repository_name stringlengths 5 67 | func_path_in_repository stringlengths 4 234 | func_name stringlengths 0 314 | whole_func_string stringlengths 52 3.87M | language stringclasses 6
values | func_code_string stringlengths 52 3.87M | func_code_tokens listlengths 15 672k | func_documentation_string stringlengths 1 47.2k | func_documentation_tokens listlengths 1 3.92k | split_name stringclasses 1
value | func_code_url stringlengths 85 339 |
|---|---|---|---|---|---|---|---|---|---|---|
OTL/jps | jps/publisher.py | Publisher.publish | def publish(self, payload):
'''Publish payload to the topic
.. note:: If you publishes just after creating Publisher instance, it will causes
lost of message. You have to add sleep if you just want to publish once.
>>> pub = jps.Publisher('topic')
>>> time.sleep(0.1)
... | python | def publish(self, payload):
'''Publish payload to the topic
.. note:: If you publishes just after creating Publisher instance, it will causes
lost of message. You have to add sleep if you just want to publish once.
>>> pub = jps.Publisher('topic')
>>> time.sleep(0.1)
... | [
"def",
"publish",
"(",
"self",
",",
"payload",
")",
":",
"if",
"self",
".",
"_serializer",
"is",
"not",
"None",
":",
"payload",
"=",
"self",
".",
"_serializer",
"(",
"payload",
")",
"if",
"self",
".",
"_topic",
"==",
"'*'",
":",
"# special case for publi... | Publish payload to the topic
.. note:: If you publishes just after creating Publisher instance, it will causes
lost of message. You have to add sleep if you just want to publish once.
>>> pub = jps.Publisher('topic')
>>> time.sleep(0.1)
>>> pub.publish('{data}')
... | [
"Publish",
"payload",
"to",
"the",
"topic"
] | train | https://github.com/OTL/jps/blob/2c5a438d59611fffca6853072c822ef22665ed87/jps/publisher.py#L47-L66 |
ilblackdragon/django-misc | misc/parser.py | XlsReader.formatrow | def formatrow(self, types, values, wanttupledate):
""" Internal function used to clean up the incoming excel data """
## Data Type Codes:
## EMPTY 0
## TEXT 1 a Unicode string
## NUMBER 2 float
## DATE 3 float
## BOOLEAN 4 int; 1 means TRUE, 0 means FALSE
... | python | def formatrow(self, types, values, wanttupledate):
""" Internal function used to clean up the incoming excel data """
## Data Type Codes:
## EMPTY 0
## TEXT 1 a Unicode string
## NUMBER 2 float
## DATE 3 float
## BOOLEAN 4 int; 1 means TRUE, 0 means FALSE
... | [
"def",
"formatrow",
"(",
"self",
",",
"types",
",",
"values",
",",
"wanttupledate",
")",
":",
"## Data Type Codes:",
"## EMPTY 0",
"## TEXT 1 a Unicode string",
"## NUMBER 2 float",
"## DATE 3 float",
"## BOOLEAN 4 int; 1 means TRUE, 0 means FALSE",
"## ERROR 5",
"return... | Internal function used to clean up the incoming excel data | [
"Internal",
"function",
"used",
"to",
"clean",
"up",
"the",
"incoming",
"excel",
"data"
] | train | https://github.com/ilblackdragon/django-misc/blob/0accd2dc97de656a1c9e275be81e817f78a2eb9d/misc/parser.py#L21-L54 |
gasparka/pyhacores | under_construction/fsk_demodulator/model.py | FSKDemodulator.main | def main(self, input):
"""
:type input: Complex
:rtype: Sfix
"""
demod = self.demod.main(input)
match = self.match.main(demod)
return match | python | def main(self, input):
"""
:type input: Complex
:rtype: Sfix
"""
demod = self.demod.main(input)
match = self.match.main(demod)
return match | [
"def",
"main",
"(",
"self",
",",
"input",
")",
":",
"demod",
"=",
"self",
".",
"demod",
".",
"main",
"(",
"input",
")",
"match",
"=",
"self",
".",
"match",
".",
"main",
"(",
"demod",
")",
"return",
"match"
] | :type input: Complex
:rtype: Sfix | [
":",
"type",
"input",
":",
"Complex",
":",
"rtype",
":",
"Sfix"
] | train | https://github.com/gasparka/pyhacores/blob/16c186fbbf90385f2ba3498395123e79b6fcf340/under_construction/fsk_demodulator/model.py#L25-L33 |
whyscream/dspam-milter | dspam/milter.py | DspamMilter.connect | def connect(self, hostname, family, hostaddr):
"""
Log new connections.
"""
self.client_ip = hostaddr[0]
self.client_port = hostaddr[1]
self.time_start = time.time()
logger.debug('<{}> Connect from {}[{}]:{}'.format(
self.id, hostname, self.client_ip,... | python | def connect(self, hostname, family, hostaddr):
"""
Log new connections.
"""
self.client_ip = hostaddr[0]
self.client_port = hostaddr[1]
self.time_start = time.time()
logger.debug('<{}> Connect from {}[{}]:{}'.format(
self.id, hostname, self.client_ip,... | [
"def",
"connect",
"(",
"self",
",",
"hostname",
",",
"family",
",",
"hostaddr",
")",
":",
"self",
".",
"client_ip",
"=",
"hostaddr",
"[",
"0",
"]",
"self",
".",
"client_port",
"=",
"hostaddr",
"[",
"1",
"]",
"self",
".",
"time_start",
"=",
"time",
".... | Log new connections. | [
"Log",
"new",
"connections",
"."
] | train | https://github.com/whyscream/dspam-milter/blob/f9939b718eed02cb7e56f8c5b921db4cfe1cd85a/dspam/milter.py#L74-L84 |
whyscream/dspam-milter | dspam/milter.py | DspamMilter.envrcpt | def envrcpt(self, rcpt, *params):
"""
Send all recipients to DSPAM.
"""
if rcpt.startswith('<'):
rcpt = rcpt[1:]
if rcpt.endswith('>'):
rcpt = rcpt[:-1]
if self.recipient_delimiter_re:
rcpt = self.recipient_delimiter_re.sub('', rcpt)
... | python | def envrcpt(self, rcpt, *params):
"""
Send all recipients to DSPAM.
"""
if rcpt.startswith('<'):
rcpt = rcpt[1:]
if rcpt.endswith('>'):
rcpt = rcpt[:-1]
if self.recipient_delimiter_re:
rcpt = self.recipient_delimiter_re.sub('', rcpt)
... | [
"def",
"envrcpt",
"(",
"self",
",",
"rcpt",
",",
"*",
"params",
")",
":",
"if",
"rcpt",
".",
"startswith",
"(",
"'<'",
")",
":",
"rcpt",
"=",
"rcpt",
"[",
"1",
":",
"]",
"if",
"rcpt",
".",
"endswith",
"(",
"'>'",
")",
":",
"rcpt",
"=",
"rcpt",
... | Send all recipients to DSPAM. | [
"Send",
"all",
"recipients",
"to",
"DSPAM",
"."
] | train | https://github.com/whyscream/dspam-milter/blob/f9939b718eed02cb7e56f8c5b921db4cfe1cd85a/dspam/milter.py#L86-L100 |
whyscream/dspam-milter | dspam/milter.py | DspamMilter.header | def header(self, name, value):
"""
Store all message headers, optionally clean them up.
This simply stores all message headers so we can send them to DSPAM.
Additionally, headers that have the same prefix as the ones we're
about to add are deleted.
"""
self.mess... | python | def header(self, name, value):
"""
Store all message headers, optionally clean them up.
This simply stores all message headers so we can send them to DSPAM.
Additionally, headers that have the same prefix as the ones we're
about to add are deleted.
"""
self.mess... | [
"def",
"header",
"(",
"self",
",",
"name",
",",
"value",
")",
":",
"self",
".",
"message",
"+=",
"\"{}: {}\\r\\n\"",
".",
"format",
"(",
"name",
",",
"value",
")",
"logger",
".",
"debug",
"(",
"'<{}> Received {} header'",
".",
"format",
"(",
"self",
".",... | Store all message headers, optionally clean them up.
This simply stores all message headers so we can send them to DSPAM.
Additionally, headers that have the same prefix as the ones we're
about to add are deleted. | [
"Store",
"all",
"message",
"headers",
"optionally",
"clean",
"them",
"up",
"."
] | train | https://github.com/whyscream/dspam-milter/blob/f9939b718eed02cb7e56f8c5b921db4cfe1cd85a/dspam/milter.py#L103-L118 |
whyscream/dspam-milter | dspam/milter.py | DspamMilter.body | def body(self, block):
"""
Store message body.
"""
self.message += block
logger.debug('<{}> Received {} bytes of message body'.format(
self.id, len(block)))
return Milter.CONTINUE | python | def body(self, block):
"""
Store message body.
"""
self.message += block
logger.debug('<{}> Received {} bytes of message body'.format(
self.id, len(block)))
return Milter.CONTINUE | [
"def",
"body",
"(",
"self",
",",
"block",
")",
":",
"self",
".",
"message",
"+=",
"block",
"logger",
".",
"debug",
"(",
"'<{}> Received {} bytes of message body'",
".",
"format",
"(",
"self",
".",
"id",
",",
"len",
"(",
"block",
")",
")",
")",
"return",
... | Store message body. | [
"Store",
"message",
"body",
"."
] | train | https://github.com/whyscream/dspam-milter/blob/f9939b718eed02cb7e56f8c5b921db4cfe1cd85a/dspam/milter.py#L130-L138 |
whyscream/dspam-milter | dspam/milter.py | DspamMilter.eom | def eom(self):
"""
Send the message to DSPAM for classification and a return a milter
response based on the results.
If <DspamMilter>.static_user is set, that single DSPAM user account
will be used for processing the message. If it is unset, all envelope
recipients will ... | python | def eom(self):
"""
Send the message to DSPAM for classification and a return a milter
response based on the results.
If <DspamMilter>.static_user is set, that single DSPAM user account
will be used for processing the message. If it is unset, all envelope
recipients will ... | [
"def",
"eom",
"(",
"self",
")",
":",
"for",
"header",
"in",
"self",
".",
"remove_headers",
":",
"self",
".",
"chgheader",
"(",
"header",
",",
"1",
",",
"''",
")",
"logger",
".",
"info",
"(",
"'<{}> Removing existing {} header'",
".",
"format",
"(",
"self... | Send the message to DSPAM for classification and a return a milter
response based on the results.
If <DspamMilter>.static_user is set, that single DSPAM user account
will be used for processing the message. If it is unset, all envelope
recipients will be passed to DSPAM, and the final d... | [
"Send",
"the",
"message",
"to",
"DSPAM",
"for",
"classification",
"and",
"a",
"return",
"a",
"milter",
"response",
"based",
"on",
"the",
"results",
"."
] | train | https://github.com/whyscream/dspam-milter/blob/f9939b718eed02cb7e56f8c5b921db4cfe1cd85a/dspam/milter.py#L140-L236 |
whyscream/dspam-milter | dspam/milter.py | DspamMilter.close | def close(self):
"""
Log disconnects.
"""
time_spent = time.time() - self.time_start
logger.debug(
'<{}> Disconnect from [{}]:{}, time spent {:.3f} seconds'.format(
self.id, self.client_ip, self.client_port, time_spent))
return Milter.CONTINUE | python | def close(self):
"""
Log disconnects.
"""
time_spent = time.time() - self.time_start
logger.debug(
'<{}> Disconnect from [{}]:{}, time spent {:.3f} seconds'.format(
self.id, self.client_ip, self.client_port, time_spent))
return Milter.CONTINUE | [
"def",
"close",
"(",
"self",
")",
":",
"time_spent",
"=",
"time",
".",
"time",
"(",
")",
"-",
"self",
".",
"time_start",
"logger",
".",
"debug",
"(",
"'<{}> Disconnect from [{}]:{}, time spent {:.3f} seconds'",
".",
"format",
"(",
"self",
".",
"id",
",",
"se... | Log disconnects. | [
"Log",
"disconnects",
"."
] | train | https://github.com/whyscream/dspam-milter/blob/f9939b718eed02cb7e56f8c5b921db4cfe1cd85a/dspam/milter.py#L238-L247 |
whyscream/dspam-milter | dspam/milter.py | DspamMilter.compute_verdict | def compute_verdict(self, results):
"""
Match results to the configured reject, quarantine and accept classes,
and return a verdict based on that.
The verdict classes are matched in the order: reject_classes,
quarantine_classes, accept_classes. This means that you can configure
... | python | def compute_verdict(self, results):
"""
Match results to the configured reject, quarantine and accept classes,
and return a verdict based on that.
The verdict classes are matched in the order: reject_classes,
quarantine_classes, accept_classes. This means that you can configure
... | [
"def",
"compute_verdict",
"(",
"self",
",",
"results",
")",
":",
"if",
"results",
"[",
"'class'",
"]",
"in",
"self",
".",
"reject_classes",
":",
"threshold",
"=",
"self",
".",
"reject_classes",
"[",
"results",
"[",
"'class'",
"]",
"]",
"if",
"float",
"("... | Match results to the configured reject, quarantine and accept classes,
and return a verdict based on that.
The verdict classes are matched in the order: reject_classes,
quarantine_classes, accept_classes. This means that you can configure
different verdicts for different confidence resu... | [
"Match",
"results",
"to",
"the",
"configured",
"reject",
"quarantine",
"and",
"accept",
"classes",
"and",
"return",
"a",
"verdict",
"based",
"on",
"that",
"."
] | train | https://github.com/whyscream/dspam-milter/blob/f9939b718eed02cb7e56f8c5b921db4cfe1cd85a/dspam/milter.py#L249-L298 |
whyscream/dspam-milter | dspam/milter.py | DspamMilter.add_dspam_headers | def add_dspam_headers(self, results):
"""
Format DSPAM headers with passed results, and add them to the message.
Args:
results -- A results dictionary from DspamClient.
"""
for header in self.headers:
hname = self.header_prefix + header
if header.... | python | def add_dspam_headers(self, results):
"""
Format DSPAM headers with passed results, and add them to the message.
Args:
results -- A results dictionary from DspamClient.
"""
for header in self.headers:
hname = self.header_prefix + header
if header.... | [
"def",
"add_dspam_headers",
"(",
"self",
",",
"results",
")",
":",
"for",
"header",
"in",
"self",
".",
"headers",
":",
"hname",
"=",
"self",
".",
"header_prefix",
"+",
"header",
"if",
"header",
".",
"lower",
"(",
")",
"in",
"results",
":",
"hvalue",
"=... | Format DSPAM headers with passed results, and add them to the message.
Args:
results -- A results dictionary from DspamClient. | [
"Format",
"DSPAM",
"headers",
"with",
"passed",
"results",
"and",
"add",
"them",
"to",
"the",
"message",
"."
] | train | https://github.com/whyscream/dspam-milter/blob/f9939b718eed02cb7e56f8c5b921db4cfe1cd85a/dspam/milter.py#L300-L324 |
whyscream/dspam-milter | dspam/milter.py | DspamMilterDaemon.configure | def configure(self, config_file):
"""
Parse configuration, and setup objects to use it.
"""
cfg = configparser.RawConfigParser()
try:
cfg.readfp(open(config_file))
except IOError as err:
logger.critical(
'Error while reading config... | python | def configure(self, config_file):
"""
Parse configuration, and setup objects to use it.
"""
cfg = configparser.RawConfigParser()
try:
cfg.readfp(open(config_file))
except IOError as err:
logger.critical(
'Error while reading config... | [
"def",
"configure",
"(",
"self",
",",
"config_file",
")",
":",
"cfg",
"=",
"configparser",
".",
"RawConfigParser",
"(",
")",
"try",
":",
"cfg",
".",
"readfp",
"(",
"open",
"(",
"config_file",
")",
")",
"except",
"IOError",
"as",
"err",
":",
"logger",
"... | Parse configuration, and setup objects to use it. | [
"Parse",
"configuration",
"and",
"setup",
"objects",
"to",
"use",
"it",
"."
] | train | https://github.com/whyscream/dspam-milter/blob/f9939b718eed02cb7e56f8c5b921db4cfe1cd85a/dspam/milter.py#L352-L429 |
brantai/python-rightscale | rightscale/commands.py | list_instances | def list_instances(
deployment_name='',
cloud_name='EC2 us-east-1',
view='tiny',
):
"""
Returns a list of instances from your account.
:param str deployment_name: If provided, only lists servers in the
specified deployment.
:param str cloud_name: The friendly na... | python | def list_instances(
deployment_name='',
cloud_name='EC2 us-east-1',
view='tiny',
):
"""
Returns a list of instances from your account.
:param str deployment_name: If provided, only lists servers in the
specified deployment.
:param str cloud_name: The friendly na... | [
"def",
"list_instances",
"(",
"deployment_name",
"=",
"''",
",",
"cloud_name",
"=",
"'EC2 us-east-1'",
",",
"view",
"=",
"'tiny'",
",",
")",
":",
"api",
"=",
"get_api",
"(",
")",
"cloud",
"=",
"find_by_name",
"(",
"api",
".",
"clouds",
",",
"cloud_name",
... | Returns a list of instances from your account.
:param str deployment_name: If provided, only lists servers in the
specified deployment.
:param str cloud_name: The friendly name for a RightScale-supported cloud.
E.g. ``EC2 us-east-1``, ``us-west-2``, etc...
:param str view: The level of de... | [
"Returns",
"a",
"list",
"of",
"instances",
"from",
"your",
"account",
"."
] | train | https://github.com/brantai/python-rightscale/blob/5fbf4089922917247be712d58645a7b1504f0944/rightscale/commands.py#L34-L60 |
brantai/python-rightscale | rightscale/commands.py | run_script_on_server | def run_script_on_server(
script_name,
server_name,
inputs=None,
timeout_s=10,
output=sys.stdout
):
"""
Runs a RightScript and polls for status.
Sample usage::
from rightscale import run_script_on_server
run_script_on_server(
... | python | def run_script_on_server(
script_name,
server_name,
inputs=None,
timeout_s=10,
output=sys.stdout
):
"""
Runs a RightScript and polls for status.
Sample usage::
from rightscale import run_script_on_server
run_script_on_server(
... | [
"def",
"run_script_on_server",
"(",
"script_name",
",",
"server_name",
",",
"inputs",
"=",
"None",
",",
"timeout_s",
"=",
"10",
",",
"output",
"=",
"sys",
".",
"stdout",
")",
":",
"api",
"=",
"get_api",
"(",
")",
"script",
"=",
"find_by_name",
"(",
"api"... | Runs a RightScript and polls for status.
Sample usage::
from rightscale import run_script_on_server
run_script_on_server(
'my cool bob lol script',
'some server',
inputs={'BOB': 'blah blah', 'LOL': 'fubar'},
)
Sample output::
... | [
"Runs",
"a",
"RightScript",
"and",
"polls",
"for",
"status",
"."
] | train | https://github.com/brantai/python-rightscale/blob/5fbf4089922917247be712d58645a7b1504f0944/rightscale/commands.py#L63-L113 |
brantai/python-rightscale | rightscale/commands.py | get_by_path | def get_by_path(path, first=False):
"""
Search for resources using colon-separated path notation.
E.g.::
path = 'deployments:production:servers:haproxy'
haproxies = get_by_path(path)
:param bool first: Always use the first returned match for all intermediate
searches along the... | python | def get_by_path(path, first=False):
"""
Search for resources using colon-separated path notation.
E.g.::
path = 'deployments:production:servers:haproxy'
haproxies = get_by_path(path)
:param bool first: Always use the first returned match for all intermediate
searches along the... | [
"def",
"get_by_path",
"(",
"path",
",",
"first",
"=",
"False",
")",
":",
"api",
"=",
"get_api",
"(",
")",
"cur_res",
"=",
"api",
"parts",
"=",
"path",
".",
"split",
"(",
"':'",
")",
"for",
"part",
"in",
"parts",
":",
"res",
"=",
"getattr",
"(",
"... | Search for resources using colon-separated path notation.
E.g.::
path = 'deployments:production:servers:haproxy'
haproxies = get_by_path(path)
:param bool first: Always use the first returned match for all intermediate
searches along the path. If this is ``False`` and an intermediate... | [
"Search",
"for",
"resources",
"using",
"colon",
"-",
"separated",
"path",
"notation",
"."
] | train | https://github.com/brantai/python-rightscale/blob/5fbf4089922917247be712d58645a7b1504f0944/rightscale/commands.py#L116-L144 |
CalebBell/fpi | fpi/saltation.py | Rizk | def Rizk(mp, dp, rhog, D):
r'''Calculates saltation velocity of the gas for pneumatic conveying,
according to [1]_ as described in [2]_ and many others.
.. math::
\mu=\left(\frac{1}{10^{1440d_p+1.96}}\right)\left(Fr_s\right)^{1100d_p+2.5}
Fr_s = \frac{V_{salt}}{\sqrt{gD}}
\mu = \f... | python | def Rizk(mp, dp, rhog, D):
r'''Calculates saltation velocity of the gas for pneumatic conveying,
according to [1]_ as described in [2]_ and many others.
.. math::
\mu=\left(\frac{1}{10^{1440d_p+1.96}}\right)\left(Fr_s\right)^{1100d_p+2.5}
Fr_s = \frac{V_{salt}}{\sqrt{gD}}
\mu = \f... | [
"def",
"Rizk",
"(",
"mp",
",",
"dp",
",",
"rhog",
",",
"D",
")",
":",
"alpha",
"=",
"1440",
"*",
"dp",
"+",
"1.96",
"beta",
"=",
"1100",
"*",
"dp",
"+",
"2.5",
"term1",
"=",
"1.",
"/",
"10",
"**",
"alpha",
"Frs_sorta",
"=",
"1",
"/",
"(",
"... | r'''Calculates saltation velocity of the gas for pneumatic conveying,
according to [1]_ as described in [2]_ and many others.
.. math::
\mu=\left(\frac{1}{10^{1440d_p+1.96}}\right)\left(Fr_s\right)^{1100d_p+2.5}
Fr_s = \frac{V_{salt}}{\sqrt{gD}}
\mu = \frac{m_p}{\frac{\pi}{4}D^2V \rho... | [
"r",
"Calculates",
"saltation",
"velocity",
"of",
"the",
"gas",
"for",
"pneumatic",
"conveying",
"according",
"to",
"[",
"1",
"]",
"_",
"as",
"described",
"in",
"[",
"2",
"]",
"_",
"and",
"many",
"others",
"."
] | train | https://github.com/CalebBell/fpi/blob/6e6da3b9d0c17e10cc0886c97bc1bb8aeba2cca5/fpi/saltation.py#L26-L82 |
CalebBell/fpi | fpi/saltation.py | Matsumoto_1977 | def Matsumoto_1977(mp, rhop, dp, rhog, D, Vterminal=1):
r'''Calculates saltation velocity of the gas for pneumatic conveying,
according to [1]_ and reproduced in [2]_, [3]_, and [4]_.
First equation is used if third equation yeilds d* higher than dp.
Otherwise, use equation 2.
.. math::
\m... | python | def Matsumoto_1977(mp, rhop, dp, rhog, D, Vterminal=1):
r'''Calculates saltation velocity of the gas for pneumatic conveying,
according to [1]_ and reproduced in [2]_, [3]_, and [4]_.
First equation is used if third equation yeilds d* higher than dp.
Otherwise, use equation 2.
.. math::
\m... | [
"def",
"Matsumoto_1977",
"(",
"mp",
",",
"rhop",
",",
"dp",
",",
"rhog",
",",
"D",
",",
"Vterminal",
"=",
"1",
")",
":",
"limit",
"=",
"1.39",
"*",
"D",
"*",
"(",
"rhop",
"/",
"rhog",
")",
"**",
"-",
"0.74",
"A",
"=",
"pi",
"/",
"4",
"*",
"... | r'''Calculates saltation velocity of the gas for pneumatic conveying,
according to [1]_ and reproduced in [2]_, [3]_, and [4]_.
First equation is used if third equation yeilds d* higher than dp.
Otherwise, use equation 2.
.. math::
\mu = 5560\left(\frac{d_p}{D}\right)^{1.43}\left(\frac{Fr_s}{1... | [
"r",
"Calculates",
"saltation",
"velocity",
"of",
"the",
"gas",
"for",
"pneumatic",
"conveying",
"according",
"to",
"[",
"1",
"]",
"_",
"and",
"reproduced",
"in",
"[",
"2",
"]",
"_",
"[",
"3",
"]",
"_",
"and",
"[",
"4",
"]",
"_",
"."
] | train | https://github.com/CalebBell/fpi/blob/6e6da3b9d0c17e10cc0886c97bc1bb8aeba2cca5/fpi/saltation.py#L217-L304 |
CalebBell/fpi | fpi/saltation.py | Weber | def Weber(mp, rhop, dp, rhog, D, Vterminal=4):
r'''Calculates saltation velocity of the gas for pneumatic conveying,
according to [1]_ as described in [2]_, [3]_, [4]_, and [5]_.
If Vterminal is under 3 m/s, use equation 1; otherwise, equation 2.
.. math::
Fr_s = \left(7 + \frac{8}{3}V_{termin... | python | def Weber(mp, rhop, dp, rhog, D, Vterminal=4):
r'''Calculates saltation velocity of the gas for pneumatic conveying,
according to [1]_ as described in [2]_, [3]_, [4]_, and [5]_.
If Vterminal is under 3 m/s, use equation 1; otherwise, equation 2.
.. math::
Fr_s = \left(7 + \frac{8}{3}V_{termin... | [
"def",
"Weber",
"(",
"mp",
",",
"rhop",
",",
"dp",
",",
"rhog",
",",
"D",
",",
"Vterminal",
"=",
"4",
")",
":",
"if",
"Vterminal",
"<=",
"3",
":",
"term1",
"=",
"(",
"7",
"+",
"8",
"/",
"3.",
"*",
"Vterminal",
")",
"*",
"(",
"dp",
"/",
"D",... | r'''Calculates saltation velocity of the gas for pneumatic conveying,
according to [1]_ as described in [2]_, [3]_, [4]_, and [5]_.
If Vterminal is under 3 m/s, use equation 1; otherwise, equation 2.
.. math::
Fr_s = \left(7 + \frac{8}{3}V_{terminal}\right)\mu^{0.25}
\left(\frac{d_p}{D}\ri... | [
"r",
"Calculates",
"saltation",
"velocity",
"of",
"the",
"gas",
"for",
"pneumatic",
"conveying",
"according",
"to",
"[",
"1",
"]",
"_",
"as",
"described",
"in",
"[",
"2",
"]",
"_",
"[",
"3",
"]",
"_",
"[",
"4",
"]",
"_",
"and",
"[",
"5",
"]",
"_"... | train | https://github.com/CalebBell/fpi/blob/6e6da3b9d0c17e10cc0886c97bc1bb8aeba2cca5/fpi/saltation.py#L376-L452 |
CalebBell/fpi | fpi/saltation.py | Geldart_Ling | def Geldart_Ling(mp, rhog, D, mug):
r'''Calculates saltation velocity of the gas for pneumatic conveying,
according to [1]_ as described in [2]_ and [3]_.
if Gs/D < 47000, use equation 1, otherwise use equation 2.
.. math::
V_{salt} = 1.5G_s^{0.465}D^{-0.01} \mu^{0.055}\rho_f^{-0.42}
... | python | def Geldart_Ling(mp, rhog, D, mug):
r'''Calculates saltation velocity of the gas for pneumatic conveying,
according to [1]_ as described in [2]_ and [3]_.
if Gs/D < 47000, use equation 1, otherwise use equation 2.
.. math::
V_{salt} = 1.5G_s^{0.465}D^{-0.01} \mu^{0.055}\rho_f^{-0.42}
... | [
"def",
"Geldart_Ling",
"(",
"mp",
",",
"rhog",
",",
"D",
",",
"mug",
")",
":",
"Gs",
"=",
"mp",
"/",
"(",
"pi",
"/",
"4",
"*",
"D",
"**",
"2",
")",
"if",
"Gs",
"/",
"D",
"<=",
"47000",
":",
"V",
"=",
"1.5",
"*",
"Gs",
"**",
"0.465",
"*",
... | r'''Calculates saltation velocity of the gas for pneumatic conveying,
according to [1]_ as described in [2]_ and [3]_.
if Gs/D < 47000, use equation 1, otherwise use equation 2.
.. math::
V_{salt} = 1.5G_s^{0.465}D^{-0.01} \mu^{0.055}\rho_f^{-0.42}
V_{salt} = 8.7G_s^{0.302}D^{0.153} \mu^{... | [
"r",
"Calculates",
"saltation",
"velocity",
"of",
"the",
"gas",
"for",
"pneumatic",
"conveying",
"according",
"to",
"[",
"1",
"]",
"_",
"as",
"described",
"in",
"[",
"2",
"]",
"_",
"and",
"[",
"3",
"]",
"_",
"."
] | train | https://github.com/CalebBell/fpi/blob/6e6da3b9d0c17e10cc0886c97bc1bb8aeba2cca5/fpi/saltation.py#L455-L518 |
williamjameshandley/fgivenx | fgivenx/plot.py | plot | def plot(x, y, z, ax=None, **kwargs):
r"""
Plot iso-probability mass function, converted to sigmas.
Parameters
----------
x, y, z : numpy arrays
Same as arguments to :func:`matplotlib.pyplot.contour`
ax: axes object, optional
:class:`matplotlib.axes._subplots.AxesSubplot` to pl... | python | def plot(x, y, z, ax=None, **kwargs):
r"""
Plot iso-probability mass function, converted to sigmas.
Parameters
----------
x, y, z : numpy arrays
Same as arguments to :func:`matplotlib.pyplot.contour`
ax: axes object, optional
:class:`matplotlib.axes._subplots.AxesSubplot` to pl... | [
"def",
"plot",
"(",
"x",
",",
"y",
",",
"z",
",",
"ax",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"ax",
"is",
"None",
":",
"ax",
"=",
"matplotlib",
".",
"pyplot",
".",
"gca",
"(",
")",
"# Get inputs",
"colors",
"=",
"kwargs",
".",
... | r"""
Plot iso-probability mass function, converted to sigmas.
Parameters
----------
x, y, z : numpy arrays
Same as arguments to :func:`matplotlib.pyplot.contour`
ax: axes object, optional
:class:`matplotlib.axes._subplots.AxesSubplot` to plot the contours
onto. If unsupplie... | [
"r",
"Plot",
"iso",
"-",
"probability",
"mass",
"function",
"converted",
"to",
"sigmas",
"."
] | train | https://github.com/williamjameshandley/fgivenx/blob/a16790652a3cef3cfacd4b97da62786cb66fec13/fgivenx/plot.py#L7-L106 |
williamjameshandley/fgivenx | fgivenx/plot.py | plot_lines | def plot_lines(x, fsamps, ax=None, downsample=100, **kwargs):
"""
Plot function samples as a set of line plots.
Parameters
----------
x: 1D array-like
x values to plot
fsamps: 2D array-like
set of functions to plot at each x. As returned by
:func:`fgivenx.compute_sample... | python | def plot_lines(x, fsamps, ax=None, downsample=100, **kwargs):
"""
Plot function samples as a set of line plots.
Parameters
----------
x: 1D array-like
x values to plot
fsamps: 2D array-like
set of functions to plot at each x. As returned by
:func:`fgivenx.compute_sample... | [
"def",
"plot_lines",
"(",
"x",
",",
"fsamps",
",",
"ax",
"=",
"None",
",",
"downsample",
"=",
"100",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"ax",
"is",
"None",
":",
"ax",
"=",
"matplotlib",
".",
"pyplot",
".",
"gca",
"(",
")",
"if",
"downsample... | Plot function samples as a set of line plots.
Parameters
----------
x: 1D array-like
x values to plot
fsamps: 2D array-like
set of functions to plot at each x. As returned by
:func:`fgivenx.compute_samples`
ax: axes object
:class:`matplotlib.pyplot.ax` to plot on.
... | [
"Plot",
"function",
"samples",
"as",
"a",
"set",
"of",
"line",
"plots",
"."
] | train | https://github.com/williamjameshandley/fgivenx/blob/a16790652a3cef3cfacd4b97da62786cb66fec13/fgivenx/plot.py#L109-L139 |
cag/sphinxcontrib-soliditydomain | sphinxcontrib/soliditydomain/documenters.py | SolidityObjectDocumenter.add_content | def add_content(self, more_content):
"""Add content from source docs and user."""
sourcename = self.get_sourcename()
if self.object.docs:
self.add_line('', sourcename)
for line in self.object.docs.splitlines():
self.add_line(line, sourcename)
# a... | python | def add_content(self, more_content):
"""Add content from source docs and user."""
sourcename = self.get_sourcename()
if self.object.docs:
self.add_line('', sourcename)
for line in self.object.docs.splitlines():
self.add_line(line, sourcename)
# a... | [
"def",
"add_content",
"(",
"self",
",",
"more_content",
")",
":",
"sourcename",
"=",
"self",
".",
"get_sourcename",
"(",
")",
"if",
"self",
".",
"object",
".",
"docs",
":",
"self",
".",
"add_line",
"(",
"''",
",",
"sourcename",
")",
"for",
"line",
"in"... | Add content from source docs and user. | [
"Add",
"content",
"from",
"source",
"docs",
"and",
"user",
"."
] | train | https://github.com/cag/sphinxcontrib-soliditydomain/blob/b004b6e43727771027b4065fab18fcb9ccb2c826/sphinxcontrib/soliditydomain/documenters.py#L50-L63 |
cag/sphinxcontrib-soliditydomain | sphinxcontrib/soliditydomain/documenters.py | SolidityObjectDocumenter.document_members | def document_members(self, all_members=False):
# type: (bool) -> None
"""Generate reST for member documentation.
If *all_members* is True, do all members, else those given by
*self.options.members*.
"""
sourcename = self.get_sourcename()
want_all = all_members o... | python | def document_members(self, all_members=False):
# type: (bool) -> None
"""Generate reST for member documentation.
If *all_members* is True, do all members, else those given by
*self.options.members*.
"""
sourcename = self.get_sourcename()
want_all = all_members o... | [
"def",
"document_members",
"(",
"self",
",",
"all_members",
"=",
"False",
")",
":",
"# type: (bool) -> None",
"sourcename",
"=",
"self",
".",
"get_sourcename",
"(",
")",
"want_all",
"=",
"all_members",
"or",
"self",
".",
"options",
".",
"members",
"is",
"ALL",... | Generate reST for member documentation.
If *all_members* is True, do all members, else those given by
*self.options.members*. | [
"Generate",
"reST",
"for",
"member",
"documentation",
"."
] | train | https://github.com/cag/sphinxcontrib-soliditydomain/blob/b004b6e43727771027b4065fab18fcb9ccb2c826/sphinxcontrib/soliditydomain/documenters.py#L65-L139 |
cag/sphinxcontrib-soliditydomain | sphinxcontrib/soliditydomain/documenters.py | SolidityObjectDocumenter.generate | def generate(self, more_content=None, all_members=False):
# type: (Any, str, bool, bool) -> None
"""Generate reST for the object given by *self.name*, and possibly for
its members.
If *more_content* is given, include that content.
If *all_members* is True, document all members.
... | python | def generate(self, more_content=None, all_members=False):
# type: (Any, str, bool, bool) -> None
"""Generate reST for the object given by *self.name*, and possibly for
its members.
If *more_content* is given, include that content.
If *all_members* is True, document all members.
... | [
"def",
"generate",
"(",
"self",
",",
"more_content",
"=",
"None",
",",
"all_members",
"=",
"False",
")",
":",
"# type: (Any, str, bool, bool) -> None",
"directive",
"=",
"getattr",
"(",
"self",
",",
"'directivetype'",
",",
"self",
".",
"objtype",
")",
"# parse c... | Generate reST for the object given by *self.name*, and possibly for
its members.
If *more_content* is given, include that content.
If *all_members* is True, document all members. | [
"Generate",
"reST",
"for",
"the",
"object",
"given",
"by",
"*",
"self",
".",
"name",
"*",
"and",
"possibly",
"for",
"its",
"members",
"."
] | train | https://github.com/cag/sphinxcontrib-soliditydomain/blob/b004b6e43727771027b4065fab18fcb9ccb2c826/sphinxcontrib/soliditydomain/documenters.py#L141-L220 |
simoninireland/epyc | epyc/lab.py | Lab.addParameter | def addParameter( self, k, r ):
"""Add a parameter to the experiment's parameter space. k is the
parameter name, and r is its range.
:param k: parameter name
:param r: parameter range"""
if isinstance(r, six.string_types) or not isinstance(r, collections.Iterable):
... | python | def addParameter( self, k, r ):
"""Add a parameter to the experiment's parameter space. k is the
parameter name, and r is its range.
:param k: parameter name
:param r: parameter range"""
if isinstance(r, six.string_types) or not isinstance(r, collections.Iterable):
... | [
"def",
"addParameter",
"(",
"self",
",",
"k",
",",
"r",
")",
":",
"if",
"isinstance",
"(",
"r",
",",
"six",
".",
"string_types",
")",
"or",
"not",
"isinstance",
"(",
"r",
",",
"collections",
".",
"Iterable",
")",
":",
"# range is a single value (where a st... | Add a parameter to the experiment's parameter space. k is the
parameter name, and r is its range.
:param k: parameter name
:param r: parameter range | [
"Add",
"a",
"parameter",
"to",
"the",
"experiment",
"s",
"parameter",
"space",
".",
"k",
"is",
"the",
"parameter",
"name",
"and",
"r",
"is",
"its",
"range",
"."
] | train | https://github.com/simoninireland/epyc/blob/b3b61007741a0ab3de64df89070a6f30de8ec268/epyc/lab.py#L56-L71 |
simoninireland/epyc | epyc/lab.py | Lab._crossProduct | def _crossProduct( self, ls ):
"""Internal method to generate the cross product of all parameter
values, creating the parameter space for the experiment.
:param ls: an array of parameter names
:returns: list of dicts"""
p = ls[0]
ds = []
if len(ls) == 1:
... | python | def _crossProduct( self, ls ):
"""Internal method to generate the cross product of all parameter
values, creating the parameter space for the experiment.
:param ls: an array of parameter names
:returns: list of dicts"""
p = ls[0]
ds = []
if len(ls) == 1:
... | [
"def",
"_crossProduct",
"(",
"self",
",",
"ls",
")",
":",
"p",
"=",
"ls",
"[",
"0",
"]",
"ds",
"=",
"[",
"]",
"if",
"len",
"(",
"ls",
")",
"==",
"1",
":",
"# last parameter, convert range to a dict",
"for",
"i",
"in",
"self",
".",
"_parameters",
"[",... | Internal method to generate the cross product of all parameter
values, creating the parameter space for the experiment.
:param ls: an array of parameter names
:returns: list of dicts | [
"Internal",
"method",
"to",
"generate",
"the",
"cross",
"product",
"of",
"all",
"parameter",
"values",
"creating",
"the",
"parameter",
"space",
"for",
"the",
"experiment",
"."
] | train | https://github.com/simoninireland/epyc/blob/b3b61007741a0ab3de64df89070a6f30de8ec268/epyc/lab.py#L103-L128 |
simoninireland/epyc | epyc/lab.py | Lab.parameterSpace | def parameterSpace( self ):
"""Return the parameter space of the experiment as a list of dicts,
with each dict mapping each parameter name to a value.
:returns: the parameter space as a list of dicts"""
ps = self.parameters()
if len(ps) == 0:
return []
else:
... | python | def parameterSpace( self ):
"""Return the parameter space of the experiment as a list of dicts,
with each dict mapping each parameter name to a value.
:returns: the parameter space as a list of dicts"""
ps = self.parameters()
if len(ps) == 0:
return []
else:
... | [
"def",
"parameterSpace",
"(",
"self",
")",
":",
"ps",
"=",
"self",
".",
"parameters",
"(",
")",
"if",
"len",
"(",
"ps",
")",
"==",
"0",
":",
"return",
"[",
"]",
"else",
":",
"return",
"self",
".",
"_crossProduct",
"(",
"ps",
")"
] | Return the parameter space of the experiment as a list of dicts,
with each dict mapping each parameter name to a value.
:returns: the parameter space as a list of dicts | [
"Return",
"the",
"parameter",
"space",
"of",
"the",
"experiment",
"as",
"a",
"list",
"of",
"dicts",
"with",
"each",
"dict",
"mapping",
"each",
"parameter",
"name",
"to",
"a",
"value",
"."
] | train | https://github.com/simoninireland/epyc/blob/b3b61007741a0ab3de64df89070a6f30de8ec268/epyc/lab.py#L130-L139 |
simoninireland/epyc | epyc/lab.py | Lab.runExperiment | def runExperiment( self, e ):
"""Run an experiment over all the points in the parameter space.
The results will be stored in the notebook.
:param e: the experiment"""
# create the parameter space
ps = self.parameterSpace()
# run the experiment at each point
nb ... | python | def runExperiment( self, e ):
"""Run an experiment over all the points in the parameter space.
The results will be stored in the notebook.
:param e: the experiment"""
# create the parameter space
ps = self.parameterSpace()
# run the experiment at each point
nb ... | [
"def",
"runExperiment",
"(",
"self",
",",
"e",
")",
":",
"# create the parameter space",
"ps",
"=",
"self",
".",
"parameterSpace",
"(",
")",
"# run the experiment at each point",
"nb",
"=",
"self",
".",
"notebook",
"(",
")",
"for",
"p",
"in",
"ps",
":",
"#pr... | Run an experiment over all the points in the parameter space.
The results will be stored in the notebook.
:param e: the experiment | [
"Run",
"an",
"experiment",
"over",
"all",
"the",
"points",
"in",
"the",
"parameter",
"space",
".",
"The",
"results",
"will",
"be",
"stored",
"in",
"the",
"notebook",
"."
] | train | https://github.com/simoninireland/epyc/blob/b3b61007741a0ab3de64df89070a6f30de8ec268/epyc/lab.py#L141-L158 |
radujica/baloo | baloo/core/indexes/range.py | RangeIndex.evaluate | def evaluate(self, verbose=False, decode=True, passes=None, num_threads=1, apply_experimental=True):
"""Evaluates by creating an Index containing evaluated data.
See `LazyResult`
Returns
-------
Index
Index with evaluated data.
"""
if self.start == ... | python | def evaluate(self, verbose=False, decode=True, passes=None, num_threads=1, apply_experimental=True):
"""Evaluates by creating an Index containing evaluated data.
See `LazyResult`
Returns
-------
Index
Index with evaluated data.
"""
if self.start == ... | [
"def",
"evaluate",
"(",
"self",
",",
"verbose",
"=",
"False",
",",
"decode",
"=",
"True",
",",
"passes",
"=",
"None",
",",
"num_threads",
"=",
"1",
",",
"apply_experimental",
"=",
"True",
")",
":",
"if",
"self",
".",
"start",
"==",
"0",
"and",
"self"... | Evaluates by creating an Index containing evaluated data.
See `LazyResult`
Returns
-------
Index
Index with evaluated data. | [
"Evaluates",
"by",
"creating",
"an",
"Index",
"containing",
"evaluated",
"data",
"."
] | train | https://github.com/radujica/baloo/blob/f6e05e35b73a75e8a300754c6bdc575e5f2d53b9/baloo/core/indexes/range.py#L81-L97 |
Kromey/django-simplecaptcha | simplecaptcha/settings.py | _getsetting | def _getsetting(setting, default):
"""Get `setting` if set, fallback to `default` if not
This method tries to return the value of the specified setting from Django's
settings module, after prefixing the name with _DJANGO_SETTING_PREFIX. If
this fails for any reason, the value supplied in `default` will... | python | def _getsetting(setting, default):
"""Get `setting` if set, fallback to `default` if not
This method tries to return the value of the specified setting from Django's
settings module, after prefixing the name with _DJANGO_SETTING_PREFIX. If
this fails for any reason, the value supplied in `default` will... | [
"def",
"_getsetting",
"(",
"setting",
",",
"default",
")",
":",
"setting",
"=",
"_DJANGO_SETTING_PREFIX",
"+",
"setting",
"try",
":",
"return",
"getattr",
"(",
"settings",
",",
"setting",
")",
"except",
":",
"return",
"default"
] | Get `setting` if set, fallback to `default` if not
This method tries to return the value of the specified setting from Django's
settings module, after prefixing the name with _DJANGO_SETTING_PREFIX. If
this fails for any reason, the value supplied in `default` will be returned
instead. | [
"Get",
"setting",
"if",
"set",
"fallback",
"to",
"default",
"if",
"not"
] | train | https://github.com/Kromey/django-simplecaptcha/blob/16dd401e3317daf78143e9250f98b48c22cabd2d/simplecaptcha/settings.py#L13-L27 |
Kromey/django-simplecaptcha | simplecaptcha/settings.py | _setsetting | def _setsetting(setting, default):
"""Dynamically sets the variable named in `setting`
This method uses `_getsetting()` to either fetch the setting from Django's
settings module, or else fallback to the default value; it then sets a
variable in this module with the returned value.
"""
value = _... | python | def _setsetting(setting, default):
"""Dynamically sets the variable named in `setting`
This method uses `_getsetting()` to either fetch the setting from Django's
settings module, or else fallback to the default value; it then sets a
variable in this module with the returned value.
"""
value = _... | [
"def",
"_setsetting",
"(",
"setting",
",",
"default",
")",
":",
"value",
"=",
"_getsetting",
"(",
"setting",
",",
"default",
")",
"setattr",
"(",
"_self",
",",
"setting",
",",
"value",
")"
] | Dynamically sets the variable named in `setting`
This method uses `_getsetting()` to either fetch the setting from Django's
settings module, or else fallback to the default value; it then sets a
variable in this module with the returned value. | [
"Dynamically",
"sets",
"the",
"variable",
"named",
"in",
"setting"
] | train | https://github.com/Kromey/django-simplecaptcha/blob/16dd401e3317daf78143e9250f98b48c22cabd2d/simplecaptcha/settings.py#L29-L37 |
lemieuxl/pyGenClean | pyGenClean/SampleMissingness/sample_missingness.py | runPlink | def runPlink(options):
"""Run Plink with the ``mind`` option.
:param options: the options.
:type options: argparse.Namespace
"""
# The plink command
plinkCommand = [
"plink",
"--noweb",
"--bfile" if options.is_bfile else "--tfile",
options.ifile,
"--min... | python | def runPlink(options):
"""Run Plink with the ``mind`` option.
:param options: the options.
:type options: argparse.Namespace
"""
# The plink command
plinkCommand = [
"plink",
"--noweb",
"--bfile" if options.is_bfile else "--tfile",
options.ifile,
"--min... | [
"def",
"runPlink",
"(",
"options",
")",
":",
"# The plink command",
"plinkCommand",
"=",
"[",
"\"plink\"",
",",
"\"--noweb\"",
",",
"\"--bfile\"",
"if",
"options",
".",
"is_bfile",
"else",
"\"--tfile\"",
",",
"options",
".",
"ifile",
",",
"\"--mind\"",
",",
"s... | Run Plink with the ``mind`` option.
:param options: the options.
:type options: argparse.Namespace | [
"Run",
"Plink",
"with",
"the",
"mind",
"option",
"."
] | train | https://github.com/lemieuxl/pyGenClean/blob/6173a48ccc0cf3a3bd711b1f2a1fa16248b8bf55/pyGenClean/SampleMissingness/sample_missingness.py#L56-L83 |
lemieuxl/pyGenClean | pyGenClean/SampleMissingness/sample_missingness.py | checkArgs | def checkArgs(args):
"""Checks the arguments and options.
:param args: a object containing the options of the program.
:type args: argparse.Namespace
:returns: ``True`` if everything was OK.
If there is a problem with an option, an exception is raised using the
:py:class:`ProgramError` class... | python | def checkArgs(args):
"""Checks the arguments and options.
:param args: a object containing the options of the program.
:type args: argparse.Namespace
:returns: ``True`` if everything was OK.
If there is a problem with an option, an exception is raised using the
:py:class:`ProgramError` class... | [
"def",
"checkArgs",
"(",
"args",
")",
":",
"# Check if we have the tped and the tfam files",
"required_file_extensions",
"=",
"{",
"\".tfam\"",
",",
"\".tped\"",
"}",
"if",
"args",
".",
"is_bfile",
":",
"required_file_extensions",
"=",
"{",
"\".bed\"",
",",
"\".bim\""... | Checks the arguments and options.
:param args: a object containing the options of the program.
:type args: argparse.Namespace
:returns: ``True`` if everything was OK.
If there is a problem with an option, an exception is raised using the
:py:class:`ProgramError` class, a message is printed to th... | [
"Checks",
"the",
"arguments",
"and",
"options",
"."
] | train | https://github.com/lemieuxl/pyGenClean/blob/6173a48ccc0cf3a3bd711b1f2a1fa16248b8bf55/pyGenClean/SampleMissingness/sample_missingness.py#L86-L114 |
jor-/util | util/cache/memory.py | hash_key | def hash_key(*args, **kwargs):
"""Return a cache key for the specified hashable arguments."""
if kwargs:
return cachetools.keys._HashedTuple(args + _kwargs_mark + tuple(itertools.chain(sorted(kwargs.items()))))
else:
return cachetools.keys._HashedTuple(args) | python | def hash_key(*args, **kwargs):
"""Return a cache key for the specified hashable arguments."""
if kwargs:
return cachetools.keys._HashedTuple(args + _kwargs_mark + tuple(itertools.chain(sorted(kwargs.items()))))
else:
return cachetools.keys._HashedTuple(args) | [
"def",
"hash_key",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"kwargs",
":",
"return",
"cachetools",
".",
"keys",
".",
"_HashedTuple",
"(",
"args",
"+",
"_kwargs_mark",
"+",
"tuple",
"(",
"itertools",
".",
"chain",
"(",
"sorted",
"(",
... | Return a cache key for the specified hashable arguments. | [
"Return",
"a",
"cache",
"key",
"for",
"the",
"specified",
"hashable",
"arguments",
"."
] | train | https://github.com/jor-/util/blob/0eb0be84430f88885f4d48335596ca8881f85587/util/cache/memory.py#L13-L19 |
jor-/util | util/cache/memory.py | typed_hash_key | def typed_hash_key(*args, **kwargs):
"""Return a typed cache key for the specified hashable arguments."""
key = hash_key(*args, **kwargs)
key += tuple(type(v) for v in args)
key += tuple(type(v) for _, v in sorted(kwargs.items()))
return key | python | def typed_hash_key(*args, **kwargs):
"""Return a typed cache key for the specified hashable arguments."""
key = hash_key(*args, **kwargs)
key += tuple(type(v) for v in args)
key += tuple(type(v) for _, v in sorted(kwargs.items()))
return key | [
"def",
"typed_hash_key",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"key",
"=",
"hash_key",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"key",
"+=",
"tuple",
"(",
"type",
"(",
"v",
")",
"for",
"v",
"in",
"args",
")",
"key",
"+=",
... | Return a typed cache key for the specified hashable arguments. | [
"Return",
"a",
"typed",
"cache",
"key",
"for",
"the",
"specified",
"hashable",
"arguments",
"."
] | train | https://github.com/jor-/util/blob/0eb0be84430f88885f4d48335596ca8881f85587/util/cache/memory.py#L22-L28 |
jor-/util | util/cache/memory.py | attribute_dependend_key | def attribute_dependend_key(key_function, *dependencies):
"""Return a cache key for the specified hashable arguments with additional dependent arguments."""
def dependend_key_function(self, *args, **kwargs):
key = hash_key(*args, **kwargs)
if len(dependencies) > 0:
dependec... | python | def attribute_dependend_key(key_function, *dependencies):
"""Return a cache key for the specified hashable arguments with additional dependent arguments."""
def dependend_key_function(self, *args, **kwargs):
key = hash_key(*args, **kwargs)
if len(dependencies) > 0:
dependec... | [
"def",
"attribute_dependend_key",
"(",
"key_function",
",",
"*",
"dependencies",
")",
":",
"def",
"dependend_key_function",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"key",
"=",
"hash_key",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs... | Return a cache key for the specified hashable arguments with additional dependent arguments. | [
"Return",
"a",
"cache",
"key",
"for",
"the",
"specified",
"hashable",
"arguments",
"with",
"additional",
"dependent",
"arguments",
"."
] | train | https://github.com/jor-/util/blob/0eb0be84430f88885f4d48335596ca8881f85587/util/cache/memory.py#L35-L51 |
radujica/baloo | baloo/functions/utils.py | raw | def raw(func, **func_args):
"""Decorator for eager functions checking input array
and stripping away the weld_type.
Stripping the weld_type is required to keep the same code in Series.apply and because
Numpy functions don't (all) have kwargs. Passing weld_type to NumPy functions is unexpected
and r... | python | def raw(func, **func_args):
"""Decorator for eager functions checking input array
and stripping away the weld_type.
Stripping the weld_type is required to keep the same code in Series.apply and because
Numpy functions don't (all) have kwargs. Passing weld_type to NumPy functions is unexpected
and r... | [
"def",
"raw",
"(",
"func",
",",
"*",
"*",
"func_args",
")",
":",
"if",
"len",
"(",
"func_args",
")",
"==",
"0",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"array",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"isinstance",
"(",
"ar... | Decorator for eager functions checking input array
and stripping away the weld_type.
Stripping the weld_type is required to keep the same code in Series.apply and because
Numpy functions don't (all) have kwargs. Passing weld_type to NumPy functions is unexpected
and raises ValueError.
Parameters
... | [
"Decorator",
"for",
"eager",
"functions",
"checking",
"input",
"array",
"and",
"stripping",
"away",
"the",
"weld_type",
"."
] | train | https://github.com/radujica/baloo/blob/f6e05e35b73a75e8a300754c6bdc575e5f2d53b9/baloo/functions/utils.py#L23-L60 |
mfalesni/Runner | Runner/__init__.py | Run.AssertRC | def AssertRC(self, rc=0):
""" Assert used for testing on certain RC values
:raises: ``AssertionError``
"""
assert self.rc == rc, "Command `%s` failed. $? expected: %d, $? given: %d" % (self.command, rc, self.rc) | python | def AssertRC(self, rc=0):
""" Assert used for testing on certain RC values
:raises: ``AssertionError``
"""
assert self.rc == rc, "Command `%s` failed. $? expected: %d, $? given: %d" % (self.command, rc, self.rc) | [
"def",
"AssertRC",
"(",
"self",
",",
"rc",
"=",
"0",
")",
":",
"assert",
"self",
".",
"rc",
"==",
"rc",
",",
"\"Command `%s` failed. $? expected: %d, $? given: %d\"",
"%",
"(",
"self",
".",
"command",
",",
"rc",
",",
"self",
".",
"rc",
")"
] | Assert used for testing on certain RC values
:raises: ``AssertionError`` | [
"Assert",
"used",
"for",
"testing",
"on",
"certain",
"RC",
"values"
] | train | https://github.com/mfalesni/Runner/blob/8528b4909763b53746a6b07804c6d44111df8751/Runner/__init__.py#L60-L65 |
mfalesni/Runner | Runner/__init__.py | Run.command | def command(cls, command, stdin=None, shell=False):
""" Runs specified command.
The command can be fed with data on stdin with parameter ``stdin``.
The command can also be treated as a shell command with parameter ``shell``.
Please refer to subprocess.Popen on how does this stuff work
... | python | def command(cls, command, stdin=None, shell=False):
""" Runs specified command.
The command can be fed with data on stdin with parameter ``stdin``.
The command can also be treated as a shell command with parameter ``shell``.
Please refer to subprocess.Popen on how does this stuff work
... | [
"def",
"command",
"(",
"cls",
",",
"command",
",",
"stdin",
"=",
"None",
",",
"shell",
"=",
"False",
")",
":",
"if",
"not",
"shell",
"and",
"isinstance",
"(",
"command",
",",
"str",
")",
":",
"command",
"=",
"cls",
".",
"shlex",
".",
"split",
"(",
... | Runs specified command.
The command can be fed with data on stdin with parameter ``stdin``.
The command can also be treated as a shell command with parameter ``shell``.
Please refer to subprocess.Popen on how does this stuff work
:returns: Run() instance with resulting data | [
"Runs",
"specified",
"command",
"."
] | train | https://github.com/mfalesni/Runner/blob/8528b4909763b53746a6b07804c6d44111df8751/Runner/__init__.py#L68-L97 |
radujica/baloo | baloo/weld/lazy_result.py | LazyResult.evaluate | def evaluate(self, verbose=False, decode=True, passes=None, num_threads=1,
apply_experimental_transforms=True):
"""Evaluate the stored expression.
Parameters
----------
verbose : bool, optional
Whether to print output for each Weld compilation step.
... | python | def evaluate(self, verbose=False, decode=True, passes=None, num_threads=1,
apply_experimental_transforms=True):
"""Evaluate the stored expression.
Parameters
----------
verbose : bool, optional
Whether to print output for each Weld compilation step.
... | [
"def",
"evaluate",
"(",
"self",
",",
"verbose",
"=",
"False",
",",
"decode",
"=",
"True",
",",
"passes",
"=",
"None",
",",
"num_threads",
"=",
"1",
",",
"apply_experimental_transforms",
"=",
"True",
")",
":",
"if",
"isinstance",
"(",
"self",
".",
"weld_e... | Evaluate the stored expression.
Parameters
----------
verbose : bool, optional
Whether to print output for each Weld compilation step.
decode : bool, optional
Whether to decode the result
passes : list, optional
Which Weld optimization passes ... | [
"Evaluate",
"the",
"stored",
"expression",
"."
] | train | https://github.com/radujica/baloo/blob/f6e05e35b73a75e8a300754c6bdc575e5f2d53b9/baloo/weld/lazy_result.py#L53-L95 |
radujica/baloo | baloo/weld/convertors/encoders.py | numpy_to_weld_type | def numpy_to_weld_type(np_dtype):
"""Convert from NumPy dtype to Weld type.
Note that support for strings is intended to be only for
Python 2 str and Python 3 bytes. No unicode.
Parameters
----------
np_dtype : numpy.dtype or str
NumPy dtype.
Returns
-------
WeldType
... | python | def numpy_to_weld_type(np_dtype):
"""Convert from NumPy dtype to Weld type.
Note that support for strings is intended to be only for
Python 2 str and Python 3 bytes. No unicode.
Parameters
----------
np_dtype : numpy.dtype or str
NumPy dtype.
Returns
-------
WeldType
... | [
"def",
"numpy_to_weld_type",
"(",
"np_dtype",
")",
":",
"if",
"not",
"isinstance",
"(",
"np_dtype",
",",
"(",
"str",
",",
"bytes",
",",
"np",
".",
"dtype",
",",
"type",
")",
")",
":",
"raise",
"TypeError",
"(",
"'Can only convert np.dtype or str'",
")",
"i... | Convert from NumPy dtype to Weld type.
Note that support for strings is intended to be only for
Python 2 str and Python 3 bytes. No unicode.
Parameters
----------
np_dtype : numpy.dtype or str
NumPy dtype.
Returns
-------
WeldType
Corresponding WeldType.
Examples
... | [
"Convert",
"from",
"NumPy",
"dtype",
"to",
"Weld",
"type",
"."
] | train | https://github.com/radujica/baloo/blob/f6e05e35b73a75e8a300754c6bdc575e5f2d53b9/baloo/weld/convertors/encoders.py#L27-L59 |
kobinpy/wsgicli | wsgicli.py | run | def run(filepath, wsgiapp, host, port, reload, interval,
static, static_root, static_dirs, lineprof, lineprof_file, validate):
"""
Runs a development server for WSGI Application.
Usage:
$ wsgicli run hello.py app -h 0.0.0.0 -p 5000 --reload
$ wsgicli run hello.py app --static --st... | python | def run(filepath, wsgiapp, host, port, reload, interval,
static, static_root, static_dirs, lineprof, lineprof_file, validate):
"""
Runs a development server for WSGI Application.
Usage:
$ wsgicli run hello.py app -h 0.0.0.0 -p 5000 --reload
$ wsgicli run hello.py app --static --st... | [
"def",
"run",
"(",
"filepath",
",",
"wsgiapp",
",",
"host",
",",
"port",
",",
"reload",
",",
"interval",
",",
"static",
",",
"static_root",
",",
"static_dirs",
",",
"lineprof",
",",
"lineprof_file",
",",
"validate",
")",
":",
"insert_import_path_to_sys_modules... | Runs a development server for WSGI Application.
Usage:
$ wsgicli run hello.py app -h 0.0.0.0 -p 5000 --reload
$ wsgicli run hello.py app --static --static-root /static/ --static-dirs ./static/ | [
"Runs",
"a",
"development",
"server",
"for",
"WSGI",
"Application",
"."
] | train | https://github.com/kobinpy/wsgicli/blob/30fee1550a263c0821a0b79283f293f393c8dc27/wsgicli.py#L145-L184 |
kobinpy/wsgicli | wsgicli.py | insert_import_path_to_sys_modules | def insert_import_path_to_sys_modules(import_path):
"""
When importing a module, Python references the directories in sys.path.
The default value of sys.path varies depending on the system, But:
When you start Python with a script, the directory of the script is inserted into sys.path[0].
So we hav... | python | def insert_import_path_to_sys_modules(import_path):
"""
When importing a module, Python references the directories in sys.path.
The default value of sys.path varies depending on the system, But:
When you start Python with a script, the directory of the script is inserted into sys.path[0].
So we hav... | [
"def",
"insert_import_path_to_sys_modules",
"(",
"import_path",
")",
":",
"abspath",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"import_path",
")",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"abspath",
")",
":",
"sys",
".",
"path",
".",
"insert",
"(",... | When importing a module, Python references the directories in sys.path.
The default value of sys.path varies depending on the system, But:
When you start Python with a script, the directory of the script is inserted into sys.path[0].
So we have to replace sys.path to import object in specified scripts. | [
"When",
"importing",
"a",
"module",
"Python",
"references",
"the",
"directories",
"in",
"sys",
".",
"path",
".",
"The",
"default",
"value",
"of",
"sys",
".",
"path",
"varies",
"depending",
"on",
"the",
"system",
"But",
":",
"When",
"you",
"start",
"Python"... | train | https://github.com/kobinpy/wsgicli/blob/30fee1550a263c0821a0b79283f293f393c8dc27/wsgicli.py#L222-L234 |
kobinpy/wsgicli | wsgicli.py | shell | def shell(filepath, wsgiapp, interpreter, models):
"""
Runs a python shell.
Usage:
$ wsgicli shell app.py app -i ipython
"""
model_base_classes = get_model_base_classes()
imported_objects = {}
if models and model_base_classes:
insert_import_path_to_sys_modules(filepath)
... | python | def shell(filepath, wsgiapp, interpreter, models):
"""
Runs a python shell.
Usage:
$ wsgicli shell app.py app -i ipython
"""
model_base_classes = get_model_base_classes()
imported_objects = {}
if models and model_base_classes:
insert_import_path_to_sys_modules(filepath)
... | [
"def",
"shell",
"(",
"filepath",
",",
"wsgiapp",
",",
"interpreter",
",",
"models",
")",
":",
"model_base_classes",
"=",
"get_model_base_classes",
"(",
")",
"imported_objects",
"=",
"{",
"}",
"if",
"models",
"and",
"model_base_classes",
":",
"insert_import_path_to... | Runs a python shell.
Usage:
$ wsgicli shell app.py app -i ipython | [
"Runs",
"a",
"python",
"shell",
"."
] | train | https://github.com/kobinpy/wsgicli/blob/30fee1550a263c0821a0b79283f293f393c8dc27/wsgicli.py#L320-L350 |
lgiordani/dictregister | dictregister/dictregister.py | DictRegister.kadd | def kadd(self, key, value):
"""Adds the given key/value to all elements.
Single values for a key are stored directly, as key:value, multiple
values for the same key are stored as key,set(values).
"""
for item in self:
try:
# Use the key as a set
... | python | def kadd(self, key, value):
"""Adds the given key/value to all elements.
Single values for a key are stored directly, as key:value, multiple
values for the same key are stored as key,set(values).
"""
for item in self:
try:
# Use the key as a set
... | [
"def",
"kadd",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"for",
"item",
"in",
"self",
":",
"try",
":",
"# Use the key as a set",
"item",
"[",
"key",
"]",
".",
"add",
"(",
"value",
")",
"except",
"KeyError",
":",
"# This happens if the key is not pre... | Adds the given key/value to all elements.
Single values for a key are stored directly, as key:value, multiple
values for the same key are stored as key,set(values). | [
"Adds",
"the",
"given",
"key",
"/",
"value",
"to",
"all",
"elements",
".",
"Single",
"values",
"for",
"a",
"key",
"are",
"stored",
"directly",
"as",
"key",
":",
"value",
"multiple",
"values",
"for",
"the",
"same",
"key",
"are",
"stored",
"as",
"key",
"... | train | https://github.com/lgiordani/dictregister/blob/da3d8110d238c7b518811cb7bce65fad6f5cfc19/dictregister/dictregister.py#L26-L40 |
lgiordani/dictregister | dictregister/dictregister.py | DictRegister.kreplace | def kreplace(self, key, value):
"""Replaces the given key/value for each element.
If the key is not present silently passes.
"""
for item in self:
if key in item:
item[key] = value | python | def kreplace(self, key, value):
"""Replaces the given key/value for each element.
If the key is not present silently passes.
"""
for item in self:
if key in item:
item[key] = value | [
"def",
"kreplace",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"for",
"item",
"in",
"self",
":",
"if",
"key",
"in",
"item",
":",
"item",
"[",
"key",
"]",
"=",
"value"
] | Replaces the given key/value for each element.
If the key is not present silently passes. | [
"Replaces",
"the",
"given",
"key",
"/",
"value",
"for",
"each",
"element",
".",
"If",
"the",
"key",
"is",
"not",
"present",
"silently",
"passes",
"."
] | train | https://github.com/lgiordani/dictregister/blob/da3d8110d238c7b518811cb7bce65fad6f5cfc19/dictregister/dictregister.py#L42-L48 |
lgiordani/dictregister | dictregister/dictregister.py | DictRegister.kremove | def kremove(self, key, value=None):
"""Removes the given key/value from all elements.
If value is not specified, the whole key is removed.
If value is not None and the key is present but with a
different value, or if the key is not present, silently passes.
"""
for item i... | python | def kremove(self, key, value=None):
"""Removes the given key/value from all elements.
If value is not specified, the whole key is removed.
If value is not None and the key is present but with a
different value, or if the key is not present, silently passes.
"""
for item i... | [
"def",
"kremove",
"(",
"self",
",",
"key",
",",
"value",
"=",
"None",
")",
":",
"for",
"item",
"in",
"self",
":",
"if",
"value",
"is",
"None",
":",
"# Just pop the key if present,",
"# otherwise return None",
"# (shortcut to ignore the exception)",
"item",
".",
... | Removes the given key/value from all elements.
If value is not specified, the whole key is removed.
If value is not None and the key is present but with a
different value, or if the key is not present, silently passes. | [
"Removes",
"the",
"given",
"key",
"/",
"value",
"from",
"all",
"elements",
".",
"If",
"value",
"is",
"not",
"specified",
"the",
"whole",
"key",
"is",
"removed",
".",
"If",
"value",
"is",
"not",
"None",
"and",
"the",
"key",
"is",
"present",
"but",
"with... | train | https://github.com/lgiordani/dictregister/blob/da3d8110d238c7b518811cb7bce65fad6f5cfc19/dictregister/dictregister.py#L50-L78 |
lgiordani/dictregister | dictregister/dictregister.py | DictRegister.dfilter | def dfilter(self, **kwds):
"""Returns a DictRegister which contains only the
elements that match the given specifications.
"""
starting_list = self[:]
filtered_list = []
for key, value in six.iteritems(kwds):
for item in starting_list:
if self.... | python | def dfilter(self, **kwds):
"""Returns a DictRegister which contains only the
elements that match the given specifications.
"""
starting_list = self[:]
filtered_list = []
for key, value in six.iteritems(kwds):
for item in starting_list:
if self.... | [
"def",
"dfilter",
"(",
"self",
",",
"*",
"*",
"kwds",
")",
":",
"starting_list",
"=",
"self",
"[",
":",
"]",
"filtered_list",
"=",
"[",
"]",
"for",
"key",
",",
"value",
"in",
"six",
".",
"iteritems",
"(",
"kwds",
")",
":",
"for",
"item",
"in",
"s... | Returns a DictRegister which contains only the
elements that match the given specifications. | [
"Returns",
"a",
"DictRegister",
"which",
"contains",
"only",
"the",
"elements",
"that",
"match",
"the",
"given",
"specifications",
"."
] | train | https://github.com/lgiordani/dictregister/blob/da3d8110d238c7b518811cb7bce65fad6f5cfc19/dictregister/dictregister.py#L117-L129 |
lgiordani/dictregister | dictregister/dictregister.py | DictRegister.dpop | def dpop(self, **kwds):
"""Pops and returns the first element that matches the
given specification. If no elements are found
raises IndexError.
"""
item = self.dget(**kwds)
self.remove(item)
return item | python | def dpop(self, **kwds):
"""Pops and returns the first element that matches the
given specification. If no elements are found
raises IndexError.
"""
item = self.dget(**kwds)
self.remove(item)
return item | [
"def",
"dpop",
"(",
"self",
",",
"*",
"*",
"kwds",
")",
":",
"item",
"=",
"self",
".",
"dget",
"(",
"*",
"*",
"kwds",
")",
"self",
".",
"remove",
"(",
"item",
")",
"return",
"item"
] | Pops and returns the first element that matches the
given specification. If no elements are found
raises IndexError. | [
"Pops",
"and",
"returns",
"the",
"first",
"element",
"that",
"matches",
"the",
"given",
"specification",
".",
"If",
"no",
"elements",
"are",
"found",
"raises",
"IndexError",
"."
] | train | https://github.com/lgiordani/dictregister/blob/da3d8110d238c7b518811cb7bce65fad6f5cfc19/dictregister/dictregister.py#L138-L145 |
lgiordani/dictregister | dictregister/dictregister.py | DictRegister.dremove | def dremove(self, **kwds):
"""Removes from the object any element that matches the
given specification.
"""
filtered_dr = self.dfilter(**kwds)
for item in filtered_dr:
self.remove(item)
return filtered_dr | python | def dremove(self, **kwds):
"""Removes from the object any element that matches the
given specification.
"""
filtered_dr = self.dfilter(**kwds)
for item in filtered_dr:
self.remove(item)
return filtered_dr | [
"def",
"dremove",
"(",
"self",
",",
"*",
"*",
"kwds",
")",
":",
"filtered_dr",
"=",
"self",
".",
"dfilter",
"(",
"*",
"*",
"kwds",
")",
"for",
"item",
"in",
"filtered_dr",
":",
"self",
".",
"remove",
"(",
"item",
")",
"return",
"filtered_dr"
] | Removes from the object any element that matches the
given specification. | [
"Removes",
"from",
"the",
"object",
"any",
"element",
"that",
"matches",
"the",
"given",
"specification",
"."
] | train | https://github.com/lgiordani/dictregister/blob/da3d8110d238c7b518811cb7bce65fad6f5cfc19/dictregister/dictregister.py#L147-L154 |
lgiordani/dictregister | dictregister/dictregister.py | DictRegister.dremove_copy | def dremove_copy(self, **kwds):
"""Returns a copy of the object without any element that
matches the given specification.
"""
copy_dr = DictRegister(self)
copy_dr.dremove(**kwds)
return copy_dr | python | def dremove_copy(self, **kwds):
"""Returns a copy of the object without any element that
matches the given specification.
"""
copy_dr = DictRegister(self)
copy_dr.dremove(**kwds)
return copy_dr | [
"def",
"dremove_copy",
"(",
"self",
",",
"*",
"*",
"kwds",
")",
":",
"copy_dr",
"=",
"DictRegister",
"(",
"self",
")",
"copy_dr",
".",
"dremove",
"(",
"*",
"*",
"kwds",
")",
"return",
"copy_dr"
] | Returns a copy of the object without any element that
matches the given specification. | [
"Returns",
"a",
"copy",
"of",
"the",
"object",
"without",
"any",
"element",
"that",
"matches",
"the",
"given",
"specification",
"."
] | train | https://github.com/lgiordani/dictregister/blob/da3d8110d238c7b518811cb7bce65fad6f5cfc19/dictregister/dictregister.py#L156-L162 |
iDigBio/idigbio-python-client | examples/fetch_media/fetch_media.py | get_media_with_naming | def get_media_with_naming (output_dir, media_url, uuid, size):
"""
Download a media file to a directory and name it based on the input parameters.
'output_dir' controls where the download is placed.
'media_url' is the url / link to the media that will be downloaded.
'uuid' is used to uniquely identify the out... | python | def get_media_with_naming (output_dir, media_url, uuid, size):
"""
Download a media file to a directory and name it based on the input parameters.
'output_dir' controls where the download is placed.
'media_url' is the url / link to the media that will be downloaded.
'uuid' is used to uniquely identify the out... | [
"def",
"get_media_with_naming",
"(",
"output_dir",
",",
"media_url",
",",
"uuid",
",",
"size",
")",
":",
"try",
":",
"response",
"=",
"requests",
".",
"get",
"(",
"media_url",
",",
"stream",
"=",
"True",
")",
"response",
".",
"raise_for_status",
"(",
")",
... | Download a media file to a directory and name it based on the input parameters.
'output_dir' controls where the download is placed.
'media_url' is the url / link to the media that will be downloaded.
'uuid' is used to uniquely identify the output filename.
'SIZE' is the class of image derivative, useful in the ... | [
"Download",
"a",
"media",
"file",
"to",
"a",
"directory",
"and",
"name",
"it",
"based",
"on",
"the",
"input",
"parameters",
"."
] | train | https://github.com/iDigBio/idigbio-python-client/blob/e896075b9fed297fc420caf303b3bb5a2298d969/examples/fetch_media/fetch_media.py#L173-L207 |
photo/openphoto-python | trovebox/main.py | main | def main(args=sys.argv[1:]):
"""Run the commandline script"""
usage = "%prog --help"
parser = OptionParser(usage, add_help_option=False)
parser.add_option('-c', '--config', help="Configuration file to use",
action='store', type='string', dest='config_file')
parser.add_option('-... | python | def main(args=sys.argv[1:]):
"""Run the commandline script"""
usage = "%prog --help"
parser = OptionParser(usage, add_help_option=False)
parser.add_option('-c', '--config', help="Configuration file to use",
action='store', type='string', dest='config_file')
parser.add_option('-... | [
"def",
"main",
"(",
"args",
"=",
"sys",
".",
"argv",
"[",
"1",
":",
"]",
")",
":",
"usage",
"=",
"\"%prog --help\"",
"parser",
"=",
"OptionParser",
"(",
"usage",
",",
"add_help_option",
"=",
"False",
")",
"parser",
".",
"add_option",
"(",
"'-c'",
",",
... | Run the commandline script | [
"Run",
"the",
"commandline",
"script"
] | train | https://github.com/photo/openphoto-python/blob/209a1da27c8d8c88dbcf4ea6c6f57031ea1bc44b/trovebox/main.py#L29-L110 |
photo/openphoto-python | trovebox/main.py | extract_files | def extract_files(params):
"""
Extract filenames from the "photo" parameter so they can be uploaded,
returning (updated_params, files).
Uses the same technique as the Trovebox PHP commandline tool:
* Filename can only be in the "photo" parameter
* Filename must be prefixed with "@"
* F... | python | def extract_files(params):
"""
Extract filenames from the "photo" parameter so they can be uploaded,
returning (updated_params, files).
Uses the same technique as the Trovebox PHP commandline tool:
* Filename can only be in the "photo" parameter
* Filename must be prefixed with "@"
* F... | [
"def",
"extract_files",
"(",
"params",
")",
":",
"files",
"=",
"{",
"}",
"updated_params",
"=",
"{",
"}",
"for",
"name",
"in",
"params",
":",
"if",
"name",
"==",
"\"photo\"",
"and",
"params",
"[",
"name",
"]",
".",
"startswith",
"(",
"\"@\"",
")",
":... | Extract filenames from the "photo" parameter so they can be uploaded,
returning (updated_params, files).
Uses the same technique as the Trovebox PHP commandline tool:
* Filename can only be in the "photo" parameter
* Filename must be prefixed with "@"
* Filename must exist
...otherwise the... | [
"Extract",
"filenames",
"from",
"the",
"photo",
"parameter",
"so",
"they",
"can",
"be",
"uploaded",
"returning",
"(",
"updated_params",
"files",
")",
".",
"Uses",
"the",
"same",
"technique",
"as",
"the",
"Trovebox",
"PHP",
"commandline",
"tool",
":",
"*",
"F... | train | https://github.com/photo/openphoto-python/blob/209a1da27c8d8c88dbcf4ea6c6f57031ea1bc44b/trovebox/main.py#L112-L137 |
sveetch/django-icomoon | icomoon/utils.py | extend_webfont_settings | def extend_webfont_settings(webfont_settings):
"""
Validate a webfont settings and optionally fill missing ``csspart_path``
option.
Args:
webfont_settings (dict): Webfont settings (an item value from
``settings.ICOMOON_WEBFONTS``).
Returns:
dict: Webfont settings
""... | python | def extend_webfont_settings(webfont_settings):
"""
Validate a webfont settings and optionally fill missing ``csspart_path``
option.
Args:
webfont_settings (dict): Webfont settings (an item value from
``settings.ICOMOON_WEBFONTS``).
Returns:
dict: Webfont settings
""... | [
"def",
"extend_webfont_settings",
"(",
"webfont_settings",
")",
":",
"if",
"not",
"webfont_settings",
".",
"get",
"(",
"'fontdir_path'",
",",
"False",
")",
":",
"raise",
"IcomoonSettingsError",
"(",
"(",
"\"Webfont settings miss the required key \"",
"\"item 'fontdir_path... | Validate a webfont settings and optionally fill missing ``csspart_path``
option.
Args:
webfont_settings (dict): Webfont settings (an item value from
``settings.ICOMOON_WEBFONTS``).
Returns:
dict: Webfont settings | [
"Validate",
"a",
"webfont",
"settings",
"and",
"optionally",
"fill",
"missing",
"csspart_path",
"option",
"."
] | train | https://github.com/sveetch/django-icomoon/blob/39f363ad3fbf53400be64a6c9413bf80c6308edf/icomoon/utils.py#L9-L28 |
jtmoulia/switchboard-python | examples/lamsonworker.py | main | def main(url, lamson_host, lamson_port, lamson_debug):
"""
Create, connect, and block on the Lamson worker.
"""
try:
worker = LamsonWorker(url=url,
lamson_host=lamson_host,
lamson_port=lamson_port,
lamson_d... | python | def main(url, lamson_host, lamson_port, lamson_debug):
"""
Create, connect, and block on the Lamson worker.
"""
try:
worker = LamsonWorker(url=url,
lamson_host=lamson_host,
lamson_port=lamson_port,
lamson_d... | [
"def",
"main",
"(",
"url",
",",
"lamson_host",
",",
"lamson_port",
",",
"lamson_debug",
")",
":",
"try",
":",
"worker",
"=",
"LamsonWorker",
"(",
"url",
"=",
"url",
",",
"lamson_host",
"=",
"lamson_host",
",",
"lamson_port",
"=",
"lamson_port",
",",
"lamso... | Create, connect, and block on the Lamson worker. | [
"Create",
"connect",
"and",
"block",
"on",
"the",
"Lamson",
"worker",
"."
] | train | https://github.com/jtmoulia/switchboard-python/blob/c9b0cb74cb12a64385465091be633e78d39f08b1/examples/lamsonworker.py#L47-L59 |
jtmoulia/switchboard-python | examples/lamsonworker.py | LamsonWorker.received_new | def received_new(self, msg):
"""
As new messages arrive, deliver them to the lamson relay.
"""
logger.info("Receiving msg, delivering to Lamson...")
logger.debug("Relaying msg to lamson: From: %s, To: %s",
msg['From'], msg['To'])
self._relay.deliver(m... | python | def received_new(self, msg):
"""
As new messages arrive, deliver them to the lamson relay.
"""
logger.info("Receiving msg, delivering to Lamson...")
logger.debug("Relaying msg to lamson: From: %s, To: %s",
msg['From'], msg['To'])
self._relay.deliver(m... | [
"def",
"received_new",
"(",
"self",
",",
"msg",
")",
":",
"logger",
".",
"info",
"(",
"\"Receiving msg, delivering to Lamson...\"",
")",
"logger",
".",
"debug",
"(",
"\"Relaying msg to lamson: From: %s, To: %s\"",
",",
"msg",
"[",
"'From'",
"]",
",",
"msg",
"[",
... | As new messages arrive, deliver them to the lamson relay. | [
"As",
"new",
"messages",
"arrive",
"deliver",
"them",
"to",
"the",
"lamson",
"relay",
"."
] | train | https://github.com/jtmoulia/switchboard-python/blob/c9b0cb74cb12a64385465091be633e78d39f08b1/examples/lamsonworker.py#L37-L44 |
ryanpetrello/cleaver | cleaver/reports/web/bottle.py | validate | def validate(**vkargs):
"""
Validates and manipulates keyword arguments by user defined callables.
Handles ValueError and missing arguments by raising HTTPError(403).
"""
depr('Use route wildcard filters instead.')
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **... | python | def validate(**vkargs):
"""
Validates and manipulates keyword arguments by user defined callables.
Handles ValueError and missing arguments by raising HTTPError(403).
"""
depr('Use route wildcard filters instead.')
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **... | [
"def",
"validate",
"(",
"*",
"*",
"vkargs",
")",
":",
"depr",
"(",
"'Use route wildcard filters instead.'",
")",
"def",
"decorator",
"(",
"func",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
... | Validates and manipulates keyword arguments by user defined callables.
Handles ValueError and missing arguments by raising HTTPError(403). | [
"Validates",
"and",
"manipulates",
"keyword",
"arguments",
"by",
"user",
"defined",
"callables",
".",
"Handles",
"ValueError",
"and",
"missing",
"arguments",
"by",
"raising",
"HTTPError",
"(",
"403",
")",
"."
] | train | https://github.com/ryanpetrello/cleaver/blob/0ef266e1a0603c6d414df4b9926ce2a59844db35/cleaver/reports/web/bottle.py#L2248-L2266 |
ryanpetrello/cleaver | cleaver/reports/web/bottle.py | Bottle.mount | def mount(self, prefix, app, **options):
''' Mount an application (:class:`Bottle` or plain WSGI) to a specific
URL prefix. Example::
root_app.mount('/admin/', admin_app)
:param prefix: path prefix or `mount-point`. If it ends in a slash,
that slash is m... | python | def mount(self, prefix, app, **options):
''' Mount an application (:class:`Bottle` or plain WSGI) to a specific
URL prefix. Example::
root_app.mount('/admin/', admin_app)
:param prefix: path prefix or `mount-point`. If it ends in a slash,
that slash is m... | [
"def",
"mount",
"(",
"self",
",",
"prefix",
",",
"app",
",",
"*",
"*",
"options",
")",
":",
"if",
"isinstance",
"(",
"app",
",",
"basestring",
")",
":",
"prefix",
",",
"app",
"=",
"app",
",",
"prefix",
"depr",
"(",
"'Parameter order of Bottle.mount() cha... | Mount an application (:class:`Bottle` or plain WSGI) to a specific
URL prefix. Example::
root_app.mount('/admin/', admin_app)
:param prefix: path prefix or `mount-point`. If it ends in a slash,
that slash is mandatory.
:param app: an instance of :cla... | [
"Mount",
"an",
"application",
"(",
":",
"class",
":",
"Bottle",
"or",
"plain",
"WSGI",
")",
"to",
"a",
"specific",
"URL",
"prefix",
".",
"Example",
"::"
] | train | https://github.com/ryanpetrello/cleaver/blob/0ef266e1a0603c6d414df4b9926ce2a59844db35/cleaver/reports/web/bottle.py#L581-L618 |
ryanpetrello/cleaver | cleaver/reports/web/bottle.py | BaseRequest.query | def query(self):
''' The :attr:`query_string` parsed into a :class:`FormsDict`. These
values are sometimes called "URL arguments" or "GET parameters", but
not to be confused with "URL wildcards" as they are provided by the
:class:`Router`. '''
pairs = parse_qsl(self.q... | python | def query(self):
''' The :attr:`query_string` parsed into a :class:`FormsDict`. These
values are sometimes called "URL arguments" or "GET parameters", but
not to be confused with "URL wildcards" as they are provided by the
:class:`Router`. '''
pairs = parse_qsl(self.q... | [
"def",
"query",
"(",
"self",
")",
":",
"pairs",
"=",
"parse_qsl",
"(",
"self",
".",
"query_string",
",",
"keep_blank_values",
"=",
"True",
")",
"get",
"=",
"self",
".",
"environ",
"[",
"'bottle.get'",
"]",
"=",
"FormsDict",
"(",
")",
"for",
"key",
",",... | The :attr:`query_string` parsed into a :class:`FormsDict`. These
values are sometimes called "URL arguments" or "GET parameters", but
not to be confused with "URL wildcards" as they are provided by the
:class:`Router`. | [
"The",
":",
"attr",
":",
"query_string",
"parsed",
"into",
"a",
":",
"class",
":",
"FormsDict",
".",
"These",
"values",
"are",
"sometimes",
"called",
"URL",
"arguments",
"or",
"GET",
"parameters",
"but",
"not",
"to",
"be",
"confused",
"with",
"URL",
"wildc... | train | https://github.com/ryanpetrello/cleaver/blob/0ef266e1a0603c6d414df4b9926ce2a59844db35/cleaver/reports/web/bottle.py#L988-L997 |
ryanpetrello/cleaver | cleaver/reports/web/bottle.py | BaseRequest.forms | def forms(self):
""" Form values parsed from an `url-encoded` or `multipart/form-data`
encoded POST or PUT request body. The result is retuned as a
:class:`FormsDict`. All keys and values are strings. File uploads
are stored separately in :attr:`files`. """
forms = Fo... | python | def forms(self):
""" Form values parsed from an `url-encoded` or `multipart/form-data`
encoded POST or PUT request body. The result is retuned as a
:class:`FormsDict`. All keys and values are strings. File uploads
are stored separately in :attr:`files`. """
forms = Fo... | [
"def",
"forms",
"(",
"self",
")",
":",
"forms",
"=",
"FormsDict",
"(",
")",
"for",
"name",
",",
"item",
"in",
"self",
".",
"POST",
".",
"allitems",
"(",
")",
":",
"if",
"not",
"hasattr",
"(",
"item",
",",
"'filename'",
")",
":",
"forms",
"[",
"na... | Form values parsed from an `url-encoded` or `multipart/form-data`
encoded POST or PUT request body. The result is retuned as a
:class:`FormsDict`. All keys and values are strings. File uploads
are stored separately in :attr:`files`. | [
"Form",
"values",
"parsed",
"from",
"an",
"url",
"-",
"encoded",
"or",
"multipart",
"/",
"form",
"-",
"data",
"encoded",
"POST",
"or",
"PUT",
"request",
"body",
".",
"The",
"result",
"is",
"retuned",
"as",
"a",
":",
"class",
":",
"FormsDict",
".",
"All... | train | https://github.com/ryanpetrello/cleaver/blob/0ef266e1a0603c6d414df4b9926ce2a59844db35/cleaver/reports/web/bottle.py#L1000-L1009 |
ryanpetrello/cleaver | cleaver/reports/web/bottle.py | BaseRequest.files | def files(self):
""" File uploads parsed from an `url-encoded` or `multipart/form-data`
encoded POST or PUT request body. The values are instances of
:class:`cgi.FieldStorage`. The most important attributes are:
filename
The filename, if specified; otherwise ... | python | def files(self):
""" File uploads parsed from an `url-encoded` or `multipart/form-data`
encoded POST or PUT request body. The values are instances of
:class:`cgi.FieldStorage`. The most important attributes are:
filename
The filename, if specified; otherwise ... | [
"def",
"files",
"(",
"self",
")",
":",
"files",
"=",
"FormsDict",
"(",
")",
"for",
"name",
",",
"item",
"in",
"self",
".",
"POST",
".",
"allitems",
"(",
")",
":",
"if",
"hasattr",
"(",
"item",
",",
"'filename'",
")",
":",
"files",
"[",
"name",
"]... | File uploads parsed from an `url-encoded` or `multipart/form-data`
encoded POST or PUT request body. The values are instances of
:class:`cgi.FieldStorage`. The most important attributes are:
filename
The filename, if specified; otherwise None; this is the client
... | [
"File",
"uploads",
"parsed",
"from",
"an",
"url",
"-",
"encoded",
"or",
"multipart",
"/",
"form",
"-",
"data",
"encoded",
"POST",
"or",
"PUT",
"request",
"body",
".",
"The",
"values",
"are",
"instances",
"of",
":",
"class",
":",
"cgi",
".",
"FieldStorage... | train | https://github.com/ryanpetrello/cleaver/blob/0ef266e1a0603c6d414df4b9926ce2a59844db35/cleaver/reports/web/bottle.py#L1023-L1043 |
ryanpetrello/cleaver | cleaver/reports/web/bottle.py | BaseResponse.iter_headers | def iter_headers(self):
''' Yield (header, value) tuples, skipping headers that are not
allowed with the current response status code. '''
headers = self._headers.items()
bad_headers = self.bad_headers.get(self._status_code)
if bad_headers:
headers = [h for h in h... | python | def iter_headers(self):
''' Yield (header, value) tuples, skipping headers that are not
allowed with the current response status code. '''
headers = self._headers.items()
bad_headers = self.bad_headers.get(self._status_code)
if bad_headers:
headers = [h for h in h... | [
"def",
"iter_headers",
"(",
"self",
")",
":",
"headers",
"=",
"self",
".",
"_headers",
".",
"items",
"(",
")",
"bad_headers",
"=",
"self",
".",
"bad_headers",
".",
"get",
"(",
"self",
".",
"_status_code",
")",
"if",
"bad_headers",
":",
"headers",
"=",
... | Yield (header, value) tuples, skipping headers that are not
allowed with the current response status code. | [
"Yield",
"(",
"header",
"value",
")",
"tuples",
"skipping",
"headers",
"that",
"are",
"not",
"allowed",
"with",
"the",
"current",
"response",
"status",
"code",
"."
] | train | https://github.com/ryanpetrello/cleaver/blob/0ef266e1a0603c6d414df4b9926ce2a59844db35/cleaver/reports/web/bottle.py#L1393-L1405 |
ryanpetrello/cleaver | cleaver/reports/web/bottle.py | ResourceManager.add_path | def add_path(self, path, base=None, index=None, create=False):
''' Add a new path to the list of search paths. Return False if it does
not exist.
:param path: The new search path. Relative paths are turned into an
absolute and normalized form. If the path looks like a fi... | python | def add_path(self, path, base=None, index=None, create=False):
''' Add a new path to the list of search paths. Return False if it does
not exist.
:param path: The new search path. Relative paths are turned into an
absolute and normalized form. If the path looks like a fi... | [
"def",
"add_path",
"(",
"self",
",",
"path",
",",
"base",
"=",
"None",
",",
"index",
"=",
"None",
",",
"create",
"=",
"False",
")",
":",
"base",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"base",
"or",
... | Add a new path to the list of search paths. Return False if it does
not exist.
:param path: The new search path. Relative paths are turned into an
absolute and normalized form. If the path looks like a file (not
ending in `/`), the filename is stripped off.
... | [
"Add",
"a",
"new",
"path",
"to",
"the",
"list",
"of",
"search",
"paths",
".",
"Return",
"False",
"if",
"it",
"does",
"not",
"exist",
"."
] | train | https://github.com/ryanpetrello/cleaver/blob/0ef266e1a0603c6d414df4b9926ce2a59844db35/cleaver/reports/web/bottle.py#L1948-L1977 |
OTL/jps | jps/utils.py | JsonMultiplePublisher.publish | def publish(self, json_msg):
'''
json_msg = '{"topic1": 1.0, "topic2": {"x": 0.1}}'
'''
pyobj = json.loads(json_msg)
for topic, value in pyobj.items():
msg = '{topic} {data}'.format(topic=topic, data=json.dumps(value))
self._pub.publish(msg) | python | def publish(self, json_msg):
'''
json_msg = '{"topic1": 1.0, "topic2": {"x": 0.1}}'
'''
pyobj = json.loads(json_msg)
for topic, value in pyobj.items():
msg = '{topic} {data}'.format(topic=topic, data=json.dumps(value))
self._pub.publish(msg) | [
"def",
"publish",
"(",
"self",
",",
"json_msg",
")",
":",
"pyobj",
"=",
"json",
".",
"loads",
"(",
"json_msg",
")",
"for",
"topic",
",",
"value",
"in",
"pyobj",
".",
"items",
"(",
")",
":",
"msg",
"=",
"'{topic} {data}'",
".",
"format",
"(",
"topic",... | json_msg = '{"topic1": 1.0, "topic2": {"x": 0.1}}' | [
"json_msg",
"=",
"{",
"topic1",
":",
"1",
".",
"0",
"topic2",
":",
"{",
"x",
":",
"0",
".",
"1",
"}}"
] | train | https://github.com/OTL/jps/blob/2c5a438d59611fffca6853072c822ef22665ed87/jps/utils.py#L24-L31 |
lemieuxl/pyGenClean | pyGenClean/__init__.py | add_file_handler_to_root | def add_file_handler_to_root(log_fn):
"""Adds a file handler to the root logging.
:param log_fn: the name of the log file.
:type log_fn: str
"""
file_handler = logging.FileHandler(log_fn, mode="w")
file_handler.setFormatter(logging.Formatter(
fmt="[%(asctime)s %(name)s %(levelname)s] ... | python | def add_file_handler_to_root(log_fn):
"""Adds a file handler to the root logging.
:param log_fn: the name of the log file.
:type log_fn: str
"""
file_handler = logging.FileHandler(log_fn, mode="w")
file_handler.setFormatter(logging.Formatter(
fmt="[%(asctime)s %(name)s %(levelname)s] ... | [
"def",
"add_file_handler_to_root",
"(",
"log_fn",
")",
":",
"file_handler",
"=",
"logging",
".",
"FileHandler",
"(",
"log_fn",
",",
"mode",
"=",
"\"w\"",
")",
"file_handler",
".",
"setFormatter",
"(",
"logging",
".",
"Formatter",
"(",
"fmt",
"=",
"\"[%(asctime... | Adds a file handler to the root logging.
:param log_fn: the name of the log file.
:type log_fn: str | [
"Adds",
"a",
"file",
"handler",
"to",
"the",
"root",
"logging",
"."
] | train | https://github.com/lemieuxl/pyGenClean/blob/6173a48ccc0cf3a3bd711b1f2a1fa16248b8bf55/pyGenClean/__init__.py#L43-L56 |
Eugeny/exconsole | exconsole/console.py | register | def register(reg_signal=signal.SIGQUIT, reg_unhandled=True, commands=[]):
"""
Registers exconsole hooks
:param reg_signal: if not None, register signal handler (default: ``signal.SIGQUIT``)
:param reg_unhandled: if ``True``, register unhandled exception hook (``sys.excepthook``)
:param commands: li... | python | def register(reg_signal=signal.SIGQUIT, reg_unhandled=True, commands=[]):
"""
Registers exconsole hooks
:param reg_signal: if not None, register signal handler (default: ``signal.SIGQUIT``)
:param reg_unhandled: if ``True``, register unhandled exception hook (``sys.excepthook``)
:param commands: li... | [
"def",
"register",
"(",
"reg_signal",
"=",
"signal",
".",
"SIGQUIT",
",",
"reg_unhandled",
"=",
"True",
",",
"commands",
"=",
"[",
"]",
")",
":",
"if",
"reg_signal",
":",
"signal",
".",
"signal",
"(",
"reg_signal",
",",
"handle_quit",
")",
"if",
"reg_unh... | Registers exconsole hooks
:param reg_signal: if not None, register signal handler (default: ``signal.SIGQUIT``)
:param reg_unhandled: if ``True``, register unhandled exception hook (``sys.excepthook``)
:param commands: list of custom commands/objects: (<local name>, <help string>, <function or object>) | [
"Registers",
"exconsole",
"hooks"
] | train | https://github.com/Eugeny/exconsole/blob/edf180d49f51d7e337c43a77d1e11338d047233a/exconsole/console.py#L8-L20 |
Eugeny/exconsole | exconsole/console.py | launch | def launch(exception=None, extraceback=None, signalnum=None, frame=None):
"""
Launches an emergency console
:param exception: unhandled exception value
:param extraceback: unhandled exception traceback
:param signalnum: interrupting signal number
:param frame: interrupting signal frame
"""
... | python | def launch(exception=None, extraceback=None, signalnum=None, frame=None):
"""
Launches an emergency console
:param exception: unhandled exception value
:param extraceback: unhandled exception traceback
:param signalnum: interrupting signal number
:param frame: interrupting signal frame
"""
... | [
"def",
"launch",
"(",
"exception",
"=",
"None",
",",
"extraceback",
"=",
"None",
",",
"signalnum",
"=",
"None",
",",
"frame",
"=",
"None",
")",
":",
"print",
"(",
"'\\n'",
")",
"print",
"(",
"'Activating emergency console'",
")",
"print",
"(",
"'----------... | Launches an emergency console
:param exception: unhandled exception value
:param extraceback: unhandled exception traceback
:param signalnum: interrupting signal number
:param frame: interrupting signal frame | [
"Launches",
"an",
"emergency",
"console"
] | train | https://github.com/Eugeny/exconsole/blob/edf180d49f51d7e337c43a77d1e11338d047233a/exconsole/console.py#L31-L142 |
brunobeltran/pscan | pscan/__init__.py | Scan.params | def params(self):
"""A generator that iterates through all parameters requested the
correct number of times each. Returns them as a dict with form
{'param_name': param_value, ... } for use as f(**params)."""
comb_sizes = []
comb_keys = []
for key,val in self.comb_params.i... | python | def params(self):
"""A generator that iterates through all parameters requested the
correct number of times each. Returns them as a dict with form
{'param_name': param_value, ... } for use as f(**params)."""
comb_sizes = []
comb_keys = []
for key,val in self.comb_params.i... | [
"def",
"params",
"(",
"self",
")",
":",
"comb_sizes",
"=",
"[",
"]",
"comb_keys",
"=",
"[",
"]",
"for",
"key",
",",
"val",
"in",
"self",
".",
"comb_params",
".",
"items",
"(",
")",
":",
"comb_keys",
".",
"append",
"(",
"key",
")",
"comb_sizes",
"."... | A generator that iterates through all parameters requested the
correct number of times each. Returns them as a dict with form
{'param_name': param_value, ... } for use as f(**params). | [
"A",
"generator",
"that",
"iterates",
"through",
"all",
"parameters",
"requested",
"the",
"correct",
"number",
"of",
"times",
"each",
".",
"Returns",
"them",
"as",
"a",
"dict",
"with",
"form",
"{",
"param_name",
":",
"param_value",
"...",
"}",
"for",
"use",
... | train | https://github.com/brunobeltran/pscan/blob/de623c66e68f293fd3a8979d5e3012f0a055f6dc/pscan/__init__.py#L169-L203 |
brunobeltran/pscan | pscan/__init__.py | Scan.add_params | def add_params(self, p):
"""Add new variables or change values to be used for particular
parameter names that will not be jointly varied."""
new_params = p.copy()
for key,val in new_params.items():
if not isinstance(val, collections.Iterable):
new_params[key] ... | python | def add_params(self, p):
"""Add new variables or change values to be used for particular
parameter names that will not be jointly varied."""
new_params = p.copy()
for key,val in new_params.items():
if not isinstance(val, collections.Iterable):
new_params[key] ... | [
"def",
"add_params",
"(",
"self",
",",
"p",
")",
":",
"new_params",
"=",
"p",
".",
"copy",
"(",
")",
"for",
"key",
",",
"val",
"in",
"new_params",
".",
"items",
"(",
")",
":",
"if",
"not",
"isinstance",
"(",
"val",
",",
"collections",
".",
"Iterabl... | Add new variables or change values to be used for particular
parameter names that will not be jointly varied. | [
"Add",
"new",
"variables",
"or",
"change",
"values",
"to",
"be",
"used",
"for",
"particular",
"parameter",
"names",
"that",
"will",
"not",
"be",
"jointly",
"varied",
"."
] | train | https://github.com/brunobeltran/pscan/blob/de623c66e68f293fd3a8979d5e3012f0a055f6dc/pscan/__init__.py#L224-L232 |
OpenGeoVis/espatools | espatools/raster.py | RasterSet.GetRGB | def GetRGB(self, scheme='infrared', names=None):
"""Get an RGB color scheme based on predefined presets or specify your
own band names to use. A given set of names always overrides a scheme.
Note:
Available schemes are defined in ``RGB_SCHEMES`` and include:
- ``true``
... | python | def GetRGB(self, scheme='infrared', names=None):
"""Get an RGB color scheme based on predefined presets or specify your
own band names to use. A given set of names always overrides a scheme.
Note:
Available schemes are defined in ``RGB_SCHEMES`` and include:
- ``true``
... | [
"def",
"GetRGB",
"(",
"self",
",",
"scheme",
"=",
"'infrared'",
",",
"names",
"=",
"None",
")",
":",
"if",
"names",
"is",
"not",
"None",
":",
"if",
"not",
"isinstance",
"(",
"names",
",",
"(",
"list",
",",
"tuple",
")",
")",
"or",
"len",
"(",
"na... | Get an RGB color scheme based on predefined presets or specify your
own band names to use. A given set of names always overrides a scheme.
Note:
Available schemes are defined in ``RGB_SCHEMES`` and include:
- ``true``
- ``infrared``
- ``false_a``
... | [
"Get",
"an",
"RGB",
"color",
"scheme",
"based",
"on",
"predefined",
"presets",
"or",
"specify",
"your",
"own",
"band",
"names",
"to",
"use",
".",
"A",
"given",
"set",
"of",
"names",
"always",
"overrides",
"a",
"scheme",
"."
] | train | https://github.com/OpenGeoVis/espatools/blob/5c04daae0f035c7efcb4096bb85a26c6959ac9ea/espatools/raster.py#L131-L166 |
brantai/python-rightscale | rightscale/httpclient.py | HTTPClient.login | def login(self):
"""
Gets and stores an OAUTH token from Rightscale.
"""
log.debug('Logging into RightScale...')
login_data = {
'grant_type': 'refresh_token',
'refresh_token': self.refresh_token,
}
response = self._request('post', self.... | python | def login(self):
"""
Gets and stores an OAUTH token from Rightscale.
"""
log.debug('Logging into RightScale...')
login_data = {
'grant_type': 'refresh_token',
'refresh_token': self.refresh_token,
}
response = self._request('post', self.... | [
"def",
"login",
"(",
"self",
")",
":",
"log",
".",
"debug",
"(",
"'Logging into RightScale...'",
")",
"login_data",
"=",
"{",
"'grant_type'",
":",
"'refresh_token'",
",",
"'refresh_token'",
":",
"self",
".",
"refresh_token",
",",
"}",
"response",
"=",
"self",
... | Gets and stores an OAUTH token from Rightscale. | [
"Gets",
"and",
"stores",
"an",
"OAUTH",
"token",
"from",
"Rightscale",
"."
] | train | https://github.com/brantai/python-rightscale/blob/5fbf4089922917247be712d58645a7b1504f0944/rightscale/httpclient.py#L72-L92 |
brantai/python-rightscale | rightscale/httpclient.py | HTTPClient.request | def request(self, method, path='/', url=None, ignore_codes=[], **kwargs):
"""
Wrapper for the ._request method that verifies if we're logged into
RightScale before making a call, and sanity checks the oauth expiration
time.
:param str method: An HTTP method (e.g. 'get', 'post', ... | python | def request(self, method, path='/', url=None, ignore_codes=[], **kwargs):
"""
Wrapper for the ._request method that verifies if we're logged into
RightScale before making a call, and sanity checks the oauth expiration
time.
:param str method: An HTTP method (e.g. 'get', 'post', ... | [
"def",
"request",
"(",
"self",
",",
"method",
",",
"path",
"=",
"'/'",
",",
"url",
"=",
"None",
",",
"ignore_codes",
"=",
"[",
"]",
",",
"*",
"*",
"kwargs",
")",
":",
"# On every call, check if we're both logged in, and if the token is",
"# expiring. If it is, we'... | Wrapper for the ._request method that verifies if we're logged into
RightScale before making a call, and sanity checks the oauth expiration
time.
:param str method: An HTTP method (e.g. 'get', 'post', 'PUT', etc...)
:param str path: A path component of the target URL. This will be
... | [
"Wrapper",
"for",
"the",
".",
"_request",
"method",
"that",
"verifies",
"if",
"we",
"re",
"logged",
"into",
"RightScale",
"before",
"making",
"a",
"call",
"and",
"sanity",
"checks",
"the",
"oauth",
"expiration",
"time",
"."
] | train | https://github.com/brantai/python-rightscale/blob/5fbf4089922917247be712d58645a7b1504f0944/rightscale/httpclient.py#L94-L127 |
brantai/python-rightscale | rightscale/httpclient.py | HTTPClient._request | def _request(self, method, path='/', url=None, ignore_codes=[], **kwargs):
"""
Performs HTTP request.
:param str method: An HTTP method (e.g. 'get', 'post', 'PUT', etc...)
:param str path: A path component of the target URL. This will be
appended to the value of ``self.end... | python | def _request(self, method, path='/', url=None, ignore_codes=[], **kwargs):
"""
Performs HTTP request.
:param str method: An HTTP method (e.g. 'get', 'post', 'PUT', etc...)
:param str path: A path component of the target URL. This will be
appended to the value of ``self.end... | [
"def",
"_request",
"(",
"self",
",",
"method",
",",
"path",
"=",
"'/'",
",",
"url",
"=",
"None",
",",
"ignore_codes",
"=",
"[",
"]",
",",
"*",
"*",
"kwargs",
")",
":",
"_url",
"=",
"url",
"if",
"url",
"else",
"(",
"self",
".",
"endpoint",
"+",
... | Performs HTTP request.
:param str method: An HTTP method (e.g. 'get', 'post', 'PUT', etc...)
:param str path: A path component of the target URL. This will be
appended to the value of ``self.endpoint``. If both :attr:`path`
and :attr:`url` are specified, the value in :attr:`u... | [
"Performs",
"HTTP",
"request",
"."
] | train | https://github.com/brantai/python-rightscale/blob/5fbf4089922917247be712d58645a7b1504f0944/rightscale/httpclient.py#L129-L157 |
titusz/epubcheck | src/epubcheck/wrap.py | validate | def validate(epub_path):
"""Minimal validation.
:return bool: True if valid else False
"""
try:
subprocess.check_call([c.JAVA, '-jar', c.EPUBCHECK, epub_path])
return True
except subprocess.CalledProcessError:
return False | python | def validate(epub_path):
"""Minimal validation.
:return bool: True if valid else False
"""
try:
subprocess.check_call([c.JAVA, '-jar', c.EPUBCHECK, epub_path])
return True
except subprocess.CalledProcessError:
return False | [
"def",
"validate",
"(",
"epub_path",
")",
":",
"try",
":",
"subprocess",
".",
"check_call",
"(",
"[",
"c",
".",
"JAVA",
",",
"'-jar'",
",",
"c",
".",
"EPUBCHECK",
",",
"epub_path",
"]",
")",
"return",
"True",
"except",
"subprocess",
".",
"CalledProcessEr... | Minimal validation.
:return bool: True if valid else False | [
"Minimal",
"validation",
"."
] | train | https://github.com/titusz/epubcheck/blob/7adde81543d3ae7385ab7062adb76e1414d49c2e/src/epubcheck/wrap.py#L7-L17 |
thiagopbueno/pyrddl | pyrddl/utils.py | rename_next_state_fluent | def rename_next_state_fluent(name: str) -> str:
'''Returns next state fluent canonical name.
Args:
name (str): The current state fluent name.
Returns:
str: The next state fluent name.
'''
i = name.index('/')
functor = name[:i-1]
arity = name[i+1:]
return "{}/{}".format(... | python | def rename_next_state_fluent(name: str) -> str:
'''Returns next state fluent canonical name.
Args:
name (str): The current state fluent name.
Returns:
str: The next state fluent name.
'''
i = name.index('/')
functor = name[:i-1]
arity = name[i+1:]
return "{}/{}".format(... | [
"def",
"rename_next_state_fluent",
"(",
"name",
":",
"str",
")",
"->",
"str",
":",
"i",
"=",
"name",
".",
"index",
"(",
"'/'",
")",
"functor",
"=",
"name",
"[",
":",
"i",
"-",
"1",
"]",
"arity",
"=",
"name",
"[",
"i",
"+",
"1",
":",
"]",
"retur... | Returns next state fluent canonical name.
Args:
name (str): The current state fluent name.
Returns:
str: The next state fluent name. | [
"Returns",
"next",
"state",
"fluent",
"canonical",
"name",
"."
] | train | https://github.com/thiagopbueno/pyrddl/blob/3bcfa850b1a7532c7744358f3c6b9e0f8ab978c9/pyrddl/utils.py#L17-L29 |
thiagopbueno/pyrddl | pyrddl/utils.py | rename_state_fluent | def rename_state_fluent(name: str) -> str:
'''Returns current state fluent canonical name.
Args:
name (str): The next state fluent name.
Returns:
str: The current state fluent name.
'''
i = name.index('/')
functor = name[:i]
arity = name[i+1:]
return "{}'/{}".format(fun... | python | def rename_state_fluent(name: str) -> str:
'''Returns current state fluent canonical name.
Args:
name (str): The next state fluent name.
Returns:
str: The current state fluent name.
'''
i = name.index('/')
functor = name[:i]
arity = name[i+1:]
return "{}'/{}".format(fun... | [
"def",
"rename_state_fluent",
"(",
"name",
":",
"str",
")",
"->",
"str",
":",
"i",
"=",
"name",
".",
"index",
"(",
"'/'",
")",
"functor",
"=",
"name",
"[",
":",
"i",
"]",
"arity",
"=",
"name",
"[",
"i",
"+",
"1",
":",
"]",
"return",
"\"{}'/{}\"",... | Returns current state fluent canonical name.
Args:
name (str): The next state fluent name.
Returns:
str: The current state fluent name. | [
"Returns",
"current",
"state",
"fluent",
"canonical",
"name",
"."
] | train | https://github.com/thiagopbueno/pyrddl/blob/3bcfa850b1a7532c7744358f3c6b9e0f8ab978c9/pyrddl/utils.py#L32-L44 |
lemieuxl/pyGenClean | pyGenClean/RelatedSamples/merge_related_samples.py | main | def main(argString=None):
"""The main function of the module.
:param argString: the options.
:type argString: list
"""
# Getting and checking the options
args = parseArgs(argString)
checkArgs(args)
merge_related_samples(args.ibs_related, args.out, args.no_status) | python | def main(argString=None):
"""The main function of the module.
:param argString: the options.
:type argString: list
"""
# Getting and checking the options
args = parseArgs(argString)
checkArgs(args)
merge_related_samples(args.ibs_related, args.out, args.no_status) | [
"def",
"main",
"(",
"argString",
"=",
"None",
")",
":",
"# Getting and checking the options",
"args",
"=",
"parseArgs",
"(",
"argString",
")",
"checkArgs",
"(",
"args",
")",
"merge_related_samples",
"(",
"args",
".",
"ibs_related",
",",
"args",
".",
"out",
","... | The main function of the module.
:param argString: the options.
:type argString: list | [
"The",
"main",
"function",
"of",
"the",
"module",
"."
] | train | https://github.com/lemieuxl/pyGenClean/blob/6173a48ccc0cf3a3bd711b1f2a1fa16248b8bf55/pyGenClean/RelatedSamples/merge_related_samples.py#L31-L43 |
lemieuxl/pyGenClean | pyGenClean/RelatedSamples/merge_related_samples.py | merge_related_samples | def merge_related_samples(file_name, out_prefix, no_status):
"""Merge related samples.
:param file_name: the name of the input file.
:param out_prefix: the prefix of the output files.
:param no_status: is there a status column in the file?
:type file_name: str
:type out_prefix: str
:type n... | python | def merge_related_samples(file_name, out_prefix, no_status):
"""Merge related samples.
:param file_name: the name of the input file.
:param out_prefix: the prefix of the output files.
:param no_status: is there a status column in the file?
:type file_name: str
:type out_prefix: str
:type n... | [
"def",
"merge_related_samples",
"(",
"file_name",
",",
"out_prefix",
",",
"no_status",
")",
":",
"# What we need to save",
"status",
"=",
"{",
"}",
"samples_sets",
"=",
"[",
"]",
"open_function",
"=",
"open",
"if",
"file_name",
".",
"endswith",
"(",
"\".gz\"",
... | Merge related samples.
:param file_name: the name of the input file.
:param out_prefix: the prefix of the output files.
:param no_status: is there a status column in the file?
:type file_name: str
:type out_prefix: str
:type no_status: boolean
In the output file, there are a pair of sampl... | [
"Merge",
"related",
"samples",
"."
] | train | https://github.com/lemieuxl/pyGenClean/blob/6173a48ccc0cf3a3bd711b1f2a1fa16248b8bf55/pyGenClean/RelatedSamples/merge_related_samples.py#L46-L172 |
lemieuxl/pyGenClean | pyGenClean/RelatedSamples/merge_related_samples.py | checkArgs | def checkArgs(args):
"""Checks the arguments and options.
:param args: a an object containing the options of the program.
:type args: argparse.Namespace
:returns: ``True`` if everything was OK.
If there is a problem with an option, an exception is raised using the
:py:class:`ProgramError` cl... | python | def checkArgs(args):
"""Checks the arguments and options.
:param args: a an object containing the options of the program.
:type args: argparse.Namespace
:returns: ``True`` if everything was OK.
If there is a problem with an option, an exception is raised using the
:py:class:`ProgramError` cl... | [
"def",
"checkArgs",
"(",
"args",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"args",
".",
"ibs_related",
")",
":",
"msg",
"=",
"\"{}: no such file\"",
".",
"format",
"(",
"args",
".",
"ibs_related",
")",
"raise",
"ProgramError",
"(",
... | Checks the arguments and options.
:param args: a an object containing the options of the program.
:type args: argparse.Namespace
:returns: ``True`` if everything was OK.
If there is a problem with an option, an exception is raised using the
:py:class:`ProgramError` class, a message is printed to... | [
"Checks",
"the",
"arguments",
"and",
"options",
"."
] | train | https://github.com/lemieuxl/pyGenClean/blob/6173a48ccc0cf3a3bd711b1f2a1fa16248b8bf55/pyGenClean/RelatedSamples/merge_related_samples.py#L175-L193 |
RacingTadpole/django-singleton-admin | django_singleton_admin/admin.py | admin_url | def admin_url(model, url, object_id=None):
"""
Returns the URL for the given model and admin url name.
"""
opts = model._meta
url = "admin:%s_%s_%s" % (opts.app_label, opts.object_name.lower(), url)
args = ()
if object_id is not None:
args = (object_id,)
return reverse(url, args=... | python | def admin_url(model, url, object_id=None):
"""
Returns the URL for the given model and admin url name.
"""
opts = model._meta
url = "admin:%s_%s_%s" % (opts.app_label, opts.object_name.lower(), url)
args = ()
if object_id is not None:
args = (object_id,)
return reverse(url, args=... | [
"def",
"admin_url",
"(",
"model",
",",
"url",
",",
"object_id",
"=",
"None",
")",
":",
"opts",
"=",
"model",
".",
"_meta",
"url",
"=",
"\"admin:%s_%s_%s\"",
"%",
"(",
"opts",
".",
"app_label",
",",
"opts",
".",
"object_name",
".",
"lower",
"(",
")",
... | Returns the URL for the given model and admin url name. | [
"Returns",
"the",
"URL",
"for",
"the",
"given",
"model",
"and",
"admin",
"url",
"name",
"."
] | train | https://github.com/RacingTadpole/django-singleton-admin/blob/0a81454be11fdcbaf95ca5018667a8dff3f45bf7/django_singleton_admin/admin.py#L15-L24 |
RacingTadpole/django-singleton-admin | django_singleton_admin/admin.py | SingletonAdmin.handle_save | def handle_save(self, request, response):
"""
Handles redirect back to the dashboard when save is clicked
(eg not save and continue editing), by checking for a redirect
response, which only occurs if the form is valid.
"""
form_valid = isinstance(response, HttpResponseRed... | python | def handle_save(self, request, response):
"""
Handles redirect back to the dashboard when save is clicked
(eg not save and continue editing), by checking for a redirect
response, which only occurs if the form is valid.
"""
form_valid = isinstance(response, HttpResponseRed... | [
"def",
"handle_save",
"(",
"self",
",",
"request",
",",
"response",
")",
":",
"form_valid",
"=",
"isinstance",
"(",
"response",
",",
"HttpResponseRedirect",
")",
"if",
"request",
".",
"POST",
".",
"get",
"(",
"\"_save\"",
")",
"and",
"form_valid",
":",
"re... | Handles redirect back to the dashboard when save is clicked
(eg not save and continue editing), by checking for a redirect
response, which only occurs if the form is valid. | [
"Handles",
"redirect",
"back",
"to",
"the",
"dashboard",
"when",
"save",
"is",
"clicked",
"(",
"eg",
"not",
"save",
"and",
"continue",
"editing",
")",
"by",
"checking",
"for",
"a",
"redirect",
"response",
"which",
"only",
"occurs",
"if",
"the",
"form",
"is... | train | https://github.com/RacingTadpole/django-singleton-admin/blob/0a81454be11fdcbaf95ca5018667a8dff3f45bf7/django_singleton_admin/admin.py#L33-L42 |
RacingTadpole/django-singleton-admin | django_singleton_admin/admin.py | SingletonAdmin.add_view | def add_view(self, *args, **kwargs):
"""
Redirect to the change view if the singleton instance exists.
"""
try:
singleton = self.model.objects.get()
except (self.model.DoesNotExist, self.model.MultipleObjectsReturned):
kwargs.setdefault("extra_context", {}... | python | def add_view(self, *args, **kwargs):
"""
Redirect to the change view if the singleton instance exists.
"""
try:
singleton = self.model.objects.get()
except (self.model.DoesNotExist, self.model.MultipleObjectsReturned):
kwargs.setdefault("extra_context", {}... | [
"def",
"add_view",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"singleton",
"=",
"self",
".",
"model",
".",
"objects",
".",
"get",
"(",
")",
"except",
"(",
"self",
".",
"model",
".",
"DoesNotExist",
",",
"self",
... | Redirect to the change view if the singleton instance exists. | [
"Redirect",
"to",
"the",
"change",
"view",
"if",
"the",
"singleton",
"instance",
"exists",
"."
] | train | https://github.com/RacingTadpole/django-singleton-admin/blob/0a81454be11fdcbaf95ca5018667a8dff3f45bf7/django_singleton_admin/admin.py#L44-L55 |
RacingTadpole/django-singleton-admin | django_singleton_admin/admin.py | SingletonAdmin.changelist_view | def changelist_view(self, *args, **kwargs):
"""
Redirect to the add view if no records exist or the change
view if the singleton instance exists.
"""
try:
singleton = self.model.objects.get()
except self.model.MultipleObjectsReturned:
return super(... | python | def changelist_view(self, *args, **kwargs):
"""
Redirect to the add view if no records exist or the change
view if the singleton instance exists.
"""
try:
singleton = self.model.objects.get()
except self.model.MultipleObjectsReturned:
return super(... | [
"def",
"changelist_view",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"singleton",
"=",
"self",
".",
"model",
".",
"objects",
".",
"get",
"(",
")",
"except",
"self",
".",
"model",
".",
"MultipleObjectsReturned",
":",
... | Redirect to the add view if no records exist or the change
view if the singleton instance exists. | [
"Redirect",
"to",
"the",
"add",
"view",
"if",
"no",
"records",
"exist",
"or",
"the",
"change",
"view",
"if",
"the",
"singleton",
"instance",
"exists",
"."
] | train | https://github.com/RacingTadpole/django-singleton-admin/blob/0a81454be11fdcbaf95ca5018667a8dff3f45bf7/django_singleton_admin/admin.py#L57-L68 |
RacingTadpole/django-singleton-admin | django_singleton_admin/admin.py | SingletonAdmin.change_view | def change_view(self, *args, **kwargs):
"""
If only the singleton instance exists, pass ``True`` for
``singleton`` into the template which will use CSS to hide
the "save and add another" button.
"""
kwargs.setdefault("extra_context", {})
kwargs["extra_context"]["s... | python | def change_view(self, *args, **kwargs):
"""
If only the singleton instance exists, pass ``True`` for
``singleton`` into the template which will use CSS to hide
the "save and add another" button.
"""
kwargs.setdefault("extra_context", {})
kwargs["extra_context"]["s... | [
"def",
"change_view",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
".",
"setdefault",
"(",
"\"extra_context\"",
",",
"{",
"}",
")",
"kwargs",
"[",
"\"extra_context\"",
"]",
"[",
"\"singleton\"",
"]",
"=",
"self",
".",
"mo... | If only the singleton instance exists, pass ``True`` for
``singleton`` into the template which will use CSS to hide
the "save and add another" button. | [
"If",
"only",
"the",
"singleton",
"instance",
"exists",
"pass",
"True",
"for",
"singleton",
"into",
"the",
"template",
"which",
"will",
"use",
"CSS",
"to",
"hide",
"the",
"save",
"and",
"add",
"another",
"button",
"."
] | train | https://github.com/RacingTadpole/django-singleton-admin/blob/0a81454be11fdcbaf95ca5018667a8dff3f45bf7/django_singleton_admin/admin.py#L70-L79 |
OTL/jps | jps/tools.py | pub | def pub(topic_name, json_msg, repeat_rate=None, host=jps.env.get_master_host(), pub_port=jps.DEFAULT_PUB_PORT):
'''publishes the data to the topic
:param topic_name: name of the topic
:param json_msg: data to be published
:param repeat_rate: if None, publishes once. if not None, it is used as [Hz].
... | python | def pub(topic_name, json_msg, repeat_rate=None, host=jps.env.get_master_host(), pub_port=jps.DEFAULT_PUB_PORT):
'''publishes the data to the topic
:param topic_name: name of the topic
:param json_msg: data to be published
:param repeat_rate: if None, publishes once. if not None, it is used as [Hz].
... | [
"def",
"pub",
"(",
"topic_name",
",",
"json_msg",
",",
"repeat_rate",
"=",
"None",
",",
"host",
"=",
"jps",
".",
"env",
".",
"get_master_host",
"(",
")",
",",
"pub_port",
"=",
"jps",
".",
"DEFAULT_PUB_PORT",
")",
":",
"pub",
"=",
"jps",
".",
"Publisher... | publishes the data to the topic
:param topic_name: name of the topic
:param json_msg: data to be published
:param repeat_rate: if None, publishes once. if not None, it is used as [Hz]. | [
"publishes",
"the",
"data",
"to",
"the",
"topic"
] | train | https://github.com/OTL/jps/blob/2c5a438d59611fffca6853072c822ef22665ed87/jps/tools.py#L11-L28 |
OTL/jps | jps/tools.py | echo | def echo(topic_name, num_print=None, out=sys.stdout, host=jps.env.get_master_host(), sub_port=jps.DEFAULT_SUB_PORT):
'''print the data for the given topic forever
'''
class PrintWithCount(object):
def __init__(self, out):
self._printed = 0
self._out = out
def print_... | python | def echo(topic_name, num_print=None, out=sys.stdout, host=jps.env.get_master_host(), sub_port=jps.DEFAULT_SUB_PORT):
'''print the data for the given topic forever
'''
class PrintWithCount(object):
def __init__(self, out):
self._printed = 0
self._out = out
def print_... | [
"def",
"echo",
"(",
"topic_name",
",",
"num_print",
"=",
"None",
",",
"out",
"=",
"sys",
".",
"stdout",
",",
"host",
"=",
"jps",
".",
"env",
".",
"get_master_host",
"(",
")",
",",
"sub_port",
"=",
"jps",
".",
"DEFAULT_SUB_PORT",
")",
":",
"class",
"P... | print the data for the given topic forever | [
"print",
"the",
"data",
"for",
"the",
"given",
"topic",
"forever"
] | train | https://github.com/OTL/jps/blob/2c5a438d59611fffca6853072c822ef22665ed87/jps/tools.py#L31-L55 |
OTL/jps | jps/tools.py | show_list | def show_list(timeout_in_sec, out=sys.stdout, host=jps.env.get_master_host(), sub_port=jps.DEFAULT_SUB_PORT):
'''get the name list of the topics, and print it
'''
class TopicNameStore(object):
def __init__(self):
self._topic_names = set()
def callback(self, msg, topic):
... | python | def show_list(timeout_in_sec, out=sys.stdout, host=jps.env.get_master_host(), sub_port=jps.DEFAULT_SUB_PORT):
'''get the name list of the topics, and print it
'''
class TopicNameStore(object):
def __init__(self):
self._topic_names = set()
def callback(self, msg, topic):
... | [
"def",
"show_list",
"(",
"timeout_in_sec",
",",
"out",
"=",
"sys",
".",
"stdout",
",",
"host",
"=",
"jps",
".",
"env",
".",
"get_master_host",
"(",
")",
",",
"sub_port",
"=",
"jps",
".",
"DEFAULT_SUB_PORT",
")",
":",
"class",
"TopicNameStore",
"(",
"obje... | get the name list of the topics, and print it | [
"get",
"the",
"name",
"list",
"of",
"the",
"topics",
"and",
"print",
"it"
] | train | https://github.com/OTL/jps/blob/2c5a438d59611fffca6853072c822ef22665ed87/jps/tools.py#L58-L81 |
OTL/jps | jps/tools.py | record | def record(file_path, topic_names=[], host=jps.env.get_master_host(), sub_port=jps.DEFAULT_SUB_PORT):
'''record the topic data to the file
'''
class TopicRecorder(object):
def __init__(self, file_path, topic_names):
self._topic_names = topic_names
self._file_path = file_path... | python | def record(file_path, topic_names=[], host=jps.env.get_master_host(), sub_port=jps.DEFAULT_SUB_PORT):
'''record the topic data to the file
'''
class TopicRecorder(object):
def __init__(self, file_path, topic_names):
self._topic_names = topic_names
self._file_path = file_path... | [
"def",
"record",
"(",
"file_path",
",",
"topic_names",
"=",
"[",
"]",
",",
"host",
"=",
"jps",
".",
"env",
".",
"get_master_host",
"(",
")",
",",
"sub_port",
"=",
"jps",
".",
"DEFAULT_SUB_PORT",
")",
":",
"class",
"TopicRecorder",
"(",
"object",
")",
"... | record the topic data to the file | [
"record",
"the",
"topic",
"data",
"to",
"the",
"file"
] | train | https://github.com/OTL/jps/blob/2c5a438d59611fffca6853072c822ef22665ed87/jps/tools.py#L84-L127 |
OTL/jps | jps/tools.py | play | def play(file_path, host=jps.env.get_master_host(), pub_port=jps.DEFAULT_PUB_PORT):
'''replay the recorded data by record()
'''
pub = jps.Publisher('*', host=host, pub_port=pub_port)
time.sleep(0.2)
last_time = None
print('start publishing file {}'.format(file_path))
with open(file_path, 'r'... | python | def play(file_path, host=jps.env.get_master_host(), pub_port=jps.DEFAULT_PUB_PORT):
'''replay the recorded data by record()
'''
pub = jps.Publisher('*', host=host, pub_port=pub_port)
time.sleep(0.2)
last_time = None
print('start publishing file {}'.format(file_path))
with open(file_path, 'r'... | [
"def",
"play",
"(",
"file_path",
",",
"host",
"=",
"jps",
".",
"env",
".",
"get_master_host",
"(",
")",
",",
"pub_port",
"=",
"jps",
".",
"DEFAULT_PUB_PORT",
")",
":",
"pub",
"=",
"jps",
".",
"Publisher",
"(",
"'*'",
",",
"host",
"=",
"host",
",",
... | replay the recorded data by record() | [
"replay",
"the",
"recorded",
"data",
"by",
"record",
"()"
] | train | https://github.com/OTL/jps/blob/2c5a438d59611fffca6853072c822ef22665ed87/jps/tools.py#L130-L149 |
OTL/jps | jps/tools.py | topic_command | def topic_command():
'''command line tool for jps
'''
parser = argparse.ArgumentParser(description='json pub/sub tool')
pub_common_parser = jps.ArgumentParser(subscriber=False, add_help=False)
sub_common_parser = jps.ArgumentParser(publisher=False, add_help=False)
command_parsers = parser.add_su... | python | def topic_command():
'''command line tool for jps
'''
parser = argparse.ArgumentParser(description='json pub/sub tool')
pub_common_parser = jps.ArgumentParser(subscriber=False, add_help=False)
sub_common_parser = jps.ArgumentParser(publisher=False, add_help=False)
command_parsers = parser.add_su... | [
"def",
"topic_command",
"(",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"'json pub/sub tool'",
")",
"pub_common_parser",
"=",
"jps",
".",
"ArgumentParser",
"(",
"subscriber",
"=",
"False",
",",
"add_help",
"=",
"False",
... | command line tool for jps | [
"command",
"line",
"tool",
"for",
"jps"
] | train | https://github.com/OTL/jps/blob/2c5a438d59611fffca6853072c822ef22665ed87/jps/tools.py#L152-L208 |
ilblackdragon/django-misc | misc/utils.py | str_to_class | def str_to_class(class_name):
"""
Returns a class based on class name
"""
mod_str, cls_str = class_name.rsplit('.', 1)
mod = __import__(mod_str, globals(), locals(), [''])
cls = getattr(mod, cls_str)
return cls | python | def str_to_class(class_name):
"""
Returns a class based on class name
"""
mod_str, cls_str = class_name.rsplit('.', 1)
mod = __import__(mod_str, globals(), locals(), [''])
cls = getattr(mod, cls_str)
return cls | [
"def",
"str_to_class",
"(",
"class_name",
")",
":",
"mod_str",
",",
"cls_str",
"=",
"class_name",
".",
"rsplit",
"(",
"'.'",
",",
"1",
")",
"mod",
"=",
"__import__",
"(",
"mod_str",
",",
"globals",
"(",
")",
",",
"locals",
"(",
")",
",",
"[",
"''",
... | Returns a class based on class name | [
"Returns",
"a",
"class",
"based",
"on",
"class",
"name"
] | train | https://github.com/ilblackdragon/django-misc/blob/0accd2dc97de656a1c9e275be81e817f78a2eb9d/misc/utils.py#L44-L51 |
ilblackdragon/django-misc | misc/utils.py | get_hierarchy_uploader | def get_hierarchy_uploader(root):
"""
Returns uploader, that uses get_hierarch_path to store files
"""
# Workaround to avoid Django 1.7 makemigrations wierd behaviour:
# More details: https://code.djangoproject.com/ticket/22436
import sys
if len(sys.argv) > 1 and sys.argv[1] in ('makemigrati... | python | def get_hierarchy_uploader(root):
"""
Returns uploader, that uses get_hierarch_path to store files
"""
# Workaround to avoid Django 1.7 makemigrations wierd behaviour:
# More details: https://code.djangoproject.com/ticket/22436
import sys
if len(sys.argv) > 1 and sys.argv[1] in ('makemigrati... | [
"def",
"get_hierarchy_uploader",
"(",
"root",
")",
":",
"# Workaround to avoid Django 1.7 makemigrations wierd behaviour:",
"# More details: https://code.djangoproject.com/ticket/22436",
"import",
"sys",
"if",
"len",
"(",
"sys",
".",
"argv",
")",
">",
"1",
"and",
"sys",
"."... | Returns uploader, that uses get_hierarch_path to store files | [
"Returns",
"uploader",
"that",
"uses",
"get_hierarch_path",
"to",
"store",
"files"
] | train | https://github.com/ilblackdragon/django-misc/blob/0accd2dc97de656a1c9e275be81e817f78a2eb9d/misc/utils.py#L75-L90 |
jaraco/jaraco.packaging | jaraco/packaging/sphinx.py | load_config_from_setup | def load_config_from_setup(app):
"""
Replace values in app.config from package metadata
"""
# for now, assume project root is one level up
root = os.path.join(app.confdir, '..')
setup_script = os.path.join(root, 'setup.py')
fields = ['--name', '--version', '--url', '--author']
dist_info_... | python | def load_config_from_setup(app):
"""
Replace values in app.config from package metadata
"""
# for now, assume project root is one level up
root = os.path.join(app.confdir, '..')
setup_script = os.path.join(root, 'setup.py')
fields = ['--name', '--version', '--url', '--author']
dist_info_... | [
"def",
"load_config_from_setup",
"(",
"app",
")",
":",
"# for now, assume project root is one level up",
"root",
"=",
"os",
".",
"path",
".",
"join",
"(",
"app",
".",
"confdir",
",",
"'..'",
")",
"setup_script",
"=",
"os",
".",
"path",
".",
"join",
"(",
"roo... | Replace values in app.config from package metadata | [
"Replace",
"values",
"in",
"app",
".",
"config",
"from",
"package",
"metadata"
] | train | https://github.com/jaraco/jaraco.packaging/blob/c84fd1282b222bc262a2bab7a2e668c947472f46/jaraco/packaging/sphinx.py#L18-L37 |
jrjparks/django-rest-framework-nested | rest_framework_nested/serializers.py | NestedHyperlinkedModelSerializer.build_url_field | def build_url_field(self, field_name, model_class):
"""
Create a field representing the object's own URL.
"""
field_class = self.serializer_url_field
field_kwargs = rest_framework.serializers.get_url_kwargs(model_class)
field_kwargs.update({"parent_lookup_field": self.get... | python | def build_url_field(self, field_name, model_class):
"""
Create a field representing the object's own URL.
"""
field_class = self.serializer_url_field
field_kwargs = rest_framework.serializers.get_url_kwargs(model_class)
field_kwargs.update({"parent_lookup_field": self.get... | [
"def",
"build_url_field",
"(",
"self",
",",
"field_name",
",",
"model_class",
")",
":",
"field_class",
"=",
"self",
".",
"serializer_url_field",
"field_kwargs",
"=",
"rest_framework",
".",
"serializers",
".",
"get_url_kwargs",
"(",
"model_class",
")",
"field_kwargs"... | Create a field representing the object's own URL. | [
"Create",
"a",
"field",
"representing",
"the",
"object",
"s",
"own",
"URL",
"."
] | train | https://github.com/jrjparks/django-rest-framework-nested/blob/8ab797281e11507b8142f342ad73ca48ef82565c/rest_framework_nested/serializers.py#L33-L40 |
jrjparks/django-rest-framework-nested | rest_framework_nested/serializers.py | NestedHyperlinkedModelSerializer.get_parent_lookup_field | def get_parent_lookup_field(self):
"""
Return tha parent_lookup_field for the NestedHyperlinkedModelSerializer.
If `parent_lookup_field` of `parent_model` is not defined lookup ForeignKey field of model.
:return: parent_lookup_field
"""
if hasattr(self.Meta, "parent_looku... | python | def get_parent_lookup_field(self):
"""
Return tha parent_lookup_field for the NestedHyperlinkedModelSerializer.
If `parent_lookup_field` of `parent_model` is not defined lookup ForeignKey field of model.
:return: parent_lookup_field
"""
if hasattr(self.Meta, "parent_looku... | [
"def",
"get_parent_lookup_field",
"(",
"self",
")",
":",
"if",
"hasattr",
"(",
"self",
".",
"Meta",
",",
"\"parent_lookup_field\"",
")",
":",
"return",
"getattr",
"(",
"self",
".",
"Meta",
",",
"\"parent_lookup_field\"",
")",
"elif",
"hasattr",
"(",
"self",
... | Return tha parent_lookup_field for the NestedHyperlinkedModelSerializer.
If `parent_lookup_field` of `parent_model` is not defined lookup ForeignKey field of model.
:return: parent_lookup_field | [
"Return",
"tha",
"parent_lookup_field",
"for",
"the",
"NestedHyperlinkedModelSerializer",
".",
"If",
"parent_lookup_field",
"of",
"parent_model",
"is",
"not",
"defined",
"lookup",
"ForeignKey",
"field",
"of",
"model",
".",
":",
"return",
":",
"parent_lookup_field"
] | train | https://github.com/jrjparks/django-rest-framework-nested/blob/8ab797281e11507b8142f342ad73ca48ef82565c/rest_framework_nested/serializers.py#L42-L64 |
jrjparks/django-rest-framework-nested | rest_framework_nested/relations.py | NestedHyperlinkedRelatedField.get_object | def get_object(self, view_name, view_args, view_kwargs):
"""
Return the object corresponding to a matched URL.
Takes the matched URL conf arguments, and should return an
object instance, or raise an `ObjectDoesNotExist` exception.
"""
lookup_value = view_kwargs.get(self.... | python | def get_object(self, view_name, view_args, view_kwargs):
"""
Return the object corresponding to a matched URL.
Takes the matched URL conf arguments, and should return an
object instance, or raise an `ObjectDoesNotExist` exception.
"""
lookup_value = view_kwargs.get(self.... | [
"def",
"get_object",
"(",
"self",
",",
"view_name",
",",
"view_args",
",",
"view_kwargs",
")",
":",
"lookup_value",
"=",
"view_kwargs",
".",
"get",
"(",
"self",
".",
"lookup_url_kwarg",
")",
"parent_lookup_value",
"=",
"view_kwargs",
".",
"get",
"(",
"self",
... | Return the object corresponding to a matched URL.
Takes the matched URL conf arguments, and should return an
object instance, or raise an `ObjectDoesNotExist` exception. | [
"Return",
"the",
"object",
"corresponding",
"to",
"a",
"matched",
"URL",
"."
] | train | https://github.com/jrjparks/django-rest-framework-nested/blob/8ab797281e11507b8142f342ad73ca48ef82565c/rest_framework_nested/relations.py#L15-L30 |
jrjparks/django-rest-framework-nested | rest_framework_nested/relations.py | NestedHyperlinkedRelatedField.get_url | def get_url(self, obj, view_name, request, format):
"""
Given an object, return the URL that hyperlinks to the object.
May raise a `NoReverseMatch` if the `view_name` and `lookup_field`
attributes are not configured to correctly match the URL conf.
"""
# Unsaved objects ... | python | def get_url(self, obj, view_name, request, format):
"""
Given an object, return the URL that hyperlinks to the object.
May raise a `NoReverseMatch` if the `view_name` and `lookup_field`
attributes are not configured to correctly match the URL conf.
"""
# Unsaved objects ... | [
"def",
"get_url",
"(",
"self",
",",
"obj",
",",
"view_name",
",",
"request",
",",
"format",
")",
":",
"# Unsaved objects will not yet have a valid URL.",
"if",
"obj",
".",
"pk",
"is",
"None",
":",
"return",
"None",
"lookup_value",
"=",
"getattr",
"(",
"obj",
... | Given an object, return the URL that hyperlinks to the object.
May raise a `NoReverseMatch` if the `view_name` and `lookup_field`
attributes are not configured to correctly match the URL conf. | [
"Given",
"an",
"object",
"return",
"the",
"URL",
"that",
"hyperlinks",
"to",
"the",
"object",
"."
] | train | https://github.com/jrjparks/django-rest-framework-nested/blob/8ab797281e11507b8142f342ad73ca48ef82565c/rest_framework_nested/relations.py#L32-L57 |
gregorymfoster/honeypot | honeypot/honeypot/www/models.py | HoneypotLogTable.create_table | def create_table(self, drop=False, with_test_data=False):
"""
Creates the honeypot_log table
"""
db = self.get_sql_hook(self.sql_conn_id)
table = self.table_name
if drop:
sql = "DROP TABLE IF EXISTS {table};".format(**locals())
logging.info("Execut... | python | def create_table(self, drop=False, with_test_data=False):
"""
Creates the honeypot_log table
"""
db = self.get_sql_hook(self.sql_conn_id)
table = self.table_name
if drop:
sql = "DROP TABLE IF EXISTS {table};".format(**locals())
logging.info("Execut... | [
"def",
"create_table",
"(",
"self",
",",
"drop",
"=",
"False",
",",
"with_test_data",
"=",
"False",
")",
":",
"db",
"=",
"self",
".",
"get_sql_hook",
"(",
"self",
".",
"sql_conn_id",
")",
"table",
"=",
"self",
".",
"table_name",
"if",
"drop",
":",
"sql... | Creates the honeypot_log table | [
"Creates",
"the",
"honeypot_log",
"table"
] | train | https://github.com/gregorymfoster/honeypot/blob/e4c2528551ac02e14631c47d93050769866c5429/honeypot/honeypot/www/models.py#L142-L169 |
wolfhong/formic | formic/treewalk.py | TreeWalk.list_to_tree | def list_to_tree(cls, files):
"""Converts a list of filenames into a directory tree structure."""
def attach(branch, trunk):
"""Insert a branch of directories on its trunk."""
parts = branch.split('/', 1)
if len(parts) == 1: # branch is a file
trunk[... | python | def list_to_tree(cls, files):
"""Converts a list of filenames into a directory tree structure."""
def attach(branch, trunk):
"""Insert a branch of directories on its trunk."""
parts = branch.split('/', 1)
if len(parts) == 1: # branch is a file
trunk[... | [
"def",
"list_to_tree",
"(",
"cls",
",",
"files",
")",
":",
"def",
"attach",
"(",
"branch",
",",
"trunk",
")",
":",
"\"\"\"Insert a branch of directories on its trunk.\"\"\"",
"parts",
"=",
"branch",
".",
"split",
"(",
"'/'",
",",
"1",
")",
"if",
"len",
"(",
... | Converts a list of filenames into a directory tree structure. | [
"Converts",
"a",
"list",
"of",
"filenames",
"into",
"a",
"directory",
"tree",
"structure",
"."
] | train | https://github.com/wolfhong/formic/blob/0d81eb88dcbb6fa705194fc6ccf2993f4abbaa76/formic/treewalk.py#L14-L31 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.