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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
gisce/libComXML | libcomxml/core/__init__.py | XmlModel.build_tree | def build_tree(self):
"""Bulids the tree with all the fields converted to Elements
"""
if self.built:
return
self.doc_root = self.root.element()
for key in self.sorted_fields():
if key not in self._fields:
continue
field = self._fields[key]
if field != self.root:
if isinstance(field, XmlModel):
field.build_tree()
if (self.drop_empty and field.drop_empty
and len(field.doc_root) == 0):
continue
self.doc_root.append(field.doc_root)
elif isinstance(field, list):
# we just allow XmlFields and XmlModels
# Also xml as str for memory management
for item in field:
if isinstance(item, XmlField):
ele = item.element()
if self.drop_empty and len(ele) == 0:
continue
self.doc_root.append(ele)
elif isinstance(item, XmlModel):
item.build_tree()
if self.drop_empty and len(item.doc_root) == 0:
continue
self.doc_root.append(item.doc_root)
elif isinstance(item, (six.text_type, six.string_types)):
ele = etree.fromstring(clean_xml(item))
self.doc_root.append(ele)
item = None
elif (field.parent or self.root.name) == self.root.name:
ele = field.element()
if self.drop_empty and len(ele) == 0 and not ele.text:
continue
ele = field.element(parent=self.doc_root)
else:
nodes = [n for n in self.doc_root.iterdescendants(
tag=field.parent)]
if nodes:
ele = field.element()
if (self.drop_empty and len(ele) == 0 and not ele.text):
continue
ele = field.element(parent=nodes[0])
#else:
# raise RuntimeError("No parent found!")
self.built = True | python | def build_tree(self):
"""Bulids the tree with all the fields converted to Elements
"""
if self.built:
return
self.doc_root = self.root.element()
for key in self.sorted_fields():
if key not in self._fields:
continue
field = self._fields[key]
if field != self.root:
if isinstance(field, XmlModel):
field.build_tree()
if (self.drop_empty and field.drop_empty
and len(field.doc_root) == 0):
continue
self.doc_root.append(field.doc_root)
elif isinstance(field, list):
# we just allow XmlFields and XmlModels
# Also xml as str for memory management
for item in field:
if isinstance(item, XmlField):
ele = item.element()
if self.drop_empty and len(ele) == 0:
continue
self.doc_root.append(ele)
elif isinstance(item, XmlModel):
item.build_tree()
if self.drop_empty and len(item.doc_root) == 0:
continue
self.doc_root.append(item.doc_root)
elif isinstance(item, (six.text_type, six.string_types)):
ele = etree.fromstring(clean_xml(item))
self.doc_root.append(ele)
item = None
elif (field.parent or self.root.name) == self.root.name:
ele = field.element()
if self.drop_empty and len(ele) == 0 and not ele.text:
continue
ele = field.element(parent=self.doc_root)
else:
nodes = [n for n in self.doc_root.iterdescendants(
tag=field.parent)]
if nodes:
ele = field.element()
if (self.drop_empty and len(ele) == 0 and not ele.text):
continue
ele = field.element(parent=nodes[0])
#else:
# raise RuntimeError("No parent found!")
self.built = True | [
"def",
"build_tree",
"(",
"self",
")",
":",
"if",
"self",
".",
"built",
":",
"return",
"self",
".",
"doc_root",
"=",
"self",
".",
"root",
".",
"element",
"(",
")",
"for",
"key",
"in",
"self",
".",
"sorted_fields",
"(",
")",
":",
"if",
"key",
"not",... | Bulids the tree with all the fields converted to Elements | [
"Bulids",
"the",
"tree",
"with",
"all",
"the",
"fields",
"converted",
"to",
"Elements"
] | 0aab7fe8790e33484778ac7b1ec827f9094d81f7 | https://github.com/gisce/libComXML/blob/0aab7fe8790e33484778ac7b1ec827f9094d81f7/libcomxml/core/__init__.py#L223-L273 | train | 24,400 |
timofurrer/observable | observable/property.py | _preserve_settings | def _preserve_settings(method: T.Callable) -> T.Callable:
"""Decorator that ensures ObservableProperty-specific attributes
are kept when using methods to change deleter, getter or setter."""
@functools.wraps(method)
def _wrapper(
old: "ObservableProperty", handler: T.Callable
) -> "ObservableProperty":
new = method(old, handler) # type: ObservableProperty
new.event = old.event
new.observable = old.observable
return new
return _wrapper | python | def _preserve_settings(method: T.Callable) -> T.Callable:
"""Decorator that ensures ObservableProperty-specific attributes
are kept when using methods to change deleter, getter or setter."""
@functools.wraps(method)
def _wrapper(
old: "ObservableProperty", handler: T.Callable
) -> "ObservableProperty":
new = method(old, handler) # type: ObservableProperty
new.event = old.event
new.observable = old.observable
return new
return _wrapper | [
"def",
"_preserve_settings",
"(",
"method",
":",
"T",
".",
"Callable",
")",
"->",
"T",
".",
"Callable",
":",
"@",
"functools",
".",
"wraps",
"(",
"method",
")",
"def",
"_wrapper",
"(",
"old",
":",
"\"ObservableProperty\"",
",",
"handler",
":",
"T",
".",
... | Decorator that ensures ObservableProperty-specific attributes
are kept when using methods to change deleter, getter or setter. | [
"Decorator",
"that",
"ensures",
"ObservableProperty",
"-",
"specific",
"attributes",
"are",
"kept",
"when",
"using",
"methods",
"to",
"change",
"deleter",
"getter",
"or",
"setter",
"."
] | a6a764efaf9408a334bdb1ddf4327d9dbc4b8eaa | https://github.com/timofurrer/observable/blob/a6a764efaf9408a334bdb1ddf4327d9dbc4b8eaa/observable/property.py#L15-L28 | train | 24,401 |
timofurrer/observable | observable/property.py | ObservableProperty._trigger_event | def _trigger_event(
self, holder: T.Any, alt_name: str, action: str, *event_args: T.Any
) -> None:
"""Triggers an event on the associated Observable object.
The Holder is the object this property is a member of, alt_name
is used as the event name when self.event is not set, action is
prepended to the event name and event_args are passed through
to the registered event handlers."""
if isinstance(self.observable, Observable):
observable = self.observable
elif isinstance(self.observable, str):
observable = getattr(holder, self.observable)
elif isinstance(holder, Observable):
observable = holder
else:
raise TypeError(
"This ObservableProperty is no member of an Observable "
"object. Specify where to find the Observable object for "
"triggering events with the observable keyword argument "
"when initializing the ObservableProperty."
)
name = alt_name if self.event is None else self.event
event = "{}_{}".format(action, name)
observable.trigger(event, *event_args) | python | def _trigger_event(
self, holder: T.Any, alt_name: str, action: str, *event_args: T.Any
) -> None:
"""Triggers an event on the associated Observable object.
The Holder is the object this property is a member of, alt_name
is used as the event name when self.event is not set, action is
prepended to the event name and event_args are passed through
to the registered event handlers."""
if isinstance(self.observable, Observable):
observable = self.observable
elif isinstance(self.observable, str):
observable = getattr(holder, self.observable)
elif isinstance(holder, Observable):
observable = holder
else:
raise TypeError(
"This ObservableProperty is no member of an Observable "
"object. Specify where to find the Observable object for "
"triggering events with the observable keyword argument "
"when initializing the ObservableProperty."
)
name = alt_name if self.event is None else self.event
event = "{}_{}".format(action, name)
observable.trigger(event, *event_args) | [
"def",
"_trigger_event",
"(",
"self",
",",
"holder",
":",
"T",
".",
"Any",
",",
"alt_name",
":",
"str",
",",
"action",
":",
"str",
",",
"*",
"event_args",
":",
"T",
".",
"Any",
")",
"->",
"None",
":",
"if",
"isinstance",
"(",
"self",
".",
"observab... | Triggers an event on the associated Observable object.
The Holder is the object this property is a member of, alt_name
is used as the event name when self.event is not set, action is
prepended to the event name and event_args are passed through
to the registered event handlers. | [
"Triggers",
"an",
"event",
"on",
"the",
"associated",
"Observable",
"object",
".",
"The",
"Holder",
"is",
"the",
"object",
"this",
"property",
"is",
"a",
"member",
"of",
"alt_name",
"is",
"used",
"as",
"the",
"event",
"name",
"when",
"self",
".",
"event",
... | a6a764efaf9408a334bdb1ddf4327d9dbc4b8eaa | https://github.com/timofurrer/observable/blob/a6a764efaf9408a334bdb1ddf4327d9dbc4b8eaa/observable/property.py#L70-L95 | train | 24,402 |
timofurrer/observable | observable/property.py | ObservableProperty.create_with | def create_with(
cls, event: str = None, observable: T.Union[str, Observable] = None
) -> T.Callable[..., "ObservableProperty"]:
"""Creates a partial application of ObservableProperty with
event and observable preset."""
return functools.partial(cls, event=event, observable=observable) | python | def create_with(
cls, event: str = None, observable: T.Union[str, Observable] = None
) -> T.Callable[..., "ObservableProperty"]:
"""Creates a partial application of ObservableProperty with
event and observable preset."""
return functools.partial(cls, event=event, observable=observable) | [
"def",
"create_with",
"(",
"cls",
",",
"event",
":",
"str",
"=",
"None",
",",
"observable",
":",
"T",
".",
"Union",
"[",
"str",
",",
"Observable",
"]",
"=",
"None",
")",
"->",
"T",
".",
"Callable",
"[",
"...",
",",
"\"ObservableProperty\"",
"]",
":",... | Creates a partial application of ObservableProperty with
event and observable preset. | [
"Creates",
"a",
"partial",
"application",
"of",
"ObservableProperty",
"with",
"event",
"and",
"observable",
"preset",
"."
] | a6a764efaf9408a334bdb1ddf4327d9dbc4b8eaa | https://github.com/timofurrer/observable/blob/a6a764efaf9408a334bdb1ddf4327d9dbc4b8eaa/observable/property.py#L102-L108 | train | 24,403 |
timofurrer/observable | observable/core.py | Observable.get_all_handlers | def get_all_handlers(self) -> T.Dict[str, T.List[T.Callable]]:
"""Returns a dict with event names as keys and lists of
registered handlers as values."""
events = {}
for event, handlers in self._events.items():
events[event] = list(handlers)
return events | python | def get_all_handlers(self) -> T.Dict[str, T.List[T.Callable]]:
"""Returns a dict with event names as keys and lists of
registered handlers as values."""
events = {}
for event, handlers in self._events.items():
events[event] = list(handlers)
return events | [
"def",
"get_all_handlers",
"(",
"self",
")",
"->",
"T",
".",
"Dict",
"[",
"str",
",",
"T",
".",
"List",
"[",
"T",
".",
"Callable",
"]",
"]",
":",
"events",
"=",
"{",
"}",
"for",
"event",
",",
"handlers",
"in",
"self",
".",
"_events",
".",
"items"... | Returns a dict with event names as keys and lists of
registered handlers as values. | [
"Returns",
"a",
"dict",
"with",
"event",
"names",
"as",
"keys",
"and",
"lists",
"of",
"registered",
"handlers",
"as",
"values",
"."
] | a6a764efaf9408a334bdb1ddf4327d9dbc4b8eaa | https://github.com/timofurrer/observable/blob/a6a764efaf9408a334bdb1ddf4327d9dbc4b8eaa/observable/core.py#L39-L46 | train | 24,404 |
timofurrer/observable | observable/core.py | Observable.get_handlers | def get_handlers(self, event: str) -> T.List[T.Callable]:
"""Returns a list of handlers registered for the given event."""
return list(self._events.get(event, [])) | python | def get_handlers(self, event: str) -> T.List[T.Callable]:
"""Returns a list of handlers registered for the given event."""
return list(self._events.get(event, [])) | [
"def",
"get_handlers",
"(",
"self",
",",
"event",
":",
"str",
")",
"->",
"T",
".",
"List",
"[",
"T",
".",
"Callable",
"]",
":",
"return",
"list",
"(",
"self",
".",
"_events",
".",
"get",
"(",
"event",
",",
"[",
"]",
")",
")"
] | Returns a list of handlers registered for the given event. | [
"Returns",
"a",
"list",
"of",
"handlers",
"registered",
"for",
"the",
"given",
"event",
"."
] | a6a764efaf9408a334bdb1ddf4327d9dbc4b8eaa | https://github.com/timofurrer/observable/blob/a6a764efaf9408a334bdb1ddf4327d9dbc4b8eaa/observable/core.py#L48-L51 | train | 24,405 |
timofurrer/observable | observable/core.py | Observable.is_registered | def is_registered(self, event: str, handler: T.Callable) -> bool:
"""Returns whether the given handler is registered for the
given event."""
return handler in self._events.get(event, []) | python | def is_registered(self, event: str, handler: T.Callable) -> bool:
"""Returns whether the given handler is registered for the
given event."""
return handler in self._events.get(event, []) | [
"def",
"is_registered",
"(",
"self",
",",
"event",
":",
"str",
",",
"handler",
":",
"T",
".",
"Callable",
")",
"->",
"bool",
":",
"return",
"handler",
"in",
"self",
".",
"_events",
".",
"get",
"(",
"event",
",",
"[",
"]",
")"
] | Returns whether the given handler is registered for the
given event. | [
"Returns",
"whether",
"the",
"given",
"handler",
"is",
"registered",
"for",
"the",
"given",
"event",
"."
] | a6a764efaf9408a334bdb1ddf4327d9dbc4b8eaa | https://github.com/timofurrer/observable/blob/a6a764efaf9408a334bdb1ddf4327d9dbc4b8eaa/observable/core.py#L53-L57 | train | 24,406 |
timofurrer/observable | observable/core.py | Observable.on | def on( # pylint: disable=invalid-name
self, event: str, *handlers: T.Callable
) -> T.Callable:
"""Registers one or more handlers to a specified event.
This method may as well be used as a decorator for the handler."""
def _on_wrapper(*handlers: T.Callable) -> T.Callable:
"""wrapper for on decorator"""
self._events[event].extend(handlers)
return handlers[0]
if handlers:
return _on_wrapper(*handlers)
return _on_wrapper | python | def on( # pylint: disable=invalid-name
self, event: str, *handlers: T.Callable
) -> T.Callable:
"""Registers one or more handlers to a specified event.
This method may as well be used as a decorator for the handler."""
def _on_wrapper(*handlers: T.Callable) -> T.Callable:
"""wrapper for on decorator"""
self._events[event].extend(handlers)
return handlers[0]
if handlers:
return _on_wrapper(*handlers)
return _on_wrapper | [
"def",
"on",
"(",
"# pylint: disable=invalid-name",
"self",
",",
"event",
":",
"str",
",",
"*",
"handlers",
":",
"T",
".",
"Callable",
")",
"->",
"T",
".",
"Callable",
":",
"def",
"_on_wrapper",
"(",
"*",
"handlers",
":",
"T",
".",
"Callable",
")",
"->... | Registers one or more handlers to a specified event.
This method may as well be used as a decorator for the handler. | [
"Registers",
"one",
"or",
"more",
"handlers",
"to",
"a",
"specified",
"event",
".",
"This",
"method",
"may",
"as",
"well",
"be",
"used",
"as",
"a",
"decorator",
"for",
"the",
"handler",
"."
] | a6a764efaf9408a334bdb1ddf4327d9dbc4b8eaa | https://github.com/timofurrer/observable/blob/a6a764efaf9408a334bdb1ddf4327d9dbc4b8eaa/observable/core.py#L59-L72 | train | 24,407 |
timofurrer/observable | observable/core.py | Observable.once | def once(self, event: str, *handlers: T.Callable) -> T.Callable:
"""Registers one or more handlers to a specified event, but
removes them when the event is first triggered.
This method may as well be used as a decorator for the handler."""
def _once_wrapper(*handlers: T.Callable) -> T.Callable:
"""Wrapper for 'once' decorator"""
def _wrapper(*args: T.Any, **kw: T.Any) -> None:
"""Wrapper that unregisters itself before executing
the handlers"""
self.off(event, _wrapper)
for handler in handlers:
handler(*args, **kw)
return _wrapper
if handlers:
return self.on(event, _once_wrapper(*handlers))
return lambda x: self.on(event, _once_wrapper(x)) | python | def once(self, event: str, *handlers: T.Callable) -> T.Callable:
"""Registers one or more handlers to a specified event, but
removes them when the event is first triggered.
This method may as well be used as a decorator for the handler."""
def _once_wrapper(*handlers: T.Callable) -> T.Callable:
"""Wrapper for 'once' decorator"""
def _wrapper(*args: T.Any, **kw: T.Any) -> None:
"""Wrapper that unregisters itself before executing
the handlers"""
self.off(event, _wrapper)
for handler in handlers:
handler(*args, **kw)
return _wrapper
if handlers:
return self.on(event, _once_wrapper(*handlers))
return lambda x: self.on(event, _once_wrapper(x)) | [
"def",
"once",
"(",
"self",
",",
"event",
":",
"str",
",",
"*",
"handlers",
":",
"T",
".",
"Callable",
")",
"->",
"T",
".",
"Callable",
":",
"def",
"_once_wrapper",
"(",
"*",
"handlers",
":",
"T",
".",
"Callable",
")",
"->",
"T",
".",
"Callable",
... | Registers one or more handlers to a specified event, but
removes them when the event is first triggered.
This method may as well be used as a decorator for the handler. | [
"Registers",
"one",
"or",
"more",
"handlers",
"to",
"a",
"specified",
"event",
"but",
"removes",
"them",
"when",
"the",
"event",
"is",
"first",
"triggered",
".",
"This",
"method",
"may",
"as",
"well",
"be",
"used",
"as",
"a",
"decorator",
"for",
"the",
"... | a6a764efaf9408a334bdb1ddf4327d9dbc4b8eaa | https://github.com/timofurrer/observable/blob/a6a764efaf9408a334bdb1ddf4327d9dbc4b8eaa/observable/core.py#L100-L120 | train | 24,408 |
timofurrer/observable | observable/core.py | Observable.trigger | def trigger(self, event: str, *args: T.Any, **kw: T.Any) -> bool:
"""Triggers all handlers which are subscribed to an event.
Returns True when there were callbacks to execute, False otherwise."""
callbacks = list(self._events.get(event, []))
if not callbacks:
return False
for callback in callbacks:
callback(*args, **kw)
return True | python | def trigger(self, event: str, *args: T.Any, **kw: T.Any) -> bool:
"""Triggers all handlers which are subscribed to an event.
Returns True when there were callbacks to execute, False otherwise."""
callbacks = list(self._events.get(event, []))
if not callbacks:
return False
for callback in callbacks:
callback(*args, **kw)
return True | [
"def",
"trigger",
"(",
"self",
",",
"event",
":",
"str",
",",
"*",
"args",
":",
"T",
".",
"Any",
",",
"*",
"*",
"kw",
":",
"T",
".",
"Any",
")",
"->",
"bool",
":",
"callbacks",
"=",
"list",
"(",
"self",
".",
"_events",
".",
"get",
"(",
"event... | Triggers all handlers which are subscribed to an event.
Returns True when there were callbacks to execute, False otherwise. | [
"Triggers",
"all",
"handlers",
"which",
"are",
"subscribed",
"to",
"an",
"event",
".",
"Returns",
"True",
"when",
"there",
"were",
"callbacks",
"to",
"execute",
"False",
"otherwise",
"."
] | a6a764efaf9408a334bdb1ddf4327d9dbc4b8eaa | https://github.com/timofurrer/observable/blob/a6a764efaf9408a334bdb1ddf4327d9dbc4b8eaa/observable/core.py#L122-L132 | train | 24,409 |
jacobtomlinson/datapoint-python | datapoint/__init__.py | connection | def connection(profile_name='default', api_key=None):
"""Connect to DataPoint with the given API key profile name."""
if api_key is None:
profile_fname = datapoint.profile.API_profile_fname(profile_name)
if not os.path.exists(profile_fname):
raise ValueError('Profile not found in {}. Please install your API \n'
'key with datapoint.profile.install_API_key('
'"<YOUR-KEY>")'.format(profile_fname))
with open(profile_fname) as fh:
api_key = fh.readlines()
return Manager(api_key=api_key) | python | def connection(profile_name='default', api_key=None):
"""Connect to DataPoint with the given API key profile name."""
if api_key is None:
profile_fname = datapoint.profile.API_profile_fname(profile_name)
if not os.path.exists(profile_fname):
raise ValueError('Profile not found in {}. Please install your API \n'
'key with datapoint.profile.install_API_key('
'"<YOUR-KEY>")'.format(profile_fname))
with open(profile_fname) as fh:
api_key = fh.readlines()
return Manager(api_key=api_key) | [
"def",
"connection",
"(",
"profile_name",
"=",
"'default'",
",",
"api_key",
"=",
"None",
")",
":",
"if",
"api_key",
"is",
"None",
":",
"profile_fname",
"=",
"datapoint",
".",
"profile",
".",
"API_profile_fname",
"(",
"profile_name",
")",
"if",
"not",
"os",
... | Connect to DataPoint with the given API key profile name. | [
"Connect",
"to",
"DataPoint",
"with",
"the",
"given",
"API",
"key",
"profile",
"name",
"."
] | 1d3f596f21975f42c1484f5a9c3ff057de0b47ae | https://github.com/jacobtomlinson/datapoint-python/blob/1d3f596f21975f42c1484f5a9c3ff057de0b47ae/datapoint/__init__.py#L12-L22 | train | 24,410 |
jacobtomlinson/datapoint-python | datapoint/Timestep.py | Timestep.elements | def elements(self):
"""Return a list of the elements which are not None"""
elements = []
for el in ct:
if isinstance(el[1], datapoint.Element.Element):
elements.append(el[1])
return elements | python | def elements(self):
"""Return a list of the elements which are not None"""
elements = []
for el in ct:
if isinstance(el[1], datapoint.Element.Element):
elements.append(el[1])
return elements | [
"def",
"elements",
"(",
"self",
")",
":",
"elements",
"=",
"[",
"]",
"for",
"el",
"in",
"ct",
":",
"if",
"isinstance",
"(",
"el",
"[",
"1",
"]",
",",
"datapoint",
".",
"Element",
".",
"Element",
")",
":",
"elements",
".",
"append",
"(",
"el",
"["... | Return a list of the elements which are not None | [
"Return",
"a",
"list",
"of",
"the",
"elements",
"which",
"are",
"not",
"None"
] | 1d3f596f21975f42c1484f5a9c3ff057de0b47ae | https://github.com/jacobtomlinson/datapoint-python/blob/1d3f596f21975f42c1484f5a9c3ff057de0b47ae/datapoint/Timestep.py#L25-L34 | train | 24,411 |
jacobtomlinson/datapoint-python | datapoint/Manager.py | Manager.__retry_session | def __retry_session(self, retries=10, backoff_factor=0.3,
status_forcelist=(500, 502, 504),
session=None):
"""
Retry the connection using requests if it fails. Use this as a wrapper
to request from datapoint
"""
# requests.Session allows finer control, which is needed to use the
# retrying code
the_session = session or requests.Session()
# The Retry object manages the actual retrying
retry = Retry(total=retries, read=retries, connect=retries,
backoff_factor=backoff_factor,
status_forcelist=status_forcelist)
adapter = HTTPAdapter(max_retries=retry)
the_session.mount('http://', adapter)
the_session.mount('https://', adapter)
return the_session | python | def __retry_session(self, retries=10, backoff_factor=0.3,
status_forcelist=(500, 502, 504),
session=None):
"""
Retry the connection using requests if it fails. Use this as a wrapper
to request from datapoint
"""
# requests.Session allows finer control, which is needed to use the
# retrying code
the_session = session or requests.Session()
# The Retry object manages the actual retrying
retry = Retry(total=retries, read=retries, connect=retries,
backoff_factor=backoff_factor,
status_forcelist=status_forcelist)
adapter = HTTPAdapter(max_retries=retry)
the_session.mount('http://', adapter)
the_session.mount('https://', adapter)
return the_session | [
"def",
"__retry_session",
"(",
"self",
",",
"retries",
"=",
"10",
",",
"backoff_factor",
"=",
"0.3",
",",
"status_forcelist",
"=",
"(",
"500",
",",
"502",
",",
"504",
")",
",",
"session",
"=",
"None",
")",
":",
"# requests.Session allows finer control, which i... | Retry the connection using requests if it fails. Use this as a wrapper
to request from datapoint | [
"Retry",
"the",
"connection",
"using",
"requests",
"if",
"it",
"fails",
".",
"Use",
"this",
"as",
"a",
"wrapper",
"to",
"request",
"from",
"datapoint"
] | 1d3f596f21975f42c1484f5a9c3ff057de0b47ae | https://github.com/jacobtomlinson/datapoint-python/blob/1d3f596f21975f42c1484f5a9c3ff057de0b47ae/datapoint/Manager.py#L109-L131 | train | 24,412 |
jacobtomlinson/datapoint-python | datapoint/Manager.py | Manager.__call_api | def __call_api(self, path, params=None, api_url=FORECAST_URL):
"""
Call the datapoint api using the requests module
"""
if not params:
params = dict()
payload = {'key': self.api_key}
payload.update(params)
url = "%s/%s" % (api_url, path)
# Add a timeout to the request.
# The value of 1 second is based on attempting 100 connections to
# datapoint and taking ten times the mean connection time (rounded up).
# Could expose to users in the functions which need to call the api.
#req = requests.get(url, params=payload, timeout=1)
# The wrapper function __retry_session returns a requests.Session
# object. This has a .get() function like requests.get(), so the use
# doesn't change here.
sess = self.__retry_session()
req = sess.get(url, params=payload, timeout=1)
try:
data = req.json()
except ValueError:
raise APIException("DataPoint has not returned any data, this could be due to an incorrect API key")
self.call_response = data
if req.status_code != 200:
msg = [data[m] for m in ("message", "error_message", "status") \
if m in data][0]
raise Exception(msg)
return data | python | def __call_api(self, path, params=None, api_url=FORECAST_URL):
"""
Call the datapoint api using the requests module
"""
if not params:
params = dict()
payload = {'key': self.api_key}
payload.update(params)
url = "%s/%s" % (api_url, path)
# Add a timeout to the request.
# The value of 1 second is based on attempting 100 connections to
# datapoint and taking ten times the mean connection time (rounded up).
# Could expose to users in the functions which need to call the api.
#req = requests.get(url, params=payload, timeout=1)
# The wrapper function __retry_session returns a requests.Session
# object. This has a .get() function like requests.get(), so the use
# doesn't change here.
sess = self.__retry_session()
req = sess.get(url, params=payload, timeout=1)
try:
data = req.json()
except ValueError:
raise APIException("DataPoint has not returned any data, this could be due to an incorrect API key")
self.call_response = data
if req.status_code != 200:
msg = [data[m] for m in ("message", "error_message", "status") \
if m in data][0]
raise Exception(msg)
return data | [
"def",
"__call_api",
"(",
"self",
",",
"path",
",",
"params",
"=",
"None",
",",
"api_url",
"=",
"FORECAST_URL",
")",
":",
"if",
"not",
"params",
":",
"params",
"=",
"dict",
"(",
")",
"payload",
"=",
"{",
"'key'",
":",
"self",
".",
"api_key",
"}",
"... | Call the datapoint api using the requests module | [
"Call",
"the",
"datapoint",
"api",
"using",
"the",
"requests",
"module"
] | 1d3f596f21975f42c1484f5a9c3ff057de0b47ae | https://github.com/jacobtomlinson/datapoint-python/blob/1d3f596f21975f42c1484f5a9c3ff057de0b47ae/datapoint/Manager.py#L133-L165 | train | 24,413 |
jacobtomlinson/datapoint-python | datapoint/Manager.py | Manager._get_wx_units | def _get_wx_units(self, params, name):
"""
Give the Wx array returned from datapoint and an element
name and return the units for that element.
"""
units = ""
for param in params:
if str(name) == str(param['name']):
units = param['units']
return units | python | def _get_wx_units(self, params, name):
"""
Give the Wx array returned from datapoint and an element
name and return the units for that element.
"""
units = ""
for param in params:
if str(name) == str(param['name']):
units = param['units']
return units | [
"def",
"_get_wx_units",
"(",
"self",
",",
"params",
",",
"name",
")",
":",
"units",
"=",
"\"\"",
"for",
"param",
"in",
"params",
":",
"if",
"str",
"(",
"name",
")",
"==",
"str",
"(",
"param",
"[",
"'name'",
"]",
")",
":",
"units",
"=",
"param",
"... | Give the Wx array returned from datapoint and an element
name and return the units for that element. | [
"Give",
"the",
"Wx",
"array",
"returned",
"from",
"datapoint",
"and",
"an",
"element",
"name",
"and",
"return",
"the",
"units",
"for",
"that",
"element",
"."
] | 1d3f596f21975f42c1484f5a9c3ff057de0b47ae | https://github.com/jacobtomlinson/datapoint-python/blob/1d3f596f21975f42c1484f5a9c3ff057de0b47ae/datapoint/Manager.py#L188-L197 | train | 24,414 |
jacobtomlinson/datapoint-python | datapoint/Manager.py | Manager._visibility_to_text | def _visibility_to_text(self, distance):
"""
Convert observed visibility in metres to text used in forecast
"""
if not isinstance(distance, (int, long)):
raise ValueError("Distance must be an integer not", type(distance))
if distance < 0:
raise ValueError("Distance out of bounds, should be 0 or greater")
if 0 <= distance < 1000:
return 'VP'
elif 1000 <= distance < 4000:
return 'PO'
elif 4000 <= distance < 10000:
return 'MO'
elif 10000 <= distance < 20000:
return 'GO'
elif 20000 <= distance < 40000:
return 'VG'
else:
return 'EX' | python | def _visibility_to_text(self, distance):
"""
Convert observed visibility in metres to text used in forecast
"""
if not isinstance(distance, (int, long)):
raise ValueError("Distance must be an integer not", type(distance))
if distance < 0:
raise ValueError("Distance out of bounds, should be 0 or greater")
if 0 <= distance < 1000:
return 'VP'
elif 1000 <= distance < 4000:
return 'PO'
elif 4000 <= distance < 10000:
return 'MO'
elif 10000 <= distance < 20000:
return 'GO'
elif 20000 <= distance < 40000:
return 'VG'
else:
return 'EX' | [
"def",
"_visibility_to_text",
"(",
"self",
",",
"distance",
")",
":",
"if",
"not",
"isinstance",
"(",
"distance",
",",
"(",
"int",
",",
"long",
")",
")",
":",
"raise",
"ValueError",
"(",
"\"Distance must be an integer not\"",
",",
"type",
"(",
"distance",
")... | Convert observed visibility in metres to text used in forecast | [
"Convert",
"observed",
"visibility",
"in",
"metres",
"to",
"text",
"used",
"in",
"forecast"
] | 1d3f596f21975f42c1484f5a9c3ff057de0b47ae | https://github.com/jacobtomlinson/datapoint-python/blob/1d3f596f21975f42c1484f5a9c3ff057de0b47ae/datapoint/Manager.py#L207-L228 | train | 24,415 |
jacobtomlinson/datapoint-python | datapoint/Manager.py | Manager.get_forecast_sites | def get_forecast_sites(self):
"""
This function returns a list of Site object.
"""
time_now = time()
if (time_now - self.forecast_sites_last_update) > self.forecast_sites_update_time or self.forecast_sites_last_request is None:
data = self.__call_api("sitelist/")
sites = list()
for jsoned in data['Locations']['Location']:
site = Site()
site.name = jsoned['name']
site.id = jsoned['id']
site.latitude = jsoned['latitude']
site.longitude = jsoned['longitude']
if 'region' in jsoned:
site.region = jsoned['region']
if 'elevation' in jsoned:
site.elevation = jsoned['elevation']
if 'unitaryAuthArea' in jsoned:
site.unitaryAuthArea = jsoned['unitaryAuthArea']
if 'nationalPark' in jsoned:
site.nationalPark = jsoned['nationalPark']
site.api_key = self.api_key
sites.append(site)
self.forecast_sites_last_request = sites
# Only set self.sites_last_update once self.sites_last_request has
# been set
self.forecast_sites_last_update = time_now
else:
sites = self.forecast_sites_last_request
return sites | python | def get_forecast_sites(self):
"""
This function returns a list of Site object.
"""
time_now = time()
if (time_now - self.forecast_sites_last_update) > self.forecast_sites_update_time or self.forecast_sites_last_request is None:
data = self.__call_api("sitelist/")
sites = list()
for jsoned in data['Locations']['Location']:
site = Site()
site.name = jsoned['name']
site.id = jsoned['id']
site.latitude = jsoned['latitude']
site.longitude = jsoned['longitude']
if 'region' in jsoned:
site.region = jsoned['region']
if 'elevation' in jsoned:
site.elevation = jsoned['elevation']
if 'unitaryAuthArea' in jsoned:
site.unitaryAuthArea = jsoned['unitaryAuthArea']
if 'nationalPark' in jsoned:
site.nationalPark = jsoned['nationalPark']
site.api_key = self.api_key
sites.append(site)
self.forecast_sites_last_request = sites
# Only set self.sites_last_update once self.sites_last_request has
# been set
self.forecast_sites_last_update = time_now
else:
sites = self.forecast_sites_last_request
return sites | [
"def",
"get_forecast_sites",
"(",
"self",
")",
":",
"time_now",
"=",
"time",
"(",
")",
"if",
"(",
"time_now",
"-",
"self",
".",
"forecast_sites_last_update",
")",
">",
"self",
".",
"forecast_sites_update_time",
"or",
"self",
".",
"forecast_sites_last_request",
"... | This function returns a list of Site object. | [
"This",
"function",
"returns",
"a",
"list",
"of",
"Site",
"object",
"."
] | 1d3f596f21975f42c1484f5a9c3ff057de0b47ae | https://github.com/jacobtomlinson/datapoint-python/blob/1d3f596f21975f42c1484f5a9c3ff057de0b47ae/datapoint/Manager.py#L239-L278 | train | 24,416 |
jacobtomlinson/datapoint-python | datapoint/Manager.py | Manager.get_nearest_site | def get_nearest_site(self, latitude=None, longitude=None):
"""
Deprecated. This function returns nearest Site object to the specified
coordinates.
"""
warning_message = 'This function is deprecated. Use get_nearest_forecast_site() instead'
warn(warning_message, DeprecationWarning, stacklevel=2)
return self.get_nearest_forecast_site(latitude, longitude) | python | def get_nearest_site(self, latitude=None, longitude=None):
"""
Deprecated. This function returns nearest Site object to the specified
coordinates.
"""
warning_message = 'This function is deprecated. Use get_nearest_forecast_site() instead'
warn(warning_message, DeprecationWarning, stacklevel=2)
return self.get_nearest_forecast_site(latitude, longitude) | [
"def",
"get_nearest_site",
"(",
"self",
",",
"latitude",
"=",
"None",
",",
"longitude",
"=",
"None",
")",
":",
"warning_message",
"=",
"'This function is deprecated. Use get_nearest_forecast_site() instead'",
"warn",
"(",
"warning_message",
",",
"DeprecationWarning",
",",... | Deprecated. This function returns nearest Site object to the specified
coordinates. | [
"Deprecated",
".",
"This",
"function",
"returns",
"nearest",
"Site",
"object",
"to",
"the",
"specified",
"coordinates",
"."
] | 1d3f596f21975f42c1484f5a9c3ff057de0b47ae | https://github.com/jacobtomlinson/datapoint-python/blob/1d3f596f21975f42c1484f5a9c3ff057de0b47ae/datapoint/Manager.py#L280-L288 | train | 24,417 |
jacobtomlinson/datapoint-python | datapoint/Manager.py | Manager.get_nearest_forecast_site | def get_nearest_forecast_site(self, latitude=None, longitude=None):
"""
This function returns the nearest Site object to the specified
coordinates.
"""
if longitude is None:
print('ERROR: No latitude given.')
return False
if latitude is None:
print('ERROR: No latitude given.')
return False
nearest = False
distance = None
sites = self.get_forecast_sites()
# Sometimes there is a TypeError exception here: sites is None
# So, sometimes self.get_all_sites() has returned None.
for site in sites:
new_distance = \
self._distance_between_coords(
float(site.longitude),
float(site.latitude),
float(longitude),
float(latitude))
if ((distance == None) or (new_distance < distance)):
distance = new_distance
nearest = site
# If the nearest site is more than 30km away, raise an error
if distance > 30:
raise APIException("There is no site within 30km.")
return nearest | python | def get_nearest_forecast_site(self, latitude=None, longitude=None):
"""
This function returns the nearest Site object to the specified
coordinates.
"""
if longitude is None:
print('ERROR: No latitude given.')
return False
if latitude is None:
print('ERROR: No latitude given.')
return False
nearest = False
distance = None
sites = self.get_forecast_sites()
# Sometimes there is a TypeError exception here: sites is None
# So, sometimes self.get_all_sites() has returned None.
for site in sites:
new_distance = \
self._distance_between_coords(
float(site.longitude),
float(site.latitude),
float(longitude),
float(latitude))
if ((distance == None) or (new_distance < distance)):
distance = new_distance
nearest = site
# If the nearest site is more than 30km away, raise an error
if distance > 30:
raise APIException("There is no site within 30km.")
return nearest | [
"def",
"get_nearest_forecast_site",
"(",
"self",
",",
"latitude",
"=",
"None",
",",
"longitude",
"=",
"None",
")",
":",
"if",
"longitude",
"is",
"None",
":",
"print",
"(",
"'ERROR: No latitude given.'",
")",
"return",
"False",
"if",
"latitude",
"is",
"None",
... | This function returns the nearest Site object to the specified
coordinates. | [
"This",
"function",
"returns",
"the",
"nearest",
"Site",
"object",
"to",
"the",
"specified",
"coordinates",
"."
] | 1d3f596f21975f42c1484f5a9c3ff057de0b47ae | https://github.com/jacobtomlinson/datapoint-python/blob/1d3f596f21975f42c1484f5a9c3ff057de0b47ae/datapoint/Manager.py#L290-L325 | train | 24,418 |
jacobtomlinson/datapoint-python | datapoint/Manager.py | Manager.get_observation_sites | def get_observation_sites(self):
"""
This function returns a list of Site objects for which observations are available.
"""
if (time() - self.observation_sites_last_update) > self.observation_sites_update_time:
self.observation_sites_last_update = time()
data = self.__call_api("sitelist/", None, OBSERVATION_URL)
sites = list()
for jsoned in data['Locations']['Location']:
site = Site()
site.name = jsoned['name']
site.id = jsoned['id']
site.latitude = jsoned['latitude']
site.longitude = jsoned['longitude']
if 'region' in jsoned:
site.region = jsoned['region']
if 'elevation' in jsoned:
site.elevation = jsoned['elevation']
if 'unitaryAuthArea' in jsoned:
site.unitaryAuthArea = jsoned['unitaryAuthArea']
if 'nationalPark' in jsoned:
site.nationalPark = jsoned['nationalPark']
site.api_key = self.api_key
sites.append(site)
self.observation_sites_last_request = sites
else:
sites = observation_self.sites_last_request
return sites | python | def get_observation_sites(self):
"""
This function returns a list of Site objects for which observations are available.
"""
if (time() - self.observation_sites_last_update) > self.observation_sites_update_time:
self.observation_sites_last_update = time()
data = self.__call_api("sitelist/", None, OBSERVATION_URL)
sites = list()
for jsoned in data['Locations']['Location']:
site = Site()
site.name = jsoned['name']
site.id = jsoned['id']
site.latitude = jsoned['latitude']
site.longitude = jsoned['longitude']
if 'region' in jsoned:
site.region = jsoned['region']
if 'elevation' in jsoned:
site.elevation = jsoned['elevation']
if 'unitaryAuthArea' in jsoned:
site.unitaryAuthArea = jsoned['unitaryAuthArea']
if 'nationalPark' in jsoned:
site.nationalPark = jsoned['nationalPark']
site.api_key = self.api_key
sites.append(site)
self.observation_sites_last_request = sites
else:
sites = observation_self.sites_last_request
return sites | [
"def",
"get_observation_sites",
"(",
"self",
")",
":",
"if",
"(",
"time",
"(",
")",
"-",
"self",
".",
"observation_sites_last_update",
")",
">",
"self",
".",
"observation_sites_update_time",
":",
"self",
".",
"observation_sites_last_update",
"=",
"time",
"(",
")... | This function returns a list of Site objects for which observations are available. | [
"This",
"function",
"returns",
"a",
"list",
"of",
"Site",
"objects",
"for",
"which",
"observations",
"are",
"available",
"."
] | 1d3f596f21975f42c1484f5a9c3ff057de0b47ae | https://github.com/jacobtomlinson/datapoint-python/blob/1d3f596f21975f42c1484f5a9c3ff057de0b47ae/datapoint/Manager.py#L433-L467 | train | 24,419 |
jacobtomlinson/datapoint-python | datapoint/Manager.py | Manager.get_nearest_observation_site | def get_nearest_observation_site(self, latitude=None, longitude=None):
"""
This function returns the nearest Site to the specified
coordinates that supports observations
"""
if longitude is None:
print('ERROR: No longitude given.')
return False
if latitude is None:
print('ERROR: No latitude given.')
return False
nearest = False
distance = None
sites = self.get_observation_sites()
for site in sites:
new_distance = \
self._distance_between_coords(
float(site.longitude),
float(site.latitude),
float(longitude),
float(latitude))
if ((distance == None) or (new_distance < distance)):
distance = new_distance
nearest = site
# If the nearest site is more than 20km away, raise an error
if distance > 20:
raise APIException("There is no site within 30km.")
return nearest | python | def get_nearest_observation_site(self, latitude=None, longitude=None):
"""
This function returns the nearest Site to the specified
coordinates that supports observations
"""
if longitude is None:
print('ERROR: No longitude given.')
return False
if latitude is None:
print('ERROR: No latitude given.')
return False
nearest = False
distance = None
sites = self.get_observation_sites()
for site in sites:
new_distance = \
self._distance_between_coords(
float(site.longitude),
float(site.latitude),
float(longitude),
float(latitude))
if ((distance == None) or (new_distance < distance)):
distance = new_distance
nearest = site
# If the nearest site is more than 20km away, raise an error
if distance > 20:
raise APIException("There is no site within 30km.")
return nearest | [
"def",
"get_nearest_observation_site",
"(",
"self",
",",
"latitude",
"=",
"None",
",",
"longitude",
"=",
"None",
")",
":",
"if",
"longitude",
"is",
"None",
":",
"print",
"(",
"'ERROR: No longitude given.'",
")",
"return",
"False",
"if",
"latitude",
"is",
"None... | This function returns the nearest Site to the specified
coordinates that supports observations | [
"This",
"function",
"returns",
"the",
"nearest",
"Site",
"to",
"the",
"specified",
"coordinates",
"that",
"supports",
"observations"
] | 1d3f596f21975f42c1484f5a9c3ff057de0b47ae | https://github.com/jacobtomlinson/datapoint-python/blob/1d3f596f21975f42c1484f5a9c3ff057de0b47ae/datapoint/Manager.py#L469-L501 | train | 24,420 |
jacobtomlinson/datapoint-python | datapoint/regions/RegionManager.py | RegionManager.call_api | def call_api(self, path, **kwargs):
'''
Call datapoint api
'''
if 'key' not in kwargs:
kwargs['key'] = self.api_key
req = requests.get('{0}{1}'.format(self.base_url, path), params=kwargs)
if req.status_code != requests.codes.ok:
req.raise_for_status()
return req.json() | python | def call_api(self, path, **kwargs):
'''
Call datapoint api
'''
if 'key' not in kwargs:
kwargs['key'] = self.api_key
req = requests.get('{0}{1}'.format(self.base_url, path), params=kwargs)
if req.status_code != requests.codes.ok:
req.raise_for_status()
return req.json() | [
"def",
"call_api",
"(",
"self",
",",
"path",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"'key'",
"not",
"in",
"kwargs",
":",
"kwargs",
"[",
"'key'",
"]",
"=",
"self",
".",
"api_key",
"req",
"=",
"requests",
".",
"get",
"(",
"'{0}{1}'",
".",
"format",... | Call datapoint api | [
"Call",
"datapoint",
"api"
] | 1d3f596f21975f42c1484f5a9c3ff057de0b47ae | https://github.com/jacobtomlinson/datapoint-python/blob/1d3f596f21975f42c1484f5a9c3ff057de0b47ae/datapoint/regions/RegionManager.py#L27-L38 | train | 24,421 |
jacobtomlinson/datapoint-python | datapoint/regions/RegionManager.py | RegionManager.get_all_regions | def get_all_regions(self):
'''
Request a list of regions from Datapoint. Returns each Region
as a Site object. Regions rarely change, so we cache the response
for one hour to minimise requests to API.
'''
if (time() - self.regions_last_update) < self.regions_update_time:
return self.regions_last_request
response = self.call_api(self.all_regions_path)
regions = []
for location in response['Locations']['Location']:
region = Site()
region.id = location['@id']
region.region = location['@name']
region.name = REGION_NAMES[location['@name']]
regions.append(region)
self.regions_last_update = time()
self.regions_last_request = regions
return regions | python | def get_all_regions(self):
'''
Request a list of regions from Datapoint. Returns each Region
as a Site object. Regions rarely change, so we cache the response
for one hour to minimise requests to API.
'''
if (time() - self.regions_last_update) < self.regions_update_time:
return self.regions_last_request
response = self.call_api(self.all_regions_path)
regions = []
for location in response['Locations']['Location']:
region = Site()
region.id = location['@id']
region.region = location['@name']
region.name = REGION_NAMES[location['@name']]
regions.append(region)
self.regions_last_update = time()
self.regions_last_request = regions
return regions | [
"def",
"get_all_regions",
"(",
"self",
")",
":",
"if",
"(",
"time",
"(",
")",
"-",
"self",
".",
"regions_last_update",
")",
"<",
"self",
".",
"regions_update_time",
":",
"return",
"self",
".",
"regions_last_request",
"response",
"=",
"self",
".",
"call_api",... | Request a list of regions from Datapoint. Returns each Region
as a Site object. Regions rarely change, so we cache the response
for one hour to minimise requests to API. | [
"Request",
"a",
"list",
"of",
"regions",
"from",
"Datapoint",
".",
"Returns",
"each",
"Region",
"as",
"a",
"Site",
"object",
".",
"Regions",
"rarely",
"change",
"so",
"we",
"cache",
"the",
"response",
"for",
"one",
"hour",
"to",
"minimise",
"requests",
"to... | 1d3f596f21975f42c1484f5a9c3ff057de0b47ae | https://github.com/jacobtomlinson/datapoint-python/blob/1d3f596f21975f42c1484f5a9c3ff057de0b47ae/datapoint/regions/RegionManager.py#L40-L60 | train | 24,422 |
jacobtomlinson/datapoint-python | datapoint/Forecast.py | Forecast.now | def now(self):
"""
Function to return just the current timestep from this forecast
"""
# From the comments in issue 19: forecast.days[0] is dated for the
# previous day shortly after midnight
now = None
# Set the time now to be in the same time zone as the first timestep in
# the forecast. This shouldn't cause problems with daylight savings as
# the change is far enough after midnight.
d = datetime.datetime.now(tz=self.days[0].date.tzinfo)
# d is something like datetime.datetime(2019, 1, 19, 17, 5, 28, 337439)
# d.replace(...) is datetime.datetime(2019, 1, 19, 0, 0)
# for_total_seconds is then: datetime.timedelta(seconds=61528,
# microseconds=337439)
# In this example, this is (17*60*60) + (5*60) + 28 = 61528
# this is the number of seconds through the day
for_total_seconds = d - \
d.replace(hour=0, minute=0, second=0, microsecond=0)
# In the example time,
# for_total_seconds.total_seconds() = 61528 + 0.337439
# This is the number of seconds after midnight
# msm is then the number of minutes after midnight
msm = for_total_seconds.total_seconds() / 60
# If the date now and the date in the forecast are the same, proceed
if self.days[0].date.strftime("%Y-%m-%dZ") == d.strftime("%Y-%m-%dZ"):
# We have determined that the date in the forecast and the date now
# are the same.
#
# Now, test if timestep.name is larger than the number of minutes
# since midnight for each timestep.
# The timestep we keep is the one with the largest timestep.name
# which is less than the number of minutes since midnight
for timestep in self.days[0].timesteps:
if timestep.name > msm:
# break here stops the for loop
break
# now is assigned to the last timestep that did not break the
# loop
now = timestep
return now
# Bodge to get around problems near midnight:
# Previous method does not account for the end of the month. The test
# trying to be evaluated is that the absolute difference between the
# last timestep of the first day and the current time is less than 4
# hours. 4 hours is because the final timestep of the previous day is
# for 21:00
elif abs(self.days[0].timesteps[-1].date - d).total_seconds() < 14400:
# This is verbose to check that the returned data makes sense
timestep_to_return = self.days[0].timesteps[-1]
return timestep_to_return
else:
return False | python | def now(self):
"""
Function to return just the current timestep from this forecast
"""
# From the comments in issue 19: forecast.days[0] is dated for the
# previous day shortly after midnight
now = None
# Set the time now to be in the same time zone as the first timestep in
# the forecast. This shouldn't cause problems with daylight savings as
# the change is far enough after midnight.
d = datetime.datetime.now(tz=self.days[0].date.tzinfo)
# d is something like datetime.datetime(2019, 1, 19, 17, 5, 28, 337439)
# d.replace(...) is datetime.datetime(2019, 1, 19, 0, 0)
# for_total_seconds is then: datetime.timedelta(seconds=61528,
# microseconds=337439)
# In this example, this is (17*60*60) + (5*60) + 28 = 61528
# this is the number of seconds through the day
for_total_seconds = d - \
d.replace(hour=0, minute=0, second=0, microsecond=0)
# In the example time,
# for_total_seconds.total_seconds() = 61528 + 0.337439
# This is the number of seconds after midnight
# msm is then the number of minutes after midnight
msm = for_total_seconds.total_seconds() / 60
# If the date now and the date in the forecast are the same, proceed
if self.days[0].date.strftime("%Y-%m-%dZ") == d.strftime("%Y-%m-%dZ"):
# We have determined that the date in the forecast and the date now
# are the same.
#
# Now, test if timestep.name is larger than the number of minutes
# since midnight for each timestep.
# The timestep we keep is the one with the largest timestep.name
# which is less than the number of minutes since midnight
for timestep in self.days[0].timesteps:
if timestep.name > msm:
# break here stops the for loop
break
# now is assigned to the last timestep that did not break the
# loop
now = timestep
return now
# Bodge to get around problems near midnight:
# Previous method does not account for the end of the month. The test
# trying to be evaluated is that the absolute difference between the
# last timestep of the first day and the current time is less than 4
# hours. 4 hours is because the final timestep of the previous day is
# for 21:00
elif abs(self.days[0].timesteps[-1].date - d).total_seconds() < 14400:
# This is verbose to check that the returned data makes sense
timestep_to_return = self.days[0].timesteps[-1]
return timestep_to_return
else:
return False | [
"def",
"now",
"(",
"self",
")",
":",
"# From the comments in issue 19: forecast.days[0] is dated for the",
"# previous day shortly after midnight",
"now",
"=",
"None",
"# Set the time now to be in the same time zone as the first timestep in",
"# the forecast. This shouldn't cause problems wi... | Function to return just the current timestep from this forecast | [
"Function",
"to",
"return",
"just",
"the",
"current",
"timestep",
"from",
"this",
"forecast"
] | 1d3f596f21975f42c1484f5a9c3ff057de0b47ae | https://github.com/jacobtomlinson/datapoint-python/blob/1d3f596f21975f42c1484f5a9c3ff057de0b47ae/datapoint/Forecast.py#L22-L80 | train | 24,423 |
jacobtomlinson/datapoint-python | datapoint/Forecast.py | Forecast.future | def future(self,in_days=None,in_hours=None,in_minutes=None,in_seconds=None):
"""
Function to return a future timestep
"""
future = None
# Initialize variables to 0
dd, hh, mm, ss = [0 for i in range(4)]
if (in_days != None):
dd = dd + in_days
if (in_hours != None):
hh = hh + in_hours
if (in_minutes != None):
mm = mm + in_minutes
if (in_seconds != None):
ss = ss + in_seconds
# Set the hours, minutes and seconds from now (minus the days)
dnow = datetime.datetime.utcnow() # Now
d = dnow + \
datetime.timedelta(hours=hh, minutes=mm, seconds = ss)
# Time from midnight
for_total_seconds = d - \
d.replace(hour=0, minute=0, second=0, microsecond=0)
# Convert into minutes since midnight
try:
msm = for_total_seconds.total_seconds()/60.
except:
# For versions before 2.7
msm = self.timedelta_total_seconds(for_total_seconds)/60.
if (dd<len(self.days)):
for timestep in self.days[dd].timesteps:
if timestep.name >= msm:
future = timestep
return future
else:
print('ERROR: requested date is outside the forecast range selected,' + str(len(self.days)))
return False | python | def future(self,in_days=None,in_hours=None,in_minutes=None,in_seconds=None):
"""
Function to return a future timestep
"""
future = None
# Initialize variables to 0
dd, hh, mm, ss = [0 for i in range(4)]
if (in_days != None):
dd = dd + in_days
if (in_hours != None):
hh = hh + in_hours
if (in_minutes != None):
mm = mm + in_minutes
if (in_seconds != None):
ss = ss + in_seconds
# Set the hours, minutes and seconds from now (minus the days)
dnow = datetime.datetime.utcnow() # Now
d = dnow + \
datetime.timedelta(hours=hh, minutes=mm, seconds = ss)
# Time from midnight
for_total_seconds = d - \
d.replace(hour=0, minute=0, second=0, microsecond=0)
# Convert into minutes since midnight
try:
msm = for_total_seconds.total_seconds()/60.
except:
# For versions before 2.7
msm = self.timedelta_total_seconds(for_total_seconds)/60.
if (dd<len(self.days)):
for timestep in self.days[dd].timesteps:
if timestep.name >= msm:
future = timestep
return future
else:
print('ERROR: requested date is outside the forecast range selected,' + str(len(self.days)))
return False | [
"def",
"future",
"(",
"self",
",",
"in_days",
"=",
"None",
",",
"in_hours",
"=",
"None",
",",
"in_minutes",
"=",
"None",
",",
"in_seconds",
"=",
"None",
")",
":",
"future",
"=",
"None",
"# Initialize variables to 0",
"dd",
",",
"hh",
",",
"mm",
",",
"s... | Function to return a future timestep | [
"Function",
"to",
"return",
"a",
"future",
"timestep"
] | 1d3f596f21975f42c1484f5a9c3ff057de0b47ae | https://github.com/jacobtomlinson/datapoint-python/blob/1d3f596f21975f42c1484f5a9c3ff057de0b47ae/datapoint/Forecast.py#L82-L121 | train | 24,424 |
jacobtomlinson/datapoint-python | datapoint/profile.py | install_API_key | def install_API_key(api_key, profile_name='default'):
"""Put the given API key into the given profile name."""
fname = API_profile_fname(profile_name)
if not os.path.isdir(os.path.dirname(fname)):
os.makedirs(os.path.dirname(fname))
with open(fname, 'w') as fh:
fh.write(api_key) | python | def install_API_key(api_key, profile_name='default'):
"""Put the given API key into the given profile name."""
fname = API_profile_fname(profile_name)
if not os.path.isdir(os.path.dirname(fname)):
os.makedirs(os.path.dirname(fname))
with open(fname, 'w') as fh:
fh.write(api_key) | [
"def",
"install_API_key",
"(",
"api_key",
",",
"profile_name",
"=",
"'default'",
")",
":",
"fname",
"=",
"API_profile_fname",
"(",
"profile_name",
")",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"fname",
")... | Put the given API key into the given profile name. | [
"Put",
"the",
"given",
"API",
"key",
"into",
"the",
"given",
"profile",
"name",
"."
] | 1d3f596f21975f42c1484f5a9c3ff057de0b47ae | https://github.com/jacobtomlinson/datapoint-python/blob/1d3f596f21975f42c1484f5a9c3ff057de0b47ae/datapoint/profile.py#L12-L18 | train | 24,425 |
ltworf/typedload | typedload/typechecks.py | is_namedtuple | def is_namedtuple(type_: Type[Any]) -> bool:
'''
Generated with typing.NamedTuple
'''
return _issubclass(type_, tuple) and hasattr(type_, '_field_types') and hasattr(type_, '_fields') | python | def is_namedtuple(type_: Type[Any]) -> bool:
'''
Generated with typing.NamedTuple
'''
return _issubclass(type_, tuple) and hasattr(type_, '_field_types') and hasattr(type_, '_fields') | [
"def",
"is_namedtuple",
"(",
"type_",
":",
"Type",
"[",
"Any",
"]",
")",
"->",
"bool",
":",
"return",
"_issubclass",
"(",
"type_",
",",
"tuple",
")",
"and",
"hasattr",
"(",
"type_",
",",
"'_field_types'",
")",
"and",
"hasattr",
"(",
"type_",
",",
"'_fi... | Generated with typing.NamedTuple | [
"Generated",
"with",
"typing",
".",
"NamedTuple"
] | 7fd130612963bfcec3242698463ef863ca4af927 | https://github.com/ltworf/typedload/blob/7fd130612963bfcec3242698463ef863ca4af927/typedload/typechecks.py#L168-L172 | train | 24,426 |
ltworf/typedload | typedload/typechecks.py | uniontypes | def uniontypes(type_: Type[Any]) -> Set[Type[Any]]:
'''
Returns the types of a Union.
Raises ValueError if the argument is not a Union
and AttributeError when running on an unsupported
Python version.
'''
if not is_union(type_):
raise ValueError('Not a Union: ' + str(type_))
if hasattr(type_, '__args__'):
return set(type_.__args__)
elif hasattr(type_, '__union_params__'):
return set(type_.__union_params__)
raise AttributeError('The typing API for this Python version is unknown') | python | def uniontypes(type_: Type[Any]) -> Set[Type[Any]]:
'''
Returns the types of a Union.
Raises ValueError if the argument is not a Union
and AttributeError when running on an unsupported
Python version.
'''
if not is_union(type_):
raise ValueError('Not a Union: ' + str(type_))
if hasattr(type_, '__args__'):
return set(type_.__args__)
elif hasattr(type_, '__union_params__'):
return set(type_.__union_params__)
raise AttributeError('The typing API for this Python version is unknown') | [
"def",
"uniontypes",
"(",
"type_",
":",
"Type",
"[",
"Any",
"]",
")",
"->",
"Set",
"[",
"Type",
"[",
"Any",
"]",
"]",
":",
"if",
"not",
"is_union",
"(",
"type_",
")",
":",
"raise",
"ValueError",
"(",
"'Not a Union: '",
"+",
"str",
"(",
"type_",
")"... | Returns the types of a Union.
Raises ValueError if the argument is not a Union
and AttributeError when running on an unsupported
Python version. | [
"Returns",
"the",
"types",
"of",
"a",
"Union",
"."
] | 7fd130612963bfcec3242698463ef863ca4af927 | https://github.com/ltworf/typedload/blob/7fd130612963bfcec3242698463ef863ca4af927/typedload/typechecks.py#L200-L215 | train | 24,427 |
ltworf/typedload | typedload/datadumper.py | Dumper.index | def index(self, value: Any) -> int:
"""
Returns the index in the handlers list
that matches the given value.
If no condition matches, ValueError is raised.
"""
for i, cond in ((j[0], j[1][0]) for j in enumerate(self.handlers)):
try:
match = cond(value)
except:
if self.raiseconditionerrors:
raise
match = False
if match:
return i
raise TypedloadValueError('Unable to dump %s' % value, value=value) | python | def index(self, value: Any) -> int:
"""
Returns the index in the handlers list
that matches the given value.
If no condition matches, ValueError is raised.
"""
for i, cond in ((j[0], j[1][0]) for j in enumerate(self.handlers)):
try:
match = cond(value)
except:
if self.raiseconditionerrors:
raise
match = False
if match:
return i
raise TypedloadValueError('Unable to dump %s' % value, value=value) | [
"def",
"index",
"(",
"self",
",",
"value",
":",
"Any",
")",
"->",
"int",
":",
"for",
"i",
",",
"cond",
"in",
"(",
"(",
"j",
"[",
"0",
"]",
",",
"j",
"[",
"1",
"]",
"[",
"0",
"]",
")",
"for",
"j",
"in",
"enumerate",
"(",
"self",
".",
"hand... | Returns the index in the handlers list
that matches the given value.
If no condition matches, ValueError is raised. | [
"Returns",
"the",
"index",
"in",
"the",
"handlers",
"list",
"that",
"matches",
"the",
"given",
"value",
"."
] | 7fd130612963bfcec3242698463ef863ca4af927 | https://github.com/ltworf/typedload/blob/7fd130612963bfcec3242698463ef863ca4af927/typedload/datadumper.py#L111-L127 | train | 24,428 |
ltworf/typedload | typedload/datadumper.py | Dumper.dump | def dump(self, value: Any) -> Any:
"""
Dump the typed data structure into its
untyped equivalent.
"""
index = self.index(value)
func = self.handlers[index][1]
return func(self, value) | python | def dump(self, value: Any) -> Any:
"""
Dump the typed data structure into its
untyped equivalent.
"""
index = self.index(value)
func = self.handlers[index][1]
return func(self, value) | [
"def",
"dump",
"(",
"self",
",",
"value",
":",
"Any",
")",
"->",
"Any",
":",
"index",
"=",
"self",
".",
"index",
"(",
"value",
")",
"func",
"=",
"self",
".",
"handlers",
"[",
"index",
"]",
"[",
"1",
"]",
"return",
"func",
"(",
"self",
",",
"val... | Dump the typed data structure into its
untyped equivalent. | [
"Dump",
"the",
"typed",
"data",
"structure",
"into",
"its",
"untyped",
"equivalent",
"."
] | 7fd130612963bfcec3242698463ef863ca4af927 | https://github.com/ltworf/typedload/blob/7fd130612963bfcec3242698463ef863ca4af927/typedload/datadumper.py#L129-L136 | train | 24,429 |
ltworf/typedload | typedload/dataloader.py | _forwardrefload | def _forwardrefload(l: Loader, value: Any, type_: type) -> Any:
"""
This resolves a ForwardRef.
It just looks up the type in the dictionary of known types
and loads the value using that.
"""
if l.frefs is None:
raise TypedloadException('ForwardRef resolving is disabled for the loader', value=value, type_=type_)
tname = type_.__forward_arg__ # type: ignore
t = l.frefs.get(tname)
if t is None:
raise TypedloadValueError(
"ForwardRef '%s' unknown" % tname,
value=value,
type_=type_
)
return l.load(value, t, annotation=Annotation(AnnotationType.FORWARDREF, tname)) | python | def _forwardrefload(l: Loader, value: Any, type_: type) -> Any:
"""
This resolves a ForwardRef.
It just looks up the type in the dictionary of known types
and loads the value using that.
"""
if l.frefs is None:
raise TypedloadException('ForwardRef resolving is disabled for the loader', value=value, type_=type_)
tname = type_.__forward_arg__ # type: ignore
t = l.frefs.get(tname)
if t is None:
raise TypedloadValueError(
"ForwardRef '%s' unknown" % tname,
value=value,
type_=type_
)
return l.load(value, t, annotation=Annotation(AnnotationType.FORWARDREF, tname)) | [
"def",
"_forwardrefload",
"(",
"l",
":",
"Loader",
",",
"value",
":",
"Any",
",",
"type_",
":",
"type",
")",
"->",
"Any",
":",
"if",
"l",
".",
"frefs",
"is",
"None",
":",
"raise",
"TypedloadException",
"(",
"'ForwardRef resolving is disabled for the loader'",
... | This resolves a ForwardRef.
It just looks up the type in the dictionary of known types
and loads the value using that. | [
"This",
"resolves",
"a",
"ForwardRef",
"."
] | 7fd130612963bfcec3242698463ef863ca4af927 | https://github.com/ltworf/typedload/blob/7fd130612963bfcec3242698463ef863ca4af927/typedload/dataloader.py#L223-L240 | train | 24,430 |
ltworf/typedload | typedload/dataloader.py | _basicload | def _basicload(l: Loader, value: Any, type_: type) -> Any:
"""
This converts a value into a basic type.
In theory it does nothing, but it performs type checking
and raises if conditions fail.
It also attempts casting, if enabled.
"""
if type(value) != type_:
if l.basiccast:
try:
return type_(value)
except ValueError as e:
raise TypedloadValueError(str(e), value=value, type_=type_)
except TypeError as e:
raise TypedloadTypeError(str(e), value=value, type_=type_)
except Exception as e:
raise TypedloadException(str(e), value=value, type_=type_)
else:
raise TypedloadValueError('Not of type %s' % type_, value=value, type_=type_)
return value | python | def _basicload(l: Loader, value: Any, type_: type) -> Any:
"""
This converts a value into a basic type.
In theory it does nothing, but it performs type checking
and raises if conditions fail.
It also attempts casting, if enabled.
"""
if type(value) != type_:
if l.basiccast:
try:
return type_(value)
except ValueError as e:
raise TypedloadValueError(str(e), value=value, type_=type_)
except TypeError as e:
raise TypedloadTypeError(str(e), value=value, type_=type_)
except Exception as e:
raise TypedloadException(str(e), value=value, type_=type_)
else:
raise TypedloadValueError('Not of type %s' % type_, value=value, type_=type_)
return value | [
"def",
"_basicload",
"(",
"l",
":",
"Loader",
",",
"value",
":",
"Any",
",",
"type_",
":",
"type",
")",
"->",
"Any",
":",
"if",
"type",
"(",
"value",
")",
"!=",
"type_",
":",
"if",
"l",
".",
"basiccast",
":",
"try",
":",
"return",
"type_",
"(",
... | This converts a value into a basic type.
In theory it does nothing, but it performs type checking
and raises if conditions fail.
It also attempts casting, if enabled. | [
"This",
"converts",
"a",
"value",
"into",
"a",
"basic",
"type",
"."
] | 7fd130612963bfcec3242698463ef863ca4af927 | https://github.com/ltworf/typedload/blob/7fd130612963bfcec3242698463ef863ca4af927/typedload/dataloader.py#L243-L265 | train | 24,431 |
ltworf/typedload | typedload/dataloader.py | _unionload | def _unionload(l: Loader, value, type_) -> Any:
"""
Loads a value into a union.
Basically this iterates all the types inside the
union, until one that doesn't raise an exception
is found.
If no suitable type is found, an exception is raised.
"""
try:
args = uniontypes(type_)
except AttributeError:
raise TypedloadAttributeError('The typing API for this Python version is unknown')
# Do not convert basic types, if possible
if type(value) in args.intersection(l.basictypes):
return value
exceptions = []
# Try all types
for t in args:
try:
return l.load(value, t, annotation=Annotation(AnnotationType.UNION, t))
except Exception as e:
exceptions.append(e)
raise TypedloadValueError(
'Value could not be loaded into %s' % type_,
value=value,
type_=type_,
exceptions=exceptions
) | python | def _unionload(l: Loader, value, type_) -> Any:
"""
Loads a value into a union.
Basically this iterates all the types inside the
union, until one that doesn't raise an exception
is found.
If no suitable type is found, an exception is raised.
"""
try:
args = uniontypes(type_)
except AttributeError:
raise TypedloadAttributeError('The typing API for this Python version is unknown')
# Do not convert basic types, if possible
if type(value) in args.intersection(l.basictypes):
return value
exceptions = []
# Try all types
for t in args:
try:
return l.load(value, t, annotation=Annotation(AnnotationType.UNION, t))
except Exception as e:
exceptions.append(e)
raise TypedloadValueError(
'Value could not be loaded into %s' % type_,
value=value,
type_=type_,
exceptions=exceptions
) | [
"def",
"_unionload",
"(",
"l",
":",
"Loader",
",",
"value",
",",
"type_",
")",
"->",
"Any",
":",
"try",
":",
"args",
"=",
"uniontypes",
"(",
"type_",
")",
"except",
"AttributeError",
":",
"raise",
"TypedloadAttributeError",
"(",
"'The typing API for this Pytho... | Loads a value into a union.
Basically this iterates all the types inside the
union, until one that doesn't raise an exception
is found.
If no suitable type is found, an exception is raised. | [
"Loads",
"a",
"value",
"into",
"a",
"union",
"."
] | 7fd130612963bfcec3242698463ef863ca4af927 | https://github.com/ltworf/typedload/blob/7fd130612963bfcec3242698463ef863ca4af927/typedload/dataloader.py#L401-L433 | train | 24,432 |
ltworf/typedload | typedload/dataloader.py | _enumload | def _enumload(l: Loader, value, type_) -> Enum:
"""
This loads something into an Enum.
It tries with basic types first.
If that fails, it tries to look for type annotations inside the
Enum, and tries to use those to load the value into something
that is compatible with the Enum.
Of course if that fails too, a ValueError is raised.
"""
try:
# Try naïve conversion
return type_(value)
except:
pass
# Try with the typing hints
for _, t in get_type_hints(type_).items():
try:
return type_(l.load(value, t))
except:
pass
raise TypedloadValueError(
'Value could not be loaded into %s' % type_,
value=value,
type_=type_
) | python | def _enumload(l: Loader, value, type_) -> Enum:
"""
This loads something into an Enum.
It tries with basic types first.
If that fails, it tries to look for type annotations inside the
Enum, and tries to use those to load the value into something
that is compatible with the Enum.
Of course if that fails too, a ValueError is raised.
"""
try:
# Try naïve conversion
return type_(value)
except:
pass
# Try with the typing hints
for _, t in get_type_hints(type_).items():
try:
return type_(l.load(value, t))
except:
pass
raise TypedloadValueError(
'Value could not be loaded into %s' % type_,
value=value,
type_=type_
) | [
"def",
"_enumload",
"(",
"l",
":",
"Loader",
",",
"value",
",",
"type_",
")",
"->",
"Enum",
":",
"try",
":",
"# Try naïve conversion",
"return",
"type_",
"(",
"value",
")",
"except",
":",
"pass",
"# Try with the typing hints",
"for",
"_",
",",
"t",
"in",
... | This loads something into an Enum.
It tries with basic types first.
If that fails, it tries to look for type annotations inside the
Enum, and tries to use those to load the value into something
that is compatible with the Enum.
Of course if that fails too, a ValueError is raised. | [
"This",
"loads",
"something",
"into",
"an",
"Enum",
"."
] | 7fd130612963bfcec3242698463ef863ca4af927 | https://github.com/ltworf/typedload/blob/7fd130612963bfcec3242698463ef863ca4af927/typedload/dataloader.py#L436-L464 | train | 24,433 |
ltworf/typedload | typedload/dataloader.py | _noneload | def _noneload(l: Loader, value, type_) -> None:
"""
Loads a value that can only be None,
so it fails if it isn't
"""
if value is None:
return None
raise TypedloadValueError('Not None', value=value, type_=type_) | python | def _noneload(l: Loader, value, type_) -> None:
"""
Loads a value that can only be None,
so it fails if it isn't
"""
if value is None:
return None
raise TypedloadValueError('Not None', value=value, type_=type_) | [
"def",
"_noneload",
"(",
"l",
":",
"Loader",
",",
"value",
",",
"type_",
")",
"->",
"None",
":",
"if",
"value",
"is",
"None",
":",
"return",
"None",
"raise",
"TypedloadValueError",
"(",
"'Not None'",
",",
"value",
"=",
"value",
",",
"type_",
"=",
"type... | Loads a value that can only be None,
so it fails if it isn't | [
"Loads",
"a",
"value",
"that",
"can",
"only",
"be",
"None",
"so",
"it",
"fails",
"if",
"it",
"isn",
"t"
] | 7fd130612963bfcec3242698463ef863ca4af927 | https://github.com/ltworf/typedload/blob/7fd130612963bfcec3242698463ef863ca4af927/typedload/dataloader.py#L467-L474 | train | 24,434 |
ltworf/typedload | typedload/dataloader.py | Loader.index | def index(self, type_: Type[T]) -> int:
"""
Returns the index in the handlers list
that matches the given type.
If no condition matches, ValueError is raised.
"""
for i, cond in ((q[0], q[1][0]) for q in enumerate(self.handlers)):
try:
match = cond(type_)
except:
if self.raiseconditionerrors:
raise
match = False
if match:
return i
raise ValueError('No matching condition found') | python | def index(self, type_: Type[T]) -> int:
"""
Returns the index in the handlers list
that matches the given type.
If no condition matches, ValueError is raised.
"""
for i, cond in ((q[0], q[1][0]) for q in enumerate(self.handlers)):
try:
match = cond(type_)
except:
if self.raiseconditionerrors:
raise
match = False
if match:
return i
raise ValueError('No matching condition found') | [
"def",
"index",
"(",
"self",
",",
"type_",
":",
"Type",
"[",
"T",
"]",
")",
"->",
"int",
":",
"for",
"i",
",",
"cond",
"in",
"(",
"(",
"q",
"[",
"0",
"]",
",",
"q",
"[",
"1",
"]",
"[",
"0",
"]",
")",
"for",
"q",
"in",
"enumerate",
"(",
... | Returns the index in the handlers list
that matches the given type.
If no condition matches, ValueError is raised. | [
"Returns",
"the",
"index",
"in",
"the",
"handlers",
"list",
"that",
"matches",
"the",
"given",
"type",
"."
] | 7fd130612963bfcec3242698463ef863ca4af927 | https://github.com/ltworf/typedload/blob/7fd130612963bfcec3242698463ef863ca4af927/typedload/dataloader.py#L174-L190 | train | 24,435 |
ltworf/typedload | typedload/dataloader.py | Loader.load | def load(self, value: Any, type_: Type[T], *, annotation: Optional[Annotation] = None) -> T:
"""
Loads value into the typed data structure.
TypeError is raised if there is no known way to treat type_,
otherwise all errors raise a ValueError.
"""
try:
index = self.index(type_)
except ValueError:
raise TypedloadTypeError(
'Cannot deal with value of type %s' % type_,
value=value,
type_=type_
)
# Add type to known types, to resolve ForwardRef later on
if self.frefs is not None and hasattr(type_, '__name__'):
tname = type_.__name__
if tname not in self.frefs:
self.frefs[tname] = type_
func = self.handlers[index][1]
try:
return func(self, value, type_)
except Exception as e:
assert isinstance(e, TypedloadException)
e.trace.insert(0, TraceItem(value, type_, annotation))
raise e | python | def load(self, value: Any, type_: Type[T], *, annotation: Optional[Annotation] = None) -> T:
"""
Loads value into the typed data structure.
TypeError is raised if there is no known way to treat type_,
otherwise all errors raise a ValueError.
"""
try:
index = self.index(type_)
except ValueError:
raise TypedloadTypeError(
'Cannot deal with value of type %s' % type_,
value=value,
type_=type_
)
# Add type to known types, to resolve ForwardRef later on
if self.frefs is not None and hasattr(type_, '__name__'):
tname = type_.__name__
if tname not in self.frefs:
self.frefs[tname] = type_
func = self.handlers[index][1]
try:
return func(self, value, type_)
except Exception as e:
assert isinstance(e, TypedloadException)
e.trace.insert(0, TraceItem(value, type_, annotation))
raise e | [
"def",
"load",
"(",
"self",
",",
"value",
":",
"Any",
",",
"type_",
":",
"Type",
"[",
"T",
"]",
",",
"*",
",",
"annotation",
":",
"Optional",
"[",
"Annotation",
"]",
"=",
"None",
")",
"->",
"T",
":",
"try",
":",
"index",
"=",
"self",
".",
"inde... | Loads value into the typed data structure.
TypeError is raised if there is no known way to treat type_,
otherwise all errors raise a ValueError. | [
"Loads",
"value",
"into",
"the",
"typed",
"data",
"structure",
"."
] | 7fd130612963bfcec3242698463ef863ca4af927 | https://github.com/ltworf/typedload/blob/7fd130612963bfcec3242698463ef863ca4af927/typedload/dataloader.py#L192-L220 | train | 24,436 |
ltworf/typedload | example.py | get_data | def get_data(city: Optional[str]) -> Dict[str, Any]:
"""
Use the Yahoo weather API to get weather information
"""
req = urllib.request.Request(get_url(city))
with urllib.request.urlopen(req) as f:
response = f.read()
answer = response.decode('ascii')
data = json.loads(answer)
r = data['query']['results']['channel'] # Remove some useless nesting
return r | python | def get_data(city: Optional[str]) -> Dict[str, Any]:
"""
Use the Yahoo weather API to get weather information
"""
req = urllib.request.Request(get_url(city))
with urllib.request.urlopen(req) as f:
response = f.read()
answer = response.decode('ascii')
data = json.loads(answer)
r = data['query']['results']['channel'] # Remove some useless nesting
return r | [
"def",
"get_data",
"(",
"city",
":",
"Optional",
"[",
"str",
"]",
")",
"->",
"Dict",
"[",
"str",
",",
"Any",
"]",
":",
"req",
"=",
"urllib",
".",
"request",
".",
"Request",
"(",
"get_url",
"(",
"city",
")",
")",
"with",
"urllib",
".",
"request",
... | Use the Yahoo weather API to get weather information | [
"Use",
"the",
"Yahoo",
"weather",
"API",
"to",
"get",
"weather",
"information"
] | 7fd130612963bfcec3242698463ef863ca4af927 | https://github.com/ltworf/typedload/blob/7fd130612963bfcec3242698463ef863ca4af927/example.py#L51-L61 | train | 24,437 |
ltworf/typedload | typedload/__init__.py | load | def load(value: Any, type_: Type[T], **kwargs) -> T:
"""
Quick function call to load data into a type.
It is useful to avoid creating the Loader object,
in case only the default parameters are used.
"""
from . import dataloader
loader = dataloader.Loader(**kwargs)
return loader.load(value, type_) | python | def load(value: Any, type_: Type[T], **kwargs) -> T:
"""
Quick function call to load data into a type.
It is useful to avoid creating the Loader object,
in case only the default parameters are used.
"""
from . import dataloader
loader = dataloader.Loader(**kwargs)
return loader.load(value, type_) | [
"def",
"load",
"(",
"value",
":",
"Any",
",",
"type_",
":",
"Type",
"[",
"T",
"]",
",",
"*",
"*",
"kwargs",
")",
"->",
"T",
":",
"from",
".",
"import",
"dataloader",
"loader",
"=",
"dataloader",
".",
"Loader",
"(",
"*",
"*",
"kwargs",
")",
"retur... | Quick function call to load data into a type.
It is useful to avoid creating the Loader object,
in case only the default parameters are used. | [
"Quick",
"function",
"call",
"to",
"load",
"data",
"into",
"a",
"type",
"."
] | 7fd130612963bfcec3242698463ef863ca4af927 | https://github.com/ltworf/typedload/blob/7fd130612963bfcec3242698463ef863ca4af927/typedload/__init__.py#L145-L154 | train | 24,438 |
ltworf/typedload | typedload/__init__.py | dump | def dump(value: Any, **kwargs) -> Any:
"""
Quick function to dump a data structure into
something that is compatible with json or
other programs and languages.
It is useful to avoid creating the Dumper object,
in case only the default parameters are used.
"""
from . import datadumper
dumper = datadumper.Dumper(**kwargs)
return dumper.dump(value) | python | def dump(value: Any, **kwargs) -> Any:
"""
Quick function to dump a data structure into
something that is compatible with json or
other programs and languages.
It is useful to avoid creating the Dumper object,
in case only the default parameters are used.
"""
from . import datadumper
dumper = datadumper.Dumper(**kwargs)
return dumper.dump(value) | [
"def",
"dump",
"(",
"value",
":",
"Any",
",",
"*",
"*",
"kwargs",
")",
"->",
"Any",
":",
"from",
".",
"import",
"datadumper",
"dumper",
"=",
"datadumper",
".",
"Dumper",
"(",
"*",
"*",
"kwargs",
")",
"return",
"dumper",
".",
"dump",
"(",
"value",
"... | Quick function to dump a data structure into
something that is compatible with json or
other programs and languages.
It is useful to avoid creating the Dumper object,
in case only the default parameters are used. | [
"Quick",
"function",
"to",
"dump",
"a",
"data",
"structure",
"into",
"something",
"that",
"is",
"compatible",
"with",
"json",
"or",
"other",
"programs",
"and",
"languages",
"."
] | 7fd130612963bfcec3242698463ef863ca4af927 | https://github.com/ltworf/typedload/blob/7fd130612963bfcec3242698463ef863ca4af927/typedload/__init__.py#L157-L168 | train | 24,439 |
ltworf/typedload | typedload/__init__.py | attrload | def attrload(value: Any, type_: Type[T], **kwargs) -> T:
"""
Quick function call to load data supporting the "attr" module
in addition to the default ones.
"""
from . import dataloader
from .plugins import attrload as loadplugin
loader = dataloader.Loader(**kwargs)
loadplugin.add2loader(loader)
return loader.load(value, type_) | python | def attrload(value: Any, type_: Type[T], **kwargs) -> T:
"""
Quick function call to load data supporting the "attr" module
in addition to the default ones.
"""
from . import dataloader
from .plugins import attrload as loadplugin
loader = dataloader.Loader(**kwargs)
loadplugin.add2loader(loader)
return loader.load(value, type_) | [
"def",
"attrload",
"(",
"value",
":",
"Any",
",",
"type_",
":",
"Type",
"[",
"T",
"]",
",",
"*",
"*",
"kwargs",
")",
"->",
"T",
":",
"from",
".",
"import",
"dataloader",
"from",
".",
"plugins",
"import",
"attrload",
"as",
"loadplugin",
"loader",
"=",... | Quick function call to load data supporting the "attr" module
in addition to the default ones. | [
"Quick",
"function",
"call",
"to",
"load",
"data",
"supporting",
"the",
"attr",
"module",
"in",
"addition",
"to",
"the",
"default",
"ones",
"."
] | 7fd130612963bfcec3242698463ef863ca4af927 | https://github.com/ltworf/typedload/blob/7fd130612963bfcec3242698463ef863ca4af927/typedload/__init__.py#L171-L180 | train | 24,440 |
ltworf/typedload | typedload/__init__.py | attrdump | def attrdump(value: Any, **kwargs) -> Any:
"""
Quick function to do a dump that supports the "attr"
module.
"""
from . import datadumper
from .plugins import attrdump as dumpplugin
dumper = datadumper.Dumper(**kwargs)
dumpplugin.add2dumper(dumper)
return dumper.dump(value) | python | def attrdump(value: Any, **kwargs) -> Any:
"""
Quick function to do a dump that supports the "attr"
module.
"""
from . import datadumper
from .plugins import attrdump as dumpplugin
dumper = datadumper.Dumper(**kwargs)
dumpplugin.add2dumper(dumper)
return dumper.dump(value) | [
"def",
"attrdump",
"(",
"value",
":",
"Any",
",",
"*",
"*",
"kwargs",
")",
"->",
"Any",
":",
"from",
".",
"import",
"datadumper",
"from",
".",
"plugins",
"import",
"attrdump",
"as",
"dumpplugin",
"dumper",
"=",
"datadumper",
".",
"Dumper",
"(",
"*",
"*... | Quick function to do a dump that supports the "attr"
module. | [
"Quick",
"function",
"to",
"do",
"a",
"dump",
"that",
"supports",
"the",
"attr",
"module",
"."
] | 7fd130612963bfcec3242698463ef863ca4af927 | https://github.com/ltworf/typedload/blob/7fd130612963bfcec3242698463ef863ca4af927/typedload/__init__.py#L183-L192 | train | 24,441 |
rgalanakis/goless | goless/__init__.py | on_panic | def on_panic(etype, value, tb):
"""
Called when there is an unhandled error in a goroutine.
By default, logs and exits the process.
"""
_logging.critical(_traceback.format_exception(etype, value, tb))
_be.propagate_exc(SystemExit, 1) | python | def on_panic(etype, value, tb):
"""
Called when there is an unhandled error in a goroutine.
By default, logs and exits the process.
"""
_logging.critical(_traceback.format_exception(etype, value, tb))
_be.propagate_exc(SystemExit, 1) | [
"def",
"on_panic",
"(",
"etype",
",",
"value",
",",
"tb",
")",
":",
"_logging",
".",
"critical",
"(",
"_traceback",
".",
"format_exception",
"(",
"etype",
",",
"value",
",",
"tb",
")",
")",
"_be",
".",
"propagate_exc",
"(",
"SystemExit",
",",
"1",
")"
... | Called when there is an unhandled error in a goroutine.
By default, logs and exits the process. | [
"Called",
"when",
"there",
"is",
"an",
"unhandled",
"error",
"in",
"a",
"goroutine",
".",
"By",
"default",
"logs",
"and",
"exits",
"the",
"process",
"."
] | 286cd69482ae5a56c899a0c0d5d895772d96e83d | https://github.com/rgalanakis/goless/blob/286cd69482ae5a56c899a0c0d5d895772d96e83d/goless/__init__.py#L35-L41 | train | 24,442 |
rgalanakis/goless | write_benchresults.py | stdout_to_results | def stdout_to_results(s):
"""Turns the multi-line output of a benchmark process into
a sequence of BenchmarkResult instances."""
results = s.strip().split('\n')
return [BenchmarkResult(*r.split()) for r in results] | python | def stdout_to_results(s):
"""Turns the multi-line output of a benchmark process into
a sequence of BenchmarkResult instances."""
results = s.strip().split('\n')
return [BenchmarkResult(*r.split()) for r in results] | [
"def",
"stdout_to_results",
"(",
"s",
")",
":",
"results",
"=",
"s",
".",
"strip",
"(",
")",
".",
"split",
"(",
"'\\n'",
")",
"return",
"[",
"BenchmarkResult",
"(",
"*",
"r",
".",
"split",
"(",
")",
")",
"for",
"r",
"in",
"results",
"]"
] | Turns the multi-line output of a benchmark process into
a sequence of BenchmarkResult instances. | [
"Turns",
"the",
"multi",
"-",
"line",
"output",
"of",
"a",
"benchmark",
"process",
"into",
"a",
"sequence",
"of",
"BenchmarkResult",
"instances",
"."
] | 286cd69482ae5a56c899a0c0d5d895772d96e83d | https://github.com/rgalanakis/goless/blob/286cd69482ae5a56c899a0c0d5d895772d96e83d/write_benchresults.py#L37-L41 | train | 24,443 |
rgalanakis/goless | write_benchresults.py | benchmark_process_and_backend | def benchmark_process_and_backend(exe, backend):
"""Returns BenchmarkResults for a given executable and backend."""
env = dict(os.environ)
env['GOLESS_BACKEND'] = backend
args = [exe, '-m', 'benchmark']
return get_benchproc_results(args, env=env) | python | def benchmark_process_and_backend(exe, backend):
"""Returns BenchmarkResults for a given executable and backend."""
env = dict(os.environ)
env['GOLESS_BACKEND'] = backend
args = [exe, '-m', 'benchmark']
return get_benchproc_results(args, env=env) | [
"def",
"benchmark_process_and_backend",
"(",
"exe",
",",
"backend",
")",
":",
"env",
"=",
"dict",
"(",
"os",
".",
"environ",
")",
"env",
"[",
"'GOLESS_BACKEND'",
"]",
"=",
"backend",
"args",
"=",
"[",
"exe",
",",
"'-m'",
",",
"'benchmark'",
"]",
"return"... | Returns BenchmarkResults for a given executable and backend. | [
"Returns",
"BenchmarkResults",
"for",
"a",
"given",
"executable",
"and",
"backend",
"."
] | 286cd69482ae5a56c899a0c0d5d895772d96e83d | https://github.com/rgalanakis/goless/blob/286cd69482ae5a56c899a0c0d5d895772d96e83d/write_benchresults.py#L58-L63 | train | 24,444 |
rgalanakis/goless | write_benchresults.py | insert_seperator_results | def insert_seperator_results(results):
"""Given a sequence of BenchmarkResults,
return a new sequence where a "seperator" BenchmarkResult has been placed
between differing benchmarks to provide a visual difference."""
sepbench = BenchmarkResult(*[' ' * w for w in COLUMN_WIDTHS])
last_bm = None
for r in results:
if last_bm is None:
last_bm = r.benchmark
elif last_bm != r.benchmark:
yield sepbench
last_bm = r.benchmark
yield r | python | def insert_seperator_results(results):
"""Given a sequence of BenchmarkResults,
return a new sequence where a "seperator" BenchmarkResult has been placed
between differing benchmarks to provide a visual difference."""
sepbench = BenchmarkResult(*[' ' * w for w in COLUMN_WIDTHS])
last_bm = None
for r in results:
if last_bm is None:
last_bm = r.benchmark
elif last_bm != r.benchmark:
yield sepbench
last_bm = r.benchmark
yield r | [
"def",
"insert_seperator_results",
"(",
"results",
")",
":",
"sepbench",
"=",
"BenchmarkResult",
"(",
"*",
"[",
"' '",
"*",
"w",
"for",
"w",
"in",
"COLUMN_WIDTHS",
"]",
")",
"last_bm",
"=",
"None",
"for",
"r",
"in",
"results",
":",
"if",
"last_bm",
"is",... | Given a sequence of BenchmarkResults,
return a new sequence where a "seperator" BenchmarkResult has been placed
between differing benchmarks to provide a visual difference. | [
"Given",
"a",
"sequence",
"of",
"BenchmarkResults",
"return",
"a",
"new",
"sequence",
"where",
"a",
"seperator",
"BenchmarkResult",
"has",
"been",
"placed",
"between",
"differing",
"benchmarks",
"to",
"provide",
"a",
"visual",
"difference",
"."
] | 286cd69482ae5a56c899a0c0d5d895772d96e83d | https://github.com/rgalanakis/goless/blob/286cd69482ae5a56c899a0c0d5d895772d96e83d/write_benchresults.py#L86-L98 | train | 24,445 |
zeldamods/byml-v2 | byml/byml.py | Byml.parse | def parse(self) -> typing.Union[list, dict, None]:
"""Parse the BYML and get the root node with all children."""
root_node_offset = self._read_u32(12)
if root_node_offset == 0:
return None
node_type = self._data[root_node_offset]
if not _is_container_type(node_type):
raise ValueError("Invalid root node: expected array or dict, got type 0x%x" % node_type)
return self._parse_node(node_type, 12) | python | def parse(self) -> typing.Union[list, dict, None]:
"""Parse the BYML and get the root node with all children."""
root_node_offset = self._read_u32(12)
if root_node_offset == 0:
return None
node_type = self._data[root_node_offset]
if not _is_container_type(node_type):
raise ValueError("Invalid root node: expected array or dict, got type 0x%x" % node_type)
return self._parse_node(node_type, 12) | [
"def",
"parse",
"(",
"self",
")",
"->",
"typing",
".",
"Union",
"[",
"list",
",",
"dict",
",",
"None",
"]",
":",
"root_node_offset",
"=",
"self",
".",
"_read_u32",
"(",
"12",
")",
"if",
"root_node_offset",
"==",
"0",
":",
"return",
"None",
"node_type",... | Parse the BYML and get the root node with all children. | [
"Parse",
"the",
"BYML",
"and",
"get",
"the",
"root",
"node",
"with",
"all",
"children",
"."
] | 508c590e5036e160068c0b5968b6b8feeca3b58c | https://github.com/zeldamods/byml-v2/blob/508c590e5036e160068c0b5968b6b8feeca3b58c/byml/byml.py#L82-L91 | train | 24,446 |
InterSIS/django-rest-serializer-field-permissions | rest_framework_serializer_field_permissions/fields.py | PermissionMixin.check_permission | def check_permission(self, request):
"""
Check this field's permissions to determine whether or not it may be
shown.
"""
return all((permission.has_permission(request) for permission in self.permission_classes)) | python | def check_permission(self, request):
"""
Check this field's permissions to determine whether or not it may be
shown.
"""
return all((permission.has_permission(request) for permission in self.permission_classes)) | [
"def",
"check_permission",
"(",
"self",
",",
"request",
")",
":",
"return",
"all",
"(",
"(",
"permission",
".",
"has_permission",
"(",
"request",
")",
"for",
"permission",
"in",
"self",
".",
"permission_classes",
")",
")"
] | Check this field's permissions to determine whether or not it may be
shown. | [
"Check",
"this",
"field",
"s",
"permissions",
"to",
"determine",
"whether",
"or",
"not",
"it",
"may",
"be",
"shown",
"."
] | 6406312a1c3c7d9242246ecec3393a8bf1d25609 | https://github.com/InterSIS/django-rest-serializer-field-permissions/blob/6406312a1c3c7d9242246ecec3393a8bf1d25609/rest_framework_serializer_field_permissions/fields.py#L29-L34 | train | 24,447 |
sesh/piprot | piprot/providers/github.py | build_github_url | def build_github_url(
repo,
branch=None,
path='requirements.txt',
token=None
):
"""
Builds a URL to a file inside a Github repository.
"""
repo = re.sub(r"^http(s)?://github.com/", "", repo).strip('/')
# args come is as 'None' instead of not being provided
if not path:
path = 'requirements.txt'
if not branch:
branch = get_default_branch(repo)
url = 'https://raw.githubusercontent.com/{}/{}/{}'.format(
repo, branch, path
)
if token:
url = '{}?token={}'.format(url, token)
return url | python | def build_github_url(
repo,
branch=None,
path='requirements.txt',
token=None
):
"""
Builds a URL to a file inside a Github repository.
"""
repo = re.sub(r"^http(s)?://github.com/", "", repo).strip('/')
# args come is as 'None' instead of not being provided
if not path:
path = 'requirements.txt'
if not branch:
branch = get_default_branch(repo)
url = 'https://raw.githubusercontent.com/{}/{}/{}'.format(
repo, branch, path
)
if token:
url = '{}?token={}'.format(url, token)
return url | [
"def",
"build_github_url",
"(",
"repo",
",",
"branch",
"=",
"None",
",",
"path",
"=",
"'requirements.txt'",
",",
"token",
"=",
"None",
")",
":",
"repo",
"=",
"re",
".",
"sub",
"(",
"r\"^http(s)?://github.com/\"",
",",
"\"\"",
",",
"repo",
")",
".",
"stri... | Builds a URL to a file inside a Github repository. | [
"Builds",
"a",
"URL",
"to",
"a",
"file",
"inside",
"a",
"Github",
"repository",
"."
] | b9d61495123b26160fad647a0230d387d92b0841 | https://github.com/sesh/piprot/blob/b9d61495123b26160fad647a0230d387d92b0841/piprot/providers/github.py#L12-L38 | train | 24,448 |
sesh/piprot | piprot/providers/github.py | get_default_branch | def get_default_branch(repo):
"""returns the name of the default branch of the repo"""
url = "{}/repos/{}".format(GITHUB_API_BASE, repo)
response = requests.get(url)
if response.status_code == 200:
api_response = json.loads(response.text)
return api_response['default_branch']
else:
return 'master' | python | def get_default_branch(repo):
"""returns the name of the default branch of the repo"""
url = "{}/repos/{}".format(GITHUB_API_BASE, repo)
response = requests.get(url)
if response.status_code == 200:
api_response = json.loads(response.text)
return api_response['default_branch']
else:
return 'master' | [
"def",
"get_default_branch",
"(",
"repo",
")",
":",
"url",
"=",
"\"{}/repos/{}\"",
".",
"format",
"(",
"GITHUB_API_BASE",
",",
"repo",
")",
"response",
"=",
"requests",
".",
"get",
"(",
"url",
")",
"if",
"response",
".",
"status_code",
"==",
"200",
":",
... | returns the name of the default branch of the repo | [
"returns",
"the",
"name",
"of",
"the",
"default",
"branch",
"of",
"the",
"repo"
] | b9d61495123b26160fad647a0230d387d92b0841 | https://github.com/sesh/piprot/blob/b9d61495123b26160fad647a0230d387d92b0841/piprot/providers/github.py#L41-L49 | train | 24,449 |
sesh/piprot | piprot/providers/github.py | get_requirements_file_from_url | def get_requirements_file_from_url(url):
"""fetches the requiremets from the url"""
response = requests.get(url)
if response.status_code == 200:
return StringIO(response.text)
else:
return StringIO("") | python | def get_requirements_file_from_url(url):
"""fetches the requiremets from the url"""
response = requests.get(url)
if response.status_code == 200:
return StringIO(response.text)
else:
return StringIO("") | [
"def",
"get_requirements_file_from_url",
"(",
"url",
")",
":",
"response",
"=",
"requests",
".",
"get",
"(",
"url",
")",
"if",
"response",
".",
"status_code",
"==",
"200",
":",
"return",
"StringIO",
"(",
"response",
".",
"text",
")",
"else",
":",
"return",... | fetches the requiremets from the url | [
"fetches",
"the",
"requiremets",
"from",
"the",
"url"
] | b9d61495123b26160fad647a0230d387d92b0841 | https://github.com/sesh/piprot/blob/b9d61495123b26160fad647a0230d387d92b0841/piprot/providers/github.py#L52-L59 | train | 24,450 |
dmort27/panphon | panphon/permissive.py | PermissiveFeatureTable.longest_one_seg_prefix | def longest_one_seg_prefix(self, word):
"""Return longest IPA Unicode prefix of `word`
Args:
word (unicode): word as IPA string
Returns:
unicode: longest single-segment prefix of `word`
"""
match = self.seg_regex.match(word)
if match:
return match.group(0)
else:
return '' | python | def longest_one_seg_prefix(self, word):
"""Return longest IPA Unicode prefix of `word`
Args:
word (unicode): word as IPA string
Returns:
unicode: longest single-segment prefix of `word`
"""
match = self.seg_regex.match(word)
if match:
return match.group(0)
else:
return '' | [
"def",
"longest_one_seg_prefix",
"(",
"self",
",",
"word",
")",
":",
"match",
"=",
"self",
".",
"seg_regex",
".",
"match",
"(",
"word",
")",
"if",
"match",
":",
"return",
"match",
".",
"group",
"(",
"0",
")",
"else",
":",
"return",
"''"
] | Return longest IPA Unicode prefix of `word`
Args:
word (unicode): word as IPA string
Returns:
unicode: longest single-segment prefix of `word` | [
"Return",
"longest",
"IPA",
"Unicode",
"prefix",
"of",
"word"
] | 17eaa482e3edb211f3a8138137d76e4b9246d201 | https://github.com/dmort27/panphon/blob/17eaa482e3edb211f3a8138137d76e4b9246d201/panphon/permissive.py#L144-L157 | train | 24,451 |
dmort27/panphon | panphon/permissive.py | PermissiveFeatureTable.filter_segs | def filter_segs(self, segs):
"""Given list of strings, return only those which are valid segments.
Args:
segs (list): list of unicode values
Returns:
list: values in `segs` that are valid segments (according to the
definititions of bases and diacritics/modifiers known to the
object
"""
def whole_seg(seg):
m = self.seg_regex.match(seg)
if m and m.group(0) == seg:
return True
else:
return False
return list(filter(whole_seg, segs)) | python | def filter_segs(self, segs):
"""Given list of strings, return only those which are valid segments.
Args:
segs (list): list of unicode values
Returns:
list: values in `segs` that are valid segments (according to the
definititions of bases and diacritics/modifiers known to the
object
"""
def whole_seg(seg):
m = self.seg_regex.match(seg)
if m and m.group(0) == seg:
return True
else:
return False
return list(filter(whole_seg, segs)) | [
"def",
"filter_segs",
"(",
"self",
",",
"segs",
")",
":",
"def",
"whole_seg",
"(",
"seg",
")",
":",
"m",
"=",
"self",
".",
"seg_regex",
".",
"match",
"(",
"seg",
")",
"if",
"m",
"and",
"m",
".",
"group",
"(",
"0",
")",
"==",
"seg",
":",
"return... | Given list of strings, return only those which are valid segments.
Args:
segs (list): list of unicode values
Returns:
list: values in `segs` that are valid segments (according to the
definititions of bases and diacritics/modifiers known to the
object | [
"Given",
"list",
"of",
"strings",
"return",
"only",
"those",
"which",
"are",
"valid",
"segments",
"."
] | 17eaa482e3edb211f3a8138137d76e4b9246d201 | https://github.com/dmort27/panphon/blob/17eaa482e3edb211f3a8138137d76e4b9246d201/panphon/permissive.py#L174-L191 | train | 24,452 |
dmort27/panphon | panphon/bin/validate_ipa.py | Validator.validate_line | def validate_line(self, line):
"""Validate Unicode IPA string relative to panphon.
line -- String of IPA characters. Can contain whitespace and limited
punctuation.
"""
line0 = line
pos = 0
while line:
seg_m = self.ft.seg_regex.match(line)
wsp_m = self.ws_punc_regex.match(line)
if seg_m:
length = len(seg_m.group(0))
line = line[length:]
pos += length
elif wsp_m:
length = len(wsp_m.group(0))
line = line[length:]
pos += length
else:
msg = 'IPA not valid at position {} in "{}".'.format(pos, line0.strip())
# msg = msg.decode('utf-8')
print(msg, file=sys.stderr)
line = line[1:]
pos += 1 | python | def validate_line(self, line):
"""Validate Unicode IPA string relative to panphon.
line -- String of IPA characters. Can contain whitespace and limited
punctuation.
"""
line0 = line
pos = 0
while line:
seg_m = self.ft.seg_regex.match(line)
wsp_m = self.ws_punc_regex.match(line)
if seg_m:
length = len(seg_m.group(0))
line = line[length:]
pos += length
elif wsp_m:
length = len(wsp_m.group(0))
line = line[length:]
pos += length
else:
msg = 'IPA not valid at position {} in "{}".'.format(pos, line0.strip())
# msg = msg.decode('utf-8')
print(msg, file=sys.stderr)
line = line[1:]
pos += 1 | [
"def",
"validate_line",
"(",
"self",
",",
"line",
")",
":",
"line0",
"=",
"line",
"pos",
"=",
"0",
"while",
"line",
":",
"seg_m",
"=",
"self",
".",
"ft",
".",
"seg_regex",
".",
"match",
"(",
"line",
")",
"wsp_m",
"=",
"self",
".",
"ws_punc_regex",
... | Validate Unicode IPA string relative to panphon.
line -- String of IPA characters. Can contain whitespace and limited
punctuation. | [
"Validate",
"Unicode",
"IPA",
"string",
"relative",
"to",
"panphon",
"."
] | 17eaa482e3edb211f3a8138137d76e4b9246d201 | https://github.com/dmort27/panphon/blob/17eaa482e3edb211f3a8138137d76e4b9246d201/panphon/bin/validate_ipa.py#L26-L50 | train | 24,453 |
dmort27/panphon | panphon/_panphon.py | segment_text | def segment_text(text, seg_regex=SEG_REGEX):
"""Return an iterator of segments in the text.
Args:
text (unicode): string of IPA Unicode text
seg_regex (_regex.Pattern): compiled regex defining a segment (base +
modifiers)
Return:
generator: segments in the input text
"""
for m in seg_regex.finditer(text):
yield m.group(0) | python | def segment_text(text, seg_regex=SEG_REGEX):
"""Return an iterator of segments in the text.
Args:
text (unicode): string of IPA Unicode text
seg_regex (_regex.Pattern): compiled regex defining a segment (base +
modifiers)
Return:
generator: segments in the input text
"""
for m in seg_regex.finditer(text):
yield m.group(0) | [
"def",
"segment_text",
"(",
"text",
",",
"seg_regex",
"=",
"SEG_REGEX",
")",
":",
"for",
"m",
"in",
"seg_regex",
".",
"finditer",
"(",
"text",
")",
":",
"yield",
"m",
".",
"group",
"(",
"0",
")"
] | Return an iterator of segments in the text.
Args:
text (unicode): string of IPA Unicode text
seg_regex (_regex.Pattern): compiled regex defining a segment (base +
modifiers)
Return:
generator: segments in the input text | [
"Return",
"an",
"iterator",
"of",
"segments",
"in",
"the",
"text",
"."
] | 17eaa482e3edb211f3a8138137d76e4b9246d201 | https://github.com/dmort27/panphon/blob/17eaa482e3edb211f3a8138137d76e4b9246d201/panphon/_panphon.py#L33-L45 | train | 24,454 |
dmort27/panphon | panphon/_panphon.py | FeatureTable.fts_match | def fts_match(self, features, segment):
"""Answer question "are `ft_mask`'s features a subset of ft_seg?"
This is like `FeatureTable.match` except that it checks whether a
segment is valid and returns None if it is not.
Args:
features (set): pattern defined as set of (value, feature) tuples
segment (set): segment defined as a set of (value, feature) tuples
Returns:
bool: True iff all features in `ft_mask` are also in `ft_seg`; None
if segment is not valid
"""
features = set(features)
if self.seg_known(segment):
return features <= self.fts(segment)
else:
return None | python | def fts_match(self, features, segment):
"""Answer question "are `ft_mask`'s features a subset of ft_seg?"
This is like `FeatureTable.match` except that it checks whether a
segment is valid and returns None if it is not.
Args:
features (set): pattern defined as set of (value, feature) tuples
segment (set): segment defined as a set of (value, feature) tuples
Returns:
bool: True iff all features in `ft_mask` are also in `ft_seg`; None
if segment is not valid
"""
features = set(features)
if self.seg_known(segment):
return features <= self.fts(segment)
else:
return None | [
"def",
"fts_match",
"(",
"self",
",",
"features",
",",
"segment",
")",
":",
"features",
"=",
"set",
"(",
"features",
")",
"if",
"self",
".",
"seg_known",
"(",
"segment",
")",
":",
"return",
"features",
"<=",
"self",
".",
"fts",
"(",
"segment",
")",
"... | Answer question "are `ft_mask`'s features a subset of ft_seg?"
This is like `FeatureTable.match` except that it checks whether a
segment is valid and returns None if it is not.
Args:
features (set): pattern defined as set of (value, feature) tuples
segment (set): segment defined as a set of (value, feature) tuples
Returns:
bool: True iff all features in `ft_mask` are also in `ft_seg`; None
if segment is not valid | [
"Answer",
"question",
"are",
"ft_mask",
"s",
"features",
"a",
"subset",
"of",
"ft_seg?"
] | 17eaa482e3edb211f3a8138137d76e4b9246d201 | https://github.com/dmort27/panphon/blob/17eaa482e3edb211f3a8138137d76e4b9246d201/panphon/_panphon.py#L189-L207 | train | 24,455 |
dmort27/panphon | panphon/_panphon.py | FeatureTable.longest_one_seg_prefix | def longest_one_seg_prefix(self, word):
"""Return longest Unicode IPA prefix of a word
Args:
word (unicode): input word as Unicode IPA string
Returns:
unicode: longest single-segment prefix of `word` in database
"""
for i in range(self.longest_seg, 0, -1):
if word[:i] in self.seg_dict:
return word[:i]
return '' | python | def longest_one_seg_prefix(self, word):
"""Return longest Unicode IPA prefix of a word
Args:
word (unicode): input word as Unicode IPA string
Returns:
unicode: longest single-segment prefix of `word` in database
"""
for i in range(self.longest_seg, 0, -1):
if word[:i] in self.seg_dict:
return word[:i]
return '' | [
"def",
"longest_one_seg_prefix",
"(",
"self",
",",
"word",
")",
":",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"longest_seg",
",",
"0",
",",
"-",
"1",
")",
":",
"if",
"word",
"[",
":",
"i",
"]",
"in",
"self",
".",
"seg_dict",
":",
"return",
"w... | Return longest Unicode IPA prefix of a word
Args:
word (unicode): input word as Unicode IPA string
Returns:
unicode: longest single-segment prefix of `word` in database | [
"Return",
"longest",
"Unicode",
"IPA",
"prefix",
"of",
"a",
"word"
] | 17eaa482e3edb211f3a8138137d76e4b9246d201 | https://github.com/dmort27/panphon/blob/17eaa482e3edb211f3a8138137d76e4b9246d201/panphon/_panphon.py#L209-L221 | train | 24,456 |
dmort27/panphon | panphon/_panphon.py | FeatureTable.validate_word | def validate_word(self, word):
"""Returns True if `word` consists exhaustively of valid IPA segments
Args:
word (unicode): input word as Unicode IPA string
Returns:
bool: True if `word` can be divided exhaustively into IPA segments
that exist in the database
"""
while word:
match = self.seg_regex.match(word)
if match:
word = word[len(match.group(0)):]
else:
# print('{}\t->\t{}\t'.format(orig, word).encode('utf-8'), file=sys.stderr)
return False
return True | python | def validate_word(self, word):
"""Returns True if `word` consists exhaustively of valid IPA segments
Args:
word (unicode): input word as Unicode IPA string
Returns:
bool: True if `word` can be divided exhaustively into IPA segments
that exist in the database
"""
while word:
match = self.seg_regex.match(word)
if match:
word = word[len(match.group(0)):]
else:
# print('{}\t->\t{}\t'.format(orig, word).encode('utf-8'), file=sys.stderr)
return False
return True | [
"def",
"validate_word",
"(",
"self",
",",
"word",
")",
":",
"while",
"word",
":",
"match",
"=",
"self",
".",
"seg_regex",
".",
"match",
"(",
"word",
")",
"if",
"match",
":",
"word",
"=",
"word",
"[",
"len",
"(",
"match",
".",
"group",
"(",
"0",
"... | Returns True if `word` consists exhaustively of valid IPA segments
Args:
word (unicode): input word as Unicode IPA string
Returns:
bool: True if `word` can be divided exhaustively into IPA segments
that exist in the database | [
"Returns",
"True",
"if",
"word",
"consists",
"exhaustively",
"of",
"valid",
"IPA",
"segments"
] | 17eaa482e3edb211f3a8138137d76e4b9246d201 | https://github.com/dmort27/panphon/blob/17eaa482e3edb211f3a8138137d76e4b9246d201/panphon/_panphon.py#L223-L241 | train | 24,457 |
dmort27/panphon | panphon/_panphon.py | FeatureTable.segs | def segs(self, word):
"""Returns a list of segments from a word
Args:
word (unicode): input word as Unicode IPA string
Returns:
list: list of strings corresponding to segments found in `word`
"""
return [m.group('all') for m in self.seg_regex.finditer(word)] | python | def segs(self, word):
"""Returns a list of segments from a word
Args:
word (unicode): input word as Unicode IPA string
Returns:
list: list of strings corresponding to segments found in `word`
"""
return [m.group('all') for m in self.seg_regex.finditer(word)] | [
"def",
"segs",
"(",
"self",
",",
"word",
")",
":",
"return",
"[",
"m",
".",
"group",
"(",
"'all'",
")",
"for",
"m",
"in",
"self",
".",
"seg_regex",
".",
"finditer",
"(",
"word",
")",
"]"
] | Returns a list of segments from a word
Args:
word (unicode): input word as Unicode IPA string
Returns:
list: list of strings corresponding to segments found in `word` | [
"Returns",
"a",
"list",
"of",
"segments",
"from",
"a",
"word"
] | 17eaa482e3edb211f3a8138137d76e4b9246d201 | https://github.com/dmort27/panphon/blob/17eaa482e3edb211f3a8138137d76e4b9246d201/panphon/_panphon.py#L243-L252 | train | 24,458 |
dmort27/panphon | panphon/_panphon.py | FeatureTable.word_fts | def word_fts(self, word):
"""Return featural analysis of `word`
Args:
word (unicode): one or more IPA segments
Returns:
list: list of lists (value, feature) tuples where each inner list
corresponds to a segment in `word`
"""
return list(map(self.fts, self.segs(word))) | python | def word_fts(self, word):
"""Return featural analysis of `word`
Args:
word (unicode): one or more IPA segments
Returns:
list: list of lists (value, feature) tuples where each inner list
corresponds to a segment in `word`
"""
return list(map(self.fts, self.segs(word))) | [
"def",
"word_fts",
"(",
"self",
",",
"word",
")",
":",
"return",
"list",
"(",
"map",
"(",
"self",
".",
"fts",
",",
"self",
".",
"segs",
"(",
"word",
")",
")",
")"
] | Return featural analysis of `word`
Args:
word (unicode): one or more IPA segments
Returns:
list: list of lists (value, feature) tuples where each inner list
corresponds to a segment in `word` | [
"Return",
"featural",
"analysis",
"of",
"word"
] | 17eaa482e3edb211f3a8138137d76e4b9246d201 | https://github.com/dmort27/panphon/blob/17eaa482e3edb211f3a8138137d76e4b9246d201/panphon/_panphon.py#L254-L264 | train | 24,459 |
dmort27/panphon | panphon/_panphon.py | FeatureTable.filter_string | def filter_string(self, word):
"""Return a string like the input but containing only legal IPA segments
Args:
word (unicode): input string to be filtered
Returns:
unicode: string identical to `word` but with invalid IPA segments
absent
"""
segs = [m.group(0) for m in self.seg_regex.finditer(word)]
return ''.join(segs) | python | def filter_string(self, word):
"""Return a string like the input but containing only legal IPA segments
Args:
word (unicode): input string to be filtered
Returns:
unicode: string identical to `word` but with invalid IPA segments
absent
"""
segs = [m.group(0) for m in self.seg_regex.finditer(word)]
return ''.join(segs) | [
"def",
"filter_string",
"(",
"self",
",",
"word",
")",
":",
"segs",
"=",
"[",
"m",
".",
"group",
"(",
"0",
")",
"for",
"m",
"in",
"self",
".",
"seg_regex",
".",
"finditer",
"(",
"word",
")",
"]",
"return",
"''",
".",
"join",
"(",
"segs",
")"
] | Return a string like the input but containing only legal IPA segments
Args:
word (unicode): input string to be filtered
Returns:
unicode: string identical to `word` but with invalid IPA segments
absent | [
"Return",
"a",
"string",
"like",
"the",
"input",
"but",
"containing",
"only",
"legal",
"IPA",
"segments"
] | 17eaa482e3edb211f3a8138137d76e4b9246d201 | https://github.com/dmort27/panphon/blob/17eaa482e3edb211f3a8138137d76e4b9246d201/panphon/_panphon.py#L325-L337 | train | 24,460 |
dmort27/panphon | panphon/_panphon.py | FeatureTable.fts_intersection | def fts_intersection(self, segs):
"""Return the features shared by `segs`
Args:
segs (list): list of Unicode IPA segments
Returns:
set: set of (value, feature) tuples shared by the valid segments in
`segs`
"""
fts_vecs = [self.fts(s) for s in self.filter_segs(segs)]
return reduce(lambda a, b: a & b, fts_vecs) | python | def fts_intersection(self, segs):
"""Return the features shared by `segs`
Args:
segs (list): list of Unicode IPA segments
Returns:
set: set of (value, feature) tuples shared by the valid segments in
`segs`
"""
fts_vecs = [self.fts(s) for s in self.filter_segs(segs)]
return reduce(lambda a, b: a & b, fts_vecs) | [
"def",
"fts_intersection",
"(",
"self",
",",
"segs",
")",
":",
"fts_vecs",
"=",
"[",
"self",
".",
"fts",
"(",
"s",
")",
"for",
"s",
"in",
"self",
".",
"filter_segs",
"(",
"segs",
")",
"]",
"return",
"reduce",
"(",
"lambda",
"a",
",",
"b",
":",
"a... | Return the features shared by `segs`
Args:
segs (list): list of Unicode IPA segments
Returns:
set: set of (value, feature) tuples shared by the valid segments in
`segs` | [
"Return",
"the",
"features",
"shared",
"by",
"segs"
] | 17eaa482e3edb211f3a8138137d76e4b9246d201 | https://github.com/dmort27/panphon/blob/17eaa482e3edb211f3a8138137d76e4b9246d201/panphon/_panphon.py#L339-L350 | train | 24,461 |
dmort27/panphon | panphon/_panphon.py | FeatureTable.fts_match_any | def fts_match_any(self, fts, inv):
"""Return `True` if any segment in `inv` matches the features in `fts`
Args:
fts (list): a collection of (value, feature) tuples
inv (list): a collection of IPA segments represented as Unicode
strings
Returns:
bool: `True` if any segment in `inv` matches the features in `fts`
"""
return any([self.fts_match(fts, s) for s in inv]) | python | def fts_match_any(self, fts, inv):
"""Return `True` if any segment in `inv` matches the features in `fts`
Args:
fts (list): a collection of (value, feature) tuples
inv (list): a collection of IPA segments represented as Unicode
strings
Returns:
bool: `True` if any segment in `inv` matches the features in `fts`
"""
return any([self.fts_match(fts, s) for s in inv]) | [
"def",
"fts_match_any",
"(",
"self",
",",
"fts",
",",
"inv",
")",
":",
"return",
"any",
"(",
"[",
"self",
".",
"fts_match",
"(",
"fts",
",",
"s",
")",
"for",
"s",
"in",
"inv",
"]",
")"
] | Return `True` if any segment in `inv` matches the features in `fts`
Args:
fts (list): a collection of (value, feature) tuples
inv (list): a collection of IPA segments represented as Unicode
strings
Returns:
bool: `True` if any segment in `inv` matches the features in `fts` | [
"Return",
"True",
"if",
"any",
"segment",
"in",
"inv",
"matches",
"the",
"features",
"in",
"fts"
] | 17eaa482e3edb211f3a8138137d76e4b9246d201 | https://github.com/dmort27/panphon/blob/17eaa482e3edb211f3a8138137d76e4b9246d201/panphon/_panphon.py#L352-L363 | train | 24,462 |
dmort27/panphon | panphon/_panphon.py | FeatureTable.fts_match_all | def fts_match_all(self, fts, inv):
"""Return `True` if all segments in `inv` matches the features in fts
Args:
fts (list): a collection of (value, feature) tuples
inv (list): a collection of IPA segments represented as Unicode
strings
Returns:
bool: `True` if all segments in `inv` matches the features in `fts`
"""
return all([self.fts_match(fts, s) for s in inv]) | python | def fts_match_all(self, fts, inv):
"""Return `True` if all segments in `inv` matches the features in fts
Args:
fts (list): a collection of (value, feature) tuples
inv (list): a collection of IPA segments represented as Unicode
strings
Returns:
bool: `True` if all segments in `inv` matches the features in `fts`
"""
return all([self.fts_match(fts, s) for s in inv]) | [
"def",
"fts_match_all",
"(",
"self",
",",
"fts",
",",
"inv",
")",
":",
"return",
"all",
"(",
"[",
"self",
".",
"fts_match",
"(",
"fts",
",",
"s",
")",
"for",
"s",
"in",
"inv",
"]",
")"
] | Return `True` if all segments in `inv` matches the features in fts
Args:
fts (list): a collection of (value, feature) tuples
inv (list): a collection of IPA segments represented as Unicode
strings
Returns:
bool: `True` if all segments in `inv` matches the features in `fts` | [
"Return",
"True",
"if",
"all",
"segments",
"in",
"inv",
"matches",
"the",
"features",
"in",
"fts"
] | 17eaa482e3edb211f3a8138137d76e4b9246d201 | https://github.com/dmort27/panphon/blob/17eaa482e3edb211f3a8138137d76e4b9246d201/panphon/_panphon.py#L365-L376 | train | 24,463 |
dmort27/panphon | panphon/_panphon.py | FeatureTable.fts_contrast2 | def fts_contrast2(self, fs, ft_name, inv):
"""Return `True` if there is a segment in `inv` that contrasts in feature
`ft_name`.
Args:
fs (list): feature specifications used to filter `inv`.
ft_name (str): name of the feature where contrast must be present.
inv (list): collection of segments represented as Unicode segments.
Returns:
bool: `True` if two segments in `inv` are identical in features except
for feature `ft_name`
"""
inv_fts = [self.fts(x) for x in inv if set(fs) <= self.fts(x)]
for a in inv_fts:
for b in inv_fts:
if a != b:
diff = a ^ b
if len(diff) == 2:
if all([nm == ft_name for (_, nm) in diff]):
return True
return False | python | def fts_contrast2(self, fs, ft_name, inv):
"""Return `True` if there is a segment in `inv` that contrasts in feature
`ft_name`.
Args:
fs (list): feature specifications used to filter `inv`.
ft_name (str): name of the feature where contrast must be present.
inv (list): collection of segments represented as Unicode segments.
Returns:
bool: `True` if two segments in `inv` are identical in features except
for feature `ft_name`
"""
inv_fts = [self.fts(x) for x in inv if set(fs) <= self.fts(x)]
for a in inv_fts:
for b in inv_fts:
if a != b:
diff = a ^ b
if len(diff) == 2:
if all([nm == ft_name for (_, nm) in diff]):
return True
return False | [
"def",
"fts_contrast2",
"(",
"self",
",",
"fs",
",",
"ft_name",
",",
"inv",
")",
":",
"inv_fts",
"=",
"[",
"self",
".",
"fts",
"(",
"x",
")",
"for",
"x",
"in",
"inv",
"if",
"set",
"(",
"fs",
")",
"<=",
"self",
".",
"fts",
"(",
"x",
")",
"]",
... | Return `True` if there is a segment in `inv` that contrasts in feature
`ft_name`.
Args:
fs (list): feature specifications used to filter `inv`.
ft_name (str): name of the feature where contrast must be present.
inv (list): collection of segments represented as Unicode segments.
Returns:
bool: `True` if two segments in `inv` are identical in features except
for feature `ft_name` | [
"Return",
"True",
"if",
"there",
"is",
"a",
"segment",
"in",
"inv",
"that",
"contrasts",
"in",
"feature",
"ft_name",
"."
] | 17eaa482e3edb211f3a8138137d76e4b9246d201 | https://github.com/dmort27/panphon/blob/17eaa482e3edb211f3a8138137d76e4b9246d201/panphon/_panphon.py#L378-L399 | train | 24,464 |
dmort27/panphon | panphon/_panphon.py | FeatureTable.fts_count | def fts_count(self, fts, inv):
"""Return the count of segments in an inventory matching a given
feature mask.
Args:
fts (set): feature mask given as a set of (value, feature) tuples
inv (set): inventory of segments (as Unicode IPA strings)
Returns:
int: number of segments in `inv` that match feature mask `fts`
"""
return len(list(filter(lambda s: self.fts_match(fts, s), inv))) | python | def fts_count(self, fts, inv):
"""Return the count of segments in an inventory matching a given
feature mask.
Args:
fts (set): feature mask given as a set of (value, feature) tuples
inv (set): inventory of segments (as Unicode IPA strings)
Returns:
int: number of segments in `inv` that match feature mask `fts`
"""
return len(list(filter(lambda s: self.fts_match(fts, s), inv))) | [
"def",
"fts_count",
"(",
"self",
",",
"fts",
",",
"inv",
")",
":",
"return",
"len",
"(",
"list",
"(",
"filter",
"(",
"lambda",
"s",
":",
"self",
".",
"fts_match",
"(",
"fts",
",",
"s",
")",
",",
"inv",
")",
")",
")"
] | Return the count of segments in an inventory matching a given
feature mask.
Args:
fts (set): feature mask given as a set of (value, feature) tuples
inv (set): inventory of segments (as Unicode IPA strings)
Returns:
int: number of segments in `inv` that match feature mask `fts` | [
"Return",
"the",
"count",
"of",
"segments",
"in",
"an",
"inventory",
"matching",
"a",
"given",
"feature",
"mask",
"."
] | 17eaa482e3edb211f3a8138137d76e4b9246d201 | https://github.com/dmort27/panphon/blob/17eaa482e3edb211f3a8138137d76e4b9246d201/panphon/_panphon.py#L401-L412 | train | 24,465 |
dmort27/panphon | panphon/_panphon.py | FeatureTable.match_pattern | def match_pattern(self, pat, word):
"""Implements fixed-width pattern matching.
Matches just in case pattern is the same length (in segments) as the
word and each of the segments in the pattern is a featural subset of the
corresponding segment in the word. Matches return the corresponding list
of feature sets; failed matches return None.
Args:
pat (list): pattern consisting of a sequence of sets of (value,
feature) tuples
word (unicode): a Unicode IPA string consisting of zero or more
segments
Returns:
list: corresponding list of feature sets or, if there is no match,
None
"""
segs = self.word_fts(word)
if len(pat) != len(segs):
return None
else:
if all([set(p) <= s for (p, s) in zip(pat, segs)]):
return segs | python | def match_pattern(self, pat, word):
"""Implements fixed-width pattern matching.
Matches just in case pattern is the same length (in segments) as the
word and each of the segments in the pattern is a featural subset of the
corresponding segment in the word. Matches return the corresponding list
of feature sets; failed matches return None.
Args:
pat (list): pattern consisting of a sequence of sets of (value,
feature) tuples
word (unicode): a Unicode IPA string consisting of zero or more
segments
Returns:
list: corresponding list of feature sets or, if there is no match,
None
"""
segs = self.word_fts(word)
if len(pat) != len(segs):
return None
else:
if all([set(p) <= s for (p, s) in zip(pat, segs)]):
return segs | [
"def",
"match_pattern",
"(",
"self",
",",
"pat",
",",
"word",
")",
":",
"segs",
"=",
"self",
".",
"word_fts",
"(",
"word",
")",
"if",
"len",
"(",
"pat",
")",
"!=",
"len",
"(",
"segs",
")",
":",
"return",
"None",
"else",
":",
"if",
"all",
"(",
"... | Implements fixed-width pattern matching.
Matches just in case pattern is the same length (in segments) as the
word and each of the segments in the pattern is a featural subset of the
corresponding segment in the word. Matches return the corresponding list
of feature sets; failed matches return None.
Args:
pat (list): pattern consisting of a sequence of sets of (value,
feature) tuples
word (unicode): a Unicode IPA string consisting of zero or more
segments
Returns:
list: corresponding list of feature sets or, if there is no match,
None | [
"Implements",
"fixed",
"-",
"width",
"pattern",
"matching",
"."
] | 17eaa482e3edb211f3a8138137d76e4b9246d201 | https://github.com/dmort27/panphon/blob/17eaa482e3edb211f3a8138137d76e4b9246d201/panphon/_panphon.py#L414-L437 | train | 24,466 |
dmort27/panphon | panphon/_panphon.py | FeatureTable.compile_regex_from_str | def compile_regex_from_str(self, ft_str):
"""Given a string describing features masks for a sequence of segments,
return a regex matching the corresponding strings.
Args:
ft_str (str): feature masks, each enclosed in square brackets, in
which the features are delimited by any standard delimiter.
Returns:
Pattern: regular expression pattern equivalent to `ft_str`
"""
sequence = []
for m in re.finditer(r'\[([^]]+)\]', ft_str):
ft_mask = fts(m.group(1))
segs = self.all_segs_matching_fts(ft_mask)
sub_pat = '({})'.format('|'.join(segs))
sequence.append(sub_pat)
pattern = ''.join(sequence)
regex = re.compile(pattern)
return regex | python | def compile_regex_from_str(self, ft_str):
"""Given a string describing features masks for a sequence of segments,
return a regex matching the corresponding strings.
Args:
ft_str (str): feature masks, each enclosed in square brackets, in
which the features are delimited by any standard delimiter.
Returns:
Pattern: regular expression pattern equivalent to `ft_str`
"""
sequence = []
for m in re.finditer(r'\[([^]]+)\]', ft_str):
ft_mask = fts(m.group(1))
segs = self.all_segs_matching_fts(ft_mask)
sub_pat = '({})'.format('|'.join(segs))
sequence.append(sub_pat)
pattern = ''.join(sequence)
regex = re.compile(pattern)
return regex | [
"def",
"compile_regex_from_str",
"(",
"self",
",",
"ft_str",
")",
":",
"sequence",
"=",
"[",
"]",
"for",
"m",
"in",
"re",
".",
"finditer",
"(",
"r'\\[([^]]+)\\]'",
",",
"ft_str",
")",
":",
"ft_mask",
"=",
"fts",
"(",
"m",
".",
"group",
"(",
"1",
")",... | Given a string describing features masks for a sequence of segments,
return a regex matching the corresponding strings.
Args:
ft_str (str): feature masks, each enclosed in square brackets, in
which the features are delimited by any standard delimiter.
Returns:
Pattern: regular expression pattern equivalent to `ft_str` | [
"Given",
"a",
"string",
"describing",
"features",
"masks",
"for",
"a",
"sequence",
"of",
"segments",
"return",
"a",
"regex",
"matching",
"the",
"corresponding",
"strings",
"."
] | 17eaa482e3edb211f3a8138137d76e4b9246d201 | https://github.com/dmort27/panphon/blob/17eaa482e3edb211f3a8138137d76e4b9246d201/panphon/_panphon.py#L476-L496 | train | 24,467 |
dmort27/panphon | panphon/_panphon.py | FeatureTable.segment_to_vector | def segment_to_vector(self, seg):
"""Given a Unicode IPA segment, return a list of feature specificiations
in cannonical order.
Args:
seg (unicode): IPA consonant or vowel
Returns:
list: feature specifications ('+'/'-'/'0') in the order from
`FeatureTable.names`
"""
ft_dict = {ft: val for (val, ft) in self.fts(seg)}
return [ft_dict[name] for name in self.names] | python | def segment_to_vector(self, seg):
"""Given a Unicode IPA segment, return a list of feature specificiations
in cannonical order.
Args:
seg (unicode): IPA consonant or vowel
Returns:
list: feature specifications ('+'/'-'/'0') in the order from
`FeatureTable.names`
"""
ft_dict = {ft: val for (val, ft) in self.fts(seg)}
return [ft_dict[name] for name in self.names] | [
"def",
"segment_to_vector",
"(",
"self",
",",
"seg",
")",
":",
"ft_dict",
"=",
"{",
"ft",
":",
"val",
"for",
"(",
"val",
",",
"ft",
")",
"in",
"self",
".",
"fts",
"(",
"seg",
")",
"}",
"return",
"[",
"ft_dict",
"[",
"name",
"]",
"for",
"name",
... | Given a Unicode IPA segment, return a list of feature specificiations
in cannonical order.
Args:
seg (unicode): IPA consonant or vowel
Returns:
list: feature specifications ('+'/'-'/'0') in the order from
`FeatureTable.names` | [
"Given",
"a",
"Unicode",
"IPA",
"segment",
"return",
"a",
"list",
"of",
"feature",
"specificiations",
"in",
"cannonical",
"order",
"."
] | 17eaa482e3edb211f3a8138137d76e4b9246d201 | https://github.com/dmort27/panphon/blob/17eaa482e3edb211f3a8138137d76e4b9246d201/panphon/_panphon.py#L498-L510 | train | 24,468 |
dmort27/panphon | panphon/_panphon.py | FeatureTable.word_to_vector_list | def word_to_vector_list(self, word, numeric=False, xsampa=False):
"""Return a list of feature vectors, given a Unicode IPA word.
Args:
word (unicode): string in IPA
numeric (bool): if True, return features as numeric values instead
of strings
Returns:
list: a list of lists of '+'/'-'/'0' or 1/-1/0
"""
if xsampa:
word = self.xsampa.convert(word)
tensor = list(map(self.segment_to_vector, self.segs(word)))
if numeric:
return self.tensor_to_numeric(tensor)
else:
return tensor | python | def word_to_vector_list(self, word, numeric=False, xsampa=False):
"""Return a list of feature vectors, given a Unicode IPA word.
Args:
word (unicode): string in IPA
numeric (bool): if True, return features as numeric values instead
of strings
Returns:
list: a list of lists of '+'/'-'/'0' or 1/-1/0
"""
if xsampa:
word = self.xsampa.convert(word)
tensor = list(map(self.segment_to_vector, self.segs(word)))
if numeric:
return self.tensor_to_numeric(tensor)
else:
return tensor | [
"def",
"word_to_vector_list",
"(",
"self",
",",
"word",
",",
"numeric",
"=",
"False",
",",
"xsampa",
"=",
"False",
")",
":",
"if",
"xsampa",
":",
"word",
"=",
"self",
".",
"xsampa",
".",
"convert",
"(",
"word",
")",
"tensor",
"=",
"list",
"(",
"map",... | Return a list of feature vectors, given a Unicode IPA word.
Args:
word (unicode): string in IPA
numeric (bool): if True, return features as numeric values instead
of strings
Returns:
list: a list of lists of '+'/'-'/'0' or 1/-1/0 | [
"Return",
"a",
"list",
"of",
"feature",
"vectors",
"given",
"a",
"Unicode",
"IPA",
"word",
"."
] | 17eaa482e3edb211f3a8138137d76e4b9246d201 | https://github.com/dmort27/panphon/blob/17eaa482e3edb211f3a8138137d76e4b9246d201/panphon/_panphon.py#L516-L533 | train | 24,469 |
ivanlei/threatbutt | threatbutt/threatbutt.py | ThreatButt.clown_strike_ioc | def clown_strike_ioc(self, ioc):
"""Performs Clown Strike lookup on an IoC.
Args:
ioc - An IoC.
"""
r = requests.get('http://threatbutt.io/api', data='ioc={0}'.format(ioc))
self._output(r.text) | python | def clown_strike_ioc(self, ioc):
"""Performs Clown Strike lookup on an IoC.
Args:
ioc - An IoC.
"""
r = requests.get('http://threatbutt.io/api', data='ioc={0}'.format(ioc))
self._output(r.text) | [
"def",
"clown_strike_ioc",
"(",
"self",
",",
"ioc",
")",
":",
"r",
"=",
"requests",
".",
"get",
"(",
"'http://threatbutt.io/api'",
",",
"data",
"=",
"'ioc={0}'",
".",
"format",
"(",
"ioc",
")",
")",
"self",
".",
"_output",
"(",
"r",
".",
"text",
")"
] | Performs Clown Strike lookup on an IoC.
Args:
ioc - An IoC. | [
"Performs",
"Clown",
"Strike",
"lookup",
"on",
"an",
"IoC",
"."
] | faff507a4bebfa585d3044427111418c257c34ec | https://github.com/ivanlei/threatbutt/blob/faff507a4bebfa585d3044427111418c257c34ec/threatbutt/threatbutt.py#L20-L27 | train | 24,470 |
ivanlei/threatbutt | threatbutt/threatbutt.py | ThreatButt.bespoke_md5 | def bespoke_md5(self, md5):
"""Performs Bespoke MD5 lookup on an MD5.
Args:
md5 - A hash.
"""
r = requests.post('http://threatbutt.io/api/md5/{0}'.format(md5))
self._output(r.text) | python | def bespoke_md5(self, md5):
"""Performs Bespoke MD5 lookup on an MD5.
Args:
md5 - A hash.
"""
r = requests.post('http://threatbutt.io/api/md5/{0}'.format(md5))
self._output(r.text) | [
"def",
"bespoke_md5",
"(",
"self",
",",
"md5",
")",
":",
"r",
"=",
"requests",
".",
"post",
"(",
"'http://threatbutt.io/api/md5/{0}'",
".",
"format",
"(",
"md5",
")",
")",
"self",
".",
"_output",
"(",
"r",
".",
"text",
")"
] | Performs Bespoke MD5 lookup on an MD5.
Args:
md5 - A hash. | [
"Performs",
"Bespoke",
"MD5",
"lookup",
"on",
"an",
"MD5",
"."
] | faff507a4bebfa585d3044427111418c257c34ec | https://github.com/ivanlei/threatbutt/blob/faff507a4bebfa585d3044427111418c257c34ec/threatbutt/threatbutt.py#L29-L36 | train | 24,471 |
dmort27/panphon | panphon/sonority.py | Sonority.sonority_from_fts | def sonority_from_fts(self, seg):
"""Given a segment as features, returns the sonority on a scale of 1
to 9.
Args:
seg (list): collection of (value, feature) pairs representing
a segment (vowel or consonant)
Returns:
int: sonority of `seg` between 1 and 9
"""
def match(m):
return self.fm.match(fts(m), seg)
minusHi = BoolTree(match('-hi'), 9, 8)
minusNas = BoolTree(match('-nas'), 6, 5)
plusVoi1 = BoolTree(match('+voi'), 4, 3)
plusVoi2 = BoolTree(match('+voi'), 2, 1)
plusCont = BoolTree(match('+cont'), plusVoi1, plusVoi2)
plusSon = BoolTree(match('+son'), minusNas, plusCont)
minusCons = BoolTree(match('-cons'), 7, plusSon)
plusSyl = BoolTree(match('+syl'), minusHi, minusCons)
return plusSyl.get_value() | python | def sonority_from_fts(self, seg):
"""Given a segment as features, returns the sonority on a scale of 1
to 9.
Args:
seg (list): collection of (value, feature) pairs representing
a segment (vowel or consonant)
Returns:
int: sonority of `seg` between 1 and 9
"""
def match(m):
return self.fm.match(fts(m), seg)
minusHi = BoolTree(match('-hi'), 9, 8)
minusNas = BoolTree(match('-nas'), 6, 5)
plusVoi1 = BoolTree(match('+voi'), 4, 3)
plusVoi2 = BoolTree(match('+voi'), 2, 1)
plusCont = BoolTree(match('+cont'), plusVoi1, plusVoi2)
plusSon = BoolTree(match('+son'), minusNas, plusCont)
minusCons = BoolTree(match('-cons'), 7, plusSon)
plusSyl = BoolTree(match('+syl'), minusHi, minusCons)
return plusSyl.get_value() | [
"def",
"sonority_from_fts",
"(",
"self",
",",
"seg",
")",
":",
"def",
"match",
"(",
"m",
")",
":",
"return",
"self",
".",
"fm",
".",
"match",
"(",
"fts",
"(",
"m",
")",
",",
"seg",
")",
"minusHi",
"=",
"BoolTree",
"(",
"match",
"(",
"'-hi'",
")",... | Given a segment as features, returns the sonority on a scale of 1
to 9.
Args:
seg (list): collection of (value, feature) pairs representing
a segment (vowel or consonant)
Returns:
int: sonority of `seg` between 1 and 9 | [
"Given",
"a",
"segment",
"as",
"features",
"returns",
"the",
"sonority",
"on",
"a",
"scale",
"of",
"1",
"to",
"9",
"."
] | 17eaa482e3edb211f3a8138137d76e4b9246d201 | https://github.com/dmort27/panphon/blob/17eaa482e3edb211f3a8138137d76e4b9246d201/panphon/sonority.py#L50-L73 | train | 24,472 |
RRZE-HPC/pycachesim | cachesim/cache.py | CacheSimulator.from_dict | def from_dict(cls, d):
"""Create cache hierarchy from dictionary."""
main_memory = MainMemory()
caches = {}
referred_caches = set()
# First pass, create all named caches and collect references
for name, conf in d.items():
caches[name] = Cache(name=name,
**{k: v for k, v in conf.items()
if k not in ['store_to', 'load_from', 'victims_to']})
if 'store_to' in conf:
referred_caches.add(conf['store_to'])
if 'load_from' in conf:
referred_caches.add(conf['load_from'])
if 'victims_to' in conf:
referred_caches.add(conf['victims_to'])
# Second pass, connect caches
for name, conf in d.items():
if 'store_to' in conf and conf['store_to'] is not None:
caches[name].set_store_to(caches[conf['store_to']])
if 'load_from' in conf and conf['load_from'] is not None:
caches[name].set_load_from(caches[conf['load_from']])
if 'victims_to' in conf and conf['victims_to'] is not None:
caches[name].set_victims_to(caches[conf['victims_to']])
# Find first level (not target of any load_from or store_to)
first_level = set(d.keys()) - referred_caches
assert len(first_level) == 1, "Unable to find first cache level."
first_level = caches[list(first_level)[0]]
# Find last level caches (has no load_from or store_to target)
last_level_load = c = first_level
while c is not None:
last_level_load = c
c = c.load_from
assert last_level_load is not None, "Unable to find last cache level."
last_level_store = c = first_level
while c is not None:
last_level_store = c
c = c.store_to
assert last_level_store is not None, "Unable to find last cache level."
# Set main memory connections
main_memory.load_to(last_level_load)
main_memory.store_from(last_level_store)
return cls(first_level, main_memory), caches, main_memory | python | def from_dict(cls, d):
"""Create cache hierarchy from dictionary."""
main_memory = MainMemory()
caches = {}
referred_caches = set()
# First pass, create all named caches and collect references
for name, conf in d.items():
caches[name] = Cache(name=name,
**{k: v for k, v in conf.items()
if k not in ['store_to', 'load_from', 'victims_to']})
if 'store_to' in conf:
referred_caches.add(conf['store_to'])
if 'load_from' in conf:
referred_caches.add(conf['load_from'])
if 'victims_to' in conf:
referred_caches.add(conf['victims_to'])
# Second pass, connect caches
for name, conf in d.items():
if 'store_to' in conf and conf['store_to'] is not None:
caches[name].set_store_to(caches[conf['store_to']])
if 'load_from' in conf and conf['load_from'] is not None:
caches[name].set_load_from(caches[conf['load_from']])
if 'victims_to' in conf and conf['victims_to'] is not None:
caches[name].set_victims_to(caches[conf['victims_to']])
# Find first level (not target of any load_from or store_to)
first_level = set(d.keys()) - referred_caches
assert len(first_level) == 1, "Unable to find first cache level."
first_level = caches[list(first_level)[0]]
# Find last level caches (has no load_from or store_to target)
last_level_load = c = first_level
while c is not None:
last_level_load = c
c = c.load_from
assert last_level_load is not None, "Unable to find last cache level."
last_level_store = c = first_level
while c is not None:
last_level_store = c
c = c.store_to
assert last_level_store is not None, "Unable to find last cache level."
# Set main memory connections
main_memory.load_to(last_level_load)
main_memory.store_from(last_level_store)
return cls(first_level, main_memory), caches, main_memory | [
"def",
"from_dict",
"(",
"cls",
",",
"d",
")",
":",
"main_memory",
"=",
"MainMemory",
"(",
")",
"caches",
"=",
"{",
"}",
"referred_caches",
"=",
"set",
"(",
")",
"# First pass, create all named caches and collect references",
"for",
"name",
",",
"conf",
"in",
... | Create cache hierarchy from dictionary. | [
"Create",
"cache",
"hierarchy",
"from",
"dictionary",
"."
] | 6dd084d29cf91ec19b016e0db9ccdfc8d1f63c5b | https://github.com/RRZE-HPC/pycachesim/blob/6dd084d29cf91ec19b016e0db9ccdfc8d1f63c5b/cachesim/cache.py#L49-L98 | train | 24,473 |
RRZE-HPC/pycachesim | cachesim/cache.py | CacheSimulator.load | def load(self, addr, length=1):
"""
Load one or more addresses.
:param addr: byte address of load location
:param length: All address from addr until addr+length (exclusive) are
loaded (default: 1)
"""
if addr is None:
return
elif not isinstance(addr, Iterable):
self.first_level.load(addr, length=length)
else:
self.first_level.iterload(addr, length=length) | python | def load(self, addr, length=1):
"""
Load one or more addresses.
:param addr: byte address of load location
:param length: All address from addr until addr+length (exclusive) are
loaded (default: 1)
"""
if addr is None:
return
elif not isinstance(addr, Iterable):
self.first_level.load(addr, length=length)
else:
self.first_level.iterload(addr, length=length) | [
"def",
"load",
"(",
"self",
",",
"addr",
",",
"length",
"=",
"1",
")",
":",
"if",
"addr",
"is",
"None",
":",
"return",
"elif",
"not",
"isinstance",
"(",
"addr",
",",
"Iterable",
")",
":",
"self",
".",
"first_level",
".",
"load",
"(",
"addr",
",",
... | Load one or more addresses.
:param addr: byte address of load location
:param length: All address from addr until addr+length (exclusive) are
loaded (default: 1) | [
"Load",
"one",
"or",
"more",
"addresses",
"."
] | 6dd084d29cf91ec19b016e0db9ccdfc8d1f63c5b | https://github.com/RRZE-HPC/pycachesim/blob/6dd084d29cf91ec19b016e0db9ccdfc8d1f63c5b/cachesim/cache.py#L116-L129 | train | 24,474 |
RRZE-HPC/pycachesim | cachesim/cache.py | CacheSimulator.store | def store(self, addr, length=1, non_temporal=False):
"""
Store one or more adresses.
:param addr: byte address of store location
:param length: All address from addr until addr+length (exclusive) are
stored (default: 1)
:param non_temporal: if True, no write-allocate will be issued, but cacheline will be zeroed
"""
if non_temporal:
raise ValueError("non_temporal stores are not yet supported")
if addr is None:
return
elif not isinstance(addr, Iterable):
self.first_level.store(addr, length=length)
else:
self.first_level.iterstore(addr, length=length) | python | def store(self, addr, length=1, non_temporal=False):
"""
Store one or more adresses.
:param addr: byte address of store location
:param length: All address from addr until addr+length (exclusive) are
stored (default: 1)
:param non_temporal: if True, no write-allocate will be issued, but cacheline will be zeroed
"""
if non_temporal:
raise ValueError("non_temporal stores are not yet supported")
if addr is None:
return
elif not isinstance(addr, Iterable):
self.first_level.store(addr, length=length)
else:
self.first_level.iterstore(addr, length=length) | [
"def",
"store",
"(",
"self",
",",
"addr",
",",
"length",
"=",
"1",
",",
"non_temporal",
"=",
"False",
")",
":",
"if",
"non_temporal",
":",
"raise",
"ValueError",
"(",
"\"non_temporal stores are not yet supported\"",
")",
"if",
"addr",
"is",
"None",
":",
"ret... | Store one or more adresses.
:param addr: byte address of store location
:param length: All address from addr until addr+length (exclusive) are
stored (default: 1)
:param non_temporal: if True, no write-allocate will be issued, but cacheline will be zeroed | [
"Store",
"one",
"or",
"more",
"adresses",
"."
] | 6dd084d29cf91ec19b016e0db9ccdfc8d1f63c5b | https://github.com/RRZE-HPC/pycachesim/blob/6dd084d29cf91ec19b016e0db9ccdfc8d1f63c5b/cachesim/cache.py#L131-L148 | train | 24,475 |
RRZE-HPC/pycachesim | cachesim/cache.py | CacheSimulator.loadstore | def loadstore(self, addrs, length=1):
"""
Load and store address in order given.
:param addrs: iteratable of address tuples: [(loads, stores), ...]
:param length: will load and store all bytes between addr and
addr+length (for each address)
"""
if not isinstance(addrs, Iterable):
raise ValueError("addr must be iteratable")
self.first_level.loadstore(addrs, length=length) | python | def loadstore(self, addrs, length=1):
"""
Load and store address in order given.
:param addrs: iteratable of address tuples: [(loads, stores), ...]
:param length: will load and store all bytes between addr and
addr+length (for each address)
"""
if not isinstance(addrs, Iterable):
raise ValueError("addr must be iteratable")
self.first_level.loadstore(addrs, length=length) | [
"def",
"loadstore",
"(",
"self",
",",
"addrs",
",",
"length",
"=",
"1",
")",
":",
"if",
"not",
"isinstance",
"(",
"addrs",
",",
"Iterable",
")",
":",
"raise",
"ValueError",
"(",
"\"addr must be iteratable\"",
")",
"self",
".",
"first_level",
".",
"loadstor... | Load and store address in order given.
:param addrs: iteratable of address tuples: [(loads, stores), ...]
:param length: will load and store all bytes between addr and
addr+length (for each address) | [
"Load",
"and",
"store",
"address",
"in",
"order",
"given",
"."
] | 6dd084d29cf91ec19b016e0db9ccdfc8d1f63c5b | https://github.com/RRZE-HPC/pycachesim/blob/6dd084d29cf91ec19b016e0db9ccdfc8d1f63c5b/cachesim/cache.py#L150-L161 | train | 24,476 |
RRZE-HPC/pycachesim | cachesim/cache.py | CacheSimulator.print_stats | def print_stats(self, header=True, file=sys.stdout):
"""Pretty print stats table."""
if header:
print("CACHE {:*^18} {:*^18} {:*^18} {:*^18} {:*^18}".format(
"HIT", "MISS", "LOAD", "STORE", "EVICT"), file=file)
for s in self.stats():
print("{name:>5} {HIT_count:>6} ({HIT_byte:>8}B) {MISS_count:>6} ({MISS_byte:>8}B) "
"{LOAD_count:>6} ({LOAD_byte:>8}B) {STORE_count:>6} "
"({STORE_byte:>8}B) {EVICT_count:>6} ({EVICT_byte:>8}B)".format(
HIT_bytes=2342, **s),
file=file) | python | def print_stats(self, header=True, file=sys.stdout):
"""Pretty print stats table."""
if header:
print("CACHE {:*^18} {:*^18} {:*^18} {:*^18} {:*^18}".format(
"HIT", "MISS", "LOAD", "STORE", "EVICT"), file=file)
for s in self.stats():
print("{name:>5} {HIT_count:>6} ({HIT_byte:>8}B) {MISS_count:>6} ({MISS_byte:>8}B) "
"{LOAD_count:>6} ({LOAD_byte:>8}B) {STORE_count:>6} "
"({STORE_byte:>8}B) {EVICT_count:>6} ({EVICT_byte:>8}B)".format(
HIT_bytes=2342, **s),
file=file) | [
"def",
"print_stats",
"(",
"self",
",",
"header",
"=",
"True",
",",
"file",
"=",
"sys",
".",
"stdout",
")",
":",
"if",
"header",
":",
"print",
"(",
"\"CACHE {:*^18} {:*^18} {:*^18} {:*^18} {:*^18}\"",
".",
"format",
"(",
"\"HIT\"",
",",
"\"MISS\"",
",",
"\"L... | Pretty print stats table. | [
"Pretty",
"print",
"stats",
"table",
"."
] | 6dd084d29cf91ec19b016e0db9ccdfc8d1f63c5b | https://github.com/RRZE-HPC/pycachesim/blob/6dd084d29cf91ec19b016e0db9ccdfc8d1f63c5b/cachesim/cache.py#L168-L178 | train | 24,477 |
RRZE-HPC/pycachesim | cachesim/cache.py | CacheSimulator.levels | def levels(self, with_mem=True):
"""Return cache levels, optionally including main memory."""
p = self.first_level
while p is not None:
yield p
# FIXME bad hack to include victim caches, need a more general solution, probably
# involving recursive tree walking
if p.victims_to is not None and p.victims_to != p.load_from:
yield p.victims_to
if p.store_to is not None and p.store_to != p.load_from and p.store_to != p.victims_to:
yield p.store_to
p = p.load_from
if with_mem:
yield self.main_memory | python | def levels(self, with_mem=True):
"""Return cache levels, optionally including main memory."""
p = self.first_level
while p is not None:
yield p
# FIXME bad hack to include victim caches, need a more general solution, probably
# involving recursive tree walking
if p.victims_to is not None and p.victims_to != p.load_from:
yield p.victims_to
if p.store_to is not None and p.store_to != p.load_from and p.store_to != p.victims_to:
yield p.store_to
p = p.load_from
if with_mem:
yield self.main_memory | [
"def",
"levels",
"(",
"self",
",",
"with_mem",
"=",
"True",
")",
":",
"p",
"=",
"self",
".",
"first_level",
"while",
"p",
"is",
"not",
"None",
":",
"yield",
"p",
"# FIXME bad hack to include victim caches, need a more general solution, probably",
"# involving recursiv... | Return cache levels, optionally including main memory. | [
"Return",
"cache",
"levels",
"optionally",
"including",
"main",
"memory",
"."
] | 6dd084d29cf91ec19b016e0db9ccdfc8d1f63c5b | https://github.com/RRZE-HPC/pycachesim/blob/6dd084d29cf91ec19b016e0db9ccdfc8d1f63c5b/cachesim/cache.py#L180-L194 | train | 24,478 |
RRZE-HPC/pycachesim | cachesim/cache.py | CacheSimulator.count_invalid_entries | def count_invalid_entries(self):
"""Sum of all invalid entry counts from cache levels."""
return sum([c.count_invalid_entries() for c in self.levels(with_mem=False)]) | python | def count_invalid_entries(self):
"""Sum of all invalid entry counts from cache levels."""
return sum([c.count_invalid_entries() for c in self.levels(with_mem=False)]) | [
"def",
"count_invalid_entries",
"(",
"self",
")",
":",
"return",
"sum",
"(",
"[",
"c",
".",
"count_invalid_entries",
"(",
")",
"for",
"c",
"in",
"self",
".",
"levels",
"(",
"with_mem",
"=",
"False",
")",
"]",
")"
] | Sum of all invalid entry counts from cache levels. | [
"Sum",
"of",
"all",
"invalid",
"entry",
"counts",
"from",
"cache",
"levels",
"."
] | 6dd084d29cf91ec19b016e0db9ccdfc8d1f63c5b | https://github.com/RRZE-HPC/pycachesim/blob/6dd084d29cf91ec19b016e0db9ccdfc8d1f63c5b/cachesim/cache.py#L196-L198 | train | 24,479 |
RRZE-HPC/pycachesim | cachesim/cache.py | Cache.set_load_from | def set_load_from(self, load_from):
"""Update load_from in Cache and backend."""
assert load_from is None or isinstance(load_from, Cache), \
"load_from needs to be None or a Cache object."
assert load_from is None or load_from.cl_size <= self.cl_size, \
"cl_size may only increase towards main memory."
self.load_from = load_from
self.backend.load_from = load_from.backend | python | def set_load_from(self, load_from):
"""Update load_from in Cache and backend."""
assert load_from is None or isinstance(load_from, Cache), \
"load_from needs to be None or a Cache object."
assert load_from is None or load_from.cl_size <= self.cl_size, \
"cl_size may only increase towards main memory."
self.load_from = load_from
self.backend.load_from = load_from.backend | [
"def",
"set_load_from",
"(",
"self",
",",
"load_from",
")",
":",
"assert",
"load_from",
"is",
"None",
"or",
"isinstance",
"(",
"load_from",
",",
"Cache",
")",
",",
"\"load_from needs to be None or a Cache object.\"",
"assert",
"load_from",
"is",
"None",
"or",
"loa... | Update load_from in Cache and backend. | [
"Update",
"load_from",
"in",
"Cache",
"and",
"backend",
"."
] | 6dd084d29cf91ec19b016e0db9ccdfc8d1f63c5b | https://github.com/RRZE-HPC/pycachesim/blob/6dd084d29cf91ec19b016e0db9ccdfc8d1f63c5b/cachesim/cache.py#L338-L345 | train | 24,480 |
RRZE-HPC/pycachesim | cachesim/cache.py | Cache.set_store_to | def set_store_to(self, store_to):
"""Update store_to in Cache and backend."""
assert store_to is None or isinstance(store_to, Cache), \
"store_to needs to be None or a Cache object."
assert store_to is None or store_to.cl_size <= self.cl_size, \
"cl_size may only increase towards main memory."
self.store_to = store_to
self.backend.store_to = store_to.backend | python | def set_store_to(self, store_to):
"""Update store_to in Cache and backend."""
assert store_to is None or isinstance(store_to, Cache), \
"store_to needs to be None or a Cache object."
assert store_to is None or store_to.cl_size <= self.cl_size, \
"cl_size may only increase towards main memory."
self.store_to = store_to
self.backend.store_to = store_to.backend | [
"def",
"set_store_to",
"(",
"self",
",",
"store_to",
")",
":",
"assert",
"store_to",
"is",
"None",
"or",
"isinstance",
"(",
"store_to",
",",
"Cache",
")",
",",
"\"store_to needs to be None or a Cache object.\"",
"assert",
"store_to",
"is",
"None",
"or",
"store_to"... | Update store_to in Cache and backend. | [
"Update",
"store_to",
"in",
"Cache",
"and",
"backend",
"."
] | 6dd084d29cf91ec19b016e0db9ccdfc8d1f63c5b | https://github.com/RRZE-HPC/pycachesim/blob/6dd084d29cf91ec19b016e0db9ccdfc8d1f63c5b/cachesim/cache.py#L347-L354 | train | 24,481 |
RRZE-HPC/pycachesim | cachesim/cache.py | Cache.set_victims_to | def set_victims_to(self, victims_to):
"""Update victims_to in Cache and backend."""
assert victims_to is None or isinstance(victims_to, Cache), \
"store_to needs to be None or a Cache object."
assert victims_to is None or victims_to.cl_size == self.cl_size, \
"cl_size may only increase towards main memory."
self.victims_to = victims_to
self.backend.victims_to = victims_to.backend | python | def set_victims_to(self, victims_to):
"""Update victims_to in Cache and backend."""
assert victims_to is None or isinstance(victims_to, Cache), \
"store_to needs to be None or a Cache object."
assert victims_to is None or victims_to.cl_size == self.cl_size, \
"cl_size may only increase towards main memory."
self.victims_to = victims_to
self.backend.victims_to = victims_to.backend | [
"def",
"set_victims_to",
"(",
"self",
",",
"victims_to",
")",
":",
"assert",
"victims_to",
"is",
"None",
"or",
"isinstance",
"(",
"victims_to",
",",
"Cache",
")",
",",
"\"store_to needs to be None or a Cache object.\"",
"assert",
"victims_to",
"is",
"None",
"or",
... | Update victims_to in Cache and backend. | [
"Update",
"victims_to",
"in",
"Cache",
"and",
"backend",
"."
] | 6dd084d29cf91ec19b016e0db9ccdfc8d1f63c5b | https://github.com/RRZE-HPC/pycachesim/blob/6dd084d29cf91ec19b016e0db9ccdfc8d1f63c5b/cachesim/cache.py#L356-L363 | train | 24,482 |
RRZE-HPC/pycachesim | cachesim/cache.py | MainMemory.load_to | def load_to(self, last_level_load):
"""Set level where to load from."""
assert isinstance(last_level_load, Cache), \
"last_level needs to be a Cache object."
assert last_level_load.load_from is None, \
"last_level_load must be a last level cache (.load_from is None)."
self.last_level_load = last_level_load | python | def load_to(self, last_level_load):
"""Set level where to load from."""
assert isinstance(last_level_load, Cache), \
"last_level needs to be a Cache object."
assert last_level_load.load_from is None, \
"last_level_load must be a last level cache (.load_from is None)."
self.last_level_load = last_level_load | [
"def",
"load_to",
"(",
"self",
",",
"last_level_load",
")",
":",
"assert",
"isinstance",
"(",
"last_level_load",
",",
"Cache",
")",
",",
"\"last_level needs to be a Cache object.\"",
"assert",
"last_level_load",
".",
"load_from",
"is",
"None",
",",
"\"last_level_load ... | Set level where to load from. | [
"Set",
"level",
"where",
"to",
"load",
"from",
"."
] | 6dd084d29cf91ec19b016e0db9ccdfc8d1f63c5b | https://github.com/RRZE-HPC/pycachesim/blob/6dd084d29cf91ec19b016e0db9ccdfc8d1f63c5b/cachesim/cache.py#L441-L447 | train | 24,483 |
RRZE-HPC/pycachesim | cachesim/cache.py | MainMemory.store_from | def store_from(self, last_level_store):
"""Set level where to store to."""
assert isinstance(last_level_store, Cache), \
"last_level needs to be a Cache object."
assert last_level_store.store_to is None, \
"last_level_store must be a last level cache (.store_to is None)."
self.last_level_store = last_level_store | python | def store_from(self, last_level_store):
"""Set level where to store to."""
assert isinstance(last_level_store, Cache), \
"last_level needs to be a Cache object."
assert last_level_store.store_to is None, \
"last_level_store must be a last level cache (.store_to is None)."
self.last_level_store = last_level_store | [
"def",
"store_from",
"(",
"self",
",",
"last_level_store",
")",
":",
"assert",
"isinstance",
"(",
"last_level_store",
",",
"Cache",
")",
",",
"\"last_level needs to be a Cache object.\"",
"assert",
"last_level_store",
".",
"store_to",
"is",
"None",
",",
"\"last_level_... | Set level where to store to. | [
"Set",
"level",
"where",
"to",
"store",
"to",
"."
] | 6dd084d29cf91ec19b016e0db9ccdfc8d1f63c5b | https://github.com/RRZE-HPC/pycachesim/blob/6dd084d29cf91ec19b016e0db9ccdfc8d1f63c5b/cachesim/cache.py#L449-L455 | train | 24,484 |
datastore/datastore | datastore/core/key.py | Key.list | def list(self):
'''Returns the `list` representation of this Key.
Note that this method assumes the key is immutable.
'''
if not self._list:
self._list = map(Namespace, self._string.split('/'))
return self._list | python | def list(self):
'''Returns the `list` representation of this Key.
Note that this method assumes the key is immutable.
'''
if not self._list:
self._list = map(Namespace, self._string.split('/'))
return self._list | [
"def",
"list",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_list",
":",
"self",
".",
"_list",
"=",
"map",
"(",
"Namespace",
",",
"self",
".",
"_string",
".",
"split",
"(",
"'/'",
")",
")",
"return",
"self",
".",
"_list"
] | Returns the `list` representation of this Key.
Note that this method assumes the key is immutable. | [
"Returns",
"the",
"list",
"representation",
"of",
"this",
"Key",
"."
] | 7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3 | https://github.com/datastore/datastore/blob/7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3/datastore/core/key.py#L81-L88 | train | 24,485 |
datastore/datastore | datastore/core/key.py | Key.instance | def instance(self, other):
'''Returns an instance Key, by appending a name to the namespace.'''
assert '/' not in str(other)
return Key(str(self) + ':' + str(other)) | python | def instance(self, other):
'''Returns an instance Key, by appending a name to the namespace.'''
assert '/' not in str(other)
return Key(str(self) + ':' + str(other)) | [
"def",
"instance",
"(",
"self",
",",
"other",
")",
":",
"assert",
"'/'",
"not",
"in",
"str",
"(",
"other",
")",
"return",
"Key",
"(",
"str",
"(",
"self",
")",
"+",
"':'",
"+",
"str",
"(",
"other",
")",
")"
] | Returns an instance Key, by appending a name to the namespace. | [
"Returns",
"an",
"instance",
"Key",
"by",
"appending",
"a",
"name",
"to",
"the",
"namespace",
"."
] | 7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3 | https://github.com/datastore/datastore/blob/7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3/datastore/core/key.py#L115-L118 | train | 24,486 |
datastore/datastore | datastore/core/key.py | Key.isAncestorOf | def isAncestorOf(self, other):
'''Returns whether this Key is an ancestor of `other`.
>>> john = Key('/Comedy/MontyPython/Actor:JohnCleese')
>>> Key('/Comedy').isAncestorOf(john)
True
'''
if isinstance(other, Key):
return other._string.startswith(self._string + '/')
raise TypeError('%s is not of type %s' % (other, Key)) | python | def isAncestorOf(self, other):
'''Returns whether this Key is an ancestor of `other`.
>>> john = Key('/Comedy/MontyPython/Actor:JohnCleese')
>>> Key('/Comedy').isAncestorOf(john)
True
'''
if isinstance(other, Key):
return other._string.startswith(self._string + '/')
raise TypeError('%s is not of type %s' % (other, Key)) | [
"def",
"isAncestorOf",
"(",
"self",
",",
"other",
")",
":",
"if",
"isinstance",
"(",
"other",
",",
"Key",
")",
":",
"return",
"other",
".",
"_string",
".",
"startswith",
"(",
"self",
".",
"_string",
"+",
"'/'",
")",
"raise",
"TypeError",
"(",
"'%s is n... | Returns whether this Key is an ancestor of `other`.
>>> john = Key('/Comedy/MontyPython/Actor:JohnCleese')
>>> Key('/Comedy').isAncestorOf(john)
True | [
"Returns",
"whether",
"this",
"Key",
"is",
"an",
"ancestor",
"of",
"other",
"."
] | 7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3 | https://github.com/datastore/datastore/blob/7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3/datastore/core/key.py#L147-L157 | train | 24,487 |
datastore/datastore | datastore/core/key.py | Key.isDescendantOf | def isDescendantOf(self, other):
'''Returns whether this Key is a descendant of `other`.
>>> Key('/Comedy/MontyPython').isDescendantOf(Key('/Comedy'))
True
'''
if isinstance(other, Key):
return other.isAncestorOf(self)
raise TypeError('%s is not of type %s' % (other, Key)) | python | def isDescendantOf(self, other):
'''Returns whether this Key is a descendant of `other`.
>>> Key('/Comedy/MontyPython').isDescendantOf(Key('/Comedy'))
True
'''
if isinstance(other, Key):
return other.isAncestorOf(self)
raise TypeError('%s is not of type %s' % (other, Key)) | [
"def",
"isDescendantOf",
"(",
"self",
",",
"other",
")",
":",
"if",
"isinstance",
"(",
"other",
",",
"Key",
")",
":",
"return",
"other",
".",
"isAncestorOf",
"(",
"self",
")",
"raise",
"TypeError",
"(",
"'%s is not of type %s'",
"%",
"(",
"other",
",",
"... | Returns whether this Key is a descendant of `other`.
>>> Key('/Comedy/MontyPython').isDescendantOf(Key('/Comedy'))
True | [
"Returns",
"whether",
"this",
"Key",
"is",
"a",
"descendant",
"of",
"other",
"."
] | 7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3 | https://github.com/datastore/datastore/blob/7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3/datastore/core/key.py#L159-L168 | train | 24,488 |
datastore/datastore | datastore/filesystem/__init__.py | ensure_directory_exists | def ensure_directory_exists(directory):
'''Ensures `directory` exists. May make `directory` and intermediate dirs.
Raises RuntimeError if `directory` is a file.
'''
if not os.path.exists(directory):
os.makedirs(directory)
elif os.path.isfile(directory):
raise RuntimeError('Path %s is a file, not a directory.' % directory) | python | def ensure_directory_exists(directory):
'''Ensures `directory` exists. May make `directory` and intermediate dirs.
Raises RuntimeError if `directory` is a file.
'''
if not os.path.exists(directory):
os.makedirs(directory)
elif os.path.isfile(directory):
raise RuntimeError('Path %s is a file, not a directory.' % directory) | [
"def",
"ensure_directory_exists",
"(",
"directory",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"directory",
")",
":",
"os",
".",
"makedirs",
"(",
"directory",
")",
"elif",
"os",
".",
"path",
".",
"isfile",
"(",
"directory",
")",
":",... | Ensures `directory` exists. May make `directory` and intermediate dirs.
Raises RuntimeError if `directory` is a file. | [
"Ensures",
"directory",
"exists",
".",
"May",
"make",
"directory",
"and",
"intermediate",
"dirs",
".",
"Raises",
"RuntimeError",
"if",
"directory",
"is",
"a",
"file",
"."
] | 7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3 | https://github.com/datastore/datastore/blob/7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3/datastore/filesystem/__init__.py#L16-L23 | train | 24,489 |
datastore/datastore | datastore/filesystem/__init__.py | FileSystemDatastore.relative_path | def relative_path(self, key):
'''Returns the relative path for given `key`'''
key = str(key) # stringify
key = key.replace(':', '/') # turn namespace delimiters into slashes
key = key[1:] # remove first slash (absolute)
if not self.case_sensitive:
key = key.lower() # coerce to lowercase
return os.path.normpath(key) | python | def relative_path(self, key):
'''Returns the relative path for given `key`'''
key = str(key) # stringify
key = key.replace(':', '/') # turn namespace delimiters into slashes
key = key[1:] # remove first slash (absolute)
if not self.case_sensitive:
key = key.lower() # coerce to lowercase
return os.path.normpath(key) | [
"def",
"relative_path",
"(",
"self",
",",
"key",
")",
":",
"key",
"=",
"str",
"(",
"key",
")",
"# stringify",
"key",
"=",
"key",
".",
"replace",
"(",
"':'",
",",
"'/'",
")",
"# turn namespace delimiters into slashes",
"key",
"=",
"key",
"[",
"1",
":",
... | Returns the relative path for given `key` | [
"Returns",
"the",
"relative",
"path",
"for",
"given",
"key"
] | 7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3 | https://github.com/datastore/datastore/blob/7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3/datastore/filesystem/__init__.py#L111-L118 | train | 24,490 |
datastore/datastore | datastore/filesystem/__init__.py | FileSystemDatastore.path | def path(self, key):
'''Returns the `path` for given `key`'''
return os.path.join(self.root_path, self.relative_path(key)) | python | def path(self, key):
'''Returns the `path` for given `key`'''
return os.path.join(self.root_path, self.relative_path(key)) | [
"def",
"path",
"(",
"self",
",",
"key",
")",
":",
"return",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"root_path",
",",
"self",
".",
"relative_path",
"(",
"key",
")",
")"
] | Returns the `path` for given `key` | [
"Returns",
"the",
"path",
"for",
"given",
"key"
] | 7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3 | https://github.com/datastore/datastore/blob/7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3/datastore/filesystem/__init__.py#L120-L122 | train | 24,491 |
datastore/datastore | datastore/filesystem/__init__.py | FileSystemDatastore.object_path | def object_path(self, key):
'''return the object path for `key`.'''
return os.path.join(self.root_path, self.relative_object_path(key)) | python | def object_path(self, key):
'''return the object path for `key`.'''
return os.path.join(self.root_path, self.relative_object_path(key)) | [
"def",
"object_path",
"(",
"self",
",",
"key",
")",
":",
"return",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"root_path",
",",
"self",
".",
"relative_object_path",
"(",
"key",
")",
")"
] | return the object path for `key`. | [
"return",
"the",
"object",
"path",
"for",
"key",
"."
] | 7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3 | https://github.com/datastore/datastore/blob/7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3/datastore/filesystem/__init__.py#L128-L130 | train | 24,492 |
datastore/datastore | datastore/filesystem/__init__.py | FileSystemDatastore._write_object | def _write_object(self, path, value):
'''write out `object` to file at `path`'''
ensure_directory_exists(os.path.dirname(path))
with open(path, 'w') as f:
f.write(value) | python | def _write_object(self, path, value):
'''write out `object` to file at `path`'''
ensure_directory_exists(os.path.dirname(path))
with open(path, 'w') as f:
f.write(value) | [
"def",
"_write_object",
"(",
"self",
",",
"path",
",",
"value",
")",
":",
"ensure_directory_exists",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"path",
")",
")",
"with",
"open",
"(",
"path",
",",
"'w'",
")",
"as",
"f",
":",
"f",
".",
"write",
"("... | write out `object` to file at `path` | [
"write",
"out",
"object",
"to",
"file",
"at",
"path"
] | 7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3 | https://github.com/datastore/datastore/blob/7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3/datastore/filesystem/__init__.py#L135-L140 | train | 24,493 |
datastore/datastore | datastore/filesystem/__init__.py | FileSystemDatastore._read_object | def _read_object(self, path):
'''read in object from file at `path`'''
if not os.path.exists(path):
return None
if os.path.isdir(path):
raise RuntimeError('%s is a directory, not a file.' % path)
with open(path) as f:
file_contents = f.read()
return file_contents | python | def _read_object(self, path):
'''read in object from file at `path`'''
if not os.path.exists(path):
return None
if os.path.isdir(path):
raise RuntimeError('%s is a directory, not a file.' % path)
with open(path) as f:
file_contents = f.read()
return file_contents | [
"def",
"_read_object",
"(",
"self",
",",
"path",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
":",
"return",
"None",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"path",
")",
":",
"raise",
"RuntimeError",
"(",
"'%s is a... | read in object from file at `path` | [
"read",
"in",
"object",
"from",
"file",
"at",
"path"
] | 7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3 | https://github.com/datastore/datastore/blob/7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3/datastore/filesystem/__init__.py#L142-L153 | train | 24,494 |
datastore/datastore | datastore/filesystem/__init__.py | FileSystemDatastore.get | def get(self, key):
'''Return the object named by key or None if it does not exist.
Args:
key: Key naming the object to retrieve
Returns:
object or None
'''
path = self.object_path(key)
return self._read_object(path) | python | def get(self, key):
'''Return the object named by key or None if it does not exist.
Args:
key: Key naming the object to retrieve
Returns:
object or None
'''
path = self.object_path(key)
return self._read_object(path) | [
"def",
"get",
"(",
"self",
",",
"key",
")",
":",
"path",
"=",
"self",
".",
"object_path",
"(",
"key",
")",
"return",
"self",
".",
"_read_object",
"(",
"path",
")"
] | Return the object named by key or None if it does not exist.
Args:
key: Key naming the object to retrieve
Returns:
object or None | [
"Return",
"the",
"object",
"named",
"by",
"key",
"or",
"None",
"if",
"it",
"does",
"not",
"exist",
"."
] | 7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3 | https://github.com/datastore/datastore/blob/7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3/datastore/filesystem/__init__.py#L163-L173 | train | 24,495 |
datastore/datastore | datastore/filesystem/__init__.py | FileSystemDatastore.query | def query(self, query):
'''Returns an iterable of objects matching criteria expressed in `query`
FSDatastore.query queries all the `.obj` files within the directory
specified by the query.key.
Args:
query: Query object describing the objects to return.
Raturns:
Cursor with all objects matching criteria
'''
path = self.path(query.key)
if os.path.exists(path):
filenames = os.listdir(path)
filenames = list(set(filenames) - set(self.ignore_list))
filenames = map(lambda f: os.path.join(path, f), filenames)
iterable = self._read_object_gen(filenames)
else:
iterable = list()
return query(iterable) | python | def query(self, query):
'''Returns an iterable of objects matching criteria expressed in `query`
FSDatastore.query queries all the `.obj` files within the directory
specified by the query.key.
Args:
query: Query object describing the objects to return.
Raturns:
Cursor with all objects matching criteria
'''
path = self.path(query.key)
if os.path.exists(path):
filenames = os.listdir(path)
filenames = list(set(filenames) - set(self.ignore_list))
filenames = map(lambda f: os.path.join(path, f), filenames)
iterable = self._read_object_gen(filenames)
else:
iterable = list()
return query(iterable) | [
"def",
"query",
"(",
"self",
",",
"query",
")",
":",
"path",
"=",
"self",
".",
"path",
"(",
"query",
".",
"key",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
":",
"filenames",
"=",
"os",
".",
"listdir",
"(",
"path",
")",
"file... | Returns an iterable of objects matching criteria expressed in `query`
FSDatastore.query queries all the `.obj` files within the directory
specified by the query.key.
Args:
query: Query object describing the objects to return.
Raturns:
Cursor with all objects matching criteria | [
"Returns",
"an",
"iterable",
"of",
"objects",
"matching",
"criteria",
"expressed",
"in",
"query",
"FSDatastore",
".",
"query",
"queries",
"all",
"the",
".",
"obj",
"files",
"within",
"the",
"directory",
"specified",
"by",
"the",
"query",
".",
"key",
"."
] | 7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3 | https://github.com/datastore/datastore/blob/7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3/datastore/filesystem/__init__.py#L198-L219 | train | 24,496 |
datastore/datastore | datastore/filesystem/__init__.py | FileSystemDatastore.contains | def contains(self, key):
'''Returns whether the object named by `key` exists.
Optimized to only check whether the file object exists.
Args:
key: Key naming the object to check.
Returns:
boalean whether the object exists
'''
path = self.object_path(key)
return os.path.exists(path) and os.path.isfile(path) | python | def contains(self, key):
'''Returns whether the object named by `key` exists.
Optimized to only check whether the file object exists.
Args:
key: Key naming the object to check.
Returns:
boalean whether the object exists
'''
path = self.object_path(key)
return os.path.exists(path) and os.path.isfile(path) | [
"def",
"contains",
"(",
"self",
",",
"key",
")",
":",
"path",
"=",
"self",
".",
"object_path",
"(",
"key",
")",
"return",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
"and",
"os",
".",
"path",
".",
"isfile",
"(",
"path",
")"
] | Returns whether the object named by `key` exists.
Optimized to only check whether the file object exists.
Args:
key: Key naming the object to check.
Returns:
boalean whether the object exists | [
"Returns",
"whether",
"the",
"object",
"named",
"by",
"key",
"exists",
".",
"Optimized",
"to",
"only",
"check",
"whether",
"the",
"file",
"object",
"exists",
"."
] | 7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3 | https://github.com/datastore/datastore/blob/7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3/datastore/filesystem/__init__.py#L221-L232 | train | 24,497 |
datastore/datastore | datastore/core/basic.py | DictDatastore._collection | def _collection(self, key):
'''Returns the namespace collection for `key`.'''
collection = str(key.path)
if not collection in self._items:
self._items[collection] = dict()
return self._items[collection] | python | def _collection(self, key):
'''Returns the namespace collection for `key`.'''
collection = str(key.path)
if not collection in self._items:
self._items[collection] = dict()
return self._items[collection] | [
"def",
"_collection",
"(",
"self",
",",
"key",
")",
":",
"collection",
"=",
"str",
"(",
"key",
".",
"path",
")",
"if",
"not",
"collection",
"in",
"self",
".",
"_items",
":",
"self",
".",
"_items",
"[",
"collection",
"]",
"=",
"dict",
"(",
")",
"ret... | Returns the namespace collection for `key`. | [
"Returns",
"the",
"namespace",
"collection",
"for",
"key",
"."
] | 7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3 | https://github.com/datastore/datastore/blob/7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3/datastore/core/basic.py#L121-L126 | train | 24,498 |
datastore/datastore | datastore/core/basic.py | DictDatastore.query | def query(self, query):
'''Returns an iterable of objects matching criteria expressed in `query`
Naively applies the query operations on the objects within the namespaced
collection corresponding to ``query.key.path``.
Args:
query: Query object describing the objects to return.
Raturns:
iterable cursor with all objects matching criteria
'''
# entire dataset already in memory, so ok to apply query naively
if str(query.key) in self._items:
return query(self._items[str(query.key)].values())
else:
return query([]) | python | def query(self, query):
'''Returns an iterable of objects matching criteria expressed in `query`
Naively applies the query operations on the objects within the namespaced
collection corresponding to ``query.key.path``.
Args:
query: Query object describing the objects to return.
Raturns:
iterable cursor with all objects matching criteria
'''
# entire dataset already in memory, so ok to apply query naively
if str(query.key) in self._items:
return query(self._items[str(query.key)].values())
else:
return query([]) | [
"def",
"query",
"(",
"self",
",",
"query",
")",
":",
"# entire dataset already in memory, so ok to apply query naively",
"if",
"str",
"(",
"query",
".",
"key",
")",
"in",
"self",
".",
"_items",
":",
"return",
"query",
"(",
"self",
".",
"_items",
"[",
"str",
... | Returns an iterable of objects matching criteria expressed in `query`
Naively applies the query operations on the objects within the namespaced
collection corresponding to ``query.key.path``.
Args:
query: Query object describing the objects to return.
Raturns:
iterable cursor with all objects matching criteria | [
"Returns",
"an",
"iterable",
"of",
"objects",
"matching",
"criteria",
"expressed",
"in",
"query"
] | 7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3 | https://github.com/datastore/datastore/blob/7ccf0cd4748001d3dbf5e6dda369b0f63e0269d3/datastore/core/basic.py#L188-L205 | train | 24,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.