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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
RudolfCardinal/pythonlib | cardinal_pythonlib/platformfunc.py | validate_pair | def validate_pair(ob: Any) -> bool:
"""
Does the object have length 2?
"""
try:
if len(ob) != 2:
log.warning("Unexpected result: {!r}", ob)
raise ValueError()
except ValueError:
return False
return True | python | def validate_pair(ob: Any) -> bool:
"""
Does the object have length 2?
"""
try:
if len(ob) != 2:
log.warning("Unexpected result: {!r}", ob)
raise ValueError()
except ValueError:
return False
return True | [
"def",
"validate_pair",
"(",
"ob",
":",
"Any",
")",
"->",
"bool",
":",
"try",
":",
"if",
"len",
"(",
"ob",
")",
"!=",
"2",
":",
"log",
".",
"warning",
"(",
"\"Unexpected result: {!r}\"",
",",
"ob",
")",
"raise",
"ValueError",
"(",
")",
"except",
"Val... | Does the object have length 2? | [
"Does",
"the",
"object",
"have",
"length",
"2?"
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/platformfunc.py#L174-L184 | train | 53,300 |
RudolfCardinal/pythonlib | cardinal_pythonlib/email/mailboxpurge.py | clean_message | def clean_message(message: Message, topmost: bool = False) -> Message:
"""
Clean a message of all its binary parts.
This guts all binary attachments, and returns the message itself for
convenience.
"""
if message.is_multipart():
# Don't recurse in already-deleted attachments
if message.get_content_type() != 'message/external-body':
parts = message.get_payload()
parts[:] = map(clean_message, parts)
elif message_is_binary(message):
# Don't gut if this is the topmost message
if not topmost:
message = gut_message(message)
return message | python | def clean_message(message: Message, topmost: bool = False) -> Message:
"""
Clean a message of all its binary parts.
This guts all binary attachments, and returns the message itself for
convenience.
"""
if message.is_multipart():
# Don't recurse in already-deleted attachments
if message.get_content_type() != 'message/external-body':
parts = message.get_payload()
parts[:] = map(clean_message, parts)
elif message_is_binary(message):
# Don't gut if this is the topmost message
if not topmost:
message = gut_message(message)
return message | [
"def",
"clean_message",
"(",
"message",
":",
"Message",
",",
"topmost",
":",
"bool",
"=",
"False",
")",
"->",
"Message",
":",
"if",
"message",
".",
"is_multipart",
"(",
")",
":",
"# Don't recurse in already-deleted attachments",
"if",
"message",
".",
"get_conten... | Clean a message of all its binary parts.
This guts all binary attachments, and returns the message itself for
convenience. | [
"Clean",
"a",
"message",
"of",
"all",
"its",
"binary",
"parts",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/email/mailboxpurge.py#L80-L98 | train | 53,301 |
RudolfCardinal/pythonlib | cardinal_pythonlib/crypto.py | is_password_valid | def is_password_valid(plaintextpw: str, storedhash: str) -> bool:
"""
Checks if a plaintext password matches a stored hash.
Uses ``bcrypt``. The stored hash includes its own incorporated salt.
"""
# Upon CamCOPS from MySQL 5.5.34 (Ubuntu) to 5.1.71 (CentOS 6.5), the
# VARCHAR was retrieved as Unicode. We needed to convert that to a str.
# For Python 3 compatibility, we just str-convert everything, avoiding the
# unicode keyword, which no longer exists.
if storedhash is None:
storedhash = ""
storedhash = str(storedhash)
if plaintextpw is None:
plaintextpw = ""
plaintextpw = str(plaintextpw)
try:
h = bcrypt.hashpw(plaintextpw, storedhash)
except ValueError: # e.g. ValueError: invalid salt
return False
return h == storedhash | python | def is_password_valid(plaintextpw: str, storedhash: str) -> bool:
"""
Checks if a plaintext password matches a stored hash.
Uses ``bcrypt``. The stored hash includes its own incorporated salt.
"""
# Upon CamCOPS from MySQL 5.5.34 (Ubuntu) to 5.1.71 (CentOS 6.5), the
# VARCHAR was retrieved as Unicode. We needed to convert that to a str.
# For Python 3 compatibility, we just str-convert everything, avoiding the
# unicode keyword, which no longer exists.
if storedhash is None:
storedhash = ""
storedhash = str(storedhash)
if plaintextpw is None:
plaintextpw = ""
plaintextpw = str(plaintextpw)
try:
h = bcrypt.hashpw(plaintextpw, storedhash)
except ValueError: # e.g. ValueError: invalid salt
return False
return h == storedhash | [
"def",
"is_password_valid",
"(",
"plaintextpw",
":",
"str",
",",
"storedhash",
":",
"str",
")",
"->",
"bool",
":",
"# Upon CamCOPS from MySQL 5.5.34 (Ubuntu) to 5.1.71 (CentOS 6.5), the",
"# VARCHAR was retrieved as Unicode. We needed to convert that to a str.",
"# For Python 3 compa... | Checks if a plaintext password matches a stored hash.
Uses ``bcrypt``. The stored hash includes its own incorporated salt. | [
"Checks",
"if",
"a",
"plaintext",
"password",
"matches",
"a",
"stored",
"hash",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/crypto.py#L56-L76 | train | 53,302 |
JohnVinyard/featureflow | featureflow/extractor.py | FunctionalNode.version | def version(self):
"""
Compute the version identifier for this functional node using the
func code and local names. Optionally, also allow closed-over variable
values to affect the version number when closure_fingerprint is
specified
"""
try:
f = self.func.__call__.__code__
except AttributeError:
f = self.func.__code__
h = md5()
h.update(f.co_code)
h.update(str(f.co_names).encode())
try:
closure = self.func.__closure__
except AttributeError:
return h.hexdigest()
if closure is None or self.closure_fingerprint is None:
return h.hexdigest()
d = dict(
(name, cell.cell_contents)
for name, cell in zip(f.co_freevars, closure))
h.update(self.closure_fingerprint(d).encode())
return h.hexdigest() | python | def version(self):
"""
Compute the version identifier for this functional node using the
func code and local names. Optionally, also allow closed-over variable
values to affect the version number when closure_fingerprint is
specified
"""
try:
f = self.func.__call__.__code__
except AttributeError:
f = self.func.__code__
h = md5()
h.update(f.co_code)
h.update(str(f.co_names).encode())
try:
closure = self.func.__closure__
except AttributeError:
return h.hexdigest()
if closure is None or self.closure_fingerprint is None:
return h.hexdigest()
d = dict(
(name, cell.cell_contents)
for name, cell in zip(f.co_freevars, closure))
h.update(self.closure_fingerprint(d).encode())
return h.hexdigest() | [
"def",
"version",
"(",
"self",
")",
":",
"try",
":",
"f",
"=",
"self",
".",
"func",
".",
"__call__",
".",
"__code__",
"except",
"AttributeError",
":",
"f",
"=",
"self",
".",
"func",
".",
"__code__",
"h",
"=",
"md5",
"(",
")",
"h",
".",
"update",
... | Compute the version identifier for this functional node using the
func code and local names. Optionally, also allow closed-over variable
values to affect the version number when closure_fingerprint is
specified | [
"Compute",
"the",
"version",
"identifier",
"for",
"this",
"functional",
"node",
"using",
"the",
"func",
"code",
"and",
"local",
"names",
".",
"Optionally",
"also",
"allow",
"closed",
"-",
"over",
"variable",
"values",
"to",
"affect",
"the",
"version",
"number"... | 7731487b00e38fa4f58c88b7881870fda2d69fdb | https://github.com/JohnVinyard/featureflow/blob/7731487b00e38fa4f58c88b7881870fda2d69fdb/featureflow/extractor.py#L189-L218 | train | 53,303 |
meyersj/geotweet | geotweet/mapreduce/state_county_wordcount.py | StateCountyWordCountJob.mapper_init | def mapper_init(self):
""" Download counties geojson from S3 and build spatial index and cache """
self.counties = CachedCountyLookup(precision=GEOHASH_PRECISION)
self.extractor = WordExtractor() | python | def mapper_init(self):
""" Download counties geojson from S3 and build spatial index and cache """
self.counties = CachedCountyLookup(precision=GEOHASH_PRECISION)
self.extractor = WordExtractor() | [
"def",
"mapper_init",
"(",
"self",
")",
":",
"self",
".",
"counties",
"=",
"CachedCountyLookup",
"(",
"precision",
"=",
"GEOHASH_PRECISION",
")",
"self",
".",
"extractor",
"=",
"WordExtractor",
"(",
")"
] | Download counties geojson from S3 and build spatial index and cache | [
"Download",
"counties",
"geojson",
"from",
"S3",
"and",
"build",
"spatial",
"index",
"and",
"cache"
] | 1a6b55f98adf34d1b91f172d9187d599616412d9 | https://github.com/meyersj/geotweet/blob/1a6b55f98adf34d1b91f172d9187d599616412d9/geotweet/mapreduce/state_county_wordcount.py#L60-L63 | train | 53,304 |
meyersj/geotweet | geotweet/geomongo/__init__.py | GeoMongo.run | def run(self):
""" Top level runner to load State and County GeoJSON files into Mongo DB """
logging.info("Starting GeoJSON MongoDB loading process.")
mongo = dict(uri=self.mongo, db=self.db, collection=self.collection)
self.load(self.source, **mongo)
logging.info("Finished loading {0} into MongoDB".format(self.source)) | python | def run(self):
""" Top level runner to load State and County GeoJSON files into Mongo DB """
logging.info("Starting GeoJSON MongoDB loading process.")
mongo = dict(uri=self.mongo, db=self.db, collection=self.collection)
self.load(self.source, **mongo)
logging.info("Finished loading {0} into MongoDB".format(self.source)) | [
"def",
"run",
"(",
"self",
")",
":",
"logging",
".",
"info",
"(",
"\"Starting GeoJSON MongoDB loading process.\"",
")",
"mongo",
"=",
"dict",
"(",
"uri",
"=",
"self",
".",
"mongo",
",",
"db",
"=",
"self",
".",
"db",
",",
"collection",
"=",
"self",
".",
... | Top level runner to load State and County GeoJSON files into Mongo DB | [
"Top",
"level",
"runner",
"to",
"load",
"State",
"and",
"County",
"GeoJSON",
"files",
"into",
"Mongo",
"DB"
] | 1a6b55f98adf34d1b91f172d9187d599616412d9 | https://github.com/meyersj/geotweet/blob/1a6b55f98adf34d1b91f172d9187d599616412d9/geotweet/geomongo/__init__.py#L19-L24 | train | 53,305 |
meyersj/geotweet | geotweet/geomongo/__init__.py | GeoMongo.load | def load(self, geojson, uri=None, db=None, collection=None):
""" Load geojson file into mongodb instance """
logging.info("Mongo URI: {0}".format(uri))
logging.info("Mongo DB: {0}".format(db))
logging.info("Mongo Collection: {0}".format(collection))
logging.info("Geojson File to be loaded: {0}".format(geojson))
mongo = MongoGeo(db=db, collection=collection, uri=uri)
GeoJSONLoader().load(geojson, mongo.insert) | python | def load(self, geojson, uri=None, db=None, collection=None):
""" Load geojson file into mongodb instance """
logging.info("Mongo URI: {0}".format(uri))
logging.info("Mongo DB: {0}".format(db))
logging.info("Mongo Collection: {0}".format(collection))
logging.info("Geojson File to be loaded: {0}".format(geojson))
mongo = MongoGeo(db=db, collection=collection, uri=uri)
GeoJSONLoader().load(geojson, mongo.insert) | [
"def",
"load",
"(",
"self",
",",
"geojson",
",",
"uri",
"=",
"None",
",",
"db",
"=",
"None",
",",
"collection",
"=",
"None",
")",
":",
"logging",
".",
"info",
"(",
"\"Mongo URI: {0}\"",
".",
"format",
"(",
"uri",
")",
")",
"logging",
".",
"info",
"... | Load geojson file into mongodb instance | [
"Load",
"geojson",
"file",
"into",
"mongodb",
"instance"
] | 1a6b55f98adf34d1b91f172d9187d599616412d9 | https://github.com/meyersj/geotweet/blob/1a6b55f98adf34d1b91f172d9187d599616412d9/geotweet/geomongo/__init__.py#L26-L33 | train | 53,306 |
DCOD-OpenSource/django-project-version | djversion/utils.py | get_version | def get_version():
"""
Return formatted version string.
Returns:
str: string with project version or empty string.
"""
if all([VERSION, UPDATED, any([isinstance(UPDATED, date), isinstance(UPDATED, datetime), ]), ]):
return FORMAT_STRING.format(**{"version": VERSION, "updated": UPDATED, })
elif VERSION:
return VERSION
elif UPDATED:
return localize(UPDATED) if any([isinstance(UPDATED, date), isinstance(UPDATED, datetime), ]) else ""
else:
return "" | python | def get_version():
"""
Return formatted version string.
Returns:
str: string with project version or empty string.
"""
if all([VERSION, UPDATED, any([isinstance(UPDATED, date), isinstance(UPDATED, datetime), ]), ]):
return FORMAT_STRING.format(**{"version": VERSION, "updated": UPDATED, })
elif VERSION:
return VERSION
elif UPDATED:
return localize(UPDATED) if any([isinstance(UPDATED, date), isinstance(UPDATED, datetime), ]) else ""
else:
return "" | [
"def",
"get_version",
"(",
")",
":",
"if",
"all",
"(",
"[",
"VERSION",
",",
"UPDATED",
",",
"any",
"(",
"[",
"isinstance",
"(",
"UPDATED",
",",
"date",
")",
",",
"isinstance",
"(",
"UPDATED",
",",
"datetime",
")",
",",
"]",
")",
",",
"]",
")",
":... | Return formatted version string.
Returns:
str: string with project version or empty string. | [
"Return",
"formatted",
"version",
"string",
"."
] | 5fc63609cdf0cb2777f9e9155aa88f443e252b71 | https://github.com/DCOD-OpenSource/django-project-version/blob/5fc63609cdf0cb2777f9e9155aa88f443e252b71/djversion/utils.py#L25-L44 | train | 53,307 |
RudolfCardinal/pythonlib | cardinal_pythonlib/openxml/find_recovered_openxml.py | process_file | def process_file(filename: str,
filetypes: List[str],
move_to: str,
delete_if_not_specified_file_type: bool,
show_zip_output: bool) -> None:
"""
Deals with an OpenXML, including if it is potentially corrupted.
Args:
filename: filename to process
filetypes: list of filetypes that we care about, e.g.
``['docx', 'pptx', 'xlsx']``.
move_to: move matching files to this directory
delete_if_not_specified_file_type: if ``True``, and the file is **not**
a type specified in ``filetypes``, then delete the file.
show_zip_output: show the output from the external ``zip`` tool?
"""
# log.critical("process_file: start")
try:
reader = CorruptedOpenXmlReader(filename,
show_zip_output=show_zip_output)
if reader.file_type in filetypes:
log.info("Found {}: {}", reader.description, filename)
if move_to:
dest_file = os.path.join(move_to, os.path.basename(filename))
_, ext = os.path.splitext(dest_file)
if ext != reader.suggested_extension():
dest_file += reader.suggested_extension()
reader.move_to(destination_filename=dest_file)
else:
log.info("Unrecognized or unwanted contents: " + filename)
if delete_if_not_specified_file_type:
log.info("Deleting: " + filename)
os.remove(filename)
except Exception as e:
# Must explicitly catch and report errors, since otherwise they vanish
# into the ether.
log.critical("Uncaught error in subprocess: {!r}\n{}", e,
traceback.format_exc())
raise | python | def process_file(filename: str,
filetypes: List[str],
move_to: str,
delete_if_not_specified_file_type: bool,
show_zip_output: bool) -> None:
"""
Deals with an OpenXML, including if it is potentially corrupted.
Args:
filename: filename to process
filetypes: list of filetypes that we care about, e.g.
``['docx', 'pptx', 'xlsx']``.
move_to: move matching files to this directory
delete_if_not_specified_file_type: if ``True``, and the file is **not**
a type specified in ``filetypes``, then delete the file.
show_zip_output: show the output from the external ``zip`` tool?
"""
# log.critical("process_file: start")
try:
reader = CorruptedOpenXmlReader(filename,
show_zip_output=show_zip_output)
if reader.file_type in filetypes:
log.info("Found {}: {}", reader.description, filename)
if move_to:
dest_file = os.path.join(move_to, os.path.basename(filename))
_, ext = os.path.splitext(dest_file)
if ext != reader.suggested_extension():
dest_file += reader.suggested_extension()
reader.move_to(destination_filename=dest_file)
else:
log.info("Unrecognized or unwanted contents: " + filename)
if delete_if_not_specified_file_type:
log.info("Deleting: " + filename)
os.remove(filename)
except Exception as e:
# Must explicitly catch and report errors, since otherwise they vanish
# into the ether.
log.critical("Uncaught error in subprocess: {!r}\n{}", e,
traceback.format_exc())
raise | [
"def",
"process_file",
"(",
"filename",
":",
"str",
",",
"filetypes",
":",
"List",
"[",
"str",
"]",
",",
"move_to",
":",
"str",
",",
"delete_if_not_specified_file_type",
":",
"bool",
",",
"show_zip_output",
":",
"bool",
")",
"->",
"None",
":",
"# log.critica... | Deals with an OpenXML, including if it is potentially corrupted.
Args:
filename: filename to process
filetypes: list of filetypes that we care about, e.g.
``['docx', 'pptx', 'xlsx']``.
move_to: move matching files to this directory
delete_if_not_specified_file_type: if ``True``, and the file is **not**
a type specified in ``filetypes``, then delete the file.
show_zip_output: show the output from the external ``zip`` tool? | [
"Deals",
"with",
"an",
"OpenXML",
"including",
"if",
"it",
"is",
"potentially",
"corrupted",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/openxml/find_recovered_openxml.py#L294-L333 | train | 53,308 |
oxalorg/Stab | stab/watchman.py | Watchman.should_build | def should_build(self, fpath, meta):
"""
Checks if the file should be built or not
Only skips layouts which are tagged as INCREMENTAL
Rebuilds only those files with mtime changed since previous build
"""
if meta.get('layout', self.default_template) in self.inc_layout:
if self.prev_mtime.get(fpath, 0) == os.path.getmtime(fpath):
return False
else:
return True
return True | python | def should_build(self, fpath, meta):
"""
Checks if the file should be built or not
Only skips layouts which are tagged as INCREMENTAL
Rebuilds only those files with mtime changed since previous build
"""
if meta.get('layout', self.default_template) in self.inc_layout:
if self.prev_mtime.get(fpath, 0) == os.path.getmtime(fpath):
return False
else:
return True
return True | [
"def",
"should_build",
"(",
"self",
",",
"fpath",
",",
"meta",
")",
":",
"if",
"meta",
".",
"get",
"(",
"'layout'",
",",
"self",
".",
"default_template",
")",
"in",
"self",
".",
"inc_layout",
":",
"if",
"self",
".",
"prev_mtime",
".",
"get",
"(",
"fp... | Checks if the file should be built or not
Only skips layouts which are tagged as INCREMENTAL
Rebuilds only those files with mtime changed since previous build | [
"Checks",
"if",
"the",
"file",
"should",
"be",
"built",
"or",
"not",
"Only",
"skips",
"layouts",
"which",
"are",
"tagged",
"as",
"INCREMENTAL",
"Rebuilds",
"only",
"those",
"files",
"with",
"mtime",
"changed",
"since",
"previous",
"build"
] | 8f0ded780fd7a53a674835c9cb1b7ca08b98f562 | https://github.com/oxalorg/Stab/blob/8f0ded780fd7a53a674835c9cb1b7ca08b98f562/stab/watchman.py#L24-L35 | train | 53,309 |
calston/rhumba | rhumba/backends/redis.py | Backend.clusterQueues | def clusterQueues(self):
""" Return a dict of queues in cluster and servers running them
"""
servers = yield self.getClusterServers()
queues = {}
for sname in servers:
qs = yield self.get('rhumba.server.%s.queues' % sname)
uuid = yield self.get('rhumba.server.%s.uuid' % sname)
qs = json.loads(qs)
for q in qs:
if q not in queues:
queues[q] = []
queues[q].append({'host': sname, 'uuid': uuid})
defer.returnValue(queues) | python | def clusterQueues(self):
""" Return a dict of queues in cluster and servers running them
"""
servers = yield self.getClusterServers()
queues = {}
for sname in servers:
qs = yield self.get('rhumba.server.%s.queues' % sname)
uuid = yield self.get('rhumba.server.%s.uuid' % sname)
qs = json.loads(qs)
for q in qs:
if q not in queues:
queues[q] = []
queues[q].append({'host': sname, 'uuid': uuid})
defer.returnValue(queues) | [
"def",
"clusterQueues",
"(",
"self",
")",
":",
"servers",
"=",
"yield",
"self",
".",
"getClusterServers",
"(",
")",
"queues",
"=",
"{",
"}",
"for",
"sname",
"in",
"servers",
":",
"qs",
"=",
"yield",
"self",
".",
"get",
"(",
"'rhumba.server.%s.queues'",
"... | Return a dict of queues in cluster and servers running them | [
"Return",
"a",
"dict",
"of",
"queues",
"in",
"cluster",
"and",
"servers",
"running",
"them"
] | 05e3cbf4e531cc51b4777912eb98a4f006893f5e | https://github.com/calston/rhumba/blob/05e3cbf4e531cc51b4777912eb98a4f006893f5e/rhumba/backends/redis.py#L207-L226 | train | 53,310 |
avihad/twistes | twistes/client.py | Elasticsearch.close | def close(self):
"""
close all http connections.
returns a deferred that fires once they're all closed.
"""
def validate_client(client):
"""
Validate that the connection is for the current client
:param client:
:return:
"""
host, port = client.addr
parsed_url = urlparse(self._hostname)
return host == parsed_url.hostname and port == parsed_url.port
# read https://github.com/twisted/treq/issues/86
# to understand the following...
def _check_fds(_):
fds = set(reactor.getReaders() + reactor.getReaders())
if not [fd for fd in fds if isinstance(fd, Client) and validate_client(fd)]:
return
return deferLater(reactor, 0, _check_fds, None)
pool = self._async_http_client_params["pool"]
return pool.closeCachedConnections().addBoth(_check_fds) | python | def close(self):
"""
close all http connections.
returns a deferred that fires once they're all closed.
"""
def validate_client(client):
"""
Validate that the connection is for the current client
:param client:
:return:
"""
host, port = client.addr
parsed_url = urlparse(self._hostname)
return host == parsed_url.hostname and port == parsed_url.port
# read https://github.com/twisted/treq/issues/86
# to understand the following...
def _check_fds(_):
fds = set(reactor.getReaders() + reactor.getReaders())
if not [fd for fd in fds if isinstance(fd, Client) and validate_client(fd)]:
return
return deferLater(reactor, 0, _check_fds, None)
pool = self._async_http_client_params["pool"]
return pool.closeCachedConnections().addBoth(_check_fds) | [
"def",
"close",
"(",
"self",
")",
":",
"def",
"validate_client",
"(",
"client",
")",
":",
"\"\"\"\n Validate that the connection is for the current client\n :param client:\n :return:\n \"\"\"",
"host",
",",
"port",
"=",
"client",
".",
... | close all http connections.
returns a deferred that fires once they're all closed. | [
"close",
"all",
"http",
"connections",
".",
"returns",
"a",
"deferred",
"that",
"fires",
"once",
"they",
"re",
"all",
"closed",
"."
] | 9ab8f5aa088b8886aefe3dec85a400e5035e034a | https://github.com/avihad/twistes/blob/9ab8f5aa088b8886aefe3dec85a400e5035e034a/twistes/client.py#L666-L692 | train | 53,311 |
davenquinn/Attitude | attitude/helpers/dem.py | extract_line | def extract_line(geom, dem, **kwargs):
"""
Extract a linear feature from a `rasterio` geospatial dataset.
"""
kwargs.setdefault('masked', True)
coords_in = coords_array(geom)
# Transform geometry into pixels
f = lambda *x: ~dem.transform * x
px = transform(f,geom)
# Subdivide geometry segments if option is given
interval = kwargs.pop('subdivide', 1)
if interval is not None:
px = subdivide(px, interval=interval)
# Transform pixels back to geometry
# to capture subdivisions
f = lambda *x: dem.transform * (x[0],x[1])
geom = transform(f,px)
# Get min and max coords for windowing
# Does not deal with edge cases where points
# are outside of footprint of DEM
coords_px = coords_array(px)
mins = N.floor(coords_px.min(axis=0))
maxs = N.ceil(coords_px.max(axis=0))
window = tuple((int(mn),int(mx))
for mn,mx in zip(mins[::-1],maxs[::-1]))
aff = Affine.translation(*(-mins))
f = lambda *x: aff * x
px_to_extract = transform(f,px)
band = dem.read(1, window=window, **kwargs)
extracted = bilinear(band, px_to_extract)
coords = coords_array(extracted)
coords[:,:2] = coords_array(geom)
return coords | python | def extract_line(geom, dem, **kwargs):
"""
Extract a linear feature from a `rasterio` geospatial dataset.
"""
kwargs.setdefault('masked', True)
coords_in = coords_array(geom)
# Transform geometry into pixels
f = lambda *x: ~dem.transform * x
px = transform(f,geom)
# Subdivide geometry segments if option is given
interval = kwargs.pop('subdivide', 1)
if interval is not None:
px = subdivide(px, interval=interval)
# Transform pixels back to geometry
# to capture subdivisions
f = lambda *x: dem.transform * (x[0],x[1])
geom = transform(f,px)
# Get min and max coords for windowing
# Does not deal with edge cases where points
# are outside of footprint of DEM
coords_px = coords_array(px)
mins = N.floor(coords_px.min(axis=0))
maxs = N.ceil(coords_px.max(axis=0))
window = tuple((int(mn),int(mx))
for mn,mx in zip(mins[::-1],maxs[::-1]))
aff = Affine.translation(*(-mins))
f = lambda *x: aff * x
px_to_extract = transform(f,px)
band = dem.read(1, window=window, **kwargs)
extracted = bilinear(band, px_to_extract)
coords = coords_array(extracted)
coords[:,:2] = coords_array(geom)
return coords | [
"def",
"extract_line",
"(",
"geom",
",",
"dem",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
".",
"setdefault",
"(",
"'masked'",
",",
"True",
")",
"coords_in",
"=",
"coords_array",
"(",
"geom",
")",
"# Transform geometry into pixels",
"f",
"=",
"lambda",
"... | Extract a linear feature from a `rasterio` geospatial dataset. | [
"Extract",
"a",
"linear",
"feature",
"from",
"a",
"rasterio",
"geospatial",
"dataset",
"."
] | 2ce97b9aba0aa5deedc6617c2315e07e6396d240 | https://github.com/davenquinn/Attitude/blob/2ce97b9aba0aa5deedc6617c2315e07e6396d240/attitude/helpers/dem.py#L58-L101 | train | 53,312 |
calston/rhumba | rhumba/utils.py | fork | def fork(executable, args=(), env={}, path=None, timeout=3600):
"""fork
Provides a deferred wrapper function with a timeout function
:param executable: Executable
:type executable: str.
:param args: Tupple of arguments
:type args: tupple.
:param env: Environment dictionary
:type env: dict.
:param timeout: Kill the child process if timeout is exceeded
:type timeout: int.
"""
d = defer.Deferred()
p = ProcessProtocol(d, timeout)
reactor.spawnProcess(p, executable, (executable,)+tuple(args), env, path)
return d | python | def fork(executable, args=(), env={}, path=None, timeout=3600):
"""fork
Provides a deferred wrapper function with a timeout function
:param executable: Executable
:type executable: str.
:param args: Tupple of arguments
:type args: tupple.
:param env: Environment dictionary
:type env: dict.
:param timeout: Kill the child process if timeout is exceeded
:type timeout: int.
"""
d = defer.Deferred()
p = ProcessProtocol(d, timeout)
reactor.spawnProcess(p, executable, (executable,)+tuple(args), env, path)
return d | [
"def",
"fork",
"(",
"executable",
",",
"args",
"=",
"(",
")",
",",
"env",
"=",
"{",
"}",
",",
"path",
"=",
"None",
",",
"timeout",
"=",
"3600",
")",
":",
"d",
"=",
"defer",
".",
"Deferred",
"(",
")",
"p",
"=",
"ProcessProtocol",
"(",
"d",
",",
... | fork
Provides a deferred wrapper function with a timeout function
:param executable: Executable
:type executable: str.
:param args: Tupple of arguments
:type args: tupple.
:param env: Environment dictionary
:type env: dict.
:param timeout: Kill the child process if timeout is exceeded
:type timeout: int. | [
"fork",
"Provides",
"a",
"deferred",
"wrapper",
"function",
"with",
"a",
"timeout",
"function"
] | 05e3cbf4e531cc51b4777912eb98a4f006893f5e | https://github.com/calston/rhumba/blob/05e3cbf4e531cc51b4777912eb98a4f006893f5e/rhumba/utils.py#L52-L68 | train | 53,313 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_web.py | number_to_dp | def number_to_dp(number: Optional[float],
dp: int,
default: Optional[str] = "",
en_dash_for_minus: bool = True) -> str:
"""
Format number to ``dp`` decimal places, optionally using a UTF-8 en dash
for minus signs.
"""
if number is None:
return default
if number == float("inf"):
return u"∞"
if number == float("-inf"):
s = u"-∞"
else:
s = u"{:.{precision}f}".format(number, precision=dp)
if en_dash_for_minus:
s = s.replace("-", u"–") # hyphen becomes en dash for minus sign
return s | python | def number_to_dp(number: Optional[float],
dp: int,
default: Optional[str] = "",
en_dash_for_minus: bool = True) -> str:
"""
Format number to ``dp`` decimal places, optionally using a UTF-8 en dash
for minus signs.
"""
if number is None:
return default
if number == float("inf"):
return u"∞"
if number == float("-inf"):
s = u"-∞"
else:
s = u"{:.{precision}f}".format(number, precision=dp)
if en_dash_for_minus:
s = s.replace("-", u"–") # hyphen becomes en dash for minus sign
return s | [
"def",
"number_to_dp",
"(",
"number",
":",
"Optional",
"[",
"float",
"]",
",",
"dp",
":",
"int",
",",
"default",
":",
"Optional",
"[",
"str",
"]",
"=",
"\"\"",
",",
"en_dash_for_minus",
":",
"bool",
"=",
"True",
")",
"->",
"str",
":",
"if",
"number",... | Format number to ``dp`` decimal places, optionally using a UTF-8 en dash
for minus signs. | [
"Format",
"number",
"to",
"dp",
"decimal",
"places",
"optionally",
"using",
"a",
"UTF",
"-",
"8",
"en",
"dash",
"for",
"minus",
"signs",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_web.py#L109-L127 | train | 53,314 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_web.py | debug_form_contents | def debug_form_contents(form: cgi.FieldStorage,
to_stderr: bool = True,
to_logger: bool = False) -> None:
"""
Writes the keys and values of a CGI form to ``stderr``.
"""
for k in form.keys():
text = "{0} = {1}".format(k, form.getvalue(k))
if to_stderr:
sys.stderr.write(text)
if to_logger:
log.info(text) | python | def debug_form_contents(form: cgi.FieldStorage,
to_stderr: bool = True,
to_logger: bool = False) -> None:
"""
Writes the keys and values of a CGI form to ``stderr``.
"""
for k in form.keys():
text = "{0} = {1}".format(k, form.getvalue(k))
if to_stderr:
sys.stderr.write(text)
if to_logger:
log.info(text) | [
"def",
"debug_form_contents",
"(",
"form",
":",
"cgi",
".",
"FieldStorage",
",",
"to_stderr",
":",
"bool",
"=",
"True",
",",
"to_logger",
":",
"bool",
"=",
"False",
")",
"->",
"None",
":",
"for",
"k",
"in",
"form",
".",
"keys",
"(",
")",
":",
"text",... | Writes the keys and values of a CGI form to ``stderr``. | [
"Writes",
"the",
"keys",
"and",
"values",
"of",
"a",
"CGI",
"form",
"to",
"stderr",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_web.py#L134-L145 | train | 53,315 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_web.py | cgi_method_is_post | def cgi_method_is_post(environ: Dict[str, str]) -> bool:
"""
Determines if the CGI method was ``POST``, given the CGI environment.
"""
method = environ.get("REQUEST_METHOD", None)
if not method:
return False
return method.upper() == "POST" | python | def cgi_method_is_post(environ: Dict[str, str]) -> bool:
"""
Determines if the CGI method was ``POST``, given the CGI environment.
"""
method = environ.get("REQUEST_METHOD", None)
if not method:
return False
return method.upper() == "POST" | [
"def",
"cgi_method_is_post",
"(",
"environ",
":",
"Dict",
"[",
"str",
",",
"str",
"]",
")",
"->",
"bool",
":",
"method",
"=",
"environ",
".",
"get",
"(",
"\"REQUEST_METHOD\"",
",",
"None",
")",
"if",
"not",
"method",
":",
"return",
"False",
"return",
"... | Determines if the CGI method was ``POST``, given the CGI environment. | [
"Determines",
"if",
"the",
"CGI",
"method",
"was",
"POST",
"given",
"the",
"CGI",
"environment",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_web.py#L149-L156 | train | 53,316 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_web.py | get_cgi_parameter_str_or_none | def get_cgi_parameter_str_or_none(form: cgi.FieldStorage,
key: str) -> Optional[str]:
"""
Extracts a string parameter from a CGI form, or ``None`` if the key doesn't
exist or the string is zero-length.
"""
s = get_cgi_parameter_str(form, key)
if s is None or len(s) == 0:
return None
return s | python | def get_cgi_parameter_str_or_none(form: cgi.FieldStorage,
key: str) -> Optional[str]:
"""
Extracts a string parameter from a CGI form, or ``None`` if the key doesn't
exist or the string is zero-length.
"""
s = get_cgi_parameter_str(form, key)
if s is None or len(s) == 0:
return None
return s | [
"def",
"get_cgi_parameter_str_or_none",
"(",
"form",
":",
"cgi",
".",
"FieldStorage",
",",
"key",
":",
"str",
")",
"->",
"Optional",
"[",
"str",
"]",
":",
"s",
"=",
"get_cgi_parameter_str",
"(",
"form",
",",
"key",
")",
"if",
"s",
"is",
"None",
"or",
"... | Extracts a string parameter from a CGI form, or ``None`` if the key doesn't
exist or the string is zero-length. | [
"Extracts",
"a",
"string",
"parameter",
"from",
"a",
"CGI",
"form",
"or",
"None",
"if",
"the",
"key",
"doesn",
"t",
"exist",
"or",
"the",
"string",
"is",
"zero",
"-",
"length",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_web.py#L172-L181 | train | 53,317 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_web.py | get_cgi_parameter_list | def get_cgi_parameter_list(form: cgi.FieldStorage, key: str) -> List[str]:
"""
Extracts a list of values, all with the same key, from a CGI form.
"""
return form.getlist(key) | python | def get_cgi_parameter_list(form: cgi.FieldStorage, key: str) -> List[str]:
"""
Extracts a list of values, all with the same key, from a CGI form.
"""
return form.getlist(key) | [
"def",
"get_cgi_parameter_list",
"(",
"form",
":",
"cgi",
".",
"FieldStorage",
",",
"key",
":",
"str",
")",
"->",
"List",
"[",
"str",
"]",
":",
"return",
"form",
".",
"getlist",
"(",
"key",
")"
] | Extracts a list of values, all with the same key, from a CGI form. | [
"Extracts",
"a",
"list",
"of",
"values",
"all",
"with",
"the",
"same",
"key",
"from",
"a",
"CGI",
"form",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_web.py#L184-L188 | train | 53,318 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_web.py | get_cgi_parameter_bool | def get_cgi_parameter_bool(form: cgi.FieldStorage, key: str) -> bool:
"""
Extracts a boolean parameter from a CGI form, on the assumption that
``"1"`` is ``True`` and everything else is ``False``.
"""
return is_1(get_cgi_parameter_str(form, key)) | python | def get_cgi_parameter_bool(form: cgi.FieldStorage, key: str) -> bool:
"""
Extracts a boolean parameter from a CGI form, on the assumption that
``"1"`` is ``True`` and everything else is ``False``.
"""
return is_1(get_cgi_parameter_str(form, key)) | [
"def",
"get_cgi_parameter_bool",
"(",
"form",
":",
"cgi",
".",
"FieldStorage",
",",
"key",
":",
"str",
")",
"->",
"bool",
":",
"return",
"is_1",
"(",
"get_cgi_parameter_str",
"(",
"form",
",",
"key",
")",
")"
] | Extracts a boolean parameter from a CGI form, on the assumption that
``"1"`` is ``True`` and everything else is ``False``. | [
"Extracts",
"a",
"boolean",
"parameter",
"from",
"a",
"CGI",
"form",
"on",
"the",
"assumption",
"that",
"1",
"is",
"True",
"and",
"everything",
"else",
"is",
"False",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_web.py#L191-L196 | train | 53,319 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_web.py | get_cgi_parameter_int | def get_cgi_parameter_int(form: cgi.FieldStorage, key: str) -> Optional[int]:
"""
Extracts an integer parameter from a CGI form, or ``None`` if the key is
absent or the string value is not convertible to ``int``.
"""
return get_int_or_none(get_cgi_parameter_str(form, key)) | python | def get_cgi_parameter_int(form: cgi.FieldStorage, key: str) -> Optional[int]:
"""
Extracts an integer parameter from a CGI form, or ``None`` if the key is
absent or the string value is not convertible to ``int``.
"""
return get_int_or_none(get_cgi_parameter_str(form, key)) | [
"def",
"get_cgi_parameter_int",
"(",
"form",
":",
"cgi",
".",
"FieldStorage",
",",
"key",
":",
"str",
")",
"->",
"Optional",
"[",
"int",
"]",
":",
"return",
"get_int_or_none",
"(",
"get_cgi_parameter_str",
"(",
"form",
",",
"key",
")",
")"
] | Extracts an integer parameter from a CGI form, or ``None`` if the key is
absent or the string value is not convertible to ``int``. | [
"Extracts",
"an",
"integer",
"parameter",
"from",
"a",
"CGI",
"form",
"or",
"None",
"if",
"the",
"key",
"is",
"absent",
"or",
"the",
"string",
"value",
"is",
"not",
"convertible",
"to",
"int",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_web.py#L221-L226 | train | 53,320 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_web.py | get_cgi_parameter_float | def get_cgi_parameter_float(form: cgi.FieldStorage,
key: str) -> Optional[float]:
"""
Extracts a float parameter from a CGI form, or None if the key is
absent or the string value is not convertible to ``float``.
"""
return get_float_or_none(get_cgi_parameter_str(form, key)) | python | def get_cgi_parameter_float(form: cgi.FieldStorage,
key: str) -> Optional[float]:
"""
Extracts a float parameter from a CGI form, or None if the key is
absent or the string value is not convertible to ``float``.
"""
return get_float_or_none(get_cgi_parameter_str(form, key)) | [
"def",
"get_cgi_parameter_float",
"(",
"form",
":",
"cgi",
".",
"FieldStorage",
",",
"key",
":",
"str",
")",
"->",
"Optional",
"[",
"float",
"]",
":",
"return",
"get_float_or_none",
"(",
"get_cgi_parameter_str",
"(",
"form",
",",
"key",
")",
")"
] | Extracts a float parameter from a CGI form, or None if the key is
absent or the string value is not convertible to ``float``. | [
"Extracts",
"a",
"float",
"parameter",
"from",
"a",
"CGI",
"form",
"or",
"None",
"if",
"the",
"key",
"is",
"absent",
"or",
"the",
"string",
"value",
"is",
"not",
"convertible",
"to",
"float",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_web.py#L229-L235 | train | 53,321 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_web.py | get_cgi_parameter_file | def get_cgi_parameter_file(form: cgi.FieldStorage,
key: str) -> Optional[bytes]:
"""
Extracts a file's contents from a "file" input in a CGI form, or None
if no such file was uploaded.
"""
(filename, filecontents) = get_cgi_parameter_filename_and_file(form, key)
return filecontents | python | def get_cgi_parameter_file(form: cgi.FieldStorage,
key: str) -> Optional[bytes]:
"""
Extracts a file's contents from a "file" input in a CGI form, or None
if no such file was uploaded.
"""
(filename, filecontents) = get_cgi_parameter_filename_and_file(form, key)
return filecontents | [
"def",
"get_cgi_parameter_file",
"(",
"form",
":",
"cgi",
".",
"FieldStorage",
",",
"key",
":",
"str",
")",
"->",
"Optional",
"[",
"bytes",
"]",
":",
"(",
"filename",
",",
"filecontents",
")",
"=",
"get_cgi_parameter_filename_and_file",
"(",
"form",
",",
"ke... | Extracts a file's contents from a "file" input in a CGI form, or None
if no such file was uploaded. | [
"Extracts",
"a",
"file",
"s",
"contents",
"from",
"a",
"file",
"input",
"in",
"a",
"CGI",
"form",
"or",
"None",
"if",
"no",
"such",
"file",
"was",
"uploaded",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_web.py#L258-L265 | train | 53,322 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_web.py | cgi_parameter_exists | def cgi_parameter_exists(form: cgi.FieldStorage, key: str) -> bool:
"""
Does a CGI form contain the key?
"""
s = get_cgi_parameter_str(form, key)
return s is not None | python | def cgi_parameter_exists(form: cgi.FieldStorage, key: str) -> bool:
"""
Does a CGI form contain the key?
"""
s = get_cgi_parameter_str(form, key)
return s is not None | [
"def",
"cgi_parameter_exists",
"(",
"form",
":",
"cgi",
".",
"FieldStorage",
",",
"key",
":",
"str",
")",
"->",
"bool",
":",
"s",
"=",
"get_cgi_parameter_str",
"(",
"form",
",",
"key",
")",
"return",
"s",
"is",
"not",
"None"
] | Does a CGI form contain the key? | [
"Does",
"a",
"CGI",
"form",
"contain",
"the",
"key?"
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_web.py#L312-L317 | train | 53,323 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_web.py | getenv_escaped | def getenv_escaped(key: str, default: str = None) -> Optional[str]:
"""
Returns an environment variable's value, CGI-escaped, or ``None``.
"""
value = os.getenv(key, default)
# noinspection PyDeprecation
return cgi.escape(value) if value is not None else None | python | def getenv_escaped(key: str, default: str = None) -> Optional[str]:
"""
Returns an environment variable's value, CGI-escaped, or ``None``.
"""
value = os.getenv(key, default)
# noinspection PyDeprecation
return cgi.escape(value) if value is not None else None | [
"def",
"getenv_escaped",
"(",
"key",
":",
"str",
",",
"default",
":",
"str",
"=",
"None",
")",
"->",
"Optional",
"[",
"str",
"]",
":",
"value",
"=",
"os",
".",
"getenv",
"(",
"key",
",",
"default",
")",
"# noinspection PyDeprecation",
"return",
"cgi",
... | Returns an environment variable's value, CGI-escaped, or ``None``. | [
"Returns",
"an",
"environment",
"variable",
"s",
"value",
"CGI",
"-",
"escaped",
"or",
"None",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_web.py#L349-L355 | train | 53,324 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_web.py | get_png_data_url | def get_png_data_url(blob: Optional[bytes]) -> str:
"""
Converts a PNG blob into a local URL encapsulating the PNG.
"""
return BASE64_PNG_URL_PREFIX + base64.b64encode(blob).decode('ascii') | python | def get_png_data_url(blob: Optional[bytes]) -> str:
"""
Converts a PNG blob into a local URL encapsulating the PNG.
"""
return BASE64_PNG_URL_PREFIX + base64.b64encode(blob).decode('ascii') | [
"def",
"get_png_data_url",
"(",
"blob",
":",
"Optional",
"[",
"bytes",
"]",
")",
"->",
"str",
":",
"return",
"BASE64_PNG_URL_PREFIX",
"+",
"base64",
".",
"b64encode",
"(",
"blob",
")",
".",
"decode",
"(",
"'ascii'",
")"
] | Converts a PNG blob into a local URL encapsulating the PNG. | [
"Converts",
"a",
"PNG",
"blob",
"into",
"a",
"local",
"URL",
"encapsulating",
"the",
"PNG",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_web.py#L401-L405 | train | 53,325 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_web.py | print_result_for_plain_cgi_script_from_tuple | def print_result_for_plain_cgi_script_from_tuple(
contenttype_headers_content: WSGI_TUPLE_TYPE,
status: str = '200 OK') -> None:
"""
Writes HTTP result to stdout.
Args:
contenttype_headers_content:
the tuple ``(contenttype, extraheaders, data)``
status:
HTTP status message (default ``"200 OK``)
"""
contenttype, headers, content = contenttype_headers_content
print_result_for_plain_cgi_script(contenttype, headers, content, status) | python | def print_result_for_plain_cgi_script_from_tuple(
contenttype_headers_content: WSGI_TUPLE_TYPE,
status: str = '200 OK') -> None:
"""
Writes HTTP result to stdout.
Args:
contenttype_headers_content:
the tuple ``(contenttype, extraheaders, data)``
status:
HTTP status message (default ``"200 OK``)
"""
contenttype, headers, content = contenttype_headers_content
print_result_for_plain_cgi_script(contenttype, headers, content, status) | [
"def",
"print_result_for_plain_cgi_script_from_tuple",
"(",
"contenttype_headers_content",
":",
"WSGI_TUPLE_TYPE",
",",
"status",
":",
"str",
"=",
"'200 OK'",
")",
"->",
"None",
":",
"contenttype",
",",
"headers",
",",
"content",
"=",
"contenttype_headers_content",
"pri... | Writes HTTP result to stdout.
Args:
contenttype_headers_content:
the tuple ``(contenttype, extraheaders, data)``
status:
HTTP status message (default ``"200 OK``) | [
"Writes",
"HTTP",
"result",
"to",
"stdout",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_web.py#L520-L533 | train | 53,326 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_web.py | print_result_for_plain_cgi_script | def print_result_for_plain_cgi_script(contenttype: str,
headers: TYPE_WSGI_RESPONSE_HEADERS,
content: bytes,
status: str = '200 OK') -> None:
"""
Writes HTTP request result to stdout.
"""
headers = [
("Status", status),
("Content-Type", contenttype),
("Content-Length", str(len(content))),
] + headers
sys.stdout.write("\n".join([h[0] + ": " + h[1] for h in headers]) + "\n\n")
sys.stdout.write(content) | python | def print_result_for_plain_cgi_script(contenttype: str,
headers: TYPE_WSGI_RESPONSE_HEADERS,
content: bytes,
status: str = '200 OK') -> None:
"""
Writes HTTP request result to stdout.
"""
headers = [
("Status", status),
("Content-Type", contenttype),
("Content-Length", str(len(content))),
] + headers
sys.stdout.write("\n".join([h[0] + ": " + h[1] for h in headers]) + "\n\n")
sys.stdout.write(content) | [
"def",
"print_result_for_plain_cgi_script",
"(",
"contenttype",
":",
"str",
",",
"headers",
":",
"TYPE_WSGI_RESPONSE_HEADERS",
",",
"content",
":",
"bytes",
",",
"status",
":",
"str",
"=",
"'200 OK'",
")",
"->",
"None",
":",
"headers",
"=",
"[",
"(",
"\"Status... | Writes HTTP request result to stdout. | [
"Writes",
"HTTP",
"request",
"result",
"to",
"stdout",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_web.py#L536-L549 | train | 53,327 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_web.py | wsgi_simple_responder | def wsgi_simple_responder(
result: Union[str, bytes],
handler: Callable[[Union[str, bytes]], WSGI_TUPLE_TYPE],
start_response: TYPE_WSGI_START_RESPONSE,
status: str = '200 OK',
extraheaders: TYPE_WSGI_RESPONSE_HEADERS = None) \
-> TYPE_WSGI_APP_RESULT:
"""
Simple WSGI app.
Args:
result: the data to be processed by ``handler``
handler: a function returning a ``(contenttype, extraheaders, data)``
tuple, e.g. ``text_result``, ``html_result``
start_response: standard WSGI ``start_response`` function
status: status code (default ``"200 OK"``)
extraheaders: optional extra HTTP headers
Returns:
WSGI application result
"""
extraheaders = extraheaders or []
(contenttype, extraheaders2, output) = handler(result)
response_headers = [('Content-Type', contenttype),
('Content-Length', str(len(output)))]
response_headers.extend(extraheaders)
if extraheaders2 is not None:
response_headers.extend(extraheaders2)
# noinspection PyArgumentList
start_response(status, response_headers)
return [output] | python | def wsgi_simple_responder(
result: Union[str, bytes],
handler: Callable[[Union[str, bytes]], WSGI_TUPLE_TYPE],
start_response: TYPE_WSGI_START_RESPONSE,
status: str = '200 OK',
extraheaders: TYPE_WSGI_RESPONSE_HEADERS = None) \
-> TYPE_WSGI_APP_RESULT:
"""
Simple WSGI app.
Args:
result: the data to be processed by ``handler``
handler: a function returning a ``(contenttype, extraheaders, data)``
tuple, e.g. ``text_result``, ``html_result``
start_response: standard WSGI ``start_response`` function
status: status code (default ``"200 OK"``)
extraheaders: optional extra HTTP headers
Returns:
WSGI application result
"""
extraheaders = extraheaders or []
(contenttype, extraheaders2, output) = handler(result)
response_headers = [('Content-Type', contenttype),
('Content-Length', str(len(output)))]
response_headers.extend(extraheaders)
if extraheaders2 is not None:
response_headers.extend(extraheaders2)
# noinspection PyArgumentList
start_response(status, response_headers)
return [output] | [
"def",
"wsgi_simple_responder",
"(",
"result",
":",
"Union",
"[",
"str",
",",
"bytes",
"]",
",",
"handler",
":",
"Callable",
"[",
"[",
"Union",
"[",
"str",
",",
"bytes",
"]",
"]",
",",
"WSGI_TUPLE_TYPE",
"]",
",",
"start_response",
":",
"TYPE_WSGI_START_RE... | Simple WSGI app.
Args:
result: the data to be processed by ``handler``
handler: a function returning a ``(contenttype, extraheaders, data)``
tuple, e.g. ``text_result``, ``html_result``
start_response: standard WSGI ``start_response`` function
status: status code (default ``"200 OK"``)
extraheaders: optional extra HTTP headers
Returns:
WSGI application result | [
"Simple",
"WSGI",
"app",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_web.py#L556-L587 | train | 53,328 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_web.py | bold_if_not_blank | def bold_if_not_blank(x: Optional[str]) -> str:
"""
HTML-emboldens content, unless blank.
"""
if x is None:
return u"{}".format(x)
return u"<b>{}</b>".format(x) | python | def bold_if_not_blank(x: Optional[str]) -> str:
"""
HTML-emboldens content, unless blank.
"""
if x is None:
return u"{}".format(x)
return u"<b>{}</b>".format(x) | [
"def",
"bold_if_not_blank",
"(",
"x",
":",
"Optional",
"[",
"str",
"]",
")",
"->",
"str",
":",
"if",
"x",
"is",
"None",
":",
"return",
"u\"{}\"",
".",
"format",
"(",
"x",
")",
"return",
"u\"<b>{}</b>\"",
".",
"format",
"(",
"x",
")"
] | HTML-emboldens content, unless blank. | [
"HTML",
"-",
"emboldens",
"content",
"unless",
"blank",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_web.py#L628-L634 | train | 53,329 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_web.py | make_urls_hyperlinks | def make_urls_hyperlinks(text: str) -> str:
"""
Adds hyperlinks to text that appears to contain URLs.
See
- http://stackoverflow.com/questions/1071191
- ... except that double-replaces everything; e.g. try with
``text = "me@somewhere.com me@somewhere.com"``
- http://stackp.online.fr/?p=19
"""
find_url = r'''
(?x)( # verbose identify URLs within text
(http|ftp|gopher) # make sure we find a resource type
:// # ...needs to be followed by colon-slash-slash
(\w+[:.]?){2,} # at least two domain groups, e.g. (gnosis.)(cx)
(/?| # could be just the domain name (maybe w/ slash)
[^ \n\r"]+ # or stuff then space, newline, tab, quote
[\w/]) # resource name ends in alphanumeric or slash
(?=[\s\.,>)'"\]]) # assert: followed by white or clause ending
) # end of match group
'''
replace_url = r'<a href="\1">\1</a>'
find_email = re.compile(r'([.\w\-]+@(\w[\w\-]+\.)+[\w\-]+)')
# '.' doesn't need escaping inside square brackets
# https://stackoverflow.com/questions/10397968/escape-dot-in-a-regex-range
replace_email = r'<a href="mailto:\1">\1</a>'
text = re.sub(find_url, replace_url, text)
text = re.sub(find_email, replace_email, text)
return text | python | def make_urls_hyperlinks(text: str) -> str:
"""
Adds hyperlinks to text that appears to contain URLs.
See
- http://stackoverflow.com/questions/1071191
- ... except that double-replaces everything; e.g. try with
``text = "me@somewhere.com me@somewhere.com"``
- http://stackp.online.fr/?p=19
"""
find_url = r'''
(?x)( # verbose identify URLs within text
(http|ftp|gopher) # make sure we find a resource type
:// # ...needs to be followed by colon-slash-slash
(\w+[:.]?){2,} # at least two domain groups, e.g. (gnosis.)(cx)
(/?| # could be just the domain name (maybe w/ slash)
[^ \n\r"]+ # or stuff then space, newline, tab, quote
[\w/]) # resource name ends in alphanumeric or slash
(?=[\s\.,>)'"\]]) # assert: followed by white or clause ending
) # end of match group
'''
replace_url = r'<a href="\1">\1</a>'
find_email = re.compile(r'([.\w\-]+@(\w[\w\-]+\.)+[\w\-]+)')
# '.' doesn't need escaping inside square brackets
# https://stackoverflow.com/questions/10397968/escape-dot-in-a-regex-range
replace_email = r'<a href="mailto:\1">\1</a>'
text = re.sub(find_url, replace_url, text)
text = re.sub(find_email, replace_email, text)
return text | [
"def",
"make_urls_hyperlinks",
"(",
"text",
":",
"str",
")",
"->",
"str",
":",
"find_url",
"=",
"r'''\n (?x)( # verbose identify URLs within text\n (http|ftp|gopher) # make sure we find a resource type\n :// # ...needs to be followed by colon... | Adds hyperlinks to text that appears to contain URLs.
See
- http://stackoverflow.com/questions/1071191
- ... except that double-replaces everything; e.g. try with
``text = "me@somewhere.com me@somewhere.com"``
- http://stackp.online.fr/?p=19 | [
"Adds",
"hyperlinks",
"to",
"text",
"that",
"appears",
"to",
"contain",
"URLs",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_web.py#L637-L668 | train | 53,330 |
RudolfCardinal/pythonlib | cardinal_pythonlib/sphinxtools.py | rst_underline | def rst_underline(heading: str, underline_char: str) -> str:
"""
Underlines a heading for RST files.
Args:
heading: text to underline
underline_char: character to use
Returns:
underlined heading, over two lines (without a final terminating
newline)
"""
assert "\n" not in heading
assert len(underline_char) == 1
return heading + "\n" + (underline_char * len(heading)) | python | def rst_underline(heading: str, underline_char: str) -> str:
"""
Underlines a heading for RST files.
Args:
heading: text to underline
underline_char: character to use
Returns:
underlined heading, over two lines (without a final terminating
newline)
"""
assert "\n" not in heading
assert len(underline_char) == 1
return heading + "\n" + (underline_char * len(heading)) | [
"def",
"rst_underline",
"(",
"heading",
":",
"str",
",",
"underline_char",
":",
"str",
")",
"->",
"str",
":",
"assert",
"\"\\n\"",
"not",
"in",
"heading",
"assert",
"len",
"(",
"underline_char",
")",
"==",
"1",
"return",
"heading",
"+",
"\"\\n\"",
"+",
"... | Underlines a heading for RST files.
Args:
heading: text to underline
underline_char: character to use
Returns:
underlined heading, over two lines (without a final terminating
newline) | [
"Underlines",
"a",
"heading",
"for",
"RST",
"files",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sphinxtools.py#L78-L92 | train | 53,331 |
RudolfCardinal/pythonlib | cardinal_pythonlib/sphinxtools.py | write_if_allowed | def write_if_allowed(filename: str,
content: str,
overwrite: bool = False,
mock: bool = False) -> None:
"""
Writes the contents to a file, if permitted.
Args:
filename: filename to write
content: contents to write
overwrite: permit overwrites?
mock: pretend to write, but don't
Raises:
RuntimeError: if file exists but overwriting not permitted
"""
# Check we're allowed
if not overwrite and exists(filename):
fail("File exists, not overwriting: {!r}".format(filename))
# Make the directory, if necessary
directory = dirname(filename)
if not mock:
mkdir_p(directory)
# Write the file
log.info("Writing to {!r}", filename)
if mock:
log.warning("Skipping writes as in mock mode")
else:
with open(filename, "wt") as outfile:
outfile.write(content) | python | def write_if_allowed(filename: str,
content: str,
overwrite: bool = False,
mock: bool = False) -> None:
"""
Writes the contents to a file, if permitted.
Args:
filename: filename to write
content: contents to write
overwrite: permit overwrites?
mock: pretend to write, but don't
Raises:
RuntimeError: if file exists but overwriting not permitted
"""
# Check we're allowed
if not overwrite and exists(filename):
fail("File exists, not overwriting: {!r}".format(filename))
# Make the directory, if necessary
directory = dirname(filename)
if not mock:
mkdir_p(directory)
# Write the file
log.info("Writing to {!r}", filename)
if mock:
log.warning("Skipping writes as in mock mode")
else:
with open(filename, "wt") as outfile:
outfile.write(content) | [
"def",
"write_if_allowed",
"(",
"filename",
":",
"str",
",",
"content",
":",
"str",
",",
"overwrite",
":",
"bool",
"=",
"False",
",",
"mock",
":",
"bool",
"=",
"False",
")",
"->",
"None",
":",
"# Check we're allowed",
"if",
"not",
"overwrite",
"and",
"ex... | Writes the contents to a file, if permitted.
Args:
filename: filename to write
content: contents to write
overwrite: permit overwrites?
mock: pretend to write, but don't
Raises:
RuntimeError: if file exists but overwriting not permitted | [
"Writes",
"the",
"contents",
"to",
"a",
"file",
"if",
"permitted",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sphinxtools.py#L100-L131 | train | 53,332 |
RudolfCardinal/pythonlib | cardinal_pythonlib/sphinxtools.py | FileToAutodocument.rst_filename_rel_autodoc_index | def rst_filename_rel_autodoc_index(self, index_filename: str) -> str:
"""
Returns the filename of the target RST file, relative to a specified
index file. Used to make the index refer to the RST.
"""
index_dir = dirname(abspath(expanduser(index_filename)))
return relpath(self.target_rst_filename, start=index_dir) | python | def rst_filename_rel_autodoc_index(self, index_filename: str) -> str:
"""
Returns the filename of the target RST file, relative to a specified
index file. Used to make the index refer to the RST.
"""
index_dir = dirname(abspath(expanduser(index_filename)))
return relpath(self.target_rst_filename, start=index_dir) | [
"def",
"rst_filename_rel_autodoc_index",
"(",
"self",
",",
"index_filename",
":",
"str",
")",
"->",
"str",
":",
"index_dir",
"=",
"dirname",
"(",
"abspath",
"(",
"expanduser",
"(",
"index_filename",
")",
")",
")",
"return",
"relpath",
"(",
"self",
".",
"targ... | Returns the filename of the target RST file, relative to a specified
index file. Used to make the index refer to the RST. | [
"Returns",
"the",
"filename",
"of",
"the",
"target",
"RST",
"file",
"relative",
"to",
"a",
"specified",
"index",
"file",
".",
"Used",
"to",
"make",
"the",
"index",
"refer",
"to",
"the",
"RST",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sphinxtools.py#L291-L297 | train | 53,333 |
RudolfCardinal/pythonlib | cardinal_pythonlib/sphinxtools.py | FileToAutodocument.python_module_name | def python_module_name(self) -> str:
"""
Returns the name of the Python module that this instance refers to,
in dotted Python module notation, or a blank string if it doesn't.
"""
if not self.is_python:
return ""
filepath = self.source_filename_rel_python_root
dirs_and_base = splitext(filepath)[0]
dir_and_file_parts = dirs_and_base.split(sep)
return ".".join(dir_and_file_parts) | python | def python_module_name(self) -> str:
"""
Returns the name of the Python module that this instance refers to,
in dotted Python module notation, or a blank string if it doesn't.
"""
if not self.is_python:
return ""
filepath = self.source_filename_rel_python_root
dirs_and_base = splitext(filepath)[0]
dir_and_file_parts = dirs_and_base.split(sep)
return ".".join(dir_and_file_parts) | [
"def",
"python_module_name",
"(",
"self",
")",
"->",
"str",
":",
"if",
"not",
"self",
".",
"is_python",
":",
"return",
"\"\"",
"filepath",
"=",
"self",
".",
"source_filename_rel_python_root",
"dirs_and_base",
"=",
"splitext",
"(",
"filepath",
")",
"[",
"0",
... | Returns the name of the Python module that this instance refers to,
in dotted Python module notation, or a blank string if it doesn't. | [
"Returns",
"the",
"name",
"of",
"the",
"Python",
"module",
"that",
"this",
"instance",
"refers",
"to",
"in",
"dotted",
"Python",
"module",
"notation",
"or",
"a",
"blank",
"string",
"if",
"it",
"doesn",
"t",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sphinxtools.py#L300-L310 | train | 53,334 |
RudolfCardinal/pythonlib | cardinal_pythonlib/sphinxtools.py | FileToAutodocument.write_rst | def write_rst(self,
prefix: str = "",
suffix: str = "",
heading_underline_char: str = "=",
method: AutodocMethod = None,
overwrite: bool = False,
mock: bool = False) -> None:
"""
Writes the RST file to our destination RST filename, making any
necessary directories.
Args:
prefix: as for :func:`rst_content`
suffix: as for :func:`rst_content`
heading_underline_char: as for :func:`rst_content`
method: as for :func:`rst_content`
overwrite: overwrite the file if it exists already?
mock: pretend to write, but don't
"""
content = self.rst_content(
prefix=prefix,
suffix=suffix,
heading_underline_char=heading_underline_char,
method=method
)
write_if_allowed(self.target_rst_filename, content,
overwrite=overwrite, mock=mock) | python | def write_rst(self,
prefix: str = "",
suffix: str = "",
heading_underline_char: str = "=",
method: AutodocMethod = None,
overwrite: bool = False,
mock: bool = False) -> None:
"""
Writes the RST file to our destination RST filename, making any
necessary directories.
Args:
prefix: as for :func:`rst_content`
suffix: as for :func:`rst_content`
heading_underline_char: as for :func:`rst_content`
method: as for :func:`rst_content`
overwrite: overwrite the file if it exists already?
mock: pretend to write, but don't
"""
content = self.rst_content(
prefix=prefix,
suffix=suffix,
heading_underline_char=heading_underline_char,
method=method
)
write_if_allowed(self.target_rst_filename, content,
overwrite=overwrite, mock=mock) | [
"def",
"write_rst",
"(",
"self",
",",
"prefix",
":",
"str",
"=",
"\"\"",
",",
"suffix",
":",
"str",
"=",
"\"\"",
",",
"heading_underline_char",
":",
"str",
"=",
"\"=\"",
",",
"method",
":",
"AutodocMethod",
"=",
"None",
",",
"overwrite",
":",
"bool",
"... | Writes the RST file to our destination RST filename, making any
necessary directories.
Args:
prefix: as for :func:`rst_content`
suffix: as for :func:`rst_content`
heading_underline_char: as for :func:`rst_content`
method: as for :func:`rst_content`
overwrite: overwrite the file if it exists already?
mock: pretend to write, but don't | [
"Writes",
"the",
"RST",
"file",
"to",
"our",
"destination",
"RST",
"filename",
"making",
"any",
"necessary",
"directories",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sphinxtools.py#L414-L440 | train | 53,335 |
RudolfCardinal/pythonlib | cardinal_pythonlib/sphinxtools.py | AutodocIndex.add_source_files | def add_source_files(
self,
source_filenames_or_globs: Union[str, List[str]],
method: AutodocMethod = None,
recursive: bool = None,
source_rst_title_style_python: bool = None,
pygments_language_override: Dict[str, str] = None) -> None:
"""
Adds source files to the index.
Args:
source_filenames_or_globs: string containing a filename or a
glob, describing the file(s) to be added, or a list of such
strings
method: optional method to override ``self.method``
recursive: use :func:`glob.glob` in recursive mode? (If ``None``,
the default, uses the version from the constructor.)
source_rst_title_style_python: optional to override
``self.source_rst_title_style_python``
pygments_language_override: optional to override
``self.pygments_language_override``
"""
if not source_filenames_or_globs:
return
if method is None:
# Use the default
method = self.method
if recursive is None:
recursive = self.recursive
if source_rst_title_style_python is None:
source_rst_title_style_python = self.source_rst_title_style_python
if pygments_language_override is None:
pygments_language_override = self.pygments_language_override
# Get a sorted list of filenames
final_filenames = self.get_sorted_source_files(
source_filenames_or_globs,
recursive=recursive
)
# Process that sorted list
for source_filename in final_filenames:
self.files_to_index.append(FileToAutodocument(
source_filename=source_filename,
project_root_dir=self.project_root_dir,
python_package_root_dir=self.python_package_root_dir,
target_rst_filename=self.specific_file_rst_filename(
source_filename
),
method=method,
source_rst_title_style_python=source_rst_title_style_python,
pygments_language_override=pygments_language_override,
)) | python | def add_source_files(
self,
source_filenames_or_globs: Union[str, List[str]],
method: AutodocMethod = None,
recursive: bool = None,
source_rst_title_style_python: bool = None,
pygments_language_override: Dict[str, str] = None) -> None:
"""
Adds source files to the index.
Args:
source_filenames_or_globs: string containing a filename or a
glob, describing the file(s) to be added, or a list of such
strings
method: optional method to override ``self.method``
recursive: use :func:`glob.glob` in recursive mode? (If ``None``,
the default, uses the version from the constructor.)
source_rst_title_style_python: optional to override
``self.source_rst_title_style_python``
pygments_language_override: optional to override
``self.pygments_language_override``
"""
if not source_filenames_or_globs:
return
if method is None:
# Use the default
method = self.method
if recursive is None:
recursive = self.recursive
if source_rst_title_style_python is None:
source_rst_title_style_python = self.source_rst_title_style_python
if pygments_language_override is None:
pygments_language_override = self.pygments_language_override
# Get a sorted list of filenames
final_filenames = self.get_sorted_source_files(
source_filenames_or_globs,
recursive=recursive
)
# Process that sorted list
for source_filename in final_filenames:
self.files_to_index.append(FileToAutodocument(
source_filename=source_filename,
project_root_dir=self.project_root_dir,
python_package_root_dir=self.python_package_root_dir,
target_rst_filename=self.specific_file_rst_filename(
source_filename
),
method=method,
source_rst_title_style_python=source_rst_title_style_python,
pygments_language_override=pygments_language_override,
)) | [
"def",
"add_source_files",
"(",
"self",
",",
"source_filenames_or_globs",
":",
"Union",
"[",
"str",
",",
"List",
"[",
"str",
"]",
"]",
",",
"method",
":",
"AutodocMethod",
"=",
"None",
",",
"recursive",
":",
"bool",
"=",
"None",
",",
"source_rst_title_style_... | Adds source files to the index.
Args:
source_filenames_or_globs: string containing a filename or a
glob, describing the file(s) to be added, or a list of such
strings
method: optional method to override ``self.method``
recursive: use :func:`glob.glob` in recursive mode? (If ``None``,
the default, uses the version from the constructor.)
source_rst_title_style_python: optional to override
``self.source_rst_title_style_python``
pygments_language_override: optional to override
``self.pygments_language_override`` | [
"Adds",
"source",
"files",
"to",
"the",
"index",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sphinxtools.py#L654-L707 | train | 53,336 |
RudolfCardinal/pythonlib | cardinal_pythonlib/sphinxtools.py | AutodocIndex.filename_matches_glob | def filename_matches_glob(filename: str, globtext: str) -> bool:
"""
The ``glob.glob`` function doesn't do exclusion very well. We don't
want to have to specify root directories for exclusion patterns. We
don't want to have to trawl a massive set of files to find exclusion
files. So let's implement a glob match.
Args:
filename: filename
globtext: glob
Returns:
does the filename match the glob?
See also:
- https://stackoverflow.com/questions/20638040/glob-exclude-pattern
"""
# Quick check on basename-only matching
if fnmatch(filename, globtext):
log.debug("{!r} matches {!r}", filename, globtext)
return True
bname = basename(filename)
if fnmatch(bname, globtext):
log.debug("{!r} matches {!r}", bname, globtext)
return True
# Directory matching: is actually accomplished by the code above!
# Otherwise:
return False | python | def filename_matches_glob(filename: str, globtext: str) -> bool:
"""
The ``glob.glob`` function doesn't do exclusion very well. We don't
want to have to specify root directories for exclusion patterns. We
don't want to have to trawl a massive set of files to find exclusion
files. So let's implement a glob match.
Args:
filename: filename
globtext: glob
Returns:
does the filename match the glob?
See also:
- https://stackoverflow.com/questions/20638040/glob-exclude-pattern
"""
# Quick check on basename-only matching
if fnmatch(filename, globtext):
log.debug("{!r} matches {!r}", filename, globtext)
return True
bname = basename(filename)
if fnmatch(bname, globtext):
log.debug("{!r} matches {!r}", bname, globtext)
return True
# Directory matching: is actually accomplished by the code above!
# Otherwise:
return False | [
"def",
"filename_matches_glob",
"(",
"filename",
":",
"str",
",",
"globtext",
":",
"str",
")",
"->",
"bool",
":",
"# Quick check on basename-only matching",
"if",
"fnmatch",
"(",
"filename",
",",
"globtext",
")",
":",
"log",
".",
"debug",
"(",
"\"{!r} matches {!... | The ``glob.glob`` function doesn't do exclusion very well. We don't
want to have to specify root directories for exclusion patterns. We
don't want to have to trawl a massive set of files to find exclusion
files. So let's implement a glob match.
Args:
filename: filename
globtext: glob
Returns:
does the filename match the glob?
See also:
- https://stackoverflow.com/questions/20638040/glob-exclude-pattern | [
"The",
"glob",
".",
"glob",
"function",
"doesn",
"t",
"do",
"exclusion",
"very",
"well",
".",
"We",
"don",
"t",
"want",
"to",
"have",
"to",
"specify",
"root",
"directories",
"for",
"exclusion",
"patterns",
".",
"We",
"don",
"t",
"want",
"to",
"have",
"... | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sphinxtools.py#L740-L769 | train | 53,337 |
RudolfCardinal/pythonlib | cardinal_pythonlib/sphinxtools.py | AutodocIndex.should_exclude | def should_exclude(self, filename) -> bool:
"""
Should we exclude this file from consideration?
"""
for skip_glob in self.skip_globs:
if self.filename_matches_glob(filename, skip_glob):
return True
return False | python | def should_exclude(self, filename) -> bool:
"""
Should we exclude this file from consideration?
"""
for skip_glob in self.skip_globs:
if self.filename_matches_glob(filename, skip_glob):
return True
return False | [
"def",
"should_exclude",
"(",
"self",
",",
"filename",
")",
"->",
"bool",
":",
"for",
"skip_glob",
"in",
"self",
".",
"skip_globs",
":",
"if",
"self",
".",
"filename_matches_glob",
"(",
"filename",
",",
"skip_glob",
")",
":",
"return",
"True",
"return",
"F... | Should we exclude this file from consideration? | [
"Should",
"we",
"exclude",
"this",
"file",
"from",
"consideration?"
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sphinxtools.py#L771-L778 | train | 53,338 |
RudolfCardinal/pythonlib | cardinal_pythonlib/sphinxtools.py | AutodocIndex.specific_file_rst_filename | def specific_file_rst_filename(self, source_filename: str) -> str:
"""
Gets the RST filename corresponding to a source filename.
See the help for the constructor for more details.
Args:
source_filename: source filename within current project
Returns:
RST filename
Note in particular: the way we structure the directories means that we
won't get clashes between files with idential names in two different
directories. However, we must also incorporate the original source
filename, in particular for C++ where ``thing.h`` and ``thing.cpp``
must not generate the same RST filename. So we just add ``.rst``.
"""
highest_code_to_target = relative_filename_within_dir(
source_filename, self.highest_code_dir)
bname = basename(source_filename)
result = join(self.autodoc_rst_root_dir,
dirname(highest_code_to_target),
bname + EXT_RST)
log.debug("Source {!r} -> RST {!r}", source_filename, result)
return result | python | def specific_file_rst_filename(self, source_filename: str) -> str:
"""
Gets the RST filename corresponding to a source filename.
See the help for the constructor for more details.
Args:
source_filename: source filename within current project
Returns:
RST filename
Note in particular: the way we structure the directories means that we
won't get clashes between files with idential names in two different
directories. However, we must also incorporate the original source
filename, in particular for C++ where ``thing.h`` and ``thing.cpp``
must not generate the same RST filename. So we just add ``.rst``.
"""
highest_code_to_target = relative_filename_within_dir(
source_filename, self.highest_code_dir)
bname = basename(source_filename)
result = join(self.autodoc_rst_root_dir,
dirname(highest_code_to_target),
bname + EXT_RST)
log.debug("Source {!r} -> RST {!r}", source_filename, result)
return result | [
"def",
"specific_file_rst_filename",
"(",
"self",
",",
"source_filename",
":",
"str",
")",
"->",
"str",
":",
"highest_code_to_target",
"=",
"relative_filename_within_dir",
"(",
"source_filename",
",",
"self",
".",
"highest_code_dir",
")",
"bname",
"=",
"basename",
"... | Gets the RST filename corresponding to a source filename.
See the help for the constructor for more details.
Args:
source_filename: source filename within current project
Returns:
RST filename
Note in particular: the way we structure the directories means that we
won't get clashes between files with idential names in two different
directories. However, we must also incorporate the original source
filename, in particular for C++ where ``thing.h`` and ``thing.cpp``
must not generate the same RST filename. So we just add ``.rst``. | [
"Gets",
"the",
"RST",
"filename",
"corresponding",
"to",
"a",
"source",
"filename",
".",
"See",
"the",
"help",
"for",
"the",
"constructor",
"for",
"more",
"details",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sphinxtools.py#L799-L823 | train | 53,339 |
RudolfCardinal/pythonlib | cardinal_pythonlib/sphinxtools.py | AutodocIndex.write_index_and_rst_files | def write_index_and_rst_files(self, overwrite: bool = False,
mock: bool = False) -> None:
"""
Writes both the individual RST files and the index.
Args:
overwrite: allow existing files to be overwritten?
mock: pretend to write, but don't
"""
for f in self.files_to_index:
if isinstance(f, FileToAutodocument):
f.write_rst(
prefix=self.rst_prefix,
suffix=self.rst_suffix,
heading_underline_char=self.source_rst_heading_underline_char, # noqa
overwrite=overwrite,
mock=mock,
)
elif isinstance(f, AutodocIndex):
f.write_index_and_rst_files(overwrite=overwrite, mock=mock)
else:
fail("Unknown thing in files_to_index: {!r}".format(f))
self.write_index(overwrite=overwrite, mock=mock) | python | def write_index_and_rst_files(self, overwrite: bool = False,
mock: bool = False) -> None:
"""
Writes both the individual RST files and the index.
Args:
overwrite: allow existing files to be overwritten?
mock: pretend to write, but don't
"""
for f in self.files_to_index:
if isinstance(f, FileToAutodocument):
f.write_rst(
prefix=self.rst_prefix,
suffix=self.rst_suffix,
heading_underline_char=self.source_rst_heading_underline_char, # noqa
overwrite=overwrite,
mock=mock,
)
elif isinstance(f, AutodocIndex):
f.write_index_and_rst_files(overwrite=overwrite, mock=mock)
else:
fail("Unknown thing in files_to_index: {!r}".format(f))
self.write_index(overwrite=overwrite, mock=mock) | [
"def",
"write_index_and_rst_files",
"(",
"self",
",",
"overwrite",
":",
"bool",
"=",
"False",
",",
"mock",
":",
"bool",
"=",
"False",
")",
"->",
"None",
":",
"for",
"f",
"in",
"self",
".",
"files_to_index",
":",
"if",
"isinstance",
"(",
"f",
",",
"File... | Writes both the individual RST files and the index.
Args:
overwrite: allow existing files to be overwritten?
mock: pretend to write, but don't | [
"Writes",
"both",
"the",
"individual",
"RST",
"files",
"and",
"the",
"index",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sphinxtools.py#L825-L847 | train | 53,340 |
RudolfCardinal/pythonlib | cardinal_pythonlib/sphinxtools.py | AutodocIndex.write_index | def write_index(self, overwrite: bool = False, mock: bool = False) -> None:
"""
Writes the index file, if permitted.
Args:
overwrite: allow existing files to be overwritten?
mock: pretend to write, but don't
"""
write_if_allowed(self.index_filename, self.index_content(),
overwrite=overwrite, mock=mock) | python | def write_index(self, overwrite: bool = False, mock: bool = False) -> None:
"""
Writes the index file, if permitted.
Args:
overwrite: allow existing files to be overwritten?
mock: pretend to write, but don't
"""
write_if_allowed(self.index_filename, self.index_content(),
overwrite=overwrite, mock=mock) | [
"def",
"write_index",
"(",
"self",
",",
"overwrite",
":",
"bool",
"=",
"False",
",",
"mock",
":",
"bool",
"=",
"False",
")",
"->",
"None",
":",
"write_if_allowed",
"(",
"self",
".",
"index_filename",
",",
"self",
".",
"index_content",
"(",
")",
",",
"o... | Writes the index file, if permitted.
Args:
overwrite: allow existing files to be overwritten?
mock: pretend to write, but don't | [
"Writes",
"the",
"index",
"file",
"if",
"permitted",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sphinxtools.py#L923-L932 | train | 53,341 |
carpyncho/feets | doc/source/JSAnimation/examples.py | basic_animation | def basic_animation(frames=100, interval=30):
"""Plot a basic sine wave with oscillating amplitude"""
fig = plt.figure()
ax = plt.axes(xlim=(0, 10), ylim=(-2, 2))
line, = ax.plot([], [], lw=2)
x = np.linspace(0, 10, 1000)
def init():
line.set_data([], [])
return line,
def animate(i):
y = np.cos(i * 0.02 * np.pi) * np.sin(x - i * 0.02 * np.pi)
line.set_data(x, y)
return line,
return animation.FuncAnimation(fig, animate, init_func=init,
frames=frames, interval=interval) | python | def basic_animation(frames=100, interval=30):
"""Plot a basic sine wave with oscillating amplitude"""
fig = plt.figure()
ax = plt.axes(xlim=(0, 10), ylim=(-2, 2))
line, = ax.plot([], [], lw=2)
x = np.linspace(0, 10, 1000)
def init():
line.set_data([], [])
return line,
def animate(i):
y = np.cos(i * 0.02 * np.pi) * np.sin(x - i * 0.02 * np.pi)
line.set_data(x, y)
return line,
return animation.FuncAnimation(fig, animate, init_func=init,
frames=frames, interval=interval) | [
"def",
"basic_animation",
"(",
"frames",
"=",
"100",
",",
"interval",
"=",
"30",
")",
":",
"fig",
"=",
"plt",
".",
"figure",
"(",
")",
"ax",
"=",
"plt",
".",
"axes",
"(",
"xlim",
"=",
"(",
"0",
",",
"10",
")",
",",
"ylim",
"=",
"(",
"-",
"2",... | Plot a basic sine wave with oscillating amplitude | [
"Plot",
"a",
"basic",
"sine",
"wave",
"with",
"oscillating",
"amplitude"
] | 53bdfb73b53845561914fc1f756e0c2377b9b76b | https://github.com/carpyncho/feets/blob/53bdfb73b53845561914fc1f756e0c2377b9b76b/doc/source/JSAnimation/examples.py#L6-L24 | train | 53,342 |
carpyncho/feets | doc/source/JSAnimation/examples.py | lorenz_animation | def lorenz_animation(N_trajectories=20, rseed=1, frames=200, interval=30):
"""Plot a 3D visualization of the dynamics of the Lorenz system"""
from scipy import integrate
from mpl_toolkits.mplot3d import Axes3D
from matplotlib.colors import cnames
def lorentz_deriv(coords, t0, sigma=10., beta=8./3, rho=28.0):
"""Compute the time-derivative of a Lorentz system."""
x, y, z = coords
return [sigma * (y - x), x * (rho - z) - y, x * y - beta * z]
# Choose random starting points, uniformly distributed from -15 to 15
np.random.seed(rseed)
x0 = -15 + 30 * np.random.random((N_trajectories, 3))
# Solve for the trajectories
t = np.linspace(0, 2, 500)
x_t = np.asarray([integrate.odeint(lorentz_deriv, x0i, t)
for x0i in x0])
# Set up figure & 3D axis for animation
fig = plt.figure()
ax = fig.add_axes([0, 0, 1, 1], projection='3d')
ax.axis('off')
# choose a different color for each trajectory
colors = plt.cm.jet(np.linspace(0, 1, N_trajectories))
# set up lines and points
lines = sum([ax.plot([], [], [], '-', c=c)
for c in colors], [])
pts = sum([ax.plot([], [], [], 'o', c=c, ms=4)
for c in colors], [])
# prepare the axes limits
ax.set_xlim((-25, 25))
ax.set_ylim((-35, 35))
ax.set_zlim((5, 55))
# set point-of-view: specified by (altitude degrees, azimuth degrees)
ax.view_init(30, 0)
# initialization function: plot the background of each frame
def init():
for line, pt in zip(lines, pts):
line.set_data([], [])
line.set_3d_properties([])
pt.set_data([], [])
pt.set_3d_properties([])
return lines + pts
# animation function: called sequentially
def animate(i):
# we'll step two time-steps per frame. This leads to nice results.
i = (2 * i) % x_t.shape[1]
for line, pt, xi in zip(lines, pts, x_t):
x, y, z = xi[:i + 1].T
line.set_data(x, y)
line.set_3d_properties(z)
pt.set_data(x[-1:], y[-1:])
pt.set_3d_properties(z[-1:])
ax.view_init(30, 0.3 * i)
fig.canvas.draw()
return lines + pts
return animation.FuncAnimation(fig, animate, init_func=init,
frames=frames, interval=interval) | python | def lorenz_animation(N_trajectories=20, rseed=1, frames=200, interval=30):
"""Plot a 3D visualization of the dynamics of the Lorenz system"""
from scipy import integrate
from mpl_toolkits.mplot3d import Axes3D
from matplotlib.colors import cnames
def lorentz_deriv(coords, t0, sigma=10., beta=8./3, rho=28.0):
"""Compute the time-derivative of a Lorentz system."""
x, y, z = coords
return [sigma * (y - x), x * (rho - z) - y, x * y - beta * z]
# Choose random starting points, uniformly distributed from -15 to 15
np.random.seed(rseed)
x0 = -15 + 30 * np.random.random((N_trajectories, 3))
# Solve for the trajectories
t = np.linspace(0, 2, 500)
x_t = np.asarray([integrate.odeint(lorentz_deriv, x0i, t)
for x0i in x0])
# Set up figure & 3D axis for animation
fig = plt.figure()
ax = fig.add_axes([0, 0, 1, 1], projection='3d')
ax.axis('off')
# choose a different color for each trajectory
colors = plt.cm.jet(np.linspace(0, 1, N_trajectories))
# set up lines and points
lines = sum([ax.plot([], [], [], '-', c=c)
for c in colors], [])
pts = sum([ax.plot([], [], [], 'o', c=c, ms=4)
for c in colors], [])
# prepare the axes limits
ax.set_xlim((-25, 25))
ax.set_ylim((-35, 35))
ax.set_zlim((5, 55))
# set point-of-view: specified by (altitude degrees, azimuth degrees)
ax.view_init(30, 0)
# initialization function: plot the background of each frame
def init():
for line, pt in zip(lines, pts):
line.set_data([], [])
line.set_3d_properties([])
pt.set_data([], [])
pt.set_3d_properties([])
return lines + pts
# animation function: called sequentially
def animate(i):
# we'll step two time-steps per frame. This leads to nice results.
i = (2 * i) % x_t.shape[1]
for line, pt, xi in zip(lines, pts, x_t):
x, y, z = xi[:i + 1].T
line.set_data(x, y)
line.set_3d_properties(z)
pt.set_data(x[-1:], y[-1:])
pt.set_3d_properties(z[-1:])
ax.view_init(30, 0.3 * i)
fig.canvas.draw()
return lines + pts
return animation.FuncAnimation(fig, animate, init_func=init,
frames=frames, interval=interval) | [
"def",
"lorenz_animation",
"(",
"N_trajectories",
"=",
"20",
",",
"rseed",
"=",
"1",
",",
"frames",
"=",
"200",
",",
"interval",
"=",
"30",
")",
":",
"from",
"scipy",
"import",
"integrate",
"from",
"mpl_toolkits",
".",
"mplot3d",
"import",
"Axes3D",
"from"... | Plot a 3D visualization of the dynamics of the Lorenz system | [
"Plot",
"a",
"3D",
"visualization",
"of",
"the",
"dynamics",
"of",
"the",
"Lorenz",
"system"
] | 53bdfb73b53845561914fc1f756e0c2377b9b76b | https://github.com/carpyncho/feets/blob/53bdfb73b53845561914fc1f756e0c2377b9b76b/doc/source/JSAnimation/examples.py#L27-L97 | train | 53,343 |
carpyncho/feets | doc/source/JSAnimation/html_writer.py | _included_frames | def _included_frames(frame_list, frame_format):
"""frame_list should be a list of filenames"""
return INCLUDED_FRAMES.format(Nframes=len(frame_list),
frame_dir=os.path.dirname(frame_list[0]),
frame_format=frame_format) | python | def _included_frames(frame_list, frame_format):
"""frame_list should be a list of filenames"""
return INCLUDED_FRAMES.format(Nframes=len(frame_list),
frame_dir=os.path.dirname(frame_list[0]),
frame_format=frame_format) | [
"def",
"_included_frames",
"(",
"frame_list",
",",
"frame_format",
")",
":",
"return",
"INCLUDED_FRAMES",
".",
"format",
"(",
"Nframes",
"=",
"len",
"(",
"frame_list",
")",
",",
"frame_dir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"frame_list",
"[",
"... | frame_list should be a list of filenames | [
"frame_list",
"should",
"be",
"a",
"list",
"of",
"filenames"
] | 53bdfb73b53845561914fc1f756e0c2377b9b76b | https://github.com/carpyncho/feets/blob/53bdfb73b53845561914fc1f756e0c2377b9b76b/doc/source/JSAnimation/html_writer.py#L222-L226 | train | 53,344 |
carpyncho/feets | doc/source/JSAnimation/html_writer.py | _embedded_frames | def _embedded_frames(frame_list, frame_format):
"""frame_list should be a list of base64-encoded png files"""
template = ' frames[{0}] = "data:image/{1};base64,{2}"\n'
embedded = "\n"
for i, frame_data in enumerate(frame_list):
embedded += template.format(i, frame_format,
frame_data.replace('\n', '\\\n'))
return embedded | python | def _embedded_frames(frame_list, frame_format):
"""frame_list should be a list of base64-encoded png files"""
template = ' frames[{0}] = "data:image/{1};base64,{2}"\n'
embedded = "\n"
for i, frame_data in enumerate(frame_list):
embedded += template.format(i, frame_format,
frame_data.replace('\n', '\\\n'))
return embedded | [
"def",
"_embedded_frames",
"(",
"frame_list",
",",
"frame_format",
")",
":",
"template",
"=",
"' frames[{0}] = \"data:image/{1};base64,{2}\"\\n'",
"embedded",
"=",
"\"\\n\"",
"for",
"i",
",",
"frame_data",
"in",
"enumerate",
"(",
"frame_list",
")",
":",
"embedded",
... | frame_list should be a list of base64-encoded png files | [
"frame_list",
"should",
"be",
"a",
"list",
"of",
"base64",
"-",
"encoded",
"png",
"files"
] | 53bdfb73b53845561914fc1f756e0c2377b9b76b | https://github.com/carpyncho/feets/blob/53bdfb73b53845561914fc1f756e0c2377b9b76b/doc/source/JSAnimation/html_writer.py#L229-L236 | train | 53,345 |
carpyncho/feets | feets/preprocess.py | remove_noise | def remove_noise(time, magnitude, error, error_limit=3, std_limit=5):
"""Points within 'std_limit' standard deviations from the mean and with
errors greater than 'error_limit' times the error mean are
considered as noise and thus are eliminated.
"""
data, mjd = magnitude, time
data_len = len(mjd)
error_mean = np.mean(error)
error_tolerance = error_limit * (error_mean or 1)
data_mean = np.mean(data)
data_std = np.std(data)
mjd_out, data_out, error_out = [], [], []
for i in range(data_len):
is_not_noise = (
error[i] < error_tolerance and
(np.absolute(data[i] - data_mean) / data_std) < std_limit)
if is_not_noise:
mjd_out.append(mjd[i])
data_out.append(data[i])
error_out.append(error[i])
data_out = np.asarray(data_out)
mjd_out = np.asarray(mjd_out)
error_out = np.asarray(error_out)
return mjd_out, data_out, error_out | python | def remove_noise(time, magnitude, error, error_limit=3, std_limit=5):
"""Points within 'std_limit' standard deviations from the mean and with
errors greater than 'error_limit' times the error mean are
considered as noise and thus are eliminated.
"""
data, mjd = magnitude, time
data_len = len(mjd)
error_mean = np.mean(error)
error_tolerance = error_limit * (error_mean or 1)
data_mean = np.mean(data)
data_std = np.std(data)
mjd_out, data_out, error_out = [], [], []
for i in range(data_len):
is_not_noise = (
error[i] < error_tolerance and
(np.absolute(data[i] - data_mean) / data_std) < std_limit)
if is_not_noise:
mjd_out.append(mjd[i])
data_out.append(data[i])
error_out.append(error[i])
data_out = np.asarray(data_out)
mjd_out = np.asarray(mjd_out)
error_out = np.asarray(error_out)
return mjd_out, data_out, error_out | [
"def",
"remove_noise",
"(",
"time",
",",
"magnitude",
",",
"error",
",",
"error_limit",
"=",
"3",
",",
"std_limit",
"=",
"5",
")",
":",
"data",
",",
"mjd",
"=",
"magnitude",
",",
"time",
"data_len",
"=",
"len",
"(",
"mjd",
")",
"error_mean",
"=",
"np... | Points within 'std_limit' standard deviations from the mean and with
errors greater than 'error_limit' times the error mean are
considered as noise and thus are eliminated. | [
"Points",
"within",
"std_limit",
"standard",
"deviations",
"from",
"the",
"mean",
"and",
"with",
"errors",
"greater",
"than",
"error_limit",
"times",
"the",
"error",
"mean",
"are",
"considered",
"as",
"noise",
"and",
"thus",
"are",
"eliminated",
"."
] | 53bdfb73b53845561914fc1f756e0c2377b9b76b | https://github.com/carpyncho/feets/blob/53bdfb73b53845561914fc1f756e0c2377b9b76b/feets/preprocess.py#L44-L73 | train | 53,346 |
carpyncho/feets | feets/preprocess.py | align | def align(time, time2, magnitude, magnitude2, error, error2):
"""Synchronizes the light-curves in the two different bands.
Returns
-------
aligned_time
aligned_magnitude
aligned_magnitude2
aligned_error
aligned_error2
"""
error = np.zeros(time.shape) if error is None else error
error2 = np.zeros(time2.shape) if error2 is None else error2
# this asume that the first series is the short one
sserie = pd.DataFrame({"mag": magnitude, "error": error}, index=time)
lserie = pd.DataFrame({"mag": magnitude2, "error": error2}, index=time2)
# if the second serie is logest then revert
if len(time) > len(time2):
sserie, lserie = lserie, sserie
# make the merge
merged = sserie.join(lserie, how="inner", rsuffix='2')
# recreate columns
new_time = merged.index.values
new_mag, new_mag2 = merged.mag.values, merged.mag2.values
new_error, new_error2 = merged.error.values, merged.error2.values
if len(time) > len(time2):
new_mag, new_mag2 = new_mag2, new_mag
new_error, new_error2 = new_error2, new_error
return new_time, new_mag, new_mag2, new_error, new_error2 | python | def align(time, time2, magnitude, magnitude2, error, error2):
"""Synchronizes the light-curves in the two different bands.
Returns
-------
aligned_time
aligned_magnitude
aligned_magnitude2
aligned_error
aligned_error2
"""
error = np.zeros(time.shape) if error is None else error
error2 = np.zeros(time2.shape) if error2 is None else error2
# this asume that the first series is the short one
sserie = pd.DataFrame({"mag": magnitude, "error": error}, index=time)
lserie = pd.DataFrame({"mag": magnitude2, "error": error2}, index=time2)
# if the second serie is logest then revert
if len(time) > len(time2):
sserie, lserie = lserie, sserie
# make the merge
merged = sserie.join(lserie, how="inner", rsuffix='2')
# recreate columns
new_time = merged.index.values
new_mag, new_mag2 = merged.mag.values, merged.mag2.values
new_error, new_error2 = merged.error.values, merged.error2.values
if len(time) > len(time2):
new_mag, new_mag2 = new_mag2, new_mag
new_error, new_error2 = new_error2, new_error
return new_time, new_mag, new_mag2, new_error, new_error2 | [
"def",
"align",
"(",
"time",
",",
"time2",
",",
"magnitude",
",",
"magnitude2",
",",
"error",
",",
"error2",
")",
":",
"error",
"=",
"np",
".",
"zeros",
"(",
"time",
".",
"shape",
")",
"if",
"error",
"is",
"None",
"else",
"error",
"error2",
"=",
"n... | Synchronizes the light-curves in the two different bands.
Returns
-------
aligned_time
aligned_magnitude
aligned_magnitude2
aligned_error
aligned_error2 | [
"Synchronizes",
"the",
"light",
"-",
"curves",
"in",
"the",
"two",
"different",
"bands",
"."
] | 53bdfb73b53845561914fc1f756e0c2377b9b76b | https://github.com/carpyncho/feets/blob/53bdfb73b53845561914fc1f756e0c2377b9b76b/feets/preprocess.py#L76-L113 | train | 53,347 |
carpyncho/feets | feets/datasets/ogle3.py | load_OGLE3_catalog | def load_OGLE3_catalog():
"""Return the full list of variables stars of OGLE-3 as a DataFrame
"""
with bz2.BZ2File(CATALOG_PATH) as bz2fp, warnings.catch_warnings():
warnings.simplefilter("ignore")
df = pd.read_table(bz2fp, skiprows=6)
df.rename(columns={"# ID": "ID"}, inplace=True)
return df | python | def load_OGLE3_catalog():
"""Return the full list of variables stars of OGLE-3 as a DataFrame
"""
with bz2.BZ2File(CATALOG_PATH) as bz2fp, warnings.catch_warnings():
warnings.simplefilter("ignore")
df = pd.read_table(bz2fp, skiprows=6)
df.rename(columns={"# ID": "ID"}, inplace=True)
return df | [
"def",
"load_OGLE3_catalog",
"(",
")",
":",
"with",
"bz2",
".",
"BZ2File",
"(",
"CATALOG_PATH",
")",
"as",
"bz2fp",
",",
"warnings",
".",
"catch_warnings",
"(",
")",
":",
"warnings",
".",
"simplefilter",
"(",
"\"ignore\"",
")",
"df",
"=",
"pd",
".",
"rea... | Return the full list of variables stars of OGLE-3 as a DataFrame | [
"Return",
"the",
"full",
"list",
"of",
"variables",
"stars",
"of",
"OGLE",
"-",
"3",
"as",
"a",
"DataFrame"
] | 53bdfb73b53845561914fc1f756e0c2377b9b76b | https://github.com/carpyncho/feets/blob/53bdfb73b53845561914fc1f756e0c2377b9b76b/feets/datasets/ogle3.py#L144-L152 | train | 53,348 |
carpyncho/feets | feets/datasets/ogle3.py | fetch_OGLE3 | def fetch_OGLE3(ogle3_id, data_home=None,
metadata=None, download_if_missing=True):
"""Retrieve a lighte curve from OGLE-3 database
Parameters
----------
ogle3_id : str
The id of the source (see: ``load_OGLE3_catalog()`` for
available sources.
data_home : optional, default: None
Specify another download and cache folder for the datasets. By default
all feets data is stored in '~/feets' subfolders.
metadata : bool | None
If it's True, the row of the dataframe from ``load_OGLE3_catalog()``
with the metadata of the source are added to the result.
download_if_missing : optional, True by default
If False, raise a IOError if the data is not locally available
instead of trying to download the data from the source site.
Returns
-------
A Data object.
Examples
--------
.. code-block:: pycon
>>> ds = fetch_OGLE3("OGLE-BLG-LPV-232377")
>>> ds
Data(id='OGLE-BLG-LPV-232377', ds_name='OGLE-III', bands=('I', 'V'))
>>> ds.bands
('I', 'V')
>>> ds.data.I
LightCurve(time[100], magnitude[100], error[100])
>>> ds.data.I.magnitude
array([ 13.816, 13.826, 13.818, 13.812, 13.8 , 13.827, 13.797,
13.82 , 13.804, 13.783, 13.823, 13.8 , 13.84 , 13.817,
13.802, 13.824, 13.822, 13.81 , 13.844, 13.848, 13.813,
13.836, 13.83 , 13.83 , 13.837, 13.811, 13.814, 13.82 ,
13.826, 13.822, 13.821, 13.817, 13.813, 13.809, 13.817,
13.836, 13.804, 13.801, 13.813, 13.823, 13.818, 13.831,
13.833, 13.814, 13.814, 13.812, 13.822, 13.814, 13.818,
13.817, 13.8 , 13.804, 13.799, 13.809, 13.815, 13.846,
13.796, 13.791, 13.804, 13.853, 13.839, 13.816, 13.825,
13.81 , 13.8 , 13.807, 13.819, 13.829, 13.844, 13.84 ,
13.842, 13.818, 13.801, 13.804, 13.814, 13.821, 13.821,
13.822, 13.82 , 13.803, 13.813, 13.826, 13.855, 13.865,
13.854, 13.828, 13.809, 13.828, 13.833, 13.829, 13.816,
13.82 , 13.827, 13.834, 13.811, 13.817, 13.808, 13.834,
13.814, 13.829])
"""
# retrieve the data dir for ogle
store_path = _get_OGLE3_data_home(data_home)
# the data dir for this lightcurve
file_path = os.path.join(store_path, "{}.tar".format(ogle3_id))
# members of the two bands of ogle3
members = {"I": "./{}.I.dat".format(ogle3_id),
"V": "./{}.V.dat".format(ogle3_id)}
# the url of the lightcurve
if download_if_missing:
url = URL.format(ogle3_id)
base.fetch(url, file_path)
bands = []
data = {}
with tarfile.TarFile(file_path) as tfp:
members_names = tfp.getnames()
for band_name, member_name in members.items():
if member_name in members_names:
member = tfp.getmember(member_name)
src = tfp.extractfile(member)
lc = _check_dim(np.loadtxt(src))
data[band_name] = {"time": lc[:, 0],
"magnitude": lc[:, 1],
"error": lc[:, 2]}
bands.append(band_name)
if metadata:
cat = load_OGLE3_catalog()
metadata = cat[cat.ID == ogle3_id].iloc[0].to_dict()
del cat
return Data(
id=ogle3_id, metadata=metadata, ds_name="OGLE-III",
description=DESCR, bands=bands, data=data) | python | def fetch_OGLE3(ogle3_id, data_home=None,
metadata=None, download_if_missing=True):
"""Retrieve a lighte curve from OGLE-3 database
Parameters
----------
ogle3_id : str
The id of the source (see: ``load_OGLE3_catalog()`` for
available sources.
data_home : optional, default: None
Specify another download and cache folder for the datasets. By default
all feets data is stored in '~/feets' subfolders.
metadata : bool | None
If it's True, the row of the dataframe from ``load_OGLE3_catalog()``
with the metadata of the source are added to the result.
download_if_missing : optional, True by default
If False, raise a IOError if the data is not locally available
instead of trying to download the data from the source site.
Returns
-------
A Data object.
Examples
--------
.. code-block:: pycon
>>> ds = fetch_OGLE3("OGLE-BLG-LPV-232377")
>>> ds
Data(id='OGLE-BLG-LPV-232377', ds_name='OGLE-III', bands=('I', 'V'))
>>> ds.bands
('I', 'V')
>>> ds.data.I
LightCurve(time[100], magnitude[100], error[100])
>>> ds.data.I.magnitude
array([ 13.816, 13.826, 13.818, 13.812, 13.8 , 13.827, 13.797,
13.82 , 13.804, 13.783, 13.823, 13.8 , 13.84 , 13.817,
13.802, 13.824, 13.822, 13.81 , 13.844, 13.848, 13.813,
13.836, 13.83 , 13.83 , 13.837, 13.811, 13.814, 13.82 ,
13.826, 13.822, 13.821, 13.817, 13.813, 13.809, 13.817,
13.836, 13.804, 13.801, 13.813, 13.823, 13.818, 13.831,
13.833, 13.814, 13.814, 13.812, 13.822, 13.814, 13.818,
13.817, 13.8 , 13.804, 13.799, 13.809, 13.815, 13.846,
13.796, 13.791, 13.804, 13.853, 13.839, 13.816, 13.825,
13.81 , 13.8 , 13.807, 13.819, 13.829, 13.844, 13.84 ,
13.842, 13.818, 13.801, 13.804, 13.814, 13.821, 13.821,
13.822, 13.82 , 13.803, 13.813, 13.826, 13.855, 13.865,
13.854, 13.828, 13.809, 13.828, 13.833, 13.829, 13.816,
13.82 , 13.827, 13.834, 13.811, 13.817, 13.808, 13.834,
13.814, 13.829])
"""
# retrieve the data dir for ogle
store_path = _get_OGLE3_data_home(data_home)
# the data dir for this lightcurve
file_path = os.path.join(store_path, "{}.tar".format(ogle3_id))
# members of the two bands of ogle3
members = {"I": "./{}.I.dat".format(ogle3_id),
"V": "./{}.V.dat".format(ogle3_id)}
# the url of the lightcurve
if download_if_missing:
url = URL.format(ogle3_id)
base.fetch(url, file_path)
bands = []
data = {}
with tarfile.TarFile(file_path) as tfp:
members_names = tfp.getnames()
for band_name, member_name in members.items():
if member_name in members_names:
member = tfp.getmember(member_name)
src = tfp.extractfile(member)
lc = _check_dim(np.loadtxt(src))
data[band_name] = {"time": lc[:, 0],
"magnitude": lc[:, 1],
"error": lc[:, 2]}
bands.append(band_name)
if metadata:
cat = load_OGLE3_catalog()
metadata = cat[cat.ID == ogle3_id].iloc[0].to_dict()
del cat
return Data(
id=ogle3_id, metadata=metadata, ds_name="OGLE-III",
description=DESCR, bands=bands, data=data) | [
"def",
"fetch_OGLE3",
"(",
"ogle3_id",
",",
"data_home",
"=",
"None",
",",
"metadata",
"=",
"None",
",",
"download_if_missing",
"=",
"True",
")",
":",
"# retrieve the data dir for ogle",
"store_path",
"=",
"_get_OGLE3_data_home",
"(",
"data_home",
")",
"# the data d... | Retrieve a lighte curve from OGLE-3 database
Parameters
----------
ogle3_id : str
The id of the source (see: ``load_OGLE3_catalog()`` for
available sources.
data_home : optional, default: None
Specify another download and cache folder for the datasets. By default
all feets data is stored in '~/feets' subfolders.
metadata : bool | None
If it's True, the row of the dataframe from ``load_OGLE3_catalog()``
with the metadata of the source are added to the result.
download_if_missing : optional, True by default
If False, raise a IOError if the data is not locally available
instead of trying to download the data from the source site.
Returns
-------
A Data object.
Examples
--------
.. code-block:: pycon
>>> ds = fetch_OGLE3("OGLE-BLG-LPV-232377")
>>> ds
Data(id='OGLE-BLG-LPV-232377', ds_name='OGLE-III', bands=('I', 'V'))
>>> ds.bands
('I', 'V')
>>> ds.data.I
LightCurve(time[100], magnitude[100], error[100])
>>> ds.data.I.magnitude
array([ 13.816, 13.826, 13.818, 13.812, 13.8 , 13.827, 13.797,
13.82 , 13.804, 13.783, 13.823, 13.8 , 13.84 , 13.817,
13.802, 13.824, 13.822, 13.81 , 13.844, 13.848, 13.813,
13.836, 13.83 , 13.83 , 13.837, 13.811, 13.814, 13.82 ,
13.826, 13.822, 13.821, 13.817, 13.813, 13.809, 13.817,
13.836, 13.804, 13.801, 13.813, 13.823, 13.818, 13.831,
13.833, 13.814, 13.814, 13.812, 13.822, 13.814, 13.818,
13.817, 13.8 , 13.804, 13.799, 13.809, 13.815, 13.846,
13.796, 13.791, 13.804, 13.853, 13.839, 13.816, 13.825,
13.81 , 13.8 , 13.807, 13.819, 13.829, 13.844, 13.84 ,
13.842, 13.818, 13.801, 13.804, 13.814, 13.821, 13.821,
13.822, 13.82 , 13.803, 13.813, 13.826, 13.855, 13.865,
13.854, 13.828, 13.809, 13.828, 13.833, 13.829, 13.816,
13.82 , 13.827, 13.834, 13.811, 13.817, 13.808, 13.834,
13.814, 13.829]) | [
"Retrieve",
"a",
"lighte",
"curve",
"from",
"OGLE",
"-",
"3",
"database"
] | 53bdfb73b53845561914fc1f756e0c2377b9b76b | https://github.com/carpyncho/feets/blob/53bdfb73b53845561914fc1f756e0c2377b9b76b/feets/datasets/ogle3.py#L155-L246 | train | 53,349 |
carpyncho/feets | feets/extractors/__init__.py | sort_by_dependencies | def sort_by_dependencies(exts, retry=None):
"""Calculate the Feature Extractor Resolution Order.
"""
sorted_ext, features_from_sorted = [], set()
pending = [(e, 0) for e in exts]
retry = len(exts) * 100 if retry is None else retry
while pending:
ext, cnt = pending.pop(0)
if not isinstance(ext, Extractor) and not issubclass(ext, Extractor):
msg = "Only Extractor instances are allowed. Found {}."
raise TypeError(msg.format(type(ext)))
deps = ext.get_dependencies()
if deps.difference(features_from_sorted):
if cnt + 1 > retry:
msg = "Maximun retry ({}) to sort achieved from extractor {}."
raise RuntimeError(msg.format(retry, type(ext)))
pending.append((ext, cnt + 1))
else:
sorted_ext.append(ext)
features_from_sorted.update(ext.get_features())
return tuple(sorted_ext) | python | def sort_by_dependencies(exts, retry=None):
"""Calculate the Feature Extractor Resolution Order.
"""
sorted_ext, features_from_sorted = [], set()
pending = [(e, 0) for e in exts]
retry = len(exts) * 100 if retry is None else retry
while pending:
ext, cnt = pending.pop(0)
if not isinstance(ext, Extractor) and not issubclass(ext, Extractor):
msg = "Only Extractor instances are allowed. Found {}."
raise TypeError(msg.format(type(ext)))
deps = ext.get_dependencies()
if deps.difference(features_from_sorted):
if cnt + 1 > retry:
msg = "Maximun retry ({}) to sort achieved from extractor {}."
raise RuntimeError(msg.format(retry, type(ext)))
pending.append((ext, cnt + 1))
else:
sorted_ext.append(ext)
features_from_sorted.update(ext.get_features())
return tuple(sorted_ext) | [
"def",
"sort_by_dependencies",
"(",
"exts",
",",
"retry",
"=",
"None",
")",
":",
"sorted_ext",
",",
"features_from_sorted",
"=",
"[",
"]",
",",
"set",
"(",
")",
"pending",
"=",
"[",
"(",
"e",
",",
"0",
")",
"for",
"e",
"in",
"exts",
"]",
"retry",
"... | Calculate the Feature Extractor Resolution Order. | [
"Calculate",
"the",
"Feature",
"Extractor",
"Resolution",
"Order",
"."
] | 53bdfb73b53845561914fc1f756e0c2377b9b76b | https://github.com/carpyncho/feets/blob/53bdfb73b53845561914fc1f756e0c2377b9b76b/feets/extractors/__init__.py#L98-L121 | train | 53,350 |
carpyncho/feets | paper/reports/fats_vs_feets/lomb.py | getSignificance | def getSignificance(wk1, wk2, nout, ofac):
""" returns the peak false alarm probabilities
Hence the lower is the probability and the more significant is the peak
"""
expy = exp(-wk2)
effm = 2.0*(nout)/ofac
sig = effm*expy
ind = (sig > 0.01).nonzero()
sig[ind] = 1.0-(1.0-expy[ind])**effm
return sig | python | def getSignificance(wk1, wk2, nout, ofac):
""" returns the peak false alarm probabilities
Hence the lower is the probability and the more significant is the peak
"""
expy = exp(-wk2)
effm = 2.0*(nout)/ofac
sig = effm*expy
ind = (sig > 0.01).nonzero()
sig[ind] = 1.0-(1.0-expy[ind])**effm
return sig | [
"def",
"getSignificance",
"(",
"wk1",
",",
"wk2",
",",
"nout",
",",
"ofac",
")",
":",
"expy",
"=",
"exp",
"(",
"-",
"wk2",
")",
"effm",
"=",
"2.0",
"*",
"(",
"nout",
")",
"/",
"ofac",
"sig",
"=",
"effm",
"*",
"expy",
"ind",
"=",
"(",
"sig",
"... | returns the peak false alarm probabilities
Hence the lower is the probability and the more significant is the peak | [
"returns",
"the",
"peak",
"false",
"alarm",
"probabilities",
"Hence",
"the",
"lower",
"is",
"the",
"probability",
"and",
"the",
"more",
"significant",
"is",
"the",
"peak"
] | 53bdfb73b53845561914fc1f756e0c2377b9b76b | https://github.com/carpyncho/feets/blob/53bdfb73b53845561914fc1f756e0c2377b9b76b/paper/reports/fats_vs_feets/lomb.py#L200-L209 | train | 53,351 |
carpyncho/feets | feets/datasets/base.py | fetch | def fetch(url, dest, force=False):
"""Retrieve data from an url and store it into dest.
Parameters
----------
url: str
Link to the remote data
dest: str
Path where the file must be stored
force: bool (default=False)
Overwrite if the file exists
Returns
-------
cached: bool
True if the file already exists
dest: str
The same string of the parameter
"""
cached = True
if force or not os.path.exists(dest):
cached = False
r = requests.get(url, stream=True)
if r.status_code == 200:
with open(dest, 'wb') as f:
for chunk in r.iter_content(1024):
f.write(chunk)
return cached, dest | python | def fetch(url, dest, force=False):
"""Retrieve data from an url and store it into dest.
Parameters
----------
url: str
Link to the remote data
dest: str
Path where the file must be stored
force: bool (default=False)
Overwrite if the file exists
Returns
-------
cached: bool
True if the file already exists
dest: str
The same string of the parameter
"""
cached = True
if force or not os.path.exists(dest):
cached = False
r = requests.get(url, stream=True)
if r.status_code == 200:
with open(dest, 'wb') as f:
for chunk in r.iter_content(1024):
f.write(chunk)
return cached, dest | [
"def",
"fetch",
"(",
"url",
",",
"dest",
",",
"force",
"=",
"False",
")",
":",
"cached",
"=",
"True",
"if",
"force",
"or",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"dest",
")",
":",
"cached",
"=",
"False",
"r",
"=",
"requests",
".",
"get",
... | Retrieve data from an url and store it into dest.
Parameters
----------
url: str
Link to the remote data
dest: str
Path where the file must be stored
force: bool (default=False)
Overwrite if the file exists
Returns
-------
cached: bool
True if the file already exists
dest: str
The same string of the parameter | [
"Retrieve",
"data",
"from",
"an",
"url",
"and",
"store",
"it",
"into",
"dest",
"."
] | 53bdfb73b53845561914fc1f756e0c2377b9b76b | https://github.com/carpyncho/feets/blob/53bdfb73b53845561914fc1f756e0c2377b9b76b/feets/datasets/base.py#L99-L129 | train | 53,352 |
carpyncho/feets | feets/datasets/synthetic.py | create_random | def create_random(magf, magf_params, errf, errf_params,
timef=np.linspace, timef_params=None, size=DEFAULT_SIZE,
id=None, ds_name=DS_NAME, description=DESCRIPTION,
bands=BANDS, metadata=METADATA):
"""Generate a data with any given random function.
Parameters
----------
magf : callable
Function to generate the magnitudes.
magf_params : dict-like
Parameters to feed the `magf` function.
errf : callable
Function to generate the magnitudes.
errf_params : dict-like
Parameters to feed the `errf` function.
timef : callable, (default=numpy.linspace)
Function to generate the times.
timef_params : dict-like or None, (default={"start": 0., "stop": 1.})
Parameters to feed the `timef` callable.
size : int (default=10000)
Number of obervation of the light curves
id : object (default=None)
Id of the created data.
ds_name : str (default="feets-synthetic")
Name of the dataset
description : str (default="Lightcurve created with random numbers")
Description of the data
bands : tuple of strings (default=("B", "V"))
The bands to be created
metadata : dict-like or None (default=None)
The metadata of the created data
Returns
-------
data
A Data object with a random lightcurves.
Examples
--------
.. code-block:: pycon
>>> from numpy import random
>>> create_random(
... magf=random.normal, magf_params={"loc": 0, "scale": 1},
... errf=random.normal, errf_params={"loc": 0, "scale": 0.008})
Data(id=None, ds_name='feets-synthetic', bands=('B', 'V'))
"""
timef_params = (
{"start": 0., "stop": 1.}
if timef_params is None else
timef_params.copy())
timef_params.update(num=size)
magf_params = magf_params.copy()
magf_params.update(size=size)
errf_params = errf_params.copy()
errf_params.update(size=size)
data = {}
for band in bands:
data[band] = {
"time": timef(**timef_params),
"magnitude": magf(**magf_params),
"error": errf(**errf_params)}
return Data(
id=id, ds_name=ds_name, description=description,
bands=bands, metadata=metadata, data=data) | python | def create_random(magf, magf_params, errf, errf_params,
timef=np.linspace, timef_params=None, size=DEFAULT_SIZE,
id=None, ds_name=DS_NAME, description=DESCRIPTION,
bands=BANDS, metadata=METADATA):
"""Generate a data with any given random function.
Parameters
----------
magf : callable
Function to generate the magnitudes.
magf_params : dict-like
Parameters to feed the `magf` function.
errf : callable
Function to generate the magnitudes.
errf_params : dict-like
Parameters to feed the `errf` function.
timef : callable, (default=numpy.linspace)
Function to generate the times.
timef_params : dict-like or None, (default={"start": 0., "stop": 1.})
Parameters to feed the `timef` callable.
size : int (default=10000)
Number of obervation of the light curves
id : object (default=None)
Id of the created data.
ds_name : str (default="feets-synthetic")
Name of the dataset
description : str (default="Lightcurve created with random numbers")
Description of the data
bands : tuple of strings (default=("B", "V"))
The bands to be created
metadata : dict-like or None (default=None)
The metadata of the created data
Returns
-------
data
A Data object with a random lightcurves.
Examples
--------
.. code-block:: pycon
>>> from numpy import random
>>> create_random(
... magf=random.normal, magf_params={"loc": 0, "scale": 1},
... errf=random.normal, errf_params={"loc": 0, "scale": 0.008})
Data(id=None, ds_name='feets-synthetic', bands=('B', 'V'))
"""
timef_params = (
{"start": 0., "stop": 1.}
if timef_params is None else
timef_params.copy())
timef_params.update(num=size)
magf_params = magf_params.copy()
magf_params.update(size=size)
errf_params = errf_params.copy()
errf_params.update(size=size)
data = {}
for band in bands:
data[band] = {
"time": timef(**timef_params),
"magnitude": magf(**magf_params),
"error": errf(**errf_params)}
return Data(
id=id, ds_name=ds_name, description=description,
bands=bands, metadata=metadata, data=data) | [
"def",
"create_random",
"(",
"magf",
",",
"magf_params",
",",
"errf",
",",
"errf_params",
",",
"timef",
"=",
"np",
".",
"linspace",
",",
"timef_params",
"=",
"None",
",",
"size",
"=",
"DEFAULT_SIZE",
",",
"id",
"=",
"None",
",",
"ds_name",
"=",
"DS_NAME"... | Generate a data with any given random function.
Parameters
----------
magf : callable
Function to generate the magnitudes.
magf_params : dict-like
Parameters to feed the `magf` function.
errf : callable
Function to generate the magnitudes.
errf_params : dict-like
Parameters to feed the `errf` function.
timef : callable, (default=numpy.linspace)
Function to generate the times.
timef_params : dict-like or None, (default={"start": 0., "stop": 1.})
Parameters to feed the `timef` callable.
size : int (default=10000)
Number of obervation of the light curves
id : object (default=None)
Id of the created data.
ds_name : str (default="feets-synthetic")
Name of the dataset
description : str (default="Lightcurve created with random numbers")
Description of the data
bands : tuple of strings (default=("B", "V"))
The bands to be created
metadata : dict-like or None (default=None)
The metadata of the created data
Returns
-------
data
A Data object with a random lightcurves.
Examples
--------
.. code-block:: pycon
>>> from numpy import random
>>> create_random(
... magf=random.normal, magf_params={"loc": 0, "scale": 1},
... errf=random.normal, errf_params={"loc": 0, "scale": 0.008})
Data(id=None, ds_name='feets-synthetic', bands=('B', 'V')) | [
"Generate",
"a",
"data",
"with",
"any",
"given",
"random",
"function",
"."
] | 53bdfb73b53845561914fc1f756e0c2377b9b76b | https://github.com/carpyncho/feets/blob/53bdfb73b53845561914fc1f756e0c2377b9b76b/feets/datasets/synthetic.py#L63-L135 | train | 53,353 |
carpyncho/feets | feets/datasets/synthetic.py | create_normal | def create_normal(mu=0., sigma=1., mu_err=0.,
sigma_err=1., seed=None, **kwargs):
"""Generate a data with magnitudes that follows a Gaussian
distribution. Also their errors are gaussian.
Parameters
----------
mu : float (default=0)
Mean of the gaussian distribution of magnitudes
sigma : float (default=1)
Standar deviation of the gaussian distribution of magnitude errors
mu_err : float (default=0)
Mean of the gaussian distribution of magnitudes
sigma_err : float (default=1)
Standar deviation of the gaussian distribution of magnitude errorrs
seed : {None, int, array_like}, optional
Random seed used to initialize the pseudo-random number generator.
Can be any integer between 0 and 2**32 - 1 inclusive, an
array (or other sequence) of such integers, or None (the default).
If seed is None, then RandomState will try to read data from
/dev/urandom (or the Windows analogue) if available or seed from
the clock otherwise.
kwargs : optional
extra arguments for create_random.
Returns
-------
data
A Data object with a random lightcurves.
Examples
--------
.. code-block:: pycon
>>> ds = create_normal(0, 1, 0, .0008, seed=42)
>>> ds
Data(id=None, ds_name='feets-synthetic', bands=('B', 'V'))
>>> ds.data.B
LightCurve(time[10000], magnitude[10000], error[10000])
>>> ds.data.B.time
array([ 0.00000000e+00, 1.00010001e-04, 2.00020002e-04, ...,
9.99799980e-01, 9.99899990e-01, 1.00000000e+00])
"""
random = np.random.RandomState(seed)
return create_random(
magf=random.normal, magf_params={"loc": mu, "scale": sigma},
errf=random.normal, errf_params={"loc": mu_err, "scale": sigma_err},
**kwargs) | python | def create_normal(mu=0., sigma=1., mu_err=0.,
sigma_err=1., seed=None, **kwargs):
"""Generate a data with magnitudes that follows a Gaussian
distribution. Also their errors are gaussian.
Parameters
----------
mu : float (default=0)
Mean of the gaussian distribution of magnitudes
sigma : float (default=1)
Standar deviation of the gaussian distribution of magnitude errors
mu_err : float (default=0)
Mean of the gaussian distribution of magnitudes
sigma_err : float (default=1)
Standar deviation of the gaussian distribution of magnitude errorrs
seed : {None, int, array_like}, optional
Random seed used to initialize the pseudo-random number generator.
Can be any integer between 0 and 2**32 - 1 inclusive, an
array (or other sequence) of such integers, or None (the default).
If seed is None, then RandomState will try to read data from
/dev/urandom (or the Windows analogue) if available or seed from
the clock otherwise.
kwargs : optional
extra arguments for create_random.
Returns
-------
data
A Data object with a random lightcurves.
Examples
--------
.. code-block:: pycon
>>> ds = create_normal(0, 1, 0, .0008, seed=42)
>>> ds
Data(id=None, ds_name='feets-synthetic', bands=('B', 'V'))
>>> ds.data.B
LightCurve(time[10000], magnitude[10000], error[10000])
>>> ds.data.B.time
array([ 0.00000000e+00, 1.00010001e-04, 2.00020002e-04, ...,
9.99799980e-01, 9.99899990e-01, 1.00000000e+00])
"""
random = np.random.RandomState(seed)
return create_random(
magf=random.normal, magf_params={"loc": mu, "scale": sigma},
errf=random.normal, errf_params={"loc": mu_err, "scale": sigma_err},
**kwargs) | [
"def",
"create_normal",
"(",
"mu",
"=",
"0.",
",",
"sigma",
"=",
"1.",
",",
"mu_err",
"=",
"0.",
",",
"sigma_err",
"=",
"1.",
",",
"seed",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"random",
"=",
"np",
".",
"random",
".",
"RandomState",
"("... | Generate a data with magnitudes that follows a Gaussian
distribution. Also their errors are gaussian.
Parameters
----------
mu : float (default=0)
Mean of the gaussian distribution of magnitudes
sigma : float (default=1)
Standar deviation of the gaussian distribution of magnitude errors
mu_err : float (default=0)
Mean of the gaussian distribution of magnitudes
sigma_err : float (default=1)
Standar deviation of the gaussian distribution of magnitude errorrs
seed : {None, int, array_like}, optional
Random seed used to initialize the pseudo-random number generator.
Can be any integer between 0 and 2**32 - 1 inclusive, an
array (or other sequence) of such integers, or None (the default).
If seed is None, then RandomState will try to read data from
/dev/urandom (or the Windows analogue) if available or seed from
the clock otherwise.
kwargs : optional
extra arguments for create_random.
Returns
-------
data
A Data object with a random lightcurves.
Examples
--------
.. code-block:: pycon
>>> ds = create_normal(0, 1, 0, .0008, seed=42)
>>> ds
Data(id=None, ds_name='feets-synthetic', bands=('B', 'V'))
>>> ds.data.B
LightCurve(time[10000], magnitude[10000], error[10000])
>>> ds.data.B.time
array([ 0.00000000e+00, 1.00010001e-04, 2.00020002e-04, ...,
9.99799980e-01, 9.99899990e-01, 1.00000000e+00]) | [
"Generate",
"a",
"data",
"with",
"magnitudes",
"that",
"follows",
"a",
"Gaussian",
"distribution",
".",
"Also",
"their",
"errors",
"are",
"gaussian",
"."
] | 53bdfb73b53845561914fc1f756e0c2377b9b76b | https://github.com/carpyncho/feets/blob/53bdfb73b53845561914fc1f756e0c2377b9b76b/feets/datasets/synthetic.py#L138-L190 | train | 53,354 |
carpyncho/feets | feets/datasets/synthetic.py | create_uniform | def create_uniform(low=0., high=1., mu_err=0., sigma_err=1.,
seed=None, **kwargs):
"""Generate a data with magnitudes that follows a uniform
distribution; the error instead are gaussian.
Parameters
----------
low : float, optional
Lower boundary of the output interval. All values generated will be
greater than or equal to low. The default value is 0.
high : float, optional
Upper boundary of the output interval. All values generated will be
less than high. The default value is 1.0.
mu_err : float (default=0)
Mean of the gaussian distribution of magnitudes
sigma_err : float (default=1)
Standar deviation of the gaussian distribution of magnitude errorrs
seed : {None, int, array_like}, optional
Random seed used to initialize the pseudo-random number generator.
Can be any integer between 0 and 2**32 - 1 inclusive, an
array (or other sequence) of such integers, or None (the default).
If seed is None, then RandomState will try to read data from
/dev/urandom (or the Windows analogue) if available or seed from
the clock otherwise.
kwargs : optional
extra arguments for create_random.
Returns
-------
data
A Data object with a random lightcurves.
Examples
--------
.. code-block:: pycon
>>> ds = synthetic.create_uniform(1, 2, 0, .0008, 42)
>>> ds
Data(id=None, ds_name='feets-synthetic', bands=('B', 'V'))
>>> ds.data.B.magnitude
array([ 1.37454012, 1.95071431, 1.73199394, ..., 1.94670792,
1.39748799, 1.2171404 ])
"""
random = np.random.RandomState(seed)
return create_random(
magf=random.uniform, magf_params={"low": low, "high": high},
errf=random.normal, errf_params={"loc": mu_err, "scale": sigma_err},
**kwargs) | python | def create_uniform(low=0., high=1., mu_err=0., sigma_err=1.,
seed=None, **kwargs):
"""Generate a data with magnitudes that follows a uniform
distribution; the error instead are gaussian.
Parameters
----------
low : float, optional
Lower boundary of the output interval. All values generated will be
greater than or equal to low. The default value is 0.
high : float, optional
Upper boundary of the output interval. All values generated will be
less than high. The default value is 1.0.
mu_err : float (default=0)
Mean of the gaussian distribution of magnitudes
sigma_err : float (default=1)
Standar deviation of the gaussian distribution of magnitude errorrs
seed : {None, int, array_like}, optional
Random seed used to initialize the pseudo-random number generator.
Can be any integer between 0 and 2**32 - 1 inclusive, an
array (or other sequence) of such integers, or None (the default).
If seed is None, then RandomState will try to read data from
/dev/urandom (or the Windows analogue) if available or seed from
the clock otherwise.
kwargs : optional
extra arguments for create_random.
Returns
-------
data
A Data object with a random lightcurves.
Examples
--------
.. code-block:: pycon
>>> ds = synthetic.create_uniform(1, 2, 0, .0008, 42)
>>> ds
Data(id=None, ds_name='feets-synthetic', bands=('B', 'V'))
>>> ds.data.B.magnitude
array([ 1.37454012, 1.95071431, 1.73199394, ..., 1.94670792,
1.39748799, 1.2171404 ])
"""
random = np.random.RandomState(seed)
return create_random(
magf=random.uniform, magf_params={"low": low, "high": high},
errf=random.normal, errf_params={"loc": mu_err, "scale": sigma_err},
**kwargs) | [
"def",
"create_uniform",
"(",
"low",
"=",
"0.",
",",
"high",
"=",
"1.",
",",
"mu_err",
"=",
"0.",
",",
"sigma_err",
"=",
"1.",
",",
"seed",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"random",
"=",
"np",
".",
"random",
".",
"RandomState",
"(... | Generate a data with magnitudes that follows a uniform
distribution; the error instead are gaussian.
Parameters
----------
low : float, optional
Lower boundary of the output interval. All values generated will be
greater than or equal to low. The default value is 0.
high : float, optional
Upper boundary of the output interval. All values generated will be
less than high. The default value is 1.0.
mu_err : float (default=0)
Mean of the gaussian distribution of magnitudes
sigma_err : float (default=1)
Standar deviation of the gaussian distribution of magnitude errorrs
seed : {None, int, array_like}, optional
Random seed used to initialize the pseudo-random number generator.
Can be any integer between 0 and 2**32 - 1 inclusive, an
array (or other sequence) of such integers, or None (the default).
If seed is None, then RandomState will try to read data from
/dev/urandom (or the Windows analogue) if available or seed from
the clock otherwise.
kwargs : optional
extra arguments for create_random.
Returns
-------
data
A Data object with a random lightcurves.
Examples
--------
.. code-block:: pycon
>>> ds = synthetic.create_uniform(1, 2, 0, .0008, 42)
>>> ds
Data(id=None, ds_name='feets-synthetic', bands=('B', 'V'))
>>> ds.data.B.magnitude
array([ 1.37454012, 1.95071431, 1.73199394, ..., 1.94670792,
1.39748799, 1.2171404 ]) | [
"Generate",
"a",
"data",
"with",
"magnitudes",
"that",
"follows",
"a",
"uniform",
"distribution",
";",
"the",
"error",
"instead",
"are",
"gaussian",
"."
] | 53bdfb73b53845561914fc1f756e0c2377b9b76b | https://github.com/carpyncho/feets/blob/53bdfb73b53845561914fc1f756e0c2377b9b76b/feets/datasets/synthetic.py#L193-L244 | train | 53,355 |
carpyncho/feets | feets/datasets/synthetic.py | create_periodic | def create_periodic(mu_err=0., sigma_err=1., seed=None, **kwargs):
"""Generate a data with magnitudes with periodic variability
distribution; the error instead are gaussian.
Parameters
----------
mu_err : float (default=0)
Mean of the gaussian distribution of magnitudes
sigma_err : float (default=1)
Standar deviation of the gaussian distribution of magnitude errorrs
seed : {None, int, array_like}, optional
Random seed used to initialize the pseudo-random number generator.
Can be any integer between 0 and 2**32 - 1 inclusive, an
array (or other sequence) of such integers, or None (the default).
If seed is None, then RandomState will try to read data from
/dev/urandom (or the Windows analogue) if available or seed from
the clock otherwise.
kwargs : optional
extra arguments for create_random.
Returns
-------
data
A Data object with a random lightcurves.
Examples
--------
.. code-block:: pycon
>>> ds = synthetic.create_periodic(bands=["Ks"])
>>> ds
Data(id=None, ds_name='feets-synthetic', bands=('Ks',))
>>> ds.data.Ks.magnitude
array([ 0.95428053, 0.73022685, 0.03005121, ..., -0.26305297,
2.57880082, 1.03376863])
"""
random = np.random.RandomState(seed)
size = kwargs.get("size", DEFAULT_SIZE)
times, mags, errors = [], [], []
for b in kwargs.get("bands", BANDS):
time = 100 * random.rand(size)
error = random.normal(size=size, loc=mu_err, scale=sigma_err)
mag = np.sin(2 * np.pi * time) + error * random.randn(size)
times.append(time)
errors.append(error)
mags.append(mag)
times, mags, errors = iter(times), iter(mags), iter(errors)
return create_random(
magf=lambda **k: next(mags), magf_params={},
errf=lambda **k: next(errors), errf_params={},
timef=lambda **k: next(times), timef_params={}, **kwargs) | python | def create_periodic(mu_err=0., sigma_err=1., seed=None, **kwargs):
"""Generate a data with magnitudes with periodic variability
distribution; the error instead are gaussian.
Parameters
----------
mu_err : float (default=0)
Mean of the gaussian distribution of magnitudes
sigma_err : float (default=1)
Standar deviation of the gaussian distribution of magnitude errorrs
seed : {None, int, array_like}, optional
Random seed used to initialize the pseudo-random number generator.
Can be any integer between 0 and 2**32 - 1 inclusive, an
array (or other sequence) of such integers, or None (the default).
If seed is None, then RandomState will try to read data from
/dev/urandom (or the Windows analogue) if available or seed from
the clock otherwise.
kwargs : optional
extra arguments for create_random.
Returns
-------
data
A Data object with a random lightcurves.
Examples
--------
.. code-block:: pycon
>>> ds = synthetic.create_periodic(bands=["Ks"])
>>> ds
Data(id=None, ds_name='feets-synthetic', bands=('Ks',))
>>> ds.data.Ks.magnitude
array([ 0.95428053, 0.73022685, 0.03005121, ..., -0.26305297,
2.57880082, 1.03376863])
"""
random = np.random.RandomState(seed)
size = kwargs.get("size", DEFAULT_SIZE)
times, mags, errors = [], [], []
for b in kwargs.get("bands", BANDS):
time = 100 * random.rand(size)
error = random.normal(size=size, loc=mu_err, scale=sigma_err)
mag = np.sin(2 * np.pi * time) + error * random.randn(size)
times.append(time)
errors.append(error)
mags.append(mag)
times, mags, errors = iter(times), iter(mags), iter(errors)
return create_random(
magf=lambda **k: next(mags), magf_params={},
errf=lambda **k: next(errors), errf_params={},
timef=lambda **k: next(times), timef_params={}, **kwargs) | [
"def",
"create_periodic",
"(",
"mu_err",
"=",
"0.",
",",
"sigma_err",
"=",
"1.",
",",
"seed",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"random",
"=",
"np",
".",
"random",
".",
"RandomState",
"(",
"seed",
")",
"size",
"=",
"kwargs",
".",
"get... | Generate a data with magnitudes with periodic variability
distribution; the error instead are gaussian.
Parameters
----------
mu_err : float (default=0)
Mean of the gaussian distribution of magnitudes
sigma_err : float (default=1)
Standar deviation of the gaussian distribution of magnitude errorrs
seed : {None, int, array_like}, optional
Random seed used to initialize the pseudo-random number generator.
Can be any integer between 0 and 2**32 - 1 inclusive, an
array (or other sequence) of such integers, or None (the default).
If seed is None, then RandomState will try to read data from
/dev/urandom (or the Windows analogue) if available or seed from
the clock otherwise.
kwargs : optional
extra arguments for create_random.
Returns
-------
data
A Data object with a random lightcurves.
Examples
--------
.. code-block:: pycon
>>> ds = synthetic.create_periodic(bands=["Ks"])
>>> ds
Data(id=None, ds_name='feets-synthetic', bands=('Ks',))
>>> ds.data.Ks.magnitude
array([ 0.95428053, 0.73022685, 0.03005121, ..., -0.26305297,
2.57880082, 1.03376863]) | [
"Generate",
"a",
"data",
"with",
"magnitudes",
"with",
"periodic",
"variability",
"distribution",
";",
"the",
"error",
"instead",
"are",
"gaussian",
"."
] | 53bdfb73b53845561914fc1f756e0c2377b9b76b | https://github.com/carpyncho/feets/blob/53bdfb73b53845561914fc1f756e0c2377b9b76b/feets/datasets/synthetic.py#L247-L305 | train | 53,356 |
carpyncho/feets | feets/libs/ls_fap.py | pdf_single | def pdf_single(z, N, normalization, dH=1, dK=3):
"""Probability density function for Lomb-Scargle periodogram
Compute the expected probability density function of the periodogram
for the null hypothesis - i.e. data consisting of Gaussian noise.
Parameters
----------
z : array-like
the periodogram value
N : int
the number of data points from which the periodogram was computed
normalization : string
The periodogram normalization. Must be one of
['standard', 'model', 'log', 'psd']
dH, dK : integers (optional)
The number of parameters in the null hypothesis and the model
Returns
-------
pdf : np.ndarray
The expected probability density function
Notes
-----
For normalization='psd', the distribution can only be computed for
periodograms constructed with errors specified.
All expressions used here are adapted from Table 1 of Baluev 2008 [1]_.
References
----------
.. [1] Baluev, R.V. MNRAS 385, 1279 (2008)
"""
if dK - dH != 2:
raise NotImplementedError("Degrees of freedom != 2")
Nk = N - dK
if normalization == 'psd':
return np.exp(-z)
elif normalization == 'standard':
return 0.5 * Nk * (1 - z) ** (0.5 * Nk - 1)
elif normalization == 'model':
return 0.5 * Nk * (1 + z) ** (-0.5 * Nk - 1)
elif normalization == 'log':
return 0.5 * Nk * np.exp(-0.5 * Nk * z)
else:
raise ValueError("normalization='{0}' is not recognized"
"".format(normalization)) | python | def pdf_single(z, N, normalization, dH=1, dK=3):
"""Probability density function for Lomb-Scargle periodogram
Compute the expected probability density function of the periodogram
for the null hypothesis - i.e. data consisting of Gaussian noise.
Parameters
----------
z : array-like
the periodogram value
N : int
the number of data points from which the periodogram was computed
normalization : string
The periodogram normalization. Must be one of
['standard', 'model', 'log', 'psd']
dH, dK : integers (optional)
The number of parameters in the null hypothesis and the model
Returns
-------
pdf : np.ndarray
The expected probability density function
Notes
-----
For normalization='psd', the distribution can only be computed for
periodograms constructed with errors specified.
All expressions used here are adapted from Table 1 of Baluev 2008 [1]_.
References
----------
.. [1] Baluev, R.V. MNRAS 385, 1279 (2008)
"""
if dK - dH != 2:
raise NotImplementedError("Degrees of freedom != 2")
Nk = N - dK
if normalization == 'psd':
return np.exp(-z)
elif normalization == 'standard':
return 0.5 * Nk * (1 - z) ** (0.5 * Nk - 1)
elif normalization == 'model':
return 0.5 * Nk * (1 + z) ** (-0.5 * Nk - 1)
elif normalization == 'log':
return 0.5 * Nk * np.exp(-0.5 * Nk * z)
else:
raise ValueError("normalization='{0}' is not recognized"
"".format(normalization)) | [
"def",
"pdf_single",
"(",
"z",
",",
"N",
",",
"normalization",
",",
"dH",
"=",
"1",
",",
"dK",
"=",
"3",
")",
":",
"if",
"dK",
"-",
"dH",
"!=",
"2",
":",
"raise",
"NotImplementedError",
"(",
"\"Degrees of freedom != 2\"",
")",
"Nk",
"=",
"N",
"-",
... | Probability density function for Lomb-Scargle periodogram
Compute the expected probability density function of the periodogram
for the null hypothesis - i.e. data consisting of Gaussian noise.
Parameters
----------
z : array-like
the periodogram value
N : int
the number of data points from which the periodogram was computed
normalization : string
The periodogram normalization. Must be one of
['standard', 'model', 'log', 'psd']
dH, dK : integers (optional)
The number of parameters in the null hypothesis and the model
Returns
-------
pdf : np.ndarray
The expected probability density function
Notes
-----
For normalization='psd', the distribution can only be computed for
periodograms constructed with errors specified.
All expressions used here are adapted from Table 1 of Baluev 2008 [1]_.
References
----------
.. [1] Baluev, R.V. MNRAS 385, 1279 (2008) | [
"Probability",
"density",
"function",
"for",
"Lomb",
"-",
"Scargle",
"periodogram"
] | 53bdfb73b53845561914fc1f756e0c2377b9b76b | https://github.com/carpyncho/feets/blob/53bdfb73b53845561914fc1f756e0c2377b9b76b/feets/libs/ls_fap.py#L31-L78 | train | 53,357 |
carpyncho/feets | feets/libs/ls_fap.py | cdf_single | def cdf_single(z, N, normalization, dH=1, dK=3):
"""Cumulative distribution for the Lomb-Scargle periodogram
Compute the expected cumulative distribution of the periodogram
for the null hypothesis - i.e. data consisting of Gaussian noise.
Parameters
----------
z : array-like
the periodogram value
N : int
the number of data points from which the periodogram was computed
normalization : string
The periodogram normalization. Must be one of
['standard', 'model', 'log', 'psd']
dH, dK : integers (optional)
The number of parameters in the null hypothesis and the model
Returns
-------
cdf : np.ndarray
The expected cumulative distribution function
Notes
-----
For normalization='psd', the distribution can only be computed for
periodograms constructed with errors specified.
All expressions used here are adapted from Table 1 of Baluev 2008 [1]_.
References
----------
.. [1] Baluev, R.V. MNRAS 385, 1279 (2008)
"""
return 1 - fap_single(z, N, normalization=normalization, dH=dH, dK=dK) | python | def cdf_single(z, N, normalization, dH=1, dK=3):
"""Cumulative distribution for the Lomb-Scargle periodogram
Compute the expected cumulative distribution of the periodogram
for the null hypothesis - i.e. data consisting of Gaussian noise.
Parameters
----------
z : array-like
the periodogram value
N : int
the number of data points from which the periodogram was computed
normalization : string
The periodogram normalization. Must be one of
['standard', 'model', 'log', 'psd']
dH, dK : integers (optional)
The number of parameters in the null hypothesis and the model
Returns
-------
cdf : np.ndarray
The expected cumulative distribution function
Notes
-----
For normalization='psd', the distribution can only be computed for
periodograms constructed with errors specified.
All expressions used here are adapted from Table 1 of Baluev 2008 [1]_.
References
----------
.. [1] Baluev, R.V. MNRAS 385, 1279 (2008)
"""
return 1 - fap_single(z, N, normalization=normalization, dH=dH, dK=dK) | [
"def",
"cdf_single",
"(",
"z",
",",
"N",
",",
"normalization",
",",
"dH",
"=",
"1",
",",
"dK",
"=",
"3",
")",
":",
"return",
"1",
"-",
"fap_single",
"(",
"z",
",",
"N",
",",
"normalization",
"=",
"normalization",
",",
"dH",
"=",
"dH",
",",
"dK",
... | Cumulative distribution for the Lomb-Scargle periodogram
Compute the expected cumulative distribution of the periodogram
for the null hypothesis - i.e. data consisting of Gaussian noise.
Parameters
----------
z : array-like
the periodogram value
N : int
the number of data points from which the periodogram was computed
normalization : string
The periodogram normalization. Must be one of
['standard', 'model', 'log', 'psd']
dH, dK : integers (optional)
The number of parameters in the null hypothesis and the model
Returns
-------
cdf : np.ndarray
The expected cumulative distribution function
Notes
-----
For normalization='psd', the distribution can only be computed for
periodograms constructed with errors specified.
All expressions used here are adapted from Table 1 of Baluev 2008 [1]_.
References
----------
.. [1] Baluev, R.V. MNRAS 385, 1279 (2008) | [
"Cumulative",
"distribution",
"for",
"the",
"Lomb",
"-",
"Scargle",
"periodogram"
] | 53bdfb73b53845561914fc1f756e0c2377b9b76b | https://github.com/carpyncho/feets/blob/53bdfb73b53845561914fc1f756e0c2377b9b76b/feets/libs/ls_fap.py#L132-L166 | train | 53,358 |
carpyncho/feets | feets/libs/ls_fap.py | fap_simple | def fap_simple(Z, fmax, t, y, dy, normalization='standard'):
"""False Alarm Probability based on estimated number of indep frequencies
"""
N = len(t)
T = max(t) - min(t)
N_eff = fmax * T
p_s = cdf_single(Z, N, normalization=normalization)
return 1 - p_s ** N_eff | python | def fap_simple(Z, fmax, t, y, dy, normalization='standard'):
"""False Alarm Probability based on estimated number of indep frequencies
"""
N = len(t)
T = max(t) - min(t)
N_eff = fmax * T
p_s = cdf_single(Z, N, normalization=normalization)
return 1 - p_s ** N_eff | [
"def",
"fap_simple",
"(",
"Z",
",",
"fmax",
",",
"t",
",",
"y",
",",
"dy",
",",
"normalization",
"=",
"'standard'",
")",
":",
"N",
"=",
"len",
"(",
"t",
")",
"T",
"=",
"max",
"(",
"t",
")",
"-",
"min",
"(",
"t",
")",
"N_eff",
"=",
"fmax",
"... | False Alarm Probability based on estimated number of indep frequencies | [
"False",
"Alarm",
"Probability",
"based",
"on",
"estimated",
"number",
"of",
"indep",
"frequencies"
] | 53bdfb73b53845561914fc1f756e0c2377b9b76b | https://github.com/carpyncho/feets/blob/53bdfb73b53845561914fc1f756e0c2377b9b76b/feets/libs/ls_fap.py#L196-L204 | train | 53,359 |
carpyncho/feets | feets/libs/ls_fap.py | fap_davies | def fap_davies(Z, fmax, t, y, dy, normalization='standard'):
"""Davies upper-bound to the false alarm probability
(Eqn 5 of Baluev 2008)
"""
N = len(t)
fap_s = fap_single(Z, N, normalization=normalization)
tau = tau_davies(Z, fmax, t, y, dy, normalization=normalization)
return fap_s + tau | python | def fap_davies(Z, fmax, t, y, dy, normalization='standard'):
"""Davies upper-bound to the false alarm probability
(Eqn 5 of Baluev 2008)
"""
N = len(t)
fap_s = fap_single(Z, N, normalization=normalization)
tau = tau_davies(Z, fmax, t, y, dy, normalization=normalization)
return fap_s + tau | [
"def",
"fap_davies",
"(",
"Z",
",",
"fmax",
",",
"t",
",",
"y",
",",
"dy",
",",
"normalization",
"=",
"'standard'",
")",
":",
"N",
"=",
"len",
"(",
"t",
")",
"fap_s",
"=",
"fap_single",
"(",
"Z",
",",
"N",
",",
"normalization",
"=",
"normalization"... | Davies upper-bound to the false alarm probability
(Eqn 5 of Baluev 2008) | [
"Davies",
"upper",
"-",
"bound",
"to",
"the",
"false",
"alarm",
"probability"
] | 53bdfb73b53845561914fc1f756e0c2377b9b76b | https://github.com/carpyncho/feets/blob/53bdfb73b53845561914fc1f756e0c2377b9b76b/feets/libs/ls_fap.py#L207-L215 | train | 53,360 |
carpyncho/feets | feets/libs/ls_fap.py | fap_baluev | def fap_baluev(Z, fmax, t, y, dy, normalization='standard'):
"""Alias-free approximation to false alarm probability
(Eqn 6 of Baluev 2008)
"""
cdf = cdf_single(Z, len(t), normalization)
tau = tau_davies(Z, fmax, t, y, dy, normalization=normalization)
return 1 - cdf * np.exp(-tau) | python | def fap_baluev(Z, fmax, t, y, dy, normalization='standard'):
"""Alias-free approximation to false alarm probability
(Eqn 6 of Baluev 2008)
"""
cdf = cdf_single(Z, len(t), normalization)
tau = tau_davies(Z, fmax, t, y, dy, normalization=normalization)
return 1 - cdf * np.exp(-tau) | [
"def",
"fap_baluev",
"(",
"Z",
",",
"fmax",
",",
"t",
",",
"y",
",",
"dy",
",",
"normalization",
"=",
"'standard'",
")",
":",
"cdf",
"=",
"cdf_single",
"(",
"Z",
",",
"len",
"(",
"t",
")",
",",
"normalization",
")",
"tau",
"=",
"tau_davies",
"(",
... | Alias-free approximation to false alarm probability
(Eqn 6 of Baluev 2008) | [
"Alias",
"-",
"free",
"approximation",
"to",
"false",
"alarm",
"probability"
] | 53bdfb73b53845561914fc1f756e0c2377b9b76b | https://github.com/carpyncho/feets/blob/53bdfb73b53845561914fc1f756e0c2377b9b76b/feets/libs/ls_fap.py#L218-L225 | train | 53,361 |
carpyncho/feets | feets/libs/ls_fap.py | false_alarm_probability | def false_alarm_probability(Z, fmax, t, y, dy, normalization,
method='baluev', method_kwds=None):
"""Approximate the False Alarm Probability
Parameters
----------
TODO
Returns
-------
TODO
"""
if method not in METHODS:
raise ValueError("Unrecognized method: {0}".format(method))
method = METHODS[method]
method_kwds = method_kwds or {}
return method(Z, fmax, t, y, dy, normalization, **method_kwds) | python | def false_alarm_probability(Z, fmax, t, y, dy, normalization,
method='baluev', method_kwds=None):
"""Approximate the False Alarm Probability
Parameters
----------
TODO
Returns
-------
TODO
"""
if method not in METHODS:
raise ValueError("Unrecognized method: {0}".format(method))
method = METHODS[method]
method_kwds = method_kwds or {}
return method(Z, fmax, t, y, dy, normalization, **method_kwds) | [
"def",
"false_alarm_probability",
"(",
"Z",
",",
"fmax",
",",
"t",
",",
"y",
",",
"dy",
",",
"normalization",
",",
"method",
"=",
"'baluev'",
",",
"method_kwds",
"=",
"None",
")",
":",
"if",
"method",
"not",
"in",
"METHODS",
":",
"raise",
"ValueError",
... | Approximate the False Alarm Probability
Parameters
----------
TODO
Returns
-------
TODO | [
"Approximate",
"the",
"False",
"Alarm",
"Probability"
] | 53bdfb73b53845561914fc1f756e0c2377b9b76b | https://github.com/carpyncho/feets/blob/53bdfb73b53845561914fc1f756e0c2377b9b76b/feets/libs/ls_fap.py#L250-L267 | train | 53,362 |
carpyncho/feets | doc/source/JSAnimation/IPython_display.py | anim_to_html | def anim_to_html(anim, fps=None, embed_frames=True, default_mode='loop'):
"""Generate HTML representation of the animation"""
if fps is None and hasattr(anim, '_interval'):
# Convert interval in ms to frames per second
fps = 1000. / anim._interval
plt.close(anim._fig)
if hasattr(anim, "_html_representation"):
return anim._html_representation
else:
# tempfile can't be used here: we need a filename, and this
# fails on windows. Instead, we use a custom filename generator
#with tempfile.NamedTemporaryFile(suffix='.html') as f:
with _NameOnlyTemporaryFile(suffix='.html') as f:
anim.save(f.name, writer=HTMLWriter(fps=fps,
embed_frames=embed_frames,
default_mode=default_mode))
html = open(f.name).read()
anim._html_representation = html
return html | python | def anim_to_html(anim, fps=None, embed_frames=True, default_mode='loop'):
"""Generate HTML representation of the animation"""
if fps is None and hasattr(anim, '_interval'):
# Convert interval in ms to frames per second
fps = 1000. / anim._interval
plt.close(anim._fig)
if hasattr(anim, "_html_representation"):
return anim._html_representation
else:
# tempfile can't be used here: we need a filename, and this
# fails on windows. Instead, we use a custom filename generator
#with tempfile.NamedTemporaryFile(suffix='.html') as f:
with _NameOnlyTemporaryFile(suffix='.html') as f:
anim.save(f.name, writer=HTMLWriter(fps=fps,
embed_frames=embed_frames,
default_mode=default_mode))
html = open(f.name).read()
anim._html_representation = html
return html | [
"def",
"anim_to_html",
"(",
"anim",
",",
"fps",
"=",
"None",
",",
"embed_frames",
"=",
"True",
",",
"default_mode",
"=",
"'loop'",
")",
":",
"if",
"fps",
"is",
"None",
"and",
"hasattr",
"(",
"anim",
",",
"'_interval'",
")",
":",
"# Convert interval in ms t... | Generate HTML representation of the animation | [
"Generate",
"HTML",
"representation",
"of",
"the",
"animation"
] | 53bdfb73b53845561914fc1f756e0c2377b9b76b | https://github.com/carpyncho/feets/blob/53bdfb73b53845561914fc1f756e0c2377b9b76b/doc/source/JSAnimation/IPython_display.py#L60-L80 | train | 53,363 |
carpyncho/feets | doc/source/JSAnimation/IPython_display.py | display_animation | def display_animation(anim, **kwargs):
"""Display the animation with an IPython HTML object"""
from IPython.display import HTML
return HTML(anim_to_html(anim, **kwargs)) | python | def display_animation(anim, **kwargs):
"""Display the animation with an IPython HTML object"""
from IPython.display import HTML
return HTML(anim_to_html(anim, **kwargs)) | [
"def",
"display_animation",
"(",
"anim",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
"IPython",
".",
"display",
"import",
"HTML",
"return",
"HTML",
"(",
"anim_to_html",
"(",
"anim",
",",
"*",
"*",
"kwargs",
")",
")"
] | Display the animation with an IPython HTML object | [
"Display",
"the",
"animation",
"with",
"an",
"IPython",
"HTML",
"object"
] | 53bdfb73b53845561914fc1f756e0c2377b9b76b | https://github.com/carpyncho/feets/blob/53bdfb73b53845561914fc1f756e0c2377b9b76b/doc/source/JSAnimation/IPython_display.py#L83-L86 | train | 53,364 |
carpyncho/feets | feets/utils.py | indent | def indent(s, c=" ", n=4):
"""Indent the string 's' with the character 'c', 'n' times.
Parameters
----------
s : str
String to indent
c : str, default space
String to use as indentation
n : int, default 4
Number of chars to indent
"""
indentation = c * n
return "\n".join([indentation + l for l in s.splitlines()]) | python | def indent(s, c=" ", n=4):
"""Indent the string 's' with the character 'c', 'n' times.
Parameters
----------
s : str
String to indent
c : str, default space
String to use as indentation
n : int, default 4
Number of chars to indent
"""
indentation = c * n
return "\n".join([indentation + l for l in s.splitlines()]) | [
"def",
"indent",
"(",
"s",
",",
"c",
"=",
"\" \"",
",",
"n",
"=",
"4",
")",
":",
"indentation",
"=",
"c",
"*",
"n",
"return",
"\"\\n\"",
".",
"join",
"(",
"[",
"indentation",
"+",
"l",
"for",
"l",
"in",
"s",
".",
"splitlines",
"(",
")",
"]",
... | Indent the string 's' with the character 'c', 'n' times.
Parameters
----------
s : str
String to indent
c : str, default space
String to use as indentation
n : int, default 4
Number of chars to indent | [
"Indent",
"the",
"string",
"s",
"with",
"the",
"character",
"c",
"n",
"times",
"."
] | 53bdfb73b53845561914fc1f756e0c2377b9b76b | https://github.com/carpyncho/feets/blob/53bdfb73b53845561914fc1f756e0c2377b9b76b/feets/utils.py#L37-L52 | train | 53,365 |
andersinno/hayes | hayes/ext/date_tail.py | generate_date_tail_boost_queries | def generate_date_tail_boost_queries(
field, timedeltas_and_boosts, relative_to=None):
"""
Generate a list of RangeQueries usable to boost the scores of more
recent documents.
Example:
```
queries = generate_date_tail_boost_queries("publish_date", {
timedelta(days=90): 1,
timedelta(days=30): 2,
timedelta(days=10): 4,
})
s = Search(BoolQuery(must=..., should=queries))
# ...
```
Refs:
http://elasticsearch-users.115913.n3.nabble.com/Boost-recent-documents-td2126107.html#a2126317
:param field: field name to generate the queries against
:param timedeltas_and_boosts:
dictionary of timedelta instances and their boosts. Negative or
zero boost values will not generate rangequeries.
:type timedeltas_and_boosts: dict[timedelta, float]
:param relative_to: Relative to this datetime (may be None for "now")
:return: List of RangeQueries
"""
relative_to = relative_to or datetime.datetime.now()
times = {}
for timedelta, boost in timedeltas_and_boosts.items():
date = (relative_to - timedelta).date()
times[date] = boost
times = sorted(times.items(), key=lambda i: i[0])
queries = []
for (x, time) in enumerate(times):
kwargs = {"field": field, "boost": time[1]}
if x == 0:
kwargs["lte"] = time[0]
else:
kwargs["gt"] = time[0]
if x < len(times) - 1:
kwargs["lte"] = times[x + 1][0]
if kwargs["boost"] > 0:
q = RangeQuery()
q.add_range(**kwargs)
queries.append(q)
return queries | python | def generate_date_tail_boost_queries(
field, timedeltas_and_boosts, relative_to=None):
"""
Generate a list of RangeQueries usable to boost the scores of more
recent documents.
Example:
```
queries = generate_date_tail_boost_queries("publish_date", {
timedelta(days=90): 1,
timedelta(days=30): 2,
timedelta(days=10): 4,
})
s = Search(BoolQuery(must=..., should=queries))
# ...
```
Refs:
http://elasticsearch-users.115913.n3.nabble.com/Boost-recent-documents-td2126107.html#a2126317
:param field: field name to generate the queries against
:param timedeltas_and_boosts:
dictionary of timedelta instances and their boosts. Negative or
zero boost values will not generate rangequeries.
:type timedeltas_and_boosts: dict[timedelta, float]
:param relative_to: Relative to this datetime (may be None for "now")
:return: List of RangeQueries
"""
relative_to = relative_to or datetime.datetime.now()
times = {}
for timedelta, boost in timedeltas_and_boosts.items():
date = (relative_to - timedelta).date()
times[date] = boost
times = sorted(times.items(), key=lambda i: i[0])
queries = []
for (x, time) in enumerate(times):
kwargs = {"field": field, "boost": time[1]}
if x == 0:
kwargs["lte"] = time[0]
else:
kwargs["gt"] = time[0]
if x < len(times) - 1:
kwargs["lte"] = times[x + 1][0]
if kwargs["boost"] > 0:
q = RangeQuery()
q.add_range(**kwargs)
queries.append(q)
return queries | [
"def",
"generate_date_tail_boost_queries",
"(",
"field",
",",
"timedeltas_and_boosts",
",",
"relative_to",
"=",
"None",
")",
":",
"relative_to",
"=",
"relative_to",
"or",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
"times",
"=",
"{",
"}",
"for",
"timede... | Generate a list of RangeQueries usable to boost the scores of more
recent documents.
Example:
```
queries = generate_date_tail_boost_queries("publish_date", {
timedelta(days=90): 1,
timedelta(days=30): 2,
timedelta(days=10): 4,
})
s = Search(BoolQuery(must=..., should=queries))
# ...
```
Refs:
http://elasticsearch-users.115913.n3.nabble.com/Boost-recent-documents-td2126107.html#a2126317
:param field: field name to generate the queries against
:param timedeltas_and_boosts:
dictionary of timedelta instances and their boosts. Negative or
zero boost values will not generate rangequeries.
:type timedeltas_and_boosts: dict[timedelta, float]
:param relative_to: Relative to this datetime (may be None for "now")
:return: List of RangeQueries | [
"Generate",
"a",
"list",
"of",
"RangeQueries",
"usable",
"to",
"boost",
"the",
"scores",
"of",
"more",
"recent",
"documents",
"."
] | 88d1f6b3e0cd993d9d9fc136506bd01165fea64b | https://github.com/andersinno/hayes/blob/88d1f6b3e0cd993d9d9fc136506bd01165fea64b/hayes/ext/date_tail.py#L7-L58 | train | 53,366 |
andersinno/hayes | hayes/utils.py | batch_iterable | def batch_iterable(iterable, count):
"""
Yield batches of `count` items from the given iterable.
>>> for x in batch([1, 2, 3, 4, 5, 6, 7], 3):
>>> print(x)
[1, 2, 3]
[4, 5, 6]
[7]
:param iterable: An iterable
:type iterable: Iterable
:param count: Number of items per batch. If <= 0, nothing is yielded.
:type count: int
:return: Iterable of lists of items
:rtype: Iterable[list[object]]
"""
if count <= 0:
return
current_batch = []
for item in iterable:
if len(current_batch) == count:
yield current_batch
current_batch = []
current_batch.append(item)
if current_batch:
yield current_batch | python | def batch_iterable(iterable, count):
"""
Yield batches of `count` items from the given iterable.
>>> for x in batch([1, 2, 3, 4, 5, 6, 7], 3):
>>> print(x)
[1, 2, 3]
[4, 5, 6]
[7]
:param iterable: An iterable
:type iterable: Iterable
:param count: Number of items per batch. If <= 0, nothing is yielded.
:type count: int
:return: Iterable of lists of items
:rtype: Iterable[list[object]]
"""
if count <= 0:
return
current_batch = []
for item in iterable:
if len(current_batch) == count:
yield current_batch
current_batch = []
current_batch.append(item)
if current_batch:
yield current_batch | [
"def",
"batch_iterable",
"(",
"iterable",
",",
"count",
")",
":",
"if",
"count",
"<=",
"0",
":",
"return",
"current_batch",
"=",
"[",
"]",
"for",
"item",
"in",
"iterable",
":",
"if",
"len",
"(",
"current_batch",
")",
"==",
"count",
":",
"yield",
"curre... | Yield batches of `count` items from the given iterable.
>>> for x in batch([1, 2, 3, 4, 5, 6, 7], 3):
>>> print(x)
[1, 2, 3]
[4, 5, 6]
[7]
:param iterable: An iterable
:type iterable: Iterable
:param count: Number of items per batch. If <= 0, nothing is yielded.
:type count: int
:return: Iterable of lists of items
:rtype: Iterable[list[object]] | [
"Yield",
"batches",
"of",
"count",
"items",
"from",
"the",
"given",
"iterable",
"."
] | 88d1f6b3e0cd993d9d9fc136506bd01165fea64b | https://github.com/andersinno/hayes/blob/88d1f6b3e0cd993d9d9fc136506bd01165fea64b/hayes/utils.py#L31-L57 | train | 53,367 |
ipython/ipynb | ipynb/utils.py | validate_nb | def validate_nb(nb):
"""
Validate that given notebook JSON is importable
- Check for nbformat == 4
- Check that language is python
Do not re-implement nbformat here :D
"""
if nb['nbformat'] != 4:
return False
language_name = (nb.get('metadata', {})
.get('kernelspec', {})
.get('language', '').lower())
return language_name == 'python' | python | def validate_nb(nb):
"""
Validate that given notebook JSON is importable
- Check for nbformat == 4
- Check that language is python
Do not re-implement nbformat here :D
"""
if nb['nbformat'] != 4:
return False
language_name = (nb.get('metadata', {})
.get('kernelspec', {})
.get('language', '').lower())
return language_name == 'python' | [
"def",
"validate_nb",
"(",
"nb",
")",
":",
"if",
"nb",
"[",
"'nbformat'",
"]",
"!=",
"4",
":",
"return",
"False",
"language_name",
"=",
"(",
"nb",
".",
"get",
"(",
"'metadata'",
",",
"{",
"}",
")",
".",
"get",
"(",
"'kernelspec'",
",",
"{",
"}",
... | Validate that given notebook JSON is importable
- Check for nbformat == 4
- Check that language is python
Do not re-implement nbformat here :D | [
"Validate",
"that",
"given",
"notebook",
"JSON",
"is",
"importable"
] | 2f1526a447104d7d7b97e2a8ab66bee8d2da90ad | https://github.com/ipython/ipynb/blob/2f1526a447104d7d7b97e2a8ab66bee8d2da90ad/ipynb/utils.py#L25-L40 | train | 53,368 |
ipython/ipynb | ipynb/utils.py | filter_ast | def filter_ast(module_ast):
"""
Filters a given module ast, removing non-whitelisted nodes
It allows only the following top level items:
- imports
- function definitions
- class definitions
- top level assignments where all the targets on the LHS are all caps
"""
def node_predicate(node):
"""
Return true if given node is whitelisted
"""
for an in ALLOWED_NODES:
if isinstance(node, an):
return True
# Recurse through Assign node LHS targets when an id is not specified,
# otherwise check that the id is uppercase
if isinstance(node, ast.Assign):
return all([node_predicate(t) for t in node.targets if not hasattr(t, 'id')]) \
and all([t.id.isupper() for t in node.targets if hasattr(t, 'id')])
return False
module_ast.body = [n for n in module_ast.body if node_predicate(n)]
return module_ast | python | def filter_ast(module_ast):
"""
Filters a given module ast, removing non-whitelisted nodes
It allows only the following top level items:
- imports
- function definitions
- class definitions
- top level assignments where all the targets on the LHS are all caps
"""
def node_predicate(node):
"""
Return true if given node is whitelisted
"""
for an in ALLOWED_NODES:
if isinstance(node, an):
return True
# Recurse through Assign node LHS targets when an id is not specified,
# otherwise check that the id is uppercase
if isinstance(node, ast.Assign):
return all([node_predicate(t) for t in node.targets if not hasattr(t, 'id')]) \
and all([t.id.isupper() for t in node.targets if hasattr(t, 'id')])
return False
module_ast.body = [n for n in module_ast.body if node_predicate(n)]
return module_ast | [
"def",
"filter_ast",
"(",
"module_ast",
")",
":",
"def",
"node_predicate",
"(",
"node",
")",
":",
"\"\"\"\n Return true if given node is whitelisted\n \"\"\"",
"for",
"an",
"in",
"ALLOWED_NODES",
":",
"if",
"isinstance",
"(",
"node",
",",
"an",
")",
":... | Filters a given module ast, removing non-whitelisted nodes
It allows only the following top level items:
- imports
- function definitions
- class definitions
- top level assignments where all the targets on the LHS are all caps | [
"Filters",
"a",
"given",
"module",
"ast",
"removing",
"non",
"-",
"whitelisted",
"nodes"
] | 2f1526a447104d7d7b97e2a8ab66bee8d2da90ad | https://github.com/ipython/ipynb/blob/2f1526a447104d7d7b97e2a8ab66bee8d2da90ad/ipynb/utils.py#L43-L70 | train | 53,369 |
ipython/ipynb | ipynb/utils.py | code_from_ipynb | def code_from_ipynb(nb, markdown=False):
"""
Get the code for a given notebook
nb is passed in as a dictionary that's a parsed ipynb file
"""
code = PREAMBLE
for cell in nb['cells']:
if cell['cell_type'] == 'code':
# transform the input to executable Python
code += ''.join(cell['source'])
if cell['cell_type'] == 'markdown':
code += '\n# ' + '# '.join(cell['source'])
# We want a blank newline after each cell's output.
# And the last line of source doesn't have a newline usually.
code += '\n\n'
return code | python | def code_from_ipynb(nb, markdown=False):
"""
Get the code for a given notebook
nb is passed in as a dictionary that's a parsed ipynb file
"""
code = PREAMBLE
for cell in nb['cells']:
if cell['cell_type'] == 'code':
# transform the input to executable Python
code += ''.join(cell['source'])
if cell['cell_type'] == 'markdown':
code += '\n# ' + '# '.join(cell['source'])
# We want a blank newline after each cell's output.
# And the last line of source doesn't have a newline usually.
code += '\n\n'
return code | [
"def",
"code_from_ipynb",
"(",
"nb",
",",
"markdown",
"=",
"False",
")",
":",
"code",
"=",
"PREAMBLE",
"for",
"cell",
"in",
"nb",
"[",
"'cells'",
"]",
":",
"if",
"cell",
"[",
"'cell_type'",
"]",
"==",
"'code'",
":",
"# transform the input to executable Pytho... | Get the code for a given notebook
nb is passed in as a dictionary that's a parsed ipynb file | [
"Get",
"the",
"code",
"for",
"a",
"given",
"notebook"
] | 2f1526a447104d7d7b97e2a8ab66bee8d2da90ad | https://github.com/ipython/ipynb/blob/2f1526a447104d7d7b97e2a8ab66bee8d2da90ad/ipynb/utils.py#L72-L88 | train | 53,370 |
ipython/ipynb | ipynb/fs/finder.py | FSFinder._get_paths | def _get_paths(self, fullname):
"""
Generate ordered list of paths we should look for fullname module in
"""
real_path = os.path.join(*fullname[len(self.package_prefix):].split('.'))
for base_path in sys.path:
if base_path == '':
# Empty string means process's cwd
base_path = os.getcwd()
path = os.path.join(base_path, real_path)
yield path + '.ipynb'
yield path + '.py'
yield os.path.join(path, '__init__.ipynb')
yield os.path.join(path, '__init__.py') | python | def _get_paths(self, fullname):
"""
Generate ordered list of paths we should look for fullname module in
"""
real_path = os.path.join(*fullname[len(self.package_prefix):].split('.'))
for base_path in sys.path:
if base_path == '':
# Empty string means process's cwd
base_path = os.getcwd()
path = os.path.join(base_path, real_path)
yield path + '.ipynb'
yield path + '.py'
yield os.path.join(path, '__init__.ipynb')
yield os.path.join(path, '__init__.py') | [
"def",
"_get_paths",
"(",
"self",
",",
"fullname",
")",
":",
"real_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"*",
"fullname",
"[",
"len",
"(",
"self",
".",
"package_prefix",
")",
":",
"]",
".",
"split",
"(",
"'.'",
")",
")",
"for",
"base_pat... | Generate ordered list of paths we should look for fullname module in | [
"Generate",
"ordered",
"list",
"of",
"paths",
"we",
"should",
"look",
"for",
"fullname",
"module",
"in"
] | 2f1526a447104d7d7b97e2a8ab66bee8d2da90ad | https://github.com/ipython/ipynb/blob/2f1526a447104d7d7b97e2a8ab66bee8d2da90ad/ipynb/fs/finder.py#L24-L37 | train | 53,371 |
ipython/ipynb | ipynb/fs/finder.py | FSFinder.find_spec | def find_spec(self, fullname, path, target=None):
"""
Claims modules that are under ipynb.fs
"""
if fullname.startswith(self.package_prefix):
for path in self._get_paths(fullname):
if os.path.exists(path):
return ModuleSpec(
name=fullname,
loader=self.loader_class(fullname, path),
origin=path,
is_package=(path.endswith('__init__.ipynb') or path.endswith('__init__.py')),
) | python | def find_spec(self, fullname, path, target=None):
"""
Claims modules that are under ipynb.fs
"""
if fullname.startswith(self.package_prefix):
for path in self._get_paths(fullname):
if os.path.exists(path):
return ModuleSpec(
name=fullname,
loader=self.loader_class(fullname, path),
origin=path,
is_package=(path.endswith('__init__.ipynb') or path.endswith('__init__.py')),
) | [
"def",
"find_spec",
"(",
"self",
",",
"fullname",
",",
"path",
",",
"target",
"=",
"None",
")",
":",
"if",
"fullname",
".",
"startswith",
"(",
"self",
".",
"package_prefix",
")",
":",
"for",
"path",
"in",
"self",
".",
"_get_paths",
"(",
"fullname",
")"... | Claims modules that are under ipynb.fs | [
"Claims",
"modules",
"that",
"are",
"under",
"ipynb",
".",
"fs"
] | 2f1526a447104d7d7b97e2a8ab66bee8d2da90ad | https://github.com/ipython/ipynb/blob/2f1526a447104d7d7b97e2a8ab66bee8d2da90ad/ipynb/fs/finder.py#L39-L51 | train | 53,372 |
sixty-north/python-transducers | transducer/_util.py | coroutine | def coroutine(func):
"""Decorator for priming generator-based coroutines.
"""
@wraps(func)
def start(*args, **kwargs):
g = func(*args, **kwargs)
next(g)
return g
return start | python | def coroutine(func):
"""Decorator for priming generator-based coroutines.
"""
@wraps(func)
def start(*args, **kwargs):
g = func(*args, **kwargs)
next(g)
return g
return start | [
"def",
"coroutine",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"start",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"g",
"=",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"next",
"(",
"g",
")",
"return",... | Decorator for priming generator-based coroutines. | [
"Decorator",
"for",
"priming",
"generator",
"-",
"based",
"coroutines",
"."
] | 575357e3a17ff3b4c757967afd396bf0ea042c08 | https://github.com/sixty-north/python-transducers/blob/575357e3a17ff3b4c757967afd396bf0ea042c08/transducer/_util.py#L16-L25 | train | 53,373 |
sixty-north/python-transducers | examples/cooperative.py | ticker | async def ticker(delay, to):
"""Yield numbers from 0 to `to` every `delay` seconds."""
for i in range(to):
yield i
await asyncio.sleep(delay) | python | async def ticker(delay, to):
"""Yield numbers from 0 to `to` every `delay` seconds."""
for i in range(to):
yield i
await asyncio.sleep(delay) | [
"async",
"def",
"ticker",
"(",
"delay",
",",
"to",
")",
":",
"for",
"i",
"in",
"range",
"(",
"to",
")",
":",
"yield",
"i",
"await",
"asyncio",
".",
"sleep",
"(",
"delay",
")"
] | Yield numbers from 0 to `to` every `delay` seconds. | [
"Yield",
"numbers",
"from",
"0",
"to",
"to",
"every",
"delay",
"seconds",
"."
] | 575357e3a17ff3b4c757967afd396bf0ea042c08 | https://github.com/sixty-north/python-transducers/blob/575357e3a17ff3b4c757967afd396bf0ea042c08/examples/cooperative.py#L7-L11 | train | 53,374 |
sixty-north/python-transducers | transducer/sinks.py | rprint | def rprint(sep='\n', end='\n', file=sys.stdout, flush=False):
"""A coroutine sink which prints received items stdout
Args:
sep: Optional separator to be printed between received items.
end: Optional terminator to be printed after the last item.
file: Optional stream to which to print.
flush: Optional flag to force flushing after each item.
"""
try:
first_item = (yield)
file.write(str(first_item))
if flush:
file.flush()
while True:
item = (yield)
file.write(sep)
file.write(str(item))
if flush:
file.flush()
except GeneratorExit:
file.write(end)
if flush:
file.flush() | python | def rprint(sep='\n', end='\n', file=sys.stdout, flush=False):
"""A coroutine sink which prints received items stdout
Args:
sep: Optional separator to be printed between received items.
end: Optional terminator to be printed after the last item.
file: Optional stream to which to print.
flush: Optional flag to force flushing after each item.
"""
try:
first_item = (yield)
file.write(str(first_item))
if flush:
file.flush()
while True:
item = (yield)
file.write(sep)
file.write(str(item))
if flush:
file.flush()
except GeneratorExit:
file.write(end)
if flush:
file.flush() | [
"def",
"rprint",
"(",
"sep",
"=",
"'\\n'",
",",
"end",
"=",
"'\\n'",
",",
"file",
"=",
"sys",
".",
"stdout",
",",
"flush",
"=",
"False",
")",
":",
"try",
":",
"first_item",
"=",
"(",
"yield",
")",
"file",
".",
"write",
"(",
"str",
"(",
"first_ite... | A coroutine sink which prints received items stdout
Args:
sep: Optional separator to be printed between received items.
end: Optional terminator to be printed after the last item.
file: Optional stream to which to print.
flush: Optional flag to force flushing after each item. | [
"A",
"coroutine",
"sink",
"which",
"prints",
"received",
"items",
"stdout"
] | 575357e3a17ff3b4c757967afd396bf0ea042c08 | https://github.com/sixty-north/python-transducers/blob/575357e3a17ff3b4c757967afd396bf0ea042c08/transducer/sinks.py#L14-L37 | train | 53,375 |
sixty-north/python-transducers | transducer/sources.py | iterable_source | def iterable_source(iterable, target):
"""Convert an iterable into a stream of events.
Args:
iterable: A series of items which will be sent to the target one by one.
target: The target coroutine or sink.
Returns:
An iterator over any remaining items.
"""
it = iter(iterable)
for item in it:
try:
target.send(item)
except StopIteration:
return prepend(item, it)
return empty_iter() | python | def iterable_source(iterable, target):
"""Convert an iterable into a stream of events.
Args:
iterable: A series of items which will be sent to the target one by one.
target: The target coroutine or sink.
Returns:
An iterator over any remaining items.
"""
it = iter(iterable)
for item in it:
try:
target.send(item)
except StopIteration:
return prepend(item, it)
return empty_iter() | [
"def",
"iterable_source",
"(",
"iterable",
",",
"target",
")",
":",
"it",
"=",
"iter",
"(",
"iterable",
")",
"for",
"item",
"in",
"it",
":",
"try",
":",
"target",
".",
"send",
"(",
"item",
")",
"except",
"StopIteration",
":",
"return",
"prepend",
"(",
... | Convert an iterable into a stream of events.
Args:
iterable: A series of items which will be sent to the target one by one.
target: The target coroutine or sink.
Returns:
An iterator over any remaining items. | [
"Convert",
"an",
"iterable",
"into",
"a",
"stream",
"of",
"events",
"."
] | 575357e3a17ff3b4c757967afd396bf0ea042c08 | https://github.com/sixty-north/python-transducers/blob/575357e3a17ff3b4c757967afd396bf0ea042c08/transducer/sources.py#L6-L22 | train | 53,376 |
sixty-north/python-transducers | transducer/sources.py | poisson_source | def poisson_source(rate, iterable, target):
"""Send events at random times with uniform probability.
Args:
rate: The average number of events to send per second.
iterable: A series of items which will be sent to the target one by one.
target: The target coroutine or sink.
Returns:
An iterator over any remaining items.
"""
if rate <= 0.0:
raise ValueError("poisson_source rate {} is not positive".format(rate))
it = iter(iterable)
for item in it:
duration = random.expovariate(rate)
sleep(duration)
try:
target.send(item)
except StopIteration:
return prepend(item, it)
return empty_iter() | python | def poisson_source(rate, iterable, target):
"""Send events at random times with uniform probability.
Args:
rate: The average number of events to send per second.
iterable: A series of items which will be sent to the target one by one.
target: The target coroutine or sink.
Returns:
An iterator over any remaining items.
"""
if rate <= 0.0:
raise ValueError("poisson_source rate {} is not positive".format(rate))
it = iter(iterable)
for item in it:
duration = random.expovariate(rate)
sleep(duration)
try:
target.send(item)
except StopIteration:
return prepend(item, it)
return empty_iter() | [
"def",
"poisson_source",
"(",
"rate",
",",
"iterable",
",",
"target",
")",
":",
"if",
"rate",
"<=",
"0.0",
":",
"raise",
"ValueError",
"(",
"\"poisson_source rate {} is not positive\"",
".",
"format",
"(",
"rate",
")",
")",
"it",
"=",
"iter",
"(",
"iterable"... | Send events at random times with uniform probability.
Args:
rate: The average number of events to send per second.
iterable: A series of items which will be sent to the target one by one.
target: The target coroutine or sink.
Returns:
An iterator over any remaining items. | [
"Send",
"events",
"at",
"random",
"times",
"with",
"uniform",
"probability",
"."
] | 575357e3a17ff3b4c757967afd396bf0ea042c08 | https://github.com/sixty-north/python-transducers/blob/575357e3a17ff3b4c757967afd396bf0ea042c08/transducer/sources.py#L25-L47 | train | 53,377 |
sixty-north/python-transducers | transducer/functional.py | compose | def compose(f, *fs):
"""Compose functions right to left.
compose(f, g, h)(x) -> f(g(h(x)))
Args:
f, *fs: The head and rest of a sequence of callables. The
rightmost function passed can accept any arguments and
the returned function will have the same signature as
this last provided function. All preceding functions
must be unary.
Returns:
The composition of the argument functions. The returned
function will accept the same arguments as the rightmost
passed in function.
"""
rfs = list(chain([f], fs))
rfs.reverse()
def composed(*args, **kwargs):
return reduce(
lambda result, fn: fn(result),
rfs[1:],
rfs[0](*args, **kwargs))
return composed | python | def compose(f, *fs):
"""Compose functions right to left.
compose(f, g, h)(x) -> f(g(h(x)))
Args:
f, *fs: The head and rest of a sequence of callables. The
rightmost function passed can accept any arguments and
the returned function will have the same signature as
this last provided function. All preceding functions
must be unary.
Returns:
The composition of the argument functions. The returned
function will accept the same arguments as the rightmost
passed in function.
"""
rfs = list(chain([f], fs))
rfs.reverse()
def composed(*args, **kwargs):
return reduce(
lambda result, fn: fn(result),
rfs[1:],
rfs[0](*args, **kwargs))
return composed | [
"def",
"compose",
"(",
"f",
",",
"*",
"fs",
")",
":",
"rfs",
"=",
"list",
"(",
"chain",
"(",
"[",
"f",
"]",
",",
"fs",
")",
")",
"rfs",
".",
"reverse",
"(",
")",
"def",
"composed",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"retur... | Compose functions right to left.
compose(f, g, h)(x) -> f(g(h(x)))
Args:
f, *fs: The head and rest of a sequence of callables. The
rightmost function passed can accept any arguments and
the returned function will have the same signature as
this last provided function. All preceding functions
must be unary.
Returns:
The composition of the argument functions. The returned
function will accept the same arguments as the rightmost
passed in function. | [
"Compose",
"functions",
"right",
"to",
"left",
"."
] | 575357e3a17ff3b4c757967afd396bf0ea042c08 | https://github.com/sixty-north/python-transducers/blob/575357e3a17ff3b4c757967afd396bf0ea042c08/transducer/functional.py#L5-L31 | train | 53,378 |
sixty-north/python-transducers | transducer/transducers.py | reducing | def reducing(reducer, init=UNSET):
"""Create a reducing transducer with the given reducer.
Args:
reducer: A two-argument function which will be used to combine the
partial cumulative result in the first argument with the next
item from the input stream in the second argument.
Returns: A reducing transducer: A single argument function which,
when passed a reducing function, returns a new reducing function
which entirely reduces the input stream using 'reducer' before
passing the result to the reducing function passed to the
transducer.
"""
reducer2 = reducer
def reducing_transducer(reducer):
return Reducing(reducer, reducer2, init)
return reducing_transducer | python | def reducing(reducer, init=UNSET):
"""Create a reducing transducer with the given reducer.
Args:
reducer: A two-argument function which will be used to combine the
partial cumulative result in the first argument with the next
item from the input stream in the second argument.
Returns: A reducing transducer: A single argument function which,
when passed a reducing function, returns a new reducing function
which entirely reduces the input stream using 'reducer' before
passing the result to the reducing function passed to the
transducer.
"""
reducer2 = reducer
def reducing_transducer(reducer):
return Reducing(reducer, reducer2, init)
return reducing_transducer | [
"def",
"reducing",
"(",
"reducer",
",",
"init",
"=",
"UNSET",
")",
":",
"reducer2",
"=",
"reducer",
"def",
"reducing_transducer",
"(",
"reducer",
")",
":",
"return",
"Reducing",
"(",
"reducer",
",",
"reducer2",
",",
"init",
")",
"return",
"reducing_transduce... | Create a reducing transducer with the given reducer.
Args:
reducer: A two-argument function which will be used to combine the
partial cumulative result in the first argument with the next
item from the input stream in the second argument.
Returns: A reducing transducer: A single argument function which,
when passed a reducing function, returns a new reducing function
which entirely reduces the input stream using 'reducer' before
passing the result to the reducing function passed to the
transducer. | [
"Create",
"a",
"reducing",
"transducer",
"with",
"the",
"given",
"reducer",
"."
] | 575357e3a17ff3b4c757967afd396bf0ea042c08 | https://github.com/sixty-north/python-transducers/blob/575357e3a17ff3b4c757967afd396bf0ea042c08/transducer/transducers.py#L99-L119 | train | 53,379 |
sixty-north/python-transducers | transducer/transducers.py | scanning | def scanning(reducer, init=UNSET):
"""Create a scanning reducer."""
reducer2 = reducer
def scanning_transducer(reducer):
return Scanning(reducer, reducer2, init)
return scanning_transducer | python | def scanning(reducer, init=UNSET):
"""Create a scanning reducer."""
reducer2 = reducer
def scanning_transducer(reducer):
return Scanning(reducer, reducer2, init)
return scanning_transducer | [
"def",
"scanning",
"(",
"reducer",
",",
"init",
"=",
"UNSET",
")",
":",
"reducer2",
"=",
"reducer",
"def",
"scanning_transducer",
"(",
"reducer",
")",
":",
"return",
"Scanning",
"(",
"reducer",
",",
"reducer2",
",",
"init",
")",
"return",
"scanning_transduce... | Create a scanning reducer. | [
"Create",
"a",
"scanning",
"reducer",
"."
] | 575357e3a17ff3b4c757967afd396bf0ea042c08 | https://github.com/sixty-north/python-transducers/blob/575357e3a17ff3b4c757967afd396bf0ea042c08/transducer/transducers.py#L136-L144 | train | 53,380 |
sixty-north/python-transducers | transducer/transducers.py | taking | def taking(n):
"""Create a transducer which takes the first n items"""
if n < 0:
raise ValueError("Cannot take fewer than zero ({}) items".format(n))
def taking_transducer(reducer):
return Taking(reducer, n)
return taking_transducer | python | def taking(n):
"""Create a transducer which takes the first n items"""
if n < 0:
raise ValueError("Cannot take fewer than zero ({}) items".format(n))
def taking_transducer(reducer):
return Taking(reducer, n)
return taking_transducer | [
"def",
"taking",
"(",
"n",
")",
":",
"if",
"n",
"<",
"0",
":",
"raise",
"ValueError",
"(",
"\"Cannot take fewer than zero ({}) items\"",
".",
"format",
"(",
"n",
")",
")",
"def",
"taking_transducer",
"(",
"reducer",
")",
":",
"return",
"Taking",
"(",
"redu... | Create a transducer which takes the first n items | [
"Create",
"a",
"transducer",
"which",
"takes",
"the",
"first",
"n",
"items"
] | 575357e3a17ff3b4c757967afd396bf0ea042c08 | https://github.com/sixty-north/python-transducers/blob/575357e3a17ff3b4c757967afd396bf0ea042c08/transducer/transducers.py#L207-L216 | train | 53,381 |
sixty-north/python-transducers | transducer/transducers.py | dropping | def dropping(n):
"""Create a transducer which drops the first n items"""
if n < 0:
raise ValueError("Cannot drop fewer than zero ({}) items".format(n))
def dropping_transducer(reducer):
return Dropping(reducer, n)
return dropping_transducer | python | def dropping(n):
"""Create a transducer which drops the first n items"""
if n < 0:
raise ValueError("Cannot drop fewer than zero ({}) items".format(n))
def dropping_transducer(reducer):
return Dropping(reducer, n)
return dropping_transducer | [
"def",
"dropping",
"(",
"n",
")",
":",
"if",
"n",
"<",
"0",
":",
"raise",
"ValueError",
"(",
"\"Cannot drop fewer than zero ({}) items\"",
".",
"format",
"(",
"n",
")",
")",
"def",
"dropping_transducer",
"(",
"reducer",
")",
":",
"return",
"Dropping",
"(",
... | Create a transducer which drops the first n items | [
"Create",
"a",
"transducer",
"which",
"drops",
"the",
"first",
"n",
"items"
] | 575357e3a17ff3b4c757967afd396bf0ea042c08 | https://github.com/sixty-north/python-transducers/blob/575357e3a17ff3b4c757967afd396bf0ea042c08/transducer/transducers.py#L255-L264 | train | 53,382 |
sixty-north/python-transducers | transducer/transducers.py | batching | def batching(size):
"""Create a transducer which produces non-overlapping batches."""
if size < 1:
raise ValueError("batching() size must be at least 1")
def batching_transducer(reducer):
return Batching(reducer, size)
return batching_transducer | python | def batching(size):
"""Create a transducer which produces non-overlapping batches."""
if size < 1:
raise ValueError("batching() size must be at least 1")
def batching_transducer(reducer):
return Batching(reducer, size)
return batching_transducer | [
"def",
"batching",
"(",
"size",
")",
":",
"if",
"size",
"<",
"1",
":",
"raise",
"ValueError",
"(",
"\"batching() size must be at least 1\"",
")",
"def",
"batching_transducer",
"(",
"reducer",
")",
":",
"return",
"Batching",
"(",
"reducer",
",",
"size",
")",
... | Create a transducer which produces non-overlapping batches. | [
"Create",
"a",
"transducer",
"which",
"produces",
"non",
"-",
"overlapping",
"batches",
"."
] | 575357e3a17ff3b4c757967afd396bf0ea042c08 | https://github.com/sixty-north/python-transducers/blob/575357e3a17ff3b4c757967afd396bf0ea042c08/transducer/transducers.py#L360-L369 | train | 53,383 |
sixty-north/python-transducers | transducer/transducers.py | windowing | def windowing(size, padding=UNSET, window_type=tuple):
"""Create a transducer which produces a moving window over items."""
if size < 1:
raise ValueError("windowing() size {} is not at least 1".format(size))
def windowing_transducer(reducer):
return Windowing(reducer, size, padding, window_type)
return windowing_transducer | python | def windowing(size, padding=UNSET, window_type=tuple):
"""Create a transducer which produces a moving window over items."""
if size < 1:
raise ValueError("windowing() size {} is not at least 1".format(size))
def windowing_transducer(reducer):
return Windowing(reducer, size, padding, window_type)
return windowing_transducer | [
"def",
"windowing",
"(",
"size",
",",
"padding",
"=",
"UNSET",
",",
"window_type",
"=",
"tuple",
")",
":",
"if",
"size",
"<",
"1",
":",
"raise",
"ValueError",
"(",
"\"windowing() size {} is not at least 1\"",
".",
"format",
"(",
"size",
")",
")",
"def",
"w... | Create a transducer which produces a moving window over items. | [
"Create",
"a",
"transducer",
"which",
"produces",
"a",
"moving",
"window",
"over",
"items",
"."
] | 575357e3a17ff3b4c757967afd396bf0ea042c08 | https://github.com/sixty-north/python-transducers/blob/575357e3a17ff3b4c757967afd396bf0ea042c08/transducer/transducers.py#L398-L407 | train | 53,384 |
sixty-north/python-transducers | transducer/transducers.py | first | def first(predicate=None):
"""Create a transducer which obtains the first item, then terminates."""
predicate = true if predicate is None else predicate
def first_transducer(reducer):
return First(reducer, predicate)
return first_transducer | python | def first(predicate=None):
"""Create a transducer which obtains the first item, then terminates."""
predicate = true if predicate is None else predicate
def first_transducer(reducer):
return First(reducer, predicate)
return first_transducer | [
"def",
"first",
"(",
"predicate",
"=",
"None",
")",
":",
"predicate",
"=",
"true",
"if",
"predicate",
"is",
"None",
"else",
"predicate",
"def",
"first_transducer",
"(",
"reducer",
")",
":",
"return",
"First",
"(",
"reducer",
",",
"predicate",
")",
"return"... | Create a transducer which obtains the first item, then terminates. | [
"Create",
"a",
"transducer",
"which",
"obtains",
"the",
"first",
"item",
"then",
"terminates",
"."
] | 575357e3a17ff3b4c757967afd396bf0ea042c08 | https://github.com/sixty-north/python-transducers/blob/575357e3a17ff3b4c757967afd396bf0ea042c08/transducer/transducers.py#L422-L430 | train | 53,385 |
sixty-north/python-transducers | transducer/transducers.py | last | def last(predicate=None):
"""Create a transducer which obtains the last item."""
predicate = true if predicate is None else predicate
def last_transducer(reducer):
return Last(reducer, predicate)
return last_transducer | python | def last(predicate=None):
"""Create a transducer which obtains the last item."""
predicate = true if predicate is None else predicate
def last_transducer(reducer):
return Last(reducer, predicate)
return last_transducer | [
"def",
"last",
"(",
"predicate",
"=",
"None",
")",
":",
"predicate",
"=",
"true",
"if",
"predicate",
"is",
"None",
"else",
"predicate",
"def",
"last_transducer",
"(",
"reducer",
")",
":",
"return",
"Last",
"(",
"reducer",
",",
"predicate",
")",
"return",
... | Create a transducer which obtains the last item. | [
"Create",
"a",
"transducer",
"which",
"obtains",
"the",
"last",
"item",
"."
] | 575357e3a17ff3b4c757967afd396bf0ea042c08 | https://github.com/sixty-north/python-transducers/blob/575357e3a17ff3b4c757967afd396bf0ea042c08/transducer/transducers.py#L453-L461 | train | 53,386 |
sixty-north/python-transducers | transducer/transducers.py | element_at | def element_at(index):
"""Create a transducer which obtains the item at the specified index."""
if index < 0:
raise IndexError("element_at used with illegal index {}".format(index))
def element_at_transducer(reducer):
return ElementAt(reducer, index)
return element_at_transducer | python | def element_at(index):
"""Create a transducer which obtains the item at the specified index."""
if index < 0:
raise IndexError("element_at used with illegal index {}".format(index))
def element_at_transducer(reducer):
return ElementAt(reducer, index)
return element_at_transducer | [
"def",
"element_at",
"(",
"index",
")",
":",
"if",
"index",
"<",
"0",
":",
"raise",
"IndexError",
"(",
"\"element_at used with illegal index {}\"",
".",
"format",
"(",
"index",
")",
")",
"def",
"element_at_transducer",
"(",
"reducer",
")",
":",
"return",
"Elem... | Create a transducer which obtains the item at the specified index. | [
"Create",
"a",
"transducer",
"which",
"obtains",
"the",
"item",
"at",
"the",
"specified",
"index",
"."
] | 575357e3a17ff3b4c757967afd396bf0ea042c08 | https://github.com/sixty-north/python-transducers/blob/575357e3a17ff3b4c757967afd396bf0ea042c08/transducer/transducers.py#L486-L495 | train | 53,387 |
bjodah/pycompilation | pycompilation/compilation.py | compile_sources | def compile_sources(files, CompilerRunner_=None,
destdir=None, cwd=None,
keep_dir_struct=False,
per_file_kwargs=None,
**kwargs):
"""
Compile source code files to object files.
Parameters
----------
files: iterable of path strings
source files, if cwd is given, the paths are taken as relative.
CompilerRunner_: CompilerRunner instance (optional)
could be e.g. pycompilation.FortranCompilerRunner
Will be inferred from filename extensions if missing.
destdir: path string
output directory, if cwd is given, the path is taken as relative
cwd: path string
working directory. Specify to have compiler run in other directory.
also used as root of relative paths.
keep_dir_struct: bool
Reproduce directory structure in `destdir`. default: False
per_file_kwargs: dict
dict mapping instances in `files` to keyword arguments
**kwargs: dict
default keyword arguments to pass to CompilerRunner_
"""
_per_file_kwargs = {}
if per_file_kwargs is not None:
for k, v in per_file_kwargs.items():
if isinstance(k, Glob):
for path in glob.glob(k.pathname):
_per_file_kwargs[path] = v
elif isinstance(k, ArbitraryDepthGlob):
for path in glob_at_depth(k.filename, cwd):
_per_file_kwargs[path] = v
else:
_per_file_kwargs[k] = v
# Set up destination directory
destdir = destdir or '.'
if not os.path.isdir(destdir):
if os.path.exists(destdir):
raise IOError("{} is not a directory".format(destdir))
else:
make_dirs(destdir)
if cwd is None:
cwd = '.'
for f in files:
copy(f, destdir, only_update=True, dest_is_dir=True)
# Compile files and return list of paths to the objects
dstpaths = []
for f in files:
if keep_dir_struct:
name, ext = os.path.splitext(f)
else:
name, ext = os.path.splitext(os.path.basename(f))
file_kwargs = kwargs.copy()
file_kwargs.update(_per_file_kwargs.get(f, {}))
dstpaths.append(src2obj(
f, CompilerRunner_, cwd=cwd,
**file_kwargs
))
return dstpaths | python | def compile_sources(files, CompilerRunner_=None,
destdir=None, cwd=None,
keep_dir_struct=False,
per_file_kwargs=None,
**kwargs):
"""
Compile source code files to object files.
Parameters
----------
files: iterable of path strings
source files, if cwd is given, the paths are taken as relative.
CompilerRunner_: CompilerRunner instance (optional)
could be e.g. pycompilation.FortranCompilerRunner
Will be inferred from filename extensions if missing.
destdir: path string
output directory, if cwd is given, the path is taken as relative
cwd: path string
working directory. Specify to have compiler run in other directory.
also used as root of relative paths.
keep_dir_struct: bool
Reproduce directory structure in `destdir`. default: False
per_file_kwargs: dict
dict mapping instances in `files` to keyword arguments
**kwargs: dict
default keyword arguments to pass to CompilerRunner_
"""
_per_file_kwargs = {}
if per_file_kwargs is not None:
for k, v in per_file_kwargs.items():
if isinstance(k, Glob):
for path in glob.glob(k.pathname):
_per_file_kwargs[path] = v
elif isinstance(k, ArbitraryDepthGlob):
for path in glob_at_depth(k.filename, cwd):
_per_file_kwargs[path] = v
else:
_per_file_kwargs[k] = v
# Set up destination directory
destdir = destdir or '.'
if not os.path.isdir(destdir):
if os.path.exists(destdir):
raise IOError("{} is not a directory".format(destdir))
else:
make_dirs(destdir)
if cwd is None:
cwd = '.'
for f in files:
copy(f, destdir, only_update=True, dest_is_dir=True)
# Compile files and return list of paths to the objects
dstpaths = []
for f in files:
if keep_dir_struct:
name, ext = os.path.splitext(f)
else:
name, ext = os.path.splitext(os.path.basename(f))
file_kwargs = kwargs.copy()
file_kwargs.update(_per_file_kwargs.get(f, {}))
dstpaths.append(src2obj(
f, CompilerRunner_, cwd=cwd,
**file_kwargs
))
return dstpaths | [
"def",
"compile_sources",
"(",
"files",
",",
"CompilerRunner_",
"=",
"None",
",",
"destdir",
"=",
"None",
",",
"cwd",
"=",
"None",
",",
"keep_dir_struct",
"=",
"False",
",",
"per_file_kwargs",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"_per_file_kwar... | Compile source code files to object files.
Parameters
----------
files: iterable of path strings
source files, if cwd is given, the paths are taken as relative.
CompilerRunner_: CompilerRunner instance (optional)
could be e.g. pycompilation.FortranCompilerRunner
Will be inferred from filename extensions if missing.
destdir: path string
output directory, if cwd is given, the path is taken as relative
cwd: path string
working directory. Specify to have compiler run in other directory.
also used as root of relative paths.
keep_dir_struct: bool
Reproduce directory structure in `destdir`. default: False
per_file_kwargs: dict
dict mapping instances in `files` to keyword arguments
**kwargs: dict
default keyword arguments to pass to CompilerRunner_ | [
"Compile",
"source",
"code",
"files",
"to",
"object",
"files",
"."
] | 43eac8d82f8258d30d4df77fd2ad3f3e4f4dca18 | https://github.com/bjodah/pycompilation/blob/43eac8d82f8258d30d4df77fd2ad3f3e4f4dca18/pycompilation/compilation.py#L85-L150 | train | 53,388 |
bjodah/pycompilation | pycompilation/compilation.py | link | def link(obj_files, out_file=None, shared=False, CompilerRunner_=None,
cwd=None, cplus=False, fort=False, **kwargs):
"""
Link object files.
Parameters
----------
obj_files: iterable of path strings
out_file: path string (optional)
path to executable/shared library, if missing
it will be deduced from the last item in obj_files.
shared: bool
Generate a shared library? default: False
CompilerRunner_: pycompilation.CompilerRunner subclass (optional)
If not given the `cplus` and `fort` flags will be inspected
(fallback is the C compiler)
cwd: path string
root of relative paths and working directory for compiler
cplus: bool
C++ objects? default: False
fort: bool
Fortran objects? default: False
**kwargs: dict
keyword arguments passed onto CompilerRunner_
Returns
-------
The absolute to the generated shared object / executable
"""
if out_file is None:
out_file, ext = os.path.splitext(os.path.basename(obj_files[-1]))
if shared:
out_file += sharedext
if not CompilerRunner_:
if fort:
CompilerRunner_, extra_kwargs, vendor = \
get_mixed_fort_c_linker(
vendor=kwargs.get('vendor', None),
metadir=kwargs.get('metadir', None),
cplus=cplus,
cwd=cwd,
)
for k, v in extra_kwargs.items():
expand_collection_in_dict(kwargs, k, v)
else:
if cplus:
CompilerRunner_ = CppCompilerRunner
else:
CompilerRunner_ = CCompilerRunner
flags = kwargs.pop('flags', [])
if shared:
if '-shared' not in flags:
flags.append('-shared')
# mimic GNU linker behavior on OS X when using -shared
# (otherwise likely Undefined symbol errors)
dl_flag = '-undefined dynamic_lookup'
if sys.platform == 'darwin' and dl_flag not in flags:
flags.append(dl_flag)
run_linker = kwargs.pop('run_linker', True)
if not run_linker:
raise ValueError("link(..., run_linker=False)!?")
out_file = get_abspath(out_file, cwd=cwd)
runner = CompilerRunner_(
obj_files, out_file, flags,
cwd=cwd,
**kwargs)
runner.run()
return out_file | python | def link(obj_files, out_file=None, shared=False, CompilerRunner_=None,
cwd=None, cplus=False, fort=False, **kwargs):
"""
Link object files.
Parameters
----------
obj_files: iterable of path strings
out_file: path string (optional)
path to executable/shared library, if missing
it will be deduced from the last item in obj_files.
shared: bool
Generate a shared library? default: False
CompilerRunner_: pycompilation.CompilerRunner subclass (optional)
If not given the `cplus` and `fort` flags will be inspected
(fallback is the C compiler)
cwd: path string
root of relative paths and working directory for compiler
cplus: bool
C++ objects? default: False
fort: bool
Fortran objects? default: False
**kwargs: dict
keyword arguments passed onto CompilerRunner_
Returns
-------
The absolute to the generated shared object / executable
"""
if out_file is None:
out_file, ext = os.path.splitext(os.path.basename(obj_files[-1]))
if shared:
out_file += sharedext
if not CompilerRunner_:
if fort:
CompilerRunner_, extra_kwargs, vendor = \
get_mixed_fort_c_linker(
vendor=kwargs.get('vendor', None),
metadir=kwargs.get('metadir', None),
cplus=cplus,
cwd=cwd,
)
for k, v in extra_kwargs.items():
expand_collection_in_dict(kwargs, k, v)
else:
if cplus:
CompilerRunner_ = CppCompilerRunner
else:
CompilerRunner_ = CCompilerRunner
flags = kwargs.pop('flags', [])
if shared:
if '-shared' not in flags:
flags.append('-shared')
# mimic GNU linker behavior on OS X when using -shared
# (otherwise likely Undefined symbol errors)
dl_flag = '-undefined dynamic_lookup'
if sys.platform == 'darwin' and dl_flag not in flags:
flags.append(dl_flag)
run_linker = kwargs.pop('run_linker', True)
if not run_linker:
raise ValueError("link(..., run_linker=False)!?")
out_file = get_abspath(out_file, cwd=cwd)
runner = CompilerRunner_(
obj_files, out_file, flags,
cwd=cwd,
**kwargs)
runner.run()
return out_file | [
"def",
"link",
"(",
"obj_files",
",",
"out_file",
"=",
"None",
",",
"shared",
"=",
"False",
",",
"CompilerRunner_",
"=",
"None",
",",
"cwd",
"=",
"None",
",",
"cplus",
"=",
"False",
",",
"fort",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"if"... | Link object files.
Parameters
----------
obj_files: iterable of path strings
out_file: path string (optional)
path to executable/shared library, if missing
it will be deduced from the last item in obj_files.
shared: bool
Generate a shared library? default: False
CompilerRunner_: pycompilation.CompilerRunner subclass (optional)
If not given the `cplus` and `fort` flags will be inspected
(fallback is the C compiler)
cwd: path string
root of relative paths and working directory for compiler
cplus: bool
C++ objects? default: False
fort: bool
Fortran objects? default: False
**kwargs: dict
keyword arguments passed onto CompilerRunner_
Returns
-------
The absolute to the generated shared object / executable | [
"Link",
"object",
"files",
"."
] | 43eac8d82f8258d30d4df77fd2ad3f3e4f4dca18 | https://github.com/bjodah/pycompilation/blob/43eac8d82f8258d30d4df77fd2ad3f3e4f4dca18/pycompilation/compilation.py#L153-L225 | train | 53,389 |
bjodah/pycompilation | pycompilation/compilation.py | simple_cythonize | def simple_cythonize(src, destdir=None, cwd=None, logger=None,
full_module_name=None, only_update=False,
**cy_kwargs):
"""
Generates a C file from a Cython source file.
Parameters
----------
src: path string
path to Cython source
destdir: path string (optional)
Path to output directory (default: '.')
cwd: path string (optional)
Root of relative paths (default: '.')
logger: logging.Logger
info level used.
full_module_name: string
passed to cy_compile (default: None)
only_update: bool
Only cythonize if source is newer. default: False
**cy_kwargs:
second argument passed to cy_compile.
Generates a .cpp file if cplus=True in cy_kwargs, else a .c file.
"""
from Cython.Compiler.Main import (
default_options, CompilationOptions
)
from Cython.Compiler.Main import compile as cy_compile
assert src.lower().endswith('.pyx') or src.lower().endswith('.py')
cwd = cwd or '.'
destdir = destdir or '.'
ext = '.cpp' if cy_kwargs.get('cplus', False) else '.c'
c_name = os.path.splitext(os.path.basename(src))[0] + ext
dstfile = os.path.join(destdir, c_name)
if only_update:
if not missing_or_other_newer(dstfile, src, cwd=cwd):
msg = '{0} newer than {1}, did not re-cythonize.'.format(
dstfile, src)
if logger:
logger.info(msg)
else:
print(msg)
return dstfile
if cwd:
ori_dir = os.getcwd()
else:
ori_dir = '.'
os.chdir(cwd)
try:
cy_options = CompilationOptions(default_options)
cy_options.__dict__.update(cy_kwargs)
if logger:
logger.info("Cythonizing {0} to {1}".format(
src, dstfile))
cy_result = cy_compile([src], cy_options, full_module_name=full_module_name)
if cy_result.num_errors > 0:
raise ValueError("Cython compilation failed.")
if os.path.abspath(os.path.dirname(
src)) != os.path.abspath(destdir):
if os.path.exists(dstfile):
os.unlink(dstfile)
shutil.move(os.path.join(os.path.dirname(src), c_name),
destdir)
finally:
os.chdir(ori_dir)
return dstfile | python | def simple_cythonize(src, destdir=None, cwd=None, logger=None,
full_module_name=None, only_update=False,
**cy_kwargs):
"""
Generates a C file from a Cython source file.
Parameters
----------
src: path string
path to Cython source
destdir: path string (optional)
Path to output directory (default: '.')
cwd: path string (optional)
Root of relative paths (default: '.')
logger: logging.Logger
info level used.
full_module_name: string
passed to cy_compile (default: None)
only_update: bool
Only cythonize if source is newer. default: False
**cy_kwargs:
second argument passed to cy_compile.
Generates a .cpp file if cplus=True in cy_kwargs, else a .c file.
"""
from Cython.Compiler.Main import (
default_options, CompilationOptions
)
from Cython.Compiler.Main import compile as cy_compile
assert src.lower().endswith('.pyx') or src.lower().endswith('.py')
cwd = cwd or '.'
destdir = destdir or '.'
ext = '.cpp' if cy_kwargs.get('cplus', False) else '.c'
c_name = os.path.splitext(os.path.basename(src))[0] + ext
dstfile = os.path.join(destdir, c_name)
if only_update:
if not missing_or_other_newer(dstfile, src, cwd=cwd):
msg = '{0} newer than {1}, did not re-cythonize.'.format(
dstfile, src)
if logger:
logger.info(msg)
else:
print(msg)
return dstfile
if cwd:
ori_dir = os.getcwd()
else:
ori_dir = '.'
os.chdir(cwd)
try:
cy_options = CompilationOptions(default_options)
cy_options.__dict__.update(cy_kwargs)
if logger:
logger.info("Cythonizing {0} to {1}".format(
src, dstfile))
cy_result = cy_compile([src], cy_options, full_module_name=full_module_name)
if cy_result.num_errors > 0:
raise ValueError("Cython compilation failed.")
if os.path.abspath(os.path.dirname(
src)) != os.path.abspath(destdir):
if os.path.exists(dstfile):
os.unlink(dstfile)
shutil.move(os.path.join(os.path.dirname(src), c_name),
destdir)
finally:
os.chdir(ori_dir)
return dstfile | [
"def",
"simple_cythonize",
"(",
"src",
",",
"destdir",
"=",
"None",
",",
"cwd",
"=",
"None",
",",
"logger",
"=",
"None",
",",
"full_module_name",
"=",
"None",
",",
"only_update",
"=",
"False",
",",
"*",
"*",
"cy_kwargs",
")",
":",
"from",
"Cython",
"."... | Generates a C file from a Cython source file.
Parameters
----------
src: path string
path to Cython source
destdir: path string (optional)
Path to output directory (default: '.')
cwd: path string (optional)
Root of relative paths (default: '.')
logger: logging.Logger
info level used.
full_module_name: string
passed to cy_compile (default: None)
only_update: bool
Only cythonize if source is newer. default: False
**cy_kwargs:
second argument passed to cy_compile.
Generates a .cpp file if cplus=True in cy_kwargs, else a .c file. | [
"Generates",
"a",
"C",
"file",
"from",
"a",
"Cython",
"source",
"file",
"."
] | 43eac8d82f8258d30d4df77fd2ad3f3e4f4dca18 | https://github.com/bjodah/pycompilation/blob/43eac8d82f8258d30d4df77fd2ad3f3e4f4dca18/pycompilation/compilation.py#L311-L381 | train | 53,390 |
bjodah/pycompilation | pycompilation/compilation.py | src2obj | def src2obj(srcpath, CompilerRunner_=None, objpath=None,
only_update=False, cwd=None, out_ext=None, inc_py=False,
**kwargs):
"""
Compiles a source code file to an object file.
Files ending with '.pyx' assumed to be cython files and
are dispatched to pyx2obj.
Parameters
----------
srcpath: path string
path to source file
CompilerRunner_: pycompilation.CompilerRunner subclass (optional)
Default: deduced from extension of srcpath
objpath: path string (optional)
path to generated object. defualt: deduced from srcpath
only_update: bool
only compile if source is newer than objpath. default: False
cwd: path string (optional)
working directory and root of relative paths. default: current dir.
out_ext: string
set when objpath is a dir and you want to override defaults
('.o'/'.obj' for Unix/Windows).
inc_py: bool
add Python include path to include_dirs. default: False
**kwargs: dict
keyword arguments passed onto CompilerRunner_ or pyx2obj
"""
name, ext = os.path.splitext(os.path.basename(srcpath))
if objpath is None:
if os.path.isabs(srcpath):
objpath = '.'
else:
objpath = os.path.dirname(srcpath)
objpath = objpath or '.' # avoid objpath == ''
out_ext = out_ext or objext
if os.path.isdir(objpath):
objpath = os.path.join(objpath, name+out_ext)
include_dirs = kwargs.pop('include_dirs', [])
if inc_py:
from distutils.sysconfig import get_python_inc
py_inc_dir = get_python_inc()
if py_inc_dir not in include_dirs:
include_dirs.append(py_inc_dir)
if ext.lower() == '.pyx':
return pyx2obj(srcpath, objpath=objpath,
include_dirs=include_dirs, cwd=cwd,
only_update=only_update, **kwargs)
if CompilerRunner_ is None:
CompilerRunner_, std = extension_mapping[ext.lower()]
if 'std' not in kwargs:
kwargs['std'] = std
# src2obj implies not running the linker...
run_linker = kwargs.pop('run_linker', False)
if run_linker:
raise CompilationError("src2obj called with run_linker=True")
if only_update:
if not missing_or_other_newer(objpath, srcpath, cwd=cwd):
msg = "Found {0}, did not recompile.".format(objpath)
if kwargs.get('logger', None):
kwargs['logger'].info(msg)
else:
print(msg)
return objpath
runner = CompilerRunner_(
[srcpath], objpath, include_dirs=include_dirs,
run_linker=run_linker, cwd=cwd, **kwargs)
runner.run()
return objpath | python | def src2obj(srcpath, CompilerRunner_=None, objpath=None,
only_update=False, cwd=None, out_ext=None, inc_py=False,
**kwargs):
"""
Compiles a source code file to an object file.
Files ending with '.pyx' assumed to be cython files and
are dispatched to pyx2obj.
Parameters
----------
srcpath: path string
path to source file
CompilerRunner_: pycompilation.CompilerRunner subclass (optional)
Default: deduced from extension of srcpath
objpath: path string (optional)
path to generated object. defualt: deduced from srcpath
only_update: bool
only compile if source is newer than objpath. default: False
cwd: path string (optional)
working directory and root of relative paths. default: current dir.
out_ext: string
set when objpath is a dir and you want to override defaults
('.o'/'.obj' for Unix/Windows).
inc_py: bool
add Python include path to include_dirs. default: False
**kwargs: dict
keyword arguments passed onto CompilerRunner_ or pyx2obj
"""
name, ext = os.path.splitext(os.path.basename(srcpath))
if objpath is None:
if os.path.isabs(srcpath):
objpath = '.'
else:
objpath = os.path.dirname(srcpath)
objpath = objpath or '.' # avoid objpath == ''
out_ext = out_ext or objext
if os.path.isdir(objpath):
objpath = os.path.join(objpath, name+out_ext)
include_dirs = kwargs.pop('include_dirs', [])
if inc_py:
from distutils.sysconfig import get_python_inc
py_inc_dir = get_python_inc()
if py_inc_dir not in include_dirs:
include_dirs.append(py_inc_dir)
if ext.lower() == '.pyx':
return pyx2obj(srcpath, objpath=objpath,
include_dirs=include_dirs, cwd=cwd,
only_update=only_update, **kwargs)
if CompilerRunner_ is None:
CompilerRunner_, std = extension_mapping[ext.lower()]
if 'std' not in kwargs:
kwargs['std'] = std
# src2obj implies not running the linker...
run_linker = kwargs.pop('run_linker', False)
if run_linker:
raise CompilationError("src2obj called with run_linker=True")
if only_update:
if not missing_or_other_newer(objpath, srcpath, cwd=cwd):
msg = "Found {0}, did not recompile.".format(objpath)
if kwargs.get('logger', None):
kwargs['logger'].info(msg)
else:
print(msg)
return objpath
runner = CompilerRunner_(
[srcpath], objpath, include_dirs=include_dirs,
run_linker=run_linker, cwd=cwd, **kwargs)
runner.run()
return objpath | [
"def",
"src2obj",
"(",
"srcpath",
",",
"CompilerRunner_",
"=",
"None",
",",
"objpath",
"=",
"None",
",",
"only_update",
"=",
"False",
",",
"cwd",
"=",
"None",
",",
"out_ext",
"=",
"None",
",",
"inc_py",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":"... | Compiles a source code file to an object file.
Files ending with '.pyx' assumed to be cython files and
are dispatched to pyx2obj.
Parameters
----------
srcpath: path string
path to source file
CompilerRunner_: pycompilation.CompilerRunner subclass (optional)
Default: deduced from extension of srcpath
objpath: path string (optional)
path to generated object. defualt: deduced from srcpath
only_update: bool
only compile if source is newer than objpath. default: False
cwd: path string (optional)
working directory and root of relative paths. default: current dir.
out_ext: string
set when objpath is a dir and you want to override defaults
('.o'/'.obj' for Unix/Windows).
inc_py: bool
add Python include path to include_dirs. default: False
**kwargs: dict
keyword arguments passed onto CompilerRunner_ or pyx2obj | [
"Compiles",
"a",
"source",
"code",
"file",
"to",
"an",
"object",
"file",
".",
"Files",
"ending",
"with",
".",
"pyx",
"assumed",
"to",
"be",
"cython",
"files",
"and",
"are",
"dispatched",
"to",
"pyx2obj",
"."
] | 43eac8d82f8258d30d4df77fd2ad3f3e4f4dca18 | https://github.com/bjodah/pycompilation/blob/43eac8d82f8258d30d4df77fd2ad3f3e4f4dca18/pycompilation/compilation.py#L398-L471 | train | 53,391 |
bjodah/pycompilation | pycompilation/compilation.py | compile_link_import_strings | def compile_link_import_strings(codes, build_dir=None, **kwargs):
"""
Creates a temporary directory and dumps, compiles and links
provided source code.
Parameters
----------
codes: iterable of name/source pair tuples
build_dir: string (default: None)
path to cache_dir. None implies use a temporary directory.
**kwargs:
keyword arguments passed onto `compile_link_import_py_ext`
"""
build_dir = build_dir or tempfile.mkdtemp()
if not os.path.isdir(build_dir):
raise OSError("Non-existent directory: ", build_dir)
source_files = []
if kwargs.get('logger', False) is True:
import logging
logging.basicConfig(level=logging.DEBUG)
kwargs['logger'] = logging.getLogger()
only_update = kwargs.get('only_update', True)
for name, code_ in codes:
dest = os.path.join(build_dir, name)
differs = True
md5_in_mem = md5_of_string(code_.encode('utf-8')).hexdigest()
if only_update and os.path.exists(dest):
if os.path.exists(dest+'.md5'):
md5_on_disk = open(dest+'.md5', 'rt').read()
else:
md5_on_disk = md5_of_file(dest).hexdigest()
differs = md5_on_disk != md5_in_mem
if not only_update or differs:
with open(dest, 'wt') as fh:
fh.write(code_)
open(dest+'.md5', 'wt').write(md5_in_mem)
source_files.append(dest)
return compile_link_import_py_ext(
source_files, build_dir=build_dir, **kwargs) | python | def compile_link_import_strings(codes, build_dir=None, **kwargs):
"""
Creates a temporary directory and dumps, compiles and links
provided source code.
Parameters
----------
codes: iterable of name/source pair tuples
build_dir: string (default: None)
path to cache_dir. None implies use a temporary directory.
**kwargs:
keyword arguments passed onto `compile_link_import_py_ext`
"""
build_dir = build_dir or tempfile.mkdtemp()
if not os.path.isdir(build_dir):
raise OSError("Non-existent directory: ", build_dir)
source_files = []
if kwargs.get('logger', False) is True:
import logging
logging.basicConfig(level=logging.DEBUG)
kwargs['logger'] = logging.getLogger()
only_update = kwargs.get('only_update', True)
for name, code_ in codes:
dest = os.path.join(build_dir, name)
differs = True
md5_in_mem = md5_of_string(code_.encode('utf-8')).hexdigest()
if only_update and os.path.exists(dest):
if os.path.exists(dest+'.md5'):
md5_on_disk = open(dest+'.md5', 'rt').read()
else:
md5_on_disk = md5_of_file(dest).hexdigest()
differs = md5_on_disk != md5_in_mem
if not only_update or differs:
with open(dest, 'wt') as fh:
fh.write(code_)
open(dest+'.md5', 'wt').write(md5_in_mem)
source_files.append(dest)
return compile_link_import_py_ext(
source_files, build_dir=build_dir, **kwargs) | [
"def",
"compile_link_import_strings",
"(",
"codes",
",",
"build_dir",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"build_dir",
"=",
"build_dir",
"or",
"tempfile",
".",
"mkdtemp",
"(",
")",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"build_dir... | Creates a temporary directory and dumps, compiles and links
provided source code.
Parameters
----------
codes: iterable of name/source pair tuples
build_dir: string (default: None)
path to cache_dir. None implies use a temporary directory.
**kwargs:
keyword arguments passed onto `compile_link_import_py_ext` | [
"Creates",
"a",
"temporary",
"directory",
"and",
"dumps",
"compiles",
"and",
"links",
"provided",
"source",
"code",
"."
] | 43eac8d82f8258d30d4df77fd2ad3f3e4f4dca18 | https://github.com/bjodah/pycompilation/blob/43eac8d82f8258d30d4df77fd2ad3f3e4f4dca18/pycompilation/compilation.py#L676-L717 | train | 53,392 |
BlueBrain/hpcbench | hpcbench/benchmark/osu.py | OSU.arguments | def arguments(self):
"""Dictionary providing the list of arguments for every
benchmark"""
if 'arguments' in self.attributes:
LOGGER.warning(
"WARNING: 'arguments' use in OSU yaml configuration file is deprecated. Please use 'options'!"
)
arguments = self.attributes['arguments']
if isinstance(arguments, dict):
return arguments
else:
return {k: arguments for k in self.categories}
elif 'options' in self.attributes:
options = self.attributes['options']
if isinstance(options, dict):
return options
else:
return {k: options for k in self.categories} | python | def arguments(self):
"""Dictionary providing the list of arguments for every
benchmark"""
if 'arguments' in self.attributes:
LOGGER.warning(
"WARNING: 'arguments' use in OSU yaml configuration file is deprecated. Please use 'options'!"
)
arguments = self.attributes['arguments']
if isinstance(arguments, dict):
return arguments
else:
return {k: arguments for k in self.categories}
elif 'options' in self.attributes:
options = self.attributes['options']
if isinstance(options, dict):
return options
else:
return {k: options for k in self.categories} | [
"def",
"arguments",
"(",
"self",
")",
":",
"if",
"'arguments'",
"in",
"self",
".",
"attributes",
":",
"LOGGER",
".",
"warning",
"(",
"\"WARNING: 'arguments' use in OSU yaml configuration file is deprecated. Please use 'options'!\"",
")",
"arguments",
"=",
"self",
".",
"... | Dictionary providing the list of arguments for every
benchmark | [
"Dictionary",
"providing",
"the",
"list",
"of",
"arguments",
"for",
"every",
"benchmark"
] | 192d0ec142b897157ec25f131d1ef28f84752592 | https://github.com/BlueBrain/hpcbench/blob/192d0ec142b897157ec25f131d1ef28f84752592/hpcbench/benchmark/osu.py#L289-L306 | train | 53,393 |
portfoliome/foil | foil/serializers.py | _ | def _(obj):
"""ISO 8601 format. Interprets naive datetime as UTC with zulu suffix."""
tz_offset = obj.utcoffset()
if not tz_offset or tz_offset == UTC_ZERO:
iso_datetime = obj.strftime('%Y-%m-%dT%H:%M:%S.%fZ')
else:
iso_datetime = obj.isoformat()
return iso_datetime | python | def _(obj):
"""ISO 8601 format. Interprets naive datetime as UTC with zulu suffix."""
tz_offset = obj.utcoffset()
if not tz_offset or tz_offset == UTC_ZERO:
iso_datetime = obj.strftime('%Y-%m-%dT%H:%M:%S.%fZ')
else:
iso_datetime = obj.isoformat()
return iso_datetime | [
"def",
"_",
"(",
"obj",
")",
":",
"tz_offset",
"=",
"obj",
".",
"utcoffset",
"(",
")",
"if",
"not",
"tz_offset",
"or",
"tz_offset",
"==",
"UTC_ZERO",
":",
"iso_datetime",
"=",
"obj",
".",
"strftime",
"(",
"'%Y-%m-%dT%H:%M:%S.%fZ'",
")",
"else",
":",
"iso... | ISO 8601 format. Interprets naive datetime as UTC with zulu suffix. | [
"ISO",
"8601",
"format",
".",
"Interprets",
"naive",
"datetime",
"as",
"UTC",
"with",
"zulu",
"suffix",
"."
] | b66d8cf4ab048a387d8c7a033b47e922ed6917d6 | https://github.com/portfoliome/foil/blob/b66d8cf4ab048a387d8c7a033b47e922ed6917d6/foil/serializers.py#L26-L36 | train | 53,394 |
Metatab/metatab | metatab/resolver.py | WebResolver.get_row_generator | def get_row_generator(self, ref, cache=None):
"""Return a row generator for a reference"""
from inspect import isgenerator
from rowgenerators import get_generator
g = get_generator(ref)
if not g:
raise GenerateError("Cant figure out how to generate rows from {} ref: {}".format(type(ref), ref))
else:
return g | python | def get_row_generator(self, ref, cache=None):
"""Return a row generator for a reference"""
from inspect import isgenerator
from rowgenerators import get_generator
g = get_generator(ref)
if not g:
raise GenerateError("Cant figure out how to generate rows from {} ref: {}".format(type(ref), ref))
else:
return g | [
"def",
"get_row_generator",
"(",
"self",
",",
"ref",
",",
"cache",
"=",
"None",
")",
":",
"from",
"inspect",
"import",
"isgenerator",
"from",
"rowgenerators",
"import",
"get_generator",
"g",
"=",
"get_generator",
"(",
"ref",
")",
"if",
"not",
"g",
":",
"ra... | Return a row generator for a reference | [
"Return",
"a",
"row",
"generator",
"for",
"a",
"reference"
] | 8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22 | https://github.com/Metatab/metatab/blob/8336ec3e4bd8da84a9a5cb86de1c1086e14b8b22/metatab/resolver.py#L34-L45 | train | 53,395 |
portfoliome/foil | foil/filters.py | create_key_filter | def create_key_filter(properties: Dict[str, list]) -> List[Tuple]:
"""Generate combinations of key, value pairs for each key in properties.
Examples
--------
properties = {'ent': ['geo_rev', 'supply_chain'], 'own', 'fi'}
>> create_key_filter(properties)
--> [('ent', 'geo_rev'), ('ent', 'supply_chain'), ('own', 'fi')]
"""
combinations = (product([k], v) for k, v in properties.items())
return chain.from_iterable(combinations) | python | def create_key_filter(properties: Dict[str, list]) -> List[Tuple]:
"""Generate combinations of key, value pairs for each key in properties.
Examples
--------
properties = {'ent': ['geo_rev', 'supply_chain'], 'own', 'fi'}
>> create_key_filter(properties)
--> [('ent', 'geo_rev'), ('ent', 'supply_chain'), ('own', 'fi')]
"""
combinations = (product([k], v) for k, v in properties.items())
return chain.from_iterable(combinations) | [
"def",
"create_key_filter",
"(",
"properties",
":",
"Dict",
"[",
"str",
",",
"list",
"]",
")",
"->",
"List",
"[",
"Tuple",
"]",
":",
"combinations",
"=",
"(",
"product",
"(",
"[",
"k",
"]",
",",
"v",
")",
"for",
"k",
",",
"v",
"in",
"properties",
... | Generate combinations of key, value pairs for each key in properties.
Examples
--------
properties = {'ent': ['geo_rev', 'supply_chain'], 'own', 'fi'}
>> create_key_filter(properties)
--> [('ent', 'geo_rev'), ('ent', 'supply_chain'), ('own', 'fi')] | [
"Generate",
"combinations",
"of",
"key",
"value",
"pairs",
"for",
"each",
"key",
"in",
"properties",
"."
] | b66d8cf4ab048a387d8c7a033b47e922ed6917d6 | https://github.com/portfoliome/foil/blob/b66d8cf4ab048a387d8c7a033b47e922ed6917d6/foil/filters.py#L38-L50 | train | 53,396 |
portfoliome/foil | foil/filters.py | create_indexer | def create_indexer(indexes: list):
"""Create indexer function to pluck values from list."""
if len(indexes) == 1:
index = indexes[0]
return lambda x: (x[index],)
else:
return itemgetter(*indexes) | python | def create_indexer(indexes: list):
"""Create indexer function to pluck values from list."""
if len(indexes) == 1:
index = indexes[0]
return lambda x: (x[index],)
else:
return itemgetter(*indexes) | [
"def",
"create_indexer",
"(",
"indexes",
":",
"list",
")",
":",
"if",
"len",
"(",
"indexes",
")",
"==",
"1",
":",
"index",
"=",
"indexes",
"[",
"0",
"]",
"return",
"lambda",
"x",
":",
"(",
"x",
"[",
"index",
"]",
",",
")",
"else",
":",
"return",
... | Create indexer function to pluck values from list. | [
"Create",
"indexer",
"function",
"to",
"pluck",
"values",
"from",
"list",
"."
] | b66d8cf4ab048a387d8c7a033b47e922ed6917d6 | https://github.com/portfoliome/foil/blob/b66d8cf4ab048a387d8c7a033b47e922ed6917d6/foil/filters.py#L53-L60 | train | 53,397 |
portfoliome/foil | foil/filters.py | AttributeFilter.including | def including(self, sequence) -> Generator:
"""Include the sequence elements matching the filter set."""
return (element for element in sequence
if self.indexer(element) in self.predicates) | python | def including(self, sequence) -> Generator:
"""Include the sequence elements matching the filter set."""
return (element for element in sequence
if self.indexer(element) in self.predicates) | [
"def",
"including",
"(",
"self",
",",
"sequence",
")",
"->",
"Generator",
":",
"return",
"(",
"element",
"for",
"element",
"in",
"sequence",
"if",
"self",
".",
"indexer",
"(",
"element",
")",
"in",
"self",
".",
"predicates",
")"
] | Include the sequence elements matching the filter set. | [
"Include",
"the",
"sequence",
"elements",
"matching",
"the",
"filter",
"set",
"."
] | b66d8cf4ab048a387d8c7a033b47e922ed6917d6 | https://github.com/portfoliome/foil/blob/b66d8cf4ab048a387d8c7a033b47e922ed6917d6/foil/filters.py#L27-L30 | train | 53,398 |
portfoliome/foil | foil/filters.py | AttributeFilter.excluding | def excluding(self, sequence) -> Generator:
"""Exclude the sequence elements matching the filter set."""
return (element for element in sequence
if self.indexer(element) not in self.predicates) | python | def excluding(self, sequence) -> Generator:
"""Exclude the sequence elements matching the filter set."""
return (element for element in sequence
if self.indexer(element) not in self.predicates) | [
"def",
"excluding",
"(",
"self",
",",
"sequence",
")",
"->",
"Generator",
":",
"return",
"(",
"element",
"for",
"element",
"in",
"sequence",
"if",
"self",
".",
"indexer",
"(",
"element",
")",
"not",
"in",
"self",
".",
"predicates",
")"
] | Exclude the sequence elements matching the filter set. | [
"Exclude",
"the",
"sequence",
"elements",
"matching",
"the",
"filter",
"set",
"."
] | b66d8cf4ab048a387d8c7a033b47e922ed6917d6 | https://github.com/portfoliome/foil/blob/b66d8cf4ab048a387d8c7a033b47e922ed6917d6/foil/filters.py#L32-L35 | train | 53,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.