code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
3
942
language
stringclasses
30 values
license
stringclasses
15 values
size
int32
3
1.05M
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Python utilities required by Keras.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import binascii import codecs import marshal import os import re import sys import time import types as python_types import numpy as np import six from tensorflow.python.util import nest from tensorflow.python.util import tf_decorator from tensorflow.python.util import tf_inspect from tensorflow.python.util.tf_export import keras_export _GLOBAL_CUSTOM_OBJECTS = {} @keras_export('keras.utils.CustomObjectScope') class CustomObjectScope(object): """Provides a scope that changes to `_GLOBAL_CUSTOM_OBJECTS` cannot escape. Code within a `with` statement will be able to access custom objects by name. Changes to global custom objects persist within the enclosing `with` statement. At end of the `with` statement, global custom objects are reverted to state at beginning of the `with` statement. Example: Consider a custom object `MyObject` (e.g. a class): ```python with CustomObjectScope({'MyObject':MyObject}): layer = Dense(..., kernel_regularizer='MyObject') # save, load, etc. will recognize custom object by name ``` """ def __init__(self, *args): self.custom_objects = args self.backup = None def __enter__(self): self.backup = _GLOBAL_CUSTOM_OBJECTS.copy() for objects in self.custom_objects: _GLOBAL_CUSTOM_OBJECTS.update(objects) return self def __exit__(self, *args, **kwargs): _GLOBAL_CUSTOM_OBJECTS.clear() _GLOBAL_CUSTOM_OBJECTS.update(self.backup) @keras_export('keras.utils.custom_object_scope') def custom_object_scope(*args): """Provides a scope that changes to `_GLOBAL_CUSTOM_OBJECTS` cannot escape. Convenience wrapper for `CustomObjectScope`. Code within a `with` statement will be able to access custom objects by name. Changes to global custom objects persist within the enclosing `with` statement. At end of the `with` statement, global custom objects are reverted to state at beginning of the `with` statement. Example: Consider a custom object `MyObject` ```python with custom_object_scope({'MyObject':MyObject}): layer = Dense(..., kernel_regularizer='MyObject') # save, load, etc. will recognize custom object by name ``` Arguments: *args: Variable length list of dictionaries of name, class pairs to add to custom objects. Returns: Object of type `CustomObjectScope`. """ return CustomObjectScope(*args) @keras_export('keras.utils.get_custom_objects') def get_custom_objects(): """Retrieves a live reference to the global dictionary of custom objects. Updating and clearing custom objects using `custom_object_scope` is preferred, but `get_custom_objects` can be used to directly access `_GLOBAL_CUSTOM_OBJECTS`. Example: ```python get_custom_objects().clear() get_custom_objects()['MyObject'] = MyObject ``` Returns: Global dictionary of names to classes (`_GLOBAL_CUSTOM_OBJECTS`). """ return _GLOBAL_CUSTOM_OBJECTS def serialize_keras_class_and_config(cls_name, cls_config): """Returns the serialization of the class with the given config.""" return {'class_name': cls_name, 'config': cls_config} @keras_export('keras.utils.serialize_keras_object') def serialize_keras_object(instance): _, instance = tf_decorator.unwrap(instance) if instance is None: return None if hasattr(instance, 'get_config'): return serialize_keras_class_and_config(instance.__class__.__name__, instance.get_config()) if hasattr(instance, '__name__'): return instance.__name__ raise ValueError('Cannot serialize', instance) def class_and_config_for_serialized_keras_object( config, module_objects=None, custom_objects=None, printable_module_name='object'): """Returns the class name and config for a serialized keras object.""" if (not isinstance(config, dict) or 'class_name' not in config or 'config' not in config): raise ValueError('Improper config format: ' + str(config)) class_name = config['class_name'] if custom_objects and class_name in custom_objects: cls = custom_objects[class_name] elif class_name in _GLOBAL_CUSTOM_OBJECTS: cls = _GLOBAL_CUSTOM_OBJECTS[class_name] else: module_objects = module_objects or {} cls = module_objects.get(class_name) if cls is None: raise ValueError('Unknown ' + printable_module_name + ': ' + class_name) return (cls, config['config']) @keras_export('keras.utils.deserialize_keras_object') def deserialize_keras_object(identifier, module_objects=None, custom_objects=None, printable_module_name='object'): if identifier is None: return None if isinstance(identifier, dict): # In this case we are dealing with a Keras config dictionary. config = identifier (cls, cls_config) = class_and_config_for_serialized_keras_object( config, module_objects, custom_objects, printable_module_name) if hasattr(cls, 'from_config'): arg_spec = tf_inspect.getfullargspec(cls.from_config) custom_objects = custom_objects or {} if 'custom_objects' in arg_spec.args: return cls.from_config( cls_config, custom_objects=dict( list(_GLOBAL_CUSTOM_OBJECTS.items()) + list(custom_objects.items()))) with CustomObjectScope(custom_objects): return cls.from_config(cls_config) else: # Then `cls` may be a function returning a class. # in this case by convention `config` holds # the kwargs of the function. custom_objects = custom_objects or {} with CustomObjectScope(custom_objects): return cls(**cls_config) elif isinstance(identifier, six.string_types): object_name = identifier if custom_objects and object_name in custom_objects: obj = custom_objects.get(object_name) elif object_name in _GLOBAL_CUSTOM_OBJECTS: obj = _GLOBAL_CUSTOM_OBJECTS[object_name] else: obj = module_objects.get(object_name) if obj is None: raise ValueError('Unknown ' + printable_module_name + ':' + object_name) # Classes passed by name are instantiated with no args, functions are # returned as-is. if tf_inspect.isclass(obj): return obj() return obj else: raise ValueError('Could not interpret serialized ' + printable_module_name + ': ' + identifier) def func_dump(func): """Serializes a user defined function. Arguments: func: the function to serialize. Returns: A tuple `(code, defaults, closure)`. """ if os.name == 'nt': raw_code = marshal.dumps(func.__code__).replace(b'\\', b'/') code = codecs.encode(raw_code, 'base64').decode('ascii') else: raw_code = marshal.dumps(func.__code__) code = codecs.encode(raw_code, 'base64').decode('ascii') defaults = func.__defaults__ if func.__closure__: closure = tuple(c.cell_contents for c in func.__closure__) else: closure = None return code, defaults, closure def func_load(code, defaults=None, closure=None, globs=None): """Deserializes a user defined function. Arguments: code: bytecode of the function. defaults: defaults of the function. closure: closure of the function. globs: dictionary of global objects. Returns: A function object. """ if isinstance(code, (tuple, list)): # unpack previous dump code, defaults, closure = code if isinstance(defaults, list): defaults = tuple(defaults) def ensure_value_to_cell(value): """Ensures that a value is converted to a python cell object. Arguments: value: Any value that needs to be casted to the cell type Returns: A value wrapped as a cell object (see function "func_load") """ def dummy_fn(): # pylint: disable=pointless-statement value # just access it so it gets captured in .__closure__ cell_value = dummy_fn.__closure__[0] if not isinstance(value, type(cell_value)): return cell_value return value if closure is not None: closure = tuple(ensure_value_to_cell(_) for _ in closure) try: raw_code = codecs.decode(code.encode('ascii'), 'base64') except (UnicodeEncodeError, binascii.Error): raw_code = code.encode('raw_unicode_escape') code = marshal.loads(raw_code) if globs is None: globs = globals() return python_types.FunctionType( code, globs, name=code.co_name, argdefs=defaults, closure=closure) def has_arg(fn, name, accept_all=False): """Checks if a callable accepts a given keyword argument. Arguments: fn: Callable to inspect. name: Check if `fn` can be called with `name` as a keyword argument. accept_all: What to return if there is no parameter called `name` but the function accepts a `**kwargs` argument. Returns: bool, whether `fn` accepts a `name` keyword argument. """ arg_spec = tf_inspect.getfullargspec(fn) if accept_all and arg_spec.varkw is not None: return True return name in arg_spec.args @keras_export('keras.utils.Progbar') class Progbar(object): """Displays a progress bar. Arguments: target: Total number of steps expected, None if unknown. width: Progress bar width on screen. verbose: Verbosity mode, 0 (silent), 1 (verbose), 2 (semi-verbose) stateful_metrics: Iterable of string names of metrics that should *not* be averaged over time. Metrics in this list will be displayed as-is. All others will be averaged by the progbar before display. interval: Minimum visual progress update interval (in seconds). unit_name: Display name for step counts (usually "step" or "sample"). """ def __init__(self, target, width=30, verbose=1, interval=0.05, stateful_metrics=None, unit_name='step'): self.target = target self.width = width self.verbose = verbose self.interval = interval self.unit_name = unit_name if stateful_metrics: self.stateful_metrics = set(stateful_metrics) else: self.stateful_metrics = set() self._dynamic_display = ((hasattr(sys.stdout, 'isatty') and sys.stdout.isatty()) or 'ipykernel' in sys.modules or 'posix' in sys.modules) self._total_width = 0 self._seen_so_far = 0 # We use a dict + list to avoid garbage collection # issues found in OrderedDict self._values = {} self._values_order = [] self._start = time.time() self._last_update = 0 def update(self, current, values=None): """Updates the progress bar. Arguments: current: Index of current step. values: List of tuples: `(name, value_for_last_step)`. If `name` is in `stateful_metrics`, `value_for_last_step` will be displayed as-is. Else, an average of the metric over time will be displayed. """ values = values or [] for k, v in values: if k not in self._values_order: self._values_order.append(k) if k not in self.stateful_metrics: if k not in self._values: self._values[k] = [v * (current - self._seen_so_far), current - self._seen_so_far] else: self._values[k][0] += v * (current - self._seen_so_far) self._values[k][1] += (current - self._seen_so_far) else: # Stateful metrics output a numeric value. This representation # means "take an average from a single value" but keeps the # numeric formatting. self._values[k] = [v, 1] self._seen_so_far = current now = time.time() info = ' - %.0fs' % (now - self._start) if self.verbose == 1: if (now - self._last_update < self.interval and self.target is not None and current < self.target): return prev_total_width = self._total_width if self._dynamic_display: sys.stdout.write('\b' * prev_total_width) sys.stdout.write('\r') else: sys.stdout.write('\n') if self.target is not None: numdigits = int(np.log10(self.target)) + 1 bar = ('%' + str(numdigits) + 'd/%d [') % (current, self.target) prog = float(current) / self.target prog_width = int(self.width * prog) if prog_width > 0: bar += ('=' * (prog_width - 1)) if current < self.target: bar += '>' else: bar += '=' bar += ('.' * (self.width - prog_width)) bar += ']' else: bar = '%7d/Unknown' % current self._total_width = len(bar) sys.stdout.write(bar) if current: time_per_unit = (now - self._start) / current else: time_per_unit = 0 if self.target is not None and current < self.target: eta = time_per_unit * (self.target - current) if eta > 3600: eta_format = '%d:%02d:%02d' % (eta // 3600, (eta % 3600) // 60, eta % 60) elif eta > 60: eta_format = '%d:%02d' % (eta // 60, eta % 60) else: eta_format = '%ds' % eta info = ' - ETA: %s' % eta_format else: if time_per_unit >= 1 or time_per_unit == 0: info += ' %.0fs/%s' % (time_per_unit, self.unit_name) elif time_per_unit >= 1e-3: info += ' %.0fms/%s' % (time_per_unit * 1e3, self.unit_name) else: info += ' %.0fus/%s' % (time_per_unit * 1e6, self.unit_name) for k in self._values_order: info += ' - %s:' % k if isinstance(self._values[k], list): avg = np.mean(self._values[k][0] / max(1, self._values[k][1])) if abs(avg) > 1e-3: info += ' %.4f' % avg else: info += ' %.4e' % avg else: info += ' %s' % self._values[k] self._total_width += len(info) if prev_total_width > self._total_width: info += (' ' * (prev_total_width - self._total_width)) if self.target is not None and current >= self.target: info += '\n' sys.stdout.write(info) sys.stdout.flush() elif self.verbose == 2: if self.target is not None and current >= self.target: numdigits = int(np.log10(self.target)) + 1 count = ('%' + str(numdigits) + 'd/%d') % (current, self.target) info = count + info for k in self._values_order: info += ' - %s:' % k avg = np.mean(self._values[k][0] / max(1, self._values[k][1])) if avg > 1e-3: info += ' %.4f' % avg else: info += ' %.4e' % avg info += '\n' sys.stdout.write(info) sys.stdout.flush() self._last_update = now def add(self, n, values=None): self.update(self._seen_so_far + n, values) def make_batches(size, batch_size): """Returns a list of batch indices (tuples of indices). Arguments: size: Integer, total size of the data to slice into batches. batch_size: Integer, batch size. Returns: A list of tuples of array indices. """ num_batches = int(np.ceil(size / float(batch_size))) return [(i * batch_size, min(size, (i + 1) * batch_size)) for i in range(0, num_batches)] def slice_arrays(arrays, start=None, stop=None): """Slice an array or list of arrays. This takes an array-like, or a list of array-likes, and outputs: - arrays[start:stop] if `arrays` is an array-like - [x[start:stop] for x in arrays] if `arrays` is a list Can also work on list/array of indices: `slice_arrays(x, indices)` Arguments: arrays: Single array or list of arrays. start: can be an integer index (start index) or a list/array of indices stop: integer (stop index); should be None if `start` was a list. Returns: A slice of the array(s). Raises: ValueError: If the value of start is a list and stop is not None. """ if arrays is None: return [None] if isinstance(start, list) and stop is not None: raise ValueError('The stop argument has to be None if the value of start ' 'is a list.') elif isinstance(arrays, list): if hasattr(start, '__len__'): # hdf5 datasets only support list objects as indices if hasattr(start, 'shape'): start = start.tolist() return [None if x is None else x[start] for x in arrays] return [ None if x is None else None if not hasattr(x, '__getitem__') else x[start:stop] for x in arrays ] else: if hasattr(start, '__len__'): if hasattr(start, 'shape'): start = start.tolist() return arrays[start] if hasattr(start, '__getitem__'): return arrays[start:stop] return [None] def to_list(x): """Normalizes a list/tensor into a list. If a tensor is passed, we return a list of size 1 containing the tensor. Arguments: x: target object to be normalized. Returns: A list. """ if isinstance(x, list): return x return [x] def object_list_uid(object_list): """Creates a single string from object ids.""" object_list = nest.flatten(object_list) return ', '.join([str(abs(id(x))) for x in object_list]) def to_snake_case(name): intermediate = re.sub('(.)([A-Z][a-z0-9]+)', r'\1_\2', name) insecure = re.sub('([a-z])([A-Z])', r'\1_\2', intermediate).lower() # If the class is private the name starts with "_" which is not secure # for creating scopes. We prefix the name with "private" in this case. if insecure[0] != '_': return insecure return 'private' + insecure def is_all_none(structure): iterable = nest.flatten(structure) # We cannot use Python's `any` because the iterable may return Tensors. for element in iterable: if element is not None: return False return True def check_for_unexpected_keys(name, input_dict, expected_values): unknown = set(input_dict.keys()).difference(expected_values) if unknown: raise ValueError('Unknown entries in {} dictionary: {}. Only expected ' 'following keys: {}'.format(name, list(unknown), expected_values)) def validate_kwargs(kwargs, allowed_kwargs, error_message='Keyword argument not understood:'): """Checks that all keyword arguments are in the set of allowed keys.""" for kwarg in kwargs: if kwarg not in allowed_kwargs: raise TypeError(error_message, kwarg)
alsrgv/tensorflow
tensorflow/python/keras/utils/generic_utils.py
Python
apache-2.0
19,553
const $ = require('jquery'); const { BagItProfile } = require('../../bagit/bagit_profile'); const { Job } = require('../../core/job'); const { JobRunController } = require('./job_run_controller'); const { PackageOperation } = require('../../core/package_operation'); const path = require('path'); const { StorageService } = require('../../core/storage_service'); const { TestUtil } = require('../../core/test_util'); const { UITestUtil } = require('../common/ui_test_util'); const { UploadOperation } = require('../../core/upload_operation'); const { Util } = require('../../core/util'); beforeEach(() => { TestUtil.deleteJsonFile('Job'); TestUtil.deleteJsonFile('StorageService'); }); afterAll(() => { TestUtil.deleteJsonFile('Job'); TestUtil.deleteJsonFile('StorageService'); }); function getStorageService(name, proto, host) { let ss = new StorageService({ name: name, protocol: proto, host: host }); ss.save(); return ss; } function getUploadOp(name, proto, host) { let ss = getStorageService(name, proto, host); let op = new UploadOperation(); op.sourceFiles = ['/dev/null']; op.storageServiceId = ss.id; return op; } function getJob() { var job = new Job(); job.packageOp = new PackageOperation('TestBag', '/dev/null'); job.packageOp.packageFormat = 'BagIt'; job.packageOp._trimLeadingPaths = false; job.packageOp.sourceFiles = [ __dirname, path.join(__dirname, '..', 'forms') ]; job.dirCount = 2; job.fileCount = 12; job.byteCount = 237174; job.uploadOps = [ getUploadOp('target1', 's3', 'target1.com'), getUploadOp('target2', 's3', 'target2.com') ]; job.bagItProfile = BagItProfile.load(path.join(__dirname, '..', '..', 'test', 'profiles', 'multi_manifest.json')); job.save(); return job; } function getController() { let job = getJob(); let params = new URLSearchParams({ id: job.id }); return new JobRunController(params); } test('constructor', () => { let controller = getController(); expect(controller.model).toEqual(Job); expect(controller.job).not.toBeNull(); }); test('show', () => { let controller = getController(); let response = controller.show() expect(response.container).toMatch(controller.job.packageOp.packageName); expect(response.container).toMatch(controller.job.packageOp.outputPath); expect(response.container).toMatch(controller.job.bagItProfile.name); expect(response.container).toMatch(controller.job.bagItProfile.description); expect(response.container).toMatch('2 Directories'); expect(response.container).toMatch('12 Files'); expect(response.container).toMatch('231.62 KB'); expect(response.container).toMatch(controller.job.packageOp.sourceFiles[0]); expect(response.container).toMatch(controller.job.packageOp.sourceFiles[1]); });
APTrust/easy-store
ui/controllers/job_run_controller.test.js
JavaScript
apache-2.0
2,913
package io.github.dantesun.petclinic.data.velocity; import org.apache.ibatis.executor.parameter.ParameterHandler; import org.apache.ibatis.mapping.BoundSql; import org.apache.ibatis.mapping.MappedStatement; import org.apache.ibatis.mapping.SqlSource; import org.apache.ibatis.parsing.XNode; import org.apache.ibatis.scripting.LanguageDriver; import org.apache.ibatis.session.Configuration; import org.apache.ibatis.type.Alias; import org.mybatis.scripting.velocity.Driver; /** * Created by dsun on 15/2/22. */ @Alias("velocity") public class VelocityDriver implements LanguageDriver { private Driver driverImpl = new Driver(); @Override public ParameterHandler createParameterHandler(MappedStatement mappedStatement, Object parameterObject, BoundSql boundSql) { return driverImpl.createParameterHandler(mappedStatement, parameterObject, boundSql); } @Override public SqlSource createSqlSource(Configuration configuration, XNode script, Class<?> parameterType) { return createSqlSource(configuration, script.getNode().getTextContent(), parameterType); } @Override public SqlSource createSqlSource(Configuration configuration, String script, Class<?> parameterType) { if (parameterType == null) { parameterType = Object.class; } return new VelocitySqlSource(configuration, script, parameterType); } }
dantesun/webapp-boilerplate
core-models/src/main/java/io/github/dantesun/petclinic/data/velocity/VelocityDriver.java
Java
apache-2.0
1,398
# Pseudonocardia halophobica (Akimov et al., 1989) McVeigh et al., 1994 SPECIES #### Status ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Bacteria/Actinobacteria/Actinobacteria/Actinomycetales/Pseudonocardiaceae/Pseudonocardia/Pseudonocardia halophobica/README.md
Markdown
apache-2.0
227
package core.utils; import java.util.ArrayList; import java.util.List; public class Page<T> { public static final int PAGE_SIZE = 10; protected List<T> listObjects = new ArrayList<>(); protected int currentPage; protected int pageSize = PAGE_SIZE; /** * Constructor. * @param list contains the ArrayList to copy * @param page correspond to the currentPage */ public Page(List<T> list, int page) { for (int i = 0; i < list.size(); i++) { this.listObjects.add(list.get(i)); } this.currentPage = page; } /** * Constructor. * @param list contains the ArrayList to copy * @param page correspond to the currentPage * @param pageSize the page size */ public Page(List<T> list, int page, int pageSize) { for (int i = 0; i < list.size(); i++) { this.listObjects.add(list.get(i)); } this.currentPage = page; this.pageSize = pageSize; } /** * Get the ArrayList containing a T page. * @return the ArrayList containing a T page */ public List<T> getListPage() { return listObjects; } /** * Get the next page. * @return next page */ public int getNextPage() { return currentPage + 1; } /** * Get previous page. * @return previous page if currentPage > 0 else 0 */ public int getPreviousPage() { if (currentPage > 0) { return currentPage - 1; } else { return 0; } } /** * Get the current page. * @return the current page */ public int getCurrentPage() { return currentPage; } /** * Get the page size. * @return the page size */ public int getPageSize() { return pageSize; } /** * Test if the ArrayList<T> is empty. * @return True if Empty, else false */ public boolean isEmpty() { return listObjects.isEmpty(); } /** * Returns a string representation of the object. * @return a string representation of the object. */ @Override public String toString() { return this.getClass() + " [listObjects = " + listObjects + "]"; } /** * Equals Methode. * @param o other object * @return true if equals, else false */ @Override public boolean equals(Object o) { Page<T> page = (Page<T>) o; if (page.getPageSize() != this.pageSize || page.getCurrentPage() != this.currentPage) { return false; } boolean equals = true; int i = 0; while (i < this.pageSize && equals) { equals = page.getListPage().get(i).equals(this.listObjects.get(i)); i++; } return equals; } /** * Hash Code. * @return hash code */ @Override public int hashCode() { int result = listObjects != null ? listObjects.hashCode() : 0; result = 31 * result + currentPage; result = 31 * result + pageSize; return result; } /** * Add a Object in the ArrayList. * @param t the object */ public void add(T t) { listObjects.add(t); } }
gdanguy/training-java-gdanguy
core/src/main/java/core/utils/Page.java
Java
apache-2.0
3,276
<?php /** * DO NOT EDIT THIS FILE! * * This file was automatically generated from external sources. * * Any manual change here will be lost the next time the SDK * is updated. You've been warned! */ namespace DTS\eBaySDK\Test\PostOrder\Types; use DTS\eBaySDK\PostOrder\Types\ReturnShippingCostDetailType; class ReturnShippingCostDetailTypeTest extends \PHPUnit_Framework_TestCase { private $obj; protected function setUp() { $this->obj = new ReturnShippingCostDetailType(); } public function testCanBeCreated() { $this->assertInstanceOf('\DTS\eBaySDK\PostOrder\Types\ReturnShippingCostDetailType', $this->obj); } public function testExtendsBaseType() { $this->assertInstanceOf('\DTS\eBaySDK\Types\BaseType', $this->obj); } }
davidtsadler/ebay-sdk-php
test/PostOrder/Types/ReturnShippingCostDetailTypeTest.php
PHP
apache-2.0
802
/** * @license Apache-2.0 * * Copyright (c) 2020 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // MODULES // var isPositiveInteger = require( '@stdlib/math/base/assert/is-positive-integer' ); var constantFunction = require( '@stdlib/utils/constant-function' ); var isfinite = require( '@stdlib/math/base/assert/is-finite' ); var round = require( '@stdlib/math/base/special/round' ); var isnan = require( '@stdlib/math/base/assert/is-nan' ); var exp = require( '@stdlib/math/base/special/exp' ); var LN2 = require( '@stdlib/constants/float64/ln-two' ); var weights = require( './weights.js' ); // MAIN // /** * Returns a function for evaluating the cumulative distribution function (CDF) for the distribution of the Wilcoxon signed rank test statistic with `n` observations. * * @param {PositiveInteger} n - number of observations * @returns {Function} CDF * * @example * var cdf = factory( 8 ); * var y = cdf( 3.9 ); * // returns ~0.027 * * y = cdf( 17.0 ); * // returns ~0.473 */ function factory( n ) { var mlim; var pui; if ( !isPositiveInteger( n ) || !isfinite( n ) ) { return constantFunction( NaN ); } pui = exp( -n * LN2 ); mlim = n * ( n + 1 ) / 2; return cdf; /** * Evaluates the cumulative distribution function (CDF) for the distribution of the Wilcoxon signed rank test statistic. * * @private * @param {number} x - input value * @returns {Probability} evaluated CDF * * @example * var y = cdf( 2 ); * // returns <number> */ function cdf( x ) { var i; var p; if ( isnan( x ) ) { return NaN; } if ( x < 0.0 ) { return 0.0; } x = round( x ); if ( x >= mlim ) { return 1.0; } p = 0; for ( i = 0; i <= x; i++ ) { p += weights( i, n ) * pui; } return p; } } // EXPORTS // module.exports = factory;
stdlib-js/stdlib
lib/node_modules/@stdlib/stats/base/dists/signrank/cdf/lib/factory.js
JavaScript
apache-2.0
2,313
/* * Copyright (C) 2015 The Gravitee team (http://gravitee.io) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import {Component, OnInit} from '@angular/core'; import {SnackbarService} from "../../../services/snackbar.service"; import {ActivatedRoute, Router} from "@angular/router"; import {AppConfig} from "../../../../config/app.config"; import {DomainService} from "../../../services/domain.service"; import {AuthService} from "../../../services/auth.service"; @Component({ selector: 'app-scim', templateUrl: './scim.component.html', styleUrls: ['./scim.component.scss'] }) export class ScimComponent implements OnInit { domainId: string; domain: any = {}; formChanged = false; editMode: boolean; constructor(private domainService: DomainService, private snackbarService: SnackbarService, private authService: AuthService, private route: ActivatedRoute, private router: Router) { } ngOnInit() { this.domain = this.route.snapshot.data['domain']; this.domainId = this.domain.id; this.editMode = this.authService.hasPermissions(['domain_scim_update']); } save() { this.domainService.patchScimSettings(this.domainId, this.domain).subscribe(data => { this.domain = data; this.formChanged = false; this.snackbarService.open('SCIM configuration updated'); }); } enableSCIM(event) { this.domain.scim = { 'enabled': (event.checked) }; this.formChanged = true; } isSCIMEnabled() { return this.domain.scim && this.domain.scim.enabled; } }
gravitee-io/graviteeio-access-management
gravitee-am-ui/src/app/domain/settings/scim/scim.component.ts
TypeScript
apache-2.0
2,097
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="description" content=""> <meta name="author" content=""> <title>Software Testing</title> <link rel="stylesheet" type="text/css" href="style.css" /> <script type="text/javascript" src="cookies.js"></script> <!-- Bootstrap Core CSS --> <link href="css/bootstrap.min.css" rel="stylesheet"> <!-- Custom CSS --> <link href="css/small-business.css" rel="stylesheet"> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script> <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <!-- Navigation --> <nav class="navbar navbar-inverse navbar-fixed-top" role="navigation"> <div class="container"> <!-- Brand and toggle get grouped for better mobile display --> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="#"> <img src="http://techspot.ccsf.edu/images/yuba.png" width="170" height="90" alt=""> </a> </div> <!-- Collect the nav links, forms, and other content for toggling --> <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1"> <ul class="nav navbar-nav"> <li> <a href="cookies.html">Log In</a> </li> <li> <a href="page1.html">Home</a> </li> <li> <a href="opp.html">Opportunity</a> </li> <li> <a href="ld.html">L&D</a> </li> <li> <a href="topics.html">Topics</a> </li> </ul> <span class="eggs"><script>readCookie('myCookie')</script></span> </div> <!-- /.navbar-collapse --> </div> <!-- /.container --> </nav> <!-- Page Content --> <div class="container"> <!-- Heading Row --> <div class="row"> <div class="col-md-8"> <img class="img-responsive img-rounded" src="http://www.clevertech.biz/img/service-header/software-testing.jpg" alt=""> </div> <!-- /.col-md-8 --> <div class="col-md-4"> <h1>In The News</h1> <p style="color: black"> <strong>US prisoners released early by software bug</strong> </p> <p style="color: black">The bug miscalculated the sentence reductions prisoners in Washington state had received for good behaviour.It was introduced in 2002 as part of an update that followed a court ruling about applying good behaviour credits.State officials said that many early-release prisoners would have to return to jail to finish their sentences.</p> <a class="btn btn-primary btn-lg" href="http://www.bbc.com/news/technology-35167191">Read more</a> </div> <!-- /.col-md-4 --> </div> <!-- /.row --> <hr> <!-- Call to Action Well --> <div class="row"> <div class="col-lg-12"> <div class="well text-center"> <a href="https://www.facebook.com/YearUpBayArea/" target="_blank"><img src="http://www.niftybuttons.com/scribble/facebook.png" border="0" margin="1px"></a><a href="https://www.linkedin.com/company/year-up" target="_blank"><img src="http://www.niftybuttons.com/scribble/linkedin.png" border="0" margin="1px"></a><a href="https://www.youtube.com/user/SFYearUp" target="_blank"><img src="http://www.niftybuttons.com/scribble/youtube.png" border="0" margin="1px"> <a href="https://twitter.com/yearupbayarea?lang=en" target="_blank"><img src="http://www.niftybuttons.com/scribble/twitter.png" border="0" margin="1px"></a> </a> </div> </div> <!-- /.col-lg-12 --> </div> <!-- /.row --> <!-- Content Row --> <div class="row"> <div class="col-md-4"> <h2>Overview</h2> <p style="color: black">One of the very first things you will cover in QA are the different kinds of bus there are. There are a total of 5 you will need to remember. Software Development Life Cycle (SDLC), being the different stages a product goes threw before its releas date. How to properly log any bugs you find within a spec. Following the different methods testers use, which are constantly changing. One of the industry standards used today is Agile Testing. One other thing you will cover is White and Black Box Testing. In addition you will also cover White Box Dynamic and Static Testing; Black Box Dynamic and Static Testing. You will learn about Test-to-fail and Test-to-pass. One of the last of few things you will learn in QA is VCS (Version Control Systems), which can be very helpful while testing or creating a product. </p> <a class="btn btn-default" href="http://softwaretestingfundamentals.com/software-testing-methods/">More Info</a> </div> <!-- /.col-md-4 --> <div class="col-md-4"> <h2>Software Tools</h2> <p style="color:black">If you're intrested in learning a bit more about QA but don't know where to start, ther will be a link to a very insightful book at the end of this page. It is what we used in our QA class and it will give you an overview of QA and software testing. One out of two of the major things you will need to know is logging a specification bug. A basic templet should have your name, the date, the products name, the version number, and 3 pieces of information. Such as the type of bug you found, a potential bug, why you think it's a bug, and your suggested solution to fixing this bug. In addition you will have to know the 5 bugs that exist to actually identify them. The second thing will be Equivelence Partitioning. Equivalence partitioning (also called Equivalence Class Partitioning or ECP) is a software testing technique that divides the input data of a software unit into partitions of equivalent data from which test cases can be derived. In principle, test cases are designed to cover each partition at least once. </p> <a href="myfile.pdf"><img src="https://p.gr-assets.com/max_square/fill/books/1348774033/1543131.jpg" width="400" height="387"></a> </div> <!-- /.col-md-4 --> <!-- /.col-md-4 --> </div> <!-- /.row --> <!-- Footer --> <footer> <div class="row"> <div class="col-lg-12"> <center> <p style="color:black">Copyright &copy; YUBA 2016&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <a href="page1.html">Home&nbsp;&nbsp;</a> <a href="opp.html">Opportunities&nbsp;&nbsp;</a> <a href="ld.html">L+D&nbsp;&nbsp;</a> <a href="topics.html">Topics&nbsp;&nbsp;</a> <a href="http://www.yearup.org/future-students/?location=bay-area/">Apply Today</a> </p> </center> </div> </div> </footer> </div> <!-- /.container --> <!-- jQuery --> <script src="js/jquery.js"></script> <!-- Bootstrap Core JavaScript --> <script src="js/bootstrap.min.js"></script> </body> </html>
dannalaynas/QA-WebSite
Topics.html
HTML
apache-2.0
7,678
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.ignite.ml.preprocessing.imputer; import org.apache.ignite.ml.math.functions.IgniteBiFunction; /** * Preprocessing function that makes imputing. * * @param <K> Type of a key in {@code upstream} data. * @param <V> Type of a value in {@code upstream} data. */ public class ImputerPreprocessor<K, V> implements IgniteBiFunction<K, V, double[]> { /** */ private static final long serialVersionUID = 6887800576392623469L; /** Filling values. */ private final double[] imputingValues; /** Base preprocessor. */ private final IgniteBiFunction<K, V, double[]> basePreprocessor; /** * Constructs a new instance of imputing preprocessor. * * @param basePreprocessor Base preprocessor. */ public ImputerPreprocessor(double[] imputingValues, IgniteBiFunction<K, V, double[]> basePreprocessor) { this.imputingValues = imputingValues; this.basePreprocessor = basePreprocessor; } /** * Applies this preprocessor. * * @param k Key. * @param v Value. * @return Preprocessed row. */ @Override public double[] apply(K k, V v) { double[] res = basePreprocessor.apply(k, v); assert res.length == imputingValues.length; for (int i = 0; i < res.length; i++) { if (Double.valueOf(res[i]).equals(Double.NaN)) res[i] = imputingValues[i]; } return res; } }
voipp/ignite
modules/ml/src/main/java/org/apache/ignite/ml/preprocessing/imputer/ImputerPreprocessor.java
Java
apache-2.0
2,255
/* © 2017 Altavant Technologies Inc. Web: http://www.altavant.com */ namespace Altavant.Fusion.Graphics { using System; using Fusion.Utils; public enum MatrixOrder : byte { Append, Prepend } public class Matrix { private float _m11; private float _m12; private float _m21; private float _m22; private float _offsetX; private float _offsetY; private float[] _values; public Matrix() : this(1F, 0F, 0F, 1F, 0F, 0F) { } public Matrix(float m11, float m12, float m21, float m22, float offsetX, float offsetY) { _m11 = m11; _m12 = m12; _m21 = m21; _m22 = m22; _offsetX = offsetX; _offsetY = offsetY; } public Matrix(Android.Graphics.Matrix matrix) { float[] values = new float[9]; matrix.GetValues(values); _m11 = values[Android.Graphics.Matrix.MscaleX]; _m21 = values[Android.Graphics.Matrix.MskewX]; _offsetX = values[Android.Graphics.Matrix.MtransX]; _m12 = values[Android.Graphics.Matrix.MskewY]; _m22 = values[Android.Graphics.Matrix.MscaleY]; _offsetY = values[Android.Graphics.Matrix.MtransY]; } public float M11 { get { return _m11; } set { _m11 = value; } } public float M12 { get { return _m12; } set { _m12 = value; } } public float M21 { get { return _m21; } set { _m21 = value; } } public float M22 { get { return _m22; } set { _m22 = value; } } public float OffsetX { get { return _offsetX; } set { _offsetX = value; } } public float OffsetY { get { return _offsetY; } set { _offsetY = value; } } public static Matrix Identity { get { return new Matrix(1F, 0F, 0F, 1F, 0F, 0F); } } public bool IsIdentity { get { if ((_m11 == 1F) && (_m12 == 0F) && (_m21 == 0F) && (_m22 == 1F) && (_offsetX == 0F) && (_offsetY == 0F)) return true; return false; } } public void SetValues(float m11, float m12, float m21, float m22, float offsetX, float offsetY) { _m11 = m11; _m12 = m12; _m21 = m21; _m22 = m22; _offsetX = offsetX; _offsetY = offsetY; } public void Reset() { _m11 = 1F; _m12 = 0F; _m21 = 0F; _m22 = 1F; _offsetX = 0F; _offsetY = 0F; } public void Multiply(Matrix matrix) { Multiply(matrix, MatrixOrder.Prepend); } public void Multiply(Matrix matrix, MatrixOrder order) { if (matrix == null) throw new ArgumentNullException(nameof(matrix)); float a11, a12, a21, a22, aX, aY; float b11, b12, b21, b22, bX, bY; if (order == MatrixOrder.Append) { a11 = _m11; a12 = _m12; a21 = _m21; a22 = _m22; aX = _offsetX; aY = _offsetY; b11 = matrix.M11; b12 = matrix.M12; b21 = matrix.M21; b22 = matrix.M22; bX = matrix.OffsetX; bY = matrix.OffsetY; } else { a11 = matrix.M11; a12 = matrix.M12; a21 = matrix.M21; a22 = matrix.M22; aX = matrix.OffsetX; aY = matrix.OffsetY; b11 = _m11; b12 = _m12; b21 = _m21; b22 = _m22; bX = _offsetX; bY = _offsetY; } _m11 = a11 * b11 + a12 * b21; _m12 = a11 * b12 + a12 * b22; _m21 = a21 * b11 + a22 * b21; _m22 = a21 * b12 + a22 * b22; _offsetX = aX * b11 + aY * b21 + bX; _offsetY = aX * b12 + aY * b22 + bY; } public void Translate(float offsetX, float offsetY) { Translate(offsetX, offsetY, MatrixOrder.Prepend); } public void Translate(float offsetX, float offsetY, MatrixOrder order) { Matrix matrix = Translation(offsetX, offsetY); Multiply(matrix, order); } public void Rotate(float angle) { Rotate(angle, MatrixOrder.Prepend); } public void Rotate(float angle, MatrixOrder order) { Matrix matrix = Rotation(angle); Multiply(matrix, order); } public void RotateAt(float angle, Point center) { RotateAt(angle, center.X, center.Y, MatrixOrder.Prepend); } public void RotateAt(float angle, float centerX, float centerY) { RotateAt(angle, centerX, centerY, MatrixOrder.Prepend); } public void RotateAt(float angle, Point center, MatrixOrder order) { if (center == null) throw new ArgumentNullException(nameof(center)); RotateAt(angle, center.X, center.Y, order); } public void RotateAt(float angle, float centerX, float centerY, MatrixOrder order) { Matrix matrix = RotationAt(angle, centerX, centerY); Multiply(matrix, order); } public void Scale(float scaleX, float scaleY) { Scale(scaleX, scaleY, MatrixOrder.Prepend); } public void Scale(float scaleX, float scaleY, MatrixOrder order) { Matrix matrix = Scaling(scaleX, scaleY); Multiply(matrix, order); } public void ScaleAt(float scaleX, float scaleY, Point center) { ScaleAt(scaleX, scaleY, center.X, center.Y, MatrixOrder.Prepend); } public void ScaleAt(float scaleX, float scaleY, float centerX, float centerY) { ScaleAt(scaleX, scaleY, centerX, centerY, MatrixOrder.Prepend); } public void ScaleAt(float scaleX, float scaleY, Point center, MatrixOrder order) { if (center == null) throw new ArgumentNullException(nameof(center)); ScaleAt(scaleX, scaleY, center.X, center.Y, order); } public void ScaleAt(float scaleX, float scaleY, float centerX, float centerY, MatrixOrder order) { Matrix matrix = ScalingAt(scaleX, scaleY, centerX, centerY); Multiply(matrix, order); } public void Shear(float shearX, float shearY) { Shear(shearX, shearY, MatrixOrder.Prepend); } public void Shear(float shearX, float shearY, MatrixOrder order) { Matrix matrix = Shearing(shearX, shearY); Multiply(matrix, order); } public void ShearAt(float shearX, float shearY, Point center) { ShearAt(shearX, shearY, center.X, center.Y, MatrixOrder.Prepend); } public void ShearAt(float shearX, float shearY, float centerX, float centerY) { ShearAt(shearX, shearY, centerX, centerY, MatrixOrder.Prepend); } public void ShearAt(float shearX, float shearY, Point center, MatrixOrder order) { if (center == null) throw new ArgumentNullException(nameof(center)); ShearAt(shearX, shearY, center.X, center.Y, order); } public void ShearAt(float shearX, float shearY, float centerX, float centerY, MatrixOrder order) { Matrix matrix = ShearingAt(shearX, shearY, centerX, centerY); Multiply(matrix, order); } public void Skew(float skewX, float skewY) { Skew(skewX, skewY, MatrixOrder.Prepend); } public void Skew(float skewX, float skewY, MatrixOrder order) { Matrix matrix = Skewing(skewX, skewY); Multiply(matrix, order); } public void SkewAt(float skewX, float skewY, Point center) { SkewAt(skewX, skewY, center.X, center.Y, MatrixOrder.Prepend); } public void SkewAt(float skewX, float skewY, float centerX, float centerY) { SkewAt(skewX, skewY, centerX, centerY, MatrixOrder.Prepend); } public void SkewAt(float skewX, float skewY, Point center, MatrixOrder order) { if (center == null) throw new ArgumentNullException(nameof(center)); SkewAt(skewX, skewY, center.X, center.Y, order); } public void SkewAt(float skewX, float skewY, float centerX, float centerY, MatrixOrder order) { Matrix matrix = SkewingAt(skewX, skewY, centerX, centerY); Multiply(matrix, order); } public Point TransformPoint(Point pt) { return TransformPoint(pt.X, pt.Y); } public Point TransformPoint(float x, float y) { float x1 = x * _m11 + y * _m21 + _offsetX; float y1 = x * _m12 + y * _m22 + _offsetY; return new Point(x1, y1); } public Matrix Clone() { return new Matrix(_m11, _m12, _m21, _m22, _offsetX, _offsetY); } public override int GetHashCode() { return _m11.GetHashCode() ^ _m12.GetHashCode() ^ _m21.GetHashCode() ^ _m22.GetHashCode() ^ _offsetX.GetHashCode() ^ _offsetY.GetHashCode(); } public override bool Equals(object obj) { if (obj == null) return false; if (obj == this) return true; if (obj is Matrix) { Matrix matrix = (Matrix)obj; if ((_m11 == matrix.M11) && (_m12 == matrix.M12) && (_m21 == matrix.M21) && (_m22 == matrix.M22) && (_offsetX == matrix.OffsetX) && (_offsetY == matrix.OffsetY)) return true; } return false; } public override string ToString() { CharBuffer cb = new CharBuffer(); cb.Add(Converter.ToString(_m11, 3)); cb.Add(", "); cb.Add(Converter.ToString(_m12, 3)); cb.Add(", "); cb.Add(Converter.ToString(_m21, 3)); cb.Add(", "); cb.Add(Converter.ToString(_m22, 3)); cb.Add(", "); cb.Add(Converter.ToString(_offsetX, 3)); cb.Add(", "); cb.Add(Converter.ToString(_offsetY, 3)); return cb.ToString(); } public static Matrix Parse(string s) { if (string.IsNullOrEmpty(s)) throw new ArgumentException(nameof(s)); string[] vals = Utils.Split(s); float m11 = Convert.ToSingle(vals[0], Converter.NumberFormatInfo); float m12 = Convert.ToSingle(vals[1], Converter.NumberFormatInfo); float m21 = Convert.ToSingle(vals[2], Converter.NumberFormatInfo); float m22 = Convert.ToSingle(vals[3], Converter.NumberFormatInfo); float offsetX = Convert.ToSingle(vals[4], Converter.NumberFormatInfo); float offsetY = Convert.ToSingle(vals[5], Converter.NumberFormatInfo); return new Matrix(m11, m12, m21, m22, offsetX, offsetY); } public static Matrix Translation(Point offset) { return new Matrix(1F, 0F, 0F, 1F, offset.X, offset.Y); } public static Matrix Translation(float offsetX, float offsetY) { return new Matrix(1F, 0F, 0F, 1F, offsetX, offsetY); } public static Matrix Rotation(float angle) { double radianAngle = angle * Math.PI / 180F; float cosAngle = (float)Math.Cos(radianAngle); float sinAngle = (float)Math.Sin(radianAngle); return new Matrix(cosAngle, sinAngle, -sinAngle, cosAngle, 0F, 0F); } public static Matrix RotationAt(float angle, Point center) { return RotationAt(angle, center.X, center.Y); } public static Matrix RotationAt(float angle, float centerX, float centerY) { double radianAngle = angle * Math.PI / 180F; float cosAngle = (float)Math.Cos(radianAngle); float sinAngle = (float)Math.Sin(radianAngle); Matrix m1 = new Matrix(1F, 0F, 0F, 1F, -centerX, -centerY); Matrix m2 = new Matrix(cosAngle, sinAngle, -sinAngle, cosAngle, 0F, 0F); Matrix m3 = new Matrix(1F, 0F, 0F, 1F, centerX, centerY); m1.Multiply(m2, MatrixOrder.Append); m1.Multiply(m3, MatrixOrder.Append); return m1; } public static Matrix Scaling(float scale) { return Scaling(scale, scale); } public static Matrix Scaling(float scaleX, float scaleY) { return new Matrix(scaleX, 0F, 0F, scaleY, 0F, 0F); } public static Matrix ScalingAt(float scale, Point center) { return ScalingAt(scale, scale, center.X, center.Y); } public static Matrix ScalingAt(float scaleX, float scaleY, Point center) { return ScalingAt(scaleX, scaleY, center.X, center.Y); } public static Matrix ScalingAt(float scale, float centerX, float centerY) { return ScalingAt(scale, scale, centerX, centerY); } public static Matrix ScalingAt(float scaleX, float scaleY, float centerX, float centerY) { Matrix m1 = new Matrix(1F, 0F, 0F, 1F, -centerX, -centerY); Matrix m2 = new Matrix(scaleX, 0F, 0F, scaleY, 0F, 0F); Matrix m3 = new Matrix(1F, 0F, 0F, 1F, centerX, centerY); m1.Multiply(m2, MatrixOrder.Append); m1.Multiply(m3, MatrixOrder.Append); return m1; } public static Matrix Shearing(float shearX, float shearY) { return new Matrix(1F, shearY, shearX, 1F, 0F, 0F); } public static Matrix ShearingAt(float shearX, float shearY, Point center) { return ShearingAt(shearX, shearY, center.X, center.Y); } public static Matrix ShearingAt(float shearX, float shearY, float centerX, float centerY) { Matrix m1 = new Matrix(1F, 0F, 0F, 1F, -centerX, -centerY); Matrix m2 = new Matrix(1F, shearY, shearX, 1F, 0F, 0F); Matrix m3 = new Matrix(1F, 0F, 0F, 1F, centerX, centerY); m1.Multiply(m2, MatrixOrder.Append); m1.Multiply(m3, MatrixOrder.Append); return m1; } public static Matrix Skewing(float skewX, float skewY) { double angleAlpha = skewX * Math.PI / 180F; double angleBeta = skewY * Math.PI / 180F; float tanAlpha = (float)Math.Tan(angleAlpha); float tanBeta = (float)Math.Tan(angleBeta); return new Matrix(1F, tanBeta, tanAlpha, 1F, 0F, 0F); } public static Matrix SkewingAt(float skewX, float skewY, Point center) { return SkewingAt(skewX, skewY, center.X, center.Y); } public static Matrix SkewingAt(float skewX, float skewY, float centerX, float centerY) { double angleAlpha = skewX * Math.PI / 180F; double angleBeta = skewY * Math.PI / 180F; float tanAlpha = (float)Math.Tan(angleAlpha); float tanBeta = (float)Math.Tan(angleBeta); Matrix m1 = new Matrix(1F, 0F, 0F, 1F, -centerX, -centerY); Matrix m2 = new Matrix(1F, tanBeta, tanAlpha, 1F, 0F, 0F); Matrix m3 = new Matrix(1F, 0F, 0F, 1F, centerX, centerY); m1.Multiply(m2, MatrixOrder.Append); m1.Multiply(m3, MatrixOrder.Append); return m1; } public Android.Graphics.Matrix ToNative() { Android.Graphics.Matrix m = new Android.Graphics.Matrix(); ToNative(m); return m; } public void ToNative(Android.Graphics.Matrix m) { if (_values == null) _values = new float[9]; _values[Android.Graphics.Matrix.MscaleX] = _m11; _values[Android.Graphics.Matrix.MskewX] = _m21; _values[Android.Graphics.Matrix.MtransX] = _offsetX; _values[Android.Graphics.Matrix.MskewY] = _m12; _values[Android.Graphics.Matrix.MscaleY] = _m22; _values[Android.Graphics.Matrix.MtransY] = _offsetY; _values[Android.Graphics.Matrix.Mpersp2] = 1F; m.SetValues(_values); } } }
altavant/Fusion
Android/Source/Graphics/Matrix.cs
C#
apache-2.0
14,618
/* * Copyright (c) 2008-2013, Hazelcast, Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hazelcast.core; import junit.framework.TestCase; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; @RunWith(com.hazelcast.util.RandomBlockJUnit4ClassRunner.class) public class IMapAsyncTest { private final String key = "key"; private final String value1 = "value1"; private final String value2 = "value2"; @BeforeClass @AfterClass public static void init() throws Exception { Hazelcast.shutdownAll(); } @Test public void testGetAsync() throws Exception { IMap<String, String> map = Hazelcast.getMap("map:test:getAsync"); map.put(key, value1); Future<String> f1 = map.getAsync(key); TestCase.assertEquals(value1, f1.get()); } @Test public void testPutAsync() throws Exception { IMap<String, String> map = Hazelcast.getMap("map:test:putAsync"); Future<String> f1 = map.putAsync(key, value1); String f1Val = f1.get(); TestCase.assertNull(f1Val); Future<String> f2 = map.putAsync(key, value2); String f2Val = f2.get(); TestCase.assertEquals(value1, f2Val); } @Test public void testRemoveAsync() throws Exception { IMap<String, String> map = Hazelcast.getMap("map:test:removeAsync"); // populate map map.put(key, value1); Future<String> f1 = map.removeAsync(key); TestCase.assertEquals(value1, f1.get()); } @Test public void testRemoveAsyncWithImmediateTimeout() throws Exception { final IMap<String, String> map = Hazelcast.getMap("map:test:removeAsync:timeout"); // populate map map.put(key, value1); final CountDownLatch latch = new CountDownLatch(1); new Thread(new Runnable() { public void run() { map.lock(key); latch.countDown(); } }).start(); assertTrue(latch.await(20, TimeUnit.SECONDS)); Future<String> f1 = map.removeAsync(key); try { assertEquals(value1, f1.get(0L, TimeUnit.SECONDS)); } catch (TimeoutException e) { // expected return; } TestCase.fail("Failed to throw TimeoutException with zero timeout"); } @Test public void testRemoveAsyncWithNonExistantKey() throws Exception { IMap<String, String> map = Hazelcast.getMap("map:test:removeAsync:nonexistant"); Future<String> f1 = map.removeAsync(key); TestCase.assertNull(f1.get()); } }
health-and-care-developer-network/health-and-care-developer-network
library/hazelcast/2.5/hazelcast-2.5-source/hazelcast/src/test/java/com/hazelcast/core/IMapAsyncTest.java
Java
apache-2.0
3,450
/* * Licensed to ElasticSearch and Shay Banon under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. ElasticSearch licenses this * file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.index.query; import org.elasticsearch.common.xcontent.XContentBuilder; import java.io.IOException; /** * */ public class SpanFirstQueryBuilder extends BaseQueryBuilder implements SpanQueryBuilder, BoostableQueryBuilder<SpanFirstQueryBuilder> { public static final String NAME = "span_first"; private final SpanQueryBuilder matchBuilder; private final int end; private float boost = -1; public SpanFirstQueryBuilder(SpanQueryBuilder matchBuilder, int end) { this.matchBuilder = matchBuilder; this.end = end; } public SpanFirstQueryBuilder boost(float boost) { this.boost = boost; return this; } @Override protected void doXContent(XContentBuilder builder, Params params) throws IOException { builder.startObject(NAME); builder.field("match"); matchBuilder.toXContent(builder, params); builder.field("end", end); if (boost != -1) { builder.field("boost", boost); } builder.endObject(); } }
jprante/elasticsearch-client
elasticsearch-client-search/src/main/java/org/elasticsearch/index/query/SpanFirstQueryBuilder.java
Java
apache-2.0
1,877
[assembly: Xamarin.Forms.Platform.WPF.ExportRenderer(typeof(Xamarin.Forms.Entry), typeof(Xamarin.Forms.Platform.WPF.Controls.EntryRenderer))] namespace Xamarin.Forms.Platform.WPF.Controls { using System.Windows; using System.Windows.Controls; public partial class EntryRenderer : Xamarin.Forms.Platform.WPF.Rendereres.ViewRenderer { bool ignoreTextChange; public new Entry Model { get { return (Entry)base.Model; } set { base.Model = value; } } public EntryRenderer() { InitializeComponent(); } protected override void LoadModel(View model) { ((Entry)model).TextChanged += EntryModel_TextChanged; base.LoadModel(model); } protected override void UnloadModel(View model) { ((Entry)model).TextChanged -= EntryModel_TextChanged; base.UnloadModel(model); } void EntryModel_TextChanged(object sender, Xamarin.Forms.TextChangedEventArgs e) { if (ignoreTextChange) return; ignoreTextChange = true; TextBox.Text = e.NewTextValue; PasswordBox.Password = e.NewTextValue; ignoreTextChange = false; } void TextBox_TextChanged(object sender, TextChangedEventArgs e) { if (ignoreTextChange) return; ignoreTextChange = true; Model.Text = TextBox.Text; PasswordBox.Password = TextBox.Text; ignoreTextChange = false; } void PasswordBox_PasswordChanged(object sender, RoutedEventArgs e) { if (ignoreTextChange) return; ignoreTextChange = true; Model.Text = PasswordBox.Password; TextBox.Text = PasswordBox.Password; ignoreTextChange = false; } private void Entry_LostFocus(object sender, RoutedEventArgs e) { if (Model != null) Model.SendCompleted(); } private void Entry_PreviewKeyDown(object sender, System.Windows.Input.KeyEventArgs e) { if (Model != null && e.Key == System.Windows.Input.Key.Return) { Model.SendCompleted(); e.Handled = true; } } protected override bool Handle_BackgroundColorProperty(BindableProperty property) { // Background color is set directly to the TextBox/PasswordBox with bindings. return true; } } }
jvlppm/xamarin-forms-wpf
src/Xamarin.Forms.Platforms/Xamarin.Forms.Platform.WPF/Platform.WPF/Rendereres/EntryRenderer.xaml.cs
C#
apache-2.0
2,632
/*§ =========================================================================== MoonDeploy =========================================================================== Copyright (C) 2015-2016 Gianluca Costa =========================================================================== Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =========================================================================== */ package test /* It is not trivial to perform automated tests for MoonDeploy. Currently, testing is based on its actual execution for existing programs such as GraphsJ, Chronos IDE and KnapScal. */
giancosta86/moondeploy
v3/test/test.go
GO
apache-2.0
1,117
# Asterinites colombiensis Doub. & D. Pons ex Kalgutkar & Janson. SPECIES #### Status ACCEPTED #### According to Index Fungorum #### Published in AASP Contributions Series (Dallas) 39: 32 + pl. 30, fig. 9 (2000) #### Original name Asterinites colombiensis Doub. & D. Pons ex Kalgutkar & Janson. ### Remarks null
mdoering/backbone
life/Fungi/Asterinites/Asterinites colombiensis/README.md
Markdown
apache-2.0
316
page_title: Dockerfile Reference page_description: Dockerfiles use a simple DSL which allows you to automate the steps you would normally manually take to create an image. page_keywords: builder, docker, Dockerfile, automation, image creation # Dockerfile Reference **Docker can act as a builder** and read instructions from a text *Dockerfile* to automate the steps you would otherwise take manually to create an image. Executing `docker build` will run your steps and commit them along the way, giving you a final image. ## Usage To [*build*](../commandline/cli/#cli-build) an image from a source repository, create a description file called Dockerfile at the root of your repository. This file will describe the steps to assemble the image. Then call `docker build` with the path of your source repository as the argument (for example, `.`): $ sudo docker build . The path to the source repository defines where to find the *context* of the build. The build is run by the Docker daemon, not by the CLI, so the whole context must be transferred to the daemon. The Docker CLI reports "Sending build context to Docker daemon" when the context is sent to the daemon. You can specify a repository and tag at which to save the new image if the build succeeds: $ sudo docker build -t shykes/myapp . The Docker daemon will run your steps one-by-one, committing the result to a new image if necessary, before finally outputting the ID of your new image. The Docker daemon will automatically clean up the context you sent. Note that each instruction is run independently, and causes a new image to be created - so `RUN cd /tmp` will not have any effect on the next instructions. Whenever possible, Docker will re-use the intermediate images, accelerating `docker build` significantly (indicated by `Using cache`): $ docker build -t SvenDowideit/ambassador . Uploading context 10.24 kB Uploading context Step 1 : FROM docker-ut ---> cbba202fe96b Step 2 : MAINTAINER [email protected] ---> Using cache ---> 51182097be13 Step 3 : CMD env | grep _TCP= | sed 's/.*_PORT_\([0-9]*\)_TCP=tcp:\/\/\(.*\):\(.*\)/socat TCP4-LISTEN:\1,fork,reuseaddr TCP4:\2:\3 \&/' | sh && top ---> Using cache ---> 1a5ffc17324d Successfully built 1a5ffc17324d When you're done with your build, you're ready to look into [*Pushing a repository to its registry*]( /userguide/dockerrepos/#image-push). ## Format Here is the format of the Dockerfile: # Comment INSTRUCTION arguments The Instruction is not case-sensitive, however convention is for them to be UPPERCASE in order to distinguish them from arguments more easily. Docker evaluates the instructions in a Dockerfile in order. **The first instruction must be \`FROM\`** in order to specify the [*Base Image*](/terms/image/#base-image-def) from which you are building. Docker will treat lines that *begin* with `#` as a comment. A `#` marker anywhere else in the line will be treated as an argument. This allows statements like: # Comment RUN echo 'we are running some # of cool things' Here is the set of instructions you can use in a Dockerfile for building images. ## .dockerignore If a file named `.dockerignore` exists in the source repository, then it is interpreted as a newline-separated list of exclusion patterns. Exclusion patterns match files or directories relative to the source repository that will be excluded from the context. Globbing is done using Go's [filepath.Match](http://golang.org/pkg/path/filepath#Match) rules. The following example shows the use of the `.dockerignore` file to exclude the `.git` directory from the context. Its effect can be seen in the changed size of the uploaded context. $ docker build . Uploading context 18.829 MB Uploading context Step 0 : FROM busybox ---> 769b9341d937 Step 1 : CMD echo Hello World ---> Using cache ---> 99cc1ad10469 Successfully built 99cc1ad10469 $ echo ".git" > .dockerignore $ docker build . Uploading context 6.76 MB Uploading context Step 0 : FROM busybox ---> 769b9341d937 Step 1 : CMD echo Hello World ---> Using cache ---> 99cc1ad10469 Successfully built 99cc1ad10469 ## FROM FROM <image> Or FROM <image>:<tag> The `FROM` instruction sets the [*Base Image*](/terms/image/#base-image-def) for subsequent instructions. As such, a valid Dockerfile must have `FROM` as its first instruction. The image can be any valid image – it is especially easy to start by **pulling an image** from the [*Public Repositories*]( /userguide/dockerrepos/#using-public-repositories). `FROM` must be the first non-comment instruction in the Dockerfile. `FROM` can appear multiple times within a single Dockerfile in order to create multiple images. Simply make a note of the last image id output by the commit before each new `FROM` command. If no `tag` is given to the `FROM` instruction, `latest` is assumed. If the used tag does not exist, an error will be returned. ## MAINTAINER MAINTAINER <name> The `MAINTAINER` instruction allows you to set the *Author* field of the generated images. ## RUN RUN has 2 forms: - `RUN <command>` (the command is run in a shell - `/bin/sh -c`) - `RUN ["executable", "param1", "param2"]` (*exec* form) The `RUN` instruction will execute any commands in a new layer on top of the current image and commit the results. The resulting committed image will be used for the next step in the Dockerfile. Layering `RUN` instructions and generating commits conforms to the core concepts of Docker where commits are cheap and containers can be created from any point in an image's history, much like source control. The *exec* form makes it possible to avoid shell string munging, and to `RUN` commands using a base image that does not contain `/bin/sh`. The cache for `RUN` instructions isn't invalidated automatically during the next build. The cache for an instruction like `RUN apt-get dist-upgrade -y` will be reused during the next build. The cache for `RUN` instructions can be invalidated by using the `--no-cache` flag, for example `docker build --no-cache`. The cache for `RUN` instructions can be invalidated by `ADD` instructions. See [below](#add) for details. ### Known Issues (RUN) - [Issue 783](https://github.com/dotcloud/docker/issues/783) is about file permissions problems that can occur when using the AUFS file system. You might notice it during an attempt to `rm` a file, for example. The issue describes a workaround. - [Issue 2424](https://github.com/dotcloud/docker/issues/2424) Locale will not be set automatically. ## CMD CMD has three forms: - `CMD ["executable","param1","param2"]` (like an *exec*, this is the preferred form) - `CMD ["param1","param2"]` (as *default parameters to ENTRYPOINT*) - `CMD command param1 param2` (as a *shell*) There can only be one CMD in a Dockerfile. If you list more than one CMD then only the last CMD will take effect. **The main purpose of a CMD is to provide defaults for an executing container.** These defaults can include an executable, or they can omit the executable, in which case you must specify an ENTRYPOINT as well. When used in the shell or exec formats, the `CMD` instruction sets the command to be executed when running the image. If you use the *shell* form of the CMD, then the `<command>` will execute in `/bin/sh -c`: FROM ubuntu CMD echo "This is a test." | wc - If you want to **run your** `<command>` **without a shell** then you must express the command as a JSON array and give the full path to the executable. **This array form is the preferred format of CMD.** Any additional parameters must be individually expressed as strings in the array: FROM ubuntu CMD ["/usr/bin/wc","--help"] If you would like your container to run the same executable every time, then you should consider using `ENTRYPOINT` in combination with `CMD`. See [*ENTRYPOINT*](#entrypoint). If the user specifies arguments to `docker run` then they will override the default specified in CMD. > **Note**: > don't confuse `RUN` with `CMD`. `RUN` actually runs a command and commits > the result; `CMD` does not execute anything at build time, but specifies > the intended command for the image. ## EXPOSE EXPOSE <port> [<port>...] The `EXPOSE` instructions informs Docker that the container will listen on the specified network ports at runtime. Docker uses this information to interconnect containers using links (see the [Docker User Guide](/userguide/dockerlinks)). ## ENV ENV <key> <value> The `ENV` instruction sets the environment variable `<key>` to the value `<value>`. This value will be passed to all future `RUN` instructions. This is functionally equivalent to prefixing the command with `<key>=<value>` The environment variables set using `ENV` will persist when a container is run from the resulting image. You can view the values using `docker inspect`, and change them using `docker run --env <key>=<value>`. > **Note**: > One example where this can cause unexpected consequences, is setting > `ENV DEBIAN_FRONTEND noninteractive`. Which will persist when the container > is run interactively; for example: `docker run -t -i image bash` ## ADD ADD <src> <dest> The `ADD` instruction will copy new files from `<src>` and add them to the container's filesystem at path `<dest>`. `<src>` must be the path to a file or directory relative to the source directory being built (also called the *context* of the build) or a remote file URL. `<dest>` is the absolute path to which the source will be copied inside the destination container. All new files and directories are created with a uid and gid of 0. In the case where `<src>` is a remote file URL, the destination will have permissions 600. > **Note**: > If you build by passing a Dockerfile through STDIN (`docker build - < somefile`), > there is no build context, so the Dockerfile can only contain a URL > based ADD statement. > You can also pass a compressed archive through STDIN: > (`docker build - < archive.tar.gz`), the `Dockerfile` at the root of > the archive and the rest of the archive will get used at the context > of the build. > > **Note**: > If your URL files are protected using authentication, you will need to > use `RUN wget` , `RUN curl` > or use another tool from within the container as ADD does not support > authentication. > **Note**: > The first encountered `ADD` instruction will invalidate the cache for all > following instructions from the Dockerfile if the contents of `<src>` have > changed. This includes invalidating the cache for `RUN` instructions. The copy obeys the following rules: - The `<src>` path must be inside the *context* of the build; you cannot `ADD ../something /something`, because the first step of a `docker build` is to send the context directory (and subdirectories) to the docker daemon. - If `<src>` is a URL and `<dest>` does not end with a trailing slash, then a file is downloaded from the URL and copied to `<dest>`. - If `<src>` is a URL and `<dest>` does end with a trailing slash, then the filename is inferred from the URL and the file is downloaded to `<dest>/<filename>`. For instance, `ADD http://example.com/foobar /` would create the file `/foobar`. The URL must have a nontrivial path so that an appropriate filename can be discovered in this case (`http://example.com` will not work). - If `<src>` is a directory, the entire directory is copied, including filesystem metadata. - If `<src>` is a *local* tar archive in a recognized compression format (identity, gzip, bzip2 or xz) then it is unpacked as a directory. Resources from *remote* URLs are **not** decompressed. When a directory is copied or unpacked, it has the same behavior as `tar -x`: the result is the union of: 1. whatever existed at the destination path and 2. the contents of the source tree, with conflicts resolved in favor of "2." on a file-by-file basis. - If `<src>` is any other kind of file, it is copied individually along with its metadata. In this case, if `<dest>` ends with a trailing slash `/`, it will be considered a directory and the contents of `<src>` will be written at `<dest>/base(<src>)`. - If `<dest>` does not end with a trailing slash, it will be considered a regular file and the contents of `<src>` will be written at `<dest>`. - If `<dest>` doesn't exist, it is created along with all missing directories in its path. ## COPY COPY <src> <dest> The `COPY` instruction will copy new files from `<src>` and add them to the container's filesystem at path `<dest>`. `<src>` must be the path to a file or directory relative to the source directory being built (also called the *context* of the build). `<dest>` is the absolute path to which the source will be copied inside the destination container. All new files and directories are created with a uid and gid of 0. > **Note**: > If you build using STDIN (`docker build - < somefile`), there is no > build context, so `COPY` can't be used. The copy obeys the following rules: - The `<src>` path must be inside the *context* of the build; you cannot `COPY ../something /something`, because the first step of a `docker build` is to send the context directory (and subdirectories) to the docker daemon. - If `<src>` is a directory, the entire directory is copied, including filesystem metadata. - If `<src>` is any other kind of file, it is copied individually along with its metadata. In this case, if `<dest>` ends with a trailing slash `/`, it will be considered a directory and the contents of `<src>` will be written at `<dest>/base(<src>)`. - If `<dest>` does not end with a trailing slash, it will be considered a regular file and the contents of `<src>` will be written at `<dest>`. - If `<dest>` doesn't exist, it is created along with all missing directories in its path. ## ENTRYPOINT ENTRYPOINT has two forms: - `ENTRYPOINT ["executable", "param1", "param2"]` (like an *exec*, preferred form) - `ENTRYPOINT command param1 param2` (as a *shell*) There can only be one `ENTRYPOINT` in a Dockerfile. If you have more than one `ENTRYPOINT`, then only the last one in the Dockerfile will have an effect. An `ENTRYPOINT` helps you to configure a container that you can run as an executable. That is, when you specify an `ENTRYPOINT`, then the whole container runs as if it was just that executable. The `ENTRYPOINT` instruction adds an entry command that will **not** be overwritten when arguments are passed to `docker run`, unlike the behavior of `CMD`. This allows arguments to be passed to the entrypoint. i.e. `docker run <image> -d` will pass the "-d" argument to the ENTRYPOINT. You can specify parameters either in the ENTRYPOINT JSON array (as in "like an exec" above), or by using a CMD statement. Parameters in the ENTRYPOINT will not be overridden by the `docker run` arguments, but parameters specified via CMD will be overridden by `docker run` arguments. Like a `CMD`, you can specify a plain string for the `ENTRYPOINT` and it will execute in `/bin/sh -c`: FROM ubuntu ENTRYPOINT wc -l - For example, that Dockerfile's image will *always* take STDIN as input ("-") and print the number of lines ("-l"). If you wanted to make this optional but default, you could use a CMD: FROM ubuntu CMD ["-l", "-"] ENTRYPOINT ["/usr/bin/wc"] ## VOLUME VOLUME ["/data"] The `VOLUME` instruction will create a mount point with the specified name and mark it as holding externally mounted volumes from native host or other containers. The value can be a JSON array, `VOLUME ["/var/log/"]`, or a plain string, `VOLUME /var/log`. For more information/examples and mounting instructions via the Docker client, refer to [*Share Directories via Volumes*]( /userguide/dockervolumes/#volume-def) documentation. ## USER USER daemon The `USER` instruction sets the username or UID to use when running the image and for any following `RUN` directives. ## WORKDIR WORKDIR /path/to/workdir The `WORKDIR` instruction sets the working directory for the `RUN`, `CMD` and `ENTRYPOINT` Dockerfile commands that follow it. It can be used multiple times in the one Dockerfile. If a relative path is provided, it will be relative to the path of the previous `WORKDIR` instruction. For example: WORKDIR /a WORKDIR b WORKDIR c RUN pwd The output of the final `pwd` command in this Dockerfile would be `/a/b/c`. ## ONBUILD ONBUILD [INSTRUCTION] The `ONBUILD` instruction adds to the image a "trigger" instruction to be executed at a later time, when the image is used as the base for another build. The trigger will be executed in the context of the downstream build, as if it had been inserted immediately after the *FROM* instruction in the downstream Dockerfile. Any build instruction can be registered as a trigger. This is useful if you are building an image which will be used as a base to build other images, for example an application build environment or a daemon which may be customized with user-specific configuration. For example, if your image is a reusable python application builder, it will require application source code to be added in a particular directory, and it might require a build script to be called *after* that. You can't just call *ADD* and *RUN* now, because you don't yet have access to the application source code, and it will be different for each application build. You could simply provide application developers with a boilerplate Dockerfile to copy-paste into their application, but that is inefficient, error-prone and difficult to update because it mixes with application-specific code. The solution is to use *ONBUILD* to register in advance instructions to run later, during the next build stage. Here's how it works: 1. When it encounters an *ONBUILD* instruction, the builder adds a trigger to the metadata of the image being built. The instruction does not otherwise affect the current build. 2. At the end of the build, a list of all triggers is stored in the image manifest, under the key *OnBuild*. They can be inspected with *docker inspect*. 3. Later the image may be used as a base for a new build, using the *FROM* instruction. As part of processing the *FROM* instruction, the downstream builder looks for *ONBUILD* triggers, and executes them in the same order they were registered. If any of the triggers fail, the *FROM* instruction is aborted which in turn causes the build to fail. If all triggers succeed, the FROM instruction completes and the build continues as usual. 4. Triggers are cleared from the final image after being executed. In other words they are not inherited by "grand-children" builds. For example you might add something like this: [...] ONBUILD ADD . /app/src ONBUILD RUN /usr/local/bin/python-build --dir /app/src [...] > **Warning**: Chaining ONBUILD instructions using ONBUILD ONBUILD isn't allowed. > **Warning**: ONBUILD may not trigger FROM or MAINTAINER instructions. ## Dockerfile Examples # Nginx # # VERSION 0.0.1 FROM ubuntu MAINTAINER Victor Vieux <[email protected]> # make sure the package repository is up to date RUN echo "deb http://archive.ubuntu.com/ubuntu precise main universe" > /etc/apt/sources.list RUN apt-get update RUN apt-get install -y inotify-tools nginx apache2 openssh-server # Firefox over VNC # # VERSION 0.3 FROM ubuntu # make sure the package repository is up to date RUN echo "deb http://archive.ubuntu.com/ubuntu precise main universe" > /etc/apt/sources.list RUN apt-get update # Install vnc, xvfb in order to create a 'fake' display and firefox RUN apt-get install -y x11vnc xvfb firefox RUN mkdir /.vnc # Setup a password RUN x11vnc -storepasswd 1234 ~/.vnc/passwd # Autostart firefox (might not be the best way, but it does the trick) RUN bash -c 'echo "firefox" >> /.bashrc' EXPOSE 5900 CMD ["x11vnc", "-forever", "-usepw", "-create"] # Multiple images example # # VERSION 0.1 FROM ubuntu RUN echo foo > bar # Will output something like ===> 907ad6c2736f FROM ubuntu RUN echo moo > oink # Will output something like ===> 695d7793cbe4 # You᾿ll now have two images, 907ad6c2736f with /bar, and 695d7793cbe4 with # /oink.
abudulemusa/docker
docs/sources/reference/builder.md
Markdown
apache-2.0
20,602
/** * @license * Copyright The Closure Library Authors. * SPDX-License-Identifier: Apache-2.0 */ /** * @fileoverview Displays and edits the value of a cookie. * Intended only for debugging. */ goog.provide('goog.ui.CookieEditor'); goog.require('goog.asserts'); goog.require('goog.dom'); goog.require('goog.dom.TagName'); goog.require('goog.events.EventType'); goog.require('goog.net.Cookies'); goog.require('goog.string'); goog.require('goog.style'); goog.require('goog.ui.Component'); goog.requireType('goog.events.Event'); /** * Displays and edits the value of a cookie. * @final * @unrestricted */ goog.ui.CookieEditor = class extends goog.ui.Component { /** * @param {goog.dom.DomHelper=} opt_domHelper Optional DOM helper. */ constructor(opt_domHelper) { 'use strict'; super(opt_domHelper); } /** * Sets the cookie which this component will edit. * @param {string} cookieKey Cookie key. */ selectCookie(cookieKey) { 'use strict'; goog.asserts.assert(goog.net.Cookies.getInstance().isValidName(cookieKey)); this.cookieKey_ = cookieKey; if (this.textAreaElem_) { this.textAreaElem_.value = goog.net.Cookies.getInstance().get(cookieKey) || ''; } } /** @override */ canDecorate() { 'use strict'; return false; } /** @override */ createDom() { 'use strict'; // Debug-only, so we don't need i18n. this.clearButtonElem_ = goog.dom.createDom( goog.dom.TagName.BUTTON, /* attributes */ null, 'Clear'); this.updateButtonElem_ = goog.dom.createDom( goog.dom.TagName.BUTTON, /* attributes */ null, 'Update'); var value = this.cookieKey_ && goog.net.Cookies.getInstance().get(this.cookieKey_); this.textAreaElem_ = goog.dom.createDom( goog.dom.TagName.TEXTAREA, /* attibutes */ null, value || ''); this.valueWarningElem_ = goog.dom.createDom( goog.dom.TagName.SPAN, /* attibutes */ {'style': 'display:none;color:red'}, 'Invalid cookie value.'); this.setElementInternal(goog.dom.createDom( goog.dom.TagName.DIV, /* attibutes */ null, this.valueWarningElem_, goog.dom.createDom(goog.dom.TagName.BR), this.textAreaElem_, goog.dom.createDom(goog.dom.TagName.BR), this.clearButtonElem_, this.updateButtonElem_)); } /** @override */ enterDocument() { 'use strict'; super.enterDocument(); this.getHandler().listen( this.clearButtonElem_, goog.events.EventType.CLICK, this.handleClear_); this.getHandler().listen( this.updateButtonElem_, goog.events.EventType.CLICK, this.handleUpdate_); } /** * Handles user clicking clear button. * @param {!goog.events.Event} e The click event. * @private */ handleClear_(e) { 'use strict'; if (this.cookieKey_) { goog.net.Cookies.getInstance().remove(this.cookieKey_); } this.textAreaElem_.value = ''; } /** * Handles user clicking update button. * @param {!goog.events.Event} e The click event. * @private */ handleUpdate_(e) { 'use strict'; if (this.cookieKey_) { var value = this.textAreaElem_.value; if (value) { // Strip line breaks. value = goog.string.stripNewlines(value); } if (goog.net.Cookies.getInstance().isValidValue(value)) { goog.net.Cookies.getInstance().set(this.cookieKey_, value); goog.style.setElementShown(this.valueWarningElem_, false); } else { goog.style.setElementShown(this.valueWarningElem_, true); } } } /** @override */ disposeInternal() { 'use strict'; this.clearButtonElem_ = null; this.cookieKey_ = null; this.textAreaElem_ = null; this.updateButtonElem_ = null; this.valueWarningElem_ = null; } }; /** * Cookie key. * @type {?string} * @private */ goog.ui.CookieEditor.prototype.cookieKey_; /** * Text area. * @type {HTMLTextAreaElement} * @private */ goog.ui.CookieEditor.prototype.textAreaElem_; /** * Clear button. * @type {HTMLButtonElement} * @private */ goog.ui.CookieEditor.prototype.clearButtonElem_; /** * Invalid value warning text. * @type {HTMLSpanElement} * @private */ goog.ui.CookieEditor.prototype.valueWarningElem_; /** * Update button. * @type {HTMLButtonElement} * @private */ goog.ui.CookieEditor.prototype.updateButtonElem_; // TODO(user): add combobox for user to select different cookies
google/closure-library
closure/goog/ui/cookieeditor.js
JavaScript
apache-2.0
4,463
/* * Forge SDK * * The Forge Platform contains an expanding collection of web service components that can be used with Autodesk cloud-based products or your own technologies. Take advantage of Autodesk’s expertise in design and engineering. * * OpenAPI spec version: 0.1.0 * Contact: [email protected] * Generated by: https://github.com/swagger-api/swagger-codegen.git * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Linq; using System.IO; using System.Text; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; namespace Autodesk.Forge.Model { /// <summary> /// RelRefMeta /// </summary> [DataContract] public partial class RelRefMeta : IEquatable<RelRefMeta> { /// <summary> /// Gets or Sets RefType /// </summary> [JsonConverter(typeof(StringEnumConverter))] public enum RefTypeEnum { /// <summary> /// Enum Derived for "derived" /// </summary> [EnumMember(Value = "derived")] Derived, /// <summary> /// Enum Dependencies for "dependencies" /// </summary> [EnumMember(Value = "dependencies")] Dependencies, /// <summary> /// Enum Auxiliary for "auxiliary" /// </summary> [EnumMember(Value = "auxiliary")] Auxiliary, /// <summary> /// Enum Xrefs for "xrefs" /// </summary> [EnumMember(Value = "xrefs")] Xrefs } /// <summary> /// describes the direction of the reference relative to the resource the refs are queried for /// </summary> /// <value>describes the direction of the reference relative to the resource the refs are queried for</value> [JsonConverter(typeof(StringEnumConverter))] public enum DirectionEnum { /// <summary> /// Enum From for "from" /// </summary> [EnumMember(Value = "from")] From, /// <summary> /// Enum To for "to" /// </summary> [EnumMember(Value = "to")] To } /// <summary> /// Gets or Sets FromType /// </summary> [JsonConverter(typeof(StringEnumConverter))] public enum FromTypeEnum { /// <summary> /// Enum Folders for "folders" /// </summary> [EnumMember(Value = "folders")] Folders, /// <summary> /// Enum Items for "items" /// </summary> [EnumMember(Value = "items")] Items, /// <summary> /// Enum Versions for "versions" /// </summary> [EnumMember(Value = "versions")] Versions } /// <summary> /// Gets or Sets ToType /// </summary> [JsonConverter(typeof(StringEnumConverter))] public enum ToTypeEnum { /// <summary> /// Enum Folders for "folders" /// </summary> [EnumMember(Value = "folders")] Folders, /// <summary> /// Enum Items for "items" /// </summary> [EnumMember(Value = "items")] Items, /// <summary> /// Enum Versions for "versions" /// </summary> [EnumMember(Value = "versions")] Versions } /// <summary> /// Gets or Sets RefType /// </summary> [DataMember(Name="refType", EmitDefaultValue=false)] public RefTypeEnum? RefType { get; set; } /// <summary> /// describes the direction of the reference relative to the resource the refs are queried for /// </summary> /// <value>describes the direction of the reference relative to the resource the refs are queried for</value> [DataMember(Name="direction", EmitDefaultValue=false)] public DirectionEnum? Direction { get; set; } /// <summary> /// Gets or Sets FromType /// </summary> [DataMember(Name="fromType", EmitDefaultValue=false)] public FromTypeEnum? FromType { get; set; } /// <summary> /// Gets or Sets ToType /// </summary> [DataMember(Name="toType", EmitDefaultValue=false)] public ToTypeEnum? ToType { get; set; } /// <summary> /// Initializes a new instance of the <see cref="RelRefMeta" /> class. /// </summary> [JsonConstructorAttribute] protected RelRefMeta() { } /// <summary> /// Initializes a new instance of the <see cref="RelRefMeta" /> class. /// </summary> /// <param name="RefType">RefType (required).</param> /// <param name="Direction">describes the direction of the reference relative to the resource the refs are queried for (required).</param> /// <param name="FromId">FromId (required).</param> /// <param name="FromType">FromType (required).</param> /// <param name="ToId">ToId (required).</param> /// <param name="ToType">ToType (required).</param> /// <param name="Extension">Extension (required).</param> public RelRefMeta(RefTypeEnum? RefType = null, DirectionEnum? Direction = null, string FromId = null, FromTypeEnum? FromType = null, string ToId = null, ToTypeEnum? ToType = null, BaseAttributesExtensionObject Extension = null) { // to ensure "RefType" is required (not null) if (RefType == null) { throw new InvalidDataException("RefType is a required property for RelRefMeta and cannot be null"); } else { this.RefType = RefType; } // to ensure "Direction" is required (not null) if (Direction == null) { throw new InvalidDataException("Direction is a required property for RelRefMeta and cannot be null"); } else { this.Direction = Direction; } // to ensure "FromId" is required (not null) if (FromId == null) { throw new InvalidDataException("FromId is a required property for RelRefMeta and cannot be null"); } else { this.FromId = FromId; } // to ensure "FromType" is required (not null) if (FromType == null) { throw new InvalidDataException("FromType is a required property for RelRefMeta and cannot be null"); } else { this.FromType = FromType; } // to ensure "ToId" is required (not null) if (ToId == null) { throw new InvalidDataException("ToId is a required property for RelRefMeta and cannot be null"); } else { this.ToId = ToId; } // to ensure "ToType" is required (not null) if (ToType == null) { throw new InvalidDataException("ToType is a required property for RelRefMeta and cannot be null"); } else { this.ToType = ToType; } // to ensure "Extension" is required (not null) if (Extension == null) { throw new InvalidDataException("Extension is a required property for RelRefMeta and cannot be null"); } else { this.Extension = Extension; } } /// <summary> /// Gets or Sets FromId /// </summary> [DataMember(Name="fromId", EmitDefaultValue=false)] public string FromId { get; set; } /// <summary> /// Gets or Sets ToId /// </summary> [DataMember(Name="toId", EmitDefaultValue=false)] public string ToId { get; set; } /// <summary> /// Gets or Sets Extension /// </summary> [DataMember(Name="extension", EmitDefaultValue=false)] public BaseAttributesExtensionObject Extension { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class RelRefMeta {\n"); sb.Append(" RefType: ").Append(RefType).Append("\n"); sb.Append(" Direction: ").Append(Direction).Append("\n"); sb.Append(" FromId: ").Append(FromId).Append("\n"); sb.Append(" FromType: ").Append(FromType).Append("\n"); sb.Append(" ToId: ").Append(ToId).Append("\n"); sb.Append(" ToType: ").Append(ToType).Append("\n"); sb.Append(" Extension: ").Append(Extension).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="obj">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object obj) { // credit: http://stackoverflow.com/a/10454552/677735 return this.Equals(obj as RelRefMeta); } /// <summary> /// Returns true if RelRefMeta instances are equal /// </summary> /// <param name="other">Instance of RelRefMeta to be compared</param> /// <returns>Boolean</returns> public bool Equals(RelRefMeta other) { // credit: http://stackoverflow.com/a/10454552/677735 if (other == null) return false; return ( this.RefType == other.RefType || this.RefType != null && this.RefType.Equals(other.RefType) ) && ( this.Direction == other.Direction || this.Direction != null && this.Direction.Equals(other.Direction) ) && ( this.FromId == other.FromId || this.FromId != null && this.FromId.Equals(other.FromId) ) && ( this.FromType == other.FromType || this.FromType != null && this.FromType.Equals(other.FromType) ) && ( this.ToId == other.ToId || this.ToId != null && this.ToId.Equals(other.ToId) ) && ( this.ToType == other.ToType || this.ToType != null && this.ToType.Equals(other.ToType) ) && ( this.Extension == other.Extension || this.Extension != null && this.Extension.Equals(other.Extension) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { // credit: http://stackoverflow.com/a/263416/677735 unchecked // Overflow is fine, just wrap { int hash = 41; // Suitable nullity checks etc, of course :) if (this.RefType != null) hash = hash * 59 + this.RefType.GetHashCode(); if (this.Direction != null) hash = hash * 59 + this.Direction.GetHashCode(); if (this.FromId != null) hash = hash * 59 + this.FromId.GetHashCode(); if (this.FromType != null) hash = hash * 59 + this.FromType.GetHashCode(); if (this.ToId != null) hash = hash * 59 + this.ToId.GetHashCode(); if (this.ToType != null) hash = hash * 59 + this.ToType.GetHashCode(); if (this.Extension != null) hash = hash * 59 + this.Extension.GetHashCode(); return hash; } } } }
Autodesk-Forge/forge-api-dotnet-client
src/Autodesk.Forge/Model/RelRefMeta.cs
C#
apache-2.0
13,760
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /* Package db contains functions related to database. * db.go includes conneting to db, query and insertion. * dbschema.go contains definitions of struct for db tables. Currently it only contains Module struct. */ package db import ( "database/sql" "fmt" "os" "strconv" "github.com/golang/glog" // Go postgres driver for Go's database/sql package _ "github.com/lib/pq" ) // These are SQL stataments used in this package. // Query statements can be appended based on its query parameters. const ( // $4 and $5 should be assigned with the same value (the JSON data of module). insertModule = `INSERT INTO modules (orgName, name, version, data) VALUES($1, $2, $3, $4) on conflict (orgName, name, version) do update set data=$5` selectModules = `select * from modules` // We want to ensure that user has to provide all three inputs, // instead of deleting too many modules by mistake with some fields missing. deleteModule = `delete from modules where orgName = $1 and name = $2 and version = $3` selectFeatureBundles = `select * from featureBundles` // $4 and $5 should be assigned with the same value (the JSON data of feature-bundle). insertFeatureBundle = `INSERT INTO featureBundles (orgName, name, version, data) VALUES($1, $2, $3, $4) on conflict (orgName, name, version) do update set data=$5` deleteFeatureBundle = `delete from featurebundles where orgName = $1 and name = $2 and version = $3` ) // db is the global variable of connection to database. // It would be assigned value when *ConnectDB* function is called. // // We choose to use this global variable due to that *gqlgen* automatically generates many server side codes. // Resolver functions generated by *gqlgen* are handler functions for graphQL queries and are methods of *resolver* struct. // If we define a struct with field of db connection instead of using the global variable // and change *Query* functions to methods of that struct, // we need to initialize db connection while initializing *resolver* object in server codes // such that *resolver* functions can call these *Query* functions. // However, initialization function of *resolver* struct is automatically generated and overwritten every time. // Thus, we cannot initialize a db connection inside the *resolver* objects. // // Another option is to establish a new db connection for each *Query* function and close it after query finishes. // However, that would be too expensive to connect to db every time server receives a new query. var db *sql.DB // ConnectDB establishes connection to database, *db* variable is assigned when opening database. // This should only be called once before any other database function is called. // // Users need set environment variables for connection, including // * DB_HOST: host address of target db instances, by default: localhost. // * DB_PORT: port number of postgres db, by default: 5432. // * DB_USERNAME: username of database, error would be returned if not set. // * DB_PWD: password of target database, error would be returned if not set. // * DB_NAME: name of database for connection, error would be returned if not set. // * DB_SOCKER_DIR: directory of Unix socket in Cloud Run which serves as Cloud SQL // Auth proxy to connect to postgres database. // If service is deployed on Cloud Run, just use the default value. // By default, it is set to `/cloudsql`. func ConnectDB() error { // read db config from env // port number of target database port := 5432 if portStr, ok := os.LookupEnv("DB_PORT"); !ok { glog.Infof("DB_PORT not set, setting port to %d", port) } else { var err error if port, err = strconv.Atoi(portStr); err != nil { return fmt.Errorf("DB_PORT in incorrect format: %v", err) } } // username of target database user, ok := os.LookupEnv("DB_USERNAME") if !ok { return fmt.Errorf("DB_USERNAME not set") } // password of target database password, ok := os.LookupEnv("DB_PWD") if !ok { return fmt.Errorf("DB_PWD not set") } // name of target database dbname, ok := os.LookupEnv("DB_NAME") if !ok { return fmt.Errorf("DB_NAME not set") } // (Cloud Run only) Directory of Unix socket socketDir, ok := os.LookupEnv("DB_SOCKET_DIR") if !ok { socketDir = "/cloudsql" } var psqlconn string // connection string used to connect to traget database // host address of target database host, ok := os.LookupEnv("DB_HOST") switch { case !ok: glog.Infoln("DB_HOST not set, setting host to localhost") host = "localhost" fallthrough case host == "localhost": // This connection string is used if service is not deployed on Cloud Run, // instead connection is made from localhost via Cloud SQL proxy. psqlconn = fmt.Sprintf("host=%s port=%d user=%s password=%s dbname=%s sslmode=disable", host, port, user, password, dbname) default: psqlconn = fmt.Sprintf("host=%s/%s port=%d user=%s password=%s dbname=%s", socketDir, host, port, user, password, dbname) } // open database var err error db, err = sql.Open("postgres", psqlconn) if err != nil { return fmt.Errorf("open database failed: %v", err) } // see if connection is established successfully if err := db.Ping(); err != nil { return fmt.Errorf("ping database failed: %v", err) } return nil } // Close function closes db connection func Close() error { return db.Close() } // InsertModule inserts module into database given values of four field of MODULE schema. // Or if there is existing module with existing key (orgName, name, version), update data field. // Error is returned when insertion failed. func InsertModule(orgName string, name string, version string, data string) error { if _, err := db.Exec(insertModule, orgName, name, version, data, data); err != nil { return fmt.Errorf("insert/update module into db failed: %v", err) } return nil } // ReadModulesByRow scans from queried modules from rows one by one, rows are closed inside. // Return slice of db Module struct each field of which corresponds to one column in db. // Error is returned when scan rows failed. func ReadModulesByRow(rows *sql.Rows) ([]Module, error) { var modules []Module defer rows.Close() for rows.Next() { var module Module if err := rows.Scan(&module.OrgName, &module.Name, &module.Version, &module.Data); err != nil { return nil, fmt.Errorf("scan db rows failure, %v", err) } modules = append(modules, module) } return modules, nil } // FormatQueryStr is used to generate query statement string based on query parameters. // * parmNames is a list of names of all non-nil query parameters. // * baseQuery is query statement without any query parameters. func FormatQueryStr(parmNames []string, baseQuery string) string { queryStmt := baseQuery for i := 0; i < len(parmNames); i++ { if i == 0 { queryStmt += " where" } else { queryStmt += " and" } queryStmt += fmt.Sprintf(" %s=$%d", parmNames[i], i+1) } return queryStmt } // QueryModulesByOrgName queries modules of organization with *orgName* from database. // If orgName is null then directly query all modules. // Return slice of db Module struct each field of which corresponds to one column in db. // Error is returned when query or reading data failed. func QueryModulesByOrgName(orgName *string) ([]Module, error) { var parms []interface{} // parms is used to store value of non-nil query parameters parmNames := []string{} // parmNames is used to store name of non-nil query parameters if orgName != nil { parms = append(parms, *orgName) parmNames = append(parmNames, "orgName") } // Format query statement string based on non-nil query parameters queryStmt := FormatQueryStr(parmNames, selectModules) rows, err := db.Query(queryStmt, parms...) if err != nil { return nil, fmt.Errorf("QueryModulesByOrgName failed: %v", err) } defer rows.Close() return ReadModulesByRow(rows) } // QueryModulesByKey queries modules by its key (name, version), it is possible that parameters are null. // If both parameters are null, this equals query for all modules. // Return slice of db Module struct each field of which corresponds to one column in db. // Error is returned when query or reading data failed. func QueryModulesByKey(name *string, version *string) ([]Module, error) { var parms []interface{} // parms is used to store value of non-nil query parameters parmNames := []string{} // parmNames is used to store name of non-nil query parameters if name != nil { parms = append(parms, *name) parmNames = append(parmNames, "name") } if version != nil { parms = append(parms, *version) parmNames = append(parmNames, "version") } // Format query statement string based on non-nil query parameters queryStmt := FormatQueryStr(parmNames, selectModules) rows, err := db.Query(queryStmt, parms...) if err != nil { return nil, fmt.Errorf("QueryModulesByOrgName failed: %v", err) } defer rows.Close() return ReadModulesByRow(rows) } // DeleteModule takes three string, orgName, name, version, // whose combination is key of one Module in DB's Module table. // If deletion fails, an non-nil error is returned. // If the number of rows affected by this deletion is not 1, an error is also returned. func DeleteModule(orgName string, name string, version string) error { result, err := db.Exec(deleteModule, orgName, name, version) if err != nil { return fmt.Errorf("DeleteModule failed: %v", err) } num, err := result.RowsAffected() if err != nil { return fmt.Errorf("DeleteModule, access rows affected in result failed: %v", err) } // delete should only affect one row if num != 1 { return fmt.Errorf("DeleteModule: affected row is not one, it affects %d rows", num) } return nil } // ReadFeatureBundlesByRow scans from queried FeatureBundles from rows one by one, rows are closed inside. // Return slice of db FeatureBundle struct each field of which corresponds to one column in db. // Error is returned when scan rows failed. func ReadFeatureBundlesByRow(rows *sql.Rows) ([]FeatureBundle, error) { var featureBundles []FeatureBundle defer rows.Close() for rows.Next() { var featureBundle FeatureBundle if err := rows.Scan(&featureBundle.OrgName, &featureBundle.Name, &featureBundle.Version, &featureBundle.Data); err != nil { return nil, fmt.Errorf("ReadFeatureBundlesByRow: scan db rows failure, %v", err) } featureBundles = append(featureBundles, featureBundle) } return featureBundles, nil } // QueryFeatureBundlesByOrgName queries feature-bundles of organization with *orgName* from database. // If orgName is null then directly query all feature-bundles. // Return slice of db FeatureBundle struct each field of which corresponds to one column in db. // Error is returned when query or reading data failed. func QueryFeatureBundlesByOrgName(orgName *string) ([]FeatureBundle, error) { var parms []interface{} // parms is used to store value of non-nil query parameters parmNames := []string{} // parmNames is used to store name of non-nil query parameters if orgName != nil { parms = append(parms, *orgName) parmNames = append(parmNames, "orgName") } // Format query statement string based on non-nil query parameters queryStmt := FormatQueryStr(parmNames, selectFeatureBundles) rows, err := db.Query(queryStmt, parms...) if err != nil { return nil, fmt.Errorf("QueryFeatureBundlesByOrgName failed: %v", err) } return ReadFeatureBundlesByRow(rows) } // InsertFeatureBundle inserts FeatureBundle into database given values of four field of FeatureBundle schema. // Or if there is existing FeatureBundle with existing key (orgName, name, version), update data field. // Error is returned when insertion failed. func InsertFeatureBundle(orgName string, name string, version string, data string) error { if _, err := db.Exec(insertFeatureBundle, orgName, name, version, data, data); err != nil { return fmt.Errorf("insert/update FeatureBundle into db failed: %v", err) } return nil } // DeleteFeatureBundle takes three pointer of string, orgName, name, version, // whose combination is key of one FeatureBundle in DB's FeatureBundle table. // If deletion fails, an non-nil error is returned. // If the number of rows affected by this deletion is not 1, an error is also returned. func DeleteFeatureBundle(orgName string, name string, version string) error { result, err := db.Exec(deleteFeatureBundle, orgName, name, version) if err != nil { return fmt.Errorf("DeleteFeatureBundle failed: %v", err) } num, err := result.RowsAffected() if err != nil { return fmt.Errorf("DeleteFeatureBundle, access rows affected in result failed: %v", err) } // delete should only affect one row if num != 1 { return fmt.Errorf("DeleteFeatureBundle: affected row is not one, it affects %d rows", num) } return nil } // QueryFeatureBundlesByKey queries feature-bundles by its key (name, version), it is possible that // If both parameters are null, this equals query for all feature-bundles. // Return slice of db FeatureBundle struct each field of which corresponds to one column in // Error is returned when query or reading data failed. func QueryFeatureBundlesByKey(name *string, version *string) ([]FeatureBundle, error) { var parms []interface{} // parms is used to store value of non-nil query paramete parmNames := []string{} // parmNames is used to store name of non-nil query param if name != nil { parms = append(parms, *name) parmNames = append(parmNames, "name") } if version != nil { parms = append(parms, *version) parmNames = append(parmNames, "version") } // Format query statement string based on non-nil query parameters queryStmt := FormatQueryStr(parmNames, selectFeatureBundles) rows, err := db.Query(queryStmt, parms...) if err != nil { return nil, fmt.Errorf("QueryFeatureBundlesByKey failed: %v", err) } return ReadFeatureBundlesByRow(rows) }
openconfig/catalog-server
pkg/db/db.go
GO
apache-2.0
14,564
#!/usr/bin/env perl use warnings; use strict; use POSIX; # convert a set of numbers to a distribution my $bin = shift @ARGV; my $col = shift @ARGV; $bin or die "usage: $0 <bin size> <column number (0 based)> <table (on STDIN)>\n"; my $delim = "\t"; my $n=0; my $sum=0; my $min=1000000000; my $max = -999999999; my %dist; while (<>) { chomp; my @x = split /$delim/, $_; my $val = $x[$col]; is_numeric($val) or next; $sum += $val; $min = $val if ($val < $min); $max = $val if ($val > $max); my $obin = int($val/$bin); $dist{$obin}++; $n++; } my $nover2=$n/2; my $half_ass = $sum/2; my $mean = int(1000*$sum/$n+0.5)/1000; my $sum2=0; my $minbin = $bin*floor($min/$bin); my %cumdist; while (my($obin,$tally) = each %dist) { $sum2 += $tally*($obin*$bin-$mean)**2 } my $stdev = int(1000*sqrt($sum2/$n)+0.5)/1000; my $N50_sum=0; my $N50=0; my ($mode_height,$mode_bin)=(0,0); my $median_bin=0; my $iter=0; my $previ; my @bins = sort {$a <=> $b} keys %dist; for my $i (@bins) { $iter++; if ($N50_sum < $half_ass) { $N50 = $minbin+$i*$bin + floor($bin/2); $N50_sum += $dist{$i}*$N50; } $cumdist{$i} = $dist{$i}; if ($iter>1) { $cumdist{$i} += $cumdist{$previ}; } if ($cumdist{$i} < $nover2) { $median_bin = $i; } if($dist{$i} > $mode_height) { $mode_height = $dist{$i}; $mode_bin = $i; } $previ=$i; } my $mode = $mode_bin*$bin; my $median = $median_bin*$bin; #print "# ", join ("\t",qw(N mean stdev median mode min max N50(bin))),"\n"; #print "# ", join ("\t",($n,$mean,$stdev,$median, $mode,$min,$max,$N50)),"\n"; print qq{# N\t$n # mean\t$mean # stdev\t$stdev # median\t$median # mode\t$mode # min\t$min # max\t$max # N50\t$N50 }; print "\n#", join ("\t",qw(bin raw_dist norm_dist cumulative_dist)),"\n"; for my $i (@bins) { print join ("\t",$i*$bin,$dist{$i},int(1000*$dist{$i}/$n)/1000,int(1000*$cumdist{$i}/$n)/1000),"\n"; } sub getnum { my $str = shift; $str =~ s/^\s+//; $str =~ s/\s+$//; $! = 0; my($num, $unparsed) = strtod($str); if (($str eq '') || ($unparsed != 0) || $!) { return undef; } else { return $num; } } sub is_numeric { defined getnum($_[0]) }
warelab/misc
set2dist.pl
Perl
apache-2.0
2,168
/* Copyright 2014 Cloudbase Solutions Srl Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http ://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "Tcp.h" #include "Ethernet.h" #include "Ipv4.h" #include "Ipv6.h" #include "Frame.h" #include "PacketInfo.h" #include "OvsNetBuffer.h" #include "Checksum.h" OVS_TCP_HEADER* GetTcpHeader(VOID* pPacketBuffer) { OVS_ETHERNET_HEADER* pEthHeader = (OVS_ETHERNET_HEADER*)pPacketBuffer; OVS_TCP_HEADER* pTcpHeader = NULL; if (pEthHeader->type == RtlUshortByteSwap(OVS_ETHERTYPE_QTAG)) { pEthHeader = (OVS_ETHERNET_HEADER*)((BYTE*)pEthHeader + OVS_ETHERNET_VLAN_LEN); } if (pEthHeader->type != RtlUshortByteSwap(OVS_ETHERTYPE_IPV4) && pEthHeader->type != RtlUshortByteSwap(OVS_ETHERTYPE_IPV6)) { return NULL; } if (pEthHeader->type == RtlUshortByteSwap(OVS_ETHERTYPE_IPV4)) { const OVS_IPV4_HEADER* pIpv4Header = ReadIpv4Header(pEthHeader); if (pIpv4Header->Protocol != OVS_IPPROTO_TCP) { return NULL; } pTcpHeader = (OVS_TCP_HEADER*)AdvanceIpv4Header(pIpv4Header); return pTcpHeader; } if (pEthHeader->type == RtlUshortByteSwap(OVS_ETHERTYPE_IPV6)) { OVS_IPV6_HEADER* pIpv6Header = ReadIpv6Header(pEthHeader); BYTE nextHeader = pIpv6Header->nextHeader; VOID* advancedBuffer = AdvanceIpv6Header(pIpv6Header); BYTE headerLength = 0; while (IsIpv6Extension(nextHeader)) { nextHeader = *((BYTE*)advancedBuffer); headerLength = *(sizeof(nextHeader) + (BYTE*)advancedBuffer); advancedBuffer = ((BYTE*)advancedBuffer) + headerLength + 8; } if (nextHeader != OVS_IPV6_EXTH_TCP) { return NULL; } pTcpHeader = (OVS_TCP_HEADER*)advancedBuffer; return pTcpHeader; } return NULL; } BOOLEAN ONB_SetTcp(OVS_NET_BUFFER* pOvsNb, const OVS_PI_TCP* pTcpPI) { OVS_TCP_HEADER *pTcpHeader = NULL; OVS_IPV4_HEADER* pIpv4Header = NULL; VOID* buffer = NULL; UINT16 csumRecomp = 0; UINT16 offset = 0, reserved = 0, flags = 0; buffer = ONB_GetData(pOvsNb); pIpv4Header = GetIpv4Header(buffer); pTcpHeader = GetTcpHeader(buffer); if (pTcpPI->source != pTcpHeader->sourcePort) { DEBUGP_FRAMES(LOG_INFO, "src port (BE): 0x%x -> 0x%x\n", pTcpHeader->sourcePort, pTcpPI->source); DEBUGP_FRAMES(LOG_INFO, "dst port (BE): 0x%x\n", pTcpHeader->destinationPort); csumRecomp = (WORD)RecomputeChecksum((BYTE*)&pTcpHeader->sourcePort, (BYTE*)&pTcpPI->source, 2, pTcpHeader->checksum); csumRecomp = RtlUshortByteSwap(csumRecomp); pTcpHeader->checksum = csumRecomp; pTcpHeader->sourcePort = pTcpPI->source; } if (pTcpPI->destination != pTcpHeader->destinationPort) { DEBUGP_FRAMES(LOG_INFO, "src port (BE): 0x%x\n", pTcpHeader->sourcePort); DEBUGP_FRAMES(LOG_INFO, "dst port (BE): 0x%x -> 0x%x\n", pTcpHeader->destinationPort, pTcpPI->destination); csumRecomp = (WORD)RecomputeChecksum((BYTE*)&pTcpHeader->destinationPort, (BYTE*)&pTcpPI->destination, 2, pTcpHeader->checksum); csumRecomp = RtlUshortByteSwap(csumRecomp); pTcpHeader->checksum = csumRecomp; pTcpHeader->destinationPort = pTcpPI->destination; } offset = GetTcpDataOffset(pTcpHeader->flagsAndOffset); reserved = GetTcpReserved(pTcpHeader->flagsAndOffset); flags = GetTcpFlags(pTcpHeader->flagsAndOffset); DEBUGP_FRAMES(LOG_INFO, "seq number: 0x%x; ack number: 0x%x; offset: 0x%x; reserved: 0x%x; flags: 0x%x\n", pTcpHeader->sequenceNo, pTcpHeader->acknowledgeNo, offset, reserved, flags); return TRUE; } _Use_decl_annotations_ void DbgPrintTcpHeader(const VOID* buffer) { OVS_TCP_HEADER* pTcpHeader = (OVS_TCP_HEADER*)buffer; UNREFERENCED_PARAMETER(pTcpHeader); DEBUGP_FRAMES(LOG_INFO, "tcp: src port = %d; dest port = %d\n", RtlUshortByteSwap(pTcpHeader->sourcePort), RtlUshortByteSwap(pTcpHeader->destinationPort)); } BOOLEAN VerifyTcpHeader(BYTE* buffer, ULONG* pLength) { OVS_TCP_HEADER* pTcpHeader = (OVS_TCP_HEADER*)buffer; //TODO: verify. ATM nothing is done UNREFERENCED_PARAMETER(buffer); UNREFERENCED_PARAMETER(pLength); UNREFERENCED_PARAMETER(pTcpHeader); return TRUE; }
cloudbase/openvswitch-hyperv-kernel
Driver/Protocol/Tcp.c
C
apache-2.0
4,804
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (version 1.7.0_65) on Wed Sep 03 20:01:19 PDT 2014 --> <meta http-equiv="Content-Type" content="text/html" charset="UTF-8"> <title>AuthenticationProtos.WhoAmIRequestOrBuilder (HBase 0.98.6-hadoop2 API)</title> <meta name="date" content="2014-09-03"> <link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="AuthenticationProtos.WhoAmIRequestOrBuilder (HBase 0.98.6-hadoop2 API)"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="class-use/AuthenticationProtos.WhoAmIRequestOrBuilder.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../../../org/apache/hadoop/hbase/protobuf/generated/AuthenticationProtos.WhoAmIRequest.Builder.html" title="class in org.apache.hadoop.hbase.protobuf.generated"><span class="strong">Prev Class</span></a></li> <li><a href="../../../../../../org/apache/hadoop/hbase/protobuf/generated/AuthenticationProtos.WhoAmIResponse.html" title="class in org.apache.hadoop.hbase.protobuf.generated"><span class="strong">Next Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?org/apache/hadoop/hbase/protobuf/generated/AuthenticationProtos.WhoAmIRequestOrBuilder.html" target="_top">Frames</a></li> <li><a href="AuthenticationProtos.WhoAmIRequestOrBuilder.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li>Method</li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li>Method</li> </ul> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <!-- ======== START OF CLASS DATA ======== --> <div class="header"> <div class="subTitle">org.apache.hadoop.hbase.protobuf.generated</div> <h2 title="Interface AuthenticationProtos.WhoAmIRequestOrBuilder" class="title">Interface AuthenticationProtos.WhoAmIRequestOrBuilder</h2> </div> <div class="contentContainer"> <div class="description"> <ul class="blockList"> <li class="blockList"> <dl> <dt>All Superinterfaces:</dt> <dd>com.google.protobuf.MessageLiteOrBuilder, com.google.protobuf.MessageOrBuilder</dd> </dl> <dl> <dt>All Known Implementing Classes:</dt> <dd><a href="../../../../../../org/apache/hadoop/hbase/protobuf/generated/AuthenticationProtos.WhoAmIRequest.html" title="class in org.apache.hadoop.hbase.protobuf.generated">AuthenticationProtos.WhoAmIRequest</a>, <a href="../../../../../../org/apache/hadoop/hbase/protobuf/generated/AuthenticationProtos.WhoAmIRequest.Builder.html" title="class in org.apache.hadoop.hbase.protobuf.generated">AuthenticationProtos.WhoAmIRequest.Builder</a></dd> </dl> <dl> <dt>Enclosing class:</dt> <dd><a href="../../../../../../org/apache/hadoop/hbase/protobuf/generated/AuthenticationProtos.html" title="class in org.apache.hadoop.hbase.protobuf.generated">AuthenticationProtos</a></dd> </dl> <hr> <br> <pre>public static interface <span class="strong">AuthenticationProtos.WhoAmIRequestOrBuilder</span> extends com.google.protobuf.MessageOrBuilder</pre> </li> </ul> </div> <div class="summary"> <ul class="blockList"> <li class="blockList"> <!-- ========== METHOD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="method_summary"> <!-- --> </a> <h3>Method Summary</h3> <ul class="blockList"> <li class="blockList"><a name="methods_inherited_from_class_com.google.protobuf.MessageOrBuilder"> <!-- --> </a> <h3>Methods inherited from interface&nbsp;com.google.protobuf.MessageOrBuilder</h3> <code>findInitializationErrors, getAllFields, getDefaultInstanceForType, getDescriptorForType, getField, getInitializationErrorString, getRepeatedField, getRepeatedFieldCount, getUnknownFields, hasField</code></li> </ul> <ul class="blockList"> <li class="blockList"><a name="methods_inherited_from_class_com.google.protobuf.MessageLiteOrBuilder"> <!-- --> </a> <h3>Methods inherited from interface&nbsp;com.google.protobuf.MessageLiteOrBuilder</h3> <code>isInitialized</code></li> </ul> </li> </ul> </li> </ul> </div> </div> <!-- ========= END OF CLASS DATA ========= --> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="class-use/AuthenticationProtos.WhoAmIRequestOrBuilder.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../../../org/apache/hadoop/hbase/protobuf/generated/AuthenticationProtos.WhoAmIRequest.Builder.html" title="class in org.apache.hadoop.hbase.protobuf.generated"><span class="strong">Prev Class</span></a></li> <li><a href="../../../../../../org/apache/hadoop/hbase/protobuf/generated/AuthenticationProtos.WhoAmIResponse.html" title="class in org.apache.hadoop.hbase.protobuf.generated"><span class="strong">Next Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?org/apache/hadoop/hbase/protobuf/generated/AuthenticationProtos.WhoAmIRequestOrBuilder.html" target="_top">Frames</a></li> <li><a href="AuthenticationProtos.WhoAmIRequestOrBuilder.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li>Method</li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li>Method</li> </ul> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small>Copyright &#169; 2014 <a href="http://www.apache.org/">The Apache Software Foundation</a>. All rights reserved.</small></p> </body> </html>
lshain/hbase-0.98.6-hadoop2
docs/devapidocs/org/apache/hadoop/hbase/protobuf/generated/AuthenticationProtos.WhoAmIRequestOrBuilder.html
HTML
apache-2.0
8,113
// LUCENENET specific - excluding this class in favor of DirectoryNotFoundException, // although that means we need to catch DirectoryNotFoundException everywhere that // FileNotFoundException is being caught (because it is a superclass) to be sure we have the same behavior. //using System; //using System.IO; //namespace YAF.Lucene.Net.Store //{ // /* // * Licensed to the Apache Software Foundation (ASF) under one or more // * contributor license agreements. See the NOTICE file distributed with // * this work for additional information regarding copyright ownership. // * The ASF licenses this file to You under the Apache License, Version 2.0 // * (the "License"); you may not use this file except in compliance with // * the License. You may obtain a copy of the License at // * // * http://www.apache.org/licenses/LICENSE-2.0 // * // * Unless required by applicable law or agreed to in writing, software // * distributed under the License is distributed on an "AS IS" BASIS, // * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // * See the License for the specific language governing permissions and // * limitations under the License. // */ // /// <summary> // /// This exception is thrown when you try to list a // /// non-existent directory. // /// </summary> // // LUCENENET: It is no longer good practice to use binary serialization. // // See: https://github.com/dotnet/corefx/issues/23584#issuecomment-325724568 //#if FEATURE_SERIALIZABLE_EXCEPTIONS // [Serializable] //#endif // public class NoSuchDirectoryException : FileNotFoundException // { // public NoSuchDirectoryException(string message) // : base(message) // { // } // } //}
YAFNET/YAFNET
yafsrc/Lucene.Net/Lucene.Net/Store/NoSuchDirectoryException.cs
C#
apache-2.0
1,813
# Caperonia hystrix Pax & K.Hoffm. SPECIES #### Status SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Malpighiales/Euphorbiaceae/Caperonia/Caperonia linearifolia/ Syn. Caperonia hystrix/README.md
Markdown
apache-2.0
189
/* * Copyright 2017 Red Hat, Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.kie.workbench.common.screens.library.client.screens.assets; import elemental2.dom.HTMLElement; import org.guvnor.common.services.project.model.WorkspaceProject; import org.jboss.errai.ui.client.local.spi.TranslationService; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.kie.workbench.common.screens.library.api.LibraryService; import org.kie.workbench.common.screens.library.client.util.LibraryPlaces; import org.kie.workbench.common.services.shared.project.KieModule; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import org.uberfire.ext.widgets.common.client.common.BusyIndicatorView; import org.uberfire.mocks.CallerMock; import static org.mockito.Mockito.any; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.reset; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @RunWith(MockitoJUnitRunner.class) public class AssetsScreenTest { private AssetsScreen assetsScreen; @Mock private AssetsScreen.View view; @Mock private LibraryPlaces libraryPlaces; @Mock private EmptyAssetsScreen emptyAssetsScreen; @Mock private PopulatedAssetsScreen populatedAssetsScreen; @Mock private InvalidProjectScreen invalidProjectScreen; @Mock private TranslationService ts; @Mock private BusyIndicatorView busyIndicatorView; @Mock private LibraryService libraryService; private WorkspaceProject workspaceProject; @Before public void setUp() { workspaceProject = mock(WorkspaceProject.class); doReturn(mock(KieModule.class)).when(workspaceProject).getMainModule(); when(libraryPlaces.getActiveWorkspaceContext()).thenReturn(workspaceProject); EmptyAssetsView emptyView = mock(EmptyAssetsView.class); PopulatedAssetsView populatedView = mock(PopulatedAssetsView.class); InvalidProjectView invalidProjectView = mock(InvalidProjectView.class); HTMLElement emptyElement = mock(HTMLElement.class); HTMLElement populatedElement = mock(HTMLElement.class); HTMLElement invalidProjectElement = mock(HTMLElement.class); when(emptyAssetsScreen.getView()).thenReturn(emptyView); when(emptyView.getElement()).thenReturn(emptyElement); when(populatedAssetsScreen.getView()).thenReturn(populatedView); when(populatedView.getElement()).thenReturn(populatedElement); when(invalidProjectScreen.getView()).thenReturn(invalidProjectView); when(invalidProjectView.getElement()).thenReturn(invalidProjectElement); this.assetsScreen = new AssetsScreen(view, libraryPlaces, emptyAssetsScreen, populatedAssetsScreen, invalidProjectScreen, ts, busyIndicatorView, new CallerMock<>(libraryService)); } @Test public void testShowEmptyScreenAssets() { when(libraryService.hasAssets(any(WorkspaceProject.class))).thenReturn(false); this.assetsScreen.init(); verify(emptyAssetsScreen, times(1)).getView(); verify(populatedAssetsScreen, never()).getView(); verify(view).setContent(emptyAssetsScreen.getView().getElement()); } @Test public void testShowPopulatedScreenAssets() { when(libraryService.hasAssets(any(WorkspaceProject.class))).thenReturn(true); this.assetsScreen.init(); verify(emptyAssetsScreen, never()).getView(); verify(populatedAssetsScreen, times(1)).getView(); verify(view).setContent(populatedAssetsScreen.getView().getElement()); } @Test public void testSetContentNotCalledWhenAlreadyDisplayed() throws Exception { try { testShowEmptyScreenAssets(); } catch (AssertionError ae) { throw new AssertionError("Precondition failed. Could not set empty asset screen.", ae); } HTMLElement emptyElement = emptyAssetsScreen.getView().getElement(); emptyElement.parentNode = mock(HTMLElement.class); reset(view); assetsScreen.init(); verify(view, never()).setContent(any()); } @Test public void testInvalidProject() throws Exception { reset(workspaceProject); doReturn(null).when(workspaceProject).getMainModule(); assetsScreen.init(); verify(view).setContent(invalidProjectScreen.getView().getElement()); verify(libraryService, never()).hasAssets(any(WorkspaceProject.class)); } }
etirelli/kie-wb-common
kie-wb-common-screens/kie-wb-common-library/kie-wb-common-library-client/src/test/java/org/kie/workbench/common/screens/library/client/screens/assets/AssetsScreenTest.java
Java
apache-2.0
5,601
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using System.Xml.Linq; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.ExtractMethod; using Microsoft.CodeAnalysis.Editor.CSharp.ExtractMethod; using Microsoft.CodeAnalysis.Editor.Implementation.Interactive; using Microsoft.CodeAnalysis.Editor.UnitTests; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.ExtractMethod; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Text.Operations; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ExtractMethod { public partial class ExtractMethodTests : ExtractMethodBase { [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod1() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test(string[] args) { [|int i; i = 10;|] } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test(string[] args) { NewMethod(); } private static void NewMethod() { int i = 10; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod2() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test(string[] args) { [|int i = 10; int i2 = 10;|] } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test(string[] args) { NewMethod(); } private static void NewMethod() { int i = 10; int i2 = 10; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod3() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test(string[] args) { int i = 10; [|int i2 = i;|] } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test(string[] args) { int i = 10; NewMethod(i); } private static void NewMethod(int i) { int i2 = i; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod4() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test(string[] args) { int i = 10; int i2 = i; [|i2 += i;|] } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test(string[] args) { int i = 10; int i2 = i; i2 = NewMethod(i); } private static int NewMethod(int i, int i2) { i2 += i; return i2; } }"; // compoundaction not supported yet. await TestExtractMethodAsync(code, expected, temporaryFailing: true); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod5() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test(string[] args) { int i = 10; int i2 = i; [|i2 = i;|] } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test(string[] args) { int i = 10; int i2 = i; NewMethod(i); } private static void NewMethod(int i) { int i2 = i; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod6() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { int field; void Test(string[] args) { int i = 10; [|field = i;|] } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { int field; void Test(string[] args) { int i = 10; NewMethod(i); } private void NewMethod(int i) { field = i; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod7() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test(string[] args) { string [] a = null; [|Test(a);|] } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test(string[] args) { string[] a = null; NewMethod(a); } private void NewMethod(string[] a) { Test(a); } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod8() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { static void Test(string[] args) { string [] a = null; [|Test(a);|] } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { static void Test(string[] args) { string[] a = null; NewMethod(a); } private static void NewMethod(string[] a) { Test(a); } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod9() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test(string[] args) { int i; string s; [|i = 10; s = args[0] + i.ToString();|] } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test(string[] args) { NewMethod(args); } private static void NewMethod(string[] args) { int i; string s; i = 10; s = args[0] + i.ToString(); } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod10() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test(string[] args) { [|int i; i = 10; string s; s = args[0] + i.ToString();|] Console.WriteLine(s); } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test(string[] args) { string s = NewMethod(args); Console.WriteLine(s); } private static string NewMethod(string[] args) { int i = 10; string s; s = args[0] + i.ToString(); return s; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod11() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test(string[] args) { [|int i; int i2 = 10;|] i = 10; } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test(string[] args) { int i; NewMethod(); i = 10; } private static void NewMethod() { int i2 = 10; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod11_1() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test(string[] args) { [|int i; int i2 = 10;|] } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test(string[] args) { NewMethod(); } private static void NewMethod() { int i; int i2 = 10; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod12() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test(string[] args) { int i = 10; [|i = i + 1;|] Console.WriteLine(i); } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test(string[] args) { int i = 10; i = NewMethod(i); Console.WriteLine(i); } private static int NewMethod(int i) { i = i + 1; return i; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ControlVariableInForeachStatement() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test(string[] args) { foreach (var s in args) { [|Console.WriteLine(s);|] } } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test(string[] args) { foreach (var s in args) { NewMethod(s); } } private static void NewMethod(string s) { Console.WriteLine(s); } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod14() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test(string[] args) { for(var i = 1; i < 10; i++) { [|Console.WriteLine(i);|] } } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test(string[] args) { for (var i = 1; i < 10; i++) { NewMethod(i); } } private static void NewMethod(int i) { Console.WriteLine(i); } }"; // var in for loop doesn't get bound yet await TestExtractMethodAsync(code, expected, temporaryFailing: true); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod15() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test(string[] args) { [|int s = 10, i = 1; int b = s + i;|] System.Console.WriteLine(s); System.Console.WriteLine(i); } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test(string[] args) { int s, i; NewMethod(out s, out i); System.Console.WriteLine(s); System.Console.WriteLine(i); } private static void NewMethod(out int s, out int i) { s = 10; i = 1; int b = s + i; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod16() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test(string[] args) { [|int i = 1;|] System.Console.WriteLine(i); } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test(string[] args) { int i = NewMethod(); System.Console.WriteLine(i); } private static int NewMethod() { return 1; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(538932, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538932")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod17() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test<T>(out T t) where T : class, new() { [|T t1; Test(out t1); t = t1;|] System.Console.WriteLine(t1.ToString()); } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test<T>(out T t) where T : class, new() { T t1; NewMethod(out t, out t1); System.Console.WriteLine(t1.ToString()); } private void NewMethod<T>(out T t, out T t1) where T : class, new() { Test(out t1); t = t1; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod18() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test<T>(out T t) where T : class, new() { [|T t1 = GetValue(out t);|] System.Console.WriteLine(t1.ToString()); } private T GetValue<T>(out T t) where T : class, new() { return t = new T(); } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test<T>(out T t) where T : class, new() { T t1; NewMethod(out t, out t1); System.Console.WriteLine(t1.ToString()); } private void NewMethod<T>(out T t, out T t1) where T : class, new() { t1 = GetValue(out t); } private T GetValue<T>(out T t) where T : class, new() { return t = new T(); } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod19() { var code = @"using System; using System.Collections.Generic; using System.Linq; unsafe class Program { void Test() { [|int i = 1;|] } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; unsafe class Program { void Test() { NewMethod(); } private static void NewMethod() { int i = 1; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod20() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { unsafe void Test() { [|int i = 1;|] } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { unsafe void Test() { NewMethod(); } private static unsafe void NewMethod() { int i = 1; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(542677, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542677")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod21() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test() { unsafe { [|int i = 1;|] } } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test() { unsafe { NewMethod(); } } private static unsafe void NewMethod() { int i = 1; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod22() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test() { int i; [|int b = 10; if (b < 10) { i = 5; }|] i = 6; Console.WriteLine(i); } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test() { int i; NewMethod(i); i = 6; Console.WriteLine(i); } private static void NewMethod(int i) { int b = 10; if (b < 10) { i = 5; } } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod23() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { static void Main(string[] args) { if (true) [|Console.WriteLine(args[0].ToString());|] } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { static void Main(string[] args) { if (true) NewMethod(args); } private static void NewMethod(string[] args) { Console.WriteLine(args[0].ToString()); } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod24() { var code = @"using System; class Program { static void Main(string[] args) { int y = [|int.Parse(args[0].ToString())|]; } }"; var expected = @"using System; class Program { static void Main(string[] args) { int y = GetY(args); } private static int GetY(string[] args) { return int.Parse(args[0].ToString()); } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod25() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { static void Main(string[] args) { if (([|new int[] { 1, 2, 3 }|]).Any()) { return; } } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { static void Main(string[] args) { if ((NewMethod()).Any()) { return; } } private static int[] NewMethod() { return new int[] { 1, 2, 3 }; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod26() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { static void Main(string[] args) { if ([|(new int[] { 1, 2, 3 })|].Any()) { return; } } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { static void Main(string[] args) { if (NewMethod().Any()) { return; } } private static int[] NewMethod() { return (new int[] { 1, 2, 3 }); } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod27() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test() { int i = 1; [|int b = 10; if (b < 10) { i = 5; }|] i = 6; Console.WriteLine(i); } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test() { int i = 1; NewMethod(i); i = 6; Console.WriteLine(i); } private static void NewMethod(int i) { int b = 10; if (b < 10) { i = 5; } } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod28() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { int Test() { [|return 1;|] } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { int Test() { return NewMethod(); } private static int NewMethod() { return 1; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod29() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { int Test() { int i = 0; [|if (i < 0) { return 1; } else { return 0; }|] } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { int Test() { int i = 0; return NewMethod(i); } private static int NewMethod(int i) { if (i < 0) { return 1; } else { return 0; } } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod30() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test(out int i) { [|i = 10;|] } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { void Test(out int i) { i = NewMethod(); } private static int NewMethod() { return 10; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod31() { var code = @"using System; using System.Collections.Generic; using System.Text; class Program { void Test() { StringBuilder builder = new StringBuilder(); [|builder.Append(""Hello""); builder.Append("" From ""); builder.Append("" Roslyn"");|] return builder.ToString(); } }"; var expected = @"using System; using System.Collections.Generic; using System.Text; class Program { void Test() { StringBuilder builder = new StringBuilder(); NewMethod(builder); return builder.ToString(); } private static void NewMethod(StringBuilder builder) { builder.Append(""Hello""); builder.Append("" From ""); builder.Append("" Roslyn""); } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod32() { var code = @"using System; class Program { void Test() { int v = 0; Console.Write([|v|]); } }"; var expected = @"using System; class Program { void Test() { int v = 0; Console.Write(GetV(v)); } private static int GetV(int v) { return v; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(3792, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod33() { var code = @"using System; class Program { void Test() { int v = 0; while (true) { Console.Write([|v++|]); } } }"; var expected = @"using System; class Program { void Test() { int v = 0; while (true) { Console.Write(NewMethod(ref v)); } } private static int NewMethod(ref int v) { return v++; } }"; // this bug has two issues. one is "v" being not in the dataFlowIn and ReadInside collection (hence no method parameter) // and the other is binding not working for "v++" (hence object as return type) await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod34() { var code = @"using System; class Program { static void Main(string[] args) { int x = 1; int y = 2; int z = [|x + y|]; } } "; var expected = @"using System; class Program { static void Main(string[] args) { int x = 1; int y = 2; int z = GetZ(x, y); } private static int GetZ(int x, int y) { return x + y; } } "; await TestExtractMethodAsync(code, expected); } [WorkItem(538239, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538239")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod35() { var code = @"using System; class Program { static void Main(string[] args) { int[] r = [|new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 }|]; } }"; var expected = @"using System; class Program { static void Main(string[] args) { int[] r = GetR(); } private static int[] GetR() { return new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 }; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod36() { var code = @"using System; class Program { static void Main(ref int i) { [|i = 1;|] } }"; var expected = @"using System; class Program { static void Main(ref int i) { i = NewMethod(); } private static int NewMethod() { return 1; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod37() { var code = @"using System; class Program { static void Main(out int i) { [|i = 1;|] } }"; var expected = @"using System; class Program { static void Main(out int i) { i = NewMethod(); } private static int NewMethod() { return 1; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(538231, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538231")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod38() { var code = @"using System; class Program { static void Main(string[] args) { // int v = 0; // while (true) // { // NewMethod(v++); // NewMethod(ReturnVal(v++)); // } int unassigned; // extract // unassigned = ReturnVal(0); [|unassigned = unassigned + 10;|] // read // int newVar = unassigned; // write // unassigned = 0; } }"; var expected = @"using System; class Program { static void Main(string[] args) { // int v = 0; // while (true) // { // NewMethod(v++); // NewMethod(ReturnVal(v++)); // } int unassigned; // extract // unassigned = ReturnVal(0); NewMethod(unassigned); // read // int newVar = unassigned; // write // unassigned = 0; } private static void NewMethod(int unassigned) { unassigned = unassigned + 10; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(538231, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538231")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod39() { var code = @"using System; class Program { static void Main(string[] args) { // int v = 0; // while (true) // { // NewMethod(v++); // NewMethod(ReturnVal(v++)); // } int unassigned; // extract [|// unassigned = ReturnVal(0); unassigned = unassigned + 10; // read|] // int newVar = unassigned; // write // unassigned = 0; } }"; var expected = @"using System; class Program { static void Main(string[] args) { // int v = 0; // while (true) // { // NewMethod(v++); // NewMethod(ReturnVal(v++)); // } int unassigned; // extract NewMethod(unassigned); // int newVar = unassigned; // write // unassigned = 0; } private static void NewMethod(int unassigned) { // unassigned = ReturnVal(0); unassigned = unassigned + 10; // read } }"; // current bottom-up re-writer makes re-attaching trivia half belongs to previous token // and half belongs to next token very hard. // for now, it won't be able to re-associate trivia belongs to next token. await TestExtractMethodAsync(code, expected); } [WorkItem(538303, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538303")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod40() { var code = @"class Program { static void Main(string[] args) { [|int x;|] } }"; await ExpectExtractMethodToFailAsync(code); } [WorkItem(868414, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/868414")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethodWithLeadingTrivia() { // ensure that the extraction doesn't result in trivia moving up a line: // // a //b // NewMethod(); await TestExtractMethodAsync( @"class C { void M() { // a // b [|System.Console.WriteLine();|] } }", @"class C { void M() { // a // b NewMethod(); } private static void NewMethod() { System.Console.WriteLine(); } }"); } [WorkItem(632351, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/632351")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethodFailForTypeInFromClause() { var code = @"class Program { static void Main(string[] args) { var z = from [|T|] x in e; } }"; await ExpectExtractMethodToFailAsync(code); } [WorkItem(632351, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/632351")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethodFailForTypeInFromClause_1() { var code = @"class Program { static void Main(string[] args) { var z = from [|W.T|] x in e; } }"; await ExpectExtractMethodToFailAsync(code); } [WorkItem(538314, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538314")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod41() { var code = @"class Program { static void Main(string[] args) { int x = 10; [|int y; if (x == 10) y = 5;|] Console.WriteLine(y); } }"; var expected = @"class Program { static void Main(string[] args) { int x = 10; int y = NewMethod(x); Console.WriteLine(y); } private static int NewMethod(int x) { int y; if (x == 10) y = 5; return y; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(538327, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538327")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod42() { var code = @"using System; class Program { static void Main(string[] args) { int a, b; [|a = 5; b = 7;|] Console.Write(a + b); } }"; var expected = @"using System; class Program { static void Main(string[] args) { int a, b; NewMethod(out a, out b); Console.Write(a + b); } private static void NewMethod(out int a, out int b) { a = 5; b = 7; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(538327, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538327")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod43() { var code = @"using System; class Program { static void Main(string[] args) { int a, b; [|a = 5; b = 7; int c; int d; int e, f; c = 1; d = 1; e = 1; f = 1;|] Console.Write(a + b); } }"; var expected = @"using System; class Program { static void Main(string[] args) { int a, b; NewMethod(out a, out b); Console.Write(a + b); } private static void NewMethod(out int a, out int b) { a = 5; b = 7; int c; int d; int e, f; c = 1; d = 1; e = 1; f = 1; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(538328, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538328")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod44() { var code = @"using System; class Program { static void Main(string[] args) { int a; //modified in [|a = 1;|] /*data flow out*/ Console.Write(a); } }"; var expected = @"using System; class Program { static void Main(string[] args) { int a; //modified in a = NewMethod(); /*data flow out*/ Console.Write(a); } private static int NewMethod() { return 1; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(538393, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538393")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod45() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { static void Main(string[] args) { /**/[|;|]/**/ } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { static void Main(string[] args) { /**/ NewMethod();/**/ } private static void NewMethod() { ; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(538393, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538393")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod46() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { static void Main() { int x = 1; [|Goo(ref x);|] Console.WriteLine(x); } static void Goo(ref int x) { x = x + 1; } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { static void Main() { int x = 1; x = NewMethod(x); Console.WriteLine(x); } private static int NewMethod(int x) { Goo(ref x); return x; } static void Goo(ref int x) { x = x + 1; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(538399, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538399")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod47() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { static void Main() { int x = 1; [|while (true) Console.WriteLine(x);|] } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { static void Main() { int x = 1; NewMethod(x); } private static void NewMethod(int x) { while (true) Console.WriteLine(x); } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(538401, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538401")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod48() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { static void Main() { int[] x = [|{ 1, 2, 3 }|]; } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { static void Main() { int[] x = GetX(); } private static int[] GetX() { return new int[] { 1, 2, 3 }; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(538405, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538405")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod49() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { static void Goo(int GetX) { int x = [|1|]; } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { static void Goo(int GetX) { int x = GetX1(); } private static int GetX1() { return 1; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethodNormalProperty() { var code = @" class Class { private static string name; public static string Names { get { return ""1""; } set { name = value; } } static void Goo(int i) { string str = [|Class.Names|]; } }"; var expected = @" class Class { private static string name; public static string Names { get { return ""1""; } set { name = value; } } static void Goo(int i) { string str = GetStr(); } private static string GetStr() { return Class.Names; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(538932, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538932")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethodAutoProperty() { var code = @" class Class { public string Name { get; set; } static void Main() { string str = new Class().[|Name|]; } }"; // given span is not an expression // selection validator should take care of this case var expected = @" class Class { public string Name { get; set; } static void Main() { string str = GetStr(); } private static string GetStr() { return new Class().Name; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(538402, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538402")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task BugFix3994() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { static void Main() { byte x = [|1|]; } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { static void Main() { byte x = GetX(); } private static byte GetX() { return 1; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(538404, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538404")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task BugFix3996() { var code = @"class A<T> { class D : A<T> { } class B { } static D.B Goo() { return null; } class C<T2> { static void Bar() { D.B x = [|Goo()|]; } } }"; var expected = @"class A<T> { class D : A<T> { } class B { } static D.B Goo() { return null; } class C<T2> { static void Bar() { D.B x = GetX(); } private static B GetX() { return Goo(); } } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task InsertionPoint() { var code = @"class Test { void Method(string i) { int y2 = [|1|]; } void Method(int i) { } }"; var expected = @"class Test { void Method(string i) { int y2 = GetY2(); } private static int GetY2() { return 1; } void Method(int i) { } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(538980, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538980")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task BugFix4757() { var code = @"class GenericMethod { void Method<T>(T t) { T a; [|a = t;|] } }"; var expected = @"class GenericMethod { void Method<T>(T t) { NewMethod(t); } private static void NewMethod<T>(T t) { T a = t; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(538980, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538980")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task BugFix4757_2() { var code = @"class GenericMethod<T1> { void Method<T>(T t) { T a; T1 b; [|a = t; b = default(T1);|] } }"; var expected = @"class GenericMethod<T1> { void Method<T>(T t) { NewMethod(t); } private static void NewMethod<T>(T t) { T a; T1 b; a = t; b = default(T1); } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(538980, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538980")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task BugFix4757_3() { var code = @"class GenericMethod { void Method<T, T1>(T t) { T1 a1; T a; [|a = t; a1 = default(T);|] } }"; var expected = @"class GenericMethod { void Method<T, T1>(T t) { NewMethod<T, T1>(t); } private static void NewMethod<T, T1>(T t) { T1 a1; T a; a = t; a1 = default(T); } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(538422, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538422")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task BugFix4758() { var code = @"using System; class TestOutParameter { void Method(out int x) { x = 5; Console.Write([|x|]); } }"; var expected = @"using System; class TestOutParameter { void Method(out int x) { x = 5; Console.Write(GetX(x)); } private static int GetX(int x) { return x; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(538422, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538422")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task BugFix4758_2() { var code = @"class TestOutParameter { void Method(out int x) { x = 5; Console.Write([|x|]); } }"; var expected = @"class TestOutParameter { void Method(out int x) { x = 5; Console.Write(GetX(x)); } private static int GetX(int x) { return x; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(538984, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538984")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task BugFix4761() { var code = @"using System; class A { void Method() { System.Func<int, int> a = x => [|x * x|]; } }"; var expected = @"using System; class A { void Method() { System.Func<int, int> a = x => NewMethod(x); } private static int NewMethod(int x) { return x * x; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(538997, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538997")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task BugFix4779() { var code = @"using System; class Program { static void Main() { string s = ""; Func<string> f = [|s|].ToString; } } "; var expected = @"using System; class Program { static void Main() { string s = ""; Func<string> f = GetS(s).ToString; } private static string GetS(string s) { return s; } } "; await TestExtractMethodAsync(code, expected); } [WorkItem(538997, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538997")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task BugFix4779_2() { var code = @"using System; class Program { static void Main() { string s = ""; var f = [|s|].ToString(); } } "; var expected = @"using System; class Program { static void Main() { string s = ""; var f = GetS(s).ToString(); } private static string GetS(string s) { return s; } } "; await TestExtractMethodAsync(code, expected); } [WorkItem(4780, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task BugFix4780() { var code = @"using System; class Program { static void Main() { string s = ""; object f = (Func<string>)[|s.ToString|]; } }"; var expected = @"using System; class Program { static void Main() { string s = ""; object f = (Func<string>)GetToString(s); } private static Func<string> GetToString(string s) { return s.ToString; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(4780, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task BugFix4780_2() { var code = @"using System; class Program { static void Main() { string s = ""; object f = (string)[|s.ToString()|]; } }"; var expected = @"using System; class Program { static void Main() { string s = ""; object f = (string)NewMethod(s); } private static string NewMethod(string s) { return s.ToString(); } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(4782, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task BugFix4782() { var code = @"class A<T> { class D : A<T[]> { } class B { } class C<T> { static void Goo<T>(T a) { T t = [|default(T)|]; } } }"; var expected = @"class A<T> { class D : A<T[]> { } class B { } class C<T> { static void Goo<T>(T a) { T t = GetT<T>(); } private static T GetT<T>() { return default(T); } } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(4782, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task BugFix4782_2() { var code = @"class A<T> { class D : A<T[]> { } class B { } class C<T> { static void Goo() { D.B x = [|new D.B()|]; } } }"; await ExpectExtractMethodToFailAsync(code); } [WorkItem(4791, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task BugFix4791() { var code = @"class Program { delegate int Func(int a); static void Main(string[] args) { Func v = (int a) => [|a|]; } }"; var expected = @"class Program { delegate int Func(int a); static void Main(string[] args) { Func v = (int a) => GetA(a); } private static int GetA(int a) { return a; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(539019, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539019")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task BugFix4809() { var code = @"class Program { public Program() { [|int x = 2;|] } }"; var expected = @"class Program { public Program() { NewMethod(); } private static void NewMethod() { int x = 2; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(539029, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539029")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task BugFix4813() { var code = @"using System; class Program { public Program() { object o = [|new Program()|]; } }"; var expected = @"using System; class Program { public Program() { object o = GetO(); } private static Program GetO() { return new Program(); } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(538425, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538425")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task BugFix4031() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { static void Main() { bool x = true, y = true, z = true; if (x) while (y) { } else [|while (z) { }|] } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { static void Main() { bool x = true, y = true, z = true; if (x) while (y) { } else NewMethod(z); } private static void NewMethod(bool z) { while (z) { } } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(527499, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527499")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task BugFix3992() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { static void Main() { int x = 1; [|while (false) Console.WriteLine(x);|] } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { static void Main() { int x = 1; NewMethod(x); } private static void NewMethod(int x) { while (false) Console.WriteLine(x); } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(539029, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539029")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task BugFix4823() { var code = @"class Program { private double area = 1.0; public double Area { get { return area; } } public override string ToString() { return string.Format(""{0:F2}"", [|Area|]); } }"; var expected = @"class Program { private double area = 1.0; public double Area { get { return area; } } public override string ToString() { return string.Format(""{0:F2}"", GetArea()); } private double GetArea() { return Area; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(538985, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538985")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task BugFix4762() { var code = @"class Program { static void Main(string[] args) { //comments [|int x = 2;|] } } "; var expected = @"class Program { static void Main(string[] args) { //comments NewMethod(); } private static void NewMethod() { int x = 2; } } "; await TestExtractMethodAsync(code, expected); } [WorkItem(538966, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538966")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task BugFix4744() { var code = @"class Program { static void Main(string[] args) { [|int x = 2; //comments|] } } "; var expected = @"class Program { static void Main(string[] args) { NewMethod(); } private static void NewMethod() { int x = 2; //comments } } "; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoNoNoNoNoYesNoNo() { var code = @"using System; class Program { void Test1() { int i; [| if (int.Parse(""1"") > 0) { i = 10; } |] } }"; var expected = @"using System; class Program { void Test1() { int i; NewMethod(i); } private static void NewMethod(int i) { if (int.Parse(""1"") > 0) { i = 10; } } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoNoNoNoNoYesNoYes() { var code = @"using System; class Program { void Test2() { int i = 0; [| if (int.Parse(""1"") > 0) { i = 10; } |] } }"; var expected = @"using System; class Program { void Test2() { int i = 0; NewMethod(i); } private static void NewMethod(int i) { if (int.Parse(""1"") > 0) { i = 10; } } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoNoNoNoNoYesYesNo() { var code = @"using System; class Program { void Test3() { int i; while (i > 10) ; [| if (int.Parse(""1"") > 0) { i = 10; } |] } }"; var expected = @"using System; class Program { void Test3() { int i; while (i > 10) ; NewMethod(i); } private static void NewMethod(int i) { if (int.Parse(""1"") > 0) { i = 10; } } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoNoNoNoNoYesYesYes() { var code = @"using System; class Program { void Test4() { int i = 10; while (i > 10) ; [| if (int.Parse(""1"") > 0) { i = 10; } |] } }"; var expected = @"using System; class Program { void Test4() { int i = 10; while (i > 10) ; NewMethod(i); } private static void NewMethod(int i) { if (int.Parse(""1"") > 0) { i = 10; } } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoNoNoNoYesYesNoNo() { var code = @"using System; class Program { void Test4_1() { int i; [| if (int.Parse(""1"") > 0) { i = 10; Console.WriteLine(i); } |] } }"; var expected = @"using System; class Program { void Test4_1() { NewMethod(); } private static void NewMethod() { int i; if (int.Parse(""1"") > 0) { i = 10; Console.WriteLine(i); } } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoNoNoNoYesYesNoYes() { var code = @"using System; class Program { void Test4_2() { int i = 10; [| if (int.Parse(""1"") > 0) { i = 10; Console.WriteLine(i); } |] } }"; var expected = @"using System; class Program { void Test4_2() { int i = 10; NewMethod(i); } private static void NewMethod(int i) { if (int.Parse(""1"") > 0) { i = 10; Console.WriteLine(i); } } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoNoNoNoYesYesYesNo() { var code = @"using System; class Program { void Test4_3() { int i; Console.WriteLine(i); [| if (int.Parse(""1"") > 0) { i = 10; Console.WriteLine(i); } |] } }"; var expected = @"using System; class Program { void Test4_3() { int i; Console.WriteLine(i); NewMethod(); } private static void NewMethod() { int i; if (int.Parse(""1"") > 0) { i = 10; Console.WriteLine(i); } } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoNoNoNoYesYesYesYes() { var code = @"using System; class Program { void Test4_4() { int i = 10; Console.WriteLine(i); [| if (int.Parse(""1"") > 0) { i = 10; Console.WriteLine(i); } |] } }"; var expected = @"using System; class Program { void Test4_4() { int i = 10; Console.WriteLine(i); NewMethod(i); } private static void NewMethod(int i) { if (int.Parse(""1"") > 0) { i = 10; Console.WriteLine(i); } } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoNoNoYesNoNoNoNo() { var code = @"using System; class Program { void Test5() { [| int i; |] } }"; await ExpectExtractMethodToFailAsync(code); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoNoNoYesNoNoNoYes() { var code = @"using System; class Program { void Test6() { [| int i; |] i = 1; } }"; await ExpectExtractMethodToFailAsync(code); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoNoNoYesNoYesNoNo() { var code = @"using System; class Program { void Test7() { [| int i; if (int.Parse(""1"") > 0) { i = 10; } |] } }"; var expected = @"using System; class Program { void Test7() { NewMethod(); } private static void NewMethod() { int i; if (int.Parse(""1"") > 0) { i = 10; } } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoNoNoYesNoYesNoYes() { var code = @"using System; class Program { void Test8() { [| int i; if (int.Parse(""1"") > 0) { i = 10; } |] i = 2; } }"; var expected = @"using System; class Program { void Test8() { int i; NewMethod(); i = 2; } private static void NewMethod() { int i; if (int.Parse(""1"") > 0) { i = 10; } } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoNoNoYesYesNoNoNo() { var code = @"using System; class Program { void Test9() { [| int i; Console.WriteLine(i); |] } }"; var expected = @"using System; class Program { void Test9() { NewMethod(); } private static void NewMethod() { int i; Console.WriteLine(i); } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoNoNoYesYesNoNoYes() { var code = @"using System; class Program { void Test10() { [| int i; Console.WriteLine(i); |] i = 10; } }"; var expected = @"using System; class Program { void Test10() { int i; NewMethod(); i = 10; } private static void NewMethod() { int i; Console.WriteLine(i); } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoNoNoYesYesYesNoNo() { var code = @"using System; class Program { void Test11() { [| int i; if (int.Parse(""1"") > 0) { i = 10; } Console.WriteLine(i); |] } }"; var expected = @"using System; class Program { void Test11() { NewMethod(); } private static void NewMethod() { int i; if (int.Parse(""1"") > 0) { i = 10; } Console.WriteLine(i); } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoNoNoYesYesYesNoYes() { var code = @"using System; class Program { void Test12() { [| int i; if (int.Parse(""1"") > 0) { i = 10; } Console.WriteLine(i); |] i = 10; } }"; var expected = @"using System; class Program { void Test12() { int i; NewMethod(); i = 10; } private static void NewMethod() { int i; if (int.Parse(""1"") > 0) { i = 10; } Console.WriteLine(i); } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoNoYesNoNoYesNoNo() { var code = @"using System; class Program { void Test13() { int i; [| i = 10; |] } }"; var expected = @"using System; class Program { void Test13() { NewMethod(); } private static void NewMethod() { int i = 10; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoNoYesNoNoYesNoYes() { var code = @"using System; class Program { void Test14() { int i; [| i = 10; |] i = 1; } }"; var expected = @"using System; class Program { void Test14() { int i; NewMethod(); i = 1; } private static void NewMethod() { int i = 10; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoNoYesNoNoYesYesNo() { var code = @"using System; class Program { void Test15() { int i; Console.WriteLine(i); [| i = 10; |] } }"; var expected = @"using System; class Program { void Test15() { int i; Console.WriteLine(i); NewMethod(); } private static void NewMethod() { int i = 10; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoNoYesNoNoYesYesYes() { var code = @"using System; class Program { void Test16() { int i; [| i = 10; |] i = 10; Console.WriteLine(i); } }"; var expected = @"using System; class Program { void Test16() { int i; NewMethod(); i = 10; Console.WriteLine(i); } private static void NewMethod() { int i = 10; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoNoYesNoYesYesNoNo() { var code = @"using System; class Program { void Test16_1() { int i; [| i = 10; Console.WriteLine(i); |] } }"; var expected = @"using System; class Program { void Test16_1() { NewMethod(); } private static void NewMethod() { int i = 10; Console.WriteLine(i); } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoNoYesNoYesYesNoYes() { var code = @"using System; class Program { void Test16_2() { int i = 10; [| i = 10; Console.WriteLine(i); |] } }"; var expected = @"using System; class Program { void Test16_2() { int i = 10; NewMethod(); } private static void NewMethod() { int i = 10; Console.WriteLine(i); } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoNoYesNoYesYesYesNo() { var code = @"using System; class Program { void Test16_3() { int i; Console.WriteLine(i); [| i = 10; Console.WriteLine(i); |] } }"; var expected = @"using System; class Program { void Test16_3() { int i; Console.WriteLine(i); NewMethod(); } private static void NewMethod() { int i = 10; Console.WriteLine(i); } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoNoYesNoYesYesYesYes() { var code = @"using System; class Program { void Test16_4() { int i = 10; Console.WriteLine(i); [| i = 10; Console.WriteLine(i); |] } }"; var expected = @"using System; class Program { void Test16_4() { int i = 10; Console.WriteLine(i); NewMethod(); } private static void NewMethod() { int i = 10; Console.WriteLine(i); } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoNoYesYesNoYesNoNo() { var code = @"using System; class Program { void Test17() { [| int i = 10; |] } }"; var expected = @"using System; class Program { void Test17() { NewMethod(); } private static void NewMethod() { int i = 10; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoNoYesYesNoYesNoYes() { var code = @"using System; class Program { void Test18() { [| int i = 10; |] i = 10; } }"; var expected = @"using System; class Program { void Test18() { int i; NewMethod(); i = 10; } private static void NewMethod() { int i = 10; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoNoYesYesYesYesNoNo() { var code = @"using System; class Program { void Test19() { [| int i = 10; Console.WriteLine(i); |] } }"; var expected = @"using System; class Program { void Test19() { NewMethod(); } private static void NewMethod() { int i = 10; Console.WriteLine(i); } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoNoYesYesYesYesNoYes() { var code = @"using System; class Program { void Test20() { [| int i = 10; Console.WriteLine(i); |] i = 10; } }"; var expected = @"using System; class Program { void Test20() { int i; NewMethod(); i = 10; } private static void NewMethod() { int i = 10; Console.WriteLine(i); } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoYesNoNoNoYesYesNo() { var code = @"using System; class Program { void Test21() { int i; [| if (int.Parse(""1"") > 10) { i = 1; } |] Console.WriteLine(i); } }"; var expected = @"using System; class Program { void Test21() { int i; i = NewMethod(i); Console.WriteLine(i); } private static int NewMethod(int i) { if (int.Parse(""1"") > 10) { i = 1; } return i; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoYesNoNoNoYesYesYes() { var code = @"using System; class Program { void Test22() { int i = 10; [| if (int.Parse(""1"") > 10) { i = 1; } |] Console.WriteLine(i); } }"; var expected = @"using System; class Program { void Test22() { int i = 10; i = NewMethod(i); Console.WriteLine(i); } private static int NewMethod(int i) { if (int.Parse(""1"") > 10) { i = 1; } return i; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoYesNoNoYesYesYesNo() { var code = @"using System; class Program { void Test22_1() { int i; [| if (int.Parse(""1"") > 10) { i = 1; Console.WriteLine(i); } |] Console.WriteLine(i); } }"; var expected = @"using System; class Program { void Test22_1() { int i; i = NewMethod(i); Console.WriteLine(i); } private static int NewMethod(int i) { if (int.Parse(""1"") > 10) { i = 1; Console.WriteLine(i); } return i; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoYesNoNoYesYesYesYes() { var code = @"using System; class Program { void Test22_2() { int i = 10; [| if (int.Parse(""1"") > 10) { i = 1; Console.WriteLine(i); } |] Console.WriteLine(i); } }"; var expected = @"using System; class Program { void Test22_2() { int i = 10; i = NewMethod(i); Console.WriteLine(i); } private static int NewMethod(int i) { if (int.Parse(""1"") > 10) { i = 1; Console.WriteLine(i); } return i; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoYesNoYesNoNoYesNo() { var code = @"using System; class Program { void Test23() { [| int i; |] Console.WriteLine(i); } }"; await ExpectExtractMethodToFailAsync(code); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoYesNoYesNoNoYesYes() { var code = @"using System; class Program { void Test24() { [| int i; |] Console.WriteLine(i); i = 10; } }"; await ExpectExtractMethodToFailAsync(code); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoYesNoYesNoYesYesNo() { var code = @"using System; class Program { void Test25() { [| int i; if (int.Parse(""1"") > 9) { i = 10; } |] Console.WriteLine(i); } }"; var expected = @"using System; class Program { void Test25() { int i = NewMethod(); Console.WriteLine(i); } private static int NewMethod() { int i; if (int.Parse(""1"") > 9) { i = 10; } return i; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoYesNoYesNoYesYesYes() { var code = @"using System; class Program { void Test26() { [| int i; if (int.Parse(""1"") > 9) { i = 10; } |] Console.WriteLine(i); i = 10; } }"; var expected = @"using System; class Program { void Test26() { int i = NewMethod(); Console.WriteLine(i); i = 10; } private static int NewMethod() { int i; if (int.Parse(""1"") > 9) { i = 10; } return i; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoYesNoYesYesNoYesNo() { var code = @"using System; class Program { void Test27() { [| int i; Console.WriteLine(i); |] Console.WriteLine(i); } }"; var expected = @"using System; class Program { void Test27() { int i = NewMethod(); Console.WriteLine(i); } private static int NewMethod() { int i; Console.WriteLine(i); return i; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoYesNoYesYesNoYesYes() { var code = @"using System; class Program { void Test28() { [| int i; Console.WriteLine(i); |] Console.WriteLine(i); i = 10; } }"; var expected = @"using System; class Program { void Test28() { int i = NewMethod(); Console.WriteLine(i); i = 10; } private static int NewMethod() { int i; Console.WriteLine(i); return i; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoYesNoYesYesYesYesNo() { var code = @"using System; class Program { void Test29() { [| int i; if (int.Parse(""1"") > 0) { i = 10; } Console.WriteLine(i); |] Console.WriteLine(i); } }"; var expected = @"using System; class Program { void Test29() { int i = NewMethod(); Console.WriteLine(i); } private static int NewMethod() { int i; if (int.Parse(""1"") > 0) { i = 10; } Console.WriteLine(i); return i; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoYesNoYesYesYesYesYes() { var code = @"using System; class Program { void Test30() { [| int i; if (int.Parse(""1"") > 0) { i = 10; } Console.WriteLine(i); |] Console.WriteLine(i); i = 10; } }"; var expected = @"using System; class Program { void Test30() { int i = NewMethod(); Console.WriteLine(i); i = 10; } private static int NewMethod() { int i; if (int.Parse(""1"") > 0) { i = 10; } Console.WriteLine(i); return i; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoYesYesNoNoYesYesNo() { var code = @"using System; class Program { void Test31() { int i; [| i = 10; |] Console.WriteLine(i); } }"; var expected = @"using System; class Program { void Test31() { int i; i = NewMethod(); Console.WriteLine(i); } private static int NewMethod() { return 10; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoYesYesNoNoYesYesYes() { var code = @"using System; class Program { void Test32() { int i; [| i = 10; |] Console.WriteLine(i); i = 10; } }"; var expected = @"using System; class Program { void Test32() { int i; i = NewMethod(); Console.WriteLine(i); i = 10; } private static int NewMethod() { return 10; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoYesYesNoYesYesYesNo() { var code = @"using System; class Program { void Test32_1() { int i; [| i = 10; Console.WriteLine(i); |] Console.WriteLine(i); } }"; var expected = @"using System; class Program { void Test32_1() { int i; i = NewMethod(); Console.WriteLine(i); } private static int NewMethod() { int i = 10; Console.WriteLine(i); return i; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoYesYesNoYesYesYesYes() { var code = @"using System; class Program { void Test32_2() { int i = 10; [| i = 10; Console.WriteLine(i); |] Console.WriteLine(i); } }"; var expected = @"using System; class Program { void Test32_2() { int i = 10; i = NewMethod(); Console.WriteLine(i); } private static int NewMethod() { int i = 10; Console.WriteLine(i); return i; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoYesYesYesNoYesYesNo() { var code = @"using System; class Program { void Test33() { [| int i = 10; |] Console.WriteLine(i); } }"; var expected = @"using System; class Program { void Test33() { int i = NewMethod(); Console.WriteLine(i); } private static int NewMethod() { return 10; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoYesYesYesNoYesYesYes() { var code = @"using System; class Program { void Test34() { [| int i = 10; |] Console.WriteLine(i); i = 10; } }"; var expected = @"using System; class Program { void Test34() { int i = NewMethod(); Console.WriteLine(i); i = 10; } private static int NewMethod() { return 10; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoYesYesYesYesYesYesNo() { var code = @"using System; class Program { void Test35() { [| int i = 10; Console.WriteLine(i); |] Console.WriteLine(i); } }"; var expected = @"using System; class Program { void Test35() { int i = NewMethod(); Console.WriteLine(i); } private static int NewMethod() { int i = 10; Console.WriteLine(i); return i; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_NoYesYesYesYesYesYesYes() { var code = @"using System; class Program { void Test36() { [| int i = 10; Console.WriteLine(i); |] Console.WriteLine(i); i = 10; } }"; var expected = @"using System; class Program { void Test36() { int i = NewMethod(); Console.WriteLine(i); i = 10; } private static int NewMethod() { int i = 10; Console.WriteLine(i); return i; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_YesNoNoNoYesNoNoNo() { var code = @"using System; class Program { void Test37() { int i; [| Console.WriteLine(i); |] } }"; var expected = @"using System; class Program { void Test37() { int i; NewMethod(i); } private static void NewMethod(int i) { Console.WriteLine(i); } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_YesNoNoNoYesNoNoYes() { var code = @"using System; class Program { void Test38() { int i = 10; [| Console.WriteLine(i); |] } }"; var expected = @"using System; class Program { void Test38() { int i = 10; NewMethod(i); } private static void NewMethod(int i) { Console.WriteLine(i); } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_YesNoNoNoYesNoYesNo() { var code = @"using System; class Program { void Test39() { int i; [| Console.WriteLine(i); |] Console.WriteLine(i); } }"; var expected = @"using System; class Program { void Test39() { int i; NewMethod(i); Console.WriteLine(i); } private static void NewMethod(int i) { Console.WriteLine(i); } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_YesNoNoNoYesNoYesYes() { var code = @"using System; class Program { void Test40() { int i = 10; [| Console.WriteLine(i); |] Console.WriteLine(i); } }"; var expected = @"using System; class Program { void Test40() { int i = 10; NewMethod(i); Console.WriteLine(i); } private static void NewMethod(int i) { Console.WriteLine(i); } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_YesNoNoNoYesYesNoNo() { var code = @"using System; class Program { void Test41() { int i; [| Console.WriteLine(i); if (int.Parse(""1"") > 0) { i = 10; } |] } }"; var expected = @"using System; class Program { void Test41() { int i; NewMethod(i); } private static void NewMethod(int i) { Console.WriteLine(i); if (int.Parse(""1"") > 0) { i = 10; } } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_YesNoNoNoYesYesNoYes() { var code = @"using System; class Program { void Test42() { int i = 10; [| Console.WriteLine(i); if (int.Parse(""1"") > 0) { i = 10; } |] } }"; var expected = @"using System; class Program { void Test42() { int i = 10; NewMethod(i); } private static void NewMethod(int i) { Console.WriteLine(i); if (int.Parse(""1"") > 0) { i = 10; } } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_YesNoNoNoYesYesYesNo() { var code = @"using System; class Program { void Test43() { int i; Console.WriteLine(i); [| Console.WriteLine(i); if (int.Parse(""1"") > 0) { i = 10; } |] } }"; var expected = @"using System; class Program { void Test43() { int i; Console.WriteLine(i); NewMethod(i); } private static void NewMethod(int i) { Console.WriteLine(i); if (int.Parse(""1"") > 0) { i = 10; } } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_YesNoNoNoYesYesYesYes() { var code = @"using System; class Program { void Test44() { int i = 10; Console.WriteLine(i); [| Console.WriteLine(i); if (int.Parse(""1"") > 0) { i = 10; } |] } }"; var expected = @"using System; class Program { void Test44() { int i = 10; Console.WriteLine(i); NewMethod(i); } private static void NewMethod(int i) { Console.WriteLine(i); if (int.Parse(""1"") > 0) { i = 10; } } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_YesNoYesNoYesYesNoNo() { var code = @"using System; class Program { void Test45() { int i; [| Console.WriteLine(i); i = 10; |] } }"; var expected = @"using System; class Program { void Test45() { int i; NewMethod(i); } private static void NewMethod(int i) { Console.WriteLine(i); i = 10; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_YesNoYesNoYesYesNoYes() { var code = @"using System; class Program { void Test46() { int i = 10; [| Console.WriteLine(i); i = 10; |] } }"; var expected = @"using System; class Program { void Test46() { int i = 10; NewMethod(i); } private static void NewMethod(int i) { Console.WriteLine(i); i = 10; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_YesNoYesNoYesYesYesNo() { var code = @"using System; class Program { void Test47() { int i; Console.WriteLine(i); [| Console.WriteLine(i); i = 10; |] } }"; var expected = @"using System; class Program { void Test47() { int i; Console.WriteLine(i); NewMethod(i); } private static void NewMethod(int i) { Console.WriteLine(i); i = 10; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_YesNoYesNoYesYesYesYes() { var code = @"using System; class Program { void Test48() { int i = 10; Console.WriteLine(i); [| Console.WriteLine(i); i = 10; |] } }"; var expected = @"using System; class Program { void Test48() { int i = 10; Console.WriteLine(i); NewMethod(i); } private static void NewMethod(int i) { Console.WriteLine(i); i = 10; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_YesYesNoNoYesYesYesNo() { var code = @"using System; class Program { void Test49() { int i; [| Console.WriteLine(i); if (int.Parse(""1"") > 0) { i = 10; } |] Console.WriteLine(i); } }"; var expected = @"using System; class Program { void Test49() { int i; i = NewMethod(i); Console.WriteLine(i); } private static int NewMethod(int i) { Console.WriteLine(i); if (int.Parse(""1"") > 0) { i = 10; } return i; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_YesYesNoNoYesYesYesYes() { var code = @"using System; class Program { void Test50() { int i = 10; [| Console.WriteLine(i); if (int.Parse(""1"") > 0) { i = 10; } |] Console.WriteLine(i); } }"; var expected = @"using System; class Program { void Test50() { int i = 10; i = NewMethod(i); Console.WriteLine(i); } private static int NewMethod(int i) { Console.WriteLine(i); if (int.Parse(""1"") > 0) { i = 10; } return i; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_YesYesYesNoYesYesYesNo() { var code = @"using System; class Program { void Test51() { int i; [| Console.WriteLine(i); i = 10; |] Console.WriteLine(i); } }"; var expected = @"using System; class Program { void Test51() { int i; i = NewMethod(i); Console.WriteLine(i); } private static int NewMethod(int i) { Console.WriteLine(i); i = 10; return i; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task MatrixCase_YesYesYesNoYesYesYesYes() { var code = @"using System; class Program { void Test52() { int i = 10; [| Console.WriteLine(i); i = 10; |] Console.WriteLine(i); } }"; var expected = @"using System; class Program { void Test52() { int i = 10; i = NewMethod(i); Console.WriteLine(i); } private static int NewMethod(int i) { Console.WriteLine(i); i = 10; return i; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(539049, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539049")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethodInProperty1() { var code = @"class C2 { static public int Area { get { return 1; } } } class C3 { public static int Area { get { return [|C2.Area|]; } } } "; var expected = @"class C2 { static public int Area { get { return 1; } } } class C3 { public static int Area { get { return GetArea(); } } private static int GetArea() { return C2.Area; } } "; await TestExtractMethodAsync(code, expected); } [WorkItem(539049, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539049")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethodInProperty2() { var code = @"class C3 { public static int Area { get { [|int i = 10; return i;|] } } } "; var expected = @"class C3 { public static int Area { get { return NewMethod(); } } private static int NewMethod() { return 10; } } "; await TestExtractMethodAsync(code, expected); } [WorkItem(539049, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539049")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethodInProperty3() { var code = @"class C3 { public static int Area { set { [|int i = value;|] } } } "; var expected = @"class C3 { public static int Area { set { NewMethod(value); } } private static void NewMethod(int value) { int i = value; } } "; await TestExtractMethodAsync(code, expected); } [WorkItem(539029, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539029")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethodProperty() { var code = @"class Program { private double area = 1.0; public double Area { get { return area; } } public override string ToString() { return string.Format(""{0:F2}"", [|Area|]); } } "; var expected = @"class Program { private double area = 1.0; public double Area { get { return area; } } public override string ToString() { return string.Format(""{0:F2}"", GetArea()); } private double GetArea() { return Area; } } "; await TestExtractMethodAsync(code, expected); } [WorkItem(539196, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539196")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethodWithDeclareOneMoreVariablesInSameLineBeUsedAfter() { var code = @"class C { void M() { [|int x, y = 1;|] x = 4; Console.Write(x + y); } }"; var expected = @"class C { void M() { int x; int y = NewMethod(); x = 4; Console.Write(x + y); } private static int NewMethod() { return 1; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(539196, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539196")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethodWithDeclareOneMoreVariablesInSameLineNotBeUsedAfter() { var code = @"class C { void M() { [|int x, y = 1;|] } }"; var expected = @"class C { void M() { NewMethod(); } private static void NewMethod() { int x, y = 1; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(539214, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539214")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethodForSplitOutStatementWithComments() { var code = @"class C { void M() { //start [|int x, y; x = 5; y = 10;|] //end Console.Write(x + y); } }"; var expected = @"class C { void M() { //start int x, y; NewMethod(out x, out y); //end Console.Write(x + y); } private static void NewMethod(out int x, out int y) { x = 5; y = 10; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(539225, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539225")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task Bug5098() { var code = @"class Program { static void Main(string[] args) { [|return;|] Console.Write(4); } }"; await ExpectExtractMethodToFailAsync(code); } [WorkItem(539229, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539229")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task Bug5107() { var code = @"class Program { static void Main(string[] args) { int i = 10; [|int j = j + i;|] Console.Write(i); Console.Write(j); } }"; var expected = @"class Program { static void Main(string[] args) { int i = 10; int j = NewMethod(i); Console.Write(i); Console.Write(j); } private static int NewMethod(int i) { return j + i; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(539500, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539500")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task LambdaLiftedVariable1() { var code = @"class Program { delegate void Func(ref int i, int r); static void Main(string[] args) { int temp = 2; Func fnc = (ref int arg, int arg2) => { [|temp = arg = arg2;|] }; temp = 4; fnc(ref temp, 2); System.Console.WriteLine(temp); } }"; var expected = @"class Program { delegate void Func(ref int i, int r); static void Main(string[] args) { int temp = 2; Func fnc = (ref int arg, int arg2) => { arg = NewMethod(arg2); }; temp = 4; fnc(ref temp, 2); System.Console.WriteLine(temp); } private static int NewMethod(int arg2) { int arg, temp; temp = arg = arg2; return arg; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(539488, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539488")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task LambdaLiftedVariable2() { var code = @"class Program { delegate void Action(); static void Main(string[] args) { int i = 0; Action query = null; if (i == 0) { query = () => { System.Console.WriteLine(i); }; } [|i = 3;|] query(); } }"; var expected = @"class Program { delegate void Action(); static void Main(string[] args) { int i = 0; Action query = null; if (i == 0) { query = () => { System.Console.WriteLine(i); }; } NewMethod(); query(); } private static void NewMethod() { int i = 3; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(539531, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539531")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task Bug5533() { var code = @"using System; class Program { delegate void TestDelegate(ref int x); static void Main(string[] args) { [|TestDelegate testDel = (ref int x) => { x = 10; };|] int p = 2; testDel(ref p); Console.WriteLine(p); } }"; var expected = @"using System; class Program { delegate void TestDelegate(ref int x); static void Main(string[] args) { TestDelegate testDel = NewMethod(); int p = 2; testDel(ref p); Console.WriteLine(p); } private static TestDelegate NewMethod() { return (ref int x) => { x = 10; }; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(539531, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539531")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task Bug5533_1() { var code = @"using System; class Program { delegate void TestDelegate(ref int x); static void Main(string[] args) { [|TestDelegate testDel = (ref int x) => { int y = x; x = 10; };|] int p = 2; testDel(ref p); Console.WriteLine(p); } }"; var expected = @"using System; class Program { delegate void TestDelegate(ref int x); static void Main(string[] args) { TestDelegate testDel = NewMethod(); int p = 2; testDel(ref p); Console.WriteLine(p); } private static TestDelegate NewMethod() { return (ref int x) => { int y = x; x = 10; }; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(539531, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539531")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task Bug5533_2() { var code = @"using System; class Program { delegate void TestDelegate(ref int x); static void Main(string[] args) { TestDelegate testDel = (ref int x) => { [|int y = x; x = 10;|] }; int p = 2; testDel(ref p); Console.WriteLine(p); } }"; var expected = @"using System; class Program { delegate void TestDelegate(ref int x); static void Main(string[] args) { TestDelegate testDel = (ref int x) => { x = NewMethod(x); }; int p = 2; testDel(ref p); Console.WriteLine(p); } private static int NewMethod(int x) { int y = x; x = 10; return x; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(539531, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539531")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task Bug5533_3() { var code = @"using System; class Program { delegate void TestDelegate(ref int x); static void Main(string[] args) { [|TestDelegate testDel = delegate (ref int x) { x = 10; };|] int p = 2; testDel(ref p); Console.WriteLine(p); } }"; var expected = @"using System; class Program { delegate void TestDelegate(ref int x); static void Main(string[] args) { TestDelegate testDel = NewMethod(); int p = 2; testDel(ref p); Console.WriteLine(p); } private static TestDelegate NewMethod() { return delegate (ref int x) { x = 10; }; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(539859, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539859")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task LambdaLiftedVariable3() { var code = @"using System; class Program { static void Main(string[] args) { Action<int> F = x => { Action<int> F2 = x2 => { [|Console.WriteLine(args.Length + x2 + x);|] }; F2(x); }; F(args.Length); } }"; var expected = @"using System; class Program { static void Main(string[] args) { Action<int> F = x => { Action<int> F2 = x2 => { NewMethod(args, x, x2); }; F2(x); }; F(args.Length); } private static void NewMethod(string[] args, int x, int x2) { Console.WriteLine(args.Length + x2 + x); } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(539882, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539882")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task Bug5982() { var code = @"using System; using System.Collections.Generic; class Program { static void Main(string[] args) { List<int> list = new List<int>(); Console.WriteLine([|list.Capacity|]); } }"; var expected = @"using System; using System.Collections.Generic; class Program { static void Main(string[] args) { List<int> list = new List<int>(); Console.WriteLine(GetCapacity(list)); } private static int GetCapacity(List<int> list) { return list.Capacity; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(539932, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539932")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task Bug6041() { var code = @"using System; class Program { delegate R Del<in T, out R>(T arg); public void Goo() { Del<Exception, ArgumentException> d = (arg) => { return new ArgumentException(); }; [|d(new ArgumentException());|] } }"; var expected = @"using System; class Program { delegate R Del<in T, out R>(T arg); public void Goo() { Del<Exception, ArgumentException> d = (arg) => { return new ArgumentException(); }; NewMethod(d); } private static void NewMethod(Del<Exception, ArgumentException> d) { d(new ArgumentException()); } }"; await TestExtractMethodAsync(code, expected, allowMovingDeclaration: false); } [WorkItem(540183, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540183")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod50() { var code = @"class C { void Method() { while (true) { [|int i = 1; while (false) { int j = 1;|] } } } }"; var expected = @"class C { void Method() { while (true) { NewMethod(); } } private static void NewMethod() { int i = 1; while (false) { int j = 1; } } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod51() { var code = @"class C { void Method() { while (true) { switch(1) { case 1: [|int i = 10; break; case 2: int i2 = 20;|] break; } } } }"; var expected = @"class C { void Method() { while (true) { NewMethod(); } } private static void NewMethod() { switch (1) { case 1: int i = 10; break; case 2: int i2 = 20; break; } } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod52() { var code = @"class C { void Method() { [|int i = 1; while (false) { int j = 1;|] } } }"; var expected = @"class C { void Method() { NewMethod(); } private static void NewMethod() { int i = 1; while (false) { int j = 1; } } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(539963, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539963")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod53() { var code = @"class Class { void Main() { Enum e = Enum.[|Field|]; } } enum Enum { }"; await ExpectExtractMethodToFailAsync(code); } [WorkItem(539964, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539964")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod54() { var code = @"class Class { void Main([|string|][] args) { } }"; await ExpectExtractMethodToFailAsync(code); } [WorkItem(540072, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540072")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task Bug6220() { var code = @"class C { void Main() { [| float f = 1.2f; |] System.Console.WriteLine(); } }"; var expected = @"class C { void Main() { NewMethod(); System.Console.WriteLine(); } private static void NewMethod() { float f = 1.2f; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(540072, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540072")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task Bug6220_1() { var code = @"class C { void Main() { [| float f = 1.2f; // test |] System.Console.WriteLine(); } }"; var expected = @"class C { void Main() { NewMethod(); System.Console.WriteLine(); } private static void NewMethod() { float f = 1.2f; // test } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(540071, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540071")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task Bug6219() { var code = @"class C { void Main() { float @float = 1.2f; [|@float = 1.44F;|] } }"; var expected = @"class C { void Main() { float @float = 1.2f; NewMethod(); } private static void NewMethod() { float @float = 1.44F; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(540080, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540080")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task Bug6230() { var code = @"class C { void M() { int v =[| /**/1 + 2|]; System.Console.WriteLine(); } }"; var expected = @"class C { void M() { int v = GetV(); System.Console.WriteLine(); } private static int GetV() { return /**/1 + 2; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(540080, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540080")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task Bug6230_1() { var code = @"class C { void M() { int v [|= /**/1 + 2|]; System.Console.WriteLine(); } }"; var expected = @"class C { void M() { NewMethod(); System.Console.WriteLine(); } private static void NewMethod() { int v = /**/1 + 2; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(540052, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540052")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task Bug6197() { var code = @"using System; class Program { static void Main(string[] args) { Func<int, int> d = [|NewMethod|]; d.Invoke(2); } private static int NewMethod(int x) { return x * 2; } }"; var expected = @"using System; class Program { static void Main(string[] args) { Func<int, int> d = GetD(); d.Invoke(2); } private static Func<int, int> GetD() { return NewMethod; } private static int NewMethod(int x) { return x * 2; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(6277, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task Bug6277() { var code = @"using System; class Program { static void Main(string[] args) { [|int x; x = 1;|] return; int y = x; } }"; var expected = @"using System; class Program { static void Main(string[] args) { int x = NewMethod(); return; int y = x; } private static int NewMethod() { return 1; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(540151, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540151")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ArgumentlessReturnWithConstIfExpression() { var code = @"using System; class Program { void Test() { [|if (true) return;|] Console.WriteLine(); } }"; var expected = @"using System; class Program { void Test() { NewMethod(); return; Console.WriteLine(); } private static void NewMethod() { if (true) return; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(540151, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540151")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ArgumentlessReturnWithConstIfExpression_1() { var code = @"using System; class Program { void Test() { if (true) [|if (true) return;|] Console.WriteLine(); } }"; var expected = @"using System; class Program { void Test() { if (true) { NewMethod(); return; } Console.WriteLine(); } private static void NewMethod() { if (true) return; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(540151, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540151")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ArgumentlessReturnWithConstIfExpression_2() { var code = @"using System; class Program { void Test() { [|if (true) return;|] } }"; var expected = @"using System; class Program { void Test() { NewMethod(); } private static void NewMethod() { if (true) return; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(540151, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540151")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ArgumentlessReturnWithConstIfExpression_3() { var code = @"using System; class Program { void Test() { if (true) [|if (true) return;|] } }"; var expected = @"using System; class Program { void Test() { if (true) { NewMethod(); return; } } private static void NewMethod() { if (true) return; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(540154, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540154")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task Bug6313() { var code = @"using System; class Program { void Test(bool b) { [|if (b) { return; } Console.WriteLine();|] } }"; var expected = @"using System; class Program { void Test(bool b) { NewMethod(b); } private static void NewMethod(bool b) { if (b) { return; } Console.WriteLine(); } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(540154, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540154")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task Bug6313_1() { var code = @"using System; class Program { void Test(bool b) { [|if (b) { return; }|] Console.WriteLine(); } }"; await ExpectExtractMethodToFailAsync(code); } [WorkItem(540154, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540154")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task Bug6313_2() { var code = @"using System; class Program { int Test(bool b) { [|if (b) { return 1; } Console.WriteLine();|] } }"; await ExpectExtractMethodToFailAsync(code); } [WorkItem(540154, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540154")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task Bug6313_3() { var code = @"using System; class Program { void Test() { [|bool b = true; if (b) { return; } Action d = () => { if (b) { return; } Console.WriteLine(1); };|] } }"; var expected = @"using System; class Program { void Test() { NewMethod(); } private static void NewMethod() { bool b = true; if (b) { return; } Action d = () => { if (b) { return; } Console.WriteLine(1); }; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(540154, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540154")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task Bug6313_4() { var code = @"using System; class Program { void Test() { [|Action d = () => { int i = 1; if (i > 10) { return; } Console.WriteLine(1); }; Action d2 = () => { int i = 1; if (i > 10) { return; } Console.WriteLine(1); };|] Console.WriteLine(1); } }"; var expected = @"using System; class Program { void Test() { NewMethod(); Console.WriteLine(1); } private static void NewMethod() { Action d = () => { int i = 1; if (i > 10) { return; } Console.WriteLine(1); }; Action d2 = () => { int i = 1; if (i > 10) { return; } Console.WriteLine(1); }; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(540154, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540154")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task Bug6313_5() { var code = @"using System; class Program { void Test() { Action d = () => { [|int i = 1; if (i > 10) { return; } Console.WriteLine(1);|] }; } }"; var expected = @"using System; class Program { void Test() { Action d = () => { NewMethod(); }; } private static void NewMethod() { int i = 1; if (i > 10) { return; } Console.WriteLine(1); } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(540154, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540154")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task Bug6313_6() { var code = @"using System; class Program { void Test() { Action d = () => { [|int i = 1; if (i > 10) { return; }|] Console.WriteLine(1); }; } }"; await ExpectExtractMethodToFailAsync(code); } [WorkItem(540170, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540170")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task Bug6333() { var code = @"using System; class Program { void Test() { Program p; [|p = new Program()|]; } }"; var expected = @"using System; class Program { void Test() { Program p; p = NewMethod(); } private static Program NewMethod() { return new Program(); } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(540216, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540216")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task Bug6393() { var code = @"using System; class Program { object Test<T>() { T abcd; [|abcd = new T()|]; return abcd; } }"; var expected = @"using System; class Program { object Test<T>() { T abcd; abcd = NewMethod<T>(); return abcd; } private static T NewMethod<T>() { return new T(); } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(540184, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540184")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task Bug6351() { var code = @"class Test { void method() { if (true) { for (int i = 0; i < 5; i++) { /*Begin*/ [|System.Console.WriteLine(); } System.Console.WriteLine();|] /*End*/ } } }"; var expected = @"class Test { void method() { if (true) { NewMethod(); /*End*/ } } private static void NewMethod() { for (int i = 0; i < 5; i++) { /*Begin*/ System.Console.WriteLine(); } System.Console.WriteLine(); } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(540184, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540184")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task Bug6351_1() { var code = @"class Test { void method() { if (true) { for (int i = 0; i < 5; i++) { /*Begin*/ [|System.Console.WriteLine(); } System.Console.WriteLine(); /*End*/|] } } }"; var expected = @"class Test { void method() { if (true) { NewMethod(); } } private static void NewMethod() { for (int i = 0; i < 5; i++) { /*Begin*/ System.Console.WriteLine(); } System.Console.WriteLine(); /*End*/ } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(540184, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540184")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task Bug6351_2() { var code = @"class Test { void method() { if (true) [|{ for (int i = 0; i < 5; i++) { /*Begin*/ System.Console.WriteLine(); } System.Console.WriteLine(); /*End*/ }|] } }"; var expected = @"class Test { void method() { if (true) NewMethod(); } private static void NewMethod() { for (int i = 0; i < 5; i++) { /*Begin*/ System.Console.WriteLine(); } System.Console.WriteLine(); /*End*/ } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(540333, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540333")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task Bug6560() { var code = @"using System; class Program { static void Main(string[] args) { string S = [|null|]; int Y = S.Length; } }"; var expected = @"using System; class Program { static void Main(string[] args) { string S = GetS(); int Y = S.Length; } private static string GetS() { return null; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(540335, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540335")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task Bug6562() { var code = @"using System; class Program { int y = [|10|]; }"; var expected = @"using System; class Program { int y = GetY(); private static int GetY() { return 10; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(540335, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540335")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task Bug6562_1() { var code = @"using System; class Program { const int i = [|10|]; }"; await ExpectExtractMethodToFailAsync(code); } [WorkItem(540335, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540335")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task Bug6562_2() { var code = @"using System; class Program { Func<string> f = [|() => ""test""|]; }"; var expected = @"using System; class Program { Func<string> f = GetF(); private static Func<string> GetF() { return () => ""test""; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(540335, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540335")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task Bug6562_3() { var code = @"using System; class Program { Func<string> f = () => [|""test""|]; }"; var expected = @"using System; class Program { Func<string> f = () => NewMethod(); private static string NewMethod() { return ""test""; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(540361, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540361")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task Bug6598() { var code = @"using System; using System.Collections.Generic; using System.Linq; class { static void Main(string[] args) { [|Program|] } }"; await ExpectExtractMethodToFailAsync(code); } [WorkItem(540372, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540372")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task Bug6613() { var code = @"#define A using System; class Program { static void Main(string[] args) { #if A [|Console.Write(5);|] #endif } }"; var expected = @"#define A using System; class Program { static void Main(string[] args) { #if A NewMethod(); #endif } private static void NewMethod() { Console.Write(5); } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(540396, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540396")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task InvalidSelection_MethodBody() { var code = @"using System; class Program { static void Main(string[] args) { void Method5(bool b1, bool b2) [|{ if (b1) { if (b2) return; Console.WriteLine(); } Console.WriteLine(); }|] } } "; await ExpectExtractMethodToFailAsync(code); } [WorkItem(541586, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541586")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task StructThis() { var code = @"struct S { void Goo() { [|this = new S();|] } }"; var expected = @"struct S { void Goo() { NewMethod(); } private void NewMethod() { this = new S(); } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(541627, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541627")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task DontUseConvertedTypeForImplicitNumericConversion() { var code = @"class T { void Goo() { int x1 = 5; long x2 = [|x1|]; } }"; var expected = @"class T { void Goo() { int x1 = 5; long x2 = GetX2(x1); } private static int GetX2(int x1) { return x1; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(541668, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541668")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task BreakInSelection() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { static void Main(string[] args) { string x1 = ""Hello""; switch (x1) { case null: int i1 = 10; break; default: switch (x1) { default: switch (x1) { [|default: int j1 = 99; i1 = 45; x1 = ""t""; string j2 = i1.ToString() + j1.ToString() + x1; break; } break; } break;|] } } }"; await ExpectExtractMethodToFailAsync(code); } [WorkItem(541671, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541671")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task UnreachableCodeWithReturnStatement() { var code = @"class Program { static void Main(string[] args) { return; [|int i1 = 45; i1 = i1 + 10;|] return; } }"; var expected = @"class Program { static void Main(string[] args) { return; NewMethod(); return; } private static void NewMethod() { int i1 = 45; i1 = i1 + 10; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(539862, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539862")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task DontBlindlyPutCapturedVariable1() { var code = @"using System; class Program { private static readonly int v = 5; delegate int Del(int i); static void Main(string[] args) { Ros.A a = new Ros.A(); Del d = (int x) => { [|a.F(x)|]; return x * v; }; d(3); } } namespace Ros { partial class A { public void F(int s) { } } }"; var expected = @"using System; class Program { private static readonly int v = 5; delegate int Del(int i); static void Main(string[] args) { Ros.A a = new Ros.A(); Del d = (int x) => { NewMethod(x, a); return x * v; }; d(3); } private static void NewMethod(int x, Ros.A a) { a.F(x); } } namespace Ros { partial class A { public void F(int s) { } } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(539862, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539862")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task DontBlindlyPutCapturedVariable2() { var code = @"using System; class Program { private static readonly int v = 5; delegate int Del(int i); static void Main(string[] args) { Program p; Del d = (int x) => { [|p = null;|]; return x * v; }; d(3); } }"; var expected = @"using System; class Program { private static readonly int v = 5; delegate int Del(int i); static void Main(string[] args) { Program p; Del d = (int x) => { p = NewMethod(); ; return x * v; }; d(3); } private static Program NewMethod() { return null; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(541889, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541889")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task DontCrashOnRangeVariableSymbol() { var code = @"class Test { public void Linq1() { int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; var lowNums = [|from|] n in numbers where n < 5 select n; } }"; await ExpectExtractMethodToFailAsync(code); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractRangeVariable() { var code = @"using System.Linq; class Test { public void Linq1() { string[] array = null; var q = from string s in array select [|s|]; } }"; var expected = @"using System.Linq; class Test { public void Linq1() { string[] array = null; var q = from string s in array select GetS(s); } private static string GetS(string s) { return s; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(542155, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542155")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task GenericWithErrorType() { var code = @"using Goo.Utilities; class Goo<T> { } class Bar { void gibberish() { Goo<[|Integer|]> x = null; x.IsEmpty(); } } namespace Goo.Utilities { internal static class GooExtensions { public static bool IsEmpty<T>(this Goo<T> source) { return false; } } }"; var expected = @"using Goo.Utilities; class Goo<T> { } class Bar { void gibberish() { Goo<Integer> x = NewMethod(); x.IsEmpty(); } private static Goo<Integer> NewMethod() { return null; } } namespace Goo.Utilities { internal static class GooExtensions { public static bool IsEmpty<T>(this Goo<T> source) { return false; } } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(542105, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542105")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task NamedArgument() { var code = @"using System; class C { int this[int x = 5, int y = 7] { get { return 0; } set { } } void Goo() { var y = this[[|y|]: 1]; } }"; var expected = @"using System; class C { int this[int x = 5, int y = 7] { get { return 0; } set { } } void Goo() { var y = GetY(); } private int GetY() { return this[y: 1]; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(542213, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542213")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task QueryExpressionVariable() { var code = @"using System; using System.Linq; using System.Collections.Generic; class Program { static void Main(string[] args) { var q2 = from a in Enumerable.Range(1, 2) from b in Enumerable.Range(1, 2) where ([|a == b|]) select a; } }"; var expected = @"using System; using System.Linq; using System.Collections.Generic; class Program { static void Main(string[] args) { var q2 = from a in Enumerable.Range(1, 2) from b in Enumerable.Range(1, 2) where (NewMethod(a, b)) select a; } private static bool NewMethod(int a, int b) { return a == b; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(542465, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542465")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task IsExpression() { var code = @"using System; class Class1 { } class IsTest { static void Test(Class1 o) { var b = new Class1() is [|Class1|]; } static void Main() { } }"; var expected = @"using System; class Class1 { } class IsTest { static void Test(Class1 o) { var b = GetB(); } private static bool GetB() { return new Class1() is Class1; } static void Main() { } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(542526, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542526")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task TypeParametersInConstraint() { var code = @"using System; using System.Collections.Generic; class A { static void Goo<T, S>(T x) where T : IList<S> { var y = [|x.Count|]; } }"; var expected = @"using System; using System.Collections.Generic; class A { static void Goo<T, S>(T x) where T : IList<S> { var y = GetY<T, S>(x); } private static int GetY<T, S>(T x) where T : IList<S> { return x.Count; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(542619, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542619")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task GlobalNamespaceInReturnType() { var code = @"class Program { class System { class Action { } } static global::System.Action a = () => { global::System.Console.WriteLine(); [|}|]; }"; var expected = @"class Program { class System { class Action { } } static global::System.Action a = GetA(); private static global::System.Action GetA() { return () => { global::System.Console.WriteLine(); }; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(542582, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542582")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethodExpandSelectionOnFor() { var code = @"using System; class Program { static void Main(string[] args) { for (int i = 0; i < 10; i++) [|{ Console.WriteLine(i);|] } } }"; var expected = @"using System; class Program { static void Main(string[] args) { for (int i = 0; i < 10; i++) NewMethod(i); } private static void NewMethod(int i) { Console.WriteLine(i); } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethodNotContainerOnFor() { var code = @"using System; class Program { static void Main(string[] args) { for (int i = 0; i < [|10|]; i++) ; } }"; var expected = @"using System; class Program { static void Main(string[] args) { for (int i = 0; i < NewMethod(); i++) ; } private static int NewMethod() { return 10; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethodExpandSelectionOnForeach() { var code = @"using System; class Program { static void Main(string[] args) { foreach (var c in ""123"") [|{ Console.Write(c);|] } } }"; var expected = @"using System; class Program { static void Main(string[] args) { foreach (var c in ""123"") NewMethod(c); } private static void NewMethod(char c) { Console.Write(c); } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethodNotContainerOnForeach() { var code = @"using System; class Program { static void Main(string[] args) { foreach (var c in [|""123""|]) { Console.Write(c); } } }"; var expected = @"using System; class Program { static void Main(string[] args) { foreach (var c in NewMethod()) { Console.Write(c); } } private static string NewMethod() { return ""123""; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethodNotContainerOnElseClause() { var code = @"using System; class Program { static void Main(string[] args) { if ([|true|]) { } else { } } }"; var expected = @"using System; class Program { static void Main(string[] args) { if (NewMethod()) { } else { } } private static bool NewMethod() { return true; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethodExpandSelectionOnLabel() { var code = @"using System; class Program { static void Main(string[] args) { repeat: Console.WriteLine(""Roslyn"")[|;|] if (true) goto repeat; } }"; var expected = @"using System; class Program { static void Main(string[] args) { repeat: NewMethod(); if (true) goto repeat; } private static void NewMethod() { Console.WriteLine(""Roslyn""); } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethodNotContainerOnLabel() { var code = @"using System; class Program { static void Main(string[] args) { repeat: Console.WriteLine(""Roslyn""); if ([|true|]) goto repeat; } }"; var expected = @"using System; class Program { static void Main(string[] args) { repeat: Console.WriteLine(""Roslyn""); if (NewMethod()) goto repeat; } private static bool NewMethod() { return true; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethodExpandSelectionOnSwitch() { var code = @"using System; class Program { static void Main(string[] args) { switch (args[0]) { case ""1"": Console.WriteLine(""one"")[|;|] break; default: Console.WriteLine(""other""); break; } } }"; var expected = @"using System; class Program { static void Main(string[] args) { switch (args[0]) { case ""1"": NewMethod(); break; default: Console.WriteLine(""other""); break; } } private static void NewMethod() { Console.WriteLine(""one""); } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethodNotContainerOnSwitch() { var code = @"using System; class Program { static void Main(string[] args) { switch ([|args[0]|]) { case ""1"": Console.WriteLine(""one""); break; default: Console.WriteLine(""other""); break; } } }"; var expected = @"using System; class Program { static void Main(string[] args) { switch (NewMethod(args)) { case ""1"": Console.WriteLine(""one""); break; default: Console.WriteLine(""other""); break; } } private static string NewMethod(string[] args) { return args[0]; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethodExpandSelectionOnDo() { var code = @"using System; class Program { static void Main(string[] args) { do [|{ Console.WriteLine(""I don't like"");|] } while (DateTime.Now.DayOfWeek == DayOfWeek.Monday); } }"; var expected = @"using System; class Program { static void Main(string[] args) { do NewMethod(); while (DateTime.Now.DayOfWeek == DayOfWeek.Monday); } private static void NewMethod() { Console.WriteLine(""I don't like""); } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethodNotContainerOnDo() { var code = @"using System; class Program { static void Main(string[] args) { do { Console.WriteLine(""I don't like""); } while ([|DateTime.Now.DayOfWeek == DayOfWeek.Monday|]); } }"; var expected = @"using System; class Program { static void Main(string[] args) { do { Console.WriteLine(""I don't like""); } while (NewMethod()); } private static bool NewMethod() { return DateTime.Now.DayOfWeek == DayOfWeek.Monday; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethodExpandSelectionOnWhile() { var code = @"using System; class Program { static void Main(string[] args) { while (true) [|{ ;|] } } }"; var expected = @"using System; class Program { static void Main(string[] args) { while (true) NewMethod(); } private static void NewMethod() { ; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethodExpandSelectionOnStruct() { var code = @"using System; struct Goo { static Action a = () => { Console.WriteLine(); [|}|]; }"; var expected = @"using System; struct Goo { static Action a = GetA(); private static Action GetA() { return () => { Console.WriteLine(); }; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(542619, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542619")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethodIncludeGlobal() { var code = @"class Program { class System { class Action { } } static global::System.Action a = () => { global::System.Console.WriteLine(); [|}|]; static void Main(string[] args) { } }"; var expected = @"class Program { class System { class Action { } } static global::System.Action a = GetA(); private static global::System.Action GetA() { return () => { global::System.Console.WriteLine(); }; } static void Main(string[] args) { } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(542582, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542582")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethodExpandSelection() { var code = @"class Program { static void Main(string[] args) { for (int i = 0; i < 10; i++) [|{ System.Console.WriteLine(i);|] } } }"; var expected = @"class Program { static void Main(string[] args) { for (int i = 0; i < 10; i++) NewMethod(i); } private static void NewMethod(int i) { System.Console.WriteLine(i); } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(542594, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542594")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethodRename1() { var code = @"class Program { static void Main() { [|var i = 42;|] var j = 42; } private static void NewMethod() { } private static void NewMethod2() { } }"; var expected = @"class Program { static void Main() { NewMethod1(); var j = 42; } private static void NewMethod1() { var i = 42; } private static void NewMethod() { } private static void NewMethod2() { } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(542594, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542594")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethodRename2() { var code = @"class Program { static void Main() { NewMethod1(); [|var j = 42;|] } private static void NewMethod1() { var i = 42; } private static void NewMethod() { } private static void NewMethod2() { } }"; var expected = @"class Program { static void Main() { NewMethod1(); NewMethod3(); } private static void NewMethod3() { var j = 42; } private static void NewMethod1() { var i = 42; } private static void NewMethod() { } private static void NewMethod2() { } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(542632, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542632")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethodInInteractive1() { var code = @"int i; [|i = 2|]; i = 3;"; var expected = @"int i; i = NewMethod(); int NewMethod() { return 2; } i = 3;"; await TestExtractMethodAsync(code, expected, parseOptions: Options.Script); } [WorkItem(542670, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542670")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task TypeParametersInConstraint1() { var code = @"using System; using System.Collections.Generic; class A { static void Goo<T, S, U>(T x) where T : IList<S> where S : IList<U> { var y = [|x.Count|]; } }"; var expected = @"using System; using System.Collections.Generic; class A { static void Goo<T, S, U>(T x) where T : IList<S> where S : IList<U> { var y = GetY<T, S>(x); } private static int GetY<T, S>(T x) where T : IList<S> { return x.Count; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(706894, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/706894")] [WorkItem(543012, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543012")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task TypeParametersInConstraint2() { var code = @" using System; interface I<T> where T : IComparable<T> { int Count { get; } } class A { static void Goo<T, S>(S x) where S : I<T> where T : IComparable<T> { var y = [|x.Count|]; } } "; var expected = @" using System; interface I<T> where T : IComparable<T> { int Count { get; } } class A { static void Goo<T, S>(S x) where S : I<T> where T : IComparable<T> { var y = GetY<T, S>(x); } private static int GetY<T, S>(S x) where T : IComparable<T> where S : I<T> { return x.Count; } } "; await TestExtractMethodAsync(code, expected); } [WorkItem(706894, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/706894")] [WorkItem(543012, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543012")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task TypeParametersInConstraint3() { var code = @" using System; interface I<T> where T : class { int Count { get; } } class A { static void Goo<T, S>(S x) where S : I<T> where T : class { var y = [|x.Count|]; } } "; var expected = @" using System; interface I<T> where T : class { int Count { get; } } class A { static void Goo<T, S>(S x) where S : I<T> where T : class { var y = GetY<T, S>(x); } private static int GetY<T, S>(S x) where T : class where S : I<T> { return x.Count; } } "; await TestExtractMethodAsync(code, expected); } [WorkItem(543012, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543012")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task TypeParametersInConstraint4() { var code = @" using System; using System.Collections.Generic; interface I<T> where T : class { } interface I2<T1, T2> : I<T1> where T1 : class, IEnumerable<T2> where T2 : struct { int Count { get; } } class A { public virtual void Goo<T, S>(S x) where S : IList<I2<IEnumerable<T>, T>> where T : struct { } } class B : A { public override void Goo<T, S>(S x) { var y = [|x.Count|]; } } "; var expected = @" using System; using System.Collections.Generic; interface I<T> where T : class { } interface I2<T1, T2> : I<T1> where T1 : class, IEnumerable<T2> where T2 : struct { int Count { get; } } class A { public virtual void Goo<T, S>(S x) where S : IList<I2<IEnumerable<T>, T>> where T : struct { } } class B : A { public override void Goo<T, S>(S x) { var y = GetY<T, S>(x); } private static int GetY<T, S>(S x) where T : struct where S : IList<I2<IEnumerable<T>, T>> { return x.Count; } } "; await TestExtractMethodAsync(code, expected); } [WorkItem(543012, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543012")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task TypeParametersInConstraintBestEffort() { var code = @" using System; using System.Collections.Generic; using System.Linq; class A<T> { public virtual void Test<S>(S s) where S : T { } } class B : A<string> { public override void Test<S>(S s) { var t = [|s.ToString()|]; } } "; var expected = @" using System; using System.Collections.Generic; using System.Linq; class A<T> { public virtual void Test<S>(S s) where S : T { } } class B : A<string> { public override void Test<S>(S s) { var t = GetT(s); } private static string GetT<S>(S s) where S : string { return s.ToString(); } } "; await TestExtractMethodAsync(code, expected); } [WorkItem(542672, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542672")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ConstructedTypes() { var code = @"using System; using System.Collections.Generic; class Program { static void Goo<T>() { List<T> x = new List<T>(); Action a = () => Console.WriteLine([|x.Count|]); } }"; var expected = @"using System; using System.Collections.Generic; class Program { static void Goo<T>() { List<T> x = new List<T>(); Action a = () => Console.WriteLine(GetCount(x)); } private static int GetCount<T>(List<T> x) { return x.Count; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(542792, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542792")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task TypeInDefault() { var code = @"using System; using System.Collections.Generic; using System.Linq; class Program { static void Main(string[] args) { Node<int, Exception> node = new Node<int, Exception>(); } } class Node<K, T> where T : new() { public K Key; public T Item; public Node<K, T> NextNode; public Node() { Key = default([|K|]); Item = new T(); NextNode = null; Console.WriteLine(Key); } }"; var expected = @"using System; using System.Collections.Generic; using System.Linq; class Program { static void Main(string[] args) { Node<int, Exception> node = new Node<int, Exception>(); } } class Node<K, T> where T : new() { public K Key; public T Item; public Node<K, T> NextNode; public Node() { Key = NewMethod(); Item = new T(); NextNode = null; Console.WriteLine(Key); } private static K NewMethod() { return default(K); } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(542708, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542708")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task Script_ArgumentException() { var code = @"using System; public static void GetNonVirtualMethod<TDelegate>( Type type, string name) { Type delegateType = typeof(TDelegate); var invoke = [|delegateType|].GetMethod(""Invoke""); }"; var expected = @"using System; public static void GetNonVirtualMethod<TDelegate>( Type type, string name) { Type delegateType = typeof(TDelegate); var invoke = GetDelegateType(delegateType).GetMethod(""Invoke""); } Type GetDelegateType(Type delegateType) { return delegateType; }"; await TestExtractMethodAsync(code, expected, parseOptions: Options.Script); } [WorkItem(529008, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529008")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ReadOutSideIsUnReachable() { var code = @"class Test { public static void Main() { string str = string.Empty; object obj; [|lock (new string[][] { new string[] { str }, new string[] { str } }) { obj = new object(); return; }|] System.Console.Write(obj); } }"; var expected = @"class Test { public static void Main() { string str = string.Empty; object obj; NewMethod(str, out obj); return; System.Console.Write(obj); } private static void NewMethod(string str, out object obj) { lock (new string[][] { new string[] { str }, new string[] { str } }) { obj = new object(); return; } } }"; await TestExtractMethodAsync(code, expected, allowMovingDeclaration: false); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] [WorkItem(543186, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543186")] public async Task AnonymousTypePropertyName() { var code = @"class C { void M() { var x = new { [|String|] = true }; } }"; var expected = @"class C { void M() { NewMethod(); } private static void NewMethod() { var x = new { String = true }; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(543662, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543662")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ArgumentOfBaseConstrInit() { var code = @"class O { public O(int t) : base([|t|]) { } }"; var expected = @"class O { public O(int t) : base(GetT(t)) { } private static int GetT(int t) { return t; } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task UnsafeType() { var code = @" unsafe class O { unsafe public O(int t) { [|t = 1;|] } }"; var expected = @" unsafe class O { unsafe public O(int t) { NewMethod(); } private static void NewMethod() { int t = 1; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(544144, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544144")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task CastExpressionWithImplicitUserDefinedConversion() { var code = @" class C { static public implicit operator long(C i) { return 5; } static void Main() { C c = new C(); int y1 = [|(int)c|]; } }"; var expected = @" class C { static public implicit operator long(C i) { return 5; } static void Main() { C c = new C(); int y1 = GetY1(c); } private static int GetY1(C c) { return (int)c; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(544387, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544387")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task FixedPointerVariable() { var code = @" class Test { static int x = 0; unsafe static void Main() { fixed (int* p1 = &x) { int a1 = [|*p1|]; } } }"; var expected = @" class Test { static int x = 0; unsafe static void Main() { fixed (int* p1 = &x) { int a1 = GetA1(p1); } } private static unsafe int GetA1(int* p1) { return *p1; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(544444, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544444")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task PointerDeclarationStatement() { var code = @" class Program { unsafe static void Main() { int* p1 = null; [|int* p2 = p1;|] } }"; var expected = @" class Program { unsafe static void Main() { int* p1 = null; NewMethod(p1); } private static unsafe void NewMethod(int* p1) { int* p2 = p1; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(544446, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544446")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task PrecededByCastExpr() { var code = @" class Program { static void Main() { int i1 = (int)[|5L|]; } }"; var expected = @" class Program { static void Main() { int i1 = (int)NewMethod(); } private static long NewMethod() { return 5L; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(542944, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542944")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExpressionWithLocalConst() { var code = @"class Program { static void Main(string[] args) { const string a = null; [|a = null;|] } }"; var expected = @"class Program { static void Main(string[] args) { const string a = null; NewMethod(a); } private static void NewMethod(string a) { a = null; } }"; await TestExtractMethodAsync(code, expected, allowMovingDeclaration: true); } [WorkItem(542944, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542944")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExpressionWithLocalConst2() { var code = @"class Program { static void Main(string[] args) { const string a = null; [|a = null;|] } }"; var expected = @"class Program { static void Main(string[] args) { const string a = null; a = NewMethod(a); } private static string NewMethod(string a) { a = null; return a; } }"; await TestExtractMethodAsync(code, expected, allowMovingDeclaration: false); } [WorkItem(544675, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544675")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task HiddenPosition() { var code = @"class Program { static void Main(string[] args) { const string a = null; [|a = null;|] } #line default #line hidden }"; await ExpectExtractMethodToFailAsync(code); } [WorkItem(530609, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530609")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task NoCrashInteractive() { var code = @"[|if (true) { }|]"; var expected = @"NewMethod(); void NewMethod() { if (true) { } }"; await TestExtractMethodAsync(code, expected, parseOptions: new CSharpParseOptions(kind: SourceCodeKind.Script)); } [WorkItem(530322, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530322")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethodShouldNotBreakFormatting() { var code = @"class C { void M(int i, int j, int k) { M(0, [|1|], 2); } }"; var expected = @"class C { void M(int i, int j, int k) { M(0, NewMethod(), 2); } private static int NewMethod() { return 1; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(604389, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/604389")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task TestExtractLiteralExpression() { var code = @"class Program { static void Main() { var c = new C { X = { Y = { [|1|] } } }; } } class C { public dynamic X; }"; var expected = @"class Program { static void Main() { var c = new C { X = { Y = { NewMethod() } } }; } private static int NewMethod() { return 1; } } class C { public dynamic X; }"; await TestExtractMethodAsync(code, expected); } [WorkItem(604389, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/604389")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task TestExtractCollectionInitializer() { var code = @"class Program { static void Main() { var c = new C { X = { Y = [|{ 1 }|] } }; } } class C { public dynamic X; }"; var expected = @"class Program { static void Main() { var c = GetC(); } private static C GetC() { return new C { X = { Y = { 1 } } }; } } class C { public dynamic X; }"; await TestExtractMethodAsync(code, expected); } [WorkItem(854662, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/854662")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task TestExtractCollectionInitializer2() { var code = @"using System; using System.Collections.Generic; class Program { public Dictionary<int, int> A { get; private set; } static int Main(string[] args) { int a = 0; return new Program { A = { { [|a + 2|], 0 } } }.A.Count; } }"; var expected = @"using System; using System.Collections.Generic; class Program { public Dictionary<int, int> A { get; private set; } static int Main(string[] args) { int a = 0; return new Program { A = { { NewMethod(a), 0 } } }.A.Count; } private static int NewMethod(int a) { return a + 2; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(530267, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530267")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task TestCoClassImplicitConversion() { var code = @"using System; using System.Runtime.InteropServices; [CoClass(typeof(C))] [ComImport] [Guid(""8D3A7A55-A8F5-4669-A5AD-996A3EB8F2ED"")] interface I { } class C : I { static void Main() { [|new I()|]; // Extract Method } }"; var expected = @"using System; using System.Runtime.InteropServices; [CoClass(typeof(C))] [ComImport] [Guid(""8D3A7A55-A8F5-4669-A5AD-996A3EB8F2ED"")] interface I { } class C : I { static void Main() { NewMethod(); // Extract Method } private static I NewMethod() { return new I(); } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(530710, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530710")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task TestOverloadResolution() { var code = @"using System; static class C { static void Ex(this string x) { } static void Inner(Action<string> x, string y) { } static void Inner(Action<string> x, int y) { } static void Inner(Action<int> x, int y) { } static void Outer(object y, Action<string> x) { Console.WriteLine(1); } static void Outer(string y, Action<int> x) { Console.WriteLine(2); } static void Main() { Outer(null, y => Inner(x => { [|x|].Ex(); }, y)); // Prints 1 } } static class E { public static void Ex(this int x) { } }"; var expected = @"using System; static class C { static void Ex(this string x) { } static void Inner(Action<string> x, string y) { } static void Inner(Action<string> x, int y) { } static void Inner(Action<int> x, int y) { } static void Outer(object y, Action<string> x) { Console.WriteLine(1); } static void Outer(string y, Action<int> x) { Console.WriteLine(2); } static void Main() { Outer(null, (Action<string>)(y => Inner(x => { GetX(x).Ex(); }, y))); // Prints 1 } private static string GetX(string x) { return x; } } static class E { public static void Ex(this int x) { } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(530710, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530710")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task TestOverloadResolution1() { var code = @"using System; static class C { static void Ex(this string x) { } static void Inner(Action<string> x, string y) { } static void Inner(Action<string> x, int y) { } static void Inner(Action<int> x, int y) { } static void Outer(object y, Action<string> x) { Console.WriteLine(1); } static void Outer(string y, Action<int> x) { Console.WriteLine(2); } static void Main() { Outer(null, y => Inner(x => { [|x.Ex()|]; }, y)); // Prints 1 } } static class E { public static void Ex(this int x) { } }"; var expected = @"using System; static class C { static void Ex(this string x) { } static void Inner(Action<string> x, string y) { } static void Inner(Action<string> x, int y) { } static void Inner(Action<int> x, int y) { } static void Outer(object y, Action<string> x) { Console.WriteLine(1); } static void Outer(string y, Action<int> x) { Console.WriteLine(2); } static void Main() { Outer(null, (Action<string>)(y => Inner(x => { NewMethod(x); }, y))); // Prints 1 } private static void NewMethod(string x) { x.Ex(); } } static class E { public static void Ex(this int x) { } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(530710, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530710")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task TestOverloadResolution2() { var code = @"using System; static class C { static void Ex(this string x) { } static void Inner(Action<string> x, string y) { } static void Inner(Action<string> x, int y) { } static void Inner(Action<int> x, int y) { } static void Outer(object y, Action<string> x) { Console.WriteLine(1); } static void Outer(string y, Action<int> x) { Console.WriteLine(2); } static void Main() { Outer(null, y => Inner(x => { [|x.Ex();|] }, y)); // Prints 1 } } static class E { public static void Ex(this int x) { } }"; var expected = @"using System; static class C { static void Ex(this string x) { } static void Inner(Action<string> x, string y) { } static void Inner(Action<string> x, int y) { } static void Inner(Action<int> x, int y) { } static void Outer(object y, Action<string> x) { Console.WriteLine(1); } static void Outer(string y, Action<int> x) { Console.WriteLine(2); } static void Main() { Outer(null, (Action<string>)(y => Inner(x => { NewMethod(x); }, y))); // Prints 1 } private static void NewMethod(string x) { x.Ex(); } } static class E { public static void Ex(this int x) { } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(731924, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/731924")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task TestTreatEnumSpecial() { var code = @"using System; class Program { public enum A { A1, A2 } static void Main(string[] args) { A a = A.A1; [|Console.WriteLine(a);|] } }"; var expected = @"using System; class Program { public enum A { A1, A2 } static void Main(string[] args) { A a = A.A1; NewMethod(a); } private static void NewMethod(A a) { Console.WriteLine(a); } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(756222, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/756222")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task TestReturnStatementInAsyncMethod() { var code = @"using System.Threading.Tasks; class C { async Task<int> M() { await Task.Yield(); [|return 3;|] } }"; var expected = @"using System.Threading.Tasks; class C { async Task<int> M() { await Task.Yield(); return NewMethod(); } private static int NewMethod() { return 3; } }"; await TestExtractMethodAsync(code, expected); } [WorkItem(574576, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/574576")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task TestAsyncMethodWithRefOrOutParameters() { var code = @"using System.Threading.Tasks; class C { public async void Goo() { [|var q = 1; var p = 2; await Task.Yield();|] var r = q; var s = p; } }"; await ExpectExtractMethodToFailAsync(code); } [WorkItem(1025272, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1025272")] [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task TestAsyncMethodWithWellKnownValueType() { var code = @"using System; using System.Threading; using System.Threading.Tasks; class Program { public async Task Hello() { var cancellationToken = CancellationToken.None; [|var i = await Task.Run(() => { Console.WriteLine(); cancellationToken.ThrowIfCancellationRequested(); return 1; }, cancellationToken);|] cancellationToken.ThrowIfCancellationRequested(); Console.WriteLine(i); } }"; var expected = @"using System; using System.Threading; using System.Threading.Tasks; class Program { public async Task Hello() { var cancellationToken = CancellationToken.None; int i = await NewMethod(ref cancellationToken); cancellationToken.ThrowIfCancellationRequested(); Console.WriteLine(i); } private static async Task<int> NewMethod(ref CancellationToken cancellationToken) { return await Task.Run(() => { Console.WriteLine(); cancellationToken.ThrowIfCancellationRequested(); return 1; }, cancellationToken); } }"; await ExpectExtractMethodToFailAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task TestAsyncMethodWithWellKnownValueType1() { var code = @"using System; using System.Threading; using System.Threading.Tasks; class Program { public async Task Hello() { var cancellationToken = CancellationToken.None; [|var i = await Task.Run(() => { Console.WriteLine(); cancellationToken = CancellationToken.None; return 1; }, cancellationToken);|] cancellationToken.ThrowIfCancellationRequested(); Console.WriteLine(i); } }"; await ExpectExtractMethodToFailAsync(code, allowMovingDeclaration: false); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task TestDontPutOutOrRefForStructOff() { var code = @"using System.Threading.Tasks; namespace ClassLibrary9 { public struct S { public int I; } public class Class1 { private async Task<int> Test() { S s = new S(); s.I = 10; [|int i = await Task.Run(() => { var i2 = s.I; return Test(); });|] return i; } } }"; await ExpectExtractMethodToFailAsync(code, dontPutOutOrRefOnStruct: false); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task TestDontPutOutOrRefForStructOn() { var code = @"using System.Threading.Tasks; namespace ClassLibrary9 { public struct S { public int I; } public class Class1 { private async Task<int> Test() { S s = new S(); s.I = 10; [|int i = await Task.Run(() => { var i2 = s.I; return Test(); });|] return i; } } }"; var expected = @"using System.Threading.Tasks; namespace ClassLibrary9 { public struct S { public int I; } public class Class1 { private async Task<int> Test() { S s = new S(); s.I = 10; int i = await NewMethod(s); return i; } private async Task<int> NewMethod(S s) { return await Task.Run(() => { var i2 = s.I; return Test(); }); } } }"; await TestExtractMethodAsync(code, expected, dontPutOutOrRefOnStruct: true); } [Theory] [InlineData("add", "remove")] [InlineData("remove", "add")] [WorkItem(17474, "https://github.com/dotnet/roslyn/issues/17474")] [Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task TestExtractMethodEventAccessorUnresolvedName(string testedAccessor, string untestedAccessor) { // This code intentionally omits a 'using System;' var code = $@"namespace ClassLibrary9 {{ public class Class {{ public event EventHandler Event {{ {testedAccessor} {{ [|throw new NotImplementedException();|] }} {untestedAccessor} {{ throw new NotImplementedException(); }} }} }} }}"; var expected = $@"namespace ClassLibrary9 {{ public class Class {{ public event EventHandler Event {{ {testedAccessor} {{ NewMethod(); }} {untestedAccessor} {{ throw new NotImplementedException(); }} }} private static void NewMethod() {{ throw new NotImplementedException(); }} }} }}"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] [WorkItem(19958, "https://github.com/dotnet/roslyn/issues/19958")] public async Task TestExtractMethodRefPassThrough() { var code = @"using System; namespace ClassLibrary9 { internal class ClassExtensions { public static int OtherMethod(ref int x) => x; public static void Method(ref int x) => Console.WriteLine(OtherMethod(ref [|x|])); } }"; var expected = @"using System; namespace ClassLibrary9 { internal class ClassExtensions { public static int OtherMethod(ref int x) => x; public static void Method(ref int x) => Console.WriteLine(OtherMethod(ref $x$)); public static ref int NewMethod(ref int x) { return ref x; } } }"; await TestExtractMethodAsync(code, expected, temporaryFailing: true); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] [WorkItem(19958, "https://github.com/dotnet/roslyn/issues/19958")] public async Task TestExtractMethodRefPassThroughDuplicateVariable() { var code = @"using System; namespace ClassLibrary9 { internal interface IClass { bool InterfaceMethod(ref Guid x, out IOtherClass y); } internal interface IOtherClass { bool OtherInterfaceMethod(); } internal static class ClassExtensions { public static void Method(this IClass instance, Guid guid) { var r = instance.InterfaceMethod(ref [|guid|], out IOtherClass guid); if (!r) return; r = guid.OtherInterfaceMethod(); if (r) throw null; } } }"; var expected = @"using System; namespace ClassLibrary9 { internal interface IClass { bool InterfaceMethod(ref Guid x, out IOtherClass y); } internal interface IOtherClass { bool OtherInterfaceMethod(); } internal static class ClassExtensions { public static void Method(this IClass instance, Guid guid) { var r = instance.InterfaceMethod(ref NewMethod(ref guid), out IOtherClass guid); if (!r) return; r = guid.OtherInterfaceMethod(); if (r) throw null; } public static ref Guid NewMethod(ref Guid guid) { return ref guid; } } }"; await TestExtractMethodAsync(code, expected, temporaryFailing: true); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod_Argument1() { var service = new CSharpExtractMethodService(); Assert.NotNull(await Record.ExceptionAsync(async () => { var tree = await service.ExtractMethodAsync(null, default(TextSpan), null, CancellationToken.None); })); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public async Task ExtractMethod_Argument2() { var solution = new AdhocWorkspace().CurrentSolution; var projectId = ProjectId.CreateNewId(); var project = solution.AddProject(projectId, "Project", "Project.dll", LanguageNames.CSharp).GetProject(projectId); var document = project.AddMetadataReference(TestReferences.NetFx.v4_0_30319.mscorlib) .AddDocument("Document", SourceText.From("")); var service = new CSharpExtractMethodService() as IExtractMethodService; await service.ExtractMethodAsync(document, default(TextSpan)); } [WpfFact] [Trait(Traits.Feature, Traits.Features.ExtractMethod)] [Trait(Traits.Feature, Traits.Features.Interactive)] public void ExtractMethodCommandDisabledInSubmission() { var exportProvider = MinimalTestExportProvider.CreateExportProvider( TestExportProvider.EntireAssemblyCatalogWithCSharpAndVisualBasic.WithParts(typeof(InteractiveDocumentSupportsFeatureService))); using (var workspace = TestWorkspace.Create(XElement.Parse(@" <Workspace> <Submission Language=""C#"" CommonReferences=""true""> typeof(string).$$Name </Submission> </Workspace> "), workspaceKind: WorkspaceKind.Interactive, exportProvider: exportProvider)) { // Force initialization. workspace.GetOpenDocumentIds().Select(id => workspace.GetTestDocument(id).GetTextView()).ToList(); var textView = workspace.Documents.Single().GetTextView(); var handler = new ExtractMethodCommandHandler( workspace.GetService<ITextBufferUndoManagerProvider>(), workspace.GetService<IEditorOperationsFactoryService>(), workspace.GetService<IInlineRenameService>(), workspace.GetService<Host.IWaitIndicator>()); var delegatedToNext = false; Func<CommandState> nextHandler = () => { delegatedToNext = true; return CommandState.Unavailable; }; var state = handler.GetCommandState(new Commands.ExtractMethodCommandArgs(textView, textView.TextBuffer), nextHandler); Assert.True(delegatedToNext); Assert.False(state.IsAvailable); } } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] [WorkItem(18347, "https://github.com/dotnet/roslyn/issues/18347")] public async Task ExtractMethodUnreferencedLocalFunction1() { var code = @"namespace ExtractMethodCrashRepro { public static class SomeClass { private static void Repro( int arg ) { [|int localValue = arg;|] int LocalCapture() => arg; } } }"; var expected = @"namespace ExtractMethodCrashRepro { public static class SomeClass { private static void Repro( int arg ) { NewMethod(arg); int LocalCapture() => arg; } private static void NewMethod(int arg) { int localValue = arg; } } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] [WorkItem(18347, "https://github.com/dotnet/roslyn/issues/18347")] public async Task ExtractMethodUnreferencedLocalFunction2() { var code = @"namespace ExtractMethodCrashRepro { public static class SomeClass { private static void Repro( int arg ) { int LocalCapture() => arg; [|int localValue = arg;|] } } }"; var expected = @"namespace ExtractMethodCrashRepro { public static class SomeClass { private static void Repro( int arg ) { int LocalCapture() => arg; NewMethod(arg); } private static void NewMethod(int arg) { int localValue = arg; } } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] [WorkItem(18347, "https://github.com/dotnet/roslyn/issues/18347")] public async Task ExtractMethodUnreferencedLocalFunction3() { var code = @"namespace ExtractMethodCrashRepro { public static class SomeClass { private static void Repro( int arg ) { [|arg = arg + 3;|] int LocalCapture() => arg; } } }"; var expected = @"namespace ExtractMethodCrashRepro { public static class SomeClass { private static void Repro( int arg ) { NewMethod(arg); int LocalCapture() => arg; } private static void NewMethod(int arg) { arg = arg + 3; } } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] [WorkItem(18347, "https://github.com/dotnet/roslyn/issues/18347")] public async Task ExtractMethodUnreferencedLocalFunction4() { var code = @"namespace ExtractMethodCrashRepro { public static class SomeClass { private static void Repro( int arg ) { int LocalCapture() => arg; [|arg = arg + 3;|] } } }"; var expected = @"namespace ExtractMethodCrashRepro { public static class SomeClass { private static void Repro( int arg ) { int LocalCapture() => arg; NewMethod(arg); } private static void NewMethod(int arg) { arg = arg + 3; } } }"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] [WorkItem(18347, "https://github.com/dotnet/roslyn/issues/18347")] public async Task ExtractMethodUnreferencedLocalFunction5() { var code = @"namespace ExtractMethodCrashRepro { public static class SomeClass { private static void Repro( int arg ) { [|arg = arg + 3;|] arg = 1; int LocalCapture() => arg; } } }"; var expected = @"namespace ExtractMethodCrashRepro { public static class SomeClass { private static void Repro( int arg ) { NewMethod(arg); arg = 1; int LocalCapture() => arg; } private static void NewMethod(int arg) { arg = arg + 3; } } }"; await TestExtractMethodAsync(code, expected); } [Theory] [InlineData("LocalCapture();")] [InlineData("System.Func<int> function = LocalCapture;")] [InlineData("System.Func<int> function = () => LocalCapture();")] [Trait(Traits.Feature, Traits.Features.ExtractMethod)] [WorkItem(18347, "https://github.com/dotnet/roslyn/issues/18347")] public async Task ExtractMethodFlowsToLocalFunction1(string usageSyntax) { var code = $@"namespace ExtractMethodCrashRepro {{ public static class SomeClass {{ private static void Repro( int arg ) {{ [|arg = arg + 3;|] {usageSyntax} int LocalCapture() => arg; }} }} }}"; var expected = $@"namespace ExtractMethodCrashRepro {{ public static class SomeClass {{ private static void Repro( int arg ) {{ arg = NewMethod(arg); {usageSyntax} int LocalCapture() => arg; }} private static int NewMethod(int arg) {{ arg = arg + 3; return arg; }} }} }}"; await TestExtractMethodAsync(code, expected); } [Theory] [InlineData("LocalCapture();")] [InlineData("System.Func<int> function = LocalCapture;")] [InlineData("System.Func<int> function = () => LocalCapture();")] [Trait(Traits.Feature, Traits.Features.ExtractMethod)] [WorkItem(18347, "https://github.com/dotnet/roslyn/issues/18347")] public async Task ExtractMethodFlowsToLocalFunction2(string usageSyntax) { var code = $@"namespace ExtractMethodCrashRepro {{ public static class SomeClass {{ private static void Repro( int arg ) {{ int LocalCapture() => arg; [|arg = arg + 3;|] {usageSyntax} }} }} }}"; var expected = $@"namespace ExtractMethodCrashRepro {{ public static class SomeClass {{ private static void Repro( int arg ) {{ int LocalCapture() => arg; arg = NewMethod(arg); {usageSyntax} }} private static int NewMethod(int arg) {{ arg = arg + 3; return arg; }} }} }}"; await TestExtractMethodAsync(code, expected); } /// <summary> /// This test verifies that Extract Method works properly when the region to extract references a local /// function, the local function uses an unassigned but wholly local variable. /// </summary> [Theory] [InlineData("LocalCapture();")] [InlineData("System.Func<int> function = LocalCapture;")] [InlineData("System.Func<int> function = () => LocalCapture();")] [Trait(Traits.Feature, Traits.Features.ExtractMethod)] [WorkItem(18347, "https://github.com/dotnet/roslyn/issues/18347")] public async Task ExtractMethodFlowsToLocalFunctionWithUnassignedLocal(string usageSyntax) { var code = $@"namespace ExtractMethodCrashRepro {{ public static class SomeClass {{ private static void Repro( int arg ) {{ int local; int LocalCapture() => arg + local; [|arg = arg + 3;|] {usageSyntax} }} }} }}"; var expected = $@"namespace ExtractMethodCrashRepro {{ public static class SomeClass {{ private static void Repro( int arg ) {{ int local; int LocalCapture() => arg + local; arg = NewMethod(arg); {usageSyntax} }} private static int NewMethod(int arg) {{ arg = arg + 3; return arg; }} }} }}"; await TestExtractMethodAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] [WorkItem(18347, "https://github.com/dotnet/roslyn/issues/18347")] public async Task ExtractMethodDoesNotFlowToLocalFunction1() { var code = @"namespace ExtractMethodCrashRepro { public static class SomeClass { private static void Repro( int arg ) { [|arg = arg + 3;|] arg = 1; int LocalCapture() => arg; } } }"; var expected = @"namespace ExtractMethodCrashRepro { public static class SomeClass { private static void Repro( int arg ) { NewMethod(arg); arg = 1; int LocalCapture() => arg; } private static void NewMethod(int arg) { arg = arg + 3; } } }"; await TestExtractMethodAsync(code, expected); } } }
kelltrick/roslyn
src/EditorFeatures/CSharpTest/ExtractMethod/ExtractMethodTests.cs
C#
apache-2.0
210,991
//------------------------------------------------------------------------------ // <自动生成> // 此代码由工具生成。 // // 对此文件的更改可能导致不正确的行为,如果 // 重新生成代码,则所做更改将丢失。 // </自动生成> //------------------------------------------------------------------------------ namespace News { public partial class NewsEdit { /// <summary> /// tbTitle 控件。 /// </summary> /// <remarks> /// 自动生成的字段。 /// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。 /// </remarks> protected global::System.Web.UI.WebControls.TextBox tbTitle; /// <summary> /// ddlSort 控件。 /// </summary> /// <remarks> /// 自动生成的字段。 /// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。 /// </remarks> protected global::System.Web.UI.WebControls.DropDownList ddlSort; /// <summary> /// CKEditorControl1 控件。 /// </summary> /// <remarks> /// 自动生成的字段。 /// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。 /// </remarks> protected global::CKEditor.NET.CKEditorControl CKEditorControl1; /// <summary> /// btnSave 控件。 /// </summary> /// <remarks> /// 自动生成的字段。 /// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。 /// </remarks> protected global::System.Web.UI.WebControls.Button btnSave; /// <summary> /// btnBack 控件。 /// </summary> /// <remarks> /// 自动生成的字段。 /// 若要进行修改,请将字段声明从设计器文件移到代码隐藏文件。 /// </remarks> protected global::System.Web.UI.WebControls.Button btnBack; } }
Rangowj/NewsSystem
News/News/NewsEdit.aspx.designer.cs
C#
apache-2.0
2,172
//- Copyright 2013 the Neutrino authors (see AUTHORS). //- Licensed under the Apache License, Version 2.0 (see LICENSE). #ifndef _RUNTIME_INL #define _RUNTIME_INL #include "runtime.h" // Expands to the body of a safe_ function that works by calling a delegate and // if it fails garbage collecting and trying again once. #define RETRY_ONCE_IMPL(RUNTIME, DELEGATE) do { \ __GENERIC_RETRY_DEF__(P_FLAVOR, RUNTIME, value, DELEGATE, P_RETURN); \ return value; \ } while (false) #endif // _RUNTIME_INL
tundra/neutrino
src/c/runtime-inl.h
C
apache-2.0
608
# Strobilanthes perplexa J.R.I.Wood SPECIES #### Status ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Lamiales/Acanthaceae/Strobilanthes/Strobilanthes perplexa/README.md
Markdown
apache-2.0
183
/* * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.provider; import com.google.android.apps.iosched.provider.ScheduleContract.Blocks; import com.google.android.apps.iosched.provider.ScheduleContract.Notes; import com.google.android.apps.iosched.provider.ScheduleContract.Rooms; import com.google.android.apps.iosched.provider.ScheduleContract.SearchSuggest; import com.google.android.apps.iosched.provider.ScheduleContract.Sessions; import com.google.android.apps.iosched.provider.ScheduleContract.Speakers; import com.google.android.apps.iosched.provider.ScheduleContract.Tracks; import com.google.android.apps.iosched.provider.ScheduleContract.Vendors; import com.google.android.apps.iosched.provider.ScheduleDatabase.SessionsSearchColumns; import com.google.android.apps.iosched.provider.ScheduleDatabase.SessionsSpeakers; import com.google.android.apps.iosched.provider.ScheduleDatabase.SessionsTracks; import com.google.android.apps.iosched.provider.ScheduleDatabase.Tables; import com.google.android.apps.iosched.provider.ScheduleDatabase.VendorsSearchColumns; import com.google.android.apps.iosched.util.NotesExporter; import com.google.android.apps.iosched.util.SelectionBuilder; import android.app.Activity; import android.app.SearchManager; import android.content.ContentProvider; import android.content.ContentProviderOperation; import android.content.ContentProviderResult; import android.content.ContentUris; import android.content.ContentValues; import android.content.Context; import android.content.OperationApplicationException; import android.content.UriMatcher; import android.database.Cursor; import android.database.MatrixCursor; import android.database.sqlite.SQLiteDatabase; import android.net.Uri; import android.os.ParcelFileDescriptor; import android.provider.BaseColumns; import android.provider.OpenableColumns; import android.util.Log; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import net.bespokesystems.android.apps.wicsa2011.de.service.SyncService; /** * Provider that stores {@link ScheduleContract} data. Data is usually inserted * by {@link SyncService}, and queried by various {@link Activity} instances. */ public class ScheduleProvider extends ContentProvider { private static final String TAG = "ScheduleProvider"; private static final boolean LOGV = Log.isLoggable(TAG, Log.VERBOSE); private ScheduleDatabase mOpenHelper; private static final UriMatcher sUriMatcher = buildUriMatcher(); private static final int BLOCKS = 100; private static final int BLOCKS_BETWEEN = 101; private static final int BLOCKS_ID = 102; private static final int BLOCKS_ID_SESSIONS = 103; private static final int TRACKS = 200; private static final int TRACKS_ID = 201; private static final int TRACKS_ID_SESSIONS = 202; private static final int TRACKS_ID_VENDORS = 203; private static final int ROOMS = 300; private static final int ROOMS_ID = 301; private static final int ROOMS_ID_SESSIONS = 302; private static final int SESSIONS = 400; private static final int SESSIONS_STARRED = 401; private static final int SESSIONS_SEARCH = 402; private static final int SESSIONS_AT = 403; private static final int SESSIONS_ID = 404; private static final int SESSIONS_ID_SPEAKERS = 405; private static final int SESSIONS_ID_TRACKS = 406; private static final int SESSIONS_ID_NOTES = 407; private static final int SPEAKERS = 500; private static final int SPEAKERS_ID = 501; private static final int SPEAKERS_ID_SESSIONS = 502; private static final int VENDORS = 600; private static final int VENDORS_STARRED = 601; private static final int VENDORS_SEARCH = 603; private static final int VENDORS_ID = 604; private static final int NOTES = 700; private static final int NOTES_EXPORT = 701; private static final int NOTES_ID = 702; private static final int SEARCH_SUGGEST = 800; private static final String MIME_XML = "text/xml"; /** * Build and return a {@link UriMatcher} that catches all {@link Uri} * variations supported by this {@link ContentProvider}. */ private static UriMatcher buildUriMatcher() { final UriMatcher matcher = new UriMatcher(UriMatcher.NO_MATCH); final String authority = ScheduleContract.CONTENT_AUTHORITY; matcher.addURI(authority, "blocks", BLOCKS); matcher.addURI(authority, "blocks/between/*/*", BLOCKS_BETWEEN); matcher.addURI(authority, "blocks/*", BLOCKS_ID); matcher.addURI(authority, "blocks/*/sessions", BLOCKS_ID_SESSIONS); matcher.addURI(authority, "tracks", TRACKS); matcher.addURI(authority, "tracks/*", TRACKS_ID); matcher.addURI(authority, "tracks/*/sessions", TRACKS_ID_SESSIONS); matcher.addURI(authority, "tracks/*/vendors", TRACKS_ID_VENDORS); matcher.addURI(authority, "rooms", ROOMS); matcher.addURI(authority, "rooms/*", ROOMS_ID); matcher.addURI(authority, "rooms/*/sessions", ROOMS_ID_SESSIONS); matcher.addURI(authority, "sessions", SESSIONS); matcher.addURI(authority, "sessions/starred", SESSIONS_STARRED); matcher.addURI(authority, "sessions/search/*", SESSIONS_SEARCH); matcher.addURI(authority, "sessions/at/*", SESSIONS_AT); matcher.addURI(authority, "sessions/*", SESSIONS_ID); matcher.addURI(authority, "sessions/*/speakers", SESSIONS_ID_SPEAKERS); matcher.addURI(authority, "sessions/*/tracks", SESSIONS_ID_TRACKS); matcher.addURI(authority, "sessions/*/notes", SESSIONS_ID_NOTES); matcher.addURI(authority, "speakers", SPEAKERS); matcher.addURI(authority, "speakers/*", SPEAKERS_ID); matcher.addURI(authority, "speakers/*/sessions", SPEAKERS_ID_SESSIONS); matcher.addURI(authority, "vendors", VENDORS); matcher.addURI(authority, "vendors/starred", VENDORS_STARRED); matcher.addURI(authority, "vendors/search/*", VENDORS_SEARCH); matcher.addURI(authority, "vendors/*", VENDORS_ID); matcher.addURI(authority, "notes", NOTES); matcher.addURI(authority, "notes/export", NOTES_EXPORT); matcher.addURI(authority, "notes/*", NOTES_ID); matcher.addURI(authority, "search_suggest_query", SEARCH_SUGGEST); return matcher; } @Override public boolean onCreate() { final Context context = getContext(); mOpenHelper = new ScheduleDatabase(context); return true; } /** {@inheritDoc} */ @Override public String getType(Uri uri) { final int match = sUriMatcher.match(uri); switch (match) { case BLOCKS: return Blocks.CONTENT_TYPE; case BLOCKS_BETWEEN: return Blocks.CONTENT_TYPE; case BLOCKS_ID: return Blocks.CONTENT_ITEM_TYPE; case BLOCKS_ID_SESSIONS: return Sessions.CONTENT_TYPE; case TRACKS: return Tracks.CONTENT_TYPE; case TRACKS_ID: return Tracks.CONTENT_ITEM_TYPE; case TRACKS_ID_SESSIONS: return Sessions.CONTENT_TYPE; case TRACKS_ID_VENDORS: return Vendors.CONTENT_TYPE; case ROOMS: return Rooms.CONTENT_TYPE; case ROOMS_ID: return Rooms.CONTENT_ITEM_TYPE; case ROOMS_ID_SESSIONS: return Sessions.CONTENT_TYPE; case SESSIONS: return Sessions.CONTENT_TYPE; case SESSIONS_STARRED: return Sessions.CONTENT_TYPE; case SESSIONS_SEARCH: return Sessions.CONTENT_TYPE; case SESSIONS_AT: return Sessions.CONTENT_TYPE; case SESSIONS_ID: return Sessions.CONTENT_ITEM_TYPE; case SESSIONS_ID_SPEAKERS: return Speakers.CONTENT_TYPE; case SESSIONS_ID_TRACKS: return Tracks.CONTENT_TYPE; case SESSIONS_ID_NOTES: return Notes.CONTENT_TYPE; case SPEAKERS: return Speakers.CONTENT_TYPE; case SPEAKERS_ID: return Speakers.CONTENT_ITEM_TYPE; case SPEAKERS_ID_SESSIONS: return Sessions.CONTENT_TYPE; case VENDORS: return Vendors.CONTENT_TYPE; case VENDORS_STARRED: return Vendors.CONTENT_TYPE; case VENDORS_SEARCH: return Vendors.CONTENT_TYPE; case VENDORS_ID: return Vendors.CONTENT_ITEM_TYPE; case NOTES: return Notes.CONTENT_TYPE; case NOTES_EXPORT: return MIME_XML; case NOTES_ID: return Notes.CONTENT_ITEM_TYPE; default: throw new UnsupportedOperationException("Unknown uri: " + uri); } } /** {@inheritDoc} */ @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { if (LOGV) Log.v(TAG, "query(uri=" + uri + ", proj=" + Arrays.toString(projection) + ")"); final SQLiteDatabase db = mOpenHelper.getReadableDatabase(); final int match = sUriMatcher.match(uri); switch (match) { default: { // Most cases are handled with simple SelectionBuilder final SelectionBuilder builder = buildExpandedSelection(uri, match); return builder.where(selection, selectionArgs).query(db, projection, sortOrder); } case NOTES_EXPORT: { // Provide query values for file attachments final String[] columns = { OpenableColumns.DISPLAY_NAME, OpenableColumns.SIZE }; final MatrixCursor cursor = new MatrixCursor(columns, 1); cursor.addRow(new String[] { "notes.xml", null }); return cursor; } case SEARCH_SUGGEST: { final SelectionBuilder builder = new SelectionBuilder(); // Adjust incoming query to become SQL text match selectionArgs[0] = selectionArgs[0] + "%"; builder.table(Tables.SEARCH_SUGGEST); builder.where(selection, selectionArgs); builder.map(SearchManager.SUGGEST_COLUMN_QUERY, SearchManager.SUGGEST_COLUMN_TEXT_1); projection = new String[] { BaseColumns._ID, SearchManager.SUGGEST_COLUMN_TEXT_1, SearchManager.SUGGEST_COLUMN_QUERY }; final String limit = uri.getQueryParameter(SearchManager.SUGGEST_PARAMETER_LIMIT); return builder.query(db, projection, null, null, SearchSuggest.DEFAULT_SORT, limit); } } } /** {@inheritDoc} */ @Override public Uri insert(Uri uri, ContentValues values) { if (LOGV) Log.v(TAG, "insert(uri=" + uri + ", values=" + values.toString() + ")"); final SQLiteDatabase db = mOpenHelper.getWritableDatabase(); final int match = sUriMatcher.match(uri); switch (match) { case BLOCKS: { db.insertOrThrow(Tables.BLOCKS, null, values); return Blocks.buildBlockUri(values.getAsString(Blocks.BLOCK_ID)); } case TRACKS: { db.insertOrThrow(Tables.TRACKS, null, values); return Tracks.buildTrackUri(values.getAsString(Tracks.TRACK_ID)); } case ROOMS: { db.insertOrThrow(Tables.ROOMS, null, values); return Rooms.buildRoomUri(values.getAsString(Rooms.ROOM_ID)); } case SESSIONS: { db.insertOrThrow(Tables.SESSIONS, null, values); return Sessions.buildSessionUri(values.getAsString(Sessions.SESSION_ID)); } case SESSIONS_ID_SPEAKERS: { db.insertOrThrow(Tables.SESSIONS_SPEAKERS, null, values); return Speakers.buildSpeakerUri(values.getAsString(SessionsSpeakers.SPEAKER_ID)); } case SESSIONS_ID_TRACKS: { db.insertOrThrow(Tables.SESSIONS_TRACKS, null, values); return Tracks.buildTrackUri(values.getAsString(SessionsTracks.TRACK_ID)); } case SESSIONS_ID_NOTES: { final String sessionId = Sessions.getSessionId(uri); values.put(Notes.SESSION_ID, sessionId); final long noteId = db.insertOrThrow(Tables.NOTES, null, values); return ContentUris.withAppendedId(Notes.CONTENT_URI, noteId); } case SPEAKERS: { db.insertOrThrow(Tables.SPEAKERS, null, values); return Speakers.buildSpeakerUri(values.getAsString(Speakers.SPEAKER_ID)); } case VENDORS: { db.insertOrThrow(Tables.VENDORS, null, values); return Vendors.buildVendorUri(values.getAsString(Vendors.VENDOR_ID)); } case NOTES: { final long noteId = db.insertOrThrow(Tables.NOTES, null, values); return ContentUris.withAppendedId(Notes.CONTENT_URI, noteId); } case SEARCH_SUGGEST: { db.insertOrThrow(Tables.SEARCH_SUGGEST, null, values); return SearchSuggest.CONTENT_URI; } default: { throw new UnsupportedOperationException("Unknown uri: " + uri); } } } /** {@inheritDoc} */ @Override public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { if (LOGV) Log.v(TAG, "update(uri=" + uri + ", values=" + values.toString() + ")"); final SQLiteDatabase db = mOpenHelper.getWritableDatabase(); final SelectionBuilder builder = buildSimpleSelection(uri); return builder.where(selection, selectionArgs).update(db, values); } /** {@inheritDoc} */ @Override public int delete(Uri uri, String selection, String[] selectionArgs) { if (LOGV) Log.v(TAG, "delete(uri=" + uri + ")"); final SQLiteDatabase db = mOpenHelper.getWritableDatabase(); final SelectionBuilder builder = buildSimpleSelection(uri); return builder.where(selection, selectionArgs).delete(db); } /** * Apply the given set of {@link ContentProviderOperation}, executing inside * a {@link SQLiteDatabase} transaction. All changes will be rolled back if * any single one fails. */ @Override public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations) throws OperationApplicationException { final SQLiteDatabase db = mOpenHelper.getWritableDatabase(); db.beginTransaction(); try { final int numOperations = operations.size(); final ContentProviderResult[] results = new ContentProviderResult[numOperations]; for (int i = 0; i < numOperations; i++) { results[i] = operations.get(i).apply(this, results, i); } db.setTransactionSuccessful(); return results; } finally { db.endTransaction(); } } /** * Build a simple {@link SelectionBuilder} to match the requested * {@link Uri}. This is usually enough to support {@link #insert}, * {@link #update}, and {@link #delete} operations. */ private SelectionBuilder buildSimpleSelection(Uri uri) { final SelectionBuilder builder = new SelectionBuilder(); final int match = sUriMatcher.match(uri); switch (match) { case BLOCKS: { return builder.table(Tables.BLOCKS); } case BLOCKS_ID: { final String blockId = Blocks.getBlockId(uri); return builder.table(Tables.BLOCKS) .where(Blocks.BLOCK_ID + "=?", blockId); } case TRACKS: { return builder.table(Tables.TRACKS); } case TRACKS_ID: { final String trackId = Tracks.getTrackId(uri); return builder.table(Tables.TRACKS) .where(Tracks.TRACK_ID + "=?", trackId); } case ROOMS: { return builder.table(Tables.ROOMS); } case ROOMS_ID: { final String roomId = Rooms.getRoomId(uri); return builder.table(Tables.ROOMS) .where(Rooms.ROOM_ID + "=?", roomId); } case SESSIONS: { return builder.table(Tables.SESSIONS); } case SESSIONS_ID: { final String sessionId = Sessions.getSessionId(uri); return builder.table(Tables.SESSIONS) .where(Sessions.SESSION_ID + "=?", sessionId); } case SESSIONS_ID_SPEAKERS: { final String sessionId = Sessions.getSessionId(uri); return builder.table(Tables.SESSIONS_SPEAKERS) .where(Sessions.SESSION_ID + "=?", sessionId); } case SESSIONS_ID_TRACKS: { final String sessionId = Sessions.getSessionId(uri); return builder.table(Tables.SESSIONS_TRACKS) .where(Sessions.SESSION_ID + "=?", sessionId); } case SPEAKERS: { return builder.table(Tables.SPEAKERS); } case SPEAKERS_ID: { final String speakerId = Speakers.getSpeakerId(uri); return builder.table(Tables.SPEAKERS) .where(Speakers.SPEAKER_ID + "=?", speakerId); } case VENDORS: { return builder.table(Tables.VENDORS); } case VENDORS_ID: { final String vendorId = Vendors.getVendorId(uri); return builder.table(Tables.VENDORS) .where(Vendors.VENDOR_ID + "=?", vendorId); } case NOTES: { return builder.table(Tables.NOTES); } case NOTES_ID: { final String noteId = uri.getPathSegments().get(1); return builder.table(Tables.NOTES) .where(Notes._ID + "=?", noteId); } case SEARCH_SUGGEST: { return builder.table(Tables.SEARCH_SUGGEST); } default: { throw new UnsupportedOperationException("Unknown uri: " + uri); } } } /** * Build an advanced {@link SelectionBuilder} to match the requested * {@link Uri}. This is usually only used by {@link #query}, since it * performs table joins useful for {@link Cursor} data. */ private SelectionBuilder buildExpandedSelection(Uri uri, int match) { final SelectionBuilder builder = new SelectionBuilder(); switch (match) { case BLOCKS: { return builder.table(Tables.BLOCKS); } case BLOCKS_BETWEEN: { final List<String> segments = uri.getPathSegments(); final String startTime = segments.get(2); final String endTime = segments.get(3); return builder.table(Tables.BLOCKS) .map(Blocks.SESSIONS_COUNT, Subquery.BLOCK_SESSIONS_COUNT) .map(Blocks.CONTAINS_STARRED, Subquery.BLOCK_CONTAINS_STARRED) .where(Blocks.BLOCK_START + ">=?", startTime) .where(Blocks.BLOCK_START + "<=?", endTime); } case BLOCKS_ID: { final String blockId = Blocks.getBlockId(uri); return builder.table(Tables.BLOCKS) .map(Blocks.SESSIONS_COUNT, Subquery.BLOCK_SESSIONS_COUNT) .map(Blocks.CONTAINS_STARRED, Subquery.BLOCK_CONTAINS_STARRED) .where(Blocks.BLOCK_ID + "=?", blockId); } case BLOCKS_ID_SESSIONS: { final String blockId = Blocks.getBlockId(uri); return builder.table(Tables.SESSIONS_JOIN_BLOCKS_ROOMS) .map(Blocks.SESSIONS_COUNT, Subquery.BLOCK_SESSIONS_COUNT) .map(Blocks.CONTAINS_STARRED, Subquery.BLOCK_CONTAINS_STARRED) .mapToTable(Sessions._ID, Tables.SESSIONS) .mapToTable(Sessions.SESSION_ID, Tables.SESSIONS) .mapToTable(Sessions.BLOCK_ID, Tables.SESSIONS) .mapToTable(Sessions.ROOM_ID, Tables.SESSIONS) .where(Qualified.SESSIONS_BLOCK_ID + "=?", blockId); } case TRACKS: { return builder.table(Tables.TRACKS) .map(Tracks.SESSIONS_COUNT, Subquery.TRACK_SESSIONS_COUNT) .map(Tracks.VENDORS_COUNT, Subquery.TRACK_VENDORS_COUNT); } case TRACKS_ID: { final String trackId = Tracks.getTrackId(uri); return builder.table(Tables.TRACKS) .where(Tracks.TRACK_ID + "=?", trackId); } case TRACKS_ID_SESSIONS: { final String trackId = Tracks.getTrackId(uri); return builder.table(Tables.SESSIONS_TRACKS_JOIN_SESSIONS_BLOCKS_ROOMS) .mapToTable(Sessions._ID, Tables.SESSIONS) .mapToTable(Sessions.SESSION_ID, Tables.SESSIONS) .mapToTable(Sessions.BLOCK_ID, Tables.SESSIONS) .mapToTable(Sessions.ROOM_ID, Tables.SESSIONS) .where(Qualified.SESSIONS_TRACKS_TRACK_ID + "=?", trackId); } case TRACKS_ID_VENDORS: { final String trackId = Tracks.getTrackId(uri); return builder.table(Tables.VENDORS_JOIN_TRACKS) .mapToTable(Vendors._ID, Tables.VENDORS) .mapToTable(Vendors.TRACK_ID, Tables.VENDORS) .where(Qualified.VENDORS_TRACK_ID + "=?", trackId); } case ROOMS: { return builder.table(Tables.ROOMS); } case ROOMS_ID: { final String roomId = Rooms.getRoomId(uri); return builder.table(Tables.ROOMS) .where(Rooms.ROOM_ID + "=?", roomId); } case ROOMS_ID_SESSIONS: { final String roomId = Rooms.getRoomId(uri); return builder.table(Tables.SESSIONS_JOIN_BLOCKS_ROOMS) .mapToTable(Sessions._ID, Tables.SESSIONS) .mapToTable(Sessions.BLOCK_ID, Tables.SESSIONS) .mapToTable(Sessions.ROOM_ID, Tables.SESSIONS) .where(Qualified.SESSIONS_ROOM_ID + "=?", roomId); } case SESSIONS: { return builder.table(Tables.SESSIONS_JOIN_BLOCKS_ROOMS) .mapToTable(Sessions._ID, Tables.SESSIONS) .mapToTable(Sessions.BLOCK_ID, Tables.SESSIONS) .mapToTable(Sessions.ROOM_ID, Tables.SESSIONS); } case SESSIONS_STARRED: { return builder.table(Tables.SESSIONS_JOIN_BLOCKS_ROOMS) .mapToTable(Sessions._ID, Tables.SESSIONS) .mapToTable(Sessions.BLOCK_ID, Tables.SESSIONS) .mapToTable(Sessions.ROOM_ID, Tables.SESSIONS) .where(Sessions.STARRED + "=1"); } case SESSIONS_SEARCH: { final String query = Sessions.getSearchQuery(uri); return builder.table(Tables.SESSIONS_SEARCH_JOIN_SESSIONS_BLOCKS_ROOMS) .map(Sessions.SEARCH_SNIPPET, Subquery.SESSIONS_SNIPPET) .mapToTable(Sessions._ID, Tables.SESSIONS) .mapToTable(Sessions.SESSION_ID, Tables.SESSIONS) .mapToTable(Sessions.BLOCK_ID, Tables.SESSIONS) .mapToTable(Sessions.ROOM_ID, Tables.SESSIONS) .where(SessionsSearchColumns.BODY + " MATCH ?", query); } case SESSIONS_AT: { final List<String> segments = uri.getPathSegments(); final String time = segments.get(2); return builder.table(Tables.SESSIONS_JOIN_BLOCKS_ROOMS) .mapToTable(Sessions._ID, Tables.SESSIONS) .mapToTable(Sessions.BLOCK_ID, Tables.SESSIONS) .mapToTable(Sessions.ROOM_ID, Tables.SESSIONS) .where(Sessions.BLOCK_START + "<=?", time) .where(Sessions.BLOCK_END + ">=?", time); } case SESSIONS_ID: { final String sessionId = Sessions.getSessionId(uri); return builder.table(Tables.SESSIONS_JOIN_BLOCKS_ROOMS) .mapToTable(Sessions._ID, Tables.SESSIONS) .mapToTable(Sessions.BLOCK_ID, Tables.SESSIONS) .mapToTable(Sessions.ROOM_ID, Tables.SESSIONS) .where(Qualified.SESSIONS_SESSION_ID + "=?", sessionId); } case SESSIONS_ID_SPEAKERS: { final String sessionId = Sessions.getSessionId(uri); return builder.table(Tables.SESSIONS_SPEAKERS_JOIN_SPEAKERS) .mapToTable(Speakers._ID, Tables.SPEAKERS) .mapToTable(Speakers.SPEAKER_ID, Tables.SPEAKERS) .where(Qualified.SESSIONS_SPEAKERS_SESSION_ID + "=?", sessionId); } case SESSIONS_ID_TRACKS: { final String sessionId = Sessions.getSessionId(uri); return builder.table(Tables.SESSIONS_TRACKS_JOIN_TRACKS) .mapToTable(Tracks._ID, Tables.TRACKS) .mapToTable(Tracks.TRACK_ID, Tables.TRACKS) .where(Qualified.SESSIONS_TRACKS_SESSION_ID + "=?", sessionId); } case SESSIONS_ID_NOTES: { final String sessionId = Sessions.getSessionId(uri); return builder.table(Tables.NOTES) .where(Notes.SESSION_ID + "=?", sessionId); } case SPEAKERS: { return builder.table(Tables.SPEAKERS); } case SPEAKERS_ID: { final String speakerId = Speakers.getSpeakerId(uri); return builder.table(Tables.SPEAKERS) .where(Speakers.SPEAKER_ID + "=?", speakerId); } case SPEAKERS_ID_SESSIONS: { final String speakerId = Speakers.getSpeakerId(uri); return builder.table(Tables.SESSIONS_SPEAKERS_JOIN_SESSIONS_BLOCKS_ROOMS) .mapToTable(Sessions._ID, Tables.SESSIONS) .mapToTable(Sessions.SESSION_ID, Tables.SESSIONS) .mapToTable(Sessions.BLOCK_ID, Tables.SESSIONS) .mapToTable(Sessions.ROOM_ID, Tables.SESSIONS) .where(Qualified.SESSIONS_SPEAKERS_SPEAKER_ID + "=?", speakerId); } case VENDORS: { return builder.table(Tables.VENDORS_JOIN_TRACKS) .mapToTable(Vendors._ID, Tables.VENDORS) .mapToTable(Vendors.TRACK_ID, Tables.VENDORS); } case VENDORS_STARRED: { return builder.table(Tables.VENDORS_JOIN_TRACKS) .mapToTable(Vendors._ID, Tables.VENDORS) .mapToTable(Vendors.TRACK_ID, Tables.VENDORS) .where(Vendors.STARRED + "=1"); } case VENDORS_SEARCH: { final String query = Vendors.getSearchQuery(uri); return builder.table(Tables.VENDORS_SEARCH_JOIN_VENDORS_TRACKS) .map(Vendors.SEARCH_SNIPPET, Subquery.VENDORS_SNIPPET) .mapToTable(Vendors._ID, Tables.VENDORS) .mapToTable(Vendors.VENDOR_ID, Tables.VENDORS) .mapToTable(Vendors.TRACK_ID, Tables.VENDORS) .where(VendorsSearchColumns.BODY + " MATCH ?", query); } case VENDORS_ID: { final String vendorId = Vendors.getVendorId(uri); return builder.table(Tables.VENDORS_JOIN_TRACKS) .mapToTable(Vendors._ID, Tables.VENDORS) .mapToTable(Vendors.TRACK_ID, Tables.VENDORS) .where(Vendors.VENDOR_ID + "=?", vendorId); } case NOTES: { return builder.table(Tables.NOTES); } case NOTES_ID: { final long noteId = Notes.getNoteId(uri); return builder.table(Tables.NOTES) .where(Notes._ID + "=?", Long.toString(noteId)); } default: { throw new UnsupportedOperationException("Unknown uri: " + uri); } } } @Override public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException { final int match = sUriMatcher.match(uri); switch (match) { case NOTES_EXPORT: { try { final File notesFile = NotesExporter.writeExportedNotes(getContext()); return ParcelFileDescriptor .open(notesFile, ParcelFileDescriptor.MODE_READ_ONLY); } catch (IOException e) { throw new FileNotFoundException("Unable to export notes: " + e.toString()); } } default: { throw new UnsupportedOperationException("Unknown uri: " + uri); } } } private interface Subquery { String BLOCK_SESSIONS_COUNT = "(SELECT COUNT(" + Qualified.SESSIONS_SESSION_ID + ") FROM " + Tables.SESSIONS + " WHERE " + Qualified.SESSIONS_BLOCK_ID + "=" + Qualified.BLOCKS_BLOCK_ID + ")"; String BLOCK_CONTAINS_STARRED = "(SELECT MAX(" + Qualified.SESSIONS_STARRED + ") FROM " + Tables.SESSIONS + " WHERE " + Qualified.SESSIONS_BLOCK_ID + "=" + Qualified.BLOCKS_BLOCK_ID + ")"; String TRACK_SESSIONS_COUNT = "(SELECT COUNT(" + Qualified.SESSIONS_TRACKS_SESSION_ID + ") FROM " + Tables.SESSIONS_TRACKS + " WHERE " + Qualified.SESSIONS_TRACKS_TRACK_ID + "=" + Qualified.TRACKS_TRACK_ID + ")"; String TRACK_VENDORS_COUNT = "(SELECT COUNT(" + Qualified.VENDORS_VENDOR_ID + ") FROM " + Tables.VENDORS + " WHERE " + Qualified.VENDORS_TRACK_ID + "=" + Qualified.TRACKS_TRACK_ID + ")"; String SESSIONS_SNIPPET = "snippet(" + Tables.SESSIONS_SEARCH + ",'{','}','\u2026')"; String VENDORS_SNIPPET = "snippet(" + Tables.VENDORS_SEARCH + ",'{','}','\u2026')"; } /** * {@link ScheduleContract} fields that are fully qualified with a specific * parent {@link Tables}. Used when needed to work around SQL ambiguity. */ private interface Qualified { String SESSIONS_SESSION_ID = Tables.SESSIONS + "." + Sessions.SESSION_ID; String SESSIONS_BLOCK_ID = Tables.SESSIONS + "." + Sessions.BLOCK_ID; String SESSIONS_ROOM_ID = Tables.SESSIONS + "." + Sessions.ROOM_ID; String SESSIONS_TRACKS_SESSION_ID = Tables.SESSIONS_TRACKS + "." + SessionsTracks.SESSION_ID; String SESSIONS_TRACKS_TRACK_ID = Tables.SESSIONS_TRACKS + "." + SessionsTracks.TRACK_ID; String SESSIONS_SPEAKERS_SESSION_ID = Tables.SESSIONS_SPEAKERS + "." + SessionsSpeakers.SESSION_ID; String SESSIONS_SPEAKERS_SPEAKER_ID = Tables.SESSIONS_SPEAKERS + "." + SessionsSpeakers.SPEAKER_ID; String VENDORS_VENDOR_ID = Tables.VENDORS + "." + Vendors.VENDOR_ID; String VENDORS_TRACK_ID = Tables.VENDORS + "." + Vendors.TRACK_ID; @SuppressWarnings("hiding") String SESSIONS_STARRED = Tables.SESSIONS + "." + Sessions.STARRED; String TRACKS_TRACK_ID = Tables.TRACKS + "." + Tracks.TRACK_ID; String BLOCKS_BLOCK_ID = Tables.BLOCKS + "." + Blocks.BLOCK_ID; } }
ghchinoy/wicsa2011
src/com/google/android/apps/iosched/provider/ScheduleProvider.java
Java
apache-2.0
33,646
# dtstructs [![Build Status](https://travis-ci.org/mbe24/dtstructs.svg?branch=master)](https://travis-ci.org/mbe24/dtstructs) [![License Info](http://img.shields.io/badge/license-Apache%20License%20v2.0-orange.svg)](https://raw.githubusercontent.com/mbe24/jcurry/master/LICENSE) =========== C++ Data Structures -------------------
mbe24/dtstructs
README.md
Markdown
apache-2.0
330
/* * Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.inspector.model; import com.amazonaws.AmazonServiceException; /** * */ public class NoSuchEntityException extends AmazonServiceException { private static final long serialVersionUID = 1L; /** * Constructs a new NoSuchEntityException with the specified error message. * * @param message * Describes the error encountered. */ public NoSuchEntityException(String message) { super(message); } }
trasa/aws-sdk-java
aws-java-sdk-inspector/src/main/java/com/amazonaws/services/inspector/model/NoSuchEntityException.java
Java
apache-2.0
1,070
/* * Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.dataexchange.model; import java.io.Serializable; import javax.annotation.Generated; import com.amazonaws.AmazonWebServiceRequest; /** * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/dataexchange-2017-07-25/DeleteEventAction" target="_top">AWS API * Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class DeleteEventActionRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable { /** * <p> * The unique identifier for the event action. * </p> */ private String eventActionId; /** * <p> * The unique identifier for the event action. * </p> * * @param eventActionId * The unique identifier for the event action. */ public void setEventActionId(String eventActionId) { this.eventActionId = eventActionId; } /** * <p> * The unique identifier for the event action. * </p> * * @return The unique identifier for the event action. */ public String getEventActionId() { return this.eventActionId; } /** * <p> * The unique identifier for the event action. * </p> * * @param eventActionId * The unique identifier for the event action. * @return Returns a reference to this object so that method calls can be chained together. */ public DeleteEventActionRequest withEventActionId(String eventActionId) { setEventActionId(eventActionId); return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getEventActionId() != null) sb.append("EventActionId: ").append(getEventActionId()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof DeleteEventActionRequest == false) return false; DeleteEventActionRequest other = (DeleteEventActionRequest) obj; if (other.getEventActionId() == null ^ this.getEventActionId() == null) return false; if (other.getEventActionId() != null && other.getEventActionId().equals(this.getEventActionId()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getEventActionId() == null) ? 0 : getEventActionId().hashCode()); return hashCode; } @Override public DeleteEventActionRequest clone() { return (DeleteEventActionRequest) super.clone(); } }
aws/aws-sdk-java
aws-java-sdk-dataexchange/src/main/java/com/amazonaws/services/dataexchange/model/DeleteEventActionRequest.java
Java
apache-2.0
3,714
# Daedalea microzona Lév., 1846 SPECIES #### Status SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in Annls Sci. Nat. , Bot. , sér. 3 5: 142 (1846) #### Original name Daedalea microzona Lév., 1846 ### Remarks null
mdoering/backbone
life/Fungi/Basidiomycota/Agaricomycetes/Polyporales/Fomitopsidaceae/Daedalea/Daedalea flavida/ Syn. Daedalea microzona/README.md
Markdown
apache-2.0
255
/******************************************************************************* * Copyright 2017 Xoriant Corporation. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ /* * Doctor Appointment * Appointment * * OpenAPI spec version: 1.0.0 * * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ package io.swagger.client.api; import io.swagger.client.ApiException; import io.swagger.client.model.Payload; import org.junit.Test; import org.junit.Ignore; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * API tests for DefaultApi */ @Ignore public class DefaultApiTest { private final DefaultApi api = new DefaultApi(); /** * Post new Doctor info * * endpoint for posting a newly created Doctor entity to the server * * @throws ApiException * if the Api call fails */ @Test public void createDoctorTest() throws ApiException { Payload payload = null; api.createDoctor(payload); // TODO: test validations } }
XoriantOpenSource/swagger-blog-examples
swagger-blog-2/java-client/src/test/java/io/swagger/client/api/DefaultApiTest.java
Java
apache-2.0
1,849
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Linq; using System.Text; using System.Windows.Forms; namespace com.huawei.ebg.esdk.ucsdk.client.control { public partial class DialCall : Button { public DialCall() { InitializeComponent(); } # region 自定义字段 private string _ucAccount; [Description("被叫UC帐号")] public string UCAccount { get { return _ucAccount; } set { _ucAccount = value; } } private string _calledNumber; [Description("被叫号码")] public string CalledNumber { get { return _calledNumber; } set { _calledNumber = value; } } # endregion protected override void OnClick(EventArgs e) { base.OnClick(e); try { CtrlBusiness.DirectCall(_ucAccount, _calledNumber); } catch (Exception ex) { //throw ex; } } } }
eSDK/esdk_uc_control_net
com.huawei.ebg.esdk.ucsdk.client.control/Client Control/DialCall.cs
C#
apache-2.0
1,163
/* * ============================================================================= * * Copyright (c) 2011-2016, The THYMELEAF team (http://www.thymeleaf.org) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * ============================================================================= */ package org.thymeleaf.dialect.dialectwrapping; import org.thymeleaf.context.ITemplateContext; import org.thymeleaf.model.IModel; import org.thymeleaf.processor.element.AbstractElementModelProcessor; import org.thymeleaf.processor.element.IElementModelStructureHandler; import org.thymeleaf.templatemode.TemplateMode; public class ElementModelProcessor extends AbstractElementModelProcessor { public ElementModelProcessor(final String dialectPrefix) { super(TemplateMode.HTML, dialectPrefix, "div", true, null, false, 100); } @Override protected void doProcess(final ITemplateContext context, final IModel model, final IElementModelStructureHandler structureHandler) { } }
thymeleaf/thymeleaf-tests
src/test/java/org/thymeleaf/dialect/dialectwrapping/ElementModelProcessor.java
Java
apache-2.0
1,538
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyTitle("Accela.WindowsStoreSDK")] [assembly: AssemblyDescription("Accela SDK for Windows & Windows Phone")] [assembly: AssemblyCompany("Accela Inc.")] [assembly: AssemblyProduct("AccelaSDK")] [assembly: AssemblyCopyright("Copyright © 2013, Accela Inc.")] [assembly: AssemblyVersion("3.0.1.3")] [assembly: AssemblyFileVersion("3.0.1.3")] [assembly: ComVisible(false)]
Accela-Inc/Windows-SDK
src/AccelaSDK/Properties/AssemblyInfo.cs
C#
apache-2.0
492
--- layout: default title: CAS - SMS Messaging category: Notifications --- # SMS Messaging CAS presents the ability to notify users on select actions via SMS messaging. Example actions include notification of risky authentication attempts or password reset links/tokens. SMS providers supported by CAS are listed below. Note that an active/professional subscription may be required for certain providers. ## Custom Send text messages using your own custom implementation. ```java @Bean public SmsSender smsSender() { ... } ``` ## Groovy Send text messages using an external Groovy script. ```groovy import java.util.* def run(Object[] args) { def from = args[0] def to = args[1] def message = args[2] def logger = args[3] logger.debug("Sending message ${message} to ${to} from ${from}") true } ``` To see the relevant list of CAS properties, please [review this guide](../configuration/Configuration-Properties.html#groovy). ## REST Send text messages using a RESTful API. This is a `POST` with the following parameters: | Field | Description |---------------------|--------------------------------------------------- | `clientIpAddress` | The client IP address. | `serverIpAddress` | The server IP address. | `from` | The from address of the text message. | `to` | The target recipient of the text message. The request body contains the actual message. A status code of `200` is expected from the endpoint. To see the relevant list of CAS properties, please [review this guide](../configuration/Configuration-Properties.html#rest-2). ## Twilio To learn more, [visit this site](https://www.twilio.com/). ```xml <dependency> <groupId>org.apereo.cas</groupId> <artifactId>cas-server-support-sms-twilio</artifactId> <version>${cas.version}</version> </dependency> ``` To see the relevant list of CAS properties, please [review this guide](../configuration/Configuration-Properties.html#twilio). ## TextMagic To learn more, [visit this site](https://www.textmagic.com/). ```xml <dependency> <groupId>org.apereo.cas</groupId> <artifactId>cas-server-support-sms-textmagic</artifactId> <version>${cas.version}</version> </dependency> ``` To see the relevant list of CAS properties, please [review this guide](../configuration/Configuration-Properties.html#textmagic). ## Clickatell To learn more, [visit this site](http://www.clickatell.com/). ```xml <dependency> <groupId>org.apereo.cas</groupId> <artifactId>cas-server-support-sms-clickatell</artifactId> <version>${cas.version}</version> </dependency> ``` To see the relevant list of CAS properties, please [review this guide](../configuration/Configuration-Properties.html#clickatell). ## Amazon SNS To learn more, [visit this site](https://docs.aws.amazon.com/sns). ```xml <dependency> <groupId>org.apereo.cas</groupId> <artifactId>cas-server-support-sms-aws-sns</artifactId> <version>${cas.version}</version> </dependency> ``` To see the relevant list of CAS properties, please [review this guide](../configuration/Configuration-Properties.html#amazon-sns). ## Nexmo To learn more, [visit this site](https://dashboard.nexmo.com/). ```xml <dependency> <groupId>org.apereo.cas</groupId> <artifactId>cas-server-support-sms-nexmo</artifactId> <version>${cas.version}</version> </dependency> ``` To see the relevant list of CAS properties, please [review this guide](../configuration/Configuration-Properties.html#nexmo).
leleuj/cas
docs/cas-server-documentation/notifications/SMS-Messaging-Configuration.md
Markdown
apache-2.0
3,561
/** * @license Apache-2.0 * * Copyright (c) 2020 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // MODULES // var Float32Array = require( '@stdlib/array/float32' ); var addon = require( './smin.native.js' ); // MAIN // /** * Computes the minimum value of a single-precision floating-point strided array. * * @param {PositiveInteger} N - number of indexed elements * @param {Float32Array} x - input array * @param {integer} stride - stride length * @param {NonNegativeInteger} offset - starting index * @returns {number} minimum value * * @example * var Float32Array = require( '@stdlib/array/float32' ); * var floor = require( '@stdlib/math/base/special/floor' ); * * var x = new Float32Array( [ 2.0, 1.0, 2.0, -2.0, -2.0, 2.0, 3.0, 4.0 ] ); * var N = floor( x.length / 2 ); * * var v = smin( N, x, 2, 1 ); * // returns -2.0 */ function smin( N, x, stride, offset ) { var view; if ( stride < 0 ) { offset += (N-1) * stride; } view = new Float32Array( x.buffer, x.byteOffset+(x.BYTES_PER_ELEMENT*offset), x.length-offset ); // eslint-disable-line max-len return addon( N, view, stride ); } // EXPORTS // module.exports = smin;
stdlib-js/stdlib
lib/node_modules/@stdlib/stats/base/smin/lib/ndarray.native.js
JavaScript
apache-2.0
1,677
/* * Copyright 2014-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.lightsail.model.transform; import java.math.*; import javax.annotation.Generated; import com.amazonaws.services.lightsail.model.*; import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*; import com.amazonaws.transform.*; import com.fasterxml.jackson.core.JsonToken; import static com.fasterxml.jackson.core.JsonToken.*; /** * DetachStaticIpResult JSON Unmarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class DetachStaticIpResultJsonUnmarshaller implements Unmarshaller<DetachStaticIpResult, JsonUnmarshallerContext> { public DetachStaticIpResult unmarshall(JsonUnmarshallerContext context) throws Exception { DetachStaticIpResult detachStaticIpResult = new DetachStaticIpResult(); int originalDepth = context.getCurrentDepth(); String currentParentElement = context.getCurrentParentElement(); int targetDepth = originalDepth + 1; JsonToken token = context.getCurrentToken(); if (token == null) token = context.nextToken(); if (token == VALUE_NULL) { return detachStaticIpResult; } while (true) { if (token == null) break; if (token == FIELD_NAME || token == START_OBJECT) { if (context.testExpression("operations", targetDepth)) { context.nextToken(); detachStaticIpResult.setOperations(new ListUnmarshaller<Operation>(OperationJsonUnmarshaller.getInstance()).unmarshall(context)); } } else if (token == END_ARRAY || token == END_OBJECT) { if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) { if (context.getCurrentDepth() <= originalDepth) break; } } token = context.nextToken(); } return detachStaticIpResult; } private static DetachStaticIpResultJsonUnmarshaller instance; public static DetachStaticIpResultJsonUnmarshaller getInstance() { if (instance == null) instance = new DetachStaticIpResultJsonUnmarshaller(); return instance; } }
jentfoo/aws-sdk-java
aws-java-sdk-lightsail/src/main/java/com/amazonaws/services/lightsail/model/transform/DetachStaticIpResultJsonUnmarshaller.java
Java
apache-2.0
2,855
package io.teknek.nibiru.transport.rpc; import io.teknek.nibiru.transport.BaseResponse; public class BlockingRpcResponse<T> implements BaseResponse { private String exception; private T rpcResult; public BlockingRpcResponse(){ } public String getException() { return exception; } public void setException(String exception) { this.exception = exception; } public T getRpcResult() { return rpcResult; } public void setRpcResult(T rpcResult) { this.rpcResult = rpcResult; } }
edwardcapriolo/nibiru
src/main/java/io/teknek/nibiru/transport/rpc/BlockingRpcResponse.java
Java
apache-2.0
530
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (version 1.7.0_80) on Thu Oct 15 19:26:58 UTC 2015 --> <title>DescribeScheduledActionsResult (AWS SDK for Java - 1.10.27)</title> <meta name="date" content="2015-10-15"> <link rel="stylesheet" type="text/css" href="../../../../../JavaDoc.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="DescribeScheduledActionsResult (AWS SDK for Java - 1.10.27)"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="../../../../../index-all.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> <div class="aboutLanguage"><em> <!-- Scripts for Syntax Highlighter START--> <script id="syntaxhighlight_script_core" type="text/javascript" src = "http://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/resources/syntaxhighlight/scripts/shCore.js"> </script> <script id="syntaxhighlight_script_java" type="text/javascript" src = "http://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/resources/syntaxhighlight/scripts/shBrushJava.js"> </script> <link id="syntaxhighlight_css_core" rel="stylesheet" type="text/css" href = "http://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/resources/syntaxhighlight/styles/shCoreDefault.css"/> <link id="syntaxhighlight_css_theme" rel="stylesheet" type="text/css" href = "http://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/resources/syntaxhighlight/styles/shThemeDefault.css"/> <!-- Scripts for Syntax Highlighter END--> <div> <!-- BEGIN-SECTION --> <div id="divsearch" style="float:left;"> <span id="lblsearch" for="searchQuery"> <label>Search</label> </span> <form id="nav-search-form" target="_parent" method="get" action="http://docs.aws.amazon.com/search/doc-search.html#facet_doc_guide=API+Reference&facet_doc_product=AWS+SDK+for+Java"> <div id="nav-searchfield-outer" class="nav-sprite"> <div class="nav-searchfield-inner nav-sprite"> <div id="nav-searchfield-width"> <input id="nav-searchfield" name="searchQuery"> </div> </div> </div> <div id="nav-search-button" class="nav-sprite"> <input alt="" id="nav-search-button-inner" type="image"> </div> <input name="searchPath" type="hidden" value="documentation-guide" /> <input name="this_doc_product" type="hidden" value="AWS SDK for Java" /> <input name="this_doc_guide" type="hidden" value="API Reference" /> <input name="doc_locale" type="hidden" value="en_us" /> </form> </div> <!-- END-SECTION --> <!-- BEGIN-FEEDBACK-SECTION --> <div id="feedback-section"> <h3>Did this page help you?</h3> <div id="feedback-link-sectioin"> <a id="feedback_yes" target="_blank" style="display:inline;">Yes</a>&nbsp;&nbsp; <a id="feedback_no" target="_blank" style="display:inline;">No</a>&nbsp;&nbsp; <a id="go_cti" target="_blank" style="display:inline;">Tell us about it...</a> </div> </div> <script type="text/javascript"> window.onload = function(){ /* Dynamically add feedback links */ var javadoc_root_name = "/javadoc/"; var javadoc_path = location.href.substring(0, location.href.lastIndexOf(javadoc_root_name) + javadoc_root_name.length); var file_path = location.href.substring(location.href.lastIndexOf(javadoc_root_name) + javadoc_root_name.length); var feedback_yes_url = javadoc_path + "javadoc-resources/feedbackyes.html?topic_id="; var feedback_no_url = javadoc_path + "javadoc-resources/feedbackno.html?topic_id="; var feedback_tellmore_url = "https://aws-portal.amazon.com/gp/aws/html-forms-controller/documentation/aws_doc_feedback_04?service_name=Java-Ref&file_name="; if(file_path != "overview-frame.html") { var file_name = file_path.replace(/[/.]/g, '_'); document.getElementById("feedback_yes").setAttribute("href", feedback_yes_url + file_name); document.getElementById("feedback_no").setAttribute("href", feedback_no_url + file_name); document.getElementById("go_cti").setAttribute("href", feedback_tellmore_url + file_name); } else { // hide the search box and the feeback links in overview-frame page, // show "AWS SDK for Java" instead. document.getElementById("feedback-section").outerHTML = "AWS SDK for Java"; document.getElementById("divsearch").outerHTML = ""; } }; </script> <!-- END-FEEDBACK-SECTION --> </div> </em></div> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../../com/amazonaws/services/autoscaling/model/DescribeScheduledActionsRequest.html" title="class in com.amazonaws.services.autoscaling.model"><span class="strong">Prev Class</span></a></li> <li><a href="../../../../../com/amazonaws/services/autoscaling/model/DescribeTagsRequest.html" title="class in com.amazonaws.services.autoscaling.model"><span class="strong">Next Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?com/amazonaws/services/autoscaling/model/DescribeScheduledActionsResult.html" target="_top">Frames</a></li> <li><a href="DescribeScheduledActionsResult.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor_summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method_summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor_detail">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method_detail">Method</a></li> </ul> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <!-- ======== START OF CLASS DATA ======== --> <div class="header"> <div class="subTitle">com.amazonaws.services.autoscaling.model</div> <h2 title="Class DescribeScheduledActionsResult" class="title">Class DescribeScheduledActionsResult</h2> </div> <div class="contentContainer"> <ul class="inheritance"> <li>java.lang.Object</li> <li> <ul class="inheritance"> <li>com.amazonaws.services.autoscaling.model.DescribeScheduledActionsResult</li> </ul> </li> </ul> <div class="description"> <ul class="blockList"> <li class="blockList"> <dl> <dt>All Implemented Interfaces:</dt> <dd>java.io.Serializable, java.lang.Cloneable</dd> </dl> <hr> <br> <pre>public class <span class="strong">DescribeScheduledActionsResult</span> extends java.lang.Object implements java.io.Serializable, java.lang.Cloneable</pre> <dl><dt><span class="strong">See Also:</span></dt><dd><a href="../../../../../serialized-form.html#com.amazonaws.services.autoscaling.model.DescribeScheduledActionsResult">Serialized Form</a></dd></dl> </li> </ul> </div> <div class="summary"> <ul class="blockList"> <li class="blockList"> <!-- ======== CONSTRUCTOR SUMMARY ======== --> <ul class="blockList"> <li class="blockList"><a name="constructor_summary"> <!-- --> </a> <h3>Constructor Summary</h3> <table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation"> <caption><span>Constructors</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colOne" scope="col">Constructor and Description</th> </tr> <tr class="altColor"> <td class="colOne"><code><strong><a href="../../../../../com/amazonaws/services/autoscaling/model/DescribeScheduledActionsResult.html#DescribeScheduledActionsResult()">DescribeScheduledActionsResult</a></strong>()</code>&nbsp;</td> </tr> </table> </li> </ul> <!-- ========== METHOD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="method_summary"> <!-- --> </a> <h3>Method Summary</h3> <table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation"> <caption><span>Methods</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tr class="altColor"> <td class="colFirst"><code><a href="../../../../../com/amazonaws/services/autoscaling/model/DescribeScheduledActionsResult.html" title="class in com.amazonaws.services.autoscaling.model">DescribeScheduledActionsResult</a></code></td> <td class="colLast"><code><strong><a href="../../../../../com/amazonaws/services/autoscaling/model/DescribeScheduledActionsResult.html#clone()">clone</a></strong>()</code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>boolean</code></td> <td class="colLast"><code><strong><a href="../../../../../com/amazonaws/services/autoscaling/model/DescribeScheduledActionsResult.html#equals(java.lang.Object)">equals</a></strong>(java.lang.Object&nbsp;obj)</code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code>java.lang.String</code></td> <td class="colLast"><code><strong><a href="../../../../../com/amazonaws/services/autoscaling/model/DescribeScheduledActionsResult.html#getNextToken()">getNextToken</a></strong>()</code> <div class="block">The token to use when requesting the next set of items.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>java.util.List&lt;<a href="../../../../../com/amazonaws/services/autoscaling/model/ScheduledUpdateGroupAction.html" title="class in com.amazonaws.services.autoscaling.model">ScheduledUpdateGroupAction</a>&gt;</code></td> <td class="colLast"><code><strong><a href="../../../../../com/amazonaws/services/autoscaling/model/DescribeScheduledActionsResult.html#getScheduledUpdateGroupActions()">getScheduledUpdateGroupActions</a></strong>()</code> <div class="block">The scheduled actions.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>int</code></td> <td class="colLast"><code><strong><a href="../../../../../com/amazonaws/services/autoscaling/model/DescribeScheduledActionsResult.html#hashCode()">hashCode</a></strong>()</code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><strong><a href="../../../../../com/amazonaws/services/autoscaling/model/DescribeScheduledActionsResult.html#setNextToken(java.lang.String)">setNextToken</a></strong>(java.lang.String&nbsp;nextToken)</code> <div class="block">The token to use when requesting the next set of items.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><strong><a href="../../../../../com/amazonaws/services/autoscaling/model/DescribeScheduledActionsResult.html#setScheduledUpdateGroupActions(java.util.Collection)">setScheduledUpdateGroupActions</a></strong>(java.util.Collection&lt;<a href="../../../../../com/amazonaws/services/autoscaling/model/ScheduledUpdateGroupAction.html" title="class in com.amazonaws.services.autoscaling.model">ScheduledUpdateGroupAction</a>&gt;&nbsp;scheduledUpdateGroupActions)</code> <div class="block">The scheduled actions.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>java.lang.String</code></td> <td class="colLast"><code><strong><a href="../../../../../com/amazonaws/services/autoscaling/model/DescribeScheduledActionsResult.html#toString()">toString</a></strong>()</code> <div class="block">Returns a string representation of this object; useful for testing and debugging.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code><a href="../../../../../com/amazonaws/services/autoscaling/model/DescribeScheduledActionsResult.html" title="class in com.amazonaws.services.autoscaling.model">DescribeScheduledActionsResult</a></code></td> <td class="colLast"><code><strong><a href="../../../../../com/amazonaws/services/autoscaling/model/DescribeScheduledActionsResult.html#withNextToken(java.lang.String)">withNextToken</a></strong>(java.lang.String&nbsp;nextToken)</code> <div class="block">The token to use when requesting the next set of items.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code><a href="../../../../../com/amazonaws/services/autoscaling/model/DescribeScheduledActionsResult.html" title="class in com.amazonaws.services.autoscaling.model">DescribeScheduledActionsResult</a></code></td> <td class="colLast"><code><strong><a href="../../../../../com/amazonaws/services/autoscaling/model/DescribeScheduledActionsResult.html#withScheduledUpdateGroupActions(java.util.Collection)">withScheduledUpdateGroupActions</a></strong>(java.util.Collection&lt;<a href="../../../../../com/amazonaws/services/autoscaling/model/ScheduledUpdateGroupAction.html" title="class in com.amazonaws.services.autoscaling.model">ScheduledUpdateGroupAction</a>&gt;&nbsp;scheduledUpdateGroupActions)</code> <div class="block">The scheduled actions.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code><a href="../../../../../com/amazonaws/services/autoscaling/model/DescribeScheduledActionsResult.html" title="class in com.amazonaws.services.autoscaling.model">DescribeScheduledActionsResult</a></code></td> <td class="colLast"><code><strong><a href="../../../../../com/amazonaws/services/autoscaling/model/DescribeScheduledActionsResult.html#withScheduledUpdateGroupActions(com.amazonaws.services.autoscaling.model.ScheduledUpdateGroupAction...)">withScheduledUpdateGroupActions</a></strong>(<a href="../../../../../com/amazonaws/services/autoscaling/model/ScheduledUpdateGroupAction.html" title="class in com.amazonaws.services.autoscaling.model">ScheduledUpdateGroupAction</a>...&nbsp;scheduledUpdateGroupActions)</code> <div class="block">The scheduled actions.</div> </td> </tr> </table> <ul class="blockList"> <li class="blockList"><a name="methods_inherited_from_class_java.lang.Object"> <!-- --> </a> <h3>Methods inherited from class&nbsp;java.lang.Object</h3> <code>getClass, notify, notifyAll, wait, wait, wait</code></li> </ul> </li> </ul> </li> </ul> </div> <div class="details"> <ul class="blockList"> <li class="blockList"> <!-- ========= CONSTRUCTOR DETAIL ======== --> <ul class="blockList"> <li class="blockList"><a name="constructor_detail"> <!-- --> </a> <h3>Constructor Detail</h3> <a name="DescribeScheduledActionsResult()"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>DescribeScheduledActionsResult</h4> <pre>public&nbsp;DescribeScheduledActionsResult()</pre> </li> </ul> </li> </ul> <!-- ============ METHOD DETAIL ========== --> <ul class="blockList"> <li class="blockList"><a name="method_detail"> <!-- --> </a> <h3>Method Detail</h3> <a name="getScheduledUpdateGroupActions()"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>getScheduledUpdateGroupActions</h4> <pre>public&nbsp;java.util.List&lt;<a href="../../../../../com/amazonaws/services/autoscaling/model/ScheduledUpdateGroupAction.html" title="class in com.amazonaws.services.autoscaling.model">ScheduledUpdateGroupAction</a>&gt;&nbsp;getScheduledUpdateGroupActions()</pre> <div class="block">The scheduled actions.</div> <dl><dt><span class="strong">Returns:</span></dt><dd>The scheduled actions.</dd></dl> </li> </ul> <a name="setScheduledUpdateGroupActions(java.util.Collection)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>setScheduledUpdateGroupActions</h4> <pre>public&nbsp;void&nbsp;setScheduledUpdateGroupActions(java.util.Collection&lt;<a href="../../../../../com/amazonaws/services/autoscaling/model/ScheduledUpdateGroupAction.html" title="class in com.amazonaws.services.autoscaling.model">ScheduledUpdateGroupAction</a>&gt;&nbsp;scheduledUpdateGroupActions)</pre> <div class="block">The scheduled actions.</div> <dl><dt><span class="strong">Parameters:</span></dt><dd><code>scheduledUpdateGroupActions</code> - The scheduled actions.</dd></dl> </li> </ul> <a name="withScheduledUpdateGroupActions(com.amazonaws.services.autoscaling.model.ScheduledUpdateGroupAction...)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>withScheduledUpdateGroupActions</h4> <pre>public&nbsp;<a href="../../../../../com/amazonaws/services/autoscaling/model/DescribeScheduledActionsResult.html" title="class in com.amazonaws.services.autoscaling.model">DescribeScheduledActionsResult</a>&nbsp;withScheduledUpdateGroupActions(<a href="../../../../../com/amazonaws/services/autoscaling/model/ScheduledUpdateGroupAction.html" title="class in com.amazonaws.services.autoscaling.model">ScheduledUpdateGroupAction</a>...&nbsp;scheduledUpdateGroupActions)</pre> <div class="block">The scheduled actions. <p> <b>NOTE:</b> This method appends the values to the existing list (if any). Use <a href="../../../../../com/amazonaws/services/autoscaling/model/DescribeScheduledActionsResult.html#setScheduledUpdateGroupActions(java.util.Collection)"><code>setScheduledUpdateGroupActions(java.util.Collection)</code></a> or <a href="../../../../../com/amazonaws/services/autoscaling/model/DescribeScheduledActionsResult.html#withScheduledUpdateGroupActions(java.util.Collection)"><code>withScheduledUpdateGroupActions(java.util.Collection)</code></a> if you want to override the existing values. <p> Returns a reference to this object so that method calls can be chained together.</div> <dl><dt><span class="strong">Parameters:</span></dt><dd><code>scheduledUpdateGroupActions</code> - The scheduled actions.</dd> <dt><span class="strong">Returns:</span></dt><dd>A reference to this updated object so that method calls can be chained together.</dd></dl> </li> </ul> <a name="withScheduledUpdateGroupActions(java.util.Collection)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>withScheduledUpdateGroupActions</h4> <pre>public&nbsp;<a href="../../../../../com/amazonaws/services/autoscaling/model/DescribeScheduledActionsResult.html" title="class in com.amazonaws.services.autoscaling.model">DescribeScheduledActionsResult</a>&nbsp;withScheduledUpdateGroupActions(java.util.Collection&lt;<a href="../../../../../com/amazonaws/services/autoscaling/model/ScheduledUpdateGroupAction.html" title="class in com.amazonaws.services.autoscaling.model">ScheduledUpdateGroupAction</a>&gt;&nbsp;scheduledUpdateGroupActions)</pre> <div class="block">The scheduled actions. <p> Returns a reference to this object so that method calls can be chained together.</div> <dl><dt><span class="strong">Parameters:</span></dt><dd><code>scheduledUpdateGroupActions</code> - The scheduled actions.</dd> <dt><span class="strong">Returns:</span></dt><dd>A reference to this updated object so that method calls can be chained together.</dd></dl> </li> </ul> <a name="getNextToken()"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>getNextToken</h4> <pre>public&nbsp;java.lang.String&nbsp;getNextToken()</pre> <div class="block">The token to use when requesting the next set of items. If there are no additional items to return, the string is empty. <p> <b>Constraints:</b><br/> <b>Pattern: </b>[&#92;u0020-&#92;uD7FF&#92;uE000-&#92;uFFFD&#92;uD800&#92;uDC00-&#92;uDBFF&#92;uDFFF\r\n\t]*<br/></div> <dl><dt><span class="strong">Returns:</span></dt><dd>The token to use when requesting the next set of items. If there are no additional items to return, the string is empty.</dd></dl> </li> </ul> <a name="setNextToken(java.lang.String)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>setNextToken</h4> <pre>public&nbsp;void&nbsp;setNextToken(java.lang.String&nbsp;nextToken)</pre> <div class="block">The token to use when requesting the next set of items. If there are no additional items to return, the string is empty. <p> <b>Constraints:</b><br/> <b>Pattern: </b>[&#92;u0020-&#92;uD7FF&#92;uE000-&#92;uFFFD&#92;uD800&#92;uDC00-&#92;uDBFF&#92;uDFFF\r\n\t]*<br/></div> <dl><dt><span class="strong">Parameters:</span></dt><dd><code>nextToken</code> - The token to use when requesting the next set of items. If there are no additional items to return, the string is empty.</dd></dl> </li> </ul> <a name="withNextToken(java.lang.String)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>withNextToken</h4> <pre>public&nbsp;<a href="../../../../../com/amazonaws/services/autoscaling/model/DescribeScheduledActionsResult.html" title="class in com.amazonaws.services.autoscaling.model">DescribeScheduledActionsResult</a>&nbsp;withNextToken(java.lang.String&nbsp;nextToken)</pre> <div class="block">The token to use when requesting the next set of items. If there are no additional items to return, the string is empty. <p> Returns a reference to this object so that method calls can be chained together. <p> <b>Constraints:</b><br/> <b>Pattern: </b>[&#92;u0020-&#92;uD7FF&#92;uE000-&#92;uFFFD&#92;uD800&#92;uDC00-&#92;uDBFF&#92;uDFFF\r\n\t]*<br/></div> <dl><dt><span class="strong">Parameters:</span></dt><dd><code>nextToken</code> - The token to use when requesting the next set of items. If there are no additional items to return, the string is empty.</dd> <dt><span class="strong">Returns:</span></dt><dd>A reference to this updated object so that method calls can be chained together.</dd></dl> </li> </ul> <a name="toString()"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>toString</h4> <pre>public&nbsp;java.lang.String&nbsp;toString()</pre> <div class="block">Returns a string representation of this object; useful for testing and debugging.</div> <dl> <dt><strong>Overrides:</strong></dt> <dd><code>toString</code>&nbsp;in class&nbsp;<code>java.lang.Object</code></dd> <dt><span class="strong">Returns:</span></dt><dd>A string representation of this object.</dd><dt><span class="strong">See Also:</span></dt><dd><code>Object.toString()</code></dd></dl> </li> </ul> <a name="hashCode()"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>hashCode</h4> <pre>public&nbsp;int&nbsp;hashCode()</pre> <dl> <dt><strong>Overrides:</strong></dt> <dd><code>hashCode</code>&nbsp;in class&nbsp;<code>java.lang.Object</code></dd> </dl> </li> </ul> <a name="equals(java.lang.Object)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>equals</h4> <pre>public&nbsp;boolean&nbsp;equals(java.lang.Object&nbsp;obj)</pre> <dl> <dt><strong>Overrides:</strong></dt> <dd><code>equals</code>&nbsp;in class&nbsp;<code>java.lang.Object</code></dd> </dl> </li> </ul> <a name="clone()"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>clone</h4> <pre>public&nbsp;<a href="../../../../../com/amazonaws/services/autoscaling/model/DescribeScheduledActionsResult.html" title="class in com.amazonaws.services.autoscaling.model">DescribeScheduledActionsResult</a>&nbsp;clone()</pre> <dl> <dt><strong>Overrides:</strong></dt> <dd><code>clone</code>&nbsp;in class&nbsp;<code>java.lang.Object</code></dd> </dl> </li> </ul> </li> </ul> </li> </ul> </div> </div> <!-- ========= END OF CLASS DATA ========= --> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="../../../../../index-all.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> <div class="aboutLanguage"><em> <div> <!-- Script for Syntax Highlighter START --> <script type="text/javascript"> SyntaxHighlighter.all() </script> <!-- Script for Syntax Highlighter END --> </div> <script src="http://a0.awsstatic.com/chrome/js/1.0.46/jquery.1.9.js" type="text/javascript"></script> <script>jQuery.noConflict();</script> <script> jQuery(function ($) { $("div.header").prepend('<!--REGION_DISCLAIMER_DO_NOT_REMOVE-->'); }); </script> <!-- BEGIN-URCHIN-TRACKER --> <script src="http://l0.awsstatic.com/js/urchin.js" type="text/javascript"></script> <script type="text/javascript">urchinTracker();</script> <!-- END-URCHIN-TRACKER --> <!-- SiteCatalyst code version: H.25.2. Copyright 1996-2012 Adobe, Inc. All Rights Reserved. More info available at http://www.omniture.com --> <script language="JavaScript" type="text/javascript" src="https://media.amazonwebservices.com/js/sitecatalyst/s_code.min.js (view-source:https://media.amazonwebservices.com/js/sitecatalyst/s_code.min.js)" /> <script language="JavaScript" type="text/javascript"> <!-- // Documentation Service Name s.prop66='AWS SDK for Java'; s.eVar66='D=c66'; // Documentation Guide Name s.prop65='API Reference'; s.eVar65='D=c65'; var s_code=s.t();if(s_code)document.write(s_code) //--> </script> <script language="JavaScript" type="text/javascript"> <!--if(navigator.appVersion.indexOf('MSIE')>=0)document.write(unescape('%3C')+'\!-'+'-') //--> </script> <noscript> <img src="http://amazonwebservices.d2.sc.omtrdc.net/b/ss/awsamazondev/1/H.25.2--NS/0" height="1" width="1" border="0" alt="" /> </noscript> <!--/DO NOT REMOVE/--> <!-- End SiteCatalyst code version: H.25.2. --> </em></div> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../../com/amazonaws/services/autoscaling/model/DescribeScheduledActionsRequest.html" title="class in com.amazonaws.services.autoscaling.model"><span class="strong">Prev Class</span></a></li> <li><a href="../../../../../com/amazonaws/services/autoscaling/model/DescribeTagsRequest.html" title="class in com.amazonaws.services.autoscaling.model"><span class="strong">Next Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?com/amazonaws/services/autoscaling/model/DescribeScheduledActionsResult.html" target="_top">Frames</a></li> <li><a href="DescribeScheduledActionsResult.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor_summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method_summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor_detail">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method_detail">Method</a></li> </ul> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small> Copyright &#169; 2013 Amazon Web Services, Inc. All Rights Reserved. </small></p> </body> </html>
TomNong/Project2-Intel-Edison
documentation/javadoc/com/amazonaws/services/autoscaling/model/DescribeScheduledActionsResult.html
HTML
apache-2.0
29,161
/* Copyright 2021 The Kubeflow Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package main import ( "encoding/json" "fmt" "os" "strings" "github.com/go-openapi/spec" "github.com/kubeflow/katib/pkg/apis/v1beta1" "k8s.io/klog" "k8s.io/kube-openapi/pkg/common" ) // Generate OpenAPI spec definitions for Katib Resource func main() { if len(os.Args) <= 2 { klog.Fatal("Supply Swagger version and Katib Version") } version := os.Args[1] if !strings.HasPrefix(version, "v") { version = "v" + version } refCallback := func(name string) spec.Ref { return spec.MustCreateRef("#/definitions/" + common.EscapeJsonPointer(swaggify(name))) } katibVersion := os.Args[2] oAPIDefs := make(map[string]common.OpenAPIDefinition) if katibVersion == "v1beta1" { oAPIDefs = v1beta1.GetOpenAPIDefinitions(refCallback) } else { klog.Fatalf("Katib version %v is not supported", katibVersion) } defs := spec.Definitions{} for defName, val := range oAPIDefs { defs[swaggify(defName)] = val.Schema } swagger := spec.Swagger{ SwaggerProps: spec.SwaggerProps{ Swagger: "2.0", Definitions: defs, Paths: &spec.Paths{Paths: map[string]spec.PathItem{}}, Info: &spec.Info{ InfoProps: spec.InfoProps{ Title: "Katib", Description: "Swagger description for Katib", Version: version, }, }, }, } jsonBytes, err := json.MarshalIndent(swagger, "", " ") if err != nil { klog.Fatal(err.Error()) } fmt.Println(string(jsonBytes)) } func swaggify(name string) string { name = strings.Replace(name, "github.com/kubeflow/katib/pkg/apis/controller/common/", "", -1) name = strings.Replace(name, "github.com/kubeflow/katib/pkg/apis/controller/experiments/", "", -1) name = strings.Replace(name, "github.com/kubeflow/katib/pkg/apis/controller/suggestions", "", -1) name = strings.Replace(name, "github.com/kubeflow/katib/pkg/apis/controller/trials", "", -1) name = strings.Replace(name, "k8s.io/api/core/", "", -1) name = strings.Replace(name, "k8s.io/apimachinery/pkg/apis/meta/", "", -1) name = strings.Replace(name, "/", ".", -1) return name }
kubeflow/katib
hack/swagger/main.go
GO
apache-2.0
2,606
# -*- coding: utf-8 -*- from __future__ import unicode_literals import pytest import allure_commons from allure_pytest.utils import ALLURE_LABEL_PREFIX, ALLURE_LINK_PREFIX class AllureTestHelper(object): def __init__(self, config): self.config = config @allure_commons.hookimpl def decorate_as_label(self, label_type, labels): allure_label_marker = '{prefix}.{label_type}'.format(prefix=ALLURE_LABEL_PREFIX, label_type=label_type) allure_label = getattr(pytest.mark, allure_label_marker) return allure_label(*labels, label_type=label_type) @allure_commons.hookimpl def decorate_as_link(self, url, link_type, name): allure_link_marker = '{prefix}.{link_type}'.format(prefix=ALLURE_LINK_PREFIX, link_type=link_type) pattern = dict(self.config.option.allure_link_pattern).get(link_type, u'{}') url = pattern.format(url) allure_link = getattr(pytest.mark, allure_link_marker) return allure_link(url, name=name, link_type=link_type)
igogorek/allure-python
allure-pytest/src/helper.py
Python
apache-2.0
1,026
/* * Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.config.model.transform; import java.util.List; import javax.annotation.Generated; import com.amazonaws.SdkClientException; import com.amazonaws.services.config.model.*; import com.amazonaws.protocol.*; import com.amazonaws.annotation.SdkInternalApi; /** * DescribeConfigRulesRequestMarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") @SdkInternalApi public class DescribeConfigRulesRequestMarshaller { private static final MarshallingInfo<List> CONFIGRULENAMES_BINDING = MarshallingInfo.builder(MarshallingType.LIST) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("ConfigRuleNames").build(); private static final MarshallingInfo<String> NEXTTOKEN_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("NextToken").build(); private static final DescribeConfigRulesRequestMarshaller instance = new DescribeConfigRulesRequestMarshaller(); public static DescribeConfigRulesRequestMarshaller getInstance() { return instance; } /** * Marshall the given parameter object. */ public void marshall(DescribeConfigRulesRequest describeConfigRulesRequest, ProtocolMarshaller protocolMarshaller) { if (describeConfigRulesRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(describeConfigRulesRequest.getConfigRuleNames(), CONFIGRULENAMES_BINDING); protocolMarshaller.marshall(describeConfigRulesRequest.getNextToken(), NEXTTOKEN_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
aws/aws-sdk-java
aws-java-sdk-config/src/main/java/com/amazonaws/services/config/model/transform/DescribeConfigRulesRequestMarshaller.java
Java
apache-2.0
2,415
/* * Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.iotevents.model; import java.io.Serializable; import javax.annotation.Generated; import com.amazonaws.AmazonWebServiceRequest; /** * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/iotevents-2018-07-27/GetDetectorModelAnalysisResults" * target="_top">AWS API Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class GetDetectorModelAnalysisResultsRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable { /** * <p> * The ID of the analysis result that you want to retrieve. * </p> */ private String analysisId; /** * <p> * The token that you can use to return the next set of results. * </p> */ private String nextToken; /** * <p> * The maximum number of results to be returned per request. * </p> */ private Integer maxResults; /** * <p> * The ID of the analysis result that you want to retrieve. * </p> * * @param analysisId * The ID of the analysis result that you want to retrieve. */ public void setAnalysisId(String analysisId) { this.analysisId = analysisId; } /** * <p> * The ID of the analysis result that you want to retrieve. * </p> * * @return The ID of the analysis result that you want to retrieve. */ public String getAnalysisId() { return this.analysisId; } /** * <p> * The ID of the analysis result that you want to retrieve. * </p> * * @param analysisId * The ID of the analysis result that you want to retrieve. * @return Returns a reference to this object so that method calls can be chained together. */ public GetDetectorModelAnalysisResultsRequest withAnalysisId(String analysisId) { setAnalysisId(analysisId); return this; } /** * <p> * The token that you can use to return the next set of results. * </p> * * @param nextToken * The token that you can use to return the next set of results. */ public void setNextToken(String nextToken) { this.nextToken = nextToken; } /** * <p> * The token that you can use to return the next set of results. * </p> * * @return The token that you can use to return the next set of results. */ public String getNextToken() { return this.nextToken; } /** * <p> * The token that you can use to return the next set of results. * </p> * * @param nextToken * The token that you can use to return the next set of results. * @return Returns a reference to this object so that method calls can be chained together. */ public GetDetectorModelAnalysisResultsRequest withNextToken(String nextToken) { setNextToken(nextToken); return this; } /** * <p> * The maximum number of results to be returned per request. * </p> * * @param maxResults * The maximum number of results to be returned per request. */ public void setMaxResults(Integer maxResults) { this.maxResults = maxResults; } /** * <p> * The maximum number of results to be returned per request. * </p> * * @return The maximum number of results to be returned per request. */ public Integer getMaxResults() { return this.maxResults; } /** * <p> * The maximum number of results to be returned per request. * </p> * * @param maxResults * The maximum number of results to be returned per request. * @return Returns a reference to this object so that method calls can be chained together. */ public GetDetectorModelAnalysisResultsRequest withMaxResults(Integer maxResults) { setMaxResults(maxResults); return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getAnalysisId() != null) sb.append("AnalysisId: ").append(getAnalysisId()).append(","); if (getNextToken() != null) sb.append("NextToken: ").append(getNextToken()).append(","); if (getMaxResults() != null) sb.append("MaxResults: ").append(getMaxResults()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof GetDetectorModelAnalysisResultsRequest == false) return false; GetDetectorModelAnalysisResultsRequest other = (GetDetectorModelAnalysisResultsRequest) obj; if (other.getAnalysisId() == null ^ this.getAnalysisId() == null) return false; if (other.getAnalysisId() != null && other.getAnalysisId().equals(this.getAnalysisId()) == false) return false; if (other.getNextToken() == null ^ this.getNextToken() == null) return false; if (other.getNextToken() != null && other.getNextToken().equals(this.getNextToken()) == false) return false; if (other.getMaxResults() == null ^ this.getMaxResults() == null) return false; if (other.getMaxResults() != null && other.getMaxResults().equals(this.getMaxResults()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getAnalysisId() == null) ? 0 : getAnalysisId().hashCode()); hashCode = prime * hashCode + ((getNextToken() == null) ? 0 : getNextToken().hashCode()); hashCode = prime * hashCode + ((getMaxResults() == null) ? 0 : getMaxResults().hashCode()); return hashCode; } @Override public GetDetectorModelAnalysisResultsRequest clone() { return (GetDetectorModelAnalysisResultsRequest) super.clone(); } }
aws/aws-sdk-java
aws-java-sdk-iotevents/src/main/java/com/amazonaws/services/iotevents/model/GetDetectorModelAnalysisResultsRequest.java
Java
apache-2.0
7,053
/* * Copyright 2014-2015 Nippon Telegraph and Telephone Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef __LAGOPUS_RUNNABLE_FUNCS_H__ #define __LAGOPUS_RUNNABLE_FUNCS_H__ /** * @file lagopus_runnable_funcs.h */ #ifndef RUNNABLE_T_DECLARED typedef struct lagopus_runnable_record *lagopus_runnable_t; #define RUNNABLE_T_DECLARED #endif /* ! RUNNABLE_T_DECLARED */ /** * A procedure for a runnable. * * @param[in] rptr A runnable. * @param[in] arg An argument. * * @details If any resoures acquired in the function must be released * before returning. Doing this must be the functions's responsibility. * * @details This function must not loop infinitely, but must return in * appropriate amount of execution time. */ typedef void (*lagopus_runnable_proc_t)(const lagopus_runnable_t *rptr, void *arg); /** * Free a runnable up. * * @param[in] rptr A pointer to a runnable. * * @details Don't free the \b *rptr itself up. */ typedef void (*lagopus_runnable_freeup_proc_t)(lagopus_runnable_t *rptr); #endif /* ! __LAGOPUS_RUNNABLE_FUNCS_H__ */
trojan00/lagopus
src/include/lagopus_runnable_funcs.h
C
apache-2.0
1,702
/* Copyright 2014 The Kubernetes 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 cmd import ( "bytes" "fmt" "io" jsonpatch "github.com/evanphx/json-patch" "github.com/golang/glog" "github.com/spf13/cobra" "k8s.io/apimachinery/pkg/api/meta" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/types" "k8s.io/apimachinery/pkg/util/json" "k8s.io/cli-runtime/pkg/genericclioptions" "k8s.io/cli-runtime/pkg/genericclioptions/printers" "k8s.io/cli-runtime/pkg/genericclioptions/resource" "k8s.io/kubernetes/pkg/kubectl" "k8s.io/kubernetes/pkg/kubectl/cmd/templates" cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util" "k8s.io/kubernetes/pkg/kubectl/scheme" "k8s.io/kubernetes/pkg/kubectl/util/i18n" ) // AnnotateOptions have the data required to perform the annotate operation type AnnotateOptions struct { PrintFlags *genericclioptions.PrintFlags PrintObj printers.ResourcePrinterFunc // Filename options resource.FilenameOptions RecordFlags *genericclioptions.RecordFlags // Common user flags overwrite bool local bool dryrun bool all bool resourceVersion string selector string fieldSelector string outputFormat string // results of arg parsing resources []string newAnnotations map[string]string removeAnnotations []string Recorder genericclioptions.Recorder namespace string enforceNamespace bool builder *resource.Builder unstructuredClientForMapping func(mapping *meta.RESTMapping) (resource.RESTClient, error) includeUninitialized bool genericclioptions.IOStreams } var ( annotateLong = templates.LongDesc(` Update the annotations on one or more resources All Kubernetes objects support the ability to store additional data with the object as annotations. Annotations are key/value pairs that can be larger than labels and include arbitrary string values such as structured JSON. Tools and system extensions may use annotations to store their own data. Attempting to set an annotation that already exists will fail unless --overwrite is set. If --resource-version is specified and does not match the current resource version on the server the command will fail.`) annotateExample = templates.Examples(i18n.T(` # Update pod 'foo' with the annotation 'description' and the value 'my frontend'. # If the same annotation is set multiple times, only the last value will be applied kubectl annotate pods foo description='my frontend' # Update a pod identified by type and name in "pod.json" kubectl annotate -f pod.json description='my frontend' # Update pod 'foo' with the annotation 'description' and the value 'my frontend running nginx', overwriting any existing value. kubectl annotate --overwrite pods foo description='my frontend running nginx' # Update all pods in the namespace kubectl annotate pods --all description='my frontend running nginx' # Update pod 'foo' only if the resource is unchanged from version 1. kubectl annotate pods foo description='my frontend running nginx' --resource-version=1 # Update pod 'foo' by removing an annotation named 'description' if it exists. # Does not require the --overwrite flag. kubectl annotate pods foo description-`)) ) func NewAnnotateOptions(ioStreams genericclioptions.IOStreams) *AnnotateOptions { return &AnnotateOptions{ PrintFlags: genericclioptions.NewPrintFlags("annotated").WithTypeSetter(scheme.Scheme), RecordFlags: genericclioptions.NewRecordFlags(), Recorder: genericclioptions.NoopRecorder{}, IOStreams: ioStreams, } } func NewCmdAnnotate(parent string, f cmdutil.Factory, ioStreams genericclioptions.IOStreams) *cobra.Command { o := NewAnnotateOptions(ioStreams) cmd := &cobra.Command{ Use: "annotate [--overwrite] (-f FILENAME | TYPE NAME) KEY_1=VAL_1 ... KEY_N=VAL_N [--resource-version=version]", DisableFlagsInUseLine: true, Short: i18n.T("Update the annotations on a resource"), Long: annotateLong + "\n\n" + cmdutil.SuggestApiResources(parent), Example: annotateExample, Run: func(cmd *cobra.Command, args []string) { cmdutil.CheckErr(o.Complete(f, cmd, args)) cmdutil.CheckErr(o.Validate()) cmdutil.CheckErr(o.RunAnnotate()) }, } // bind flag structs o.RecordFlags.AddFlags(cmd) o.PrintFlags.AddFlags(cmd) cmdutil.AddIncludeUninitializedFlag(cmd) cmd.Flags().BoolVar(&o.overwrite, "overwrite", o.overwrite, "If true, allow annotations to be overwritten, otherwise reject annotation updates that overwrite existing annotations.") cmd.Flags().BoolVar(&o.local, "local", o.local, "If true, annotation will NOT contact api-server but run locally.") cmd.Flags().StringVarP(&o.selector, "selector", "l", o.selector, "Selector (label query) to filter on, not including uninitialized ones, supports '=', '==', and '!='.(e.g. -l key1=value1,key2=value2).") cmd.Flags().StringVar(&o.fieldSelector, "field-selector", o.fieldSelector, "Selector (field query) to filter on, supports '=', '==', and '!='.(e.g. --field-selector key1=value1,key2=value2). The server only supports a limited number of field queries per type.") cmd.Flags().BoolVar(&o.all, "all", o.all, "Select all resources, including uninitialized ones, in the namespace of the specified resource types.") cmd.Flags().StringVar(&o.resourceVersion, "resource-version", o.resourceVersion, i18n.T("If non-empty, the annotation update will only succeed if this is the current resource-version for the object. Only valid when specifying a single resource.")) usage := "identifying the resource to update the annotation" cmdutil.AddFilenameOptionFlags(cmd, &o.FilenameOptions, usage) cmdutil.AddDryRunFlag(cmd) return cmd } // Complete adapts from the command line args and factory to the data required. func (o *AnnotateOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args []string) error { var err error o.RecordFlags.Complete(cmd) o.Recorder, err = o.RecordFlags.ToRecorder() if err != nil { return err } o.outputFormat = cmdutil.GetFlagString(cmd, "output") o.dryrun = cmdutil.GetDryRunFlag(cmd) if o.dryrun { o.PrintFlags.Complete("%s (dry run)") } printer, err := o.PrintFlags.ToPrinter() if err != nil { return err } o.PrintObj = func(obj runtime.Object, out io.Writer) error { return printer.PrintObj(obj, out) } o.namespace, o.enforceNamespace, err = f.ToRawKubeConfigLoader().Namespace() if err != nil { return err } o.includeUninitialized = cmdutil.ShouldIncludeUninitialized(cmd, false) o.builder = f.NewBuilder() o.unstructuredClientForMapping = f.UnstructuredClientForMapping // retrieves resource and annotation args from args // also checks args to verify that all resources are specified before annotations resources, annotationArgs, err := cmdutil.GetResourcesAndPairs(args, "annotation") if err != nil { return err } o.resources = resources o.newAnnotations, o.removeAnnotations, err = parseAnnotations(annotationArgs) if err != nil { return err } return nil } // Validate checks to the AnnotateOptions to see if there is sufficient information run the command. func (o AnnotateOptions) Validate() error { if o.all && len(o.selector) > 0 { return fmt.Errorf("cannot set --all and --selector at the same time") } if o.all && len(o.fieldSelector) > 0 { return fmt.Errorf("cannot set --all and --field-selector at the same time") } if len(o.resources) < 1 && cmdutil.IsFilenameSliceEmpty(o.Filenames) { return fmt.Errorf("one or more resources must be specified as <resource> <name> or <resource>/<name>") } if len(o.newAnnotations) < 1 && len(o.removeAnnotations) < 1 { return fmt.Errorf("at least one annotation update is required") } return validateAnnotations(o.removeAnnotations, o.newAnnotations) } // RunAnnotate does the work func (o AnnotateOptions) RunAnnotate() error { b := o.builder. Unstructured(). LocalParam(o.local). ContinueOnError(). NamespaceParam(o.namespace).DefaultNamespace(). FilenameParam(o.enforceNamespace, &o.FilenameOptions). IncludeUninitialized(o.includeUninitialized). Flatten() if !o.local { b = b.LabelSelectorParam(o.selector). FieldSelectorParam(o.fieldSelector). ResourceTypeOrNameArgs(o.all, o.resources...). Latest() } r := b.Do() if err := r.Err(); err != nil { return err } var singleItemImpliedResource bool r.IntoSingleItemImplied(&singleItemImpliedResource) // only apply resource version locking on a single resource. // we must perform this check after o.builder.Do() as // []o.resources can not not accurately return the proper number // of resources when they are not passed in "resource/name" format. if !singleItemImpliedResource && len(o.resourceVersion) > 0 { return fmt.Errorf("--resource-version may only be used with a single resource") } return r.Visit(func(info *resource.Info, err error) error { if err != nil { return err } var outputObj runtime.Object obj := info.Object if o.dryrun || o.local { if err := o.updateAnnotations(obj); err != nil { return err } outputObj = obj } else { name, namespace := info.Name, info.Namespace oldData, err := json.Marshal(obj) if err != nil { return err } if err := o.Recorder.Record(info.Object); err != nil { glog.V(4).Infof("error recording current command: %v", err) } if err := o.updateAnnotations(obj); err != nil { return err } newData, err := json.Marshal(obj) if err != nil { return err } patchBytes, err := jsonpatch.CreateMergePatch(oldData, newData) createdPatch := err == nil if err != nil { glog.V(2).Infof("couldn't compute patch: %v", err) } mapping := info.ResourceMapping() client, err := o.unstructuredClientForMapping(mapping) if err != nil { return err } helper := resource.NewHelper(client, mapping) if createdPatch { outputObj, err = helper.Patch(namespace, name, types.MergePatchType, patchBytes) } else { outputObj, err = helper.Replace(namespace, name, false, obj) } if err != nil { return err } } return o.PrintObj(outputObj, o.Out) }) } // parseAnnotations retrieves new and remove annotations from annotation args func parseAnnotations(annotationArgs []string) (map[string]string, []string, error) { return cmdutil.ParsePairs(annotationArgs, "annotation", true) } // validateAnnotations checks the format of annotation args and checks removed annotations aren't in the new annotations map func validateAnnotations(removeAnnotations []string, newAnnotations map[string]string) error { var modifyRemoveBuf bytes.Buffer for _, removeAnnotation := range removeAnnotations { if _, found := newAnnotations[removeAnnotation]; found { if modifyRemoveBuf.Len() > 0 { modifyRemoveBuf.WriteString(", ") } modifyRemoveBuf.WriteString(fmt.Sprintf(removeAnnotation)) } } if modifyRemoveBuf.Len() > 0 { return fmt.Errorf("can not both modify and remove the following annotation(s) in the same command: %s", modifyRemoveBuf.String()) } return nil } // validateNoAnnotationOverwrites validates that when overwrite is false, to-be-updated annotations don't exist in the object annotation map (yet) func validateNoAnnotationOverwrites(accessor metav1.Object, annotations map[string]string) error { var buf bytes.Buffer for key := range annotations { // change-cause annotation can always be overwritten if key == kubectl.ChangeCauseAnnotation { continue } if value, found := accessor.GetAnnotations()[key]; found { if buf.Len() > 0 { buf.WriteString("; ") } buf.WriteString(fmt.Sprintf("'%s' already has a value (%s)", key, value)) } } if buf.Len() > 0 { return fmt.Errorf("--overwrite is false but found the following declared annotation(s): %s", buf.String()) } return nil } // updateAnnotations updates annotations of obj func (o AnnotateOptions) updateAnnotations(obj runtime.Object) error { accessor, err := meta.Accessor(obj) if err != nil { return err } if !o.overwrite { if err := validateNoAnnotationOverwrites(accessor, o.newAnnotations); err != nil { return err } } annotations := accessor.GetAnnotations() if annotations == nil { annotations = make(map[string]string) } for key, value := range o.newAnnotations { annotations[key] = value } for _, annotation := range o.removeAnnotations { delete(annotations, annotation) } accessor.SetAnnotations(annotations) if len(o.resourceVersion) != 0 { accessor.SetResourceVersion(o.resourceVersion) } return nil }
mdshuai/kubernetes
pkg/kubectl/cmd/annotate.go
GO
apache-2.0
13,212
--- title: Span page_title: Span | UI for WinForms Documentation description: Span slug: winforms/richtextbox-(obsolete)/features/document-elements/span tags: span published: True position: 4 previous_url: richtextbox-features-document-elements-span --- # Span The __Span__ class represents an inline object that allows you to display formatted text. The __Spans__ can only be used in the context of a __Paragraph__ class. As the spans are inline elements they get placed one after another and the text inside them gets wrapped to the next line if the space is insufficient. This topic demonstrates how to: * [Use Spans](#use-spans) * [Add Text to a Span](#add-text-to-a-span) * [Customize a Span](#customize-a-span) ## Use Spans The __Spans__can be used only in the context of the [Paragraph]({%slug winforms/richtextbox-(obsolete)/features/document-elements/paragraph%}) element. The __Paragraph__ exposes a collection of Inlines, to which the spans can be added. {{source=..\SamplesCS\RichTextBox\Features\Document Elements\RichTextBoxSpan.cs region=UseSpans}} {{source=..\SamplesVB\RichTextBox\Features\Document Elements\RichTextBoxSpan.vb region=UseSpans}} ````C# Section section = new Section(); Paragraph paragraph = new Paragraph(); Span span = new Span("Span declared in code-behind"); paragraph.Inlines.Add(span); section.Blocks.Add(paragraph); this.radRichTextBox1.Document.Sections.Add(section); ```` ````VB.NET Dim section As New Section() Dim paragraph As New Paragraph() Dim span As New Span("Span declared in code-behind") paragraph.Inlines.Add(span) section.Blocks.Add(paragraph) Me.RadRichTextBox1.Document.Sections.Add(section) ```` {{endregion}} ## Add Text to a Span To specify the text in the __Span__ you can use its __Text__ property. {{source=..\SamplesCS\RichTextBox\Features\Document Elements\RichTextBoxSpan.cs region=AddTextToSpan}} {{source=..\SamplesVB\RichTextBox\Features\Document Elements\RichTextBoxSpan.vb region=AddTextToSpan}} ````C# Span mySpan = new Span(); mySpan.Text = "Thank you for choosing Telerik RadRichTextBox!"; ```` ````VB.NET Dim mySpan As New Span() mySpan.Text = "Thank you for choosing Telerik RadRichTextBox!" ```` {{endregion}} >caution The Text property of Span cannot be set to an empty string, as Spans that do not contain any text are considered invalid. If you add an empty Span in the document programmatically, an exception will be thrown. > ## Customize a Span The __Span__ exposes several properties that allow you to customize the layout of the elements placed underneath it. Here is a list of them: * __BaselineAlignment__ - indicates whether the text is __Baseline__, __Subscript__ or __Superscript__. * __FontFamily__ - represents the name of the text's font. * __FontSize__ - represent the size of the text. * __FontStyle__ - indicates whether the text should have its style set to bold, italic or to normal. * __ForeColor__ - represents the foreground color for the text. * __HighlightColor__ - represents the background color for the text. * __Strikethrough__ - indicates whether the text should be stroke through. * __UnderlineType__ - indicates whether the text should be underlined.
telerik/winforms-docs
controls/richtextbox/features/document-elements/span.md
Markdown
apache-2.0
3,217
// Copyright 2018 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.google.api.ads.adwords.jaxws.v201809.cm; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; /** * * Returns a list of CampaignSharedSets based on the given selector. * @param selector the selector specifying the query * @return a list of CampaignSharedSet entities that meet the criterion specified * by the selector * @throws ApiException * * * <p>Java class for get element declaration. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;element name="get"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="selector" type="{https://adwords.google.com/api/adwords/cm/v201809}Selector" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "selector" }) @XmlRootElement(name = "get") public class CampaignSharedSetServiceInterfaceget { protected Selector selector; /** * Gets the value of the selector property. * * @return * possible object is * {@link Selector } * */ public Selector getSelector() { return selector; } /** * Sets the value of the selector property. * * @param value * allowed object is * {@link Selector } * */ public void setSelector(Selector value) { this.selector = value; } }
googleads/googleads-java-lib
modules/adwords_appengine/src/main/java/com/google/api/ads/adwords/jaxws/v201809/cm/CampaignSharedSetServiceInterfaceget.java
Java
apache-2.0
2,446
/* Copyright 2018 The Knative 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 testing import ( appsv1 "k8s.io/api/apps/v1" corev1 "k8s.io/api/core/v1" rbacv1 "k8s.io/api/rbac/v1" apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" fakeapiextensionsclientset "k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset/fake" apiextensionsv1listers "k8s.io/apiextensions-apiserver/pkg/client/listers/apiextensions/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" fakekubeclientset "k8s.io/client-go/kubernetes/fake" appsv1listers "k8s.io/client-go/listers/apps/v1" corev1listers "k8s.io/client-go/listers/core/v1" rbacv1listers "k8s.io/client-go/listers/rbac/v1" "k8s.io/client-go/tools/cache" sourcesv1beta2 "knative.dev/eventing/pkg/apis/sources/v1beta2" fakeeventingclientset "knative.dev/eventing/pkg/client/clientset/versioned/fake" sourcev1beta2listers "knative.dev/eventing/pkg/client/listers/sources/v1beta2" duckv1 "knative.dev/pkg/apis/duck/v1" "knative.dev/pkg/reconciler/testing" ) var subscriberAddToScheme = func(scheme *runtime.Scheme) error { scheme.AddKnownTypeWithName(schema.GroupVersionKind{Group: "testing.eventing.knative.dev", Version: "v1", Kind: "Subscriber"}, &unstructured.Unstructured{}) return nil } var sourceAddToScheme = func(scheme *runtime.Scheme) error { scheme.AddKnownTypeWithName(schema.GroupVersionKind{Group: "testing.sources.knative.dev", Version: "v1", Kind: "TestSource"}, &duckv1.Source{}) return nil } var clientSetSchemes = []func(*runtime.Scheme) error{ fakekubeclientset.AddToScheme, fakeeventingclientset.AddToScheme, fakeapiextensionsclientset.AddToScheme, subscriberAddToScheme, sourceAddToScheme, } type Listers struct { sorter testing.ObjectSorter } func NewScheme() *runtime.Scheme { scheme := runtime.NewScheme() for _, addTo := range clientSetSchemes { addTo(scheme) } return scheme } func NewListers(objs []runtime.Object) Listers { scheme := runtime.NewScheme() for _, addTo := range clientSetSchemes { addTo(scheme) } ls := Listers{ sorter: testing.NewObjectSorter(scheme), } ls.sorter.AddObjects(objs...) return ls } func (l *Listers) indexerFor(obj runtime.Object) cache.Indexer { return l.sorter.IndexerForObjectType(obj) } func (l *Listers) GetKubeObjects() []runtime.Object { return l.sorter.ObjectsForSchemeFunc(fakekubeclientset.AddToScheme) } func (l *Listers) GetEventingObjects() []runtime.Object { return l.sorter.ObjectsForSchemeFunc(fakeeventingclientset.AddToScheme) } func (l *Listers) GetAPIExtentionsObjects() []runtime.Object { return l.sorter.ObjectsForSchemeFunc(fakeapiextensionsclientset.AddToScheme) } func (l *Listers) GetSubscriberObjects() []runtime.Object { return l.sorter.ObjectsForSchemeFunc(subscriberAddToScheme) } func (l *Listers) GetAllObjects() []runtime.Object { all := l.GetSubscriberObjects() all = append(all, l.GetEventingObjects()...) all = append(all, l.GetKubeObjects()...) return all } func (l *Listers) GetPingSourceV1beta2Lister() sourcev1beta2listers.PingSourceLister { return sourcev1beta2listers.NewPingSourceLister(l.indexerFor(&sourcesv1beta2.PingSource{})) } func (l *Listers) GetDeploymentLister() appsv1listers.DeploymentLister { return appsv1listers.NewDeploymentLister(l.indexerFor(&appsv1.Deployment{})) } func (l *Listers) GetK8sServiceLister() corev1listers.ServiceLister { return corev1listers.NewServiceLister(l.indexerFor(&corev1.Service{})) } func (l *Listers) GetSecretLister() corev1listers.SecretLister { return corev1listers.NewSecretLister(l.indexerFor(&corev1.Secret{})) } func (l *Listers) GetNamespaceLister() corev1listers.NamespaceLister { return corev1listers.NewNamespaceLister(l.indexerFor(&corev1.Namespace{})) } func (l *Listers) GetServiceAccountLister() corev1listers.ServiceAccountLister { return corev1listers.NewServiceAccountLister(l.indexerFor(&corev1.ServiceAccount{})) } func (l *Listers) GetServiceLister() corev1listers.ServiceLister { return corev1listers.NewServiceLister(l.indexerFor(&corev1.Service{})) } func (l *Listers) GetRoleBindingLister() rbacv1listers.RoleBindingLister { return rbacv1listers.NewRoleBindingLister(l.indexerFor(&rbacv1.RoleBinding{})) } func (l *Listers) GetEndpointsLister() corev1listers.EndpointsLister { return corev1listers.NewEndpointsLister(l.indexerFor(&corev1.Endpoints{})) } func (l *Listers) GetConfigMapLister() corev1listers.ConfigMapLister { return corev1listers.NewConfigMapLister(l.indexerFor(&corev1.ConfigMap{})) } func (l *Listers) GetCustomResourceDefinitionLister() apiextensionsv1listers.CustomResourceDefinitionLister { return apiextensionsv1listers.NewCustomResourceDefinitionLister(l.indexerFor(&apiextensionsv1.CustomResourceDefinition{})) }
google/knative-gcp
vendor/knative.dev/eventing/pkg/reconciler/testing/listers.go
GO
apache-2.0
5,343
# AUTOGENERATED FILE FROM balenalib/jetson-tx1-fedora:34-run ENV GO_VERSION 1.16.3 # gcc for cgo RUN dnf install -y \ gcc-c++ \ gcc \ git \ && dnf clean all RUN mkdir -p /usr/local/go \ && curl -SLO "https://storage.googleapis.com/golang/go$GO_VERSION.linux-arm64.tar.gz" \ && echo "f4e96bbcd5d2d1942f5b55d9e4ab19564da4fad192012f6d7b0b9b055ba4208f go$GO_VERSION.linux-arm64.tar.gz" | sha256sum -c - \ && tar -xzf "go$GO_VERSION.linux-arm64.tar.gz" -C /usr/local/go --strip-components=1 \ && rm -f go$GO_VERSION.linux-arm64.tar.gz ENV GOROOT /usr/local/go ENV GOPATH /go ENV PATH $GOPATH/bin:/usr/local/go/bin:$PATH RUN mkdir -p "$GOPATH/src" "$GOPATH/bin" && chmod -R 777 "$GOPATH" WORKDIR $GOPATH 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/[email protected]" \ && echo "Running test-stack@golang" \ && chmod +x [email protected] \ && bash [email protected] \ && rm -rf [email protected] RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo $'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: ARM v8 \nOS: Fedora 34 \nVariant: run variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nGo v1.16.3 \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/golang/jetson-tx1/fedora/34/1.16.3/run/Dockerfile
Dockerfile
apache-2.0
2,071
# Using git with proxy Git-sync supports using a proxy through git-configuration. ## Background See [issue 180](https://github.com/kubernetes/git-sync/issues/180) for a background. See [Github documentation](https://docs.github.com/en/github/authenticating-to-github/using-ssh-over-the-https-port) specifically for GitHub. Lastly, [see similar issue for FluxCD](https://github.com/fluxcd/flux/pull/3152) for configuration. ## Step 1: Create configuration Create a ConfigMap to store your configuration: ```bash cat << EOF >> /tmp/ssh-config Host github.com ProxyCommand socat STDIO PROXY:<proxyIP>:%h:%p,proxyport=<proxyport>,proxyauth=<proxyAuth> User git Hostname ssh.github.com Port 443 IdentityFile /etc/git-secret/ssh EOF kubectl create configmap ssh-config --from-file=ssh-config=/tmp/ssh-config ``` then mount this under `~/.ssh/config`, typically `/tmp/.ssh/config`: ```yaml ... apiVersion: v1 kind: Pod ... spec: containers: - name: git-sync ... volumeMounts: - name: ssh-config mountPath: /tmp/.ssh/config readOnly: true subPath: ssh-config volumes: - name: ssh-config configMap: name: ssh-config ```
kubernetes/git-sync
docs/proxy.md
Markdown
apache-2.0
1,215
/** * AET * * Copyright (C) 2013 Cognifide 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. */ /* * Copyright [2016] [http://bmp.lightbody.net/] * * 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.browsermob.core.json; import java.io.IOException; import java.lang.reflect.Type; import java.text.DateFormat; import java.util.Date; import org.codehaus.jackson.JsonGenerationException; import org.codehaus.jackson.JsonGenerator; import org.codehaus.jackson.JsonNode; import org.codehaus.jackson.map.JsonMappingException; import org.codehaus.jackson.map.SerializerProvider; import org.codehaus.jackson.map.ser.ScalarSerializerBase; public class ISO8601DateFormatter extends ScalarSerializerBase<Date> { public final static ISO8601DateFormatter instance = new ISO8601DateFormatter(); public ISO8601DateFormatter() { super(Date.class); } @Override public void serialize(Date value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonGenerationException { DateFormat df = (DateFormat) provider.getConfig().getDateFormat().clone(); jgen.writeString(df.format(value)); } @Override public JsonNode getSchema(SerializerProvider provider, Type typeHint) throws JsonMappingException { return createSchemaNode("string", true); } }
Cognifide/AET
api/jobs-api/src/main/java/org/browsermob/core/json/ISO8601DateFormatter.java
Java
apache-2.0
2,315
package org.apache.lucene.index; /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.io.IOException; import org.apache.lucene.analysis.tokenattributes.OffsetAttribute; import org.apache.lucene.analysis.tokenattributes.PayloadAttribute; import org.apache.lucene.codecs.TermVectorsWriter; import org.apache.lucene.util.ByteBlockPool; import org.apache.lucene.util.BytesRef; import org.apache.lucene.util.RamUsageEstimator; final class TermVectorsConsumerPerField extends TermsHashConsumerPerField { final TermsHashPerField termsHashPerField; final TermVectorsConsumer termsWriter; final FieldInfo fieldInfo; final DocumentsWriterPerThread.DocState docState; final FieldInvertState fieldState; boolean doVectors; boolean doVectorPositions; boolean doVectorOffsets; boolean doVectorPayloads; int maxNumPostings; OffsetAttribute offsetAttribute; PayloadAttribute payloadAttribute; boolean hasPayloads; // if enabled, and we actually saw any for this field public TermVectorsConsumerPerField(TermsHashPerField termsHashPerField, TermVectorsConsumer termsWriter, FieldInfo fieldInfo) { this.termsHashPerField = termsHashPerField; this.termsWriter = termsWriter; this.fieldInfo = fieldInfo; docState = termsHashPerField.docState; fieldState = termsHashPerField.fieldState; } @Override int getStreamCount() { return 2; } @Override boolean start(IndexableField[] fields, int count) { doVectors = false; doVectorPositions = false; doVectorOffsets = false; doVectorPayloads = false; hasPayloads = false; for(int i=0;i<count;i++) { IndexableField field = fields[i]; if (field.fieldType().indexed()) { if (field.fieldType().storeTermVectors()) { doVectors = true; doVectorPositions |= field.fieldType().storeTermVectorPositions(); doVectorOffsets |= field.fieldType().storeTermVectorOffsets(); if (doVectorPositions) { doVectorPayloads |= field.fieldType().storeTermVectorPayloads(); } else if (field.fieldType().storeTermVectorPayloads()) { // TODO: move this check somewhere else, and impl the other missing ones throw new IllegalArgumentException("cannot index term vector payloads without term vector positions (field=\"" + field.name() + "\")"); } } else { if (field.fieldType().storeTermVectorOffsets()) { throw new IllegalArgumentException("cannot index term vector offsets when term vectors are not indexed (field=\"" + field.name() + "\")"); } if (field.fieldType().storeTermVectorPositions()) { throw new IllegalArgumentException("cannot index term vector positions when term vectors are not indexed (field=\"" + field.name() + "\")"); } if (field.fieldType().storeTermVectorPayloads()) { throw new IllegalArgumentException("cannot index term vector payloads when term vectors are not indexed (field=\"" + field.name() + "\")"); } } } else { if (field.fieldType().storeTermVectors()) { throw new IllegalArgumentException("cannot index term vectors when field is not indexed (field=\"" + field.name() + "\")"); } if (field.fieldType().storeTermVectorOffsets()) { throw new IllegalArgumentException("cannot index term vector offsets when field is not indexed (field=\"" + field.name() + "\")"); } if (field.fieldType().storeTermVectorPositions()) { throw new IllegalArgumentException("cannot index term vector positions when field is not indexed (field=\"" + field.name() + "\")"); } if (field.fieldType().storeTermVectorPayloads()) { throw new IllegalArgumentException("cannot index term vector payloads when field is not indexed (field=\"" + field.name() + "\")"); } } } if (doVectors) { termsWriter.hasVectors = true; if (termsHashPerField.bytesHash.size() != 0) { // Only necessary if previous doc hit a // non-aborting exception while writing vectors in // this field: termsHashPerField.reset(); } } // TODO: only if needed for performance //perThread.postingsCount = 0; return doVectors; } public void abort() {} /** Called once per field per document if term vectors * are enabled, to write the vectors to * RAMOutputStream, which is then quickly flushed to * the real term vectors files in the Directory. */ @Override void finish() { if (!doVectors || termsHashPerField.bytesHash.size() == 0) { return; } termsWriter.addFieldToFlush(this); } void finishDocument() throws IOException { assert docState.testPoint("TermVectorsTermsWriterPerField.finish start"); final int numPostings = termsHashPerField.bytesHash.size(); final BytesRef flushTerm = termsWriter.flushTerm; assert numPostings >= 0; if (numPostings > maxNumPostings) maxNumPostings = numPostings; // This is called once, after inverting all occurrences // of a given field in the doc. At this point we flush // our hash into the DocWriter. assert termsWriter.vectorFieldsInOrder(fieldInfo); TermVectorsPostingsArray postings = (TermVectorsPostingsArray) termsHashPerField.postingsArray; final TermVectorsWriter tv = termsWriter.writer; final int[] termIDs = termsHashPerField.sortPostings(); tv.startField(fieldInfo, numPostings, doVectorPositions, doVectorOffsets, hasPayloads); final ByteSliceReader posReader = doVectorPositions ? termsWriter.vectorSliceReaderPos : null; final ByteSliceReader offReader = doVectorOffsets ? termsWriter.vectorSliceReaderOff : null; final ByteBlockPool termBytePool = termsHashPerField.termBytePool; for(int j=0;j<numPostings;j++) { final int termID = termIDs[j]; final int freq = postings.freqs[termID]; // Get BytesRef termBytePool.setBytesRef(flushTerm, postings.textStarts[termID]); tv.startTerm(flushTerm, freq); if (doVectorPositions || doVectorOffsets) { if (posReader != null) { termsHashPerField.initReader(posReader, termID, 0); } if (offReader != null) { termsHashPerField.initReader(offReader, termID, 1); } tv.addProx(freq, posReader, offReader); } tv.finishTerm(); } tv.finishField(); termsHashPerField.reset(); fieldInfo.setStoreTermVectors(); } @Override void start(IndexableField f) { if (doVectorOffsets) { offsetAttribute = fieldState.attributeSource.addAttribute(OffsetAttribute.class); } else { offsetAttribute = null; } if (doVectorPayloads && fieldState.attributeSource.hasAttribute(PayloadAttribute.class)) { payloadAttribute = fieldState.attributeSource.getAttribute(PayloadAttribute.class); } else { payloadAttribute = null; } } void writeProx(TermVectorsPostingsArray postings, int termID) { if (doVectorOffsets) { int startOffset = fieldState.offset + offsetAttribute.startOffset(); int endOffset = fieldState.offset + offsetAttribute.endOffset(); termsHashPerField.writeVInt(1, startOffset - postings.lastOffsets[termID]); termsHashPerField.writeVInt(1, endOffset - startOffset); postings.lastOffsets[termID] = endOffset; } if (doVectorPositions) { final BytesRef payload; if (payloadAttribute == null) { payload = null; } else { payload = payloadAttribute.getPayload(); } final int pos = fieldState.position - postings.lastPositions[termID]; if (payload != null && payload.length > 0) { termsHashPerField.writeVInt(0, (pos<<1)|1); termsHashPerField.writeVInt(0, payload.length); termsHashPerField.writeBytes(0, payload.bytes, payload.offset, payload.length); hasPayloads = true; } else { termsHashPerField.writeVInt(0, pos<<1); } postings.lastPositions[termID] = fieldState.position; } } @Override void newTerm(final int termID) { assert docState.testPoint("TermVectorsTermsWriterPerField.newTerm start"); TermVectorsPostingsArray postings = (TermVectorsPostingsArray) termsHashPerField.postingsArray; postings.freqs[termID] = 1; postings.lastOffsets[termID] = 0; postings.lastPositions[termID] = 0; writeProx(postings, termID); } @Override void addTerm(final int termID) { assert docState.testPoint("TermVectorsTermsWriterPerField.addTerm start"); TermVectorsPostingsArray postings = (TermVectorsPostingsArray) termsHashPerField.postingsArray; postings.freqs[termID]++; writeProx(postings, termID); } @Override void skippingLongTerm() {} @Override ParallelPostingsArray createPostingsArray(int size) { return new TermVectorsPostingsArray(size); } static final class TermVectorsPostingsArray extends ParallelPostingsArray { public TermVectorsPostingsArray(int size) { super(size); freqs = new int[size]; lastOffsets = new int[size]; lastPositions = new int[size]; } int[] freqs; // How many times this term occurred in the current doc int[] lastOffsets; // Last offset we saw int[] lastPositions; // Last position where this term occurred @Override ParallelPostingsArray newInstance(int size) { return new TermVectorsPostingsArray(size); } @Override void copyTo(ParallelPostingsArray toArray, int numToCopy) { assert toArray instanceof TermVectorsPostingsArray; TermVectorsPostingsArray to = (TermVectorsPostingsArray) toArray; super.copyTo(toArray, numToCopy); System.arraycopy(freqs, 0, to.freqs, 0, size); System.arraycopy(lastOffsets, 0, to.lastOffsets, 0, size); System.arraycopy(lastPositions, 0, to.lastPositions, 0, size); } @Override int bytesPerPosting() { return super.bytesPerPosting() + 3 * RamUsageEstimator.NUM_BYTES_INT; } } }
fogbeam/Heceta_solr
lucene/core/src/java/org/apache/lucene/index/TermVectorsConsumerPerField.java
Java
apache-2.0
10,979
# # Author:: Scott Bonds ([email protected]) # Copyright:: Copyright 2014-2016, Scott Bonds # License:: Apache License, Version 2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # require "spec_helper" require "ostruct" describe Chef::Provider::Package::Openbsd do let(:node) do node = Chef::Node.new node.default["kernel"] = { "name" => "OpenBSD", "release" => "5.5", "machine" => "amd64" } node end let (:provider) do events = Chef::EventDispatch::Dispatcher.new run_context = Chef::RunContext.new(node, {}, events) Chef::Provider::Package::Openbsd.new(new_resource, run_context) end let(:new_resource) { Chef::Resource::Package.new(name) } before(:each) do ENV["PKG_PATH"] = nil end describe "install a package" do let(:name) { "ihavetoes" } let(:version) { "0.0" } context "when not already installed" do before do allow(provider).to receive(:shell_out_compacted!).with("pkg_info", "-e", "#{name}->0", anything).and_return(instance_double("shellout", stdout: "")) end context "when there is a single candidate" do context "when source is not provided" do it "should run the installation command" do expect(provider).to receive(:shell_out_compacted!).with("pkg_info", "-I", name, anything).and_return( instance_double("shellout", stdout: "#{name}-#{version}\n") ) expect(provider).to receive(:shell_out_compacted!).with( "pkg_add", "-r", "#{name}-#{version}", { env: { "PKG_PATH" => "http://ftp.OpenBSD.org/pub/OpenBSD/5.5/packages/amd64/" }, timeout: 900 } ) { OpenStruct.new status: true } provider.run_action(:install) end end end context "when there are multiple candidates" do let(:flavor_a) { "flavora" } let(:flavor_b) { "flavorb" } context "if no version is specified" do it "should raise an exception" do expect(provider).to receive(:shell_out_compacted!).with("pkg_info", "-I", name, anything).and_return( instance_double("shellout", stdout: "#{name}-#{version}-#{flavor_a}\n#{name}-#{version}-#{flavor_b}\n") ) expect { provider.run_action(:install) }.to raise_error(Chef::Exceptions::Package, /multiple matching candidates/) end end context "if a flavor is specified" do let(:flavor) { "flavora" } let(:package_name) { "ihavetoes" } let(:name) { "#{package_name}--#{flavor}" } context "if no version is specified" do it "should run the installation command" do expect(provider).to receive(:shell_out_compacted!).with("pkg_info", "-e", "#{package_name}->0", anything).and_return(instance_double("shellout", stdout: "")) expect(provider).to receive(:shell_out_compacted!).with("pkg_info", "-I", name, anything).and_return( instance_double("shellout", stdout: "#{name}-#{version}-#{flavor}\n") ) expect(provider).to receive(:shell_out_compacted!).with( "pkg_add", "-r", "#{name}-#{version}-#{flavor}", { env: { "PKG_PATH" => "http://ftp.OpenBSD.org/pub/OpenBSD/5.5/packages/amd64/" }, timeout: 900 } ) { OpenStruct.new status: true } provider.run_action(:install) end end end context "if a version is specified" do it "should use the flavor from the version" do expect(provider).to receive(:shell_out_compacted!).with("pkg_info", "-I", "#{name}-#{version}-#{flavor_b}", anything).and_return( instance_double("shellout", stdout: "#{name}-#{version}-#{flavor_a}\n") ) new_resource.version("#{version}-#{flavor_b}") expect(provider).to receive(:shell_out_compacted!).with( "pkg_add", "-r", "#{name}-#{version}-#{flavor_b}", { env: { "PKG_PATH" => "http://ftp.OpenBSD.org/pub/OpenBSD/5.5/packages/amd64/" }, timeout: 900 } ) { OpenStruct.new status: true } provider.run_action(:install) end end end end end describe "delete a package" do before do @name = "ihavetoes" @new_resource = Chef::Resource::Package.new(@name) @current_resource = Chef::Resource::Package.new(@name) @provider = Chef::Provider::Package::Openbsd.new(@new_resource, @run_context) @provider.current_resource = @current_resource end it "should run the command to delete the installed package" do expect(@provider).to receive(:shell_out_compacted!).with( "pkg_delete", @name, env: nil, timeout: 900 ) { OpenStruct.new status: true } @provider.remove_package(@name, nil) end end end
jaymzh/chef
spec/unit/provider/package/openbsd_spec.rb
Ruby
apache-2.0
5,369
/* * Copyright 2011 Ning, Inc. * * Ning 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.mogwee.executors; import java.util.concurrent.ThreadFactory; import java.util.concurrent.atomic.AtomicInteger; /** * Factory that sets the name of each thread it creates to {@code [name]-[id]}. * This makes debugging stack traces much easier. */ public class NamedThreadFactory implements ThreadFactory { private final AtomicInteger count = new AtomicInteger(0); private final String name; public NamedThreadFactory(String name) { this.name = name; } @Override public Thread newThread(final Runnable runnable) { Thread thread = new Thread(runnable); thread.setName(name + "-" + count.incrementAndGet()); return thread; } }
twilliamson/mogwee-executors
src/main/java/com/mogwee/executors/NamedThreadFactory.java
Java
apache-2.0
1,331
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.6.0_11) on Mon Oct 19 11:00:57 CEST 2009 --> <META http-equiv="Content-Type" content="text/html; charset=UTF-8"> <TITLE> Uses of Class org.apache.mina.statemachine.annotation.IoHandlerTransitions (Apache MINA 2.0.0-RC1 API Documentation) </TITLE> <META NAME="date" CONTENT="2009-10-19"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class org.apache.mina.statemachine.annotation.IoHandlerTransitions (Apache MINA 2.0.0-RC1 API Documentation)"; } } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <HR> <!-- ========= START OF TOP NAVBAR ======= --> <A NAME="navbar_top"><!-- --></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../org/apache/mina/statemachine/annotation/IoHandlerTransitions.html" title="annotation in org.apache.mina.statemachine.annotation"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../../index.html?org/apache/mina/statemachine/annotation//class-useIoHandlerTransitions.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="IoHandlerTransitions.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <CENTER> <H2> <B>Uses of Class<br>org.apache.mina.statemachine.annotation.IoHandlerTransitions</B></H2> </CENTER> No usage of org.apache.mina.statemachine.annotation.IoHandlerTransitions <P> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <A NAME="navbar_bottom"><!-- --></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../org/apache/mina/statemachine/annotation/IoHandlerTransitions.html" title="annotation in org.apache.mina.statemachine.annotation"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../../index.html?org/apache/mina/statemachine/annotation//class-useIoHandlerTransitions.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="IoHandlerTransitions.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> Copyright &#169; 2004-2009 <a href="http://mina.apache.org/">Apache MINA Project</a>. All Rights Reserved. </BODY> </HTML>
sardine/mina-ja
docs/apidocs/org/apache/mina/statemachine/annotation/class-use/IoHandlerTransitions.html
HTML
apache-2.0
6,444
# # farmwork/forms.py # from django import forms from django.utils.text import slugify from .models import Farmwork # ======================================================== # FARMWORK FORM # ======================================================== class FarmworkForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(FarmworkForm, self).__init__(*args, **kwargs) class Meta: model = Farmwork fields = [ 'job_role', 'job_fruit', 'job_pay', 'job_pay_type', 'job_start_date', 'job_duration', 'job_duration_type', 'job_description', 'con_first_name', 'con_surname', 'con_number', 'con_email', 'con_description', 'acc_variety', 'acc_price', 'acc_price_type', 'acc_description', 'loc_street_address', 'loc_city', 'loc_state', 'loc_post_code', ] # -- # AUTO GENERATE SLUG ON SAVE # Credit: https://keyerror.com/blog/automatically-generating-unique-slugs-in-django # -- def save(self): if self.instance.pk: return super(FarmworkForm, self).save() instance = super(FarmworkForm, self).save(commit=False) instance.slug = slugify(instance.get_job_fruit_display() + '-' + instance.get_job_role_display() + '-in-' + instance.loc_city) instance.save() return instance
ianmilliken/rwf
backend/apps/farmwork/forms.py
Python
apache-2.0
1,542
namespace Konves.ChordPro.Directives { public sealed class CommentBoxDirective : Directive { public CommentBoxDirective(string text) { Text = text; } public string Text { get; set; } } }
skonves/Konves.ChordPro
src/Konves.ChordPro/Directives/CommentBoxDirective.cs
C#
apache-2.0
205
from django.contrib.auth.models import AnonymousUser from core.models import Identity from api.v2.serializers.post import AccountSerializer from api.v2.views.base import AdminAuthViewSet class AccountViewSet(AdminAuthViewSet): """ API endpoint that allows providers to be viewed or edited. """ lookup_fields = ("id", "uuid") queryset = Identity.objects.all() serializer_class = AccountSerializer http_method_names = ['post', 'head', 'options', 'trace'] def get_queryset(self): """ Filter providers by current user """ user = self.request.user if (type(user) == AnonymousUser): return Identity.objects.none() identities = user.current_identities() return identities
CCI-MOC/GUI-Backend
api/v2/views/account.py
Python
apache-2.0
771
--- title: raft(2) categories: 分布式算法 tags: Raft --- ## 概念 ### 1. Term ![term](../images/raft/raft_term.png) raft中,将时间划分成了一段一段的,每一段成为一个term。每当发起一次领导竞选(leader election)时,term会加1。 由图可以看到蓝色为election时期,绿色为leader带领follower正常操作时期。但也可以看到term3只有leader election,且之后马上又是leader election,但term已经变为4了。但term3到term4这是怎么回事呢?不急慢慢来,暂且先明白term的含义 ### 2. HeartBeat raft算法是一个分区容错共识算法,因此它需要具有判断分区是否发生故障。leader节点会每隔一段时间就向follower节点发送一个心跳信息,然后follower节点会返回一个消息,以此来判断节点是否发生故障或者分区故障。这个行为称为heartBeat。 ### 3. election timeout 上面说了,leader节点每隔一段时间会向follower节点发送一个心跳信息。如果leader节点没有发送呢? 如果follower节点在election timeout这个时间内没有收到心跳信息,则会发起新一轮竞选。election timeout和heart beat的时间不一样,且心跳的时间远远小于election timeout ### 4. Role ![raft_role](../images/raft/raft_role.png) 各角色职责: follower: 1. 接收心跳信息 2. 当在election timeout未接收 ## 工具 ### AppendEntries RPC |Arguments:|| |:--:|:--:| |term|leader的term| |leaderId|leader所在服务器id| |prevLogIndex|| |prevLogTerm|| |entries[]|日志数组| |leaderCommit|leader当前已经commit的log index| |**Results:**|| |term|| |success|| ### RequestVote RPC | Arguments: | | | :----------: | :-----------------------------: | | term | candidate的term number | | candidateId | candidate的id | | lastLogIndex | candidate最近一条日志的索引 | | lastLogTerm | candidate最近一条日志的term编号 | | **Results:** | | | term | | | voteGranted | |
gobraves/gobraves.github.io
source/_drafts/raft-2.md
Markdown
apache-2.0
2,173
<?php $test = array('2004', '2005', '2006'); $test2 = array('1000', '1170', '660'); $end = array_pop($test); $end2 = array_pop($test2); ?> <html> <head> <script type="text/javascript" src="https://www.google.com/jsapi?autoload={ 'modules':[{ 'name':'visualization', 'version':'1', 'packages':['corechart'] }] }"></script> <script type="text/javascript"> google.setOnLoadCallback(drawChart); function drawChart() { var data = google.visualization.arrayToDataTable([ ['Year', 'Sales'], <?php foreach (array_combine($test, $test2) as $nb => $nb2) { echo '["'.$nb.'", '.$nb2."],"; echo "\n"; } echo '["'.$end.'", '.$end2."]"; ?> ]); var options = { title: 'Company Performance', curveType: 'function', legend: { position: 'bottom' } }; var chart = new google.visualization.LineChart(document.getElementById('curve_chart')); chart.draw(data, options); } </script> </head> <body> <div id="curve_chart" style="width: 900px; height: 500px"></div> </body> </html>
LamaDelRay/codecampECOMMERCE
index.php
PHP
apache-2.0
1,233
/* * Copyright (C) 2015 The Gravitee team (http://gravitee.io) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import ApiCreationController from './api-creation.controller'; import { shouldDisplayHint } from './form.helper'; import ApiPrimaryOwnerModeService from '../../../../services/apiPrimaryOwnerMode.service'; const ApiCreationStep1Component: ng.IComponentOptions = { require: { parent: '^apiCreation', }, template: require('./api-creation-step1.html'), controller: class { private parent: ApiCreationController; private advancedMode: boolean; private useGroupAsPrimaryOwner: boolean; public shouldDisplayHint = shouldDisplayHint; constructor(private ApiPrimaryOwnerModeService: ApiPrimaryOwnerModeService) { 'ngInject'; this.advancedMode = false; this.useGroupAsPrimaryOwner = this.ApiPrimaryOwnerModeService.isGroupOnly(); } toggleAdvancedMode = () => { this.advancedMode = !this.advancedMode; if (!this.advancedMode) { this.parent.api.groups = []; } }; canUseAdvancedMode = () => { return ( (this.ApiPrimaryOwnerModeService.isHybrid() && ((this.parent.attachableGroups && this.parent.attachableGroups.length > 0) || (this.parent.poGroups && this.parent.poGroups.length > 0))) || (this.ApiPrimaryOwnerModeService.isGroupOnly() && this.parent.attachableGroups && this.parent.attachableGroups.length > 0) ); }; }, }; export default ApiCreationStep1Component;
gravitee-io/gravitee-management-webui
src/management/api/creation/steps/api-creation-step1.component.ts
TypeScript
apache-2.0
2,038
/* * Copyright 2013 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 de.micromata.jira.rest.core.misc; /** * @author Christian Schulze * @author Vitali Filippow */ public interface RestPathConstants { // Common Stuff for Jersey Client String AUTHORIZATION = "Authorization"; String BASIC = "Basic"; // REST Paths String BASE_REST_PATH = "/rest/api/2"; String PROJECT = "/project"; String USER = "/user"; String SEARCH = "/search"; String ISSUE = "/issue"; String COMMENT = "/comment"; String VERSIONS = "/versions"; String COMPONENTS = "/components"; String ISSUETPYES = "/issuetype"; String STATUS = "/status"; String PRIORITY = "/priority"; String TRANSITIONS = "/transitions"; String WORKLOG = "/worklog"; String ATTACHMENTS = "/attachments"; String ATTACHMENT = "/attachment"; String ASSIGNABLE = "/assignable"; String FILTER = "/filter"; String FAVORITE = "/favourite"; String FIELD = "/field"; String META = "/meta"; String CREATEMETA = "/createmeta"; String MYPERMISSIONS = "/mypermissions"; String CONFIGURATION = "/configuration"; }
micromata/jiraRestClient
src/main/java/de/micromata/jira/rest/core/misc/RestPathConstants.java
Java
apache-2.0
1,734
/***************************************************************************** * Copyright (C) jparsec.org * * ------------------------------------------------------------------------- * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * *****************************************************************************/ package org.jparsec.examples.sql.parser; import static org.jparsec.examples.sql.parser.TerminalParser.phrase; import static org.jparsec.examples.sql.parser.TerminalParser.term; import java.util.List; import java.util.function.BinaryOperator; import java.util.function.UnaryOperator; import org.jparsec.OperatorTable; import org.jparsec.Parser; import org.jparsec.Parsers; import org.jparsec.examples.sql.ast.BetweenExpression; import org.jparsec.examples.sql.ast.BinaryExpression; import org.jparsec.examples.sql.ast.BinaryRelationalExpression; import org.jparsec.examples.sql.ast.Expression; import org.jparsec.examples.sql.ast.FullCaseExpression; import org.jparsec.examples.sql.ast.FunctionExpression; import org.jparsec.examples.sql.ast.LikeExpression; import org.jparsec.examples.sql.ast.NullExpression; import org.jparsec.examples.sql.ast.NumberExpression; import org.jparsec.examples.sql.ast.Op; import org.jparsec.examples.sql.ast.QualifiedName; import org.jparsec.examples.sql.ast.QualifiedNameExpression; import org.jparsec.examples.sql.ast.Relation; import org.jparsec.examples.sql.ast.SimpleCaseExpression; import org.jparsec.examples.sql.ast.StringExpression; import org.jparsec.examples.sql.ast.TupleExpression; import org.jparsec.examples.sql.ast.UnaryExpression; import org.jparsec.examples.sql.ast.UnaryRelationalExpression; import org.jparsec.examples.sql.ast.WildcardExpression; import org.jparsec.functors.Pair; /** * Parser for expressions. * * @author Ben Yu */ public final class ExpressionParser { static final Parser<Expression> NULL = term("null").<Expression>retn(NullExpression.instance); static final Parser<Expression> NUMBER = TerminalParser.NUMBER.map(NumberExpression::new); static final Parser<Expression> QUALIFIED_NAME = TerminalParser.QUALIFIED_NAME .map(QualifiedNameExpression::new); static final Parser<Expression> QUALIFIED_WILDCARD = TerminalParser.QUALIFIED_NAME .followedBy(phrase(". *")) .map(WildcardExpression::new); static final Parser<Expression> WILDCARD = term("*").<Expression>retn(new WildcardExpression(QualifiedName.of())) .or(QUALIFIED_WILDCARD); static final Parser<Expression> STRING = TerminalParser.STRING.map(StringExpression::new); static Parser<Expression> functionCall(Parser<Expression> param) { return Parsers.sequence( TerminalParser.QUALIFIED_NAME, paren(param.sepBy(TerminalParser.term(","))), FunctionExpression::new); } static Parser<Expression> tuple(Parser<Expression> expr) { return paren(expr.sepBy(term(","))).map(TupleExpression::new); } static Parser<Expression> simpleCase(Parser<Expression> expr) { return Parsers.sequence( term("case").next(expr), whenThens(expr, expr), term("else").next(expr).optional().followedBy(term("end")), SimpleCaseExpression::new); } static Parser<Expression> fullCase(Parser<Expression> cond, Parser<Expression> expr) { return Parsers.sequence( term("case").next(whenThens(cond, expr)), term("else").next(expr).optional().followedBy(term("end")), FullCaseExpression::new); } private static Parser<List<Pair<Expression, Expression>>> whenThens( Parser<Expression> cond, Parser<Expression> expr) { return Parsers.pair(term("when").next(cond), term("then").next(expr)).many1(); } static <T> Parser<T> paren(Parser<T> parser) { return parser.between(term("("), term(")")); } static Parser<Expression> arithmetic(Parser<Expression> atom) { Parser.Reference<Expression> reference = Parser.newReference(); Parser<Expression> operand = Parsers.or(paren(reference.lazy()), functionCall(reference.lazy()), atom); Parser<Expression> parser = new OperatorTable<Expression>() .infixl(binary("+", Op.PLUS), 10) .infixl(binary("-", Op.MINUS), 10) .infixl(binary("*", Op.MUL), 20) .infixl(binary("/", Op.DIV), 20) .infixl(binary("%", Op.MOD), 20) .prefix(unary("-", Op.NEG), 50) .build(operand); reference.set(parser); return parser; } static Parser<Expression> expression(Parser<Expression> cond) { Parser.Reference<Expression> reference = Parser.newReference(); Parser<Expression> lazyExpr = reference.lazy(); Parser<Expression> atom = Parsers.or( NUMBER, WILDCARD, QUALIFIED_NAME, simpleCase(lazyExpr), fullCase(cond, lazyExpr)); Parser<Expression> expression = arithmetic(atom).label("expression"); reference.set(expression); return expression; } /************************** boolean expressions ****************************/ static Parser<Expression> compare(Parser<Expression> expr) { return Parsers.or( compare(expr, ">", Op.GT), compare(expr, ">=", Op.GE), compare(expr, "<", Op.LT), compare(expr, "<=", Op.LE), compare(expr, "=", Op.EQ), compare(expr, "<>", Op.NE), nullCheck(expr), like(expr), between(expr)); } static Parser<Expression> like(Parser<Expression> expr) { return Parsers.sequence( expr, Parsers.or(term("like").retn(true), phrase("not like").retn(false)), expr, term("escape").next(expr).optional(), LikeExpression::new); } static Parser<Expression> nullCheck(Parser<Expression> expr) { return Parsers.sequence( expr, phrase("is not").retn(Op.NOT).or(phrase("is").retn(Op.IS)), NULL, BinaryExpression::new); } static Parser<Expression> logical(Parser<Expression> expr) { Parser.Reference<Expression> ref = Parser.newReference(); Parser<Expression> parser = new OperatorTable<Expression>() .prefix(unary("not", Op.NOT), 30) .infixl(binary("and", Op.AND), 20) .infixl(binary("or", Op.OR), 10) .build(paren(ref.lazy()).or(expr)).label("logical expression"); ref.set(parser); return parser; } static Parser<Expression> between(Parser<Expression> expr) { return Parsers.sequence( expr, Parsers.or(term("between").retn(true), phrase("not between").retn(false)), expr, term("and").next(expr), BetweenExpression::new); } static Parser<Expression> exists(Parser<Relation> relation) { return term("exists").next(relation).map(e -> new UnaryRelationalExpression(e, Op.EXISTS)); } static Parser<Expression> notExists(Parser<Relation> relation) { return phrase("not exists").next(relation) .map(e -> new UnaryRelationalExpression(e, Op.NOT_EXISTS)); } static Parser<Expression> inRelation(Parser<Expression> expr, Parser<Relation> relation) { return Parsers.sequence( expr, Parsers.between(phrase("in ("), relation, term(")")), (e, r) -> new BinaryRelationalExpression(e, Op.IN, r)); } static Parser<Expression> notInRelation(Parser<Expression> expr, Parser<Relation> relation) { return Parsers.sequence( expr, Parsers.between(phrase("not in ("), relation, term(")")), (e, r) -> new BinaryRelationalExpression(e, Op.NOT_IN, r)); } static Parser<Expression> in(Parser<Expression> expr) { return Parsers.sequence( expr, term("in").next(tuple(expr)), (e, t) -> new BinaryExpression(e, Op.IN, t)); } static Parser<Expression> notIn(Parser<Expression> expr) { return Parsers.sequence( expr, phrase("not in").next(tuple(expr)), (e, t) -> new BinaryExpression(e, Op.NOT_IN, t)); } static Parser<Expression> condition(Parser<Expression> expr, Parser<Relation> rel) { Parser<Expression> atom = Parsers.or( compare(expr), in(expr), notIn(expr), exists(rel), notExists(rel), inRelation(expr, rel), notInRelation(expr, rel)); return logical(atom); } /************************** utility methods ****************************/ private static Parser<Expression> compare( Parser<Expression> operand, String name, Op op) { return Parsers.sequence( operand, term(name).retn(op), operand, BinaryExpression::new); } private static Parser<BinaryOperator<Expression>> binary(String name, Op op) { return term(name).retn((l, r) -> new BinaryExpression(l, op, r)); } private static Parser<UnaryOperator<Expression>> unary(String name, Op op) { return term(name).retn(e -> new UnaryExpression(op, e)); } }
jparsec/jparsec
jparsec-examples/src/main/java/org/jparsec/examples/sql/parser/ExpressionParser.java
Java
apache-2.0
9,523
--- title: Over the Moon for June! date: 2016-06-01 00:00:00 -06:00 categories: - whats-blooming layout: post blog-banner: whats-blooming-now-summer.jpg post-date: June 01, 2016 post-time: 4:33 PM blog-image: wbn-default.jpg --- <div class="text-center"> Here at the Garden, we are over the moon excited for the warm weather that brings an abundance of flowers. Now that it is June and many of you are out of school and the official start of summer is right around the corner, there is no excuse to not be at Red Butte enjoying nature's splendor.</div> <div class="text-center"> <img src="/images/blogs/Opuntia%20polyacantha%20Flower%20HMS16.jpg" width="560" height="420" alt="" title="" /> <p>Plains Pricklypear &nbsp;&nbsp;<i> Opuntia polyacantha</i></p> <p>This plant may be prickly but it sure is pretty! Can be seen near Hobb's Bench.</p> </div> <div class="text-center"> <img src="/images/blogs/Natural%20Area%20HMS16.jpg" width="560" height="420" alt="" title="" /> <p>Natural Area</p> <p>Be sure to hike through the Natural Area while you are here, the scene is breathtaking.</p> </div> <div class="text-center"> <img src="/images/blogs/Baptisia%20australis%20%27Bluemound%27%20Flower%20HMS16.jpg" width="560" height="1103" alt="" title="" /> <p>Bluemound False Indigo &nbsp;&nbsp;<i> Baptisia australis </i> 'Bluemound'</p> <p>Along the Floral Walk, these exciting flowers are sure to lift your spirits.</p> </div> <div class="text-center"> <img src="/images/blogs/Yucca%20angustissima%20Habit%20and%20Flower%20HMS16.jpg" width="560" height="1088" alt="" title="" /> <p>Narrow-leaf Yucca &nbsp;&nbsp;<i> Yucca angustissima</i></p> <p>These unique flowers are thick and waxy and can only be pollinated by the Pronuba moth. You will find this native beauty at Hobb's Bench.</p> </div> <div class="text-center"> <img src="/images/blogs/Picea%20orientalis%20%27Aureospicata%27%20Habit%20and%20New%20Growth%20HMS16.jpg" width="560" height="810" alt="" title="" /> <p>Golden Candle Oriental Spruce &nbsp;&nbsp;<i> Picea orientalis</i> 'Aureospicata'</p> <p>On the way to Hobb's Bench, check out the wonderful contrast of yellow new growth against the dark green old growth. Amazing right?!</p> </div> <div class="text-center"> The sun is shining, so put on your sunblock and come see the Garden blooming with magnificent color.</div> <h5 class="text-center green">Photos by Heidi Simper</h5>
jonroler/rbgmd
_posts/2016-06-01-over-the-moon-for-june.md
Markdown
apache-2.0
2,444
/* * Copyright 2004-2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.grails.web.json; import static org.codehaus.groovy.grails.web.json.JSONWriter.Mode.ARRAY; import static org.codehaus.groovy.grails.web.json.JSONWriter.Mode.KEY; import static org.codehaus.groovy.grails.web.json.JSONWriter.Mode.OBJECT; import java.io.IOException; import java.io.Writer; /** * A JSONWriter dedicated to create indented/pretty printed output. * * @author Siegfried Puchbauer * @since 1.1 */ public class PrettyPrintJSONWriter extends JSONWriter { public static final String DEFAULT_INDENT_STR = " "; public static final String NEWLINE; static { String nl = System.getProperty("line.separator"); NEWLINE = nl != null ? nl : "\n"; } private int indentLevel = 0; private final String indentStr; public PrettyPrintJSONWriter(Writer w) { this(w, DEFAULT_INDENT_STR); } public PrettyPrintJSONWriter(Writer w, String indentStr) { super(w); this.indentStr = indentStr; } private void newline() { try { writer.write(NEWLINE); } catch (IOException e) { throw new JSONException(e); } } private void indent() { try { for (int i = 0; i < indentLevel; i++) { writer.write(indentStr); } } catch (IOException e) { throw new JSONException(e); } } @Override protected JSONWriter append(String s) { if (s == null) { throw new JSONException("Null pointer"); } if (mode == OBJECT || mode == ARRAY) { try { if (comma && mode == ARRAY) { comma(); } if (mode == ARRAY) { newline(); indent(); } writer.write(s); } catch (IOException e) { throw new JSONException(e); } if (mode == OBJECT) { mode = KEY; } comma = true; return this; } throw new JSONException("Value out of sequence."); } @Override protected JSONWriter end(Mode m, char c) { newline(); indent(); return super.end(m, c); } @Override public JSONWriter array() { super.array(); indentLevel++; return this; } @Override public JSONWriter endArray() { indentLevel--; super.endArray(); return this; } @Override public JSONWriter object() { super.object(); indentLevel++; return this; } @Override public JSONWriter endObject() { indentLevel--; super.endObject(); return this; } @Override public JSONWriter key(String s) { if (s == null) { throw new JSONException("Null key."); } if (mode == KEY) { try { if (comma) { comma(); } newline(); indent(); writer.write(JSONObject.quote(s)); writer.write(": "); comma = false; mode = OBJECT; return this; } catch (IOException e) { throw new JSONException(e); } } throw new JSONException("Misplaced key."); } }
jeffbrown/grailsnolib
grails-web/src/main/groovy/org/codehaus/groovy/grails/web/json/PrettyPrintJSONWriter.java
Java
apache-2.0
4,112
/* * Infoplus API * * Infoplus API. * * OpenAPI spec version: v1.0 * Contact: [email protected] * Generated by: https://github.com/swagger-api/swagger-codegen.git * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using RestSharp; using Infoplus.Client; using Infoplus.Model; namespace Infoplus.Api { /// <summary> /// Represents a collection of functions to interact with the API endpoints /// </summary> public interface IReplenishmentApi : IApiAccessor { #region Synchronous Operations /// <summary> /// Search replenishments by filter /// </summary> /// <remarks> /// Returns the list of replenishments that match the given filter. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="filter">Query string, used to filter results. (optional)</param> /// <param name="page">Result page number. Defaults to 1. (optional)</param> /// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param> /// <param name="sort">Sort results by specified field. (optional)</param> /// <returns>List&lt;Replenishment&gt;</returns> List<Replenishment> GetReplenishmentByFilter (string filter = null, int? page = null, int? limit = null, string sort = null); /// <summary> /// Search replenishments by filter /// </summary> /// <remarks> /// Returns the list of replenishments that match the given filter. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="filter">Query string, used to filter results. (optional)</param> /// <param name="page">Result page number. Defaults to 1. (optional)</param> /// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param> /// <param name="sort">Sort results by specified field. (optional)</param> /// <returns>ApiResponse of List&lt;Replenishment&gt;</returns> ApiResponse<List<Replenishment>> GetReplenishmentByFilterWithHttpInfo (string filter = null, int? page = null, int? limit = null, string sort = null); /// <summary> /// Get a replenishment by id /// </summary> /// <remarks> /// Returns the replenishment identified by the specified id. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="replenishmentId">Id of the replenishment to be returned.</param> /// <returns>Replenishment</returns> Replenishment GetReplenishmentById (int? replenishmentId); /// <summary> /// Get a replenishment by id /// </summary> /// <remarks> /// Returns the replenishment identified by the specified id. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="replenishmentId">Id of the replenishment to be returned.</param> /// <returns>ApiResponse of Replenishment</returns> ApiResponse<Replenishment> GetReplenishmentByIdWithHttpInfo (int? replenishmentId); #endregion Synchronous Operations #region Asynchronous Operations /// <summary> /// Search replenishments by filter /// </summary> /// <remarks> /// Returns the list of replenishments that match the given filter. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="filter">Query string, used to filter results. (optional)</param> /// <param name="page">Result page number. Defaults to 1. (optional)</param> /// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param> /// <param name="sort">Sort results by specified field. (optional)</param> /// <returns>Task of List&lt;Replenishment&gt;</returns> System.Threading.Tasks.Task<List<Replenishment>> GetReplenishmentByFilterAsync (string filter = null, int? page = null, int? limit = null, string sort = null); /// <summary> /// Search replenishments by filter /// </summary> /// <remarks> /// Returns the list of replenishments that match the given filter. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="filter">Query string, used to filter results. (optional)</param> /// <param name="page">Result page number. Defaults to 1. (optional)</param> /// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param> /// <param name="sort">Sort results by specified field. (optional)</param> /// <returns>Task of ApiResponse (List&lt;Replenishment&gt;)</returns> System.Threading.Tasks.Task<ApiResponse<List<Replenishment>>> GetReplenishmentByFilterAsyncWithHttpInfo (string filter = null, int? page = null, int? limit = null, string sort = null); /// <summary> /// Get a replenishment by id /// </summary> /// <remarks> /// Returns the replenishment identified by the specified id. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="replenishmentId">Id of the replenishment to be returned.</param> /// <returns>Task of Replenishment</returns> System.Threading.Tasks.Task<Replenishment> GetReplenishmentByIdAsync (int? replenishmentId); /// <summary> /// Get a replenishment by id /// </summary> /// <remarks> /// Returns the replenishment identified by the specified id. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="replenishmentId">Id of the replenishment to be returned.</param> /// <returns>Task of ApiResponse (Replenishment)</returns> System.Threading.Tasks.Task<ApiResponse<Replenishment>> GetReplenishmentByIdAsyncWithHttpInfo (int? replenishmentId); #endregion Asynchronous Operations } /// <summary> /// Represents a collection of functions to interact with the API endpoints /// </summary> public partial class ReplenishmentApi : IReplenishmentApi { private Infoplus.Client.ExceptionFactory _exceptionFactory = (name, response) => null; /// <summary> /// Initializes a new instance of the <see cref="ReplenishmentApi"/> class. /// </summary> /// <returns></returns> public ReplenishmentApi(String basePath) { this.Configuration = new Configuration(new ApiClient(basePath)); ExceptionFactory = Infoplus.Client.Configuration.DefaultExceptionFactory; // ensure API client has configuration ready if (Configuration.ApiClient.Configuration == null) { this.Configuration.ApiClient.Configuration = this.Configuration; } } /// <summary> /// Initializes a new instance of the <see cref="ReplenishmentApi"/> class /// using Configuration object /// </summary> /// <param name="configuration">An instance of Configuration</param> /// <returns></returns> public ReplenishmentApi(Configuration configuration = null) { if (configuration == null) // use the default one in Configuration this.Configuration = Configuration.Default; else this.Configuration = configuration; ExceptionFactory = Infoplus.Client.Configuration.DefaultExceptionFactory; // ensure API client has configuration ready if (Configuration.ApiClient.Configuration == null) { this.Configuration.ApiClient.Configuration = this.Configuration; } } /// <summary> /// Gets the base path of the API client. /// </summary> /// <value>The base path</value> public String GetBasePath() { return this.Configuration.ApiClient.RestClient.BaseUrl.ToString(); } /// <summary> /// Sets the base path of the API client. /// </summary> /// <value>The base path</value> [Obsolete("SetBasePath is deprecated, please do 'Configuration.ApiClient = new ApiClient(\"http://new-path\")' instead.")] public void SetBasePath(String basePath) { // do nothing } /// <summary> /// Gets or sets the configuration object /// </summary> /// <value>An instance of the Configuration</value> public Configuration Configuration {get; set;} /// <summary> /// Provides a factory method hook for the creation of exceptions. /// </summary> public Infoplus.Client.ExceptionFactory ExceptionFactory { get { if (_exceptionFactory != null && _exceptionFactory.GetInvocationList().Length > 1) { throw new InvalidOperationException("Multicast delegate for ExceptionFactory is unsupported."); } return _exceptionFactory; } set { _exceptionFactory = value; } } /// <summary> /// Gets the default header. /// </summary> /// <returns>Dictionary of HTTP header</returns> [Obsolete("DefaultHeader is deprecated, please use Configuration.DefaultHeader instead.")] public Dictionary<String, String> DefaultHeader() { return this.Configuration.DefaultHeader; } /// <summary> /// Add default header. /// </summary> /// <param name="key">Header field name.</param> /// <param name="value">Header field value.</param> /// <returns></returns> [Obsolete("AddDefaultHeader is deprecated, please use Configuration.AddDefaultHeader instead.")] public void AddDefaultHeader(string key, string value) { this.Configuration.AddDefaultHeader(key, value); } /// <summary> /// Search replenishments by filter Returns the list of replenishments that match the given filter. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="filter">Query string, used to filter results. (optional)</param> /// <param name="page">Result page number. Defaults to 1. (optional)</param> /// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param> /// <param name="sort">Sort results by specified field. (optional)</param> /// <returns>List&lt;Replenishment&gt;</returns> public List<Replenishment> GetReplenishmentByFilter (string filter = null, int? page = null, int? limit = null, string sort = null) { ApiResponse<List<Replenishment>> localVarResponse = GetReplenishmentByFilterWithHttpInfo(filter, page, limit, sort); return localVarResponse.Data; } /// <summary> /// Search replenishments by filter Returns the list of replenishments that match the given filter. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="filter">Query string, used to filter results. (optional)</param> /// <param name="page">Result page number. Defaults to 1. (optional)</param> /// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param> /// <param name="sort">Sort results by specified field. (optional)</param> /// <returns>ApiResponse of List&lt;Replenishment&gt;</returns> public ApiResponse< List<Replenishment> > GetReplenishmentByFilterWithHttpInfo (string filter = null, int? page = null, int? limit = null, string sort = null) { var localVarPath = "/v1.0/replenishment/search"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new Dictionary<String, String>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/json" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); if (filter != null) localVarQueryParams.Add("filter", Configuration.ApiClient.ParameterToString(filter)); // query parameter if (page != null) localVarQueryParams.Add("page", Configuration.ApiClient.ParameterToString(page)); // query parameter if (limit != null) localVarQueryParams.Add("limit", Configuration.ApiClient.ParameterToString(limit)); // query parameter if (sort != null) localVarQueryParams.Add("sort", Configuration.ApiClient.ParameterToString(sort)); // query parameter // authentication (api_key) required if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("API-Key"))) { localVarHeaderParams["API-Key"] = Configuration.GetApiKeyWithPrefix("API-Key"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath, Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("GetReplenishmentByFilter", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<List<Replenishment>>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (List<Replenishment>) Configuration.ApiClient.Deserialize(localVarResponse, typeof(List<Replenishment>))); } /// <summary> /// Search replenishments by filter Returns the list of replenishments that match the given filter. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="filter">Query string, used to filter results. (optional)</param> /// <param name="page">Result page number. Defaults to 1. (optional)</param> /// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param> /// <param name="sort">Sort results by specified field. (optional)</param> /// <returns>Task of List&lt;Replenishment&gt;</returns> public async System.Threading.Tasks.Task<List<Replenishment>> GetReplenishmentByFilterAsync (string filter = null, int? page = null, int? limit = null, string sort = null) { ApiResponse<List<Replenishment>> localVarResponse = await GetReplenishmentByFilterAsyncWithHttpInfo(filter, page, limit, sort); return localVarResponse.Data; } /// <summary> /// Search replenishments by filter Returns the list of replenishments that match the given filter. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="filter">Query string, used to filter results. (optional)</param> /// <param name="page">Result page number. Defaults to 1. (optional)</param> /// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param> /// <param name="sort">Sort results by specified field. (optional)</param> /// <returns>Task of ApiResponse (List&lt;Replenishment&gt;)</returns> public async System.Threading.Tasks.Task<ApiResponse<List<Replenishment>>> GetReplenishmentByFilterAsyncWithHttpInfo (string filter = null, int? page = null, int? limit = null, string sort = null) { var localVarPath = "/v1.0/replenishment/search"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new Dictionary<String, String>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/json" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); if (filter != null) localVarQueryParams.Add("filter", Configuration.ApiClient.ParameterToString(filter)); // query parameter if (page != null) localVarQueryParams.Add("page", Configuration.ApiClient.ParameterToString(page)); // query parameter if (limit != null) localVarQueryParams.Add("limit", Configuration.ApiClient.ParameterToString(limit)); // query parameter if (sort != null) localVarQueryParams.Add("sort", Configuration.ApiClient.ParameterToString(sort)); // query parameter // authentication (api_key) required if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("API-Key"))) { localVarHeaderParams["API-Key"] = Configuration.GetApiKeyWithPrefix("API-Key"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath, Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("GetReplenishmentByFilter", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<List<Replenishment>>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (List<Replenishment>) Configuration.ApiClient.Deserialize(localVarResponse, typeof(List<Replenishment>))); } /// <summary> /// Get a replenishment by id Returns the replenishment identified by the specified id. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="replenishmentId">Id of the replenishment to be returned.</param> /// <returns>Replenishment</returns> public Replenishment GetReplenishmentById (int? replenishmentId) { ApiResponse<Replenishment> localVarResponse = GetReplenishmentByIdWithHttpInfo(replenishmentId); return localVarResponse.Data; } /// <summary> /// Get a replenishment by id Returns the replenishment identified by the specified id. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="replenishmentId">Id of the replenishment to be returned.</param> /// <returns>ApiResponse of Replenishment</returns> public ApiResponse< Replenishment > GetReplenishmentByIdWithHttpInfo (int? replenishmentId) { // verify the required parameter 'replenishmentId' is set if (replenishmentId == null) throw new ApiException(400, "Missing required parameter 'replenishmentId' when calling ReplenishmentApi->GetReplenishmentById"); var localVarPath = "/v1.0/replenishment/{replenishmentId}"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new Dictionary<String, String>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/json" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); if (replenishmentId != null) localVarPathParams.Add("replenishmentId", Configuration.ApiClient.ParameterToString(replenishmentId)); // path parameter // authentication (api_key) required if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("API-Key"))) { localVarHeaderParams["API-Key"] = Configuration.GetApiKeyWithPrefix("API-Key"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath, Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("GetReplenishmentById", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<Replenishment>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (Replenishment) Configuration.ApiClient.Deserialize(localVarResponse, typeof(Replenishment))); } /// <summary> /// Get a replenishment by id Returns the replenishment identified by the specified id. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="replenishmentId">Id of the replenishment to be returned.</param> /// <returns>Task of Replenishment</returns> public async System.Threading.Tasks.Task<Replenishment> GetReplenishmentByIdAsync (int? replenishmentId) { ApiResponse<Replenishment> localVarResponse = await GetReplenishmentByIdAsyncWithHttpInfo(replenishmentId); return localVarResponse.Data; } /// <summary> /// Get a replenishment by id Returns the replenishment identified by the specified id. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="replenishmentId">Id of the replenishment to be returned.</param> /// <returns>Task of ApiResponse (Replenishment)</returns> public async System.Threading.Tasks.Task<ApiResponse<Replenishment>> GetReplenishmentByIdAsyncWithHttpInfo (int? replenishmentId) { // verify the required parameter 'replenishmentId' is set if (replenishmentId == null) throw new ApiException(400, "Missing required parameter 'replenishmentId' when calling ReplenishmentApi->GetReplenishmentById"); var localVarPath = "/v1.0/replenishment/{replenishmentId}"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new Dictionary<String, String>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/json" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); if (replenishmentId != null) localVarPathParams.Add("replenishmentId", Configuration.ApiClient.ParameterToString(replenishmentId)); // path parameter // authentication (api_key) required if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("API-Key"))) { localVarHeaderParams["API-Key"] = Configuration.GetApiKeyWithPrefix("API-Key"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath, Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("GetReplenishmentById", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<Replenishment>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (Replenishment) Configuration.ApiClient.Deserialize(localVarResponse, typeof(Replenishment))); } } }
infopluscommerce/infoplus-csharp-client
src/Infoplus/Api/ReplenishmentApi.cs
C#
apache-2.0
29,649
<%# Copyright 2013-2018 the original author or authors from the JHipster project. This file is part of the JHipster project, see http://www.jhipster.tech/ for more information. 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. -%> <div> <div class="row"> <div class="col-md-8 col-md-offset-2"> <h1 data-translate="register.title">Registration</h1> <div class="alert alert-success" ng-show="vm.success" data-translate="register.messages.success"> <strong>Registration saved!</strong> Please check your email for confirmation. </div> <div class="alert alert-danger" ng-show="vm.error" data-translate="register.messages.error.fail"> <strong>Registration failed!</strong> Please try again later. </div> <div class="alert alert-danger" ng-show="vm.errorUserExists" data-translate="register.messages.error.userexists"> <strong>Login name already registered!</strong> Please choose another one. </div> <div class="alert alert-danger" ng-show="vm.errorEmailExists" data-translate="register.messages.error.emailexists"> <strong>Email is already in use!</strong> Please choose another one. </div> <div class="alert alert-danger" ng-show="vm.doNotMatch" data-translate="global.messages.error.dontmatch"> The password and its confirmation do not match! </div> </div> <%_ if (enableSocialSignIn) { _%> <div class="col-md-4 col-md-offset-2"> <%_ } else { _%> <div class="col-md-8 col-md-offset-2"> <%_ } _%> <form ng-show="!vm.success" name="form" role="form" novalidate ng-submit="vm.register()" show-validation> <div class="form-group"> <label class="control-label" for="login" data-translate="global.form.username">Username</label> <input type="text" class="form-control" id="login" name="login" placeholder="{{'global.form.username.placeholder' | translate}}" ng-model="vm.registerAccount.login" ng-minlength=1 ng-maxlength=50 ng-pattern="/^[_'.@A-Za-z0-9-]*$/" required> <div ng-show="form.login.$dirty && form.login.$invalid"> <p class="help-block" ng-show="form.login.$error.required" data-translate="register.messages.validate.login.required"> Your username is required. </p> <p class="help-block" ng-show="form.login.$error.minlength" data-translate="register.messages.validate.login.minlength"> Your username is required to be at least 1 character. </p> <p class="help-block" ng-show="form.login.$error.maxlength" data-translate="register.messages.validate.login.maxlength"> Your username cannot be longer than 50 characters. </p> <p class="help-block" ng-show="form.login.$error.pattern" data-translate="register.messages.validate.login.pattern"> Your username can only contain letters and digits. </p> </div> </div> <div class="form-group"> <label class="control-label" for="email" data-translate="global.form.email">Email</label> <input type="email" class="form-control" id="email" name="email" placeholder="{{'global.form.email.placeholder' | translate}}" ng-model="vm.registerAccount.email" ng-minlength=5 ng-maxlength=100 required> <div ng-show="form.email.$dirty && form.email.$invalid"> <p class="help-block" ng-show="form.email.$error.required" data-translate="global.messages.validate.email.required"> Your email is required. </p> <p class="help-block" ng-show="form.email.$error.email" data-translate="global.messages.validate.email.invalid"> Your email is invalid. </p> <p class="help-block" ng-show="form.email.$error.minlength" data-translate="global.messages.validate.email.minlength"> Your email is required to be at least 5 characters. </p> <p class="help-block" ng-show="form.email.$error.maxlength" data-translate="global.messages.validate.email.maxlength"> Your email cannot be longer than 100 characters. </p> </div> </div> <div class="form-group"> <label class="control-label" for="password" data-translate="global.form.newpassword">New password</label> <input type="password" class="form-control" id="password" name="password" placeholder="{{'global.form.newpassword.placeholder' | translate}}" ng-model="vm.registerAccount.password" ng-minlength=4 ng-maxlength=50 required> <div ng-show="form.password.$dirty && form.password.$invalid"> <p class="help-block" ng-show="form.password.$error.required" data-translate="global.messages.validate.newpassword.required"> Your password is required. </p> <p class="help-block" ng-show="form.password.$error.minlength" data-translate="global.messages.validate.newpassword.minlength"> Your password is required to be at least 4 characters. </p> <p class="help-block" ng-show="form.password.$error.maxlength" data-translate="global.messages.validate.newpassword.maxlength"> Your password cannot be longer than 50 characters. </p> </div> <password-strength-bar password-to-check="vm.registerAccount.password"></password-strength-bar> </div> <div class="form-group"> <label class="control-label" for="confirmPassword" data-translate="global.form.confirmpassword">New password confirmation</label> <input type="password" class="form-control" id="confirmPassword" name="confirmPassword" placeholder="{{'global.form.confirmpassword.placeholder' | translate}}" ng-model="vm.confirmPassword" ng-minlength=4 ng-maxlength=50 required> <div ng-show="form.confirmPassword.$dirty && form.confirmPassword.$invalid"> <p class="help-block" ng-show="form.confirmPassword.$error.required" data-translate="global.messages.validate.confirmpassword.required"> Your confirmation password is required. </p> <p class="help-block" ng-show="form.confirmPassword.$error.minlength" data-translate="global.messages.validate.confirmpassword.minlength"> Your confirmation password is required to be at least 4 characters. </p> <p class="help-block" ng-show="form.confirmPassword.$error.maxlength" data-translate="global.messages.validate.confirmpassword.maxlength"> Your confirmation password cannot be longer than 50 characters. </p> </div> </div> <button type="submit" ng-disabled="form.$invalid" class="btn btn-primary" data-translate="register.form.button">Register</button> </form> <p></p> <div class="alert alert-warning" data-translate="global.messages.info.authenticated" translate-compile> If you want to <a class="alert-link" href="" ng-click="vm.login()">sign in</a>, you can try the default accounts:<br/>- Administrator (login="admin" and password="admin") <br/>- User (login="user" and password="user"). </div> </div> <%_ if (enableSocialSignIn) { _%> <div class="col-md-4"> <br/> <jh-social ng-provider="google"></jh-social> <jh-social ng-provider="facebook"></jh-social> <jh-social ng-provider="twitter"></jh-social> <!-- jhipster-needle-add-social-button --> </div> <%_ } _%> </div> </div>
nkolosnjaji/generator-jhipster
generators/client/templates/angularjs/src/main/webapp/app/account/register/_register.html
HTML
apache-2.0
9,568
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable enable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.UnitTests.Diagnostics; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; using static Roslyn.Test.Utilities.TestBase; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.UserDiagnosticProviderEngine { [UseExportProvider] public class DiagnosticAnalyzerDriverTests { [Fact] public async Task DiagnosticAnalyzerDriverAllInOne() { var source = TestResource.AllInOneCSharpCode; // AllInOneCSharpCode has no properties with initializers or named types with primary constructors. var symbolKindsWithNoCodeBlocks = new HashSet<SymbolKind>(); symbolKindsWithNoCodeBlocks.Add(SymbolKind.Property); symbolKindsWithNoCodeBlocks.Add(SymbolKind.NamedType); var missingSyntaxNodes = new HashSet<SyntaxKind>(); // https://github.com/dotnet/roslyn/issues/44682 - Add to all in one missingSyntaxNodes.Add(SyntaxKind.WithExpression); missingSyntaxNodes.Add(SyntaxKind.RecordDeclaration); missingSyntaxNodes.Add(SyntaxKind.FunctionPointerType); var analyzer = new CSharpTrackingDiagnosticAnalyzer(); using var workspace = TestWorkspace.CreateCSharp(source, TestOptions.Regular); var analyzerReference = new AnalyzerImageReference(ImmutableArray.Create<DiagnosticAnalyzer>(analyzer)); workspace.TryApplyChanges(workspace.CurrentSolution.WithAnalyzerReferences(new[] { analyzerReference })); var document = workspace.CurrentSolution.Projects.Single().Documents.Single(); AccessSupportedDiagnostics(analyzer); await DiagnosticProviderTestUtilities.GetAllDiagnosticsAsync(document, new TextSpan(0, document.GetTextAsync().Result.Length)); analyzer.VerifyAllAnalyzerMembersWereCalled(); analyzer.VerifyAnalyzeSymbolCalledForAllSymbolKinds(); analyzer.VerifyAnalyzeNodeCalledForAllSyntaxKinds(missingSyntaxNodes); analyzer.VerifyOnCodeBlockCalledForAllSymbolAndMethodKinds(symbolKindsWithNoCodeBlocks, true); } [Fact, WorkItem(908658, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/908658")] public async Task DiagnosticAnalyzerDriverVsAnalyzerDriverOnCodeBlock() { var methodNames = new string[] { "Initialize", "AnalyzeCodeBlock" }; var source = @" [System.Obsolete] class C { int P { get; set; } delegate void A(); delegate string F(); } "; var ideEngineAnalyzer = new CSharpTrackingDiagnosticAnalyzer(); using (var ideEngineWorkspace = TestWorkspace.CreateCSharp(source)) { var analyzerReference = new AnalyzerImageReference(ImmutableArray.Create<DiagnosticAnalyzer>(ideEngineAnalyzer)); ideEngineWorkspace.TryApplyChanges(ideEngineWorkspace.CurrentSolution.WithAnalyzerReferences(new[] { analyzerReference })); var ideEngineDocument = ideEngineWorkspace.CurrentSolution.Projects.Single().Documents.Single(); await DiagnosticProviderTestUtilities.GetAllDiagnosticsAsync(ideEngineDocument, new TextSpan(0, ideEngineDocument.GetTextAsync().Result.Length)); foreach (var method in methodNames) { Assert.False(ideEngineAnalyzer.CallLog.Any(e => e.CallerName == method && e.MethodKind == MethodKind.DelegateInvoke && e.ReturnsVoid)); Assert.False(ideEngineAnalyzer.CallLog.Any(e => e.CallerName == method && e.MethodKind == MethodKind.DelegateInvoke && !e.ReturnsVoid)); Assert.True(ideEngineAnalyzer.CallLog.Any(e => e.CallerName == method && e.SymbolKind == SymbolKind.NamedType)); Assert.False(ideEngineAnalyzer.CallLog.Any(e => e.CallerName == method && e.SymbolKind == SymbolKind.Property)); } } var compilerEngineAnalyzer = new CSharpTrackingDiagnosticAnalyzer(); using var compilerEngineWorkspace = TestWorkspace.CreateCSharp(source); var compilerEngineCompilation = (CSharpCompilation)compilerEngineWorkspace.CurrentSolution.Projects.Single().GetRequiredCompilationAsync(CancellationToken.None).Result; compilerEngineCompilation.GetAnalyzerDiagnostics(new[] { compilerEngineAnalyzer }); foreach (var method in methodNames) { Assert.False(compilerEngineAnalyzer.CallLog.Any(e => e.CallerName == method && e.MethodKind == MethodKind.DelegateInvoke && e.ReturnsVoid)); Assert.False(compilerEngineAnalyzer.CallLog.Any(e => e.CallerName == method && e.MethodKind == MethodKind.DelegateInvoke && !e.ReturnsVoid)); Assert.True(compilerEngineAnalyzer.CallLog.Any(e => e.CallerName == method && e.SymbolKind == SymbolKind.NamedType)); Assert.False(compilerEngineAnalyzer.CallLog.Any(e => e.CallerName == method && e.SymbolKind == SymbolKind.Property)); } } [Fact] [WorkItem(759, "https://github.com/dotnet/roslyn/issues/759")] public async Task DiagnosticAnalyzerDriverIsSafeAgainstAnalyzerExceptions() { var source = TestResource.AllInOneCSharpCode; using var workspace = TestWorkspace.CreateCSharp(source, TestOptions.Regular); await ThrowingDiagnosticAnalyzer<SyntaxKind>.VerifyAnalyzerEngineIsSafeAgainstExceptionsAsync(async analyzer => { var analyzerReference = new AnalyzerImageReference(ImmutableArray.Create(analyzer)); workspace.TryApplyChanges(workspace.CurrentSolution.WithAnalyzerReferences(new[] { analyzerReference })); var document = workspace.CurrentSolution.Projects.Single().Documents.Single(); return await DiagnosticProviderTestUtilities.GetAllDiagnosticsAsync(document, new TextSpan(0, document.GetTextAsync().Result.Length)); }); } [WorkItem(908621, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/908621")] [Fact] public void DiagnosticServiceIsSafeAgainstAnalyzerExceptions_1() { var analyzer = new ThrowingDiagnosticAnalyzer<SyntaxKind>(); analyzer.ThrowOn(typeof(DiagnosticAnalyzer).GetProperties().Single().Name); AccessSupportedDiagnostics(analyzer); } [WorkItem(908621, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/908621")] [Fact] public void DiagnosticServiceIsSafeAgainstAnalyzerExceptions_2() { var analyzer = new ThrowingDoNotCatchDiagnosticAnalyzer<SyntaxKind>(); analyzer.ThrowOn(typeof(DiagnosticAnalyzer).GetProperties().Single().Name); var exceptions = new List<Exception>(); try { AccessSupportedDiagnostics(analyzer); } catch (Exception e) { exceptions.Add(e); } Assert.True(exceptions.Count == 0); } [Fact] public async Task AnalyzerOptionsArePassedToAllAnalyzers() { using var workspace = TestWorkspace.CreateCSharp(TestResource.AllInOneCSharpCode, TestOptions.Regular); var additionalDocId = DocumentId.CreateNewId(workspace.CurrentSolution.Projects.Single().Id); var additionalText = new TestAdditionalText("add.config", SourceText.From("random text")); var options = new AnalyzerOptions(ImmutableArray.Create<AdditionalText>(additionalText)); var analyzer = new OptionsDiagnosticAnalyzer<SyntaxKind>(expectedOptions: options); var analyzerReference = new AnalyzerImageReference(ImmutableArray.Create<DiagnosticAnalyzer>(analyzer)); workspace.TryApplyChanges(workspace.CurrentSolution .WithAnalyzerReferences(new[] { analyzerReference }) .AddAdditionalDocument(additionalDocId, "add.config", additionalText.GetText())); var sourceDocument = workspace.CurrentSolution.Projects.Single().Documents.Single(); await DiagnosticProviderTestUtilities.GetAllDiagnosticsAsync(sourceDocument, new TextSpan(0, sourceDocument.GetTextAsync().Result.Length)); analyzer.VerifyAnalyzerOptions(); } private void AccessSupportedDiagnostics(DiagnosticAnalyzer analyzer) { var diagnosticService = new HostDiagnosticAnalyzers(new[] { new AnalyzerImageReference(ImmutableArray.Create(analyzer)) }); diagnosticService.GetDiagnosticDescriptorsPerReference(new DiagnosticAnalyzerInfoCache()); } private class ThrowingDoNotCatchDiagnosticAnalyzer<TLanguageKindEnum> : ThrowingDiagnosticAnalyzer<TLanguageKindEnum>, IBuiltInAnalyzer where TLanguageKindEnum : struct { public bool OpenFileOnly(OptionSet options) => false; public DiagnosticAnalyzerCategory GetAnalyzerCategory() => DiagnosticAnalyzerCategory.SyntaxTreeWithoutSemanticsAnalysis | DiagnosticAnalyzerCategory.SemanticDocumentAnalysis | DiagnosticAnalyzerCategory.ProjectAnalysis; } [Fact] public async Task AnalyzerCreatedAtCompilationLevelNeedNotBeCompilationAnalyzer() { var source = @"x"; using var workspace = TestWorkspace.CreateCSharp(source); var analyzer = new CompilationAnalyzerWithSyntaxTreeAnalyzer(); var analyzerReference = new AnalyzerImageReference(ImmutableArray.Create<DiagnosticAnalyzer>(analyzer)); workspace.TryApplyChanges(workspace.CurrentSolution.WithAnalyzerReferences(new[] { analyzerReference })); var ideEngineDocument = workspace.CurrentSolution.Projects.Single().Documents.Single(); var diagnostics = await DiagnosticProviderTestUtilities.GetAllDiagnosticsAsync(ideEngineDocument, new TextSpan(0, ideEngineDocument.GetTextAsync().Result.Length)); var diagnosticsFromAnalyzer = diagnostics.Where(d => d.Id == "SyntaxDiagnostic"); Assert.Equal(1, diagnosticsFromAnalyzer.Count()); } private class CompilationAnalyzerWithSyntaxTreeAnalyzer : DiagnosticAnalyzer { private const string ID = "SyntaxDiagnostic"; private static readonly DiagnosticDescriptor s_syntaxDiagnosticDescriptor = new DiagnosticDescriptor(ID, title: "Syntax", messageFormat: "Syntax", category: "Test", defaultSeverity: DiagnosticSeverity.Warning, isEnabledByDefault: true); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(s_syntaxDiagnosticDescriptor); } } public override void Initialize(AnalysisContext context) => context.RegisterCompilationStartAction(CreateAnalyzerWithinCompilation); public void CreateAnalyzerWithinCompilation(CompilationStartAnalysisContext context) => context.RegisterSyntaxTreeAction(new SyntaxTreeAnalyzer().AnalyzeSyntaxTree); private class SyntaxTreeAnalyzer { public void AnalyzeSyntaxTree(SyntaxTreeAnalysisContext context) => context.ReportDiagnostic(Diagnostic.Create(s_syntaxDiagnosticDescriptor, context.Tree.GetRoot().GetFirstToken().GetLocation())); } } [Fact] public async Task CodeBlockAnalyzersOnlyAnalyzeExecutableCode() { var source = @" using System; class C { void F(int x = 0) { Console.WriteLine(0); } } "; var analyzer = new CodeBlockAnalyzerFactory(); using (var ideEngineWorkspace = TestWorkspace.CreateCSharp(source)) { var analyzerReference = new AnalyzerImageReference(ImmutableArray.Create<DiagnosticAnalyzer>(analyzer)); ideEngineWorkspace.TryApplyChanges(ideEngineWorkspace.CurrentSolution.WithAnalyzerReferences(new[] { analyzerReference })); var ideEngineDocument = ideEngineWorkspace.CurrentSolution.Projects.Single().Documents.Single(); var diagnostics = await DiagnosticProviderTestUtilities.GetAllDiagnosticsAsync(ideEngineDocument, new TextSpan(0, ideEngineDocument.GetTextAsync().Result.Length)); var diagnosticsFromAnalyzer = diagnostics.Where(d => d.Id == CodeBlockAnalyzerFactory.Descriptor.Id); Assert.Equal(2, diagnosticsFromAnalyzer.Count()); } source = @" using System; class C { void F(int x = 0, int y = 1, int z = 2) { Console.WriteLine(0); } } "; using (var compilerEngineWorkspace = TestWorkspace.CreateCSharp(source)) { var compilerEngineCompilation = (CSharpCompilation)compilerEngineWorkspace.CurrentSolution.Projects.Single().GetRequiredCompilationAsync(CancellationToken.None).Result; var diagnostics = compilerEngineCompilation.GetAnalyzerDiagnostics(new[] { analyzer }); var diagnosticsFromAnalyzer = diagnostics.Where(d => d.Id == CodeBlockAnalyzerFactory.Descriptor.Id); Assert.Equal(4, diagnosticsFromAnalyzer.Count()); } } private class CodeBlockAnalyzerFactory : DiagnosticAnalyzer { public static DiagnosticDescriptor Descriptor = DescriptorFactory.CreateSimpleDescriptor("DummyDiagnostic"); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(Descriptor); } } public override void Initialize(AnalysisContext context) => context.RegisterCodeBlockStartAction<SyntaxKind>(CreateAnalyzerWithinCodeBlock); public void CreateAnalyzerWithinCodeBlock(CodeBlockStartAnalysisContext<SyntaxKind> context) { var blockAnalyzer = new CodeBlockAnalyzer(); context.RegisterCodeBlockEndAction(blockAnalyzer.AnalyzeCodeBlock); context.RegisterSyntaxNodeAction(blockAnalyzer.AnalyzeNode, blockAnalyzer.SyntaxKindsOfInterest.ToArray()); } private class CodeBlockAnalyzer { public ImmutableArray<SyntaxKind> SyntaxKindsOfInterest { get { return ImmutableArray.Create(SyntaxKind.MethodDeclaration, SyntaxKind.ExpressionStatement, SyntaxKind.EqualsValueClause); } } public void AnalyzeCodeBlock(CodeBlockAnalysisContext context) { } public void AnalyzeNode(SyntaxNodeAnalysisContext context) { // Ensure only executable nodes are analyzed. Assert.NotEqual(SyntaxKind.MethodDeclaration, context.Node.Kind()); context.ReportDiagnostic(Diagnostic.Create(Descriptor, context.Node.GetLocation())); } } } [Fact] public async Task TestDiagnosticSpan() { var source = @"// empty code"; var analyzer = new InvalidSpanAnalyzer(); using var compilerEngineWorkspace = TestWorkspace.CreateCSharp(source); var compilerEngineCompilation = (CSharpCompilation)(await compilerEngineWorkspace.CurrentSolution.Projects.Single().GetRequiredCompilationAsync(CancellationToken.None)); var diagnostics = compilerEngineCompilation.GetAnalyzerDiagnostics(new[] { analyzer }); AssertEx.Any(diagnostics, d => d.Id == AnalyzerHelper.AnalyzerExceptionDiagnosticId); } private class InvalidSpanAnalyzer : DiagnosticAnalyzer { public static DiagnosticDescriptor Descriptor = DescriptorFactory.CreateSimpleDescriptor("DummyDiagnostic"); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) => context.RegisterSyntaxTreeAction(Analyze); private void Analyze(SyntaxTreeAnalysisContext context) => context.ReportDiagnostic(Diagnostic.Create(Descriptor, Location.Create(context.Tree, TextSpan.FromBounds(1000, 2000)))); } [Fact, WorkItem(18818, "https://github.com/dotnet/roslyn/issues/18818")] public async Task TestNuGetAndVsixAnalyzer_ReportsSameId() { // NuGet and VSIX analyzer reporting same diagnostic IDs. var reportedDiagnosticIds = new[] { "A", "B", "C" }; var nugetAnalyzer = new NuGetAnalyzer(reportedDiagnosticIds); var vsixAnalyzer = new VsixAnalyzer(reportedDiagnosticIds); Assert.Equal(reportedDiagnosticIds, nugetAnalyzer.SupportedDiagnostics.Select(d => d.Id).Order()); Assert.Equal(reportedDiagnosticIds, vsixAnalyzer.SupportedDiagnostics.Select(d => d.Id).Order()); // No NuGet or VSIX analyzer - no diagnostics. await TestNuGetAndVsixAnalyzerCoreAsync( nugetAnalyzer: null, expectedNugetAnalyzerExecuted: false, vsixAnalyzer: null, expectedVsixAnalyzerExecuted: false); // Only NuGet analyzer - verify diagnostics. await TestNuGetAndVsixAnalyzerCoreAsync( nugetAnalyzer, expectedNugetAnalyzerExecuted: true, vsixAnalyzer: null, expectedVsixAnalyzerExecuted: false, new[] { (Diagnostic("A", "Class").WithLocation(1, 7), nameof(NuGetAnalyzer)), (Diagnostic("B", "Class").WithLocation(1, 7), nameof(NuGetAnalyzer)), (Diagnostic("C", "Class").WithLocation(1, 7), nameof(NuGetAnalyzer)), }); // Only VSIX analyzer - verify diagnostics. await TestNuGetAndVsixAnalyzerCoreAsync( nugetAnalyzer: null, expectedNugetAnalyzerExecuted: false, vsixAnalyzer, expectedVsixAnalyzerExecuted: true, new[] { (Diagnostic("A", "Class").WithLocation(1, 7), nameof(VsixAnalyzer)), (Diagnostic("B", "Class").WithLocation(1, 7), nameof(VsixAnalyzer)), (Diagnostic("C", "Class").WithLocation(1, 7), nameof(VsixAnalyzer)), }); // Both NuGet and VSIX analyzer, verify the following: // 1) No duplicate diagnostics // 2) Only NuGet analyzer executes await TestNuGetAndVsixAnalyzerCoreAsync( nugetAnalyzer, expectedNugetAnalyzerExecuted: true, vsixAnalyzer, expectedVsixAnalyzerExecuted: false, new[] { (Diagnostic("A", "Class").WithLocation(1, 7), nameof(NuGetAnalyzer)), (Diagnostic("B", "Class").WithLocation(1, 7), nameof(NuGetAnalyzer)), (Diagnostic("C", "Class").WithLocation(1, 7), nameof(NuGetAnalyzer)), }); } [Fact, WorkItem(18818, "https://github.com/dotnet/roslyn/issues/18818")] public async Task TestNuGetAndVsixAnalyzer_NuGetAnalyzerReportsSubsetOfVsixAnalyzerIds() { // NuGet analyzer reports subset of diagnostic IDs reported by VSIX analyzer. var nugetAnalyzerDiagnosticIds = new[] { "B" }; var vsixAnalyzerDiagnosticIds = new[] { "A", "B", "C" }; var nugetAnalyzer = new NuGetAnalyzer(nugetAnalyzerDiagnosticIds); var vsixAnalyzer = new VsixAnalyzer(vsixAnalyzerDiagnosticIds); Assert.Equal(nugetAnalyzerDiagnosticIds, nugetAnalyzer.SupportedDiagnostics.Select(d => d.Id).Order()); Assert.Equal(vsixAnalyzerDiagnosticIds, vsixAnalyzer.SupportedDiagnostics.Select(d => d.Id).Order()); // Only NuGet analyzer - verify diagnostics. await TestNuGetAndVsixAnalyzerCoreAsync( nugetAnalyzer, expectedNugetAnalyzerExecuted: true, vsixAnalyzer: null, expectedVsixAnalyzerExecuted: false, new[] { (Diagnostic("B", "Class").WithLocation(1, 7), nameof(NuGetAnalyzer)) }); // Only VSIX analyzer - verify diagnostics. await TestNuGetAndVsixAnalyzerCoreAsync( nugetAnalyzer: null, expectedNugetAnalyzerExecuted: false, vsixAnalyzer, expectedVsixAnalyzerExecuted: true, new[] { (Diagnostic("A", "Class").WithLocation(1, 7), nameof(VsixAnalyzer)), (Diagnostic("B", "Class").WithLocation(1, 7), nameof(VsixAnalyzer)), (Diagnostic("C", "Class").WithLocation(1, 7), nameof(VsixAnalyzer)), }); // Both NuGet and VSIX analyzer, verify the following: // 1) No duplicate diagnostics // 2) Both NuGet and Vsix analyzers execute // 3) Appropriate diagnostic filtering is done - NuGet analyzer reported diagnostic IDs are filtered from Vsix analyzer execution. await TestNuGetAndVsixAnalyzerCoreAsync( nugetAnalyzer, expectedNugetAnalyzerExecuted: true, vsixAnalyzer, expectedVsixAnalyzerExecuted: true, new[] { (Diagnostic("A", "Class").WithLocation(1, 7), nameof(VsixAnalyzer)), (Diagnostic("B", "Class").WithLocation(1, 7), nameof(NuGetAnalyzer)), (Diagnostic("C", "Class").WithLocation(1, 7), nameof(VsixAnalyzer)), }); } [Fact, WorkItem(18818, "https://github.com/dotnet/roslyn/issues/18818")] public async Task TestNuGetAndVsixAnalyzer_VsixAnalyzerReportsSubsetOfNuGetAnalyzerIds() { // VSIX analyzer reports subset of diagnostic IDs reported by NuGet analyzer. var nugetAnalyzerDiagnosticIds = new[] { "A", "B", "C" }; var vsixAnalyzerDiagnosticIds = new[] { "B" }; var nugetAnalyzer = new NuGetAnalyzer(nugetAnalyzerDiagnosticIds); var vsixAnalyzer = new VsixAnalyzer(vsixAnalyzerDiagnosticIds); Assert.Equal(nugetAnalyzerDiagnosticIds, nugetAnalyzer.SupportedDiagnostics.Select(d => d.Id).Order()); Assert.Equal(vsixAnalyzerDiagnosticIds, vsixAnalyzer.SupportedDiagnostics.Select(d => d.Id).Order()); // Only NuGet analyzer - verify diagnostics. await TestNuGetAndVsixAnalyzerCoreAsync( nugetAnalyzer, expectedNugetAnalyzerExecuted: true, vsixAnalyzer: null, expectedVsixAnalyzerExecuted: false, new[] { (Diagnostic("A", "Class").WithLocation(1, 7), nameof(NuGetAnalyzer)), (Diagnostic("B", "Class").WithLocation(1, 7), nameof(NuGetAnalyzer)), (Diagnostic("C", "Class").WithLocation(1, 7), nameof(NuGetAnalyzer)) }); // Only VSIX analyzer - verify diagnostics. await TestNuGetAndVsixAnalyzerCoreAsync( nugetAnalyzer: null, expectedNugetAnalyzerExecuted: false, vsixAnalyzer, expectedVsixAnalyzerExecuted: true, new[] { (Diagnostic("B", "Class").WithLocation(1, 7), nameof(VsixAnalyzer)) }); // Both NuGet and VSIX analyzer, verify the following: // 1) No duplicate diagnostics // 2) Only NuGet analyzer executes await TestNuGetAndVsixAnalyzerCoreAsync( nugetAnalyzer, expectedNugetAnalyzerExecuted: true, vsixAnalyzer, expectedVsixAnalyzerExecuted: false, new[] { (Diagnostic("A", "Class").WithLocation(1, 7), nameof(NuGetAnalyzer)), (Diagnostic("B", "Class").WithLocation(1, 7), nameof(NuGetAnalyzer)), (Diagnostic("C", "Class").WithLocation(1, 7), nameof(NuGetAnalyzer)), }); } [Fact, WorkItem(18818, "https://github.com/dotnet/roslyn/issues/18818")] public async Task TestNuGetAndVsixAnalyzer_MultipleNuGetAnalyzersCollectivelyReportSameIds() { // Multiple NuGet analyzers collectively report same diagnostic IDs reported by Vsix analyzer. var firstNugetAnalyzerDiagnosticIds = new[] { "B" }; var secondNugetAnalyzerDiagnosticIds = new[] { "A", "C" }; var vsixAnalyzerDiagnosticIds = new[] { "A", "B", "C" }; var firstNugetAnalyzer = new NuGetAnalyzer(firstNugetAnalyzerDiagnosticIds); var secondNugetAnalyzer = new NuGetAnalyzer(secondNugetAnalyzerDiagnosticIds); var vsixAnalyzer = new VsixAnalyzer(vsixAnalyzerDiagnosticIds); Assert.Equal(firstNugetAnalyzerDiagnosticIds, firstNugetAnalyzer.SupportedDiagnostics.Select(d => d.Id).Order()); Assert.Equal(secondNugetAnalyzerDiagnosticIds, secondNugetAnalyzer.SupportedDiagnostics.Select(d => d.Id).Order()); Assert.Equal(vsixAnalyzerDiagnosticIds, vsixAnalyzer.SupportedDiagnostics.Select(d => d.Id).Order()); // All NuGet analyzers and no Vsix analyzer, verify the following: // 1) No duplicate diagnostics // 2) Only NuGet analyzers execute await TestNuGetAndVsixAnalyzerCoreAsync( nugetAnalyzers: ImmutableArray.Create(firstNugetAnalyzer, secondNugetAnalyzer), expectedNugetAnalyzersExecuted: true, vsixAnalyzers: ImmutableArray<VsixAnalyzer>.Empty, expectedVsixAnalyzersExecuted: false, new[] { (Diagnostic("A", "Class").WithLocation(1, 7), nameof(NuGetAnalyzer)), (Diagnostic("B", "Class").WithLocation(1, 7), nameof(NuGetAnalyzer)), (Diagnostic("C", "Class").WithLocation(1, 7), nameof(NuGetAnalyzer)) }); // All NuGet analyzers and Vsix analyzer, verify the following: // 1) No duplicate diagnostics // 2) Only NuGet analyzers execute await TestNuGetAndVsixAnalyzerCoreAsync( nugetAnalyzers: ImmutableArray.Create(firstNugetAnalyzer, secondNugetAnalyzer), expectedNugetAnalyzersExecuted: true, vsixAnalyzers: ImmutableArray.Create(vsixAnalyzer), expectedVsixAnalyzersExecuted: false, new[] { (Diagnostic("A", "Class").WithLocation(1, 7), nameof(NuGetAnalyzer)), (Diagnostic("B", "Class").WithLocation(1, 7), nameof(NuGetAnalyzer)), (Diagnostic("C", "Class").WithLocation(1, 7), nameof(NuGetAnalyzer)) }); // Subset of NuGet analyzers and Vsix analyzer, verify the following: // 1) No duplicate diagnostics // 2) Both NuGet and Vsix analyzers execute // 3) Appropriate diagnostic filtering is done - NuGet analyzer reported diagnostic IDs are filtered from Vsix analyzer execution. await TestNuGetAndVsixAnalyzerCoreAsync( nugetAnalyzers: ImmutableArray.Create(firstNugetAnalyzer), expectedNugetAnalyzersExecuted: true, vsixAnalyzers: ImmutableArray.Create(vsixAnalyzer), expectedVsixAnalyzersExecuted: true, new[] { (Diagnostic("A", "Class").WithLocation(1, 7), nameof(VsixAnalyzer)), (Diagnostic("B", "Class").WithLocation(1, 7), nameof(NuGetAnalyzer)), (Diagnostic("C", "Class").WithLocation(1, 7), nameof(VsixAnalyzer)) }); } private static Task TestNuGetAndVsixAnalyzerCoreAsync( NuGetAnalyzer? nugetAnalyzer, bool expectedNugetAnalyzerExecuted, VsixAnalyzer? vsixAnalyzer, bool expectedVsixAnalyzerExecuted, params (DiagnosticDescription diagnostic, string message)[] expectedDiagnostics) => TestNuGetAndVsixAnalyzerCoreAsync( nugetAnalyzer != null ? ImmutableArray.Create(nugetAnalyzer) : ImmutableArray<NuGetAnalyzer>.Empty, expectedNugetAnalyzerExecuted, vsixAnalyzer != null ? ImmutableArray.Create(vsixAnalyzer) : ImmutableArray<VsixAnalyzer>.Empty, expectedVsixAnalyzerExecuted, expectedDiagnostics); private static async Task TestNuGetAndVsixAnalyzerCoreAsync( ImmutableArray<NuGetAnalyzer> nugetAnalyzers, bool expectedNugetAnalyzersExecuted, ImmutableArray<VsixAnalyzer> vsixAnalyzers, bool expectedVsixAnalyzersExecuted, params (DiagnosticDescription diagnostic, string message)[] expectedDiagnostics) { // First clear out the analyzer state for all analyzers. foreach (var nugetAnalyzer in nugetAnalyzers) { nugetAnalyzer.SymbolActionInvoked = false; } foreach (var vsixAnalyzer in vsixAnalyzers) { vsixAnalyzer.SymbolActionInvoked = false; } using var workspace = TestWorkspace.CreateCSharp("class Class { }", TestOptions.Regular); Assert.True(workspace.TryApplyChanges(workspace.CurrentSolution.WithAnalyzerReferences(new[] { new AnalyzerImageReference(vsixAnalyzers.CastArray<DiagnosticAnalyzer>()) }))); var project = workspace.CurrentSolution.Projects.Single(); if (!nugetAnalyzers.IsEmpty) { project = project.WithAnalyzerReferences(new[] { new AnalyzerImageReference(nugetAnalyzers.As<DiagnosticAnalyzer>()) }); } var document = project.Documents.Single(); var root = await document.GetRequiredSyntaxRootAsync(CancellationToken.None); var diagnostics = (await DiagnosticProviderTestUtilities.GetAllDiagnosticsAsync(document, root.FullSpan)) .OrderBy(d => d.Id).ToImmutableArray(); diagnostics.Verify(expectedDiagnostics.Select(d => d.diagnostic).ToArray()); int index = 0; foreach (var (_, expectedMessage) in expectedDiagnostics) { Assert.Equal(expectedMessage, diagnostics[index].GetMessage()); index++; } foreach (var nugetAnalyzer in nugetAnalyzers) { Assert.Equal(expectedNugetAnalyzersExecuted, nugetAnalyzer.SymbolActionInvoked); } foreach (var vsixAnalyzer in vsixAnalyzers) { Assert.Equal(expectedVsixAnalyzersExecuted, vsixAnalyzer.SymbolActionInvoked); } } [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] private sealed class NuGetAnalyzer : AbstractNuGetOrVsixAnalyzer { public NuGetAnalyzer(string[] reportedIds) : base(nameof(NuGetAnalyzer), reportedIds) { } } [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] private sealed class VsixAnalyzer : AbstractNuGetOrVsixAnalyzer { public VsixAnalyzer(string[] reportedIds) : base(nameof(VsixAnalyzer), reportedIds) { } } private abstract class AbstractNuGetOrVsixAnalyzer : DiagnosticAnalyzer { protected AbstractNuGetOrVsixAnalyzer(string analyzerName, params string[] reportedIds) => SupportedDiagnostics = CreateSupportedDiagnostics(analyzerName, reportedIds); private static ImmutableArray<DiagnosticDescriptor> CreateSupportedDiagnostics(string analyzerName, string[] reportedIds) { var builder = ArrayBuilder<DiagnosticDescriptor>.GetInstance(reportedIds.Length); foreach (var id in reportedIds) { var descriptor = new DiagnosticDescriptor(id, "Title", messageFormat: analyzerName, "Category", DiagnosticSeverity.Warning, isEnabledByDefault: true); builder.Add(descriptor); } return builder.ToImmutableAndFree(); } public bool SymbolActionInvoked { get; set; } public sealed override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } public sealed override void Initialize(AnalysisContext context) => context.RegisterSymbolAction(OnSymbol, SymbolKind.NamedType); private void OnSymbol(SymbolAnalysisContext context) { SymbolActionInvoked = true; foreach (var descriptor in SupportedDiagnostics) { var diagnostic = Diagnostic.Create(descriptor, context.Symbol.Locations[0]); context.ReportDiagnostic(diagnostic); } } } } }
davkean/roslyn
src/EditorFeatures/CSharpTest/Diagnostics/DiagnosticAnalyzerDriver/DiagnosticAnalyzerDriverTests.cs
C#
apache-2.0
34,710
// bslmf_invokeresult.06.t.cpp -*-C++-*- // ============================================================================ // INCLUDE STANDARD TEST MACHINERY FROM CASE 0 // ---------------------------------------------------------------------------- #define BSLMF_INVOKERESULT_00T_AS_INCLUDE #include <bslmf_invokeresult.00.t.cpp> //============================================================================= // TEST PLAN //----------------------------------------------------------------------------- // See the test plan in 'bslmf_invokeresult.00.t.cpp'. // // This file contains the following test: // [6] 'InvokeResultDeductionFailed' //----------------------------------------------------------------------------- // ============================================================================ // STANDARD BSL ASSERT TEST FUNCTION // ---------------------------------------------------------------------------- // These are defined as part of the standard machinery included from file // bslmf_invokeresult.00.t.cpp // // We need to suppress the bde_verify error due to them not being in this file: // BDE_VERIFY pragma: -TP19 // ============================================================================ // STANDARD BSL TEST DRIVER MACRO ABBREVIATIONS // ---------------------------------------------------------------------------- // These are defined as part of the standard machinery included from file // bslmf_invokeresult.00.t.cpp // // We need to suppress the bde_verify error due to them not being in this file: // BDE_VERIFY pragma: -TP19 using namespace BloombergLP; //============================================================================= // GLOBAL TYPEDEFS/CONSTANTS FOR TESTING //----------------------------------------------------------------------------- template <class TP> TP returnObj() // Return a value-initialized object of type 'TP'. { return TP(); } template <class TP> TP& returnNoCVRef() // Return a reference to a value-initialized object of type 'TP'. 'TP' is // assumed not to be cv-qualified. { static TP obj; return obj; } template <class TP> TP& returnLvalueRef() // Return an lvalue reference to a value-initialized object of type // 'TP'. 'TP' may be cv-qualified. { return returnNoCVRef<typename bsl::remove_cv<TP>::type>(); } #ifdef BSLS_COMPILERFEATURES_SUPPORT_RVALUE_REFERENCES template <class TP> TP&& returnRvalueRef() // Return an rvalue reference to a value-initialized object of type 'TP'. { return std::move(returnLvalueRef<TP>()); } #endif template <class TP> bslmf::InvokeResultDeductionFailed discardObj() // Return an 'bslmf::InvokeResultDeductionFailed' object initialized from // an rvalue of type 'TP'. { return returnObj<TP>(); } template <class TP> bslmf::InvokeResultDeductionFailed discardLvalueRef() // Return an 'bslmf::InvokeResultDeductionFailed' object initialized from // an lvalue reference of type 'TP&'. 'TP' may be cv-qualified. { return returnLvalueRef<TP>(); } #ifdef BSLS_COMPILERFEATURES_SUPPORT_RVALUE_REFERENCES template <class TP> bslmf::InvokeResultDeductionFailed discardRvalueRef() // Return an 'bslmf::InvokeResultDeductionFailed' object initialized from // an rvalue reference of type 'TP&&'. 'TP' may be cv-qualified. { return returnRvalueRef<TP>(); } #endif // ============================================================================ // MAIN PROGRAM // ---------------------------------------------------------------------------- int main(int argc, char *argv[]) { const int test = argc > 1 ? atoi(argv[1]) : 0; BSLA_MAYBE_UNUSED const bool verbose = argc > 2; BSLA_MAYBE_UNUSED const bool veryVerbose = argc > 3; BSLA_MAYBE_UNUSED const bool veryVeryVerbose = argc > 4; BSLA_MAYBE_UNUSED const bool veryVeryVeryVerbose = argc > 5; using BloombergLP::bslmf::InvokeResultDeductionFailed; printf("TEST " __FILE__ " CASE %d\n", test); // As test cases are defined elsewhere, we need to suppress bde_verify // warnings about missing test case comments/banners. // BDE_VERIFY pragma: push // BDE_VERIFY pragma: -TP05 // BDE_VERIFY pragma: -TP17 switch (test) { case 0: // Zero is always the leading case. case 8: BSLA_FALLTHROUGH; case 7: { referUserToElsewhere(test, verbose); } break; case 6: { // -------------------------------------------------------------------- // TESTING 'InvokeResultDeductionFailed' // // Concerns: //: 1 'bslmf::InvokeResultDeductionFailed' can be constructed from any //: object type. //: 2 'bslmf::InvokeResultDeductionFailed' can be constructed from any //: lvalue reference. //: 3 The previous concerns apply if the initializer is cv qualified. //: 4 In C++11 and later compilations, //: 'bslmf::InvokeResultDeductionFailed' can be constructed from any //: rvalue reference. //: 5 The above concerns apply to values that are the result of a //: function return. //: 6 The 'return' statement of a function returning a //: 'bslmf::InvokeResultDeductionFailed' can specify an lvalue or //: rvalue of any type, resulting in the value being ignored. // // Plan: //: 1 For concern 1, construct 'bslmf::InvokeResultDeductionFailed' //: objects from value-initialized objects of numeric type, //: pointer type, class type, and enumeration type. There is nothing //: to verify -- simply compiling successfully is enough. //: 2 For concern 2, create variables of the same types as in the //: previous step. Construct a 'bslmf::InvokeResultDeductionFailed' //: object from each (lvalue) variable. //: 3 For concern 3, repeat step 2, using a 'const_cast' to add cv //: qualifiers to the lvalues. //: 4 For concern 4, repeat step 2, applying 'std::move' to each //: variable used to construct an object (C++11 and later only). //: 5 For concern 5, implement a function 'returnObj<TP>' that returns //: an object of type 'TP', a function 'returnLvalueRef<TP>', that //: returns a reference of type 'TP&' and (for C++11 and later) //: 'returnRvalueRef<TP>' that returns a reference of type //: 'TP&&'. Construct a 'bslmf::InvokeResultDeductionFailed' object //: from a call to each function template instantiated with each of //: the types from step 1 and various cv-qualifier combinations. //: 6 For concern 6, implement function templates returning //: 'bslmf::InvokeResultDeductionFailed' objects 'discardObj<TP>', //: 'discardLvalueRef<TP>', and 'discardRvalueRef<TP>'. These //: functions respectively contain the statements 'return //: returnObj<TP>', 'return returnLvalueRef<TP>', and 'return //: returnRvalueRef<TP>'. Invoke each function with the same types //: as in step 5. // // Testing // 'InvokeResultDeductionFailed' // -------------------------------------------------------------------- if (verbose) printf("\nTESTING 'InvokeResultDeductionFailed'" "\n=====================================\n"); if (verbose) printf( "This test only exists in file bslm_invokeresult.%02d.t.cpp\n" "(versions in other files are no-ops)\n", test); int v1 = 0; bsl::nullptr_t v2; const char* v3 = "hello"; MyEnum v4 = MY_ENUMERATOR; MyClass v5; ASSERT(true); // Suppress "not used" warning // Step 1: Conversion from rvalue { bslmf::InvokeResultDeductionFailed x1(0); (void) x1; // Suppress "set but not used" warning bslmf::InvokeResultDeductionFailed x2 = bsl::nullptr_t(); bslmf::InvokeResultDeductionFailed x3("hello"); bslmf::InvokeResultDeductionFailed x4(MY_ENUMERATOR); // MyEnum bslmf::InvokeResultDeductionFailed x5 = MyClass(); (void) x2; // Suppress "set but not used" warning (void) x3; // Suppress "set but not used" warning (void) x4; // Suppress "set but not used" warning (void) x5; // Suppress "set but not used" warning } // Step 2: Conversion from lvalue { bslmf::InvokeResultDeductionFailed x1 = v1; (void) x1; // Suppress "set but not used" warning bslmf::InvokeResultDeductionFailed x2 = v2; bslmf::InvokeResultDeductionFailed x3 = v3; bslmf::InvokeResultDeductionFailed x4 = v4; bslmf::InvokeResultDeductionFailed x5 = v5; (void) x2; // Suppress "set but not used" warning (void) x3; // Suppress "set but not used" warning (void) x4; // Suppress "set but not used" warning (void) x5; // Suppress "set but not used" warning } // Step 3: Conversion from cv-qualified lvalue { bslmf::InvokeResultDeductionFailed x1 = const_cast<const int&>(v1); bslmf::InvokeResultDeductionFailed x3 = const_cast<const char *volatile& >(v3); bslmf::InvokeResultDeductionFailed x4 = const_cast<const volatile MyEnum&>(v4); bslmf::InvokeResultDeductionFailed x5 = const_cast<const MyClass&>(v5); (void) x1; // Suppress "set but not used" warning (void) x3; // Suppress "set but not used" warning (void) x4; // Suppress "set but not used" warning (void) x5; // Suppress "set but not used" warning } #ifdef BSLS_COMPILERFEATURES_SUPPORT_RVALUE_REFERENCES // Step 4: Conversion from rvalue reference { bslmf::InvokeResultDeductionFailed x1 = std::move(v1); bslmf::InvokeResultDeductionFailed x2 = std::move(v2); bslmf::InvokeResultDeductionFailed x3 = std::move(v3); bslmf::InvokeResultDeductionFailed x4 = std::move(v4); bslmf::InvokeResultDeductionFailed x5 = std::move(v5); (void) x1; // Suppress "set but not used" warning (void) x2; // Suppress "set but not used" warning (void) x3; // Suppress "set but not used" warning (void) x4; // Suppress "set but not used" warning (void) x5; // Suppress "set but not used" warning } #endif // Step 5: Initialization from function return { bslmf::InvokeResultDeductionFailed x1 = returnObj<int>(); (void) x1; // Suppress "set but not used" warning bslmf::InvokeResultDeductionFailed x2 = returnObj<bsl::nullptr_t>(); bslmf::InvokeResultDeductionFailed x3 = returnObj<const char *>(); bslmf::InvokeResultDeductionFailed x4 = returnObj<MyEnum>(); bslmf::InvokeResultDeductionFailed x5 = returnObj<MyClass>(); (void) x2; // Suppress "set but not used" warning (void) x3; // Suppress "set but not used" warning (void) x4; // Suppress "set but not used" warning (void) x5; // Suppress "set but not used" warning } { bslmf::InvokeResultDeductionFailed x1 = returnLvalueRef<int>(); bslmf::InvokeResultDeductionFailed x2 = returnLvalueRef<bsl::nullptr_t>(); bslmf::InvokeResultDeductionFailed x3 = returnLvalueRef<const char *const>(); bslmf::InvokeResultDeductionFailed x4 = returnLvalueRef<volatile MyEnum>(); bslmf::InvokeResultDeductionFailed x5 = returnLvalueRef<const volatile MyClass>(); (void) x1; // Suppress "set but not used" warning (void) x2; // Suppress "set but not used" warning (void) x3; // Suppress "set but not used" warning (void) x4; // Suppress "set but not used" warning (void) x5; // Suppress "set but not used" warning } #ifdef BSLS_COMPILERFEATURES_SUPPORT_RVALUE_REFERENCES { bslmf::InvokeResultDeductionFailed x1 = returnRvalueRef<int>(); bslmf::InvokeResultDeductionFailed x2 = returnRvalueRef<bsl::nullptr_t>(); bslmf::InvokeResultDeductionFailed x3 = returnRvalueRef<const char *>(); bslmf::InvokeResultDeductionFailed x4 = returnRvalueRef<MyEnum>(); bslmf::InvokeResultDeductionFailed x5 = returnRvalueRef<MyClass>(); (void) x1; // Suppress "set but not used" warning (void) x2; // Suppress "set but not used" warning (void) x3; // Suppress "set but not used" warning (void) x4; // Suppress "set but not used" warning (void) x5; // Suppress "set but not used" warning } #endif // Step 6: Return 'bslmf::InvokeResultDeductionFailed' { discardObj<int>(); discardObj<bsl::nullptr_t>(); discardObj<const char *>(); discardObj<MyEnum>(); discardObj<MyClass>(); discardLvalueRef<int>(); discardLvalueRef<bsl::nullptr_t>(); discardLvalueRef<const char *const>(); discardLvalueRef<volatile MyEnum>(); discardLvalueRef<const volatile MyClass>(); #ifdef BSLS_COMPILERFEATURES_SUPPORT_RVALUE_REFERENCES discardRvalueRef<int>(); discardRvalueRef<bsl::nullptr_t>(); discardRvalueRef<const char *>(); discardRvalueRef<MyEnum>(); discardRvalueRef<MyClass>(); #endif } } break; case 5: BSLA_FALLTHROUGH; case 4: BSLA_FALLTHROUGH; case 3: BSLA_FALLTHROUGH; case 2: BSLA_FALLTHROUGH; case 1: { referUserToElsewhere(test, verbose); } break; default: { fprintf(stderr, "WARNING: CASE `%d' NOT FOUND.\n", test); testStatus = -1; } } // BDE_VERIFY pragma: pop if (testStatus > 0) { fprintf(stderr, "Error, non-zero test status = %d.\n", testStatus); } return testStatus; } // ---------------------------------------------------------------------------- // Copyright 2018 Bloomberg Finance L.P. // // 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. // ----------------------------- END-OF-FILE ----------------------------------
bloomberg/bde
groups/bsl/bslmf/bslmf_invokeresult.06.t.cpp
C++
apache-2.0
15,358
/** * Test for LOOMIA TILE Token * * @author Pactum IO <[email protected]> */ import {getEvents, BigNumber} from './helpers/tools'; import expectThrow from './helpers/expectThrow'; const loomiaToken = artifacts.require('./TileToken'); const should = require('chai') // eslint-disable-line .use(require('chai-as-promised')) .use(require('chai-bignumber')(BigNumber)) .should(); /** * Tile Token Contract */ contract('TileToken', (accounts) => { const owner = accounts[0]; const tokenHolder1 = accounts[1]; const spendingAddress = accounts[2]; const recipient = accounts[3]; const anotherAccount = accounts[4]; const tokenHolder5 = accounts[5]; const zeroTokenHolder = accounts[6]; const zeroAddress = '0x0000000000000000000000000000000000000000'; const zero = new BigNumber(0); const tokenSupply = new BigNumber(1046000000000000000000000000); // Provide Tile Token instance for every test case let tileTokenInstance; beforeEach(async () => { tileTokenInstance = await loomiaToken.deployed(); }); it('should instantiate the token correctly', async () => { const name = await tileTokenInstance.NAME(); const symbol = await tileTokenInstance.SYMBOL(); const decimals = await tileTokenInstance.DECIMALS(); const totalSupply = await tileTokenInstance.totalSupply(); assert.equal(name, 'LOOMIA TILE', 'Name does not match'); assert.equal(symbol, 'TILE', 'Symbol does not match'); assert.equal(decimals, 18, 'Decimals does not match'); totalSupply.should.be.bignumber.equal(tokenSupply); }); describe('balanceOf', function () { describe('when the requested account has no tokens', function () { it('returns zero', async function () { const balance = await tileTokenInstance.balanceOf(zeroTokenHolder); balance.should.be.bignumber.equal(zero); }); }); describe('when the requested account has some tokens', function () { it('returns the total amount of tokens', async function () { const balance = await tileTokenInstance.balanceOf(owner); balance.should.be.bignumber.equal(tokenSupply); }); }); }); describe('transfer', function () { describe('when the recipient is not the zero address', function () { const to = tokenHolder1; describe('when the sender does not have enough balance', function () { const transferAmount = tokenSupply.add(1); it('reverts', async function () { await expectThrow(tileTokenInstance.transfer(to, transferAmount, { from: owner })); }); }); describe('when the sender has enough balance', function () { const transferAmount = new BigNumber(500 * 1e18); it('transfers the requested amount', async function () { await tileTokenInstance.transfer(to, transferAmount, { from: owner }); const senderBalance = await tileTokenInstance.balanceOf(owner); senderBalance.should.be.bignumber.equal(tokenSupply.sub(transferAmount)); const recipientBalance = await tileTokenInstance.balanceOf(to); recipientBalance.should.be.bignumber.equal(transferAmount); }); it('emits a transfer event', async function () { const tx = await tileTokenInstance.transfer(to, transferAmount, { from: owner }); // Test the event const events = getEvents(tx, 'Transfer'); assert.equal(events[0].from, owner, 'From address does not match'); assert.equal(events[0].to, to, 'To address does not match'); (events[0].value).should.be.bignumber.equal(transferAmount); }); }); }); describe('when the recipient is the zero address', function () { const to = zeroAddress; it('reverts', async function () { await expectThrow(tileTokenInstance.transfer(to, 100, { from: owner })); }); }); }); describe('approve', function () { describe('when the spender is not the zero address', function () { const spender = spendingAddress; describe('when the sender has enough balance', function () { const amount = new BigNumber(100 * 1e18); it('emits an approval event', async function () { const tx = await tileTokenInstance.approve(spender, amount, { from: owner }); // Test the event const events = getEvents(tx, 'Approval'); assert.equal(events[0].owner, owner, 'address does not match'); assert.equal(events[0].spender, spender, 'Spender address does not match'); (events[0].value).should.be.bignumber.equal(amount); }); describe('when there was no approved amount before', function () { it('approves the requested amount', async function () { await tileTokenInstance.approve(spender, amount, { from: owner }); const allowance = await tileTokenInstance.allowance(owner, spender); allowance.should.be.bignumber.equal(amount); }); }); describe('when the spender had an approved amount', function () { beforeEach(async function () { await tileTokenInstance.approve(spender, 1, { from: owner }); }); it('approves the requested amount and replaces the previous one', async function () { await tileTokenInstance.approve(spender, amount, { from: owner }); const allowance = await tileTokenInstance.allowance(owner, spender); allowance.should.be.bignumber.equal(amount); }); }); }); describe('when the sender does not have enough balance', function () { const amount = new BigNumber(101 * 1e18); it('emits an approval event', async function () { const tx = await tileTokenInstance.approve(spender, amount, { from: owner }); const events = getEvents(tx, 'Approval'); assert.equal(events[0].owner, owner, 'address does not match'); assert.equal(events[0].spender, spender, 'Spender address does not match'); (events[0].value).should.be.bignumber.equal(amount); }); describe('when there was no approved amount before', function () { it('approves the requested amount', async function () { await tileTokenInstance.approve(spender, amount, { from: owner }); const allowance = await tileTokenInstance.allowance(owner, spender); allowance.should.be.bignumber.equal(amount); }); }); describe('when the spender had an approved amount', function () { beforeEach(async function () { await tileTokenInstance.approve(spender, 1, { from: owner }); }); it('approves the requested amount and replaces the previous one', async function () { await tileTokenInstance.approve(spender, amount, { from: owner }); const allowance = await tileTokenInstance.allowance(owner, spender); allowance.should.be.bignumber.equal(amount); }); }); }); }); describe('when the spender is the zero address', function () { const amount = new BigNumber(100 * 1e18); const spender = zeroAddress; it('approves the requested amount', async function () { await tileTokenInstance.approve(spender, amount, { from: owner }); const allowance = await tileTokenInstance.allowance(owner, spender); allowance.should.be.bignumber.equal(amount); }); it('emits an approval event', async function () { const tx = await tileTokenInstance.approve(spender, amount, { from: owner }); const events = getEvents(tx, 'Approval'); assert.equal(events[0].owner, owner, 'address does not match'); assert.equal(events[0].spender, spender, 'Spender address does not match'); (events[0].value).should.be.bignumber.equal(amount); }); }); }); describe('transfer from', function () { const spender = recipient; describe('when the recipient is not the zero address', function () { const to = anotherAccount; describe('when the spender has enough approved balance', function () { beforeEach(async function () { const approvalAmount = new BigNumber(30000 * 1e18); await tileTokenInstance.approve(spender, approvalAmount, { from: owner }); await tileTokenInstance.approve(spender, approvalAmount, { from: zeroTokenHolder }); }); describe('when the owner has enough balance', function () { const amount = new BigNumber(30000 * 1e18); it('transfers the requested amount', async function () { const balanceBefore = await tileTokenInstance.balanceOf(owner); await tileTokenInstance.transferFrom(owner, to, amount, { from: spender }); const senderBalance = await tileTokenInstance.balanceOf(owner); senderBalance.should.be.bignumber.equal(balanceBefore.sub(amount)); const recipientBalance = await tileTokenInstance.balanceOf(to); recipientBalance.should.be.bignumber.equal(amount); }); it('decreases the spender allowance', async function () { await tileTokenInstance.transferFrom(owner, to, amount, { from: spender }); const allowance = await tileTokenInstance.allowance(owner, spender); assert(allowance.eq(0)); }); it('emits a transfer event', async function () { const tx = await tileTokenInstance.transferFrom(owner, to, amount, { from: spender }); // Test the event const events = getEvents(tx, 'Transfer'); assert.equal(events[0].from, owner, 'address does not match'); assert.equal(events[0].to, to, 'To address does not match'); (events[0].value).should.be.bignumber.equal(amount); }); }); describe('when the owner does not have enough balance', function () { const amount = new BigNumber(1 * 1e18); it('reverts', async function () { await expectThrow(tileTokenInstance.transferFrom(zeroTokenHolder, to, amount, { from: spender })); }); }); }); describe('when the spender does not have enough approved balance', function () { beforeEach(async function () { const approvalAmount = new BigNumber(99 * 1e18); const bigApprovalAmount = new BigNumber(999 * 1e18); await tileTokenInstance.approve(spender, approvalAmount, { from: owner }); await tileTokenInstance.approve(spender, bigApprovalAmount, { from: tokenHolder1 }); }); describe('when the owner has enough balance', function () { const amount = new BigNumber(100 * 1e18); it('reverts', async function () { await expectThrow(tileTokenInstance.transferFrom(owner, to, amount, { from: spender })); }); }); describe('when the owner does not have enough balance', function () { const amount = new BigNumber(1001 * 1e18); it('reverts', async function () { await expectThrow(tileTokenInstance.transferFrom(tokenHolder1, to, amount, { from: spender })); }); }); }); }); describe('when the recipient is the zero address', function () { const amount = new BigNumber(100 * 1e18); const to = zeroAddress; beforeEach(async function () { await tileTokenInstance.approve(spender, amount, { from: owner }); }); it('reverts', async function () { await expectThrow(tileTokenInstance.transferFrom(owner, to, amount, { from: spender })); }); }); }); describe('decrease approval', function () { describe('when the spender is not the zero address', function () { const spender = recipient; describe('when the sender has enough balance', function () { const amount = new BigNumber(100 * 1e18); it('emits an approval event', async function () { const tx = await tileTokenInstance.decreaseApproval(spender, amount, { from: owner }); // Test the event const events = getEvents(tx, 'Approval'); assert.equal(events[0].owner, owner, 'address does not match'); assert.equal(events[0].spender, spender, 'Spender address does not match'); (events[0].value).should.be.bignumber.equal(0); }); describe('when there was no approved amount before', function () { it('keeps the allowance to zero', async function () { await tileTokenInstance.decreaseApproval(spender, amount, { from: owner }); const allowance = await tileTokenInstance.allowance(owner, spender); allowance.should.be.bignumber.equal(0); }); }); describe('when the spender had an approved amount', function () { beforeEach(async function () { const approvalAmount = new BigNumber(1000 * 1e18); await tileTokenInstance.approve(spender, approvalAmount, { from: owner }); }); it('decreases the spender allowance subtracting the requested amount', async function () { await tileTokenInstance.decreaseApproval(spender, amount, { from: owner }); const approvalAmount = new BigNumber(1000 * 1e18); const allowance = await tileTokenInstance.allowance(owner, spender); allowance.should.be.bignumber.equal(approvalAmount.sub(amount)); }); }); }); describe('when the sender does not have enough balance', function () { const amount = new BigNumber(1000 * 1e18); it('emits an approval event', async function () { const tx = await tileTokenInstance.decreaseApproval(spender, amount, { from: owner }); // Test the event const events = getEvents(tx, 'Approval'); assert.equal(events[0].owner, owner, 'address does not match'); assert.equal(events[0].spender, spender, 'Spender address does not match'); (events[0].value).should.be.bignumber.equal(0); }); describe('when there was no approved amount before', function () { it('keeps the allowance to zero', async function () { await tileTokenInstance.decreaseApproval(spender, amount, { from: owner }); const allowance = await tileTokenInstance.allowance(owner, spender); allowance.should.be.bignumber.equal(0); }); }); describe('when the spender had an approved amount', function () { beforeEach(async function () { const approvalAmount = new BigNumber(1001 * 1e18); await tileTokenInstance.approve(spender, approvalAmount, { from: owner }); }); it('decreases the spender allowance subtracting the requested amount', async function () { await tileTokenInstance.decreaseApproval(spender, amount, { from: owner }); const allowance = await tileTokenInstance.allowance(owner, spender); allowance.should.be.bignumber.equal(1 * 1e18); }); }); }); }); describe('when the spender is the zero address', function () { const amount = new BigNumber(100 * 1e18); const spender = zeroAddress; it('decreases the requested amount', async function () { await tileTokenInstance.decreaseApproval(spender, amount, { from: owner }); const allowance = await tileTokenInstance.allowance(owner, spender); allowance.should.be.bignumber.equal(0); }); it('emits an approval event', async function () { const tx = await tileTokenInstance.decreaseApproval(spender, amount, { from: owner }); // Test the event const events = getEvents(tx, 'Approval'); assert.equal(events[0].owner, owner, 'address does not match'); assert.equal(events[0].spender, spender, 'Spender address does not match'); (events[0].value).should.be.bignumber.equal(0); }); }); }); describe('increase approval', function () { const amount = new BigNumber(100 * 1e18); describe('when the spender is not the zero address', function () { const spender = recipient; describe('when the sender has enough balance', function () { it('emits an approval event', async function () { const oldAllowance = await tileTokenInstance.allowance(owner, spender); const tx = await tileTokenInstance.increaseApproval(spender, amount, { from: owner }); // Test the event const events = getEvents(tx, 'Approval'); assert.equal(events[0].owner, owner, 'address does not match'); assert.equal(events[0].spender, spender, 'Spender address does not match'); (events[0].value).should.be.bignumber.equal(amount.add(oldAllowance)); }); describe('when there was no approved amount before', function () { it('approves the requested amount', async function () { const oldAllowance = await tileTokenInstance.allowance(owner, spender); await tileTokenInstance.increaseApproval(spender, amount, { from: owner }); const allowance = await tileTokenInstance.allowance(owner, spender); allowance.should.be.bignumber.equal(amount.add(oldAllowance)); }); }); describe('when the spender had an approved amount', function () { beforeEach(async function () { const approvalAmount = new BigNumber(1 * 1e18); await tileTokenInstance.approve(spender, approvalAmount, { from: owner }); }); it('increases the spender allowance adding the requested amount', async function () { const oldAllowance = await tileTokenInstance.allowance(owner, spender); await tileTokenInstance.increaseApproval(spender, amount, { from: owner }); const allowance = await tileTokenInstance.allowance(owner, spender); allowance.should.be.bignumber.equal(oldAllowance.add(amount)); }); }); }); describe('when the sender does not have enough balance', function () { const amount = new BigNumber(2 * 1e18); it('emits an approval event', async function () { const oldAllowance = await tileTokenInstance.allowance(tokenHolder1, spender); const tx = await tileTokenInstance.increaseApproval(spender, amount, { from: tokenHolder1 }); // Test the event const events = getEvents(tx, 'Approval'); assert.equal(events[0].owner, tokenHolder1, 'address does not match'); assert.equal(events[0].spender, spender, 'Spender address does not match'); (events[0].value).should.be.bignumber.equal(oldAllowance.add(amount)); }); describe('when there was no approved amount before', function () { it('approves the requested amount', async function () { await tileTokenInstance.increaseApproval(spender, amount, { from: tokenHolder5 }); const allowance = await tileTokenInstance.allowance(tokenHolder5, spender); allowance.should.be.bignumber.equal(amount); }); }); describe('when the spender had an approved amount', function () { beforeEach(async function () { const approvalAmount = new BigNumber(1 * 1e18); await tileTokenInstance.approve(spender, approvalAmount, { from: tokenHolder5 }); }); it('increases the spender allowance adding the requested amount', async function () { const oldAllowance = await tileTokenInstance.allowance(tokenHolder5, spender); await tileTokenInstance.increaseApproval(spender, amount, { from: tokenHolder5 }); const allowance = await tileTokenInstance.allowance(tokenHolder5, spender); allowance.should.be.bignumber.equal(oldAllowance.add(amount)); }); }); }); }); describe('when the spender is the zero address', function () { const spender = zeroAddress; it('approves the requested amount', async function () { await tileTokenInstance.increaseApproval(spender, amount, { from: owner }); const allowance = await tileTokenInstance.allowance(owner, spender); allowance.should.be.bignumber.equal(amount); }); it('emits an approval event', async function () { const oldAllowance = await tileTokenInstance.allowance(owner, spender); const tx = await tileTokenInstance.increaseApproval(spender, amount, { from: owner }); // Test the event const events = getEvents(tx, 'Approval'); assert.equal(events[0].owner, owner, 'address does not match'); assert.equal(events[0].spender, spender, 'Spender address does not match'); (events[0].value).should.be.bignumber.equal(oldAllowance.add(amount)); }); }); }); });
LOOMIA/loomia
tiletoken/test/contracts/0_TileToken.js
JavaScript
apache-2.0
26,410
/** */ package org.tud.inf.st.mbt.ocm.impl; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.EPackage; import org.eclipse.emf.ecore.impl.EFactoryImpl; import org.eclipse.emf.ecore.plugin.EcorePlugin; import org.tud.inf.st.mbt.ocm.*; /** * <!-- begin-user-doc --> * An implementation of the model <b>Factory</b>. * <!-- end-user-doc --> * @generated */ public class OcmFactoryImpl extends EFactoryImpl implements OcmFactory { /** * Creates the default factory implementation. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public static OcmFactory init() { try { OcmFactory theOcmFactory = (OcmFactory)EPackage.Registry.INSTANCE.getEFactory(OcmPackage.eNS_URI); if (theOcmFactory != null) { return theOcmFactory; } } catch (Exception exception) { EcorePlugin.INSTANCE.log(exception); } return new OcmFactoryImpl(); } /** * Creates an instance of the factory. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public OcmFactoryImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public EObject create(EClass eClass) { switch (eClass.getClassifierID()) { case OcmPackage.OPERATIONAL_CONFIGURATION_MODEL: return createOperationalConfigurationModel(); case OcmPackage.STANDARD_CONFIGURATION_NODE: return createStandardConfigurationNode(); case OcmPackage.RECONFIGURATION_ACTION_NODE: return createReconfigurationActionNode(); case OcmPackage.TIMED_EDGE: return createTimedEdge(); case OcmPackage.EVENT_GUARDED_EDGE: return createEventGuardedEdge(); default: throw new IllegalArgumentException("The class '" + eClass.getName() + "' is not a valid classifier"); } } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public OperationalConfigurationModel createOperationalConfigurationModel() { OperationalConfigurationModelImpl operationalConfigurationModel = new OperationalConfigurationModelImpl(); return operationalConfigurationModel; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public StandardConfigurationNode createStandardConfigurationNode() { StandardConfigurationNodeImpl standardConfigurationNode = new StandardConfigurationNodeImpl(); return standardConfigurationNode; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public ReconfigurationActionNode createReconfigurationActionNode() { ReconfigurationActionNodeImpl reconfigurationActionNode = new ReconfigurationActionNodeImpl(); return reconfigurationActionNode; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public TimedEdge createTimedEdge() { TimedEdgeImpl timedEdge = new TimedEdgeImpl(); return timedEdge; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EventGuardedEdge createEventGuardedEdge() { EventGuardedEdgeImpl eventGuardedEdge = new EventGuardedEdgeImpl(); return eventGuardedEdge; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public OcmPackage getOcmPackage() { return (OcmPackage)getEPackage(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @deprecated * @generated */ @Deprecated public static OcmPackage getPackage() { return OcmPackage.eINSTANCE; } } //OcmFactoryImpl
paetti1988/qmate
MATE/org.tud.inf.st.mbt.emf/src-gen/org/tud/inf/st/mbt/ocm/impl/OcmFactoryImpl.java
Java
apache-2.0
3,466
/** * Copyright (c) 2013-2019 Contributors to the Eclipse Foundation * * <p> See the NOTICE file distributed with this work for additional information regarding copyright * ownership. All rights reserved. This program and the accompanying materials are made available * under the terms of the Apache License, Version 2.0 which accompanies this distribution and is * available at http://www.apache.org/licenses/LICENSE-2.0.txt */ package org.locationtech.geowave.core.store.util; import java.util.Iterator; import java.util.Map; import org.locationtech.geowave.core.store.adapter.PersistentAdapterStore; import org.locationtech.geowave.core.store.adapter.RowMergingDataAdapter; import org.locationtech.geowave.core.store.adapter.RowMergingDataAdapter.RowTransform; import org.locationtech.geowave.core.store.api.Index; import org.locationtech.geowave.core.store.entities.GeoWaveRow; import org.locationtech.geowave.core.store.operations.RowDeleter; import org.locationtech.geowave.core.store.operations.RowWriter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class RewritingMergingEntryIterator<T> extends MergingEntryIterator<T> { private static final Logger LOGGER = LoggerFactory.getLogger(RewritingMergingEntryIterator.class); private final RowWriter writer; private final RowDeleter deleter; public RewritingMergingEntryIterator( final PersistentAdapterStore adapterStore, final Index index, final Iterator<GeoWaveRow> scannerIt, final Map<Short, RowMergingDataAdapter> mergingAdapters, final RowWriter writer, final RowDeleter deleter) { super(adapterStore, index, scannerIt, null, null, mergingAdapters, null, null); this.writer = writer; this.deleter = deleter; } @Override protected GeoWaveRow mergeSingleRowValues( final GeoWaveRow singleRow, final RowTransform rowTransform) { if (singleRow.getFieldValues().length < 2) { return singleRow; } deleter.delete(singleRow); deleter.flush(); final GeoWaveRow merged = super.mergeSingleRowValues(singleRow, rowTransform); writer.write(merged); return merged; } }
spohnan/geowave
core/store/src/main/java/org/locationtech/geowave/core/store/util/RewritingMergingEntryIterator.java
Java
apache-2.0
2,157
package plugin /* usage: !day */ import ( "strings" "time" "github.com/microamp/gerri/cmd" "github.com/microamp/gerri/data" ) func ReplyDay(pm data.Privmsg, config *data.Config) (string, error) { return cmd.Privmsg(pm.Target, strings.ToLower(time.Now().Weekday().String())), nil }
kesara/gerri
plugin/day.go
GO
apache-2.0
289
/* * Copyright (C) 2019 Contentful GmbH * * 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.contentful.java.cma; import com.contentful.java.cma.model.CMAArray; import com.contentful.java.cma.model.CMATag; import io.reactivex.Flowable; import retrofit2.Response; import retrofit2.http.GET; import retrofit2.http.PUT; import retrofit2.http.Path; import retrofit2.http.QueryMap; import retrofit2.http.Body; import retrofit2.http.DELETE; import java.util.Map; /** * Spaces Service. */ interface ServiceContentTags { @GET("/spaces/{space_id}/environments/{environment_id}/tags") Flowable<CMAArray<CMATag>> fetchAll( @Path("space_id") String spaceId, @Path("environment_id") String environmentID, @QueryMap Map<String, String> query ); @PUT("/spaces/{space_id}/environments/{environment_id}/tags/{tag_id}") Flowable<CMATag> create( @Path("space_id") String spaceId, @Path("environment_id") String environmentID, @Path("tag_id") String tagId, @Body CMATag tag); @GET("/spaces/{space_id}/environments/{environment_id}/tags/{tag_id}") Flowable<CMATag> fetchOne( @Path("space_id") String spaceId, @Path("environment_id") String environmentID, @Path("tag_id") String tagId ); @PUT("/spaces/{space_id}/environments/{environment_id}/tags/{tag_id}") Flowable<CMATag> update( @Path("space_id") String spaceId, @Path("environment_id") String environmentID, @Path("tag_id") String tagId, @Body CMATag tag); @DELETE("/spaces/{space_id}/environments/{environment_id}/tags/{tag_id}") Flowable<Response<Void>> delete( @Path("space_id") String spaceId, @Path("environment_id") String environmentID, @Path("tag_id") String tagId); }
contentful/contentful-management.java
src/main/java/com/contentful/java/cma/ServiceContentTags.java
Java
apache-2.0
2,309
package main import ( "net/url" "time" "github.com/codegangsta/cli" "github.com/michaeltrobinson/cadvisor-integration/scraper" "github.com/signalfx/metricproxy/protocol/signalfx" log "github.com/Sirupsen/logrus" ) var ( sfxAPIToken string sfxIngestURL string clusterName string sendInterval time.Duration cadvisorPort int discoveryInterval time.Duration maxDatapoints int kubeUser string kubePass string ) func init() { app.Commands = append(app.Commands, cli.Command{ Name: "run", Usage: "start the service (the default)", Action: run, Before: setupRun, Flags: []cli.Flag{ cli.StringFlag{ Name: "sfx-ingest-url", EnvVar: "SFX_ENDPOINT", Value: "https://ingest.signalfx.com", Usage: "SignalFx ingest URL", }, cli.StringFlag{ Name: "sfx-api-token", EnvVar: "SFX_API_TOKEN", Usage: "SignalFx API token", }, cli.StringFlag{ Name: "cluster-name", EnvVar: "CLUSTER_NAME", Usage: "Cluster name will appear as dimension", }, cli.DurationFlag{ Name: "send-interval", EnvVar: "SEND_INTERVAL", Value: time.Second * 30, Usage: "Rate at which data is queried from cAdvisor and send to SignalFx", }, cli.IntFlag{ Name: "cadvisor-port", EnvVar: "CADVISOR_PORT", Value: 4194, Usage: "Port on which cAdvisor listens", }, cli.DurationFlag{ Name: "discovery-interval", EnvVar: "NODE_SERVICE_DISCOVERY_INTERVAL", Value: time.Minute * 5, Usage: "Rate at which nodes and services will be rediscovered", }, cli.StringFlag{ Name: "kube-user", EnvVar: "KUBE_USER", Usage: "Username to authenticate to kubernetes api", }, cli.StringFlag{ Name: "kube-pass", EnvVar: "KUBE_PASS", Usage: "Password to authenticate to kubernetes api", }, cli.IntFlag{ Name: "max-datapoints", EnvVar: "MAX_DATAPOINTS", Value: 50, Usage: "How many datapoints to batch before forwarding to SignalFX", }, }, }) } func setupRun(c *cli.Context) error { sfxAPIToken = c.String("sfx-api-token") if sfxAPIToken == "" { cli.ShowAppHelp(c) log.Fatal("API token is required") } clusterName = c.String("cluster-name") if clusterName == "" { cli.ShowAppHelp(c) log.Fatal("cluster name is required") } sfxIngestURL = c.String("sfx-ingest-url") sendInterval = c.Duration("send-interval") cadvisorPort = c.Int("cadvisor-port") discoveryInterval = c.Duration("discovery-interval") kubeUser = c.String("kube-user") kubePass = c.String("kube-pass") if kubeUser == "" || kubePass == "" { cli.ShowAppHelp(c) log.Fatal("kubernetes credentials are required") } maxDatapoints = c.Int("max-datapoints") return nil } func run(c *cli.Context) { s := scraper.New( newSfxClient(sfxIngestURL, sfxAPIToken), scraper.Config{ ClusterName: clusterName, CadvisorPort: cadvisorPort, KubeUser: kubeUser, KubePass: kubePass, MaxDatapoints: maxDatapoints, }) if err := s.Run(sendInterval, discoveryInterval); err != nil { log.WithError(err).Fatal("failure") } } func newSfxClient(ingestURL, authToken string) *signalfx.Forwarder { sfxEndpoint, err := url.Parse(ingestURL) if err != nil { panic("failed to parse SFX ingest URL") } return signalfx.NewSignalfxJSONForwarder(sfxEndpoint.String(), time.Second*10, authToken, 10, "", "", "") }
michaeltrobinson/cadvisor-integration
cmd/signalfx-cadvisord/run.go
GO
apache-2.0
3,432
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #pragma once #include <aws/mwaa/MWAA_EXPORTS.h> #include <aws/mwaa/MWAARequest.h> #include <aws/core/utils/memory/stl/AWSMap.h> #include <aws/core/utils/memory/stl/AWSString.h> #include <aws/mwaa/model/LoggingConfigurationInput.h> #include <aws/mwaa/model/NetworkConfiguration.h> #include <aws/mwaa/model/WebserverAccessMode.h> #include <utility> namespace Aws { namespace MWAA { namespace Model { /** * <p>This section contains the Amazon Managed Workflows for Apache Airflow (MWAA) * API reference documentation to create an environment. For more information, see * <a href="https://docs.aws.amazon.com/mwaa/latest/userguide/get-started.html">Get * started with Amazon Managed Workflows for Apache Airflow</a>.</p><p><h3>See * Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/mwaa-2020-07-01/CreateEnvironmentInput">AWS * API Reference</a></p> */ class AWS_MWAA_API CreateEnvironmentRequest : public MWAARequest { public: CreateEnvironmentRequest(); // Service request name is the Operation name which will send this request out, // each operation should has unique request name, so that we can get operation's name from this request. // Note: this is not true for response, multiple operations may have the same response name, // so we can not get operation's name from response. inline virtual const char* GetServiceRequestName() const override { return "CreateEnvironment"; } Aws::String SerializePayload() const override; /** * <p>The Apache Airflow configuration setting you want to override in your * environment. For more information, see <a * href="https://docs.aws.amazon.com/mwaa/latest/userguide/configuring-env-variables.html">Environment * configuration</a>.</p> */ inline const Aws::Map<Aws::String, Aws::String>& GetAirflowConfigurationOptions() const{ return m_airflowConfigurationOptions; } /** * <p>The Apache Airflow configuration setting you want to override in your * environment. For more information, see <a * href="https://docs.aws.amazon.com/mwaa/latest/userguide/configuring-env-variables.html">Environment * configuration</a>.</p> */ inline bool AirflowConfigurationOptionsHasBeenSet() const { return m_airflowConfigurationOptionsHasBeenSet; } /** * <p>The Apache Airflow configuration setting you want to override in your * environment. For more information, see <a * href="https://docs.aws.amazon.com/mwaa/latest/userguide/configuring-env-variables.html">Environment * configuration</a>.</p> */ inline void SetAirflowConfigurationOptions(const Aws::Map<Aws::String, Aws::String>& value) { m_airflowConfigurationOptionsHasBeenSet = true; m_airflowConfigurationOptions = value; } /** * <p>The Apache Airflow configuration setting you want to override in your * environment. For more information, see <a * href="https://docs.aws.amazon.com/mwaa/latest/userguide/configuring-env-variables.html">Environment * configuration</a>.</p> */ inline void SetAirflowConfigurationOptions(Aws::Map<Aws::String, Aws::String>&& value) { m_airflowConfigurationOptionsHasBeenSet = true; m_airflowConfigurationOptions = std::move(value); } /** * <p>The Apache Airflow configuration setting you want to override in your * environment. For more information, see <a * href="https://docs.aws.amazon.com/mwaa/latest/userguide/configuring-env-variables.html">Environment * configuration</a>.</p> */ inline CreateEnvironmentRequest& WithAirflowConfigurationOptions(const Aws::Map<Aws::String, Aws::String>& value) { SetAirflowConfigurationOptions(value); return *this;} /** * <p>The Apache Airflow configuration setting you want to override in your * environment. For more information, see <a * href="https://docs.aws.amazon.com/mwaa/latest/userguide/configuring-env-variables.html">Environment * configuration</a>.</p> */ inline CreateEnvironmentRequest& WithAirflowConfigurationOptions(Aws::Map<Aws::String, Aws::String>&& value) { SetAirflowConfigurationOptions(std::move(value)); return *this;} /** * <p>The Apache Airflow configuration setting you want to override in your * environment. For more information, see <a * href="https://docs.aws.amazon.com/mwaa/latest/userguide/configuring-env-variables.html">Environment * configuration</a>.</p> */ inline CreateEnvironmentRequest& AddAirflowConfigurationOptions(const Aws::String& key, const Aws::String& value) { m_airflowConfigurationOptionsHasBeenSet = true; m_airflowConfigurationOptions.emplace(key, value); return *this; } /** * <p>The Apache Airflow configuration setting you want to override in your * environment. For more information, see <a * href="https://docs.aws.amazon.com/mwaa/latest/userguide/configuring-env-variables.html">Environment * configuration</a>.</p> */ inline CreateEnvironmentRequest& AddAirflowConfigurationOptions(Aws::String&& key, const Aws::String& value) { m_airflowConfigurationOptionsHasBeenSet = true; m_airflowConfigurationOptions.emplace(std::move(key), value); return *this; } /** * <p>The Apache Airflow configuration setting you want to override in your * environment. For more information, see <a * href="https://docs.aws.amazon.com/mwaa/latest/userguide/configuring-env-variables.html">Environment * configuration</a>.</p> */ inline CreateEnvironmentRequest& AddAirflowConfigurationOptions(const Aws::String& key, Aws::String&& value) { m_airflowConfigurationOptionsHasBeenSet = true; m_airflowConfigurationOptions.emplace(key, std::move(value)); return *this; } /** * <p>The Apache Airflow configuration setting you want to override in your * environment. For more information, see <a * href="https://docs.aws.amazon.com/mwaa/latest/userguide/configuring-env-variables.html">Environment * configuration</a>.</p> */ inline CreateEnvironmentRequest& AddAirflowConfigurationOptions(Aws::String&& key, Aws::String&& value) { m_airflowConfigurationOptionsHasBeenSet = true; m_airflowConfigurationOptions.emplace(std::move(key), std::move(value)); return *this; } /** * <p>The Apache Airflow configuration setting you want to override in your * environment. For more information, see <a * href="https://docs.aws.amazon.com/mwaa/latest/userguide/configuring-env-variables.html">Environment * configuration</a>.</p> */ inline CreateEnvironmentRequest& AddAirflowConfigurationOptions(const char* key, Aws::String&& value) { m_airflowConfigurationOptionsHasBeenSet = true; m_airflowConfigurationOptions.emplace(key, std::move(value)); return *this; } /** * <p>The Apache Airflow configuration setting you want to override in your * environment. For more information, see <a * href="https://docs.aws.amazon.com/mwaa/latest/userguide/configuring-env-variables.html">Environment * configuration</a>.</p> */ inline CreateEnvironmentRequest& AddAirflowConfigurationOptions(Aws::String&& key, const char* value) { m_airflowConfigurationOptionsHasBeenSet = true; m_airflowConfigurationOptions.emplace(std::move(key), value); return *this; } /** * <p>The Apache Airflow configuration setting you want to override in your * environment. For more information, see <a * href="https://docs.aws.amazon.com/mwaa/latest/userguide/configuring-env-variables.html">Environment * configuration</a>.</p> */ inline CreateEnvironmentRequest& AddAirflowConfigurationOptions(const char* key, const char* value) { m_airflowConfigurationOptionsHasBeenSet = true; m_airflowConfigurationOptions.emplace(key, value); return *this; } /** * <p>The Apache Airflow version you want to use for your environment.</p> */ inline const Aws::String& GetAirflowVersion() const{ return m_airflowVersion; } /** * <p>The Apache Airflow version you want to use for your environment.</p> */ inline bool AirflowVersionHasBeenSet() const { return m_airflowVersionHasBeenSet; } /** * <p>The Apache Airflow version you want to use for your environment.</p> */ inline void SetAirflowVersion(const Aws::String& value) { m_airflowVersionHasBeenSet = true; m_airflowVersion = value; } /** * <p>The Apache Airflow version you want to use for your environment.</p> */ inline void SetAirflowVersion(Aws::String&& value) { m_airflowVersionHasBeenSet = true; m_airflowVersion = std::move(value); } /** * <p>The Apache Airflow version you want to use for your environment.</p> */ inline void SetAirflowVersion(const char* value) { m_airflowVersionHasBeenSet = true; m_airflowVersion.assign(value); } /** * <p>The Apache Airflow version you want to use for your environment.</p> */ inline CreateEnvironmentRequest& WithAirflowVersion(const Aws::String& value) { SetAirflowVersion(value); return *this;} /** * <p>The Apache Airflow version you want to use for your environment.</p> */ inline CreateEnvironmentRequest& WithAirflowVersion(Aws::String&& value) { SetAirflowVersion(std::move(value)); return *this;} /** * <p>The Apache Airflow version you want to use for your environment.</p> */ inline CreateEnvironmentRequest& WithAirflowVersion(const char* value) { SetAirflowVersion(value); return *this;} /** * <p>The relative path to the DAG folder on your Amazon S3 storage bucket. For * example, <code>dags</code>. For more information, see <a * href="https://docs.aws.amazon.com/mwaa/latest/userguide/configuring-dag-import.html">Importing * DAGs on Amazon MWAA</a>.</p> */ inline const Aws::String& GetDagS3Path() const{ return m_dagS3Path; } /** * <p>The relative path to the DAG folder on your Amazon S3 storage bucket. For * example, <code>dags</code>. For more information, see <a * href="https://docs.aws.amazon.com/mwaa/latest/userguide/configuring-dag-import.html">Importing * DAGs on Amazon MWAA</a>.</p> */ inline bool DagS3PathHasBeenSet() const { return m_dagS3PathHasBeenSet; } /** * <p>The relative path to the DAG folder on your Amazon S3 storage bucket. For * example, <code>dags</code>. For more information, see <a * href="https://docs.aws.amazon.com/mwaa/latest/userguide/configuring-dag-import.html">Importing * DAGs on Amazon MWAA</a>.</p> */ inline void SetDagS3Path(const Aws::String& value) { m_dagS3PathHasBeenSet = true; m_dagS3Path = value; } /** * <p>The relative path to the DAG folder on your Amazon S3 storage bucket. For * example, <code>dags</code>. For more information, see <a * href="https://docs.aws.amazon.com/mwaa/latest/userguide/configuring-dag-import.html">Importing * DAGs on Amazon MWAA</a>.</p> */ inline void SetDagS3Path(Aws::String&& value) { m_dagS3PathHasBeenSet = true; m_dagS3Path = std::move(value); } /** * <p>The relative path to the DAG folder on your Amazon S3 storage bucket. For * example, <code>dags</code>. For more information, see <a * href="https://docs.aws.amazon.com/mwaa/latest/userguide/configuring-dag-import.html">Importing * DAGs on Amazon MWAA</a>.</p> */ inline void SetDagS3Path(const char* value) { m_dagS3PathHasBeenSet = true; m_dagS3Path.assign(value); } /** * <p>The relative path to the DAG folder on your Amazon S3 storage bucket. For * example, <code>dags</code>. For more information, see <a * href="https://docs.aws.amazon.com/mwaa/latest/userguide/configuring-dag-import.html">Importing * DAGs on Amazon MWAA</a>.</p> */ inline CreateEnvironmentRequest& WithDagS3Path(const Aws::String& value) { SetDagS3Path(value); return *this;} /** * <p>The relative path to the DAG folder on your Amazon S3 storage bucket. For * example, <code>dags</code>. For more information, see <a * href="https://docs.aws.amazon.com/mwaa/latest/userguide/configuring-dag-import.html">Importing * DAGs on Amazon MWAA</a>.</p> */ inline CreateEnvironmentRequest& WithDagS3Path(Aws::String&& value) { SetDagS3Path(std::move(value)); return *this;} /** * <p>The relative path to the DAG folder on your Amazon S3 storage bucket. For * example, <code>dags</code>. For more information, see <a * href="https://docs.aws.amazon.com/mwaa/latest/userguide/configuring-dag-import.html">Importing * DAGs on Amazon MWAA</a>.</p> */ inline CreateEnvironmentRequest& WithDagS3Path(const char* value) { SetDagS3Path(value); return *this;} /** * <p>The environment class you want to use for your environment. The environment * class determines the size of the containers and database used for your Apache * Airflow services.</p> */ inline const Aws::String& GetEnvironmentClass() const{ return m_environmentClass; } /** * <p>The environment class you want to use for your environment. The environment * class determines the size of the containers and database used for your Apache * Airflow services.</p> */ inline bool EnvironmentClassHasBeenSet() const { return m_environmentClassHasBeenSet; } /** * <p>The environment class you want to use for your environment. The environment * class determines the size of the containers and database used for your Apache * Airflow services.</p> */ inline void SetEnvironmentClass(const Aws::String& value) { m_environmentClassHasBeenSet = true; m_environmentClass = value; } /** * <p>The environment class you want to use for your environment. The environment * class determines the size of the containers and database used for your Apache * Airflow services.</p> */ inline void SetEnvironmentClass(Aws::String&& value) { m_environmentClassHasBeenSet = true; m_environmentClass = std::move(value); } /** * <p>The environment class you want to use for your environment. The environment * class determines the size of the containers and database used for your Apache * Airflow services.</p> */ inline void SetEnvironmentClass(const char* value) { m_environmentClassHasBeenSet = true; m_environmentClass.assign(value); } /** * <p>The environment class you want to use for your environment. The environment * class determines the size of the containers and database used for your Apache * Airflow services.</p> */ inline CreateEnvironmentRequest& WithEnvironmentClass(const Aws::String& value) { SetEnvironmentClass(value); return *this;} /** * <p>The environment class you want to use for your environment. The environment * class determines the size of the containers and database used for your Apache * Airflow services.</p> */ inline CreateEnvironmentRequest& WithEnvironmentClass(Aws::String&& value) { SetEnvironmentClass(std::move(value)); return *this;} /** * <p>The environment class you want to use for your environment. The environment * class determines the size of the containers and database used for your Apache * Airflow services.</p> */ inline CreateEnvironmentRequest& WithEnvironmentClass(const char* value) { SetEnvironmentClass(value); return *this;} /** * <p>The Amazon Resource Name (ARN) of the execution role for your environment. An * execution role is an AWS Identity and Access Management (IAM) role that grants * MWAA permission to access AWS services and resources used by your environment. * For example, <code>arn:aws:iam::123456789:role/my-execution-role</code>. For * more information, see <a * href="https://docs.aws.amazon.com/mwaa/latest/userguide/manage-access.html">Managing * access to Amazon Managed Workflows for Apache Airflow</a>.</p> */ inline const Aws::String& GetExecutionRoleArn() const{ return m_executionRoleArn; } /** * <p>The Amazon Resource Name (ARN) of the execution role for your environment. An * execution role is an AWS Identity and Access Management (IAM) role that grants * MWAA permission to access AWS services and resources used by your environment. * For example, <code>arn:aws:iam::123456789:role/my-execution-role</code>. For * more information, see <a * href="https://docs.aws.amazon.com/mwaa/latest/userguide/manage-access.html">Managing * access to Amazon Managed Workflows for Apache Airflow</a>.</p> */ inline bool ExecutionRoleArnHasBeenSet() const { return m_executionRoleArnHasBeenSet; } /** * <p>The Amazon Resource Name (ARN) of the execution role for your environment. An * execution role is an AWS Identity and Access Management (IAM) role that grants * MWAA permission to access AWS services and resources used by your environment. * For example, <code>arn:aws:iam::123456789:role/my-execution-role</code>. For * more information, see <a * href="https://docs.aws.amazon.com/mwaa/latest/userguide/manage-access.html">Managing * access to Amazon Managed Workflows for Apache Airflow</a>.</p> */ inline void SetExecutionRoleArn(const Aws::String& value) { m_executionRoleArnHasBeenSet = true; m_executionRoleArn = value; } /** * <p>The Amazon Resource Name (ARN) of the execution role for your environment. An * execution role is an AWS Identity and Access Management (IAM) role that grants * MWAA permission to access AWS services and resources used by your environment. * For example, <code>arn:aws:iam::123456789:role/my-execution-role</code>. For * more information, see <a * href="https://docs.aws.amazon.com/mwaa/latest/userguide/manage-access.html">Managing * access to Amazon Managed Workflows for Apache Airflow</a>.</p> */ inline void SetExecutionRoleArn(Aws::String&& value) { m_executionRoleArnHasBeenSet = true; m_executionRoleArn = std::move(value); } /** * <p>The Amazon Resource Name (ARN) of the execution role for your environment. An * execution role is an AWS Identity and Access Management (IAM) role that grants * MWAA permission to access AWS services and resources used by your environment. * For example, <code>arn:aws:iam::123456789:role/my-execution-role</code>. For * more information, see <a * href="https://docs.aws.amazon.com/mwaa/latest/userguide/manage-access.html">Managing * access to Amazon Managed Workflows for Apache Airflow</a>.</p> */ inline void SetExecutionRoleArn(const char* value) { m_executionRoleArnHasBeenSet = true; m_executionRoleArn.assign(value); } /** * <p>The Amazon Resource Name (ARN) of the execution role for your environment. An * execution role is an AWS Identity and Access Management (IAM) role that grants * MWAA permission to access AWS services and resources used by your environment. * For example, <code>arn:aws:iam::123456789:role/my-execution-role</code>. For * more information, see <a * href="https://docs.aws.amazon.com/mwaa/latest/userguide/manage-access.html">Managing * access to Amazon Managed Workflows for Apache Airflow</a>.</p> */ inline CreateEnvironmentRequest& WithExecutionRoleArn(const Aws::String& value) { SetExecutionRoleArn(value); return *this;} /** * <p>The Amazon Resource Name (ARN) of the execution role for your environment. An * execution role is an AWS Identity and Access Management (IAM) role that grants * MWAA permission to access AWS services and resources used by your environment. * For example, <code>arn:aws:iam::123456789:role/my-execution-role</code>. For * more information, see <a * href="https://docs.aws.amazon.com/mwaa/latest/userguide/manage-access.html">Managing * access to Amazon Managed Workflows for Apache Airflow</a>.</p> */ inline CreateEnvironmentRequest& WithExecutionRoleArn(Aws::String&& value) { SetExecutionRoleArn(std::move(value)); return *this;} /** * <p>The Amazon Resource Name (ARN) of the execution role for your environment. An * execution role is an AWS Identity and Access Management (IAM) role that grants * MWAA permission to access AWS services and resources used by your environment. * For example, <code>arn:aws:iam::123456789:role/my-execution-role</code>. For * more information, see <a * href="https://docs.aws.amazon.com/mwaa/latest/userguide/manage-access.html">Managing * access to Amazon Managed Workflows for Apache Airflow</a>.</p> */ inline CreateEnvironmentRequest& WithExecutionRoleArn(const char* value) { SetExecutionRoleArn(value); return *this;} /** * <p>The AWS Key Management Service (KMS) key to encrypt and decrypt the data in * your environment. You can use an AWS KMS key managed by MWAA, or a custom KMS * key (advanced). For more information, see <a * href="https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html?icmpid=docs_console_unmapped#master_keys">Customer * master keys (CMKs)</a> in the AWS KMS developer guide.</p> */ inline const Aws::String& GetKmsKey() const{ return m_kmsKey; } /** * <p>The AWS Key Management Service (KMS) key to encrypt and decrypt the data in * your environment. You can use an AWS KMS key managed by MWAA, or a custom KMS * key (advanced). For more information, see <a * href="https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html?icmpid=docs_console_unmapped#master_keys">Customer * master keys (CMKs)</a> in the AWS KMS developer guide.</p> */ inline bool KmsKeyHasBeenSet() const { return m_kmsKeyHasBeenSet; } /** * <p>The AWS Key Management Service (KMS) key to encrypt and decrypt the data in * your environment. You can use an AWS KMS key managed by MWAA, or a custom KMS * key (advanced). For more information, see <a * href="https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html?icmpid=docs_console_unmapped#master_keys">Customer * master keys (CMKs)</a> in the AWS KMS developer guide.</p> */ inline void SetKmsKey(const Aws::String& value) { m_kmsKeyHasBeenSet = true; m_kmsKey = value; } /** * <p>The AWS Key Management Service (KMS) key to encrypt and decrypt the data in * your environment. You can use an AWS KMS key managed by MWAA, or a custom KMS * key (advanced). For more information, see <a * href="https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html?icmpid=docs_console_unmapped#master_keys">Customer * master keys (CMKs)</a> in the AWS KMS developer guide.</p> */ inline void SetKmsKey(Aws::String&& value) { m_kmsKeyHasBeenSet = true; m_kmsKey = std::move(value); } /** * <p>The AWS Key Management Service (KMS) key to encrypt and decrypt the data in * your environment. You can use an AWS KMS key managed by MWAA, or a custom KMS * key (advanced). For more information, see <a * href="https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html?icmpid=docs_console_unmapped#master_keys">Customer * master keys (CMKs)</a> in the AWS KMS developer guide.</p> */ inline void SetKmsKey(const char* value) { m_kmsKeyHasBeenSet = true; m_kmsKey.assign(value); } /** * <p>The AWS Key Management Service (KMS) key to encrypt and decrypt the data in * your environment. You can use an AWS KMS key managed by MWAA, or a custom KMS * key (advanced). For more information, see <a * href="https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html?icmpid=docs_console_unmapped#master_keys">Customer * master keys (CMKs)</a> in the AWS KMS developer guide.</p> */ inline CreateEnvironmentRequest& WithKmsKey(const Aws::String& value) { SetKmsKey(value); return *this;} /** * <p>The AWS Key Management Service (KMS) key to encrypt and decrypt the data in * your environment. You can use an AWS KMS key managed by MWAA, or a custom KMS * key (advanced). For more information, see <a * href="https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html?icmpid=docs_console_unmapped#master_keys">Customer * master keys (CMKs)</a> in the AWS KMS developer guide.</p> */ inline CreateEnvironmentRequest& WithKmsKey(Aws::String&& value) { SetKmsKey(std::move(value)); return *this;} /** * <p>The AWS Key Management Service (KMS) key to encrypt and decrypt the data in * your environment. You can use an AWS KMS key managed by MWAA, or a custom KMS * key (advanced). For more information, see <a * href="https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html?icmpid=docs_console_unmapped#master_keys">Customer * master keys (CMKs)</a> in the AWS KMS developer guide.</p> */ inline CreateEnvironmentRequest& WithKmsKey(const char* value) { SetKmsKey(value); return *this;} /** * <p>The Apache Airflow logs you want to send to Amazon CloudWatch Logs.</p> */ inline const LoggingConfigurationInput& GetLoggingConfiguration() const{ return m_loggingConfiguration; } /** * <p>The Apache Airflow logs you want to send to Amazon CloudWatch Logs.</p> */ inline bool LoggingConfigurationHasBeenSet() const { return m_loggingConfigurationHasBeenSet; } /** * <p>The Apache Airflow logs you want to send to Amazon CloudWatch Logs.</p> */ inline void SetLoggingConfiguration(const LoggingConfigurationInput& value) { m_loggingConfigurationHasBeenSet = true; m_loggingConfiguration = value; } /** * <p>The Apache Airflow logs you want to send to Amazon CloudWatch Logs.</p> */ inline void SetLoggingConfiguration(LoggingConfigurationInput&& value) { m_loggingConfigurationHasBeenSet = true; m_loggingConfiguration = std::move(value); } /** * <p>The Apache Airflow logs you want to send to Amazon CloudWatch Logs.</p> */ inline CreateEnvironmentRequest& WithLoggingConfiguration(const LoggingConfigurationInput& value) { SetLoggingConfiguration(value); return *this;} /** * <p>The Apache Airflow logs you want to send to Amazon CloudWatch Logs.</p> */ inline CreateEnvironmentRequest& WithLoggingConfiguration(LoggingConfigurationInput&& value) { SetLoggingConfiguration(std::move(value)); return *this;} /** * <p>The maximum number of workers that you want to run in your environment. MWAA * scales the number of Apache Airflow workers and the Fargate containers that run * your tasks up to the number you specify in this field. When there are no more * tasks running, and no more in the queue, MWAA disposes of the extra containers * leaving the one worker that is included with your environment.</p> */ inline int GetMaxWorkers() const{ return m_maxWorkers; } /** * <p>The maximum number of workers that you want to run in your environment. MWAA * scales the number of Apache Airflow workers and the Fargate containers that run * your tasks up to the number you specify in this field. When there are no more * tasks running, and no more in the queue, MWAA disposes of the extra containers * leaving the one worker that is included with your environment.</p> */ inline bool MaxWorkersHasBeenSet() const { return m_maxWorkersHasBeenSet; } /** * <p>The maximum number of workers that you want to run in your environment. MWAA * scales the number of Apache Airflow workers and the Fargate containers that run * your tasks up to the number you specify in this field. When there are no more * tasks running, and no more in the queue, MWAA disposes of the extra containers * leaving the one worker that is included with your environment.</p> */ inline void SetMaxWorkers(int value) { m_maxWorkersHasBeenSet = true; m_maxWorkers = value; } /** * <p>The maximum number of workers that you want to run in your environment. MWAA * scales the number of Apache Airflow workers and the Fargate containers that run * your tasks up to the number you specify in this field. When there are no more * tasks running, and no more in the queue, MWAA disposes of the extra containers * leaving the one worker that is included with your environment.</p> */ inline CreateEnvironmentRequest& WithMaxWorkers(int value) { SetMaxWorkers(value); return *this;} /** * <p>The name of your MWAA environment.</p> */ inline const Aws::String& GetName() const{ return m_name; } /** * <p>The name of your MWAA environment.</p> */ inline bool NameHasBeenSet() const { return m_nameHasBeenSet; } /** * <p>The name of your MWAA environment.</p> */ inline void SetName(const Aws::String& value) { m_nameHasBeenSet = true; m_name = value; } /** * <p>The name of your MWAA environment.</p> */ inline void SetName(Aws::String&& value) { m_nameHasBeenSet = true; m_name = std::move(value); } /** * <p>The name of your MWAA environment.</p> */ inline void SetName(const char* value) { m_nameHasBeenSet = true; m_name.assign(value); } /** * <p>The name of your MWAA environment.</p> */ inline CreateEnvironmentRequest& WithName(const Aws::String& value) { SetName(value); return *this;} /** * <p>The name of your MWAA environment.</p> */ inline CreateEnvironmentRequest& WithName(Aws::String&& value) { SetName(std::move(value)); return *this;} /** * <p>The name of your MWAA environment.</p> */ inline CreateEnvironmentRequest& WithName(const char* value) { SetName(value); return *this;} /** * <p>The VPC networking components you want to use for your environment. At least * two private subnet identifiers and one VPC security group identifier are * required to create an environment. For more information, see <a * href="https://docs.aws.amazon.com/mwaa/latest/userguide/vpc-mwaa.html">Creating * the VPC network for a MWAA environment</a>.</p> */ inline const NetworkConfiguration& GetNetworkConfiguration() const{ return m_networkConfiguration; } /** * <p>The VPC networking components you want to use for your environment. At least * two private subnet identifiers and one VPC security group identifier are * required to create an environment. For more information, see <a * href="https://docs.aws.amazon.com/mwaa/latest/userguide/vpc-mwaa.html">Creating * the VPC network for a MWAA environment</a>.</p> */ inline bool NetworkConfigurationHasBeenSet() const { return m_networkConfigurationHasBeenSet; } /** * <p>The VPC networking components you want to use for your environment. At least * two private subnet identifiers and one VPC security group identifier are * required to create an environment. For more information, see <a * href="https://docs.aws.amazon.com/mwaa/latest/userguide/vpc-mwaa.html">Creating * the VPC network for a MWAA environment</a>.</p> */ inline void SetNetworkConfiguration(const NetworkConfiguration& value) { m_networkConfigurationHasBeenSet = true; m_networkConfiguration = value; } /** * <p>The VPC networking components you want to use for your environment. At least * two private subnet identifiers and one VPC security group identifier are * required to create an environment. For more information, see <a * href="https://docs.aws.amazon.com/mwaa/latest/userguide/vpc-mwaa.html">Creating * the VPC network for a MWAA environment</a>.</p> */ inline void SetNetworkConfiguration(NetworkConfiguration&& value) { m_networkConfigurationHasBeenSet = true; m_networkConfiguration = std::move(value); } /** * <p>The VPC networking components you want to use for your environment. At least * two private subnet identifiers and one VPC security group identifier are * required to create an environment. For more information, see <a * href="https://docs.aws.amazon.com/mwaa/latest/userguide/vpc-mwaa.html">Creating * the VPC network for a MWAA environment</a>.</p> */ inline CreateEnvironmentRequest& WithNetworkConfiguration(const NetworkConfiguration& value) { SetNetworkConfiguration(value); return *this;} /** * <p>The VPC networking components you want to use for your environment. At least * two private subnet identifiers and one VPC security group identifier are * required to create an environment. For more information, see <a * href="https://docs.aws.amazon.com/mwaa/latest/userguide/vpc-mwaa.html">Creating * the VPC network for a MWAA environment</a>.</p> */ inline CreateEnvironmentRequest& WithNetworkConfiguration(NetworkConfiguration&& value) { SetNetworkConfiguration(std::move(value)); return *this;} /** * <p>The <code>plugins.zip</code> file version you want to use.</p> */ inline const Aws::String& GetPluginsS3ObjectVersion() const{ return m_pluginsS3ObjectVersion; } /** * <p>The <code>plugins.zip</code> file version you want to use.</p> */ inline bool PluginsS3ObjectVersionHasBeenSet() const { return m_pluginsS3ObjectVersionHasBeenSet; } /** * <p>The <code>plugins.zip</code> file version you want to use.</p> */ inline void SetPluginsS3ObjectVersion(const Aws::String& value) { m_pluginsS3ObjectVersionHasBeenSet = true; m_pluginsS3ObjectVersion = value; } /** * <p>The <code>plugins.zip</code> file version you want to use.</p> */ inline void SetPluginsS3ObjectVersion(Aws::String&& value) { m_pluginsS3ObjectVersionHasBeenSet = true; m_pluginsS3ObjectVersion = std::move(value); } /** * <p>The <code>plugins.zip</code> file version you want to use.</p> */ inline void SetPluginsS3ObjectVersion(const char* value) { m_pluginsS3ObjectVersionHasBeenSet = true; m_pluginsS3ObjectVersion.assign(value); } /** * <p>The <code>plugins.zip</code> file version you want to use.</p> */ inline CreateEnvironmentRequest& WithPluginsS3ObjectVersion(const Aws::String& value) { SetPluginsS3ObjectVersion(value); return *this;} /** * <p>The <code>plugins.zip</code> file version you want to use.</p> */ inline CreateEnvironmentRequest& WithPluginsS3ObjectVersion(Aws::String&& value) { SetPluginsS3ObjectVersion(std::move(value)); return *this;} /** * <p>The <code>plugins.zip</code> file version you want to use.</p> */ inline CreateEnvironmentRequest& WithPluginsS3ObjectVersion(const char* value) { SetPluginsS3ObjectVersion(value); return *this;} /** * <p>The relative path to the <code>plugins.zip</code> file on your Amazon S3 * storage bucket. For example, <code>plugins.zip</code>. If a relative path is * provided in the request, then <code>PluginsS3ObjectVersion</code> is required. * For more information, see <a * href="https://docs.aws.amazon.com/mwaa/latest/userguide/configuring-dag-import.html">Importing * DAGs on Amazon MWAA</a>.</p> */ inline const Aws::String& GetPluginsS3Path() const{ return m_pluginsS3Path; } /** * <p>The relative path to the <code>plugins.zip</code> file on your Amazon S3 * storage bucket. For example, <code>plugins.zip</code>. If a relative path is * provided in the request, then <code>PluginsS3ObjectVersion</code> is required. * For more information, see <a * href="https://docs.aws.amazon.com/mwaa/latest/userguide/configuring-dag-import.html">Importing * DAGs on Amazon MWAA</a>.</p> */ inline bool PluginsS3PathHasBeenSet() const { return m_pluginsS3PathHasBeenSet; } /** * <p>The relative path to the <code>plugins.zip</code> file on your Amazon S3 * storage bucket. For example, <code>plugins.zip</code>. If a relative path is * provided in the request, then <code>PluginsS3ObjectVersion</code> is required. * For more information, see <a * href="https://docs.aws.amazon.com/mwaa/latest/userguide/configuring-dag-import.html">Importing * DAGs on Amazon MWAA</a>.</p> */ inline void SetPluginsS3Path(const Aws::String& value) { m_pluginsS3PathHasBeenSet = true; m_pluginsS3Path = value; } /** * <p>The relative path to the <code>plugins.zip</code> file on your Amazon S3 * storage bucket. For example, <code>plugins.zip</code>. If a relative path is * provided in the request, then <code>PluginsS3ObjectVersion</code> is required. * For more information, see <a * href="https://docs.aws.amazon.com/mwaa/latest/userguide/configuring-dag-import.html">Importing * DAGs on Amazon MWAA</a>.</p> */ inline void SetPluginsS3Path(Aws::String&& value) { m_pluginsS3PathHasBeenSet = true; m_pluginsS3Path = std::move(value); } /** * <p>The relative path to the <code>plugins.zip</code> file on your Amazon S3 * storage bucket. For example, <code>plugins.zip</code>. If a relative path is * provided in the request, then <code>PluginsS3ObjectVersion</code> is required. * For more information, see <a * href="https://docs.aws.amazon.com/mwaa/latest/userguide/configuring-dag-import.html">Importing * DAGs on Amazon MWAA</a>.</p> */ inline void SetPluginsS3Path(const char* value) { m_pluginsS3PathHasBeenSet = true; m_pluginsS3Path.assign(value); } /** * <p>The relative path to the <code>plugins.zip</code> file on your Amazon S3 * storage bucket. For example, <code>plugins.zip</code>. If a relative path is * provided in the request, then <code>PluginsS3ObjectVersion</code> is required. * For more information, see <a * href="https://docs.aws.amazon.com/mwaa/latest/userguide/configuring-dag-import.html">Importing * DAGs on Amazon MWAA</a>.</p> */ inline CreateEnvironmentRequest& WithPluginsS3Path(const Aws::String& value) { SetPluginsS3Path(value); return *this;} /** * <p>The relative path to the <code>plugins.zip</code> file on your Amazon S3 * storage bucket. For example, <code>plugins.zip</code>. If a relative path is * provided in the request, then <code>PluginsS3ObjectVersion</code> is required. * For more information, see <a * href="https://docs.aws.amazon.com/mwaa/latest/userguide/configuring-dag-import.html">Importing * DAGs on Amazon MWAA</a>.</p> */ inline CreateEnvironmentRequest& WithPluginsS3Path(Aws::String&& value) { SetPluginsS3Path(std::move(value)); return *this;} /** * <p>The relative path to the <code>plugins.zip</code> file on your Amazon S3 * storage bucket. For example, <code>plugins.zip</code>. If a relative path is * provided in the request, then <code>PluginsS3ObjectVersion</code> is required. * For more information, see <a * href="https://docs.aws.amazon.com/mwaa/latest/userguide/configuring-dag-import.html">Importing * DAGs on Amazon MWAA</a>.</p> */ inline CreateEnvironmentRequest& WithPluginsS3Path(const char* value) { SetPluginsS3Path(value); return *this;} /** * <p>The <code>requirements.txt</code> file version you want to use.</p> */ inline const Aws::String& GetRequirementsS3ObjectVersion() const{ return m_requirementsS3ObjectVersion; } /** * <p>The <code>requirements.txt</code> file version you want to use.</p> */ inline bool RequirementsS3ObjectVersionHasBeenSet() const { return m_requirementsS3ObjectVersionHasBeenSet; } /** * <p>The <code>requirements.txt</code> file version you want to use.</p> */ inline void SetRequirementsS3ObjectVersion(const Aws::String& value) { m_requirementsS3ObjectVersionHasBeenSet = true; m_requirementsS3ObjectVersion = value; } /** * <p>The <code>requirements.txt</code> file version you want to use.</p> */ inline void SetRequirementsS3ObjectVersion(Aws::String&& value) { m_requirementsS3ObjectVersionHasBeenSet = true; m_requirementsS3ObjectVersion = std::move(value); } /** * <p>The <code>requirements.txt</code> file version you want to use.</p> */ inline void SetRequirementsS3ObjectVersion(const char* value) { m_requirementsS3ObjectVersionHasBeenSet = true; m_requirementsS3ObjectVersion.assign(value); } /** * <p>The <code>requirements.txt</code> file version you want to use.</p> */ inline CreateEnvironmentRequest& WithRequirementsS3ObjectVersion(const Aws::String& value) { SetRequirementsS3ObjectVersion(value); return *this;} /** * <p>The <code>requirements.txt</code> file version you want to use.</p> */ inline CreateEnvironmentRequest& WithRequirementsS3ObjectVersion(Aws::String&& value) { SetRequirementsS3ObjectVersion(std::move(value)); return *this;} /** * <p>The <code>requirements.txt</code> file version you want to use.</p> */ inline CreateEnvironmentRequest& WithRequirementsS3ObjectVersion(const char* value) { SetRequirementsS3ObjectVersion(value); return *this;} /** * <p>The relative path to the <code>requirements.txt</code> file on your Amazon S3 * storage bucket. For example, <code>requirements.txt</code>. If a relative path * is provided in the request, then <code>RequirementsS3ObjectVersion</code> is * required. For more information, see <a * href="https://docs.aws.amazon.com/mwaa/latest/userguide/configuring-dag-import.html">Importing * DAGs on Amazon MWAA</a>.</p> */ inline const Aws::String& GetRequirementsS3Path() const{ return m_requirementsS3Path; } /** * <p>The relative path to the <code>requirements.txt</code> file on your Amazon S3 * storage bucket. For example, <code>requirements.txt</code>. If a relative path * is provided in the request, then <code>RequirementsS3ObjectVersion</code> is * required. For more information, see <a * href="https://docs.aws.amazon.com/mwaa/latest/userguide/configuring-dag-import.html">Importing * DAGs on Amazon MWAA</a>.</p> */ inline bool RequirementsS3PathHasBeenSet() const { return m_requirementsS3PathHasBeenSet; } /** * <p>The relative path to the <code>requirements.txt</code> file on your Amazon S3 * storage bucket. For example, <code>requirements.txt</code>. If a relative path * is provided in the request, then <code>RequirementsS3ObjectVersion</code> is * required. For more information, see <a * href="https://docs.aws.amazon.com/mwaa/latest/userguide/configuring-dag-import.html">Importing * DAGs on Amazon MWAA</a>.</p> */ inline void SetRequirementsS3Path(const Aws::String& value) { m_requirementsS3PathHasBeenSet = true; m_requirementsS3Path = value; } /** * <p>The relative path to the <code>requirements.txt</code> file on your Amazon S3 * storage bucket. For example, <code>requirements.txt</code>. If a relative path * is provided in the request, then <code>RequirementsS3ObjectVersion</code> is * required. For more information, see <a * href="https://docs.aws.amazon.com/mwaa/latest/userguide/configuring-dag-import.html">Importing * DAGs on Amazon MWAA</a>.</p> */ inline void SetRequirementsS3Path(Aws::String&& value) { m_requirementsS3PathHasBeenSet = true; m_requirementsS3Path = std::move(value); } /** * <p>The relative path to the <code>requirements.txt</code> file on your Amazon S3 * storage bucket. For example, <code>requirements.txt</code>. If a relative path * is provided in the request, then <code>RequirementsS3ObjectVersion</code> is * required. For more information, see <a * href="https://docs.aws.amazon.com/mwaa/latest/userguide/configuring-dag-import.html">Importing * DAGs on Amazon MWAA</a>.</p> */ inline void SetRequirementsS3Path(const char* value) { m_requirementsS3PathHasBeenSet = true; m_requirementsS3Path.assign(value); } /** * <p>The relative path to the <code>requirements.txt</code> file on your Amazon S3 * storage bucket. For example, <code>requirements.txt</code>. If a relative path * is provided in the request, then <code>RequirementsS3ObjectVersion</code> is * required. For more information, see <a * href="https://docs.aws.amazon.com/mwaa/latest/userguide/configuring-dag-import.html">Importing * DAGs on Amazon MWAA</a>.</p> */ inline CreateEnvironmentRequest& WithRequirementsS3Path(const Aws::String& value) { SetRequirementsS3Path(value); return *this;} /** * <p>The relative path to the <code>requirements.txt</code> file on your Amazon S3 * storage bucket. For example, <code>requirements.txt</code>. If a relative path * is provided in the request, then <code>RequirementsS3ObjectVersion</code> is * required. For more information, see <a * href="https://docs.aws.amazon.com/mwaa/latest/userguide/configuring-dag-import.html">Importing * DAGs on Amazon MWAA</a>.</p> */ inline CreateEnvironmentRequest& WithRequirementsS3Path(Aws::String&& value) { SetRequirementsS3Path(std::move(value)); return *this;} /** * <p>The relative path to the <code>requirements.txt</code> file on your Amazon S3 * storage bucket. For example, <code>requirements.txt</code>. If a relative path * is provided in the request, then <code>RequirementsS3ObjectVersion</code> is * required. For more information, see <a * href="https://docs.aws.amazon.com/mwaa/latest/userguide/configuring-dag-import.html">Importing * DAGs on Amazon MWAA</a>.</p> */ inline CreateEnvironmentRequest& WithRequirementsS3Path(const char* value) { SetRequirementsS3Path(value); return *this;} /** * <p>The Amazon Resource Name (ARN) of your Amazon S3 storage bucket. For example, * <code>arn:aws:s3:::airflow-mybucketname</code>.</p> */ inline const Aws::String& GetSourceBucketArn() const{ return m_sourceBucketArn; } /** * <p>The Amazon Resource Name (ARN) of your Amazon S3 storage bucket. For example, * <code>arn:aws:s3:::airflow-mybucketname</code>.</p> */ inline bool SourceBucketArnHasBeenSet() const { return m_sourceBucketArnHasBeenSet; } /** * <p>The Amazon Resource Name (ARN) of your Amazon S3 storage bucket. For example, * <code>arn:aws:s3:::airflow-mybucketname</code>.</p> */ inline void SetSourceBucketArn(const Aws::String& value) { m_sourceBucketArnHasBeenSet = true; m_sourceBucketArn = value; } /** * <p>The Amazon Resource Name (ARN) of your Amazon S3 storage bucket. For example, * <code>arn:aws:s3:::airflow-mybucketname</code>.</p> */ inline void SetSourceBucketArn(Aws::String&& value) { m_sourceBucketArnHasBeenSet = true; m_sourceBucketArn = std::move(value); } /** * <p>The Amazon Resource Name (ARN) of your Amazon S3 storage bucket. For example, * <code>arn:aws:s3:::airflow-mybucketname</code>.</p> */ inline void SetSourceBucketArn(const char* value) { m_sourceBucketArnHasBeenSet = true; m_sourceBucketArn.assign(value); } /** * <p>The Amazon Resource Name (ARN) of your Amazon S3 storage bucket. For example, * <code>arn:aws:s3:::airflow-mybucketname</code>.</p> */ inline CreateEnvironmentRequest& WithSourceBucketArn(const Aws::String& value) { SetSourceBucketArn(value); return *this;} /** * <p>The Amazon Resource Name (ARN) of your Amazon S3 storage bucket. For example, * <code>arn:aws:s3:::airflow-mybucketname</code>.</p> */ inline CreateEnvironmentRequest& WithSourceBucketArn(Aws::String&& value) { SetSourceBucketArn(std::move(value)); return *this;} /** * <p>The Amazon Resource Name (ARN) of your Amazon S3 storage bucket. For example, * <code>arn:aws:s3:::airflow-mybucketname</code>.</p> */ inline CreateEnvironmentRequest& WithSourceBucketArn(const char* value) { SetSourceBucketArn(value); return *this;} /** * <p>The metadata tags you want to attach to your environment. For more * information, see <a * href="https://docs.aws.amazon.com/general/latest/gr/aws_tagging.html">Tagging * AWS resources</a>.</p> */ inline const Aws::Map<Aws::String, Aws::String>& GetTags() const{ return m_tags; } /** * <p>The metadata tags you want to attach to your environment. For more * information, see <a * href="https://docs.aws.amazon.com/general/latest/gr/aws_tagging.html">Tagging * AWS resources</a>.</p> */ inline bool TagsHasBeenSet() const { return m_tagsHasBeenSet; } /** * <p>The metadata tags you want to attach to your environment. For more * information, see <a * href="https://docs.aws.amazon.com/general/latest/gr/aws_tagging.html">Tagging * AWS resources</a>.</p> */ inline void SetTags(const Aws::Map<Aws::String, Aws::String>& value) { m_tagsHasBeenSet = true; m_tags = value; } /** * <p>The metadata tags you want to attach to your environment. For more * information, see <a * href="https://docs.aws.amazon.com/general/latest/gr/aws_tagging.html">Tagging * AWS resources</a>.</p> */ inline void SetTags(Aws::Map<Aws::String, Aws::String>&& value) { m_tagsHasBeenSet = true; m_tags = std::move(value); } /** * <p>The metadata tags you want to attach to your environment. For more * information, see <a * href="https://docs.aws.amazon.com/general/latest/gr/aws_tagging.html">Tagging * AWS resources</a>.</p> */ inline CreateEnvironmentRequest& WithTags(const Aws::Map<Aws::String, Aws::String>& value) { SetTags(value); return *this;} /** * <p>The metadata tags you want to attach to your environment. For more * information, see <a * href="https://docs.aws.amazon.com/general/latest/gr/aws_tagging.html">Tagging * AWS resources</a>.</p> */ inline CreateEnvironmentRequest& WithTags(Aws::Map<Aws::String, Aws::String>&& value) { SetTags(std::move(value)); return *this;} /** * <p>The metadata tags you want to attach to your environment. For more * information, see <a * href="https://docs.aws.amazon.com/general/latest/gr/aws_tagging.html">Tagging * AWS resources</a>.</p> */ inline CreateEnvironmentRequest& AddTags(const Aws::String& key, const Aws::String& value) { m_tagsHasBeenSet = true; m_tags.emplace(key, value); return *this; } /** * <p>The metadata tags you want to attach to your environment. For more * information, see <a * href="https://docs.aws.amazon.com/general/latest/gr/aws_tagging.html">Tagging * AWS resources</a>.</p> */ inline CreateEnvironmentRequest& AddTags(Aws::String&& key, const Aws::String& value) { m_tagsHasBeenSet = true; m_tags.emplace(std::move(key), value); return *this; } /** * <p>The metadata tags you want to attach to your environment. For more * information, see <a * href="https://docs.aws.amazon.com/general/latest/gr/aws_tagging.html">Tagging * AWS resources</a>.</p> */ inline CreateEnvironmentRequest& AddTags(const Aws::String& key, Aws::String&& value) { m_tagsHasBeenSet = true; m_tags.emplace(key, std::move(value)); return *this; } /** * <p>The metadata tags you want to attach to your environment. For more * information, see <a * href="https://docs.aws.amazon.com/general/latest/gr/aws_tagging.html">Tagging * AWS resources</a>.</p> */ inline CreateEnvironmentRequest& AddTags(Aws::String&& key, Aws::String&& value) { m_tagsHasBeenSet = true; m_tags.emplace(std::move(key), std::move(value)); return *this; } /** * <p>The metadata tags you want to attach to your environment. For more * information, see <a * href="https://docs.aws.amazon.com/general/latest/gr/aws_tagging.html">Tagging * AWS resources</a>.</p> */ inline CreateEnvironmentRequest& AddTags(const char* key, Aws::String&& value) { m_tagsHasBeenSet = true; m_tags.emplace(key, std::move(value)); return *this; } /** * <p>The metadata tags you want to attach to your environment. For more * information, see <a * href="https://docs.aws.amazon.com/general/latest/gr/aws_tagging.html">Tagging * AWS resources</a>.</p> */ inline CreateEnvironmentRequest& AddTags(Aws::String&& key, const char* value) { m_tagsHasBeenSet = true; m_tags.emplace(std::move(key), value); return *this; } /** * <p>The metadata tags you want to attach to your environment. For more * information, see <a * href="https://docs.aws.amazon.com/general/latest/gr/aws_tagging.html">Tagging * AWS resources</a>.</p> */ inline CreateEnvironmentRequest& AddTags(const char* key, const char* value) { m_tagsHasBeenSet = true; m_tags.emplace(key, value); return *this; } /** * <p>The networking access of your Apache Airflow web server. A public network * allows your Airflow UI to be accessed over the Internet by users granted access * in your IAM policy. A private network limits access of your Airflow UI to users * within your VPC. For more information, see <a * href="https://docs.aws.amazon.com/mwaa/latest/userguide/vpc-mwaa.html">Creating * the VPC network for a MWAA environment</a>.</p> */ inline const WebserverAccessMode& GetWebserverAccessMode() const{ return m_webserverAccessMode; } /** * <p>The networking access of your Apache Airflow web server. A public network * allows your Airflow UI to be accessed over the Internet by users granted access * in your IAM policy. A private network limits access of your Airflow UI to users * within your VPC. For more information, see <a * href="https://docs.aws.amazon.com/mwaa/latest/userguide/vpc-mwaa.html">Creating * the VPC network for a MWAA environment</a>.</p> */ inline bool WebserverAccessModeHasBeenSet() const { return m_webserverAccessModeHasBeenSet; } /** * <p>The networking access of your Apache Airflow web server. A public network * allows your Airflow UI to be accessed over the Internet by users granted access * in your IAM policy. A private network limits access of your Airflow UI to users * within your VPC. For more information, see <a * href="https://docs.aws.amazon.com/mwaa/latest/userguide/vpc-mwaa.html">Creating * the VPC network for a MWAA environment</a>.</p> */ inline void SetWebserverAccessMode(const WebserverAccessMode& value) { m_webserverAccessModeHasBeenSet = true; m_webserverAccessMode = value; } /** * <p>The networking access of your Apache Airflow web server. A public network * allows your Airflow UI to be accessed over the Internet by users granted access * in your IAM policy. A private network limits access of your Airflow UI to users * within your VPC. For more information, see <a * href="https://docs.aws.amazon.com/mwaa/latest/userguide/vpc-mwaa.html">Creating * the VPC network for a MWAA environment</a>.</p> */ inline void SetWebserverAccessMode(WebserverAccessMode&& value) { m_webserverAccessModeHasBeenSet = true; m_webserverAccessMode = std::move(value); } /** * <p>The networking access of your Apache Airflow web server. A public network * allows your Airflow UI to be accessed over the Internet by users granted access * in your IAM policy. A private network limits access of your Airflow UI to users * within your VPC. For more information, see <a * href="https://docs.aws.amazon.com/mwaa/latest/userguide/vpc-mwaa.html">Creating * the VPC network for a MWAA environment</a>.</p> */ inline CreateEnvironmentRequest& WithWebserverAccessMode(const WebserverAccessMode& value) { SetWebserverAccessMode(value); return *this;} /** * <p>The networking access of your Apache Airflow web server. A public network * allows your Airflow UI to be accessed over the Internet by users granted access * in your IAM policy. A private network limits access of your Airflow UI to users * within your VPC. For more information, see <a * href="https://docs.aws.amazon.com/mwaa/latest/userguide/vpc-mwaa.html">Creating * the VPC network for a MWAA environment</a>.</p> */ inline CreateEnvironmentRequest& WithWebserverAccessMode(WebserverAccessMode&& value) { SetWebserverAccessMode(std::move(value)); return *this;} /** * <p>The day and time you want MWAA to start weekly maintenance updates on your * environment.</p> */ inline const Aws::String& GetWeeklyMaintenanceWindowStart() const{ return m_weeklyMaintenanceWindowStart; } /** * <p>The day and time you want MWAA to start weekly maintenance updates on your * environment.</p> */ inline bool WeeklyMaintenanceWindowStartHasBeenSet() const { return m_weeklyMaintenanceWindowStartHasBeenSet; } /** * <p>The day and time you want MWAA to start weekly maintenance updates on your * environment.</p> */ inline void SetWeeklyMaintenanceWindowStart(const Aws::String& value) { m_weeklyMaintenanceWindowStartHasBeenSet = true; m_weeklyMaintenanceWindowStart = value; } /** * <p>The day and time you want MWAA to start weekly maintenance updates on your * environment.</p> */ inline void SetWeeklyMaintenanceWindowStart(Aws::String&& value) { m_weeklyMaintenanceWindowStartHasBeenSet = true; m_weeklyMaintenanceWindowStart = std::move(value); } /** * <p>The day and time you want MWAA to start weekly maintenance updates on your * environment.</p> */ inline void SetWeeklyMaintenanceWindowStart(const char* value) { m_weeklyMaintenanceWindowStartHasBeenSet = true; m_weeklyMaintenanceWindowStart.assign(value); } /** * <p>The day and time you want MWAA to start weekly maintenance updates on your * environment.</p> */ inline CreateEnvironmentRequest& WithWeeklyMaintenanceWindowStart(const Aws::String& value) { SetWeeklyMaintenanceWindowStart(value); return *this;} /** * <p>The day and time you want MWAA to start weekly maintenance updates on your * environment.</p> */ inline CreateEnvironmentRequest& WithWeeklyMaintenanceWindowStart(Aws::String&& value) { SetWeeklyMaintenanceWindowStart(std::move(value)); return *this;} /** * <p>The day and time you want MWAA to start weekly maintenance updates on your * environment.</p> */ inline CreateEnvironmentRequest& WithWeeklyMaintenanceWindowStart(const char* value) { SetWeeklyMaintenanceWindowStart(value); return *this;} private: Aws::Map<Aws::String, Aws::String> m_airflowConfigurationOptions; bool m_airflowConfigurationOptionsHasBeenSet; Aws::String m_airflowVersion; bool m_airflowVersionHasBeenSet; Aws::String m_dagS3Path; bool m_dagS3PathHasBeenSet; Aws::String m_environmentClass; bool m_environmentClassHasBeenSet; Aws::String m_executionRoleArn; bool m_executionRoleArnHasBeenSet; Aws::String m_kmsKey; bool m_kmsKeyHasBeenSet; LoggingConfigurationInput m_loggingConfiguration; bool m_loggingConfigurationHasBeenSet; int m_maxWorkers; bool m_maxWorkersHasBeenSet; Aws::String m_name; bool m_nameHasBeenSet; NetworkConfiguration m_networkConfiguration; bool m_networkConfigurationHasBeenSet; Aws::String m_pluginsS3ObjectVersion; bool m_pluginsS3ObjectVersionHasBeenSet; Aws::String m_pluginsS3Path; bool m_pluginsS3PathHasBeenSet; Aws::String m_requirementsS3ObjectVersion; bool m_requirementsS3ObjectVersionHasBeenSet; Aws::String m_requirementsS3Path; bool m_requirementsS3PathHasBeenSet; Aws::String m_sourceBucketArn; bool m_sourceBucketArnHasBeenSet; Aws::Map<Aws::String, Aws::String> m_tags; bool m_tagsHasBeenSet; WebserverAccessMode m_webserverAccessMode; bool m_webserverAccessModeHasBeenSet; Aws::String m_weeklyMaintenanceWindowStart; bool m_weeklyMaintenanceWindowStartHasBeenSet; }; } // namespace Model } // namespace MWAA } // namespace Aws
jt70471/aws-sdk-cpp
aws-cpp-sdk-mwaa/include/aws/mwaa/model/CreateEnvironmentRequest.h
C
apache-2.0
60,613
# Puccinia isoglossae Doidge SPECIES #### Status ACCEPTED #### According to Index Fungorum #### Published in Bothalia 2(1a): 72 (1926) #### Original name Puccinia isoglossae Doidge ### Remarks null
mdoering/backbone
life/Fungi/Basidiomycota/Pucciniomycetes/Pucciniales/Pucciniaceae/Puccinia/Puccinia isoglossae/README.md
Markdown
apache-2.0
202
# Uromyces veratri f. adenostylis E. Fisch. FORM #### Status ACCEPTED #### According to Index Fungorum #### Published in null #### Original name Uromyces veratri f. adenostylis E. Fisch. ### Remarks null
mdoering/backbone
life/Fungi/Basidiomycota/Pucciniomycetes/Pucciniales/Pucciniaceae/Uromyces/Uromyces veratri/Uromyces veratri adenostylis/README.md
Markdown
apache-2.0
208
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated from a template. // // Manual changes to this file may cause unexpected behavior in your application. // Manual changes to this file will be overwritten if the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace Powerfront.Backend.EntityFramework { using System; using System.Collections.Generic; public partial class Type { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")] public Type() { this.CustomerRecords = new HashSet<CustomerRecord>(); } public string TypeId { get; set; } public string Name { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<CustomerRecord> CustomerRecords { get; set; } } }
systemsymbiosis/ASP-MVC-Demo
Powerfront.Backend/EntityFramework/Type.cs
C#
apache-2.0
1,112
/* * Copyright (c) 2012. Piraso Alvin R. de Leon. All Rights Reserved. * * See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The Piraso 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.piraso.server.sql; import org.piraso.server.AbstractContextLoggerBeanProcessor; import javax.sql.DataSource; /** * Create a bean post processor which ensures that any bean instance of type {@link DataSource} will * be wrap by a context logger aware instance. * */ public class SQLContextLoggerBeanPostProcessor extends AbstractContextLoggerBeanProcessor<DataSource> { public SQLContextLoggerBeanPostProcessor() { super(DataSource.class); } @Override public DataSource createProxy(DataSource o, String id) { return SQLContextLogger.create(o, id); } }
piraso/piraso-sql
context-logger/server/src/main/java/org/piraso/server/sql/SQLContextLoggerBeanPostProcessor.java
Java
apache-2.0
1,383
package org.lionsoul.jcseg.util; import java.io.Serializable; /** * string buffer class * * @author chenxin<[email protected]> */ public class IStringBuffer implements Serializable { private static final long serialVersionUID = 1L; /** * buffer char array. */ private char buff[]; private int count; /** * create a buffer with a default length 16 */ public IStringBuffer() { this(16); } /** * create a buffer with a specified length * * @param length */ public IStringBuffer( int length ) { if ( length <= 0 ) { throw new IllegalArgumentException("length <= 0"); } buff = new char[length]; count = 0; } /** * create a buffer with a specified string * * @param str */ public IStringBuffer( String str ) { this(str.length()+16); append(str); } /** * resize the buffer * this will have to copy the old chars from the old buffer to the new buffer * * @param length */ private void resizeTo( int length ) { if ( length <= 0 ) throw new IllegalArgumentException("length <= 0"); if ( length != buff.length ) { int len = ( length > buff.length ) ? buff.length : length; //System.out.println("resize:"+length); char[] obuff = buff; buff = new char[length]; /*for ( int j = 0; j < len; j++ ) { buff[j] = obuff[j]; }*/ System.arraycopy(obuff, 0, buff, 0, len); } } /** * append a string to the buffer * * @param str string to append to */ public IStringBuffer append( String str ) { if ( str == null ) throw new NullPointerException(); //check the necessary to resize the buffer. if ( count + str.length() > buff.length ) { resizeTo( (count + str.length()) * 2 + 1 ); } for ( int j = 0; j < str.length(); j++ ) { buff[count++] = str.charAt(j); } return this; } /** * append parts of the chars to the buffer * * @param chars * @param start the start index * @param length length of chars to append to */ public IStringBuffer append( char[] chars, int start, int length ) { if ( chars == null ) throw new NullPointerException(); if ( start < 0 ) throw new IndexOutOfBoundsException(); if ( length <= 0 ) throw new IndexOutOfBoundsException(); if ( start + length > chars.length ) throw new IndexOutOfBoundsException(); //check the necessary to resize the buffer. if ( count + length > buff.length ) { resizeTo( (count + length) * 2 + 1 ); } for ( int j = 0; j < length; j++ ) { buff[count++] = chars[start+j]; } return this; } /** * append the rest of the chars to the buffer * * @param chars * @param start the start index * @return IStringBuffer * */ public IStringBuffer append( char[] chars, int start ) { append(chars, start, chars.length - start); return this; } /** * append some chars to the buffer * * @param chars */ public IStringBuffer append( char[] chars ) { return append(chars, 0, chars.length); } /** * append a char to the buffer * * @param c the char to append to */ public IStringBuffer append( char c ) { if ( count == buff.length ) { resizeTo( buff.length * 2 + 1 ); } buff[count++] = c; return this; } /** * append a boolean value * * @param bool */ public IStringBuffer append(boolean bool) { String str = bool ? "true" : "false"; return append(str); } /** * append a short value * * @param shortv */ public IStringBuffer append(short shortv) { return append(String.valueOf(shortv)); } /** * append a int value * * @param intv */ public IStringBuffer append(int intv) { return append(String.valueOf(intv)); } /** * append a long value * * @param longv */ public IStringBuffer append(long longv) { return append(String.valueOf(longv)); } /** * append a float value * * @param floatv */ public IStringBuffer append(float floatv) { return append(String.valueOf(floatv)); } /** * append a double value * * @param doublev */ public IStringBuffer append(double doublev) { return append(String.valueOf(doublev)); } /** * return the length of the buffer * * @return int the length of the buffer */ public int length() { return count; } /** * set the length of the buffer * actually it just override the count and the actual buffer * has nothing changed * * @param length */ public int setLength(int length) { int oldCount = count; count = length; return oldCount; } /** * get the char at a specified position in the buffer */ public char charAt( int idx ) { if ( idx < 0 ) throw new IndexOutOfBoundsException("idx{"+idx+"} < 0"); if ( idx >= count ) throw new IndexOutOfBoundsException("idx{"+idx+"} >= buffer.length"); return buff[idx]; } /** * always return the last char * * @return char */ public char last() { if ( count == 0 ) { throw new IndexOutOfBoundsException("Empty buffer"); } return buff[count-1]; } /** * always return the first char * * @return char */ public char first() { if ( count == 0 ) { throw new IndexOutOfBoundsException("Empty buffer"); } return buff[0]; } /** * delete the char at the specified position */ public IStringBuffer deleteCharAt( int idx ) { if ( idx < 0 ) throw new IndexOutOfBoundsException("idx < 0"); if ( idx >= count ) throw new IndexOutOfBoundsException("idx >= buffer.length"); //here we got a bug for j < count //change over it to count - 1 //thanks for the feedback of [email protected] //@date 2013-08-22 for ( int j = idx; j < count - 1; j++ ) { buff[j] = buff[j+1]; } count--; return this; } /** * set the char at the specified index * * @param idx * @param chr */ public void set(int idx, char chr) { if ( idx < 0 ) throw new IndexOutOfBoundsException("idx < 0"); if ( idx >= count ) throw new IndexOutOfBoundsException("idx >= buffer.length"); buff[idx] = chr; } /** * return the chars of the buffer * * @return char[] */ public char[] buffer() { return buff; } /** * clear the buffer by reset the count to 0 */ public IStringBuffer clear() { count = 0; return this; } /** * return the string of the current buffer * * @return String * @see Object#toString() */ public String toString() { return new String(buff, 0, count); } }
lionsoul2014/jcseg
jcseg-core/src/main/java/org/lionsoul/jcseg/util/IStringBuffer.java
Java
apache-2.0
7,966
/* * Copyright (c) 2017 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #ifndef MODULES_VIDEO_CODING_CODECS_STEREO_INCLUDE_STEREO_ENCODER_ADAPTER_H_ #define MODULES_VIDEO_CODING_CODECS_STEREO_INCLUDE_STEREO_ENCODER_ADAPTER_H_ #include <map> #include <memory> #include <vector> #include "api/video_codecs/sdp_video_format.h" #include "api/video_codecs/video_encoder.h" #include "api/video_codecs/video_encoder_factory.h" #include "modules/video_coding/include/video_codec_interface.h" namespace webrtc { enum AlphaCodecStream { kYUVStream = 0, kAXXStream = 1, kAlphaCodecStreams = 2, }; class StereoEncoderAdapter : public VideoEncoder { public: // |factory| is not owned and expected to outlive this class' lifetime. explicit StereoEncoderAdapter(VideoEncoderFactory* factory, const SdpVideoFormat& associated_format); virtual ~StereoEncoderAdapter(); // Implements VideoEncoder int InitEncode(const VideoCodec* inst, int number_of_cores, size_t max_payload_size) override; int Encode(const VideoFrame& input_image, const CodecSpecificInfo* codec_specific_info, const std::vector<FrameType>* frame_types) override; int RegisterEncodeCompleteCallback(EncodedImageCallback* callback) override; int SetChannelParameters(uint32_t packet_loss, int64_t rtt) override; int SetRateAllocation(const BitrateAllocation& bitrate, uint32_t new_framerate) override; int Release() override; const char* ImplementationName() const override; EncodedImageCallback::Result OnEncodedImage( AlphaCodecStream stream_idx, const EncodedImage& encodedImage, const CodecSpecificInfo* codecSpecificInfo, const RTPFragmentationHeader* fragmentation); private: // Wrapper class that redirects OnEncodedImage() calls. class AdapterEncodedImageCallback; VideoEncoderFactory* const factory_; const SdpVideoFormat associated_format_; std::vector<std::unique_ptr<VideoEncoder>> encoders_; std::vector<std::unique_ptr<AdapterEncodedImageCallback>> adapter_callbacks_; EncodedImageCallback* encoded_complete_callback_; // Holds the encoded image info. struct ImageStereoInfo; std::map<uint32_t /* timestamp */, ImageStereoInfo> image_stereo_info_; uint16_t picture_index_ = 0; std::vector<uint8_t> stereo_dummy_planes_; }; } // namespace webrtc #endif // MODULES_VIDEO_CODING_CODECS_STEREO_INCLUDE_STEREO_ENCODER_ADAPTER_H_
wangcy6/storm_app
frame/c++/webrtc-master/modules/video_coding/codecs/stereo/include/stereo_encoder_adapter.h
C
apache-2.0
2,841
package net.happybrackets.core.control; import com.google.gson.Gson; import de.sciss.net.OSCMessage; import net.happybrackets.core.Device; import net.happybrackets.core.OSCVocabulary; import net.happybrackets.core.scheduling.HBScheduler; import net.happybrackets.core.scheduling.ScheduledEventListener; import net.happybrackets.core.scheduling.ScheduledObject; import net.happybrackets.device.HB; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.*; /** * This class facilitates sending message values between sketches, * devices, and a graphical environment. * The values can be represented as sliders, text boxes, check boxes, and buttons * * A message can either be an integer, a double, a string, a boolean, a trigger or a complete class. * * Although similar to the send and receive objects in Max in that the name and type * parameter of the {@link DynamicControl} determines message interconnection, * DynamicControls also have an attribute called {@link ControlScope}, which dictates how far (in * a topological sense) the object can reach in order to communicate with other * DynamicControls. DynamicControls can be bound to different objects, the default being the class that instantiated it. * * <br>The classes are best accessed through {@link DynamicControlParent} abstractions * */ public class DynamicControl implements ScheduledEventListener { static Gson gson = new Gson(); // flag for testing static boolean ignoreName = false; private boolean isPersistentControl = false; /** * Set ignore name for testing * @param ignore true to ignore */ static void setIgnoreName(boolean ignore){ ignoreName = true; } static int deviceSendId = 0; // we will use this to number all messages we send. They can be filtered at receiver by testing last message mapped /** * Define a list of target devices. Can be either device name or IP address * If it is a device name, there will be a lookup of stored device names */ Set<String> targetDevices = new HashSet<>(); // we will map Message ID to device name. If the last ID is in this map, we will ignore message static Map<String, Integer> messageIdMap = new Hashtable<>(); /** * See if we will process a control message based on device name and message_id * If the message_id is mapped against the device_name, ignore message, otherwise store mapping and return true; * @param device_name the device name * @param message_id the message_id * @return true if we are going to process this message */ public static boolean enableProcessControlMessage(String device_name, int message_id){ boolean ret = true; if (messageIdMap.containsKey(device_name)) { if (messageIdMap.get(device_name) == message_id) { ret = false; } } if (ret){ messageIdMap.put(device_name, message_id); } return ret; } // The device name that set last message to this control // A Null value will indicate that it was this device String sendingDevice = null; /** * Get the name of the device that sent the message. If the message was local, will return this device name * @return name of device that sent message */ public String getSendingDevice(){ String ret = sendingDevice; if (ret == null) { ret = deviceName; } return ret; } /** * Define how we want the object displayed in the plugin */ public enum DISPLAY_TYPE { DISPLAY_DEFAULT, DISPLAY_HIDDEN, DISPLAY_DISABLED, DISPLAY_ENABLED_BUDDY, DISPLAY_DISABLED_BUDDY } /** * Return all mapped device addresses for this control * @return returns the set of mapped targeted devices */ public Set<String> getTargetDeviceAddresses(){ return targetDevices; } @Override public void doScheduledEvent(double scheduledTime, Object param) { FutureControlMessage message = (FutureControlMessage) param; this.objVal = message.controlValue; this.executionTime = 0; this.sendingDevice = message.sourceDevice; notifyLocalListeners(); if (!message.localOnly) { notifyValueSetListeners(); } synchronized (futureMessageListLock) { futureMessageList.remove(message); } } /** * Add one or more device names or addresses as strings to use in {@link ControlScope#TARGET} Message * @param deviceNames device name or IP Address */ public synchronized void addTargetDevice(String... deviceNames){ for (String name: deviceNames) { targetDevices.add(name); } } /** * Remove all set target devices and replace with the those provided as arguments * Adds device address as a string or device name to {@link ControlScope#TARGET} Message * @param deviceNames device name or IP Address */ public synchronized void setTargetDevice(String... deviceNames){ targetDevices.clear(); addTargetDevice(deviceNames); } /** * Remove all set target devices and replace with the those provided as arguments * Adds device addresses to {@link ControlScope#TARGET} Message * @param inetAddresses device name or IP Address */ public synchronized void setTargetDevice(InetAddress... inetAddresses){ targetDevices.clear(); addTargetDevice(inetAddresses); } /** * Add one or more device {@link InetAddress} for use in {@link ControlScope#TARGET} Message * @param inetAddresses the target addresses to add */ public void addTargetDevice(InetAddress... inetAddresses){ for (InetAddress address: inetAddresses) { targetDevices.add(address.getHostAddress()); } } /** * Clear all devices as Targets */ public synchronized void clearTargetDevices(){ targetDevices.clear(); } /** * Remove one or more device names or addresses as a string. * For use in {@link ControlScope#TARGET} Messages * @param deviceNames device names or IP Addresses to remove */ public synchronized void removeTargetDevice(String... deviceNames){ for (String name: deviceNames) { targetDevices.remove(name); } } /** * Remove one or more {@link InetAddress} for use in {@link ControlScope#TARGET} Message * @param inetAddresses the target addresses to remove */ public void removeTargetDevice(InetAddress... inetAddresses){ for (InetAddress address: inetAddresses) { targetDevices.remove(address.getHostAddress()); } } /** * Create an Interface to listen to */ public interface DynamicControlListener { void update(DynamicControl control); } public interface ControlScopeChangedListener { void controlScopeChanged(ControlScope new_scope); } /** * The way Create Messages are sent */ private enum CREATE_MESSAGE_ARGS { DEVICE_NAME, MAP_KEY, CONTROL_NAME, PARENT_SKETCH_NAME, PARENT_SKETCH_ID, CONTROL_TYPE, OBJ_VAL, MIN_VAL, MAX_VAL, CONTROL_SCOPE, DISPLAY_TYPE_VAL } // Define the Arguments used in an Update message private enum UPDATE_MESSAGE_ARGS { DEVICE_NAME, CONTROL_NAME, CONTROL_TYPE, MAP_KEY, OBJ_VAL, CONTROL_SCOPE, DISPLAY_TYPE_VAL, MIN_VALUE, MAX_VALUE } // Define Global Message arguments public enum NETWORK_TRANSMIT_MESSAGE_ARGS { DEVICE_NAME, CONTROL_NAME, CONTROL_TYPE, OBJ_VAL, EXECUTE_TIME_MLILI_MS, // Most Significant Int of Milliseconds - stored as int EXECUTE_TIME_MLILI_LS, // Least Significant Bit of Milliseconds - stored as int EXECUTE_TIME_NANO, // Number on Nano Seconds - stored as int MESSAGE_ID // we will increment an integer and send the message multiple times. We will ignore message if last message was this one } // Define Device Name Message arguments private enum DEVICE_NAME_ARGS { DEVICE_NAME } // Define where our first Array type global dynamic control message is in OSC final static int OSC_TRANSMIT_ARRAY_ARG = NETWORK_TRANSMIT_MESSAGE_ARGS.MESSAGE_ID.ordinal() + 1; // When an event is scheduled in the future, we will create one of these and schedule it class FutureControlMessage{ /** * Create a Future Control message * @param source_device the source device name * @param value the value to be executed * @param execution_time the time the value needs to be executed */ public FutureControlMessage(String source_device, Object value, double execution_time){ sourceDevice = source_device; controlValue = value; executionTime = execution_time; } Object controlValue; double executionTime; boolean localOnly = false; // if we are local only, we will not sendValue changed listeners String sourceDevice; /// have a copy of our pending scheduled object in case we want to cancel it ScheduledObject pendingSchedule = null; } static ControlMap controlMap = ControlMap.getInstance(); private static final Object controlMapLock = new Object(); private static int instanceCounter = 0; // we will use this to order the creation of our objects and give them a unique number on device private final Object instanceCounterLock = new Object(); private final Object valueChangedLock = new Object(); private final String controlMapKey; private List<DynamicControlListener> controlListenerList = new ArrayList<>(); private List<DynamicControlListener> globalControlListenerList = new ArrayList<>(); private List<ControlScopeChangedListener> controlScopeChangedList = new ArrayList<>(); private List<FutureControlMessage> futureMessageList = new ArrayList<>(); // This listener is only called when value on control set private List<DynamicControlListener> valueSetListenerList = new ArrayList<>(); // Create Object to lock shared resources private final Object controlScopeChangedLock = new Object(); private final Object controlListenerLock = new Object(); private final Object globalListenerLock = new Object(); private final Object valueSetListenerLock = new Object(); private final Object futureMessageListLock = new Object(); static boolean disableScheduler = false; // set flag if we are going to disable scheduler - eg, in GUI /** * Create the text we will display at the beginning of tooltip * @param tooltipPrefix The starting text of the tooltip * @return this object */ public DynamicControl setTooltipPrefix(String tooltipPrefix) { this.tooltipPrefix = tooltipPrefix; return this; } private String tooltipPrefix = ""; // The Object sketch that this control was created in private Object parentSketch = null; final int parentId; private final String deviceName; private String parentSketchName; private ControlType controlType; final String controlName; private ControlScope controlScope = ControlScope.SKETCH; private Object objVal = 0; private Object maximumDisplayValue = 0; private Object minimumDisplayValue = 0; // This is the time we want to execute the control value private double executionTime = 0; DISPLAY_TYPE displayType = DISPLAY_TYPE.DISPLAY_DEFAULT; // Whether the control is displayType on control Screen /** * Set whether we disable setting all values in context of scheduler * @param disabled set true to disable */ public static void setDisableScheduler(boolean disabled){ disableScheduler = disabled; } /** * Whether we disable the control on the screen * @return How we will disable control on screen */ public DISPLAY_TYPE getDisplayType(){ return displayType; } /** * Set how we will display control object on the screen * @param display_type how we will display control * @return this */ public DynamicControl setDisplayType(DISPLAY_TYPE display_type){ displayType = display_type; notifyValueSetListeners(); //notifyLocalListeners(); return this; } /** * Returns the JVM execution time we last used when we set the value * @return lastExecution time set */ public double getExecutionTime(){ return executionTime; } /** * Convert a float or int into required number type based on control. If not a FLOAT or INT, will just return value * @param control_type the control type * @param source_value the value we want * @return the converted value */ static private Object convertValue (ControlType control_type, Object source_value) { Object ret = source_value; // Convert if we are a float control if (control_type == ControlType.FLOAT) { if (source_value == null){ ret = 0.0; }else if (source_value instanceof Integer) { Integer i = (Integer) source_value; double f = i.doubleValue(); ret = f; }else if (source_value instanceof Double) { Double d = (Double) source_value; ret = d; }else if (source_value instanceof Long) { Long l = (Long) source_value; double f = l.doubleValue(); ret = f; } else if (source_value instanceof Float) { double f = (Float) source_value; ret = f; } else if (source_value instanceof String) { double f = Double.parseDouble((String)source_value); ret = f; } // Convert if we are an int control } else if (control_type == ControlType.INT) { if (source_value == null){ ret = 0; }else if (source_value instanceof Float) { Float f = (Float) source_value; Integer i = f.intValue(); ret = i; }else if (source_value instanceof Double) { Double d = (Double) source_value; Integer i = d.intValue(); ret = i; }else if (source_value instanceof Long) { Long l = (Long) source_value; Integer i = l.intValue(); ret = i; } // Convert if we are a BOOLEAN control } else if (control_type == ControlType.BOOLEAN) { if (source_value == null){ ret = 0; }if (source_value instanceof Integer) { Integer i = (Integer) source_value; Boolean b = i != 0; ret = b; }else if (source_value instanceof Long) { Long l = (Long) source_value; Integer i = l.intValue(); Boolean b = i != 0; ret = b; } // Convert if we are a TRIGGER control }else if (control_type == ControlType.TRIGGER) { if (source_value == null) { ret = System.currentTimeMillis(); } // Convert if we are a TEXT control }else if (control_type == ControlType.TEXT) { if (source_value == null) { ret = ""; } } return ret; } /** * Get the Sketch or class object linked to this control * @return the parentSketch or Object */ public Object getParentSketch() { return parentSketch; } /** * This is a private constructor used to initialise constant attributes of this object * * @param parent_sketch the object calling - typically this * @param control_type The type of control you want to create * @param name The name we will give to differentiate between different controls in this class * @param initial_value The initial value of the control * @param display_type how we want to display the object * */ private DynamicControl(Object parent_sketch, ControlType control_type, String name, Object initial_value, DISPLAY_TYPE display_type) { if (parent_sketch == null){ parent_sketch = new Object(); } displayType = display_type; parentSketch = parent_sketch; parentSketchName = parent_sketch.getClass().getName(); controlType = control_type; controlName = name; objVal = convertValue (control_type, initial_value); parentId = parent_sketch.hashCode(); deviceName = Device.getDeviceName(); synchronized (instanceCounterLock) { controlMapKey = Device.getDeviceName() + instanceCounter; instanceCounter++; } } /** * Ascertain the Control Type based on the Value * @param value the value we are obtaing a control value from * @return a control type */ public static ControlType getControlType(Object value){ ControlType ret = ControlType.OBJECT; if (value == null){ ret = ControlType.TRIGGER; } else if (value instanceof Float || value instanceof Double){ ret = ControlType.FLOAT; } else if (value instanceof Boolean){ ret = ControlType.BOOLEAN; } else if (value instanceof String){ ret = ControlType.TEXT; } else if (value instanceof Integer || value instanceof Long){ ret = ControlType.INT; } return ret; } /** * A dynamic control that can be accessed from outside this sketch * it is created with the sketch object that contains it along with the type * * @param name The name we will give to associate it with other DynamicControls with identical ControlScope and type. * @param initial_value The initial value of the control */ public DynamicControl(String name, Object initial_value) { this(new Object(), getControlType(initial_value), name, initial_value, DISPLAY_TYPE.DISPLAY_DEFAULT); synchronized (controlMapLock) { controlMap.addControl(this); } } /** * A dynamic control that can be accessed from outside this sketch * it is created with the sketch object that contains it along with the type * * @param control_type The type of control message you want to send * @param name The name we will give to associate it with other DynamicControls with identical ControlScope and type. * @param initial_value The initial value of the control */ public DynamicControl(ControlType control_type, String name, Object initial_value) { this(new Object(), control_type, name, initial_value, DISPLAY_TYPE.DISPLAY_DEFAULT); synchronized (controlMapLock) { controlMap.addControl(this); } } /** * A dynamic control that can be accessed from outside this sketch * it is created with the sketch object that contains it along with the type * @param parent_sketch the object calling - typically this, however, you can use any class object * @param control_type The type of control message you want to send * @param name The name we will give to associate it with other DynamicControls with identical ControlScope and type. */ public DynamicControl(Object parent_sketch, ControlType control_type, String name) { this(parent_sketch, control_type, name, null, DISPLAY_TYPE.DISPLAY_DEFAULT); synchronized (controlMapLock) { controlMap.addControl(this); } } /** * A dynamic control that can be accessed from outside this sketch * it is created with the sketch object that contains it along with the type * * @param control_type The type of control message you want to send * @param name The name we will give to associate it with other DynamicControls with identical ControlScope and type. */ public DynamicControl(ControlType control_type, String name) { this(new Object(), control_type, name, convertValue(control_type, null), DISPLAY_TYPE.DISPLAY_DEFAULT); synchronized (controlMapLock) { controlMap.addControl(this); } } /** * A dynamic control that can be accessed from outside this sketch * it is created with the sketch object that contains it along with the type * * @param parent_sketch the object calling - typically this, however, you can use any class object * @param control_type The type of control message you want to send * @param name The name we will give to associate it with other DynamicControls with identical ControlScope and type. * @param initial_value The initial value of the control */ public DynamicControl(Object parent_sketch, ControlType control_type, String name, Object initial_value) { this(parent_sketch, control_type, name, initial_value, DISPLAY_TYPE.DISPLAY_DEFAULT); synchronized (controlMapLock) { controlMap.addControl(this); } } /** * Set this control as a persistentSimulation control so it does not get removed on reset * @return this */ public DynamicControl setPersistentController(){ controlMap.addPersistentControl(this); isPersistentControl = true; return this; } /** * See if control is a persistent control * @return true if a simulator control */ public boolean isPersistentControl() { return isPersistentControl; } /** * A dynamic control that can be accessed from outside * it is created with the sketch object that contains it along with the type * * @param parent_sketch the object calling - typically this, however, you can use any class object * @param control_type The type of control message you want to send * @param name The name we will give to associate it with other DynamicControls with identical ControlScope and type. * @param initial_value The initial value of the control * @param min_value The minimum display value of the control. Only used for display purposes * @param max_value The maximum display value of the control. Only used for display purposes */ public DynamicControl(Object parent_sketch, ControlType control_type, String name, Object initial_value, Object min_value, Object max_value) { this(parent_sketch, control_type, name, initial_value, DISPLAY_TYPE.DISPLAY_DEFAULT); minimumDisplayValue = convertValue (control_type, min_value); maximumDisplayValue = convertValue (control_type, max_value); synchronized (controlMapLock) { controlMap.addControl(this); } } /** * A dynamic control that can be accessed from outside * it is created with the sketch object that contains it along with the type * * @param parent_sketch the object calling - typically this, however, you can use any class object * @param control_type The type of control message you want to send * @param name The name we will give to associate it with other DynamicControls with identical ControlScope and type. * @param initial_value The initial value of the control * @param min_value The minimum display value of the control. Only used for display purposes * @param max_value The maximum display value of the control. Only used for display purposes * @param display_type The way we want the control displayed */ public DynamicControl(Object parent_sketch, ControlType control_type, String name, Object initial_value, Object min_value, Object max_value, DISPLAY_TYPE display_type) { this(parent_sketch, control_type, name, initial_value, display_type); minimumDisplayValue = convertValue (control_type, min_value); maximumDisplayValue = convertValue (control_type, max_value); synchronized (controlMapLock) { controlMap.addControl(this); } } /** * A dynamic control that can be accessed from outside * it is created with the sketch object that contains it along with the type * * @param control_type The type of control message you want to send * @param name The name we will give to associate it with other DynamicControls with identical ControlScope and type. * @param initial_value The initial value of the control * @param min_value The minimum display value of the control. Only used for display purposes * @param max_value The maximum display value of the control. Only used for display purposes */ public DynamicControl(ControlType control_type, String name, Object initial_value, Object min_value, Object max_value) { this(new Object(), control_type, name, initial_value, DISPLAY_TYPE.DISPLAY_DEFAULT); minimumDisplayValue = convertValue (control_type, min_value); maximumDisplayValue = convertValue (control_type, max_value); synchronized (controlMapLock) { controlMap.addControl(this); } } /** * Get the type of control we want * @return The type of value this control is */ public ControlType getControlType(){ return controlType; } /** * Get the scope of this control. Can be Sketch, Class, Device, or global * @return The Scope */ public ControlScope getControlScope(){ return controlScope; } /** * Changed the scope that the control has. It will update control map so the correct events will be generated based on its scope * @param new_scope The new Control Scope * @return this object */ public synchronized DynamicControl setControlScope(ControlScope new_scope) { ControlScope old_scope = controlScope; if (old_scope != new_scope) { controlScope = new_scope; notifyValueSetListeners(); // prevent control scope from changing the value //notifyLocalListeners(); notifyControlChangeListeners(); } return this; } /** * Get the Dynamic control based on Map key * * @param map_key the string that we are using as the key * @return the Object associated with this control */ public static DynamicControl getControl(String map_key) { DynamicControl ret = null; synchronized (controlMapLock) { ret = controlMap.getControl(map_key); } return ret; } /** * Update the parameters of this control with another. This would have been caused by an object having other than SKETCH control scope * If the parameters are changed, this object will notify it's listeners that a change has occurred * @param mirror_control The control that we are copying from * @return this object */ public DynamicControl updateControl(DynamicControl mirror_control){ if (mirror_control != null) { // first check our scope and type are the same boolean scope_matches = getControlScope() == mirror_control.getControlScope() && getControlType() == mirror_control.getControlType(); if (scope_matches) { // Now we need to check whether the scope matches us if (getControlScope() == ControlScope.SKETCH) { scope_matches = this.parentSketch == mirror_control.parentSketch && this.parentSketch != null; } // Now we need to check whether the scope matches us else if (getControlScope() == ControlScope.CLASS) { scope_matches = this.parentSketchName.equals(mirror_control.parentSketchName); } else if (getControlScope() == ControlScope.DEVICE){ scope_matches = this.deviceName.equals(mirror_control.deviceName); } else if (getControlScope() == ControlScope.TARGET){ // check if our mirror has this address scope_matches = mirror_control.targetsThisDevice(); } // Otherwise it must be global. We have a match } if (scope_matches) { // do not use setters as we only want to generate one notifyLocalListeners boolean changed = false; if (mirror_control.executionTime <= 0.0) { // his needs to be done now if (!objVal.equals(mirror_control.objVal)) { //objVal = mirror_control.objVal; // let this get done inside the scheduleValue return changed = true; } if (changed) { scheduleValue(null, mirror_control.objVal, 0); } } else { scheduleValue(null, mirror_control.objVal, mirror_control.executionTime); } } } return this; } /** * Check whether this device is targeted by checking the loopback, localhost and devicenames * @return */ private boolean targetsThisDevice() { boolean ret = false; String device_name = Device.getDeviceName(); String loopback = InetAddress.getLoopbackAddress().getHostAddress(); for (String device: targetDevices) { if (device_name.equalsIgnoreCase(device)){ return true; } if (device_name.equalsIgnoreCase(loopback)){ return true; } try { if (InetAddress.getLocalHost().getHostAddress().equalsIgnoreCase(device)){ return true; } } catch (UnknownHostException e) { //e.printStackTrace(); } } return ret; } /** * Schedule this control to change its value in context of scheduler * @param source_device the device name that was the source of this message - can be null * @param value the value to send * @param execution_time the time it needs to be executed * @param local_only if true, will not send value changed to notifyValueSetListeners */ void scheduleValue(String source_device, Object value, double execution_time, boolean local_only){ // We need to convert the Object value into the exact type. EG, integer must be cast to boolean if that is thr control type Object converted_value = convertValue(controlType, value); if (disableScheduler || execution_time == 0){ this.objVal = converted_value; this.executionTime = 0; this.sendingDevice = source_device; notifyLocalListeners(); if (!local_only) { notifyValueSetListeners(); } } else { FutureControlMessage message = new FutureControlMessage(source_device, converted_value, execution_time); message.localOnly = local_only; message.pendingSchedule = HBScheduler.getGlobalScheduler().addScheduledObject(execution_time, message, this); synchronized (futureMessageListLock) { futureMessageList.add(message); } } } /** * Schedule this control to send a value to it's locallisteners at a scheduled time. Will also notify valueListeners (eg GUI controls) * @param source_device the device name that was the source of this message - can be null * @param value the value to send * @param execution_time the time it needs to be executed */ void scheduleValue(String source_device, Object value, double execution_time) { scheduleValue(source_device, value, execution_time, false); } /** * Process the DynamicControl deviceName message and map device name to IPAddress * We ignore our own device * @param src_address The address of the device * @param msg The OSC Message that has device name */ public static void processDeviceNameMessage(InetAddress src_address, OSCMessage msg) { // do some error checking here if (src_address != null) { String device_name = (String) msg.getArg(DEVICE_NAME_ARGS.DEVICE_NAME.ordinal()); try { if (!Device.getDeviceName().equalsIgnoreCase(device_name)) { HB.HBInstance.addDeviceAddress(device_name, src_address); } } catch(Exception ex){} } } /** * Process the DynamicControl deviceRequest message * Send a deviceName back to src. Test that their name is mapped correctly * If name is not mapped we will request from all devices globally * @param src_address The address of the device * @param msg The OSC Message that has device name */ public static void processRequestNameMessage(InetAddress src_address, OSCMessage msg) { String device_name = (String) msg.getArg(DEVICE_NAME_ARGS.DEVICE_NAME.ordinal()); // ignore ourself if (!Device.getDeviceName().equalsIgnoreCase(device_name)) { // send them our message OSCMessage nameMessage = buildDeviceNameMessage(); ControlMap.getInstance().sendGlobalDynamicControlMessage(nameMessage, null); // See if we have them mapped the same boolean address_changed = HB.HBInstance.addDeviceAddress(device_name, src_address); if (address_changed){ // request all postRequestNamesMessage(); } } } /** * Post a request device name message to other devices so we can target them specifically and update our map */ public static void postRequestNamesMessage(){ OSCMessage requestMessage = buildDeviceRequestNameMessage(); ControlMap.getInstance().sendGlobalDynamicControlMessage(requestMessage, null); } /** * Build OSC Message that gives our device name * @return OSC Message that has name */ public static OSCMessage buildDeviceNameMessage(){ return new OSCMessage(OSCVocabulary.DynamicControlMessage.DEVICE_NAME, new Object[]{ Device.getDeviceName(), }); } /** * Build OSC Message that requests devices send us their name * @return OSC Message to request name */ public static OSCMessage buildDeviceRequestNameMessage(){ return new OSCMessage(OSCVocabulary.DynamicControlMessage.REQUEST_NAME, new Object[]{ Device.getDeviceName(), }); } /** * Convert two halves of a long stored integer values into a long value * @param msi most significant integer * @param lsi least significant integer * @return a long value consisting of the concatenation of both int values */ public static long integersToLong(int msi, int lsi){ return (long) msi << 32 | lsi & 0xFFFFFFFFL; } /** * Convert a long into two integers in an array of two integers * @param l_value the Long values that needs to be encoded * @return an array of two integers. ret[0] will be most significant integer while int [1] will be lease significant */ public static int [] longToIntegers (long l_value){ int msi = (int) (l_value >> 32); // this is most significant integer int lsi = (int) l_value; // This is LSB that has been trimmed down; return new int[]{msi, lsi}; } // We will create a single array that we can cache the size of an array of ints for scheduled time // This is used in numberIntsForScheduledTime private static int [] intArrayCache = null; /** * Return the array size of Integers that would be required to encode a scheduled time * @return the Array */ public static int numberIntsForScheduledTime(){ if (intArrayCache == null) { intArrayCache = scheduleTimeToIntegers(0); } return intArrayCache.length; } /** * Convert a SchedulerTime into integers in an array of three integers * @param d_val the double values that needs to be encoded * @return an array of three integers. ret[0] will be most significant integer while int [1] will be lease significant. int [2] is the number of nano seconds */ public static int [] scheduleTimeToIntegers (double d_val){ long lval = (long)d_val; int msi = (int) (lval >> 32); // this is most significant integer int lsi = (int) lval; // This is LSB that has been trimmed down; double nano = d_val - lval; nano *= 1000000; int n = (int) nano; return new int[]{msi, lsi, n}; } /** * Convert three integers to a double representing scheduler time * @param msi the most significant value of millisecond value * @param lsi the least significant value of millisecond value * @param nano the number of nanoseconds * @return a double representing the scheduler time */ public static double integersToScheduleTime(int msi, int lsi, int nano){ long milliseconds = integersToLong(msi, lsi); double ret = milliseconds; double nanoseconds = nano; return ret + nanoseconds / 1000000d; } /** * Process the {@link ControlScope#GLOBAL} or {@link ControlScope#TARGET} Message from an OSC Message. Examine buildUpdateMessage for parameters inside Message * We will not process messages that have come from this device because they will be actioned through local listeners * @param msg OSC message with new value * @param controlScope the type of {@link ControlScope}; */ public static void processOSCControlMessage(OSCMessage msg, ControlScope controlScope) { String device_name = (String) msg.getArg(NETWORK_TRANSMIT_MESSAGE_ARGS.DEVICE_NAME.ordinal()); int message_id = (int)msg.getArg(NETWORK_TRANSMIT_MESSAGE_ARGS.MESSAGE_ID.ordinal()); // Make sure we ignore messages from this device if (ignoreName || !device_name.equals(Device.getDeviceName())) { if (enableProcessControlMessage(device_name, message_id)) { String control_name = (String) msg.getArg(NETWORK_TRANSMIT_MESSAGE_ARGS.CONTROL_NAME.ordinal()); ControlType control_type = ControlType.values()[(int) msg.getArg(NETWORK_TRANSMIT_MESSAGE_ARGS.CONTROL_TYPE.ordinal())]; Object obj_val = msg.getArg(NETWORK_TRANSMIT_MESSAGE_ARGS.OBJ_VAL.ordinal()); Object ms_max = msg.getArg(NETWORK_TRANSMIT_MESSAGE_ARGS.EXECUTE_TIME_MLILI_MS.ordinal()); Object ms_min = msg.getArg(NETWORK_TRANSMIT_MESSAGE_ARGS.EXECUTE_TIME_MLILI_LS.ordinal()); Object nano = msg.getArg(NETWORK_TRANSMIT_MESSAGE_ARGS.EXECUTE_TIME_NANO.ordinal()); double execution_time = integersToScheduleTime((int) ms_max, (int) ms_min, (int) nano); boolean data_converted = false; // we only want to do data conversion once synchronized (controlMapLock) { List<DynamicControl> named_controls = controlMap.getControlsByName(control_name); for (DynamicControl named_control : named_controls) { if (named_control.controlScope == controlScope && control_type.equals(named_control.controlType)) { // we must NOT call setVal as this will generate a global series again. // Just notifyListeners specific to this control but not globally if (!data_converted) { // we need to see if this is a boolean Object as OSC does not support that if (control_type == ControlType.BOOLEAN) { int osc_val = (int) obj_val; Boolean bool_val = osc_val != 0; obj_val = bool_val; data_converted = true; } else if (control_type == ControlType.OBJECT) { if (!(obj_val instanceof String)) { // This is not a Json Message // We will need to get all the remaining OSC arguments after the schedule time and store that as ObjVal int num_args = msg.getArgCount() - OSC_TRANSMIT_ARRAY_ARG; Object[] restore_args = new Object[num_args]; for (int i = 0; i < num_args; i++) { restore_args[i] = msg.getArg(OSC_TRANSMIT_ARRAY_ARG + i); } obj_val = restore_args; data_converted = true; } } } // We need to schedule this value named_control.scheduleValue(device_name, obj_val, execution_time); } } } } } } /** * Process the Update Message from an OSC Message. Examine buildUpdateMessage for parameters inside Message * The message is directed as a specific control defined by the MAP_KEY parameter in the OSC Message * @param msg OSC message with new value */ public static void processUpdateMessage(OSCMessage msg){ String map_key = (String) msg.getArg(UPDATE_MESSAGE_ARGS.MAP_KEY.ordinal()); String control_name = (String) msg.getArg(UPDATE_MESSAGE_ARGS.CONTROL_NAME.ordinal()); Object obj_val = msg.getArg(UPDATE_MESSAGE_ARGS.OBJ_VAL.ordinal()); ControlScope control_scope = ControlScope.values ()[(int) msg.getArg(UPDATE_MESSAGE_ARGS.CONTROL_SCOPE.ordinal())]; DISPLAY_TYPE display_type = DISPLAY_TYPE.DISPLAY_DEFAULT; DynamicControl control = getControl(map_key); if (control != null) { Object display_min = control.getMinimumDisplayValue(); Object display_max = control.getMaximumDisplayValue(); if (msg.getArgCount() > UPDATE_MESSAGE_ARGS.DISPLAY_TYPE_VAL.ordinal()) { int osc_val = (int) msg.getArg(UPDATE_MESSAGE_ARGS.DISPLAY_TYPE_VAL.ordinal()); display_type = DISPLAY_TYPE.values ()[osc_val]; } if (msg.getArgCount() > UPDATE_MESSAGE_ARGS.MAX_VALUE.ordinal()){ display_max = msg.getArg(UPDATE_MESSAGE_ARGS.MAX_VALUE.ordinal()); } if (msg.getArgCount() > UPDATE_MESSAGE_ARGS.MIN_VALUE.ordinal()){ display_min = msg.getArg(UPDATE_MESSAGE_ARGS.MIN_VALUE.ordinal()); } // do not use setters as we only want to generate one notifyLocalListeners boolean changed = false; boolean control_scope_changed = false; if (control.displayType != display_type) { changed = true; } control.displayType = display_type; obj_val = convertValue(control.controlType, obj_val); display_max = convertValue(control.controlType, display_max); display_min = convertValue(control.controlType, display_min); if (!obj_val.equals(control.objVal) || !display_max.equals(control.maximumDisplayValue) || !display_min.equals(control.minimumDisplayValue) ) { changed = true; } if (!control_scope.equals(control.controlScope)) { control.controlScope = control_scope; //control.executionTime = execution_time; changed = true; control_scope_changed = true; } if (changed) { control.maximumDisplayValue = display_max; control.minimumDisplayValue = display_min; control.scheduleValue(null, obj_val, 0, true); if (control.getControlScope() != ControlScope.UNIQUE){ control.objVal = obj_val; control.notifyGlobalListeners(); } } if (control_scope_changed) { control.notifyControlChangeListeners(); } } } /** * Build OSC Message that specifies a removal of a control * @return OSC Message to notify removal */ public OSCMessage buildRemoveMessage(){ return new OSCMessage(OSCVocabulary.DynamicControlMessage.DESTROY, new Object[]{ deviceName, controlMapKey }); } /** * Return an object that can be sent by OSC based on control TYpe * @param obj_val The object value we want to send * @return the type we will actually send */ private Object OSCArgumentObject (Object obj_val){ Object ret = obj_val; if (obj_val instanceof Boolean) { boolean b = (Boolean) obj_val; return b? 1:0; } else if (obj_val instanceof Double){ String s = ((Double)obj_val).toString(); ret = s; } return ret; } /** * Build OSC Message that specifies an update * @return OSC Message To send to specific control */ public OSCMessage buildUpdateMessage(){ Object sendObjType = objVal; if (controlType == ControlType.OBJECT){ sendObjType = objVal.toString(); } return new OSCMessage(OSCVocabulary.DynamicControlMessage.UPDATE, new Object[]{ deviceName, controlName, controlType.ordinal(), controlMapKey, OSCArgumentObject(sendObjType), controlScope.ordinal(), displayType.ordinal(), OSCArgumentObject(minimumDisplayValue), OSCArgumentObject(maximumDisplayValue), }); } /** * Build OSC Message that specifies a Network update * @return OSC Message directed to controls with same name, scope, but on different devices */ public OSCMessage buildNetworkSendMessage(){ deviceSendId++; String OSC_MessageName = OSCVocabulary.DynamicControlMessage.GLOBAL; // define the arguments for send time int [] execution_args = scheduleTimeToIntegers(executionTime); if (controlScope == ControlScope.TARGET){ OSC_MessageName = OSCVocabulary.DynamicControlMessage.TARGET; } if (controlType == ControlType.OBJECT){ /* DEVICE_NAME, CONTROL_NAME, CONTROL_TYPE, OBJ_VAL, EXECUTE_TIME_MLILI_MS, // Most Significant Int of Milliseconds - stored as int EXECUTE_TIME_MLILI_LS, // Least Significant Bit of Milliseconds - stored as int EXECUTE_TIME_NANO // Number on Nano Seconds - stored as int */ // we need to see if we have a custom encode function if (objVal instanceof CustomGlobalEncoder){ Object [] encode_data = ((CustomGlobalEncoder)objVal).encodeGlobalMessage(); int num_args = OSC_TRANSMIT_ARRAY_ARG + encode_data.length; Object [] osc_args = new Object[num_args]; osc_args[0] = deviceName; osc_args[1] = controlName; osc_args[2] = controlType.ordinal(); osc_args[3] = 0; // by defining zero we are going to say this is NOT json osc_args[4] = execution_args [0]; osc_args[5] = execution_args [1]; osc_args[6] = execution_args [2]; osc_args[7] = deviceSendId; // now encode the object parameters for (int i = 0; i < encode_data.length; i++){ osc_args[OSC_TRANSMIT_ARRAY_ARG + i] = encode_data[i]; } return new OSCMessage(OSC_MessageName, osc_args); } else { String jsonString = gson.toJson(objVal); return new OSCMessage(OSC_MessageName, new Object[]{ deviceName, controlName, controlType.ordinal(), jsonString, execution_args[0], execution_args[1], execution_args[2], deviceSendId }); } } else { return new OSCMessage(OSC_MessageName, new Object[]{ deviceName, controlName, controlType.ordinal(), OSCArgumentObject(objVal), execution_args[0], execution_args[1], execution_args[2], deviceSendId }); } } /** * Build the OSC Message for a create message * @return OSC Message required to create the object */ public OSCMessage buildCreateMessage() { Object sendObjType = objVal; if (controlType == ControlType.OBJECT){ sendObjType = objVal.toString(); } return new OSCMessage(OSCVocabulary.DynamicControlMessage.CREATE, new Object[]{ deviceName, controlMapKey, controlName, parentSketchName, parentId, controlType.ordinal(), OSCArgumentObject(sendObjType), OSCArgumentObject(minimumDisplayValue), OSCArgumentObject(maximumDisplayValue), controlScope.ordinal(), displayType.ordinal() }); } /** * Create a DynamicControl based on OSC Message. This will keep OSC implementation inside this class * The buildUpdateMessage shows how messages are constructed * @param msg the OSC Message with the parameters to make Control */ public DynamicControl (OSCMessage msg) { deviceName = (String) msg.getArg(CREATE_MESSAGE_ARGS.DEVICE_NAME.ordinal()); controlMapKey = (String) msg.getArg(CREATE_MESSAGE_ARGS.MAP_KEY.ordinal()); controlName = (String) msg.getArg(CREATE_MESSAGE_ARGS.CONTROL_NAME.ordinal()); parentSketchName = (String) msg.getArg(CREATE_MESSAGE_ARGS.PARENT_SKETCH_NAME.ordinal()); parentId = (int) msg.getArg(CREATE_MESSAGE_ARGS.PARENT_SKETCH_ID.ordinal()); controlType = ControlType.values ()[(int) msg.getArg(CREATE_MESSAGE_ARGS.CONTROL_TYPE.ordinal())]; objVal = convertValue (controlType, msg.getArg(CREATE_MESSAGE_ARGS.OBJ_VAL.ordinal())); minimumDisplayValue = convertValue (controlType, msg.getArg(CREATE_MESSAGE_ARGS.MIN_VAL.ordinal())); maximumDisplayValue = convertValue (controlType, msg.getArg(CREATE_MESSAGE_ARGS.MAX_VAL.ordinal())); controlScope = ControlScope.values ()[(int) msg.getArg(CREATE_MESSAGE_ARGS.CONTROL_SCOPE.ordinal())]; if (msg.getArgCount() > CREATE_MESSAGE_ARGS.DISPLAY_TYPE_VAL.ordinal()) { int osc_val = (int) msg.getArg(CREATE_MESSAGE_ARGS.DISPLAY_TYPE_VAL.ordinal()); displayType = DISPLAY_TYPE.values ()[osc_val]; } synchronized (controlMapLock) { controlMap.addControl(this); } } /** * Get the map key created in the device as a method for mapping back * @return The unique key to identify this object */ public String getControlMapKey(){ return controlMapKey; } /** * Set the value of the object and notify any listeners * Additionally, the value will propagate to any controls that match the control scope * If we are using a trigger, send a random number or a unique value * @param val the value to set * @return this object */ public DynamicControl setValue(Object val) { return setValue(val, 0); } /** * Set the value of the object and notify any listeners * Additionally, the value will propagate to any controls that match the control scope * If we are using a trigger, send a random number or a unique value * @param val the value to set * @param execution_time the Scheduler time we want this to occur * @return this object */ public DynamicControl setValue(Object val, double execution_time) { executionTime = execution_time; val = convertValue (controlType, val); if (!objVal.equals(val)) { if (controlType == ControlType.FLOAT) { objVal = (Double) val; } else { objVal = val; } notifyGlobalListeners(); scheduleValue(null, val, execution_time); } return this; } /** * Gets the value of the control. The type needs to be cast to the required type in the listener * @return Control Value */ public Object getValue(){ return objVal; } /** * The maximum value that we want as a display, for example, in a slider control. Does not limit values in the messages * @return The maximum value we want a graphical display to be set to */ public Object getMaximumDisplayValue(){ return maximumDisplayValue; } /** * Set the minimum display range for display * @param min minimum display value * * @return this */ public DynamicControl setMinimumValue(Object min) {minimumDisplayValue = min; return this;} /** * Set the maximum display range for display * @param max maximum display value * @return this */ public DynamicControl setMaximumDisplayValue(Object max) {maximumDisplayValue = max; return this;} /** * The minimum value that we want as a display, for example, in a slider control. Does not limit values in the messages * @return The minimum value we want a graphical display to be set to */ public Object getMinimumDisplayValue(){ return minimumDisplayValue; } /** * Get the name of the control used for ControlScope matching. Also displayed in GUI * @return The name of the control for scope matching */ public String getControlName(){ return controlName; } /** * Register Listener to receive changed values in the control * @param listener Listener to register for events * @return this */ public DynamicControl addControlListener(DynamicControlListener listener) { if (listener != null) { synchronized (controlListenerLock) { controlListenerList.add(listener); } } return this; } /** * Register Listener to receive changed values in the control that need to be global type messages * @param listener Listener to register for events * @return this listener that has been created */ public DynamicControl addGlobalControlListener(DynamicControlListener listener) { if (listener != null) { synchronized (globalListenerLock) { globalControlListenerList.add(listener); } } return this; } /** * Register Listener to receive changed values in the control that need to be received when value is specifically set from * Within sketch * @param listener Listener to register for events * @return this */ public DynamicControl addValueSetListener(DynamicControlListener listener) { if (listener != null) { synchronized (valueSetListenerLock) { valueSetListenerList.add(listener); } } return this; } /** * Deregister listener so it no longer receives messages from this control * @param listener The lsitener we are removing * @return this object */ public DynamicControl removeControlListener(DynamicControlListener listener) { if (listener != null) { synchronized (controlListenerLock) { controlListenerList.remove(listener); } } return this; } /** * Deregister listener so it no longer receives messages from this control * @param listener the listener we are remmoving * @return this object */ public DynamicControl removeGlobalControlListener(DynamicControlListener listener) { if (listener != null) { synchronized (globalListenerLock) { globalControlListenerList.remove(listener); } } return this; } /** * Register Listener to receive changed values in the control scope * @param listener Listener to register for events * @return this object */ public DynamicControl addControlScopeListener(ControlScopeChangedListener listener){ if (listener != null) { synchronized (controlScopeChangedLock) { controlScopeChangedList.add(listener); } } return this; } /** * Deregister listener so it no longer receives messages from this control * @param listener the listener * @return this object */ public DynamicControl removeControlScopeChangedListener(ControlScopeChangedListener listener) { if (listener != null) { synchronized (controlScopeChangedLock) { controlScopeChangedList.remove(listener); } } return this; } /** * Erase all listeners from this control * @return this object */ public DynamicControl eraseListeners() { // We need to synchronized (futureMessageListLock){ for (FutureControlMessage message: futureMessageList) { message.pendingSchedule.setCancelled(true); } futureMessageList.clear(); } synchronized (controlListenerLock) {controlListenerList.clear();} synchronized (controlScopeChangedLock) {controlScopeChangedList.clear();} return this; } /** * Notify all registered listeners of object value on this device * @return this object */ public DynamicControl notifyLocalListeners() { synchronized (controlListenerLock) { controlListenerList.forEach(listener -> { try { listener.update(this); } catch (Exception ex) { ex.printStackTrace(); } }); } return this; } /** * Send Update Message when value set */ public void notifyValueSetListeners(){ synchronized (valueSetListenerLock) { valueSetListenerList.forEach(listener -> { try { listener.update(this); } catch (Exception ex) { ex.printStackTrace(); } }); } } /** * Send Global Update Message */ public void notifyGlobalListeners(){ synchronized (globalListenerLock) { globalControlListenerList.forEach(listener -> { try { listener.update(this); } catch (Exception ex) { ex.printStackTrace(); } }); } } /** * Notify all registered listeners of object value * @return this object */ public DynamicControl notifyControlChangeListeners() { synchronized (controlScopeChangedLock) { controlScopeChangedList.forEach(listener -> { try { listener.controlScopeChanged(this.getControlScope()); } catch (Exception ex) { ex.printStackTrace(); } }); } return this; } /** * Get the tooltip to display * @return the tooltip to display */ public String getTooltipText(){ String control_scope_text = ""; if (getControlScope() == ControlScope.UNIQUE) { control_scope_text = "UNIQUE scope"; } else if (getControlScope() == ControlScope.SKETCH) { control_scope_text = "SKETCH scope"; } else if (getControlScope() == ControlScope.CLASS) { control_scope_text = "CLASS scope - " + parentSketchName; } else if (getControlScope() == ControlScope.DEVICE) { control_scope_text = "DEVICE scope - " + deviceName; } else if (getControlScope() == ControlScope.GLOBAL) { control_scope_text = "GLOBAL scope"; } return tooltipPrefix + "\n" + control_scope_text; } }
orsjb/HappyBrackets
HappyBrackets/src/main/java/net/happybrackets/core/control/DynamicControl.java
Java
apache-2.0
63,210
# Moritzia dasyantha Fresen. SPECIES #### Status ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Boraginales/Boraginaceae/Moritzia/Moritzia dasyantha/README.md
Markdown
apache-2.0
176
// Copyright 2020 The IREE Authors // // Licensed under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // #ifndef IREE_COMPILER_DIALECT_HAL_TARGET_LLVM_LLVMAOTTARGET_H_ #define IREE_COMPILER_DIALECT_HAL_TARGET_LLVM_LLVMAOTTARGET_H_ #include "iree/compiler/Dialect/HAL/Target/LLVM/LLVMTargetOptions.h" namespace mlir { namespace iree_compiler { namespace IREE { namespace HAL { // Registers the LLVM Ahead-Of-Time (AOT) target backends. void registerLLVMAOTTargetBackends( std::function<LLVMTargetOptions()> queryOptions); } // namespace HAL } // namespace IREE } // namespace iree_compiler } // namespace mlir #endif // IREE_COMPILER_DIALECT_HAL_TARGET_LLVM_LLVMAOTTARGET_H_
google/iree
iree/compiler/Dialect/HAL/Target/LLVM/LLVMAOTTarget.h
C
apache-2.0
809
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.6.0_27) on Wed Nov 06 17:51:16 PST 2013 --> <TITLE> QuantileUtil (DataFu 1.1.0) </TITLE> <META NAME="date" CONTENT="2013-11-06"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="QuantileUtil (DataFu 1.1.0)"; } } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <HR> <!-- ========= START OF TOP NAVBAR ======= --> <A NAME="navbar_top"><!-- --></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="class-use/QuantileUtil.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../../datafu/pig/stats/Quantile.html" title="class in datafu.pig.stats"><B>PREV CLASS</B></A>&nbsp; &nbsp;<A HREF="../../../datafu/pig/stats/StreamingMedian.html" title="class in datafu.pig.stats"><B>NEXT CLASS</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../index.html?datafu/pig/stats/QuantileUtil.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="QuantileUtil.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> <TR> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> SUMMARY:&nbsp;NESTED&nbsp;|&nbsp;FIELD&nbsp;|&nbsp;<A HREF="#constructor_summary">CONSTR</A>&nbsp;|&nbsp;<A HREF="#method_summary">METHOD</A></FONT></TD> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> DETAIL:&nbsp;FIELD&nbsp;|&nbsp;<A HREF="#constructor_detail">CONSTR</A>&nbsp;|&nbsp;<A HREF="#method_detail">METHOD</A></FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <!-- ======== START OF CLASS DATA ======== --> <H2> <FONT SIZE="-1"> datafu.pig.stats</FONT> <BR> Class QuantileUtil</H2> <PRE> java.lang.Object <IMG SRC="../../../resources/inherit.gif" ALT="extended by "><B>datafu.pig.stats.QuantileUtil</B> </PRE> <HR> <DL> <DT><PRE>public class <B>QuantileUtil</B><DT>extends java.lang.Object</DL> </PRE> <P> Methods used by <A HREF="../../../datafu/pig/stats/Quantile.html" title="class in datafu.pig.stats"><CODE>Quantile</CODE></A>. <P> <P> <DL> <DT><B>Author:</B></DT> <DD>"Matthew Hayes <[email protected]>"</DD> </DL> <HR> <P> <!-- ======== CONSTRUCTOR SUMMARY ======== --> <A NAME="constructor_summary"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Constructor Summary</B></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><CODE><B><A HREF="../../../datafu/pig/stats/QuantileUtil.html#QuantileUtil()">QuantileUtil</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> </TABLE> &nbsp; <!-- ========== METHOD SUMMARY =========== --> <A NAME="method_summary"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Method Summary</B></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>static&nbsp;java.util.ArrayList&lt;java.lang.Double&gt;</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../datafu/pig/stats/QuantileUtil.html#getNQuantiles(int)">getNQuantiles</A></B>(int&nbsp;numQuantiles)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>static&nbsp;java.util.ArrayList&lt;java.lang.Double&gt;</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../datafu/pig/stats/QuantileUtil.html#getQuantilesFromParams(java.lang.String...)">getQuantilesFromParams</A></B>(java.lang.String...&nbsp;k)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> </TABLE> &nbsp;<A NAME="methods_inherited_from_class_java.lang.Object"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#EEEEFF" CLASS="TableSubHeadingColor"> <TH ALIGN="left"><B>Methods inherited from class java.lang.Object</B></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><CODE>clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</CODE></TD> </TR> </TABLE> &nbsp; <P> <!-- ========= CONSTRUCTOR DETAIL ======== --> <A NAME="constructor_detail"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2"> <B>Constructor Detail</B></FONT></TH> </TR> </TABLE> <A NAME="QuantileUtil()"><!-- --></A><H3> QuantileUtil</H3> <PRE> public <B>QuantileUtil</B>()</PRE> <DL> </DL> <!-- ============ METHOD DETAIL ========== --> <A NAME="method_detail"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2"> <B>Method Detail</B></FONT></TH> </TR> </TABLE> <A NAME="getNQuantiles(int)"><!-- --></A><H3> getNQuantiles</H3> <PRE> public static java.util.ArrayList&lt;java.lang.Double&gt; <B>getNQuantiles</B>(int&nbsp;numQuantiles)</PRE> <DL> <DD><DL> </DL> </DD> </DL> <HR> <A NAME="getQuantilesFromParams(java.lang.String...)"><!-- --></A><H3> getQuantilesFromParams</H3> <PRE> public static java.util.ArrayList&lt;java.lang.Double&gt; <B>getQuantilesFromParams</B>(java.lang.String...&nbsp;k)</PRE> <DL> <DD><DL> </DL> </DD> </DL> <!-- ========= END OF CLASS DATA ========= --> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <A NAME="navbar_bottom"><!-- --></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="class-use/QuantileUtil.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../../datafu/pig/stats/Quantile.html" title="class in datafu.pig.stats"><B>PREV CLASS</B></A>&nbsp; &nbsp;<A HREF="../../../datafu/pig/stats/StreamingMedian.html" title="class in datafu.pig.stats"><B>NEXT CLASS</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../index.html?datafu/pig/stats/QuantileUtil.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="QuantileUtil.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> <TR> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> SUMMARY:&nbsp;NESTED&nbsp;|&nbsp;FIELD&nbsp;|&nbsp;<A HREF="#constructor_summary">CONSTR</A>&nbsp;|&nbsp;<A HREF="#method_summary">METHOD</A></FONT></TD> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> DETAIL:&nbsp;FIELD&nbsp;|&nbsp;<A HREF="#constructor_detail">CONSTR</A>&nbsp;|&nbsp;<A HREF="#method_detail">METHOD</A></FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> Matthew Hayes, Sam Shah </BODY> </HTML>
shaohua-zhang/incubator-datafu
site/source/docs/datafu/1.1.0/datafu/pig/stats/QuantileUtil.html
HTML
apache-2.0
10,689
# AUTOGENERATED FILE FROM balenalib/artik520-fedora:34-run ENV NODE_VERSION 16.14.0 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 keyserver.ubuntu.com --recv-keys "$key" ; \ done \ && curl -SLO "http://nodejs.org/dist/v$NODE_VERSION/node-v$NODE_VERSION-linux-armv7l.tar.gz" \ && echo "2df94404f4dd22aee67370cd24b2c802f82409434e5ed26061c7aaec74a8ebc2 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/[email protected]" \ && echo "Running test-stack@node" \ && chmod +x [email protected] \ && bash [email protected] \ && rm -rf [email protected] 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: Fedora 34 \nVariant: run variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nNode.js v16.14.0, Yarn v1.22.4 \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info RUN echo $'#!/bin/sh.real\nbalena-info\nrm -f /bin/sh\ncp /bin/sh.real /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \ && chmod +x /bin/sh-shim \ && cp /bin/sh /bin/sh.real \ && mv /bin/sh-shim /bin/sh
resin-io-library/base-images
balena-base-images/node/artik520/fedora/34/16.14.0/run/Dockerfile
Dockerfile
apache-2.0
2,745
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="de"> <head> <!-- Generated by javadoc (version 1.7.0_17) on Tue May 14 03:45:01 CEST 2013 --> <title>AtlasTmxMapLoader (libgdx API)</title> <meta name="date" content="2013-05-14"> <link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="AtlasTmxMapLoader (libgdx API)"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="class-use/AtlasTmxMapLoader.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-all.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> <div class="aboutLanguage"><em> libgdx API <style> body, td, th { font-family:Helvetica, Tahoma, Arial, sans-serif; font-size:10pt } pre, code, tt { font-size:9pt; font-family:Lucida Console, Courier New, sans-serif } h1, h2, h3, .FrameTitleFont, .FrameHeadingFont, .TableHeadingColor font { font-size:105%; font-weight:bold } .TableHeadingColor { background:#EEEEFF; } a { text-decoration:none } a:hover { text-decoration:underline } a:link, a:visited { color:blue } table { border:0px } .TableRowColor td:first-child { border-left:1px solid black } .TableRowColor td { border:0px; border-bottom:1px solid black; border-right:1px solid black } hr { border:0px; border-bottom:1px solid #333366; } </style> </em></div> </div> <div class="subNav"> <ul class="navList"> <li>Prev Class</li> <li><a href="../../../../../com/badlogic/gdx/maps/tiled/AtlasTmxMapLoader.AtlasTiledMapLoaderParameters.html" title="class in com.badlogic.gdx.maps.tiled"><span class="strong">Next Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?com/badlogic/gdx/maps/tiled/AtlasTmxMapLoader.html" target="_top">Frames</a></li> <li><a href="AtlasTmxMapLoader.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li><a href="#nested_class_summary">Nested</a>&nbsp;|&nbsp;</li> <li><a href="#field_summary">Field</a>&nbsp;|&nbsp;</li> <li><a href="#constructor_summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method_summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li><a href="#field_detail">Field</a>&nbsp;|&nbsp;</li> <li><a href="#constructor_detail">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method_detail">Method</a></li> </ul> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <!-- ======== START OF CLASS DATA ======== --> <div class="header"> <div class="subTitle">com.badlogic.gdx.maps.tiled</div> <h2 title="Class AtlasTmxMapLoader" class="title">Class AtlasTmxMapLoader</h2> </div> <div class="contentContainer"> <ul class="inheritance"> <li>java.lang.Object</li> <li> <ul class="inheritance"> <li><a href="../../../../../com/badlogic/gdx/assets/loaders/AssetLoader.html" title="class in com.badlogic.gdx.assets.loaders">com.badlogic.gdx.assets.loaders.AssetLoader</a>&lt;T,P&gt;</li> <li> <ul class="inheritance"> <li><a href="../../../../../com/badlogic/gdx/assets/loaders/AsynchronousAssetLoader.html" title="class in com.badlogic.gdx.assets.loaders">com.badlogic.gdx.assets.loaders.AsynchronousAssetLoader</a>&lt;<a href="../../../../../com/badlogic/gdx/maps/tiled/TiledMap.html" title="class in com.badlogic.gdx.maps.tiled">TiledMap</a>,<a href="../../../../../com/badlogic/gdx/maps/tiled/AtlasTmxMapLoader.AtlasTiledMapLoaderParameters.html" title="class in com.badlogic.gdx.maps.tiled">AtlasTmxMapLoader.AtlasTiledMapLoaderParameters</a>&gt;</li> <li> <ul class="inheritance"> <li>com.badlogic.gdx.maps.tiled.AtlasTmxMapLoader</li> </ul> </li> </ul> </li> </ul> </li> </ul> <div class="description"> <ul class="blockList"> <li class="blockList"> <hr> <br> <pre>public class <span class="strong">AtlasTmxMapLoader</span> extends <a href="../../../../../com/badlogic/gdx/assets/loaders/AsynchronousAssetLoader.html" title="class in com.badlogic.gdx.assets.loaders">AsynchronousAssetLoader</a>&lt;<a href="../../../../../com/badlogic/gdx/maps/tiled/TiledMap.html" title="class in com.badlogic.gdx.maps.tiled">TiledMap</a>,<a href="../../../../../com/badlogic/gdx/maps/tiled/AtlasTmxMapLoader.AtlasTiledMapLoaderParameters.html" title="class in com.badlogic.gdx.maps.tiled">AtlasTmxMapLoader.AtlasTiledMapLoaderParameters</a>&gt;</pre> <div class="block">A TiledMap Loader which loads tiles from a TextureAtlas instead of separate images. It requires a map-level property called 'atlas' with its value being the relative path to the TextureAtlas. The atlas must have in it indexed regions named after the tilesets used in the map. The indexes shall be local to the tileset (not the global id). Strip whitespace and rotation should not be used when creating the atlas.</div> <dl><dt><span class="strong">Author:</span></dt> <dd>Justin Shapcott, Manuel Bua</dd></dl> </li> </ul> </div> <div class="summary"> <ul class="blockList"> <li class="blockList"> <!-- ======== NESTED CLASS SUMMARY ======== --> <ul class="blockList"> <li class="blockList"><a name="nested_class_summary"> <!-- --> </a> <h3>Nested Class Summary</h3> <table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Nested Class Summary table, listing nested classes, and an explanation"> <caption><span>Nested Classes</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Class and Description</th> </tr> <tr class="altColor"> <td class="colFirst"><code>static class&nbsp;</code></td> <td class="colLast"><code><strong><a href="../../../../../com/badlogic/gdx/maps/tiled/AtlasTmxMapLoader.AtlasTiledMapLoaderParameters.html" title="class in com.badlogic.gdx.maps.tiled">AtlasTmxMapLoader.AtlasTiledMapLoaderParameters</a></strong></code>&nbsp;</td> </tr> </table> </li> </ul> <!-- =========== FIELD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="field_summary"> <!-- --> </a> <h3>Field Summary</h3> <table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Field Summary table, listing fields, and an explanation"> <caption><span>Fields</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Field and Description</th> </tr> <tr class="altColor"> <td class="colFirst"><code>protected static int</code></td> <td class="colLast"><code><strong><a href="../../../../../com/badlogic/gdx/maps/tiled/AtlasTmxMapLoader.html#FLAG_FLIP_DIAGONALLY">FLAG_FLIP_DIAGONALLY</a></strong></code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>protected static int</code></td> <td class="colLast"><code><strong><a href="../../../../../com/badlogic/gdx/maps/tiled/AtlasTmxMapLoader.html#FLAG_FLIP_HORIZONTALLY">FLAG_FLIP_HORIZONTALLY</a></strong></code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code>protected static int</code></td> <td class="colLast"><code><strong><a href="../../../../../com/badlogic/gdx/maps/tiled/AtlasTmxMapLoader.html#FLAG_FLIP_VERTICALLY">FLAG_FLIP_VERTICALLY</a></strong></code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>protected <a href="../../../../../com/badlogic/gdx/maps/tiled/TiledMap.html" title="class in com.badlogic.gdx.maps.tiled">TiledMap</a></code></td> <td class="colLast"><code><strong><a href="../../../../../com/badlogic/gdx/maps/tiled/AtlasTmxMapLoader.html#map">map</a></strong></code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code>protected int</code></td> <td class="colLast"><code><strong><a href="../../../../../com/badlogic/gdx/maps/tiled/AtlasTmxMapLoader.html#mapHeightInPixels">mapHeightInPixels</a></strong></code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>protected int</code></td> <td class="colLast"><code><strong><a href="../../../../../com/badlogic/gdx/maps/tiled/AtlasTmxMapLoader.html#mapWidthInPixels">mapWidthInPixels</a></strong></code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code>protected static int</code></td> <td class="colLast"><code><strong><a href="../../../../../com/badlogic/gdx/maps/tiled/AtlasTmxMapLoader.html#MASK_CLEAR">MASK_CLEAR</a></strong></code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>protected <a href="../../../../../com/badlogic/gdx/utils/XmlReader.Element.html" title="class in com.badlogic.gdx.utils">XmlReader.Element</a></code></td> <td class="colLast"><code><strong><a href="../../../../../com/badlogic/gdx/maps/tiled/AtlasTmxMapLoader.html#root">root</a></strong></code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code>protected <a href="../../../../../com/badlogic/gdx/utils/Array.html" title="class in com.badlogic.gdx.utils">Array</a>&lt;<a href="../../../../../com/badlogic/gdx/graphics/Texture.html" title="class in com.badlogic.gdx.graphics">Texture</a>&gt;</code></td> <td class="colLast"><code><strong><a href="../../../../../com/badlogic/gdx/maps/tiled/AtlasTmxMapLoader.html#trackedTextures">trackedTextures</a></strong></code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>protected <a href="../../../../../com/badlogic/gdx/utils/XmlReader.html" title="class in com.badlogic.gdx.utils">XmlReader</a></code></td> <td class="colLast"><code><strong><a href="../../../../../com/badlogic/gdx/maps/tiled/AtlasTmxMapLoader.html#xml">xml</a></strong></code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code>protected boolean</code></td> <td class="colLast"><code><strong><a href="../../../../../com/badlogic/gdx/maps/tiled/AtlasTmxMapLoader.html#yUp">yUp</a></strong></code>&nbsp;</td> </tr> </table> </li> </ul> <!-- ======== CONSTRUCTOR SUMMARY ======== --> <ul class="blockList"> <li class="blockList"><a name="constructor_summary"> <!-- --> </a> <h3>Constructor Summary</h3> <table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation"> <caption><span>Constructors</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colOne" scope="col">Constructor and Description</th> </tr> <tr class="altColor"> <td class="colOne"><code><strong><a href="../../../../../com/badlogic/gdx/maps/tiled/AtlasTmxMapLoader.html#AtlasTmxMapLoader()">AtlasTmxMapLoader</a></strong>()</code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colOne"><code><strong><a href="../../../../../com/badlogic/gdx/maps/tiled/AtlasTmxMapLoader.html#AtlasTmxMapLoader(com.badlogic.gdx.assets.loaders.FileHandleResolver)">AtlasTmxMapLoader</a></strong>(<a href="../../../../../com/badlogic/gdx/assets/loaders/FileHandleResolver.html" title="interface in com.badlogic.gdx.assets.loaders">FileHandleResolver</a>&nbsp;resolver)</code>&nbsp;</td> </tr> </table> </li> </ul> <!-- ========== METHOD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="method_summary"> <!-- --> </a> <h3>Method Summary</h3> <table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation"> <caption><span>Methods</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tr class="altColor"> <td class="colFirst"><code>protected <a href="../../../../../com/badlogic/gdx/maps/tiled/TiledMapTileLayer.Cell.html" title="class in com.badlogic.gdx.maps.tiled">TiledMapTileLayer.Cell</a></code></td> <td class="colLast"><code><strong><a href="../../../../../com/badlogic/gdx/maps/tiled/AtlasTmxMapLoader.html#createTileLayerCell(boolean, boolean, boolean)">createTileLayerCell</a></strong>(boolean&nbsp;flipHorizontally, boolean&nbsp;flipVertically, boolean&nbsp;flipDiagonally)</code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code><a href="../../../../../com/badlogic/gdx/utils/Array.html" title="class in com.badlogic.gdx.utils">Array</a>&lt;<a href="../../../../../com/badlogic/gdx/assets/AssetDescriptor.html" title="class in com.badlogic.gdx.assets">AssetDescriptor</a>&gt;</code></td> <td class="colLast"><code><strong><a href="../../../../../com/badlogic/gdx/maps/tiled/AtlasTmxMapLoader.html#getDependencies(java.lang.String, com.badlogic.gdx.maps.tiled.AtlasTmxMapLoader.AtlasTiledMapLoaderParameters)">getDependencies</a></strong>(java.lang.String&nbsp;fileName, <a href="../../../../../com/badlogic/gdx/maps/tiled/AtlasTmxMapLoader.AtlasTiledMapLoaderParameters.html" title="class in com.badlogic.gdx.maps.tiled">AtlasTmxMapLoader.AtlasTiledMapLoaderParameters</a>&nbsp;parameter)</code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code>static <a href="../../../../../com/badlogic/gdx/files/FileHandle.html" title="class in com.badlogic.gdx.files">FileHandle</a></code></td> <td class="colLast"><code><strong><a href="../../../../../com/badlogic/gdx/maps/tiled/AtlasTmxMapLoader.html#getRelativeFileHandle(com.badlogic.gdx.files.FileHandle, java.lang.String)">getRelativeFileHandle</a></strong>(<a href="../../../../../com/badlogic/gdx/files/FileHandle.html" title="class in com.badlogic.gdx.files">FileHandle</a>&nbsp;file, java.lang.String&nbsp;path)</code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code><a href="../../../../../com/badlogic/gdx/maps/tiled/TiledMap.html" title="class in com.badlogic.gdx.maps.tiled">TiledMap</a></code></td> <td class="colLast"><code><strong><a href="../../../../../com/badlogic/gdx/maps/tiled/AtlasTmxMapLoader.html#load(java.lang.String)">load</a></strong>(java.lang.String&nbsp;fileName)</code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code><a href="../../../../../com/badlogic/gdx/maps/tiled/TiledMap.html" title="class in com.badlogic.gdx.maps.tiled">TiledMap</a></code></td> <td class="colLast"><code><strong><a href="../../../../../com/badlogic/gdx/maps/tiled/AtlasTmxMapLoader.html#load(java.lang.String, com.badlogic.gdx.maps.tiled.AtlasTmxMapLoader.AtlasTiledMapLoaderParameters)">load</a></strong>(java.lang.String&nbsp;fileName, <a href="../../../../../com/badlogic/gdx/maps/tiled/AtlasTmxMapLoader.AtlasTiledMapLoaderParameters.html" title="class in com.badlogic.gdx.maps.tiled">AtlasTmxMapLoader.AtlasTiledMapLoaderParameters</a>&nbsp;parameter)</code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><strong><a href="../../../../../com/badlogic/gdx/maps/tiled/AtlasTmxMapLoader.html#loadAsync(com.badlogic.gdx.assets.AssetManager, java.lang.String, com.badlogic.gdx.maps.tiled.AtlasTmxMapLoader.AtlasTiledMapLoaderParameters)">loadAsync</a></strong>(<a href="../../../../../com/badlogic/gdx/assets/AssetManager.html" title="class in com.badlogic.gdx.assets">AssetManager</a>&nbsp;manager, java.lang.String&nbsp;fileName, <a href="../../../../../com/badlogic/gdx/maps/tiled/AtlasTmxMapLoader.AtlasTiledMapLoaderParameters.html" title="class in com.badlogic.gdx.maps.tiled">AtlasTmxMapLoader.AtlasTiledMapLoaderParameters</a>&nbsp;parameter)</code> <div class="block">Loads the non-OpenGL part of the asset and injects any dependencies of the asset into the AssetManager.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>protected <a href="../../../../../com/badlogic/gdx/files/FileHandle.html" title="class in com.badlogic.gdx.files">FileHandle</a></code></td> <td class="colLast"><code><strong><a href="../../../../../com/badlogic/gdx/maps/tiled/AtlasTmxMapLoader.html#loadAtlas(com.badlogic.gdx.utils.XmlReader.Element, com.badlogic.gdx.files.FileHandle)">loadAtlas</a></strong>(<a href="../../../../../com/badlogic/gdx/utils/XmlReader.Element.html" title="class in com.badlogic.gdx.utils">XmlReader.Element</a>&nbsp;root, <a href="../../../../../com/badlogic/gdx/files/FileHandle.html" title="class in com.badlogic.gdx.files">FileHandle</a>&nbsp;tmxFile)</code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>protected <a href="../../../../../com/badlogic/gdx/maps/tiled/TiledMap.html" title="class in com.badlogic.gdx.maps.tiled">TiledMap</a></code></td> <td class="colLast"><code><strong><a href="../../../../../com/badlogic/gdx/maps/tiled/AtlasTmxMapLoader.html#loadMap(com.badlogic.gdx.utils.XmlReader.Element, com.badlogic.gdx.files.FileHandle, com.badlogic.gdx.maps.tiled.AtlasTmxMapLoader.AtlasResolver, com.badlogic.gdx.maps.tiled.AtlasTmxMapLoader.AtlasTiledMapLoaderParameters)">loadMap</a></strong>(<a href="../../../../../com/badlogic/gdx/utils/XmlReader.Element.html" title="class in com.badlogic.gdx.utils">XmlReader.Element</a>&nbsp;root, <a href="../../../../../com/badlogic/gdx/files/FileHandle.html" title="class in com.badlogic.gdx.files">FileHandle</a>&nbsp;tmxFile, com.badlogic.gdx.maps.tiled.AtlasTmxMapLoader.AtlasResolver&nbsp;resolver, <a href="../../../../../com/badlogic/gdx/maps/tiled/AtlasTmxMapLoader.AtlasTiledMapLoaderParameters.html" title="class in com.badlogic.gdx.maps.tiled">AtlasTmxMapLoader.AtlasTiledMapLoaderParameters</a>&nbsp;parameter)</code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code>protected void</code></td> <td class="colLast"><code><strong><a href="../../../../../com/badlogic/gdx/maps/tiled/AtlasTmxMapLoader.html#loadObject(com.badlogic.gdx.maps.MapLayer, com.badlogic.gdx.utils.XmlReader.Element)">loadObject</a></strong>(<a href="../../../../../com/badlogic/gdx/maps/MapLayer.html" title="class in com.badlogic.gdx.maps">MapLayer</a>&nbsp;layer, <a href="../../../../../com/badlogic/gdx/utils/XmlReader.Element.html" title="class in com.badlogic.gdx.utils">XmlReader.Element</a>&nbsp;element)</code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>protected void</code></td> <td class="colLast"><code><strong><a href="../../../../../com/badlogic/gdx/maps/tiled/AtlasTmxMapLoader.html#loadObjectGroup(com.badlogic.gdx.maps.tiled.TiledMap, com.badlogic.gdx.utils.XmlReader.Element)">loadObjectGroup</a></strong>(<a href="../../../../../com/badlogic/gdx/maps/tiled/TiledMap.html" title="class in com.badlogic.gdx.maps.tiled">TiledMap</a>&nbsp;map, <a href="../../../../../com/badlogic/gdx/utils/XmlReader.Element.html" title="class in com.badlogic.gdx.utils">XmlReader.Element</a>&nbsp;element)</code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code>protected void</code></td> <td class="colLast"><code><strong><a href="../../../../../com/badlogic/gdx/maps/tiled/AtlasTmxMapLoader.html#loadProperties(com.badlogic.gdx.maps.MapProperties, com.badlogic.gdx.utils.XmlReader.Element)">loadProperties</a></strong>(<a href="../../../../../com/badlogic/gdx/maps/MapProperties.html" title="class in com.badlogic.gdx.maps">MapProperties</a>&nbsp;properties, <a href="../../../../../com/badlogic/gdx/utils/XmlReader.Element.html" title="class in com.badlogic.gdx.utils">XmlReader.Element</a>&nbsp;element)</code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code><a href="../../../../../com/badlogic/gdx/maps/tiled/TiledMap.html" title="class in com.badlogic.gdx.maps.tiled">TiledMap</a></code></td> <td class="colLast"><code><strong><a href="../../../../../com/badlogic/gdx/maps/tiled/AtlasTmxMapLoader.html#loadSync(com.badlogic.gdx.assets.AssetManager, java.lang.String, com.badlogic.gdx.maps.tiled.AtlasTmxMapLoader.AtlasTiledMapLoaderParameters)">loadSync</a></strong>(<a href="../../../../../com/badlogic/gdx/assets/AssetManager.html" title="class in com.badlogic.gdx.assets">AssetManager</a>&nbsp;manager, java.lang.String&nbsp;fileName, <a href="../../../../../com/badlogic/gdx/maps/tiled/AtlasTmxMapLoader.AtlasTiledMapLoaderParameters.html" title="class in com.badlogic.gdx.maps.tiled">AtlasTmxMapLoader.AtlasTiledMapLoaderParameters</a>&nbsp;parameter)</code> <div class="block">Loads th</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>protected void</code></td> <td class="colLast"><code><strong><a href="../../../../../com/badlogic/gdx/maps/tiled/AtlasTmxMapLoader.html#loadTileLayer(com.badlogic.gdx.maps.tiled.TiledMap, com.badlogic.gdx.utils.XmlReader.Element)">loadTileLayer</a></strong>(<a href="../../../../../com/badlogic/gdx/maps/tiled/TiledMap.html" title="class in com.badlogic.gdx.maps.tiled">TiledMap</a>&nbsp;map, <a href="../../../../../com/badlogic/gdx/utils/XmlReader.Element.html" title="class in com.badlogic.gdx.utils">XmlReader.Element</a>&nbsp;element)</code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>protected void</code></td> <td class="colLast"><code><strong><a href="../../../../../com/badlogic/gdx/maps/tiled/AtlasTmxMapLoader.html#loadTileset(com.badlogic.gdx.maps.tiled.TiledMap, com.badlogic.gdx.utils.XmlReader.Element, com.badlogic.gdx.files.FileHandle, com.badlogic.gdx.maps.tiled.AtlasTmxMapLoader.AtlasResolver, com.badlogic.gdx.maps.tiled.AtlasTmxMapLoader.AtlasTiledMapLoaderParameters)">loadTileset</a></strong>(<a href="../../../../../com/badlogic/gdx/maps/tiled/TiledMap.html" title="class in com.badlogic.gdx.maps.tiled">TiledMap</a>&nbsp;map, <a href="../../../../../com/badlogic/gdx/utils/XmlReader.Element.html" title="class in com.badlogic.gdx.utils">XmlReader.Element</a>&nbsp;element, <a href="../../../../../com/badlogic/gdx/files/FileHandle.html" title="class in com.badlogic.gdx.files">FileHandle</a>&nbsp;tmxFile, com.badlogic.gdx.maps.tiled.AtlasTmxMapLoader.AtlasResolver&nbsp;resolver, <a href="../../../../../com/badlogic/gdx/maps/tiled/AtlasTmxMapLoader.AtlasTiledMapLoaderParameters.html" title="class in com.badlogic.gdx.maps.tiled">AtlasTmxMapLoader.AtlasTiledMapLoaderParameters</a>&nbsp;parameter)</code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code>protected static int</code></td> <td class="colLast"><code><strong><a href="../../../../../com/badlogic/gdx/maps/tiled/AtlasTmxMapLoader.html#unsignedByteToInt(byte)">unsignedByteToInt</a></strong>(byte&nbsp;b)</code>&nbsp;</td> </tr> </table> <ul class="blockList"> <li class="blockList"><a name="methods_inherited_from_class_com.badlogic.gdx.assets.loaders.AssetLoader"> <!-- --> </a> <h3>Methods inherited from class&nbsp;com.badlogic.gdx.assets.loaders.<a href="../../../../../com/badlogic/gdx/assets/loaders/AssetLoader.html" title="class in com.badlogic.gdx.assets.loaders">AssetLoader</a></h3> <code><a href="../../../../../com/badlogic/gdx/assets/loaders/AssetLoader.html#resolve(java.lang.String)">resolve</a></code></li> </ul> <ul class="blockList"> <li class="blockList"><a name="methods_inherited_from_class_java.lang.Object"> <!-- --> </a> <h3>Methods inherited from class&nbsp;java.lang.Object</h3> <code>clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</code></li> </ul> </li> </ul> </li> </ul> </div> <div class="details"> <ul class="blockList"> <li class="blockList"> <!-- ============ FIELD DETAIL =========== --> <ul class="blockList"> <li class="blockList"><a name="field_detail"> <!-- --> </a> <h3>Field Detail</h3> <a name="FLAG_FLIP_HORIZONTALLY"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>FLAG_FLIP_HORIZONTALLY</h4> <pre>protected static final&nbsp;int FLAG_FLIP_HORIZONTALLY</pre> <dl><dt><span class="strong">See Also:</span></dt><dd><a href="../../../../../constant-values.html#com.badlogic.gdx.maps.tiled.AtlasTmxMapLoader.FLAG_FLIP_HORIZONTALLY">Constant Field Values</a></dd></dl> </li> </ul> <a name="FLAG_FLIP_VERTICALLY"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>FLAG_FLIP_VERTICALLY</h4> <pre>protected static final&nbsp;int FLAG_FLIP_VERTICALLY</pre> <dl><dt><span class="strong">See Also:</span></dt><dd><a href="../../../../../constant-values.html#com.badlogic.gdx.maps.tiled.AtlasTmxMapLoader.FLAG_FLIP_VERTICALLY">Constant Field Values</a></dd></dl> </li> </ul> <a name="FLAG_FLIP_DIAGONALLY"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>FLAG_FLIP_DIAGONALLY</h4> <pre>protected static final&nbsp;int FLAG_FLIP_DIAGONALLY</pre> <dl><dt><span class="strong">See Also:</span></dt><dd><a href="../../../../../constant-values.html#com.badlogic.gdx.maps.tiled.AtlasTmxMapLoader.FLAG_FLIP_DIAGONALLY">Constant Field Values</a></dd></dl> </li> </ul> <a name="MASK_CLEAR"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>MASK_CLEAR</h4> <pre>protected static final&nbsp;int MASK_CLEAR</pre> <dl><dt><span class="strong">See Also:</span></dt><dd><a href="../../../../../constant-values.html#com.badlogic.gdx.maps.tiled.AtlasTmxMapLoader.MASK_CLEAR">Constant Field Values</a></dd></dl> </li> </ul> <a name="xml"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>xml</h4> <pre>protected&nbsp;<a href="../../../../../com/badlogic/gdx/utils/XmlReader.html" title="class in com.badlogic.gdx.utils">XmlReader</a> xml</pre> </li> </ul> <a name="root"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>root</h4> <pre>protected&nbsp;<a href="../../../../../com/badlogic/gdx/utils/XmlReader.Element.html" title="class in com.badlogic.gdx.utils">XmlReader.Element</a> root</pre> </li> </ul> <a name="yUp"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>yUp</h4> <pre>protected&nbsp;boolean yUp</pre> </li> </ul> <a name="mapWidthInPixels"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>mapWidthInPixels</h4> <pre>protected&nbsp;int mapWidthInPixels</pre> </li> </ul> <a name="mapHeightInPixels"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>mapHeightInPixels</h4> <pre>protected&nbsp;int mapHeightInPixels</pre> </li> </ul> <a name="map"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>map</h4> <pre>protected&nbsp;<a href="../../../../../com/badlogic/gdx/maps/tiled/TiledMap.html" title="class in com.badlogic.gdx.maps.tiled">TiledMap</a> map</pre> </li> </ul> <a name="trackedTextures"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>trackedTextures</h4> <pre>protected&nbsp;<a href="../../../../../com/badlogic/gdx/utils/Array.html" title="class in com.badlogic.gdx.utils">Array</a>&lt;<a href="../../../../../com/badlogic/gdx/graphics/Texture.html" title="class in com.badlogic.gdx.graphics">Texture</a>&gt; trackedTextures</pre> </li> </ul> </li> </ul> <!-- ========= CONSTRUCTOR DETAIL ======== --> <ul class="blockList"> <li class="blockList"><a name="constructor_detail"> <!-- --> </a> <h3>Constructor Detail</h3> <a name="AtlasTmxMapLoader()"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>AtlasTmxMapLoader</h4> <pre>public&nbsp;AtlasTmxMapLoader()</pre> </li> </ul> <a name="AtlasTmxMapLoader(com.badlogic.gdx.assets.loaders.FileHandleResolver)"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>AtlasTmxMapLoader</h4> <pre>public&nbsp;AtlasTmxMapLoader(<a href="../../../../../com/badlogic/gdx/assets/loaders/FileHandleResolver.html" title="interface in com.badlogic.gdx.assets.loaders">FileHandleResolver</a>&nbsp;resolver)</pre> </li> </ul> </li> </ul> <!-- ============ METHOD DETAIL ========== --> <ul class="blockList"> <li class="blockList"><a name="method_detail"> <!-- --> </a> <h3>Method Detail</h3> <a name="load(java.lang.String)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>load</h4> <pre>public&nbsp;<a href="../../../../../com/badlogic/gdx/maps/tiled/TiledMap.html" title="class in com.badlogic.gdx.maps.tiled">TiledMap</a>&nbsp;load(java.lang.String&nbsp;fileName)</pre> </li> </ul> <a name="getDependencies(java.lang.String, com.badlogic.gdx.maps.tiled.AtlasTmxMapLoader.AtlasTiledMapLoaderParameters)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>getDependencies</h4> <pre>public&nbsp;<a href="../../../../../com/badlogic/gdx/utils/Array.html" title="class in com.badlogic.gdx.utils">Array</a>&lt;<a href="../../../../../com/badlogic/gdx/assets/AssetDescriptor.html" title="class in com.badlogic.gdx.assets">AssetDescriptor</a>&gt;&nbsp;getDependencies(java.lang.String&nbsp;fileName, <a href="../../../../../com/badlogic/gdx/maps/tiled/AtlasTmxMapLoader.AtlasTiledMapLoaderParameters.html" title="class in com.badlogic.gdx.maps.tiled">AtlasTmxMapLoader.AtlasTiledMapLoaderParameters</a>&nbsp;parameter)</pre> <dl> <dt><strong>Specified by:</strong></dt> <dd><code><a href="../../../../../com/badlogic/gdx/assets/loaders/AssetLoader.html#getDependencies(java.lang.String, P)">getDependencies</a></code>&nbsp;in class&nbsp;<code><a href="../../../../../com/badlogic/gdx/assets/loaders/AssetLoader.html" title="class in com.badlogic.gdx.assets.loaders">AssetLoader</a>&lt;<a href="../../../../../com/badlogic/gdx/maps/tiled/TiledMap.html" title="class in com.badlogic.gdx.maps.tiled">TiledMap</a>,<a href="../../../../../com/badlogic/gdx/maps/tiled/AtlasTmxMapLoader.AtlasTiledMapLoaderParameters.html" title="class in com.badlogic.gdx.maps.tiled">AtlasTmxMapLoader.AtlasTiledMapLoaderParameters</a>&gt;</code></dd> <dt><span class="strong">Parameters:</span></dt><dd><code>fileName</code> - name of the asset to load</dd><dd><code>parameter</code> - parameters for loading the asset</dd> <dt><span class="strong">Returns:</span></dt><dd>other assets that the asset depends on and need to be loaded first or null if there are no dependencies.</dd></dl> </li> </ul> <a name="load(java.lang.String, com.badlogic.gdx.maps.tiled.AtlasTmxMapLoader.AtlasTiledMapLoaderParameters)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>load</h4> <pre>public&nbsp;<a href="../../../../../com/badlogic/gdx/maps/tiled/TiledMap.html" title="class in com.badlogic.gdx.maps.tiled">TiledMap</a>&nbsp;load(java.lang.String&nbsp;fileName, <a href="../../../../../com/badlogic/gdx/maps/tiled/AtlasTmxMapLoader.AtlasTiledMapLoaderParameters.html" title="class in com.badlogic.gdx.maps.tiled">AtlasTmxMapLoader.AtlasTiledMapLoaderParameters</a>&nbsp;parameter)</pre> </li> </ul> <a name="loadAtlas(com.badlogic.gdx.utils.XmlReader.Element, com.badlogic.gdx.files.FileHandle)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>loadAtlas</h4> <pre>protected&nbsp;<a href="../../../../../com/badlogic/gdx/files/FileHandle.html" title="class in com.badlogic.gdx.files">FileHandle</a>&nbsp;loadAtlas(<a href="../../../../../com/badlogic/gdx/utils/XmlReader.Element.html" title="class in com.badlogic.gdx.utils">XmlReader.Element</a>&nbsp;root, <a href="../../../../../com/badlogic/gdx/files/FileHandle.html" title="class in com.badlogic.gdx.files">FileHandle</a>&nbsp;tmxFile) throws java.io.IOException</pre> <dl><dt><span class="strong">Throws:</span></dt> <dd><code>java.io.IOException</code></dd></dl> </li> </ul> <a name="loadAsync(com.badlogic.gdx.assets.AssetManager, java.lang.String, com.badlogic.gdx.maps.tiled.AtlasTmxMapLoader.AtlasTiledMapLoaderParameters)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>loadAsync</h4> <pre>public&nbsp;void&nbsp;loadAsync(<a href="../../../../../com/badlogic/gdx/assets/AssetManager.html" title="class in com.badlogic.gdx.assets">AssetManager</a>&nbsp;manager, java.lang.String&nbsp;fileName, <a href="../../../../../com/badlogic/gdx/maps/tiled/AtlasTmxMapLoader.AtlasTiledMapLoaderParameters.html" title="class in com.badlogic.gdx.maps.tiled">AtlasTmxMapLoader.AtlasTiledMapLoaderParameters</a>&nbsp;parameter)</pre> <div class="block"><strong>Description copied from class:&nbsp;<code><a href="../../../../../com/badlogic/gdx/assets/loaders/AsynchronousAssetLoader.html#loadAsync(com.badlogic.gdx.assets.AssetManager, java.lang.String, P)">AsynchronousAssetLoader</a></code></strong></div> <div class="block">Loads the non-OpenGL part of the asset and injects any dependencies of the asset into the AssetManager.</div> <dl> <dt><strong>Specified by:</strong></dt> <dd><code><a href="../../../../../com/badlogic/gdx/assets/loaders/AsynchronousAssetLoader.html#loadAsync(com.badlogic.gdx.assets.AssetManager, java.lang.String, P)">loadAsync</a></code>&nbsp;in class&nbsp;<code><a href="../../../../../com/badlogic/gdx/assets/loaders/AsynchronousAssetLoader.html" title="class in com.badlogic.gdx.assets.loaders">AsynchronousAssetLoader</a>&lt;<a href="../../../../../com/badlogic/gdx/maps/tiled/TiledMap.html" title="class in com.badlogic.gdx.maps.tiled">TiledMap</a>,<a href="../../../../../com/badlogic/gdx/maps/tiled/AtlasTmxMapLoader.AtlasTiledMapLoaderParameters.html" title="class in com.badlogic.gdx.maps.tiled">AtlasTmxMapLoader.AtlasTiledMapLoaderParameters</a>&gt;</code></dd> <dd><code>fileName</code> - the name of the asset to load</dd><dd><code>parameter</code> - the parameters to use for loading the asset</dd></dl> </li> </ul> <a name="loadSync(com.badlogic.gdx.assets.AssetManager, java.lang.String, com.badlogic.gdx.maps.tiled.AtlasTmxMapLoader.AtlasTiledMapLoaderParameters)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>loadSync</h4> <pre>public&nbsp;<a href="../../../../../com/badlogic/gdx/maps/tiled/TiledMap.html" title="class in com.badlogic.gdx.maps.tiled">TiledMap</a>&nbsp;loadSync(<a href="../../../../../com/badlogic/gdx/assets/AssetManager.html" title="class in com.badlogic.gdx.assets">AssetManager</a>&nbsp;manager, java.lang.String&nbsp;fileName, <a href="../../../../../com/badlogic/gdx/maps/tiled/AtlasTmxMapLoader.AtlasTiledMapLoaderParameters.html" title="class in com.badlogic.gdx.maps.tiled">AtlasTmxMapLoader.AtlasTiledMapLoaderParameters</a>&nbsp;parameter)</pre> <div class="block"><strong>Description copied from class:&nbsp;<code><a href="../../../../../com/badlogic/gdx/assets/loaders/AsynchronousAssetLoader.html#loadSync(com.badlogic.gdx.assets.AssetManager, java.lang.String, P)">AsynchronousAssetLoader</a></code></strong></div> <div class="block">Loads th</div> <dl> <dt><strong>Specified by:</strong></dt> <dd><code><a href="../../../../../com/badlogic/gdx/assets/loaders/AsynchronousAssetLoader.html#loadSync(com.badlogic.gdx.assets.AssetManager, java.lang.String, P)">loadSync</a></code>&nbsp;in class&nbsp;<code><a href="../../../../../com/badlogic/gdx/assets/loaders/AsynchronousAssetLoader.html" title="class in com.badlogic.gdx.assets.loaders">AsynchronousAssetLoader</a>&lt;<a href="../../../../../com/badlogic/gdx/maps/tiled/TiledMap.html" title="class in com.badlogic.gdx.maps.tiled">TiledMap</a>,<a href="../../../../../com/badlogic/gdx/maps/tiled/AtlasTmxMapLoader.AtlasTiledMapLoaderParameters.html" title="class in com.badlogic.gdx.maps.tiled">AtlasTmxMapLoader.AtlasTiledMapLoaderParameters</a>&gt;</code></dd> </dl> </li> </ul> <a name="loadMap(com.badlogic.gdx.utils.XmlReader.Element, com.badlogic.gdx.files.FileHandle, com.badlogic.gdx.maps.tiled.AtlasTmxMapLoader.AtlasResolver, com.badlogic.gdx.maps.tiled.AtlasTmxMapLoader.AtlasTiledMapLoaderParameters)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>loadMap</h4> <pre>protected&nbsp;<a href="../../../../../com/badlogic/gdx/maps/tiled/TiledMap.html" title="class in com.badlogic.gdx.maps.tiled">TiledMap</a>&nbsp;loadMap(<a href="../../../../../com/badlogic/gdx/utils/XmlReader.Element.html" title="class in com.badlogic.gdx.utils">XmlReader.Element</a>&nbsp;root, <a href="../../../../../com/badlogic/gdx/files/FileHandle.html" title="class in com.badlogic.gdx.files">FileHandle</a>&nbsp;tmxFile, com.badlogic.gdx.maps.tiled.AtlasTmxMapLoader.AtlasResolver&nbsp;resolver, <a href="../../../../../com/badlogic/gdx/maps/tiled/AtlasTmxMapLoader.AtlasTiledMapLoaderParameters.html" title="class in com.badlogic.gdx.maps.tiled">AtlasTmxMapLoader.AtlasTiledMapLoaderParameters</a>&nbsp;parameter)</pre> </li> </ul> <a name="loadTileset(com.badlogic.gdx.maps.tiled.TiledMap, com.badlogic.gdx.utils.XmlReader.Element, com.badlogic.gdx.files.FileHandle, com.badlogic.gdx.maps.tiled.AtlasTmxMapLoader.AtlasResolver, com.badlogic.gdx.maps.tiled.AtlasTmxMapLoader.AtlasTiledMapLoaderParameters)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>loadTileset</h4> <pre>protected&nbsp;void&nbsp;loadTileset(<a href="../../../../../com/badlogic/gdx/maps/tiled/TiledMap.html" title="class in com.badlogic.gdx.maps.tiled">TiledMap</a>&nbsp;map, <a href="../../../../../com/badlogic/gdx/utils/XmlReader.Element.html" title="class in com.badlogic.gdx.utils">XmlReader.Element</a>&nbsp;element, <a href="../../../../../com/badlogic/gdx/files/FileHandle.html" title="class in com.badlogic.gdx.files">FileHandle</a>&nbsp;tmxFile, com.badlogic.gdx.maps.tiled.AtlasTmxMapLoader.AtlasResolver&nbsp;resolver, <a href="../../../../../com/badlogic/gdx/maps/tiled/AtlasTmxMapLoader.AtlasTiledMapLoaderParameters.html" title="class in com.badlogic.gdx.maps.tiled">AtlasTmxMapLoader.AtlasTiledMapLoaderParameters</a>&nbsp;parameter)</pre> </li> </ul> <a name="loadTileLayer(com.badlogic.gdx.maps.tiled.TiledMap, com.badlogic.gdx.utils.XmlReader.Element)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>loadTileLayer</h4> <pre>protected&nbsp;void&nbsp;loadTileLayer(<a href="../../../../../com/badlogic/gdx/maps/tiled/TiledMap.html" title="class in com.badlogic.gdx.maps.tiled">TiledMap</a>&nbsp;map, <a href="../../../../../com/badlogic/gdx/utils/XmlReader.Element.html" title="class in com.badlogic.gdx.utils">XmlReader.Element</a>&nbsp;element)</pre> </li> </ul> <a name="loadObjectGroup(com.badlogic.gdx.maps.tiled.TiledMap, com.badlogic.gdx.utils.XmlReader.Element)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>loadObjectGroup</h4> <pre>protected&nbsp;void&nbsp;loadObjectGroup(<a href="../../../../../com/badlogic/gdx/maps/tiled/TiledMap.html" title="class in com.badlogic.gdx.maps.tiled">TiledMap</a>&nbsp;map, <a href="../../../../../com/badlogic/gdx/utils/XmlReader.Element.html" title="class in com.badlogic.gdx.utils">XmlReader.Element</a>&nbsp;element)</pre> </li> </ul> <a name="loadObject(com.badlogic.gdx.maps.MapLayer, com.badlogic.gdx.utils.XmlReader.Element)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>loadObject</h4> <pre>protected&nbsp;void&nbsp;loadObject(<a href="../../../../../com/badlogic/gdx/maps/MapLayer.html" title="class in com.badlogic.gdx.maps">MapLayer</a>&nbsp;layer, <a href="../../../../../com/badlogic/gdx/utils/XmlReader.Element.html" title="class in com.badlogic.gdx.utils">XmlReader.Element</a>&nbsp;element)</pre> </li> </ul> <a name="loadProperties(com.badlogic.gdx.maps.MapProperties, com.badlogic.gdx.utils.XmlReader.Element)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>loadProperties</h4> <pre>protected&nbsp;void&nbsp;loadProperties(<a href="../../../../../com/badlogic/gdx/maps/MapProperties.html" title="class in com.badlogic.gdx.maps">MapProperties</a>&nbsp;properties, <a href="../../../../../com/badlogic/gdx/utils/XmlReader.Element.html" title="class in com.badlogic.gdx.utils">XmlReader.Element</a>&nbsp;element)</pre> </li> </ul> <a name="createTileLayerCell(boolean, boolean, boolean)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>createTileLayerCell</h4> <pre>protected&nbsp;<a href="../../../../../com/badlogic/gdx/maps/tiled/TiledMapTileLayer.Cell.html" title="class in com.badlogic.gdx.maps.tiled">TiledMapTileLayer.Cell</a>&nbsp;createTileLayerCell(boolean&nbsp;flipHorizontally, boolean&nbsp;flipVertically, boolean&nbsp;flipDiagonally)</pre> </li> </ul> <a name="getRelativeFileHandle(com.badlogic.gdx.files.FileHandle, java.lang.String)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>getRelativeFileHandle</h4> <pre>public static&nbsp;<a href="../../../../../com/badlogic/gdx/files/FileHandle.html" title="class in com.badlogic.gdx.files">FileHandle</a>&nbsp;getRelativeFileHandle(<a href="../../../../../com/badlogic/gdx/files/FileHandle.html" title="class in com.badlogic.gdx.files">FileHandle</a>&nbsp;file, java.lang.String&nbsp;path)</pre> </li> </ul> <a name="unsignedByteToInt(byte)"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>unsignedByteToInt</h4> <pre>protected static&nbsp;int&nbsp;unsignedByteToInt(byte&nbsp;b)</pre> </li> </ul> </li> </ul> </li> </ul> </div> </div> <!-- ========= END OF CLASS DATA ========= --> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="class-use/AtlasTmxMapLoader.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-all.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> <div class="aboutLanguage"><em>libgdx API</em></div> </div> <div class="subNav"> <ul class="navList"> <li>Prev Class</li> <li><a href="../../../../../com/badlogic/gdx/maps/tiled/AtlasTmxMapLoader.AtlasTiledMapLoaderParameters.html" title="class in com.badlogic.gdx.maps.tiled"><span class="strong">Next Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?com/badlogic/gdx/maps/tiled/AtlasTmxMapLoader.html" target="_top">Frames</a></li> <li><a href="AtlasTmxMapLoader.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li><a href="#nested_class_summary">Nested</a>&nbsp;|&nbsp;</li> <li><a href="#field_summary">Field</a>&nbsp;|&nbsp;</li> <li><a href="#constructor_summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method_summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li><a href="#field_detail">Field</a>&nbsp;|&nbsp;</li> <li><a href="#constructor_detail">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method_detail">Method</a></li> </ul> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small> <div style="font-size:9pt"><i> Copyright &copy; 2010-2013 Mario Zechner ([email protected]), Nathan Sweet ([email protected]) </i></div> </small></p> </body> </html>
leszekuchacz/Leszek-Uchacz
docs/api/com/badlogic/gdx/maps/tiled/AtlasTmxMapLoader.html
HTML
apache-2.0
44,497
<?php declare(strict_types=1); namespace OpenTelemetry\Tests\Unit\Contrib; use AssertWell\PHPUnitGlobalState\EnvironmentVariables; use Grpc\UnaryCall; use Mockery; use Mockery\MockInterface; use OpenTelemetry\Contrib\OtlpGrpc\Exporter; use Opentelemetry\Proto\Collector\Trace\V1\TraceServiceClient; use OpenTelemetry\SDK\Trace\SpanExporterInterface; use OpenTelemetry\Tests\Unit\SDK\Trace\SpanExporter\AbstractExporterTest; use OpenTelemetry\Tests\Unit\SDK\Util\SpanData; use org\bovigo\vfs\vfsStream; /** * @covers OpenTelemetry\Contrib\OtlpGrpc\Exporter */ class OTLPGrpcExporterTest extends AbstractExporterTest { use EnvironmentVariables; public function createExporter(): SpanExporterInterface { return new Exporter(); } public function tearDown(): void { $this->restoreEnvironmentVariables(); } /** * @psalm-suppress UndefinedConstant */ public function test_exporter_happy_path(): void { $exporter = new Exporter( //These first parameters were copied from the constructor's default values 'localhost:4317', true, '', '', false, 10, $this->createMockTraceServiceClient([ 'expectations' => [ 'num_spans' => 1, ], 'return_values' => [ 'status_code' => \Grpc\STATUS_OK, ], ]) ); $exporterStatusCode = $exporter->export([new SpanData()]); $this->assertSame(SpanExporterInterface::STATUS_SUCCESS, $exporterStatusCode); } public function test_exporter_unexpected_grpc_response_status(): void { $exporter = new Exporter( //These first parameters were copied from the constructor's default values 'localhost:4317', true, '', '', false, 10, $this->createMockTraceServiceClient([ 'expectations' => [ 'num_spans' => 1, ], 'return_values' => [ 'status_code' => 'An unexpected status', ], ]) ); $exporterStatusCode = $exporter->export([new SpanData()]); $this->assertSame(SpanExporterInterface::STATUS_FAILED_NOT_RETRYABLE, $exporterStatusCode); } public function test_exporter_grpc_responds_as_unavailable(): void { $this->assertEquals(SpanExporterInterface::STATUS_FAILED_RETRYABLE, (new Exporter())->export([new SpanData()])); } public function test_set_headers_with_environment_variables(): void { $this->setEnvironmentVariable('OTEL_EXPORTER_OTLP_HEADERS', 'x-aaa=foo,x-bbb=barf'); $exporter = new Exporter(); $this->assertEquals(['x-aaa' => 'foo', 'x-bbb' => 'barf'], $exporter->getHeaders()); } public function test_set_header(): void { $exporter = new Exporter(); $exporter->setHeader('foo', 'bar'); $headers = $exporter->getHeaders(); $this->assertArrayHasKey('foo', $headers); $this->assertEquals('bar', $headers['foo']); } public function test_set_headers_in_constructor(): void { $exporter = new Exporter('localhost:4317', true, '', 'x-aaa=foo,x-bbb=bar'); $this->assertEquals(['x-aaa' => 'foo', 'x-bbb' => 'bar'], $exporter->getHeaders()); $exporter->setHeader('key', 'value'); $this->assertEquals(['x-aaa' => 'foo', 'x-bbb' => 'bar', 'key' => 'value'], $exporter->getHeaders()); } public function test_should_be_ok_to_exporter_empty_spans_collection(): void { $this->assertEquals( SpanExporterInterface::STATUS_SUCCESS, (new Exporter('test.otlp'))->export([]) ); } private function isInsecure(Exporter $exporter) : bool { $reflection = new \ReflectionClass($exporter); $property = $reflection->getProperty('insecure'); $property->setAccessible(true); return $property->getValue($exporter); } public function test_client_options(): void { // default options $exporter = new Exporter('localhost:4317'); $opts = $exporter->getClientOptions(); $this->assertEquals(10, $opts['timeout']); $this->assertTrue($this->isInsecure($exporter)); $this->assertArrayNotHasKey('grpc.default_compression_algorithm', $opts); // method args $exporter = new Exporter('localhost:4317', false, '', '', true, 5); $opts = $exporter->getClientOptions(); $this->assertEquals(5, $opts['timeout']); $this->assertFalse($this->isInsecure($exporter)); $this->assertEquals(2, $opts['grpc.default_compression_algorithm']); // env vars $this->setEnvironmentVariable('OTEL_EXPORTER_OTLP_TIMEOUT', '1'); $this->setEnvironmentVariable('OTEL_EXPORTER_OTLP_COMPRESSION', 'gzip'); $this->setEnvironmentVariable('OTEL_EXPORTER_OTLP_INSECURE', 'false'); $exporter = new Exporter('localhost:4317'); $opts = $exporter->getClientOptions(); $this->assertEquals(1, $opts['timeout']); $this->assertFalse($this->isInsecure($exporter)); $this->assertEquals(2, $opts['grpc.default_compression_algorithm']); } /** * @psalm-suppress PossiblyUndefinedMethod * @psalm-suppress UndefinedMagicMethod */ private function createMockTraceServiceClient(array $options = []) { [ 'expectations' => [ 'num_spans' => $expectedNumSpans, ], 'return_values' => [ 'status_code' => $statusCode, ] ] = $options; /** @var MockInterface&TraceServiceClient */ $mockClient = Mockery::mock(TraceServiceClient::class) ->allows('Export') ->withArgs(function ($request) use ($expectedNumSpans) { return (count($request->getResourceSpans()) === $expectedNumSpans); }) ->andReturns( Mockery::mock(UnaryCall::class) ->allows('wait') ->andReturns( [ 'unused response data', new class($statusCode) { public $code; public function __construct($code) { $this->code = $code; } }, ] ) ->getMock() ) ->getMock(); return $mockClient; } public function test_from_connection_string(): void { // @phpstan-ignore-next-line $this->assertNotSame( Exporter::fromConnectionString(), Exporter::fromConnectionString() ); } public function test_create_with_cert_file(): void { $certDir = 'var'; $certFile = 'file.cert'; vfsStream::setup($certDir); $certPath = vfsStream::url(sprintf('%s/%s', $certDir, $certFile)); file_put_contents($certPath, 'foo'); $this->setEnvironmentVariable('OTEL_EXPORTER_OTLP_INSECURE', 'false'); $this->setEnvironmentVariable('OTEL_EXPORTER_OTLP_CERTIFICATE', $certPath); $this->assertSame( $certPath, (new Exporter())->getCertificateFile() ); } }
open-telemetry/opentelemetry-php
tests/Unit/Contrib/OTLPGrpcExporterTest.php
PHP
apache-2.0
7,876
/* * MMX optimized DSP utils * Copyright (c) 2000, 2001 Fabrice Bellard * Copyright (c) 2002-2004 Michael Niedermayer <[email protected]> * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * MMX optimization by Nick Kurshev <[email protected]> */ #include "libavutil/x86_cpu.h" #include "libavcodec/dsputil.h" #include "libavcodec/h264dsp.h" #include "libavcodec/mpegvideo.h" #include "libavcodec/simple_idct.h" #include "dsputil_mmx.h" #include "vp3dsp_mmx.h" #include "vp3dsp_sse2.h" #include "vp6dsp_mmx.h" #include "vp6dsp_sse2.h" #include "idct_xvid.h" //#undef NDEBUG //#include <assert.h> int mm_flags; /* multimedia extension flags */ /* pixel operations */ DECLARE_ALIGNED(8, const uint64_t, ff_bone) = 0x0101010101010101ULL; DECLARE_ALIGNED(8, const uint64_t, ff_wtwo) = 0x0002000200020002ULL; DECLARE_ALIGNED(16, const uint64_t, ff_pdw_80000000)[2] = {0x8000000080000000ULL, 0x8000000080000000ULL}; DECLARE_ALIGNED(8, const uint64_t, ff_pw_3 ) = 0x0003000300030003ULL; DECLARE_ALIGNED(8, const uint64_t, ff_pw_4 ) = 0x0004000400040004ULL; DECLARE_ALIGNED(16, const xmm_reg, ff_pw_5 ) = {0x0005000500050005ULL, 0x0005000500050005ULL}; DECLARE_ALIGNED(16, const xmm_reg, ff_pw_8 ) = {0x0008000800080008ULL, 0x0008000800080008ULL}; DECLARE_ALIGNED(8, const uint64_t, ff_pw_15 ) = 0x000F000F000F000FULL; DECLARE_ALIGNED(16, const xmm_reg, ff_pw_16 ) = {0x0010001000100010ULL, 0x0010001000100010ULL}; DECLARE_ALIGNED(8, const uint64_t, ff_pw_20 ) = 0x0014001400140014ULL; DECLARE_ALIGNED(16, const xmm_reg, ff_pw_28 ) = {0x001C001C001C001CULL, 0x001C001C001C001CULL}; DECLARE_ALIGNED(16, const xmm_reg, ff_pw_32 ) = {0x0020002000200020ULL, 0x0020002000200020ULL}; DECLARE_ALIGNED(8, const uint64_t, ff_pw_42 ) = 0x002A002A002A002AULL; DECLARE_ALIGNED(16, const xmm_reg, ff_pw_64 ) = {0x0040004000400040ULL, 0x0040004000400040ULL}; DECLARE_ALIGNED(8, const uint64_t, ff_pw_96 ) = 0x0060006000600060ULL; DECLARE_ALIGNED(8, const uint64_t, ff_pw_128) = 0x0080008000800080ULL; DECLARE_ALIGNED(8, const uint64_t, ff_pw_255) = 0x00ff00ff00ff00ffULL; DECLARE_ALIGNED(8, const uint64_t, ff_pb_1 ) = 0x0101010101010101ULL; DECLARE_ALIGNED(8, const uint64_t, ff_pb_3 ) = 0x0303030303030303ULL; DECLARE_ALIGNED(8, const uint64_t, ff_pb_7 ) = 0x0707070707070707ULL; DECLARE_ALIGNED(8, const uint64_t, ff_pb_1F ) = 0x1F1F1F1F1F1F1F1FULL; DECLARE_ALIGNED(8, const uint64_t, ff_pb_3F ) = 0x3F3F3F3F3F3F3F3FULL; DECLARE_ALIGNED(8, const uint64_t, ff_pb_81 ) = 0x8181818181818181ULL; DECLARE_ALIGNED(8, const uint64_t, ff_pb_A1 ) = 0xA1A1A1A1A1A1A1A1ULL; DECLARE_ALIGNED(8, const uint64_t, ff_pb_FC ) = 0xFCFCFCFCFCFCFCFCULL; DECLARE_ALIGNED(16, const double, ff_pd_1)[2] = { 1.0, 1.0 }; DECLARE_ALIGNED(16, const double, ff_pd_2)[2] = { 2.0, 2.0 }; #define JUMPALIGN() __asm__ volatile (ASMALIGN(3)::) #define MOVQ_ZERO(regd) __asm__ volatile ("pxor %%" #regd ", %%" #regd ::) #define MOVQ_BFE(regd) \ __asm__ volatile ( \ "pcmpeqd %%" #regd ", %%" #regd " \n\t"\ "paddb %%" #regd ", %%" #regd " \n\t" ::) #ifndef PIC #define MOVQ_BONE(regd) __asm__ volatile ("movq %0, %%" #regd " \n\t" ::"m"(ff_bone)) #define MOVQ_WTWO(regd) __asm__ volatile ("movq %0, %%" #regd " \n\t" ::"m"(ff_wtwo)) #else // for shared library it's better to use this way for accessing constants // pcmpeqd -> -1 #define MOVQ_BONE(regd) \ __asm__ volatile ( \ "pcmpeqd %%" #regd ", %%" #regd " \n\t" \ "psrlw $15, %%" #regd " \n\t" \ "packuswb %%" #regd ", %%" #regd " \n\t" ::) #define MOVQ_WTWO(regd) \ __asm__ volatile ( \ "pcmpeqd %%" #regd ", %%" #regd " \n\t" \ "psrlw $15, %%" #regd " \n\t" \ "psllw $1, %%" #regd " \n\t"::) #endif // using regr as temporary and for the output result // first argument is unmodifed and second is trashed // regfe is supposed to contain 0xfefefefefefefefe #define PAVGB_MMX_NO_RND(rega, regb, regr, regfe) \ "movq " #rega ", " #regr " \n\t"\ "pand " #regb ", " #regr " \n\t"\ "pxor " #rega ", " #regb " \n\t"\ "pand " #regfe "," #regb " \n\t"\ "psrlq $1, " #regb " \n\t"\ "paddb " #regb ", " #regr " \n\t" #define PAVGB_MMX(rega, regb, regr, regfe) \ "movq " #rega ", " #regr " \n\t"\ "por " #regb ", " #regr " \n\t"\ "pxor " #rega ", " #regb " \n\t"\ "pand " #regfe "," #regb " \n\t"\ "psrlq $1, " #regb " \n\t"\ "psubb " #regb ", " #regr " \n\t" // mm6 is supposed to contain 0xfefefefefefefefe #define PAVGBP_MMX_NO_RND(rega, regb, regr, regc, regd, regp) \ "movq " #rega ", " #regr " \n\t"\ "movq " #regc ", " #regp " \n\t"\ "pand " #regb ", " #regr " \n\t"\ "pand " #regd ", " #regp " \n\t"\ "pxor " #rega ", " #regb " \n\t"\ "pxor " #regc ", " #regd " \n\t"\ "pand %%mm6, " #regb " \n\t"\ "pand %%mm6, " #regd " \n\t"\ "psrlq $1, " #regb " \n\t"\ "psrlq $1, " #regd " \n\t"\ "paddb " #regb ", " #regr " \n\t"\ "paddb " #regd ", " #regp " \n\t" #define PAVGBP_MMX(rega, regb, regr, regc, regd, regp) \ "movq " #rega ", " #regr " \n\t"\ "movq " #regc ", " #regp " \n\t"\ "por " #regb ", " #regr " \n\t"\ "por " #regd ", " #regp " \n\t"\ "pxor " #rega ", " #regb " \n\t"\ "pxor " #regc ", " #regd " \n\t"\ "pand %%mm6, " #regb " \n\t"\ "pand %%mm6, " #regd " \n\t"\ "psrlq $1, " #regd " \n\t"\ "psrlq $1, " #regb " \n\t"\ "psubb " #regb ", " #regr " \n\t"\ "psubb " #regd ", " #regp " \n\t" /***********************************/ /* MMX no rounding */ #define DEF(x, y) x ## _no_rnd_ ## y ##_mmx #define SET_RND MOVQ_WONE #define PAVGBP(a, b, c, d, e, f) PAVGBP_MMX_NO_RND(a, b, c, d, e, f) #define PAVGB(a, b, c, e) PAVGB_MMX_NO_RND(a, b, c, e) #define OP_AVG(a, b, c, e) PAVGB_MMX(a, b, c, e) #include "dsputil_mmx_rnd_template.c" #undef DEF #undef SET_RND #undef PAVGBP #undef PAVGB /***********************************/ /* MMX rounding */ #define DEF(x, y) x ## _ ## y ##_mmx #define SET_RND MOVQ_WTWO #define PAVGBP(a, b, c, d, e, f) PAVGBP_MMX(a, b, c, d, e, f) #define PAVGB(a, b, c, e) PAVGB_MMX(a, b, c, e) #include "dsputil_mmx_rnd_template.c" #undef DEF #undef SET_RND #undef PAVGBP #undef PAVGB #undef OP_AVG /***********************************/ /* 3Dnow specific */ #define DEF(x) x ## _3dnow #define PAVGB "pavgusb" #define OP_AVG PAVGB #include "dsputil_mmx_avg_template.c" #undef DEF #undef PAVGB #undef OP_AVG /***********************************/ /* MMX2 specific */ #define DEF(x) x ## _mmx2 /* Introduced only in MMX2 set */ #define PAVGB "pavgb" #define OP_AVG PAVGB #include "dsputil_mmx_avg_template.c" #undef DEF #undef PAVGB #undef OP_AVG #define put_no_rnd_pixels16_mmx put_pixels16_mmx #define put_no_rnd_pixels8_mmx put_pixels8_mmx #define put_pixels16_mmx2 put_pixels16_mmx #define put_pixels8_mmx2 put_pixels8_mmx #define put_pixels4_mmx2 put_pixels4_mmx #define put_no_rnd_pixels16_mmx2 put_no_rnd_pixels16_mmx #define put_no_rnd_pixels8_mmx2 put_no_rnd_pixels8_mmx #define put_pixels16_3dnow put_pixels16_mmx #define put_pixels8_3dnow put_pixels8_mmx #define put_pixels4_3dnow put_pixels4_mmx #define put_no_rnd_pixels16_3dnow put_no_rnd_pixels16_mmx #define put_no_rnd_pixels8_3dnow put_no_rnd_pixels8_mmx /***********************************/ /* standard MMX */ void put_pixels_clamped_mmx(const DCTELEM *block, uint8_t *pixels, int line_size) { const DCTELEM *p; uint8_t *pix; /* read the pixels */ p = block; pix = pixels; /* unrolled loop */ __asm__ volatile( "movq %3, %%mm0 \n\t" "movq 8%3, %%mm1 \n\t" "movq 16%3, %%mm2 \n\t" "movq 24%3, %%mm3 \n\t" "movq 32%3, %%mm4 \n\t" "movq 40%3, %%mm5 \n\t" "movq 48%3, %%mm6 \n\t" "movq 56%3, %%mm7 \n\t" "packuswb %%mm1, %%mm0 \n\t" "packuswb %%mm3, %%mm2 \n\t" "packuswb %%mm5, %%mm4 \n\t" "packuswb %%mm7, %%mm6 \n\t" "movq %%mm0, (%0) \n\t" "movq %%mm2, (%0, %1) \n\t" "movq %%mm4, (%0, %1, 2) \n\t" "movq %%mm6, (%0, %2) \n\t" ::"r" (pix), "r" ((x86_reg)line_size), "r" ((x86_reg)line_size*3), "m"(*p) :"memory"); pix += line_size*4; p += 32; // if here would be an exact copy of the code above // compiler would generate some very strange code // thus using "r" __asm__ volatile( "movq (%3), %%mm0 \n\t" "movq 8(%3), %%mm1 \n\t" "movq 16(%3), %%mm2 \n\t" "movq 24(%3), %%mm3 \n\t" "movq 32(%3), %%mm4 \n\t" "movq 40(%3), %%mm5 \n\t" "movq 48(%3), %%mm6 \n\t" "movq 56(%3), %%mm7 \n\t" "packuswb %%mm1, %%mm0 \n\t" "packuswb %%mm3, %%mm2 \n\t" "packuswb %%mm5, %%mm4 \n\t" "packuswb %%mm7, %%mm6 \n\t" "movq %%mm0, (%0) \n\t" "movq %%mm2, (%0, %1) \n\t" "movq %%mm4, (%0, %1, 2) \n\t" "movq %%mm6, (%0, %2) \n\t" ::"r" (pix), "r" ((x86_reg)line_size), "r" ((x86_reg)line_size*3), "r"(p) :"memory"); } DECLARE_ASM_CONST(8, uint8_t, ff_vector128)[8] = { 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80 }; #define put_signed_pixels_clamped_mmx_half(off) \ "movq "#off"(%2), %%mm1 \n\t"\ "movq 16+"#off"(%2), %%mm2 \n\t"\ "movq 32+"#off"(%2), %%mm3 \n\t"\ "movq 48+"#off"(%2), %%mm4 \n\t"\ "packsswb 8+"#off"(%2), %%mm1 \n\t"\ "packsswb 24+"#off"(%2), %%mm2 \n\t"\ "packsswb 40+"#off"(%2), %%mm3 \n\t"\ "packsswb 56+"#off"(%2), %%mm4 \n\t"\ "paddb %%mm0, %%mm1 \n\t"\ "paddb %%mm0, %%mm2 \n\t"\ "paddb %%mm0, %%mm3 \n\t"\ "paddb %%mm0, %%mm4 \n\t"\ "movq %%mm1, (%0) \n\t"\ "movq %%mm2, (%0, %3) \n\t"\ "movq %%mm3, (%0, %3, 2) \n\t"\ "movq %%mm4, (%0, %1) \n\t" void put_signed_pixels_clamped_mmx(const DCTELEM *block, uint8_t *pixels, int line_size) { x86_reg line_skip = line_size; x86_reg line_skip3; __asm__ volatile ( "movq "MANGLE(ff_vector128)", %%mm0 \n\t" "lea (%3, %3, 2), %1 \n\t" put_signed_pixels_clamped_mmx_half(0) "lea (%0, %3, 4), %0 \n\t" put_signed_pixels_clamped_mmx_half(64) :"+&r" (pixels), "=&r" (line_skip3) :"r" (block), "r"(line_skip) :"memory"); } void add_pixels_clamped_mmx(const DCTELEM *block, uint8_t *pixels, int line_size) { const DCTELEM *p; uint8_t *pix; int i; /* read the pixels */ p = block; pix = pixels; MOVQ_ZERO(mm7); i = 4; do { __asm__ volatile( "movq (%2), %%mm0 \n\t" "movq 8(%2), %%mm1 \n\t" "movq 16(%2), %%mm2 \n\t" "movq 24(%2), %%mm3 \n\t" "movq %0, %%mm4 \n\t" "movq %1, %%mm6 \n\t" "movq %%mm4, %%mm5 \n\t" "punpcklbw %%mm7, %%mm4 \n\t" "punpckhbw %%mm7, %%mm5 \n\t" "paddsw %%mm4, %%mm0 \n\t" "paddsw %%mm5, %%mm1 \n\t" "movq %%mm6, %%mm5 \n\t" "punpcklbw %%mm7, %%mm6 \n\t" "punpckhbw %%mm7, %%mm5 \n\t" "paddsw %%mm6, %%mm2 \n\t" "paddsw %%mm5, %%mm3 \n\t" "packuswb %%mm1, %%mm0 \n\t" "packuswb %%mm3, %%mm2 \n\t" "movq %%mm0, %0 \n\t" "movq %%mm2, %1 \n\t" :"+m"(*pix), "+m"(*(pix+line_size)) :"r"(p) :"memory"); pix += line_size*2; p += 16; } while (--i); } static void put_pixels4_mmx(uint8_t *block, const uint8_t *pixels, int line_size, int h) { __asm__ volatile( "lea (%3, %3), %%"REG_a" \n\t" ASMALIGN(3) "1: \n\t" "movd (%1), %%mm0 \n\t" "movd (%1, %3), %%mm1 \n\t" "movd %%mm0, (%2) \n\t" "movd %%mm1, (%2, %3) \n\t" "add %%"REG_a", %1 \n\t" "add %%"REG_a", %2 \n\t" "movd (%1), %%mm0 \n\t" "movd (%1, %3), %%mm1 \n\t" "movd %%mm0, (%2) \n\t" "movd %%mm1, (%2, %3) \n\t" "add %%"REG_a", %1 \n\t" "add %%"REG_a", %2 \n\t" "subl $4, %0 \n\t" "jnz 1b \n\t" : "+g"(h), "+r" (pixels), "+r" (block) : "r"((x86_reg)line_size) : "%"REG_a, "memory" ); } static void put_pixels8_mmx(uint8_t *block, const uint8_t *pixels, int line_size, int h) { __asm__ volatile( "lea (%3, %3), %%"REG_a" \n\t" ASMALIGN(3) "1: \n\t" "movq (%1), %%mm0 \n\t" "movq (%1, %3), %%mm1 \n\t" "movq %%mm0, (%2) \n\t" "movq %%mm1, (%2, %3) \n\t" "add %%"REG_a", %1 \n\t" "add %%"REG_a", %2 \n\t" "movq (%1), %%mm0 \n\t" "movq (%1, %3), %%mm1 \n\t" "movq %%mm0, (%2) \n\t" "movq %%mm1, (%2, %3) \n\t" "add %%"REG_a", %1 \n\t" "add %%"REG_a", %2 \n\t" "subl $4, %0 \n\t" "jnz 1b \n\t" : "+g"(h), "+r" (pixels), "+r" (block) : "r"((x86_reg)line_size) : "%"REG_a, "memory" ); } static void put_pixels16_mmx(uint8_t *block, const uint8_t *pixels, int line_size, int h) { __asm__ volatile( "lea (%3, %3), %%"REG_a" \n\t" ASMALIGN(3) "1: \n\t" "movq (%1), %%mm0 \n\t" "movq 8(%1), %%mm4 \n\t" "movq (%1, %3), %%mm1 \n\t" "movq 8(%1, %3), %%mm5 \n\t" "movq %%mm0, (%2) \n\t" "movq %%mm4, 8(%2) \n\t" "movq %%mm1, (%2, %3) \n\t" "movq %%mm5, 8(%2, %3) \n\t" "add %%"REG_a", %1 \n\t" "add %%"REG_a", %2 \n\t" "movq (%1), %%mm0 \n\t" "movq 8(%1), %%mm4 \n\t" "movq (%1, %3), %%mm1 \n\t" "movq 8(%1, %3), %%mm5 \n\t" "movq %%mm0, (%2) \n\t" "movq %%mm4, 8(%2) \n\t" "movq %%mm1, (%2, %3) \n\t" "movq %%mm5, 8(%2, %3) \n\t" "add %%"REG_a", %1 \n\t" "add %%"REG_a", %2 \n\t" "subl $4, %0 \n\t" "jnz 1b \n\t" : "+g"(h), "+r" (pixels), "+r" (block) : "r"((x86_reg)line_size) : "%"REG_a, "memory" ); } static void put_pixels16_sse2(uint8_t *block, const uint8_t *pixels, int line_size, int h) { __asm__ volatile( "1: \n\t" "movdqu (%1), %%xmm0 \n\t" "movdqu (%1,%3), %%xmm1 \n\t" "movdqu (%1,%3,2), %%xmm2 \n\t" "movdqu (%1,%4), %%xmm3 \n\t" "movdqa %%xmm0, (%2) \n\t" "movdqa %%xmm1, (%2,%3) \n\t" "movdqa %%xmm2, (%2,%3,2) \n\t" "movdqa %%xmm3, (%2,%4) \n\t" "subl $4, %0 \n\t" "lea (%1,%3,4), %1 \n\t" "lea (%2,%3,4), %2 \n\t" "jnz 1b \n\t" : "+g"(h), "+r" (pixels), "+r" (block) : "r"((x86_reg)line_size), "r"((x86_reg)3L*line_size) : "memory" ); } static void avg_pixels16_sse2(uint8_t *block, const uint8_t *pixels, int line_size, int h) { __asm__ volatile( "1: \n\t" "movdqu (%1), %%xmm0 \n\t" "movdqu (%1,%3), %%xmm1 \n\t" "movdqu (%1,%3,2), %%xmm2 \n\t" "movdqu (%1,%4), %%xmm3 \n\t" "pavgb (%2), %%xmm0 \n\t" "pavgb (%2,%3), %%xmm1 \n\t" "pavgb (%2,%3,2), %%xmm2 \n\t" "pavgb (%2,%4), %%xmm3 \n\t" "movdqa %%xmm0, (%2) \n\t" "movdqa %%xmm1, (%2,%3) \n\t" "movdqa %%xmm2, (%2,%3,2) \n\t" "movdqa %%xmm3, (%2,%4) \n\t" "subl $4, %0 \n\t" "lea (%1,%3,4), %1 \n\t" "lea (%2,%3,4), %2 \n\t" "jnz 1b \n\t" : "+g"(h), "+r" (pixels), "+r" (block) : "r"((x86_reg)line_size), "r"((x86_reg)3L*line_size) : "memory" ); } #define CLEAR_BLOCKS(name,n) \ static void name(DCTELEM *blocks)\ {\ __asm__ volatile(\ "pxor %%mm7, %%mm7 \n\t"\ "mov %1, %%"REG_a" \n\t"\ "1: \n\t"\ "movq %%mm7, (%0, %%"REG_a") \n\t"\ "movq %%mm7, 8(%0, %%"REG_a") \n\t"\ "movq %%mm7, 16(%0, %%"REG_a") \n\t"\ "movq %%mm7, 24(%0, %%"REG_a") \n\t"\ "add $32, %%"REG_a" \n\t"\ " js 1b \n\t"\ : : "r" (((uint8_t *)blocks)+128*n),\ "i" (-128*n)\ : "%"REG_a\ );\ } CLEAR_BLOCKS(clear_blocks_mmx, 6) CLEAR_BLOCKS(clear_block_mmx, 1) static void clear_block_sse(DCTELEM *block) { __asm__ volatile( "xorps %%xmm0, %%xmm0 \n" "movaps %%xmm0, (%0) \n" "movaps %%xmm0, 16(%0) \n" "movaps %%xmm0, 32(%0) \n" "movaps %%xmm0, 48(%0) \n" "movaps %%xmm0, 64(%0) \n" "movaps %%xmm0, 80(%0) \n" "movaps %%xmm0, 96(%0) \n" "movaps %%xmm0, 112(%0) \n" :: "r"(block) : "memory" ); } static void clear_blocks_sse(DCTELEM *blocks) {\ __asm__ volatile( "xorps %%xmm0, %%xmm0 \n" "mov %1, %%"REG_a" \n" "1: \n" "movaps %%xmm0, (%0, %%"REG_a") \n" "movaps %%xmm0, 16(%0, %%"REG_a") \n" "movaps %%xmm0, 32(%0, %%"REG_a") \n" "movaps %%xmm0, 48(%0, %%"REG_a") \n" "movaps %%xmm0, 64(%0, %%"REG_a") \n" "movaps %%xmm0, 80(%0, %%"REG_a") \n" "movaps %%xmm0, 96(%0, %%"REG_a") \n" "movaps %%xmm0, 112(%0, %%"REG_a") \n" "add $128, %%"REG_a" \n" " js 1b \n" : : "r" (((uint8_t *)blocks)+128*6), "i" (-128*6) : "%"REG_a ); } static void add_bytes_mmx(uint8_t *dst, uint8_t *src, int w){ x86_reg i=0; __asm__ volatile( "jmp 2f \n\t" "1: \n\t" "movq (%1, %0), %%mm0 \n\t" "movq (%2, %0), %%mm1 \n\t" "paddb %%mm0, %%mm1 \n\t" "movq %%mm1, (%2, %0) \n\t" "movq 8(%1, %0), %%mm0 \n\t" "movq 8(%2, %0), %%mm1 \n\t" "paddb %%mm0, %%mm1 \n\t" "movq %%mm1, 8(%2, %0) \n\t" "add $16, %0 \n\t" "2: \n\t" "cmp %3, %0 \n\t" " js 1b \n\t" : "+r" (i) : "r"(src), "r"(dst), "r"((x86_reg)w-15) ); for(; i<w; i++) dst[i+0] += src[i+0]; } static void add_bytes_l2_mmx(uint8_t *dst, uint8_t *src1, uint8_t *src2, int w){ x86_reg i=0; __asm__ volatile( "jmp 2f \n\t" "1: \n\t" "movq (%2, %0), %%mm0 \n\t" "movq 8(%2, %0), %%mm1 \n\t" "paddb (%3, %0), %%mm0 \n\t" "paddb 8(%3, %0), %%mm1 \n\t" "movq %%mm0, (%1, %0) \n\t" "movq %%mm1, 8(%1, %0) \n\t" "add $16, %0 \n\t" "2: \n\t" "cmp %4, %0 \n\t" " js 1b \n\t" : "+r" (i) : "r"(dst), "r"(src1), "r"(src2), "r"((x86_reg)w-15) ); for(; i<w; i++) dst[i] = src1[i] + src2[i]; } #if HAVE_7REGS && HAVE_TEN_OPERANDS static void add_hfyu_median_prediction_cmov(uint8_t *dst, const uint8_t *top, const uint8_t *diff, int w, int *left, int *left_top) { x86_reg w2 = -w; x86_reg x; int l = *left & 0xff; int tl = *left_top & 0xff; int t; __asm__ volatile( "mov %7, %3 \n" "1: \n" "movzx (%3,%4), %2 \n" "mov %2, %k3 \n" "sub %b1, %b3 \n" "add %b0, %b3 \n" "mov %2, %1 \n" "cmp %0, %2 \n" "cmovg %0, %2 \n" "cmovg %1, %0 \n" "cmp %k3, %0 \n" "cmovg %k3, %0 \n" "mov %7, %3 \n" "cmp %2, %0 \n" "cmovl %2, %0 \n" "add (%6,%4), %b0 \n" "mov %b0, (%5,%4) \n" "inc %4 \n" "jl 1b \n" :"+&q"(l), "+&q"(tl), "=&r"(t), "=&q"(x), "+&r"(w2) :"r"(dst+w), "r"(diff+w), "rm"(top+w) ); *left = l; *left_top = tl; } #endif #define H263_LOOP_FILTER \ "pxor %%mm7, %%mm7 \n\t"\ "movq %0, %%mm0 \n\t"\ "movq %0, %%mm1 \n\t"\ "movq %3, %%mm2 \n\t"\ "movq %3, %%mm3 \n\t"\ "punpcklbw %%mm7, %%mm0 \n\t"\ "punpckhbw %%mm7, %%mm1 \n\t"\ "punpcklbw %%mm7, %%mm2 \n\t"\ "punpckhbw %%mm7, %%mm3 \n\t"\ "psubw %%mm2, %%mm0 \n\t"\ "psubw %%mm3, %%mm1 \n\t"\ "movq %1, %%mm2 \n\t"\ "movq %1, %%mm3 \n\t"\ "movq %2, %%mm4 \n\t"\ "movq %2, %%mm5 \n\t"\ "punpcklbw %%mm7, %%mm2 \n\t"\ "punpckhbw %%mm7, %%mm3 \n\t"\ "punpcklbw %%mm7, %%mm4 \n\t"\ "punpckhbw %%mm7, %%mm5 \n\t"\ "psubw %%mm2, %%mm4 \n\t"\ "psubw %%mm3, %%mm5 \n\t"\ "psllw $2, %%mm4 \n\t"\ "psllw $2, %%mm5 \n\t"\ "paddw %%mm0, %%mm4 \n\t"\ "paddw %%mm1, %%mm5 \n\t"\ "pxor %%mm6, %%mm6 \n\t"\ "pcmpgtw %%mm4, %%mm6 \n\t"\ "pcmpgtw %%mm5, %%mm7 \n\t"\ "pxor %%mm6, %%mm4 \n\t"\ "pxor %%mm7, %%mm5 \n\t"\ "psubw %%mm6, %%mm4 \n\t"\ "psubw %%mm7, %%mm5 \n\t"\ "psrlw $3, %%mm4 \n\t"\ "psrlw $3, %%mm5 \n\t"\ "packuswb %%mm5, %%mm4 \n\t"\ "packsswb %%mm7, %%mm6 \n\t"\ "pxor %%mm7, %%mm7 \n\t"\ "movd %4, %%mm2 \n\t"\ "punpcklbw %%mm2, %%mm2 \n\t"\ "punpcklbw %%mm2, %%mm2 \n\t"\ "punpcklbw %%mm2, %%mm2 \n\t"\ "psubusb %%mm4, %%mm2 \n\t"\ "movq %%mm2, %%mm3 \n\t"\ "psubusb %%mm4, %%mm3 \n\t"\ "psubb %%mm3, %%mm2 \n\t"\ "movq %1, %%mm3 \n\t"\ "movq %2, %%mm4 \n\t"\ "pxor %%mm6, %%mm3 \n\t"\ "pxor %%mm6, %%mm4 \n\t"\ "paddusb %%mm2, %%mm3 \n\t"\ "psubusb %%mm2, %%mm4 \n\t"\ "pxor %%mm6, %%mm3 \n\t"\ "pxor %%mm6, %%mm4 \n\t"\ "paddusb %%mm2, %%mm2 \n\t"\ "packsswb %%mm1, %%mm0 \n\t"\ "pcmpgtb %%mm0, %%mm7 \n\t"\ "pxor %%mm7, %%mm0 \n\t"\ "psubb %%mm7, %%mm0 \n\t"\ "movq %%mm0, %%mm1 \n\t"\ "psubusb %%mm2, %%mm0 \n\t"\ "psubb %%mm0, %%mm1 \n\t"\ "pand %5, %%mm1 \n\t"\ "psrlw $2, %%mm1 \n\t"\ "pxor %%mm7, %%mm1 \n\t"\ "psubb %%mm7, %%mm1 \n\t"\ "movq %0, %%mm5 \n\t"\ "movq %3, %%mm6 \n\t"\ "psubb %%mm1, %%mm5 \n\t"\ "paddb %%mm1, %%mm6 \n\t" static void h263_v_loop_filter_mmx(uint8_t *src, int stride, int qscale){ if(CONFIG_H263_DECODER || CONFIG_H263_ENCODER) { const int strength= ff_h263_loop_filter_strength[qscale]; __asm__ volatile( H263_LOOP_FILTER "movq %%mm3, %1 \n\t" "movq %%mm4, %2 \n\t" "movq %%mm5, %0 \n\t" "movq %%mm6, %3 \n\t" : "+m" (*(uint64_t*)(src - 2*stride)), "+m" (*(uint64_t*)(src - 1*stride)), "+m" (*(uint64_t*)(src + 0*stride)), "+m" (*(uint64_t*)(src + 1*stride)) : "g" (2*strength), "m"(ff_pb_FC) ); } } static inline void transpose4x4(uint8_t *dst, uint8_t *src, int dst_stride, int src_stride){ __asm__ volatile( //FIXME could save 1 instruction if done as 8x4 ... "movd %4, %%mm0 \n\t" "movd %5, %%mm1 \n\t" "movd %6, %%mm2 \n\t" "movd %7, %%mm3 \n\t" "punpcklbw %%mm1, %%mm0 \n\t" "punpcklbw %%mm3, %%mm2 \n\t" "movq %%mm0, %%mm1 \n\t" "punpcklwd %%mm2, %%mm0 \n\t" "punpckhwd %%mm2, %%mm1 \n\t" "movd %%mm0, %0 \n\t" "punpckhdq %%mm0, %%mm0 \n\t" "movd %%mm0, %1 \n\t" "movd %%mm1, %2 \n\t" "punpckhdq %%mm1, %%mm1 \n\t" "movd %%mm1, %3 \n\t" : "=m" (*(uint32_t*)(dst + 0*dst_stride)), "=m" (*(uint32_t*)(dst + 1*dst_stride)), "=m" (*(uint32_t*)(dst + 2*dst_stride)), "=m" (*(uint32_t*)(dst + 3*dst_stride)) : "m" (*(uint32_t*)(src + 0*src_stride)), "m" (*(uint32_t*)(src + 1*src_stride)), "m" (*(uint32_t*)(src + 2*src_stride)), "m" (*(uint32_t*)(src + 3*src_stride)) ); } static void h263_h_loop_filter_mmx(uint8_t *src, int stride, int qscale){ if(CONFIG_H263_DECODER || CONFIG_H263_ENCODER) { const int strength= ff_h263_loop_filter_strength[qscale]; DECLARE_ALIGNED(8, uint64_t, temp)[4]; uint8_t *btemp= (uint8_t*)temp; src -= 2; transpose4x4(btemp , src , 8, stride); transpose4x4(btemp+4, src + 4*stride, 8, stride); __asm__ volatile( H263_LOOP_FILTER // 5 3 4 6 : "+m" (temp[0]), "+m" (temp[1]), "+m" (temp[2]), "+m" (temp[3]) : "g" (2*strength), "m"(ff_pb_FC) ); __asm__ volatile( "movq %%mm5, %%mm1 \n\t" "movq %%mm4, %%mm0 \n\t" "punpcklbw %%mm3, %%mm5 \n\t" "punpcklbw %%mm6, %%mm4 \n\t" "punpckhbw %%mm3, %%mm1 \n\t" "punpckhbw %%mm6, %%mm0 \n\t" "movq %%mm5, %%mm3 \n\t" "movq %%mm1, %%mm6 \n\t" "punpcklwd %%mm4, %%mm5 \n\t" "punpcklwd %%mm0, %%mm1 \n\t" "punpckhwd %%mm4, %%mm3 \n\t" "punpckhwd %%mm0, %%mm6 \n\t" "movd %%mm5, (%0) \n\t" "punpckhdq %%mm5, %%mm5 \n\t" "movd %%mm5, (%0,%2) \n\t" "movd %%mm3, (%0,%2,2) \n\t" "punpckhdq %%mm3, %%mm3 \n\t" "movd %%mm3, (%0,%3) \n\t" "movd %%mm1, (%1) \n\t" "punpckhdq %%mm1, %%mm1 \n\t" "movd %%mm1, (%1,%2) \n\t" "movd %%mm6, (%1,%2,2) \n\t" "punpckhdq %%mm6, %%mm6 \n\t" "movd %%mm6, (%1,%3) \n\t" :: "r" (src), "r" (src + 4*stride), "r" ((x86_reg) stride ), "r" ((x86_reg)(3*stride)) ); } } /* draw the edges of width 'w' of an image of size width, height this mmx version can only handle w==8 || w==16 */ static void draw_edges_mmx(uint8_t *buf, int wrap, int width, int height, int w) { uint8_t *ptr, *last_line; int i; last_line = buf + (height - 1) * wrap; /* left and right */ ptr = buf; if(w==8) { __asm__ volatile( "1: \n\t" "movd (%0), %%mm0 \n\t" "punpcklbw %%mm0, %%mm0 \n\t" "punpcklwd %%mm0, %%mm0 \n\t" "punpckldq %%mm0, %%mm0 \n\t" "movq %%mm0, -8(%0) \n\t" "movq -8(%0, %2), %%mm1 \n\t" "punpckhbw %%mm1, %%mm1 \n\t" "punpckhwd %%mm1, %%mm1 \n\t" "punpckhdq %%mm1, %%mm1 \n\t" "movq %%mm1, (%0, %2) \n\t" "add %1, %0 \n\t" "cmp %3, %0 \n\t" " jb 1b \n\t" : "+r" (ptr) : "r" ((x86_reg)wrap), "r" ((x86_reg)width), "r" (ptr + wrap*height) ); } else { __asm__ volatile( "1: \n\t" "movd (%0), %%mm0 \n\t" "punpcklbw %%mm0, %%mm0 \n\t" "punpcklwd %%mm0, %%mm0 \n\t" "punpckldq %%mm0, %%mm0 \n\t" "movq %%mm0, -8(%0) \n\t" "movq %%mm0, -16(%0) \n\t" "movq -8(%0, %2), %%mm1 \n\t" "punpckhbw %%mm1, %%mm1 \n\t" "punpckhwd %%mm1, %%mm1 \n\t" "punpckhdq %%mm1, %%mm1 \n\t" "movq %%mm1, (%0, %2) \n\t" "movq %%mm1, 8(%0, %2) \n\t" "add %1, %0 \n\t" "cmp %3, %0 \n\t" " jb 1b \n\t" : "+r" (ptr) : "r" ((x86_reg)wrap), "r" ((x86_reg)width), "r" (ptr + wrap*height) ); } for(i=0;i<w;i+=4) { /* top and bottom (and hopefully also the corners) */ ptr= buf - (i + 1) * wrap - w; __asm__ volatile( "1: \n\t" "movq (%1, %0), %%mm0 \n\t" "movq %%mm0, (%0) \n\t" "movq %%mm0, (%0, %2) \n\t" "movq %%mm0, (%0, %2, 2) \n\t" "movq %%mm0, (%0, %3) \n\t" "add $8, %0 \n\t" "cmp %4, %0 \n\t" " jb 1b \n\t" : "+r" (ptr) : "r" ((x86_reg)buf - (x86_reg)ptr - w), "r" ((x86_reg)-wrap), "r" ((x86_reg)-wrap*3), "r" (ptr+width+2*w) ); ptr= last_line + (i + 1) * wrap - w; __asm__ volatile( "1: \n\t" "movq (%1, %0), %%mm0 \n\t" "movq %%mm0, (%0) \n\t" "movq %%mm0, (%0, %2) \n\t" "movq %%mm0, (%0, %2, 2) \n\t" "movq %%mm0, (%0, %3) \n\t" "add $8, %0 \n\t" "cmp %4, %0 \n\t" " jb 1b \n\t" : "+r" (ptr) : "r" ((x86_reg)last_line - (x86_reg)ptr - w), "r" ((x86_reg)wrap), "r" ((x86_reg)wrap*3), "r" (ptr+width+2*w) ); } } #define PAETH(cpu, abs3)\ static void add_png_paeth_prediction_##cpu(uint8_t *dst, uint8_t *src, uint8_t *top, int w, int bpp)\ {\ x86_reg i = -bpp;\ x86_reg end = w-3;\ __asm__ volatile(\ "pxor %%mm7, %%mm7 \n"\ "movd (%1,%0), %%mm0 \n"\ "movd (%2,%0), %%mm1 \n"\ "punpcklbw %%mm7, %%mm0 \n"\ "punpcklbw %%mm7, %%mm1 \n"\ "add %4, %0 \n"\ "1: \n"\ "movq %%mm1, %%mm2 \n"\ "movd (%2,%0), %%mm1 \n"\ "movq %%mm2, %%mm3 \n"\ "punpcklbw %%mm7, %%mm1 \n"\ "movq %%mm2, %%mm4 \n"\ "psubw %%mm1, %%mm3 \n"\ "psubw %%mm0, %%mm4 \n"\ "movq %%mm3, %%mm5 \n"\ "paddw %%mm4, %%mm5 \n"\ abs3\ "movq %%mm4, %%mm6 \n"\ "pminsw %%mm5, %%mm6 \n"\ "pcmpgtw %%mm6, %%mm3 \n"\ "pcmpgtw %%mm5, %%mm4 \n"\ "movq %%mm4, %%mm6 \n"\ "pand %%mm3, %%mm4 \n"\ "pandn %%mm3, %%mm6 \n"\ "pandn %%mm0, %%mm3 \n"\ "movd (%3,%0), %%mm0 \n"\ "pand %%mm1, %%mm6 \n"\ "pand %%mm4, %%mm2 \n"\ "punpcklbw %%mm7, %%mm0 \n"\ "movq %6, %%mm5 \n"\ "paddw %%mm6, %%mm0 \n"\ "paddw %%mm2, %%mm3 \n"\ "paddw %%mm3, %%mm0 \n"\ "pand %%mm5, %%mm0 \n"\ "movq %%mm0, %%mm3 \n"\ "packuswb %%mm3, %%mm3 \n"\ "movd %%mm3, (%1,%0) \n"\ "add %4, %0 \n"\ "cmp %5, %0 \n"\ "jle 1b \n"\ :"+r"(i)\ :"r"(dst), "r"(top), "r"(src), "r"((x86_reg)bpp), "g"(end),\ "m"(ff_pw_255)\ :"memory"\ );\ } #define ABS3_MMX2\ "psubw %%mm5, %%mm7 \n"\ "pmaxsw %%mm7, %%mm5 \n"\ "pxor %%mm6, %%mm6 \n"\ "pxor %%mm7, %%mm7 \n"\ "psubw %%mm3, %%mm6 \n"\ "psubw %%mm4, %%mm7 \n"\ "pmaxsw %%mm6, %%mm3 \n"\ "pmaxsw %%mm7, %%mm4 \n"\ "pxor %%mm7, %%mm7 \n" #define ABS3_SSSE3\ "pabsw %%mm3, %%mm3 \n"\ "pabsw %%mm4, %%mm4 \n"\ "pabsw %%mm5, %%mm5 \n" PAETH(mmx2, ABS3_MMX2) #if HAVE_SSSE3 PAETH(ssse3, ABS3_SSSE3) #endif #define QPEL_V_LOW(m3,m4,m5,m6, pw_20, pw_3, rnd, in0, in1, in2, in7, out, OP)\ "paddw " #m4 ", " #m3 " \n\t" /* x1 */\ "movq "MANGLE(ff_pw_20)", %%mm4 \n\t" /* 20 */\ "pmullw " #m3 ", %%mm4 \n\t" /* 20x1 */\ "movq "#in7", " #m3 " \n\t" /* d */\ "movq "#in0", %%mm5 \n\t" /* D */\ "paddw " #m3 ", %%mm5 \n\t" /* x4 */\ "psubw %%mm5, %%mm4 \n\t" /* 20x1 - x4 */\ "movq "#in1", %%mm5 \n\t" /* C */\ "movq "#in2", %%mm6 \n\t" /* B */\ "paddw " #m6 ", %%mm5 \n\t" /* x3 */\ "paddw " #m5 ", %%mm6 \n\t" /* x2 */\ "paddw %%mm6, %%mm6 \n\t" /* 2x2 */\ "psubw %%mm6, %%mm5 \n\t" /* -2x2 + x3 */\ "pmullw "MANGLE(ff_pw_3)", %%mm5 \n\t" /* -6x2 + 3x3 */\ "paddw " #rnd ", %%mm4 \n\t" /* x2 */\ "paddw %%mm4, %%mm5 \n\t" /* 20x1 - 6x2 + 3x3 - x4 */\ "psraw $5, %%mm5 \n\t"\ "packuswb %%mm5, %%mm5 \n\t"\ OP(%%mm5, out, %%mm7, d) #define QPEL_BASE(OPNAME, ROUNDER, RND, OP_MMX2, OP_3DNOW)\ static void OPNAME ## mpeg4_qpel16_h_lowpass_mmx2(uint8_t *dst, uint8_t *src, int dstStride, int srcStride, int h){\ uint64_t temp;\ \ __asm__ volatile(\ "pxor %%mm7, %%mm7 \n\t"\ "1: \n\t"\ "movq (%0), %%mm0 \n\t" /* ABCDEFGH */\ "movq %%mm0, %%mm1 \n\t" /* ABCDEFGH */\ "movq %%mm0, %%mm2 \n\t" /* ABCDEFGH */\ "punpcklbw %%mm7, %%mm0 \n\t" /* 0A0B0C0D */\ "punpckhbw %%mm7, %%mm1 \n\t" /* 0E0F0G0H */\ "pshufw $0x90, %%mm0, %%mm5 \n\t" /* 0A0A0B0C */\ "pshufw $0x41, %%mm0, %%mm6 \n\t" /* 0B0A0A0B */\ "movq %%mm2, %%mm3 \n\t" /* ABCDEFGH */\ "movq %%mm2, %%mm4 \n\t" /* ABCDEFGH */\ "psllq $8, %%mm2 \n\t" /* 0ABCDEFG */\ "psllq $16, %%mm3 \n\t" /* 00ABCDEF */\ "psllq $24, %%mm4 \n\t" /* 000ABCDE */\ "punpckhbw %%mm7, %%mm2 \n\t" /* 0D0E0F0G */\ "punpckhbw %%mm7, %%mm3 \n\t" /* 0C0D0E0F */\ "punpckhbw %%mm7, %%mm4 \n\t" /* 0B0C0D0E */\ "paddw %%mm3, %%mm5 \n\t" /* b */\ "paddw %%mm2, %%mm6 \n\t" /* c */\ "paddw %%mm5, %%mm5 \n\t" /* 2b */\ "psubw %%mm5, %%mm6 \n\t" /* c - 2b */\ "pshufw $0x06, %%mm0, %%mm5 \n\t" /* 0C0B0A0A */\ "pmullw "MANGLE(ff_pw_3)", %%mm6 \n\t" /* 3c - 6b */\ "paddw %%mm4, %%mm0 \n\t" /* a */\ "paddw %%mm1, %%mm5 \n\t" /* d */\ "pmullw "MANGLE(ff_pw_20)", %%mm0 \n\t" /* 20a */\ "psubw %%mm5, %%mm0 \n\t" /* 20a - d */\ "paddw %6, %%mm6 \n\t"\ "paddw %%mm6, %%mm0 \n\t" /* 20a - 6b + 3c - d */\ "psraw $5, %%mm0 \n\t"\ "movq %%mm0, %5 \n\t"\ /* mm1=EFGH, mm2=DEFG, mm3=CDEF, mm4=BCDE, mm7=0 */\ \ "movq 5(%0), %%mm0 \n\t" /* FGHIJKLM */\ "movq %%mm0, %%mm5 \n\t" /* FGHIJKLM */\ "movq %%mm0, %%mm6 \n\t" /* FGHIJKLM */\ "psrlq $8, %%mm0 \n\t" /* GHIJKLM0 */\ "psrlq $16, %%mm5 \n\t" /* HIJKLM00 */\ "punpcklbw %%mm7, %%mm0 \n\t" /* 0G0H0I0J */\ "punpcklbw %%mm7, %%mm5 \n\t" /* 0H0I0J0K */\ "paddw %%mm0, %%mm2 \n\t" /* b */\ "paddw %%mm5, %%mm3 \n\t" /* c */\ "paddw %%mm2, %%mm2 \n\t" /* 2b */\ "psubw %%mm2, %%mm3 \n\t" /* c - 2b */\ "movq %%mm6, %%mm2 \n\t" /* FGHIJKLM */\ "psrlq $24, %%mm6 \n\t" /* IJKLM000 */\ "punpcklbw %%mm7, %%mm2 \n\t" /* 0F0G0H0I */\ "punpcklbw %%mm7, %%mm6 \n\t" /* 0I0J0K0L */\ "pmullw "MANGLE(ff_pw_3)", %%mm3 \n\t" /* 3c - 6b */\ "paddw %%mm2, %%mm1 \n\t" /* a */\ "paddw %%mm6, %%mm4 \n\t" /* d */\ "pmullw "MANGLE(ff_pw_20)", %%mm1 \n\t" /* 20a */\ "psubw %%mm4, %%mm3 \n\t" /* - 6b +3c - d */\ "paddw %6, %%mm1 \n\t"\ "paddw %%mm1, %%mm3 \n\t" /* 20a - 6b +3c - d */\ "psraw $5, %%mm3 \n\t"\ "movq %5, %%mm1 \n\t"\ "packuswb %%mm3, %%mm1 \n\t"\ OP_MMX2(%%mm1, (%1),%%mm4, q)\ /* mm0= GHIJ, mm2=FGHI, mm5=HIJK, mm6=IJKL, mm7=0 */\ \ "movq 9(%0), %%mm1 \n\t" /* JKLMNOPQ */\ "movq %%mm1, %%mm4 \n\t" /* JKLMNOPQ */\ "movq %%mm1, %%mm3 \n\t" /* JKLMNOPQ */\ "psrlq $8, %%mm1 \n\t" /* KLMNOPQ0 */\ "psrlq $16, %%mm4 \n\t" /* LMNOPQ00 */\ "punpcklbw %%mm7, %%mm1 \n\t" /* 0K0L0M0N */\ "punpcklbw %%mm7, %%mm4 \n\t" /* 0L0M0N0O */\ "paddw %%mm1, %%mm5 \n\t" /* b */\ "paddw %%mm4, %%mm0 \n\t" /* c */\ "paddw %%mm5, %%mm5 \n\t" /* 2b */\ "psubw %%mm5, %%mm0 \n\t" /* c - 2b */\ "movq %%mm3, %%mm5 \n\t" /* JKLMNOPQ */\ "psrlq $24, %%mm3 \n\t" /* MNOPQ000 */\ "pmullw "MANGLE(ff_pw_3)", %%mm0 \n\t" /* 3c - 6b */\ "punpcklbw %%mm7, %%mm3 \n\t" /* 0M0N0O0P */\ "paddw %%mm3, %%mm2 \n\t" /* d */\ "psubw %%mm2, %%mm0 \n\t" /* -6b + 3c - d */\ "movq %%mm5, %%mm2 \n\t" /* JKLMNOPQ */\ "punpcklbw %%mm7, %%mm2 \n\t" /* 0J0K0L0M */\ "punpckhbw %%mm7, %%mm5 \n\t" /* 0N0O0P0Q */\ "paddw %%mm2, %%mm6 \n\t" /* a */\ "pmullw "MANGLE(ff_pw_20)", %%mm6 \n\t" /* 20a */\ "paddw %6, %%mm0 \n\t"\ "paddw %%mm6, %%mm0 \n\t" /* 20a - 6b + 3c - d */\ "psraw $5, %%mm0 \n\t"\ /* mm1=KLMN, mm2=JKLM, mm3=MNOP, mm4=LMNO, mm5=NOPQ mm7=0 */\ \ "paddw %%mm5, %%mm3 \n\t" /* a */\ "pshufw $0xF9, %%mm5, %%mm6 \n\t" /* 0O0P0Q0Q */\ "paddw %%mm4, %%mm6 \n\t" /* b */\ "pshufw $0xBE, %%mm5, %%mm4 \n\t" /* 0P0Q0Q0P */\ "pshufw $0x6F, %%mm5, %%mm5 \n\t" /* 0Q0Q0P0O */\ "paddw %%mm1, %%mm4 \n\t" /* c */\ "paddw %%mm2, %%mm5 \n\t" /* d */\ "paddw %%mm6, %%mm6 \n\t" /* 2b */\ "psubw %%mm6, %%mm4 \n\t" /* c - 2b */\ "pmullw "MANGLE(ff_pw_20)", %%mm3 \n\t" /* 20a */\ "pmullw "MANGLE(ff_pw_3)", %%mm4 \n\t" /* 3c - 6b */\ "psubw %%mm5, %%mm3 \n\t" /* -6b + 3c - d */\ "paddw %6, %%mm4 \n\t"\ "paddw %%mm3, %%mm4 \n\t" /* 20a - 6b + 3c - d */\ "psraw $5, %%mm4 \n\t"\ "packuswb %%mm4, %%mm0 \n\t"\ OP_MMX2(%%mm0, 8(%1), %%mm4, q)\ \ "add %3, %0 \n\t"\ "add %4, %1 \n\t"\ "decl %2 \n\t"\ " jnz 1b \n\t"\ : "+a"(src), "+c"(dst), "+D"(h)\ : "d"((x86_reg)srcStride), "S"((x86_reg)dstStride), /*"m"(ff_pw_20), "m"(ff_pw_3),*/ "m"(temp), "m"(ROUNDER)\ : "memory"\ );\ }\ \ static void OPNAME ## mpeg4_qpel16_h_lowpass_3dnow(uint8_t *dst, uint8_t *src, int dstStride, int srcStride, int h){\ int i;\ int16_t temp[16];\ /* quick HACK, XXX FIXME MUST be optimized */\ for(i=0; i<h; i++)\ {\ temp[ 0]= (src[ 0]+src[ 1])*20 - (src[ 0]+src[ 2])*6 + (src[ 1]+src[ 3])*3 - (src[ 2]+src[ 4]);\ temp[ 1]= (src[ 1]+src[ 2])*20 - (src[ 0]+src[ 3])*6 + (src[ 0]+src[ 4])*3 - (src[ 1]+src[ 5]);\ temp[ 2]= (src[ 2]+src[ 3])*20 - (src[ 1]+src[ 4])*6 + (src[ 0]+src[ 5])*3 - (src[ 0]+src[ 6]);\ temp[ 3]= (src[ 3]+src[ 4])*20 - (src[ 2]+src[ 5])*6 + (src[ 1]+src[ 6])*3 - (src[ 0]+src[ 7]);\ temp[ 4]= (src[ 4]+src[ 5])*20 - (src[ 3]+src[ 6])*6 + (src[ 2]+src[ 7])*3 - (src[ 1]+src[ 8]);\ temp[ 5]= (src[ 5]+src[ 6])*20 - (src[ 4]+src[ 7])*6 + (src[ 3]+src[ 8])*3 - (src[ 2]+src[ 9]);\ temp[ 6]= (src[ 6]+src[ 7])*20 - (src[ 5]+src[ 8])*6 + (src[ 4]+src[ 9])*3 - (src[ 3]+src[10]);\ temp[ 7]= (src[ 7]+src[ 8])*20 - (src[ 6]+src[ 9])*6 + (src[ 5]+src[10])*3 - (src[ 4]+src[11]);\ temp[ 8]= (src[ 8]+src[ 9])*20 - (src[ 7]+src[10])*6 + (src[ 6]+src[11])*3 - (src[ 5]+src[12]);\ temp[ 9]= (src[ 9]+src[10])*20 - (src[ 8]+src[11])*6 + (src[ 7]+src[12])*3 - (src[ 6]+src[13]);\ temp[10]= (src[10]+src[11])*20 - (src[ 9]+src[12])*6 + (src[ 8]+src[13])*3 - (src[ 7]+src[14]);\ temp[11]= (src[11]+src[12])*20 - (src[10]+src[13])*6 + (src[ 9]+src[14])*3 - (src[ 8]+src[15]);\ temp[12]= (src[12]+src[13])*20 - (src[11]+src[14])*6 + (src[10]+src[15])*3 - (src[ 9]+src[16]);\ temp[13]= (src[13]+src[14])*20 - (src[12]+src[15])*6 + (src[11]+src[16])*3 - (src[10]+src[16]);\ temp[14]= (src[14]+src[15])*20 - (src[13]+src[16])*6 + (src[12]+src[16])*3 - (src[11]+src[15]);\ temp[15]= (src[15]+src[16])*20 - (src[14]+src[16])*6 + (src[13]+src[15])*3 - (src[12]+src[14]);\ __asm__ volatile(\ "movq (%0), %%mm0 \n\t"\ "movq 8(%0), %%mm1 \n\t"\ "paddw %2, %%mm0 \n\t"\ "paddw %2, %%mm1 \n\t"\ "psraw $5, %%mm0 \n\t"\ "psraw $5, %%mm1 \n\t"\ "packuswb %%mm1, %%mm0 \n\t"\ OP_3DNOW(%%mm0, (%1), %%mm1, q)\ "movq 16(%0), %%mm0 \n\t"\ "movq 24(%0), %%mm1 \n\t"\ "paddw %2, %%mm0 \n\t"\ "paddw %2, %%mm1 \n\t"\ "psraw $5, %%mm0 \n\t"\ "psraw $5, %%mm1 \n\t"\ "packuswb %%mm1, %%mm0 \n\t"\ OP_3DNOW(%%mm0, 8(%1), %%mm1, q)\ :: "r"(temp), "r"(dst), "m"(ROUNDER)\ : "memory"\ );\ dst+=dstStride;\ src+=srcStride;\ }\ }\ \ static void OPNAME ## mpeg4_qpel8_h_lowpass_mmx2(uint8_t *dst, uint8_t *src, int dstStride, int srcStride, int h){\ __asm__ volatile(\ "pxor %%mm7, %%mm7 \n\t"\ "1: \n\t"\ "movq (%0), %%mm0 \n\t" /* ABCDEFGH */\ "movq %%mm0, %%mm1 \n\t" /* ABCDEFGH */\ "movq %%mm0, %%mm2 \n\t" /* ABCDEFGH */\ "punpcklbw %%mm7, %%mm0 \n\t" /* 0A0B0C0D */\ "punpckhbw %%mm7, %%mm1 \n\t" /* 0E0F0G0H */\ "pshufw $0x90, %%mm0, %%mm5 \n\t" /* 0A0A0B0C */\ "pshufw $0x41, %%mm0, %%mm6 \n\t" /* 0B0A0A0B */\ "movq %%mm2, %%mm3 \n\t" /* ABCDEFGH */\ "movq %%mm2, %%mm4 \n\t" /* ABCDEFGH */\ "psllq $8, %%mm2 \n\t" /* 0ABCDEFG */\ "psllq $16, %%mm3 \n\t" /* 00ABCDEF */\ "psllq $24, %%mm4 \n\t" /* 000ABCDE */\ "punpckhbw %%mm7, %%mm2 \n\t" /* 0D0E0F0G */\ "punpckhbw %%mm7, %%mm3 \n\t" /* 0C0D0E0F */\ "punpckhbw %%mm7, %%mm4 \n\t" /* 0B0C0D0E */\ "paddw %%mm3, %%mm5 \n\t" /* b */\ "paddw %%mm2, %%mm6 \n\t" /* c */\ "paddw %%mm5, %%mm5 \n\t" /* 2b */\ "psubw %%mm5, %%mm6 \n\t" /* c - 2b */\ "pshufw $0x06, %%mm0, %%mm5 \n\t" /* 0C0B0A0A */\ "pmullw "MANGLE(ff_pw_3)", %%mm6 \n\t" /* 3c - 6b */\ "paddw %%mm4, %%mm0 \n\t" /* a */\ "paddw %%mm1, %%mm5 \n\t" /* d */\ "pmullw "MANGLE(ff_pw_20)", %%mm0 \n\t" /* 20a */\ "psubw %%mm5, %%mm0 \n\t" /* 20a - d */\ "paddw %5, %%mm6 \n\t"\ "paddw %%mm6, %%mm0 \n\t" /* 20a - 6b + 3c - d */\ "psraw $5, %%mm0 \n\t"\ /* mm1=EFGH, mm2=DEFG, mm3=CDEF, mm4=BCDE, mm7=0 */\ \ "movd 5(%0), %%mm5 \n\t" /* FGHI */\ "punpcklbw %%mm7, %%mm5 \n\t" /* 0F0G0H0I */\ "pshufw $0xF9, %%mm5, %%mm6 \n\t" /* 0G0H0I0I */\ "paddw %%mm5, %%mm1 \n\t" /* a */\ "paddw %%mm6, %%mm2 \n\t" /* b */\ "pshufw $0xBE, %%mm5, %%mm6 \n\t" /* 0H0I0I0H */\ "pshufw $0x6F, %%mm5, %%mm5 \n\t" /* 0I0I0H0G */\ "paddw %%mm6, %%mm3 \n\t" /* c */\ "paddw %%mm5, %%mm4 \n\t" /* d */\ "paddw %%mm2, %%mm2 \n\t" /* 2b */\ "psubw %%mm2, %%mm3 \n\t" /* c - 2b */\ "pmullw "MANGLE(ff_pw_20)", %%mm1 \n\t" /* 20a */\ "pmullw "MANGLE(ff_pw_3)", %%mm3 \n\t" /* 3c - 6b */\ "psubw %%mm4, %%mm3 \n\t" /* -6b + 3c - d */\ "paddw %5, %%mm1 \n\t"\ "paddw %%mm1, %%mm3 \n\t" /* 20a - 6b + 3c - d */\ "psraw $5, %%mm3 \n\t"\ "packuswb %%mm3, %%mm0 \n\t"\ OP_MMX2(%%mm0, (%1), %%mm4, q)\ \ "add %3, %0 \n\t"\ "add %4, %1 \n\t"\ "decl %2 \n\t"\ " jnz 1b \n\t"\ : "+a"(src), "+c"(dst), "+d"(h)\ : "S"((x86_reg)srcStride), "D"((x86_reg)dstStride), /*"m"(ff_pw_20), "m"(ff_pw_3),*/ "m"(ROUNDER)\ : "memory"\ );\ }\ \ static void OPNAME ## mpeg4_qpel8_h_lowpass_3dnow(uint8_t *dst, uint8_t *src, int dstStride, int srcStride, int h){\ int i;\ int16_t temp[8];\ /* quick HACK, XXX FIXME MUST be optimized */\ for(i=0; i<h; i++)\ {\ temp[ 0]= (src[ 0]+src[ 1])*20 - (src[ 0]+src[ 2])*6 + (src[ 1]+src[ 3])*3 - (src[ 2]+src[ 4]);\ temp[ 1]= (src[ 1]+src[ 2])*20 - (src[ 0]+src[ 3])*6 + (src[ 0]+src[ 4])*3 - (src[ 1]+src[ 5]);\ temp[ 2]= (src[ 2]+src[ 3])*20 - (src[ 1]+src[ 4])*6 + (src[ 0]+src[ 5])*3 - (src[ 0]+src[ 6]);\ temp[ 3]= (src[ 3]+src[ 4])*20 - (src[ 2]+src[ 5])*6 + (src[ 1]+src[ 6])*3 - (src[ 0]+src[ 7]);\ temp[ 4]= (src[ 4]+src[ 5])*20 - (src[ 3]+src[ 6])*6 + (src[ 2]+src[ 7])*3 - (src[ 1]+src[ 8]);\ temp[ 5]= (src[ 5]+src[ 6])*20 - (src[ 4]+src[ 7])*6 + (src[ 3]+src[ 8])*3 - (src[ 2]+src[ 8]);\ temp[ 6]= (src[ 6]+src[ 7])*20 - (src[ 5]+src[ 8])*6 + (src[ 4]+src[ 8])*3 - (src[ 3]+src[ 7]);\ temp[ 7]= (src[ 7]+src[ 8])*20 - (src[ 6]+src[ 8])*6 + (src[ 5]+src[ 7])*3 - (src[ 4]+src[ 6]);\ __asm__ volatile(\ "movq (%0), %%mm0 \n\t"\ "movq 8(%0), %%mm1 \n\t"\ "paddw %2, %%mm0 \n\t"\ "paddw %2, %%mm1 \n\t"\ "psraw $5, %%mm0 \n\t"\ "psraw $5, %%mm1 \n\t"\ "packuswb %%mm1, %%mm0 \n\t"\ OP_3DNOW(%%mm0, (%1), %%mm1, q)\ :: "r"(temp), "r"(dst), "m"(ROUNDER)\ :"memory"\ );\ dst+=dstStride;\ src+=srcStride;\ }\ } #define QPEL_OP(OPNAME, ROUNDER, RND, OP, MMX)\ \ static void OPNAME ## mpeg4_qpel16_v_lowpass_ ## MMX(uint8_t *dst, uint8_t *src, int dstStride, int srcStride){\ uint64_t temp[17*4];\ uint64_t *temp_ptr= temp;\ int count= 17;\ \ /*FIXME unroll */\ __asm__ volatile(\ "pxor %%mm7, %%mm7 \n\t"\ "1: \n\t"\ "movq (%0), %%mm0 \n\t"\ "movq (%0), %%mm1 \n\t"\ "movq 8(%0), %%mm2 \n\t"\ "movq 8(%0), %%mm3 \n\t"\ "punpcklbw %%mm7, %%mm0 \n\t"\ "punpckhbw %%mm7, %%mm1 \n\t"\ "punpcklbw %%mm7, %%mm2 \n\t"\ "punpckhbw %%mm7, %%mm3 \n\t"\ "movq %%mm0, (%1) \n\t"\ "movq %%mm1, 17*8(%1) \n\t"\ "movq %%mm2, 2*17*8(%1) \n\t"\ "movq %%mm3, 3*17*8(%1) \n\t"\ "add $8, %1 \n\t"\ "add %3, %0 \n\t"\ "decl %2 \n\t"\ " jnz 1b \n\t"\ : "+r" (src), "+r" (temp_ptr), "+r"(count)\ : "r" ((x86_reg)srcStride)\ : "memory"\ );\ \ temp_ptr= temp;\ count=4;\ \ /*FIXME reorder for speed */\ __asm__ volatile(\ /*"pxor %%mm7, %%mm7 \n\t"*/\ "1: \n\t"\ "movq (%0), %%mm0 \n\t"\ "movq 8(%0), %%mm1 \n\t"\ "movq 16(%0), %%mm2 \n\t"\ "movq 24(%0), %%mm3 \n\t"\ QPEL_V_LOW(%%mm0, %%mm1, %%mm2, %%mm3, %5, %6, %5, 16(%0), 8(%0), (%0), 32(%0), (%1), OP)\ QPEL_V_LOW(%%mm1, %%mm2, %%mm3, %%mm0, %5, %6, %5, 8(%0), (%0), (%0), 40(%0), (%1, %3), OP)\ "add %4, %1 \n\t"\ QPEL_V_LOW(%%mm2, %%mm3, %%mm0, %%mm1, %5, %6, %5, (%0), (%0), 8(%0), 48(%0), (%1), OP)\ \ QPEL_V_LOW(%%mm3, %%mm0, %%mm1, %%mm2, %5, %6, %5, (%0), 8(%0), 16(%0), 56(%0), (%1, %3), OP)\ "add %4, %1 \n\t"\ QPEL_V_LOW(%%mm0, %%mm1, %%mm2, %%mm3, %5, %6, %5, 8(%0), 16(%0), 24(%0), 64(%0), (%1), OP)\ QPEL_V_LOW(%%mm1, %%mm2, %%mm3, %%mm0, %5, %6, %5, 16(%0), 24(%0), 32(%0), 72(%0), (%1, %3), OP)\ "add %4, %1 \n\t"\ QPEL_V_LOW(%%mm2, %%mm3, %%mm0, %%mm1, %5, %6, %5, 24(%0), 32(%0), 40(%0), 80(%0), (%1), OP)\ QPEL_V_LOW(%%mm3, %%mm0, %%mm1, %%mm2, %5, %6, %5, 32(%0), 40(%0), 48(%0), 88(%0), (%1, %3), OP)\ "add %4, %1 \n\t"\ QPEL_V_LOW(%%mm0, %%mm1, %%mm2, %%mm3, %5, %6, %5, 40(%0), 48(%0), 56(%0), 96(%0), (%1), OP)\ QPEL_V_LOW(%%mm1, %%mm2, %%mm3, %%mm0, %5, %6, %5, 48(%0), 56(%0), 64(%0),104(%0), (%1, %3), OP)\ "add %4, %1 \n\t"\ QPEL_V_LOW(%%mm2, %%mm3, %%mm0, %%mm1, %5, %6, %5, 56(%0), 64(%0), 72(%0),112(%0), (%1), OP)\ QPEL_V_LOW(%%mm3, %%mm0, %%mm1, %%mm2, %5, %6, %5, 64(%0), 72(%0), 80(%0),120(%0), (%1, %3), OP)\ "add %4, %1 \n\t"\ QPEL_V_LOW(%%mm0, %%mm1, %%mm2, %%mm3, %5, %6, %5, 72(%0), 80(%0), 88(%0),128(%0), (%1), OP)\ \ QPEL_V_LOW(%%mm1, %%mm2, %%mm3, %%mm0, %5, %6, %5, 80(%0), 88(%0), 96(%0),128(%0), (%1, %3), OP)\ "add %4, %1 \n\t" \ QPEL_V_LOW(%%mm2, %%mm3, %%mm0, %%mm1, %5, %6, %5, 88(%0), 96(%0),104(%0),120(%0), (%1), OP)\ QPEL_V_LOW(%%mm3, %%mm0, %%mm1, %%mm2, %5, %6, %5, 96(%0),104(%0),112(%0),112(%0), (%1, %3), OP)\ \ "add $136, %0 \n\t"\ "add %6, %1 \n\t"\ "decl %2 \n\t"\ " jnz 1b \n\t"\ \ : "+r"(temp_ptr), "+r"(dst), "+g"(count)\ : "r"((x86_reg)dstStride), "r"(2*(x86_reg)dstStride), /*"m"(ff_pw_20), "m"(ff_pw_3),*/ "m"(ROUNDER), "g"(4-14*(x86_reg)dstStride)\ :"memory"\ );\ }\ \ static void OPNAME ## mpeg4_qpel8_v_lowpass_ ## MMX(uint8_t *dst, uint8_t *src, int dstStride, int srcStride){\ uint64_t temp[9*2];\ uint64_t *temp_ptr= temp;\ int count= 9;\ \ /*FIXME unroll */\ __asm__ volatile(\ "pxor %%mm7, %%mm7 \n\t"\ "1: \n\t"\ "movq (%0), %%mm0 \n\t"\ "movq (%0), %%mm1 \n\t"\ "punpcklbw %%mm7, %%mm0 \n\t"\ "punpckhbw %%mm7, %%mm1 \n\t"\ "movq %%mm0, (%1) \n\t"\ "movq %%mm1, 9*8(%1) \n\t"\ "add $8, %1 \n\t"\ "add %3, %0 \n\t"\ "decl %2 \n\t"\ " jnz 1b \n\t"\ : "+r" (src), "+r" (temp_ptr), "+r"(count)\ : "r" ((x86_reg)srcStride)\ : "memory"\ );\ \ temp_ptr= temp;\ count=2;\ \ /*FIXME reorder for speed */\ __asm__ volatile(\ /*"pxor %%mm7, %%mm7 \n\t"*/\ "1: \n\t"\ "movq (%0), %%mm0 \n\t"\ "movq 8(%0), %%mm1 \n\t"\ "movq 16(%0), %%mm2 \n\t"\ "movq 24(%0), %%mm3 \n\t"\ QPEL_V_LOW(%%mm0, %%mm1, %%mm2, %%mm3, %5, %6, %5, 16(%0), 8(%0), (%0), 32(%0), (%1), OP)\ QPEL_V_LOW(%%mm1, %%mm2, %%mm3, %%mm0, %5, %6, %5, 8(%0), (%0), (%0), 40(%0), (%1, %3), OP)\ "add %4, %1 \n\t"\ QPEL_V_LOW(%%mm2, %%mm3, %%mm0, %%mm1, %5, %6, %5, (%0), (%0), 8(%0), 48(%0), (%1), OP)\ \ QPEL_V_LOW(%%mm3, %%mm0, %%mm1, %%mm2, %5, %6, %5, (%0), 8(%0), 16(%0), 56(%0), (%1, %3), OP)\ "add %4, %1 \n\t"\ QPEL_V_LOW(%%mm0, %%mm1, %%mm2, %%mm3, %5, %6, %5, 8(%0), 16(%0), 24(%0), 64(%0), (%1), OP)\ \ QPEL_V_LOW(%%mm1, %%mm2, %%mm3, %%mm0, %5, %6, %5, 16(%0), 24(%0), 32(%0), 64(%0), (%1, %3), OP)\ "add %4, %1 \n\t"\ QPEL_V_LOW(%%mm2, %%mm3, %%mm0, %%mm1, %5, %6, %5, 24(%0), 32(%0), 40(%0), 56(%0), (%1), OP)\ QPEL_V_LOW(%%mm3, %%mm0, %%mm1, %%mm2, %5, %6, %5, 32(%0), 40(%0), 48(%0), 48(%0), (%1, %3), OP)\ \ "add $72, %0 \n\t"\ "add %6, %1 \n\t"\ "decl %2 \n\t"\ " jnz 1b \n\t"\ \ : "+r"(temp_ptr), "+r"(dst), "+g"(count)\ : "r"((x86_reg)dstStride), "r"(2*(x86_reg)dstStride), /*"m"(ff_pw_20), "m"(ff_pw_3),*/ "m"(ROUNDER), "g"(4-6*(x86_reg)dstStride)\ : "memory"\ );\ }\ \ static void OPNAME ## qpel8_mc00_ ## MMX (uint8_t *dst, uint8_t *src, int stride){\ OPNAME ## pixels8_ ## MMX(dst, src, stride, 8);\ }\ \ static void OPNAME ## qpel8_mc10_ ## MMX(uint8_t *dst, uint8_t *src, int stride){\ uint64_t temp[8];\ uint8_t * const half= (uint8_t*)temp;\ put ## RND ## mpeg4_qpel8_h_lowpass_ ## MMX(half, src, 8, stride, 8);\ OPNAME ## pixels8_l2_ ## MMX(dst, src, half, stride, stride, 8);\ }\ \ static void OPNAME ## qpel8_mc20_ ## MMX(uint8_t *dst, uint8_t *src, int stride){\ OPNAME ## mpeg4_qpel8_h_lowpass_ ## MMX(dst, src, stride, stride, 8);\ }\ \ static void OPNAME ## qpel8_mc30_ ## MMX(uint8_t *dst, uint8_t *src, int stride){\ uint64_t temp[8];\ uint8_t * const half= (uint8_t*)temp;\ put ## RND ## mpeg4_qpel8_h_lowpass_ ## MMX(half, src, 8, stride, 8);\ OPNAME ## pixels8_l2_ ## MMX(dst, src+1, half, stride, stride, 8);\ }\ \ static void OPNAME ## qpel8_mc01_ ## MMX(uint8_t *dst, uint8_t *src, int stride){\ uint64_t temp[8];\ uint8_t * const half= (uint8_t*)temp;\ put ## RND ## mpeg4_qpel8_v_lowpass_ ## MMX(half, src, 8, stride);\ OPNAME ## pixels8_l2_ ## MMX(dst, src, half, stride, stride, 8);\ }\ \ static void OPNAME ## qpel8_mc02_ ## MMX(uint8_t *dst, uint8_t *src, int stride){\ OPNAME ## mpeg4_qpel8_v_lowpass_ ## MMX(dst, src, stride, stride);\ }\ \ static void OPNAME ## qpel8_mc03_ ## MMX(uint8_t *dst, uint8_t *src, int stride){\ uint64_t temp[8];\ uint8_t * const half= (uint8_t*)temp;\ put ## RND ## mpeg4_qpel8_v_lowpass_ ## MMX(half, src, 8, stride);\ OPNAME ## pixels8_l2_ ## MMX(dst, src+stride, half, stride, stride, 8);\ }\ static void OPNAME ## qpel8_mc11_ ## MMX(uint8_t *dst, uint8_t *src, int stride){\ uint64_t half[8 + 9];\ uint8_t * const halfH= ((uint8_t*)half) + 64;\ uint8_t * const halfHV= ((uint8_t*)half);\ put ## RND ## mpeg4_qpel8_h_lowpass_ ## MMX(halfH, src, 8, stride, 9);\ put ## RND ## pixels8_l2_ ## MMX(halfH, src, halfH, 8, stride, 9);\ put ## RND ## mpeg4_qpel8_v_lowpass_ ## MMX(halfHV, halfH, 8, 8);\ OPNAME ## pixels8_l2_ ## MMX(dst, halfH, halfHV, stride, 8, 8);\ }\ static void OPNAME ## qpel8_mc31_ ## MMX(uint8_t *dst, uint8_t *src, int stride){\ uint64_t half[8 + 9];\ uint8_t * const halfH= ((uint8_t*)half) + 64;\ uint8_t * const halfHV= ((uint8_t*)half);\ put ## RND ## mpeg4_qpel8_h_lowpass_ ## MMX(halfH, src, 8, stride, 9);\ put ## RND ## pixels8_l2_ ## MMX(halfH, src+1, halfH, 8, stride, 9);\ put ## RND ## mpeg4_qpel8_v_lowpass_ ## MMX(halfHV, halfH, 8, 8);\ OPNAME ## pixels8_l2_ ## MMX(dst, halfH, halfHV, stride, 8, 8);\ }\ static void OPNAME ## qpel8_mc13_ ## MMX(uint8_t *dst, uint8_t *src, int stride){\ uint64_t half[8 + 9];\ uint8_t * const halfH= ((uint8_t*)half) + 64;\ uint8_t * const halfHV= ((uint8_t*)half);\ put ## RND ## mpeg4_qpel8_h_lowpass_ ## MMX(halfH, src, 8, stride, 9);\ put ## RND ## pixels8_l2_ ## MMX(halfH, src, halfH, 8, stride, 9);\ put ## RND ## mpeg4_qpel8_v_lowpass_ ## MMX(halfHV, halfH, 8, 8);\ OPNAME ## pixels8_l2_ ## MMX(dst, halfH+8, halfHV, stride, 8, 8);\ }\ static void OPNAME ## qpel8_mc33_ ## MMX(uint8_t *dst, uint8_t *src, int stride){\ uint64_t half[8 + 9];\ uint8_t * const halfH= ((uint8_t*)half) + 64;\ uint8_t * const halfHV= ((uint8_t*)half);\ put ## RND ## mpeg4_qpel8_h_lowpass_ ## MMX(halfH, src, 8, stride, 9);\ put ## RND ## pixels8_l2_ ## MMX(halfH, src+1, halfH, 8, stride, 9);\ put ## RND ## mpeg4_qpel8_v_lowpass_ ## MMX(halfHV, halfH, 8, 8);\ OPNAME ## pixels8_l2_ ## MMX(dst, halfH+8, halfHV, stride, 8, 8);\ }\ static void OPNAME ## qpel8_mc21_ ## MMX(uint8_t *dst, uint8_t *src, int stride){\ uint64_t half[8 + 9];\ uint8_t * const halfH= ((uint8_t*)half) + 64;\ uint8_t * const halfHV= ((uint8_t*)half);\ put ## RND ## mpeg4_qpel8_h_lowpass_ ## MMX(halfH, src, 8, stride, 9);\ put ## RND ## mpeg4_qpel8_v_lowpass_ ## MMX(halfHV, halfH, 8, 8);\ OPNAME ## pixels8_l2_ ## MMX(dst, halfH, halfHV, stride, 8, 8);\ }\ static void OPNAME ## qpel8_mc23_ ## MMX(uint8_t *dst, uint8_t *src, int stride){\ uint64_t half[8 + 9];\ uint8_t * const halfH= ((uint8_t*)half) + 64;\ uint8_t * const halfHV= ((uint8_t*)half);\ put ## RND ## mpeg4_qpel8_h_lowpass_ ## MMX(halfH, src, 8, stride, 9);\ put ## RND ## mpeg4_qpel8_v_lowpass_ ## MMX(halfHV, halfH, 8, 8);\ OPNAME ## pixels8_l2_ ## MMX(dst, halfH+8, halfHV, stride, 8, 8);\ }\ static void OPNAME ## qpel8_mc12_ ## MMX(uint8_t *dst, uint8_t *src, int stride){\ uint64_t half[8 + 9];\ uint8_t * const halfH= ((uint8_t*)half);\ put ## RND ## mpeg4_qpel8_h_lowpass_ ## MMX(halfH, src, 8, stride, 9);\ put ## RND ## pixels8_l2_ ## MMX(halfH, src, halfH, 8, stride, 9);\ OPNAME ## mpeg4_qpel8_v_lowpass_ ## MMX(dst, halfH, stride, 8);\ }\ static void OPNAME ## qpel8_mc32_ ## MMX(uint8_t *dst, uint8_t *src, int stride){\ uint64_t half[8 + 9];\ uint8_t * const halfH= ((uint8_t*)half);\ put ## RND ## mpeg4_qpel8_h_lowpass_ ## MMX(halfH, src, 8, stride, 9);\ put ## RND ## pixels8_l2_ ## MMX(halfH, src+1, halfH, 8, stride, 9);\ OPNAME ## mpeg4_qpel8_v_lowpass_ ## MMX(dst, halfH, stride, 8);\ }\ static void OPNAME ## qpel8_mc22_ ## MMX(uint8_t *dst, uint8_t *src, int stride){\ uint64_t half[9];\ uint8_t * const halfH= ((uint8_t*)half);\ put ## RND ## mpeg4_qpel8_h_lowpass_ ## MMX(halfH, src, 8, stride, 9);\ OPNAME ## mpeg4_qpel8_v_lowpass_ ## MMX(dst, halfH, stride, 8);\ }\ static void OPNAME ## qpel16_mc00_ ## MMX (uint8_t *dst, uint8_t *src, int stride){\ OPNAME ## pixels16_ ## MMX(dst, src, stride, 16);\ }\ \ static void OPNAME ## qpel16_mc10_ ## MMX(uint8_t *dst, uint8_t *src, int stride){\ uint64_t temp[32];\ uint8_t * const half= (uint8_t*)temp;\ put ## RND ## mpeg4_qpel16_h_lowpass_ ## MMX(half, src, 16, stride, 16);\ OPNAME ## pixels16_l2_ ## MMX(dst, src, half, stride, stride, 16);\ }\ \ static void OPNAME ## qpel16_mc20_ ## MMX(uint8_t *dst, uint8_t *src, int stride){\ OPNAME ## mpeg4_qpel16_h_lowpass_ ## MMX(dst, src, stride, stride, 16);\ }\ \ static void OPNAME ## qpel16_mc30_ ## MMX(uint8_t *dst, uint8_t *src, int stride){\ uint64_t temp[32];\ uint8_t * const half= (uint8_t*)temp;\ put ## RND ## mpeg4_qpel16_h_lowpass_ ## MMX(half, src, 16, stride, 16);\ OPNAME ## pixels16_l2_ ## MMX(dst, src+1, half, stride, stride, 16);\ }\ \ static void OPNAME ## qpel16_mc01_ ## MMX(uint8_t *dst, uint8_t *src, int stride){\ uint64_t temp[32];\ uint8_t * const half= (uint8_t*)temp;\ put ## RND ## mpeg4_qpel16_v_lowpass_ ## MMX(half, src, 16, stride);\ OPNAME ## pixels16_l2_ ## MMX(dst, src, half, stride, stride, 16);\ }\ \ static void OPNAME ## qpel16_mc02_ ## MMX(uint8_t *dst, uint8_t *src, int stride){\ OPNAME ## mpeg4_qpel16_v_lowpass_ ## MMX(dst, src, stride, stride);\ }\ \ static void OPNAME ## qpel16_mc03_ ## MMX(uint8_t *dst, uint8_t *src, int stride){\ uint64_t temp[32];\ uint8_t * const half= (uint8_t*)temp;\ put ## RND ## mpeg4_qpel16_v_lowpass_ ## MMX(half, src, 16, stride);\ OPNAME ## pixels16_l2_ ## MMX(dst, src+stride, half, stride, stride, 16);\ }\ static void OPNAME ## qpel16_mc11_ ## MMX(uint8_t *dst, uint8_t *src, int stride){\ uint64_t half[16*2 + 17*2];\ uint8_t * const halfH= ((uint8_t*)half) + 256;\ uint8_t * const halfHV= ((uint8_t*)half);\ put ## RND ## mpeg4_qpel16_h_lowpass_ ## MMX(halfH, src, 16, stride, 17);\ put ## RND ## pixels16_l2_ ## MMX(halfH, src, halfH, 16, stride, 17);\ put ## RND ## mpeg4_qpel16_v_lowpass_ ## MMX(halfHV, halfH, 16, 16);\ OPNAME ## pixels16_l2_ ## MMX(dst, halfH, halfHV, stride, 16, 16);\ }\ static void OPNAME ## qpel16_mc31_ ## MMX(uint8_t *dst, uint8_t *src, int stride){\ uint64_t half[16*2 + 17*2];\ uint8_t * const halfH= ((uint8_t*)half) + 256;\ uint8_t * const halfHV= ((uint8_t*)half);\ put ## RND ## mpeg4_qpel16_h_lowpass_ ## MMX(halfH, src, 16, stride, 17);\ put ## RND ## pixels16_l2_ ## MMX(halfH, src+1, halfH, 16, stride, 17);\ put ## RND ## mpeg4_qpel16_v_lowpass_ ## MMX(halfHV, halfH, 16, 16);\ OPNAME ## pixels16_l2_ ## MMX(dst, halfH, halfHV, stride, 16, 16);\ }\ static void OPNAME ## qpel16_mc13_ ## MMX(uint8_t *dst, uint8_t *src, int stride){\ uint64_t half[16*2 + 17*2];\ uint8_t * const halfH= ((uint8_t*)half) + 256;\ uint8_t * const halfHV= ((uint8_t*)half);\ put ## RND ## mpeg4_qpel16_h_lowpass_ ## MMX(halfH, src, 16, stride, 17);\ put ## RND ## pixels16_l2_ ## MMX(halfH, src, halfH, 16, stride, 17);\ put ## RND ## mpeg4_qpel16_v_lowpass_ ## MMX(halfHV, halfH, 16, 16);\ OPNAME ## pixels16_l2_ ## MMX(dst, halfH+16, halfHV, stride, 16, 16);\ }\ static void OPNAME ## qpel16_mc33_ ## MMX(uint8_t *dst, uint8_t *src, int stride){\ uint64_t half[16*2 + 17*2];\ uint8_t * const halfH= ((uint8_t*)half) + 256;\ uint8_t * const halfHV= ((uint8_t*)half);\ put ## RND ## mpeg4_qpel16_h_lowpass_ ## MMX(halfH, src, 16, stride, 17);\ put ## RND ## pixels16_l2_ ## MMX(halfH, src+1, halfH, 16, stride, 17);\ put ## RND ## mpeg4_qpel16_v_lowpass_ ## MMX(halfHV, halfH, 16, 16);\ OPNAME ## pixels16_l2_ ## MMX(dst, halfH+16, halfHV, stride, 16, 16);\ }\ static void OPNAME ## qpel16_mc21_ ## MMX(uint8_t *dst, uint8_t *src, int stride){\ uint64_t half[16*2 + 17*2];\ uint8_t * const halfH= ((uint8_t*)half) + 256;\ uint8_t * const halfHV= ((uint8_t*)half);\ put ## RND ## mpeg4_qpel16_h_lowpass_ ## MMX(halfH, src, 16, stride, 17);\ put ## RND ## mpeg4_qpel16_v_lowpass_ ## MMX(halfHV, halfH, 16, 16);\ OPNAME ## pixels16_l2_ ## MMX(dst, halfH, halfHV, stride, 16, 16);\ }\ static void OPNAME ## qpel16_mc23_ ## MMX(uint8_t *dst, uint8_t *src, int stride){\ uint64_t half[16*2 + 17*2];\ uint8_t * const halfH= ((uint8_t*)half) + 256;\ uint8_t * const halfHV= ((uint8_t*)half);\ put ## RND ## mpeg4_qpel16_h_lowpass_ ## MMX(halfH, src, 16, stride, 17);\ put ## RND ## mpeg4_qpel16_v_lowpass_ ## MMX(halfHV, halfH, 16, 16);\ OPNAME ## pixels16_l2_ ## MMX(dst, halfH+16, halfHV, stride, 16, 16);\ }\ static void OPNAME ## qpel16_mc12_ ## MMX(uint8_t *dst, uint8_t *src, int stride){\ uint64_t half[17*2];\ uint8_t * const halfH= ((uint8_t*)half);\ put ## RND ## mpeg4_qpel16_h_lowpass_ ## MMX(halfH, src, 16, stride, 17);\ put ## RND ## pixels16_l2_ ## MMX(halfH, src, halfH, 16, stride, 17);\ OPNAME ## mpeg4_qpel16_v_lowpass_ ## MMX(dst, halfH, stride, 16);\ }\ static void OPNAME ## qpel16_mc32_ ## MMX(uint8_t *dst, uint8_t *src, int stride){\ uint64_t half[17*2];\ uint8_t * const halfH= ((uint8_t*)half);\ put ## RND ## mpeg4_qpel16_h_lowpass_ ## MMX(halfH, src, 16, stride, 17);\ put ## RND ## pixels16_l2_ ## MMX(halfH, src+1, halfH, 16, stride, 17);\ OPNAME ## mpeg4_qpel16_v_lowpass_ ## MMX(dst, halfH, stride, 16);\ }\ static void OPNAME ## qpel16_mc22_ ## MMX(uint8_t *dst, uint8_t *src, int stride){\ uint64_t half[17*2];\ uint8_t * const halfH= ((uint8_t*)half);\ put ## RND ## mpeg4_qpel16_h_lowpass_ ## MMX(halfH, src, 16, stride, 17);\ OPNAME ## mpeg4_qpel16_v_lowpass_ ## MMX(dst, halfH, stride, 16);\ } #define PUT_OP(a,b,temp, size) "mov" #size " " #a ", " #b " \n\t" #define AVG_3DNOW_OP(a,b,temp, size) \ "mov" #size " " #b ", " #temp " \n\t"\ "pavgusb " #temp ", " #a " \n\t"\ "mov" #size " " #a ", " #b " \n\t" #define AVG_MMX2_OP(a,b,temp, size) \ "mov" #size " " #b ", " #temp " \n\t"\ "pavgb " #temp ", " #a " \n\t"\ "mov" #size " " #a ", " #b " \n\t" QPEL_BASE(put_ , ff_pw_16, _ , PUT_OP, PUT_OP) QPEL_BASE(avg_ , ff_pw_16, _ , AVG_MMX2_OP, AVG_3DNOW_OP) QPEL_BASE(put_no_rnd_, ff_pw_15, _no_rnd_, PUT_OP, PUT_OP) QPEL_OP(put_ , ff_pw_16, _ , PUT_OP, 3dnow) QPEL_OP(avg_ , ff_pw_16, _ , AVG_3DNOW_OP, 3dnow) QPEL_OP(put_no_rnd_, ff_pw_15, _no_rnd_, PUT_OP, 3dnow) QPEL_OP(put_ , ff_pw_16, _ , PUT_OP, mmx2) QPEL_OP(avg_ , ff_pw_16, _ , AVG_MMX2_OP, mmx2) QPEL_OP(put_no_rnd_, ff_pw_15, _no_rnd_, PUT_OP, mmx2) /***********************************/ /* bilinear qpel: not compliant to any spec, only for -lavdopts fast */ #define QPEL_2TAP_XY(OPNAME, SIZE, MMX, XY, HPEL)\ static void OPNAME ## 2tap_qpel ## SIZE ## _mc ## XY ## _ ## MMX(uint8_t *dst, uint8_t *src, int stride){\ OPNAME ## pixels ## SIZE ## HPEL(dst, src, stride, SIZE);\ } #define QPEL_2TAP_L3(OPNAME, SIZE, MMX, XY, S0, S1, S2)\ static void OPNAME ## 2tap_qpel ## SIZE ## _mc ## XY ## _ ## MMX(uint8_t *dst, uint8_t *src, int stride){\ OPNAME ## 2tap_qpel ## SIZE ## _l3_ ## MMX(dst, src+S0, stride, SIZE, S1, S2);\ } #define QPEL_2TAP(OPNAME, SIZE, MMX)\ QPEL_2TAP_XY(OPNAME, SIZE, MMX, 20, _x2_ ## MMX)\ QPEL_2TAP_XY(OPNAME, SIZE, MMX, 02, _y2_ ## MMX)\ QPEL_2TAP_XY(OPNAME, SIZE, MMX, 22, _xy2_mmx)\ static const qpel_mc_func OPNAME ## 2tap_qpel ## SIZE ## _mc00_ ## MMX =\ OPNAME ## qpel ## SIZE ## _mc00_ ## MMX;\ static const qpel_mc_func OPNAME ## 2tap_qpel ## SIZE ## _mc21_ ## MMX =\ OPNAME ## 2tap_qpel ## SIZE ## _mc20_ ## MMX;\ static const qpel_mc_func OPNAME ## 2tap_qpel ## SIZE ## _mc12_ ## MMX =\ OPNAME ## 2tap_qpel ## SIZE ## _mc02_ ## MMX;\ static void OPNAME ## 2tap_qpel ## SIZE ## _mc32_ ## MMX(uint8_t *dst, uint8_t *src, int stride){\ OPNAME ## pixels ## SIZE ## _y2_ ## MMX(dst, src+1, stride, SIZE);\ }\ static void OPNAME ## 2tap_qpel ## SIZE ## _mc23_ ## MMX(uint8_t *dst, uint8_t *src, int stride){\ OPNAME ## pixels ## SIZE ## _x2_ ## MMX(dst, src+stride, stride, SIZE);\ }\ QPEL_2TAP_L3(OPNAME, SIZE, MMX, 10, 0, 1, 0)\ QPEL_2TAP_L3(OPNAME, SIZE, MMX, 30, 1, -1, 0)\ QPEL_2TAP_L3(OPNAME, SIZE, MMX, 01, 0, stride, 0)\ QPEL_2TAP_L3(OPNAME, SIZE, MMX, 03, stride, -stride, 0)\ QPEL_2TAP_L3(OPNAME, SIZE, MMX, 11, 0, stride, 1)\ QPEL_2TAP_L3(OPNAME, SIZE, MMX, 31, 1, stride, -1)\ QPEL_2TAP_L3(OPNAME, SIZE, MMX, 13, stride, -stride, 1)\ QPEL_2TAP_L3(OPNAME, SIZE, MMX, 33, stride+1, -stride, -1)\ QPEL_2TAP(put_, 16, mmx2) QPEL_2TAP(avg_, 16, mmx2) QPEL_2TAP(put_, 8, mmx2) QPEL_2TAP(avg_, 8, mmx2) QPEL_2TAP(put_, 16, 3dnow) QPEL_2TAP(avg_, 16, 3dnow) QPEL_2TAP(put_, 8, 3dnow) QPEL_2TAP(avg_, 8, 3dnow) #if 0 static void just_return(void) { return; } #endif static void gmc_mmx(uint8_t *dst, uint8_t *src, int stride, int h, int ox, int oy, int dxx, int dxy, int dyx, int dyy, int shift, int r, int width, int height){ const int w = 8; const int ix = ox>>(16+shift); const int iy = oy>>(16+shift); const int oxs = ox>>4; const int oys = oy>>4; const int dxxs = dxx>>4; const int dxys = dxy>>4; const int dyxs = dyx>>4; const int dyys = dyy>>4; const uint16_t r4[4] = {r,r,r,r}; const uint16_t dxy4[4] = {dxys,dxys,dxys,dxys}; const uint16_t dyy4[4] = {dyys,dyys,dyys,dyys}; const uint64_t shift2 = 2*shift; uint8_t edge_buf[(h+1)*stride]; int x, y; const int dxw = (dxx-(1<<(16+shift)))*(w-1); const int dyh = (dyy-(1<<(16+shift)))*(h-1); const int dxh = dxy*(h-1); const int dyw = dyx*(w-1); if( // non-constant fullpel offset (3% of blocks) ((ox^(ox+dxw)) | (ox^(ox+dxh)) | (ox^(ox+dxw+dxh)) | (oy^(oy+dyw)) | (oy^(oy+dyh)) | (oy^(oy+dyw+dyh))) >> (16+shift) // uses more than 16 bits of subpel mv (only at huge resolution) || (dxx|dxy|dyx|dyy)&15 ) { //FIXME could still use mmx for some of the rows ff_gmc_c(dst, src, stride, h, ox, oy, dxx, dxy, dyx, dyy, shift, r, width, height); return; } src += ix + iy*stride; if( (unsigned)ix >= width-w || (unsigned)iy >= height-h ) { ff_emulated_edge_mc(edge_buf, src, stride, w+1, h+1, ix, iy, width, height); src = edge_buf; } __asm__ volatile( "movd %0, %%mm6 \n\t" "pxor %%mm7, %%mm7 \n\t" "punpcklwd %%mm6, %%mm6 \n\t" "punpcklwd %%mm6, %%mm6 \n\t" :: "r"(1<<shift) ); for(x=0; x<w; x+=4){ uint16_t dx4[4] = { oxs - dxys + dxxs*(x+0), oxs - dxys + dxxs*(x+1), oxs - dxys + dxxs*(x+2), oxs - dxys + dxxs*(x+3) }; uint16_t dy4[4] = { oys - dyys + dyxs*(x+0), oys - dyys + dyxs*(x+1), oys - dyys + dyxs*(x+2), oys - dyys + dyxs*(x+3) }; for(y=0; y<h; y++){ __asm__ volatile( "movq %0, %%mm4 \n\t" "movq %1, %%mm5 \n\t" "paddw %2, %%mm4 \n\t" "paddw %3, %%mm5 \n\t" "movq %%mm4, %0 \n\t" "movq %%mm5, %1 \n\t" "psrlw $12, %%mm4 \n\t" "psrlw $12, %%mm5 \n\t" : "+m"(*dx4), "+m"(*dy4) : "m"(*dxy4), "m"(*dyy4) ); __asm__ volatile( "movq %%mm6, %%mm2 \n\t" "movq %%mm6, %%mm1 \n\t" "psubw %%mm4, %%mm2 \n\t" "psubw %%mm5, %%mm1 \n\t" "movq %%mm2, %%mm0 \n\t" "movq %%mm4, %%mm3 \n\t" "pmullw %%mm1, %%mm0 \n\t" // (s-dx)*(s-dy) "pmullw %%mm5, %%mm3 \n\t" // dx*dy "pmullw %%mm5, %%mm2 \n\t" // (s-dx)*dy "pmullw %%mm4, %%mm1 \n\t" // dx*(s-dy) "movd %4, %%mm5 \n\t" "movd %3, %%mm4 \n\t" "punpcklbw %%mm7, %%mm5 \n\t" "punpcklbw %%mm7, %%mm4 \n\t" "pmullw %%mm5, %%mm3 \n\t" // src[1,1] * dx*dy "pmullw %%mm4, %%mm2 \n\t" // src[0,1] * (s-dx)*dy "movd %2, %%mm5 \n\t" "movd %1, %%mm4 \n\t" "punpcklbw %%mm7, %%mm5 \n\t" "punpcklbw %%mm7, %%mm4 \n\t" "pmullw %%mm5, %%mm1 \n\t" // src[1,0] * dx*(s-dy) "pmullw %%mm4, %%mm0 \n\t" // src[0,0] * (s-dx)*(s-dy) "paddw %5, %%mm1 \n\t" "paddw %%mm3, %%mm2 \n\t" "paddw %%mm1, %%mm0 \n\t" "paddw %%mm2, %%mm0 \n\t" "psrlw %6, %%mm0 \n\t" "packuswb %%mm0, %%mm0 \n\t" "movd %%mm0, %0 \n\t" : "=m"(dst[x+y*stride]) : "m"(src[0]), "m"(src[1]), "m"(src[stride]), "m"(src[stride+1]), "m"(*r4), "m"(shift2) ); src += stride; } src += 4-h*stride; } } #define PREFETCH(name, op) \ static void name(void *mem, int stride, int h){\ const uint8_t *p= mem;\ do{\ __asm__ volatile(#op" %0" :: "m"(*p));\ p+= stride;\ }while(--h);\ } PREFETCH(prefetch_mmx2, prefetcht0) PREFETCH(prefetch_3dnow, prefetch) #undef PREFETCH #include "h264dsp_mmx.c" #include "rv40dsp_mmx.c" /* CAVS specific */ void ff_put_cavs_qpel8_mc00_mmx2(uint8_t *dst, uint8_t *src, int stride) { put_pixels8_mmx(dst, src, stride, 8); } void ff_avg_cavs_qpel8_mc00_mmx2(uint8_t *dst, uint8_t *src, int stride) { avg_pixels8_mmx(dst, src, stride, 8); } void ff_put_cavs_qpel16_mc00_mmx2(uint8_t *dst, uint8_t *src, int stride) { put_pixels16_mmx(dst, src, stride, 16); } void ff_avg_cavs_qpel16_mc00_mmx2(uint8_t *dst, uint8_t *src, int stride) { avg_pixels16_mmx(dst, src, stride, 16); } /* VC1 specific */ void ff_put_vc1_mspel_mc00_mmx(uint8_t *dst, const uint8_t *src, int stride, int rnd) { put_pixels8_mmx(dst, src, stride, 8); } void ff_avg_vc1_mspel_mc00_mmx2(uint8_t *dst, const uint8_t *src, int stride, int rnd) { avg_pixels8_mmx2(dst, src, stride, 8); } /* XXX: those functions should be suppressed ASAP when all IDCTs are converted */ #if CONFIG_GPL static void ff_libmpeg2mmx_idct_put(uint8_t *dest, int line_size, DCTELEM *block) { ff_mmx_idct (block); put_pixels_clamped_mmx(block, dest, line_size); } static void ff_libmpeg2mmx_idct_add(uint8_t *dest, int line_size, DCTELEM *block) { ff_mmx_idct (block); add_pixels_clamped_mmx(block, dest, line_size); } static void ff_libmpeg2mmx2_idct_put(uint8_t *dest, int line_size, DCTELEM *block) { ff_mmxext_idct (block); put_pixels_clamped_mmx(block, dest, line_size); } static void ff_libmpeg2mmx2_idct_add(uint8_t *dest, int line_size, DCTELEM *block) { ff_mmxext_idct (block); add_pixels_clamped_mmx(block, dest, line_size); } #endif static void ff_idct_xvid_mmx_put(uint8_t *dest, int line_size, DCTELEM *block) { ff_idct_xvid_mmx (block); put_pixels_clamped_mmx(block, dest, line_size); } static void ff_idct_xvid_mmx_add(uint8_t *dest, int line_size, DCTELEM *block) { ff_idct_xvid_mmx (block); add_pixels_clamped_mmx(block, dest, line_size); } static void ff_idct_xvid_mmx2_put(uint8_t *dest, int line_size, DCTELEM *block) { ff_idct_xvid_mmx2 (block); put_pixels_clamped_mmx(block, dest, line_size); } static void ff_idct_xvid_mmx2_add(uint8_t *dest, int line_size, DCTELEM *block) { ff_idct_xvid_mmx2 (block); add_pixels_clamped_mmx(block, dest, line_size); } static void vorbis_inverse_coupling_3dnow(float *mag, float *ang, int blocksize) { int i; __asm__ volatile("pxor %%mm7, %%mm7":); for(i=0; i<blocksize; i+=2) { __asm__ volatile( "movq %0, %%mm0 \n\t" "movq %1, %%mm1 \n\t" "movq %%mm0, %%mm2 \n\t" "movq %%mm1, %%mm3 \n\t" "pfcmpge %%mm7, %%mm2 \n\t" // m <= 0.0 "pfcmpge %%mm7, %%mm3 \n\t" // a <= 0.0 "pslld $31, %%mm2 \n\t" // keep only the sign bit "pxor %%mm2, %%mm1 \n\t" "movq %%mm3, %%mm4 \n\t" "pand %%mm1, %%mm3 \n\t" "pandn %%mm1, %%mm4 \n\t" "pfadd %%mm0, %%mm3 \n\t" // a = m + ((a<0) & (a ^ sign(m))) "pfsub %%mm4, %%mm0 \n\t" // m = m + ((a>0) & (a ^ sign(m))) "movq %%mm3, %1 \n\t" "movq %%mm0, %0 \n\t" :"+m"(mag[i]), "+m"(ang[i]) ::"memory" ); } __asm__ volatile("femms"); } static void vorbis_inverse_coupling_sse(float *mag, float *ang, int blocksize) { int i; __asm__ volatile( "movaps %0, %%xmm5 \n\t" ::"m"(ff_pdw_80000000[0]) ); for(i=0; i<blocksize; i+=4) { __asm__ volatile( "movaps %0, %%xmm0 \n\t" "movaps %1, %%xmm1 \n\t" "xorps %%xmm2, %%xmm2 \n\t" "xorps %%xmm3, %%xmm3 \n\t" "cmpleps %%xmm0, %%xmm2 \n\t" // m <= 0.0 "cmpleps %%xmm1, %%xmm3 \n\t" // a <= 0.0 "andps %%xmm5, %%xmm2 \n\t" // keep only the sign bit "xorps %%xmm2, %%xmm1 \n\t" "movaps %%xmm3, %%xmm4 \n\t" "andps %%xmm1, %%xmm3 \n\t" "andnps %%xmm1, %%xmm4 \n\t" "addps %%xmm0, %%xmm3 \n\t" // a = m + ((a<0) & (a ^ sign(m))) "subps %%xmm4, %%xmm0 \n\t" // m = m + ((a>0) & (a ^ sign(m))) "movaps %%xmm3, %1 \n\t" "movaps %%xmm0, %0 \n\t" :"+m"(mag[i]), "+m"(ang[i]) ::"memory" ); } } #define IF1(x) x #define IF0(x) #define MIX5(mono,stereo)\ __asm__ volatile(\ "movss 0(%2), %%xmm5 \n"\ "movss 8(%2), %%xmm6 \n"\ "movss 24(%2), %%xmm7 \n"\ "shufps $0, %%xmm5, %%xmm5 \n"\ "shufps $0, %%xmm6, %%xmm6 \n"\ "shufps $0, %%xmm7, %%xmm7 \n"\ "1: \n"\ "movaps (%0,%1), %%xmm0 \n"\ "movaps 0x400(%0,%1), %%xmm1 \n"\ "movaps 0x800(%0,%1), %%xmm2 \n"\ "movaps 0xc00(%0,%1), %%xmm3 \n"\ "movaps 0x1000(%0,%1), %%xmm4 \n"\ "mulps %%xmm5, %%xmm0 \n"\ "mulps %%xmm6, %%xmm1 \n"\ "mulps %%xmm5, %%xmm2 \n"\ "mulps %%xmm7, %%xmm3 \n"\ "mulps %%xmm7, %%xmm4 \n"\ stereo("addps %%xmm1, %%xmm0 \n")\ "addps %%xmm1, %%xmm2 \n"\ "addps %%xmm3, %%xmm0 \n"\ "addps %%xmm4, %%xmm2 \n"\ mono("addps %%xmm2, %%xmm0 \n")\ "movaps %%xmm0, (%0,%1) \n"\ stereo("movaps %%xmm2, 0x400(%0,%1) \n")\ "add $16, %0 \n"\ "jl 1b \n"\ :"+&r"(i)\ :"r"(samples[0]+len), "r"(matrix)\ :"memory"\ ); #define MIX_MISC(stereo)\ __asm__ volatile(\ "1: \n"\ "movaps (%3,%0), %%xmm0 \n"\ stereo("movaps %%xmm0, %%xmm1 \n")\ "mulps %%xmm6, %%xmm0 \n"\ stereo("mulps %%xmm7, %%xmm1 \n")\ "lea 1024(%3,%0), %1 \n"\ "mov %5, %2 \n"\ "2: \n"\ "movaps (%1), %%xmm2 \n"\ stereo("movaps %%xmm2, %%xmm3 \n")\ "mulps (%4,%2), %%xmm2 \n"\ stereo("mulps 16(%4,%2), %%xmm3 \n")\ "addps %%xmm2, %%xmm0 \n"\ stereo("addps %%xmm3, %%xmm1 \n")\ "add $1024, %1 \n"\ "add $32, %2 \n"\ "jl 2b \n"\ "movaps %%xmm0, (%3,%0) \n"\ stereo("movaps %%xmm1, 1024(%3,%0) \n")\ "add $16, %0 \n"\ "jl 1b \n"\ :"+&r"(i), "=&r"(j), "=&r"(k)\ :"r"(samples[0]+len), "r"(matrix_simd+in_ch), "g"((intptr_t)-32*(in_ch-1))\ :"memory"\ ); static void ac3_downmix_sse(float (*samples)[256], float (*matrix)[2], int out_ch, int in_ch, int len) { int (*matrix_cmp)[2] = (int(*)[2])matrix; intptr_t i,j,k; i = -len*sizeof(float); if(in_ch == 5 && out_ch == 2 && !(matrix_cmp[0][1]|matrix_cmp[2][0]|matrix_cmp[3][1]|matrix_cmp[4][0]|(matrix_cmp[1][0]^matrix_cmp[1][1])|(matrix_cmp[0][0]^matrix_cmp[2][1]))) { MIX5(IF0,IF1); } else if(in_ch == 5 && out_ch == 1 && matrix_cmp[0][0]==matrix_cmp[2][0] && matrix_cmp[3][0]==matrix_cmp[4][0]) { MIX5(IF1,IF0); } else { DECLARE_ALIGNED(16, float, matrix_simd)[in_ch][2][4]; j = 2*in_ch*sizeof(float); __asm__ volatile( "1: \n" "sub $8, %0 \n" "movss (%2,%0), %%xmm6 \n" "movss 4(%2,%0), %%xmm7 \n" "shufps $0, %%xmm6, %%xmm6 \n" "shufps $0, %%xmm7, %%xmm7 \n" "movaps %%xmm6, (%1,%0,4) \n" "movaps %%xmm7, 16(%1,%0,4) \n" "jg 1b \n" :"+&r"(j) :"r"(matrix_simd), "r"(matrix) :"memory" ); if(out_ch == 2) { MIX_MISC(IF1); } else { MIX_MISC(IF0); } } } static void vector_fmul_3dnow(float *dst, const float *src, int len){ x86_reg i = (len-4)*4; __asm__ volatile( "1: \n\t" "movq (%1,%0), %%mm0 \n\t" "movq 8(%1,%0), %%mm1 \n\t" "pfmul (%2,%0), %%mm0 \n\t" "pfmul 8(%2,%0), %%mm1 \n\t" "movq %%mm0, (%1,%0) \n\t" "movq %%mm1, 8(%1,%0) \n\t" "sub $16, %0 \n\t" "jge 1b \n\t" "femms \n\t" :"+r"(i) :"r"(dst), "r"(src) :"memory" ); } static void vector_fmul_sse(float *dst, const float *src, int len){ x86_reg i = (len-8)*4; __asm__ volatile( "1: \n\t" "movaps (%1,%0), %%xmm0 \n\t" "movaps 16(%1,%0), %%xmm1 \n\t" "mulps (%2,%0), %%xmm0 \n\t" "mulps 16(%2,%0), %%xmm1 \n\t" "movaps %%xmm0, (%1,%0) \n\t" "movaps %%xmm1, 16(%1,%0) \n\t" "sub $32, %0 \n\t" "jge 1b \n\t" :"+r"(i) :"r"(dst), "r"(src) :"memory" ); } static void vector_fmul_reverse_3dnow2(float *dst, const float *src0, const float *src1, int len){ x86_reg i = len*4-16; __asm__ volatile( "1: \n\t" "pswapd 8(%1), %%mm0 \n\t" "pswapd (%1), %%mm1 \n\t" "pfmul (%3,%0), %%mm0 \n\t" "pfmul 8(%3,%0), %%mm1 \n\t" "movq %%mm0, (%2,%0) \n\t" "movq %%mm1, 8(%2,%0) \n\t" "add $16, %1 \n\t" "sub $16, %0 \n\t" "jge 1b \n\t" :"+r"(i), "+r"(src1) :"r"(dst), "r"(src0) ); __asm__ volatile("femms"); } static void vector_fmul_reverse_sse(float *dst, const float *src0, const float *src1, int len){ x86_reg i = len*4-32; __asm__ volatile( "1: \n\t" "movaps 16(%1), %%xmm0 \n\t" "movaps (%1), %%xmm1 \n\t" "shufps $0x1b, %%xmm0, %%xmm0 \n\t" "shufps $0x1b, %%xmm1, %%xmm1 \n\t" "mulps (%3,%0), %%xmm0 \n\t" "mulps 16(%3,%0), %%xmm1 \n\t" "movaps %%xmm0, (%2,%0) \n\t" "movaps %%xmm1, 16(%2,%0) \n\t" "add $32, %1 \n\t" "sub $32, %0 \n\t" "jge 1b \n\t" :"+r"(i), "+r"(src1) :"r"(dst), "r"(src0) ); } static void vector_fmul_add_3dnow(float *dst, const float *src0, const float *src1, const float *src2, int len){ x86_reg i = (len-4)*4; __asm__ volatile( "1: \n\t" "movq (%2,%0), %%mm0 \n\t" "movq 8(%2,%0), %%mm1 \n\t" "pfmul (%3,%0), %%mm0 \n\t" "pfmul 8(%3,%0), %%mm1 \n\t" "pfadd (%4,%0), %%mm0 \n\t" "pfadd 8(%4,%0), %%mm1 \n\t" "movq %%mm0, (%1,%0) \n\t" "movq %%mm1, 8(%1,%0) \n\t" "sub $16, %0 \n\t" "jge 1b \n\t" :"+r"(i) :"r"(dst), "r"(src0), "r"(src1), "r"(src2) :"memory" ); __asm__ volatile("femms"); } static void vector_fmul_add_sse(float *dst, const float *src0, const float *src1, const float *src2, int len){ x86_reg i = (len-8)*4; __asm__ volatile( "1: \n\t" "movaps (%2,%0), %%xmm0 \n\t" "movaps 16(%2,%0), %%xmm1 \n\t" "mulps (%3,%0), %%xmm0 \n\t" "mulps 16(%3,%0), %%xmm1 \n\t" "addps (%4,%0), %%xmm0 \n\t" "addps 16(%4,%0), %%xmm1 \n\t" "movaps %%xmm0, (%1,%0) \n\t" "movaps %%xmm1, 16(%1,%0) \n\t" "sub $32, %0 \n\t" "jge 1b \n\t" :"+r"(i) :"r"(dst), "r"(src0), "r"(src1), "r"(src2) :"memory" ); } static void vector_fmul_window_3dnow2(float *dst, const float *src0, const float *src1, const float *win, float add_bias, int len){ #if HAVE_6REGS if(add_bias == 0){ x86_reg i = -len*4; x86_reg j = len*4-8; __asm__ volatile( "1: \n" "pswapd (%5,%1), %%mm1 \n" "movq (%5,%0), %%mm0 \n" "pswapd (%4,%1), %%mm5 \n" "movq (%3,%0), %%mm4 \n" "movq %%mm0, %%mm2 \n" "movq %%mm1, %%mm3 \n" "pfmul %%mm4, %%mm2 \n" // src0[len+i]*win[len+i] "pfmul %%mm5, %%mm3 \n" // src1[ j]*win[len+j] "pfmul %%mm4, %%mm1 \n" // src0[len+i]*win[len+j] "pfmul %%mm5, %%mm0 \n" // src1[ j]*win[len+i] "pfadd %%mm3, %%mm2 \n" "pfsub %%mm0, %%mm1 \n" "pswapd %%mm2, %%mm2 \n" "movq %%mm1, (%2,%0) \n" "movq %%mm2, (%2,%1) \n" "sub $8, %1 \n" "add $8, %0 \n" "jl 1b \n" "femms \n" :"+r"(i), "+r"(j) :"r"(dst+len), "r"(src0+len), "r"(src1), "r"(win+len) ); }else #endif ff_vector_fmul_window_c(dst, src0, src1, win, add_bias, len); } static void vector_fmul_window_sse(float *dst, const float *src0, const float *src1, const float *win, float add_bias, int len){ #if HAVE_6REGS if(add_bias == 0){ x86_reg i = -len*4; x86_reg j = len*4-16; __asm__ volatile( "1: \n" "movaps (%5,%1), %%xmm1 \n" "movaps (%5,%0), %%xmm0 \n" "movaps (%4,%1), %%xmm5 \n" "movaps (%3,%0), %%xmm4 \n" "shufps $0x1b, %%xmm1, %%xmm1 \n" "shufps $0x1b, %%xmm5, %%xmm5 \n" "movaps %%xmm0, %%xmm2 \n" "movaps %%xmm1, %%xmm3 \n" "mulps %%xmm4, %%xmm2 \n" // src0[len+i]*win[len+i] "mulps %%xmm5, %%xmm3 \n" // src1[ j]*win[len+j] "mulps %%xmm4, %%xmm1 \n" // src0[len+i]*win[len+j] "mulps %%xmm5, %%xmm0 \n" // src1[ j]*win[len+i] "addps %%xmm3, %%xmm2 \n" "subps %%xmm0, %%xmm1 \n" "shufps $0x1b, %%xmm2, %%xmm2 \n" "movaps %%xmm1, (%2,%0) \n" "movaps %%xmm2, (%2,%1) \n" "sub $16, %1 \n" "add $16, %0 \n" "jl 1b \n" :"+r"(i), "+r"(j) :"r"(dst+len), "r"(src0+len), "r"(src1), "r"(win+len) ); }else #endif ff_vector_fmul_window_c(dst, src0, src1, win, add_bias, len); } static void int32_to_float_fmul_scalar_sse(float *dst, const int *src, float mul, int len) { x86_reg i = -4*len; __asm__ volatile( "movss %3, %%xmm4 \n" "shufps $0, %%xmm4, %%xmm4 \n" "1: \n" "cvtpi2ps (%2,%0), %%xmm0 \n" "cvtpi2ps 8(%2,%0), %%xmm1 \n" "cvtpi2ps 16(%2,%0), %%xmm2 \n" "cvtpi2ps 24(%2,%0), %%xmm3 \n" "movlhps %%xmm1, %%xmm0 \n" "movlhps %%xmm3, %%xmm2 \n" "mulps %%xmm4, %%xmm0 \n" "mulps %%xmm4, %%xmm2 \n" "movaps %%xmm0, (%1,%0) \n" "movaps %%xmm2, 16(%1,%0) \n" "add $32, %0 \n" "jl 1b \n" :"+r"(i) :"r"(dst+len), "r"(src+len), "m"(mul) ); } static void int32_to_float_fmul_scalar_sse2(float *dst, const int *src, float mul, int len) { x86_reg i = -4*len; __asm__ volatile( "movss %3, %%xmm4 \n" "shufps $0, %%xmm4, %%xmm4 \n" "1: \n" "cvtdq2ps (%2,%0), %%xmm0 \n" "cvtdq2ps 16(%2,%0), %%xmm1 \n" "mulps %%xmm4, %%xmm0 \n" "mulps %%xmm4, %%xmm1 \n" "movaps %%xmm0, (%1,%0) \n" "movaps %%xmm1, 16(%1,%0) \n" "add $32, %0 \n" "jl 1b \n" :"+r"(i) :"r"(dst+len), "r"(src+len), "m"(mul) ); } static void vector_clipf_sse(float *dst, const float *src, float min, float max, int len) { x86_reg i = (len-16)*4; __asm__ volatile( "movss %3, %%xmm4 \n" "movss %4, %%xmm5 \n" "shufps $0, %%xmm4, %%xmm4 \n" "shufps $0, %%xmm5, %%xmm5 \n" "1: \n\t" "movaps (%2,%0), %%xmm0 \n\t" // 3/1 on intel "movaps 16(%2,%0), %%xmm1 \n\t" "movaps 32(%2,%0), %%xmm2 \n\t" "movaps 48(%2,%0), %%xmm3 \n\t" "maxps %%xmm4, %%xmm0 \n\t" "maxps %%xmm4, %%xmm1 \n\t" "maxps %%xmm4, %%xmm2 \n\t" "maxps %%xmm4, %%xmm3 \n\t" "minps %%xmm5, %%xmm0 \n\t" "minps %%xmm5, %%xmm1 \n\t" "minps %%xmm5, %%xmm2 \n\t" "minps %%xmm5, %%xmm3 \n\t" "movaps %%xmm0, (%1,%0) \n\t" "movaps %%xmm1, 16(%1,%0) \n\t" "movaps %%xmm2, 32(%1,%0) \n\t" "movaps %%xmm3, 48(%1,%0) \n\t" "sub $64, %0 \n\t" "jge 1b \n\t" :"+&r"(i) :"r"(dst), "r"(src), "m"(min), "m"(max) :"memory" ); } static void float_to_int16_3dnow(int16_t *dst, const float *src, long len){ x86_reg reglen = len; // not bit-exact: pf2id uses different rounding than C and SSE __asm__ volatile( "add %0 , %0 \n\t" "lea (%2,%0,2) , %2 \n\t" "add %0 , %1 \n\t" "neg %0 \n\t" "1: \n\t" "pf2id (%2,%0,2) , %%mm0 \n\t" "pf2id 8(%2,%0,2) , %%mm1 \n\t" "pf2id 16(%2,%0,2) , %%mm2 \n\t" "pf2id 24(%2,%0,2) , %%mm3 \n\t" "packssdw %%mm1 , %%mm0 \n\t" "packssdw %%mm3 , %%mm2 \n\t" "movq %%mm0 , (%1,%0) \n\t" "movq %%mm2 , 8(%1,%0) \n\t" "add $16 , %0 \n\t" " js 1b \n\t" "femms \n\t" :"+r"(reglen), "+r"(dst), "+r"(src) ); } static void float_to_int16_sse(int16_t *dst, const float *src, long len){ x86_reg reglen = len; __asm__ volatile( "add %0 , %0 \n\t" "lea (%2,%0,2) , %2 \n\t" "add %0 , %1 \n\t" "neg %0 \n\t" "1: \n\t" "cvtps2pi (%2,%0,2) , %%mm0 \n\t" "cvtps2pi 8(%2,%0,2) , %%mm1 \n\t" "cvtps2pi 16(%2,%0,2) , %%mm2 \n\t" "cvtps2pi 24(%2,%0,2) , %%mm3 \n\t" "packssdw %%mm1 , %%mm0 \n\t" "packssdw %%mm3 , %%mm2 \n\t" "movq %%mm0 , (%1,%0) \n\t" "movq %%mm2 , 8(%1,%0) \n\t" "add $16 , %0 \n\t" " js 1b \n\t" "emms \n\t" :"+r"(reglen), "+r"(dst), "+r"(src) ); } static void float_to_int16_sse2(int16_t *dst, const float *src, long len){ x86_reg reglen = len; __asm__ volatile( "add %0 , %0 \n\t" "lea (%2,%0,2) , %2 \n\t" "add %0 , %1 \n\t" "neg %0 \n\t" "1: \n\t" "cvtps2dq (%2,%0,2) , %%xmm0 \n\t" "cvtps2dq 16(%2,%0,2) , %%xmm1 \n\t" "packssdw %%xmm1 , %%xmm0 \n\t" "movdqa %%xmm0 , (%1,%0) \n\t" "add $16 , %0 \n\t" " js 1b \n\t" :"+r"(reglen), "+r"(dst), "+r"(src) ); } void ff_float_to_int16_interleave6_sse(int16_t *dst, const float **src, int len); void ff_float_to_int16_interleave6_3dnow(int16_t *dst, const float **src, int len); void ff_float_to_int16_interleave6_3dn2(int16_t *dst, const float **src, int len); int32_t ff_scalarproduct_int16_mmx2(int16_t *v1, int16_t *v2, int order, int shift); int32_t ff_scalarproduct_int16_sse2(int16_t *v1, int16_t *v2, int order, int shift); int32_t ff_scalarproduct_and_madd_int16_mmx2(int16_t *v1, int16_t *v2, int16_t *v3, int order, int mul); int32_t ff_scalarproduct_and_madd_int16_sse2(int16_t *v1, int16_t *v2, int16_t *v3, int order, int mul); int32_t ff_scalarproduct_and_madd_int16_ssse3(int16_t *v1, int16_t *v2, int16_t *v3, int order, int mul); void ff_add_hfyu_median_prediction_mmx2(uint8_t *dst, const uint8_t *top, const uint8_t *diff, int w, int *left, int *left_top); int ff_add_hfyu_left_prediction_ssse3(uint8_t *dst, const uint8_t *src, int w, int left); int ff_add_hfyu_left_prediction_sse4(uint8_t *dst, const uint8_t *src, int w, int left); void ff_x264_deblock_v_luma_sse2(uint8_t *pix, int stride, int alpha, int beta, int8_t *tc0); void ff_x264_deblock_h_luma_sse2(uint8_t *pix, int stride, int alpha, int beta, int8_t *tc0); void ff_x264_deblock_h_luma_intra_mmxext(uint8_t *pix, int stride, int alpha, int beta); void ff_x264_deblock_v_luma_intra_sse2(uint8_t *pix, int stride, int alpha, int beta); void ff_x264_deblock_h_luma_intra_sse2(uint8_t *pix, int stride, int alpha, int beta); #if HAVE_YASM && ARCH_X86_32 void ff_x264_deblock_v8_luma_intra_mmxext(uint8_t *pix, int stride, int alpha, int beta); static void ff_x264_deblock_v_luma_intra_mmxext(uint8_t *pix, int stride, int alpha, int beta) { ff_x264_deblock_v8_luma_intra_mmxext(pix+0, stride, alpha, beta); ff_x264_deblock_v8_luma_intra_mmxext(pix+8, stride, alpha, beta); } #elif !HAVE_YASM #define ff_float_to_int16_interleave6_sse(a,b,c) float_to_int16_interleave_misc_sse(a,b,c,6) #define ff_float_to_int16_interleave6_3dnow(a,b,c) float_to_int16_interleave_misc_3dnow(a,b,c,6) #define ff_float_to_int16_interleave6_3dn2(a,b,c) float_to_int16_interleave_misc_3dnow(a,b,c,6) #endif #define ff_float_to_int16_interleave6_sse2 ff_float_to_int16_interleave6_sse #define FLOAT_TO_INT16_INTERLEAVE(cpu, body) \ /* gcc pessimizes register allocation if this is in the same function as float_to_int16_interleave_sse2*/\ static av_noinline void float_to_int16_interleave_misc_##cpu(int16_t *dst, const float **src, long len, int channels){\ DECLARE_ALIGNED(16, int16_t, tmp)[len];\ int i,j,c;\ for(c=0; c<channels; c++){\ float_to_int16_##cpu(tmp, src[c], len);\ for(i=0, j=c; i<len; i++, j+=channels)\ dst[j] = tmp[i];\ }\ }\ \ static void float_to_int16_interleave_##cpu(int16_t *dst, const float **src, long len, int channels){\ if(channels==1)\ float_to_int16_##cpu(dst, src[0], len);\ else if(channels==2){\ x86_reg reglen = len; \ const float *src0 = src[0];\ const float *src1 = src[1];\ __asm__ volatile(\ "shl $2, %0 \n"\ "add %0, %1 \n"\ "add %0, %2 \n"\ "add %0, %3 \n"\ "neg %0 \n"\ body\ :"+r"(reglen), "+r"(dst), "+r"(src0), "+r"(src1)\ );\ }else if(channels==6){\ ff_float_to_int16_interleave6_##cpu(dst, src, len);\ }else\ float_to_int16_interleave_misc_##cpu(dst, src, len, channels);\ } FLOAT_TO_INT16_INTERLEAVE(3dnow, "1: \n" "pf2id (%2,%0), %%mm0 \n" "pf2id 8(%2,%0), %%mm1 \n" "pf2id (%3,%0), %%mm2 \n" "pf2id 8(%3,%0), %%mm3 \n" "packssdw %%mm1, %%mm0 \n" "packssdw %%mm3, %%mm2 \n" "movq %%mm0, %%mm1 \n" "punpcklwd %%mm2, %%mm0 \n" "punpckhwd %%mm2, %%mm1 \n" "movq %%mm0, (%1,%0)\n" "movq %%mm1, 8(%1,%0)\n" "add $16, %0 \n" "js 1b \n" "femms \n" ) FLOAT_TO_INT16_INTERLEAVE(sse, "1: \n" "cvtps2pi (%2,%0), %%mm0 \n" "cvtps2pi 8(%2,%0), %%mm1 \n" "cvtps2pi (%3,%0), %%mm2 \n" "cvtps2pi 8(%3,%0), %%mm3 \n" "packssdw %%mm1, %%mm0 \n" "packssdw %%mm3, %%mm2 \n" "movq %%mm0, %%mm1 \n" "punpcklwd %%mm2, %%mm0 \n" "punpckhwd %%mm2, %%mm1 \n" "movq %%mm0, (%1,%0)\n" "movq %%mm1, 8(%1,%0)\n" "add $16, %0 \n" "js 1b \n" "emms \n" ) FLOAT_TO_INT16_INTERLEAVE(sse2, "1: \n" "cvtps2dq (%2,%0), %%xmm0 \n" "cvtps2dq (%3,%0), %%xmm1 \n" "packssdw %%xmm1, %%xmm0 \n" "movhlps %%xmm0, %%xmm1 \n" "punpcklwd %%xmm1, %%xmm0 \n" "movdqa %%xmm0, (%1,%0) \n" "add $16, %0 \n" "js 1b \n" ) static void float_to_int16_interleave_3dn2(int16_t *dst, const float **src, long len, int channels){ if(channels==6) ff_float_to_int16_interleave6_3dn2(dst, src, len); else float_to_int16_interleave_3dnow(dst, src, len, channels); } float ff_scalarproduct_float_sse(const float *v1, const float *v2, int order); void dsputil_init_mmx(DSPContext* c, AVCodecContext *avctx) { mm_flags = mm_support(); if (avctx->dsp_mask) { if (avctx->dsp_mask & FF_MM_FORCE) mm_flags |= (avctx->dsp_mask & 0xffff); else mm_flags &= ~(avctx->dsp_mask & 0xffff); } #if 0 av_log(avctx, AV_LOG_INFO, "libavcodec: CPU flags:"); if (mm_flags & FF_MM_MMX) av_log(avctx, AV_LOG_INFO, " mmx"); if (mm_flags & FF_MM_MMX2) av_log(avctx, AV_LOG_INFO, " mmx2"); if (mm_flags & FF_MM_3DNOW) av_log(avctx, AV_LOG_INFO, " 3dnow"); if (mm_flags & FF_MM_SSE) av_log(avctx, AV_LOG_INFO, " sse"); if (mm_flags & FF_MM_SSE2) av_log(avctx, AV_LOG_INFO, " sse2"); av_log(avctx, AV_LOG_INFO, "\n"); #endif if (mm_flags & FF_MM_MMX) { const int idct_algo= avctx->idct_algo; if(avctx->lowres==0){ if(idct_algo==FF_IDCT_AUTO || idct_algo==FF_IDCT_SIMPLEMMX){ c->idct_put= ff_simple_idct_put_mmx; c->idct_add= ff_simple_idct_add_mmx; c->idct = ff_simple_idct_mmx; c->idct_permutation_type= FF_SIMPLE_IDCT_PERM; #if CONFIG_GPL }else if(idct_algo==FF_IDCT_LIBMPEG2MMX){ if(mm_flags & FF_MM_MMX2){ c->idct_put= ff_libmpeg2mmx2_idct_put; c->idct_add= ff_libmpeg2mmx2_idct_add; c->idct = ff_mmxext_idct; }else{ c->idct_put= ff_libmpeg2mmx_idct_put; c->idct_add= ff_libmpeg2mmx_idct_add; c->idct = ff_mmx_idct; } c->idct_permutation_type= FF_LIBMPEG2_IDCT_PERM; #endif }else if((CONFIG_VP3_DECODER || CONFIG_VP5_DECODER || CONFIG_VP6_DECODER) && idct_algo==FF_IDCT_VP3){ if(mm_flags & FF_MM_SSE2){ c->idct_put= ff_vp3_idct_put_sse2; c->idct_add= ff_vp3_idct_add_sse2; c->idct = ff_vp3_idct_sse2; c->idct_permutation_type= FF_TRANSPOSE_IDCT_PERM; }else{ c->idct_put= ff_vp3_idct_put_mmx; c->idct_add= ff_vp3_idct_add_mmx; c->idct = ff_vp3_idct_mmx; c->idct_permutation_type= FF_PARTTRANS_IDCT_PERM; } }else if(idct_algo==FF_IDCT_CAVS){ c->idct_permutation_type= FF_TRANSPOSE_IDCT_PERM; }else if(idct_algo==FF_IDCT_XVIDMMX){ if(mm_flags & FF_MM_SSE2){ c->idct_put= ff_idct_xvid_sse2_put; c->idct_add= ff_idct_xvid_sse2_add; c->idct = ff_idct_xvid_sse2; c->idct_permutation_type= FF_SSE2_IDCT_PERM; }else if(mm_flags & FF_MM_MMX2){ c->idct_put= ff_idct_xvid_mmx2_put; c->idct_add= ff_idct_xvid_mmx2_add; c->idct = ff_idct_xvid_mmx2; }else{ c->idct_put= ff_idct_xvid_mmx_put; c->idct_add= ff_idct_xvid_mmx_add; c->idct = ff_idct_xvid_mmx; } } } c->put_pixels_clamped = put_pixels_clamped_mmx; c->put_signed_pixels_clamped = put_signed_pixels_clamped_mmx; c->add_pixels_clamped = add_pixels_clamped_mmx; c->clear_block = clear_block_mmx; c->clear_blocks = clear_blocks_mmx; if ((mm_flags & FF_MM_SSE) && !(CONFIG_MPEG_XVMC_DECODER && avctx->xvmc_acceleration > 1)){ /* XvMCCreateBlocks() may not allocate 16-byte aligned blocks */ c->clear_block = clear_block_sse; c->clear_blocks = clear_blocks_sse; } #define SET_HPEL_FUNCS(PFX, IDX, SIZE, CPU) \ c->PFX ## _pixels_tab[IDX][0] = PFX ## _pixels ## SIZE ## _ ## CPU; \ c->PFX ## _pixels_tab[IDX][1] = PFX ## _pixels ## SIZE ## _x2_ ## CPU; \ c->PFX ## _pixels_tab[IDX][2] = PFX ## _pixels ## SIZE ## _y2_ ## CPU; \ c->PFX ## _pixels_tab[IDX][3] = PFX ## _pixels ## SIZE ## _xy2_ ## CPU SET_HPEL_FUNCS(put, 0, 16, mmx); SET_HPEL_FUNCS(put_no_rnd, 0, 16, mmx); SET_HPEL_FUNCS(avg, 0, 16, mmx); SET_HPEL_FUNCS(avg_no_rnd, 0, 16, mmx); SET_HPEL_FUNCS(put, 1, 8, mmx); SET_HPEL_FUNCS(put_no_rnd, 1, 8, mmx); SET_HPEL_FUNCS(avg, 1, 8, mmx); SET_HPEL_FUNCS(avg_no_rnd, 1, 8, mmx); c->gmc= gmc_mmx; c->add_bytes= add_bytes_mmx; c->add_bytes_l2= add_bytes_l2_mmx; c->draw_edges = draw_edges_mmx; if (CONFIG_H263_DECODER || CONFIG_H263_ENCODER) { c->h263_v_loop_filter= h263_v_loop_filter_mmx; c->h263_h_loop_filter= h263_h_loop_filter_mmx; } c->put_h264_chroma_pixels_tab[0]= put_h264_chroma_mc8_mmx_rnd; c->put_h264_chroma_pixels_tab[1]= put_h264_chroma_mc4_mmx; c->put_no_rnd_vc1_chroma_pixels_tab[0]= put_vc1_chroma_mc8_mmx_nornd; c->put_rv40_chroma_pixels_tab[0]= put_rv40_chroma_mc8_mmx; c->put_rv40_chroma_pixels_tab[1]= put_rv40_chroma_mc4_mmx; if (CONFIG_VP6_DECODER) { c->vp6_filter_diag4 = ff_vp6_filter_diag4_mmx; } if (mm_flags & FF_MM_MMX2) { c->prefetch = prefetch_mmx2; c->put_pixels_tab[0][1] = put_pixels16_x2_mmx2; c->put_pixels_tab[0][2] = put_pixels16_y2_mmx2; c->avg_pixels_tab[0][0] = avg_pixels16_mmx2; c->avg_pixels_tab[0][1] = avg_pixels16_x2_mmx2; c->avg_pixels_tab[0][2] = avg_pixels16_y2_mmx2; c->put_pixels_tab[1][1] = put_pixels8_x2_mmx2; c->put_pixels_tab[1][2] = put_pixels8_y2_mmx2; c->avg_pixels_tab[1][0] = avg_pixels8_mmx2; c->avg_pixels_tab[1][1] = avg_pixels8_x2_mmx2; c->avg_pixels_tab[1][2] = avg_pixels8_y2_mmx2; if(!(avctx->flags & CODEC_FLAG_BITEXACT)){ c->put_no_rnd_pixels_tab[0][1] = put_no_rnd_pixels16_x2_mmx2; c->put_no_rnd_pixels_tab[0][2] = put_no_rnd_pixels16_y2_mmx2; c->put_no_rnd_pixels_tab[1][1] = put_no_rnd_pixels8_x2_mmx2; c->put_no_rnd_pixels_tab[1][2] = put_no_rnd_pixels8_y2_mmx2; c->avg_pixels_tab[0][3] = avg_pixels16_xy2_mmx2; c->avg_pixels_tab[1][3] = avg_pixels8_xy2_mmx2; if (CONFIG_VP3_DECODER) { c->vp3_v_loop_filter= ff_vp3_v_loop_filter_mmx2; c->vp3_h_loop_filter= ff_vp3_h_loop_filter_mmx2; } } if (CONFIG_VP3_DECODER) { c->vp3_idct_dc_add = ff_vp3_idct_dc_add_mmx2; } if (CONFIG_VP3_DECODER && (avctx->codec_id == CODEC_ID_VP3 || avctx->codec_id == CODEC_ID_THEORA)) { c->put_no_rnd_pixels_tab[1][1] = put_no_rnd_pixels8_x2_exact_mmx2; c->put_no_rnd_pixels_tab[1][2] = put_no_rnd_pixels8_y2_exact_mmx2; } #define SET_QPEL_FUNCS(PFX, IDX, SIZE, CPU) \ c->PFX ## _pixels_tab[IDX][ 0] = PFX ## SIZE ## _mc00_ ## CPU; \ c->PFX ## _pixels_tab[IDX][ 1] = PFX ## SIZE ## _mc10_ ## CPU; \ c->PFX ## _pixels_tab[IDX][ 2] = PFX ## SIZE ## _mc20_ ## CPU; \ c->PFX ## _pixels_tab[IDX][ 3] = PFX ## SIZE ## _mc30_ ## CPU; \ c->PFX ## _pixels_tab[IDX][ 4] = PFX ## SIZE ## _mc01_ ## CPU; \ c->PFX ## _pixels_tab[IDX][ 5] = PFX ## SIZE ## _mc11_ ## CPU; \ c->PFX ## _pixels_tab[IDX][ 6] = PFX ## SIZE ## _mc21_ ## CPU; \ c->PFX ## _pixels_tab[IDX][ 7] = PFX ## SIZE ## _mc31_ ## CPU; \ c->PFX ## _pixels_tab[IDX][ 8] = PFX ## SIZE ## _mc02_ ## CPU; \ c->PFX ## _pixels_tab[IDX][ 9] = PFX ## SIZE ## _mc12_ ## CPU; \ c->PFX ## _pixels_tab[IDX][10] = PFX ## SIZE ## _mc22_ ## CPU; \ c->PFX ## _pixels_tab[IDX][11] = PFX ## SIZE ## _mc32_ ## CPU; \ c->PFX ## _pixels_tab[IDX][12] = PFX ## SIZE ## _mc03_ ## CPU; \ c->PFX ## _pixels_tab[IDX][13] = PFX ## SIZE ## _mc13_ ## CPU; \ c->PFX ## _pixels_tab[IDX][14] = PFX ## SIZE ## _mc23_ ## CPU; \ c->PFX ## _pixels_tab[IDX][15] = PFX ## SIZE ## _mc33_ ## CPU SET_QPEL_FUNCS(put_qpel, 0, 16, mmx2); SET_QPEL_FUNCS(put_qpel, 1, 8, mmx2); SET_QPEL_FUNCS(put_no_rnd_qpel, 0, 16, mmx2); SET_QPEL_FUNCS(put_no_rnd_qpel, 1, 8, mmx2); SET_QPEL_FUNCS(avg_qpel, 0, 16, mmx2); SET_QPEL_FUNCS(avg_qpel, 1, 8, mmx2); SET_QPEL_FUNCS(put_h264_qpel, 0, 16, mmx2); SET_QPEL_FUNCS(put_h264_qpel, 1, 8, mmx2); SET_QPEL_FUNCS(put_h264_qpel, 2, 4, mmx2); SET_QPEL_FUNCS(avg_h264_qpel, 0, 16, mmx2); SET_QPEL_FUNCS(avg_h264_qpel, 1, 8, mmx2); SET_QPEL_FUNCS(avg_h264_qpel, 2, 4, mmx2); SET_QPEL_FUNCS(put_2tap_qpel, 0, 16, mmx2); SET_QPEL_FUNCS(put_2tap_qpel, 1, 8, mmx2); SET_QPEL_FUNCS(avg_2tap_qpel, 0, 16, mmx2); SET_QPEL_FUNCS(avg_2tap_qpel, 1, 8, mmx2); c->avg_rv40_chroma_pixels_tab[0]= avg_rv40_chroma_mc8_mmx2; c->avg_rv40_chroma_pixels_tab[1]= avg_rv40_chroma_mc4_mmx2; c->avg_no_rnd_vc1_chroma_pixels_tab[0]= avg_vc1_chroma_mc8_mmx2_nornd; c->avg_h264_chroma_pixels_tab[0]= avg_h264_chroma_mc8_mmx2_rnd; c->avg_h264_chroma_pixels_tab[1]= avg_h264_chroma_mc4_mmx2; c->avg_h264_chroma_pixels_tab[2]= avg_h264_chroma_mc2_mmx2; c->put_h264_chroma_pixels_tab[2]= put_h264_chroma_mc2_mmx2; #if HAVE_YASM c->add_hfyu_median_prediction = ff_add_hfyu_median_prediction_mmx2; #endif #if HAVE_7REGS && HAVE_TEN_OPERANDS if( mm_flags&FF_MM_3DNOW ) c->add_hfyu_median_prediction = add_hfyu_median_prediction_cmov; #endif if (CONFIG_CAVS_DECODER) ff_cavsdsp_init_mmx2(c, avctx); if (CONFIG_VC1_DECODER) ff_vc1dsp_init_mmx(c, avctx); c->add_png_paeth_prediction= add_png_paeth_prediction_mmx2; } else if (mm_flags & FF_MM_3DNOW) { c->prefetch = prefetch_3dnow; c->put_pixels_tab[0][1] = put_pixels16_x2_3dnow; c->put_pixels_tab[0][2] = put_pixels16_y2_3dnow; c->avg_pixels_tab[0][0] = avg_pixels16_3dnow; c->avg_pixels_tab[0][1] = avg_pixels16_x2_3dnow; c->avg_pixels_tab[0][2] = avg_pixels16_y2_3dnow; c->put_pixels_tab[1][1] = put_pixels8_x2_3dnow; c->put_pixels_tab[1][2] = put_pixels8_y2_3dnow; c->avg_pixels_tab[1][0] = avg_pixels8_3dnow; c->avg_pixels_tab[1][1] = avg_pixels8_x2_3dnow; c->avg_pixels_tab[1][2] = avg_pixels8_y2_3dnow; if(!(avctx->flags & CODEC_FLAG_BITEXACT)){ c->put_no_rnd_pixels_tab[0][1] = put_no_rnd_pixels16_x2_3dnow; c->put_no_rnd_pixels_tab[0][2] = put_no_rnd_pixels16_y2_3dnow; c->put_no_rnd_pixels_tab[1][1] = put_no_rnd_pixels8_x2_3dnow; c->put_no_rnd_pixels_tab[1][2] = put_no_rnd_pixels8_y2_3dnow; c->avg_pixels_tab[0][3] = avg_pixels16_xy2_3dnow; c->avg_pixels_tab[1][3] = avg_pixels8_xy2_3dnow; } if (CONFIG_VP3_DECODER && (avctx->codec_id == CODEC_ID_VP3 || avctx->codec_id == CODEC_ID_THEORA)) { c->put_no_rnd_pixels_tab[1][1] = put_no_rnd_pixels8_x2_exact_3dnow; c->put_no_rnd_pixels_tab[1][2] = put_no_rnd_pixels8_y2_exact_3dnow; } SET_QPEL_FUNCS(put_qpel, 0, 16, 3dnow); SET_QPEL_FUNCS(put_qpel, 1, 8, 3dnow); SET_QPEL_FUNCS(put_no_rnd_qpel, 0, 16, 3dnow); SET_QPEL_FUNCS(put_no_rnd_qpel, 1, 8, 3dnow); SET_QPEL_FUNCS(avg_qpel, 0, 16, 3dnow); SET_QPEL_FUNCS(avg_qpel, 1, 8, 3dnow); SET_QPEL_FUNCS(put_h264_qpel, 0, 16, 3dnow); SET_QPEL_FUNCS(put_h264_qpel, 1, 8, 3dnow); SET_QPEL_FUNCS(put_h264_qpel, 2, 4, 3dnow); SET_QPEL_FUNCS(avg_h264_qpel, 0, 16, 3dnow); SET_QPEL_FUNCS(avg_h264_qpel, 1, 8, 3dnow); SET_QPEL_FUNCS(avg_h264_qpel, 2, 4, 3dnow); SET_QPEL_FUNCS(put_2tap_qpel, 0, 16, 3dnow); SET_QPEL_FUNCS(put_2tap_qpel, 1, 8, 3dnow); SET_QPEL_FUNCS(avg_2tap_qpel, 0, 16, 3dnow); SET_QPEL_FUNCS(avg_2tap_qpel, 1, 8, 3dnow); c->avg_h264_chroma_pixels_tab[0]= avg_h264_chroma_mc8_3dnow_rnd; c->avg_h264_chroma_pixels_tab[1]= avg_h264_chroma_mc4_3dnow; c->avg_rv40_chroma_pixels_tab[0]= avg_rv40_chroma_mc8_3dnow; c->avg_rv40_chroma_pixels_tab[1]= avg_rv40_chroma_mc4_3dnow; if (CONFIG_CAVS_DECODER) ff_cavsdsp_init_3dnow(c, avctx); } #define H264_QPEL_FUNCS(x, y, CPU)\ c->put_h264_qpel_pixels_tab[0][x+y*4] = put_h264_qpel16_mc##x##y##_##CPU;\ c->put_h264_qpel_pixels_tab[1][x+y*4] = put_h264_qpel8_mc##x##y##_##CPU;\ c->avg_h264_qpel_pixels_tab[0][x+y*4] = avg_h264_qpel16_mc##x##y##_##CPU;\ c->avg_h264_qpel_pixels_tab[1][x+y*4] = avg_h264_qpel8_mc##x##y##_##CPU; if((mm_flags & FF_MM_SSE2) && !(mm_flags & FF_MM_3DNOW)){ // these functions are slower than mmx on AMD, but faster on Intel c->put_pixels_tab[0][0] = put_pixels16_sse2; c->avg_pixels_tab[0][0] = avg_pixels16_sse2; H264_QPEL_FUNCS(0, 0, sse2); } if(mm_flags & FF_MM_SSE2){ H264_QPEL_FUNCS(0, 1, sse2); H264_QPEL_FUNCS(0, 2, sse2); H264_QPEL_FUNCS(0, 3, sse2); H264_QPEL_FUNCS(1, 1, sse2); H264_QPEL_FUNCS(1, 2, sse2); H264_QPEL_FUNCS(1, 3, sse2); H264_QPEL_FUNCS(2, 1, sse2); H264_QPEL_FUNCS(2, 2, sse2); H264_QPEL_FUNCS(2, 3, sse2); H264_QPEL_FUNCS(3, 1, sse2); H264_QPEL_FUNCS(3, 2, sse2); H264_QPEL_FUNCS(3, 3, sse2); if (CONFIG_VP6_DECODER) { c->vp6_filter_diag4 = ff_vp6_filter_diag4_sse2; } } #if HAVE_SSSE3 if(mm_flags & FF_MM_SSSE3){ H264_QPEL_FUNCS(1, 0, ssse3); H264_QPEL_FUNCS(1, 1, ssse3); H264_QPEL_FUNCS(1, 2, ssse3); H264_QPEL_FUNCS(1, 3, ssse3); H264_QPEL_FUNCS(2, 0, ssse3); H264_QPEL_FUNCS(2, 1, ssse3); H264_QPEL_FUNCS(2, 2, ssse3); H264_QPEL_FUNCS(2, 3, ssse3); H264_QPEL_FUNCS(3, 0, ssse3); H264_QPEL_FUNCS(3, 1, ssse3); H264_QPEL_FUNCS(3, 2, ssse3); H264_QPEL_FUNCS(3, 3, ssse3); c->put_no_rnd_vc1_chroma_pixels_tab[0]= put_vc1_chroma_mc8_ssse3_nornd; c->avg_no_rnd_vc1_chroma_pixels_tab[0]= avg_vc1_chroma_mc8_ssse3_nornd; c->put_h264_chroma_pixels_tab[0]= put_h264_chroma_mc8_ssse3_rnd; c->avg_h264_chroma_pixels_tab[0]= avg_h264_chroma_mc8_ssse3_rnd; c->put_h264_chroma_pixels_tab[1]= put_h264_chroma_mc4_ssse3; c->avg_h264_chroma_pixels_tab[1]= avg_h264_chroma_mc4_ssse3; c->add_png_paeth_prediction= add_png_paeth_prediction_ssse3; #if HAVE_YASM c->add_hfyu_left_prediction = ff_add_hfyu_left_prediction_ssse3; if (mm_flags & FF_MM_SSE4) // not really sse4, just slow on Conroe c->add_hfyu_left_prediction = ff_add_hfyu_left_prediction_sse4; #endif } #endif if(mm_flags & FF_MM_3DNOW){ c->vorbis_inverse_coupling = vorbis_inverse_coupling_3dnow; c->vector_fmul = vector_fmul_3dnow; if(!(avctx->flags & CODEC_FLAG_BITEXACT)){ c->float_to_int16 = float_to_int16_3dnow; c->float_to_int16_interleave = float_to_int16_interleave_3dnow; } } if(mm_flags & FF_MM_3DNOWEXT){ c->vector_fmul_reverse = vector_fmul_reverse_3dnow2; c->vector_fmul_window = vector_fmul_window_3dnow2; if(!(avctx->flags & CODEC_FLAG_BITEXACT)){ c->float_to_int16_interleave = float_to_int16_interleave_3dn2; } } if(mm_flags & FF_MM_MMX2){ #if HAVE_YASM c->scalarproduct_int16 = ff_scalarproduct_int16_mmx2; c->scalarproduct_and_madd_int16 = ff_scalarproduct_and_madd_int16_mmx2; #endif } if(mm_flags & FF_MM_SSE){ c->vorbis_inverse_coupling = vorbis_inverse_coupling_sse; c->ac3_downmix = ac3_downmix_sse; c->vector_fmul = vector_fmul_sse; c->vector_fmul_reverse = vector_fmul_reverse_sse; c->vector_fmul_add = vector_fmul_add_sse; c->vector_fmul_window = vector_fmul_window_sse; c->int32_to_float_fmul_scalar = int32_to_float_fmul_scalar_sse; c->vector_clipf = vector_clipf_sse; c->float_to_int16 = float_to_int16_sse; c->float_to_int16_interleave = float_to_int16_interleave_sse; #if HAVE_YASM c->scalarproduct_float = ff_scalarproduct_float_sse; #endif } if(mm_flags & FF_MM_3DNOW) c->vector_fmul_add = vector_fmul_add_3dnow; // faster than sse if(mm_flags & FF_MM_SSE2){ c->int32_to_float_fmul_scalar = int32_to_float_fmul_scalar_sse2; c->float_to_int16 = float_to_int16_sse2; c->float_to_int16_interleave = float_to_int16_interleave_sse2; #if HAVE_YASM c->scalarproduct_int16 = ff_scalarproduct_int16_sse2; c->scalarproduct_and_madd_int16 = ff_scalarproduct_and_madd_int16_sse2; #endif } if((mm_flags & FF_MM_SSSE3) && !(mm_flags & (FF_MM_SSE42|FF_MM_3DNOW)) && HAVE_YASM) // cachesplit c->scalarproduct_and_madd_int16 = ff_scalarproduct_and_madd_int16_ssse3; } if (CONFIG_ENCODERS) dsputilenc_init_mmx(c, avctx); #if 0 // for speed testing get_pixels = just_return; put_pixels_clamped = just_return; add_pixels_clamped = just_return; pix_abs16x16 = just_return; pix_abs16x16_x2 = just_return; pix_abs16x16_y2 = just_return; pix_abs16x16_xy2 = just_return; put_pixels_tab[0] = just_return; put_pixels_tab[1] = just_return; put_pixels_tab[2] = just_return; put_pixels_tab[3] = just_return; put_no_rnd_pixels_tab[0] = just_return; put_no_rnd_pixels_tab[1] = just_return; put_no_rnd_pixels_tab[2] = just_return; put_no_rnd_pixels_tab[3] = just_return; avg_pixels_tab[0] = just_return; avg_pixels_tab[1] = just_return; avg_pixels_tab[2] = just_return; avg_pixels_tab[3] = just_return; avg_no_rnd_pixels_tab[0] = just_return; avg_no_rnd_pixels_tab[1] = just_return; avg_no_rnd_pixels_tab[2] = just_return; avg_no_rnd_pixels_tab[3] = just_return; //av_fdct = just_return; //ff_idct = just_return; #endif } #if CONFIG_H264DSP void ff_h264dsp_init_x86(H264DSPContext *c) { mm_flags = mm_support(); if (mm_flags & FF_MM_MMX) { c->h264_idct_dc_add= c->h264_idct_add= ff_h264_idct_add_mmx; c->h264_idct8_dc_add= c->h264_idct8_add= ff_h264_idct8_add_mmx; c->h264_idct_add16 = ff_h264_idct_add16_mmx; c->h264_idct8_add4 = ff_h264_idct8_add4_mmx; c->h264_idct_add8 = ff_h264_idct_add8_mmx; c->h264_idct_add16intra= ff_h264_idct_add16intra_mmx; if (mm_flags & FF_MM_MMX2) { c->h264_idct_dc_add= ff_h264_idct_dc_add_mmx2; c->h264_idct8_dc_add= ff_h264_idct8_dc_add_mmx2; c->h264_idct_add16 = ff_h264_idct_add16_mmx2; c->h264_idct8_add4 = ff_h264_idct8_add4_mmx2; c->h264_idct_add8 = ff_h264_idct_add8_mmx2; c->h264_idct_add16intra= ff_h264_idct_add16intra_mmx2; c->h264_v_loop_filter_luma= h264_v_loop_filter_luma_mmx2; c->h264_h_loop_filter_luma= h264_h_loop_filter_luma_mmx2; c->h264_v_loop_filter_chroma= h264_v_loop_filter_chroma_mmx2; c->h264_h_loop_filter_chroma= h264_h_loop_filter_chroma_mmx2; c->h264_v_loop_filter_chroma_intra= h264_v_loop_filter_chroma_intra_mmx2; c->h264_h_loop_filter_chroma_intra= h264_h_loop_filter_chroma_intra_mmx2; c->h264_loop_filter_strength= h264_loop_filter_strength_mmx2; c->weight_h264_pixels_tab[0]= ff_h264_weight_16x16_mmx2; c->weight_h264_pixels_tab[1]= ff_h264_weight_16x8_mmx2; c->weight_h264_pixels_tab[2]= ff_h264_weight_8x16_mmx2; c->weight_h264_pixels_tab[3]= ff_h264_weight_8x8_mmx2; c->weight_h264_pixels_tab[4]= ff_h264_weight_8x4_mmx2; c->weight_h264_pixels_tab[5]= ff_h264_weight_4x8_mmx2; c->weight_h264_pixels_tab[6]= ff_h264_weight_4x4_mmx2; c->weight_h264_pixels_tab[7]= ff_h264_weight_4x2_mmx2; c->biweight_h264_pixels_tab[0]= ff_h264_biweight_16x16_mmx2; c->biweight_h264_pixels_tab[1]= ff_h264_biweight_16x8_mmx2; c->biweight_h264_pixels_tab[2]= ff_h264_biweight_8x16_mmx2; c->biweight_h264_pixels_tab[3]= ff_h264_biweight_8x8_mmx2; c->biweight_h264_pixels_tab[4]= ff_h264_biweight_8x4_mmx2; c->biweight_h264_pixels_tab[5]= ff_h264_biweight_4x8_mmx2; c->biweight_h264_pixels_tab[6]= ff_h264_biweight_4x4_mmx2; c->biweight_h264_pixels_tab[7]= ff_h264_biweight_4x2_mmx2; } if(mm_flags & FF_MM_SSE2){ c->h264_idct8_add = ff_h264_idct8_add_sse2; c->h264_idct8_add4= ff_h264_idct8_add4_sse2; } #if CONFIG_GPL && HAVE_YASM if (mm_flags & FF_MM_MMX2){ #if ARCH_X86_32 c->h264_v_loop_filter_luma_intra = ff_x264_deblock_v_luma_intra_mmxext; c->h264_h_loop_filter_luma_intra = ff_x264_deblock_h_luma_intra_mmxext; #endif if( mm_flags&FF_MM_SSE2 ){ #if ARCH_X86_64 || !defined(__ICC) || __ICC > 1110 c->h264_v_loop_filter_luma = ff_x264_deblock_v_luma_sse2; c->h264_h_loop_filter_luma = ff_x264_deblock_h_luma_sse2; c->h264_v_loop_filter_luma_intra = ff_x264_deblock_v_luma_intra_sse2; c->h264_h_loop_filter_luma_intra = ff_x264_deblock_h_luma_intra_sse2; #endif c->h264_idct_add16 = ff_h264_idct_add16_sse2; c->h264_idct_add8 = ff_h264_idct_add8_sse2; c->h264_idct_add16intra = ff_h264_idct_add16intra_sse2; } } #endif } } #endif /* CONFIG_H264DSP */
longluo/FFMpeg
jni/libffmpeg/libavcodec/x86/dsputil_mmx.c
C
apache-2.0
126,287
#!/bin/bash # Copyright 2015 Google, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License.set -x -e # Only run on the master node ROLE=$(/usr/share/google/get_metadata_value attributes/dataproc-role) if [[ "${ROLE}" == 'Master' ]]; then # Install dependencies needed for iPython Notebook apt-get install build-essential python-dev libpng-dev libfreetype6-dev libxft-dev pkg-config python-matplotlib python-requests python-numpy -y curl https://bootstrap.pypa.io/get-pip.py | python # Install iPython Notebook and create a profile mkdir IPythonNB cd IPythonNB pip install "ipython[notebook]" ipython profile create default # Set up configuration for iPython Notebook echo "c = get_config()" > /root/.ipython/profile_default/ipython_notebook_config.py echo "c.NotebookApp.ip = '*'" >> /root/.ipython/profile_default/ipython_notebook_config.py echo "c.NotebookApp.open_browser = False" >> /root/.ipython/profile_default/ipython_notebook_config.py echo "c.NotebookApp.port = 8123" >> /root/.ipython/profile_default/ipython_notebook_config.py # Setup script for iPython Notebook so it uses the cluster's Spark cat > /root/.ipython/profile_default/startup/00-pyspark-setup.py <<'_EOF' import os import sys spark_home = '/usr/lib/spark/' os.environ["SPARK_HOME"] = spark_home sys.path.insert(0, os.path.join(spark_home, 'python')) sys.path.insert(0, os.path.join(spark_home, 'python/lib/py4j-0.8.2.1-src.zip')) execfile(os.path.join(spark_home, 'python/pyspark/shell.py')) _EOF # Start iPython Notebook on port 8123 nohup ipython notebook --no-browser --ip=* --port=8123 > /var/log/python_notebook.log & fi
giuseppereina/dataproc-initialization-actions
ipython-notebook/ipython.sh
Shell
apache-2.0
2,164
// Code generated by protoc-gen-go. DO NOT EDIT. // versions: // protoc-gen-go v1.26.0 // protoc v3.17.3 // source: github.com/google/cloudprober/surfacers/postgres/proto/config.proto package proto import ( protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" reflect "reflect" sync "sync" ) const ( // Verify that this generated code is sufficiently up-to-date. _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) // Verify that runtime/protoimpl is sufficiently up-to-date. _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) type SurfacerConf struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields ConnectionString *string `protobuf:"bytes,1,req,name=connection_string,json=connectionString" json:"connection_string,omitempty"` MetricsTableName *string `protobuf:"bytes,2,req,name=metrics_table_name,json=metricsTableName" json:"metrics_table_name,omitempty"` MetricsBufferSize *int64 `protobuf:"varint,3,opt,name=metrics_buffer_size,json=metricsBufferSize,def=10000" json:"metrics_buffer_size,omitempty"` } // Default values for SurfacerConf fields. const ( Default_SurfacerConf_MetricsBufferSize = int64(10000) ) func (x *SurfacerConf) Reset() { *x = SurfacerConf{} if protoimpl.UnsafeEnabled { mi := &file_github_com_google_cloudprober_surfacers_postgres_proto_config_proto_msgTypes[0] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *SurfacerConf) String() string { return protoimpl.X.MessageStringOf(x) } func (*SurfacerConf) ProtoMessage() {} func (x *SurfacerConf) ProtoReflect() protoreflect.Message { mi := &file_github_com_google_cloudprober_surfacers_postgres_proto_config_proto_msgTypes[0] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use SurfacerConf.ProtoReflect.Descriptor instead. func (*SurfacerConf) Descriptor() ([]byte, []int) { return file_github_com_google_cloudprober_surfacers_postgres_proto_config_proto_rawDescGZIP(), []int{0} } func (x *SurfacerConf) GetConnectionString() string { if x != nil && x.ConnectionString != nil { return *x.ConnectionString } return "" } func (x *SurfacerConf) GetMetricsTableName() string { if x != nil && x.MetricsTableName != nil { return *x.MetricsTableName } return "" } func (x *SurfacerConf) GetMetricsBufferSize() int64 { if x != nil && x.MetricsBufferSize != nil { return *x.MetricsBufferSize } return Default_SurfacerConf_MetricsBufferSize } var File_github_com_google_cloudprober_surfacers_postgres_proto_config_proto protoreflect.FileDescriptor var file_github_com_google_cloudprober_surfacers_postgres_proto_config_proto_rawDesc = []byte{ 0x0a, 0x43, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x70, 0x72, 0x6f, 0x62, 0x65, 0x72, 0x2f, 0x73, 0x75, 0x72, 0x66, 0x61, 0x63, 0x65, 0x72, 0x73, 0x2f, 0x70, 0x6f, 0x73, 0x74, 0x67, 0x72, 0x65, 0x73, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2f, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x1d, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x70, 0x72, 0x6f, 0x62, 0x65, 0x72, 0x2e, 0x73, 0x75, 0x72, 0x66, 0x61, 0x63, 0x65, 0x72, 0x2e, 0x70, 0x6f, 0x73, 0x74, 0x67, 0x72, 0x65, 0x73, 0x22, 0xa0, 0x01, 0x0a, 0x0c, 0x53, 0x75, 0x72, 0x66, 0x61, 0x63, 0x65, 0x72, 0x43, 0x6f, 0x6e, 0x66, 0x12, 0x2b, 0x0a, 0x11, 0x63, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x5f, 0x73, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x18, 0x01, 0x20, 0x02, 0x28, 0x09, 0x52, 0x10, 0x63, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x53, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x12, 0x2c, 0x0a, 0x12, 0x6d, 0x65, 0x74, 0x72, 0x69, 0x63, 0x73, 0x5f, 0x74, 0x61, 0x62, 0x6c, 0x65, 0x5f, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x02, 0x20, 0x02, 0x28, 0x09, 0x52, 0x10, 0x6d, 0x65, 0x74, 0x72, 0x69, 0x63, 0x73, 0x54, 0x61, 0x62, 0x6c, 0x65, 0x4e, 0x61, 0x6d, 0x65, 0x12, 0x35, 0x0a, 0x13, 0x6d, 0x65, 0x74, 0x72, 0x69, 0x63, 0x73, 0x5f, 0x62, 0x75, 0x66, 0x66, 0x65, 0x72, 0x5f, 0x73, 0x69, 0x7a, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x03, 0x3a, 0x05, 0x31, 0x30, 0x30, 0x30, 0x30, 0x52, 0x11, 0x6d, 0x65, 0x74, 0x72, 0x69, 0x63, 0x73, 0x42, 0x75, 0x66, 0x66, 0x65, 0x72, 0x53, 0x69, 0x7a, 0x65, 0x42, 0x38, 0x5a, 0x36, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x63, 0x6c, 0x6f, 0x75, 0x64, 0x70, 0x72, 0x6f, 0x62, 0x65, 0x72, 0x2f, 0x73, 0x75, 0x72, 0x66, 0x61, 0x63, 0x65, 0x72, 0x73, 0x2f, 0x70, 0x6f, 0x73, 0x74, 0x67, 0x72, 0x65, 0x73, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, } var ( file_github_com_google_cloudprober_surfacers_postgres_proto_config_proto_rawDescOnce sync.Once file_github_com_google_cloudprober_surfacers_postgres_proto_config_proto_rawDescData = file_github_com_google_cloudprober_surfacers_postgres_proto_config_proto_rawDesc ) func file_github_com_google_cloudprober_surfacers_postgres_proto_config_proto_rawDescGZIP() []byte { file_github_com_google_cloudprober_surfacers_postgres_proto_config_proto_rawDescOnce.Do(func() { file_github_com_google_cloudprober_surfacers_postgres_proto_config_proto_rawDescData = protoimpl.X.CompressGZIP(file_github_com_google_cloudprober_surfacers_postgres_proto_config_proto_rawDescData) }) return file_github_com_google_cloudprober_surfacers_postgres_proto_config_proto_rawDescData } var file_github_com_google_cloudprober_surfacers_postgres_proto_config_proto_msgTypes = make([]protoimpl.MessageInfo, 1) var file_github_com_google_cloudprober_surfacers_postgres_proto_config_proto_goTypes = []interface{}{ (*SurfacerConf)(nil), // 0: cloudprober.surfacer.postgres.SurfacerConf } var file_github_com_google_cloudprober_surfacers_postgres_proto_config_proto_depIdxs = []int32{ 0, // [0:0] is the sub-list for method output_type 0, // [0:0] is the sub-list for method input_type 0, // [0:0] is the sub-list for extension type_name 0, // [0:0] is the sub-list for extension extendee 0, // [0:0] is the sub-list for field type_name } func init() { file_github_com_google_cloudprober_surfacers_postgres_proto_config_proto_init() } func file_github_com_google_cloudprober_surfacers_postgres_proto_config_proto_init() { if File_github_com_google_cloudprober_surfacers_postgres_proto_config_proto != nil { return } if !protoimpl.UnsafeEnabled { file_github_com_google_cloudprober_surfacers_postgres_proto_config_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*SurfacerConf); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } } type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: file_github_com_google_cloudprober_surfacers_postgres_proto_config_proto_rawDesc, NumEnums: 0, NumMessages: 1, NumExtensions: 0, NumServices: 0, }, GoTypes: file_github_com_google_cloudprober_surfacers_postgres_proto_config_proto_goTypes, DependencyIndexes: file_github_com_google_cloudprober_surfacers_postgres_proto_config_proto_depIdxs, MessageInfos: file_github_com_google_cloudprober_surfacers_postgres_proto_config_proto_msgTypes, }.Build() File_github_com_google_cloudprober_surfacers_postgres_proto_config_proto = out.File file_github_com_google_cloudprober_surfacers_postgres_proto_config_proto_rawDesc = nil file_github_com_google_cloudprober_surfacers_postgres_proto_config_proto_goTypes = nil file_github_com_google_cloudprober_surfacers_postgres_proto_config_proto_depIdxs = nil }
google/cloudprober
surfacers/postgres/proto/config.pb.go
GO
apache-2.0
7,937
/* * Copyright 2014-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.elasticmapreduce.model.transform; import javax.annotation.Generated; import com.amazonaws.SdkClientException; import com.amazonaws.services.elasticmapreduce.model.*; import com.amazonaws.protocol.*; import com.amazonaws.annotation.SdkInternalApi; /** * ListBootstrapActionsRequestMarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") @SdkInternalApi public class ListBootstrapActionsRequestMarshaller { private static final MarshallingInfo<String> CLUSTERID_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("ClusterId").build(); private static final MarshallingInfo<String> MARKER_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("Marker").build(); private static final ListBootstrapActionsRequestMarshaller instance = new ListBootstrapActionsRequestMarshaller(); public static ListBootstrapActionsRequestMarshaller getInstance() { return instance; } /** * Marshall the given parameter object. */ public void marshall(ListBootstrapActionsRequest listBootstrapActionsRequest, ProtocolMarshaller protocolMarshaller) { if (listBootstrapActionsRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(listBootstrapActionsRequest.getClusterId(), CLUSTERID_BINDING); protocolMarshaller.marshall(listBootstrapActionsRequest.getMarker(), MARKER_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
jentfoo/aws-sdk-java
aws-java-sdk-emr/src/main/java/com/amazonaws/services/elasticmapreduce/model/transform/ListBootstrapActionsRequestMarshaller.java
Java
apache-2.0
2,390
/** * Server-side support classes for WebSocket requests. */ @NonNullApi @NonNullFields package org.springframework.web.reactive.socket.server.support; import org.springframework.lang.NonNullApi; import org.springframework.lang.NonNullFields;
spring-projects/spring-framework
spring-webflux/src/main/java/org/springframework/web/reactive/socket/server/support/package-info.java
Java
apache-2.0
246
/** * */ package org.commcare.cases.ledger; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.util.Enumeration; import java.util.Hashtable; import java.util.Vector; import org.javarosa.core.services.storage.IMetaData; import org.javarosa.core.services.storage.Persistable; import org.javarosa.core.util.externalizable.DeserializationException; import org.javarosa.core.util.externalizable.ExtUtil; import org.javarosa.core.util.externalizable.ExtWrapMap; import org.javarosa.core.util.externalizable.PrototypeFactory; /** * A Ledger is a data model which tracks numeric data organized into * different sections with different meanings. * * @author ctsims * */ public class Ledger implements Persistable, IMetaData { //NOTE: Right now this is (lazily) implemented assuming that each ledger //object tracks _all_ of the sections for an entity, which will likely be a terrible way //to do things long-term. public static final String STORAGE_KEY = "ledger"; public static final String INDEX_ENTITY_ID = "entity-id"; String entityId; int recordId = -1; Hashtable<String, Hashtable<String, Integer>> sections; public Ledger() { } public Ledger(String entityId) { this.entityId = entityId; this.sections = new Hashtable<String, Hashtable<String, Integer>>(); } /** * Get the ID of the linked entity associated with this Ledger record * @return */ public String getEntiyId() { return entityId; } /** * Retrieve an entry from a specific section of the ledger. * * If no entry is defined, the ledger will return the value '0' * * @param sectionId The section containing the entry * @param entryId The Id of the entry to retrieve * @return the entry value. '0' if no entry exists. */ public int getEntry(String sectionId, String entryId) { if(!sections.containsKey(sectionId) || !sections.get(sectionId).containsKey(entryId)) { return 0; } return sections.get(sectionId).get(entryId).intValue(); } /** * @return The list of sections available in this ledger */ public String[] getSectionList() { String[] sectionList = new String[sections.size()]; int i = 0; for(Enumeration e = sections.keys(); e.hasMoreElements();) { sectionList[i] = (String)e.nextElement(); ++i; } return sectionList; } /** * Retrieves a list of all entries (by ID) defined in a * section of the ledger * * @param sectionId The ID of a section * @return The IDs of all entries defined in the provided section */ public String[] getListOfEntries(String sectionId) { Hashtable<String, Integer> entries = sections.get(sectionId); String[] entryList = new String[entries.size()]; int i = 0; for(Enumeration e = entries.keys(); e.hasMoreElements();) { entryList[i] = (String)e.nextElement(); ++i; } return entryList; } /* * (non-Javadoc) * @see org.javarosa.core.util.externalizable.Externalizable#readExternal(java.io.DataInputStream, org.javarosa.core.util.externalizable.PrototypeFactory) */ public void readExternal(DataInputStream in, PrototypeFactory pf) throws IOException, DeserializationException { recordId = ExtUtil.readInt(in); entityId = ExtUtil.readString(in); sections = (Hashtable<String, Hashtable<String, Integer>>) ExtUtil.read(in, new ExtWrapMap(String.class, new ExtWrapMap(String.class, Integer.class))); } /* * (non-Javadoc) * @see org.javarosa.core.util.externalizable.Externalizable#writeExternal(java.io.DataOutputStream) */ public void writeExternal(DataOutputStream out) throws IOException { ExtUtil.writeNumeric(out, recordId); ExtUtil.writeString(out, entityId); ExtUtil.write(out, new ExtWrapMap(sections, new ExtWrapMap(String.class, Integer.class))); } /* * (non-Javadoc) * @see org.javarosa.core.services.storage.Persistable#setID(int) */ public void setID(int ID) { recordId = ID; } /* * (non-Javadoc) * @see org.javarosa.core.services.storage.Persistable#getID() */ public int getID() { return recordId; } /** * Sets the value of an entry in the specified section of this ledger * * @param sectionId * @param entryId * @param quantity */ public void setEntry(String sectionId, String entryId, int quantity) { if(!sections.containsKey(sectionId)) { sections.put(sectionId, new Hashtable<String, Integer>()); } sections.get(sectionId).put(entryId, new Integer(quantity)); } /* * (non-Javadoc) * @see org.javarosa.core.services.storage.IMetaData#getMetaDataFields() */ public String[] getMetaDataFields() { return new String[] {INDEX_ENTITY_ID}; } /* * (non-Javadoc) * @see org.javarosa.core.services.storage.IMetaData#getMetaData(java.lang.String) */ public Object getMetaData(String fieldName) { if(fieldName.equals(INDEX_ENTITY_ID)){ return entityId; } else { throw new IllegalArgumentException("No metadata field " + fieldName + " in the ledger storage system"); } } }
wpride/commcare
cases/src/org/commcare/cases/ledger/Ledger.java
Java
apache-2.0
4,988