repo
stringlengths 7
55
| path
stringlengths 4
127
| func_name
stringlengths 1
88
| original_string
stringlengths 75
19.8k
| language
stringclasses 1
value | code
stringlengths 75
19.8k
| code_tokens
list | docstring
stringlengths 3
17.3k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 87
242
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
ShadowBlip/Neteria | neteria/core.py | ListenerUDP.scheduler | def scheduler(self, sleep_time=0.2):
"""Starts the scheduler to check for scheduled calls and execute them
at the correct time.
Args:
sleep_time (float): The amount of time to wait in seconds between
each loop iteration. This prevents the scheduler from consuming
100% of the host's CPU. Defaults to 0.2 seconds.
Returns:
None
"""
while self.listening:
# If we have any scheduled calls, execute them and remove them from
# our list of scheduled calls.
if self.scheduled_calls:
timestamp = time.time()
self.scheduled_calls[:] = [item for item in self.scheduled_calls
if not self.time_reached(timestamp, item)]
time.sleep(sleep_time)
logger.info("Shutting down the call scheduler...") | python | def scheduler(self, sleep_time=0.2):
"""Starts the scheduler to check for scheduled calls and execute them
at the correct time.
Args:
sleep_time (float): The amount of time to wait in seconds between
each loop iteration. This prevents the scheduler from consuming
100% of the host's CPU. Defaults to 0.2 seconds.
Returns:
None
"""
while self.listening:
# If we have any scheduled calls, execute them and remove them from
# our list of scheduled calls.
if self.scheduled_calls:
timestamp = time.time()
self.scheduled_calls[:] = [item for item in self.scheduled_calls
if not self.time_reached(timestamp, item)]
time.sleep(sleep_time)
logger.info("Shutting down the call scheduler...") | [
"def",
"scheduler",
"(",
"self",
",",
"sleep_time",
"=",
"0.2",
")",
":",
"while",
"self",
".",
"listening",
":",
"# If we have any scheduled calls, execute them and remove them from",
"# our list of scheduled calls.",
"if",
"self",
".",
"scheduled_calls",
":",
"timestamp",
"=",
"time",
".",
"time",
"(",
")",
"self",
".",
"scheduled_calls",
"[",
":",
"]",
"=",
"[",
"item",
"for",
"item",
"in",
"self",
".",
"scheduled_calls",
"if",
"not",
"self",
".",
"time_reached",
"(",
"timestamp",
",",
"item",
")",
"]",
"time",
".",
"sleep",
"(",
"sleep_time",
")",
"logger",
".",
"info",
"(",
"\"Shutting down the call scheduler...\"",
")"
]
| Starts the scheduler to check for scheduled calls and execute them
at the correct time.
Args:
sleep_time (float): The amount of time to wait in seconds between
each loop iteration. This prevents the scheduler from consuming
100% of the host's CPU. Defaults to 0.2 seconds.
Returns:
None | [
"Starts",
"the",
"scheduler",
"to",
"check",
"for",
"scheduled",
"calls",
"and",
"execute",
"them",
"at",
"the",
"correct",
"time",
"."
]
| 1a8c976eb2beeca0a5a272a34ac58b2c114495a4 | https://github.com/ShadowBlip/Neteria/blob/1a8c976eb2beeca0a5a272a34ac58b2c114495a4/neteria/core.py#L244-L267 | train |
ShadowBlip/Neteria | neteria/core.py | ListenerUDP.call_later | def call_later(self, time_seconds, callback, arguments):
"""Schedules a function to be run x number of seconds from now.
The call_later method is primarily used to resend messages if we
haven't received a confirmation message from the receiving host.
We can wait x number of seconds for a response and then try
sending the message again.
Args:
time_seconds (float): The number of seconds from now we should call
the provided function.
callback (function): The method to execute when our time has been
reached. E.g. self.retransmit
arguments (dict): A dictionary of arguments to send to the callback.
Returns:
None
"""
scheduled_call = {'ts': time.time() + time_seconds,
'callback': callback,
'args': arguments}
self.scheduled_calls.append(scheduled_call) | python | def call_later(self, time_seconds, callback, arguments):
"""Schedules a function to be run x number of seconds from now.
The call_later method is primarily used to resend messages if we
haven't received a confirmation message from the receiving host.
We can wait x number of seconds for a response and then try
sending the message again.
Args:
time_seconds (float): The number of seconds from now we should call
the provided function.
callback (function): The method to execute when our time has been
reached. E.g. self.retransmit
arguments (dict): A dictionary of arguments to send to the callback.
Returns:
None
"""
scheduled_call = {'ts': time.time() + time_seconds,
'callback': callback,
'args': arguments}
self.scheduled_calls.append(scheduled_call) | [
"def",
"call_later",
"(",
"self",
",",
"time_seconds",
",",
"callback",
",",
"arguments",
")",
":",
"scheduled_call",
"=",
"{",
"'ts'",
":",
"time",
".",
"time",
"(",
")",
"+",
"time_seconds",
",",
"'callback'",
":",
"callback",
",",
"'args'",
":",
"arguments",
"}",
"self",
".",
"scheduled_calls",
".",
"append",
"(",
"scheduled_call",
")"
]
| Schedules a function to be run x number of seconds from now.
The call_later method is primarily used to resend messages if we
haven't received a confirmation message from the receiving host.
We can wait x number of seconds for a response and then try
sending the message again.
Args:
time_seconds (float): The number of seconds from now we should call
the provided function.
callback (function): The method to execute when our time has been
reached. E.g. self.retransmit
arguments (dict): A dictionary of arguments to send to the callback.
Returns:
None | [
"Schedules",
"a",
"function",
"to",
"be",
"run",
"x",
"number",
"of",
"seconds",
"from",
"now",
"."
]
| 1a8c976eb2beeca0a5a272a34ac58b2c114495a4 | https://github.com/ShadowBlip/Neteria/blob/1a8c976eb2beeca0a5a272a34ac58b2c114495a4/neteria/core.py#L269-L292 | train |
ShadowBlip/Neteria | neteria/core.py | ListenerUDP.time_reached | def time_reached(self, current_time, scheduled_call):
"""Checks to see if it's time to run a scheduled call or not.
If it IS time to run a scheduled call, this function will execute the
method associated with that call.
Args:
current_time (float): Current timestamp from time.time().
scheduled_call (dict): A scheduled call dictionary that contains the
timestamp to execute the call, the method to execute, and the
arguments used to call the method.
Returns:
None
Examples:
>>> scheduled_call
{'callback': <function foo at 0x7f022c42cf50>,
'args': {'k': 'v'},
'ts': 1415066599.769509}
"""
if current_time >= scheduled_call['ts']:
scheduled_call['callback'](scheduled_call['args'])
return True
else:
return False | python | def time_reached(self, current_time, scheduled_call):
"""Checks to see if it's time to run a scheduled call or not.
If it IS time to run a scheduled call, this function will execute the
method associated with that call.
Args:
current_time (float): Current timestamp from time.time().
scheduled_call (dict): A scheduled call dictionary that contains the
timestamp to execute the call, the method to execute, and the
arguments used to call the method.
Returns:
None
Examples:
>>> scheduled_call
{'callback': <function foo at 0x7f022c42cf50>,
'args': {'k': 'v'},
'ts': 1415066599.769509}
"""
if current_time >= scheduled_call['ts']:
scheduled_call['callback'](scheduled_call['args'])
return True
else:
return False | [
"def",
"time_reached",
"(",
"self",
",",
"current_time",
",",
"scheduled_call",
")",
":",
"if",
"current_time",
">=",
"scheduled_call",
"[",
"'ts'",
"]",
":",
"scheduled_call",
"[",
"'callback'",
"]",
"(",
"scheduled_call",
"[",
"'args'",
"]",
")",
"return",
"True",
"else",
":",
"return",
"False"
]
| Checks to see if it's time to run a scheduled call or not.
If it IS time to run a scheduled call, this function will execute the
method associated with that call.
Args:
current_time (float): Current timestamp from time.time().
scheduled_call (dict): A scheduled call dictionary that contains the
timestamp to execute the call, the method to execute, and the
arguments used to call the method.
Returns:
None
Examples:
>>> scheduled_call
{'callback': <function foo at 0x7f022c42cf50>,
'args': {'k': 'v'},
'ts': 1415066599.769509} | [
"Checks",
"to",
"see",
"if",
"it",
"s",
"time",
"to",
"run",
"a",
"scheduled",
"call",
"or",
"not",
"."
]
| 1a8c976eb2beeca0a5a272a34ac58b2c114495a4 | https://github.com/ShadowBlip/Neteria/blob/1a8c976eb2beeca0a5a272a34ac58b2c114495a4/neteria/core.py#L294-L322 | train |
ShadowBlip/Neteria | neteria/core.py | ListenerUDP.send_datagram | def send_datagram(self, message, address, message_type="unicast"):
"""Sends a UDP datagram packet to the requested address.
Datagrams can be sent as a "unicast", "multicast", or "broadcast"
message. Unicast messages are messages that will be sent to a single
host, multicast messages will be delivered to all hosts listening for
multicast messages, and broadcast messages will be delivered to ALL
hosts on the network.
Args:
message (str): The raw serialized packet data to send.
address (tuple): The address and port of the destination to send the
packet. E.g. (address, port)
message_type -- The type of packet to send. Can be "unicast",
"multicast", or "broadcast". Defaults to "unicast".
Returns:
None
"""
if self.bufsize is not 0 and len(message) > self.bufsize:
raise Exception("Datagram is too large. Messages should be " +
"under " + str(self.bufsize) + " bytes in size.")
if message_type == "broadcast":
self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
elif message_type == "multicast":
self.sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)
try:
logger.debug("Sending packet")
self.sock.sendto(message, address)
if self.stats_enabled:
self.stats['bytes_sent'] += len(message)
except socket.error:
logger.error("Failed to send, [Errno 101]: Network is unreachable.") | python | def send_datagram(self, message, address, message_type="unicast"):
"""Sends a UDP datagram packet to the requested address.
Datagrams can be sent as a "unicast", "multicast", or "broadcast"
message. Unicast messages are messages that will be sent to a single
host, multicast messages will be delivered to all hosts listening for
multicast messages, and broadcast messages will be delivered to ALL
hosts on the network.
Args:
message (str): The raw serialized packet data to send.
address (tuple): The address and port of the destination to send the
packet. E.g. (address, port)
message_type -- The type of packet to send. Can be "unicast",
"multicast", or "broadcast". Defaults to "unicast".
Returns:
None
"""
if self.bufsize is not 0 and len(message) > self.bufsize:
raise Exception("Datagram is too large. Messages should be " +
"under " + str(self.bufsize) + " bytes in size.")
if message_type == "broadcast":
self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
elif message_type == "multicast":
self.sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)
try:
logger.debug("Sending packet")
self.sock.sendto(message, address)
if self.stats_enabled:
self.stats['bytes_sent'] += len(message)
except socket.error:
logger.error("Failed to send, [Errno 101]: Network is unreachable.") | [
"def",
"send_datagram",
"(",
"self",
",",
"message",
",",
"address",
",",
"message_type",
"=",
"\"unicast\"",
")",
":",
"if",
"self",
".",
"bufsize",
"is",
"not",
"0",
"and",
"len",
"(",
"message",
")",
">",
"self",
".",
"bufsize",
":",
"raise",
"Exception",
"(",
"\"Datagram is too large. Messages should be \"",
"+",
"\"under \"",
"+",
"str",
"(",
"self",
".",
"bufsize",
")",
"+",
"\" bytes in size.\"",
")",
"if",
"message_type",
"==",
"\"broadcast\"",
":",
"self",
".",
"sock",
".",
"setsockopt",
"(",
"socket",
".",
"SOL_SOCKET",
",",
"socket",
".",
"SO_BROADCAST",
",",
"1",
")",
"elif",
"message_type",
"==",
"\"multicast\"",
":",
"self",
".",
"sock",
".",
"setsockopt",
"(",
"socket",
".",
"IPPROTO_IP",
",",
"socket",
".",
"IP_MULTICAST_TTL",
",",
"2",
")",
"try",
":",
"logger",
".",
"debug",
"(",
"\"Sending packet\"",
")",
"self",
".",
"sock",
".",
"sendto",
"(",
"message",
",",
"address",
")",
"if",
"self",
".",
"stats_enabled",
":",
"self",
".",
"stats",
"[",
"'bytes_sent'",
"]",
"+=",
"len",
"(",
"message",
")",
"except",
"socket",
".",
"error",
":",
"logger",
".",
"error",
"(",
"\"Failed to send, [Errno 101]: Network is unreachable.\"",
")"
]
| Sends a UDP datagram packet to the requested address.
Datagrams can be sent as a "unicast", "multicast", or "broadcast"
message. Unicast messages are messages that will be sent to a single
host, multicast messages will be delivered to all hosts listening for
multicast messages, and broadcast messages will be delivered to ALL
hosts on the network.
Args:
message (str): The raw serialized packet data to send.
address (tuple): The address and port of the destination to send the
packet. E.g. (address, port)
message_type -- The type of packet to send. Can be "unicast",
"multicast", or "broadcast". Defaults to "unicast".
Returns:
None | [
"Sends",
"a",
"UDP",
"datagram",
"packet",
"to",
"the",
"requested",
"address",
"."
]
| 1a8c976eb2beeca0a5a272a34ac58b2c114495a4 | https://github.com/ShadowBlip/Neteria/blob/1a8c976eb2beeca0a5a272a34ac58b2c114495a4/neteria/core.py#L324-L360 | train |
ShadowBlip/Neteria | neteria/core.py | ListenerUDP.receive_datagram | def receive_datagram(self, data, address):
"""Executes when UDP data has been received and sends the packet data
to our app to process the request.
Args:
data (str): The raw serialized packet data received.
address (tuple): The address and port of the origin of the received
packet. E.g. (address, port).
Returns:
None
"""
# If we do not specify an application, just print the data.
if not self.app:
logger.debug("Packet received", address, data)
return False
# Send the data we've recieved from the network and send it
# to our application for processing.
try:
response = self.app.handle_message(data, address)
except Exception as err:
logger.error("Error processing message from " + str(address) +
":" + str(data))
logger.error(traceback.format_exc())
return False
# If our application generated a response to this message,
# send it to the original sender.
if response:
self.send_datagram(response, address) | python | def receive_datagram(self, data, address):
"""Executes when UDP data has been received and sends the packet data
to our app to process the request.
Args:
data (str): The raw serialized packet data received.
address (tuple): The address and port of the origin of the received
packet. E.g. (address, port).
Returns:
None
"""
# If we do not specify an application, just print the data.
if not self.app:
logger.debug("Packet received", address, data)
return False
# Send the data we've recieved from the network and send it
# to our application for processing.
try:
response = self.app.handle_message(data, address)
except Exception as err:
logger.error("Error processing message from " + str(address) +
":" + str(data))
logger.error(traceback.format_exc())
return False
# If our application generated a response to this message,
# send it to the original sender.
if response:
self.send_datagram(response, address) | [
"def",
"receive_datagram",
"(",
"self",
",",
"data",
",",
"address",
")",
":",
"# If we do not specify an application, just print the data.",
"if",
"not",
"self",
".",
"app",
":",
"logger",
".",
"debug",
"(",
"\"Packet received\"",
",",
"address",
",",
"data",
")",
"return",
"False",
"# Send the data we've recieved from the network and send it",
"# to our application for processing.",
"try",
":",
"response",
"=",
"self",
".",
"app",
".",
"handle_message",
"(",
"data",
",",
"address",
")",
"except",
"Exception",
"as",
"err",
":",
"logger",
".",
"error",
"(",
"\"Error processing message from \"",
"+",
"str",
"(",
"address",
")",
"+",
"\":\"",
"+",
"str",
"(",
"data",
")",
")",
"logger",
".",
"error",
"(",
"traceback",
".",
"format_exc",
"(",
")",
")",
"return",
"False",
"# If our application generated a response to this message,",
"# send it to the original sender.",
"if",
"response",
":",
"self",
".",
"send_datagram",
"(",
"response",
",",
"address",
")"
]
| Executes when UDP data has been received and sends the packet data
to our app to process the request.
Args:
data (str): The raw serialized packet data received.
address (tuple): The address and port of the origin of the received
packet. E.g. (address, port).
Returns:
None | [
"Executes",
"when",
"UDP",
"data",
"has",
"been",
"received",
"and",
"sends",
"the",
"packet",
"data",
"to",
"our",
"app",
"to",
"process",
"the",
"request",
"."
]
| 1a8c976eb2beeca0a5a272a34ac58b2c114495a4 | https://github.com/ShadowBlip/Neteria/blob/1a8c976eb2beeca0a5a272a34ac58b2c114495a4/neteria/core.py#L362-L394 | train |
sprockets/sprockets.mixins.metrics | examples/statsd.py | make_application | def make_application():
"""
Create a application configured to send metrics.
Metrics will be sent to localhost:8125 namespaced with
``webapps``. Run netcat or a similar listener then run this
example. HTTP GETs will result in a metric like::
webapps.SimpleHandler.GET.204:255.24497032165527|ms
"""
settings = {}
application = web.Application([web.url('/', SimpleHandler)], **settings)
statsd.install(application, **{'namespace': 'testing'})
return application | python | def make_application():
"""
Create a application configured to send metrics.
Metrics will be sent to localhost:8125 namespaced with
``webapps``. Run netcat or a similar listener then run this
example. HTTP GETs will result in a metric like::
webapps.SimpleHandler.GET.204:255.24497032165527|ms
"""
settings = {}
application = web.Application([web.url('/', SimpleHandler)], **settings)
statsd.install(application, **{'namespace': 'testing'})
return application | [
"def",
"make_application",
"(",
")",
":",
"settings",
"=",
"{",
"}",
"application",
"=",
"web",
".",
"Application",
"(",
"[",
"web",
".",
"url",
"(",
"'/'",
",",
"SimpleHandler",
")",
"]",
",",
"*",
"*",
"settings",
")",
"statsd",
".",
"install",
"(",
"application",
",",
"*",
"*",
"{",
"'namespace'",
":",
"'testing'",
"}",
")",
"return",
"application"
]
| Create a application configured to send metrics.
Metrics will be sent to localhost:8125 namespaced with
``webapps``. Run netcat or a similar listener then run this
example. HTTP GETs will result in a metric like::
webapps.SimpleHandler.GET.204:255.24497032165527|ms | [
"Create",
"a",
"application",
"configured",
"to",
"send",
"metrics",
"."
]
| 0b17d5f0c09a2be9db779e17e6789d3d5ff9a0d0 | https://github.com/sprockets/sprockets.mixins.metrics/blob/0b17d5f0c09a2be9db779e17e6789d3d5ff9a0d0/examples/statsd.py#L34-L48 | train |
ehansis/ozelot | examples/leonardo/leonardo/common/analysis.py | plots_html_page | def plots_html_page(query_module):
"""Generate analysis output as html page
Args:
query_module (module): module to use for querying data for the
desired model/pipeline variant, e.g. leonardo.standard.queries
"""
# page template
template = jenv.get_template("analysis.html")
# container for template context
context = dict(extended=config.EXTENDED)
# a database client/session to run queries in
cl = client.get_client()
session = cl.create_session()
# general styling
seaborn.set_style('whitegrid')
#
# plot: painting area by decade, with linear regression
#
decade_df = query_module.decade_query()
pix_size = pixels_to_inches((600, 400))
ax = seaborn.lmplot(x='decade', y='area', data=decade_df,
size=pix_size[1], aspect=pix_size[0] / pix_size[1],
scatter_kws={"s": 30, "alpha": 0.3})
ax.set(xlabel='Decade', ylabel='Area, m^2')
context['area_by_decade_svg'] = fig_to_svg(plt.gcf())
plt.close('all')
#
# plot: painting area by gender, with logistic regression
#
if config.EXTENDED:
gender_df = query_module.gender_query()
pix_size = pixels_to_inches((600, 400))
g = seaborn.FacetGrid(gender_df, hue="gender", margin_titles=True,
size=pix_size[1], aspect=pix_size[0] / pix_size[1])
bins = np.linspace(0, 5, 30)
g.map(plt.hist, "area", bins=bins, lw=0, alpha=0.5, normed=True)
g.axes[0, 0].set_xlabel('Area, m^2')
g.axes[0, 0].set_ylabel('Percentage of paintings')
context['area_by_gender_svg'] = fig_to_svg(plt.gcf())
plt.close('all')
#
# render template
#
out_file = path.join(out_dir, "analysis.html")
html_content = template.render(**context)
with open(out_file, 'w') as f:
f.write(html_content)
# done, clean up
plt.close('all')
session.close() | python | def plots_html_page(query_module):
"""Generate analysis output as html page
Args:
query_module (module): module to use for querying data for the
desired model/pipeline variant, e.g. leonardo.standard.queries
"""
# page template
template = jenv.get_template("analysis.html")
# container for template context
context = dict(extended=config.EXTENDED)
# a database client/session to run queries in
cl = client.get_client()
session = cl.create_session()
# general styling
seaborn.set_style('whitegrid')
#
# plot: painting area by decade, with linear regression
#
decade_df = query_module.decade_query()
pix_size = pixels_to_inches((600, 400))
ax = seaborn.lmplot(x='decade', y='area', data=decade_df,
size=pix_size[1], aspect=pix_size[0] / pix_size[1],
scatter_kws={"s": 30, "alpha": 0.3})
ax.set(xlabel='Decade', ylabel='Area, m^2')
context['area_by_decade_svg'] = fig_to_svg(plt.gcf())
plt.close('all')
#
# plot: painting area by gender, with logistic regression
#
if config.EXTENDED:
gender_df = query_module.gender_query()
pix_size = pixels_to_inches((600, 400))
g = seaborn.FacetGrid(gender_df, hue="gender", margin_titles=True,
size=pix_size[1], aspect=pix_size[0] / pix_size[1])
bins = np.linspace(0, 5, 30)
g.map(plt.hist, "area", bins=bins, lw=0, alpha=0.5, normed=True)
g.axes[0, 0].set_xlabel('Area, m^2')
g.axes[0, 0].set_ylabel('Percentage of paintings')
context['area_by_gender_svg'] = fig_to_svg(plt.gcf())
plt.close('all')
#
# render template
#
out_file = path.join(out_dir, "analysis.html")
html_content = template.render(**context)
with open(out_file, 'w') as f:
f.write(html_content)
# done, clean up
plt.close('all')
session.close() | [
"def",
"plots_html_page",
"(",
"query_module",
")",
":",
"# page template",
"template",
"=",
"jenv",
".",
"get_template",
"(",
"\"analysis.html\"",
")",
"# container for template context",
"context",
"=",
"dict",
"(",
"extended",
"=",
"config",
".",
"EXTENDED",
")",
"# a database client/session to run queries in",
"cl",
"=",
"client",
".",
"get_client",
"(",
")",
"session",
"=",
"cl",
".",
"create_session",
"(",
")",
"# general styling",
"seaborn",
".",
"set_style",
"(",
"'whitegrid'",
")",
"#",
"# plot: painting area by decade, with linear regression",
"#",
"decade_df",
"=",
"query_module",
".",
"decade_query",
"(",
")",
"pix_size",
"=",
"pixels_to_inches",
"(",
"(",
"600",
",",
"400",
")",
")",
"ax",
"=",
"seaborn",
".",
"lmplot",
"(",
"x",
"=",
"'decade'",
",",
"y",
"=",
"'area'",
",",
"data",
"=",
"decade_df",
",",
"size",
"=",
"pix_size",
"[",
"1",
"]",
",",
"aspect",
"=",
"pix_size",
"[",
"0",
"]",
"/",
"pix_size",
"[",
"1",
"]",
",",
"scatter_kws",
"=",
"{",
"\"s\"",
":",
"30",
",",
"\"alpha\"",
":",
"0.3",
"}",
")",
"ax",
".",
"set",
"(",
"xlabel",
"=",
"'Decade'",
",",
"ylabel",
"=",
"'Area, m^2'",
")",
"context",
"[",
"'area_by_decade_svg'",
"]",
"=",
"fig_to_svg",
"(",
"plt",
".",
"gcf",
"(",
")",
")",
"plt",
".",
"close",
"(",
"'all'",
")",
"#",
"# plot: painting area by gender, with logistic regression",
"#",
"if",
"config",
".",
"EXTENDED",
":",
"gender_df",
"=",
"query_module",
".",
"gender_query",
"(",
")",
"pix_size",
"=",
"pixels_to_inches",
"(",
"(",
"600",
",",
"400",
")",
")",
"g",
"=",
"seaborn",
".",
"FacetGrid",
"(",
"gender_df",
",",
"hue",
"=",
"\"gender\"",
",",
"margin_titles",
"=",
"True",
",",
"size",
"=",
"pix_size",
"[",
"1",
"]",
",",
"aspect",
"=",
"pix_size",
"[",
"0",
"]",
"/",
"pix_size",
"[",
"1",
"]",
")",
"bins",
"=",
"np",
".",
"linspace",
"(",
"0",
",",
"5",
",",
"30",
")",
"g",
".",
"map",
"(",
"plt",
".",
"hist",
",",
"\"area\"",
",",
"bins",
"=",
"bins",
",",
"lw",
"=",
"0",
",",
"alpha",
"=",
"0.5",
",",
"normed",
"=",
"True",
")",
"g",
".",
"axes",
"[",
"0",
",",
"0",
"]",
".",
"set_xlabel",
"(",
"'Area, m^2'",
")",
"g",
".",
"axes",
"[",
"0",
",",
"0",
"]",
".",
"set_ylabel",
"(",
"'Percentage of paintings'",
")",
"context",
"[",
"'area_by_gender_svg'",
"]",
"=",
"fig_to_svg",
"(",
"plt",
".",
"gcf",
"(",
")",
")",
"plt",
".",
"close",
"(",
"'all'",
")",
"#",
"# render template",
"#",
"out_file",
"=",
"path",
".",
"join",
"(",
"out_dir",
",",
"\"analysis.html\"",
")",
"html_content",
"=",
"template",
".",
"render",
"(",
"*",
"*",
"context",
")",
"with",
"open",
"(",
"out_file",
",",
"'w'",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"html_content",
")",
"# done, clean up",
"plt",
".",
"close",
"(",
"'all'",
")",
"session",
".",
"close",
"(",
")"
]
| Generate analysis output as html page
Args:
query_module (module): module to use for querying data for the
desired model/pipeline variant, e.g. leonardo.standard.queries | [
"Generate",
"analysis",
"output",
"as",
"html",
"page"
]
| 948675e02eb6fca940450f5cb814f53e97159e5b | https://github.com/ehansis/ozelot/blob/948675e02eb6fca940450f5cb814f53e97159e5b/examples/leonardo/leonardo/common/analysis.py#L50-L113 | train |
fkarb/xltable | xltable/worksheet.py | _to_pywintypes | def _to_pywintypes(row):
"""convert values in a row to types accepted by excel"""
def _pywintype(x):
if isinstance(x, dt.date):
return dt.datetime(x.year, x.month, x.day, tzinfo=dt.timezone.utc)
elif isinstance(x, (dt.datetime, pa.Timestamp)):
if x.tzinfo is None:
return x.replace(tzinfo=dt.timezone.utc)
elif isinstance(x, str):
if re.match("^\d{4}-\d{2}-\d{2}$", x):
return "'" + x
return x
elif isinstance(x, np.integer):
return int(x)
elif isinstance(x, np.floating):
return float(x)
elif x is not None and not isinstance(x, (str, int, float, bool)):
return str(x)
return x
return [_pywintype(x) for x in row] | python | def _to_pywintypes(row):
"""convert values in a row to types accepted by excel"""
def _pywintype(x):
if isinstance(x, dt.date):
return dt.datetime(x.year, x.month, x.day, tzinfo=dt.timezone.utc)
elif isinstance(x, (dt.datetime, pa.Timestamp)):
if x.tzinfo is None:
return x.replace(tzinfo=dt.timezone.utc)
elif isinstance(x, str):
if re.match("^\d{4}-\d{2}-\d{2}$", x):
return "'" + x
return x
elif isinstance(x, np.integer):
return int(x)
elif isinstance(x, np.floating):
return float(x)
elif x is not None and not isinstance(x, (str, int, float, bool)):
return str(x)
return x
return [_pywintype(x) for x in row] | [
"def",
"_to_pywintypes",
"(",
"row",
")",
":",
"def",
"_pywintype",
"(",
"x",
")",
":",
"if",
"isinstance",
"(",
"x",
",",
"dt",
".",
"date",
")",
":",
"return",
"dt",
".",
"datetime",
"(",
"x",
".",
"year",
",",
"x",
".",
"month",
",",
"x",
".",
"day",
",",
"tzinfo",
"=",
"dt",
".",
"timezone",
".",
"utc",
")",
"elif",
"isinstance",
"(",
"x",
",",
"(",
"dt",
".",
"datetime",
",",
"pa",
".",
"Timestamp",
")",
")",
":",
"if",
"x",
".",
"tzinfo",
"is",
"None",
":",
"return",
"x",
".",
"replace",
"(",
"tzinfo",
"=",
"dt",
".",
"timezone",
".",
"utc",
")",
"elif",
"isinstance",
"(",
"x",
",",
"str",
")",
":",
"if",
"re",
".",
"match",
"(",
"\"^\\d{4}-\\d{2}-\\d{2}$\"",
",",
"x",
")",
":",
"return",
"\"'\"",
"+",
"x",
"return",
"x",
"elif",
"isinstance",
"(",
"x",
",",
"np",
".",
"integer",
")",
":",
"return",
"int",
"(",
"x",
")",
"elif",
"isinstance",
"(",
"x",
",",
"np",
".",
"floating",
")",
":",
"return",
"float",
"(",
"x",
")",
"elif",
"x",
"is",
"not",
"None",
"and",
"not",
"isinstance",
"(",
"x",
",",
"(",
"str",
",",
"int",
",",
"float",
",",
"bool",
")",
")",
":",
"return",
"str",
"(",
"x",
")",
"return",
"x",
"return",
"[",
"_pywintype",
"(",
"x",
")",
"for",
"x",
"in",
"row",
"]"
]
| convert values in a row to types accepted by excel | [
"convert",
"values",
"in",
"a",
"row",
"to",
"types",
"accepted",
"by",
"excel"
]
| 7a592642d27ad5ee90d2aa8c26338abaa9d84bea | https://github.com/fkarb/xltable/blob/7a592642d27ad5ee90d2aa8c26338abaa9d84bea/xltable/worksheet.py#L640-L666 | train |
fkarb/xltable | xltable/worksheet.py | Worksheet.iterrows | def iterrows(self, workbook=None):
"""
Yield rows as lists of data.
The data is exactly as it is in the source pandas DataFrames and
any formulas are not resolved.
"""
resolved_tables = []
max_height = 0
max_width = 0
# while yielding rows __formula_values is updated with any formula values set on Expressions
self.__formula_values = {}
for name, (table, (row, col)) in list(self.__tables.items()):
# get the resolved 2d data array from the table
#
# expressions with no explicit table will use None when calling
# get_table/get_table_pos, which should return the current table.
#
self.__tables[None] = (table, (row, col))
data = table.get_data(workbook, row, col, self.__formula_values)
del self.__tables[None]
height, width = data.shape
upper_left = (row, col)
lower_right = (row + height - 1, col + width - 1)
max_height = max(max_height, lower_right[0] + 1)
max_width = max(max_width, lower_right[1] + 1)
resolved_tables.append((name, data, upper_left, lower_right))
for row, col in self.__values.keys():
max_width = max(max_width, row+1)
max_height = max(max_height, col+1)
# Build the whole table up-front. Doing it row by row is too slow.
table = [[None] * max_width for i in range(max_height)]
for name, data, upper_left, lower_right in resolved_tables:
for i, r in enumerate(range(upper_left[0], lower_right[0]+1)):
for j, c in enumerate(range(upper_left[1], lower_right[1]+1)):
table[r][c] = data[i][j]
for (r, c), value in self.__values.items():
if isinstance(value, Value):
value = value.value
if isinstance(value, Expression):
if value.has_value:
self.__formula_values[(r, c)] = value.value
value = value.get_formula(workbook, r, c)
table[r][c] = value
for row in table:
yield row | python | def iterrows(self, workbook=None):
"""
Yield rows as lists of data.
The data is exactly as it is in the source pandas DataFrames and
any formulas are not resolved.
"""
resolved_tables = []
max_height = 0
max_width = 0
# while yielding rows __formula_values is updated with any formula values set on Expressions
self.__formula_values = {}
for name, (table, (row, col)) in list(self.__tables.items()):
# get the resolved 2d data array from the table
#
# expressions with no explicit table will use None when calling
# get_table/get_table_pos, which should return the current table.
#
self.__tables[None] = (table, (row, col))
data = table.get_data(workbook, row, col, self.__formula_values)
del self.__tables[None]
height, width = data.shape
upper_left = (row, col)
lower_right = (row + height - 1, col + width - 1)
max_height = max(max_height, lower_right[0] + 1)
max_width = max(max_width, lower_right[1] + 1)
resolved_tables.append((name, data, upper_left, lower_right))
for row, col in self.__values.keys():
max_width = max(max_width, row+1)
max_height = max(max_height, col+1)
# Build the whole table up-front. Doing it row by row is too slow.
table = [[None] * max_width for i in range(max_height)]
for name, data, upper_left, lower_right in resolved_tables:
for i, r in enumerate(range(upper_left[0], lower_right[0]+1)):
for j, c in enumerate(range(upper_left[1], lower_right[1]+1)):
table[r][c] = data[i][j]
for (r, c), value in self.__values.items():
if isinstance(value, Value):
value = value.value
if isinstance(value, Expression):
if value.has_value:
self.__formula_values[(r, c)] = value.value
value = value.get_formula(workbook, r, c)
table[r][c] = value
for row in table:
yield row | [
"def",
"iterrows",
"(",
"self",
",",
"workbook",
"=",
"None",
")",
":",
"resolved_tables",
"=",
"[",
"]",
"max_height",
"=",
"0",
"max_width",
"=",
"0",
"# while yielding rows __formula_values is updated with any formula values set on Expressions",
"self",
".",
"__formula_values",
"=",
"{",
"}",
"for",
"name",
",",
"(",
"table",
",",
"(",
"row",
",",
"col",
")",
")",
"in",
"list",
"(",
"self",
".",
"__tables",
".",
"items",
"(",
")",
")",
":",
"# get the resolved 2d data array from the table",
"#",
"# expressions with no explicit table will use None when calling",
"# get_table/get_table_pos, which should return the current table.",
"#",
"self",
".",
"__tables",
"[",
"None",
"]",
"=",
"(",
"table",
",",
"(",
"row",
",",
"col",
")",
")",
"data",
"=",
"table",
".",
"get_data",
"(",
"workbook",
",",
"row",
",",
"col",
",",
"self",
".",
"__formula_values",
")",
"del",
"self",
".",
"__tables",
"[",
"None",
"]",
"height",
",",
"width",
"=",
"data",
".",
"shape",
"upper_left",
"=",
"(",
"row",
",",
"col",
")",
"lower_right",
"=",
"(",
"row",
"+",
"height",
"-",
"1",
",",
"col",
"+",
"width",
"-",
"1",
")",
"max_height",
"=",
"max",
"(",
"max_height",
",",
"lower_right",
"[",
"0",
"]",
"+",
"1",
")",
"max_width",
"=",
"max",
"(",
"max_width",
",",
"lower_right",
"[",
"1",
"]",
"+",
"1",
")",
"resolved_tables",
".",
"append",
"(",
"(",
"name",
",",
"data",
",",
"upper_left",
",",
"lower_right",
")",
")",
"for",
"row",
",",
"col",
"in",
"self",
".",
"__values",
".",
"keys",
"(",
")",
":",
"max_width",
"=",
"max",
"(",
"max_width",
",",
"row",
"+",
"1",
")",
"max_height",
"=",
"max",
"(",
"max_height",
",",
"col",
"+",
"1",
")",
"# Build the whole table up-front. Doing it row by row is too slow.",
"table",
"=",
"[",
"[",
"None",
"]",
"*",
"max_width",
"for",
"i",
"in",
"range",
"(",
"max_height",
")",
"]",
"for",
"name",
",",
"data",
",",
"upper_left",
",",
"lower_right",
"in",
"resolved_tables",
":",
"for",
"i",
",",
"r",
"in",
"enumerate",
"(",
"range",
"(",
"upper_left",
"[",
"0",
"]",
",",
"lower_right",
"[",
"0",
"]",
"+",
"1",
")",
")",
":",
"for",
"j",
",",
"c",
"in",
"enumerate",
"(",
"range",
"(",
"upper_left",
"[",
"1",
"]",
",",
"lower_right",
"[",
"1",
"]",
"+",
"1",
")",
")",
":",
"table",
"[",
"r",
"]",
"[",
"c",
"]",
"=",
"data",
"[",
"i",
"]",
"[",
"j",
"]",
"for",
"(",
"r",
",",
"c",
")",
",",
"value",
"in",
"self",
".",
"__values",
".",
"items",
"(",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"Value",
")",
":",
"value",
"=",
"value",
".",
"value",
"if",
"isinstance",
"(",
"value",
",",
"Expression",
")",
":",
"if",
"value",
".",
"has_value",
":",
"self",
".",
"__formula_values",
"[",
"(",
"r",
",",
"c",
")",
"]",
"=",
"value",
".",
"value",
"value",
"=",
"value",
".",
"get_formula",
"(",
"workbook",
",",
"r",
",",
"c",
")",
"table",
"[",
"r",
"]",
"[",
"c",
"]",
"=",
"value",
"for",
"row",
"in",
"table",
":",
"yield",
"row"
]
| Yield rows as lists of data.
The data is exactly as it is in the source pandas DataFrames and
any formulas are not resolved. | [
"Yield",
"rows",
"as",
"lists",
"of",
"data",
"."
]
| 7a592642d27ad5ee90d2aa8c26338abaa9d84bea | https://github.com/fkarb/xltable/blob/7a592642d27ad5ee90d2aa8c26338abaa9d84bea/xltable/worksheet.py#L115-L169 | train |
redhat-cip/python-dciclient | dciclient/v1/api/file.py | create | def create(context, name, content=None, file_path=None, mime='text/plain',
jobstate_id=None, md5=None, job_id=None, test_id=None):
"""Method to create a file on the Control-Server
This method allows one to upload a file to the Control-Server. The file
to be uploaded can be specified in two different ways either by specifying
its content directly or or by specifying the file_path where the file is
located.
content can be in the form of: string, bytes or a file-descriptor.
"""
if content and file_path:
raise Exception('content and file_path are mutually exclusive')
elif not content and not file_path:
raise Exception(
'At least one of content or file_path must be specified'
)
headers = {'DCI-NAME': name,
'DCI-MIME': mime,
'DCI-JOBSTATE-ID': jobstate_id,
'DCI-MD5': md5,
'DCI-JOB-ID': job_id,
'DCI-TEST-ID': test_id}
headers = utils.sanitize_kwargs(**headers)
uri = '%s/%s' % (context.dci_cs_api, RESOURCE)
if content:
if not hasattr(content, 'read'):
if not isinstance(content, bytes):
content = content.encode('utf-8')
content = io.BytesIO(content)
return context.session.post(uri, headers=headers, data=content)
else:
if not os.path.exists(file_path):
raise FileErrorException()
with open(file_path, 'rb') as f:
return context.session.post(uri, headers=headers, data=f) | python | def create(context, name, content=None, file_path=None, mime='text/plain',
jobstate_id=None, md5=None, job_id=None, test_id=None):
"""Method to create a file on the Control-Server
This method allows one to upload a file to the Control-Server. The file
to be uploaded can be specified in two different ways either by specifying
its content directly or or by specifying the file_path where the file is
located.
content can be in the form of: string, bytes or a file-descriptor.
"""
if content and file_path:
raise Exception('content and file_path are mutually exclusive')
elif not content and not file_path:
raise Exception(
'At least one of content or file_path must be specified'
)
headers = {'DCI-NAME': name,
'DCI-MIME': mime,
'DCI-JOBSTATE-ID': jobstate_id,
'DCI-MD5': md5,
'DCI-JOB-ID': job_id,
'DCI-TEST-ID': test_id}
headers = utils.sanitize_kwargs(**headers)
uri = '%s/%s' % (context.dci_cs_api, RESOURCE)
if content:
if not hasattr(content, 'read'):
if not isinstance(content, bytes):
content = content.encode('utf-8')
content = io.BytesIO(content)
return context.session.post(uri, headers=headers, data=content)
else:
if not os.path.exists(file_path):
raise FileErrorException()
with open(file_path, 'rb') as f:
return context.session.post(uri, headers=headers, data=f) | [
"def",
"create",
"(",
"context",
",",
"name",
",",
"content",
"=",
"None",
",",
"file_path",
"=",
"None",
",",
"mime",
"=",
"'text/plain'",
",",
"jobstate_id",
"=",
"None",
",",
"md5",
"=",
"None",
",",
"job_id",
"=",
"None",
",",
"test_id",
"=",
"None",
")",
":",
"if",
"content",
"and",
"file_path",
":",
"raise",
"Exception",
"(",
"'content and file_path are mutually exclusive'",
")",
"elif",
"not",
"content",
"and",
"not",
"file_path",
":",
"raise",
"Exception",
"(",
"'At least one of content or file_path must be specified'",
")",
"headers",
"=",
"{",
"'DCI-NAME'",
":",
"name",
",",
"'DCI-MIME'",
":",
"mime",
",",
"'DCI-JOBSTATE-ID'",
":",
"jobstate_id",
",",
"'DCI-MD5'",
":",
"md5",
",",
"'DCI-JOB-ID'",
":",
"job_id",
",",
"'DCI-TEST-ID'",
":",
"test_id",
"}",
"headers",
"=",
"utils",
".",
"sanitize_kwargs",
"(",
"*",
"*",
"headers",
")",
"uri",
"=",
"'%s/%s'",
"%",
"(",
"context",
".",
"dci_cs_api",
",",
"RESOURCE",
")",
"if",
"content",
":",
"if",
"not",
"hasattr",
"(",
"content",
",",
"'read'",
")",
":",
"if",
"not",
"isinstance",
"(",
"content",
",",
"bytes",
")",
":",
"content",
"=",
"content",
".",
"encode",
"(",
"'utf-8'",
")",
"content",
"=",
"io",
".",
"BytesIO",
"(",
"content",
")",
"return",
"context",
".",
"session",
".",
"post",
"(",
"uri",
",",
"headers",
"=",
"headers",
",",
"data",
"=",
"content",
")",
"else",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"file_path",
")",
":",
"raise",
"FileErrorException",
"(",
")",
"with",
"open",
"(",
"file_path",
",",
"'rb'",
")",
"as",
"f",
":",
"return",
"context",
".",
"session",
".",
"post",
"(",
"uri",
",",
"headers",
"=",
"headers",
",",
"data",
"=",
"f",
")"
]
| Method to create a file on the Control-Server
This method allows one to upload a file to the Control-Server. The file
to be uploaded can be specified in two different ways either by specifying
its content directly or or by specifying the file_path where the file is
located.
content can be in the form of: string, bytes or a file-descriptor. | [
"Method",
"to",
"create",
"a",
"file",
"on",
"the",
"Control",
"-",
"Server"
]
| a4aa5899062802bbe4c30a075d8447f8d222d214 | https://github.com/redhat-cip/python-dciclient/blob/a4aa5899062802bbe4c30a075d8447f8d222d214/dciclient/v1/api/file.py#L26-L65 | train |
lsst-sqre/documenteer | documenteer/sphinxext/lssttasks/configfieldlists.py | register_formatter | def register_formatter(field_typestr):
"""Decorate a configuration field formatter function to register it with
the `get_field_formatter` accessor.
This decorator also performs common helpers for the formatter functions:
- Does type checking on the field argument passed to a formatter.
- Assembles a section node from the nodes returned by the formatter.
"""
def decorator_register(formatter):
@functools.wraps(formatter)
def wrapped_formatter(*args, **kwargs):
field_name = args[0]
field = args[1]
field_id = args[2]
# Before running the formatter, do type checking
field_type = get_type(field_typestr)
if not isinstance(field, field_type):
message = ('Field {0} ({1!r}) is not an '
'{2} type. It is an {3}.')
raise ValueError(
message.format(field_name, field, field_typestr,
typestring(field)))
# Run the formatter itself
nodes = formatter(*args, **kwargs)
# Package nodes from the formatter into a section
section = make_section(
section_id=field_id + '-section',
contents=nodes)
return section
FIELD_FORMATTERS[field_typestr] = wrapped_formatter
return wrapped_formatter
return decorator_register | python | def register_formatter(field_typestr):
"""Decorate a configuration field formatter function to register it with
the `get_field_formatter` accessor.
This decorator also performs common helpers for the formatter functions:
- Does type checking on the field argument passed to a formatter.
- Assembles a section node from the nodes returned by the formatter.
"""
def decorator_register(formatter):
@functools.wraps(formatter)
def wrapped_formatter(*args, **kwargs):
field_name = args[0]
field = args[1]
field_id = args[2]
# Before running the formatter, do type checking
field_type = get_type(field_typestr)
if not isinstance(field, field_type):
message = ('Field {0} ({1!r}) is not an '
'{2} type. It is an {3}.')
raise ValueError(
message.format(field_name, field, field_typestr,
typestring(field)))
# Run the formatter itself
nodes = formatter(*args, **kwargs)
# Package nodes from the formatter into a section
section = make_section(
section_id=field_id + '-section',
contents=nodes)
return section
FIELD_FORMATTERS[field_typestr] = wrapped_formatter
return wrapped_formatter
return decorator_register | [
"def",
"register_formatter",
"(",
"field_typestr",
")",
":",
"def",
"decorator_register",
"(",
"formatter",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"formatter",
")",
"def",
"wrapped_formatter",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"field_name",
"=",
"args",
"[",
"0",
"]",
"field",
"=",
"args",
"[",
"1",
"]",
"field_id",
"=",
"args",
"[",
"2",
"]",
"# Before running the formatter, do type checking",
"field_type",
"=",
"get_type",
"(",
"field_typestr",
")",
"if",
"not",
"isinstance",
"(",
"field",
",",
"field_type",
")",
":",
"message",
"=",
"(",
"'Field {0} ({1!r}) is not an '",
"'{2} type. It is an {3}.'",
")",
"raise",
"ValueError",
"(",
"message",
".",
"format",
"(",
"field_name",
",",
"field",
",",
"field_typestr",
",",
"typestring",
"(",
"field",
")",
")",
")",
"# Run the formatter itself",
"nodes",
"=",
"formatter",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"# Package nodes from the formatter into a section",
"section",
"=",
"make_section",
"(",
"section_id",
"=",
"field_id",
"+",
"'-section'",
",",
"contents",
"=",
"nodes",
")",
"return",
"section",
"FIELD_FORMATTERS",
"[",
"field_typestr",
"]",
"=",
"wrapped_formatter",
"return",
"wrapped_formatter",
"return",
"decorator_register"
]
| Decorate a configuration field formatter function to register it with
the `get_field_formatter` accessor.
This decorator also performs common helpers for the formatter functions:
- Does type checking on the field argument passed to a formatter.
- Assembles a section node from the nodes returned by the formatter. | [
"Decorate",
"a",
"configuration",
"field",
"formatter",
"function",
"to",
"register",
"it",
"with",
"the",
"get_field_formatter",
"accessor",
"."
]
| 75f02901a80042b28d074df1cc1dca32eb8e38c8 | https://github.com/lsst-sqre/documenteer/blob/75f02901a80042b28d074df1cc1dca32eb8e38c8/documenteer/sphinxext/lssttasks/configfieldlists.py#L281-L319 | train |
lsst-sqre/documenteer | documenteer/sphinxext/lssttasks/configfieldlists.py | format_configurablefield_nodes | def format_configurablefield_nodes(field_name, field, field_id, state, lineno):
"""Create a section node that documents a ConfigurableField config field.
Parameters
----------
field_name : `str`
Name of the configuration field (the attribute name of on the config
class).
field : ``lsst.pex.config.ConfigurableField``
A configuration field.
field_id : `str`
Unique identifier for this field. This is used as the id and name of
the section node. with a -section suffix
state : ``docutils.statemachine.State``
Usually the directive's ``state`` attribute.
lineno (`int`)
Usually the directive's ``lineno`` attribute.
Returns
-------
``docutils.nodes.section``
Section containing documentation nodes for the ConfigurableField.
"""
# Custom default target definition list that links to Task topics
default_item = nodes.definition_list_item()
default_item.append(nodes.term(text="Default"))
default_item_content = nodes.definition()
para = nodes.paragraph()
name = '.'.join((field.target.__module__, field.target.__name__))
para += pending_task_xref(rawsource=name)
default_item_content += para
default_item += default_item_content
# Definition list for key-value metadata
dl = nodes.definition_list()
dl += default_item
dl += create_field_type_item_node(field, state)
# Doc for this ConfigurableField, parsed as rst
desc_node = create_description_node(field, state)
# Title for configuration field
title = create_title_node(field_name, field, field_id, state, lineno)
return [title, dl, desc_node] | python | def format_configurablefield_nodes(field_name, field, field_id, state, lineno):
"""Create a section node that documents a ConfigurableField config field.
Parameters
----------
field_name : `str`
Name of the configuration field (the attribute name of on the config
class).
field : ``lsst.pex.config.ConfigurableField``
A configuration field.
field_id : `str`
Unique identifier for this field. This is used as the id and name of
the section node. with a -section suffix
state : ``docutils.statemachine.State``
Usually the directive's ``state`` attribute.
lineno (`int`)
Usually the directive's ``lineno`` attribute.
Returns
-------
``docutils.nodes.section``
Section containing documentation nodes for the ConfigurableField.
"""
# Custom default target definition list that links to Task topics
default_item = nodes.definition_list_item()
default_item.append(nodes.term(text="Default"))
default_item_content = nodes.definition()
para = nodes.paragraph()
name = '.'.join((field.target.__module__, field.target.__name__))
para += pending_task_xref(rawsource=name)
default_item_content += para
default_item += default_item_content
# Definition list for key-value metadata
dl = nodes.definition_list()
dl += default_item
dl += create_field_type_item_node(field, state)
# Doc for this ConfigurableField, parsed as rst
desc_node = create_description_node(field, state)
# Title for configuration field
title = create_title_node(field_name, field, field_id, state, lineno)
return [title, dl, desc_node] | [
"def",
"format_configurablefield_nodes",
"(",
"field_name",
",",
"field",
",",
"field_id",
",",
"state",
",",
"lineno",
")",
":",
"# Custom default target definition list that links to Task topics",
"default_item",
"=",
"nodes",
".",
"definition_list_item",
"(",
")",
"default_item",
".",
"append",
"(",
"nodes",
".",
"term",
"(",
"text",
"=",
"\"Default\"",
")",
")",
"default_item_content",
"=",
"nodes",
".",
"definition",
"(",
")",
"para",
"=",
"nodes",
".",
"paragraph",
"(",
")",
"name",
"=",
"'.'",
".",
"join",
"(",
"(",
"field",
".",
"target",
".",
"__module__",
",",
"field",
".",
"target",
".",
"__name__",
")",
")",
"para",
"+=",
"pending_task_xref",
"(",
"rawsource",
"=",
"name",
")",
"default_item_content",
"+=",
"para",
"default_item",
"+=",
"default_item_content",
"# Definition list for key-value metadata",
"dl",
"=",
"nodes",
".",
"definition_list",
"(",
")",
"dl",
"+=",
"default_item",
"dl",
"+=",
"create_field_type_item_node",
"(",
"field",
",",
"state",
")",
"# Doc for this ConfigurableField, parsed as rst",
"desc_node",
"=",
"create_description_node",
"(",
"field",
",",
"state",
")",
"# Title for configuration field",
"title",
"=",
"create_title_node",
"(",
"field_name",
",",
"field",
",",
"field_id",
",",
"state",
",",
"lineno",
")",
"return",
"[",
"title",
",",
"dl",
",",
"desc_node",
"]"
]
| Create a section node that documents a ConfigurableField config field.
Parameters
----------
field_name : `str`
Name of the configuration field (the attribute name of on the config
class).
field : ``lsst.pex.config.ConfigurableField``
A configuration field.
field_id : `str`
Unique identifier for this field. This is used as the id and name of
the section node. with a -section suffix
state : ``docutils.statemachine.State``
Usually the directive's ``state`` attribute.
lineno (`int`)
Usually the directive's ``lineno`` attribute.
Returns
-------
``docutils.nodes.section``
Section containing documentation nodes for the ConfigurableField. | [
"Create",
"a",
"section",
"node",
"that",
"documents",
"a",
"ConfigurableField",
"config",
"field",
"."
]
| 75f02901a80042b28d074df1cc1dca32eb8e38c8 | https://github.com/lsst-sqre/documenteer/blob/75f02901a80042b28d074df1cc1dca32eb8e38c8/documenteer/sphinxext/lssttasks/configfieldlists.py#L380-L424 | train |
lsst-sqre/documenteer | documenteer/sphinxext/lssttasks/configfieldlists.py | format_listfield_nodes | def format_listfield_nodes(field_name, field, field_id, state, lineno):
"""Create a section node that documents a ListField config field.
Parameters
----------
field_name : `str`
Name of the configuration field (the attribute name of on the config
class).
field : ``lsst.pex.config.ListField``
A configuration field.
field_id : `str`
Unique identifier for this field. This is used as the id and name of
the section node. with a -section suffix
state : ``docutils.statemachine.State``
Usually the directive's ``state`` attribute.
lineno (`int`)
Usually the directive's ``lineno`` attribute.
Returns
-------
``docutils.nodes.section``
Section containing documentation nodes for the ListField.
"""
# ListField's store their item types in the itemtype attribute
itemtype_node = nodes.definition_list_item()
itemtype_node += nodes.term(text='Item type')
itemtype_def = nodes.definition()
itemtype_def += make_python_xref_nodes_for_type(
field.itemtype,
state,
hide_namespace=False)
itemtype_node += itemtype_def
minlength_node = None
if field.minLength:
minlength_node = nodes.definition_list_item()
minlength_node += nodes.term(text='Minimum length')
minlength_def = nodes.definition()
minlength_def += nodes.paragraph(text=str(field.minLength))
minlength_node += minlength_def
maxlength_node = None
if field.maxLength:
maxlength_node = nodes.definition_list_item()
maxlength_node += nodes.term(text='Maximum length')
maxlength_def = nodes.definition()
maxlength_def += nodes.paragraph(text=str(field.maxLength))
maxlength_node += maxlength_def
length_node = None
if field.length:
length_node = nodes.definition_list_item()
length_node += nodes.term(text='Required length')
length_def = nodes.definition()
length_def += nodes.paragraph(text=str(field.length))
length_node += length_def
# Type description
field_type_item = nodes.definition_list_item()
field_type_item.append(nodes.term(text="Field type"))
field_type_item_content = nodes.definition()
field_type_item_content_p = nodes.paragraph()
field_type_item_content_p += make_python_xref_nodes_for_type(
field.itemtype,
state,
hide_namespace=False)[0].children[0]
field_type_item_content_p += nodes.Text(' ', ' ')
field_type_item_content_p += make_python_xref_nodes_for_type(
type(field),
state,
hide_namespace=True)[0].children[0]
if field.optional:
field_type_item_content_p += nodes.Text(' (optional)', ' (optional)')
field_type_item_content += field_type_item_content_p
field_type_item += field_type_item_content
# Reference target
env = state.document.settings.env
ref_target = create_configfield_ref_target_node(field_id, env, lineno)
# Title is the field's attribute name
title = nodes.title(text=field_name)
title += ref_target
# Definition list for key-value metadata
dl = nodes.definition_list()
dl += create_default_item_node(field, state)
dl += field_type_item
if minlength_node:
dl += minlength_node
if maxlength_node:
dl += maxlength_node
if length_node:
dl += length_node
# Doc for this ConfigurableField, parsed as rst
desc_node = create_description_node(field, state)
# Title for configuration field
title = create_title_node(field_name, field, field_id, state, lineno)
return [title, dl, desc_node] | python | def format_listfield_nodes(field_name, field, field_id, state, lineno):
"""Create a section node that documents a ListField config field.
Parameters
----------
field_name : `str`
Name of the configuration field (the attribute name of on the config
class).
field : ``lsst.pex.config.ListField``
A configuration field.
field_id : `str`
Unique identifier for this field. This is used as the id and name of
the section node. with a -section suffix
state : ``docutils.statemachine.State``
Usually the directive's ``state`` attribute.
lineno (`int`)
Usually the directive's ``lineno`` attribute.
Returns
-------
``docutils.nodes.section``
Section containing documentation nodes for the ListField.
"""
# ListField's store their item types in the itemtype attribute
itemtype_node = nodes.definition_list_item()
itemtype_node += nodes.term(text='Item type')
itemtype_def = nodes.definition()
itemtype_def += make_python_xref_nodes_for_type(
field.itemtype,
state,
hide_namespace=False)
itemtype_node += itemtype_def
minlength_node = None
if field.minLength:
minlength_node = nodes.definition_list_item()
minlength_node += nodes.term(text='Minimum length')
minlength_def = nodes.definition()
minlength_def += nodes.paragraph(text=str(field.minLength))
minlength_node += minlength_def
maxlength_node = None
if field.maxLength:
maxlength_node = nodes.definition_list_item()
maxlength_node += nodes.term(text='Maximum length')
maxlength_def = nodes.definition()
maxlength_def += nodes.paragraph(text=str(field.maxLength))
maxlength_node += maxlength_def
length_node = None
if field.length:
length_node = nodes.definition_list_item()
length_node += nodes.term(text='Required length')
length_def = nodes.definition()
length_def += nodes.paragraph(text=str(field.length))
length_node += length_def
# Type description
field_type_item = nodes.definition_list_item()
field_type_item.append(nodes.term(text="Field type"))
field_type_item_content = nodes.definition()
field_type_item_content_p = nodes.paragraph()
field_type_item_content_p += make_python_xref_nodes_for_type(
field.itemtype,
state,
hide_namespace=False)[0].children[0]
field_type_item_content_p += nodes.Text(' ', ' ')
field_type_item_content_p += make_python_xref_nodes_for_type(
type(field),
state,
hide_namespace=True)[0].children[0]
if field.optional:
field_type_item_content_p += nodes.Text(' (optional)', ' (optional)')
field_type_item_content += field_type_item_content_p
field_type_item += field_type_item_content
# Reference target
env = state.document.settings.env
ref_target = create_configfield_ref_target_node(field_id, env, lineno)
# Title is the field's attribute name
title = nodes.title(text=field_name)
title += ref_target
# Definition list for key-value metadata
dl = nodes.definition_list()
dl += create_default_item_node(field, state)
dl += field_type_item
if minlength_node:
dl += minlength_node
if maxlength_node:
dl += maxlength_node
if length_node:
dl += length_node
# Doc for this ConfigurableField, parsed as rst
desc_node = create_description_node(field, state)
# Title for configuration field
title = create_title_node(field_name, field, field_id, state, lineno)
return [title, dl, desc_node] | [
"def",
"format_listfield_nodes",
"(",
"field_name",
",",
"field",
",",
"field_id",
",",
"state",
",",
"lineno",
")",
":",
"# ListField's store their item types in the itemtype attribute",
"itemtype_node",
"=",
"nodes",
".",
"definition_list_item",
"(",
")",
"itemtype_node",
"+=",
"nodes",
".",
"term",
"(",
"text",
"=",
"'Item type'",
")",
"itemtype_def",
"=",
"nodes",
".",
"definition",
"(",
")",
"itemtype_def",
"+=",
"make_python_xref_nodes_for_type",
"(",
"field",
".",
"itemtype",
",",
"state",
",",
"hide_namespace",
"=",
"False",
")",
"itemtype_node",
"+=",
"itemtype_def",
"minlength_node",
"=",
"None",
"if",
"field",
".",
"minLength",
":",
"minlength_node",
"=",
"nodes",
".",
"definition_list_item",
"(",
")",
"minlength_node",
"+=",
"nodes",
".",
"term",
"(",
"text",
"=",
"'Minimum length'",
")",
"minlength_def",
"=",
"nodes",
".",
"definition",
"(",
")",
"minlength_def",
"+=",
"nodes",
".",
"paragraph",
"(",
"text",
"=",
"str",
"(",
"field",
".",
"minLength",
")",
")",
"minlength_node",
"+=",
"minlength_def",
"maxlength_node",
"=",
"None",
"if",
"field",
".",
"maxLength",
":",
"maxlength_node",
"=",
"nodes",
".",
"definition_list_item",
"(",
")",
"maxlength_node",
"+=",
"nodes",
".",
"term",
"(",
"text",
"=",
"'Maximum length'",
")",
"maxlength_def",
"=",
"nodes",
".",
"definition",
"(",
")",
"maxlength_def",
"+=",
"nodes",
".",
"paragraph",
"(",
"text",
"=",
"str",
"(",
"field",
".",
"maxLength",
")",
")",
"maxlength_node",
"+=",
"maxlength_def",
"length_node",
"=",
"None",
"if",
"field",
".",
"length",
":",
"length_node",
"=",
"nodes",
".",
"definition_list_item",
"(",
")",
"length_node",
"+=",
"nodes",
".",
"term",
"(",
"text",
"=",
"'Required length'",
")",
"length_def",
"=",
"nodes",
".",
"definition",
"(",
")",
"length_def",
"+=",
"nodes",
".",
"paragraph",
"(",
"text",
"=",
"str",
"(",
"field",
".",
"length",
")",
")",
"length_node",
"+=",
"length_def",
"# Type description",
"field_type_item",
"=",
"nodes",
".",
"definition_list_item",
"(",
")",
"field_type_item",
".",
"append",
"(",
"nodes",
".",
"term",
"(",
"text",
"=",
"\"Field type\"",
")",
")",
"field_type_item_content",
"=",
"nodes",
".",
"definition",
"(",
")",
"field_type_item_content_p",
"=",
"nodes",
".",
"paragraph",
"(",
")",
"field_type_item_content_p",
"+=",
"make_python_xref_nodes_for_type",
"(",
"field",
".",
"itemtype",
",",
"state",
",",
"hide_namespace",
"=",
"False",
")",
"[",
"0",
"]",
".",
"children",
"[",
"0",
"]",
"field_type_item_content_p",
"+=",
"nodes",
".",
"Text",
"(",
"' '",
",",
"' '",
")",
"field_type_item_content_p",
"+=",
"make_python_xref_nodes_for_type",
"(",
"type",
"(",
"field",
")",
",",
"state",
",",
"hide_namespace",
"=",
"True",
")",
"[",
"0",
"]",
".",
"children",
"[",
"0",
"]",
"if",
"field",
".",
"optional",
":",
"field_type_item_content_p",
"+=",
"nodes",
".",
"Text",
"(",
"' (optional)'",
",",
"' (optional)'",
")",
"field_type_item_content",
"+=",
"field_type_item_content_p",
"field_type_item",
"+=",
"field_type_item_content",
"# Reference target",
"env",
"=",
"state",
".",
"document",
".",
"settings",
".",
"env",
"ref_target",
"=",
"create_configfield_ref_target_node",
"(",
"field_id",
",",
"env",
",",
"lineno",
")",
"# Title is the field's attribute name",
"title",
"=",
"nodes",
".",
"title",
"(",
"text",
"=",
"field_name",
")",
"title",
"+=",
"ref_target",
"# Definition list for key-value metadata",
"dl",
"=",
"nodes",
".",
"definition_list",
"(",
")",
"dl",
"+=",
"create_default_item_node",
"(",
"field",
",",
"state",
")",
"dl",
"+=",
"field_type_item",
"if",
"minlength_node",
":",
"dl",
"+=",
"minlength_node",
"if",
"maxlength_node",
":",
"dl",
"+=",
"maxlength_node",
"if",
"length_node",
":",
"dl",
"+=",
"length_node",
"# Doc for this ConfigurableField, parsed as rst",
"desc_node",
"=",
"create_description_node",
"(",
"field",
",",
"state",
")",
"# Title for configuration field",
"title",
"=",
"create_title_node",
"(",
"field_name",
",",
"field",
",",
"field_id",
",",
"state",
",",
"lineno",
")",
"return",
"[",
"title",
",",
"dl",
",",
"desc_node",
"]"
]
| Create a section node that documents a ListField config field.
Parameters
----------
field_name : `str`
Name of the configuration field (the attribute name of on the config
class).
field : ``lsst.pex.config.ListField``
A configuration field.
field_id : `str`
Unique identifier for this field. This is used as the id and name of
the section node. with a -section suffix
state : ``docutils.statemachine.State``
Usually the directive's ``state`` attribute.
lineno (`int`)
Usually the directive's ``lineno`` attribute.
Returns
-------
``docutils.nodes.section``
Section containing documentation nodes for the ListField. | [
"Create",
"a",
"section",
"node",
"that",
"documents",
"a",
"ListField",
"config",
"field",
"."
]
| 75f02901a80042b28d074df1cc1dca32eb8e38c8 | https://github.com/lsst-sqre/documenteer/blob/75f02901a80042b28d074df1cc1dca32eb8e38c8/documenteer/sphinxext/lssttasks/configfieldlists.py#L428-L529 | train |
lsst-sqre/documenteer | documenteer/sphinxext/lssttasks/configfieldlists.py | format_choicefield_nodes | def format_choicefield_nodes(field_name, field, field_id, state, lineno):
"""Create a section node that documents a ChoiceField config field.
Parameters
----------
field_name : `str`
Name of the configuration field (the attribute name of on the config
class).
field : ``lsst.pex.config.ChoiceField``
A configuration field.
field_id : `str`
Unique identifier for this field. This is used as the id and name of
the section node. with a -section suffix
state : ``docutils.statemachine.State``
Usually the directive's ``state`` attribute.
lineno (`int`)
Usually the directive's ``lineno`` attribute.
Returns
-------
``docutils.nodes.section``
Section containing documentation nodes for the ChoiceField.
"""
# Create a definition list for the choices
choice_dl = nodes.definition_list()
for choice_value, choice_doc in field.allowed.items():
item = nodes.definition_list_item()
item_term = nodes.term()
item_term += nodes.literal(text=repr(choice_value))
item += item_term
item_definition = nodes.definition()
item_definition.append(nodes.paragraph(text=choice_doc))
item += item_definition
choice_dl.append(item)
choices_node = nodes.definition_list_item()
choices_node.append(nodes.term(text='Choices'))
choices_definition = nodes.definition()
choices_definition.append(choice_dl)
choices_node.append(choices_definition)
# Field type
field_type_item = nodes.definition_list_item()
field_type_item.append(nodes.term(text="Field type"))
field_type_item_content = nodes.definition()
field_type_item_content_p = nodes.paragraph()
field_type_item_content_p += make_python_xref_nodes_for_type(
field.dtype,
state,
hide_namespace=False)[0].children[0]
field_type_item_content_p += nodes.Text(' ', ' ')
field_type_item_content_p += make_python_xref_nodes_for_type(
type(field),
state,
hide_namespace=True)[0].children[0]
if field.optional:
field_type_item_content_p += nodes.Text(' (optional)', ' (optional)')
field_type_item_content += field_type_item_content_p
field_type_item += field_type_item_content
# Definition list for key-value metadata
dl = nodes.definition_list()
dl += create_default_item_node(field, state)
dl += field_type_item
dl += choices_node
# Doc for this ConfigurableField, parsed as rst
desc_node = create_description_node(field, state)
# Title for configuration field
title = create_title_node(field_name, field, field_id, state, lineno)
return [title, dl, desc_node] | python | def format_choicefield_nodes(field_name, field, field_id, state, lineno):
"""Create a section node that documents a ChoiceField config field.
Parameters
----------
field_name : `str`
Name of the configuration field (the attribute name of on the config
class).
field : ``lsst.pex.config.ChoiceField``
A configuration field.
field_id : `str`
Unique identifier for this field. This is used as the id and name of
the section node. with a -section suffix
state : ``docutils.statemachine.State``
Usually the directive's ``state`` attribute.
lineno (`int`)
Usually the directive's ``lineno`` attribute.
Returns
-------
``docutils.nodes.section``
Section containing documentation nodes for the ChoiceField.
"""
# Create a definition list for the choices
choice_dl = nodes.definition_list()
for choice_value, choice_doc in field.allowed.items():
item = nodes.definition_list_item()
item_term = nodes.term()
item_term += nodes.literal(text=repr(choice_value))
item += item_term
item_definition = nodes.definition()
item_definition.append(nodes.paragraph(text=choice_doc))
item += item_definition
choice_dl.append(item)
choices_node = nodes.definition_list_item()
choices_node.append(nodes.term(text='Choices'))
choices_definition = nodes.definition()
choices_definition.append(choice_dl)
choices_node.append(choices_definition)
# Field type
field_type_item = nodes.definition_list_item()
field_type_item.append(nodes.term(text="Field type"))
field_type_item_content = nodes.definition()
field_type_item_content_p = nodes.paragraph()
field_type_item_content_p += make_python_xref_nodes_for_type(
field.dtype,
state,
hide_namespace=False)[0].children[0]
field_type_item_content_p += nodes.Text(' ', ' ')
field_type_item_content_p += make_python_xref_nodes_for_type(
type(field),
state,
hide_namespace=True)[0].children[0]
if field.optional:
field_type_item_content_p += nodes.Text(' (optional)', ' (optional)')
field_type_item_content += field_type_item_content_p
field_type_item += field_type_item_content
# Definition list for key-value metadata
dl = nodes.definition_list()
dl += create_default_item_node(field, state)
dl += field_type_item
dl += choices_node
# Doc for this ConfigurableField, parsed as rst
desc_node = create_description_node(field, state)
# Title for configuration field
title = create_title_node(field_name, field, field_id, state, lineno)
return [title, dl, desc_node] | [
"def",
"format_choicefield_nodes",
"(",
"field_name",
",",
"field",
",",
"field_id",
",",
"state",
",",
"lineno",
")",
":",
"# Create a definition list for the choices",
"choice_dl",
"=",
"nodes",
".",
"definition_list",
"(",
")",
"for",
"choice_value",
",",
"choice_doc",
"in",
"field",
".",
"allowed",
".",
"items",
"(",
")",
":",
"item",
"=",
"nodes",
".",
"definition_list_item",
"(",
")",
"item_term",
"=",
"nodes",
".",
"term",
"(",
")",
"item_term",
"+=",
"nodes",
".",
"literal",
"(",
"text",
"=",
"repr",
"(",
"choice_value",
")",
")",
"item",
"+=",
"item_term",
"item_definition",
"=",
"nodes",
".",
"definition",
"(",
")",
"item_definition",
".",
"append",
"(",
"nodes",
".",
"paragraph",
"(",
"text",
"=",
"choice_doc",
")",
")",
"item",
"+=",
"item_definition",
"choice_dl",
".",
"append",
"(",
"item",
")",
"choices_node",
"=",
"nodes",
".",
"definition_list_item",
"(",
")",
"choices_node",
".",
"append",
"(",
"nodes",
".",
"term",
"(",
"text",
"=",
"'Choices'",
")",
")",
"choices_definition",
"=",
"nodes",
".",
"definition",
"(",
")",
"choices_definition",
".",
"append",
"(",
"choice_dl",
")",
"choices_node",
".",
"append",
"(",
"choices_definition",
")",
"# Field type",
"field_type_item",
"=",
"nodes",
".",
"definition_list_item",
"(",
")",
"field_type_item",
".",
"append",
"(",
"nodes",
".",
"term",
"(",
"text",
"=",
"\"Field type\"",
")",
")",
"field_type_item_content",
"=",
"nodes",
".",
"definition",
"(",
")",
"field_type_item_content_p",
"=",
"nodes",
".",
"paragraph",
"(",
")",
"field_type_item_content_p",
"+=",
"make_python_xref_nodes_for_type",
"(",
"field",
".",
"dtype",
",",
"state",
",",
"hide_namespace",
"=",
"False",
")",
"[",
"0",
"]",
".",
"children",
"[",
"0",
"]",
"field_type_item_content_p",
"+=",
"nodes",
".",
"Text",
"(",
"' '",
",",
"' '",
")",
"field_type_item_content_p",
"+=",
"make_python_xref_nodes_for_type",
"(",
"type",
"(",
"field",
")",
",",
"state",
",",
"hide_namespace",
"=",
"True",
")",
"[",
"0",
"]",
".",
"children",
"[",
"0",
"]",
"if",
"field",
".",
"optional",
":",
"field_type_item_content_p",
"+=",
"nodes",
".",
"Text",
"(",
"' (optional)'",
",",
"' (optional)'",
")",
"field_type_item_content",
"+=",
"field_type_item_content_p",
"field_type_item",
"+=",
"field_type_item_content",
"# Definition list for key-value metadata",
"dl",
"=",
"nodes",
".",
"definition_list",
"(",
")",
"dl",
"+=",
"create_default_item_node",
"(",
"field",
",",
"state",
")",
"dl",
"+=",
"field_type_item",
"dl",
"+=",
"choices_node",
"# Doc for this ConfigurableField, parsed as rst",
"desc_node",
"=",
"create_description_node",
"(",
"field",
",",
"state",
")",
"# Title for configuration field",
"title",
"=",
"create_title_node",
"(",
"field_name",
",",
"field",
",",
"field_id",
",",
"state",
",",
"lineno",
")",
"return",
"[",
"title",
",",
"dl",
",",
"desc_node",
"]"
]
| Create a section node that documents a ChoiceField config field.
Parameters
----------
field_name : `str`
Name of the configuration field (the attribute name of on the config
class).
field : ``lsst.pex.config.ChoiceField``
A configuration field.
field_id : `str`
Unique identifier for this field. This is used as the id and name of
the section node. with a -section suffix
state : ``docutils.statemachine.State``
Usually the directive's ``state`` attribute.
lineno (`int`)
Usually the directive's ``lineno`` attribute.
Returns
-------
``docutils.nodes.section``
Section containing documentation nodes for the ChoiceField. | [
"Create",
"a",
"section",
"node",
"that",
"documents",
"a",
"ChoiceField",
"config",
"field",
"."
]
| 75f02901a80042b28d074df1cc1dca32eb8e38c8 | https://github.com/lsst-sqre/documenteer/blob/75f02901a80042b28d074df1cc1dca32eb8e38c8/documenteer/sphinxext/lssttasks/configfieldlists.py#L533-L605 | train |
lsst-sqre/documenteer | documenteer/sphinxext/lssttasks/configfieldlists.py | format_rangefield_nodes | def format_rangefield_nodes(field_name, field, field_id, state, lineno):
"""Create a section node that documents a RangeField config field.
Parameters
----------
field_name : `str`
Name of the configuration field (the attribute name of on the config
class).
field : ``lsst.pex.config.RangeField``
A configuration field.
field_id : `str`
Unique identifier for this field. This is used as the id and name of
the section node. with a -section suffix
state : ``docutils.statemachine.State``
Usually the directive's ``state`` attribute.
lineno (`int`)
Usually the directive's ``lineno`` attribute.
Returns
-------
``docutils.nodes.section``
Section containing documentation nodes for the RangeField.
"""
# Field type
field_type_item = nodes.definition_list_item()
field_type_item.append(nodes.term(text="Field type"))
field_type_item_content = nodes.definition()
field_type_item_content_p = nodes.paragraph()
field_type_item_content_p += make_python_xref_nodes_for_type(
field.dtype,
state,
hide_namespace=False)[0].children[0]
field_type_item_content_p += nodes.Text(' ', ' ')
field_type_item_content_p += make_python_xref_nodes_for_type(
type(field),
state,
hide_namespace=True)[0].children[0]
if field.optional:
field_type_item_content_p += nodes.Text(' (optional)', ' (optional)')
field_type_item_content += field_type_item_content_p
field_type_item += field_type_item_content
# Format definition list item for the range
range_node = nodes.definition_list_item()
range_node += nodes.term(text='Range')
range_node_def = nodes.definition()
range_node_def += nodes.paragraph(text=field.rangeString)
range_node += range_node_def
# Definition list for key-value metadata
dl = nodes.definition_list()
dl += create_default_item_node(field, state)
dl += field_type_item
dl += range_node
# Doc for this field, parsed as rst
desc_node = create_description_node(field, state)
# Title for configuration field
title = create_title_node(field_name, field, field_id, state, lineno)
return [title, dl, desc_node] | python | def format_rangefield_nodes(field_name, field, field_id, state, lineno):
"""Create a section node that documents a RangeField config field.
Parameters
----------
field_name : `str`
Name of the configuration field (the attribute name of on the config
class).
field : ``lsst.pex.config.RangeField``
A configuration field.
field_id : `str`
Unique identifier for this field. This is used as the id and name of
the section node. with a -section suffix
state : ``docutils.statemachine.State``
Usually the directive's ``state`` attribute.
lineno (`int`)
Usually the directive's ``lineno`` attribute.
Returns
-------
``docutils.nodes.section``
Section containing documentation nodes for the RangeField.
"""
# Field type
field_type_item = nodes.definition_list_item()
field_type_item.append(nodes.term(text="Field type"))
field_type_item_content = nodes.definition()
field_type_item_content_p = nodes.paragraph()
field_type_item_content_p += make_python_xref_nodes_for_type(
field.dtype,
state,
hide_namespace=False)[0].children[0]
field_type_item_content_p += nodes.Text(' ', ' ')
field_type_item_content_p += make_python_xref_nodes_for_type(
type(field),
state,
hide_namespace=True)[0].children[0]
if field.optional:
field_type_item_content_p += nodes.Text(' (optional)', ' (optional)')
field_type_item_content += field_type_item_content_p
field_type_item += field_type_item_content
# Format definition list item for the range
range_node = nodes.definition_list_item()
range_node += nodes.term(text='Range')
range_node_def = nodes.definition()
range_node_def += nodes.paragraph(text=field.rangeString)
range_node += range_node_def
# Definition list for key-value metadata
dl = nodes.definition_list()
dl += create_default_item_node(field, state)
dl += field_type_item
dl += range_node
# Doc for this field, parsed as rst
desc_node = create_description_node(field, state)
# Title for configuration field
title = create_title_node(field_name, field, field_id, state, lineno)
return [title, dl, desc_node] | [
"def",
"format_rangefield_nodes",
"(",
"field_name",
",",
"field",
",",
"field_id",
",",
"state",
",",
"lineno",
")",
":",
"# Field type",
"field_type_item",
"=",
"nodes",
".",
"definition_list_item",
"(",
")",
"field_type_item",
".",
"append",
"(",
"nodes",
".",
"term",
"(",
"text",
"=",
"\"Field type\"",
")",
")",
"field_type_item_content",
"=",
"nodes",
".",
"definition",
"(",
")",
"field_type_item_content_p",
"=",
"nodes",
".",
"paragraph",
"(",
")",
"field_type_item_content_p",
"+=",
"make_python_xref_nodes_for_type",
"(",
"field",
".",
"dtype",
",",
"state",
",",
"hide_namespace",
"=",
"False",
")",
"[",
"0",
"]",
".",
"children",
"[",
"0",
"]",
"field_type_item_content_p",
"+=",
"nodes",
".",
"Text",
"(",
"' '",
",",
"' '",
")",
"field_type_item_content_p",
"+=",
"make_python_xref_nodes_for_type",
"(",
"type",
"(",
"field",
")",
",",
"state",
",",
"hide_namespace",
"=",
"True",
")",
"[",
"0",
"]",
".",
"children",
"[",
"0",
"]",
"if",
"field",
".",
"optional",
":",
"field_type_item_content_p",
"+=",
"nodes",
".",
"Text",
"(",
"' (optional)'",
",",
"' (optional)'",
")",
"field_type_item_content",
"+=",
"field_type_item_content_p",
"field_type_item",
"+=",
"field_type_item_content",
"# Format definition list item for the range",
"range_node",
"=",
"nodes",
".",
"definition_list_item",
"(",
")",
"range_node",
"+=",
"nodes",
".",
"term",
"(",
"text",
"=",
"'Range'",
")",
"range_node_def",
"=",
"nodes",
".",
"definition",
"(",
")",
"range_node_def",
"+=",
"nodes",
".",
"paragraph",
"(",
"text",
"=",
"field",
".",
"rangeString",
")",
"range_node",
"+=",
"range_node_def",
"# Definition list for key-value metadata",
"dl",
"=",
"nodes",
".",
"definition_list",
"(",
")",
"dl",
"+=",
"create_default_item_node",
"(",
"field",
",",
"state",
")",
"dl",
"+=",
"field_type_item",
"dl",
"+=",
"range_node",
"# Doc for this field, parsed as rst",
"desc_node",
"=",
"create_description_node",
"(",
"field",
",",
"state",
")",
"# Title for configuration field",
"title",
"=",
"create_title_node",
"(",
"field_name",
",",
"field",
",",
"field_id",
",",
"state",
",",
"lineno",
")",
"return",
"[",
"title",
",",
"dl",
",",
"desc_node",
"]"
]
| Create a section node that documents a RangeField config field.
Parameters
----------
field_name : `str`
Name of the configuration field (the attribute name of on the config
class).
field : ``lsst.pex.config.RangeField``
A configuration field.
field_id : `str`
Unique identifier for this field. This is used as the id and name of
the section node. with a -section suffix
state : ``docutils.statemachine.State``
Usually the directive's ``state`` attribute.
lineno (`int`)
Usually the directive's ``lineno`` attribute.
Returns
-------
``docutils.nodes.section``
Section containing documentation nodes for the RangeField. | [
"Create",
"a",
"section",
"node",
"that",
"documents",
"a",
"RangeField",
"config",
"field",
"."
]
| 75f02901a80042b28d074df1cc1dca32eb8e38c8 | https://github.com/lsst-sqre/documenteer/blob/75f02901a80042b28d074df1cc1dca32eb8e38c8/documenteer/sphinxext/lssttasks/configfieldlists.py#L609-L670 | train |
lsst-sqre/documenteer | documenteer/sphinxext/lssttasks/configfieldlists.py | format_dictfield_nodes | def format_dictfield_nodes(field_name, field, field_id, state, lineno):
"""Create a section node that documents a DictField config field.
Parameters
----------
field_name : `str`
Name of the configuration field (the attribute name of on the config
class).
field : ``lsst.pex.config.DictField``
A configuration field.
field_id : `str`
Unique identifier for this field. This is used as the id and name of
the section node. with a -section suffix
state : ``docutils.statemachine.State``
Usually the directive's ``state`` attribute.
lineno (`int`)
Usually the directive's ``lineno`` attribute.
Returns
-------
``docutils.nodes.section``
Section containing documentation nodes for the DictField.
"""
# Custom value type field for definition list
valuetype_item = nodes.definition_list_item()
valuetype_item = nodes.term(text='Value type')
valuetype_def = nodes.definition()
valuetype_def += make_python_xref_nodes_for_type(
field.itemtype,
state,
hide_namespace=False)
valuetype_item += valuetype_def
# Definition list for key-value metadata
dl = nodes.definition_list()
dl += create_default_item_node(field, state)
dl += create_field_type_item_node(field, state)
dl += create_keytype_item_node(field, state)
dl += valuetype_item
# Doc for this field, parsed as rst
desc_node = create_description_node(field, state)
# Title for configuration field
title = create_title_node(field_name, field, field_id, state, lineno)
return [title, dl, desc_node] | python | def format_dictfield_nodes(field_name, field, field_id, state, lineno):
"""Create a section node that documents a DictField config field.
Parameters
----------
field_name : `str`
Name of the configuration field (the attribute name of on the config
class).
field : ``lsst.pex.config.DictField``
A configuration field.
field_id : `str`
Unique identifier for this field. This is used as the id and name of
the section node. with a -section suffix
state : ``docutils.statemachine.State``
Usually the directive's ``state`` attribute.
lineno (`int`)
Usually the directive's ``lineno`` attribute.
Returns
-------
``docutils.nodes.section``
Section containing documentation nodes for the DictField.
"""
# Custom value type field for definition list
valuetype_item = nodes.definition_list_item()
valuetype_item = nodes.term(text='Value type')
valuetype_def = nodes.definition()
valuetype_def += make_python_xref_nodes_for_type(
field.itemtype,
state,
hide_namespace=False)
valuetype_item += valuetype_def
# Definition list for key-value metadata
dl = nodes.definition_list()
dl += create_default_item_node(field, state)
dl += create_field_type_item_node(field, state)
dl += create_keytype_item_node(field, state)
dl += valuetype_item
# Doc for this field, parsed as rst
desc_node = create_description_node(field, state)
# Title for configuration field
title = create_title_node(field_name, field, field_id, state, lineno)
return [title, dl, desc_node] | [
"def",
"format_dictfield_nodes",
"(",
"field_name",
",",
"field",
",",
"field_id",
",",
"state",
",",
"lineno",
")",
":",
"# Custom value type field for definition list",
"valuetype_item",
"=",
"nodes",
".",
"definition_list_item",
"(",
")",
"valuetype_item",
"=",
"nodes",
".",
"term",
"(",
"text",
"=",
"'Value type'",
")",
"valuetype_def",
"=",
"nodes",
".",
"definition",
"(",
")",
"valuetype_def",
"+=",
"make_python_xref_nodes_for_type",
"(",
"field",
".",
"itemtype",
",",
"state",
",",
"hide_namespace",
"=",
"False",
")",
"valuetype_item",
"+=",
"valuetype_def",
"# Definition list for key-value metadata",
"dl",
"=",
"nodes",
".",
"definition_list",
"(",
")",
"dl",
"+=",
"create_default_item_node",
"(",
"field",
",",
"state",
")",
"dl",
"+=",
"create_field_type_item_node",
"(",
"field",
",",
"state",
")",
"dl",
"+=",
"create_keytype_item_node",
"(",
"field",
",",
"state",
")",
"dl",
"+=",
"valuetype_item",
"# Doc for this field, parsed as rst",
"desc_node",
"=",
"create_description_node",
"(",
"field",
",",
"state",
")",
"# Title for configuration field",
"title",
"=",
"create_title_node",
"(",
"field_name",
",",
"field",
",",
"field_id",
",",
"state",
",",
"lineno",
")",
"return",
"[",
"title",
",",
"dl",
",",
"desc_node",
"]"
]
| Create a section node that documents a DictField config field.
Parameters
----------
field_name : `str`
Name of the configuration field (the attribute name of on the config
class).
field : ``lsst.pex.config.DictField``
A configuration field.
field_id : `str`
Unique identifier for this field. This is used as the id and name of
the section node. with a -section suffix
state : ``docutils.statemachine.State``
Usually the directive's ``state`` attribute.
lineno (`int`)
Usually the directive's ``lineno`` attribute.
Returns
-------
``docutils.nodes.section``
Section containing documentation nodes for the DictField. | [
"Create",
"a",
"section",
"node",
"that",
"documents",
"a",
"DictField",
"config",
"field",
"."
]
| 75f02901a80042b28d074df1cc1dca32eb8e38c8 | https://github.com/lsst-sqre/documenteer/blob/75f02901a80042b28d074df1cc1dca32eb8e38c8/documenteer/sphinxext/lssttasks/configfieldlists.py#L674-L720 | train |
lsst-sqre/documenteer | documenteer/sphinxext/lssttasks/configfieldlists.py | format_configfield_nodes | def format_configfield_nodes(field_name, field, field_id, state, lineno):
"""Create a section node that documents a ConfigField config field.
Parameters
----------
field_name : `str`
Name of the configuration field (the attribute name of on the config
class).
field : ``lsst.pex.config.ConfigField``
A configuration field.
field_id : `str`
Unique identifier for this field. This is used as the id and name of
the section node. with a -section suffix
state : ``docutils.statemachine.State``
Usually the directive's ``state`` attribute.
lineno (`int`)
Usually the directive's ``lineno`` attribute.
Returns
-------
``docutils.nodes.section``
Section containing documentation nodes for the ConfigField.
"""
# Default data type node
dtype_node = nodes.definition_list_item()
dtype_node = nodes.term(text='Data type')
dtype_def = nodes.definition()
dtype_def_para = nodes.paragraph()
name = '.'.join((field.dtype.__module__, field.dtype.__name__))
dtype_def_para += pending_config_xref(rawsource=name)
dtype_def += dtype_def_para
dtype_node += dtype_def
# Definition list for key-value metadata
dl = nodes.definition_list()
dl += dtype_node
dl += create_field_type_item_node(field, state)
# Doc for this field, parsed as rst
desc_node = create_description_node(field, state)
# Title for configuration field
title = create_title_node(field_name, field, field_id, state, lineno)
return [title, dl, desc_node] | python | def format_configfield_nodes(field_name, field, field_id, state, lineno):
"""Create a section node that documents a ConfigField config field.
Parameters
----------
field_name : `str`
Name of the configuration field (the attribute name of on the config
class).
field : ``lsst.pex.config.ConfigField``
A configuration field.
field_id : `str`
Unique identifier for this field. This is used as the id and name of
the section node. with a -section suffix
state : ``docutils.statemachine.State``
Usually the directive's ``state`` attribute.
lineno (`int`)
Usually the directive's ``lineno`` attribute.
Returns
-------
``docutils.nodes.section``
Section containing documentation nodes for the ConfigField.
"""
# Default data type node
dtype_node = nodes.definition_list_item()
dtype_node = nodes.term(text='Data type')
dtype_def = nodes.definition()
dtype_def_para = nodes.paragraph()
name = '.'.join((field.dtype.__module__, field.dtype.__name__))
dtype_def_para += pending_config_xref(rawsource=name)
dtype_def += dtype_def_para
dtype_node += dtype_def
# Definition list for key-value metadata
dl = nodes.definition_list()
dl += dtype_node
dl += create_field_type_item_node(field, state)
# Doc for this field, parsed as rst
desc_node = create_description_node(field, state)
# Title for configuration field
title = create_title_node(field_name, field, field_id, state, lineno)
return [title, dl, desc_node] | [
"def",
"format_configfield_nodes",
"(",
"field_name",
",",
"field",
",",
"field_id",
",",
"state",
",",
"lineno",
")",
":",
"# Default data type node",
"dtype_node",
"=",
"nodes",
".",
"definition_list_item",
"(",
")",
"dtype_node",
"=",
"nodes",
".",
"term",
"(",
"text",
"=",
"'Data type'",
")",
"dtype_def",
"=",
"nodes",
".",
"definition",
"(",
")",
"dtype_def_para",
"=",
"nodes",
".",
"paragraph",
"(",
")",
"name",
"=",
"'.'",
".",
"join",
"(",
"(",
"field",
".",
"dtype",
".",
"__module__",
",",
"field",
".",
"dtype",
".",
"__name__",
")",
")",
"dtype_def_para",
"+=",
"pending_config_xref",
"(",
"rawsource",
"=",
"name",
")",
"dtype_def",
"+=",
"dtype_def_para",
"dtype_node",
"+=",
"dtype_def",
"# Definition list for key-value metadata",
"dl",
"=",
"nodes",
".",
"definition_list",
"(",
")",
"dl",
"+=",
"dtype_node",
"dl",
"+=",
"create_field_type_item_node",
"(",
"field",
",",
"state",
")",
"# Doc for this field, parsed as rst",
"desc_node",
"=",
"create_description_node",
"(",
"field",
",",
"state",
")",
"# Title for configuration field",
"title",
"=",
"create_title_node",
"(",
"field_name",
",",
"field",
",",
"field_id",
",",
"state",
",",
"lineno",
")",
"return",
"[",
"title",
",",
"dl",
",",
"desc_node",
"]"
]
| Create a section node that documents a ConfigField config field.
Parameters
----------
field_name : `str`
Name of the configuration field (the attribute name of on the config
class).
field : ``lsst.pex.config.ConfigField``
A configuration field.
field_id : `str`
Unique identifier for this field. This is used as the id and name of
the section node. with a -section suffix
state : ``docutils.statemachine.State``
Usually the directive's ``state`` attribute.
lineno (`int`)
Usually the directive's ``lineno`` attribute.
Returns
-------
``docutils.nodes.section``
Section containing documentation nodes for the ConfigField. | [
"Create",
"a",
"section",
"node",
"that",
"documents",
"a",
"ConfigField",
"config",
"field",
"."
]
| 75f02901a80042b28d074df1cc1dca32eb8e38c8 | https://github.com/lsst-sqre/documenteer/blob/75f02901a80042b28d074df1cc1dca32eb8e38c8/documenteer/sphinxext/lssttasks/configfieldlists.py#L724-L768 | train |
lsst-sqre/documenteer | documenteer/sphinxext/lssttasks/configfieldlists.py | format_configchoicefield_nodes | def format_configchoicefield_nodes(field_name, field, field_id, state, lineno):
"""Create a section node that documents a ConfigChoiceField config field.
Parameters
----------
field_name : `str`
Name of the configuration field (the attribute name of on the config
class).
field : ``lsst.pex.config.ConfigChoiceField``
A configuration field.
field_id : `str`
Unique identifier for this field. This is used as the id and name of
the section node. with a -section suffix
state : ``docutils.statemachine.State``
Usually the directive's ``state`` attribute.
lineno (`int`)
Usually the directive's ``lineno`` attribute.
Returns
-------
``docutils.nodes.section``
Section containing documentation nodes for the ConfigChoiceField.
"""
# Create a definition list for the choices
choice_dl = nodes.definition_list()
for choice_value, choice_class in field.typemap.items():
item = nodes.definition_list_item()
item_term = nodes.term()
item_term += nodes.literal(text=repr(choice_value))
item += item_term
item_definition = nodes.definition()
def_para = nodes.paragraph()
name = '.'.join((choice_class.__module__, choice_class.__name__))
def_para += pending_config_xref(rawsource=name)
item_definition += def_para
item += item_definition
choice_dl.append(item)
choices_node = nodes.definition_list_item()
choices_node.append(nodes.term(text='Choices'))
choices_definition = nodes.definition()
choices_definition.append(choice_dl)
choices_node.append(choices_definition)
# Field type
field_type_item = nodes.definition_list_item()
field_type_item.append(nodes.term(text="Field type"))
field_type_item_content = nodes.definition()
field_type_item_content_p = nodes.paragraph()
if field.multi:
multi_text = "Multi-selection "
else:
multi_text = "Single-selection "
field_type_item_content_p += nodes.Text(multi_text, multi_text)
field_type_item_content_p += make_python_xref_nodes_for_type(
type(field),
state,
hide_namespace=True)[0].children[0]
if field.optional:
field_type_item_content_p += nodes.Text(' (optional)', ' (optional)')
field_type_item_content += field_type_item_content_p
field_type_item += field_type_item_content
dl = nodes.definition_list()
dl += create_default_item_node(field, state)
dl += field_type_item
dl += choices_node
# Doc for this field, parsed as rst
desc_node = create_description_node(field, state)
# Title for configuration field
title = create_title_node(field_name, field, field_id, state, lineno)
return [title, dl, desc_node] | python | def format_configchoicefield_nodes(field_name, field, field_id, state, lineno):
"""Create a section node that documents a ConfigChoiceField config field.
Parameters
----------
field_name : `str`
Name of the configuration field (the attribute name of on the config
class).
field : ``lsst.pex.config.ConfigChoiceField``
A configuration field.
field_id : `str`
Unique identifier for this field. This is used as the id and name of
the section node. with a -section suffix
state : ``docutils.statemachine.State``
Usually the directive's ``state`` attribute.
lineno (`int`)
Usually the directive's ``lineno`` attribute.
Returns
-------
``docutils.nodes.section``
Section containing documentation nodes for the ConfigChoiceField.
"""
# Create a definition list for the choices
choice_dl = nodes.definition_list()
for choice_value, choice_class in field.typemap.items():
item = nodes.definition_list_item()
item_term = nodes.term()
item_term += nodes.literal(text=repr(choice_value))
item += item_term
item_definition = nodes.definition()
def_para = nodes.paragraph()
name = '.'.join((choice_class.__module__, choice_class.__name__))
def_para += pending_config_xref(rawsource=name)
item_definition += def_para
item += item_definition
choice_dl.append(item)
choices_node = nodes.definition_list_item()
choices_node.append(nodes.term(text='Choices'))
choices_definition = nodes.definition()
choices_definition.append(choice_dl)
choices_node.append(choices_definition)
# Field type
field_type_item = nodes.definition_list_item()
field_type_item.append(nodes.term(text="Field type"))
field_type_item_content = nodes.definition()
field_type_item_content_p = nodes.paragraph()
if field.multi:
multi_text = "Multi-selection "
else:
multi_text = "Single-selection "
field_type_item_content_p += nodes.Text(multi_text, multi_text)
field_type_item_content_p += make_python_xref_nodes_for_type(
type(field),
state,
hide_namespace=True)[0].children[0]
if field.optional:
field_type_item_content_p += nodes.Text(' (optional)', ' (optional)')
field_type_item_content += field_type_item_content_p
field_type_item += field_type_item_content
dl = nodes.definition_list()
dl += create_default_item_node(field, state)
dl += field_type_item
dl += choices_node
# Doc for this field, parsed as rst
desc_node = create_description_node(field, state)
# Title for configuration field
title = create_title_node(field_name, field, field_id, state, lineno)
return [title, dl, desc_node] | [
"def",
"format_configchoicefield_nodes",
"(",
"field_name",
",",
"field",
",",
"field_id",
",",
"state",
",",
"lineno",
")",
":",
"# Create a definition list for the choices",
"choice_dl",
"=",
"nodes",
".",
"definition_list",
"(",
")",
"for",
"choice_value",
",",
"choice_class",
"in",
"field",
".",
"typemap",
".",
"items",
"(",
")",
":",
"item",
"=",
"nodes",
".",
"definition_list_item",
"(",
")",
"item_term",
"=",
"nodes",
".",
"term",
"(",
")",
"item_term",
"+=",
"nodes",
".",
"literal",
"(",
"text",
"=",
"repr",
"(",
"choice_value",
")",
")",
"item",
"+=",
"item_term",
"item_definition",
"=",
"nodes",
".",
"definition",
"(",
")",
"def_para",
"=",
"nodes",
".",
"paragraph",
"(",
")",
"name",
"=",
"'.'",
".",
"join",
"(",
"(",
"choice_class",
".",
"__module__",
",",
"choice_class",
".",
"__name__",
")",
")",
"def_para",
"+=",
"pending_config_xref",
"(",
"rawsource",
"=",
"name",
")",
"item_definition",
"+=",
"def_para",
"item",
"+=",
"item_definition",
"choice_dl",
".",
"append",
"(",
"item",
")",
"choices_node",
"=",
"nodes",
".",
"definition_list_item",
"(",
")",
"choices_node",
".",
"append",
"(",
"nodes",
".",
"term",
"(",
"text",
"=",
"'Choices'",
")",
")",
"choices_definition",
"=",
"nodes",
".",
"definition",
"(",
")",
"choices_definition",
".",
"append",
"(",
"choice_dl",
")",
"choices_node",
".",
"append",
"(",
"choices_definition",
")",
"# Field type",
"field_type_item",
"=",
"nodes",
".",
"definition_list_item",
"(",
")",
"field_type_item",
".",
"append",
"(",
"nodes",
".",
"term",
"(",
"text",
"=",
"\"Field type\"",
")",
")",
"field_type_item_content",
"=",
"nodes",
".",
"definition",
"(",
")",
"field_type_item_content_p",
"=",
"nodes",
".",
"paragraph",
"(",
")",
"if",
"field",
".",
"multi",
":",
"multi_text",
"=",
"\"Multi-selection \"",
"else",
":",
"multi_text",
"=",
"\"Single-selection \"",
"field_type_item_content_p",
"+=",
"nodes",
".",
"Text",
"(",
"multi_text",
",",
"multi_text",
")",
"field_type_item_content_p",
"+=",
"make_python_xref_nodes_for_type",
"(",
"type",
"(",
"field",
")",
",",
"state",
",",
"hide_namespace",
"=",
"True",
")",
"[",
"0",
"]",
".",
"children",
"[",
"0",
"]",
"if",
"field",
".",
"optional",
":",
"field_type_item_content_p",
"+=",
"nodes",
".",
"Text",
"(",
"' (optional)'",
",",
"' (optional)'",
")",
"field_type_item_content",
"+=",
"field_type_item_content_p",
"field_type_item",
"+=",
"field_type_item_content",
"dl",
"=",
"nodes",
".",
"definition_list",
"(",
")",
"dl",
"+=",
"create_default_item_node",
"(",
"field",
",",
"state",
")",
"dl",
"+=",
"field_type_item",
"dl",
"+=",
"choices_node",
"# Doc for this field, parsed as rst",
"desc_node",
"=",
"create_description_node",
"(",
"field",
",",
"state",
")",
"# Title for configuration field",
"title",
"=",
"create_title_node",
"(",
"field_name",
",",
"field",
",",
"field_id",
",",
"state",
",",
"lineno",
")",
"return",
"[",
"title",
",",
"dl",
",",
"desc_node",
"]"
]
| Create a section node that documents a ConfigChoiceField config field.
Parameters
----------
field_name : `str`
Name of the configuration field (the attribute name of on the config
class).
field : ``lsst.pex.config.ConfigChoiceField``
A configuration field.
field_id : `str`
Unique identifier for this field. This is used as the id and name of
the section node. with a -section suffix
state : ``docutils.statemachine.State``
Usually the directive's ``state`` attribute.
lineno (`int`)
Usually the directive's ``lineno`` attribute.
Returns
-------
``docutils.nodes.section``
Section containing documentation nodes for the ConfigChoiceField. | [
"Create",
"a",
"section",
"node",
"that",
"documents",
"a",
"ConfigChoiceField",
"config",
"field",
"."
]
| 75f02901a80042b28d074df1cc1dca32eb8e38c8 | https://github.com/lsst-sqre/documenteer/blob/75f02901a80042b28d074df1cc1dca32eb8e38c8/documenteer/sphinxext/lssttasks/configfieldlists.py#L772-L846 | train |
lsst-sqre/documenteer | documenteer/sphinxext/lssttasks/configfieldlists.py | format_configdictfield_nodes | def format_configdictfield_nodes(field_name, field, field_id, state, lineno):
"""Create a section node that documents a ConfigDictField config field.
Parameters
----------
field_name : `str`
Name of the configuration field (the attribute name of on the config
class).
field : ``lsst.pex.config.ConfigDictField``
A configuration field.
field_id : `str`
Unique identifier for this field. This is used as the id and name of
the section node. with a -section suffix
state : ``docutils.statemachine.State``
Usually the directive's ``state`` attribute.
lineno (`int`)
Usually the directive's ``lineno`` attribute.
Returns
-------
``docutils.nodes.section``
Section containing documentation nodes for the ConfigDictField.
"""
# Valuetype links to a Config task topic
value_item = nodes.definition_list_item()
value_item += nodes.term(text="Value type")
value_item_def = nodes.definition()
value_item_def_para = nodes.paragraph()
name = '.'.join((field.itemtype.__module__, field.itemtype.__name__))
value_item_def_para += pending_config_xref(rawsource=name)
value_item_def += value_item_def_para
value_item += value_item_def
dl = nodes.definition_list()
dl += create_default_item_node(field, state)
dl += create_field_type_item_node(field, state)
dl += create_keytype_item_node(field, state)
dl += value_item
# Doc for this field, parsed as rst
desc_node = create_description_node(field, state)
# Title for configuration field
title = create_title_node(field_name, field, field_id, state, lineno)
return [title, dl, desc_node] | python | def format_configdictfield_nodes(field_name, field, field_id, state, lineno):
"""Create a section node that documents a ConfigDictField config field.
Parameters
----------
field_name : `str`
Name of the configuration field (the attribute name of on the config
class).
field : ``lsst.pex.config.ConfigDictField``
A configuration field.
field_id : `str`
Unique identifier for this field. This is used as the id and name of
the section node. with a -section suffix
state : ``docutils.statemachine.State``
Usually the directive's ``state`` attribute.
lineno (`int`)
Usually the directive's ``lineno`` attribute.
Returns
-------
``docutils.nodes.section``
Section containing documentation nodes for the ConfigDictField.
"""
# Valuetype links to a Config task topic
value_item = nodes.definition_list_item()
value_item += nodes.term(text="Value type")
value_item_def = nodes.definition()
value_item_def_para = nodes.paragraph()
name = '.'.join((field.itemtype.__module__, field.itemtype.__name__))
value_item_def_para += pending_config_xref(rawsource=name)
value_item_def += value_item_def_para
value_item += value_item_def
dl = nodes.definition_list()
dl += create_default_item_node(field, state)
dl += create_field_type_item_node(field, state)
dl += create_keytype_item_node(field, state)
dl += value_item
# Doc for this field, parsed as rst
desc_node = create_description_node(field, state)
# Title for configuration field
title = create_title_node(field_name, field, field_id, state, lineno)
return [title, dl, desc_node] | [
"def",
"format_configdictfield_nodes",
"(",
"field_name",
",",
"field",
",",
"field_id",
",",
"state",
",",
"lineno",
")",
":",
"# Valuetype links to a Config task topic",
"value_item",
"=",
"nodes",
".",
"definition_list_item",
"(",
")",
"value_item",
"+=",
"nodes",
".",
"term",
"(",
"text",
"=",
"\"Value type\"",
")",
"value_item_def",
"=",
"nodes",
".",
"definition",
"(",
")",
"value_item_def_para",
"=",
"nodes",
".",
"paragraph",
"(",
")",
"name",
"=",
"'.'",
".",
"join",
"(",
"(",
"field",
".",
"itemtype",
".",
"__module__",
",",
"field",
".",
"itemtype",
".",
"__name__",
")",
")",
"value_item_def_para",
"+=",
"pending_config_xref",
"(",
"rawsource",
"=",
"name",
")",
"value_item_def",
"+=",
"value_item_def_para",
"value_item",
"+=",
"value_item_def",
"dl",
"=",
"nodes",
".",
"definition_list",
"(",
")",
"dl",
"+=",
"create_default_item_node",
"(",
"field",
",",
"state",
")",
"dl",
"+=",
"create_field_type_item_node",
"(",
"field",
",",
"state",
")",
"dl",
"+=",
"create_keytype_item_node",
"(",
"field",
",",
"state",
")",
"dl",
"+=",
"value_item",
"# Doc for this field, parsed as rst",
"desc_node",
"=",
"create_description_node",
"(",
"field",
",",
"state",
")",
"# Title for configuration field",
"title",
"=",
"create_title_node",
"(",
"field_name",
",",
"field",
",",
"field_id",
",",
"state",
",",
"lineno",
")",
"return",
"[",
"title",
",",
"dl",
",",
"desc_node",
"]"
]
| Create a section node that documents a ConfigDictField config field.
Parameters
----------
field_name : `str`
Name of the configuration field (the attribute name of on the config
class).
field : ``lsst.pex.config.ConfigDictField``
A configuration field.
field_id : `str`
Unique identifier for this field. This is used as the id and name of
the section node. with a -section suffix
state : ``docutils.statemachine.State``
Usually the directive's ``state`` attribute.
lineno (`int`)
Usually the directive's ``lineno`` attribute.
Returns
-------
``docutils.nodes.section``
Section containing documentation nodes for the ConfigDictField. | [
"Create",
"a",
"section",
"node",
"that",
"documents",
"a",
"ConfigDictField",
"config",
"field",
"."
]
| 75f02901a80042b28d074df1cc1dca32eb8e38c8 | https://github.com/lsst-sqre/documenteer/blob/75f02901a80042b28d074df1cc1dca32eb8e38c8/documenteer/sphinxext/lssttasks/configfieldlists.py#L850-L895 | train |
lsst-sqre/documenteer | documenteer/sphinxext/lssttasks/configfieldlists.py | format_registryfield_nodes | def format_registryfield_nodes(field_name, field, field_id, state, lineno):
"""Create a section node that documents a RegistryField config field.
Parameters
----------
field_name : `str`
Name of the configuration field (the attribute name of on the config
class).
field : ``lsst.pex.config.RegistryField``
A configuration field.
field_id : `str`
Unique identifier for this field. This is used as the id and name of
the section node. with a -section suffix
state : ``docutils.statemachine.State``
Usually the directive's ``state`` attribute.
lineno (`int`)
Usually the directive's ``lineno`` attribute.
Returns
-------
``docutils.nodes.section``
Section containing documentation nodes for the RegistryField.
"""
from lsst.pex.config.registry import ConfigurableWrapper
# Create a definition list for the choices
# This iteration is over field.registry.items(), not field.items(), so
# that the directive shows the configurables, not their ConfigClasses.
choice_dl = nodes.definition_list()
for choice_value, choice_class in field.registry.items():
# Introspect the class name from item in the registry. This is harder
# than it should be. Most registry items seem to fall in the first
# category. Some are ConfigurableWrapper types that expose the
# underlying task class through the _target attribute.
if hasattr(choice_class, '__module__') \
and hasattr(choice_class, '__name__'):
name = '.'.join((choice_class.__module__, choice_class.__name__))
elif isinstance(choice_class, ConfigurableWrapper):
name = '.'.join((choice_class._target.__class__.__module__,
choice_class._target.__class__.__name__))
else:
name = '.'.join((choice_class.__class__.__module__,
choice_class.__class__.__name__))
item = nodes.definition_list_item()
item_term = nodes.term()
item_term += nodes.literal(text=repr(choice_value))
item += item_term
item_definition = nodes.definition()
def_para = nodes.paragraph()
def_para += pending_task_xref(rawsource=name)
item_definition += def_para
item += item_definition
choice_dl.append(item)
choices_node = nodes.definition_list_item()
choices_node.append(nodes.term(text='Choices'))
choices_definition = nodes.definition()
choices_definition.append(choice_dl)
choices_node.append(choices_definition)
# Field type
field_type_item = nodes.definition_list_item()
field_type_item.append(nodes.term(text="Field type"))
field_type_item_content = nodes.definition()
field_type_item_content_p = nodes.paragraph()
if field.multi:
multi_text = "Multi-selection "
else:
multi_text = "Single-selection "
field_type_item_content_p += nodes.Text(multi_text, multi_text)
field_type_item_content_p += make_python_xref_nodes_for_type(
type(field),
state,
hide_namespace=True)[0].children[0]
if field.optional:
field_type_item_content_p += nodes.Text(' (optional)', ' (optional)')
field_type_item_content += field_type_item_content_p
field_type_item += field_type_item_content
dl = nodes.definition_list()
dl += create_default_item_node(field, state)
dl += field_type_item
dl += choices_node
# Doc for this field, parsed as rst
desc_node = create_description_node(field, state)
# Title for configuration field
title = create_title_node(field_name, field, field_id, state, lineno)
return [title, dl, desc_node] | python | def format_registryfield_nodes(field_name, field, field_id, state, lineno):
"""Create a section node that documents a RegistryField config field.
Parameters
----------
field_name : `str`
Name of the configuration field (the attribute name of on the config
class).
field : ``lsst.pex.config.RegistryField``
A configuration field.
field_id : `str`
Unique identifier for this field. This is used as the id and name of
the section node. with a -section suffix
state : ``docutils.statemachine.State``
Usually the directive's ``state`` attribute.
lineno (`int`)
Usually the directive's ``lineno`` attribute.
Returns
-------
``docutils.nodes.section``
Section containing documentation nodes for the RegistryField.
"""
from lsst.pex.config.registry import ConfigurableWrapper
# Create a definition list for the choices
# This iteration is over field.registry.items(), not field.items(), so
# that the directive shows the configurables, not their ConfigClasses.
choice_dl = nodes.definition_list()
for choice_value, choice_class in field.registry.items():
# Introspect the class name from item in the registry. This is harder
# than it should be. Most registry items seem to fall in the first
# category. Some are ConfigurableWrapper types that expose the
# underlying task class through the _target attribute.
if hasattr(choice_class, '__module__') \
and hasattr(choice_class, '__name__'):
name = '.'.join((choice_class.__module__, choice_class.__name__))
elif isinstance(choice_class, ConfigurableWrapper):
name = '.'.join((choice_class._target.__class__.__module__,
choice_class._target.__class__.__name__))
else:
name = '.'.join((choice_class.__class__.__module__,
choice_class.__class__.__name__))
item = nodes.definition_list_item()
item_term = nodes.term()
item_term += nodes.literal(text=repr(choice_value))
item += item_term
item_definition = nodes.definition()
def_para = nodes.paragraph()
def_para += pending_task_xref(rawsource=name)
item_definition += def_para
item += item_definition
choice_dl.append(item)
choices_node = nodes.definition_list_item()
choices_node.append(nodes.term(text='Choices'))
choices_definition = nodes.definition()
choices_definition.append(choice_dl)
choices_node.append(choices_definition)
# Field type
field_type_item = nodes.definition_list_item()
field_type_item.append(nodes.term(text="Field type"))
field_type_item_content = nodes.definition()
field_type_item_content_p = nodes.paragraph()
if field.multi:
multi_text = "Multi-selection "
else:
multi_text = "Single-selection "
field_type_item_content_p += nodes.Text(multi_text, multi_text)
field_type_item_content_p += make_python_xref_nodes_for_type(
type(field),
state,
hide_namespace=True)[0].children[0]
if field.optional:
field_type_item_content_p += nodes.Text(' (optional)', ' (optional)')
field_type_item_content += field_type_item_content_p
field_type_item += field_type_item_content
dl = nodes.definition_list()
dl += create_default_item_node(field, state)
dl += field_type_item
dl += choices_node
# Doc for this field, parsed as rst
desc_node = create_description_node(field, state)
# Title for configuration field
title = create_title_node(field_name, field, field_id, state, lineno)
return [title, dl, desc_node] | [
"def",
"format_registryfield_nodes",
"(",
"field_name",
",",
"field",
",",
"field_id",
",",
"state",
",",
"lineno",
")",
":",
"from",
"lsst",
".",
"pex",
".",
"config",
".",
"registry",
"import",
"ConfigurableWrapper",
"# Create a definition list for the choices",
"# This iteration is over field.registry.items(), not field.items(), so",
"# that the directive shows the configurables, not their ConfigClasses.",
"choice_dl",
"=",
"nodes",
".",
"definition_list",
"(",
")",
"for",
"choice_value",
",",
"choice_class",
"in",
"field",
".",
"registry",
".",
"items",
"(",
")",
":",
"# Introspect the class name from item in the registry. This is harder",
"# than it should be. Most registry items seem to fall in the first",
"# category. Some are ConfigurableWrapper types that expose the",
"# underlying task class through the _target attribute.",
"if",
"hasattr",
"(",
"choice_class",
",",
"'__module__'",
")",
"and",
"hasattr",
"(",
"choice_class",
",",
"'__name__'",
")",
":",
"name",
"=",
"'.'",
".",
"join",
"(",
"(",
"choice_class",
".",
"__module__",
",",
"choice_class",
".",
"__name__",
")",
")",
"elif",
"isinstance",
"(",
"choice_class",
",",
"ConfigurableWrapper",
")",
":",
"name",
"=",
"'.'",
".",
"join",
"(",
"(",
"choice_class",
".",
"_target",
".",
"__class__",
".",
"__module__",
",",
"choice_class",
".",
"_target",
".",
"__class__",
".",
"__name__",
")",
")",
"else",
":",
"name",
"=",
"'.'",
".",
"join",
"(",
"(",
"choice_class",
".",
"__class__",
".",
"__module__",
",",
"choice_class",
".",
"__class__",
".",
"__name__",
")",
")",
"item",
"=",
"nodes",
".",
"definition_list_item",
"(",
")",
"item_term",
"=",
"nodes",
".",
"term",
"(",
")",
"item_term",
"+=",
"nodes",
".",
"literal",
"(",
"text",
"=",
"repr",
"(",
"choice_value",
")",
")",
"item",
"+=",
"item_term",
"item_definition",
"=",
"nodes",
".",
"definition",
"(",
")",
"def_para",
"=",
"nodes",
".",
"paragraph",
"(",
")",
"def_para",
"+=",
"pending_task_xref",
"(",
"rawsource",
"=",
"name",
")",
"item_definition",
"+=",
"def_para",
"item",
"+=",
"item_definition",
"choice_dl",
".",
"append",
"(",
"item",
")",
"choices_node",
"=",
"nodes",
".",
"definition_list_item",
"(",
")",
"choices_node",
".",
"append",
"(",
"nodes",
".",
"term",
"(",
"text",
"=",
"'Choices'",
")",
")",
"choices_definition",
"=",
"nodes",
".",
"definition",
"(",
")",
"choices_definition",
".",
"append",
"(",
"choice_dl",
")",
"choices_node",
".",
"append",
"(",
"choices_definition",
")",
"# Field type",
"field_type_item",
"=",
"nodes",
".",
"definition_list_item",
"(",
")",
"field_type_item",
".",
"append",
"(",
"nodes",
".",
"term",
"(",
"text",
"=",
"\"Field type\"",
")",
")",
"field_type_item_content",
"=",
"nodes",
".",
"definition",
"(",
")",
"field_type_item_content_p",
"=",
"nodes",
".",
"paragraph",
"(",
")",
"if",
"field",
".",
"multi",
":",
"multi_text",
"=",
"\"Multi-selection \"",
"else",
":",
"multi_text",
"=",
"\"Single-selection \"",
"field_type_item_content_p",
"+=",
"nodes",
".",
"Text",
"(",
"multi_text",
",",
"multi_text",
")",
"field_type_item_content_p",
"+=",
"make_python_xref_nodes_for_type",
"(",
"type",
"(",
"field",
")",
",",
"state",
",",
"hide_namespace",
"=",
"True",
")",
"[",
"0",
"]",
".",
"children",
"[",
"0",
"]",
"if",
"field",
".",
"optional",
":",
"field_type_item_content_p",
"+=",
"nodes",
".",
"Text",
"(",
"' (optional)'",
",",
"' (optional)'",
")",
"field_type_item_content",
"+=",
"field_type_item_content_p",
"field_type_item",
"+=",
"field_type_item_content",
"dl",
"=",
"nodes",
".",
"definition_list",
"(",
")",
"dl",
"+=",
"create_default_item_node",
"(",
"field",
",",
"state",
")",
"dl",
"+=",
"field_type_item",
"dl",
"+=",
"choices_node",
"# Doc for this field, parsed as rst",
"desc_node",
"=",
"create_description_node",
"(",
"field",
",",
"state",
")",
"# Title for configuration field",
"title",
"=",
"create_title_node",
"(",
"field_name",
",",
"field",
",",
"field_id",
",",
"state",
",",
"lineno",
")",
"return",
"[",
"title",
",",
"dl",
",",
"desc_node",
"]"
]
| Create a section node that documents a RegistryField config field.
Parameters
----------
field_name : `str`
Name of the configuration field (the attribute name of on the config
class).
field : ``lsst.pex.config.RegistryField``
A configuration field.
field_id : `str`
Unique identifier for this field. This is used as the id and name of
the section node. with a -section suffix
state : ``docutils.statemachine.State``
Usually the directive's ``state`` attribute.
lineno (`int`)
Usually the directive's ``lineno`` attribute.
Returns
-------
``docutils.nodes.section``
Section containing documentation nodes for the RegistryField. | [
"Create",
"a",
"section",
"node",
"that",
"documents",
"a",
"RegistryField",
"config",
"field",
"."
]
| 75f02901a80042b28d074df1cc1dca32eb8e38c8 | https://github.com/lsst-sqre/documenteer/blob/75f02901a80042b28d074df1cc1dca32eb8e38c8/documenteer/sphinxext/lssttasks/configfieldlists.py#L899-L990 | train |
lsst-sqre/documenteer | documenteer/sphinxext/lssttasks/configfieldlists.py | create_field_type_item_node | def create_field_type_item_node(field, state):
"""Create a definition list item node that describes a field's type.
Parameters
----------
field : ``lsst.pex.config.Field``
A configuration field.
state : ``docutils.statemachine.State``
Usually the directive's ``state`` attribute.
Returns
-------
``docutils.nodes.definition_list_item``
Definition list item that describes a field's type.
"""
type_item = nodes.definition_list_item()
type_item.append(nodes.term(text="Field type"))
type_item_content = nodes.definition()
type_item_content_p = nodes.paragraph()
type_item_content_p += make_python_xref_nodes_for_type(
type(field),
state,
hide_namespace=True)[0].children
if field.optional:
type_item_content_p += nodes.Text(' (optional)', ' (optional)')
type_item_content += type_item_content_p
type_item += type_item_content
return type_item | python | def create_field_type_item_node(field, state):
"""Create a definition list item node that describes a field's type.
Parameters
----------
field : ``lsst.pex.config.Field``
A configuration field.
state : ``docutils.statemachine.State``
Usually the directive's ``state`` attribute.
Returns
-------
``docutils.nodes.definition_list_item``
Definition list item that describes a field's type.
"""
type_item = nodes.definition_list_item()
type_item.append(nodes.term(text="Field type"))
type_item_content = nodes.definition()
type_item_content_p = nodes.paragraph()
type_item_content_p += make_python_xref_nodes_for_type(
type(field),
state,
hide_namespace=True)[0].children
if field.optional:
type_item_content_p += nodes.Text(' (optional)', ' (optional)')
type_item_content += type_item_content_p
type_item += type_item_content
return type_item | [
"def",
"create_field_type_item_node",
"(",
"field",
",",
"state",
")",
":",
"type_item",
"=",
"nodes",
".",
"definition_list_item",
"(",
")",
"type_item",
".",
"append",
"(",
"nodes",
".",
"term",
"(",
"text",
"=",
"\"Field type\"",
")",
")",
"type_item_content",
"=",
"nodes",
".",
"definition",
"(",
")",
"type_item_content_p",
"=",
"nodes",
".",
"paragraph",
"(",
")",
"type_item_content_p",
"+=",
"make_python_xref_nodes_for_type",
"(",
"type",
"(",
"field",
")",
",",
"state",
",",
"hide_namespace",
"=",
"True",
")",
"[",
"0",
"]",
".",
"children",
"if",
"field",
".",
"optional",
":",
"type_item_content_p",
"+=",
"nodes",
".",
"Text",
"(",
"' (optional)'",
",",
"' (optional)'",
")",
"type_item_content",
"+=",
"type_item_content_p",
"type_item",
"+=",
"type_item_content",
"return",
"type_item"
]
| Create a definition list item node that describes a field's type.
Parameters
----------
field : ``lsst.pex.config.Field``
A configuration field.
state : ``docutils.statemachine.State``
Usually the directive's ``state`` attribute.
Returns
-------
``docutils.nodes.definition_list_item``
Definition list item that describes a field's type. | [
"Create",
"a",
"definition",
"list",
"item",
"node",
"that",
"describes",
"a",
"field",
"s",
"type",
"."
]
| 75f02901a80042b28d074df1cc1dca32eb8e38c8 | https://github.com/lsst-sqre/documenteer/blob/75f02901a80042b28d074df1cc1dca32eb8e38c8/documenteer/sphinxext/lssttasks/configfieldlists.py#L993-L1020 | train |
lsst-sqre/documenteer | documenteer/sphinxext/lssttasks/configfieldlists.py | create_default_item_node | def create_default_item_node(field, state):
"""Create a definition list item node that describes the default value
of a Field config.
Parameters
----------
field : ``lsst.pex.config.Field``
A configuration field.
state : ``docutils.statemachine.State``
Usually the directive's ``state`` attribute.
Returns
-------
``docutils.nodes.definition_list_item``
Definition list item that describes the default target of a
ConfigurableField config.
"""
default_item = nodes.definition_list_item()
default_item.append(nodes.term(text="Default"))
default_item_content = nodes.definition()
default_item_content.append(
nodes.literal(text=repr(field.default))
)
default_item.append(default_item_content)
return default_item | python | def create_default_item_node(field, state):
"""Create a definition list item node that describes the default value
of a Field config.
Parameters
----------
field : ``lsst.pex.config.Field``
A configuration field.
state : ``docutils.statemachine.State``
Usually the directive's ``state`` attribute.
Returns
-------
``docutils.nodes.definition_list_item``
Definition list item that describes the default target of a
ConfigurableField config.
"""
default_item = nodes.definition_list_item()
default_item.append(nodes.term(text="Default"))
default_item_content = nodes.definition()
default_item_content.append(
nodes.literal(text=repr(field.default))
)
default_item.append(default_item_content)
return default_item | [
"def",
"create_default_item_node",
"(",
"field",
",",
"state",
")",
":",
"default_item",
"=",
"nodes",
".",
"definition_list_item",
"(",
")",
"default_item",
".",
"append",
"(",
"nodes",
".",
"term",
"(",
"text",
"=",
"\"Default\"",
")",
")",
"default_item_content",
"=",
"nodes",
".",
"definition",
"(",
")",
"default_item_content",
".",
"append",
"(",
"nodes",
".",
"literal",
"(",
"text",
"=",
"repr",
"(",
"field",
".",
"default",
")",
")",
")",
"default_item",
".",
"append",
"(",
"default_item_content",
")",
"return",
"default_item"
]
| Create a definition list item node that describes the default value
of a Field config.
Parameters
----------
field : ``lsst.pex.config.Field``
A configuration field.
state : ``docutils.statemachine.State``
Usually the directive's ``state`` attribute.
Returns
-------
``docutils.nodes.definition_list_item``
Definition list item that describes the default target of a
ConfigurableField config. | [
"Create",
"a",
"definition",
"list",
"item",
"node",
"that",
"describes",
"the",
"default",
"value",
"of",
"a",
"Field",
"config",
"."
]
| 75f02901a80042b28d074df1cc1dca32eb8e38c8 | https://github.com/lsst-sqre/documenteer/blob/75f02901a80042b28d074df1cc1dca32eb8e38c8/documenteer/sphinxext/lssttasks/configfieldlists.py#L1023-L1047 | train |
lsst-sqre/documenteer | documenteer/sphinxext/lssttasks/configfieldlists.py | create_keytype_item_node | def create_keytype_item_node(field, state):
"""Create a definition list item node that describes the key type
of a dict-type config field.
Parameters
----------
field : ``lsst.pex.config.Field``
A ``lsst.pex.config.DictField`` or ``lsst.pex.config.DictConfigField``.
state : ``docutils.statemachine.State``
Usually the directive's ``state`` attribute.
Returns
-------
``docutils.nodes.definition_list_item``
Definition list item that describes the key type for the field.
"""
keytype_node = nodes.definition_list_item()
keytype_node = nodes.term(text='Key type')
keytype_def = nodes.definition()
keytype_def += make_python_xref_nodes_for_type(
field.keytype,
state,
hide_namespace=False)
keytype_node += keytype_def
return keytype_node | python | def create_keytype_item_node(field, state):
"""Create a definition list item node that describes the key type
of a dict-type config field.
Parameters
----------
field : ``lsst.pex.config.Field``
A ``lsst.pex.config.DictField`` or ``lsst.pex.config.DictConfigField``.
state : ``docutils.statemachine.State``
Usually the directive's ``state`` attribute.
Returns
-------
``docutils.nodes.definition_list_item``
Definition list item that describes the key type for the field.
"""
keytype_node = nodes.definition_list_item()
keytype_node = nodes.term(text='Key type')
keytype_def = nodes.definition()
keytype_def += make_python_xref_nodes_for_type(
field.keytype,
state,
hide_namespace=False)
keytype_node += keytype_def
return keytype_node | [
"def",
"create_keytype_item_node",
"(",
"field",
",",
"state",
")",
":",
"keytype_node",
"=",
"nodes",
".",
"definition_list_item",
"(",
")",
"keytype_node",
"=",
"nodes",
".",
"term",
"(",
"text",
"=",
"'Key type'",
")",
"keytype_def",
"=",
"nodes",
".",
"definition",
"(",
")",
"keytype_def",
"+=",
"make_python_xref_nodes_for_type",
"(",
"field",
".",
"keytype",
",",
"state",
",",
"hide_namespace",
"=",
"False",
")",
"keytype_node",
"+=",
"keytype_def",
"return",
"keytype_node"
]
| Create a definition list item node that describes the key type
of a dict-type config field.
Parameters
----------
field : ``lsst.pex.config.Field``
A ``lsst.pex.config.DictField`` or ``lsst.pex.config.DictConfigField``.
state : ``docutils.statemachine.State``
Usually the directive's ``state`` attribute.
Returns
-------
``docutils.nodes.definition_list_item``
Definition list item that describes the key type for the field. | [
"Create",
"a",
"definition",
"list",
"item",
"node",
"that",
"describes",
"the",
"key",
"type",
"of",
"a",
"dict",
"-",
"type",
"config",
"field",
"."
]
| 75f02901a80042b28d074df1cc1dca32eb8e38c8 | https://github.com/lsst-sqre/documenteer/blob/75f02901a80042b28d074df1cc1dca32eb8e38c8/documenteer/sphinxext/lssttasks/configfieldlists.py#L1050-L1074 | train |
lsst-sqre/documenteer | documenteer/sphinxext/lssttasks/configfieldlists.py | create_description_node | def create_description_node(field, state):
"""Creates docutils nodes for the Field's description, built from the
field's ``doc`` and ``optional`` attributes.
Parameters
----------
field : ``lsst.pex.config.Field``
A configuration field.
state : ``docutils.statemachine.State``
Usually the directive's ``state`` attribute.
Returns
-------
``docutils.nodes.section``
Section containing nodes for the description of the ``field``.
"""
doc_container_node = nodes.container()
doc_container_node += parse_rst_content(field.doc, state)
return doc_container_node | python | def create_description_node(field, state):
"""Creates docutils nodes for the Field's description, built from the
field's ``doc`` and ``optional`` attributes.
Parameters
----------
field : ``lsst.pex.config.Field``
A configuration field.
state : ``docutils.statemachine.State``
Usually the directive's ``state`` attribute.
Returns
-------
``docutils.nodes.section``
Section containing nodes for the description of the ``field``.
"""
doc_container_node = nodes.container()
doc_container_node += parse_rst_content(field.doc, state)
return doc_container_node | [
"def",
"create_description_node",
"(",
"field",
",",
"state",
")",
":",
"doc_container_node",
"=",
"nodes",
".",
"container",
"(",
")",
"doc_container_node",
"+=",
"parse_rst_content",
"(",
"field",
".",
"doc",
",",
"state",
")",
"return",
"doc_container_node"
]
| Creates docutils nodes for the Field's description, built from the
field's ``doc`` and ``optional`` attributes.
Parameters
----------
field : ``lsst.pex.config.Field``
A configuration field.
state : ``docutils.statemachine.State``
Usually the directive's ``state`` attribute.
Returns
-------
``docutils.nodes.section``
Section containing nodes for the description of the ``field``. | [
"Creates",
"docutils",
"nodes",
"for",
"the",
"Field",
"s",
"description",
"built",
"from",
"the",
"field",
"s",
"doc",
"and",
"optional",
"attributes",
"."
]
| 75f02901a80042b28d074df1cc1dca32eb8e38c8 | https://github.com/lsst-sqre/documenteer/blob/75f02901a80042b28d074df1cc1dca32eb8e38c8/documenteer/sphinxext/lssttasks/configfieldlists.py#L1077-L1096 | train |
lsst-sqre/documenteer | documenteer/sphinxext/lssttasks/configfieldlists.py | create_title_node | def create_title_node(field_name, field, field_id, state, lineno):
"""Create docutils nodes for the configuration field's title and
reference target node.
Parameters
----------
field : ``lsst.pex.config.Field``
A configuration field.
state : ``docutils.statemachine.State``
Usually the directive's ``state`` attribute.
Returns
-------
``docutils.nodes.title``
Title containing nodes for the title of the ``field`` and reference
target.
"""
# Reference target
env = state.document.settings.env
ref_target = create_configfield_ref_target_node(field_id, env, lineno)
# Title is the field's attribute name
title = nodes.title(text=field_name)
title += ref_target
return title | python | def create_title_node(field_name, field, field_id, state, lineno):
"""Create docutils nodes for the configuration field's title and
reference target node.
Parameters
----------
field : ``lsst.pex.config.Field``
A configuration field.
state : ``docutils.statemachine.State``
Usually the directive's ``state`` attribute.
Returns
-------
``docutils.nodes.title``
Title containing nodes for the title of the ``field`` and reference
target.
"""
# Reference target
env = state.document.settings.env
ref_target = create_configfield_ref_target_node(field_id, env, lineno)
# Title is the field's attribute name
title = nodes.title(text=field_name)
title += ref_target
return title | [
"def",
"create_title_node",
"(",
"field_name",
",",
"field",
",",
"field_id",
",",
"state",
",",
"lineno",
")",
":",
"# Reference target",
"env",
"=",
"state",
".",
"document",
".",
"settings",
".",
"env",
"ref_target",
"=",
"create_configfield_ref_target_node",
"(",
"field_id",
",",
"env",
",",
"lineno",
")",
"# Title is the field's attribute name",
"title",
"=",
"nodes",
".",
"title",
"(",
"text",
"=",
"field_name",
")",
"title",
"+=",
"ref_target",
"return",
"title"
]
| Create docutils nodes for the configuration field's title and
reference target node.
Parameters
----------
field : ``lsst.pex.config.Field``
A configuration field.
state : ``docutils.statemachine.State``
Usually the directive's ``state`` attribute.
Returns
-------
``docutils.nodes.title``
Title containing nodes for the title of the ``field`` and reference
target. | [
"Create",
"docutils",
"nodes",
"for",
"the",
"configuration",
"field",
"s",
"title",
"and",
"reference",
"target",
"node",
"."
]
| 75f02901a80042b28d074df1cc1dca32eb8e38c8 | https://github.com/lsst-sqre/documenteer/blob/75f02901a80042b28d074df1cc1dca32eb8e38c8/documenteer/sphinxext/lssttasks/configfieldlists.py#L1099-L1124 | train |
lsst-sqre/documenteer | documenteer/sphinxext/lssttasks/configfieldlists.py | create_configfield_ref_target_node | def create_configfield_ref_target_node(target_id, env, lineno):
"""Create a ``target`` node that marks a configuration field.
Internally, this also adds to the ``lsst_configfields`` attribute of the
environment that is consumed by `documenteer.sphinxext.lssttasks.
crossrefs.process_pending_configfield_xref_nodes`.
See also
--------
`documenteer.sphinxext.lssttasks.crossrefs.process_pending_configfield_xref_nodes`
"""
target_node = nodes.target('', '', ids=[target_id])
# Store these task/configurable topic nodes in the environment for later
# cross referencing.
if not hasattr(env, 'lsst_configfields'):
env.lsst_configfields = {}
env.lsst_configfields[target_id] = {
'docname': env.docname,
'lineno': lineno,
'target': target_node,
}
return target_node | python | def create_configfield_ref_target_node(target_id, env, lineno):
"""Create a ``target`` node that marks a configuration field.
Internally, this also adds to the ``lsst_configfields`` attribute of the
environment that is consumed by `documenteer.sphinxext.lssttasks.
crossrefs.process_pending_configfield_xref_nodes`.
See also
--------
`documenteer.sphinxext.lssttasks.crossrefs.process_pending_configfield_xref_nodes`
"""
target_node = nodes.target('', '', ids=[target_id])
# Store these task/configurable topic nodes in the environment for later
# cross referencing.
if not hasattr(env, 'lsst_configfields'):
env.lsst_configfields = {}
env.lsst_configfields[target_id] = {
'docname': env.docname,
'lineno': lineno,
'target': target_node,
}
return target_node | [
"def",
"create_configfield_ref_target_node",
"(",
"target_id",
",",
"env",
",",
"lineno",
")",
":",
"target_node",
"=",
"nodes",
".",
"target",
"(",
"''",
",",
"''",
",",
"ids",
"=",
"[",
"target_id",
"]",
")",
"# Store these task/configurable topic nodes in the environment for later",
"# cross referencing.",
"if",
"not",
"hasattr",
"(",
"env",
",",
"'lsst_configfields'",
")",
":",
"env",
".",
"lsst_configfields",
"=",
"{",
"}",
"env",
".",
"lsst_configfields",
"[",
"target_id",
"]",
"=",
"{",
"'docname'",
":",
"env",
".",
"docname",
",",
"'lineno'",
":",
"lineno",
",",
"'target'",
":",
"target_node",
",",
"}",
"return",
"target_node"
]
| Create a ``target`` node that marks a configuration field.
Internally, this also adds to the ``lsst_configfields`` attribute of the
environment that is consumed by `documenteer.sphinxext.lssttasks.
crossrefs.process_pending_configfield_xref_nodes`.
See also
--------
`documenteer.sphinxext.lssttasks.crossrefs.process_pending_configfield_xref_nodes` | [
"Create",
"a",
"target",
"node",
"that",
"marks",
"a",
"configuration",
"field",
"."
]
| 75f02901a80042b28d074df1cc1dca32eb8e38c8 | https://github.com/lsst-sqre/documenteer/blob/75f02901a80042b28d074df1cc1dca32eb8e38c8/documenteer/sphinxext/lssttasks/configfieldlists.py#L1127-L1150 | train |
bgyori/pykqml | kqml/kqml_module.py | translate_argv | def translate_argv(raw_args):
"""Enables conversion from system arguments.
Parameters
----------
raw_args : list
Arguments taken raw from the system input.
Returns
-------
kwargs : dict
The input arguments formatted as a kwargs dict.
To use as input, simply use `KQMLModule(**kwargs)`.
"""
kwargs = {}
def get_parameter(param_str):
for i, a in enumerate(raw_args):
if a == param_str:
assert len(raw_args) == i+2 and raw_args[i+1][0] != '-', \
'All arguments must have a value, e.g. `-testing true`'
return raw_args[i+1]
return None
value = get_parameter('-testing')
if value is not None and value.lower() in ('true', 't', 'yes'):
kwargs['testing'] = True
value = get_parameter('-connect')
if value is not None:
colon = value.find(':')
if colon > -1:
kwargs['host'] = value[0:colon]
kwargs['port'] = int(value[colon+1:])
else:
kwargs['host'] = value
value = get_parameter('-name')
if value is not None:
kwargs['name'] = value
value = get_parameter('-group')
if value is not None:
kwargs['group_name'] = value
value = get_parameter('-scan')
if value in ('true', 't', 'yes'):
kwargs['scan_for_port'] = True
value = get_parameter('-debug')
if value in ('true', 't', 'yes'):
kwargs['debug'] = True
return kwargs | python | def translate_argv(raw_args):
"""Enables conversion from system arguments.
Parameters
----------
raw_args : list
Arguments taken raw from the system input.
Returns
-------
kwargs : dict
The input arguments formatted as a kwargs dict.
To use as input, simply use `KQMLModule(**kwargs)`.
"""
kwargs = {}
def get_parameter(param_str):
for i, a in enumerate(raw_args):
if a == param_str:
assert len(raw_args) == i+2 and raw_args[i+1][0] != '-', \
'All arguments must have a value, e.g. `-testing true`'
return raw_args[i+1]
return None
value = get_parameter('-testing')
if value is not None and value.lower() in ('true', 't', 'yes'):
kwargs['testing'] = True
value = get_parameter('-connect')
if value is not None:
colon = value.find(':')
if colon > -1:
kwargs['host'] = value[0:colon]
kwargs['port'] = int(value[colon+1:])
else:
kwargs['host'] = value
value = get_parameter('-name')
if value is not None:
kwargs['name'] = value
value = get_parameter('-group')
if value is not None:
kwargs['group_name'] = value
value = get_parameter('-scan')
if value in ('true', 't', 'yes'):
kwargs['scan_for_port'] = True
value = get_parameter('-debug')
if value in ('true', 't', 'yes'):
kwargs['debug'] = True
return kwargs | [
"def",
"translate_argv",
"(",
"raw_args",
")",
":",
"kwargs",
"=",
"{",
"}",
"def",
"get_parameter",
"(",
"param_str",
")",
":",
"for",
"i",
",",
"a",
"in",
"enumerate",
"(",
"raw_args",
")",
":",
"if",
"a",
"==",
"param_str",
":",
"assert",
"len",
"(",
"raw_args",
")",
"==",
"i",
"+",
"2",
"and",
"raw_args",
"[",
"i",
"+",
"1",
"]",
"[",
"0",
"]",
"!=",
"'-'",
",",
"'All arguments must have a value, e.g. `-testing true`'",
"return",
"raw_args",
"[",
"i",
"+",
"1",
"]",
"return",
"None",
"value",
"=",
"get_parameter",
"(",
"'-testing'",
")",
"if",
"value",
"is",
"not",
"None",
"and",
"value",
".",
"lower",
"(",
")",
"in",
"(",
"'true'",
",",
"'t'",
",",
"'yes'",
")",
":",
"kwargs",
"[",
"'testing'",
"]",
"=",
"True",
"value",
"=",
"get_parameter",
"(",
"'-connect'",
")",
"if",
"value",
"is",
"not",
"None",
":",
"colon",
"=",
"value",
".",
"find",
"(",
"':'",
")",
"if",
"colon",
">",
"-",
"1",
":",
"kwargs",
"[",
"'host'",
"]",
"=",
"value",
"[",
"0",
":",
"colon",
"]",
"kwargs",
"[",
"'port'",
"]",
"=",
"int",
"(",
"value",
"[",
"colon",
"+",
"1",
":",
"]",
")",
"else",
":",
"kwargs",
"[",
"'host'",
"]",
"=",
"value",
"value",
"=",
"get_parameter",
"(",
"'-name'",
")",
"if",
"value",
"is",
"not",
"None",
":",
"kwargs",
"[",
"'name'",
"]",
"=",
"value",
"value",
"=",
"get_parameter",
"(",
"'-group'",
")",
"if",
"value",
"is",
"not",
"None",
":",
"kwargs",
"[",
"'group_name'",
"]",
"=",
"value",
"value",
"=",
"get_parameter",
"(",
"'-scan'",
")",
"if",
"value",
"in",
"(",
"'true'",
",",
"'t'",
",",
"'yes'",
")",
":",
"kwargs",
"[",
"'scan_for_port'",
"]",
"=",
"True",
"value",
"=",
"get_parameter",
"(",
"'-debug'",
")",
"if",
"value",
"in",
"(",
"'true'",
",",
"'t'",
",",
"'yes'",
")",
":",
"kwargs",
"[",
"'debug'",
"]",
"=",
"True",
"return",
"kwargs"
]
| Enables conversion from system arguments.
Parameters
----------
raw_args : list
Arguments taken raw from the system input.
Returns
-------
kwargs : dict
The input arguments formatted as a kwargs dict.
To use as input, simply use `KQMLModule(**kwargs)`. | [
"Enables",
"conversion",
"from",
"system",
"arguments",
"."
]
| c18b39868626215deb634567c6bd7c0838e443c0 | https://github.com/bgyori/pykqml/blob/c18b39868626215deb634567c6bd7c0838e443c0/kqml/kqml_module.py#L22-L75 | train |
lsst-sqre/documenteer | documenteer/sphinxext/lssttasks/topiclists.py | BaseTopicListDirective._build_toctree | def _build_toctree(self):
"""Create a hidden toctree node with the contents of a directory
prefixed by the directory name specified by the `toctree` directive
option.
"""
dirname = posixpath.dirname(self._env.docname)
tree_prefix = self.options['toctree'].strip()
root = posixpath.normpath(posixpath.join(dirname, tree_prefix))
docnames = [docname for docname in self._env.found_docs
if docname.startswith(root)]
# Sort docnames alphabetically based on **class** name.
# The standard we assume is that task doc pages are named after
# their Python namespace.
# NOTE: this ordering only applies to the toctree; the visual ordering
# is set by `process_task_topic_list`.
# NOTE: docnames are **always** POSIX-like paths
class_names = [docname.split('/')[-1].split('.')[-1]
for docname in docnames]
docnames = [docname for docname, _ in
sorted(zip(docnames, class_names),
key=lambda pair: pair[1])]
tocnode = sphinx.addnodes.toctree()
tocnode['includefiles'] = docnames
tocnode['entries'] = [(None, docname) for docname in docnames]
tocnode['maxdepth'] = -1
tocnode['glob'] = None
tocnode['hidden'] = True
return tocnode | python | def _build_toctree(self):
"""Create a hidden toctree node with the contents of a directory
prefixed by the directory name specified by the `toctree` directive
option.
"""
dirname = posixpath.dirname(self._env.docname)
tree_prefix = self.options['toctree'].strip()
root = posixpath.normpath(posixpath.join(dirname, tree_prefix))
docnames = [docname for docname in self._env.found_docs
if docname.startswith(root)]
# Sort docnames alphabetically based on **class** name.
# The standard we assume is that task doc pages are named after
# their Python namespace.
# NOTE: this ordering only applies to the toctree; the visual ordering
# is set by `process_task_topic_list`.
# NOTE: docnames are **always** POSIX-like paths
class_names = [docname.split('/')[-1].split('.')[-1]
for docname in docnames]
docnames = [docname for docname, _ in
sorted(zip(docnames, class_names),
key=lambda pair: pair[1])]
tocnode = sphinx.addnodes.toctree()
tocnode['includefiles'] = docnames
tocnode['entries'] = [(None, docname) for docname in docnames]
tocnode['maxdepth'] = -1
tocnode['glob'] = None
tocnode['hidden'] = True
return tocnode | [
"def",
"_build_toctree",
"(",
"self",
")",
":",
"dirname",
"=",
"posixpath",
".",
"dirname",
"(",
"self",
".",
"_env",
".",
"docname",
")",
"tree_prefix",
"=",
"self",
".",
"options",
"[",
"'toctree'",
"]",
".",
"strip",
"(",
")",
"root",
"=",
"posixpath",
".",
"normpath",
"(",
"posixpath",
".",
"join",
"(",
"dirname",
",",
"tree_prefix",
")",
")",
"docnames",
"=",
"[",
"docname",
"for",
"docname",
"in",
"self",
".",
"_env",
".",
"found_docs",
"if",
"docname",
".",
"startswith",
"(",
"root",
")",
"]",
"# Sort docnames alphabetically based on **class** name.",
"# The standard we assume is that task doc pages are named after",
"# their Python namespace.",
"# NOTE: this ordering only applies to the toctree; the visual ordering",
"# is set by `process_task_topic_list`.",
"# NOTE: docnames are **always** POSIX-like paths",
"class_names",
"=",
"[",
"docname",
".",
"split",
"(",
"'/'",
")",
"[",
"-",
"1",
"]",
".",
"split",
"(",
"'.'",
")",
"[",
"-",
"1",
"]",
"for",
"docname",
"in",
"docnames",
"]",
"docnames",
"=",
"[",
"docname",
"for",
"docname",
",",
"_",
"in",
"sorted",
"(",
"zip",
"(",
"docnames",
",",
"class_names",
")",
",",
"key",
"=",
"lambda",
"pair",
":",
"pair",
"[",
"1",
"]",
")",
"]",
"tocnode",
"=",
"sphinx",
".",
"addnodes",
".",
"toctree",
"(",
")",
"tocnode",
"[",
"'includefiles'",
"]",
"=",
"docnames",
"tocnode",
"[",
"'entries'",
"]",
"=",
"[",
"(",
"None",
",",
"docname",
")",
"for",
"docname",
"in",
"docnames",
"]",
"tocnode",
"[",
"'maxdepth'",
"]",
"=",
"-",
"1",
"tocnode",
"[",
"'glob'",
"]",
"=",
"None",
"tocnode",
"[",
"'hidden'",
"]",
"=",
"True",
"return",
"tocnode"
]
| Create a hidden toctree node with the contents of a directory
prefixed by the directory name specified by the `toctree` directive
option. | [
"Create",
"a",
"hidden",
"toctree",
"node",
"with",
"the",
"contents",
"of",
"a",
"directory",
"prefixed",
"by",
"the",
"directory",
"name",
"specified",
"by",
"the",
"toctree",
"directive",
"option",
"."
]
| 75f02901a80042b28d074df1cc1dca32eb8e38c8 | https://github.com/lsst-sqre/documenteer/blob/75f02901a80042b28d074df1cc1dca32eb8e38c8/documenteer/sphinxext/lssttasks/topiclists.py#L74-L104 | train |
mastro35/flows | flows/Actions/WebserverAction.py | MyServerRequestHandler.do_GET | def do_GET(self):
"""
Handle GET WebMethod
"""
self.send_response(200)
self.send_header("Content-type", "text/html")
self.end_headers()
self.wfile.write(bytes(json.dumps(self.message), "utf-8")) | python | def do_GET(self):
"""
Handle GET WebMethod
"""
self.send_response(200)
self.send_header("Content-type", "text/html")
self.end_headers()
self.wfile.write(bytes(json.dumps(self.message), "utf-8")) | [
"def",
"do_GET",
"(",
"self",
")",
":",
"self",
".",
"send_response",
"(",
"200",
")",
"self",
".",
"send_header",
"(",
"\"Content-type\"",
",",
"\"text/html\"",
")",
"self",
".",
"end_headers",
"(",
")",
"self",
".",
"wfile",
".",
"write",
"(",
"bytes",
"(",
"json",
".",
"dumps",
"(",
"self",
".",
"message",
")",
",",
"\"utf-8\"",
")",
")"
]
| Handle GET WebMethod | [
"Handle",
"GET",
"WebMethod"
]
| 05e488385673a69597b5b39c7728795aa4d5eb18 | https://github.com/mastro35/flows/blob/05e488385673a69597b5b39c7728795aa4d5eb18/flows/Actions/WebserverAction.py#L76-L84 | train |
mastro35/flows | flows/Actions/WebserverAction.py | DannyHTTPServer.serve_forever | def serve_forever(self, poll_interval=0.5):
"""
Cycle for webserer
"""
while self.is_alive:
self.handle_request()
time.sleep(poll_interval) | python | def serve_forever(self, poll_interval=0.5):
"""
Cycle for webserer
"""
while self.is_alive:
self.handle_request()
time.sleep(poll_interval) | [
"def",
"serve_forever",
"(",
"self",
",",
"poll_interval",
"=",
"0.5",
")",
":",
"while",
"self",
".",
"is_alive",
":",
"self",
".",
"handle_request",
"(",
")",
"time",
".",
"sleep",
"(",
"poll_interval",
")"
]
| Cycle for webserer | [
"Cycle",
"for",
"webserer"
]
| 05e488385673a69597b5b39c7728795aa4d5eb18 | https://github.com/mastro35/flows/blob/05e488385673a69597b5b39c7728795aa4d5eb18/flows/Actions/WebserverAction.py#L100-L106 | train |
mastro35/flows | flows/Actions/WebserverAction.py | DannyHTTPServer.stop | def stop(self):
"""
Stop the webserver
"""
self.is_alive = False
self.server_close()
flows.Global.LOGGER.info("Server Stops " + (str(self.server_address))) | python | def stop(self):
"""
Stop the webserver
"""
self.is_alive = False
self.server_close()
flows.Global.LOGGER.info("Server Stops " + (str(self.server_address))) | [
"def",
"stop",
"(",
"self",
")",
":",
"self",
".",
"is_alive",
"=",
"False",
"self",
".",
"server_close",
"(",
")",
"flows",
".",
"Global",
".",
"LOGGER",
".",
"info",
"(",
"\"Server Stops \"",
"+",
"(",
"str",
"(",
"self",
".",
"server_address",
")",
")",
")"
]
| Stop the webserver | [
"Stop",
"the",
"webserver"
]
| 05e488385673a69597b5b39c7728795aa4d5eb18 | https://github.com/mastro35/flows/blob/05e488385673a69597b5b39c7728795aa4d5eb18/flows/Actions/WebserverAction.py#L108-L114 | train |
yymao/generic-catalog-reader | GCR/query.py | GCRQuery.check_scalar | def check_scalar(self, scalar_dict):
"""
check if `scalar_dict` satisfy query
"""
table = {k: np.array([v]) for k, v in scalar_dict.items()}
return self.mask(table)[0] | python | def check_scalar(self, scalar_dict):
"""
check if `scalar_dict` satisfy query
"""
table = {k: np.array([v]) for k, v in scalar_dict.items()}
return self.mask(table)[0] | [
"def",
"check_scalar",
"(",
"self",
",",
"scalar_dict",
")",
":",
"table",
"=",
"{",
"k",
":",
"np",
".",
"array",
"(",
"[",
"v",
"]",
")",
"for",
"k",
",",
"v",
"in",
"scalar_dict",
".",
"items",
"(",
")",
"}",
"return",
"self",
".",
"mask",
"(",
"table",
")",
"[",
"0",
"]"
]
| check if `scalar_dict` satisfy query | [
"check",
"if",
"scalar_dict",
"satisfy",
"query"
]
| bc6267ac41b9f68106ed6065184469ac13fdc0b6 | https://github.com/yymao/generic-catalog-reader/blob/bc6267ac41b9f68106ed6065184469ac13fdc0b6/GCR/query.py#L28-L33 | train |
untwisted/untwisted | untwisted/stdin.py | Stdin.dumpfile | def dumpfile(self, fd):
"""
Dump a file through a Spin instance.
"""
self.start()
dump = DumpFile(fd)
self.queue.append(dump) | python | def dumpfile(self, fd):
"""
Dump a file through a Spin instance.
"""
self.start()
dump = DumpFile(fd)
self.queue.append(dump) | [
"def",
"dumpfile",
"(",
"self",
",",
"fd",
")",
":",
"self",
".",
"start",
"(",
")",
"dump",
"=",
"DumpFile",
"(",
"fd",
")",
"self",
".",
"queue",
".",
"append",
"(",
"dump",
")"
]
| Dump a file through a Spin instance. | [
"Dump",
"a",
"file",
"through",
"a",
"Spin",
"instance",
"."
]
| 8a8d9c8a8d0f3452d5de67cd760297bb5759f637 | https://github.com/untwisted/untwisted/blob/8a8d9c8a8d0f3452d5de67cd760297bb5759f637/untwisted/stdin.py#L62-L69 | train |
lsst-sqre/documenteer | documenteer/sphinxext/remotecodeblock.py | RemoteCodeBlock.run | def run(self):
"""Run the ``remote-code-block`` directive.
"""
document = self.state.document
if not document.settings.file_insertion_enabled:
return [document.reporter.warning('File insertion disabled',
line=self.lineno)]
try:
location = self.state_machine.get_source_and_line(self.lineno)
# Customized for RemoteCodeBlock
url = self.arguments[0]
reader = RemoteCodeBlockReader(url, self.options, self.config)
text, lines = reader.read(location=location)
retnode = nodes.literal_block(text, text)
set_source_info(self, retnode)
if self.options.get('diff'): # if diff is set, set udiff
retnode['language'] = 'udiff'
elif 'language' in self.options:
retnode['language'] = self.options['language']
retnode['linenos'] = ('linenos' in self.options or
'lineno-start' in self.options or
'lineno-match' in self.options)
retnode['classes'] += self.options.get('class', [])
extra_args = retnode['highlight_args'] = {}
if 'emphasize-lines' in self.options:
hl_lines = parselinenos(self.options['emphasize-lines'], lines)
if any(i >= lines for i in hl_lines):
logger.warning(
'line number spec is out of range(1-%d): %r' %
(lines, self.options['emphasize-lines']),
location=location)
extra_args['hl_lines'] = [x + 1 for x in hl_lines if x < lines]
extra_args['linenostart'] = reader.lineno_start
if 'caption' in self.options:
caption = self.options['caption'] or self.arguments[0]
retnode = container_wrapper(self, retnode, caption)
# retnode will be note_implicit_target that is linked from caption
# and numref. when options['name'] is provided, it should be
# primary ID.
self.add_name(retnode)
return [retnode]
except Exception as exc:
return [document.reporter.warning(str(exc), line=self.lineno)] | python | def run(self):
"""Run the ``remote-code-block`` directive.
"""
document = self.state.document
if not document.settings.file_insertion_enabled:
return [document.reporter.warning('File insertion disabled',
line=self.lineno)]
try:
location = self.state_machine.get_source_and_line(self.lineno)
# Customized for RemoteCodeBlock
url = self.arguments[0]
reader = RemoteCodeBlockReader(url, self.options, self.config)
text, lines = reader.read(location=location)
retnode = nodes.literal_block(text, text)
set_source_info(self, retnode)
if self.options.get('diff'): # if diff is set, set udiff
retnode['language'] = 'udiff'
elif 'language' in self.options:
retnode['language'] = self.options['language']
retnode['linenos'] = ('linenos' in self.options or
'lineno-start' in self.options or
'lineno-match' in self.options)
retnode['classes'] += self.options.get('class', [])
extra_args = retnode['highlight_args'] = {}
if 'emphasize-lines' in self.options:
hl_lines = parselinenos(self.options['emphasize-lines'], lines)
if any(i >= lines for i in hl_lines):
logger.warning(
'line number spec is out of range(1-%d): %r' %
(lines, self.options['emphasize-lines']),
location=location)
extra_args['hl_lines'] = [x + 1 for x in hl_lines if x < lines]
extra_args['linenostart'] = reader.lineno_start
if 'caption' in self.options:
caption = self.options['caption'] or self.arguments[0]
retnode = container_wrapper(self, retnode, caption)
# retnode will be note_implicit_target that is linked from caption
# and numref. when options['name'] is provided, it should be
# primary ID.
self.add_name(retnode)
return [retnode]
except Exception as exc:
return [document.reporter.warning(str(exc), line=self.lineno)] | [
"def",
"run",
"(",
"self",
")",
":",
"document",
"=",
"self",
".",
"state",
".",
"document",
"if",
"not",
"document",
".",
"settings",
".",
"file_insertion_enabled",
":",
"return",
"[",
"document",
".",
"reporter",
".",
"warning",
"(",
"'File insertion disabled'",
",",
"line",
"=",
"self",
".",
"lineno",
")",
"]",
"try",
":",
"location",
"=",
"self",
".",
"state_machine",
".",
"get_source_and_line",
"(",
"self",
".",
"lineno",
")",
"# Customized for RemoteCodeBlock",
"url",
"=",
"self",
".",
"arguments",
"[",
"0",
"]",
"reader",
"=",
"RemoteCodeBlockReader",
"(",
"url",
",",
"self",
".",
"options",
",",
"self",
".",
"config",
")",
"text",
",",
"lines",
"=",
"reader",
".",
"read",
"(",
"location",
"=",
"location",
")",
"retnode",
"=",
"nodes",
".",
"literal_block",
"(",
"text",
",",
"text",
")",
"set_source_info",
"(",
"self",
",",
"retnode",
")",
"if",
"self",
".",
"options",
".",
"get",
"(",
"'diff'",
")",
":",
"# if diff is set, set udiff",
"retnode",
"[",
"'language'",
"]",
"=",
"'udiff'",
"elif",
"'language'",
"in",
"self",
".",
"options",
":",
"retnode",
"[",
"'language'",
"]",
"=",
"self",
".",
"options",
"[",
"'language'",
"]",
"retnode",
"[",
"'linenos'",
"]",
"=",
"(",
"'linenos'",
"in",
"self",
".",
"options",
"or",
"'lineno-start'",
"in",
"self",
".",
"options",
"or",
"'lineno-match'",
"in",
"self",
".",
"options",
")",
"retnode",
"[",
"'classes'",
"]",
"+=",
"self",
".",
"options",
".",
"get",
"(",
"'class'",
",",
"[",
"]",
")",
"extra_args",
"=",
"retnode",
"[",
"'highlight_args'",
"]",
"=",
"{",
"}",
"if",
"'emphasize-lines'",
"in",
"self",
".",
"options",
":",
"hl_lines",
"=",
"parselinenos",
"(",
"self",
".",
"options",
"[",
"'emphasize-lines'",
"]",
",",
"lines",
")",
"if",
"any",
"(",
"i",
">=",
"lines",
"for",
"i",
"in",
"hl_lines",
")",
":",
"logger",
".",
"warning",
"(",
"'line number spec is out of range(1-%d): %r'",
"%",
"(",
"lines",
",",
"self",
".",
"options",
"[",
"'emphasize-lines'",
"]",
")",
",",
"location",
"=",
"location",
")",
"extra_args",
"[",
"'hl_lines'",
"]",
"=",
"[",
"x",
"+",
"1",
"for",
"x",
"in",
"hl_lines",
"if",
"x",
"<",
"lines",
"]",
"extra_args",
"[",
"'linenostart'",
"]",
"=",
"reader",
".",
"lineno_start",
"if",
"'caption'",
"in",
"self",
".",
"options",
":",
"caption",
"=",
"self",
".",
"options",
"[",
"'caption'",
"]",
"or",
"self",
".",
"arguments",
"[",
"0",
"]",
"retnode",
"=",
"container_wrapper",
"(",
"self",
",",
"retnode",
",",
"caption",
")",
"# retnode will be note_implicit_target that is linked from caption",
"# and numref. when options['name'] is provided, it should be",
"# primary ID.",
"self",
".",
"add_name",
"(",
"retnode",
")",
"return",
"[",
"retnode",
"]",
"except",
"Exception",
"as",
"exc",
":",
"return",
"[",
"document",
".",
"reporter",
".",
"warning",
"(",
"str",
"(",
"exc",
")",
",",
"line",
"=",
"self",
".",
"lineno",
")",
"]"
]
| Run the ``remote-code-block`` directive. | [
"Run",
"the",
"remote",
"-",
"code",
"-",
"block",
"directive",
"."
]
| 75f02901a80042b28d074df1cc1dca32eb8e38c8 | https://github.com/lsst-sqre/documenteer/blob/75f02901a80042b28d074df1cc1dca32eb8e38c8/documenteer/sphinxext/remotecodeblock.py#L75-L124 | train |
lsst-sqre/documenteer | documenteer/sphinxext/remotecodeblock.py | RemoteCodeBlockReader.read_file | def read_file(self, url, location=None):
"""Read content from the web by overriding
`LiteralIncludeReader.read_file`.
"""
response = requests_retry_session().get(url, timeout=10.0)
response.raise_for_status()
text = response.text
if 'tab-width' in self.options:
text = text.expandtabs(self.options['tab-width'])
return text.splitlines(True) | python | def read_file(self, url, location=None):
"""Read content from the web by overriding
`LiteralIncludeReader.read_file`.
"""
response = requests_retry_session().get(url, timeout=10.0)
response.raise_for_status()
text = response.text
if 'tab-width' in self.options:
text = text.expandtabs(self.options['tab-width'])
return text.splitlines(True) | [
"def",
"read_file",
"(",
"self",
",",
"url",
",",
"location",
"=",
"None",
")",
":",
"response",
"=",
"requests_retry_session",
"(",
")",
".",
"get",
"(",
"url",
",",
"timeout",
"=",
"10.0",
")",
"response",
".",
"raise_for_status",
"(",
")",
"text",
"=",
"response",
".",
"text",
"if",
"'tab-width'",
"in",
"self",
".",
"options",
":",
"text",
"=",
"text",
".",
"expandtabs",
"(",
"self",
".",
"options",
"[",
"'tab-width'",
"]",
")",
"return",
"text",
".",
"splitlines",
"(",
"True",
")"
]
| Read content from the web by overriding
`LiteralIncludeReader.read_file`. | [
"Read",
"content",
"from",
"the",
"web",
"by",
"overriding",
"LiteralIncludeReader",
".",
"read_file",
"."
]
| 75f02901a80042b28d074df1cc1dca32eb8e38c8 | https://github.com/lsst-sqre/documenteer/blob/75f02901a80042b28d074df1cc1dca32eb8e38c8/documenteer/sphinxext/remotecodeblock.py#L131-L141 | train |
mastro35/flows | flows/Actions/PassOnInterval.py | PassOnInterval.verify_time | def verify_time(self, now):
'''Verify the time'''
return now.time() >= self.start_time and now.time() <= self.end_time | python | def verify_time(self, now):
'''Verify the time'''
return now.time() >= self.start_time and now.time() <= self.end_time | [
"def",
"verify_time",
"(",
"self",
",",
"now",
")",
":",
"return",
"now",
".",
"time",
"(",
")",
">=",
"self",
".",
"start_time",
"and",
"now",
".",
"time",
"(",
")",
"<=",
"self",
".",
"end_time"
]
| Verify the time | [
"Verify",
"the",
"time"
]
| 05e488385673a69597b5b39c7728795aa4d5eb18 | https://github.com/mastro35/flows/blob/05e488385673a69597b5b39c7728795aa4d5eb18/flows/Actions/PassOnInterval.py#L63-L65 | train |
mastro35/flows | flows/Actions/PassOnInterval.py | PassOnInterval.verify_weekday | def verify_weekday(self, now):
'''Verify the weekday'''
return self.weekdays == "*" or str(now.weekday()) in self.weekdays.split(" ") | python | def verify_weekday(self, now):
'''Verify the weekday'''
return self.weekdays == "*" or str(now.weekday()) in self.weekdays.split(" ") | [
"def",
"verify_weekday",
"(",
"self",
",",
"now",
")",
":",
"return",
"self",
".",
"weekdays",
"==",
"\"*\"",
"or",
"str",
"(",
"now",
".",
"weekday",
"(",
")",
")",
"in",
"self",
".",
"weekdays",
".",
"split",
"(",
"\" \"",
")"
]
| Verify the weekday | [
"Verify",
"the",
"weekday"
]
| 05e488385673a69597b5b39c7728795aa4d5eb18 | https://github.com/mastro35/flows/blob/05e488385673a69597b5b39c7728795aa4d5eb18/flows/Actions/PassOnInterval.py#L67-L69 | train |
mastro35/flows | flows/Actions/PassOnInterval.py | PassOnInterval.verify_day | def verify_day(self, now):
'''Verify the day'''
return self.day == "*" or str(now.day) in self.day.split(" ") | python | def verify_day(self, now):
'''Verify the day'''
return self.day == "*" or str(now.day) in self.day.split(" ") | [
"def",
"verify_day",
"(",
"self",
",",
"now",
")",
":",
"return",
"self",
".",
"day",
"==",
"\"*\"",
"or",
"str",
"(",
"now",
".",
"day",
")",
"in",
"self",
".",
"day",
".",
"split",
"(",
"\" \"",
")"
]
| Verify the day | [
"Verify",
"the",
"day"
]
| 05e488385673a69597b5b39c7728795aa4d5eb18 | https://github.com/mastro35/flows/blob/05e488385673a69597b5b39c7728795aa4d5eb18/flows/Actions/PassOnInterval.py#L71-L73 | train |
mastro35/flows | flows/Actions/PassOnInterval.py | PassOnInterval.verify_month | def verify_month(self, now):
'''Verify the month'''
return self.month == "*" or str(now.month) in self.month.split(" ") | python | def verify_month(self, now):
'''Verify the month'''
return self.month == "*" or str(now.month) in self.month.split(" ") | [
"def",
"verify_month",
"(",
"self",
",",
"now",
")",
":",
"return",
"self",
".",
"month",
"==",
"\"*\"",
"or",
"str",
"(",
"now",
".",
"month",
")",
"in",
"self",
".",
"month",
".",
"split",
"(",
"\" \"",
")"
]
| Verify the month | [
"Verify",
"the",
"month"
]
| 05e488385673a69597b5b39c7728795aa4d5eb18 | https://github.com/mastro35/flows/blob/05e488385673a69597b5b39c7728795aa4d5eb18/flows/Actions/PassOnInterval.py#L75-L77 | train |
maljovec/topopy | topopy/TopologicalObject.py | TopologicalObject.aggregate_duplicates | def aggregate_duplicates(X, Y, aggregator="mean", precision=precision):
""" A function that will attempt to collapse duplicates in
domain space, X, by aggregating values over the range space,
Y.
@ In, X, an m-by-n array of values specifying m
n-dimensional samples
@ In, Y, a m vector of values specifying the output
responses corresponding to the m samples specified by X
@ In, aggregator, an optional string or callable object that
specifies what type of aggregation to do when duplicates are
found in the domain space. Default value is mean meaning the
code will calculate the mean range value over each of the
unique, duplicated samples.
@ In, precision, an optional positive integer specifying how
many digits numbers should be rounded to in order to
determine if they are unique or not.
@ Out, (unique_X, aggregated_Y), a tuple where the first
value is an m'-by-n array specifying the unique domain
samples and the second value is an m' vector specifying the
associated range values. m' <= m.
"""
if callable(aggregator):
pass
elif "min" in aggregator.lower():
aggregator = np.min
elif "max" in aggregator.lower():
aggregator = np.max
elif "median" in aggregator.lower():
aggregator = np.median
elif aggregator.lower() in ["average", "mean"]:
aggregator = np.mean
elif "first" in aggregator.lower():
def aggregator(x):
return x[0]
elif "last" in aggregator.lower():
def aggregator(x):
return x[-1]
else:
warnings.warn(
'Aggregator "{}" not understood. Skipping sample '
"aggregation.".format(aggregator)
)
return X, Y
is_y_multivariate = Y.ndim > 1
X_rounded = X.round(decimals=precision)
unique_xs = np.unique(X_rounded, axis=0)
old_size = len(X_rounded)
new_size = len(unique_xs)
if old_size == new_size:
return X, Y
if not is_y_multivariate:
Y = np.atleast_2d(Y).T
reduced_y = np.empty((new_size, Y.shape[1]))
warnings.warn(
"Domain space duplicates caused a data reduction. "
+ "Original size: {} vs. New size: {}".format(old_size, new_size)
)
for col in range(Y.shape[1]):
for i, distinct_row in enumerate(unique_xs):
filtered_rows = np.all(X_rounded == distinct_row, axis=1)
reduced_y[i, col] = aggregator(Y[filtered_rows, col])
if not is_y_multivariate:
reduced_y = reduced_y.flatten()
return unique_xs, reduced_y | python | def aggregate_duplicates(X, Y, aggregator="mean", precision=precision):
""" A function that will attempt to collapse duplicates in
domain space, X, by aggregating values over the range space,
Y.
@ In, X, an m-by-n array of values specifying m
n-dimensional samples
@ In, Y, a m vector of values specifying the output
responses corresponding to the m samples specified by X
@ In, aggregator, an optional string or callable object that
specifies what type of aggregation to do when duplicates are
found in the domain space. Default value is mean meaning the
code will calculate the mean range value over each of the
unique, duplicated samples.
@ In, precision, an optional positive integer specifying how
many digits numbers should be rounded to in order to
determine if they are unique or not.
@ Out, (unique_X, aggregated_Y), a tuple where the first
value is an m'-by-n array specifying the unique domain
samples and the second value is an m' vector specifying the
associated range values. m' <= m.
"""
if callable(aggregator):
pass
elif "min" in aggregator.lower():
aggregator = np.min
elif "max" in aggregator.lower():
aggregator = np.max
elif "median" in aggregator.lower():
aggregator = np.median
elif aggregator.lower() in ["average", "mean"]:
aggregator = np.mean
elif "first" in aggregator.lower():
def aggregator(x):
return x[0]
elif "last" in aggregator.lower():
def aggregator(x):
return x[-1]
else:
warnings.warn(
'Aggregator "{}" not understood. Skipping sample '
"aggregation.".format(aggregator)
)
return X, Y
is_y_multivariate = Y.ndim > 1
X_rounded = X.round(decimals=precision)
unique_xs = np.unique(X_rounded, axis=0)
old_size = len(X_rounded)
new_size = len(unique_xs)
if old_size == new_size:
return X, Y
if not is_y_multivariate:
Y = np.atleast_2d(Y).T
reduced_y = np.empty((new_size, Y.shape[1]))
warnings.warn(
"Domain space duplicates caused a data reduction. "
+ "Original size: {} vs. New size: {}".format(old_size, new_size)
)
for col in range(Y.shape[1]):
for i, distinct_row in enumerate(unique_xs):
filtered_rows = np.all(X_rounded == distinct_row, axis=1)
reduced_y[i, col] = aggregator(Y[filtered_rows, col])
if not is_y_multivariate:
reduced_y = reduced_y.flatten()
return unique_xs, reduced_y | [
"def",
"aggregate_duplicates",
"(",
"X",
",",
"Y",
",",
"aggregator",
"=",
"\"mean\"",
",",
"precision",
"=",
"precision",
")",
":",
"if",
"callable",
"(",
"aggregator",
")",
":",
"pass",
"elif",
"\"min\"",
"in",
"aggregator",
".",
"lower",
"(",
")",
":",
"aggregator",
"=",
"np",
".",
"min",
"elif",
"\"max\"",
"in",
"aggregator",
".",
"lower",
"(",
")",
":",
"aggregator",
"=",
"np",
".",
"max",
"elif",
"\"median\"",
"in",
"aggregator",
".",
"lower",
"(",
")",
":",
"aggregator",
"=",
"np",
".",
"median",
"elif",
"aggregator",
".",
"lower",
"(",
")",
"in",
"[",
"\"average\"",
",",
"\"mean\"",
"]",
":",
"aggregator",
"=",
"np",
".",
"mean",
"elif",
"\"first\"",
"in",
"aggregator",
".",
"lower",
"(",
")",
":",
"def",
"aggregator",
"(",
"x",
")",
":",
"return",
"x",
"[",
"0",
"]",
"elif",
"\"last\"",
"in",
"aggregator",
".",
"lower",
"(",
")",
":",
"def",
"aggregator",
"(",
"x",
")",
":",
"return",
"x",
"[",
"-",
"1",
"]",
"else",
":",
"warnings",
".",
"warn",
"(",
"'Aggregator \"{}\" not understood. Skipping sample '",
"\"aggregation.\"",
".",
"format",
"(",
"aggregator",
")",
")",
"return",
"X",
",",
"Y",
"is_y_multivariate",
"=",
"Y",
".",
"ndim",
">",
"1",
"X_rounded",
"=",
"X",
".",
"round",
"(",
"decimals",
"=",
"precision",
")",
"unique_xs",
"=",
"np",
".",
"unique",
"(",
"X_rounded",
",",
"axis",
"=",
"0",
")",
"old_size",
"=",
"len",
"(",
"X_rounded",
")",
"new_size",
"=",
"len",
"(",
"unique_xs",
")",
"if",
"old_size",
"==",
"new_size",
":",
"return",
"X",
",",
"Y",
"if",
"not",
"is_y_multivariate",
":",
"Y",
"=",
"np",
".",
"atleast_2d",
"(",
"Y",
")",
".",
"T",
"reduced_y",
"=",
"np",
".",
"empty",
"(",
"(",
"new_size",
",",
"Y",
".",
"shape",
"[",
"1",
"]",
")",
")",
"warnings",
".",
"warn",
"(",
"\"Domain space duplicates caused a data reduction. \"",
"+",
"\"Original size: {} vs. New size: {}\"",
".",
"format",
"(",
"old_size",
",",
"new_size",
")",
")",
"for",
"col",
"in",
"range",
"(",
"Y",
".",
"shape",
"[",
"1",
"]",
")",
":",
"for",
"i",
",",
"distinct_row",
"in",
"enumerate",
"(",
"unique_xs",
")",
":",
"filtered_rows",
"=",
"np",
".",
"all",
"(",
"X_rounded",
"==",
"distinct_row",
",",
"axis",
"=",
"1",
")",
"reduced_y",
"[",
"i",
",",
"col",
"]",
"=",
"aggregator",
"(",
"Y",
"[",
"filtered_rows",
",",
"col",
"]",
")",
"if",
"not",
"is_y_multivariate",
":",
"reduced_y",
"=",
"reduced_y",
".",
"flatten",
"(",
")",
"return",
"unique_xs",
",",
"reduced_y"
]
| A function that will attempt to collapse duplicates in
domain space, X, by aggregating values over the range space,
Y.
@ In, X, an m-by-n array of values specifying m
n-dimensional samples
@ In, Y, a m vector of values specifying the output
responses corresponding to the m samples specified by X
@ In, aggregator, an optional string or callable object that
specifies what type of aggregation to do when duplicates are
found in the domain space. Default value is mean meaning the
code will calculate the mean range value over each of the
unique, duplicated samples.
@ In, precision, an optional positive integer specifying how
many digits numbers should be rounded to in order to
determine if they are unique or not.
@ Out, (unique_X, aggregated_Y), a tuple where the first
value is an m'-by-n array specifying the unique domain
samples and the second value is an m' vector specifying the
associated range values. m' <= m. | [
"A",
"function",
"that",
"will",
"attempt",
"to",
"collapse",
"duplicates",
"in",
"domain",
"space",
"X",
"by",
"aggregating",
"values",
"over",
"the",
"range",
"space",
"Y",
"."
]
| 4be598d51c4e4043b73d4ad44beed6d289e2f088 | https://github.com/maljovec/topopy/blob/4be598d51c4e4043b73d4ad44beed6d289e2f088/topopy/TopologicalObject.py#L19-L94 | train |
maljovec/topopy | topopy/TopologicalObject.py | TopologicalObject.__set_data | def __set_data(self, X, Y, w=None):
""" Internally assigns the input data and normalizes it
according to the user's specifications
@ In, X, an m-by-n array of values specifying m
n-dimensional samples
@ In, Y, a m vector of values specifying the output
responses corresponding to the m samples specified by X
@ In, w, an optional m vector of values specifying the
weights associated to each of the m samples used. Default of
None means all points will be equally weighted
"""
self.X = X
self.Y = Y
self.check_duplicates()
if w is not None:
self.w = np.array(w)
else:
self.w = np.ones(len(Y)) * 1.0 / float(len(Y))
if self.normalization == "feature":
# This doesn't work with one-dimensional arrays on older
# versions of sklearn
min_max_scaler = sklearn.preprocessing.MinMaxScaler()
self.Xnorm = min_max_scaler.fit_transform(np.atleast_2d(self.X))
elif self.normalization == "zscore":
self.Xnorm = sklearn.preprocessing.scale(
self.X, axis=0, with_mean=True, with_std=True, copy=True
)
else:
self.Xnorm = np.array(self.X) | python | def __set_data(self, X, Y, w=None):
""" Internally assigns the input data and normalizes it
according to the user's specifications
@ In, X, an m-by-n array of values specifying m
n-dimensional samples
@ In, Y, a m vector of values specifying the output
responses corresponding to the m samples specified by X
@ In, w, an optional m vector of values specifying the
weights associated to each of the m samples used. Default of
None means all points will be equally weighted
"""
self.X = X
self.Y = Y
self.check_duplicates()
if w is not None:
self.w = np.array(w)
else:
self.w = np.ones(len(Y)) * 1.0 / float(len(Y))
if self.normalization == "feature":
# This doesn't work with one-dimensional arrays on older
# versions of sklearn
min_max_scaler = sklearn.preprocessing.MinMaxScaler()
self.Xnorm = min_max_scaler.fit_transform(np.atleast_2d(self.X))
elif self.normalization == "zscore":
self.Xnorm = sklearn.preprocessing.scale(
self.X, axis=0, with_mean=True, with_std=True, copy=True
)
else:
self.Xnorm = np.array(self.X) | [
"def",
"__set_data",
"(",
"self",
",",
"X",
",",
"Y",
",",
"w",
"=",
"None",
")",
":",
"self",
".",
"X",
"=",
"X",
"self",
".",
"Y",
"=",
"Y",
"self",
".",
"check_duplicates",
"(",
")",
"if",
"w",
"is",
"not",
"None",
":",
"self",
".",
"w",
"=",
"np",
".",
"array",
"(",
"w",
")",
"else",
":",
"self",
".",
"w",
"=",
"np",
".",
"ones",
"(",
"len",
"(",
"Y",
")",
")",
"*",
"1.0",
"/",
"float",
"(",
"len",
"(",
"Y",
")",
")",
"if",
"self",
".",
"normalization",
"==",
"\"feature\"",
":",
"# This doesn't work with one-dimensional arrays on older",
"# versions of sklearn",
"min_max_scaler",
"=",
"sklearn",
".",
"preprocessing",
".",
"MinMaxScaler",
"(",
")",
"self",
".",
"Xnorm",
"=",
"min_max_scaler",
".",
"fit_transform",
"(",
"np",
".",
"atleast_2d",
"(",
"self",
".",
"X",
")",
")",
"elif",
"self",
".",
"normalization",
"==",
"\"zscore\"",
":",
"self",
".",
"Xnorm",
"=",
"sklearn",
".",
"preprocessing",
".",
"scale",
"(",
"self",
".",
"X",
",",
"axis",
"=",
"0",
",",
"with_mean",
"=",
"True",
",",
"with_std",
"=",
"True",
",",
"copy",
"=",
"True",
")",
"else",
":",
"self",
".",
"Xnorm",
"=",
"np",
".",
"array",
"(",
"self",
".",
"X",
")"
]
| Internally assigns the input data and normalizes it
according to the user's specifications
@ In, X, an m-by-n array of values specifying m
n-dimensional samples
@ In, Y, a m vector of values specifying the output
responses corresponding to the m samples specified by X
@ In, w, an optional m vector of values specifying the
weights associated to each of the m samples used. Default of
None means all points will be equally weighted | [
"Internally",
"assigns",
"the",
"input",
"data",
"and",
"normalizes",
"it",
"according",
"to",
"the",
"user",
"s",
"specifications"
]
| 4be598d51c4e4043b73d4ad44beed6d289e2f088 | https://github.com/maljovec/topopy/blob/4be598d51c4e4043b73d4ad44beed6d289e2f088/topopy/TopologicalObject.py#L168-L198 | train |
maljovec/topopy | topopy/TopologicalObject.py | TopologicalObject.build | def build(self, X, Y, w=None, edges=None):
""" Assigns data to this object and builds the requested topological
structure
@ In, X, an m-by-n array of values specifying m
n-dimensional samples
@ In, Y, a m vector of values specifying the output
responses corresponding to the m samples specified by X
@ In, w, an optional m vector of values specifying the
weights associated to each of the m samples used. Default of
None means all points will be equally weighted
@ In, edges, an optional list of custom edges to use as a
starting point for pruning, or in place of a computed graph.
"""
self.reset()
if X is None or Y is None:
return
self.__set_data(X, Y, w)
if self.debug:
sys.stdout.write("Graph Preparation: ")
start = time.clock()
self.graph_rep = nglpy.Graph(
self.Xnorm,
self.graph,
self.max_neighbors,
self.beta,
connect=self.connect,
)
if self.debug:
end = time.clock()
sys.stdout.write("%f s\n" % (end - start)) | python | def build(self, X, Y, w=None, edges=None):
""" Assigns data to this object and builds the requested topological
structure
@ In, X, an m-by-n array of values specifying m
n-dimensional samples
@ In, Y, a m vector of values specifying the output
responses corresponding to the m samples specified by X
@ In, w, an optional m vector of values specifying the
weights associated to each of the m samples used. Default of
None means all points will be equally weighted
@ In, edges, an optional list of custom edges to use as a
starting point for pruning, or in place of a computed graph.
"""
self.reset()
if X is None or Y is None:
return
self.__set_data(X, Y, w)
if self.debug:
sys.stdout.write("Graph Preparation: ")
start = time.clock()
self.graph_rep = nglpy.Graph(
self.Xnorm,
self.graph,
self.max_neighbors,
self.beta,
connect=self.connect,
)
if self.debug:
end = time.clock()
sys.stdout.write("%f s\n" % (end - start)) | [
"def",
"build",
"(",
"self",
",",
"X",
",",
"Y",
",",
"w",
"=",
"None",
",",
"edges",
"=",
"None",
")",
":",
"self",
".",
"reset",
"(",
")",
"if",
"X",
"is",
"None",
"or",
"Y",
"is",
"None",
":",
"return",
"self",
".",
"__set_data",
"(",
"X",
",",
"Y",
",",
"w",
")",
"if",
"self",
".",
"debug",
":",
"sys",
".",
"stdout",
".",
"write",
"(",
"\"Graph Preparation: \"",
")",
"start",
"=",
"time",
".",
"clock",
"(",
")",
"self",
".",
"graph_rep",
"=",
"nglpy",
".",
"Graph",
"(",
"self",
".",
"Xnorm",
",",
"self",
".",
"graph",
",",
"self",
".",
"max_neighbors",
",",
"self",
".",
"beta",
",",
"connect",
"=",
"self",
".",
"connect",
",",
")",
"if",
"self",
".",
"debug",
":",
"end",
"=",
"time",
".",
"clock",
"(",
")",
"sys",
".",
"stdout",
".",
"write",
"(",
"\"%f s\\n\"",
"%",
"(",
"end",
"-",
"start",
")",
")"
]
| Assigns data to this object and builds the requested topological
structure
@ In, X, an m-by-n array of values specifying m
n-dimensional samples
@ In, Y, a m vector of values specifying the output
responses corresponding to the m samples specified by X
@ In, w, an optional m vector of values specifying the
weights associated to each of the m samples used. Default of
None means all points will be equally weighted
@ In, edges, an optional list of custom edges to use as a
starting point for pruning, or in place of a computed graph. | [
"Assigns",
"data",
"to",
"this",
"object",
"and",
"builds",
"the",
"requested",
"topological",
"structure"
]
| 4be598d51c4e4043b73d4ad44beed6d289e2f088 | https://github.com/maljovec/topopy/blob/4be598d51c4e4043b73d4ad44beed6d289e2f088/topopy/TopologicalObject.py#L200-L234 | train |
maljovec/topopy | topopy/TopologicalObject.py | TopologicalObject.load_data_and_build | def load_data_and_build(self, filename, delimiter=","):
""" Convenience function for directly working with a data file.
This opens a file and reads the data into an array, sets the
data as an nparray and list of dimnames
@ In, filename, string representing the data file
"""
data = np.genfromtxt(
filename, dtype=float, delimiter=delimiter, names=True
)
data = data.view(np.float64).reshape(data.shape + (-1,))
X = data[:, 0:-1]
Y = data[:, -1]
self.build(X=X, Y=Y) | python | def load_data_and_build(self, filename, delimiter=","):
""" Convenience function for directly working with a data file.
This opens a file and reads the data into an array, sets the
data as an nparray and list of dimnames
@ In, filename, string representing the data file
"""
data = np.genfromtxt(
filename, dtype=float, delimiter=delimiter, names=True
)
data = data.view(np.float64).reshape(data.shape + (-1,))
X = data[:, 0:-1]
Y = data[:, -1]
self.build(X=X, Y=Y) | [
"def",
"load_data_and_build",
"(",
"self",
",",
"filename",
",",
"delimiter",
"=",
"\",\"",
")",
":",
"data",
"=",
"np",
".",
"genfromtxt",
"(",
"filename",
",",
"dtype",
"=",
"float",
",",
"delimiter",
"=",
"delimiter",
",",
"names",
"=",
"True",
")",
"data",
"=",
"data",
".",
"view",
"(",
"np",
".",
"float64",
")",
".",
"reshape",
"(",
"data",
".",
"shape",
"+",
"(",
"-",
"1",
",",
")",
")",
"X",
"=",
"data",
"[",
":",
",",
"0",
":",
"-",
"1",
"]",
"Y",
"=",
"data",
"[",
":",
",",
"-",
"1",
"]",
"self",
".",
"build",
"(",
"X",
"=",
"X",
",",
"Y",
"=",
"Y",
")"
]
| Convenience function for directly working with a data file.
This opens a file and reads the data into an array, sets the
data as an nparray and list of dimnames
@ In, filename, string representing the data file | [
"Convenience",
"function",
"for",
"directly",
"working",
"with",
"a",
"data",
"file",
".",
"This",
"opens",
"a",
"file",
"and",
"reads",
"the",
"data",
"into",
"an",
"array",
"sets",
"the",
"data",
"as",
"an",
"nparray",
"and",
"list",
"of",
"dimnames"
]
| 4be598d51c4e4043b73d4ad44beed6d289e2f088 | https://github.com/maljovec/topopy/blob/4be598d51c4e4043b73d4ad44beed6d289e2f088/topopy/TopologicalObject.py#L236-L250 | train |
maljovec/topopy | topopy/TopologicalObject.py | TopologicalObject.get_normed_x | def get_normed_x(self, rows=None, cols=None):
""" Returns the normalized input data requested by the user
@ In, rows, a list of non-negative integers specifying the
row indices to return
@ In, cols, a list of non-negative integers specifying the
column indices to return
@ Out, a matrix of floating point values specifying the
normalized data values used in internal computations
filtered by the three input parameters.
"""
if rows is None:
rows = list(range(0, self.get_sample_size()))
if cols is None:
cols = list(range(0, self.get_dimensionality()))
if not hasattr(rows, "__iter__"):
rows = [rows]
rows = sorted(list(set(rows)))
retValue = self.Xnorm[rows, :]
return retValue[:, cols] | python | def get_normed_x(self, rows=None, cols=None):
""" Returns the normalized input data requested by the user
@ In, rows, a list of non-negative integers specifying the
row indices to return
@ In, cols, a list of non-negative integers specifying the
column indices to return
@ Out, a matrix of floating point values specifying the
normalized data values used in internal computations
filtered by the three input parameters.
"""
if rows is None:
rows = list(range(0, self.get_sample_size()))
if cols is None:
cols = list(range(0, self.get_dimensionality()))
if not hasattr(rows, "__iter__"):
rows = [rows]
rows = sorted(list(set(rows)))
retValue = self.Xnorm[rows, :]
return retValue[:, cols] | [
"def",
"get_normed_x",
"(",
"self",
",",
"rows",
"=",
"None",
",",
"cols",
"=",
"None",
")",
":",
"if",
"rows",
"is",
"None",
":",
"rows",
"=",
"list",
"(",
"range",
"(",
"0",
",",
"self",
".",
"get_sample_size",
"(",
")",
")",
")",
"if",
"cols",
"is",
"None",
":",
"cols",
"=",
"list",
"(",
"range",
"(",
"0",
",",
"self",
".",
"get_dimensionality",
"(",
")",
")",
")",
"if",
"not",
"hasattr",
"(",
"rows",
",",
"\"__iter__\"",
")",
":",
"rows",
"=",
"[",
"rows",
"]",
"rows",
"=",
"sorted",
"(",
"list",
"(",
"set",
"(",
"rows",
")",
")",
")",
"retValue",
"=",
"self",
".",
"Xnorm",
"[",
"rows",
",",
":",
"]",
"return",
"retValue",
"[",
":",
",",
"cols",
"]"
]
| Returns the normalized input data requested by the user
@ In, rows, a list of non-negative integers specifying the
row indices to return
@ In, cols, a list of non-negative integers specifying the
column indices to return
@ Out, a matrix of floating point values specifying the
normalized data values used in internal computations
filtered by the three input parameters. | [
"Returns",
"the",
"normalized",
"input",
"data",
"requested",
"by",
"the",
"user"
]
| 4be598d51c4e4043b73d4ad44beed6d289e2f088 | https://github.com/maljovec/topopy/blob/4be598d51c4e4043b73d4ad44beed6d289e2f088/topopy/TopologicalObject.py#L252-L272 | train |
maljovec/topopy | topopy/TopologicalObject.py | TopologicalObject.get_x | def get_x(self, rows=None, cols=None):
""" Returns the input data requested by the user
@ In, rows, a list of non-negative integers specifying the
row indices to return
@ In, cols, a list of non-negative integers specifying the
column indices to return
@ Out, a matrix of floating point values specifying the
input data values filtered by the two input parameters.
"""
if rows is None:
rows = list(range(0, self.get_sample_size()))
if cols is None:
cols = list(range(0, self.get_dimensionality()))
if not hasattr(rows, "__iter__"):
rows = [rows]
rows = sorted(list(set(rows)))
retValue = self.X[rows, :]
if len(rows) == 0:
return []
return retValue[:, cols] | python | def get_x(self, rows=None, cols=None):
""" Returns the input data requested by the user
@ In, rows, a list of non-negative integers specifying the
row indices to return
@ In, cols, a list of non-negative integers specifying the
column indices to return
@ Out, a matrix of floating point values specifying the
input data values filtered by the two input parameters.
"""
if rows is None:
rows = list(range(0, self.get_sample_size()))
if cols is None:
cols = list(range(0, self.get_dimensionality()))
if not hasattr(rows, "__iter__"):
rows = [rows]
rows = sorted(list(set(rows)))
retValue = self.X[rows, :]
if len(rows) == 0:
return []
return retValue[:, cols] | [
"def",
"get_x",
"(",
"self",
",",
"rows",
"=",
"None",
",",
"cols",
"=",
"None",
")",
":",
"if",
"rows",
"is",
"None",
":",
"rows",
"=",
"list",
"(",
"range",
"(",
"0",
",",
"self",
".",
"get_sample_size",
"(",
")",
")",
")",
"if",
"cols",
"is",
"None",
":",
"cols",
"=",
"list",
"(",
"range",
"(",
"0",
",",
"self",
".",
"get_dimensionality",
"(",
")",
")",
")",
"if",
"not",
"hasattr",
"(",
"rows",
",",
"\"__iter__\"",
")",
":",
"rows",
"=",
"[",
"rows",
"]",
"rows",
"=",
"sorted",
"(",
"list",
"(",
"set",
"(",
"rows",
")",
")",
")",
"retValue",
"=",
"self",
".",
"X",
"[",
"rows",
",",
":",
"]",
"if",
"len",
"(",
"rows",
")",
"==",
"0",
":",
"return",
"[",
"]",
"return",
"retValue",
"[",
":",
",",
"cols",
"]"
]
| Returns the input data requested by the user
@ In, rows, a list of non-negative integers specifying the
row indices to return
@ In, cols, a list of non-negative integers specifying the
column indices to return
@ Out, a matrix of floating point values specifying the
input data values filtered by the two input parameters. | [
"Returns",
"the",
"input",
"data",
"requested",
"by",
"the",
"user"
]
| 4be598d51c4e4043b73d4ad44beed6d289e2f088 | https://github.com/maljovec/topopy/blob/4be598d51c4e4043b73d4ad44beed6d289e2f088/topopy/TopologicalObject.py#L274-L295 | train |
maljovec/topopy | topopy/TopologicalObject.py | TopologicalObject.get_y | def get_y(self, indices=None):
""" Returns the output data requested by the user
@ In, indices, a list of non-negative integers specifying
the row indices to return
@ Out, an nparray of floating point values specifying the output
data values filtered by the indices input parameter.
"""
if indices is None:
indices = list(range(0, self.get_sample_size()))
else:
if not hasattr(indices, "__iter__"):
indices = [indices]
indices = sorted(list(set(indices)))
if len(indices) == 0:
return []
return self.Y[indices] | python | def get_y(self, indices=None):
""" Returns the output data requested by the user
@ In, indices, a list of non-negative integers specifying
the row indices to return
@ Out, an nparray of floating point values specifying the output
data values filtered by the indices input parameter.
"""
if indices is None:
indices = list(range(0, self.get_sample_size()))
else:
if not hasattr(indices, "__iter__"):
indices = [indices]
indices = sorted(list(set(indices)))
if len(indices) == 0:
return []
return self.Y[indices] | [
"def",
"get_y",
"(",
"self",
",",
"indices",
"=",
"None",
")",
":",
"if",
"indices",
"is",
"None",
":",
"indices",
"=",
"list",
"(",
"range",
"(",
"0",
",",
"self",
".",
"get_sample_size",
"(",
")",
")",
")",
"else",
":",
"if",
"not",
"hasattr",
"(",
"indices",
",",
"\"__iter__\"",
")",
":",
"indices",
"=",
"[",
"indices",
"]",
"indices",
"=",
"sorted",
"(",
"list",
"(",
"set",
"(",
"indices",
")",
")",
")",
"if",
"len",
"(",
"indices",
")",
"==",
"0",
":",
"return",
"[",
"]",
"return",
"self",
".",
"Y",
"[",
"indices",
"]"
]
| Returns the output data requested by the user
@ In, indices, a list of non-negative integers specifying
the row indices to return
@ Out, an nparray of floating point values specifying the output
data values filtered by the indices input parameter. | [
"Returns",
"the",
"output",
"data",
"requested",
"by",
"the",
"user"
]
| 4be598d51c4e4043b73d4ad44beed6d289e2f088 | https://github.com/maljovec/topopy/blob/4be598d51c4e4043b73d4ad44beed6d289e2f088/topopy/TopologicalObject.py#L297-L313 | train |
maljovec/topopy | topopy/TopologicalObject.py | TopologicalObject.get_weights | def get_weights(self, indices=None):
""" Returns the weights requested by the user
@ In, indices, a list of non-negative integers specifying
the row indices to return
@ Out, a list of floating point values specifying the
weights associated to the input data rows filtered by the
indices input parameter.
"""
if indices is None:
indices = list(range(0, self.get_sample_size()))
else:
indices = sorted(list(set(indices)))
if len(indices) == 0:
return []
return self.w[indices] | python | def get_weights(self, indices=None):
""" Returns the weights requested by the user
@ In, indices, a list of non-negative integers specifying
the row indices to return
@ Out, a list of floating point values specifying the
weights associated to the input data rows filtered by the
indices input parameter.
"""
if indices is None:
indices = list(range(0, self.get_sample_size()))
else:
indices = sorted(list(set(indices)))
if len(indices) == 0:
return []
return self.w[indices] | [
"def",
"get_weights",
"(",
"self",
",",
"indices",
"=",
"None",
")",
":",
"if",
"indices",
"is",
"None",
":",
"indices",
"=",
"list",
"(",
"range",
"(",
"0",
",",
"self",
".",
"get_sample_size",
"(",
")",
")",
")",
"else",
":",
"indices",
"=",
"sorted",
"(",
"list",
"(",
"set",
"(",
"indices",
")",
")",
")",
"if",
"len",
"(",
"indices",
")",
"==",
"0",
":",
"return",
"[",
"]",
"return",
"self",
".",
"w",
"[",
"indices",
"]"
]
| Returns the weights requested by the user
@ In, indices, a list of non-negative integers specifying
the row indices to return
@ Out, a list of floating point values specifying the
weights associated to the input data rows filtered by the
indices input parameter. | [
"Returns",
"the",
"weights",
"requested",
"by",
"the",
"user"
]
| 4be598d51c4e4043b73d4ad44beed6d289e2f088 | https://github.com/maljovec/topopy/blob/4be598d51c4e4043b73d4ad44beed6d289e2f088/topopy/TopologicalObject.py#L315-L330 | train |
maljovec/topopy | topopy/TopologicalObject.py | TopologicalObject.check_duplicates | def check_duplicates(self):
""" Function to test whether duplicates exist in the input or
output space. First, if an aggregator function has been
specified, the domain space duplicates will be consolidated
using the function to generate a new range value for that
shared point. Otherwise, it will raise a ValueError.
The function will raise a warning if duplicates exist in the
output space
@Out, None
"""
if self.aggregator is not None:
X, Y = TopologicalObject.aggregate_duplicates(
self.X, self.Y, self.aggregator
)
self.X = X
self.Y = Y
temp_x = self.X.round(decimals=TopologicalObject.precision)
unique_xs = len(np.unique(temp_x, axis=0))
# unique_ys = len(np.unique(self.Y, axis=0))
# if len(self.Y) != unique_ys:
# warnings.warn('Range space has duplicates. Simulation of '
# 'simplicity may help, but artificial noise may '
# 'occur in flat regions of the domain. Sample size:'
# '{} vs. Unique Records: {}'.format(len(self.Y),
# unique_ys))
if len(self.X) != unique_xs:
raise ValueError(
"Domain space has duplicates. Try using an "
"aggregator function to consolidate duplicates "
"into a single sample with one range value. "
"e.g., " + self.__class__.__name__ + "(aggregator='max'). "
"\n\tNumber of "
"Records: {}\n\tNumber of Unique Records: {}\n".format(
len(self.X), unique_xs
)
) | python | def check_duplicates(self):
""" Function to test whether duplicates exist in the input or
output space. First, if an aggregator function has been
specified, the domain space duplicates will be consolidated
using the function to generate a new range value for that
shared point. Otherwise, it will raise a ValueError.
The function will raise a warning if duplicates exist in the
output space
@Out, None
"""
if self.aggregator is not None:
X, Y = TopologicalObject.aggregate_duplicates(
self.X, self.Y, self.aggregator
)
self.X = X
self.Y = Y
temp_x = self.X.round(decimals=TopologicalObject.precision)
unique_xs = len(np.unique(temp_x, axis=0))
# unique_ys = len(np.unique(self.Y, axis=0))
# if len(self.Y) != unique_ys:
# warnings.warn('Range space has duplicates. Simulation of '
# 'simplicity may help, but artificial noise may '
# 'occur in flat regions of the domain. Sample size:'
# '{} vs. Unique Records: {}'.format(len(self.Y),
# unique_ys))
if len(self.X) != unique_xs:
raise ValueError(
"Domain space has duplicates. Try using an "
"aggregator function to consolidate duplicates "
"into a single sample with one range value. "
"e.g., " + self.__class__.__name__ + "(aggregator='max'). "
"\n\tNumber of "
"Records: {}\n\tNumber of Unique Records: {}\n".format(
len(self.X), unique_xs
)
) | [
"def",
"check_duplicates",
"(",
"self",
")",
":",
"if",
"self",
".",
"aggregator",
"is",
"not",
"None",
":",
"X",
",",
"Y",
"=",
"TopologicalObject",
".",
"aggregate_duplicates",
"(",
"self",
".",
"X",
",",
"self",
".",
"Y",
",",
"self",
".",
"aggregator",
")",
"self",
".",
"X",
"=",
"X",
"self",
".",
"Y",
"=",
"Y",
"temp_x",
"=",
"self",
".",
"X",
".",
"round",
"(",
"decimals",
"=",
"TopologicalObject",
".",
"precision",
")",
"unique_xs",
"=",
"len",
"(",
"np",
".",
"unique",
"(",
"temp_x",
",",
"axis",
"=",
"0",
")",
")",
"# unique_ys = len(np.unique(self.Y, axis=0))",
"# if len(self.Y) != unique_ys:",
"# warnings.warn('Range space has duplicates. Simulation of '",
"# 'simplicity may help, but artificial noise may '",
"# 'occur in flat regions of the domain. Sample size:'",
"# '{} vs. Unique Records: {}'.format(len(self.Y),",
"# unique_ys))",
"if",
"len",
"(",
"self",
".",
"X",
")",
"!=",
"unique_xs",
":",
"raise",
"ValueError",
"(",
"\"Domain space has duplicates. Try using an \"",
"\"aggregator function to consolidate duplicates \"",
"\"into a single sample with one range value. \"",
"\"e.g., \"",
"+",
"self",
".",
"__class__",
".",
"__name__",
"+",
"\"(aggregator='max'). \"",
"\"\\n\\tNumber of \"",
"\"Records: {}\\n\\tNumber of Unique Records: {}\\n\"",
".",
"format",
"(",
"len",
"(",
"self",
".",
"X",
")",
",",
"unique_xs",
")",
")"
]
| Function to test whether duplicates exist in the input or
output space. First, if an aggregator function has been
specified, the domain space duplicates will be consolidated
using the function to generate a new range value for that
shared point. Otherwise, it will raise a ValueError.
The function will raise a warning if duplicates exist in the
output space
@Out, None | [
"Function",
"to",
"test",
"whether",
"duplicates",
"exist",
"in",
"the",
"input",
"or",
"output",
"space",
".",
"First",
"if",
"an",
"aggregator",
"function",
"has",
"been",
"specified",
"the",
"domain",
"space",
"duplicates",
"will",
"be",
"consolidated",
"using",
"the",
"function",
"to",
"generate",
"a",
"new",
"range",
"value",
"for",
"that",
"shared",
"point",
".",
"Otherwise",
"it",
"will",
"raise",
"a",
"ValueError",
".",
"The",
"function",
"will",
"raise",
"a",
"warning",
"if",
"duplicates",
"exist",
"in",
"the",
"output",
"space"
]
| 4be598d51c4e4043b73d4ad44beed6d289e2f088 | https://github.com/maljovec/topopy/blob/4be598d51c4e4043b73d4ad44beed6d289e2f088/topopy/TopologicalObject.py#L353-L392 | train |
bskinn/pent | pent/utils.py | column_stack_2d | def column_stack_2d(data):
"""Perform column-stacking on a list of 2d data blocks."""
return list(list(itt.chain.from_iterable(_)) for _ in zip(*data)) | python | def column_stack_2d(data):
"""Perform column-stacking on a list of 2d data blocks."""
return list(list(itt.chain.from_iterable(_)) for _ in zip(*data)) | [
"def",
"column_stack_2d",
"(",
"data",
")",
":",
"return",
"list",
"(",
"list",
"(",
"itt",
".",
"chain",
".",
"from_iterable",
"(",
"_",
")",
")",
"for",
"_",
"in",
"zip",
"(",
"*",
"data",
")",
")"
]
| Perform column-stacking on a list of 2d data blocks. | [
"Perform",
"column",
"-",
"stacking",
"on",
"a",
"list",
"of",
"2d",
"data",
"blocks",
"."
]
| 7a81e55f46bc3aed3f09d96449d59a770b4730c2 | https://github.com/bskinn/pent/blob/7a81e55f46bc3aed3f09d96449d59a770b4730c2/pent/utils.py#L30-L32 | train |
lsst-sqre/documenteer | documenteer/stackdocs/rootdiscovery.py | discover_conf_py_directory | def discover_conf_py_directory(initial_dir):
"""Discover the directory containing the conf.py file.
This function is useful for building stack docs since it will look in
the current working directory and all parents.
Parameters
----------
initial_dir : `str`
The inititial directory to search from. In practice, this is often the
directory that the user is running the stack-docs CLI from.
Returns
-------
root_dir : `str`
The root documentation directory containing ``conf.py``.
Raises
------
FileNotFoundError
Raised if a ``conf.py`` file is not found in the initial directory,
or any parents.
"""
# Create an absolute Path to work with
initial_dir = pathlib.Path(initial_dir).resolve()
# Search upwards until a conf.py is found
try:
return str(_search_parents(initial_dir))
except FileNotFoundError:
raise | python | def discover_conf_py_directory(initial_dir):
"""Discover the directory containing the conf.py file.
This function is useful for building stack docs since it will look in
the current working directory and all parents.
Parameters
----------
initial_dir : `str`
The inititial directory to search from. In practice, this is often the
directory that the user is running the stack-docs CLI from.
Returns
-------
root_dir : `str`
The root documentation directory containing ``conf.py``.
Raises
------
FileNotFoundError
Raised if a ``conf.py`` file is not found in the initial directory,
or any parents.
"""
# Create an absolute Path to work with
initial_dir = pathlib.Path(initial_dir).resolve()
# Search upwards until a conf.py is found
try:
return str(_search_parents(initial_dir))
except FileNotFoundError:
raise | [
"def",
"discover_conf_py_directory",
"(",
"initial_dir",
")",
":",
"# Create an absolute Path to work with",
"initial_dir",
"=",
"pathlib",
".",
"Path",
"(",
"initial_dir",
")",
".",
"resolve",
"(",
")",
"# Search upwards until a conf.py is found",
"try",
":",
"return",
"str",
"(",
"_search_parents",
"(",
"initial_dir",
")",
")",
"except",
"FileNotFoundError",
":",
"raise"
]
| Discover the directory containing the conf.py file.
This function is useful for building stack docs since it will look in
the current working directory and all parents.
Parameters
----------
initial_dir : `str`
The inititial directory to search from. In practice, this is often the
directory that the user is running the stack-docs CLI from.
Returns
-------
root_dir : `str`
The root documentation directory containing ``conf.py``.
Raises
------
FileNotFoundError
Raised if a ``conf.py`` file is not found in the initial directory,
or any parents. | [
"Discover",
"the",
"directory",
"containing",
"the",
"conf",
".",
"py",
"file",
"."
]
| 75f02901a80042b28d074df1cc1dca32eb8e38c8 | https://github.com/lsst-sqre/documenteer/blob/75f02901a80042b28d074df1cc1dca32eb8e38c8/documenteer/stackdocs/rootdiscovery.py#L51-L81 | train |
lsst-sqre/documenteer | documenteer/stackdocs/rootdiscovery.py | _search_parents | def _search_parents(initial_dir):
"""Search the initial and parent directories for a ``conf.py`` Sphinx
configuration file that represents the root of a Sphinx project.
Returns
-------
root_dir : `pathlib.Path`
Directory path containing a ``conf.py`` file.
Raises
------
FileNotFoundError
Raised if a ``conf.py`` file is not found in the initial directory
or any parents.
"""
root_paths = ('.', '/')
parent = pathlib.Path(initial_dir)
while True:
if _has_conf_py(parent):
return parent
if str(parent) in root_paths:
break
parent = parent.parent
msg = (
"Cannot detect a conf.py Sphinx configuration file from {!s}. "
"Are you inside a Sphinx documenation repository?"
).format(initial_dir)
raise FileNotFoundError(msg) | python | def _search_parents(initial_dir):
"""Search the initial and parent directories for a ``conf.py`` Sphinx
configuration file that represents the root of a Sphinx project.
Returns
-------
root_dir : `pathlib.Path`
Directory path containing a ``conf.py`` file.
Raises
------
FileNotFoundError
Raised if a ``conf.py`` file is not found in the initial directory
or any parents.
"""
root_paths = ('.', '/')
parent = pathlib.Path(initial_dir)
while True:
if _has_conf_py(parent):
return parent
if str(parent) in root_paths:
break
parent = parent.parent
msg = (
"Cannot detect a conf.py Sphinx configuration file from {!s}. "
"Are you inside a Sphinx documenation repository?"
).format(initial_dir)
raise FileNotFoundError(msg) | [
"def",
"_search_parents",
"(",
"initial_dir",
")",
":",
"root_paths",
"=",
"(",
"'.'",
",",
"'/'",
")",
"parent",
"=",
"pathlib",
".",
"Path",
"(",
"initial_dir",
")",
"while",
"True",
":",
"if",
"_has_conf_py",
"(",
"parent",
")",
":",
"return",
"parent",
"if",
"str",
"(",
"parent",
")",
"in",
"root_paths",
":",
"break",
"parent",
"=",
"parent",
".",
"parent",
"msg",
"=",
"(",
"\"Cannot detect a conf.py Sphinx configuration file from {!s}. \"",
"\"Are you inside a Sphinx documenation repository?\"",
")",
".",
"format",
"(",
"initial_dir",
")",
"raise",
"FileNotFoundError",
"(",
"msg",
")"
]
| Search the initial and parent directories for a ``conf.py`` Sphinx
configuration file that represents the root of a Sphinx project.
Returns
-------
root_dir : `pathlib.Path`
Directory path containing a ``conf.py`` file.
Raises
------
FileNotFoundError
Raised if a ``conf.py`` file is not found in the initial directory
or any parents. | [
"Search",
"the",
"initial",
"and",
"parent",
"directories",
"for",
"a",
"conf",
".",
"py",
"Sphinx",
"configuration",
"file",
"that",
"represents",
"the",
"root",
"of",
"a",
"Sphinx",
"project",
"."
]
| 75f02901a80042b28d074df1cc1dca32eb8e38c8 | https://github.com/lsst-sqre/documenteer/blob/75f02901a80042b28d074df1cc1dca32eb8e38c8/documenteer/stackdocs/rootdiscovery.py#L91-L118 | train |
micolous/python-slackrealtime | src/slackrealtime/session.py | request_session | def request_session(token, url=None):
"""
Requests a WebSocket session for the Real-Time Messaging API.
Returns a SessionMetadata object containing the information retrieved from
the API call.
"""
if url is None:
api = SlackApi()
else:
api = SlackApi(url)
response = api.rtm.start(token=token)
return SessionMetadata(response, api, token) | python | def request_session(token, url=None):
"""
Requests a WebSocket session for the Real-Time Messaging API.
Returns a SessionMetadata object containing the information retrieved from
the API call.
"""
if url is None:
api = SlackApi()
else:
api = SlackApi(url)
response = api.rtm.start(token=token)
return SessionMetadata(response, api, token) | [
"def",
"request_session",
"(",
"token",
",",
"url",
"=",
"None",
")",
":",
"if",
"url",
"is",
"None",
":",
"api",
"=",
"SlackApi",
"(",
")",
"else",
":",
"api",
"=",
"SlackApi",
"(",
"url",
")",
"response",
"=",
"api",
".",
"rtm",
".",
"start",
"(",
"token",
"=",
"token",
")",
"return",
"SessionMetadata",
"(",
"response",
",",
"api",
",",
"token",
")"
]
| Requests a WebSocket session for the Real-Time Messaging API.
Returns a SessionMetadata object containing the information retrieved from
the API call. | [
"Requests",
"a",
"WebSocket",
"session",
"for",
"the",
"Real",
"-",
"Time",
"Messaging",
"API",
".",
"Returns",
"a",
"SessionMetadata",
"object",
"containing",
"the",
"information",
"retrieved",
"from",
"the",
"API",
"call",
"."
]
| e9c94416f979a6582110ebba09c147de2bfe20a1 | https://github.com/micolous/python-slackrealtime/blob/e9c94416f979a6582110ebba09c147de2bfe20a1/src/slackrealtime/session.py#L208-L221 | train |
micolous/python-slackrealtime | src/slackrealtime/session.py | SessionMetadata._find_resource_by_key | def _find_resource_by_key(self, resource_list, key, value):
"""
Finds a resource by key, first case insensitive match.
Returns tuple of (key, resource)
Raises KeyError if the given key cannot be found.
"""
original = value
value = unicode(value.upper())
for k, resource in resource_list.iteritems():
if key in resource and resource[key].upper() == value:
return k, resource
raise KeyError, original | python | def _find_resource_by_key(self, resource_list, key, value):
"""
Finds a resource by key, first case insensitive match.
Returns tuple of (key, resource)
Raises KeyError if the given key cannot be found.
"""
original = value
value = unicode(value.upper())
for k, resource in resource_list.iteritems():
if key in resource and resource[key].upper() == value:
return k, resource
raise KeyError, original | [
"def",
"_find_resource_by_key",
"(",
"self",
",",
"resource_list",
",",
"key",
",",
"value",
")",
":",
"original",
"=",
"value",
"value",
"=",
"unicode",
"(",
"value",
".",
"upper",
"(",
")",
")",
"for",
"k",
",",
"resource",
"in",
"resource_list",
".",
"iteritems",
"(",
")",
":",
"if",
"key",
"in",
"resource",
"and",
"resource",
"[",
"key",
"]",
".",
"upper",
"(",
")",
"==",
"value",
":",
"return",
"k",
",",
"resource",
"raise",
"KeyError",
",",
"original"
]
| Finds a resource by key, first case insensitive match.
Returns tuple of (key, resource)
Raises KeyError if the given key cannot be found. | [
"Finds",
"a",
"resource",
"by",
"key",
"first",
"case",
"insensitive",
"match",
"."
]
| e9c94416f979a6582110ebba09c147de2bfe20a1 | https://github.com/micolous/python-slackrealtime/blob/e9c94416f979a6582110ebba09c147de2bfe20a1/src/slackrealtime/session.py#L61-L75 | train |
micolous/python-slackrealtime | src/slackrealtime/session.py | SessionMetadata.find_im_by_user_name | def find_im_by_user_name(self, name, auto_create=True):
"""
Finds the ID of the IM with a particular user by name, with the option
to automatically create a new channel if it doesn't exist.
"""
uid = self.find_user_by_name(name)[0]
try:
return self.find_im_by_user_id(uid)
except KeyError:
# IM does not exist, create it?
if auto_create:
response = self.api.im.open(token=self.token, user=uid)
return response[u'channel'][u'id']
else:
raise | python | def find_im_by_user_name(self, name, auto_create=True):
"""
Finds the ID of the IM with a particular user by name, with the option
to automatically create a new channel if it doesn't exist.
"""
uid = self.find_user_by_name(name)[0]
try:
return self.find_im_by_user_id(uid)
except KeyError:
# IM does not exist, create it?
if auto_create:
response = self.api.im.open(token=self.token, user=uid)
return response[u'channel'][u'id']
else:
raise | [
"def",
"find_im_by_user_name",
"(",
"self",
",",
"name",
",",
"auto_create",
"=",
"True",
")",
":",
"uid",
"=",
"self",
".",
"find_user_by_name",
"(",
"name",
")",
"[",
"0",
"]",
"try",
":",
"return",
"self",
".",
"find_im_by_user_id",
"(",
"uid",
")",
"except",
"KeyError",
":",
"# IM does not exist, create it?",
"if",
"auto_create",
":",
"response",
"=",
"self",
".",
"api",
".",
"im",
".",
"open",
"(",
"token",
"=",
"self",
".",
"token",
",",
"user",
"=",
"uid",
")",
"return",
"response",
"[",
"u'channel'",
"]",
"[",
"u'id'",
"]",
"else",
":",
"raise"
]
| Finds the ID of the IM with a particular user by name, with the option
to automatically create a new channel if it doesn't exist. | [
"Finds",
"the",
"ID",
"of",
"the",
"IM",
"with",
"a",
"particular",
"user",
"by",
"name",
"with",
"the",
"option",
"to",
"automatically",
"create",
"a",
"new",
"channel",
"if",
"it",
"doesn",
"t",
"exist",
"."
]
| e9c94416f979a6582110ebba09c147de2bfe20a1 | https://github.com/micolous/python-slackrealtime/blob/e9c94416f979a6582110ebba09c147de2bfe20a1/src/slackrealtime/session.py#L92-L106 | train |
micolous/python-slackrealtime | src/slackrealtime/session.py | SessionMetadata.update | def update(self, event):
"""
All messages from the Protocol get passed through this method. This
allows the client to have an up-to-date state for the client.
However, this method doesn't actually update right away. Instead, the
acutal update happens in another thread, potentially later, in order to
allow user code to handle the event faster.
"""
# Create our own copy of the event data, as we'll be pushing that to
# another data structure and we don't want it mangled by user code later
# on.
event = event.copy()
# Now just defer the work to later.
reactor.callInThread(self._update_deferred, event) | python | def update(self, event):
"""
All messages from the Protocol get passed through this method. This
allows the client to have an up-to-date state for the client.
However, this method doesn't actually update right away. Instead, the
acutal update happens in another thread, potentially later, in order to
allow user code to handle the event faster.
"""
# Create our own copy of the event data, as we'll be pushing that to
# another data structure and we don't want it mangled by user code later
# on.
event = event.copy()
# Now just defer the work to later.
reactor.callInThread(self._update_deferred, event) | [
"def",
"update",
"(",
"self",
",",
"event",
")",
":",
"# Create our own copy of the event data, as we'll be pushing that to",
"# another data structure and we don't want it mangled by user code later",
"# on.",
"event",
"=",
"event",
".",
"copy",
"(",
")",
"# Now just defer the work to later.",
"reactor",
".",
"callInThread",
"(",
"self",
".",
"_update_deferred",
",",
"event",
")"
]
| All messages from the Protocol get passed through this method. This
allows the client to have an up-to-date state for the client.
However, this method doesn't actually update right away. Instead, the
acutal update happens in another thread, potentially later, in order to
allow user code to handle the event faster. | [
"All",
"messages",
"from",
"the",
"Protocol",
"get",
"passed",
"through",
"this",
"method",
".",
"This",
"allows",
"the",
"client",
"to",
"have",
"an",
"up",
"-",
"to",
"-",
"date",
"state",
"for",
"the",
"client",
".",
"However",
"this",
"method",
"doesn",
"t",
"actually",
"update",
"right",
"away",
".",
"Instead",
"the",
"acutal",
"update",
"happens",
"in",
"another",
"thread",
"potentially",
"later",
"in",
"order",
"to",
"allow",
"user",
"code",
"to",
"handle",
"the",
"event",
"faster",
"."
]
| e9c94416f979a6582110ebba09c147de2bfe20a1 | https://github.com/micolous/python-slackrealtime/blob/e9c94416f979a6582110ebba09c147de2bfe20a1/src/slackrealtime/session.py#L108-L125 | train |
fkarb/xltable | xltable/chart.py | Chart.iter_series | def iter_series(self, workbook, row, col):
"""
Yield series dictionaries with values resolved to the final excel formulas.
"""
for series in self.__series:
series = dict(series)
series["values"] = series["values"].get_formula(workbook, row, col)
if "categories" in series:
series["categories"] = series["categories"].get_formula(workbook, row, col)
yield series | python | def iter_series(self, workbook, row, col):
"""
Yield series dictionaries with values resolved to the final excel formulas.
"""
for series in self.__series:
series = dict(series)
series["values"] = series["values"].get_formula(workbook, row, col)
if "categories" in series:
series["categories"] = series["categories"].get_formula(workbook, row, col)
yield series | [
"def",
"iter_series",
"(",
"self",
",",
"workbook",
",",
"row",
",",
"col",
")",
":",
"for",
"series",
"in",
"self",
".",
"__series",
":",
"series",
"=",
"dict",
"(",
"series",
")",
"series",
"[",
"\"values\"",
"]",
"=",
"series",
"[",
"\"values\"",
"]",
".",
"get_formula",
"(",
"workbook",
",",
"row",
",",
"col",
")",
"if",
"\"categories\"",
"in",
"series",
":",
"series",
"[",
"\"categories\"",
"]",
"=",
"series",
"[",
"\"categories\"",
"]",
".",
"get_formula",
"(",
"workbook",
",",
"row",
",",
"col",
")",
"yield",
"series"
]
| Yield series dictionaries with values resolved to the final excel formulas. | [
"Yield",
"series",
"dictionaries",
"with",
"values",
"resolved",
"to",
"the",
"final",
"excel",
"formulas",
"."
]
| 7a592642d27ad5ee90d2aa8c26338abaa9d84bea | https://github.com/fkarb/xltable/blob/7a592642d27ad5ee90d2aa8c26338abaa9d84bea/xltable/chart.py#L85-L94 | train |
gmdzy2010/dingtalk_sdk_gmdzy2010 | dingtalk_sdk_gmdzy2010/user_request.py | DeptUserRequest.get_userinfo | def get_userinfo(self):
"""Method to get current user's name, mobile, email and position."""
wanted_fields = ["name", "mobile", "orgEmail", "position", "avatar"]
userinfo = {k: self.json_response.get(k, None) for k in wanted_fields}
return userinfo | python | def get_userinfo(self):
"""Method to get current user's name, mobile, email and position."""
wanted_fields = ["name", "mobile", "orgEmail", "position", "avatar"]
userinfo = {k: self.json_response.get(k, None) for k in wanted_fields}
return userinfo | [
"def",
"get_userinfo",
"(",
"self",
")",
":",
"wanted_fields",
"=",
"[",
"\"name\"",
",",
"\"mobile\"",
",",
"\"orgEmail\"",
",",
"\"position\"",
",",
"\"avatar\"",
"]",
"userinfo",
"=",
"{",
"k",
":",
"self",
".",
"json_response",
".",
"get",
"(",
"k",
",",
"None",
")",
"for",
"k",
"in",
"wanted_fields",
"}",
"return",
"userinfo"
]
| Method to get current user's name, mobile, email and position. | [
"Method",
"to",
"get",
"current",
"user",
"s",
"name",
"mobile",
"email",
"and",
"position",
"."
]
| b06cb1f78f89be9554dcb6101af8bc72718a9ecd | https://github.com/gmdzy2010/dingtalk_sdk_gmdzy2010/blob/b06cb1f78f89be9554dcb6101af8bc72718a9ecd/dingtalk_sdk_gmdzy2010/user_request.py#L30-L34 | train |
gmdzy2010/dingtalk_sdk_gmdzy2010 | dingtalk_sdk_gmdzy2010/user_request.py | AdminUsersRequest.get_admin_ids | def get_admin_ids(self):
"""Method to get the administrator id list."""
admins = self.json_response.get("admin_list", None)
admin_ids = [admin_id for admin_id in admins["userid"]]
return admin_ids | python | def get_admin_ids(self):
"""Method to get the administrator id list."""
admins = self.json_response.get("admin_list", None)
admin_ids = [admin_id for admin_id in admins["userid"]]
return admin_ids | [
"def",
"get_admin_ids",
"(",
"self",
")",
":",
"admins",
"=",
"self",
".",
"json_response",
".",
"get",
"(",
"\"admin_list\"",
",",
"None",
")",
"admin_ids",
"=",
"[",
"admin_id",
"for",
"admin_id",
"in",
"admins",
"[",
"\"userid\"",
"]",
"]",
"return",
"admin_ids"
]
| Method to get the administrator id list. | [
"Method",
"to",
"get",
"the",
"administrator",
"id",
"list",
"."
]
| b06cb1f78f89be9554dcb6101af8bc72718a9ecd | https://github.com/gmdzy2010/dingtalk_sdk_gmdzy2010/blob/b06cb1f78f89be9554dcb6101af8bc72718a9ecd/dingtalk_sdk_gmdzy2010/user_request.py#L54-L58 | train |
zsimic/runez | src/runez/program.py | run | def run(program, *args, **kwargs):
"""Run 'program' with 'args'"""
args = flattened(args, split=SHELL)
full_path = which(program)
logger = kwargs.pop("logger", LOG.debug)
fatal = kwargs.pop("fatal", True)
dryrun = kwargs.pop("dryrun", is_dryrun())
include_error = kwargs.pop("include_error", False)
message = "Would run" if dryrun else "Running"
message = "%s: %s %s" % (message, short(full_path or program), represented_args(args))
if logger:
logger(message)
if dryrun:
return message
if not full_path:
return abort("%s is not installed", short(program), fatal=fatal)
stdout = kwargs.pop("stdout", subprocess.PIPE)
stderr = kwargs.pop("stderr", subprocess.PIPE)
args = [full_path] + args
try:
path_env = kwargs.pop("path_env", None)
if path_env:
kwargs["env"] = added_env_paths(path_env, env=kwargs.get("env"))
p = subprocess.Popen(args, stdout=stdout, stderr=stderr, **kwargs) # nosec
output, err = p.communicate()
output = decode(output, strip=True)
err = decode(err, strip=True)
if p.returncode and fatal is not None:
note = ": %s\n%s" % (err, output) if output or err else ""
message = "%s exited with code %s%s" % (short(program), p.returncode, note.strip())
return abort(message, fatal=fatal)
if include_error and err:
output = "%s\n%s" % (output, err)
return output and output.strip()
except Exception as e:
return abort("%s failed: %s", short(program), e, exc_info=e, fatal=fatal) | python | def run(program, *args, **kwargs):
"""Run 'program' with 'args'"""
args = flattened(args, split=SHELL)
full_path = which(program)
logger = kwargs.pop("logger", LOG.debug)
fatal = kwargs.pop("fatal", True)
dryrun = kwargs.pop("dryrun", is_dryrun())
include_error = kwargs.pop("include_error", False)
message = "Would run" if dryrun else "Running"
message = "%s: %s %s" % (message, short(full_path or program), represented_args(args))
if logger:
logger(message)
if dryrun:
return message
if not full_path:
return abort("%s is not installed", short(program), fatal=fatal)
stdout = kwargs.pop("stdout", subprocess.PIPE)
stderr = kwargs.pop("stderr", subprocess.PIPE)
args = [full_path] + args
try:
path_env = kwargs.pop("path_env", None)
if path_env:
kwargs["env"] = added_env_paths(path_env, env=kwargs.get("env"))
p = subprocess.Popen(args, stdout=stdout, stderr=stderr, **kwargs) # nosec
output, err = p.communicate()
output = decode(output, strip=True)
err = decode(err, strip=True)
if p.returncode and fatal is not None:
note = ": %s\n%s" % (err, output) if output or err else ""
message = "%s exited with code %s%s" % (short(program), p.returncode, note.strip())
return abort(message, fatal=fatal)
if include_error and err:
output = "%s\n%s" % (output, err)
return output and output.strip()
except Exception as e:
return abort("%s failed: %s", short(program), e, exc_info=e, fatal=fatal) | [
"def",
"run",
"(",
"program",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"args",
"=",
"flattened",
"(",
"args",
",",
"split",
"=",
"SHELL",
")",
"full_path",
"=",
"which",
"(",
"program",
")",
"logger",
"=",
"kwargs",
".",
"pop",
"(",
"\"logger\"",
",",
"LOG",
".",
"debug",
")",
"fatal",
"=",
"kwargs",
".",
"pop",
"(",
"\"fatal\"",
",",
"True",
")",
"dryrun",
"=",
"kwargs",
".",
"pop",
"(",
"\"dryrun\"",
",",
"is_dryrun",
"(",
")",
")",
"include_error",
"=",
"kwargs",
".",
"pop",
"(",
"\"include_error\"",
",",
"False",
")",
"message",
"=",
"\"Would run\"",
"if",
"dryrun",
"else",
"\"Running\"",
"message",
"=",
"\"%s: %s %s\"",
"%",
"(",
"message",
",",
"short",
"(",
"full_path",
"or",
"program",
")",
",",
"represented_args",
"(",
"args",
")",
")",
"if",
"logger",
":",
"logger",
"(",
"message",
")",
"if",
"dryrun",
":",
"return",
"message",
"if",
"not",
"full_path",
":",
"return",
"abort",
"(",
"\"%s is not installed\"",
",",
"short",
"(",
"program",
")",
",",
"fatal",
"=",
"fatal",
")",
"stdout",
"=",
"kwargs",
".",
"pop",
"(",
"\"stdout\"",
",",
"subprocess",
".",
"PIPE",
")",
"stderr",
"=",
"kwargs",
".",
"pop",
"(",
"\"stderr\"",
",",
"subprocess",
".",
"PIPE",
")",
"args",
"=",
"[",
"full_path",
"]",
"+",
"args",
"try",
":",
"path_env",
"=",
"kwargs",
".",
"pop",
"(",
"\"path_env\"",
",",
"None",
")",
"if",
"path_env",
":",
"kwargs",
"[",
"\"env\"",
"]",
"=",
"added_env_paths",
"(",
"path_env",
",",
"env",
"=",
"kwargs",
".",
"get",
"(",
"\"env\"",
")",
")",
"p",
"=",
"subprocess",
".",
"Popen",
"(",
"args",
",",
"stdout",
"=",
"stdout",
",",
"stderr",
"=",
"stderr",
",",
"*",
"*",
"kwargs",
")",
"# nosec",
"output",
",",
"err",
"=",
"p",
".",
"communicate",
"(",
")",
"output",
"=",
"decode",
"(",
"output",
",",
"strip",
"=",
"True",
")",
"err",
"=",
"decode",
"(",
"err",
",",
"strip",
"=",
"True",
")",
"if",
"p",
".",
"returncode",
"and",
"fatal",
"is",
"not",
"None",
":",
"note",
"=",
"\": %s\\n%s\"",
"%",
"(",
"err",
",",
"output",
")",
"if",
"output",
"or",
"err",
"else",
"\"\"",
"message",
"=",
"\"%s exited with code %s%s\"",
"%",
"(",
"short",
"(",
"program",
")",
",",
"p",
".",
"returncode",
",",
"note",
".",
"strip",
"(",
")",
")",
"return",
"abort",
"(",
"message",
",",
"fatal",
"=",
"fatal",
")",
"if",
"include_error",
"and",
"err",
":",
"output",
"=",
"\"%s\\n%s\"",
"%",
"(",
"output",
",",
"err",
")",
"return",
"output",
"and",
"output",
".",
"strip",
"(",
")",
"except",
"Exception",
"as",
"e",
":",
"return",
"abort",
"(",
"\"%s failed: %s\"",
",",
"short",
"(",
"program",
")",
",",
"e",
",",
"exc_info",
"=",
"e",
",",
"fatal",
"=",
"fatal",
")"
]
| Run 'program' with 'args | [
"Run",
"program",
"with",
"args"
]
| 14363b719a1aae1528859a501a22d075ce0abfcc | https://github.com/zsimic/runez/blob/14363b719a1aae1528859a501a22d075ce0abfcc/src/runez/program.py#L100-L143 | train |
gmdzy2010/dingtalk_sdk_gmdzy2010 | dingtalk_sdk_gmdzy2010/department_request.py | DeptRequest.get_dept_name | def get_dept_name(self):
"""Method to get the department name"""
self.logger.info("%s\t%s" % (self.request_method, self.request_url))
return self.json_response.get("name", None) | python | def get_dept_name(self):
"""Method to get the department name"""
self.logger.info("%s\t%s" % (self.request_method, self.request_url))
return self.json_response.get("name", None) | [
"def",
"get_dept_name",
"(",
"self",
")",
":",
"self",
".",
"logger",
".",
"info",
"(",
"\"%s\\t%s\"",
"%",
"(",
"self",
".",
"request_method",
",",
"self",
".",
"request_url",
")",
")",
"return",
"self",
".",
"json_response",
".",
"get",
"(",
"\"name\"",
",",
"None",
")"
]
| Method to get the department name | [
"Method",
"to",
"get",
"the",
"department",
"name"
]
| b06cb1f78f89be9554dcb6101af8bc72718a9ecd | https://github.com/gmdzy2010/dingtalk_sdk_gmdzy2010/blob/b06cb1f78f89be9554dcb6101af8bc72718a9ecd/dingtalk_sdk_gmdzy2010/department_request.py#L22-L25 | train |
gmdzy2010/dingtalk_sdk_gmdzy2010 | dingtalk_sdk_gmdzy2010/department_request.py | DeptRequest.get_dept_manager_ids | def get_dept_manager_ids(self):
"""Method to get the id list of department manager."""
self.logger.info("%s\t%s" % (self.request_method, self.request_url))
return self.json_response.get("deptManagerUseridList", None) | python | def get_dept_manager_ids(self):
"""Method to get the id list of department manager."""
self.logger.info("%s\t%s" % (self.request_method, self.request_url))
return self.json_response.get("deptManagerUseridList", None) | [
"def",
"get_dept_manager_ids",
"(",
"self",
")",
":",
"self",
".",
"logger",
".",
"info",
"(",
"\"%s\\t%s\"",
"%",
"(",
"self",
".",
"request_method",
",",
"self",
".",
"request_url",
")",
")",
"return",
"self",
".",
"json_response",
".",
"get",
"(",
"\"deptManagerUseridList\"",
",",
"None",
")"
]
| Method to get the id list of department manager. | [
"Method",
"to",
"get",
"the",
"id",
"list",
"of",
"department",
"manager",
"."
]
| b06cb1f78f89be9554dcb6101af8bc72718a9ecd | https://github.com/gmdzy2010/dingtalk_sdk_gmdzy2010/blob/b06cb1f78f89be9554dcb6101af8bc72718a9ecd/dingtalk_sdk_gmdzy2010/department_request.py#L27-L30 | train |
gmdzy2010/dingtalk_sdk_gmdzy2010 | dingtalk_sdk_gmdzy2010/department_request.py | DeptsRequest.get_depts | def get_depts(self, dept_name=None):
"""Method to get department by name."""
depts = self.json_response.get("department", None)
params = self.kwargs.get("params", None)
fetch_child = params.get("fetch_child", True) if params else True
if dept_name is not None:
depts = [dept for dept in depts if dept["name"] == dept_name]
depts = [{"id": dept["id"], "name": dept["name"]} for dept in depts]
self.logger.info("%s\t%s" % (self.request_method, self.request_url))
return depts if fetch_child else depts[0] | python | def get_depts(self, dept_name=None):
"""Method to get department by name."""
depts = self.json_response.get("department", None)
params = self.kwargs.get("params", None)
fetch_child = params.get("fetch_child", True) if params else True
if dept_name is not None:
depts = [dept for dept in depts if dept["name"] == dept_name]
depts = [{"id": dept["id"], "name": dept["name"]} for dept in depts]
self.logger.info("%s\t%s" % (self.request_method, self.request_url))
return depts if fetch_child else depts[0] | [
"def",
"get_depts",
"(",
"self",
",",
"dept_name",
"=",
"None",
")",
":",
"depts",
"=",
"self",
".",
"json_response",
".",
"get",
"(",
"\"department\"",
",",
"None",
")",
"params",
"=",
"self",
".",
"kwargs",
".",
"get",
"(",
"\"params\"",
",",
"None",
")",
"fetch_child",
"=",
"params",
".",
"get",
"(",
"\"fetch_child\"",
",",
"True",
")",
"if",
"params",
"else",
"True",
"if",
"dept_name",
"is",
"not",
"None",
":",
"depts",
"=",
"[",
"dept",
"for",
"dept",
"in",
"depts",
"if",
"dept",
"[",
"\"name\"",
"]",
"==",
"dept_name",
"]",
"depts",
"=",
"[",
"{",
"\"id\"",
":",
"dept",
"[",
"\"id\"",
"]",
",",
"\"name\"",
":",
"dept",
"[",
"\"name\"",
"]",
"}",
"for",
"dept",
"in",
"depts",
"]",
"self",
".",
"logger",
".",
"info",
"(",
"\"%s\\t%s\"",
"%",
"(",
"self",
".",
"request_method",
",",
"self",
".",
"request_url",
")",
")",
"return",
"depts",
"if",
"fetch_child",
"else",
"depts",
"[",
"0",
"]"
]
| Method to get department by name. | [
"Method",
"to",
"get",
"department",
"by",
"name",
"."
]
| b06cb1f78f89be9554dcb6101af8bc72718a9ecd | https://github.com/gmdzy2010/dingtalk_sdk_gmdzy2010/blob/b06cb1f78f89be9554dcb6101af8bc72718a9ecd/dingtalk_sdk_gmdzy2010/department_request.py#L52-L61 | train |
lsst-sqre/documenteer | documenteer/sphinxext/__init__.py | setup | def setup(app):
"""Wrapper for the `setup` functions of each individual extension module.
"""
jira.setup(app)
lsstdocushare.setup(app)
mockcoderefs.setup(app)
packagetoctree.setup(app)
remotecodeblock.setup(app)
try:
__version__ = get_distribution('documenteer').version
except DistributionNotFound:
# package is not installed
__version__ = 'unknown'
return {'version': __version__,
'parallel_read_safe': True,
'parallel_write_safe': True} | python | def setup(app):
"""Wrapper for the `setup` functions of each individual extension module.
"""
jira.setup(app)
lsstdocushare.setup(app)
mockcoderefs.setup(app)
packagetoctree.setup(app)
remotecodeblock.setup(app)
try:
__version__ = get_distribution('documenteer').version
except DistributionNotFound:
# package is not installed
__version__ = 'unknown'
return {'version': __version__,
'parallel_read_safe': True,
'parallel_write_safe': True} | [
"def",
"setup",
"(",
"app",
")",
":",
"jira",
".",
"setup",
"(",
"app",
")",
"lsstdocushare",
".",
"setup",
"(",
"app",
")",
"mockcoderefs",
".",
"setup",
"(",
"app",
")",
"packagetoctree",
".",
"setup",
"(",
"app",
")",
"remotecodeblock",
".",
"setup",
"(",
"app",
")",
"try",
":",
"__version__",
"=",
"get_distribution",
"(",
"'documenteer'",
")",
".",
"version",
"except",
"DistributionNotFound",
":",
"# package is not installed",
"__version__",
"=",
"'unknown'",
"return",
"{",
"'version'",
":",
"__version__",
",",
"'parallel_read_safe'",
":",
"True",
",",
"'parallel_write_safe'",
":",
"True",
"}"
]
| Wrapper for the `setup` functions of each individual extension module. | [
"Wrapper",
"for",
"the",
"setup",
"functions",
"of",
"each",
"individual",
"extension",
"module",
"."
]
| 75f02901a80042b28d074df1cc1dca32eb8e38c8 | https://github.com/lsst-sqre/documenteer/blob/75f02901a80042b28d074df1cc1dca32eb8e38c8/documenteer/sphinxext/__init__.py#L25-L41 | train |
lsst-sqre/documenteer | documenteer/sphinxext/lssttasks/crossrefs.py | task_ref_role | def task_ref_role(name, rawtext, text, lineno, inliner,
options=None, content=None):
"""Process a role that references the target nodes created by the
``lsst-task`` directive.
Parameters
----------
name
The role name used in the document.
rawtext
The entire markup snippet, with role.
text
The text marked with the role.
lineno
The line number where ``rawtext`` appears in the input.
inliner
The inliner instance that called us.
options
Directive options for customization.
content
The directive content for customization.
Returns
-------
nodes : `list`
List of nodes to insert into the document.
messages : `list`
List of system messages.
"""
# app = inliner.document.settings.env.app
node = pending_task_xref(rawsource=text)
return [node], [] | python | def task_ref_role(name, rawtext, text, lineno, inliner,
options=None, content=None):
"""Process a role that references the target nodes created by the
``lsst-task`` directive.
Parameters
----------
name
The role name used in the document.
rawtext
The entire markup snippet, with role.
text
The text marked with the role.
lineno
The line number where ``rawtext`` appears in the input.
inliner
The inliner instance that called us.
options
Directive options for customization.
content
The directive content for customization.
Returns
-------
nodes : `list`
List of nodes to insert into the document.
messages : `list`
List of system messages.
"""
# app = inliner.document.settings.env.app
node = pending_task_xref(rawsource=text)
return [node], [] | [
"def",
"task_ref_role",
"(",
"name",
",",
"rawtext",
",",
"text",
",",
"lineno",
",",
"inliner",
",",
"options",
"=",
"None",
",",
"content",
"=",
"None",
")",
":",
"# app = inliner.document.settings.env.app",
"node",
"=",
"pending_task_xref",
"(",
"rawsource",
"=",
"text",
")",
"return",
"[",
"node",
"]",
",",
"[",
"]"
]
| Process a role that references the target nodes created by the
``lsst-task`` directive.
Parameters
----------
name
The role name used in the document.
rawtext
The entire markup snippet, with role.
text
The text marked with the role.
lineno
The line number where ``rawtext`` appears in the input.
inliner
The inliner instance that called us.
options
Directive options for customization.
content
The directive content for customization.
Returns
-------
nodes : `list`
List of nodes to insert into the document.
messages : `list`
List of system messages. | [
"Process",
"a",
"role",
"that",
"references",
"the",
"target",
"nodes",
"created",
"by",
"the",
"lsst",
"-",
"task",
"directive",
"."
]
| 75f02901a80042b28d074df1cc1dca32eb8e38c8 | https://github.com/lsst-sqre/documenteer/blob/75f02901a80042b28d074df1cc1dca32eb8e38c8/documenteer/sphinxext/lssttasks/crossrefs.py#L89-L120 | train |
lsst-sqre/documenteer | documenteer/sphinxext/lssttasks/crossrefs.py | process_pending_task_xref_nodes | def process_pending_task_xref_nodes(app, doctree, fromdocname):
"""Process the ``pending_task_xref`` nodes during the ``doctree-resolved``
event to insert links to the locations of ``lsst-task-topic`` directives.
"""
logger = getLogger(__name__)
env = app.builder.env
for node in doctree.traverse(pending_task_xref):
content = []
# The source of the node is the class name the user entered via the
# lsst-task-topic role. For example:
# lsst.pipe.tasks.processCcd.ProcessCcdTask
role_parts = split_role_content(node.rawsource)
task_id = format_task_id(role_parts['ref'])
if role_parts['display']:
# user's custom display text
display_text = role_parts['display']
elif role_parts['last_component']:
# just the name of the class
display_text = role_parts['ref'].split('.')[-1]
else:
display_text = role_parts['ref']
link_label = nodes.literal()
link_label += nodes.Text(display_text, display_text)
if hasattr(env, 'lsst_task_topics') and \
task_id in env.lsst_task_topics:
# A task topic, marked up with the lsst-task-topic directive is
# available
task_data = env.lsst_task_topics[task_id]
ref_node = nodes.reference('', '')
ref_node['refdocname'] = task_data['docname']
ref_node['refuri'] = app.builder.get_relative_uri(
fromdocname, task_data['docname'])
ref_node['refuri'] += '#' + task_data['target']['refid']
ref_node += link_label
content.append(ref_node)
else:
# Fallback if the task topic isn't known. Just print the label text
content.append(link_label)
message = 'lsst-task could not find a reference to %s'
logger.warning(message, role_parts['ref'], location=node)
# replacing the pending_task_xref node with this reference
node.replace_self(content) | python | def process_pending_task_xref_nodes(app, doctree, fromdocname):
"""Process the ``pending_task_xref`` nodes during the ``doctree-resolved``
event to insert links to the locations of ``lsst-task-topic`` directives.
"""
logger = getLogger(__name__)
env = app.builder.env
for node in doctree.traverse(pending_task_xref):
content = []
# The source of the node is the class name the user entered via the
# lsst-task-topic role. For example:
# lsst.pipe.tasks.processCcd.ProcessCcdTask
role_parts = split_role_content(node.rawsource)
task_id = format_task_id(role_parts['ref'])
if role_parts['display']:
# user's custom display text
display_text = role_parts['display']
elif role_parts['last_component']:
# just the name of the class
display_text = role_parts['ref'].split('.')[-1]
else:
display_text = role_parts['ref']
link_label = nodes.literal()
link_label += nodes.Text(display_text, display_text)
if hasattr(env, 'lsst_task_topics') and \
task_id in env.lsst_task_topics:
# A task topic, marked up with the lsst-task-topic directive is
# available
task_data = env.lsst_task_topics[task_id]
ref_node = nodes.reference('', '')
ref_node['refdocname'] = task_data['docname']
ref_node['refuri'] = app.builder.get_relative_uri(
fromdocname, task_data['docname'])
ref_node['refuri'] += '#' + task_data['target']['refid']
ref_node += link_label
content.append(ref_node)
else:
# Fallback if the task topic isn't known. Just print the label text
content.append(link_label)
message = 'lsst-task could not find a reference to %s'
logger.warning(message, role_parts['ref'], location=node)
# replacing the pending_task_xref node with this reference
node.replace_self(content) | [
"def",
"process_pending_task_xref_nodes",
"(",
"app",
",",
"doctree",
",",
"fromdocname",
")",
":",
"logger",
"=",
"getLogger",
"(",
"__name__",
")",
"env",
"=",
"app",
".",
"builder",
".",
"env",
"for",
"node",
"in",
"doctree",
".",
"traverse",
"(",
"pending_task_xref",
")",
":",
"content",
"=",
"[",
"]",
"# The source of the node is the class name the user entered via the",
"# lsst-task-topic role. For example:",
"# lsst.pipe.tasks.processCcd.ProcessCcdTask",
"role_parts",
"=",
"split_role_content",
"(",
"node",
".",
"rawsource",
")",
"task_id",
"=",
"format_task_id",
"(",
"role_parts",
"[",
"'ref'",
"]",
")",
"if",
"role_parts",
"[",
"'display'",
"]",
":",
"# user's custom display text",
"display_text",
"=",
"role_parts",
"[",
"'display'",
"]",
"elif",
"role_parts",
"[",
"'last_component'",
"]",
":",
"# just the name of the class",
"display_text",
"=",
"role_parts",
"[",
"'ref'",
"]",
".",
"split",
"(",
"'.'",
")",
"[",
"-",
"1",
"]",
"else",
":",
"display_text",
"=",
"role_parts",
"[",
"'ref'",
"]",
"link_label",
"=",
"nodes",
".",
"literal",
"(",
")",
"link_label",
"+=",
"nodes",
".",
"Text",
"(",
"display_text",
",",
"display_text",
")",
"if",
"hasattr",
"(",
"env",
",",
"'lsst_task_topics'",
")",
"and",
"task_id",
"in",
"env",
".",
"lsst_task_topics",
":",
"# A task topic, marked up with the lsst-task-topic directive is",
"# available",
"task_data",
"=",
"env",
".",
"lsst_task_topics",
"[",
"task_id",
"]",
"ref_node",
"=",
"nodes",
".",
"reference",
"(",
"''",
",",
"''",
")",
"ref_node",
"[",
"'refdocname'",
"]",
"=",
"task_data",
"[",
"'docname'",
"]",
"ref_node",
"[",
"'refuri'",
"]",
"=",
"app",
".",
"builder",
".",
"get_relative_uri",
"(",
"fromdocname",
",",
"task_data",
"[",
"'docname'",
"]",
")",
"ref_node",
"[",
"'refuri'",
"]",
"+=",
"'#'",
"+",
"task_data",
"[",
"'target'",
"]",
"[",
"'refid'",
"]",
"ref_node",
"+=",
"link_label",
"content",
".",
"append",
"(",
"ref_node",
")",
"else",
":",
"# Fallback if the task topic isn't known. Just print the label text",
"content",
".",
"append",
"(",
"link_label",
")",
"message",
"=",
"'lsst-task could not find a reference to %s'",
"logger",
".",
"warning",
"(",
"message",
",",
"role_parts",
"[",
"'ref'",
"]",
",",
"location",
"=",
"node",
")",
"# replacing the pending_task_xref node with this reference",
"node",
".",
"replace_self",
"(",
"content",
")"
]
| Process the ``pending_task_xref`` nodes during the ``doctree-resolved``
event to insert links to the locations of ``lsst-task-topic`` directives. | [
"Process",
"the",
"pending_task_xref",
"nodes",
"during",
"the",
"doctree",
"-",
"resolved",
"event",
"to",
"insert",
"links",
"to",
"the",
"locations",
"of",
"lsst",
"-",
"task",
"-",
"topic",
"directives",
"."
]
| 75f02901a80042b28d074df1cc1dca32eb8e38c8 | https://github.com/lsst-sqre/documenteer/blob/75f02901a80042b28d074df1cc1dca32eb8e38c8/documenteer/sphinxext/lssttasks/crossrefs.py#L123-L173 | train |
lsst-sqre/documenteer | documenteer/sphinxext/lssttasks/crossrefs.py | config_ref_role | def config_ref_role(name, rawtext, text, lineno, inliner,
options=None, content=None):
"""Process a role that references the target nodes created by the
``lsst-config-topic`` directive.
Parameters
----------
name
The role name used in the document.
rawtext
The entire markup snippet, with role.
text
The text marked with the role.
lineno
The line number where ``rawtext`` appears in the input.
inliner
The inliner instance that called us.
options
Directive options for customization.
content
The directive content for customization.
Returns
-------
nodes : `list`
List of nodes to insert into the document.
messages : `list`
List of system messages.
See also
--------
`format_config_id`
`ConfigTopicTargetDirective`
`pending_config_xref`
"""
node = pending_config_xref(rawsource=text)
return [node], [] | python | def config_ref_role(name, rawtext, text, lineno, inliner,
options=None, content=None):
"""Process a role that references the target nodes created by the
``lsst-config-topic`` directive.
Parameters
----------
name
The role name used in the document.
rawtext
The entire markup snippet, with role.
text
The text marked with the role.
lineno
The line number where ``rawtext`` appears in the input.
inliner
The inliner instance that called us.
options
Directive options for customization.
content
The directive content for customization.
Returns
-------
nodes : `list`
List of nodes to insert into the document.
messages : `list`
List of system messages.
See also
--------
`format_config_id`
`ConfigTopicTargetDirective`
`pending_config_xref`
"""
node = pending_config_xref(rawsource=text)
return [node], [] | [
"def",
"config_ref_role",
"(",
"name",
",",
"rawtext",
",",
"text",
",",
"lineno",
",",
"inliner",
",",
"options",
"=",
"None",
",",
"content",
"=",
"None",
")",
":",
"node",
"=",
"pending_config_xref",
"(",
"rawsource",
"=",
"text",
")",
"return",
"[",
"node",
"]",
",",
"[",
"]"
]
| Process a role that references the target nodes created by the
``lsst-config-topic`` directive.
Parameters
----------
name
The role name used in the document.
rawtext
The entire markup snippet, with role.
text
The text marked with the role.
lineno
The line number where ``rawtext`` appears in the input.
inliner
The inliner instance that called us.
options
Directive options for customization.
content
The directive content for customization.
Returns
-------
nodes : `list`
List of nodes to insert into the document.
messages : `list`
List of system messages.
See also
--------
`format_config_id`
`ConfigTopicTargetDirective`
`pending_config_xref` | [
"Process",
"a",
"role",
"that",
"references",
"the",
"target",
"nodes",
"created",
"by",
"the",
"lsst",
"-",
"config",
"-",
"topic",
"directive",
"."
]
| 75f02901a80042b28d074df1cc1dca32eb8e38c8 | https://github.com/lsst-sqre/documenteer/blob/75f02901a80042b28d074df1cc1dca32eb8e38c8/documenteer/sphinxext/lssttasks/crossrefs.py#L176-L212 | train |
lsst-sqre/documenteer | documenteer/sphinxext/lssttasks/crossrefs.py | process_pending_config_xref_nodes | def process_pending_config_xref_nodes(app, doctree, fromdocname):
"""Process the ``pending_config_xref`` nodes during the ``doctree-resolved``
event to insert links to the locations of ``lsst-config-topic`` directives.
See also
--------
`config_ref_role`
`ConfigTopicTargetDirective`
`pending_config_xref`
"""
logger = getLogger(__name__)
env = app.builder.env
for node in doctree.traverse(pending_config_xref):
content = []
# The source of the node is the content the authored entered in the
# lsst-config role
role_parts = split_role_content(node.rawsource)
config_id = format_config_id(role_parts['ref'])
if role_parts['display']:
# user's custom display text
display_text = role_parts['display']
elif role_parts['last_component']:
# just the name of the class
display_text = role_parts['ref'].split('.')[-1]
else:
display_text = role_parts['ref']
link_label = nodes.literal()
link_label += nodes.Text(display_text, display_text)
if hasattr(env, 'lsst_task_topics') and \
config_id in env.lsst_task_topics:
# A config topic, marked up with the lsst-task directive is
# available
config_data = env.lsst_task_topics[config_id]
ref_node = nodes.reference('', '')
ref_node['refdocname'] = config_data['docname']
ref_node['refuri'] = app.builder.get_relative_uri(
fromdocname, config_data['docname'])
ref_node['refuri'] += '#' + config_data['target']['refid']
ref_node += link_label
content.append(ref_node)
else:
# Fallback if the config topic isn't known. Just print the
# role's formatted content.
content.append(link_label)
message = 'lsst-config could not find a reference to %s'
logger.warning(message, role_parts['ref'], location=node)
# replacing the pending_config_xref node with this reference
node.replace_self(content) | python | def process_pending_config_xref_nodes(app, doctree, fromdocname):
"""Process the ``pending_config_xref`` nodes during the ``doctree-resolved``
event to insert links to the locations of ``lsst-config-topic`` directives.
See also
--------
`config_ref_role`
`ConfigTopicTargetDirective`
`pending_config_xref`
"""
logger = getLogger(__name__)
env = app.builder.env
for node in doctree.traverse(pending_config_xref):
content = []
# The source of the node is the content the authored entered in the
# lsst-config role
role_parts = split_role_content(node.rawsource)
config_id = format_config_id(role_parts['ref'])
if role_parts['display']:
# user's custom display text
display_text = role_parts['display']
elif role_parts['last_component']:
# just the name of the class
display_text = role_parts['ref'].split('.')[-1]
else:
display_text = role_parts['ref']
link_label = nodes.literal()
link_label += nodes.Text(display_text, display_text)
if hasattr(env, 'lsst_task_topics') and \
config_id in env.lsst_task_topics:
# A config topic, marked up with the lsst-task directive is
# available
config_data = env.lsst_task_topics[config_id]
ref_node = nodes.reference('', '')
ref_node['refdocname'] = config_data['docname']
ref_node['refuri'] = app.builder.get_relative_uri(
fromdocname, config_data['docname'])
ref_node['refuri'] += '#' + config_data['target']['refid']
ref_node += link_label
content.append(ref_node)
else:
# Fallback if the config topic isn't known. Just print the
# role's formatted content.
content.append(link_label)
message = 'lsst-config could not find a reference to %s'
logger.warning(message, role_parts['ref'], location=node)
# replacing the pending_config_xref node with this reference
node.replace_self(content) | [
"def",
"process_pending_config_xref_nodes",
"(",
"app",
",",
"doctree",
",",
"fromdocname",
")",
":",
"logger",
"=",
"getLogger",
"(",
"__name__",
")",
"env",
"=",
"app",
".",
"builder",
".",
"env",
"for",
"node",
"in",
"doctree",
".",
"traverse",
"(",
"pending_config_xref",
")",
":",
"content",
"=",
"[",
"]",
"# The source of the node is the content the authored entered in the",
"# lsst-config role",
"role_parts",
"=",
"split_role_content",
"(",
"node",
".",
"rawsource",
")",
"config_id",
"=",
"format_config_id",
"(",
"role_parts",
"[",
"'ref'",
"]",
")",
"if",
"role_parts",
"[",
"'display'",
"]",
":",
"# user's custom display text",
"display_text",
"=",
"role_parts",
"[",
"'display'",
"]",
"elif",
"role_parts",
"[",
"'last_component'",
"]",
":",
"# just the name of the class",
"display_text",
"=",
"role_parts",
"[",
"'ref'",
"]",
".",
"split",
"(",
"'.'",
")",
"[",
"-",
"1",
"]",
"else",
":",
"display_text",
"=",
"role_parts",
"[",
"'ref'",
"]",
"link_label",
"=",
"nodes",
".",
"literal",
"(",
")",
"link_label",
"+=",
"nodes",
".",
"Text",
"(",
"display_text",
",",
"display_text",
")",
"if",
"hasattr",
"(",
"env",
",",
"'lsst_task_topics'",
")",
"and",
"config_id",
"in",
"env",
".",
"lsst_task_topics",
":",
"# A config topic, marked up with the lsst-task directive is",
"# available",
"config_data",
"=",
"env",
".",
"lsst_task_topics",
"[",
"config_id",
"]",
"ref_node",
"=",
"nodes",
".",
"reference",
"(",
"''",
",",
"''",
")",
"ref_node",
"[",
"'refdocname'",
"]",
"=",
"config_data",
"[",
"'docname'",
"]",
"ref_node",
"[",
"'refuri'",
"]",
"=",
"app",
".",
"builder",
".",
"get_relative_uri",
"(",
"fromdocname",
",",
"config_data",
"[",
"'docname'",
"]",
")",
"ref_node",
"[",
"'refuri'",
"]",
"+=",
"'#'",
"+",
"config_data",
"[",
"'target'",
"]",
"[",
"'refid'",
"]",
"ref_node",
"+=",
"link_label",
"content",
".",
"append",
"(",
"ref_node",
")",
"else",
":",
"# Fallback if the config topic isn't known. Just print the",
"# role's formatted content.",
"content",
".",
"append",
"(",
"link_label",
")",
"message",
"=",
"'lsst-config could not find a reference to %s'",
"logger",
".",
"warning",
"(",
"message",
",",
"role_parts",
"[",
"'ref'",
"]",
",",
"location",
"=",
"node",
")",
"# replacing the pending_config_xref node with this reference",
"node",
".",
"replace_self",
"(",
"content",
")"
]
| Process the ``pending_config_xref`` nodes during the ``doctree-resolved``
event to insert links to the locations of ``lsst-config-topic`` directives.
See also
--------
`config_ref_role`
`ConfigTopicTargetDirective`
`pending_config_xref` | [
"Process",
"the",
"pending_config_xref",
"nodes",
"during",
"the",
"doctree",
"-",
"resolved",
"event",
"to",
"insert",
"links",
"to",
"the",
"locations",
"of",
"lsst",
"-",
"config",
"-",
"topic",
"directives",
"."
]
| 75f02901a80042b28d074df1cc1dca32eb8e38c8 | https://github.com/lsst-sqre/documenteer/blob/75f02901a80042b28d074df1cc1dca32eb8e38c8/documenteer/sphinxext/lssttasks/crossrefs.py#L215-L271 | train |
lsst-sqre/documenteer | documenteer/sphinxext/lssttasks/crossrefs.py | configfield_ref_role | def configfield_ref_role(name, rawtext, text, lineno, inliner,
options=None, content=None):
"""Process a role that references the Task configuration field nodes
created by the ``lsst-config-fields``, ``lsst-task-config-subtasks``,
and ``lsst-task-config-subtasks`` directives.
Parameters
----------
name
The role name used in the document.
rawtext
The entire markup snippet, with role.
text
The text marked with the role.
lineno
The line number where ``rawtext`` appears in the input.
inliner
The inliner instance that called us.
options
Directive options for customization.
content
The directive content for customization.
Returns
-------
nodes : `list`
List of nodes to insert into the document.
messages : `list`
List of system messages.
See also
--------
`format_configfield_id`
`pending_configfield_xref`
`process_pending_configfield_xref_nodes`
"""
node = pending_configfield_xref(rawsource=text)
return [node], [] | python | def configfield_ref_role(name, rawtext, text, lineno, inliner,
options=None, content=None):
"""Process a role that references the Task configuration field nodes
created by the ``lsst-config-fields``, ``lsst-task-config-subtasks``,
and ``lsst-task-config-subtasks`` directives.
Parameters
----------
name
The role name used in the document.
rawtext
The entire markup snippet, with role.
text
The text marked with the role.
lineno
The line number where ``rawtext`` appears in the input.
inliner
The inliner instance that called us.
options
Directive options for customization.
content
The directive content for customization.
Returns
-------
nodes : `list`
List of nodes to insert into the document.
messages : `list`
List of system messages.
See also
--------
`format_configfield_id`
`pending_configfield_xref`
`process_pending_configfield_xref_nodes`
"""
node = pending_configfield_xref(rawsource=text)
return [node], [] | [
"def",
"configfield_ref_role",
"(",
"name",
",",
"rawtext",
",",
"text",
",",
"lineno",
",",
"inliner",
",",
"options",
"=",
"None",
",",
"content",
"=",
"None",
")",
":",
"node",
"=",
"pending_configfield_xref",
"(",
"rawsource",
"=",
"text",
")",
"return",
"[",
"node",
"]",
",",
"[",
"]"
]
| Process a role that references the Task configuration field nodes
created by the ``lsst-config-fields``, ``lsst-task-config-subtasks``,
and ``lsst-task-config-subtasks`` directives.
Parameters
----------
name
The role name used in the document.
rawtext
The entire markup snippet, with role.
text
The text marked with the role.
lineno
The line number where ``rawtext`` appears in the input.
inliner
The inliner instance that called us.
options
Directive options for customization.
content
The directive content for customization.
Returns
-------
nodes : `list`
List of nodes to insert into the document.
messages : `list`
List of system messages.
See also
--------
`format_configfield_id`
`pending_configfield_xref`
`process_pending_configfield_xref_nodes` | [
"Process",
"a",
"role",
"that",
"references",
"the",
"Task",
"configuration",
"field",
"nodes",
"created",
"by",
"the",
"lsst",
"-",
"config",
"-",
"fields",
"lsst",
"-",
"task",
"-",
"config",
"-",
"subtasks",
"and",
"lsst",
"-",
"task",
"-",
"config",
"-",
"subtasks",
"directives",
"."
]
| 75f02901a80042b28d074df1cc1dca32eb8e38c8 | https://github.com/lsst-sqre/documenteer/blob/75f02901a80042b28d074df1cc1dca32eb8e38c8/documenteer/sphinxext/lssttasks/crossrefs.py#L274-L311 | train |
lsst-sqre/documenteer | documenteer/sphinxext/lssttasks/crossrefs.py | process_pending_configfield_xref_nodes | def process_pending_configfield_xref_nodes(app, doctree, fromdocname):
"""Process the ``pending_configfield_xref`` nodes during the
``doctree-resolved`` event to insert links to the locations of
configuration field nodes.
See also
--------
`format_configfield_id`
`configfield_ref_role`
`pending_configfield_xref`
"""
logger = getLogger(__name__)
env = app.builder.env
for node in doctree.traverse(pending_configfield_xref):
content = []
# The source is the text the user entered into the role, which is
# the importable name of the config class's and the attribute
role_parts = split_role_content(node.rawsource)
namespace_components = role_parts['ref'].split('.')
field_name = namespace_components[-1]
class_namespace = namespace_components[:-1]
configfield_id = format_configfield_id(class_namespace, field_name)
if role_parts['display']:
# user's custom display text
display_text = role_parts['display']
elif role_parts['last_component']:
# just the name of the class
display_text = role_parts['ref'].split('.')[-1]
else:
display_text = role_parts['ref']
link_label = nodes.literal()
link_label += nodes.Text(display_text, display_text)
if hasattr(env, 'lsst_configfields') \
and configfield_id in env.lsst_configfields:
# A config field topic is available
configfield_data = env.lsst_configfields[configfield_id]
ref_node = nodes.reference('', '')
ref_node['refdocname'] = configfield_data['docname']
ref_node['refuri'] = app.builder.get_relative_uri(
fromdocname, configfield_data['docname'])
ref_node['refuri'] += '#' + configfield_id
ref_node += link_label
content.append(ref_node)
else:
# Fallback if the config field isn't known. Just print the Config
# field attribute name
literal_node = nodes.literal()
link_label = nodes.Text(field_name, field_name)
literal_node += link_label
content.append(literal_node)
message = 'lsst-config-field could not find a reference to %s'
logger.warning(message, role_parts['ref'], location=node)
# replacing the pending_configfield_xref node with this reference
node.replace_self(content) | python | def process_pending_configfield_xref_nodes(app, doctree, fromdocname):
"""Process the ``pending_configfield_xref`` nodes during the
``doctree-resolved`` event to insert links to the locations of
configuration field nodes.
See also
--------
`format_configfield_id`
`configfield_ref_role`
`pending_configfield_xref`
"""
logger = getLogger(__name__)
env = app.builder.env
for node in doctree.traverse(pending_configfield_xref):
content = []
# The source is the text the user entered into the role, which is
# the importable name of the config class's and the attribute
role_parts = split_role_content(node.rawsource)
namespace_components = role_parts['ref'].split('.')
field_name = namespace_components[-1]
class_namespace = namespace_components[:-1]
configfield_id = format_configfield_id(class_namespace, field_name)
if role_parts['display']:
# user's custom display text
display_text = role_parts['display']
elif role_parts['last_component']:
# just the name of the class
display_text = role_parts['ref'].split('.')[-1]
else:
display_text = role_parts['ref']
link_label = nodes.literal()
link_label += nodes.Text(display_text, display_text)
if hasattr(env, 'lsst_configfields') \
and configfield_id in env.lsst_configfields:
# A config field topic is available
configfield_data = env.lsst_configfields[configfield_id]
ref_node = nodes.reference('', '')
ref_node['refdocname'] = configfield_data['docname']
ref_node['refuri'] = app.builder.get_relative_uri(
fromdocname, configfield_data['docname'])
ref_node['refuri'] += '#' + configfield_id
ref_node += link_label
content.append(ref_node)
else:
# Fallback if the config field isn't known. Just print the Config
# field attribute name
literal_node = nodes.literal()
link_label = nodes.Text(field_name, field_name)
literal_node += link_label
content.append(literal_node)
message = 'lsst-config-field could not find a reference to %s'
logger.warning(message, role_parts['ref'], location=node)
# replacing the pending_configfield_xref node with this reference
node.replace_self(content) | [
"def",
"process_pending_configfield_xref_nodes",
"(",
"app",
",",
"doctree",
",",
"fromdocname",
")",
":",
"logger",
"=",
"getLogger",
"(",
"__name__",
")",
"env",
"=",
"app",
".",
"builder",
".",
"env",
"for",
"node",
"in",
"doctree",
".",
"traverse",
"(",
"pending_configfield_xref",
")",
":",
"content",
"=",
"[",
"]",
"# The source is the text the user entered into the role, which is",
"# the importable name of the config class's and the attribute",
"role_parts",
"=",
"split_role_content",
"(",
"node",
".",
"rawsource",
")",
"namespace_components",
"=",
"role_parts",
"[",
"'ref'",
"]",
".",
"split",
"(",
"'.'",
")",
"field_name",
"=",
"namespace_components",
"[",
"-",
"1",
"]",
"class_namespace",
"=",
"namespace_components",
"[",
":",
"-",
"1",
"]",
"configfield_id",
"=",
"format_configfield_id",
"(",
"class_namespace",
",",
"field_name",
")",
"if",
"role_parts",
"[",
"'display'",
"]",
":",
"# user's custom display text",
"display_text",
"=",
"role_parts",
"[",
"'display'",
"]",
"elif",
"role_parts",
"[",
"'last_component'",
"]",
":",
"# just the name of the class",
"display_text",
"=",
"role_parts",
"[",
"'ref'",
"]",
".",
"split",
"(",
"'.'",
")",
"[",
"-",
"1",
"]",
"else",
":",
"display_text",
"=",
"role_parts",
"[",
"'ref'",
"]",
"link_label",
"=",
"nodes",
".",
"literal",
"(",
")",
"link_label",
"+=",
"nodes",
".",
"Text",
"(",
"display_text",
",",
"display_text",
")",
"if",
"hasattr",
"(",
"env",
",",
"'lsst_configfields'",
")",
"and",
"configfield_id",
"in",
"env",
".",
"lsst_configfields",
":",
"# A config field topic is available",
"configfield_data",
"=",
"env",
".",
"lsst_configfields",
"[",
"configfield_id",
"]",
"ref_node",
"=",
"nodes",
".",
"reference",
"(",
"''",
",",
"''",
")",
"ref_node",
"[",
"'refdocname'",
"]",
"=",
"configfield_data",
"[",
"'docname'",
"]",
"ref_node",
"[",
"'refuri'",
"]",
"=",
"app",
".",
"builder",
".",
"get_relative_uri",
"(",
"fromdocname",
",",
"configfield_data",
"[",
"'docname'",
"]",
")",
"ref_node",
"[",
"'refuri'",
"]",
"+=",
"'#'",
"+",
"configfield_id",
"ref_node",
"+=",
"link_label",
"content",
".",
"append",
"(",
"ref_node",
")",
"else",
":",
"# Fallback if the config field isn't known. Just print the Config",
"# field attribute name",
"literal_node",
"=",
"nodes",
".",
"literal",
"(",
")",
"link_label",
"=",
"nodes",
".",
"Text",
"(",
"field_name",
",",
"field_name",
")",
"literal_node",
"+=",
"link_label",
"content",
".",
"append",
"(",
"literal_node",
")",
"message",
"=",
"'lsst-config-field could not find a reference to %s'",
"logger",
".",
"warning",
"(",
"message",
",",
"role_parts",
"[",
"'ref'",
"]",
",",
"location",
"=",
"node",
")",
"# replacing the pending_configfield_xref node with this reference",
"node",
".",
"replace_self",
"(",
"content",
")"
]
| Process the ``pending_configfield_xref`` nodes during the
``doctree-resolved`` event to insert links to the locations of
configuration field nodes.
See also
--------
`format_configfield_id`
`configfield_ref_role`
`pending_configfield_xref` | [
"Process",
"the",
"pending_configfield_xref",
"nodes",
"during",
"the",
"doctree",
"-",
"resolved",
"event",
"to",
"insert",
"links",
"to",
"the",
"locations",
"of",
"configuration",
"field",
"nodes",
"."
]
| 75f02901a80042b28d074df1cc1dca32eb8e38c8 | https://github.com/lsst-sqre/documenteer/blob/75f02901a80042b28d074df1cc1dca32eb8e38c8/documenteer/sphinxext/lssttasks/crossrefs.py#L314-L377 | train |
zsimic/runez | src/runez/config.py | to_bytesize | def to_bytesize(value, default_unit=None, base=DEFAULT_BASE):
"""Convert `value` to bytes, accepts notations such as "4k" to mean 4096 bytes
Args:
value (str | unicode | int | None): Number of bytes optionally suffixed by a char from UNITS
default_unit (str | unicode | None): Default unit to use for unqualified values
base (int): Base to use (usually 1024)
Returns:
(int | None): Deduced bytesize value, if possible
"""
if isinstance(value, (int, float)):
return unitized(value, default_unit, base)
if value is None:
return None
try:
if value[-1].lower() == "b":
# Accept notations such as "1mb", as they get used out of habit
value = value[:-1]
unit = value[-1:].lower()
if unit.isdigit():
unit = default_unit
else:
value = value[:-1]
return unitized(to_number(float, value), unit, base)
except (IndexError, TypeError, ValueError):
return None | python | def to_bytesize(value, default_unit=None, base=DEFAULT_BASE):
"""Convert `value` to bytes, accepts notations such as "4k" to mean 4096 bytes
Args:
value (str | unicode | int | None): Number of bytes optionally suffixed by a char from UNITS
default_unit (str | unicode | None): Default unit to use for unqualified values
base (int): Base to use (usually 1024)
Returns:
(int | None): Deduced bytesize value, if possible
"""
if isinstance(value, (int, float)):
return unitized(value, default_unit, base)
if value is None:
return None
try:
if value[-1].lower() == "b":
# Accept notations such as "1mb", as they get used out of habit
value = value[:-1]
unit = value[-1:].lower()
if unit.isdigit():
unit = default_unit
else:
value = value[:-1]
return unitized(to_number(float, value), unit, base)
except (IndexError, TypeError, ValueError):
return None | [
"def",
"to_bytesize",
"(",
"value",
",",
"default_unit",
"=",
"None",
",",
"base",
"=",
"DEFAULT_BASE",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"(",
"int",
",",
"float",
")",
")",
":",
"return",
"unitized",
"(",
"value",
",",
"default_unit",
",",
"base",
")",
"if",
"value",
"is",
"None",
":",
"return",
"None",
"try",
":",
"if",
"value",
"[",
"-",
"1",
"]",
".",
"lower",
"(",
")",
"==",
"\"b\"",
":",
"# Accept notations such as \"1mb\", as they get used out of habit",
"value",
"=",
"value",
"[",
":",
"-",
"1",
"]",
"unit",
"=",
"value",
"[",
"-",
"1",
":",
"]",
".",
"lower",
"(",
")",
"if",
"unit",
".",
"isdigit",
"(",
")",
":",
"unit",
"=",
"default_unit",
"else",
":",
"value",
"=",
"value",
"[",
":",
"-",
"1",
"]",
"return",
"unitized",
"(",
"to_number",
"(",
"float",
",",
"value",
")",
",",
"unit",
",",
"base",
")",
"except",
"(",
"IndexError",
",",
"TypeError",
",",
"ValueError",
")",
":",
"return",
"None"
]
| Convert `value` to bytes, accepts notations such as "4k" to mean 4096 bytes
Args:
value (str | unicode | int | None): Number of bytes optionally suffixed by a char from UNITS
default_unit (str | unicode | None): Default unit to use for unqualified values
base (int): Base to use (usually 1024)
Returns:
(int | None): Deduced bytesize value, if possible | [
"Convert",
"value",
"to",
"bytes",
"accepts",
"notations",
"such",
"as",
"4k",
"to",
"mean",
"4096",
"bytes"
]
| 14363b719a1aae1528859a501a22d075ce0abfcc | https://github.com/zsimic/runez/blob/14363b719a1aae1528859a501a22d075ce0abfcc/src/runez/config.py#L372-L404 | train |
zsimic/runez | src/runez/config.py | to_number | def to_number(result_type, value, default=None, minimum=None, maximum=None):
"""Cast `value` to numeric `result_type` if possible
Args:
result_type (type): Numerical type to convert to (one of: int, float, ...)
value (str | unicode): Value to convert
default (result_type.__class__ | None): Default to use `value` can't be turned into an int
minimum (result_type.__class__ | None): If specified, result can't be below this minimum
maximum (result_type.__class__ | None): If specified, result can't be above this maximum
Returns:
Corresponding numeric value
"""
try:
return capped(result_type(value), minimum, maximum)
except (TypeError, ValueError):
return default | python | def to_number(result_type, value, default=None, minimum=None, maximum=None):
"""Cast `value` to numeric `result_type` if possible
Args:
result_type (type): Numerical type to convert to (one of: int, float, ...)
value (str | unicode): Value to convert
default (result_type.__class__ | None): Default to use `value` can't be turned into an int
minimum (result_type.__class__ | None): If specified, result can't be below this minimum
maximum (result_type.__class__ | None): If specified, result can't be above this maximum
Returns:
Corresponding numeric value
"""
try:
return capped(result_type(value), minimum, maximum)
except (TypeError, ValueError):
return default | [
"def",
"to_number",
"(",
"result_type",
",",
"value",
",",
"default",
"=",
"None",
",",
"minimum",
"=",
"None",
",",
"maximum",
"=",
"None",
")",
":",
"try",
":",
"return",
"capped",
"(",
"result_type",
"(",
"value",
")",
",",
"minimum",
",",
"maximum",
")",
"except",
"(",
"TypeError",
",",
"ValueError",
")",
":",
"return",
"default"
]
| Cast `value` to numeric `result_type` if possible
Args:
result_type (type): Numerical type to convert to (one of: int, float, ...)
value (str | unicode): Value to convert
default (result_type.__class__ | None): Default to use `value` can't be turned into an int
minimum (result_type.__class__ | None): If specified, result can't be below this minimum
maximum (result_type.__class__ | None): If specified, result can't be above this maximum
Returns:
Corresponding numeric value | [
"Cast",
"value",
"to",
"numeric",
"result_type",
"if",
"possible"
]
| 14363b719a1aae1528859a501a22d075ce0abfcc | https://github.com/zsimic/runez/blob/14363b719a1aae1528859a501a22d075ce0abfcc/src/runez/config.py#L451-L468 | train |
zsimic/runez | src/runez/config.py | Configuration.set_providers | def set_providers(self, *providers):
"""Replace current providers with given ones"""
if self.providers:
self.clear()
for provider in providers:
self.add(provider) | python | def set_providers(self, *providers):
"""Replace current providers with given ones"""
if self.providers:
self.clear()
for provider in providers:
self.add(provider) | [
"def",
"set_providers",
"(",
"self",
",",
"*",
"providers",
")",
":",
"if",
"self",
".",
"providers",
":",
"self",
".",
"clear",
"(",
")",
"for",
"provider",
"in",
"providers",
":",
"self",
".",
"add",
"(",
"provider",
")"
]
| Replace current providers with given ones | [
"Replace",
"current",
"providers",
"with",
"given",
"ones"
]
| 14363b719a1aae1528859a501a22d075ce0abfcc | https://github.com/zsimic/runez/blob/14363b719a1aae1528859a501a22d075ce0abfcc/src/runez/config.py#L62-L67 | train |
zsimic/runez | src/runez/config.py | Configuration.get_bytesize | def get_bytesize(self, key, default=None, minimum=None, maximum=None, default_unit=None, base=DEFAULT_BASE):
"""Size in bytes expressed by value configured under 'key'
Args:
key (str | unicode): Key to lookup
default (int | str | unicode | None): Default to use if key is not configured
minimum (int | str | unicode | None): If specified, result can't be below this minimum
maximum (int | str | unicode | None): If specified, result can't be above this maximum
default_unit (str | unicode | None): Default unit for unqualified values (see UNITS)
base (int): Base to use (usually 1024)
Returns:
(int): Size in bytes
"""
value = to_bytesize(self.get_str(key), default_unit, base)
if value is None:
return to_bytesize(default, default_unit, base)
return capped(value, to_bytesize(minimum, default_unit, base), to_bytesize(maximum, default_unit, base)) | python | def get_bytesize(self, key, default=None, minimum=None, maximum=None, default_unit=None, base=DEFAULT_BASE):
"""Size in bytes expressed by value configured under 'key'
Args:
key (str | unicode): Key to lookup
default (int | str | unicode | None): Default to use if key is not configured
minimum (int | str | unicode | None): If specified, result can't be below this minimum
maximum (int | str | unicode | None): If specified, result can't be above this maximum
default_unit (str | unicode | None): Default unit for unqualified values (see UNITS)
base (int): Base to use (usually 1024)
Returns:
(int): Size in bytes
"""
value = to_bytesize(self.get_str(key), default_unit, base)
if value is None:
return to_bytesize(default, default_unit, base)
return capped(value, to_bytesize(minimum, default_unit, base), to_bytesize(maximum, default_unit, base)) | [
"def",
"get_bytesize",
"(",
"self",
",",
"key",
",",
"default",
"=",
"None",
",",
"minimum",
"=",
"None",
",",
"maximum",
"=",
"None",
",",
"default_unit",
"=",
"None",
",",
"base",
"=",
"DEFAULT_BASE",
")",
":",
"value",
"=",
"to_bytesize",
"(",
"self",
".",
"get_str",
"(",
"key",
")",
",",
"default_unit",
",",
"base",
")",
"if",
"value",
"is",
"None",
":",
"return",
"to_bytesize",
"(",
"default",
",",
"default_unit",
",",
"base",
")",
"return",
"capped",
"(",
"value",
",",
"to_bytesize",
"(",
"minimum",
",",
"default_unit",
",",
"base",
")",
",",
"to_bytesize",
"(",
"maximum",
",",
"default_unit",
",",
"base",
")",
")"
]
| Size in bytes expressed by value configured under 'key'
Args:
key (str | unicode): Key to lookup
default (int | str | unicode | None): Default to use if key is not configured
minimum (int | str | unicode | None): If specified, result can't be below this minimum
maximum (int | str | unicode | None): If specified, result can't be above this maximum
default_unit (str | unicode | None): Default unit for unqualified values (see UNITS)
base (int): Base to use (usually 1024)
Returns:
(int): Size in bytes | [
"Size",
"in",
"bytes",
"expressed",
"by",
"value",
"configured",
"under",
"key"
]
| 14363b719a1aae1528859a501a22d075ce0abfcc | https://github.com/zsimic/runez/blob/14363b719a1aae1528859a501a22d075ce0abfcc/src/runez/config.py#L196-L213 | train |
sprockets/sprockets.mixins.metrics | sprockets/mixins/metrics/statsd.py | install | def install(application, **kwargs):
"""Call this to install StatsD for the Tornado application.
:param tornado.web.Application application: the application to
install the collector into.
:param kwargs: keyword parameters to pass to the
:class:`StatsDCollector` initializer.
:returns: :data:`True` if the client was installed successfully,
or :data:`False` otherwise.
- **host** The StatsD host. If host is not specified, the
``STATSD_HOST`` environment variable, or default `127.0.0.1`,
will be pass into the :class:`StatsDCollector`.
- **port** The StatsD port. If port is not specified, the
``STATSD_PORT`` environment variable, or default `8125`,
will be pass into the :class:`StatsDCollector`.
- **namespace** The StatsD bucket to write metrics into.
"""
if getattr(application, 'statsd', None) is not None:
LOGGER.warning('Statsd collector is already installed')
return False
if 'host' not in kwargs:
kwargs['host'] = os.environ.get('STATSD_HOST', '127.0.0.1')
if 'port' not in kwargs:
kwargs['port'] = os.environ.get('STATSD_PORT', '8125')
if 'protocol' not in kwargs:
kwargs['protocol'] = os.environ.get('STATSD_PROTOCOL', 'udp')
setattr(application, 'statsd', StatsDCollector(**kwargs))
return True | python | def install(application, **kwargs):
"""Call this to install StatsD for the Tornado application.
:param tornado.web.Application application: the application to
install the collector into.
:param kwargs: keyword parameters to pass to the
:class:`StatsDCollector` initializer.
:returns: :data:`True` if the client was installed successfully,
or :data:`False` otherwise.
- **host** The StatsD host. If host is not specified, the
``STATSD_HOST`` environment variable, or default `127.0.0.1`,
will be pass into the :class:`StatsDCollector`.
- **port** The StatsD port. If port is not specified, the
``STATSD_PORT`` environment variable, or default `8125`,
will be pass into the :class:`StatsDCollector`.
- **namespace** The StatsD bucket to write metrics into.
"""
if getattr(application, 'statsd', None) is not None:
LOGGER.warning('Statsd collector is already installed')
return False
if 'host' not in kwargs:
kwargs['host'] = os.environ.get('STATSD_HOST', '127.0.0.1')
if 'port' not in kwargs:
kwargs['port'] = os.environ.get('STATSD_PORT', '8125')
if 'protocol' not in kwargs:
kwargs['protocol'] = os.environ.get('STATSD_PROTOCOL', 'udp')
setattr(application, 'statsd', StatsDCollector(**kwargs))
return True | [
"def",
"install",
"(",
"application",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"getattr",
"(",
"application",
",",
"'statsd'",
",",
"None",
")",
"is",
"not",
"None",
":",
"LOGGER",
".",
"warning",
"(",
"'Statsd collector is already installed'",
")",
"return",
"False",
"if",
"'host'",
"not",
"in",
"kwargs",
":",
"kwargs",
"[",
"'host'",
"]",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'STATSD_HOST'",
",",
"'127.0.0.1'",
")",
"if",
"'port'",
"not",
"in",
"kwargs",
":",
"kwargs",
"[",
"'port'",
"]",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'STATSD_PORT'",
",",
"'8125'",
")",
"if",
"'protocol'",
"not",
"in",
"kwargs",
":",
"kwargs",
"[",
"'protocol'",
"]",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'STATSD_PROTOCOL'",
",",
"'udp'",
")",
"setattr",
"(",
"application",
",",
"'statsd'",
",",
"StatsDCollector",
"(",
"*",
"*",
"kwargs",
")",
")",
"return",
"True"
]
| Call this to install StatsD for the Tornado application.
:param tornado.web.Application application: the application to
install the collector into.
:param kwargs: keyword parameters to pass to the
:class:`StatsDCollector` initializer.
:returns: :data:`True` if the client was installed successfully,
or :data:`False` otherwise.
- **host** The StatsD host. If host is not specified, the
``STATSD_HOST`` environment variable, or default `127.0.0.1`,
will be pass into the :class:`StatsDCollector`.
- **port** The StatsD port. If port is not specified, the
``STATSD_PORT`` environment variable, or default `8125`,
will be pass into the :class:`StatsDCollector`.
- **namespace** The StatsD bucket to write metrics into. | [
"Call",
"this",
"to",
"install",
"StatsD",
"for",
"the",
"Tornado",
"application",
"."
]
| 0b17d5f0c09a2be9db779e17e6789d3d5ff9a0d0 | https://github.com/sprockets/sprockets.mixins.metrics/blob/0b17d5f0c09a2be9db779e17e6789d3d5ff9a0d0/sprockets/mixins/metrics/statsd.py#L202-L234 | train |
sprockets/sprockets.mixins.metrics | sprockets/mixins/metrics/statsd.py | StatsdMixin.record_timing | def record_timing(self, duration, *path):
"""Record a timing.
This method records a timing to the application's namespace
followed by a calculated path. Each element of `path` is
converted to a string and normalized before joining the
elements by periods. The normalization process is little
more than replacing periods with dashes.
:param float duration: timing to record in seconds
:param path: elements of the metric path to record
"""
self.application.statsd.send(path, duration * 1000.0, 'ms') | python | def record_timing(self, duration, *path):
"""Record a timing.
This method records a timing to the application's namespace
followed by a calculated path. Each element of `path` is
converted to a string and normalized before joining the
elements by periods. The normalization process is little
more than replacing periods with dashes.
:param float duration: timing to record in seconds
:param path: elements of the metric path to record
"""
self.application.statsd.send(path, duration * 1000.0, 'ms') | [
"def",
"record_timing",
"(",
"self",
",",
"duration",
",",
"*",
"path",
")",
":",
"self",
".",
"application",
".",
"statsd",
".",
"send",
"(",
"path",
",",
"duration",
"*",
"1000.0",
",",
"'ms'",
")"
]
| Record a timing.
This method records a timing to the application's namespace
followed by a calculated path. Each element of `path` is
converted to a string and normalized before joining the
elements by periods. The normalization process is little
more than replacing periods with dashes.
:param float duration: timing to record in seconds
:param path: elements of the metric path to record | [
"Record",
"a",
"timing",
"."
]
| 0b17d5f0c09a2be9db779e17e6789d3d5ff9a0d0 | https://github.com/sprockets/sprockets.mixins.metrics/blob/0b17d5f0c09a2be9db779e17e6789d3d5ff9a0d0/sprockets/mixins/metrics/statsd.py#L19-L32 | train |
sprockets/sprockets.mixins.metrics | sprockets/mixins/metrics/statsd.py | StatsdMixin.increase_counter | def increase_counter(self, *path, **kwargs):
"""Increase a counter.
This method increases a counter within the application's
namespace. Each element of `path` is converted to a string
and normalized before joining the elements by periods. The
normalization process is little more than replacing periods
with dashes.
:param path: elements of the metric path to incr
:keyword int amount: amount to increase the counter by. If
omitted, the counter is increased by one.
"""
self.application.statsd.send(path, kwargs.get('amount', '1'), 'c') | python | def increase_counter(self, *path, **kwargs):
"""Increase a counter.
This method increases a counter within the application's
namespace. Each element of `path` is converted to a string
and normalized before joining the elements by periods. The
normalization process is little more than replacing periods
with dashes.
:param path: elements of the metric path to incr
:keyword int amount: amount to increase the counter by. If
omitted, the counter is increased by one.
"""
self.application.statsd.send(path, kwargs.get('amount', '1'), 'c') | [
"def",
"increase_counter",
"(",
"self",
",",
"*",
"path",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"application",
".",
"statsd",
".",
"send",
"(",
"path",
",",
"kwargs",
".",
"get",
"(",
"'amount'",
",",
"'1'",
")",
",",
"'c'",
")"
]
| Increase a counter.
This method increases a counter within the application's
namespace. Each element of `path` is converted to a string
and normalized before joining the elements by periods. The
normalization process is little more than replacing periods
with dashes.
:param path: elements of the metric path to incr
:keyword int amount: amount to increase the counter by. If
omitted, the counter is increased by one. | [
"Increase",
"a",
"counter",
"."
]
| 0b17d5f0c09a2be9db779e17e6789d3d5ff9a0d0 | https://github.com/sprockets/sprockets.mixins.metrics/blob/0b17d5f0c09a2be9db779e17e6789d3d5ff9a0d0/sprockets/mixins/metrics/statsd.py#L34-L48 | train |
sprockets/sprockets.mixins.metrics | sprockets/mixins/metrics/statsd.py | StatsdMixin.execution_timer | def execution_timer(self, *path):
"""
Record the time it takes to perform an arbitrary code block.
:param path: elements of the metric path to record
This method returns a context manager that records the amount
of time spent inside of the context and submits a timing metric
to the specified `path` using (:meth:`record_timing`).
"""
start = time.time()
try:
yield
finally:
self.record_timing(max(start, time.time()) - start, *path) | python | def execution_timer(self, *path):
"""
Record the time it takes to perform an arbitrary code block.
:param path: elements of the metric path to record
This method returns a context manager that records the amount
of time spent inside of the context and submits a timing metric
to the specified `path` using (:meth:`record_timing`).
"""
start = time.time()
try:
yield
finally:
self.record_timing(max(start, time.time()) - start, *path) | [
"def",
"execution_timer",
"(",
"self",
",",
"*",
"path",
")",
":",
"start",
"=",
"time",
".",
"time",
"(",
")",
"try",
":",
"yield",
"finally",
":",
"self",
".",
"record_timing",
"(",
"max",
"(",
"start",
",",
"time",
".",
"time",
"(",
")",
")",
"-",
"start",
",",
"*",
"path",
")"
]
| Record the time it takes to perform an arbitrary code block.
:param path: elements of the metric path to record
This method returns a context manager that records the amount
of time spent inside of the context and submits a timing metric
to the specified `path` using (:meth:`record_timing`). | [
"Record",
"the",
"time",
"it",
"takes",
"to",
"perform",
"an",
"arbitrary",
"code",
"block",
"."
]
| 0b17d5f0c09a2be9db779e17e6789d3d5ff9a0d0 | https://github.com/sprockets/sprockets.mixins.metrics/blob/0b17d5f0c09a2be9db779e17e6789d3d5ff9a0d0/sprockets/mixins/metrics/statsd.py#L51-L66 | train |
sprockets/sprockets.mixins.metrics | sprockets/mixins/metrics/statsd.py | StatsdMixin.on_finish | def on_finish(self):
"""
Records the time taken to process the request.
This method records the amount of time taken to process the request
(as reported by
:meth:`~tornado.httputil.HTTPServerRequest.request_time`) under the
path defined by the class's module, it's name, the request method,
and the status code. The :meth:`.record_timing` method is used
to send the metric, so the configured namespace is used as well.
"""
super().on_finish()
self.record_timing(self.request.request_time(),
self.__class__.__name__, self.request.method,
self.get_status()) | python | def on_finish(self):
"""
Records the time taken to process the request.
This method records the amount of time taken to process the request
(as reported by
:meth:`~tornado.httputil.HTTPServerRequest.request_time`) under the
path defined by the class's module, it's name, the request method,
and the status code. The :meth:`.record_timing` method is used
to send the metric, so the configured namespace is used as well.
"""
super().on_finish()
self.record_timing(self.request.request_time(),
self.__class__.__name__, self.request.method,
self.get_status()) | [
"def",
"on_finish",
"(",
"self",
")",
":",
"super",
"(",
")",
".",
"on_finish",
"(",
")",
"self",
".",
"record_timing",
"(",
"self",
".",
"request",
".",
"request_time",
"(",
")",
",",
"self",
".",
"__class__",
".",
"__name__",
",",
"self",
".",
"request",
".",
"method",
",",
"self",
".",
"get_status",
"(",
")",
")"
]
| Records the time taken to process the request.
This method records the amount of time taken to process the request
(as reported by
:meth:`~tornado.httputil.HTTPServerRequest.request_time`) under the
path defined by the class's module, it's name, the request method,
and the status code. The :meth:`.record_timing` method is used
to send the metric, so the configured namespace is used as well. | [
"Records",
"the",
"time",
"taken",
"to",
"process",
"the",
"request",
"."
]
| 0b17d5f0c09a2be9db779e17e6789d3d5ff9a0d0 | https://github.com/sprockets/sprockets.mixins.metrics/blob/0b17d5f0c09a2be9db779e17e6789d3d5ff9a0d0/sprockets/mixins/metrics/statsd.py#L68-L83 | train |
sprockets/sprockets.mixins.metrics | sprockets/mixins/metrics/statsd.py | StatsDCollector._tcp_on_closed | async def _tcp_on_closed(self):
"""Invoked when the socket is closed."""
LOGGER.warning('Not connected to statsd, connecting in %s seconds',
self._tcp_reconnect_sleep)
await asyncio.sleep(self._tcp_reconnect_sleep)
self._sock = self._tcp_socket() | python | async def _tcp_on_closed(self):
"""Invoked when the socket is closed."""
LOGGER.warning('Not connected to statsd, connecting in %s seconds',
self._tcp_reconnect_sleep)
await asyncio.sleep(self._tcp_reconnect_sleep)
self._sock = self._tcp_socket() | [
"async",
"def",
"_tcp_on_closed",
"(",
"self",
")",
":",
"LOGGER",
".",
"warning",
"(",
"'Not connected to statsd, connecting in %s seconds'",
",",
"self",
".",
"_tcp_reconnect_sleep",
")",
"await",
"asyncio",
".",
"sleep",
"(",
"self",
".",
"_tcp_reconnect_sleep",
")",
"self",
".",
"_sock",
"=",
"self",
".",
"_tcp_socket",
"(",
")"
]
| Invoked when the socket is closed. | [
"Invoked",
"when",
"the",
"socket",
"is",
"closed",
"."
]
| 0b17d5f0c09a2be9db779e17e6789d3d5ff9a0d0 | https://github.com/sprockets/sprockets.mixins.metrics/blob/0b17d5f0c09a2be9db779e17e6789d3d5ff9a0d0/sprockets/mixins/metrics/statsd.py#L135-L140 | train |
sprockets/sprockets.mixins.metrics | sprockets/mixins/metrics/statsd.py | StatsDCollector.send | def send(self, path, value, metric_type):
"""Send a metric to Statsd.
:param list path: The metric path to record
:param mixed value: The value to record
:param str metric_type: The metric type
"""
msg = self._msg_format.format(
path=self._build_path(path, metric_type),
value=value,
metric_type=metric_type)
LOGGER.debug('Sending %s to %s:%s', msg.encode('ascii'),
self._host, self._port)
try:
if self._tcp:
if self._sock.closed():
return
return self._sock.write(msg.encode('ascii'))
self._sock.sendto(msg.encode('ascii'), (self._host, self._port))
except iostream.StreamClosedError as error: # pragma: nocover
LOGGER.warning('Error sending TCP statsd metric: %s', error)
except (OSError, socket.error) as error: # pragma: nocover
LOGGER.exception('Error sending statsd metric: %s', error) | python | def send(self, path, value, metric_type):
"""Send a metric to Statsd.
:param list path: The metric path to record
:param mixed value: The value to record
:param str metric_type: The metric type
"""
msg = self._msg_format.format(
path=self._build_path(path, metric_type),
value=value,
metric_type=metric_type)
LOGGER.debug('Sending %s to %s:%s', msg.encode('ascii'),
self._host, self._port)
try:
if self._tcp:
if self._sock.closed():
return
return self._sock.write(msg.encode('ascii'))
self._sock.sendto(msg.encode('ascii'), (self._host, self._port))
except iostream.StreamClosedError as error: # pragma: nocover
LOGGER.warning('Error sending TCP statsd metric: %s', error)
except (OSError, socket.error) as error: # pragma: nocover
LOGGER.exception('Error sending statsd metric: %s', error) | [
"def",
"send",
"(",
"self",
",",
"path",
",",
"value",
",",
"metric_type",
")",
":",
"msg",
"=",
"self",
".",
"_msg_format",
".",
"format",
"(",
"path",
"=",
"self",
".",
"_build_path",
"(",
"path",
",",
"metric_type",
")",
",",
"value",
"=",
"value",
",",
"metric_type",
"=",
"metric_type",
")",
"LOGGER",
".",
"debug",
"(",
"'Sending %s to %s:%s'",
",",
"msg",
".",
"encode",
"(",
"'ascii'",
")",
",",
"self",
".",
"_host",
",",
"self",
".",
"_port",
")",
"try",
":",
"if",
"self",
".",
"_tcp",
":",
"if",
"self",
".",
"_sock",
".",
"closed",
"(",
")",
":",
"return",
"return",
"self",
".",
"_sock",
".",
"write",
"(",
"msg",
".",
"encode",
"(",
"'ascii'",
")",
")",
"self",
".",
"_sock",
".",
"sendto",
"(",
"msg",
".",
"encode",
"(",
"'ascii'",
")",
",",
"(",
"self",
".",
"_host",
",",
"self",
".",
"_port",
")",
")",
"except",
"iostream",
".",
"StreamClosedError",
"as",
"error",
":",
"# pragma: nocover",
"LOGGER",
".",
"warning",
"(",
"'Error sending TCP statsd metric: %s'",
",",
"error",
")",
"except",
"(",
"OSError",
",",
"socket",
".",
"error",
")",
"as",
"error",
":",
"# pragma: nocover",
"LOGGER",
".",
"exception",
"(",
"'Error sending statsd metric: %s'",
",",
"error",
")"
]
| Send a metric to Statsd.
:param list path: The metric path to record
:param mixed value: The value to record
:param str metric_type: The metric type | [
"Send",
"a",
"metric",
"to",
"Statsd",
"."
]
| 0b17d5f0c09a2be9db779e17e6789d3d5ff9a0d0 | https://github.com/sprockets/sprockets.mixins.metrics/blob/0b17d5f0c09a2be9db779e17e6789d3d5ff9a0d0/sprockets/mixins/metrics/statsd.py#L146-L172 | train |
sprockets/sprockets.mixins.metrics | sprockets/mixins/metrics/statsd.py | StatsDCollector._build_path | def _build_path(self, path, metric_type):
"""Return a normalized path.
:param list path: elements of the metric path to record
:param str metric_type: The metric type
:rtype: str
"""
path = self._get_prefixes(metric_type) + list(path)
return '{}.{}'.format(self._namespace,
'.'.join(str(p).replace('.', '-') for p in path)) | python | def _build_path(self, path, metric_type):
"""Return a normalized path.
:param list path: elements of the metric path to record
:param str metric_type: The metric type
:rtype: str
"""
path = self._get_prefixes(metric_type) + list(path)
return '{}.{}'.format(self._namespace,
'.'.join(str(p).replace('.', '-') for p in path)) | [
"def",
"_build_path",
"(",
"self",
",",
"path",
",",
"metric_type",
")",
":",
"path",
"=",
"self",
".",
"_get_prefixes",
"(",
"metric_type",
")",
"+",
"list",
"(",
"path",
")",
"return",
"'{}.{}'",
".",
"format",
"(",
"self",
".",
"_namespace",
",",
"'.'",
".",
"join",
"(",
"str",
"(",
"p",
")",
".",
"replace",
"(",
"'.'",
",",
"'-'",
")",
"for",
"p",
"in",
"path",
")",
")"
]
| Return a normalized path.
:param list path: elements of the metric path to record
:param str metric_type: The metric type
:rtype: str | [
"Return",
"a",
"normalized",
"path",
"."
]
| 0b17d5f0c09a2be9db779e17e6789d3d5ff9a0d0 | https://github.com/sprockets/sprockets.mixins.metrics/blob/0b17d5f0c09a2be9db779e17e6789d3d5ff9a0d0/sprockets/mixins/metrics/statsd.py#L174-L184 | train |
sprockets/sprockets.mixins.metrics | sprockets/mixins/metrics/statsd.py | StatsDCollector._get_prefixes | def _get_prefixes(self, metric_type):
"""Get prefixes where applicable
Add metric prefix counters, timers respectively if
:attr:`prepend_metric_type` flag is True.
:param str metric_type: The metric type
:rtype: list
"""
prefixes = []
if self._prepend_metric_type:
prefixes.append(self.METRIC_TYPES[metric_type])
return prefixes | python | def _get_prefixes(self, metric_type):
"""Get prefixes where applicable
Add metric prefix counters, timers respectively if
:attr:`prepend_metric_type` flag is True.
:param str metric_type: The metric type
:rtype: list
"""
prefixes = []
if self._prepend_metric_type:
prefixes.append(self.METRIC_TYPES[metric_type])
return prefixes | [
"def",
"_get_prefixes",
"(",
"self",
",",
"metric_type",
")",
":",
"prefixes",
"=",
"[",
"]",
"if",
"self",
".",
"_prepend_metric_type",
":",
"prefixes",
".",
"append",
"(",
"self",
".",
"METRIC_TYPES",
"[",
"metric_type",
"]",
")",
"return",
"prefixes"
]
| Get prefixes where applicable
Add metric prefix counters, timers respectively if
:attr:`prepend_metric_type` flag is True.
:param str metric_type: The metric type
:rtype: list | [
"Get",
"prefixes",
"where",
"applicable"
]
| 0b17d5f0c09a2be9db779e17e6789d3d5ff9a0d0 | https://github.com/sprockets/sprockets.mixins.metrics/blob/0b17d5f0c09a2be9db779e17e6789d3d5ff9a0d0/sprockets/mixins/metrics/statsd.py#L186-L199 | train |
mesbahamin/chronophore | chronophore/qtview.py | QtChronophoreUI._show_feedback_label | def _show_feedback_label(self, message, seconds=None):
"""Display a message in lbl_feedback, which times out after some
number of seconds.
"""
if seconds is None:
seconds = CONFIG['MESSAGE_DURATION']
logger.debug('Label feedback: "{}"'.format(message))
self.feedback_label_timer.timeout.connect(self._hide_feedback_label)
self.lbl_feedback.setText(str(message))
self.lbl_feedback.show()
self.feedback_label_timer.start(1000 * seconds) | python | def _show_feedback_label(self, message, seconds=None):
"""Display a message in lbl_feedback, which times out after some
number of seconds.
"""
if seconds is None:
seconds = CONFIG['MESSAGE_DURATION']
logger.debug('Label feedback: "{}"'.format(message))
self.feedback_label_timer.timeout.connect(self._hide_feedback_label)
self.lbl_feedback.setText(str(message))
self.lbl_feedback.show()
self.feedback_label_timer.start(1000 * seconds) | [
"def",
"_show_feedback_label",
"(",
"self",
",",
"message",
",",
"seconds",
"=",
"None",
")",
":",
"if",
"seconds",
"is",
"None",
":",
"seconds",
"=",
"CONFIG",
"[",
"'MESSAGE_DURATION'",
"]",
"logger",
".",
"debug",
"(",
"'Label feedback: \"{}\"'",
".",
"format",
"(",
"message",
")",
")",
"self",
".",
"feedback_label_timer",
".",
"timeout",
".",
"connect",
"(",
"self",
".",
"_hide_feedback_label",
")",
"self",
".",
"lbl_feedback",
".",
"setText",
"(",
"str",
"(",
"message",
")",
")",
"self",
".",
"lbl_feedback",
".",
"show",
"(",
")",
"self",
".",
"feedback_label_timer",
".",
"start",
"(",
"1000",
"*",
"seconds",
")"
]
| Display a message in lbl_feedback, which times out after some
number of seconds. | [
"Display",
"a",
"message",
"in",
"lbl_feedback",
"which",
"times",
"out",
"after",
"some",
"number",
"of",
"seconds",
"."
]
| ee140c61b4dfada966f078de8304bac737cec6f7 | https://github.com/mesbahamin/chronophore/blob/ee140c61b4dfada966f078de8304bac737cec6f7/chronophore/qtview.py#L137-L149 | train |
mesbahamin/chronophore | chronophore/qtview.py | QtUserTypeSelectionDialog.update_user_type | def update_user_type(self):
"""Return either 'tutor' or 'student' based on which radio
button is selected.
"""
if self.rb_tutor.isChecked():
self.user_type = 'tutor'
elif self.rb_student.isChecked():
self.user_type = 'student'
self.accept() | python | def update_user_type(self):
"""Return either 'tutor' or 'student' based on which radio
button is selected.
"""
if self.rb_tutor.isChecked():
self.user_type = 'tutor'
elif self.rb_student.isChecked():
self.user_type = 'student'
self.accept() | [
"def",
"update_user_type",
"(",
"self",
")",
":",
"if",
"self",
".",
"rb_tutor",
".",
"isChecked",
"(",
")",
":",
"self",
".",
"user_type",
"=",
"'tutor'",
"elif",
"self",
".",
"rb_student",
".",
"isChecked",
"(",
")",
":",
"self",
".",
"user_type",
"=",
"'student'",
"self",
".",
"accept",
"(",
")"
]
| Return either 'tutor' or 'student' based on which radio
button is selected. | [
"Return",
"either",
"tutor",
"or",
"student",
"based",
"on",
"which",
"radio",
"button",
"is",
"selected",
"."
]
| ee140c61b4dfada966f078de8304bac737cec6f7 | https://github.com/mesbahamin/chronophore/blob/ee140c61b4dfada966f078de8304bac737cec6f7/chronophore/qtview.py#L278-L286 | train |
pereorga/csvshuf | csvshuf/csvshuf.py | shuffle_sattolo | def shuffle_sattolo(items):
"""Shuffle items in place using Sattolo's algorithm."""
_randrange = random.randrange
for i in reversed(range(1, len(items))):
j = _randrange(i) # 0 <= j < i
items[j], items[i] = items[i], items[j] | python | def shuffle_sattolo(items):
"""Shuffle items in place using Sattolo's algorithm."""
_randrange = random.randrange
for i in reversed(range(1, len(items))):
j = _randrange(i) # 0 <= j < i
items[j], items[i] = items[i], items[j] | [
"def",
"shuffle_sattolo",
"(",
"items",
")",
":",
"_randrange",
"=",
"random",
".",
"randrange",
"for",
"i",
"in",
"reversed",
"(",
"range",
"(",
"1",
",",
"len",
"(",
"items",
")",
")",
")",
":",
"j",
"=",
"_randrange",
"(",
"i",
")",
"# 0 <= j < i",
"items",
"[",
"j",
"]",
",",
"items",
"[",
"i",
"]",
"=",
"items",
"[",
"i",
"]",
",",
"items",
"[",
"j",
"]"
]
| Shuffle items in place using Sattolo's algorithm. | [
"Shuffle",
"items",
"in",
"place",
"using",
"Sattolo",
"s",
"algorithm",
"."
]
| 70fdd4f512ef980bffe9cc51bfe59fea116d7c2f | https://github.com/pereorga/csvshuf/blob/70fdd4f512ef980bffe9cc51bfe59fea116d7c2f/csvshuf/csvshuf.py#L19-L24 | train |
pereorga/csvshuf | csvshuf/csvshuf.py | column_list | def column_list(string):
"""Validate and convert comma-separated list of column numbers."""
try:
columns = list(map(int, string.split(',')))
except ValueError as e:
raise argparse.ArgumentTypeError(*e.args)
for column in columns:
if column < 1:
raise argparse.ArgumentTypeError(
'Invalid column {!r}: column numbers start at 1.'
.format(column))
return columns | python | def column_list(string):
"""Validate and convert comma-separated list of column numbers."""
try:
columns = list(map(int, string.split(',')))
except ValueError as e:
raise argparse.ArgumentTypeError(*e.args)
for column in columns:
if column < 1:
raise argparse.ArgumentTypeError(
'Invalid column {!r}: column numbers start at 1.'
.format(column))
return columns | [
"def",
"column_list",
"(",
"string",
")",
":",
"try",
":",
"columns",
"=",
"list",
"(",
"map",
"(",
"int",
",",
"string",
".",
"split",
"(",
"','",
")",
")",
")",
"except",
"ValueError",
"as",
"e",
":",
"raise",
"argparse",
".",
"ArgumentTypeError",
"(",
"*",
"e",
".",
"args",
")",
"for",
"column",
"in",
"columns",
":",
"if",
"column",
"<",
"1",
":",
"raise",
"argparse",
".",
"ArgumentTypeError",
"(",
"'Invalid column {!r}: column numbers start at 1.'",
".",
"format",
"(",
"column",
")",
")",
"return",
"columns"
]
| Validate and convert comma-separated list of column numbers. | [
"Validate",
"and",
"convert",
"comma",
"-",
"separated",
"list",
"of",
"column",
"numbers",
"."
]
| 70fdd4f512ef980bffe9cc51bfe59fea116d7c2f | https://github.com/pereorga/csvshuf/blob/70fdd4f512ef980bffe9cc51bfe59fea116d7c2f/csvshuf/csvshuf.py#L27-L38 | train |
pereorga/csvshuf | csvshuf/csvshuf.py | main | def main():
parser = argparse.ArgumentParser(description='Shuffle columns in a CSV file')
parser.add_argument(metavar="FILE", dest='input_file', type=argparse.FileType('r'), nargs='?',
default=sys.stdin, help='Input CSV file. If omitted, read standard input.')
parser.add_argument('-s', '--sattolo',
action='store_const', const=shuffle_sattolo,
dest='shuffle', default=random.shuffle,
help="Use Sattolo's shuffle algorithm.")
col_group = parser.add_mutually_exclusive_group()
col_group.add_argument('-c', '--columns', type=column_list,
help='Comma-separated list of columns to include.')
col_group.add_argument('-C', '--no-columns', type=column_list,
help='Comma-separated list of columns to exclude.')
delim_group = parser.add_mutually_exclusive_group()
delim_group.add_argument('-d', '--delimiter', type=str, default=',',
help='Input column delimiter.')
delim_group.add_argument('-t', '--tabbed', dest='delimiter',
action='store_const', const='\t',
help='Delimit input with tabs.')
parser.add_argument('-q', '--quotechar', type=str, default='"',
help='Quote character.')
parser.add_argument('-o', '--output-delimiter', type=str, default=',',
help='Output column delimiter.')
parser.add_argument('-v', '--version', action='version',
version='%(prog)s {version}'.format(version=__version__))
args = parser.parse_args()
reader = csv.reader(args.input_file, delimiter=args.delimiter, quotechar=args.quotechar)
"""Get the first row and use it as column headers"""
headers = next(reader)
"""Create a matrix of lists of columns"""
table = []
for c in range(len(headers)):
table.append([])
for row in reader:
for c in range(len(headers)):
table[c].append(row[c])
cols = args.columns
if args.no_columns:
"""If columns to exclude are provided, get a list of all other columns"""
cols = list(set(range(len(headers))) - set(args.no_columns))
elif not cols:
"""If no columns are provided all columns will be shuffled"""
cols = range(len(headers))
for c in cols:
if c > len(headers):
sys.stderr.write('Invalid column {0}. Last column is {1}.\n'.format(c, len(headers)))
exit(1)
args.shuffle(table[c - 1])
"""Transpose the matrix"""
table = zip(*table)
writer = csv.writer(sys.stdout, delimiter=args.output_delimiter)
writer.writerow(headers)
for row in table:
writer.writerow(row) | python | def main():
parser = argparse.ArgumentParser(description='Shuffle columns in a CSV file')
parser.add_argument(metavar="FILE", dest='input_file', type=argparse.FileType('r'), nargs='?',
default=sys.stdin, help='Input CSV file. If omitted, read standard input.')
parser.add_argument('-s', '--sattolo',
action='store_const', const=shuffle_sattolo,
dest='shuffle', default=random.shuffle,
help="Use Sattolo's shuffle algorithm.")
col_group = parser.add_mutually_exclusive_group()
col_group.add_argument('-c', '--columns', type=column_list,
help='Comma-separated list of columns to include.')
col_group.add_argument('-C', '--no-columns', type=column_list,
help='Comma-separated list of columns to exclude.')
delim_group = parser.add_mutually_exclusive_group()
delim_group.add_argument('-d', '--delimiter', type=str, default=',',
help='Input column delimiter.')
delim_group.add_argument('-t', '--tabbed', dest='delimiter',
action='store_const', const='\t',
help='Delimit input with tabs.')
parser.add_argument('-q', '--quotechar', type=str, default='"',
help='Quote character.')
parser.add_argument('-o', '--output-delimiter', type=str, default=',',
help='Output column delimiter.')
parser.add_argument('-v', '--version', action='version',
version='%(prog)s {version}'.format(version=__version__))
args = parser.parse_args()
reader = csv.reader(args.input_file, delimiter=args.delimiter, quotechar=args.quotechar)
"""Get the first row and use it as column headers"""
headers = next(reader)
"""Create a matrix of lists of columns"""
table = []
for c in range(len(headers)):
table.append([])
for row in reader:
for c in range(len(headers)):
table[c].append(row[c])
cols = args.columns
if args.no_columns:
"""If columns to exclude are provided, get a list of all other columns"""
cols = list(set(range(len(headers))) - set(args.no_columns))
elif not cols:
"""If no columns are provided all columns will be shuffled"""
cols = range(len(headers))
for c in cols:
if c > len(headers):
sys.stderr.write('Invalid column {0}. Last column is {1}.\n'.format(c, len(headers)))
exit(1)
args.shuffle(table[c - 1])
"""Transpose the matrix"""
table = zip(*table)
writer = csv.writer(sys.stdout, delimiter=args.output_delimiter)
writer.writerow(headers)
for row in table:
writer.writerow(row) | [
"def",
"main",
"(",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"'Shuffle columns in a CSV file'",
")",
"parser",
".",
"add_argument",
"(",
"metavar",
"=",
"\"FILE\"",
",",
"dest",
"=",
"'input_file'",
",",
"type",
"=",
"argparse",
".",
"FileType",
"(",
"'r'",
")",
",",
"nargs",
"=",
"'?'",
",",
"default",
"=",
"sys",
".",
"stdin",
",",
"help",
"=",
"'Input CSV file. If omitted, read standard input.'",
")",
"parser",
".",
"add_argument",
"(",
"'-s'",
",",
"'--sattolo'",
",",
"action",
"=",
"'store_const'",
",",
"const",
"=",
"shuffle_sattolo",
",",
"dest",
"=",
"'shuffle'",
",",
"default",
"=",
"random",
".",
"shuffle",
",",
"help",
"=",
"\"Use Sattolo's shuffle algorithm.\"",
")",
"col_group",
"=",
"parser",
".",
"add_mutually_exclusive_group",
"(",
")",
"col_group",
".",
"add_argument",
"(",
"'-c'",
",",
"'--columns'",
",",
"type",
"=",
"column_list",
",",
"help",
"=",
"'Comma-separated list of columns to include.'",
")",
"col_group",
".",
"add_argument",
"(",
"'-C'",
",",
"'--no-columns'",
",",
"type",
"=",
"column_list",
",",
"help",
"=",
"'Comma-separated list of columns to exclude.'",
")",
"delim_group",
"=",
"parser",
".",
"add_mutually_exclusive_group",
"(",
")",
"delim_group",
".",
"add_argument",
"(",
"'-d'",
",",
"'--delimiter'",
",",
"type",
"=",
"str",
",",
"default",
"=",
"','",
",",
"help",
"=",
"'Input column delimiter.'",
")",
"delim_group",
".",
"add_argument",
"(",
"'-t'",
",",
"'--tabbed'",
",",
"dest",
"=",
"'delimiter'",
",",
"action",
"=",
"'store_const'",
",",
"const",
"=",
"'\\t'",
",",
"help",
"=",
"'Delimit input with tabs.'",
")",
"parser",
".",
"add_argument",
"(",
"'-q'",
",",
"'--quotechar'",
",",
"type",
"=",
"str",
",",
"default",
"=",
"'\"'",
",",
"help",
"=",
"'Quote character.'",
")",
"parser",
".",
"add_argument",
"(",
"'-o'",
",",
"'--output-delimiter'",
",",
"type",
"=",
"str",
",",
"default",
"=",
"','",
",",
"help",
"=",
"'Output column delimiter.'",
")",
"parser",
".",
"add_argument",
"(",
"'-v'",
",",
"'--version'",
",",
"action",
"=",
"'version'",
",",
"version",
"=",
"'%(prog)s {version}'",
".",
"format",
"(",
"version",
"=",
"__version__",
")",
")",
"args",
"=",
"parser",
".",
"parse_args",
"(",
")",
"reader",
"=",
"csv",
".",
"reader",
"(",
"args",
".",
"input_file",
",",
"delimiter",
"=",
"args",
".",
"delimiter",
",",
"quotechar",
"=",
"args",
".",
"quotechar",
")",
"headers",
"=",
"next",
"(",
"reader",
")",
"\"\"\"Create a matrix of lists of columns\"\"\"",
"table",
"=",
"[",
"]",
"for",
"c",
"in",
"range",
"(",
"len",
"(",
"headers",
")",
")",
":",
"table",
".",
"append",
"(",
"[",
"]",
")",
"for",
"row",
"in",
"reader",
":",
"for",
"c",
"in",
"range",
"(",
"len",
"(",
"headers",
")",
")",
":",
"table",
"[",
"c",
"]",
".",
"append",
"(",
"row",
"[",
"c",
"]",
")",
"cols",
"=",
"args",
".",
"columns",
"if",
"args",
".",
"no_columns",
":",
"\"\"\"If columns to exclude are provided, get a list of all other columns\"\"\"",
"cols",
"=",
"list",
"(",
"set",
"(",
"range",
"(",
"len",
"(",
"headers",
")",
")",
")",
"-",
"set",
"(",
"args",
".",
"no_columns",
")",
")",
"elif",
"not",
"cols",
":",
"\"\"\"If no columns are provided all columns will be shuffled\"\"\"",
"cols",
"=",
"range",
"(",
"len",
"(",
"headers",
")",
")",
"for",
"c",
"in",
"cols",
":",
"if",
"c",
">",
"len",
"(",
"headers",
")",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"'Invalid column {0}. Last column is {1}.\\n'",
".",
"format",
"(",
"c",
",",
"len",
"(",
"headers",
")",
")",
")",
"exit",
"(",
"1",
")",
"args",
".",
"shuffle",
"(",
"table",
"[",
"c",
"-",
"1",
"]",
")",
"\"\"\"Transpose the matrix\"\"\"",
"table",
"=",
"zip",
"(",
"*",
"table",
")",
"writer",
"=",
"csv",
".",
"writer",
"(",
"sys",
".",
"stdout",
",",
"delimiter",
"=",
"args",
".",
"output_delimiter",
")",
"writer",
".",
"writerow",
"(",
"headers",
")",
"for",
"row",
"in",
"table",
":",
"writer",
".",
"writerow",
"(",
"row",
")"
]
| Get the first row and use it as column headers | [
"Get",
"the",
"first",
"row",
"and",
"use",
"it",
"as",
"column",
"headers"
]
| 70fdd4f512ef980bffe9cc51bfe59fea116d7c2f | https://github.com/pereorga/csvshuf/blob/70fdd4f512ef980bffe9cc51bfe59fea116d7c2f/csvshuf/csvshuf.py#L41-L101 | train |
bgyori/pykqml | kqml/kqml_list.py | KQMLList.get | def get(self, keyword):
"""Return the element of the list after the given keyword.
Parameters
----------
keyword : str
The keyword parameter to find in the list.
Putting a colon before the keyword is optional, if no colon is
given, it is added automatically (e.g. "keyword" will be found as
":keyword" in the list).
Returns
-------
obj : KQMLObject
The object corresponding to the keyword parameter
Example:
kl = KQMLList.from_string('(FAILURE :reason INVALID_PARAMETER)')
kl.get('reason') # KQMLToken('INVALID_PARAMETER')
"""
if not keyword.startswith(':'):
keyword = ':' + keyword
for i, s in enumerate(self.data):
if s.to_string().upper() == keyword.upper():
if i < len(self.data)-1:
return self.data[i+1]
else:
return None
return None | python | def get(self, keyword):
"""Return the element of the list after the given keyword.
Parameters
----------
keyword : str
The keyword parameter to find in the list.
Putting a colon before the keyword is optional, if no colon is
given, it is added automatically (e.g. "keyword" will be found as
":keyword" in the list).
Returns
-------
obj : KQMLObject
The object corresponding to the keyword parameter
Example:
kl = KQMLList.from_string('(FAILURE :reason INVALID_PARAMETER)')
kl.get('reason') # KQMLToken('INVALID_PARAMETER')
"""
if not keyword.startswith(':'):
keyword = ':' + keyword
for i, s in enumerate(self.data):
if s.to_string().upper() == keyword.upper():
if i < len(self.data)-1:
return self.data[i+1]
else:
return None
return None | [
"def",
"get",
"(",
"self",
",",
"keyword",
")",
":",
"if",
"not",
"keyword",
".",
"startswith",
"(",
"':'",
")",
":",
"keyword",
"=",
"':'",
"+",
"keyword",
"for",
"i",
",",
"s",
"in",
"enumerate",
"(",
"self",
".",
"data",
")",
":",
"if",
"s",
".",
"to_string",
"(",
")",
".",
"upper",
"(",
")",
"==",
"keyword",
".",
"upper",
"(",
")",
":",
"if",
"i",
"<",
"len",
"(",
"self",
".",
"data",
")",
"-",
"1",
":",
"return",
"self",
".",
"data",
"[",
"i",
"+",
"1",
"]",
"else",
":",
"return",
"None",
"return",
"None"
]
| Return the element of the list after the given keyword.
Parameters
----------
keyword : str
The keyword parameter to find in the list.
Putting a colon before the keyword is optional, if no colon is
given, it is added automatically (e.g. "keyword" will be found as
":keyword" in the list).
Returns
-------
obj : KQMLObject
The object corresponding to the keyword parameter
Example:
kl = KQMLList.from_string('(FAILURE :reason INVALID_PARAMETER)')
kl.get('reason') # KQMLToken('INVALID_PARAMETER') | [
"Return",
"the",
"element",
"of",
"the",
"list",
"after",
"the",
"given",
"keyword",
"."
]
| c18b39868626215deb634567c6bd7c0838e443c0 | https://github.com/bgyori/pykqml/blob/c18b39868626215deb634567c6bd7c0838e443c0/kqml/kqml_list.py#L44-L72 | train |
bgyori/pykqml | kqml/kqml_list.py | KQMLList.gets | def gets(self, keyword):
"""Return the element of the list after the given keyword as string.
Parameters
----------
keyword : str
The keyword parameter to find in the list.
Putting a colon before the keyword is optional, if no colon is
given, it is added automatically (e.g. "keyword" will be found as
":keyword" in the list).
Returns
-------
obj_str : str
The string value corresponding to the keyword parameter
Example:
kl = KQMLList.from_string('(FAILURE :reason INVALID_PARAMETER)')
kl.gets('reason') # 'INVALID_PARAMETER'
"""
param = self.get(keyword)
if param is not None:
return safe_decode(param.string_value())
return None | python | def gets(self, keyword):
"""Return the element of the list after the given keyword as string.
Parameters
----------
keyword : str
The keyword parameter to find in the list.
Putting a colon before the keyword is optional, if no colon is
given, it is added automatically (e.g. "keyword" will be found as
":keyword" in the list).
Returns
-------
obj_str : str
The string value corresponding to the keyword parameter
Example:
kl = KQMLList.from_string('(FAILURE :reason INVALID_PARAMETER)')
kl.gets('reason') # 'INVALID_PARAMETER'
"""
param = self.get(keyword)
if param is not None:
return safe_decode(param.string_value())
return None | [
"def",
"gets",
"(",
"self",
",",
"keyword",
")",
":",
"param",
"=",
"self",
".",
"get",
"(",
"keyword",
")",
"if",
"param",
"is",
"not",
"None",
":",
"return",
"safe_decode",
"(",
"param",
".",
"string_value",
"(",
")",
")",
"return",
"None"
]
| Return the element of the list after the given keyword as string.
Parameters
----------
keyword : str
The keyword parameter to find in the list.
Putting a colon before the keyword is optional, if no colon is
given, it is added automatically (e.g. "keyword" will be found as
":keyword" in the list).
Returns
-------
obj_str : str
The string value corresponding to the keyword parameter
Example:
kl = KQMLList.from_string('(FAILURE :reason INVALID_PARAMETER)')
kl.gets('reason') # 'INVALID_PARAMETER' | [
"Return",
"the",
"element",
"of",
"the",
"list",
"after",
"the",
"given",
"keyword",
"as",
"string",
"."
]
| c18b39868626215deb634567c6bd7c0838e443c0 | https://github.com/bgyori/pykqml/blob/c18b39868626215deb634567c6bd7c0838e443c0/kqml/kqml_list.py#L74-L97 | train |
bgyori/pykqml | kqml/kqml_list.py | KQMLList.append | def append(self, obj):
"""Append an element to the end of the list.
Parameters
----------
obj : KQMLObject or str
If a string is passed, it is instantiated as a
KQMLToken before being added to the list.
"""
if isinstance(obj, str):
obj = KQMLToken(obj)
self.data.append(obj) | python | def append(self, obj):
"""Append an element to the end of the list.
Parameters
----------
obj : KQMLObject or str
If a string is passed, it is instantiated as a
KQMLToken before being added to the list.
"""
if isinstance(obj, str):
obj = KQMLToken(obj)
self.data.append(obj) | [
"def",
"append",
"(",
"self",
",",
"obj",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"str",
")",
":",
"obj",
"=",
"KQMLToken",
"(",
"obj",
")",
"self",
".",
"data",
".",
"append",
"(",
"obj",
")"
]
| Append an element to the end of the list.
Parameters
----------
obj : KQMLObject or str
If a string is passed, it is instantiated as a
KQMLToken before being added to the list. | [
"Append",
"an",
"element",
"to",
"the",
"end",
"of",
"the",
"list",
"."
]
| c18b39868626215deb634567c6bd7c0838e443c0 | https://github.com/bgyori/pykqml/blob/c18b39868626215deb634567c6bd7c0838e443c0/kqml/kqml_list.py#L100-L111 | train |
bgyori/pykqml | kqml/kqml_list.py | KQMLList.push | def push(self, obj):
"""Prepend an element to the beginnging of the list.
Parameters
----------
obj : KQMLObject or str
If a string is passed, it is instantiated as a
KQMLToken before being added to the list.
"""
if isinstance(obj, str):
obj = KQMLToken(obj)
self.data.insert(0, obj) | python | def push(self, obj):
"""Prepend an element to the beginnging of the list.
Parameters
----------
obj : KQMLObject or str
If a string is passed, it is instantiated as a
KQMLToken before being added to the list.
"""
if isinstance(obj, str):
obj = KQMLToken(obj)
self.data.insert(0, obj) | [
"def",
"push",
"(",
"self",
",",
"obj",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"str",
")",
":",
"obj",
"=",
"KQMLToken",
"(",
"obj",
")",
"self",
".",
"data",
".",
"insert",
"(",
"0",
",",
"obj",
")"
]
| Prepend an element to the beginnging of the list.
Parameters
----------
obj : KQMLObject or str
If a string is passed, it is instantiated as a
KQMLToken before being added to the list. | [
"Prepend",
"an",
"element",
"to",
"the",
"beginnging",
"of",
"the",
"list",
"."
]
| c18b39868626215deb634567c6bd7c0838e443c0 | https://github.com/bgyori/pykqml/blob/c18b39868626215deb634567c6bd7c0838e443c0/kqml/kqml_list.py#L113-L124 | train |
bgyori/pykqml | kqml/kqml_list.py | KQMLList.set | def set(self, keyword, value):
"""Set the element of the list after the given keyword.
Parameters
----------
keyword : str
The keyword parameter to find in the list.
Putting a colon before the keyword is optional, if no colon is
given, it is added automatically (e.g. "keyword" will be found as
":keyword" in the list).
value : KQMLObject or str
If the value is given as str, it is instantiated as a KQMLToken
Example:
kl = KQMLList.from_string('(FAILURE)')
kl.set('reason', 'INVALID_PARAMETER')
"""
if not keyword.startswith(':'):
keyword = ':' + keyword
if isinstance(value, str):
value = KQMLToken(value)
if isinstance(keyword, str):
keyword = KQMLToken(keyword)
found = False
for i, key in enumerate(self.data):
if key.to_string().lower() == keyword.lower():
found = True
if i < len(self.data)-1:
self.data[i+1] = value
break
if not found:
self.data.append(keyword)
self.data.append(value) | python | def set(self, keyword, value):
"""Set the element of the list after the given keyword.
Parameters
----------
keyword : str
The keyword parameter to find in the list.
Putting a colon before the keyword is optional, if no colon is
given, it is added automatically (e.g. "keyword" will be found as
":keyword" in the list).
value : KQMLObject or str
If the value is given as str, it is instantiated as a KQMLToken
Example:
kl = KQMLList.from_string('(FAILURE)')
kl.set('reason', 'INVALID_PARAMETER')
"""
if not keyword.startswith(':'):
keyword = ':' + keyword
if isinstance(value, str):
value = KQMLToken(value)
if isinstance(keyword, str):
keyword = KQMLToken(keyword)
found = False
for i, key in enumerate(self.data):
if key.to_string().lower() == keyword.lower():
found = True
if i < len(self.data)-1:
self.data[i+1] = value
break
if not found:
self.data.append(keyword)
self.data.append(value) | [
"def",
"set",
"(",
"self",
",",
"keyword",
",",
"value",
")",
":",
"if",
"not",
"keyword",
".",
"startswith",
"(",
"':'",
")",
":",
"keyword",
"=",
"':'",
"+",
"keyword",
"if",
"isinstance",
"(",
"value",
",",
"str",
")",
":",
"value",
"=",
"KQMLToken",
"(",
"value",
")",
"if",
"isinstance",
"(",
"keyword",
",",
"str",
")",
":",
"keyword",
"=",
"KQMLToken",
"(",
"keyword",
")",
"found",
"=",
"False",
"for",
"i",
",",
"key",
"in",
"enumerate",
"(",
"self",
".",
"data",
")",
":",
"if",
"key",
".",
"to_string",
"(",
")",
".",
"lower",
"(",
")",
"==",
"keyword",
".",
"lower",
"(",
")",
":",
"found",
"=",
"True",
"if",
"i",
"<",
"len",
"(",
"self",
".",
"data",
")",
"-",
"1",
":",
"self",
".",
"data",
"[",
"i",
"+",
"1",
"]",
"=",
"value",
"break",
"if",
"not",
"found",
":",
"self",
".",
"data",
".",
"append",
"(",
"keyword",
")",
"self",
".",
"data",
".",
"append",
"(",
"value",
")"
]
| Set the element of the list after the given keyword.
Parameters
----------
keyword : str
The keyword parameter to find in the list.
Putting a colon before the keyword is optional, if no colon is
given, it is added automatically (e.g. "keyword" will be found as
":keyword" in the list).
value : KQMLObject or str
If the value is given as str, it is instantiated as a KQMLToken
Example:
kl = KQMLList.from_string('(FAILURE)')
kl.set('reason', 'INVALID_PARAMETER') | [
"Set",
"the",
"element",
"of",
"the",
"list",
"after",
"the",
"given",
"keyword",
"."
]
| c18b39868626215deb634567c6bd7c0838e443c0 | https://github.com/bgyori/pykqml/blob/c18b39868626215deb634567c6bd7c0838e443c0/kqml/kqml_list.py#L149-L182 | train |
bgyori/pykqml | kqml/kqml_list.py | KQMLList.sets | def sets(self, keyword, value):
"""Set the element of the list after the given keyword as string.
Parameters
----------
keyword : str
The keyword parameter to find in the list.
Putting a colon before the keyword is optional, if no colon is
given, it is added automatically (e.g. "keyword" will be found as
":keyword" in the list).
value : str
The value is instantiated as KQMLString and added to the list.
Example:
kl = KQMLList.from_string('(FAILURE)')
kl.sets('reason', 'this is a custom string message, not a token')
"""
if isinstance(value, str):
value = KQMLString(value)
self.set(keyword, value) | python | def sets(self, keyword, value):
"""Set the element of the list after the given keyword as string.
Parameters
----------
keyword : str
The keyword parameter to find in the list.
Putting a colon before the keyword is optional, if no colon is
given, it is added automatically (e.g. "keyword" will be found as
":keyword" in the list).
value : str
The value is instantiated as KQMLString and added to the list.
Example:
kl = KQMLList.from_string('(FAILURE)')
kl.sets('reason', 'this is a custom string message, not a token')
"""
if isinstance(value, str):
value = KQMLString(value)
self.set(keyword, value) | [
"def",
"sets",
"(",
"self",
",",
"keyword",
",",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"str",
")",
":",
"value",
"=",
"KQMLString",
"(",
"value",
")",
"self",
".",
"set",
"(",
"keyword",
",",
"value",
")"
]
| Set the element of the list after the given keyword as string.
Parameters
----------
keyword : str
The keyword parameter to find in the list.
Putting a colon before the keyword is optional, if no colon is
given, it is added automatically (e.g. "keyword" will be found as
":keyword" in the list).
value : str
The value is instantiated as KQMLString and added to the list.
Example:
kl = KQMLList.from_string('(FAILURE)')
kl.sets('reason', 'this is a custom string message, not a token') | [
"Set",
"the",
"element",
"of",
"the",
"list",
"after",
"the",
"given",
"keyword",
"as",
"string",
"."
]
| c18b39868626215deb634567c6bd7c0838e443c0 | https://github.com/bgyori/pykqml/blob/c18b39868626215deb634567c6bd7c0838e443c0/kqml/kqml_list.py#L184-L204 | train |
mastro35/flows | flows/ConfigManager.py | ConfigManager.read_recipe | def read_recipe(self, filename):
"""
Read a recipe file from disk
"""
Global.LOGGER.debug(f"reading recipe {filename}")
if not os.path.isfile(filename):
Global.LOGGER.error(filename + " recipe not found, skipping")
return
config = configparser.ConfigParser(allow_no_value=True,
delimiters="=")
config.read(filename)
for section in config.sections():
self.sections[section] = config[section]
Global.LOGGER.debug("Read recipe " + filename) | python | def read_recipe(self, filename):
"""
Read a recipe file from disk
"""
Global.LOGGER.debug(f"reading recipe {filename}")
if not os.path.isfile(filename):
Global.LOGGER.error(filename + " recipe not found, skipping")
return
config = configparser.ConfigParser(allow_no_value=True,
delimiters="=")
config.read(filename)
for section in config.sections():
self.sections[section] = config[section]
Global.LOGGER.debug("Read recipe " + filename) | [
"def",
"read_recipe",
"(",
"self",
",",
"filename",
")",
":",
"Global",
".",
"LOGGER",
".",
"debug",
"(",
"f\"reading recipe {filename}\"",
")",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"filename",
")",
":",
"Global",
".",
"LOGGER",
".",
"error",
"(",
"filename",
"+",
"\" recipe not found, skipping\"",
")",
"return",
"config",
"=",
"configparser",
".",
"ConfigParser",
"(",
"allow_no_value",
"=",
"True",
",",
"delimiters",
"=",
"\"=\"",
")",
"config",
".",
"read",
"(",
"filename",
")",
"for",
"section",
"in",
"config",
".",
"sections",
"(",
")",
":",
"self",
".",
"sections",
"[",
"section",
"]",
"=",
"config",
"[",
"section",
"]",
"Global",
".",
"LOGGER",
".",
"debug",
"(",
"\"Read recipe \"",
"+",
"filename",
")"
]
| Read a recipe file from disk | [
"Read",
"a",
"recipe",
"file",
"from",
"disk"
]
| 05e488385673a69597b5b39c7728795aa4d5eb18 | https://github.com/mastro35/flows/blob/05e488385673a69597b5b39c7728795aa4d5eb18/flows/ConfigManager.py#L56-L73 | train |
mastro35/flows | flows/ConfigManager.py | ConfigManager.set_socket_address | def set_socket_address(self):
"""
Set a random port to be used by zmq
"""
Global.LOGGER.debug('defining socket addresses for zmq')
random.seed()
default_port = random.randrange(5001, 5999)
internal_0mq_address = "tcp://127.0.0.1"
internal_0mq_port_subscriber = str(default_port)
internal_0mq_port_publisher = str(default_port)
Global.LOGGER.info(str.format(
f"zmq subsystem subscriber on {internal_0mq_port_subscriber} port"))
Global.LOGGER.info(str.format(
f"zmq subsystem publisher on {internal_0mq_port_publisher} port"))
self.subscriber_socket_address = f"{internal_0mq_address}:{internal_0mq_port_subscriber}"
self.publisher_socket_address = f"{internal_0mq_address}:{internal_0mq_port_publisher}" | python | def set_socket_address(self):
"""
Set a random port to be used by zmq
"""
Global.LOGGER.debug('defining socket addresses for zmq')
random.seed()
default_port = random.randrange(5001, 5999)
internal_0mq_address = "tcp://127.0.0.1"
internal_0mq_port_subscriber = str(default_port)
internal_0mq_port_publisher = str(default_port)
Global.LOGGER.info(str.format(
f"zmq subsystem subscriber on {internal_0mq_port_subscriber} port"))
Global.LOGGER.info(str.format(
f"zmq subsystem publisher on {internal_0mq_port_publisher} port"))
self.subscriber_socket_address = f"{internal_0mq_address}:{internal_0mq_port_subscriber}"
self.publisher_socket_address = f"{internal_0mq_address}:{internal_0mq_port_publisher}" | [
"def",
"set_socket_address",
"(",
"self",
")",
":",
"Global",
".",
"LOGGER",
".",
"debug",
"(",
"'defining socket addresses for zmq'",
")",
"random",
".",
"seed",
"(",
")",
"default_port",
"=",
"random",
".",
"randrange",
"(",
"5001",
",",
"5999",
")",
"internal_0mq_address",
"=",
"\"tcp://127.0.0.1\"",
"internal_0mq_port_subscriber",
"=",
"str",
"(",
"default_port",
")",
"internal_0mq_port_publisher",
"=",
"str",
"(",
"default_port",
")",
"Global",
".",
"LOGGER",
".",
"info",
"(",
"str",
".",
"format",
"(",
"f\"zmq subsystem subscriber on {internal_0mq_port_subscriber} port\"",
")",
")",
"Global",
".",
"LOGGER",
".",
"info",
"(",
"str",
".",
"format",
"(",
"f\"zmq subsystem publisher on {internal_0mq_port_publisher} port\"",
")",
")",
"self",
".",
"subscriber_socket_address",
"=",
"f\"{internal_0mq_address}:{internal_0mq_port_subscriber}\"",
"self",
".",
"publisher_socket_address",
"=",
"f\"{internal_0mq_address}:{internal_0mq_port_publisher}\""
]
| Set a random port to be used by zmq | [
"Set",
"a",
"random",
"port",
"to",
"be",
"used",
"by",
"zmq"
]
| 05e488385673a69597b5b39c7728795aa4d5eb18 | https://github.com/mastro35/flows/blob/05e488385673a69597b5b39c7728795aa4d5eb18/flows/ConfigManager.py#L75-L93 | train |
yymao/generic-catalog-reader | GCR/base.py | BaseGenericCatalog.get_quantities | def get_quantities(self, quantities, filters=None, native_filters=None, return_iterator=False):
"""
Fetch quantities from this catalog.
Parameters
----------
quantities : str or list of str or tuple of str
quantities to fetch
filters : list of tuple, or GCRQuery instance, optional
filters to apply. Each filter should be in the format of (callable, str, str, ...)
native_filters : list of tuple, optional
Native filters to apply. Each filter should be in the format of (callable, str, str, ...)
return_iterator : bool, optional
if True, return an iterator that iterates over the native format, default is False
Returns
-------
quantities : dict, or iterator of dict (when `return_iterator` is True)
"""
quantities = self._preprocess_requested_quantities(quantities)
filters = self._preprocess_filters(filters)
native_filters = self._preprocess_native_filters(native_filters)
it = self._get_quantities_iter(quantities, filters, native_filters)
if return_iterator:
return it
data_all = defaultdict(list)
for data in it:
for q in quantities:
data_all[q].append(data[q])
return {q: concatenate_1d(data_all[q]) for q in quantities} | python | def get_quantities(self, quantities, filters=None, native_filters=None, return_iterator=False):
"""
Fetch quantities from this catalog.
Parameters
----------
quantities : str or list of str or tuple of str
quantities to fetch
filters : list of tuple, or GCRQuery instance, optional
filters to apply. Each filter should be in the format of (callable, str, str, ...)
native_filters : list of tuple, optional
Native filters to apply. Each filter should be in the format of (callable, str, str, ...)
return_iterator : bool, optional
if True, return an iterator that iterates over the native format, default is False
Returns
-------
quantities : dict, or iterator of dict (when `return_iterator` is True)
"""
quantities = self._preprocess_requested_quantities(quantities)
filters = self._preprocess_filters(filters)
native_filters = self._preprocess_native_filters(native_filters)
it = self._get_quantities_iter(quantities, filters, native_filters)
if return_iterator:
return it
data_all = defaultdict(list)
for data in it:
for q in quantities:
data_all[q].append(data[q])
return {q: concatenate_1d(data_all[q]) for q in quantities} | [
"def",
"get_quantities",
"(",
"self",
",",
"quantities",
",",
"filters",
"=",
"None",
",",
"native_filters",
"=",
"None",
",",
"return_iterator",
"=",
"False",
")",
":",
"quantities",
"=",
"self",
".",
"_preprocess_requested_quantities",
"(",
"quantities",
")",
"filters",
"=",
"self",
".",
"_preprocess_filters",
"(",
"filters",
")",
"native_filters",
"=",
"self",
".",
"_preprocess_native_filters",
"(",
"native_filters",
")",
"it",
"=",
"self",
".",
"_get_quantities_iter",
"(",
"quantities",
",",
"filters",
",",
"native_filters",
")",
"if",
"return_iterator",
":",
"return",
"it",
"data_all",
"=",
"defaultdict",
"(",
"list",
")",
"for",
"data",
"in",
"it",
":",
"for",
"q",
"in",
"quantities",
":",
"data_all",
"[",
"q",
"]",
".",
"append",
"(",
"data",
"[",
"q",
"]",
")",
"return",
"{",
"q",
":",
"concatenate_1d",
"(",
"data_all",
"[",
"q",
"]",
")",
"for",
"q",
"in",
"quantities",
"}"
]
| Fetch quantities from this catalog.
Parameters
----------
quantities : str or list of str or tuple of str
quantities to fetch
filters : list of tuple, or GCRQuery instance, optional
filters to apply. Each filter should be in the format of (callable, str, str, ...)
native_filters : list of tuple, optional
Native filters to apply. Each filter should be in the format of (callable, str, str, ...)
return_iterator : bool, optional
if True, return an iterator that iterates over the native format, default is False
Returns
-------
quantities : dict, or iterator of dict (when `return_iterator` is True) | [
"Fetch",
"quantities",
"from",
"this",
"catalog",
"."
]
| bc6267ac41b9f68106ed6065184469ac13fdc0b6 | https://github.com/yymao/generic-catalog-reader/blob/bc6267ac41b9f68106ed6065184469ac13fdc0b6/GCR/base.py#L41-L77 | train |
yymao/generic-catalog-reader | GCR/base.py | BaseGenericCatalog.list_all_quantities | def list_all_quantities(self, include_native=False, with_info=False):
"""
Return a list of all available quantities in this catalog.
If *include_native* is `True`, includes native quantities.
If *with_info* is `True`, return a dict with quantity info.
See also: list_all_native_quantities
"""
q = set(self._quantity_modifiers)
if include_native:
q.update(self._native_quantities)
return {k: self.get_quantity_info(k) for k in q} if with_info else list(q) | python | def list_all_quantities(self, include_native=False, with_info=False):
"""
Return a list of all available quantities in this catalog.
If *include_native* is `True`, includes native quantities.
If *with_info* is `True`, return a dict with quantity info.
See also: list_all_native_quantities
"""
q = set(self._quantity_modifiers)
if include_native:
q.update(self._native_quantities)
return {k: self.get_quantity_info(k) for k in q} if with_info else list(q) | [
"def",
"list_all_quantities",
"(",
"self",
",",
"include_native",
"=",
"False",
",",
"with_info",
"=",
"False",
")",
":",
"q",
"=",
"set",
"(",
"self",
".",
"_quantity_modifiers",
")",
"if",
"include_native",
":",
"q",
".",
"update",
"(",
"self",
".",
"_native_quantities",
")",
"return",
"{",
"k",
":",
"self",
".",
"get_quantity_info",
"(",
"k",
")",
"for",
"k",
"in",
"q",
"}",
"if",
"with_info",
"else",
"list",
"(",
"q",
")"
]
| Return a list of all available quantities in this catalog.
If *include_native* is `True`, includes native quantities.
If *with_info* is `True`, return a dict with quantity info.
See also: list_all_native_quantities | [
"Return",
"a",
"list",
"of",
"all",
"available",
"quantities",
"in",
"this",
"catalog",
"."
]
| bc6267ac41b9f68106ed6065184469ac13fdc0b6 | https://github.com/yymao/generic-catalog-reader/blob/bc6267ac41b9f68106ed6065184469ac13fdc0b6/GCR/base.py#L126-L138 | train |
yymao/generic-catalog-reader | GCR/base.py | BaseGenericCatalog.list_all_native_quantities | def list_all_native_quantities(self, with_info=False):
"""
Return a list of all available native quantities in this catalog.
If *with_info* is `True`, return a dict with quantity info.
See also: list_all_quantities
"""
q = self._native_quantities
return {k: self.get_quantity_info(k) for k in q} if with_info else list(q) | python | def list_all_native_quantities(self, with_info=False):
"""
Return a list of all available native quantities in this catalog.
If *with_info* is `True`, return a dict with quantity info.
See also: list_all_quantities
"""
q = self._native_quantities
return {k: self.get_quantity_info(k) for k in q} if with_info else list(q) | [
"def",
"list_all_native_quantities",
"(",
"self",
",",
"with_info",
"=",
"False",
")",
":",
"q",
"=",
"self",
".",
"_native_quantities",
"return",
"{",
"k",
":",
"self",
".",
"get_quantity_info",
"(",
"k",
")",
"for",
"k",
"in",
"q",
"}",
"if",
"with_info",
"else",
"list",
"(",
"q",
")"
]
| Return a list of all available native quantities in this catalog.
If *with_info* is `True`, return a dict with quantity info.
See also: list_all_quantities | [
"Return",
"a",
"list",
"of",
"all",
"available",
"native",
"quantities",
"in",
"this",
"catalog",
"."
]
| bc6267ac41b9f68106ed6065184469ac13fdc0b6 | https://github.com/yymao/generic-catalog-reader/blob/bc6267ac41b9f68106ed6065184469ac13fdc0b6/GCR/base.py#L140-L149 | train |
yymao/generic-catalog-reader | GCR/base.py | BaseGenericCatalog.first_available | def first_available(self, *quantities):
"""
Return the first available quantity in the input arguments.
Return `None` if none of them is available.
"""
for i, q in enumerate(quantities):
if self.has_quantity(q):
if i:
warnings.warn('{} not available; using {} instead'.format(quantities[0], q))
return q | python | def first_available(self, *quantities):
"""
Return the first available quantity in the input arguments.
Return `None` if none of them is available.
"""
for i, q in enumerate(quantities):
if self.has_quantity(q):
if i:
warnings.warn('{} not available; using {} instead'.format(quantities[0], q))
return q | [
"def",
"first_available",
"(",
"self",
",",
"*",
"quantities",
")",
":",
"for",
"i",
",",
"q",
"in",
"enumerate",
"(",
"quantities",
")",
":",
"if",
"self",
".",
"has_quantity",
"(",
"q",
")",
":",
"if",
"i",
":",
"warnings",
".",
"warn",
"(",
"'{} not available; using {} instead'",
".",
"format",
"(",
"quantities",
"[",
"0",
"]",
",",
"q",
")",
")",
"return",
"q"
]
| Return the first available quantity in the input arguments.
Return `None` if none of them is available. | [
"Return",
"the",
"first",
"available",
"quantity",
"in",
"the",
"input",
"arguments",
".",
"Return",
"None",
"if",
"none",
"of",
"them",
"is",
"available",
"."
]
| bc6267ac41b9f68106ed6065184469ac13fdc0b6 | https://github.com/yymao/generic-catalog-reader/blob/bc6267ac41b9f68106ed6065184469ac13fdc0b6/GCR/base.py#L151-L160 | train |
yymao/generic-catalog-reader | GCR/base.py | BaseGenericCatalog.get_input_kwargs | def get_input_kwargs(self, key=None, default=None):
"""
Deprecated. Use `get_catalog_info` instead.
Get information from the catalog config file.
If *key* is `None`, return the full dict.
"""
warnings.warn("`get_input_kwargs` is deprecated; use `get_catalog_info` instead.", DeprecationWarning)
return self.get_catalog_info(key, default) | python | def get_input_kwargs(self, key=None, default=None):
"""
Deprecated. Use `get_catalog_info` instead.
Get information from the catalog config file.
If *key* is `None`, return the full dict.
"""
warnings.warn("`get_input_kwargs` is deprecated; use `get_catalog_info` instead.", DeprecationWarning)
return self.get_catalog_info(key, default) | [
"def",
"get_input_kwargs",
"(",
"self",
",",
"key",
"=",
"None",
",",
"default",
"=",
"None",
")",
":",
"warnings",
".",
"warn",
"(",
"\"`get_input_kwargs` is deprecated; use `get_catalog_info` instead.\"",
",",
"DeprecationWarning",
")",
"return",
"self",
".",
"get_catalog_info",
"(",
"key",
",",
"default",
")"
]
| Deprecated. Use `get_catalog_info` instead.
Get information from the catalog config file.
If *key* is `None`, return the full dict. | [
"Deprecated",
".",
"Use",
"get_catalog_info",
"instead",
"."
]
| bc6267ac41b9f68106ed6065184469ac13fdc0b6 | https://github.com/yymao/generic-catalog-reader/blob/bc6267ac41b9f68106ed6065184469ac13fdc0b6/GCR/base.py#L162-L170 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.