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 list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
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.... | 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.... | [
"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 |
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
) -> "Obse... | 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
) -> "Obse... | [
"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 |
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, actio... | 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, actio... | [
"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 |
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=obse... | 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=obse... | [
"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 |
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 |
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 |
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 |
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:
... | 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:
... | [
"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 |
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.C... | 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.C... | [
"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 |
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
... | 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
... | [
"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 |
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 {}.... | 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 {}.... | [
"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 |
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 |
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 ... | 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 ... | [
"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 |
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)
# Ad... | 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)
# Ad... | [
"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 |
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']
... | 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']
... | [
"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 |
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... | 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... | [
"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 |
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/")
... | 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/")
... | [
"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 |
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, Deprecati... | 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, Deprecati... | [
"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 |
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:
... | 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:
... | [
"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 |
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 = se... | 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 = se... | [
"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 |
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... | 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... | [
"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 |
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_stat... | 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_stat... | [
"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 |
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:
... | 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:
... | [
"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 |
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... | 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... | [
"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 |
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
... | 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
... | [
"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 |
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 |
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 |
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... | 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... | [
"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 |
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 = co... | 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 = co... | [
"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 |
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 |
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', ... | 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', ... | [
"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 |
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:
... | 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:
... | [
"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 |
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_)
... | 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_)
... | [
"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 |
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... | 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... | [
"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 |
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 |
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 =... | 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 =... | [
"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 |
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 = ... | 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 = ... | [
"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 |
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 =... | 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 =... | [
"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 |
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(val... | 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(val... | [
"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 |
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
... | 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
... | [
"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 |
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(... | 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(... | [
"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 |
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 |
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 |
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 |
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 |
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
f... | 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
f... | [
"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 |
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):... | 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):... | [
"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 |
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 |
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:
... | 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:
... | [
"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 |
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:
... | 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:
... | [
"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 |
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 |
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:
... | 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:
... | [
"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 |
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... | 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... | [
"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
... | [
"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 |
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)
... | 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)
... | [
"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 |
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: segme... | 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: segme... | [
"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 |
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... | 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... | [
"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): segmen... | [
"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 |
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... | 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... | [
"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 |
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 da... | 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 da... | [
"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 |
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(wo... | 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(wo... | [
"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 |
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 lis... | 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 lis... | [
"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 |
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
"""
... | 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
"""
... | [
"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 |
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... | 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... | [
"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 |
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:
... | 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:
... | [
"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... | [
"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 |
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:
... | 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:
... | [
"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... | [
"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 |
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.
in... | 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.
in... | [
"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 Unicod... | [
"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 |
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:
i... | 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:
i... | [
"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... | [
"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 |
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 correspondi... | 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 correspondi... | [
"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... | [
"Implements",
"fixed",
"-",
"width",
"pattern",
"matching",
"."
] | 17eaa482e3edb211f3a8138137d76e4b9246d201 | https://github.com/dmort27/panphon/blob/17eaa482e3edb211f3a8138137d76e4b9246d201/panphon/_panphon.py#L414-L437 | train |
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 b... | 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 b... | [
"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:
... | [
"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 |
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
`Feature... | 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
`Feature... | [
"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 |
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
... | 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
... | [
"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 |
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 |
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 |
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 `s... | 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 `s... | [
"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 |
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,
... | 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,
... | [
"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 |
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
el... | 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
el... | [
"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 |
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 wri... | 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 wri... | [
"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 |
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 ... | 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 ... | [
"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 |
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_... | 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_... | [
"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 |
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... | 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... | [
"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 |
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 |
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 ... | 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 ... | [
"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 |
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... | 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... | [
"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 |
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... | 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... | [
"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 |
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)."
... | 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)."
... | [
"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 |
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)."... | 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)."... | [
"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 |
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 |
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 |
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... | 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... | [
"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 |
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 |
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 dir... | 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 dir... | [
"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 |
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.low... | 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.low... | [
"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 |
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 |
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 |
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 |
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 |
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 |
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 ... | 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 ... | [
"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 |
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(pat... | 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(pat... | [
"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 |
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 |
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:
... | 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:
... | [
"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 obj... | [
"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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.