repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1 value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1 value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
genialis/django-rest-framework-reactive | src/rest_framework_reactive/consumers.py | MainConsumer.observer_poll | async def observer_poll(self, message):
"""Poll observer after a delay."""
# Sleep until we need to notify the observer.
await asyncio.sleep(message['interval'])
# Dispatch task to evaluate the observable.
await self.channel_layer.send(
CHANNEL_WORKER, {'type': TYPE_EVALUATE, 'observer': message['observer']}
) | python | async def observer_poll(self, message):
"""Poll observer after a delay."""
# Sleep until we need to notify the observer.
await asyncio.sleep(message['interval'])
# Dispatch task to evaluate the observable.
await self.channel_layer.send(
CHANNEL_WORKER, {'type': TYPE_EVALUATE, 'observer': message['observer']}
) | [
"async",
"def",
"observer_poll",
"(",
"self",
",",
"message",
")",
":",
"# Sleep until we need to notify the observer.",
"await",
"asyncio",
".",
"sleep",
"(",
"message",
"[",
"'interval'",
"]",
")",
"# Dispatch task to evaluate the observable.",
"await",
"self",
".",
... | Poll observer after a delay. | [
"Poll",
"observer",
"after",
"a",
"delay",
"."
] | ddf3d899685a54b6bd0ae4b3789649a89340c59f | https://github.com/genialis/django-rest-framework-reactive/blob/ddf3d899685a54b6bd0ae4b3789649a89340c59f/src/rest_framework_reactive/consumers.py#L49-L57 | train | 30,700 |
genialis/django-rest-framework-reactive | src/rest_framework_reactive/consumers.py | WorkerConsumer.observer_evaluate | async def observer_evaluate(self, message):
"""Execute observer evaluation on the worker or throttle."""
observer_id = message['observer']
throttle_rate = get_queryobserver_settings()['throttle_rate']
if throttle_rate <= 0:
await self._evaluate(observer_id)
return
cache_key = throttle_cache_key(observer_id)
try:
count = cache.incr(cache_key)
# Ignore if delayed observer already scheduled.
if count == 2:
await self.channel_layer.send(
CHANNEL_MAIN,
{
'type': TYPE_POLL,
'observer': observer_id,
'interval': throttle_rate,
},
)
except ValueError:
count = cache.get_or_set(cache_key, default=1, timeout=throttle_rate)
# Ignore if cache was set and increased in another thread.
if count == 1:
await self._evaluate(observer_id) | python | async def observer_evaluate(self, message):
"""Execute observer evaluation on the worker or throttle."""
observer_id = message['observer']
throttle_rate = get_queryobserver_settings()['throttle_rate']
if throttle_rate <= 0:
await self._evaluate(observer_id)
return
cache_key = throttle_cache_key(observer_id)
try:
count = cache.incr(cache_key)
# Ignore if delayed observer already scheduled.
if count == 2:
await self.channel_layer.send(
CHANNEL_MAIN,
{
'type': TYPE_POLL,
'observer': observer_id,
'interval': throttle_rate,
},
)
except ValueError:
count = cache.get_or_set(cache_key, default=1, timeout=throttle_rate)
# Ignore if cache was set and increased in another thread.
if count == 1:
await self._evaluate(observer_id) | [
"async",
"def",
"observer_evaluate",
"(",
"self",
",",
"message",
")",
":",
"observer_id",
"=",
"message",
"[",
"'observer'",
"]",
"throttle_rate",
"=",
"get_queryobserver_settings",
"(",
")",
"[",
"'throttle_rate'",
"]",
"if",
"throttle_rate",
"<=",
"0",
":",
... | Execute observer evaluation on the worker or throttle. | [
"Execute",
"observer",
"evaluation",
"on",
"the",
"worker",
"or",
"throttle",
"."
] | ddf3d899685a54b6bd0ae4b3789649a89340c59f | https://github.com/genialis/django-rest-framework-reactive/blob/ddf3d899685a54b6bd0ae4b3789649a89340c59f/src/rest_framework_reactive/consumers.py#L93-L118 | train | 30,701 |
genialis/django-rest-framework-reactive | src/rest_framework_reactive/consumers.py | ClientConsumer.websocket_connect | def websocket_connect(self, message):
"""Called when WebSocket connection is established."""
self.session_id = self.scope['url_route']['kwargs']['subscriber_id']
super().websocket_connect(message)
# Create new subscriber object.
Subscriber.objects.get_or_create(session_id=self.session_id) | python | def websocket_connect(self, message):
"""Called when WebSocket connection is established."""
self.session_id = self.scope['url_route']['kwargs']['subscriber_id']
super().websocket_connect(message)
# Create new subscriber object.
Subscriber.objects.get_or_create(session_id=self.session_id) | [
"def",
"websocket_connect",
"(",
"self",
",",
"message",
")",
":",
"self",
".",
"session_id",
"=",
"self",
".",
"scope",
"[",
"'url_route'",
"]",
"[",
"'kwargs'",
"]",
"[",
"'subscriber_id'",
"]",
"super",
"(",
")",
".",
"websocket_connect",
"(",
"message"... | Called when WebSocket connection is established. | [
"Called",
"when",
"WebSocket",
"connection",
"is",
"established",
"."
] | ddf3d899685a54b6bd0ae4b3789649a89340c59f | https://github.com/genialis/django-rest-framework-reactive/blob/ddf3d899685a54b6bd0ae4b3789649a89340c59f/src/rest_framework_reactive/consumers.py#L124-L130 | train | 30,702 |
genialis/django-rest-framework-reactive | src/rest_framework_reactive/consumers.py | ClientConsumer.disconnect | def disconnect(self, code):
"""Called when WebSocket connection is closed."""
Subscriber.objects.filter(session_id=self.session_id).delete() | python | def disconnect(self, code):
"""Called when WebSocket connection is closed."""
Subscriber.objects.filter(session_id=self.session_id).delete() | [
"def",
"disconnect",
"(",
"self",
",",
"code",
")",
":",
"Subscriber",
".",
"objects",
".",
"filter",
"(",
"session_id",
"=",
"self",
".",
"session_id",
")",
".",
"delete",
"(",
")"
] | Called when WebSocket connection is closed. | [
"Called",
"when",
"WebSocket",
"connection",
"is",
"closed",
"."
] | ddf3d899685a54b6bd0ae4b3789649a89340c59f | https://github.com/genialis/django-rest-framework-reactive/blob/ddf3d899685a54b6bd0ae4b3789649a89340c59f/src/rest_framework_reactive/consumers.py#L140-L142 | train | 30,703 |
genialis/django-rest-framework-reactive | src/rest_framework_reactive/consumers.py | ClientConsumer.observer_update | def observer_update(self, message):
"""Called when update from observer is received."""
# Demultiplex observer update into multiple messages.
for action in ('added', 'changed', 'removed'):
for item in message[action]:
self.send_json(
{
'msg': action,
'observer': message['observer'],
'primary_key': message['primary_key'],
'order': item['order'],
'item': item['data'],
}
) | python | def observer_update(self, message):
"""Called when update from observer is received."""
# Demultiplex observer update into multiple messages.
for action in ('added', 'changed', 'removed'):
for item in message[action]:
self.send_json(
{
'msg': action,
'observer': message['observer'],
'primary_key': message['primary_key'],
'order': item['order'],
'item': item['data'],
}
) | [
"def",
"observer_update",
"(",
"self",
",",
"message",
")",
":",
"# Demultiplex observer update into multiple messages.",
"for",
"action",
"in",
"(",
"'added'",
",",
"'changed'",
",",
"'removed'",
")",
":",
"for",
"item",
"in",
"message",
"[",
"action",
"]",
":"... | Called when update from observer is received. | [
"Called",
"when",
"update",
"from",
"observer",
"is",
"received",
"."
] | ddf3d899685a54b6bd0ae4b3789649a89340c59f | https://github.com/genialis/django-rest-framework-reactive/blob/ddf3d899685a54b6bd0ae4b3789649a89340c59f/src/rest_framework_reactive/consumers.py#L144-L157 | train | 30,704 |
genialis/django-rest-framework-reactive | src/rest_framework_reactive/observer.py | remove_subscriber | def remove_subscriber(session_id, observer_id):
"""Remove subscriber from the given observer.
:param session_id: Subscriber's session identifier
:param observer_id: Observer identifier
"""
models.Observer.subscribers.through.objects.filter(
subscriber_id=session_id, observer_id=observer_id
).delete() | python | def remove_subscriber(session_id, observer_id):
"""Remove subscriber from the given observer.
:param session_id: Subscriber's session identifier
:param observer_id: Observer identifier
"""
models.Observer.subscribers.through.objects.filter(
subscriber_id=session_id, observer_id=observer_id
).delete() | [
"def",
"remove_subscriber",
"(",
"session_id",
",",
"observer_id",
")",
":",
"models",
".",
"Observer",
".",
"subscribers",
".",
"through",
".",
"objects",
".",
"filter",
"(",
"subscriber_id",
"=",
"session_id",
",",
"observer_id",
"=",
"observer_id",
")",
"."... | Remove subscriber from the given observer.
:param session_id: Subscriber's session identifier
:param observer_id: Observer identifier | [
"Remove",
"subscriber",
"from",
"the",
"given",
"observer",
"."
] | ddf3d899685a54b6bd0ae4b3789649a89340c59f | https://github.com/genialis/django-rest-framework-reactive/blob/ddf3d899685a54b6bd0ae4b3789649a89340c59f/src/rest_framework_reactive/observer.py#L473-L481 | train | 30,705 |
genialis/django-rest-framework-reactive | src/rest_framework_reactive/observer.py | QueryObserver._get_logging_extra | def _get_logging_extra(self, duration=None, results=None):
"""Extra information for logger."""
return {
'duration': duration,
'results': results,
'observer_id': self.id,
'viewset': '{}.{}'.format(
self._request.viewset_class.__module__,
self._request.viewset_class.__name__,
),
'method': self._request.viewset_method,
'path': self._request.path,
'get': self._request.GET,
} | python | def _get_logging_extra(self, duration=None, results=None):
"""Extra information for logger."""
return {
'duration': duration,
'results': results,
'observer_id': self.id,
'viewset': '{}.{}'.format(
self._request.viewset_class.__module__,
self._request.viewset_class.__name__,
),
'method': self._request.viewset_method,
'path': self._request.path,
'get': self._request.GET,
} | [
"def",
"_get_logging_extra",
"(",
"self",
",",
"duration",
"=",
"None",
",",
"results",
"=",
"None",
")",
":",
"return",
"{",
"'duration'",
":",
"duration",
",",
"'results'",
":",
"results",
",",
"'observer_id'",
":",
"self",
".",
"id",
",",
"'viewset'",
... | Extra information for logger. | [
"Extra",
"information",
"for",
"logger",
"."
] | ddf3d899685a54b6bd0ae4b3789649a89340c59f | https://github.com/genialis/django-rest-framework-reactive/blob/ddf3d899685a54b6bd0ae4b3789649a89340c59f/src/rest_framework_reactive/observer.py#L98-L111 | train | 30,706 |
genialis/django-rest-framework-reactive | src/rest_framework_reactive/observer.py | QueryObserver._get_logging_id | def _get_logging_id(self):
"""Get logging identifier."""
return "{}.{}/{}".format(
self._request.viewset_class.__module__,
self._request.viewset_class.__name__,
self._request.viewset_method,
) | python | def _get_logging_id(self):
"""Get logging identifier."""
return "{}.{}/{}".format(
self._request.viewset_class.__module__,
self._request.viewset_class.__name__,
self._request.viewset_method,
) | [
"def",
"_get_logging_id",
"(",
"self",
")",
":",
"return",
"\"{}.{}/{}\"",
".",
"format",
"(",
"self",
".",
"_request",
".",
"viewset_class",
".",
"__module__",
",",
"self",
".",
"_request",
".",
"viewset_class",
".",
"__name__",
",",
"self",
".",
"_request"... | Get logging identifier. | [
"Get",
"logging",
"identifier",
"."
] | ddf3d899685a54b6bd0ae4b3789649a89340c59f | https://github.com/genialis/django-rest-framework-reactive/blob/ddf3d899685a54b6bd0ae4b3789649a89340c59f/src/rest_framework_reactive/observer.py#L113-L119 | train | 30,707 |
genialis/django-rest-framework-reactive | src/rest_framework_reactive/observer.py | QueryObserver._warning | def _warning(self, msg, duration=None, results=None):
"""Log warnings."""
logger.warning(
"{} ({})".format(msg, self._get_logging_id()),
extra=self._get_logging_extra(duration=duration, results=results),
) | python | def _warning(self, msg, duration=None, results=None):
"""Log warnings."""
logger.warning(
"{} ({})".format(msg, self._get_logging_id()),
extra=self._get_logging_extra(duration=duration, results=results),
) | [
"def",
"_warning",
"(",
"self",
",",
"msg",
",",
"duration",
"=",
"None",
",",
"results",
"=",
"None",
")",
":",
"logger",
".",
"warning",
"(",
"\"{} ({})\"",
".",
"format",
"(",
"msg",
",",
"self",
".",
"_get_logging_id",
"(",
")",
")",
",",
"extra"... | Log warnings. | [
"Log",
"warnings",
"."
] | ddf3d899685a54b6bd0ae4b3789649a89340c59f | https://github.com/genialis/django-rest-framework-reactive/blob/ddf3d899685a54b6bd0ae4b3789649a89340c59f/src/rest_framework_reactive/observer.py#L121-L126 | train | 30,708 |
genialis/django-rest-framework-reactive | src/rest_framework_reactive/observer.py | QueryObserver.evaluate | async def evaluate(self):
"""Evaluate the query observer.
:param return_emitted: True if the emitted diffs should be returned (testing only)
"""
@database_sync_to_async
def remove_subscribers():
models.Observer.subscribers.through.objects.filter(
observer_id=self.id
).delete()
@database_sync_to_async
def get_subscriber_sessions():
return list(
models.Observer.subscribers.through.objects.filter(observer_id=self.id)
.distinct('subscriber_id')
.values_list('subscriber_id', flat=True)
)
try:
settings = get_queryobserver_settings()
start = time.time()
# Evaluate the observer
added, changed, removed = await database_sync_to_async(self._evaluate)()
duration = time.time() - start
# Log slow observers.
if duration > settings['warnings']['max_processing_time']:
self._warning("Slow observed viewset", duration=duration)
# Remove subscribers of really slow observers.
if duration > settings['errors']['max_processing_time']:
logger.error(
"Removing subscribers to extremely slow observed viewset ({})".format(
self._get_logging_id()
),
extra=self._get_logging_extra(duration=duration),
)
await remove_subscribers()
if self._meta.change_detection == Options.CHANGE_DETECTION_POLL:
# Register poller.
await get_channel_layer().send(
CHANNEL_MAIN,
{
'type': TYPE_POLL,
'observer': self.id,
'interval': self._meta.poll_interval,
},
)
message = {
'type': TYPE_ITEM_UPDATE,
'observer': self.id,
'primary_key': self._meta.primary_key,
'added': added,
'changed': changed,
'removed': removed,
}
# Only generate notifications in case there were any changes.
if added or changed or removed:
for session_id in await get_subscriber_sessions():
await get_channel_layer().group_send(
GROUP_SESSIONS.format(session_id=session_id), message
)
except Exception:
logger.exception(
"Error while evaluating observer ({})".format(self._get_logging_id()),
extra=self._get_logging_extra(),
) | python | async def evaluate(self):
"""Evaluate the query observer.
:param return_emitted: True if the emitted diffs should be returned (testing only)
"""
@database_sync_to_async
def remove_subscribers():
models.Observer.subscribers.through.objects.filter(
observer_id=self.id
).delete()
@database_sync_to_async
def get_subscriber_sessions():
return list(
models.Observer.subscribers.through.objects.filter(observer_id=self.id)
.distinct('subscriber_id')
.values_list('subscriber_id', flat=True)
)
try:
settings = get_queryobserver_settings()
start = time.time()
# Evaluate the observer
added, changed, removed = await database_sync_to_async(self._evaluate)()
duration = time.time() - start
# Log slow observers.
if duration > settings['warnings']['max_processing_time']:
self._warning("Slow observed viewset", duration=duration)
# Remove subscribers of really slow observers.
if duration > settings['errors']['max_processing_time']:
logger.error(
"Removing subscribers to extremely slow observed viewset ({})".format(
self._get_logging_id()
),
extra=self._get_logging_extra(duration=duration),
)
await remove_subscribers()
if self._meta.change_detection == Options.CHANGE_DETECTION_POLL:
# Register poller.
await get_channel_layer().send(
CHANNEL_MAIN,
{
'type': TYPE_POLL,
'observer': self.id,
'interval': self._meta.poll_interval,
},
)
message = {
'type': TYPE_ITEM_UPDATE,
'observer': self.id,
'primary_key': self._meta.primary_key,
'added': added,
'changed': changed,
'removed': removed,
}
# Only generate notifications in case there were any changes.
if added or changed or removed:
for session_id in await get_subscriber_sessions():
await get_channel_layer().group_send(
GROUP_SESSIONS.format(session_id=session_id), message
)
except Exception:
logger.exception(
"Error while evaluating observer ({})".format(self._get_logging_id()),
extra=self._get_logging_extra(),
) | [
"async",
"def",
"evaluate",
"(",
"self",
")",
":",
"@",
"database_sync_to_async",
"def",
"remove_subscribers",
"(",
")",
":",
"models",
".",
"Observer",
".",
"subscribers",
".",
"through",
".",
"objects",
".",
"filter",
"(",
"observer_id",
"=",
"self",
".",
... | Evaluate the query observer.
:param return_emitted: True if the emitted diffs should be returned (testing only) | [
"Evaluate",
"the",
"query",
"observer",
"."
] | ddf3d899685a54b6bd0ae4b3789649a89340c59f | https://github.com/genialis/django-rest-framework-reactive/blob/ddf3d899685a54b6bd0ae4b3789649a89340c59f/src/rest_framework_reactive/observer.py#L252-L325 | train | 30,709 |
genialis/django-rest-framework-reactive | src/rest_framework_reactive/observer.py | QueryObserver._viewset_results | def _viewset_results(self):
"""Parse results from the viewset response."""
results = []
try:
response = self._viewset_method(
self._viewset.request, *self._request.args, **self._request.kwargs
)
if response.status_code == 200:
results = response.data
if not isinstance(results, list):
if isinstance(results, dict):
# XXX: This can incidently match if a single
# object has results key
if 'results' in results and isinstance(
results['results'], list
):
# Support paginated results.
results = results['results']
else:
results.setdefault(self._meta.primary_key, 1)
results = [collections.OrderedDict(results)]
else:
raise ValueError(
"Observable views must return a dictionary or a list of dictionaries!"
)
except Http404:
pass
except django_exceptions.ObjectDoesNotExist:
# The evaluation may fail when certain dependent objects (like users) are removed
# from the database. In this case, the observer is stopped.
pass
return results | python | def _viewset_results(self):
"""Parse results from the viewset response."""
results = []
try:
response = self._viewset_method(
self._viewset.request, *self._request.args, **self._request.kwargs
)
if response.status_code == 200:
results = response.data
if not isinstance(results, list):
if isinstance(results, dict):
# XXX: This can incidently match if a single
# object has results key
if 'results' in results and isinstance(
results['results'], list
):
# Support paginated results.
results = results['results']
else:
results.setdefault(self._meta.primary_key, 1)
results = [collections.OrderedDict(results)]
else:
raise ValueError(
"Observable views must return a dictionary or a list of dictionaries!"
)
except Http404:
pass
except django_exceptions.ObjectDoesNotExist:
# The evaluation may fail when certain dependent objects (like users) are removed
# from the database. In this case, the observer is stopped.
pass
return results | [
"def",
"_viewset_results",
"(",
"self",
")",
":",
"results",
"=",
"[",
"]",
"try",
":",
"response",
"=",
"self",
".",
"_viewset_method",
"(",
"self",
".",
"_viewset",
".",
"request",
",",
"*",
"self",
".",
"_request",
".",
"args",
",",
"*",
"*",
"sel... | Parse results from the viewset response. | [
"Parse",
"results",
"from",
"the",
"viewset",
"response",
"."
] | ddf3d899685a54b6bd0ae4b3789649a89340c59f | https://github.com/genialis/django-rest-framework-reactive/blob/ddf3d899685a54b6bd0ae4b3789649a89340c59f/src/rest_framework_reactive/observer.py#L327-L361 | train | 30,710 |
genialis/django-rest-framework-reactive | src/rest_framework_reactive/observer.py | QueryObserver._evaluate | def _evaluate(self, viewset_results=None):
"""Evaluate query observer.
:param viewset_results: Objects returned by the viewset query
"""
if viewset_results is None:
viewset_results = self._viewset_results()
try:
observer = models.Observer.objects.get(id=self.id)
# Do not evaluate the observer if there are no subscribers
if observer.subscribers.count() == 0:
return (None, None, None)
# Update last evaluation time.
models.Observer.objects.filter(id=self.id).update(
last_evaluation=timezone.now()
)
# Log viewsets with too much output.
max_result = get_queryobserver_settings()['warnings']['max_result_length']
if len(viewset_results) > max_result:
self._warning(
"Observed viewset returns too many results",
results=len(viewset_results),
)
new_results = collections.OrderedDict()
for order, item in enumerate(viewset_results):
if not isinstance(item, dict):
raise ValueError(
"Observable views must return a dictionary or a list of dictionaries!"
)
item = {'order': order, 'data': item}
try:
new_results[str(item['data'][self._meta.primary_key])] = item
except KeyError:
raise KeyError(
"Observable view did not return primary key field '{}'!".format(
self._meta.primary_key
)
)
# Process difference between old results and new results.
added, changed = [], []
new_ids = list(new_results.keys())
removed_qs = observer.items.exclude(primary_key__in=new_results.keys())
removed = list(removed_qs.values('order', 'data'))
maybe_changed_qs = observer.items.filter(primary_key__in=new_results.keys())
with transaction.atomic():
# Removed items.
removed_qs.delete()
# Defer unique ordering constraint before processing order updates.
# NOTE: The name of the constrait is generated by Django ORM.
with connection.cursor() as cursor:
cursor.execute(
"SET CONSTRAINTS rest_framework_reactive_item_observer_id_order_9b8adde6_uniq DEFERRED"
)
# Changed items.
for item_id, old_order, old_data in maybe_changed_qs.values_list(
'primary_key', 'order', 'data'
):
new_item = new_results[item_id]
new_ids.remove(item_id)
if new_item['data'] != old_data:
changed.append(new_item)
observer.items.filter(primary_key=item_id).update(
data=new_item['data'], order=new_item['order']
)
elif new_item['order'] != old_order:
# TODO: If only order has changed, don't transmit
# full data (needs frontend support).
changed.append(new_item)
observer.items.filter(primary_key=item_id).update(
order=new_item['order']
)
# Added items.
for item_id in new_ids:
item = new_results[item_id]
added.append(item)
observer.items.create(
primary_key=item_id, order=item['order'], data=item['data']
)
return (added, changed, removed)
except models.Observer.DoesNotExist:
# Observer removed, ignore evaluation
return (None, None, None) | python | def _evaluate(self, viewset_results=None):
"""Evaluate query observer.
:param viewset_results: Objects returned by the viewset query
"""
if viewset_results is None:
viewset_results = self._viewset_results()
try:
observer = models.Observer.objects.get(id=self.id)
# Do not evaluate the observer if there are no subscribers
if observer.subscribers.count() == 0:
return (None, None, None)
# Update last evaluation time.
models.Observer.objects.filter(id=self.id).update(
last_evaluation=timezone.now()
)
# Log viewsets with too much output.
max_result = get_queryobserver_settings()['warnings']['max_result_length']
if len(viewset_results) > max_result:
self._warning(
"Observed viewset returns too many results",
results=len(viewset_results),
)
new_results = collections.OrderedDict()
for order, item in enumerate(viewset_results):
if not isinstance(item, dict):
raise ValueError(
"Observable views must return a dictionary or a list of dictionaries!"
)
item = {'order': order, 'data': item}
try:
new_results[str(item['data'][self._meta.primary_key])] = item
except KeyError:
raise KeyError(
"Observable view did not return primary key field '{}'!".format(
self._meta.primary_key
)
)
# Process difference between old results and new results.
added, changed = [], []
new_ids = list(new_results.keys())
removed_qs = observer.items.exclude(primary_key__in=new_results.keys())
removed = list(removed_qs.values('order', 'data'))
maybe_changed_qs = observer.items.filter(primary_key__in=new_results.keys())
with transaction.atomic():
# Removed items.
removed_qs.delete()
# Defer unique ordering constraint before processing order updates.
# NOTE: The name of the constrait is generated by Django ORM.
with connection.cursor() as cursor:
cursor.execute(
"SET CONSTRAINTS rest_framework_reactive_item_observer_id_order_9b8adde6_uniq DEFERRED"
)
# Changed items.
for item_id, old_order, old_data in maybe_changed_qs.values_list(
'primary_key', 'order', 'data'
):
new_item = new_results[item_id]
new_ids.remove(item_id)
if new_item['data'] != old_data:
changed.append(new_item)
observer.items.filter(primary_key=item_id).update(
data=new_item['data'], order=new_item['order']
)
elif new_item['order'] != old_order:
# TODO: If only order has changed, don't transmit
# full data (needs frontend support).
changed.append(new_item)
observer.items.filter(primary_key=item_id).update(
order=new_item['order']
)
# Added items.
for item_id in new_ids:
item = new_results[item_id]
added.append(item)
observer.items.create(
primary_key=item_id, order=item['order'], data=item['data']
)
return (added, changed, removed)
except models.Observer.DoesNotExist:
# Observer removed, ignore evaluation
return (None, None, None) | [
"def",
"_evaluate",
"(",
"self",
",",
"viewset_results",
"=",
"None",
")",
":",
"if",
"viewset_results",
"is",
"None",
":",
"viewset_results",
"=",
"self",
".",
"_viewset_results",
"(",
")",
"try",
":",
"observer",
"=",
"models",
".",
"Observer",
".",
"obj... | Evaluate query observer.
:param viewset_results: Objects returned by the viewset query | [
"Evaluate",
"query",
"observer",
"."
] | ddf3d899685a54b6bd0ae4b3789649a89340c59f | https://github.com/genialis/django-rest-framework-reactive/blob/ddf3d899685a54b6bd0ae4b3789649a89340c59f/src/rest_framework_reactive/observer.py#L363-L459 | train | 30,711 |
genialis/django-rest-framework-reactive | src/rest_framework_reactive/decorators.py | observable | def observable(
_method_or_viewset=None, poll_interval=None, primary_key=None, dependencies=None
):
"""Make ViewSet or ViewSet method observable.
Decorating a ViewSet class is the same as decorating its `list` method.
If decorated method returns a response containing a list of items, it must
use the provided `LimitOffsetPagination` for any pagination. In case a
non-list response is returned, the resulting item will be wrapped into a
list.
When multiple decorators are used, `observable` must be the first one to be
applied as it needs access to the method name.
:param poll_interval: Configure given observable as a polling observable
:param primary_key: Primary key for tracking observable items
:param dependencies: List of ORM to register as dependencies for
orm_notify. If None the observer will subscribe to notifications from
the queryset model.
"""
if poll_interval and dependencies:
raise ValueError('Only one of poll_interval and dependencies arguments allowed')
def decorator_observable(method_or_viewset):
if inspect.isclass(method_or_viewset):
list_method = getattr(method_or_viewset, 'list', None)
if list_method is not None:
method_or_viewset.list = observable(list_method)
return method_or_viewset
# Do not decorate an already observable method twice.
if getattr(method_or_viewset, 'is_observable', False):
return method_or_viewset
@functools.wraps(method_or_viewset)
def wrapper(self, request, *args, **kwargs):
if observer_request.OBSERVABLE_QUERY_PARAMETER in request.query_params:
# TODO: Validate the session identifier.
session_id = request.query_params[
observer_request.OBSERVABLE_QUERY_PARAMETER
]
# Create request and subscribe the session to given observer.
request = observer_request.Request(
self.__class__, method_or_viewset.__name__, request, args, kwargs
)
# Initialize observer and subscribe.
instance = observer.QueryObserver(request)
data = instance.subscribe(session_id, dependencies)
return response.Response({'observer': instance.id, 'items': data})
else:
# Non-reactive API.
return method_or_viewset(self, request, *args, **kwargs)
wrapper.is_observable = True
if poll_interval is not None:
wrapper.observable_change_detection = observer.Options.CHANGE_DETECTION_POLL
wrapper.observable_poll_interval = poll_interval
if primary_key is not None:
wrapper.observable_primary_key = primary_key
return wrapper
if _method_or_viewset is None:
return decorator_observable
else:
return decorator_observable(_method_or_viewset) | python | def observable(
_method_or_viewset=None, poll_interval=None, primary_key=None, dependencies=None
):
"""Make ViewSet or ViewSet method observable.
Decorating a ViewSet class is the same as decorating its `list` method.
If decorated method returns a response containing a list of items, it must
use the provided `LimitOffsetPagination` for any pagination. In case a
non-list response is returned, the resulting item will be wrapped into a
list.
When multiple decorators are used, `observable` must be the first one to be
applied as it needs access to the method name.
:param poll_interval: Configure given observable as a polling observable
:param primary_key: Primary key for tracking observable items
:param dependencies: List of ORM to register as dependencies for
orm_notify. If None the observer will subscribe to notifications from
the queryset model.
"""
if poll_interval and dependencies:
raise ValueError('Only one of poll_interval and dependencies arguments allowed')
def decorator_observable(method_or_viewset):
if inspect.isclass(method_or_viewset):
list_method = getattr(method_or_viewset, 'list', None)
if list_method is not None:
method_or_viewset.list = observable(list_method)
return method_or_viewset
# Do not decorate an already observable method twice.
if getattr(method_or_viewset, 'is_observable', False):
return method_or_viewset
@functools.wraps(method_or_viewset)
def wrapper(self, request, *args, **kwargs):
if observer_request.OBSERVABLE_QUERY_PARAMETER in request.query_params:
# TODO: Validate the session identifier.
session_id = request.query_params[
observer_request.OBSERVABLE_QUERY_PARAMETER
]
# Create request and subscribe the session to given observer.
request = observer_request.Request(
self.__class__, method_or_viewset.__name__, request, args, kwargs
)
# Initialize observer and subscribe.
instance = observer.QueryObserver(request)
data = instance.subscribe(session_id, dependencies)
return response.Response({'observer': instance.id, 'items': data})
else:
# Non-reactive API.
return method_or_viewset(self, request, *args, **kwargs)
wrapper.is_observable = True
if poll_interval is not None:
wrapper.observable_change_detection = observer.Options.CHANGE_DETECTION_POLL
wrapper.observable_poll_interval = poll_interval
if primary_key is not None:
wrapper.observable_primary_key = primary_key
return wrapper
if _method_or_viewset is None:
return decorator_observable
else:
return decorator_observable(_method_or_viewset) | [
"def",
"observable",
"(",
"_method_or_viewset",
"=",
"None",
",",
"poll_interval",
"=",
"None",
",",
"primary_key",
"=",
"None",
",",
"dependencies",
"=",
"None",
")",
":",
"if",
"poll_interval",
"and",
"dependencies",
":",
"raise",
"ValueError",
"(",
"'Only o... | Make ViewSet or ViewSet method observable.
Decorating a ViewSet class is the same as decorating its `list` method.
If decorated method returns a response containing a list of items, it must
use the provided `LimitOffsetPagination` for any pagination. In case a
non-list response is returned, the resulting item will be wrapped into a
list.
When multiple decorators are used, `observable` must be the first one to be
applied as it needs access to the method name.
:param poll_interval: Configure given observable as a polling observable
:param primary_key: Primary key for tracking observable items
:param dependencies: List of ORM to register as dependencies for
orm_notify. If None the observer will subscribe to notifications from
the queryset model. | [
"Make",
"ViewSet",
"or",
"ViewSet",
"method",
"observable",
"."
] | ddf3d899685a54b6bd0ae4b3789649a89340c59f | https://github.com/genialis/django-rest-framework-reactive/blob/ddf3d899685a54b6bd0ae4b3789649a89340c59f/src/rest_framework_reactive/decorators.py#L10-L84 | train | 30,712 |
jrigden/pyPodcastParser | pyPodcastParser/Podcast.py | Podcast.set_is_valid_rss | def set_is_valid_rss(self):
"""Check to if this is actually a valid RSS feed"""
if self.title and self.link and self.description:
self.is_valid_rss = True
else:
self.is_valid_rss = False | python | def set_is_valid_rss(self):
"""Check to if this is actually a valid RSS feed"""
if self.title and self.link and self.description:
self.is_valid_rss = True
else:
self.is_valid_rss = False | [
"def",
"set_is_valid_rss",
"(",
"self",
")",
":",
"if",
"self",
".",
"title",
"and",
"self",
".",
"link",
"and",
"self",
".",
"description",
":",
"self",
".",
"is_valid_rss",
"=",
"True",
"else",
":",
"self",
".",
"is_valid_rss",
"=",
"False"
] | Check to if this is actually a valid RSS feed | [
"Check",
"to",
"if",
"this",
"is",
"actually",
"a",
"valid",
"RSS",
"feed"
] | b21e027bb56ec77986d76fc1990f4e420c6de869 | https://github.com/jrigden/pyPodcastParser/blob/b21e027bb56ec77986d76fc1990f4e420c6de869/pyPodcastParser/Podcast.py#L105-L110 | train | 30,713 |
jrigden/pyPodcastParser | pyPodcastParser/Podcast.py | Podcast.set_extended_elements | def set_extended_elements(self):
"""Parses and sets non required elements"""
self.set_creative_commons()
self.set_owner()
self.set_subtitle()
self.set_summary() | python | def set_extended_elements(self):
"""Parses and sets non required elements"""
self.set_creative_commons()
self.set_owner()
self.set_subtitle()
self.set_summary() | [
"def",
"set_extended_elements",
"(",
"self",
")",
":",
"self",
".",
"set_creative_commons",
"(",
")",
"self",
".",
"set_owner",
"(",
")",
"self",
".",
"set_subtitle",
"(",
")",
"self",
".",
"set_summary",
"(",
")"
] | Parses and sets non required elements | [
"Parses",
"and",
"sets",
"non",
"required",
"elements"
] | b21e027bb56ec77986d76fc1990f4e420c6de869 | https://github.com/jrigden/pyPodcastParser/blob/b21e027bb56ec77986d76fc1990f4e420c6de869/pyPodcastParser/Podcast.py#L160-L165 | train | 30,714 |
jrigden/pyPodcastParser | pyPodcastParser/Podcast.py | Podcast.set_itunes | def set_itunes(self):
"""Sets elements related to itunes"""
self.set_itunes_author_name()
self.set_itunes_block()
self.set_itunes_complete()
self.set_itunes_explicit()
self.set_itune_image()
self.set_itunes_keywords()
self.set_itunes_new_feed_url()
self.set_itunes_categories()
self.set_items() | python | def set_itunes(self):
"""Sets elements related to itunes"""
self.set_itunes_author_name()
self.set_itunes_block()
self.set_itunes_complete()
self.set_itunes_explicit()
self.set_itune_image()
self.set_itunes_keywords()
self.set_itunes_new_feed_url()
self.set_itunes_categories()
self.set_items() | [
"def",
"set_itunes",
"(",
"self",
")",
":",
"self",
".",
"set_itunes_author_name",
"(",
")",
"self",
".",
"set_itunes_block",
"(",
")",
"self",
".",
"set_itunes_complete",
"(",
")",
"self",
".",
"set_itunes_explicit",
"(",
")",
"self",
".",
"set_itune_image",
... | Sets elements related to itunes | [
"Sets",
"elements",
"related",
"to",
"itunes"
] | b21e027bb56ec77986d76fc1990f4e420c6de869 | https://github.com/jrigden/pyPodcastParser/blob/b21e027bb56ec77986d76fc1990f4e420c6de869/pyPodcastParser/Podcast.py#L167-L177 | train | 30,715 |
jrigden/pyPodcastParser | pyPodcastParser/Podcast.py | Podcast.set_optional_elements | def set_optional_elements(self):
"""Sets elements considered option by RSS spec"""
self.set_categories()
self.set_copyright()
self.set_generator()
self.set_image()
self.set_language()
self.set_last_build_date()
self.set_managing_editor()
self.set_published_date()
self.set_pubsubhubbub()
self.set_ttl()
self.set_web_master() | python | def set_optional_elements(self):
"""Sets elements considered option by RSS spec"""
self.set_categories()
self.set_copyright()
self.set_generator()
self.set_image()
self.set_language()
self.set_last_build_date()
self.set_managing_editor()
self.set_published_date()
self.set_pubsubhubbub()
self.set_ttl()
self.set_web_master() | [
"def",
"set_optional_elements",
"(",
"self",
")",
":",
"self",
".",
"set_categories",
"(",
")",
"self",
".",
"set_copyright",
"(",
")",
"self",
".",
"set_generator",
"(",
")",
"self",
".",
"set_image",
"(",
")",
"self",
".",
"set_language",
"(",
")",
"se... | Sets elements considered option by RSS spec | [
"Sets",
"elements",
"considered",
"option",
"by",
"RSS",
"spec"
] | b21e027bb56ec77986d76fc1990f4e420c6de869 | https://github.com/jrigden/pyPodcastParser/blob/b21e027bb56ec77986d76fc1990f4e420c6de869/pyPodcastParser/Podcast.py#L179-L191 | train | 30,716 |
jrigden/pyPodcastParser | pyPodcastParser/Podcast.py | Podcast.set_soup | def set_soup(self):
"""Sets soup and strips items"""
self.soup = BeautifulSoup(self.feed_content, "html.parser")
for item in self.soup.findAll('item'):
item.decompose()
for image in self.soup.findAll('image'):
image.decompose() | python | def set_soup(self):
"""Sets soup and strips items"""
self.soup = BeautifulSoup(self.feed_content, "html.parser")
for item in self.soup.findAll('item'):
item.decompose()
for image in self.soup.findAll('image'):
image.decompose() | [
"def",
"set_soup",
"(",
"self",
")",
":",
"self",
".",
"soup",
"=",
"BeautifulSoup",
"(",
"self",
".",
"feed_content",
",",
"\"html.parser\"",
")",
"for",
"item",
"in",
"self",
".",
"soup",
".",
"findAll",
"(",
"'item'",
")",
":",
"item",
".",
"decompo... | Sets soup and strips items | [
"Sets",
"soup",
"and",
"strips",
"items"
] | b21e027bb56ec77986d76fc1990f4e420c6de869 | https://github.com/jrigden/pyPodcastParser/blob/b21e027bb56ec77986d76fc1990f4e420c6de869/pyPodcastParser/Podcast.py#L199-L205 | train | 30,717 |
jrigden/pyPodcastParser | pyPodcastParser/Podcast.py | Podcast.set_categories | def set_categories(self):
"""Parses and set feed categories"""
self.categories = []
temp_categories = self.soup.findAll('category')
for category in temp_categories:
category_text = category.string
self.categories.append(category_text) | python | def set_categories(self):
"""Parses and set feed categories"""
self.categories = []
temp_categories = self.soup.findAll('category')
for category in temp_categories:
category_text = category.string
self.categories.append(category_text) | [
"def",
"set_categories",
"(",
"self",
")",
":",
"self",
".",
"categories",
"=",
"[",
"]",
"temp_categories",
"=",
"self",
".",
"soup",
".",
"findAll",
"(",
"'category'",
")",
"for",
"category",
"in",
"temp_categories",
":",
"category_text",
"=",
"category",
... | Parses and set feed categories | [
"Parses",
"and",
"set",
"feed",
"categories"
] | b21e027bb56ec77986d76fc1990f4e420c6de869 | https://github.com/jrigden/pyPodcastParser/blob/b21e027bb56ec77986d76fc1990f4e420c6de869/pyPodcastParser/Podcast.py#L219-L225 | train | 30,718 |
jrigden/pyPodcastParser | pyPodcastParser/Podcast.py | Podcast.count_items | def count_items(self):
"""Counts Items in full_soup and soup. For debugging"""
soup_items = self.soup.findAll('item')
full_soup_items = self.full_soup.findAll('item')
return len(soup_items), len(full_soup_items) | python | def count_items(self):
"""Counts Items in full_soup and soup. For debugging"""
soup_items = self.soup.findAll('item')
full_soup_items = self.full_soup.findAll('item')
return len(soup_items), len(full_soup_items) | [
"def",
"count_items",
"(",
"self",
")",
":",
"soup_items",
"=",
"self",
".",
"soup",
".",
"findAll",
"(",
"'item'",
")",
"full_soup_items",
"=",
"self",
".",
"full_soup",
".",
"findAll",
"(",
"'item'",
")",
"return",
"len",
"(",
"soup_items",
")",
",",
... | Counts Items in full_soup and soup. For debugging | [
"Counts",
"Items",
"in",
"full_soup",
"and",
"soup",
".",
"For",
"debugging"
] | b21e027bb56ec77986d76fc1990f4e420c6de869 | https://github.com/jrigden/pyPodcastParser/blob/b21e027bb56ec77986d76fc1990f4e420c6de869/pyPodcastParser/Podcast.py#L227-L231 | train | 30,719 |
jrigden/pyPodcastParser | pyPodcastParser/Podcast.py | Podcast.set_copyright | def set_copyright(self):
"""Parses copyright and set value"""
try:
self.copyright = self.soup.find('copyright').string
except AttributeError:
self.copyright = None | python | def set_copyright(self):
"""Parses copyright and set value"""
try:
self.copyright = self.soup.find('copyright').string
except AttributeError:
self.copyright = None | [
"def",
"set_copyright",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"copyright",
"=",
"self",
".",
"soup",
".",
"find",
"(",
"'copyright'",
")",
".",
"string",
"except",
"AttributeError",
":",
"self",
".",
"copyright",
"=",
"None"
] | Parses copyright and set value | [
"Parses",
"copyright",
"and",
"set",
"value"
] | b21e027bb56ec77986d76fc1990f4e420c6de869 | https://github.com/jrigden/pyPodcastParser/blob/b21e027bb56ec77986d76fc1990f4e420c6de869/pyPodcastParser/Podcast.py#L233-L238 | train | 30,720 |
jrigden/pyPodcastParser | pyPodcastParser/Podcast.py | Podcast.set_creative_commons | def set_creative_commons(self):
"""Parses creative commons for item and sets value"""
try:
self.creative_commons = self.soup.find(
'creativecommons:license').string
except AttributeError:
self.creative_commons = None | python | def set_creative_commons(self):
"""Parses creative commons for item and sets value"""
try:
self.creative_commons = self.soup.find(
'creativecommons:license').string
except AttributeError:
self.creative_commons = None | [
"def",
"set_creative_commons",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"creative_commons",
"=",
"self",
".",
"soup",
".",
"find",
"(",
"'creativecommons:license'",
")",
".",
"string",
"except",
"AttributeError",
":",
"self",
".",
"creative_commons",
"=... | Parses creative commons for item and sets value | [
"Parses",
"creative",
"commons",
"for",
"item",
"and",
"sets",
"value"
] | b21e027bb56ec77986d76fc1990f4e420c6de869 | https://github.com/jrigden/pyPodcastParser/blob/b21e027bb56ec77986d76fc1990f4e420c6de869/pyPodcastParser/Podcast.py#L240-L246 | train | 30,721 |
jrigden/pyPodcastParser | pyPodcastParser/Podcast.py | Podcast.set_description | def set_description(self):
"""Parses description and sets value"""
try:
self.description = self.soup.find('description').string
except AttributeError:
self.description = None | python | def set_description(self):
"""Parses description and sets value"""
try:
self.description = self.soup.find('description').string
except AttributeError:
self.description = None | [
"def",
"set_description",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"description",
"=",
"self",
".",
"soup",
".",
"find",
"(",
"'description'",
")",
".",
"string",
"except",
"AttributeError",
":",
"self",
".",
"description",
"=",
"None"
] | Parses description and sets value | [
"Parses",
"description",
"and",
"sets",
"value"
] | b21e027bb56ec77986d76fc1990f4e420c6de869 | https://github.com/jrigden/pyPodcastParser/blob/b21e027bb56ec77986d76fc1990f4e420c6de869/pyPodcastParser/Podcast.py#L248-L253 | train | 30,722 |
jrigden/pyPodcastParser | pyPodcastParser/Podcast.py | Podcast.set_generator | def set_generator(self):
"""Parses feed generator and sets value"""
try:
self.generator = self.soup.find('generator').string
except AttributeError:
self.generator = None | python | def set_generator(self):
"""Parses feed generator and sets value"""
try:
self.generator = self.soup.find('generator').string
except AttributeError:
self.generator = None | [
"def",
"set_generator",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"generator",
"=",
"self",
".",
"soup",
".",
"find",
"(",
"'generator'",
")",
".",
"string",
"except",
"AttributeError",
":",
"self",
".",
"generator",
"=",
"None"
] | Parses feed generator and sets value | [
"Parses",
"feed",
"generator",
"and",
"sets",
"value"
] | b21e027bb56ec77986d76fc1990f4e420c6de869 | https://github.com/jrigden/pyPodcastParser/blob/b21e027bb56ec77986d76fc1990f4e420c6de869/pyPodcastParser/Podcast.py#L255-L260 | train | 30,723 |
jrigden/pyPodcastParser | pyPodcastParser/Podcast.py | Podcast.set_image | def set_image(self):
"""Parses image element and set values"""
temp_soup = self.full_soup
for item in temp_soup.findAll('item'):
item.decompose()
image = temp_soup.find('image')
try:
self.image_title = image.find('title').string
except AttributeError:
self.image_title = None
try:
self.image_url = image.find('url').string
except AttributeError:
self.image_url = None
try:
self.image_link = image.find('link').string
except AttributeError:
self.image_link = None
try:
self.image_width = image.find('width').string
except AttributeError:
self.image_width = None
try:
self.image_height = image.find('height').string
except AttributeError:
self.image_height = None | python | def set_image(self):
"""Parses image element and set values"""
temp_soup = self.full_soup
for item in temp_soup.findAll('item'):
item.decompose()
image = temp_soup.find('image')
try:
self.image_title = image.find('title').string
except AttributeError:
self.image_title = None
try:
self.image_url = image.find('url').string
except AttributeError:
self.image_url = None
try:
self.image_link = image.find('link').string
except AttributeError:
self.image_link = None
try:
self.image_width = image.find('width').string
except AttributeError:
self.image_width = None
try:
self.image_height = image.find('height').string
except AttributeError:
self.image_height = None | [
"def",
"set_image",
"(",
"self",
")",
":",
"temp_soup",
"=",
"self",
".",
"full_soup",
"for",
"item",
"in",
"temp_soup",
".",
"findAll",
"(",
"'item'",
")",
":",
"item",
".",
"decompose",
"(",
")",
"image",
"=",
"temp_soup",
".",
"find",
"(",
"'image'"... | Parses image element and set values | [
"Parses",
"image",
"element",
"and",
"set",
"values"
] | b21e027bb56ec77986d76fc1990f4e420c6de869 | https://github.com/jrigden/pyPodcastParser/blob/b21e027bb56ec77986d76fc1990f4e420c6de869/pyPodcastParser/Podcast.py#L262-L287 | train | 30,724 |
jrigden/pyPodcastParser | pyPodcastParser/Podcast.py | Podcast.set_itunes_author_name | def set_itunes_author_name(self):
"""Parses author name from itunes tags and sets value"""
try:
self.itunes_author_name = self.soup.find('itunes:author').string
except AttributeError:
self.itunes_author_name = None | python | def set_itunes_author_name(self):
"""Parses author name from itunes tags and sets value"""
try:
self.itunes_author_name = self.soup.find('itunes:author').string
except AttributeError:
self.itunes_author_name = None | [
"def",
"set_itunes_author_name",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"itunes_author_name",
"=",
"self",
".",
"soup",
".",
"find",
"(",
"'itunes:author'",
")",
".",
"string",
"except",
"AttributeError",
":",
"self",
".",
"itunes_author_name",
"=",
... | Parses author name from itunes tags and sets value | [
"Parses",
"author",
"name",
"from",
"itunes",
"tags",
"and",
"sets",
"value"
] | b21e027bb56ec77986d76fc1990f4e420c6de869 | https://github.com/jrigden/pyPodcastParser/blob/b21e027bb56ec77986d76fc1990f4e420c6de869/pyPodcastParser/Podcast.py#L289-L294 | train | 30,725 |
jrigden/pyPodcastParser | pyPodcastParser/Podcast.py | Podcast.set_itunes_block | def set_itunes_block(self):
"""Check and see if podcast is blocked from iTunes and sets value"""
try:
block = self.soup.find('itunes:block').string.lower()
except AttributeError:
block = ""
if block == "yes":
self.itunes_block = True
else:
self.itunes_block = False | python | def set_itunes_block(self):
"""Check and see if podcast is blocked from iTunes and sets value"""
try:
block = self.soup.find('itunes:block').string.lower()
except AttributeError:
block = ""
if block == "yes":
self.itunes_block = True
else:
self.itunes_block = False | [
"def",
"set_itunes_block",
"(",
"self",
")",
":",
"try",
":",
"block",
"=",
"self",
".",
"soup",
".",
"find",
"(",
"'itunes:block'",
")",
".",
"string",
".",
"lower",
"(",
")",
"except",
"AttributeError",
":",
"block",
"=",
"\"\"",
"if",
"block",
"==",... | Check and see if podcast is blocked from iTunes and sets value | [
"Check",
"and",
"see",
"if",
"podcast",
"is",
"blocked",
"from",
"iTunes",
"and",
"sets",
"value"
] | b21e027bb56ec77986d76fc1990f4e420c6de869 | https://github.com/jrigden/pyPodcastParser/blob/b21e027bb56ec77986d76fc1990f4e420c6de869/pyPodcastParser/Podcast.py#L296-L305 | train | 30,726 |
jrigden/pyPodcastParser | pyPodcastParser/Podcast.py | Podcast.set_itunes_categories | def set_itunes_categories(self):
"""Parses and set itunes categories"""
self.itunes_categories = []
temp_categories = self.soup.findAll('itunes:category')
for category in temp_categories:
category_text = category.get('text')
self.itunes_categories.append(category_text) | python | def set_itunes_categories(self):
"""Parses and set itunes categories"""
self.itunes_categories = []
temp_categories = self.soup.findAll('itunes:category')
for category in temp_categories:
category_text = category.get('text')
self.itunes_categories.append(category_text) | [
"def",
"set_itunes_categories",
"(",
"self",
")",
":",
"self",
".",
"itunes_categories",
"=",
"[",
"]",
"temp_categories",
"=",
"self",
".",
"soup",
".",
"findAll",
"(",
"'itunes:category'",
")",
"for",
"category",
"in",
"temp_categories",
":",
"category_text",
... | Parses and set itunes categories | [
"Parses",
"and",
"set",
"itunes",
"categories"
] | b21e027bb56ec77986d76fc1990f4e420c6de869 | https://github.com/jrigden/pyPodcastParser/blob/b21e027bb56ec77986d76fc1990f4e420c6de869/pyPodcastParser/Podcast.py#L307-L313 | train | 30,727 |
jrigden/pyPodcastParser | pyPodcastParser/Podcast.py | Podcast.set_itunes_complete | def set_itunes_complete(self):
"""Parses complete from itunes tags and sets value"""
try:
self.itunes_complete = self.soup.find('itunes:complete').string
self.itunes_complete = self.itunes_complete.lower()
except AttributeError:
self.itunes_complete = None | python | def set_itunes_complete(self):
"""Parses complete from itunes tags and sets value"""
try:
self.itunes_complete = self.soup.find('itunes:complete').string
self.itunes_complete = self.itunes_complete.lower()
except AttributeError:
self.itunes_complete = None | [
"def",
"set_itunes_complete",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"itunes_complete",
"=",
"self",
".",
"soup",
".",
"find",
"(",
"'itunes:complete'",
")",
".",
"string",
"self",
".",
"itunes_complete",
"=",
"self",
".",
"itunes_complete",
".",
... | Parses complete from itunes tags and sets value | [
"Parses",
"complete",
"from",
"itunes",
"tags",
"and",
"sets",
"value"
] | b21e027bb56ec77986d76fc1990f4e420c6de869 | https://github.com/jrigden/pyPodcastParser/blob/b21e027bb56ec77986d76fc1990f4e420c6de869/pyPodcastParser/Podcast.py#L315-L321 | train | 30,728 |
jrigden/pyPodcastParser | pyPodcastParser/Podcast.py | Podcast.set_itunes_explicit | def set_itunes_explicit(self):
"""Parses explicit from itunes tags and sets value"""
try:
self.itunes_explicit = self.soup.find('itunes:explicit').string
self.itunes_explicit = self.itunes_explicit.lower()
except AttributeError:
self.itunes_explicit = None | python | def set_itunes_explicit(self):
"""Parses explicit from itunes tags and sets value"""
try:
self.itunes_explicit = self.soup.find('itunes:explicit').string
self.itunes_explicit = self.itunes_explicit.lower()
except AttributeError:
self.itunes_explicit = None | [
"def",
"set_itunes_explicit",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"itunes_explicit",
"=",
"self",
".",
"soup",
".",
"find",
"(",
"'itunes:explicit'",
")",
".",
"string",
"self",
".",
"itunes_explicit",
"=",
"self",
".",
"itunes_explicit",
".",
... | Parses explicit from itunes tags and sets value | [
"Parses",
"explicit",
"from",
"itunes",
"tags",
"and",
"sets",
"value"
] | b21e027bb56ec77986d76fc1990f4e420c6de869 | https://github.com/jrigden/pyPodcastParser/blob/b21e027bb56ec77986d76fc1990f4e420c6de869/pyPodcastParser/Podcast.py#L323-L329 | train | 30,729 |
jrigden/pyPodcastParser | pyPodcastParser/Podcast.py | Podcast.set_itune_image | def set_itune_image(self):
"""Parses itunes images and set url as value"""
try:
self.itune_image = self.soup.find('itunes:image').get('href')
except AttributeError:
self.itune_image = None | python | def set_itune_image(self):
"""Parses itunes images and set url as value"""
try:
self.itune_image = self.soup.find('itunes:image').get('href')
except AttributeError:
self.itune_image = None | [
"def",
"set_itune_image",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"itune_image",
"=",
"self",
".",
"soup",
".",
"find",
"(",
"'itunes:image'",
")",
".",
"get",
"(",
"'href'",
")",
"except",
"AttributeError",
":",
"self",
".",
"itune_image",
"=",
... | Parses itunes images and set url as value | [
"Parses",
"itunes",
"images",
"and",
"set",
"url",
"as",
"value"
] | b21e027bb56ec77986d76fc1990f4e420c6de869 | https://github.com/jrigden/pyPodcastParser/blob/b21e027bb56ec77986d76fc1990f4e420c6de869/pyPodcastParser/Podcast.py#L331-L336 | train | 30,730 |
jrigden/pyPodcastParser | pyPodcastParser/Podcast.py | Podcast.set_itunes_keywords | def set_itunes_keywords(self):
"""Parses itunes keywords and set value"""
try:
keywords = self.soup.find('itunes:keywords').string
except AttributeError:
keywords = None
try:
self.itunes_keywords = [keyword.strip()
for keyword in keywords.split(',')]
self.itunes_keywords = list(set(self.itunes_keywords))
except AttributeError:
self.itunes_keywords = [] | python | def set_itunes_keywords(self):
"""Parses itunes keywords and set value"""
try:
keywords = self.soup.find('itunes:keywords').string
except AttributeError:
keywords = None
try:
self.itunes_keywords = [keyword.strip()
for keyword in keywords.split(',')]
self.itunes_keywords = list(set(self.itunes_keywords))
except AttributeError:
self.itunes_keywords = [] | [
"def",
"set_itunes_keywords",
"(",
"self",
")",
":",
"try",
":",
"keywords",
"=",
"self",
".",
"soup",
".",
"find",
"(",
"'itunes:keywords'",
")",
".",
"string",
"except",
"AttributeError",
":",
"keywords",
"=",
"None",
"try",
":",
"self",
".",
"itunes_key... | Parses itunes keywords and set value | [
"Parses",
"itunes",
"keywords",
"and",
"set",
"value"
] | b21e027bb56ec77986d76fc1990f4e420c6de869 | https://github.com/jrigden/pyPodcastParser/blob/b21e027bb56ec77986d76fc1990f4e420c6de869/pyPodcastParser/Podcast.py#L338-L349 | train | 30,731 |
jrigden/pyPodcastParser | pyPodcastParser/Podcast.py | Podcast.set_itunes_new_feed_url | def set_itunes_new_feed_url(self):
"""Parses new feed url from itunes tags and sets value"""
try:
self.itunes_new_feed_url = self.soup.find(
'itunes:new-feed-url').string
except AttributeError:
self.itunes_new_feed_url = None | python | def set_itunes_new_feed_url(self):
"""Parses new feed url from itunes tags and sets value"""
try:
self.itunes_new_feed_url = self.soup.find(
'itunes:new-feed-url').string
except AttributeError:
self.itunes_new_feed_url = None | [
"def",
"set_itunes_new_feed_url",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"itunes_new_feed_url",
"=",
"self",
".",
"soup",
".",
"find",
"(",
"'itunes:new-feed-url'",
")",
".",
"string",
"except",
"AttributeError",
":",
"self",
".",
"itunes_new_feed_url",... | Parses new feed url from itunes tags and sets value | [
"Parses",
"new",
"feed",
"url",
"from",
"itunes",
"tags",
"and",
"sets",
"value"
] | b21e027bb56ec77986d76fc1990f4e420c6de869 | https://github.com/jrigden/pyPodcastParser/blob/b21e027bb56ec77986d76fc1990f4e420c6de869/pyPodcastParser/Podcast.py#L351-L357 | train | 30,732 |
jrigden/pyPodcastParser | pyPodcastParser/Podcast.py | Podcast.set_language | def set_language(self):
"""Parses feed language and set value"""
try:
self.language = self.soup.find('language').string
except AttributeError:
self.language = None | python | def set_language(self):
"""Parses feed language and set value"""
try:
self.language = self.soup.find('language').string
except AttributeError:
self.language = None | [
"def",
"set_language",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"language",
"=",
"self",
".",
"soup",
".",
"find",
"(",
"'language'",
")",
".",
"string",
"except",
"AttributeError",
":",
"self",
".",
"language",
"=",
"None"
] | Parses feed language and set value | [
"Parses",
"feed",
"language",
"and",
"set",
"value"
] | b21e027bb56ec77986d76fc1990f4e420c6de869 | https://github.com/jrigden/pyPodcastParser/blob/b21e027bb56ec77986d76fc1990f4e420c6de869/pyPodcastParser/Podcast.py#L359-L364 | train | 30,733 |
jrigden/pyPodcastParser | pyPodcastParser/Podcast.py | Podcast.set_last_build_date | def set_last_build_date(self):
"""Parses last build date and set value"""
try:
self.last_build_date = self.soup.find('lastbuilddate').string
except AttributeError:
self.last_build_date = None | python | def set_last_build_date(self):
"""Parses last build date and set value"""
try:
self.last_build_date = self.soup.find('lastbuilddate').string
except AttributeError:
self.last_build_date = None | [
"def",
"set_last_build_date",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"last_build_date",
"=",
"self",
".",
"soup",
".",
"find",
"(",
"'lastbuilddate'",
")",
".",
"string",
"except",
"AttributeError",
":",
"self",
".",
"last_build_date",
"=",
"None"
] | Parses last build date and set value | [
"Parses",
"last",
"build",
"date",
"and",
"set",
"value"
] | b21e027bb56ec77986d76fc1990f4e420c6de869 | https://github.com/jrigden/pyPodcastParser/blob/b21e027bb56ec77986d76fc1990f4e420c6de869/pyPodcastParser/Podcast.py#L366-L371 | train | 30,734 |
jrigden/pyPodcastParser | pyPodcastParser/Podcast.py | Podcast.set_link | def set_link(self):
"""Parses link to homepage and set value"""
try:
self.link = self.soup.find('link').string
except AttributeError:
self.link = None | python | def set_link(self):
"""Parses link to homepage and set value"""
try:
self.link = self.soup.find('link').string
except AttributeError:
self.link = None | [
"def",
"set_link",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"link",
"=",
"self",
".",
"soup",
".",
"find",
"(",
"'link'",
")",
".",
"string",
"except",
"AttributeError",
":",
"self",
".",
"link",
"=",
"None"
] | Parses link to homepage and set value | [
"Parses",
"link",
"to",
"homepage",
"and",
"set",
"value"
] | b21e027bb56ec77986d76fc1990f4e420c6de869 | https://github.com/jrigden/pyPodcastParser/blob/b21e027bb56ec77986d76fc1990f4e420c6de869/pyPodcastParser/Podcast.py#L373-L378 | train | 30,735 |
jrigden/pyPodcastParser | pyPodcastParser/Podcast.py | Podcast.set_managing_editor | def set_managing_editor(self):
"""Parses managing editor and set value"""
try:
self.managing_editor = self.soup.find('managingeditor').string
except AttributeError:
self.managing_editor = None | python | def set_managing_editor(self):
"""Parses managing editor and set value"""
try:
self.managing_editor = self.soup.find('managingeditor').string
except AttributeError:
self.managing_editor = None | [
"def",
"set_managing_editor",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"managing_editor",
"=",
"self",
".",
"soup",
".",
"find",
"(",
"'managingeditor'",
")",
".",
"string",
"except",
"AttributeError",
":",
"self",
".",
"managing_editor",
"=",
"None"
... | Parses managing editor and set value | [
"Parses",
"managing",
"editor",
"and",
"set",
"value"
] | b21e027bb56ec77986d76fc1990f4e420c6de869 | https://github.com/jrigden/pyPodcastParser/blob/b21e027bb56ec77986d76fc1990f4e420c6de869/pyPodcastParser/Podcast.py#L380-L385 | train | 30,736 |
jrigden/pyPodcastParser | pyPodcastParser/Podcast.py | Podcast.set_published_date | def set_published_date(self):
"""Parses published date and set value"""
try:
self.published_date = self.soup.find('pubdate').string
except AttributeError:
self.published_date = None | python | def set_published_date(self):
"""Parses published date and set value"""
try:
self.published_date = self.soup.find('pubdate').string
except AttributeError:
self.published_date = None | [
"def",
"set_published_date",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"published_date",
"=",
"self",
".",
"soup",
".",
"find",
"(",
"'pubdate'",
")",
".",
"string",
"except",
"AttributeError",
":",
"self",
".",
"published_date",
"=",
"None"
] | Parses published date and set value | [
"Parses",
"published",
"date",
"and",
"set",
"value"
] | b21e027bb56ec77986d76fc1990f4e420c6de869 | https://github.com/jrigden/pyPodcastParser/blob/b21e027bb56ec77986d76fc1990f4e420c6de869/pyPodcastParser/Podcast.py#L387-L392 | train | 30,737 |
jrigden/pyPodcastParser | pyPodcastParser/Podcast.py | Podcast.set_pubsubhubbub | def set_pubsubhubbub(self):
"""Parses pubsubhubbub and email then sets value"""
self.pubsubhubbub = None
atom_links = self.soup.findAll('atom:link')
for atom_link in atom_links:
rel = atom_link.get('rel')
if rel == "hub":
self.pubsubhubbub = atom_link.get('href') | python | def set_pubsubhubbub(self):
"""Parses pubsubhubbub and email then sets value"""
self.pubsubhubbub = None
atom_links = self.soup.findAll('atom:link')
for atom_link in atom_links:
rel = atom_link.get('rel')
if rel == "hub":
self.pubsubhubbub = atom_link.get('href') | [
"def",
"set_pubsubhubbub",
"(",
"self",
")",
":",
"self",
".",
"pubsubhubbub",
"=",
"None",
"atom_links",
"=",
"self",
".",
"soup",
".",
"findAll",
"(",
"'atom:link'",
")",
"for",
"atom_link",
"in",
"atom_links",
":",
"rel",
"=",
"atom_link",
".",
"get",
... | Parses pubsubhubbub and email then sets value | [
"Parses",
"pubsubhubbub",
"and",
"email",
"then",
"sets",
"value"
] | b21e027bb56ec77986d76fc1990f4e420c6de869 | https://github.com/jrigden/pyPodcastParser/blob/b21e027bb56ec77986d76fc1990f4e420c6de869/pyPodcastParser/Podcast.py#L394-L401 | train | 30,738 |
jrigden/pyPodcastParser | pyPodcastParser/Podcast.py | Podcast.set_owner | def set_owner(self):
"""Parses owner name and email then sets value"""
owner = self.soup.find('itunes:owner')
try:
self.owner_name = owner.find('itunes:name').string
except AttributeError:
self.owner_name = None
try:
self.owner_email = owner.find('itunes:email').string
except AttributeError:
self.owner_email = None | python | def set_owner(self):
"""Parses owner name and email then sets value"""
owner = self.soup.find('itunes:owner')
try:
self.owner_name = owner.find('itunes:name').string
except AttributeError:
self.owner_name = None
try:
self.owner_email = owner.find('itunes:email').string
except AttributeError:
self.owner_email = None | [
"def",
"set_owner",
"(",
"self",
")",
":",
"owner",
"=",
"self",
".",
"soup",
".",
"find",
"(",
"'itunes:owner'",
")",
"try",
":",
"self",
".",
"owner_name",
"=",
"owner",
".",
"find",
"(",
"'itunes:name'",
")",
".",
"string",
"except",
"AttributeError",... | Parses owner name and email then sets value | [
"Parses",
"owner",
"name",
"and",
"email",
"then",
"sets",
"value"
] | b21e027bb56ec77986d76fc1990f4e420c6de869 | https://github.com/jrigden/pyPodcastParser/blob/b21e027bb56ec77986d76fc1990f4e420c6de869/pyPodcastParser/Podcast.py#L403-L413 | train | 30,739 |
jrigden/pyPodcastParser | pyPodcastParser/Podcast.py | Podcast.set_subtitle | def set_subtitle(self):
"""Parses subtitle and sets value"""
try:
self.subtitle = self.soup.find('itunes:subtitle').string
except AttributeError:
self.subtitle = None | python | def set_subtitle(self):
"""Parses subtitle and sets value"""
try:
self.subtitle = self.soup.find('itunes:subtitle').string
except AttributeError:
self.subtitle = None | [
"def",
"set_subtitle",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"subtitle",
"=",
"self",
".",
"soup",
".",
"find",
"(",
"'itunes:subtitle'",
")",
".",
"string",
"except",
"AttributeError",
":",
"self",
".",
"subtitle",
"=",
"None"
] | Parses subtitle and sets value | [
"Parses",
"subtitle",
"and",
"sets",
"value"
] | b21e027bb56ec77986d76fc1990f4e420c6de869 | https://github.com/jrigden/pyPodcastParser/blob/b21e027bb56ec77986d76fc1990f4e420c6de869/pyPodcastParser/Podcast.py#L415-L420 | train | 30,740 |
jrigden/pyPodcastParser | pyPodcastParser/Podcast.py | Podcast.set_web_master | def set_web_master(self):
"""Parses the feed's webmaster and sets value"""
try:
self.web_master = self.soup.find('webmaster').string
except AttributeError:
self.web_master = None | python | def set_web_master(self):
"""Parses the feed's webmaster and sets value"""
try:
self.web_master = self.soup.find('webmaster').string
except AttributeError:
self.web_master = None | [
"def",
"set_web_master",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"web_master",
"=",
"self",
".",
"soup",
".",
"find",
"(",
"'webmaster'",
")",
".",
"string",
"except",
"AttributeError",
":",
"self",
".",
"web_master",
"=",
"None"
] | Parses the feed's webmaster and sets value | [
"Parses",
"the",
"feed",
"s",
"webmaster",
"and",
"sets",
"value"
] | b21e027bb56ec77986d76fc1990f4e420c6de869 | https://github.com/jrigden/pyPodcastParser/blob/b21e027bb56ec77986d76fc1990f4e420c6de869/pyPodcastParser/Podcast.py#L443-L448 | train | 30,741 |
jrigden/pyPodcastParser | pyPodcastParser/Item.py | Item.set_rss_element | def set_rss_element(self):
"""Set each of the basic rss elements."""
self.set_author()
self.set_categories()
self.set_comments()
self.set_creative_commons()
self.set_description()
self.set_enclosure()
self.set_guid()
self.set_link()
self.set_published_date()
self.set_title() | python | def set_rss_element(self):
"""Set each of the basic rss elements."""
self.set_author()
self.set_categories()
self.set_comments()
self.set_creative_commons()
self.set_description()
self.set_enclosure()
self.set_guid()
self.set_link()
self.set_published_date()
self.set_title() | [
"def",
"set_rss_element",
"(",
"self",
")",
":",
"self",
".",
"set_author",
"(",
")",
"self",
".",
"set_categories",
"(",
")",
"self",
".",
"set_comments",
"(",
")",
"self",
".",
"set_creative_commons",
"(",
")",
"self",
".",
"set_description",
"(",
")",
... | Set each of the basic rss elements. | [
"Set",
"each",
"of",
"the",
"basic",
"rss",
"elements",
"."
] | b21e027bb56ec77986d76fc1990f4e420c6de869 | https://github.com/jrigden/pyPodcastParser/blob/b21e027bb56ec77986d76fc1990f4e420c6de869/pyPodcastParser/Item.py#L96-L107 | train | 30,742 |
jrigden/pyPodcastParser | pyPodcastParser/Item.py | Item.set_author | def set_author(self):
"""Parses author and set value."""
try:
self.author = self.soup.find('author').string
except AttributeError:
self.author = None | python | def set_author(self):
"""Parses author and set value."""
try:
self.author = self.soup.find('author').string
except AttributeError:
self.author = None | [
"def",
"set_author",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"author",
"=",
"self",
".",
"soup",
".",
"find",
"(",
"'author'",
")",
".",
"string",
"except",
"AttributeError",
":",
"self",
".",
"author",
"=",
"None"
] | Parses author and set value. | [
"Parses",
"author",
"and",
"set",
"value",
"."
] | b21e027bb56ec77986d76fc1990f4e420c6de869 | https://github.com/jrigden/pyPodcastParser/blob/b21e027bb56ec77986d76fc1990f4e420c6de869/pyPodcastParser/Item.py#L109-L114 | train | 30,743 |
jrigden/pyPodcastParser | pyPodcastParser/Item.py | Item.set_comments | def set_comments(self):
"""Parses comments and set value."""
try:
self.comments = self.soup.find('comments').string
except AttributeError:
self.comments = None | python | def set_comments(self):
"""Parses comments and set value."""
try:
self.comments = self.soup.find('comments').string
except AttributeError:
self.comments = None | [
"def",
"set_comments",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"comments",
"=",
"self",
".",
"soup",
".",
"find",
"(",
"'comments'",
")",
".",
"string",
"except",
"AttributeError",
":",
"self",
".",
"comments",
"=",
"None"
] | Parses comments and set value. | [
"Parses",
"comments",
"and",
"set",
"value",
"."
] | b21e027bb56ec77986d76fc1990f4e420c6de869 | https://github.com/jrigden/pyPodcastParser/blob/b21e027bb56ec77986d76fc1990f4e420c6de869/pyPodcastParser/Item.py#L124-L129 | train | 30,744 |
jrigden/pyPodcastParser | pyPodcastParser/Item.py | Item.set_enclosure | def set_enclosure(self):
"""Parses enclosure_url, enclosure_type then set values."""
try:
self.enclosure_url = self.soup.find('enclosure')['url']
except:
self.enclosure_url = None
try:
self.enclosure_type = self.soup.find('enclosure')['type']
except:
self.enclosure_type = None
try:
self.enclosure_length = self.soup.find('enclosure')['length']
self.enclosure_length = int(self.enclosure_length)
except:
self.enclosure_length = None | python | def set_enclosure(self):
"""Parses enclosure_url, enclosure_type then set values."""
try:
self.enclosure_url = self.soup.find('enclosure')['url']
except:
self.enclosure_url = None
try:
self.enclosure_type = self.soup.find('enclosure')['type']
except:
self.enclosure_type = None
try:
self.enclosure_length = self.soup.find('enclosure')['length']
self.enclosure_length = int(self.enclosure_length)
except:
self.enclosure_length = None | [
"def",
"set_enclosure",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"enclosure_url",
"=",
"self",
".",
"soup",
".",
"find",
"(",
"'enclosure'",
")",
"[",
"'url'",
"]",
"except",
":",
"self",
".",
"enclosure_url",
"=",
"None",
"try",
":",
"self",
... | Parses enclosure_url, enclosure_type then set values. | [
"Parses",
"enclosure_url",
"enclosure_type",
"then",
"set",
"values",
"."
] | b21e027bb56ec77986d76fc1990f4e420c6de869 | https://github.com/jrigden/pyPodcastParser/blob/b21e027bb56ec77986d76fc1990f4e420c6de869/pyPodcastParser/Item.py#L146-L160 | train | 30,745 |
jrigden/pyPodcastParser | pyPodcastParser/Item.py | Item.set_guid | def set_guid(self):
"""Parses guid and set value"""
try:
self.guid = self.soup.find('guid').string
except AttributeError:
self.guid = None | python | def set_guid(self):
"""Parses guid and set value"""
try:
self.guid = self.soup.find('guid').string
except AttributeError:
self.guid = None | [
"def",
"set_guid",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"guid",
"=",
"self",
".",
"soup",
".",
"find",
"(",
"'guid'",
")",
".",
"string",
"except",
"AttributeError",
":",
"self",
".",
"guid",
"=",
"None"
] | Parses guid and set value | [
"Parses",
"guid",
"and",
"set",
"value"
] | b21e027bb56ec77986d76fc1990f4e420c6de869 | https://github.com/jrigden/pyPodcastParser/blob/b21e027bb56ec77986d76fc1990f4e420c6de869/pyPodcastParser/Item.py#L162-L167 | train | 30,746 |
jrigden/pyPodcastParser | pyPodcastParser/Item.py | Item.set_title | def set_title(self):
"""Parses title and set value."""
try:
self.title = self.soup.find('title').string
except AttributeError:
self.title = None | python | def set_title(self):
"""Parses title and set value."""
try:
self.title = self.soup.find('title').string
except AttributeError:
self.title = None | [
"def",
"set_title",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"title",
"=",
"self",
".",
"soup",
".",
"find",
"(",
"'title'",
")",
".",
"string",
"except",
"AttributeError",
":",
"self",
".",
"title",
"=",
"None"
] | Parses title and set value. | [
"Parses",
"title",
"and",
"set",
"value",
"."
] | b21e027bb56ec77986d76fc1990f4e420c6de869 | https://github.com/jrigden/pyPodcastParser/blob/b21e027bb56ec77986d76fc1990f4e420c6de869/pyPodcastParser/Item.py#L183-L188 | train | 30,747 |
jrigden/pyPodcastParser | pyPodcastParser/Item.py | Item.set_itunes_element | def set_itunes_element(self):
"""Set each of the itunes elements."""
self.set_itunes_author_name()
self.set_itunes_block()
self.set_itunes_closed_captioned()
self.set_itunes_duration()
self.set_itunes_explicit()
self.set_itune_image()
self.set_itunes_order()
self.set_itunes_subtitle()
self.set_itunes_summary() | python | def set_itunes_element(self):
"""Set each of the itunes elements."""
self.set_itunes_author_name()
self.set_itunes_block()
self.set_itunes_closed_captioned()
self.set_itunes_duration()
self.set_itunes_explicit()
self.set_itune_image()
self.set_itunes_order()
self.set_itunes_subtitle()
self.set_itunes_summary() | [
"def",
"set_itunes_element",
"(",
"self",
")",
":",
"self",
".",
"set_itunes_author_name",
"(",
")",
"self",
".",
"set_itunes_block",
"(",
")",
"self",
".",
"set_itunes_closed_captioned",
"(",
")",
"self",
".",
"set_itunes_duration",
"(",
")",
"self",
".",
"se... | Set each of the itunes elements. | [
"Set",
"each",
"of",
"the",
"itunes",
"elements",
"."
] | b21e027bb56ec77986d76fc1990f4e420c6de869 | https://github.com/jrigden/pyPodcastParser/blob/b21e027bb56ec77986d76fc1990f4e420c6de869/pyPodcastParser/Item.py#L190-L200 | train | 30,748 |
jrigden/pyPodcastParser | pyPodcastParser/Item.py | Item.set_itunes_closed_captioned | def set_itunes_closed_captioned(self):
"""Parses isClosedCaptioned from itunes tags and sets value"""
try:
self.itunes_closed_captioned = self.soup.find(
'itunes:isclosedcaptioned').string
self.itunes_closed_captioned = self.itunes_closed_captioned.lower()
except AttributeError:
self.itunes_closed_captioned = None | python | def set_itunes_closed_captioned(self):
"""Parses isClosedCaptioned from itunes tags and sets value"""
try:
self.itunes_closed_captioned = self.soup.find(
'itunes:isclosedcaptioned').string
self.itunes_closed_captioned = self.itunes_closed_captioned.lower()
except AttributeError:
self.itunes_closed_captioned = None | [
"def",
"set_itunes_closed_captioned",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"itunes_closed_captioned",
"=",
"self",
".",
"soup",
".",
"find",
"(",
"'itunes:isclosedcaptioned'",
")",
".",
"string",
"self",
".",
"itunes_closed_captioned",
"=",
"self",
".... | Parses isClosedCaptioned from itunes tags and sets value | [
"Parses",
"isClosedCaptioned",
"from",
"itunes",
"tags",
"and",
"sets",
"value"
] | b21e027bb56ec77986d76fc1990f4e420c6de869 | https://github.com/jrigden/pyPodcastParser/blob/b21e027bb56ec77986d76fc1990f4e420c6de869/pyPodcastParser/Item.py#L220-L227 | train | 30,749 |
jrigden/pyPodcastParser | pyPodcastParser/Item.py | Item.set_itunes_duration | def set_itunes_duration(self):
"""Parses duration from itunes tags and sets value"""
try:
self.itunes_duration = self.soup.find('itunes:duration').string
except AttributeError:
self.itunes_duration = None | python | def set_itunes_duration(self):
"""Parses duration from itunes tags and sets value"""
try:
self.itunes_duration = self.soup.find('itunes:duration').string
except AttributeError:
self.itunes_duration = None | [
"def",
"set_itunes_duration",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"itunes_duration",
"=",
"self",
".",
"soup",
".",
"find",
"(",
"'itunes:duration'",
")",
".",
"string",
"except",
"AttributeError",
":",
"self",
".",
"itunes_duration",
"=",
"None"... | Parses duration from itunes tags and sets value | [
"Parses",
"duration",
"from",
"itunes",
"tags",
"and",
"sets",
"value"
] | b21e027bb56ec77986d76fc1990f4e420c6de869 | https://github.com/jrigden/pyPodcastParser/blob/b21e027bb56ec77986d76fc1990f4e420c6de869/pyPodcastParser/Item.py#L229-L234 | train | 30,750 |
jrigden/pyPodcastParser | pyPodcastParser/Item.py | Item.set_itunes_order | def set_itunes_order(self):
"""Parses episode order and set url as value"""
try:
self.itunes_order = self.soup.find('itunes:order').string
self.itunes_order = self.itunes_order.lower()
except AttributeError:
self.itunes_order = None | python | def set_itunes_order(self):
"""Parses episode order and set url as value"""
try:
self.itunes_order = self.soup.find('itunes:order').string
self.itunes_order = self.itunes_order.lower()
except AttributeError:
self.itunes_order = None | [
"def",
"set_itunes_order",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"itunes_order",
"=",
"self",
".",
"soup",
".",
"find",
"(",
"'itunes:order'",
")",
".",
"string",
"self",
".",
"itunes_order",
"=",
"self",
".",
"itunes_order",
".",
"lower",
"(",... | Parses episode order and set url as value | [
"Parses",
"episode",
"order",
"and",
"set",
"url",
"as",
"value"
] | b21e027bb56ec77986d76fc1990f4e420c6de869 | https://github.com/jrigden/pyPodcastParser/blob/b21e027bb56ec77986d76fc1990f4e420c6de869/pyPodcastParser/Item.py#L251-L257 | train | 30,751 |
jrigden/pyPodcastParser | pyPodcastParser/Item.py | Item.set_itunes_subtitle | def set_itunes_subtitle(self):
"""Parses subtitle from itunes tags and sets value"""
try:
self.itunes_subtitle = self.soup.find('itunes:subtitle').string
except AttributeError:
self.itunes_subtitle = None | python | def set_itunes_subtitle(self):
"""Parses subtitle from itunes tags and sets value"""
try:
self.itunes_subtitle = self.soup.find('itunes:subtitle').string
except AttributeError:
self.itunes_subtitle = None | [
"def",
"set_itunes_subtitle",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"itunes_subtitle",
"=",
"self",
".",
"soup",
".",
"find",
"(",
"'itunes:subtitle'",
")",
".",
"string",
"except",
"AttributeError",
":",
"self",
".",
"itunes_subtitle",
"=",
"None"... | Parses subtitle from itunes tags and sets value | [
"Parses",
"subtitle",
"from",
"itunes",
"tags",
"and",
"sets",
"value"
] | b21e027bb56ec77986d76fc1990f4e420c6de869 | https://github.com/jrigden/pyPodcastParser/blob/b21e027bb56ec77986d76fc1990f4e420c6de869/pyPodcastParser/Item.py#L259-L264 | train | 30,752 |
jrigden/pyPodcastParser | pyPodcastParser/Item.py | Item.set_itunes_summary | def set_itunes_summary(self):
"""Parses summary from itunes tags and sets value"""
try:
self.itunes_summary = self.soup.find('itunes:summary').string
except AttributeError:
self.itunes_summary = None | python | def set_itunes_summary(self):
"""Parses summary from itunes tags and sets value"""
try:
self.itunes_summary = self.soup.find('itunes:summary').string
except AttributeError:
self.itunes_summary = None | [
"def",
"set_itunes_summary",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"itunes_summary",
"=",
"self",
".",
"soup",
".",
"find",
"(",
"'itunes:summary'",
")",
".",
"string",
"except",
"AttributeError",
":",
"self",
".",
"itunes_summary",
"=",
"None"
] | Parses summary from itunes tags and sets value | [
"Parses",
"summary",
"from",
"itunes",
"tags",
"and",
"sets",
"value"
] | b21e027bb56ec77986d76fc1990f4e420c6de869 | https://github.com/jrigden/pyPodcastParser/blob/b21e027bb56ec77986d76fc1990f4e420c6de869/pyPodcastParser/Item.py#L266-L271 | train | 30,753 |
roamanalytics/mittens | mittens/np_mittens.py | Mittens._apply_updates | def _apply_updates(self, gradients):
"""Apply AdaGrad update to parameters.
Parameters
----------
gradients
Returns
-------
"""
if not hasattr(self, 'optimizers'):
self.optimizers = \
{obj: AdaGradOptimizer(self.learning_rate)
for obj in ['W', 'C', 'bw', 'bc']}
self.W -= self.optimizers['W'].get_step(gradients['W'])
self.C -= self.optimizers['C'].get_step(gradients['C'])
self.bw -= self.optimizers['bw'].get_step(gradients['bw'])
self.bc -= self.optimizers['bc'].get_step(gradients['bc']) | python | def _apply_updates(self, gradients):
"""Apply AdaGrad update to parameters.
Parameters
----------
gradients
Returns
-------
"""
if not hasattr(self, 'optimizers'):
self.optimizers = \
{obj: AdaGradOptimizer(self.learning_rate)
for obj in ['W', 'C', 'bw', 'bc']}
self.W -= self.optimizers['W'].get_step(gradients['W'])
self.C -= self.optimizers['C'].get_step(gradients['C'])
self.bw -= self.optimizers['bw'].get_step(gradients['bw'])
self.bc -= self.optimizers['bc'].get_step(gradients['bc']) | [
"def",
"_apply_updates",
"(",
"self",
",",
"gradients",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'optimizers'",
")",
":",
"self",
".",
"optimizers",
"=",
"{",
"obj",
":",
"AdaGradOptimizer",
"(",
"self",
".",
"learning_rate",
")",
"for",
"obj... | Apply AdaGrad update to parameters.
Parameters
----------
gradients
Returns
------- | [
"Apply",
"AdaGrad",
"update",
"to",
"parameters",
"."
] | dbf0c3f8d18651475cf7e21ab1ceb824c5f89150 | https://github.com/roamanalytics/mittens/blob/dbf0c3f8d18651475cf7e21ab1ceb824c5f89150/mittens/np_mittens.py#L136-L154 | train | 30,754 |
roamanalytics/mittens | mittens/np_mittens.py | AdaGradOptimizer.get_step | def get_step(self, grad):
"""Computes the 'step' to take for the next gradient descent update.
Returns the step rather than performing the update so that
parameters can be updated in place rather than overwritten.
Examples
--------
>>> gradient = # ...
>>> optimizer = AdaGradOptimizer(0.01)
>>> params -= optimizer.get_step(gradient)
Parameters
----------
grad
Returns
-------
np.array
Size matches `grad`.
"""
if self._momentum is None:
self._momentum = self.initial_accumulator_value * np.ones_like(grad)
self._momentum += grad ** 2
return self.learning_rate * grad / np.sqrt(self._momentum) | python | def get_step(self, grad):
"""Computes the 'step' to take for the next gradient descent update.
Returns the step rather than performing the update so that
parameters can be updated in place rather than overwritten.
Examples
--------
>>> gradient = # ...
>>> optimizer = AdaGradOptimizer(0.01)
>>> params -= optimizer.get_step(gradient)
Parameters
----------
grad
Returns
-------
np.array
Size matches `grad`.
"""
if self._momentum is None:
self._momentum = self.initial_accumulator_value * np.ones_like(grad)
self._momentum += grad ** 2
return self.learning_rate * grad / np.sqrt(self._momentum) | [
"def",
"get_step",
"(",
"self",
",",
"grad",
")",
":",
"if",
"self",
".",
"_momentum",
"is",
"None",
":",
"self",
".",
"_momentum",
"=",
"self",
".",
"initial_accumulator_value",
"*",
"np",
".",
"ones_like",
"(",
"grad",
")",
"self",
".",
"_momentum",
... | Computes the 'step' to take for the next gradient descent update.
Returns the step rather than performing the update so that
parameters can be updated in place rather than overwritten.
Examples
--------
>>> gradient = # ...
>>> optimizer = AdaGradOptimizer(0.01)
>>> params -= optimizer.get_step(gradient)
Parameters
----------
grad
Returns
-------
np.array
Size matches `grad`. | [
"Computes",
"the",
"step",
"to",
"take",
"for",
"the",
"next",
"gradient",
"descent",
"update",
"."
] | dbf0c3f8d18651475cf7e21ab1ceb824c5f89150 | https://github.com/roamanalytics/mittens/blob/dbf0c3f8d18651475cf7e21ab1ceb824c5f89150/mittens/np_mittens.py#L176-L200 | train | 30,755 |
roamanalytics/mittens | mittens/mittens_base.py | _format_param_value | def _format_param_value(key, value):
"""Wraps string values in quotes, and returns as 'key=value'.
"""
if isinstance(value, str):
value = "'{}'".format(value)
return "{}={}".format(key, value) | python | def _format_param_value(key, value):
"""Wraps string values in quotes, and returns as 'key=value'.
"""
if isinstance(value, str):
value = "'{}'".format(value)
return "{}={}".format(key, value) | [
"def",
"_format_param_value",
"(",
"key",
",",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"str",
")",
":",
"value",
"=",
"\"'{}'\"",
".",
"format",
"(",
"value",
")",
"return",
"\"{}={}\"",
".",
"format",
"(",
"key",
",",
"value",
")"
] | Wraps string values in quotes, and returns as 'key=value'. | [
"Wraps",
"string",
"values",
"in",
"quotes",
"and",
"returns",
"as",
"key",
"=",
"value",
"."
] | dbf0c3f8d18651475cf7e21ab1ceb824c5f89150 | https://github.com/roamanalytics/mittens/blob/dbf0c3f8d18651475cf7e21ab1ceb824c5f89150/mittens/mittens_base.py#L188-L193 | train | 30,756 |
roamanalytics/mittens | mittens/mittens_base.py | randmatrix | def randmatrix(m, n, random_seed=None):
"""Creates an m x n matrix of random values drawn using
the Xavier Glorot method."""
val = np.sqrt(6.0 / (m + n))
np.random.seed(random_seed)
return np.random.uniform(-val, val, size=(m, n)) | python | def randmatrix(m, n, random_seed=None):
"""Creates an m x n matrix of random values drawn using
the Xavier Glorot method."""
val = np.sqrt(6.0 / (m + n))
np.random.seed(random_seed)
return np.random.uniform(-val, val, size=(m, n)) | [
"def",
"randmatrix",
"(",
"m",
",",
"n",
",",
"random_seed",
"=",
"None",
")",
":",
"val",
"=",
"np",
".",
"sqrt",
"(",
"6.0",
"/",
"(",
"m",
"+",
"n",
")",
")",
"np",
".",
"random",
".",
"seed",
"(",
"random_seed",
")",
"return",
"np",
".",
... | Creates an m x n matrix of random values drawn using
the Xavier Glorot method. | [
"Creates",
"an",
"m",
"x",
"n",
"matrix",
"of",
"random",
"values",
"drawn",
"using",
"the",
"Xavier",
"Glorot",
"method",
"."
] | dbf0c3f8d18651475cf7e21ab1ceb824c5f89150 | https://github.com/roamanalytics/mittens/blob/dbf0c3f8d18651475cf7e21ab1ceb824c5f89150/mittens/mittens_base.py#L264-L269 | train | 30,757 |
roamanalytics/mittens | mittens/mittens_base.py | MittensBase._progressbar | def _progressbar(self, msg, iter_num):
"""Display a progress bar with current loss.
Parameters
----------
msg : str
Message to print alongside the progress bar
iter_num : int
Iteration number.
Progress is only printed if this is a multiple of
`self.display_progress`.
"""
if self.display_progress and \
(iter_num + 1) % self.display_progress == 0:
sys.stderr.write('\r')
sys.stderr.write("Iteration {}: {}".format(iter_num + 1, msg))
sys.stderr.flush() | python | def _progressbar(self, msg, iter_num):
"""Display a progress bar with current loss.
Parameters
----------
msg : str
Message to print alongside the progress bar
iter_num : int
Iteration number.
Progress is only printed if this is a multiple of
`self.display_progress`.
"""
if self.display_progress and \
(iter_num + 1) % self.display_progress == 0:
sys.stderr.write('\r')
sys.stderr.write("Iteration {}: {}".format(iter_num + 1, msg))
sys.stderr.flush() | [
"def",
"_progressbar",
"(",
"self",
",",
"msg",
",",
"iter_num",
")",
":",
"if",
"self",
".",
"display_progress",
"and",
"(",
"iter_num",
"+",
"1",
")",
"%",
"self",
".",
"display_progress",
"==",
"0",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"'... | Display a progress bar with current loss.
Parameters
----------
msg : str
Message to print alongside the progress bar
iter_num : int
Iteration number.
Progress is only printed if this is a multiple of
`self.display_progress`. | [
"Display",
"a",
"progress",
"bar",
"with",
"current",
"loss",
"."
] | dbf0c3f8d18651475cf7e21ab1ceb824c5f89150 | https://github.com/roamanalytics/mittens/blob/dbf0c3f8d18651475cf7e21ab1ceb824c5f89150/mittens/mittens_base.py#L149-L167 | train | 30,758 |
roamanalytics/mittens | mittens/tf_mittens.py | Mittens._build_graph | def _build_graph(self, vocab, initial_embedding_dict):
"""Builds the computatation graph.
Parameters
------------
vocab : Iterable
initial_embedding_dict : dict
"""
# Constants
self.ones = tf.ones([self.n_words, 1])
# Parameters:
if initial_embedding_dict is None:
# Ordinary GloVe
self.W = self._weight_init(self.n_words, self.n, 'W')
self.C = self._weight_init(self.n_words, self.n, 'C')
else:
# This is the case where we have values to use as a
# "warm start":
self.n = len(next(iter(initial_embedding_dict.values())))
W = randmatrix(len(vocab), self.n)
C = randmatrix(len(vocab), self.n)
self.original_embedding = np.zeros((len(vocab), self.n))
self.has_embedding = np.zeros(len(vocab))
for i, w in enumerate(vocab):
if w in initial_embedding_dict:
self.has_embedding[i] = 1.0
embedding = np.array(initial_embedding_dict[w])
self.original_embedding[i] = embedding
# Divide the original embedding into W and C,
# plus some noise to break the symmetry that would
# otherwise cause both gradient updates to be
# identical.
W[i] = 0.5 * embedding + noise(self.n)
C[i] = 0.5 * embedding + noise(self.n)
self.W = tf.Variable(W, name='W', dtype=tf.float32)
self.C = tf.Variable(C, name='C', dtype=tf.float32)
self.original_embedding = tf.constant(self.original_embedding,
dtype=tf.float32)
self.has_embedding = tf.constant(self.has_embedding,
dtype=tf.float32)
# This is for testing. It differs from
# `self.original_embedding` only in that it includes the
# random noise we added above to break the symmetry.
self.G_start = W + C
self.bw = self._weight_init(self.n_words, 1, 'bw')
self.bc = self._weight_init(self.n_words, 1, 'bc')
self.model = tf.tensordot(self.W, tf.transpose(self.C), axes=1) + \
tf.tensordot(self.bw, tf.transpose(self.ones), axes=1) + \
tf.tensordot(self.ones, tf.transpose(self.bc), axes=1) | python | def _build_graph(self, vocab, initial_embedding_dict):
"""Builds the computatation graph.
Parameters
------------
vocab : Iterable
initial_embedding_dict : dict
"""
# Constants
self.ones = tf.ones([self.n_words, 1])
# Parameters:
if initial_embedding_dict is None:
# Ordinary GloVe
self.W = self._weight_init(self.n_words, self.n, 'W')
self.C = self._weight_init(self.n_words, self.n, 'C')
else:
# This is the case where we have values to use as a
# "warm start":
self.n = len(next(iter(initial_embedding_dict.values())))
W = randmatrix(len(vocab), self.n)
C = randmatrix(len(vocab), self.n)
self.original_embedding = np.zeros((len(vocab), self.n))
self.has_embedding = np.zeros(len(vocab))
for i, w in enumerate(vocab):
if w in initial_embedding_dict:
self.has_embedding[i] = 1.0
embedding = np.array(initial_embedding_dict[w])
self.original_embedding[i] = embedding
# Divide the original embedding into W and C,
# plus some noise to break the symmetry that would
# otherwise cause both gradient updates to be
# identical.
W[i] = 0.5 * embedding + noise(self.n)
C[i] = 0.5 * embedding + noise(self.n)
self.W = tf.Variable(W, name='W', dtype=tf.float32)
self.C = tf.Variable(C, name='C', dtype=tf.float32)
self.original_embedding = tf.constant(self.original_embedding,
dtype=tf.float32)
self.has_embedding = tf.constant(self.has_embedding,
dtype=tf.float32)
# This is for testing. It differs from
# `self.original_embedding` only in that it includes the
# random noise we added above to break the symmetry.
self.G_start = W + C
self.bw = self._weight_init(self.n_words, 1, 'bw')
self.bc = self._weight_init(self.n_words, 1, 'bc')
self.model = tf.tensordot(self.W, tf.transpose(self.C), axes=1) + \
tf.tensordot(self.bw, tf.transpose(self.ones), axes=1) + \
tf.tensordot(self.ones, tf.transpose(self.bc), axes=1) | [
"def",
"_build_graph",
"(",
"self",
",",
"vocab",
",",
"initial_embedding_dict",
")",
":",
"# Constants",
"self",
".",
"ones",
"=",
"tf",
".",
"ones",
"(",
"[",
"self",
".",
"n_words",
",",
"1",
"]",
")",
"# Parameters:",
"if",
"initial_embedding_dict",
"i... | Builds the computatation graph.
Parameters
------------
vocab : Iterable
initial_embedding_dict : dict | [
"Builds",
"the",
"computatation",
"graph",
"."
] | dbf0c3f8d18651475cf7e21ab1ceb824c5f89150 | https://github.com/roamanalytics/mittens/blob/dbf0c3f8d18651475cf7e21ab1ceb824c5f89150/mittens/tf_mittens.py#L103-L154 | train | 30,759 |
roamanalytics/mittens | mittens/tf_mittens.py | Mittens._get_cost_function | def _get_cost_function(self):
"""Compute the cost of the Mittens objective function.
If self.mittens = 0, this is the same as the cost of GloVe.
"""
self.weights = tf.placeholder(
tf.float32, shape=[self.n_words, self.n_words])
self.log_coincidence = tf.placeholder(
tf.float32, shape=[self.n_words, self.n_words])
self.diffs = tf.subtract(self.model, self.log_coincidence)
cost = tf.reduce_sum(
0.5 * tf.multiply(self.weights, tf.square(self.diffs)))
if self.mittens > 0:
self.mittens = tf.constant(self.mittens, tf.float32)
cost += self.mittens * tf.reduce_sum(
tf.multiply(
self.has_embedding,
self._tf_squared_euclidean(
tf.add(self.W, self.C),
self.original_embedding)))
tf.summary.scalar("cost", cost)
return cost | python | def _get_cost_function(self):
"""Compute the cost of the Mittens objective function.
If self.mittens = 0, this is the same as the cost of GloVe.
"""
self.weights = tf.placeholder(
tf.float32, shape=[self.n_words, self.n_words])
self.log_coincidence = tf.placeholder(
tf.float32, shape=[self.n_words, self.n_words])
self.diffs = tf.subtract(self.model, self.log_coincidence)
cost = tf.reduce_sum(
0.5 * tf.multiply(self.weights, tf.square(self.diffs)))
if self.mittens > 0:
self.mittens = tf.constant(self.mittens, tf.float32)
cost += self.mittens * tf.reduce_sum(
tf.multiply(
self.has_embedding,
self._tf_squared_euclidean(
tf.add(self.W, self.C),
self.original_embedding)))
tf.summary.scalar("cost", cost)
return cost | [
"def",
"_get_cost_function",
"(",
"self",
")",
":",
"self",
".",
"weights",
"=",
"tf",
".",
"placeholder",
"(",
"tf",
".",
"float32",
",",
"shape",
"=",
"[",
"self",
".",
"n_words",
",",
"self",
".",
"n_words",
"]",
")",
"self",
".",
"log_coincidence",... | Compute the cost of the Mittens objective function.
If self.mittens = 0, this is the same as the cost of GloVe. | [
"Compute",
"the",
"cost",
"of",
"the",
"Mittens",
"objective",
"function",
"."
] | dbf0c3f8d18651475cf7e21ab1ceb824c5f89150 | https://github.com/roamanalytics/mittens/blob/dbf0c3f8d18651475cf7e21ab1ceb824c5f89150/mittens/tf_mittens.py#L156-L177 | train | 30,760 |
roamanalytics/mittens | mittens/tf_mittens.py | Mittens._tf_squared_euclidean | def _tf_squared_euclidean(X, Y):
"""Squared Euclidean distance between the rows of `X` and `Y`.
"""
return tf.reduce_sum(tf.pow(tf.subtract(X, Y), 2), axis=1) | python | def _tf_squared_euclidean(X, Y):
"""Squared Euclidean distance between the rows of `X` and `Y`.
"""
return tf.reduce_sum(tf.pow(tf.subtract(X, Y), 2), axis=1) | [
"def",
"_tf_squared_euclidean",
"(",
"X",
",",
"Y",
")",
":",
"return",
"tf",
".",
"reduce_sum",
"(",
"tf",
".",
"pow",
"(",
"tf",
".",
"subtract",
"(",
"X",
",",
"Y",
")",
",",
"2",
")",
",",
"axis",
"=",
"1",
")"
] | Squared Euclidean distance between the rows of `X` and `Y`. | [
"Squared",
"Euclidean",
"distance",
"between",
"the",
"rows",
"of",
"X",
"and",
"Y",
"."
] | dbf0c3f8d18651475cf7e21ab1ceb824c5f89150 | https://github.com/roamanalytics/mittens/blob/dbf0c3f8d18651475cf7e21ab1ceb824c5f89150/mittens/tf_mittens.py#L180-L183 | train | 30,761 |
roamanalytics/mittens | mittens/tf_mittens.py | Mittens._weight_init | def _weight_init(self, m, n, name):
"""
Uses the Xavier Glorot method for initializing weights. This is
built in to TensorFlow as `tf.contrib.layers.xavier_initializer`,
but it's nice to see all the details.
"""
x = np.sqrt(6.0/(m+n))
with tf.name_scope(name) as scope:
return tf.Variable(
tf.random_uniform(
[m, n], minval=-x, maxval=x), name=name) | python | def _weight_init(self, m, n, name):
"""
Uses the Xavier Glorot method for initializing weights. This is
built in to TensorFlow as `tf.contrib.layers.xavier_initializer`,
but it's nice to see all the details.
"""
x = np.sqrt(6.0/(m+n))
with tf.name_scope(name) as scope:
return tf.Variable(
tf.random_uniform(
[m, n], minval=-x, maxval=x), name=name) | [
"def",
"_weight_init",
"(",
"self",
",",
"m",
",",
"n",
",",
"name",
")",
":",
"x",
"=",
"np",
".",
"sqrt",
"(",
"6.0",
"/",
"(",
"m",
"+",
"n",
")",
")",
"with",
"tf",
".",
"name_scope",
"(",
"name",
")",
"as",
"scope",
":",
"return",
"tf",
... | Uses the Xavier Glorot method for initializing weights. This is
built in to TensorFlow as `tf.contrib.layers.xavier_initializer`,
but it's nice to see all the details. | [
"Uses",
"the",
"Xavier",
"Glorot",
"method",
"for",
"initializing",
"weights",
".",
"This",
"is",
"built",
"in",
"to",
"TensorFlow",
"as",
"tf",
".",
"contrib",
".",
"layers",
".",
"xavier_initializer",
"but",
"it",
"s",
"nice",
"to",
"see",
"all",
"the",
... | dbf0c3f8d18651475cf7e21ab1ceb824c5f89150 | https://github.com/roamanalytics/mittens/blob/dbf0c3f8d18651475cf7e21ab1ceb824c5f89150/mittens/tf_mittens.py#L197-L207 | train | 30,762 |
kvh/ramp | ramp/selectors.py | BinaryFeatureSelector.round_robin | def round_robin(self, x, y, n_keep):
""" Ensures all classes get representative features, not just those with strong features """
vals = y.unique()
scores = {}
for cls in vals:
scores[cls] = self.rank(x, np.equal(cls, y).astype('Int64'))
scores[cls].reverse()
keepers = set()
while len(keepers) < n_keep:
for cls in vals:
keepers.add(scores[cls].pop()[1])
return list(keepers) | python | def round_robin(self, x, y, n_keep):
""" Ensures all classes get representative features, not just those with strong features """
vals = y.unique()
scores = {}
for cls in vals:
scores[cls] = self.rank(x, np.equal(cls, y).astype('Int64'))
scores[cls].reverse()
keepers = set()
while len(keepers) < n_keep:
for cls in vals:
keepers.add(scores[cls].pop()[1])
return list(keepers) | [
"def",
"round_robin",
"(",
"self",
",",
"x",
",",
"y",
",",
"n_keep",
")",
":",
"vals",
"=",
"y",
".",
"unique",
"(",
")",
"scores",
"=",
"{",
"}",
"for",
"cls",
"in",
"vals",
":",
"scores",
"[",
"cls",
"]",
"=",
"self",
".",
"rank",
"(",
"x"... | Ensures all classes get representative features, not just those with strong features | [
"Ensures",
"all",
"classes",
"get",
"representative",
"features",
"not",
"just",
"those",
"with",
"strong",
"features"
] | 8618ce673e49b95f40c9659319c3cb72281dacac | https://github.com/kvh/ramp/blob/8618ce673e49b95f40c9659319c3cb72281dacac/ramp/selectors.py#L151-L162 | train | 30,763 |
kvh/ramp | ramp/store.py | dumppickle | def dumppickle(obj, fname, protocol=-1):
"""
Pickle object `obj` to file `fname`.
"""
with open(fname, 'wb') as fout: # 'b' for binary, needed on Windows
pickle.dump(obj, fout, protocol=protocol) | python | def dumppickle(obj, fname, protocol=-1):
"""
Pickle object `obj` to file `fname`.
"""
with open(fname, 'wb') as fout: # 'b' for binary, needed on Windows
pickle.dump(obj, fout, protocol=protocol) | [
"def",
"dumppickle",
"(",
"obj",
",",
"fname",
",",
"protocol",
"=",
"-",
"1",
")",
":",
"with",
"open",
"(",
"fname",
",",
"'wb'",
")",
"as",
"fout",
":",
"# 'b' for binary, needed on Windows",
"pickle",
".",
"dump",
"(",
"obj",
",",
"fout",
",",
"pro... | Pickle object `obj` to file `fname`. | [
"Pickle",
"object",
"obj",
"to",
"file",
"fname",
"."
] | 8618ce673e49b95f40c9659319c3cb72281dacac | https://github.com/kvh/ramp/blob/8618ce673e49b95f40c9659319c3cb72281dacac/ramp/store.py#L29-L34 | train | 30,764 |
kvh/ramp | ramp/estimators/base.py | Estimator.predict_maxprob | def predict_maxprob(self, x, **kwargs):
"""
Most likely value. Generally equivalent to predict.
"""
return self.base_estimator_.predict(x.values, **kwargs) | python | def predict_maxprob(self, x, **kwargs):
"""
Most likely value. Generally equivalent to predict.
"""
return self.base_estimator_.predict(x.values, **kwargs) | [
"def",
"predict_maxprob",
"(",
"self",
",",
"x",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"base_estimator_",
".",
"predict",
"(",
"x",
".",
"values",
",",
"*",
"*",
"kwargs",
")"
] | Most likely value. Generally equivalent to predict. | [
"Most",
"likely",
"value",
".",
"Generally",
"equivalent",
"to",
"predict",
"."
] | 8618ce673e49b95f40c9659319c3cb72281dacac | https://github.com/kvh/ramp/blob/8618ce673e49b95f40c9659319c3cb72281dacac/ramp/estimators/base.py#L44-L48 | train | 30,765 |
kvh/ramp | ramp/utils.py | _pprint | def _pprint(params):
"""prints object state in stable manner"""
params_list = list()
line_sep = ','
for i, (k, v) in enumerate(sorted(params.iteritems())):
if type(v) is float:
# use str for representing floating point numbers
# this way we get consistent representation across
# architectures and versions.
this_repr = '%s=%.10f' % (k, v)
else:
# use repr of the rest
this_repr = '%s=%r' % (k, v)
params_list.append(this_repr)
lines = ','.join(params_list)
return lines | python | def _pprint(params):
"""prints object state in stable manner"""
params_list = list()
line_sep = ','
for i, (k, v) in enumerate(sorted(params.iteritems())):
if type(v) is float:
# use str for representing floating point numbers
# this way we get consistent representation across
# architectures and versions.
this_repr = '%s=%.10f' % (k, v)
else:
# use repr of the rest
this_repr = '%s=%r' % (k, v)
params_list.append(this_repr)
lines = ','.join(params_list)
return lines | [
"def",
"_pprint",
"(",
"params",
")",
":",
"params_list",
"=",
"list",
"(",
")",
"line_sep",
"=",
"','",
"for",
"i",
",",
"(",
"k",
",",
"v",
")",
"in",
"enumerate",
"(",
"sorted",
"(",
"params",
".",
"iteritems",
"(",
")",
")",
")",
":",
"if",
... | prints object state in stable manner | [
"prints",
"object",
"state",
"in",
"stable",
"manner"
] | 8618ce673e49b95f40c9659319c3cb72281dacac | https://github.com/kvh/ramp/blob/8618ce673e49b95f40c9659319c3cb72281dacac/ramp/utils.py#L10-L26 | train | 30,766 |
kvh/ramp | ramp/shortcuts.py | cross_validate | def cross_validate(data=None, folds=5, repeat=1, metrics=None,
reporters=None, model_def=None, **kwargs):
"""Shortcut to cross-validate a single configuration.
ModelDefinition variables are passed in as keyword args, along
with the cross-validation parameters.
"""
md_kwargs = {}
if model_def is None:
for arg in ModelDefinition.params:
if arg in kwargs:
md_kwargs[arg] = kwargs.pop(arg)
model_def = ModelDefinition(**md_kwargs)
if metrics is None:
metrics = []
if reporters is None:
reporters = []
metrics = [MetricReporter(metric) for metric in metrics]
results = modeling.cross_validate(model_def, data, folds, repeat=repeat, **kwargs)
for r in reporters + metrics:
r.process_results(results)
return CVResult(results, reporters, metrics) | python | def cross_validate(data=None, folds=5, repeat=1, metrics=None,
reporters=None, model_def=None, **kwargs):
"""Shortcut to cross-validate a single configuration.
ModelDefinition variables are passed in as keyword args, along
with the cross-validation parameters.
"""
md_kwargs = {}
if model_def is None:
for arg in ModelDefinition.params:
if arg in kwargs:
md_kwargs[arg] = kwargs.pop(arg)
model_def = ModelDefinition(**md_kwargs)
if metrics is None:
metrics = []
if reporters is None:
reporters = []
metrics = [MetricReporter(metric) for metric in metrics]
results = modeling.cross_validate(model_def, data, folds, repeat=repeat, **kwargs)
for r in reporters + metrics:
r.process_results(results)
return CVResult(results, reporters, metrics) | [
"def",
"cross_validate",
"(",
"data",
"=",
"None",
",",
"folds",
"=",
"5",
",",
"repeat",
"=",
"1",
",",
"metrics",
"=",
"None",
",",
"reporters",
"=",
"None",
",",
"model_def",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"md_kwargs",
"=",
"{",... | Shortcut to cross-validate a single configuration.
ModelDefinition variables are passed in as keyword args, along
with the cross-validation parameters. | [
"Shortcut",
"to",
"cross",
"-",
"validate",
"a",
"single",
"configuration",
"."
] | 8618ce673e49b95f40c9659319c3cb72281dacac | https://github.com/kvh/ramp/blob/8618ce673e49b95f40c9659319c3cb72281dacac/ramp/shortcuts.py#L109-L130 | train | 30,767 |
kvh/ramp | ramp/shortcuts.py | cv_factory | def cv_factory(data=None, folds=5, repeat=1, reporters=[], metrics=None,
cv_runner=None, **kwargs):
"""Shortcut to iterate and cross-validate models.
All ModelDefinition kwargs should be iterables that can be
passed to model_definition_factory.
Parameters:
___________
data:
Raw DataFrame
folds:
If an int, than basic k-fold cross-validation will be done.
Otherwise must be an iterable of tuples of pandas Indexes
[(train_index, test_index), ...]
repeat:
How many times to repeat each cross-validation run of each model. Only
makes sense if cross-validation folds are randomized.
kwargs:
Can be any keyword accepted by `ModelDefinition`.
Values should be iterables.
"""
cv_runner = cv_runner or cross_validate
md_kwargs = {}
for arg in ModelDefinition.params:
if arg in kwargs:
md_kwargs[arg] = kwargs.pop(arg)
model_def_fact = model_definition_factory(ModelDefinition(), **md_kwargs)
results = []
model_defs = list(model_def_fact)
for model_def in model_defs:
reporters = [reporter.copy() for reporter in reporters]
cvr = cv_runner(model_def=model_def,
data=data,
folds=folds,
repeat=repeat,
reporters=reporters,
metrics=metrics,
**kwargs)
results.append(cvr)
return CVComparisonResult(model_defs, results) | python | def cv_factory(data=None, folds=5, repeat=1, reporters=[], metrics=None,
cv_runner=None, **kwargs):
"""Shortcut to iterate and cross-validate models.
All ModelDefinition kwargs should be iterables that can be
passed to model_definition_factory.
Parameters:
___________
data:
Raw DataFrame
folds:
If an int, than basic k-fold cross-validation will be done.
Otherwise must be an iterable of tuples of pandas Indexes
[(train_index, test_index), ...]
repeat:
How many times to repeat each cross-validation run of each model. Only
makes sense if cross-validation folds are randomized.
kwargs:
Can be any keyword accepted by `ModelDefinition`.
Values should be iterables.
"""
cv_runner = cv_runner or cross_validate
md_kwargs = {}
for arg in ModelDefinition.params:
if arg in kwargs:
md_kwargs[arg] = kwargs.pop(arg)
model_def_fact = model_definition_factory(ModelDefinition(), **md_kwargs)
results = []
model_defs = list(model_def_fact)
for model_def in model_defs:
reporters = [reporter.copy() for reporter in reporters]
cvr = cv_runner(model_def=model_def,
data=data,
folds=folds,
repeat=repeat,
reporters=reporters,
metrics=metrics,
**kwargs)
results.append(cvr)
return CVComparisonResult(model_defs, results) | [
"def",
"cv_factory",
"(",
"data",
"=",
"None",
",",
"folds",
"=",
"5",
",",
"repeat",
"=",
"1",
",",
"reporters",
"=",
"[",
"]",
",",
"metrics",
"=",
"None",
",",
"cv_runner",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"cv_runner",
"=",
"cv_... | Shortcut to iterate and cross-validate models.
All ModelDefinition kwargs should be iterables that can be
passed to model_definition_factory.
Parameters:
___________
data:
Raw DataFrame
folds:
If an int, than basic k-fold cross-validation will be done.
Otherwise must be an iterable of tuples of pandas Indexes
[(train_index, test_index), ...]
repeat:
How many times to repeat each cross-validation run of each model. Only
makes sense if cross-validation folds are randomized.
kwargs:
Can be any keyword accepted by `ModelDefinition`.
Values should be iterables. | [
"Shortcut",
"to",
"iterate",
"and",
"cross",
"-",
"validate",
"models",
"."
] | 8618ce673e49b95f40c9659319c3cb72281dacac | https://github.com/kvh/ramp/blob/8618ce673e49b95f40c9659319c3cb72281dacac/ramp/shortcuts.py#L133-L178 | train | 30,768 |
kvh/ramp | ramp/reporters.py | DualThresholdMetricReporter.build_report | def build_report(self):
"""
Calculates the pair of metrics for each threshold for each result.
"""
thresholds = self.thresholds
lower_quantile = self.config['lower_quantile']
upper_quantile = self.config['upper_quantile']
if self.n_current_results > self.n_cached_curves:
# If there are new curves, recompute
colnames = ['_'.join([metric, stat])
for metric in [self.metric1.name, self.metric2.name]
for stat in ['Mean', 'Median',
'%d_Percentile' % (100*lower_quantile),
'%d_Percentile' % (upper_quantile*100)]]
self.ret = pd.DataFrame(columns=colnames, index=thresholds, dtype='float64')
for threshold in thresholds:
m1s = Series([self.metric1.score(result, threshold) for result in self.results])
m2s = Series([self.metric2.score(result, threshold) for result in self.results])
self.ret.loc[threshold] = (m1s.mean(), m1s.quantile(.5), m1s.quantile(.05), m1s.quantile(.95),
m2s.mean(), m2s.quantile(.5), m2s.quantile(.05), m2s.quantile(.95))
self.build_curves()
self.summary_df = self.ret
return self.ret | python | def build_report(self):
"""
Calculates the pair of metrics for each threshold for each result.
"""
thresholds = self.thresholds
lower_quantile = self.config['lower_quantile']
upper_quantile = self.config['upper_quantile']
if self.n_current_results > self.n_cached_curves:
# If there are new curves, recompute
colnames = ['_'.join([metric, stat])
for metric in [self.metric1.name, self.metric2.name]
for stat in ['Mean', 'Median',
'%d_Percentile' % (100*lower_quantile),
'%d_Percentile' % (upper_quantile*100)]]
self.ret = pd.DataFrame(columns=colnames, index=thresholds, dtype='float64')
for threshold in thresholds:
m1s = Series([self.metric1.score(result, threshold) for result in self.results])
m2s = Series([self.metric2.score(result, threshold) for result in self.results])
self.ret.loc[threshold] = (m1s.mean(), m1s.quantile(.5), m1s.quantile(.05), m1s.quantile(.95),
m2s.mean(), m2s.quantile(.5), m2s.quantile(.05), m2s.quantile(.95))
self.build_curves()
self.summary_df = self.ret
return self.ret | [
"def",
"build_report",
"(",
"self",
")",
":",
"thresholds",
"=",
"self",
".",
"thresholds",
"lower_quantile",
"=",
"self",
".",
"config",
"[",
"'lower_quantile'",
"]",
"upper_quantile",
"=",
"self",
".",
"config",
"[",
"'upper_quantile'",
"]",
"if",
"self",
... | Calculates the pair of metrics for each threshold for each result. | [
"Calculates",
"the",
"pair",
"of",
"metrics",
"for",
"each",
"threshold",
"for",
"each",
"result",
"."
] | 8618ce673e49b95f40c9659319c3cb72281dacac | https://github.com/kvh/ramp/blob/8618ce673e49b95f40c9659319c3cb72281dacac/ramp/reporters.py#L219-L243 | train | 30,769 |
kvh/ramp | ramp/model_definition.py | model_definition_factory | def model_definition_factory(base_model_definition, **kwargs):
"""
Provides an iterator over passed-in
configuration values, allowing for easy
exploration of models.
Parameters:
___________
base_model_definition:
The base `ModelDefinition` to augment
kwargs:
Can be any keyword accepted by `ModelDefinition`.
Values should be iterables.
"""
if not kwargs:
yield config
else:
for param in kwargs:
if not hasattr(base_model_definition, param):
raise ValueError("'%s' is not a valid configuration parameter" % param)
for raw_params in itertools.product(*kwargs.values()):
new_definition = copy.copy(base_model_definition)
new_definition.update(dict(zip(kwargs.keys(), raw_params)))
yield new_definition | python | def model_definition_factory(base_model_definition, **kwargs):
"""
Provides an iterator over passed-in
configuration values, allowing for easy
exploration of models.
Parameters:
___________
base_model_definition:
The base `ModelDefinition` to augment
kwargs:
Can be any keyword accepted by `ModelDefinition`.
Values should be iterables.
"""
if not kwargs:
yield config
else:
for param in kwargs:
if not hasattr(base_model_definition, param):
raise ValueError("'%s' is not a valid configuration parameter" % param)
for raw_params in itertools.product(*kwargs.values()):
new_definition = copy.copy(base_model_definition)
new_definition.update(dict(zip(kwargs.keys(), raw_params)))
yield new_definition | [
"def",
"model_definition_factory",
"(",
"base_model_definition",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"kwargs",
":",
"yield",
"config",
"else",
":",
"for",
"param",
"in",
"kwargs",
":",
"if",
"not",
"hasattr",
"(",
"base_model_definition",
",",
"p... | Provides an iterator over passed-in
configuration values, allowing for easy
exploration of models.
Parameters:
___________
base_model_definition:
The base `ModelDefinition` to augment
kwargs:
Can be any keyword accepted by `ModelDefinition`.
Values should be iterables. | [
"Provides",
"an",
"iterator",
"over",
"passed",
"-",
"in",
"configuration",
"values",
"allowing",
"for",
"easy",
"exploration",
"of",
"models",
"."
] | 8618ce673e49b95f40c9659319c3cb72281dacac | https://github.com/kvh/ramp/blob/8618ce673e49b95f40c9659319c3cb72281dacac/ramp/model_definition.py#L217-L243 | train | 30,770 |
kvh/ramp | ramp/model_definition.py | ModelDefinition.summary | def summary(self):
"""
Summary of model definition for labeling. Intended to be somewhat
readable but unique to a given model definition.
"""
if self.features is not None:
feature_count = len(self.features)
else:
feature_count = 0
feature_hash = 'feathash:' + str(hash(tuple(self.features)))
return (str(self.estimator), feature_count, feature_hash, self.target) | python | def summary(self):
"""
Summary of model definition for labeling. Intended to be somewhat
readable but unique to a given model definition.
"""
if self.features is not None:
feature_count = len(self.features)
else:
feature_count = 0
feature_hash = 'feathash:' + str(hash(tuple(self.features)))
return (str(self.estimator), feature_count, feature_hash, self.target) | [
"def",
"summary",
"(",
"self",
")",
":",
"if",
"self",
".",
"features",
"is",
"not",
"None",
":",
"feature_count",
"=",
"len",
"(",
"self",
".",
"features",
")",
"else",
":",
"feature_count",
"=",
"0",
"feature_hash",
"=",
"'feathash:'",
"+",
"str",
"(... | Summary of model definition for labeling. Intended to be somewhat
readable but unique to a given model definition. | [
"Summary",
"of",
"model",
"definition",
"for",
"labeling",
".",
"Intended",
"to",
"be",
"somewhat",
"readable",
"but",
"unique",
"to",
"a",
"given",
"model",
"definition",
"."
] | 8618ce673e49b95f40c9659319c3cb72281dacac | https://github.com/kvh/ramp/blob/8618ce673e49b95f40c9659319c3cb72281dacac/ramp/model_definition.py#L197-L207 | train | 30,771 |
kvh/ramp | ramp/features/base.py | ComboFeature.column_rename | def column_rename(self, existing_name, hsh=None):
"""
Like unique_name, but in addition must be unique to each column of this
feature. accomplishes this by prepending readable string to existing
column name and replacing unique hash at end of column name.
"""
try:
existing_name = str(existing_name)
except UnicodeEncodeError:
pass
if hsh is None:
hsh = self._hash()
if self._name:
return '%s(%s) [%s]' %(self._name, self._remove_hashes(existing_name),
hsh)
return '%s [%s]'%(self._remove_hashes(existing_name),
hsh) | python | def column_rename(self, existing_name, hsh=None):
"""
Like unique_name, but in addition must be unique to each column of this
feature. accomplishes this by prepending readable string to existing
column name and replacing unique hash at end of column name.
"""
try:
existing_name = str(existing_name)
except UnicodeEncodeError:
pass
if hsh is None:
hsh = self._hash()
if self._name:
return '%s(%s) [%s]' %(self._name, self._remove_hashes(existing_name),
hsh)
return '%s [%s]'%(self._remove_hashes(existing_name),
hsh) | [
"def",
"column_rename",
"(",
"self",
",",
"existing_name",
",",
"hsh",
"=",
"None",
")",
":",
"try",
":",
"existing_name",
"=",
"str",
"(",
"existing_name",
")",
"except",
"UnicodeEncodeError",
":",
"pass",
"if",
"hsh",
"is",
"None",
":",
"hsh",
"=",
"se... | Like unique_name, but in addition must be unique to each column of this
feature. accomplishes this by prepending readable string to existing
column name and replacing unique hash at end of column name. | [
"Like",
"unique_name",
"but",
"in",
"addition",
"must",
"be",
"unique",
"to",
"each",
"column",
"of",
"this",
"feature",
".",
"accomplishes",
"this",
"by",
"prepending",
"readable",
"string",
"to",
"existing",
"column",
"name",
"and",
"replacing",
"unique",
"h... | 8618ce673e49b95f40c9659319c3cb72281dacac | https://github.com/kvh/ramp/blob/8618ce673e49b95f40c9659319c3cb72281dacac/ramp/features/base.py#L228-L244 | train | 30,772 |
ludbb/secp256k1-py | secp256k1/__init__.py | ECDSA.ecdsa_signature_normalize | def ecdsa_signature_normalize(self, raw_sig, check_only=False):
"""
Check and optionally convert a signature to a normalized lower-S form.
If check_only is True then the normalized signature is not returned.
This function always return a tuple containing a boolean (True if
not previously normalized or False if signature was already
normalized), and the normalized signature. When check_only is True,
the normalized signature returned is always None.
"""
if check_only:
sigout = ffi.NULL
else:
sigout = ffi.new('secp256k1_ecdsa_signature *')
result = lib.secp256k1_ecdsa_signature_normalize(
self.ctx, sigout, raw_sig)
return (bool(result), sigout if sigout != ffi.NULL else None) | python | def ecdsa_signature_normalize(self, raw_sig, check_only=False):
"""
Check and optionally convert a signature to a normalized lower-S form.
If check_only is True then the normalized signature is not returned.
This function always return a tuple containing a boolean (True if
not previously normalized or False if signature was already
normalized), and the normalized signature. When check_only is True,
the normalized signature returned is always None.
"""
if check_only:
sigout = ffi.NULL
else:
sigout = ffi.new('secp256k1_ecdsa_signature *')
result = lib.secp256k1_ecdsa_signature_normalize(
self.ctx, sigout, raw_sig)
return (bool(result), sigout if sigout != ffi.NULL else None) | [
"def",
"ecdsa_signature_normalize",
"(",
"self",
",",
"raw_sig",
",",
"check_only",
"=",
"False",
")",
":",
"if",
"check_only",
":",
"sigout",
"=",
"ffi",
".",
"NULL",
"else",
":",
"sigout",
"=",
"ffi",
".",
"new",
"(",
"'secp256k1_ecdsa_signature *'",
")",
... | Check and optionally convert a signature to a normalized lower-S form.
If check_only is True then the normalized signature is not returned.
This function always return a tuple containing a boolean (True if
not previously normalized or False if signature was already
normalized), and the normalized signature. When check_only is True,
the normalized signature returned is always None. | [
"Check",
"and",
"optionally",
"convert",
"a",
"signature",
"to",
"a",
"normalized",
"lower",
"-",
"S",
"form",
".",
"If",
"check_only",
"is",
"True",
"then",
"the",
"normalized",
"signature",
"is",
"not",
"returned",
"."
] | f5e455227bf1e833128adf80de8ee0ebcebf218c | https://github.com/ludbb/secp256k1-py/blob/f5e455227bf1e833128adf80de8ee0ebcebf218c/secp256k1/__init__.py#L84-L102 | train | 30,773 |
ludbb/secp256k1-py | secp256k1/__init__.py | Schnorr.schnorr_partial_combine | def schnorr_partial_combine(self, schnorr_sigs):
"""Combine multiple Schnorr partial signatures."""
if not HAS_SCHNORR:
raise Exception("secp256k1_schnorr not enabled")
assert len(schnorr_sigs) > 0
sig64 = ffi.new('char [64]')
sig64sin = []
for sig in schnorr_sigs:
if not isinstance(sig, bytes):
raise TypeError('expected bytes, got {}'.format(type(sig)))
if len(sig) != 64:
raise Exception('invalid signature length')
sig64sin.append(ffi.new('char []', sig))
res = lib.secp256k1_schnorr_partial_combine(
self.ctx, sig64, sig64sin, len(sig64sin))
if res <= 0:
raise Exception('failed to combine signatures ({})'.format(res))
return bytes(ffi.buffer(sig64, 64)) | python | def schnorr_partial_combine(self, schnorr_sigs):
"""Combine multiple Schnorr partial signatures."""
if not HAS_SCHNORR:
raise Exception("secp256k1_schnorr not enabled")
assert len(schnorr_sigs) > 0
sig64 = ffi.new('char [64]')
sig64sin = []
for sig in schnorr_sigs:
if not isinstance(sig, bytes):
raise TypeError('expected bytes, got {}'.format(type(sig)))
if len(sig) != 64:
raise Exception('invalid signature length')
sig64sin.append(ffi.new('char []', sig))
res = lib.secp256k1_schnorr_partial_combine(
self.ctx, sig64, sig64sin, len(sig64sin))
if res <= 0:
raise Exception('failed to combine signatures ({})'.format(res))
return bytes(ffi.buffer(sig64, 64)) | [
"def",
"schnorr_partial_combine",
"(",
"self",
",",
"schnorr_sigs",
")",
":",
"if",
"not",
"HAS_SCHNORR",
":",
"raise",
"Exception",
"(",
"\"secp256k1_schnorr not enabled\"",
")",
"assert",
"len",
"(",
"schnorr_sigs",
")",
">",
"0",
"sig64",
"=",
"ffi",
".",
"... | Combine multiple Schnorr partial signatures. | [
"Combine",
"multiple",
"Schnorr",
"partial",
"signatures",
"."
] | f5e455227bf1e833128adf80de8ee0ebcebf218c | https://github.com/ludbb/secp256k1-py/blob/f5e455227bf1e833128adf80de8ee0ebcebf218c/secp256k1/__init__.py#L179-L199 | train | 30,774 |
ludbb/secp256k1-py | secp256k1/__init__.py | PublicKey.combine | def combine(self, pubkeys):
"""Add a number of public keys together."""
assert len(pubkeys) > 0
outpub = ffi.new('secp256k1_pubkey *')
for item in pubkeys:
assert ffi.typeof(item) is ffi.typeof('secp256k1_pubkey *')
res = lib.secp256k1_ec_pubkey_combine(
self.ctx, outpub, pubkeys, len(pubkeys))
if not res:
raise Exception('failed to combine public keys')
self.public_key = outpub
return outpub | python | def combine(self, pubkeys):
"""Add a number of public keys together."""
assert len(pubkeys) > 0
outpub = ffi.new('secp256k1_pubkey *')
for item in pubkeys:
assert ffi.typeof(item) is ffi.typeof('secp256k1_pubkey *')
res = lib.secp256k1_ec_pubkey_combine(
self.ctx, outpub, pubkeys, len(pubkeys))
if not res:
raise Exception('failed to combine public keys')
self.public_key = outpub
return outpub | [
"def",
"combine",
"(",
"self",
",",
"pubkeys",
")",
":",
"assert",
"len",
"(",
"pubkeys",
")",
">",
"0",
"outpub",
"=",
"ffi",
".",
"new",
"(",
"'secp256k1_pubkey *'",
")",
"for",
"item",
"in",
"pubkeys",
":",
"assert",
"ffi",
".",
"typeof",
"(",
"it... | Add a number of public keys together. | [
"Add",
"a",
"number",
"of",
"public",
"keys",
"together",
"."
] | f5e455227bf1e833128adf80de8ee0ebcebf218c | https://github.com/ludbb/secp256k1-py/blob/f5e455227bf1e833128adf80de8ee0ebcebf218c/secp256k1/__init__.py#L247-L261 | train | 30,775 |
ludbb/secp256k1-py | secp256k1/__init__.py | PrivateKey.schnorr_generate_nonce_pair | def schnorr_generate_nonce_pair(self, msg, raw=False,
digest=hashlib.sha256):
"""
Generate a nonce pair deterministically for use with
schnorr_partial_sign.
"""
if not HAS_SCHNORR:
raise Exception("secp256k1_schnorr not enabled")
msg32 = _hash32(msg, raw, digest)
pubnonce = ffi.new('secp256k1_pubkey *')
privnonce = ffi.new('char [32]')
valid = lib.secp256k1_schnorr_generate_nonce_pair(
self.ctx, pubnonce, privnonce, msg32, self.private_key,
ffi.NULL, ffi.NULL)
assert valid == 1
return pubnonce, privnonce | python | def schnorr_generate_nonce_pair(self, msg, raw=False,
digest=hashlib.sha256):
"""
Generate a nonce pair deterministically for use with
schnorr_partial_sign.
"""
if not HAS_SCHNORR:
raise Exception("secp256k1_schnorr not enabled")
msg32 = _hash32(msg, raw, digest)
pubnonce = ffi.new('secp256k1_pubkey *')
privnonce = ffi.new('char [32]')
valid = lib.secp256k1_schnorr_generate_nonce_pair(
self.ctx, pubnonce, privnonce, msg32, self.private_key,
ffi.NULL, ffi.NULL)
assert valid == 1
return pubnonce, privnonce | [
"def",
"schnorr_generate_nonce_pair",
"(",
"self",
",",
"msg",
",",
"raw",
"=",
"False",
",",
"digest",
"=",
"hashlib",
".",
"sha256",
")",
":",
"if",
"not",
"HAS_SCHNORR",
":",
"raise",
"Exception",
"(",
"\"secp256k1_schnorr not enabled\"",
")",
"msg32",
"=",... | Generate a nonce pair deterministically for use with
schnorr_partial_sign. | [
"Generate",
"a",
"nonce",
"pair",
"deterministically",
"for",
"use",
"with",
"schnorr_partial_sign",
"."
] | f5e455227bf1e833128adf80de8ee0ebcebf218c | https://github.com/ludbb/secp256k1-py/blob/f5e455227bf1e833128adf80de8ee0ebcebf218c/secp256k1/__init__.py#L422-L440 | train | 30,776 |
ludbb/secp256k1-py | secp256k1/__init__.py | PrivateKey.schnorr_partial_sign | def schnorr_partial_sign(self, msg, privnonce, pubnonce_others,
raw=False, digest=hashlib.sha256):
"""
Produce a partial Schnorr signature, which can be combined using
schnorr_partial_combine to end up with a full signature that is
verifiable using PublicKey.schnorr_verify.
To combine pubnonces, use PublicKey.combine.
Do not pass the pubnonce produced for the respective privnonce;
combine the pubnonces from other signers and pass that instead.
"""
if not HAS_SCHNORR:
raise Exception("secp256k1_schnorr not enabled")
msg32 = _hash32(msg, raw, digest)
sig64 = ffi.new('char [64]')
res = lib.secp256k1_schnorr_partial_sign(
self.ctx, sig64, msg32, self.private_key,
pubnonce_others, privnonce)
if res <= 0:
raise Exception('failed to partially sign ({})'.format(res))
return bytes(ffi.buffer(sig64, 64)) | python | def schnorr_partial_sign(self, msg, privnonce, pubnonce_others,
raw=False, digest=hashlib.sha256):
"""
Produce a partial Schnorr signature, which can be combined using
schnorr_partial_combine to end up with a full signature that is
verifiable using PublicKey.schnorr_verify.
To combine pubnonces, use PublicKey.combine.
Do not pass the pubnonce produced for the respective privnonce;
combine the pubnonces from other signers and pass that instead.
"""
if not HAS_SCHNORR:
raise Exception("secp256k1_schnorr not enabled")
msg32 = _hash32(msg, raw, digest)
sig64 = ffi.new('char [64]')
res = lib.secp256k1_schnorr_partial_sign(
self.ctx, sig64, msg32, self.private_key,
pubnonce_others, privnonce)
if res <= 0:
raise Exception('failed to partially sign ({})'.format(res))
return bytes(ffi.buffer(sig64, 64)) | [
"def",
"schnorr_partial_sign",
"(",
"self",
",",
"msg",
",",
"privnonce",
",",
"pubnonce_others",
",",
"raw",
"=",
"False",
",",
"digest",
"=",
"hashlib",
".",
"sha256",
")",
":",
"if",
"not",
"HAS_SCHNORR",
":",
"raise",
"Exception",
"(",
"\"secp256k1_schno... | Produce a partial Schnorr signature, which can be combined using
schnorr_partial_combine to end up with a full signature that is
verifiable using PublicKey.schnorr_verify.
To combine pubnonces, use PublicKey.combine.
Do not pass the pubnonce produced for the respective privnonce;
combine the pubnonces from other signers and pass that instead. | [
"Produce",
"a",
"partial",
"Schnorr",
"signature",
"which",
"can",
"be",
"combined",
"using",
"schnorr_partial_combine",
"to",
"end",
"up",
"with",
"a",
"full",
"signature",
"that",
"is",
"verifiable",
"using",
"PublicKey",
".",
"schnorr_verify",
"."
] | f5e455227bf1e833128adf80de8ee0ebcebf218c | https://github.com/ludbb/secp256k1-py/blob/f5e455227bf1e833128adf80de8ee0ebcebf218c/secp256k1/__init__.py#L442-L466 | train | 30,777 |
ludbb/secp256k1-py | setup_support.py | build_flags | def build_flags(library, type_, path):
"""Return separated build flags from pkg-config output"""
pkg_config_path = [path]
if "PKG_CONFIG_PATH" in os.environ:
pkg_config_path.append(os.environ['PKG_CONFIG_PATH'])
if "LIB_DIR" in os.environ:
pkg_config_path.append(os.environ['LIB_DIR'])
pkg_config_path.append(os.path.join(os.environ['LIB_DIR'], "pkgconfig"))
options = [
"--static",
{
'I': "--cflags-only-I",
'L': "--libs-only-L",
'l': "--libs-only-l"
}[type_]
]
return [
flag.strip("-{}".format(type_))
for flag
in subprocess.check_output(
["pkg-config"] + options + [library],
env=dict(os.environ, PKG_CONFIG_PATH=":".join(pkg_config_path))
).decode("UTF-8").split()
] | python | def build_flags(library, type_, path):
"""Return separated build flags from pkg-config output"""
pkg_config_path = [path]
if "PKG_CONFIG_PATH" in os.environ:
pkg_config_path.append(os.environ['PKG_CONFIG_PATH'])
if "LIB_DIR" in os.environ:
pkg_config_path.append(os.environ['LIB_DIR'])
pkg_config_path.append(os.path.join(os.environ['LIB_DIR'], "pkgconfig"))
options = [
"--static",
{
'I': "--cflags-only-I",
'L': "--libs-only-L",
'l': "--libs-only-l"
}[type_]
]
return [
flag.strip("-{}".format(type_))
for flag
in subprocess.check_output(
["pkg-config"] + options + [library],
env=dict(os.environ, PKG_CONFIG_PATH=":".join(pkg_config_path))
).decode("UTF-8").split()
] | [
"def",
"build_flags",
"(",
"library",
",",
"type_",
",",
"path",
")",
":",
"pkg_config_path",
"=",
"[",
"path",
"]",
"if",
"\"PKG_CONFIG_PATH\"",
"in",
"os",
".",
"environ",
":",
"pkg_config_path",
".",
"append",
"(",
"os",
".",
"environ",
"[",
"'PKG_CONFI... | Return separated build flags from pkg-config output | [
"Return",
"separated",
"build",
"flags",
"from",
"pkg",
"-",
"config",
"output"
] | f5e455227bf1e833128adf80de8ee0ebcebf218c | https://github.com/ludbb/secp256k1-py/blob/f5e455227bf1e833128adf80de8ee0ebcebf218c/setup_support.py#L41-L67 | train | 30,778 |
jpscaletti/pyceo | pyceo/manager.py | Manager.command | def command(self, group=None, help="", name=None):
"""Decorator for adding a command to this manager."""
def decorator(func):
return self.add_command(func, group=group, help=help, name=name)
return decorator | python | def command(self, group=None, help="", name=None):
"""Decorator for adding a command to this manager."""
def decorator(func):
return self.add_command(func, group=group, help=help, name=name)
return decorator | [
"def",
"command",
"(",
"self",
",",
"group",
"=",
"None",
",",
"help",
"=",
"\"\"",
",",
"name",
"=",
"None",
")",
":",
"def",
"decorator",
"(",
"func",
")",
":",
"return",
"self",
".",
"add_command",
"(",
"func",
",",
"group",
"=",
"group",
",",
... | Decorator for adding a command to this manager. | [
"Decorator",
"for",
"adding",
"a",
"command",
"to",
"this",
"manager",
"."
] | 7f37eaf8e557d25f8e54634176139e0aad84b8df | https://github.com/jpscaletti/pyceo/blob/7f37eaf8e557d25f8e54634176139e0aad84b8df/pyceo/manager.py#L57-L61 | train | 30,779 |
jpscaletti/pyceo | pyceo/parser.py | parse_args | def parse_args(cliargs):
"""Parse the command line arguments and return a list of the positional
arguments and a dictionary with the named ones.
>>> parse_args(["abc", "def", "-w", "3", "--foo", "bar", "-narf=zort"])
(['abc', 'def'], {'w': '3', 'foo': 'bar', 'narf': 'zort'})
>>> parse_args(["-abc"])
([], {'abc': True})
>>> parse_args(["-f", "1", "-f", "2", "-f", "3"])
([], {'f': ['1', '2', '3']})
"""
# Split the "key=arg" arguments
largs = []
for arg in cliargs:
if "=" in arg:
key, arg = arg.split("=")
largs.append(key)
largs.append(arg)
args = []
flags = []
kwargs = {}
key = None
for sarg in largs:
if is_key(sarg):
if key is not None:
flags.append(key)
key = sarg.strip("-")
continue
if not key:
args.append(sarg)
continue
value = kwargs.get(key)
if value:
if isinstance(value, list):
value.append(sarg)
else:
value = [value, sarg]
kwargs[key] = value
else:
kwargs[key] = sarg
# Get the flags
if key:
flags.append(key)
# An extra key whitout a value is a flag if it hasn"t been used before.
# Otherwise is a typo.
for flag in flags:
if not kwargs.get(flag):
kwargs[flag] = True
return args, kwargs | python | def parse_args(cliargs):
"""Parse the command line arguments and return a list of the positional
arguments and a dictionary with the named ones.
>>> parse_args(["abc", "def", "-w", "3", "--foo", "bar", "-narf=zort"])
(['abc', 'def'], {'w': '3', 'foo': 'bar', 'narf': 'zort'})
>>> parse_args(["-abc"])
([], {'abc': True})
>>> parse_args(["-f", "1", "-f", "2", "-f", "3"])
([], {'f': ['1', '2', '3']})
"""
# Split the "key=arg" arguments
largs = []
for arg in cliargs:
if "=" in arg:
key, arg = arg.split("=")
largs.append(key)
largs.append(arg)
args = []
flags = []
kwargs = {}
key = None
for sarg in largs:
if is_key(sarg):
if key is not None:
flags.append(key)
key = sarg.strip("-")
continue
if not key:
args.append(sarg)
continue
value = kwargs.get(key)
if value:
if isinstance(value, list):
value.append(sarg)
else:
value = [value, sarg]
kwargs[key] = value
else:
kwargs[key] = sarg
# Get the flags
if key:
flags.append(key)
# An extra key whitout a value is a flag if it hasn"t been used before.
# Otherwise is a typo.
for flag in flags:
if not kwargs.get(flag):
kwargs[flag] = True
return args, kwargs | [
"def",
"parse_args",
"(",
"cliargs",
")",
":",
"# Split the \"key=arg\" arguments",
"largs",
"=",
"[",
"]",
"for",
"arg",
"in",
"cliargs",
":",
"if",
"\"=\"",
"in",
"arg",
":",
"key",
",",
"arg",
"=",
"arg",
".",
"split",
"(",
"\"=\"",
")",
"largs",
".... | Parse the command line arguments and return a list of the positional
arguments and a dictionary with the named ones.
>>> parse_args(["abc", "def", "-w", "3", "--foo", "bar", "-narf=zort"])
(['abc', 'def'], {'w': '3', 'foo': 'bar', 'narf': 'zort'})
>>> parse_args(["-abc"])
([], {'abc': True})
>>> parse_args(["-f", "1", "-f", "2", "-f", "3"])
([], {'f': ['1', '2', '3']}) | [
"Parse",
"the",
"command",
"line",
"arguments",
"and",
"return",
"a",
"list",
"of",
"the",
"positional",
"arguments",
"and",
"a",
"dictionary",
"with",
"the",
"named",
"ones",
"."
] | 7f37eaf8e557d25f8e54634176139e0aad84b8df | https://github.com/jpscaletti/pyceo/blob/7f37eaf8e557d25f8e54634176139e0aad84b8df/pyceo/parser.py#L3-L59 | train | 30,780 |
jpscaletti/pyceo | pyceo/params.py | param | def param(name, help=""):
"""Decorator that add a parameter to the wrapped command or function."""
def decorator(func):
params = getattr(func, "params", [])
_param = Param(name, help)
# Insert at the beginning so the apparent order is preserved
params.insert(0, _param)
func.params = params
return func
return decorator | python | def param(name, help=""):
"""Decorator that add a parameter to the wrapped command or function."""
def decorator(func):
params = getattr(func, "params", [])
_param = Param(name, help)
# Insert at the beginning so the apparent order is preserved
params.insert(0, _param)
func.params = params
return func
return decorator | [
"def",
"param",
"(",
"name",
",",
"help",
"=",
"\"\"",
")",
":",
"def",
"decorator",
"(",
"func",
")",
":",
"params",
"=",
"getattr",
"(",
"func",
",",
"\"params\"",
",",
"[",
"]",
")",
"_param",
"=",
"Param",
"(",
"name",
",",
"help",
")",
"# In... | Decorator that add a parameter to the wrapped command or function. | [
"Decorator",
"that",
"add",
"a",
"parameter",
"to",
"the",
"wrapped",
"command",
"or",
"function",
"."
] | 7f37eaf8e557d25f8e54634176139e0aad84b8df | https://github.com/jpscaletti/pyceo/blob/7f37eaf8e557d25f8e54634176139e0aad84b8df/pyceo/params.py#L20-L30 | train | 30,781 |
jpscaletti/pyceo | pyceo/params.py | option | def option(name, help=""):
"""Decorator that add an option to the wrapped command or function."""
def decorator(func):
options = getattr(func, "options", [])
_option = Param(name, help)
# Insert at the beginning so the apparent order is preserved
options.insert(0, _option)
func.options = options
return func
return decorator | python | def option(name, help=""):
"""Decorator that add an option to the wrapped command or function."""
def decorator(func):
options = getattr(func, "options", [])
_option = Param(name, help)
# Insert at the beginning so the apparent order is preserved
options.insert(0, _option)
func.options = options
return func
return decorator | [
"def",
"option",
"(",
"name",
",",
"help",
"=",
"\"\"",
")",
":",
"def",
"decorator",
"(",
"func",
")",
":",
"options",
"=",
"getattr",
"(",
"func",
",",
"\"options\"",
",",
"[",
"]",
")",
"_option",
"=",
"Param",
"(",
"name",
",",
"help",
")",
"... | Decorator that add an option to the wrapped command or function. | [
"Decorator",
"that",
"add",
"an",
"option",
"to",
"the",
"wrapped",
"command",
"or",
"function",
"."
] | 7f37eaf8e557d25f8e54634176139e0aad84b8df | https://github.com/jpscaletti/pyceo/blob/7f37eaf8e557d25f8e54634176139e0aad84b8df/pyceo/params.py#L33-L43 | train | 30,782 |
release-engineering/productmd | productmd/common.py | _open_file_obj | def _open_file_obj(f, mode="r"):
"""
A context manager that provides access to a file.
:param f: the file to be opened
:type f: a file-like object or path to file
:param mode: how to open the file
:type mode: string
"""
if isinstance(f, six.string_types):
if f.startswith(("http://", "https://")):
file_obj = _urlopen(f)
yield file_obj
file_obj.close()
else:
with open(f, mode) as file_obj:
yield file_obj
else:
yield f | python | def _open_file_obj(f, mode="r"):
"""
A context manager that provides access to a file.
:param f: the file to be opened
:type f: a file-like object or path to file
:param mode: how to open the file
:type mode: string
"""
if isinstance(f, six.string_types):
if f.startswith(("http://", "https://")):
file_obj = _urlopen(f)
yield file_obj
file_obj.close()
else:
with open(f, mode) as file_obj:
yield file_obj
else:
yield f | [
"def",
"_open_file_obj",
"(",
"f",
",",
"mode",
"=",
"\"r\"",
")",
":",
"if",
"isinstance",
"(",
"f",
",",
"six",
".",
"string_types",
")",
":",
"if",
"f",
".",
"startswith",
"(",
"(",
"\"http://\"",
",",
"\"https://\"",
")",
")",
":",
"file_obj",
"=... | A context manager that provides access to a file.
:param f: the file to be opened
:type f: a file-like object or path to file
:param mode: how to open the file
:type mode: string | [
"A",
"context",
"manager",
"that",
"provides",
"access",
"to",
"a",
"file",
"."
] | 49256bf2e8c84124f42346241140b986ad7bfc38 | https://github.com/release-engineering/productmd/blob/49256bf2e8c84124f42346241140b986ad7bfc38/productmd/common.py#L172-L190 | train | 30,783 |
release-engineering/productmd | productmd/common.py | split_version | def split_version(version):
"""
Split version to a list of integers
that can be easily compared.
:param version: Release version
:type version: str
:rtype: [int] or [string]
"""
if re.match("^[^0-9].*", version):
return [version]
return [int(i) for i in version.split(".")] | python | def split_version(version):
"""
Split version to a list of integers
that can be easily compared.
:param version: Release version
:type version: str
:rtype: [int] or [string]
"""
if re.match("^[^0-9].*", version):
return [version]
return [int(i) for i in version.split(".")] | [
"def",
"split_version",
"(",
"version",
")",
":",
"if",
"re",
".",
"match",
"(",
"\"^[^0-9].*\"",
",",
"version",
")",
":",
"return",
"[",
"version",
"]",
"return",
"[",
"int",
"(",
"i",
")",
"for",
"i",
"in",
"version",
".",
"split",
"(",
"\".\"",
... | Split version to a list of integers
that can be easily compared.
:param version: Release version
:type version: str
:rtype: [int] or [string] | [
"Split",
"version",
"to",
"a",
"list",
"of",
"integers",
"that",
"can",
"be",
"easily",
"compared",
"."
] | 49256bf2e8c84124f42346241140b986ad7bfc38 | https://github.com/release-engineering/productmd/blob/49256bf2e8c84124f42346241140b986ad7bfc38/productmd/common.py#L376-L387 | train | 30,784 |
release-engineering/productmd | productmd/common.py | get_major_version | def get_major_version(version, remove=None):
"""Return major version of a provided version string. Major version is the
first component of the dot-separated version string. For non-version-like
strings this function returns the argument unchanged.
The ``remove`` parameter is deprecated since version 1.18 and will be
removed in the future.
:param version: Version string
:type version: str
:rtype: str
"""
if remove:
warnings.warn("remove argument is deprecated", DeprecationWarning)
version_split = version.split(".")
return version_split[0] | python | def get_major_version(version, remove=None):
"""Return major version of a provided version string. Major version is the
first component of the dot-separated version string. For non-version-like
strings this function returns the argument unchanged.
The ``remove`` parameter is deprecated since version 1.18 and will be
removed in the future.
:param version: Version string
:type version: str
:rtype: str
"""
if remove:
warnings.warn("remove argument is deprecated", DeprecationWarning)
version_split = version.split(".")
return version_split[0] | [
"def",
"get_major_version",
"(",
"version",
",",
"remove",
"=",
"None",
")",
":",
"if",
"remove",
":",
"warnings",
".",
"warn",
"(",
"\"remove argument is deprecated\"",
",",
"DeprecationWarning",
")",
"version_split",
"=",
"version",
".",
"split",
"(",
"\".\"",... | Return major version of a provided version string. Major version is the
first component of the dot-separated version string. For non-version-like
strings this function returns the argument unchanged.
The ``remove`` parameter is deprecated since version 1.18 and will be
removed in the future.
:param version: Version string
:type version: str
:rtype: str | [
"Return",
"major",
"version",
"of",
"a",
"provided",
"version",
"string",
".",
"Major",
"version",
"is",
"the",
"first",
"component",
"of",
"the",
"dot",
"-",
"separated",
"version",
"string",
".",
"For",
"non",
"-",
"version",
"-",
"like",
"strings",
"thi... | 49256bf2e8c84124f42346241140b986ad7bfc38 | https://github.com/release-engineering/productmd/blob/49256bf2e8c84124f42346241140b986ad7bfc38/productmd/common.py#L390-L405 | train | 30,785 |
release-engineering/productmd | productmd/common.py | get_minor_version | def get_minor_version(version, remove=None):
"""Return minor version of a provided version string. Minor version is the
second component in the dot-separated version string. For non-version-like
strings this function returns ``None``.
The ``remove`` parameter is deprecated since version 1.18 and will be
removed in the future.
:param version: Version string
:type version: str
:rtype: str
"""
if remove:
warnings.warn("remove argument is deprecated", DeprecationWarning)
version_split = version.split(".")
try:
# Assume MAJOR.MINOR.REST...
return version_split[1]
except IndexError:
return None | python | def get_minor_version(version, remove=None):
"""Return minor version of a provided version string. Minor version is the
second component in the dot-separated version string. For non-version-like
strings this function returns ``None``.
The ``remove`` parameter is deprecated since version 1.18 and will be
removed in the future.
:param version: Version string
:type version: str
:rtype: str
"""
if remove:
warnings.warn("remove argument is deprecated", DeprecationWarning)
version_split = version.split(".")
try:
# Assume MAJOR.MINOR.REST...
return version_split[1]
except IndexError:
return None | [
"def",
"get_minor_version",
"(",
"version",
",",
"remove",
"=",
"None",
")",
":",
"if",
"remove",
":",
"warnings",
".",
"warn",
"(",
"\"remove argument is deprecated\"",
",",
"DeprecationWarning",
")",
"version_split",
"=",
"version",
".",
"split",
"(",
"\".\"",... | Return minor version of a provided version string. Minor version is the
second component in the dot-separated version string. For non-version-like
strings this function returns ``None``.
The ``remove`` parameter is deprecated since version 1.18 and will be
removed in the future.
:param version: Version string
:type version: str
:rtype: str | [
"Return",
"minor",
"version",
"of",
"a",
"provided",
"version",
"string",
".",
"Minor",
"version",
"is",
"the",
"second",
"component",
"in",
"the",
"dot",
"-",
"separated",
"version",
"string",
".",
"For",
"non",
"-",
"version",
"-",
"like",
"strings",
"th... | 49256bf2e8c84124f42346241140b986ad7bfc38 | https://github.com/release-engineering/productmd/blob/49256bf2e8c84124f42346241140b986ad7bfc38/productmd/common.py#L408-L427 | train | 30,786 |
release-engineering/productmd | productmd/common.py | create_release_id | def create_release_id(short, version, type, bp_short=None, bp_version=None, bp_type=None):
"""
Create release_id from given parts.
:param short: Release short name
:type short: str
:param version: Release version
:type version: str
:param version: Release type
:type version: str
:param bp_short: Base Product short name
:type bp_short: str
:param bp_version: Base Product version
:type bp_version: str
:param bp_type: Base Product type
:rtype: str
"""
if not is_valid_release_short(short):
raise ValueError("Release short name is not valid: %s" % short)
if not is_valid_release_version(version):
raise ValueError("Release short version is not valid: %s" % version)
if not is_valid_release_type(type):
raise ValueError("Release type is not valid: %s" % type)
if type == "ga":
result = "%s-%s" % (short, version)
else:
result = "%s-%s-%s" % (short, version, type)
if bp_short:
result += "@%s" % create_release_id(bp_short, bp_version, bp_type)
return result | python | def create_release_id(short, version, type, bp_short=None, bp_version=None, bp_type=None):
"""
Create release_id from given parts.
:param short: Release short name
:type short: str
:param version: Release version
:type version: str
:param version: Release type
:type version: str
:param bp_short: Base Product short name
:type bp_short: str
:param bp_version: Base Product version
:type bp_version: str
:param bp_type: Base Product type
:rtype: str
"""
if not is_valid_release_short(short):
raise ValueError("Release short name is not valid: %s" % short)
if not is_valid_release_version(version):
raise ValueError("Release short version is not valid: %s" % version)
if not is_valid_release_type(type):
raise ValueError("Release type is not valid: %s" % type)
if type == "ga":
result = "%s-%s" % (short, version)
else:
result = "%s-%s-%s" % (short, version, type)
if bp_short:
result += "@%s" % create_release_id(bp_short, bp_version, bp_type)
return result | [
"def",
"create_release_id",
"(",
"short",
",",
"version",
",",
"type",
",",
"bp_short",
"=",
"None",
",",
"bp_version",
"=",
"None",
",",
"bp_type",
"=",
"None",
")",
":",
"if",
"not",
"is_valid_release_short",
"(",
"short",
")",
":",
"raise",
"ValueError"... | Create release_id from given parts.
:param short: Release short name
:type short: str
:param version: Release version
:type version: str
:param version: Release type
:type version: str
:param bp_short: Base Product short name
:type bp_short: str
:param bp_version: Base Product version
:type bp_version: str
:param bp_type: Base Product type
:rtype: str | [
"Create",
"release_id",
"from",
"given",
"parts",
"."
] | 49256bf2e8c84124f42346241140b986ad7bfc38 | https://github.com/release-engineering/productmd/blob/49256bf2e8c84124f42346241140b986ad7bfc38/productmd/common.py#L430-L462 | train | 30,787 |
release-engineering/productmd | productmd/common.py | MetadataBase._assert_matches_re | def _assert_matches_re(self, field, expected_patterns):
"""
The list of patterns can contain either strings or compiled regular
expressions.
"""
value = getattr(self, field)
for pattern in expected_patterns:
try:
if pattern.match(value):
return
except AttributeError:
# It's not a compiled regex, treat it as string.
if re.match(pattern, value):
return
raise ValueError("%s: Field '%s' has invalid value: %s. It does not match any provided REs: %s"
% (self.__class__.__name__, field, value, expected_patterns)) | python | def _assert_matches_re(self, field, expected_patterns):
"""
The list of patterns can contain either strings or compiled regular
expressions.
"""
value = getattr(self, field)
for pattern in expected_patterns:
try:
if pattern.match(value):
return
except AttributeError:
# It's not a compiled regex, treat it as string.
if re.match(pattern, value):
return
raise ValueError("%s: Field '%s' has invalid value: %s. It does not match any provided REs: %s"
% (self.__class__.__name__, field, value, expected_patterns)) | [
"def",
"_assert_matches_re",
"(",
"self",
",",
"field",
",",
"expected_patterns",
")",
":",
"value",
"=",
"getattr",
"(",
"self",
",",
"field",
")",
"for",
"pattern",
"in",
"expected_patterns",
":",
"try",
":",
"if",
"pattern",
".",
"match",
"(",
"value",
... | The list of patterns can contain either strings or compiled regular
expressions. | [
"The",
"list",
"of",
"patterns",
"can",
"contain",
"either",
"strings",
"or",
"compiled",
"regular",
"expressions",
"."
] | 49256bf2e8c84124f42346241140b986ad7bfc38 | https://github.com/release-engineering/productmd/blob/49256bf2e8c84124f42346241140b986ad7bfc38/productmd/common.py#L222-L237 | train | 30,788 |
release-engineering/productmd | productmd/common.py | MetadataBase.loads | def loads(self, s):
"""
Load data from a string.
:param s: input data
:type s: str
"""
io = six.StringIO()
io.write(s)
io.seek(0)
self.load(io)
self.validate() | python | def loads(self, s):
"""
Load data from a string.
:param s: input data
:type s: str
"""
io = six.StringIO()
io.write(s)
io.seek(0)
self.load(io)
self.validate() | [
"def",
"loads",
"(",
"self",
",",
"s",
")",
":",
"io",
"=",
"six",
".",
"StringIO",
"(",
")",
"io",
".",
"write",
"(",
"s",
")",
"io",
".",
"seek",
"(",
"0",
")",
"self",
".",
"load",
"(",
"io",
")",
"self",
".",
"validate",
"(",
")"
] | Load data from a string.
:param s: input data
:type s: str | [
"Load",
"data",
"from",
"a",
"string",
"."
] | 49256bf2e8c84124f42346241140b986ad7bfc38 | https://github.com/release-engineering/productmd/blob/49256bf2e8c84124f42346241140b986ad7bfc38/productmd/common.py#L265-L276 | train | 30,789 |
release-engineering/productmd | productmd/common.py | MetadataBase.dump | def dump(self, f):
"""
Dump data to a file.
:param f: file-like object or path to file
:type f: file or str
"""
self.validate()
with _open_file_obj(f, "w") as f:
parser = self._get_parser()
self.serialize(parser)
self.build_file(parser, f) | python | def dump(self, f):
"""
Dump data to a file.
:param f: file-like object or path to file
:type f: file or str
"""
self.validate()
with _open_file_obj(f, "w") as f:
parser = self._get_parser()
self.serialize(parser)
self.build_file(parser, f) | [
"def",
"dump",
"(",
"self",
",",
"f",
")",
":",
"self",
".",
"validate",
"(",
")",
"with",
"_open_file_obj",
"(",
"f",
",",
"\"w\"",
")",
"as",
"f",
":",
"parser",
"=",
"self",
".",
"_get_parser",
"(",
")",
"self",
".",
"serialize",
"(",
"parser",
... | Dump data to a file.
:param f: file-like object or path to file
:type f: file or str | [
"Dump",
"data",
"to",
"a",
"file",
"."
] | 49256bf2e8c84124f42346241140b986ad7bfc38 | https://github.com/release-engineering/productmd/blob/49256bf2e8c84124f42346241140b986ad7bfc38/productmd/common.py#L278-L289 | train | 30,790 |
release-engineering/productmd | productmd/common.py | MetadataBase.dumps | def dumps(self):
"""
Dump data to a string.
:rtype: str
"""
io = six.StringIO()
self.dump(io)
io.seek(0)
return io.read() | python | def dumps(self):
"""
Dump data to a string.
:rtype: str
"""
io = six.StringIO()
self.dump(io)
io.seek(0)
return io.read() | [
"def",
"dumps",
"(",
"self",
")",
":",
"io",
"=",
"six",
".",
"StringIO",
"(",
")",
"self",
".",
"dump",
"(",
"io",
")",
"io",
".",
"seek",
"(",
"0",
")",
"return",
"io",
".",
"read",
"(",
")"
] | Dump data to a string.
:rtype: str | [
"Dump",
"data",
"to",
"a",
"string",
"."
] | 49256bf2e8c84124f42346241140b986ad7bfc38 | https://github.com/release-engineering/productmd/blob/49256bf2e8c84124f42346241140b986ad7bfc38/productmd/common.py#L291-L300 | train | 30,791 |
release-engineering/productmd | productmd/composeinfo.py | BaseProduct._validate_version | def _validate_version(self):
"""If the version starts with a digit, it must be a sematic-versioning
style string.
"""
self._assert_type("version", list(six.string_types))
self._assert_matches_re("version", [RELEASE_VERSION_RE]) | python | def _validate_version(self):
"""If the version starts with a digit, it must be a sematic-versioning
style string.
"""
self._assert_type("version", list(six.string_types))
self._assert_matches_re("version", [RELEASE_VERSION_RE]) | [
"def",
"_validate_version",
"(",
"self",
")",
":",
"self",
".",
"_assert_type",
"(",
"\"version\"",
",",
"list",
"(",
"six",
".",
"string_types",
")",
")",
"self",
".",
"_assert_matches_re",
"(",
"\"version\"",
",",
"[",
"RELEASE_VERSION_RE",
"]",
")"
] | If the version starts with a digit, it must be a sematic-versioning
style string. | [
"If",
"the",
"version",
"starts",
"with",
"a",
"digit",
"it",
"must",
"be",
"a",
"sematic",
"-",
"versioning",
"style",
"string",
"."
] | 49256bf2e8c84124f42346241140b986ad7bfc38 | https://github.com/release-engineering/productmd/blob/49256bf2e8c84124f42346241140b986ad7bfc38/productmd/composeinfo.py#L422-L427 | train | 30,792 |
release-engineering/productmd | productmd/composeinfo.py | BaseProduct.type_suffix | def type_suffix(self):
"""This is used in compose ID."""
if not self.type or self.type.lower() == 'ga':
return ''
return '-%s' % self.type.lower() | python | def type_suffix(self):
"""This is used in compose ID."""
if not self.type or self.type.lower() == 'ga':
return ''
return '-%s' % self.type.lower() | [
"def",
"type_suffix",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"type",
"or",
"self",
".",
"type",
".",
"lower",
"(",
")",
"==",
"'ga'",
":",
"return",
"''",
"return",
"'-%s'",
"%",
"self",
".",
"type",
".",
"lower",
"(",
")"
] | This is used in compose ID. | [
"This",
"is",
"used",
"in",
"compose",
"ID",
"."
] | 49256bf2e8c84124f42346241140b986ad7bfc38 | https://github.com/release-engineering/productmd/blob/49256bf2e8c84124f42346241140b986ad7bfc38/productmd/composeinfo.py#L449-L453 | train | 30,793 |
release-engineering/productmd | productmd/composeinfo.py | VariantBase.get_variants | def get_variants(self, arch=None, types=None, recursive=False):
"""
Return all variants of given arch and types.
Supported variant types:
self - include the top-level ("self") variant as well
addon
variant
optional
"""
types = types or []
result = []
if "self" in types:
result.append(self)
for variant in six.itervalues(self.variants):
if types and variant.type not in types:
continue
if arch and arch not in variant.arches.union(["src"]):
continue
result.append(variant)
if recursive:
result.extend(variant.get_variants(types=[i for i in types if i != "self"], recursive=True))
result.sort(key=lambda x: x.uid)
return result | python | def get_variants(self, arch=None, types=None, recursive=False):
"""
Return all variants of given arch and types.
Supported variant types:
self - include the top-level ("self") variant as well
addon
variant
optional
"""
types = types or []
result = []
if "self" in types:
result.append(self)
for variant in six.itervalues(self.variants):
if types and variant.type not in types:
continue
if arch and arch not in variant.arches.union(["src"]):
continue
result.append(variant)
if recursive:
result.extend(variant.get_variants(types=[i for i in types if i != "self"], recursive=True))
result.sort(key=lambda x: x.uid)
return result | [
"def",
"get_variants",
"(",
"self",
",",
"arch",
"=",
"None",
",",
"types",
"=",
"None",
",",
"recursive",
"=",
"False",
")",
":",
"types",
"=",
"types",
"or",
"[",
"]",
"result",
"=",
"[",
"]",
"if",
"\"self\"",
"in",
"types",
":",
"result",
".",
... | Return all variants of given arch and types.
Supported variant types:
self - include the top-level ("self") variant as well
addon
variant
optional | [
"Return",
"all",
"variants",
"of",
"given",
"arch",
"and",
"types",
"."
] | 49256bf2e8c84124f42346241140b986ad7bfc38 | https://github.com/release-engineering/productmd/blob/49256bf2e8c84124f42346241140b986ad7bfc38/productmd/composeinfo.py#L605-L631 | train | 30,794 |
release-engineering/productmd | productmd/rpms.py | Rpms.add | def add(self, variant, arch, nevra, path, sigkey, category, srpm_nevra=None):
"""
Map RPM to to variant and arch.
:param variant: compose variant UID
:type variant: str
:param arch: compose architecture
:type arch: str
:param nevra: name-epoch:version-release.arch
:type nevra: str
:param sigkey: sigkey hash
:type sigkey: str or None
:param category: RPM category, one of binary, debug, source
:type category: str
:param srpm_nevra: name-epoch:version-release.arch of RPM's SRPM
:type srpm_nevra: str
"""
if arch not in productmd.common.RPM_ARCHES:
raise ValueError("Arch not found in RPM_ARCHES: %s" % arch)
if arch in ["src", "nosrc"]:
raise ValueError("Source arch is not allowed. Map source files under binary arches.")
if category not in SUPPORTED_CATEGORIES:
raise ValueError("Invalid category value: %s" % category)
if path.startswith("/"):
raise ValueError("Relative path expected: %s" % path)
nevra, nevra_dict = self._check_nevra(nevra)
if category == "source" and srpm_nevra is not None:
raise ValueError("Expected blank srpm_nevra for source package: %s" % nevra)
if category != "source" and srpm_nevra is None:
raise ValueError("Missing srpm_nevra for package: %s" % nevra)
if (category == "source") != (nevra_dict["arch"] in ("src", "nosrc")):
raise ValueError("Invalid category/arch combination: %s/%s" % (category, nevra))
if sigkey is not None:
sigkey = sigkey.lower()
if srpm_nevra:
srpm_nevra, _ = self._check_nevra(srpm_nevra)
else:
srpm_nevra = nevra
arches = self.rpms.setdefault(variant, {})
srpms = arches.setdefault(arch, {})
rpms = srpms.setdefault(srpm_nevra, {})
rpms[nevra] = {"sigkey": sigkey, "path": path, "category": category} | python | def add(self, variant, arch, nevra, path, sigkey, category, srpm_nevra=None):
"""
Map RPM to to variant and arch.
:param variant: compose variant UID
:type variant: str
:param arch: compose architecture
:type arch: str
:param nevra: name-epoch:version-release.arch
:type nevra: str
:param sigkey: sigkey hash
:type sigkey: str or None
:param category: RPM category, one of binary, debug, source
:type category: str
:param srpm_nevra: name-epoch:version-release.arch of RPM's SRPM
:type srpm_nevra: str
"""
if arch not in productmd.common.RPM_ARCHES:
raise ValueError("Arch not found in RPM_ARCHES: %s" % arch)
if arch in ["src", "nosrc"]:
raise ValueError("Source arch is not allowed. Map source files under binary arches.")
if category not in SUPPORTED_CATEGORIES:
raise ValueError("Invalid category value: %s" % category)
if path.startswith("/"):
raise ValueError("Relative path expected: %s" % path)
nevra, nevra_dict = self._check_nevra(nevra)
if category == "source" and srpm_nevra is not None:
raise ValueError("Expected blank srpm_nevra for source package: %s" % nevra)
if category != "source" and srpm_nevra is None:
raise ValueError("Missing srpm_nevra for package: %s" % nevra)
if (category == "source") != (nevra_dict["arch"] in ("src", "nosrc")):
raise ValueError("Invalid category/arch combination: %s/%s" % (category, nevra))
if sigkey is not None:
sigkey = sigkey.lower()
if srpm_nevra:
srpm_nevra, _ = self._check_nevra(srpm_nevra)
else:
srpm_nevra = nevra
arches = self.rpms.setdefault(variant, {})
srpms = arches.setdefault(arch, {})
rpms = srpms.setdefault(srpm_nevra, {})
rpms[nevra] = {"sigkey": sigkey, "path": path, "category": category} | [
"def",
"add",
"(",
"self",
",",
"variant",
",",
"arch",
",",
"nevra",
",",
"path",
",",
"sigkey",
",",
"category",
",",
"srpm_nevra",
"=",
"None",
")",
":",
"if",
"arch",
"not",
"in",
"productmd",
".",
"common",
".",
"RPM_ARCHES",
":",
"raise",
"Valu... | Map RPM to to variant and arch.
:param variant: compose variant UID
:type variant: str
:param arch: compose architecture
:type arch: str
:param nevra: name-epoch:version-release.arch
:type nevra: str
:param sigkey: sigkey hash
:type sigkey: str or None
:param category: RPM category, one of binary, debug, source
:type category: str
:param srpm_nevra: name-epoch:version-release.arch of RPM's SRPM
:type srpm_nevra: str | [
"Map",
"RPM",
"to",
"to",
"variant",
"and",
"arch",
"."
] | 49256bf2e8c84124f42346241140b986ad7bfc38 | https://github.com/release-engineering/productmd/blob/49256bf2e8c84124f42346241140b986ad7bfc38/productmd/rpms.py#L133-L185 | train | 30,795 |
mopidy/mopidy-gmusic | mopidy_gmusic/translator.py | album_to_ref | def album_to_ref(album):
"""Convert a mopidy album to a mopidy ref."""
name = ''
for artist in album.artists:
if len(name) > 0:
name += ', '
name += artist.name
if (len(name)) > 0:
name += ' - '
if album.name:
name += album.name
else:
name += 'Unknown Album'
return Ref.directory(uri=album.uri, name=name) | python | def album_to_ref(album):
"""Convert a mopidy album to a mopidy ref."""
name = ''
for artist in album.artists:
if len(name) > 0:
name += ', '
name += artist.name
if (len(name)) > 0:
name += ' - '
if album.name:
name += album.name
else:
name += 'Unknown Album'
return Ref.directory(uri=album.uri, name=name) | [
"def",
"album_to_ref",
"(",
"album",
")",
":",
"name",
"=",
"''",
"for",
"artist",
"in",
"album",
".",
"artists",
":",
"if",
"len",
"(",
"name",
")",
">",
"0",
":",
"name",
"+=",
"', '",
"name",
"+=",
"artist",
".",
"name",
"if",
"(",
"len",
"(",... | Convert a mopidy album to a mopidy ref. | [
"Convert",
"a",
"mopidy",
"album",
"to",
"a",
"mopidy",
"ref",
"."
] | bbfe876d2a7e4f0f4f9308193bb988936bdfd5c3 | https://github.com/mopidy/mopidy-gmusic/blob/bbfe876d2a7e4f0f4f9308193bb988936bdfd5c3/mopidy_gmusic/translator.py#L8-L21 | train | 30,796 |
mopidy/mopidy-gmusic | mopidy_gmusic/translator.py | artist_to_ref | def artist_to_ref(artist):
"""Convert a mopidy artist to a mopidy ref."""
if artist.name:
name = artist.name
else:
name = 'Unknown artist'
return Ref.directory(uri=artist.uri, name=name) | python | def artist_to_ref(artist):
"""Convert a mopidy artist to a mopidy ref."""
if artist.name:
name = artist.name
else:
name = 'Unknown artist'
return Ref.directory(uri=artist.uri, name=name) | [
"def",
"artist_to_ref",
"(",
"artist",
")",
":",
"if",
"artist",
".",
"name",
":",
"name",
"=",
"artist",
".",
"name",
"else",
":",
"name",
"=",
"'Unknown artist'",
"return",
"Ref",
".",
"directory",
"(",
"uri",
"=",
"artist",
".",
"uri",
",",
"name",
... | Convert a mopidy artist to a mopidy ref. | [
"Convert",
"a",
"mopidy",
"artist",
"to",
"a",
"mopidy",
"ref",
"."
] | bbfe876d2a7e4f0f4f9308193bb988936bdfd5c3 | https://github.com/mopidy/mopidy-gmusic/blob/bbfe876d2a7e4f0f4f9308193bb988936bdfd5c3/mopidy_gmusic/translator.py#L24-L30 | train | 30,797 |
mopidy/mopidy-gmusic | mopidy_gmusic/translator.py | track_to_ref | def track_to_ref(track, with_track_no=False):
"""Convert a mopidy track to a mopidy ref."""
if with_track_no and track.track_no > 0:
name = '%d - ' % track.track_no
else:
name = ''
for artist in track.artists:
if len(name) > 0:
name += ', '
name += artist.name
if (len(name)) > 0:
name += ' - '
name += track.name
return Ref.track(uri=track.uri, name=name) | python | def track_to_ref(track, with_track_no=False):
"""Convert a mopidy track to a mopidy ref."""
if with_track_no and track.track_no > 0:
name = '%d - ' % track.track_no
else:
name = ''
for artist in track.artists:
if len(name) > 0:
name += ', '
name += artist.name
if (len(name)) > 0:
name += ' - '
name += track.name
return Ref.track(uri=track.uri, name=name) | [
"def",
"track_to_ref",
"(",
"track",
",",
"with_track_no",
"=",
"False",
")",
":",
"if",
"with_track_no",
"and",
"track",
".",
"track_no",
">",
"0",
":",
"name",
"=",
"'%d - '",
"%",
"track",
".",
"track_no",
"else",
":",
"name",
"=",
"''",
"for",
"art... | Convert a mopidy track to a mopidy ref. | [
"Convert",
"a",
"mopidy",
"track",
"to",
"a",
"mopidy",
"ref",
"."
] | bbfe876d2a7e4f0f4f9308193bb988936bdfd5c3 | https://github.com/mopidy/mopidy-gmusic/blob/bbfe876d2a7e4f0f4f9308193bb988936bdfd5c3/mopidy_gmusic/translator.py#L33-L46 | train | 30,798 |
tulir/mautrix-python | mautrix_appservice/intent_api.py | HTTPAPI.user | def user(self, user: str) -> "ChildHTTPAPI":
"""
Get a child HTTPAPI instance.
Args:
user: The Matrix ID of the user whose API to get.
Returns:
A HTTPAPI instance that always uses the given Matrix ID.
"""
if self.is_real_user:
raise ValueError("Can't get child of real user")
try:
return self.children[user]
except KeyError:
child = ChildHTTPAPI(user, self)
self.children[user] = child
return child | python | def user(self, user: str) -> "ChildHTTPAPI":
"""
Get a child HTTPAPI instance.
Args:
user: The Matrix ID of the user whose API to get.
Returns:
A HTTPAPI instance that always uses the given Matrix ID.
"""
if self.is_real_user:
raise ValueError("Can't get child of real user")
try:
return self.children[user]
except KeyError:
child = ChildHTTPAPI(user, self)
self.children[user] = child
return child | [
"def",
"user",
"(",
"self",
",",
"user",
":",
"str",
")",
"->",
"\"ChildHTTPAPI\"",
":",
"if",
"self",
".",
"is_real_user",
":",
"raise",
"ValueError",
"(",
"\"Can't get child of real user\"",
")",
"try",
":",
"return",
"self",
".",
"children",
"[",
"user",
... | Get a child HTTPAPI instance.
Args:
user: The Matrix ID of the user whose API to get.
Returns:
A HTTPAPI instance that always uses the given Matrix ID. | [
"Get",
"a",
"child",
"HTTPAPI",
"instance",
"."
] | 21bb0870e4103dd03ecc61396ce02adb9301f382 | https://github.com/tulir/mautrix-python/blob/21bb0870e4103dd03ecc61396ce02adb9301f382/mautrix_appservice/intent_api.py#L59-L77 | train | 30,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.