repo stringlengths 7 55 | path stringlengths 4 223 | func_name stringlengths 1 134 | original_string stringlengths 75 104k | language stringclasses 1
value | code stringlengths 75 104k | code_tokens listlengths 19 28.4k | docstring stringlengths 1 46.9k | docstring_tokens listlengths 1 1.97k | sha stringlengths 40 40 | url stringlengths 87 315 | partition stringclasses 3
values | summary stringlengths 4 350 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
dgomes/pyipma | pyipma/api.py | IPMA_API._to_number | def _to_number(cls, string):
"""Convert string to int or float."""
try:
if float(string) - int(string) == 0:
return int(string)
return float(string)
except ValueError:
try:
return float(string)
except ValueError:
... | python | def _to_number(cls, string):
"""Convert string to int or float."""
try:
if float(string) - int(string) == 0:
return int(string)
return float(string)
except ValueError:
try:
return float(string)
except ValueError:
... | [
"def",
"_to_number",
"(",
"cls",
",",
"string",
")",
":",
"try",
":",
"if",
"float",
"(",
"string",
")",
"-",
"int",
"(",
"string",
")",
"==",
"0",
":",
"return",
"int",
"(",
"string",
")",
"return",
"float",
"(",
"string",
")",
"except",
"ValueErr... | Convert string to int or float. | [
"Convert",
"string",
"to",
"int",
"or",
"float",
"."
] | cd808abeb70dca0e336afdf55bef3f73973eaa71 | https://github.com/dgomes/pyipma/blob/cd808abeb70dca0e336afdf55bef3f73973eaa71/pyipma/api.py#L35-L45 | train | Convert string to int or float. |
dgomes/pyipma | pyipma/api.py | IPMA_API.stations | async def stations(self):
"""Retrieve stations."""
data = await self.retrieve(API_DISTRITS)
Station = namedtuple('Station', ['latitude', 'longitude',
'idAreaAviso', 'idConselho',
'idDistrito', 'idRegiao',
... | python | async def stations(self):
"""Retrieve stations."""
data = await self.retrieve(API_DISTRITS)
Station = namedtuple('Station', ['latitude', 'longitude',
'idAreaAviso', 'idConselho',
'idDistrito', 'idRegiao',
... | [
"async",
"def",
"stations",
"(",
"self",
")",
":",
"data",
"=",
"await",
"self",
".",
"retrieve",
"(",
"API_DISTRITS",
")",
"Station",
"=",
"namedtuple",
"(",
"'Station'",
",",
"[",
"'latitude'",
",",
"'longitude'",
",",
"'idAreaAviso'",
",",
"'idConselho'",... | Retrieve stations. | [
"Retrieve",
"stations",
"."
] | cd808abeb70dca0e336afdf55bef3f73973eaa71 | https://github.com/dgomes/pyipma/blob/cd808abeb70dca0e336afdf55bef3f73973eaa71/pyipma/api.py#L47-L74 | train | Retrieve stations. |
dgomes/pyipma | pyipma/api.py | IPMA_API.forecast | async def forecast(self, globalIdLocal):
"""Retrieve next 5 days forecast."""
data = await self.retrieve(API_FORECAST + "{globalIdLocal}.json".
format(globalIdLocal=globalIdLocal))
if not self.weather_type:
await self.weather_type_classe()
... | python | async def forecast(self, globalIdLocal):
"""Retrieve next 5 days forecast."""
data = await self.retrieve(API_FORECAST + "{globalIdLocal}.json".
format(globalIdLocal=globalIdLocal))
if not self.weather_type:
await self.weather_type_classe()
... | [
"async",
"def",
"forecast",
"(",
"self",
",",
"globalIdLocal",
")",
":",
"data",
"=",
"await",
"self",
".",
"retrieve",
"(",
"API_FORECAST",
"+",
"\"{globalIdLocal}.json\"",
".",
"format",
"(",
"globalIdLocal",
"=",
"globalIdLocal",
")",
")",
"if",
"not",
"s... | Retrieve next 5 days forecast. | [
"Retrieve",
"next",
"5",
"days",
"forecast",
"."
] | cd808abeb70dca0e336afdf55bef3f73973eaa71 | https://github.com/dgomes/pyipma/blob/cd808abeb70dca0e336afdf55bef3f73973eaa71/pyipma/api.py#L76-L97 | train | Retrieve next 5 days forecast. |
dgomes/pyipma | pyipma/api.py | IPMA_API.weather_type_classe | async def weather_type_classe(self):
"""Retrieve translation for weather type."""
data = await self.retrieve(url=API_WEATHER_TYPE)
self.weather_type = dict()
for _type in data['data']:
self.weather_type[_type['idWeatherType']] = _type['descIdWeatherTypePT']
return... | python | async def weather_type_classe(self):
"""Retrieve translation for weather type."""
data = await self.retrieve(url=API_WEATHER_TYPE)
self.weather_type = dict()
for _type in data['data']:
self.weather_type[_type['idWeatherType']] = _type['descIdWeatherTypePT']
return... | [
"async",
"def",
"weather_type_classe",
"(",
"self",
")",
":",
"data",
"=",
"await",
"self",
".",
"retrieve",
"(",
"url",
"=",
"API_WEATHER_TYPE",
")",
"self",
".",
"weather_type",
"=",
"dict",
"(",
")",
"for",
"_type",
"in",
"data",
"[",
"'data'",
"]",
... | Retrieve translation for weather type. | [
"Retrieve",
"translation",
"for",
"weather",
"type",
"."
] | cd808abeb70dca0e336afdf55bef3f73973eaa71 | https://github.com/dgomes/pyipma/blob/cd808abeb70dca0e336afdf55bef3f73973eaa71/pyipma/api.py#L99-L109 | train | Retrieve translation for weather type. |
dgomes/pyipma | pyipma/api.py | IPMA_API.wind_type_classe | async def wind_type_classe(self):
"""Retrieve translation for wind type."""
data = await self.retrieve(url=API_WIND_TYPE)
self.wind_type = dict()
for _type in data['data']:
self.wind_type[int(_type['classWindSpeed'])] = _type['descClassWindSpeedDailyPT']
return se... | python | async def wind_type_classe(self):
"""Retrieve translation for wind type."""
data = await self.retrieve(url=API_WIND_TYPE)
self.wind_type = dict()
for _type in data['data']:
self.wind_type[int(_type['classWindSpeed'])] = _type['descClassWindSpeedDailyPT']
return se... | [
"async",
"def",
"wind_type_classe",
"(",
"self",
")",
":",
"data",
"=",
"await",
"self",
".",
"retrieve",
"(",
"url",
"=",
"API_WIND_TYPE",
")",
"self",
".",
"wind_type",
"=",
"dict",
"(",
")",
"for",
"_type",
"in",
"data",
"[",
"'data'",
"]",
":",
"... | Retrieve translation for wind type. | [
"Retrieve",
"translation",
"for",
"wind",
"type",
"."
] | cd808abeb70dca0e336afdf55bef3f73973eaa71 | https://github.com/dgomes/pyipma/blob/cd808abeb70dca0e336afdf55bef3f73973eaa71/pyipma/api.py#L111-L121 | train | Retrieve translation for wind type. |
dgomes/pyipma | pyipma/api.py | IPMA_API.observations | async def observations(self):
"""Retrieve current weather observation."""
observations = []
raw_stations = await self.retrieve(url=API_OBSERVATION_STATIONS,
headers={'Referer': 'http://www.ipma.pt'})
if not raw_stations:
return obse... | python | async def observations(self):
"""Retrieve current weather observation."""
observations = []
raw_stations = await self.retrieve(url=API_OBSERVATION_STATIONS,
headers={'Referer': 'http://www.ipma.pt'})
if not raw_stations:
return obse... | [
"async",
"def",
"observations",
"(",
"self",
")",
":",
"observations",
"=",
"[",
"]",
"raw_stations",
"=",
"await",
"self",
".",
"retrieve",
"(",
"url",
"=",
"API_OBSERVATION_STATIONS",
",",
"headers",
"=",
"{",
"'Referer'",
":",
"'http://www.ipma.pt'",
"}",
... | Retrieve current weather observation. | [
"Retrieve",
"current",
"weather",
"observation",
"."
] | cd808abeb70dca0e336afdf55bef3f73973eaa71 | https://github.com/dgomes/pyipma/blob/cd808abeb70dca0e336afdf55bef3f73973eaa71/pyipma/api.py#L123-L171 | train | Retrieve current weather observation. |
jdodds/feather | feather/dispatcher.py | Dispatcher.register | def register(self, plugin):
"""Add the plugin to our set of listeners for each message that it
listens to, tell it to use our messages Queue for communication, and
start it up.
"""
for listener in plugin.listeners:
self.listeners[listener].add(plugin)
self.plu... | python | def register(self, plugin):
"""Add the plugin to our set of listeners for each message that it
listens to, tell it to use our messages Queue for communication, and
start it up.
"""
for listener in plugin.listeners:
self.listeners[listener].add(plugin)
self.plu... | [
"def",
"register",
"(",
"self",
",",
"plugin",
")",
":",
"for",
"listener",
"in",
"plugin",
".",
"listeners",
":",
"self",
".",
"listeners",
"[",
"listener",
"]",
".",
"add",
"(",
"plugin",
")",
"self",
".",
"plugins",
".",
"add",
"(",
"plugin",
")",... | Add the plugin to our set of listeners for each message that it
listens to, tell it to use our messages Queue for communication, and
start it up. | [
"Add",
"the",
"plugin",
"to",
"our",
"set",
"of",
"listeners",
"for",
"each",
"message",
"that",
"it",
"listens",
"to",
"tell",
"it",
"to",
"use",
"our",
"messages",
"Queue",
"for",
"communication",
"and",
"start",
"it",
"up",
"."
] | 92a9426e692b33c7fddf758df8dbc99a9a1ba8ef | https://github.com/jdodds/feather/blob/92a9426e692b33c7fddf758df8dbc99a9a1ba8ef/feather/dispatcher.py#L16-L25 | train | Register a new plugin to our set of listeners and messages Queue for communication. |
jdodds/feather | feather/dispatcher.py | Dispatcher.start | def start(self):
"""Send 'APP_START' to any plugins that listen for it, and loop around
waiting for messages and sending them to their listening plugins until
it's time to shutdown.
"""
self.recieve('APP_START')
self.alive = True
while self.alive:
mess... | python | def start(self):
"""Send 'APP_START' to any plugins that listen for it, and loop around
waiting for messages and sending them to their listening plugins until
it's time to shutdown.
"""
self.recieve('APP_START')
self.alive = True
while self.alive:
mess... | [
"def",
"start",
"(",
"self",
")",
":",
"self",
".",
"recieve",
"(",
"'APP_START'",
")",
"self",
".",
"alive",
"=",
"True",
"while",
"self",
".",
"alive",
":",
"message",
",",
"payload",
"=",
"self",
".",
"messages",
".",
"get",
"(",
")",
"if",
"mes... | Send 'APP_START' to any plugins that listen for it, and loop around
waiting for messages and sending them to their listening plugins until
it's time to shutdown. | [
"Send",
"APP_START",
"to",
"any",
"plugins",
"that",
"listen",
"for",
"it",
"and",
"loop",
"around",
"waiting",
"for",
"messages",
"and",
"sending",
"them",
"to",
"their",
"listening",
"plugins",
"until",
"it",
"s",
"time",
"to",
"shutdown",
"."
] | 92a9426e692b33c7fddf758df8dbc99a9a1ba8ef | https://github.com/jdodds/feather/blob/92a9426e692b33c7fddf758df8dbc99a9a1ba8ef/feather/dispatcher.py#L27-L41 | train | Send APP_START to any plugins that listen for it and loop around the messages waiting for them to be sent to their listening plugins until the application is stopped. |
tamasgal/km3pipe | km3pipe/style/__init__.py | ColourCycler.choose | def choose(self, palette):
"""Pick a palette"""
try:
self._cycler = cycle(self.colours[palette])
except KeyError:
raise KeyError(
"Chose one of the following colour palettes: {0}".format(
self.available
)
) | python | def choose(self, palette):
"""Pick a palette"""
try:
self._cycler = cycle(self.colours[palette])
except KeyError:
raise KeyError(
"Chose one of the following colour palettes: {0}".format(
self.available
)
) | [
"def",
"choose",
"(",
"self",
",",
"palette",
")",
":",
"try",
":",
"self",
".",
"_cycler",
"=",
"cycle",
"(",
"self",
".",
"colours",
"[",
"palette",
"]",
")",
"except",
"KeyError",
":",
"raise",
"KeyError",
"(",
"\"Chose one of the following colour palette... | Pick a palette | [
"Pick",
"a",
"palette"
] | 7a9b59ac899a28775b5bdc5d391d9a5340d08040 | https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/style/__init__.py#L50-L59 | train | Pick a palette |
tamasgal/km3pipe | km3pipe/style/__init__.py | ColourCycler.refresh_styles | def refresh_styles(self):
"""Load all available styles"""
import matplotlib.pyplot as plt
self.colours = {}
for style in plt.style.available:
try:
style_colours = plt.style.library[style]['axes.prop_cycle']
self.colours[style] = [c['color'] fo... | python | def refresh_styles(self):
"""Load all available styles"""
import matplotlib.pyplot as plt
self.colours = {}
for style in plt.style.available:
try:
style_colours = plt.style.library[style]['axes.prop_cycle']
self.colours[style] = [c['color'] fo... | [
"def",
"refresh_styles",
"(",
"self",
")",
":",
"import",
"matplotlib",
".",
"pyplot",
"as",
"plt",
"self",
".",
"colours",
"=",
"{",
"}",
"for",
"style",
"in",
"plt",
".",
"style",
".",
"available",
":",
"try",
":",
"style_colours",
"=",
"plt",
".",
... | Load all available styles | [
"Load",
"all",
"available",
"styles"
] | 7a9b59ac899a28775b5bdc5d391d9a5340d08040 | https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/style/__init__.py#L61-L76 | train | Load all available styles and update colours |
wtsi-hgi/consul-lock | consullock/cli.py | _create_parser | def _create_parser() -> ArgumentParser:
"""
Creates argument parser for the CLI.
:return: the argument parser
"""
parser = ArgumentParser(prog=EXECUTABLE_NAME, description=f"{DESCRIPTION} (v{VERSION})")
parser.add_argument(
f"-{VERBOSE_SHORT_PARAMETER}", action="count", default=0,
... | python | def _create_parser() -> ArgumentParser:
"""
Creates argument parser for the CLI.
:return: the argument parser
"""
parser = ArgumentParser(prog=EXECUTABLE_NAME, description=f"{DESCRIPTION} (v{VERSION})")
parser.add_argument(
f"-{VERBOSE_SHORT_PARAMETER}", action="count", default=0,
... | [
"def",
"_create_parser",
"(",
")",
"->",
"ArgumentParser",
":",
"parser",
"=",
"ArgumentParser",
"(",
"prog",
"=",
"EXECUTABLE_NAME",
",",
"description",
"=",
"f\"{DESCRIPTION} (v{VERSION})\"",
")",
"parser",
".",
"add_argument",
"(",
"f\"-{VERBOSE_SHORT_PARAMETER}\"",
... | Creates argument parser for the CLI.
:return: the argument parser | [
"Creates",
"argument",
"parser",
"for",
"the",
"CLI",
".",
":",
"return",
":",
"the",
"argument",
"parser"
] | deb07ab41dabbb49f4d0bbc062bc3b4b6e5d71b2 | https://github.com/wtsi-hgi/consul-lock/blob/deb07ab41dabbb49f4d0bbc062bc3b4b6e5d71b2/consullock/cli.py#L124-L179 | train | Creates argument parser for the CLI. |
wtsi-hgi/consul-lock | consullock/cli.py | parse_cli_configuration | def parse_cli_configuration(arguments: List[str]) -> CliConfiguration:
"""
Parses the configuration passed in via command line arguments.
:param arguments: CLI arguments
:return: the configuration
"""
try:
parsed_arguments = {x.replace("_", "-"): y for x, y in vars(_argument_parser.parse... | python | def parse_cli_configuration(arguments: List[str]) -> CliConfiguration:
"""
Parses the configuration passed in via command line arguments.
:param arguments: CLI arguments
:return: the configuration
"""
try:
parsed_arguments = {x.replace("_", "-"): y for x, y in vars(_argument_parser.parse... | [
"def",
"parse_cli_configuration",
"(",
"arguments",
":",
"List",
"[",
"str",
"]",
")",
"->",
"CliConfiguration",
":",
"try",
":",
"parsed_arguments",
"=",
"{",
"x",
".",
"replace",
"(",
"\"_\"",
",",
"\"-\"",
")",
":",
"y",
"for",
"x",
",",
"y",
"in",
... | Parses the configuration passed in via command line arguments.
:param arguments: CLI arguments
:return: the configuration | [
"Parses",
"the",
"configuration",
"passed",
"in",
"via",
"command",
"line",
"arguments",
".",
":",
"param",
"arguments",
":",
"CLI",
"arguments",
":",
"return",
":",
"the",
"configuration"
] | deb07ab41dabbb49f4d0bbc062bc3b4b6e5d71b2 | https://github.com/wtsi-hgi/consul-lock/blob/deb07ab41dabbb49f4d0bbc062bc3b4b6e5d71b2/consullock/cli.py#L185-L234 | train | Parses the CLI arguments and returns a CliConfiguration object. |
wtsi-hgi/consul-lock | consullock/cli.py | _get_verbosity | def _get_verbosity(parsed_arguments: Dict) -> int:
"""
Gets the verbosity level from the parsed arguments.
:param parsed_arguments: the parsed arguments
:return: the verbosity level implied
"""
verbosity = DEFAULT_LOG_VERBOSITY - (int(parsed_arguments[VERBOSE_SHORT_PARAMETER]) * 10)
if verbo... | python | def _get_verbosity(parsed_arguments: Dict) -> int:
"""
Gets the verbosity level from the parsed arguments.
:param parsed_arguments: the parsed arguments
:return: the verbosity level implied
"""
verbosity = DEFAULT_LOG_VERBOSITY - (int(parsed_arguments[VERBOSE_SHORT_PARAMETER]) * 10)
if verbo... | [
"def",
"_get_verbosity",
"(",
"parsed_arguments",
":",
"Dict",
")",
"->",
"int",
":",
"verbosity",
"=",
"DEFAULT_LOG_VERBOSITY",
"-",
"(",
"int",
"(",
"parsed_arguments",
"[",
"VERBOSE_SHORT_PARAMETER",
"]",
")",
"*",
"10",
")",
"if",
"verbosity",
"<",
"10",
... | Gets the verbosity level from the parsed arguments.
:param parsed_arguments: the parsed arguments
:return: the verbosity level implied | [
"Gets",
"the",
"verbosity",
"level",
"from",
"the",
"parsed",
"arguments",
".",
":",
"param",
"parsed_arguments",
":",
"the",
"parsed",
"arguments",
":",
"return",
":",
"the",
"verbosity",
"level",
"implied"
] | deb07ab41dabbb49f4d0bbc062bc3b4b6e5d71b2 | https://github.com/wtsi-hgi/consul-lock/blob/deb07ab41dabbb49f4d0bbc062bc3b4b6e5d71b2/consullock/cli.py#L237-L247 | train | Gets the verbosity level from the parsed arguments. |
wtsi-hgi/consul-lock | consullock/cli.py | _generate_event_listener_caller | def _generate_event_listener_caller(executables: List[str]) -> LockEventListener:
"""
TODO
:param executables:
:return:
"""
def event_listener_caller(key: str):
for executable in executables:
try:
process = subprocess.Popen([executable, key], stderr=subprocess... | python | def _generate_event_listener_caller(executables: List[str]) -> LockEventListener:
"""
TODO
:param executables:
:return:
"""
def event_listener_caller(key: str):
for executable in executables:
try:
process = subprocess.Popen([executable, key], stderr=subprocess... | [
"def",
"_generate_event_listener_caller",
"(",
"executables",
":",
"List",
"[",
"str",
"]",
")",
"->",
"LockEventListener",
":",
"def",
"event_listener_caller",
"(",
"key",
":",
"str",
")",
":",
"for",
"executable",
"in",
"executables",
":",
"try",
":",
"proce... | TODO
:param executables:
:return: | [
"TODO",
":",
"param",
"executables",
":",
":",
"return",
":"
] | deb07ab41dabbb49f4d0bbc062bc3b4b6e5d71b2 | https://github.com/wtsi-hgi/consul-lock/blob/deb07ab41dabbb49f4d0bbc062bc3b4b6e5d71b2/consullock/cli.py#L250-L273 | train | Generate a function that will be called when a lock event is received. |
wtsi-hgi/consul-lock | consullock/cli.py | _acquire_lock | def _acquire_lock(lock_manager: ConsulLockManager, configuration: CliLockConfiguration) \
-> Optional[ConnectedConsulLockInformation]:
"""
TODO
:param lock_manager:
:param configuration:
:return:
"""
event_listeners: LockEventListener = {}
if configuration.on_before_locked_execut... | python | def _acquire_lock(lock_manager: ConsulLockManager, configuration: CliLockConfiguration) \
-> Optional[ConnectedConsulLockInformation]:
"""
TODO
:param lock_manager:
:param configuration:
:return:
"""
event_listeners: LockEventListener = {}
if configuration.on_before_locked_execut... | [
"def",
"_acquire_lock",
"(",
"lock_manager",
":",
"ConsulLockManager",
",",
"configuration",
":",
"CliLockConfiguration",
")",
"->",
"Optional",
"[",
"ConnectedConsulLockInformation",
"]",
":",
"event_listeners",
":",
"LockEventListener",
"=",
"{",
"}",
"if",
"configu... | TODO
:param lock_manager:
:param configuration:
:return: | [
"TODO",
":",
"param",
"lock_manager",
":",
":",
"param",
"configuration",
":",
":",
"return",
":"
] | deb07ab41dabbb49f4d0bbc062bc3b4b6e5d71b2 | https://github.com/wtsi-hgi/consul-lock/blob/deb07ab41dabbb49f4d0bbc062bc3b4b6e5d71b2/consullock/cli.py#L276-L301 | train | Acquires a lock. |
wtsi-hgi/consul-lock | consullock/cli.py | _acquire_lock_and_execute | def _acquire_lock_and_execute(lock_manager: ConsulLockManager, configuration: CliLockAndExecuteConfiguration):
"""
Executes whilst holding a lock, exiting after the execute returns with the executables return code.
:param lock_manager: the lock manager
:param configuration: the configuration
"""
... | python | def _acquire_lock_and_execute(lock_manager: ConsulLockManager, configuration: CliLockAndExecuteConfiguration):
"""
Executes whilst holding a lock, exiting after the execute returns with the executables return code.
:param lock_manager: the lock manager
:param configuration: the configuration
"""
... | [
"def",
"_acquire_lock_and_execute",
"(",
"lock_manager",
":",
"ConsulLockManager",
",",
"configuration",
":",
"CliLockAndExecuteConfiguration",
")",
":",
"lock",
"=",
"_acquire_lock",
"(",
"lock_manager",
",",
"configuration",
")",
"if",
"lock",
"is",
"None",
":",
"... | Executes whilst holding a lock, exiting after the execute returns with the executables return code.
:param lock_manager: the lock manager
:param configuration: the configuration | [
"Executes",
"whilst",
"holding",
"a",
"lock",
"exiting",
"after",
"the",
"execute",
"returns",
"with",
"the",
"executables",
"return",
"code",
".",
":",
"param",
"lock_manager",
":",
"the",
"lock",
"manager",
":",
"param",
"configuration",
":",
"the",
"configu... | deb07ab41dabbb49f4d0bbc062bc3b4b6e5d71b2 | https://github.com/wtsi-hgi/consul-lock/blob/deb07ab41dabbb49f4d0bbc062bc3b4b6e5d71b2/consullock/cli.py#L304-L314 | train | Acquires a lock and executes it. |
wtsi-hgi/consul-lock | consullock/cli.py | _acquire_lock_and_exit | def _acquire_lock_and_exit(lock_manager: ConsulLockManager, configuration: CliLockConfiguration):
"""
Locks a lock then exits.
:param lock_manager: the lock manager
:param configuration: the configuration required to lock the lock
"""
lock = _acquire_lock(lock_manager, configuration)
print(j... | python | def _acquire_lock_and_exit(lock_manager: ConsulLockManager, configuration: CliLockConfiguration):
"""
Locks a lock then exits.
:param lock_manager: the lock manager
:param configuration: the configuration required to lock the lock
"""
lock = _acquire_lock(lock_manager, configuration)
print(j... | [
"def",
"_acquire_lock_and_exit",
"(",
"lock_manager",
":",
"ConsulLockManager",
",",
"configuration",
":",
"CliLockConfiguration",
")",
":",
"lock",
"=",
"_acquire_lock",
"(",
"lock_manager",
",",
"configuration",
")",
"print",
"(",
"json",
".",
"dumps",
"(",
"loc... | Locks a lock then exits.
:param lock_manager: the lock manager
:param configuration: the configuration required to lock the lock | [
"Locks",
"a",
"lock",
"then",
"exits",
".",
":",
"param",
"lock_manager",
":",
"the",
"lock",
"manager",
":",
"param",
"configuration",
":",
"the",
"configuration",
"required",
"to",
"lock",
"the",
"lock"
] | deb07ab41dabbb49f4d0bbc062bc3b4b6e5d71b2 | https://github.com/wtsi-hgi/consul-lock/blob/deb07ab41dabbb49f4d0bbc062bc3b4b6e5d71b2/consullock/cli.py#L317-L330 | train | Acquires a lock then exits. |
wtsi-hgi/consul-lock | consullock/cli.py | _release_lock | def _release_lock(lock_manager: ConsulLockManager, configuration: CliUnlockConfiguration):
"""
Unlocks a lock.
:param lock_manager: the lock manager
:param configuration: the configuration required to unlock the lock
"""
if configuration.regex_key_enabled:
release_information = sorted(li... | python | def _release_lock(lock_manager: ConsulLockManager, configuration: CliUnlockConfiguration):
"""
Unlocks a lock.
:param lock_manager: the lock manager
:param configuration: the configuration required to unlock the lock
"""
if configuration.regex_key_enabled:
release_information = sorted(li... | [
"def",
"_release_lock",
"(",
"lock_manager",
":",
"ConsulLockManager",
",",
"configuration",
":",
"CliUnlockConfiguration",
")",
":",
"if",
"configuration",
".",
"regex_key_enabled",
":",
"release_information",
"=",
"sorted",
"(",
"list",
"(",
"lock_manager",
".",
"... | Unlocks a lock.
:param lock_manager: the lock manager
:param configuration: the configuration required to unlock the lock | [
"Unlocks",
"a",
"lock",
".",
":",
"param",
"lock_manager",
":",
"the",
"lock",
"manager",
":",
"param",
"configuration",
":",
"the",
"configuration",
"required",
"to",
"unlock",
"the",
"lock"
] | deb07ab41dabbb49f4d0bbc062bc3b4b6e5d71b2 | https://github.com/wtsi-hgi/consul-lock/blob/deb07ab41dabbb49f4d0bbc062bc3b4b6e5d71b2/consullock/cli.py#L333-L345 | train | Unlocks a lock. |
wtsi-hgi/consul-lock | consullock/cli.py | main | def main(cli_arguments: List[str]):
"""
Entrypoint.
:param cli_arguments: arguments passed in via the CLI
:raises SystemExit: always raised
"""
cli_configuration: CliConfiguration
try:
cli_configuration = parse_cli_configuration(cli_arguments)
except InvalidCliArgumentError as e:... | python | def main(cli_arguments: List[str]):
"""
Entrypoint.
:param cli_arguments: arguments passed in via the CLI
:raises SystemExit: always raised
"""
cli_configuration: CliConfiguration
try:
cli_configuration = parse_cli_configuration(cli_arguments)
except InvalidCliArgumentError as e:... | [
"def",
"main",
"(",
"cli_arguments",
":",
"List",
"[",
"str",
"]",
")",
":",
"cli_configuration",
":",
"CliConfiguration",
"try",
":",
"cli_configuration",
"=",
"parse_cli_configuration",
"(",
"cli_arguments",
")",
"except",
"InvalidCliArgumentError",
"as",
"e",
"... | Entrypoint.
:param cli_arguments: arguments passed in via the CLI
:raises SystemExit: always raised | [
"Entrypoint",
".",
":",
"param",
"cli_arguments",
":",
"arguments",
"passed",
"in",
"via",
"the",
"CLI",
":",
"raises",
"SystemExit",
":",
"always",
"raised"
] | deb07ab41dabbb49f4d0bbc062bc3b4b6e5d71b2 | https://github.com/wtsi-hgi/consul-lock/blob/deb07ab41dabbb49f4d0bbc062bc3b4b6e5d71b2/consullock/cli.py#L348-L405 | train | Entrypoint. |
dsoprea/PySchedules | pyschedules/retrieve.py | get_file_object | def get_file_object(username, password, utc_start=None, utc_stop=None):
"""Make the connection. Return a file-like object."""
if not utc_start:
utc_start = datetime.now()
if not utc_stop:
utc_stop = utc_start + timedelta(days=1)
logging.info("Downloading schedules for username [%s] in... | python | def get_file_object(username, password, utc_start=None, utc_stop=None):
"""Make the connection. Return a file-like object."""
if not utc_start:
utc_start = datetime.now()
if not utc_stop:
utc_stop = utc_start + timedelta(days=1)
logging.info("Downloading schedules for username [%s] in... | [
"def",
"get_file_object",
"(",
"username",
",",
"password",
",",
"utc_start",
"=",
"None",
",",
"utc_stop",
"=",
"None",
")",
":",
"if",
"not",
"utc_start",
":",
"utc_start",
"=",
"datetime",
".",
"now",
"(",
")",
"if",
"not",
"utc_stop",
":",
"utc_stop"... | Make the connection. Return a file-like object. | [
"Make",
"the",
"connection",
".",
"Return",
"a",
"file",
"-",
"like",
"object",
"."
] | e5aae988fad90217f72db45f93bf69839f4d75e7 | https://github.com/dsoprea/PySchedules/blob/e5aae988fad90217f72db45f93bf69839f4d75e7/pyschedules/retrieve.py#L51-L81 | train | Make the connection to the Schedules Direct service and return a file - like object. |
dsoprea/PySchedules | pyschedules/retrieve.py | process_file_object | def process_file_object(file_obj, importer, progress):
"""Parse the data using the connected file-like object."""
logging.info("Processing schedule data.")
try:
handler = XmlCallbacks(importer, progress)
parser = sax.make_parser()
parser.setContentHandler(handler)
parser.se... | python | def process_file_object(file_obj, importer, progress):
"""Parse the data using the connected file-like object."""
logging.info("Processing schedule data.")
try:
handler = XmlCallbacks(importer, progress)
parser = sax.make_parser()
parser.setContentHandler(handler)
parser.se... | [
"def",
"process_file_object",
"(",
"file_obj",
",",
"importer",
",",
"progress",
")",
":",
"logging",
".",
"info",
"(",
"\"Processing schedule data.\"",
")",
"try",
":",
"handler",
"=",
"XmlCallbacks",
"(",
"importer",
",",
"progress",
")",
"parser",
"=",
"sax... | Parse the data using the connected file-like object. | [
"Parse",
"the",
"data",
"using",
"the",
"connected",
"file",
"-",
"like",
"object",
"."
] | e5aae988fad90217f72db45f93bf69839f4d75e7 | https://github.com/dsoprea/PySchedules/blob/e5aae988fad90217f72db45f93bf69839f4d75e7/pyschedules/retrieve.py#L83-L98 | train | Parse the data using the connected file - like object. |
dsoprea/PySchedules | pyschedules/retrieve.py | parse_schedules | def parse_schedules(username, password, importer, progress, utc_start=None,
utc_stop=None):
"""A utility function to marry the connecting and reading functions."""
file_obj = get_file_object(username, password, utc_start, utc_stop)
process_file_object(file_obj, importer, progress) | python | def parse_schedules(username, password, importer, progress, utc_start=None,
utc_stop=None):
"""A utility function to marry the connecting and reading functions."""
file_obj = get_file_object(username, password, utc_start, utc_stop)
process_file_object(file_obj, importer, progress) | [
"def",
"parse_schedules",
"(",
"username",
",",
"password",
",",
"importer",
",",
"progress",
",",
"utc_start",
"=",
"None",
",",
"utc_stop",
"=",
"None",
")",
":",
"file_obj",
"=",
"get_file_object",
"(",
"username",
",",
"password",
",",
"utc_start",
",",
... | A utility function to marry the connecting and reading functions. | [
"A",
"utility",
"function",
"to",
"marry",
"the",
"connecting",
"and",
"reading",
"functions",
"."
] | e5aae988fad90217f72db45f93bf69839f4d75e7 | https://github.com/dsoprea/PySchedules/blob/e5aae988fad90217f72db45f93bf69839f4d75e7/pyschedules/retrieve.py#L100-L105 | train | A utility function to marry the connecting and reading functions. |
tamasgal/km3pipe | km3pipe/utils/km3h5concat.py | km3h5concat | def km3h5concat(input_files, output_file, n_events=None, **kwargs):
"""Concatenate KM3HDF5 files via pipeline."""
from km3pipe import Pipeline # noqa
from km3pipe.io import HDF5Pump, HDF5Sink # noqa
pipe = Pipeline()
pipe.attach(HDF5Pump, filenames=input_files, **kwargs)
pipe.attach(Statu... | python | def km3h5concat(input_files, output_file, n_events=None, **kwargs):
"""Concatenate KM3HDF5 files via pipeline."""
from km3pipe import Pipeline # noqa
from km3pipe.io import HDF5Pump, HDF5Sink # noqa
pipe = Pipeline()
pipe.attach(HDF5Pump, filenames=input_files, **kwargs)
pipe.attach(Statu... | [
"def",
"km3h5concat",
"(",
"input_files",
",",
"output_file",
",",
"n_events",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
"km3pipe",
"import",
"Pipeline",
"# noqa",
"from",
"km3pipe",
".",
"io",
"import",
"HDF5Pump",
",",
"HDF5Sink",
"# noqa",
... | Concatenate KM3HDF5 files via pipeline. | [
"Concatenate",
"KM3HDF5",
"files",
"via",
"pipeline",
"."
] | 7a9b59ac899a28775b5bdc5d391d9a5340d08040 | https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/utils/km3h5concat.py#L32-L41 | train | Concatenate KM3HDF5 files via pipeline. |
IRC-SPHERE/HyperStream | hyperstream/utils/time_utils.py | construct_experiment_id | def construct_experiment_id(time_interval):
"""
Construct an experiment id from a time interval
:return: The experiment id
:type time_interval: TimeInterval
:rtype: str
"""
# Construct id based on unix epoch timestamps
epoch = udatetime.utcfromtimestamp(0).replace(tzinfo=UTC)
start =... | python | def construct_experiment_id(time_interval):
"""
Construct an experiment id from a time interval
:return: The experiment id
:type time_interval: TimeInterval
:rtype: str
"""
# Construct id based on unix epoch timestamps
epoch = udatetime.utcfromtimestamp(0).replace(tzinfo=UTC)
start =... | [
"def",
"construct_experiment_id",
"(",
"time_interval",
")",
":",
"# Construct id based on unix epoch timestamps",
"epoch",
"=",
"udatetime",
".",
"utcfromtimestamp",
"(",
"0",
")",
".",
"replace",
"(",
"tzinfo",
"=",
"UTC",
")",
"start",
"=",
"int",
"(",
"(",
"... | Construct an experiment id from a time interval
:return: The experiment id
:type time_interval: TimeInterval
:rtype: str | [
"Construct",
"an",
"experiment",
"id",
"from",
"a",
"time",
"interval",
":",
"return",
":",
"The",
"experiment",
"id",
":",
"type",
"time_interval",
":",
"TimeInterval",
":",
"rtype",
":",
"str"
] | 98478f4d31ed938f4aa7c958ed0d4c3ffcb2e780 | https://github.com/IRC-SPHERE/HyperStream/blob/98478f4d31ed938f4aa7c958ed0d4c3ffcb2e780/hyperstream/utils/time_utils.py#L76-L87 | train | Construct an experiment id from a time interval |
IRC-SPHERE/HyperStream | hyperstream/utils/time_utils.py | reconstruct_interval | def reconstruct_interval(experiment_id):
"""
Reverse the construct_experiment_id operation
:param experiment_id: The experiment id
:return: time interval
"""
start, end = map(lambda x: udatetime.utcfromtimestamp(x / 1000.0), map(float, experiment_id.split("-")))
from ..time_interval import T... | python | def reconstruct_interval(experiment_id):
"""
Reverse the construct_experiment_id operation
:param experiment_id: The experiment id
:return: time interval
"""
start, end = map(lambda x: udatetime.utcfromtimestamp(x / 1000.0), map(float, experiment_id.split("-")))
from ..time_interval import T... | [
"def",
"reconstruct_interval",
"(",
"experiment_id",
")",
":",
"start",
",",
"end",
"=",
"map",
"(",
"lambda",
"x",
":",
"udatetime",
".",
"utcfromtimestamp",
"(",
"x",
"/",
"1000.0",
")",
",",
"map",
"(",
"float",
",",
"experiment_id",
".",
"split",
"("... | Reverse the construct_experiment_id operation
:param experiment_id: The experiment id
:return: time interval | [
"Reverse",
"the",
"construct_experiment_id",
"operation",
":",
"param",
"experiment_id",
":",
"The",
"experiment",
"id",
":",
"return",
":",
"time",
"interval"
] | 98478f4d31ed938f4aa7c958ed0d4c3ffcb2e780 | https://github.com/IRC-SPHERE/HyperStream/blob/98478f4d31ed938f4aa7c958ed0d4c3ffcb2e780/hyperstream/utils/time_utils.py#L90-L98 | train | Reconstructs the interval from the given experiment id. |
IRC-SPHERE/HyperStream | hyperstream/utils/time_utils.py | json_serial | def json_serial(obj):
"""JSON serializer for objects not serializable by default json code"""
if isinstance(obj, (datetime, date)):
serial = obj.isoformat()
return serial
from ..time_interval import TimeInterval, TimeIntervals
if isinstance(obj, (TimeInterval, TimeIntervals)):
... | python | def json_serial(obj):
"""JSON serializer for objects not serializable by default json code"""
if isinstance(obj, (datetime, date)):
serial = obj.isoformat()
return serial
from ..time_interval import TimeInterval, TimeIntervals
if isinstance(obj, (TimeInterval, TimeIntervals)):
... | [
"def",
"json_serial",
"(",
"obj",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"(",
"datetime",
",",
"date",
")",
")",
":",
"serial",
"=",
"obj",
".",
"isoformat",
"(",
")",
"return",
"serial",
"from",
".",
".",
"time_interval",
"import",
"TimeInterv... | JSON serializer for objects not serializable by default json code | [
"JSON",
"serializer",
"for",
"objects",
"not",
"serializable",
"by",
"default",
"json",
"code"
] | 98478f4d31ed938f4aa7c958ed0d4c3ffcb2e780 | https://github.com/IRC-SPHERE/HyperStream/blob/98478f4d31ed938f4aa7c958ed0d4c3ffcb2e780/hyperstream/utils/time_utils.py#L105-L124 | train | JSON serializer for objects not serializable by default json code |
IRC-SPHERE/HyperStream | hyperstream/tools/aggregate_plate/2016-11-11_v1.0.0.py | AggregatePlate.mapper | def mapper(self, meta_data, instance):
"""
Pull out the meta data plate value and put it into the instance value
:param meta_data: the original meta data
:param instance: the original instance
:return: the modified instance
"""
d = dict(meta_data)
v = d.po... | python | def mapper(self, meta_data, instance):
"""
Pull out the meta data plate value and put it into the instance value
:param meta_data: the original meta data
:param instance: the original instance
:return: the modified instance
"""
d = dict(meta_data)
v = d.po... | [
"def",
"mapper",
"(",
"self",
",",
"meta_data",
",",
"instance",
")",
":",
"d",
"=",
"dict",
"(",
"meta_data",
")",
"v",
"=",
"d",
".",
"pop",
"(",
"self",
".",
"aggregation_meta_data",
")",
"instance",
"=",
"deepcopy",
"(",
"instance",
")",
"instance"... | Pull out the meta data plate value and put it into the instance value
:param meta_data: the original meta data
:param instance: the original instance
:return: the modified instance | [
"Pull",
"out",
"the",
"meta",
"data",
"plate",
"value",
"and",
"put",
"it",
"into",
"the",
"instance",
"value",
":",
"param",
"meta_data",
":",
"the",
"original",
"meta",
"data",
":",
"param",
"instance",
":",
"the",
"original",
"instance",
":",
"return",
... | 98478f4d31ed938f4aa7c958ed0d4c3ffcb2e780 | https://github.com/IRC-SPHERE/HyperStream/blob/98478f4d31ed938f4aa7c958ed0d4c3ffcb2e780/hyperstream/tools/aggregate_plate/2016-11-11_v1.0.0.py#L43-L54 | train | This method is used to map the meta data into the instance value |
tamasgal/km3pipe | km3pipe/utils/streamds.py | get_data | def get_data(stream, parameters, fmt):
"""Retrieve data for given stream and parameters, or None if not found"""
sds = kp.db.StreamDS()
if stream not in sds.streams:
log.error("Stream '{}' not found in the database.".format(stream))
return
params = {}
if parameters:
for param... | python | def get_data(stream, parameters, fmt):
"""Retrieve data for given stream and parameters, or None if not found"""
sds = kp.db.StreamDS()
if stream not in sds.streams:
log.error("Stream '{}' not found in the database.".format(stream))
return
params = {}
if parameters:
for param... | [
"def",
"get_data",
"(",
"stream",
",",
"parameters",
",",
"fmt",
")",
":",
"sds",
"=",
"kp",
".",
"db",
".",
"StreamDS",
"(",
")",
"if",
"stream",
"not",
"in",
"sds",
".",
"streams",
":",
"log",
".",
"error",
"(",
"\"Stream '{}' not found in the database... | Retrieve data for given stream and parameters, or None if not found | [
"Retrieve",
"data",
"for",
"given",
"stream",
"and",
"parameters",
"or",
"None",
"if",
"not",
"found"
] | 7a9b59ac899a28775b5bdc5d391d9a5340d08040 | https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/utils/streamds.py#L56-L80 | train | Retrieve data for given stream and parameters. |
tamasgal/km3pipe | km3pipe/utils/streamds.py | available_streams | def available_streams():
"""Show a short list of available streams."""
sds = kp.db.StreamDS()
print("Available streams: ")
print(', '.join(sorted(sds.streams))) | python | def available_streams():
"""Show a short list of available streams."""
sds = kp.db.StreamDS()
print("Available streams: ")
print(', '.join(sorted(sds.streams))) | [
"def",
"available_streams",
"(",
")",
":",
"sds",
"=",
"kp",
".",
"db",
".",
"StreamDS",
"(",
")",
"print",
"(",
"\"Available streams: \"",
")",
"print",
"(",
"', '",
".",
"join",
"(",
"sorted",
"(",
"sds",
".",
"streams",
")",
")",
")"
] | Show a short list of available streams. | [
"Show",
"a",
"short",
"list",
"of",
"available",
"streams",
"."
] | 7a9b59ac899a28775b5bdc5d391d9a5340d08040 | https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/utils/streamds.py#L83-L87 | train | Show a short list of available streams. |
tamasgal/km3pipe | km3pipe/utils/streamds.py | upload_runsummary | def upload_runsummary(csv_filename, dryrun=False):
"""Reads the CSV file and uploads its contents to the runsummary table"""
print("Checking '{}' for consistency.".format(csv_filename))
if not os.path.exists(csv_filename):
log.critical("{} -> file not found.".format(csv_filename))
return
... | python | def upload_runsummary(csv_filename, dryrun=False):
"""Reads the CSV file and uploads its contents to the runsummary table"""
print("Checking '{}' for consistency.".format(csv_filename))
if not os.path.exists(csv_filename):
log.critical("{} -> file not found.".format(csv_filename))
return
... | [
"def",
"upload_runsummary",
"(",
"csv_filename",
",",
"dryrun",
"=",
"False",
")",
":",
"print",
"(",
"\"Checking '{}' for consistency.\"",
".",
"format",
"(",
"csv_filename",
")",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"csv_filename",
")",
... | Reads the CSV file and uploads its contents to the runsummary table | [
"Reads",
"the",
"CSV",
"file",
"and",
"uploads",
"its",
"contents",
"to",
"the",
"runsummary",
"table"
] | 7a9b59ac899a28775b5bdc5d391d9a5340d08040 | https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/utils/streamds.py#L90-L162 | train | Reads the CSV file and uploads its contents to the runsummary table. |
tamasgal/km3pipe | km3pipe/utils/streamds.py | convert_runsummary_to_json | def convert_runsummary_to_json(
df, comment='Uploaded via km3pipe.StreamDS', prefix='TEST_'
):
"""Convert a Pandas DataFrame with runsummary to JSON for DB upload"""
data_field = []
comment += ", by {}".format(getpass.getuser())
for det_id, det_data in df.groupby('det_id'):
runs_field = ... | python | def convert_runsummary_to_json(
df, comment='Uploaded via km3pipe.StreamDS', prefix='TEST_'
):
"""Convert a Pandas DataFrame with runsummary to JSON for DB upload"""
data_field = []
comment += ", by {}".format(getpass.getuser())
for det_id, det_data in df.groupby('det_id'):
runs_field = ... | [
"def",
"convert_runsummary_to_json",
"(",
"df",
",",
"comment",
"=",
"'Uploaded via km3pipe.StreamDS'",
",",
"prefix",
"=",
"'TEST_'",
")",
":",
"data_field",
"=",
"[",
"]",
"comment",
"+=",
"\", by {}\"",
".",
"format",
"(",
"getpass",
".",
"getuser",
"(",
")... | Convert a Pandas DataFrame with runsummary to JSON for DB upload | [
"Convert",
"a",
"Pandas",
"DataFrame",
"with",
"runsummary",
"to",
"JSON",
"for",
"DB",
"upload"
] | 7a9b59ac899a28775b5bdc5d391d9a5340d08040 | https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/utils/streamds.py#L165-L203 | train | Convert a Pandas DataFrame with runsummary to JSON for DB upload |
PrefPy/prefpy | prefpy/mechanismMcmcSampleGenerator.py | MechanismMcmcSampleGeneratorMallows.calcAcceptanceRatio | def calcAcceptanceRatio(self, V, W):
"""
Given a order vector V and a proposed order vector W, calculate the acceptance ratio for
changing to W when using MCMC.
ivar: dict<int,<dict,<int,int>>> wmg: A two-dimensional dictionary that associates integer
representations of eac... | python | def calcAcceptanceRatio(self, V, W):
"""
Given a order vector V and a proposed order vector W, calculate the acceptance ratio for
changing to W when using MCMC.
ivar: dict<int,<dict,<int,int>>> wmg: A two-dimensional dictionary that associates integer
representations of eac... | [
"def",
"calcAcceptanceRatio",
"(",
"self",
",",
"V",
",",
"W",
")",
":",
"acceptanceRatio",
"=",
"1.0",
"for",
"comb",
"in",
"itertools",
".",
"combinations",
"(",
"V",
",",
"2",
")",
":",
"#Check if comb[0] is ranked before comb[1] in V and W",
"vIOverJ",
"=",
... | Given a order vector V and a proposed order vector W, calculate the acceptance ratio for
changing to W when using MCMC.
ivar: dict<int,<dict,<int,int>>> wmg: A two-dimensional dictionary that associates integer
representations of each pair of candidates, cand1 and cand2, with the number of... | [
"Given",
"a",
"order",
"vector",
"V",
"and",
"a",
"proposed",
"order",
"vector",
"W",
"calculate",
"the",
"acceptance",
"ratio",
"for",
"changing",
"to",
"W",
"when",
"using",
"MCMC",
"."
] | f395ba3782f05684fa5de0cece387a6da9391d02 | https://github.com/PrefPy/prefpy/blob/f395ba3782f05684fa5de0cece387a6da9391d02/prefpy/mechanismMcmcSampleGenerator.py#L34-L62 | train | Calculates the acceptance ratio for a given order vector V and a proposed order vector W. |
PrefPy/prefpy | prefpy/mechanismMcmcSampleGenerator.py | MechanismMcmcSampleGeneratorMallowsAdjacentPairwiseFlip.getNextSample | def getNextSample(self, V):
"""
Generate the next sample by randomly flipping two adjacent candidates.
:ivar list<int> V: Contains integer representations of each candidate in order of their
ranking in a vote, from first to last. This is the current sample.
"""
# Se... | python | def getNextSample(self, V):
"""
Generate the next sample by randomly flipping two adjacent candidates.
:ivar list<int> V: Contains integer representations of each candidate in order of their
ranking in a vote, from first to last. This is the current sample.
"""
# Se... | [
"def",
"getNextSample",
"(",
"self",
",",
"V",
")",
":",
"# Select a random alternative in V to switch with its adacent alternatives.",
"randPos",
"=",
"random",
".",
"randint",
"(",
"0",
",",
"len",
"(",
"V",
")",
"-",
"2",
")",
"W",
"=",
"copy",
".",
"deepco... | Generate the next sample by randomly flipping two adjacent candidates.
:ivar list<int> V: Contains integer representations of each candidate in order of their
ranking in a vote, from first to last. This is the current sample. | [
"Generate",
"the",
"next",
"sample",
"by",
"randomly",
"flipping",
"two",
"adjacent",
"candidates",
"."
] | f395ba3782f05684fa5de0cece387a6da9391d02 | https://github.com/PrefPy/prefpy/blob/f395ba3782f05684fa5de0cece387a6da9391d02/prefpy/mechanismMcmcSampleGenerator.py#L66-L89 | train | Generate the next sample by randomly flipping two adjacent candidates and selecting a random alternative in V. |
PrefPy/prefpy | prefpy/mechanismMcmcSampleGenerator.py | MechanismMcmcSampleGeneratorMallowsRandShuffle.getNextSample | def getNextSample(self, V):
"""
Generate the next sample by randomly shuffling candidates.
:ivar list<int> V: Contains integer representations of each candidate in order of their
ranking in a vote, from first to last. This is the current sample.
"""
positions = rang... | python | def getNextSample(self, V):
"""
Generate the next sample by randomly shuffling candidates.
:ivar list<int> V: Contains integer representations of each candidate in order of their
ranking in a vote, from first to last. This is the current sample.
"""
positions = rang... | [
"def",
"getNextSample",
"(",
"self",
",",
"V",
")",
":",
"positions",
"=",
"range",
"(",
"0",
",",
"len",
"(",
"self",
".",
"wmg",
")",
")",
"randPoss",
"=",
"random",
".",
"sample",
"(",
"positions",
",",
"self",
".",
"shuffleSize",
")",
"flipSet",
... | Generate the next sample by randomly shuffling candidates.
:ivar list<int> V: Contains integer representations of each candidate in order of their
ranking in a vote, from first to last. This is the current sample. | [
"Generate",
"the",
"next",
"sample",
"by",
"randomly",
"shuffling",
"candidates",
"."
] | f395ba3782f05684fa5de0cece387a6da9391d02 | https://github.com/PrefPy/prefpy/blob/f395ba3782f05684fa5de0cece387a6da9391d02/prefpy/mechanismMcmcSampleGenerator.py#L98-L121 | train | Generate the next sample by randomly shuffling candidates. |
PrefPy/prefpy | prefpy/mechanismMcmcSampleGenerator.py | MechanismMcmcSampleGeneratorMallowsJumpingDistribution.getNextSample | def getNextSample(self, V):
"""
We generate a new ranking based on a Mallows-based jumping distribution. The algorithm is
described in "Bayesian Ordinal Peer Grading" by Raman and Joachims.
:ivar list<int> V: Contains integer representations of each candidate in order of their
... | python | def getNextSample(self, V):
"""
We generate a new ranking based on a Mallows-based jumping distribution. The algorithm is
described in "Bayesian Ordinal Peer Grading" by Raman and Joachims.
:ivar list<int> V: Contains integer representations of each candidate in order of their
... | [
"def",
"getNextSample",
"(",
"self",
",",
"V",
")",
":",
"phi",
"=",
"self",
".",
"phi",
"wmg",
"=",
"self",
".",
"wmg",
"W",
"=",
"[",
"]",
"W",
".",
"append",
"(",
"V",
"[",
"0",
"]",
")",
"for",
"j",
"in",
"range",
"(",
"2",
",",
"len",
... | We generate a new ranking based on a Mallows-based jumping distribution. The algorithm is
described in "Bayesian Ordinal Peer Grading" by Raman and Joachims.
:ivar list<int> V: Contains integer representations of each candidate in order of their
ranking in a vote, from first to last. | [
"We",
"generate",
"a",
"new",
"ranking",
"based",
"on",
"a",
"Mallows",
"-",
"based",
"jumping",
"distribution",
".",
"The",
"algorithm",
"is",
"described",
"in",
"Bayesian",
"Ordinal",
"Peer",
"Grading",
"by",
"Raman",
"and",
"Joachims",
"."
] | f395ba3782f05684fa5de0cece387a6da9391d02 | https://github.com/PrefPy/prefpy/blob/f395ba3782f05684fa5de0cece387a6da9391d02/prefpy/mechanismMcmcSampleGenerator.py#L125-L157 | train | This method generates a new ranking based on a Mallows - based jumping distribution. |
PrefPy/prefpy | prefpy/mechanismMcmcSampleGenerator.py | MechanismMcmcSampleGeneratorMallowsPlakettLuce.getNextSample | def getNextSample(self, V):
"""
Given a ranking over the candidates, generate a new ranking by assigning each candidate at
position i a Plakett-Luce weight of phi^i and draw a new ranking.
:ivar list<int> V: Contains integer representations of each candidate in order of their
... | python | def getNextSample(self, V):
"""
Given a ranking over the candidates, generate a new ranking by assigning each candidate at
position i a Plakett-Luce weight of phi^i and draw a new ranking.
:ivar list<int> V: Contains integer representations of each candidate in order of their
... | [
"def",
"getNextSample",
"(",
"self",
",",
"V",
")",
":",
"W",
",",
"WProb",
"=",
"self",
".",
"drawRankingPlakettLuce",
"(",
"V",
")",
"VProb",
"=",
"self",
".",
"calcProbOfVFromW",
"(",
"V",
",",
"W",
")",
"acceptanceRatio",
"=",
"self",
".",
"calcAcc... | Given a ranking over the candidates, generate a new ranking by assigning each candidate at
position i a Plakett-Luce weight of phi^i and draw a new ranking.
:ivar list<int> V: Contains integer representations of each candidate in order of their
ranking in a vote, from first to last. | [
"Given",
"a",
"ranking",
"over",
"the",
"candidates",
"generate",
"a",
"new",
"ranking",
"by",
"assigning",
"each",
"candidate",
"at",
"position",
"i",
"a",
"Plakett",
"-",
"Luce",
"weight",
"of",
"phi^i",
"and",
"draw",
"a",
"new",
"ranking",
"."
] | f395ba3782f05684fa5de0cece387a6da9391d02 | https://github.com/PrefPy/prefpy/blob/f395ba3782f05684fa5de0cece387a6da9391d02/prefpy/mechanismMcmcSampleGenerator.py#L191-L206 | train | Given a ranking over the candidates generate a new ranking by assigning each candidate at
position i a Plakett - Luce weight of phi^i draw a new ranking. |
PrefPy/prefpy | prefpy/mechanismMcmcSampleGenerator.py | MechanismMcmcSampleGeneratorMallowsPlakettLuce.calcDrawingProbs | def calcDrawingProbs(self):
"""
Returns a vector that contains the probabily of an item being from each position. We say
that every item in a order vector is drawn with weight phi^i where i is its position.
"""
wmg = self.wmg
phi = self.phi
# We say the weight o... | python | def calcDrawingProbs(self):
"""
Returns a vector that contains the probabily of an item being from each position. We say
that every item in a order vector is drawn with weight phi^i where i is its position.
"""
wmg = self.wmg
phi = self.phi
# We say the weight o... | [
"def",
"calcDrawingProbs",
"(",
"self",
")",
":",
"wmg",
"=",
"self",
".",
"wmg",
"phi",
"=",
"self",
".",
"phi",
"# We say the weight of the candidate in position i is phi^i.",
"weights",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"len",
"(",
... | Returns a vector that contains the probabily of an item being from each position. We say
that every item in a order vector is drawn with weight phi^i where i is its position. | [
"Returns",
"a",
"vector",
"that",
"contains",
"the",
"probabily",
"of",
"an",
"item",
"being",
"from",
"each",
"position",
".",
"We",
"say",
"that",
"every",
"item",
"in",
"a",
"order",
"vector",
"is",
"drawn",
"with",
"weight",
"phi^i",
"where",
"i",
"i... | f395ba3782f05684fa5de0cece387a6da9391d02 | https://github.com/PrefPy/prefpy/blob/f395ba3782f05684fa5de0cece387a6da9391d02/prefpy/mechanismMcmcSampleGenerator.py#L208-L227 | train | Calculates the probabilty of an item being from each position. |
PrefPy/prefpy | prefpy/mechanismMcmcSampleGenerator.py | MechanismMcmcSampleGeneratorMallowsPlakettLuce.drawRankingPlakettLuce | def drawRankingPlakettLuce(self, rankList):
"""
Given an order vector over the candidates, draw candidates to generate a new order vector.
:ivar list<int> rankList: Contains integer representations of each candidate in order of their
rank in a vote, from first to last.
"""
... | python | def drawRankingPlakettLuce(self, rankList):
"""
Given an order vector over the candidates, draw candidates to generate a new order vector.
:ivar list<int> rankList: Contains integer representations of each candidate in order of their
rank in a vote, from first to last.
"""
... | [
"def",
"drawRankingPlakettLuce",
"(",
"self",
",",
"rankList",
")",
":",
"probs",
"=",
"self",
".",
"plakettLuceProbs",
"numCands",
"=",
"len",
"(",
"rankList",
")",
"newRanking",
"=",
"[",
"]",
"remainingCands",
"=",
"copy",
".",
"deepcopy",
"(",
"rankList"... | Given an order vector over the candidates, draw candidates to generate a new order vector.
:ivar list<int> rankList: Contains integer representations of each candidate in order of their
rank in a vote, from first to last. | [
"Given",
"an",
"order",
"vector",
"over",
"the",
"candidates",
"draw",
"candidates",
"to",
"generate",
"a",
"new",
"order",
"vector",
"."
] | f395ba3782f05684fa5de0cece387a6da9391d02 | https://github.com/PrefPy/prefpy/blob/f395ba3782f05684fa5de0cece387a6da9391d02/prefpy/mechanismMcmcSampleGenerator.py#L229-L263 | train | Given an order vector over the candidates draw candidates to generate a new order vector. |
PrefPy/prefpy | prefpy/mechanismMcmcSampleGenerator.py | MechanismMcmcSampleGeneratorMallowsPlakettLuce.calcProbOfVFromW | def calcProbOfVFromW(self, V, W):
"""
Given a order vector V and an order vector W, calculate the probability that we generate
V as our next sample if our current sample was W.
:ivar list<int> V: Contains integer representations of each candidate in order of their
ranking in... | python | def calcProbOfVFromW(self, V, W):
"""
Given a order vector V and an order vector W, calculate the probability that we generate
V as our next sample if our current sample was W.
:ivar list<int> V: Contains integer representations of each candidate in order of their
ranking in... | [
"def",
"calcProbOfVFromW",
"(",
"self",
",",
"V",
",",
"W",
")",
":",
"weights",
"=",
"range",
"(",
"0",
",",
"len",
"(",
"V",
")",
")",
"i",
"=",
"0",
"for",
"alt",
"in",
"W",
":",
"weights",
"[",
"alt",
"-",
"1",
"]",
"=",
"self",
".",
"p... | Given a order vector V and an order vector W, calculate the probability that we generate
V as our next sample if our current sample was W.
:ivar list<int> V: Contains integer representations of each candidate in order of their
ranking in a vote, from first to last.
:ivar list<int> W... | [
"Given",
"a",
"order",
"vector",
"V",
"and",
"an",
"order",
"vector",
"W",
"calculate",
"the",
"probability",
"that",
"we",
"generate",
"V",
"as",
"our",
"next",
"sample",
"if",
"our",
"current",
"sample",
"was",
"W",
"."
] | f395ba3782f05684fa5de0cece387a6da9391d02 | https://github.com/PrefPy/prefpy/blob/f395ba3782f05684fa5de0cece387a6da9391d02/prefpy/mechanismMcmcSampleGenerator.py#L265-L289 | train | Calculate the probability that we draw V as our next sample if our current sample was W. |
PrefPy/prefpy | prefpy/mechanismMcmcSampleGenerator.py | MechanismMcmcSampleGeneratorCondorcet.getNextSample | def getNextSample(self, V):
"""
Generate the next sample for the condorcet model. This algorithm is described in "Computing
Optimal Bayesian Decisions for Rank Aggregation via MCMC Sampling," and is adapted from
code written by Lirong Xia.
:ivar list<list<int> V: A two-... | python | def getNextSample(self, V):
"""
Generate the next sample for the condorcet model. This algorithm is described in "Computing
Optimal Bayesian Decisions for Rank Aggregation via MCMC Sampling," and is adapted from
code written by Lirong Xia.
:ivar list<list<int> V: A two-... | [
"def",
"getNextSample",
"(",
"self",
",",
"V",
")",
":",
"cands",
"=",
"range",
"(",
"len",
"(",
"self",
".",
"wmg",
")",
")",
"W",
"=",
"copy",
".",
"deepcopy",
"(",
"V",
")",
"allPairs",
"=",
"itertools",
".",
"combinations",
"(",
"cands",
",",
... | Generate the next sample for the condorcet model. This algorithm is described in "Computing
Optimal Bayesian Decisions for Rank Aggregation via MCMC Sampling," and is adapted from
code written by Lirong Xia.
:ivar list<list<int> V: A two-dimensional list that for every pair of candidat... | [
"Generate",
"the",
"next",
"sample",
"for",
"the",
"condorcet",
"model",
".",
"This",
"algorithm",
"is",
"described",
"in",
"Computing",
"Optimal",
"Bayesian",
"Decisions",
"for",
"Rank",
"Aggregation",
"via",
"MCMC",
"Sampling",
"and",
"is",
"adapted",
"from",
... | f395ba3782f05684fa5de0cece387a6da9391d02 | https://github.com/PrefPy/prefpy/blob/f395ba3782f05684fa5de0cece387a6da9391d02/prefpy/mechanismMcmcSampleGenerator.py#L293-L321 | train | Generate the next sample for the condorcet model. |
tamasgal/km3pipe | km3pipe/io/root.py | get_hist | def get_hist(rfile, histname, get_overflow=False):
"""Read a 1D Histogram."""
import root_numpy as rnp
rfile = open_rfile(rfile)
hist = rfile[histname]
xlims = np.array(list(hist.xedges()))
bin_values = rnp.hist2array(hist, include_overflow=get_overflow)
rfile.close()
return bin_values,... | python | def get_hist(rfile, histname, get_overflow=False):
"""Read a 1D Histogram."""
import root_numpy as rnp
rfile = open_rfile(rfile)
hist = rfile[histname]
xlims = np.array(list(hist.xedges()))
bin_values = rnp.hist2array(hist, include_overflow=get_overflow)
rfile.close()
return bin_values,... | [
"def",
"get_hist",
"(",
"rfile",
",",
"histname",
",",
"get_overflow",
"=",
"False",
")",
":",
"import",
"root_numpy",
"as",
"rnp",
"rfile",
"=",
"open_rfile",
"(",
"rfile",
")",
"hist",
"=",
"rfile",
"[",
"histname",
"]",
"xlims",
"=",
"np",
".",
"arr... | Read a 1D Histogram. | [
"Read",
"a",
"1D",
"Histogram",
"."
] | 7a9b59ac899a28775b5bdc5d391d9a5340d08040 | https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/io/root.py#L31-L40 | train | Read a 1D Histogram. |
tamasgal/km3pipe | km3pipe/io/root.py | interpol_hist2d | def interpol_hist2d(h2d, oversamp_factor=10):
"""Sample the interpolator of a root 2d hist.
Root's hist2d has a weird internal interpolation routine,
also using neighbouring bins.
"""
from rootpy import ROOTError
xlim = h2d.bins(axis=0)
ylim = h2d.bins(axis=1)
xn = h2d.nbins(0)
yn ... | python | def interpol_hist2d(h2d, oversamp_factor=10):
"""Sample the interpolator of a root 2d hist.
Root's hist2d has a weird internal interpolation routine,
also using neighbouring bins.
"""
from rootpy import ROOTError
xlim = h2d.bins(axis=0)
ylim = h2d.bins(axis=1)
xn = h2d.nbins(0)
yn ... | [
"def",
"interpol_hist2d",
"(",
"h2d",
",",
"oversamp_factor",
"=",
"10",
")",
":",
"from",
"rootpy",
"import",
"ROOTError",
"xlim",
"=",
"h2d",
".",
"bins",
"(",
"axis",
"=",
"0",
")",
"ylim",
"=",
"h2d",
".",
"bins",
"(",
"axis",
"=",
"1",
")",
"x... | Sample the interpolator of a root 2d hist.
Root's hist2d has a weird internal interpolation routine,
also using neighbouring bins. | [
"Sample",
"the",
"interpolator",
"of",
"a",
"root",
"2d",
"hist",
"."
] | 7a9b59ac899a28775b5bdc5d391d9a5340d08040 | https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/io/root.py#L70-L91 | train | Sample the interpolator of a root 2d hist. |
cprogrammer1994/GLWindow | GLWindow/__init__.py | create_window | def create_window(size=None, samples=16, *, fullscreen=False, title=None, threaded=True) -> Window:
'''
Create the main window.
Args:
size (tuple): The width and height of the window.
samples (int): The number of samples.
Keyword Args:
fullscreen (bool):... | python | def create_window(size=None, samples=16, *, fullscreen=False, title=None, threaded=True) -> Window:
'''
Create the main window.
Args:
size (tuple): The width and height of the window.
samples (int): The number of samples.
Keyword Args:
fullscreen (bool):... | [
"def",
"create_window",
"(",
"size",
"=",
"None",
",",
"samples",
"=",
"16",
",",
"*",
",",
"fullscreen",
"=",
"False",
",",
"title",
"=",
"None",
",",
"threaded",
"=",
"True",
")",
"->",
"Window",
":",
"if",
"size",
"is",
"None",
":",
"width",
","... | Create the main window.
Args:
size (tuple): The width and height of the window.
samples (int): The number of samples.
Keyword Args:
fullscreen (bool): Fullscreen?
title (bool): The title of the window.
threaded (bool): Threaded?
Retu... | [
"Create",
"the",
"main",
"window",
"."
] | 521e18fcbc15e88d3c1f3547aa313c3a07386ee5 | https://github.com/cprogrammer1994/GLWindow/blob/521e18fcbc15e88d3c1f3547aa313c3a07386ee5/GLWindow/__init__.py#L307-L335 | train | Create the main window. |
cprogrammer1994/GLWindow | GLWindow/__init__.py | Window.clear | def clear(self, red=0.0, green=0.0, blue=0.0, alpha=0.0) -> None:
'''
Clear the window.
'''
self.wnd.clear(red, green, blue, alpha) | python | def clear(self, red=0.0, green=0.0, blue=0.0, alpha=0.0) -> None:
'''
Clear the window.
'''
self.wnd.clear(red, green, blue, alpha) | [
"def",
"clear",
"(",
"self",
",",
"red",
"=",
"0.0",
",",
"green",
"=",
"0.0",
",",
"blue",
"=",
"0.0",
",",
"alpha",
"=",
"0.0",
")",
"->",
"None",
":",
"self",
".",
"wnd",
".",
"clear",
"(",
"red",
",",
"green",
",",
"blue",
",",
"alpha",
"... | Clear the window. | [
"Clear",
"the",
"window",
"."
] | 521e18fcbc15e88d3c1f3547aa313c3a07386ee5 | https://github.com/cprogrammer1994/GLWindow/blob/521e18fcbc15e88d3c1f3547aa313c3a07386ee5/GLWindow/__init__.py#L59-L64 | train | Clear the color of the current color. |
cprogrammer1994/GLWindow | GLWindow/__init__.py | Window.windowed | def windowed(self, size) -> None:
'''
Set the window to windowed mode.
'''
width, height = size
self.wnd.windowed(width, height) | python | def windowed(self, size) -> None:
'''
Set the window to windowed mode.
'''
width, height = size
self.wnd.windowed(width, height) | [
"def",
"windowed",
"(",
"self",
",",
"size",
")",
"->",
"None",
":",
"width",
",",
"height",
"=",
"size",
"self",
".",
"wnd",
".",
"windowed",
"(",
"width",
",",
"height",
")"
] | Set the window to windowed mode. | [
"Set",
"the",
"window",
"to",
"windowed",
"mode",
"."
] | 521e18fcbc15e88d3c1f3547aa313c3a07386ee5 | https://github.com/cprogrammer1994/GLWindow/blob/521e18fcbc15e88d3c1f3547aa313c3a07386ee5/GLWindow/__init__.py#L73-L80 | train | Set the window to windowed mode. |
cprogrammer1994/GLWindow | GLWindow/__init__.py | Window.viewport | def viewport(self) -> Tuple[int, int, int, int]:
'''
tuple: The viewport of the window.
'''
return self.wnd.viewport | python | def viewport(self) -> Tuple[int, int, int, int]:
'''
tuple: The viewport of the window.
'''
return self.wnd.viewport | [
"def",
"viewport",
"(",
"self",
")",
"->",
"Tuple",
"[",
"int",
",",
"int",
",",
"int",
",",
"int",
"]",
":",
"return",
"self",
".",
"wnd",
".",
"viewport"
] | tuple: The viewport of the window. | [
"tuple",
":",
"The",
"viewport",
"of",
"the",
"window",
"."
] | 521e18fcbc15e88d3c1f3547aa313c3a07386ee5 | https://github.com/cprogrammer1994/GLWindow/blob/521e18fcbc15e88d3c1f3547aa313c3a07386ee5/GLWindow/__init__.py#L243-L248 | train | Returns the viewport of the window. |
developmentseed/sentinel-s3 | sentinel_s3/main.py | product_metadata | def product_metadata(product, dst_folder, counter=None, writers=[file_writer], geometry_check=None):
""" Extract metadata for a specific product """
if not counter:
counter = {
'products': 0,
'saved_tiles': 0,
'skipped_tiles': 0,
'skipped_tiles_paths': []... | python | def product_metadata(product, dst_folder, counter=None, writers=[file_writer], geometry_check=None):
""" Extract metadata for a specific product """
if not counter:
counter = {
'products': 0,
'saved_tiles': 0,
'skipped_tiles': 0,
'skipped_tiles_paths': []... | [
"def",
"product_metadata",
"(",
"product",
",",
"dst_folder",
",",
"counter",
"=",
"None",
",",
"writers",
"=",
"[",
"file_writer",
"]",
",",
"geometry_check",
"=",
"None",
")",
":",
"if",
"not",
"counter",
":",
"counter",
"=",
"{",
"'products'",
":",
"0... | Extract metadata for a specific product | [
"Extract",
"metadata",
"for",
"a",
"specific",
"product"
] | 02bf2f9cb6aff527e492b39518a54f0b4613ddda | https://github.com/developmentseed/sentinel-s3/blob/02bf2f9cb6aff527e492b39518a54f0b4613ddda/sentinel_s3/main.py#L58-L93 | train | Extract metadata for a specific product |
developmentseed/sentinel-s3 | sentinel_s3/main.py | daily_metadata | def daily_metadata(year, month, day, dst_folder, writers=[file_writer], geometry_check=None,
num_worker_threads=1):
""" Extra metadata for all products in a specific date """
threaded = False
counter = {
'products': 0,
'saved_tiles': 0,
'skipped_tiles': 0,
... | python | def daily_metadata(year, month, day, dst_folder, writers=[file_writer], geometry_check=None,
num_worker_threads=1):
""" Extra metadata for all products in a specific date """
threaded = False
counter = {
'products': 0,
'saved_tiles': 0,
'skipped_tiles': 0,
... | [
"def",
"daily_metadata",
"(",
"year",
",",
"month",
",",
"day",
",",
"dst_folder",
",",
"writers",
"=",
"[",
"file_writer",
"]",
",",
"geometry_check",
"=",
"None",
",",
"num_worker_threads",
"=",
"1",
")",
":",
"threaded",
"=",
"False",
"counter",
"=",
... | Extra metadata for all products in a specific date | [
"Extra",
"metadata",
"for",
"all",
"products",
"in",
"a",
"specific",
"date"
] | 02bf2f9cb6aff527e492b39518a54f0b4613ddda | https://github.com/developmentseed/sentinel-s3/blob/02bf2f9cb6aff527e492b39518a54f0b4613ddda/sentinel_s3/main.py#L102-L158 | train | Generate a single archive of all products in a specific date. |
developmentseed/sentinel-s3 | sentinel_s3/main.py | range_metadata | def range_metadata(start, end, dst_folder, num_worker_threads=0, writers=[file_writer], geometry_check=None):
""" Extra metadata for all products in a date range """
assert isinstance(start, date)
assert isinstance(end, date)
delta = end - start
dates = []
for i in range(delta.days + 1):
... | python | def range_metadata(start, end, dst_folder, num_worker_threads=0, writers=[file_writer], geometry_check=None):
""" Extra metadata for all products in a date range """
assert isinstance(start, date)
assert isinstance(end, date)
delta = end - start
dates = []
for i in range(delta.days + 1):
... | [
"def",
"range_metadata",
"(",
"start",
",",
"end",
",",
"dst_folder",
",",
"num_worker_threads",
"=",
"0",
",",
"writers",
"=",
"[",
"file_writer",
"]",
",",
"geometry_check",
"=",
"None",
")",
":",
"assert",
"isinstance",
"(",
"start",
",",
"date",
")",
... | Extra metadata for all products in a date range | [
"Extra",
"metadata",
"for",
"all",
"products",
"in",
"a",
"date",
"range"
] | 02bf2f9cb6aff527e492b39518a54f0b4613ddda | https://github.com/developmentseed/sentinel-s3/blob/02bf2f9cb6aff527e492b39518a54f0b4613ddda/sentinel_s3/main.py#L161-L194 | train | Get all metadata for all products in a date range. |
NaPs/Kolekto | kolekto/tmdb_proxy.py | get_on_tmdb | def get_on_tmdb(uri, **kwargs):
""" Get a resource on TMDB.
"""
kwargs['api_key'] = app.config['TMDB_API_KEY']
response = requests_session.get((TMDB_API_URL + uri).encode('utf8'), params=kwargs)
response.raise_for_status()
return json.loads(response.text) | python | def get_on_tmdb(uri, **kwargs):
""" Get a resource on TMDB.
"""
kwargs['api_key'] = app.config['TMDB_API_KEY']
response = requests_session.get((TMDB_API_URL + uri).encode('utf8'), params=kwargs)
response.raise_for_status()
return json.loads(response.text) | [
"def",
"get_on_tmdb",
"(",
"uri",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'api_key'",
"]",
"=",
"app",
".",
"config",
"[",
"'TMDB_API_KEY'",
"]",
"response",
"=",
"requests_session",
".",
"get",
"(",
"(",
"TMDB_API_URL",
"+",
"uri",
")",
"."... | Get a resource on TMDB. | [
"Get",
"a",
"resource",
"on",
"TMDB",
"."
] | 29c5469da8782780a06bf9a76c59414bb6fd8fe3 | https://github.com/NaPs/Kolekto/blob/29c5469da8782780a06bf9a76c59414bb6fd8fe3/kolekto/tmdb_proxy.py#L40-L46 | train | Get a resource on TMDB. |
NaPs/Kolekto | kolekto/tmdb_proxy.py | search | def search():
""" Search a movie on TMDB.
"""
redis_key = 's_%s' % request.args['query'].lower()
cached = redis_ro_conn.get(redis_key)
if cached:
return Response(cached)
else:
try:
found = get_on_tmdb(u'/search/movie', query=request.args['query'])
movies =... | python | def search():
""" Search a movie on TMDB.
"""
redis_key = 's_%s' % request.args['query'].lower()
cached = redis_ro_conn.get(redis_key)
if cached:
return Response(cached)
else:
try:
found = get_on_tmdb(u'/search/movie', query=request.args['query'])
movies =... | [
"def",
"search",
"(",
")",
":",
"redis_key",
"=",
"'s_%s'",
"%",
"request",
".",
"args",
"[",
"'query'",
"]",
".",
"lower",
"(",
")",
"cached",
"=",
"redis_ro_conn",
".",
"get",
"(",
"redis_key",
")",
"if",
"cached",
":",
"return",
"Response",
"(",
"... | Search a movie on TMDB. | [
"Search",
"a",
"movie",
"on",
"TMDB",
"."
] | 29c5469da8782780a06bf9a76c59414bb6fd8fe3 | https://github.com/NaPs/Kolekto/blob/29c5469da8782780a06bf9a76c59414bb6fd8fe3/kolekto/tmdb_proxy.py#L50-L72 | train | Search a movie on TMDB. |
NaPs/Kolekto | kolekto/tmdb_proxy.py | get_movie | def get_movie(tmdb_id):
""" Get informations about a movie using its tmdb id.
"""
redis_key = 'm_%s' % tmdb_id
cached = redis_ro_conn.get(redis_key)
if cached:
return Response(cached)
else:
try:
details = get_on_tmdb(u'/movie/%d' % tmdb_id)
cast = get_on_t... | python | def get_movie(tmdb_id):
""" Get informations about a movie using its tmdb id.
"""
redis_key = 'm_%s' % tmdb_id
cached = redis_ro_conn.get(redis_key)
if cached:
return Response(cached)
else:
try:
details = get_on_tmdb(u'/movie/%d' % tmdb_id)
cast = get_on_t... | [
"def",
"get_movie",
"(",
"tmdb_id",
")",
":",
"redis_key",
"=",
"'m_%s'",
"%",
"tmdb_id",
"cached",
"=",
"redis_ro_conn",
".",
"get",
"(",
"redis_key",
")",
"if",
"cached",
":",
"return",
"Response",
"(",
"cached",
")",
"else",
":",
"try",
":",
"details"... | Get informations about a movie using its tmdb id. | [
"Get",
"informations",
"about",
"a",
"movie",
"using",
"its",
"tmdb",
"id",
"."
] | 29c5469da8782780a06bf9a76c59414bb6fd8fe3 | https://github.com/NaPs/Kolekto/blob/29c5469da8782780a06bf9a76c59414bb6fd8fe3/kolekto/tmdb_proxy.py#L76-L107 | train | Get informations about a movie using its tmdb id. |
LeadPages/gcloud_requests | gcloud_requests/proxy.py | RequestsProxy._handle_response_error | def _handle_response_error(self, response, retries, **kwargs):
r"""Provides a way for each connection wrapper to handle error
responses.
Parameters:
response(Response): An instance of :class:`.requests.Response`.
retries(int): The number of times :meth:`.request` has been
... | python | def _handle_response_error(self, response, retries, **kwargs):
r"""Provides a way for each connection wrapper to handle error
responses.
Parameters:
response(Response): An instance of :class:`.requests.Response`.
retries(int): The number of times :meth:`.request` has been
... | [
"def",
"_handle_response_error",
"(",
"self",
",",
"response",
",",
"retries",
",",
"*",
"*",
"kwargs",
")",
":",
"error",
"=",
"self",
".",
"_convert_response_to_error",
"(",
"response",
")",
"if",
"error",
"is",
"None",
":",
"return",
"response",
"max_retr... | r"""Provides a way for each connection wrapper to handle error
responses.
Parameters:
response(Response): An instance of :class:`.requests.Response`.
retries(int): The number of times :meth:`.request` has been
called so far.
\**kwargs: The parameters with which... | [
"r",
"Provides",
"a",
"way",
"for",
"each",
"connection",
"wrapper",
"to",
"handle",
"error",
"responses",
"."
] | 8933363c4e9fa1e5ec0e90d683fca8ef8a949752 | https://github.com/LeadPages/gcloud_requests/blob/8933363c4e9fa1e5ec0e90d683fca8ef8a949752/gcloud_requests/proxy.py#L132-L162 | train | Handles the response of a request and returns a new Response object. |
LeadPages/gcloud_requests | gcloud_requests/proxy.py | RequestsProxy._convert_response_to_error | def _convert_response_to_error(self, response):
"""Subclasses may override this method in order to influence
how errors are parsed from the response.
Parameters:
response(Response): The response object.
Returns:
object or None: Any object for which a max retry count... | python | def _convert_response_to_error(self, response):
"""Subclasses may override this method in order to influence
how errors are parsed from the response.
Parameters:
response(Response): The response object.
Returns:
object or None: Any object for which a max retry count... | [
"def",
"_convert_response_to_error",
"(",
"self",
",",
"response",
")",
":",
"content_type",
"=",
"response",
".",
"headers",
".",
"get",
"(",
"\"content-type\"",
",",
"\"\"",
")",
"if",
"\"application/x-protobuf\"",
"in",
"content_type",
":",
"self",
".",
"logg... | Subclasses may override this method in order to influence
how errors are parsed from the response.
Parameters:
response(Response): The response object.
Returns:
object or None: Any object for which a max retry count can
be retrieved or None if the error cannot be ... | [
"Subclasses",
"may",
"override",
"this",
"method",
"in",
"order",
"to",
"influence",
"how",
"errors",
"are",
"parsed",
"from",
"the",
"response",
"."
] | 8933363c4e9fa1e5ec0e90d683fca8ef8a949752 | https://github.com/LeadPages/gcloud_requests/blob/8933363c4e9fa1e5ec0e90d683fca8ef8a949752/gcloud_requests/proxy.py#L164-L193 | train | Convert the response to an error object. |
IRC-SPHERE/HyperStream | hyperstream/tools/asset_plate_generator/2017-03-17_v0.2.0.py | AssetPlateGenerator.generate_instance | def generate_instance(self, timestamp, value, meta_data):
"""
Generate a stream instance, checking if the filters are matched
:param timestamp: The timestamp
:param value: The value
:param meta_data: The meta data
:return: The stream instance (or None)
"""
... | python | def generate_instance(self, timestamp, value, meta_data):
"""
Generate a stream instance, checking if the filters are matched
:param timestamp: The timestamp
:param value: The value
:param meta_data: The meta data
:return: The stream instance (or None)
"""
... | [
"def",
"generate_instance",
"(",
"self",
",",
"timestamp",
",",
"value",
",",
"meta_data",
")",
":",
"if",
"not",
"self",
".",
"filters",
"or",
"meta_data",
"in",
"self",
".",
"filters",
":",
"if",
"self",
".",
"filters",
":",
"logging",
".",
"debug",
... | Generate a stream instance, checking if the filters are matched
:param timestamp: The timestamp
:param value: The value
:param meta_data: The meta data
:return: The stream instance (or None) | [
"Generate",
"a",
"stream",
"instance",
"checking",
"if",
"the",
"filters",
"are",
"matched",
":",
"param",
"timestamp",
":",
"The",
"timestamp",
":",
"param",
"value",
":",
"The",
"value",
":",
"param",
"meta_data",
":",
"The",
"meta",
"data",
":",
"return... | 98478f4d31ed938f4aa7c958ed0d4c3ffcb2e780 | https://github.com/IRC-SPHERE/HyperStream/blob/98478f4d31ed938f4aa7c958ed0d4c3ffcb2e780/hyperstream/tools/asset_plate_generator/2017-03-17_v0.2.0.py#L67-L81 | train | Generate a stream instance based on the filters |
NaPs/Kolekto | kolekto/pattern.py | parse_pattern | def parse_pattern(format_string, env, wrapper=lambda x, y: y):
""" Parse the format_string and return prepared data according to the env.
Pick each field found in the format_string from the env(ironment), apply
the wrapper on each data and return a mapping between field-to-replace and
values for each.
... | python | def parse_pattern(format_string, env, wrapper=lambda x, y: y):
""" Parse the format_string and return prepared data according to the env.
Pick each field found in the format_string from the env(ironment), apply
the wrapper on each data and return a mapping between field-to-replace and
values for each.
... | [
"def",
"parse_pattern",
"(",
"format_string",
",",
"env",
",",
"wrapper",
"=",
"lambda",
"x",
",",
"y",
":",
"y",
")",
":",
"formatter",
"=",
"Formatter",
"(",
")",
"fields",
"=",
"[",
"x",
"[",
"1",
"]",
"for",
"x",
"in",
"formatter",
".",
"parse"... | Parse the format_string and return prepared data according to the env.
Pick each field found in the format_string from the env(ironment), apply
the wrapper on each data and return a mapping between field-to-replace and
values for each. | [
"Parse",
"the",
"format_string",
"and",
"return",
"prepared",
"data",
"according",
"to",
"the",
"env",
"."
] | 29c5469da8782780a06bf9a76c59414bb6fd8fe3 | https://github.com/NaPs/Kolekto/blob/29c5469da8782780a06bf9a76c59414bb6fd8fe3/kolekto/pattern.py#L7-L38 | train | Parse a format string and return a prepared environment with the values found in the env. |
lexibank/pylexibank | src/pylexibank/commands/misc.py | new_dataset | def new_dataset(args):
"""
lexibank new-dataset OUTDIR [ID]
"""
if not args.args:
raise ParserError('you must specify an existing directory')
outdir = Path(args.args.pop(0))
if not outdir.exists():
raise ParserError('you must specify an existing directory')
id_pattern = re.c... | python | def new_dataset(args):
"""
lexibank new-dataset OUTDIR [ID]
"""
if not args.args:
raise ParserError('you must specify an existing directory')
outdir = Path(args.args.pop(0))
if not outdir.exists():
raise ParserError('you must specify an existing directory')
id_pattern = re.c... | [
"def",
"new_dataset",
"(",
"args",
")",
":",
"if",
"not",
"args",
".",
"args",
":",
"raise",
"ParserError",
"(",
"'you must specify an existing directory'",
")",
"outdir",
"=",
"Path",
"(",
"args",
".",
"args",
".",
"pop",
"(",
"0",
")",
")",
"if",
"not"... | lexibank new-dataset OUTDIR [ID] | [
"lexibank",
"new",
"-",
"dataset",
"OUTDIR",
"[",
"ID",
"]"
] | c28e7f122f20de1232623dd7003cb5b01535e581 | https://github.com/lexibank/pylexibank/blob/c28e7f122f20de1232623dd7003cb5b01535e581/src/pylexibank/commands/misc.py#L25-L78 | train | lexibank new - dataset OUTDIR [ ID ] |
lexibank/pylexibank | src/pylexibank/commands/misc.py | ls | def ls(args):
"""
lexibank ls [COLS]+
column specification:
- license
- lexemes
- macroareas
"""
db = Database(args.db)
db.create(exists_ok=True)
in_db = {r[0]: r[1] for r in db.fetchall('select id, version from dataset')}
# FIXME: how to smartly choose columns?
table = ... | python | def ls(args):
"""
lexibank ls [COLS]+
column specification:
- license
- lexemes
- macroareas
"""
db = Database(args.db)
db.create(exists_ok=True)
in_db = {r[0]: r[1] for r in db.fetchall('select id, version from dataset')}
# FIXME: how to smartly choose columns?
table = ... | [
"def",
"ls",
"(",
"args",
")",
":",
"db",
"=",
"Database",
"(",
"args",
".",
"db",
")",
"db",
".",
"create",
"(",
"exists_ok",
"=",
"True",
")",
"in_db",
"=",
"{",
"r",
"[",
"0",
"]",
":",
"r",
"[",
"1",
"]",
"for",
"r",
"in",
"db",
".",
... | lexibank ls [COLS]+
column specification:
- license
- lexemes
- macroareas | [
"lexibank",
"ls",
"[",
"COLS",
"]",
"+"
] | c28e7f122f20de1232623dd7003cb5b01535e581 | https://github.com/lexibank/pylexibank/blob/c28e7f122f20de1232623dd7003cb5b01535e581/src/pylexibank/commands/misc.py#L181-L264 | train | ls - List all available lexical articles |
tamasgal/km3pipe | km3pipe/stats.py | mad | def mad(v):
"""MAD -- Median absolute deviation. More robust than standard deviation.
"""
return np.median(np.abs(v - np.median(v))) | python | def mad(v):
"""MAD -- Median absolute deviation. More robust than standard deviation.
"""
return np.median(np.abs(v - np.median(v))) | [
"def",
"mad",
"(",
"v",
")",
":",
"return",
"np",
".",
"median",
"(",
"np",
".",
"abs",
"(",
"v",
"-",
"np",
".",
"median",
"(",
"v",
")",
")",
")"
] | MAD -- Median absolute deviation. More robust than standard deviation. | [
"MAD",
"--",
"Median",
"absolute",
"deviation",
".",
"More",
"robust",
"than",
"standard",
"deviation",
"."
] | 7a9b59ac899a28775b5bdc5d391d9a5340d08040 | https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/stats.py#L114-L117 | train | MAD -- Median absolute deviation. More robust than standard deviation. |
tamasgal/km3pipe | km3pipe/stats.py | param_names | def param_names(scipy_dist):
"""Get names of fit parameters from a ``scipy.rv_*`` distribution."""
if not isinstance(scipy_dist, rv_continuous):
raise TypeError
names = ['loc', 'scale']
if scipy_dist.shapes is not None:
names += scipy_dist.shapes.split()
return names | python | def param_names(scipy_dist):
"""Get names of fit parameters from a ``scipy.rv_*`` distribution."""
if not isinstance(scipy_dist, rv_continuous):
raise TypeError
names = ['loc', 'scale']
if scipy_dist.shapes is not None:
names += scipy_dist.shapes.split()
return names | [
"def",
"param_names",
"(",
"scipy_dist",
")",
":",
"if",
"not",
"isinstance",
"(",
"scipy_dist",
",",
"rv_continuous",
")",
":",
"raise",
"TypeError",
"names",
"=",
"[",
"'loc'",
",",
"'scale'",
"]",
"if",
"scipy_dist",
".",
"shapes",
"is",
"not",
"None",
... | Get names of fit parameters from a ``scipy.rv_*`` distribution. | [
"Get",
"names",
"of",
"fit",
"parameters",
"from",
"a",
"scipy",
".",
"rv_",
"*",
"distribution",
"."
] | 7a9b59ac899a28775b5bdc5d391d9a5340d08040 | https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/stats.py#L133-L140 | train | Get names of fit parameters from a scipy. rv_* distribution. |
tamasgal/km3pipe | km3pipe/stats.py | perc | def perc(arr, p=95, **kwargs):
"""Create symmetric percentiles, with ``p`` coverage."""
offset = (100 - p) / 2
return np.percentile(arr, (offset, 100 - offset), **kwargs) | python | def perc(arr, p=95, **kwargs):
"""Create symmetric percentiles, with ``p`` coverage."""
offset = (100 - p) / 2
return np.percentile(arr, (offset, 100 - offset), **kwargs) | [
"def",
"perc",
"(",
"arr",
",",
"p",
"=",
"95",
",",
"*",
"*",
"kwargs",
")",
":",
"offset",
"=",
"(",
"100",
"-",
"p",
")",
"/",
"2",
"return",
"np",
".",
"percentile",
"(",
"arr",
",",
"(",
"offset",
",",
"100",
"-",
"offset",
")",
",",
"... | Create symmetric percentiles, with ``p`` coverage. | [
"Create",
"symmetric",
"percentiles",
"with",
"p",
"coverage",
"."
] | 7a9b59ac899a28775b5bdc5d391d9a5340d08040 | https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/stats.py#L143-L146 | train | Create symmetric percentiles with p coverage. |
tamasgal/km3pipe | km3pipe/stats.py | resample_1d | def resample_1d(arr, n_out=None, random_state=None):
"""Resample an array, with replacement.
Parameters
==========
arr: np.ndarray
The array is resampled along the first axis.
n_out: int, optional
Number of samples to return. If not specified,
return ``len(arr)`` samples.
... | python | def resample_1d(arr, n_out=None, random_state=None):
"""Resample an array, with replacement.
Parameters
==========
arr: np.ndarray
The array is resampled along the first axis.
n_out: int, optional
Number of samples to return. If not specified,
return ``len(arr)`` samples.
... | [
"def",
"resample_1d",
"(",
"arr",
",",
"n_out",
"=",
"None",
",",
"random_state",
"=",
"None",
")",
":",
"if",
"random_state",
"is",
"None",
":",
"random_state",
"=",
"np",
".",
"random",
".",
"RandomState",
"(",
")",
"arr",
"=",
"np",
".",
"atleast_1d... | Resample an array, with replacement.
Parameters
==========
arr: np.ndarray
The array is resampled along the first axis.
n_out: int, optional
Number of samples to return. If not specified,
return ``len(arr)`` samples. | [
"Resample",
"an",
"array",
"with",
"replacement",
"."
] | 7a9b59ac899a28775b5bdc5d391d9a5340d08040 | https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/stats.py#L149-L167 | train | Resample an array with replacement. |
tamasgal/km3pipe | km3pipe/stats.py | bootstrap_params | def bootstrap_params(rv_cont, data, n_iter=5, **kwargs):
"""Bootstrap the fit params of a distribution.
Parameters
==========
rv_cont: scipy.stats.rv_continuous instance
The distribution which to fit.
data: array-like, 1d
The data on which to fit.
n_iter: int [default=10]
... | python | def bootstrap_params(rv_cont, data, n_iter=5, **kwargs):
"""Bootstrap the fit params of a distribution.
Parameters
==========
rv_cont: scipy.stats.rv_continuous instance
The distribution which to fit.
data: array-like, 1d
The data on which to fit.
n_iter: int [default=10]
... | [
"def",
"bootstrap_params",
"(",
"rv_cont",
",",
"data",
",",
"n_iter",
"=",
"5",
",",
"*",
"*",
"kwargs",
")",
":",
"fit_res",
"=",
"[",
"]",
"for",
"_",
"in",
"range",
"(",
"n_iter",
")",
":",
"params",
"=",
"rv_cont",
".",
"fit",
"(",
"resample_1... | Bootstrap the fit params of a distribution.
Parameters
==========
rv_cont: scipy.stats.rv_continuous instance
The distribution which to fit.
data: array-like, 1d
The data on which to fit.
n_iter: int [default=10]
Number of bootstrap iterations. | [
"Bootstrap",
"the",
"fit",
"params",
"of",
"a",
"distribution",
"."
] | 7a9b59ac899a28775b5bdc5d391d9a5340d08040 | https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/stats.py#L170-L187 | train | Bootstrap the fit params of a distribution. |
tamasgal/km3pipe | km3pipe/stats.py | param_describe | def param_describe(params, quant=95, axis=0):
"""Get mean + quantile range from bootstrapped params."""
par = np.mean(params, axis=axis)
lo, up = perc(quant)
p_up = np.percentile(params, up, axis=axis)
p_lo = np.percentile(params, lo, axis=axis)
return par, p_lo, p_up | python | def param_describe(params, quant=95, axis=0):
"""Get mean + quantile range from bootstrapped params."""
par = np.mean(params, axis=axis)
lo, up = perc(quant)
p_up = np.percentile(params, up, axis=axis)
p_lo = np.percentile(params, lo, axis=axis)
return par, p_lo, p_up | [
"def",
"param_describe",
"(",
"params",
",",
"quant",
"=",
"95",
",",
"axis",
"=",
"0",
")",
":",
"par",
"=",
"np",
".",
"mean",
"(",
"params",
",",
"axis",
"=",
"axis",
")",
"lo",
",",
"up",
"=",
"perc",
"(",
"quant",
")",
"p_up",
"=",
"np",
... | Get mean + quantile range from bootstrapped params. | [
"Get",
"mean",
"+",
"quantile",
"range",
"from",
"bootstrapped",
"params",
"."
] | 7a9b59ac899a28775b5bdc5d391d9a5340d08040 | https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/stats.py#L190-L196 | train | Get mean + quantile range from bootstrapped params. |
tamasgal/km3pipe | km3pipe/stats.py | bootstrap_fit | def bootstrap_fit(
rv_cont, data, n_iter=10, quant=95, print_params=True, **kwargs
):
"""Bootstrap a distribution fit + get confidence intervals for the params.
Parameters
==========
rv_cont: scipy.stats.rv_continuous instance
The distribution which to fit.
data: array-like, 1d
... | python | def bootstrap_fit(
rv_cont, data, n_iter=10, quant=95, print_params=True, **kwargs
):
"""Bootstrap a distribution fit + get confidence intervals for the params.
Parameters
==========
rv_cont: scipy.stats.rv_continuous instance
The distribution which to fit.
data: array-like, 1d
... | [
"def",
"bootstrap_fit",
"(",
"rv_cont",
",",
"data",
",",
"n_iter",
"=",
"10",
",",
"quant",
"=",
"95",
",",
"print_params",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"fit_params",
"=",
"bootstrap_params",
"(",
"rv_cont",
",",
"data",
",",
"n_ite... | Bootstrap a distribution fit + get confidence intervals for the params.
Parameters
==========
rv_cont: scipy.stats.rv_continuous instance
The distribution which to fit.
data: array-like, 1d
The data on which to fit.
n_iter: int [default=10]
Number of bootstrap iterations.
... | [
"Bootstrap",
"a",
"distribution",
"fit",
"+",
"get",
"confidence",
"intervals",
"for",
"the",
"params",
"."
] | 7a9b59ac899a28775b5bdc5d391d9a5340d08040 | https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/stats.py#L199-L241 | train | Bootstrap a distribution fit + get confidence intervals for the params. |
tamasgal/km3pipe | km3pipe/stats.py | rv_kde.rvs | def rvs(self, *args, **kwargs):
"""Draw Random Variates.
Parameters
----------
size: int, optional (default=1)
random_state_: optional (default=None)
"""
# TODO REVERSE THIS FUCK PYTHON2
size = kwargs.pop('size', 1)
random_state = kwargs.pop('size... | python | def rvs(self, *args, **kwargs):
"""Draw Random Variates.
Parameters
----------
size: int, optional (default=1)
random_state_: optional (default=None)
"""
# TODO REVERSE THIS FUCK PYTHON2
size = kwargs.pop('size', 1)
random_state = kwargs.pop('size... | [
"def",
"rvs",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# TODO REVERSE THIS FUCK PYTHON2",
"size",
"=",
"kwargs",
".",
"pop",
"(",
"'size'",
",",
"1",
")",
"random_state",
"=",
"kwargs",
".",
"pop",
"(",
"'size'",
",",
"None",
... | Draw Random Variates.
Parameters
----------
size: int, optional (default=1)
random_state_: optional (default=None) | [
"Draw",
"Random",
"Variates",
"."
] | 7a9b59ac899a28775b5bdc5d391d9a5340d08040 | https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/stats.py#L99-L111 | train | Draw Random Variates. |
tamasgal/km3pipe | km3pipe/utils/i3shower2hdf5.py | i3extract | def i3extract(infile, outfile=None):
"""Main event loop"""
if outfile is None:
outfile = infile + '.h5'
tray = I3Tray()
tray.AddModule('I3Reader', 'i3_reader', filename=infile)
# tray.AddModule(KeepReconstructed, "event_selector")
tray.AddModule(ReadEventMeta, 'read_meta') # grab the ... | python | def i3extract(infile, outfile=None):
"""Main event loop"""
if outfile is None:
outfile = infile + '.h5'
tray = I3Tray()
tray.AddModule('I3Reader', 'i3_reader', filename=infile)
# tray.AddModule(KeepReconstructed, "event_selector")
tray.AddModule(ReadEventMeta, 'read_meta') # grab the ... | [
"def",
"i3extract",
"(",
"infile",
",",
"outfile",
"=",
"None",
")",
":",
"if",
"outfile",
"is",
"None",
":",
"outfile",
"=",
"infile",
"+",
"'.h5'",
"tray",
"=",
"I3Tray",
"(",
")",
"tray",
".",
"AddModule",
"(",
"'I3Reader'",
",",
"'i3_reader'",
",",... | Main event loop | [
"Main",
"event",
"loop"
] | 7a9b59ac899a28775b5bdc5d391d9a5340d08040 | https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/utils/i3shower2hdf5.py#L301-L345 | train | This function extracts the i3 file and returns the file name. |
tamasgal/km3pipe | km3pipe/utils/i3shower2hdf5.py | main | def main():
"""Entry point when running as script from commandline."""
from docopt import docopt
args = docopt(__doc__)
infile = args['INFILE']
outfile = args['OUTFILE']
i3extract(infile, outfile) | python | def main():
"""Entry point when running as script from commandline."""
from docopt import docopt
args = docopt(__doc__)
infile = args['INFILE']
outfile = args['OUTFILE']
i3extract(infile, outfile) | [
"def",
"main",
"(",
")",
":",
"from",
"docopt",
"import",
"docopt",
"args",
"=",
"docopt",
"(",
"__doc__",
")",
"infile",
"=",
"args",
"[",
"'INFILE'",
"]",
"outfile",
"=",
"args",
"[",
"'OUTFILE'",
"]",
"i3extract",
"(",
"infile",
",",
"outfile",
")"
... | Entry point when running as script from commandline. | [
"Entry",
"point",
"when",
"running",
"as",
"script",
"from",
"commandline",
"."
] | 7a9b59ac899a28775b5bdc5d391d9a5340d08040 | https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/utils/i3shower2hdf5.py#L348-L354 | train | Entry point when running as script from commandline. |
IRC-SPHERE/HyperStream | hyperstream/client.py | Client.connect | def connect(self, server_config):
"""Connect using the configuration given
:param server_config: The server configuration
"""
if 'connection_string' in server_config:
self.client = pymongo.MongoClient(
server_config['connection_string'])
self.... | python | def connect(self, server_config):
"""Connect using the configuration given
:param server_config: The server configuration
"""
if 'connection_string' in server_config:
self.client = pymongo.MongoClient(
server_config['connection_string'])
self.... | [
"def",
"connect",
"(",
"self",
",",
"server_config",
")",
":",
"if",
"'connection_string'",
"in",
"server_config",
":",
"self",
".",
"client",
"=",
"pymongo",
".",
"MongoClient",
"(",
"server_config",
"[",
"'connection_string'",
"]",
")",
"self",
".",
"db",
... | Connect using the configuration given
:param server_config: The server configuration | [
"Connect",
"using",
"the",
"configuration",
"given"
] | 98478f4d31ed938f4aa7c958ed0d4c3ffcb2e780 | https://github.com/IRC-SPHERE/HyperStream/blob/98478f4d31ed938f4aa7c958ed0d4c3ffcb2e780/hyperstream/client.py#L65-L107 | train | Connect to the database and store the ID of the current object in the connection object. |
tamasgal/km3pipe | km3pipe/utils/ptconcat.py | ptconcat | def ptconcat(output_file, input_files, overwrite=False):
"""Concatenate HDF5 Files"""
filt = tb.Filters(
complevel=5, shuffle=True, fletcher32=True, complib='zlib'
)
out_tabs = {}
dt_file = input_files[0]
log.info("Reading data struct '%s'..." % dt_file)
h5struc = tb.open_file(dt_fil... | python | def ptconcat(output_file, input_files, overwrite=False):
"""Concatenate HDF5 Files"""
filt = tb.Filters(
complevel=5, shuffle=True, fletcher32=True, complib='zlib'
)
out_tabs = {}
dt_file = input_files[0]
log.info("Reading data struct '%s'..." % dt_file)
h5struc = tb.open_file(dt_fil... | [
"def",
"ptconcat",
"(",
"output_file",
",",
"input_files",
",",
"overwrite",
"=",
"False",
")",
":",
"filt",
"=",
"tb",
".",
"Filters",
"(",
"complevel",
"=",
"5",
",",
"shuffle",
"=",
"True",
",",
"fletcher32",
"=",
"True",
",",
"complib",
"=",
"'zlib... | Concatenate HDF5 Files | [
"Concatenate",
"HDF5",
"Files"
] | 7a9b59ac899a28775b5bdc5d391d9a5340d08040 | https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/utils/ptconcat.py#L36-L68 | train | Concatenate HDF5 Files |
tamasgal/km3pipe | km3modules/k40.py | calibrate_dom | def calibrate_dom(
dom_id,
data,
detector,
livetime=None,
fit_ang_dist=False,
scale_mc_to_data=True,
ad_fit_shape='pexp',
fit_background=True,
ctmin=-1.
):
"""Calibrate intra DOM PMT time offsets, efficiencies and sigmas
Parameters
... | python | def calibrate_dom(
dom_id,
data,
detector,
livetime=None,
fit_ang_dist=False,
scale_mc_to_data=True,
ad_fit_shape='pexp',
fit_background=True,
ctmin=-1.
):
"""Calibrate intra DOM PMT time offsets, efficiencies and sigmas
Parameters
... | [
"def",
"calibrate_dom",
"(",
"dom_id",
",",
"data",
",",
"detector",
",",
"livetime",
"=",
"None",
",",
"fit_ang_dist",
"=",
"False",
",",
"scale_mc_to_data",
"=",
"True",
",",
"ad_fit_shape",
"=",
"'pexp'",
",",
"fit_background",
"=",
"True",
",",
"ctmin",
... | Calibrate intra DOM PMT time offsets, efficiencies and sigmas
Parameters
----------
dom_id: DOM ID
data: dict of coincidences or root or hdf5 file
detector: instance of detector class
livetime: data-taking duration [s]
fixed_ang_dist: fixing angular distribution ... | [
"Calibrate",
"intra",
"DOM",
"PMT",
"time",
"offsets",
"efficiencies",
"and",
"sigmas"
] | 7a9b59ac899a28775b5bdc5d391d9a5340d08040 | https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3modules/k40.py#L382-L498 | train | Calibrate intra DOM PMT time offsets efficiencies and sigmas for a given DOM. |
tamasgal/km3pipe | km3modules/k40.py | load_k40_coincidences_from_hdf5 | def load_k40_coincidences_from_hdf5(filename, dom_id):
"""Load k40 coincidences from hdf5 file
Parameters
----------
filename: filename of hdf5 file
dom_id: DOM ID
Returns
-------
data: numpy array of coincidences
livetime: duration of data-taking
"""
with h5py.File(filena... | python | def load_k40_coincidences_from_hdf5(filename, dom_id):
"""Load k40 coincidences from hdf5 file
Parameters
----------
filename: filename of hdf5 file
dom_id: DOM ID
Returns
-------
data: numpy array of coincidences
livetime: duration of data-taking
"""
with h5py.File(filena... | [
"def",
"load_k40_coincidences_from_hdf5",
"(",
"filename",
",",
"dom_id",
")",
":",
"with",
"h5py",
".",
"File",
"(",
"filename",
",",
"'r'",
")",
"as",
"h5f",
":",
"data",
"=",
"h5f",
"[",
"'/k40counts/{0}'",
".",
"format",
"(",
"dom_id",
")",
"]",
"liv... | Load k40 coincidences from hdf5 file
Parameters
----------
filename: filename of hdf5 file
dom_id: DOM ID
Returns
-------
data: numpy array of coincidences
livetime: duration of data-taking | [
"Load",
"k40",
"coincidences",
"from",
"hdf5",
"file"
] | 7a9b59ac899a28775b5bdc5d391d9a5340d08040 | https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3modules/k40.py#L507-L526 | train | Load k40 coincidences from hdf5 file |
tamasgal/km3pipe | km3modules/k40.py | load_k40_coincidences_from_rootfile | def load_k40_coincidences_from_rootfile(filename, dom_id):
"""Load k40 coincidences from JMonitorK40 ROOT file
Parameters
----------
filename: root file produced by JMonitorK40
dom_id: DOM ID
Returns
-------
data: numpy array of coincidences
dom_weight: weight to apply to coinciden... | python | def load_k40_coincidences_from_rootfile(filename, dom_id):
"""Load k40 coincidences from JMonitorK40 ROOT file
Parameters
----------
filename: root file produced by JMonitorK40
dom_id: DOM ID
Returns
-------
data: numpy array of coincidences
dom_weight: weight to apply to coinciden... | [
"def",
"load_k40_coincidences_from_rootfile",
"(",
"filename",
",",
"dom_id",
")",
":",
"from",
"ROOT",
"import",
"TFile",
"root_file_monitor",
"=",
"TFile",
"(",
"filename",
",",
"\"READ\"",
")",
"dom_name",
"=",
"str",
"(",
"dom_id",
")",
"+",
"\".2S\"",
"hi... | Load k40 coincidences from JMonitorK40 ROOT file
Parameters
----------
filename: root file produced by JMonitorK40
dom_id: DOM ID
Returns
-------
data: numpy array of coincidences
dom_weight: weight to apply to coincidences to get rate in Hz | [
"Load",
"k40",
"coincidences",
"from",
"JMonitorK40",
"ROOT",
"file"
] | 7a9b59ac899a28775b5bdc5d391d9a5340d08040 | https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3modules/k40.py#L529-L566 | train | Load k40 coincidences from a ROOT file produced by JMonitorK40. |
tamasgal/km3pipe | km3modules/k40.py | fit_delta_ts | def fit_delta_ts(data, livetime, fit_background=True):
"""Fits gaussians to delta t for each PMT pair.
Parameters
----------
data: 2d np.array: x = PMT combinations (465), y = time, entry = frequency
livetime: length of data taking in seconds
fit_background: if True: fits gaussian with offset, ... | python | def fit_delta_ts(data, livetime, fit_background=True):
"""Fits gaussians to delta t for each PMT pair.
Parameters
----------
data: 2d np.array: x = PMT combinations (465), y = time, entry = frequency
livetime: length of data taking in seconds
fit_background: if True: fits gaussian with offset, ... | [
"def",
"fit_delta_ts",
"(",
"data",
",",
"livetime",
",",
"fit_background",
"=",
"True",
")",
":",
"data",
"=",
"data",
"/",
"livetime",
"start",
"=",
"-",
"(",
"data",
".",
"shape",
"[",
"1",
"]",
"-",
"1",
")",
"/",
"2",
"end",
"=",
"-",
"start... | Fits gaussians to delta t for each PMT pair.
Parameters
----------
data: 2d np.array: x = PMT combinations (465), y = time, entry = frequency
livetime: length of data taking in seconds
fit_background: if True: fits gaussian with offset, else without offset
Returns
-------
numpy arrays ... | [
"Fits",
"gaussians",
"to",
"delta",
"t",
"for",
"each",
"PMT",
"pair",
"."
] | 7a9b59ac899a28775b5bdc5d391d9a5340d08040 | https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3modules/k40.py#L579-L632 | train | Fits gaussians to delta t for each PMT pair. |
tamasgal/km3pipe | km3modules/k40.py | calculate_angles | def calculate_angles(detector, combs):
"""Calculates angles between PMT combinations according to positions in
detector_file
Parameters
----------
detector_file: file from which to read the PMT positions (.detx)
combs: pmt combinations
Returns
-------
angles: numpy array of angles ... | python | def calculate_angles(detector, combs):
"""Calculates angles between PMT combinations according to positions in
detector_file
Parameters
----------
detector_file: file from which to read the PMT positions (.detx)
combs: pmt combinations
Returns
-------
angles: numpy array of angles ... | [
"def",
"calculate_angles",
"(",
"detector",
",",
"combs",
")",
":",
"angles",
"=",
"[",
"]",
"pmt_angles",
"=",
"detector",
".",
"pmt_angles",
"for",
"first",
",",
"second",
"in",
"combs",
":",
"angles",
".",
"append",
"(",
"kp",
".",
"math",
".",
"ang... | Calculates angles between PMT combinations according to positions in
detector_file
Parameters
----------
detector_file: file from which to read the PMT positions (.detx)
combs: pmt combinations
Returns
-------
angles: numpy array of angles between all PMT combinations | [
"Calculates",
"angles",
"between",
"PMT",
"combinations",
"according",
"to",
"positions",
"in",
"detector_file"
] | 7a9b59ac899a28775b5bdc5d391d9a5340d08040 | https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3modules/k40.py#L635-L657 | train | Calculates the angles between all PMT combinations according to positions in
detector_file
combs |
tamasgal/km3pipe | km3modules/k40.py | fit_angular_distribution | def fit_angular_distribution(angles, rates, rate_errors, shape='pexp'):
"""Fits angular distribution of rates.
Parameters
----------
rates: numpy array
with rates for all PMT combinations
angles: numpy array
with angles for all PMT combinations
shape:
which function to fit; ex... | python | def fit_angular_distribution(angles, rates, rate_errors, shape='pexp'):
"""Fits angular distribution of rates.
Parameters
----------
rates: numpy array
with rates for all PMT combinations
angles: numpy array
with angles for all PMT combinations
shape:
which function to fit; ex... | [
"def",
"fit_angular_distribution",
"(",
"angles",
",",
"rates",
",",
"rate_errors",
",",
"shape",
"=",
"'pexp'",
")",
":",
"if",
"shape",
"==",
"'exp'",
":",
"fit_function",
"=",
"exponential",
"# p0 = [-0.91871169, 2.72224241, -1.19065965, 1.48054122]",
"if",
"shap... | Fits angular distribution of rates.
Parameters
----------
rates: numpy array
with rates for all PMT combinations
angles: numpy array
with angles for all PMT combinations
shape:
which function to fit; exp for exponential or pexp for
exponential_polinomial
Returns
---... | [
"Fits",
"angular",
"distribution",
"of",
"rates",
"."
] | 7a9b59ac899a28775b5bdc5d391d9a5340d08040 | https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3modules/k40.py#L668-L696 | train | Fits angular distribution of rates for all PMTs. |
tamasgal/km3pipe | km3modules/k40.py | minimize_t0s | def minimize_t0s(means, weights, combs):
"""Varies t0s to minimize the deviation of the gaussian means from zero.
Parameters
----------
means: numpy array of means of all PMT combinations
weights: numpy array of weights for the squared sum
combs: pmt combinations to use for minimization
Re... | python | def minimize_t0s(means, weights, combs):
"""Varies t0s to minimize the deviation of the gaussian means from zero.
Parameters
----------
means: numpy array of means of all PMT combinations
weights: numpy array of weights for the squared sum
combs: pmt combinations to use for minimization
Re... | [
"def",
"minimize_t0s",
"(",
"means",
",",
"weights",
",",
"combs",
")",
":",
"def",
"make_quality_function",
"(",
"means",
",",
"weights",
",",
"combs",
")",
":",
"def",
"quality_function",
"(",
"t0s",
")",
":",
"sq_sum",
"=",
"0",
"for",
"mean",
",",
... | Varies t0s to minimize the deviation of the gaussian means from zero.
Parameters
----------
means: numpy array of means of all PMT combinations
weights: numpy array of weights for the squared sum
combs: pmt combinations to use for minimization
Returns
-------
opt_t0s: optimal t0 values... | [
"Varies",
"t0s",
"to",
"minimize",
"the",
"deviation",
"of",
"the",
"gaussian",
"means",
"from",
"zero",
"."
] | 7a9b59ac899a28775b5bdc5d391d9a5340d08040 | https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3modules/k40.py#L699-L728 | train | Varies t0s to minimize the deviation of the gaussian means from zero. |
tamasgal/km3pipe | km3modules/k40.py | minimize_sigmas | def minimize_sigmas(sigmas, weights, combs):
"""Varies sigmas to minimize gaussian sigma12 - sqrt(sigma1² + sigma2²).
Parameters
----------
sigmas: numpy array of fitted sigmas of gaussians
weights: numpy array of weights for the squared sum
combs: pmt combinations to use for minimization
... | python | def minimize_sigmas(sigmas, weights, combs):
"""Varies sigmas to minimize gaussian sigma12 - sqrt(sigma1² + sigma2²).
Parameters
----------
sigmas: numpy array of fitted sigmas of gaussians
weights: numpy array of weights for the squared sum
combs: pmt combinations to use for minimization
... | [
"def",
"minimize_sigmas",
"(",
"sigmas",
",",
"weights",
",",
"combs",
")",
":",
"def",
"make_quality_function",
"(",
"sigmas",
",",
"weights",
",",
"combs",
")",
":",
"def",
"quality_function",
"(",
"s",
")",
":",
"sq_sum",
"=",
"0",
"for",
"sigma",
","... | Varies sigmas to minimize gaussian sigma12 - sqrt(sigma1² + sigma2²).
Parameters
----------
sigmas: numpy array of fitted sigmas of gaussians
weights: numpy array of weights for the squared sum
combs: pmt combinations to use for minimization
Returns
-------
opt_sigmas: optimal sigma va... | [
"Varies",
"sigmas",
"to",
"minimize",
"gaussian",
"sigma12",
"-",
"sqrt",
"(",
"sigma1²",
"+",
"sigma2²",
")",
"."
] | 7a9b59ac899a28775b5bdc5d391d9a5340d08040 | https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3modules/k40.py#L731-L761 | train | Varies sigmas to minimize gaussian sigma12 - sqrt ( sigma1 + sigma2 + sigma1² + sigma2². |
tamasgal/km3pipe | km3modules/k40.py | minimize_qes | def minimize_qes(fitted_rates, rates, weights, combs):
"""Varies QEs to minimize the deviation of the rates from the fitted_rates.
Parameters
----------
fitted_rates: numpy array of fitted rates from fit_angular_distribution
rates: numpy array of rates of all PMT combinations
weights: numpy arr... | python | def minimize_qes(fitted_rates, rates, weights, combs):
"""Varies QEs to minimize the deviation of the rates from the fitted_rates.
Parameters
----------
fitted_rates: numpy array of fitted rates from fit_angular_distribution
rates: numpy array of rates of all PMT combinations
weights: numpy arr... | [
"def",
"minimize_qes",
"(",
"fitted_rates",
",",
"rates",
",",
"weights",
",",
"combs",
")",
":",
"def",
"make_quality_function",
"(",
"fitted_rates",
",",
"rates",
",",
"weights",
",",
"combs",
")",
":",
"def",
"quality_function",
"(",
"qes",
")",
":",
"s... | Varies QEs to minimize the deviation of the rates from the fitted_rates.
Parameters
----------
fitted_rates: numpy array of fitted rates from fit_angular_distribution
rates: numpy array of rates of all PMT combinations
weights: numpy array of weights for the squared sum
combs: pmt combinations ... | [
"Varies",
"QEs",
"to",
"minimize",
"the",
"deviation",
"of",
"the",
"rates",
"from",
"the",
"fitted_rates",
"."
] | 7a9b59ac899a28775b5bdc5d391d9a5340d08040 | https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3modules/k40.py#L764-L795 | train | Varies QEs to minimize the deviation of the rates from the fitted_rates rates weights and combs. |
tamasgal/km3pipe | km3modules/k40.py | correct_means | def correct_means(means, opt_t0s, combs):
"""Applies optimal t0s to gaussians means.
Should be around zero afterwards.
Parameters
----------
means: numpy array of means of gaussians of all PMT combinations
opt_t0s: numpy array of optimal t0 values for all PMTs
combs: pmt combinations used ... | python | def correct_means(means, opt_t0s, combs):
"""Applies optimal t0s to gaussians means.
Should be around zero afterwards.
Parameters
----------
means: numpy array of means of gaussians of all PMT combinations
opt_t0s: numpy array of optimal t0 values for all PMTs
combs: pmt combinations used ... | [
"def",
"correct_means",
"(",
"means",
",",
"opt_t0s",
",",
"combs",
")",
":",
"corrected_means",
"=",
"np",
".",
"array",
"(",
"[",
"(",
"opt_t0s",
"[",
"comb",
"[",
"1",
"]",
"]",
"-",
"opt_t0s",
"[",
"comb",
"[",
"0",
"]",
"]",
")",
"-",
"mean"... | Applies optimal t0s to gaussians means.
Should be around zero afterwards.
Parameters
----------
means: numpy array of means of gaussians of all PMT combinations
opt_t0s: numpy array of optimal t0 values for all PMTs
combs: pmt combinations used to correct
Returns
-------
corrected... | [
"Applies",
"optimal",
"t0s",
"to",
"gaussians",
"means",
"."
] | 7a9b59ac899a28775b5bdc5d391d9a5340d08040 | https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3modules/k40.py#L798-L816 | train | Applies optimal t0s to gaussians means. |
tamasgal/km3pipe | km3modules/k40.py | correct_rates | def correct_rates(rates, opt_qes, combs):
"""Applies optimal qes to rates.
Should be closer to fitted_rates afterwards.
Parameters
----------
rates: numpy array of rates of all PMT combinations
opt_qes: numpy array of optimal qe values for all PMTs
combs: pmt combinations used to correct
... | python | def correct_rates(rates, opt_qes, combs):
"""Applies optimal qes to rates.
Should be closer to fitted_rates afterwards.
Parameters
----------
rates: numpy array of rates of all PMT combinations
opt_qes: numpy array of optimal qe values for all PMTs
combs: pmt combinations used to correct
... | [
"def",
"correct_rates",
"(",
"rates",
",",
"opt_qes",
",",
"combs",
")",
":",
"corrected_rates",
"=",
"np",
".",
"array",
"(",
"[",
"rate",
"/",
"opt_qes",
"[",
"comb",
"[",
"0",
"]",
"]",
"/",
"opt_qes",
"[",
"comb",
"[",
"1",
"]",
"]",
"for",
"... | Applies optimal qes to rates.
Should be closer to fitted_rates afterwards.
Parameters
----------
rates: numpy array of rates of all PMT combinations
opt_qes: numpy array of optimal qe values for all PMTs
combs: pmt combinations used to correct
Returns
-------
corrected_rates: nump... | [
"Applies",
"optimal",
"qes",
"to",
"rates",
"."
] | 7a9b59ac899a28775b5bdc5d391d9a5340d08040 | https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3modules/k40.py#L819-L839 | train | Applies optimal qes to rates. |
tamasgal/km3pipe | km3modules/k40.py | calculate_rms_means | def calculate_rms_means(means, corrected_means):
"""Calculates RMS of means from zero before and after correction
Parameters
----------
means: numpy array of means of gaussians of all PMT combinations
corrected_means: numpy array of corrected gaussian means for all PMT combs
Returns
------... | python | def calculate_rms_means(means, corrected_means):
"""Calculates RMS of means from zero before and after correction
Parameters
----------
means: numpy array of means of gaussians of all PMT combinations
corrected_means: numpy array of corrected gaussian means for all PMT combs
Returns
------... | [
"def",
"calculate_rms_means",
"(",
"means",
",",
"corrected_means",
")",
":",
"rms_means",
"=",
"np",
".",
"sqrt",
"(",
"np",
".",
"mean",
"(",
"(",
"means",
"-",
"0",
")",
"**",
"2",
")",
")",
"rms_corrected_means",
"=",
"np",
".",
"sqrt",
"(",
"np"... | Calculates RMS of means from zero before and after correction
Parameters
----------
means: numpy array of means of gaussians of all PMT combinations
corrected_means: numpy array of corrected gaussian means for all PMT combs
Returns
-------
rms_means: RMS of means from zero
rms_correcte... | [
"Calculates",
"RMS",
"of",
"means",
"from",
"zero",
"before",
"and",
"after",
"correction"
] | 7a9b59ac899a28775b5bdc5d391d9a5340d08040 | https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3modules/k40.py#L842-L857 | train | Calculates the RMS of means from zero before and after corrections a PMT tree. |
tamasgal/km3pipe | km3modules/k40.py | calculate_rms_rates | def calculate_rms_rates(rates, fitted_rates, corrected_rates):
"""Calculates RMS of rates from fitted_rates before and after correction
Parameters
----------
rates: numpy array of rates of all PMT combinations
corrected_rates: numpy array of corrected rates for all PMT combinations
Returns
... | python | def calculate_rms_rates(rates, fitted_rates, corrected_rates):
"""Calculates RMS of rates from fitted_rates before and after correction
Parameters
----------
rates: numpy array of rates of all PMT combinations
corrected_rates: numpy array of corrected rates for all PMT combinations
Returns
... | [
"def",
"calculate_rms_rates",
"(",
"rates",
",",
"fitted_rates",
",",
"corrected_rates",
")",
":",
"rms_rates",
"=",
"np",
".",
"sqrt",
"(",
"np",
".",
"mean",
"(",
"(",
"rates",
"-",
"fitted_rates",
")",
"**",
"2",
")",
")",
"rms_corrected_rates",
"=",
... | Calculates RMS of rates from fitted_rates before and after correction
Parameters
----------
rates: numpy array of rates of all PMT combinations
corrected_rates: numpy array of corrected rates for all PMT combinations
Returns
-------
rms_rates: RMS of rates from fitted_rates
rms_correct... | [
"Calculates",
"RMS",
"of",
"rates",
"from",
"fitted_rates",
"before",
"and",
"after",
"correction"
] | 7a9b59ac899a28775b5bdc5d391d9a5340d08040 | https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3modules/k40.py#L860-L875 | train | Calculates RMS of rates from fitted_rates before and after correction
|
tamasgal/km3pipe | km3modules/k40.py | add_to_twofold_matrix | def add_to_twofold_matrix(times, tdcs, mat, tmax=10):
"""Add counts to twofold coincidences for a given `tmax`.
Parameters
----------
times: np.ndarray of hit times (int32)
tdcs: np.ndarray of channel_ids (uint8)
mat: ref to a np.array((465, tmax * 2 + 1))
tmax: int (time window)
Retur... | python | def add_to_twofold_matrix(times, tdcs, mat, tmax=10):
"""Add counts to twofold coincidences for a given `tmax`.
Parameters
----------
times: np.ndarray of hit times (int32)
tdcs: np.ndarray of channel_ids (uint8)
mat: ref to a np.array((465, tmax * 2 + 1))
tmax: int (time window)
Retur... | [
"def",
"add_to_twofold_matrix",
"(",
"times",
",",
"tdcs",
",",
"mat",
",",
"tmax",
"=",
"10",
")",
":",
"h_idx",
"=",
"0",
"# index of initial hit",
"c_idx",
"=",
"0",
"# index of coincident candidate hit",
"n_hits",
"=",
"len",
"(",
"times",
")",
"multiplici... | Add counts to twofold coincidences for a given `tmax`.
Parameters
----------
times: np.ndarray of hit times (int32)
tdcs: np.ndarray of channel_ids (uint8)
mat: ref to a np.array((465, tmax * 2 + 1))
tmax: int (time window)
Returns
-------
mat: coincidence matrix (np.array((465, tm... | [
"Add",
"counts",
"to",
"twofold",
"coincidences",
"for",
"a",
"given",
"tmax",
"."
] | 7a9b59ac899a28775b5bdc5d391d9a5340d08040 | https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3modules/k40.py#L885-L926 | train | Add counts to twofold coincidences for a given tmax. |
tamasgal/km3pipe | km3modules/k40.py | TwofoldCounter.reset | def reset(self):
"""Reset coincidence counter"""
self.counts = defaultdict(partial(np.zeros, (465, self.tmax * 2 + 1)))
self.n_timeslices = defaultdict(int) | python | def reset(self):
"""Reset coincidence counter"""
self.counts = defaultdict(partial(np.zeros, (465, self.tmax * 2 + 1)))
self.n_timeslices = defaultdict(int) | [
"def",
"reset",
"(",
"self",
")",
":",
"self",
".",
"counts",
"=",
"defaultdict",
"(",
"partial",
"(",
"np",
".",
"zeros",
",",
"(",
"465",
",",
"self",
".",
"tmax",
"*",
"2",
"+",
"1",
")",
")",
")",
"self",
".",
"n_timeslices",
"=",
"defaultdic... | Reset coincidence counter | [
"Reset",
"coincidence",
"counter"
] | 7a9b59ac899a28775b5bdc5d391d9a5340d08040 | https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3modules/k40.py#L247-L250 | train | Reset the coincidence counter to its initial state. |
tamasgal/km3pipe | km3modules/k40.py | TwofoldCounter.dump | def dump(self):
"""Write coincidence counts into a Python pickle"""
self.print("Dumping data to {}".format(self.dump_filename))
pickle.dump({
'data': self.counts,
'livetime': self.get_livetime()
}, open(self.dump_filename, "wb")) | python | def dump(self):
"""Write coincidence counts into a Python pickle"""
self.print("Dumping data to {}".format(self.dump_filename))
pickle.dump({
'data': self.counts,
'livetime': self.get_livetime()
}, open(self.dump_filename, "wb")) | [
"def",
"dump",
"(",
"self",
")",
":",
"self",
".",
"print",
"(",
"\"Dumping data to {}\"",
".",
"format",
"(",
"self",
".",
"dump_filename",
")",
")",
"pickle",
".",
"dump",
"(",
"{",
"'data'",
":",
"self",
".",
"counts",
",",
"'livetime'",
":",
"self"... | Write coincidence counts into a Python pickle | [
"Write",
"coincidence",
"counts",
"into",
"a",
"Python",
"pickle"
] | 7a9b59ac899a28775b5bdc5d391d9a5340d08040 | https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3modules/k40.py#L283-L289 | train | Write coincidence counts into a Python pickle file |
ioos/pyoos | pyoos/parsers/ioos/one/describe_sensor.py | DescribeSensor.get_named_by_definition | def get_named_by_definition(cls, element_list, string_def):
"""Attempts to get an IOOS definition from a list of xml elements"""
try:
return next(
(
st.value
for st in element_list
if st.definition == string_def
... | python | def get_named_by_definition(cls, element_list, string_def):
"""Attempts to get an IOOS definition from a list of xml elements"""
try:
return next(
(
st.value
for st in element_list
if st.definition == string_def
... | [
"def",
"get_named_by_definition",
"(",
"cls",
",",
"element_list",
",",
"string_def",
")",
":",
"try",
":",
"return",
"next",
"(",
"(",
"st",
".",
"value",
"for",
"st",
"in",
"element_list",
"if",
"st",
".",
"definition",
"==",
"string_def",
")",
")",
"e... | Attempts to get an IOOS definition from a list of xml elements | [
"Attempts",
"to",
"get",
"an",
"IOOS",
"definition",
"from",
"a",
"list",
"of",
"xml",
"elements"
] | 908660385029ecd8eccda8ab3a6b20b47b915c77 | https://github.com/ioos/pyoos/blob/908660385029ecd8eccda8ab3a6b20b47b915c77/pyoos/parsers/ioos/one/describe_sensor.py#L37-L48 | train | Attempts to get an IOOS definition from a list of xml elements |
ioos/pyoos | pyoos/parsers/ioos/one/describe_sensor.py | DescribeSensor.get_ioos_def | def get_ioos_def(self, ident, elem_type, ont):
"""Gets a definition given an identifier and where to search for it"""
if elem_type == "identifier":
getter_fn = self.system.get_identifiers_by_name
elif elem_type == "classifier":
getter_fn = self.system.get_classifiers_by_n... | python | def get_ioos_def(self, ident, elem_type, ont):
"""Gets a definition given an identifier and where to search for it"""
if elem_type == "identifier":
getter_fn = self.system.get_identifiers_by_name
elif elem_type == "classifier":
getter_fn = self.system.get_classifiers_by_n... | [
"def",
"get_ioos_def",
"(",
"self",
",",
"ident",
",",
"elem_type",
",",
"ont",
")",
":",
"if",
"elem_type",
"==",
"\"identifier\"",
":",
"getter_fn",
"=",
"self",
".",
"system",
".",
"get_identifiers_by_name",
"elif",
"elem_type",
"==",
"\"classifier\"",
":",... | Gets a definition given an identifier and where to search for it | [
"Gets",
"a",
"definition",
"given",
"an",
"identifier",
"and",
"where",
"to",
"search",
"for",
"it"
] | 908660385029ecd8eccda8ab3a6b20b47b915c77 | https://github.com/ioos/pyoos/blob/908660385029ecd8eccda8ab3a6b20b47b915c77/pyoos/parsers/ioos/one/describe_sensor.py#L50-L60 | train | Gets a definition given an identifier and where to search for it |
mouse-reeve/horoscope-generator | horoscope_generator/HoroscopeGenerator.py | get_sentence | def get_sentence(start=None, depth=7):
''' follow the grammatical patterns to generate a random sentence '''
if not GRAMMAR:
return 'Please set a GRAMMAR file'
start = start if start else GRAMMAR.start()
if isinstance(start, Nonterminal):
productions = GRAMMAR.productions(start)
... | python | def get_sentence(start=None, depth=7):
''' follow the grammatical patterns to generate a random sentence '''
if not GRAMMAR:
return 'Please set a GRAMMAR file'
start = start if start else GRAMMAR.start()
if isinstance(start, Nonterminal):
productions = GRAMMAR.productions(start)
... | [
"def",
"get_sentence",
"(",
"start",
"=",
"None",
",",
"depth",
"=",
"7",
")",
":",
"if",
"not",
"GRAMMAR",
":",
"return",
"'Please set a GRAMMAR file'",
"start",
"=",
"start",
"if",
"start",
"else",
"GRAMMAR",
".",
"start",
"(",
")",
"if",
"isinstance",
... | follow the grammatical patterns to generate a random sentence | [
"follow",
"the",
"grammatical",
"patterns",
"to",
"generate",
"a",
"random",
"sentence"
] | 01acf298116745ded5819d348c28a98a7492ccf3 | https://github.com/mouse-reeve/horoscope-generator/blob/01acf298116745ded5819d348c28a98a7492ccf3/horoscope_generator/HoroscopeGenerator.py#L17-L38 | train | follow the grammatical patterns to generate a random sentence |
mouse-reeve/horoscope-generator | horoscope_generator/HoroscopeGenerator.py | format_sentence | def format_sentence(sentence):
''' fix display formatting of a sentence array '''
for index, word in enumerate(sentence):
if word == 'a' and index + 1 < len(sentence) and \
re.match(r'^[aeiou]', sentence[index + 1]) and not \
re.match(r'^uni', sentence[index + 1]):
... | python | def format_sentence(sentence):
''' fix display formatting of a sentence array '''
for index, word in enumerate(sentence):
if word == 'a' and index + 1 < len(sentence) and \
re.match(r'^[aeiou]', sentence[index + 1]) and not \
re.match(r'^uni', sentence[index + 1]):
... | [
"def",
"format_sentence",
"(",
"sentence",
")",
":",
"for",
"index",
",",
"word",
"in",
"enumerate",
"(",
"sentence",
")",
":",
"if",
"word",
"==",
"'a'",
"and",
"index",
"+",
"1",
"<",
"len",
"(",
"sentence",
")",
"and",
"re",
".",
"match",
"(",
"... | fix display formatting of a sentence array | [
"fix",
"display",
"formatting",
"of",
"a",
"sentence",
"array"
] | 01acf298116745ded5819d348c28a98a7492ccf3 | https://github.com/mouse-reeve/horoscope-generator/blob/01acf298116745ded5819d348c28a98a7492ccf3/horoscope_generator/HoroscopeGenerator.py#L40-L50 | train | fix display formatting of a sentence array |
dsoprea/PySchedules | pyschedules/examples/read.py | EntityTrigger.new_station | def new_station(self, _id, callSign, name, affiliate, fccChannelNumber):
"""Callback run for each new station"""
if self.__v_station:
# [Station: 11440, WFLX, WFLX, Fox Affiliate, 29]
# [Station: 11836, WSCV, WSCV, TELEMUNDO (HBC) Affiliate, 51]
# [Station: 11867, TB... | python | def new_station(self, _id, callSign, name, affiliate, fccChannelNumber):
"""Callback run for each new station"""
if self.__v_station:
# [Station: 11440, WFLX, WFLX, Fox Affiliate, 29]
# [Station: 11836, WSCV, WSCV, TELEMUNDO (HBC) Affiliate, 51]
# [Station: 11867, TB... | [
"def",
"new_station",
"(",
"self",
",",
"_id",
",",
"callSign",
",",
"name",
",",
"affiliate",
",",
"fccChannelNumber",
")",
":",
"if",
"self",
".",
"__v_station",
":",
"# [Station: 11440, WFLX, WFLX, Fox Affiliate, 29]",
"# [Station: 11836, WSCV, WSCV, TELEMUNDO (HBC) Af... | Callback run for each new station | [
"Callback",
"run",
"for",
"each",
"new",
"station"
] | e5aae988fad90217f72db45f93bf69839f4d75e7 | https://github.com/dsoprea/PySchedules/blob/e5aae988fad90217f72db45f93bf69839f4d75e7/pyschedules/examples/read.py#L37-L53 | train | Callback run for each new station |
dsoprea/PySchedules | pyschedules/examples/read.py | EntityTrigger.new_lineup | def new_lineup(self, name, location, device, _type, postalCode, _id):
"""Callback run for each new lineup"""
if self.__v_lineup:
# [Lineup: Comcast West Palm Beach /Palm Beach Co., West Palm Beach, Digital, CableDigital, 33436, FL09567:X]
print("[Lineup: %s, %s, %s, %s, %s, %s]"... | python | def new_lineup(self, name, location, device, _type, postalCode, _id):
"""Callback run for each new lineup"""
if self.__v_lineup:
# [Lineup: Comcast West Palm Beach /Palm Beach Co., West Palm Beach, Digital, CableDigital, 33436, FL09567:X]
print("[Lineup: %s, %s, %s, %s, %s, %s]"... | [
"def",
"new_lineup",
"(",
"self",
",",
"name",
",",
"location",
",",
"device",
",",
"_type",
",",
"postalCode",
",",
"_id",
")",
":",
"if",
"self",
".",
"__v_lineup",
":",
"# [Lineup: Comcast West Palm Beach /Palm Beach Co., West Palm Beach, Digital, CableDigital, 33436... | Callback run for each new lineup | [
"Callback",
"run",
"for",
"each",
"new",
"lineup"
] | e5aae988fad90217f72db45f93bf69839f4d75e7 | https://github.com/dsoprea/PySchedules/blob/e5aae988fad90217f72db45f93bf69839f4d75e7/pyschedules/examples/read.py#L55-L61 | train | Callback run for each new lineup |
dsoprea/PySchedules | pyschedules/examples/read.py | EntityTrigger.new_mapping | def new_mapping(self, lineup, station, channel, channelMinor,
validFrom, validTo, onAirFrom, onAirTo):
"""Callback run for each new mapping within a lineup"""
if self.__v_mapping:
# [Mapping: FL09567:X, 11097, 45, None, 2010-06-29 00:00:00.00, None, None, None]
... | python | def new_mapping(self, lineup, station, channel, channelMinor,
validFrom, validTo, onAirFrom, onAirTo):
"""Callback run for each new mapping within a lineup"""
if self.__v_mapping:
# [Mapping: FL09567:X, 11097, 45, None, 2010-06-29 00:00:00.00, None, None, None]
... | [
"def",
"new_mapping",
"(",
"self",
",",
"lineup",
",",
"station",
",",
"channel",
",",
"channelMinor",
",",
"validFrom",
",",
"validTo",
",",
"onAirFrom",
",",
"onAirTo",
")",
":",
"if",
"self",
".",
"__v_mapping",
":",
"# [Mapping: FL09567:X, 11097, 45, None, 2... | Callback run for each new mapping within a lineup | [
"Callback",
"run",
"for",
"each",
"new",
"mapping",
"within",
"a",
"lineup"
] | e5aae988fad90217f72db45f93bf69839f4d75e7 | https://github.com/dsoprea/PySchedules/blob/e5aae988fad90217f72db45f93bf69839f4d75e7/pyschedules/examples/read.py#L63-L71 | train | Callback run for each new mapping within a lineup |
dsoprea/PySchedules | pyschedules/examples/read.py | EntityTrigger.new_schedule | def new_schedule(self, program, station, time, duration, new, stereo,
subtitled, hdtv, closeCaptioned, ei, tvRating, dolby,
partNumber, partTotal):
"""Callback run for each new schedule entry"""
if self.__v_schedule:
# [Schedule: EP012964250031, 70387... | python | def new_schedule(self, program, station, time, duration, new, stereo,
subtitled, hdtv, closeCaptioned, ei, tvRating, dolby,
partNumber, partTotal):
"""Callback run for each new schedule entry"""
if self.__v_schedule:
# [Schedule: EP012964250031, 70387... | [
"def",
"new_schedule",
"(",
"self",
",",
"program",
",",
"station",
",",
"time",
",",
"duration",
",",
"new",
",",
"stereo",
",",
"subtitled",
",",
"hdtv",
",",
"closeCaptioned",
",",
"ei",
",",
"tvRating",
",",
"dolby",
",",
"partNumber",
",",
"partTota... | Callback run for each new schedule entry | [
"Callback",
"run",
"for",
"each",
"new",
"schedule",
"entry"
] | e5aae988fad90217f72db45f93bf69839f4d75e7 | https://github.com/dsoprea/PySchedules/blob/e5aae988fad90217f72db45f93bf69839f4d75e7/pyschedules/examples/read.py#L73-L84 | train | Callback run for each new schedule entry |
dsoprea/PySchedules | pyschedules/examples/read.py | EntityTrigger.new_program | def new_program(self, _id, series, title, subtitle, description, mpaaRating,
starRating, runTime, year, showType, colorCode,
originalAirDate, syndicatedEpisodeNumber, advisories):
"""Callback run for each new program entry"""
if self.__v_program:
# [Pro... | python | def new_program(self, _id, series, title, subtitle, description, mpaaRating,
starRating, runTime, year, showType, colorCode,
originalAirDate, syndicatedEpisodeNumber, advisories):
"""Callback run for each new program entry"""
if self.__v_program:
# [Pro... | [
"def",
"new_program",
"(",
"self",
",",
"_id",
",",
"series",
",",
"title",
",",
"subtitle",
",",
"description",
",",
"mpaaRating",
",",
"starRating",
",",
"runTime",
",",
"year",
",",
"showType",
",",
"colorCode",
",",
"originalAirDate",
",",
"syndicatedEpi... | Callback run for each new program entry | [
"Callback",
"run",
"for",
"each",
"new",
"program",
"entry"
] | e5aae988fad90217f72db45f93bf69839f4d75e7 | https://github.com/dsoprea/PySchedules/blob/e5aae988fad90217f72db45f93bf69839f4d75e7/pyschedules/examples/read.py#L86-L96 | train | Callback run for each new program entry |
dsoprea/PySchedules | pyschedules/examples/read.py | EntityTrigger.new_crew_member | def new_crew_member(self, program, role, fullname, givenname, surname):
"""Callback run for each new crew member entry. 'fullname' is a
derived full-name, based on the presence of 'givenname' and/or
'surname'.
"""
if self.__v_crew_member:
# [Crew: EP000036710112, Ac... | python | def new_crew_member(self, program, role, fullname, givenname, surname):
"""Callback run for each new crew member entry. 'fullname' is a
derived full-name, based on the presence of 'givenname' and/or
'surname'.
"""
if self.__v_crew_member:
# [Crew: EP000036710112, Ac... | [
"def",
"new_crew_member",
"(",
"self",
",",
"program",
",",
"role",
",",
"fullname",
",",
"givenname",
",",
"surname",
")",
":",
"if",
"self",
".",
"__v_crew_member",
":",
"# [Crew: EP000036710112, Actor, Estelle Parsons]",
"print",
"(",
"\"[Crew: %s, %s, %s]\"",
"%... | Callback run for each new crew member entry. 'fullname' is a
derived full-name, based on the presence of 'givenname' and/or
'surname'. | [
"Callback",
"run",
"for",
"each",
"new",
"crew",
"member",
"entry",
".",
"fullname",
"is",
"a",
"derived",
"full",
"-",
"name",
"based",
"on",
"the",
"presence",
"of",
"givenname",
"and",
"/",
"or",
"surname",
"."
] | e5aae988fad90217f72db45f93bf69839f4d75e7 | https://github.com/dsoprea/PySchedules/blob/e5aae988fad90217f72db45f93bf69839f4d75e7/pyschedules/examples/read.py#L98-L106 | train | Callback run for each new crew member entry. |
dsoprea/PySchedules | pyschedules/examples/read.py | EntityTrigger.new_genre | def new_genre(self, program, genre, relevance):
"""Callback run for each new program genre entry"""
if self.__v_genre:
# [Genre: SP002709210000, Sports event, 0]
# [Genre: SP002709210000, Basketball, 1]
# [Genre: SP002737310000, Sports event, 0]
# [Genre:... | python | def new_genre(self, program, genre, relevance):
"""Callback run for each new program genre entry"""
if self.__v_genre:
# [Genre: SP002709210000, Sports event, 0]
# [Genre: SP002709210000, Basketball, 1]
# [Genre: SP002737310000, Sports event, 0]
# [Genre:... | [
"def",
"new_genre",
"(",
"self",
",",
"program",
",",
"genre",
",",
"relevance",
")",
":",
"if",
"self",
".",
"__v_genre",
":",
"# [Genre: SP002709210000, Sports event, 0]",
"# [Genre: SP002709210000, Basketball, 1]",
"# [Genre: SP002737310000, Sports event, 0]",
"# [Genre: S... | Callback run for each new program genre entry | [
"Callback",
"run",
"for",
"each",
"new",
"program",
"genre",
"entry"
] | e5aae988fad90217f72db45f93bf69839f4d75e7 | https://github.com/dsoprea/PySchedules/blob/e5aae988fad90217f72db45f93bf69839f4d75e7/pyschedules/examples/read.py#L108-L120 | train | Callback run for each new program genre entry |
tamasgal/km3pipe | km3pipe/shell.py | qsub | def qsub(script, job_name, dryrun=False, *args, **kwargs):
"""Submit a job via qsub."""
print("Preparing job script...")
job_string = gen_job(script=script, job_name=job_name, *args, **kwargs)
env = os.environ.copy()
if dryrun:
print(
"This is a dry run! Here is the generated job... | python | def qsub(script, job_name, dryrun=False, *args, **kwargs):
"""Submit a job via qsub."""
print("Preparing job script...")
job_string = gen_job(script=script, job_name=job_name, *args, **kwargs)
env = os.environ.copy()
if dryrun:
print(
"This is a dry run! Here is the generated job... | [
"def",
"qsub",
"(",
"script",
",",
"job_name",
",",
"dryrun",
"=",
"False",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"print",
"(",
"\"Preparing job script...\"",
")",
"job_string",
"=",
"gen_job",
"(",
"script",
"=",
"script",
",",
"job_name"... | Submit a job via qsub. | [
"Submit",
"a",
"job",
"via",
"qsub",
"."
] | 7a9b59ac899a28775b5bdc5d391d9a5340d08040 | https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/shell.py#L66-L82 | train | Submit a job via qsub. |
tamasgal/km3pipe | km3pipe/shell.py | gen_job | def gen_job(
script,
job_name,
log_path='qlogs',
group='km3net',
platform='cl7',
walltime='00:10:00',
vmem='8G',
fsize='8G',
shell=None,
email=None,
send_mail='n',
job_array_start=1,
job_array_stop=None,
job_... | python | def gen_job(
script,
job_name,
log_path='qlogs',
group='km3net',
platform='cl7',
walltime='00:10:00',
vmem='8G',
fsize='8G',
shell=None,
email=None,
send_mail='n',
job_array_start=1,
job_array_stop=None,
job_... | [
"def",
"gen_job",
"(",
"script",
",",
"job_name",
",",
"log_path",
"=",
"'qlogs'",
",",
"group",
"=",
"'km3net'",
",",
"platform",
"=",
"'cl7'",
",",
"walltime",
"=",
"'00:10:00'",
",",
"vmem",
"=",
"'8G'",
",",
"fsize",
"=",
"'8G'",
",",
"shell",
"=",... | Generate a job script. | [
"Generate",
"a",
"job",
"script",
"."
] | 7a9b59ac899a28775b5bdc5d391d9a5340d08040 | https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/shell.py#L85-L147 | train | Generate a job script. |
tamasgal/km3pipe | km3pipe/shell.py | get_jpp_env | def get_jpp_env(jpp_dir):
"""Return the environment dict of a loaded Jpp env.
The returned env can be passed to `subprocess.Popen("J...", env=env)`
to execute Jpp commands.
"""
env = {
v[0]: ''.join(v[1:])
for v in [
l.split('=') for l in os.popen(
"sour... | python | def get_jpp_env(jpp_dir):
"""Return the environment dict of a loaded Jpp env.
The returned env can be passed to `subprocess.Popen("J...", env=env)`
to execute Jpp commands.
"""
env = {
v[0]: ''.join(v[1:])
for v in [
l.split('=') for l in os.popen(
"sour... | [
"def",
"get_jpp_env",
"(",
"jpp_dir",
")",
":",
"env",
"=",
"{",
"v",
"[",
"0",
"]",
":",
"''",
".",
"join",
"(",
"v",
"[",
"1",
":",
"]",
")",
"for",
"v",
"in",
"[",
"l",
".",
"split",
"(",
"'='",
")",
"for",
"l",
"in",
"os",
".",
"popen... | Return the environment dict of a loaded Jpp env.
The returned env can be passed to `subprocess.Popen("J...", env=env)`
to execute Jpp commands. | [
"Return",
"the",
"environment",
"dict",
"of",
"a",
"loaded",
"Jpp",
"env",
"."
] | 7a9b59ac899a28775b5bdc5d391d9a5340d08040 | https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/shell.py#L150-L165 | train | Return the environment dict of a loaded Jpp env. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.