code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
# If we're already waiting on an/some outstanding disconnects # make sure we continue to wait for them... log.debug("%r: close", self) self._closing = True # Close down any clients we have brokerclients, self.clients = self.clients, None self._close_broke...
def close(self)
Permanently dispose of the client - Immediately mark the client as closed, causing current operations to fail with :exc:`~afkak.common.CancelledError` and future operations to fail with :exc:`~afkak.common.ClientError`. - Clear cached metadata. - Close any connections to Kaf...
12.649477
12.638518
1.000867
topics = tuple(_coerce_topic(t) for t in topics) log.debug("%r: load_metadata_for_topics(%s)", self, ', '.join(repr(t) for t in topics)) fetch_all_metadata = not topics # create the request requestId = self._next_id() request = KafkaCodec.encode_metadata_request...
def load_metadata_for_topics(self, *topics)
Discover topic metadata and brokers Afkak internally calls this method whenever metadata is required. :param str topics: Topic names to look up. The resulting metadata includes the list of topic partitions, brokers owning those partitions, and which partitions are i...
4.519485
4.418212
1.022922
group = _coerce_consumer_group(group) log.debug("%r: load_consumer_metadata_for_group(%r)", self, group) # If we are already loading the metadata for this group, then # just return the outstanding deferred if group in self.coordinator_fetches: d = defer.Defe...
def load_consumer_metadata_for_group(self, group)
Determine broker for the consumer metadata for the specified group Returns a deferred which callbacks with True if the group's coordinator could be determined, or errbacks with ConsumerCoordinatorNotAvailableError if not. Parameters ---------- group: group n...
3.982506
3.842242
1.036506
encoder = partial( KafkaCodec.encode_produce_request, acks=acks, timeout=timeout) if acks == 0: decoder = None else: decoder = KafkaCodec.decode_produce_response resps = yield self._send_broker_aware_request( ...
def send_produce_request(self, payloads=None, acks=1, timeout=DEFAULT_REPLICAS_ACK_MSECS, fail_on_error=True, callback=None)
Encode and send some ProduceRequests ProduceRequests will be grouped by (topic, partition) and then sent to a specific broker. Output is a list of responses in the same order as the list of payloads specified Parameters ---------- payloads: list of ProduceRe...
3.821197
4.54659
0.840453
if (max_wait_time / 1000) > (self.timeout - 0.1): raise ValueError( "%r: max_wait_time: %d must be less than client.timeout by " "at least 100 milliseconds.", self, max_wait_time) encoder = partial(KafkaCodec.encode_fetch_request, ...
def send_fetch_request(self, payloads=None, fail_on_error=True, callback=None, max_wait_time=DEFAULT_FETCH_SERVER_WAIT_MSECS, min_bytes=DEFAULT_FETCH_MIN_BYTES)
Encode and send a FetchRequest Payloads are grouped by topic and partition so they can be pipelined to the same brokers. Raises ====== FailedPayloadsError, LeaderUnavailableError, PartitionUnavailableError
4.641526
4.567288
1.016254
encoder = partial(KafkaCodec.encode_offset_fetch_request, group=group) decoder = KafkaCodec.decode_offset_fetch_response resps = yield self._send_broker_aware_request( payloads, encoder, decoder, consumer_group=group) returnValue(self._hand...
def send_offset_fetch_request(self, group, payloads=None, fail_on_error=True, callback=None)
Takes a group (string) and list of OffsetFetchRequest and returns a list of OffsetFetchResponse objects
4.75981
4.953605
0.960878
group = _coerce_consumer_group(group) encoder = partial(KafkaCodec.encode_offset_commit_request, group=group, group_generation_id=group_generation_id, consumer_id=consumer_id) decoder = KafkaCodec.decode_offset_commit_response ...
def send_offset_commit_request(self, group, payloads=None, fail_on_error=True, callback=None, group_generation_id=-1, consumer_id='')
Send a list of OffsetCommitRequests to the Kafka broker for the given consumer group. Args: group (str): The consumer group to which to commit the offsets payloads ([OffsetCommitRequest]): List of topic, partition, offsets to commit. fail_on_error (bool): Wheth...
3.608326
4.057764
0.88924
if self._closing: raise ClientError("Cannot get broker client for node_id={}: {} has been closed".format(node_id, self)) if node_id not in self.clients: broker_metadata = self._brokers[node_id] log.debug("%r: creating client for %s", self, broker_metadata) ...
def _get_brokerclient(self, node_id)
Get a broker client. :param int node_id: Broker node ID :raises KeyError: for an unknown node ID :returns: :class:`_KafkaBrokerClient`
3.887404
3.640951
1.067689
def _log_close_failure(failure, brokerclient): log.debug( 'BrokerClient: %s close result: %s: %s', brokerclient, failure.type.__name__, failure.getErrorMessage()) def _clean_close_dlist(result, close_dlist): # If there aren't any other ou...
def _close_brokerclients(self, clients)
Close the given broker clients. :param clients: Iterable of `_KafkaBrokerClient`
3.221581
3.361144
0.958478
log.debug("%r: _update_brokers(%r, remove=%r)", self, brokers, remove) brokers_by_id = {bm.node_id: bm for bm in brokers} self._brokers.update(brokers_by_id) # Update the metadata of broker clients that already exist. for node_id, broker_meta in broker...
def _update_brokers(self, brokers, remove=False)
Update `self._brokers` and `self.clients` Update our self.clients based on brokers in received metadata Take the received dict of brokers and reconcile it with our current list of brokers (self.clients). If there is a new one, bring up a new connection to it, and if remove is True, and ...
2.842386
2.589721
1.097564
key = TopicAndPartition(topic, partition) # reload metadata whether the partition is not available # or has no leader (broker is None) if self.topics_to_brokers.get(key) is None: yield self.load_metadata_for_topics(topic) if key not in self.topics_to_broker...
def _get_leader_for_partition(self, topic, partition)
Returns the leader for a partition or None if the partition exists but has no leader. PartitionUnavailableError will be raised if the topic or partition is not part of the metadata.
5.435142
4.770844
1.139241
if self.consumer_group_to_brokers.get(consumer_group) is None: yield self.load_consumer_metadata_for_group(consumer_group) returnValue(self.consumer_group_to_brokers.get(consumer_group))
def _get_coordinator_for_group(self, consumer_group)
Returns the coordinator (broker) for a consumer group Returns the broker for a given consumer group or Raises ConsumerCoordinatorNotAvailableError
3.899415
3.777193
1.032358
def _timeout_request(broker, requestId): try: # FIXME: This should be done by calling .cancel() on the Deferred # returned by the broker client. broker.cancelRequest(requestId, reason=RequestTimedOutError( 'Req...
def _make_request_to_broker(self, broker, requestId, request, **kwArgs)
Send a request to the specified broker.
4.953167
4.890821
1.012748
node_ids = list(self._brokers.keys()) # Randomly shuffle the brokers to distribute the load random.shuffle(node_ids) # Prioritize connected brokers def connected(node_id): try: return self.clients[node_id].connected() except KeyEr...
def _send_broker_unaware_request(self, requestId, request)
Attempt to send a broker-agnostic request to one of the known brokers: 1. Try each connected broker (in random order) 2. Try each known but unconnected broker (in random order) 3. Try each of the bootstrap hosts (in random order) :param bytes request: The bytes of a Kafka `...
5.327105
5.042294
1.056484
hostports = list(self._bootstrap_hosts) random.shuffle(hostports) for host, port in hostports: ep = self._endpoint_factory(self.reactor, host, port) try: protocol = yield ep.connect(_bootstrapFactory) except Exception as e: ...
def _send_bootstrap_request(self, request)
Make a request using an ephemeral broker connection This routine is used to make broker-unaware requests to get the initial cluster metadata. It cycles through the configured hosts, trying to connect and send the request to each in turn. This temporary connection is closed once a respon...
3.35803
3.196571
1.05051
descripter = ExpressionDescriptor(expression, options) return descripter.get_description(DescriptionTypeEnum.FULL)
def get_description(expression, options=None)
Generates a human readable string for the Cron Expression Args: expression: The cron expression string options: Options to control the output description Returns: The cron expression description
10.10568
14.089204
0.717264
try: if self._parsed is False: parser = ExpressionParser(self._expression, self._options) self._expression_parts = parser.parse() self._parsed = True choices = { DescriptionTypeEnum.FULL: self.get_full_description,...
def get_description(self, description_type=DescriptionTypeEnum.FULL)
Generates a human readable string for the Cron Expression Args: description_type: Which part(s) of the expression to describe Returns: The cron expression description Raises: Exception: if throw_exception_on_parse_error is True
2.122979
1.832478
1.158529
try: time_segment = self.get_time_of_day_description() day_of_month_desc = self.get_day_of_month_description() month_desc = self.get_month_description() day_of_week_desc = self.get_day_of_week_description() year_desc = self.get_year_descripti...
def get_full_description(self)
Generates the FULL description Returns: The FULL description Raises: FormatException: if formating fails and throw_exception_on_parse_error is True
3.25047
2.81008
1.156718
seconds_expression = self._expression_parts[0] minute_expression = self._expression_parts[1] hour_expression = self._expression_parts[2] description = StringBuilder() # handle special cases first if any(exp in minute_expression for exp in self._special_characte...
def get_time_of_day_description(self)
Generates a description for only the TIMEOFDAY portion of the expression Returns: The TIMEOFDAY description
2.447194
2.469211
0.991083
return self.get_segment_description( self._expression_parts[0], _("every second"), lambda s: s, lambda s: _("every {0} seconds").format(s), lambda s: _("seconds {0} through {1} past the minute"), lambda s: _("at {0} seconds past t...
def get_seconds_description(self)
Generates a description for only the SECONDS portion of the expression Returns: The SECONDS description
6.297512
5.665463
1.111562
return self.get_segment_description( self._expression_parts[1], _("every minute"), lambda s: s, lambda s: _("every {0} minutes").format(s), lambda s: _("minutes {0} through {1} past the hour"), lambda s: '' if s == "0" else _("at ...
def get_minutes_description(self)
Generates a description for only the MINUTE portion of the expression Returns: The MINUTE description
6.657679
5.897062
1.128982
expression = self._expression_parts[2] return self.get_segment_description( expression, _("every hour"), lambda s: self.format_time(s, "0"), lambda s: _("every {0} hours").format(s), lambda s: _("between {0} and {1}"), lamb...
def get_hours_description(self)
Generates a description for only the HOUR portion of the expression Returns: The HOUR description
4.995983
5.456813
0.91555
if self._expression_parts[5] == "*" and self._expression_parts[3] != "*": # DOM is specified and DOW is * so to prevent contradiction like "on day 1 of the month, every day" # we will not specified a DOW description. return "" def get_day_name(s): ...
def get_day_of_week_description(self)
Generates a description for only the DAYOFWEEK portion of the expression Returns: The DAYOFWEEK description
3.747551
3.696458
1.013822
return self.get_segment_description( self._expression_parts[4], '', lambda s: datetime.date(datetime.date.today().year, int(s), 1).strftime("%B"), lambda s: _(", every {0} months").format(s), lambda s: _(", {0} through {1}"), lambd...
def get_month_description(self)
Generates a description for only the MONTH portion of the expression Returns: The MONTH description
6.048262
5.959369
1.014917
expression = self._expression_parts[3] expression = expression.replace("?", "*") if expression == "L": description = _(", on the last day of the month") elif expression == "LW" or expression == "WL": description = _(", on the last weekday of the month") ...
def get_day_of_month_description(self)
Generates a description for only the DAYOFMONTH portion of the expression Returns: The DAYOFMONTH description
3.281713
3.385772
0.969266
def format_year(s): regex = re.compile(r"^\d+$") if regex.match(s): year_int = int(s) if year_int < 1900: return year_int return datetime.date(year_int, 1, 1).strftime("%Y") else: re...
def get_year_description(self)
Generates a description for only the YEAR portion of the expression Returns: The YEAR description
4.000232
3.852698
1.038294
description = None if expression is None or expression == '': description = '' elif expression == "*": description = all_description elif any(ext in expression for ext in ['/', '-', ',']) is False: description = get_description_format(expressi...
def get_segment_description( self, expression, all_description, get_single_item_description, get_interval_description_format, get_between_description_format, get_description_format )
Returns segment description Args: expression: Segment to descript all_description: * get_single_item_description: 1 get_interval_description_format: 1/2 get_between_description_format: 1-2 get_description_format: format get_single_item_desc...
2.411245
2.412489
0.999484
description = "" between_segments = between_expression.split('-') between_segment_1_description = get_single_item_description(between_segments[0]) between_segment_2_description = get_single_item_description(between_segments[1]) between_segment_2_description = between_seg...
def generate_between_segment_description( self, between_expression, get_between_description_format, get_single_item_description )
Generates the between segment description :param between_expression: :param get_between_description_format: :param get_single_item_description: :return: The between segment description
2.059759
2.117849
0.972571
hour = int(hour_expression) period = '' if self._options.use_24hour_time_format is False: period = " PM" if (hour >= 12) else " AM" if hour > 12: hour -= 12 minute = str(int(minute_expression)) # !FIXME WUT ??? second = '' ...
def format_time( self, hour_expression, minute_expression, second_expression='' )
Given time parts, will contruct a formatted time description Args: hour_expression: Hours part minute_expression: Minutes part second_expression: Seconds part Returns: Formatted time description
3.520932
3.702982
0.950837
if use_verbose_format is False: description = description.replace( _(", every minute"), '') description = description.replace(_(", every hour"), '') description = description.replace(_(", every day"), '') return description
def transform_verbosity(self, description, use_verbose_format)
Transforms the verbosity of the expression description by stripping verbosity from original description Args: description: The description to transform use_verbose_format: If True, will leave description as it, if False, will strip verbose parts second_expression: Seconds par...
4.293999
4.824533
0.890034
if case_type == CasingTypeEnum.Sentence: description = "{}{}".format( description[0].upper(), description[1:]) elif case_type == CasingTypeEnum.Title: description = description.title() else: description = description.lo...
def transform_case(self, description, case_type)
Transforms the case of the expression description, based on options Args: description: The description to transform case_type: The casing type that controls the output casing second_expression: Seconds part Returns: The transformed description with proper ...
3.541681
3.030559
1.168656
return [ calendar.day_name[6], calendar.day_name[0], calendar.day_name[1], calendar.day_name[2], calendar.day_name[3], calendar.day_name[4], calendar.day_name[5] ][day_number]
def number_to_day(self, day_number)
Returns localized day name by its CRON number Args: day_number: Number of a day Returns: Day corresponding to day_number Raises: IndexError: When day_number is not found
1.819823
2.083226
0.87356
# Have we been started already, and not stopped? if self._start_d is not None: raise RestartError("Start called on already-started consumer") # Keep track of state for debugging self._state = '[started]' # Create and return a deferred for alerting on errors...
def start(self, start_offset)
Starts fetching messages from Kafka and delivering them to the :attr:`.processor` function. :param int start_offset: The offset within the partition from which to start fetching. Special values include: :const:`OFFSET_EARLIEST`, :const:`OFFSET_LATEST`, and :const:`OF...
4.843915
4.422919
1.095185
def _handle_shutdown_commit_success(result): self._shutdown_d, d = None, self._shutdown_d self.stop() self._shuttingdown = False # Shutdown complete d.callback((self._last_processed_offset, self._last_committed_offset)...
def shutdown(self)
Gracefully shutdown the consumer Consumer will complete any outstanding processing, commit its current offsets (if so configured) and stop. Returns deferred which callbacks with a tuple of: (last processed offset, last committed offset) if it was able to successfully commit, or...
4.166119
3.672454
1.134424
if self._start_d is None: raise RestopError("Stop called on non-running consumer") self._stopping = True # Keep track of state for debugging self._state = '[stopping]' # Are we waiting for a request to come back? if self._request_d: self....
def stop(self)
Stop the consumer and return offset of last processed message. This cancels all outstanding operations. Also, if the deferred returned by `start` hasn't been called, it is called with a tuple consisting of the last processed offset and the last committed offset. :raises: :exc:`RestopE...
3.602508
3.119198
1.154947
# Can't commit without a consumer_group if not self.consumer_group: return fail(Failure(InvalidConsumerGroupError( "Bad Group_id:{0!r}".format(self.consumer_group)))) # short circuit if we are 'up to date', or haven't processed anything if ((self._las...
def commit(self)
Commit the offset of the message we last processed if it is different from what we believe is the last offset committed to Kafka. .. note:: It is possible to commit a smaller offset than Kafka has stored. This is by design, so we can reprocess a Kafka message stream if ...
5.812636
5.061138
1.148484
# Check if we are even supposed to do any auto-committing if (self._stopping or self._shuttingdown or (not self._start_d) or (self._last_processed_offset is None) or (not self.consumer_group) or (by_count and not self.auto_commit_every_n)): ...
def _auto_commit(self, by_count=False)
Check if we should start a new commit operation and commit
4.209057
4.185456
1.005639
# Have we been told to stop or shutdown? Then don't actually retry. if self._stopping or self._shuttingdown or self._start_d is None: # Stopping, or stopped already? No more fetching. return if self._retry_call is None: if after is None: ...
def _retry_fetch(self, after=None)
Schedule a delayed :meth:`_do_fetch` call after a failure :param float after: The delay in seconds after which to do the retried fetch. If `None`, our internal :attr:`retry_delay` is used, and adjusted by :const:`REQUEST_RETRY_FACTOR`.
5.378815
4.648486
1.157111
# Got a response, clear our outstanding request deferred self._request_d = None # Successful request, reset our retry delay, count, etc self.retry_delay = self.retry_init_delay self._fetch_attempt_count = 1 response = response[0] if hasattr(response, 'o...
def _handle_offset_response(self, response)
Handle responses to both OffsetRequest and OffsetFetchRequest, since they are similar enough. :param response: A tuple of a single OffsetFetchResponse or OffsetResponse
5.559131
5.209544
1.067105
# outstanding request got errback'd, clear it self._request_d = None if self._stopping and failure.check(CancelledError): # Not really an error return # Do we need to abort? if (self.request_retry_max_attempts != 0 and self._fetch...
def _handle_offset_error(self, failure)
Retry the offset fetch request if appropriate. Once the :attr:`.retry_delay` reaches our :attr:`.retry_max_delay`, we log a warning. This should perhaps be extended to abort sooner on certain errors.
5.496176
5.023037
1.094194
# If there's a _commit_call, and it's not active, clear it, it probably # just called us... if self._commit_call and not self._commit_call.active(): self._commit_call = None # Make sure we only have one outstanding commit request at a time if self._commit_re...
def _send_commit_request(self, retry_delay=None, attempt=None)
Send a commit request with our last_processed_offset
3.740995
3.561855
1.050294
# Check if we are stopping and the request was cancelled if self._stopping and failure.check(CancelledError): # Not really an error return self._deliver_commit_result(self._last_committed_offset) # Check that the failure type is a Kafka error...this could maybe ...
def _handle_commit_error(self, failure, retry_delay, attempt)
Retry the commit request, depending on failure type Depending on the type of the failure, we retry the commit request with the latest processed offset, or callback/errback self._commit_ds
5.260506
5.257211
1.000627
# Check if we're stopping/stopped and the errback of the processor # deferred is just the cancelling we initiated. If so, we skip # notifying via the _start_d deferred, as it will be 'callback'd at the # end of stop() if not (self._stopping and failure.check(CancelledEr...
def _handle_processor_error(self, failure)
Handle a failure in the processing of a block of messages This method is called when the processor func fails while processing a block of messages. Since we can't know how best to handle a processor failure, we just :func:`errback` our :func:`start` method's deferred to let our user kno...
11.043701
10.882706
1.014794
# The _request_d deferred has fired, clear it. self._request_d = None if failure.check(OffsetOutOfRangeError): if self.auto_offset_reset is None: self._start_d.errback(failure) return self._fetch_offset = self.auto_offset_reset ...
def _handle_fetch_error(self, failure)
A fetch request resulted in an error. Retry after our current delay When a fetch error occurs, we check to see if the Consumer is being stopped, and if so just return, trapping the CancelledError. If not, we check if the Consumer has a non-zero setting for :attr:`request_retry_max_attem...
4.729671
3.955642
1.195677
# Successful fetch, reset our retry delay self.retry_delay = self.retry_init_delay self._fetch_attempt_count = 1 # Check to see if we are still processing the last block we fetched... if self._msg_block_d: # We are still working through the last block of mes...
def _handle_fetch_response(self, responses)
The callback handling the successful response from the fetch request Delivers the message list to the processor, handles per-message errors (ConsumerFetchSizeTooSmall), triggers another fetch request If the processor is still processing the last batch of messages, we defer this process...
5.757731
5.641209
1.020656
# Have we been told to shutdown? if self._shuttingdown: return # Do we have any messages to process? if not messages: # No, we're done with this block. If we had another fetch result # waiting, this callback will trigger the processing thereof...
def _process_messages(self, messages)
Send messages to the `processor` callback to be processed In the case we have a commit policy, we send messages to the processor in blocks no bigger than auto_commit_every_n (if set). Otherwise, we send the entire message block to be processed.
5.270091
4.93671
1.067531
# Check for outstanding request. if self._request_d: log.debug("_do_fetch: Outstanding request: %r", self._request_d) return # Cleanup our _retry_call, if we have one if self._retry_call is not None: if self._retry_call.active(): ...
def _do_fetch(self)
Send a fetch request if there isn't a request outstanding Sends a fetch request to the Kafka cluster to get messages at the current offset. When the response comes back, if there are messages, it delivers them to the :attr:`processor` callback and initiates another fetch request. If t...
3.034919
2.8821
1.053024
log.warning( '_commit_timer_failed: uncaught error %r: %s in _auto_commit', fail, fail.getBriefTraceback()) self._commit_looper_d = self._commit_looper.start( self.auto_commit_every_s, now=False)
def _commit_timer_failed(self, fail)
Handle an error in the commit() function Our commit() function called by the LoopingCall failed. Some error probably came back from Kafka and _check_error() raised the exception For now, just log the failure and restart the loop
8.353142
6.859516
1.217745
if self._commit_looper is not lCall: log.warning('_commit_timer_stopped with wrong timer:%s not:%s', lCall, self._commit_looper) else: log.debug('_commit_timer_stopped: %s %s', lCall, self._commit_looper) self._co...
def _commit_timer_stopped(self, lCall)
We're shutting down, clean up our looping call...
3.216471
3.051546
1.054046
# Ensure byte_array arg is a bytearray if not isinstance(byte_array, bytearray): raise TypeError("Type: %r of 'byte_array' arg must be 'bytearray'", type(byte_array)) length = len(byte_array) # 'm' and 'r' are mixing constants generated offline. # They're not re...
def pure_murmur2(byte_array, seed=0x9747b28c)
Pure-python Murmur2 implementation. Based on java client, see org.apache.kafka.common.utils.Utils.murmur2 https://github.com/apache/kafka/blob/0.8.2/clients/src/main/java/org/apache/kafka/common/utils/Utils.java#L244 Args: byte_array: bytearray - Raises TypeError otherwise Returns: MurmurHash2...
1.670649
1.637852
1.020024
return partitions[(self._hash(key) & 0x7FFFFFFF) % len(partitions)]
def partition(self, key, partitions)
Select a partition based on the hash of the key. :param key: Partition key :type key: text string or UTF-8 `bytes` or `bytearray` :param list partitions: An indexed sequence of partition identifiers. :returns: One of the given partition identifiers. The result wi...
5.204875
5.750541
0.90511
if not has_snappy(): # FIXME This should be static, not checked every call. raise NotImplementedError("Snappy codec is not available") if xerial_compatible: def _chunker(): for i in range(0, len(payload), xerial_blocksize): yield payload[i:i+xerial_blocksize] ...
def snappy_encode(payload, xerial_compatible=False, xerial_blocksize=32 * 1024)
Compress the given data with the Snappy algorithm. :param bytes payload: Data to compress. :param bool xerial_compatible: If set then the stream is broken into length-prefixed blocks in a fashion compatible with the xerial snappy library. The format winds up being:: +-----...
2.89749
3.142877
0.921923
if not hasattr(self, '_info_cache'): encoding_backend = get_backend() try: path = os.path.abspath(self.path) except AttributeError: path = os.path.abspath(self.name) self._info_cache = encoding_backend.get_media_info(path) ...
def _get_video_info(self)
Returns basic information about the video as dictionary.
3.183213
2.948523
1.079596
# any more data? out = process.stderr.read(10) if not out: break out = out.decode(console_encoding) output += out buf += out try: line, buf = buf.split('\r', 1) except ValueError: ...
def encode(self, source_path, target_path, params): # NOQA: C901 total_time = self.get_media_info(source_path)['duration'] cmds = [self.ffmpeg_path, '-i', source_path] cmds.extend(self.params) cmds.extend(params) cmds.extend([target_path]) process = self._spaw...
Encodes a video to a specified file. All encoder specific options are passed in using `params`.
3.619004
3.726352
0.971192
cmds = [self.ffprobe_path, '-i', video_path] cmds.extend(['-print_format', 'json']) cmds.extend(['-show_format', '-show_streams']) process = self._spawn(cmds) stdout, __ = self._check_returncode(process) media_info = self._parse_media_info(stdout) retu...
def get_media_info(self, video_path)
Returns information about the given video as dict.
2.497351
2.477324
1.008084
filename = os.path.basename(video_path) filename, __ = os.path.splitext(filename) _, image_path = tempfile.mkstemp(suffix='_{}.jpg'.format(filename)) video_duration = self.get_media_info(video_path)['duration'] if at_time > video_duration: raise exceptions.I...
def get_thumbnail(self, video_path, at_time=0.5)
Extracts an image of a video and returns its path. If the requested thumbnail is not within the duration of the video an `InvalidTimeError` is thrown.
2.745295
2.626843
1.045093
# get instance Model = apps.get_model(app_label=app_label, model_name=model_name) instance = Model.objects.get(pk=object_pk) # search for `VideoFields` fields = instance._meta.fields for field in fields: if isinstance(field, VideoField): if not getattr(instance, field.n...
def convert_all_videos(app_label, model_name, object_pk)
Automatically converts all videos of a given instance.
3.115634
3.040208
1.02481
instance = fieldfile.instance field = fieldfile.field filename = os.path.basename(fieldfile.path) source_path = fieldfile.path encoding_backend = get_backend() for options in settings.VIDEO_ENCODING_FORMATS[encoding_backend.name]: video_format, created = Format.objects.get_or_cre...
def convert_video(fieldfile, force=False)
Converts a given video file into all defined formats.
3.570161
3.603588
0.990724
results = [] cache = {} #scale variables in x because PSO works with velocities to visit different configurations tuning_options["scaling"] = True #using this instead of get_bounds because scaling is used bounds, _, _ = get_bounds_x0_eps(tuning_options) args = (kernel_options, tunin...
def tune(runner, kernel_options, device_options, tuning_options)
Find the best performing kernel configuration in the parameter space :params runner: A runner from kernel_tuner.runners :type runner: kernel_tuner.runner :param kernel_options: A dictionary with all options for the kernel. :type kernel_options: dict :param device_options: A dictionary with all op...
4.580303
4.503734
1.017001
return np.linalg.norm(self.position-other.position)
def distance_to(self, other)
Return Euclidian distance between self and other Firefly
4.445734
3.354374
1.325354
self.evaluate(_cost_func) self.intensity = 1 / self.time
def compute_intensity(self, _cost_func)
Evaluate cost function and compute intensity at this position
8.875723
7.301169
1.215658
self.position += beta * (other.position - self.position) self.position += alpha * (np.random.uniform(-0.5, 0.5, len(self.position))) self.position = np.minimum(self.position, [b[1] for b in self.bounds]) self.position = np.maximum(self.position, [b[0] for b in self.bounds])
def move_towards(self, other, beta, alpha)
Move firefly towards another given beta and alpha values
2.293157
2.062778
1.111684
#first check if the length is the same if len(instance.arguments) != len(answer): raise TypeError("The length of argument list and provided results do not match.") #for each element in the argument list, check if the types match for i, arg in enumerate(instance.arguments): if answe...
def _default_verify_function(instance, answer, result_host, atol, verbose)
default verify function based on numpy.allclose
2.809583
2.775992
1.0121
logging.debug('benchmark ' + instance.name) logging.debug('thread block dimensions x,y,z=%d,%d,%d', *instance.threads) logging.debug('grid dimensions x,y,z=%d,%d,%d', *instance.grid) time = None try: time = self.dev.benchmark(func, gpu_args, instance.threads...
def benchmark(self, func, gpu_args, instance, times, verbose)
benchmark the kernel instance
5.339433
5.213839
1.024089
logging.debug('check_kernel_output') #if not using custom verify function, check if the length is the same if not verify and len(instance.arguments) != len(answer): raise TypeError("The length of argument list and provided results do not match.") #zero GPU memory f...
def check_kernel_output(self, func, gpu_args, instance, answer, atol, verify, verbose)
runs the kernel once and checks the result against answer
3.698081
3.678184
1.00541
instance_string = util.get_instance_string(params) logging.debug('compile_and_benchmark ' + instance_string) mem_usage = round(resource.getrusage(resource.RUSAGE_SELF).ru_maxrss/1024.0, 1) logging.debug('Memory usage : %2.2f MB', mem_usage) verbose = tuning_options.ve...
def compile_and_benchmark(self, gpu_args, params, kernel_options, tuning_options)
Compile and benchmark a kernel instance based on kernel strings and parameters
3.504588
3.438639
1.019179
logging.debug('compile_kernel ' + instance.name) #compile kernel_string into device func func = None try: func = self.dev.compile(instance.name, instance.kernel_string) except Exception as e: #compiles may fail because certain kernel configuratio...
def compile_kernel(self, instance, verbose)
compile the kernel for this specific instance
5.941555
5.941059
1.000083
if self.lang == "CUDA": self.dev.copy_constant_memory_args(cmem_args) else: raise Exception("Error cannot copy constant memory arguments when language is not CUDA")
def copy_constant_memory_args(self, cmem_args)
adds constant memory arguments to the most recently compiled module, if using CUDA
4.772903
3.904177
1.222512
if self.lang == "CUDA": self.dev.copy_texture_memory_args(texmem_args) else: raise Exception("Error cannot copy texture memory arguments when language is not CUDA")
def copy_texture_memory_args(self, texmem_args)
adds texture memory arguments to the most recently compiled module, if using CUDA
4.884994
3.916668
1.247232
instance_string = util.get_instance_string(params) grid_div = (kernel_options.grid_div_x, kernel_options.grid_div_y, kernel_options.grid_div_z) #insert default block_size_names if needed if not kernel_options.block_size_names: kernel_options.block_size_names = util....
def create_kernel_instance(self, kernel_options, params, verbose)
create kernel instance from kernel source, parameters, problem size, grid divisors, and so on
4.014205
3.824275
1.049664
logging.debug('run_kernel %s', instance.name) logging.debug('thread block dims (%d, %d, %d)', *instance.threads) logging.debug('grid dims (%d, %d, %d)', *instance.grid) try: self.dev.run_kernel(func, gpu_args, instance.threads, instance.grid) except Exceptio...
def run_kernel(self, func, gpu_args, instance)
Run a compiled kernel instance on a device
3.532151
3.488238
1.012589
for i in range(0, len(l), n): yield l[i:i + n]
def _chunk_list(l, n)
Yield successive n-sized chunks from l.
2.003627
1.847176
1.084697
workflow = self._parameter_sweep(parameter_space, kernel_options, self.device_options, tuning_options) if tuning_options.verbose: with NCDisplay(_error_filter) as display: answer = run_parallel_with_display(workflow, self.max_...
def run(self, parameter_space, kernel_options, tuning_options)
Tune all instances in parameter_space using a multiple threads :param parameter_space: The parameter space as an iterable. :type parameter_space: iterable :param kernel_options: A dictionary with all options for the kernel. :type kernel_options: kernel_tuner.interface.Options ...
6.757653
7.053584
0.958045
results = [] #randomize parameter space to do pseudo load balancing parameter_space = list(parameter_space) random.shuffle(parameter_space) #split parameter space into chunks work_per_thread = int(numpy.ceil(len(parameter_space) / float(self.max_threads))) ...
def _parameter_sweep(self, parameter_space, kernel_options, device_options, tuning_options)
Build a Noodles workflow by sweeping the parameter space
4.297132
4.054715
1.059787
#detect language and create high-level device interface self.dev = DeviceInterface(kernel_options.kernel_string, iterations=tuning_options.iterations, **device_options) #move data to the GPU gpu_args = self.dev.ready_argument_list(kernel_options.arguments) results = [...
def _run_chunk(self, chunk, kernel_options, device_options, tuning_options)
Benchmark a single kernel instance in the parameter space
5.653329
5.453789
1.036588
tune_params = tuning_options.tune_params #compute cartesian product of all tunable parameters parameter_space = itertools.product(*tune_params.values()) #check for search space restrictions if tuning_options.restrictions is not None: parameter_space = filter(lambda p: util.check_rest...
def tune(runner, kernel_options, device_options, tuning_options)
Tune a random sample of sample_fraction fraction in the parameter space :params runner: A runner from kernel_tuner.runners :type runner: kernel_tuner.runner :param kernel_options: A dictionary with all options for the kernel. :type kernel_options: kernel_tuner.interface.Options :param device_opti...
3.278509
3.143378
1.042989
types_map = {"uint8": ["uchar", "unsigned char", "uint8_t"], "int8": ["char", "int8_t"], "uint16": ["ushort", "unsigned short", "uint16_t"], "int16": ["short", "int16_t"], "uint32": ["uint", "unsigned int", "uint32_t"], "int32...
def check_argument_type(dtype, kernel_argument, i)
check if the numpy.dtype matches the type used in the code
2.14612
2.135399
1.005021
kernel_arguments = list() collected_errors = list() for iterator in re.finditer(kernel_name + "[ \n\t]*" + "\(", kernel_string): kernel_start = iterator.end() kernel_end = kernel_string.find(")", kernel_start) if kernel_start != 0: kernel_arguments.append(kernel_stri...
def check_argument_list(kernel_name, kernel_string, args)
raise an exception if a kernel arguments do not match host arguments
3.620862
3.498674
1.034924
forbidden_names = ("grid_size_x", "grid_size_y", "grid_size_z") forbidden_name_substr = ("time", "times") for name, param in tune_params.items(): if name in forbidden_names: raise ValueError("Tune parameter " + name + " with value " + str(param) + " has a forbidden name!") f...
def check_tune_params_list(tune_params)
raise an exception if a tune parameter has a forbidden name
2.85054
2.532871
1.125418
params = OrderedDict(zip(keys, element)) for restrict in restrictions: if not eval(replace_param_occurrences(restrict, params)): if verbose: print("skipping config", get_instance_string(params), "reason: config fails restriction") return False return True
def check_restrictions(restrictions, element, keys, verbose)
check whether a specific instance meets the search space restrictions
7.684898
6.61769
1.161266
if lang is None: if callable(kernel_source): raise TypeError("Please specify language when using a code generator function") kernel_string = get_kernel_string(kernel_source) if "__global__" in kernel_string: lang = "CUDA" elif "__kernel" in kernel_string:...
def detect_language(lang, kernel_source)
attempt to detect language from the kernel_string if not specified
3.71569
3.302067
1.125262
compact_str_items = [] # first make a list of compact strings for each parameter for k, v in params.items(): unit = "" if isinstance(units, dict): #check if not None not enough, units could be mocked which causes errors unit = units.get(k, "") compact_str_items.appen...
def get_config_string(params, units=None)
return a compact string representation of a dictionary
5.590233
5.289203
1.056914
def get_dimension_divisor(divisor_list, default, params): if divisor_list is None: if default in params: divisor_list = [default] else: return 1 return numpy.prod([int(eval(replace_param_occurrences(s, params))) for s in divisor_list]) ...
def get_grid_dimensions(current_problem_size, params, grid_div, block_size_names)
compute grid dims based on problem sizes and listed grid divisors
3.119802
2.979399
1.047125
#logging.debug('get_kernel_string called with %s', str(kernel_source)) logging.debug('get_kernel_string called') kernel_string = None if callable(kernel_source): kernel_string = kernel_source(params) elif isinstance(kernel_source, str): if looks_like_a_filename(kernel_source): ...
def get_kernel_string(kernel_source, params=None)
retrieve the kernel source and return as a string This function processes the passed kernel_source argument, which could be a function, a string with a filename, or just a string with code already. If kernel_source is a function, the function is called with instance parameters in 'params' as the only ...
2.856332
2.751482
1.038107
if isinstance(problem_size, (str, int, numpy.integer)): problem_size = (problem_size, ) current_problem_size = [1, 1, 1] for i, s in enumerate(problem_size): if isinstance(s, str): current_problem_size[i] = int(eval(replace_param_occurrences(s, params))) elif isinsta...
def get_problem_size(problem_size, params)
compute current problem size
2.645934
2.508815
1.054655
file = tempfile.mkstemp(suffix=suffix or "", prefix="temp_", dir=os.getcwd()) # or "" for Python 2 compatibility os.close(file[0]) return file[1]
def get_temp_filename(suffix=None)
return a string in the form of temp_X, where X is a large integer
4.897072
4.757533
1.02933
if not block_size_names: block_size_names = default_block_size_names block_size_x = params.get(block_size_names[0], 256) block_size_y = params.get(block_size_names[1], 1) block_size_z = params.get(block_size_names[2], 1) return (int(block_size_x), int(block_size_y), int(block_size_z))
def get_thread_block_dimensions(params, block_size_names=None)
thread block size from tuning params, currently using convention
1.688576
1.660776
1.016739
logging.debug('looks_like_a_filename called') result = False if isinstance(kernel_source, str): result = True #test if not too long if len(kernel_source) > 250: result = False #test if not contains special characters for c in "();{}\\": if...
def looks_like_a_filename(kernel_source)
attempt to detect whether source code or a filename was passed
4.222158
4.13382
1.02137
logging.debug('prepare_kernel_string called for %s', kernel_name) grid_dim_names = ["grid_size_x", "grid_size_y", "grid_size_z"] for i, g in enumerate(grid): kernel_string = "#define " + grid_dim_names[i] + " " + str(g) + "\n" + kernel_string for i, g in enumerate(threads): kernel_...
def prepare_kernel_string(kernel_name, kernel_string, params, grid, threads, block_size_names)
prepare kernel string for compilation Prepends the kernel with a series of C preprocessor defines specific to this kernel instance: * the thread block dimensions * the grid dimensions * tunable parameters Additionally the name of kernel is replace with an instance specific name. This i...
2.140274
2.085354
1.026336
temp_files = dict() kernel_string = get_kernel_string(kernel_file_list[0], params) name, kernel_string = prepare_kernel_string(kernel_name, kernel_string, params, grid, threads, block_size_names) if len(kernel_file_list) > 1: for f in kernel_file_list[1:]: #generate temp filen...
def prepare_list_of_files(kernel_name, kernel_file_list, params, grid, threads, block_size_names)
prepare the kernel string along with any additional files The first file in the list is allowed to include or read in the others The files beyond the first are considered additional files that may also contain tunable parameters For each file beyond the first this function creates a temporary file with ...
2.778987
2.630539
1.056432
if os.path.isfile(filename): with open(filename, 'r') as f: return f.read()
def read_file(filename)
return the contents of the file named filename or None if file not found
2.394426
2.059848
1.162428
for k, v in params.items(): string = string.replace(k, str(v)) return string
def replace_param_occurrences(string, params)
replace occurrences of the tuning params with their current value
2.501508
2.256708
1.108477
threads = get_thread_block_dimensions(params, block_size_names) current_problem_size = get_problem_size(problem_size, params) grid = get_grid_dimensions(current_problem_size, params, grid_div, block_size_names) return threads, grid
def setup_block_and_grid(problem_size, grid_div, params, block_size_names=None)
compute problem size, thread block and grid dimensions for this kernel
3.293582
2.874445
1.145815
import sys #ugly fix, hopefully we can find a better one if sys.version_info[0] >= 3: with open(filename, 'w', encoding="utf-8") as f: f.write(string) else: with open(filename, 'w') as f: f.write(string.encode("utf-8"))
def write_file(filename, string)
dump the contents of string to a file called filename
2.721849
2.680082
1.015584
gpu_args = [] for arg in arguments: # if arg i is a numpy array copy to device if isinstance(arg, numpy.ndarray): gpu_args.append(cl.Buffer(self.ctx, self.mf.READ_WRITE | self.mf.COPY_HOST_PTR, hostbuf=arg)) else: # if not an array, just pass ...
def ready_argument_list(self, arguments)
ready argument list to be passed to the kernel, allocates gpu mem :param arguments: List of arguments to be passed to the kernel. The order should match the argument list on the OpenCL kernel. Allowed values are numpy.ndarray, and/or numpy.int32, numpy.float32, and so on. :type ...
3.539785
3.317511
1.067
prg = cl.Program(self.ctx, kernel_string).build(options=self.compiler_options) func = getattr(prg, kernel_name) return func
def compile(self, kernel_name, kernel_string)
call the OpenCL compiler to compile the kernel, return the device function :param kernel_name: The name of the kernel to be compiled, used to lookup the function after compilation. :type kernel_name: string :param kernel_string: The OpenCL kernel code that contains the function `ke...
2.864553
3.720062
0.770028
global_size = (grid[0]*threads[0], grid[1]*threads[1], grid[2]*threads[2]) local_size = threads time = [] for _ in range(self.iterations): event = func(self.queue, global_size, local_size, *gpu_args) event.wait() time.append((event.profile.end...
def benchmark(self, func, gpu_args, threads, grid, times)
runs the kernel and measures time repeatedly, returns average time Runs the kernel and measures kernel execution time repeatedly, number of iterations is set during the creation of OpenCLFunctions. Benchmark returns a robust average, from all measurements the fastest and slowest runs are ...
2.851524
2.476219
1.151564
global_size = (grid[0]*threads[0], grid[1]*threads[1], grid[2]*threads[2]) local_size = threads event = func(self.queue, global_size, local_size, *gpu_args) event.wait()
def run_kernel(self, func, gpu_args, threads, grid)
runs the OpenCL kernel passed as 'func' :param func: An OpenCL Kernel :type func: pyopencl.Kernel :param gpu_args: A list of arguments to the kernel, order should match the order in the code. Allowed values are either variables in global memory or single values passed b...
2.799035
2.957211
0.946512
if isinstance(buffer, cl.Buffer): try: cl.enqueue_fill_buffer(self.queue, buffer, numpy.uint32(value), 0, size) except AttributeError: src=numpy.zeros(size, dtype='uint8')+numpy.uint8(value) cl.enqueue_copy(self.queue, buffer, src)
def memset(self, buffer, value, size)
set the memory in allocation to the value in value :param allocation: An OpenCL Buffer to fill :type allocation: pyopencl.Buffer :param value: The value to set the memory to :type value: a single 32-bit int :param size: The size of to the allocation unit in bytes :type...
3.042678
3.532301
0.861387
if isinstance(src, cl.Buffer): cl.enqueue_copy(self.queue, dest, src)
def memcpy_dtoh(self, dest, src)
perform a device to host memory copy :param dest: A numpy array in host memory to store the data :type dest: numpy.ndarray :param src: An OpenCL Buffer to copy data from :type src: pyopencl.Buffer
3.720823
4.606407
0.807749