repository_name stringlengths 5 67 | func_path_in_repository stringlengths 4 234 | func_name stringlengths 0 314 | whole_func_string stringlengths 52 3.87M | language stringclasses 6
values | func_code_string stringlengths 52 3.87M | func_code_tokens listlengths 15 672k | func_documentation_string stringlengths 1 47.2k | func_documentation_tokens listlengths 1 3.92k | split_name stringclasses 1
value | func_code_url stringlengths 85 339 |
|---|---|---|---|---|---|---|---|---|---|---|
duniter/duniter-python-api | duniterpy/api/bma/wot.py | requirements | async def requirements(client: Client, search: str) -> dict:
"""
GET list of requirements for a given UID/Public key
:param client: Client to connect to the api
:param search: UID or public key
:return:
"""
return await client.get(MODULE + '/requirements/%s' % search, schema=REQUIREMENTS_SCHEMA) | python | async def requirements(client: Client, search: str) -> dict:
"""
GET list of requirements for a given UID/Public key
:param client: Client to connect to the api
:param search: UID or public key
:return:
"""
return await client.get(MODULE + '/requirements/%s' % search, schema=REQUIREMENTS_SCHEMA) | [
"async",
"def",
"requirements",
"(",
"client",
":",
"Client",
",",
"search",
":",
"str",
")",
"->",
"dict",
":",
"return",
"await",
"client",
".",
"get",
"(",
"MODULE",
"+",
"'/requirements/%s'",
"%",
"search",
",",
"schema",
"=",
"REQUIREMENTS_SCHEMA",
")... | GET list of requirements for a given UID/Public key
:param client: Client to connect to the api
:param search: UID or public key
:return: | [
"GET",
"list",
"of",
"requirements",
"for",
"a",
"given",
"UID",
"/",
"Public",
"key"
] | train | https://github.com/duniter/duniter-python-api/blob/3a1e5d61a2f72f5afaf29d010c6cf4dff3648165/duniterpy/api/bma/wot.py#L393-L401 |
duniter/duniter-python-api | duniterpy/api/bma/wot.py | identity_of | async def identity_of(client: Client, search: str) -> dict:
"""
GET Identity data written in the blockchain
:param client: Client to connect to the api
:param search: UID or public key
:return:
"""
return await client.get(MODULE + '/identity-of/%s' % search, schema=IDENTITY_OF_SCHEMA) | python | async def identity_of(client: Client, search: str) -> dict:
"""
GET Identity data written in the blockchain
:param client: Client to connect to the api
:param search: UID or public key
:return:
"""
return await client.get(MODULE + '/identity-of/%s' % search, schema=IDENTITY_OF_SCHEMA) | [
"async",
"def",
"identity_of",
"(",
"client",
":",
"Client",
",",
"search",
":",
"str",
")",
"->",
"dict",
":",
"return",
"await",
"client",
".",
"get",
"(",
"MODULE",
"+",
"'/identity-of/%s'",
"%",
"search",
",",
"schema",
"=",
"IDENTITY_OF_SCHEMA",
")"
] | GET Identity data written in the blockchain
:param client: Client to connect to the api
:param search: UID or public key
:return: | [
"GET",
"Identity",
"data",
"written",
"in",
"the",
"blockchain"
] | train | https://github.com/duniter/duniter-python-api/blob/3a1e5d61a2f72f5afaf29d010c6cf4dff3648165/duniterpy/api/bma/wot.py#L404-L412 |
Laufire/ec | tools/modules/helpers.py | shell_exec | def shell_exec(command, **kwargs): # from gitapi.py
"""Excecutes the given command silently.
"""
proc = Popen(shlex.split(command), stdout=PIPE, stderr=PIPE, **kwargs)
out, err = [x.decode("utf-8") for x in proc.communicate()]
return {'out': out, 'err': err, 'code': proc.returncode} | python | def shell_exec(command, **kwargs): # from gitapi.py
"""Excecutes the given command silently.
"""
proc = Popen(shlex.split(command), stdout=PIPE, stderr=PIPE, **kwargs)
out, err = [x.decode("utf-8") for x in proc.communicate()]
return {'out': out, 'err': err, 'code': proc.returncode} | [
"def",
"shell_exec",
"(",
"command",
",",
"*",
"*",
"kwargs",
")",
":",
"# from gitapi.py",
"proc",
"=",
"Popen",
"(",
"shlex",
".",
"split",
"(",
"command",
")",
",",
"stdout",
"=",
"PIPE",
",",
"stderr",
"=",
"PIPE",
",",
"*",
"*",
"kwargs",
")",
... | Excecutes the given command silently. | [
"Excecutes",
"the",
"given",
"command",
"silently",
"."
] | train | https://github.com/Laufire/ec/blob/63e84a1daef9234487d7de538e5da233a7d13071/tools/modules/helpers.py#L9-L16 |
Laufire/ec | tools/modules/helpers.py | run | def run(command, **kwargs):
"""Excecutes the given command while transfering control, till the execution is complete.
"""
print command
p = Popen(shlex.split(command), **kwargs)
p.wait()
return p.returncode | python | def run(command, **kwargs):
"""Excecutes the given command while transfering control, till the execution is complete.
"""
print command
p = Popen(shlex.split(command), **kwargs)
p.wait()
return p.returncode | [
"def",
"run",
"(",
"command",
",",
"*",
"*",
"kwargs",
")",
":",
"print",
"command",
"p",
"=",
"Popen",
"(",
"shlex",
".",
"split",
"(",
"command",
")",
",",
"*",
"*",
"kwargs",
")",
"p",
".",
"wait",
"(",
")",
"return",
"p",
".",
"returncode"
] | Excecutes the given command while transfering control, till the execution is complete. | [
"Excecutes",
"the",
"given",
"command",
"while",
"transfering",
"control",
"till",
"the",
"execution",
"is",
"complete",
"."
] | train | https://github.com/Laufire/ec/blob/63e84a1daef9234487d7de538e5da233a7d13071/tools/modules/helpers.py#L24-L31 |
gisgroup/statbank-python | statbank/__init__.py | data | def data(tableid,
variables=dict(),
stream=False,
descending=False,
lang=DEFAULT_LANGUAGE):
"""Pulls data from a table and generates rows.
Variables is a dictionary mapping variable codes to values.
Streaming:
Values must be chosen for all variables when streaming
"""
# bulk is also in csv format, but the response is streamed
format = 'BULK' if stream else 'CSV'
request = Request('data', tableid, format,
timeOrder='Descending' if descending else None,
valuePresentation='CodeAndValue',
lang=lang,
**variables)
return (Data(datum, lang=lang) for datum in request.csv) | python | def data(tableid,
variables=dict(),
stream=False,
descending=False,
lang=DEFAULT_LANGUAGE):
"""Pulls data from a table and generates rows.
Variables is a dictionary mapping variable codes to values.
Streaming:
Values must be chosen for all variables when streaming
"""
# bulk is also in csv format, but the response is streamed
format = 'BULK' if stream else 'CSV'
request = Request('data', tableid, format,
timeOrder='Descending' if descending else None,
valuePresentation='CodeAndValue',
lang=lang,
**variables)
return (Data(datum, lang=lang) for datum in request.csv) | [
"def",
"data",
"(",
"tableid",
",",
"variables",
"=",
"dict",
"(",
")",
",",
"stream",
"=",
"False",
",",
"descending",
"=",
"False",
",",
"lang",
"=",
"DEFAULT_LANGUAGE",
")",
":",
"# bulk is also in csv format, but the response is streamed",
"format",
"=",
"'B... | Pulls data from a table and generates rows.
Variables is a dictionary mapping variable codes to values.
Streaming:
Values must be chosen for all variables when streaming | [
"Pulls",
"data",
"from",
"a",
"table",
"and",
"generates",
"rows",
"."
] | train | https://github.com/gisgroup/statbank-python/blob/3678820d8da35f225d706ea5096c1f08bf0b9c68/statbank/__init__.py#L16-L37 |
gisgroup/statbank-python | statbank/__init__.py | subjects | def subjects(subjects=None,
recursive=False,
include_tables=False,
lang=DEFAULT_LANGUAGE):
"""List subjects from the subject hierarchy.
If subjects is not given, the root subjects will be used.
Returns a generator.
"""
request = Request('subjects', *subjects,
recursive=recursive,
includeTables=include_tables,
lang=lang)
return (Subject(subject, lang=lang) for subject in request.json) | python | def subjects(subjects=None,
recursive=False,
include_tables=False,
lang=DEFAULT_LANGUAGE):
"""List subjects from the subject hierarchy.
If subjects is not given, the root subjects will be used.
Returns a generator.
"""
request = Request('subjects', *subjects,
recursive=recursive,
includeTables=include_tables,
lang=lang)
return (Subject(subject, lang=lang) for subject in request.json) | [
"def",
"subjects",
"(",
"subjects",
"=",
"None",
",",
"recursive",
"=",
"False",
",",
"include_tables",
"=",
"False",
",",
"lang",
"=",
"DEFAULT_LANGUAGE",
")",
":",
"request",
"=",
"Request",
"(",
"'subjects'",
",",
"*",
"subjects",
",",
"recursive",
"=",... | List subjects from the subject hierarchy.
If subjects is not given, the root subjects will be used.
Returns a generator. | [
"List",
"subjects",
"from",
"the",
"subject",
"hierarchy",
"."
] | train | https://github.com/gisgroup/statbank-python/blob/3678820d8da35f225d706ea5096c1f08bf0b9c68/statbank/__init__.py#L40-L55 |
gisgroup/statbank-python | statbank/__init__.py | tableinfo | def tableinfo(tableid, lang=DEFAULT_LANGUAGE):
"""Fetch metadata for statbank table
Metadata includes information about variables,
which can be used when extracting data.
"""
request = Request('tableinfo', tableid, lang=lang)
return Tableinfo(request.json, lang=lang) | python | def tableinfo(tableid, lang=DEFAULT_LANGUAGE):
"""Fetch metadata for statbank table
Metadata includes information about variables,
which can be used when extracting data.
"""
request = Request('tableinfo', tableid, lang=lang)
return Tableinfo(request.json, lang=lang) | [
"def",
"tableinfo",
"(",
"tableid",
",",
"lang",
"=",
"DEFAULT_LANGUAGE",
")",
":",
"request",
"=",
"Request",
"(",
"'tableinfo'",
",",
"tableid",
",",
"lang",
"=",
"lang",
")",
"return",
"Tableinfo",
"(",
"request",
".",
"json",
",",
"lang",
"=",
"lang"... | Fetch metadata for statbank table
Metadata includes information about variables,
which can be used when extracting data. | [
"Fetch",
"metadata",
"for",
"statbank",
"table"
] | train | https://github.com/gisgroup/statbank-python/blob/3678820d8da35f225d706ea5096c1f08bf0b9c68/statbank/__init__.py#L58-L66 |
gisgroup/statbank-python | statbank/__init__.py | tables | def tables(subjects=None,
pastDays=None,
include_inactive=False,
lang=DEFAULT_LANGUAGE):
"""Find tables placed under given subjects.
"""
request = Request('tables',
subjects=subjects,
pastDays=pastDays,
includeInactive=include_inactive,
lang=lang)
return (Table(table, lang=lang) for table in request.json) | python | def tables(subjects=None,
pastDays=None,
include_inactive=False,
lang=DEFAULT_LANGUAGE):
"""Find tables placed under given subjects.
"""
request = Request('tables',
subjects=subjects,
pastDays=pastDays,
includeInactive=include_inactive,
lang=lang)
return (Table(table, lang=lang) for table in request.json) | [
"def",
"tables",
"(",
"subjects",
"=",
"None",
",",
"pastDays",
"=",
"None",
",",
"include_inactive",
"=",
"False",
",",
"lang",
"=",
"DEFAULT_LANGUAGE",
")",
":",
"request",
"=",
"Request",
"(",
"'tables'",
",",
"subjects",
"=",
"subjects",
",",
"pastDays... | Find tables placed under given subjects. | [
"Find",
"tables",
"placed",
"under",
"given",
"subjects",
"."
] | train | https://github.com/gisgroup/statbank-python/blob/3678820d8da35f225d706ea5096c1f08bf0b9c68/statbank/__init__.py#L69-L81 |
vadimk2016/v-vk-api | v_vk_api/api.py | API.request_method | def request_method(self, method: str,
**method_kwargs: Union[str, int]) -> dict:
"""
Process method request and return json with results
:param method: str: specifies the method, example: "users.get"
:param method_kwargs: dict: method parameters,
example: "users_id=1", "fields='city, contacts'"
"""
response = self.session.send_method_request(method, method_kwargs)
self.check_for_errors(method, method_kwargs, response)
return response | python | def request_method(self, method: str,
**method_kwargs: Union[str, int]) -> dict:
"""
Process method request and return json with results
:param method: str: specifies the method, example: "users.get"
:param method_kwargs: dict: method parameters,
example: "users_id=1", "fields='city, contacts'"
"""
response = self.session.send_method_request(method, method_kwargs)
self.check_for_errors(method, method_kwargs, response)
return response | [
"def",
"request_method",
"(",
"self",
",",
"method",
":",
"str",
",",
"*",
"*",
"method_kwargs",
":",
"Union",
"[",
"str",
",",
"int",
"]",
")",
"->",
"dict",
":",
"response",
"=",
"self",
".",
"session",
".",
"send_method_request",
"(",
"method",
",",... | Process method request and return json with results
:param method: str: specifies the method, example: "users.get"
:param method_kwargs: dict: method parameters,
example: "users_id=1", "fields='city, contacts'" | [
"Process",
"method",
"request",
"and",
"return",
"json",
"with",
"results"
] | train | https://github.com/vadimk2016/v-vk-api/blob/ef5656e09944b5319a1f573cfb7b022f3d31c0cf/v_vk_api/api.py#L28-L39 |
vadimk2016/v-vk-api | v_vk_api/api.py | API.request_get_user | def request_get_user(self, user_ids) -> dict:
"""
Method to get users by ID, do not need authorization
"""
method_params = {'user_ids': user_ids}
response = self.session.send_method_request('users.get', method_params)
self.check_for_errors('users.get', method_params, response)
return response | python | def request_get_user(self, user_ids) -> dict:
"""
Method to get users by ID, do not need authorization
"""
method_params = {'user_ids': user_ids}
response = self.session.send_method_request('users.get', method_params)
self.check_for_errors('users.get', method_params, response)
return response | [
"def",
"request_get_user",
"(",
"self",
",",
"user_ids",
")",
"->",
"dict",
":",
"method_params",
"=",
"{",
"'user_ids'",
":",
"user_ids",
"}",
"response",
"=",
"self",
".",
"session",
".",
"send_method_request",
"(",
"'users.get'",
",",
"method_params",
")",
... | Method to get users by ID, do not need authorization | [
"Method",
"to",
"get",
"users",
"by",
"ID",
"do",
"not",
"need",
"authorization"
] | train | https://github.com/vadimk2016/v-vk-api/blob/ef5656e09944b5319a1f573cfb7b022f3d31c0cf/v_vk_api/api.py#L41-L48 |
vadimk2016/v-vk-api | v_vk_api/api.py | API.request_set_status | def request_set_status(self, text: str) -> dict:
"""
Method to set user status
"""
method_params = {'text': text}
response = self.session.send_method_request('status.set',
method_params)
self.check_for_errors('status.set', method_params, response)
return response | python | def request_set_status(self, text: str) -> dict:
"""
Method to set user status
"""
method_params = {'text': text}
response = self.session.send_method_request('status.set',
method_params)
self.check_for_errors('status.set', method_params, response)
return response | [
"def",
"request_set_status",
"(",
"self",
",",
"text",
":",
"str",
")",
"->",
"dict",
":",
"method_params",
"=",
"{",
"'text'",
":",
"text",
"}",
"response",
"=",
"self",
".",
"session",
".",
"send_method_request",
"(",
"'status.set'",
",",
"method_params",
... | Method to set user status | [
"Method",
"to",
"set",
"user",
"status"
] | train | https://github.com/vadimk2016/v-vk-api/blob/ef5656e09944b5319a1f573cfb7b022f3d31c0cf/v_vk_api/api.py#L50-L58 |
cohorte/cohorte-herald | python/herald/utilities/mcast_spy.py | hexdump | def hexdump(src, length=16, sep='.'):
"""
Returns src in hex dump.
From https://gist.github.com/ImmortalPC/c340564823f283fe530b
:param length: Nb Bytes by row.
:param sep: For the text part, sep will be used for non ASCII char.
:return: The hexdump
"""
result = []
for i in range(0, len(src), length):
sub_src = src[i:i + length]
hexa = ''
for h in range(0, len(sub_src)):
if h == length / 2:
hexa += ' '
h = sub_src[h]
if not isinstance(h, int):
h = ord(h)
h = hex(h).replace('0x', '')
if len(h) == 1:
h = '0' + h
hexa += h + ' '
hexa = hexa.strip(' ')
text = ''
for c in sub_src:
if not isinstance(c, int):
c = ord(c)
if 0x20 <= c < 0x7F:
text += chr(c)
else:
text += sep
result.append(('%08X: %-' + str(length * (2 + 1) + 1) + 's |%s|')
% (i, hexa, text))
return '\n'.join(result) | python | def hexdump(src, length=16, sep='.'):
"""
Returns src in hex dump.
From https://gist.github.com/ImmortalPC/c340564823f283fe530b
:param length: Nb Bytes by row.
:param sep: For the text part, sep will be used for non ASCII char.
:return: The hexdump
"""
result = []
for i in range(0, len(src), length):
sub_src = src[i:i + length]
hexa = ''
for h in range(0, len(sub_src)):
if h == length / 2:
hexa += ' '
h = sub_src[h]
if not isinstance(h, int):
h = ord(h)
h = hex(h).replace('0x', '')
if len(h) == 1:
h = '0' + h
hexa += h + ' '
hexa = hexa.strip(' ')
text = ''
for c in sub_src:
if not isinstance(c, int):
c = ord(c)
if 0x20 <= c < 0x7F:
text += chr(c)
else:
text += sep
result.append(('%08X: %-' + str(length * (2 + 1) + 1) + 's |%s|')
% (i, hexa, text))
return '\n'.join(result) | [
"def",
"hexdump",
"(",
"src",
",",
"length",
"=",
"16",
",",
"sep",
"=",
"'.'",
")",
":",
"result",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"src",
")",
",",
"length",
")",
":",
"sub_src",
"=",
"src",
"[",
"i",
"... | Returns src in hex dump.
From https://gist.github.com/ImmortalPC/c340564823f283fe530b
:param length: Nb Bytes by row.
:param sep: For the text part, sep will be used for non ASCII char.
:return: The hexdump | [
"Returns",
"src",
"in",
"hex",
"dump",
".",
"From",
"https",
":",
"//",
"gist",
".",
"github",
".",
"com",
"/",
"ImmortalPC",
"/",
"c340564823f283fe530b"
] | train | https://github.com/cohorte/cohorte-herald/blob/bb3445d0031c8b3abad71e6219cc559b49faa3ee/python/herald/utilities/mcast_spy.py#L49-L86 |
cohorte/cohorte-herald | python/herald/utilities/mcast_spy.py | run_spy | def run_spy(group, port, verbose):
"""
Runs the multicast spy
:param group: Multicast group
:param port: Multicast port
:param verbose: If True, prints more details
"""
# Create the socket
socket, group = multicast.create_multicast_socket(group, port)
print("Socket created:", group, "port:", port)
# Set the socket as non-blocking
socket.setblocking(0)
# Prepare stats storage
stats = {
"total_bytes": 0,
"total_count": 0,
"sender_bytes": {},
"sender_count": {},
}
print("Press Ctrl+C to exit")
try:
loop_nb = 0
while True:
if loop_nb % 50 == 0:
loop_nb = 0
print("Reading...")
loop_nb += 1
ready = select.select([socket], [], [], .1)
if ready[0]:
# Socket is ready
data, sender = socket.recvfrom(1024)
len_data = len(data)
# Store stats
stats["total_bytes"] += len_data
stats["total_count"] += 1
try:
stats["sender_bytes"][sender] += len_data
stats["sender_count"][sender] += 1
except KeyError:
stats["sender_bytes"][sender] = len_data
stats["sender_count"][sender] = 1
print("Got", len_data, "bytes from", sender[0], "port",
sender[1], "at", datetime.datetime.now())
if verbose:
print(hexdump(data))
except KeyboardInterrupt:
# Interrupt
print("Ctrl+C received: bye !")
# Print statistics
print("Total number of packets:", stats["total_count"])
print("Total read bytes.......:", stats["total_bytes"])
for sender in stats["sender_count"]:
print("\nSender", sender[0], "from port", sender[1])
print("\tTotal packets:", stats["sender_count"][sender])
print("\tTotal bytes..:", stats["sender_bytes"][sender])
return 0 | python | def run_spy(group, port, verbose):
"""
Runs the multicast spy
:param group: Multicast group
:param port: Multicast port
:param verbose: If True, prints more details
"""
# Create the socket
socket, group = multicast.create_multicast_socket(group, port)
print("Socket created:", group, "port:", port)
# Set the socket as non-blocking
socket.setblocking(0)
# Prepare stats storage
stats = {
"total_bytes": 0,
"total_count": 0,
"sender_bytes": {},
"sender_count": {},
}
print("Press Ctrl+C to exit")
try:
loop_nb = 0
while True:
if loop_nb % 50 == 0:
loop_nb = 0
print("Reading...")
loop_nb += 1
ready = select.select([socket], [], [], .1)
if ready[0]:
# Socket is ready
data, sender = socket.recvfrom(1024)
len_data = len(data)
# Store stats
stats["total_bytes"] += len_data
stats["total_count"] += 1
try:
stats["sender_bytes"][sender] += len_data
stats["sender_count"][sender] += 1
except KeyError:
stats["sender_bytes"][sender] = len_data
stats["sender_count"][sender] = 1
print("Got", len_data, "bytes from", sender[0], "port",
sender[1], "at", datetime.datetime.now())
if verbose:
print(hexdump(data))
except KeyboardInterrupt:
# Interrupt
print("Ctrl+C received: bye !")
# Print statistics
print("Total number of packets:", stats["total_count"])
print("Total read bytes.......:", stats["total_bytes"])
for sender in stats["sender_count"]:
print("\nSender", sender[0], "from port", sender[1])
print("\tTotal packets:", stats["sender_count"][sender])
print("\tTotal bytes..:", stats["sender_bytes"][sender])
return 0 | [
"def",
"run_spy",
"(",
"group",
",",
"port",
",",
"verbose",
")",
":",
"# Create the socket",
"socket",
",",
"group",
"=",
"multicast",
".",
"create_multicast_socket",
"(",
"group",
",",
"port",
")",
"print",
"(",
"\"Socket created:\"",
",",
"group",
",",
"\... | Runs the multicast spy
:param group: Multicast group
:param port: Multicast port
:param verbose: If True, prints more details | [
"Runs",
"the",
"multicast",
"spy"
] | train | https://github.com/cohorte/cohorte-herald/blob/bb3445d0031c8b3abad71e6219cc559b49faa3ee/python/herald/utilities/mcast_spy.py#L89-L156 |
cohorte/cohorte-herald | python/herald/utilities/mcast_spy.py | main | def main(argv=None):
"""
Entry point
:param argv: Program arguments
"""
parser = argparse.ArgumentParser(description="Multicast packets spy")
parser.add_argument("-g", "--group", dest="group", default="239.0.0.1",
help="Multicast target group (address)")
parser.add_argument("-p", "--port", type=int, dest="port", default=42000,
help="Multicast target port")
parser.add_argument("-d", "--debug", action="store_true", dest="debug",
help="Set logger to DEBUG level")
parser.add_argument("-v", "--verbose", action="store_true", dest="verbose",
help="Verbose output")
# Parse arguments
args = parser.parse_args(argv)
# Configure the logger
if args.debug:
logging.basicConfig(level=logging.DEBUG)
else:
logging.basicConfig(level=logging.WARNING)
try:
return run_spy(args.group, args.port, args.verbose)
except Exception as ex:
logging.exception("Error running spy: %s", ex)
return 1 | python | def main(argv=None):
"""
Entry point
:param argv: Program arguments
"""
parser = argparse.ArgumentParser(description="Multicast packets spy")
parser.add_argument("-g", "--group", dest="group", default="239.0.0.1",
help="Multicast target group (address)")
parser.add_argument("-p", "--port", type=int, dest="port", default=42000,
help="Multicast target port")
parser.add_argument("-d", "--debug", action="store_true", dest="debug",
help="Set logger to DEBUG level")
parser.add_argument("-v", "--verbose", action="store_true", dest="verbose",
help="Verbose output")
# Parse arguments
args = parser.parse_args(argv)
# Configure the logger
if args.debug:
logging.basicConfig(level=logging.DEBUG)
else:
logging.basicConfig(level=logging.WARNING)
try:
return run_spy(args.group, args.port, args.verbose)
except Exception as ex:
logging.exception("Error running spy: %s", ex)
return 1 | [
"def",
"main",
"(",
"argv",
"=",
"None",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"\"Multicast packets spy\"",
")",
"parser",
".",
"add_argument",
"(",
"\"-g\"",
",",
"\"--group\"",
",",
"dest",
"=",
"\"group\"",
"... | Entry point
:param argv: Program arguments | [
"Entry",
"point"
] | train | https://github.com/cohorte/cohorte-herald/blob/bb3445d0031c8b3abad71e6219cc559b49faa3ee/python/herald/utilities/mcast_spy.py#L159-L191 |
azraq27/neural | neural/decon.py | stack_decon_stims | def stack_decon_stims(stim_list):
'''take a ``list`` (in order of runs) of ``dict``s of stim_name:DeconStim and stack them together. returns
a single ``dict`` of stim_name:decon_stim
As in, takes:
[
# Run 1
{ "stim1": decon_stim1a, "stim2": decon_stim2a },
# Run 2
{ "stim1": decon_stim1b, "stim2": decon_stim2b, "stim3": decon_stim3 }
]
And makes:
{ "stim1": decon_stim1, "stim2": decon_stim2, "stim3": decon_stim3 }
If a stimulus is not present in a run, it will fill that run with an empty stimulus
'''
stim_names = list(set(nl.flatten([stims.keys() for stims in stim_list])))
stim_dict = {}
for stim_name in stim_names:
types = list(set([stims[stim_name].type() for stims in stim_list if stim_name in stims]))
if len(types)>1:
nl.notify('Error: Trying to stack stimuli of different types! (%s)' % stim_name,level=nl.level.error)
return None
type = types[0]
stim_stack = []
for i in xrange(len(stim_list)):
if stim_name in stim_list[i]:
stim_stack.append(stim_list[i][stim_name])
else:
stim_stack.append(stim_list[i].values()[0].blank_stim(type=type))
stim_dict[stim_name] = copy.copy(stim_stack[0])
for stim in stim_stack[1:]:
stim_dict[stim_name] = stim_dict[stim_name].concat_stim(stim)
return stim_dict.values() | python | def stack_decon_stims(stim_list):
'''take a ``list`` (in order of runs) of ``dict``s of stim_name:DeconStim and stack them together. returns
a single ``dict`` of stim_name:decon_stim
As in, takes:
[
# Run 1
{ "stim1": decon_stim1a, "stim2": decon_stim2a },
# Run 2
{ "stim1": decon_stim1b, "stim2": decon_stim2b, "stim3": decon_stim3 }
]
And makes:
{ "stim1": decon_stim1, "stim2": decon_stim2, "stim3": decon_stim3 }
If a stimulus is not present in a run, it will fill that run with an empty stimulus
'''
stim_names = list(set(nl.flatten([stims.keys() for stims in stim_list])))
stim_dict = {}
for stim_name in stim_names:
types = list(set([stims[stim_name].type() for stims in stim_list if stim_name in stims]))
if len(types)>1:
nl.notify('Error: Trying to stack stimuli of different types! (%s)' % stim_name,level=nl.level.error)
return None
type = types[0]
stim_stack = []
for i in xrange(len(stim_list)):
if stim_name in stim_list[i]:
stim_stack.append(stim_list[i][stim_name])
else:
stim_stack.append(stim_list[i].values()[0].blank_stim(type=type))
stim_dict[stim_name] = copy.copy(stim_stack[0])
for stim in stim_stack[1:]:
stim_dict[stim_name] = stim_dict[stim_name].concat_stim(stim)
return stim_dict.values() | [
"def",
"stack_decon_stims",
"(",
"stim_list",
")",
":",
"stim_names",
"=",
"list",
"(",
"set",
"(",
"nl",
".",
"flatten",
"(",
"[",
"stims",
".",
"keys",
"(",
")",
"for",
"stims",
"in",
"stim_list",
"]",
")",
")",
")",
"stim_dict",
"=",
"{",
"}",
"... | take a ``list`` (in order of runs) of ``dict``s of stim_name:DeconStim and stack them together. returns
a single ``dict`` of stim_name:decon_stim
As in, takes:
[
# Run 1
{ "stim1": decon_stim1a, "stim2": decon_stim2a },
# Run 2
{ "stim1": decon_stim1b, "stim2": decon_stim2b, "stim3": decon_stim3 }
]
And makes:
{ "stim1": decon_stim1, "stim2": decon_stim2, "stim3": decon_stim3 }
If a stimulus is not present in a run, it will fill that run with an empty stimulus | [
"take",
"a",
"list",
"(",
"in",
"order",
"of",
"runs",
")",
"of",
"dict",
"s",
"of",
"stim_name",
":",
"DeconStim",
"and",
"stack",
"them",
"together",
".",
"returns",
"a",
"single",
"dict",
"of",
"stim_name",
":",
"decon_stim"
] | train | https://github.com/azraq27/neural/blob/fe91bfeecbf73ad99708cf5dca66cb61fcd529f5/neural/decon.py#L421-L457 |
azraq27/neural | neural/decon.py | smooth_decon_to_fwhm | def smooth_decon_to_fwhm(decon,fwhm,cache=True):
'''takes an input :class:`Decon` object and uses ``3dBlurToFWHM`` to make the output as close as possible to ``fwhm``
returns the final measured fwhm. If ``cache`` is ``True``, will save the blurred input file (and use it again in the future)'''
if os.path.exists(decon.prefix):
return
blur_dset = lambda dset: nl.suffix(dset,'_smooth_to_%.2f' % fwhm)
with nl.notify('Running smooth_decon_to_fwhm analysis (with %.2fmm blur)' % fwhm):
tmpdir = tempfile.mkdtemp()
try:
cwd = os.getcwd()
random_files = [re.sub(r'\[\d+\]$','',str(x)) for x in nl.flatten([x for x in decon.__dict__.values() if isinstance(x,basestring) or isinstance(x,list)]+[x.values() for x in decon.__dict__.values() if isinstance(x,dict)])]
files_to_copy = [x for x in random_files if os.path.exists(x) and x[0]!='/']
files_to_copy += [blur_dset(dset) for dset in decon.input_dsets if os.path.exists(blur_dset(dset))]
# copy crap
for file in files_to_copy:
try:
shutil.copytree(file,tmpdir)
except OSError as e:
shutil.copy(file,tmpdir)
shutil.copy(file,tmpdir)
copyback_files = [decon.prefix,decon.errts]
with nl.run_in(tmpdir):
if os.path.exists(decon.prefix):
os.remove(decon.prefix)
# Create the blurred inputs (or load from cache)
if cache and all([os.path.exists(os.path.join(cwd,blur_dset(dset))) for dset in decon.input_dsets]):
# Everything is already cached...
nl.notify('Using cache\'d blurred datasets')
else:
# Need to make them from scratch
with nl.notify('Creating blurred datasets'):
old_errts = decon.errts
decon.errts = 'residual.nii.gz'
decon.prefix = os.path.basename(decon.prefix)
# Run once in place to get the residual dataset
decon.run()
running_reps = 0
for dset in decon.input_dsets:
info = nl.dset_info(dset)
residual_dset = nl.suffix(dset,'_residual')
nl.run(['3dbucket','-prefix',residual_dset,'%s[%d..%d]'%(decon.errts,running_reps,running_reps+info.reps-1)],products=residual_dset)
cmd = ['3dBlurToFWHM','-quiet','-input',dset,'-blurmaster',residual_dset,'-prefix',blur_dset(dset),'-FWHM',fwhm]
if decon.mask:
if decon.mask=='auto':
cmd += ['-automask']
else:
cmd += ['-mask',decon.mask]
nl.run(cmd,products=blur_dset(dset))
running_reps += info.reps
if cache:
copyback_files.append(blur_dset(dset))
decon.errts = old_errts
decon.input_dsets = [blur_dset(dset) for dset in decon.input_dsets]
for d in [decon.prefix,decon.errts]:
if os.path.exists(d):
try:
os.remove(d)
except:
pass
decon.run()
for copyfile in copyback_files:
if os.path.exists(copyfile):
shutil.copy(copyfile,cwd)
else:
nl.notify('Warning: deconvolve did not produce expected file %s' % decon.prefix,level=nl.level.warning)
except:
raise
finally:
shutil.rmtree(tmpdir,True) | python | def smooth_decon_to_fwhm(decon,fwhm,cache=True):
'''takes an input :class:`Decon` object and uses ``3dBlurToFWHM`` to make the output as close as possible to ``fwhm``
returns the final measured fwhm. If ``cache`` is ``True``, will save the blurred input file (and use it again in the future)'''
if os.path.exists(decon.prefix):
return
blur_dset = lambda dset: nl.suffix(dset,'_smooth_to_%.2f' % fwhm)
with nl.notify('Running smooth_decon_to_fwhm analysis (with %.2fmm blur)' % fwhm):
tmpdir = tempfile.mkdtemp()
try:
cwd = os.getcwd()
random_files = [re.sub(r'\[\d+\]$','',str(x)) for x in nl.flatten([x for x in decon.__dict__.values() if isinstance(x,basestring) or isinstance(x,list)]+[x.values() for x in decon.__dict__.values() if isinstance(x,dict)])]
files_to_copy = [x for x in random_files if os.path.exists(x) and x[0]!='/']
files_to_copy += [blur_dset(dset) for dset in decon.input_dsets if os.path.exists(blur_dset(dset))]
# copy crap
for file in files_to_copy:
try:
shutil.copytree(file,tmpdir)
except OSError as e:
shutil.copy(file,tmpdir)
shutil.copy(file,tmpdir)
copyback_files = [decon.prefix,decon.errts]
with nl.run_in(tmpdir):
if os.path.exists(decon.prefix):
os.remove(decon.prefix)
# Create the blurred inputs (or load from cache)
if cache and all([os.path.exists(os.path.join(cwd,blur_dset(dset))) for dset in decon.input_dsets]):
# Everything is already cached...
nl.notify('Using cache\'d blurred datasets')
else:
# Need to make them from scratch
with nl.notify('Creating blurred datasets'):
old_errts = decon.errts
decon.errts = 'residual.nii.gz'
decon.prefix = os.path.basename(decon.prefix)
# Run once in place to get the residual dataset
decon.run()
running_reps = 0
for dset in decon.input_dsets:
info = nl.dset_info(dset)
residual_dset = nl.suffix(dset,'_residual')
nl.run(['3dbucket','-prefix',residual_dset,'%s[%d..%d]'%(decon.errts,running_reps,running_reps+info.reps-1)],products=residual_dset)
cmd = ['3dBlurToFWHM','-quiet','-input',dset,'-blurmaster',residual_dset,'-prefix',blur_dset(dset),'-FWHM',fwhm]
if decon.mask:
if decon.mask=='auto':
cmd += ['-automask']
else:
cmd += ['-mask',decon.mask]
nl.run(cmd,products=blur_dset(dset))
running_reps += info.reps
if cache:
copyback_files.append(blur_dset(dset))
decon.errts = old_errts
decon.input_dsets = [blur_dset(dset) for dset in decon.input_dsets]
for d in [decon.prefix,decon.errts]:
if os.path.exists(d):
try:
os.remove(d)
except:
pass
decon.run()
for copyfile in copyback_files:
if os.path.exists(copyfile):
shutil.copy(copyfile,cwd)
else:
nl.notify('Warning: deconvolve did not produce expected file %s' % decon.prefix,level=nl.level.warning)
except:
raise
finally:
shutil.rmtree(tmpdir,True) | [
"def",
"smooth_decon_to_fwhm",
"(",
"decon",
",",
"fwhm",
",",
"cache",
"=",
"True",
")",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"decon",
".",
"prefix",
")",
":",
"return",
"blur_dset",
"=",
"lambda",
"dset",
":",
"nl",
".",
"suffix",
"(",... | takes an input :class:`Decon` object and uses ``3dBlurToFWHM`` to make the output as close as possible to ``fwhm``
returns the final measured fwhm. If ``cache`` is ``True``, will save the blurred input file (and use it again in the future) | [
"takes",
"an",
"input",
":",
"class",
":",
"Decon",
"object",
"and",
"uses",
"3dBlurToFWHM",
"to",
"make",
"the",
"output",
"as",
"close",
"as",
"possible",
"to",
"fwhm",
"returns",
"the",
"final",
"measured",
"fwhm",
".",
"If",
"cache",
"is",
"True",
"w... | train | https://github.com/azraq27/neural/blob/fe91bfeecbf73ad99708cf5dca66cb61fcd529f5/neural/decon.py#L459-L530 |
azraq27/neural | neural/decon.py | Decon.command_list | def command_list(self):
'''returns the 3dDeconvolve command as a list
The list returned can be run by passing it into a subprocess-like command
(e.g., neural.run())
'''
cmd = ['3dDeconvolve']
cmd += ['-jobs',multiprocessing.cpu_count()]
cmd += self.opts
if(len(self.input_dsets)):
cmd += ['-input'] + ['%s[%d..%d]' % (dset,self.partial[dset][0],self.partial[dset][1]) if dset in self.partial else dset for dset in self.input_dsets]
else:
cmd += ['-nodata']
if self.reps:
cmd += [str(self.reps)]
if self.TR:
cmd += [str(self.TR)]
if self.censor_file:
censor_file = self.censor_file
if self.partial:
# This assumes only one dataset!
with open(censor_file) as inf:
censor = inf.read().split()[self.partial.values()[0][0]:self.partial.values()[0][1]+1]
with tempfile.NamedTemporaryFile(delete=False) as f:
f.write('\n'.join(censor))
censor_file = f.name
self._del_files.append(f.name)
cmd += ['-censor', censor_file]
nfirst = self.nfirst
if len(self.input_dsets) and self.input_dsets[0] in self.partial:
nfirst -= self.partial[self.input_dsets[0]][0]
if nfirst<0:
nfirst = 0
cmd += ['-nfirst',str(nfirst)]
if self.mask:
if self.mask=='auto':
cmd += ['-automask']
else:
cmd += ['-mask',self.mask]
cmd += ['-polort',str(self.polort)]
stim_num = 1
all_stims = list(self.decon_stims)
all_stims += [DeconStim(stim,column_file=self.stim_files[stim],base=(stim in self.stim_base)) for stim in self.stim_files]
for stim in self.stim_times:
decon_stim = DeconStim(stim,times_file=self.stim_times[stim])
decon_stim.times_model = self.models[stim] if stim in self.models else self.model_default
decon_stim.AM1 = (stim in self.stim_am1)
decon_stim.AM2 = (stim in self.stim_am2)
decon_stim.base = (stim in self.stim_base)
all_stims.append(decon_stim)
if self.partial:
for i in xrange(len(self.input_dsets)):
if self.input_dsets[i] in self.partial:
new_stims = []
for stim in all_stims:
stim = stim.partial(self.partial[self.input_dsets[i]][0],self.partial[self.input_dsets[i]][1],i)
if stim:
new_stims.append(stim)
all_stims = new_stims
cmd += ['-num_stimts',len(all_stims)]
stimautoname = lambda d,s: 'stimfile_auto-%d-%s_' % (d,s.name) + str(datetime.datetime.now()).replace(" ","_").replace(":",".")
for stim in all_stims:
column_file = stim.column_file
if stim.column!=None:
column_file = stimautoname(stim_num,stim)
with open(column_file,"w") as f:
f.write('\n'.join([str(x) for x in stim.column]))
if column_file:
cmd += ['-stim_file',stim_num,column_file,'-stim_label',stim_num,stim.name]
if stim.base:
cmd += ['-stim_base',stim_num]
stim_num += 1
continue
times_file = stim.times_file
if stim.times!=None:
times = list(stim.times)
if '__iter__' not in dir(times[0]):
# a single list
times = [times]
times_file = stimautoname(stim_num,stim)
with open(times_file,"w") as f:
f.write('\n'.join([' '.join([str(x) for x in y]) if len(y)>0 else '*' for y in times]))
if times_file:
opt = '-stim_times'
if stim.AM1:
opt = '-stim_times_AM1'
if stim.AM2:
opt = '-stim_times_AM2'
cmd += [opt,stim_num,times_file,stim.times_model]
cmd += ['-stim_label',stim_num,stim.name]
if stim.base:
cmd += ['-stim_base',stim_num]
stim_num += 1
strip_number = r'[-+]?(\d+)?\*?(\w+)(\[.*?\])?'
all_glts = {}
stim_names = [stim.name for stim in all_stims]
if self.validate_glts:
for glt in self.glts:
ok = True
for stim in self.glts[glt].split():
m = re.match(strip_number,stim)
if m:
stim = m.group(2)
if stim not in stim_names:
ok = False
if ok:
all_glts[glt] = self.glts[glt]
else:
all_glts = self.glts
cmd += ['-num_glt',len(all_glts)]
glt_num = 1
for glt in all_glts:
cmd += ['-gltsym','SYM: %s' % all_glts[glt],'-glt_label',glt_num,glt]
glt_num += 1
if self.bout:
cmd += ['-bout']
if self.tout:
cmd += ['-tout']
if self.vout:
cmd += ['-vout']
if self.rout:
cmd += ['-rout']
if self.errts:
cmd += ['-errts', self.errts]
if self.prefix:
cmd += ['-bucket', self.prefix]
return [str(x) for x in cmd] | python | def command_list(self):
'''returns the 3dDeconvolve command as a list
The list returned can be run by passing it into a subprocess-like command
(e.g., neural.run())
'''
cmd = ['3dDeconvolve']
cmd += ['-jobs',multiprocessing.cpu_count()]
cmd += self.opts
if(len(self.input_dsets)):
cmd += ['-input'] + ['%s[%d..%d]' % (dset,self.partial[dset][0],self.partial[dset][1]) if dset in self.partial else dset for dset in self.input_dsets]
else:
cmd += ['-nodata']
if self.reps:
cmd += [str(self.reps)]
if self.TR:
cmd += [str(self.TR)]
if self.censor_file:
censor_file = self.censor_file
if self.partial:
# This assumes only one dataset!
with open(censor_file) as inf:
censor = inf.read().split()[self.partial.values()[0][0]:self.partial.values()[0][1]+1]
with tempfile.NamedTemporaryFile(delete=False) as f:
f.write('\n'.join(censor))
censor_file = f.name
self._del_files.append(f.name)
cmd += ['-censor', censor_file]
nfirst = self.nfirst
if len(self.input_dsets) and self.input_dsets[0] in self.partial:
nfirst -= self.partial[self.input_dsets[0]][0]
if nfirst<0:
nfirst = 0
cmd += ['-nfirst',str(nfirst)]
if self.mask:
if self.mask=='auto':
cmd += ['-automask']
else:
cmd += ['-mask',self.mask]
cmd += ['-polort',str(self.polort)]
stim_num = 1
all_stims = list(self.decon_stims)
all_stims += [DeconStim(stim,column_file=self.stim_files[stim],base=(stim in self.stim_base)) for stim in self.stim_files]
for stim in self.stim_times:
decon_stim = DeconStim(stim,times_file=self.stim_times[stim])
decon_stim.times_model = self.models[stim] if stim in self.models else self.model_default
decon_stim.AM1 = (stim in self.stim_am1)
decon_stim.AM2 = (stim in self.stim_am2)
decon_stim.base = (stim in self.stim_base)
all_stims.append(decon_stim)
if self.partial:
for i in xrange(len(self.input_dsets)):
if self.input_dsets[i] in self.partial:
new_stims = []
for stim in all_stims:
stim = stim.partial(self.partial[self.input_dsets[i]][0],self.partial[self.input_dsets[i]][1],i)
if stim:
new_stims.append(stim)
all_stims = new_stims
cmd += ['-num_stimts',len(all_stims)]
stimautoname = lambda d,s: 'stimfile_auto-%d-%s_' % (d,s.name) + str(datetime.datetime.now()).replace(" ","_").replace(":",".")
for stim in all_stims:
column_file = stim.column_file
if stim.column!=None:
column_file = stimautoname(stim_num,stim)
with open(column_file,"w") as f:
f.write('\n'.join([str(x) for x in stim.column]))
if column_file:
cmd += ['-stim_file',stim_num,column_file,'-stim_label',stim_num,stim.name]
if stim.base:
cmd += ['-stim_base',stim_num]
stim_num += 1
continue
times_file = stim.times_file
if stim.times!=None:
times = list(stim.times)
if '__iter__' not in dir(times[0]):
# a single list
times = [times]
times_file = stimautoname(stim_num,stim)
with open(times_file,"w") as f:
f.write('\n'.join([' '.join([str(x) for x in y]) if len(y)>0 else '*' for y in times]))
if times_file:
opt = '-stim_times'
if stim.AM1:
opt = '-stim_times_AM1'
if stim.AM2:
opt = '-stim_times_AM2'
cmd += [opt,stim_num,times_file,stim.times_model]
cmd += ['-stim_label',stim_num,stim.name]
if stim.base:
cmd += ['-stim_base',stim_num]
stim_num += 1
strip_number = r'[-+]?(\d+)?\*?(\w+)(\[.*?\])?'
all_glts = {}
stim_names = [stim.name for stim in all_stims]
if self.validate_glts:
for glt in self.glts:
ok = True
for stim in self.glts[glt].split():
m = re.match(strip_number,stim)
if m:
stim = m.group(2)
if stim not in stim_names:
ok = False
if ok:
all_glts[glt] = self.glts[glt]
else:
all_glts = self.glts
cmd += ['-num_glt',len(all_glts)]
glt_num = 1
for glt in all_glts:
cmd += ['-gltsym','SYM: %s' % all_glts[glt],'-glt_label',glt_num,glt]
glt_num += 1
if self.bout:
cmd += ['-bout']
if self.tout:
cmd += ['-tout']
if self.vout:
cmd += ['-vout']
if self.rout:
cmd += ['-rout']
if self.errts:
cmd += ['-errts', self.errts]
if self.prefix:
cmd += ['-bucket', self.prefix]
return [str(x) for x in cmd] | [
"def",
"command_list",
"(",
"self",
")",
":",
"cmd",
"=",
"[",
"'3dDeconvolve'",
"]",
"cmd",
"+=",
"[",
"'-jobs'",
",",
"multiprocessing",
".",
"cpu_count",
"(",
")",
"]",
"cmd",
"+=",
"self",
".",
"opts",
"if",
"(",
"len",
"(",
"self",
".",
"input_d... | returns the 3dDeconvolve command as a list
The list returned can be run by passing it into a subprocess-like command
(e.g., neural.run()) | [
"returns",
"the",
"3dDeconvolve",
"command",
"as",
"a",
"list"
] | train | https://github.com/azraq27/neural/blob/fe91bfeecbf73ad99708cf5dca66cb61fcd529f5/neural/decon.py#L99-L239 |
azraq27/neural | neural/decon.py | Decon.run | def run(self):
'''runs 3dDeconvolve through the neural.utils.run shortcut'''
out = nl.run(self.command_list(),products=self.prefix)
if out and out.output:
sds_list = re.findall(r'Stimulus: (.*?) *\n +h\[ 0\] norm\. std\. dev\. = +(\d+\.\d+)',out.output)
self.stim_sds = {}
for s in sds_list:
self.stim_sds[s[0]] = float(s[1]) | python | def run(self):
'''runs 3dDeconvolve through the neural.utils.run shortcut'''
out = nl.run(self.command_list(),products=self.prefix)
if out and out.output:
sds_list = re.findall(r'Stimulus: (.*?) *\n +h\[ 0\] norm\. std\. dev\. = +(\d+\.\d+)',out.output)
self.stim_sds = {}
for s in sds_list:
self.stim_sds[s[0]] = float(s[1]) | [
"def",
"run",
"(",
"self",
")",
":",
"out",
"=",
"nl",
".",
"run",
"(",
"self",
".",
"command_list",
"(",
")",
",",
"products",
"=",
"self",
".",
"prefix",
")",
"if",
"out",
"and",
"out",
".",
"output",
":",
"sds_list",
"=",
"re",
".",
"findall",... | runs 3dDeconvolve through the neural.utils.run shortcut | [
"runs",
"3dDeconvolve",
"through",
"the",
"neural",
".",
"utils",
".",
"run",
"shortcut"
] | train | https://github.com/azraq27/neural/blob/fe91bfeecbf73ad99708cf5dca66cb61fcd529f5/neural/decon.py#L255-L262 |
azraq27/neural | neural/decon.py | DeconStim.type | def type(self):
'''returns kind of stim ("column" or "times"), based on what parameters are set'''
if self.column!=None or self.column_file:
return "column"
if self.times!=None or self.times_file:
return "times"
return None | python | def type(self):
'''returns kind of stim ("column" or "times"), based on what parameters are set'''
if self.column!=None or self.column_file:
return "column"
if self.times!=None or self.times_file:
return "times"
return None | [
"def",
"type",
"(",
"self",
")",
":",
"if",
"self",
".",
"column",
"!=",
"None",
"or",
"self",
".",
"column_file",
":",
"return",
"\"column\"",
"if",
"self",
".",
"times",
"!=",
"None",
"or",
"self",
".",
"times_file",
":",
"return",
"\"times\"",
"retu... | returns kind of stim ("column" or "times"), based on what parameters are set | [
"returns",
"kind",
"of",
"stim",
"(",
"column",
"or",
"times",
")",
"based",
"on",
"what",
"parameters",
"are",
"set"
] | train | https://github.com/azraq27/neural/blob/fe91bfeecbf73ad99708cf5dca66cb61fcd529f5/neural/decon.py#L304-L310 |
azraq27/neural | neural/decon.py | DeconStim.read_file | def read_file(self):
'''if this is stored in a file, read it into self.column'''
column_selector = r'(.*)\[(\d+)\]$'
if self.column_file:
column = None
m = re.match(column_selector,self.column_file)
file = self.column_file
if m:
file = m.group(1)
column = int(m.group(2))
with open(file) as f:
lines = f.read().split('\n')
if column!=None:
lines = [x.split()[column] for x in lines]
self.column = [nl.numberize(x) for x in lines]
self.column_file = None
if self.times_file:
with open(self.times_file) as f:
self.times = [[nl.numberize(x) for x in y.split()] for y in f.read().split('\n')]
self.times_file = None | python | def read_file(self):
'''if this is stored in a file, read it into self.column'''
column_selector = r'(.*)\[(\d+)\]$'
if self.column_file:
column = None
m = re.match(column_selector,self.column_file)
file = self.column_file
if m:
file = m.group(1)
column = int(m.group(2))
with open(file) as f:
lines = f.read().split('\n')
if column!=None:
lines = [x.split()[column] for x in lines]
self.column = [nl.numberize(x) for x in lines]
self.column_file = None
if self.times_file:
with open(self.times_file) as f:
self.times = [[nl.numberize(x) for x in y.split()] for y in f.read().split('\n')]
self.times_file = None | [
"def",
"read_file",
"(",
"self",
")",
":",
"column_selector",
"=",
"r'(.*)\\[(\\d+)\\]$'",
"if",
"self",
".",
"column_file",
":",
"column",
"=",
"None",
"m",
"=",
"re",
".",
"match",
"(",
"column_selector",
",",
"self",
".",
"column_file",
")",
"file",
"="... | if this is stored in a file, read it into self.column | [
"if",
"this",
"is",
"stored",
"in",
"a",
"file",
"read",
"it",
"into",
"self",
".",
"column"
] | train | https://github.com/azraq27/neural/blob/fe91bfeecbf73ad99708cf5dca66cb61fcd529f5/neural/decon.py#L312-L331 |
azraq27/neural | neural/decon.py | DeconStim.blank_stim | def blank_stim(self,type=None,fill=0):
'''Makes a blank version of stim. If a type is not given, returned as same type as current stim.
If a column stim, will fill in blanks with ``fill``'''
blank = copy.copy(self)
blank.name = 'Blank'
if type==None:
type = self.type()
if type=="column":
num_reps = self.reps
if num_reps==None:
if self.type()=="column":
self.read_file()
num_reps = len(self.column)
else:
nl.notify('Error: requested to return a blank column, but I can\'t figure out how many reps to make it!',level=nl.level.error)
blank.column = [fill]*num_reps
return blank
if type=="times":
blank.times = []
return blank | python | def blank_stim(self,type=None,fill=0):
'''Makes a blank version of stim. If a type is not given, returned as same type as current stim.
If a column stim, will fill in blanks with ``fill``'''
blank = copy.copy(self)
blank.name = 'Blank'
if type==None:
type = self.type()
if type=="column":
num_reps = self.reps
if num_reps==None:
if self.type()=="column":
self.read_file()
num_reps = len(self.column)
else:
nl.notify('Error: requested to return a blank column, but I can\'t figure out how many reps to make it!',level=nl.level.error)
blank.column = [fill]*num_reps
return blank
if type=="times":
blank.times = []
return blank | [
"def",
"blank_stim",
"(",
"self",
",",
"type",
"=",
"None",
",",
"fill",
"=",
"0",
")",
":",
"blank",
"=",
"copy",
".",
"copy",
"(",
"self",
")",
"blank",
".",
"name",
"=",
"'Blank'",
"if",
"type",
"==",
"None",
":",
"type",
"=",
"self",
".",
"... | Makes a blank version of stim. If a type is not given, returned as same type as current stim.
If a column stim, will fill in blanks with ``fill`` | [
"Makes",
"a",
"blank",
"version",
"of",
"stim",
".",
"If",
"a",
"type",
"is",
"not",
"given",
"returned",
"as",
"same",
"type",
"as",
"current",
"stim",
".",
"If",
"a",
"column",
"stim",
"will",
"fill",
"in",
"blanks",
"with",
"fill"
] | train | https://github.com/azraq27/neural/blob/fe91bfeecbf73ad99708cf5dca66cb61fcd529f5/neural/decon.py#L333-L352 |
azraq27/neural | neural/decon.py | DeconStim.concat_stim | def concat_stim(self,decon_stim):
'''concatenate this to another :class:`DeconStim` of the same "type"'''
if self.type()!=decon_stim.type():
nl.notify('Error: Trying to concatenate stimuli of different types! %s (%s) with %s (%s)' % (self.name,self.type(),decon_stim.name,decon_stim.type()),level=nl.level.error)
return None
concat_stim = copy.copy(self)
if self.name=='Blank':
concat_stim = copy.copy(decon_stim)
self.read_file()
if self.type()=="column":
# if an explicit # of reps is given, concat to that
reps = [x.reps if x.reps else len(x.column) for x in [self,decon_stim]]
concat_stim.column = self.column[:reps[0]] + decon_stim.column[:reps[1]]
return concat_stim
if self.type()=="times":
if len(self.times)==0 or '__iter__' not in dir(self.times[0]):
self.times = [self.times]
if len(decon_stim.times)==0 or '__iter__' not in dir(decon_stim.times[0]):
decon_stim.times = [decon_stim.times]
concat_stim.times = self.times + decon_stim.times
return concat_stim
return None | python | def concat_stim(self,decon_stim):
'''concatenate this to another :class:`DeconStim` of the same "type"'''
if self.type()!=decon_stim.type():
nl.notify('Error: Trying to concatenate stimuli of different types! %s (%s) with %s (%s)' % (self.name,self.type(),decon_stim.name,decon_stim.type()),level=nl.level.error)
return None
concat_stim = copy.copy(self)
if self.name=='Blank':
concat_stim = copy.copy(decon_stim)
self.read_file()
if self.type()=="column":
# if an explicit # of reps is given, concat to that
reps = [x.reps if x.reps else len(x.column) for x in [self,decon_stim]]
concat_stim.column = self.column[:reps[0]] + decon_stim.column[:reps[1]]
return concat_stim
if self.type()=="times":
if len(self.times)==0 or '__iter__' not in dir(self.times[0]):
self.times = [self.times]
if len(decon_stim.times)==0 or '__iter__' not in dir(decon_stim.times[0]):
decon_stim.times = [decon_stim.times]
concat_stim.times = self.times + decon_stim.times
return concat_stim
return None | [
"def",
"concat_stim",
"(",
"self",
",",
"decon_stim",
")",
":",
"if",
"self",
".",
"type",
"(",
")",
"!=",
"decon_stim",
".",
"type",
"(",
")",
":",
"nl",
".",
"notify",
"(",
"'Error: Trying to concatenate stimuli of different types! %s (%s) with %s (%s)'",
"%",
... | concatenate this to another :class:`DeconStim` of the same "type" | [
"concatenate",
"this",
"to",
"another",
":",
"class",
":",
"DeconStim",
"of",
"the",
"same",
"type"
] | train | https://github.com/azraq27/neural/blob/fe91bfeecbf73ad99708cf5dca66cb61fcd529f5/neural/decon.py#L354-L376 |
azraq27/neural | neural/decon.py | DeconStim.partial | def partial(self,start=0,end=None,run=0):
'''chops the stimulus by only including time points ``start`` through ``end`` (in reps, inclusive; ``None``=until the end)
if using stim_times-style simulus, will change the ``run``'th run. If a column, will just chop the column'''
self.read_file()
decon_stim = copy.copy(self)
if start<0:
start = 0
if self.type()=="column":
decon_stim.column_file = None
if end>=len(decon_stim.column):
end = None
if end==None:
decon_stim.column = decon_stim.column[start:]
else:
decon_stim.column = decon_stim.column[start:end+1]
if len(decon_stim.column)==0:
return None
if self.type()=="times":
if self.TR==None:
nl.notify('Error: cannot get partial segment of a stim_times stimulus without a TR',level=nl.level.error)
return None
def time_in(a):
first_number = r'^(\d+(\.\d+)?)'
if isinstance(a,basestring):
m = re.match(first_number,a)
if m:
a = m.group(1)
else:
nl.notify('Warning: cannot intepret a number from the stim_time: "%s"' % a,level=nl.level.warning)
return False
a = float(a)/self.TR
if a>=start and (end==None or a<=end):
return True
return False
decon_stim.times_file = None
if len(decon_stim.times)==0 or '__iter__' not in dir(decon_stim.times[0]):
decon_stim.times = [decon_stim.times]
decon_stim.times[run] = [x for x in decon_stim.times[run] if time_in(x)]
if len(nl.flatten(decon_stim.times))==0:
return None
return decon_stim | python | def partial(self,start=0,end=None,run=0):
'''chops the stimulus by only including time points ``start`` through ``end`` (in reps, inclusive; ``None``=until the end)
if using stim_times-style simulus, will change the ``run``'th run. If a column, will just chop the column'''
self.read_file()
decon_stim = copy.copy(self)
if start<0:
start = 0
if self.type()=="column":
decon_stim.column_file = None
if end>=len(decon_stim.column):
end = None
if end==None:
decon_stim.column = decon_stim.column[start:]
else:
decon_stim.column = decon_stim.column[start:end+1]
if len(decon_stim.column)==0:
return None
if self.type()=="times":
if self.TR==None:
nl.notify('Error: cannot get partial segment of a stim_times stimulus without a TR',level=nl.level.error)
return None
def time_in(a):
first_number = r'^(\d+(\.\d+)?)'
if isinstance(a,basestring):
m = re.match(first_number,a)
if m:
a = m.group(1)
else:
nl.notify('Warning: cannot intepret a number from the stim_time: "%s"' % a,level=nl.level.warning)
return False
a = float(a)/self.TR
if a>=start and (end==None or a<=end):
return True
return False
decon_stim.times_file = None
if len(decon_stim.times)==0 or '__iter__' not in dir(decon_stim.times[0]):
decon_stim.times = [decon_stim.times]
decon_stim.times[run] = [x for x in decon_stim.times[run] if time_in(x)]
if len(nl.flatten(decon_stim.times))==0:
return None
return decon_stim | [
"def",
"partial",
"(",
"self",
",",
"start",
"=",
"0",
",",
"end",
"=",
"None",
",",
"run",
"=",
"0",
")",
":",
"self",
".",
"read_file",
"(",
")",
"decon_stim",
"=",
"copy",
".",
"copy",
"(",
"self",
")",
"if",
"start",
"<",
"0",
":",
"start",... | chops the stimulus by only including time points ``start`` through ``end`` (in reps, inclusive; ``None``=until the end)
if using stim_times-style simulus, will change the ``run``'th run. If a column, will just chop the column | [
"chops",
"the",
"stimulus",
"by",
"only",
"including",
"time",
"points",
"start",
"through",
"end",
"(",
"in",
"reps",
"inclusive",
";",
"None",
"=",
"until",
"the",
"end",
")",
"if",
"using",
"stim_times",
"-",
"style",
"simulus",
"will",
"change",
"the",... | train | https://github.com/azraq27/neural/blob/fe91bfeecbf73ad99708cf5dca66cb61fcd529f5/neural/decon.py#L378-L419 |
cohorte/cohorte-herald | python/herald/beans.py | DelayedNotification.notify | def notify(self):
"""
Calls the notification method
:return: True if the notification method has been called
"""
if self.__method is not None:
self.__method(self.__peer)
return True
return False | python | def notify(self):
"""
Calls the notification method
:return: True if the notification method has been called
"""
if self.__method is not None:
self.__method(self.__peer)
return True
return False | [
"def",
"notify",
"(",
"self",
")",
":",
"if",
"self",
".",
"__method",
"is",
"not",
"None",
":",
"self",
".",
"__method",
"(",
"self",
".",
"__peer",
")",
"return",
"True",
"return",
"False"
] | Calls the notification method
:return: True if the notification method has been called | [
"Calls",
"the",
"notification",
"method"
] | train | https://github.com/cohorte/cohorte-herald/blob/bb3445d0031c8b3abad71e6219cc559b49faa3ee/python/herald/beans.py#L387-L396 |
fredericklussier/ObservablePy | observablePy/Observable.py | Observable.observeState | def observeState(self, call=None):
"""
Registers an observer to the any changes.
The called function should have 2 parameters:
- previousState,
- actualState
:param func call: The function to call.
When not given, decorator usage is assumed.
:return: the function to call once state change.
:rtype: func
:raises TypeError: if the called function is not callable
=================
How to use it
=================
-----------------
1. Calling the function
-----------------
.. code-block:: python
instance.observeState(functionName)
instance.observeState(functionName)
...
def functionName(previousState, actualState):
-----------------
2. Using Decoration
-----------------
.. code-block:: python
@instance.observeState()
def functionName(previousState, actualState):
@instance.observeState()
def functionName(previousState, actualState):
"""
def _observe(call):
self.__observers.add("*", call)
return call
if call is not None:
return _observe(call)
else:
return _observe | python | def observeState(self, call=None):
"""
Registers an observer to the any changes.
The called function should have 2 parameters:
- previousState,
- actualState
:param func call: The function to call.
When not given, decorator usage is assumed.
:return: the function to call once state change.
:rtype: func
:raises TypeError: if the called function is not callable
=================
How to use it
=================
-----------------
1. Calling the function
-----------------
.. code-block:: python
instance.observeState(functionName)
instance.observeState(functionName)
...
def functionName(previousState, actualState):
-----------------
2. Using Decoration
-----------------
.. code-block:: python
@instance.observeState()
def functionName(previousState, actualState):
@instance.observeState()
def functionName(previousState, actualState):
"""
def _observe(call):
self.__observers.add("*", call)
return call
if call is not None:
return _observe(call)
else:
return _observe | [
"def",
"observeState",
"(",
"self",
",",
"call",
"=",
"None",
")",
":",
"def",
"_observe",
"(",
"call",
")",
":",
"self",
".",
"__observers",
".",
"add",
"(",
"\"*\"",
",",
"call",
")",
"return",
"call",
"if",
"call",
"is",
"not",
"None",
":",
"ret... | Registers an observer to the any changes.
The called function should have 2 parameters:
- previousState,
- actualState
:param func call: The function to call.
When not given, decorator usage is assumed.
:return: the function to call once state change.
:rtype: func
:raises TypeError: if the called function is not callable
=================
How to use it
=================
-----------------
1. Calling the function
-----------------
.. code-block:: python
instance.observeState(functionName)
instance.observeState(functionName)
...
def functionName(previousState, actualState):
-----------------
2. Using Decoration
-----------------
.. code-block:: python
@instance.observeState()
def functionName(previousState, actualState):
@instance.observeState()
def functionName(previousState, actualState): | [
"Registers",
"an",
"observer",
"to",
"the",
"any",
"changes",
".",
"The",
"called",
"function",
"should",
"have",
"2",
"parameters",
":",
"-",
"previousState",
"-",
"actualState"
] | train | https://github.com/fredericklussier/ObservablePy/blob/fd7926a0568621f80b1d567d18f199976f1fa4e8/observablePy/Observable.py#L152-L195 |
fredericklussier/ObservablePy | observablePy/Observable.py | Observable.observeElements | def observeElements(self, what, call=None):
"""
Registers an observer function to a specific state field or
list of state fields.
The function to call should have 2 parameters:
- previousValue,
-actualValue
:param what: name of the state field or names of the
state field to observe.
:type what: str | array
:param func call: The function to call. When not given,
decorator usage is assumed.
:return: the function to call once state change.
:rtype: func
:raises TypeError: if the called function is not callable
=================
How to use it
=================
-----------------
1. Calling the function
-----------------
.. code-block:: python
instance.observeFields("FieldName", functionName)
instance.observeFields(["FieldName1","FieldName2"], functionName)
...
def functionName(previousState, actualState):
-----------------
2. Using Decoration
-----------------
.. code-block:: python
@instance.observeFields("FieldName")
def functionName(previousValue, actualValue):
@instance.observeFields(["FieldName1","FieldName2"])
def functionName(previousValue, actualValue):
"""
def _observe(call):
self.__observers.add(what, call)
return call
toEvaluate = []
if isinstance(what, str):
toEvaluate.append(what)
else:
toEvaluate = what
if not self.areObservableElements(toEvaluate):
msg = 'Could not find observable element named "{0}" in {1}'
raise ValueError(msg.format(what, self.__class__))
if call is not None:
return _observe(call)
else:
return _observe | python | def observeElements(self, what, call=None):
"""
Registers an observer function to a specific state field or
list of state fields.
The function to call should have 2 parameters:
- previousValue,
-actualValue
:param what: name of the state field or names of the
state field to observe.
:type what: str | array
:param func call: The function to call. When not given,
decorator usage is assumed.
:return: the function to call once state change.
:rtype: func
:raises TypeError: if the called function is not callable
=================
How to use it
=================
-----------------
1. Calling the function
-----------------
.. code-block:: python
instance.observeFields("FieldName", functionName)
instance.observeFields(["FieldName1","FieldName2"], functionName)
...
def functionName(previousState, actualState):
-----------------
2. Using Decoration
-----------------
.. code-block:: python
@instance.observeFields("FieldName")
def functionName(previousValue, actualValue):
@instance.observeFields(["FieldName1","FieldName2"])
def functionName(previousValue, actualValue):
"""
def _observe(call):
self.__observers.add(what, call)
return call
toEvaluate = []
if isinstance(what, str):
toEvaluate.append(what)
else:
toEvaluate = what
if not self.areObservableElements(toEvaluate):
msg = 'Could not find observable element named "{0}" in {1}'
raise ValueError(msg.format(what, self.__class__))
if call is not None:
return _observe(call)
else:
return _observe | [
"def",
"observeElements",
"(",
"self",
",",
"what",
",",
"call",
"=",
"None",
")",
":",
"def",
"_observe",
"(",
"call",
")",
":",
"self",
".",
"__observers",
".",
"add",
"(",
"what",
",",
"call",
")",
"return",
"call",
"toEvaluate",
"=",
"[",
"]",
... | Registers an observer function to a specific state field or
list of state fields.
The function to call should have 2 parameters:
- previousValue,
-actualValue
:param what: name of the state field or names of the
state field to observe.
:type what: str | array
:param func call: The function to call. When not given,
decorator usage is assumed.
:return: the function to call once state change.
:rtype: func
:raises TypeError: if the called function is not callable
=================
How to use it
=================
-----------------
1. Calling the function
-----------------
.. code-block:: python
instance.observeFields("FieldName", functionName)
instance.observeFields(["FieldName1","FieldName2"], functionName)
...
def functionName(previousState, actualState):
-----------------
2. Using Decoration
-----------------
.. code-block:: python
@instance.observeFields("FieldName")
def functionName(previousValue, actualValue):
@instance.observeFields(["FieldName1","FieldName2"])
def functionName(previousValue, actualValue): | [
"Registers",
"an",
"observer",
"function",
"to",
"a",
"specific",
"state",
"field",
"or",
"list",
"of",
"state",
"fields",
".",
"The",
"function",
"to",
"call",
"should",
"have",
"2",
"parameters",
":",
"-",
"previousValue",
"-",
"actualValue"
] | train | https://github.com/fredericklussier/ObservablePy/blob/fd7926a0568621f80b1d567d18f199976f1fa4e8/observablePy/Observable.py#L203-L260 |
bioidiap/gridtk | gridtk/script/jman.py | setup | def setup(args):
"""Returns the JobManager and sets up the basic infrastructure"""
kwargs = {'wrapper_script' : args.wrapper_script, 'debug' : args.verbose==3, 'database' : args.database}
if args.local:
jm = local.JobManagerLocal(**kwargs)
else:
jm = sge.JobManagerSGE(**kwargs)
# set-up logging
if args.verbose not in range(0,4):
raise ValueError("The verbosity level %d does not exist. Please reduce the number of '--verbose' parameters in your call to maximum 3" % level)
# set up the verbosity level of the logging system
log_level = {
0: logging.ERROR,
1: logging.WARNING,
2: logging.INFO,
3: logging.DEBUG
}[args.verbose]
handler = logging.StreamHandler()
handler.setFormatter(logging.Formatter("%(asctime)s %(levelname)s %(name)s: %(message)s"))
logger.addHandler(handler)
logger.setLevel(log_level)
return jm | python | def setup(args):
"""Returns the JobManager and sets up the basic infrastructure"""
kwargs = {'wrapper_script' : args.wrapper_script, 'debug' : args.verbose==3, 'database' : args.database}
if args.local:
jm = local.JobManagerLocal(**kwargs)
else:
jm = sge.JobManagerSGE(**kwargs)
# set-up logging
if args.verbose not in range(0,4):
raise ValueError("The verbosity level %d does not exist. Please reduce the number of '--verbose' parameters in your call to maximum 3" % level)
# set up the verbosity level of the logging system
log_level = {
0: logging.ERROR,
1: logging.WARNING,
2: logging.INFO,
3: logging.DEBUG
}[args.verbose]
handler = logging.StreamHandler()
handler.setFormatter(logging.Formatter("%(asctime)s %(levelname)s %(name)s: %(message)s"))
logger.addHandler(handler)
logger.setLevel(log_level)
return jm | [
"def",
"setup",
"(",
"args",
")",
":",
"kwargs",
"=",
"{",
"'wrapper_script'",
":",
"args",
".",
"wrapper_script",
",",
"'debug'",
":",
"args",
".",
"verbose",
"==",
"3",
",",
"'database'",
":",
"args",
".",
"database",
"}",
"if",
"args",
".",
"local",... | Returns the JobManager and sets up the basic infrastructure | [
"Returns",
"the",
"JobManager",
"and",
"sets",
"up",
"the",
"basic",
"infrastructure"
] | train | https://github.com/bioidiap/gridtk/blob/9e3291b8b50388682908927231b2730db1da147d/gridtk/script/jman.py#L29-L55 |
bioidiap/gridtk | gridtk/script/jman.py | get_memfree | def get_memfree(memory, parallel):
"""Computes the memory required for the memfree field."""
number = int(memory.rstrip(string.ascii_letters))
memtype = memory.lstrip(string.digits)
if not memtype:
memtype = "G"
return "%d%s" % (number*parallel, memtype) | python | def get_memfree(memory, parallel):
"""Computes the memory required for the memfree field."""
number = int(memory.rstrip(string.ascii_letters))
memtype = memory.lstrip(string.digits)
if not memtype:
memtype = "G"
return "%d%s" % (number*parallel, memtype) | [
"def",
"get_memfree",
"(",
"memory",
",",
"parallel",
")",
":",
"number",
"=",
"int",
"(",
"memory",
".",
"rstrip",
"(",
"string",
".",
"ascii_letters",
")",
")",
"memtype",
"=",
"memory",
".",
"lstrip",
"(",
"string",
".",
"digits",
")",
"if",
"not",
... | Computes the memory required for the memfree field. | [
"Computes",
"the",
"memory",
"required",
"for",
"the",
"memfree",
"field",
"."
] | train | https://github.com/bioidiap/gridtk/blob/9e3291b8b50388682908927231b2730db1da147d/gridtk/script/jman.py#L98-L104 |
bioidiap/gridtk | gridtk/script/jman.py | submit | def submit(args):
"""Submission command"""
# set full path to command
if args.job[0] == '--':
del args.job[0]
if not os.path.isabs(args.job[0]):
args.job[0] = os.path.abspath(args.job[0])
jm = setup(args)
kwargs = {
'queue': args.qname,
'cwd': True,
'verbosity' : args.verbose,
'name': args.name,
'env': args.env,
'memfree': args.memory,
'io_big': args.io_big,
}
if args.array is not None: kwargs['array'] = get_array(args.array)
if args.exec_dir is not None: kwargs['exec_dir'] = args.exec_dir
if args.log_dir is not None: kwargs['log_dir'] = args.log_dir
if args.dependencies is not None: kwargs['dependencies'] = args.dependencies
if args.qname != 'all.q': kwargs['hvmem'] = args.memory
# if this is a GPU queue and args.memory is provided, we set gpumem flag
# remove 'G' last character from the args.memory string
if args.qname in ('gpu', 'lgpu', 'sgpu', 'gpum') and args.memory is not None:
kwargs['gpumem'] = args.memory
# don't set these for GPU processing or the maximum virtual memroy will be
# set on ulimit
kwargs.pop('memfree', None)
kwargs.pop('hvmem', None)
if args.parallel is not None:
kwargs['pe_opt'] = "pe_mth %d" % args.parallel
if args.memory is not None:
kwargs['memfree'] = get_memfree(args.memory, args.parallel)
kwargs['dry_run'] = args.dry_run
kwargs['stop_on_failure'] = args.stop_on_failure
# submit the job(s)
for _ in range(args.repeat):
job_id = jm.submit(args.job, **kwargs)
dependencies = kwargs.get('dependencies', [])
dependencies.append(job_id)
kwargs['dependencies'] = dependencies
if args.print_id:
print (job_id, end='') | python | def submit(args):
"""Submission command"""
# set full path to command
if args.job[0] == '--':
del args.job[0]
if not os.path.isabs(args.job[0]):
args.job[0] = os.path.abspath(args.job[0])
jm = setup(args)
kwargs = {
'queue': args.qname,
'cwd': True,
'verbosity' : args.verbose,
'name': args.name,
'env': args.env,
'memfree': args.memory,
'io_big': args.io_big,
}
if args.array is not None: kwargs['array'] = get_array(args.array)
if args.exec_dir is not None: kwargs['exec_dir'] = args.exec_dir
if args.log_dir is not None: kwargs['log_dir'] = args.log_dir
if args.dependencies is not None: kwargs['dependencies'] = args.dependencies
if args.qname != 'all.q': kwargs['hvmem'] = args.memory
# if this is a GPU queue and args.memory is provided, we set gpumem flag
# remove 'G' last character from the args.memory string
if args.qname in ('gpu', 'lgpu', 'sgpu', 'gpum') and args.memory is not None:
kwargs['gpumem'] = args.memory
# don't set these for GPU processing or the maximum virtual memroy will be
# set on ulimit
kwargs.pop('memfree', None)
kwargs.pop('hvmem', None)
if args.parallel is not None:
kwargs['pe_opt'] = "pe_mth %d" % args.parallel
if args.memory is not None:
kwargs['memfree'] = get_memfree(args.memory, args.parallel)
kwargs['dry_run'] = args.dry_run
kwargs['stop_on_failure'] = args.stop_on_failure
# submit the job(s)
for _ in range(args.repeat):
job_id = jm.submit(args.job, **kwargs)
dependencies = kwargs.get('dependencies', [])
dependencies.append(job_id)
kwargs['dependencies'] = dependencies
if args.print_id:
print (job_id, end='') | [
"def",
"submit",
"(",
"args",
")",
":",
"# set full path to command",
"if",
"args",
".",
"job",
"[",
"0",
"]",
"==",
"'--'",
":",
"del",
"args",
".",
"job",
"[",
"0",
"]",
"if",
"not",
"os",
".",
"path",
".",
"isabs",
"(",
"args",
".",
"job",
"["... | Submission command | [
"Submission",
"command"
] | train | https://github.com/bioidiap/gridtk/blob/9e3291b8b50388682908927231b2730db1da147d/gridtk/script/jman.py#L106-L154 |
bioidiap/gridtk | gridtk/script/jman.py | resubmit | def resubmit(args):
"""Re-submits the jobs with the given ids."""
jm = setup(args)
kwargs = {
'cwd': True,
'verbosity' : args.verbose
}
if args.qname is not None:
kwargs['queue'] = args.qname
if args.memory is not None:
kwargs['memfree'] = args.memory
if args.qname not in (None, 'all.q'):
kwargs['hvmem'] = args.memory
# if this is a GPU queue and args.memory is provided, we set gpumem flag
# remove 'G' last character from the args.memory string
if args.qname in ('gpu', 'lgpu', 'sgpu', 'gpum') and args.memory is not None:
kwargs['gpumem'] = args.memory
# don't set these for GPU processing or the maximum virtual memroy will be
# set on ulimit
kwargs.pop('memfree', None)
kwargs.pop('hvmem', None)
if args.parallel is not None:
kwargs['pe_opt'] = "pe_mth %d" % args.parallel
kwargs['memfree'] = get_memfree(args.memory, args.parallel)
if args.io_big:
kwargs['io_big'] = True
if args.no_io_big:
kwargs['io_big'] = False
jm.resubmit(get_ids(args.job_ids), args.also_success, args.running_jobs, args.overwrite_command, keep_logs=args.keep_logs, **kwargs) | python | def resubmit(args):
"""Re-submits the jobs with the given ids."""
jm = setup(args)
kwargs = {
'cwd': True,
'verbosity' : args.verbose
}
if args.qname is not None:
kwargs['queue'] = args.qname
if args.memory is not None:
kwargs['memfree'] = args.memory
if args.qname not in (None, 'all.q'):
kwargs['hvmem'] = args.memory
# if this is a GPU queue and args.memory is provided, we set gpumem flag
# remove 'G' last character from the args.memory string
if args.qname in ('gpu', 'lgpu', 'sgpu', 'gpum') and args.memory is not None:
kwargs['gpumem'] = args.memory
# don't set these for GPU processing or the maximum virtual memroy will be
# set on ulimit
kwargs.pop('memfree', None)
kwargs.pop('hvmem', None)
if args.parallel is not None:
kwargs['pe_opt'] = "pe_mth %d" % args.parallel
kwargs['memfree'] = get_memfree(args.memory, args.parallel)
if args.io_big:
kwargs['io_big'] = True
if args.no_io_big:
kwargs['io_big'] = False
jm.resubmit(get_ids(args.job_ids), args.also_success, args.running_jobs, args.overwrite_command, keep_logs=args.keep_logs, **kwargs) | [
"def",
"resubmit",
"(",
"args",
")",
":",
"jm",
"=",
"setup",
"(",
"args",
")",
"kwargs",
"=",
"{",
"'cwd'",
":",
"True",
",",
"'verbosity'",
":",
"args",
".",
"verbose",
"}",
"if",
"args",
".",
"qname",
"is",
"not",
"None",
":",
"kwargs",
"[",
"... | Re-submits the jobs with the given ids. | [
"Re",
"-",
"submits",
"the",
"jobs",
"with",
"the",
"given",
"ids",
"."
] | train | https://github.com/bioidiap/gridtk/blob/9e3291b8b50388682908927231b2730db1da147d/gridtk/script/jman.py#L157-L187 |
bioidiap/gridtk | gridtk/script/jman.py | run_scheduler | def run_scheduler(args):
"""Runs the scheduler on the local machine. To stop it, please use Ctrl-C."""
if not args.local:
raise ValueError("The execute command can only be used with the '--local' command line option")
jm = setup(args)
jm.run_scheduler(parallel_jobs=args.parallel, job_ids=get_ids(args.job_ids), sleep_time=args.sleep_time, die_when_finished=args.die_when_finished, no_log=args.no_log_files, nice=args.nice, verbosity=args.verbose) | python | def run_scheduler(args):
"""Runs the scheduler on the local machine. To stop it, please use Ctrl-C."""
if not args.local:
raise ValueError("The execute command can only be used with the '--local' command line option")
jm = setup(args)
jm.run_scheduler(parallel_jobs=args.parallel, job_ids=get_ids(args.job_ids), sleep_time=args.sleep_time, die_when_finished=args.die_when_finished, no_log=args.no_log_files, nice=args.nice, verbosity=args.verbose) | [
"def",
"run_scheduler",
"(",
"args",
")",
":",
"if",
"not",
"args",
".",
"local",
":",
"raise",
"ValueError",
"(",
"\"The execute command can only be used with the '--local' command line option\"",
")",
"jm",
"=",
"setup",
"(",
"args",
")",
"jm",
".",
"run_scheduler... | Runs the scheduler on the local machine. To stop it, please use Ctrl-C. | [
"Runs",
"the",
"scheduler",
"on",
"the",
"local",
"machine",
".",
"To",
"stop",
"it",
"please",
"use",
"Ctrl",
"-",
"C",
"."
] | train | https://github.com/bioidiap/gridtk/blob/9e3291b8b50388682908927231b2730db1da147d/gridtk/script/jman.py#L190-L195 |
bioidiap/gridtk | gridtk/script/jman.py | list | def list(args):
"""Lists the jobs in the given database."""
jm = setup(args)
jm.list(job_ids=get_ids(args.job_ids), print_array_jobs=args.print_array_jobs, print_dependencies=args.print_dependencies, status=args.status, long=args.long, print_times=args.print_times, ids_only=args.ids_only, names=args.names) | python | def list(args):
"""Lists the jobs in the given database."""
jm = setup(args)
jm.list(job_ids=get_ids(args.job_ids), print_array_jobs=args.print_array_jobs, print_dependencies=args.print_dependencies, status=args.status, long=args.long, print_times=args.print_times, ids_only=args.ids_only, names=args.names) | [
"def",
"list",
"(",
"args",
")",
":",
"jm",
"=",
"setup",
"(",
"args",
")",
"jm",
".",
"list",
"(",
"job_ids",
"=",
"get_ids",
"(",
"args",
".",
"job_ids",
")",
",",
"print_array_jobs",
"=",
"args",
".",
"print_array_jobs",
",",
"print_dependencies",
"... | Lists the jobs in the given database. | [
"Lists",
"the",
"jobs",
"in",
"the",
"given",
"database",
"."
] | train | https://github.com/bioidiap/gridtk/blob/9e3291b8b50388682908927231b2730db1da147d/gridtk/script/jman.py#L198-L201 |
bioidiap/gridtk | gridtk/script/jman.py | communicate | def communicate(args):
"""Uses qstat to get the status of the requested jobs."""
if args.local:
raise ValueError("The communicate command can only be used without the '--local' command line option")
jm = setup(args)
jm.communicate(job_ids=get_ids(args.job_ids)) | python | def communicate(args):
"""Uses qstat to get the status of the requested jobs."""
if args.local:
raise ValueError("The communicate command can only be used without the '--local' command line option")
jm = setup(args)
jm.communicate(job_ids=get_ids(args.job_ids)) | [
"def",
"communicate",
"(",
"args",
")",
":",
"if",
"args",
".",
"local",
":",
"raise",
"ValueError",
"(",
"\"The communicate command can only be used without the '--local' command line option\"",
")",
"jm",
"=",
"setup",
"(",
"args",
")",
"jm",
".",
"communicate",
"... | Uses qstat to get the status of the requested jobs. | [
"Uses",
"qstat",
"to",
"get",
"the",
"status",
"of",
"the",
"requested",
"jobs",
"."
] | train | https://github.com/bioidiap/gridtk/blob/9e3291b8b50388682908927231b2730db1da147d/gridtk/script/jman.py#L204-L209 |
bioidiap/gridtk | gridtk/script/jman.py | report | def report(args):
"""Reports the results of the finished (and unfinished) jobs."""
jm = setup(args)
jm.report(job_ids=get_ids(args.job_ids), array_ids=get_ids(args.array_ids), output=not args.errors_only, error=not args.output_only, status=args.status, name=args.name) | python | def report(args):
"""Reports the results of the finished (and unfinished) jobs."""
jm = setup(args)
jm.report(job_ids=get_ids(args.job_ids), array_ids=get_ids(args.array_ids), output=not args.errors_only, error=not args.output_only, status=args.status, name=args.name) | [
"def",
"report",
"(",
"args",
")",
":",
"jm",
"=",
"setup",
"(",
"args",
")",
"jm",
".",
"report",
"(",
"job_ids",
"=",
"get_ids",
"(",
"args",
".",
"job_ids",
")",
",",
"array_ids",
"=",
"get_ids",
"(",
"args",
".",
"array_ids",
")",
",",
"output"... | Reports the results of the finished (and unfinished) jobs. | [
"Reports",
"the",
"results",
"of",
"the",
"finished",
"(",
"and",
"unfinished",
")",
"jobs",
"."
] | train | https://github.com/bioidiap/gridtk/blob/9e3291b8b50388682908927231b2730db1da147d/gridtk/script/jman.py#L212-L215 |
bioidiap/gridtk | gridtk/script/jman.py | stop | def stop(args):
"""Stops (qdel's) the jobs with the given ids."""
if args.local:
raise ValueError("Stopping commands locally is not supported (please kill them yourself)")
jm = setup(args)
jm.stop_jobs(get_ids(args.job_ids)) | python | def stop(args):
"""Stops (qdel's) the jobs with the given ids."""
if args.local:
raise ValueError("Stopping commands locally is not supported (please kill them yourself)")
jm = setup(args)
jm.stop_jobs(get_ids(args.job_ids)) | [
"def",
"stop",
"(",
"args",
")",
":",
"if",
"args",
".",
"local",
":",
"raise",
"ValueError",
"(",
"\"Stopping commands locally is not supported (please kill them yourself)\"",
")",
"jm",
"=",
"setup",
"(",
"args",
")",
"jm",
".",
"stop_jobs",
"(",
"get_ids",
"(... | Stops (qdel's) the jobs with the given ids. | [
"Stops",
"(",
"qdel",
"s",
")",
"the",
"jobs",
"with",
"the",
"given",
"ids",
"."
] | train | https://github.com/bioidiap/gridtk/blob/9e3291b8b50388682908927231b2730db1da147d/gridtk/script/jman.py#L218-L223 |
bioidiap/gridtk | gridtk/script/jman.py | delete | def delete(args):
"""Deletes the jobs from the job manager. If the jobs are still running in the grid, they are stopped."""
jm = setup(args)
# first, stop the jobs if they are running in the grid
if not args.local and 'executing' in args.status:
stop(args)
# then, delete them from the database
jm.delete(job_ids=get_ids(args.job_ids), array_ids=get_ids(args.array_ids), delete_logs=not args.keep_logs, delete_log_dir=not args.keep_log_dir, status=args.status) | python | def delete(args):
"""Deletes the jobs from the job manager. If the jobs are still running in the grid, they are stopped."""
jm = setup(args)
# first, stop the jobs if they are running in the grid
if not args.local and 'executing' in args.status:
stop(args)
# then, delete them from the database
jm.delete(job_ids=get_ids(args.job_ids), array_ids=get_ids(args.array_ids), delete_logs=not args.keep_logs, delete_log_dir=not args.keep_log_dir, status=args.status) | [
"def",
"delete",
"(",
"args",
")",
":",
"jm",
"=",
"setup",
"(",
"args",
")",
"# first, stop the jobs if they are running in the grid",
"if",
"not",
"args",
".",
"local",
"and",
"'executing'",
"in",
"args",
".",
"status",
":",
"stop",
"(",
"args",
")",
"# th... | Deletes the jobs from the job manager. If the jobs are still running in the grid, they are stopped. | [
"Deletes",
"the",
"jobs",
"from",
"the",
"job",
"manager",
".",
"If",
"the",
"jobs",
"are",
"still",
"running",
"in",
"the",
"grid",
"they",
"are",
"stopped",
"."
] | train | https://github.com/bioidiap/gridtk/blob/9e3291b8b50388682908927231b2730db1da147d/gridtk/script/jman.py#L226-L233 |
bioidiap/gridtk | gridtk/script/jman.py | run_job | def run_job(args):
"""Starts the wrapper script to execute a job, interpreting the JOB_ID and SGE_TASK_ID keywords that are set by the grid or by us."""
jm = setup(args)
job_id = int(os.environ['JOB_ID'])
array_id = int(os.environ['SGE_TASK_ID']) if os.environ['SGE_TASK_ID'] != 'undefined' else None
jm.run_job(job_id, array_id) | python | def run_job(args):
"""Starts the wrapper script to execute a job, interpreting the JOB_ID and SGE_TASK_ID keywords that are set by the grid or by us."""
jm = setup(args)
job_id = int(os.environ['JOB_ID'])
array_id = int(os.environ['SGE_TASK_ID']) if os.environ['SGE_TASK_ID'] != 'undefined' else None
jm.run_job(job_id, array_id) | [
"def",
"run_job",
"(",
"args",
")",
":",
"jm",
"=",
"setup",
"(",
"args",
")",
"job_id",
"=",
"int",
"(",
"os",
".",
"environ",
"[",
"'JOB_ID'",
"]",
")",
"array_id",
"=",
"int",
"(",
"os",
".",
"environ",
"[",
"'SGE_TASK_ID'",
"]",
")",
"if",
"o... | Starts the wrapper script to execute a job, interpreting the JOB_ID and SGE_TASK_ID keywords that are set by the grid or by us. | [
"Starts",
"the",
"wrapper",
"script",
"to",
"execute",
"a",
"job",
"interpreting",
"the",
"JOB_ID",
"and",
"SGE_TASK_ID",
"keywords",
"that",
"are",
"set",
"by",
"the",
"grid",
"or",
"by",
"us",
"."
] | train | https://github.com/bioidiap/gridtk/blob/9e3291b8b50388682908927231b2730db1da147d/gridtk/script/jman.py#L236-L241 |
ajyoon/blur | blur/soft.py | SoftOptions.with_random_weights | def with_random_weights(cls, options):
"""
Initialize from a list of options with random weights.
The weights assigned to each object are uniformally random
integers between ``1`` and ``len(options)``
Args:
options (list): The list of options of any type this object
can return with the ``get()`` method.
Returns:
SoftOptions: A newly constructed instance
"""
return cls([(value, random.randint(1, len(options)))
for value in options]) | python | def with_random_weights(cls, options):
"""
Initialize from a list of options with random weights.
The weights assigned to each object are uniformally random
integers between ``1`` and ``len(options)``
Args:
options (list): The list of options of any type this object
can return with the ``get()`` method.
Returns:
SoftOptions: A newly constructed instance
"""
return cls([(value, random.randint(1, len(options)))
for value in options]) | [
"def",
"with_random_weights",
"(",
"cls",
",",
"options",
")",
":",
"return",
"cls",
"(",
"[",
"(",
"value",
",",
"random",
".",
"randint",
"(",
"1",
",",
"len",
"(",
"options",
")",
")",
")",
"for",
"value",
"in",
"options",
"]",
")"
] | Initialize from a list of options with random weights.
The weights assigned to each object are uniformally random
integers between ``1`` and ``len(options)``
Args:
options (list): The list of options of any type this object
can return with the ``get()`` method.
Returns:
SoftOptions: A newly constructed instance | [
"Initialize",
"from",
"a",
"list",
"of",
"options",
"with",
"random",
"weights",
"."
] | train | https://github.com/ajyoon/blur/blob/25fcf083af112bb003956a7a7e1c6ff7d8fef279/blur/soft.py#L102-L117 |
ajyoon/blur | blur/soft.py | SoftFloat.bounded_uniform | def bounded_uniform(cls, lowest, highest, weight_interval=None):
"""
Initialize with a uniform distribution between two values.
If no ``weight_interval`` is passed, this weight distribution
will just consist of ``[(lowest, 1), (highest, 1)]``. If specified,
weights (still with uniform weight distribution) will be added every
``weight_interval``. Use this if you intend to modify the weights
in any complex way after initialization.
Args:
lowest (float or int):
highest (float or int):
weight_interval (int):
Returns:
SoftFloat: A newly constructed instance.
"""
if weight_interval is None:
weights = [(lowest, 1), (highest, 1)]
else:
i = lowest
weights = []
while i < highest:
weights.append((i, 1))
i += weight_interval
weights.append((highest, 1))
return cls(weights) | python | def bounded_uniform(cls, lowest, highest, weight_interval=None):
"""
Initialize with a uniform distribution between two values.
If no ``weight_interval`` is passed, this weight distribution
will just consist of ``[(lowest, 1), (highest, 1)]``. If specified,
weights (still with uniform weight distribution) will be added every
``weight_interval``. Use this if you intend to modify the weights
in any complex way after initialization.
Args:
lowest (float or int):
highest (float or int):
weight_interval (int):
Returns:
SoftFloat: A newly constructed instance.
"""
if weight_interval is None:
weights = [(lowest, 1), (highest, 1)]
else:
i = lowest
weights = []
while i < highest:
weights.append((i, 1))
i += weight_interval
weights.append((highest, 1))
return cls(weights) | [
"def",
"bounded_uniform",
"(",
"cls",
",",
"lowest",
",",
"highest",
",",
"weight_interval",
"=",
"None",
")",
":",
"if",
"weight_interval",
"is",
"None",
":",
"weights",
"=",
"[",
"(",
"lowest",
",",
"1",
")",
",",
"(",
"highest",
",",
"1",
")",
"]"... | Initialize with a uniform distribution between two values.
If no ``weight_interval`` is passed, this weight distribution
will just consist of ``[(lowest, 1), (highest, 1)]``. If specified,
weights (still with uniform weight distribution) will be added every
``weight_interval``. Use this if you intend to modify the weights
in any complex way after initialization.
Args:
lowest (float or int):
highest (float or int):
weight_interval (int):
Returns:
SoftFloat: A newly constructed instance. | [
"Initialize",
"with",
"a",
"uniform",
"distribution",
"between",
"two",
"values",
"."
] | train | https://github.com/ajyoon/blur/blob/25fcf083af112bb003956a7a7e1c6ff7d8fef279/blur/soft.py#L201-L228 |
ajyoon/blur | blur/soft.py | SoftColor.rgb_to_hex | def rgb_to_hex(cls, color):
"""
Convert an ``(r, g, b)`` color tuple to a hexadecimal string.
Alphabetical characters in the output will be capitalized.
Args:
color (tuple): An rgb color tuple of form: (int, int, int)
Returns: string
Example:
>>> SoftColor.rgb_to_hex((0, 0, 0))
'#000000'
>>> SoftColor.rgb_to_hex((255, 255, 255))
'#FFFFFF'
"""
return '#{0:02x}{1:02x}{2:02x}'.format(
cls._bound_color_value(color[0]),
cls._bound_color_value(color[1]),
cls._bound_color_value(color[2])).upper() | python | def rgb_to_hex(cls, color):
"""
Convert an ``(r, g, b)`` color tuple to a hexadecimal string.
Alphabetical characters in the output will be capitalized.
Args:
color (tuple): An rgb color tuple of form: (int, int, int)
Returns: string
Example:
>>> SoftColor.rgb_to_hex((0, 0, 0))
'#000000'
>>> SoftColor.rgb_to_hex((255, 255, 255))
'#FFFFFF'
"""
return '#{0:02x}{1:02x}{2:02x}'.format(
cls._bound_color_value(color[0]),
cls._bound_color_value(color[1]),
cls._bound_color_value(color[2])).upper() | [
"def",
"rgb_to_hex",
"(",
"cls",
",",
"color",
")",
":",
"return",
"'#{0:02x}{1:02x}{2:02x}'",
".",
"format",
"(",
"cls",
".",
"_bound_color_value",
"(",
"color",
"[",
"0",
"]",
")",
",",
"cls",
".",
"_bound_color_value",
"(",
"color",
"[",
"1",
"]",
")"... | Convert an ``(r, g, b)`` color tuple to a hexadecimal string.
Alphabetical characters in the output will be capitalized.
Args:
color (tuple): An rgb color tuple of form: (int, int, int)
Returns: string
Example:
>>> SoftColor.rgb_to_hex((0, 0, 0))
'#000000'
>>> SoftColor.rgb_to_hex((255, 255, 255))
'#FFFFFF' | [
"Convert",
"an",
"(",
"r",
"g",
"b",
")",
"color",
"tuple",
"to",
"a",
"hexadecimal",
"string",
"."
] | train | https://github.com/ajyoon/blur/blob/25fcf083af112bb003956a7a7e1c6ff7d8fef279/blur/soft.py#L404-L424 |
ajyoon/blur | blur/soft.py | SoftColor.get | def get(self):
"""
Get an rgb color tuple according to the probability distribution.
Returns:
tuple(int, int, int): A ``(red, green, blue)`` tuple.
Example:
>>> color = SoftColor(([(0, 1), (255, 10)],),
... ([(0, 1), (255, 10)],),
... ([(0, 1), (255, 10)],))
>>> color.get() # doctest: +SKIP
(234, 201, 243)
"""
if isinstance(self.red, SoftInt):
red = self.red.get()
else:
red = self.red
if isinstance(self.green, SoftInt):
green = self.green.get()
else:
green = self.green
if isinstance(self.blue, SoftInt):
blue = self.blue.get()
else:
blue = self.blue
return (red, green, blue) | python | def get(self):
"""
Get an rgb color tuple according to the probability distribution.
Returns:
tuple(int, int, int): A ``(red, green, blue)`` tuple.
Example:
>>> color = SoftColor(([(0, 1), (255, 10)],),
... ([(0, 1), (255, 10)],),
... ([(0, 1), (255, 10)],))
>>> color.get() # doctest: +SKIP
(234, 201, 243)
"""
if isinstance(self.red, SoftInt):
red = self.red.get()
else:
red = self.red
if isinstance(self.green, SoftInt):
green = self.green.get()
else:
green = self.green
if isinstance(self.blue, SoftInt):
blue = self.blue.get()
else:
blue = self.blue
return (red, green, blue) | [
"def",
"get",
"(",
"self",
")",
":",
"if",
"isinstance",
"(",
"self",
".",
"red",
",",
"SoftInt",
")",
":",
"red",
"=",
"self",
".",
"red",
".",
"get",
"(",
")",
"else",
":",
"red",
"=",
"self",
".",
"red",
"if",
"isinstance",
"(",
"self",
".",... | Get an rgb color tuple according to the probability distribution.
Returns:
tuple(int, int, int): A ``(red, green, blue)`` tuple.
Example:
>>> color = SoftColor(([(0, 1), (255, 10)],),
... ([(0, 1), (255, 10)],),
... ([(0, 1), (255, 10)],))
>>> color.get() # doctest: +SKIP
(234, 201, 243) | [
"Get",
"an",
"rgb",
"color",
"tuple",
"according",
"to",
"the",
"probability",
"distribution",
"."
] | train | https://github.com/ajyoon/blur/blob/25fcf083af112bb003956a7a7e1c6ff7d8fef279/blur/soft.py#L426-L452 |
timothycrosley/short | short/cli.py | grow | def grow(files: hug.types.multiple, in_ext: hug.types.text="short", out_ext: hug.types.text="html",
out_dir: hug.types.text="", recursive: hug.types.smart_boolean=False):
"""Grow up your markup"""
if files == ['-']:
print(text(sys.stdin.read()))
return
print(INTRO)
if recursive:
files = iter_source_code(files, in_ext)
for file_name in files:
with open(file_name, 'r') as input_file:
output_file_name = "{0}.{1}".format(os.path.join(out_dir, ".".join(file_name.split('.')[:-1])), out_ext)
with open(output_file_name, 'w') as output_file:
print(" |-> [{2}]: {3} '{0}' -> '{1}' till it's not short...".format(file_name, output_file_name,
'HTML', 'Growing'))
output_file.write(text(input_file.read()))
print(" |")
print(" | >>> Done Growing! :) <<<")
print("") | python | def grow(files: hug.types.multiple, in_ext: hug.types.text="short", out_ext: hug.types.text="html",
out_dir: hug.types.text="", recursive: hug.types.smart_boolean=False):
"""Grow up your markup"""
if files == ['-']:
print(text(sys.stdin.read()))
return
print(INTRO)
if recursive:
files = iter_source_code(files, in_ext)
for file_name in files:
with open(file_name, 'r') as input_file:
output_file_name = "{0}.{1}".format(os.path.join(out_dir, ".".join(file_name.split('.')[:-1])), out_ext)
with open(output_file_name, 'w') as output_file:
print(" |-> [{2}]: {3} '{0}' -> '{1}' till it's not short...".format(file_name, output_file_name,
'HTML', 'Growing'))
output_file.write(text(input_file.read()))
print(" |")
print(" | >>> Done Growing! :) <<<")
print("") | [
"def",
"grow",
"(",
"files",
":",
"hug",
".",
"types",
".",
"multiple",
",",
"in_ext",
":",
"hug",
".",
"types",
".",
"text",
"=",
"\"short\"",
",",
"out_ext",
":",
"hug",
".",
"types",
".",
"text",
"=",
"\"html\"",
",",
"out_dir",
":",
"hug",
".",... | Grow up your markup | [
"Grow",
"up",
"your",
"markup"
] | train | https://github.com/timothycrosley/short/blob/dcf25ec01b5406d9e0a35ac7dd8112239c0912a5/short/cli.py#L50-L71 |
MacHu-GWU/pymongo_mate-project | pymongo_mate/pkg/pandas_mate/util.py | read_csv_arg_preprocess | def read_csv_arg_preprocess(abspath, memory_usage=100 * 1000 * 1000):
"""Automatically decide if we need to use iterator mode to read a csv file.
:param abspath: csv file absolute path.
:param memory_usage: max memory will be used for pandas.read_csv().
"""
if memory_usage < 1000 * 1000:
raise ValueError("Please specify a valid memory usage for read_csv, "
"the value should larger than 1MB and less than "
"your available memory.")
size = os.path.getsize(abspath) # total size in bytes
n_time = math.ceil(size * 1.0 / memory_usage) # at lease read n times
lines = count_lines(abspath) # total lines
chunksize = math.ceil(lines / n_time) # lines to read each time
if chunksize >= lines:
iterator = False
chunksize = None
else:
iterator = True
return iterator, chunksize | python | def read_csv_arg_preprocess(abspath, memory_usage=100 * 1000 * 1000):
"""Automatically decide if we need to use iterator mode to read a csv file.
:param abspath: csv file absolute path.
:param memory_usage: max memory will be used for pandas.read_csv().
"""
if memory_usage < 1000 * 1000:
raise ValueError("Please specify a valid memory usage for read_csv, "
"the value should larger than 1MB and less than "
"your available memory.")
size = os.path.getsize(abspath) # total size in bytes
n_time = math.ceil(size * 1.0 / memory_usage) # at lease read n times
lines = count_lines(abspath) # total lines
chunksize = math.ceil(lines / n_time) # lines to read each time
if chunksize >= lines:
iterator = False
chunksize = None
else:
iterator = True
return iterator, chunksize | [
"def",
"read_csv_arg_preprocess",
"(",
"abspath",
",",
"memory_usage",
"=",
"100",
"*",
"1000",
"*",
"1000",
")",
":",
"if",
"memory_usage",
"<",
"1000",
"*",
"1000",
":",
"raise",
"ValueError",
"(",
"\"Please specify a valid memory usage for read_csv, \"",
"\"the v... | Automatically decide if we need to use iterator mode to read a csv file.
:param abspath: csv file absolute path.
:param memory_usage: max memory will be used for pandas.read_csv(). | [
"Automatically",
"decide",
"if",
"we",
"need",
"to",
"use",
"iterator",
"mode",
"to",
"read",
"a",
"csv",
"file",
"."
] | train | https://github.com/MacHu-GWU/pymongo_mate-project/blob/be53170c2db54cb705b9e548d32ef26c773ff7f3/pymongo_mate/pkg/pandas_mate/util.py#L28-L50 |
MacHu-GWU/pymongo_mate-project | pymongo_mate/pkg/pandas_mate/util.py | to_prettytable | def to_prettytable(df):
"""Convert DataFrame into ``PrettyTable``.
"""
pt = PrettyTable()
pt.field_names = df.columns
for tp in zip(*(l for col, l in df.iteritems())):
pt.add_row(tp)
return pt | python | def to_prettytable(df):
"""Convert DataFrame into ``PrettyTable``.
"""
pt = PrettyTable()
pt.field_names = df.columns
for tp in zip(*(l for col, l in df.iteritems())):
pt.add_row(tp)
return pt | [
"def",
"to_prettytable",
"(",
"df",
")",
":",
"pt",
"=",
"PrettyTable",
"(",
")",
"pt",
".",
"field_names",
"=",
"df",
".",
"columns",
"for",
"tp",
"in",
"zip",
"(",
"*",
"(",
"l",
"for",
"col",
",",
"l",
"in",
"df",
".",
"iteritems",
"(",
")",
... | Convert DataFrame into ``PrettyTable``. | [
"Convert",
"DataFrame",
"into",
"PrettyTable",
"."
] | train | https://github.com/MacHu-GWU/pymongo_mate-project/blob/be53170c2db54cb705b9e548d32ef26c773ff7f3/pymongo_mate/pkg/pandas_mate/util.py#L53-L60 |
chrlie/frogsay | src/frogsay/__init__.py | cli | def cli():
"""\
Frogsay generates an ASCII picture of a FROG spouting a FROG tip.
FROG tips are fetched from frog.tips's API endpoint when needed,
otherwise they are cached locally in an application-specific folder.
"""
with open_client(cache_dir=get_cache_dir()) as client:
tip = client.frog_tip()
terminal_width = click.termui.get_terminal_size()[0]
wisdom = make_frog_fresco(tip, width=terminal_width)
click.echo(wisdom) | python | def cli():
"""\
Frogsay generates an ASCII picture of a FROG spouting a FROG tip.
FROG tips are fetched from frog.tips's API endpoint when needed,
otherwise they are cached locally in an application-specific folder.
"""
with open_client(cache_dir=get_cache_dir()) as client:
tip = client.frog_tip()
terminal_width = click.termui.get_terminal_size()[0]
wisdom = make_frog_fresco(tip, width=terminal_width)
click.echo(wisdom) | [
"def",
"cli",
"(",
")",
":",
"with",
"open_client",
"(",
"cache_dir",
"=",
"get_cache_dir",
"(",
")",
")",
"as",
"client",
":",
"tip",
"=",
"client",
".",
"frog_tip",
"(",
")",
"terminal_width",
"=",
"click",
".",
"termui",
".",
"get_terminal_size",
"(",... | \
Frogsay generates an ASCII picture of a FROG spouting a FROG tip.
FROG tips are fetched from frog.tips's API endpoint when needed,
otherwise they are cached locally in an application-specific folder. | [
"\\",
"Frogsay",
"generates",
"an",
"ASCII",
"picture",
"of",
"a",
"FROG",
"spouting",
"a",
"FROG",
"tip",
"."
] | train | https://github.com/chrlie/frogsay/blob/1c21e1401dc24719732218af830d34b842ab10b9/src/frogsay/__init__.py#L17-L30 |
duniter/duniter-python-api | duniterpy/key/verifying_key.py | VerifyingKey.verify_document | def verify_document(self, document: Document) -> bool:
"""
Check specified document
:param duniterpy.documents.Document document:
:return:
"""
signature = base64.b64decode(document.signatures[0])
prepended = signature + bytes(document.raw(), 'ascii')
try:
self.verify(prepended)
return True
except ValueError:
return False | python | def verify_document(self, document: Document) -> bool:
"""
Check specified document
:param duniterpy.documents.Document document:
:return:
"""
signature = base64.b64decode(document.signatures[0])
prepended = signature + bytes(document.raw(), 'ascii')
try:
self.verify(prepended)
return True
except ValueError:
return False | [
"def",
"verify_document",
"(",
"self",
",",
"document",
":",
"Document",
")",
"->",
"bool",
":",
"signature",
"=",
"base64",
".",
"b64decode",
"(",
"document",
".",
"signatures",
"[",
"0",
"]",
")",
"prepended",
"=",
"signature",
"+",
"bytes",
"(",
"docu... | Check specified document
:param duniterpy.documents.Document document:
:return: | [
"Check",
"specified",
"document",
":",
"param",
"duniterpy",
".",
"documents",
".",
"Document",
"document",
":",
":",
"return",
":"
] | train | https://github.com/duniter/duniter-python-api/blob/3a1e5d61a2f72f5afaf29d010c6cf4dff3648165/duniterpy/key/verifying_key.py#L30-L43 |
duniter/duniter-python-api | duniterpy/key/verifying_key.py | VerifyingKey.verify_ws2p_head | def verify_ws2p_head(self, head: Any) -> bool:
"""
Check specified document
:param Any head:
:return:
"""
signature = base64.b64decode(head.signature)
inline = head.inline()
prepended = signature + bytes(inline, 'ascii')
try:
self.verify(prepended)
return True
except ValueError:
return False | python | def verify_ws2p_head(self, head: Any) -> bool:
"""
Check specified document
:param Any head:
:return:
"""
signature = base64.b64decode(head.signature)
inline = head.inline()
prepended = signature + bytes(inline, 'ascii')
try:
self.verify(prepended)
return True
except ValueError:
return False | [
"def",
"verify_ws2p_head",
"(",
"self",
",",
"head",
":",
"Any",
")",
"->",
"bool",
":",
"signature",
"=",
"base64",
".",
"b64decode",
"(",
"head",
".",
"signature",
")",
"inline",
"=",
"head",
".",
"inline",
"(",
")",
"prepended",
"=",
"signature",
"+... | Check specified document
:param Any head:
:return: | [
"Check",
"specified",
"document",
":",
"param",
"Any",
"head",
":",
":",
"return",
":"
] | train | https://github.com/duniter/duniter-python-api/blob/3a1e5d61a2f72f5afaf29d010c6cf4dff3648165/duniterpy/key/verifying_key.py#L45-L59 |
Datary/scrapbag | scrapbag/spss.py | parse_spss_headerfile | def parse_spss_headerfile(path, **kwargs):
"""
Parse spss header file
Arguments:
path {str} -- path al fichero de cabecera.
leyend_position -- posicion del la leyenda en el header.
"""
headers_clean = {}
try:
with codecs.open(path, 'r', kwargs.get('encoding', 'latin-1')) as file_:
raw_file = file_.read()
raw_splited = exclude_empty_values(raw_file.split('.\r\n'))
# suposse that by default spss leyend is in position 0.
leyend = parse_spss_header_leyend(
raw_leyend=raw_splited.pop(kwargs.get('leyend_position', 0)),
leyend=headers_clean)
if not leyend:
raise Exception('Empty leyend')
# only want VARIABLE(S) LABEL(S) & VALUE(S) LABEL(S)
for label in [x for x in raw_splited if 'label' in x.lower()]:
values = parse_spss_header_labels(
raw_labels=label,
headers=leyend)
except Exception as ex:
logger.error('Fail to parse spss headerfile - {}'.format(ex), header_file=path)
headers_clean = {}
return headers_clean | python | def parse_spss_headerfile(path, **kwargs):
"""
Parse spss header file
Arguments:
path {str} -- path al fichero de cabecera.
leyend_position -- posicion del la leyenda en el header.
"""
headers_clean = {}
try:
with codecs.open(path, 'r', kwargs.get('encoding', 'latin-1')) as file_:
raw_file = file_.read()
raw_splited = exclude_empty_values(raw_file.split('.\r\n'))
# suposse that by default spss leyend is in position 0.
leyend = parse_spss_header_leyend(
raw_leyend=raw_splited.pop(kwargs.get('leyend_position', 0)),
leyend=headers_clean)
if not leyend:
raise Exception('Empty leyend')
# only want VARIABLE(S) LABEL(S) & VALUE(S) LABEL(S)
for label in [x for x in raw_splited if 'label' in x.lower()]:
values = parse_spss_header_labels(
raw_labels=label,
headers=leyend)
except Exception as ex:
logger.error('Fail to parse spss headerfile - {}'.format(ex), header_file=path)
headers_clean = {}
return headers_clean | [
"def",
"parse_spss_headerfile",
"(",
"path",
",",
"*",
"*",
"kwargs",
")",
":",
"headers_clean",
"=",
"{",
"}",
"try",
":",
"with",
"codecs",
".",
"open",
"(",
"path",
",",
"'r'",
",",
"kwargs",
".",
"get",
"(",
"'encoding'",
",",
"'latin-1'",
")",
"... | Parse spss header file
Arguments:
path {str} -- path al fichero de cabecera.
leyend_position -- posicion del la leyenda en el header. | [
"Parse",
"spss",
"header",
"file"
] | train | https://github.com/Datary/scrapbag/blob/3a4f9824ab6fe21121214ba9963690618da2c9de/scrapbag/spss.py#L149-L181 |
Datary/scrapbag | scrapbag/spss.py | parse_spss_datafile | def parse_spss_datafile(path, **kwargs):
"""
Parse spss data file
Arguments:
path {str} -- path al fichero de cabecera.
**kwargs {[dict]} -- otros argumentos que puedan llegar
"""
data_clean = []
with codecs.open(path, 'r', kwargs.get('encoding', 'latin-1')) as file_:
raw_file = file_.read()
data_clean = raw_file.split('\r\n')
return exclude_empty_values(data_clean) | python | def parse_spss_datafile(path, **kwargs):
"""
Parse spss data file
Arguments:
path {str} -- path al fichero de cabecera.
**kwargs {[dict]} -- otros argumentos que puedan llegar
"""
data_clean = []
with codecs.open(path, 'r', kwargs.get('encoding', 'latin-1')) as file_:
raw_file = file_.read()
data_clean = raw_file.split('\r\n')
return exclude_empty_values(data_clean) | [
"def",
"parse_spss_datafile",
"(",
"path",
",",
"*",
"*",
"kwargs",
")",
":",
"data_clean",
"=",
"[",
"]",
"with",
"codecs",
".",
"open",
"(",
"path",
",",
"'r'",
",",
"kwargs",
".",
"get",
"(",
"'encoding'",
",",
"'latin-1'",
")",
")",
"as",
"file_"... | Parse spss data file
Arguments:
path {str} -- path al fichero de cabecera.
**kwargs {[dict]} -- otros argumentos que puedan llegar | [
"Parse",
"spss",
"data",
"file"
] | train | https://github.com/Datary/scrapbag/blob/3a4f9824ab6fe21121214ba9963690618da2c9de/scrapbag/spss.py#L184-L196 |
Datary/scrapbag | scrapbag/pdf.py | pdf_to_text | def pdf_to_text(pdf_filepath='', **kwargs):
"""
Parse pdf to a list of strings using the pdfminer lib.
Args:
no_laparams=False,
all_texts=None,
detect_vertical=None, word_margin=None, char_margin=None,
line_margin=None, boxes_flow=None, codec='utf-8',
strip_control=False, maxpages=0, page_numbers=None, password="",
scale=1.0, rotation=0, layoutmode='normal', debug=False,
disable_caching=False,
"""
result = []
try:
if not os.path.exists(pdf_filepath):
raise ValueError("No valid pdf filepath introduced..")
# TODO: REVIEW THIS PARAMS
# update params if not defined
kwargs['outfp'] = kwargs.get('outfp', StringIO())
kwargs['laparams'] = kwargs.get('laparams', pdfminer.layout.LAParams())
kwargs['imagewriter'] = kwargs.get('imagewriter', None)
kwargs['output_type'] = kwargs.get('output_type', "text")
kwargs['codec'] = kwargs.get('codec', 'utf-8')
kwargs['disable_caching'] = kwargs.get('disable_caching', False)
with open(pdf_filepath, "rb") as f_pdf:
pdfminer.high_level.extract_text_to_fp(f_pdf, **kwargs)
result = kwargs.get('outfp').getvalue()
except Exception:
logger.error('fail pdf to text parsing')
return result | python | def pdf_to_text(pdf_filepath='', **kwargs):
"""
Parse pdf to a list of strings using the pdfminer lib.
Args:
no_laparams=False,
all_texts=None,
detect_vertical=None, word_margin=None, char_margin=None,
line_margin=None, boxes_flow=None, codec='utf-8',
strip_control=False, maxpages=0, page_numbers=None, password="",
scale=1.0, rotation=0, layoutmode='normal', debug=False,
disable_caching=False,
"""
result = []
try:
if not os.path.exists(pdf_filepath):
raise ValueError("No valid pdf filepath introduced..")
# TODO: REVIEW THIS PARAMS
# update params if not defined
kwargs['outfp'] = kwargs.get('outfp', StringIO())
kwargs['laparams'] = kwargs.get('laparams', pdfminer.layout.LAParams())
kwargs['imagewriter'] = kwargs.get('imagewriter', None)
kwargs['output_type'] = kwargs.get('output_type', "text")
kwargs['codec'] = kwargs.get('codec', 'utf-8')
kwargs['disable_caching'] = kwargs.get('disable_caching', False)
with open(pdf_filepath, "rb") as f_pdf:
pdfminer.high_level.extract_text_to_fp(f_pdf, **kwargs)
result = kwargs.get('outfp').getvalue()
except Exception:
logger.error('fail pdf to text parsing')
return result | [
"def",
"pdf_to_text",
"(",
"pdf_filepath",
"=",
"''",
",",
"*",
"*",
"kwargs",
")",
":",
"result",
"=",
"[",
"]",
"try",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"pdf_filepath",
")",
":",
"raise",
"ValueError",
"(",
"\"No valid pdf file... | Parse pdf to a list of strings using the pdfminer lib.
Args:
no_laparams=False,
all_texts=None,
detect_vertical=None, word_margin=None, char_margin=None,
line_margin=None, boxes_flow=None, codec='utf-8',
strip_control=False, maxpages=0, page_numbers=None, password="",
scale=1.0, rotation=0, layoutmode='normal', debug=False,
disable_caching=False, | [
"Parse",
"pdf",
"to",
"a",
"list",
"of",
"strings",
"using",
"the",
"pdfminer",
"lib",
"."
] | train | https://github.com/Datary/scrapbag/blob/3a4f9824ab6fe21121214ba9963690618da2c9de/scrapbag/pdf.py#L24-L60 |
Datary/scrapbag | scrapbag/pdf.py | pdf_row_limiter | def pdf_row_limiter(rows, limits=None, **kwargs):
"""
Limit row passing a value. In this case we dont implementate a best effort
algorithm because the posibilities are infite with a data text structure
from a pdf.
"""
limits = limits or [None, None]
upper_limit = limits[0] if limits else None
lower_limit = limits[1] if len(limits) > 1 else None
return rows[upper_limit: lower_limit] | python | def pdf_row_limiter(rows, limits=None, **kwargs):
"""
Limit row passing a value. In this case we dont implementate a best effort
algorithm because the posibilities are infite with a data text structure
from a pdf.
"""
limits = limits or [None, None]
upper_limit = limits[0] if limits else None
lower_limit = limits[1] if len(limits) > 1 else None
return rows[upper_limit: lower_limit] | [
"def",
"pdf_row_limiter",
"(",
"rows",
",",
"limits",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"limits",
"=",
"limits",
"or",
"[",
"None",
",",
"None",
"]",
"upper_limit",
"=",
"limits",
"[",
"0",
"]",
"if",
"limits",
"else",
"None",
"lower_li... | Limit row passing a value. In this case we dont implementate a best effort
algorithm because the posibilities are infite with a data text structure
from a pdf. | [
"Limit",
"row",
"passing",
"a",
"value",
".",
"In",
"this",
"case",
"we",
"dont",
"implementate",
"a",
"best",
"effort",
"algorithm",
"because",
"the",
"posibilities",
"are",
"infite",
"with",
"a",
"data",
"text",
"structure",
"from",
"a",
"pdf",
"."
] | train | https://github.com/Datary/scrapbag/blob/3a4f9824ab6fe21121214ba9963690618da2c9de/scrapbag/pdf.py#L63-L74 |
Datary/scrapbag | scrapbag/pdf.py | pdf_to_dict | def pdf_to_dict(pdf_filepath, **kwargs):
"""
Main method to parse a pdf file to a dict.
"""
callbacks = {
'pdf_to_text': pdf_to_text,
'pdf_row_format': pdf_row_format,
'pdf_row_limiter': pdf_row_limiter,
'pdf_row_parser': pdf_row_parser,
'pdf_row_cleaner': pdf_row_cleaner
}
callbacks.update(kwargs.get('alt_callbacks', {}))
rows = kwargs.get('rows', [])
if not rows:
# pdf to string
rows_str = callbacks.get('pdf_to_text')(pdf_filepath, **kwargs)
# string to list of rows
rows = callbacks.get('pdf_row_format')(rows_str, **kwargs)
# apply limits
rows = callbacks.get('pdf_row_limiter')(rows, **kwargs)
# Parse data from rows to dict
rows = callbacks.get('pdf_row_parser')(rows, **kwargs)
# apply cleaner
rows = callbacks.get('pdf_row_cleaner')(rows)
return rows | python | def pdf_to_dict(pdf_filepath, **kwargs):
"""
Main method to parse a pdf file to a dict.
"""
callbacks = {
'pdf_to_text': pdf_to_text,
'pdf_row_format': pdf_row_format,
'pdf_row_limiter': pdf_row_limiter,
'pdf_row_parser': pdf_row_parser,
'pdf_row_cleaner': pdf_row_cleaner
}
callbacks.update(kwargs.get('alt_callbacks', {}))
rows = kwargs.get('rows', [])
if not rows:
# pdf to string
rows_str = callbacks.get('pdf_to_text')(pdf_filepath, **kwargs)
# string to list of rows
rows = callbacks.get('pdf_row_format')(rows_str, **kwargs)
# apply limits
rows = callbacks.get('pdf_row_limiter')(rows, **kwargs)
# Parse data from rows to dict
rows = callbacks.get('pdf_row_parser')(rows, **kwargs)
# apply cleaner
rows = callbacks.get('pdf_row_cleaner')(rows)
return rows | [
"def",
"pdf_to_dict",
"(",
"pdf_filepath",
",",
"*",
"*",
"kwargs",
")",
":",
"callbacks",
"=",
"{",
"'pdf_to_text'",
":",
"pdf_to_text",
",",
"'pdf_row_format'",
":",
"pdf_row_format",
",",
"'pdf_row_limiter'",
":",
"pdf_row_limiter",
",",
"'pdf_row_parser'",
":"... | Main method to parse a pdf file to a dict. | [
"Main",
"method",
"to",
"parse",
"a",
"pdf",
"file",
"to",
"a",
"dict",
"."
] | train | https://github.com/Datary/scrapbag/blob/3a4f9824ab6fe21121214ba9963690618da2c9de/scrapbag/pdf.py#L98-L131 |
etcher-be/epab | epab/utils/_stashed.py | stashed | def stashed(func):
"""
Simple decorator to stash changed files between a destructive repo operation
"""
@functools.wraps(func)
def _wrapper(*args, **kwargs):
if CTX.stash and not CTX.repo.stashed:
CTX.repo.stash(func.__name__)
try:
func(*args, **kwargs)
finally:
CTX.repo.unstash()
else:
func(*args, **kwargs)
return _wrapper | python | def stashed(func):
"""
Simple decorator to stash changed files between a destructive repo operation
"""
@functools.wraps(func)
def _wrapper(*args, **kwargs):
if CTX.stash and not CTX.repo.stashed:
CTX.repo.stash(func.__name__)
try:
func(*args, **kwargs)
finally:
CTX.repo.unstash()
else:
func(*args, **kwargs)
return _wrapper | [
"def",
"stashed",
"(",
"func",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"_wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"CTX",
".",
"stash",
"and",
"not",
"CTX",
".",
"repo",
".",
"stashed",
":",
... | Simple decorator to stash changed files between a destructive repo operation | [
"Simple",
"decorator",
"to",
"stash",
"changed",
"files",
"between",
"a",
"destructive",
"repo",
"operation"
] | train | https://github.com/etcher-be/epab/blob/024cde74d058281aa66e6e4b7b71dccbe803b1c1/epab/utils/_stashed.py#L11-L27 |
cltrudeau/screwdriver | screwdriver.py | dynamic_load | def dynamic_load(name):
"""Equivalent of "from X import Y" statement using dot notation to specify
what to import and return. For example, foo.bar.thing returns the item
"thing" in the module "foo.bar" """
pieces = name.split('.')
item = pieces[-1]
mod_name = '.'.join(pieces[:-1])
mod = __import__(mod_name, globals(), locals(), [item])
return getattr(mod, item) | python | def dynamic_load(name):
"""Equivalent of "from X import Y" statement using dot notation to specify
what to import and return. For example, foo.bar.thing returns the item
"thing" in the module "foo.bar" """
pieces = name.split('.')
item = pieces[-1]
mod_name = '.'.join(pieces[:-1])
mod = __import__(mod_name, globals(), locals(), [item])
return getattr(mod, item) | [
"def",
"dynamic_load",
"(",
"name",
")",
":",
"pieces",
"=",
"name",
".",
"split",
"(",
"'.'",
")",
"item",
"=",
"pieces",
"[",
"-",
"1",
"]",
"mod_name",
"=",
"'.'",
".",
"join",
"(",
"pieces",
"[",
":",
"-",
"1",
"]",
")",
"mod",
"=",
"__impo... | Equivalent of "from X import Y" statement using dot notation to specify
what to import and return. For example, foo.bar.thing returns the item
"thing" in the module "foo.bar" | [
"Equivalent",
"of",
"from",
"X",
"import",
"Y",
"statement",
"using",
"dot",
"notation",
"to",
"specify",
"what",
"to",
"import",
"and",
"return",
".",
"For",
"example",
"foo",
".",
"bar",
".",
"thing",
"returns",
"the",
"item",
"thing",
"in",
"the",
"mo... | train | https://github.com/cltrudeau/screwdriver/blob/6b70b545c5df1e6ac5a78367e47d63e3be1b57ba/screwdriver.py#L12-L21 |
cltrudeau/screwdriver | screwdriver.py | list_to_rows | def list_to_rows(src, size):
"""A generator that takes a enumerable item and returns a series of
slices. Useful for turning a list into a series of rows.
>>> list(list_to_rows([1, 2, 3, 4, 5, 6, 7], 3))
[[1, 2, 3], [4, 5, 6], [7, ]]
"""
row = []
for item in src:
row.append(item)
if len(row) == size:
yield row
row = []
if row:
yield row | python | def list_to_rows(src, size):
"""A generator that takes a enumerable item and returns a series of
slices. Useful for turning a list into a series of rows.
>>> list(list_to_rows([1, 2, 3, 4, 5, 6, 7], 3))
[[1, 2, 3], [4, 5, 6], [7, ]]
"""
row = []
for item in src:
row.append(item)
if len(row) == size:
yield row
row = []
if row:
yield row | [
"def",
"list_to_rows",
"(",
"src",
",",
"size",
")",
":",
"row",
"=",
"[",
"]",
"for",
"item",
"in",
"src",
":",
"row",
".",
"append",
"(",
"item",
")",
"if",
"len",
"(",
"row",
")",
"==",
"size",
":",
"yield",
"row",
"row",
"=",
"[",
"]",
"i... | A generator that takes a enumerable item and returns a series of
slices. Useful for turning a list into a series of rows.
>>> list(list_to_rows([1, 2, 3, 4, 5, 6, 7], 3))
[[1, 2, 3], [4, 5, 6], [7, ]] | [
"A",
"generator",
"that",
"takes",
"a",
"enumerable",
"item",
"and",
"returns",
"a",
"series",
"of",
"slices",
".",
"Useful",
"for",
"turning",
"a",
"list",
"into",
"a",
"series",
"of",
"rows",
"."
] | train | https://github.com/cltrudeau/screwdriver/blob/6b70b545c5df1e6ac5a78367e47d63e3be1b57ba/screwdriver.py#L82-L98 |
cltrudeau/screwdriver | screwdriver.py | head_tail_middle | def head_tail_middle(src):
"""Returns a tuple consisting of the head of a enumerable, the middle
as a list and the tail of the enumerable. If the enumerable is 1 item, the
middle will be empty and the tail will be None.
>>> head_tail_middle([1, 2, 3, 4])
1, [2, 3], 4
"""
if len(src) == 0:
return None, [], None
if len(src) == 1:
return src[0], [], None
if len(src) == 2:
return src[0], [], src[1]
return src[0], src[1:-1], src[-1] | python | def head_tail_middle(src):
"""Returns a tuple consisting of the head of a enumerable, the middle
as a list and the tail of the enumerable. If the enumerable is 1 item, the
middle will be empty and the tail will be None.
>>> head_tail_middle([1, 2, 3, 4])
1, [2, 3], 4
"""
if len(src) == 0:
return None, [], None
if len(src) == 1:
return src[0], [], None
if len(src) == 2:
return src[0], [], src[1]
return src[0], src[1:-1], src[-1] | [
"def",
"head_tail_middle",
"(",
"src",
")",
":",
"if",
"len",
"(",
"src",
")",
"==",
"0",
":",
"return",
"None",
",",
"[",
"]",
",",
"None",
"if",
"len",
"(",
"src",
")",
"==",
"1",
":",
"return",
"src",
"[",
"0",
"]",
",",
"[",
"]",
",",
"... | Returns a tuple consisting of the head of a enumerable, the middle
as a list and the tail of the enumerable. If the enumerable is 1 item, the
middle will be empty and the tail will be None.
>>> head_tail_middle([1, 2, 3, 4])
1, [2, 3], 4 | [
"Returns",
"a",
"tuple",
"consisting",
"of",
"the",
"head",
"of",
"a",
"enumerable",
"the",
"middle",
"as",
"a",
"list",
"and",
"the",
"tail",
"of",
"the",
"enumerable",
".",
"If",
"the",
"enumerable",
"is",
"1",
"item",
"the",
"middle",
"will",
"be",
... | train | https://github.com/cltrudeau/screwdriver/blob/6b70b545c5df1e6ac5a78367e47d63e3be1b57ba/screwdriver.py#L101-L119 |
scivision/gridaurora | gridaurora/calcemissions.py | calcemissions | def calcemissions(rates: xarray.DataArray, sim) -> Tuple[xarray.DataArray, np.ndarray, np.ndarray]:
if not sim.reacreq:
return 0., 0., 0.
ver = None
lamb = None
br = None
"""
Franck-Condon factor
http://chemistry.illinoisstate.edu/standard/che460/handouts/460-Feb28lec-S13.pdf
http://assign3.chem.usyd.edu.au/spectroscopy/index.php
"""
# %% METASTABLE
if 'metastable' in sim.reacreq:
ver, lamb, br = getMetastable(rates, ver, lamb, br, sim.reactionfn)
# %% PROMPT ATOMIC OXYGEN EMISSIONS
if 'atomic' in sim.reacreq:
ver, lamb, br = getAtomic(rates, ver, lamb, br, sim.reactionfn)
# %% N2 1N EMISSIONS
if 'n21ng' in sim.reacreq:
ver, lamb, br = getN21NG(rates, ver, lamb, br, sim.reactionfn)
# %% N2+ Meinel band
if 'n2meinel' in sim.reacreq:
ver, lamb, br = getN2meinel(rates, ver, lamb, br, sim.reactionfn)
# %% N2 2P (after Vallance Jones, 1974)
if 'n22pg' in sim.reacreq:
ver, lamb, br = getN22PG(rates, ver, lamb, br, sim.reactionfn)
# %% N2 1P
if 'n21pg' in sim.reacreq:
ver, lamb, br = getN21PG(rates, ver, lamb, br, sim.reactionfn)
# %% Remove NaN wavelength entries
if ver is None:
raise ValueError('you have not selected any reactions to generate VER')
# %% sort by wavelength, eliminate NaN
lamb, ver, br = sortelimlambda(lamb, ver, br)
# %% assemble output
dfver = xarray.DataArray(data=ver, coords=[('alt_km', rates.alt_km),
('wavelength_nm', lamb)])
return dfver, ver, br | python | def calcemissions(rates: xarray.DataArray, sim) -> Tuple[xarray.DataArray, np.ndarray, np.ndarray]:
if not sim.reacreq:
return 0., 0., 0.
ver = None
lamb = None
br = None
"""
Franck-Condon factor
http://chemistry.illinoisstate.edu/standard/che460/handouts/460-Feb28lec-S13.pdf
http://assign3.chem.usyd.edu.au/spectroscopy/index.php
"""
# %% METASTABLE
if 'metastable' in sim.reacreq:
ver, lamb, br = getMetastable(rates, ver, lamb, br, sim.reactionfn)
# %% PROMPT ATOMIC OXYGEN EMISSIONS
if 'atomic' in sim.reacreq:
ver, lamb, br = getAtomic(rates, ver, lamb, br, sim.reactionfn)
# %% N2 1N EMISSIONS
if 'n21ng' in sim.reacreq:
ver, lamb, br = getN21NG(rates, ver, lamb, br, sim.reactionfn)
# %% N2+ Meinel band
if 'n2meinel' in sim.reacreq:
ver, lamb, br = getN2meinel(rates, ver, lamb, br, sim.reactionfn)
# %% N2 2P (after Vallance Jones, 1974)
if 'n22pg' in sim.reacreq:
ver, lamb, br = getN22PG(rates, ver, lamb, br, sim.reactionfn)
# %% N2 1P
if 'n21pg' in sim.reacreq:
ver, lamb, br = getN21PG(rates, ver, lamb, br, sim.reactionfn)
# %% Remove NaN wavelength entries
if ver is None:
raise ValueError('you have not selected any reactions to generate VER')
# %% sort by wavelength, eliminate NaN
lamb, ver, br = sortelimlambda(lamb, ver, br)
# %% assemble output
dfver = xarray.DataArray(data=ver, coords=[('alt_km', rates.alt_km),
('wavelength_nm', lamb)])
return dfver, ver, br | [
"def",
"calcemissions",
"(",
"rates",
":",
"xarray",
".",
"DataArray",
",",
"sim",
")",
"->",
"Tuple",
"[",
"xarray",
".",
"DataArray",
",",
"np",
".",
"ndarray",
",",
"np",
".",
"ndarray",
"]",
":",
"if",
"not",
"sim",
".",
"reacreq",
":",
"return",... | Franck-Condon factor
http://chemistry.illinoisstate.edu/standard/che460/handouts/460-Feb28lec-S13.pdf
http://assign3.chem.usyd.edu.au/spectroscopy/index.php | [
"Franck",
"-",
"Condon",
"factor",
"http",
":",
"//",
"chemistry",
".",
"illinoisstate",
".",
"edu",
"/",
"standard",
"/",
"che460",
"/",
"handouts",
"/",
"460",
"-",
"Feb28lec",
"-",
"S13",
".",
"pdf",
"http",
":",
"//",
"assign3",
".",
"chem",
".",
... | train | https://github.com/scivision/gridaurora/blob/c3957b93c2201afff62bd104e0acead52c0d9e90/gridaurora/calcemissions.py#L20-L59 |
scivision/gridaurora | gridaurora/calcemissions.py | getMetastable | def getMetastable(rates, ver: np.ndarray, lamb, br, reactfn: Path):
with h5py.File(reactfn, 'r') as f:
A = f['/metastable/A'][:]
lambnew = f['/metastable/lambda'].value.ravel(order='F') # some are not 1-D!
"""
concatenate along the reaction dimension, axis=-1
"""
vnew = np.concatenate((A[:2] * rates.loc[..., 'no1s'].values[:, None],
A[2:4] * rates.loc[..., 'no1d'].values[:, None],
A[4:] * rates.loc[..., 'noii2p'].values[:, None]), axis=-1)
assert vnew.shape == (rates.shape[0], A.size)
return catvl(rates.alt_km, ver, vnew, lamb, lambnew, br) | python | def getMetastable(rates, ver: np.ndarray, lamb, br, reactfn: Path):
with h5py.File(reactfn, 'r') as f:
A = f['/metastable/A'][:]
lambnew = f['/metastable/lambda'].value.ravel(order='F') # some are not 1-D!
"""
concatenate along the reaction dimension, axis=-1
"""
vnew = np.concatenate((A[:2] * rates.loc[..., 'no1s'].values[:, None],
A[2:4] * rates.loc[..., 'no1d'].values[:, None],
A[4:] * rates.loc[..., 'noii2p'].values[:, None]), axis=-1)
assert vnew.shape == (rates.shape[0], A.size)
return catvl(rates.alt_km, ver, vnew, lamb, lambnew, br) | [
"def",
"getMetastable",
"(",
"rates",
",",
"ver",
":",
"np",
".",
"ndarray",
",",
"lamb",
",",
"br",
",",
"reactfn",
":",
"Path",
")",
":",
"with",
"h5py",
".",
"File",
"(",
"reactfn",
",",
"'r'",
")",
"as",
"f",
":",
"A",
"=",
"f",
"[",
"'/met... | concatenate along the reaction dimension, axis=-1 | [
"concatenate",
"along",
"the",
"reaction",
"dimension",
"axis",
"=",
"-",
"1"
] | train | https://github.com/scivision/gridaurora/blob/c3957b93c2201afff62bd104e0acead52c0d9e90/gridaurora/calcemissions.py#L62-L76 |
scivision/gridaurora | gridaurora/calcemissions.py | getAtomic | def getAtomic(rates, ver, lamb, br, reactfn):
""" prompt atomic emissions (nm)
844.6 777.4
"""
with h5py.File(reactfn, 'r') as f:
lambnew = f['/atomic/lambda'].value.ravel(order='F') # some are not 1-D!
vnew = np.concatenate((rates.loc[..., 'po3p3p'].values[..., None],
rates.loc[..., 'po3p5p'].values[..., None]), axis=-1)
return catvl(rates.alt_km, ver, vnew, lamb, lambnew, br) | python | def getAtomic(rates, ver, lamb, br, reactfn):
""" prompt atomic emissions (nm)
844.6 777.4
"""
with h5py.File(reactfn, 'r') as f:
lambnew = f['/atomic/lambda'].value.ravel(order='F') # some are not 1-D!
vnew = np.concatenate((rates.loc[..., 'po3p3p'].values[..., None],
rates.loc[..., 'po3p5p'].values[..., None]), axis=-1)
return catvl(rates.alt_km, ver, vnew, lamb, lambnew, br) | [
"def",
"getAtomic",
"(",
"rates",
",",
"ver",
",",
"lamb",
",",
"br",
",",
"reactfn",
")",
":",
"with",
"h5py",
".",
"File",
"(",
"reactfn",
",",
"'r'",
")",
"as",
"f",
":",
"lambnew",
"=",
"f",
"[",
"'/atomic/lambda'",
"]",
".",
"value",
".",
"r... | prompt atomic emissions (nm)
844.6 777.4 | [
"prompt",
"atomic",
"emissions",
"(",
"nm",
")",
"844",
".",
"6",
"777",
".",
"4"
] | train | https://github.com/scivision/gridaurora/blob/c3957b93c2201afff62bd104e0acead52c0d9e90/gridaurora/calcemissions.py#L79-L89 |
scivision/gridaurora | gridaurora/calcemissions.py | getN21NG | def getN21NG(rates, ver, lamb, br, reactfn):
"""
excitation Franck-Condon factors (derived from Vallance Jones, 1974)
"""
with h5py.File(str(reactfn), 'r', libver='latest') as f:
A = f['/N2+1NG/A'].value
lambdaA = f['/N2+1NG/lambda'].value.ravel(order='F')
franckcondon = f['/N2+1NG/fc'].value
return doBandTrapz(A, lambdaA, franckcondon, rates.loc[..., 'p1ng'], lamb, ver, rates.alt_km, br) | python | def getN21NG(rates, ver, lamb, br, reactfn):
"""
excitation Franck-Condon factors (derived from Vallance Jones, 1974)
"""
with h5py.File(str(reactfn), 'r', libver='latest') as f:
A = f['/N2+1NG/A'].value
lambdaA = f['/N2+1NG/lambda'].value.ravel(order='F')
franckcondon = f['/N2+1NG/fc'].value
return doBandTrapz(A, lambdaA, franckcondon, rates.loc[..., 'p1ng'], lamb, ver, rates.alt_km, br) | [
"def",
"getN21NG",
"(",
"rates",
",",
"ver",
",",
"lamb",
",",
"br",
",",
"reactfn",
")",
":",
"with",
"h5py",
".",
"File",
"(",
"str",
"(",
"reactfn",
")",
",",
"'r'",
",",
"libver",
"=",
"'latest'",
")",
"as",
"f",
":",
"A",
"=",
"f",
"[",
... | excitation Franck-Condon factors (derived from Vallance Jones, 1974) | [
"excitation",
"Franck",
"-",
"Condon",
"factors",
"(",
"derived",
"from",
"Vallance",
"Jones",
"1974",
")"
] | train | https://github.com/scivision/gridaurora/blob/c3957b93c2201afff62bd104e0acead52c0d9e90/gridaurora/calcemissions.py#L92-L101 |
scivision/gridaurora | gridaurora/calcemissions.py | getN21PG | def getN21PG(rates, ver, lamb, br, reactfn):
with h5py.File(str(reactfn), 'r', libver='latest') as fid:
A = fid['/N2_1PG/A'].value
lambnew = fid['/N2_1PG/lambda'].value.ravel(order='F')
franckcondon = fid['/N2_1PG/fc'].value
tau1PG = 1 / np.nansum(A, axis=1)
"""
solve for base concentration
confac=[1.66;1.56;1.31;1.07;.77;.5;.33;.17;.08;.04;.02;.004;.001]; %Cartwright, 1973b, stop at nuprime==12
Gattinger and Vallance Jones 1974
confac=array([1.66,1.86,1.57,1.07,.76,.45,.25,.14,.07,.03,.01,.004,.001])
"""
consfac = franckcondon/franckcondon.sum() # normalize
losscoef = (consfac / tau1PG).sum()
N01pg = rates.loc[..., 'p1pg'] / losscoef
scalevec = (A * consfac[:, None]).ravel(order='F') # for clarity (verified with matlab)
vnew = scalevec[None, None, :] * N01pg.values[..., None]
return catvl(rates.alt_km, ver, vnew, lamb, lambnew, br) | python | def getN21PG(rates, ver, lamb, br, reactfn):
with h5py.File(str(reactfn), 'r', libver='latest') as fid:
A = fid['/N2_1PG/A'].value
lambnew = fid['/N2_1PG/lambda'].value.ravel(order='F')
franckcondon = fid['/N2_1PG/fc'].value
tau1PG = 1 / np.nansum(A, axis=1)
"""
solve for base concentration
confac=[1.66;1.56;1.31;1.07;.77;.5;.33;.17;.08;.04;.02;.004;.001]; %Cartwright, 1973b, stop at nuprime==12
Gattinger and Vallance Jones 1974
confac=array([1.66,1.86,1.57,1.07,.76,.45,.25,.14,.07,.03,.01,.004,.001])
"""
consfac = franckcondon/franckcondon.sum() # normalize
losscoef = (consfac / tau1PG).sum()
N01pg = rates.loc[..., 'p1pg'] / losscoef
scalevec = (A * consfac[:, None]).ravel(order='F') # for clarity (verified with matlab)
vnew = scalevec[None, None, :] * N01pg.values[..., None]
return catvl(rates.alt_km, ver, vnew, lamb, lambnew, br) | [
"def",
"getN21PG",
"(",
"rates",
",",
"ver",
",",
"lamb",
",",
"br",
",",
"reactfn",
")",
":",
"with",
"h5py",
".",
"File",
"(",
"str",
"(",
"reactfn",
")",
",",
"'r'",
",",
"libver",
"=",
"'latest'",
")",
"as",
"fid",
":",
"A",
"=",
"fid",
"["... | solve for base concentration
confac=[1.66;1.56;1.31;1.07;.77;.5;.33;.17;.08;.04;.02;.004;.001]; %Cartwright, 1973b, stop at nuprime==12
Gattinger and Vallance Jones 1974
confac=array([1.66,1.86,1.57,1.07,.76,.45,.25,.14,.07,.03,.01,.004,.001]) | [
"solve",
"for",
"base",
"concentration",
"confac",
"=",
"[",
"1",
".",
"66",
";",
"1",
".",
"56",
";",
"1",
".",
"31",
";",
"1",
".",
"07",
";",
".",
"77",
";",
".",
"5",
";",
".",
"33",
";",
".",
"17",
";",
".",
"08",
";",
".",
"04",
"... | train | https://github.com/scivision/gridaurora/blob/c3957b93c2201afff62bd104e0acead52c0d9e90/gridaurora/calcemissions.py#L125-L148 |
scivision/gridaurora | gridaurora/calcemissions.py | doBandTrapz | def doBandTrapz(Aein, lambnew, fc, kin, lamb, ver, z, br):
"""
ver dimensions: wavelength, altitude, time
A and lambda dimensions:
axis 0 is upper state vib. level (nu')
axis 1 is bottom state vib level (nu'')
there is a Franck-Condon parameter (variable fc) for each upper state nu'
"""
tau = 1/np.nansum(Aein, axis=1)
scalevec = (Aein * tau[:, None] * fc[:, None]).ravel(order='F')
vnew = scalevec[None, None, :]*kin.values[..., None]
return catvl(z, ver, vnew, lamb, lambnew, br) | python | def doBandTrapz(Aein, lambnew, fc, kin, lamb, ver, z, br):
"""
ver dimensions: wavelength, altitude, time
A and lambda dimensions:
axis 0 is upper state vib. level (nu')
axis 1 is bottom state vib level (nu'')
there is a Franck-Condon parameter (variable fc) for each upper state nu'
"""
tau = 1/np.nansum(Aein, axis=1)
scalevec = (Aein * tau[:, None] * fc[:, None]).ravel(order='F')
vnew = scalevec[None, None, :]*kin.values[..., None]
return catvl(z, ver, vnew, lamb, lambnew, br) | [
"def",
"doBandTrapz",
"(",
"Aein",
",",
"lambnew",
",",
"fc",
",",
"kin",
",",
"lamb",
",",
"ver",
",",
"z",
",",
"br",
")",
":",
"tau",
"=",
"1",
"/",
"np",
".",
"nansum",
"(",
"Aein",
",",
"axis",
"=",
"1",
")",
"scalevec",
"=",
"(",
"Aein"... | ver dimensions: wavelength, altitude, time
A and lambda dimensions:
axis 0 is upper state vib. level (nu')
axis 1 is bottom state vib level (nu'')
there is a Franck-Condon parameter (variable fc) for each upper state nu' | [
"ver",
"dimensions",
":",
"wavelength",
"altitude",
"time"
] | train | https://github.com/scivision/gridaurora/blob/c3957b93c2201afff62bd104e0acead52c0d9e90/gridaurora/calcemissions.py#L151-L166 |
scivision/gridaurora | gridaurora/calcemissions.py | catvl | def catvl(z, ver, vnew, lamb, lambnew, br):
"""
trapz integrates over altitude axis, axis = -2
concatenate over reaction dimension, axis = -1
br: column integrated brightness
lamb: wavelength [nm]
ver: volume emission rate [photons / cm^-3 s^-3 ...]
"""
if ver is not None:
br = np.concatenate((br, np.trapz(vnew, z, axis=-2)), axis=-1) # must come first!
ver = np.concatenate((ver, vnew), axis=-1)
lamb = np.concatenate((lamb, lambnew))
else:
ver = vnew.copy(order='F')
lamb = lambnew.copy()
br = np.trapz(ver, z, axis=-2)
return ver, lamb, br | python | def catvl(z, ver, vnew, lamb, lambnew, br):
"""
trapz integrates over altitude axis, axis = -2
concatenate over reaction dimension, axis = -1
br: column integrated brightness
lamb: wavelength [nm]
ver: volume emission rate [photons / cm^-3 s^-3 ...]
"""
if ver is not None:
br = np.concatenate((br, np.trapz(vnew, z, axis=-2)), axis=-1) # must come first!
ver = np.concatenate((ver, vnew), axis=-1)
lamb = np.concatenate((lamb, lambnew))
else:
ver = vnew.copy(order='F')
lamb = lambnew.copy()
br = np.trapz(ver, z, axis=-2)
return ver, lamb, br | [
"def",
"catvl",
"(",
"z",
",",
"ver",
",",
"vnew",
",",
"lamb",
",",
"lambnew",
",",
"br",
")",
":",
"if",
"ver",
"is",
"not",
"None",
":",
"br",
"=",
"np",
".",
"concatenate",
"(",
"(",
"br",
",",
"np",
".",
"trapz",
"(",
"vnew",
",",
"z",
... | trapz integrates over altitude axis, axis = -2
concatenate over reaction dimension, axis = -1
br: column integrated brightness
lamb: wavelength [nm]
ver: volume emission rate [photons / cm^-3 s^-3 ...] | [
"trapz",
"integrates",
"over",
"altitude",
"axis",
"axis",
"=",
"-",
"2",
"concatenate",
"over",
"reaction",
"dimension",
"axis",
"=",
"-",
"1"
] | train | https://github.com/scivision/gridaurora/blob/c3957b93c2201afff62bd104e0acead52c0d9e90/gridaurora/calcemissions.py#L169-L187 |
victorfsf/djurls | djurls/config.py | uconf | def uconf(**kwargs):
"""
Function to set a default namespace/include.
It returns a decorator with the namespace/include argument already set.
Arguments:
- include: A custom URL list, previously
set on the module's urls.py;
- namespace: the URL's namespace.
"""
if len(kwargs) != 1:
# this function must have exactly
# one specific argument (namespace or include)
raise TypeError(
'uconf() takes exactly 1 argument. ({} given)'.format(len(kwargs))
)
# gets the argument name
arg_name = list(kwargs.keys()).pop(0)
# checks if it has a valid name (it must be 'namespace' or 'include')
if arg_name not in ['include', 'namespace']:
# if it's not a valid name, raise a TypeError
raise TypeError(
'Invalid argument: {}'.format(arg_name)
)
# creates the decorator with namespace/include already set.
return partial(umap, **kwargs) | python | def uconf(**kwargs):
"""
Function to set a default namespace/include.
It returns a decorator with the namespace/include argument already set.
Arguments:
- include: A custom URL list, previously
set on the module's urls.py;
- namespace: the URL's namespace.
"""
if len(kwargs) != 1:
# this function must have exactly
# one specific argument (namespace or include)
raise TypeError(
'uconf() takes exactly 1 argument. ({} given)'.format(len(kwargs))
)
# gets the argument name
arg_name = list(kwargs.keys()).pop(0)
# checks if it has a valid name (it must be 'namespace' or 'include')
if arg_name not in ['include', 'namespace']:
# if it's not a valid name, raise a TypeError
raise TypeError(
'Invalid argument: {}'.format(arg_name)
)
# creates the decorator with namespace/include already set.
return partial(umap, **kwargs) | [
"def",
"uconf",
"(",
"*",
"*",
"kwargs",
")",
":",
"if",
"len",
"(",
"kwargs",
")",
"!=",
"1",
":",
"# this function must have exactly",
"# one specific argument (namespace or include)",
"raise",
"TypeError",
"(",
"'uconf() takes exactly 1 argument. ({} given)'",
".",
"... | Function to set a default namespace/include.
It returns a decorator with the namespace/include argument already set.
Arguments:
- include: A custom URL list, previously
set on the module's urls.py;
- namespace: the URL's namespace. | [
"Function",
"to",
"set",
"a",
"default",
"namespace",
"/",
"include",
".",
"It",
"returns",
"a",
"decorator",
"with",
"the",
"namespace",
"/",
"include",
"argument",
"already",
"set",
".",
"Arguments",
":",
"-",
"include",
":",
"A",
"custom",
"URL",
"list"... | train | https://github.com/victorfsf/djurls/blob/c90a46e5e17c12dd6920100419a89e428baf4711/djurls/config.py#L6-L30 |
etcher-be/epab | epab/linters/_pep8.py | pep8 | def pep8(amend: bool = False, stage: bool = False):
"""
Runs Pyup's Safety tool (https://pyup.io/safety/)
Args:
amend: whether or not to commit results
stage: whether or not to stage changes
"""
_pep8(amend, stage) | python | def pep8(amend: bool = False, stage: bool = False):
"""
Runs Pyup's Safety tool (https://pyup.io/safety/)
Args:
amend: whether or not to commit results
stage: whether or not to stage changes
"""
_pep8(amend, stage) | [
"def",
"pep8",
"(",
"amend",
":",
"bool",
"=",
"False",
",",
"stage",
":",
"bool",
"=",
"False",
")",
":",
"_pep8",
"(",
"amend",
",",
"stage",
")"
] | Runs Pyup's Safety tool (https://pyup.io/safety/)
Args:
amend: whether or not to commit results
stage: whether or not to stage changes | [
"Runs",
"Pyup",
"s",
"Safety",
"tool",
"(",
"https",
":",
"//",
"pyup",
".",
"io",
"/",
"safety",
"/",
")"
] | train | https://github.com/etcher-be/epab/blob/024cde74d058281aa66e6e4b7b71dccbe803b1c1/epab/linters/_pep8.py#L30-L38 |
ttm/socialLegacy | social/twiter.py | Twitter.searchTag | def searchTag(self,HTAG="#arenaNETmundial"):
"""Set Twitter search or stream criteria for the selection of tweets"""
search = t.search(q=HTAG,count=100,result_type="recent")
ss=search[:]
search = t.search(q=HTAG,count=150,max_id=ss[-1]['id']-1,result_type="recent")
#search = t.search(q=HTAG,count=150,since_id=ss[-1]['id'],result_type="recent")
while seach:
ss+=search[:]
search = t.search(q=HTAG,count=150,max_id=ss[-1]['id']-1,result_type="recent") | python | def searchTag(self,HTAG="#arenaNETmundial"):
"""Set Twitter search or stream criteria for the selection of tweets"""
search = t.search(q=HTAG,count=100,result_type="recent")
ss=search[:]
search = t.search(q=HTAG,count=150,max_id=ss[-1]['id']-1,result_type="recent")
#search = t.search(q=HTAG,count=150,since_id=ss[-1]['id'],result_type="recent")
while seach:
ss+=search[:]
search = t.search(q=HTAG,count=150,max_id=ss[-1]['id']-1,result_type="recent") | [
"def",
"searchTag",
"(",
"self",
",",
"HTAG",
"=",
"\"#arenaNETmundial\"",
")",
":",
"search",
"=",
"t",
".",
"search",
"(",
"q",
"=",
"HTAG",
",",
"count",
"=",
"100",
",",
"result_type",
"=",
"\"recent\"",
")",
"ss",
"=",
"search",
"[",
":",
"]",
... | Set Twitter search or stream criteria for the selection of tweets | [
"Set",
"Twitter",
"search",
"or",
"stream",
"criteria",
"for",
"the",
"selection",
"of",
"tweets"
] | train | https://github.com/ttm/socialLegacy/blob/c0930cfe6e84392729449bf7c92569e1556fd109/social/twiter.py#L24-L32 |
COLORFULBOARD/revision | revision/file_transfer.py | FileTransfer.download | def download(self,
url,
dest_path=None):
"""
:param url:
:type url: str
:param dest_path:
:type dest_path: str
"""
if os.path.exists(dest_path):
os.remove(dest_path)
resp = get(url, stream=True)
size = int(resp.headers.get("content-length"))
label = "Downloading {filename} ({size:.2f}MB)".format(
filename=os.path.basename(dest_path),
size=size / float(self.chunk_size) / self.chunk_size
)
with open_file(dest_path, 'wb') as file:
content_iter = resp.iter_content(chunk_size=self.chunk_size)
with progressbar(content_iter,
length=size / self.chunk_size,
label=label) as bar:
for chunk in bar:
if chunk:
file.write(chunk)
file.flush() | python | def download(self,
url,
dest_path=None):
"""
:param url:
:type url: str
:param dest_path:
:type dest_path: str
"""
if os.path.exists(dest_path):
os.remove(dest_path)
resp = get(url, stream=True)
size = int(resp.headers.get("content-length"))
label = "Downloading {filename} ({size:.2f}MB)".format(
filename=os.path.basename(dest_path),
size=size / float(self.chunk_size) / self.chunk_size
)
with open_file(dest_path, 'wb') as file:
content_iter = resp.iter_content(chunk_size=self.chunk_size)
with progressbar(content_iter,
length=size / self.chunk_size,
label=label) as bar:
for chunk in bar:
if chunk:
file.write(chunk)
file.flush() | [
"def",
"download",
"(",
"self",
",",
"url",
",",
"dest_path",
"=",
"None",
")",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"dest_path",
")",
":",
"os",
".",
"remove",
"(",
"dest_path",
")",
"resp",
"=",
"get",
"(",
"url",
",",
"stream",
"=... | :param url:
:type url: str
:param dest_path:
:type dest_path: str | [
":",
"param",
"url",
":",
":",
"type",
"url",
":",
"str",
":",
"param",
"dest_path",
":",
":",
"type",
"dest_path",
":",
"str"
] | train | https://github.com/COLORFULBOARD/revision/blob/2f22e72cce5b60032a80c002ac45c2ecef0ed987/revision/file_transfer.py#L27-L54 |
COLORFULBOARD/revision | revision/file_transfer.py | FileTransfer.upload | def upload(self,
url,
method="POST",
file_path=None):
"""
:param url:
:type url: str
:param method:
:type method: str
:param file_path:
:type file_path: str
"""
if not os.path.exists(file_path):
raise RuntimeError("")
with open_file(file_path, 'rb') as file:
size = os.path.getsize(file_path)
label = "Uploading {filename} ({size:.2f}MB)".format(
filename=os.path.basename(file_path),
size=size / float(self.chunk_size) / self.chunk_size
)
if method == "PUT":
resp = put(url, data=file)
elif method == "POST":
resp = post(url, data=file)
content_iter = resp.iter_content(chunk_size=self.chunk_size)
with progressbar(content_iter,
length=size / self.chunk_size,
label=label) as bar:
for _ in bar:
pass | python | def upload(self,
url,
method="POST",
file_path=None):
"""
:param url:
:type url: str
:param method:
:type method: str
:param file_path:
:type file_path: str
"""
if not os.path.exists(file_path):
raise RuntimeError("")
with open_file(file_path, 'rb') as file:
size = os.path.getsize(file_path)
label = "Uploading {filename} ({size:.2f}MB)".format(
filename=os.path.basename(file_path),
size=size / float(self.chunk_size) / self.chunk_size
)
if method == "PUT":
resp = put(url, data=file)
elif method == "POST":
resp = post(url, data=file)
content_iter = resp.iter_content(chunk_size=self.chunk_size)
with progressbar(content_iter,
length=size / self.chunk_size,
label=label) as bar:
for _ in bar:
pass | [
"def",
"upload",
"(",
"self",
",",
"url",
",",
"method",
"=",
"\"POST\"",
",",
"file_path",
"=",
"None",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"file_path",
")",
":",
"raise",
"RuntimeError",
"(",
"\"\"",
")",
"with",
"open_fil... | :param url:
:type url: str
:param method:
:type method: str
:param file_path:
:type file_path: str | [
":",
"param",
"url",
":",
":",
"type",
"url",
":",
"str",
":",
"param",
"method",
":",
":",
"type",
"method",
":",
"str",
":",
"param",
"file_path",
":",
":",
"type",
"file_path",
":",
"str"
] | train | https://github.com/COLORFULBOARD/revision/blob/2f22e72cce5b60032a80c002ac45c2ecef0ed987/revision/file_transfer.py#L56-L89 |
earlye/nephele | nephele/AwsLogStream.py | AwsLogStream.do_tail | def do_tail(self,args):
"""Tail the logs"""
response = AwsConnectionFactory.getLogClient().get_log_events(
logGroupName=self.logStream['logGroupName'],
logStreamName=self.logStream['logStreamName'],
limit=10,
startFromHead=False
)
pprint(response) | python | def do_tail(self,args):
"""Tail the logs"""
response = AwsConnectionFactory.getLogClient().get_log_events(
logGroupName=self.logStream['logGroupName'],
logStreamName=self.logStream['logStreamName'],
limit=10,
startFromHead=False
)
pprint(response) | [
"def",
"do_tail",
"(",
"self",
",",
"args",
")",
":",
"response",
"=",
"AwsConnectionFactory",
".",
"getLogClient",
"(",
")",
".",
"get_log_events",
"(",
"logGroupName",
"=",
"self",
".",
"logStream",
"[",
"'logGroupName'",
"]",
",",
"logStreamName",
"=",
"s... | Tail the logs | [
"Tail",
"the",
"logs"
] | train | https://github.com/earlye/nephele/blob/a7dadc68f4124671457f09119419978c4d22013e/nephele/AwsLogStream.py#L15-L23 |
mozilla/socorrolib | socorrolib/lib/migrations.py | get_local_filepath | def get_local_filepath(filename):
"""
Helper for finding our raw SQL files locally.
Expects files to be in:
$SOCORRO_PATH/socorrolib/external/postgresql/raw_sql/procs/
"""
procs_dir = os.path.normpath(os.path.join(
__file__,
'../../',
'external/postgresql/raw_sql/procs'
))
return os.path.join(procs_dir, filename) | python | def get_local_filepath(filename):
"""
Helper for finding our raw SQL files locally.
Expects files to be in:
$SOCORRO_PATH/socorrolib/external/postgresql/raw_sql/procs/
"""
procs_dir = os.path.normpath(os.path.join(
__file__,
'../../',
'external/postgresql/raw_sql/procs'
))
return os.path.join(procs_dir, filename) | [
"def",
"get_local_filepath",
"(",
"filename",
")",
":",
"procs_dir",
"=",
"os",
".",
"path",
".",
"normpath",
"(",
"os",
".",
"path",
".",
"join",
"(",
"__file__",
",",
"'../../'",
",",
"'external/postgresql/raw_sql/procs'",
")",
")",
"return",
"os",
".",
... | Helper for finding our raw SQL files locally.
Expects files to be in:
$SOCORRO_PATH/socorrolib/external/postgresql/raw_sql/procs/ | [
"Helper",
"for",
"finding",
"our",
"raw",
"SQL",
"files",
"locally",
"."
] | train | https://github.com/mozilla/socorrolib/blob/4ec08c6a4ee2c8a69150268afdd324f5f22b90c8/socorrolib/lib/migrations.py#L16-L28 |
mozilla/socorrolib | socorrolib/lib/migrations.py | load_stored_proc | def load_stored_proc(op, filelist):
"""
Takes the alembic op object as arguments and a list of files as arguments
Load and run CREATE OR REPLACE function commands from files
"""
for filename in filelist:
sqlfile = get_local_filepath(filename)
# Capturing "file not exists" here rather than allowing
# an exception to be thrown. Some of the rollback scripts
# would otherwise throw unhelpful exceptions when a SQL
# file is removed from the repo.
if not os.path.isfile(sqlfile):
warnings.warn(
"Did not find %r. Continuing migration." % sqlfile,
UserWarning,
2
)
continue
with open(sqlfile, 'r') as stored_proc:
op.execute(stored_proc.read()) | python | def load_stored_proc(op, filelist):
"""
Takes the alembic op object as arguments and a list of files as arguments
Load and run CREATE OR REPLACE function commands from files
"""
for filename in filelist:
sqlfile = get_local_filepath(filename)
# Capturing "file not exists" here rather than allowing
# an exception to be thrown. Some of the rollback scripts
# would otherwise throw unhelpful exceptions when a SQL
# file is removed from the repo.
if not os.path.isfile(sqlfile):
warnings.warn(
"Did not find %r. Continuing migration." % sqlfile,
UserWarning,
2
)
continue
with open(sqlfile, 'r') as stored_proc:
op.execute(stored_proc.read()) | [
"def",
"load_stored_proc",
"(",
"op",
",",
"filelist",
")",
":",
"for",
"filename",
"in",
"filelist",
":",
"sqlfile",
"=",
"get_local_filepath",
"(",
"filename",
")",
"# Capturing \"file not exists\" here rather than allowing",
"# an exception to be thrown. Some of the rollba... | Takes the alembic op object as arguments and a list of files as arguments
Load and run CREATE OR REPLACE function commands from files | [
"Takes",
"the",
"alembic",
"op",
"object",
"as",
"arguments",
"and",
"a",
"list",
"of",
"files",
"as",
"arguments",
"Load",
"and",
"run",
"CREATE",
"OR",
"REPLACE",
"function",
"commands",
"from",
"files"
] | train | https://github.com/mozilla/socorrolib/blob/4ec08c6a4ee2c8a69150268afdd324f5f22b90c8/socorrolib/lib/migrations.py#L31-L50 |
coded-by-hand/mass | env/lib/python2.7/site-packages/pip-1.0.2-py2.7.egg/pip/util.py | rmtree_errorhandler | def rmtree_errorhandler(func, path, exc_info):
"""On Windows, the files in .svn are read-only, so when rmtree() tries to
remove them, an exception is thrown. We catch that here, remove the
read-only attribute, and hopefully continue without problems."""
exctype, value = exc_info[:2]
# On Python 2.4, it will be OSError number 13
# On all more recent Pythons, it'll be WindowsError number 5
if not ((exctype is WindowsError and value.args[0] == 5) or
(exctype is OSError and value.args[0] == 13)):
raise
# file type should currently be read only
if ((os.stat(path).st_mode & stat.S_IREAD) != stat.S_IREAD):
raise
# convert to read/write
os.chmod(path, stat.S_IWRITE)
# use the original function to repeat the operation
func(path) | python | def rmtree_errorhandler(func, path, exc_info):
"""On Windows, the files in .svn are read-only, so when rmtree() tries to
remove them, an exception is thrown. We catch that here, remove the
read-only attribute, and hopefully continue without problems."""
exctype, value = exc_info[:2]
# On Python 2.4, it will be OSError number 13
# On all more recent Pythons, it'll be WindowsError number 5
if not ((exctype is WindowsError and value.args[0] == 5) or
(exctype is OSError and value.args[0] == 13)):
raise
# file type should currently be read only
if ((os.stat(path).st_mode & stat.S_IREAD) != stat.S_IREAD):
raise
# convert to read/write
os.chmod(path, stat.S_IWRITE)
# use the original function to repeat the operation
func(path) | [
"def",
"rmtree_errorhandler",
"(",
"func",
",",
"path",
",",
"exc_info",
")",
":",
"exctype",
",",
"value",
"=",
"exc_info",
"[",
":",
"2",
"]",
"# On Python 2.4, it will be OSError number 13",
"# On all more recent Pythons, it'll be WindowsError number 5",
"if",
"not",
... | On Windows, the files in .svn are read-only, so when rmtree() tries to
remove them, an exception is thrown. We catch that here, remove the
read-only attribute, and hopefully continue without problems. | [
"On",
"Windows",
"the",
"files",
"in",
".",
"svn",
"are",
"read",
"-",
"only",
"so",
"when",
"rmtree",
"()",
"tries",
"to",
"remove",
"them",
"an",
"exception",
"is",
"thrown",
".",
"We",
"catch",
"that",
"here",
"remove",
"the",
"read",
"-",
"only",
... | train | https://github.com/coded-by-hand/mass/blob/59005479efed3cd8598a8f0c66791a4482071899/env/lib/python2.7/site-packages/pip-1.0.2-py2.7.egg/pip/util.py#L32-L48 |
coded-by-hand/mass | env/lib/python2.7/site-packages/pip-1.0.2-py2.7.egg/pip/util.py | display_path | def display_path(path):
"""Gives the display value for a given path, making it relative to cwd
if possible."""
path = os.path.normcase(os.path.abspath(path))
if path.startswith(os.getcwd() + os.path.sep):
path = '.' + path[len(os.getcwd()):]
return path | python | def display_path(path):
"""Gives the display value for a given path, making it relative to cwd
if possible."""
path = os.path.normcase(os.path.abspath(path))
if path.startswith(os.getcwd() + os.path.sep):
path = '.' + path[len(os.getcwd()):]
return path | [
"def",
"display_path",
"(",
"path",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"normcase",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"path",
")",
")",
"if",
"path",
".",
"startswith",
"(",
"os",
".",
"getcwd",
"(",
")",
"+",
"os",
".",
"... | Gives the display value for a given path, making it relative to cwd
if possible. | [
"Gives",
"the",
"display",
"value",
"for",
"a",
"given",
"path",
"making",
"it",
"relative",
"to",
"cwd",
"if",
"possible",
"."
] | train | https://github.com/coded-by-hand/mass/blob/59005479efed3cd8598a8f0c66791a4482071899/env/lib/python2.7/site-packages/pip-1.0.2-py2.7.egg/pip/util.py#L51-L57 |
coded-by-hand/mass | env/lib/python2.7/site-packages/pip-1.0.2-py2.7.egg/pip/util.py | get_pathext | def get_pathext(default_pathext=None):
"""Returns the path extensions from environment or a default"""
if default_pathext is None:
default_pathext = os.pathsep.join([ '.COM', '.EXE', '.BAT', '.CMD' ])
pathext = os.environ.get('PATHEXT', default_pathext)
return pathext | python | def get_pathext(default_pathext=None):
"""Returns the path extensions from environment or a default"""
if default_pathext is None:
default_pathext = os.pathsep.join([ '.COM', '.EXE', '.BAT', '.CMD' ])
pathext = os.environ.get('PATHEXT', default_pathext)
return pathext | [
"def",
"get_pathext",
"(",
"default_pathext",
"=",
"None",
")",
":",
"if",
"default_pathext",
"is",
"None",
":",
"default_pathext",
"=",
"os",
".",
"pathsep",
".",
"join",
"(",
"[",
"'.COM'",
",",
"'.EXE'",
",",
"'.BAT'",
",",
"'.CMD'",
"]",
")",
"pathex... | Returns the path extensions from environment or a default | [
"Returns",
"the",
"path",
"extensions",
"from",
"environment",
"or",
"a",
"default"
] | train | https://github.com/coded-by-hand/mass/blob/59005479efed3cd8598a8f0c66791a4482071899/env/lib/python2.7/site-packages/pip-1.0.2-py2.7.egg/pip/util.py#L98-L103 |
coded-by-hand/mass | env/lib/python2.7/site-packages/pip-1.0.2-py2.7.egg/pip/util.py | ask | def ask(message, options):
"""Ask the message interactively, with the given possible responses"""
while 1:
if os.environ.get('PIP_NO_INPUT'):
raise Exception('No input was expected ($PIP_NO_INPUT set); question: %s' % message)
response = raw_input(message)
response = response.strip().lower()
if response not in options:
print('Your response (%r) was not one of the expected responses: %s' % (
response, ', '.join(options)))
else:
return response | python | def ask(message, options):
"""Ask the message interactively, with the given possible responses"""
while 1:
if os.environ.get('PIP_NO_INPUT'):
raise Exception('No input was expected ($PIP_NO_INPUT set); question: %s' % message)
response = raw_input(message)
response = response.strip().lower()
if response not in options:
print('Your response (%r) was not one of the expected responses: %s' % (
response, ', '.join(options)))
else:
return response | [
"def",
"ask",
"(",
"message",
",",
"options",
")",
":",
"while",
"1",
":",
"if",
"os",
".",
"environ",
".",
"get",
"(",
"'PIP_NO_INPUT'",
")",
":",
"raise",
"Exception",
"(",
"'No input was expected ($PIP_NO_INPUT set); question: %s'",
"%",
"message",
")",
"re... | Ask the message interactively, with the given possible responses | [
"Ask",
"the",
"message",
"interactively",
"with",
"the",
"given",
"possible",
"responses"
] | train | https://github.com/coded-by-hand/mass/blob/59005479efed3cd8598a8f0c66791a4482071899/env/lib/python2.7/site-packages/pip-1.0.2-py2.7.egg/pip/util.py#L105-L116 |
coded-by-hand/mass | env/lib/python2.7/site-packages/pip-1.0.2-py2.7.egg/pip/util.py | get_installed_distributions | def get_installed_distributions(local_only=True, skip=('setuptools', 'pip', 'python')):
"""
Return a list of installed Distribution objects.
If ``local_only`` is True (default), only return installations
local to the current virtualenv, if in a virtualenv.
``skip`` argument is an iterable of lower-case project names to
ignore; defaults to ('setuptools', 'pip', 'python'). [FIXME also
skip virtualenv?]
"""
if local_only:
local_test = dist_is_local
else:
local_test = lambda d: True
return [d for d in pkg_resources.working_set if local_test(d) and d.key not in skip] | python | def get_installed_distributions(local_only=True, skip=('setuptools', 'pip', 'python')):
"""
Return a list of installed Distribution objects.
If ``local_only`` is True (default), only return installations
local to the current virtualenv, if in a virtualenv.
``skip`` argument is an iterable of lower-case project names to
ignore; defaults to ('setuptools', 'pip', 'python'). [FIXME also
skip virtualenv?]
"""
if local_only:
local_test = dist_is_local
else:
local_test = lambda d: True
return [d for d in pkg_resources.working_set if local_test(d) and d.key not in skip] | [
"def",
"get_installed_distributions",
"(",
"local_only",
"=",
"True",
",",
"skip",
"=",
"(",
"'setuptools'",
",",
"'pip'",
",",
"'python'",
")",
")",
":",
"if",
"local_only",
":",
"local_test",
"=",
"dist_is_local",
"else",
":",
"local_test",
"=",
"lambda",
... | Return a list of installed Distribution objects.
If ``local_only`` is True (default), only return installations
local to the current virtualenv, if in a virtualenv.
``skip`` argument is an iterable of lower-case project names to
ignore; defaults to ('setuptools', 'pip', 'python'). [FIXME also
skip virtualenv?] | [
"Return",
"a",
"list",
"of",
"installed",
"Distribution",
"objects",
"."
] | train | https://github.com/coded-by-hand/mass/blob/59005479efed3cd8598a8f0c66791a4482071899/env/lib/python2.7/site-packages/pip-1.0.2-py2.7.egg/pip/util.py#L288-L304 |
coded-by-hand/mass | env/lib/python2.7/site-packages/pip-1.0.2-py2.7.egg/pip/util.py | dist_location | def dist_location(dist):
"""
Get the site-packages location of this distribution. Generally
this is dist.location, except in the case of develop-installed
packages, where dist.location is the source code location, and we
want to know where the egg-link file is.
"""
egg_link = egg_link_path(dist)
if os.path.exists(egg_link):
return egg_link
return dist.location | python | def dist_location(dist):
"""
Get the site-packages location of this distribution. Generally
this is dist.location, except in the case of develop-installed
packages, where dist.location is the source code location, and we
want to know where the egg-link file is.
"""
egg_link = egg_link_path(dist)
if os.path.exists(egg_link):
return egg_link
return dist.location | [
"def",
"dist_location",
"(",
"dist",
")",
":",
"egg_link",
"=",
"egg_link_path",
"(",
"dist",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"egg_link",
")",
":",
"return",
"egg_link",
"return",
"dist",
".",
"location"
] | Get the site-packages location of this distribution. Generally
this is dist.location, except in the case of develop-installed
packages, where dist.location is the source code location, and we
want to know where the egg-link file is. | [
"Get",
"the",
"site",
"-",
"packages",
"location",
"of",
"this",
"distribution",
".",
"Generally",
"this",
"is",
"dist",
".",
"location",
"except",
"in",
"the",
"case",
"of",
"develop",
"-",
"installed",
"packages",
"where",
"dist",
".",
"location",
"is",
... | train | https://github.com/coded-by-hand/mass/blob/59005479efed3cd8598a8f0c66791a4482071899/env/lib/python2.7/site-packages/pip-1.0.2-py2.7.egg/pip/util.py#L321-L332 |
coded-by-hand/mass | env/lib/python2.7/site-packages/pip-1.0.2-py2.7.egg/pip/util.py | unzip_file | def unzip_file(filename, location, flatten=True):
"""Unzip the file (zip file located at filename) to the destination
location"""
if not os.path.exists(location):
os.makedirs(location)
zipfp = open(filename, 'rb')
try:
zip = zipfile.ZipFile(zipfp)
leading = has_leading_dir(zip.namelist()) and flatten
for name in zip.namelist():
data = zip.read(name)
fn = name
if leading:
fn = split_leading_dir(name)[1]
fn = os.path.join(location, fn)
dir = os.path.dirname(fn)
if not os.path.exists(dir):
os.makedirs(dir)
if fn.endswith('/') or fn.endswith('\\'):
# A directory
if not os.path.exists(fn):
os.makedirs(fn)
else:
fp = open(fn, 'wb')
try:
fp.write(data)
finally:
fp.close()
finally:
zipfp.close() | python | def unzip_file(filename, location, flatten=True):
"""Unzip the file (zip file located at filename) to the destination
location"""
if not os.path.exists(location):
os.makedirs(location)
zipfp = open(filename, 'rb')
try:
zip = zipfile.ZipFile(zipfp)
leading = has_leading_dir(zip.namelist()) and flatten
for name in zip.namelist():
data = zip.read(name)
fn = name
if leading:
fn = split_leading_dir(name)[1]
fn = os.path.join(location, fn)
dir = os.path.dirname(fn)
if not os.path.exists(dir):
os.makedirs(dir)
if fn.endswith('/') or fn.endswith('\\'):
# A directory
if not os.path.exists(fn):
os.makedirs(fn)
else:
fp = open(fn, 'wb')
try:
fp.write(data)
finally:
fp.close()
finally:
zipfp.close() | [
"def",
"unzip_file",
"(",
"filename",
",",
"location",
",",
"flatten",
"=",
"True",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"location",
")",
":",
"os",
".",
"makedirs",
"(",
"location",
")",
"zipfp",
"=",
"open",
"(",
"filename"... | Unzip the file (zip file located at filename) to the destination
location | [
"Unzip",
"the",
"file",
"(",
"zip",
"file",
"located",
"at",
"filename",
")",
"to",
"the",
"destination",
"location"
] | train | https://github.com/coded-by-hand/mass/blob/59005479efed3cd8598a8f0c66791a4482071899/env/lib/python2.7/site-packages/pip-1.0.2-py2.7.egg/pip/util.py#L365-L394 |
coded-by-hand/mass | env/lib/python2.7/site-packages/pip-1.0.2-py2.7.egg/pip/util.py | untar_file | def untar_file(filename, location):
"""Untar the file (tar file located at filename) to the destination location"""
if not os.path.exists(location):
os.makedirs(location)
if filename.lower().endswith('.gz') or filename.lower().endswith('.tgz'):
mode = 'r:gz'
elif filename.lower().endswith('.bz2') or filename.lower().endswith('.tbz'):
mode = 'r:bz2'
elif filename.lower().endswith('.tar'):
mode = 'r'
else:
logger.warn('Cannot determine compression type for file %s' % filename)
mode = 'r:*'
tar = tarfile.open(filename, mode)
try:
# note: python<=2.5 doesnt seem to know about pax headers, filter them
leading = has_leading_dir([
member.name for member in tar.getmembers()
if member.name != 'pax_global_header'
])
for member in tar.getmembers():
fn = member.name
if fn == 'pax_global_header':
continue
if leading:
fn = split_leading_dir(fn)[1]
path = os.path.join(location, fn)
if member.isdir():
if not os.path.exists(path):
os.makedirs(path)
else:
try:
fp = tar.extractfile(member)
except (KeyError, AttributeError):
e = sys.exc_info()[1]
# Some corrupt tar files seem to produce this
# (specifically bad symlinks)
logger.warn(
'In the tar file %s the member %s is invalid: %s'
% (filename, member.name, e))
continue
if not os.path.exists(os.path.dirname(path)):
os.makedirs(os.path.dirname(path))
destfp = open(path, 'wb')
try:
shutil.copyfileobj(fp, destfp)
finally:
destfp.close()
fp.close()
finally:
tar.close() | python | def untar_file(filename, location):
"""Untar the file (tar file located at filename) to the destination location"""
if not os.path.exists(location):
os.makedirs(location)
if filename.lower().endswith('.gz') or filename.lower().endswith('.tgz'):
mode = 'r:gz'
elif filename.lower().endswith('.bz2') or filename.lower().endswith('.tbz'):
mode = 'r:bz2'
elif filename.lower().endswith('.tar'):
mode = 'r'
else:
logger.warn('Cannot determine compression type for file %s' % filename)
mode = 'r:*'
tar = tarfile.open(filename, mode)
try:
# note: python<=2.5 doesnt seem to know about pax headers, filter them
leading = has_leading_dir([
member.name for member in tar.getmembers()
if member.name != 'pax_global_header'
])
for member in tar.getmembers():
fn = member.name
if fn == 'pax_global_header':
continue
if leading:
fn = split_leading_dir(fn)[1]
path = os.path.join(location, fn)
if member.isdir():
if not os.path.exists(path):
os.makedirs(path)
else:
try:
fp = tar.extractfile(member)
except (KeyError, AttributeError):
e = sys.exc_info()[1]
# Some corrupt tar files seem to produce this
# (specifically bad symlinks)
logger.warn(
'In the tar file %s the member %s is invalid: %s'
% (filename, member.name, e))
continue
if not os.path.exists(os.path.dirname(path)):
os.makedirs(os.path.dirname(path))
destfp = open(path, 'wb')
try:
shutil.copyfileobj(fp, destfp)
finally:
destfp.close()
fp.close()
finally:
tar.close() | [
"def",
"untar_file",
"(",
"filename",
",",
"location",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"location",
")",
":",
"os",
".",
"makedirs",
"(",
"location",
")",
"if",
"filename",
".",
"lower",
"(",
")",
".",
"endswith",
"(",
... | Untar the file (tar file located at filename) to the destination location | [
"Untar",
"the",
"file",
"(",
"tar",
"file",
"located",
"at",
"filename",
")",
"to",
"the",
"destination",
"location"
] | train | https://github.com/coded-by-hand/mass/blob/59005479efed3cd8598a8f0c66791a4482071899/env/lib/python2.7/site-packages/pip-1.0.2-py2.7.egg/pip/util.py#L397-L447 |
salesking/salesking_python_sdk | salesking/utils/schema.py | _value_properties_are_referenced | def _value_properties_are_referenced(val):
"""
val is a dictionary
:param val:
:return: True/False
"""
if ((u'properties' in val.keys()) and
(u'$ref' in val['properties'].keys())):
return True
return False | python | def _value_properties_are_referenced(val):
"""
val is a dictionary
:param val:
:return: True/False
"""
if ((u'properties' in val.keys()) and
(u'$ref' in val['properties'].keys())):
return True
return False | [
"def",
"_value_properties_are_referenced",
"(",
"val",
")",
":",
"if",
"(",
"(",
"u'properties'",
"in",
"val",
".",
"keys",
"(",
")",
")",
"and",
"(",
"u'$ref'",
"in",
"val",
"[",
"'properties'",
"]",
".",
"keys",
"(",
")",
")",
")",
":",
"return",
"... | val is a dictionary
:param val:
:return: True/False | [
"val",
"is",
"a",
"dictionary",
":",
"param",
"val",
":",
":",
"return",
":",
"True",
"/",
"False"
] | train | https://github.com/salesking/salesking_python_sdk/blob/0d5a95c5ee4e16a85562ceaf67bb11b55e47ee4c/salesking/utils/schema.py#L6-L15 |
salesking/salesking_python_sdk | salesking/utils/schema.py | _value_is_type_text | def _value_is_type_text(val):
"""
val is a dictionary
:param val:
:return: True/False
"""
if ((u'type' in val.keys()) and
(val['type'].lower() == u"text")):
return True
return False | python | def _value_is_type_text(val):
"""
val is a dictionary
:param val:
:return: True/False
"""
if ((u'type' in val.keys()) and
(val['type'].lower() == u"text")):
return True
return False | [
"def",
"_value_is_type_text",
"(",
"val",
")",
":",
"if",
"(",
"(",
"u'type'",
"in",
"val",
".",
"keys",
"(",
")",
")",
"and",
"(",
"val",
"[",
"'type'",
"]",
".",
"lower",
"(",
")",
"==",
"u\"text\"",
")",
")",
":",
"return",
"True",
"return",
"... | val is a dictionary
:param val:
:return: True/False | [
"val",
"is",
"a",
"dictionary",
":",
"param",
"val",
":",
":",
"return",
":",
"True",
"/",
"False"
] | train | https://github.com/salesking/salesking_python_sdk/blob/0d5a95c5ee4e16a85562ceaf67bb11b55e47ee4c/salesking/utils/schema.py#L43-L52 |
uw-it-aca/uw-restclients-uwnetid | uw_uwnetid/subscription_60.py | _has_desired_permit | def _has_desired_permit(permits, acategory, astatus):
"""
return True if permits has one whose
category_code and status_code match with the given ones
"""
if permits is None:
return False
for permit in permits:
if permit.category_code == acategory and\
permit.status_code == astatus:
return True
return False | python | def _has_desired_permit(permits, acategory, astatus):
"""
return True if permits has one whose
category_code and status_code match with the given ones
"""
if permits is None:
return False
for permit in permits:
if permit.category_code == acategory and\
permit.status_code == astatus:
return True
return False | [
"def",
"_has_desired_permit",
"(",
"permits",
",",
"acategory",
",",
"astatus",
")",
":",
"if",
"permits",
"is",
"None",
":",
"return",
"False",
"for",
"permit",
"in",
"permits",
":",
"if",
"permit",
".",
"category_code",
"==",
"acategory",
"and",
"permit",
... | return True if permits has one whose
category_code and status_code match with the given ones | [
"return",
"True",
"if",
"permits",
"has",
"one",
"whose",
"category_code",
"and",
"status_code",
"match",
"with",
"the",
"given",
"ones"
] | train | https://github.com/uw-it-aca/uw-restclients-uwnetid/blob/58c78b564f9c920a8f8fd408eec959ddd5605b0b/uw_uwnetid/subscription_60.py#L35-L46 |
spreecode/python-sofort | sofort/xml.py | __compact_notification_addresses | def __compact_notification_addresses(addresses_):
"""
Input::
{
'default': 'http://domain/notice',
'event1': 'http://domain/notice',
'event2': 'http://domain/notice',
'event3': 'http://domain/notice3',
'event4': 'http://domain/notice3'
}
Output::
{
'default': 'http://domain/notice',
'event1,event2': 'http://domain/notice',
'event3,event4': 'http://domain/notice3'
}
"""
result = {}
addresses = dict(addresses_)
default = addresses.pop('default', None)
for key, value in __reverse_group_dict(addresses).items():
result[','.join(value)] = key
if default:
result['default'] = default
return result | python | def __compact_notification_addresses(addresses_):
"""
Input::
{
'default': 'http://domain/notice',
'event1': 'http://domain/notice',
'event2': 'http://domain/notice',
'event3': 'http://domain/notice3',
'event4': 'http://domain/notice3'
}
Output::
{
'default': 'http://domain/notice',
'event1,event2': 'http://domain/notice',
'event3,event4': 'http://domain/notice3'
}
"""
result = {}
addresses = dict(addresses_)
default = addresses.pop('default', None)
for key, value in __reverse_group_dict(addresses).items():
result[','.join(value)] = key
if default:
result['default'] = default
return result | [
"def",
"__compact_notification_addresses",
"(",
"addresses_",
")",
":",
"result",
"=",
"{",
"}",
"addresses",
"=",
"dict",
"(",
"addresses_",
")",
"default",
"=",
"addresses",
".",
"pop",
"(",
"'default'",
",",
"None",
")",
"for",
"key",
",",
"value",
"in"... | Input::
{
'default': 'http://domain/notice',
'event1': 'http://domain/notice',
'event2': 'http://domain/notice',
'event3': 'http://domain/notice3',
'event4': 'http://domain/notice3'
}
Output::
{
'default': 'http://domain/notice',
'event1,event2': 'http://domain/notice',
'event3,event4': 'http://domain/notice3'
} | [
"Input",
"::"
] | train | https://github.com/spreecode/python-sofort/blob/0d467e8fd56462b2d8a0ba65085ffd9a5a4d1add/sofort/xml.py#L92-L123 |
thejunglejane/datums | datums/migrations/env.py | run_migrations_offline | def run_migrations_offline():
"""Run migrations in 'offline' mode.
This configures the context with just a URL
and not an Engine, though an Engine is acceptable
here as well. By skipping the Engine creation
we don't even need a DBAPI to be available.
Calls to context.execute() here emit the given string to the
script output.
"""
url = os.environ['DATABASE_URI']
context.configure(
url=url, target_metadata=target_metadata, literal_binds=True)
with context.begin_transaction():
context.run_migrations() | python | def run_migrations_offline():
"""Run migrations in 'offline' mode.
This configures the context with just a URL
and not an Engine, though an Engine is acceptable
here as well. By skipping the Engine creation
we don't even need a DBAPI to be available.
Calls to context.execute() here emit the given string to the
script output.
"""
url = os.environ['DATABASE_URI']
context.configure(
url=url, target_metadata=target_metadata, literal_binds=True)
with context.begin_transaction():
context.run_migrations() | [
"def",
"run_migrations_offline",
"(",
")",
":",
"url",
"=",
"os",
".",
"environ",
"[",
"'DATABASE_URI'",
"]",
"context",
".",
"configure",
"(",
"url",
"=",
"url",
",",
"target_metadata",
"=",
"target_metadata",
",",
"literal_binds",
"=",
"True",
")",
"with",... | Run migrations in 'offline' mode.
This configures the context with just a URL
and not an Engine, though an Engine is acceptable
here as well. By skipping the Engine creation
we don't even need a DBAPI to be available.
Calls to context.execute() here emit the given string to the
script output. | [
"Run",
"migrations",
"in",
"offline",
"mode",
"."
] | train | https://github.com/thejunglejane/datums/blob/2250b365e37ba952c2426edc615c1487afabae6e/datums/migrations/env.py#L28-L45 |
thejunglejane/datums | datums/migrations/env.py | run_migrations_online | def run_migrations_online():
"""Run migrations in 'online' mode.
In this scenario we need to create an Engine
and associate a connection with the context.
"""
alembic_config = config.get_section(config.config_ini_section)
alembic_config['sqlalchemy.url'] = os.environ['DATABASE_URI']
connectable = engine_from_config(
alembic_config,
prefix='sqlalchemy.',
poolclass=pool.NullPool)
with connectable.connect() as connection:
context.configure(
connection=connection,
target_metadata=target_metadata
)
with context.begin_transaction():
context.run_migrations() | python | def run_migrations_online():
"""Run migrations in 'online' mode.
In this scenario we need to create an Engine
and associate a connection with the context.
"""
alembic_config = config.get_section(config.config_ini_section)
alembic_config['sqlalchemy.url'] = os.environ['DATABASE_URI']
connectable = engine_from_config(
alembic_config,
prefix='sqlalchemy.',
poolclass=pool.NullPool)
with connectable.connect() as connection:
context.configure(
connection=connection,
target_metadata=target_metadata
)
with context.begin_transaction():
context.run_migrations() | [
"def",
"run_migrations_online",
"(",
")",
":",
"alembic_config",
"=",
"config",
".",
"get_section",
"(",
"config",
".",
"config_ini_section",
")",
"alembic_config",
"[",
"'sqlalchemy.url'",
"]",
"=",
"os",
".",
"environ",
"[",
"'DATABASE_URI'",
"]",
"connectable",... | Run migrations in 'online' mode.
In this scenario we need to create an Engine
and associate a connection with the context. | [
"Run",
"migrations",
"in",
"online",
"mode",
"."
] | train | https://github.com/thejunglejane/datums/blob/2250b365e37ba952c2426edc615c1487afabae6e/datums/migrations/env.py#L48-L70 |
ttm/socialLegacy | social/utils.py | makeRetweetNetwork | def makeRetweetNetwork(tweets):
"""Receives tweets, returns directed retweet networks.
Without and with isolated nodes.
"""
G=x.DiGraph()
G_=x.DiGraph()
for tweet in tweets:
text=tweet["text"]
us=tweet["user"]["screen_name"]
if text.startswith("RT @"):
prev_us=text.split(":")[0].split("@")[1]
#print(us,prev_us,text)
if G.has_edge(prev_us,us):
G[prev_us][us]["weight"]+=1
G_[prev_us][us]["weight"]+=1
else:
G.add_edge(prev_us, us, weight=1.)
G_.add_edge(prev_us, us, weight=1.)
if us not in G_.nodes():
G_.add_node(us)
return G,G_ | python | def makeRetweetNetwork(tweets):
"""Receives tweets, returns directed retweet networks.
Without and with isolated nodes.
"""
G=x.DiGraph()
G_=x.DiGraph()
for tweet in tweets:
text=tweet["text"]
us=tweet["user"]["screen_name"]
if text.startswith("RT @"):
prev_us=text.split(":")[0].split("@")[1]
#print(us,prev_us,text)
if G.has_edge(prev_us,us):
G[prev_us][us]["weight"]+=1
G_[prev_us][us]["weight"]+=1
else:
G.add_edge(prev_us, us, weight=1.)
G_.add_edge(prev_us, us, weight=1.)
if us not in G_.nodes():
G_.add_node(us)
return G,G_ | [
"def",
"makeRetweetNetwork",
"(",
"tweets",
")",
":",
"G",
"=",
"x",
".",
"DiGraph",
"(",
")",
"G_",
"=",
"x",
".",
"DiGraph",
"(",
")",
"for",
"tweet",
"in",
"tweets",
":",
"text",
"=",
"tweet",
"[",
"\"text\"",
"]",
"us",
"=",
"tweet",
"[",
"\"... | Receives tweets, returns directed retweet networks.
Without and with isolated nodes. | [
"Receives",
"tweets",
"returns",
"directed",
"retweet",
"networks",
".",
"Without",
"and",
"with",
"isolated",
"nodes",
"."
] | train | https://github.com/ttm/socialLegacy/blob/c0930cfe6e84392729449bf7c92569e1556fd109/social/utils.py#L2-L23 |
ttm/socialLegacy | social/utils.py | GDFgraph.makeNetwork | def makeNetwork(self):
"""Makes graph object from .gdf loaded data"""
if "weight" in self.data_friendships.keys():
self.G=G=x.DiGraph()
else:
self.G=G=x.Graph()
F=self.data_friends
for friendn in range(self.n_friends):
if "posts" in F.keys():
G.add_node(F["name"][friendn],
label=F["label"][friendn],
posts=F["posts"][friendn])
elif "agerank" in F.keys():
G.add_node(F["name"][friendn],
label=F["label"][friendn],
gender=F["sex"][friendn],
locale=F["locale"][friendn],
agerank=F["agerank"][friendn])
else:
G.add_node(F["name"][friendn],
label=F["label"][friendn],
gender=F["sex"][friendn],
locale=F["locale"][friendn])
F=self.data_friendships
for friendshipn in range(self.n_friendships):
if "weight" in F.keys():
G.add_edge(F["node1"][friendshipn],F["node2"][friendshipn],weight=F["weight"][friendshipn])
else:
G.add_edge(F["node1"][friendshipn],F["node2"][friendshipn]) | python | def makeNetwork(self):
"""Makes graph object from .gdf loaded data"""
if "weight" in self.data_friendships.keys():
self.G=G=x.DiGraph()
else:
self.G=G=x.Graph()
F=self.data_friends
for friendn in range(self.n_friends):
if "posts" in F.keys():
G.add_node(F["name"][friendn],
label=F["label"][friendn],
posts=F["posts"][friendn])
elif "agerank" in F.keys():
G.add_node(F["name"][friendn],
label=F["label"][friendn],
gender=F["sex"][friendn],
locale=F["locale"][friendn],
agerank=F["agerank"][friendn])
else:
G.add_node(F["name"][friendn],
label=F["label"][friendn],
gender=F["sex"][friendn],
locale=F["locale"][friendn])
F=self.data_friendships
for friendshipn in range(self.n_friendships):
if "weight" in F.keys():
G.add_edge(F["node1"][friendshipn],F["node2"][friendshipn],weight=F["weight"][friendshipn])
else:
G.add_edge(F["node1"][friendshipn],F["node2"][friendshipn]) | [
"def",
"makeNetwork",
"(",
"self",
")",
":",
"if",
"\"weight\"",
"in",
"self",
".",
"data_friendships",
".",
"keys",
"(",
")",
":",
"self",
".",
"G",
"=",
"G",
"=",
"x",
".",
"DiGraph",
"(",
")",
"else",
":",
"self",
".",
"G",
"=",
"G",
"=",
"x... | Makes graph object from .gdf loaded data | [
"Makes",
"graph",
"object",
"from",
".",
"gdf",
"loaded",
"data"
] | train | https://github.com/ttm/socialLegacy/blob/c0930cfe6e84392729449bf7c92569e1556fd109/social/utils.py#L57-L85 |
JIC-CSB/jicbioimage.transform | appveyor/install.py | downlad_file | def downlad_file(url, fname):
"""Download file from url and save as fname."""
print("Downloading {} as {}".format(url, fname))
response = urlopen(url)
download = response.read()
with open(fname, 'wb') as fh:
fh.write(download) | python | def downlad_file(url, fname):
"""Download file from url and save as fname."""
print("Downloading {} as {}".format(url, fname))
response = urlopen(url)
download = response.read()
with open(fname, 'wb') as fh:
fh.write(download) | [
"def",
"downlad_file",
"(",
"url",
",",
"fname",
")",
":",
"print",
"(",
"\"Downloading {} as {}\"",
".",
"format",
"(",
"url",
",",
"fname",
")",
")",
"response",
"=",
"urlopen",
"(",
"url",
")",
"download",
"=",
"response",
".",
"read",
"(",
")",
"wi... | Download file from url and save as fname. | [
"Download",
"file",
"from",
"url",
"and",
"save",
"as",
"fname",
"."
] | train | https://github.com/JIC-CSB/jicbioimage.transform/blob/494c282d964c3a9b54c2a1b3730f5625ea2a494b/appveyor/install.py#L10-L16 |
JIC-CSB/jicbioimage.transform | appveyor/install.py | unzip_file | def unzip_file(zip_fname):
"""Unzip the zip_fname in the current directory."""
print("Unzipping {}".format(zip_fname))
with zipfile.ZipFile(zip_fname) as zf:
zf.extractall() | python | def unzip_file(zip_fname):
"""Unzip the zip_fname in the current directory."""
print("Unzipping {}".format(zip_fname))
with zipfile.ZipFile(zip_fname) as zf:
zf.extractall() | [
"def",
"unzip_file",
"(",
"zip_fname",
")",
":",
"print",
"(",
"\"Unzipping {}\"",
".",
"format",
"(",
"zip_fname",
")",
")",
"with",
"zipfile",
".",
"ZipFile",
"(",
"zip_fname",
")",
"as",
"zf",
":",
"zf",
".",
"extractall",
"(",
")"
] | Unzip the zip_fname in the current directory. | [
"Unzip",
"the",
"zip_fname",
"in",
"the",
"current",
"directory",
"."
] | train | https://github.com/JIC-CSB/jicbioimage.transform/blob/494c282d964c3a9b54c2a1b3730f5625ea2a494b/appveyor/install.py#L19-L23 |
JIC-CSB/jicbioimage.transform | appveyor/install.py | install_from_zip | def install_from_zip(url):
"""Download and unzip from url."""
fname = 'tmp.zip'
downlad_file(url, fname)
unzip_file(fname)
print("Removing {}".format(fname))
os.unlink(fname) | python | def install_from_zip(url):
"""Download and unzip from url."""
fname = 'tmp.zip'
downlad_file(url, fname)
unzip_file(fname)
print("Removing {}".format(fname))
os.unlink(fname) | [
"def",
"install_from_zip",
"(",
"url",
")",
":",
"fname",
"=",
"'tmp.zip'",
"downlad_file",
"(",
"url",
",",
"fname",
")",
"unzip_file",
"(",
"fname",
")",
"print",
"(",
"\"Removing {}\"",
".",
"format",
"(",
"fname",
")",
")",
"os",
".",
"unlink",
"(",
... | Download and unzip from url. | [
"Download",
"and",
"unzip",
"from",
"url",
"."
] | train | https://github.com/JIC-CSB/jicbioimage.transform/blob/494c282d964c3a9b54c2a1b3730f5625ea2a494b/appveyor/install.py#L25-L31 |
haykkh/resultr | resultr/__main__.py | main | def main(args=None):
"""The main routine."""
if args is None:
args = sys.argv[1:]
parser = argparse.ArgumentParser(
description='Makes UCL PHAS results better')
parser.add_argument('--input', '-i',
type=str, help="csv file to import")
parser.add_argument('--format', '-f', type=str,
help="reformats results by module and exports it to file specified")
parser.add_argument('--plot', '-p', action='store_true',
help="plot the module results")
parser.add_argument('--exportplots', '-ep', type=str,
help="export all plots to /path/you/want/")
parser.add_argument('--showplots', '-sp',
action='store_true', help="show all plots")
parser.add_argument(
'--my', '-m', action="store_true", help="returns your weighted average for the year")
parser.add_argument('--year', '-y', help="specify your year")
parser.add_argument('--rank', '-r', action='store_true',
help="returns your rank in the year")
parser.add_argument('--candidate', '-c',
help="specify your candidate number")
args = parser.parse_args()
#########################
# #
# end #
# argparse #
# #
# #
#########################
resultr.main(args) | python | def main(args=None):
"""The main routine."""
if args is None:
args = sys.argv[1:]
parser = argparse.ArgumentParser(
description='Makes UCL PHAS results better')
parser.add_argument('--input', '-i',
type=str, help="csv file to import")
parser.add_argument('--format', '-f', type=str,
help="reformats results by module and exports it to file specified")
parser.add_argument('--plot', '-p', action='store_true',
help="plot the module results")
parser.add_argument('--exportplots', '-ep', type=str,
help="export all plots to /path/you/want/")
parser.add_argument('--showplots', '-sp',
action='store_true', help="show all plots")
parser.add_argument(
'--my', '-m', action="store_true", help="returns your weighted average for the year")
parser.add_argument('--year', '-y', help="specify your year")
parser.add_argument('--rank', '-r', action='store_true',
help="returns your rank in the year")
parser.add_argument('--candidate', '-c',
help="specify your candidate number")
args = parser.parse_args()
#########################
# #
# end #
# argparse #
# #
# #
#########################
resultr.main(args) | [
"def",
"main",
"(",
"args",
"=",
"None",
")",
":",
"if",
"args",
"is",
"None",
":",
"args",
"=",
"sys",
".",
"argv",
"[",
"1",
":",
"]",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"'Makes UCL PHAS results better'",
")",
... | The main routine. | [
"The",
"main",
"routine",
"."
] | train | https://github.com/haykkh/resultr/blob/decd222a4c0d3ea75595fd546b797b60297623b6/resultr/__main__.py#L5-L38 |
BD2KOnFHIR/i2b2model | i2b2model/shared/tablenames.py | _I2B2Tables.phys_name | def phys_name(self, item: str) -> str:
"""Return the physical (mapped) name of item.
:param item: logical table name
:return: physical name of table
"""
v = self.__dict__[item]
return v if v is not None else item | python | def phys_name(self, item: str) -> str:
"""Return the physical (mapped) name of item.
:param item: logical table name
:return: physical name of table
"""
v = self.__dict__[item]
return v if v is not None else item | [
"def",
"phys_name",
"(",
"self",
",",
"item",
":",
"str",
")",
"->",
"str",
":",
"v",
"=",
"self",
".",
"__dict__",
"[",
"item",
"]",
"return",
"v",
"if",
"v",
"is",
"not",
"None",
"else",
"item"
] | Return the physical (mapped) name of item.
:param item: logical table name
:return: physical name of table | [
"Return",
"the",
"physical",
"(",
"mapped",
")",
"name",
"of",
"item",
"."
] | train | https://github.com/BD2KOnFHIR/i2b2model/blob/9d49bb53b0733dd83ab5b716014865e270a3c903/i2b2model/shared/tablenames.py#L37-L44 |
BD2KOnFHIR/i2b2model | i2b2model/shared/tablenames.py | _I2B2Tables.all_tables | def all_tables(self) -> List[str]:
"""
List of all known tables
:return:
"""
return sorted([k for k in self.__dict__.keys()
if k not in _I2B2Tables._funcs and not k.startswith("_")]) | python | def all_tables(self) -> List[str]:
"""
List of all known tables
:return:
"""
return sorted([k for k in self.__dict__.keys()
if k not in _I2B2Tables._funcs and not k.startswith("_")]) | [
"def",
"all_tables",
"(",
"self",
")",
"->",
"List",
"[",
"str",
"]",
":",
"return",
"sorted",
"(",
"[",
"k",
"for",
"k",
"in",
"self",
".",
"__dict__",
".",
"keys",
"(",
")",
"if",
"k",
"not",
"in",
"_I2B2Tables",
".",
"_funcs",
"and",
"not",
"k... | List of all known tables
:return: | [
"List",
"of",
"all",
"known",
"tables",
":",
"return",
":"
] | train | https://github.com/BD2KOnFHIR/i2b2model/blob/9d49bb53b0733dd83ab5b716014865e270a3c903/i2b2model/shared/tablenames.py#L46-L52 |
ShawnClake/Apitax | apitax/ah/api/controllers/admins_controller.py | system_status | def system_status(): # noqa: E501
"""Retrieve the system status
Retrieve the system status # noqa: E501
:rtype: Response
"""
if(not hasAccess()):
return redirectUnauthorized()
body = State.config.serialize(["driver", "log", "log-file", "log-colorize"])
body.update({'debug': State.options.debug, 'sensitive': State.options.sensitive})
return Response(status=200, body=body) | python | def system_status(): # noqa: E501
"""Retrieve the system status
Retrieve the system status # noqa: E501
:rtype: Response
"""
if(not hasAccess()):
return redirectUnauthorized()
body = State.config.serialize(["driver", "log", "log-file", "log-colorize"])
body.update({'debug': State.options.debug, 'sensitive': State.options.sensitive})
return Response(status=200, body=body) | [
"def",
"system_status",
"(",
")",
":",
"# noqa: E501",
"if",
"(",
"not",
"hasAccess",
"(",
")",
")",
":",
"return",
"redirectUnauthorized",
"(",
")",
"body",
"=",
"State",
".",
"config",
".",
"serialize",
"(",
"[",
"\"driver\"",
",",
"\"log\"",
",",
"\"l... | Retrieve the system status
Retrieve the system status # noqa: E501
:rtype: Response | [
"Retrieve",
"the",
"system",
"status"
] | train | https://github.com/ShawnClake/Apitax/blob/2eb9c6990d4088b2503c7f13c2a76f8e59606e6d/apitax/ah/api/controllers/admins_controller.py#L54-L67 |
zhexiao/ezhost | ezhost/ServerCommand.py | ServerCommand.login_server | def login_server(self):
"""
Login to server
"""
local('ssh -i {0} {1}@{2}'.format(
env.key_filename, env.user, env.host_string
)) | python | def login_server(self):
"""
Login to server
"""
local('ssh -i {0} {1}@{2}'.format(
env.key_filename, env.user, env.host_string
)) | [
"def",
"login_server",
"(",
"self",
")",
":",
"local",
"(",
"'ssh -i {0} {1}@{2}'",
".",
"format",
"(",
"env",
".",
"key_filename",
",",
"env",
".",
"user",
",",
"env",
".",
"host_string",
")",
")"
] | Login to server | [
"Login",
"to",
"server"
] | train | https://github.com/zhexiao/ezhost/blob/4146bc0be14bb1bfe98ec19283d19fab420871b3/ezhost/ServerCommand.py#L63-L69 |
sorrowless/battery_systray | batticon/batticon.py | Indicator.set_refresh | def set_refresh(self, timeout, callback, *callback_args):
"""
It is just stub for simplify setting timeout.
Args:
timeout (int): timeout in milliseconds, after which callback will be called
callback (callable): usually, just a function that will be called each time after timeout
*callback_args (any type): arguments that will be passed to callback function
"""
GObject.timeout_add(timeout, callback, *callback_args) | python | def set_refresh(self, timeout, callback, *callback_args):
"""
It is just stub for simplify setting timeout.
Args:
timeout (int): timeout in milliseconds, after which callback will be called
callback (callable): usually, just a function that will be called each time after timeout
*callback_args (any type): arguments that will be passed to callback function
"""
GObject.timeout_add(timeout, callback, *callback_args) | [
"def",
"set_refresh",
"(",
"self",
",",
"timeout",
",",
"callback",
",",
"*",
"callback_args",
")",
":",
"GObject",
".",
"timeout_add",
"(",
"timeout",
",",
"callback",
",",
"*",
"callback_args",
")"
] | It is just stub for simplify setting timeout.
Args:
timeout (int): timeout in milliseconds, after which callback will be called
callback (callable): usually, just a function that will be called each time after timeout
*callback_args (any type): arguments that will be passed to callback function | [
"It",
"is",
"just",
"stub",
"for",
"simplify",
"setting",
"timeout",
".",
"Args",
":",
"timeout",
"(",
"int",
")",
":",
"timeout",
"in",
"milliseconds",
"after",
"which",
"callback",
"will",
"be",
"called",
"callback",
"(",
"callable",
")",
":",
"usually",... | train | https://github.com/sorrowless/battery_systray/blob/4594fca6f357660e081c2800af4a8b21c607bef1/batticon/batticon.py#L31-L39 |
sorrowless/battery_systray | batticon/batticon.py | Indicator.add_menu_item | def add_menu_item(self, command, title):
"""
Add mouse right click menu item.
Args:
command (callable): function that will be called after left mouse click on title
title (str): label that will be shown in menu
"""
m_item = Gtk.MenuItem()
m_item.set_label(title)
m_item.connect('activate', command)
self.menu.append(m_item)
self.menu.show_all() | python | def add_menu_item(self, command, title):
"""
Add mouse right click menu item.
Args:
command (callable): function that will be called after left mouse click on title
title (str): label that will be shown in menu
"""
m_item = Gtk.MenuItem()
m_item.set_label(title)
m_item.connect('activate', command)
self.menu.append(m_item)
self.menu.show_all() | [
"def",
"add_menu_item",
"(",
"self",
",",
"command",
",",
"title",
")",
":",
"m_item",
"=",
"Gtk",
".",
"MenuItem",
"(",
")",
"m_item",
".",
"set_label",
"(",
"title",
")",
"m_item",
".",
"connect",
"(",
"'activate'",
",",
"command",
")",
"self",
".",
... | Add mouse right click menu item.
Args:
command (callable): function that will be called after left mouse click on title
title (str): label that will be shown in menu | [
"Add",
"mouse",
"right",
"click",
"menu",
"item",
".",
"Args",
":",
"command",
"(",
"callable",
")",
":",
"function",
"that",
"will",
"be",
"called",
"after",
"left",
"mouse",
"click",
"on",
"title",
"title",
"(",
"str",
")",
":",
"label",
"that",
"wil... | train | https://github.com/sorrowless/battery_systray/blob/4594fca6f357660e081c2800af4a8b21c607bef1/batticon/batticon.py#L49-L60 |
sorrowless/battery_systray | batticon/batticon.py | Indicator.add_seperator | def add_seperator(self):
"""
Add separator between labels in menu that called on right mouse click.
"""
m_item = Gtk.SeparatorMenuItem()
self.menu.append(m_item)
self.menu.show_all() | python | def add_seperator(self):
"""
Add separator between labels in menu that called on right mouse click.
"""
m_item = Gtk.SeparatorMenuItem()
self.menu.append(m_item)
self.menu.show_all() | [
"def",
"add_seperator",
"(",
"self",
")",
":",
"m_item",
"=",
"Gtk",
".",
"SeparatorMenuItem",
"(",
")",
"self",
".",
"menu",
".",
"append",
"(",
"m_item",
")",
"self",
".",
"menu",
".",
"show_all",
"(",
")"
] | Add separator between labels in menu that called on right mouse click. | [
"Add",
"separator",
"between",
"labels",
"in",
"menu",
"that",
"called",
"on",
"right",
"mouse",
"click",
"."
] | train | https://github.com/sorrowless/battery_systray/blob/4594fca6f357660e081c2800af4a8b21c607bef1/batticon/batticon.py#L62-L68 |
sorrowless/battery_systray | batticon/batticon.py | Indicator.right_click_event_statusicon | def right_click_event_statusicon(self, icon, button, time):
"""
It's just way how popup menu works in GTK. Don't ask me how it works.
"""
def pos(menu, aicon):
"""Just return menu"""
return Gtk.StatusIcon.position_menu(menu, aicon)
self.menu.popup(None, None, pos, icon, button, time) | python | def right_click_event_statusicon(self, icon, button, time):
"""
It's just way how popup menu works in GTK. Don't ask me how it works.
"""
def pos(menu, aicon):
"""Just return menu"""
return Gtk.StatusIcon.position_menu(menu, aicon)
self.menu.popup(None, None, pos, icon, button, time) | [
"def",
"right_click_event_statusicon",
"(",
"self",
",",
"icon",
",",
"button",
",",
"time",
")",
":",
"def",
"pos",
"(",
"menu",
",",
"aicon",
")",
":",
"\"\"\"Just return menu\"\"\"",
"return",
"Gtk",
".",
"StatusIcon",
".",
"position_menu",
"(",
"menu",
"... | It's just way how popup menu works in GTK. Don't ask me how it works. | [
"It",
"s",
"just",
"way",
"how",
"popup",
"menu",
"works",
"in",
"GTK",
".",
"Don",
"t",
"ask",
"me",
"how",
"it",
"works",
"."
] | train | https://github.com/sorrowless/battery_systray/blob/4594fca6f357660e081c2800af4a8b21c607bef1/batticon/batticon.py#L70-L79 |
sorrowless/battery_systray | batticon/batticon.py | Application.check_battery | def check_battery(self):
"""
Implement how we will check battery condition. Now it just trying to check standard battery
in /sys
"""
self.charging = False if \
subprocess.getoutput("cat /sys/class/power_supply/BAT0/status") == 'Discharging' \
else True
percent = subprocess.getoutput("cat /sys/class/power_supply/BAT0/capacity")
if not self.charging:
for val in self.dischlist:
if int(percent) <= int(val):
self.indicator.set_icon(self.dischformat.format(value=val))
break
else:
for val in self.chlist:
if int(percent) <= int(val):
self.indicator.set_icon(self.chformat.format(value=val))
break
return True | python | def check_battery(self):
"""
Implement how we will check battery condition. Now it just trying to check standard battery
in /sys
"""
self.charging = False if \
subprocess.getoutput("cat /sys/class/power_supply/BAT0/status") == 'Discharging' \
else True
percent = subprocess.getoutput("cat /sys/class/power_supply/BAT0/capacity")
if not self.charging:
for val in self.dischlist:
if int(percent) <= int(val):
self.indicator.set_icon(self.dischformat.format(value=val))
break
else:
for val in self.chlist:
if int(percent) <= int(val):
self.indicator.set_icon(self.chformat.format(value=val))
break
return True | [
"def",
"check_battery",
"(",
"self",
")",
":",
"self",
".",
"charging",
"=",
"False",
"if",
"subprocess",
".",
"getoutput",
"(",
"\"cat /sys/class/power_supply/BAT0/status\"",
")",
"==",
"'Discharging'",
"else",
"True",
"percent",
"=",
"subprocess",
".",
"getoutpu... | Implement how we will check battery condition. Now it just trying to check standard battery
in /sys | [
"Implement",
"how",
"we",
"will",
"check",
"battery",
"condition",
".",
"Now",
"it",
"just",
"trying",
"to",
"check",
"standard",
"battery",
"in",
"/",
"sys"
] | train | https://github.com/sorrowless/battery_systray/blob/4594fca6f357660e081c2800af4a8b21c607bef1/batticon/batticon.py#L140-L159 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.