code
stringlengths
4
1.01M
language
stringclasses
2 values
# coding=utf-8 # Copyright 2016 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for StatementVisitor.""" from __future__ import unicode_literals import re import subprocess import textwrap import unittest from grumpy_tools.compiler import block from grumpy_tools.compiler import imputil from grumpy_tools.compiler import shard_test from grumpy_tools.compiler import stmt from grumpy_tools.compiler import util from grumpy_tools.vendor import pythonparser from grumpy_tools.vendor.pythonparser import ast class StatementVisitorTest(unittest.TestCase): def testAssertNoMsg(self): self.assertEqual((0, 'AssertionError()\n'), _GrumpRun(textwrap.dedent("""\ try: assert False except AssertionError as e: print repr(e)"""))) def testAssertMsg(self): want = (0, "AssertionError('foo',)\n") self.assertEqual(want, _GrumpRun(textwrap.dedent("""\ try: assert False, 'foo' except AssertionError as e: print repr(e)"""))) def testBareAssert(self): # Assertion errors at the top level of a block should raise: # https://github.com/google/grumpy/issues/18 want = (0, 'ok\n') self.assertEqual(want, _GrumpRun(textwrap.dedent("""\ def foo(): assert False try: foo() except AssertionError: print 'ok' else: print 'bad'"""))) def testAssignAttribute(self): self.assertEqual((0, '123\n'), _GrumpRun(textwrap.dedent("""\ e = Exception() e.foo = 123 print e.foo"""))) def testAssignName(self): self.assertEqual((0, 'bar\n'), _GrumpRun(textwrap.dedent("""\ foo = 'bar' print foo"""))) def testAssignMultiple(self): self.assertEqual((0, 'baz baz\n'), _GrumpRun(textwrap.dedent("""\ foo = bar = 'baz' print foo, bar"""))) def testAssignSubscript(self): self.assertEqual((0, "{'bar': None}\n"), _GrumpRun(textwrap.dedent("""\ foo = {} foo['bar'] = None print foo"""))) def testAssignTuple(self): self.assertEqual((0, 'a b\n'), _GrumpRun(textwrap.dedent("""\ baz = ('a', 'b') foo, bar = baz print foo, bar"""))) def testAugAssign(self): self.assertEqual((0, '42\n'), _GrumpRun(textwrap.dedent("""\ foo = 41 foo += 1 print foo"""))) def testAugAssignBitAnd(self): self.assertEqual((0, '3\n'), _GrumpRun(textwrap.dedent("""\ foo = 7 foo &= 3 print foo"""))) def testAugAssignPow(self): self.assertEqual((0, '64\n'), _GrumpRun(textwrap.dedent("""\ foo = 8 foo **= 2 print foo"""))) def testClassDef(self): self.assertEqual((0, "<type 'type'>\n"), _GrumpRun(textwrap.dedent("""\ class Foo(object): pass print type(Foo)"""))) def testClassDefWithVar(self): self.assertEqual((0, 'abc\n'), _GrumpRun(textwrap.dedent("""\ class Foo(object): bar = 'abc' print Foo.bar"""))) def testDeleteAttribute(self): self.assertEqual((0, 'False\n'), _GrumpRun(textwrap.dedent("""\ class Foo(object): bar = 42 del Foo.bar print hasattr(Foo, 'bar')"""))) def testDeleteClassLocal(self): self.assertEqual((0, 'False\n'), _GrumpRun(textwrap.dedent("""\ class Foo(object): bar = 'baz' del bar print hasattr(Foo, 'bar')"""))) def testDeleteGlobal(self): self.assertEqual((0, 'False\n'), _GrumpRun(textwrap.dedent("""\ foo = 42 del foo print 'foo' in globals()"""))) def testDeleteLocal(self): self.assertEqual((0, 'ok\n'), _GrumpRun(textwrap.dedent("""\ def foo(): bar = 123 del bar try: print bar raise AssertionError except UnboundLocalError: print 'ok' foo()"""))) def testDeleteNonexistentLocal(self): self.assertRaisesRegexp( util.ParseError, 'cannot delete nonexistent local', _ParseAndVisit, 'def foo():\n del bar') def testDeleteSubscript(self): self.assertEqual((0, '{}\n'), _GrumpRun(textwrap.dedent("""\ foo = {'bar': 'baz'} del foo['bar'] print foo"""))) def testExprCall(self): self.assertEqual((0, 'bar\n'), _GrumpRun(textwrap.dedent("""\ def foo(): print 'bar' foo()"""))) def testExprNameGlobal(self): self.assertEqual((0, ''), _GrumpRun(textwrap.dedent("""\ foo = 42 foo"""))) def testExprNameLocal(self): self.assertEqual((0, ''), _GrumpRun(textwrap.dedent("""\ foo = 42 def bar(): foo bar()"""))) def testFor(self): self.assertEqual((0, '1\n2\n3\n'), _GrumpRun(textwrap.dedent("""\ for i in (1, 2, 3): print i"""))) def testForBreak(self): self.assertEqual((0, '1\n'), _GrumpRun(textwrap.dedent("""\ for i in (1, 2, 3): print i break"""))) def testForContinue(self): self.assertEqual((0, '1\n2\n3\n'), _GrumpRun(textwrap.dedent("""\ for i in (1, 2, 3): print i continue raise AssertionError"""))) def testForElse(self): self.assertEqual((0, 'foo\nbar\n'), _GrumpRun(textwrap.dedent("""\ for i in (1,): print 'foo' else: print 'bar'"""))) def testForElseBreakNotNested(self): self.assertRaisesRegexp( util.ParseError, "'continue' not in loop", _ParseAndVisit, 'for i in (1,):\n pass\nelse:\n continue') def testForElseContinueNotNested(self): self.assertRaisesRegexp( util.ParseError, "'continue' not in loop", _ParseAndVisit, 'for i in (1,):\n pass\nelse:\n continue') def testFunctionDecorator(self): self.assertEqual((0, '<b>foo</b>\n'), _GrumpRun(textwrap.dedent("""\ def bold(fn): return lambda: '<b>' + fn() + '</b>' @bold def foo(): return 'foo' print foo()"""))) def testFunctionDecoratorWithArg(self): self.assertEqual((0, '<b id=red>foo</b>\n'), _GrumpRun(textwrap.dedent("""\ def tag(name): def bold(fn): return lambda: '<b id=' + name + '>' + fn() + '</b>' return bold @tag('red') def foo(): return 'foo' print foo()"""))) def testFunctionDef(self): self.assertEqual((0, 'bar baz\n'), _GrumpRun(textwrap.dedent("""\ def foo(a, b): print a, b foo('bar', 'baz')"""))) def testFunctionDefGenerator(self): self.assertEqual((0, "['foo', 'bar']\n"), _GrumpRun(textwrap.dedent("""\ def gen(): yield 'foo' yield 'bar' print list(gen())"""))) def testFunctionDefGeneratorReturnValue(self): self.assertRaisesRegexp( util.ParseError, 'returning a value in a generator function', _ParseAndVisit, 'def foo():\n yield 1\n return 2') def testFunctionDefLocal(self): self.assertEqual((0, 'baz\n'), _GrumpRun(textwrap.dedent("""\ def foo(): def bar(): print 'baz' bar() foo()"""))) def testIf(self): self.assertEqual((0, 'foo\n'), _GrumpRun(textwrap.dedent("""\ if 123: print 'foo' if '': print 'bar'"""))) def testIfElif(self): self.assertEqual((0, 'foo\nbar\n'), _GrumpRun(textwrap.dedent("""\ if True: print 'foo' elif False: print 'bar' if False: print 'foo' elif True: print 'bar'"""))) def testIfElse(self): self.assertEqual((0, 'foo\nbar\n'), _GrumpRun(textwrap.dedent("""\ if True: print 'foo' else: print 'bar' if False: print 'foo' else: print 'bar'"""))) def testImport(self): self.assertEqual((0, "<type 'dict'>\n"), _GrumpRun(textwrap.dedent("""\ import sys print type(sys.modules)"""))) def testImportFutureLateRaises(self): regexp = 'from __future__ imports must occur at the beginning of the file' self.assertRaisesRegexp(util.ImportError, regexp, _ParseAndVisit, 'foo = bar\nfrom __future__ import print_function') def testFutureUnicodeLiterals(self): want = "u'foo'\n" self.assertEqual((0, want), _GrumpRun(textwrap.dedent("""\ from __future__ import unicode_literals print repr('foo')"""))) def testImportMember(self): self.assertEqual((0, "<type 'dict'>\n"), _GrumpRun(textwrap.dedent("""\ from sys import modules print type(modules)"""))) def testImportConflictingPackage(self): self.assertEqual((0, ''), _GrumpRun(textwrap.dedent("""\ import time from "__go__/time" import Now"""))) def testImportNative(self): self.assertEqual((0, '1 1000000000\n'), _GrumpRun(textwrap.dedent("""\ from "__go__/time" import Nanosecond, Second print Nanosecond, Second"""))) def testImportGrumpy(self): self.assertEqual((0, ''), _GrumpRun(textwrap.dedent("""\ from "__go__/grumpy" import Assert Assert(__frame__(), True, 'bad')"""))) def testImportNativeType(self): self.assertEqual((0, "<type 'Duration'>\n"), _GrumpRun(textwrap.dedent("""\ from "__go__/time" import Duration print Duration"""))) def testImportWildcardMemberRaises(self): regexp = 'wildcard member import is not implemented' self.assertRaisesRegexp(util.ImportError, regexp, _ParseAndVisit, 'from foo import *') self.assertRaisesRegexp(util.ImportError, regexp, _ParseAndVisit, 'from "__go__/foo" import *') def testPrintStatement(self): self.assertEqual((0, 'abc 123\nfoo bar\n'), _GrumpRun(textwrap.dedent("""\ print 'abc', print '123' print 'foo', 'bar'"""))) def testPrintFunction(self): want = "abc\n123\nabc 123\nabcx123\nabc 123 " self.assertEqual((0, want), _GrumpRun(textwrap.dedent("""\ "module docstring is ok to proceed __future__" from __future__ import print_function print('abc') print(123) print('abc', 123) print('abc', 123, sep='x') print('abc', 123, end=' ')"""))) def testRaiseExitStatus(self): self.assertEqual(1, _GrumpRun('raise Exception')[0]) def testRaiseInstance(self): self.assertEqual((0, 'foo\n'), _GrumpRun(textwrap.dedent("""\ try: raise RuntimeError('foo') print 'bad' except RuntimeError as e: print e"""))) def testRaiseTypeAndArg(self): self.assertEqual((0, 'foo\n'), _GrumpRun(textwrap.dedent("""\ try: raise KeyError('foo') print 'bad' except KeyError as e: print e"""))) def testRaiseAgain(self): self.assertEqual((0, 'foo\n'), _GrumpRun(textwrap.dedent("""\ try: try: raise AssertionError('foo') except AssertionError: raise except Exception as e: print e"""))) def testRaiseTraceback(self): self.assertEqual((0, ''), _GrumpRun(textwrap.dedent("""\ import sys try: try: raise Exception except: e, _, tb = sys.exc_info() raise e, None, tb except: e2, _, tb2 = sys.exc_info() assert e is e2 assert tb is tb2"""))) def testReturn(self): self.assertEqual((0, 'bar\n'), _GrumpRun(textwrap.dedent("""\ def foo(): return 'bar' print foo()"""))) def testTryBareExcept(self): self.assertEqual((0, ''), _GrumpRun(textwrap.dedent("""\ try: raise AssertionError except: pass"""))) def testTryElse(self): self.assertEqual((0, 'foo baz\n'), _GrumpRun(textwrap.dedent("""\ try: print 'foo', except: print 'bar' else: print 'baz'"""))) def testTryMultipleExcept(self): self.assertEqual((0, 'bar\n'), _GrumpRun(textwrap.dedent("""\ try: raise AssertionError except RuntimeError: print 'foo' except AssertionError: print 'bar' except: print 'baz'"""))) def testTryFinally(self): result = _GrumpRun(textwrap.dedent("""\ try: print 'foo', finally: print 'bar' try: print 'foo', raise Exception finally: print 'bar'""")) self.assertEqual(1, result[0]) self.assertIn('foo bar\nfoo bar\n', result[1]) self.assertIn('Exception\n', result[1]) def testWhile(self): self.assertEqual((0, '2\n1\n'), _GrumpRun(textwrap.dedent("""\ i = 2 while i: print i i -= 1"""))) def testWhileElse(self): self.assertEqual((0, 'bar\n'), _GrumpRun(textwrap.dedent("""\ while False: print 'foo' else: print 'bar'"""))) def testWith(self): self.assertEqual((0, 'enter\n1\nexit\nenter\n2\nexit\n3\n'), _GrumpRun(textwrap.dedent("""\ class ContextManager(object): def __enter__(self): print "enter" def __exit__(self, exc_type, value, traceback): print "exit" a = ContextManager() with a: print 1 try: with a: print 2 raise RuntimeError except RuntimeError: print 3 """))) def testWithAs(self): self.assertEqual((0, '1 2 3\n'), _GrumpRun(textwrap.dedent("""\ class ContextManager(object): def __enter__(self): return (1, (2, 3)) def __exit__(self, *args): pass with ContextManager() as [x, (y, z)]: print x, y, z """))) def testWriteExceptDispatcherBareExcept(self): visitor = stmt.StatementVisitor(_MakeModuleBlock()) handlers = [ast.ExceptHandler(type=ast.Name(id='foo')), ast.ExceptHandler(type=None)] self.assertEqual(visitor._write_except_dispatcher( # pylint: disable=protected-access 'exc', 'tb', handlers), [1, 2]) expected = re.compile(r'ResolveGlobal\(.*foo.*\bIsInstance\(.*' r'goto Label1.*goto Label2', re.DOTALL) self.assertRegexpMatches(visitor.writer.getvalue(), expected) def testWriteExceptDispatcherBareExceptionNotLast(self): visitor = stmt.StatementVisitor(_MakeModuleBlock()) handlers = [ast.ExceptHandler(type=None), ast.ExceptHandler(type=ast.Name(id='foo'))] self.assertRaisesRegexp(util.ParseError, r"default 'except:' must be last", visitor._write_except_dispatcher, # pylint: disable=protected-access 'exc', 'tb', handlers) def testWriteExceptDispatcherMultipleExcept(self): visitor = stmt.StatementVisitor(_MakeModuleBlock()) handlers = [ast.ExceptHandler(type=ast.Name(id='foo')), ast.ExceptHandler(type=ast.Name(id='bar'))] self.assertEqual(visitor._write_except_dispatcher( # pylint: disable=protected-access 'exc', 'tb', handlers), [1, 2]) expected = re.compile( r'ResolveGlobal\(.*foo.*\bif .*\bIsInstance\(.*\{.*goto Label1.*' r'ResolveGlobal\(.*bar.*\bif .*\bIsInstance\(.*\{.*goto Label2.*' r'\bRaise\(exc\.ToObject\(\), nil, tb\.ToObject\(\)\)', re.DOTALL) self.assertRegexpMatches(visitor.writer.getvalue(), expected) def _MakeModuleBlock(): return block.ModuleBlock(None, '__main__', '<test>', '', imputil.FutureFeatures()) def _ParseAndVisit(source): mod = pythonparser.parse(source) _, future_features = imputil.parse_future_features(mod) importer = imputil.Importer(None, 'foo', 'foo.py', False) b = block.ModuleBlock(importer, '__main__', '<test>', source, future_features) visitor = stmt.StatementVisitor(b) visitor.visit(mod) return visitor def _GrumpRun(cmd): p = subprocess.Popen(['grumpy', 'run'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) out, _ = p.communicate(cmd) return p.returncode, out if __name__ == '__main__': shard_test.main()
Java
/* * Copyright 2017-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.lettuce.core.cluster.api.async; import java.util.List; import java.util.Set; import io.lettuce.core.GeoAddArgs; import io.lettuce.core.GeoArgs; import io.lettuce.core.GeoCoordinates; import io.lettuce.core.GeoRadiusStoreArgs; import io.lettuce.core.GeoSearch; import io.lettuce.core.GeoValue; import io.lettuce.core.GeoWithin; import io.lettuce.core.Value; /** * Asynchronous executed commands on a node selection for the Geo-API. * * @author Mark Paluch * @since 4.0 * @generated by io.lettuce.apigenerator.CreateAsyncNodeSelectionClusterApi */ public interface NodeSelectionGeoAsyncCommands<K, V> { /** * Single geo add. * * @param key the key of the geo set. * @param longitude the longitude coordinate according to WGS84. * @param latitude the latitude coordinate according to WGS84. * @param member the member to add. * @return Long integer-reply the number of elements that were added to the set. */ AsyncExecutions<Long> geoadd(K key, double longitude, double latitude, V member); /** * Single geo add. * * @param key the key of the geo set. * @param longitude the longitude coordinate according to WGS84. * @param latitude the latitude coordinate according to WGS84. * @param member the member to add. * @param args additional arguments. * @return Long integer-reply the number of elements that were added to the set. * @since 6.1 */ AsyncExecutions<Long> geoadd(K key, double longitude, double latitude, V member, GeoAddArgs args); /** * Multi geo add. * * @param key the key of the geo set. * @param lngLatMember triplets of double longitude, double latitude and V member. * @return Long integer-reply the number of elements that were added to the set. */ AsyncExecutions<Long> geoadd(K key, Object... lngLatMember); /** * Multi geo add. * * @param key the key of the geo set. * @param values {@link io.lettuce.core.GeoValue} values to add. * @return Long integer-reply the number of elements that were added to the set. * @since 6.1 */ AsyncExecutions<Long> geoadd(K key, GeoValue<V>... values); /** * Multi geo add. * * @param key the key of the geo set. * @param args additional arguments. * @param lngLatMember triplets of double longitude, double latitude and V member. * @return Long integer-reply the number of elements that were added to the set. * @since 6.1 */ AsyncExecutions<Long> geoadd(K key, GeoAddArgs args, Object... lngLatMember); /** * Multi geo add. * * @param key the key of the geo set. * @param args additional arguments. * @param values {@link io.lettuce.core.GeoValue} values to add. * @return Long integer-reply the number of elements that were added to the set. * @since 6.1 */ AsyncExecutions<Long> geoadd(K key, GeoAddArgs args, GeoValue<V>... values); /** * Retrieve distance between points {@code from} and {@code to}. If one or more elements are missing {@code null} is * returned. Default in meters by, otherwise according to {@code unit} * * @param key the key of the geo set. * @param from from member. * @param to to member. * @param unit distance unit. * @return distance between points {@code from} and {@code to}. If one or more elements are missing {@code null} is * returned. */ AsyncExecutions<Double> geodist(K key, V from, V to, GeoArgs.Unit unit); /** * Retrieve Geohash strings representing the position of one or more elements in a sorted set value representing a * geospatial index. * * @param key the key of the geo set. * @param members the members. * @return bulk reply Geohash strings in the order of {@code members}. Returns {@code null} if a member is not found. */ AsyncExecutions<List<Value<String>>> geohash(K key, V... members); /** * Get geo coordinates for the {@code members}. * * @param key the key of the geo set. * @param members the members. * @return a list of {@link GeoCoordinates}s representing the x,y position of each element specified in the arguments. For * missing elements {@code null} is returned. */ AsyncExecutions<List<GeoCoordinates>> geopos(K key, V... members); /** * Retrieve members selected by distance with the center of {@code longitude} and {@code latitude}. * * @param key the key of the geo set. * @param longitude the longitude coordinate according to WGS84. * @param latitude the latitude coordinate according to WGS84. * @param distance radius distance. * @param unit distance unit. * @return bulk reply. */ AsyncExecutions<Set<V>> georadius(K key, double longitude, double latitude, double distance, GeoArgs.Unit unit); /** * Retrieve members selected by distance with the center of {@code longitude} and {@code latitude}. * * @param key the key of the geo set. * @param longitude the longitude coordinate according to WGS84. * @param latitude the latitude coordinate according to WGS84. * @param distance radius distance. * @param unit distance unit. * @param geoArgs args to control the result. * @return nested multi-bulk reply. The {@link GeoWithin} contains only fields which were requested by {@link GeoArgs}. */ AsyncExecutions<List<GeoWithin<V>>> georadius(K key, double longitude, double latitude, double distance, GeoArgs.Unit unit, GeoArgs geoArgs); /** * Perform a {@link #georadius(Object, double, double, double, GeoArgs.Unit, GeoArgs)} query and store the results in a * sorted set. * * @param key the key of the geo set. * @param longitude the longitude coordinate according to WGS84. * @param latitude the latitude coordinate according to WGS84. * @param distance radius distance. * @param unit distance unit. * @param geoRadiusStoreArgs args to store either the resulting elements with their distance or the resulting elements with * their locations a sorted set. * @return Long integer-reply the number of elements in the result. */ AsyncExecutions<Long> georadius(K key, double longitude, double latitude, double distance, GeoArgs.Unit unit, GeoRadiusStoreArgs<K> geoRadiusStoreArgs); /** * Retrieve members selected by distance with the center of {@code member}. The member itself is always contained in the * results. * * @param key the key of the geo set. * @param member reference member. * @param distance radius distance. * @param unit distance unit. * @return set of members. */ AsyncExecutions<Set<V>> georadiusbymember(K key, V member, double distance, GeoArgs.Unit unit); /** * Retrieve members selected by distance with the center of {@code member}. The member itself is always contained in the * results. * * @param key the key of the geo set. * @param member reference member. * @param distance radius distance. * @param unit distance unit. * @param geoArgs args to control the result. * @return nested multi-bulk reply. The {@link GeoWithin} contains only fields which were requested by {@link GeoArgs}. */ AsyncExecutions<List<GeoWithin<V>>> georadiusbymember(K key, V member, double distance, GeoArgs.Unit unit, GeoArgs geoArgs); /** * Perform a {@link #georadiusbymember(Object, Object, double, GeoArgs.Unit, GeoArgs)} query and store the results in a * sorted set. * * @param key the key of the geo set. * @param member reference member. * @param distance radius distance. * @param unit distance unit. * @param geoRadiusStoreArgs args to store either the resulting elements with their distance or the resulting elements with * their locations a sorted set. * @return Long integer-reply the number of elements in the result. */ AsyncExecutions<Long> georadiusbymember(K key, V member, double distance, GeoArgs.Unit unit, GeoRadiusStoreArgs<K> geoRadiusStoreArgs); /** * Retrieve members selected by distance with the center of {@code reference} the search {@code predicate}. * Use {@link GeoSearch} to create reference and predicate objects. * * @param key the key of the geo set. * @param reference the reference member or longitude/latitude coordinates. * @param predicate the bounding box or radius to search in. * @return bulk reply. * @since 6.1 */ AsyncExecutions<Set<V>> geosearch(K key, GeoSearch.GeoRef<K> reference, GeoSearch.GeoPredicate predicate); /** * Retrieve members selected by distance with the center of {@code reference} the search {@code predicate}. * Use {@link GeoSearch} to create reference and predicate objects. * * @param key the key of the geo set. * @param reference the reference member or longitude/latitude coordinates. * @param predicate the bounding box or radius to search in. * @param geoArgs args to control the result. * @return nested multi-bulk reply. The {@link GeoWithin} contains only fields which were requested by {@link GeoArgs}. * @since 6.1 */ AsyncExecutions<List<GeoWithin<V>>> geosearch(K key, GeoSearch.GeoRef<K> reference, GeoSearch.GeoPredicate predicate, GeoArgs geoArgs); /** * Perform a {@link #geosearch(Object, GeoSearch.GeoRef, GeoSearch.GeoPredicate, GeoArgs)} query and store the results in a * sorted set. * * @param destination the destination where to store results. * @param key the key of the geo set. * @param reference the reference member or longitude/latitude coordinates. * @param predicate the bounding box or radius to search in. * @param geoArgs args to control the result. * @param storeDist stores the items in a sorted set populated with their distance from the center of the circle or box, as a floating-point number, in the same unit specified for that shape. * @return Long integer-reply the number of elements in the result. * @since 6.1 */ AsyncExecutions<Long> geosearchstore(K destination, K key, GeoSearch.GeoRef<K> reference, GeoSearch.GeoPredicate predicate, GeoArgs geoArgs, boolean storeDist); }
Java
<html> <head> <meta http-equiv="Content-Type" content="text/html;charset=utf-8"> <link rel="stylesheet" type="text/css" href="licenses.css"> </head> <body> <h2>fh-service-mongodb-cloud</h2> <table> <tr> <th>Package Group</th> <th>Package Artifact</th> <th>Package Version</th> <th>Remote Licenses</th> <th>Local Licenses</th> </tr> <tr> <td>N/A</td> <td>accepts</td> <td>1.0.0</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=#>No local license could be found for the dependency</a></td> </tr> <tr> <td>N/A</td> <td>accepts</td> <td>1.3.4</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=ACCEPTS_MIT.TXT>ACCEPTS_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>adm-zip</td> <td>0.4.7</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=#>No local license could be found for the dependency</a></td> </tr> <tr> <td>N/A</td> <td>ajv</td> <td>4.11.5</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=AJV_MIT.TXT>AJV_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>ajv</td> <td>5.5.2</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=AJV_MIT.TXT>AJV_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>amqp</td> <td>0.2.0</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=#>No local license could be found for the dependency</a></td> </tr> <tr> <td>N/A</td> <td>ansi-regex</td> <td>2.1.1</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=ANSI-REGEX_MIT.TXT>ANSI-REGEX_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>ansi-styles</td> <td>2.2.1</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=ANSI-STYLES_MIT.TXT>ANSI-STYLES_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>append-field</td> <td>0.1.0</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=APPEND-FIELD_MIT.TXT>APPEND-FIELD_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>archiver</td> <td>1.0.0</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=ARCHIVER_MIT.TXT>ARCHIVER_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>archiver-utils</td> <td>1.3.0</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=ARCHIVER-UTILS_MIT.TXT>ARCHIVER-UTILS_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>array-flatten</td> <td>1.1.1</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=ARRAY-FLATTEN_MIT.TXT>ARRAY-FLATTEN_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>asn1</td> <td>0.2.3</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=ASN1_MIT.TXT>ASN1_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>assert-plus</td> <td>0.2.0</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=#>No local license could be found for the dependency</a></td> </tr> <tr> <td>N/A</td> <td>assert-plus</td> <td>1.0.0</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=#>No local license could be found for the dependency</a></td> </tr> <tr> <td>N/A</td> <td>async</td> <td>0.2.7</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=ASYNC_MIT.TXT>ASYNC_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>async</td> <td>1.5.2</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=ASYNC_MIT.TXT>ASYNC_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>async</td> <td>2.1.5</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=ASYNC_MIT.TXT>ASYNC_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>async</td> <td>0.2.9</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=ASYNC_MIT.TXT>ASYNC_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>async-listener</td> <td>0.6.0</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;BSD-2-Clause</td> <td><a href=#>No local license could be found for the dependency</a></td> </tr> <tr> <td>N/A</td> <td>asynckit</td> <td>0.4.0</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=ASYNCKIT_MIT.TXT>ASYNCKIT_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>aws-sign2</td> <td>0.6.0</td> <td>http:&#x2F;&#x2F;www.apache.org&#x2F;licenses&#x2F;LICENSE-2.0</td> <td><a href=AWS-SIGN2_APACHE-2.0.TXT>AWS-SIGN2_APACHE-2.0.TXT</a></td> </tr> <tr> <td>N/A</td> <td>aws-sign2</td> <td>0.7.0</td> <td>http:&#x2F;&#x2F;www.apache.org&#x2F;licenses&#x2F;LICENSE-2.0</td> <td><a href=AWS-SIGN2_APACHE-2.0.TXT>AWS-SIGN2_APACHE-2.0.TXT</a></td> </tr> <tr> <td>N/A</td> <td>aws4</td> <td>1.6.0</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=AWS4_MIT.TXT>AWS4_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>backoff</td> <td>2.5.0</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=BACKOFF_MIT.TXT>BACKOFF_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>balanced-match</td> <td>1.0.0</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=BALANCED-MATCH_MIT.TXT>BALANCED-MATCH_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>balanced-match</td> <td>0.4.1</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=BALANCED-MATCH_MIT.TXT>BALANCED-MATCH_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>bcrypt-pbkdf</td> <td>1.0.1</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;BSD-3-Clause</td> <td><a href=#>No local license could be found for the dependency</a></td> </tr> <tr> <td>N/A</td> <td>bl</td> <td>1.2.1</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=BL_MIT.TXT>BL_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>bluebird</td> <td>3.5.1</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=BLUEBIRD_MIT.TXT>BLUEBIRD_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>body-parser</td> <td>1.18.2</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=BODY-PARSER_MIT.TXT>BODY-PARSER_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>body-parser</td> <td>1.0.2</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=#>No local license could be found for the dependency</a></td> </tr> <tr> <td>N/A</td> <td>boom</td> <td>2.10.1</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;BSD-3-Clause</td> <td><a href=BOOM_BSD-3-CLAUSE.TXT>BOOM_BSD-3-CLAUSE.TXT</a></td> </tr> <tr> <td>N/A</td> <td>boom</td> <td>4.3.1</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;BSD-3-Clause</td> <td><a href=BOOM_BSD-3-CLAUSE.TXT>BOOM_BSD-3-CLAUSE.TXT</a></td> </tr> <tr> <td>N/A</td> <td>boom</td> <td>5.2.0</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;BSD-3-Clause</td> <td><a href=BOOM_BSD-3-CLAUSE.TXT>BOOM_BSD-3-CLAUSE.TXT</a></td> </tr> <tr> <td>N/A</td> <td>brace-expansion</td> <td>1.1.5</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=#>No local license could be found for the dependency</a></td> </tr> <tr> <td>N/A</td> <td>brace-expansion</td> <td>1.1.8</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=#>No local license could be found for the dependency</a></td> </tr> <tr> <td>N/A</td> <td>bson</td> <td>0.4.22</td> <td>http:&#x2F;&#x2F;www.apache.org&#x2F;licenses&#x2F;LICENSE-2.0</td> <td><a href=BSON_APACHE-2.0.TXT>BSON_APACHE-2.0.TXT</a></td> </tr> <tr> <td>N/A</td> <td>bson</td> <td>0.4.23</td> <td>http:&#x2F;&#x2F;www.apache.org&#x2F;licenses&#x2F;LICENSE-2.0</td> <td><a href=BSON_APACHE-2.0.TXT>BSON_APACHE-2.0.TXT</a></td> </tr> <tr> <td>N/A</td> <td>bson</td> <td>1.0.6</td> <td>http:&#x2F;&#x2F;www.apache.org&#x2F;licenses&#x2F;LICENSE-2.0</td> <td><a href=BSON_APACHE-2.0.TXT>BSON_APACHE-2.0.TXT</a></td> </tr> <tr> <td>N/A</td> <td>buffer-crc32</td> <td>0.2.1</td> <td>UNKNOWN</td> <td><a href=#>No local license could be found for the dependency</a></td> </tr> <tr> <td>N/A</td> <td>buffer-crc32</td> <td>0.2.13</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=BUFFER-CRC32_MIT.TXT>BUFFER-CRC32_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>bunyan</td> <td>1.8.2</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=BUNYAN_MIT.TXT>BUNYAN_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>bunyan</td> <td>1.8.1</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=BUNYAN_MIT.TXT>BUNYAN_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>busboy</td> <td>0.2.14</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=BUSBOY_MIT.TXT>BUSBOY_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>bytes</td> <td>1.0.0</td> <td>UNKNOWN</td> <td><a href=#>No local license could be found for the dependency</a></td> </tr> <tr> <td>N/A</td> <td>bytes</td> <td>3.0.0</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=BYTES_MIT.TXT>BYTES_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>caseless</td> <td>0.11.0</td> <td>http:&#x2F;&#x2F;www.apache.org&#x2F;licenses&#x2F;LICENSE-2.0</td> <td><a href=CASELESS_APACHE-2.0.TXT>CASELESS_APACHE-2.0.TXT</a></td> </tr> <tr> <td>N/A</td> <td>caseless</td> <td>0.12.0</td> <td>http:&#x2F;&#x2F;www.apache.org&#x2F;licenses&#x2F;LICENSE-2.0</td> <td><a href=CASELESS_APACHE-2.0.TXT>CASELESS_APACHE-2.0.TXT</a></td> </tr> <tr> <td>N/A</td> <td>chalk</td> <td>1.1.3</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=CHALK_MIT.TXT>CHALK_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>co</td> <td>4.6.0</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=CO_MIT.TXT>CO_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>combined-stream</td> <td>1.0.5</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=COMBINED-STREAM_MIT.TXT>COMBINED-STREAM_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>combined-stream</td> <td>1.0.6</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=COMBINED-STREAM_MIT.TXT>COMBINED-STREAM_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>commander</td> <td>2.15.1</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=COMMANDER_MIT.TXT>COMMANDER_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>compress-commons</td> <td>1.2.2</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=COMPRESS-COMMONS_MIT.TXT>COMPRESS-COMMONS_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>concat-map</td> <td>0.0.1</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=CONCAT-MAP_MIT.TXT>CONCAT-MAP_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>concat-stream</td> <td>1.6.0</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=CONCAT-STREAM_MIT.TXT>CONCAT-STREAM_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>connection-parse</td> <td>0.0.7</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=#>No local license could be found for the dependency</a></td> </tr> <tr> <td>N/A</td> <td>content-disposition</td> <td>0.5.2</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=CONTENT-DISPOSITION_MIT.TXT>CONTENT-DISPOSITION_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>content-type</td> <td>1.0.4</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=CONTENT-TYPE_MIT.TXT>CONTENT-TYPE_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>continuation-local-storage</td> <td>3.1.7</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;BSD-2-Clause</td> <td><a href=CONTINUATION-LOCAL-STORAGE_BSD-2-CLAUSE.TXT>CONTINUATION-LOCAL-STORAGE_BSD-2-CLAUSE.TXT</a></td> </tr> <tr> <td>N/A</td> <td>cookie</td> <td>0.3.1</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=COOKIE_MIT.TXT>COOKIE_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>cookie</td> <td>0.1.0</td> <td>UNKNOWN</td> <td><a href=COOKIE_MIT*.TXT>COOKIE_MIT*.TXT</a></td> </tr> <tr> <td>N/A</td> <td>cookie-signature</td> <td>1.0.3</td> <td>UNKNOWN</td> <td><a href=#>No local license could be found for the dependency</a></td> </tr> <tr> <td>N/A</td> <td>cookie-signature</td> <td>1.0.6</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=#>No local license could be found for the dependency</a></td> </tr> <tr> <td>N/A</td> <td>core-util-is</td> <td>1.0.2</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=CORE-UTIL-IS_MIT.TXT>CORE-UTIL-IS_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>cors</td> <td>2.2.0</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=CORS_MIT.TXT>CORS_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>cors</td> <td>2.1.0</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=CORS_MIT.TXT>CORS_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>crc</td> <td>3.5.0</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=CRC_MIT.TXT>CRC_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>crc32-stream</td> <td>2.0.0</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=CRC32-STREAM_MIT.TXT>CRC32-STREAM_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>cryptiles</td> <td>3.1.2</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;BSD-3-Clause</td> <td><a href=CRYPTILES_BSD-3-CLAUSE.TXT>CRYPTILES_BSD-3-CLAUSE.TXT</a></td> </tr> <tr> <td>N/A</td> <td>cryptiles</td> <td>2.0.5</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;BSD-3-Clause</td> <td><a href=CRYPTILES_BSD-3-CLAUSE.TXT>CRYPTILES_BSD-3-CLAUSE.TXT</a></td> </tr> <tr> <td>N/A</td> <td>csvtojson</td> <td>0.3.6</td> <td>UNKNOWN</td> <td><a href=#>No local license could be found for the dependency</a></td> </tr> <tr> <td>N/A</td> <td>dashdash</td> <td>1.14.1</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=DASHDASH_MIT.TXT>DASHDASH_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>debug</td> <td>0.8.1</td> <td>UNKNOWN</td> <td><a href=#>No local license could be found for the dependency</a></td> </tr> <tr> <td>N/A</td> <td>debug</td> <td>2.6.9</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=DEBUG_MIT.TXT>DEBUG_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>deep-extend</td> <td>0.2.11</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=DEEP-EXTEND_MIT.TXT>DEEP-EXTEND_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>delayed-stream</td> <td>1.0.0</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=DELAYED-STREAM_MIT.TXT>DELAYED-STREAM_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>depd</td> <td>1.1.1</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=DEPD_MIT.TXT>DEPD_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>destroy</td> <td>1.0.4</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=DESTROY_MIT.TXT>DESTROY_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>dicer</td> <td>0.2.5</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=DICER_MIT.TXT>DICER_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>double-ended-queue</td> <td>2.1.0-0</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=DOUBLE-ENDED-QUEUE_MIT.TXT>DOUBLE-ENDED-QUEUE_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>dtrace-provider</td> <td>0.6.0</td> <td>UNKNOWN</td> <td><a href=DTRACE-PROVIDER_BSD*.TXT>DTRACE-PROVIDER_BSD*.TXT</a></td> </tr> <tr> <td>N/A</td> <td>dtrace-provider</td> <td>0.7.1</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;BSD-2-Clause</td> <td><a href=DTRACE-PROVIDER_BSD-2-CLAUSE.TXT>DTRACE-PROVIDER_BSD-2-CLAUSE.TXT</a></td> </tr> <tr> <td>N/A</td> <td>ecc-jsbn</td> <td>0.1.1</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=ECC-JSBN_MIT.TXT>ECC-JSBN_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>ee-first</td> <td>1.1.1</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=EE-FIRST_MIT.TXT>EE-FIRST_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>emitter-listener</td> <td>1.0.1</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;BSD-2-Clause</td> <td><a href=#>No local license could be found for the dependency</a></td> </tr> <tr> <td>N/A</td> <td>encodeurl</td> <td>1.0.1</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=ENCODEURL_MIT.TXT>ENCODEURL_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>end-of-stream</td> <td>1.4.0</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=END-OF-STREAM_MIT.TXT>END-OF-STREAM_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>env-var</td> <td>2.4.3</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=#>No local license could be found for the dependency</a></td> </tr> <tr> <td>N/A</td> <td>es6-promise</td> <td>3.0.2</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=ES6-PROMISE_MIT.TXT>ES6-PROMISE_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>escape-html</td> <td>1.0.3</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=ESCAPE-HTML_MIT.TXT>ESCAPE-HTML_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>escape-html</td> <td>1.0.1</td> <td>UNKNOWN</td> <td><a href=#>No local license could be found for the dependency</a></td> </tr> <tr> <td>N/A</td> <td>escape-string-regexp</td> <td>1.0.5</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=ESCAPE-STRING-REGEXP_MIT.TXT>ESCAPE-STRING-REGEXP_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>etag</td> <td>1.8.1</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=ETAG_MIT.TXT>ETAG_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>express</td> <td>4.16.0</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=EXPRESS_MIT.TXT>EXPRESS_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>express</td> <td>4.0.0</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=EXPRESS_MIT.TXT>EXPRESS_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>extend</td> <td>3.0.0</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=EXTEND_MIT.TXT>EXTEND_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>extend</td> <td>3.0.1</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=EXTEND_MIT.TXT>EXTEND_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>extsprintf</td> <td>1.2.0</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=EXTSPRINTF_MIT.TXT>EXTSPRINTF_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>extsprintf</td> <td>1.0.2</td> <td>UNKNOWN</td> <td><a href=EXTSPRINTF_MIT*.TXT>EXTSPRINTF_MIT*.TXT</a></td> </tr> <tr> <td>N/A</td> <td>extsprintf</td> <td>1.3.0</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=EXTSPRINTF_MIT.TXT>EXTSPRINTF_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>fast-deep-equal</td> <td>1.1.0</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=FAST-DEEP-EQUAL_MIT.TXT>FAST-DEEP-EQUAL_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>fast-json-stable-stringify</td> <td>2.0.0</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=FAST-JSON-STABLE-STRINGIFY_MIT.TXT>FAST-JSON-STABLE-STRINGIFY_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>fh-amqp-js</td> <td>0.7.1</td> <td>http:&#x2F;&#x2F;www.apache.org&#x2F;licenses&#x2F;LICENSE-2.0</td> <td><a href=FH-AMQP-JS_APACHE-2.0.TXT>FH-AMQP-JS_APACHE-2.0.TXT</a></td> </tr> <tr> <td>N/A</td> <td>fh-component-metrics</td> <td>2.7.0</td> <td>http:&#x2F;&#x2F;www.apache.org&#x2F;licenses&#x2F;LICENSE-2.0</td> <td><a href=FH-COMPONENT-METRICS_APACHE-2.0.TXT>FH-COMPONENT-METRICS_APACHE-2.0.TXT</a></td> </tr> <tr> <td>N/A</td> <td>fh-db</td> <td>3.3.0</td> <td>http:&#x2F;&#x2F;www.apache.org&#x2F;licenses&#x2F;LICENSE-2.0</td> <td><a href=FH-DB_APACHE-2.0.TXT>FH-DB_APACHE-2.0.TXT</a></td> </tr> <tr> <td>N/A</td> <td>fh-logger</td> <td>0.5.0</td> <td>http:&#x2F;&#x2F;www.apache.org&#x2F;licenses&#x2F;LICENSE-2.0</td> <td><a href=FH-LOGGER_APACHE-2.0.TXT>FH-LOGGER_APACHE-2.0.TXT</a></td> </tr> <tr> <td>N/A</td> <td>fh-mbaas-api</td> <td>8.2.1</td> <td>http:&#x2F;&#x2F;www.apache.org&#x2F;licenses&#x2F;LICENSE-2.0</td> <td><a href=FH-MBAAS-API_APACHE-2.0.TXT>FH-MBAAS-API_APACHE-2.0.TXT</a></td> </tr> <tr> <td>N/A</td> <td>fh-mbaas-client</td> <td>0.16.5</td> <td>http:&#x2F;&#x2F;www.apache.org&#x2F;licenses&#x2F;LICENSE-2.0</td> <td><a href=FH-MBAAS-CLIENT_APACHE-2.0.TXT>FH-MBAAS-CLIENT_APACHE-2.0.TXT</a></td> </tr> <tr> <td>N/A</td> <td>fh-mbaas-client</td> <td>1.1.1</td> <td>http:&#x2F;&#x2F;www.apache.org&#x2F;licenses&#x2F;LICENSE-2.0</td> <td><a href=FH-MBAAS-CLIENT_APACHE-2.0.TXT>FH-MBAAS-CLIENT_APACHE-2.0.TXT</a></td> </tr> <tr> <td>N/A</td> <td>fh-mbaas-express</td> <td>5.10.0</td> <td>http:&#x2F;&#x2F;www.apache.org&#x2F;licenses&#x2F;LICENSE-2.0</td> <td><a href=FH-MBAAS-EXPRESS_APACHE-2.0.TXT>FH-MBAAS-EXPRESS_APACHE-2.0.TXT</a></td> </tr> <tr> <td>N/A</td> <td>fh-mongodb-queue</td> <td>3.3.0</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=FH-MONGODB-QUEUE_MIT.TXT>FH-MONGODB-QUEUE_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>fh-reportingclient</td> <td>0.5.7</td> <td>http:&#x2F;&#x2F;www.apache.org&#x2F;licenses&#x2F;LICENSE-2.0</td> <td><a href=FH-REPORTINGCLIENT_APACHE-2.0.TXT>FH-REPORTINGCLIENT_APACHE-2.0.TXT</a></td> </tr> <tr> <td>N/A</td> <td>fh-security</td> <td>0.2.1</td> <td>http:&#x2F;&#x2F;www.apache.org&#x2F;licenses&#x2F;LICENSE-2.0</td> <td><a href=FH-SECURITY_APACHE-2.0.TXT>FH-SECURITY_APACHE-2.0.TXT</a></td> </tr> <tr> <td>N/A</td> <td>fh-service-mongodb-cloud</td> <td>0.2.1</td> <td>http:&#x2F;&#x2F;www.apache.org&#x2F;licenses&#x2F;LICENSE-2.0</td> <td><a href=FH-SERVICE-MONGODB-CLOUD_APACHE-2.0.TXT>FH-SERVICE-MONGODB-CLOUD_APACHE-2.0.TXT</a></td> </tr> <tr> <td>N/A</td> <td>fh-statsc</td> <td>0.3.0</td> <td>http:&#x2F;&#x2F;www.apache.org&#x2F;licenses&#x2F;LICENSE-2.0</td> <td><a href=FH-STATSC_APACHE-2.0.TXT>FH-STATSC_APACHE-2.0.TXT</a></td> </tr> <tr> <td>N/A</td> <td>fh-sync</td> <td>1.0.14</td> <td>http:&#x2F;&#x2F;www.apache.org&#x2F;licenses&#x2F;LICENSE-2.0</td> <td><a href=FH-SYNC_APACHE-2.0.TXT>FH-SYNC_APACHE-2.0.TXT</a></td> </tr> <tr> <td>N/A</td> <td>finalhandler</td> <td>1.1.0</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=FINALHANDLER_MIT.TXT>FINALHANDLER_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>forever-agent</td> <td>0.6.1</td> <td>http:&#x2F;&#x2F;www.apache.org&#x2F;licenses&#x2F;LICENSE-2.0</td> <td><a href=FOREVER-AGENT_APACHE-2.0.TXT>FOREVER-AGENT_APACHE-2.0.TXT</a></td> </tr> <tr> <td>N/A</td> <td>form-data</td> <td>2.1.2</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=FORM-DATA_MIT.TXT>FORM-DATA_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>form-data</td> <td>2.1.4</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=FORM-DATA_MIT.TXT>FORM-DATA_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>form-data</td> <td>2.3.2</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=FORM-DATA_MIT.TXT>FORM-DATA_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>forwarded</td> <td>0.1.2</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=FORWARDED_MIT.TXT>FORWARDED_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>fresh</td> <td>0.2.2</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=#>No local license could be found for the dependency</a></td> </tr> <tr> <td>N/A</td> <td>fresh</td> <td>0.2.0</td> <td>UNKNOWN</td> <td><a href=#>No local license could be found for the dependency</a></td> </tr> <tr> <td>N/A</td> <td>fresh</td> <td>0.5.2</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=FRESH_MIT.TXT>FRESH_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>fs.realpath</td> <td>1.0.0</td> <td>http:&#x2F;&#x2F;www.isc.org&#x2F;software&#x2F;license</td> <td><a href=FS.REALPATH_ISC.TXT>FS.REALPATH_ISC.TXT</a></td> </tr> <tr> <td>N/A</td> <td>generate-function</td> <td>2.0.0</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=#>No local license could be found for the dependency</a></td> </tr> <tr> <td>N/A</td> <td>generate-object-property</td> <td>1.2.0</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=GENERATE-OBJECT-PROPERTY_MIT.TXT>GENERATE-OBJECT-PROPERTY_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>getpass</td> <td>0.1.6</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=GETPASS_MIT.TXT>GETPASS_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>getpass</td> <td>0.1.7</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=GETPASS_MIT.TXT>GETPASS_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>glob</td> <td>6.0.4</td> <td>http:&#x2F;&#x2F;www.isc.org&#x2F;software&#x2F;license</td> <td><a href=GLOB_ISC.TXT>GLOB_ISC.TXT</a></td> </tr> <tr> <td>N/A</td> <td>glob</td> <td>7.1.2</td> <td>http:&#x2F;&#x2F;www.isc.org&#x2F;software&#x2F;license</td> <td><a href=GLOB_ISC.TXT>GLOB_ISC.TXT</a></td> </tr> <tr> <td>N/A</td> <td>graceful-fs</td> <td>4.1.11</td> <td>http:&#x2F;&#x2F;www.isc.org&#x2F;software&#x2F;license</td> <td><a href=GRACEFUL-FS_ISC.TXT>GRACEFUL-FS_ISC.TXT</a></td> </tr> <tr> <td>N/A</td> <td>har-schema</td> <td>1.0.5</td> <td>http:&#x2F;&#x2F;www.isc.org&#x2F;software&#x2F;license</td> <td><a href=HAR-SCHEMA_ISC.TXT>HAR-SCHEMA_ISC.TXT</a></td> </tr> <tr> <td>N/A</td> <td>har-schema</td> <td>2.0.0</td> <td>http:&#x2F;&#x2F;www.isc.org&#x2F;software&#x2F;license</td> <td><a href=HAR-SCHEMA_ISC.TXT>HAR-SCHEMA_ISC.TXT</a></td> </tr> <tr> <td>N/A</td> <td>har-validator</td> <td>2.0.6</td> <td>http:&#x2F;&#x2F;www.isc.org&#x2F;software&#x2F;license</td> <td><a href=HAR-VALIDATOR_ISC.TXT>HAR-VALIDATOR_ISC.TXT</a></td> </tr> <tr> <td>N/A</td> <td>har-validator</td> <td>4.2.1</td> <td>http:&#x2F;&#x2F;www.isc.org&#x2F;software&#x2F;license</td> <td><a href=HAR-VALIDATOR_ISC.TXT>HAR-VALIDATOR_ISC.TXT</a></td> </tr> <tr> <td>N/A</td> <td>har-validator</td> <td>5.0.3</td> <td>http:&#x2F;&#x2F;www.isc.org&#x2F;software&#x2F;license</td> <td><a href=HAR-VALIDATOR_ISC.TXT>HAR-VALIDATOR_ISC.TXT</a></td> </tr> <tr> <td>N/A</td> <td>has-ansi</td> <td>2.0.0</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=HAS-ANSI_MIT.TXT>HAS-ANSI_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>hashring</td> <td>3.2.0</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=HASHRING_MIT.TXT>HASHRING_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>hawk</td> <td>3.1.3</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;BSD-3-Clause</td> <td><a href=HAWK_BSD-3-CLAUSE.TXT>HAWK_BSD-3-CLAUSE.TXT</a></td> </tr> <tr> <td>N/A</td> <td>hawk</td> <td>6.0.2</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;BSD-3-Clause</td> <td><a href=HAWK_BSD-3-CLAUSE.TXT>HAWK_BSD-3-CLAUSE.TXT</a></td> </tr> <tr> <td>N/A</td> <td>hoek</td> <td>2.16.3</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;BSD-3-Clause</td> <td><a href=HOEK_BSD-3-CLAUSE.TXT>HOEK_BSD-3-CLAUSE.TXT</a></td> </tr> <tr> <td>N/A</td> <td>hoek</td> <td>4.2.1</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;BSD-3-Clause</td> <td><a href=HOEK_BSD-3-CLAUSE.TXT>HOEK_BSD-3-CLAUSE.TXT</a></td> </tr> <tr> <td>N/A</td> <td>http-errors</td> <td>1.6.2</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=HTTP-ERRORS_MIT.TXT>HTTP-ERRORS_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>http-signature</td> <td>1.2.0</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=HTTP-SIGNATURE_MIT.TXT>HTTP-SIGNATURE_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>http-signature</td> <td>1.1.1</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=HTTP-SIGNATURE_MIT.TXT>HTTP-SIGNATURE_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>iconv-lite</td> <td>0.4.19</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=ICONV-LITE_MIT.TXT>ICONV-LITE_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>inflight</td> <td>1.0.5</td> <td>http:&#x2F;&#x2F;www.isc.org&#x2F;software&#x2F;license</td> <td><a href=INFLIGHT_ISC.TXT>INFLIGHT_ISC.TXT</a></td> </tr> <tr> <td>N/A</td> <td>inflight</td> <td>1.0.6</td> <td>http:&#x2F;&#x2F;www.isc.org&#x2F;software&#x2F;license</td> <td><a href=INFLIGHT_ISC.TXT>INFLIGHT_ISC.TXT</a></td> </tr> <tr> <td>N/A</td> <td>inherits</td> <td>2.0.1</td> <td>http:&#x2F;&#x2F;www.isc.org&#x2F;software&#x2F;license</td> <td><a href=INHERITS_ISC.TXT>INHERITS_ISC.TXT</a></td> </tr> <tr> <td>N/A</td> <td>inherits</td> <td>2.0.3</td> <td>http:&#x2F;&#x2F;www.isc.org&#x2F;software&#x2F;license</td> <td><a href=INHERITS_ISC.TXT>INHERITS_ISC.TXT</a></td> </tr> <tr> <td>N/A</td> <td>ini</td> <td>1.1.0</td> <td>UNKNOWN</td> <td><a href=INI_MIT*.TXT>INI_MIT*.TXT</a></td> </tr> <tr> <td>N/A</td> <td>ipaddr.js</td> <td>1.5.2</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=IPADDR.JS_MIT.TXT>IPADDR.JS_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>is-my-ip-valid</td> <td>1.0.0</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=#>No local license could be found for the dependency</a></td> </tr> <tr> <td>N/A</td> <td>is-my-json-valid</td> <td>2.17.2</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=IS-MY-JSON-VALID_MIT.TXT>IS-MY-JSON-VALID_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>is-property</td> <td>1.0.2</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=IS-PROPERTY_MIT.TXT>IS-PROPERTY_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>is-typedarray</td> <td>1.0.0</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=IS-TYPEDARRAY_MIT.TXT>IS-TYPEDARRAY_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>isarray</td> <td>0.0.1</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=#>No local license could be found for the dependency</a></td> </tr> <tr> <td>N/A</td> <td>isarray</td> <td>1.0.0</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=#>No local license could be found for the dependency</a></td> </tr> <tr> <td>N/A</td> <td>isstream</td> <td>0.1.2</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=ISSTREAM_MIT.TXT>ISSTREAM_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>jackpot</td> <td>0.0.6</td> <td>UNKNOWN</td> <td><a href=#>No local license could be found for the dependency</a></td> </tr> <tr> <td>N/A</td> <td>jcsv</td> <td>0.0.3</td> <td>UNKNOWN</td> <td><a href=#>No local license could be found for the dependency</a></td> </tr> <tr> <td>N/A</td> <td>jodid25519</td> <td>1.0.2</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=JODID25519_MIT.TXT>JODID25519_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>jsbn</td> <td>0.1.1</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=JSBN_MIT.TXT>JSBN_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>json-schema</td> <td>0.2.3</td> <td>UNKNOWN</td> <td><a href=#>No local license could be found for the dependency</a></td> </tr> <tr> <td>N/A</td> <td>json-schema-traverse</td> <td>0.3.1</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=JSON-SCHEMA-TRAVERSE_MIT.TXT>JSON-SCHEMA-TRAVERSE_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>json-stable-stringify</td> <td>1.0.1</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=JSON-STABLE-STRINGIFY_MIT.TXT>JSON-STABLE-STRINGIFY_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>json-stringify-safe</td> <td>5.0.1</td> <td>http:&#x2F;&#x2F;www.isc.org&#x2F;software&#x2F;license</td> <td><a href=JSON-STRINGIFY-SAFE_ISC.TXT>JSON-STRINGIFY-SAFE_ISC.TXT</a></td> </tr> <tr> <td>N/A</td> <td>jsonify</td> <td>0.0.0</td> <td>UNKNOWN</td> <td><a href=JSONIFY_PUBLIC%20DOMAIN.TXT>JSONIFY_PUBLIC DOMAIN.TXT</a></td> </tr> <tr> <td>N/A</td> <td>jsonpointer</td> <td>4.0.1</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=JSONPOINTER_MIT.TXT>JSONPOINTER_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>jsprim</td> <td>1.4.0</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=JSPRIM_MIT.TXT>JSPRIM_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>jsprim</td> <td>1.4.1</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=JSPRIM_MIT.TXT>JSPRIM_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>lazystream</td> <td>1.0.0</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=#>No local license could be found for the dependency</a></td> </tr> <tr> <td>N/A</td> <td>lodash</td> <td>3.10.1</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=LODASH_MIT.TXT>LODASH_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>lodash</td> <td>1.3.1</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=#>No local license could be found for the dependency</a></td> </tr> <tr> <td>N/A</td> <td>lodash</td> <td>4.17.4</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=LODASH_MIT.TXT>LODASH_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>lodash</td> <td>4.17.5</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=LODASH_MIT.TXT>LODASH_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>lodash</td> <td>2.4.1</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=LODASH_MIT.TXT>LODASH_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>lodash</td> <td>3.9.3</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=LODASH_MIT.TXT>LODASH_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>lodash-contrib</td> <td>393.0.1</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=LODASH-CONTRIB_MIT.TXT>LODASH-CONTRIB_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>media-typer</td> <td>0.3.0</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=MEDIA-TYPER_MIT.TXT>MEDIA-TYPER_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>memcached</td> <td>2.2.2</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=MEMCACHED_MIT.TXT>MEMCACHED_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>merge-descriptors</td> <td>0.0.2</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=#>No local license could be found for the dependency</a></td> </tr> <tr> <td>N/A</td> <td>merge-descriptors</td> <td>1.0.1</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=MERGE-DESCRIPTORS_MIT.TXT>MERGE-DESCRIPTORS_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>methods</td> <td>0.1.0</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=#>No local license could be found for the dependency</a></td> </tr> <tr> <td>N/A</td> <td>methods</td> <td>1.1.2</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=METHODS_MIT.TXT>METHODS_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>mime</td> <td>1.2.11</td> <td>UNKNOWN</td> <td><a href=MIME_MIT*.TXT>MIME_MIT*.TXT</a></td> </tr> <tr> <td>N/A</td> <td>mime</td> <td>1.4.1</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=MIME_MIT.TXT>MIME_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>mime-db</td> <td>1.33.0</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=MIME-DB_MIT.TXT>MIME-DB_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>mime-db</td> <td>1.26.0</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=MIME-DB_MIT.TXT>MIME-DB_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>mime-db</td> <td>1.30.0</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=MIME-DB_MIT.TXT>MIME-DB_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>mime-types</td> <td>2.1.14</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=MIME-TYPES_MIT.TXT>MIME-TYPES_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>mime-types</td> <td>2.1.17</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=MIME-TYPES_MIT.TXT>MIME-TYPES_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>mime-types</td> <td>2.1.18</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=MIME-TYPES_MIT.TXT>MIME-TYPES_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>mime-types</td> <td>1.0.0</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=MIME-TYPES_MIT.TXT>MIME-TYPES_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>minimatch</td> <td>3.0.2</td> <td>http:&#x2F;&#x2F;www.isc.org&#x2F;software&#x2F;license</td> <td><a href=MINIMATCH_ISC.TXT>MINIMATCH_ISC.TXT</a></td> </tr> <tr> <td>N/A</td> <td>minimatch</td> <td>3.0.4</td> <td>http:&#x2F;&#x2F;www.isc.org&#x2F;software&#x2F;license</td> <td><a href=MINIMATCH_ISC.TXT>MINIMATCH_ISC.TXT</a></td> </tr> <tr> <td>N/A</td> <td>minimist</td> <td>0.0.8</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=MINIMIST_MIT.TXT>MINIMIST_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>mkdirp</td> <td>0.5.1</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=MKDIRP_MIT.TXT>MKDIRP_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>moment</td> <td>2.13.0</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=MOMENT_MIT.TXT>MOMENT_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>moment</td> <td>2.18.1</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=MOMENT_MIT.TXT>MOMENT_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>mongodb</td> <td>3.0.5</td> <td>http:&#x2F;&#x2F;www.apache.org&#x2F;licenses&#x2F;LICENSE-2.0</td> <td><a href=MONGODB_APACHE-2.0.TXT>MONGODB_APACHE-2.0.TXT</a></td> </tr> <tr> <td>N/A</td> <td>mongodb</td> <td>2.1.18</td> <td>http:&#x2F;&#x2F;www.apache.org&#x2F;licenses&#x2F;LICENSE-2.0</td> <td><a href=MONGODB_APACHE-2.0.TXT>MONGODB_APACHE-2.0.TXT</a></td> </tr> <tr> <td>N/A</td> <td>mongodb-core</td> <td>1.3.18</td> <td>http:&#x2F;&#x2F;www.apache.org&#x2F;licenses&#x2F;LICENSE-2.0</td> <td><a href=MONGODB-CORE_APACHE-2.0.TXT>MONGODB-CORE_APACHE-2.0.TXT</a></td> </tr> <tr> <td>N/A</td> <td>mongodb-core</td> <td>3.0.5</td> <td>http:&#x2F;&#x2F;www.apache.org&#x2F;licenses&#x2F;LICENSE-2.0</td> <td><a href=MONGODB-CORE_APACHE-2.0.TXT>MONGODB-CORE_APACHE-2.0.TXT</a></td> </tr> <tr> <td>N/A</td> <td>mongodb-lock</td> <td>0.4.0</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=MONGODB-LOCK_MIT.TXT>MONGODB-LOCK_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>mongodb-uri</td> <td>0.9.7</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=MONGODB-URI_MIT.TXT>MONGODB-URI_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>ms</td> <td>2.0.0</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=MS_MIT.TXT>MS_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>multer</td> <td>1.3.0</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=MULTER_MIT.TXT>MULTER_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>mv</td> <td>2.1.1</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=MV_MIT.TXT>MV_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>nan</td> <td>2.3.5</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=NAN_MIT.TXT>NAN_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>nan</td> <td>2.7.0</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=NAN_MIT.TXT>NAN_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>ncp</td> <td>2.0.0</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=NCP_MIT.TXT>NCP_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>negotiator</td> <td>0.6.1</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=NEGOTIATOR_MIT.TXT>NEGOTIATOR_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>negotiator</td> <td>0.3.0</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=NEGOTIATOR_MIT.TXT>NEGOTIATOR_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>node-rsa</td> <td>0.3.2</td> <td>UNKNOWN</td> <td><a href=#>No local license could be found for the dependency</a></td> </tr> <tr> <td>N/A</td> <td>node-uuid</td> <td>1.4.7</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=NODE-UUID_MIT.TXT>NODE-UUID_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>normalize-path</td> <td>2.1.1</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=NORMALIZE-PATH_MIT.TXT>NORMALIZE-PATH_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>oauth-sign</td> <td>0.8.2</td> <td>http:&#x2F;&#x2F;www.apache.org&#x2F;licenses&#x2F;LICENSE-2.0</td> <td><a href=OAUTH-SIGN_APACHE-2.0.TXT>OAUTH-SIGN_APACHE-2.0.TXT</a></td> </tr> <tr> <td>N/A</td> <td>object-assign</td> <td>3.0.0</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=OBJECT-ASSIGN_MIT.TXT>OBJECT-ASSIGN_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>on-finished</td> <td>2.3.0</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=ON-FINISHED_MIT.TXT>ON-FINISHED_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>once</td> <td>1.3.3</td> <td>http:&#x2F;&#x2F;www.isc.org&#x2F;software&#x2F;license</td> <td><a href=ONCE_ISC.TXT>ONCE_ISC.TXT</a></td> </tr> <tr> <td>N/A</td> <td>once</td> <td>1.4.0</td> <td>http:&#x2F;&#x2F;www.isc.org&#x2F;software&#x2F;license</td> <td><a href=ONCE_ISC.TXT>ONCE_ISC.TXT</a></td> </tr> <tr> <td>N/A</td> <td>optimist</td> <td>0.3.7</td> <td>UNKNOWN</td> <td><a href=OPTIMIST_MIT*.TXT>OPTIMIST_MIT*.TXT</a></td> </tr> <tr> <td>N/A</td> <td>optval</td> <td>1.0.1</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=OPTVAL_MIT.TXT>OPTVAL_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>parse-duration</td> <td>0.1.1</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=#>No local license could be found for the dependency</a></td> </tr> <tr> <td>N/A</td> <td>parseurl</td> <td>1.3.2</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=PARSEURL_MIT.TXT>PARSEURL_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>parseurl</td> <td>1.0.1</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=#>No local license could be found for the dependency</a></td> </tr> <tr> <td>N/A</td> <td>path-is-absolute</td> <td>1.0.1</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=PATH-IS-ABSOLUTE_MIT.TXT>PATH-IS-ABSOLUTE_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>path-is-absolute</td> <td>1.0.0</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=PATH-IS-ABSOLUTE_MIT.TXT>PATH-IS-ABSOLUTE_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>path-to-regexp</td> <td>0.1.2</td> <td>UNKNOWN</td> <td><a href=#>No local license could be found for the dependency</a></td> </tr> <tr> <td>N/A</td> <td>path-to-regexp</td> <td>0.1.7</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=PATH-TO-REGEXP_MIT.TXT>PATH-TO-REGEXP_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>performance-now</td> <td>2.1.0</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=PERFORMANCE-NOW_MIT.TXT>PERFORMANCE-NOW_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>performance-now</td> <td>0.2.0</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=PERFORMANCE-NOW_MIT.TXT>PERFORMANCE-NOW_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>pinkie</td> <td>2.0.4</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=PINKIE_MIT.TXT>PINKIE_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>pinkie-promise</td> <td>2.0.1</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=PINKIE-PROMISE_MIT.TXT>PINKIE-PROMISE_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>precond</td> <td>0.2.3</td> <td>UNKNOWN</td> <td><a href=#>No local license could be found for the dependency</a></td> </tr> <tr> <td>N/A</td> <td>process-nextick-args</td> <td>1.0.7</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=PROCESS-NEXTICK-ARGS_MIT.TXT>PROCESS-NEXTICK-ARGS_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>proxy-addr</td> <td>2.0.2</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=PROXY-ADDR_MIT.TXT>PROXY-ADDR_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>punycode</td> <td>1.4.1</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=#>No local license could be found for the dependency</a></td> </tr> <tr> <td>N/A</td> <td>qs</td> <td>0.6.6</td> <td>UNKNOWN</td> <td><a href=#>No local license could be found for the dependency</a></td> </tr> <tr> <td>N/A</td> <td>qs</td> <td>6.3.2</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;BSD-3-Clause</td> <td><a href=QS_BSD-3-CLAUSE.TXT>QS_BSD-3-CLAUSE.TXT</a></td> </tr> <tr> <td>N/A</td> <td>qs</td> <td>6.4.0</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;BSD-3-Clause</td> <td><a href=QS_BSD-3-CLAUSE.TXT>QS_BSD-3-CLAUSE.TXT</a></td> </tr> <tr> <td>N/A</td> <td>qs</td> <td>6.5.1</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;BSD-3-Clause</td> <td><a href=QS_BSD-3-CLAUSE.TXT>QS_BSD-3-CLAUSE.TXT</a></td> </tr> <tr> <td>N/A</td> <td>range-parser</td> <td>0.0.4</td> <td>UNKNOWN</td> <td><a href=#>No local license could be found for the dependency</a></td> </tr> <tr> <td>N/A</td> <td>range-parser</td> <td>1.0.0</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=#>No local license could be found for the dependency</a></td> </tr> <tr> <td>N/A</td> <td>range-parser</td> <td>1.2.0</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=RANGE-PARSER_MIT.TXT>RANGE-PARSER_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>raw-body</td> <td>2.3.2</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=RAW-BODY_MIT.TXT>RAW-BODY_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>raw-body</td> <td>1.1.7</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=#>No local license could be found for the dependency</a></td> </tr> <tr> <td>N/A</td> <td>rc</td> <td>0.1.1</td> <td>UNKNOWN</td> <td><a href=#>No local license could be found for the dependency</a></td> </tr> <tr> <td>N/A</td> <td>readable-stream</td> <td>2.3.3</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=READABLE-STREAM_MIT.TXT>READABLE-STREAM_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>readable-stream</td> <td>1.0.31</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=READABLE-STREAM_MIT.TXT>READABLE-STREAM_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>readable-stream</td> <td>1.1.14</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=READABLE-STREAM_MIT.TXT>READABLE-STREAM_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>redis</td> <td>2.6.5</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=REDIS_MIT.TXT>REDIS_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>redis</td> <td>2.8.0</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=REDIS_MIT.TXT>REDIS_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>redis-commands</td> <td>1.3.4</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=REDIS-COMMANDS_MIT.TXT>REDIS-COMMANDS_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>redis-parser</td> <td>2.6.0</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=REDIS-PARSER_MIT.TXT>REDIS-PARSER_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>remove-trailing-separator</td> <td>1.1.0</td> <td>http:&#x2F;&#x2F;www.isc.org&#x2F;software&#x2F;license</td> <td><a href=REMOVE-TRAILING-SEPARATOR_ISC.TXT>REMOVE-TRAILING-SEPARATOR_ISC.TXT</a></td> </tr> <tr> <td>N/A</td> <td>request</td> <td>2.83.0</td> <td>http:&#x2F;&#x2F;www.apache.org&#x2F;licenses&#x2F;LICENSE-2.0</td> <td><a href=REQUEST_APACHE-2.0.TXT>REQUEST_APACHE-2.0.TXT</a></td> </tr> <tr> <td>N/A</td> <td>request</td> <td>2.79.0</td> <td>http:&#x2F;&#x2F;www.apache.org&#x2F;licenses&#x2F;LICENSE-2.0</td> <td><a href=REQUEST_APACHE-2.0.TXT>REQUEST_APACHE-2.0.TXT</a></td> </tr> <tr> <td>N/A</td> <td>request</td> <td>2.81.0</td> <td>http:&#x2F;&#x2F;www.apache.org&#x2F;licenses&#x2F;LICENSE-2.0</td> <td><a href=REQUEST_APACHE-2.0.TXT>REQUEST_APACHE-2.0.TXT</a></td> </tr> <tr> <td>N/A</td> <td>require_optional</td> <td>1.0.1</td> <td>http:&#x2F;&#x2F;www.apache.org&#x2F;licenses&#x2F;LICENSE-2.0</td> <td><a href=REQUIRE_OPTIONAL_APACHE-2.0.TXT>REQUIRE_OPTIONAL_APACHE-2.0.TXT</a></td> </tr> <tr> <td>N/A</td> <td>resolve-from</td> <td>2.0.0</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=RESOLVE-FROM_MIT.TXT>RESOLVE-FROM_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>retry</td> <td>0.6.0</td> <td>UNKNOWN</td> <td><a href=RETRY_MIT*.TXT>RETRY_MIT*.TXT</a></td> </tr> <tr> <td>N/A</td> <td>rimraf</td> <td>2.4.5</td> <td>http:&#x2F;&#x2F;www.isc.org&#x2F;software&#x2F;license</td> <td><a href=RIMRAF_ISC.TXT>RIMRAF_ISC.TXT</a></td> </tr> <tr> <td>N/A</td> <td>safe-buffer</td> <td>5.1.1</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=SAFE-BUFFER_MIT.TXT>SAFE-BUFFER_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>safe-buffer</td> <td>5.0.1</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=SAFE-BUFFER_MIT.TXT>SAFE-BUFFER_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>safe-json-stringify</td> <td>1.0.4</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=#>No local license could be found for the dependency</a></td> </tr> <tr> <td>N/A</td> <td>safe-json-stringify</td> <td>1.0.3</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=#>No local license could be found for the dependency</a></td> </tr> <tr> <td>N/A</td> <td>semver</td> <td>5.5.0</td> <td>http:&#x2F;&#x2F;www.isc.org&#x2F;software&#x2F;license</td> <td><a href=SEMVER_ISC.TXT>SEMVER_ISC.TXT</a></td> </tr> <tr> <td>N/A</td> <td>semver</td> <td>5.4.1</td> <td>http:&#x2F;&#x2F;www.isc.org&#x2F;software&#x2F;license</td> <td><a href=SEMVER_ISC.TXT>SEMVER_ISC.TXT</a></td> </tr> <tr> <td>N/A</td> <td>send</td> <td>0.1.4</td> <td>UNKNOWN</td> <td><a href=#>No local license could be found for the dependency</a></td> </tr> <tr> <td>N/A</td> <td>send</td> <td>0.16.0</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=SEND_MIT.TXT>SEND_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>send</td> <td>0.2.0</td> <td>UNKNOWN</td> <td><a href=#>No local license could be found for the dependency</a></td> </tr> <tr> <td>N/A</td> <td>serve-static</td> <td>1.0.1</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=SERVE-STATIC_MIT.TXT>SERVE-STATIC_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>serve-static</td> <td>1.13.0</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=SERVE-STATIC_MIT.TXT>SERVE-STATIC_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>setprototypeof</td> <td>1.0.3</td> <td>http:&#x2F;&#x2F;www.isc.org&#x2F;software&#x2F;license</td> <td><a href=SETPROTOTYPEOF_ISC.TXT>SETPROTOTYPEOF_ISC.TXT</a></td> </tr> <tr> <td>N/A</td> <td>setprototypeof</td> <td>1.1.0</td> <td>http:&#x2F;&#x2F;www.isc.org&#x2F;software&#x2F;license</td> <td><a href=SETPROTOTYPEOF_ISC.TXT>SETPROTOTYPEOF_ISC.TXT</a></td> </tr> <tr> <td>N/A</td> <td>shimmer</td> <td>1.0.0</td> <td>UNKNOWN</td> <td><a href=#>No local license could be found for the dependency</a></td> </tr> <tr> <td>N/A</td> <td>simple-lru-cache</td> <td>0.0.2</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=SIMPLE-LRU-CACHE_MIT.TXT>SIMPLE-LRU-CACHE_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>sntp</td> <td>1.0.9</td> <td>UNKNOWN</td> <td><a href=SNTP_BSD.TXT>SNTP_BSD.TXT</a></td> </tr> <tr> <td>N/A</td> <td>sntp</td> <td>2.1.0</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;BSD-3-Clause</td> <td><a href=SNTP_BSD-3-CLAUSE.TXT>SNTP_BSD-3-CLAUSE.TXT</a></td> </tr> <tr> <td>N/A</td> <td>sshpk</td> <td>1.11.0</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=SSHPK_MIT.TXT>SSHPK_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>sshpk</td> <td>1.13.1</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=SSHPK_MIT.TXT>SSHPK_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>sshpk</td> <td>1.14.1</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=SSHPK_MIT.TXT>SSHPK_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>statuses</td> <td>1.3.1</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=STATUSES_MIT.TXT>STATUSES_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>stream-buffers</td> <td>3.0.0</td> <td>http:&#x2F;&#x2F;unlicense.org&#x2F;</td> <td><a href=#>No local license could be found for the dependency</a></td> </tr> <tr> <td>N/A</td> <td>streamsearch</td> <td>0.1.2</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=STREAMSEARCH_MIT.TXT>STREAMSEARCH_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>string_decoder</td> <td>0.10.31</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=STRING_DECODER_MIT.TXT>STRING_DECODER_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>string_decoder</td> <td>1.0.3</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=STRING_DECODER_MIT.TXT>STRING_DECODER_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>stringstream</td> <td>0.0.5</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=STRINGSTREAM_MIT.TXT>STRINGSTREAM_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>strip-ansi</td> <td>3.0.1</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=STRIP-ANSI_MIT.TXT>STRIP-ANSI_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>supports-color</td> <td>2.0.0</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=SUPPORTS-COLOR_MIT.TXT>SUPPORTS-COLOR_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>tar-stream</td> <td>1.5.4</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=TAR-STREAM_MIT.TXT>TAR-STREAM_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>tough-cookie</td> <td>2.3.4</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;BSD-3-Clause</td> <td><a href=TOUGH-COOKIE_BSD-3-CLAUSE.TXT>TOUGH-COOKIE_BSD-3-CLAUSE.TXT</a></td> </tr> <tr> <td>N/A</td> <td>tough-cookie</td> <td>2.3.2</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;BSD-3-Clause</td> <td><a href=TOUGH-COOKIE_BSD-3-CLAUSE.TXT>TOUGH-COOKIE_BSD-3-CLAUSE.TXT</a></td> </tr> <tr> <td>N/A</td> <td>tunnel-agent</td> <td>0.6.0</td> <td>http:&#x2F;&#x2F;www.apache.org&#x2F;licenses&#x2F;LICENSE-2.0</td> <td><a href=TUNNEL-AGENT_APACHE-2.0.TXT>TUNNEL-AGENT_APACHE-2.0.TXT</a></td> </tr> <tr> <td>N/A</td> <td>tunnel-agent</td> <td>0.4.3</td> <td>http:&#x2F;&#x2F;www.apache.org&#x2F;licenses&#x2F;LICENSE-2.0</td> <td><a href=TUNNEL-AGENT_APACHE-2.0.TXT>TUNNEL-AGENT_APACHE-2.0.TXT</a></td> </tr> <tr> <td>N/A</td> <td>tweetnacl</td> <td>0.14.5</td> <td>http:&#x2F;&#x2F;unlicense.org&#x2F;</td> <td><a href=TWEETNACL_UNLICENSE.TXT>TWEETNACL_UNLICENSE.TXT</a></td> </tr> <tr> <td>N/A</td> <td>type-is</td> <td>1.0.0</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=#>No local license could be found for the dependency</a></td> </tr> <tr> <td>N/A</td> <td>type-is</td> <td>1.1.0</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=#>No local license could be found for the dependency</a></td> </tr> <tr> <td>N/A</td> <td>type-is</td> <td>1.2.2</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=#>No local license could be found for the dependency</a></td> </tr> <tr> <td>N/A</td> <td>type-is</td> <td>1.6.15</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=TYPE-IS_MIT.TXT>TYPE-IS_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>typedarray</td> <td>0.0.6</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=TYPEDARRAY_MIT.TXT>TYPEDARRAY_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>underscore</td> <td>1.5.1</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=UNDERSCORE_MIT.TXT>UNDERSCORE_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>underscore</td> <td>1.8.3</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=UNDERSCORE_MIT.TXT>UNDERSCORE_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>underscore</td> <td>1.7.0</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=UNDERSCORE_MIT.TXT>UNDERSCORE_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>unifiedpush-node-sender</td> <td>0.12.1</td> <td>http:&#x2F;&#x2F;www.apache.org&#x2F;licenses&#x2F;LICENSE-2.0</td> <td><a href=#>No local license could be found for the dependency</a></td> </tr> <tr> <td>N/A</td> <td>unpipe</td> <td>1.0.0</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=UNPIPE_MIT.TXT>UNPIPE_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>util-deprecate</td> <td>1.0.2</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=UTIL-DEPRECATE_MIT.TXT>UTIL-DEPRECATE_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>utils-merge</td> <td>1.0.0</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=UTILS-MERGE_MIT.TXT>UTILS-MERGE_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>utils-merge</td> <td>1.0.1</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=UTILS-MERGE_MIT.TXT>UTILS-MERGE_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>uuid</td> <td>3.0.1</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=UUID_MIT.TXT>UUID_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>uuid</td> <td>3.2.1</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=UUID_MIT.TXT>UUID_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>vary</td> <td>1.1.2</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=VARY_MIT.TXT>VARY_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>verror</td> <td>1.10.0</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=VERROR_MIT.TXT>VERROR_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>verror</td> <td>1.3.6</td> <td>UNKNOWN</td> <td><a href=VERROR_MIT*.TXT>VERROR_MIT*.TXT</a></td> </tr> <tr> <td>N/A</td> <td>verror</td> <td>1.6.1</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=VERROR_MIT.TXT>VERROR_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>wordwrap</td> <td>0.0.3</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=WORDWRAP_MIT.TXT>WORDWRAP_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>wrappy</td> <td>1.0.2</td> <td>http:&#x2F;&#x2F;www.isc.org&#x2F;software&#x2F;license</td> <td><a href=WRAPPY_ISC.TXT>WRAPPY_ISC.TXT</a></td> </tr> <tr> <td>N/A</td> <td>xtend</td> <td>4.0.1</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=XTEND_MIT.TXT>XTEND_MIT.TXT</a></td> </tr> <tr> <td>N/A</td> <td>zip-stream</td> <td>1.2.0</td> <td>http:&#x2F;&#x2F;www.opensource.org&#x2F;licenses&#x2F;MIT</td> <td><a href=ZIP-STREAM_MIT.TXT>ZIP-STREAM_MIT.TXT</a></td> </tr> </table> </body> </html>
Java
export const removeWeight = (element) => { try { element.removeAttribute('data-weight'); } catch (e) { // We are now in IE11 territory if (!!element) { element.setAttribute('data-weight', null); } } };
Java
using MO.Core.Forms.Common; using System; using System.ComponentModel; using System.Drawing; using System.Windows.Forms; namespace MO.Core.Forms.Controls { //============================================================ // <T>颜色选取控件<T> //============================================================ public partial class QColorPicker : QControl { // 最大高度 protected int _heighMax = 20; // 颜色宽度 protected int _colorWidth = 18; // 颜色 protected Color _selectColor = Color.Black; //============================================================ // <T>构造颜色选取控件<T> //============================================================ public QColorPicker() { InitializeComponent(); } //============================================================ // <T>设置颜色<T> //============================================================ protected void InnerSetSize(int width, int height) { // 设置尺寸 Width = width; Height = height = _heighMax; // 设置信息 int contentLeft = _borderOuter.Left.Width + _borderInner.Left.Width; int contentRight = _borderOuter.Bottom.Width + _borderInner.Bottom.Width; int contentTop = _borderOuter.Top.Width + _borderInner.Top.Width; int contentBottom = _borderOuter.Bottom.Width + _borderInner.Bottom.Width; // 设置容器 pnlContanier.SetBounds( contentLeft, contentTop, width - contentLeft - contentRight, height - contentTop - contentBottom); // 设置内容框 txtValue.SetBounds( contentLeft, contentTop, width - _colorWidth - contentLeft - contentRight - 2, height - contentTop - contentBottom); // 设置颜色框 pnlColor.SetBounds( width - _colorWidth - contentLeft - contentRight, contentTop - 2, _colorWidth, height - contentTop - contentBottom); Invalidate(); } //============================================================ // <T>大小</T> //============================================================ [Browsable(true)] public new Size Size { get { return base.Size; } set { InnerSetSize(value.Width, value.Height); } } //============================================================ // <T>刷新颜色处理。</T> //============================================================ public void RefreshColor(){ pnlColor.BackColor = _selectColor; txtValue.Text = RColor.FormatHex(_selectColor.ToArgb()); } //============================================================ // <T>获取或获得选中颜色。</T> //============================================================ [Browsable(true)] [DefaultValue(typeof(Color), "Color.Black")] public Color SelectColor { get { return _selectColor; } set { _selectColor = value; RefreshColor(); } } //============================================================ // <T>获取或获得选中颜色文本。</T> //============================================================ [Browsable(true)] [DefaultValue("FF000000")] public string SelectColorText { get { return RColor.FormatHex(_selectColor.ToArgb()); } set { _selectColor = RColor.ParseHexColor(value); RefreshColor(); } } //============================================================ // <T>获取或获得选中颜色内容。</T> //============================================================ [Browsable(true)] [DefaultValue(-16777216)] public int SelectColorValue { get { return _selectColor.ToArgb(); } set { _selectColor = Color.FromArgb(value); RefreshColor(); } } //============================================================ // <T>调整下拉框的高度</T> //============================================================ private void QColorPicker_Resize(object sender, EventArgs e) { InnerSetSize(Width, Height); } //============================================================ // <T>鼠标点击事件处理。</T> //============================================================ private void pnlColor_Click(object sender, EventArgs e) { dlgColor.Color = _selectColor; DialogResult resultCd = dlgColor.ShowDialog(); if (resultCd == DialogResult.OK) { _selectColor = dlgColor.Color; RefreshColor(); } } //============================================================ // <T>文本变更。</T> //============================================================ private void txtValue_Leave(object sender, EventArgs e) { _selectColor = RColor.ParseHexColor(txtValue.Text); RefreshColor(); } } }
Java
/** * Copyright (C) 2015 The Gravitee team (http://gravitee.io) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.gravitee.gateway.services.sync.cache; import com.hazelcast.core.HazelcastInstance; import org.springframework.beans.factory.annotation.Autowired; import java.util.Map; /** * @author David BRASSELY (david.brassely at graviteesource.com) * @author GraviteeSource Team */ public final class CacheManager { @Autowired private HazelcastInstance hzInstance; public <K, V> Map<K, V> getCache(String name) { return hzInstance.getMap(name); } }
Java
/* * Copyright 2017 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <folly/detail/CacheLocality.h> #include <folly/portability/GTest.h> #include <sched.h> #include <memory> #include <thread> #include <type_traits> #include <unordered_map> #include <glog/logging.h> using namespace folly::detail; /// This is the relevant nodes from a production box's sysfs tree. If you /// think this map is ugly you should see the version of this test that /// used a real directory tree. To reduce the chance of testing error /// I haven't tried to remove the common prefix static std::unordered_map<std::string, std::string> fakeSysfsTree = { {"/sys/devices/system/cpu/cpu0/cache/index0/shared_cpu_list", "0,17"}, {"/sys/devices/system/cpu/cpu0/cache/index0/type", "Data"}, {"/sys/devices/system/cpu/cpu0/cache/index1/shared_cpu_list", "0,17"}, {"/sys/devices/system/cpu/cpu0/cache/index1/type", "Instruction"}, {"/sys/devices/system/cpu/cpu0/cache/index2/shared_cpu_list", "0,17"}, {"/sys/devices/system/cpu/cpu0/cache/index2/type", "Unified"}, {"/sys/devices/system/cpu/cpu0/cache/index3/shared_cpu_list", "0-8,17-23"}, {"/sys/devices/system/cpu/cpu0/cache/index3/type", "Unified"}, {"/sys/devices/system/cpu/cpu1/cache/index0/shared_cpu_list", "1,18"}, {"/sys/devices/system/cpu/cpu1/cache/index0/type", "Data"}, {"/sys/devices/system/cpu/cpu1/cache/index1/shared_cpu_list", "1,18"}, {"/sys/devices/system/cpu/cpu1/cache/index1/type", "Instruction"}, {"/sys/devices/system/cpu/cpu1/cache/index2/shared_cpu_list", "1,18"}, {"/sys/devices/system/cpu/cpu1/cache/index2/type", "Unified"}, {"/sys/devices/system/cpu/cpu1/cache/index3/shared_cpu_list", "0-8,17-23"}, {"/sys/devices/system/cpu/cpu1/cache/index3/type", "Unified"}, {"/sys/devices/system/cpu/cpu2/cache/index0/shared_cpu_list", "2,19"}, {"/sys/devices/system/cpu/cpu2/cache/index0/type", "Data"}, {"/sys/devices/system/cpu/cpu2/cache/index1/shared_cpu_list", "2,19"}, {"/sys/devices/system/cpu/cpu2/cache/index1/type", "Instruction"}, {"/sys/devices/system/cpu/cpu2/cache/index2/shared_cpu_list", "2,19"}, {"/sys/devices/system/cpu/cpu2/cache/index2/type", "Unified"}, {"/sys/devices/system/cpu/cpu2/cache/index3/shared_cpu_list", "0-8,17-23"}, {"/sys/devices/system/cpu/cpu2/cache/index3/type", "Unified"}, {"/sys/devices/system/cpu/cpu3/cache/index0/shared_cpu_list", "3,20"}, {"/sys/devices/system/cpu/cpu3/cache/index0/type", "Data"}, {"/sys/devices/system/cpu/cpu3/cache/index1/shared_cpu_list", "3,20"}, {"/sys/devices/system/cpu/cpu3/cache/index1/type", "Instruction"}, {"/sys/devices/system/cpu/cpu3/cache/index2/shared_cpu_list", "3,20"}, {"/sys/devices/system/cpu/cpu3/cache/index2/type", "Unified"}, {"/sys/devices/system/cpu/cpu3/cache/index3/shared_cpu_list", "0-8,17-23"}, {"/sys/devices/system/cpu/cpu3/cache/index3/type", "Unified"}, {"/sys/devices/system/cpu/cpu4/cache/index0/shared_cpu_list", "4,21"}, {"/sys/devices/system/cpu/cpu4/cache/index0/type", "Data"}, {"/sys/devices/system/cpu/cpu4/cache/index1/shared_cpu_list", "4,21"}, {"/sys/devices/system/cpu/cpu4/cache/index1/type", "Instruction"}, {"/sys/devices/system/cpu/cpu4/cache/index2/shared_cpu_list", "4,21"}, {"/sys/devices/system/cpu/cpu4/cache/index2/type", "Unified"}, {"/sys/devices/system/cpu/cpu4/cache/index3/shared_cpu_list", "0-8,17-23"}, {"/sys/devices/system/cpu/cpu4/cache/index3/type", "Unified"}, {"/sys/devices/system/cpu/cpu5/cache/index0/shared_cpu_list", "5-6"}, {"/sys/devices/system/cpu/cpu5/cache/index0/type", "Data"}, {"/sys/devices/system/cpu/cpu5/cache/index1/shared_cpu_list", "5-6"}, {"/sys/devices/system/cpu/cpu5/cache/index1/type", "Instruction"}, {"/sys/devices/system/cpu/cpu5/cache/index2/shared_cpu_list", "5-6"}, {"/sys/devices/system/cpu/cpu5/cache/index2/type", "Unified"}, {"/sys/devices/system/cpu/cpu5/cache/index3/shared_cpu_list", "0-8,17-23"}, {"/sys/devices/system/cpu/cpu5/cache/index3/type", "Unified"}, {"/sys/devices/system/cpu/cpu6/cache/index0/shared_cpu_list", "5-6"}, {"/sys/devices/system/cpu/cpu6/cache/index0/type", "Data"}, {"/sys/devices/system/cpu/cpu6/cache/index1/shared_cpu_list", "5-6"}, {"/sys/devices/system/cpu/cpu6/cache/index1/type", "Instruction"}, {"/sys/devices/system/cpu/cpu6/cache/index2/shared_cpu_list", "5-6"}, {"/sys/devices/system/cpu/cpu6/cache/index2/type", "Unified"}, {"/sys/devices/system/cpu/cpu6/cache/index3/shared_cpu_list", "0-8,17-23"}, {"/sys/devices/system/cpu/cpu6/cache/index3/type", "Unified"}, {"/sys/devices/system/cpu/cpu7/cache/index0/shared_cpu_list", "7,22"}, {"/sys/devices/system/cpu/cpu7/cache/index0/type", "Data"}, {"/sys/devices/system/cpu/cpu7/cache/index1/shared_cpu_list", "7,22"}, {"/sys/devices/system/cpu/cpu7/cache/index1/type", "Instruction"}, {"/sys/devices/system/cpu/cpu7/cache/index2/shared_cpu_list", "7,22"}, {"/sys/devices/system/cpu/cpu7/cache/index2/type", "Unified"}, {"/sys/devices/system/cpu/cpu7/cache/index3/shared_cpu_list", "0-8,17-23"}, {"/sys/devices/system/cpu/cpu7/cache/index3/type", "Unified"}, {"/sys/devices/system/cpu/cpu8/cache/index0/shared_cpu_list", "8,23"}, {"/sys/devices/system/cpu/cpu8/cache/index0/type", "Data"}, {"/sys/devices/system/cpu/cpu8/cache/index1/shared_cpu_list", "8,23"}, {"/sys/devices/system/cpu/cpu8/cache/index1/type", "Instruction"}, {"/sys/devices/system/cpu/cpu8/cache/index2/shared_cpu_list", "8,23"}, {"/sys/devices/system/cpu/cpu8/cache/index2/type", "Unified"}, {"/sys/devices/system/cpu/cpu8/cache/index3/shared_cpu_list", "0-8,17-23"}, {"/sys/devices/system/cpu/cpu8/cache/index3/type", "Unified"}, {"/sys/devices/system/cpu/cpu9/cache/index0/shared_cpu_list", "9,24"}, {"/sys/devices/system/cpu/cpu9/cache/index0/type", "Data"}, {"/sys/devices/system/cpu/cpu9/cache/index1/shared_cpu_list", "9,24"}, {"/sys/devices/system/cpu/cpu9/cache/index1/type", "Instruction"}, {"/sys/devices/system/cpu/cpu9/cache/index2/shared_cpu_list", "9,24"}, {"/sys/devices/system/cpu/cpu9/cache/index2/type", "Unified"}, {"/sys/devices/system/cpu/cpu9/cache/index3/shared_cpu_list", "9-16,24-31"}, {"/sys/devices/system/cpu/cpu9/cache/index3/type", "Unified"}, {"/sys/devices/system/cpu/cpu10/cache/index0/shared_cpu_list", "10,25"}, {"/sys/devices/system/cpu/cpu10/cache/index0/type", "Data"}, {"/sys/devices/system/cpu/cpu10/cache/index1/shared_cpu_list", "10,25"}, {"/sys/devices/system/cpu/cpu10/cache/index1/type", "Instruction"}, {"/sys/devices/system/cpu/cpu10/cache/index2/shared_cpu_list", "10,25"}, {"/sys/devices/system/cpu/cpu10/cache/index2/type", "Unified"}, {"/sys/devices/system/cpu/cpu10/cache/index3/shared_cpu_list", "9-16,24-31"}, {"/sys/devices/system/cpu/cpu10/cache/index3/type", "Unified"}, {"/sys/devices/system/cpu/cpu11/cache/index0/shared_cpu_list", "11,26"}, {"/sys/devices/system/cpu/cpu11/cache/index0/type", "Data"}, {"/sys/devices/system/cpu/cpu11/cache/index1/shared_cpu_list", "11,26"}, {"/sys/devices/system/cpu/cpu11/cache/index1/type", "Instruction"}, {"/sys/devices/system/cpu/cpu11/cache/index2/shared_cpu_list", "11,26"}, {"/sys/devices/system/cpu/cpu11/cache/index2/type", "Unified"}, {"/sys/devices/system/cpu/cpu11/cache/index3/shared_cpu_list", "9-16,24-31"}, {"/sys/devices/system/cpu/cpu11/cache/index3/type", "Unified"}, {"/sys/devices/system/cpu/cpu12/cache/index0/shared_cpu_list", "12,27"}, {"/sys/devices/system/cpu/cpu12/cache/index0/type", "Data"}, {"/sys/devices/system/cpu/cpu12/cache/index1/shared_cpu_list", "12,27"}, {"/sys/devices/system/cpu/cpu12/cache/index1/type", "Instruction"}, {"/sys/devices/system/cpu/cpu12/cache/index2/shared_cpu_list", "12,27"}, {"/sys/devices/system/cpu/cpu12/cache/index2/type", "Unified"}, {"/sys/devices/system/cpu/cpu12/cache/index3/shared_cpu_list", "9-16,24-31"}, {"/sys/devices/system/cpu/cpu12/cache/index3/type", "Unified"}, {"/sys/devices/system/cpu/cpu13/cache/index0/shared_cpu_list", "13,28"}, {"/sys/devices/system/cpu/cpu13/cache/index0/type", "Data"}, {"/sys/devices/system/cpu/cpu13/cache/index1/shared_cpu_list", "13,28"}, {"/sys/devices/system/cpu/cpu13/cache/index1/type", "Instruction"}, {"/sys/devices/system/cpu/cpu13/cache/index2/shared_cpu_list", "13,28"}, {"/sys/devices/system/cpu/cpu13/cache/index2/type", "Unified"}, {"/sys/devices/system/cpu/cpu13/cache/index3/shared_cpu_list", "9-16,24-31"}, {"/sys/devices/system/cpu/cpu13/cache/index3/type", "Unified"}, {"/sys/devices/system/cpu/cpu14/cache/index0/shared_cpu_list", "14,29"}, {"/sys/devices/system/cpu/cpu14/cache/index0/type", "Data"}, {"/sys/devices/system/cpu/cpu14/cache/index1/shared_cpu_list", "14,29"}, {"/sys/devices/system/cpu/cpu14/cache/index1/type", "Instruction"}, {"/sys/devices/system/cpu/cpu14/cache/index2/shared_cpu_list", "14,29"}, {"/sys/devices/system/cpu/cpu14/cache/index2/type", "Unified"}, {"/sys/devices/system/cpu/cpu14/cache/index3/shared_cpu_list", "9-16,24-31"}, {"/sys/devices/system/cpu/cpu14/cache/index3/type", "Unified"}, {"/sys/devices/system/cpu/cpu15/cache/index0/shared_cpu_list", "15,30"}, {"/sys/devices/system/cpu/cpu15/cache/index0/type", "Data"}, {"/sys/devices/system/cpu/cpu15/cache/index1/shared_cpu_list", "15,30"}, {"/sys/devices/system/cpu/cpu15/cache/index1/type", "Instruction"}, {"/sys/devices/system/cpu/cpu15/cache/index2/shared_cpu_list", "15,30"}, {"/sys/devices/system/cpu/cpu15/cache/index2/type", "Unified"}, {"/sys/devices/system/cpu/cpu15/cache/index3/shared_cpu_list", "9-16,24-31"}, {"/sys/devices/system/cpu/cpu15/cache/index3/type", "Unified"}, {"/sys/devices/system/cpu/cpu16/cache/index0/shared_cpu_list", "16,31"}, {"/sys/devices/system/cpu/cpu16/cache/index0/type", "Data"}, {"/sys/devices/system/cpu/cpu16/cache/index1/shared_cpu_list", "16,31"}, {"/sys/devices/system/cpu/cpu16/cache/index1/type", "Instruction"}, {"/sys/devices/system/cpu/cpu16/cache/index2/shared_cpu_list", "16,31"}, {"/sys/devices/system/cpu/cpu16/cache/index2/type", "Unified"}, {"/sys/devices/system/cpu/cpu16/cache/index3/shared_cpu_list", "9-16,24-31"}, {"/sys/devices/system/cpu/cpu16/cache/index3/type", "Unified"}, {"/sys/devices/system/cpu/cpu17/cache/index0/shared_cpu_list", "0,17"}, {"/sys/devices/system/cpu/cpu17/cache/index0/type", "Data"}, {"/sys/devices/system/cpu/cpu17/cache/index1/shared_cpu_list", "0,17"}, {"/sys/devices/system/cpu/cpu17/cache/index1/type", "Instruction"}, {"/sys/devices/system/cpu/cpu17/cache/index2/shared_cpu_list", "0,17"}, {"/sys/devices/system/cpu/cpu17/cache/index2/type", "Unified"}, {"/sys/devices/system/cpu/cpu17/cache/index3/shared_cpu_list", "0-8,17-23"}, {"/sys/devices/system/cpu/cpu17/cache/index3/type", "Unified"}, {"/sys/devices/system/cpu/cpu18/cache/index0/shared_cpu_list", "1,18"}, {"/sys/devices/system/cpu/cpu18/cache/index0/type", "Data"}, {"/sys/devices/system/cpu/cpu18/cache/index1/shared_cpu_list", "1,18"}, {"/sys/devices/system/cpu/cpu18/cache/index1/type", "Instruction"}, {"/sys/devices/system/cpu/cpu18/cache/index2/shared_cpu_list", "1,18"}, {"/sys/devices/system/cpu/cpu18/cache/index2/type", "Unified"}, {"/sys/devices/system/cpu/cpu18/cache/index3/shared_cpu_list", "0-8,17-23"}, {"/sys/devices/system/cpu/cpu18/cache/index3/type", "Unified"}, {"/sys/devices/system/cpu/cpu19/cache/index0/shared_cpu_list", "2,19"}, {"/sys/devices/system/cpu/cpu19/cache/index0/type", "Data"}, {"/sys/devices/system/cpu/cpu19/cache/index1/shared_cpu_list", "2,19"}, {"/sys/devices/system/cpu/cpu19/cache/index1/type", "Instruction"}, {"/sys/devices/system/cpu/cpu19/cache/index2/shared_cpu_list", "2,19"}, {"/sys/devices/system/cpu/cpu19/cache/index2/type", "Unified"}, {"/sys/devices/system/cpu/cpu19/cache/index3/shared_cpu_list", "0-8,17-23"}, {"/sys/devices/system/cpu/cpu19/cache/index3/type", "Unified"}, {"/sys/devices/system/cpu/cpu20/cache/index0/shared_cpu_list", "3,20"}, {"/sys/devices/system/cpu/cpu20/cache/index0/type", "Data"}, {"/sys/devices/system/cpu/cpu20/cache/index1/shared_cpu_list", "3,20"}, {"/sys/devices/system/cpu/cpu20/cache/index1/type", "Instruction"}, {"/sys/devices/system/cpu/cpu20/cache/index2/shared_cpu_list", "3,20"}, {"/sys/devices/system/cpu/cpu20/cache/index2/type", "Unified"}, {"/sys/devices/system/cpu/cpu20/cache/index3/shared_cpu_list", "0-8,17-23"}, {"/sys/devices/system/cpu/cpu20/cache/index3/type", "Unified"}, {"/sys/devices/system/cpu/cpu21/cache/index0/shared_cpu_list", "4,21"}, {"/sys/devices/system/cpu/cpu21/cache/index0/type", "Data"}, {"/sys/devices/system/cpu/cpu21/cache/index1/shared_cpu_list", "4,21"}, {"/sys/devices/system/cpu/cpu21/cache/index1/type", "Instruction"}, {"/sys/devices/system/cpu/cpu21/cache/index2/shared_cpu_list", "4,21"}, {"/sys/devices/system/cpu/cpu21/cache/index2/type", "Unified"}, {"/sys/devices/system/cpu/cpu21/cache/index3/shared_cpu_list", "0-8,17-23"}, {"/sys/devices/system/cpu/cpu21/cache/index3/type", "Unified"}, {"/sys/devices/system/cpu/cpu22/cache/index0/shared_cpu_list", "7,22"}, {"/sys/devices/system/cpu/cpu22/cache/index0/type", "Data"}, {"/sys/devices/system/cpu/cpu22/cache/index1/shared_cpu_list", "7,22"}, {"/sys/devices/system/cpu/cpu22/cache/index1/type", "Instruction"}, {"/sys/devices/system/cpu/cpu22/cache/index2/shared_cpu_list", "7,22"}, {"/sys/devices/system/cpu/cpu22/cache/index2/type", "Unified"}, {"/sys/devices/system/cpu/cpu22/cache/index3/shared_cpu_list", "0-8,17-23"}, {"/sys/devices/system/cpu/cpu22/cache/index3/type", "Unified"}, {"/sys/devices/system/cpu/cpu23/cache/index0/shared_cpu_list", "8,23"}, {"/sys/devices/system/cpu/cpu23/cache/index0/type", "Data"}, {"/sys/devices/system/cpu/cpu23/cache/index1/shared_cpu_list", "8,23"}, {"/sys/devices/system/cpu/cpu23/cache/index1/type", "Instruction"}, {"/sys/devices/system/cpu/cpu23/cache/index2/shared_cpu_list", "8,23"}, {"/sys/devices/system/cpu/cpu23/cache/index2/type", "Unified"}, {"/sys/devices/system/cpu/cpu23/cache/index3/shared_cpu_list", "0-8,17-23"}, {"/sys/devices/system/cpu/cpu23/cache/index3/type", "Unified"}, {"/sys/devices/system/cpu/cpu24/cache/index0/shared_cpu_list", "9,24"}, {"/sys/devices/system/cpu/cpu24/cache/index0/type", "Data"}, {"/sys/devices/system/cpu/cpu24/cache/index1/shared_cpu_list", "9,24"}, {"/sys/devices/system/cpu/cpu24/cache/index1/type", "Instruction"}, {"/sys/devices/system/cpu/cpu24/cache/index2/shared_cpu_list", "9,24"}, {"/sys/devices/system/cpu/cpu24/cache/index2/type", "Unified"}, {"/sys/devices/system/cpu/cpu24/cache/index3/shared_cpu_list", "9-16,24-31"}, {"/sys/devices/system/cpu/cpu24/cache/index3/type", "Unified"}, {"/sys/devices/system/cpu/cpu25/cache/index0/shared_cpu_list", "10,25"}, {"/sys/devices/system/cpu/cpu25/cache/index0/type", "Data"}, {"/sys/devices/system/cpu/cpu25/cache/index1/shared_cpu_list", "10,25"}, {"/sys/devices/system/cpu/cpu25/cache/index1/type", "Instruction"}, {"/sys/devices/system/cpu/cpu25/cache/index2/shared_cpu_list", "10,25"}, {"/sys/devices/system/cpu/cpu25/cache/index2/type", "Unified"}, {"/sys/devices/system/cpu/cpu25/cache/index3/shared_cpu_list", "9-16,24-31"}, {"/sys/devices/system/cpu/cpu25/cache/index3/type", "Unified"}, {"/sys/devices/system/cpu/cpu26/cache/index0/shared_cpu_list", "11,26"}, {"/sys/devices/system/cpu/cpu26/cache/index0/type", "Data"}, {"/sys/devices/system/cpu/cpu26/cache/index1/shared_cpu_list", "11,26"}, {"/sys/devices/system/cpu/cpu26/cache/index1/type", "Instruction"}, {"/sys/devices/system/cpu/cpu26/cache/index2/shared_cpu_list", "11,26"}, {"/sys/devices/system/cpu/cpu26/cache/index2/type", "Unified"}, {"/sys/devices/system/cpu/cpu26/cache/index3/shared_cpu_list", "9-16,24-31"}, {"/sys/devices/system/cpu/cpu26/cache/index3/type", "Unified"}, {"/sys/devices/system/cpu/cpu27/cache/index0/shared_cpu_list", "12,27"}, {"/sys/devices/system/cpu/cpu27/cache/index0/type", "Data"}, {"/sys/devices/system/cpu/cpu27/cache/index1/shared_cpu_list", "12,27"}, {"/sys/devices/system/cpu/cpu27/cache/index1/type", "Instruction"}, {"/sys/devices/system/cpu/cpu27/cache/index2/shared_cpu_list", "12,27"}, {"/sys/devices/system/cpu/cpu27/cache/index2/type", "Unified"}, {"/sys/devices/system/cpu/cpu27/cache/index3/shared_cpu_list", "9-16,24-31"}, {"/sys/devices/system/cpu/cpu27/cache/index3/type", "Unified"}, {"/sys/devices/system/cpu/cpu28/cache/index0/shared_cpu_list", "13,28"}, {"/sys/devices/system/cpu/cpu28/cache/index0/type", "Data"}, {"/sys/devices/system/cpu/cpu28/cache/index1/shared_cpu_list", "13,28"}, {"/sys/devices/system/cpu/cpu28/cache/index1/type", "Instruction"}, {"/sys/devices/system/cpu/cpu28/cache/index2/shared_cpu_list", "13,28"}, {"/sys/devices/system/cpu/cpu28/cache/index2/type", "Unified"}, {"/sys/devices/system/cpu/cpu28/cache/index3/shared_cpu_list", "9-16,24-31"}, {"/sys/devices/system/cpu/cpu28/cache/index3/type", "Unified"}, {"/sys/devices/system/cpu/cpu29/cache/index0/shared_cpu_list", "14,29"}, {"/sys/devices/system/cpu/cpu29/cache/index0/type", "Data"}, {"/sys/devices/system/cpu/cpu29/cache/index1/shared_cpu_list", "14,29"}, {"/sys/devices/system/cpu/cpu29/cache/index1/type", "Instruction"}, {"/sys/devices/system/cpu/cpu29/cache/index2/shared_cpu_list", "14,29"}, {"/sys/devices/system/cpu/cpu29/cache/index2/type", "Unified"}, {"/sys/devices/system/cpu/cpu29/cache/index3/shared_cpu_list", "9-16,24-31"}, {"/sys/devices/system/cpu/cpu29/cache/index3/type", "Unified"}, {"/sys/devices/system/cpu/cpu30/cache/index0/shared_cpu_list", "15,30"}, {"/sys/devices/system/cpu/cpu30/cache/index0/type", "Data"}, {"/sys/devices/system/cpu/cpu30/cache/index1/shared_cpu_list", "15,30"}, {"/sys/devices/system/cpu/cpu30/cache/index1/type", "Instruction"}, {"/sys/devices/system/cpu/cpu30/cache/index2/shared_cpu_list", "15,30"}, {"/sys/devices/system/cpu/cpu30/cache/index2/type", "Unified"}, {"/sys/devices/system/cpu/cpu30/cache/index3/shared_cpu_list", "9-16,24-31"}, {"/sys/devices/system/cpu/cpu30/cache/index3/type", "Unified"}, {"/sys/devices/system/cpu/cpu31/cache/index0/shared_cpu_list", "16,31"}, {"/sys/devices/system/cpu/cpu31/cache/index0/type", "Data"}, {"/sys/devices/system/cpu/cpu31/cache/index1/shared_cpu_list", "16,31"}, {"/sys/devices/system/cpu/cpu31/cache/index1/type", "Instruction"}, {"/sys/devices/system/cpu/cpu31/cache/index2/shared_cpu_list", "16,31"}, {"/sys/devices/system/cpu/cpu31/cache/index2/type", "Unified"}, {"/sys/devices/system/cpu/cpu31/cache/index3/shared_cpu_list", "9-16,24-31"}, {"/sys/devices/system/cpu/cpu31/cache/index3/type", "Unified"}}; /// This is the expected CacheLocality structure for fakeSysfsTree static const CacheLocality nonUniformExampleLocality = {32, {16, 16, 2}, {0, 2, 4, 6, 8, 10, 11, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 1, 3, 5, 7, 9, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31}}; TEST(CacheLocality, FakeSysfs) { auto parsed = CacheLocality::readFromSysfsTree([](std::string name) { auto iter = fakeSysfsTree.find(name); return iter == fakeSysfsTree.end() ? std::string() : iter->second; }); auto& expected = nonUniformExampleLocality; EXPECT_EQ(expected.numCpus, parsed.numCpus); EXPECT_EQ(expected.numCachesByLevel, parsed.numCachesByLevel); EXPECT_EQ(expected.localityIndexByCpu, parsed.localityIndexByCpu); } #if FOLLY_HAVE_LINUX_VDSO TEST(Getcpu, VdsoGetcpu) { unsigned cpu; Getcpu::resolveVdsoFunc()(&cpu, nullptr, nullptr); EXPECT_TRUE(cpu < CPU_SETSIZE); } #endif #ifdef FOLLY_TLS TEST(ThreadId, SimpleTls) { unsigned cpu = 0; auto rv = folly::detail::FallbackGetcpu<SequentialThreadId<std::atomic>>::getcpu( &cpu, nullptr, nullptr); EXPECT_EQ(rv, 0); EXPECT_TRUE(cpu > 0); unsigned again; folly::detail::FallbackGetcpu<SequentialThreadId<std::atomic>>::getcpu( &again, nullptr, nullptr); EXPECT_EQ(cpu, again); } #endif TEST(ThreadId, SimplePthread) { unsigned cpu = 0; auto rv = folly::detail::FallbackGetcpu<HashingThreadId>::getcpu( &cpu, nullptr, nullptr); EXPECT_EQ(rv, 0); EXPECT_TRUE(cpu > 0); unsigned again; folly::detail::FallbackGetcpu<HashingThreadId>::getcpu( &again, nullptr, nullptr); EXPECT_EQ(cpu, again); } #ifdef FOLLY_TLS static FOLLY_TLS unsigned testingCpu = 0; static int testingGetcpu(unsigned* cpu, unsigned* node, void* /* unused */) { if (cpu != nullptr) { *cpu = testingCpu; } if (node != nullptr) { *node = testingCpu; } return 0; } #endif TEST(AccessSpreader, Simple) { for (size_t s = 1; s < 200; ++s) { EXPECT_LT(AccessSpreader<>::current(s), s); } } #ifdef FOLLY_TLS #define DECLARE_SPREADER_TAG(tag, locality, func) \ namespace { \ template <typename dummy> \ struct tag {}; \ } \ namespace folly { \ namespace detail { \ template <> \ const CacheLocality& CacheLocality::system<tag>() { \ static auto* inst = new CacheLocality(locality); \ return *inst; \ } \ template <> \ Getcpu::Func AccessSpreader<tag>::pickGetcpuFunc() { \ return func; \ } \ } \ } DECLARE_SPREADER_TAG(ManualTag, CacheLocality::uniform(16), testingGetcpu) TEST(AccessSpreader, Wrapping) { // this test won't pass unless locality.numCpus divides kMaxCpus auto numCpus = CacheLocality::system<ManualTag>().numCpus; EXPECT_EQ(0, 128 % numCpus); for (size_t s = 1; s < 200; ++s) { for (size_t c = 0; c < 400; ++c) { testingCpu = c; auto observed = AccessSpreader<ManualTag>::current(s); testingCpu = c % numCpus; auto expected = AccessSpreader<ManualTag>::current(s); EXPECT_EQ(expected, observed) << "numCpus=" << numCpus << ", s=" << s << ", c=" << c; } } } #endif
Java
/* * Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.codecommit.model; import javax.annotation.Generated; /** * <p> * The number of approvals required for the approval rule exceeds the maximum number allowed. * </p> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class MaximumNumberOfApprovalsExceededException extends com.amazonaws.services.codecommit.model.AWSCodeCommitException { private static final long serialVersionUID = 1L; /** * Constructs a new MaximumNumberOfApprovalsExceededException with the specified error message. * * @param message * Describes the error encountered. */ public MaximumNumberOfApprovalsExceededException(String message) { super(message); } }
Java
/** * Copyright (C) 2014-2015 Really Inc. <http://really.io> */ package io.really.model import akka.contrib.pattern.ShardRegion import _root_.io.really.{ RoutableToCollectionActor, ReallyConfig } class CollectionSharding(config: ReallyConfig) { implicit val implicitConfig = config val maxShards = config.Sharding.maxShards /** * ID Extractor for Akka Sharding extension * ID is the BucketId */ val idExtractor: ShardRegion.IdExtractor = { case req: RoutableToCollectionActor => Helpers.getBucketIDFromR(req.r) -> req } /** * Shard Resolver for Akka Sharding extension */ val shardResolver: ShardRegion.ShardResolver = { case req: RoutableToCollectionActor => (Helpers.getBucketIDFromR(req.r).hashCode % maxShards).toString } }
Java
#!/bin/bash echo "bootstrap" service ssh restart cd /MapRouletteAPI # Delete any RUNNING_PID file on restart rm RUNNING_PID || true ./setupServer.sh > setupServer.log 2>&1 while true; do sleep 1000; done
Java
#define NETCORE using System; using System.Linq; using System.Reflection; namespace Foundatio.Force.DeepCloner.Helpers { internal static class ReflectionHelper { public static bool IsEnum(this Type t) { #if NETCORE return t.GetTypeInfo().IsEnum; #else return t.IsEnum; #endif } public static bool IsValueType(this Type t) { #if NETCORE return t.GetTypeInfo().IsValueType; #else return t.IsValueType; #endif } public static bool IsClass(this Type t) { #if NETCORE return t.GetTypeInfo().IsClass; #else return t.IsClass; #endif } public static Type BaseType(this Type t) { #if NETCORE return t.GetTypeInfo().BaseType; #else return t.BaseType; #endif } public static FieldInfo[] GetAllFields(this Type t) { #if NETCORE return t.GetTypeInfo().DeclaredFields.Where(x => !x.IsStatic).ToArray(); #else return t.GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public); #endif } public static PropertyInfo[] GetPublicProperties(this Type t) { #if NETCORE return t.GetTypeInfo().DeclaredProperties.ToArray(); #else return t.GetProperties(BindingFlags.Instance | BindingFlags.Public); #endif } public static FieldInfo[] GetDeclaredFields(this Type t) { #if NETCORE return t.GetTypeInfo().DeclaredFields.Where(x => !x.IsStatic).ToArray(); #else return t.GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.DeclaredOnly); #endif } public static ConstructorInfo[] GetPrivateConstructors(this Type t) { #if NETCORE return t.GetTypeInfo().DeclaredConstructors.ToArray(); #else return t.GetConstructors(BindingFlags.NonPublic | BindingFlags.Instance); #endif } public static ConstructorInfo[] GetPublicConstructors(this Type t) { #if NETCORE return t.GetTypeInfo().DeclaredConstructors.ToArray(); #else return t.GetConstructors(BindingFlags.Public | BindingFlags.Instance); #endif } public static MethodInfo GetPrivateMethod(this Type t, string methodName) { #if NETCORE return t.GetTypeInfo().GetDeclaredMethod(methodName); #else return t.GetMethod(methodName, BindingFlags.NonPublic | BindingFlags.Instance); #endif } public static MethodInfo GetMethod(this Type t, string methodName) { #if NETCORE return t.GetTypeInfo().GetDeclaredMethod(methodName); #else return t.GetMethod(methodName); #endif } public static MethodInfo GetPrivateStaticMethod(this Type t, string methodName) { #if NETCORE return t.GetTypeInfo().GetDeclaredMethod(methodName); #else return t.GetMethod(methodName, BindingFlags.NonPublic | BindingFlags.Static); #endif } public static FieldInfo GetPrivateField(this Type t, string fieldName) { #if NETCORE return t.GetTypeInfo().GetDeclaredField(fieldName); #else return t.GetField(fieldName, BindingFlags.NonPublic | BindingFlags.Instance); #endif } public static FieldInfo GetPrivateStaticField(this Type t, string fieldName) { #if NETCORE return t.GetTypeInfo().GetDeclaredField(fieldName); #else return t.GetField(fieldName, BindingFlags.NonPublic | BindingFlags.Static); #endif } #if NETCORE public static bool IsSubclassOfTypeByName(this Type t, string typeName) { while (t != null) { if (t.Name == typeName) return true; t = t.BaseType(); } return false; } #endif #if NETCORE public static bool IsAssignableFrom(this Type from, Type to) { return from.GetTypeInfo().IsAssignableFrom(to.GetTypeInfo()); } public static bool IsInstanceOfType(this Type from, object to) { return from.IsAssignableFrom(to.GetType()); } #endif public static Type[] GenericArguments(this Type t) { #if NETCORE return t.GetTypeInfo().GenericTypeArguments; #else return t.GetGenericArguments(); #endif } } }
Java
"""Translation helper functions.""" import locale import os import re import sys import gettext as gettext_module from cStringIO import StringIO from django.utils.importlib import import_module from django.utils.safestring import mark_safe, SafeData from django.utils.thread_support import currentThread # Translations are cached in a dictionary for every language+app tuple. # The active translations are stored by threadid to make them thread local. _translations = {} _active = {} # The default translation is based on the settings file. _default = None # This is a cache for normalized accept-header languages to prevent multiple # file lookups when checking the same locale on repeated requests. _accepted = {} # Format of Accept-Language header values. From RFC 2616, section 14.4 and 3.9. accept_language_re = re.compile(r''' ([A-Za-z]{1,8}(?:-[A-Za-z]{1,8})*|\*) # "en", "en-au", "x-y-z", "*" (?:;q=(0(?:\.\d{,3})?|1(?:.0{,3})?))? # Optional "q=1.00", "q=0.8" (?:\s*,\s*|$) # Multiple accepts per header. ''', re.VERBOSE) def to_locale(language, to_lower=False): """ Turns a language name (en-us) into a locale name (en_US). If 'to_lower' is True, the last component is lower-cased (en_us). """ p = language.find('-') if p >= 0: if to_lower: return language[:p].lower()+'_'+language[p+1:].lower() else: return language[:p].lower()+'_'+language[p+1:].upper() else: return language.lower() def to_language(locale): """Turns a locale name (en_US) into a language name (en-us).""" p = locale.find('_') if p >= 0: return locale[:p].lower()+'-'+locale[p+1:].lower() else: return locale.lower() class DjangoTranslation(gettext_module.GNUTranslations): """ This class sets up the GNUTranslations context with regard to output charset. Django uses a defined DEFAULT_CHARSET as the output charset on Python 2.4. With Python 2.3, use DjangoTranslation23. """ def __init__(self, *args, **kw): from django.conf import settings gettext_module.GNUTranslations.__init__(self, *args, **kw) # Starting with Python 2.4, there's a function to define # the output charset. Before 2.4, the output charset is # identical with the translation file charset. try: self.set_output_charset('utf-8') except AttributeError: pass self.django_output_charset = 'utf-8' self.__language = '??' def merge(self, other): self._catalog.update(other._catalog) def set_language(self, language): self.__language = language def language(self): return self.__language def __repr__(self): return "<DjangoTranslation lang:%s>" % self.__language class DjangoTranslation23(DjangoTranslation): """ Compatibility class that is only used with Python 2.3. Python 2.3 doesn't support set_output_charset on translation objects and needs this wrapper class to make sure input charsets from translation files are correctly translated to output charsets. With a full switch to Python 2.4, this can be removed from the source. """ def gettext(self, msgid): res = self.ugettext(msgid) return res.encode(self.django_output_charset) def ngettext(self, msgid1, msgid2, n): res = self.ungettext(msgid1, msgid2, n) return res.encode(self.django_output_charset) def translation(language): """ Returns a translation object. This translation object will be constructed out of multiple GNUTranslations objects by merging their catalogs. It will construct a object for the requested language and add a fallback to the default language, if it's different from the requested language. """ global _translations t = _translations.get(language, None) if t is not None: return t from django.conf import settings # set up the right translation class klass = DjangoTranslation if sys.version_info < (2, 4): klass = DjangoTranslation23 globalpath = os.path.join(os.path.dirname(sys.modules[settings.__module__].__file__), 'locale') if settings.SETTINGS_MODULE is not None: parts = settings.SETTINGS_MODULE.split('.') project = import_module(parts[0]) projectpath = os.path.join(os.path.dirname(project.__file__), 'locale') else: projectpath = None def _fetch(lang, fallback=None): global _translations loc = to_locale(lang) res = _translations.get(lang, None) if res is not None: return res def _translation(path): try: t = gettext_module.translation('django', path, [loc], klass) t.set_language(lang) return t except IOError, e: return None res = _translation(globalpath) # We want to ensure that, for example, "en-gb" and "en-us" don't share # the same translation object (thus, merging en-us with a local update # doesn't affect en-gb), even though they will both use the core "en" # translation. So we have to subvert Python's internal gettext caching. base_lang = lambda x: x.split('-', 1)[0] if base_lang(lang) in [base_lang(trans) for trans in _translations]: res._info = res._info.copy() res._catalog = res._catalog.copy() def _merge(path): t = _translation(path) if t is not None: if res is None: return t else: res.merge(t) return res for localepath in settings.LOCALE_PATHS: if os.path.isdir(localepath): res = _merge(localepath) if projectpath and os.path.isdir(projectpath): res = _merge(projectpath) for appname in settings.INSTALLED_APPS: app = import_module(appname) apppath = os.path.join(os.path.dirname(app.__file__), 'locale') if os.path.isdir(apppath): res = _merge(apppath) if res is None: if fallback is not None: res = fallback else: return gettext_module.NullTranslations() _translations[lang] = res return res default_translation = _fetch(settings.LANGUAGE_CODE) current_translation = _fetch(language, fallback=default_translation) return current_translation def activate(language): """ Fetches the translation object for a given tuple of application name and language and installs it as the current translation object for the current thread. """ _active[currentThread()] = translation(language) def deactivate(): """ Deinstalls the currently active translation object so that further _ calls will resolve against the default translation object, again. """ global _active if currentThread() in _active: del _active[currentThread()] def deactivate_all(): """ Makes the active translation object a NullTranslations() instance. This is useful when we want delayed translations to appear as the original string for some reason. """ _active[currentThread()] = gettext_module.NullTranslations() def get_language(): """Returns the currently selected language.""" t = _active.get(currentThread(), None) if t is not None: try: return to_language(t.language()) except AttributeError: pass # If we don't have a real translation object, assume it's the default language. from django.conf import settings return settings.LANGUAGE_CODE def get_language_bidi(): """ Returns selected language's BiDi layout. False = left-to-right layout True = right-to-left layout """ from django.conf import settings base_lang = get_language().split('-')[0] return base_lang in settings.LANGUAGES_BIDI def catalog(): """ Returns the current active catalog for further processing. This can be used if you need to modify the catalog or want to access the whole message catalog instead of just translating one string. """ global _default, _active t = _active.get(currentThread(), None) if t is not None: return t if _default is None: from django.conf import settings _default = translation(settings.LANGUAGE_CODE) return _default def do_translate(message, translation_function): """ Translates 'message' using the given 'translation_function' name -- which will be either gettext or ugettext. It uses the current thread to find the translation object to use. If no current translation is activated, the message will be run through the default translation object. """ global _default, _active t = _active.get(currentThread(), None) if t is not None: result = getattr(t, translation_function)(message) else: if _default is None: from django.conf import settings _default = translation(settings.LANGUAGE_CODE) result = getattr(_default, translation_function)(message) if isinstance(message, SafeData): return mark_safe(result) return result def gettext(message): return do_translate(message, 'gettext') def ugettext(message): return do_translate(message, 'ugettext') def gettext_noop(message): """ Marks strings for translation but doesn't translate them now. This can be used to store strings in global variables that should stay in the base language (because they might be used externally) and will be translated later. """ return message def do_ntranslate(singular, plural, number, translation_function): global _default, _active t = _active.get(currentThread(), None) if t is not None: return getattr(t, translation_function)(singular, plural, number) if _default is None: from django.conf import settings _default = translation(settings.LANGUAGE_CODE) return getattr(_default, translation_function)(singular, plural, number) def ngettext(singular, plural, number): """ Returns a UTF-8 bytestring of the translation of either the singular or plural, based on the number. """ return do_ntranslate(singular, plural, number, 'ngettext') def ungettext(singular, plural, number): """ Returns a unicode strings of the translation of either the singular or plural, based on the number. """ return do_ntranslate(singular, plural, number, 'ungettext') def check_for_language(lang_code): """ Checks whether there is a global language file for the given language code. This is used to decide whether a user-provided language is available. This is only used for language codes from either the cookies or session. """ from django.conf import settings globalpath = os.path.join(os.path.dirname(sys.modules[settings.__module__].__file__), 'locale') if gettext_module.find('django', globalpath, [to_locale(lang_code)]) is not None: return True else: return False def get_language_from_request(request): """ Analyzes the request to find what language the user wants the system to show. Only languages listed in settings.LANGUAGES are taken into account. If the user requests a sublanguage where we have a main language, we send out the main language. """ global _accepted from django.conf import settings globalpath = os.path.join(os.path.dirname(sys.modules[settings.__module__].__file__), 'locale') supported = dict(settings.LANGUAGES) if hasattr(request, 'session'): lang_code = request.session.get('django_language', None) if lang_code in supported and lang_code is not None and check_for_language(lang_code): return lang_code lang_code = request.COOKIES.get(settings.LANGUAGE_COOKIE_NAME) if lang_code and lang_code in supported and check_for_language(lang_code): return lang_code accept = request.META.get('HTTP_ACCEPT_LANGUAGE', '') for accept_lang, unused in parse_accept_lang_header(accept): if accept_lang == '*': break # We have a very restricted form for our language files (no encoding # specifier, since they all must be UTF-8 and only one possible # language each time. So we avoid the overhead of gettext.find() and # work out the MO file manually. # 'normalized' is the root name of the locale in POSIX format (which is # the format used for the directories holding the MO files). normalized = locale.locale_alias.get(to_locale(accept_lang, True)) if not normalized: continue # Remove the default encoding from locale_alias. normalized = normalized.split('.')[0] if normalized in _accepted: # We've seen this locale before and have an MO file for it, so no # need to check again. return _accepted[normalized] for lang, dirname in ((accept_lang, normalized), (accept_lang.split('-')[0], normalized.split('_')[0])): if lang.lower() not in supported: continue langfile = os.path.join(globalpath, dirname, 'LC_MESSAGES', 'django.mo') if os.path.exists(langfile): _accepted[normalized] = lang return lang return settings.LANGUAGE_CODE def get_date_formats(): """ Checks whether translation files provide a translation for some technical message ID to store date and time formats. If it doesn't contain one, the formats provided in the settings will be used. """ from django.conf import settings date_format = ugettext('DATE_FORMAT') datetime_format = ugettext('DATETIME_FORMAT') time_format = ugettext('TIME_FORMAT') if date_format == 'DATE_FORMAT': date_format = settings.DATE_FORMAT if datetime_format == 'DATETIME_FORMAT': datetime_format = settings.DATETIME_FORMAT if time_format == 'TIME_FORMAT': time_format = settings.TIME_FORMAT return date_format, datetime_format, time_format def get_partial_date_formats(): """ Checks whether translation files provide a translation for some technical message ID to store partial date formats. If it doesn't contain one, the formats provided in the settings will be used. """ from django.conf import settings year_month_format = ugettext('YEAR_MONTH_FORMAT') month_day_format = ugettext('MONTH_DAY_FORMAT') if year_month_format == 'YEAR_MONTH_FORMAT': year_month_format = settings.YEAR_MONTH_FORMAT if month_day_format == 'MONTH_DAY_FORMAT': month_day_format = settings.MONTH_DAY_FORMAT return year_month_format, month_day_format dot_re = re.compile(r'\S') def blankout(src, char): """ Changes every non-whitespace character to the given char. Used in the templatize function. """ return dot_re.sub(char, src) inline_re = re.compile(r"""^\s*trans\s+((?:".*?")|(?:'.*?'))\s*""") block_re = re.compile(r"""^\s*blocktrans(?:\s+|$)""") endblock_re = re.compile(r"""^\s*endblocktrans$""") plural_re = re.compile(r"""^\s*plural$""") constant_re = re.compile(r"""_\(((?:".*?")|(?:'.*?'))\)""") def templatize(src): """ Turns a Django template into something that is understood by xgettext. It does so by translating the Django translation tags into standard gettext function invocations. """ from django.template import Lexer, TOKEN_TEXT, TOKEN_VAR, TOKEN_BLOCK out = StringIO() intrans = False inplural = False singular = [] plural = [] for t in Lexer(src, None).tokenize(): if intrans: if t.token_type == TOKEN_BLOCK: endbmatch = endblock_re.match(t.contents) pluralmatch = plural_re.match(t.contents) if endbmatch: if inplural: out.write(' ngettext(%r,%r,count) ' % (''.join(singular), ''.join(plural))) for part in singular: out.write(blankout(part, 'S')) for part in plural: out.write(blankout(part, 'P')) else: out.write(' gettext(%r) ' % ''.join(singular)) for part in singular: out.write(blankout(part, 'S')) intrans = False inplural = False singular = [] plural = [] elif pluralmatch: inplural = True else: raise SyntaxError("Translation blocks must not include other block tags: %s" % t.contents) elif t.token_type == TOKEN_VAR: if inplural: plural.append('%%(%s)s' % t.contents) else: singular.append('%%(%s)s' % t.contents) elif t.token_type == TOKEN_TEXT: if inplural: plural.append(t.contents) else: singular.append(t.contents) else: if t.token_type == TOKEN_BLOCK: imatch = inline_re.match(t.contents) bmatch = block_re.match(t.contents) cmatches = constant_re.findall(t.contents) if imatch: g = imatch.group(1) if g[0] == '"': g = g.strip('"') elif g[0] == "'": g = g.strip("'") out.write(' gettext(%r) ' % g) elif bmatch: for fmatch in constant_re.findall(t.contents): out.write(' _(%s) ' % fmatch) intrans = True inplural = False singular = [] plural = [] elif cmatches: for cmatch in cmatches: out.write(' _(%s) ' % cmatch) else: out.write(blankout(t.contents, 'B')) elif t.token_type == TOKEN_VAR: parts = t.contents.split('|') cmatch = constant_re.match(parts[0]) if cmatch: out.write(' _(%s) ' % cmatch.group(1)) for p in parts[1:]: if p.find(':_(') >= 0: out.write(' %s ' % p.split(':',1)[1]) else: out.write(blankout(p, 'F')) else: out.write(blankout(t.contents, 'X')) return out.getvalue() def parse_accept_lang_header(lang_string): """ Parses the lang_string, which is the body of an HTTP Accept-Language header, and returns a list of (lang, q-value), ordered by 'q' values. Any format errors in lang_string results in an empty list being returned. """ result = [] pieces = accept_language_re.split(lang_string) if pieces[-1]: return [] for i in range(0, len(pieces) - 1, 3): first, lang, priority = pieces[i : i + 3] if first: return [] priority = priority and float(priority) or 1.0 result.append((lang, priority)) result.sort(lambda x, y: -cmp(x[1], y[1])) return result
Java
#pragma once #include "DBC/DBC__File.h" DBC_DEF_BEGIN(DBC_CreatureDisplayInfo) __DBC_REF_ID(DBC_CreatureModelData, CreatureModelDataID, 2); __DBC_TVALUE(uint32, SoundID, 3); __DBC_REF_ID(DBC_CreatureDisplayInfoExtra, HumanoidData, 4); __DBC_TVALUE(float_t, Scale, 5); __DBC_TVALUE(uint32, Opacity, 6); // 0 - 255 __DBC_STRING(Texture1, 7); // Name of texture for 1st geoset with type 2 (see this). Texture must be in the same dir as M2 file of creature is. __DBC_STRING(Texture2, 8); // Name of texture for 2nd geoset with type 2 (see this). Texture must be in the same dir as M2 file of creature is. __DBC_STRING(Texture3, 9); // Name of texture for 3rd geoset with type 2 (see this). Texture must be in the same dir as M2 file of creature is. __DBC_STRING(PortaitTexture, 10); __DBC_TVALUE(uint32, UnitBloodLevelID, 11); __DBC_TVALUE(uint32, UnitBloodID, 12); __DBC_TVALUE(uint32, NPCSoundsID, 13); __DBC_TVALUE(uint32, ParticlesID, 14); __DBC_TVALUE(uint32, CreatureGeosetData, 15); __DBC_TVALUE(uint32, ObjectEffectPackageID, 16); DBC_DEF_END
Java
# # ncurses, keep it simple for the moment # option(USE_BUNDLED_NCURSES "Enable building of the bundled ncurses" ${USE_BUNDLED_DEPS}) if(CURSES_INCLUDE_DIR) # we already have ncurses elseif(NOT USE_BUNDLED_NCURSES) set(CURSES_NEED_NCURSES TRUE) find_package(Curses REQUIRED) message(STATUS "Found ncurses: include: ${CURSES_INCLUDE_DIR}, lib: ${CURSES_LIBRARIES}") else() set(CURSES_BUNDLE_DIR "${PROJECT_BINARY_DIR}/ncurses-prefix/src/ncurses") set(CURSES_INCLUDE_DIR "${CURSES_BUNDLE_DIR}/include/") set(CURSES_LIBRARIES "${CURSES_BUNDLE_DIR}/lib/libncurses.a") if(NOT TARGET ncurses) message(STATUS "Using bundled ncurses in '${CURSES_BUNDLE_DIR}'") ExternalProject_Add(ncurses PREFIX "${PROJECT_BINARY_DIR}/ncurses-prefix" URL "http://download.draios.com/dependencies/ncurses-6.0-20150725.tgz" URL_MD5 "32b8913312e738d707ae68da439ca1f4" CONFIGURE_COMMAND ./configure --without-cxx --without-cxx-binding --without-ada --without-manpages --without-progs --without-tests --with-terminfo-dirs=/etc/terminfo:/lib/terminfo:/usr/share/terminfo BUILD_COMMAND ${CMD_MAKE} BUILD_IN_SOURCE 1 BUILD_BYPRODUCTS ${CURSES_LIBRARIES} INSTALL_COMMAND "") endif() endif() include_directories("${CURSES_INCLUDE_DIR}")
Java
{-# LANGUAGE ExplicitForAll, Rank2Types #-} -- | An implementation of Reagents (http://www.mpi-sws.org/~turon/reagents.pdf) -- NOTE: currently this is just a very tiny core of the Reagent design. Needs -- lots of work. module Data.Concurrent.Internal.Reagent where import Data.IORef import Data.Atomics import Prelude hiding (succ, fail) type Reagent a = forall b. (a -> IO b) -> IO b -> IO b -- | Execute a Reagent. {-# INLINE react #-} react :: Reagent a -> IO a react r = try where try = r finish try finish x = return x -- | Like atomicModifyIORef, but uses CAS and permits the update action to force -- a retry by returning Nothing {-# INLINE atomicUpdate #-} atomicUpdate :: IORef a -> (a -> Maybe (a, b)) -> Reagent b atomicUpdate r f succ fail = do curTicket <- readForCAS r let cur = peekTicket curTicket case f cur of Just (new, out) -> do (done, _) <- casIORef r curTicket new if done then succ out else fail Nothing -> fail atomicUpdate_ :: IORef a -> (a -> a) -> Reagent () atomicUpdate_ r f = atomicUpdate r (\x -> Just (f x, ())) postCommit :: Reagent a -> (a -> IO b) -> Reagent b postCommit r f succ fail = r (\x -> f x >>= succ) fail choice :: Reagent a -> Reagent a -> Reagent a choice _ _ = error "TODO"
Java
using System; using NDatabase.Api; using NUnit.Framework; using Test.NDatabase.Odb.Test.VO.Human; namespace Test.NDatabase.Odb.Test.Query.Criteria { public class TestPolyMorphic : ODBTest { private const string DbName = "TestPolyMorphic.ndb"; [Test] public void Test1() { DeleteBase(DbName); using (var odb = Open(DbName)) { odb.Store(new Animal("dog", "M", "my dog")); odb.Store(new Animal("cat", "F", "my cat")); odb.Store(new Man("Joe")); odb.Store(new Woman("Karine")); } IObjectSet<object> os; using (var odb = Open(DbName)) { var q = odb.Query<object>(); os = q.Execute<object>(); Println(os); } AssertEquals(4, os.Count); DeleteBase(DbName); } [Test] public void Test2() { DeleteBase(DbName); using (var odb = Open(DbName)) { odb.Store(new Animal("dog", "M", "my dog")); odb.Store(new Animal("cat", "F", "my cat")); odb.Store(new Man("Joe")); odb.Store(new Woman("Karine")); } IObjectSet<Human> os; using (var odb = Open(DbName)) { var q = odb.Query<Human>(); os = q.Execute<Human>(); Println(os); } AssertEquals(2, os.Count); DeleteBase(DbName); } [Test] public void Test3() { DeleteBase(DbName); using (var odb = Open(DbName)) { odb.Store(new Animal("dog", "M", "my dog")); odb.Store(new Animal("cat", "F", "my cat")); odb.Store(new Man("Joe")); odb.Store(new Woman("Karine")); } IValues os; using (var odb = Open(DbName)) { var q = odb.ValuesQuery<object>().Field("specie"); os = q.Execute(); Println(os); } AssertEquals(4, os.Count); DeleteBase(DbName); } [Test] public void Test4() { DeleteBase(DbName); using (var odb = Open(DbName)) { odb.Store(new Animal("dog", "M", "my dog")); odb.Store(new Animal("cat", "F", "my cat")); odb.Store(new Man("Joe")); odb.Store(new Woman("Karine")); } IValues os; using (var odb = Open(DbName)) { var q = odb.ValuesQuery<Human>().Field("specie"); os = q.Execute(); Println(os); } AssertEquals(2, os.Count); DeleteBase(DbName); } [Test] public void Test5() { DeleteBase(DbName); using (var odb = Open(DbName)) { odb.Store(new Animal("dog", "M", "my dog")); odb.Store(new Animal("cat", "F", "my cat")); odb.Store(new Man("Joe")); odb.Store(new Woman("Karine")); } IValues os; using (var odb = Open(DbName)) { var q = odb.ValuesQuery<Man>().Field("specie"); os = q.Execute(); Println(os); } AssertEquals(1, os.Count); DeleteBase(DbName); } [Test] public void Test6() { DeleteBase(DbName); using (var odb = Open(DbName)) { odb.Store(new Animal("dog", "M", "my dog")); odb.Store(new Animal("cat", "F", "my cat")); odb.Store(new Man("Joe")); odb.Store(new Woman("Karine")); } Decimal nb; using (var odb = Open(DbName)) { var q = odb.Query<object>(); nb = q.Count(); Println(nb); } AssertEquals(new Decimal(4), nb); DeleteBase(DbName); } [Test] public void Test7() { const int size = 3000; var baseName = GetBaseName(); using (var odb = Open(baseName)) { for (var i = 0; i < size; i++) { odb.Store(new Animal("dog", "M", "my dog")); odb.Store(new Animal("cat", "F", "my cat")); odb.Store(new Man("Joe" + i)); odb.Store(new Woman("Karine" + i)); } } Decimal nb; using (var odb = Open(baseName)) { var q = odb.Query<object>(); nb = q.Count(); Println(nb); } AssertEquals(new Decimal(4 * size), nb); DeleteBase(baseName); } [Test] public void Test8() { const int size = 3000; var baseName = GetBaseName(); using (var odb = Open(baseName)) { for (var i = 0; i < size; i++) { odb.Store(new Animal("dog" + i, "M", "my dog" + i)); odb.Store(new Animal("cat" + i, "F", "my cat" + i)); odb.Store(new Man("Joe" + i)); odb.Store(new Woman("Karine" + i)); } } Decimal nb; using (var odb = Open(baseName)) { var q = odb.Query<object>(); q.Descend("specie").Constrain("man").Equal(); nb = q.Count(); Println(nb); } AssertEquals(new Decimal(1 * size), nb); DeleteBase(baseName); } } }
Java
package org.myrobotlab.framework; import static org.myrobotlab.framework.StatusLevel.DEBUG; import static org.myrobotlab.framework.StatusLevel.ERROR; import static org.myrobotlab.framework.StatusLevel.INFO; import static org.myrobotlab.framework.StatusLevel.SUCCESS; import static org.myrobotlab.framework.StatusLevel.WARN; import java.io.IOException; import java.io.PrintWriter; import java.io.Serializable; import java.io.StringWriter; import java.util.Objects; import org.myrobotlab.codec.CodecUtils; import org.myrobotlab.logging.Level; import org.myrobotlab.logging.LoggerFactory; import org.myrobotlab.logging.LoggingFactory; import org.slf4j.Logger; /** * Goal is to have a very simple Pojo with only a few (native Java helper * methods) WARNING !!! - this class used to extend Exception or Throwable - but * the gson serializer would stack overflow with self reference issue * * TODO - allow radix tree searches for "keys" ??? * */ public class Status implements Serializable {// extends Exception { private static final long serialVersionUID = 1L; public final static Logger log = LoggerFactory.getLogger(Status.class); public String name; // service name ??? /** * FIXME - should probably be an enum now that serialization mostly works now * with enums [debug|info|warn|error|success] - yes the last part is different * than "logging" but could still be a status... * */ public String level; /** * The key is the non changing part and good identifier of what went on... For * Exceptions I would recommend the Exception.class.getSimpleName() for the * key, whilst the "detail" is for "changing" detail. This becomes important * when Stati are aggregated - and humans are interested in "high" counts of * specific Status while the details are not important unless diagnosing one. * * Violating Servo limits is a good example - "key" can be "Outside servo * limits". The key can contain spaces and punctuation - the important part is * that it is STATIC. * * "details" contain dynamic specifics - for example: "key":"Outside servo * limits", "detail":"servo01 moveTo(75) limit is greater than 100" */ public String key; /** * Dynamic of verbose explanation of the status. e.g. "detail":"servo01 * moveTo(75) limit is greater than 100" or complete stack trace from an * exception */ public String detail; /** * optional source of status */ public Object source; // --- static creation of typed Status objects ---- public static Status debug(String format, Object... args) { Status status = new Status(String.format(format, args)); status.level = DEBUG; return status; } public static Status error(Exception e) { Status s = new Status(e); s.level = ERROR; return s; } public static Status error(String msg) { Status s = new Status(msg); s.level = ERROR; return s; } public static Status error(String format, Object... args) { Status status = new Status(String.format(format, args)); status.level = ERROR; return status; } public static Status warn(String msg) { Status s = new Status(msg); s.level = ERROR; return s; } public static Status warn(String format, Object... args) { Status status = new Status(String.format(format, args)); status.level = WARN; return status; } public static Status info(String msg) { Status s = new Status(msg); s.level = INFO; return s; } public static Status info(String format, Object... args) { String formattedInfo = String.format(format, args); Status status = new Status(formattedInfo); status.level = INFO; return status; } public final static String stackToString(final Throwable e) { StringWriter sw; try { sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); e.printStackTrace(pw); } catch (Exception e2) { return "bad stackToString"; } return "------\r\n" + sw.toString() + "------\r\n"; } public Status(Exception e) { this.level = ERROR; StringWriter sw; try { sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); e.printStackTrace(pw); detail = sw.toString(); } catch (Exception e2) { } this.key = String.format("%s - %s", e.getClass().getSimpleName(), e.getMessage()); } public Status(Status s) { if (s == null) { return; } this.name = s.name; this.level = s.level; this.key = s.key; this.detail = s.detail; } /** * for minimal amount of information error is assumed, and info is detail of * an ERROR * * @param detail * d */ public Status(String detail) { this.level = ERROR; this.detail = detail; } public Status(String name, String level, String key, String detail) { this.name = name; this.level = level; this.key = key; this.detail = detail; } public boolean isDebug() { return DEBUG.equals(level); } public boolean isError() { return ERROR.equals(level); } public boolean isInfo() { return INFO.equals(level); } public boolean isWarn() { return WARN.equals(level); } @Override public String toString() { StringBuffer sb = new StringBuffer(); if (name != null) { sb.append(name); sb.append(" "); } if (level != null) { sb.append(level); sb.append(" "); } if (key != null) { sb.append(key); sb.append(" "); } if (detail != null) { sb.append(detail); } return sb.toString(); } static public final Status newInstance(String name, String level, String key, String detail) { Status s = new Status(name, level, key, detail); return s; } @Override public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof Status)) { return false; } Status status = (Status) o; return Objects.equals(name, status.name) && Objects.equals(level, status.level) && Objects.equals(key, status.key) && Objects.equals(detail, status.detail); } @Override public int hashCode() { return Objects.hash(name, level, key, detail); } public static void main(String[] args) throws IOException, InterruptedException { LoggingFactory.init(Level.INFO); Status test = new Status("i am pessimistic"); // Status subTest = new Status("i am sub pessimistic"); // test.add(subTest); String json = CodecUtils.toJson(test); Status z = CodecUtils.fromJson(json, Status.class); log.info(json); log.info(z.toString()); } public static Status success() { Status s = new Status(SUCCESS); s.level = SUCCESS; return s; } public boolean isSuccess() { return SUCCESS.equals(level); } public static Status success(String detail) { Status s = new Status(SUCCESS); s.level = SUCCESS; s.detail = detail; return s; } }
Java
// 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. using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Shared.Collections; using Microsoft.CodeAnalysis.Structure; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.Structure { internal class RegionDirectiveStructureProvider : AbstractSyntaxNodeStructureProvider<RegionDirectiveTriviaSyntax> { private static string GetBannerText(DirectiveTriviaSyntax simpleDirective) { var kw = simpleDirective.DirectiveNameToken; var prefixLength = kw.Span.End - simpleDirective.Span.Start; var text = simpleDirective.ToString().Substring(prefixLength).Trim(); if (text.Length == 0) { return simpleDirective.HashToken.ToString() + kw.ToString(); } else { return text; } } protected override void CollectBlockSpans( SyntaxToken previousToken, RegionDirectiveTriviaSyntax regionDirective, ref TemporaryArray<BlockSpan> spans, BlockStructureOptionProvider optionProvider, CancellationToken cancellationToken) { var match = regionDirective.GetMatchingDirective(cancellationToken); if (match != null) { // Always auto-collapse regions for Metadata As Source. These generated files only have one region at // the top of the file, which has content like the following: // // #region Assembly System.Runtime, Version=4.2.2.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a // // C:\Program Files\dotnet\packs\Microsoft.NETCore.App.Ref\3.1.0\ref\netcoreapp3.1\System.Runtime.dll // #endregion // // For other files, auto-collapse regions based on the user option. var autoCollapse = optionProvider.IsMetadataAsSource || optionProvider.GetOption( BlockStructureOptions.CollapseRegionsWhenCollapsingToDefinitions, LanguageNames.CSharp); spans.Add(new BlockSpan( isCollapsible: true, textSpan: TextSpan.FromBounds(regionDirective.SpanStart, match.Span.End), type: BlockTypes.PreprocessorRegion, bannerText: GetBannerText(regionDirective), autoCollapse: autoCollapse, isDefaultCollapsed: !optionProvider.IsMetadataAsSource)); } } } }
Java
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Type resolution: the phase that finds all the types in the AST with // unresolved type variables and replaces "ty_var" types with their // substitutions. use self::ResolveReason::*; use astconv::AstConv; use check::FnCtxt; use middle::def; use middle::pat_util; use middle::ty::{mod, Ty, MethodCall, MethodCallee}; use middle::ty_fold::{TypeFolder,TypeFoldable}; use middle::infer::{force_all, resolve_all, resolve_region}; use middle::infer::resolve_type; use middle::infer; use write_substs_to_tcx; use write_ty_to_tcx; use util::ppaux::Repr; use std::cell::Cell; use syntax::ast; use syntax::codemap::{DUMMY_SP, Span}; use syntax::print::pprust::pat_to_string; use syntax::visit; use syntax::visit::Visitor; /////////////////////////////////////////////////////////////////////////// // Entry point functions pub fn resolve_type_vars_in_expr(fcx: &FnCtxt, e: &ast::Expr) { assert_eq!(fcx.writeback_errors.get(), false); let mut wbcx = WritebackCx::new(fcx); wbcx.visit_expr(e); wbcx.visit_upvar_borrow_map(); wbcx.visit_unboxed_closures(); wbcx.visit_object_cast_map(); } pub fn resolve_type_vars_in_fn(fcx: &FnCtxt, decl: &ast::FnDecl, blk: &ast::Block) { assert_eq!(fcx.writeback_errors.get(), false); let mut wbcx = WritebackCx::new(fcx); wbcx.visit_block(blk); for arg in decl.inputs.iter() { wbcx.visit_node_id(ResolvingPattern(arg.pat.span), arg.id); wbcx.visit_pat(&*arg.pat); // Privacy needs the type for the whole pattern, not just each binding if !pat_util::pat_is_binding(&fcx.tcx().def_map, &*arg.pat) { wbcx.visit_node_id(ResolvingPattern(arg.pat.span), arg.pat.id); } } wbcx.visit_upvar_borrow_map(); wbcx.visit_unboxed_closures(); wbcx.visit_object_cast_map(); } /////////////////////////////////////////////////////////////////////////// // The Writerback context. This visitor walks the AST, checking the // fn-specific tables to find references to types or regions. It // resolves those regions to remove inference variables and writes the // final result back into the master tables in the tcx. Here and // there, it applies a few ad-hoc checks that were not convenient to // do elsewhere. struct WritebackCx<'cx, 'tcx: 'cx> { fcx: &'cx FnCtxt<'cx, 'tcx>, } impl<'cx, 'tcx> WritebackCx<'cx, 'tcx> { fn new(fcx: &'cx FnCtxt<'cx, 'tcx>) -> WritebackCx<'cx, 'tcx> { WritebackCx { fcx: fcx } } fn tcx(&self) -> &'cx ty::ctxt<'tcx> { self.fcx.tcx() } } /////////////////////////////////////////////////////////////////////////// // Impl of Visitor for Resolver // // This is the master code which walks the AST. It delegates most of // the heavy lifting to the generic visit and resolve functions // below. In general, a function is made into a `visitor` if it must // traffic in node-ids or update tables in the type context etc. impl<'cx, 'tcx, 'v> Visitor<'v> for WritebackCx<'cx, 'tcx> { fn visit_item(&mut self, _: &ast::Item) { // Ignore items } fn visit_stmt(&mut self, s: &ast::Stmt) { if self.fcx.writeback_errors.get() { return; } self.visit_node_id(ResolvingExpr(s.span), ty::stmt_node_id(s)); visit::walk_stmt(self, s); } fn visit_expr(&mut self, e: &ast::Expr) { if self.fcx.writeback_errors.get() { return; } self.visit_node_id(ResolvingExpr(e.span), e.id); self.visit_method_map_entry(ResolvingExpr(e.span), MethodCall::expr(e.id)); match e.node { ast::ExprClosure(_, _, ref decl, _) | ast::ExprProc(ref decl, _) => { for input in decl.inputs.iter() { let _ = self.visit_node_id(ResolvingExpr(e.span), input.id); } } _ => {} } visit::walk_expr(self, e); } fn visit_block(&mut self, b: &ast::Block) { if self.fcx.writeback_errors.get() { return; } self.visit_node_id(ResolvingExpr(b.span), b.id); visit::walk_block(self, b); } fn visit_pat(&mut self, p: &ast::Pat) { if self.fcx.writeback_errors.get() { return; } self.visit_node_id(ResolvingPattern(p.span), p.id); debug!("Type for pattern binding {} (id {}) resolved to {}", pat_to_string(p), p.id, ty::node_id_to_type(self.tcx(), p.id).repr(self.tcx())); visit::walk_pat(self, p); } fn visit_local(&mut self, l: &ast::Local) { if self.fcx.writeback_errors.get() { return; } let var_ty = self.fcx.local_ty(l.span, l.id); let var_ty = self.resolve(&var_ty, ResolvingLocal(l.span)); write_ty_to_tcx(self.tcx(), l.id, var_ty); visit::walk_local(self, l); } fn visit_ty(&mut self, t: &ast::Ty) { match t.node { ast::TyFixedLengthVec(ref ty, ref count_expr) => { self.visit_ty(&**ty); write_ty_to_tcx(self.tcx(), count_expr.id, ty::mk_uint()); } _ => visit::walk_ty(self, t) } } } impl<'cx, 'tcx> WritebackCx<'cx, 'tcx> { fn visit_upvar_borrow_map(&self) { if self.fcx.writeback_errors.get() { return; } for (upvar_id, upvar_borrow) in self.fcx.inh.upvar_borrow_map.borrow().iter() { let r = upvar_borrow.region; let r = self.resolve(&r, ResolvingUpvar(*upvar_id)); let new_upvar_borrow = ty::UpvarBorrow { kind: upvar_borrow.kind, region: r }; debug!("Upvar borrow for {} resolved to {}", upvar_id.repr(self.tcx()), new_upvar_borrow.repr(self.tcx())); self.fcx.tcx().upvar_borrow_map.borrow_mut().insert( *upvar_id, new_upvar_borrow); } } fn visit_unboxed_closures(&self) { if self.fcx.writeback_errors.get() { return } for (def_id, unboxed_closure) in self.fcx .inh .unboxed_closures .borrow() .iter() { let closure_ty = self.resolve(&unboxed_closure.closure_type, ResolvingUnboxedClosure(*def_id)); let unboxed_closure = ty::UnboxedClosure { closure_type: closure_ty, kind: unboxed_closure.kind, }; self.fcx .tcx() .unboxed_closures .borrow_mut() .insert(*def_id, unboxed_closure); } } fn visit_object_cast_map(&self) { if self.fcx.writeback_errors.get() { return } for (&node_id, trait_ref) in self.fcx .inh .object_cast_map .borrow() .iter() { let span = ty::expr_span(self.tcx(), node_id); let reason = ResolvingExpr(span); let closure_ty = self.resolve(trait_ref, reason); self.tcx() .object_cast_map .borrow_mut() .insert(node_id, closure_ty); } } fn visit_node_id(&self, reason: ResolveReason, id: ast::NodeId) { // Resolve any borrowings for the node with id `id` self.visit_adjustments(reason, id); // Resolve the type of the node with id `id` let n_ty = self.fcx.node_ty(id); let n_ty = self.resolve(&n_ty, reason); write_ty_to_tcx(self.tcx(), id, n_ty); debug!("Node {} has type {}", id, n_ty.repr(self.tcx())); // Resolve any substitutions self.fcx.opt_node_ty_substs(id, |item_substs| { write_substs_to_tcx(self.tcx(), id, self.resolve(item_substs, reason)); }); } fn visit_adjustments(&self, reason: ResolveReason, id: ast::NodeId) { match self.fcx.inh.adjustments.borrow_mut().remove(&id) { None => { debug!("No adjustments for node {}", id); } Some(adjustment) => { let adj_object = ty::adjust_is_object(&adjustment); let resolved_adjustment = match adjustment { ty::AdjustAddEnv(store) => { // FIXME(eddyb) #2190 Allow only statically resolved // bare functions to coerce to a closure to avoid // constructing (slower) indirect call wrappers. match self.tcx().def_map.borrow().get(&id) { Some(&def::DefFn(..)) | Some(&def::DefStaticMethod(..)) | Some(&def::DefVariant(..)) | Some(&def::DefStruct(_)) => { } _ => { span_err!(self.tcx().sess, reason.span(self.tcx()), E0100, "cannot coerce non-statically resolved bare fn to closure"); span_help!(self.tcx().sess, reason.span(self.tcx()), "consider embedding the function in a closure"); } } ty::AdjustAddEnv(self.resolve(&store, reason)) } ty::AdjustDerefRef(adj) => { for autoderef in range(0, adj.autoderefs) { let method_call = MethodCall::autoderef(id, autoderef); self.visit_method_map_entry(reason, method_call); } if adj_object { let method_call = MethodCall::autoobject(id); self.visit_method_map_entry(reason, method_call); } ty::AdjustDerefRef(ty::AutoDerefRef { autoderefs: adj.autoderefs, autoref: self.resolve(&adj.autoref, reason), }) } }; debug!("Adjustments for node {}: {}", id, resolved_adjustment); self.tcx().adjustments.borrow_mut().insert( id, resolved_adjustment); } } } fn visit_method_map_entry(&self, reason: ResolveReason, method_call: MethodCall) { // Resolve any method map entry match self.fcx.inh.method_map.borrow_mut().remove(&method_call) { Some(method) => { debug!("writeback::resolve_method_map_entry(call={}, entry={})", method_call, method.repr(self.tcx())); let new_method = MethodCallee { origin: self.resolve(&method.origin, reason), ty: self.resolve(&method.ty, reason), substs: self.resolve(&method.substs, reason), }; self.tcx().method_map.borrow_mut().insert( method_call, new_method); } None => {} } } fn resolve<T:ResolveIn<'tcx>>(&self, t: &T, reason: ResolveReason) -> T { t.resolve_in(&mut Resolver::new(self.fcx, reason)) } } /////////////////////////////////////////////////////////////////////////// // Resolution reason. enum ResolveReason { ResolvingExpr(Span), ResolvingLocal(Span), ResolvingPattern(Span), ResolvingUpvar(ty::UpvarId), ResolvingUnboxedClosure(ast::DefId), } impl Copy for ResolveReason {} impl ResolveReason { fn span(&self, tcx: &ty::ctxt) -> Span { match *self { ResolvingExpr(s) => s, ResolvingLocal(s) => s, ResolvingPattern(s) => s, ResolvingUpvar(upvar_id) => { ty::expr_span(tcx, upvar_id.closure_expr_id) } ResolvingUnboxedClosure(did) => { if did.krate == ast::LOCAL_CRATE { ty::expr_span(tcx, did.node) } else { DUMMY_SP } } } } } /////////////////////////////////////////////////////////////////////////// // Convenience methods for resolving different kinds of things. trait ResolveIn<'tcx> { fn resolve_in<'a>(&self, resolver: &mut Resolver<'a, 'tcx>) -> Self; } impl<'tcx, T: TypeFoldable<'tcx>> ResolveIn<'tcx> for T { fn resolve_in<'a>(&self, resolver: &mut Resolver<'a, 'tcx>) -> T { self.fold_with(resolver) } } /////////////////////////////////////////////////////////////////////////// // The Resolver. This is the type folding engine that detects // unresolved types and so forth. struct Resolver<'cx, 'tcx: 'cx> { tcx: &'cx ty::ctxt<'tcx>, infcx: &'cx infer::InferCtxt<'cx, 'tcx>, writeback_errors: &'cx Cell<bool>, reason: ResolveReason, } impl<'cx, 'tcx> Resolver<'cx, 'tcx> { fn new(fcx: &'cx FnCtxt<'cx, 'tcx>, reason: ResolveReason) -> Resolver<'cx, 'tcx> { Resolver::from_infcx(fcx.infcx(), &fcx.writeback_errors, reason) } fn from_infcx(infcx: &'cx infer::InferCtxt<'cx, 'tcx>, writeback_errors: &'cx Cell<bool>, reason: ResolveReason) -> Resolver<'cx, 'tcx> { Resolver { infcx: infcx, tcx: infcx.tcx, writeback_errors: writeback_errors, reason: reason } } fn report_error(&self, e: infer::fixup_err) { self.writeback_errors.set(true); if !self.tcx.sess.has_errors() { match self.reason { ResolvingExpr(span) => { span_err!(self.tcx.sess, span, E0101, "cannot determine a type for this expression: {}", infer::fixup_err_to_string(e)); } ResolvingLocal(span) => { span_err!(self.tcx.sess, span, E0102, "cannot determine a type for this local variable: {}", infer::fixup_err_to_string(e)); } ResolvingPattern(span) => { span_err!(self.tcx.sess, span, E0103, "cannot determine a type for this pattern binding: {}", infer::fixup_err_to_string(e)); } ResolvingUpvar(upvar_id) => { let span = self.reason.span(self.tcx); span_err!(self.tcx.sess, span, E0104, "cannot resolve lifetime for captured variable `{}`: {}", ty::local_var_name_str(self.tcx, upvar_id.var_id).get().to_string(), infer::fixup_err_to_string(e)); } ResolvingUnboxedClosure(_) => { let span = self.reason.span(self.tcx); self.tcx.sess.span_err(span, "cannot determine a type for this \ unboxed closure") } } } } } impl<'cx, 'tcx> TypeFolder<'tcx> for Resolver<'cx, 'tcx> { fn tcx<'a>(&'a self) -> &'a ty::ctxt<'tcx> { self.tcx } fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> { if !ty::type_needs_infer(t) { return t; } match resolve_type(self.infcx, None, t, resolve_all | force_all) { Ok(t) => t, Err(e) => { self.report_error(e); ty::mk_err() } } } fn fold_region(&mut self, r: ty::Region) -> ty::Region { match resolve_region(self.infcx, r, resolve_all | force_all) { Ok(r) => r, Err(e) => { self.report_error(e); ty::ReStatic } } } } /////////////////////////////////////////////////////////////////////////// // During type check, we store promises with the result of trait // lookup rather than the actual results (because the results are not // necessarily available immediately). These routines unwind the // promises. It is expected that we will have already reported any // errors that may be encountered, so if the promises store an error, // a dummy result is returned.
Java
# Brevichara H. Horn af Rantzien, 1956 GENUS #### Status ACCEPTED #### According to Interim Register of Marine and Nonmarine Genera #### Published in null #### Original name null ### Remarks null
Java
# Schismus patens J.Presl SPECIES #### Status SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
Java
# Javorkaea hondurensis (Donn.Sm.) Borhidi & Komlódi SPECIES #### Status SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
Java
# Kentrosphaera A. Borzì, 1883 GENUS #### Status ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
Java
# Borreria lagurus S.Moore SPECIES #### Status SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
Java
# Mimosa callidryas Barneby SPECIES #### Status ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
Java
# Ligularia fangiana Hand.-Mazz. SPECIES #### Status ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
Java
# Couroupita cutteri C.V.Morton & Skutch SPECIES #### Status SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
Java
# Viola robusta Hillebr. SPECIES #### Status SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in F. Hawaiian Isl. 16. 1888 #### Original name null ### Remarks null
Java
'use strict'; module.exports = function (grunt) { grunt.config( 'a11y', { live: { options: { urls: ['www.google.com'] } } }); };
Java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.tez.dag.api; import java.io.IOException; import java.nio.ByteBuffer; import org.apache.tez.common.TezCommonUtils; import org.apache.tez.dag.api.records.DAGProtos.TezEntityDescriptorProto; import org.junit.Assert; import org.junit.Test; public class TestDagTypeConverters { @Test(timeout = 5000) public void testTezEntityDescriptorSerialization() throws IOException { UserPayload payload = UserPayload.create(ByteBuffer.wrap(new String("Foobar").getBytes()), 100); String historytext = "Bar123"; EntityDescriptor entityDescriptor = InputDescriptor.create("inputClazz").setUserPayload(payload) .setHistoryText(historytext); TezEntityDescriptorProto proto = DagTypeConverters.convertToDAGPlan(entityDescriptor); Assert.assertEquals(payload.getVersion(), proto.getTezUserPayload().getVersion()); Assert.assertArrayEquals(payload.deepCopyAsArray(), proto.getTezUserPayload().getUserPayload().toByteArray()); Assert.assertTrue(proto.hasHistoryText()); Assert.assertNotEquals(historytext, proto.getHistoryText()); Assert.assertEquals(historytext, new String( TezCommonUtils.decompressByteStringToByteArray(proto.getHistoryText()))); // Ensure that the history text is not deserialized InputDescriptor inputDescriptor = DagTypeConverters.convertInputDescriptorFromDAGPlan(proto); Assert.assertNull(inputDescriptor.getHistoryText()); } }
Java
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.component.jetty; import java.util.Map; import org.apache.camel.Exchange; import org.apache.camel.Processor; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.impl.JndiRegistry; import org.junit.Test; /** * @version */ public class HttpFilterCamelHeadersTest extends BaseJettyTest { @Test public void testFilterCamelHeaders() throws Exception { Exchange out = template.send("http://localhost:{{port}}/test/filter", new Processor() { public void process(Exchange exchange) throws Exception { exchange.getIn().setBody("Claus"); exchange.getIn().setHeader("bar", 123); } }); assertNotNull(out); assertEquals("Hi Claus", out.getOut().getBody(String.class)); // there should be no internal Camel headers // except for the response code Map<String, Object> headers = out.getOut().getHeaders(); for (String key : headers.keySet()) { if (!key.equalsIgnoreCase(Exchange.HTTP_RESPONSE_CODE)) { assertTrue("Should not contain any Camel internal headers", !key.toLowerCase().startsWith("camel")); } else { assertEquals(200, headers.get(Exchange.HTTP_RESPONSE_CODE)); } } } @Override protected JndiRegistry createRegistry() throws Exception { JndiRegistry jndi = super.createRegistry(); jndi.bind("foo", new MyFooBean()); return jndi; } @Override protected RouteBuilder createRouteBuilder() throws Exception { return new RouteBuilder() { @Override public void configure() throws Exception { from("jetty:http://localhost:{{port}}/test/filter").beanRef("foo"); } }; } public static class MyFooBean { public String hello(String name) { return "Hi " + name; } } }
Java
package org.lightadmin.core.view.preparer; import org.apache.tiles.AttributeContext; import org.apache.tiles.context.TilesRequestContext; import org.lightadmin.core.config.domain.DomainTypeAdministrationConfiguration; public class FormViewPreparer extends ConfigurationAwareViewPreparer { @Override protected void execute(final TilesRequestContext tilesContext, final AttributeContext attributeContext, final DomainTypeAdministrationConfiguration configuration) { super.execute(tilesContext, attributeContext, configuration); addAttribute(attributeContext, "fields", configuration.getFormViewFragment().getFields()); } }
Java
""" Support for EBox. Get data from 'My Usage Page' page: https://client.ebox.ca/myusage For more details about this platform, please refer to the documentation at https://home-assistant.io/components/sensor.ebox/ """ import logging from datetime import timedelta import voluptuous as vol import homeassistant.helpers.config_validation as cv from homeassistant.components.sensor import PLATFORM_SCHEMA from homeassistant.const import ( CONF_USERNAME, CONF_PASSWORD, CONF_NAME, CONF_MONITORED_VARIABLES, ) from homeassistant.helpers.entity import Entity from homeassistant.util import Throttle from homeassistant.exceptions import PlatformNotReady _LOGGER = logging.getLogger(__name__) GIGABITS = "Gb" PRICE = "CAD" DAYS = "days" PERCENT = "%" DEFAULT_NAME = "EBox" REQUESTS_TIMEOUT = 15 SCAN_INTERVAL = timedelta(minutes=15) MIN_TIME_BETWEEN_UPDATES = timedelta(minutes=15) SENSOR_TYPES = { "usage": ["Usage", PERCENT, "mdi:percent"], "balance": ["Balance", PRICE, "mdi:square-inc-cash"], "limit": ["Data limit", GIGABITS, "mdi:download"], "days_left": ["Days left", DAYS, "mdi:calendar-today"], "before_offpeak_download": ["Download before offpeak", GIGABITS, "mdi:download"], "before_offpeak_upload": ["Upload before offpeak", GIGABITS, "mdi:upload"], "before_offpeak_total": ["Total before offpeak", GIGABITS, "mdi:download"], "offpeak_download": ["Offpeak download", GIGABITS, "mdi:download"], "offpeak_upload": ["Offpeak Upload", GIGABITS, "mdi:upload"], "offpeak_total": ["Offpeak Total", GIGABITS, "mdi:download"], "download": ["Download", GIGABITS, "mdi:download"], "upload": ["Upload", GIGABITS, "mdi:upload"], "total": ["Total", GIGABITS, "mdi:download"], } PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( { vol.Required(CONF_MONITORED_VARIABLES): vol.All( cv.ensure_list, [vol.In(SENSOR_TYPES)] ), vol.Required(CONF_USERNAME): cv.string, vol.Required(CONF_PASSWORD): cv.string, vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, } ) async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Set up the EBox sensor.""" username = config.get(CONF_USERNAME) password = config.get(CONF_PASSWORD) httpsession = hass.helpers.aiohttp_client.async_get_clientsession() ebox_data = EBoxData(username, password, httpsession) name = config.get(CONF_NAME) from pyebox.client import PyEboxError try: await ebox_data.async_update() except PyEboxError as exp: _LOGGER.error("Failed login: %s", exp) raise PlatformNotReady sensors = [] for variable in config[CONF_MONITORED_VARIABLES]: sensors.append(EBoxSensor(ebox_data, variable, name)) async_add_entities(sensors, True) class EBoxSensor(Entity): """Implementation of a EBox sensor.""" def __init__(self, ebox_data, sensor_type, name): """Initialize the sensor.""" self.client_name = name self.type = sensor_type self._name = SENSOR_TYPES[sensor_type][0] self._unit_of_measurement = SENSOR_TYPES[sensor_type][1] self._icon = SENSOR_TYPES[sensor_type][2] self.ebox_data = ebox_data self._state = None @property def name(self): """Return the name of the sensor.""" return f"{self.client_name} {self._name}" @property def state(self): """Return the state of the sensor.""" return self._state @property def unit_of_measurement(self): """Return the unit of measurement of this entity, if any.""" return self._unit_of_measurement @property def icon(self): """Icon to use in the frontend, if any.""" return self._icon async def async_update(self): """Get the latest data from EBox and update the state.""" await self.ebox_data.async_update() if self.type in self.ebox_data.data: self._state = round(self.ebox_data.data[self.type], 2) class EBoxData: """Get data from Ebox.""" def __init__(self, username, password, httpsession): """Initialize the data object.""" from pyebox import EboxClient self.client = EboxClient(username, password, REQUESTS_TIMEOUT, httpsession) self.data = {} @Throttle(MIN_TIME_BETWEEN_UPDATES) async def async_update(self): """Get the latest data from Ebox.""" from pyebox.client import PyEboxError try: await self.client.fetch_data() except PyEboxError as exp: _LOGGER.error("Error on receive last EBox data: %s", exp) return # Update data self.data = self.client.get_data()
Java
# Eriosyce aspillagae subsp. aspillagae SUBSPECIES #### Status ACCEPTED #### According to NUB Generator [autonym] #### Published in null #### Original name null ### Remarks null
Java
/* * Licensed to The Apereo Foundation under one or more contributor license * agreements. See the NOTICE file distributed with this work for * additional information regarding copyright ownership. * * The Apereo Foundation 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.unitime.timetable.solver.exam.ui; import java.io.PrintWriter; import java.io.Serializable; import java.util.Collection; import java.util.Collections; import java.util.Enumeration; import java.util.HashSet; import java.util.Hashtable; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; import java.util.Vector; import javax.servlet.jsp.JspWriter; import org.cpsolver.exam.model.Exam; import org.cpsolver.exam.model.ExamDistributionConstraint; import org.cpsolver.exam.model.ExamInstructor; import org.cpsolver.exam.model.ExamPlacement; import org.cpsolver.exam.model.ExamRoom; import org.cpsolver.exam.model.ExamRoomPlacement; import org.cpsolver.exam.model.ExamStudent; import org.cpsolver.ifs.extension.AssignedValue; import org.cpsolver.ifs.extension.ConflictStatistics; import org.cpsolver.ifs.model.Constraint; import org.dom4j.Element; import org.unitime.timetable.model.PreferenceLevel; import org.unitime.timetable.solver.ui.TimetableInfo; import org.unitime.timetable.webutil.timegrid.ExamGridTable; /** * @author Tomas Muller */ public class ExamConflictStatisticsInfo implements TimetableInfo, Serializable { private static final long serialVersionUID = 7L; public static int sVersion = 7; // to be able to do some changes in the future public static final int sConstraintTypeRoom = 1; public static final int sConstraintTypeInstructor = 2; public static final int sConstraintTypeGroup = 3; public static final int sConstraintTypeStudent = 4; private Hashtable iVariables = new Hashtable(); public Collection getCBS() { return iVariables.values(); } public CBSVariable getCBS(Long classId) { return (CBSVariable)iVariables.get(classId); } public void load(ConflictStatistics cbs) { load(cbs, null); } public ExamConflictStatisticsInfo getConflictStatisticsSubInfo(Vector variables) { ExamConflictStatisticsInfo ret = new ExamConflictStatisticsInfo(); for (Enumeration e=variables.elements();e.hasMoreElements();) { Exam exam = (Exam)e.nextElement(); CBSVariable var = (CBSVariable)iVariables.get(exam.getId()); if (var!=null) ret.iVariables.put(exam.getId(),var); } return ret; } public void merge(ExamConflictStatisticsInfo info) { if (info!=null) iVariables.putAll(info.iVariables); } public void load(ConflictStatistics cbs, Long examId) { iVariables.clear(); for (Iterator i1=cbs.getNoGoods().entrySet().iterator();i1.hasNext();) { Map.Entry entry = (Map.Entry)i1.next(); AssignedValue assignment = (AssignedValue)entry.getKey(); ExamPlacement placement = (ExamPlacement)assignment.getValue(); Exam exam = (Exam)placement.variable(); if (examId!=null && !examId.equals(exam.getId())) continue; CBSVariable var = (CBSVariable)iVariables.get(exam.getId()); if (var==null) { String pref = PreferenceLevel.sNeutral;//SolverGridModel.hardConflicts2pref(exam,null); var = new CBSVariable(exam.getId(),exam.getName(),pref); iVariables.put(exam.getId(),var); } Vector roomIds = new Vector(); Vector roomNames = new Vector(); Vector roomPrefs = new Vector(); for (Iterator i=new TreeSet(placement.getRoomPlacements()).iterator();i.hasNext();) { ExamRoomPlacement room = (ExamRoomPlacement)i.next(); roomIds.add(room.getId()); roomNames.add(room.getName()); roomPrefs.add(exam.getRoomPlacements().size()==placement.getRoomPlacements().size()?PreferenceLevel.sIntLevelRequired:room.getPenalty(placement.getPeriod())); } CBSValue val = new CBSValue(var, placement.getPeriod().getId(), placement.getPeriod().getDayStr()+" "+placement.getPeriod().getTimeStr(), (exam.getPeriodPlacements().size()==1?PreferenceLevel.sIntLevelRequired:placement.getPeriodPlacement().getPenalty()), roomIds, roomNames, roomPrefs); var.values().add(val); List noGoods = (List)entry.getValue(); Hashtable constr2assignments = new Hashtable(); for (Iterator e2=noGoods.iterator();e2.hasNext();) { AssignedValue noGood = (AssignedValue)e2.next(); if (noGood.getConstraint()==null) continue; Vector aaa = (Vector)constr2assignments.get(noGood.getConstraint()); if (aaa == null) { aaa = new Vector(); constr2assignments.put(noGood.getConstraint(), aaa); } aaa.addElement(noGood); } for (Iterator i2=constr2assignments.entrySet().iterator();i2.hasNext();) { Map.Entry entry2 = (Map.Entry)i2.next(); Constraint constraint = (Constraint)entry2.getKey(); Vector noGoodsThisConstraint = (Vector)entry2.getValue(); CBSConstraint con = null; if (constraint instanceof ExamRoom) { con = new CBSConstraint(val, sConstraintTypeRoom, constraint.getId(), constraint.getName(), PreferenceLevel.sRequired); } else if (constraint instanceof ExamInstructor) { con = new CBSConstraint(val, sConstraintTypeInstructor, constraint.getId(), constraint.getName(), PreferenceLevel.sRequired); } else if (constraint instanceof ExamStudent) { con = new CBSConstraint(val, sConstraintTypeStudent, constraint.getId(), constraint.getName(), PreferenceLevel.sRequired); } else if (constraint instanceof ExamDistributionConstraint) { con = new CBSConstraint(val, sConstraintTypeGroup, constraint.getId(), ((ExamDistributionConstraint)constraint).getTypeString(), (constraint.isHard()?PreferenceLevel.sRequired:PreferenceLevel.int2prolog(((ExamDistributionConstraint)constraint).getWeight()))); } else { con = new CBSConstraint(val, -1, constraint.getId(), constraint.getName(), PreferenceLevel.sRequired); } val.constraints().add(con); for (Enumeration e3=noGoodsThisConstraint.elements();e3.hasMoreElements();) { AssignedValue ass = (AssignedValue)e3.nextElement(); ExamPlacement p = (ExamPlacement)ass.getValue(); Exam x = (Exam)p.variable(); String pr = PreferenceLevel.sNeutral;//SolverGridModel.hardConflicts2pref(x,p); Vector aroomIds = new Vector(); Vector aroomNames = new Vector(); Vector aroomPrefs = new Vector(); for (Iterator i=new TreeSet(p.getRoomPlacements()).iterator();i.hasNext();) { ExamRoomPlacement room = (ExamRoomPlacement)i.next(); aroomIds.add(room.getId()); aroomNames.add(room.getName()); aroomPrefs.add(x.getRoomPlacements().size()==p.getRoomPlacements().size()?PreferenceLevel.sIntLevelRequired:room.getPenalty(p.getPeriod())); } CBSAssignment a = new CBSAssignment(con, x.getId(), x.getName(), pr, p.getPeriod().getId(), p.getPeriod().getDayStr()+" "+p.getPeriod().getTimeStr(), (x.getPeriodPlacements().size()==1?PreferenceLevel.sIntLevelRequired:p.getPeriodPlacement().getPenalty()), aroomIds, aroomNames, aroomPrefs); con.assignments().add(a); a.incCounter((int)ass.getCounter(0)); } } } } public void load(Element root) { int version = Integer.parseInt(root.attributeValue("version")); if (version==sVersion) { iVariables.clear(); for (Iterator i1=root.elementIterator("var");i1.hasNext();) { CBSVariable var = new CBSVariable((Element)i1.next()); iVariables.put(Long.valueOf(var.getId()),var); } } } public void save(Element root) { root.addAttribute("version", String.valueOf(sVersion)); for (Iterator i1=iVariables.values().iterator();i1.hasNext();) { ((CBSVariable)i1.next()).save(root.addElement("var")); } } public static interface Counter { public int getCounter(); public void incCounter(int value); } public static class CBSVariable implements Counter, Comparable, Serializable { private static final long serialVersionUID = 1L; int iCounter = 0; long iExamId; String iName; HashSet iValues = new HashSet(); CBSConstraint iConstraint = null; String iPref = null; CBSVariable(long examId, String name, String pref) { iExamId = examId; iName = name; iPref = pref; } CBSVariable(CBSConstraint constraint, long classId, String examId, String pref) { iConstraint = constraint; iExamId = classId; iName = examId; iPref = pref; } CBSVariable(Element element) { iExamId = Long.parseLong(element.attributeValue("exam")); iName = element.attributeValue("name"); iPref = element.attributeValue("pref"); for (Iterator i=element.elementIterator("val");i.hasNext();) iValues.add(new CBSValue(this,(Element)i.next())); } public long getId() { return iExamId; } public int getCounter() { return iCounter; } public String getName() { return iName; } public String getPref() { return iPref; } public void incCounter(int value) { iCounter+=value; if (iConstraint!=null) iConstraint.incCounter(value); } public Set values() { return iValues; } public int hashCode() { return (Long.valueOf(iExamId)).hashCode(); } public boolean equals(Object o) { if (o==null || !(o instanceof CBSVariable)) return false; return ((CBSVariable)o).getId()==getId(); } public int compareTo(Object o) { if (o==null || !(o instanceof CBSVariable)) return -1; int ret = -(Integer.valueOf(iCounter)).compareTo(Integer.valueOf(((CBSVariable)o).getCounter())); if (ret!=0) return ret; return toString().compareTo(o.toString()); } public String toString() { return iName; } public void save(Element element) { element.addAttribute("exam",String.valueOf(iExamId)); element.addAttribute("name", iName); if (iPref!=null) element.addAttribute("pref", iPref); for (Iterator i=iValues.iterator();i.hasNext();) ((CBSValue)i.next()).save(element.addElement("val")); } } public static class CBSValue implements Counter, Comparable, Serializable { private static final long serialVersionUID = 1L; int iCounter = 0; Long iPeriodId; String iPeriodName; int iPeriodPref; Vector iRoomIds; String iInstructorName = null; Vector iRoomNames; Vector iRoomPrefs; CBSVariable iVariable = null; HashSet iConstraints = new HashSet(); HashSet iAssignments = new HashSet(); int iLength; CBSValue(CBSVariable var, Long periodId, String periodName, int periodPref, Vector roomIds, Vector roomNames, Vector roomPrefs) { iVariable = var; iRoomIds = roomIds; iRoomNames = roomNames; iRoomPrefs = roomPrefs; iPeriodId = periodId; iPeriodName = periodName; iPeriodPref = periodPref; } CBSValue(CBSVariable var, Element element) { iVariable = var; iPeriodId = Long.valueOf(element.attributeValue("period")); iPeriodName = element.attributeValue("name"); iPeriodPref = Integer.parseInt(element.attributeValue("pref")); iRoomIds = new Vector(); iRoomNames = new Vector(); iRoomPrefs = new Vector(); for (Iterator i=element.elementIterator("room");i.hasNext();) { Element r = (Element)i.next(); iRoomIds.addElement(Integer.valueOf(r.attributeValue("id"))); iRoomNames.addElement(r.attributeValue("name")); iRoomPrefs.addElement(Integer.valueOf(r.attributeValue("pref"))); } for (Iterator i=element.elementIterator("cons");i.hasNext();) iConstraints.add(new CBSConstraint(this,(Element)i.next())); } public CBSVariable variable() { return iVariable; } public Long getPeriodId() { return iPeriodId; } public String getPeriodName() { return iPeriodName; } public int getPeriodPref() { return iPeriodPref; } public Vector getRoomNames() { return iRoomNames; } public Vector getRoomPrefs() { return iRoomPrefs; } public String toString() { return iPeriodName+" "+iRoomNames; } public int getCounter() { return iCounter; } public void incCounter(int value) { iCounter+=value; if (iVariable!=null) iVariable.incCounter(value); } public Vector getRoomIds() { return iRoomIds; } public Set constraints() { return iConstraints; } public Set assignments() { return iAssignments; } public int hashCode() { return combine(iPeriodId.hashCode(), (iRoomIds==null?0:iRoomIds.hashCode())); } public boolean equals(Object o) { if (o==null || !(o instanceof CBSValue)) return false; CBSValue v = (CBSValue)o; return v.getRoomIds().equals(getRoomIds()) && v.getPeriodId().equals(getPeriodId()); } public int compareTo(Object o) { if (o==null || !(o instanceof CBSValue)) return -1; int ret = -(Integer.valueOf(iCounter)).compareTo(Integer.valueOf(((CBSValue)o).getCounter())); if (ret!=0) return ret; return toString().compareTo(o.toString()); } public void save(Element element) { element.addAttribute("period",String.valueOf(iPeriodId)); element.addAttribute("pref",String.valueOf(iPeriodPref)); element.addAttribute("name", iPeriodName); for (int i=0;i<iRoomIds.size();i++) { Element r = element.addElement("room"); r.addAttribute("id",iRoomIds.elementAt(i).toString()); r.addAttribute("name",iRoomNames.elementAt(i).toString()); r.addAttribute("pref",iRoomPrefs.elementAt(i).toString()); } for (Iterator i=iConstraints.iterator();i.hasNext();) ((CBSConstraint)i.next()).save(element.addElement("cons")); } } public static class CBSConstraint implements Counter, Comparable, Serializable { private static final long serialVersionUID = 1L; CBSValue iValue; int iCounter = 0; long iId; String iName = null; int iType; HashSet iAssignments = new HashSet(); HashSet iVariables = new HashSet(); String iPref; CBSConstraint(int type, long id, String name, String pref) { iId = id; iType = type; iName = name; iPref = pref; } CBSConstraint(CBSValue value, int type, long id, String name, String pref) { iId = id; iType = type; iValue = value; iName = name; iPref = pref; } CBSConstraint(CBSValue value, Element element) { iValue = value; iId = Integer.parseInt(element.attributeValue("id")); iType = Integer.parseInt(element.attributeValue("type")); iName = element.attributeValue("name"); iPref = element.attributeValue("pref"); for (Iterator i=element.elementIterator("nogood");i.hasNext();) iAssignments.add(new CBSAssignment(this,(Element)i.next())); } public long getId() { return iId; } public int getType() { return iType; } public String getName() { return iName; } public CBSValue value() { return iValue; } public Set variables() { return iVariables; } public Set assignments() { return iAssignments; } public String getPref() { return iPref; } public int getCounter() { return iCounter; } public void incCounter(int value) { iCounter+=value; if (iValue!=null) iValue.incCounter(value); } public int hashCode() { return combine((int)iId,iType); } public boolean equals(Object o) { if (o==null || !(o instanceof CBSConstraint)) return false; CBSConstraint c = (CBSConstraint)o; return c.getId()==getId() && c.getType()==getType(); } public int compareTo(Object o) { if (o==null || !(o instanceof CBSConstraint)) return -1; int ret = -(Integer.valueOf(iCounter)).compareTo(Integer.valueOf(((CBSConstraint)o).getCounter())); if (ret!=0) return ret; return toString().compareTo(o.toString()); } public void save(Element element) { element.addAttribute("id",String.valueOf(iId)); element.addAttribute("type",String.valueOf(iType)); if (iName!=null) element.addAttribute("name", iName); if (iPref!=null) element.addAttribute("pref", iPref); for (Iterator i=iAssignments.iterator();i.hasNext();) ((CBSAssignment)i.next()).save(element.addElement("nogood")); } } public static class CBSAssignment implements Counter, Comparable, Serializable { private static final long serialVersionUID = 1L; CBSConstraint iConstraint; Long iExamId; String iExamName; String iExamPref; Long iPeriodId; String iPeriodName; int iPeriodPref; int iCounter = 0; Vector iRoomIds; Vector iRoomPrefs; Vector iRoomNames; CBSAssignment(CBSConstraint constraint, Long examId, String examName, String examPref, Long periodId, String periodName, int periodPref, Vector roomIds, Vector roomNames, Vector roomPrefs) { iExamId = examId; iExamName = examName; iExamPref = examPref; iPeriodId = periodId; iPeriodName = periodName; iPeriodPref = periodPref; iRoomIds = roomIds; iRoomNames = roomNames; iRoomPrefs = roomPrefs; iConstraint = constraint; } CBSAssignment(CBSConstraint constraint, Element element) { iConstraint = constraint; iExamId = Long.valueOf(element.attributeValue("exam")); iExamName = element.attributeValue("name"); iExamPref = element.attributeValue("pref"); iRoomIds = new Vector(); iRoomNames = new Vector(); iRoomPrefs = new Vector(); for (Iterator i=element.elementIterator("room");i.hasNext();) { Element r = (Element)i.next(); iRoomIds.addElement(Integer.valueOf(r.attributeValue("id"))); iRoomNames.addElement(r.attributeValue("name")); iRoomPrefs.addElement(Integer.valueOf(r.attributeValue("pref"))); } iPeriodId = Long.valueOf(element.attributeValue("period")); iPeriodName = element.attributeValue("periodName"); iPeriodPref = Integer.parseInt(element.attributeValue("periodPref")); incCounter(Integer.parseInt(element.attributeValue("cnt"))); } public Long getId() { return iExamId; } public CBSConstraint getConstraint() { return iConstraint; } public String getName() { return iExamName; } public String getPref() { return iExamPref; } public Long getPeriodId() { return iPeriodId; } public String getPeriodName() { return iPeriodName; } public int getPeriodPref() { return iPeriodPref; } public String toString() { return iExamName+" "+iPeriodName+" "+iRoomNames; } public Vector getRoomNames() { return iRoomNames; } public Vector getRoomIds() { return iRoomIds; } public Vector getRoomPrefs() { return iRoomPrefs; } public int hashCode() { return combine(iExamId.hashCode(),combine(iRoomIds.hashCode(),iPeriodId.hashCode())); } public int getCounter() { return iCounter; } public void incCounter(int value) { iCounter+=value; if (iConstraint!=null) iConstraint.incCounter(value); } public boolean equals(Object o) { if (o==null || !(o instanceof CBSAssignment)) return false; CBSAssignment a = (CBSAssignment)o; return a.getId().equals(getId()) && a.getRoomIds().equals(getRoomIds()) && a.getPeriodId().equals(getPeriodId()); } public int compareTo(Object o) { if (o==null || !(o instanceof CBSAssignment)) return -1; int ret = -(Integer.valueOf(iCounter)).compareTo(Integer.valueOf(((CBSAssignment)o).getCounter())); if (ret!=0) return ret; return toString().compareTo(o.toString()); } public void save(Element element) { element.addAttribute("exam",String.valueOf(iExamId)); element.addAttribute("name",iExamName); element.addAttribute("pref",iExamPref); for (int i=0;i<iRoomIds.size();i++) { Element r = element.addElement("room"); r.addAttribute("id",iRoomIds.elementAt(i).toString()); r.addAttribute("name",iRoomNames.elementAt(i).toString()); r.addAttribute("pref",iRoomPrefs.elementAt(i).toString()); } element.addAttribute("period", String.valueOf(iPeriodId)); element.addAttribute("periodName", iPeriodName); element.addAttribute("periodPref", String.valueOf(iPeriodPref)); element.addAttribute("cnt", String.valueOf(iCounter)); } } private static int combine(int a, int b) { int ret = 0; for (int i=0;i<15;i++) ret = ret | ((a & (1<<i))<<i) | ((b & (1<<i))<<(i+1)); return ret; } //--------- toHtml ------------------------------------------------- private static String IMG_BASE = "images/"; private static String IMG_EXPAND = IMG_BASE+"expand_node_btn.gif"; private static String IMG_COLLAPSE = IMG_BASE+"collapse_node_btn.gif"; private static String IMG_LEAF = IMG_BASE+"end_node_btn.gif"; public static int TYPE_VARIABLE_BASED = 0; public static int TYPE_CONSTRAINT_BASED = 1; private void menu_item(PrintWriter out, String id, String name, String description, String page, boolean isCollapsed) { out.println("<div style=\"margin-left:5px;\">"); out.println("<A style=\"border:0;background:0\" id=\"__idMenu"+id+"\" href=\"javascript:toggle('"+id+"')\" name=\""+name+"\">"); out.println("<img id=\"__idMenuImg"+id+"\" border=\"0\" src=\""+(isCollapsed ? IMG_EXPAND : IMG_COLLAPSE)+"\" align=\"absmiddle\"></A>"); out.println("&nbsp;<A class='noFancyLinks' target=\"__idContentFrame\" "+(page == null ? "" : page+" onmouseover=\"this.style.cursor='hand';this.style.cursor='pointer';\" ")+"title=\""+(description == null ? "" : description)+"\" >"+ name+(description == null?"":" <font color='gray'>[" + description + "]</font>")+"</A><br>"); out.println("</div>"); out.println("<div ID=\"__idMenuDiv"+id+"\" style=\"display:"+(isCollapsed ? "none" : "block")+";position:relative;margin-left:18px;\">"); } private void leaf_item(PrintWriter out, String name, String description, String page) { out.println("<div style=\"margin-left:5px;\">"); out.println("<img border=\"0\" src=\""+IMG_LEAF+"\" align=\"absmiddle\">"); out.println("&nbsp;<A class='noFancyLinks' target=\"__idContentFrame\" "+(page == null ? "" : page + " onmouseover=\"this.style.cursor='hand';this.style.cursor='pointer';\" ")+"title=\""+(description == null ? "" : description)+"\" >"+name+(description == null ? "" : " <font color='gray'>[" + description + "]</font>")+"</A><br>"); out.println("</div>"); } private void end_item(PrintWriter out) { out.println("</div>"); } private void unassignedVariableMenuItem(PrintWriter out, String menuId, CBSVariable variable, boolean clickable) { String name = "<font color='"+PreferenceLevel.prolog2color(variable.getPref())+"'>"+ variable.getName()+ "</font>"; String description = null; String onClick = null; if (clickable) onClick = "onclick=\"(parent ? parent : window).showGwtDialog('Examination Assignment', 'examInfo.do?examId="+variable.getId()+"&op=Reset','900','90%');\""; menu_item(out, menuId, variable.getCounter() + "&times; " + name, description, onClick, true); } private void unassignmentMenuItem(PrintWriter out, String menuId, CBSValue value, boolean clickable) { String name = "<font color='"+PreferenceLevel.int2color(value.getPeriodPref())+"'>"+ value.getPeriodName()+ "</font> "; String roomLink = ""; for (int i=0;i<value.getRoomIds().size();i++) { name += (i>0?", ":"")+"<font color='"+PreferenceLevel.int2color(((Integer)value.getRoomPrefs().elementAt(i)).intValue())+"'>"+ value.getRoomNames().elementAt(i)+"</font>"; roomLink += (i>0?":":"")+value.getRoomIds().elementAt(i); } String description = null; String onClick = null; if (clickable) onClick = "onclick=\"(parent ? parent : window).showGwtDialog('Examination Assignment', 'examInfo.do?examId="+value.variable().getId()+"&period="+value.getPeriodId()+"&room="+roomLink+"&op=Try&reset=1','900','90%');\""; menu_item(out, menuId, value.getCounter() + "&times; " + name, description, onClick, true); } private void constraintMenuItem(PrintWriter out, String menuId, CBSConstraint constraint, boolean clickable) { String name = "<font color='"+PreferenceLevel.prolog2color(constraint.getPref())+"'>"; String link = null; switch (constraint.getType()) { case sConstraintTypeGroup : name += "Distribution "+constraint.getName(); break; case sConstraintTypeInstructor : name += "Instructor "+constraint.getName(); if (clickable) link = "examGrid.do?filter="+constraint.getName()+"&resource="+ExamGridTable.sResourceInstructor+"&op=Cbs"; break; case sConstraintTypeRoom : name += "Room "+constraint.getName(); if (clickable) link = "examGrid.do?filter="+constraint.getName()+"&resource="+ExamGridTable.sResourceRoom+"&op=Cbs"; break; case sConstraintTypeStudent : name += "Student "+constraint.getName(); break; default : name += (constraint.getName()==null?"Unknown":constraint.getName()); } name += "</font>"; String description = null; String onClick = null; if (link!=null) onClick = "href=\""+link+"\""; menu_item(out, menuId, constraint.getCounter() + "&times; " + name, description, onClick, true); } private void assignmentLeafItem(PrintWriter out, CBSAssignment assignment, boolean clickable) { String name = "<font color='"+PreferenceLevel.prolog2color(assignment.getPref())+"'>"+ assignment.getName()+ "</font> &larr; "+ "<font color='"+PreferenceLevel.int2color(assignment.getPeriodPref())+"'>"+ assignment.getPeriodName()+ "</font> "; String roomLink = ""; for (int i=0;i<assignment.getRoomIds().size();i++) { name += (i>0?", ":"")+"<font color='"+PreferenceLevel.int2color(((Integer)assignment.getRoomPrefs().elementAt(i)).intValue())+"'>"+ assignment.getRoomNames().elementAt(i)+"</font>"; roomLink += (i>0?":":"")+assignment.getRoomIds().elementAt(i); } String onClick = null; if (clickable) onClick = "onclick=\"(parent ? parent : window).showGwtDialog('Examination Assignment', 'examInfo.do?examId="+assignment.getId()+"&period="+assignment.getPeriodId()+"&room="+roomLink+"&op=Try&reset=1','900','90%');\""; leaf_item(out, assignment.getCounter()+"&times; "+name, null, onClick); } public static void printHtmlHeader(JspWriter jsp) { PrintWriter out = new PrintWriter(jsp); printHtmlHeader(out, false); } public static void printHtmlHeader(PrintWriter out, boolean style) { if (style) { out.println("<style type=\"text/css\">"); out.println("<!--"); out.println("A:link { color: blue; text-decoration: none; border:0; background:0; }"); out.println("A:visited { color: blue; text-decoration: none; border:0; background:0; }"); out.println("A:active { color: blue; text-decoration: none; border:0; background:0; }"); out.println("A:hover { color: blue; text-decoration: none; border:0; background:0; }"); out.println(".TextBody { background-color: white; color:black; font-size: 12px; }"); out.println(".WelcomeHead { color: black; margin-top: 0px; margin-left: 0px; font-weight: bold; text-align: right; font-size: 30px; font-family: Comic Sans MS}"); out.println("-->"); out.println("</style>"); out.println(); } out.println("<script language=\"javascript\" type=\"text/javascript\">"); out.println("function toggle(item) {"); out.println(" obj=document.getElementById(\"__idMenuDiv\"+item);"); out.println(" visible=(obj.style.display!=\"none\");"); out.println(" img=document.getElementById(\"__idMenuImg\" + item);"); out.println(" menu=document.getElementById(\"__idMenu\" + item);"); out.println(" if (visible) {obj.style.display=\"none\";img.src=\""+IMG_EXPAND+"\";}"); out.println(" else {obj.style.display=\"block\";img.src=\""+IMG_COLLAPSE+"\";}"); out.println("}"); out.println("</script>"); out.flush(); } private Vector filter(Collection counters, double limit) { Vector cnt = new Vector(counters); Collections.sort(cnt); int total = 0; for (Enumeration e=cnt.elements();e.hasMoreElements();) total += ((Counter)e.nextElement()).getCounter(); int totalLimit = (int)Math.ceil(limit*total); int current = 0; Vector ret = new Vector(); for (Enumeration e=cnt.elements();e.hasMoreElements();) { Counter c = (Counter)e.nextElement(); ret.addElement(c); current += c.getCounter(); if (current>=totalLimit) break; } return ret; } /** Print conflict-based statistics in HTML format */ public void printHtml(JspWriter jsp, double limit, int type, boolean clickable) { printHtml(jsp, null, new double[] {limit,limit,limit,limit}, type, clickable); } /** Print conflict-based statistics in HTML format */ public void printHtml(PrintWriter out, double limit, int type, boolean clickable) { printHtml(out, null, new double[] {limit,limit,limit,limit}, type, clickable); } /** Print conflict-based statistics in HTML format */ public void printHtml(JspWriter jsp, double[] limit, int type, boolean clickable) { printHtml(jsp, null, limit, type, clickable); } /** Print conflict-based statistics in HTML format */ public void printHtml(PrintWriter out, double[] limit, int type, boolean clickable) { printHtml(out, null, limit, type, clickable); } /** Print conflict-based statistics in HTML format */ public void printHtml(JspWriter jsp, Long classId, double limit, int type, boolean clickable) { printHtml(jsp, classId, new double[] {limit,limit,limit,limit}, type, clickable); } /** Print conflict-based statistics in HTML format */ public void printHtml(PrintWriter out, Long classId, double limit, int type, boolean clickable) { printHtml(out, classId, new double[] {limit,limit,limit,limit}, type, clickable); } /** Print conflict-based statistics in HTML format */ public void printHtml(JspWriter jsp, Long classId, double[] limit, int type, boolean clickable) { PrintWriter out = new PrintWriter(jsp); printHtml(out, classId, limit, type, clickable); } /** Print conflict-based statistics in HTML format */ public void printHtml(PrintWriter out, Long classId, double[] limit, int type, boolean clickable) { if (type == TYPE_VARIABLE_BASED) { Vector vars = filter(iVariables.values(), limit[0]); if (classId!=null) { CBSVariable var = (CBSVariable)iVariables.get(classId); vars.clear(); if (var!=null) vars.add(var); } for (Enumeration e1 = vars.elements(); e1.hasMoreElements();) { CBSVariable variable = (CBSVariable)e1.nextElement(); String m1 = String.valueOf(variable.getId()); if (classId==null) unassignedVariableMenuItem(out,m1,variable, clickable); Vector vals = filter(variable.values(), limit[1]); int id = 0; for (Enumeration e2 = vals.elements();e2.hasMoreElements();) { CBSValue value = (CBSValue)e2.nextElement(); String m2 = m1+"."+(id++); unassignmentMenuItem(out,m2,value, clickable); Vector constraints =filter(value.constraints(),limit[2]); for (Enumeration e3 = constraints.elements(); e3.hasMoreElements();) { CBSConstraint constraint = (CBSConstraint)e3.nextElement(); String m3 = m2 + constraint.getType()+"."+constraint.getId(); constraintMenuItem(out,m3,constraint, clickable); Vector assignments = filter(constraint.assignments(),limit[3]); for (Enumeration e4 = assignments.elements();e4.hasMoreElements();) { CBSAssignment assignment = (CBSAssignment)e4.nextElement(); assignmentLeafItem(out, assignment, clickable); } end_item(out); } end_item(out); } end_item(out); } } else if (type == TYPE_CONSTRAINT_BASED) { Hashtable constraints = new Hashtable(); for (Enumeration e1 = iVariables.elements(); e1.hasMoreElements();) { CBSVariable variable = (CBSVariable)e1.nextElement(); if (classId!=null && classId.longValue()!=variable.getId()) continue; for (Iterator e2=variable.values().iterator();e2.hasNext();) { CBSValue value = (CBSValue)e2.next(); for (Iterator e3=value.constraints().iterator();e3.hasNext();) { CBSConstraint constraint = (CBSConstraint)e3.next(); CBSConstraint xConstraint = (CBSConstraint)constraints.get(constraint.getType()+"."+constraint.getId()); if (xConstraint==null) { xConstraint = new CBSConstraint(constraint.getType(),constraint.getId(),constraint.getName(),constraint.getPref()); constraints.put(constraint.getType()+"."+constraint.getId(),xConstraint); } CBSVariable xVariable = null; for (Iterator i=xConstraint.variables().iterator();i.hasNext();) { CBSVariable v = (CBSVariable)i.next(); if (v.getId()==variable.getId()) { xVariable = v; break; } } if (xVariable==null) { xVariable = new CBSVariable(xConstraint,variable.getId(),variable.getName(),variable.getPref()); xConstraint.variables().add(xVariable); } CBSValue xValue = new CBSValue(xVariable, value.getPeriodId(), value.getPeriodName(), value.getPeriodPref(), value.getRoomIds(), value.getRoomNames(), value.getRoomPrefs()); xVariable.values().add(xValue); for (Iterator e4=constraint.assignments().iterator();e4.hasNext();) { CBSAssignment assignment = (CBSAssignment)e4.next(); xValue.assignments().add(assignment); xValue.incCounter(assignment.getCounter()); } } } } Vector consts = filter(constraints.values(), limit[0]); for (Enumeration e1 = consts.elements(); e1.hasMoreElements();) { CBSConstraint constraint = (CBSConstraint)e1.nextElement(); String m1 = constraint.getType()+"."+constraint.getId(); constraintMenuItem(out,m1,constraint, clickable); Vector variables = filter(constraint.variables(), limit[1]); Collections.sort(variables); for (Enumeration e2 = variables.elements(); e2.hasMoreElements();) { CBSVariable variable = (CBSVariable)e2.nextElement(); String m2 = m1+"."+variable.getId(); if (classId==null) unassignedVariableMenuItem(out,m2,variable, clickable); Vector vals = filter(variable.values(), limit[2]); int id = 0; for (Enumeration e3 = vals.elements();e3.hasMoreElements();) { CBSValue value = (CBSValue)e3.nextElement(); String m3 = m2+"."+(id++); unassignmentMenuItem(out,m3,value, clickable); Vector assignments = filter(value.assignments(), limit[3]); for (Enumeration e4 = assignments.elements();e4.hasMoreElements();) { CBSAssignment assignment = (CBSAssignment)e4.nextElement(); assignmentLeafItem(out, assignment, clickable); } end_item(out); } if (classId==null) end_item(out); } end_item(out); } } out.flush(); } public boolean saveToFile() { return true; } }
Java
#ifndef _CUFTPD_H #define _CUFTPD_H #define CUFTPD_DEBUG(fmt, ...) cuftpd_debug(__FILE__, __LINE__, fmt, __VA_ARGS__) #define CUFTPD_ARR_LEN(arr) (sizeof(arr)/sizeof(arr[0])) #define CUFTPD_VER "1.0" #define CUFTPD_DEF_SRV_PORT 21 #define CUFTPD_LISTEN_QU_LEN 8 #define CUFTPD_LINE_END "\r\n" #define CUFTPD_OK 0 #define CUFTPD_ERR (-1) #define CUFTPD_CHECK_LOGIN() \ do { \ if (!cuftpd_cur_user) { \ cuftpd_send_resp(ctrlfd, 530, "first please"); \ return CUFTPD_ERR; \ } \ } while(0) struct cuftpd_cmd_struct { char *cmd_name; int (*cmd_handler)(int ctrlfd, char *cmd_line); }; struct cuftpd_user_struct { char user[128]; char pass[128]; }; #endif
Java
package no.nb.nna.veidemann.chrome.client.ws; import no.nb.nna.veidemann.chrome.client.ws.GetBrowserVersionCmd.Response; public class GetBrowserVersionCmd extends Command<Response> { public GetBrowserVersionCmd(Cdp client) { super(client, "Browser", "getVersion", Response.class); } public static class Response { private String protocolVersion; private String product; private String revision; private String userAgent; private String jsVersion; /** * Protocol version. */ public String protocolVersion() { return protocolVersion; } /** * Product name. */ public String product() { return product; } /** * Product revision. */ public String revision() { return revision; } /** * User-Agent. */ public String userAgent() { return userAgent; } /** * V8 version. */ public String jsVersion() { return jsVersion; } public String toString() { return "Version{protocolVersion=" + protocolVersion + ", product=" + product + ", revision=" + revision + ", userAgent=" + userAgent + ", jsVersion=" + jsVersion + "}"; } } }
Java
package fr.javatronic.blog.massive.annotation1; import fr.javatronic.blog.processor.Annotation_001; @Annotation_001 public class Class_914 { }
Java
OC.L10N.register( "settings", { "Security & Setup Warnings" : "Säkerhets & Inställningsvarningar", "Cron" : "Cron", "Sharing" : "Dela", "Security" : "Säkerhet", "Email Server" : "E-postserver", "Log" : "Logg", "Authentication error" : "Fel vid autentisering", "Your full name has been changed." : "Hela ditt namn har ändrats", "Unable to change full name" : "Kunde inte ändra hela namnet", "Files decrypted successfully" : "Filerna dekrypterades utan fel", "Couldn't decrypt your files, please check your owncloud.log or ask your administrator" : "Det gick inte att dekryptera dina filer, kontrollera din owncloud.log eller fråga administratören", "Couldn't decrypt your files, check your password and try again" : "Det gick inte att dekryptera filerna, kontrollera ditt lösenord och försök igen", "Encryption keys deleted permanently" : "Krypteringsnycklar raderades permanent", "Couldn't permanently delete your encryption keys, please check your owncloud.log or ask your administrator" : "Det gick inte att permanent ta bort dina krypteringsnycklar, kontrollera din owncloud.log eller fråga din administratör", "Couldn't remove app." : "Kunde inte ta bort applikationen.", "Backups restored successfully" : "Återställning av säkerhetskopior lyckades", "Couldn't restore your encryption keys, please check your owncloud.log or ask your administrator" : "Kan inte återställa dina krypteringsnycklar, vänligen kontrollera din owncloud.log eller fråga din administratör.", "Language changed" : "Språk ändrades", "Invalid request" : "Ogiltig begäran", "Admins can't remove themself from the admin group" : "Administratörer kan inte ta bort sig själva från admingruppen", "Unable to add user to group %s" : "Kan inte lägga till användare i gruppen %s", "Unable to remove user from group %s" : "Kan inte radera användare från gruppen %s", "Couldn't update app." : "Kunde inte uppdatera appen.", "Wrong password" : "Fel lösenord", "No user supplied" : "Ingen användare angiven", "Please provide an admin recovery password, otherwise all user data will be lost" : "Ange ett återställningslösenord för administratören. Annars kommer all användardata förloras", "Wrong admin recovery password. Please check the password and try again." : "Felaktigt återställningslösenord för administratör. Kolla lösenordet och prova igen.", "Back-end doesn't support password change, but the users encryption key was successfully updated." : "Gränssnittet stödjer inte byte av lösenord, men användarnas krypteringsnyckel blev uppdaterad.", "Unable to change password" : "Kunde inte ändra lösenord", "Enabled" : "Aktiverad", "Not enabled" : "Inte aktiverad", "Recommended" : "Rekomenderad", "Group already exists." : "Gruppen finns redan.", "Unable to add group." : "Lyckades inte lägga till grupp.", "Unable to delete group." : "Lyckades inte radera grupp.", "log-level out of allowed range" : "logg-nivå utanför tillåtet område", "Saved" : "Sparad", "test email settings" : "testa e-post inställningar", "If you received this email, the settings seem to be correct." : "Om du mottog detta e-postmeddelande, verkar dina inställningar vara korrekta.", "A problem occurred while sending the email. Please revise your settings." : "Ett problem uppstod när e-postmeddelandet skickades. Vänligen se över dina inställningar.", "Email sent" : "E-post skickat", "You need to set your user email before being able to send test emails." : "Du behöver ställa in din användares e-postadress före du kan skicka test e-post.", "Invalid mail address" : "Ogiltig e-postadress", "Unable to create user." : "Kan inte skapa användare.", "Your %s account was created" : "Ditt %s konto skapades", "Unable to delete user." : "Kan inte radera användare.", "Forbidden" : "Förbjuden", "Invalid user" : "Ogiltig användare", "Unable to change mail address" : "Kan inte ändra e-postadress", "Email saved" : "E-post sparad", "Are you really sure you want add \"{domain}\" as trusted domain?" : "Är du verkligen säker på att du vill lägga till \"{domain}\" som en trusted domian?", "Add trusted domain" : "Lägg till betrodd domän", "Sending..." : "Skickar ...", "All" : "Alla", "Please wait...." : "Var god vänta ...", "Error while disabling app" : "Fel vid inaktivering av app", "Disable" : "Deaktivera", "Enable" : "Aktivera", "Error while enabling app" : "Fel vid aktivering av app", "Updating...." : "Uppdaterar ...", "Error while updating app" : "Fel uppstod vid uppdatering av appen", "Updated" : "Uppdaterad", "Uninstalling ...." : "Avinstallerar ...", "Error while uninstalling app" : "Ett fel inträffade när applikatonen avinstallerades", "Uninstall" : "Avinstallera", "Select a profile picture" : "Välj en profilbild", "Very weak password" : "Väldigt svagt lösenord", "Weak password" : "Svagt lösenord", "So-so password" : "Okej lösenord", "Good password" : "Bra lösenord", "Strong password" : "Starkt lösenord", "Valid until {date}" : "Giltig t.o.m. {date}", "Delete" : "Radera", "Decrypting files... Please wait, this can take some time." : "Dekrypterar filer ... Vänligen vänta, detta kan ta en stund.", "Delete encryption keys permanently." : "Radera krypteringsnycklar permanent", "Restore encryption keys." : "Återställ krypteringsnycklar", "Groups" : "Grupper", "Unable to delete {objName}" : "Kunde inte radera {objName}", "Error creating group" : "Fel vid skapande av grupp", "A valid group name must be provided" : "Ett giltigt gruppnamn måste anges", "deleted {groupName}" : "raderade {groupName} ", "undo" : "ångra", "no group" : "ingen grupp", "never" : "aldrig", "deleted {userName}" : "raderade {userName}", "add group" : "lägg till grupp", "A valid username must be provided" : "Ett giltigt användarnamn måste anges", "Error creating user" : "Fel vid skapande av användare", "A valid password must be provided" : "Ett giltigt lösenord måste anges", "A valid email must be provided" : "En giltig e-postadress måste anges", "__language_name__" : "__language_name__", "Personal Info" : "Personlig info", "SSL root certificates" : "SSL rotcertifikat", "Encryption" : "Kryptering", "Everything (fatal issues, errors, warnings, info, debug)" : "Allting (allvarliga fel, fel, varningar, info, debug)", "Info, warnings, errors and fatal issues" : "Info, varningar och allvarliga fel", "Warnings, errors and fatal issues" : "Varningar, fel och allvarliga fel", "Errors and fatal issues" : "Fel och allvarliga fel", "Fatal issues only" : "Endast allvarliga fel", "None" : "Ingen", "Login" : "Logga in", "Plain" : "Enkel", "NT LAN Manager" : "NT LAN Manager", "SSL" : "SSL", "TLS" : "TLS", "Security Warning" : "Säkerhetsvarning", "You are accessing %s via HTTP. We strongly suggest you configure your server to require using HTTPS instead." : "Du ansluter till %s via HTTP. Vi rekommenderar starkt att du konfigurerar din server att använda HTTPS istället.", "Read-Only config enabled" : "Skrivskyddad konfiguration påslagen", "The Read-Only config has been enabled. This prevents setting some configurations via the web-interface. Furthermore, the file needs to be made writable manually for every update." : "Lär-bara konfigureringen har blivit aktiv. Detta förhindrar att några konfigureringar kan sättas via web-gränssnittet.", "Setup Warning" : "Installationsvarning", "PHP is apparently setup to strip inline doc blocks. This will make several core apps inaccessible." : "PHP är tydligen inställd för att rensa inline doc block. Detta kommer att göra flera kärnapplikationer otillgängliga.", "This is probably caused by a cache/accelerator such as Zend OPcache or eAccelerator." : "Detta orsakas troligtvis av en cache/accelerator som t ex Zend OPchache eller eAccelerator.", "Database Performance Info" : "Databasprestanda Information", "Microsoft Windows Platform" : "Microsoft Windows-platform", "Your server is running on Microsoft Windows. We highly recommend Linux for optimal user experience." : "Din server använder Microsoft Windows. Vi rekommenderar starkt Linux för en optimal användarerfarenhet.", "Module 'fileinfo' missing" : "Modulen \"fileinfo\" saknas", "The PHP module 'fileinfo' is missing. We strongly recommend to enable this module to get best results with mime-type detection." : "PHP-modulen 'fileinfo' saknas. Vi rekommenderar starkt att aktivera den här modulen för att kunna upptäcka korrekt mime-typ.", "PHP charset is not set to UTF-8" : "PHP-teckenuppsättning är inte satt till UTF-8", "PHP charset is not set to UTF-8. This can cause major issues with non-ASCII characters in file names. We highly recommend to change the value of 'default_charset' php.ini to 'UTF-8'." : "PHP-teckenuppsättning är inte satt till UTF-8. Detta kan orsaka stora problem med icke-ASCII-tecken i filnamn. Vi rekommenderar starkt att ändra värdet \"default_charset\" i php.ini till \"UTF-8\".", "Locale not working" : "\"Locale\" fungerar inte", "System locale can not be set to a one which supports UTF-8." : "Systemspråk kan inte ställas in till ett som stödjer UTF-8.", "This means that there might be problems with certain characters in file names." : "Detta betyder att där kan komma att uppstå problem med vissa tecken i filnamn.", "We strongly suggest installing the required packages on your system to support one of the following locales: %s." : "Vi rekommenderar starkt att installera de nödvändiga paketen på ditt system för att stödja en av följande språkversioner: %s.", "URL generation in notification emails" : "URL-generering i notifieringsmejl", "If your installation is not installed in the root of the domain and uses system cron, there can be issues with the URL generation. To avoid these problems, please set the \"overwrite.cli.url\" option in your config.php file to the webroot path of your installation (Suggested: \"%s\")" : "Om din installation inte installerades på roten av domänen och använder system cron så kan det uppstå problem med URL-genereringen. För att undvika dessa problem, var vänlig sätt \"overwrite.cli.url\"-inställningen i din config.php-fil till webbrotsökvägen av din installation (Föreslagen: \"%s\")", "Configuration Checks" : "Konfigurationskontroller", "No problems found" : "Inga problem hittades", "Please double check the <a href='%s'>installation guides</a>." : "Var god kontrollera <a href='%s'>installationsguiden</a>.", "Last cron was executed at %s." : "Sista cron kördes vid %s", "Last cron was executed at %s. This is more than an hour ago, something seems wrong." : "Sista cron kördes vid %s. Detta är mer än en timme sedan, något verkar fel.", "Cron was not executed yet!" : "Cron kördes inte ännu!", "Execute one task with each page loaded" : "Exekvera en uppgift vid varje sidladdning", "cron.php is registered at a webcron service to call cron.php every 15 minutes over http." : "cron.php är registrerad som en webcron service att ropa på cron.php varje 15 minuter över http.", "Use system's cron service to call the cron.php file every 15 minutes." : "Använd systemets cron-tjänst för att anropa cron.php var 15:e minut.", "Allow apps to use the Share API" : "Tillåt applikationer att använda delat API", "Allow users to share via link" : "Tillåt användare att dela via länk", "Enforce password protection" : "Tillämpa lösenordskydd", "Allow public uploads" : "Tillåt offentlig uppladdning", "Allow users to send mail notification for shared files" : "Tillåt användare att skicka mailnotifieringar för delade filer", "Set default expiration date" : "Ställ in standardutgångsdatum", "Expire after " : "Förfaller efter", "days" : "dagar", "Enforce expiration date" : "Tillämpa förfallodatum", "Allow resharing" : "Tillåt vidaredelning", "Restrict users to only share with users in their groups" : "Begränsa användare till att enbart kunna dela med användare i deras grupper", "Allow users to send mail notification for shared files to other users" : "Tillåt användare att skicka mejlnotifiering för delade filer till andra användare", "Exclude groups from sharing" : "Exkludera grupp från att dela", "These groups will still be able to receive shares, but not to initiate them." : "Dessa grupper kommer fortfarande kunna ta emot delningar, men inte skapa delningar.", "Enforce HTTPS" : "Kräv HTTPS", "Forces the clients to connect to %s via an encrypted connection." : "Tvingar klienterna att ansluta till %s via en krypterad anslutning.", "Enforce HTTPS for subdomains" : "Framtvinga HTTPS för underdomäner", "Forces the clients to connect to %s and subdomains via an encrypted connection." : "Tvingar klienter att ansluta till %s och underdomäner via en krypterad anslutning.", "Please connect to your %s via HTTPS to enable or disable the SSL enforcement." : "Anslut till din %s via HTTPS för att aktivera/deaktivera SSL", "This is used for sending out notifications." : "Detta används för att skicka ut notifieringar.", "Send mode" : "Sändningsläge", "From address" : "Från adress", "mail" : "mail", "Authentication method" : "Autentiseringsmetod", "Authentication required" : "Autentisering krävs", "Server address" : "Serveradress", "Port" : "Port", "Credentials" : "Inloggningsuppgifter", "SMTP Username" : "SMTP-användarnamn", "SMTP Password" : "SMTP-lösenord", "Store credentials" : "Lagra inloggningsuppgifter", "Test email settings" : "Testa e-postinställningar", "Send email" : "Skicka e-post", "Log level" : "Nivå på loggning", "Download logfile" : "Ladda ner loggfil", "More" : "Mer", "Less" : "Mindre", "The logfile is bigger than 100MB. Downloading it may take some time!" : "Loggfilen är större än 100MB. Att ladda ner den kan ta lite tid!", "Version" : "Version", "Developed by the <a href=\"http://ownCloud.org/contact\" target=\"_blank\">ownCloud community</a>, the <a href=\"https://github.com/owncloud\" target=\"_blank\">source code</a> is licensed under the <a href=\"http://www.gnu.org/licenses/agpl-3.0.html\" target=\"_blank\"><abbr title=\"Affero General Public License\">AGPL</abbr></a>." : "Utvecklad av <a href=\"http://ownCloud.org/contact\" target=\"_blank\">ownCloud Community</a>, <a href=\"https://github.com/owncloud\" target=\"_blank\">källkoden</a> är licenserad under <a href=\"http://www.gnu.org/licenses/agpl-3.0.html\" target=\"_blank\"><abbr title=\"Affero General Public License\">AGPL</abbr></a>.", "More apps" : "Fler appar", "Add your app" : "Lägg till din app", "by" : "av", "licensed" : "licensierad", "Documentation:" : "Dokumentation:", "User Documentation" : "Användardokumentation", "Admin Documentation" : "Administratörsdokumentation", "This app cannot be installed because the following dependencies are not fulfilled:" : "Denna applikation kan inte installeras då följande beroenden inte är uppfyllda: %s", "Update to %s" : "Uppdatera till %s", "Enable only for specific groups" : "Aktivera endast för specifika grupper", "Uninstall App" : "Avinstallera applikation", "Hey there,<br><br>just letting you know that you now have an %s account.<br><br>Your username: %s<br>Access it: <a href=\"%s\">%s</a><br><br>" : "Hej där,<br><br>vill bara informera dig om att du nu har ett %s konto.<br><br>Ditt användarnamn: %s<br>Accessa det genom: <a href=\"%s\">%s</a><br><br>", "Cheers!" : "Ha de fint!", "Hey there,\n\njust letting you know that you now have an %s account.\n\nYour username: %s\nAccess it: %s\n\n" : "Hej där,\n\nvill bara informera dig om att du nu har ett %s konto.\n\nDitt användarnamn: %s\nAccessa det genom: %s\n", "Administrator Documentation" : "Administratörsdokumentation", "Online Documentation" : "Onlinedokumentation", "Forum" : "Forum", "Bugtracker" : "Bugtracker", "Commercial Support" : "Kommersiell support", "Get the apps to sync your files" : "Skaffa apparna för att synkronisera dina filer", "Desktop client" : "Skrivbordsklient", "Android app" : "Android-app", "iOS app" : "iOS-app", "If you want to support the project\n\t\t<a href=\"https://owncloud.org/contribute\"\n\t\t\ttarget=\"_blank\">join development</a>\n\t\tor\n\t\t<a href=\"https://owncloud.org/promote\"\n\t\t\ttarget=\"_blank\">spread the word</a>!" : "Om du vill stödja projektet\n<a href=\"https://owncloud.org/contribute\"\n\t\t\ttarget=\"_blank\">hjälp till med utvecklingen</a>\n\t\teller\n\t\t<a href=\"https://owncloud.org/promote\"\n\t\t\ttarget=\"_blank\">sprid budskapet vidare</a>!", "Show First Run Wizard again" : "Visa Första uppstarts-guiden igen", "You have used <strong>%s</strong> of the available <strong>%s</strong>" : "Du har använt <strong>%s</strong> av tillgängliga <strong>%s</strong>", "Password" : "Lösenord", "Your password was changed" : "Ditt lösenord har ändrats", "Unable to change your password" : "Kunde inte ändra ditt lösenord", "Current password" : "Nuvarande lösenord", "New password" : "Nytt lösenord", "Change password" : "Ändra lösenord", "Full Name" : "Hela namnet", "No display name set" : "Inget visningsnamn angivet", "Email" : "E-post", "Your email address" : "Din e-postadress", "Fill in an email address to enable password recovery and receive notifications" : "Fyll i en e-postadress för att aktivera återställning av lösenord och mottagande av notifieringar", "No email address set" : "Ingen e-postadress angiven", "Profile picture" : "Profilbild", "Upload new" : "Ladda upp ny", "Select new from Files" : "Välj ny från filer", "Remove image" : "Radera bild", "Either png or jpg. Ideally square but you will be able to crop it." : "Antingen png eller jpg. Helst fyrkantig, men du kommer att kunna beskära den.", "Your avatar is provided by your original account." : "Din avatar tillhandahålls av ditt ursprungliga konto.", "Cancel" : "Avbryt", "Choose as profile image" : "Välj som profilbild", "Language" : "Språk", "Help translate" : "Hjälp att översätta", "Common Name" : "Vanligt namn", "Valid until" : "Giltigt till", "Issued By" : "Utfärdat av", "Valid until %s" : "Giltigt till %s", "Import Root Certificate" : "Importera rotcertifikat", "The encryption app is no longer enabled, please decrypt all your files" : "Krypteringsapplikationen är inte längre aktiverad, vänligen dekryptera alla dina filer", "Log-in password" : "Inloggningslösenord", "Decrypt all Files" : "Dekryptera alla filer", "Your encryption keys are moved to a backup location. If something went wrong you can restore the keys. Only delete them permanently if you are sure that all files are decrypted correctly." : "Dina krypteringsnycklar flyttas till en backup. Om något gick fel kan du återställa nycklarna. Bara ta bort dem permanent om du är säker på att alla filer dekrypteras korrekt.", "Restore Encryption Keys" : "Återställ krypteringsnycklar", "Delete Encryption Keys" : "Radera krypteringsnycklar", "Show storage location" : "Visa lagringsplats", "Show last log in" : "Visa senaste inloggning", "Show user backend" : "Visa användar-back-end", "Send email to new user" : "Skicka e-post till ny användare", "Show email address" : "Visa e-postadress", "Username" : "Användarnamn", "E-Mail" : "E-post", "Create" : "Skapa", "Admin Recovery Password" : "Admin-återställningslösenord", "Enter the recovery password in order to recover the users files during password change" : "Ange återställningslösenordet för att återställa användarnas filer vid lösenordsbyte", "Search Users" : "Sök användare", "Add Group" : "Lägg till Grupp", "Group" : "Grupp", "Everyone" : "Alla", "Admins" : "Administratörer", "Default Quota" : "Förvald datakvot", "Please enter storage quota (ex: \"512 MB\" or \"12 GB\")" : "Var god skriv in lagringskvot (ex: \"512MB\" eller \"12 GB\")", "Unlimited" : "Obegränsad", "Other" : "Annat", "Group Admin for" : "Gruppadministratör för", "Quota" : "Kvot", "Storage Location" : "Lagringsplats", "User Backend" : "Användar-back-end", "Last Login" : "Senaste inloggning", "change full name" : "ändra hela namnet", "set new password" : "ange nytt lösenord", "change email address" : "ändra e-postadress", "Default" : "Förvald" }, "nplurals=2; plural=(n != 1);");
Java
// +build integration,ethereum package ethclient import ( "encoding/json" "fmt" "testing" "github.com/hyperledger/burrow/crypto" "github.com/hyperledger/burrow/encoding/web3hex" "github.com/hyperledger/burrow/execution/solidity" "github.com/hyperledger/burrow/rpc/rpcevents" "github.com/hyperledger/burrow/tests/web3/web3test" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) var client = NewEthClient(web3test.GetChainRPCClient()) func TestEthAccounts(t *testing.T) { accounts, err := client.Accounts() require.NoError(t, err) fmt.Println(accounts) } func TestEthSendTransaction(t *testing.T) { pk := web3test.GetPrivateKey(t) d := new(web3hex.Decoder) param := &EthSendTransactionParam{ From: web3hex.Encoder.Address(pk.GetAddress()), Gas: web3hex.Encoder.Uint64(999999), Data: web3hex.Encoder.BytesTrim(solidity.Bytecode_EventEmitter), } txHash, err := client.SendTransaction(param) require.NoError(t, err) require.NotEmpty(t, txHash) tx, err := client.GetTransactionByHash(txHash) require.NoError(t, err) assert.Greater(t, d.Uint64(tx.BlockNumber), uint64(0)) receipt, err := client.GetTransactionReceipt(txHash) require.NoError(t, err) assert.Equal(t, txHash, receipt.TransactionHash) require.NoError(t, d.Err()) } func TestNonExistentTransaction(t *testing.T) { txHash := "0x990258f47aba0cf913c14cc101ddf5b589c04765429d5709f643c891442bfcf7" receipt, err := client.GetTransactionReceipt(txHash) require.NoError(t, err) require.Equal(t, "", receipt.TransactionHash) require.Equal(t, "", receipt.BlockNumber) require.Equal(t, "", receipt.BlockHash) tx, err := client.GetTransactionByHash(txHash) require.NoError(t, err) require.Equal(t, "", tx.Hash) require.Equal(t, "", tx.BlockNumber) require.Equal(t, "", tx.BlockHash) } func TestEthClient_GetLogs(t *testing.T) { // TODO: make this test generate its own fixutres filter := &Filter{ BlockRange: rpcevents.AbsoluteRange(1, 34340), Addresses: []crypto.Address{ crypto.MustAddressFromHexString("a1e378f122fec6aa8c841397042e21bc19368768"), crypto.MustAddressFromHexString("f73aaa468496a87675d27638878a1600b0db3c71"), }, } result, err := client.GetLogs(filter) require.NoError(t, err) bs, err := json.Marshal(result) require.NoError(t, err) fmt.Printf("%s\n", string(bs)) } func TestEthClient_GetBlockByNumber(t *testing.T) { block, err := client.GetBlockByNumber("latest") require.NoError(t, err) d := new(web3hex.Decoder) assert.Greater(t, d.Uint64(block.Number), uint64(0)) require.NoError(t, d.Err()) } func TestNetVersion(t *testing.T) { chainID, err := client.NetVersion() require.NoError(t, err) require.NotEmpty(t, chainID) } func TestWeb3ClientVersion(t *testing.T) { version, err := client.Web3ClientVersion() require.NoError(t, err) require.NotEmpty(t, version) } func TestEthSyncing(t *testing.T) { result, err := client.Syncing() require.NoError(t, err) fmt.Printf("%#v\n", result) } func TestEthBlockNumber(t *testing.T) { height, err := client.BlockNumber() require.NoError(t, err) require.Greater(t, height, uint64(0)) }
Java
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Tests for the output module field formatting helper.""" import unittest from dfdatetime import semantic_time as dfdatetime_semantic_time from dfvfs.path import fake_path_spec from plaso.containers import events from plaso.lib import definitions from plaso.output import formatting_helper from tests.containers import test_lib as containers_test_lib from tests.output import test_lib class TestFieldFormattingHelper(formatting_helper.FieldFormattingHelper): """Field formatter helper for testing purposes.""" _FIELD_FORMAT_CALLBACKS = {'zone': '_FormatTimeZone'} class FieldFormattingHelperTest(test_lib.OutputModuleTestCase): """Test the output module field formatting helper.""" # pylint: disable=protected-access _TEST_EVENTS = [ {'data_type': 'test:event', 'filename': 'log/syslog.1', 'hostname': 'ubuntu', 'path_spec': fake_path_spec.FakePathSpec( location='log/syslog.1'), 'text': ( 'Reporter <CRON> PID: 8442 (pam_unix(cron:session): session\n ' 'closed for user root)'), 'timestamp': '2012-06-27 18:17:01', 'timestamp_desc': definitions.TIME_DESCRIPTION_CHANGE}] def testFormatDateTime(self): """Tests the _FormatDateTime function with dynamic time.""" output_mediator = self._CreateOutputMediator() test_helper = formatting_helper.FieldFormattingHelper(output_mediator) event, event_data, event_data_stream = ( containers_test_lib.CreateEventFromValues(self._TEST_EVENTS[0])) date_time_string = test_helper._FormatDateTime( event, event_data, event_data_stream) self.assertEqual(date_time_string, '2012-06-27T18:17:01.000000+00:00') output_mediator.SetTimezone('Europe/Amsterdam') date_time_string = test_helper._FormatDateTime( event, event_data, event_data_stream) self.assertEqual(date_time_string, '2012-06-27T20:17:01.000000+02:00') output_mediator.SetTimezone('UTC') event.date_time = dfdatetime_semantic_time.InvalidTime() date_time_string = test_helper._FormatDateTime( event, event_data, event_data_stream) self.assertEqual(date_time_string, 'Invalid') def testFormatDateTimeWithoutDynamicTime(self): """Tests the _FormatDateTime function without dynamic time.""" output_mediator = self._CreateOutputMediator(dynamic_time=False) test_helper = formatting_helper.FieldFormattingHelper(output_mediator) event, event_data, event_data_stream = ( containers_test_lib.CreateEventFromValues(self._TEST_EVENTS[0])) # Test with event.date_time date_time_string = test_helper._FormatDateTime( event, event_data, event_data_stream) self.assertEqual(date_time_string, '2012-06-27T18:17:01.000000+00:00') output_mediator.SetTimezone('Europe/Amsterdam') date_time_string = test_helper._FormatDateTime( event, event_data, event_data_stream) self.assertEqual(date_time_string, '2012-06-27T20:17:01.000000+02:00') output_mediator.SetTimezone('UTC') event.date_time = dfdatetime_semantic_time.InvalidTime() date_time_string = test_helper._FormatDateTime( event, event_data, event_data_stream) self.assertEqual(date_time_string, '0000-00-00T00:00:00.000000+00:00') # Test with event.timestamp event.date_time = None date_time_string = test_helper._FormatDateTime( event, event_data, event_data_stream) self.assertEqual(date_time_string, '2012-06-27T18:17:01.000000+00:00') event.timestamp = 0 date_time_string = test_helper._FormatDateTime( event, event_data, event_data_stream) self.assertEqual(date_time_string, '0000-00-00T00:00:00.000000+00:00') event.timestamp = -9223372036854775808 date_time_string = test_helper._FormatDateTime( event, event_data, event_data_stream) self.assertEqual(date_time_string, '0000-00-00T00:00:00.000000+00:00') def testFormatDisplayName(self): """Tests the _FormatDisplayName function.""" output_mediator = self._CreateOutputMediator() test_helper = formatting_helper.FieldFormattingHelper(output_mediator) event, event_data, event_data_stream = ( containers_test_lib.CreateEventFromValues(self._TEST_EVENTS[0])) display_name_string = test_helper._FormatDisplayName( event, event_data, event_data_stream) self.assertEqual(display_name_string, 'FAKE:log/syslog.1') def testFormatFilename(self): """Tests the _FormatFilename function.""" output_mediator = self._CreateOutputMediator() test_helper = formatting_helper.FieldFormattingHelper(output_mediator) event, event_data, event_data_stream = ( containers_test_lib.CreateEventFromValues(self._TEST_EVENTS[0])) filename_string = test_helper._FormatFilename( event, event_data, event_data_stream) self.assertEqual(filename_string, 'log/syslog.1') def testFormatHostname(self): """Tests the _FormatHostname function.""" output_mediator = self._CreateOutputMediator() test_helper = formatting_helper.FieldFormattingHelper(output_mediator) event, event_data, event_data_stream = ( containers_test_lib.CreateEventFromValues(self._TEST_EVENTS[0])) hostname_string = test_helper._FormatHostname( event, event_data, event_data_stream) self.assertEqual(hostname_string, 'ubuntu') def testFormatInode(self): """Tests the _FormatInode function.""" output_mediator = self._CreateOutputMediator() test_helper = formatting_helper.FieldFormattingHelper(output_mediator) event, event_data, event_data_stream = ( containers_test_lib.CreateEventFromValues(self._TEST_EVENTS[0])) inode_string = test_helper._FormatInode( event, event_data, event_data_stream) self.assertEqual(inode_string, '-') def testFormatMACB(self): """Tests the _FormatMACB function.""" output_mediator = self._CreateOutputMediator() test_helper = formatting_helper.FieldFormattingHelper(output_mediator) event, event_data, event_data_stream = ( containers_test_lib.CreateEventFromValues(self._TEST_EVENTS[0])) macb_string = test_helper._FormatMACB(event, event_data, event_data_stream) self.assertEqual(macb_string, '..C.') def testFormatMessage(self): """Tests the _FormatMessage function.""" output_mediator = self._CreateOutputMediator() formatters_directory_path = self._GetTestFilePath(['formatters']) output_mediator.ReadMessageFormattersFromDirectory( formatters_directory_path) test_helper = formatting_helper.FieldFormattingHelper(output_mediator) event, event_data, event_data_stream = ( containers_test_lib.CreateEventFromValues(self._TEST_EVENTS[0])) message_string = test_helper._FormatMessage( event, event_data, event_data_stream) expected_message_string = ( 'Reporter <CRON> PID: 8442 (pam_unix(cron:session): session closed ' 'for user root)') self.assertEqual(message_string, expected_message_string) def testFormatMessageShort(self): """Tests the _FormatMessageShort function.""" output_mediator = self._CreateOutputMediator() formatters_directory_path = self._GetTestFilePath(['formatters']) output_mediator.ReadMessageFormattersFromDirectory( formatters_directory_path) test_helper = formatting_helper.FieldFormattingHelper(output_mediator) event, event_data, event_data_stream = ( containers_test_lib.CreateEventFromValues(self._TEST_EVENTS[0])) message_short_string = test_helper._FormatMessageShort( event, event_data, event_data_stream) expected_message_short_string = ( 'Reporter <CRON> PID: 8442 (pam_unix(cron:session): session closed ' 'for user root)') self.assertEqual(message_short_string, expected_message_short_string) def testFormatSource(self): """Tests the _FormatSource function.""" output_mediator = self._CreateOutputMediator() test_helper = formatting_helper.FieldFormattingHelper(output_mediator) event, event_data, event_data_stream = ( containers_test_lib.CreateEventFromValues(self._TEST_EVENTS[0])) source_string = test_helper._FormatSource( event, event_data, event_data_stream) self.assertEqual(source_string, 'Test log file') def testFormatSourceShort(self): """Tests the _FormatSourceShort function.""" output_mediator = self._CreateOutputMediator() test_helper = formatting_helper.FieldFormattingHelper(output_mediator) event, event_data, event_data_stream = ( containers_test_lib.CreateEventFromValues(self._TEST_EVENTS[0])) source_short_string = test_helper._FormatSourceShort( event, event_data, event_data_stream) self.assertEqual(source_short_string, 'FILE') def testFormatTag(self): """Tests the _FormatTag function.""" output_mediator = self._CreateOutputMediator() test_helper = formatting_helper.FieldFormattingHelper(output_mediator) tag_string = test_helper._FormatTag(None) self.assertEqual(tag_string, '-') event_tag = events.EventTag() event_tag.AddLabel('one') event_tag.AddLabel('two') tag_string = test_helper._FormatTag(event_tag) self.assertEqual(tag_string, 'one two') def testFormatTime(self): """Tests the _FormatTime function.""" output_mediator = self._CreateOutputMediator() test_helper = formatting_helper.FieldFormattingHelper(output_mediator) event, event_data, event_data_stream = ( containers_test_lib.CreateEventFromValues(self._TEST_EVENTS[0])) # Test with event.date_time time_string = test_helper._FormatTime( event, event_data, event_data_stream) self.assertEqual(time_string, '18:17:01') output_mediator.SetTimezone('Europe/Amsterdam') time_string = test_helper._FormatTime( event, event_data, event_data_stream) self.assertEqual(time_string, '20:17:01') output_mediator.SetTimezone('UTC') # Test with event.timestamp event.date_time = None time_string = test_helper._FormatTime( event, event_data, event_data_stream) self.assertEqual(time_string, '18:17:01') event.timestamp = 0 time_string = test_helper._FormatTime( event, event_data, event_data_stream) self.assertEqual(time_string, '--:--:--') event.timestamp = -9223372036854775808 time_string = test_helper._FormatTime( event, event_data, event_data_stream) self.assertEqual(time_string, '--:--:--') def testFormatTimeZone(self): """Tests the _FormatTimeZone function.""" output_mediator = self._CreateOutputMediator() test_helper = formatting_helper.FieldFormattingHelper(output_mediator) event, event_data, event_data_stream = ( containers_test_lib.CreateEventFromValues(self._TEST_EVENTS[0])) zone_string = test_helper._FormatTimeZone( event, event_data, event_data_stream) self.assertEqual(zone_string, 'UTC') def testFormatUsername(self): """Tests the _FormatUsername function.""" output_mediator = self._CreateOutputMediator() test_helper = formatting_helper.FieldFormattingHelper(output_mediator) event, event_data, event_data_stream = ( containers_test_lib.CreateEventFromValues(self._TEST_EVENTS[0])) username_string = test_helper._FormatUsername( event, event_data, event_data_stream) self.assertEqual(username_string, '-') # TODO: add coverage for _ReportEventError def testGetFormattedField(self): """Tests the GetFormattedField function.""" output_mediator = self._CreateOutputMediator() test_helper = TestFieldFormattingHelper(output_mediator) event, event_data, event_data_stream = ( containers_test_lib.CreateEventFromValues(self._TEST_EVENTS[0])) zone_string = test_helper.GetFormattedField( 'zone', event, event_data, event_data_stream, None) self.assertEqual(zone_string, 'UTC') if __name__ == '__main__': unittest.main()
Java
package de.tototec.sbuild.internal import de.tototec.sbuild.TargetContext import de.tototec.sbuild.InvalidApiUsageException import de.tototec.sbuild.Project trait WithinTargetExecution { def targetContext: TargetContext protected[sbuild] def directDepsTargetContexts: Seq[TargetContext] } object WithinTargetExecution extends ThreadLocal[WithinTargetExecution] { private[sbuild] override def remove: Unit = super.remove private[sbuild] override def set(withinTargetExecution: WithinTargetExecution): Unit = super.set(withinTargetExecution) /** * To use a WithinTargetExecution, one should use this method. */ private[sbuild] def safeWithinTargetExecution[T](callingMethodName: String, project: Option[Project] = None)(doWith: WithinTargetExecution => T): T = get match { case null => val msg = I18n.marktr("'{0}' can only be used inside an exec block of a target.") val ex = new InvalidApiUsageException(I18n.notr(msg, callingMethodName), null, I18n[WithinTargetExecution.type].tr(msg, callingMethodName)) ex.buildScript = project.map(_.projectFile) throw ex case withinExecution => doWith(withinExecution) } // private[sbuild] def safeTargetContext(callingMethodName: String, project: Option[Project] = None): TargetContext = // safeWithinTargetExecution(callingMethodName, project)(_.targetContext) }
Java
package org.wikipedia.concurrency; // Copied from Android 4.4.2_r2 source // so we can use executeOnExecutor :P // // https://android.googlesource.com/platform/frameworks/base/+/android-4.4.2_r2/core/java/android/os/AsyncTask.java /* * Copyright (C) 2008 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import android.os.Handler; import android.os.Message; import android.os.Process; import android.support.annotation.NonNull; import java.util.ArrayDeque; import java.util.concurrent.BlockingQueue; import java.util.concurrent.Callable; import java.util.concurrent.CancellationException; import java.util.concurrent.ExecutionException; import java.util.concurrent.Executor; import java.util.concurrent.FutureTask; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadFactory; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; /** * <p>AsyncTask enables proper and easy use of the UI thread. This class allows to * perform background operations and publish results on the UI thread without * having to manipulate threads and/or handlers.</p> * * <p>AsyncTask is designed to be a helper class around {@link Thread} and {@link Handler} * and does not constitute a generic threading framework. AsyncTasks should ideally be * used for short operations (a few seconds at the most.) If you need to keep threads * running for long periods of time, it is highly recommended you use the various APIs * provided by the <code>java.util.concurrent</code> pacakge such as {@link Executor}, * {@link ThreadPoolExecutor} and {@link FutureTask}.</p> * * <p>An asynchronous task is defined by a computation that runs on a background thread and * whose result is published on the UI thread. An asynchronous task is defined by 3 generic * types, called <code>Params</code>, <code>Progress</code> and <code>Result</code>, * and 4 steps, called <code>onPreExecute</code>, <code>doInBackground</code>, * <code>onProgressUpdate</code> and <code>onPostExecute</code>.</p> * * <div class="special reference"> * <h3>Developer Guides</h3> * <p>For more information about using tasks and threads, read the * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html">Processes and * Threads</a> developer guide.</p> * </div> * * <h2>Usage</h2> * <p>AsyncTask must be subclassed to be used. The subclass will override at least * one method ({@link #doInBackground}), and most often will override a * second one ({@link #onPostExecute}.)</p> * * <p>Here is an example of subclassing:</p> * <pre class="prettyprint"> * private class DownloadFilesTask extends AsyncTask&lt;URL, Integer, Long&gt; { * protected Long doInBackground(URL... urls) { * int count = urls.length; * long totalSize = 0; * for (int i = 0; i < count; i++) { * totalSize += Downloader.downloadFile(urls[i]); * publishProgress((int) ((i / (float) count) * 100)); * // Escape early if cancel() is called * if (isCancelled()) break; * } * return totalSize; * } * * protected void onProgressUpdate(Integer... progress) { * setProgressPercent(progress[0]); * } * * protected void onPostExecute(Long result) { * showDialog("Downloaded " + result + " bytes"); * } * } * </pre> * * <p>Once created, a task is executed very simply:</p> * <pre class="prettyprint"> * new DownloadFilesTask().execute(url1, url2, url3); * </pre> * * <h2>AsyncTask's generic types</h2> * <p>The three types used by an asynchronous task are the following:</p> * <ol> * <li><code>Params</code>, the type of the parameters sent to the task upon * execution.</li> * <li><code>Progress</code>, the type of the progress units published during * the background computation.</li> * <li><code>Result</code>, the type of the result of the background * computation.</li> * </ol> * <p>Not all types are always used by an asynchronous task. To mark a type as unused, * simply use the type {@link Void}:</p> * <pre> * private class MyTask extends AsyncTask&lt;Void, Void, Void&gt; { ... } * </pre> * * <h2>The 4 steps</h2> * <p>When an asynchronous task is executed, the task goes through 4 steps:</p> * <ol> * <li>{@link #onPreExecute()}, invoked on the UI thread before the task * is executed. This step is normally used to setup the task, for instance by * showing a progress bar in the user interface.</li> * <li>{@link #doInBackground}, invoked on the background thread * immediately after {@link #onPreExecute()} finishes executing. This step is used * to perform background computation that can take a long time. The parameters * of the asynchronous task are passed to this step. The result of the computation must * be returned by this step and will be passed back to the last step. This step * can also use {@link #publishProgress} to publish one or more units * of progress. These values are published on the UI thread, in the * {@link #onProgressUpdate} step.</li> * <li>{@link #onProgressUpdate}, invoked on the UI thread after a * call to {@link #publishProgress}. The timing of the execution is * undefined. This method is used to display any form of progress in the user * interface while the background computation is still executing. For instance, * it can be used to animate a progress bar or show logs in a text field.</li> * <li>{@link #onPostExecute}, invoked on the UI thread after the background * computation finishes. The result of the background computation is passed to * this step as a parameter.</li> * </ol> * * <h2>Cancelling a task</h2> * <p>A task can be cancelled at any time by invoking {@link #cancel(boolean)}. Invoking * this method will cause subsequent calls to {@link #isCancelled()} to return true. * After invoking this method, {@link #onCancelled(Object)}, instead of * {@link #onPostExecute(Object)} will be invoked after {@link #doInBackground(Object[])} * returns. To ensure that a task is cancelled as quickly as possible, you should always * check the return value of {@link #isCancelled()} periodically from * {@link #doInBackground(Object[])}, if possible (inside a loop for instance.)</p> * * <h2>Threading rules</h2> * <p>There are a few threading rules that must be followed for this class to * work properly:</p> * <ul> * <li>The AsyncTask class must be loaded on the UI thread. This is done * automatically as of {@link android.os.Build.VERSION_CODES#JELLY_BEAN}.</li> * <li>The task instance must be created on the UI thread.</li> * <li>{@link #execute} must be invoked on the UI thread.</li> * <li>Do not call {@link #onPreExecute()}, {@link #onPostExecute}, * {@link #doInBackground}, {@link #onProgressUpdate} manually.</li> * <li>The task can be executed only once (an exception will be thrown if * a second execution is attempted.)</li> * </ul> * * <h2>Memory observability</h2> * <p>AsyncTask guarantees that all callback calls are synchronized in such a way that the following * operations are safe without explicit synchronizations.</p> * <ul> * <li>Set member fields in the constructor or {@link #onPreExecute}, and refer to them * in {@link #doInBackground}. * <li>Set member fields in {@link #doInBackground}, and refer to them in * {@link #onProgressUpdate} and {@link #onPostExecute}. * </ul> * * <h2>Order of execution</h2> * <p>When first introduced, AsyncTasks were executed serially on a single background * thread. Starting with {@link android.os.Build.VERSION_CODES#DONUT}, this was changed * to a pool of threads allowing multiple tasks to operate in parallel. Starting with * {@link android.os.Build.VERSION_CODES#HONEYCOMB}, tasks are executed on a single * thread to avoid common application errors caused by parallel execution.</p> * <p>If you truly want parallel execution, you can invoke * {@link #executeOnExecutor(java.util.concurrent.Executor, Object[])} with * {@link #THREAD_POOL_EXECUTOR}.</p> */ public abstract class AsyncTask<Params, Progress, Result> { private static final String LOG_TAG = "AsyncTask"; private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors(); private static final int CORE_POOL_SIZE = CPU_COUNT + 1; private static final int MAXIMUM_POOL_SIZE = CPU_COUNT * 2 + 1; private static final int KEEP_ALIVE = 1; private static final ThreadFactory sThreadFactory = new ThreadFactory() { private final AtomicInteger mCount = new AtomicInteger(1); public Thread newThread(@NonNull Runnable r) { return new Thread(r, "AsyncTask #" + mCount.getAndIncrement()); } }; private static final BlockingQueue<Runnable> sPoolWorkQueue = new LinkedBlockingQueue<>(128); /** * An {@link Executor} that can be used to execute tasks in parallel. */ public static final Executor THREAD_POOL_EXECUTOR = new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE, TimeUnit.SECONDS, sPoolWorkQueue, sThreadFactory); /** * An {@link Executor} that executes tasks one at a time in serial * order. This serialization is global to a particular process. */ public static final Executor SERIAL_EXECUTOR = new SerialExecutor(); private static final int MESSAGE_POST_RESULT = 0x1; private static final int MESSAGE_POST_PROGRESS = 0x2; private static final InternalHandler sHandler = new InternalHandler(); private static volatile Executor sDefaultExecutor = SERIAL_EXECUTOR; private final WorkerRunnable<Params, Result> mWorker; private final FutureTask<Result> mFuture; private volatile Status mStatus = Status.PENDING; private final AtomicBoolean mCancelled = new AtomicBoolean(); private final AtomicBoolean mTaskInvoked = new AtomicBoolean(); private static class SerialExecutor implements Executor { final ArrayDeque<Runnable> mTasks = new ArrayDeque<>(); Runnable mActive; public synchronized void execute(@NonNull final Runnable r) { mTasks.offer(new Runnable() { public void run() { try { r.run(); } finally { scheduleNext(); } } }); if (mActive == null) { scheduleNext(); } } protected synchronized void scheduleNext() { if ((mActive = mTasks.poll()) != null) { THREAD_POOL_EXECUTOR.execute(mActive); } } } /** * Indicates the current status of the task. Each status will be set only once * during the lifetime of a task. */ public enum Status { /** * Indicates that the task has not been executed yet. */ PENDING, /** * Indicates that the task is running. */ RUNNING, /** * Indicates that {@link AsyncTask#onPostExecute} has finished. */ FINISHED, } /** @hide Used to force static handler to be created. */ public static void init() { sHandler.getLooper(); } /** @hide */ public static void setDefaultExecutor(Executor exec) { sDefaultExecutor = exec; } /** * Creates a new asynchronous task. This constructor must be invoked on the UI thread. */ public AsyncTask() { mWorker = new WorkerRunnable<Params, Result>() { public Result call() throws Exception { mTaskInvoked.set(true); Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); //noinspection unchecked return postResult(doInBackground(mParams)); } }; mFuture = new FutureTask<Result>(mWorker) { @Override protected void done() { try { postResultIfNotInvoked(get()); } catch (InterruptedException e) { android.util.Log.w(LOG_TAG, e); } catch (ExecutionException e) { throw new RuntimeException("An error occured while executing doInBackground()", e.getCause()); } catch (CancellationException e) { postResultIfNotInvoked(null); } } }; } private void postResultIfNotInvoked(Result result) { final boolean wasTaskInvoked = mTaskInvoked.get(); if (!wasTaskInvoked) { postResult(result); } } private Result postResult(Result result) { @SuppressWarnings("unchecked") Message message = sHandler.obtainMessage(MESSAGE_POST_RESULT, new AsyncTaskResult<>(this, result)); message.sendToTarget(); return result; } /** * Returns the current status of this task. * * @return The current status. */ public final Status getStatus() { return mStatus; } /** * Override this method to perform a computation on a background thread. The * specified parameters are the parameters passed to {@link #execute} * by the caller of this task. * * This method can call {@link #publishProgress} to publish updates * on the UI thread. * * @param params The parameters of the task. * * @return A result, defined by the subclass of this task. * * @see #onPreExecute() * @see #onPostExecute * @see #publishProgress */ protected abstract Result doInBackground(Params... params); /** * Runs on the UI thread before {@link #doInBackground}. * * @see #onPostExecute * @see #doInBackground */ protected void onPreExecute() { } /** * <p>Runs on the UI thread after {@link #doInBackground}. The * specified result is the value returned by {@link #doInBackground}.</p> * * <p>This method won't be invoked if the task was cancelled.</p> * * @param result The result of the operation computed by {@link #doInBackground}. * * @see #onPreExecute * @see #doInBackground * @see #onCancelled(Object) */ @SuppressWarnings({"UnusedDeclaration"}) protected void onPostExecute(Result result) { } /** * Runs on the UI thread after {@link #publishProgress} is invoked. * The specified values are the values passed to {@link #publishProgress}. * * @param values The values indicating progress. * * @see #publishProgress * @see #doInBackground */ @SuppressWarnings({"UnusedDeclaration"}) protected void onProgressUpdate(Progress... values) { } /** * <p>Runs on the UI thread after {@link #cancel(boolean)} is invoked and * {@link #doInBackground(Object[])} has finished.</p> * * <p>The default implementation simply invokes {@link #onCancelled()} and * ignores the result. If you write your own implementation, do not call * <code>super.onCancelled(result)</code>.</p> * * @param result The result, if any, computed in * {@link #doInBackground(Object[])}, can be null * * @see #cancel(boolean) * @see #isCancelled() */ @SuppressWarnings({"UnusedParameters"}) protected void onCancelled(Result result) { onCancelled(); } /** * <p>Applications should preferably override {@link #onCancelled(Object)}. * This method is invoked by the default implementation of * {@link #onCancelled(Object)}.</p> * * <p>Runs on the UI thread after {@link #cancel(boolean)} is invoked and * {@link #doInBackground(Object[])} has finished.</p> * * @see #onCancelled(Object) * @see #cancel(boolean) * @see #isCancelled() */ protected void onCancelled() { } /** * Returns <tt>true</tt> if this task was cancelled before it completed * normally. If you are calling {@link #cancel(boolean)} on the task, * the value returned by this method should be checked periodically from * {@link #doInBackground(Object[])} to end the task as soon as possible. * * @return <tt>true</tt> if task was cancelled before it completed * * @see #cancel(boolean) */ public final boolean isCancelled() { return mCancelled.get(); } /** * <p>Attempts to cancel execution of this task. This attempt will * fail if the task has already completed, already been cancelled, * or could not be cancelled for some other reason. If successful, * and this task has not started when <tt>cancel</tt> is called, * this task should never run. If the task has already started, * then the <tt>mayInterruptIfRunning</tt> parameter determines * whether the thread executing this task should be interrupted in * an attempt to stop the task.</p> * * <p>Calling this method will result in {@link #onCancelled(Object)} being * invoked on the UI thread after {@link #doInBackground(Object[])} * returns. Calling this method guarantees that {@link #onPostExecute(Object)} * is never invoked. After invoking this method, you should check the * value returned by {@link #isCancelled()} periodically from * {@link #doInBackground(Object[])} to finish the task as early as * possible.</p> * * @param mayInterruptIfRunning <tt>true</tt> if the thread executing this * task should be interrupted; otherwise, in-progress tasks are allowed * to complete. * * @return <tt>false</tt> if the task could not be cancelled, * typically because it has already completed normally; * <tt>true</tt> otherwise * * @see #isCancelled() * @see #onCancelled(Object) */ public final boolean cancel(boolean mayInterruptIfRunning) { mCancelled.set(true); return mFuture.cancel(mayInterruptIfRunning); } /** * Waits if necessary for the computation to complete, and then * retrieves its result. * * @return The computed result. * * @throws CancellationException If the computation was cancelled. * @throws ExecutionException If the computation threw an exception. * @throws InterruptedException If the current thread was interrupted * while waiting. */ public final Result get() throws InterruptedException, ExecutionException { return mFuture.get(); } /** * Waits if necessary for at most the given time for the computation * to complete, and then retrieves its result. * * @param timeout Time to wait before cancelling the operation. * @param unit The time unit for the timeout. * * @return The computed result. * * @throws CancellationException If the computation was cancelled. * @throws ExecutionException If the computation threw an exception. * @throws InterruptedException If the current thread was interrupted * while waiting. * @throws TimeoutException If the wait timed out. */ public final Result get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { return mFuture.get(timeout, unit); } /** * Executes the task with the specified parameters. The task returns * itself (this) so that the caller can keep a reference to it. * * <p>Note: this function schedules the task on a queue for a single background * thread or pool of threads depending on the platform version. When first * introduced, AsyncTasks were executed serially on a single background thread. * Starting with {@link android.os.Build.VERSION_CODES#DONUT}, this was changed * to a pool of threads allowing multiple tasks to operate in parallel. Starting * {@link android.os.Build.VERSION_CODES#HONEYCOMB}, tasks are back to being * executed on a single thread to avoid common application errors caused * by parallel execution. If you truly want parallel execution, you can use * the {@link #executeOnExecutor} version of this method * with {@link #THREAD_POOL_EXECUTOR}; however, see commentary there for warnings * on its use. * * <p>This method must be invoked on the UI thread. * * @param params The parameters of the task. * * @return This instance of AsyncTask. * * @throws IllegalStateException If {@link #getStatus()} returns either * {@link AsyncTask.Status#RUNNING} or {@link AsyncTask.Status#FINISHED}. * * @see #executeOnExecutor(java.util.concurrent.Executor, Object[]) * @see #execute(Runnable) */ public final AsyncTask<Params, Progress, Result> execute(Params... params) { return executeOnExecutor(sDefaultExecutor, params); } /** * Executes the task with the specified parameters. The task returns * itself (this) so that the caller can keep a reference to it. * * <p>This method is typically used with {@link #THREAD_POOL_EXECUTOR} to * allow multiple tasks to run in parallel on a pool of threads managed by * AsyncTask, however you can also use your own {@link Executor} for custom * behavior. * * <p><em>Warning:</em> Allowing multiple tasks to run in parallel from * a thread pool is generally <em>not</em> what one wants, because the order * of their operation is not defined. For example, if these tasks are used * to modify any state in common (such as writing a file due to a button click), * there are no guarantees on the order of the modifications. * Without careful work it is possible in rare cases for the newer version * of the data to be over-written by an older one, leading to obscure data * loss and stability issues. Such changes are best * executed in serial; to guarantee such work is serialized regardless of * platform version you can use this function with {@link #SERIAL_EXECUTOR}. * * <p>This method must be invoked on the UI thread. * * @param exec The executor to use. {@link #THREAD_POOL_EXECUTOR} is available as a * convenient process-wide thread pool for tasks that are loosely coupled. * @param params The parameters of the task. * * @return This instance of AsyncTask. * * @throws IllegalStateException If {@link #getStatus()} returns either * {@link AsyncTask.Status#RUNNING} or {@link AsyncTask.Status#FINISHED}. * * @see #execute(Object[]) */ public final AsyncTask<Params, Progress, Result> executeOnExecutor(Executor exec, Params... params) { if (mStatus != Status.PENDING) { switch (mStatus) { case RUNNING: throw new IllegalStateException("Cannot execute task:" + " the task is already running."); case FINISHED: throw new IllegalStateException("Cannot execute task:" + " the task has already been executed " + "(a task can be executed only once)"); } } mStatus = Status.RUNNING; onPreExecute(); mWorker.mParams = params; exec.execute(mFuture); return this; } /** * Convenience version of {@link #execute(Object...)} for use with * a simple Runnable object. See {@link #execute(Object[])} for more * information on the order of execution. * * @see #execute(Object[]) * @see #executeOnExecutor(java.util.concurrent.Executor, Object[]) */ public static void execute(Runnable runnable) { sDefaultExecutor.execute(runnable); } /** * This method can be invoked from {@link #doInBackground} to * publish updates on the UI thread while the background computation is * still running. Each call to this method will trigger the execution of * {@link #onProgressUpdate} on the UI thread. * * {@link #onProgressUpdate} will note be called if the task has been * canceled. * * @param values The progress values to update the UI with. * * @see #onProgressUpdate * @see #doInBackground */ protected final void publishProgress(Progress... values) { if (!isCancelled()) { sHandler.obtainMessage(MESSAGE_POST_PROGRESS, new AsyncTaskResult<>(this, values)).sendToTarget(); } } private void finish(Result result) { if (isCancelled()) { onCancelled(result); } else { onPostExecute(result); } mStatus = Status.FINISHED; } private static class InternalHandler extends Handler { @SuppressWarnings({"unchecked", "RawUseOfParameterizedType"}) @Override public void handleMessage(Message msg) { AsyncTaskResult result = (AsyncTaskResult) msg.obj; switch (msg.what) { case MESSAGE_POST_RESULT: // There is only one result result.mTask.finish(result.mData[0]); break; case MESSAGE_POST_PROGRESS: result.mTask.onProgressUpdate(result.mData); break; } } } private static abstract class WorkerRunnable<Params, Result> implements Callable<Result> { Params[] mParams; } @SuppressWarnings({"RawUseOfParameterizedType"}) private static class AsyncTaskResult<Data> { final AsyncTask mTask; final Data[] mData; AsyncTaskResult(AsyncTask task, Data... data) { mTask = task; mData = data; } } }
Java
package cn.edu.hhu.reg.vo; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name="doctor_login") public class DoctorLogin { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(length = 16) private Integer id; /** * 医生id */ @Column(name="doctor_id",length=16) private Integer doctorId; /** * 医生登录名 */ @Column(name="login_name",length=50) private String loginName; /** * 医生登录密码 */ @Column(name="password",length=50) private String password; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Integer getDoctorId() { return doctorId; } public void setDoctorId(Integer doctorId) { this.doctorId = doctorId; } public String getLoginName() { return loginName; } public void setLoginName(String loginName) { this.loginName = loginName; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public DoctorLogin() { } }
Java
# remark-stringify [![Build][build-badge]][build] [![Coverage][coverage-badge]][coverage] [![Downloads][downloads-badge]][downloads] [![Size][size-badge]][size] [![Chat][chat-badge]][chat] [![Sponsors][sponsors-badge]][collective] [![Backers][backers-badge]][collective] [Compiler][] for [**unified**][unified]. Serializes [**mdast**][mdast] syntax trees to Markdown. Used in the [**remark** processor][remark] but can be used on its own as well. Can be [extended][extend] to change how Markdown is serialized. ## Install [npm][]: ```sh npm install remark-stringify ``` ## Use ```js var unified = require('unified') var createStream = require('unified-stream') var html = require('rehype-parse') var rehype2remark = require('rehype-remark') var stringify = require('remark-stringify') var processor = unified().use(html).use(rehype2remark).use(stringify, { bullet: '*', fence: '~', fences: true, incrementListMarker: false }) process.stdin.pipe(createStream(processor)).pipe(process.stdout) ``` [See **unified** for more examples »][unified] ## API [See **unified** for API docs »][unified] ### `processor().use(stringify[, options])` Configure the `processor` to serialize [**mdast**][mdast] syntax trees to Markdown. ###### `options` Options can be passed directly, or passed later through [`processor.data()`][data]. All the formatting options of [`mdast-util-to-markdown`][to-markdown-options] are supported and will be passed through. ## Extending the compiler See [`mdast-util-to-markdown`][to-markdown]. Then create a wrapper plugin such as [`remark-gfm`][remark-gfm]. ## Security `remark-stringify` will do its best to serialize markdown to match the syntax tree, but there are several cases where that is impossible. It’ll do its best, but complete roundtripping is impossible given that any value could be injected into the tree. As Markdown is sometimes used for HTML, and improper use of HTML can open you up to a [cross-site scripting (XSS)][xss] attack, use of `remark-stringify` and parsing it again later can potentially be unsafe. When parsing Markdown afterwards, use remark in combination with the [**rehype**][rehype] ecosystem, and use [`rehype-sanitize`][sanitize] to make the tree safe. Use of remark plugins could also open you up to other attacks. Carefully assess each plugin and the risks involved in using them. ## Contribute See [`contributing.md`][contributing] in [`remarkjs/.github`][health] for ways to get started. See [`support.md`][support] for ways to get help. Ideas for new plugins and tools can be posted in [`remarkjs/ideas`][ideas]. A curated list of awesome remark resources can be found in [**awesome remark**][awesome]. This project has a [code of conduct][coc]. By interacting with this repository, organization, or community you agree to abide by its terms. ## Sponsor Support this effort and give back by sponsoring on [OpenCollective][collective]! <!--lint ignore no-html--> <table> <tr valign="middle"> <td width="20%" align="center" colspan="2"> <a href="https://www.gatsbyjs.org">Gatsby</a> 🥇<br><br> <a href="https://www.gatsbyjs.org"><img src="https://avatars1.githubusercontent.com/u/12551863?s=256&v=4" width="128"></a> </td> <td width="20%" align="center" colspan="2"> <a href="https://vercel.com">Vercel</a> 🥇<br><br> <a href="https://vercel.com"><img src="https://avatars1.githubusercontent.com/u/14985020?s=256&v=4" width="128"></a> </td> <td width="20%" align="center" colspan="2"> <a href="https://www.netlify.com">Netlify</a><br><br> <!--OC has a sharper image--> <a href="https://www.netlify.com"><img src="https://images.opencollective.com/netlify/4087de2/logo/256.png" width="128"></a> </td> <td width="10%" align="center"> <a href="https://www.holloway.com">Holloway</a><br><br> <a href="https://www.holloway.com"><img src="https://avatars1.githubusercontent.com/u/35904294?s=128&v=4" width="64"></a> </td> <td width="10%" align="center"> <a href="https://themeisle.com">ThemeIsle</a><br><br> <a href="https://themeisle.com"><img src="https://avatars1.githubusercontent.com/u/58979018?s=128&v=4" width="64"></a> </td> <td width="10%" align="center"> <a href="https://boosthub.io">Boost Hub</a><br><br> <a href="https://boosthub.io"><img src="https://images.opencollective.com/boosthub/6318083/logo/128.png" width="64"></a> </td> <td width="10%" align="center"> <a href="https://expo.io">Expo</a><br><br> <a href="https://expo.io"><img src="https://avatars1.githubusercontent.com/u/12504344?s=128&v=4" width="64"></a> </td> </tr> <tr valign="middle"> <td width="100%" align="center" colspan="10"> <br> <a href="https://opencollective.com/unified"><strong>You?</strong></a> <br><br> </td> </tr> </table> ## License [MIT][license] © [Titus Wormer][author] <!-- Definitions --> [build-badge]: https://img.shields.io/travis/remarkjs/remark.svg [build]: https://travis-ci.org/remarkjs/remark [coverage-badge]: https://img.shields.io/codecov/c/github/remarkjs/remark.svg [coverage]: https://codecov.io/github/remarkjs/remark [downloads-badge]: https://img.shields.io/npm/dm/remark-stringify.svg [downloads]: https://www.npmjs.com/package/remark-stringify [size-badge]: https://img.shields.io/bundlephobia/minzip/remark-stringify.svg [size]: https://bundlephobia.com/result?p=remark-stringify [sponsors-badge]: https://opencollective.com/unified/sponsors/badge.svg [backers-badge]: https://opencollective.com/unified/backers/badge.svg [collective]: https://opencollective.com/unified [chat-badge]: https://img.shields.io/badge/chat-discussions-success.svg [chat]: https://github.com/remarkjs/remark/discussions [health]: https://github.com/remarkjs/.github [contributing]: https://github.com/remarkjs/.github/blob/HEAD/contributing.md [support]: https://github.com/remarkjs/.github/blob/HEAD/support.md [coc]: https://github.com/remarkjs/.github/blob/HEAD/code-of-conduct.md [ideas]: https://github.com/remarkjs/ideas [awesome]: https://github.com/remarkjs/awesome-remark [license]: https://github.com/remarkjs/remark/blob/main/license [author]: https://wooorm.com [npm]: https://docs.npmjs.com/cli/install [unified]: https://github.com/unifiedjs/unified [data]: https://github.com/unifiedjs/unified#processordatakey-value [remark]: https://github.com/remarkjs/remark/tree/main/packages/remark [compiler]: https://github.com/unifiedjs/unified#processorcompiler [mdast]: https://github.com/syntax-tree/mdast [xss]: https://en.wikipedia.org/wiki/Cross-site_scripting [rehype]: https://github.com/rehypejs/rehype [sanitize]: https://github.com/rehypejs/rehype-sanitize [to-markdown]: https://github.com/syntax-tree/mdast-util-to-markdown [to-markdown-options]: https://github.com/syntax-tree/mdast-util-to-markdown#formatting-options [extend]: #extending-the-compiler [remark-gfm]: https://github.com/remarkjs/remark-gfm
Java
/* * Copyright 2018 Aleksander Jagiełło * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package pl.themolka.arcade.team; import org.bukkit.ChatColor; import pl.themolka.arcade.command.CommandException; import pl.themolka.arcade.command.CommandUtils; import pl.themolka.arcade.command.Sender; import pl.themolka.arcade.game.GamePlayer; import pl.themolka.arcade.match.Observers; import pl.themolka.arcade.parser.Context; import pl.themolka.arcade.util.Color; import java.util.ArrayList; import java.util.Collection; public class TeamCommands { private final TeamsGame game; public TeamCommands(TeamsGame game) { this.game = game; } // // Commands // public void clearCommand(Sender sender, String teamId) { Team team = this.fetchTeam(teamId); if (team.isObservers()) { throw new CommandException("Cannot clear observers."); } Observers observers = this.game.getMatch().getObservers(); int result = 0; for (GamePlayer player : new ArrayList<>(team.getOnlineMembers())) { observers.joinForce(player); result++; } if (result > 0) { sender.sendSuccess(team.getName() + " has been cleared (" + result + " players) and moved to " + observers.getName() + "."); } else { sender.sendError("No players to clear."); } } public void forceCommand(Sender sender, String username, String teamId) { GamePlayer player = this.fetchPlayer(username); Team team = this.fetchTeam(teamId); if (team.contains(player)) { throw new CommandException(player.getUsername() + " is already member of " + team.getName() + "."); } team.joinForce(player); sender.sendSuccess(player.getUsername() + " has been moved to " + team.getName() + "."); } public void friendlyCommand(Sender sender, String teamId, boolean friendly) { Team team = this.fetchTeam(teamId); if (team.isObservers()) { throw new CommandException("Cannot edit observers."); } if (friendly == team.isFriendlyFire()) { if (friendly) { throw new CommandException(team.getName() + " is already in friendly-fire."); } else { throw new CommandException(team.getName() + " is already not in friendly-fire"); } } Team oldState = new Team(team); team.setFriendlyFire(friendly); this.callEditEvent(team, oldState, TeamEditEvent.Reason.FRIENDLY_FIRE); if (friendly) { sender.sendSuccess(oldState.getName() + " is now in friendly-fire."); } else { sender.sendSuccess(oldState.getName() + " is now not in friendly-fire."); } } public void infoCommand(Sender sender) { Collection<Team> teams = this.game.getTeams(); CommandUtils.sendTitleMessage(sender, "Teams", Integer.toString(teams.size())); for (Team team : teams) { sender.send(String.format("%s - %s/%s - %s minimal to play and %s overfill", team.getPrettyName() + ChatColor.GRAY, ChatColor.GOLD.toString() + team.getOnlineMembers().size() + ChatColor.GRAY, Integer.toString(team.getSlots()), ChatColor.GREEN.toString() + team.getMinPlayers() + ChatColor.GRAY, ChatColor.RED.toString() + team.getMaxPlayers() + ChatColor.GRAY)); } } public void kickCommand(Sender sender, String username) { GamePlayer player = this.fetchPlayer(username); Team team = this.game.getTeam(player); if (team.isObservers()) { throw new CommandException("Cannot kick from observers."); } team.leaveForce(player); team.getMatch().getObservers().joinForce(player); sender.sendSuccess(player.getUsername() + " has been kicked from " + team.getName() + "."); } public void minCommand(Sender sender, String teamId, int min) { Team team = this.fetchTeam(teamId); if (team.isObservers()) { throw new CommandException("Cannot edit observers."); } else if (min < 0) { throw new CommandException("Number cannot be negative."); } Team oldState = new Team(team); team.setMinPlayers(min); this.callEditEvent(team, oldState, TeamEditEvent.Reason.MIN_PLAYERS); sender.sendSuccess(oldState.getName() + " has been edited."); } public void overfillCommand(Sender sender, String teamId, int overfill) { Team team = this.fetchTeam(teamId); if (team.isObservers()) { throw new CommandException("Cannot edit observers."); } // set to unlimited if zero or negative int max = Integer.MAX_VALUE; if (overfill > 0) { max = overfill; } Team oldState = new Team(team); team.setMaxPlayers(max); if (max > team.getSlots()) { team.setSlots(max); // slots } this.callEditEvent(team, oldState, TeamEditEvent.Reason.MAX_PLAYERS); sender.sendSuccess(oldState.getName() + " has been edited."); } public void paintCommand(Sender sender, String teamId, String paint) { Team team = this.fetchTeam(teamId); ChatColor color = Color.parseChat(new Context(this.game.getPlugin()), paint); if (color == null) { StringBuilder colors = new StringBuilder(); for (int i = 0; i < ChatColor.values().length; i++) { ChatColor value = ChatColor.values()[i]; if (i != 0) { colors.append(", "); } ChatColor result = ChatColor.RED; if (!value.equals(ChatColor.MAGIC)) { result = value; } colors.append(result).append(value.name().toLowerCase().replace("_", "-")) .append(ChatColor.RESET).append(ChatColor.RED); } throw new CommandException("Available colors: " + colors.toString() + "."); } Team oldState = new Team(team); team.setChatColor(color); this.callEditEvent(team, oldState, TeamEditEvent.Reason.PAINT); sender.sendSuccess(oldState.getName() + " has been painted from " + oldState.getChatColor().name().toLowerCase().replace("_", "-") + " to " + team.getChatColor().name().toLowerCase().replace("_", "-") + "."); } public void renameCommand(Sender sender, String teamId, String name) { Team team = this.fetchTeam(teamId); if (name == null) { throw new CommandException("New name not given."); } else if (name.length() > Team.NAME_MAX_LENGTH) { throw new CommandException("Name too long (greater than " + Team.NAME_MAX_LENGTH + " characters)."); } else if (team.getName().equals(name)) { throw new CommandException("Already named '" + team.getName() + "'."); } Team oldState = new Team(team); team.setName(name); this.callEditEvent(team, oldState, TeamEditEvent.Reason.RENAME); sender.sendSuccess(oldState.getName() + " has been renamed to " + team.getName() + "."); } public void slotsCommand(Sender sender, String teamId, int slots) { Team team = this.fetchTeam(teamId); if (team.isObservers()) { throw new CommandException("Cannot edit observers."); } // set to unlimited if zero or negative int max = Integer.MAX_VALUE; if (slots > 0) { max = slots; } Team oldState = new Team(team); team.setSlots(max); if (max > team.getMaxPlayers()) { team.setMaxPlayers(max); // overfill } this.callEditEvent(team, oldState, TeamEditEvent.Reason.SLOTS); sender.sendSuccess(oldState.getName() + " has been edited."); } // // Command Utilities // private void callEditEvent(Team newState, Team oldState, TeamEditEvent.Reason reason) { this.game.getPlugin().getEventBus().publish(new TeamEditEvent( this.game.getPlugin(), newState, oldState, reason)); } private GamePlayer fetchPlayer(String player) { if (player != null && !player.isEmpty()) { GamePlayer result = this.game.getGame().findPlayer(player); if (result != null) { return result; } } throw new CommandException("Player not found."); } private Team fetchTeam(String team) { if (team != null && !team.isEmpty()) { Team result = this.game.findTeamById(team); if (result != null) { return result; } } throw new CommandException("Team not found."); } }
Java
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (version 1.7.0_25) on Tue Oct 08 12:24:28 JST 2013 --> <meta http-equiv="Content-Type" content="text/html" charset="UTF-8"> <title>Uses of Class twitter4j.examples.geo.CreatePlace (twitter4j-examples 3.0.4 API)</title> <meta name="date" content="2013-10-08"> <link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class twitter4j.examples.geo.CreatePlace (twitter4j-examples 3.0.4 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><a href="../../../../twitter4j/examples/geo/CreatePlace.html" title="class in twitter4j.examples.geo">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-all.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../index.html?twitter4j/examples/geo/class-use/CreatePlace.html" target="_top">Frames</a></li> <li><a href="CreatePlace.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="Uses of Class twitter4j.examples.geo.CreatePlace" class="title">Uses of Class<br>twitter4j.examples.geo.CreatePlace</h2> </div> <div class="classUseContainer">No usage of twitter4j.examples.geo.CreatePlace</div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../twitter4j/examples/geo/CreatePlace.html" title="class in twitter4j.examples.geo">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-all.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../index.html?twitter4j/examples/geo/class-use/CreatePlace.html" target="_top">Frames</a></li> <li><a href="CreatePlace.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small>Copyright &#169; 2013. All Rights Reserved.</small></p> </body> </html>
Java
package problems; import java.util.Arrays; import java.util.PriorityQueue; /** * Leetcode: Super Ugly Number * Created by alan on 2/24/2016. */ public class SuperUglyNumber { class Node implements Comparable<Node> { int val; final int prime_index; public Node(int value, int prime_idx) { this.val = value; this.prime_index = prime_idx; } public int compareTo(Node a) { return this.val - a.val; } } public int[] nthSuperUglyNumber(int n, int[] primes) { int[] nums = new int[n]; nums[0] = 1; int[] index = new int[primes.length]; PriorityQueue<Node> pq = new PriorityQueue<>(); for (int i = 0; i < primes.length; i++) pq.add(new Node(primes[i], i)); for (int i = 1; i < n; i++) { Node node = pq.poll(); while (node.val == nums[i - 1]) { node.val = nums[++index[node.prime_index]] * primes[node.prime_index]; pq.add(node); node = pq.poll(); } nums[i] = node.val; node.val = nums[++index[node.prime_index]] * primes[node.prime_index]; pq.add(node); } return nums; } public static void main(String[] args) { SuperUglyNumber sn = new SuperUglyNumber(); int[] primes = {2, 7, 13, 19}; System.out.println(Arrays.toString(primes)); System.out.println(Arrays.toString(sn.nthSuperUglyNumber(12, primes))); } }
Java
/* * Copyright 2021 HM Revenue & Customs * * 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 services import models.autocomplete.{CountryDataProvider, NameValuePair} import org.scalatestplus.mockito.MockitoSugar import org.scalatestplus.play.PlaySpec class AutoCompleteServiceSpec extends PlaySpec with MockitoSugar { trait Fixture { val locations = Seq( NameValuePair("Location 1", "location:1"), NameValuePair("Location 2", "location:2") ) val service = new AutoCompleteService(new CountryDataProvider { override def fetch: Option[Seq[NameValuePair]] = Some(locations) }) } "getLocations" must { "return a list of locations loaded from a resource file" in new Fixture { service.getCountries mustBe Some(locations) } } }
Java
package yuku.alkitab.base.util; import android.app.Activity; import android.app.Dialog; import android.content.Intent; import android.database.Cursor; import android.database.DatabaseUtils; import android.database.sqlite.SQLiteDatabase; import android.os.AsyncTask; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.util.Xml; import com.afollestad.materialdialogs.MaterialDialog; import gnu.trove.list.TIntList; import gnu.trove.list.array.TIntArrayList; import gnu.trove.map.hash.TIntLongHashMap; import gnu.trove.map.hash.TIntObjectHashMap; import gnu.trove.map.hash.TObjectIntHashMap; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.ext.DefaultHandler2; import yuku.alkitab.base.App; import yuku.alkitab.base.IsiActivity; import yuku.alkitab.base.S; import yuku.alkitab.base.storage.Db; import yuku.alkitab.base.storage.InternalDb; import yuku.alkitab.debug.R; import yuku.alkitab.model.Label; import yuku.alkitab.model.Marker; import yuku.alkitab.model.Marker_Label; import java.io.InputStream; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import static yuku.alkitab.base.util.Literals.ToStringArray; // Imported from v3. Used for once-only migration from v3 to v4. public class BookmarkImporter { static final String TAG = BookmarkImporter.class.getSimpleName(); // constants static class Bookmark2_Label { // DO NOT CHANGE CONSTANT VALUES! public static final String XMLTAG_Bookmark2_Label = "Bukmak2_Label"; public static final String XMLATTR_bookmark2_relId = "bukmak2_relId"; public static final String XMLATTR_label_relId = "label_relId"; } // constants static class BackupManager { public static final String XMLTAG_Bukmak2 = "Bukmak2"; private static final String XMLATTR_ari = "ari"; private static final String XMLATTR_kind = "jenis"; private static final String XMLATTR_caption = "tulisan"; private static final String XMLATTR_addTime = "waktuTambah"; private static final String XMLATTR_modifyTime = "waktuUbah"; private static final String XMLATTR_relId = "relId"; private static final String XMLVAL_bookmark = "bukmak"; private static final String XMLVAL_note = "catatan"; private static final String XMLVAL_highlight = "stabilo"; public static final String XMLTAG_Label = "Label"; private static final String XMLATTR_title = "judul"; private static final String XMLATTR_bgColor = "warnaLatar"; @Nullable public static Marker markerFromAttributes(Attributes attributes) { int ari = Integer.parseInt(attributes.getValue("", XMLATTR_ari)); String kind_s = attributes.getValue("", XMLATTR_kind); Marker.Kind kind = kind_s.equals(XMLVAL_bookmark) ? Marker.Kind.bookmark : kind_s.equals(XMLVAL_note) ? Marker.Kind.note : kind_s.equals(XMLVAL_highlight) ? Marker.Kind.highlight : null; String caption = unescapeHighUnicode(attributes.getValue("", XMLATTR_caption)); Date addTime = Sqlitil.toDate(Integer.parseInt(attributes.getValue("", XMLATTR_addTime))); Date modifyTime = Sqlitil.toDate(Integer.parseInt(attributes.getValue("", XMLATTR_modifyTime))); if (kind == null) { // invalid return null; } return Marker.createNewMarker(ari, kind, caption, 1, addTime, modifyTime); } public static int getRelId(Attributes attributes) { String s = attributes.getValue("", XMLATTR_relId); return s == null ? 0 : Integer.parseInt(s); } public static Label labelFromAttributes(Attributes attributes) { String title = unescapeHighUnicode(attributes.getValue("", XMLATTR_title)); String bgColor = attributes.getValue("", XMLATTR_bgColor); return Label.createNewLabel(title, 0, bgColor); } static ThreadLocal<Matcher> highUnicodeMatcher = new ThreadLocal<Matcher>() { @Override protected Matcher initialValue() { return Pattern.compile("\\[\\[~U([0-9A-Fa-f]{6})~\\]\\]").matcher(""); } }; public static String unescapeHighUnicode(String input) { if (input == null) return null; final Matcher m = highUnicodeMatcher.get(); m.reset(input); StringBuffer res = new StringBuffer(); while (m.find()) { String s = m.group(1); final int cp = Integer.parseInt(s, 16); m.appendReplacement(res, new String(new int[]{cp}, 0, 1)); } m.appendTail(res); return res.toString(); } } public static void importBookmarks(final Activity activity, @NonNull final InputStream fis, final boolean finishActivityAfterwards, final Runnable runWhenDone) { final MaterialDialog pd = new MaterialDialog.Builder(activity) .content(R.string.mengimpor_titiktiga) .cancelable(false) .progress(true, 0) .show(); new AsyncTask<Boolean, Integer, Object>() { int count_bookmark = 0; int count_label = 0; @Override protected Object doInBackground(Boolean... params) { final List<Marker> markers = new ArrayList<>(); final TObjectIntHashMap<Marker> markerToRelIdMap = new TObjectIntHashMap<>(); final List<Label> labels = new ArrayList<>(); final TObjectIntHashMap<Label> labelToRelIdMap = new TObjectIntHashMap<>(); final TIntLongHashMap labelRelIdToAbsIdMap = new TIntLongHashMap(); final TIntObjectHashMap<TIntList> markerRelIdToLabelRelIdsMap = new TIntObjectHashMap<>(); try { Xml.parse(fis, Xml.Encoding.UTF_8, new DefaultHandler2() { @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { switch (localName) { case BackupManager.XMLTAG_Bukmak2: final Marker marker = BackupManager.markerFromAttributes(attributes); if (marker != null) { markers.add(marker); final int bookmark2_relId = BackupManager.getRelId(attributes); markerToRelIdMap.put(marker, bookmark2_relId); count_bookmark++; } break; case BackupManager.XMLTAG_Label: { final Label label = BackupManager.labelFromAttributes(attributes); int label_relId = BackupManager.getRelId(attributes); labels.add(label); labelToRelIdMap.put(label, label_relId); count_label++; break; } case Bookmark2_Label.XMLTAG_Bookmark2_Label: { final int bookmark2_relId = Integer.parseInt(attributes.getValue("", Bookmark2_Label.XMLATTR_bookmark2_relId)); final int label_relId = Integer.parseInt(attributes.getValue("", Bookmark2_Label.XMLATTR_label_relId)); TIntList labelRelIds = markerRelIdToLabelRelIdsMap.get(bookmark2_relId); if (labelRelIds == null) { labelRelIds = new TIntArrayList(); markerRelIdToLabelRelIdsMap.put(bookmark2_relId, labelRelIds); } labelRelIds.add(label_relId); break; } } } }); fis.close(); } catch (Exception e) { return e; } { // bikin label-label yang diperlukan, juga map relId dengan id dari label. final HashMap<String, Label> judulMap = new HashMap<>(); final List<Label> xlabelLama = S.getDb().listAllLabels(); for (Label labelLama : xlabelLama) { judulMap.put(labelLama.title, labelLama); } for (Label label : labels) { // cari apakah label yang judulnya persis sama udah ada Label labelLama = judulMap.get(label.title); final int labelRelId = labelToRelIdMap.get(label); if (labelLama != null) { // removed from v3: update warna label lama labelRelIdToAbsIdMap.put(labelRelId, labelLama._id); AppLog.d(TAG, "label (lama) r->a : " + labelRelId + "->" + labelLama._id); } else { // belum ada, harus bikin baru Label labelBaru = S.getDb().insertLabel(label.title, label.backgroundColor); labelRelIdToAbsIdMap.put(labelRelId, labelBaru._id); AppLog.d(TAG, "label (baru) r->a : " + labelRelId + "->" + labelBaru._id); } } } importBookmarks(markers, markerToRelIdMap, labelRelIdToAbsIdMap, markerRelIdToLabelRelIdsMap); return null; } @Override protected void onPostExecute(@NonNull Object result) { pd.dismiss(); if (result instanceof Exception) { AppLog.e(TAG, "Error when importing markers", (Throwable) result); new MaterialDialog.Builder(activity) .content(activity.getString(R.string.terjadi_kesalahan_ketika_mengimpor_pesan, ((Exception) result).getMessage())) .positiveText(R.string.ok) .show(); } else { final Dialog dialog = new MaterialDialog.Builder(activity) .content(activity.getString(R.string.impor_berhasil_angka_diproses, count_bookmark, count_label)) .positiveText(R.string.ok) .show(); if (finishActivityAfterwards) { dialog.setOnDismissListener(dialog1 -> activity.finish()); } } if (runWhenDone != null) runWhenDone.run(); } }.execute(); } public static void importBookmarks(List<Marker> markers, TObjectIntHashMap<Marker> markerToRelIdMap, TIntLongHashMap labelRelIdToAbsIdMap, TIntObjectHashMap<TIntList> markerRelIdToLabelRelIdsMap) { SQLiteDatabase db = S.getDb().getWritableDatabase(); db.beginTransaction(); try { final TIntObjectHashMap<Marker> markerRelIdToMarker = new TIntObjectHashMap<>(); { // write new markers (if not available yet) for (int i = 0; i < markers.size(); i++) { Marker marker = markers.get(i); final int marker_relId = markerToRelIdMap.get(marker); // migrate: look for existing marker with same kind, ari, and content try (Cursor cursor = db.query( Db.TABLE_Marker, null, Db.Marker.ari + "=? and " + Db.Marker.kind + "=? and " + Db.Marker.caption + "=?", ToStringArray(marker.ari, marker.kind.code, marker.caption), null, null, null )) { if (cursor.moveToNext()) { marker = InternalDb.markerFromCursor(cursor); markers.set(i, marker); } else { InternalDb.insertMarker(db, marker); } // map it markerRelIdToMarker.put(marker_relId, marker); } } } { // now is marker-label assignments for (final int marker_relId : markerRelIdToLabelRelIdsMap.keys()) { final TIntList label_relIds = markerRelIdToLabelRelIdsMap.get(marker_relId); final Marker marker = markerRelIdToMarker.get(marker_relId); if (marker != null) { // existing labels > 0: ignore // existing labels == 0: insert final int existing_label_count = (int) DatabaseUtils.queryNumEntries(db, Db.TABLE_Marker_Label, Db.Marker_Label.marker_gid + "=?", ToStringArray(marker.gid)); if (existing_label_count == 0) { for (int label_relId : label_relIds.toArray()) { final long label_id = labelRelIdToAbsIdMap.get(label_relId); if (label_id > 0) { final Label label = S.getDb().getLabelById(label_id); final Marker_Label marker_label = Marker_Label.createNewMarker_Label(marker.gid, label.gid); InternalDb.insertMarker_LabelIfNotExists(db, marker_label); } else { AppLog.w(TAG, "label_id is invalid!: " + label_id); } } } } else { AppLog.w(TAG, "wrong marker_relId: " + marker_relId); } } } db.setTransactionSuccessful(); } finally { db.endTransaction(); } App.getLbm().sendBroadcast(new Intent(IsiActivity.ACTION_ATTRIBUTE_MAP_CHANGED)); } }
Java
/** * Copyright (C) 2009 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma.core.region; import java.util.Set; import org.joda.beans.impl.flexi.FlexiBean; import org.threeten.bp.ZoneId; import com.opengamma.id.ExternalBundleIdentifiable; import com.opengamma.id.ExternalIdBundle; import com.opengamma.id.UniqueId; import com.opengamma.id.UniqueIdentifiable; import com.opengamma.util.PublicAPI; import com.opengamma.util.i18n.Country; import com.opengamma.util.money.Currency; /** * A region of the world. * <p> * Many aspects of business, algorithms and contracts are specific to a region. The region may be of any size, from a municipality to a super-national group. * <p> * This interface is read-only. Implementations may be mutable. */ @PublicAPI public interface Region extends UniqueIdentifiable, ExternalBundleIdentifiable { /** * Gets the unique identifier of the region. * <p> * This specifies a single version-correction of the region. * * @return the unique identifier for this region, not null within the engine */ @Override UniqueId getUniqueId(); /** * Gets the external identifier bundle that defines the region. * <p> * Each external system has one or more identifiers by which they refer to the region. * Some of these may be unique within that system, while others may be more descriptive. * This bundle stores the set of these external identifiers. * <p> * This will include the country, currency and time-zone. * * @return the bundle defining the region, not null */ @Override // override for Javadoc ExternalIdBundle getExternalIdBundle(); /** * Gets the classification of the region. * * @return the classification of region, such as SUPER_NATIONAL or INDEPENDENT_STATE, not null */ RegionClassification getClassification(); /** * Gets the unique identifiers of the regions that this region is a member of. For example, a country might be a member * of the World, UN, European Union and NATO. * * @return the parent unique identifiers, null if this is the root entry */ Set<UniqueId> getParentRegionIds(); /** * Gets the country. * * @return the country, null if not applicable */ Country getCountry(); /** * Gets the currency. * * @return the currency, null if not applicable */ Currency getCurrency(); /** * Gets the time-zone. For larger regions, there can be multiple time-zones, so this is only reliable for municipalities. * * @return the time-zone, null if not applicable */ ZoneId getTimeZone(); /** * Gets the short descriptive name of the region. * * @return the name of the region, not null */ String getName(); /** * Gets the full descriptive name of the region. * * @return the full name of the region, not null */ String getFullName(); /** * Gets the extensible data store for additional information. Applications may store additional region based information here. * * @return the additional data, not null */ FlexiBean getData(); }
Java
var config = require('./lib/config'); var FaceRec = require('./lib/facerec').FaceRec; var hfr = new FaceRec(config); // constant var threshold = 20; var prevX; var prevY; setInterval(function() { var result = hfr.detect(); console.log('result:' + JSON.stringify(result)); if (result && result.pos_x && result.pos_y) { var newX = result.pos_x; var newY = result.pos_y; var deltaX = newX - prevX; var deltaY = newY - prevY; if (Math.abs(deltaX) > threshold) { var direction = deltaX > 0 ? "right" : "left"; console.log("moving head to " + direction + " , distance" + Math.abs(deltaX)); } if (Math.abs(deltaY) > threshold) { var direction = deltaY > 0 ? "down" : "up"; console.log("moving head to " + direction + " , distance" + Math.abs(deltaY)); } console.log('updating x and y'); prevX = newX; prevY = newY; } }, 5000);
Java
/* $Id$ * $URL: https://dev.almende.com/svn/abms/coala-common/src/main/java/com/almende/coala/time/NanoInstant.java $ * * Part of the EU project Adapt4EE, see http://www.adapt4ee.eu/ * * @license * 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 (c) 2010-2013 Almende B.V. */ package io.coala.time; /** * {@link NanoInstant} has the nano-second as base time unit * * @date $Date: 2014-06-03 14:26:09 +0200 (Tue, 03 Jun 2014) $ * @version $Revision: 296 $ * @author <a href="mailto:Rick@almende.org">Rick</a> */ public class NanoInstant extends AbstractInstant<NanoInstant> { /** */ private static final long serialVersionUID = 1L; /** */ // private static final Logger LOG = LogUtil.getLogger(NanoInstant.class); /** */ // private static final TimeUnit BASE_UNIT = TimeUnit.NANOS; /** */ public static final NanoInstant ZERO = new NanoInstant(null, 0); /** * {@link NanoInstant} constructor * * @param value */ public NanoInstant(final ClockID clockID, final Number value) { super(clockID, value, TimeUnit.NANOS); } // /** // * {@link NanoInstant} constructor // * // * @param value // */ // public NanoInstant(final ClockID clockID, final Number value, // final TimeUnit unit) // { // super(clockID, value, unit); // } // // /** @see Instant#getBaseUnit() */ // @Override // public TimeUnit getBaseUnit() // { // return BASE_UNIT; // } /** @see Instant#toUnit(TimeUnit) */ @Override public NanoInstant toUnit(final TimeUnit unit) { throw new RuntimeException( "Can't convert NanoInstant to another TimeUnit"); } /** @see Instant#plus(Number) */ @Override public NanoInstant plus(final Number value) { return new NanoInstant(getClockID(), getValue().doubleValue() + value.doubleValue()); } }
Java
package cat.ereza.customactivityoncrash.activity; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import cat.ereza.customactivityoncrash.CustomActivityOnCrash; /** * Created by zhy on 15/8/4. */ public class ClearStack extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Intent intent = getIntent().getParcelableExtra(CustomActivityOnCrash.KEY_CURRENT_INTENT); startActivity(intent); finish(); Runtime.getRuntime().exit(0); } }
Java
using System; using System.Collections.Generic; using System.Data.Services.Common; using System.IO; using System.Linq; using NuGet.Resources; namespace NuGet { [DataServiceKey("Id", "Version")] [EntityPropertyMapping("LastUpdated", SyndicationItemProperty.Updated, SyndicationTextContentKind.Plaintext, keepInContent: false)] [EntityPropertyMapping("Id", SyndicationItemProperty.Title, SyndicationTextContentKind.Plaintext, keepInContent: false)] [EntityPropertyMapping("Authors", SyndicationItemProperty.AuthorName, SyndicationTextContentKind.Plaintext, keepInContent: false)] [EntityPropertyMapping("Summary", SyndicationItemProperty.Summary, SyndicationTextContentKind.Plaintext, keepInContent: false)] [CLSCompliant(false)] public class DataServicePackage : IPackage { private readonly LazyWithRecreate<IPackage> _package; public DataServicePackage() { _package = new LazyWithRecreate<IPackage>(DownloadAndVerifyPackage, ShouldUpdatePackage); } public string Id { get; set; } public string Version { get; set; } public string Title { get; set; } public string Authors { get; set; } public string Owners { get; set; } public Uri IconUrl { get; set; } public Uri LicenseUrl { get; set; } public Uri ProjectUrl { get; set; } public Uri ReportAbuseUrl { get; set; } public Uri GalleryDetailsUrl { get; set; } public Uri DownloadUrl { get { return Context.GetReadStreamUri(this); } } public DateTimeOffset Published { get; set; } public DateTimeOffset LastUpdated { get; set; } public int DownloadCount { get; set; } public double Rating { get; set; } public int RatingsCount { get; set; } public bool RequireLicenseAcceptance { get; set; } public string Description { get; set; } public string Summary { get; set; } public string Language { get; set; } public string Tags { get; set; } public string Dependencies { get; set; } public string PackageHash { get; set; } internal string OldHash { get; set; } internal IDataServiceContext Context { get; set; } internal PackageDownloader Downloader { get; set; } IEnumerable<string> IPackageMetadata.Authors { get { if (String.IsNullOrEmpty(Authors)) { return Enumerable.Empty<string>(); } return Authors.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); } } IEnumerable<string> IPackageMetadata.Owners { get { if (String.IsNullOrEmpty(Owners)) { return Enumerable.Empty<string>(); } return Owners.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); } } IEnumerable<PackageDependency> IPackageMetadata.Dependencies { get { if (String.IsNullOrEmpty(Dependencies)) { return Enumerable.Empty<PackageDependency>(); } return from d in Dependencies.Split('|') let dependency = ParseDependency(d) where dependency != null select dependency; } } Version IPackageMetadata.Version { get { if (Version != null) { return new Version(Version); } return null; } } public IEnumerable<IPackageAssemblyReference> AssemblyReferences { get { return _package.Value.AssemblyReferences; } } public IEnumerable<FrameworkAssemblyReference> FrameworkAssemblies { get { return _package.Value.FrameworkAssemblies; } } public IEnumerable<IPackageFile> GetFiles() { return _package.Value.GetFiles(); } public Stream GetStream() { return _package.Value.GetStream(); } public override string ToString() { return this.GetFullName(); } private bool ShouldUpdatePackage() { return ShouldUpdatePackage(MachineCache.Default); } internal bool ShouldUpdatePackage(IPackageRepository repository) { // If the hash changed re-download the package. if (OldHash != PackageHash) { return true; } // If the package hasn't been cached, then re-download the package. IPackage package = GetPackage(repository); if (package == null) { return true; } // If the cached package hash isn't the same as incoming package hash // then re-download the package. string cachedHash = package.GetHash(); if (cachedHash != PackageHash) { return true; } return false; } private IPackage DownloadAndVerifyPackage() { return DownloadAndVerifyPackage(MachineCache.Default); } internal IPackage DownloadAndVerifyPackage(IPackageRepository repository) { if (String.IsNullOrEmpty(PackageHash)) { throw new InvalidOperationException(NuGetResources.PackageContentsVerifyError); } IPackage package = null; // If OldHash is null, we're looking at a new instance of the data service package. // The package might be stored in the cache so we're going to try the looking there before attempting a download. if (OldHash == null) { package = GetPackage(repository); } if (package == null) { byte[] hashBytes = Convert.FromBase64String(PackageHash); package = Downloader.DownloadPackage(DownloadUrl, hashBytes, this); // Add the package to the cache repository.AddPackage(package); // Clear the cache for this package ZipPackage.ClearCache(package); } // Update the hash OldHash = PackageHash; return package; } /// <summary> /// Parses a dependency from the feed in the format: /// id:versionSpec or id /// </summary> private static PackageDependency ParseDependency(string value) { if (String.IsNullOrWhiteSpace(value)) { return null; } string[] tokens = value.Trim().Split(new[] { ':' }, StringSplitOptions.RemoveEmptyEntries); if (tokens.Length == 0) { return null; } // Trim the id string id = tokens[0].Trim(); IVersionSpec versionSpec = null; if (tokens.Length > 1) { // Attempt to parse the version VersionUtility.TryParseVersionSpec(tokens[1], out versionSpec); } return new PackageDependency(id, versionSpec); } private IPackage GetPackage(IPackageRepository repository) { return repository.FindPackage(Id, ((IPackageMetadata)this).Version); } /// <summary> /// We can't use the built in Lazy for 2 reasons: /// 1. It caches the exception if any is thrown from the creator func (this means it won't retry calling the function). /// 2. There's no way to force a retry or expiration of the cache. /// </summary> private class LazyWithRecreate<T> { private readonly Func<T> _creator; private readonly Func<bool> _shouldRecreate; private T _value; private bool _isValueCreated; public LazyWithRecreate(Func<T> creator, Func<bool> shouldRecreate) { _creator = creator; _shouldRecreate = shouldRecreate; } public T Value { get { if (_shouldRecreate() || !_isValueCreated) { _value = _creator(); _isValueCreated = true; } return _value; } } } } }
Java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.cxf.tools.common; import javax.xml.namespace.QName; public final class ToolConstants { //public static final String TOOLSPECS_BASE = "/org/apache/cxf/tools/common/toolspec/toolspecs/"; public static final String TOOLSPECS_BASE = "/org/apache/cxf/tools/"; public static final String SCHEMA_URI = "http://www.w3.org/2001/XMLSchema"; public static final String XML_NAMESPACE_URI = "http://www.w3.org/XML/1998/namespace"; public static final String WSDL_NAMESPACE_URI = "http://schemas.xmlsoap.org/wsdl/"; public static final String WSA_NAMESPACE_URI = "http://www.w3.org/2005/08/addressing"; /** * Tools permit caller to pass in additional bean definitions. */ public static final String CFG_BEAN_CONFIG = "beans"; public static final String DEFAULT_TEMP_DIR = "gen_tmp"; public static final String CFG_OUTPUTDIR = "outputdir"; public static final String CFG_OUTPUTFILE = "outputfile"; public static final String CFG_WSDLURL = "wsdlurl"; public static final String CFG_WSDLLOCATION = "wsdlLocation"; public static final String CFG_WSDLLIST = "wsdlList"; public static final String CFG_NAMESPACE = "namespace"; public static final String CFG_VERBOSE = "verbose"; public static final String CFG_PORT = "port"; public static final String CFG_BINDING = "binding"; public static final String CFG_AUTORESOLVE = "autoNameResolution"; public static final String CFG_WEBSERVICE = "webservice"; public static final String CFG_SERVER = "server"; public static final String CFG_CLIENT = "client"; public static final String CFG_ALL = "all"; public static final String CFG_IMPL = "impl"; public static final String CFG_PACKAGENAME = "packagename"; public static final String CFG_JSPACKAGEPREFIX = "jspackageprefix"; public static final String CFG_NINCLUDE = "ninclude"; public static final String CFG_NEXCLUDE = "nexclude"; public static final String CFG_CMD_ARG = "args"; public static final String CFG_INSTALL_DIR = "install.dir"; public static final String CFG_PLATFORM_VERSION = "platform.version"; public static final String CFG_COMPILE = "compile"; public static final String CFG_CLASSDIR = "classdir"; public static final String CFG_EXTRA_SOAPHEADER = "exsoapheader"; public static final String CFG_DEFAULT_NS = "defaultns"; public static final String CFG_DEFAULT_EX = "defaultex"; public static final String CFG_NO_TYPES = "notypes"; public static final String CFG_XJC_ARGS = "xjc"; public static final String CFG_CATALOG = "catalog"; public static final String CFG_BAREMETHODS = "bareMethods"; public static final String CFG_ASYNCMETHODS = "asyncMethods"; public static final String CFG_MIMEMETHODS = "mimeMethods"; public static final String CFG_DEFAULT_VALUES = "defaultValues"; public static final String CFG_JAVASCRIPT_UTILS = "javascriptUtils"; public static final String CFG_VALIDATE_WSDL = "validate"; public static final String CFG_CREATE_XSD_IMPORTS = "createxsdimports"; /** * Front-end selection command-line option to java2ws. */ public static final String CFG_FRONTEND = "frontend"; public static final String CFG_DATABINDING = "databinding"; public static final String DEFAULT_ADDRESS = "http://localhost:9090"; // WSDL2Java Constants public static final String CFG_TYPES = "types"; public static final String CFG_INTERFACE = "interface"; public static final String CFG_NIGNOREEXCLUDE = "nignoreexclude"; public static final String CFG_ANT = "ant"; public static final String CFG_LIB_REF = "library.references"; public static final String CFG_ANT_PROP = "ant.prop"; public static final String CFG_NO_ADDRESS_BINDING = "noAddressBinding"; public static final String CFG_ALLOW_ELEMENT_REFS = "allowElementReferences"; public static final String CFG_RESERVE_NAME = "reserveClass"; public static final String CFG_FAULT_SERIAL_VERSION_UID = "faultSerialVersionUID"; public static final String CFG_EXCEPTION_SUPER = "exceptionSuper"; public static final String CFG_MARK_GENERATED = "mark-generated"; //Internal Flag to generate public static final String CFG_IMPL_CLASS = "implClass"; public static final String CFG_GEN_CLIENT = "genClient"; public static final String CFG_GEN_SERVER = "genServer"; public static final String CFG_GEN_IMPL = "genImpl"; public static final String CFG_GEN_TYPES = "genTypes"; public static final String CFG_GEN_SEI = "genSEI"; public static final String CFG_GEN_ANT = "genAnt"; public static final String CFG_GEN_SERVICE = "genService"; public static final String CFG_GEN_OVERWRITE = "overwrite"; public static final String CFG_GEN_FAULT = "genFault"; public static final String CFG_GEN_NEW_ONLY = "newonly"; // Java2WSDL Constants public static final String CFG_CLASSPATH = "classpath"; public static final String CFG_TNS = "tns"; public static final String CFG_SERVICENAME = "servicename"; public static final String CFG_SCHEMANS = "schemans"; public static final String CFG_USETYPES = "usetypes"; public static final String CFG_CLASSNAME = "classname"; public static final String CFG_PORTTYPE = "porttype"; public static final String CFG_SOURCEDIR = "sourcedir"; public static final String CFG_WSDL = "wsdl"; public static final String CFG_WRAPPERBEAN = "wrapperbean"; // WSDL2Service Constants public static final String CFG_ADDRESS = "address"; public static final String CFG_TRANSPORT = "transport"; public static final String CFG_SERVICE = "service"; public static final String CFG_BINDING_ATTR = "attrbinding"; public static final String CFG_SOAP12 = "soap12"; // WSDL2Soap Constants public static final String CFG_STYLE = "style"; public static final String CFG_USE = "use"; // XSD2WSDL Constants public static final String CFG_XSDURL = "xsdurl"; public static final String CFG_NAME = "name"; // WsdlValidator public static final String CFG_DEEP = "deep"; public static final String CFG_SCHEMA_DIR = "schemaDir"; public static final String CFG_SCHEMA_URL = "schemaURL"; public static final String CXF_SCHEMA_DIR = "cxf_schema_dir"; public static final String CXF_SCHEMAS_DIR_INJAR = "schemas/wsdl/"; public static final String CFG_SUPPRESS_WARNINGS = "suppressWarnings"; // WSDL2Java Processor Constants public static final String SEI_GENERATOR = "sei.generator"; public static final String FAULT_GENERATOR = "fault.generator"; public static final String TYPE_GENERATOR = "type.generator"; public static final String IMPL_GENERATOR = "impl.generator"; public static final String SVR_GENERATOR = "svr.generator"; public static final String CLT_GENERATOR = "clt.generator"; public static final String SERVICE_GENERATOR = "service.generator"; public static final String ANT_GENERATOR = "ant.generator"; public static final String HANDLER_GENERATOR = "handler.generator"; // Binding namespace public static final String NS_JAXWS_BINDINGS = "http://java.sun.com/xml/ns/jaxws"; public static final String NS_JAXB_BINDINGS = "http://java.sun.com/xml/ns/jaxb"; public static final QName JAXWS_BINDINGS = new QName(NS_JAXWS_BINDINGS, "bindings"); public static final QName JAXB_BINDINGS = new QName(NS_JAXB_BINDINGS, "bindings"); public static final String JAXWS_BINDINGS_WSDL_LOCATION = "wsdlLocation"; public static final String JAXWS_BINDING_NODE = "node"; public static final String JAXWS_BINDING_VERSION = "version"; public static final String ASYNC_METHOD_SUFFIX = "Async"; public static final String HANDLER_CHAINS_URI = "http://java.sun.com/xml/ns/javaee"; public static final String HANDLER_CHAIN = "handler-chain"; public static final String HANDLER_CHAINS = "handler-chains"; //public static final String RAW_JAXB_MODEL = "rawjaxbmodel"; // JMS address public static final String NS_JMS_ADDRESS = "http://cxf.apache.org/transports/jms"; public static final QName JMS_ADDRESS = new QName(NS_JMS_ADDRESS, "address"); public static final String JMS_ADDR_DEST_STYLE = "destinationStyle"; public static final String JMS_ADDR_JNDI_URL = "jndiProviderURL"; public static final String JMS_ADDR_JNDI_FAC = "jndiConnectionFactoryName"; public static final String JMS_ADDR_JNDI_DEST = "jndiDestinationName"; public static final String JMS_ADDR_MSG_TYPE = "messageType"; public static final String JMS_ADDR_INIT_CTX = "initialContextFactory"; public static final String JMS_ADDR_SUBSCRIBER_NAME = "durableSubscriberName"; public static final String JMS_ADDR_MSGID_TO_CORRID = "useMessageIDAsCorrelationID"; // XML Binding public static final String XMLBINDING_ROOTNODE = "rootNode"; public static final String XMLBINDING_HTTP_LOCATION = "location"; public static final String NS_XML_FORMAT = "http://cxf.apache.org/bindings/xformat"; public static final String XML_FORMAT_PREFIX = "xformat"; public static final String NS_XML_HTTP = "http://schemas.xmlsoap.org/wsdl/http/"; public static final String XML_HTTP_PREFIX = "http"; public static final QName XML_HTTP_ADDRESS = new QName(NS_XML_HTTP, "address"); public static final QName XML_FORMAT = new QName(NS_XML_FORMAT, "body"); public static final QName XML_BINDING_FORMAT = new QName(NS_XML_FORMAT, "binding"); public static final String XML_SCHEMA_COLLECTION = "xmlSchemaCollection"; public static final String PORTTYPE_MAP = "portTypeMap"; public static final String SCHEMA_TARGET_NAMESPACES = "schemaTargetNameSpaces"; public static final String WSDL_DEFINITION = "wsdlDefinition"; public static final String IMPORTED_DEFINITION = "importedDefinition"; public static final String IMPORTED_PORTTYPE = "importedPortType"; public static final String IMPORTED_SERVICE = "importedService"; public static final String BINDING_GENERATOR = "BindingGenerator"; // Tools framework public static final String FRONTEND_PLUGIN = "frontend"; public static final String DATABINDING_PLUGIN = "databinding"; public static final String RUNTIME_DATABINDING_CLASS = "databinding-class"; public static final String CFG_WSDL_VERSION = "wsdlversion"; // Suppress the code generation, in this case you can just get the generated code model public static final String CFG_SUPPRESS_GEN = "suppress"; public static final String DEFAULT_PACKAGE_NAME = "defaultnamespace"; //For java2ws tool public static final String SERVICE_LIST = "serviceList"; public static final String GEN_FROM_SEI = "genFromSEI"; public static final String JAXWS_FRONTEND = "jaxws"; public static final String SIMPLE_FRONTEND = "simple"; public static final String JAXB_DATABINDING = "jaxb"; public static final String AEGIS_DATABINDING = "aegis"; //For Simple FrontEnd public static final String SEI_CLASS = "seiClass"; public static final String IMPL_CLASS = "implClass"; public static final String SERVICE_NAME = "serviceName"; public static final String PORT_NAME = "portName"; public static final String DEFAULT_DATA_BINDING_NAME = "jaxb"; public static final String DATABIND_BEAN_NAME_SUFFIX = "DatabindingBean"; public static final String CLIENT_CLASS = "clientClass"; public static final String SERVER_CLASS = "serverClass"; public static final String CFG_JSPREFIXMAP = "javascriptPrefixMap"; private ToolConstants() { //utility class } }
Java
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (version 1.7.0_75) on Tue May 19 17:15:49 PDT 2015 --> <title>Uses of Class org.apache.hadoop.mapred.lib.db.DBOutputFormat.DBRecordWriter (Hadoop 2.6.0-mr1-cdh5.4.2 API)</title> <meta name="date" content="2015-05-19"> <link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class org.apache.hadoop.mapred.lib.db.DBOutputFormat.DBRecordWriter (Hadoop 2.6.0-mr1-cdh5.4.2 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><a href="../../../../../../../org/apache/hadoop/mapred/lib/db/DBOutputFormat.DBRecordWriter.html" title="class in org.apache.hadoop.mapred.lib.db">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../../index.html?org/apache/hadoop/mapred/lib/db/class-use/DBOutputFormat.DBRecordWriter.html" target="_top">Frames</a></li> <li><a href="DBOutputFormat.DBRecordWriter.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="Uses of Class org.apache.hadoop.mapred.lib.db.DBOutputFormat.DBRecordWriter" class="title">Uses of Class<br>org.apache.hadoop.mapred.lib.db.DBOutputFormat.DBRecordWriter</h2> </div> <div class="classUseContainer">No usage of org.apache.hadoop.mapred.lib.db.DBOutputFormat.DBRecordWriter</div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../../org/apache/hadoop/mapred/lib/db/DBOutputFormat.DBRecordWriter.html" title="class in org.apache.hadoop.mapred.lib.db">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../../index.html?org/apache/hadoop/mapred/lib/db/class-use/DBOutputFormat.DBRecordWriter.html" target="_top">Frames</a></li> <li><a href="DBOutputFormat.DBRecordWriter.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small>Copyright &copy; 2009 The Apache Software Foundation</small></p> </body> </html>
Java
<!doctype html> <html class="default no-js"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>PriceComparable | GDAX Trading Toolkit API Reference</title> <meta name="description" content=""> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="../assets/css/main.css"> </head> <body> <header> <div class="tsd-page-toolbar"> <div class="container"> <div class="table-wrap"> <div class="table-cell" id="tsd-search" data-index="../assets/js/search.js" data-base=".."> <div class="field"> <label for="tsd-search-field" class="tsd-widget search no-caption">Search</label> <input id="tsd-search-field" type="text" /> </div> <ul class="results"> <li class="state loading">Preparing search index...</li> <li class="state failure">The search index is not available</li> </ul> <a href="../index.html" class="title">GDAX Trading Toolkit API Reference</a> </div> <div class="table-cell" id="tsd-widgets"> <div id="tsd-filter"> <a href="#" class="tsd-widget options no-caption" data-toggle="options">Options</a> <div class="tsd-filter-group"> <div class="tsd-select" id="tsd-filter-visibility"> <span class="tsd-select-label">All</span> <ul class="tsd-select-list"> <li data-value="public">Public</li> <li data-value="protected">Public/Protected</li> <li data-value="private" class="selected">All</li> </ul> </div> <input type="checkbox" id="tsd-filter-inherited" checked /> <label class="tsd-widget" for="tsd-filter-inherited">Inherited</label> <input type="checkbox" id="tsd-filter-externals" checked /> <label class="tsd-widget" for="tsd-filter-externals">Externals</label> <input type="checkbox" id="tsd-filter-only-exported" /> <label class="tsd-widget" for="tsd-filter-only-exported">Only exported</label> </div> </div> <a href="#" class="tsd-widget menu no-caption" data-toggle="menu">Menu</a> </div> </div> </div> </div> <div class="tsd-page-title"> <div class="container"> <ul class="tsd-breadcrumb"> <li> <a href="../globals.html">Globals</a> </li> <li> <a href="../modules/_src_lib_orderbook_.html">&quot;src/lib/Orderbook&quot;</a> </li> <li> <a href="_src_lib_orderbook_.pricecomparable.html">PriceComparable</a> </li> </ul> <h1>Interface PriceComparable</h1> </div> </div> </header> <div class="container container-main"> <div class="row"> <div class="col-8 col-content"> <section class="tsd-panel tsd-hierarchy"> <h3>Hierarchy</h3> <ul class="tsd-hierarchy"> <li> <span class="target">PriceComparable</span> <ul class="tsd-hierarchy"> <li> <a href="_src_lib_orderbook_.pricelevel.html" class="tsd-signature-type">PriceLevel</a> </li> </ul> </li> </ul> </section> <section class="tsd-panel-group tsd-index-group"> <h2>Index</h2> <section class="tsd-panel tsd-index-panel"> <div class="tsd-index-content"> <section class="tsd-index-section "> <h3>Properties</h3> <ul class="tsd-index-list"> <li class="tsd-kind-property tsd-parent-kind-interface"><a href="_src_lib_orderbook_.pricecomparable.html#price" class="tsd-kind-icon">price</a></li> </ul> </section> </div> </section> </section> <section class="tsd-panel-group tsd-member-group "> <h2>Properties</h2> <section class="tsd-panel tsd-member tsd-kind-property tsd-parent-kind-interface"> <a name="price" class="tsd-anchor"></a> <h3>price</h3> <div class="tsd-signature tsd-kind-icon">price<span class="tsd-signature-symbol">:</span> <a href="../modules/_src_lib_types_.html#bigjs" class="tsd-signature-type">BigJS</a></div> <aside class="tsd-sources"> <ul> <li>Defined in <a href="https://github.com/coinbase/gdax-tt/blob/a3d18bb/src/lib/Orderbook.ts#L29">src/lib/Orderbook.ts:29</a></li> </ul> </aside> </section> </section> </div> <div class="col-4 col-menu menu-sticky-wrap menu-highlight"> <nav class="tsd-navigation primary"> <ul> <li class="globals "> <a href="../globals.html"><em>Globals</em></a> </li> <li class="current tsd-kind-external-module"> <a href="../modules/_src_lib_orderbook_.html">"src/lib/<wbr>Orderbook"</a> </li> </ul> </nav> <nav class="tsd-navigation secondary menu-sticky"> <ul class="before-current"> <li class=" tsd-kind-interface tsd-parent-kind-external-module"> <a href="_src_lib_orderbook_.basicorder.html" class="tsd-kind-icon">Basic<wbr>Order</a> </li> <li class=" tsd-kind-interface tsd-parent-kind-external-module"> <a href="_src_lib_orderbook_.cumulativepricelevel.html" class="tsd-kind-icon">Cumulative<wbr>Price<wbr>Level</a> </li> <li class=" tsd-kind-interface tsd-parent-kind-external-module"> <a href="_src_lib_orderbook_.level3order.html" class="tsd-kind-icon">Level3<wbr>Order</a> </li> <li class=" tsd-kind-interface tsd-parent-kind-external-module"> <a href="_src_lib_orderbook_.liveorder.html" class="tsd-kind-icon">Live<wbr>Order</a> </li> <li class=" tsd-kind-interface tsd-parent-kind-external-module"> <a href="_src_lib_orderbook_.orderbook.html" class="tsd-kind-icon">Orderbook</a> </li> <li class=" tsd-kind-interface tsd-parent-kind-external-module"> <a href="_src_lib_orderbook_.orderbookstate.html" class="tsd-kind-icon">Orderbook<wbr>State</a> </li> </ul> <ul class="current"> <li class="current tsd-kind-interface tsd-parent-kind-external-module"> <a href="_src_lib_orderbook_.pricecomparable.html" class="tsd-kind-icon">Price<wbr>Comparable</a> <ul> <li class=" tsd-kind-property tsd-parent-kind-interface"> <a href="_src_lib_orderbook_.pricecomparable.html#price" class="tsd-kind-icon">price</a> </li> </ul> </li> </ul> <ul class="after-current"> <li class=" tsd-kind-interface tsd-parent-kind-external-module"> <a href="_src_lib_orderbook_.pricelevel.html" class="tsd-kind-icon">Price<wbr>Level</a> </li> <li class=" tsd-kind-interface tsd-parent-kind-external-module"> <a href="_src_lib_orderbook_.pricelevelwithorders.html" class="tsd-kind-icon">Price<wbr>Level<wbr>With<wbr>Orders</a> </li> <li class=" tsd-kind-function tsd-parent-kind-external-module"> <a href="../modules/_src_lib_orderbook_.html#pricelevelfactory" class="tsd-kind-icon">Price<wbr>Level<wbr>Factory</a> </li> <li class=" tsd-kind-function tsd-parent-kind-external-module tsd-has-type-parameter"> <a href="../modules/_src_lib_orderbook_.html#pricetreefactory" class="tsd-kind-icon">Price<wbr>Tree<wbr>Factory</a> </li> </ul> </nav> </div> </div> </div> <footer class="with-border-bottom"> <div class="container"> <h2>Legend</h2> <div class="tsd-legend-group"> <ul class="tsd-legend"> <li class="tsd-kind-module"><span class="tsd-kind-icon">Module</span></li> <li class="tsd-kind-object-literal"><span class="tsd-kind-icon">Object literal</span></li> <li class="tsd-kind-variable"><span class="tsd-kind-icon">Variable</span></li> <li class="tsd-kind-function"><span class="tsd-kind-icon">Function</span></li> <li class="tsd-kind-function tsd-has-type-parameter"><span class="tsd-kind-icon">Function with type parameter</span></li> <li class="tsd-kind-index-signature"><span class="tsd-kind-icon">Index signature</span></li> <li class="tsd-kind-type-alias"><span class="tsd-kind-icon">Type alias</span></li> </ul> <ul class="tsd-legend"> <li class="tsd-kind-enum"><span class="tsd-kind-icon">Enumeration</span></li> <li class="tsd-kind-enum-member"><span class="tsd-kind-icon">Enumeration member</span></li> <li class="tsd-kind-property tsd-parent-kind-enum"><span class="tsd-kind-icon">Property</span></li> <li class="tsd-kind-method tsd-parent-kind-enum"><span class="tsd-kind-icon">Method</span></li> </ul> <ul class="tsd-legend"> <li class="tsd-kind-interface"><span class="tsd-kind-icon">Interface</span></li> <li class="tsd-kind-interface tsd-has-type-parameter"><span class="tsd-kind-icon">Interface with type parameter</span></li> <li class="tsd-kind-constructor tsd-parent-kind-interface"><span class="tsd-kind-icon">Constructor</span></li> <li class="tsd-kind-property tsd-parent-kind-interface"><span class="tsd-kind-icon">Property</span></li> <li class="tsd-kind-method tsd-parent-kind-interface"><span class="tsd-kind-icon">Method</span></li> <li class="tsd-kind-index-signature tsd-parent-kind-interface"><span class="tsd-kind-icon">Index signature</span></li> </ul> <ul class="tsd-legend"> <li class="tsd-kind-class"><span class="tsd-kind-icon">Class</span></li> <li class="tsd-kind-class tsd-has-type-parameter"><span class="tsd-kind-icon">Class with type parameter</span></li> <li class="tsd-kind-constructor tsd-parent-kind-class"><span class="tsd-kind-icon">Constructor</span></li> <li class="tsd-kind-property tsd-parent-kind-class"><span class="tsd-kind-icon">Property</span></li> <li class="tsd-kind-method tsd-parent-kind-class"><span class="tsd-kind-icon">Method</span></li> <li class="tsd-kind-accessor tsd-parent-kind-class"><span class="tsd-kind-icon">Accessor</span></li> <li class="tsd-kind-index-signature tsd-parent-kind-class"><span class="tsd-kind-icon">Index signature</span></li> </ul> <ul class="tsd-legend"> <li class="tsd-kind-constructor tsd-parent-kind-class tsd-is-inherited"><span class="tsd-kind-icon">Inherited constructor</span></li> <li class="tsd-kind-property tsd-parent-kind-class tsd-is-inherited"><span class="tsd-kind-icon">Inherited property</span></li> <li class="tsd-kind-method tsd-parent-kind-class tsd-is-inherited"><span class="tsd-kind-icon">Inherited method</span></li> <li class="tsd-kind-accessor tsd-parent-kind-class tsd-is-inherited"><span class="tsd-kind-icon">Inherited accessor</span></li> </ul> <ul class="tsd-legend"> <li class="tsd-kind-property tsd-parent-kind-class tsd-is-protected"><span class="tsd-kind-icon">Protected property</span></li> <li class="tsd-kind-method tsd-parent-kind-class tsd-is-protected"><span class="tsd-kind-icon">Protected method</span></li> <li class="tsd-kind-accessor tsd-parent-kind-class tsd-is-protected"><span class="tsd-kind-icon">Protected accessor</span></li> </ul> <ul class="tsd-legend"> <li class="tsd-kind-property tsd-parent-kind-class tsd-is-private"><span class="tsd-kind-icon">Private property</span></li> <li class="tsd-kind-method tsd-parent-kind-class tsd-is-private"><span class="tsd-kind-icon">Private method</span></li> <li class="tsd-kind-accessor tsd-parent-kind-class tsd-is-private"><span class="tsd-kind-icon">Private accessor</span></li> </ul> <ul class="tsd-legend"> <li class="tsd-kind-property tsd-parent-kind-class tsd-is-static"><span class="tsd-kind-icon">Static property</span></li> <li class="tsd-kind-call-signature tsd-parent-kind-class tsd-is-static"><span class="tsd-kind-icon">Static method</span></li> </ul> </div> </div> </footer> <div class="container tsd-generator"> <p>Generated using <a href="http://typedoc.org/" target="_blank">TypeDoc</a></p> </div> <div class="overlay"></div> <script src="../assets/js/main.js"></script> <script>if (location.protocol == 'file:') document.write('<script src="../assets/js/search.js"><' + '/script>');</script> </body> </html>
Java
/** * Copyright Pravega Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.pravega.client.connection.impl; import io.netty.bootstrap.ServerBootstrap; import io.netty.buffer.Unpooled; import io.netty.channel.Channel; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelOption; import io.netty.channel.ChannelPipeline; import io.netty.channel.EventLoopGroup; import io.netty.channel.epoll.EpollEventLoopGroup; import io.netty.channel.epoll.EpollServerSocketChannel; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioServerSocketChannel; import io.netty.handler.codec.LengthFieldBasedFrameDecoder; import io.netty.handler.logging.LogLevel; import io.netty.handler.logging.LoggingHandler; import io.netty.handler.ssl.SslContext; import io.netty.handler.ssl.SslContextBuilder; import io.netty.handler.ssl.SslHandler; import io.pravega.client.ClientConfig; import io.pravega.shared.protocol.netty.CommandDecoder; import io.pravega.shared.protocol.netty.CommandEncoder; import io.pravega.shared.protocol.netty.ConnectionFailedException; import io.pravega.shared.protocol.netty.FailingReplyProcessor; import io.pravega.shared.protocol.netty.PravegaNodeUri; import io.pravega.shared.protocol.netty.WireCommands; import io.pravega.test.common.AssertExtensions; import io.pravega.test.common.SecurityConfigDefaults; import io.pravega.test.common.TestUtils; import java.io.File; import java.net.URI; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.CompletableFuture; import java.util.function.Function; import javax.net.ssl.SSLEngine; import javax.net.ssl.SSLException; import javax.net.ssl.SSLParameters; import lombok.Cleanup; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.Timeout; import static io.pravega.shared.metrics.MetricNotifier.NO_OP_METRIC_NOTIFIER; import static io.pravega.shared.protocol.netty.WireCommands.MAX_WIRECOMMAND_SIZE; import static io.pravega.test.common.AssertExtensions.assertThrows; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertTrue; public class ConnectionPoolingTest { @Rule public Timeout globalTimeout = Timeout.seconds(1000); boolean ssl = false; private Channel serverChannel; private int port; private final String seg = "Segment-0"; private final long offset = 1234L; private final int length = 1024; private final String data = "data"; private final Function<Long, WireCommands.ReadSegment> readRequestGenerator = id -> new WireCommands.ReadSegment(seg, offset, length, "", id); private final Function<Long, WireCommands.SegmentRead> readResponseGenerator = id -> new WireCommands.SegmentRead(seg, offset, true, false, Unpooled.wrappedBuffer(data.getBytes(StandardCharsets.UTF_8)), id); private class EchoServerHandler extends ChannelInboundHandlerAdapter { @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { cause.printStackTrace(); ctx.close(); } @Override public void channelRead(ChannelHandlerContext ctx, Object message) { if (message instanceof WireCommands.Hello) { ctx.write(message); ctx.flush(); } else if (message instanceof WireCommands.ReadSegment) { WireCommands.ReadSegment msg = (WireCommands.ReadSegment) message; ctx.write(readResponseGenerator.apply(msg.getRequestId())); ctx.flush(); } } } @Before public void setUp() throws Exception { // Configure SSL. port = TestUtils.getAvailableListenPort(); final SslContext sslCtx; if (ssl) { try { sslCtx = SslContextBuilder.forServer( new File(SecurityConfigDefaults.TLS_SERVER_CERT_PATH), new File(SecurityConfigDefaults.TLS_SERVER_PRIVATE_KEY_PATH)) .build(); } catch (SSLException e) { throw new RuntimeException(e); } } else { sslCtx = null; } boolean nio = false; EventLoopGroup bossGroup; EventLoopGroup workerGroup; try { bossGroup = new EpollEventLoopGroup(1); workerGroup = new EpollEventLoopGroup(); } catch (ExceptionInInitializerError | UnsatisfiedLinkError | NoClassDefFoundError e) { nio = true; bossGroup = new NioEventLoopGroup(1); workerGroup = new NioEventLoopGroup(); } ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup) .channel(nio ? NioServerSocketChannel.class : EpollServerSocketChannel.class) .option(ChannelOption.SO_BACKLOG, 100) .handler(new LoggingHandler(LogLevel.INFO)) .childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ChannelPipeline p = ch.pipeline(); if (sslCtx != null) { SslHandler handler = sslCtx.newHandler(ch.alloc()); SSLEngine sslEngine = handler.engine(); SSLParameters sslParameters = sslEngine.getSSLParameters(); sslParameters.setEndpointIdentificationAlgorithm("LDAPS"); sslEngine.setSSLParameters(sslParameters); p.addLast(handler); } p.addLast(new CommandEncoder(null, NO_OP_METRIC_NOTIFIER), new LengthFieldBasedFrameDecoder(MAX_WIRECOMMAND_SIZE, 4, 4), new CommandDecoder(), new EchoServerHandler()); } }); // Start the server. serverChannel = b.bind("localhost", port).awaitUninterruptibly().channel(); } @After public void tearDown() throws Exception { serverChannel.close(); serverChannel.closeFuture(); } @Test public void testNonPooling() throws Exception { ClientConfig clientConfig = ClientConfig.builder() .controllerURI(URI.create((this.ssl ? "tls://" : "tcp://") + "localhost")) .trustStore(SecurityConfigDefaults.TLS_CA_CERT_PATH) .maxConnectionsPerSegmentStore(1) .build(); @Cleanup SocketConnectionFactoryImpl factory = new SocketConnectionFactoryImpl(clientConfig, 1); @Cleanup ConnectionPoolImpl connectionPool = new ConnectionPoolImpl(clientConfig, factory); ArrayBlockingQueue<WireCommands.SegmentRead> msgRead = new ArrayBlockingQueue<>(10); FailingReplyProcessor rp = new FailingReplyProcessor() { @Override public void connectionDropped() { } @Override public void segmentRead(WireCommands.SegmentRead data) { msgRead.add(data); } @Override public void processingFailure(Exception error) { } @Override public void authTokenCheckFailed(WireCommands.AuthTokenCheckFailed authTokenCheckFailed) { } }; Flow flow1 = new Flow(1, 0); @Cleanup ClientConnection connection1 = connectionPool.getClientConnection(flow1, new PravegaNodeUri("localhost", port), rp).join(); connection1.send(readRequestGenerator.apply(flow1.asLong())); WireCommands.SegmentRead msg = msgRead.take(); assertEquals(readResponseGenerator.apply(flow1.asLong()), msg); assertEquals(1, connectionPool.getActiveChannels().size()); // create a second connection, since not using a flow. @Cleanup ClientConnection connection2 = connectionPool.getClientConnection(new PravegaNodeUri("localhost", port), rp).join(); Flow flow2 = new Flow(2, 0); // send data over connection2 and verify. connection2.send(readRequestGenerator.apply(flow2.asLong())); msg = msgRead.take(); assertEquals(readResponseGenerator.apply(flow2.asLong()), msg); assertEquals(1, connectionPool.getActiveChannels().size()); assertEquals(2, factory.getOpenSocketCount()); // send data over connection1 and verify. connection1.send(readRequestGenerator.apply(flow1.asLong())); msg = msgRead.take(); assertEquals(readResponseGenerator.apply(flow1.asLong()), msg); // send data over connection2 and verify. connection2.send(readRequestGenerator.apply(flow2.asLong())); msg = msgRead.take(); assertEquals(readResponseGenerator.apply(flow2.asLong()), msg); // close a client connection, this should not close the channel. connection2.close(); assertThrows(ConnectionFailedException.class, () -> connection2.send(readRequestGenerator.apply(flow2.asLong()))); // verify we are able to send data over connection1. connection1.send(readRequestGenerator.apply(flow1.asLong())); msg = msgRead.take(); assertEquals(readResponseGenerator.apply(flow1.asLong()), msg); // close connection1 connection1.close(); assertThrows(ConnectionFailedException.class, () -> connection1.send(readRequestGenerator.apply(flow2.asLong()))); AssertExtensions.assertEventuallyEquals(0, () -> { connectionPool.pruneUnusedConnections(); return factory.getOpenSocketCount(); }, 10000); assertEquals(0, connectionPool.getActiveChannels().size()); } @Test public void testConnectionPooling() throws Exception { ClientConfig clientConfig = ClientConfig.builder() .controllerURI(URI.create((this.ssl ? "tls://" : "tcp://") + "localhost")) .trustStore(SecurityConfigDefaults.TLS_CA_CERT_PATH) .maxConnectionsPerSegmentStore(1) .build(); @Cleanup SocketConnectionFactoryImpl factory = new SocketConnectionFactoryImpl(clientConfig, 1); @Cleanup ConnectionPoolImpl connectionPool = new ConnectionPoolImpl(clientConfig, factory); ArrayBlockingQueue<WireCommands.SegmentRead> msgRead = new ArrayBlockingQueue<>(10); FailingReplyProcessor rp = new FailingReplyProcessor() { @Override public void connectionDropped() { } @Override public void segmentRead(WireCommands.SegmentRead data) { msgRead.add(data); } @Override public void processingFailure(Exception error) { } @Override public void authTokenCheckFailed(WireCommands.AuthTokenCheckFailed authTokenCheckFailed) { } }; Flow flow1 = new Flow(1, 0); @Cleanup ClientConnection connection1 = connectionPool.getClientConnection(flow1, new PravegaNodeUri("localhost", port), rp).join(); connection1.send(readRequestGenerator.apply(flow1.asLong())); WireCommands.SegmentRead msg = msgRead.take(); assertEquals(readResponseGenerator.apply(flow1.asLong()), msg); assertEquals(1, connectionPool.getActiveChannels().size()); // create a second connection, since the max number of connections is 1 this should reuse the same connection. Flow flow2 = new Flow(2, 0); CompletableFuture<ClientConnection> cf = new CompletableFuture<>(); connectionPool.getClientConnection(flow2, new PravegaNodeUri("localhost", port), rp, cf); @Cleanup ClientConnection connection2 = cf.join(); // send data over connection2 and verify. connection2.send(readRequestGenerator.apply(flow2.asLong())); msg = msgRead.take(); assertEquals(readResponseGenerator.apply(flow2.asLong()), msg); assertEquals(1, connectionPool.getActiveChannels().size()); assertEquals(1, factory.getOpenSocketCount()); // send data over connection1 and verify. connection1.send(readRequestGenerator.apply(flow1.asLong())); msg = msgRead.take(); assertEquals(readResponseGenerator.apply(flow1.asLong()), msg); // send data over connection2 and verify. connection2.send(readRequestGenerator.apply(flow2.asLong())); msg = msgRead.take(); assertEquals(readResponseGenerator.apply(flow2.asLong()), msg); // close a client connection, this should not close the channel. connection2.close(); assertThrows(ConnectionFailedException.class, () -> connection2.send(readRequestGenerator.apply(flow2.asLong()))); // verify we are able to send data over connection1. connection1.send(readRequestGenerator.apply(flow1.asLong())); msg = msgRead.take(); assertEquals(readResponseGenerator.apply(flow1.asLong()), msg); // close connection1 connection1.close(); assertThrows(ConnectionFailedException.class, () -> connection1.send(readRequestGenerator.apply(flow2.asLong()))); AssertExtensions.assertEventuallyEquals(0, () -> { connectionPool.pruneUnusedConnections(); return factory.getOpenSocketCount(); }, 10000); assertEquals(0, connectionPool.getActiveChannels().size()); } @Test public void testPoolBalancing() throws Exception { ClientConfig clientConfig = ClientConfig.builder() .controllerURI(URI.create((this.ssl ? "tls://" : "tcp://") + "localhost")) .trustStore(SecurityConfigDefaults.TLS_CA_CERT_PATH) .maxConnectionsPerSegmentStore(2) .build(); @Cleanup SocketConnectionFactoryImpl factory = new SocketConnectionFactoryImpl(clientConfig, 1); @Cleanup ConnectionPoolImpl connectionPool = new ConnectionPoolImpl(clientConfig, factory); ArrayBlockingQueue<WireCommands.SegmentRead> msgRead = new ArrayBlockingQueue<>(10); FailingReplyProcessor rp = new FailingReplyProcessor() { @Override public void connectionDropped() { } @Override public void segmentRead(WireCommands.SegmentRead data) { msgRead.add(data); } @Override public void processingFailure(Exception error) { } @Override public void authTokenCheckFailed(WireCommands.AuthTokenCheckFailed authTokenCheckFailed) { } }; Flow flow1 = new Flow(1, 0); @Cleanup ClientConnection connection1 = connectionPool.getClientConnection(flow1, new PravegaNodeUri("localhost", port), rp).join(); connection1.send(readRequestGenerator.apply(flow1.asLong())); WireCommands.SegmentRead msg = msgRead.take(); assertEquals(readResponseGenerator.apply(flow1.asLong()), msg); assertEquals(1, factory.getOpenSocketCount()); // create a second connection, since the max number of connections is 2 this should not reuse the same connection. Flow flow2 = new Flow(2, 0); @Cleanup ClientConnection connection2 = connectionPool.getClientConnection(flow2, new PravegaNodeUri("localhost", port), rp).join(); // send data over connection2 and verify. connection2.send(readRequestGenerator.apply(flow2.asLong())); msg = msgRead.take(); assertEquals(readResponseGenerator.apply(flow2.asLong()), msg); assertEquals(2, factory.getOpenSocketCount()); assertNotEquals(((FlowClientConnection) connection1).getChannel(), ((FlowClientConnection) connection2).getChannel()); // create a second connection, since the max number of connections is 2 this should reuse the same connection. Flow flow3 = new Flow(3, 0); @Cleanup ClientConnection connection3 = connectionPool.getClientConnection(flow3, new PravegaNodeUri("localhost", port), rp).join(); // send data over connection3 and verify. connection3.send(readRequestGenerator.apply(flow3.asLong())); msg = msgRead.take(); assertEquals(readResponseGenerator.apply(flow3.asLong()), msg); assertEquals(2, factory.getOpenSocketCount()); assertEquals(((FlowClientConnection) connection1).getChannel(), ((FlowClientConnection) connection3).getChannel()); Flow flow4 = new Flow(3, 0); @Cleanup ClientConnection connection4 = connectionPool.getClientConnection(flow4, new PravegaNodeUri("localhost", port), rp).join(); // send data over connection3 and verify. connection3.send(readRequestGenerator.apply(flow4.asLong())); msg = msgRead.take(); assertEquals(readResponseGenerator.apply(flow4.asLong()), msg); assertEquals(2, factory.getOpenSocketCount()); assertEquals(2, connectionPool.getActiveChannels().size()); assertNotEquals(((FlowClientConnection) connection3).getChannel(), ((FlowClientConnection) connection4).getChannel()); assertEquals(((FlowClientConnection) connection2).getChannel(), ((FlowClientConnection) connection4).getChannel()); } @Test public void testConcurrentRequests() throws Exception { ClientConfig clientConfig = ClientConfig.builder() .controllerURI(URI.create((this.ssl ? "tls://" : "tcp://") + "localhost")) .trustStore(SecurityConfigDefaults.TLS_CA_CERT_PATH) .maxConnectionsPerSegmentStore(1) .build(); @Cleanup SocketConnectionFactoryImpl factory = new SocketConnectionFactoryImpl(clientConfig, 1); @Cleanup ConnectionPoolImpl connectionPool = new ConnectionPoolImpl(clientConfig, factory); ArrayBlockingQueue<WireCommands.SegmentRead> msgRead = new ArrayBlockingQueue<>(10); FailingReplyProcessor rp = new FailingReplyProcessor() { @Override public void connectionDropped() { } @Override public void segmentRead(WireCommands.SegmentRead data) { msgRead.add(data); } @Override public void processingFailure(Exception error) { } @Override public void authTokenCheckFailed(WireCommands.AuthTokenCheckFailed authTokenCheckFailed) { } }; Flow flow1 = new Flow(1, 0); ClientConnection connection1 = connectionPool.getClientConnection(flow1, new PravegaNodeUri("localhost", port), rp).join(); // create a second connection, since the max number of connections is 1 this should reuse the same connection. Flow flow2 = new Flow(2, 0); ClientConnection connection2 = connectionPool.getClientConnection(flow2, new PravegaNodeUri("localhost", port), rp).join(); assertEquals(1, factory.getOpenSocketCount()); assertEquals(1, connectionPool.getActiveChannels().size()); connection1.send(readRequestGenerator.apply(flow1.asLong())); connection2.send(readRequestGenerator.apply(flow2.asLong())); List<WireCommands.SegmentRead> msgs = new ArrayList<WireCommands.SegmentRead>(); msgs.add(msgRead.take()); msgs.add(msgRead.take()); assertTrue(msgs.contains(readResponseGenerator.apply(flow1.asLong()))); assertTrue(msgs.contains(readResponseGenerator.apply(flow1.asLong()))); assertEquals(1, factory.getOpenSocketCount()); connection1.close(); connection2.close(); AssertExtensions.assertEventuallyEquals(0, () -> { connectionPool.pruneUnusedConnections(); return factory.getOpenSocketCount(); }, 10000); assertEquals(0, connectionPool.getActiveChannels().size()); } }
Java
#define DEBUG_TYPE "sil-simplify-cfg" #include "llvm/ADT/SmallPtrSet.h" #include "llvm/ADT/SmallVector.h" #include "swift/SIL/SILInstruction.h" #include "swift/SILOptimizer/Analysis/DominanceAnalysis.h" #include "swift/SILOptimizer/Utils/CFG.h" #include "swift/SILOptimizer/Utils/Local.h" #include "swift/SILOptimizer/Utils/SILInliner.h" using namespace swift; namespace { /// This is a class implementing a dominator-based jump-threading /// for checked_cast_br [exact]. class CheckedCastBrJumpThreading { // The checked_cast_br instruction, which // we try to jump-thread CheckedCastBranchInst *CCBI; // Basic block of the current checked_cast_br instruction. SILBasicBlock *BB; // Condition used by the current checked_cast_br instruction. SILValue Condition; // Success branch of the current checked_cast_br instruction. SILBasicBlock *SuccessBB; // Failure branch of the current checked_cast_br instruction. SILBasicBlock *FailureBB; // Current dominating checked_cast_br instruction. CheckedCastBranchInst *DomCCBI; // Basic block of the dominating checked_cast_br instruction. SILBasicBlock *DomBB; // Condition used by the dominating checked_cast_br instruction. SILValue DomCondition; // Success branch of the dominating checked_cast_br instruction. SILBasicBlock *DomSuccessBB; // Failure branch of the dominating checked_cast_br instruction. SILBasicBlock *DomFailureBB; // Current dominator tree node where we look for a dominating // checked_cast_br instruction. llvm::DomTreeNodeBase<SILBasicBlock> *Node; SILBasicBlock *ArgBB; // Dominator information to be used. DominanceInfo *DT; // Basic block created as a landing BB for all failure predecessors. SILBasicBlock *TargetFailureBB; // Basic block created as a landing BB for all success predecessors. SILBasicBlock *TargetSuccessBB; // Cloner used to clone the BB to FailureSuccessBB. Optional<BasicBlockCloner> FailureBBCloner; // Cloner used to clone the BB to TargetSuccessBB. Optional<BasicBlockCloner> SuccessBBCloner; // Predecessors reached only via a path along the // success branch of the dominating checked_cast_br. SmallVector<SILBasicBlock *, 8> SuccessPreds; // Predecessors reached only via a path along the // failure branch of the dominating checked_cast_br. SmallVector<SILBasicBlock *, 8> FailurePreds; // All other predecessors, where the outcome of the // checked_cast_br along the path is not known. SmallVector<SILBasicBlock *, 8> UnknownPreds; // Basic blocks to be added to for reprocessing // after jump-threading is done. SmallVectorImpl<SILBasicBlock *> &BlocksForWorklist; bool areEquivalentConditionsAlongPaths(); bool areEquivalentConditionsAlongSomePaths(); bool handleArgBBIsEntryBlock(SILBasicBlock *ArgBB); bool checkCloningConstraints(); void modifyCFGForUnknownPreds(); void modifyCFGForFailurePreds(); void modifyCFGForSuccessPreds(); void updateDominatorTree(); void updateSSA(); void addBlockToSimplifyCFGWorklist(SILBasicBlock *BB); void addBlocksToWorklist(); void classifyPredecessor( SILBasicBlock *Pred, SmallVectorImpl<SILBasicBlock *> &SuccessPreds, SmallVectorImpl<SILBasicBlock *> &FailurePreds, SmallVectorImpl<SILBasicBlock *> &UnknownPreds, bool SuccessDominates, bool FailureDominates); SILValue isArgValueEquivalentToCondition(SILValue Value, SILBasicBlock *DomBB, SILValue DomValue, DominanceInfo *DT); public: CheckedCastBrJumpThreading(DominanceInfo *DT, SmallVectorImpl<SILBasicBlock *> &BBs) : DT(DT), BlocksForWorklist(BBs) { } bool trySimplify(TermInst *Term); ArrayRef<SILBasicBlock*> getBlocksForWorklist() { return BlocksForWorklist; } }; } // end anonymous namespace /// Find a nearest common dominator for a given set of basic blocks. static DominanceInfoNode *findCommonDominator(ArrayRef<SILBasicBlock *> BBs, DominanceInfo *DT) { DominanceInfoNode *CommonDom = nullptr; for (auto *BB : BBs) { if (!CommonDom) { CommonDom = DT->getNode(BB); } else { CommonDom = DT->getNode( DT->findNearestCommonDominator(CommonDom->getBlock(), BB)); } } return CommonDom; } /// Find a nearest common dominator for all predecessors of /// a given basic block. static DominanceInfoNode *findCommonDominator(SILBasicBlock *BB, DominanceInfo *DT) { SmallVector<SILBasicBlock *, 8> Preds; for (auto *Pred: BB->getPreds()) Preds.push_back(Pred); return findCommonDominator(Preds, DT); } /// Estimate the cost of inlining a given basic block. static unsigned basicBlockInlineCost(SILBasicBlock *BB, unsigned Cutoff) { unsigned Cost = 0; for (auto &I : *BB) { auto ICost = instructionInlineCost(I); Cost += unsigned(ICost); if (Cost > Cutoff) return Cost; } return Cost; } /// We cannot duplicate blocks with AllocStack instructions (they need to be /// FIFO). Other instructions can be duplicated. static bool canDuplicateBlock(SILBasicBlock *BB) { for (auto &I : *BB) { if (!I.isTriviallyDuplicatable()) return false; } return true; } void CheckedCastBrJumpThreading::addBlockToSimplifyCFGWorklist(SILBasicBlock *BB) { BlocksForWorklist.push_back(BB); } /// Add affected blocks for re-processing by simplifyCFG void CheckedCastBrJumpThreading::addBlocksToWorklist() { if (TargetFailureBB) { if (!TargetFailureBB->pred_empty()) addBlockToSimplifyCFGWorklist(TargetFailureBB); } if (TargetSuccessBB) { if (!TargetSuccessBB->pred_empty()) addBlockToSimplifyCFGWorklist(TargetSuccessBB); } if (!BB->pred_empty()) addBlockToSimplifyCFGWorklist(BB); } /// Classify a predecessor of a BB containing checked_cast_br as being /// reachable via success or failure branches of a dominating checked_cast_br /// or as unknown if it can be reached via success or failure branches /// at the same time. void CheckedCastBrJumpThreading::classifyPredecessor( SILBasicBlock *Pred, SmallVectorImpl<SILBasicBlock *> &SuccessPreds, SmallVectorImpl<SILBasicBlock *> &FailurePreds, SmallVectorImpl<SILBasicBlock *> &UnknownPreds, bool SuccessDominates, bool FailureDominates) { if (SuccessDominates && FailureDominates) { UnknownPreds.push_back(Pred); return; } if (SuccessDominates) { SuccessPreds.push_back(Pred); return; } if (FailureDominates) { FailurePreds.push_back(Pred); return; } UnknownPreds.push_back(Pred); } /// Check if the root value for Value that comes /// along the path from DomBB is equivalent to the /// DomCondition. SILValue CheckedCastBrJumpThreading::isArgValueEquivalentToCondition( SILValue Value, SILBasicBlock *DomBB, SILValue DomValue, DominanceInfo *DT) { SmallPtrSet<ValueBase *, 16> SeenValues; DomValue = DomValue.stripClassCasts(); while (true) { Value = Value.stripClassCasts(); if (Value == DomValue) return Value; // We know how to propagate through BBArgs only. auto *V = dyn_cast<SILArgument>(Value); if (!V) return SILValue(); // Have we visited this BB already? if (!SeenValues.insert(Value.getDef()).second) return SILValue(); if (SeenValues.size() > 10) return SILValue(); SmallVector<SILValue, 4> IncomingValues; if (!V->getIncomingValues(IncomingValues) || IncomingValues.empty()) return SILValue(); ValueBase *Def = nullptr; for (auto IncomingValue : IncomingValues) { // Each incoming value should be either from a block // dominated by DomBB or it should be the value used in // condition in DomBB Value = IncomingValue.stripClassCasts(); if (Value == DomValue) continue; // Values should be the same if (!Def) Def = Value.getDef(); if (Def != Value.getDef()) return SILValue(); if (!DT->dominates(DomBB, Value.getDef()->getParentBB())) return SILValue(); // OK, this value is a potential candidate } Value = IncomingValues[0]; } } /// Update the SSA form after all changes. void CheckedCastBrJumpThreading::updateSSA() { assert(!(SuccessBBCloner.hasValue() && FailureBBCloner.hasValue()) && "Both cloners cannot be used at the same time yet"); // Now update the SSA form. if (!FailurePreds.empty() && FailureBBCloner.hasValue() && !SuccessBBCloner.hasValue()) updateSSAAfterCloning(*FailureBBCloner.getPointer(), TargetFailureBB, BB); if (SuccessBBCloner.hasValue() && !FailureBBCloner.hasValue()) { updateSSAAfterCloning(*SuccessBBCloner.getPointer(), TargetSuccessBB, BB); } } /// Update the SSA form after all changes. void CheckedCastBrJumpThreading::updateDominatorTree() { // Update the dominator tree. // If BB was IDom of something, then PredCBBI becomes the IDOM // of this after jump-threading. auto *BBDomNode = DT->getNode(BB); auto &Children = BBDomNode->getChildren(); if (Children.size() > 1) { SmallVector<DominanceInfoNode *, 16> ChildrenCopy; std::copy(Children.begin(), Children.end(), std::back_inserter(ChildrenCopy)); for (auto *Child : ChildrenCopy) { DT->changeImmediateDominator(Child, Node); } } DominanceInfoNode *CommonDom; // Find a common dominator for all unknown preds. if (!UnknownPreds.empty()) { // Find a new IDom for FailureBB CommonDom = findCommonDominator(FailureBB, DT); if (CommonDom) DT->changeImmediateDominator(FailureBB, CommonDom->getBlock()); CommonDom = findCommonDominator(UnknownPreds, DT); // This common dominator dominates the BB now. if (CommonDom) { DT->changeImmediateDominator(BB, CommonDom->getBlock()); } } // Find a common dominator for all failure preds. CommonDom = findCommonDominator(FailurePreds, DT); // This common dominator dominates the TargetFailureBB now. if (CommonDom) { DT->addNewBlock(TargetFailureBB, CommonDom->getBlock()); // Find a new IDom for FailureBB CommonDom = findCommonDominator(FailureBB, DT); if (CommonDom) DT->changeImmediateDominator(FailureBB, CommonDom->getBlock()); } // Find a common dominator for all success preds. CommonDom = findCommonDominator(SuccessPreds, DT); // This common dominator of all success preds dominates the BB now. if (CommonDom) { if (TargetSuccessBB) { DT->addNewBlock(TargetSuccessBB, CommonDom->getBlock()); } else { DT->changeImmediateDominator(BB, CommonDom->getBlock()); } CommonDom = findCommonDominator(SuccessBB, DT); if (CommonDom) DT->changeImmediateDominator(SuccessBB, CommonDom->getBlock()); } // End of dominator tree update. } void CheckedCastBrJumpThreading::modifyCFGForUnknownPreds() { if (UnknownPreds.empty()) return; // Check the FailureBB if it is a BB that contains a class_method // referring to the same value as a condition. This pattern is typical // for method chaining code like obj.method1().method2().etc() SILInstruction *Inst = &*FailureBB->begin(); if (ClassMethodInst *CMI = dyn_cast<ClassMethodInst>(Inst)) { if (CMI->getOperand() == Condition) { // Replace checked_cast_br by branch to FailureBB. SILBuilder(BB).createBranch(CCBI->getLoc(), FailureBB); CCBI->eraseFromParent(); } } } /// Create a copy of the BB as a landing BB /// for all FailurePreds. void CheckedCastBrJumpThreading::modifyCFGForFailurePreds() { if (FailurePreds.empty()) return; FailureBBCloner.emplace(BasicBlockCloner(BB)); FailureBBCloner->clone(); TargetFailureBB = FailureBBCloner->getDestBB(); auto *TI = TargetFailureBB->getTerminator(); SILBuilderWithScope Builder(TI); // This BB copy branches to a FailureBB. Builder.createBranch(TI->getLoc(), FailureBB); TI->eraseFromParent(); // Redirect all FailurePreds to the copy of BB. for (auto *Pred : FailurePreds) { TermInst *TI = Pred->getTerminator(); // Replace branch to BB by branch to TargetFailureBB. replaceBranchTarget(TI, BB, TargetFailureBB, /*PreserveArgs=*/true); Pred = nullptr; } } /// Create a copy of the BB or reuse BB as /// a landing basic block for all FailurePreds. void CheckedCastBrJumpThreading::modifyCFGForSuccessPreds() { if (!UnknownPreds.empty()) { if (!SuccessPreds.empty()) { // Create a copy of the BB as a landing BB. // for all SuccessPreds. SuccessBBCloner.emplace(BasicBlockCloner(BB)); SuccessBBCloner->clone(); TargetSuccessBB = SuccessBBCloner->getDestBB(); auto *TI = TargetSuccessBB->getTerminator(); SILBuilderWithScope Builder(TI); SmallVector<SILValue, 8> SuccessBBArgs; // Take argument value from the dominating BB. SuccessBBArgs.push_back(DomSuccessBB->getBBArg(0)); // This BB copy branches to SuccessBB. Builder.createBranch(TI->getLoc(), SuccessBB, SuccessBBArgs); TI->eraseFromParent(); // Redirect all SuccessPreds to the copy of BB. for (auto *Pred : SuccessPreds) { TermInst *TI = Pred->getTerminator(); // Replace branch to BB by branch to TargetSuccessBB. replaceBranchTarget(TI, BB, TargetSuccessBB, /*PreserveArgs=*/true); SuccessBBArgs.push_back(DomSuccessBB->getBBArg(0)); Pred = nullptr; } } } else { // There are no predecessors where it is not clear // if they are dominated by a success or failure branch // of DomBB. Therefore, there is no need to clone // the BB for SuccessPreds. Current BB can be re-used // instead as their target. // Add an unconditional jump at the end of the block. SmallVector<SILValue, 1> SuccessBBArgs; // Take argument value from the dominating BB SuccessBBArgs.push_back(DomSuccessBB->getBBArg(0)); SILBuilder(BB).createBranch(CCBI->getLoc(), SuccessBB, SuccessBBArgs); CCBI->eraseFromParent(); } } /// Handle a special case, where ArgBB is the entry block. bool CheckedCastBrJumpThreading::handleArgBBIsEntryBlock(SILBasicBlock *ArgBB) { if (ArgBB->getPreds().begin() == ArgBB->getPreds().end()) { // It must be the entry block // See if it is reached over Success or Failure path. bool SuccessDominates = DomSuccessBB == BB; bool FailureDominates = DomFailureBB == BB; classifyPredecessor(ArgBB, SuccessPreds, FailurePreds, UnknownPreds, SuccessDominates, FailureDominates); return true; } return false; } // Returns false if cloning required by jump threading cannot // be performed, because some of the constraints are violated. bool CheckedCastBrJumpThreading::checkCloningConstraints() { // Check some cloning related constraints. // If this argument from a different BB, then jump-threading // may require too much code duplication. if (ArgBB && ArgBB != BB) return false; // Bail out if current BB cannot be duplicated. if (!canDuplicateBlock(BB)) return false; // Check if code-bloat would be too big when this BB // is jump-threaded. // TODO: Make InlineCostCutoff parameter configurable? // Dec 1, 2014: // We looked at the inline costs of BBs from our benchmark suite // and found that currently the highest inline cost for the // whole benchmark suite is 12. In 95% of all cases it is <=3. const unsigned InlineCostCutoff = 20; if (basicBlockInlineCost(BB, InlineCostCutoff) >= InlineCostCutoff) return false; return true; } /// If conditions are not equivalent along all paths, try harder /// to check if they are actually equivalent along a subset of paths. /// To do it, try to back-propagate the Condition /// backwards and see if it is actually equivalent to DomCondition. /// along some of the paths. bool CheckedCastBrJumpThreading::areEquivalentConditionsAlongSomePaths() { auto *Arg = dyn_cast<SILArgument>(Condition); if (!Arg) return false; ArgBB = Arg->getParent(); if (!DT->dominates(DomBB, ArgBB)) return false; // Incoming values for the BBArg. SmallVector<SILValue, 4> IncomingValues; if (ArgBB != ArgBB->getParent()->begin() && (!Arg->getIncomingValues(IncomingValues) || IncomingValues.empty())) return false; // Check for each predecessor, if the incoming value coming from it // is equivalent to the DomCondition. If this is the case, it is // possible to try jump-threading along this path. if (!handleArgBBIsEntryBlock(ArgBB)) { // ArgBB is not the entry block and has predecessors. unsigned idx = 0; for (auto *PredBB : ArgBB->getPreds()) { auto IncomingValue = IncomingValues[idx]; SILValue ReachingValue = isArgValueEquivalentToCondition( IncomingValue, DomBB, DomCondition, DT); if (ReachingValue == SILValue()) { UnknownPreds.push_back(PredBB); idx++; continue; } // Condition is the same if BB is reached over a pass through Pred. DEBUG(llvm::dbgs() << "Condition is the same if reached over "); DEBUG(PredBB->print(llvm::dbgs())); // See if it is reached over Success or Failure path. bool SuccessDominates = DT->dominates(DomSuccessBB, PredBB) || DT->dominates(DomSuccessBB, BB) || DomSuccessBB == BB; bool FailureDominates = DT->dominates(DomFailureBB, PredBB) || DT->dominates(DomFailureBB, BB) || DomFailureBB == BB; classifyPredecessor( PredBB, SuccessPreds, FailurePreds, UnknownPreds, SuccessDominates, FailureDominates); idx++; } } else { // ArgBB is the entry block. Check that conditions are the equivalent in this // case as well. if (!isArgValueEquivalentToCondition(Condition, DomBB, DomCondition, DT)) return false; } // At this point we know for each predecessor of ArgBB if its reached // over the success, failure or unknown path from DomBB. // Now we can generate a new BB for preds reaching BB over the success // path and a new BB for preds reaching BB over the failure path. // Then we redirect those preds to those new basic blocks. return true; } /// Check if conditions of CCBI and DomCCBI are equivalent along /// all or at least some paths. bool CheckedCastBrJumpThreading::areEquivalentConditionsAlongPaths() { // Are conditions equivalent along all paths? if (DomCondition == Condition) { // Conditions are exactly the same, without any restrictions. // They are equivalent along all paths. // Figure out for each predecessor which branch of // the dominating checked_cast_br is used to reach it. for (auto *PredBB : BB->getPreds()) { // All predecessors should either unconditionally branch // to the current BB or be another checked_cast_br instruction. if (!dyn_cast<CheckedCastBranchInst>(PredBB->getTerminator()) && !dyn_cast<BranchInst>(PredBB->getTerminator())) return false; bool SuccessDominates = DT->dominates(DomSuccessBB, PredBB) || DomSuccessBB == BB; bool FailureDominates = DT->dominates(DomFailureBB, PredBB) || DomFailureBB == BB; classifyPredecessor(PredBB, SuccessPreds, FailurePreds, UnknownPreds, SuccessDominates, FailureDominates); } return true; } // Check if conditions are equivalent along a subset of reaching paths. return areEquivalentConditionsAlongSomePaths(); } /// Try performing a dominator-based jump-threading for /// checked_cast_br instructions. bool CheckedCastBrJumpThreading::trySimplify(TermInst *Term) { CCBI = cast<CheckedCastBranchInst>(Term); if (!CCBI) return false; // Init information about the checked_cast_br we try to // jump-thread. BB = Term->getParent(); Condition = Term->getOperand(0).stripClassCasts(); SuccessBB = CCBI->getSuccessBB(); FailureBB = CCBI->getFailureBB(); // Find a dominating checked_cast_br, which performs the same check. for (Node = DT->getNode(BB)->getIDom(); Node; Node = Node->getIDom()) { // Get current dominating block. DomBB = Node->getBlock(); auto *DomTerm = DomBB->getTerminator(); if (!DomTerm->getNumOperands()) continue; // Check that it is a dominating checked_cast_br. DomCCBI = dyn_cast<CheckedCastBranchInst>(DomTerm); if (!DomCCBI) continue; // We need to verify that the result type is the same in the // dominating checked_cast_br, but only for non-exact casts. // For exact casts, we are interested only in the // fact that the source operand is the same for // both instructions. if (!CCBI->isExact() && !DomCCBI->isExact()) { if (DomCCBI->getCastType() != CCBI->getCastType()) continue; } // Conservatively check that both checked_cast_br instructions // are either exact or non-exact. This is very conservative, // but safe. // // TODO: // If the dominating checked_cast_br is non-exact, then // it is in general not safe to assume that current exact cast // would have the same outcome. But if the dominating non-exact // checked_cast_br fails, then the current exact cast would // always fail as well. // // If the dominating checked_cast_br is exact then then // it is in general not safe to assume that the current non-exact // cast would have the same outcome. But if the dominating exact // checked_cast_br succeeds, then the current non-exact cast // would always succeed as well. // // TODO: In some specific cases, it is possible to prove that // success or failure of the dominating cast is equivalent to // the success or failure of the current cast, even if one // of them is exact and the other not. This is the case // e.g. if the class has no subclasses. if (DomCCBI->isExact() != CCBI->isExact()) continue; // Initialize state variables for the current round of checks // based on the found dominating checked_cast_br. DomSuccessBB = DomCCBI->getSuccessBB(); DomFailureBB = DomCCBI->getFailureBB(); DomCondition = DomTerm->getOperand(0).stripClassCasts(); // Init state variables for paths analysis SuccessPreds.clear(); FailurePreds.clear(); UnknownPreds.clear(); ArgBB = nullptr; // Init state variables for jump-threading transformation. TargetFailureBB = nullptr; TargetSuccessBB = nullptr; // Are conditions of CCBI and DomCCBI equivalent along (some) paths? // If this is the case, classify all incoming paths into SuccessPreds, // FailurePreds or UnknownPreds depending on how they reach CCBI. if (!areEquivalentConditionsAlongPaths()) continue; // Check if any jump-threading is required and possible. if (SuccessPreds.empty() && FailurePreds.empty()) return false; // If this check is reachable via success, failure and unknown // at the same time, then we don't know the outcome of the // dominating check. No jump-threading is possible in this case. if (!SuccessPreds.empty() && !FailurePreds.empty() && !UnknownPreds.empty()) { return false; } unsigned TotalPreds = SuccessPreds.size() + FailurePreds.size() + UnknownPreds.size(); // We only need to clone the BB if not all of its // predecessors are in the same group. if (TotalPreds != SuccessPreds.size() && TotalPreds != UnknownPreds.size()) { // Check some cloning related constraints. if (!checkCloningConstraints()) return false; } bool InvertSuccess = false; if (DomCCBI->isExact() && CCBI->isExact() && DomCCBI->getCastType() != CCBI->getCastType()) { if (TotalPreds == SuccessPreds.size()) { // The dominating exact cast was successful, but it casted to a // different type. Therefore, the current cast fails for sure. // Since we are going to change the BB, // add its successors and predecessors // for re-processing. InvertSuccess = true; } else { // Otherwise, we don't know if the current cast will succeed or // fail. return false; } } // If we have predecessors, where it is not known if they are reached over // success or failure path, we cannot eliminate a checked_cast_br. // We have to generate new dedicated BBs as landing BBs for all // FailurePreds and all SuccessPreds. // Since we are going to change the BB, // add its successors and predecessors // for re-processing. for (auto *B : BB->getPreds()) { addBlockToSimplifyCFGWorklist(B); } for (auto *B : BB->getSuccessorBlocks()) { addBlockToSimplifyCFGWorklist(B); } // Create a copy of the BB as a landing BB // for all FailurePreds. modifyCFGForFailurePreds(); if (InvertSuccess) { SILBuilder(BB).createBranch(CCBI->getLoc(), FailureBB); CCBI->eraseFromParent(); SuccessPreds.clear(); } else { // Create a copy of the BB or reuse BB as // a landing basic block for all SuccessPreds. modifyCFGForSuccessPreds(); } // Handle unknown preds. modifyCFGForUnknownPreds(); // Update the dominator tree after all changes. updateDominatorTree(); // Update the SSA form after all changes. updateSSA(); // Since a few BBs were changed now, add them for re-processing. addBlocksToWorklist(); return true; } // Jump-threading was not possible. return false; } namespace swift { bool tryCheckedCastBrJumpThreading(TermInst *Term, DominanceInfo *DT, SmallVectorImpl<SILBasicBlock *> &BBs) { CheckedCastBrJumpThreading CCBJumpThreading(DT, BBs); return CCBJumpThreading.trySimplify(Term); } } // end namespace swift
Java
package jp.co.omana.action; import org.seasar.struts.annotation.Execute; public class ServiceAction { @Execute(validator = false) public String index() { return "board.jsp"; } @Execute(validator = false) public String confirm() { return "index.jsp"; } @Execute(validator = false) public String finish() { return "index.jsp"; } }
Java
from turbo.flux import Mutation, register, dispatch, register_dispatch import mutation_types @register_dispatch('user', mutation_types.INCREASE) def increase(rank): pass def decrease(rank): return dispatch('user', mutation_types.DECREASE, rank) @register_dispatch('metric', 'inc_qps') def inc_qps(): pass
Java
/** * */ package com.sivalabs.demo.orders.repositories; import org.springframework.data.jpa.repository.JpaRepository; import com.sivalabs.demo.orders.entities.Order; /** * @author Siva * */ public interface OrderRepository extends JpaRepository<Order, Integer>{ }
Java
# Copyright 2014 NEC Corporation. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import testtools from tempest.api.compute import base from tempest.common import waiters from tempest import config from tempest.lib.common.utils import data_utils from tempest.lib import decorators from tempest.lib import exceptions CONF = config.CONF class MigrationsAdminTest(base.BaseV2ComputeAdminTest): """Test migration operations supported by admin user""" @classmethod def setup_clients(cls): super(MigrationsAdminTest, cls).setup_clients() cls.client = cls.os_admin.migrations_client @decorators.idempotent_id('75c0b83d-72a0-4cf8-a153-631e83e7d53f') def test_list_migrations(self): """Test admin user can get the migrations list""" self.client.list_migrations() @decorators.idempotent_id('1b512062-8093-438e-b47a-37d2f597cd64') @testtools.skipUnless(CONF.compute_feature_enabled.resize, 'Resize not available.') def test_list_migrations_in_flavor_resize_situation(self): """Admin can get the migrations list containing the resized server""" server = self.create_test_server(wait_until="ACTIVE") server_id = server['id'] self.resize_server(server_id, self.flavor_ref_alt) body = self.client.list_migrations()['migrations'] instance_uuids = [x['instance_uuid'] for x in body] self.assertIn(server_id, instance_uuids) def _flavor_clean_up(self, flavor_id): try: self.admin_flavors_client.delete_flavor(flavor_id) self.admin_flavors_client.wait_for_resource_deletion(flavor_id) except exceptions.NotFound: pass @decorators.idempotent_id('33f1fec3-ba18-4470-8e4e-1d888e7c3593') @testtools.skipUnless(CONF.compute_feature_enabled.resize, 'Resize not available.') def test_resize_server_revert_deleted_flavor(self): """Test reverting resized server with original flavor deleted Tests that we can revert the resize on an instance whose original flavor has been deleted. """ # First we have to create a flavor that we can delete so make a copy # of the normal flavor from which we'd create a server. flavor = self.admin_flavors_client.show_flavor( self.flavor_ref)['flavor'] flavor = self.admin_flavors_client.create_flavor( name=data_utils.rand_name('test_resize_flavor_'), ram=flavor['ram'], disk=flavor['disk'], vcpus=flavor['vcpus'] )['flavor'] self.addCleanup(self._flavor_clean_up, flavor['id']) # Set extra specs same as self.flavor_ref for the created flavor, # because the environment may need some special extra specs to # create server which should have been contained in # self.flavor_ref. extra_spec_keys = self.admin_flavors_client.list_flavor_extra_specs( self.flavor_ref)['extra_specs'] if extra_spec_keys: self.admin_flavors_client.set_flavor_extra_spec( flavor['id'], **extra_spec_keys) # Now boot a server with the copied flavor. server = self.create_test_server( wait_until='ACTIVE', flavor=flavor['id']) server = self.servers_client.show_server(server['id'])['server'] # If 'id' not in server['flavor'], we can only compare the flavor # details, so here we should save the to-be-deleted flavor's details, # for the flavor comparison after the server resizing. if not server['flavor'].get('id'): pre_flavor = {} body = self.flavors_client.show_flavor(flavor['id'])['flavor'] for key in ['name', 'ram', 'vcpus', 'disk']: pre_flavor[key] = body[key] # Delete the flavor we used to boot the instance. self._flavor_clean_up(flavor['id']) # Now resize the server and wait for it to go into verify state. self.servers_client.resize_server(server['id'], self.flavor_ref_alt) waiters.wait_for_server_status(self.servers_client, server['id'], 'VERIFY_RESIZE') # Now revert the resize, it should be OK even though the original # flavor used to boot the server was deleted. self.servers_client.revert_resize_server(server['id']) waiters.wait_for_server_status(self.servers_client, server['id'], 'ACTIVE') server = self.servers_client.show_server(server['id'])['server'] if server['flavor'].get('id'): msg = ('server flavor is not same as flavor!') self.assertEqual(flavor['id'], server['flavor']['id'], msg) else: self.assertEqual(pre_flavor['name'], server['flavor']['original_name'], "original_name in server flavor is not same as " "flavor name!") for key in ['ram', 'vcpus', 'disk']: msg = ('attribute %s in server flavor is not same as ' 'flavor!' % key) self.assertEqual(pre_flavor[key], server['flavor'][key], msg) def _test_cold_migrate_server(self, revert=False): if CONF.compute.min_compute_nodes < 2: msg = "Less than 2 compute nodes, skipping multinode tests." raise self.skipException(msg) server = self.create_test_server(wait_until="ACTIVE") src_host = self.get_host_for_server(server['id']) self.admin_servers_client.migrate_server(server['id']) waiters.wait_for_server_status(self.servers_client, server['id'], 'VERIFY_RESIZE') if revert: self.servers_client.revert_resize_server(server['id']) assert_func = self.assertEqual else: self.servers_client.confirm_resize_server(server['id']) assert_func = self.assertNotEqual waiters.wait_for_server_status(self.servers_client, server['id'], 'ACTIVE') dst_host = self.get_host_for_server(server['id']) assert_func(src_host, dst_host) @decorators.idempotent_id('4bf0be52-3b6f-4746-9a27-3143636fe30d') @testtools.skipUnless(CONF.compute_feature_enabled.cold_migration, 'Cold migration not available.') def test_cold_migration(self): """Test cold migrating server and then confirm the migration""" self._test_cold_migrate_server(revert=False) @decorators.idempotent_id('caa1aa8b-f4ef-4374-be0d-95f001c2ac2d') @testtools.skipUnless(CONF.compute_feature_enabled.cold_migration, 'Cold migration not available.') def test_revert_cold_migration(self): """Test cold migrating server and then revert the migration""" self._test_cold_migrate_server(revert=True)
Java
var structCO__config__t = [ [ "CNT_NMT", "structCO__config__t.html#aeef814580eb5ece5156e63bfc1b490c9", null ], [ "ENTRY_H1017", "structCO__config__t.html#ad17f77b55de3d90ec983fcac49eeab6d", null ], [ "CNT_HB_CONS", "structCO__config__t.html#a0031fc8f80e95f8480c918dbf8289671", null ], [ "ENTRY_H1016", "structCO__config__t.html#a0af4cf7d0355861e7f60206d794d6a91", null ], [ "CNT_EM", "structCO__config__t.html#a515e08f68835f71a6f145be8f27b510a", null ], [ "ENTRY_H1001", "structCO__config__t.html#a6a6c19e816fb76882e85b2c07c0d8f42", null ], [ "ENTRY_H1014", "structCO__config__t.html#a4827d94f6152cc12d86bd21312ae86e4", null ], [ "ENTRY_H1015", "structCO__config__t.html#a141f21b4d1730206d1af823fd6b13a01", null ], [ "ENTRY_H1003", "structCO__config__t.html#a7e320b309714b7f623c2006d45fee929", null ], [ "CNT_SDO_SRV", "structCO__config__t.html#aac83faf556924515cc2aa8003753ab58", null ], [ "ENTRY_H1200", "structCO__config__t.html#a05ab8adad4517850e31e5542895f7cc5", null ], [ "CNT_SDO_CLI", "structCO__config__t.html#a2fc9606643a7fb4d4237f01812d3a6d2", null ], [ "ENTRY_H1280", "structCO__config__t.html#a9f871c4ec753e8414cdb47eb78c3e09d", null ], [ "CNT_TIME", "structCO__config__t.html#ada2a43384a544fa2f235de24a874b1e6", null ], [ "ENTRY_H1012", "structCO__config__t.html#abac6be7122af1a8a4f9ae3ff5912d490", null ], [ "CNT_SYNC", "structCO__config__t.html#af6dbc7d9f31b4cb050e23af8cff3df33", null ], [ "ENTRY_H1005", "structCO__config__t.html#a02a4992f47db72816753ff2aa1964318", null ], [ "ENTRY_H1006", "structCO__config__t.html#aa9befdebbaaa22f309b9a1b115612071", null ], [ "ENTRY_H1007", "structCO__config__t.html#ad51ab63ca8b5836bf0dd8543f02db544", null ], [ "ENTRY_H1019", "structCO__config__t.html#a468c82f6a0afd757a6b78ce33532c0d2", null ], [ "CNT_RPDO", "structCO__config__t.html#a7a75302ac077462b67d767b0a11c9f56", null ], [ "ENTRY_H1400", "structCO__config__t.html#a5e0984d93183493d587523888465eaa7", null ], [ "ENTRY_H1600", "structCO__config__t.html#ab2ddc9943fd8c89f3b852d7ac9508d21", null ], [ "CNT_TPDO", "structCO__config__t.html#a1d830617f50e3235de35a403a1513693", null ], [ "ENTRY_H1800", "structCO__config__t.html#a29b98c08edfe0fba2e46c7af7a9edf6f", null ], [ "ENTRY_H1A00", "structCO__config__t.html#a43fd6a448c91910c603f2c7756610432", null ], [ "CNT_LEDS", "structCO__config__t.html#a642809cc681792bca855906241d891cc", null ], [ "CNT_GFC", "structCO__config__t.html#ae282bab830810b61c0b0c3223654d674", null ], [ "ENTRY_H1300", "structCO__config__t.html#a91c9f3ddb67231854af39224a9597e20", null ], [ "CNT_SRDO", "structCO__config__t.html#ae58a44be57069709af3f6acbd10953e1", null ], [ "ENTRY_H1301", "structCO__config__t.html#a87076cb1f9282d9720c21d395ff4e541", null ], [ "ENTRY_H1381", "structCO__config__t.html#a7b3172b29ce8751adcab9e4351dcc31e", null ], [ "ENTRY_H13FE", "structCO__config__t.html#a03fcaca5a8e0e71b86086908cae75f3d", null ], [ "ENTRY_H13FF", "structCO__config__t.html#aa4cb9674209b83e7f0e48b01feaa04ef", null ], [ "CNT_LSS_SLV", "structCO__config__t.html#a00a7a598b946ed13e3af7696e9f92dcc", null ], [ "CNT_LSS_MST", "structCO__config__t.html#ac253cae7039090a6c04bc1e385f3ec21", null ], [ "CNT_GTWA", "structCO__config__t.html#a64725014ecce342843f14ffc4b57e2a2", null ], [ "CNT_TRACE", "structCO__config__t.html#aaafb8ffff236b51cd6d4ab16426d460f", null ] ];
Java
/* Copyright 2017 Processwall 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. Company: Processwall Limited Address: The Winnowing House, Mill Lane, Askham Richard, York, YO23 3NW, United Kingdom Tel: +44 113 815 3440 Web: http://www.processwall.com Email: support@processwall.com */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Aras.ViewModel.Design.Applications { [Aras.ViewModel.Attributes.Application("Parts", "PartFamily", "Design", false)] public class Parts : Aras.ViewModel.Containers.Application { public Model.Design.Queries.Searches.Part SearchQuery { get; private set; } public Aras.ViewModel.Grids.Search Search { get; private set; } public Model.Design.Queries.Forms.Part FormQuery { get; private set; } public Forms.Part Form { get; private set; } private void Search_ItemsSelected(object sender, Aras.ViewModel.Grids.Search.ItemsSelectedEventArgs e) { if (this.Search.Selected.Count() > 0) { this.Form.Binding = this.Form.Store.Get(this.Search.Selected.First().ID); } else { this.Form.Binding = null; } } public Parts(Aras.ViewModel.Manager.Session Session) : base(Session) { this.Children.NotifyListChanged = false; // Create Search Query this.SearchQuery = new Model.Design.Queries.Searches.Part(this.Session.Model); // Create Search this.Search = new Aras.ViewModel.Grids.Search(this.Session); this.Search.Width = 300; this.Children.Add(this.Search); this.Search.Region = Aras.ViewModel.Regions.Left; this.Search.Binding = this.SearchQuery.Store; this.Search.Splitter = true; this.Search.ItemsSelected += Search_ItemsSelected; // Create Form Query this.FormQuery = new Model.Design.Queries.Forms.Part(this.Session.Model); // Create Form this.Form = new Forms.Part(this.Session, this.FormQuery.Store); this.Children.Add(this.Form); this.Children.NotifyListChanged = true; // Select First Part if (this.SearchQuery.Store.Count() > 0) { this.Search.Select(this.SearchQuery.Store.First()); } } } }
Java
<!-- @license Copyright (C) 2016 The Android Open Source Project Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <link rel="import" href="../../../bower_components/polymer/polymer.html"> <link rel="import" href="../../../behaviors/docs-url-behavior/docs-url-behavior.html"> <link rel="import" href="../../../behaviors/base-url-behavior/base-url-behavior.html"> <link rel="import" href="../../../behaviors/gr-admin-nav-behavior/gr-admin-nav-behavior.html"> <link rel="import" href="../../plugins/gr-endpoint-decorator/gr-endpoint-decorator.html"> <link rel="import" href="../../shared/gr-dropdown/gr-dropdown.html"> <link rel="import" href="../../shared/gr-icons/gr-icons.html"> <link rel="import" href="../../shared/gr-js-api-interface/gr-js-api-interface.html"> <link rel="import" href="../../shared/gr-rest-api-interface/gr-rest-api-interface.html"> <link rel="import" href="../gr-account-dropdown/gr-account-dropdown.html"> <link rel="import" href="../gr-smart-search/gr-smart-search.html"> <dom-module id="gr-main-header"> <template> <style include="shared-styles"> :host { display: block; } nav { align-items: center; display: flex; } .bigTitle { color: var(--header-text-color); font-size: var(--header-title-font-size); text-decoration: none; } .bigTitle:hover { text-decoration: underline; } /* TODO (viktard): Clean-up after chromium-style migrates to component. */ .titleText::before { background-image: var(--header-icon); background-size: var(--header-icon-size) var(--header-icon-size); background-repeat: no-repeat; content: ""; display: inline-block; height: var(--header-icon-size); margin-right: calc(var(--header-icon-size) / 4); vertical-align: text-bottom; width: var(--header-icon-size); } .titleText::after { content: var(--header-title-content); } ul { list-style: none; padding-left: 1em; } .links > li { cursor: default; display: inline-block; padding: 0; position: relative; } .linksTitle { display: inline-block; font-weight: var(--font-weight-bold); position: relative; text-transform: uppercase; } .linksTitle:hover { opacity: .75; } .rightItems { align-items: center; display: flex; flex: 1; justify-content: flex-end; } .rightItems gr-endpoint-decorator:not(:empty) { margin-left: 1em; } gr-smart-search { flex-grow: 1; margin-left: .5em; max-width: 500px; } gr-dropdown, .browse { padding: .6em .5em; } gr-dropdown { --gr-dropdown-item: { color: var(--primary-text-color); } } .settingsButton { margin-left: .5em; } .browse { color: var(--header-text-color); /* Same as gr-button */ margin: 5px 4px; text-decoration: none; } .invisible, .settingsButton, gr-account-dropdown { display: none; } :host([loading]) .accountContainer, :host([logged-in]) .loginButton, :host([logged-in]) .registerButton { display: none; } :host([logged-in]) .settingsButton, :host([logged-in]) gr-account-dropdown { display: inline; } .accountContainer { align-items: center; display: flex; margin: 0 -.5em 0 .5em; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .loginButton, .registerButton { padding: .5em 1em; } .dropdown-trigger { text-decoration: none; } .dropdown-content { background-color: var(--view-background-color); box-shadow: 0 1px 5px rgba(0, 0, 0, .3); } /* * We are not using :host to do this, because :host has a lowest css priority * compared to others. This means that using :host to do this would break styles. */ .linksTitle, .bigTitle, .loginButton, .registerButton, iron-icon, gr-account-dropdown { color: var(--header-text-color); } #mobileSearch { display: none; } @media screen and (max-width: 50em) { .bigTitle { font-size: var(--font-size-large); font-weight: var(--font-weight-bold); } gr-smart-search, .browse, .rightItems .hideOnMobile, .links > li.hideOnMobile { display: none; } #mobileSearch { display: inline-flex; } .accountContainer { margin-left: .5em !important; } gr-dropdown { padding: .5em 0 .5em .5em; } } </style> <nav> <a href$="[[_computeRelativeURL('/')]]" class="bigTitle"> <gr-endpoint-decorator name="header-title"> <span class="titleText"></span> </gr-endpoint-decorator> </a> <ul class="links"> <template is="dom-repeat" items="[[_links]]" as="linkGroup"> <li class$="[[linkGroup.class]]"> <gr-dropdown link down-arrow items = [[linkGroup.links]] horizontal-align="left"> <span class="linksTitle" id="[[linkGroup.title]]"> [[linkGroup.title]] </span> </gr-dropdown> </li> </template> </ul> <div class="rightItems"> <gr-endpoint-decorator class="hideOnMobile" name="header-small-banner"></gr-endpoint-decorator> <gr-smart-search id="search" search-query="{{searchQuery}}"></gr-smart-search> <gr-endpoint-decorator class="hideOnMobile" name="header-browse-source"></gr-endpoint-decorator> <div class="accountContainer" id="accountContainer"> <iron-icon id="mobileSearch" icon="gr-icons:search" on-tap='_onMobileSearchTap'></iron-icon> <div class$="[[_computeIsInvisible(_registerURL)]]"> <a class="registerButton" href$="[[_registerURL]]"> [[_registerText]] </a> </div> <a class="loginButton" href$="[[_loginURL]]">Sign in</a> <a class="settingsButton" href$="[[_generateSettingsLink()]]" title="Settings"> <iron-icon icon="gr-icons:settings"></iron-icon> </a> <gr-account-dropdown account="[[_account]]"></gr-account-dropdown> </div> </div> </nav> <gr-js-api-interface id="jsAPI"></gr-js-api-interface> <gr-rest-api-interface id="restAPI"></gr-rest-api-interface> </template> <script src="gr-main-header.js"></script> </dom-module>
Java
#include <tuple> #include "Vector2.h" Vector2::Vector2(void) { } Vector2::Vector2(float X, float Y) { this->X = X; this->Y = Y; } // Returns the length of the vector float Vector2::Magnitude() { return sqrt(X * X + Y * Y); } // Returns the length of the vector squared // Used for length comparisons without needing roots float Vector2::MagnitudeSquared() { return X * X + Y * Y; } // Normalizes the vector Vector2 Vector2::Normal() { float length = this->Magnitude(); if (length != 0) return Vector2(X / length, Y / length); return Vector2(); } // Sets the magnitude of the vector void Vector2::SetMagnitude(float mag) { Vector2 v = this->Normal(); X = v.X*mag; Y = v.Y*mag; } float Vector2::Dot(Vector2 other) { return X * other.X + Y * other.Y; } float Vector2::Cross(Vector2 other) { return X * other.Y - Y * other.X; } Vector2 Vector2::operator+(Vector2 other) { return Vector2(X + other.X, Y + other.Y); } Vector2 Vector2::operator-(Vector2 other) { return Vector2(X - other.X, Y - other.Y); } Vector2 Vector2::operator*(float scalar) { return Vector2(X * scalar, Y * scalar); } Vector2 Vector2::operator-() { return Vector2(-X, -Y); } Vector2& Vector2::operator+=(const Vector2& other) { X += other.X; Y += other.Y; return *this; } Vector2& Vector2::operator-=(const Vector2& other) { X -= other.X; Y -= other.Y; return *this; } Vector2& Vector2::operator*=(const Vector2& other) { X *= other.X; Y *= other.Y; return *this; } Vector2& Vector2::operator/=(const Vector2& other) { X /= other.X; Y /= other.Y; return *this; } bool operator==(const Vector2& L, const Vector2& R) { return std::tie(L.X, L.Y) == std::tie(R.X, R.Y); }
Java
/************************************************************ * * EaseMob CONFIDENTIAL * __________________ * Copyright (C) 2013-2014 EaseMob Technologies. All rights reserved. * * NOTICE: All information contained herein is, and remains * the property of EaseMob Technologies. * Dissemination of this information or reproduction of this material * is strictly forbidden unless prior written permission is obtained * from EaseMob Technologies. */ package com.easemob.chatuidemo.activity; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.Collections; import java.util.List; import android.annotation.SuppressLint; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.graphics.Bitmap; import android.graphics.PixelFormat; import android.hardware.Camera; import android.hardware.Camera.CameraInfo; import android.hardware.Camera.Parameters; import android.hardware.Camera.Size; import android.media.MediaRecorder; import android.media.MediaRecorder.OnErrorListener; import android.media.MediaRecorder.OnInfoListener; import android.media.MediaScannerConnection; import android.media.MediaScannerConnection.MediaScannerConnectionClient; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.os.PowerManager; import android.os.SystemClock; import android.text.TextUtils; import android.view.SurfaceHolder; import android.view.View; import android.view.View.OnClickListener; import android.view.Window; import android.view.WindowManager; import android.widget.Button; import android.widget.Chronometer; import android.widget.ImageView; import android.widget.Toast; import android.widget.VideoView; import com.easemob.chatuidemo.utils.CommonUtils; import com.easemob.chatuidemo.video.util.Utils; import com.easemob.qixin.R; import com.easemob.util.EMLog; import com.easemob.util.PathUtil; public class RecorderVideoActivity extends BaseActivity implements OnClickListener, SurfaceHolder.Callback, OnErrorListener, OnInfoListener { private static final String TAG = "RecorderVideoActivity"; private final static String CLASS_LABEL = "RecordActivity"; private PowerManager.WakeLock mWakeLock; private ImageView btnStart;// 开始录制按钮 private ImageView btnStop;// 停止录制按钮 private MediaRecorder mediaRecorder;// 录制视频的类 private VideoView mVideoView;// 显示视频的控件 String localPath = "";// 录制的视频路径 private Camera mCamera; // 预览的宽高 private int previewWidth = 480; private int previewHeight = 480; private Chronometer chronometer; private int frontCamera = 0;// 0是后置摄像头,1是前置摄像头 private Button btn_switch; Parameters cameraParameters = null; private SurfaceHolder mSurfaceHolder; int defaultVideoFrameRate = -1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE);// 去掉标题栏 getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);// 设置全屏 // 选择支持半透明模式,在有surfaceview的activity中使用 getWindow().setFormat(PixelFormat.TRANSLUCENT); setContentView(R.layout.recorder_activity); PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE); mWakeLock = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK, CLASS_LABEL); mWakeLock.acquire(); initViews(); } private void initViews() { btn_switch = (Button) findViewById(R.id.switch_btn); btn_switch.setOnClickListener(this); btn_switch.setVisibility(View.VISIBLE); mVideoView = (VideoView) findViewById(R.id.mVideoView); btnStart = (ImageView) findViewById(R.id.recorder_start); btnStop = (ImageView) findViewById(R.id.recorder_stop); btnStart.setOnClickListener(this); btnStop.setOnClickListener(this); mSurfaceHolder = mVideoView.getHolder(); mSurfaceHolder.addCallback(this); mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); chronometer = (Chronometer) findViewById(R.id.chronometer); } public void back(View view) { releaseRecorder(); releaseCamera(); finish(); } @Override protected void onResume() { super.onResume(); if (mWakeLock == null) { // 获取唤醒锁,保持屏幕常亮 PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE); mWakeLock = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK, CLASS_LABEL); mWakeLock.acquire(); } // if (!initCamera()) { // showFailDialog(); // } } @SuppressLint("NewApi") private boolean initCamera() { try { if (frontCamera == 0) { mCamera = Camera.open(CameraInfo.CAMERA_FACING_BACK); } else { mCamera = Camera.open(CameraInfo.CAMERA_FACING_FRONT); } Camera.Parameters camParams = mCamera.getParameters(); mCamera.lock(); mSurfaceHolder = mVideoView.getHolder(); mSurfaceHolder.addCallback(this); mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); mCamera.setDisplayOrientation(90); } catch (RuntimeException ex) { EMLog.e("video", "init Camera fail " + ex.getMessage()); return false; } return true; } private void handleSurfaceChanged() { if (mCamera == null) { finish(); return; } boolean hasSupportRate = false; List<Integer> supportedPreviewFrameRates = mCamera.getParameters() .getSupportedPreviewFrameRates(); if (supportedPreviewFrameRates != null && supportedPreviewFrameRates.size() > 0) { Collections.sort(supportedPreviewFrameRates); for (int i = 0; i < supportedPreviewFrameRates.size(); i++) { int supportRate = supportedPreviewFrameRates.get(i); if (supportRate == 15) { hasSupportRate = true; } } if (hasSupportRate) { defaultVideoFrameRate = 15; } else { defaultVideoFrameRate = supportedPreviewFrameRates.get(0); } } // 获取摄像头的所有支持的分辨率 List<Camera.Size> resolutionList = Utils.getResolutionList(mCamera); if (resolutionList != null && resolutionList.size() > 0) { Collections.sort(resolutionList, new Utils.ResolutionComparator()); Camera.Size previewSize = null; boolean hasSize = false; // 如果摄像头支持640*480,那么强制设为640*480 for (int i = 0; i < resolutionList.size(); i++) { Size size = resolutionList.get(i); if (size != null && size.width == 640 && size.height == 480) { previewSize = size; previewWidth = previewSize.width; previewHeight = previewSize.height; hasSize = true; break; } } // 如果不支持设为中间的那个 if (!hasSize) { int mediumResolution = resolutionList.size() / 2; if (mediumResolution >= resolutionList.size()) mediumResolution = resolutionList.size() - 1; previewSize = resolutionList.get(mediumResolution); previewWidth = previewSize.width; previewHeight = previewSize.height; } } } @Override protected void onPause() { super.onPause(); if (mWakeLock != null) { mWakeLock.release(); mWakeLock = null; } } @Override public void onClick(View view) { switch (view.getId()) { case R.id.switch_btn: switchCamera(); break; case R.id.recorder_start: // start recording if(!startRecording()) return; Toast.makeText(this, R.string.The_video_to_start, Toast.LENGTH_SHORT).show(); btn_switch.setVisibility(View.INVISIBLE); btnStart.setVisibility(View.INVISIBLE); btnStart.setEnabled(false); btnStop.setVisibility(View.VISIBLE); // 重置其他 chronometer.setBase(SystemClock.elapsedRealtime()); chronometer.start(); break; case R.id.recorder_stop: btnStop.setEnabled(false); // 停止拍摄 stopRecording(); btn_switch.setVisibility(View.VISIBLE); chronometer.stop(); btnStart.setVisibility(View.VISIBLE); btnStop.setVisibility(View.INVISIBLE); new AlertDialog.Builder(this) .setMessage(R.string.Whether_to_send) .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); sendVideo(null); } }) .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if(localPath != null){ File file = new File(localPath); if(file.exists()) file.delete(); } finish(); } }).setCancelable(false).show(); break; default: break; } } @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { // 将holder,这个holder为开始在oncreat里面取得的holder,将它赋给surfaceHolder mSurfaceHolder = holder; } @Override public void surfaceCreated(SurfaceHolder holder) { if (mCamera == null){ if(!initCamera()){ showFailDialog(); return; } } try { mCamera.setPreviewDisplay(mSurfaceHolder); mCamera.startPreview(); handleSurfaceChanged(); } catch (Exception e1) { EMLog.e("video", "start preview fail " + e1.getMessage()); showFailDialog(); } } @Override public void surfaceDestroyed(SurfaceHolder arg0) { EMLog.v("video", "surfaceDestroyed"); } public boolean startRecording(){ if (mediaRecorder == null){ if(!initRecorder()) return false; } mediaRecorder.setOnInfoListener(this); mediaRecorder.setOnErrorListener(this); mediaRecorder.start(); return true; } @SuppressLint("NewApi") private boolean initRecorder(){ if(!CommonUtils.isExitsSdcard()){ showNoSDCardDialog(); return false; } if (mCamera == null) { if(!initCamera()){ showFailDialog(); return false; } } mVideoView.setVisibility(View.VISIBLE); // TODO init button mCamera.stopPreview(); mediaRecorder = new MediaRecorder(); mCamera.unlock(); mediaRecorder.setCamera(mCamera); mediaRecorder.setAudioSource(MediaRecorder.AudioSource.DEFAULT); // 设置录制视频源为Camera(相机) mediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA); if (frontCamera == 1) { mediaRecorder.setOrientationHint(270); } else { mediaRecorder.setOrientationHint(90); } // 设置录制完成后视频的封装格式THREE_GPP为3gp.MPEG_4为mp4 mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4); mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC); // 设置录制的视频编码h263 h264 mediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264); // 设置视频录制的分辨率。必须放在设置编码和格式的后面,否则报错 mediaRecorder.setVideoSize(previewWidth, previewHeight); // 设置视频的比特率 mediaRecorder.setVideoEncodingBitRate(384 * 1024); // // 设置录制的视频帧率。必须放在设置编码和格式的后面,否则报错 if (defaultVideoFrameRate != -1) { mediaRecorder.setVideoFrameRate(defaultVideoFrameRate); } // 设置视频文件输出的路径 localPath = PathUtil.getInstance().getVideoPath() + "/" + System.currentTimeMillis() + ".mp4"; mediaRecorder.setOutputFile(localPath); mediaRecorder.setMaxDuration(30000); mediaRecorder.setPreviewDisplay(mSurfaceHolder.getSurface()); try { mediaRecorder.prepare(); } catch (IllegalStateException e) { e.printStackTrace(); return false; } catch (IOException e) { e.printStackTrace(); return false; } return true; } public void stopRecording() { if (mediaRecorder != null) { mediaRecorder.setOnErrorListener(null); mediaRecorder.setOnInfoListener(null); try { mediaRecorder.stop(); } catch (IllegalStateException e) { EMLog.e("video", "stopRecording error:" + e.getMessage()); } } releaseRecorder(); if (mCamera != null) { mCamera.stopPreview(); releaseCamera(); } } private void releaseRecorder() { if (mediaRecorder != null) { mediaRecorder.release(); mediaRecorder = null; } } protected void releaseCamera() { try { if (mCamera != null) { mCamera.stopPreview(); mCamera.release(); mCamera = null; } } catch (Exception e) { } } @SuppressLint("NewApi") public void switchCamera() { if (mCamera == null) { return; } if (Camera.getNumberOfCameras() >= 2) { btn_switch.setEnabled(false); if (mCamera != null) { mCamera.stopPreview(); mCamera.release(); mCamera = null; } switch (frontCamera) { case 0: mCamera = Camera.open(CameraInfo.CAMERA_FACING_FRONT); frontCamera = 1; break; case 1: mCamera = Camera.open(CameraInfo.CAMERA_FACING_BACK); frontCamera = 0; break; } try { mCamera.lock(); mCamera.setDisplayOrientation(90); mCamera.setPreviewDisplay(mVideoView.getHolder()); mCamera.startPreview(); } catch (IOException e) { mCamera.release(); mCamera = null; } btn_switch.setEnabled(true); } } MediaScannerConnection msc = null; ProgressDialog progressDialog = null; public void sendVideo(View view) { if (TextUtils.isEmpty(localPath)) { EMLog.e("Recorder", "recorder fail please try again!"); return; } if(msc == null) msc = new MediaScannerConnection(this, new MediaScannerConnectionClient() { @Override public void onScanCompleted(String path, Uri uri) { EMLog.d(TAG, "scanner completed"); msc.disconnect(); progressDialog.dismiss(); setResult(RESULT_OK, getIntent().putExtra("uri", uri)); finish(); } @Override public void onMediaScannerConnected() { msc.scanFile(localPath, "video/*"); } }); if(progressDialog == null){ progressDialog = new ProgressDialog(this); progressDialog.setMessage("processing..."); progressDialog.setCancelable(false); } progressDialog.show(); msc.connect(); } @Override public void onInfo(MediaRecorder mr, int what, int extra) { EMLog.v("video", "onInfo"); if (what == MediaRecorder.MEDIA_RECORDER_INFO_MAX_DURATION_REACHED) { EMLog.v("video", "max duration reached"); stopRecording(); btn_switch.setVisibility(View.VISIBLE); chronometer.stop(); btnStart.setVisibility(View.VISIBLE); btnStop.setVisibility(View.INVISIBLE); chronometer.stop(); if (localPath == null) { return; } String st3 = getResources().getString(R.string.Whether_to_send); new AlertDialog.Builder(this) .setMessage(st3) .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface arg0, int arg1) { arg0.dismiss(); sendVideo(null); } }).setNegativeButton(R.string.cancel, null) .setCancelable(false).show(); } } @Override public void onError(MediaRecorder mr, int what, int extra) { EMLog.e("video", "recording onError:"); stopRecording(); Toast.makeText(this, "Recording error has occurred. Stopping the recording", Toast.LENGTH_SHORT).show(); } public void saveBitmapFile(Bitmap bitmap) { File file = new File(Environment.getExternalStorageDirectory(), "a.jpg"); try { BufferedOutputStream bos = new BufferedOutputStream( new FileOutputStream(file)); bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos); bos.flush(); bos.close(); } catch (IOException e) { e.printStackTrace(); } } @Override protected void onDestroy() { super.onDestroy(); releaseCamera(); if (mWakeLock != null) { mWakeLock.release(); mWakeLock = null; } } @Override public void onBackPressed() { back(null); } private void showFailDialog() { new AlertDialog.Builder(this) .setTitle(R.string.prompt) .setMessage(R.string.Open_the_equipment_failure) .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { finish(); } }).setCancelable(false).show(); } private void showNoSDCardDialog() { new AlertDialog.Builder(this) .setTitle(R.string.prompt) .setMessage("No sd card!") .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { finish(); } }).setCancelable(false).show(); } }
Java
// Copyright © 2017 Chocolatey Software, Inc // Copyright © 2011 - 2017 RealDimensions Software, 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. namespace chocolatey.tests.integration.scenarios { using System.Collections.Generic; using System.Linq; using bdddoc.core; using chocolatey.infrastructure.app; using chocolatey.infrastructure.app.commands; using chocolatey.infrastructure.app.configuration; using chocolatey.infrastructure.app.services; using chocolatey.infrastructure.results; using NuGet; using Should; public class ListScenarios { public abstract class ScenariosBase : TinySpec { protected IList<PackageResult> Results; protected ChocolateyConfiguration Configuration; protected IChocolateyPackageService Service; public override void Context() { Configuration = Scenario.list(); Scenario.reset(Configuration); Scenario.add_packages_to_source_location(Configuration, Configuration.Input + "*" + Constants.PackageExtension); Scenario.add_packages_to_source_location(Configuration, "installpackage*" + Constants.PackageExtension); Scenario.install_package(Configuration, "installpackage", "1.0.0"); Scenario.install_package(Configuration, "upgradepackage", "1.0.0"); Service = NUnitSetup.Container.GetInstance<IChocolateyPackageService>(); } } [Concern(typeof(ChocolateyListCommand))] public class when_searching_packages_with_no_filter_happy_path : ScenariosBase { public override void Because() { MockLogger.reset(); Results = Service.list_run(Configuration).ToList(); } [Fact] public void should_list_available_packages_only_once() { MockLogger.contains_message_count("upgradepackage").ShouldEqual(1); } [Fact] public void should_contain_packages_and_versions_with_a_space_between_them() { MockLogger.contains_message("upgradepackage 1.1.0").ShouldBeTrue(); } [Fact] public void should_not_contain_packages_and_versions_with_a_pipe_between_them() { MockLogger.contains_message("upgradepackage|1.1.0").ShouldBeFalse(); } [Fact] public void should_contain_a_summary() { MockLogger.contains_message("packages found").ShouldBeTrue(); } [Fact] public void should_contain_debugging_messages() { MockLogger.contains_message("Searching for package information", LogLevel.Debug).ShouldBeTrue(); MockLogger.contains_message("Running list with the following filter", LogLevel.Debug).ShouldBeTrue(); MockLogger.contains_message("Start of List", LogLevel.Debug).ShouldBeTrue(); MockLogger.contains_message("End of List", LogLevel.Debug).ShouldBeTrue(); } } [Concern(typeof(ChocolateyListCommand))] public class when_searching_for_a_particular_package : ScenariosBase { public override void Context() { base.Context(); Configuration.Input = Configuration.PackageNames = "upgradepackage"; } public override void Because() { MockLogger.reset(); Results = Service.list_run(Configuration).ToList(); } [Fact] public void should_contain_packages_and_versions_with_a_space_between_them() { MockLogger.contains_message("upgradepackage 1.1.0").ShouldBeTrue(); } [Fact] public void should_not_contain_packages_that_do_not_match() { MockLogger.contains_message("installpackage").ShouldBeFalse(); } [Fact] public void should_contain_a_summary() { MockLogger.contains_message("packages found").ShouldBeTrue(); } [Fact] public void should_contain_debugging_messages() { MockLogger.contains_message("Searching for package information", LogLevel.Debug).ShouldBeTrue(); MockLogger.contains_message("Running list with the following filter", LogLevel.Debug).ShouldBeTrue(); MockLogger.contains_message("Start of List", LogLevel.Debug).ShouldBeTrue(); MockLogger.contains_message("End of List", LogLevel.Debug).ShouldBeTrue(); } } [Concern(typeof(ChocolateyListCommand))] public class when_searching_all_available_packages : ScenariosBase { public override void Context() { base.Context(); Configuration.AllVersions = true; } public override void Because() { MockLogger.reset(); Results = Service.list_run(Configuration).ToList(); } [Fact] public void should_list_available_packages_as_many_times_as_they_show_on_the_feed() { MockLogger.contains_message_count("upgradepackage").ShouldNotEqual(0); MockLogger.contains_message_count("upgradepackage").ShouldNotEqual(1); } [Fact] public void should_contain_packages_and_versions_with_a_space_between_them() { MockLogger.contains_message("upgradepackage 1.1.0").ShouldBeTrue(); } [Fact] public void should_not_contain_packages_and_versions_with_a_pipe_between_them() { MockLogger.contains_message("upgradepackage|1.1.0").ShouldBeFalse(); } [Fact] public void should_contain_a_summary() { MockLogger.contains_message("packages found").ShouldBeTrue(); } [Fact] public void should_contain_debugging_messages() { MockLogger.contains_message("Searching for package information", LogLevel.Debug).ShouldBeTrue(); MockLogger.contains_message("Running list with the following filter", LogLevel.Debug).ShouldBeTrue(); MockLogger.contains_message("Start of List", LogLevel.Debug).ShouldBeTrue(); MockLogger.contains_message("End of List", LogLevel.Debug).ShouldBeTrue(); } } [Concern(typeof(ChocolateyListCommand))] public class when_searching_packages_with_verbose : ScenariosBase { public override void Context() { base.Context(); Configuration.Verbose = true; } public override void Because() { MockLogger.reset(); Results = Service.list_run(Configuration).ToList(); } [Fact] public void should_contain_packages_and_versions_with_a_space_between_them() { MockLogger.contains_message("upgradepackage 1.1.0").ShouldBeTrue(); } [Fact] public void should_contain_description() { MockLogger.contains_message("Description: ").ShouldBeTrue(); } [Fact] public void should_contain_tags() { MockLogger.contains_message("Tags: ").ShouldBeTrue(); } [Fact] public void should_contain_download_counts() { MockLogger.contains_message("Number of Downloads: ").ShouldBeTrue(); } [Fact] public void should_not_contain_packages_and_versions_with_a_pipe_between_them() { MockLogger.contains_message("upgradepackage|1.1.0").ShouldBeFalse(); } [Fact] public void should_contain_a_summary() { MockLogger.contains_message("packages found").ShouldBeTrue(); } [Fact] public void should_contain_debugging_messages() { MockLogger.contains_message("Searching for package information", LogLevel.Debug).ShouldBeTrue(); MockLogger.contains_message("Running list with the following filter", LogLevel.Debug).ShouldBeTrue(); MockLogger.contains_message("Start of List", LogLevel.Debug).ShouldBeTrue(); MockLogger.contains_message("End of List", LogLevel.Debug).ShouldBeTrue(); } } [Concern(typeof(ChocolateyListCommand))] public class when_listing_local_packages : ScenariosBase { public override void Context() { base.Context(); Configuration.ListCommand.LocalOnly = true; Configuration.Sources = ApplicationParameters.PackagesLocation; } public override void Because() { MockLogger.reset(); Results = Service.list_run(Configuration).ToList(); } [Fact] public void should_contain_packages_and_versions_with_a_space_between_them() { MockLogger.contains_message("upgradepackage 1.0.0").ShouldBeTrue(); } [Fact] public void should_not_contain_packages_and_versions_with_a_pipe_between_them() { MockLogger.contains_message("upgradepackage|1.0.0").ShouldBeFalse(); } [Fact] public void should_contain_a_summary() { MockLogger.contains_message("packages installed").ShouldBeTrue(); } [Fact] public void should_contain_debugging_messages() { MockLogger.contains_message("Searching for package information", LogLevel.Debug).ShouldBeTrue(); MockLogger.contains_message("Running list with the following filter", LogLevel.Debug).ShouldBeTrue(); MockLogger.contains_message("Start of List", LogLevel.Debug).ShouldBeTrue(); MockLogger.contains_message("End of List", LogLevel.Debug).ShouldBeTrue(); } } [Concern(typeof(ChocolateyListCommand))] public class when_listing_local_packages_limiting_output : ScenariosBase { public override void Context() { base.Context(); Configuration.ListCommand.LocalOnly = true; Configuration.Sources = ApplicationParameters.PackagesLocation; Configuration.RegularOutput = false; } public override void Because() { MockLogger.reset(); Results = Service.list_run(Configuration).ToList(); } [Fact] public void should_contain_packages_and_versions_with_a_pipe_between_them() { MockLogger.contains_message("upgradepackage|1.0.0").ShouldBeTrue(); } [Fact] public void should_only_have_messages_related_to_package_information() { var count = MockLogger.Messages.SelectMany(messageLevel => messageLevel.Value.or_empty_list_if_null()).Count(); count.ShouldEqual(2); } [Fact] public void should_not_contain_packages_and_versions_with_a_space_between_them() { MockLogger.contains_message("upgradepackage 1.0.0").ShouldBeFalse(); } [Fact] public void should_not_contain_a_summary() { MockLogger.contains_message("packages installed").ShouldBeFalse(); } [Fact] public void should_not_contain_debugging_messages() { MockLogger.contains_message("Searching for package information", LogLevel.Debug).ShouldBeFalse(); MockLogger.contains_message("Running list with the following filter", LogLevel.Debug).ShouldBeFalse(); MockLogger.contains_message("Start of List", LogLevel.Debug).ShouldBeFalse(); MockLogger.contains_message("End of List", LogLevel.Debug).ShouldBeFalse(); } } [Concern(typeof(ChocolateyListCommand))] public class when_listing_packages_with_no_sources_enabled : ScenariosBase { public override void Context() { base.Context(); Configuration.Sources = null; } public override void Because() { MockLogger.reset(); Results = Service.list_run(Configuration).ToList(); } [Fact] public void should_have_no_sources_enabled_result() { MockLogger.contains_message("Unable to search for packages when there are no sources enabled for", LogLevel.Error).ShouldBeTrue(); } [Fact] public void should_not_list_any_packages() { Results.Count().ShouldEqual(0); } } [Concern(typeof(ChocolateyListCommand))] public class when_searching_for_an_exact_package : ScenariosBase { public override void Context() { Configuration = Scenario.list(); Scenario.reset(Configuration); Scenario.add_packages_to_source_location(Configuration, "exactpackage*" + Constants.PackageExtension); Service = NUnitSetup.Container.GetInstance<IChocolateyPackageService>(); Configuration.ListCommand.Exact = true; Configuration.Input = Configuration.PackageNames = "exactpackage"; } public override void Because() { MockLogger.reset(); Results = Service.list_run(Configuration).ToList(); } [Fact] public void should_contain_packages_and_versions_with_a_space_between_them() { MockLogger.contains_message("exactpackage 1.0.0").ShouldBeTrue(); } [Fact] public void should_not_contain_packages_that_do_not_match() { MockLogger.contains_message("exactpackage.dontfind").ShouldBeFalse(); } [Fact] public void should_contain_a_summary() { MockLogger.contains_message("packages found").ShouldBeTrue(); } [Fact] public void should_contain_debugging_messages() { MockLogger.contains_message("Searching for package information", LogLevel.Debug).ShouldBeTrue(); MockLogger.contains_message("Running list with the following filter", LogLevel.Debug).ShouldBeTrue(); MockLogger.contains_message("Start of List", LogLevel.Debug).ShouldBeTrue(); MockLogger.contains_message("End of List", LogLevel.Debug).ShouldBeTrue(); } } } }
Java
--- layout: post title: ">Solution Domain Architecture" date: 2007-05-19 21:10:00.000000000 +02:00 categories: - SDA SOA tags: [] status: publish type: post published: true meta: blogger_blog: andreasohlund.blogspot.com blogger_permalink: "/2007/05/solution-domain-architecture.html" author: login: andreas.ohlund email: andreasohlund2@gmail.com display_name: Andreas Öhlund first_name: Andreas last_name: "Öhlund" --- <p>><a href="http://blogs.msdn.com/nickmalik/default.aspx">Nick Malik</a> has a very interesting post about <a href="http://blogs.msdn.com/nickmalik/archive/2007/05/04/mining-for-services-with-solution-domain-architecture.aspx">Solution Domain Architecture </a>(SDA) which I believe is a great addition to the endless list of methods for <a href="http://www.squidoo.com/serviceengineering/">Service Engineering</a>. I especially like his teory that service reuse is most likely to happen with <em>" 'top down' services that we know, in advance, that we are going to need. " </em>and any reuse of bottom up services is <em>"is a happy accident". </em>This really highlights the need for SOA-governance in order to have a high degree of reuse of services in your service oriented architecture.</p>
Java
@font-face { font-family: 'Braille'; src: url(http://tjb0607.me/i3_tumblr_theme/font/Braille.woff); } html { background-color: #7C8491; background-image: url(http://static.tumblr.com/bwey4ra/Gzwno4oq5/sunset.jpg); background-position: bottom; background-attachment: fixed; height: 100%; margin: 0px; -webkit-background-size: cover; background-size: cover; font-family: Inconsolata, monospace; font-size: 11px; color: #fff; } #tumblr_controls { margin-top: 18px; } p, code { line-height: 11px; margin: 0px; } a, #sidebar .blogdescription a, .jslink { color: #5FD7FF; text-decoration: underline; cursor: pointer; } ul { padding-left: 11px; } #i3bar { overflow: hidden; color: #dedede; position: fixed; z-index: 1; top: 0px; left: 0px; right: 0px; height: 18px; background-color: #2d2d2d; } #i3bar p { margin: 3px 8px; } #sidebar { position: fixed; top: 47px; left: 35px; bottom: 35px; width: 450px; } .short-info .separator { color: #808080; } .window { overflow: auto; position: relative; margin: 10px; border: 2px solid #2d2d2d; box-shadow: 0px 0px 12px rgba(0, 0, 0, 0.75); } .window:hover, html:hover #active-window { border-color: #D64937; } .window:hover .cursor, html:hover #active-window .cursor { background-color: #fff; } .urxvt { background-color: rgba(28, 28, 28, 0.9); cursor: text; padding: 2px; max-width: 100%; min-height: 100%; } #i3-gaps-tumblr a .blog-title { cursor: pointer; } #i3-gaps-tumblr .blog-title p { text-align: center; } #i3-gaps-tumblr .blog-title p.small, #i3-gaps-tumblr .blog-title a { font-weight: 700; background-color: #107bcc; color: #fff; text-decoration: none; } #content { position: absolute; top: 47px; right: 35px; left: 475px; padding-bottom: 35px; } .post-header, .post-footer { overflow: hidden; position: relative; width: 100%; background-color: #303030; } .left { float: left; } .tags { padding-right: 60px; } .right { float: right; } .post-body { padding: 1em; max-width: 100%; } .post-body .title, .post-body .title a { text-decoration: none; color: #fff; font-size: 1.5em; } .post-body .link { font-size: 1.5em; } .post-body img { max-width: 100%; width: auto; height: auto; max-height: 95vh; } .post-body figure { margin: 0px; } .post-body p, .post-body blockquote { margin-top: 4px; margin-bottom: 4px; } .post-body blockquote { margin-left: 4px; border-left: 2px solid #5f5f5f; padding-left: 6px; margin-right: 0px; } .post-header, .post-header a, .post-footer, .post-footer a { color: #808080; } .footer-left { display: inline-block; } .post-footer { min-height: 22px; } .buttons { position: absolute; width: 50px; text-align: right; display: inline-block; right: 0px; padding: 2px 4px 2px 0px; } .buttons .reblogbutton { margin-bottom: -20px; } #i3bar .left .page-button { padding: 3px 5px 2px 5px; margin-bottom: 1px; color: #808080; float: left; } #i3bar .left .page-button-active { color: #dedede; background-color: #D64937; } #i3status { padding: 3px 5px 2px 5px; } #i3status > span a, #sidebar a { color: inherit; text-decoration: none; } #i3status span.i3status-separator { color: #808080; } #nav { text-align: center; overflow: hidden; width: 100%; margin-top: -10px; } #nav .prev-page-window { float: left; } #nav .next-page-window { float: right; } #nav .current-page-window { display: inline-block; margin-left: auto; margin-right: auto; } #nav .prev-page-window .urxvt, #nav .next-page-window .urxvt { cursor: pointer; } #nav a, #sidebar a, #sidebar .jslink { text-decoration: inherit; color: inherit; } #nav .prev-page-window .urxvt p, #nav .next-page-window .urxvt p { text-decoration: none; background-color: #107BCC; padding: 0px 5px; } .mobile-info { display: none; } #confirm { display: none; } #confirm-window { z-index: 2; position: fixed; left: 50%; top: 50%; width: 200px; margin-left: -100px; transform: translateY(-50%); border-color: #fff; text-align: center; } #confirm-bg { position: fixed; top: 0px; bottom: 0px; left: 0px; right: 0px; background-color: rgba(0, 0, 0, 0.5); z-index: 1; }
Java
# This code was automatically generated using xdrgen # DO NOT EDIT or your changes may be overwritten require 'xdr' # === xdr source ============================================================ # # enum PublicKeyType # { # PUBLIC_KEY_TYPE_ED25519 = KEY_TYPE_ED25519 # }; # # =========================================================================== module Stellar class PublicKeyType < XDR::Enum member :public_key_type_ed25519, 0 seal end end
Java
@CHARSET "UTF-8"; /*PRINCIPAL*/ body{ margin:0px; padding:0; font-family:verdana; font-size: 10px; height:100%; width: 100%; } img { border:0; } em { color: #b1b1b1; font-style: italic; } a { color:#333333; text-decoration: none; } a:hover { text-decoration: underline; } h1, h2, h3, h4, h5, h6 { font-family: Arial; color:#333; } h1 { font-size:2em; } h2 { clear:both; margin-top: 22px; } #principal { background-image:url(../imagens/bg-topo.png); background-repeat:repeat-x; background-position:top; } #topo{ height: 110px; /*Height of top section*/ background-image:url("../imagens/topo.png"); background-position:bottom left; background-repeat:no-repeat; } #logo { width:150px; height:70px; float:left; } #logon { width:254px; height:25px; float:right; padding-left:10px; margin: 10px 30px 0 30px; } #logon img{ margin-top:5px; } #logo-sistema { height: 30px; position: absolute; right: 82px; top: 43px; width: 127px; } #topo h1{ margin: 0; padding-top: 15px; } #barra-1 { width:100%; background-color: #cc0001; } #barra-2 { width:100%; background-color: #c8fc98; } #conteudo-col{ margin-left: 193px; /*Set left margin to LeftColumnWidth*/ } #cabecalho-div-1 { background-image:url(../imagens/bg-cabecalho-1.png); width:394px; width /*\**/: 393px; /* IE8 */ height:29px; float:left; background-repeat:repeat-x; background-position:left bottom; margin-bottom:5px; } :root #cabecalho-div-1 { width:375px\0/IE9; /* IE9 */ } #cabecalho-div-2 { background-image:url(../imagens/bg-cabecalho-2.png); width:165px; width /*\**/: 166px; /* IE8 */ height:29px; float:left; background-repeat:repeat-x; background-position:left bottom; margin-bottom:5px; } :root #cabecalho-div-2 { width:158px\0/IE9; /* IE9 */ } #miolo{ float: left; width: 100%; } .principal { background: none repeat scroll 0 0 #FFFFFF; border-bottom: 4px solid #B31419; clear: both; float: left; overflow: hidden; padding-bottom: 20px; width: 100%; } #col-esquerda{ float: left; width: 175px; /*Width of left column*/ height: 100%; margin-left: -100%; background: #efefef; margin-top:3px; } #titulo-pag{ margin-left:193px; width:57%; float:left; } #ico-internos{ float:right; text-align:right; margin:10px 20px 0 0; } #ico-internos img { } .alerta { margin-left:193px; width:100%; float:left; } #parametros { width:100%; margin-bottom:20px; } #menu { } #smoothmenu2 { height:400px; } #rodape{ clear: left; width: 100%; background: #d9d9d9; color: #333333; text-align: center; padding: 4px 0; text-align:center; } #rodape a{ color: #FFFF80; } /*FORMULARIO*/ .label-inter { /*Diminui o tamanho da label do formulário para estabelecer campos intermediários*/ position:absolute; top:0; left:5px; margin-right: 3px; text-align: right; width:80px; font-size:11px; z-index:1; } .obs { color: #b1b1b1; font-size: 11px; margin-left:5px; float:left; } div.form-divisoria { margin:-10px 0 5px 0px; width:100%; height:1px; background-color:#fff; clear:both; } div.field { } .field-busca { margin-bottom: 7px; margin-top: 7px; position: relative; text-align: right; } .buscar { height: 27px; width: 32px; float: left; } .buttonSubmit { clear:both; } #bt-submit { border: none; text-indent:-9999px; } .bt-salvar { background-image: url("../imagens/bt-salvar.png"); height: 30px; width: 63px; } .bt-cancelar { background-image:url(../imagens/bt-cancelar.png); width:30px; height:25px; } #bt-submit:hover{ border: none; } .botoes-internos { width:98.5%; text-align:right; margin-top:17px; } #voltar, #buscar-modal, #alteraplano-modal, #alteraextrato-modal, #desativaplano-modal, #novo-plano-modal, #pesquisar, #adiciona-linha-tabela-modal { display: inline; float: left; margin-left: 2px; } div.field input.error, div.field select.error, tr.errorRow div.field input, tr.errorRow div.field select { border: 1px solid #b31419; background-color: #FAFFD6; color: #b31419; } div.field div.formError { display: none; color: #FF0000; } div.field div.formError { font-weight: normal; } div.error { margin: 5px 0 23px 0; color: #b31419 !important; width:400px; padding:10px 0px 5px 3px; border:1px solid #b31419; } div.error a { color: #336699; font-size: 12px; text-decoration: underline; } label.error { color: #b31419; } .error span { margin-top:10px; } .botoes-externos { float:right; margin: -14px 30px 10px 0; } #caixa-pesquisa { /*Este não configura o MODAL */ background-color: #F5F5F5; background-image: url("../imagens/bg-pesquisa-lupa.gif"); background-position: right top; background-repeat: no-repeat; border: 1px solid #999999; display: block; min-width: 575px; padding: 0 15px 15px; position: relative; width: 65%; } /* INÍCIO - Teste Form Flexível */ .clear { clear:both; } .linha-form { line-height: 1.5em; } div.field-form-1 { width:48%; float:left; margin-right:2%; position:relative; } div.field-form-2 { float: left; margin-right: 2%; position: relative; width: 23%; } div.field-form-3 { width:14.65%; float:left; margin-right:2%; position:relative; } .textarea-form-1 { width:100%; } .textarea-form-2 { width:100%; } div.tabela-form-2 { height:91px; overflow:auto; background-color:#f5f5f5; border: 1px solid #999999; width:48%; float:left; } div.tabela-form-1 { height:99px; overflow:auto; background-color:#f5f5f5; border: 1px solid #999999; width:100%; float:left; min-width:200px; } div.tabela-form-1-menor { height:68px; overflow:auto; background-color:#f5f5f5; border: 1px solid #999999; width:100%; float:left; } div.ico-planos{ height:68px; width:100%; float:left; } div.ico-reneg{ height:49px; width:100%; float:left; } div.tabela-form-2 a{ font-weight:900; } div.add-contrato-tabela { float:left; color:#b31419; margin-left:7px; } div.field-com-busca { width:23%; float:left; margin-right:2%; position:relative; } div.ico-busca { position:absolute; z-index:500; right:0; } .textarea-form-input-1 textarea { width:98%; min-width:136px; border:1px solid #999999; height: 62px; } .textarea-form-input-2 textarea { width:100%; min-width:136px; border:1px solid #999999; } div.label-form { color:#666; margin-top:7px; } div.input-form { width:100%; } div.input-form input { width:100%; min-width:100px; border:1px solid #999999; } div.input-form select { width:100%; min-width:100px; border:1px solid #999999; } div.input-form-calendario input { width:100%; min-width:100px; border:1px solid #999999; background-image:url(../imagens/bt-calendar-18x17.png); background-repeat:no-repeat; background-position:center right; cursor:pointer; } div.input-form-busca input { width:87%; min-width:100px; border:1px solid #999999; position:relative; } div.input-form-menor input { width:100%; min-width:50px; border:1px solid #999999; } div.input-form-menor select { width:100%; min-width:50px; border:1px solid #999999; } /* FIM - Teste Form Flexível */ /* TABS */ ul.tabs { margin: 0; padding: 0; float: left; list-style: none; height: 32px; /*--Set height of tabs--*/ border-bottom: 1px solid #999; border-left: 1px solid #999; width: 98%; } ul.tabs li { float: left; margin: 0; padding: 0; height: 31px; /*--Subtract 1px from the height of the unordered list--*/ line-height: 31px; /*--Vertically aligns the text within the tab--*/ border: 1px solid #999; border-left: none; margin-bottom: -1px; /*--Pull the list item down 1px--*/ overflow: hidden; position: relative; background: #e0e0e0; } ul.tabs li a { text-decoration: none; color: #000; display: block; font-size: 1.2em; padding: 0 10px; border: 1px solid #fff; /*--Gives the bevel look with a 1px white border inside the list item--*/ outline: none; } ul.tabs li a:hover { background: #ccc; } html ul.tabs li.active, html ul.tabs li.active a:hover { /*--Makes sure that the active tab does not listen to the hover properties--*/ background: #fff; border-bottom: 1px solid #fff; /*--Makes the active tab look like it's connected with its content--*/ } ul.tabs li .reneg-tab { background-color:#b2b2b2; } ul.tabs li .reneg-tab:hover { background-color:#949494; } html ul.tabs li.active .reneg-tab, html ul.tabs li.active .reneg-tab:hover { /*--Makes sure that the active tab does not listen to the hover properties--*/ background: #fafce8; border-bottom: 1px solid #fafce8; /*--Makes the active tab look like it's connected with its content--*/ } .reneg-tb-bg { background-color:#fafce8; } /************************************/ .tab_container { border: 1px solid #999; border-top: none; border-bottom: 4px solid #ab1f23; overflow: hidden; clear: both; float: left; width: 98%; background: #fff; } .tab_content { padding: 10px; overflow:auto; } /* INÍCIO - TABELA*/ .grid td{ border-bottom:1px solid #e1e1e1; font-size:10px; line-height:2em; } table.nivel-1 { border-collapse:collapse; } table.nivel-1 tr { border-bottom:1px solid #E1E1E1; } .detalhes-contrato{ background-color:#efefef; width:100%; margin-top: -1px; padding-top: 11px; margin-bottom:20px; } .detalhes-contrato table { width:100%; background-color:#efefef; } /* FIM - TABELA*/ /************************************/ /* PÁGINAS INTERNAS */ .principal td { border-bottom:1px solid #e1e1e1; font-size:10px; } .principal td a { font-weight: bold; } /*SOLUÇÕES TEMPORÁRIAS*/ .link-pesquisa a{ border: 1px solid #999999; padding: 4px; background-color: #efefef; text-decoration:none; } .link-pesquisa-contrato a { background-color: #EFEFEF; border: 1px solid #999999; padding: 4px; position: absolute; right: 34px; text-decoration: none; top: 216px; } #nav-planos { height: 30px; margin: 20px 0; width: 100%; } #nav-icons-tabela { height: 30px; margin: 0; width: 100%; } #nav-planos h3{ float:left; margin-top: 4px; } #paginacao { float:left; } #paginacao ul{ padding:0px; margin-top: 5px; float: left; list-style:none; } #paginacao ul li { display: inline; } #paginacao ul li a{ background-image: url("../imagens/nav-bg.png"); background-repeat: no-repeat; height: 22px; padding: 5px 8px; margin-top:3px; } #paginacao ul li a:hover{ background-image: url("../imagens/nav-bg-hover.png"); text-decoration:none; } .seta-navega { float:left; } .ico-plano img{ margin-left:5px; } .ico-plano img{ margin-left:1px; }
Java
import { Component, OnInit } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; import { Location } from '@angular/common'; import { Merch } from '../data/merch'; import { MerchService } from '../data/merch.service'; @Component({ selector: 'app-merch-display', templateUrl: './merch-display.component.html', styleUrls: ['./merch-display.component.scss'], }) export class MerchDisplayComponent implements OnInit { merch: Merch[] = []; private _serviceWorker: ServiceWorker|null = null; constructor( private route: ActivatedRoute, private merchService: MerchService, private location: Location ) {} ngOnInit(): void { navigator.serviceWorker.ready.then( registration => { this._serviceWorker = registration.active; }); this.route.params.subscribe((routeParams) => { this.getMerch(routeParams.category); if (this._serviceWorker) { this._serviceWorker.postMessage({ page: routeParams.category }); } }); } getMerch(category: string): void { this.merchService .getMerchList(category) .then((merch) => (this.merch = merch)); } goBack(): void { this.location.back(); } }
Java
package com.github.sergejsamsonow.codegenerator.producer.pojo.renderer; import com.github.sergejsamsonow.codegenerator.api.producer.sc.SCMethodCodeConcatenator; import com.github.sergejsamsonow.codegenerator.api.producer.sc.SCNewLineAndIndentationFormat; import com.github.sergejsamsonow.codegenerator.producer.pojo.model.PojoProperty; import com.github.sergejsamsonow.codegenerator.producer.pojo.renderer.javalang.BeanModifier; public class JavaLangToString extends BeanModifier { public JavaLangToString(SCNewLineAndIndentationFormat format) { super(format); } @Override protected void writeBeforePropertiesIteration() { SCMethodCodeConcatenator writer = getMethodCodeWriter(); writer.annotation("@Override"); writer.start("public String toString() {"); writer.code("StringBuilder builder = new StringBuilder();"); writer.code("builder.append(\"%s (\");", getData().getClassName()); } @Override protected void writePropertyCode(PojoProperty property) { SCMethodCodeConcatenator writer = getMethodCodeWriter(); String end = isLast() ? ");" : " + \", \");"; writer.code("builder.append(\"%s: \" + Objects.toString(%s())%s", property.getFieldName(), property.getGetterName(), end); } @Override protected void writeAfterPropertiesIteration() { SCMethodCodeConcatenator writer = getMethodCodeWriter(); writer.code("builder.append(\")\");"); writer.code("return builder.toString();"); writer.end(); writer.emptyNewLine(); } }
Java
/* * Copyright 2010-2011 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.autoscaling.model; /** * <p> * The output for the TerminateInstanceInAutoScalingGroup action. * </p> */ public class TerminateInstanceInAutoScalingGroupResult { /** * A Scaling Activity. */ private Activity activity; /** * A Scaling Activity. * * @return A Scaling Activity. */ public Activity getActivity() { return activity; } /** * A Scaling Activity. * * @param activity A Scaling Activity. */ public void setActivity(Activity activity) { this.activity = activity; } /** * A Scaling Activity. * <p> * Returns a reference to this object so that method calls can be chained together. * * @param activity A Scaling Activity. * * @return A reference to this updated object so that method calls can be chained * together. */ public TerminateInstanceInAutoScalingGroupResult withActivity(Activity activity) { this.activity = activity; return this; } /** * Returns a string representation of this object; useful for testing and * debugging. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); sb.append("Activity: " + activity + ", "); sb.append("}"); return sb.toString(); } }
Java
/** * Copyright 2013-present NightWorld. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ var error = require('./error'), runner = require('./runner'), Client = require('./client'); module.exports = Authorise; /** * This is the function order used by the runner * * @type {Array} */ var fns = [ checkAuthoriseType, checkScope ]; /** * Authorise * * @param {Object} config Instance of OAuth object * @param {Object} req * @param {Object} res * @param {Object} options * @param {Function} next */ function Authorise (config, req, res, options, next) { options = options || {}; this.config = config; this.model = config.model; this.req = req; this.res = res; this.options = options; runner(fns, this, next); } function checkAuthoriseType(done) { var client = Client.credsFromBasic(this.req) || Client.credsFromBody(this.req); if (this.options.implicit) { if (this.req.body.response_type === 'token') { if (client.clientId) { this.redirectUri = this.req.body.redirect_uri || this.req.query.redirect_uri; this.clientId = client.clientId; this.req.auth_type = 'implicit'; return checkImplicitClient.call(this, done); } } } if (this.options.client_credentials) { if (client.clientId && client.clientSecret) { this.client = client; this.req.auth_type = 'client_credentials'; return getUserFromClient.call(this, done); } } getBearerToken.call(this, done); } function getUserFromClient(done) { var self = this; this.model.getClient(this.client.clientId, this.client.clientSecret, function (err, client) { if (err) return done(error('server_error', false, err)); if (!client) { return done(error('invalid_client', 'Client credentials are invalid')); } self.model.getUserFromClient(client, function (err, user) { if (err) return done(error('server_error', false, err)); if (!user) { return done(error('invalid_grant', 'Client credentials are invalid')); } self.req.oauth = { bearerToken: user }; self.req.user = { id: user.id }; done(); }); }); } function checkImplicitClient (done) { var self = this; this.model.getClient(this.clientId, null, function (err, client) { if (err) return done(error('server_error', false, err)); if (!client) { return done(error('invalid_client', 'Invalid client credentials')); } else if (self.redirectUri && Array.isArray(client.redirectUri)) { if (client.redirectUri.indexOf(self.redirectUri) === -1) { return done(error('invalid_request', 'redirect_uri does not match')); } client.redirectUri = self.redirectUri; } else if (self.redirectUri && client.redirectUri !== self.redirectUri) { return done(error('invalid_request', 'redirect_uri does not match')); } self.model.getUserFromClient(client, function (err, user) { if (err) return done(error('server_error', false, err)); if (!user) { return done(error('invalid_grant', 'Client credentials are invalid')); } // The request contains valid params so any errors after this point // are redirected to the redirect_uri self.res.redirectUri = client.redirectUri; self.res.oauthRedirect = true; self.req.oauth = { bearerToken: user }; self.req.user = { id: user.id }; done(); }); }); } /** * Get bearer token * * Extract token from request according to RFC6750 * * @param {Function} done * @this OAuth */ function getBearerToken (done) { var headerToken = this.req.get('Authorization'), getToken = this.req.query.access_token, postToken = this.req.body ? this.req.body.access_token : undefined; // Check exactly one method was used var methodsUsed = (headerToken !== undefined) + (getToken !== undefined) + (postToken !== undefined); if (methodsUsed > 1) { return done(error('invalid_request', 'Only one method may be used to authenticate at a time (Auth header, ' + 'GET or POST).')); } else if (methodsUsed === 0) { return done(error('invalid_request', 'The access token was not found')); } // Header: http://tools.ietf.org/html/rfc6750#section-2.1 if (headerToken) { var matches = headerToken.match(/Bearer\s(\S+)/); if (!matches) { return done(error('invalid_request', 'Malformed auth header')); } headerToken = matches[1]; } // POST: http://tools.ietf.org/html/rfc6750#section-2.2 if (postToken) { if (this.req.method === 'GET') { return done(error('invalid_request', 'Method cannot be GET When putting the token in the body.')); } if (!this.req.is('application/x-www-form-urlencoded')) { return done(error('invalid_request', 'When putting the token in the ' + 'body, content type must be application/x-www-form-urlencoded.')); } } this.bearerToken = headerToken || postToken || getToken; checkToken.call(this, done); } /** * Check token * * Check it against model, ensure it's not expired * @param {Function} done * @this OAuth */ function checkToken (done) { var self = this; this.model.getAccessToken(this.bearerToken, function (err, token) { if (err) return done(error('server_error', false, err)); if (!token) { return done(error('invalid_token', 'The access token provided is invalid.')); } if (token.expires !== null && (!token.expires || token.expires < new Date())) { return done(error('invalid_token', 'The access token provided has expired.')); } // Expose params self.req.oauth = { bearerToken: token }; self.req.user = token.user ? token.user : { id: token.userId }; done(); }); } /** * Check scope * * @param {Function} done * @this OAuth */ function checkScope (done) { if (!this.model.authoriseScope) return done(); this.model.authoriseScope(this.req.oauth.bearerToken, this.options.scope, function (err, invalid) { if (err) return done(error('server_error', false, err)); if (invalid) return done(error('invalid_scope', invalid)); done(); }); }
Java
from functools import wraps import json import os import traceback import validators from jinja2 import Environment, PackageLoader from notebook.utils import url_path_join from notebook.base.handlers import IPythonHandler import requests from requests.auth import HTTPBasicAuth env = Environment( loader=PackageLoader('saagie', 'jinja2'), ) SAAGIE_ROOT_URL = os.environ.get("SAAGIE_ROOT_URL", None) SAAGIE_USERNAME = None PLATFORMS_URL = None SAAGIE_BASIC_AUTH_TOKEN = None JOBS_URL_PATTERN = None JOB_URL_PATTERN = None JOB_UPGRADE_URL_PATTERN = None SCRIPT_UPLOAD_URL_PATTERN = None def get_absolute_saagie_url(saagie_url): if saagie_url.startswith('/'): return SAAGIE_ROOT_URL + saagie_url return saagie_url class ResponseError(Exception): def __init__(self, status_code): self.status_code = status_code super(ResponseError, self).__init__(status_code) class SaagieHandler(IPythonHandler): def handle_request(self, method): data = {k: v[0].decode() for k, v in self.request.arguments.items()} if 'view' not in data: self.send_error(404) return view_name = data.pop('view') notebook_path = data.pop('notebook_path', None) notebook_json = data.pop('notebook_json', None) notebook = Notebook(notebook_path, notebook_json) try: template_name, template_data = views.render( view_name, notebook=notebook, data=data, method=method) except ResponseError as e: self.send_error(e.status_code) return except: template_name = 'internal_error.html' template_data = {'error': traceback.format_exc()} self.set_status(500) template_data.update( notebook=notebook, ) template = env.get_template(template_name) self.finish(template.render(template_data)) def get(self): self.handle_request('GET') def post(self): self.handle_request('POST') def check_xsrf_cookie(self): return class SaagieCheckHandler(IPythonHandler): def get(self): self.finish() class SaagieJobRun: def __init__(self, job, run_data): self.job = job self.id = run_data['id'] self.status = run_data['status'] self.stderr = run_data.get('logs_err', '') self.stdout = run_data.get('logs_out', '') class SaagieJob: @classmethod def from_id(cls, notebook, platform_id, job_id): return SaagieJob( notebook, requests.get(JOB_URL_PATTERN % (platform_id, job_id), auth=SAAGIE_BASIC_AUTH_TOKEN).json()) def __init__(self, notebook, job_data): self.notebook = notebook self.data = job_data self.platform_id = job_data['platform_id'] self.capsule_type = job_data['capsule_code'] self.id = job_data['id'] self.name = job_data['name'] self.last_run = None def set_as_current(self): self.notebook.current_job = self @property def url(self): return (JOBS_URL_PATTERN + '/%s') % (self.platform_id, self.id) @property def admin_url(self): return get_absolute_saagie_url('/#/manager/%s/job/%s' % (self.platform_id, self.id)) @property def logs_url(self): return self.admin_url + '/logs' @property def is_started(self): return self.last_run is not None def fetch_logs(self): job_data = requests.get(self.url, auth=SAAGIE_BASIC_AUTH_TOKEN).json() run_data = job_data.get('last_instance') if run_data is None or run_data['status'] not in ('SUCCESS', 'FAILED'): return run_data = requests.get( get_absolute_saagie_url('/api/v1/jobtask/%s' % run_data['id']), auth=SAAGIE_BASIC_AUTH_TOKEN).json() self.last_run = SaagieJobRun(self, run_data) @property def details_template_name(self): return 'include/python_job_details.html' def __str__(self): return self.name def __eq__(self, other): if other is None: return False return self.platform_id == other.platform_id and self.id == other.id def __lt__(self, other): if other is None: return False return self.id < other.id class SaagiePlatform: SUPPORTED_CAPSULE_TYPES = {'python'} def __init__(self, notebook, platform_data): self.notebook = notebook self.id = platform_data['id'] self.name = platform_data['name'] self.capsule_types = {c['code'] for c in platform_data['capsules']} @property def is_supported(self): return not self.capsule_types.isdisjoint(self.SUPPORTED_CAPSULE_TYPES) def get_jobs(self): if not self.is_supported: return [] jobs_data = requests.get(JOBS_URL_PATTERN % self.id, auth=SAAGIE_BASIC_AUTH_TOKEN).json() return [SaagieJob(self.notebook, job_data) for job_data in jobs_data if job_data['category'] == 'processing' and job_data['capsule_code'] in self.SUPPORTED_CAPSULE_TYPES] def __eq__(self, other): return self.id == other.id class Notebook: CACHE = {} def __new__(cls, path, json): if path in cls.CACHE: return cls.CACHE[path] cls.CACHE[path] = new = super(Notebook, cls).__new__(cls) return new def __init__(self, path, json_data): if path is None: path = 'Untitled.ipynb' if json_data is None: json_data = json.dumps({ 'cells': [], 'metadata': {'kernelspec': {'name': 'python3'}}}) self.path = path self.json = json.loads(json_data) # In cached instances, current_job is already defined. if not hasattr(self, 'current_job'): self.current_job = None @property def name(self): return os.path.splitext(os.path.basename(self.path))[0] @property def kernel_name(self): return self.json['metadata']['kernelspec']['name'] @property def kernel_display_name(self): return self.json['metadata']['kernelspec']['display_name'] def get_code_cells(self): return [cell['source'] for cell in self.json['cells'] if cell['cell_type'] == 'code'] def get_code(self, indices=None): cells = self.get_code_cells() if indices is None: indices = list(range(len(cells))) return '\n\n\n'.join([cells[i] for i in indices]) def get_platforms(self): return [SaagiePlatform(self, platform_data) for platform_data in requests.get(PLATFORMS_URL, auth=SAAGIE_BASIC_AUTH_TOKEN).json()] class ViewsCollection(dict): def add(self, func): self[func.__name__] = func return func def render(self, view_name, notebook, data=None, method='GET', **kwargs): if data is None: data = {} try: view = views[view_name] except KeyError: raise ResponseError(404) template_data = view(method, notebook, data, **kwargs) if isinstance(template_data, tuple): template_name, template_data = template_data else: template_name = view.__name__ + '.html' return template_name, template_data views = ViewsCollection() @views.add def modal(method, notebook, data): return {} def clear_basic_auth_token(): global SAAGIE_BASIC_AUTH_TOKEN SAAGIE_BASIC_AUTH_TOKEN = None # Init an empty Basic Auth token on first launch clear_basic_auth_token() def is_logged(): if SAAGIE_ROOT_URL is None or SAAGIE_BASIC_AUTH_TOKEN is None: return False else: # Check if Basic token is still valid is_logged_in = False try: response = requests.get(SAAGIE_ROOT_URL + '/api/v1/user-current', auth=SAAGIE_BASIC_AUTH_TOKEN, allow_redirects=False) is_logged_in = response.ok except (requests.ConnectionError, requests.RequestException, requests.HTTPError, requests.Timeout) as err: print ('Error while trying to connect to Saagie: ', err) if is_logged_in is not True: # Remove Basic Auth token from globals. It will force a new login phase. clear_basic_auth_token() return is_logged_in def define_globals(saagie_root_url, saagie_username): if saagie_root_url is not None: global SAAGIE_ROOT_URL global SAAGIE_USERNAME global PLATFORMS_URL global JOBS_URL_PATTERN global JOB_URL_PATTERN global JOB_UPGRADE_URL_PATTERN global SCRIPT_UPLOAD_URL_PATTERN SAAGIE_USERNAME = saagie_username SAAGIE_ROOT_URL = saagie_root_url.strip("/") PLATFORMS_URL = SAAGIE_ROOT_URL + '/api/v1/platform' JOBS_URL_PATTERN = PLATFORMS_URL + '/%s/job' JOB_URL_PATTERN = JOBS_URL_PATTERN + '/%s' JOB_UPGRADE_URL_PATTERN = JOBS_URL_PATTERN + '/%s/version' SCRIPT_UPLOAD_URL_PATTERN = JOBS_URL_PATTERN + '/upload' @views.add def login_form(method, notebook, data): if method == 'POST': # check if the given Saagie URL is well formed if not validators.url(data['saagie_root_url']): return {'error': 'Invalid URL', 'saagie_root_url': data['saagie_root_url'] or '', 'username': data['username'] or ''} define_globals(data['saagie_root_url'], data['username']) try: basic_token = HTTPBasicAuth(data['username'], data['password']) current_user_response = requests.get(SAAGIE_ROOT_URL + '/api/v1/user-current', auth=basic_token, allow_redirects=False) if current_user_response.ok: # Login succeeded, keep the basic token for future API calls global SAAGIE_BASIC_AUTH_TOKEN SAAGIE_BASIC_AUTH_TOKEN = basic_token except (requests.ConnectionError, requests.RequestException, requests.HTTPError, requests.Timeout) as err: print ('Error while trying to connect to Saagie: ', err) return {'error': 'Connection error', 'saagie_root_url': SAAGIE_ROOT_URL, 'username': SAAGIE_USERNAME or ''} if SAAGIE_BASIC_AUTH_TOKEN is not None: return views.render('capsule_type_chooser', notebook) return {'error': 'Invalid URL, username or password.', 'saagie_root_url': SAAGIE_ROOT_URL, 'username': SAAGIE_USERNAME or ''} if is_logged(): return views.render('capsule_type_chooser', notebook) return {'error': None, 'saagie_root_url': SAAGIE_ROOT_URL or '', 'username': SAAGIE_USERNAME or ''} def login_required(view): @wraps(view) def inner(method, notebook, data, *args, **kwargs): if not is_logged(): return views.render('login_form', notebook) return view(method, notebook, data, *args, **kwargs) return inner @views.add @login_required def capsule_type_chooser(method, notebook, data): return {'username': SAAGIE_USERNAME} def get_job_form(method, notebook, data): context = {'platforms': notebook.get_platforms()} context['values'] = ({'current': {'options': {}}} if notebook.current_job is None else notebook.current_job.data) return context def create_job_base_data(data): return { 'platform_id': data['saagie-platform'], 'category': 'processing', 'name': data['job-name'], 'description': data['description'], 'current': { 'cpu': data['cpu'], 'disk': data['disk'], 'memory': data['ram'], 'isInternalSubDomain': False, 'isInternalPort': False, 'options': {} } } def upload_python_script(notebook, data): code = notebook.get_code(map(int, data.get('code-lines', '').split('|'))) files = {'file': (data['job-name'] + '.py', code)} return requests.post( SCRIPT_UPLOAD_URL_PATTERN % data['saagie-platform'], files=files, auth=SAAGIE_BASIC_AUTH_TOKEN).json()['fileName'] @views.add @login_required def python_job_form(method, notebook, data): if method == 'POST': platform_id = data['saagie-platform'] job_data = create_job_base_data(data) job_data['capsule_code'] = 'python' job_data['always_email'] = False job_data['manual'] = True job_data['retry'] = '' current = job_data['current'] current['options']['language_version'] = data['language-version'] current['releaseNote'] = data['release-note'] current['template'] = data['shell-command'] current['file'] = upload_python_script(notebook, data) new_job_data = requests.post(JOBS_URL_PATTERN % platform_id, json=job_data, auth=SAAGIE_BASIC_AUTH_TOKEN).json() job = SaagieJob(notebook, new_job_data) job.set_as_current() return views.render('starting_job', notebook, {'job': job}) context = get_job_form(method, notebook, data) context['action'] = '/saagie?view=python_job_form' context['username'] = SAAGIE_USERNAME return context @views.add @login_required def update_python_job(method, notebook, data): if method == 'POST': job = notebook.current_job platform_id = job.platform_id data['saagie-platform'] = platform_id data['job-name'] = job.name data['description'] = '' current = create_job_base_data(data)['current'] current['options']['language_version'] = data['language-version'] current['releaseNote'] = data['release-note'] current['template'] = data['shell-command'] current['file'] = upload_python_script(notebook, data) requests.post(JOB_UPGRADE_URL_PATTERN % (platform_id, job.id), json={'current': current}, auth=SAAGIE_BASIC_AUTH_TOKEN) job.last_run = None return views.render('starting_job', notebook, {'job': job}) context = get_job_form(method, notebook, data) context['action'] = '/saagie?view=update_python_job' context['username'] = SAAGIE_USERNAME return context @views.add @login_required def select_python_job(method, notebook, data): if method == 'POST': platform_id, job_id = data['job'].split('-') notebook.current_job = SaagieJob.from_id(notebook, platform_id, job_id) return views.render('update_python_job', notebook, data) jobs_by_platform = [] for platform in notebook.get_platforms(): jobs = platform.get_jobs() if jobs: jobs_by_platform.append((platform, list(sorted(jobs, reverse=True)))) return {'jobs_by_platform': jobs_by_platform, 'action': '/saagie?view=select_python_job', 'username': SAAGIE_USERNAME} @views.add @login_required def unsupported_kernel(method, notebook, data): return {'username': SAAGIE_USERNAME} @views.add @login_required def starting_job(method, notebook, data): job = notebook.current_job job.fetch_logs() if job.is_started: return views.render('started_job', notebook, {'job': job}) return {'job': job, 'username': SAAGIE_USERNAME} @views.add @login_required def started_job(method, notebook, data): return {'job': notebook.current_job, 'username': SAAGIE_USERNAME} @views.add def logout(method, notebook, data): global SAAGIE_BASIC_AUTH_TOKEN global SAAGIE_ROOT_URL global SAAGIE_USERNAME SAAGIE_BASIC_AUTH_TOKEN = None SAAGIE_ROOT_URL = None SAAGIE_USERNAME = None return {} def load_jupyter_server_extension(nb_app): web_app = nb_app.web_app base_url = web_app.settings['base_url'] route_pattern = url_path_join(base_url, '/saagie') web_app.add_handlers('.*$', [(route_pattern, SaagieHandler)]) route_pattern = url_path_join(base_url, '/saagie/check') web_app.add_handlers('.*$', [(route_pattern, SaagieCheckHandler)])
Java
//// [contextualTypeWithUnionTypeMembers.ts] //When used as a contextual type, a union type U has those members that are present in any of // its constituent types, with types that are unions of the respective members in the constituent types. interface I1<T> { commonMethodType(a: string): string; commonPropertyType: string; commonMethodWithTypeParameter(a: T): T; methodOnlyInI1(a: string): string; propertyOnlyInI1: string; } interface I2<T> { commonMethodType(a: string): string; commonPropertyType: string; commonMethodWithTypeParameter(a: T): T; methodOnlyInI2(a: string): string; propertyOnlyInI2: string; } // Let S be the set of types in U that has a property P. // If S is not empty, U has a property P of a union type of the types of P from each type in S. var i1: I1<number>; var i2: I2<number>; var i1Ori2: I1<number> | I2<number> = i1; var i1Ori2: I1<number> | I2<number> = i2; var i1Ori2: I1<number> | I2<number> = { // Like i1 commonPropertyType: "hello", commonMethodType: a=> a, commonMethodWithTypeParameter: a => a, methodOnlyInI1: a => a, propertyOnlyInI1: "Hello", }; var i1Ori2: I1<number> | I2<number> = { // Like i2 commonPropertyType: "hello", commonMethodType: a=> a, commonMethodWithTypeParameter: a => a, methodOnlyInI2: a => a, propertyOnlyInI2: "Hello", }; var i1Ori2: I1<number> | I2<number> = { // Like i1 and i2 both commonPropertyType: "hello", commonMethodType: a=> a, commonMethodWithTypeParameter: a => a, methodOnlyInI1: a => a, propertyOnlyInI1: "Hello", methodOnlyInI2: a => a, propertyOnlyInI2: "Hello", }; var arrayI1OrI2: Array<I1<number> | I2<number>> = [i1, i2, { // Like i1 commonPropertyType: "hello", commonMethodType: a=> a, commonMethodWithTypeParameter: a => a, methodOnlyInI1: a => a, propertyOnlyInI1: "Hello", }, { // Like i2 commonPropertyType: "hello", commonMethodType: a=> a, commonMethodWithTypeParameter: a => a, methodOnlyInI2: a => a, propertyOnlyInI2: "Hello", }, { // Like i1 and i2 both commonPropertyType: "hello", commonMethodType: a=> a, commonMethodWithTypeParameter: a => a, methodOnlyInI1: a => a, propertyOnlyInI1: "Hello", methodOnlyInI2: a => a, propertyOnlyInI2: "Hello", }]; interface I11 { commonMethodDifferentReturnType(a: string, b: number): string; commonPropertyDifferentType: string; } interface I21 { commonMethodDifferentReturnType(a: string, b: number): number; commonPropertyDifferentType: number; } var i11: I11; var i21: I21; var i11Ori21: I11 | I21 = i11; var i11Ori21: I11 | I21 = i21; var i11Ori21: I11 | I21 = { // Like i1 commonMethodDifferentReturnType: (a, b) => { var z = a.charAt(b); return z; }, commonPropertyDifferentType: "hello", }; var i11Ori21: I11 | I21 = { // Like i2 commonMethodDifferentReturnType: (a, b) => { var z = a.charCodeAt(b); return z; }, commonPropertyDifferentType: 10, }; var arrayOrI11OrI21: Array<I11 | I21> = [i11, i21, i11 || i21, { // Like i1 commonMethodDifferentReturnType: (a, b) => { var z = a.charAt(b); return z; }, commonPropertyDifferentType: "hello", }, { // Like i2 commonMethodDifferentReturnType: (a, b) => { var z = a.charCodeAt(b); return z; }, commonPropertyDifferentType: 10, }]; //// [contextualTypeWithUnionTypeMembers.js] // Let S be the set of types in U that has a property P. // If S is not empty, U has a property P of a union type of the types of P from each type in S. var i1; var i2; var i1Ori2 = i1; var i1Ori2 = i2; var i1Ori2 = { commonPropertyType: "hello", commonMethodType: function (a) { return a; }, commonMethodWithTypeParameter: function (a) { return a; }, methodOnlyInI1: function (a) { return a; }, propertyOnlyInI1: "Hello" }; var i1Ori2 = { commonPropertyType: "hello", commonMethodType: function (a) { return a; }, commonMethodWithTypeParameter: function (a) { return a; }, methodOnlyInI2: function (a) { return a; }, propertyOnlyInI2: "Hello" }; var i1Ori2 = { commonPropertyType: "hello", commonMethodType: function (a) { return a; }, commonMethodWithTypeParameter: function (a) { return a; }, methodOnlyInI1: function (a) { return a; }, propertyOnlyInI1: "Hello", methodOnlyInI2: function (a) { return a; }, propertyOnlyInI2: "Hello" }; var arrayI1OrI2 = [i1, i2, { commonPropertyType: "hello", commonMethodType: function (a) { return a; }, commonMethodWithTypeParameter: function (a) { return a; }, methodOnlyInI1: function (a) { return a; }, propertyOnlyInI1: "Hello" }, { commonPropertyType: "hello", commonMethodType: function (a) { return a; }, commonMethodWithTypeParameter: function (a) { return a; }, methodOnlyInI2: function (a) { return a; }, propertyOnlyInI2: "Hello" }, { commonPropertyType: "hello", commonMethodType: function (a) { return a; }, commonMethodWithTypeParameter: function (a) { return a; }, methodOnlyInI1: function (a) { return a; }, propertyOnlyInI1: "Hello", methodOnlyInI2: function (a) { return a; }, propertyOnlyInI2: "Hello" }]; var i11; var i21; var i11Ori21 = i11; var i11Ori21 = i21; var i11Ori21 = { // Like i1 commonMethodDifferentReturnType: function (a, b) { var z = a.charAt(b); return z; }, commonPropertyDifferentType: "hello" }; var i11Ori21 = { // Like i2 commonMethodDifferentReturnType: function (a, b) { var z = a.charCodeAt(b); return z; }, commonPropertyDifferentType: 10 }; var arrayOrI11OrI21 = [i11, i21, i11 || i21, { // Like i1 commonMethodDifferentReturnType: function (a, b) { var z = a.charAt(b); return z; }, commonPropertyDifferentType: "hello" }, { // Like i2 commonMethodDifferentReturnType: function (a, b) { var z = a.charCodeAt(b); return z; }, commonPropertyDifferentType: 10 }];
Java
using System; using System.Collections.Generic; using System.Linq; using System.Text; using SuperMap.WinRT.Core; using SuperMap.WinRT.Utilities; using Windows.Data.Json; using Windows.UI; namespace SuperMap.WinRT.REST { /// <summary> /// <para>${REST_ServerLayer_Title}</para> /// <para>${REST_ServerLayer_Description}</para> /// </summary> public class ServerLayer { /// <summary>${REST_ServerLayer_constructor_D}</summary> public ServerLayer() { } //Property /// <summary>${REST_ServerLayer_attribute_Bounds_D}</summary> public Rectangle2D Bounds { get; internal set; } //对应服务端的Layer属性 /// <summary>${REST_ServerLayer_attribute_caption_D}</summary> public string Caption { get; internal set; } /// <summary>${REST_ServerLayer_attribute_Description_D}</summary> public string Description { get; internal set; } /// <summary>${REST_ServerLayer_attribute_Name_D}</summary> public string Name { get; internal set; } /// <summary>${REST_ServerLayer_attribute_IsQueryable_D}</summary> public bool IsQueryable { get; internal set; } //图层的子图层先不控制 //public System.Collections.Generic.List<LayerInfo> SubLayers { get; internal set; } //这里默认是UGC了,不开放给用户啦 //private string LayerType = "UGC"; /// <summary>${REST_ServerLayer_attribute_IsVisible_D}</summary> public bool IsVisible { get; internal set; } //对应服务端UGCMapLayer属性 /// <summary>${REST_ServerLayer_attribute_IsCompleteLineSymbolDisplayed_D}</summary> public bool IsCompleteLineSymbolDisplayed { get; internal set; } /// <summary>${REST_ServerLayer_attribute_MaxScale_D}</summary> public double MaxScale { get; internal set; } /// <summary>${REST_ServerLayer_attribute_minScale_D}</summary> public double MinScale { get; internal set; } /// <summary>${REST_ServerLayer_attribute_MinVisibleGeometrySize_D}</summary> public double MinVisibleGeometrySize { get; internal set; } /// <summary>${REST_ServerLayer_attribute_OpaqueRate_D}</summary> public int OpaqueRate { get; internal set; } /// <summary>${REST_ServerLayer_attribute_IsSymbolScalable_D}</summary> public bool IsSymbolScalable { get; internal set; } /// <summary>${REST_ServerLayer_attribute_SymbolScale_D}</summary> public double SymbolScale { get; internal set; } //对应服务端UGCLayer /// <summary>${REST_ServerLayer_attribute_DatasetInfo_D}</summary> public DatasetInfo DatasetInfo { get; internal set; } /// <summary>${REST_ServerLayer_attribute_DisplayFilter_D}</summary> public string DisplayFilter { get; internal set; } /// <summary>${REST_ServerLayer_attribute_JoinItems_D}</summary> public System.Collections.Generic.List<JoinItem> JoinItems { get; internal set; } /// <summary>${REST_ServerLayer_attribute_RepresentationField_D}</summary> public string RepresentationField { get; internal set; } /// <summary>${REST_ServerLayer_attribute_UGCLayerType_D}</summary> public SuperMapLayerType UGCLayerType { get; internal set; } /// <summary>${REST_ServerLayer_attribute_UGCLayer_D}</summary> public UGCLayer UGCLayer { get; internal set; } /// <summary>${REST_ServerLayer_method_FromJson_D}</summary> /// <returns>${REST_ServerLayer_method_FromJson_return}</returns> /// <param name="json">${REST_ServerLayer_method_FromJson_param_jsonObject}</param> internal static ServerLayer FromJson(JsonObject json) { var serverLayer = new ServerLayer(); if (json["bounds"].ValueType != JsonValueType.Null) { serverLayer.Bounds = JsonHelper.ToRectangle2D(json["bounds"].GetObjectEx()); } else { //null } serverLayer.Caption = json["caption"].GetStringEx(); serverLayer.Description = json["description"].GetStringEx(); serverLayer.Name = json["name"].GetStringEx(); serverLayer.IsQueryable = json["queryable"].GetBooleanEx(); serverLayer.IsVisible = json["visible"].GetBooleanEx(); serverLayer.IsCompleteLineSymbolDisplayed = json["completeLineSymbolDisplayed"].GetBooleanEx(); serverLayer.MaxScale = json["maxScale"].GetNumberEx(); serverLayer.MinScale = json["minScale"].GetNumberEx(); serverLayer.MinVisibleGeometrySize = json["minVisibleGeometrySize"].GetNumberEx(); serverLayer.OpaqueRate = (int)json["opaqueRate"].GetNumberEx(); serverLayer.IsSymbolScalable = json["symbolScalable"].GetBooleanEx(); serverLayer.SymbolScale = json["symbolScale"].GetNumberEx(); serverLayer.DatasetInfo = DatasetInfo.FromJson(json["datasetInfo"].GetObjectEx()); serverLayer.DisplayFilter = json["displayFilter"].GetStringEx(); if (json["joinItems"].ValueType != JsonValueType.Null) { List<JoinItem> joinItems = new List<JoinItem>(); foreach (JsonValue item in json["joinItems"].GetArray()) { joinItems.Add(JoinItem.FromJson(item.GetObjectEx())); } serverLayer.JoinItems = joinItems; } serverLayer.RepresentationField = json["representationField"].GetStringEx(); if (json["ugcLayerType"].GetStringEx() == SuperMapLayerType.GRID.ToString()) { UGCGridLayer ugcGridLayer = new UGCGridLayer(); List<Color> colors = new List<Color>(); foreach (JsonValue colorItem in json["colors"].GetArray()) { colors.Add(ServerColor.FromJson(colorItem.GetObjectEx()).ToColor()); } ugcGridLayer.Colors = colors; if (json["dashStyle"].ValueType != JsonValueType.Null) { ugcGridLayer.DashStyle = ServerStyle.FromJson(json["dashStyle"].GetObjectEx()); } if (json["gridType"].ValueType != JsonValueType.Null) { ugcGridLayer.GridType = (GridType)Enum.Parse(typeof(GridType), json["gridType"].GetStringEx(), true); } else { } ugcGridLayer.HorizontalSpacing = json["horizontalSpacing"].GetNumberEx(); ugcGridLayer.SizeFixed = json["sizeFixed"].GetBooleanEx(); if (json["solidStyle"].ValueType != JsonValueType.Null) { ugcGridLayer.SolidStyle = ServerStyle.FromJson(json["solidStyle"].GetObjectEx()); } if (json["specialColor"].ValueType != JsonValueType.Null) { ugcGridLayer.SpecialColor = ServerColor.FromJson(json["specialColor"].GetObjectEx()).ToColor(); } ugcGridLayer.SpecialValue = json["specialValue"].GetNumberEx(); ugcGridLayer.VerticalSpacing = json["verticalSpacing"].GetNumberEx(); serverLayer.UGCLayer = ugcGridLayer; } else if (json["ugcLayerType"].GetStringEx() == SuperMapLayerType.IMAGE.ToString()) { UGCImageLayer ugcImageLayer = new UGCImageLayer(); ugcImageLayer.Brightness = (int)json["brightness"].GetNumberEx(); if (json["colorSpaceType"].ValueType != JsonValueType.Null) { ugcImageLayer.ColorSpaceType = (ColorSpaceType)Enum.Parse(typeof(ColorSpaceType), json["colorSpaceType"].GetStringEx(), true); } else { } ugcImageLayer.Contrast = (int)json["contrast"].GetNumberEx(); List<int> bandIndexes = new List<int>(); if (json["displayBandIndexes"].ValueType != JsonValueType.Null && (json["displayBandIndexes"].GetArray()).Count > 0) { foreach (JsonObject item in json["displayBandIndexes"].GetArray()) { bandIndexes.Add((int)item.GetNumber()); } ugcImageLayer.DisplayBandIndexes = bandIndexes; } ugcImageLayer.Transparent = json["transparent"].GetBooleanEx(); ugcImageLayer.TransparentColor = ServerColor.FromJson(json["transparentColor"].GetObjectEx()).ToColor(); serverLayer.UGCLayer = ugcImageLayer; } else if (json["ugcLayerType"].GetStringEx() == SuperMapLayerType.THEME.ToString()) { UGCThemeLayer ugcThemeLayer = new UGCThemeLayer(); if (json["theme"].ValueType != JsonValueType.Null) { if (json["theme"].GetObjectEx()["type"].GetStringEx() == "UNIQUE") { ugcThemeLayer.Theme = ThemeUnique.FromJson(json["theme"].GetObjectEx()); } else if (json["theme"].GetObjectEx()["type"].GetStringEx() == "RANGE") { ugcThemeLayer.Theme = ThemeRange.FromJson(json["theme"].GetObjectEx()); } else if (json["theme"].GetObjectEx()["type"].GetStringEx() == "LABEL") { ugcThemeLayer.Theme = ThemeLabel.FromJson(json["theme"].GetObjectEx()); } else if (json["theme"].GetObjectEx()["type"].GetStringEx() == "GRAPH") { ugcThemeLayer.Theme = ThemeGraph.FromJson(json["theme"].GetObjectEx()); } else if (json["theme"].GetObjectEx()["type"].GetStringEx() == "DOTDENSITY") { ugcThemeLayer.Theme = ThemeDotDensity.FromJson(json["theme"].GetObjectEx()); } else if (json["theme"].GetObjectEx()["type"].GetStringEx() == "GRADUATEDSYMBOL") { ugcThemeLayer.Theme = ThemeGraduatedSymbol.FromJson(json["theme"].GetObjectEx()); } else { //以后有需求再添加,现在就写到这里,共六个专题图。 } } if (json["theme"].GetObjectEx()["type"].ValueType != JsonValueType.Null) { ugcThemeLayer.ThemeType = (ThemeType)Enum.Parse(typeof(ThemeType), json["theme"].GetObjectEx()["type"].GetStringEx(), true); } serverLayer.UGCLayer = ugcThemeLayer; //ugcThemeLayer.Theme } else if (json["ugcLayerType"].GetStringEx() == SuperMapLayerType.VECTOR.ToString() && json.ContainsKey("style")) { serverLayer.UGCLayer = UGCVectorLayer.FromJson(json["style"].GetObjectEx()); } else { serverLayer.UGCLayer = new UGCLayer(); } if (json["ugcLayerType"].ValueType != JsonValueType.Null) { serverLayer.UGCLayerType = (SuperMapLayerType)Enum.Parse(typeof(SuperMapLayerType), json["ugcLayerType"].GetStringEx(), true); } else { //不做处理 } //这里不判断WMS和WFS图层。 //else if (json["ugcLayerType"] == SuperMapLayerType.WMS.ToString()) //{ //} //根据图层类型增加相应属性。 return serverLayer; } } }
Java
// /* // Copyright 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. // */ // // Code generated by MockGen. DO NOT EDIT. // Source: /go/src/sigs.k8s.io/cloud-provider-azure/pkg/azureclients/diskclient/interface.go // Package mockdiskclient is a generated GoMock package. package mockdiskclient import ( context "context" reflect "reflect" compute "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2020-12-01/compute" gomock "github.com/golang/mock/gomock" retry "sigs.k8s.io/cloud-provider-azure/pkg/retry" ) // MockInterface is a mock of Interface interface. type MockInterface struct { ctrl *gomock.Controller recorder *MockInterfaceMockRecorder } // MockInterfaceMockRecorder is the mock recorder for MockInterface. type MockInterfaceMockRecorder struct { mock *MockInterface } // NewMockInterface creates a new mock instance. func NewMockInterface(ctrl *gomock.Controller) *MockInterface { mock := &MockInterface{ctrl: ctrl} mock.recorder = &MockInterfaceMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. func (m *MockInterface) EXPECT() *MockInterfaceMockRecorder { return m.recorder } // Get mocks base method. func (m *MockInterface) Get(ctx context.Context, resourceGroupName, diskName string) (compute.Disk, *retry.Error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Get", ctx, resourceGroupName, diskName) ret0, _ := ret[0].(compute.Disk) ret1, _ := ret[1].(*retry.Error) return ret0, ret1 } // Get indicates an expected call of Get. func (mr *MockInterfaceMockRecorder) Get(ctx, resourceGroupName, diskName interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Get", reflect.TypeOf((*MockInterface)(nil).Get), ctx, resourceGroupName, diskName) } // CreateOrUpdate mocks base method. func (m *MockInterface) CreateOrUpdate(ctx context.Context, resourceGroupName, diskName string, diskParameter compute.Disk) *retry.Error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "CreateOrUpdate", ctx, resourceGroupName, diskName, diskParameter) ret0, _ := ret[0].(*retry.Error) return ret0 } // CreateOrUpdate indicates an expected call of CreateOrUpdate. func (mr *MockInterfaceMockRecorder) CreateOrUpdate(ctx, resourceGroupName, diskName, diskParameter interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateOrUpdate", reflect.TypeOf((*MockInterface)(nil).CreateOrUpdate), ctx, resourceGroupName, diskName, diskParameter) } // Update mocks base method. func (m *MockInterface) Update(ctx context.Context, resourceGroupName, diskName string, diskParameter compute.DiskUpdate) *retry.Error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Update", ctx, resourceGroupName, diskName, diskParameter) ret0, _ := ret[0].(*retry.Error) return ret0 } // Update indicates an expected call of Update. func (mr *MockInterfaceMockRecorder) Update(ctx, resourceGroupName, diskName, diskParameter interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Update", reflect.TypeOf((*MockInterface)(nil).Update), ctx, resourceGroupName, diskName, diskParameter) } // Delete mocks base method. func (m *MockInterface) Delete(ctx context.Context, resourceGroupName, diskName string) *retry.Error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Delete", ctx, resourceGroupName, diskName) ret0, _ := ret[0].(*retry.Error) return ret0 } // Delete indicates an expected call of Delete. func (mr *MockInterfaceMockRecorder) Delete(ctx, resourceGroupName, diskName interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Delete", reflect.TypeOf((*MockInterface)(nil).Delete), ctx, resourceGroupName, diskName) } // ListByResourceGroup mocks base method. func (m *MockInterface) ListByResourceGroup(ctx context.Context, resourceGroupName string) ([]compute.Disk, *retry.Error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "ListByResourceGroup", ctx, resourceGroupName) ret0, _ := ret[0].([]compute.Disk) ret1, _ := ret[1].(*retry.Error) return ret0, ret1 } // ListByResourceGroup indicates an expected call of ListByResourceGroup. func (mr *MockInterfaceMockRecorder) ListByResourceGroup(ctx, resourceGroupName interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ListByResourceGroup", reflect.TypeOf((*MockInterface)(nil).ListByResourceGroup), ctx, resourceGroupName) }
Java
.tobox{ float: left; padding: 10px; background-color: #eee; width:120px; margin:0 10px 10px 0px; text-align:center; border-radius: 3px; } .tobox.two{ width: 180px; } .tobox.fixed-box{ position:fixed; right:50px; top:50px; } .dark-tooltip{ display:none; position:absolute; z-index:99; text-decoration:none; font-weight:normal; height:auto; top:0; left:0;} .dark-tooltip.small{ padding:4px; font-size:12px; max-width:150px; -webkit-border-radius: 2px; -moz-border-radius: 2px; border-radius: 2px; } .dark-tooltip.medium{ padding:10px; font-size:14px; max-width:200px; -webkit-border-radius: 4px; -moz-border-radius: 4px; border-radius: 4px;} .dark-tooltip.large{ padding:16px; font-size:16px; max-width:250px; -webkit-border-radius: 6px; -moz-border-radius: 6px; border-radius: 6px; } /* Tips */ .dark-tooltip .tip{ transform: scale(1.01); -webkit-transform: scale(1.01); transform: scale(1.01); content: ""; position: absolute; width:0; height:0; border-style: solid; line-height: 0px; } .dark-tooltip.south .tip{ left:50%; top:100%;} .dark-tooltip.west .tip{ left:0; top:50%;} .dark-tooltip.north .tip{ left:50%; top:0; } .dark-tooltip.east .tip{ left:100%; top:50%;} .dark-tooltip.south.small .tip{ border-width: 7px 5px 0 5px; margin-left:-5px;} .dark-tooltip.south.medium .tip{ border-width: 8px 6px 0 6px; margin-left:-6px;} .dark-tooltip.south.large .tip{ border-width: 14px 12px 0 12px; margin-left:-12px;} .dark-tooltip.west.small .tip{ border-width: 5px 7px 5px 0; margin-left:-7px; margin-top:-5px;} .dark-tooltip.west.medium .tip{ border-width: 6px 8px 6px 0; margin-left:-8px; margin-top:-6px;} .dark-tooltip.west.large .tip{ border-width: 12px 14px 12px 0; margin-left:-14px; margin-top:-12px;} .dark-tooltip.north.small .tip{ border-width: 0 5px 7px 5px; margin-left:-5px; margin-top:-7px;} .dark-tooltip.north.medium .tip{ border-width: 0 6px 8px 6px; margin-left:-6px; margin-top:-8px;} .dark-tooltip.north.large .tip{ border-width: 0 12px 14px 12px; margin-left:-12px; margin-top:-14px;} .dark-tooltip.east.small .tip{ border-width: 5px 0 5px 7px; margin-top:-5px;} .dark-tooltip.east.medium .tip{ border-width: 6px 0 6px 8px; margin-top:-6px;} .dark-tooltip.east.large .tip{ border-width: 12px 0 12px 14px; margin-top:-12px;} /* confirm */ .dark-tooltip ul.confirm{ list-style-type:none;margin-top:5px;display:inline-block;margin:0 auto; } .dark-tooltip ul.confirm li{ padding:10px;float:left;margin:5px;min-width:25px;-webkit-border-radius:3px;-moz-border-radius:3px;-o-border-radius:3px;border-radius:3px;} /* themes */ .dark-tooltip.dark{ background-color:#1e1e1e; color:#fff; } .dark-tooltip.light{ background-color:#ebedf3; color:#1e1e1e; } .dark-tooltip.dark.south .tip{ border-color: #1e1e1e transparent transparent transparent; _border-color: #1e1e1e #000000 #000000 #000000; _filter: progid:DXImageTransform.Microsoft.Chroma(color='#000000'); } .dark-tooltip.dark.west .tip{ border-color: transparent #1e1e1e transparent transparent; _border-color: #000000 #1e1e1e #000000 #000000; _filter: progid:DXImageTransform.Microsoft.Chroma(color='#000000'); } .dark-tooltip.dark.north .tip{ border-color: transparent transparent #1e1e1e transparent; _border-color: #000000 #000000 #1e1e1e #000000; _filter: progid:DXImageTransform.Microsoft.Chroma(color='#000000'); } .dark-tooltip.dark.east .tip{ border-color: transparent transparent transparent #1e1e1e; _border-color: #000000 #000000 #000000 #1e1e1e; _filter: progid:DXImageTransform.Microsoft.Chroma(color='#000000'); } .dark-tooltip.light.south .tip{ border-color: #ebedf3 transparent transparent transparent; _border-color: #ebedf3 #000000 #000000 #000000; _filter: progid:DXImageTransform.Microsoft.Chroma(color='#000000'); } .dark-tooltip.light.west .tip{ border-color: transparent #ebedf3 transparent transparent; _border-color: #000000 #ebedf3 #000000 #000000; _filter: progid:DXImageTransform.Microsoft.Chroma(color='#000000'); } .dark-tooltip.light.north .tip{ border-color: transparent transparent #ebedf3 transparent; _border-color: #000000 #000000 #ebedf3 #000000; _filter: progid:DXImageTransform.Microsoft.Chroma(color='#000000'); } .dark-tooltip.light.east .tip{ border-color: transparent transparent transparent #ebedf3; _border-color:#000000 #000000 #000000 #ebedf3 ; _filter: progid:DXImageTransform.Microsoft.Chroma(color='#000000'); } .dark-tooltip.dark ul.confirm li{ background-color:#416E85;} .dark-tooltip.dark ul.confirm li:hover{ background-color:#417E85;} .dark-tooltip.light ul.confirm li{ background-color:#C1DBDB;} .dark-tooltip.light ul.confirm li:hover{ background-color:#DCE8E8;} /* Animations */ .animated{ -webkit-animation-fill-mode:both;-moz-animation-fill-mode:both;-ms-animation-fill-mode:both;-o-animation-fill-mode:both;animation-fill-mode:both; -webkit-animation-duration:.5s;-moz-animation-duration:.5s;-ms-animation-duration:.5s;-o-animation-duration:.5s;animation-duration:.5s; } @-webkit-keyframes flipInUp { 0% { -webkit-transform: perspective(400px) rotateX(-90deg); opacity: 0;} 40% { -webkit-transform: perspective(400px) rotateX(5deg);} 70% { -webkit-transform: perspective(400px) rotateX(-5deg);} 100% { -webkit-transform: perspective(400px) rotateX(0deg); opacity: 1;} } @-moz-keyframes flipInUp { 0% {transform: perspective(400px) rotateX(-90deg);opacity: 0;} 40% {transform: perspective(400px) rotateX(5deg);} 70% {transform: perspective(400px) rotateX(-5deg);} 100% {transform: perspective(400px) rotateX(0deg);opacity: 1;} } @-o-keyframes flipInUp { 0% {-o-transform: perspective(400px) rotateX(-90deg);opacity: 0;} 40% {-o-transform: perspective(400px) rotateX(5deg);} 70% {-o-transform: perspective(400px) rotateX(-5deg);} 100% {-o-transform: perspective(400px) rotateX(0deg);opacity: 1;} } @keyframes flipInUp { 0% {transform: perspective(400px) rotateX(-90deg);opacity: 0;} 40% {transform: perspective(400px) rotateX(5deg);} 70% {transform: perspective(400px) rotateX(-5deg);} 100% {transform: perspective(400px) rotateX(0deg);opacity: 1;} } @-webkit-keyframes flipInRight { 0% { -webkit-transform: perspective(400px) rotateY(-90deg); opacity: 0;} 40% { -webkit-transform: perspective(400px) rotateY(5deg);} 70% { -webkit-transform: perspective(400px) rotateY(-5deg);} 100% { -webkit-transform: perspective(400px) rotateY(0deg); opacity: 1;} } @-moz-keyframes flipInRight { 0% {transform: perspective(400px) rotateY(-90deg);opacity: 0;} 40% {transform: perspective(400px) rotateY(5deg);} 70% {transform: perspective(400px) rotateY(-5deg);} 100% {transform: perspective(400px) rotateY(0deg);opacity: 1;} } @-o-keyframes flipInRight { 0% {-o-transform: perspective(400px) rotateY(-90deg);opacity: 0;} 40% {-o-transform: perspective(400px) rotateY(5deg);} 70% {-o-transform: perspective(400px) rotateY(-5deg);} 100% {-o-transform: perspective(400px) rotateY(0deg);opacity: 1;} } @keyframes flipInRight { 0% {transform: perspective(400px) rotateY(-90deg);opacity: 0;} 40% {transform: perspective(400px) rotateY(5deg);} 70% {transform: perspective(400px) rotateY(-5deg);} 100% {transform: perspective(400px) rotateY(0deg);opacity: 1;} } .flipIn { -webkit-backface-visibility: visible !important; -moz-backface-visibility: visible !important; -o-backface-visibility: visible !important; backface-visibility: visible !important} .flipIn.south, .flipIn.north { -webkit-animation-name: flipInUp; -moz-animation-name: flipInUp; -o-animation-name: flipInUp; animation-name: flipInUp; } .flipIn.west, .flipIn.east { -webkit-animation-name: flipInRight; -moz-animation-name: flipInRight; -o-animation-name: flipInRight; animation-name: flipInRight; } @-webkit-keyframes fadeIn { 0% {opacity: 0;} 100% {opacity: 1;}} @-moz-keyframes fadeIn { 0% {opacity: 0;} 100% {opacity: 1;}} @-o-keyframes fadeIn {0% {opacity: 0;}100% {opacity: 1;}} @keyframes fadeIn {0% {opacity: 0;}100% {opacity: 1;}} .fadeIn{-webkit-animation-name: fadeIn; -moz-animation-name: fadeIn; -o-animation-name: fadeIn; animation-name: fadeIn;} /* Modal */ .darktooltip-modal-layer{ position: fixed; top: 0; left: 0; width: 100%; height: 100%; background-image: url('http://gsrthemes.com/aaika/fullwidth/js/img/modal-bg.png'); opacity: .7; display: none; }
Java
<!doctype html public "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd"> <html> <head> <title>PHPXRef 0.7.1 : Unnamed Project : Variable Reference: $object1</title> <link rel="stylesheet" href="../sample.css" type="text/css"> <link rel="stylesheet" href="../sample-print.css" type="text/css" media="print"> <style id="hilight" type="text/css"></style> <meta http-equiv="content-type" content="text/html;charset=iso-8859-1"> </head> <body bgcolor="#ffffff" text="#000000" link="#801800" vlink="#300540" alink="#ffffff"> <table class="pagetitle" width="100%"> <tr> <td valign="top" class="pagetitle"> [ <a href="../index.html">Index</a> ] </td> <td align="right" class="pagetitle"> <h2 style="margin-bottom: 0px">PHP Cross Reference of Unnamed Project</h2> </td> </tr> </table> <!-- Generated by PHPXref 0.7.1 at Thu Oct 23 18:57:41 2014 --> <!-- PHPXref (c) 2000-2010 Gareth Watts - gareth@omnipotent.net --> <!-- http://phpxref.sourceforge.net/ --> <script src="../phpxref.js" type="text/javascript"></script> <script language="JavaScript" type="text/javascript"> <!-- ext='.html'; relbase='../'; subdir='_variables'; filename='index.html'; cookiekey='phpxref'; handleNavFrame(relbase, subdir, filename); logVariable('object1'); // --> </script> <script language="JavaScript" type="text/javascript"> if (gwGetCookie('xrefnav')=='off') document.write('<p class="navlinks">[ <a href="javascript:navOn()">Show Explorer<\/a> ]<\/p>'); else document.write('<p class="navlinks">[ <a href="javascript:navOff()">Hide Explorer<\/a> ]<\/p>'); </script> <noscript> <p class="navlinks"> [ <a href="../nav.html" target="_top">Show Explorer</a> ] [ <a href="index.html" target="_top">Hide Navbar</a> ] </p> </noscript> [<a href="../index.html">Top level directory</a>]<br> <script language="JavaScript" type="text/javascript"> <!-- document.writeln('<table align="right" class="searchbox-link"><tr><td><a class="searchbox-link" href="javascript:void(0)" onMouseOver="showSearchBox()">Search</a><br>'); document.writeln('<table border="0" cellspacing="0" cellpadding="0" class="searchbox" id="searchbox">'); document.writeln('<tr><td class="searchbox-title">'); document.writeln('<a class="searchbox-title" href="javascript:showSearchPopup()">Search History +</a>'); document.writeln('<\/td><\/tr>'); document.writeln('<tr><td class="searchbox-body" id="searchbox-body">'); document.writeln('<form name="search" style="margin:0px; padding:0px" onSubmit=\'return jump()\'>'); document.writeln('<a class="searchbox-body" href="../_classes/index.html">Class<\/a>: '); document.writeln('<input type="text" size=10 value="" name="classname"><br>'); document.writeln('<a id="funcsearchlink" class="searchbox-body" href="../_functions/index.html">Function<\/a>: '); document.writeln('<input type="text" size=10 value="" name="funcname"><br>'); document.writeln('<a class="searchbox-body" href="../_variables/index.html">Variable<\/a>: '); document.writeln('<input type="text" size=10 value="" name="varname"><br>'); document.writeln('<a class="searchbox-body" href="../_constants/index.html">Constant<\/a>: '); document.writeln('<input type="text" size=10 value="" name="constname"><br>'); document.writeln('<a class="searchbox-body" href="../_tables/index.html">Table<\/a>: '); document.writeln('<input type="text" size=10 value="" name="tablename"><br>'); document.writeln('<input type="submit" class="searchbox-button" value="Search">'); document.writeln('<\/form>'); document.writeln('<\/td><\/tr><\/table>'); document.writeln('<\/td><\/tr><\/table>'); // --> </script> <div id="search-popup" class="searchpopup"><p id="searchpopup-title" class="searchpopup-title">title</p><div id="searchpopup-body" class="searchpopup-body">Body</div><p class="searchpopup-close"><a href="javascript:gwCloseActive()">[close]</a></p></div> <h3>Variable Cross Reference</h3> <h2><a href="index.html#object1">$object1</a></h2> <b>Defined at:</b><ul> <li><a href="../tests/simpletest/test/compatibility_test.php.html">/tests/simpletest/test/compatibility_test.php</A> -> <a href="../tests/simpletest/test/compatibility_test.php.source.html#l32"> line 32</A></li> </ul> <br><b>Referenced 2 times:</b><ul> <li><a href="../tests/simpletest/test/compatibility_test.php.html">/tests/simpletest/test/compatibility_test.php</a> -> <a href="../tests/simpletest/test/compatibility_test.php.source.html#l32"> line 32</a></li> <li><a href="../tests/simpletest/test/compatibility_test.php.html">/tests/simpletest/test/compatibility_test.php</a> -> <a href="../tests/simpletest/test/compatibility_test.php.source.html#l34"> line 34</a></li> </ul> <!-- A link to the phpxref site in your customized footer file is appreciated ;-) --> <br><hr> <table width="100%"> <tr><td>Generated: Thu Oct 23 18:57:41 2014</td> <td align="right"><i>Cross-referenced by <a href="http://phpxref.sourceforge.net/">PHPXref 0.7.1</a></i></td> </tr> </table> </body></html>
Java
/* * Copyright 2014 Alexey Andreev. * * 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.teavm.classlib.java.util; import org.teavm.classlib.java.io.TSerializable; import org.teavm.classlib.java.lang.TMath; import org.teavm.classlib.java.lang.TObject; import org.teavm.javascript.spi.GeneratedBy; /** * * @author Alexey Andreev */ public class TRandom extends TObject implements TSerializable { public TRandom() { } public TRandom(@SuppressWarnings("unused") long seed) { } public void setSeed(@SuppressWarnings("unused") long seed) { } protected int next(int bits) { return (int)(random() * (1L << TMath.min(32, bits))); } public void nextBytes(byte[] bytes) { for (int i = 0; i < bytes.length; ++i) { bytes[i] = (byte)next(8); } } public int nextInt() { return next(32); } public int nextInt(int n) { return (int)(random() * n); } public long nextLong() { return ((long)nextInt() << 32) | nextInt(); } public boolean nextBoolean() { return nextInt() % 2 == 0; } public float nextFloat() { return (float)random(); } public double nextDouble() { return random(); } @GeneratedBy(RandomNativeGenerator.class) private static native double random(); }
Java
#include <iostream> #include "SParser.hpp" #pragma once namespace Silent { /*static class SymTablePrinter { public: static void Out(std::string str, uint64_t currentTab) { std::string tabs = ""; for (uint64_t i = 0; i < currentTab; i++) tabs += "\t"; std::cout << tabs << str << std::endl; } SymTablePrinter() { } static void PrintSymTable(SymbolTable* symTable) { PrintNode(symTable->self, 0); } static void PrintNode(TableNode node, uint64_t currentTab) { switch (node.nodeType) { case TableNode::Type::Program: { Program* p = (Program*)node.GetNode(); Out("Program", currentTab); currentTab++; for(TableNode node : p->table->GetItems()) PrintNode(node, currentTab); currentTab--; } break; case TableNode::Type::Namespace: { Namespace* n = (Namespace*)node.GetNode(); Out("Namespace " + n->GetId(), currentTab); currentTab++; for (TableNode node : n->GetTable()->GetItems()) PrintNode(node, currentTab); currentTab--; } break; case TableNode::Type::Subroutine: { Subroutine* s = (Subroutine*)node.GetNode(); Out("Subroutine " + s->GetId(), currentTab); currentTab++; for (TableNode node : s->GetTable()->GetItems()) PrintNode(node, currentTab); currentTab--; } break; case TableNode::Type::Variable: { Variable* v = (Variable*)node.GetNode(); Out("Variable " + v->GetId(), currentTab); } break; case TableNode::Type::Structure: { Type* t = (Type*)node.GetNode(); Out("Type " + t->GetId(), currentTab); currentTab++; for (TableNode node : t->GetTable()->GetItems()) PrintNode(node, currentTab); currentTab--; } break; } } };*/ }
Java
/* Copyright (c) The m-m-m Team, Licensed under the Apache License, Version 2.0 * http://www.apache.org/licenses/LICENSE-2.0 */ package net.sf.mmm.util.io.base; import net.sf.mmm.util.exception.api.NlsNullPointerException; /** * This class is similar to {@link java.nio.ByteBuffer} but a lot simpler. * * @see java.nio.ByteBuffer#wrap(byte[], int, int) * * @author Joerg Hohwiller (hohwille at users.sourceforge.net) * @since 1.1.0 */ public class ByteArrayImpl extends AbstractByteArray { private final byte[] buffer; private int minimumIndex; private int maximumIndex; /** * The constructor. * * @param capacity is the {@code length} of the internal {@link #getBytes() buffer}. */ public ByteArrayImpl(int capacity) { this(new byte[capacity], 0, -1); } /** * The constructor. * * @param buffer is the internal {@link #getBytes() buffer}. */ public ByteArrayImpl(byte[] buffer) { this(buffer, 0, buffer.length - 1); } /** * The constructor. * * @param buffer is the internal {@link #getBytes() buffer}. * @param startIndex is the {@link #getCurrentIndex() current index} as well as the {@link #getMinimumIndex() minimum * index}. * @param maximumIndex is the {@link #getMaximumIndex() maximum index}. */ public ByteArrayImpl(byte[] buffer, int startIndex, int maximumIndex) { super(); if (buffer == null) { throw new NlsNullPointerException("buffer"); } this.buffer = buffer; this.minimumIndex = startIndex; this.maximumIndex = maximumIndex; } @Override public byte[] getBytes() { return this.buffer; } @Override public int getCurrentIndex() { return this.minimumIndex; } @Override public int getMinimumIndex() { return this.minimumIndex; } @Override public int getMaximumIndex() { return this.maximumIndex; } /** * This method sets the {@link #getMaximumIndex() maximumIndex}. This may be useful if the buffer should be reused. * <br> * <b>ATTENTION:</b><br> * Be very careful and only use this method if you know what you are doing! * * @param maximumIndex is the {@link #getMaximumIndex() maximumIndex} to set. It has to be in the range from {@code 0} * ( <code>{@link #getCurrentIndex() currentIndex} - 1</code>) to <code>{@link #getBytes()}.length</code>. */ protected void setMaximumIndex(int maximumIndex) { this.maximumIndex = maximumIndex; } @Override public ByteArrayImpl createSubArray(int minimum, int maximum) { checkSubArray(minimum, maximum); return new ByteArrayImpl(this.buffer, minimum, maximum); } @Override public String toString() { return new String(this.buffer, this.minimumIndex, getBytesAvailable()); } }
Java
/* * Licensed to Crate under one or more contributor license agreements. * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. Crate 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. * * However, if you have executed another commercial license agreement * with Crate these terms will supersede the license and you may use the * software solely pursuant to the terms of the relevant commercial * agreement. */ package io.crate.execution.engine.collect; import io.crate.breaker.RamAccounting; import io.crate.data.BatchIterator; import io.crate.data.Row; import io.crate.execution.engine.aggregation.impl.SumAggregation; import io.crate.expression.reference.doc.lucene.BytesRefColumnReference; import io.crate.expression.reference.doc.lucene.CollectorContext; import io.crate.expression.reference.doc.lucene.LongColumnReference; import io.crate.expression.reference.doc.lucene.LuceneCollectorExpression; import io.crate.metadata.Functions; import io.crate.metadata.Reference; import io.crate.metadata.ReferenceIdent; import io.crate.metadata.RelationName; import io.crate.metadata.RowGranularity; import io.crate.metadata.functions.Signature; import io.crate.test.integration.CrateDummyClusterServiceUnitTest; import io.crate.testing.TestingRowConsumer; import io.crate.types.DataTypes; import org.apache.lucene.document.Document; import org.apache.lucene.document.NumericDocValuesField; import org.apache.lucene.document.SortedSetDocValuesField; import org.apache.lucene.index.DirectoryReader; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.index.IndexWriterConfig; import org.apache.lucene.index.LeafReaderContext; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.MatchAllDocsQuery; import org.apache.lucene.store.ByteBuffersDirectory; import org.elasticsearch.common.lucene.BytesRefs; import org.elasticsearch.index.mapper.NumberFieldMapper; import org.junit.Before; import org.junit.Test; import java.io.IOException; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Consumer; import static io.crate.testing.TestingHelpers.createNodeContext; import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.Matchers.instanceOf; public class DocValuesGroupByOptimizedIteratorTest extends CrateDummyClusterServiceUnitTest { private Functions functions; private IndexSearcher indexSearcher; private List<Object[]> rows = List.of( new Object[]{"1", 1L, 1L}, new Object[]{"0", 0L, 2L}, new Object[]{"1", 1L, 3L}, new Object[]{"0", 0L, 4L} ); @Before public void setup() throws IOException { var nodeContext = createNodeContext(); functions = nodeContext.functions(); var indexWriter = new IndexWriter(new ByteBuffersDirectory(), new IndexWriterConfig()); for (var row : rows) { Document doc = new Document(); doc.add(new SortedSetDocValuesField("x", BytesRefs.toBytesRef(row[0]))); doc.add(new NumericDocValuesField("y", (Long) row[1])); doc.add(new NumericDocValuesField("z", (Long) row[2])); indexWriter.addDocument(doc); } indexWriter.commit(); indexSearcher = new IndexSearcher(DirectoryReader.open(indexWriter)); } @Test public void test_group_by_doc_values_optimized_iterator_for_single_numeric_key() throws Exception { SumAggregation<?> sumAggregation = (SumAggregation<?>) functions.getQualified( Signature.aggregate( SumAggregation.NAME, DataTypes.LONG.getTypeSignature(), DataTypes.LONG.getTypeSignature() ), List.of(DataTypes.LONG), DataTypes.LONG ); var aggregationField = new NumberFieldMapper.NumberFieldType(NumberFieldMapper.NumberType.LONG); aggregationField.setName("z"); var sumDocValuesAggregator = sumAggregation.getDocValueAggregator( List.of(DataTypes.LONG), List.of(aggregationField) ); var keyExpressions = List.of(new LongColumnReference("y")); var it = DocValuesGroupByOptimizedIterator.GroupByIterator.forSingleKey( List.of(sumDocValuesAggregator), indexSearcher, new Reference( new ReferenceIdent(RelationName.fromIndexName("test"), "y"), RowGranularity.DOC, DataTypes.LONG, null, null ), keyExpressions, RamAccounting.NO_ACCOUNTING, new MatchAllDocsQuery(), new CollectorContext() ); var rowConsumer = new TestingRowConsumer(); rowConsumer.accept(it, null); assertThat( rowConsumer.getResult(), containsInAnyOrder(new Object[]{0L, 6L}, new Object[]{1L, 4L})); } @Test public void test_group_by_doc_values_optimized_iterator_for_many_keys() throws Exception { SumAggregation<?> sumAggregation = (SumAggregation<?>) functions.getQualified( Signature.aggregate( SumAggregation.NAME, DataTypes.LONG.getTypeSignature(), DataTypes.LONG.getTypeSignature() ), List.of(DataTypes.LONG), DataTypes.LONG ); var aggregationField = new NumberFieldMapper.NumberFieldType(NumberFieldMapper.NumberType.LONG); aggregationField.setName("z"); var sumDocValuesAggregator = sumAggregation.getDocValueAggregator( List.of(DataTypes.LONG), List.of(aggregationField) ); var keyExpressions = List.of(new BytesRefColumnReference("x"), new LongColumnReference("y")); var keyRefs = List.of( new Reference( new ReferenceIdent(RelationName.fromIndexName("test"), "x"), RowGranularity.DOC, DataTypes.STRING, null, null ), new Reference( new ReferenceIdent(RelationName.fromIndexName("test"), "y"), RowGranularity.DOC, DataTypes.LONG, null, null ) ); var it = DocValuesGroupByOptimizedIterator.GroupByIterator.forManyKeys( List.of(sumDocValuesAggregator), indexSearcher, keyRefs, keyExpressions, RamAccounting.NO_ACCOUNTING, new MatchAllDocsQuery(), new CollectorContext() ); var rowConsumer = new TestingRowConsumer(); rowConsumer.accept(it, null); assertThat( rowConsumer.getResult(), containsInAnyOrder(new Object[]{"0", 0L, 6L}, new Object[]{"1", 1L, 4L}) ); } @Test public void test_optimized_iterator_stop_processing_on_kill() throws Exception { Throwable expectedException = stopOnInterrupting(it -> it.kill(new InterruptedException("killed"))); assertThat(expectedException, instanceOf(InterruptedException.class)); } @Test public void test_optimized_iterator_stop_processing_on_close() throws Exception { Throwable expectedException = stopOnInterrupting(BatchIterator::close); assertThat(expectedException, instanceOf(IllegalStateException.class)); } private Throwable stopOnInterrupting(Consumer<BatchIterator<Row>> interrupt) throws Exception { CountDownLatch waitForLoadNextBatch = new CountDownLatch(1); CountDownLatch pauseOnDocumentCollecting = new CountDownLatch(1); CountDownLatch batchLoadingCompleted = new CountDownLatch(1); BatchIterator<Row> it = createBatchIterator(() -> { waitForLoadNextBatch.countDown(); try { pauseOnDocumentCollecting.await(5, TimeUnit.SECONDS); } catch (InterruptedException e) { throw new RuntimeException(e); } }); AtomicReference<Throwable> exception = new AtomicReference<>(); Thread t = new Thread(() -> { try { it.loadNextBatch().whenComplete((r, e) -> { if (e != null) { exception.set(e.getCause()); } batchLoadingCompleted.countDown(); }); } catch (Exception e) { exception.set(e); } }); t.start(); waitForLoadNextBatch.await(5, TimeUnit.SECONDS); interrupt.accept(it); pauseOnDocumentCollecting.countDown(); batchLoadingCompleted.await(5, TimeUnit.SECONDS); return exception.get(); } private BatchIterator<Row> createBatchIterator(Runnable onNextReader) { return DocValuesGroupByOptimizedIterator.GroupByIterator.getIterator( List.of(), indexSearcher, List.of(new LuceneCollectorExpression<>() { @Override public void setNextReader(LeafReaderContext context) { onNextReader.run(); } @Override public Object value() { return null; } }), RamAccounting.NO_ACCOUNTING, (states, key) -> { }, (expressions) -> expressions.get(0).value(), (key, cells) -> cells[0] = key, new MatchAllDocsQuery(), new CollectorContext() ); } }
Java
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.vespaclient; public class ClusterDef { private final String name; public ClusterDef(String name) { this.name = name; } public String getName() { return name; } public String getRoute() { return "[Content:cluster=" + name + "]"; } }
Java
/* * Copyright (C) 2018 the original author or authors. * * This file is part of jBB Application Project. * * Licensed under the Apache License, Version 2.0 (the "License"); * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 */ package org.jbb.security.rest.oauth.client; import io.swagger.annotations.ApiModel; import lombok.AccessLevel; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; @Getter @Setter @Builder @ApiModel("OAuthClientSecret") @NoArgsConstructor(access = AccessLevel.PUBLIC) @AllArgsConstructor(access = AccessLevel.PRIVATE) public class ClientSecretDto { private String clientSecret; }
Java
# # Author:: Steven Danna (<steve@chef.io>) # Author:: Tyler Cloke (<tyler@chef.io>) # Copyright:: Copyright (c) Chef Software Inc. # 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_relative "../knife" require_relative "../dist" class Chef class Knife class UserCreate < Knife attr_accessor :user_field deps do require_relative "../user_v1" end option :file, short: "-f FILE", long: "--file FILE", description: "Write the private key to a file if the server generated one." option :user_key, long: "--user-key FILENAME", description: "Set the initial default key for the user from a file on disk (cannot pass with --prevent-keygen)." option :prevent_keygen, short: "-k", long: "--prevent-keygen", description: "API V1 (#{Chef::Dist::SERVER_PRODUCT} 12.1+) only. Prevent server from generating a default key pair for you. Cannot be passed with --user-key.", boolean: true banner "knife user create USERNAME DISPLAY_NAME FIRST_NAME LAST_NAME EMAIL PASSWORD (options)" def user @user_field ||= Chef::UserV1.new end def create_user_from_hash(hash) Chef::UserV1.from_hash(hash).create end def run test_mandatory_field(@name_args[0], "username") user.username @name_args[0] test_mandatory_field(@name_args[1], "display name") user.display_name @name_args[1] test_mandatory_field(@name_args[2], "first name") user.first_name @name_args[2] test_mandatory_field(@name_args[3], "last name") user.last_name @name_args[3] test_mandatory_field(@name_args[4], "email") user.email @name_args[4] test_mandatory_field(@name_args[5], "password") user.password @name_args[5] if config[:user_key] && config[:prevent_keygen] show_usage ui.fatal("You cannot pass --user-key and --prevent-keygen") exit 1 end if !config[:prevent_keygen] && !config[:user_key] user.create_key(true) end if config[:user_key] user.public_key File.read(File.expand_path(config[:user_key])) end output = edit_hash(user) final_user = create_user_from_hash(output) ui.info("Created #{user}") if final_user.private_key if config[:file] File.open(config[:file], "w") do |f| f.print(final_user.private_key) end else ui.msg final_user.private_key end end end end end end
Java
import numpy as np class WordClusters(object): def __init__(self, vocab, clusters): self.vocab = vocab self.clusters = clusters def ix(self, word): """ Returns the index on self.vocab and self.clusters for 'word' """ temp = np.where(self.vocab == word)[0] if temp.size == 0: raise KeyError("Word not in vocabulary") else: return temp[0] def __getitem__(self, word): return self.get_cluster(word) def get_cluster(self, word): """ Returns the cluster number for a word in the vocabulary """ idx = self.ix(word) return self.clusters[idx] def get_words_on_cluster(self, cluster): return self.vocab[self.clusters == cluster] @classmethod def from_text(cls, fname): vocab = np.genfromtxt(fname, dtype=str, delimiter=" ", usecols=0) clusters = np.genfromtxt(fname, dtype=int, delimiter=" ", usecols=1) return cls(vocab=vocab, clusters=clusters)
Java
package weixin.popular.bean.scan.crud; import weixin.popular.bean.scan.base.ProductGet; import weixin.popular.bean.scan.info.BrandInfo; public class ProductCreate extends ProductGet { private BrandInfo brand_info; public BrandInfo getBrand_info() { return brand_info; } public void setBrand_info(BrandInfo brand_info) { this.brand_info = brand_info; } }
Java
<!doctype html> <html ng-app="frontend"> <head> <meta charset="utf-8"> <title>frontend</title> <meta name="description" content=""> <meta name="viewport" content="width=device-width"> <!-- Place favicon.ico and apple-touch-icon.png in the root directory --> <!-- build:css({.tmp/serve,src}) styles/vendor.css --> <!-- bower:css --> <!-- run `gulp inject` to automatically populate bower styles dependencies --> <!-- endbower --> <!-- endbuild --> <!-- build:css({.tmp/serve,src}) styles/app.css --> <!-- inject:css --> <!-- css files will be automatically insert here --> <!-- endinject --> <!-- endbuild --> </head> <body> <!--[if lt IE 10]> <p class="browsehappy">You are using an <strong>outdated</strong> browser. Please <a href="http://browsehappy.com/">upgrade your browser</a> to improve your experience.</p> <![endif]--> <div ui-view></div> <!-- build:js(src) scripts/vendor.js --> <!-- bower:js --> <!-- run `gulp inject` to automatically populate bower script dependencies --> <!-- endbower --> <!-- endbuild --> <!-- build:js({.tmp/serve,.tmp/partials}) scripts/app.js --> <!-- inject:js --> <!-- js files will be automatically insert here --> <!-- endinject --> <script src="https://api-maps.yandex.ru/2.1/?lang=ru_RU" type="text/javascript"></script> <!-- inject:partials --> <!-- angular templates will be automatically converted in js and inserted here --> <!-- endinject --> <!-- endbuild --> </body> </html>
Java
package Paws::CloudDirectory::BatchDetachFromIndex; use Moose; has IndexReference => (is => 'ro', isa => 'Paws::CloudDirectory::ObjectReference', required => 1); has TargetReference => (is => 'ro', isa => 'Paws::CloudDirectory::ObjectReference', required => 1); 1; ### main pod documentation begin ### =head1 NAME Paws::CloudDirectory::BatchDetachFromIndex =head1 USAGE This class represents one of two things: =head3 Arguments in a call to a service Use the attributes of this class as arguments to methods. You shouldn't make instances of this class. Each attribute should be used as a named argument in the calls that expect this type of object. As an example, if Att1 is expected to be a Paws::CloudDirectory::BatchDetachFromIndex object: $service_obj->Method(Att1 => { IndexReference => $value, ..., TargetReference => $value }); =head3 Results returned from an API call Use accessors for each attribute. If Att1 is expected to be an Paws::CloudDirectory::BatchDetachFromIndex object: $result = $service_obj->Method(...); $result->Att1->IndexReference =head1 DESCRIPTION Detaches the specified object from the specified index inside a BatchRead operation. For more information, see DetachFromIndex and BatchReadRequest$Operations. =head1 ATTRIBUTES =head2 B<REQUIRED> IndexReference => L<Paws::CloudDirectory::ObjectReference> A reference to the index object. =head2 B<REQUIRED> TargetReference => L<Paws::CloudDirectory::ObjectReference> A reference to the object being detached from the index. =head1 SEE ALSO This class forms part of L<Paws>, describing an object used in L<Paws::CloudDirectory> =head1 BUGS and CONTRIBUTIONS The source code is located here: https://github.com/pplu/aws-sdk-perl Please report bugs to: https://github.com/pplu/aws-sdk-perl/issues =cut
Java
# Dematium graminum Lib. SPECIES #### Status ACCEPTED #### According to Index Fungorum #### Published in Pl. crypt. Arduenna (Liège), fasc. no. 284 (1830) #### Original name Dematium graminum Lib. ### Remarks null
Java
#!/usr/bin/env bash systemctl stop fuseki systemctl stop marple #general vars echo ">>>> Updating Fuseki" export TC_USER=fuseki export TC_GROUP=fuseki # set erb vars # endpoint name for fuseki export EP_NAME=core export SVC=fuseki export SVC_DESC="Jena-Fuseki Tomcat container" export MARPLE_SVC=marple export MARPLE_SVC_DESC="Marple service for fuseki Lucene indexes" export JAVA_HOME=`type -p javac|xargs readlink -f|xargs dirname|xargs dirname` export LUCENE_BO_VER=1.5.0 export LUCENE_BO_JAR="lucene-bo-${LUCENE_BO_VER}.jar" export LUCENE_BO_REL="https://github.com/buda-base/lucene-bo/releases/download/v${LUCENE_BO_VER}/${LUCENE_BO_JAR}" export LUCENE_ZH_VER=0.4.1 export LUCENE_ZH_JAR="lucene-zh-${LUCENE_ZH_VER}.jar" export LUCENE_ZH_REL="https://github.com/buda-base/lucene-zh/releases/download/v${LUCENE_ZH_VER}/${LUCENE_ZH_JAR}" export LUCENE_SA_VER=1.1.0 export LUCENE_SA_JAR="lucene-sa-${LUCENE_SA_VER}.jar" export LUCENE_SA_REL="https://github.com/buda-base/lucene-sa/releases/download/v${LUCENE_SA_VER}/${LUCENE_SA_JAR}" export MARPLE_REL="https://github.com/flaxsearch/marple/releases/download/v1.0/marple-1.0.jar" if [ -d /mnt/data ] ; then export DATA_DIR=/mnt/data ; else export DATA_DIR=/usr/local ; fi echo ">>>> DATA_DIR: " $DATA_DIR export DOWNLOADS=$DATA_DIR/downloads export THE_HOME=$DATA_DIR/$SVC export THE_BASE=$THE_HOME/base export CAT_HOME=$THE_HOME/tomcat echo ">>>>>>>> updating {$EP_NAME}.ttl to {$THE_BASE}/configuration/" erb /vagrant/conf/fuseki/ttl.erb > $THE_BASE/configuration/$EP_NAME.ttl echo ">>>>>>>> updating qonsole-config.js to {$CAT_HOME}/webapps/fuseki/js/app/" cp /vagrant/conf/fuseki/qonsole-config.js $CAT_HOME/webapps/fuseki/js/app/ echo ">>>>>>>> updating analyzers to {$CAT_HOME}/webapps/fuseki/WEB-INF/lib/" # the lucene-bo jar has to be added to fuseki/WEB-INF/lib/ otherwise # tomcat class loading cannot find rest of Lucene classes rm -f $CAT_HOME/webapps/fuseki/WEB-INF/lib/lucene-bo-*.jar rm -f $CAT_HOME/webapps/fuseki/WEB-INF/lib/lucene-sa-*.jar rm -f $CAT_HOME/webapps/fuseki/WEB-INF/lib/lucene-zh-*.jar pushd $DOWNLOADS; # wget -q -c $LUCENE_BO_REL wget -q $LUCENE_BO_REL -O $LUCENE_BO_JAR cp $LUCENE_BO_JAR $CAT_HOME/webapps/fuseki/WEB-INF/lib/ wget -q -c $LUCENE_ZH_REL cp $LUCENE_ZH_JAR $CAT_HOME/webapps/fuseki/WEB-INF/lib/ wget -q -c $LUCENE_SA_REL cp $LUCENE_SA_JAR $CAT_HOME/webapps/fuseki/WEB-INF/lib/ popd echo ">>>> restarting ${SVC}" systemctl start fuseki systemctl start marple echo ">>>> ${SVC} service listening on ${MAIN_PORT}" echo ">>>> Fuseki updating complete"
Java
package com.mattinsler.guiceymongo.data.query; import org.bson.BSON; /** * Created by IntelliJ IDEA. * User: mattinsler * Date: 12/29/10 * Time: 3:28 AM * To change this template use File | Settings | File Templates. */ public enum BSONType { Double(BSON.NUMBER), String(BSON.STRING), Object(BSON.OBJECT), Array(BSON.ARRAY), BinaryData(BSON.BINARY), ObjectId(BSON.OID), Boolean(BSON.BOOLEAN), Date(BSON.DATE), Null(BSON.NULL), RegularExpression(BSON.REGEX), Code(BSON.CODE), Symbol(BSON.SYMBOL), CodeWithScope(BSON.CODE_W_SCOPE), Integer(BSON.NUMBER_INT), Timestamp(BSON.TIMESTAMP), Long(BSON.NUMBER_LONG), MinKey(BSON.MINKEY), MaxKey(BSON.MAXKEY); private final byte _typeCode; BSONType(byte typeCode) { _typeCode = typeCode; } byte getTypeCode() { return _typeCode; } }
Java
/* * DBeaver - Universal Database Manager * Copyright (C) 2010-2017 Serge Rider (serge@jkiss.org) * Copyright (C) 2011-2012 Eugene Fradkin (eugene.fradkin@gmail.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jkiss.dbeaver.ext.oracle.views; import org.eclipse.swt.SWT; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.widgets.*; import org.jkiss.dbeaver.core.DBeaverCore; import org.jkiss.dbeaver.ext.oracle.model.OracleConstants; import org.jkiss.dbeaver.model.preferences.DBPPreferenceStore; import org.jkiss.dbeaver.model.DBPDataSourceContainer; import org.jkiss.dbeaver.ui.UIUtils; import org.jkiss.dbeaver.ui.preferences.PreferenceStoreDelegate; import org.jkiss.dbeaver.ui.preferences.TargetPrefPage; import org.jkiss.dbeaver.utils.PrefUtils; /** * PrefPageOracle */ public class PrefPageOracle extends TargetPrefPage { public static final String PAGE_ID = "org.jkiss.dbeaver.preferences.oracle.general"; //$NON-NLS-1$ private Text explainTableText; private Button rowidSupportCheck; private Button enableDbmsOuputCheck; public PrefPageOracle() { super(); setPreferenceStore(new PreferenceStoreDelegate(DBeaverCore.getGlobalPreferenceStore())); } @Override protected boolean hasDataSourceSpecificOptions(DBPDataSourceContainer dataSourceDescriptor) { DBPPreferenceStore store = dataSourceDescriptor.getPreferenceStore(); return store.contains(OracleConstants.PREF_EXPLAIN_TABLE_NAME) || store.contains(OracleConstants.PREF_SUPPORT_ROWID) || store.contains(OracleConstants.PREF_DBMS_OUTPUT) ; } @Override protected boolean supportsDataSourceSpecificOptions() { return true; } @Override protected Control createPreferenceContent(Composite parent) { Composite composite = UIUtils.createPlaceholder(parent, 1); { Group planGroup = UIUtils.createControlGroup(composite, "Execution plan", 2, GridData.FILL_HORIZONTAL, 0); Label descLabel = new Label(planGroup, SWT.WRAP); descLabel.setText("By default plan table in current or SYS schema will be used.\nYou may set some particular fully qualified plan table name here."); GridData gd = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING); gd.horizontalSpan = 2; descLabel.setLayoutData(gd); explainTableText = UIUtils.createLabelText(planGroup, "Plan table", "", SWT.BORDER, new GridData(GridData.FILL_HORIZONTAL)); } { Group planGroup = UIUtils.createControlGroup(composite, "Misc", 2, GridData.FILL_HORIZONTAL, 0); rowidSupportCheck = UIUtils.createLabelCheckbox(planGroup, "Use ROWID to identify rows", true); enableDbmsOuputCheck = UIUtils.createLabelCheckbox(planGroup, "Enable DBMS Output", true); } return composite; } @Override protected void loadPreferences(DBPPreferenceStore store) { explainTableText.setText(store.getString(OracleConstants.PREF_EXPLAIN_TABLE_NAME)); rowidSupportCheck.setSelection(store.getBoolean(OracleConstants.PREF_SUPPORT_ROWID)); enableDbmsOuputCheck.setSelection(store.getBoolean(OracleConstants.PREF_DBMS_OUTPUT)); } @Override protected void savePreferences(DBPPreferenceStore store) { store.setValue(OracleConstants.PREF_EXPLAIN_TABLE_NAME, explainTableText.getText()); store.setValue(OracleConstants.PREF_SUPPORT_ROWID, rowidSupportCheck.getSelection()); store.setValue(OracleConstants.PREF_DBMS_OUTPUT, enableDbmsOuputCheck.getSelection()); PrefUtils.savePreferenceStore(store); } @Override protected void clearPreferences(DBPPreferenceStore store) { store.setToDefault(OracleConstants.PREF_EXPLAIN_TABLE_NAME); store.setToDefault(OracleConstants.PREF_SUPPORT_ROWID); store.setToDefault(OracleConstants.PREF_DBMS_OUTPUT); } @Override protected String getPropertyPageID() { return PAGE_ID; } }
Java
package com.winsun.fruitmix.model; /** * Created by Administrator on 2016/7/6. */ public class Equipment { private String serviceName; private String host; private int port; public Equipment(String serviceName, String host, int port) { this.serviceName = serviceName; this.host = host; this.port = port; } public Equipment() { } public String getServiceName() { return serviceName; } public void setServiceName(String serviceName) { this.serviceName = serviceName; } public String getHost() { return host; } public void setHost(String host) { this.host = host; } public int getPort() { return port; } public void setPort(int port) { this.port = port; } }
Java