_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q5300 | _coerce_topic | train | def _coerce_topic(topic):
"""
Ensure that the topic name is text string of a valid length.
:param topic: Kafka topic name. Valid characters are in the set ``[a-zA-Z0-9._-]``.
:raises ValueError: when the topic name exceeds 249 bytes
:raises TypeError: when the topic is not :class:`unicode` or :clas... | python | {
"resource": ""
} |
q5301 | _coerce_consumer_group | train | def _coerce_consumer_group(consumer_group):
"""
Ensure that the consumer group is a text string.
:param consumer_group: :class:`bytes` or :class:`str` instance
:raises TypeError: when `consumer_group` is not :class:`bytes`
or :class:`str`
"""
if not isinstance(consumer_group, string_typ... | python | {
"resource": ""
} |
q5302 | _coerce_client_id | train | def _coerce_client_id(client_id):
"""
Ensure the provided client ID is a byte string. If a text string is
provided, it is encoded as UTF-8 bytes.
:param client_id: :class:`bytes` or :class:`str` instance
"""
if isinstance(client_id, type(u'')):
client_id = client_id.encode('utf-8')
... | python | {
"resource": ""
} |
q5303 | write_short_ascii | train | def write_short_ascii(s):
"""
Encode a Kafka short string which represents text.
:param str s:
Text string (`str` on Python 3, `str` or `unicode` on Python 2) or
``None``. The string will be ASCII-encoded.
:returns: length-prefixed `bytes`
:raises:
`struct.error` for string... | python | {
"resource": ""
} |
q5304 | write_short_bytes | train | def write_short_bytes(b):
"""
Encode a Kafka short string which contains arbitrary bytes. A short string
is limited to 32767 bytes in length by the signed 16-bit length prefix.
A length prefix of -1 indicates ``null``, represented as ``None`` in
Python.
:param bytes b:
No more than 3276... | python | {
"resource": ""
} |
q5305 | CrontabReader.parse_cron_line | train | def parse_cron_line(self, line):
"""Parses crontab line and returns only starting time string
Args:
line: crontab line
Returns:
Time part of cron line
"""
stripped = line.strip()
if stripped and stripped.startswith('#') is False:
rexr... | python | {
"resource": ""
} |
q5306 | _KafkaBrokerClient.updateMetadata | train | def updateMetadata(self, new):
"""
Update the metadata stored for this broker.
Future connections made to the broker will use the host and port
defined in the new metadata. Any existing connection is not dropped,
however.
:param new:
:clas:`afkak.common.Brok... | python | {
"resource": ""
} |
q5307 | _KafkaBrokerClient.makeRequest | train | def makeRequest(self, requestId, request, expectResponse=True):
"""
Send a request to our broker via our self.proto KafkaProtocol object.
Return a deferred which will fire when the reply matching the requestId
comes back from the server, or, if expectResponse is False, then
retu... | python | {
"resource": ""
} |
q5308 | _KafkaBrokerClient.disconnect | train | def disconnect(self):
"""
Disconnect from the Kafka broker.
This is used to implement disconnection on timeout as a workaround for
Kafka connections occasionally getting stuck on the server side under
load. Requests are not cancelled, so they will be retried.
"""
... | python | {
"resource": ""
} |
q5309 | _KafkaBrokerClient.close | train | def close(self):
"""Permanently dispose of the broker client.
This terminates any outstanding connection and cancels any pending
requests.
"""
log.debug('%r: close() proto=%r connector=%r', self, self.proto, self.connector)
assert self._dDown is None
self._dDown ... | python | {
"resource": ""
} |
q5310 | _KafkaBrokerClient._connectionLost | train | def _connectionLost(self, reason):
"""Called when the protocol connection is lost
- Log the disconnection.
- Mark any outstanding requests as unsent so they will be sent when
a new connection is made.
- If closing the broker client, mark completion of that process.
:p... | python | {
"resource": ""
} |
q5311 | _KafkaBrokerClient.handleResponse | train | def handleResponse(self, response):
"""Handle the response string received by KafkaProtocol.
Ok, we've received the response from the broker. Find the requestId
in the message, lookup & fire the deferred with the response.
"""
requestId = KafkaCodec.get_response_correlation_id(r... | python | {
"resource": ""
} |
q5312 | _KafkaBrokerClient._sendRequest | train | def _sendRequest(self, tReq):
"""Send a single request over our protocol to the Kafka broker."""
try:
tReq.sent = True
self.proto.sendString(tReq.data)
except Exception as e:
log.exception('%r: Failed to send request %r', self, tReq)
del self.reque... | python | {
"resource": ""
} |
q5313 | _KafkaBrokerClient._sendQueued | train | def _sendQueued(self):
"""Connection just came up, send the unsent requests."""
for tReq in list(self.requests.values()): # must copy, may del
if not tReq.sent:
self._sendRequest(tReq) | python | {
"resource": ""
} |
q5314 | _KafkaBrokerClient._connect | train | def _connect(self):
"""Connect to the Kafka Broker
This routine will repeatedly try to connect to the broker (with backoff
according to the retry policy) until it succeeds.
"""
def tryConnect():
self.connector = d = maybeDeferred(connect)
d.addCallback(cb... | python | {
"resource": ""
} |
q5315 | group_envs | train | def group_envs(envlist):
"""Group Tox environments for Travis CI builds
Separate by Python version so that they can go in different Travis jobs:
>>> group_envs('py37-int-snappy', 'py36-int')
[('py36', 'int', ['py36-int']), ('py37', 'int', ['py37-int-snappy'])]
Group unit tests and linting togethe... | python | {
"resource": ""
} |
q5316 | create_gzip_message | train | def create_gzip_message(message_set):
"""
Construct a gzip-compressed message containing multiple messages
The given messages will be encoded, compressed, and sent as a single atomic
message to Kafka.
:param list message_set: a list of :class:`Message` instances
"""
encoded_message_set = K... | python | {
"resource": ""
} |
q5317 | create_snappy_message | train | def create_snappy_message(message_set):
"""
Construct a Snappy-compressed message containing multiple messages
The given messages will be encoded, compressed, and sent as a single atomic
message to Kafka.
:param list message_set: a list of :class:`Message` instances
"""
encoded_message_set... | python | {
"resource": ""
} |
q5318 | create_message_set | train | def create_message_set(requests, codec=CODEC_NONE):
"""
Create a message set from a list of requests.
Each request can have a list of messages and its own key. If codec is
:data:`CODEC_NONE`, return a list of raw Kafka messages. Otherwise, return
a list containing a single codec-encoded message.
... | python | {
"resource": ""
} |
q5319 | KafkaCodec.decode_consumermetadata_response | train | def decode_consumermetadata_response(cls, data):
"""
Decode bytes to a ConsumerMetadataResponse
:param bytes data: bytes to decode
"""
(correlation_id, error_code, node_id), cur = \
relative_unpack('>ihi', data, 0)
host, cur = read_short_ascii(data, cur)
... | python | {
"resource": ""
} |
q5320 | KafkaCodec.encode_offset_fetch_request | train | def encode_offset_fetch_request(cls, client_id, correlation_id,
group, payloads):
"""
Encode some OffsetFetchRequest structs
:param bytes client_id: string
:param int correlation_id: int
:param bytes group: string, the consumer group you are f... | python | {
"resource": ""
} |
q5321 | KafkaBootstrapProtocol.stringReceived | train | def stringReceived(self, response):
"""
Handle a response from the broker.
"""
correlation_id = response[0:4]
try:
d = self._pending.pop(correlation_id)
except KeyError:
self._log.warn((
"Response has unknown correlation ID {correla... | python | {
"resource": ""
} |
q5322 | KafkaBootstrapProtocol.connectionLost | train | def connectionLost(self, reason=connectionDone):
"""
Mark the protocol as failed and fail all pending operations.
"""
self._failed = reason
pending, self._pending = self._pending, None
for d in pending.values():
d.errback(reason) | python | {
"resource": ""
} |
q5323 | KafkaBootstrapProtocol.request | train | def request(self, request):
"""
Send a request to the Kafka broker.
:param bytes request:
The bytes of a Kafka `RequestMessage`_ structure. It must have
a unique (to this connection) correlation ID.
:returns:
`Deferred` which will:
- S... | python | {
"resource": ""
} |
q5324 | Producer.stop | train | def stop(self):
"""
Terminate any outstanding requests.
:returns: :class:``Deferred` which fires when fully stopped.
"""
self.stopping = True
# Cancel any outstanding request to our client
if self._batch_send_d:
self._batch_send_d.cancel()
# D... | python | {
"resource": ""
} |
q5325 | Producer._next_partition | train | def _next_partition(self, topic, key=None):
"""get the next partition to which to publish
Check with our client for the latest partitions for the topic, then
ask our partitioner for the next partition to which we should publish
for the give key. If needed, create a new partitioner for t... | python | {
"resource": ""
} |
q5326 | Producer._send_requests | train | def _send_requests(self, parts_results, requests):
"""Send the requests
We've determined the partition for each message group in the batch, or
got errors for them.
"""
# We use these dictionaries to be able to combine all the messages
# destined to the same topic/partiti... | python | {
"resource": ""
} |
q5327 | Producer._complete_batch_send | train | def _complete_batch_send(self, resp):
"""Complete the processing of our batch send operation
Clear the deferred tracking our current batch processing
and reset our retry count and retry interval
Return none to eat any errors coming from up the deferred chain
"""
self._ba... | python | {
"resource": ""
} |
q5328 | Producer._send_batch | train | def _send_batch(self):
"""
Send the waiting messages, if there are any, and we can...
This is called by our LoopingCall every send_every_t interval, and
from send_messages everytime we have enough messages to send.
This is also called from py:method:`send_messages` via
p... | python | {
"resource": ""
} |
q5329 | Producer._handle_send_response | train | def _handle_send_response(self, result, payloadsByTopicPart,
deferredsByTopicPart):
"""Handle the response from our client to our send_produce_request
This is a bit complex. Failures can happen in a few ways:
1. The client sent an empty list, False, None or some... | python | {
"resource": ""
} |
q5330 | Producer._cancel_outstanding | train | def _cancel_outstanding(self):
"""Cancel all of our outstanding requests"""
for d in list(self._outstanding):
d.addErrback(lambda _: None) # Eat any uncaught errors
d.cancel() | python | {
"resource": ""
} |
q5331 | KafkaClient.reset_consumer_group_metadata | train | def reset_consumer_group_metadata(self, *groups):
"""Reset cache of what broker manages the offset for specified groups
Remove the cache of what Kafka broker should be contacted when
fetching or updating the committed offsets for a given consumer
group or groups.
NOTE: Does not... | python | {
"resource": ""
} |
q5332 | KafkaClient.reset_all_metadata | train | def reset_all_metadata(self):
"""Clear all cached metadata
Metadata will be re-fetched as required to satisfy requests.
"""
self.topics_to_brokers.clear()
self.topic_partitions.clear()
self.topic_errors.clear()
self.consumer_group_to_brokers.clear() | python | {
"resource": ""
} |
q5333 | KafkaClient.topic_fully_replicated | train | def topic_fully_replicated(self, topic):
"""
Determine if the given topic is fully replicated according to the
currently known cluster metadata.
.. note::
This relies on cached cluster metadata. You may call
:meth:`load_metadata_for_topics()` first to refresh th... | python | {
"resource": ""
} |
q5334 | KafkaClient.close | train | 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.
- ... | python | {
"resource": ""
} |
q5335 | KafkaClient.load_metadata_for_topics | train | 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 ... | python | {
"resource": ""
} |
q5336 | KafkaClient.load_consumer_metadata_for_group | train | 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.
... | python | {
"resource": ""
} |
q5337 | KafkaClient.send_offset_commit_request | train | 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
... | python | {
"resource": ""
} |
q5338 | KafkaClient._get_brokerclient | train | 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`
"""
if self._closing:
raise ClientError("Cannot get broker client for node... | python | {
"resource": ""
} |
q5339 | KafkaClient._close_brokerclients | train | def _close_brokerclients(self, clients):
"""
Close the given broker clients.
:param clients: Iterable of `_KafkaBrokerClient`
"""
def _log_close_failure(failure, brokerclient):
log.debug(
'BrokerClient: %s close result: %s: %s', brokerclient,
... | python | {
"resource": ""
} |
q5340 | KafkaClient._update_brokers | train | 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... | python | {
"resource": ""
} |
q5341 | KafkaClient._make_request_to_broker | train | def _make_request_to_broker(self, broker, requestId, request, **kwArgs):
"""Send a request to the specified broker."""
def _timeout_request(broker, requestId):
"""The time we allotted for the request expired, cancel it."""
try:
# FIXME: This should be done by call... | python | {
"resource": ""
} |
q5342 | KafkaClient._send_bootstrap_request | train | 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. Th... | python | {
"resource": ""
} |
q5343 | ExpressionDescriptor.get_description | train | 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:
Exc... | python | {
"resource": ""
} |
q5344 | ExpressionDescriptor.get_full_description | train | 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
"""
try:
time_segment = self.get_time_of_day_description()... | python | {
"resource": ""
} |
q5345 | ExpressionDescriptor.get_time_of_day_description | train | def get_time_of_day_description(self):
"""Generates a description for only the TIMEOFDAY portion of the expression
Returns:
The TIMEOFDAY description
"""
seconds_expression = self._expression_parts[0]
minute_expression = self._expression_parts[1]
hour_expres... | python | {
"resource": ""
} |
q5346 | ExpressionDescriptor.get_seconds_description | train | def get_seconds_description(self):
"""Generates a description for only the SECONDS portion of the expression
Returns:
The SECONDS description
"""
return self.get_segment_description(
self._expression_parts[0],
_("every second"),
lambda s... | python | {
"resource": ""
} |
q5347 | ExpressionDescriptor.get_minutes_description | train | def get_minutes_description(self):
"""Generates a description for only the MINUTE portion of the expression
Returns:
The MINUTE description
"""
return self.get_segment_description(
self._expression_parts[1],
_("every minute"),
lambda s: ... | python | {
"resource": ""
} |
q5348 | ExpressionDescriptor.get_hours_description | train | def get_hours_description(self):
"""Generates a description for only the HOUR portion of the expression
Returns:
The HOUR description
"""
expression = self._expression_parts[2]
return self.get_segment_description(
expression,
_("every hour"),... | python | {
"resource": ""
} |
q5349 | ExpressionDescriptor.get_day_of_week_description | train | def get_day_of_week_description(self):
"""Generates a description for only the DAYOFWEEK portion of the expression
Returns:
The DAYOFWEEK description
"""
if self._expression_parts[5] == "*" and self._expression_parts[3] != "*":
# DOM is specified and DOW is * s... | python | {
"resource": ""
} |
q5350 | ExpressionDescriptor.get_month_description | train | def get_month_description(self):
"""Generates a description for only the MONTH portion of the expression
Returns:
The MONTH description
"""
return self.get_segment_description(
self._expression_parts[4],
'',
lambda s: datetime.date(dateti... | python | {
"resource": ""
} |
q5351 | ExpressionDescriptor.get_day_of_month_description | train | def get_day_of_month_description(self):
"""Generates a description for only the DAYOFMONTH portion of the expression
Returns:
The DAYOFMONTH description
"""
expression = self._expression_parts[3]
expression = expression.replace("?", "*")
if expression == "L... | python | {
"resource": ""
} |
q5352 | ExpressionDescriptor.get_year_description | train | def get_year_description(self):
"""Generates a description for only the YEAR portion of the expression
Returns:
The YEAR description
"""
def format_year(s):
regex = re.compile(r"^\d+$")
if regex.match(s):
year_int = int(s)
... | python | {
"resource": ""
} |
q5353 | ExpressionDescriptor.number_to_day | train | 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
"""
return [
... | python | {
"resource": ""
} |
q5354 | Consumer.shutdown | train | 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
... | python | {
"resource": ""
} |
q5355 | Consumer.stop | train | 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 off... | python | {
"resource": ""
} |
q5356 | Consumer.commit | train | 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 reproc... | python | {
"resource": ""
} |
q5357 | Consumer._auto_commit | train | def _auto_commit(self, by_count=False):
"""Check if we should start a new commit operation and commit"""
# 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
... | python | {
"resource": ""
} |
q5358 | Consumer._handle_offset_response | train | 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
"""
# Got a response, clear our outstandi... | python | {
"resource": ""
} |
q5359 | Consumer._handle_offset_error | train | 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.
"""
# outstanding... | python | {
"resource": ""
} |
q5360 | Consumer._send_commit_request | train | def _send_commit_request(self, retry_delay=None, attempt=None):
"""Send a commit request with our last_processed_offset"""
# 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... | python | {
"resource": ""
} |
q5361 | Consumer._handle_commit_error | train | 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
"""
# Check if we are st... | python | {
"resource": ""
} |
q5362 | Consumer._handle_processor_error | train | 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 :fun... | python | {
"resource": ""
} |
q5363 | Consumer._handle_fetch_error | train | 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... | python | {
"resource": ""
} |
q5364 | Consumer._handle_fetch_response | train | 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 t... | python | {
"resource": ""
} |
q5365 | Consumer._process_messages | train | 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.
... | python | {
"resource": ""
} |
q5366 | Consumer._do_fetch | train | 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
... | python | {
"resource": ""
} |
q5367 | HashedPartitioner.partition | train | 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:
... | python | {
"resource": ""
} |
q5368 | snappy_encode | train | 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
... | python | {
"resource": ""
} |
q5369 | VideoFile._get_video_info | train | def _get_video_info(self):
"""
Returns basic information about the video as dictionary.
"""
if not hasattr(self, '_info_cache'):
encoding_backend = get_backend()
try:
path = os.path.abspath(self.path)
except AttributeError:
... | python | {
"resource": ""
} |
q5370 | FFmpegBackend.encode | train | def encode(self, source_path, target_path, params): # NOQA: C901
"""
Encodes a video to a specified file. All encoder specific options
are passed in using `params`.
"""
total_time = self.get_media_info(source_path)['duration']
cmds = [self.ffmpeg_path, '-i', source_path... | python | {
"resource": ""
} |
q5371 | FFmpegBackend.get_media_info | train | def get_media_info(self, video_path):
"""
Returns information about the given video as dict.
"""
cmds = [self.ffprobe_path, '-i', video_path]
cmds.extend(['-print_format', 'json'])
cmds.extend(['-show_format', '-show_streams'])
process = self._spawn(cmds)
... | python | {
"resource": ""
} |
q5372 | FFmpegBackend.get_thumbnail | train | 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.
"""
filename = os.path.basename(video_path)
filename, __ =... | python | {
"resource": ""
} |
q5373 | convert_all_videos | train | def convert_all_videos(app_label, model_name, object_pk):
"""
Automatically converts all videos of a given instance.
"""
# 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 = insta... | python | {
"resource": ""
} |
q5374 | convert_video | train | def convert_video(fieldfile, force=False):
"""
Converts a given video file into all defined formats.
"""
instance = fieldfile.instance
field = fieldfile.field
filename = os.path.basename(fieldfile.path)
source_path = fieldfile.path
encoding_backend = get_backend()
for options in s... | python | {
"resource": ""
} |
q5375 | Firefly.distance_to | train | def distance_to(self, other):
"""Return Euclidian distance between self and other Firefly"""
return np.linalg.norm(self.position-other.position) | python | {
"resource": ""
} |
q5376 | Firefly.compute_intensity | train | def compute_intensity(self, _cost_func):
"""Evaluate cost function and compute intensity at this position"""
self.evaluate(_cost_func)
self.intensity = 1 / self.time | python | {
"resource": ""
} |
q5377 | Firefly.move_towards | train | def move_towards(self, other, beta, alpha):
"""Move firefly towards another given beta and alpha values"""
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] ... | python | {
"resource": ""
} |
q5378 | DeviceInterface.benchmark | train | def benchmark(self, func, gpu_args, instance, times, verbose):
"""benchmark the kernel instance"""
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)
... | python | {
"resource": ""
} |
q5379 | DeviceInterface.check_kernel_output | train | def check_kernel_output(self, func, gpu_args, instance, answer, atol, verify, verbose):
"""runs the kernel once and checks the result against answer"""
logging.debug('check_kernel_output')
#if not using custom verify function, check if the length is the same
if not verify and len(instan... | python | {
"resource": ""
} |
q5380 | DeviceInterface.compile_and_benchmark | train | def compile_and_benchmark(self, gpu_args, params, kernel_options, tuning_options):
""" Compile and benchmark a kernel instance based on kernel strings and parameters """
instance_string = util.get_instance_string(params)
logging.debug('compile_and_benchmark ' + instance_string)
mem_usa... | python | {
"resource": ""
} |
q5381 | DeviceInterface.compile_kernel | train | def compile_kernel(self, instance, verbose):
"""compile the kernel for this specific instance"""
logging.debug('compile_kernel ' + instance.name)
#compile kernel_string into device func
func = None
try:
func = self.dev.compile(instance.name, instance.kernel_string)
... | python | {
"resource": ""
} |
q5382 | DeviceInterface.copy_constant_memory_args | train | def copy_constant_memory_args(self, cmem_args):
"""adds constant memory arguments to the most recently compiled module, if using CUDA"""
if self.lang == "CUDA":
self.dev.copy_constant_memory_args(cmem_args)
else:
raise Exception("Error cannot copy constant memory argument... | python | {
"resource": ""
} |
q5383 | DeviceInterface.copy_texture_memory_args | train | def copy_texture_memory_args(self, texmem_args):
"""adds texture memory arguments to the most recently compiled module, if using CUDA"""
if self.lang == "CUDA":
self.dev.copy_texture_memory_args(texmem_args)
else:
raise Exception("Error cannot copy texture memory argument... | python | {
"resource": ""
} |
q5384 | DeviceInterface.create_kernel_instance | train | def create_kernel_instance(self, kernel_options, params, verbose):
"""create kernel instance from kernel source, parameters, problem size, grid divisors, and so on"""
instance_string = util.get_instance_string(params)
grid_div = (kernel_options.grid_div_x, kernel_options.grid_div_y, kernel_optio... | python | {
"resource": ""
} |
q5385 | DeviceInterface.run_kernel | train | def run_kernel(self, func, gpu_args, instance):
""" Run a compiled kernel instance on a device """
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:
... | python | {
"resource": ""
} |
q5386 | NoodlesRunner.run | train | 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 ke... | python | {
"resource": ""
} |
q5387 | NoodlesRunner._parameter_sweep | train | def _parameter_sweep(self, parameter_space, kernel_options, device_options, tuning_options):
"""Build a Noodles workflow by sweeping the parameter space"""
results = []
#randomize parameter space to do pseudo load balancing
parameter_space = list(parameter_space)
random.shuffle(... | python | {
"resource": ""
} |
q5388 | NoodlesRunner._run_chunk | train | def _run_chunk(self, chunk, kernel_options, device_options, tuning_options):
"""Benchmark a single kernel instance in the parameter space"""
#detect language and create high-level device interface
self.dev = DeviceInterface(kernel_options.kernel_string, iterations=tuning_options.iterations, **d... | python | {
"resource": ""
} |
q5389 | tune | train | 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.
:t... | python | {
"resource": ""
} |
q5390 | check_argument_type | train | def check_argument_type(dtype, kernel_argument, i):
"""check if the numpy.dtype matches the type used in the code"""
types_map = {"uint8": ["uchar", "unsigned char", "uint8_t"],
"int8": ["char", "int8_t"],
"uint16": ["ushort", "unsigned short", "uint16_t"],
"in... | python | {
"resource": ""
} |
q5391 | check_argument_list | train | def check_argument_list(kernel_name, kernel_string, args):
""" raise an exception if a kernel arguments do not match host arguments """
kernel_arguments = list()
collected_errors = list()
for iterator in re.finditer(kernel_name + "[ \n\t]*" + "\(", kernel_string):
kernel_start = iterator.end()
... | python | {
"resource": ""
} |
q5392 | check_tune_params_list | train | def check_tune_params_list(tune_params):
""" raise an exception if a tune parameter has a forbidden name """
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:
r... | python | {
"resource": ""
} |
q5393 | check_restrictions | train | def check_restrictions(restrictions, element, keys, verbose):
""" check whether a specific instance meets the search space restrictions """
params = OrderedDict(zip(keys, element))
for restrict in restrictions:
if not eval(replace_param_occurrences(restrict, params)):
if verbose:
... | python | {
"resource": ""
} |
q5394 | detect_language | train | def detect_language(lang, kernel_source):
"""attempt to detect language from the kernel_string if not specified"""
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_sou... | python | {
"resource": ""
} |
q5395 | get_config_string | train | def get_config_string(params, units=None):
""" return a compact string representation of a dictionary """
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, unit... | python | {
"resource": ""
} |
q5396 | get_grid_dimensions | train | def get_grid_dimensions(current_problem_size, params, grid_div, block_size_names):
"""compute grid dims based on problem sizes and listed grid divisors"""
def get_dimension_divisor(divisor_list, default, params):
if divisor_list is None:
if default in params:
divisor_list = [... | python | {
"resource": ""
} |
q5397 | get_kernel_string | train | 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 c... | python | {
"resource": ""
} |
q5398 | get_problem_size | train | def get_problem_size(problem_size, params):
"""compute current problem size"""
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_... | python | {
"resource": ""
} |
q5399 | get_temp_filename | train | def get_temp_filename(suffix=None):
""" return a string in the form of temp_X, where X is a large integer """
file = tempfile.mkstemp(suffix=suffix or "", prefix="temp_", dir=os.getcwd()) # or "" for Python 2 compatibility
os.close(file[0])
return file[1] | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.