desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'@param childId: int åèç¹çid
return Defered Object'
| def callChild(self, key, *args, **kw):
| return self.childsmanager.callChild(key, *args, **kw)
|
'@param childId: int åèç¹çid
return Defered Object'
| def callChildNotForResult(self, childname, *args, **kw):
| self.childsmanager.callChildNotForResult(childname, *args, **kw)
|
''
| def __init__(self):
| self.netfactory = None
self.root = None
self.webroot = None
self.remote = {}
self.master_remote = None
self.db = None
self.mem = None
self.servername = None
self.remoteportlist = []
|
''
| def config(self, config, servername=None, dbconfig=None, memconfig=None, masterconf=None):
| GlobalObject().json_config = config
netport = config.get('netport')
webport = config.get('webport')
rootport = config.get('rootport')
self.remoteportlist = config.get('remoteport', [])
if (not servername):
servername = config.get('name')
logpath = config.get('log')
hasdb = config... |
'è¿è¡rpcçè¿æ¥'
| def remote_connect(self, rname, rhost):
| for cnf in self.remoteportlist:
_rname = cnf.get('rootname')
if (rname == _rname):
rport = cnf.get('rootport')
if (not rhost):
addr = ('localhost', rport)
else:
addr = (rhost, rport)
self.remote[rname].connect(addr)
... |
''
| def start(self):
| log.msg(('[%s] started...' % self.servername))
log.msg(('[%s] pid: %s' % (self.servername, os.getpid())))
reactor.run()
|
''
| def config(self, netfactory=None, root=None, remote=None, db=None):
| self.netfactory = netfactory
self.root = root
self.remote = remote
self.db = db
|
'@param url: str http 访é®çè·¯åŸ'
| def __init__(self, url, **kw):
| self._url = url
self.kw = kw
|
''
| def __call__(self, cls):
| if self._url:
child_name = self._url
else:
child_name = cls.__name__
return GlobalObject().webroot.route(child_name, **self.kw)(cls)
|
''
| def __init__(self, remotename):
| self.remotename = remotename
|
''
| def __call__(self, target):
| GlobalObject().remote[self.remotename]._reference._service.mapTarget(target)
|
''
| def __init__(self, logpath):
| self.file = file(logpath, 'w')
|
''
| def __call__(self, eventDict):
| if ('logLevel' in eventDict):
level = eventDict['logLevel']
elif eventDict['isError']:
level = 'ERROR'
else:
level = 'INFO'
text = log.textFromEventDict(eventDict)
if ((text is None) or (level != 'ERROR')):
return
nowdate = datetime.datetime.now()
self.file.wr... |
''
| def getHeadlength():
| pass
|
'Add a target unDisplay when client call it.'
| def addUnDisplayTarget(self, command):
| self.unDisplay.add(command)
|
'Add a target to the service.'
| def mapTarget(self, target):
| key = target.__name__
if self._targets.has_key(key):
exist_target = self._targets.get(key)
raise ('target [%d] Already exists, Conflict between the %s and %s' % (key, exist_target.__name__, target.__name__))
self._targets... |
'Remove a target from the service.'
| def unMapTarget(self, target):
| key = target.__name__
if (key in self._targets):
del self._targets[key]
|
'Remove a target from the service.'
| def unMapTargetByKey(self, targetKey):
| del self._targets[targetKey]
|
'Get a target from the service by name.'
| def getTarget(self, targetKey):
| target = self._targets.get(targetKey, None)
return target
|
'call Target
@param conn: client connection
@param targetKey: target ID
@param data: client data'
| def callTarget(self, targetKey, *args, **kw):
| target = self.getTarget(targetKey)
if (not target):
log.err((('the command ' + str(targetKey)) + ' not Found on service'))
return None
if (targetKey not in self.unDisplay):
log.msg(('call method %s on service[single]' % target.__name__))
response = t... |
'Add a target to the service.'
| def mapTarget(self, target):
| key = int(target.__name__.split('_')[(-1)])
if self._targets.has_key(key):
exist_target = self._targets.get(key)
raise ('target [%d] Already exists, Conflict between the %s and %s' % (key, exist_target.__name__, target.__name... |
'Remove a target from the service.'
| def unMapTarget(self, target):
| key = int(target.__name__.split('_')[(-1)])
if (key in self._targets):
del self._targets[key]
|
'add_argument(dest, ..., name=value, ...)
add_argument(option_string, option_string, ..., name=value, ...)'
| def add_argument(self, *args, **kwargs):
| chars = self.prefix_chars
if ((not args) or ((len(args) == 1) and (args[0][0] not in chars))):
if (args and ('dest' in kwargs)):
raise ValueError('dest supplied twice for positional argument')
kwargs = self._get_positional_kwargs(*args, **kwargs)
else:
kwar... |
'error(message: string)
Prints a usage message incorporating the message to stderr and
exits.
If you override this in a subclass, it should not return -- it
should either exit or raise an exception.'
| def error(self, message):
| self.print_usage(_sys.stderr)
self.exit(2, (_('%s: error: %s\n') % (self.prog, message)))
|
'Returns a list of subjects available on the website.'
| def get_clips(self):
| flatList = self._get_clips()
items = []
for (key, group) in groupby(flatList, (lambda x: x.category)):
clipsList = list((clip for clip in group))
items.append(Category(key, len(clipsList)))
return items
|
':return: List of Channels
:rtype : list ChannelItem'
| def get_channels(self):
| return get_channels()
|
':param channelID:
:return: List of programs for a Channel ID
:rtype: list of ProgramItem'
| def get_channel_programs(self, channelID):
| return get_channel_programs(channelID)
|
':param programID: Program ID
:param mediaType: Media type - either \'episodes\' or \'clips\'
:return: List of media items for the current Program ID and media type
:rtype: list of MediaItem'
| def get_program_media(self, programID, mediaType):
| return get_program_media(programID, mediaType)
|
'Quality can be one of the following options:
-> "360p LOW", "720p HD", "240p LOWEST", "520p HIGH"'
| def get_media_stream_by_media_id(self, quality, programID, mediaType, mediaID):
| return get_media_stream_by_media_id(quality, programID, mediaType, mediaID)
|
'The actual task for the job should be implemented here.'
| def run(self):
| pass
|
'Handle return value by appending to the ``self.result`` queue.'
| def _return(self, r):
| self.result.put(r)
|
'Does nothing in Python 2.4'
| def task_done(self):
| pass
|
'Does nothing in Python 2.4'
| def join(self):
| pass
|
'Add another worker to the pool.'
| def grow(self):
| t = self.worker_factory(self)
t.start()
self._size += 1
|
'Get rid of one worker from the pool. Raises IndexError if empty.'
| def shrink(self):
| if (self._size <= 0):
raise IndexError('pool is already empty')
self._size -= 1
self.put(SuicideJob())
|
'Retire the workers.'
| def shutdown(self):
| for i in xrange(self.size()):
self.put(SuicideJob())
|
'Approximate number of active workers (could be more if a shrinking is in progress).'
| def size(self):
| return self._size
|
'Perform a map operation distributed among the workers. Will block until done.'
| def map(self, fn, *seq):
| results = Queue()
args = zip(*seq)
for seq in args:
j = SimpleJob(results, fn, seq)
self.put(j)
r = []
for i in xrange(len(args)):
r.append(results.get())
return r
|
'DEPRECATED: Use join() instead.'
| def wait(self):
| self.join()
|
'Get jobs from the queue and perform them as they arrive.'
| def run(self):
| while 1:
job = self.jobs.get()
try:
job.run()
self.jobs.task_done()
except TerminationNotice:
self.jobs.task_done()
break
|
'Get jobs from the queue and perform them as they arrive.'
| def run(self):
| while 1:
job = self.jobs.get()
try:
job.run(toolbox=self.toolbox)
self.jobs.task_done()
except TerminationNotice:
self.jobs.task_done()
break
|
'Should we redirect and where to?
:returns: Truthy redirect location string if we got a redirect status
code and valid location. ``None`` if redirect status and no
location. ``False`` if not a redirect status code.'
| def get_redirect_location(self):
| if (self.status in [301, 302, 303, 307]):
return self.headers.get('location')
return False
|
'Similar to :meth:`httplib.HTTPResponse.read`, but with two additional
parameters: ``decode_content`` and ``cache_content``.
:param amt:
How much of the content to read. If specified, decoding and caching
is skipped because we can\'t decode partial content nor does it make
sense to cache partial content as the full res... | def read(self, amt=None, decode_content=None, cache_content=False):
| content_encoding = self.headers.get('content-encoding')
decoder = self.CONTENT_DECODERS.get(content_encoding)
if (decode_content is None):
decode_content = self._decode_content
if (self._fp is None):
return
try:
if (amt is None):
data = self._fp.read()
els... |
'Given an :class:`httplib.HTTPResponse` instance ``r``, return a
corresponding :class:`urllib3.response.HTTPResponse` object.
Remaining parameters are passed to the HTTPResponse constructor, along
with ``original_response=r``.'
| @classmethod
def from_httplib(ResponseCls, r, **response_kw):
| headers = {}
for (k, v) in r.getheaders():
k = k.lower()
has_value = headers.get(k)
if has_value:
v = ', '.join([has_value, v])
headers[k] = v
strict = getattr(r, 'strict', 0)
return ResponseCls(body=r, headers=headers, status=r.status, version=r.version, r... |
'Get a :class:`ConnectionPool` based on the host, port, and scheme.
Note that an appropriate ``port`` value is required here to normalize
connection pools in our container most effectively.'
| def connection_from_host(self, host, port=80, scheme='http'):
| pool_key = (scheme, host, port)
pool = self.pools.get(pool_key)
if pool:
return pool
pool_cls = pool_classes_by_scheme[scheme]
pool = pool_cls(host, port, **self.connection_pool_kw)
self.pools[pool_key] = pool
return pool
|
'Similar to :func:`urllib3.connectionpool.connection_from_url` but
doesn\'t pass any additional parameters to the
:class:`urllib3.connectionpool.ConnectionPool` constructor.
Additional parameters are taken from the :class:`.PoolManager`
constructor.'
| def connection_from_url(self, url):
| (scheme, host, port) = get_host(url)
port = (port or port_by_scheme.get(scheme, 80))
return self.connection_from_host(host, port=port, scheme=scheme)
|
'Same as :meth:`urllib3.connectionpool.HTTPConnectionPool.urlopen`.
``url`` must be absolute, such that an appropriate
:class:`urllib3.connectionpool.ConnectionPool` can be chosen for it.'
| def urlopen(self, method, url, **kw):
| conn = self.connection_from_url(url)
try:
return conn.urlopen(method, url, **kw)
except HostChangedError as e:
kw['retries'] = e.retries
return self.urlopen(method, e.url, **kw)
|
'Same as HTTP(S)ConnectionPool.urlopen, ``url`` must be absolute.'
| def urlopen(self, method, url, **kw):
| kw['assert_same_host'] = False
kw['headers'] = self._set_proxy_headers(kw.get('headers'))
return self.proxy_pool.urlopen(method, url, **kw)
|
'If exists: Invalidate old entry and return it.'
| def _invalidate_entry(self, key):
| old_entry = self.access_lookup.get(key)
if old_entry:
old_entry.is_valid = False
return old_entry
|
'Push entry onto our access log, invalidate the old entry if exists.'
| def _push_entry(self, key):
| self._invalidate_entry(key)
new_entry = AccessEntry(key)
self.access_lookup[key] = new_entry
self.access_log_lock.acquire()
self.access_log.appendleft(new_entry)
self.access_log_lock.release()
|
'Pop entries from our access log until we popped ``num`` valid ones.'
| def _prune_entries(self, num):
| while (num > 0):
self.access_log_lock.acquire()
p = self.access_log.pop()
self.access_log_lock.release()
if (not p.is_valid):
continue
dict.pop(self, p.key, None)
self.access_lookup.pop(p.key, None)
num -= 1
|
'Rebuild our access_log without the invalidated entries.'
| def _prune_invalidated_entries(self):
| self.access_log_lock.acquire()
self.access_log = deque((e for e in self.access_log if e.is_valid))
self.access_log_lock.release()
|
'Return ordered access keys for inspection. Used for testing.'
| def _get_ordered_access_keys(self):
| self.access_log_lock.acquire()
r = [e.key for e in self.access_log if e.is_valid]
self.access_log_lock.release()
return r
|
'Return a fresh :class:`httplib.HTTPConnection`.'
| def _new_conn(self):
| self.num_connections += 1
log.info(('Starting new HTTP connection (%d): %s' % (self.num_connections, self.host)))
return HTTPConnection(host=self.host, port=self.port)
|
'Get a connection. Will return a pooled connection if one is available.
If no connections are available and :prop:`.block` is ``False``, then a
fresh connection is returned.
:param timeout:
Seconds to wait before giving up and raising
:class:`urllib3.exceptions.EmptyPoolError` if the pool is empty and
:prop:`.block` is... | def _get_conn(self, timeout=None):
| conn = None
try:
conn = self.pool.get(block=self.block, timeout=timeout)
if (conn and is_connection_dropped(conn)):
log.info(('Resetting dropped connection: %s' % self.host))
conn.close()
except Empty:
if self.block:
raise EmptyPoolError(s... |
'Put a connection back into the pool.
:param conn:
Connection object for the current host and port as returned by
:meth:`._new_conn` or :meth:`._get_conn`.
If the pool is already full, the connection is discarded because we
exceeded maxsize. If connections are discarded frequently, then maxsize
should be increased.'
| def _put_conn(self, conn):
| try:
self.pool.put(conn, block=False)
except Full:
log.warning(('HttpConnectionPool is full, discarding connection: %s' % self.host))
|
'Perform a request on a given httplib connection object taken from our
pool.'
| def _make_request(self, conn, method, url, timeout=_Default, **httplib_request_kw):
| self.num_requests += 1
if (timeout is _Default):
timeout = self.timeout
conn.timeout = timeout
conn.request(method, url, **httplib_request_kw)
sock = getattr(conn, 'sock', False)
if sock:
sock.settimeout(timeout)
httplib_response = conn.getresponse()
log.debug(('"%s %s... |
'Check if the given ``url`` is a member of the same host as this
connection pool.'
| def is_same_host(self, url):
| (scheme, host, port) = get_host(url)
if (self.port and (not port)):
port = port_by_scheme.get(scheme)
return (url.startswith('/') or ((scheme, host, port) == (self.scheme, self.host, self.port)))
|
'Get a connection from the pool and perform an HTTP request. This is the
lowest level call for making a request, so you\'ll need to specify all
the raw details.
.. note::
More commonly, it\'s appropriate to use a convenience method provided
by :class:`.RequestMethods`, such as :meth:`request`.
.. note::
`release_conn` ... | def urlopen(self, method, url, body=None, headers=None, retries=3, redirect=True, assert_same_host=True, timeout=_Default, pool_timeout=None, release_conn=None, **response_kw):
| if (headers is None):
headers = self.headers
if (retries < 0):
raise MaxRetryError(self, url)
if (timeout is _Default):
timeout = self.timeout
if (release_conn is None):
release_conn = response_kw.get('preload_content', True)
if (assert_same_host and (not self.is_same... |
'Return a fresh :class:`httplib.HTTPSConnection`.'
| def _new_conn(self):
| self.num_connections += 1
log.info(('Starting new HTTPS connection (%d): %s' % (self.num_connections, self.host)))
if (not ssl):
if ((not HTTPSConnection) or (HTTPSConnection is object)):
raise SSLError("Can't connect to HTTPS URL because the SSL mo... |
'authurl is a random URL on the server that is protected by NTLM.
user is the Windows user, probably in the DOMAIN\username format.
pw is the password for the user.'
| def __init__(self, user, pw, authurl, *args, **kwargs):
| super(NTLMConnectionPool, self).__init__(*args, **kwargs)
self.authurl = authurl
self.rawuser = user
user_parts = user.split('\\', 1)
self.domain = user_parts[0].upper()
self.user = user_parts[1]
self.pw = pw
|
'Make a request using :meth:`urlopen` with the appropriate encoding of
``fields`` based on the ``method`` used.
This is a convenience method that requires the least amount of manual
effort. It can be used in most situations, while still having the option
to drop down to more specific methods when necessary, such as
:me... | def request(self, method, url, fields=None, headers=None, **urlopen_kw):
| method = method.upper()
if (method in self._encode_url_methods):
return self.request_encode_url(method, url, fields=fields, headers=headers, **urlopen_kw)
else:
return self.request_encode_body(method, url, fields=fields, headers=headers, **urlopen_kw)
|
'Make a request using :meth:`urlopen` with the ``fields`` encoded in
the url. This is useful for request methods like GET, HEAD, DELETE, etc.'
| def request_encode_url(self, method, url, fields=None, **urlopen_kw):
| if fields:
url += ('?' + urlencode(fields))
return self.urlopen(method, url, **urlopen_kw)
|
'Make a request using :meth:`urlopen` with the ``fields`` encoded in
the body. This is useful for request methods like POST, PUT, PATCH, etc.
When ``encode_multipart=True`` (default), then
:meth:`urllib3.filepost.encode_multipart_formdata` is used to encode the
payload with the appropriate content type. Otherwise
:meth... | def request_encode_body(self, method, url, fields=None, headers=None, encode_multipart=True, multipart_boundary=None, **urlopen_kw):
| if encode_multipart:
(body, content_type) = encode_multipart_formdata((fields or {}), boundary=multipart_boundary)
else:
(body, content_type) = (urlencode((fields or {})), 'application/x-www-form-urlencoded')
headers = (headers or {})
headers.update({'Content-Type': content_type})
re... |
'return a list of connected hosts and the number of connections
to each. [(\'foo.com:80\', 2), (\'bar.org\', 1)]'
| def open_connections(self):
| return [(host, len(li)) for (host, li) in self._cm.get_all().items()]
|
'close connection(s) to <host>
host is the host:port spec, as in \'www.cnn.com:8080\' as passed in.
no error occurs if there is no connection to that host.'
| def close_connection(self, host):
| for h in self._cm.get_all(host):
self._cm.remove(h)
h.close()
|
'close all open connections'
| def close_all(self):
| for (host, conns) in self._cm.get_all().items():
for h in conns:
self._cm.remove(h)
h.close()
|
'tells us that this request is now closed and the the
connection is ready for another request'
| def _request_closed(self, request, host, connection):
| self._cm.set_ready(connection, 1)
|
'start the transaction with a re-used connection
return a response object (r) upon success or None on failure.
This DOES not close or remove bad connections in cases where
it returns. However, if an unexpected exception occurs, it
will close and remove the connection before re-raising.'
| def _reuse_connection(self, h, req, host):
| try:
self._start_transaction(h, req)
r = h.getresponse()
except (socket.error, httplib.HTTPException):
r = None
except:
if DEBUG:
DEBUG.error(('unexpected exception - closing ' + 'connection to %s (%d)'), host, id(h))
self._cm.remove(h... |
'Create JSON object representing the query from request recieved from Dashboard.
:param request:
:return:'
| def create_from_request(self, request):
| query_json = {'process_type': DVAPQL.QUERY}
count = request.POST.get('count')
excluded = json.loads(request.POST.get('excluded_index_entries'))
selected_indexers = json.loads(request.POST.get('selected_indexers'))
approximate = (True if (request.POST.get('approximate') == 'true') else False)
que... |
'# TODO: speed this up by skipping refreshes when count is unchanged.
:param index_name:
:return:'
| def refresh_index(self, index_name):
| index_entries = IndexEntries.objects.all()
visual_index = self.visual_retriever[index_name]
for index_entry in index_entries:
if ((index_entry.pk not in visual_index.loaded_entries) and (index_entry.algorithm == index_name) and (index_entry.count > 0)):
fname = '{}/{}/indexes/{}'.format(... |
'Construct the network.'
| def setup(self):
| raise NotImplementedError('Must be implemented by the subclass.')
|
'Load network weights.
data_path: The path to the numpy-serialized network weights
session: The current TensorFlow session
ignore_missing: If true, serialized weights for missing layers are ignored.'
| def load(self, data_path, session, ignore_missing=False):
| data_dict = np.load(data_path, encoding='latin1').item()
for op_name in data_dict:
with tf.variable_scope(op_name, reuse=True):
for (param_name, data) in iteritems(data_dict[op_name]):
try:
var = tf.get_variable(param_name)
session.run(... |
'Set the input(s) for the next operation by replacing the terminal nodes.
The arguments can be either layer names or the actual layers.'
| def feed(self, *args):
| assert (len(args) != 0)
self.terminals = []
for fed_layer in args:
if isinstance(fed_layer, string_types):
try:
fed_layer = self.layers[fed_layer]
except KeyError:
raise KeyError(('Unknown layer name fed: %s' % fed_layer))
s... |
'Returns the current network output.'
| def get_output(self):
| return self.terminals[(-1)]
|
'Returns an index-suffixed unique name for the given prefix.
This is used for auto-generating layer names based on the type-prefix.'
| def get_unique_name(self, prefix):
| ident = (sum((t.startswith(prefix) for (t, _) in self.layers.items())) + 1)
return ('%s_%d' % (prefix, ident))
|
'Creates a new TensorFlow variable.'
| def make_var(self, name, shape):
| return tf.get_variable(name, shape, trainable=self.trainable)
|
'Verifies that the padding is one of the supported ones.'
| def validate_padding(self, padding):
| assert (padding in ('SAME', 'VALID'))
|
'Simplify this mess haivng a seperate create vs load/init'
| def __init__(self, fnames, n_components, model_proto_filename, m, v, sub, test_mode=False, dc=None):
| data = []
self.dc = dc
self.fnames = fnames
self.entries = []
for fname in fnames:
nmat = np.load(fname)
if (nmat.ndim > 2):
nmat = nmat.squeeze()
data.append(nmat)
for e in json.load(file(fname.replace('npy', 'json'))):
self.entries.append(e)
... |
'A simple PCA implementation that demonstrates how eigenvalue allocation
is used to permute dimensions in order to balance the variance across
subvectors. There are plenty of PCA implementations elsewhere. What is
important is that the eigenvalues can be used to compute a variance-balancing
dimension permutation.'
| def pca(self):
| (count, D) = self.data.shape
mu = (self.data.sum(axis=0) / float(count))
summed_covar = reduce((lambda acc, x: (acc + np.outer(x, x))), self.data, np.zeros((D, D)))
A = ((summed_covar / (count - 1)) - np.outer(mu, mu))
(eigenvalues, P) = np.linalg.eigh(A)
self.permuted_inds = eigenvalue_allocati... |
'Constructs a SsdInceptionV2FeatureExtractor.
Args:
depth_multiplier: float depth multiplier for feature extractor
Returns:
an ssd_inception_v2_feature_extractor.SsdInceptionV2FeatureExtractor.'
| def _create_feature_extractor(self, depth_multiplier):
| min_depth = 32
conv_hyperparams = {}
return ssd_inception_v2_feature_extractor.SSDInceptionV2FeatureExtractor(depth_multiplier, min_depth, conv_hyperparams)
|
'MobileNetV1 Feature Extractor for SSD Models.
Args:
depth_multiplier: float depth multiplier for feature extractor.
min_depth: minimum feature extractor depth.
conv_hyperparams: tf slim arg_scope for conv2d and separable_conv2d ops.
reuse_weights: Whether to reuse variables. Default is None.'
| def __init__(self, depth_multiplier, min_depth, conv_hyperparams, reuse_weights=None):
| super(SSDMobileNetV1FeatureExtractor, self).__init__(depth_multiplier, min_depth, conv_hyperparams, reuse_weights)
|
'SSD preprocessing.
Maps pixel values to the range [-1, 1].
Args:
resized_inputs: a [batch, height, width, channels] float tensor
representing a batch of images.
Returns:
preprocessed_inputs: a [batch, height, width, channels] float tensor
representing a batch of images.'
| def preprocess(self, resized_inputs):
| return (((2.0 / 255.0) * resized_inputs) - 1.0)
|
'Extract features from preprocessed inputs.
Args:
preprocessed_inputs: a [batch, height, width, channels] float tensor
representing a batch of images.
Returns:
feature_maps: a list of tensors where the ith tensor has shape
[batch, height_i, width_i, depth_i]'
| def extract_features(self, preprocessed_inputs):
| preprocessed_inputs.get_shape().assert_has_rank(4)
shape_assert = tf.Assert(tf.logical_and(tf.greater_equal(tf.shape(preprocessed_inputs)[1], 33), tf.greater_equal(tf.shape(preprocessed_inputs)[2], 33)), ['image size must at least be 33 in both height and width.'])
feature_m... |
'Constructs a new feature extractor.
Args:
depth_multiplier: float depth multiplier for feature extractor
Returns:
an ssd_meta_arch.SSDFeatureExtractor object.'
| def _create_feature_extractor(self, depth_multiplier):
| min_depth = 32
conv_hyperparams = {}
return ssd_mobilenet_v1_feature_extractor.SSDMobileNetV1FeatureExtractor(depth_multiplier, min_depth, conv_hyperparams)
|
'Constructor.
Args:
architecture: Architecture name of the Resnet V1 model.
resnet_model: Definition of the Resnet V1 model.
is_training: See base class.
first_stage_features_stride: See base class.
reuse_weights: See base class.
weight_decay: See base class.
Raises:
ValueError: If `first_stage_features_stride` is not ... | def __init__(self, architecture, resnet_model, is_training, first_stage_features_stride, reuse_weights=None, weight_decay=0.0):
| if ((first_stage_features_stride != 8) and (first_stage_features_stride != 16)):
raise ValueError('`first_stage_features_stride` must be 8 or 16.')
self._architecture = architecture
self._resnet_model = resnet_model
super(FasterRCNNResnetV1FeatureExtractor, self).__init__(is_train... |
'Faster R-CNN Resnet V1 preprocessing.
VGG style channel mean subtraction as described here:
https://gist.github.com/ksimonyan/211839e770f7b538e2d8#file-readme-md
Args:
resized_inputs: A [batch, height_in, width_in, channels] float32 tensor
representing a batch of images with values between 0 and 255.0.
Returns:
prepro... | def preprocess(self, resized_inputs):
| channel_means = [123.68, 116.779, 103.939]
return (resized_inputs - [[channel_means]])
|
'Extracts first stage RPN features.
Args:
preprocessed_inputs: A [batch, height, width, channels] float32 tensor
representing a batch of images.
scope: A scope name.
Returns:
rpn_feature_map: A tensor with shape [batch, height, width, depth]
Raises:
InvalidArgumentError: If the spatial size of `preprocessed_inputs`
(he... | def _extract_proposal_features(self, preprocessed_inputs, scope):
| if (len(preprocessed_inputs.get_shape().as_list()) != 4):
raise ValueError(('`preprocessed_inputs` must be 4 dimensional, got a tensor of shape %s' % preprocessed_inputs.get_shape()))
shape_assert = tf.Assert(tf.logical_and(tf.greater_equal(tf.shape(preprocessed_inputs)[1],... |
'Extracts second stage box classifier features.
Args:
proposal_feature_maps: A 4-D float tensor with shape
[batch_size * self.max_num_proposals, crop_height, crop_width, depth]
representing the feature map cropped to each proposal.
scope: A scope name (unused).
Returns:
proposal_classifier_features: A 4-D float tensor ... | def _extract_box_classifier_features(self, proposal_feature_maps, scope):
| with tf.variable_scope(self._architecture, reuse=self._reuse_weights):
with slim.arg_scope(resnet_utils.resnet_arg_scope(batch_norm_epsilon=1e-05, batch_norm_scale=True, weight_decay=self._weight_decay)):
with slim.arg_scope([slim.batch_norm], is_training=False):
blocks = [resnet... |
'Constructor.
Args:
is_training: See base class.
first_stage_features_stride: See base class.
reuse_weights: See base class.
weight_decay: See base class.
Raises:
ValueError: If `first_stage_features_stride` is not 8 or 16,
or if `architecture` is not supported.'
| def __init__(self, is_training, first_stage_features_stride, reuse_weights=None, weight_decay=0.0):
| super(FasterRCNNResnet50FeatureExtractor, self).__init__('resnet_v1_50', resnet_v1.resnet_v1_50, is_training, first_stage_features_stride, reuse_weights, weight_decay)
|
'Constructor.
Args:
is_training: See base class.
first_stage_features_stride: See base class.
reuse_weights: See base class.
weight_decay: See base class.
Raises:
ValueError: If `first_stage_features_stride` is not 8 or 16,
or if `architecture` is not supported.'
| def __init__(self, is_training, first_stage_features_stride, reuse_weights=None, weight_decay=0.0):
| super(FasterRCNNResnet101FeatureExtractor, self).__init__('resnet_v1_101', resnet_v1.resnet_v1_101, is_training, first_stage_features_stride, reuse_weights, weight_decay)
|
'Constructor.
Args:
is_training: See base class.
first_stage_features_stride: See base class.
reuse_weights: See base class.
weight_decay: See base class.
Raises:
ValueError: If `first_stage_features_stride` is not 8 or 16,
or if `architecture` is not supported.'
| def __init__(self, is_training, first_stage_features_stride, reuse_weights=None, weight_decay=0.0):
| super(FasterRCNNResnet152FeatureExtractor, self).__init__('resnet_v1_152', resnet_v1.resnet_v1_152, is_training, first_stage_features_stride, reuse_weights, weight_decay)
|
'InceptionV2 Feature Extractor for SSD Models.
Args:
depth_multiplier: float depth multiplier for feature extractor.
min_depth: minimum feature extractor depth.
conv_hyperparams: tf slim arg_scope for conv2d and separable_conv2d ops.
reuse_weights: Whether to reuse variables. Default is None.'
| def __init__(self, depth_multiplier, min_depth, conv_hyperparams, reuse_weights=None):
| super(SSDInceptionV2FeatureExtractor, self).__init__(depth_multiplier, min_depth, conv_hyperparams, reuse_weights)
|
'SSD preprocessing.
Maps pixel values to the range [-1, 1].
Args:
resized_inputs: a [batch, height, width, channels] float tensor
representing a batch of images.
Returns:
preprocessed_inputs: a [batch, height, width, channels] float tensor
representing a batch of images.'
| def preprocess(self, resized_inputs):
| return (((2.0 / 255.0) * resized_inputs) - 1.0)
|
'Extract features from preprocessed inputs.
Args:
preprocessed_inputs: a [batch, height, width, channels] float tensor
representing a batch of images.
Returns:
feature_maps: a list of tensors where the ith tensor has shape
[batch, height_i, width_i, depth_i]'
| def extract_features(self, preprocessed_inputs):
| preprocessed_inputs.get_shape().assert_has_rank(4)
shape_assert = tf.Assert(tf.logical_and(tf.greater_equal(tf.shape(preprocessed_inputs)[1], 33), tf.greater_equal(tf.shape(preprocessed_inputs)[2], 33)), ['image size must at least be 33 in both height and width.'])
feature_m... |
'Checks the extracted features are of correct shape.
Args:
feature_extractor: The feature extractor to test.
preprocessed_inputs: A [batch, height, width, 3] tensor to extract
features with.
expected_feature_map_shapes: The expected shape of the extracted features.'
| def _validate_features_shape(self, feature_extractor, preprocessed_inputs, expected_feature_map_shapes):
| feature_maps = feature_extractor.extract_features(preprocessed_inputs)
feature_map_shapes = [tf.shape(feature_map) for feature_map in feature_maps]
init_op = tf.global_variables_initializer()
with self.test_session() as sess:
sess.run(init_op)
feature_map_shapes_out = sess.run(feature_ma... |
'Constructs a new feature extractor.
Args:
depth_multiplier: float depth multiplier for feature extractor
Returns:
an ssd_meta_arch.SSDFeatureExtractor object.'
| @abstractmethod
def _create_feature_extractor(self, depth_multiplier):
| pass
|
'Constructor.
Args:
is_training: See base class.
first_stage_features_stride: See base class.
reuse_weights: See base class.
weight_decay: See base class.
Raises:
ValueError: If `first_stage_features_stride` is not 8 or 16.'
| def __init__(self, is_training, first_stage_features_stride, reuse_weights=None, weight_decay=0.0):
| if ((first_stage_features_stride != 8) and (first_stage_features_stride != 16)):
raise ValueError('`first_stage_features_stride` must be 8 or 16.')
super(FasterRCNNInceptionResnetV2FeatureExtractor, self).__init__(is_training, first_stage_features_stride, reuse_weights, weight_decay)
|
'Faster R-CNN with Inception Resnet v2 preprocessing.
Maps pixel values to the range [-1, 1].
Args:
resized_inputs: A [batch, height_in, width_in, channels] float32 tensor
representing a batch of images with values between 0 and 255.0.
Returns:
preprocessed_inputs: A [batch, height_out, width_out, channels] float32
ten... | def preprocess(self, resized_inputs):
| return (((2.0 / 255.0) * resized_inputs) - 1.0)
|
'Extracts first stage RPN features.
Extracts features using the first half of the Inception Resnet v2 network.
We construct the network in `align_feature_maps=True` mode, which means
that all VALID paddings in the network are changed to SAME padding so that
the feature maps are aligned.
Args:
preprocessed_inputs: A [ba... | def _extract_proposal_features(self, preprocessed_inputs, scope):
| if (len(preprocessed_inputs.get_shape().as_list()) != 4):
raise ValueError(('`preprocessed_inputs` must be 4 dimensional, got a tensor of shape %s' % preprocessed_inputs.get_shape()))
with slim.arg_scope(inception_resnet_v2.inception_resnet_v2_arg_scope(weight_decay=self._w... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.