repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
shendo/websnort | websnort/ids/snort.py | parse_version | def parse_version(output):
"""
Parses the supplied output and returns the version string.
:param output: A string containing the output of running snort.
:returns: Version string for the version of snort run. None if not found.
"""
for x in output.splitlines():
match = VERSION_PATTERN.m... | python | def parse_version(output):
"""
Parses the supplied output and returns the version string.
:param output: A string containing the output of running snort.
:returns: Version string for the version of snort run. None if not found.
"""
for x in output.splitlines():
match = VERSION_PATTERN.m... | [
"def",
"parse_version",
"(",
"output",
")",
":",
"for",
"x",
"in",
"output",
".",
"splitlines",
"(",
")",
":",
"match",
"=",
"VERSION_PATTERN",
".",
"match",
"(",
"x",
")",
"if",
"match",
":",
"return",
"match",
".",
"group",
"(",
"'version'",
")",
"... | Parses the supplied output and returns the version string.
:param output: A string containing the output of running snort.
:returns: Version string for the version of snort run. None if not found. | [
"Parses",
"the",
"supplied",
"output",
"and",
"returns",
"the",
"version",
"string",
"."
] | 19495e8834a111e889ba28efad8cd90cf55eb661 | https://github.com/shendo/websnort/blob/19495e8834a111e889ba28efad8cd90cf55eb661/websnort/ids/snort.py#L80-L91 | train | 61,000 |
shendo/websnort | websnort/ids/snort.py | parse_alert | def parse_alert(output):
"""
Parses the supplied output and yields any alerts.
Example alert format:
01/28/14-22:26:04.885446 [**] [1:1917:11] INDICATOR-SCAN UPnP service discover attempt [**] [Classification: Detection of a Network Scan] [Priority: 3] {UDP} 10.1.1.132:58650 -> 239.255.255.250:1900
... | python | def parse_alert(output):
"""
Parses the supplied output and yields any alerts.
Example alert format:
01/28/14-22:26:04.885446 [**] [1:1917:11] INDICATOR-SCAN UPnP service discover attempt [**] [Classification: Detection of a Network Scan] [Priority: 3] {UDP} 10.1.1.132:58650 -> 239.255.255.250:1900
... | [
"def",
"parse_alert",
"(",
"output",
")",
":",
"for",
"x",
"in",
"output",
".",
"splitlines",
"(",
")",
":",
"match",
"=",
"ALERT_PATTERN",
".",
"match",
"(",
"x",
")",
"if",
"match",
":",
"rec",
"=",
"{",
"'timestamp'",
":",
"datetime",
".",
"strpti... | Parses the supplied output and yields any alerts.
Example alert format:
01/28/14-22:26:04.885446 [**] [1:1917:11] INDICATOR-SCAN UPnP service discover attempt [**] [Classification: Detection of a Network Scan] [Priority: 3] {UDP} 10.1.1.132:58650 -> 239.255.255.250:1900
:param output: A string containing... | [
"Parses",
"the",
"supplied",
"output",
"and",
"yields",
"any",
"alerts",
"."
] | 19495e8834a111e889ba28efad8cd90cf55eb661 | https://github.com/shendo/websnort/blob/19495e8834a111e889ba28efad8cd90cf55eb661/websnort/ids/snort.py#L93-L118 | train | 61,001 |
shendo/websnort | websnort/ids/snort.py | Snort.run | def run(self, pcap):
"""
Runs snort against the supplied pcap.
:param pcap: Filepath to pcap file to scan
:returns: tuple of version, list of alerts
"""
proc = Popen(self._snort_cmd(pcap), stdout=PIPE,
stderr=PIPE, universal_newlines=True)
st... | python | def run(self, pcap):
"""
Runs snort against the supplied pcap.
:param pcap: Filepath to pcap file to scan
:returns: tuple of version, list of alerts
"""
proc = Popen(self._snort_cmd(pcap), stdout=PIPE,
stderr=PIPE, universal_newlines=True)
st... | [
"def",
"run",
"(",
"self",
",",
"pcap",
")",
":",
"proc",
"=",
"Popen",
"(",
"self",
".",
"_snort_cmd",
"(",
"pcap",
")",
",",
"stdout",
"=",
"PIPE",
",",
"stderr",
"=",
"PIPE",
",",
"universal_newlines",
"=",
"True",
")",
"stdout",
",",
"stderr",
... | Runs snort against the supplied pcap.
:param pcap: Filepath to pcap file to scan
:returns: tuple of version, list of alerts | [
"Runs",
"snort",
"against",
"the",
"supplied",
"pcap",
"."
] | 19495e8834a111e889ba28efad8cd90cf55eb661 | https://github.com/shendo/websnort/blob/19495e8834a111e889ba28efad8cd90cf55eb661/websnort/ids/snort.py#L63-L78 | train | 61,002 |
shendo/websnort | websnort/ids/suricata.py | Suricata.run | def run(self, pcap):
"""
Runs suricata against the supplied pcap.
:param pcap: Filepath to pcap file to scan
:returns: tuple of version, list of alerts
"""
tmpdir = None
try:
tmpdir = tempfile.mkdtemp(prefix='tmpsuri')
proc = Popen(self._s... | python | def run(self, pcap):
"""
Runs suricata against the supplied pcap.
:param pcap: Filepath to pcap file to scan
:returns: tuple of version, list of alerts
"""
tmpdir = None
try:
tmpdir = tempfile.mkdtemp(prefix='tmpsuri')
proc = Popen(self._s... | [
"def",
"run",
"(",
"self",
",",
"pcap",
")",
":",
"tmpdir",
"=",
"None",
"try",
":",
"tmpdir",
"=",
"tempfile",
".",
"mkdtemp",
"(",
"prefix",
"=",
"'tmpsuri'",
")",
"proc",
"=",
"Popen",
"(",
"self",
".",
"_suri_cmd",
"(",
"pcap",
",",
"tmpdir",
"... | Runs suricata against the supplied pcap.
:param pcap: Filepath to pcap file to scan
:returns: tuple of version, list of alerts | [
"Runs",
"suricata",
"against",
"the",
"supplied",
"pcap",
"."
] | 19495e8834a111e889ba28efad8cd90cf55eb661 | https://github.com/shendo/websnort/blob/19495e8834a111e889ba28efad8cd90cf55eb661/websnort/ids/suricata.py#L66-L88 | train | 61,003 |
shendo/websnort | websnort/web.py | analyse_pcap | def analyse_pcap(infile, filename):
"""
Run IDS across the supplied file.
:param infile: File like object containing pcap data.
:param filename: Filename of the submitted file.
:returns: Dictionary of analysis results.
"""
tmp = tempfile.NamedTemporaryFile(suffix=".pcap", delete=False)
... | python | def analyse_pcap(infile, filename):
"""
Run IDS across the supplied file.
:param infile: File like object containing pcap data.
:param filename: Filename of the submitted file.
:returns: Dictionary of analysis results.
"""
tmp = tempfile.NamedTemporaryFile(suffix=".pcap", delete=False)
... | [
"def",
"analyse_pcap",
"(",
"infile",
",",
"filename",
")",
":",
"tmp",
"=",
"tempfile",
".",
"NamedTemporaryFile",
"(",
"suffix",
"=",
"\".pcap\"",
",",
"delete",
"=",
"False",
")",
"m",
"=",
"hashlib",
".",
"md5",
"(",
")",
"results",
"=",
"{",
"'fil... | Run IDS across the supplied file.
:param infile: File like object containing pcap data.
:param filename: Filename of the submitted file.
:returns: Dictionary of analysis results. | [
"Run",
"IDS",
"across",
"the",
"supplied",
"file",
"."
] | 19495e8834a111e889ba28efad8cd90cf55eb661 | https://github.com/shendo/websnort/blob/19495e8834a111e889ba28efad8cd90cf55eb661/websnort/web.py#L59-L89 | train | 61,004 |
shendo/websnort | websnort/web.py | submit_and_render | def submit_and_render():
"""
Blocking POST handler for file submission.
Runs snort on supplied file and returns results as rendered html.
"""
data = request.files.file
template = env.get_template("results.html")
if not data:
pass
results = analyse_pcap(data.file, data.filename)
... | python | def submit_and_render():
"""
Blocking POST handler for file submission.
Runs snort on supplied file and returns results as rendered html.
"""
data = request.files.file
template = env.get_template("results.html")
if not data:
pass
results = analyse_pcap(data.file, data.filename)
... | [
"def",
"submit_and_render",
"(",
")",
":",
"data",
"=",
"request",
".",
"files",
".",
"file",
"template",
"=",
"env",
".",
"get_template",
"(",
"\"results.html\"",
")",
"if",
"not",
"data",
":",
"pass",
"results",
"=",
"analyse_pcap",
"(",
"data",
".",
"... | Blocking POST handler for file submission.
Runs snort on supplied file and returns results as rendered html. | [
"Blocking",
"POST",
"handler",
"for",
"file",
"submission",
".",
"Runs",
"snort",
"on",
"supplied",
"file",
"and",
"returns",
"results",
"as",
"rendered",
"html",
"."
] | 19495e8834a111e889ba28efad8cd90cf55eb661 | https://github.com/shendo/websnort/blob/19495e8834a111e889ba28efad8cd90cf55eb661/websnort/web.py#L92-L103 | train | 61,005 |
shendo/websnort | websnort/web.py | api_submit | def api_submit():
"""
Blocking POST handler for file submission.
Runs snort on supplied file and returns results as json text.
"""
data = request.files.file
response.content_type = 'application/json'
if not data or not hasattr(data, 'file'):
return json.dumps({"status": "Failed", "st... | python | def api_submit():
"""
Blocking POST handler for file submission.
Runs snort on supplied file and returns results as json text.
"""
data = request.files.file
response.content_type = 'application/json'
if not data or not hasattr(data, 'file'):
return json.dumps({"status": "Failed", "st... | [
"def",
"api_submit",
"(",
")",
":",
"data",
"=",
"request",
".",
"files",
".",
"file",
"response",
".",
"content_type",
"=",
"'application/json'",
"if",
"not",
"data",
"or",
"not",
"hasattr",
"(",
"data",
",",
"'file'",
")",
":",
"return",
"json",
".",
... | Blocking POST handler for file submission.
Runs snort on supplied file and returns results as json text. | [
"Blocking",
"POST",
"handler",
"for",
"file",
"submission",
".",
"Runs",
"snort",
"on",
"supplied",
"file",
"and",
"returns",
"results",
"as",
"json",
"text",
"."
] | 19495e8834a111e889ba28efad8cd90cf55eb661 | https://github.com/shendo/websnort/blob/19495e8834a111e889ba28efad8cd90cf55eb661/websnort/web.py#L106-L115 | train | 61,006 |
shendo/websnort | websnort/web.py | main | def main():
"""
Main entrypoint for command-line webserver.
"""
parser = argparse.ArgumentParser()
parser.add_argument("-H", "--host", help="Web server Host address to bind to",
default="0.0.0.0", action="store", required=False)
parser.add_argument("-p", "--port", help="W... | python | def main():
"""
Main entrypoint for command-line webserver.
"""
parser = argparse.ArgumentParser()
parser.add_argument("-H", "--host", help="Web server Host address to bind to",
default="0.0.0.0", action="store", required=False)
parser.add_argument("-p", "--port", help="W... | [
"def",
"main",
"(",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
")",
"parser",
".",
"add_argument",
"(",
"\"-H\"",
",",
"\"--host\"",
",",
"help",
"=",
"\"Web server Host address to bind to\"",
",",
"default",
"=",
"\"0.0.0.0\"",
",",
"act... | Main entrypoint for command-line webserver. | [
"Main",
"entrypoint",
"for",
"command",
"-",
"line",
"webserver",
"."
] | 19495e8834a111e889ba28efad8cd90cf55eb661 | https://github.com/shendo/websnort/blob/19495e8834a111e889ba28efad8cd90cf55eb661/websnort/web.py#L126-L138 | train | 61,007 |
shendo/websnort | websnort/runner.py | is_pcap | def is_pcap(pcap):
"""
Simple test for pcap magic bytes in supplied file.
:param pcap: File path to Pcap file to check
:returns: True if content is pcap (magic bytes present), otherwise False.
"""
with open(pcap, 'rb') as tmp:
header = tmp.read(4)
# check for both big/little end... | python | def is_pcap(pcap):
"""
Simple test for pcap magic bytes in supplied file.
:param pcap: File path to Pcap file to check
:returns: True if content is pcap (magic bytes present), otherwise False.
"""
with open(pcap, 'rb') as tmp:
header = tmp.read(4)
# check for both big/little end... | [
"def",
"is_pcap",
"(",
"pcap",
")",
":",
"with",
"open",
"(",
"pcap",
",",
"'rb'",
")",
"as",
"tmp",
":",
"header",
"=",
"tmp",
".",
"read",
"(",
"4",
")",
"# check for both big/little endian",
"if",
"header",
"==",
"b\"\\xa1\\xb2\\xc3\\xd4\"",
"or",
"head... | Simple test for pcap magic bytes in supplied file.
:param pcap: File path to Pcap file to check
:returns: True if content is pcap (magic bytes present), otherwise False. | [
"Simple",
"test",
"for",
"pcap",
"magic",
"bytes",
"in",
"supplied",
"file",
"."
] | 19495e8834a111e889ba28efad8cd90cf55eb661 | https://github.com/shendo/websnort/blob/19495e8834a111e889ba28efad8cd90cf55eb661/websnort/runner.py#L46-L59 | train | 61,008 |
shendo/websnort | websnort/runner.py | _run_ids | def _run_ids(runner, pcap):
"""
Runs the specified IDS runner.
:param runner: Runner instance to use
:param pcap: File path to pcap for analysis
:returns: dict of run metadata/alerts
"""
run = {'name': runner.conf.get('name'),
'module': runner.conf.get('module'),
'rule... | python | def _run_ids(runner, pcap):
"""
Runs the specified IDS runner.
:param runner: Runner instance to use
:param pcap: File path to pcap for analysis
:returns: dict of run metadata/alerts
"""
run = {'name': runner.conf.get('name'),
'module': runner.conf.get('module'),
'rule... | [
"def",
"_run_ids",
"(",
"runner",
",",
"pcap",
")",
":",
"run",
"=",
"{",
"'name'",
":",
"runner",
".",
"conf",
".",
"get",
"(",
"'name'",
")",
",",
"'module'",
":",
"runner",
".",
"conf",
".",
"get",
"(",
"'module'",
")",
",",
"'ruleset'",
":",
... | Runs the specified IDS runner.
:param runner: Runner instance to use
:param pcap: File path to pcap for analysis
:returns: dict of run metadata/alerts | [
"Runs",
"the",
"specified",
"IDS",
"runner",
"."
] | 19495e8834a111e889ba28efad8cd90cf55eb661 | https://github.com/shendo/websnort/blob/19495e8834a111e889ba28efad8cd90cf55eb661/websnort/runner.py#L61-L84 | train | 61,009 |
shendo/websnort | websnort/runner.py | run | def run(pcap):
"""
Runs all configured IDS instances against the supplied pcap.
:param pcap: File path to pcap file to analyse
:returns: Dict with details and results of run/s
"""
start = datetime.now()
errors = []
status = STATUS_FAILED
analyses = []
pool = ThreadPool(MAX_THREA... | python | def run(pcap):
"""
Runs all configured IDS instances against the supplied pcap.
:param pcap: File path to pcap file to analyse
:returns: Dict with details and results of run/s
"""
start = datetime.now()
errors = []
status = STATUS_FAILED
analyses = []
pool = ThreadPool(MAX_THREA... | [
"def",
"run",
"(",
"pcap",
")",
":",
"start",
"=",
"datetime",
".",
"now",
"(",
")",
"errors",
"=",
"[",
"]",
"status",
"=",
"STATUS_FAILED",
"analyses",
"=",
"[",
"]",
"pool",
"=",
"ThreadPool",
"(",
"MAX_THREADS",
")",
"try",
":",
"if",
"not",
"i... | Runs all configured IDS instances against the supplied pcap.
:param pcap: File path to pcap file to analyse
:returns: Dict with details and results of run/s | [
"Runs",
"all",
"configured",
"IDS",
"instances",
"against",
"the",
"supplied",
"pcap",
"."
] | 19495e8834a111e889ba28efad8cd90cf55eb661 | https://github.com/shendo/websnort/blob/19495e8834a111e889ba28efad8cd90cf55eb661/websnort/runner.py#L86-L126 | train | 61,010 |
gmcguire/django-db-pool | dbpool/db/backends/postgresql_psycopg2/base.py | _set_up_pool_config | def _set_up_pool_config(self):
'''
Helper to configure pool options during DatabaseWrapper initialization.
'''
self._max_conns = self.settings_dict['OPTIONS'].get('MAX_CONNS', pool_config_defaults['MAX_CONNS'])
self._min_conns = self.settings_dict['OPTIONS'].get('MIN_CONNS', self._max_conns)
... | python | def _set_up_pool_config(self):
'''
Helper to configure pool options during DatabaseWrapper initialization.
'''
self._max_conns = self.settings_dict['OPTIONS'].get('MAX_CONNS', pool_config_defaults['MAX_CONNS'])
self._min_conns = self.settings_dict['OPTIONS'].get('MIN_CONNS', self._max_conns)
... | [
"def",
"_set_up_pool_config",
"(",
"self",
")",
":",
"self",
".",
"_max_conns",
"=",
"self",
".",
"settings_dict",
"[",
"'OPTIONS'",
"]",
".",
"get",
"(",
"'MAX_CONNS'",
",",
"pool_config_defaults",
"[",
"'MAX_CONNS'",
"]",
")",
"self",
".",
"_min_conns",
"=... | Helper to configure pool options during DatabaseWrapper initialization. | [
"Helper",
"to",
"configure",
"pool",
"options",
"during",
"DatabaseWrapper",
"initialization",
"."
] | d4e0aa6a150fd7bd2024e079cd3b7147ea341e63 | https://github.com/gmcguire/django-db-pool/blob/d4e0aa6a150fd7bd2024e079cd3b7147ea341e63/dbpool/db/backends/postgresql_psycopg2/base.py#L85-L98 | train | 61,011 |
gmcguire/django-db-pool | dbpool/db/backends/postgresql_psycopg2/base.py | _create_connection_pool | def _create_connection_pool(self, conn_params):
'''
Helper to initialize the connection pool.
'''
connection_pools_lock.acquire()
try:
# One more read to prevent a read/write race condition (We do this
# here to avoid the overhead of locking each time we get a connection.)
if... | python | def _create_connection_pool(self, conn_params):
'''
Helper to initialize the connection pool.
'''
connection_pools_lock.acquire()
try:
# One more read to prevent a read/write race condition (We do this
# here to avoid the overhead of locking each time we get a connection.)
if... | [
"def",
"_create_connection_pool",
"(",
"self",
",",
"conn_params",
")",
":",
"connection_pools_lock",
".",
"acquire",
"(",
")",
"try",
":",
"# One more read to prevent a read/write race condition (We do this",
"# here to avoid the overhead of locking each time we get a connection.)",... | Helper to initialize the connection pool. | [
"Helper",
"to",
"initialize",
"the",
"connection",
"pool",
"."
] | d4e0aa6a150fd7bd2024e079cd3b7147ea341e63 | https://github.com/gmcguire/django-db-pool/blob/d4e0aa6a150fd7bd2024e079cd3b7147ea341e63/dbpool/db/backends/postgresql_psycopg2/base.py#L101-L122 | train | 61,012 |
gmcguire/django-db-pool | dbpool/db/backends/postgresql_psycopg2/base.py | PooledConnection.close | def close(self):
'''
Override to return the connection to the pool rather than closing it.
'''
if self._wrapped_connection and self._pool:
logger.debug("Returning connection %s to pool %s" % (self._wrapped_connection, self._pool))
self._pool.putconn(self._wrapped_... | python | def close(self):
'''
Override to return the connection to the pool rather than closing it.
'''
if self._wrapped_connection and self._pool:
logger.debug("Returning connection %s to pool %s" % (self._wrapped_connection, self._pool))
self._pool.putconn(self._wrapped_... | [
"def",
"close",
"(",
"self",
")",
":",
"if",
"self",
".",
"_wrapped_connection",
"and",
"self",
".",
"_pool",
":",
"logger",
".",
"debug",
"(",
"\"Returning connection %s to pool %s\"",
"%",
"(",
"self",
".",
"_wrapped_connection",
",",
"self",
".",
"_pool",
... | Override to return the connection to the pool rather than closing it. | [
"Override",
"to",
"return",
"the",
"connection",
"to",
"the",
"pool",
"rather",
"than",
"closing",
"it",
"."
] | d4e0aa6a150fd7bd2024e079cd3b7147ea341e63 | https://github.com/gmcguire/django-db-pool/blob/d4e0aa6a150fd7bd2024e079cd3b7147ea341e63/dbpool/db/backends/postgresql_psycopg2/base.py#L56-L63 | train | 61,013 |
oskyk/cashaddress | cashaddress/base58.py | b58encode_int | def b58encode_int(i, default_one=True):
'''Encode an integer using Base58'''
if not i and default_one:
return alphabet[0]
string = ""
while i:
i, idx = divmod(i, 58)
string = alphabet[idx] + string
return string | python | def b58encode_int(i, default_one=True):
'''Encode an integer using Base58'''
if not i and default_one:
return alphabet[0]
string = ""
while i:
i, idx = divmod(i, 58)
string = alphabet[idx] + string
return string | [
"def",
"b58encode_int",
"(",
"i",
",",
"default_one",
"=",
"True",
")",
":",
"if",
"not",
"i",
"and",
"default_one",
":",
"return",
"alphabet",
"[",
"0",
"]",
"string",
"=",
"\"\"",
"while",
"i",
":",
"i",
",",
"idx",
"=",
"divmod",
"(",
"i",
",",
... | Encode an integer using Base58 | [
"Encode",
"an",
"integer",
"using",
"Base58"
] | d65615368c6ca35190ff160140e721e6156ce0be | https://github.com/oskyk/cashaddress/blob/d65615368c6ca35190ff160140e721e6156ce0be/cashaddress/base58.py#L54-L62 | train | 61,014 |
prymitive/bootstrap-breadcrumbs | django_bootstrap_breadcrumbs/templatetags/django_bootstrap_breadcrumbs.py | breadcrumb_safe | def breadcrumb_safe(context, label, viewname, *args, **kwargs):
"""
Same as breadcrumb but label is not escaped.
"""
append_breadcrumb(context, _(label), viewname, args, kwargs)
return '' | python | def breadcrumb_safe(context, label, viewname, *args, **kwargs):
"""
Same as breadcrumb but label is not escaped.
"""
append_breadcrumb(context, _(label), viewname, args, kwargs)
return '' | [
"def",
"breadcrumb_safe",
"(",
"context",
",",
"label",
",",
"viewname",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"append_breadcrumb",
"(",
"context",
",",
"_",
"(",
"label",
")",
",",
"viewname",
",",
"args",
",",
"kwargs",
")",
"return",
... | Same as breadcrumb but label is not escaped. | [
"Same",
"as",
"breadcrumb",
"but",
"label",
"is",
"not",
"escaped",
"."
] | 14e7b911c70c96a5ce18512615cdb896efefa7e2 | https://github.com/prymitive/bootstrap-breadcrumbs/blob/14e7b911c70c96a5ce18512615cdb896efefa7e2/django_bootstrap_breadcrumbs/templatetags/django_bootstrap_breadcrumbs.py#L86-L91 | train | 61,015 |
prymitive/bootstrap-breadcrumbs | django_bootstrap_breadcrumbs/templatetags/django_bootstrap_breadcrumbs.py | breadcrumb_raw | def breadcrumb_raw(context, label, viewname, *args, **kwargs):
"""
Same as breadcrumb but label is not translated.
"""
append_breadcrumb(context, escape(label), viewname, args, kwargs)
return '' | python | def breadcrumb_raw(context, label, viewname, *args, **kwargs):
"""
Same as breadcrumb but label is not translated.
"""
append_breadcrumb(context, escape(label), viewname, args, kwargs)
return '' | [
"def",
"breadcrumb_raw",
"(",
"context",
",",
"label",
",",
"viewname",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"append_breadcrumb",
"(",
"context",
",",
"escape",
"(",
"label",
")",
",",
"viewname",
",",
"args",
",",
"kwargs",
")",
"retur... | Same as breadcrumb but label is not translated. | [
"Same",
"as",
"breadcrumb",
"but",
"label",
"is",
"not",
"translated",
"."
] | 14e7b911c70c96a5ce18512615cdb896efefa7e2 | https://github.com/prymitive/bootstrap-breadcrumbs/blob/14e7b911c70c96a5ce18512615cdb896efefa7e2/django_bootstrap_breadcrumbs/templatetags/django_bootstrap_breadcrumbs.py#L95-L100 | train | 61,016 |
prymitive/bootstrap-breadcrumbs | django_bootstrap_breadcrumbs/templatetags/django_bootstrap_breadcrumbs.py | breadcrumb_raw_safe | def breadcrumb_raw_safe(context, label, viewname, *args, **kwargs):
"""
Same as breadcrumb but label is not escaped and translated.
"""
append_breadcrumb(context, label, viewname, args, kwargs)
return '' | python | def breadcrumb_raw_safe(context, label, viewname, *args, **kwargs):
"""
Same as breadcrumb but label is not escaped and translated.
"""
append_breadcrumb(context, label, viewname, args, kwargs)
return '' | [
"def",
"breadcrumb_raw_safe",
"(",
"context",
",",
"label",
",",
"viewname",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"append_breadcrumb",
"(",
"context",
",",
"label",
",",
"viewname",
",",
"args",
",",
"kwargs",
")",
"return",
"''"
] | Same as breadcrumb but label is not escaped and translated. | [
"Same",
"as",
"breadcrumb",
"but",
"label",
"is",
"not",
"escaped",
"and",
"translated",
"."
] | 14e7b911c70c96a5ce18512615cdb896efefa7e2 | https://github.com/prymitive/bootstrap-breadcrumbs/blob/14e7b911c70c96a5ce18512615cdb896efefa7e2/django_bootstrap_breadcrumbs/templatetags/django_bootstrap_breadcrumbs.py#L104-L109 | train | 61,017 |
prymitive/bootstrap-breadcrumbs | django_bootstrap_breadcrumbs/templatetags/django_bootstrap_breadcrumbs.py | render_breadcrumbs | def render_breadcrumbs(context, *args):
"""
Render breadcrumbs html using bootstrap css classes.
"""
try:
template_path = args[0]
except IndexError:
template_path = getattr(settings, 'BREADCRUMBS_TEMPLATE',
'django_bootstrap_breadcrumbs/bootstrap2.htm... | python | def render_breadcrumbs(context, *args):
"""
Render breadcrumbs html using bootstrap css classes.
"""
try:
template_path = args[0]
except IndexError:
template_path = getattr(settings, 'BREADCRUMBS_TEMPLATE',
'django_bootstrap_breadcrumbs/bootstrap2.htm... | [
"def",
"render_breadcrumbs",
"(",
"context",
",",
"*",
"args",
")",
":",
"try",
":",
"template_path",
"=",
"args",
"[",
"0",
"]",
"except",
"IndexError",
":",
"template_path",
"=",
"getattr",
"(",
"settings",
",",
"'BREADCRUMBS_TEMPLATE'",
",",
"'django_bootst... | Render breadcrumbs html using bootstrap css classes. | [
"Render",
"breadcrumbs",
"html",
"using",
"bootstrap",
"css",
"classes",
"."
] | 14e7b911c70c96a5ce18512615cdb896efefa7e2 | https://github.com/prymitive/bootstrap-breadcrumbs/blob/14e7b911c70c96a5ce18512615cdb896efefa7e2/django_bootstrap_breadcrumbs/templatetags/django_bootstrap_breadcrumbs.py#L114-L160 | train | 61,018 |
danijar/layered | layered/problem.py | Problem._find_symbol | def _find_symbol(self, module, name, fallback=None):
"""
Find the symbol of the specified name inside the module or raise an
exception.
"""
if not hasattr(module, name) and fallback:
return self._find_symbol(module, fallback, None)
return getattr(module, name) | python | def _find_symbol(self, module, name, fallback=None):
"""
Find the symbol of the specified name inside the module or raise an
exception.
"""
if not hasattr(module, name) and fallback:
return self._find_symbol(module, fallback, None)
return getattr(module, name) | [
"def",
"_find_symbol",
"(",
"self",
",",
"module",
",",
"name",
",",
"fallback",
"=",
"None",
")",
":",
"if",
"not",
"hasattr",
"(",
"module",
",",
"name",
")",
"and",
"fallback",
":",
"return",
"self",
".",
"_find_symbol",
"(",
"module",
",",
"fallbac... | Find the symbol of the specified name inside the module or raise an
exception. | [
"Find",
"the",
"symbol",
"of",
"the",
"specified",
"name",
"inside",
"the",
"module",
"or",
"raise",
"an",
"exception",
"."
] | c1c09d95f90057a91ae24c80b74f415680b97338 | https://github.com/danijar/layered/blob/c1c09d95f90057a91ae24c80b74f415680b97338/layered/problem.py#L72-L79 | train | 61,019 |
danijar/layered | layered/network.py | Layer.apply | def apply(self, incoming):
"""
Store the incoming activation, apply the activation function and store
the result as outgoing activation.
"""
assert len(incoming) == self.size
self.incoming = incoming
outgoing = self.activation(self.incoming)
assert len(out... | python | def apply(self, incoming):
"""
Store the incoming activation, apply the activation function and store
the result as outgoing activation.
"""
assert len(incoming) == self.size
self.incoming = incoming
outgoing = self.activation(self.incoming)
assert len(out... | [
"def",
"apply",
"(",
"self",
",",
"incoming",
")",
":",
"assert",
"len",
"(",
"incoming",
")",
"==",
"self",
".",
"size",
"self",
".",
"incoming",
"=",
"incoming",
"outgoing",
"=",
"self",
".",
"activation",
"(",
"self",
".",
"incoming",
")",
"assert",... | Store the incoming activation, apply the activation function and store
the result as outgoing activation. | [
"Store",
"the",
"incoming",
"activation",
"apply",
"the",
"activation",
"function",
"and",
"store",
"the",
"result",
"as",
"outgoing",
"activation",
"."
] | c1c09d95f90057a91ae24c80b74f415680b97338 | https://github.com/danijar/layered/blob/c1c09d95f90057a91ae24c80b74f415680b97338/layered/network.py#L27-L36 | train | 61,020 |
danijar/layered | layered/network.py | Layer.delta | def delta(self, above):
"""
The derivative of the activation function at the current state.
"""
return self.activation.delta(self.incoming, self.outgoing, above) | python | def delta(self, above):
"""
The derivative of the activation function at the current state.
"""
return self.activation.delta(self.incoming, self.outgoing, above) | [
"def",
"delta",
"(",
"self",
",",
"above",
")",
":",
"return",
"self",
".",
"activation",
".",
"delta",
"(",
"self",
".",
"incoming",
",",
"self",
".",
"outgoing",
",",
"above",
")"
] | The derivative of the activation function at the current state. | [
"The",
"derivative",
"of",
"the",
"activation",
"function",
"at",
"the",
"current",
"state",
"."
] | c1c09d95f90057a91ae24c80b74f415680b97338 | https://github.com/danijar/layered/blob/c1c09d95f90057a91ae24c80b74f415680b97338/layered/network.py#L38-L42 | train | 61,021 |
danijar/layered | layered/network.py | Network.feed | def feed(self, weights, data):
"""
Evaluate the network with alternative weights on the input data and
return the output activation.
"""
assert len(data) == self.layers[0].size
self.layers[0].apply(data)
# Propagate trough the remaining layers.
connections... | python | def feed(self, weights, data):
"""
Evaluate the network with alternative weights on the input data and
return the output activation.
"""
assert len(data) == self.layers[0].size
self.layers[0].apply(data)
# Propagate trough the remaining layers.
connections... | [
"def",
"feed",
"(",
"self",
",",
"weights",
",",
"data",
")",
":",
"assert",
"len",
"(",
"data",
")",
"==",
"self",
".",
"layers",
"[",
"0",
"]",
".",
"size",
"self",
".",
"layers",
"[",
"0",
"]",
".",
"apply",
"(",
"data",
")",
"# Propagate trou... | Evaluate the network with alternative weights on the input data and
return the output activation. | [
"Evaluate",
"the",
"network",
"with",
"alternative",
"weights",
"on",
"the",
"input",
"data",
"and",
"return",
"the",
"output",
"activation",
"."
] | c1c09d95f90057a91ae24c80b74f415680b97338 | https://github.com/danijar/layered/blob/c1c09d95f90057a91ae24c80b74f415680b97338/layered/network.py#L154-L167 | train | 61,022 |
danijar/layered | layered/trainer.py | Trainer._init_network | def _init_network(self):
"""Define model and initialize weights."""
self.network = Network(self.problem.layers)
self.weights = Matrices(self.network.shapes)
if self.load:
loaded = np.load(self.load)
assert loaded.shape == self.weights.shape, (
'wei... | python | def _init_network(self):
"""Define model and initialize weights."""
self.network = Network(self.problem.layers)
self.weights = Matrices(self.network.shapes)
if self.load:
loaded = np.load(self.load)
assert loaded.shape == self.weights.shape, (
'wei... | [
"def",
"_init_network",
"(",
"self",
")",
":",
"self",
".",
"network",
"=",
"Network",
"(",
"self",
".",
"problem",
".",
"layers",
")",
"self",
".",
"weights",
"=",
"Matrices",
"(",
"self",
".",
"network",
".",
"shapes",
")",
"if",
"self",
".",
"load... | Define model and initialize weights. | [
"Define",
"model",
"and",
"initialize",
"weights",
"."
] | c1c09d95f90057a91ae24c80b74f415680b97338 | https://github.com/danijar/layered/blob/c1c09d95f90057a91ae24c80b74f415680b97338/layered/trainer.py#L25-L37 | train | 61,023 |
danijar/layered | layered/trainer.py | Trainer._init_training | def _init_training(self):
# pylint: disable=redefined-variable-type
"""Classes needed during training."""
if self.check:
self.backprop = CheckedBackprop(self.network, self.problem.cost)
else:
self.backprop = BatchBackprop(self.network, self.problem.cost)
s... | python | def _init_training(self):
# pylint: disable=redefined-variable-type
"""Classes needed during training."""
if self.check:
self.backprop = CheckedBackprop(self.network, self.problem.cost)
else:
self.backprop = BatchBackprop(self.network, self.problem.cost)
s... | [
"def",
"_init_training",
"(",
"self",
")",
":",
"# pylint: disable=redefined-variable-type",
"if",
"self",
".",
"check",
":",
"self",
".",
"backprop",
"=",
"CheckedBackprop",
"(",
"self",
".",
"network",
",",
"self",
".",
"problem",
".",
"cost",
")",
"else",
... | Classes needed during training. | [
"Classes",
"needed",
"during",
"training",
"."
] | c1c09d95f90057a91ae24c80b74f415680b97338 | https://github.com/danijar/layered/blob/c1c09d95f90057a91ae24c80b74f415680b97338/layered/trainer.py#L39-L50 | train | 61,024 |
danijar/layered | layered/trainer.py | Trainer._every | def _every(times, step_size, index):
"""
Given a loop over batches of an iterable and an operation that should
be performed every few elements. Determine whether the operation should
be called for the current index.
"""
current = index * step_size
step = current /... | python | def _every(times, step_size, index):
"""
Given a loop over batches of an iterable and an operation that should
be performed every few elements. Determine whether the operation should
be called for the current index.
"""
current = index * step_size
step = current /... | [
"def",
"_every",
"(",
"times",
",",
"step_size",
",",
"index",
")",
":",
"current",
"=",
"index",
"*",
"step_size",
"step",
"=",
"current",
"//",
"times",
"*",
"times",
"reached",
"=",
"current",
">=",
"step",
"overshot",
"=",
"current",
">=",
"step",
... | Given a loop over batches of an iterable and an operation that should
be performed every few elements. Determine whether the operation should
be called for the current index. | [
"Given",
"a",
"loop",
"over",
"batches",
"of",
"an",
"iterable",
"and",
"an",
"operation",
"that",
"should",
"be",
"performed",
"every",
"few",
"elements",
".",
"Determine",
"whether",
"the",
"operation",
"should",
"be",
"called",
"for",
"the",
"current",
"i... | c1c09d95f90057a91ae24c80b74f415680b97338 | https://github.com/danijar/layered/blob/c1c09d95f90057a91ae24c80b74f415680b97338/layered/trainer.py#L127-L137 | train | 61,025 |
smdabdoub/kraken-biom | kraken_biom.py | parse_tax_lvl | def parse_tax_lvl(entry, tax_lvl_depth=[]):
"""
Parse a single kraken-report entry and return a dictionary of taxa for its
named ranks.
:type entry: dict
:param entry: attributes of a single kraken-report row.
:type tax_lvl_depth: list
:param tax_lvl_depth: running record of taxon levels en... | python | def parse_tax_lvl(entry, tax_lvl_depth=[]):
"""
Parse a single kraken-report entry and return a dictionary of taxa for its
named ranks.
:type entry: dict
:param entry: attributes of a single kraken-report row.
:type tax_lvl_depth: list
:param tax_lvl_depth: running record of taxon levels en... | [
"def",
"parse_tax_lvl",
"(",
"entry",
",",
"tax_lvl_depth",
"=",
"[",
"]",
")",
":",
"# How deep in the hierarchy are we currently? Each two spaces of",
"# indentation is one level deeper. Also parse the scientific name at this",
"# level.",
"depth_and_name",
"=",
"re",
".",
"m... | Parse a single kraken-report entry and return a dictionary of taxa for its
named ranks.
:type entry: dict
:param entry: attributes of a single kraken-report row.
:type tax_lvl_depth: list
:param tax_lvl_depth: running record of taxon levels encountered in
previous calls. | [
"Parse",
"a",
"single",
"kraken",
"-",
"report",
"entry",
"and",
"return",
"a",
"dictionary",
"of",
"taxa",
"for",
"its",
"named",
"ranks",
"."
] | 46b32df9b3eb478216afc38cd1dd207492ac6c29 | https://github.com/smdabdoub/kraken-biom/blob/46b32df9b3eb478216afc38cd1dd207492ac6c29/kraken_biom.py#L85-L109 | train | 61,026 |
smdabdoub/kraken-biom | kraken_biom.py | parse_kraken_report | def parse_kraken_report(kdata, max_rank, min_rank):
"""
Parse a single output file from the kraken-report tool. Return a list
of counts at each of the acceptable taxonomic levels, and a list of
NCBI IDs and a formatted string representing their taxonomic hierarchies.
:type kdata: str
:param kd... | python | def parse_kraken_report(kdata, max_rank, min_rank):
"""
Parse a single output file from the kraken-report tool. Return a list
of counts at each of the acceptable taxonomic levels, and a list of
NCBI IDs and a formatted string representing their taxonomic hierarchies.
:type kdata: str
:param kd... | [
"def",
"parse_kraken_report",
"(",
"kdata",
",",
"max_rank",
",",
"min_rank",
")",
":",
"# map between NCBI taxonomy IDs and the string rep. of the hierarchy",
"taxa",
"=",
"OrderedDict",
"(",
")",
"# the master collection of read counts (keyed on NCBI ID)",
"counts",
"=",
"Ord... | Parse a single output file from the kraken-report tool. Return a list
of counts at each of the acceptable taxonomic levels, and a list of
NCBI IDs and a formatted string representing their taxonomic hierarchies.
:type kdata: str
:param kdata: Contents of the kraken report file. | [
"Parse",
"a",
"single",
"output",
"file",
"from",
"the",
"kraken",
"-",
"report",
"tool",
".",
"Return",
"a",
"list",
"of",
"counts",
"at",
"each",
"of",
"the",
"acceptable",
"taxonomic",
"levels",
"and",
"a",
"list",
"of",
"NCBI",
"IDs",
"and",
"a",
"... | 46b32df9b3eb478216afc38cd1dd207492ac6c29 | https://github.com/smdabdoub/kraken-biom/blob/46b32df9b3eb478216afc38cd1dd207492ac6c29/kraken_biom.py#L111-L155 | train | 61,027 |
smdabdoub/kraken-biom | kraken_biom.py | process_samples | def process_samples(kraken_reports_fp, max_rank, min_rank):
"""
Parse all kraken-report data files into sample counts dict
and store global taxon id -> taxonomy data
"""
taxa = OrderedDict()
sample_counts = OrderedDict()
for krep_fp in kraken_reports_fp:
if not osp.isfile(krep_fp):
... | python | def process_samples(kraken_reports_fp, max_rank, min_rank):
"""
Parse all kraken-report data files into sample counts dict
and store global taxon id -> taxonomy data
"""
taxa = OrderedDict()
sample_counts = OrderedDict()
for krep_fp in kraken_reports_fp:
if not osp.isfile(krep_fp):
... | [
"def",
"process_samples",
"(",
"kraken_reports_fp",
",",
"max_rank",
",",
"min_rank",
")",
":",
"taxa",
"=",
"OrderedDict",
"(",
")",
"sample_counts",
"=",
"OrderedDict",
"(",
")",
"for",
"krep_fp",
"in",
"kraken_reports_fp",
":",
"if",
"not",
"osp",
".",
"i... | Parse all kraken-report data files into sample counts dict
and store global taxon id -> taxonomy data | [
"Parse",
"all",
"kraken",
"-",
"report",
"data",
"files",
"into",
"sample",
"counts",
"dict",
"and",
"store",
"global",
"taxon",
"id",
"-",
">",
"taxonomy",
"data"
] | 46b32df9b3eb478216afc38cd1dd207492ac6c29 | https://github.com/smdabdoub/kraken-biom/blob/46b32df9b3eb478216afc38cd1dd207492ac6c29/kraken_biom.py#L158-L187 | train | 61,028 |
smdabdoub/kraken-biom | kraken_biom.py | create_biom_table | def create_biom_table(sample_counts, taxa):
"""
Create a BIOM table from sample counts and taxonomy metadata.
:type sample_counts: dict
:param sample_counts: A dictionary of dictionaries with the first level
keyed on sample ID, and the second level keyed on
... | python | def create_biom_table(sample_counts, taxa):
"""
Create a BIOM table from sample counts and taxonomy metadata.
:type sample_counts: dict
:param sample_counts: A dictionary of dictionaries with the first level
keyed on sample ID, and the second level keyed on
... | [
"def",
"create_biom_table",
"(",
"sample_counts",
",",
"taxa",
")",
":",
"data",
"=",
"[",
"[",
"0",
"if",
"taxid",
"not",
"in",
"sample_counts",
"[",
"sid",
"]",
"else",
"sample_counts",
"[",
"sid",
"]",
"[",
"taxid",
"]",
"for",
"sid",
"in",
"sample_... | Create a BIOM table from sample counts and taxonomy metadata.
:type sample_counts: dict
:param sample_counts: A dictionary of dictionaries with the first level
keyed on sample ID, and the second level keyed on
taxon ID with counts as values.
:type taxa: d... | [
"Create",
"a",
"BIOM",
"table",
"from",
"sample",
"counts",
"and",
"taxonomy",
"metadata",
"."
] | 46b32df9b3eb478216afc38cd1dd207492ac6c29 | https://github.com/smdabdoub/kraken-biom/blob/46b32df9b3eb478216afc38cd1dd207492ac6c29/kraken_biom.py#L190-L216 | train | 61,029 |
smdabdoub/kraken-biom | kraken_biom.py | write_biom | def write_biom(biomT, output_fp, fmt="hdf5", gzip=False):
"""
Write the BIOM table to a file.
:type biomT: biom.table.Table
:param biomT: A BIOM table containing the per-sample OTU counts and metadata
to be written out to file.
:type output_fp str
:param output_fp: Path to the... | python | def write_biom(biomT, output_fp, fmt="hdf5", gzip=False):
"""
Write the BIOM table to a file.
:type biomT: biom.table.Table
:param biomT: A BIOM table containing the per-sample OTU counts and metadata
to be written out to file.
:type output_fp str
:param output_fp: Path to the... | [
"def",
"write_biom",
"(",
"biomT",
",",
"output_fp",
",",
"fmt",
"=",
"\"hdf5\"",
",",
"gzip",
"=",
"False",
")",
":",
"opener",
"=",
"open",
"mode",
"=",
"'w'",
"if",
"gzip",
"and",
"fmt",
"!=",
"\"hdf5\"",
":",
"if",
"not",
"output_fp",
".",
"endsw... | Write the BIOM table to a file.
:type biomT: biom.table.Table
:param biomT: A BIOM table containing the per-sample OTU counts and metadata
to be written out to file.
:type output_fp str
:param output_fp: Path to the BIOM-format file that will be written.
:type fmt: str
:param ... | [
"Write",
"the",
"BIOM",
"table",
"to",
"a",
"file",
"."
] | 46b32df9b3eb478216afc38cd1dd207492ac6c29 | https://github.com/smdabdoub/kraken-biom/blob/46b32df9b3eb478216afc38cd1dd207492ac6c29/kraken_biom.py#L219-L252 | train | 61,030 |
smdabdoub/kraken-biom | kraken_biom.py | write_otu_file | def write_otu_file(otu_ids, fp):
"""
Write out a file containing only the list of OTU IDs from the kraken data.
One line per ID.
:type otu_ids: list or iterable
:param otu_ids: The OTU identifiers that will be written to file.
:type fp: str
:param fp: The path to the output file.
"""
... | python | def write_otu_file(otu_ids, fp):
"""
Write out a file containing only the list of OTU IDs from the kraken data.
One line per ID.
:type otu_ids: list or iterable
:param otu_ids: The OTU identifiers that will be written to file.
:type fp: str
:param fp: The path to the output file.
"""
... | [
"def",
"write_otu_file",
"(",
"otu_ids",
",",
"fp",
")",
":",
"fpdir",
"=",
"osp",
".",
"split",
"(",
"fp",
")",
"[",
"0",
"]",
"if",
"not",
"fpdir",
"==",
"\"\"",
"and",
"not",
"osp",
".",
"isdir",
"(",
"fpdir",
")",
":",
"raise",
"RuntimeError",
... | Write out a file containing only the list of OTU IDs from the kraken data.
One line per ID.
:type otu_ids: list or iterable
:param otu_ids: The OTU identifiers that will be written to file.
:type fp: str
:param fp: The path to the output file. | [
"Write",
"out",
"a",
"file",
"containing",
"only",
"the",
"list",
"of",
"OTU",
"IDs",
"from",
"the",
"kraken",
"data",
".",
"One",
"line",
"per",
"ID",
"."
] | 46b32df9b3eb478216afc38cd1dd207492ac6c29 | https://github.com/smdabdoub/kraken-biom/blob/46b32df9b3eb478216afc38cd1dd207492ac6c29/kraken_biom.py#L255-L271 | train | 61,031 |
neptune-ml/steppy-toolkit | toolkit/postprocessing.py | BlendingOptimizer.transform | def transform(self, X):
"""Performs predictions blending using the trained weights.
Args:
X (array-like): Predictions of different models.
Returns: dict with blended predictions (key is 'y_pred').
"""
assert np.shape(X)[0] == len(self._weights), (
'Blendi... | python | def transform(self, X):
"""Performs predictions blending using the trained weights.
Args:
X (array-like): Predictions of different models.
Returns: dict with blended predictions (key is 'y_pred').
"""
assert np.shape(X)[0] == len(self._weights), (
'Blendi... | [
"def",
"transform",
"(",
"self",
",",
"X",
")",
":",
"assert",
"np",
".",
"shape",
"(",
"X",
")",
"[",
"0",
"]",
"==",
"len",
"(",
"self",
".",
"_weights",
")",
",",
"(",
"'BlendingOptimizer: Number of models to blend its predictions and weights does not match: ... | Performs predictions blending using the trained weights.
Args:
X (array-like): Predictions of different models.
Returns: dict with blended predictions (key is 'y_pred'). | [
"Performs",
"predictions",
"blending",
"using",
"the",
"trained",
"weights",
"."
] | bf3f48cfcc65dffc46e65ddd5d6cfec6bb9f9132 | https://github.com/neptune-ml/steppy-toolkit/blob/bf3f48cfcc65dffc46e65ddd5d6cfec6bb9f9132/toolkit/postprocessing.py#L166-L180 | train | 61,032 |
neptune-ml/steppy-toolkit | toolkit/postprocessing.py | BlendingOptimizer.fit_transform | def fit_transform(self, X, y, step_size=0.1, init_weights=None, warm_start=False):
"""Fit optimizer to X, then transforms X. See `fit` and `transform` for further explanation."""
self.fit(X=X, y=y, step_size=step_size, init_weights=init_weights, warm_start=warm_start)
return self.transform(X=X) | python | def fit_transform(self, X, y, step_size=0.1, init_weights=None, warm_start=False):
"""Fit optimizer to X, then transforms X. See `fit` and `transform` for further explanation."""
self.fit(X=X, y=y, step_size=step_size, init_weights=init_weights, warm_start=warm_start)
return self.transform(X=X) | [
"def",
"fit_transform",
"(",
"self",
",",
"X",
",",
"y",
",",
"step_size",
"=",
"0.1",
",",
"init_weights",
"=",
"None",
",",
"warm_start",
"=",
"False",
")",
":",
"self",
".",
"fit",
"(",
"X",
"=",
"X",
",",
"y",
"=",
"y",
",",
"step_size",
"=",... | Fit optimizer to X, then transforms X. See `fit` and `transform` for further explanation. | [
"Fit",
"optimizer",
"to",
"X",
"then",
"transforms",
"X",
".",
"See",
"fit",
"and",
"transform",
"for",
"further",
"explanation",
"."
] | bf3f48cfcc65dffc46e65ddd5d6cfec6bb9f9132 | https://github.com/neptune-ml/steppy-toolkit/blob/bf3f48cfcc65dffc46e65ddd5d6cfec6bb9f9132/toolkit/postprocessing.py#L182-L186 | train | 61,033 |
romansalin/django-seo2 | djangoseo/utils.py | escape_tags | def escape_tags(value, valid_tags):
"""
Strips text from the given html string, leaving only tags.
This functionality requires BeautifulSoup, nothing will be
done otherwise.
This isn't perfect. Someone could put javascript in here:
<a onClick="alert('hi');">test</a>
So if you use v... | python | def escape_tags(value, valid_tags):
"""
Strips text from the given html string, leaving only tags.
This functionality requires BeautifulSoup, nothing will be
done otherwise.
This isn't perfect. Someone could put javascript in here:
<a onClick="alert('hi');">test</a>
So if you use v... | [
"def",
"escape_tags",
"(",
"value",
",",
"valid_tags",
")",
":",
"# 1. escape everything",
"value",
"=",
"conditional_escape",
"(",
"value",
")",
"# 2. Reenable certain tags",
"if",
"valid_tags",
":",
"# TODO: precompile somewhere once?",
"tag_re",
"=",
"re",
".",
"co... | Strips text from the given html string, leaving only tags.
This functionality requires BeautifulSoup, nothing will be
done otherwise.
This isn't perfect. Someone could put javascript in here:
<a onClick="alert('hi');">test</a>
So if you use valid_tags, you still need to trust your data ent... | [
"Strips",
"text",
"from",
"the",
"given",
"html",
"string",
"leaving",
"only",
"tags",
".",
"This",
"functionality",
"requires",
"BeautifulSoup",
"nothing",
"will",
"be",
"done",
"otherwise",
"."
] | f788699a88e286ab9a698759d9b42f57852865d8 | https://github.com/romansalin/django-seo2/blob/f788699a88e286ab9a698759d9b42f57852865d8/djangoseo/utils.py#L82-L113 | train | 61,034 |
romansalin/django-seo2 | djangoseo/utils.py | _get_seo_content_types | def _get_seo_content_types(seo_models):
"""Returns a list of content types from the models defined in settings."""
try:
return [ContentType.objects.get_for_model(m).id for m in seo_models]
except Exception: # previously caught DatabaseError
# Return an empty list if this is called too early... | python | def _get_seo_content_types(seo_models):
"""Returns a list of content types from the models defined in settings."""
try:
return [ContentType.objects.get_for_model(m).id for m in seo_models]
except Exception: # previously caught DatabaseError
# Return an empty list if this is called too early... | [
"def",
"_get_seo_content_types",
"(",
"seo_models",
")",
":",
"try",
":",
"return",
"[",
"ContentType",
".",
"objects",
".",
"get_for_model",
"(",
"m",
")",
".",
"id",
"for",
"m",
"in",
"seo_models",
"]",
"except",
"Exception",
":",
"# previously caught Databa... | Returns a list of content types from the models defined in settings. | [
"Returns",
"a",
"list",
"of",
"content",
"types",
"from",
"the",
"models",
"defined",
"in",
"settings",
"."
] | f788699a88e286ab9a698759d9b42f57852865d8 | https://github.com/romansalin/django-seo2/blob/f788699a88e286ab9a698759d9b42f57852865d8/djangoseo/utils.py#L116-L122 | train | 61,035 |
romansalin/django-seo2 | djangoseo/admin.py | register_seo_admin | def register_seo_admin(admin_site, metadata_class):
"""Register the backends specified in Meta.backends with the admin."""
if metadata_class._meta.use_sites:
path_admin = SitePathMetadataAdmin
model_instance_admin = SiteModelInstanceMetadataAdmin
model_admin = SiteModelMetadataAdmin
... | python | def register_seo_admin(admin_site, metadata_class):
"""Register the backends specified in Meta.backends with the admin."""
if metadata_class._meta.use_sites:
path_admin = SitePathMetadataAdmin
model_instance_admin = SiteModelInstanceMetadataAdmin
model_admin = SiteModelMetadataAdmin
... | [
"def",
"register_seo_admin",
"(",
"admin_site",
",",
"metadata_class",
")",
":",
"if",
"metadata_class",
".",
"_meta",
".",
"use_sites",
":",
"path_admin",
"=",
"SitePathMetadataAdmin",
"model_instance_admin",
"=",
"SiteModelInstanceMetadataAdmin",
"model_admin",
"=",
"... | Register the backends specified in Meta.backends with the admin. | [
"Register",
"the",
"backends",
"specified",
"in",
"Meta",
".",
"backends",
"with",
"the",
"admin",
"."
] | f788699a88e286ab9a698759d9b42f57852865d8 | https://github.com/romansalin/django-seo2/blob/f788699a88e286ab9a698759d9b42f57852865d8/djangoseo/admin.py#L67-L120 | train | 61,036 |
romansalin/django-seo2 | djangoseo/admin.py | MetadataFormset._construct_form | def _construct_form(self, i, **kwargs):
"""Override the method to change the form attribute empty_permitted."""
form = super(MetadataFormset, self)._construct_form(i, **kwargs)
# Monkey patch the form to always force a save.
# It's unfortunate, but necessary because we always want an ins... | python | def _construct_form(self, i, **kwargs):
"""Override the method to change the form attribute empty_permitted."""
form = super(MetadataFormset, self)._construct_form(i, **kwargs)
# Monkey patch the form to always force a save.
# It's unfortunate, but necessary because we always want an ins... | [
"def",
"_construct_form",
"(",
"self",
",",
"i",
",",
"*",
"*",
"kwargs",
")",
":",
"form",
"=",
"super",
"(",
"MetadataFormset",
",",
"self",
")",
".",
"_construct_form",
"(",
"i",
",",
"*",
"*",
"kwargs",
")",
"# Monkey patch the form to always force a sav... | Override the method to change the form attribute empty_permitted. | [
"Override",
"the",
"method",
"to",
"change",
"the",
"form",
"attribute",
"empty_permitted",
"."
] | f788699a88e286ab9a698759d9b42f57852865d8 | https://github.com/romansalin/django-seo2/blob/f788699a88e286ab9a698759d9b42f57852865d8/djangoseo/admin.py#L136-L152 | train | 61,037 |
romansalin/django-seo2 | djangoseo/base.py | _get_metadata_model | def _get_metadata_model(name=None):
"""Find registered Metadata object."""
if name is not None:
try:
return registry[name]
except KeyError:
if len(registry) == 1:
valid_names = 'Try using the name "%s" or simply leaving it '\
... | python | def _get_metadata_model(name=None):
"""Find registered Metadata object."""
if name is not None:
try:
return registry[name]
except KeyError:
if len(registry) == 1:
valid_names = 'Try using the name "%s" or simply leaving it '\
... | [
"def",
"_get_metadata_model",
"(",
"name",
"=",
"None",
")",
":",
"if",
"name",
"is",
"not",
"None",
":",
"try",
":",
"return",
"registry",
"[",
"name",
"]",
"except",
"KeyError",
":",
"if",
"len",
"(",
"registry",
")",
"==",
"1",
":",
"valid_names",
... | Find registered Metadata object. | [
"Find",
"registered",
"Metadata",
"object",
"."
] | f788699a88e286ab9a698759d9b42f57852865d8 | https://github.com/romansalin/django-seo2/blob/f788699a88e286ab9a698759d9b42f57852865d8/djangoseo/base.py#L267-L286 | train | 61,038 |
romansalin/django-seo2 | djangoseo/backends.py | MetadataBaseModel._resolve_value | def _resolve_value(self, name):
""" Returns an appropriate value for the given name. """
name = str(name)
if name in self._metadata._meta.elements:
element = self._metadata._meta.elements[name]
# Look in instances for an explicit value
if element.editable:
... | python | def _resolve_value(self, name):
""" Returns an appropriate value for the given name. """
name = str(name)
if name in self._metadata._meta.elements:
element = self._metadata._meta.elements[name]
# Look in instances for an explicit value
if element.editable:
... | [
"def",
"_resolve_value",
"(",
"self",
",",
"name",
")",
":",
"name",
"=",
"str",
"(",
"name",
")",
"if",
"name",
"in",
"self",
".",
"_metadata",
".",
"_meta",
".",
"elements",
":",
"element",
"=",
"self",
".",
"_metadata",
".",
"_meta",
".",
"element... | Returns an appropriate value for the given name. | [
"Returns",
"an",
"appropriate",
"value",
"for",
"the",
"given",
"name",
"."
] | f788699a88e286ab9a698759d9b42f57852865d8 | https://github.com/romansalin/django-seo2/blob/f788699a88e286ab9a698759d9b42f57852865d8/djangoseo/backends.py#L37-L69 | train | 61,039 |
umap-project/django-leaflet-storage | leaflet_storage/views.py | _urls_for_js | def _urls_for_js(urls=None):
"""
Return templated URLs prepared for javascript.
"""
if urls is None:
# prevent circular import
from .urls import urlpatterns
urls = [url.name for url in urlpatterns if getattr(url, 'name', None)]
urls = dict(zip(urls, [get_uri_template(url) for... | python | def _urls_for_js(urls=None):
"""
Return templated URLs prepared for javascript.
"""
if urls is None:
# prevent circular import
from .urls import urlpatterns
urls = [url.name for url in urlpatterns if getattr(url, 'name', None)]
urls = dict(zip(urls, [get_uri_template(url) for... | [
"def",
"_urls_for_js",
"(",
"urls",
"=",
"None",
")",
":",
"if",
"urls",
"is",
"None",
":",
"# prevent circular import",
"from",
".",
"urls",
"import",
"urlpatterns",
"urls",
"=",
"[",
"url",
".",
"name",
"for",
"url",
"in",
"urlpatterns",
"if",
"getattr",... | Return templated URLs prepared for javascript. | [
"Return",
"templated",
"URLs",
"prepared",
"for",
"javascript",
"."
] | c81972e524b1e09ffca355bfb7edfdede42dcc59 | https://github.com/umap-project/django-leaflet-storage/blob/c81972e524b1e09ffca355bfb7edfdede42dcc59/leaflet_storage/views.py#L43-L53 | train | 61,040 |
umap-project/django-leaflet-storage | leaflet_storage/utils.py | decorated_patterns | def decorated_patterns(func, *urls):
"""
Utility function to decorate a group of url in urls.py
Taken from http://djangosnippets.org/snippets/532/ + comments
See also http://friendpaste.com/6afByRiBB9CMwPft3a6lym
Example:
urlpatterns = [
url(r'^language/(?P<lang_code>[a-z]+)$', views.M... | python | def decorated_patterns(func, *urls):
"""
Utility function to decorate a group of url in urls.py
Taken from http://djangosnippets.org/snippets/532/ + comments
See also http://friendpaste.com/6afByRiBB9CMwPft3a6lym
Example:
urlpatterns = [
url(r'^language/(?P<lang_code>[a-z]+)$', views.M... | [
"def",
"decorated_patterns",
"(",
"func",
",",
"*",
"urls",
")",
":",
"def",
"decorate",
"(",
"urls",
",",
"func",
")",
":",
"for",
"url",
"in",
"urls",
":",
"if",
"isinstance",
"(",
"url",
",",
"RegexURLPattern",
")",
":",
"url",
".",
"__class__",
"... | Utility function to decorate a group of url in urls.py
Taken from http://djangosnippets.org/snippets/532/ + comments
See also http://friendpaste.com/6afByRiBB9CMwPft3a6lym
Example:
urlpatterns = [
url(r'^language/(?P<lang_code>[a-z]+)$', views.MyView, name='name'),
] + decorated_patterns(l... | [
"Utility",
"function",
"to",
"decorate",
"a",
"group",
"of",
"url",
"in",
"urls",
".",
"py"
] | c81972e524b1e09ffca355bfb7edfdede42dcc59 | https://github.com/umap-project/django-leaflet-storage/blob/c81972e524b1e09ffca355bfb7edfdede42dcc59/leaflet_storage/utils.py#L72-L105 | train | 61,041 |
willseward/django-custom-field | custom_field/custom_field.py | CustomFieldModel.get_custom_fields | def get_custom_fields(self):
""" Return a list of custom fields for this model """
return CustomField.objects.filter(
content_type=ContentType.objects.get_for_model(self)) | python | def get_custom_fields(self):
""" Return a list of custom fields for this model """
return CustomField.objects.filter(
content_type=ContentType.objects.get_for_model(self)) | [
"def",
"get_custom_fields",
"(",
"self",
")",
":",
"return",
"CustomField",
".",
"objects",
".",
"filter",
"(",
"content_type",
"=",
"ContentType",
".",
"objects",
".",
"get_for_model",
"(",
"self",
")",
")"
] | Return a list of custom fields for this model | [
"Return",
"a",
"list",
"of",
"custom",
"fields",
"for",
"this",
"model"
] | d42a620a53a69e53902ece77bfbdad27485f3ef1 | https://github.com/willseward/django-custom-field/blob/d42a620a53a69e53902ece77bfbdad27485f3ef1/custom_field/custom_field.py#L21-L24 | train | 61,042 |
willseward/django-custom-field | custom_field/custom_field.py | CustomFieldModel.get_custom_field | def get_custom_field(self, field_name):
""" Get a custom field object for this model
field_name - Name of the custom field you want.
"""
content_type = ContentType.objects.get_for_model(self)
return CustomField.objects.get(
content_type=content_type, name=field_name) | python | def get_custom_field(self, field_name):
""" Get a custom field object for this model
field_name - Name of the custom field you want.
"""
content_type = ContentType.objects.get_for_model(self)
return CustomField.objects.get(
content_type=content_type, name=field_name) | [
"def",
"get_custom_field",
"(",
"self",
",",
"field_name",
")",
":",
"content_type",
"=",
"ContentType",
".",
"objects",
".",
"get_for_model",
"(",
"self",
")",
"return",
"CustomField",
".",
"objects",
".",
"get",
"(",
"content_type",
"=",
"content_type",
",",... | Get a custom field object for this model
field_name - Name of the custom field you want. | [
"Get",
"a",
"custom",
"field",
"object",
"for",
"this",
"model",
"field_name",
"-",
"Name",
"of",
"the",
"custom",
"field",
"you",
"want",
"."
] | d42a620a53a69e53902ece77bfbdad27485f3ef1 | https://github.com/willseward/django-custom-field/blob/d42a620a53a69e53902ece77bfbdad27485f3ef1/custom_field/custom_field.py#L34-L40 | train | 61,043 |
willseward/django-custom-field | custom_field/custom_field.py | CustomFieldModel.get_custom_value | def get_custom_value(self, field_name):
""" Get a value for a specified custom field
field_name - Name of the custom field you want.
"""
custom_field = self.get_custom_field(field_name)
return CustomFieldValue.objects.get_or_create(
field=custom_field, object_id=self.... | python | def get_custom_value(self, field_name):
""" Get a value for a specified custom field
field_name - Name of the custom field you want.
"""
custom_field = self.get_custom_field(field_name)
return CustomFieldValue.objects.get_or_create(
field=custom_field, object_id=self.... | [
"def",
"get_custom_value",
"(",
"self",
",",
"field_name",
")",
":",
"custom_field",
"=",
"self",
".",
"get_custom_field",
"(",
"field_name",
")",
"return",
"CustomFieldValue",
".",
"objects",
".",
"get_or_create",
"(",
"field",
"=",
"custom_field",
",",
"object... | Get a value for a specified custom field
field_name - Name of the custom field you want. | [
"Get",
"a",
"value",
"for",
"a",
"specified",
"custom",
"field",
"field_name",
"-",
"Name",
"of",
"the",
"custom",
"field",
"you",
"want",
"."
] | d42a620a53a69e53902ece77bfbdad27485f3ef1 | https://github.com/willseward/django-custom-field/blob/d42a620a53a69e53902ece77bfbdad27485f3ef1/custom_field/custom_field.py#L42-L48 | train | 61,044 |
willseward/django-custom-field | custom_field/custom_field.py | CustomFieldModel.set_custom_value | def set_custom_value(self, field_name, value):
""" Set a value for a specified custom field
field_name - Name of the custom field you want.
value - Value to set it to
"""
custom_field = self.get_custom_field(field_name)
custom_value = CustomFieldValue.objects.get_or_creat... | python | def set_custom_value(self, field_name, value):
""" Set a value for a specified custom field
field_name - Name of the custom field you want.
value - Value to set it to
"""
custom_field = self.get_custom_field(field_name)
custom_value = CustomFieldValue.objects.get_or_creat... | [
"def",
"set_custom_value",
"(",
"self",
",",
"field_name",
",",
"value",
")",
":",
"custom_field",
"=",
"self",
".",
"get_custom_field",
"(",
"field_name",
")",
"custom_value",
"=",
"CustomFieldValue",
".",
"objects",
".",
"get_or_create",
"(",
"field",
"=",
"... | Set a value for a specified custom field
field_name - Name of the custom field you want.
value - Value to set it to | [
"Set",
"a",
"value",
"for",
"a",
"specified",
"custom",
"field",
"field_name",
"-",
"Name",
"of",
"the",
"custom",
"field",
"you",
"want",
".",
"value",
"-",
"Value",
"to",
"set",
"it",
"to"
] | d42a620a53a69e53902ece77bfbdad27485f3ef1 | https://github.com/willseward/django-custom-field/blob/d42a620a53a69e53902ece77bfbdad27485f3ef1/custom_field/custom_field.py#L50-L59 | train | 61,045 |
exhuma/python-cluster | cluster/method/kmeans.py | KMeansClustering.assign_item | def assign_item(self, item, origin):
"""
Assigns an item from a given cluster to the closest located cluster.
:param item: the item to be moved.
:param origin: the originating cluster.
"""
closest_cluster = origin
for cluster in self.__clusters:
if se... | python | def assign_item(self, item, origin):
"""
Assigns an item from a given cluster to the closest located cluster.
:param item: the item to be moved.
:param origin: the originating cluster.
"""
closest_cluster = origin
for cluster in self.__clusters:
if se... | [
"def",
"assign_item",
"(",
"self",
",",
"item",
",",
"origin",
")",
":",
"closest_cluster",
"=",
"origin",
"for",
"cluster",
"in",
"self",
".",
"__clusters",
":",
"if",
"self",
".",
"distance",
"(",
"item",
",",
"centroid",
"(",
"cluster",
")",
")",
"<... | Assigns an item from a given cluster to the closest located cluster.
:param item: the item to be moved.
:param origin: the originating cluster. | [
"Assigns",
"an",
"item",
"from",
"a",
"given",
"cluster",
"to",
"the",
"closest",
"located",
"cluster",
"."
] | 4c0ac14d9beafcd51f0d849151514083c296402f | https://github.com/exhuma/python-cluster/blob/4c0ac14d9beafcd51f0d849151514083c296402f/cluster/method/kmeans.py#L113-L130 | train | 61,046 |
exhuma/python-cluster | cluster/method/kmeans.py | KMeansClustering.move_item | def move_item(self, item, origin, destination):
"""
Moves an item from one cluster to anoter cluster.
:param item: the item to be moved.
:param origin: the originating cluster.
:param destination: the target cluster.
"""
if self.equality:
item_index =... | python | def move_item(self, item, origin, destination):
"""
Moves an item from one cluster to anoter cluster.
:param item: the item to be moved.
:param origin: the originating cluster.
:param destination: the target cluster.
"""
if self.equality:
item_index =... | [
"def",
"move_item",
"(",
"self",
",",
"item",
",",
"origin",
",",
"destination",
")",
":",
"if",
"self",
".",
"equality",
":",
"item_index",
"=",
"0",
"for",
"i",
",",
"element",
"in",
"enumerate",
"(",
"origin",
")",
":",
"if",
"self",
".",
"equalit... | Moves an item from one cluster to anoter cluster.
:param item: the item to be moved.
:param origin: the originating cluster.
:param destination: the target cluster. | [
"Moves",
"an",
"item",
"from",
"one",
"cluster",
"to",
"anoter",
"cluster",
"."
] | 4c0ac14d9beafcd51f0d849151514083c296402f | https://github.com/exhuma/python-cluster/blob/4c0ac14d9beafcd51f0d849151514083c296402f/cluster/method/kmeans.py#L132-L149 | train | 61,047 |
exhuma/python-cluster | cluster/method/kmeans.py | KMeansClustering.initialise_clusters | def initialise_clusters(self, input_, clustercount):
"""
Initialises the clusters by distributing the items from the data.
evenly across n clusters
:param input_: the data set (a list of tuples).
:param clustercount: the amount of clusters (n).
"""
# initialise t... | python | def initialise_clusters(self, input_, clustercount):
"""
Initialises the clusters by distributing the items from the data.
evenly across n clusters
:param input_: the data set (a list of tuples).
:param clustercount: the amount of clusters (n).
"""
# initialise t... | [
"def",
"initialise_clusters",
"(",
"self",
",",
"input_",
",",
"clustercount",
")",
":",
"# initialise the clusters with empty lists",
"self",
".",
"__clusters",
"=",
"[",
"]",
"for",
"_",
"in",
"range",
"(",
"clustercount",
")",
":",
"self",
".",
"__clusters",
... | Initialises the clusters by distributing the items from the data.
evenly across n clusters
:param input_: the data set (a list of tuples).
:param clustercount: the amount of clusters (n). | [
"Initialises",
"the",
"clusters",
"by",
"distributing",
"the",
"items",
"from",
"the",
"data",
".",
"evenly",
"across",
"n",
"clusters"
] | 4c0ac14d9beafcd51f0d849151514083c296402f | https://github.com/exhuma/python-cluster/blob/4c0ac14d9beafcd51f0d849151514083c296402f/cluster/method/kmeans.py#L151-L168 | train | 61,048 |
exhuma/python-cluster | cluster/method/hierarchical.py | HierarchicalClustering.publish_progress | def publish_progress(self, total, current):
"""
If a progress function was supplied, this will call that function with
the total number of elements, and the remaining number of elements.
:param total: The total number of elements.
:param remaining: The remaining number of elemen... | python | def publish_progress(self, total, current):
"""
If a progress function was supplied, this will call that function with
the total number of elements, and the remaining number of elements.
:param total: The total number of elements.
:param remaining: The remaining number of elemen... | [
"def",
"publish_progress",
"(",
"self",
",",
"total",
",",
"current",
")",
":",
"if",
"self",
".",
"progress_callback",
":",
"self",
".",
"progress_callback",
"(",
"total",
",",
"current",
")"
] | If a progress function was supplied, this will call that function with
the total number of elements, and the remaining number of elements.
:param total: The total number of elements.
:param remaining: The remaining number of elements. | [
"If",
"a",
"progress",
"function",
"was",
"supplied",
"this",
"will",
"call",
"that",
"function",
"with",
"the",
"total",
"number",
"of",
"elements",
"and",
"the",
"remaining",
"number",
"of",
"elements",
"."
] | 4c0ac14d9beafcd51f0d849151514083c296402f | https://github.com/exhuma/python-cluster/blob/4c0ac14d9beafcd51f0d849151514083c296402f/cluster/method/hierarchical.py#L86-L95 | train | 61,049 |
exhuma/python-cluster | cluster/method/hierarchical.py | HierarchicalClustering.set_linkage_method | def set_linkage_method(self, method):
"""
Sets the method to determine the distance between two clusters.
:param method: The method to use. It can be one of ``'single'``,
``'complete'``, ``'average'`` or ``'uclus'``, or a callable. The
callable should take two collection... | python | def set_linkage_method(self, method):
"""
Sets the method to determine the distance between two clusters.
:param method: The method to use. It can be one of ``'single'``,
``'complete'``, ``'average'`` or ``'uclus'``, or a callable. The
callable should take two collection... | [
"def",
"set_linkage_method",
"(",
"self",
",",
"method",
")",
":",
"if",
"method",
"==",
"'single'",
":",
"self",
".",
"linkage",
"=",
"single",
"elif",
"method",
"==",
"'complete'",
":",
"self",
".",
"linkage",
"=",
"complete",
"elif",
"method",
"==",
"... | Sets the method to determine the distance between two clusters.
:param method: The method to use. It can be one of ``'single'``,
``'complete'``, ``'average'`` or ``'uclus'``, or a callable. The
callable should take two collections as parameters and return a
distance value be... | [
"Sets",
"the",
"method",
"to",
"determine",
"the",
"distance",
"between",
"two",
"clusters",
"."
] | 4c0ac14d9beafcd51f0d849151514083c296402f | https://github.com/exhuma/python-cluster/blob/4c0ac14d9beafcd51f0d849151514083c296402f/cluster/method/hierarchical.py#L97-L118 | train | 61,050 |
exhuma/python-cluster | cluster/method/hierarchical.py | HierarchicalClustering.cluster | def cluster(self, matrix=None, level=None, sequence=None):
"""
Perform hierarchical clustering.
:param matrix: The 2D list that is currently under processing. The
matrix contains the distances of each item with each other
:param level: The current level of clustering
... | python | def cluster(self, matrix=None, level=None, sequence=None):
"""
Perform hierarchical clustering.
:param matrix: The 2D list that is currently under processing. The
matrix contains the distances of each item with each other
:param level: The current level of clustering
... | [
"def",
"cluster",
"(",
"self",
",",
"matrix",
"=",
"None",
",",
"level",
"=",
"None",
",",
"sequence",
"=",
"None",
")",
":",
"logger",
".",
"info",
"(",
"\"Performing cluster()\"",
")",
"if",
"matrix",
"is",
"None",
":",
"# create level 0, first iteration (... | Perform hierarchical clustering.
:param matrix: The 2D list that is currently under processing. The
matrix contains the distances of each item with each other
:param level: The current level of clustering
:param sequence: The sequence number of the clustering | [
"Perform",
"hierarchical",
"clustering",
"."
] | 4c0ac14d9beafcd51f0d849151514083c296402f | https://github.com/exhuma/python-cluster/blob/4c0ac14d9beafcd51f0d849151514083c296402f/cluster/method/hierarchical.py#L120-L189 | train | 61,051 |
exhuma/python-cluster | cluster/util.py | flatten | def flatten(L):
"""
Flattens a list.
Example:
>>> flatten([a,b,[c,d,[e,f]]])
[a,b,c,d,e,f]
"""
if not isinstance(L, list):
return [L]
if L == []:
return L
return flatten(L[0]) + flatten(L[1:]) | python | def flatten(L):
"""
Flattens a list.
Example:
>>> flatten([a,b,[c,d,[e,f]]])
[a,b,c,d,e,f]
"""
if not isinstance(L, list):
return [L]
if L == []:
return L
return flatten(L[0]) + flatten(L[1:]) | [
"def",
"flatten",
"(",
"L",
")",
":",
"if",
"not",
"isinstance",
"(",
"L",
",",
"list",
")",
":",
"return",
"[",
"L",
"]",
"if",
"L",
"==",
"[",
"]",
":",
"return",
"L",
"return",
"flatten",
"(",
"L",
"[",
"0",
"]",
")",
"+",
"flatten",
"(",
... | Flattens a list.
Example:
>>> flatten([a,b,[c,d,[e,f]]])
[a,b,c,d,e,f] | [
"Flattens",
"a",
"list",
"."
] | 4c0ac14d9beafcd51f0d849151514083c296402f | https://github.com/exhuma/python-cluster/blob/4c0ac14d9beafcd51f0d849151514083c296402f/cluster/util.py#L29-L44 | train | 61,052 |
exhuma/python-cluster | cluster/util.py | fullyflatten | def fullyflatten(container):
"""
Completely flattens out a cluster and returns a one-dimensional set
containing the cluster's items. This is useful in cases where some items of
the cluster are clusters in their own right and you only want the items.
:param container: the container to flatten.
"... | python | def fullyflatten(container):
"""
Completely flattens out a cluster and returns a one-dimensional set
containing the cluster's items. This is useful in cases where some items of
the cluster are clusters in their own right and you only want the items.
:param container: the container to flatten.
"... | [
"def",
"fullyflatten",
"(",
"container",
")",
":",
"flattened_items",
"=",
"[",
"]",
"for",
"item",
"in",
"container",
":",
"if",
"hasattr",
"(",
"item",
",",
"'items'",
")",
":",
"flattened_items",
"=",
"flattened_items",
"+",
"fullyflatten",
"(",
"item",
... | Completely flattens out a cluster and returns a one-dimensional set
containing the cluster's items. This is useful in cases where some items of
the cluster are clusters in their own right and you only want the items.
:param container: the container to flatten. | [
"Completely",
"flattens",
"out",
"a",
"cluster",
"and",
"returns",
"a",
"one",
"-",
"dimensional",
"set",
"containing",
"the",
"cluster",
"s",
"items",
".",
"This",
"is",
"useful",
"in",
"cases",
"where",
"some",
"items",
"of",
"the",
"cluster",
"are",
"cl... | 4c0ac14d9beafcd51f0d849151514083c296402f | https://github.com/exhuma/python-cluster/blob/4c0ac14d9beafcd51f0d849151514083c296402f/cluster/util.py#L47-L63 | train | 61,053 |
exhuma/python-cluster | cluster/util.py | minkowski_distance | def minkowski_distance(x, y, p=2):
"""
Calculates the minkowski distance between two points.
:param x: the first point
:param y: the second point
:param p: the order of the minkowski algorithm. If *p=1* it is equal
to the manhatten distance, if *p=2* it is equal to the euclidian
dis... | python | def minkowski_distance(x, y, p=2):
"""
Calculates the minkowski distance between two points.
:param x: the first point
:param y: the second point
:param p: the order of the minkowski algorithm. If *p=1* it is equal
to the manhatten distance, if *p=2* it is equal to the euclidian
dis... | [
"def",
"minkowski_distance",
"(",
"x",
",",
"y",
",",
"p",
"=",
"2",
")",
":",
"from",
"math",
"import",
"pow",
"assert",
"len",
"(",
"y",
")",
"==",
"len",
"(",
"x",
")",
"assert",
"len",
"(",
"x",
")",
">=",
"1",
"sum",
"=",
"0",
"for",
"i"... | Calculates the minkowski distance between two points.
:param x: the first point
:param y: the second point
:param p: the order of the minkowski algorithm. If *p=1* it is equal
to the manhatten distance, if *p=2* it is equal to the euclidian
distance. The higher the order, the closer it conv... | [
"Calculates",
"the",
"minkowski",
"distance",
"between",
"two",
"points",
"."
] | 4c0ac14d9beafcd51f0d849151514083c296402f | https://github.com/exhuma/python-cluster/blob/4c0ac14d9beafcd51f0d849151514083c296402f/cluster/util.py#L89-L106 | train | 61,054 |
exhuma/python-cluster | cluster/util.py | magnitude | def magnitude(a):
"calculates the magnitude of a vecor"
from math import sqrt
sum = 0
for coord in a:
sum += coord ** 2
return sqrt(sum) | python | def magnitude(a):
"calculates the magnitude of a vecor"
from math import sqrt
sum = 0
for coord in a:
sum += coord ** 2
return sqrt(sum) | [
"def",
"magnitude",
"(",
"a",
")",
":",
"from",
"math",
"import",
"sqrt",
"sum",
"=",
"0",
"for",
"coord",
"in",
"a",
":",
"sum",
"+=",
"coord",
"**",
"2",
"return",
"sqrt",
"(",
"sum",
")"
] | calculates the magnitude of a vecor | [
"calculates",
"the",
"magnitude",
"of",
"a",
"vecor"
] | 4c0ac14d9beafcd51f0d849151514083c296402f | https://github.com/exhuma/python-cluster/blob/4c0ac14d9beafcd51f0d849151514083c296402f/cluster/util.py#L109-L115 | train | 61,055 |
exhuma/python-cluster | cluster/util.py | dotproduct | def dotproduct(a, b):
"Calculates the dotproduct between two vecors"
assert(len(a) == len(b))
out = 0
for i in range(len(a)):
out += a[i] * b[i]
return out | python | def dotproduct(a, b):
"Calculates the dotproduct between two vecors"
assert(len(a) == len(b))
out = 0
for i in range(len(a)):
out += a[i] * b[i]
return out | [
"def",
"dotproduct",
"(",
"a",
",",
"b",
")",
":",
"assert",
"(",
"len",
"(",
"a",
")",
"==",
"len",
"(",
"b",
")",
")",
"out",
"=",
"0",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"a",
")",
")",
":",
"out",
"+=",
"a",
"[",
"i",
"]",
"... | Calculates the dotproduct between two vecors | [
"Calculates",
"the",
"dotproduct",
"between",
"two",
"vecors"
] | 4c0ac14d9beafcd51f0d849151514083c296402f | https://github.com/exhuma/python-cluster/blob/4c0ac14d9beafcd51f0d849151514083c296402f/cluster/util.py#L118-L124 | train | 61,056 |
exhuma/python-cluster | cluster/util.py | centroid | def centroid(data, method=median):
"returns the central vector of a list of vectors"
out = []
for i in range(len(data[0])):
out.append(method([x[i] for x in data]))
return tuple(out) | python | def centroid(data, method=median):
"returns the central vector of a list of vectors"
out = []
for i in range(len(data[0])):
out.append(method([x[i] for x in data]))
return tuple(out) | [
"def",
"centroid",
"(",
"data",
",",
"method",
"=",
"median",
")",
":",
"out",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"data",
"[",
"0",
"]",
")",
")",
":",
"out",
".",
"append",
"(",
"method",
"(",
"[",
"x",
"[",
"i",
"]... | returns the central vector of a list of vectors | [
"returns",
"the",
"central",
"vector",
"of",
"a",
"list",
"of",
"vectors"
] | 4c0ac14d9beafcd51f0d849151514083c296402f | https://github.com/exhuma/python-cluster/blob/4c0ac14d9beafcd51f0d849151514083c296402f/cluster/util.py#L127-L132 | train | 61,057 |
exhuma/python-cluster | cluster/cluster.py | Cluster.display | def display(self, depth=0):
"""
Pretty-prints this cluster. Useful for debuging.
"""
print(depth * " " + "[level %s]" % self.level)
for item in self.items:
if isinstance(item, Cluster):
item.display(depth + 1)
else:
print... | python | def display(self, depth=0):
"""
Pretty-prints this cluster. Useful for debuging.
"""
print(depth * " " + "[level %s]" % self.level)
for item in self.items:
if isinstance(item, Cluster):
item.display(depth + 1)
else:
print... | [
"def",
"display",
"(",
"self",
",",
"depth",
"=",
"0",
")",
":",
"print",
"(",
"depth",
"*",
"\" \"",
"+",
"\"[level %s]\"",
"%",
"self",
".",
"level",
")",
"for",
"item",
"in",
"self",
".",
"items",
":",
"if",
"isinstance",
"(",
"item",
",",
"C... | Pretty-prints this cluster. Useful for debuging. | [
"Pretty",
"-",
"prints",
"this",
"cluster",
".",
"Useful",
"for",
"debuging",
"."
] | 4c0ac14d9beafcd51f0d849151514083c296402f | https://github.com/exhuma/python-cluster/blob/4c0ac14d9beafcd51f0d849151514083c296402f/cluster/cluster.py#L63-L72 | train | 61,058 |
exhuma/python-cluster | cluster/cluster.py | Cluster.getlevel | def getlevel(self, threshold):
"""
Retrieve all clusters up to a specific level threshold. This
level-threshold represents the maximum distance between two clusters.
So the lower you set this threshold, the more clusters you will
receive and the higher you set it, you will receiv... | python | def getlevel(self, threshold):
"""
Retrieve all clusters up to a specific level threshold. This
level-threshold represents the maximum distance between two clusters.
So the lower you set this threshold, the more clusters you will
receive and the higher you set it, you will receiv... | [
"def",
"getlevel",
"(",
"self",
",",
"threshold",
")",
":",
"left",
"=",
"self",
".",
"items",
"[",
"0",
"]",
"right",
"=",
"self",
".",
"items",
"[",
"1",
"]",
"# if this object itself is below the threshold value we only need to",
"# return it's contents as a list... | Retrieve all clusters up to a specific level threshold. This
level-threshold represents the maximum distance between two clusters.
So the lower you set this threshold, the more clusters you will
receive and the higher you set it, you will receive less but bigger
clusters.
:param... | [
"Retrieve",
"all",
"clusters",
"up",
"to",
"a",
"specific",
"level",
"threshold",
".",
"This",
"level",
"-",
"threshold",
"represents",
"the",
"maximum",
"distance",
"between",
"two",
"clusters",
".",
"So",
"the",
"lower",
"you",
"set",
"this",
"threshold",
... | 4c0ac14d9beafcd51f0d849151514083c296402f | https://github.com/exhuma/python-cluster/blob/4c0ac14d9beafcd51f0d849151514083c296402f/cluster/cluster.py#L111-L162 | train | 61,059 |
tikitu/jsmin | jsmin/__init__.py | jsmin | def jsmin(js, **kwargs):
"""
returns a minified version of the javascript string
"""
if not is_3:
if cStringIO and not isinstance(js, unicode):
# strings can use cStringIO for a 3x performance
# improvement, but unicode (in python2) cannot
klass = cStr... | python | def jsmin(js, **kwargs):
"""
returns a minified version of the javascript string
"""
if not is_3:
if cStringIO and not isinstance(js, unicode):
# strings can use cStringIO for a 3x performance
# improvement, but unicode (in python2) cannot
klass = cStr... | [
"def",
"jsmin",
"(",
"js",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"is_3",
":",
"if",
"cStringIO",
"and",
"not",
"isinstance",
"(",
"js",
",",
"unicode",
")",
":",
"# strings can use cStringIO for a 3x performance",
"# improvement, but unicode (in python2)... | returns a minified version of the javascript string | [
"returns",
"a",
"minified",
"version",
"of",
"the",
"javascript",
"string"
] | e87a6f3b1490e2643cbcdef77e41840c94f9e788 | https://github.com/tikitu/jsmin/blob/e87a6f3b1490e2643cbcdef77e41840c94f9e788/jsmin/__init__.py#L45-L61 | train | 61,060 |
exhuma/python-cluster | cluster/linkage.py | cached | def cached(fun):
"""
memoizing decorator for linkage functions.
Parameters have been hardcoded (no ``*args``, ``**kwargs`` magic), because,
the way this is coded (interchangingly using sets and frozensets) is true
for this specific case. For other cases that is not necessarily guaranteed.
"""
... | python | def cached(fun):
"""
memoizing decorator for linkage functions.
Parameters have been hardcoded (no ``*args``, ``**kwargs`` magic), because,
the way this is coded (interchangingly using sets and frozensets) is true
for this specific case. For other cases that is not necessarily guaranteed.
"""
... | [
"def",
"cached",
"(",
"fun",
")",
":",
"_cache",
"=",
"{",
"}",
"@",
"wraps",
"(",
"fun",
")",
"def",
"newfun",
"(",
"a",
",",
"b",
",",
"distance_function",
")",
":",
"frozen_a",
"=",
"frozenset",
"(",
"a",
")",
"frozen_b",
"=",
"frozenset",
"(",
... | memoizing decorator for linkage functions.
Parameters have been hardcoded (no ``*args``, ``**kwargs`` magic), because,
the way this is coded (interchangingly using sets and frozensets) is true
for this specific case. For other cases that is not necessarily guaranteed. | [
"memoizing",
"decorator",
"for",
"linkage",
"functions",
"."
] | 4c0ac14d9beafcd51f0d849151514083c296402f | https://github.com/exhuma/python-cluster/blob/4c0ac14d9beafcd51f0d849151514083c296402f/cluster/linkage.py#L5-L24 | train | 61,061 |
exhuma/python-cluster | cluster/linkage.py | single | def single(a, b, distance_function):
"""
Given two collections ``a`` and ``b``, this will return the distance of the
points which are closest together. ``distance_function`` is used to
determine the distance between two elements.
Example::
>>> single([1, 2], [3, 4], lambda x, y: abs(x-y))... | python | def single(a, b, distance_function):
"""
Given two collections ``a`` and ``b``, this will return the distance of the
points which are closest together. ``distance_function`` is used to
determine the distance between two elements.
Example::
>>> single([1, 2], [3, 4], lambda x, y: abs(x-y))... | [
"def",
"single",
"(",
"a",
",",
"b",
",",
"distance_function",
")",
":",
"left_a",
",",
"right_a",
"=",
"min",
"(",
"a",
")",
",",
"max",
"(",
"a",
")",
"left_b",
",",
"right_b",
"=",
"min",
"(",
"b",
")",
",",
"max",
"(",
"b",
")",
"result",
... | Given two collections ``a`` and ``b``, this will return the distance of the
points which are closest together. ``distance_function`` is used to
determine the distance between two elements.
Example::
>>> single([1, 2], [3, 4], lambda x, y: abs(x-y))
1 # (distance between 2 and 3) | [
"Given",
"two",
"collections",
"a",
"and",
"b",
"this",
"will",
"return",
"the",
"distance",
"of",
"the",
"points",
"which",
"are",
"closest",
"together",
".",
"distance_function",
"is",
"used",
"to",
"determine",
"the",
"distance",
"between",
"two",
"elements... | 4c0ac14d9beafcd51f0d849151514083c296402f | https://github.com/exhuma/python-cluster/blob/4c0ac14d9beafcd51f0d849151514083c296402f/cluster/linkage.py#L28-L43 | train | 61,062 |
exhuma/python-cluster | cluster/linkage.py | average | def average(a, b, distance_function):
"""
Given two collections ``a`` and ``b``, this will return the mean of all
distances. ``distance_function`` is used to determine the distance between
two elements.
Example::
>>> single([1, 2], [3, 100], lambda x, y: abs(x-y))
26
"""
di... | python | def average(a, b, distance_function):
"""
Given two collections ``a`` and ``b``, this will return the mean of all
distances. ``distance_function`` is used to determine the distance between
two elements.
Example::
>>> single([1, 2], [3, 100], lambda x, y: abs(x-y))
26
"""
di... | [
"def",
"average",
"(",
"a",
",",
"b",
",",
"distance_function",
")",
":",
"distances",
"=",
"[",
"distance_function",
"(",
"x",
",",
"y",
")",
"for",
"x",
"in",
"a",
"for",
"y",
"in",
"b",
"]",
"return",
"sum",
"(",
"distances",
")",
"/",
"len",
... | Given two collections ``a`` and ``b``, this will return the mean of all
distances. ``distance_function`` is used to determine the distance between
two elements.
Example::
>>> single([1, 2], [3, 100], lambda x, y: abs(x-y))
26 | [
"Given",
"two",
"collections",
"a",
"and",
"b",
"this",
"will",
"return",
"the",
"mean",
"of",
"all",
"distances",
".",
"distance_function",
"is",
"used",
"to",
"determine",
"the",
"distance",
"between",
"two",
"elements",
"."
] | 4c0ac14d9beafcd51f0d849151514083c296402f | https://github.com/exhuma/python-cluster/blob/4c0ac14d9beafcd51f0d849151514083c296402f/cluster/linkage.py#L66-L79 | train | 61,063 |
exhuma/python-cluster | cluster/matrix.py | Matrix.worker | def worker(self):
"""
Multiprocessing task function run by worker processes
"""
tasks_completed = 0
for task in iter(self.task_queue.get, 'STOP'):
col_index, item, item2 = task
if not hasattr(item, '__iter__') or isinstance(item, tuple):
it... | python | def worker(self):
"""
Multiprocessing task function run by worker processes
"""
tasks_completed = 0
for task in iter(self.task_queue.get, 'STOP'):
col_index, item, item2 = task
if not hasattr(item, '__iter__') or isinstance(item, tuple):
it... | [
"def",
"worker",
"(",
"self",
")",
":",
"tasks_completed",
"=",
"0",
"for",
"task",
"in",
"iter",
"(",
"self",
".",
"task_queue",
".",
"get",
",",
"'STOP'",
")",
":",
"col_index",
",",
"item",
",",
"item2",
"=",
"task",
"if",
"not",
"hasattr",
"(",
... | Multiprocessing task function run by worker processes | [
"Multiprocessing",
"task",
"function",
"run",
"by",
"worker",
"processes"
] | 4c0ac14d9beafcd51f0d849151514083c296402f | https://github.com/exhuma/python-cluster/blob/4c0ac14d9beafcd51f0d849151514083c296402f/cluster/matrix.py#L89-L105 | train | 61,064 |
exhuma/python-cluster | cluster/matrix.py | Matrix.genmatrix | def genmatrix(self, num_processes=1):
"""
Actually generate the matrix
:param num_processes: If you want to use multiprocessing to split up the
work and run ``combinfunc()`` in parallel, specify
``num_processes > 1`` and this number of workers will be spun up,
... | python | def genmatrix(self, num_processes=1):
"""
Actually generate the matrix
:param num_processes: If you want to use multiprocessing to split up the
work and run ``combinfunc()`` in parallel, specify
``num_processes > 1`` and this number of workers will be spun up,
... | [
"def",
"genmatrix",
"(",
"self",
",",
"num_processes",
"=",
"1",
")",
":",
"use_multiprocessing",
"=",
"num_processes",
">",
"1",
"if",
"use_multiprocessing",
":",
"self",
".",
"task_queue",
"=",
"Queue",
"(",
")",
"self",
".",
"done_queue",
"=",
"Queue",
... | Actually generate the matrix
:param num_processes: If you want to use multiprocessing to split up the
work and run ``combinfunc()`` in parallel, specify
``num_processes > 1`` and this number of workers will be spun up,
the work is split up amongst them evenly. | [
"Actually",
"generate",
"the",
"matrix"
] | 4c0ac14d9beafcd51f0d849151514083c296402f | https://github.com/exhuma/python-cluster/blob/4c0ac14d9beafcd51f0d849151514083c296402f/cluster/matrix.py#L107-L198 | train | 61,065 |
neurosnap/mudicom | mudicom/validation.py | validate | def validate(fname):
""" This function uses dciodvfy to generate
a list of warnings and errors discovered within
the DICOM file.
:param fname: Location and filename of DICOM file.
"""
validation = {
"errors": [],
"warnings": []
}
for line in _process(fname):
kind... | python | def validate(fname):
""" This function uses dciodvfy to generate
a list of warnings and errors discovered within
the DICOM file.
:param fname: Location and filename of DICOM file.
"""
validation = {
"errors": [],
"warnings": []
}
for line in _process(fname):
kind... | [
"def",
"validate",
"(",
"fname",
")",
":",
"validation",
"=",
"{",
"\"errors\"",
":",
"[",
"]",
",",
"\"warnings\"",
":",
"[",
"]",
"}",
"for",
"line",
"in",
"_process",
"(",
"fname",
")",
":",
"kind",
",",
"message",
"=",
"_determine",
"(",
"line",
... | This function uses dciodvfy to generate
a list of warnings and errors discovered within
the DICOM file.
:param fname: Location and filename of DICOM file. | [
"This",
"function",
"uses",
"dciodvfy",
"to",
"generate",
"a",
"list",
"of",
"warnings",
"and",
"errors",
"discovered",
"within",
"the",
"DICOM",
"file",
"."
] | 04011967007409f0c5253b4f308f53a7b0fc99c6 | https://github.com/neurosnap/mudicom/blob/04011967007409f0c5253b4f308f53a7b0fc99c6/mudicom/validation.py#L27-L42 | train | 61,066 |
neurosnap/mudicom | mudicom/image.py | Image.numpy | def numpy(self):
""" Grabs image data and converts it to a numpy array """
# load GDCM's image reading functionality
image_reader = gdcm.ImageReader()
image_reader.SetFileName(self.fname)
if not image_reader.Read():
raise IOError("Could not read DICOM image")
... | python | def numpy(self):
""" Grabs image data and converts it to a numpy array """
# load GDCM's image reading functionality
image_reader = gdcm.ImageReader()
image_reader.SetFileName(self.fname)
if not image_reader.Read():
raise IOError("Could not read DICOM image")
... | [
"def",
"numpy",
"(",
"self",
")",
":",
"# load GDCM's image reading functionality",
"image_reader",
"=",
"gdcm",
".",
"ImageReader",
"(",
")",
"image_reader",
".",
"SetFileName",
"(",
"self",
".",
"fname",
")",
"if",
"not",
"image_reader",
".",
"Read",
"(",
")... | Grabs image data and converts it to a numpy array | [
"Grabs",
"image",
"data",
"and",
"converts",
"it",
"to",
"a",
"numpy",
"array"
] | 04011967007409f0c5253b4f308f53a7b0fc99c6 | https://github.com/neurosnap/mudicom/blob/04011967007409f0c5253b4f308f53a7b0fc99c6/mudicom/image.py#L29-L37 | train | 61,067 |
neurosnap/mudicom | mudicom/image.py | Image._gdcm_to_numpy | def _gdcm_to_numpy(self, image):
""" Converts a GDCM image to a numpy array.
:param image: GDCM.ImageReader.GetImage()
"""
gdcm_typemap = {
gdcm.PixelFormat.INT8: numpy.int8,
gdcm.PixelFormat.UINT8: numpy.uint8,
gdcm.PixelFormat.UINT16: numpy... | python | def _gdcm_to_numpy(self, image):
""" Converts a GDCM image to a numpy array.
:param image: GDCM.ImageReader.GetImage()
"""
gdcm_typemap = {
gdcm.PixelFormat.INT8: numpy.int8,
gdcm.PixelFormat.UINT8: numpy.uint8,
gdcm.PixelFormat.UINT16: numpy... | [
"def",
"_gdcm_to_numpy",
"(",
"self",
",",
"image",
")",
":",
"gdcm_typemap",
"=",
"{",
"gdcm",
".",
"PixelFormat",
".",
"INT8",
":",
"numpy",
".",
"int8",
",",
"gdcm",
".",
"PixelFormat",
".",
"UINT8",
":",
"numpy",
".",
"uint8",
",",
"gdcm",
".",
"... | Converts a GDCM image to a numpy array.
:param image: GDCM.ImageReader.GetImage() | [
"Converts",
"a",
"GDCM",
"image",
"to",
"a",
"numpy",
"array",
"."
] | 04011967007409f0c5253b4f308f53a7b0fc99c6 | https://github.com/neurosnap/mudicom/blob/04011967007409f0c5253b4f308f53a7b0fc99c6/mudicom/image.py#L39-L77 | train | 61,068 |
neurosnap/mudicom | mudicom/image.py | Image.save_as_plt | def save_as_plt(self, fname, pixel_array=None, vmin=None, vmax=None,
cmap=None, format=None, origin=None):
""" This method saves the image from a numpy array using matplotlib
:param fname: Location and name of the image file to be saved.
:param pixel_array: Numpy pixel array, i.e. ``num... | python | def save_as_plt(self, fname, pixel_array=None, vmin=None, vmax=None,
cmap=None, format=None, origin=None):
""" This method saves the image from a numpy array using matplotlib
:param fname: Location and name of the image file to be saved.
:param pixel_array: Numpy pixel array, i.e. ``num... | [
"def",
"save_as_plt",
"(",
"self",
",",
"fname",
",",
"pixel_array",
"=",
"None",
",",
"vmin",
"=",
"None",
",",
"vmax",
"=",
"None",
",",
"cmap",
"=",
"None",
",",
"format",
"=",
"None",
",",
"origin",
"=",
"None",
")",
":",
"from",
"matplotlib",
... | This method saves the image from a numpy array using matplotlib
:param fname: Location and name of the image file to be saved.
:param pixel_array: Numpy pixel array, i.e. ``numpy()`` return value
:param vmin: matplotlib vmin
:param vmax: matplotlib vmax
:param cmap: matplotlib c... | [
"This",
"method",
"saves",
"the",
"image",
"from",
"a",
"numpy",
"array",
"using",
"matplotlib"
] | 04011967007409f0c5253b4f308f53a7b0fc99c6 | https://github.com/neurosnap/mudicom/blob/04011967007409f0c5253b4f308f53a7b0fc99c6/mudicom/image.py#L79-L108 | train | 61,069 |
neurosnap/mudicom | mudicom/base.py | Dicom.read | def read(self):
""" Returns array of dictionaries containing all the data elements in
the DICOM file.
"""
def ds(data_element):
value = self._str_filter.ToStringPair(data_element.GetTag())
if value[1]:
return DataElement(data_element, value[0].stri... | python | def read(self):
""" Returns array of dictionaries containing all the data elements in
the DICOM file.
"""
def ds(data_element):
value = self._str_filter.ToStringPair(data_element.GetTag())
if value[1]:
return DataElement(data_element, value[0].stri... | [
"def",
"read",
"(",
"self",
")",
":",
"def",
"ds",
"(",
"data_element",
")",
":",
"value",
"=",
"self",
".",
"_str_filter",
".",
"ToStringPair",
"(",
"data_element",
".",
"GetTag",
"(",
")",
")",
"if",
"value",
"[",
"1",
"]",
":",
"return",
"DataElem... | Returns array of dictionaries containing all the data elements in
the DICOM file. | [
"Returns",
"array",
"of",
"dictionaries",
"containing",
"all",
"the",
"data",
"elements",
"in",
"the",
"DICOM",
"file",
"."
] | 04011967007409f0c5253b4f308f53a7b0fc99c6 | https://github.com/neurosnap/mudicom/blob/04011967007409f0c5253b4f308f53a7b0fc99c6/mudicom/base.py#L101-L111 | train | 61,070 |
neurosnap/mudicom | mudicom/base.py | Dicom.walk | def walk(self, fn):
""" Loops through all data elements and allows a function to interact
with each data element. Uses a generator to improve iteration.
:param fn: Function that interacts with each DICOM element """
if not hasattr(fn, "__call__"):
raise TypeError("""walk_da... | python | def walk(self, fn):
""" Loops through all data elements and allows a function to interact
with each data element. Uses a generator to improve iteration.
:param fn: Function that interacts with each DICOM element """
if not hasattr(fn, "__call__"):
raise TypeError("""walk_da... | [
"def",
"walk",
"(",
"self",
",",
"fn",
")",
":",
"if",
"not",
"hasattr",
"(",
"fn",
",",
"\"__call__\"",
")",
":",
"raise",
"TypeError",
"(",
"\"\"\"walk_dataset requires a\n function as its parameter\"\"\"",
")",
"dataset",
"=",
"self",
".",
"_data... | Loops through all data elements and allows a function to interact
with each data element. Uses a generator to improve iteration.
:param fn: Function that interacts with each DICOM element | [
"Loops",
"through",
"all",
"data",
"elements",
"and",
"allows",
"a",
"function",
"to",
"interact",
"with",
"each",
"data",
"element",
".",
"Uses",
"a",
"generator",
"to",
"improve",
"iteration",
"."
] | 04011967007409f0c5253b4f308f53a7b0fc99c6 | https://github.com/neurosnap/mudicom/blob/04011967007409f0c5253b4f308f53a7b0fc99c6/mudicom/base.py#L113-L132 | train | 61,071 |
neurosnap/mudicom | mudicom/base.py | Dicom.find | def find(self, group=None, element=None, name=None, VR=None):
""" Searches for data elements in the DICOM file given the filters
supplied to this method.
:param group: Hex decimal for the group of a DICOM element e.g. 0x002
:param element: Hex decimal for the element value of a DICOM el... | python | def find(self, group=None, element=None, name=None, VR=None):
""" Searches for data elements in the DICOM file given the filters
supplied to this method.
:param group: Hex decimal for the group of a DICOM element e.g. 0x002
:param element: Hex decimal for the element value of a DICOM el... | [
"def",
"find",
"(",
"self",
",",
"group",
"=",
"None",
",",
"element",
"=",
"None",
",",
"name",
"=",
"None",
",",
"VR",
"=",
"None",
")",
":",
"results",
"=",
"self",
".",
"read",
"(",
")",
"if",
"name",
"is",
"not",
"None",
":",
"def",
"find_... | Searches for data elements in the DICOM file given the filters
supplied to this method.
:param group: Hex decimal for the group of a DICOM element e.g. 0x002
:param element: Hex decimal for the element value of a DICOM element e.g. 0x0010
:param name: Name of the DICOM element, e.g. "Mo... | [
"Searches",
"for",
"data",
"elements",
"in",
"the",
"DICOM",
"file",
"given",
"the",
"filters",
"supplied",
"to",
"this",
"method",
"."
] | 04011967007409f0c5253b4f308f53a7b0fc99c6 | https://github.com/neurosnap/mudicom/blob/04011967007409f0c5253b4f308f53a7b0fc99c6/mudicom/base.py#L134-L167 | train | 61,072 |
neurosnap/mudicom | mudicom/base.py | Dicom.anonymize | def anonymize(self):
""" According to PS 3.15-2008, basic application level
De-Indentification of a DICOM file requires replacing the values of a
set of data elements"""
self._anon_obj = gdcm.Anonymizer()
self._anon_obj.SetFile(self._file)
self._anon_obj.RemoveGroupLength... | python | def anonymize(self):
""" According to PS 3.15-2008, basic application level
De-Indentification of a DICOM file requires replacing the values of a
set of data elements"""
self._anon_obj = gdcm.Anonymizer()
self._anon_obj.SetFile(self._file)
self._anon_obj.RemoveGroupLength... | [
"def",
"anonymize",
"(",
"self",
")",
":",
"self",
".",
"_anon_obj",
"=",
"gdcm",
".",
"Anonymizer",
"(",
")",
"self",
".",
"_anon_obj",
".",
"SetFile",
"(",
"self",
".",
"_file",
")",
"self",
".",
"_anon_obj",
".",
"RemoveGroupLength",
"(",
")",
"if",... | According to PS 3.15-2008, basic application level
De-Indentification of a DICOM file requires replacing the values of a
set of data elements | [
"According",
"to",
"PS",
"3",
".",
"15",
"-",
"2008",
"basic",
"application",
"level",
"De",
"-",
"Indentification",
"of",
"a",
"DICOM",
"file",
"requires",
"replacing",
"the",
"values",
"of",
"a",
"set",
"of",
"data",
"elements"
] | 04011967007409f0c5253b4f308f53a7b0fc99c6 | https://github.com/neurosnap/mudicom/blob/04011967007409f0c5253b4f308f53a7b0fc99c6/mudicom/base.py#L169-L196 | train | 61,073 |
neurosnap/mudicom | mudicom/base.py | Dicom.image | def image(self):
""" Read the loaded DICOM image data """
if self._image is None:
self._image = Image(self.fname)
return self._image | python | def image(self):
""" Read the loaded DICOM image data """
if self._image is None:
self._image = Image(self.fname)
return self._image | [
"def",
"image",
"(",
"self",
")",
":",
"if",
"self",
".",
"_image",
"is",
"None",
":",
"self",
".",
"_image",
"=",
"Image",
"(",
"self",
".",
"fname",
")",
"return",
"self",
".",
"_image"
] | Read the loaded DICOM image data | [
"Read",
"the",
"loaded",
"DICOM",
"image",
"data"
] | 04011967007409f0c5253b4f308f53a7b0fc99c6 | https://github.com/neurosnap/mudicom/blob/04011967007409f0c5253b4f308f53a7b0fc99c6/mudicom/base.py#L220-L224 | train | 61,074 |
wdm0006/git-pandas | gitpandas/project.py | ProjectDirectory.repo_name | def repo_name(self):
"""
Returns a DataFrame of the repo names present in this project directory
:return: DataFrame
"""
ds = [[x.repo_name] for x in self.repos]
df = pd.DataFrame(ds, columns=['repository'])
return df | python | def repo_name(self):
"""
Returns a DataFrame of the repo names present in this project directory
:return: DataFrame
"""
ds = [[x.repo_name] for x in self.repos]
df = pd.DataFrame(ds, columns=['repository'])
return df | [
"def",
"repo_name",
"(",
"self",
")",
":",
"ds",
"=",
"[",
"[",
"x",
".",
"repo_name",
"]",
"for",
"x",
"in",
"self",
".",
"repos",
"]",
"df",
"=",
"pd",
".",
"DataFrame",
"(",
"ds",
",",
"columns",
"=",
"[",
"'repository'",
"]",
")",
"return",
... | Returns a DataFrame of the repo names present in this project directory
:return: DataFrame | [
"Returns",
"a",
"DataFrame",
"of",
"the",
"repo",
"names",
"present",
"in",
"this",
"project",
"directory"
] | e56b817b1d66b8296d1d5e703d5db0e181d25899 | https://github.com/wdm0006/git-pandas/blob/e56b817b1d66b8296d1d5e703d5db0e181d25899/gitpandas/project.py#L74-L84 | train | 61,075 |
rienafairefr/pynYNAB | pynYNAB/scripts/__main__.py | CsvImport.command | def command(self):
"""Manually import a CSV into a nYNAB budget"""
print('pynYNAB CSV import')
args = self.parser.parse_args()
verify_common_args(args)
verify_csvimport(args.schema, args.accountname)
client = clientfromkwargs(**args)
delta = do_csvimport(args, c... | python | def command(self):
"""Manually import a CSV into a nYNAB budget"""
print('pynYNAB CSV import')
args = self.parser.parse_args()
verify_common_args(args)
verify_csvimport(args.schema, args.accountname)
client = clientfromkwargs(**args)
delta = do_csvimport(args, c... | [
"def",
"command",
"(",
"self",
")",
":",
"print",
"(",
"'pynYNAB CSV import'",
")",
"args",
"=",
"self",
".",
"parser",
".",
"parse_args",
"(",
")",
"verify_common_args",
"(",
"args",
")",
"verify_csvimport",
"(",
"args",
".",
"schema",
",",
"args",
".",
... | Manually import a CSV into a nYNAB budget | [
"Manually",
"import",
"a",
"CSV",
"into",
"a",
"nYNAB",
"budget"
] | d5fc0749618409c6bb01cc2b93832cc59d780eaa | https://github.com/rienafairefr/pynYNAB/blob/d5fc0749618409c6bb01cc2b93832cc59d780eaa/pynYNAB/scripts/__main__.py#L82-L92 | train | 61,076 |
rienafairefr/pynYNAB | pynYNAB/scripts/__main__.py | OfxImport.command | def command(self):
"""Manually import an OFX into a nYNAB budget"""
print('pynYNAB OFX import')
args = self.parser.parse_args()
verify_common_args(args)
client = clientfromkwargs(**args)
delta = do_ofximport(args.file, client)
client.push(expected_delta=delta) | python | def command(self):
"""Manually import an OFX into a nYNAB budget"""
print('pynYNAB OFX import')
args = self.parser.parse_args()
verify_common_args(args)
client = clientfromkwargs(**args)
delta = do_ofximport(args.file, client)
client.push(expected_delta=delta) | [
"def",
"command",
"(",
"self",
")",
":",
"print",
"(",
"'pynYNAB OFX import'",
")",
"args",
"=",
"self",
".",
"parser",
".",
"parse_args",
"(",
")",
"verify_common_args",
"(",
"args",
")",
"client",
"=",
"clientfromkwargs",
"(",
"*",
"*",
"args",
")",
"d... | Manually import an OFX into a nYNAB budget | [
"Manually",
"import",
"an",
"OFX",
"into",
"a",
"nYNAB",
"budget"
] | d5fc0749618409c6bb01cc2b93832cc59d780eaa | https://github.com/rienafairefr/pynYNAB/blob/d5fc0749618409c6bb01cc2b93832cc59d780eaa/pynYNAB/scripts/__main__.py#L104-L113 | train | 61,077 |
rienafairefr/pynYNAB | pynYNAB/schema/Entity.py | default_listener | def default_listener(col_attr, default):
"""Establish a default-setting listener."""
@event.listens_for(col_attr, "init_scalar", retval=True, propagate=True)
def init_scalar(target, value, dict_):
if default.is_callable:
# the callable of ColumnDefault always accepts a context argument... | python | def default_listener(col_attr, default):
"""Establish a default-setting listener."""
@event.listens_for(col_attr, "init_scalar", retval=True, propagate=True)
def init_scalar(target, value, dict_):
if default.is_callable:
# the callable of ColumnDefault always accepts a context argument... | [
"def",
"default_listener",
"(",
"col_attr",
",",
"default",
")",
":",
"@",
"event",
".",
"listens_for",
"(",
"col_attr",
",",
"\"init_scalar\"",
",",
"retval",
"=",
"True",
",",
"propagate",
"=",
"True",
")",
"def",
"init_scalar",
"(",
"target",
",",
"valu... | Establish a default-setting listener. | [
"Establish",
"a",
"default",
"-",
"setting",
"listener",
"."
] | d5fc0749618409c6bb01cc2b93832cc59d780eaa | https://github.com/rienafairefr/pynYNAB/blob/d5fc0749618409c6bb01cc2b93832cc59d780eaa/pynYNAB/schema/Entity.py#L165-L182 | train | 61,078 |
wdm0006/git-pandas | gitpandas/repository.py | Repository.has_coverage | def has_coverage(self):
"""
Returns a boolean for is a parseable .coverage file can be found in the repository
:return: bool
"""
if os.path.exists(self.git_dir + os.sep + '.coverage'):
try:
with open(self.git_dir + os.sep + '.coverage', 'r') as f:
... | python | def has_coverage(self):
"""
Returns a boolean for is a parseable .coverage file can be found in the repository
:return: bool
"""
if os.path.exists(self.git_dir + os.sep + '.coverage'):
try:
with open(self.git_dir + os.sep + '.coverage', 'r') as f:
... | [
"def",
"has_coverage",
"(",
"self",
")",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"git_dir",
"+",
"os",
".",
"sep",
"+",
"'.coverage'",
")",
":",
"try",
":",
"with",
"open",
"(",
"self",
".",
"git_dir",
"+",
"os",
".",
"sep"... | Returns a boolean for is a parseable .coverage file can be found in the repository
:return: bool | [
"Returns",
"a",
"boolean",
"for",
"is",
"a",
"parseable",
".",
"coverage",
"file",
"can",
"be",
"found",
"in",
"the",
"repository"
] | e56b817b1d66b8296d1d5e703d5db0e181d25899 | https://github.com/wdm0006/git-pandas/blob/e56b817b1d66b8296d1d5e703d5db0e181d25899/gitpandas/repository.py#L109-L127 | train | 61,079 |
wdm0006/git-pandas | gitpandas/repository.py | Repository.__check_extension | def __check_extension(files, ignore_globs=None, include_globs=None):
"""
Internal method to filter a list of file changes by extension and ignore_dirs.
:param files:
:param ignore_globs: a list of globs to ignore (if none falls back to extensions and ignore_dir)
:param include_g... | python | def __check_extension(files, ignore_globs=None, include_globs=None):
"""
Internal method to filter a list of file changes by extension and ignore_dirs.
:param files:
:param ignore_globs: a list of globs to ignore (if none falls back to extensions and ignore_dir)
:param include_g... | [
"def",
"__check_extension",
"(",
"files",
",",
"ignore_globs",
"=",
"None",
",",
"include_globs",
"=",
"None",
")",
":",
"if",
"include_globs",
"is",
"None",
"or",
"include_globs",
"==",
"[",
"]",
":",
"include_globs",
"=",
"[",
"'*'",
"]",
"out",
"=",
"... | Internal method to filter a list of file changes by extension and ignore_dirs.
:param files:
:param ignore_globs: a list of globs to ignore (if none falls back to extensions and ignore_dir)
:param include_globs: a list of globs to include (if none, includes all).
:return: dict | [
"Internal",
"method",
"to",
"filter",
"a",
"list",
"of",
"file",
"changes",
"by",
"extension",
"and",
"ignore_dirs",
"."
] | e56b817b1d66b8296d1d5e703d5db0e181d25899 | https://github.com/wdm0006/git-pandas/blob/e56b817b1d66b8296d1d5e703d5db0e181d25899/gitpandas/repository.py#L489-L517 | train | 61,080 |
wdm0006/git-pandas | gitpandas/repository.py | Repository._repo_name | def _repo_name(self):
"""
Returns the name of the repository, using the local directory name.
:returns: str
"""
if self._git_repo_name is not None:
return self._git_repo_name
else:
reponame = self.repo.git_dir.split(os.sep)[-2]
if rep... | python | def _repo_name(self):
"""
Returns the name of the repository, using the local directory name.
:returns: str
"""
if self._git_repo_name is not None:
return self._git_repo_name
else:
reponame = self.repo.git_dir.split(os.sep)[-2]
if rep... | [
"def",
"_repo_name",
"(",
"self",
")",
":",
"if",
"self",
".",
"_git_repo_name",
"is",
"not",
"None",
":",
"return",
"self",
".",
"_git_repo_name",
"else",
":",
"reponame",
"=",
"self",
".",
"repo",
".",
"git_dir",
".",
"split",
"(",
"os",
".",
"sep",
... | Returns the name of the repository, using the local directory name.
:returns: str | [
"Returns",
"the",
"name",
"of",
"the",
"repository",
"using",
"the",
"local",
"directory",
"name",
"."
] | e56b817b1d66b8296d1d5e703d5db0e181d25899 | https://github.com/wdm0006/git-pandas/blob/e56b817b1d66b8296d1d5e703d5db0e181d25899/gitpandas/repository.py#L798-L811 | train | 61,081 |
beardypig/pymp4 | src/pymp4/parser.py | ISO6392TLanguageCode._decode | def _decode(self, obj, context):
"""
Get the python representation of the obj
"""
return b''.join(map(int2byte, [c + 0x60 for c in bytearray(obj)])).decode("utf8") | python | def _decode(self, obj, context):
"""
Get the python representation of the obj
"""
return b''.join(map(int2byte, [c + 0x60 for c in bytearray(obj)])).decode("utf8") | [
"def",
"_decode",
"(",
"self",
",",
"obj",
",",
"context",
")",
":",
"return",
"b''",
".",
"join",
"(",
"map",
"(",
"int2byte",
",",
"[",
"c",
"+",
"0x60",
"for",
"c",
"in",
"bytearray",
"(",
"obj",
")",
"]",
")",
")",
".",
"decode",
"(",
"\"ut... | Get the python representation of the obj | [
"Get",
"the",
"python",
"representation",
"of",
"the",
"obj"
] | 5f73f01def4ffea67847ee3062095ef3bae3f2d6 | https://github.com/beardypig/pymp4/blob/5f73f01def4ffea67847ee3062095ef3bae3f2d6/src/pymp4/parser.py#L234-L238 | train | 61,082 |
djangonauts/django-rest-framework-hstore | rest_framework_hstore/serializers.py | HStoreSerializer.update | def update(self, instance, validated_data):
"""
temporarily remove hstore virtual fields otherwise DRF considers them many2many
"""
model = self.Meta.model
meta = self.Meta.model._meta
original_virtual_fields = list(meta.virtual_fields) # copy
if hasattr(model, ... | python | def update(self, instance, validated_data):
"""
temporarily remove hstore virtual fields otherwise DRF considers them many2many
"""
model = self.Meta.model
meta = self.Meta.model._meta
original_virtual_fields = list(meta.virtual_fields) # copy
if hasattr(model, ... | [
"def",
"update",
"(",
"self",
",",
"instance",
",",
"validated_data",
")",
":",
"model",
"=",
"self",
".",
"Meta",
".",
"model",
"meta",
"=",
"self",
".",
"Meta",
".",
"model",
".",
"_meta",
"original_virtual_fields",
"=",
"list",
"(",
"meta",
".",
"vi... | temporarily remove hstore virtual fields otherwise DRF considers them many2many | [
"temporarily",
"remove",
"hstore",
"virtual",
"fields",
"otherwise",
"DRF",
"considers",
"them",
"many2many"
] | aef8b5446417640764f2fdf0684dc4a0d87a8507 | https://github.com/djangonauts/django-rest-framework-hstore/blob/aef8b5446417640764f2fdf0684dc4a0d87a8507/rest_framework_hstore/serializers.py#L107-L126 | train | 61,083 |
newville/wxmplot | wxmplot/imagepanel.py | ImagePanel.update_image | def update_image(self, data):
"""
update image on panel, as quickly as possible
"""
if 1 in data.shape:
data = data.squeeze()
if self.conf.contrast_level is not None:
clevels = [self.conf.contrast_level, 100.0-self.conf.contrast_level]
imin, im... | python | def update_image(self, data):
"""
update image on panel, as quickly as possible
"""
if 1 in data.shape:
data = data.squeeze()
if self.conf.contrast_level is not None:
clevels = [self.conf.contrast_level, 100.0-self.conf.contrast_level]
imin, im... | [
"def",
"update_image",
"(",
"self",
",",
"data",
")",
":",
"if",
"1",
"in",
"data",
".",
"shape",
":",
"data",
"=",
"data",
".",
"squeeze",
"(",
")",
"if",
"self",
".",
"conf",
".",
"contrast_level",
"is",
"not",
"None",
":",
"clevels",
"=",
"[",
... | update image on panel, as quickly as possible | [
"update",
"image",
"on",
"panel",
"as",
"quickly",
"as",
"possible"
] | 8e0dc037453e5cdf18c968dc5a3d29efd761edee | https://github.com/newville/wxmplot/blob/8e0dc037453e5cdf18c968dc5a3d29efd761edee/wxmplot/imagepanel.py#L156-L167 | train | 61,084 |
newville/wxmplot | wxmplot/imagepanel.py | ImagePanel.set_viewlimits | def set_viewlimits(self, axes=None):
""" update xy limits of a plot"""
if axes is None:
axes = self.axes
xmin, xmax, ymin, ymax = self.data_range
if len(self.conf.zoom_lims) >1:
zlims = self.conf.zoom_lims[-1]
if axes in zlims:
xmin, x... | python | def set_viewlimits(self, axes=None):
""" update xy limits of a plot"""
if axes is None:
axes = self.axes
xmin, xmax, ymin, ymax = self.data_range
if len(self.conf.zoom_lims) >1:
zlims = self.conf.zoom_lims[-1]
if axes in zlims:
xmin, x... | [
"def",
"set_viewlimits",
"(",
"self",
",",
"axes",
"=",
"None",
")",
":",
"if",
"axes",
"is",
"None",
":",
"axes",
"=",
"self",
".",
"axes",
"xmin",
",",
"xmax",
",",
"ymin",
",",
"ymax",
"=",
"self",
".",
"data_range",
"if",
"len",
"(",
"self",
... | update xy limits of a plot | [
"update",
"xy",
"limits",
"of",
"a",
"plot"
] | 8e0dc037453e5cdf18c968dc5a3d29efd761edee | https://github.com/newville/wxmplot/blob/8e0dc037453e5cdf18c968dc5a3d29efd761edee/wxmplot/imagepanel.py#L196-L231 | train | 61,085 |
newville/wxmplot | wxmplot/imagepanel.py | ImagePanel.zoom_leftup | def zoom_leftup(self, event=None):
"""leftup event handler for zoom mode in images"""
if self.zoom_ini is None:
return
ini_x, ini_y, ini_xd, ini_yd = self.zoom_ini
try:
dx = abs(ini_x - event.x)
dy = abs(ini_y - event.y)
except:
d... | python | def zoom_leftup(self, event=None):
"""leftup event handler for zoom mode in images"""
if self.zoom_ini is None:
return
ini_x, ini_y, ini_xd, ini_yd = self.zoom_ini
try:
dx = abs(ini_x - event.x)
dy = abs(ini_y - event.y)
except:
d... | [
"def",
"zoom_leftup",
"(",
"self",
",",
"event",
"=",
"None",
")",
":",
"if",
"self",
".",
"zoom_ini",
"is",
"None",
":",
"return",
"ini_x",
",",
"ini_y",
",",
"ini_xd",
",",
"ini_yd",
"=",
"self",
".",
"zoom_ini",
"try",
":",
"dx",
"=",
"abs",
"("... | leftup event handler for zoom mode in images | [
"leftup",
"event",
"handler",
"for",
"zoom",
"mode",
"in",
"images"
] | 8e0dc037453e5cdf18c968dc5a3d29efd761edee | https://github.com/newville/wxmplot/blob/8e0dc037453e5cdf18c968dc5a3d29efd761edee/wxmplot/imagepanel.py#L327-L370 | train | 61,086 |
benhoff/pluginmanager | pluginmanager/directory_manager.py | DirectoryManager.collect_directories | def collect_directories(self, directories):
"""
Collects all the directories into a `set` object.
If `self.recursive` is set to `True` this method will iterate through
and return all of the directories and the subdirectories found from
`directories` that are not blacklisted.
... | python | def collect_directories(self, directories):
"""
Collects all the directories into a `set` object.
If `self.recursive` is set to `True` this method will iterate through
and return all of the directories and the subdirectories found from
`directories` that are not blacklisted.
... | [
"def",
"collect_directories",
"(",
"self",
",",
"directories",
")",
":",
"directories",
"=",
"util",
".",
"to_absolute_paths",
"(",
"directories",
")",
"if",
"not",
"self",
".",
"recursive",
":",
"return",
"self",
".",
"_remove_blacklisted",
"(",
"directories",
... | Collects all the directories into a `set` object.
If `self.recursive` is set to `True` this method will iterate through
and return all of the directories and the subdirectories found from
`directories` that are not blacklisted.
if `self.recursive` is set to `False` this will return all... | [
"Collects",
"all",
"the",
"directories",
"into",
"a",
"set",
"object",
"."
] | a8a184f9ebfbb521703492cb88c1dbda4cd04c06 | https://github.com/benhoff/pluginmanager/blob/a8a184f9ebfbb521703492cb88c1dbda4cd04c06/pluginmanager/directory_manager.py#L47-L75 | train | 61,087 |
benhoff/pluginmanager | pluginmanager/directory_manager.py | DirectoryManager.remove_directories | def remove_directories(self, directories):
"""
Removes any `directories` from the set of plugin directories.
`directories` may be a single object or an iterable.
Recommend passing in all paths as absolute, but the method will
attemmpt to convert all paths to absolute if they ar... | python | def remove_directories(self, directories):
"""
Removes any `directories` from the set of plugin directories.
`directories` may be a single object or an iterable.
Recommend passing in all paths as absolute, but the method will
attemmpt to convert all paths to absolute if they ar... | [
"def",
"remove_directories",
"(",
"self",
",",
"directories",
")",
":",
"directories",
"=",
"util",
".",
"to_absolute_paths",
"(",
"directories",
")",
"self",
".",
"plugin_directories",
"=",
"util",
".",
"remove_from_set",
"(",
"self",
".",
"plugin_directories",
... | Removes any `directories` from the set of plugin directories.
`directories` may be a single object or an iterable.
Recommend passing in all paths as absolute, but the method will
attemmpt to convert all paths to absolute if they are not already
based on the current working directory. | [
"Removes",
"any",
"directories",
"from",
"the",
"set",
"of",
"plugin",
"directories",
"."
] | a8a184f9ebfbb521703492cb88c1dbda4cd04c06 | https://github.com/benhoff/pluginmanager/blob/a8a184f9ebfbb521703492cb88c1dbda4cd04c06/pluginmanager/directory_manager.py#L116-L128 | train | 61,088 |
benhoff/pluginmanager | pluginmanager/directory_manager.py | DirectoryManager.remove_blacklisted_directories | def remove_blacklisted_directories(self, directories):
"""
Attempts to remove the `directories` from the set of blacklisted
directories. If a particular directory is not found in the set of
blacklisted, method will continue on silently.
`directories` may be a single instance or ... | python | def remove_blacklisted_directories(self, directories):
"""
Attempts to remove the `directories` from the set of blacklisted
directories. If a particular directory is not found in the set of
blacklisted, method will continue on silently.
`directories` may be a single instance or ... | [
"def",
"remove_blacklisted_directories",
"(",
"self",
",",
"directories",
")",
":",
"directories",
"=",
"util",
".",
"to_absolute_paths",
"(",
"directories",
")",
"black_dirs",
"=",
"self",
".",
"blacklisted_directories",
"black_dirs",
"=",
"util",
".",
"remove_from... | Attempts to remove the `directories` from the set of blacklisted
directories. If a particular directory is not found in the set of
blacklisted, method will continue on silently.
`directories` may be a single instance or an iterable. Recommend
passing in absolute paths. Method will try t... | [
"Attempts",
"to",
"remove",
"the",
"directories",
"from",
"the",
"set",
"of",
"blacklisted",
"directories",
".",
"If",
"a",
"particular",
"directory",
"is",
"not",
"found",
"in",
"the",
"set",
"of",
"blacklisted",
"method",
"will",
"continue",
"on",
"silently"... | a8a184f9ebfbb521703492cb88c1dbda4cd04c06 | https://github.com/benhoff/pluginmanager/blob/a8a184f9ebfbb521703492cb88c1dbda4cd04c06/pluginmanager/directory_manager.py#L194-L206 | train | 61,089 |
benhoff/pluginmanager | pluginmanager/directory_manager.py | DirectoryManager._remove_blacklisted | def _remove_blacklisted(self, directories):
"""
Attempts to remove the blacklisted directories from `directories`
and then returns whatever is left in the set.
Called from the `collect_directories` method.
"""
directories = util.to_absolute_paths(directories)
dir... | python | def _remove_blacklisted(self, directories):
"""
Attempts to remove the blacklisted directories from `directories`
and then returns whatever is left in the set.
Called from the `collect_directories` method.
"""
directories = util.to_absolute_paths(directories)
dir... | [
"def",
"_remove_blacklisted",
"(",
"self",
",",
"directories",
")",
":",
"directories",
"=",
"util",
".",
"to_absolute_paths",
"(",
"directories",
")",
"directories",
"=",
"util",
".",
"remove_from_set",
"(",
"directories",
",",
"self",
".",
"blacklisted_directori... | Attempts to remove the blacklisted directories from `directories`
and then returns whatever is left in the set.
Called from the `collect_directories` method. | [
"Attempts",
"to",
"remove",
"the",
"blacklisted",
"directories",
"from",
"directories",
"and",
"then",
"returns",
"whatever",
"is",
"left",
"in",
"the",
"set",
"."
] | a8a184f9ebfbb521703492cb88c1dbda4cd04c06 | https://github.com/benhoff/pluginmanager/blob/a8a184f9ebfbb521703492cb88c1dbda4cd04c06/pluginmanager/directory_manager.py#L208-L219 | train | 61,090 |
newville/wxmplot | examples/tifffile.py | imread | def imread(filename, *args, **kwargs):
"""Return image data from TIFF file as numpy array.
The first image series is returned if no arguments are provided.
Parameters
----------
key : int, slice, or sequence of page indices
Defines which pages to return as array.
series : int
D... | python | def imread(filename, *args, **kwargs):
"""Return image data from TIFF file as numpy array.
The first image series is returned if no arguments are provided.
Parameters
----------
key : int, slice, or sequence of page indices
Defines which pages to return as array.
series : int
D... | [
"def",
"imread",
"(",
"filename",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"with",
"TIFFfile",
"(",
"filename",
")",
"as",
"tif",
":",
"return",
"tif",
".",
"asarray",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | Return image data from TIFF file as numpy array.
The first image series is returned if no arguments are provided.
Parameters
----------
key : int, slice, or sequence of page indices
Defines which pages to return as array.
series : int
Defines which series of pages to return as arra... | [
"Return",
"image",
"data",
"from",
"TIFF",
"file",
"as",
"numpy",
"array",
"."
] | 8e0dc037453e5cdf18c968dc5a3d29efd761edee | https://github.com/newville/wxmplot/blob/8e0dc037453e5cdf18c968dc5a3d29efd761edee/examples/tifffile.py#L384-L402 | train | 61,091 |
newville/wxmplot | examples/tifffile.py | read_nih_image_header | def read_nih_image_header(fd, byte_order, dtype, count):
"""Read NIH_IMAGE_HEADER tag from file and return as dictionary."""
fd.seek(12, 1)
return {'version': struct.unpack(byte_order+'H', fd.read(2))[0]} | python | def read_nih_image_header(fd, byte_order, dtype, count):
"""Read NIH_IMAGE_HEADER tag from file and return as dictionary."""
fd.seek(12, 1)
return {'version': struct.unpack(byte_order+'H', fd.read(2))[0]} | [
"def",
"read_nih_image_header",
"(",
"fd",
",",
"byte_order",
",",
"dtype",
",",
"count",
")",
":",
"fd",
".",
"seek",
"(",
"12",
",",
"1",
")",
"return",
"{",
"'version'",
":",
"struct",
".",
"unpack",
"(",
"byte_order",
"+",
"'H'",
",",
"fd",
".",
... | Read NIH_IMAGE_HEADER tag from file and return as dictionary. | [
"Read",
"NIH_IMAGE_HEADER",
"tag",
"from",
"file",
"and",
"return",
"as",
"dictionary",
"."
] | 8e0dc037453e5cdf18c968dc5a3d29efd761edee | https://github.com/newville/wxmplot/blob/8e0dc037453e5cdf18c968dc5a3d29efd761edee/examples/tifffile.py#L1398-L1401 | train | 61,092 |
newville/wxmplot | examples/tifffile.py | read_mm_header | def read_mm_header(fd, byte_order, dtype, count):
"""Read MM_HEADER tag from file and return as numpy.rec.array."""
return numpy.rec.fromfile(fd, MM_HEADER, 1, byteorder=byte_order)[0] | python | def read_mm_header(fd, byte_order, dtype, count):
"""Read MM_HEADER tag from file and return as numpy.rec.array."""
return numpy.rec.fromfile(fd, MM_HEADER, 1, byteorder=byte_order)[0] | [
"def",
"read_mm_header",
"(",
"fd",
",",
"byte_order",
",",
"dtype",
",",
"count",
")",
":",
"return",
"numpy",
".",
"rec",
".",
"fromfile",
"(",
"fd",
",",
"MM_HEADER",
",",
"1",
",",
"byteorder",
"=",
"byte_order",
")",
"[",
"0",
"]"
] | Read MM_HEADER tag from file and return as numpy.rec.array. | [
"Read",
"MM_HEADER",
"tag",
"from",
"file",
"and",
"return",
"as",
"numpy",
".",
"rec",
".",
"array",
"."
] | 8e0dc037453e5cdf18c968dc5a3d29efd761edee | https://github.com/newville/wxmplot/blob/8e0dc037453e5cdf18c968dc5a3d29efd761edee/examples/tifffile.py#L1404-L1406 | train | 61,093 |
newville/wxmplot | examples/tifffile.py | read_mm_uic1 | def read_mm_uic1(fd, byte_order, dtype, count):
"""Read MM_UIC1 tag from file and return as dictionary."""
t = fd.read(8*count)
t = struct.unpack('%s%iI' % (byte_order, 2*count), t)
return dict((MM_TAG_IDS[k], v) for k, v in zip(t[::2], t[1::2])
if k in MM_TAG_IDS) | python | def read_mm_uic1(fd, byte_order, dtype, count):
"""Read MM_UIC1 tag from file and return as dictionary."""
t = fd.read(8*count)
t = struct.unpack('%s%iI' % (byte_order, 2*count), t)
return dict((MM_TAG_IDS[k], v) for k, v in zip(t[::2], t[1::2])
if k in MM_TAG_IDS) | [
"def",
"read_mm_uic1",
"(",
"fd",
",",
"byte_order",
",",
"dtype",
",",
"count",
")",
":",
"t",
"=",
"fd",
".",
"read",
"(",
"8",
"*",
"count",
")",
"t",
"=",
"struct",
".",
"unpack",
"(",
"'%s%iI'",
"%",
"(",
"byte_order",
",",
"2",
"*",
"count"... | Read MM_UIC1 tag from file and return as dictionary. | [
"Read",
"MM_UIC1",
"tag",
"from",
"file",
"and",
"return",
"as",
"dictionary",
"."
] | 8e0dc037453e5cdf18c968dc5a3d29efd761edee | https://github.com/newville/wxmplot/blob/8e0dc037453e5cdf18c968dc5a3d29efd761edee/examples/tifffile.py#L1414-L1419 | train | 61,094 |
newville/wxmplot | examples/tifffile.py | read_mm_uic2 | def read_mm_uic2(fd, byte_order, dtype, count):
"""Read MM_UIC2 tag from file and return as dictionary."""
result = {'number_planes': count}
values = numpy.fromfile(fd, byte_order+'I', 6*count)
result['z_distance'] = values[0::6] // values[1::6]
#result['date_created'] = tuple(values[2::6])
#res... | python | def read_mm_uic2(fd, byte_order, dtype, count):
"""Read MM_UIC2 tag from file and return as dictionary."""
result = {'number_planes': count}
values = numpy.fromfile(fd, byte_order+'I', 6*count)
result['z_distance'] = values[0::6] // values[1::6]
#result['date_created'] = tuple(values[2::6])
#res... | [
"def",
"read_mm_uic2",
"(",
"fd",
",",
"byte_order",
",",
"dtype",
",",
"count",
")",
":",
"result",
"=",
"{",
"'number_planes'",
":",
"count",
"}",
"values",
"=",
"numpy",
".",
"fromfile",
"(",
"fd",
",",
"byte_order",
"+",
"'I'",
",",
"6",
"*",
"co... | Read MM_UIC2 tag from file and return as dictionary. | [
"Read",
"MM_UIC2",
"tag",
"from",
"file",
"and",
"return",
"as",
"dictionary",
"."
] | 8e0dc037453e5cdf18c968dc5a3d29efd761edee | https://github.com/newville/wxmplot/blob/8e0dc037453e5cdf18c968dc5a3d29efd761edee/examples/tifffile.py#L1422-L1431 | train | 61,095 |
newville/wxmplot | examples/tifffile.py | read_mm_uic3 | def read_mm_uic3(fd, byte_order, dtype, count):
"""Read MM_UIC3 tag from file and return as dictionary."""
t = numpy.fromfile(fd, byte_order+'I', 2*count)
return {'wavelengths': t[0::2] // t[1::2]} | python | def read_mm_uic3(fd, byte_order, dtype, count):
"""Read MM_UIC3 tag from file and return as dictionary."""
t = numpy.fromfile(fd, byte_order+'I', 2*count)
return {'wavelengths': t[0::2] // t[1::2]} | [
"def",
"read_mm_uic3",
"(",
"fd",
",",
"byte_order",
",",
"dtype",
",",
"count",
")",
":",
"t",
"=",
"numpy",
".",
"fromfile",
"(",
"fd",
",",
"byte_order",
"+",
"'I'",
",",
"2",
"*",
"count",
")",
"return",
"{",
"'wavelengths'",
":",
"t",
"[",
"0"... | Read MM_UIC3 tag from file and return as dictionary. | [
"Read",
"MM_UIC3",
"tag",
"from",
"file",
"and",
"return",
"as",
"dictionary",
"."
] | 8e0dc037453e5cdf18c968dc5a3d29efd761edee | https://github.com/newville/wxmplot/blob/8e0dc037453e5cdf18c968dc5a3d29efd761edee/examples/tifffile.py#L1434-L1437 | train | 61,096 |
newville/wxmplot | examples/tifffile.py | read_cz_lsm_info | def read_cz_lsm_info(fd, byte_order, dtype, count):
"""Read CS_LSM_INFO tag from file and return as numpy.rec.array."""
result = numpy.rec.fromfile(fd, CZ_LSM_INFO, 1,
byteorder=byte_order)[0]
{50350412: '1.3', 67127628: '2.0'}[result.magic_number] # validation
return re... | python | def read_cz_lsm_info(fd, byte_order, dtype, count):
"""Read CS_LSM_INFO tag from file and return as numpy.rec.array."""
result = numpy.rec.fromfile(fd, CZ_LSM_INFO, 1,
byteorder=byte_order)[0]
{50350412: '1.3', 67127628: '2.0'}[result.magic_number] # validation
return re... | [
"def",
"read_cz_lsm_info",
"(",
"fd",
",",
"byte_order",
",",
"dtype",
",",
"count",
")",
":",
"result",
"=",
"numpy",
".",
"rec",
".",
"fromfile",
"(",
"fd",
",",
"CZ_LSM_INFO",
",",
"1",
",",
"byteorder",
"=",
"byte_order",
")",
"[",
"0",
"]",
"{",... | Read CS_LSM_INFO tag from file and return as numpy.rec.array. | [
"Read",
"CS_LSM_INFO",
"tag",
"from",
"file",
"and",
"return",
"as",
"numpy",
".",
"rec",
".",
"array",
"."
] | 8e0dc037453e5cdf18c968dc5a3d29efd761edee | https://github.com/newville/wxmplot/blob/8e0dc037453e5cdf18c968dc5a3d29efd761edee/examples/tifffile.py#L1447-L1452 | train | 61,097 |
newville/wxmplot | examples/tifffile.py | read_cz_lsm_scan_info | def read_cz_lsm_scan_info(fd, byte_order):
"""Read LSM scan information from file and return as Record."""
block = Record()
blocks = [block]
unpack = struct.unpack
if 0x10000000 != struct.unpack(byte_order+"I", fd.read(4))[0]:
raise ValueError("not a lsm_scan_info structure")
fd.read(8)
... | python | def read_cz_lsm_scan_info(fd, byte_order):
"""Read LSM scan information from file and return as Record."""
block = Record()
blocks = [block]
unpack = struct.unpack
if 0x10000000 != struct.unpack(byte_order+"I", fd.read(4))[0]:
raise ValueError("not a lsm_scan_info structure")
fd.read(8)
... | [
"def",
"read_cz_lsm_scan_info",
"(",
"fd",
",",
"byte_order",
")",
":",
"block",
"=",
"Record",
"(",
")",
"blocks",
"=",
"[",
"block",
"]",
"unpack",
"=",
"struct",
".",
"unpack",
"if",
"0x10000000",
"!=",
"struct",
".",
"unpack",
"(",
"byte_order",
"+",... | Read LSM scan information from file and return as Record. | [
"Read",
"LSM",
"scan",
"information",
"from",
"file",
"and",
"return",
"as",
"Record",
"."
] | 8e0dc037453e5cdf18c968dc5a3d29efd761edee | https://github.com/newville/wxmplot/blob/8e0dc037453e5cdf18c968dc5a3d29efd761edee/examples/tifffile.py#L1476-L1514 | train | 61,098 |
newville/wxmplot | examples/tifffile.py | _replace_by | def _replace_by(module_function, warn=False):
"""Try replace decorated function by module.function."""
def decorate(func, module_function=module_function, warn=warn):
sys.path.append(os.path.dirname(__file__))
try:
module, function = module_function.split('.')
func, oldfu... | python | def _replace_by(module_function, warn=False):
"""Try replace decorated function by module.function."""
def decorate(func, module_function=module_function, warn=warn):
sys.path.append(os.path.dirname(__file__))
try:
module, function = module_function.split('.')
func, oldfu... | [
"def",
"_replace_by",
"(",
"module_function",
",",
"warn",
"=",
"False",
")",
":",
"def",
"decorate",
"(",
"func",
",",
"module_function",
"=",
"module_function",
",",
"warn",
"=",
"warn",
")",
":",
"sys",
".",
"path",
".",
"append",
"(",
"os",
".",
"p... | Try replace decorated function by module.function. | [
"Try",
"replace",
"decorated",
"function",
"by",
"module",
".",
"function",
"."
] | 8e0dc037453e5cdf18c968dc5a3d29efd761edee | https://github.com/newville/wxmplot/blob/8e0dc037453e5cdf18c968dc5a3d29efd761edee/examples/tifffile.py#L1517-L1531 | train | 61,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.