repository_name stringlengths 5 67 | func_path_in_repository stringlengths 4 234 | func_name stringlengths 0 314 | whole_func_string stringlengths 52 3.87M | language stringclasses 6
values | func_code_string stringlengths 52 3.87M | func_code_tokens listlengths 15 672k | func_documentation_string stringlengths 1 47.2k | func_documentation_tokens listlengths 1 3.92k | split_name stringclasses 1
value | func_code_url stringlengths 85 339 |
|---|---|---|---|---|---|---|---|---|---|---|
ohenrik/tabs | tabs/tables.py | Table._process_table | def _process_table(self, cache=True):
"""Applies the post processors"""
table = self.source()
assert not isinstance(table, None.__class__), \
"{}.source needs to return something, not None".format(self.__class__.__name__)
table = post_process(table, self.post_processors())
if cache:
self.to_cache(table)
return table | python | def _process_table(self, cache=True):
"""Applies the post processors"""
table = self.source()
assert not isinstance(table, None.__class__), \
"{}.source needs to return something, not None".format(self.__class__.__name__)
table = post_process(table, self.post_processors())
if cache:
self.to_cache(table)
return table | [
"def",
"_process_table",
"(",
"self",
",",
"cache",
"=",
"True",
")",
":",
"table",
"=",
"self",
".",
"source",
"(",
")",
"assert",
"not",
"isinstance",
"(",
"table",
",",
"None",
".",
"__class__",
")",
",",
"\"{}.source needs to return something, not None\"",... | Applies the post processors | [
"Applies",
"the",
"post",
"processors"
] | train | https://github.com/ohenrik/tabs/blob/039ced6c5612ecdd551aeaac63789862aba05711/tabs/tables.py#L211-L219 |
ohenrik/tabs | tabs/tables.py | Table.fetch | def fetch(self, rebuild=False, cache=True):
"""Fetches the table and applies all post processors.
Args:
rebuild (bool): Rebuild the table and ignore cache. Default: False
cache (bool): Cache the finished table for faster future loading.
Default: True
"""
if rebuild:
return self._process_table(cache)
try:
return self.read_cache()
except FileNotFoundError:
return self._process_table(cache) | python | def fetch(self, rebuild=False, cache=True):
"""Fetches the table and applies all post processors.
Args:
rebuild (bool): Rebuild the table and ignore cache. Default: False
cache (bool): Cache the finished table for faster future loading.
Default: True
"""
if rebuild:
return self._process_table(cache)
try:
return self.read_cache()
except FileNotFoundError:
return self._process_table(cache) | [
"def",
"fetch",
"(",
"self",
",",
"rebuild",
"=",
"False",
",",
"cache",
"=",
"True",
")",
":",
"if",
"rebuild",
":",
"return",
"self",
".",
"_process_table",
"(",
"cache",
")",
"try",
":",
"return",
"self",
".",
"read_cache",
"(",
")",
"except",
"Fi... | Fetches the table and applies all post processors.
Args:
rebuild (bool): Rebuild the table and ignore cache. Default: False
cache (bool): Cache the finished table for faster future loading.
Default: True | [
"Fetches",
"the",
"table",
"and",
"applies",
"all",
"post",
"processors",
".",
"Args",
":",
"rebuild",
"(",
"bool",
")",
":",
"Rebuild",
"the",
"table",
"and",
"ignore",
"cache",
".",
"Default",
":",
"False",
"cache",
"(",
"bool",
")",
":",
"Cache",
"t... | train | https://github.com/ohenrik/tabs/blob/039ced6c5612ecdd551aeaac63789862aba05711/tabs/tables.py#L223-L235 |
sivakov512/python-static-api-generator | static_api_generator/generator.py | APIGenerator.generate | def generate(self):
"""Runs generation process."""
for root, _, files in os.walk(self.source_dir):
for fname in files:
source_fpath = os.path.join(root, fname)
self.generate_api_for_source(source_fpath) | python | def generate(self):
"""Runs generation process."""
for root, _, files in os.walk(self.source_dir):
for fname in files:
source_fpath = os.path.join(root, fname)
self.generate_api_for_source(source_fpath) | [
"def",
"generate",
"(",
"self",
")",
":",
"for",
"root",
",",
"_",
",",
"files",
"in",
"os",
".",
"walk",
"(",
"self",
".",
"source_dir",
")",
":",
"for",
"fname",
"in",
"files",
":",
"source_fpath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"roo... | Runs generation process. | [
"Runs",
"generation",
"process",
"."
] | train | https://github.com/sivakov512/python-static-api-generator/blob/0a7ec27324b9b2a3d1fa9894c4cba73af9ebcc01/static_api_generator/generator.py#L25-L30 |
sivakov512/python-static-api-generator | static_api_generator/generator.py | APIGenerator.generate_api_for_source | def generate_api_for_source(self, source_fpath: str):
"""Generate end json api file with directory structure for concrete
source file."""
content = self.convert_content(source_fpath)
if content is None:
return
dest_fpath = self.dest_fpath(source_fpath)
self.create_fpath_dir(dest_fpath)
with open(dest_fpath, 'w+') as dest_f:
json.dump(content, dest_f, cls=DateTimeJsonEncoder) | python | def generate_api_for_source(self, source_fpath: str):
"""Generate end json api file with directory structure for concrete
source file."""
content = self.convert_content(source_fpath)
if content is None:
return
dest_fpath = self.dest_fpath(source_fpath)
self.create_fpath_dir(dest_fpath)
with open(dest_fpath, 'w+') as dest_f:
json.dump(content, dest_f, cls=DateTimeJsonEncoder) | [
"def",
"generate_api_for_source",
"(",
"self",
",",
"source_fpath",
":",
"str",
")",
":",
"content",
"=",
"self",
".",
"convert_content",
"(",
"source_fpath",
")",
"if",
"content",
"is",
"None",
":",
"return",
"dest_fpath",
"=",
"self",
".",
"dest_fpath",
"(... | Generate end json api file with directory structure for concrete
source file. | [
"Generate",
"end",
"json",
"api",
"file",
"with",
"directory",
"structure",
"for",
"concrete",
"source",
"file",
"."
] | train | https://github.com/sivakov512/python-static-api-generator/blob/0a7ec27324b9b2a3d1fa9894c4cba73af9ebcc01/static_api_generator/generator.py#L32-L43 |
sivakov512/python-static-api-generator | static_api_generator/generator.py | APIGenerator.convert_content | def convert_content(self, fpath: str) -> typing.Optional[dict]:
"""Convert content of source file with loader, provided with
`loader_cls` self attribute.
Returns dict with converted content if loader class support source file
extenstions, otherwise return nothing."""
try:
loader = self.loader_cls(fpath)
except UnsupportedExtensionError:
return
return loader.convert_content() | python | def convert_content(self, fpath: str) -> typing.Optional[dict]:
"""Convert content of source file with loader, provided with
`loader_cls` self attribute.
Returns dict with converted content if loader class support source file
extenstions, otherwise return nothing."""
try:
loader = self.loader_cls(fpath)
except UnsupportedExtensionError:
return
return loader.convert_content() | [
"def",
"convert_content",
"(",
"self",
",",
"fpath",
":",
"str",
")",
"->",
"typing",
".",
"Optional",
"[",
"dict",
"]",
":",
"try",
":",
"loader",
"=",
"self",
".",
"loader_cls",
"(",
"fpath",
")",
"except",
"UnsupportedExtensionError",
":",
"return",
"... | Convert content of source file with loader, provided with
`loader_cls` self attribute.
Returns dict with converted content if loader class support source file
extenstions, otherwise return nothing. | [
"Convert",
"content",
"of",
"source",
"file",
"with",
"loader",
"provided",
"with",
"loader_cls",
"self",
"attribute",
"."
] | train | https://github.com/sivakov512/python-static-api-generator/blob/0a7ec27324b9b2a3d1fa9894c4cba73af9ebcc01/static_api_generator/generator.py#L45-L56 |
sivakov512/python-static-api-generator | static_api_generator/generator.py | APIGenerator.dest_fpath | def dest_fpath(self, source_fpath: str) -> str:
"""Calculates full path for end json-api file from source file full
path."""
relative_fpath = os.path.join(*source_fpath.split(os.sep)[1:])
relative_dirpath = os.path.dirname(relative_fpath)
source_fname = relative_fpath.split(os.sep)[-1]
base_fname = source_fname.split('.')[0]
dest_fname = f'{base_fname}.json'
return os.path.join(self.dest_dir, relative_dirpath, dest_fname) | python | def dest_fpath(self, source_fpath: str) -> str:
"""Calculates full path for end json-api file from source file full
path."""
relative_fpath = os.path.join(*source_fpath.split(os.sep)[1:])
relative_dirpath = os.path.dirname(relative_fpath)
source_fname = relative_fpath.split(os.sep)[-1]
base_fname = source_fname.split('.')[0]
dest_fname = f'{base_fname}.json'
return os.path.join(self.dest_dir, relative_dirpath, dest_fname) | [
"def",
"dest_fpath",
"(",
"self",
",",
"source_fpath",
":",
"str",
")",
"->",
"str",
":",
"relative_fpath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"*",
"source_fpath",
".",
"split",
"(",
"os",
".",
"sep",
")",
"[",
"1",
":",
"]",
")",
"relative_... | Calculates full path for end json-api file from source file full
path. | [
"Calculates",
"full",
"path",
"for",
"end",
"json",
"-",
"api",
"file",
"from",
"source",
"file",
"full",
"path",
"."
] | train | https://github.com/sivakov512/python-static-api-generator/blob/0a7ec27324b9b2a3d1fa9894c4cba73af9ebcc01/static_api_generator/generator.py#L58-L68 |
sivakov512/python-static-api-generator | static_api_generator/generator.py | APIGenerator.create_fpath_dir | def create_fpath_dir(self, fpath: str):
"""Creates directory for fpath."""
os.makedirs(os.path.dirname(fpath), exist_ok=True) | python | def create_fpath_dir(self, fpath: str):
"""Creates directory for fpath."""
os.makedirs(os.path.dirname(fpath), exist_ok=True) | [
"def",
"create_fpath_dir",
"(",
"self",
",",
"fpath",
":",
"str",
")",
":",
"os",
".",
"makedirs",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"fpath",
")",
",",
"exist_ok",
"=",
"True",
")"
] | Creates directory for fpath. | [
"Creates",
"directory",
"for",
"fpath",
"."
] | train | https://github.com/sivakov512/python-static-api-generator/blob/0a7ec27324b9b2a3d1fa9894c4cba73af9ebcc01/static_api_generator/generator.py#L70-L72 |
rcbops/flake8-filename | flake8_filename/__init__.py | FilenameChecker.add_options | def add_options(cls, parser):
"""Required by flake8
add the possible options, called first
Args:
parser (OptionsManager):
"""
kwargs = {'action': 'store', 'default': '', 'parse_from_config': True,
'comma_separated_list': True}
for num in range(cls.min_check, cls.max_check):
parser.add_option(None, "--filename_check{}".format(num), **kwargs) | python | def add_options(cls, parser):
"""Required by flake8
add the possible options, called first
Args:
parser (OptionsManager):
"""
kwargs = {'action': 'store', 'default': '', 'parse_from_config': True,
'comma_separated_list': True}
for num in range(cls.min_check, cls.max_check):
parser.add_option(None, "--filename_check{}".format(num), **kwargs) | [
"def",
"add_options",
"(",
"cls",
",",
"parser",
")",
":",
"kwargs",
"=",
"{",
"'action'",
":",
"'store'",
",",
"'default'",
":",
"''",
",",
"'parse_from_config'",
":",
"True",
",",
"'comma_separated_list'",
":",
"True",
"}",
"for",
"num",
"in",
"range",
... | Required by flake8
add the possible options, called first
Args:
parser (OptionsManager): | [
"Required",
"by",
"flake8",
"add",
"the",
"possible",
"options",
"called",
"first"
] | train | https://github.com/rcbops/flake8-filename/blob/5718d4af394c318d376de7434193543e0da45651/flake8_filename/__init__.py#L19-L29 |
rcbops/flake8-filename | flake8_filename/__init__.py | FilenameChecker.parse_options | def parse_options(cls, options):
"""Required by flake8
parse the options, called after add_options
Args:
options (dict): options to be parsed
"""
d = {}
for filename_check, dictionary in cls.filename_checks.items():
# retrieve the marks from the passed options
filename_data = getattr(options, filename_check)
if len(filename_data) != 0:
parsed_params = {}
for single_line in filename_data:
a = [s.strip() for s in single_line.split('=')]
# whitelist the acceptable params
if a[0] in ['filter_regex', 'filename_regex']:
parsed_params[a[0]] = a[1]
d[filename_check] = parsed_params
cls.filename_checks.update(d)
# delete any empty rules
cls.filename_checks = {x: y for x, y in cls.filename_checks.items() if len(y) > 0} | python | def parse_options(cls, options):
"""Required by flake8
parse the options, called after add_options
Args:
options (dict): options to be parsed
"""
d = {}
for filename_check, dictionary in cls.filename_checks.items():
# retrieve the marks from the passed options
filename_data = getattr(options, filename_check)
if len(filename_data) != 0:
parsed_params = {}
for single_line in filename_data:
a = [s.strip() for s in single_line.split('=')]
# whitelist the acceptable params
if a[0] in ['filter_regex', 'filename_regex']:
parsed_params[a[0]] = a[1]
d[filename_check] = parsed_params
cls.filename_checks.update(d)
# delete any empty rules
cls.filename_checks = {x: y for x, y in cls.filename_checks.items() if len(y) > 0} | [
"def",
"parse_options",
"(",
"cls",
",",
"options",
")",
":",
"d",
"=",
"{",
"}",
"for",
"filename_check",
",",
"dictionary",
"in",
"cls",
".",
"filename_checks",
".",
"items",
"(",
")",
":",
"# retrieve the marks from the passed options",
"filename_data",
"=",
... | Required by flake8
parse the options, called after add_options
Args:
options (dict): options to be parsed | [
"Required",
"by",
"flake8",
"parse",
"the",
"options",
"called",
"after",
"add_options"
] | train | https://github.com/rcbops/flake8-filename/blob/5718d4af394c318d376de7434193543e0da45651/flake8_filename/__init__.py#L32-L53 |
rcbops/flake8-filename | flake8_filename/__init__.py | FilenameChecker.run | def run(self):
"""Required by flake8
Will be called after add_options and parse_options.
Yields:
tuple: (int, int, str, type) the tuple used by flake8 to construct a violation
"""
if len(self.filename_checks) == 0:
message = "N401 no configuration found for {}, " \
"please provide filename configuration in a flake8 config".format(self.name)
yield (0, 0, message, type(self))
rule_funcs = [rules.rule_n5xx]
for rule_func in rule_funcs:
for rule_name, configured_rule in self.filename_checks.items():
for err in rule_func(self.filename, rule_name, configured_rule, type(self)):
yield err | python | def run(self):
"""Required by flake8
Will be called after add_options and parse_options.
Yields:
tuple: (int, int, str, type) the tuple used by flake8 to construct a violation
"""
if len(self.filename_checks) == 0:
message = "N401 no configuration found for {}, " \
"please provide filename configuration in a flake8 config".format(self.name)
yield (0, 0, message, type(self))
rule_funcs = [rules.rule_n5xx]
for rule_func in rule_funcs:
for rule_name, configured_rule in self.filename_checks.items():
for err in rule_func(self.filename, rule_name, configured_rule, type(self)):
yield err | [
"def",
"run",
"(",
"self",
")",
":",
"if",
"len",
"(",
"self",
".",
"filename_checks",
")",
"==",
"0",
":",
"message",
"=",
"\"N401 no configuration found for {}, \"",
"\"please provide filename configuration in a flake8 config\"",
".",
"format",
"(",
"self",
".",
"... | Required by flake8
Will be called after add_options and parse_options.
Yields:
tuple: (int, int, str, type) the tuple used by flake8 to construct a violation | [
"Required",
"by",
"flake8",
"Will",
"be",
"called",
"after",
"add_options",
"and",
"parse_options",
"."
] | train | https://github.com/rcbops/flake8-filename/blob/5718d4af394c318d376de7434193543e0da45651/flake8_filename/__init__.py#L68-L86 |
reflexsc/reflex | dev/common.py | get_my_ips | def get_my_ips():
"""highly os specific - works only in modern linux kernels"""
ips = list()
if not os.path.exists("/sys/class/net"): # not linux
return ['127.0.0.1']
for ifdev in os.listdir("/sys/class/net"):
if ifdev == "lo":
continue
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
ips.append(socket.inet_ntoa(fcntl.ioctl(
sock.fileno(),
0x8915, # SIOCGIFADDR
struct.pack('256s', ifdev[:15].encode())
)[20:24]))
except OSError:
pass
return ips | python | def get_my_ips():
"""highly os specific - works only in modern linux kernels"""
ips = list()
if not os.path.exists("/sys/class/net"): # not linux
return ['127.0.0.1']
for ifdev in os.listdir("/sys/class/net"):
if ifdev == "lo":
continue
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
ips.append(socket.inet_ntoa(fcntl.ioctl(
sock.fileno(),
0x8915, # SIOCGIFADDR
struct.pack('256s', ifdev[:15].encode())
)[20:24]))
except OSError:
pass
return ips | [
"def",
"get_my_ips",
"(",
")",
":",
"ips",
"=",
"list",
"(",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"\"/sys/class/net\"",
")",
":",
"# not linux",
"return",
"[",
"'127.0.0.1'",
"]",
"for",
"ifdev",
"in",
"os",
".",
"listdir",
"(",
"... | highly os specific - works only in modern linux kernels | [
"highly",
"os",
"specific",
"-",
"works",
"only",
"in",
"modern",
"linux",
"kernels"
] | train | https://github.com/reflexsc/reflex/blob/cee6b0ccfef395ca5e157d644a2e3252cea9fe62/dev/common.py#L241-L258 |
duniter/duniter-python-api | examples/create_and_publish_identity.py | get_identity_document | def get_identity_document(current_block: dict, uid: str, salt: str, password: str) -> Identity:
"""
Get an Identity document
:param current_block: Current block data
:param uid: Unique IDentifier
:param salt: Passphrase of the account
:param password: Password of the account
:rtype: Identity
"""
# get current block BlockStamp
timestamp = BlockUID(current_block['number'], current_block['hash'])
# create keys from credentials
key = SigningKey.from_credentials(salt, password)
# create identity document
identity = Identity(
version=10,
currency=current_block['currency'],
pubkey=key.pubkey,
uid=uid,
ts=timestamp,
signature=None
)
# sign document
identity.sign([key])
return identity | python | def get_identity_document(current_block: dict, uid: str, salt: str, password: str) -> Identity:
"""
Get an Identity document
:param current_block: Current block data
:param uid: Unique IDentifier
:param salt: Passphrase of the account
:param password: Password of the account
:rtype: Identity
"""
# get current block BlockStamp
timestamp = BlockUID(current_block['number'], current_block['hash'])
# create keys from credentials
key = SigningKey.from_credentials(salt, password)
# create identity document
identity = Identity(
version=10,
currency=current_block['currency'],
pubkey=key.pubkey,
uid=uid,
ts=timestamp,
signature=None
)
# sign document
identity.sign([key])
return identity | [
"def",
"get_identity_document",
"(",
"current_block",
":",
"dict",
",",
"uid",
":",
"str",
",",
"salt",
":",
"str",
",",
"password",
":",
"str",
")",
"->",
"Identity",
":",
"# get current block BlockStamp",
"timestamp",
"=",
"BlockUID",
"(",
"current_block",
"... | Get an Identity document
:param current_block: Current block data
:param uid: Unique IDentifier
:param salt: Passphrase of the account
:param password: Password of the account
:rtype: Identity | [
"Get",
"an",
"Identity",
"document"
] | train | https://github.com/duniter/duniter-python-api/blob/3a1e5d61a2f72f5afaf29d010c6cf4dff3648165/examples/create_and_publish_identity.py#L20-L51 |
duniter/duniter-python-api | examples/create_and_publish_identity.py | main | async def main():
"""
Main code
"""
# Create Client from endpoint string in Duniter format
client = Client(BMAS_ENDPOINT)
# Get the node summary infos to test the connection
response = await client(bma.node.summary)
print(response)
# capture current block to get version and currency and blockstamp
current_block = await client(bma.blockchain.current)
# prompt entry
uid = input("Enter your Unique IDentifier (pseudonym): ")
# prompt hidden user entry
salt = getpass.getpass("Enter your passphrase (salt): ")
# prompt hidden user entry
password = getpass.getpass("Enter your password: ")
# create our signed identity document
identity = get_identity_document(current_block, uid, salt, password)
# send the identity document to the node
response = await client(bma.wot.add, identity.signed_raw())
if response.status == 200:
print(await response.text())
else:
print("Error while publishing identity : {0}".format(await response.text()))
# Close client aiohttp session
await client.close() | python | async def main():
"""
Main code
"""
# Create Client from endpoint string in Duniter format
client = Client(BMAS_ENDPOINT)
# Get the node summary infos to test the connection
response = await client(bma.node.summary)
print(response)
# capture current block to get version and currency and blockstamp
current_block = await client(bma.blockchain.current)
# prompt entry
uid = input("Enter your Unique IDentifier (pseudonym): ")
# prompt hidden user entry
salt = getpass.getpass("Enter your passphrase (salt): ")
# prompt hidden user entry
password = getpass.getpass("Enter your password: ")
# create our signed identity document
identity = get_identity_document(current_block, uid, salt, password)
# send the identity document to the node
response = await client(bma.wot.add, identity.signed_raw())
if response.status == 200:
print(await response.text())
else:
print("Error while publishing identity : {0}".format(await response.text()))
# Close client aiohttp session
await client.close() | [
"async",
"def",
"main",
"(",
")",
":",
"# Create Client from endpoint string in Duniter format",
"client",
"=",
"Client",
"(",
"BMAS_ENDPOINT",
")",
"# Get the node summary infos to test the connection",
"response",
"=",
"await",
"client",
"(",
"bma",
".",
"node",
".",
... | Main code | [
"Main",
"code"
] | train | https://github.com/duniter/duniter-python-api/blob/3a1e5d61a2f72f5afaf29d010c6cf4dff3648165/examples/create_and_publish_identity.py#L54-L88 |
COLORFULBOARD/revision | revision/util.py | make_hash_id | def make_hash_id():
"""
Compute the `datetime.now` based SHA-1 hash of a string.
:return: Returns the sha1 hash as a string.
:rtype: str
"""
today = datetime.datetime.now().strftime(DATETIME_FORMAT)
return hashlib.sha1(today.encode('utf-8')).hexdigest() | python | def make_hash_id():
"""
Compute the `datetime.now` based SHA-1 hash of a string.
:return: Returns the sha1 hash as a string.
:rtype: str
"""
today = datetime.datetime.now().strftime(DATETIME_FORMAT)
return hashlib.sha1(today.encode('utf-8')).hexdigest() | [
"def",
"make_hash_id",
"(",
")",
":",
"today",
"=",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
".",
"strftime",
"(",
"DATETIME_FORMAT",
")",
"return",
"hashlib",
".",
"sha1",
"(",
"today",
".",
"encode",
"(",
"'utf-8'",
")",
")",
".",
"hexdiges... | Compute the `datetime.now` based SHA-1 hash of a string.
:return: Returns the sha1 hash as a string.
:rtype: str | [
"Compute",
"the",
"datetime",
".",
"now",
"based",
"SHA",
"-",
"1",
"hash",
"of",
"a",
"string",
"."
] | train | https://github.com/COLORFULBOARD/revision/blob/2f22e72cce5b60032a80c002ac45c2ecef0ed987/revision/util.py#L24-L32 |
azraq27/neural | neural/eprime.py | read_header | def read_header(filename):
''' returns a dictionary of values in the header of the given file '''
header = {}
in_header = False
data = nl.universal_read(filename)
lines = [x.strip() for x in data.split('\n')]
for line in lines:
if line=="*** Header Start ***":
in_header=True
continue
if line=="*** Header End ***":
return header
fields = line.split(": ")
if len(fields)==2:
header[fields[0]] = fields[1] | python | def read_header(filename):
''' returns a dictionary of values in the header of the given file '''
header = {}
in_header = False
data = nl.universal_read(filename)
lines = [x.strip() for x in data.split('\n')]
for line in lines:
if line=="*** Header Start ***":
in_header=True
continue
if line=="*** Header End ***":
return header
fields = line.split(": ")
if len(fields)==2:
header[fields[0]] = fields[1] | [
"def",
"read_header",
"(",
"filename",
")",
":",
"header",
"=",
"{",
"}",
"in_header",
"=",
"False",
"data",
"=",
"nl",
".",
"universal_read",
"(",
"filename",
")",
"lines",
"=",
"[",
"x",
".",
"strip",
"(",
")",
"for",
"x",
"in",
"data",
".",
"spl... | returns a dictionary of values in the header of the given file | [
"returns",
"a",
"dictionary",
"of",
"values",
"in",
"the",
"header",
"of",
"the",
"given",
"file"
] | train | https://github.com/azraq27/neural/blob/fe91bfeecbf73ad99708cf5dca66cb61fcd529f5/neural/eprime.py#L5-L19 |
azraq27/neural | neural/eprime.py | parse_frames | def parse_frames(filename):
''' quick and dirty eprime txt file parsing - doesn\'t account for nesting
**Example usage**::
for frame in neural.eprime.parse_frames("experiment-1.txt"):
trial_type = frame['TrialSlide.Tag']
trial_rt = float(frame['TrialSlide.RT'])
print '%s: %fms' % (trial_type,trial_rt)
'''
frames = []
frame = {}
data = nl.universal_read(filename)
lines = [x.strip() for x in data.split('\n')]
for line in lines:
if line == '*** LogFrame Start ***':
frame = {}
if line == '*** LogFrame End ***':
frames.append(frame)
yield frame
fields = line.split(": ")
if len(fields)==2:
frame[fields[0]] = fields[1] | python | def parse_frames(filename):
''' quick and dirty eprime txt file parsing - doesn\'t account for nesting
**Example usage**::
for frame in neural.eprime.parse_frames("experiment-1.txt"):
trial_type = frame['TrialSlide.Tag']
trial_rt = float(frame['TrialSlide.RT'])
print '%s: %fms' % (trial_type,trial_rt)
'''
frames = []
frame = {}
data = nl.universal_read(filename)
lines = [x.strip() for x in data.split('\n')]
for line in lines:
if line == '*** LogFrame Start ***':
frame = {}
if line == '*** LogFrame End ***':
frames.append(frame)
yield frame
fields = line.split(": ")
if len(fields)==2:
frame[fields[0]] = fields[1] | [
"def",
"parse_frames",
"(",
"filename",
")",
":",
"frames",
"=",
"[",
"]",
"frame",
"=",
"{",
"}",
"data",
"=",
"nl",
".",
"universal_read",
"(",
"filename",
")",
"lines",
"=",
"[",
"x",
".",
"strip",
"(",
")",
"for",
"x",
"in",
"data",
".",
"spl... | quick and dirty eprime txt file parsing - doesn\'t account for nesting
**Example usage**::
for frame in neural.eprime.parse_frames("experiment-1.txt"):
trial_type = frame['TrialSlide.Tag']
trial_rt = float(frame['TrialSlide.RT'])
print '%s: %fms' % (trial_type,trial_rt) | [
"quick",
"and",
"dirty",
"eprime",
"txt",
"file",
"parsing",
"-",
"doesn",
"\\",
"t",
"account",
"for",
"nesting",
"**",
"Example",
"usage",
"**",
"::",
"for",
"frame",
"in",
"neural",
".",
"eprime",
".",
"parse_frames",
"(",
"experiment",
"-",
"1",
".",... | train | https://github.com/azraq27/neural/blob/fe91bfeecbf73ad99708cf5dca66cb61fcd529f5/neural/eprime.py#L21-L43 |
clinicedc/edc-form-label | edc_form_label/custom_label_condition.py | CustomLabelCondition.appointment | def appointment(self):
"""Returns the appointment instance for this request or None.
"""
return django_apps.get_model(self.appointment_model).objects.get(
pk=self.request.GET.get("appointment")
) | python | def appointment(self):
"""Returns the appointment instance for this request or None.
"""
return django_apps.get_model(self.appointment_model).objects.get(
pk=self.request.GET.get("appointment")
) | [
"def",
"appointment",
"(",
"self",
")",
":",
"return",
"django_apps",
".",
"get_model",
"(",
"self",
".",
"appointment_model",
")",
".",
"objects",
".",
"get",
"(",
"pk",
"=",
"self",
".",
"request",
".",
"GET",
".",
"get",
"(",
"\"appointment\"",
")",
... | Returns the appointment instance for this request or None. | [
"Returns",
"the",
"appointment",
"instance",
"for",
"this",
"request",
"or",
"None",
"."
] | train | https://github.com/clinicedc/edc-form-label/blob/9d90807ddf784045b3867d676bee6e384a8e9d71/edc_form_label/custom_label_condition.py#L29-L34 |
clinicedc/edc-form-label | edc_form_label/custom_label_condition.py | CustomLabelCondition.previous_visit | def previous_visit(self):
"""Returns the previous visit for this request or None.
Requires attr `visit_model_cls`.
"""
previous_visit = None
if self.appointment:
appointment = self.appointment
while appointment.previous_by_timepoint:
try:
previous_visit = self.model.visit_model_cls().objects.get(
appointment=appointment.previous_by_timepoint
)
except ObjectDoesNotExist:
pass
else:
break
appointment = appointment.previous_by_timepoint
return previous_visit | python | def previous_visit(self):
"""Returns the previous visit for this request or None.
Requires attr `visit_model_cls`.
"""
previous_visit = None
if self.appointment:
appointment = self.appointment
while appointment.previous_by_timepoint:
try:
previous_visit = self.model.visit_model_cls().objects.get(
appointment=appointment.previous_by_timepoint
)
except ObjectDoesNotExist:
pass
else:
break
appointment = appointment.previous_by_timepoint
return previous_visit | [
"def",
"previous_visit",
"(",
"self",
")",
":",
"previous_visit",
"=",
"None",
"if",
"self",
".",
"appointment",
":",
"appointment",
"=",
"self",
".",
"appointment",
"while",
"appointment",
".",
"previous_by_timepoint",
":",
"try",
":",
"previous_visit",
"=",
... | Returns the previous visit for this request or None.
Requires attr `visit_model_cls`. | [
"Returns",
"the",
"previous",
"visit",
"for",
"this",
"request",
"or",
"None",
"."
] | train | https://github.com/clinicedc/edc-form-label/blob/9d90807ddf784045b3867d676bee6e384a8e9d71/edc_form_label/custom_label_condition.py#L43-L61 |
clinicedc/edc-form-label | edc_form_label/custom_label_condition.py | CustomLabelCondition.previous_obj | def previous_obj(self):
"""Returns a model obj that is the first occurrence of a previous
obj relative to this object's appointment.
Override this method if not am EDC subject model / CRF.
"""
previous_obj = None
if self.previous_visit:
try:
previous_obj = self.model.objects.get(
**{f"{self.model.visit_model_attr()}": self.previous_visit}
)
except ObjectDoesNotExist:
pass
return previous_obj | python | def previous_obj(self):
"""Returns a model obj that is the first occurrence of a previous
obj relative to this object's appointment.
Override this method if not am EDC subject model / CRF.
"""
previous_obj = None
if self.previous_visit:
try:
previous_obj = self.model.objects.get(
**{f"{self.model.visit_model_attr()}": self.previous_visit}
)
except ObjectDoesNotExist:
pass
return previous_obj | [
"def",
"previous_obj",
"(",
"self",
")",
":",
"previous_obj",
"=",
"None",
"if",
"self",
".",
"previous_visit",
":",
"try",
":",
"previous_obj",
"=",
"self",
".",
"model",
".",
"objects",
".",
"get",
"(",
"*",
"*",
"{",
"f\"{self.model.visit_model_attr()}\""... | Returns a model obj that is the first occurrence of a previous
obj relative to this object's appointment.
Override this method if not am EDC subject model / CRF. | [
"Returns",
"a",
"model",
"obj",
"that",
"is",
"the",
"first",
"occurrence",
"of",
"a",
"previous",
"obj",
"relative",
"to",
"this",
"object",
"s",
"appointment",
"."
] | train | https://github.com/clinicedc/edc-form-label/blob/9d90807ddf784045b3867d676bee6e384a8e9d71/edc_form_label/custom_label_condition.py#L64-L78 |
mozilla/socorrolib | setup.py | read | def read(fname):
"""
utility function to read and return file contents
"""
fpath = os.path.join(os.path.dirname(__file__), fname)
with codecs.open(fpath, 'r', 'utf8') as fhandle:
return fhandle.read().strip() | python | def read(fname):
"""
utility function to read and return file contents
"""
fpath = os.path.join(os.path.dirname(__file__), fname)
with codecs.open(fpath, 'r', 'utf8') as fhandle:
return fhandle.read().strip() | [
"def",
"read",
"(",
"fname",
")",
":",
"fpath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
",",
"fname",
")",
"with",
"codecs",
".",
"open",
"(",
"fpath",
",",
"'r'",
",",
"'utf8'",
")",
"... | utility function to read and return file contents | [
"utility",
"function",
"to",
"read",
"and",
"return",
"file",
"contents"
] | train | https://github.com/mozilla/socorrolib/blob/4ec08c6a4ee2c8a69150268afdd324f5f22b90c8/setup.py#L19-L25 |
eReuse/utils | ereuse_utils/__init__.py | ensure_utf8 | def ensure_utf8(app_name_to_show_on_error: str):
"""
Python3 uses by default the system set, but it expects it to be ‘utf-8’ to work correctly. This
can generate problems in reading and writing files and in ``.decode()`` method.
An example how to 'fix' it:
nano .bash_profile and add the following:
export LC_CTYPE=en_US.UTF-8
export LC_ALL=en_US.UTF-8
"""
encoding = locale.getpreferredencoding()
if encoding.lower() != 'utf-8':
raise OSError('{} works only in UTF-8, but yours is set at {}'.format(app_name_to_show_on_error, encoding)) | python | def ensure_utf8(app_name_to_show_on_error: str):
"""
Python3 uses by default the system set, but it expects it to be ‘utf-8’ to work correctly. This
can generate problems in reading and writing files and in ``.decode()`` method.
An example how to 'fix' it:
nano .bash_profile and add the following:
export LC_CTYPE=en_US.UTF-8
export LC_ALL=en_US.UTF-8
"""
encoding = locale.getpreferredencoding()
if encoding.lower() != 'utf-8':
raise OSError('{} works only in UTF-8, but yours is set at {}'.format(app_name_to_show_on_error, encoding)) | [
"def",
"ensure_utf8",
"(",
"app_name_to_show_on_error",
":",
"str",
")",
":",
"encoding",
"=",
"locale",
".",
"getpreferredencoding",
"(",
")",
"if",
"encoding",
".",
"lower",
"(",
")",
"!=",
"'utf-8'",
":",
"raise",
"OSError",
"(",
"'{} works only in UTF-8, but... | Python3 uses by default the system set, but it expects it to be ‘utf-8’ to work correctly. This
can generate problems in reading and writing files and in ``.decode()`` method.
An example how to 'fix' it:
nano .bash_profile and add the following:
export LC_CTYPE=en_US.UTF-8
export LC_ALL=en_US.UTF-8 | [
"Python3",
"uses",
"by",
"default",
"the",
"system",
"set",
"but",
"it",
"expects",
"it",
"to",
"be",
"‘utf",
"-",
"8’",
"to",
"work",
"correctly",
".",
"This",
"can",
"generate",
"problems",
"in",
"reading",
"and",
"writing",
"files",
"and",
"in",
".",
... | train | https://github.com/eReuse/utils/blob/989062e85095ea4e1204523fe0e298cf1046a01c/ereuse_utils/__init__.py#L22-L34 |
datakortet/yamldirs | yamldirs/filemaker.py | create_files | def create_files(filedef, cleanup=True):
"""Contextmanager that creates a directory structure from a yaml
descripttion.
"""
cwd = os.getcwd()
tmpdir = tempfile.mkdtemp()
try:
Filemaker(tmpdir, filedef)
if not cleanup: # pragma: nocover
pass
# print("TMPDIR =", tmpdir)
os.chdir(tmpdir)
yield tmpdir
finally:
os.chdir(cwd)
if cleanup: # pragma: nocover
shutil.rmtree(tmpdir, ignore_errors=True) | python | def create_files(filedef, cleanup=True):
"""Contextmanager that creates a directory structure from a yaml
descripttion.
"""
cwd = os.getcwd()
tmpdir = tempfile.mkdtemp()
try:
Filemaker(tmpdir, filedef)
if not cleanup: # pragma: nocover
pass
# print("TMPDIR =", tmpdir)
os.chdir(tmpdir)
yield tmpdir
finally:
os.chdir(cwd)
if cleanup: # pragma: nocover
shutil.rmtree(tmpdir, ignore_errors=True) | [
"def",
"create_files",
"(",
"filedef",
",",
"cleanup",
"=",
"True",
")",
":",
"cwd",
"=",
"os",
".",
"getcwd",
"(",
")",
"tmpdir",
"=",
"tempfile",
".",
"mkdtemp",
"(",
")",
"try",
":",
"Filemaker",
"(",
"tmpdir",
",",
"filedef",
")",
"if",
"not",
... | Contextmanager that creates a directory structure from a yaml
descripttion. | [
"Contextmanager",
"that",
"creates",
"a",
"directory",
"structure",
"from",
"a",
"yaml",
"descripttion",
"."
] | train | https://github.com/datakortet/yamldirs/blob/402c4187a27ad1e6f30b00aad22324110c9d5573/yamldirs/filemaker.py#L122-L138 |
datakortet/yamldirs | yamldirs/filemaker.py | Filemaker.make_file | def make_file(self, filename, content):
"""Create a new file with name ``filename`` and content ``content``.
"""
with open(filename, 'w') as fp:
fp.write(content) | python | def make_file(self, filename, content):
"""Create a new file with name ``filename`` and content ``content``.
"""
with open(filename, 'w') as fp:
fp.write(content) | [
"def",
"make_file",
"(",
"self",
",",
"filename",
",",
"content",
")",
":",
"with",
"open",
"(",
"filename",
",",
"'w'",
")",
"as",
"fp",
":",
"fp",
".",
"write",
"(",
"content",
")"
] | Create a new file with name ``filename`` and content ``content``. | [
"Create",
"a",
"new",
"file",
"with",
"name",
"filename",
"and",
"content",
"content",
"."
] | train | https://github.com/datakortet/yamldirs/blob/402c4187a27ad1e6f30b00aad22324110c9d5573/yamldirs/filemaker.py#L114-L118 |
MacHu-GWU/pymongo_mate-project | pymongo_mate/crud/insert.py | smart_insert | def smart_insert(col, data, minimal_size=5):
"""An optimized Insert strategy.
**中文文档**
在Insert中, 如果已经预知不会出现IntegrityError, 那么使用Bulk Insert的速度要
远远快于逐条Insert。而如果无法预知, 那么我们采用如下策略:
1. 尝试Bulk Insert, Bulk Insert由于在结束前不Commit, 所以速度很快。
2. 如果失败了, 那么对数据的条数开平方根, 进行分包, 然后对每个包重复该逻辑。
3. 若还是尝试失败, 则继续分包, 当分包的大小小于一定数量时, 则使用逐条插入。
直到成功为止。
该Insert策略在内存上需要额外的 sqrt(nbytes) 的开销, 跟原数据相比体积很小。
但时间上是各种情况下平均最优的。
"""
if isinstance(data, list):
# 首先进行尝试bulk insert
try:
col.insert(data)
# 失败了
except pymongo.errors.DuplicateKeyError:
# 分析数据量
n = len(data)
# 如果数据条数多于一定数量
if n >= minimal_size ** 2:
# 则进行分包
n_chunk = math.floor(math.sqrt(n))
for chunk in grouper_list(data, n_chunk):
smart_insert(col, chunk, minimal_size)
# 否则则一条条地逐条插入
else:
for doc in data:
try:
col.insert(doc)
except pymongo.errors.DuplicateKeyError:
pass
else: # pragma: no cover
try:
col.insert(data)
except pymongo.errors.DuplicateKeyError:
pass | python | def smart_insert(col, data, minimal_size=5):
"""An optimized Insert strategy.
**中文文档**
在Insert中, 如果已经预知不会出现IntegrityError, 那么使用Bulk Insert的速度要
远远快于逐条Insert。而如果无法预知, 那么我们采用如下策略:
1. 尝试Bulk Insert, Bulk Insert由于在结束前不Commit, 所以速度很快。
2. 如果失败了, 那么对数据的条数开平方根, 进行分包, 然后对每个包重复该逻辑。
3. 若还是尝试失败, 则继续分包, 当分包的大小小于一定数量时, 则使用逐条插入。
直到成功为止。
该Insert策略在内存上需要额外的 sqrt(nbytes) 的开销, 跟原数据相比体积很小。
但时间上是各种情况下平均最优的。
"""
if isinstance(data, list):
# 首先进行尝试bulk insert
try:
col.insert(data)
# 失败了
except pymongo.errors.DuplicateKeyError:
# 分析数据量
n = len(data)
# 如果数据条数多于一定数量
if n >= minimal_size ** 2:
# 则进行分包
n_chunk = math.floor(math.sqrt(n))
for chunk in grouper_list(data, n_chunk):
smart_insert(col, chunk, minimal_size)
# 否则则一条条地逐条插入
else:
for doc in data:
try:
col.insert(doc)
except pymongo.errors.DuplicateKeyError:
pass
else: # pragma: no cover
try:
col.insert(data)
except pymongo.errors.DuplicateKeyError:
pass | [
"def",
"smart_insert",
"(",
"col",
",",
"data",
",",
"minimal_size",
"=",
"5",
")",
":",
"if",
"isinstance",
"(",
"data",
",",
"list",
")",
":",
"# 首先进行尝试bulk insert",
"try",
":",
"col",
".",
"insert",
"(",
"data",
")",
"# 失败了",
"except",
"pymongo",
".... | An optimized Insert strategy.
**中文文档**
在Insert中, 如果已经预知不会出现IntegrityError, 那么使用Bulk Insert的速度要
远远快于逐条Insert。而如果无法预知, 那么我们采用如下策略:
1. 尝试Bulk Insert, Bulk Insert由于在结束前不Commit, 所以速度很快。
2. 如果失败了, 那么对数据的条数开平方根, 进行分包, 然后对每个包重复该逻辑。
3. 若还是尝试失败, 则继续分包, 当分包的大小小于一定数量时, 则使用逐条插入。
直到成功为止。
该Insert策略在内存上需要额外的 sqrt(nbytes) 的开销, 跟原数据相比体积很小。
但时间上是各种情况下平均最优的。 | [
"An",
"optimized",
"Insert",
"strategy",
"."
] | train | https://github.com/MacHu-GWU/pymongo_mate-project/blob/be53170c2db54cb705b9e548d32ef26c773ff7f3/pymongo_mate/crud/insert.py#L26-L67 |
MacHu-GWU/pymongo_mate-project | pymongo_mate/crud/insert.py | insert_data_frame | def insert_data_frame(col, df, int_col=None, binary_col=None, minimal_size=5):
"""Insert ``pandas.DataFrame``.
:param col: :class:`pymongo.collection.Collection` instance.
:param df: :class:`pandas.DataFrame` instance.
:param int_col: list of integer-type column.
:param binary_col: list of binary-type column.
"""
data = transform.to_dict_list_generic_type(df,
int_col=int_col,
binary_col=binary_col)
smart_insert(col, data, minimal_size) | python | def insert_data_frame(col, df, int_col=None, binary_col=None, minimal_size=5):
"""Insert ``pandas.DataFrame``.
:param col: :class:`pymongo.collection.Collection` instance.
:param df: :class:`pandas.DataFrame` instance.
:param int_col: list of integer-type column.
:param binary_col: list of binary-type column.
"""
data = transform.to_dict_list_generic_type(df,
int_col=int_col,
binary_col=binary_col)
smart_insert(col, data, minimal_size) | [
"def",
"insert_data_frame",
"(",
"col",
",",
"df",
",",
"int_col",
"=",
"None",
",",
"binary_col",
"=",
"None",
",",
"minimal_size",
"=",
"5",
")",
":",
"data",
"=",
"transform",
".",
"to_dict_list_generic_type",
"(",
"df",
",",
"int_col",
"=",
"int_col",
... | Insert ``pandas.DataFrame``.
:param col: :class:`pymongo.collection.Collection` instance.
:param df: :class:`pandas.DataFrame` instance.
:param int_col: list of integer-type column.
:param binary_col: list of binary-type column. | [
"Insert",
"pandas",
".",
"DataFrame",
"."
] | train | https://github.com/MacHu-GWU/pymongo_mate-project/blob/be53170c2db54cb705b9e548d32ef26c773ff7f3/pymongo_mate/crud/insert.py#L70-L81 |
duniter/duniter-python-api | duniterpy/key/ascii_armor.py | AsciiArmor.create | def create(message: str, pubkey: Optional[str] = None, signing_keys: Optional[List[SigningKey]] = None,
message_comment: Optional[str] = None, signatures_comment: Optional[str] = None) -> str:
"""
Encrypt a message in ascii armor format, optionally signing it
:param message: Utf-8 message
:param pubkey: Public key of recipient for encryption
:param signing_keys: Optional list of SigningKey instances
:param message_comment: Optional message comment field
:param signatures_comment: Optional signatures comment field
:return:
"""
# if no public key and no signing key...
if not pubkey and not signing_keys:
# We can not create an Ascii Armor Message
raise MISSING_PUBLIC_KEY_AND_SIGNING_KEY_EXCEPTION
# keep only one newline at the end of the message
message = message.rstrip("\n\r") + "\n"
# create block with headers
ascii_armor_block = """{begin_message_header}
""".format(begin_message_header=BEGIN_MESSAGE_HEADER)
# if encrypted message...
if pubkey:
# add encrypted message fields
ascii_armor_block += """{version_field}
""".format(version_field=AsciiArmor._get_version_field())
# add message comment if specified
if message_comment:
ascii_armor_block += """{comment_field}
""".format(comment_field=AsciiArmor._get_comment_field(message_comment))
# blank line separator
ascii_armor_block += '\n'
if pubkey:
# add encrypted message
pubkey_instance = PublicKey(pubkey)
base64_encrypted_message = base64.b64encode(pubkey_instance.encrypt_seal(message)) # type: bytes
ascii_armor_block += """{base64_encrypted_message}
""".format(base64_encrypted_message=base64_encrypted_message.decode('utf-8'))
else:
# remove trailing spaces
message = AsciiArmor._remove_trailing_spaces(message)
# add dash escaped message to ascii armor content
ascii_armor_block += AsciiArmor._dash_escape_text(message)
# if no signature...
if signing_keys is None:
# add message tail
ascii_armor_block += END_MESSAGE_HEADER
else:
# add signature blocks and close block on last signature
count = 1
for signing_key in signing_keys:
ascii_armor_block += AsciiArmor._get_signature_block(message, signing_key, count == len(signing_keys),
signatures_comment)
count += 1
return ascii_armor_block | python | def create(message: str, pubkey: Optional[str] = None, signing_keys: Optional[List[SigningKey]] = None,
message_comment: Optional[str] = None, signatures_comment: Optional[str] = None) -> str:
"""
Encrypt a message in ascii armor format, optionally signing it
:param message: Utf-8 message
:param pubkey: Public key of recipient for encryption
:param signing_keys: Optional list of SigningKey instances
:param message_comment: Optional message comment field
:param signatures_comment: Optional signatures comment field
:return:
"""
# if no public key and no signing key...
if not pubkey and not signing_keys:
# We can not create an Ascii Armor Message
raise MISSING_PUBLIC_KEY_AND_SIGNING_KEY_EXCEPTION
# keep only one newline at the end of the message
message = message.rstrip("\n\r") + "\n"
# create block with headers
ascii_armor_block = """{begin_message_header}
""".format(begin_message_header=BEGIN_MESSAGE_HEADER)
# if encrypted message...
if pubkey:
# add encrypted message fields
ascii_armor_block += """{version_field}
""".format(version_field=AsciiArmor._get_version_field())
# add message comment if specified
if message_comment:
ascii_armor_block += """{comment_field}
""".format(comment_field=AsciiArmor._get_comment_field(message_comment))
# blank line separator
ascii_armor_block += '\n'
if pubkey:
# add encrypted message
pubkey_instance = PublicKey(pubkey)
base64_encrypted_message = base64.b64encode(pubkey_instance.encrypt_seal(message)) # type: bytes
ascii_armor_block += """{base64_encrypted_message}
""".format(base64_encrypted_message=base64_encrypted_message.decode('utf-8'))
else:
# remove trailing spaces
message = AsciiArmor._remove_trailing_spaces(message)
# add dash escaped message to ascii armor content
ascii_armor_block += AsciiArmor._dash_escape_text(message)
# if no signature...
if signing_keys is None:
# add message tail
ascii_armor_block += END_MESSAGE_HEADER
else:
# add signature blocks and close block on last signature
count = 1
for signing_key in signing_keys:
ascii_armor_block += AsciiArmor._get_signature_block(message, signing_key, count == len(signing_keys),
signatures_comment)
count += 1
return ascii_armor_block | [
"def",
"create",
"(",
"message",
":",
"str",
",",
"pubkey",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"signing_keys",
":",
"Optional",
"[",
"List",
"[",
"SigningKey",
"]",
"]",
"=",
"None",
",",
"message_comment",
":",
"Optional",
"[",
"str",... | Encrypt a message in ascii armor format, optionally signing it
:param message: Utf-8 message
:param pubkey: Public key of recipient for encryption
:param signing_keys: Optional list of SigningKey instances
:param message_comment: Optional message comment field
:param signatures_comment: Optional signatures comment field
:return: | [
"Encrypt",
"a",
"message",
"in",
"ascii",
"armor",
"format",
"optionally",
"signing",
"it"
] | train | https://github.com/duniter/duniter-python-api/blob/3a1e5d61a2f72f5afaf29d010c6cf4dff3648165/duniterpy/key/ascii_armor.py#L67-L130 |
duniter/duniter-python-api | duniterpy/key/ascii_armor.py | AsciiArmor._remove_trailing_spaces | def _remove_trailing_spaces(text: str) -> str:
"""
Remove trailing spaces and tabs
:param text: Text to clean up
:return:
"""
clean_text = str()
for line in text.splitlines(True):
# remove trailing spaces (0x20) and tabs (0x09)
clean_text += line.rstrip("\x09\x20")
return clean_text | python | def _remove_trailing_spaces(text: str) -> str:
"""
Remove trailing spaces and tabs
:param text: Text to clean up
:return:
"""
clean_text = str()
for line in text.splitlines(True):
# remove trailing spaces (0x20) and tabs (0x09)
clean_text += line.rstrip("\x09\x20")
return clean_text | [
"def",
"_remove_trailing_spaces",
"(",
"text",
":",
"str",
")",
"->",
"str",
":",
"clean_text",
"=",
"str",
"(",
")",
"for",
"line",
"in",
"text",
".",
"splitlines",
"(",
"True",
")",
":",
"# remove trailing spaces (0x20) and tabs (0x09)",
"clean_text",
"+=",
... | Remove trailing spaces and tabs
:param text: Text to clean up
:return: | [
"Remove",
"trailing",
"spaces",
"and",
"tabs"
] | train | https://github.com/duniter/duniter-python-api/blob/3a1e5d61a2f72f5afaf29d010c6cf4dff3648165/duniterpy/key/ascii_armor.py#L133-L146 |
duniter/duniter-python-api | duniterpy/key/ascii_armor.py | AsciiArmor._dash_escape_text | def _dash_escape_text(text: str) -> str:
"""
Add dash '-' (0x2D) and space ' ' (0x20) as prefix on each line
:param text: Text to dash-escape
:return:
"""
dash_escaped_text = str()
for line in text.splitlines(True):
# add dash '-' (0x2D) and space ' ' (0x20) as prefix
dash_escaped_text += DASH_ESCAPE_PREFIX + line
return dash_escaped_text | python | def _dash_escape_text(text: str) -> str:
"""
Add dash '-' (0x2D) and space ' ' (0x20) as prefix on each line
:param text: Text to dash-escape
:return:
"""
dash_escaped_text = str()
for line in text.splitlines(True):
# add dash '-' (0x2D) and space ' ' (0x20) as prefix
dash_escaped_text += DASH_ESCAPE_PREFIX + line
return dash_escaped_text | [
"def",
"_dash_escape_text",
"(",
"text",
":",
"str",
")",
"->",
"str",
":",
"dash_escaped_text",
"=",
"str",
"(",
")",
"for",
"line",
"in",
"text",
".",
"splitlines",
"(",
"True",
")",
":",
"# add dash '-' (0x2D) and space ' ' (0x20) as prefix",
"dash_escaped_text... | Add dash '-' (0x2D) and space ' ' (0x20) as prefix on each line
:param text: Text to dash-escape
:return: | [
"Add",
"dash",
"-",
"(",
"0x2D",
")",
"and",
"space",
"(",
"0x20",
")",
"as",
"prefix",
"on",
"each",
"line"
] | train | https://github.com/duniter/duniter-python-api/blob/3a1e5d61a2f72f5afaf29d010c6cf4dff3648165/duniterpy/key/ascii_armor.py#L149-L162 |
duniter/duniter-python-api | duniterpy/key/ascii_armor.py | AsciiArmor._parse_dash_escaped_line | def _parse_dash_escaped_line(dash_escaped_line: str) -> str:
"""
Parse a dash-escaped text line
:param dash_escaped_line: Dash escaped text line
:return:
"""
text = str()
regex_dash_escape_prefix = compile('^' + DASH_ESCAPE_PREFIX)
# if prefixed by a dash escape prefix...
if regex_dash_escape_prefix.match(dash_escaped_line):
# remove dash '-' (0x2D) and space ' ' (0x20) prefix
text += dash_escaped_line[2:]
return text | python | def _parse_dash_escaped_line(dash_escaped_line: str) -> str:
"""
Parse a dash-escaped text line
:param dash_escaped_line: Dash escaped text line
:return:
"""
text = str()
regex_dash_escape_prefix = compile('^' + DASH_ESCAPE_PREFIX)
# if prefixed by a dash escape prefix...
if regex_dash_escape_prefix.match(dash_escaped_line):
# remove dash '-' (0x2D) and space ' ' (0x20) prefix
text += dash_escaped_line[2:]
return text | [
"def",
"_parse_dash_escaped_line",
"(",
"dash_escaped_line",
":",
"str",
")",
"->",
"str",
":",
"text",
"=",
"str",
"(",
")",
"regex_dash_escape_prefix",
"=",
"compile",
"(",
"'^'",
"+",
"DASH_ESCAPE_PREFIX",
")",
"# if prefixed by a dash escape prefix...",
"if",
"r... | Parse a dash-escaped text line
:param dash_escaped_line: Dash escaped text line
:return: | [
"Parse",
"a",
"dash",
"-",
"escaped",
"text",
"line"
] | train | https://github.com/duniter/duniter-python-api/blob/3a1e5d61a2f72f5afaf29d010c6cf4dff3648165/duniterpy/key/ascii_armor.py#L165-L179 |
duniter/duniter-python-api | duniterpy/key/ascii_armor.py | AsciiArmor._get_signature_block | def _get_signature_block(message: str, signing_key: SigningKey, close_block: bool = True,
comment: Optional[str] = None) -> str:
"""
Return a signature block
:param message: Message (not encrypted!) to sign
:param signing_key: The libnacl SigningKey instance of the keypair
:param close_block: Optional flag to close the signature block with the signature tail header
:param comment: Optional comment field content
:return:
"""
base64_signature = base64.b64encode(signing_key.signature(message))
block = """{begin_signature_header}
{version_field}
""".format(begin_signature_header=BEGIN_SIGNATURE_HEADER, version_field=AsciiArmor._get_version_field())
# add message comment if specified
if comment:
block += """{comment_field}
""".format(comment_field=AsciiArmor._get_comment_field(comment))
# blank line separator
block += '\n'
block += """{base64_signature}
""".format(base64_signature=base64_signature.decode('utf-8'))
if close_block:
block += END_SIGNATURE_HEADER
return block | python | def _get_signature_block(message: str, signing_key: SigningKey, close_block: bool = True,
comment: Optional[str] = None) -> str:
"""
Return a signature block
:param message: Message (not encrypted!) to sign
:param signing_key: The libnacl SigningKey instance of the keypair
:param close_block: Optional flag to close the signature block with the signature tail header
:param comment: Optional comment field content
:return:
"""
base64_signature = base64.b64encode(signing_key.signature(message))
block = """{begin_signature_header}
{version_field}
""".format(begin_signature_header=BEGIN_SIGNATURE_HEADER, version_field=AsciiArmor._get_version_field())
# add message comment if specified
if comment:
block += """{comment_field}
""".format(comment_field=AsciiArmor._get_comment_field(comment))
# blank line separator
block += '\n'
block += """{base64_signature}
""".format(base64_signature=base64_signature.decode('utf-8'))
if close_block:
block += END_SIGNATURE_HEADER
return block | [
"def",
"_get_signature_block",
"(",
"message",
":",
"str",
",",
"signing_key",
":",
"SigningKey",
",",
"close_block",
":",
"bool",
"=",
"True",
",",
"comment",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
")",
"->",
"str",
":",
"base64_signature",
"=",
... | Return a signature block
:param message: Message (not encrypted!) to sign
:param signing_key: The libnacl SigningKey instance of the keypair
:param close_block: Optional flag to close the signature block with the signature tail header
:param comment: Optional comment field content
:return: | [
"Return",
"a",
"signature",
"block"
] | train | https://github.com/duniter/duniter-python-api/blob/3a1e5d61a2f72f5afaf29d010c6cf4dff3648165/duniterpy/key/ascii_armor.py#L201-L232 |
duniter/duniter-python-api | duniterpy/key/ascii_armor.py | AsciiArmor.parse | def parse(ascii_armor_message: str, signing_key: Optional[SigningKey] = None,
sender_pubkeys: Optional[List[str]] = None) -> dict:
"""
Return a dict with parsed content (decrypted message, signature validation) ::
{
'message':
{
'fields': {},
'content': str,
},
'signatures': [
{'pubkey': str, 'valid': bool, fields: {}}
]
}
:param ascii_armor_message: The Ascii Armor Message Block including BEGIN and END headers
:param signing_key: Optional Libnacl SigningKey instance to decrypt message
:param sender_pubkeys: Optional sender's public keys list to verify signatures
:exception libnacl.CryptError: Raise an exception if keypair fail to decrypt the message
:exception MissingSigningKeyException: Raise an exception if no keypair given for encrypted message
:return:
"""
# regex patterns
regex_begin_message = compile(BEGIN_MESSAGE_HEADER)
regex_end_message = compile(END_MESSAGE_HEADER)
regex_begin_signature = compile(BEGIN_SIGNATURE_HEADER)
regex_end_signature = compile(END_SIGNATURE_HEADER)
regex_fields = compile("^(Version|Comment): (.+)$")
# trim message to get rid of empty lines
ascii_armor_message = ascii_armor_message.strip(" \t\n\r")
# init vars
parsed_result = {
'message':
{
'fields': {},
'content': '',
},
'signatures': []
} # type: Dict[str, Any]
cursor_status = 0
message = ''
signatures_index = 0
# parse each line...
for line in ascii_armor_message.splitlines(True):
# if begin message header detected...
if regex_begin_message.match(line):
cursor_status = ON_MESSAGE_FIELDS
continue
# if we are on the fields lines...
if cursor_status == ON_MESSAGE_FIELDS:
# parse field
m = regex_fields.match(line.strip())
if m:
# capture field
msg_field_name = m.groups()[0]
msg_field_value = m.groups()[1]
parsed_result['message']['fields'][msg_field_name] = msg_field_value
continue
# if blank line...
if line.strip("\n\t\r ") == '':
cursor_status = ON_MESSAGE_CONTENT
continue
# if we are on the message content lines...
if cursor_status == ON_MESSAGE_CONTENT:
# if a header is detected, end of message content...
if line.startswith(HEADER_PREFIX):
# if field Version is present, the message is encrypted...
if 'Version' in parsed_result['message']['fields']:
# If keypair instance to decrypt not given...
if signing_key is None:
# SigningKey keypair is mandatory to decrypt the message...
raise PARSER_MISSING_SIGNING_KEY_EXCEPTION
# decrypt message with secret key from keypair
message = AsciiArmor._decrypt(message, signing_key)
# save message content in result
parsed_result['message']['content'] = message
# if message end header...
if regex_end_message.match(line):
# stop parsing
break
# if signature begin header...
if regex_begin_signature.match(line):
# add signature dict in list
parsed_result['signatures'].append({
'fields': {}
})
cursor_status = ON_SIGNATURE_FIELDS
continue
else:
# if field Version is present, the message is encrypted...
if 'Version' in parsed_result['message']['fields']:
# concatenate encrypted line to message content
message += line
else:
# concatenate cleartext striped dash escaped line to message content
message += AsciiArmor._parse_dash_escaped_line(line)
# if we are on a signature fields zone...
if cursor_status == ON_SIGNATURE_FIELDS:
# parse field
m = regex_fields.match(line.strip())
if m:
# capture field
sig_field_name = m.groups()[0]
sig_field_value = m.groups()[1]
parsed_result['signatures'][signatures_index]['fields'][sig_field_name] = sig_field_value
continue
# if blank line...
if line.strip("\n\t\r ") == '':
cursor_status = ON_SIGNATURE_CONTENT
continue
# if we are on the signature content...
if cursor_status == ON_SIGNATURE_CONTENT:
# if no public keys provided...
if sender_pubkeys is None:
# raise exception
raise PARSER_MISSING_PUBLIC_KEYS_EXCEPTION
# if end signature header detected...
if regex_end_signature.match(line):
# end of parsing
break
# if begin signature header detected...
if regex_begin_signature.match(line):
signatures_index += 1
cursor_status = ON_SIGNATURE_FIELDS
continue
for pubkey in sender_pubkeys:
verifier = VerifyingKey(pubkey)
signature = base64.b64decode(line)
parsed_result['signatures'][signatures_index]['pubkey'] = pubkey
try:
libnacl.crypto_sign_verify_detached(signature, message, verifier.vk)
parsed_result['signatures'][signatures_index]['valid'] = True
except ValueError:
parsed_result['signatures'][signatures_index]['valid'] = False
return parsed_result | python | def parse(ascii_armor_message: str, signing_key: Optional[SigningKey] = None,
sender_pubkeys: Optional[List[str]] = None) -> dict:
"""
Return a dict with parsed content (decrypted message, signature validation) ::
{
'message':
{
'fields': {},
'content': str,
},
'signatures': [
{'pubkey': str, 'valid': bool, fields: {}}
]
}
:param ascii_armor_message: The Ascii Armor Message Block including BEGIN and END headers
:param signing_key: Optional Libnacl SigningKey instance to decrypt message
:param sender_pubkeys: Optional sender's public keys list to verify signatures
:exception libnacl.CryptError: Raise an exception if keypair fail to decrypt the message
:exception MissingSigningKeyException: Raise an exception if no keypair given for encrypted message
:return:
"""
# regex patterns
regex_begin_message = compile(BEGIN_MESSAGE_HEADER)
regex_end_message = compile(END_MESSAGE_HEADER)
regex_begin_signature = compile(BEGIN_SIGNATURE_HEADER)
regex_end_signature = compile(END_SIGNATURE_HEADER)
regex_fields = compile("^(Version|Comment): (.+)$")
# trim message to get rid of empty lines
ascii_armor_message = ascii_armor_message.strip(" \t\n\r")
# init vars
parsed_result = {
'message':
{
'fields': {},
'content': '',
},
'signatures': []
} # type: Dict[str, Any]
cursor_status = 0
message = ''
signatures_index = 0
# parse each line...
for line in ascii_armor_message.splitlines(True):
# if begin message header detected...
if regex_begin_message.match(line):
cursor_status = ON_MESSAGE_FIELDS
continue
# if we are on the fields lines...
if cursor_status == ON_MESSAGE_FIELDS:
# parse field
m = regex_fields.match(line.strip())
if m:
# capture field
msg_field_name = m.groups()[0]
msg_field_value = m.groups()[1]
parsed_result['message']['fields'][msg_field_name] = msg_field_value
continue
# if blank line...
if line.strip("\n\t\r ") == '':
cursor_status = ON_MESSAGE_CONTENT
continue
# if we are on the message content lines...
if cursor_status == ON_MESSAGE_CONTENT:
# if a header is detected, end of message content...
if line.startswith(HEADER_PREFIX):
# if field Version is present, the message is encrypted...
if 'Version' in parsed_result['message']['fields']:
# If keypair instance to decrypt not given...
if signing_key is None:
# SigningKey keypair is mandatory to decrypt the message...
raise PARSER_MISSING_SIGNING_KEY_EXCEPTION
# decrypt message with secret key from keypair
message = AsciiArmor._decrypt(message, signing_key)
# save message content in result
parsed_result['message']['content'] = message
# if message end header...
if regex_end_message.match(line):
# stop parsing
break
# if signature begin header...
if regex_begin_signature.match(line):
# add signature dict in list
parsed_result['signatures'].append({
'fields': {}
})
cursor_status = ON_SIGNATURE_FIELDS
continue
else:
# if field Version is present, the message is encrypted...
if 'Version' in parsed_result['message']['fields']:
# concatenate encrypted line to message content
message += line
else:
# concatenate cleartext striped dash escaped line to message content
message += AsciiArmor._parse_dash_escaped_line(line)
# if we are on a signature fields zone...
if cursor_status == ON_SIGNATURE_FIELDS:
# parse field
m = regex_fields.match(line.strip())
if m:
# capture field
sig_field_name = m.groups()[0]
sig_field_value = m.groups()[1]
parsed_result['signatures'][signatures_index]['fields'][sig_field_name] = sig_field_value
continue
# if blank line...
if line.strip("\n\t\r ") == '':
cursor_status = ON_SIGNATURE_CONTENT
continue
# if we are on the signature content...
if cursor_status == ON_SIGNATURE_CONTENT:
# if no public keys provided...
if sender_pubkeys is None:
# raise exception
raise PARSER_MISSING_PUBLIC_KEYS_EXCEPTION
# if end signature header detected...
if regex_end_signature.match(line):
# end of parsing
break
# if begin signature header detected...
if regex_begin_signature.match(line):
signatures_index += 1
cursor_status = ON_SIGNATURE_FIELDS
continue
for pubkey in sender_pubkeys:
verifier = VerifyingKey(pubkey)
signature = base64.b64decode(line)
parsed_result['signatures'][signatures_index]['pubkey'] = pubkey
try:
libnacl.crypto_sign_verify_detached(signature, message, verifier.vk)
parsed_result['signatures'][signatures_index]['valid'] = True
except ValueError:
parsed_result['signatures'][signatures_index]['valid'] = False
return parsed_result | [
"def",
"parse",
"(",
"ascii_armor_message",
":",
"str",
",",
"signing_key",
":",
"Optional",
"[",
"SigningKey",
"]",
"=",
"None",
",",
"sender_pubkeys",
":",
"Optional",
"[",
"List",
"[",
"str",
"]",
"]",
"=",
"None",
")",
"->",
"dict",
":",
"# regex pat... | Return a dict with parsed content (decrypted message, signature validation) ::
{
'message':
{
'fields': {},
'content': str,
},
'signatures': [
{'pubkey': str, 'valid': bool, fields: {}}
]
}
:param ascii_armor_message: The Ascii Armor Message Block including BEGIN and END headers
:param signing_key: Optional Libnacl SigningKey instance to decrypt message
:param sender_pubkeys: Optional sender's public keys list to verify signatures
:exception libnacl.CryptError: Raise an exception if keypair fail to decrypt the message
:exception MissingSigningKeyException: Raise an exception if no keypair given for encrypted message
:return: | [
"Return",
"a",
"dict",
"with",
"parsed",
"content",
"(",
"decrypted",
"message",
"signature",
"validation",
")",
"::"
] | train | https://github.com/duniter/duniter-python-api/blob/3a1e5d61a2f72f5afaf29d010c6cf4dff3648165/duniterpy/key/ascii_armor.py#L235-L394 |
duniter/duniter-python-api | duniterpy/key/ascii_armor.py | AsciiArmor._decrypt | def _decrypt(ascii_armor_message: str, signing_key: SigningKey) -> str:
"""
Decrypt a message from ascii armor format
:param ascii_armor_message: Utf-8 message
:param signing_key: SigningKey instance created from credentials
:return:
"""
data = signing_key.decrypt_seal(base64.b64decode(ascii_armor_message))
return data.decode('utf-8') | python | def _decrypt(ascii_armor_message: str, signing_key: SigningKey) -> str:
"""
Decrypt a message from ascii armor format
:param ascii_armor_message: Utf-8 message
:param signing_key: SigningKey instance created from credentials
:return:
"""
data = signing_key.decrypt_seal(base64.b64decode(ascii_armor_message))
return data.decode('utf-8') | [
"def",
"_decrypt",
"(",
"ascii_armor_message",
":",
"str",
",",
"signing_key",
":",
"SigningKey",
")",
"->",
"str",
":",
"data",
"=",
"signing_key",
".",
"decrypt_seal",
"(",
"base64",
".",
"b64decode",
"(",
"ascii_armor_message",
")",
")",
"return",
"data",
... | Decrypt a message from ascii armor format
:param ascii_armor_message: Utf-8 message
:param signing_key: SigningKey instance created from credentials
:return: | [
"Decrypt",
"a",
"message",
"from",
"ascii",
"armor",
"format"
] | train | https://github.com/duniter/duniter-python-api/blob/3a1e5d61a2f72f5afaf29d010c6cf4dff3648165/duniterpy/key/ascii_armor.py#L397-L407 |
eshandas/simple_django_logger | django_project/simple_django_logger/response.py | render | def render(request, template_name, context=None, content_type=None, status=None, using=None, logs=None):
"""
Wrapper around Django render method. Can take one or a list of logs and logs the response.
No overhead if no logs are passed.
"""
if logs:
obj_logger = ObjectLogger()
if not isinstance(logs, list):
logs = [logs, ]
for log in logs:
log = obj_logger.log_response(
log,
context,
status=str(status),
headers='',
content_type=str(content_type))
log.save()
return django_render(
request,
template_name,
context=context,
content_type=content_type,
status=status,
using=using) | python | def render(request, template_name, context=None, content_type=None, status=None, using=None, logs=None):
"""
Wrapper around Django render method. Can take one or a list of logs and logs the response.
No overhead if no logs are passed.
"""
if logs:
obj_logger = ObjectLogger()
if not isinstance(logs, list):
logs = [logs, ]
for log in logs:
log = obj_logger.log_response(
log,
context,
status=str(status),
headers='',
content_type=str(content_type))
log.save()
return django_render(
request,
template_name,
context=context,
content_type=content_type,
status=status,
using=using) | [
"def",
"render",
"(",
"request",
",",
"template_name",
",",
"context",
"=",
"None",
",",
"content_type",
"=",
"None",
",",
"status",
"=",
"None",
",",
"using",
"=",
"None",
",",
"logs",
"=",
"None",
")",
":",
"if",
"logs",
":",
"obj_logger",
"=",
"Ob... | Wrapper around Django render method. Can take one or a list of logs and logs the response.
No overhead if no logs are passed. | [
"Wrapper",
"around",
"Django",
"render",
"method",
".",
"Can",
"take",
"one",
"or",
"a",
"list",
"of",
"logs",
"and",
"logs",
"the",
"response",
".",
"No",
"overhead",
"if",
"no",
"logs",
"are",
"passed",
"."
] | train | https://github.com/eshandas/simple_django_logger/blob/a6d15ca1c1ded414ed8fe5cc0c4ca0c20a846582/django_project/simple_django_logger/response.py#L41-L64 |
i3visio/entify | entify/lib/processing.py | getEntitiesByRegexp | def getEntitiesByRegexp(data = None, listRegexp = None, verbosity=1, logFolder="./logs"):
'''
Method to obtain entities by Regexp.
:param data: text where the entities will be looked for.
:param listRegexp: list of selected regular expressions to be looked for. If None was provided, all the available will be chosen instead.
:param verbosity: Verbosity level.
:param logFolder: Folder to store the logs.
:return: a list of the available objects containing the expressions found in the provided data.
[
{
"attributes": [],
"type": "i3visio.email",
"value": "foo@bar.com"
},
{
"attributes": [],
"type": "i3visio.email",
"value": "bar@foo.com"
}
]
'''
i3visiotools.logger.setupLogger(loggerName="entify", verbosity=verbosity, logFolder=logFolder)
logger = logging.getLogger("entify")
if listRegexp == None:
listRegexp = config.getAllRegexp()
foundExpr = []
for r in listRegexp:
foundExpr += r.findExp(data)
# print foundExpr
return foundExpr | python | def getEntitiesByRegexp(data = None, listRegexp = None, verbosity=1, logFolder="./logs"):
'''
Method to obtain entities by Regexp.
:param data: text where the entities will be looked for.
:param listRegexp: list of selected regular expressions to be looked for. If None was provided, all the available will be chosen instead.
:param verbosity: Verbosity level.
:param logFolder: Folder to store the logs.
:return: a list of the available objects containing the expressions found in the provided data.
[
{
"attributes": [],
"type": "i3visio.email",
"value": "foo@bar.com"
},
{
"attributes": [],
"type": "i3visio.email",
"value": "bar@foo.com"
}
]
'''
i3visiotools.logger.setupLogger(loggerName="entify", verbosity=verbosity, logFolder=logFolder)
logger = logging.getLogger("entify")
if listRegexp == None:
listRegexp = config.getAllRegexp()
foundExpr = []
for r in listRegexp:
foundExpr += r.findExp(data)
# print foundExpr
return foundExpr | [
"def",
"getEntitiesByRegexp",
"(",
"data",
"=",
"None",
",",
"listRegexp",
"=",
"None",
",",
"verbosity",
"=",
"1",
",",
"logFolder",
"=",
"\"./logs\"",
")",
":",
"i3visiotools",
".",
"logger",
".",
"setupLogger",
"(",
"loggerName",
"=",
"\"entify\"",
",",
... | Method to obtain entities by Regexp.
:param data: text where the entities will be looked for.
:param listRegexp: list of selected regular expressions to be looked for. If None was provided, all the available will be chosen instead.
:param verbosity: Verbosity level.
:param logFolder: Folder to store the logs.
:return: a list of the available objects containing the expressions found in the provided data.
[
{
"attributes": [],
"type": "i3visio.email",
"value": "foo@bar.com"
},
{
"attributes": [],
"type": "i3visio.email",
"value": "bar@foo.com"
}
] | [
"Method",
"to",
"obtain",
"entities",
"by",
"Regexp",
"."
] | train | https://github.com/i3visio/entify/blob/51c5b89cebee3a39d44d0918e2798739361f337c/entify/lib/processing.py#L35-L70 |
i3visio/entify | entify/lib/processing.py | scanFolderForRegexp | def scanFolderForRegexp(folder = None, listRegexp = None, recursive = False, verbosity=1, logFolder= "./logs"):
'''
[Optionally] recursive method to scan the files in a given folder.
:param folder: the folder to be scanned.
:param listRegexp: listRegexp is an array of <RegexpObject>.
:param recursive: when True, it performs a recursive search on the subfolders.
:return: a list of the available objects containing the expressions found in the provided data.
[
{
"attributes": [],
"type": "i3visio.email",
"value": "foo@bar.com"
},
{
"attributes": [],
"type": "i3visio.email",
"value": "bar@foo.com"
}
]
'''
i3visiotools.logger.setupLogger(loggerName="entify", verbosity=verbosity, logFolder=logFolder)
logger = logging.getLogger("entify")
logger.info("Scanning the folder: " + folder)
results = {}
#onlyfiles = []
#for f in listdir(args.input_folder):
# if isfile(join(args.input_folder, f)):
# onlyfiles.append(f)
onlyfiles = [ f for f in listdir(folder) if isfile(join(folder,f)) ]
for f in onlyfiles:
filePath = join(folder,f)
logger.debug("Looking for regular expressions in: " + filePath)
with open(filePath, "r") as tempF:
# reading data
foundExpr = getEntitiesByRegexp(data = tempF.read(), listRegexp = listRegexp)
logger.debug("Updating the " + str(len(foundExpr)) + " results found on: " + filePath)
results[filePath] = foundExpr
if recursive:
onlyfolders = [ f for f in listdir(folder) if isdir(join(folder,f)) ]
for f in onlyfolders:
folderPath = join(folder, f)
logger.debug("Looking for additional in the folder: "+ folderPath)
results.update(scanFolderForRegexp(folder = folderPath,listRegexp = listRegexp, recursive = recursive))
return results | python | def scanFolderForRegexp(folder = None, listRegexp = None, recursive = False, verbosity=1, logFolder= "./logs"):
'''
[Optionally] recursive method to scan the files in a given folder.
:param folder: the folder to be scanned.
:param listRegexp: listRegexp is an array of <RegexpObject>.
:param recursive: when True, it performs a recursive search on the subfolders.
:return: a list of the available objects containing the expressions found in the provided data.
[
{
"attributes": [],
"type": "i3visio.email",
"value": "foo@bar.com"
},
{
"attributes": [],
"type": "i3visio.email",
"value": "bar@foo.com"
}
]
'''
i3visiotools.logger.setupLogger(loggerName="entify", verbosity=verbosity, logFolder=logFolder)
logger = logging.getLogger("entify")
logger.info("Scanning the folder: " + folder)
results = {}
#onlyfiles = []
#for f in listdir(args.input_folder):
# if isfile(join(args.input_folder, f)):
# onlyfiles.append(f)
onlyfiles = [ f for f in listdir(folder) if isfile(join(folder,f)) ]
for f in onlyfiles:
filePath = join(folder,f)
logger.debug("Looking for regular expressions in: " + filePath)
with open(filePath, "r") as tempF:
# reading data
foundExpr = getEntitiesByRegexp(data = tempF.read(), listRegexp = listRegexp)
logger.debug("Updating the " + str(len(foundExpr)) + " results found on: " + filePath)
results[filePath] = foundExpr
if recursive:
onlyfolders = [ f for f in listdir(folder) if isdir(join(folder,f)) ]
for f in onlyfolders:
folderPath = join(folder, f)
logger.debug("Looking for additional in the folder: "+ folderPath)
results.update(scanFolderForRegexp(folder = folderPath,listRegexp = listRegexp, recursive = recursive))
return results | [
"def",
"scanFolderForRegexp",
"(",
"folder",
"=",
"None",
",",
"listRegexp",
"=",
"None",
",",
"recursive",
"=",
"False",
",",
"verbosity",
"=",
"1",
",",
"logFolder",
"=",
"\"./logs\"",
")",
":",
"i3visiotools",
".",
"logger",
".",
"setupLogger",
"(",
"lo... | [Optionally] recursive method to scan the files in a given folder.
:param folder: the folder to be scanned.
:param listRegexp: listRegexp is an array of <RegexpObject>.
:param recursive: when True, it performs a recursive search on the subfolders.
:return: a list of the available objects containing the expressions found in the provided data.
[
{
"attributes": [],
"type": "i3visio.email",
"value": "foo@bar.com"
},
{
"attributes": [],
"type": "i3visio.email",
"value": "bar@foo.com"
}
] | [
"[",
"Optionally",
"]",
"recursive",
"method",
"to",
"scan",
"the",
"files",
"in",
"a",
"given",
"folder",
"."
] | train | https://github.com/i3visio/entify/blob/51c5b89cebee3a39d44d0918e2798739361f337c/entify/lib/processing.py#L73-L123 |
i3visio/entify | entify/lib/processing.py | scanResource | def scanResource(uri = None, listRegexp = None, verbosity=1, logFolder= "./logs"):
'''
[Optionally] recursive method to scan the files in a given folder.
:param uri: the URI to be scanned.
:param listRegexp: listRegexp is an array of <RegexpObject>.
:return: a dictionary where the key is the name of the file.
'''
i3visiotools.logger.setupLogger(loggerName="entify", verbosity=verbosity, logFolder=logFolder)
logger = logging.getLogger("entify")
results = {}
logger.debug("Looking for regular expressions in: " + uri)
import urllib2
foundExpr = getEntitiesByRegexp(data = urllib2.urlopen(uri).read(), listRegexp = listRegexp)
logger.debug("Updating the " + str(len(foundExpr)) + " results found on: " + uri)
results[uri] = foundExpr
return results | python | def scanResource(uri = None, listRegexp = None, verbosity=1, logFolder= "./logs"):
'''
[Optionally] recursive method to scan the files in a given folder.
:param uri: the URI to be scanned.
:param listRegexp: listRegexp is an array of <RegexpObject>.
:return: a dictionary where the key is the name of the file.
'''
i3visiotools.logger.setupLogger(loggerName="entify", verbosity=verbosity, logFolder=logFolder)
logger = logging.getLogger("entify")
results = {}
logger.debug("Looking for regular expressions in: " + uri)
import urllib2
foundExpr = getEntitiesByRegexp(data = urllib2.urlopen(uri).read(), listRegexp = listRegexp)
logger.debug("Updating the " + str(len(foundExpr)) + " results found on: " + uri)
results[uri] = foundExpr
return results | [
"def",
"scanResource",
"(",
"uri",
"=",
"None",
",",
"listRegexp",
"=",
"None",
",",
"verbosity",
"=",
"1",
",",
"logFolder",
"=",
"\"./logs\"",
")",
":",
"i3visiotools",
".",
"logger",
".",
"setupLogger",
"(",
"loggerName",
"=",
"\"entify\"",
",",
"verbos... | [Optionally] recursive method to scan the files in a given folder.
:param uri: the URI to be scanned.
:param listRegexp: listRegexp is an array of <RegexpObject>.
:return: a dictionary where the key is the name of the file. | [
"[",
"Optionally",
"]",
"recursive",
"method",
"to",
"scan",
"the",
"files",
"in",
"a",
"given",
"folder",
"."
] | train | https://github.com/i3visio/entify/blob/51c5b89cebee3a39d44d0918e2798739361f337c/entify/lib/processing.py#L126-L148 |
i3visio/entify | entify/lib/processing.py | entify_main | def entify_main(args):
'''
Main function. This function is created in this way so as to let other applications make use of the full configuration capabilities of the application.
'''
# Recovering the logger
# Calling the logger when being imported
i3visiotools.logger.setupLogger(loggerName="entify", verbosity=args.verbose, logFolder=args.logfolder)
# From now on, the logger can be recovered like this:
logger = logging.getLogger("entify")
logger.info("""entify-launcher.py Copyright (C) F. Brezo and Y. Rubio (i3visio) 2014
This program comes with ABSOLUTELY NO WARRANTY.
This is free software, and you are welcome to redistribute it under certain conditions.
For details, run:
\tpython entify-launcher.py --license""")
logger.info("Selecting the regular expressions to be analysed...")
listRegexp = []
if args.regexp:
listRegexp = config.getRegexpsByName(args.regexp)
elif args.new_regexp:
for i, r in enumerate(args.new_regexp):
list.Regexp.append(RegexpObject(name = "NewRegexp"+str(i), reg_exp = args.new_regexp))
if not args.web:
results = scanFolderForRegexp(folder = args.input_folder, listRegexp= listRegexp, recursive = args.recursive, verbosity=args.verbose, logFolder= args.logfolder)
else:
results = scanResource(uri = args.web, listRegexp= listRegexp, verbosity=args.verbose, logFolder= args.logfolder)
logger.info("Printing the results:\n" + general.dictToJson(results))
if args.output_folder:
logger.info("Preparing the output folder...")
if not os.path.exists(args.output_folder):
logger.warning("The output folder \'" + args.output_folder + "\' does not exist. The system will try to create it.")
os.makedirs(args.output_folder)
logger.info("Storing the results...")
"""if "csv" in args.extension:
with open(os.path.join(args.output_folder, "results.csv"), "w") as oF:
oF.write(resultsToCSV(results))"""
if "json" in args.extension:
with open(os.path.join(args.output_folder, "results.json"), "w") as oF:
oF.write(general.dictToJson(results)) | python | def entify_main(args):
'''
Main function. This function is created in this way so as to let other applications make use of the full configuration capabilities of the application.
'''
# Recovering the logger
# Calling the logger when being imported
i3visiotools.logger.setupLogger(loggerName="entify", verbosity=args.verbose, logFolder=args.logfolder)
# From now on, the logger can be recovered like this:
logger = logging.getLogger("entify")
logger.info("""entify-launcher.py Copyright (C) F. Brezo and Y. Rubio (i3visio) 2014
This program comes with ABSOLUTELY NO WARRANTY.
This is free software, and you are welcome to redistribute it under certain conditions.
For details, run:
\tpython entify-launcher.py --license""")
logger.info("Selecting the regular expressions to be analysed...")
listRegexp = []
if args.regexp:
listRegexp = config.getRegexpsByName(args.regexp)
elif args.new_regexp:
for i, r in enumerate(args.new_regexp):
list.Regexp.append(RegexpObject(name = "NewRegexp"+str(i), reg_exp = args.new_regexp))
if not args.web:
results = scanFolderForRegexp(folder = args.input_folder, listRegexp= listRegexp, recursive = args.recursive, verbosity=args.verbose, logFolder= args.logfolder)
else:
results = scanResource(uri = args.web, listRegexp= listRegexp, verbosity=args.verbose, logFolder= args.logfolder)
logger.info("Printing the results:\n" + general.dictToJson(results))
if args.output_folder:
logger.info("Preparing the output folder...")
if not os.path.exists(args.output_folder):
logger.warning("The output folder \'" + args.output_folder + "\' does not exist. The system will try to create it.")
os.makedirs(args.output_folder)
logger.info("Storing the results...")
"""if "csv" in args.extension:
with open(os.path.join(args.output_folder, "results.csv"), "w") as oF:
oF.write(resultsToCSV(results))"""
if "json" in args.extension:
with open(os.path.join(args.output_folder, "results.json"), "w") as oF:
oF.write(general.dictToJson(results)) | [
"def",
"entify_main",
"(",
"args",
")",
":",
"# Recovering the logger",
"# Calling the logger when being imported",
"i3visiotools",
".",
"logger",
".",
"setupLogger",
"(",
"loggerName",
"=",
"\"entify\"",
",",
"verbosity",
"=",
"args",
".",
"verbose",
",",
"logFolder"... | Main function. This function is created in this way so as to let other applications make use of the full configuration capabilities of the application. | [
"Main",
"function",
".",
"This",
"function",
"is",
"created",
"in",
"this",
"way",
"so",
"as",
"to",
"let",
"other",
"applications",
"make",
"use",
"of",
"the",
"full",
"configuration",
"capabilities",
"of",
"the",
"application",
"."
] | train | https://github.com/i3visio/entify/blob/51c5b89cebee3a39d44d0918e2798739361f337c/entify/lib/processing.py#L150-L193 |
MacHu-GWU/pymongo_mate-project | pymongo_mate/pkg/pandas_mate/transform.py | grouper_df | def grouper_df(df, chunksize):
"""Evenly divide pd.DataFrame into n rows piece, no filled value
if sub dataframe's size smaller than n.
:param df: ``pandas.DataFrame`` instance.
:param chunksize: number of rows of each small DataFrame.
**中文文档**
将 ``pandas.DataFrame`` 分拆成等大小的小DataFrame。
"""
data = list()
counter = 0
for tp in zip(*(l for col, l in df.iteritems())):
counter += 1
data.append(tp)
if counter == chunksize:
new_df = pd.DataFrame(data, columns=df.columns)
yield new_df
data = list()
counter = 0
if len(data) > 0:
new_df = pd.DataFrame(data, columns=df.columns)
yield new_df | python | def grouper_df(df, chunksize):
"""Evenly divide pd.DataFrame into n rows piece, no filled value
if sub dataframe's size smaller than n.
:param df: ``pandas.DataFrame`` instance.
:param chunksize: number of rows of each small DataFrame.
**中文文档**
将 ``pandas.DataFrame`` 分拆成等大小的小DataFrame。
"""
data = list()
counter = 0
for tp in zip(*(l for col, l in df.iteritems())):
counter += 1
data.append(tp)
if counter == chunksize:
new_df = pd.DataFrame(data, columns=df.columns)
yield new_df
data = list()
counter = 0
if len(data) > 0:
new_df = pd.DataFrame(data, columns=df.columns)
yield new_df | [
"def",
"grouper_df",
"(",
"df",
",",
"chunksize",
")",
":",
"data",
"=",
"list",
"(",
")",
"counter",
"=",
"0",
"for",
"tp",
"in",
"zip",
"(",
"*",
"(",
"l",
"for",
"col",
",",
"l",
"in",
"df",
".",
"iteritems",
"(",
")",
")",
")",
":",
"coun... | Evenly divide pd.DataFrame into n rows piece, no filled value
if sub dataframe's size smaller than n.
:param df: ``pandas.DataFrame`` instance.
:param chunksize: number of rows of each small DataFrame.
**中文文档**
将 ``pandas.DataFrame`` 分拆成等大小的小DataFrame。 | [
"Evenly",
"divide",
"pd",
".",
"DataFrame",
"into",
"n",
"rows",
"piece",
"no",
"filled",
"value",
"if",
"sub",
"dataframe",
"s",
"size",
"smaller",
"than",
"n",
"."
] | train | https://github.com/MacHu-GWU/pymongo_mate-project/blob/be53170c2db54cb705b9e548d32ef26c773ff7f3/pymongo_mate/pkg/pandas_mate/transform.py#L35-L59 |
MacHu-GWU/pymongo_mate-project | pymongo_mate/pkg/pandas_mate/transform.py | to_index_row_dict | def to_index_row_dict(df, index_col=None, use_ordered_dict=True):
"""Transform data frame to list of dict.
:param index_col: None or str, the column that used as index.
:param use_ordered_dict: if True, row dict is has same order as df.columns.
**中文文档**
将dataframe以指定列为key, 转化成以行为视角的dict结构, 提升按行index访问
的速度。若无指定列, 则使用index。
"""
if index_col:
index_list = df[index_col]
else:
index_list = df.index
columns = df.columns
if use_ordered_dict:
table = OrderedDict()
else:
table = dict()
for ind, tp in zip(index_list, itertuple(df)):
table[ind] = dict(zip(columns, tp))
return table | python | def to_index_row_dict(df, index_col=None, use_ordered_dict=True):
"""Transform data frame to list of dict.
:param index_col: None or str, the column that used as index.
:param use_ordered_dict: if True, row dict is has same order as df.columns.
**中文文档**
将dataframe以指定列为key, 转化成以行为视角的dict结构, 提升按行index访问
的速度。若无指定列, 则使用index。
"""
if index_col:
index_list = df[index_col]
else:
index_list = df.index
columns = df.columns
if use_ordered_dict:
table = OrderedDict()
else:
table = dict()
for ind, tp in zip(index_list, itertuple(df)):
table[ind] = dict(zip(columns, tp))
return table | [
"def",
"to_index_row_dict",
"(",
"df",
",",
"index_col",
"=",
"None",
",",
"use_ordered_dict",
"=",
"True",
")",
":",
"if",
"index_col",
":",
"index_list",
"=",
"df",
"[",
"index_col",
"]",
"else",
":",
"index_list",
"=",
"df",
".",
"index",
"columns",
"... | Transform data frame to list of dict.
:param index_col: None or str, the column that used as index.
:param use_ordered_dict: if True, row dict is has same order as df.columns.
**中文文档**
将dataframe以指定列为key, 转化成以行为视角的dict结构, 提升按行index访问
的速度。若无指定列, 则使用index。 | [
"Transform",
"data",
"frame",
"to",
"list",
"of",
"dict",
"."
] | train | https://github.com/MacHu-GWU/pymongo_mate-project/blob/be53170c2db54cb705b9e548d32ef26c773ff7f3/pymongo_mate/pkg/pandas_mate/transform.py#L62-L88 |
MacHu-GWU/pymongo_mate-project | pymongo_mate/pkg/pandas_mate/transform.py | to_dict_list | def to_dict_list(df, use_ordered_dict=True):
"""Transform each row to dict, and put them into a list.
**中文文档**
将 ``pandas.DataFrame`` 转换成一个字典的列表。列表的长度与行数相同, 其中
每一个字典相当于表中的一行, 相当于一个 ``pandas.Series`` 对象。
"""
if use_ordered_dict:
dict = OrderedDict
columns = df.columns
data = list()
for tp in itertuple(df):
data.append(dict(zip(columns, tp)))
return data | python | def to_dict_list(df, use_ordered_dict=True):
"""Transform each row to dict, and put them into a list.
**中文文档**
将 ``pandas.DataFrame`` 转换成一个字典的列表。列表的长度与行数相同, 其中
每一个字典相当于表中的一行, 相当于一个 ``pandas.Series`` 对象。
"""
if use_ordered_dict:
dict = OrderedDict
columns = df.columns
data = list()
for tp in itertuple(df):
data.append(dict(zip(columns, tp)))
return data | [
"def",
"to_dict_list",
"(",
"df",
",",
"use_ordered_dict",
"=",
"True",
")",
":",
"if",
"use_ordered_dict",
":",
"dict",
"=",
"OrderedDict",
"columns",
"=",
"df",
".",
"columns",
"data",
"=",
"list",
"(",
")",
"for",
"tp",
"in",
"itertuple",
"(",
"df",
... | Transform each row to dict, and put them into a list.
**中文文档**
将 ``pandas.DataFrame`` 转换成一个字典的列表。列表的长度与行数相同, 其中
每一个字典相当于表中的一行, 相当于一个 ``pandas.Series`` 对象。 | [
"Transform",
"each",
"row",
"to",
"dict",
"and",
"put",
"them",
"into",
"a",
"list",
"."
] | train | https://github.com/MacHu-GWU/pymongo_mate-project/blob/be53170c2db54cb705b9e548d32ef26c773ff7f3/pymongo_mate/pkg/pandas_mate/transform.py#L91-L106 |
MacHu-GWU/pymongo_mate-project | pymongo_mate/pkg/pandas_mate/transform.py | to_dict_list_generic_type | def to_dict_list_generic_type(df, int_col=None, binary_col=None):
"""Transform each row to dict, and put them into a list. And automatically
convert ``np.int64`` to ``int``, ``pandas.tslib.Timestamp`` to
``datetime.datetime``, ``np.nan`` to ``None``.
:param df: ``pandas.DataFrame`` instance.
:param int_col: integer type columns.
:param binary_col: binary type type columns.
**中文文档**
由于 ``pandas.Series`` 中的值的整数数据类型是 ``numpy.int64``,
时间数据类型是 ``pandas.tslib.Timestamp``, None的数据类型是 ``np.nan``。
虽然从访问和计算的角度来说没有什么问题, 但会和很多数据库的操作不兼容。
此函数能将 ``pandas.DataFrame`` 转化成字典的列表。数据类型能正确的获得int,
bytes和datetime.datetime。
"""
# Pre-process int_col, binary_col and datetime_col
if (int_col is not None) and (not isinstance(int_col, (list, tuple))):
int_col = [int_col, ]
if (binary_col is not None) and (not isinstance(binary_col, (list, tuple))):
binary_col = [binary_col, ]
datetime_col = list()
for col, dtype in dict(df.dtypes).items():
if "datetime64" in str(dtype):
datetime_col.append(col)
if len(datetime_col) == 0:
datetime_col = None
# Pre-process binary column dataframe
def b64_encode(b):
try:
return base64.b64encode(b)
except:
return b
if binary_col is not None:
for col in binary_col:
df[col] = df[col].apply(b64_encode)
data = json.loads(df.to_json(orient="records", date_format="iso"))
if int_col is not None:
for row in data:
for col in int_col:
try:
row[col] = int(row[col])
except:
pass
if binary_col is not None:
for row in data:
for col in binary_col:
try:
row[col] = base64.b64decode(row[col].encode("ascii"))
except:
pass
if datetime_col is not None:
for row in data:
for col in datetime_col:
try:
row[col] = rolex.str2datetime(row[col])
except:
pass
return data | python | def to_dict_list_generic_type(df, int_col=None, binary_col=None):
"""Transform each row to dict, and put them into a list. And automatically
convert ``np.int64`` to ``int``, ``pandas.tslib.Timestamp`` to
``datetime.datetime``, ``np.nan`` to ``None``.
:param df: ``pandas.DataFrame`` instance.
:param int_col: integer type columns.
:param binary_col: binary type type columns.
**中文文档**
由于 ``pandas.Series`` 中的值的整数数据类型是 ``numpy.int64``,
时间数据类型是 ``pandas.tslib.Timestamp``, None的数据类型是 ``np.nan``。
虽然从访问和计算的角度来说没有什么问题, 但会和很多数据库的操作不兼容。
此函数能将 ``pandas.DataFrame`` 转化成字典的列表。数据类型能正确的获得int,
bytes和datetime.datetime。
"""
# Pre-process int_col, binary_col and datetime_col
if (int_col is not None) and (not isinstance(int_col, (list, tuple))):
int_col = [int_col, ]
if (binary_col is not None) and (not isinstance(binary_col, (list, tuple))):
binary_col = [binary_col, ]
datetime_col = list()
for col, dtype in dict(df.dtypes).items():
if "datetime64" in str(dtype):
datetime_col.append(col)
if len(datetime_col) == 0:
datetime_col = None
# Pre-process binary column dataframe
def b64_encode(b):
try:
return base64.b64encode(b)
except:
return b
if binary_col is not None:
for col in binary_col:
df[col] = df[col].apply(b64_encode)
data = json.loads(df.to_json(orient="records", date_format="iso"))
if int_col is not None:
for row in data:
for col in int_col:
try:
row[col] = int(row[col])
except:
pass
if binary_col is not None:
for row in data:
for col in binary_col:
try:
row[col] = base64.b64decode(row[col].encode("ascii"))
except:
pass
if datetime_col is not None:
for row in data:
for col in datetime_col:
try:
row[col] = rolex.str2datetime(row[col])
except:
pass
return data | [
"def",
"to_dict_list_generic_type",
"(",
"df",
",",
"int_col",
"=",
"None",
",",
"binary_col",
"=",
"None",
")",
":",
"# Pre-process int_col, binary_col and datetime_col",
"if",
"(",
"int_col",
"is",
"not",
"None",
")",
"and",
"(",
"not",
"isinstance",
"(",
"int... | Transform each row to dict, and put them into a list. And automatically
convert ``np.int64`` to ``int``, ``pandas.tslib.Timestamp`` to
``datetime.datetime``, ``np.nan`` to ``None``.
:param df: ``pandas.DataFrame`` instance.
:param int_col: integer type columns.
:param binary_col: binary type type columns.
**中文文档**
由于 ``pandas.Series`` 中的值的整数数据类型是 ``numpy.int64``,
时间数据类型是 ``pandas.tslib.Timestamp``, None的数据类型是 ``np.nan``。
虽然从访问和计算的角度来说没有什么问题, 但会和很多数据库的操作不兼容。
此函数能将 ``pandas.DataFrame`` 转化成字典的列表。数据类型能正确的获得int,
bytes和datetime.datetime。 | [
"Transform",
"each",
"row",
"to",
"dict",
"and",
"put",
"them",
"into",
"a",
"list",
".",
"And",
"automatically",
"convert",
"np",
".",
"int64",
"to",
"int",
"pandas",
".",
"tslib",
".",
"Timestamp",
"to",
"datetime",
".",
"datetime",
"np",
".",
"nan",
... | train | https://github.com/MacHu-GWU/pymongo_mate-project/blob/be53170c2db54cb705b9e548d32ef26c773ff7f3/pymongo_mate/pkg/pandas_mate/transform.py#L109-L178 |
BD2KOnFHIR/i2b2model | i2b2model/sqlsupport/dbconnection.py | add_connection_args | def add_connection_args(parser: FileAwareParser, strong_config_file: bool=True) -> FileAwareParser:
"""
Add the database connection arguments to the supplied parser
:param parser: parser to add arguments to
:param strong_config_file: If True, force --conf to be processed. This is strictly a test for programming errors,
and has to be skipped due to removefacts function.
:return: parser
"""
# TODO: Decide what to do with this
parser.add_file_argument("--conf", metavar="CONFIG FILE", help="Configuration file",
action=ConfigFile if strong_config_file else None)
parser.add_argument("-db", "--dburl", help="Default database URL",
default=Default_DB_Connection)
parser.add_argument("--user", help="Default user name",
default=Default_User)
parser.add_argument("--password", help="Default password",
default=Default_Password)
parser.add_argument("--crcdb", help="CRC database URL. (default: dburl)")
parser.add_argument("--crcuser", help="User name for CRC database. (default: user)")
parser.add_argument("--crcpassword", help="Password for CRC database. (default: password)")
parser.add_argument("--ontodb", help="Ontology database URL. (default: dburl)")
parser.add_argument("--ontouser", help="User name for ontology database. (default: user)")
parser.add_argument("--ontopassword", help="Password for ontology database. (default: password)")
parser.add_argument("--onttable", metavar="ONTOLOGY TABLE NAME",
help="Ontology table name (default: {})".format(DEFAULT_ONTOLOGY_TABLE),
default=DEFAULT_ONTOLOGY_TABLE)
return parser | python | def add_connection_args(parser: FileAwareParser, strong_config_file: bool=True) -> FileAwareParser:
"""
Add the database connection arguments to the supplied parser
:param parser: parser to add arguments to
:param strong_config_file: If True, force --conf to be processed. This is strictly a test for programming errors,
and has to be skipped due to removefacts function.
:return: parser
"""
# TODO: Decide what to do with this
parser.add_file_argument("--conf", metavar="CONFIG FILE", help="Configuration file",
action=ConfigFile if strong_config_file else None)
parser.add_argument("-db", "--dburl", help="Default database URL",
default=Default_DB_Connection)
parser.add_argument("--user", help="Default user name",
default=Default_User)
parser.add_argument("--password", help="Default password",
default=Default_Password)
parser.add_argument("--crcdb", help="CRC database URL. (default: dburl)")
parser.add_argument("--crcuser", help="User name for CRC database. (default: user)")
parser.add_argument("--crcpassword", help="Password for CRC database. (default: password)")
parser.add_argument("--ontodb", help="Ontology database URL. (default: dburl)")
parser.add_argument("--ontouser", help="User name for ontology database. (default: user)")
parser.add_argument("--ontopassword", help="Password for ontology database. (default: password)")
parser.add_argument("--onttable", metavar="ONTOLOGY TABLE NAME",
help="Ontology table name (default: {})".format(DEFAULT_ONTOLOGY_TABLE),
default=DEFAULT_ONTOLOGY_TABLE)
return parser | [
"def",
"add_connection_args",
"(",
"parser",
":",
"FileAwareParser",
",",
"strong_config_file",
":",
"bool",
"=",
"True",
")",
"->",
"FileAwareParser",
":",
"# TODO: Decide what to do with this",
"parser",
".",
"add_file_argument",
"(",
"\"--conf\"",
",",
"metavar",
"... | Add the database connection arguments to the supplied parser
:param parser: parser to add arguments to
:param strong_config_file: If True, force --conf to be processed. This is strictly a test for programming errors,
and has to be skipped due to removefacts function.
:return: parser | [
"Add",
"the",
"database",
"connection",
"arguments",
"to",
"the",
"supplied",
"parser"
] | train | https://github.com/BD2KOnFHIR/i2b2model/blob/9d49bb53b0733dd83ab5b716014865e270a3c903/i2b2model/sqlsupport/dbconnection.py#L18-L46 |
BD2KOnFHIR/i2b2model | i2b2model/sqlsupport/dbconnection.py | process_parsed_args | def process_parsed_args(opts: Namespace, error_fun: Optional[Callable], connect: bool=True) -> Namespace:
"""
Set the defaults for the crc and ontology schemas
:param opts: parsed arguments
:param error_fun: Function to call if error
:param connect: actually connect. (For debugging)
:return: namespace with additional elements added
"""
def setdefault(vn: str, default: object) -> None:
assert vn in opts, "Unknown option"
if not getattr(opts, vn):
setattr(opts, vn, default)
if error_fun and \
(getattr(opts, 'dburl') is None or getattr(opts, 'user') is None or getattr(opts, 'password') is None):
error_fun("db url, user id and password must be supplied")
setdefault('crcdb', opts.dburl)
setdefault('crcuser', opts.user)
setdefault('crcpassword', opts.password)
setdefault('ontodb', opts.dburl)
setdefault('ontouser', opts.user)
setdefault('ontopassword', opts.password)
if connect:
opts.tables = I2B2Tables(opts)
# TODO: This approach needs to be re-thought. As i2b2tablenames is a singleton, any changes here
# impact the entire testing harness
if opts.onttable:
i2b2tablenames.ontology_table = opts.onttable
return opts | python | def process_parsed_args(opts: Namespace, error_fun: Optional[Callable], connect: bool=True) -> Namespace:
"""
Set the defaults for the crc and ontology schemas
:param opts: parsed arguments
:param error_fun: Function to call if error
:param connect: actually connect. (For debugging)
:return: namespace with additional elements added
"""
def setdefault(vn: str, default: object) -> None:
assert vn in opts, "Unknown option"
if not getattr(opts, vn):
setattr(opts, vn, default)
if error_fun and \
(getattr(opts, 'dburl') is None or getattr(opts, 'user') is None or getattr(opts, 'password') is None):
error_fun("db url, user id and password must be supplied")
setdefault('crcdb', opts.dburl)
setdefault('crcuser', opts.user)
setdefault('crcpassword', opts.password)
setdefault('ontodb', opts.dburl)
setdefault('ontouser', opts.user)
setdefault('ontopassword', opts.password)
if connect:
opts.tables = I2B2Tables(opts)
# TODO: This approach needs to be re-thought. As i2b2tablenames is a singleton, any changes here
# impact the entire testing harness
if opts.onttable:
i2b2tablenames.ontology_table = opts.onttable
return opts | [
"def",
"process_parsed_args",
"(",
"opts",
":",
"Namespace",
",",
"error_fun",
":",
"Optional",
"[",
"Callable",
"]",
",",
"connect",
":",
"bool",
"=",
"True",
")",
"->",
"Namespace",
":",
"def",
"setdefault",
"(",
"vn",
":",
"str",
",",
"default",
":",
... | Set the defaults for the crc and ontology schemas
:param opts: parsed arguments
:param error_fun: Function to call if error
:param connect: actually connect. (For debugging)
:return: namespace with additional elements added | [
"Set",
"the",
"defaults",
"for",
"the",
"crc",
"and",
"ontology",
"schemas",
":",
"param",
"opts",
":",
"parsed",
"arguments",
":",
"param",
"error_fun",
":",
"Function",
"to",
"call",
"if",
"error",
":",
"param",
"connect",
":",
"actually",
"connect",
"."... | train | https://github.com/BD2KOnFHIR/i2b2model/blob/9d49bb53b0733dd83ab5b716014865e270a3c903/i2b2model/sqlsupport/dbconnection.py#L49-L78 |
robehickman/simple-http-file-sync | shttpfs/versioned_storage.py | versioned_storage.build_dir_tree | def build_dir_tree(self, files):
""" Convert a flat file dict into the tree format used for storage """
def helper(split_files):
this_dir = {'files' : {}, 'dirs' : {}}
dirs = defaultdict(list)
for fle in split_files:
index = fle[0]; fileinfo = fle[1]
if len(index) == 1:
fileinfo['path'] = index[0] # store only the file name instead of the whole path
this_dir['files'][fileinfo['path']] = fileinfo
elif len(index) > 1:
dirs[index[0]].append((index[1:], fileinfo))
for name,info in dirs.iteritems():
this_dir['dirs'][name] = helper(info)
return this_dir
return helper([(name.split('/')[1:], file_info) for name, file_info in files.iteritems()]) | python | def build_dir_tree(self, files):
""" Convert a flat file dict into the tree format used for storage """
def helper(split_files):
this_dir = {'files' : {}, 'dirs' : {}}
dirs = defaultdict(list)
for fle in split_files:
index = fle[0]; fileinfo = fle[1]
if len(index) == 1:
fileinfo['path'] = index[0] # store only the file name instead of the whole path
this_dir['files'][fileinfo['path']] = fileinfo
elif len(index) > 1:
dirs[index[0]].append((index[1:], fileinfo))
for name,info in dirs.iteritems():
this_dir['dirs'][name] = helper(info)
return this_dir
return helper([(name.split('/')[1:], file_info) for name, file_info in files.iteritems()]) | [
"def",
"build_dir_tree",
"(",
"self",
",",
"files",
")",
":",
"def",
"helper",
"(",
"split_files",
")",
":",
"this_dir",
"=",
"{",
"'files'",
":",
"{",
"}",
",",
"'dirs'",
":",
"{",
"}",
"}",
"dirs",
"=",
"defaultdict",
"(",
"list",
")",
"for",
"fl... | Convert a flat file dict into the tree format used for storage | [
"Convert",
"a",
"flat",
"file",
"dict",
"into",
"the",
"tree",
"format",
"used",
"for",
"storage"
] | train | https://github.com/robehickman/simple-http-file-sync/blob/fa29b3ee58e9504e1d3ddfc0c14047284bf9921d/shttpfs/versioned_storage.py#L46-L64 |
robehickman/simple-http-file-sync | shttpfs/versioned_storage.py | versioned_storage.flatten_dir_tree | def flatten_dir_tree(self, tree):
""" Convert a file tree back into a flat dict """
result = {}
def helper(tree, leading_path = ''):
dirs = tree['dirs']; files = tree['files']
for name, file_info in files.iteritems():
file_info['path'] = leading_path + '/' + name
result[file_info['path']] = file_info
for name, contents in dirs.iteritems():
helper(contents, leading_path +'/'+ name)
helper(tree); return result | python | def flatten_dir_tree(self, tree):
""" Convert a file tree back into a flat dict """
result = {}
def helper(tree, leading_path = ''):
dirs = tree['dirs']; files = tree['files']
for name, file_info in files.iteritems():
file_info['path'] = leading_path + '/' + name
result[file_info['path']] = file_info
for name, contents in dirs.iteritems():
helper(contents, leading_path +'/'+ name)
helper(tree); return result | [
"def",
"flatten_dir_tree",
"(",
"self",
",",
"tree",
")",
":",
"result",
"=",
"{",
"}",
"def",
"helper",
"(",
"tree",
",",
"leading_path",
"=",
"''",
")",
":",
"dirs",
"=",
"tree",
"[",
"'dirs'",
"]",
"files",
"=",
"tree",
"[",
"'files'",
"]",
"for... | Convert a file tree back into a flat dict | [
"Convert",
"a",
"file",
"tree",
"back",
"into",
"a",
"flat",
"dict"
] | train | https://github.com/robehickman/simple-http-file-sync/blob/fa29b3ee58e9504e1d3ddfc0c14047284bf9921d/shttpfs/versioned_storage.py#L68-L81 |
robehickman/simple-http-file-sync | shttpfs/versioned_storage.py | versioned_storage.read_dir_tree | def read_dir_tree(self, file_hash):
""" Recursively read the directory structure beginning at hash """
json_d = self.read_index_object(file_hash, 'tree')
node = {'files' : json_d['files'], 'dirs' : {}}
for name, hsh in json_d['dirs'].iteritems(): node['dirs'][name] = self.read_dir_tree(hsh)
return node | python | def read_dir_tree(self, file_hash):
""" Recursively read the directory structure beginning at hash """
json_d = self.read_index_object(file_hash, 'tree')
node = {'files' : json_d['files'], 'dirs' : {}}
for name, hsh in json_d['dirs'].iteritems(): node['dirs'][name] = self.read_dir_tree(hsh)
return node | [
"def",
"read_dir_tree",
"(",
"self",
",",
"file_hash",
")",
":",
"json_d",
"=",
"self",
".",
"read_index_object",
"(",
"file_hash",
",",
"'tree'",
")",
"node",
"=",
"{",
"'files'",
":",
"json_d",
"[",
"'files'",
"]",
",",
"'dirs'",
":",
"{",
"}",
"}",
... | Recursively read the directory structure beginning at hash | [
"Recursively",
"read",
"the",
"directory",
"structure",
"beginning",
"at",
"hash"
] | train | https://github.com/robehickman/simple-http-file-sync/blob/fa29b3ee58e9504e1d3ddfc0c14047284bf9921d/shttpfs/versioned_storage.py#L94-L100 |
robehickman/simple-http-file-sync | shttpfs/versioned_storage.py | versioned_storage.write_dir_tree | def write_dir_tree(self, tree):
""" Recur through dir tree data structure and write it as a set of objects """
dirs = tree['dirs']; files = tree['files']
child_dirs = {name : self.write_dir_tree(contents) for name, contents in dirs.iteritems()}
return self.write_index_object('tree', {'files' : files, 'dirs': child_dirs}) | python | def write_dir_tree(self, tree):
""" Recur through dir tree data structure and write it as a set of objects """
dirs = tree['dirs']; files = tree['files']
child_dirs = {name : self.write_dir_tree(contents) for name, contents in dirs.iteritems()}
return self.write_index_object('tree', {'files' : files, 'dirs': child_dirs}) | [
"def",
"write_dir_tree",
"(",
"self",
",",
"tree",
")",
":",
"dirs",
"=",
"tree",
"[",
"'dirs'",
"]",
"files",
"=",
"tree",
"[",
"'files'",
"]",
"child_dirs",
"=",
"{",
"name",
":",
"self",
".",
"write_dir_tree",
"(",
"contents",
")",
"for",
"name",
... | Recur through dir tree data structure and write it as a set of objects | [
"Recur",
"through",
"dir",
"tree",
"data",
"structure",
"and",
"write",
"it",
"as",
"a",
"set",
"of",
"objects"
] | train | https://github.com/robehickman/simple-http-file-sync/blob/fa29b3ee58e9504e1d3ddfc0c14047284bf9921d/shttpfs/versioned_storage.py#L104-L109 |
robehickman/simple-http-file-sync | shttpfs/versioned_storage.py | versioned_storage.have_active_commit | def have_active_commit(self):
""" Checks if there is an active commit owned by the specified user """
commit_state = sfs.file_or_default(sfs.cpjoin(self.base_path, 'active_commit'), None)
if commit_state != None: return True
return False | python | def have_active_commit(self):
""" Checks if there is an active commit owned by the specified user """
commit_state = sfs.file_or_default(sfs.cpjoin(self.base_path, 'active_commit'), None)
if commit_state != None: return True
return False | [
"def",
"have_active_commit",
"(",
"self",
")",
":",
"commit_state",
"=",
"sfs",
".",
"file_or_default",
"(",
"sfs",
".",
"cpjoin",
"(",
"self",
".",
"base_path",
",",
"'active_commit'",
")",
",",
"None",
")",
"if",
"commit_state",
"!=",
"None",
":",
"retur... | Checks if there is an active commit owned by the specified user | [
"Checks",
"if",
"there",
"is",
"an",
"active",
"commit",
"owned",
"by",
"the",
"specified",
"user"
] | train | https://github.com/robehickman/simple-http-file-sync/blob/fa29b3ee58e9504e1d3ddfc0c14047284bf9921d/shttpfs/versioned_storage.py#L113-L118 |
etcher-be/epab | epab/bases/repo.py | BaseRepo.amend_commit | def amend_commit(
self,
append_to_msg: typing.Optional[str] = None,
new_message: typing.Optional[str] = None,
files_to_add: typing.Optional[typing.Union[typing.List[str], str]] = None,
):
"""
Amends last commit
Args:
append_to_msg: string to append to previous message
new_message: new commit message
files_to_add: optional list of files to commit
""" | python | def amend_commit(
self,
append_to_msg: typing.Optional[str] = None,
new_message: typing.Optional[str] = None,
files_to_add: typing.Optional[typing.Union[typing.List[str], str]] = None,
):
"""
Amends last commit
Args:
append_to_msg: string to append to previous message
new_message: new commit message
files_to_add: optional list of files to commit
""" | [
"def",
"amend_commit",
"(",
"self",
",",
"append_to_msg",
":",
"typing",
".",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"new_message",
":",
"typing",
".",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"files_to_add",
":",
"typing",
".",
"Optional",... | Amends last commit
Args:
append_to_msg: string to append to previous message
new_message: new commit message
files_to_add: optional list of files to commit | [
"Amends",
"last",
"commit"
] | train | https://github.com/etcher-be/epab/blob/024cde74d058281aa66e6e4b7b71dccbe803b1c1/epab/bases/repo.py#L210-L223 |
martinkosir/neverbounce-python | neverbounce/objects.py | VerifiedEmail.from_text_code | def from_text_code(cls, email, result_text_code):
"""
Alternative method to create an instance of VerifiedEmail object from a text code.
:param str email: Email address.
:param str result_text_code: A result of verification represented by text (e.g. valid, unknown).
:return: An instance of object.
"""
result_code = cls.result_text_codes[result_text_code]
return cls(email, result_code) | python | def from_text_code(cls, email, result_text_code):
"""
Alternative method to create an instance of VerifiedEmail object from a text code.
:param str email: Email address.
:param str result_text_code: A result of verification represented by text (e.g. valid, unknown).
:return: An instance of object.
"""
result_code = cls.result_text_codes[result_text_code]
return cls(email, result_code) | [
"def",
"from_text_code",
"(",
"cls",
",",
"email",
",",
"result_text_code",
")",
":",
"result_code",
"=",
"cls",
".",
"result_text_codes",
"[",
"result_text_code",
"]",
"return",
"cls",
"(",
"email",
",",
"result_code",
")"
] | Alternative method to create an instance of VerifiedEmail object from a text code.
:param str email: Email address.
:param str result_text_code: A result of verification represented by text (e.g. valid, unknown).
:return: An instance of object. | [
"Alternative",
"method",
"to",
"create",
"an",
"instance",
"of",
"VerifiedEmail",
"object",
"from",
"a",
"text",
"code",
".",
":",
"param",
"str",
"email",
":",
"Email",
"address",
".",
":",
"param",
"str",
"result_text_code",
":",
"A",
"result",
"of",
"ve... | train | https://github.com/martinkosir/neverbounce-python/blob/8d8b3f381dbff2a753a8770fac0d2bfab80d5bec/neverbounce/objects.py#L19-L27 |
Aluriak/ACCC | accc/pycompiler/pycompiler.py | PyCompiler.compile | def compile(self, source_code, post_treatment=''.join, source='<string>', target='exec'):
"""Return ready-to-exec object code of compilation.
Use python built-in compile function.
Use exec(1) on returned object for execute it."""
self.last_python_code = super().compile(source_code, post_treatment)
return PyCompiler.executable(self.last_python_code, source, target) | python | def compile(self, source_code, post_treatment=''.join, source='<string>', target='exec'):
"""Return ready-to-exec object code of compilation.
Use python built-in compile function.
Use exec(1) on returned object for execute it."""
self.last_python_code = super().compile(source_code, post_treatment)
return PyCompiler.executable(self.last_python_code, source, target) | [
"def",
"compile",
"(",
"self",
",",
"source_code",
",",
"post_treatment",
"=",
"''",
".",
"join",
",",
"source",
"=",
"'<string>'",
",",
"target",
"=",
"'exec'",
")",
":",
"self",
".",
"last_python_code",
"=",
"super",
"(",
")",
".",
"compile",
"(",
"s... | Return ready-to-exec object code of compilation.
Use python built-in compile function.
Use exec(1) on returned object for execute it. | [
"Return",
"ready",
"-",
"to",
"-",
"exec",
"object",
"code",
"of",
"compilation",
".",
"Use",
"python",
"built",
"-",
"in",
"compile",
"function",
".",
"Use",
"exec",
"(",
"1",
")",
"on",
"returned",
"object",
"for",
"execute",
"it",
"."
] | train | https://github.com/Aluriak/ACCC/blob/9092f985bef7ed784264c86bc19c980f4ce2309f/accc/pycompiler/pycompiler.py#L38-L43 |
hangyan/shaw | shaw/decorator/retries.py | example_exc_handler | def example_exc_handler(tries_remaining, exception, delay):
"""Example exception handler; prints a warning to stderr.
tries_remaining: The number of tries remaining.
exception: The exception instance which was raised.
"""
print >> sys.stderr, "Caught '%s', %d tries remaining, sleeping for %s seconds" % (
exception, tries_remaining, delay) | python | def example_exc_handler(tries_remaining, exception, delay):
"""Example exception handler; prints a warning to stderr.
tries_remaining: The number of tries remaining.
exception: The exception instance which was raised.
"""
print >> sys.stderr, "Caught '%s', %d tries remaining, sleeping for %s seconds" % (
exception, tries_remaining, delay) | [
"def",
"example_exc_handler",
"(",
"tries_remaining",
",",
"exception",
",",
"delay",
")",
":",
"print",
">>",
"sys",
".",
"stderr",
",",
"\"Caught '%s', %d tries remaining, sleeping for %s seconds\"",
"%",
"(",
"exception",
",",
"tries_remaining",
",",
"delay",
")"
] | Example exception handler; prints a warning to stderr.
tries_remaining: The number of tries remaining.
exception: The exception instance which was raised. | [
"Example",
"exception",
"handler",
";",
"prints",
"a",
"warning",
"to",
"stderr",
"."
] | train | https://github.com/hangyan/shaw/blob/63d01d35e225ba4edb9c61edaf351e1bc0e8fd15/shaw/decorator/retries.py#L28-L35 |
etcher-be/epab | epab/utils/_av.py | AV.set_env_var | def set_env_var(key: str, value: str):
"""
Sets environment variable on AV
Args:
key: variable name
value: variable value
"""
elib_run.run(f'appveyor SetVariable -Name {key} -Value {value}')
AV.info('Env', f'set "{key}" -> "{value}"') | python | def set_env_var(key: str, value: str):
"""
Sets environment variable on AV
Args:
key: variable name
value: variable value
"""
elib_run.run(f'appveyor SetVariable -Name {key} -Value {value}')
AV.info('Env', f'set "{key}" -> "{value}"') | [
"def",
"set_env_var",
"(",
"key",
":",
"str",
",",
"value",
":",
"str",
")",
":",
"elib_run",
".",
"run",
"(",
"f'appveyor SetVariable -Name {key} -Value {value}'",
")",
"AV",
".",
"info",
"(",
"'Env'",
",",
"f'set \"{key}\" -> \"{value}\"'",
")"
] | Sets environment variable on AV
Args:
key: variable name
value: variable value | [
"Sets",
"environment",
"variable",
"on",
"AV"
] | train | https://github.com/etcher-be/epab/blob/024cde74d058281aa66e6e4b7b71dccbe803b1c1/epab/utils/_av.py#L57-L66 |
bitesofcode/xqt | xqt/wrappers/pyqt4.py | init | def init(scope):
"""
Initialize the xqt system with the PyQt4 wrapper for the Qt system.
:param scope | <dict>
"""
# update globals
scope['py2q'] = py2q
scope['q2py'] = q2py
# define wrapper compatibility symbols
QtCore.THREADSAFE_NONE = None
# define the importable symbols
scope['QtCore'] = QtCore
scope['QtGui'] = lazy_import('PyQt4.QtGui')
scope['QtWebKit'] = lazy_import('PyQt4.QtWebKit')
scope['QtNetwork'] = lazy_import('PyQt4.QtNetwork')
scope['QtXml'] = lazy_import('PyQt4.QtXml')
# PyQt4 specific modules
scope['QtDesigner'] = lazy_import('PyQt4.QtDesigner')
scope['Qsci'] = lazy_import('PyQt4.Qsci')
scope['uic'] = lazy_import('PyQt4.uic')
scope['rcc_exe'] = 'pyrcc4'
# map shared core properties
QtCore.QDate.toPython = lambda x: x.toPyDate()
QtCore.QDateTime.toPython = lambda x: x.toPyDateTime()
QtCore.QTime.toPython = lambda x: x.toPyTime()
QtCore.Signal = Signal
QtCore.Slot = Slot
QtCore.Property = QtCore.pyqtProperty
QtCore.SIGNAL = SIGNAL
QtCore.__version__ = QtCore.QT_VERSION_STR
if SIP_VERSION == '2':
QtCore.QStringList = list
QtCore.QString = unicode | python | def init(scope):
"""
Initialize the xqt system with the PyQt4 wrapper for the Qt system.
:param scope | <dict>
"""
# update globals
scope['py2q'] = py2q
scope['q2py'] = q2py
# define wrapper compatibility symbols
QtCore.THREADSAFE_NONE = None
# define the importable symbols
scope['QtCore'] = QtCore
scope['QtGui'] = lazy_import('PyQt4.QtGui')
scope['QtWebKit'] = lazy_import('PyQt4.QtWebKit')
scope['QtNetwork'] = lazy_import('PyQt4.QtNetwork')
scope['QtXml'] = lazy_import('PyQt4.QtXml')
# PyQt4 specific modules
scope['QtDesigner'] = lazy_import('PyQt4.QtDesigner')
scope['Qsci'] = lazy_import('PyQt4.Qsci')
scope['uic'] = lazy_import('PyQt4.uic')
scope['rcc_exe'] = 'pyrcc4'
# map shared core properties
QtCore.QDate.toPython = lambda x: x.toPyDate()
QtCore.QDateTime.toPython = lambda x: x.toPyDateTime()
QtCore.QTime.toPython = lambda x: x.toPyTime()
QtCore.Signal = Signal
QtCore.Slot = Slot
QtCore.Property = QtCore.pyqtProperty
QtCore.SIGNAL = SIGNAL
QtCore.__version__ = QtCore.QT_VERSION_STR
if SIP_VERSION == '2':
QtCore.QStringList = list
QtCore.QString = unicode | [
"def",
"init",
"(",
"scope",
")",
":",
"# update globals\r",
"scope",
"[",
"'py2q'",
"]",
"=",
"py2q",
"scope",
"[",
"'q2py'",
"]",
"=",
"q2py",
"# define wrapper compatibility symbols\r",
"QtCore",
".",
"THREADSAFE_NONE",
"=",
"None",
"# define the importable symbo... | Initialize the xqt system with the PyQt4 wrapper for the Qt system.
:param scope | <dict> | [
"Initialize",
"the",
"xqt",
"system",
"with",
"the",
"PyQt4",
"wrapper",
"for",
"the",
"Qt",
"system",
".",
":",
"param",
"scope",
"|",
"<dict",
">"
] | train | https://github.com/bitesofcode/xqt/blob/befa649a2f2104a20d49c8c78ffdba5907fd94d2/xqt/wrappers/pyqt4.py#L107-L147 |
benley/butcher | butcher/buildfile.py | BuildFile.validate_internal_deps | def validate_internal_deps(self):
"""Freak out if there are missing local references."""
for node in self.node:
if ('target_obj' not in self.node[node]
and node not in self.crossrefs):
raise error.BrokenGraph('Missing target: %s referenced from %s'
' but not defined there.' %
(node, self.name)) | python | def validate_internal_deps(self):
"""Freak out if there are missing local references."""
for node in self.node:
if ('target_obj' not in self.node[node]
and node not in self.crossrefs):
raise error.BrokenGraph('Missing target: %s referenced from %s'
' but not defined there.' %
(node, self.name)) | [
"def",
"validate_internal_deps",
"(",
"self",
")",
":",
"for",
"node",
"in",
"self",
".",
"node",
":",
"if",
"(",
"'target_obj'",
"not",
"in",
"self",
".",
"node",
"[",
"node",
"]",
"and",
"node",
"not",
"in",
"self",
".",
"crossrefs",
")",
":",
"rai... | Freak out if there are missing local references. | [
"Freak",
"out",
"if",
"there",
"are",
"missing",
"local",
"references",
"."
] | train | https://github.com/benley/butcher/blob/8b18828ea040af56b7835beab5fd03eab23cc9ee/butcher/buildfile.py#L96-L103 |
benley/butcher | butcher/buildfile.py | BuildFile.crossrefs | def crossrefs(self):
"""Returns a set of non-local targets referenced by this build file."""
# TODO: memoize this?
crefs = set()
for node in self.node:
if node.repo != self.target.repo or node.path != self.target.path:
crefs.add(node)
return crefs | python | def crossrefs(self):
"""Returns a set of non-local targets referenced by this build file."""
# TODO: memoize this?
crefs = set()
for node in self.node:
if node.repo != self.target.repo or node.path != self.target.path:
crefs.add(node)
return crefs | [
"def",
"crossrefs",
"(",
"self",
")",
":",
"# TODO: memoize this?",
"crefs",
"=",
"set",
"(",
")",
"for",
"node",
"in",
"self",
".",
"node",
":",
"if",
"node",
".",
"repo",
"!=",
"self",
".",
"target",
".",
"repo",
"or",
"node",
".",
"path",
"!=",
... | Returns a set of non-local targets referenced by this build file. | [
"Returns",
"a",
"set",
"of",
"non",
"-",
"local",
"targets",
"referenced",
"by",
"this",
"build",
"file",
"."
] | train | https://github.com/benley/butcher/blob/8b18828ea040af56b7835beab5fd03eab23cc9ee/butcher/buildfile.py#L106-L113 |
benley/butcher | butcher/buildfile.py | BuildFile.crossref_paths | def crossref_paths(self):
"""Just like crossrefs, but all the targets are munged to :all."""
return set(
[address.new(repo=x.repo, path=x.path) for x in self.crossrefs]) | python | def crossref_paths(self):
"""Just like crossrefs, but all the targets are munged to :all."""
return set(
[address.new(repo=x.repo, path=x.path) for x in self.crossrefs]) | [
"def",
"crossref_paths",
"(",
"self",
")",
":",
"return",
"set",
"(",
"[",
"address",
".",
"new",
"(",
"repo",
"=",
"x",
".",
"repo",
",",
"path",
"=",
"x",
".",
"path",
")",
"for",
"x",
"in",
"self",
".",
"crossrefs",
"]",
")"
] | Just like crossrefs, but all the targets are munged to :all. | [
"Just",
"like",
"crossrefs",
"but",
"all",
"the",
"targets",
"are",
"munged",
"to",
":",
"all",
"."
] | train | https://github.com/benley/butcher/blob/8b18828ea040af56b7835beab5fd03eab23cc9ee/butcher/buildfile.py#L116-L119 |
benley/butcher | butcher/buildfile.py | BuildFile.local_targets | def local_targets(self):
"""Iterator over the targets defined in this build file."""
for node in self.node:
if (node.repo, node.path) == (self.target.repo, self.target.path):
yield node | python | def local_targets(self):
"""Iterator over the targets defined in this build file."""
for node in self.node:
if (node.repo, node.path) == (self.target.repo, self.target.path):
yield node | [
"def",
"local_targets",
"(",
"self",
")",
":",
"for",
"node",
"in",
"self",
".",
"node",
":",
"if",
"(",
"node",
".",
"repo",
",",
"node",
".",
"path",
")",
"==",
"(",
"self",
".",
"target",
".",
"repo",
",",
"self",
".",
"target",
".",
"path",
... | Iterator over the targets defined in this build file. | [
"Iterator",
"over",
"the",
"targets",
"defined",
"in",
"this",
"build",
"file",
"."
] | train | https://github.com/benley/butcher/blob/8b18828ea040af56b7835beab5fd03eab23cc9ee/butcher/buildfile.py#L122-L126 |
benley/butcher | butcher/buildfile.py | JsonBuildFile._parse | def _parse(self, stream):
"""Parse a JSON BUILD file.
Args:
builddata: dictionary of buildfile data
reponame: name of the repo that it came from
path: directory path within the repo
"""
builddata = json.load(stream)
log.debug('This is a JSON build file.')
if 'targets' not in builddata:
log.warn('Warning: No targets defined here.')
return
for tdata in builddata['targets']:
# TODO: validate name
target = address.new(target=tdata.pop('name'),
repo=self.target.repo,
path=self.target.path)
# Duplicate target definition? Uh oh.
if target in self.node and 'target_obj' in self.node[target]:
raise error.ButcherError(
'Target is defined more than once: %s', target)
rule_obj = targets.new(name=target,
ruletype=tdata.pop('type'),
**tdata)
log.debug('New target: %s', target)
self.add_node(target, {'target_obj': rule_obj})
# dep could be ":blabla" or "//foo:blabla" or "//foo/bar:blabla"
for dep in rule_obj.composed_deps() or []:
d_target = address.new(dep)
if not d_target.repo: # ":blabla"
d_target.repo = self.target.repo
if d_target.repo == self.target.repo and not d_target.path:
d_target.path = self.target.path
if d_target not in self.nodes():
self.add_node(d_target)
log.debug('New dep: %s -> %s', target, d_target)
self.add_edge(target, d_target) | python | def _parse(self, stream):
"""Parse a JSON BUILD file.
Args:
builddata: dictionary of buildfile data
reponame: name of the repo that it came from
path: directory path within the repo
"""
builddata = json.load(stream)
log.debug('This is a JSON build file.')
if 'targets' not in builddata:
log.warn('Warning: No targets defined here.')
return
for tdata in builddata['targets']:
# TODO: validate name
target = address.new(target=tdata.pop('name'),
repo=self.target.repo,
path=self.target.path)
# Duplicate target definition? Uh oh.
if target in self.node and 'target_obj' in self.node[target]:
raise error.ButcherError(
'Target is defined more than once: %s', target)
rule_obj = targets.new(name=target,
ruletype=tdata.pop('type'),
**tdata)
log.debug('New target: %s', target)
self.add_node(target, {'target_obj': rule_obj})
# dep could be ":blabla" or "//foo:blabla" or "//foo/bar:blabla"
for dep in rule_obj.composed_deps() or []:
d_target = address.new(dep)
if not d_target.repo: # ":blabla"
d_target.repo = self.target.repo
if d_target.repo == self.target.repo and not d_target.path:
d_target.path = self.target.path
if d_target not in self.nodes():
self.add_node(d_target)
log.debug('New dep: %s -> %s', target, d_target)
self.add_edge(target, d_target) | [
"def",
"_parse",
"(",
"self",
",",
"stream",
")",
":",
"builddata",
"=",
"json",
".",
"load",
"(",
"stream",
")",
"log",
".",
"debug",
"(",
"'This is a JSON build file.'",
")",
"if",
"'targets'",
"not",
"in",
"builddata",
":",
"log",
".",
"warn",
"(",
... | Parse a JSON BUILD file.
Args:
builddata: dictionary of buildfile data
reponame: name of the repo that it came from
path: directory path within the repo | [
"Parse",
"a",
"JSON",
"BUILD",
"file",
"."
] | train | https://github.com/benley/butcher/blob/8b18828ea040af56b7835beab5fd03eab23cc9ee/butcher/buildfile.py#L135-L177 |
harlowja/failure | failure/failure.py | WrappedFailure.check | def check(self, *exc_classes):
"""Check if any of exception classes caused the failure/s.
:param exc_classes: exception types/exception type names to
search for.
If any of the contained failures were caused by an exception of a
given type, the corresponding argument that matched is returned. If
not then ``None`` is returned.
"""
if not exc_classes:
return None
for cause in self:
result = cause.check(*exc_classes)
if result is not None:
return result
return None | python | def check(self, *exc_classes):
"""Check if any of exception classes caused the failure/s.
:param exc_classes: exception types/exception type names to
search for.
If any of the contained failures were caused by an exception of a
given type, the corresponding argument that matched is returned. If
not then ``None`` is returned.
"""
if not exc_classes:
return None
for cause in self:
result = cause.check(*exc_classes)
if result is not None:
return result
return None | [
"def",
"check",
"(",
"self",
",",
"*",
"exc_classes",
")",
":",
"if",
"not",
"exc_classes",
":",
"return",
"None",
"for",
"cause",
"in",
"self",
":",
"result",
"=",
"cause",
".",
"check",
"(",
"*",
"exc_classes",
")",
"if",
"result",
"is",
"not",
"No... | Check if any of exception classes caused the failure/s.
:param exc_classes: exception types/exception type names to
search for.
If any of the contained failures were caused by an exception of a
given type, the corresponding argument that matched is returned. If
not then ``None`` is returned. | [
"Check",
"if",
"any",
"of",
"exception",
"classes",
"caused",
"the",
"failure",
"/",
"s",
"."
] | train | https://github.com/harlowja/failure/blob/9ea9a46ebb26c6d7da2553c80e36892f3997bd6f/failure/failure.py#L77-L93 |
harlowja/failure | failure/failure.py | Failure.from_exc_info | def from_exc_info(cls, exc_info=None,
retain_exc_info=True,
cause=None, find_cause=True):
"""Creates a failure object from a ``sys.exc_info()`` tuple."""
if exc_info is None:
exc_info = sys.exc_info()
if not any(exc_info):
raise NoActiveException("No exception currently"
" being handled")
# This should always be the (type, value, traceback) tuple,
# either from a prior sys.exc_info() call or from some other
# creation...
if len(exc_info) != 3:
raise ValueError("Provided 'exc_info' must contain three"
" elements")
exc_type, exc_val, exc_tb = exc_info
try:
if exc_type is None or exc_val is None:
raise ValueError("Invalid exception tuple (exception"
" type and exception value must"
" be provided)")
exc_args = tuple(getattr(exc_val, 'args', []))
exc_kwargs = dict(getattr(exc_val, 'kwargs', {}))
exc_type_names = utils.extract_roots(exc_type)
if not exc_type_names:
exc_type_name = reflection.get_class_name(
exc_val, truncate_builtins=False)
# This should only be possible if the exception provided
# was not really an exception...
raise TypeError("Invalid exception type '%s' (not an"
" exception)" % (exc_type_name))
exception_str = utils.exception_message(exc_val)
if hasattr(exc_val, '__traceback_str__'):
traceback_str = exc_val.__traceback_str__
else:
if exc_tb is not None:
traceback_str = '\n'.join(
traceback.format_exception(*exc_info))
else:
traceback_str = ''
if not retain_exc_info:
exc_info = None
if find_cause and cause is None:
cause = cls._extract_cause(exc_val)
return cls(exc_info=exc_info, exc_args=exc_args,
exc_kwargs=exc_kwargs, exception_str=exception_str,
exc_type_names=exc_type_names, cause=cause,
traceback_str=traceback_str,
generated_on=sys.version_info[0:2])
finally:
del exc_type, exc_val, exc_tb | python | def from_exc_info(cls, exc_info=None,
retain_exc_info=True,
cause=None, find_cause=True):
"""Creates a failure object from a ``sys.exc_info()`` tuple."""
if exc_info is None:
exc_info = sys.exc_info()
if not any(exc_info):
raise NoActiveException("No exception currently"
" being handled")
# This should always be the (type, value, traceback) tuple,
# either from a prior sys.exc_info() call or from some other
# creation...
if len(exc_info) != 3:
raise ValueError("Provided 'exc_info' must contain three"
" elements")
exc_type, exc_val, exc_tb = exc_info
try:
if exc_type is None or exc_val is None:
raise ValueError("Invalid exception tuple (exception"
" type and exception value must"
" be provided)")
exc_args = tuple(getattr(exc_val, 'args', []))
exc_kwargs = dict(getattr(exc_val, 'kwargs', {}))
exc_type_names = utils.extract_roots(exc_type)
if not exc_type_names:
exc_type_name = reflection.get_class_name(
exc_val, truncate_builtins=False)
# This should only be possible if the exception provided
# was not really an exception...
raise TypeError("Invalid exception type '%s' (not an"
" exception)" % (exc_type_name))
exception_str = utils.exception_message(exc_val)
if hasattr(exc_val, '__traceback_str__'):
traceback_str = exc_val.__traceback_str__
else:
if exc_tb is not None:
traceback_str = '\n'.join(
traceback.format_exception(*exc_info))
else:
traceback_str = ''
if not retain_exc_info:
exc_info = None
if find_cause and cause is None:
cause = cls._extract_cause(exc_val)
return cls(exc_info=exc_info, exc_args=exc_args,
exc_kwargs=exc_kwargs, exception_str=exception_str,
exc_type_names=exc_type_names, cause=cause,
traceback_str=traceback_str,
generated_on=sys.version_info[0:2])
finally:
del exc_type, exc_val, exc_tb | [
"def",
"from_exc_info",
"(",
"cls",
",",
"exc_info",
"=",
"None",
",",
"retain_exc_info",
"=",
"True",
",",
"cause",
"=",
"None",
",",
"find_cause",
"=",
"True",
")",
":",
"if",
"exc_info",
"is",
"None",
":",
"exc_info",
"=",
"sys",
".",
"exc_info",
"(... | Creates a failure object from a ``sys.exc_info()`` tuple. | [
"Creates",
"a",
"failure",
"object",
"from",
"a",
"sys",
".",
"exc_info",
"()",
"tuple",
"."
] | train | https://github.com/harlowja/failure/blob/9ea9a46ebb26c6d7da2553c80e36892f3997bd6f/failure/failure.py#L241-L291 |
harlowja/failure | failure/failure.py | Failure.from_exception | def from_exception(cls, exception, retain_exc_info=True,
cause=None, find_cause=True):
"""Creates a failure object from a exception instance."""
exc_info = (
type(exception),
exception,
getattr(exception, '__traceback__', None)
)
return cls.from_exc_info(exc_info=exc_info,
retain_exc_info=retain_exc_info,
cause=cause, find_cause=find_cause) | python | def from_exception(cls, exception, retain_exc_info=True,
cause=None, find_cause=True):
"""Creates a failure object from a exception instance."""
exc_info = (
type(exception),
exception,
getattr(exception, '__traceback__', None)
)
return cls.from_exc_info(exc_info=exc_info,
retain_exc_info=retain_exc_info,
cause=cause, find_cause=find_cause) | [
"def",
"from_exception",
"(",
"cls",
",",
"exception",
",",
"retain_exc_info",
"=",
"True",
",",
"cause",
"=",
"None",
",",
"find_cause",
"=",
"True",
")",
":",
"exc_info",
"=",
"(",
"type",
"(",
"exception",
")",
",",
"exception",
",",
"getattr",
"(",
... | Creates a failure object from a exception instance. | [
"Creates",
"a",
"failure",
"object",
"from",
"a",
"exception",
"instance",
"."
] | train | https://github.com/harlowja/failure/blob/9ea9a46ebb26c6d7da2553c80e36892f3997bd6f/failure/failure.py#L294-L304 |
harlowja/failure | failure/failure.py | Failure.validate | def validate(cls, data):
"""Validate input data matches expected failure ``dict`` format."""
try:
jsonschema.validate(
data, cls.SCHEMA,
# See: https://github.com/Julian/jsonschema/issues/148
types={'array': (list, tuple)})
except jsonschema.ValidationError as e:
raise InvalidFormat("Failure data not of the"
" expected format: %s" % (e.message))
else:
# Ensure that all 'exc_type_names' originate from one of
# base exceptions, because those are the root exceptions that
# python mandates/provides and anything else is invalid...
causes = collections.deque([data])
while causes:
cause = causes.popleft()
try:
generated_on = cause['generated_on']
ok_bases = cls.BASE_EXCEPTIONS[generated_on[0]]
except (KeyError, IndexError):
ok_bases = []
root_exc_type = cause['exc_type_names'][-1]
if root_exc_type not in ok_bases:
raise InvalidFormat(
"Failure data 'exc_type_names' must"
" have an initial exception type that is one"
" of %s types: '%s' is not one of those"
" types" % (ok_bases, root_exc_type))
sub_cause = cause.get('cause')
if sub_cause is not None:
causes.append(sub_cause) | python | def validate(cls, data):
"""Validate input data matches expected failure ``dict`` format."""
try:
jsonschema.validate(
data, cls.SCHEMA,
# See: https://github.com/Julian/jsonschema/issues/148
types={'array': (list, tuple)})
except jsonschema.ValidationError as e:
raise InvalidFormat("Failure data not of the"
" expected format: %s" % (e.message))
else:
# Ensure that all 'exc_type_names' originate from one of
# base exceptions, because those are the root exceptions that
# python mandates/provides and anything else is invalid...
causes = collections.deque([data])
while causes:
cause = causes.popleft()
try:
generated_on = cause['generated_on']
ok_bases = cls.BASE_EXCEPTIONS[generated_on[0]]
except (KeyError, IndexError):
ok_bases = []
root_exc_type = cause['exc_type_names'][-1]
if root_exc_type not in ok_bases:
raise InvalidFormat(
"Failure data 'exc_type_names' must"
" have an initial exception type that is one"
" of %s types: '%s' is not one of those"
" types" % (ok_bases, root_exc_type))
sub_cause = cause.get('cause')
if sub_cause is not None:
causes.append(sub_cause) | [
"def",
"validate",
"(",
"cls",
",",
"data",
")",
":",
"try",
":",
"jsonschema",
".",
"validate",
"(",
"data",
",",
"cls",
".",
"SCHEMA",
",",
"# See: https://github.com/Julian/jsonschema/issues/148",
"types",
"=",
"{",
"'array'",
":",
"(",
"list",
",",
"tupl... | Validate input data matches expected failure ``dict`` format. | [
"Validate",
"input",
"data",
"matches",
"expected",
"failure",
"dict",
"format",
"."
] | train | https://github.com/harlowja/failure/blob/9ea9a46ebb26c6d7da2553c80e36892f3997bd6f/failure/failure.py#L307-L338 |
harlowja/failure | failure/failure.py | Failure.matches | def matches(self, other):
"""Checks if another object is equivalent to this object.
:returns: checks if another object is equivalent to this object
:rtype: boolean
"""
if not isinstance(other, Failure):
return False
if self.exc_info is None or other.exc_info is None:
return self._matches(other)
else:
return self == other | python | def matches(self, other):
"""Checks if another object is equivalent to this object.
:returns: checks if another object is equivalent to this object
:rtype: boolean
"""
if not isinstance(other, Failure):
return False
if self.exc_info is None or other.exc_info is None:
return self._matches(other)
else:
return self == other | [
"def",
"matches",
"(",
"self",
",",
"other",
")",
":",
"if",
"not",
"isinstance",
"(",
"other",
",",
"Failure",
")",
":",
"return",
"False",
"if",
"self",
".",
"exc_info",
"is",
"None",
"or",
"other",
".",
"exc_info",
"is",
"None",
":",
"return",
"se... | Checks if another object is equivalent to this object.
:returns: checks if another object is equivalent to this object
:rtype: boolean | [
"Checks",
"if",
"another",
"object",
"is",
"equivalent",
"to",
"this",
"object",
"."
] | train | https://github.com/harlowja/failure/blob/9ea9a46ebb26c6d7da2553c80e36892f3997bd6f/failure/failure.py#L351-L362 |
harlowja/failure | failure/failure.py | Failure.reraise_if_any | def reraise_if_any(failures, cause_cls_finder=None):
"""Re-raise exceptions if argument is not empty.
If argument is empty list/tuple/iterator, this method returns
None. If argument is converted into a list with a
single ``Failure`` object in it, that failure is reraised. Else, a
:class:`~.WrappedFailure` exception is raised with the failure
list as causes.
"""
if not isinstance(failures, (list, tuple)):
# Convert generators/other into a list...
failures = list(failures)
if len(failures) == 1:
failures[0].reraise(cause_cls_finder=cause_cls_finder)
elif len(failures) > 1:
raise WrappedFailure(failures) | python | def reraise_if_any(failures, cause_cls_finder=None):
"""Re-raise exceptions if argument is not empty.
If argument is empty list/tuple/iterator, this method returns
None. If argument is converted into a list with a
single ``Failure`` object in it, that failure is reraised. Else, a
:class:`~.WrappedFailure` exception is raised with the failure
list as causes.
"""
if not isinstance(failures, (list, tuple)):
# Convert generators/other into a list...
failures = list(failures)
if len(failures) == 1:
failures[0].reraise(cause_cls_finder=cause_cls_finder)
elif len(failures) > 1:
raise WrappedFailure(failures) | [
"def",
"reraise_if_any",
"(",
"failures",
",",
"cause_cls_finder",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"failures",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"# Convert generators/other into a list...",
"failures",
"=",
"list",
"(",
"fai... | Re-raise exceptions if argument is not empty.
If argument is empty list/tuple/iterator, this method returns
None. If argument is converted into a list with a
single ``Failure`` object in it, that failure is reraised. Else, a
:class:`~.WrappedFailure` exception is raised with the failure
list as causes. | [
"Re",
"-",
"raise",
"exceptions",
"if",
"argument",
"is",
"not",
"empty",
"."
] | train | https://github.com/harlowja/failure/blob/9ea9a46ebb26c6d7da2553c80e36892f3997bd6f/failure/failure.py#L436-L451 |
harlowja/failure | failure/failure.py | Failure.reraise | def reraise(self, cause_cls_finder=None):
"""Re-raise captured exception (possibly trying to recreate)."""
if self._exc_info:
six.reraise(*self._exc_info)
else:
# Attempt to regenerate the full chain (and then raise
# from the root); without a traceback, oh well...
root = None
parent = None
for cause in itertools.chain([self], self.iter_causes()):
if cause_cls_finder is not None:
cause_cls = cause_cls_finder(cause)
else:
cause_cls = None
if cause_cls is None:
# Unable to find where this cause came from, give up...
raise WrappedFailure([self])
exc = cause_cls(
*cause.exception_args, **cause.exception_kwargs)
# Saving this will ensure that if this same exception
# is serialized again that we will extract the traceback
# from it directly (thus proxying along the original
# traceback as much as we can).
exc.__traceback_str__ = cause.traceback_str
if root is None:
root = exc
if parent is not None:
parent.__cause__ = exc
parent = exc
six.reraise(type(root), root, tb=None) | python | def reraise(self, cause_cls_finder=None):
"""Re-raise captured exception (possibly trying to recreate)."""
if self._exc_info:
six.reraise(*self._exc_info)
else:
# Attempt to regenerate the full chain (and then raise
# from the root); without a traceback, oh well...
root = None
parent = None
for cause in itertools.chain([self], self.iter_causes()):
if cause_cls_finder is not None:
cause_cls = cause_cls_finder(cause)
else:
cause_cls = None
if cause_cls is None:
# Unable to find where this cause came from, give up...
raise WrappedFailure([self])
exc = cause_cls(
*cause.exception_args, **cause.exception_kwargs)
# Saving this will ensure that if this same exception
# is serialized again that we will extract the traceback
# from it directly (thus proxying along the original
# traceback as much as we can).
exc.__traceback_str__ = cause.traceback_str
if root is None:
root = exc
if parent is not None:
parent.__cause__ = exc
parent = exc
six.reraise(type(root), root, tb=None) | [
"def",
"reraise",
"(",
"self",
",",
"cause_cls_finder",
"=",
"None",
")",
":",
"if",
"self",
".",
"_exc_info",
":",
"six",
".",
"reraise",
"(",
"*",
"self",
".",
"_exc_info",
")",
"else",
":",
"# Attempt to regenerate the full chain (and then raise",
"# from the... | Re-raise captured exception (possibly trying to recreate). | [
"Re",
"-",
"raise",
"captured",
"exception",
"(",
"possibly",
"trying",
"to",
"recreate",
")",
"."
] | train | https://github.com/harlowja/failure/blob/9ea9a46ebb26c6d7da2553c80e36892f3997bd6f/failure/failure.py#L453-L482 |
harlowja/failure | failure/failure.py | Failure.check | def check(self, *exc_classes):
"""Check if any of ``exc_classes`` caused the failure.
Arguments of this method can be exception types or type
names (strings **fully qualified**). If captured exception is
an instance of exception of given type, the corresponding argument
is returned, otherwise ``None`` is returned.
"""
for cls in exc_classes:
cls_name = utils.cls_to_cls_name(cls)
if cls_name in self._exc_type_names:
return cls
return None | python | def check(self, *exc_classes):
"""Check if any of ``exc_classes`` caused the failure.
Arguments of this method can be exception types or type
names (strings **fully qualified**). If captured exception is
an instance of exception of given type, the corresponding argument
is returned, otherwise ``None`` is returned.
"""
for cls in exc_classes:
cls_name = utils.cls_to_cls_name(cls)
if cls_name in self._exc_type_names:
return cls
return None | [
"def",
"check",
"(",
"self",
",",
"*",
"exc_classes",
")",
":",
"for",
"cls",
"in",
"exc_classes",
":",
"cls_name",
"=",
"utils",
".",
"cls_to_cls_name",
"(",
"cls",
")",
"if",
"cls_name",
"in",
"self",
".",
"_exc_type_names",
":",
"return",
"cls",
"retu... | Check if any of ``exc_classes`` caused the failure.
Arguments of this method can be exception types or type
names (strings **fully qualified**). If captured exception is
an instance of exception of given type, the corresponding argument
is returned, otherwise ``None`` is returned. | [
"Check",
"if",
"any",
"of",
"exc_classes",
"caused",
"the",
"failure",
"."
] | train | https://github.com/harlowja/failure/blob/9ea9a46ebb26c6d7da2553c80e36892f3997bd6f/failure/failure.py#L484-L496 |
harlowja/failure | failure/failure.py | Failure.pformat | def pformat(self, traceback=False):
"""Pretty formats the failure object into a string."""
buf = six.StringIO()
if not self._exc_type_names:
buf.write('Failure: %s' % (self._exception_str))
else:
buf.write('Failure: %s: %s' % (self._exc_type_names[0],
self._exception_str))
if traceback:
if self._traceback_str is not None:
traceback_str = self._traceback_str.rstrip()
else:
traceback_str = None
if traceback_str:
buf.write(os.linesep)
buf.write(traceback_str)
else:
buf.write(os.linesep)
buf.write('Traceback not available.')
return buf.getvalue() | python | def pformat(self, traceback=False):
"""Pretty formats the failure object into a string."""
buf = six.StringIO()
if not self._exc_type_names:
buf.write('Failure: %s' % (self._exception_str))
else:
buf.write('Failure: %s: %s' % (self._exc_type_names[0],
self._exception_str))
if traceback:
if self._traceback_str is not None:
traceback_str = self._traceback_str.rstrip()
else:
traceback_str = None
if traceback_str:
buf.write(os.linesep)
buf.write(traceback_str)
else:
buf.write(os.linesep)
buf.write('Traceback not available.')
return buf.getvalue() | [
"def",
"pformat",
"(",
"self",
",",
"traceback",
"=",
"False",
")",
":",
"buf",
"=",
"six",
".",
"StringIO",
"(",
")",
"if",
"not",
"self",
".",
"_exc_type_names",
":",
"buf",
".",
"write",
"(",
"'Failure: %s'",
"%",
"(",
"self",
".",
"_exception_str",... | Pretty formats the failure object into a string. | [
"Pretty",
"formats",
"the",
"failure",
"object",
"into",
"a",
"string",
"."
] | train | https://github.com/harlowja/failure/blob/9ea9a46ebb26c6d7da2553c80e36892f3997bd6f/failure/failure.py#L513-L532 |
harlowja/failure | failure/failure.py | Failure.iter_causes | def iter_causes(self):
"""Iterate over all causes."""
curr = self._cause
while curr is not None:
yield curr
curr = curr._cause | python | def iter_causes(self):
"""Iterate over all causes."""
curr = self._cause
while curr is not None:
yield curr
curr = curr._cause | [
"def",
"iter_causes",
"(",
"self",
")",
":",
"curr",
"=",
"self",
".",
"_cause",
"while",
"curr",
"is",
"not",
"None",
":",
"yield",
"curr",
"curr",
"=",
"curr",
".",
"_cause"
] | Iterate over all causes. | [
"Iterate",
"over",
"all",
"causes",
"."
] | train | https://github.com/harlowja/failure/blob/9ea9a46ebb26c6d7da2553c80e36892f3997bd6f/failure/failure.py#L534-L539 |
harlowja/failure | failure/failure.py | Failure._extract_cause | def _extract_cause(cls, exc_val):
"""Helper routine to extract nested cause (if any)."""
# See: https://www.python.org/dev/peps/pep-3134/ for why/what
# these are...
#
# '__cause__' attribute for explicitly chained exceptions
# '__context__' attribute for implicitly chained exceptions
# '__traceback__' attribute for the traceback
#
# See: https://www.python.org/dev/peps/pep-0415/ for why/what
# the '__suppress_context__' is/means/implies...
nested_exc_vals = []
seen = [exc_val]
while True:
suppress_context = getattr(
exc_val, '__suppress_context__', False)
if suppress_context:
attr_lookups = ['__cause__']
else:
attr_lookups = ['__cause__', '__context__']
nested_exc_val = None
for attr_name in attr_lookups:
attr_val = getattr(exc_val, attr_name, None)
if attr_val is None:
continue
nested_exc_val = attr_val
if nested_exc_val is None or nested_exc_val in seen:
break
seen.append(nested_exc_val)
nested_exc_vals.append(nested_exc_val)
exc_val = nested_exc_val
last_cause = None
for exc_val in reversed(nested_exc_vals):
f = cls.from_exception(exc_val, cause=last_cause,
find_cause=False)
last_cause = f
return last_cause | python | def _extract_cause(cls, exc_val):
"""Helper routine to extract nested cause (if any)."""
# See: https://www.python.org/dev/peps/pep-3134/ for why/what
# these are...
#
# '__cause__' attribute for explicitly chained exceptions
# '__context__' attribute for implicitly chained exceptions
# '__traceback__' attribute for the traceback
#
# See: https://www.python.org/dev/peps/pep-0415/ for why/what
# the '__suppress_context__' is/means/implies...
nested_exc_vals = []
seen = [exc_val]
while True:
suppress_context = getattr(
exc_val, '__suppress_context__', False)
if suppress_context:
attr_lookups = ['__cause__']
else:
attr_lookups = ['__cause__', '__context__']
nested_exc_val = None
for attr_name in attr_lookups:
attr_val = getattr(exc_val, attr_name, None)
if attr_val is None:
continue
nested_exc_val = attr_val
if nested_exc_val is None or nested_exc_val in seen:
break
seen.append(nested_exc_val)
nested_exc_vals.append(nested_exc_val)
exc_val = nested_exc_val
last_cause = None
for exc_val in reversed(nested_exc_vals):
f = cls.from_exception(exc_val, cause=last_cause,
find_cause=False)
last_cause = f
return last_cause | [
"def",
"_extract_cause",
"(",
"cls",
",",
"exc_val",
")",
":",
"# See: https://www.python.org/dev/peps/pep-3134/ for why/what",
"# these are...",
"#",
"# '__cause__' attribute for explicitly chained exceptions",
"# '__context__' attribute for implicitly chained exceptions",
"# '__traceback... | Helper routine to extract nested cause (if any). | [
"Helper",
"routine",
"to",
"extract",
"nested",
"cause",
"(",
"if",
"any",
")",
"."
] | train | https://github.com/harlowja/failure/blob/9ea9a46ebb26c6d7da2553c80e36892f3997bd6f/failure/failure.py#L584-L620 |
harlowja/failure | failure/failure.py | Failure.from_dict | def from_dict(cls, data):
"""Converts this from a dictionary to a object."""
data = dict(data)
cause = data.get('cause')
if cause is not None:
data['cause'] = cls.from_dict(cause)
return cls(**data) | python | def from_dict(cls, data):
"""Converts this from a dictionary to a object."""
data = dict(data)
cause = data.get('cause')
if cause is not None:
data['cause'] = cls.from_dict(cause)
return cls(**data) | [
"def",
"from_dict",
"(",
"cls",
",",
"data",
")",
":",
"data",
"=",
"dict",
"(",
"data",
")",
"cause",
"=",
"data",
".",
"get",
"(",
"'cause'",
")",
"if",
"cause",
"is",
"not",
"None",
":",
"data",
"[",
"'cause'",
"]",
"=",
"cls",
".",
"from_dict... | Converts this from a dictionary to a object. | [
"Converts",
"this",
"from",
"a",
"dictionary",
"to",
"a",
"object",
"."
] | train | https://github.com/harlowja/failure/blob/9ea9a46ebb26c6d7da2553c80e36892f3997bd6f/failure/failure.py#L623-L629 |
harlowja/failure | failure/failure.py | Failure.to_dict | def to_dict(self, include_args=True, include_kwargs=True):
"""Converts this object to a dictionary.
:param include_args: boolean indicating whether to include the
exception args in the output.
:param include_kwargs: boolean indicating whether to include the
exception kwargs in the output.
"""
data = {
'exception_str': self.exception_str,
'traceback_str': self.traceback_str,
'exc_type_names': self.exception_type_names,
'exc_args': self.exception_args if include_args else tuple(),
'exc_kwargs': self.exception_kwargs if include_kwargs else {},
'generated_on': self.generated_on,
}
if self._cause is not None:
data['cause'] = self._cause.to_dict(include_args=include_args,
include_kwargs=include_kwargs)
return data | python | def to_dict(self, include_args=True, include_kwargs=True):
"""Converts this object to a dictionary.
:param include_args: boolean indicating whether to include the
exception args in the output.
:param include_kwargs: boolean indicating whether to include the
exception kwargs in the output.
"""
data = {
'exception_str': self.exception_str,
'traceback_str': self.traceback_str,
'exc_type_names': self.exception_type_names,
'exc_args': self.exception_args if include_args else tuple(),
'exc_kwargs': self.exception_kwargs if include_kwargs else {},
'generated_on': self.generated_on,
}
if self._cause is not None:
data['cause'] = self._cause.to_dict(include_args=include_args,
include_kwargs=include_kwargs)
return data | [
"def",
"to_dict",
"(",
"self",
",",
"include_args",
"=",
"True",
",",
"include_kwargs",
"=",
"True",
")",
":",
"data",
"=",
"{",
"'exception_str'",
":",
"self",
".",
"exception_str",
",",
"'traceback_str'",
":",
"self",
".",
"traceback_str",
",",
"'exc_type_... | Converts this object to a dictionary.
:param include_args: boolean indicating whether to include the
exception args in the output.
:param include_kwargs: boolean indicating whether to include the
exception kwargs in the output. | [
"Converts",
"this",
"object",
"to",
"a",
"dictionary",
"."
] | train | https://github.com/harlowja/failure/blob/9ea9a46ebb26c6d7da2553c80e36892f3997bd6f/failure/failure.py#L631-L650 |
harlowja/failure | failure/failure.py | Failure.copy | def copy(self, deep=False):
"""Copies this object (shallow or deep).
:param deep: boolean indicating whether to do a deep copy (or a
shallow copy).
"""
cause = self._cause
if cause is not None:
cause = cause.copy(deep=deep)
exc_info = utils.copy_exc_info(self.exc_info, deep=deep)
exc_args = self.exception_args
exc_kwargs = self.exception_kwargs
if deep:
exc_args = copy.deepcopy(exc_args)
exc_kwargs = copy.deepcopy(exc_kwargs)
else:
exc_args = tuple(exc_args)
exc_kwargs = exc_kwargs.copy()
# These are just simple int/strings, so deep copy doesn't really
# matter/apply here (as they are immutable anyway).
exc_type_names = tuple(self._exc_type_names)
generated_on = self._generated_on
if generated_on:
generated_on = tuple(generated_on)
# NOTE(harlowja): use `self.__class__` here so that we can work
# with subclasses (assuming anyone makes one).
return self.__class__(exc_info=exc_info,
exception_str=self.exception_str,
traceback_str=self.traceback_str,
exc_args=exc_args,
exc_kwargs=exc_kwargs,
exc_type_names=exc_type_names,
cause=cause, generated_on=generated_on) | python | def copy(self, deep=False):
"""Copies this object (shallow or deep).
:param deep: boolean indicating whether to do a deep copy (or a
shallow copy).
"""
cause = self._cause
if cause is not None:
cause = cause.copy(deep=deep)
exc_info = utils.copy_exc_info(self.exc_info, deep=deep)
exc_args = self.exception_args
exc_kwargs = self.exception_kwargs
if deep:
exc_args = copy.deepcopy(exc_args)
exc_kwargs = copy.deepcopy(exc_kwargs)
else:
exc_args = tuple(exc_args)
exc_kwargs = exc_kwargs.copy()
# These are just simple int/strings, so deep copy doesn't really
# matter/apply here (as they are immutable anyway).
exc_type_names = tuple(self._exc_type_names)
generated_on = self._generated_on
if generated_on:
generated_on = tuple(generated_on)
# NOTE(harlowja): use `self.__class__` here so that we can work
# with subclasses (assuming anyone makes one).
return self.__class__(exc_info=exc_info,
exception_str=self.exception_str,
traceback_str=self.traceback_str,
exc_args=exc_args,
exc_kwargs=exc_kwargs,
exc_type_names=exc_type_names,
cause=cause, generated_on=generated_on) | [
"def",
"copy",
"(",
"self",
",",
"deep",
"=",
"False",
")",
":",
"cause",
"=",
"self",
".",
"_cause",
"if",
"cause",
"is",
"not",
"None",
":",
"cause",
"=",
"cause",
".",
"copy",
"(",
"deep",
"=",
"deep",
")",
"exc_info",
"=",
"utils",
".",
"copy... | Copies this object (shallow or deep).
:param deep: boolean indicating whether to do a deep copy (or a
shallow copy). | [
"Copies",
"this",
"object",
"(",
"shallow",
"or",
"deep",
")",
"."
] | train | https://github.com/harlowja/failure/blob/9ea9a46ebb26c6d7da2553c80e36892f3997bd6f/failure/failure.py#L652-L684 |
henzk/ape | ape/_tasks.py | explain_feature | def explain_feature(featurename):
'''print the location of single feature and its version
if the feature is located inside a git repository,
this will also print the git-rev and modified files
'''
import os
import featuremonkey
import importlib
import subprocess
def guess_version(feature_module):
if hasattr(feature_module, '__version__'):
return feature_module.__version__
if hasattr(feature_module, 'get_version'):
return feature_module.get_version()
return ('unable to determine version:'
' please add __version__ or get_version()'
' to this feature module!')
def git_rev(module):
stdout, stderr = subprocess.Popen(
["git", "rev-parse", "HEAD"],
cwd=os.path.dirname(module.__file__),
stdout=subprocess.PIPE,
stderr=subprocess.PIPE
).communicate()
if 'Not a git repo' in stderr:
return '-'
else:
return stdout.strip()
def git_changes(module):
stdout = subprocess.Popen(
["git", "diff", "--name-only"],
cwd=os.path.dirname(module.__file__),
stdout=subprocess.PIPE,
stderr=subprocess.PIPE
).communicate()[0]
return stdout.strip() or '-'
if featurename in featuremonkey.get_features_from_equation_file(os.environ['PRODUCT_EQUATION_FILENAME']):
print()
print(featurename)
print('-' * 60)
print()
is_subfeature = '.features.' in featurename
try:
feature_module = importlib.import_module(featurename)
except ImportError:
print('Error: unable to import feature "%s"' % featurename)
print('Location: %s' % os.path.dirname(feature_module.__file__))
print()
if is_subfeature:
print('Version: see parent feature')
print()
else:
print('Version: %s' % str(guess_version(feature_module)))
print()
print('git: %s' % git_rev(feature_module))
print()
print('git changed: %s' % '\n\t\t'.join(git_changes(feature_module).split('\n')))
else:
print('No feature named ' + featurename) | python | def explain_feature(featurename):
'''print the location of single feature and its version
if the feature is located inside a git repository,
this will also print the git-rev and modified files
'''
import os
import featuremonkey
import importlib
import subprocess
def guess_version(feature_module):
if hasattr(feature_module, '__version__'):
return feature_module.__version__
if hasattr(feature_module, 'get_version'):
return feature_module.get_version()
return ('unable to determine version:'
' please add __version__ or get_version()'
' to this feature module!')
def git_rev(module):
stdout, stderr = subprocess.Popen(
["git", "rev-parse", "HEAD"],
cwd=os.path.dirname(module.__file__),
stdout=subprocess.PIPE,
stderr=subprocess.PIPE
).communicate()
if 'Not a git repo' in stderr:
return '-'
else:
return stdout.strip()
def git_changes(module):
stdout = subprocess.Popen(
["git", "diff", "--name-only"],
cwd=os.path.dirname(module.__file__),
stdout=subprocess.PIPE,
stderr=subprocess.PIPE
).communicate()[0]
return stdout.strip() or '-'
if featurename in featuremonkey.get_features_from_equation_file(os.environ['PRODUCT_EQUATION_FILENAME']):
print()
print(featurename)
print('-' * 60)
print()
is_subfeature = '.features.' in featurename
try:
feature_module = importlib.import_module(featurename)
except ImportError:
print('Error: unable to import feature "%s"' % featurename)
print('Location: %s' % os.path.dirname(feature_module.__file__))
print()
if is_subfeature:
print('Version: see parent feature')
print()
else:
print('Version: %s' % str(guess_version(feature_module)))
print()
print('git: %s' % git_rev(feature_module))
print()
print('git changed: %s' % '\n\t\t'.join(git_changes(feature_module).split('\n')))
else:
print('No feature named ' + featurename) | [
"def",
"explain_feature",
"(",
"featurename",
")",
":",
"import",
"os",
"import",
"featuremonkey",
"import",
"importlib",
"import",
"subprocess",
"def",
"guess_version",
"(",
"feature_module",
")",
":",
"if",
"hasattr",
"(",
"feature_module",
",",
"'__version__'",
... | print the location of single feature and its version
if the feature is located inside a git repository,
this will also print the git-rev and modified files | [
"print",
"the",
"location",
"of",
"single",
"feature",
"and",
"its",
"version"
] | train | https://github.com/henzk/ape/blob/a1b7ea5e5b25c42beffeaaa5c32d94ad82634819/ape/_tasks.py#L25-L90 |
henzk/ape | ape/_tasks.py | explain_features | def explain_features():
'''print the location of each feature and its version
if the feature is located inside a git repository, this will also print the git-rev and modified files
'''
from ape import tasks
import featuremonkey
import os
featurenames = featuremonkey.get_features_from_equation_file(os.environ['PRODUCT_EQUATION_FILENAME'])
for featurename in featurenames:
tasks.explain_feature(featurename) | python | def explain_features():
'''print the location of each feature and its version
if the feature is located inside a git repository, this will also print the git-rev and modified files
'''
from ape import tasks
import featuremonkey
import os
featurenames = featuremonkey.get_features_from_equation_file(os.environ['PRODUCT_EQUATION_FILENAME'])
for featurename in featurenames:
tasks.explain_feature(featurename) | [
"def",
"explain_features",
"(",
")",
":",
"from",
"ape",
"import",
"tasks",
"import",
"featuremonkey",
"import",
"os",
"featurenames",
"=",
"featuremonkey",
".",
"get_features_from_equation_file",
"(",
"os",
".",
"environ",
"[",
"'PRODUCT_EQUATION_FILENAME'",
"]",
"... | print the location of each feature and its version
if the feature is located inside a git repository, this will also print the git-rev and modified files | [
"print",
"the",
"location",
"of",
"each",
"feature",
"and",
"its",
"version"
] | train | https://github.com/henzk/ape/blob/a1b7ea5e5b25c42beffeaaa5c32d94ad82634819/ape/_tasks.py#L93-L105 |
solidsnack/v2 | v2/__init__.py | git_day | def git_day():
"""Constructs a version string of the form:
day[.<commit-number-in-day>][+<branch-name-if-not-master>]
Master is understood to be always buildable and thus untagged
versions are treated as patch levels. Branches not master are treated
as PEP-440 "local version identifiers".
"""
vec = ['env', 'TZ=UTC', 'git', 'log', '--date=iso-local', '--pretty=%ad']
day = cmd(*(vec + ['-n', '1'])).split()[0]
commits = cmd(*(vec + ['--since', day + 'T00:00Z'])).strip()
n = len(commits.split('\n'))
day = day.replace('-', '')
if n > 1:
day += '.%s' % n
# Branches that are not master are treated as local:
# https://www.python.org/dev/peps/pep-0440/#local-version-identifiers
branch = get_git_branch()
if branch != 'master':
day += '+' + s(branch)
return day | python | def git_day():
"""Constructs a version string of the form:
day[.<commit-number-in-day>][+<branch-name-if-not-master>]
Master is understood to be always buildable and thus untagged
versions are treated as patch levels. Branches not master are treated
as PEP-440 "local version identifiers".
"""
vec = ['env', 'TZ=UTC', 'git', 'log', '--date=iso-local', '--pretty=%ad']
day = cmd(*(vec + ['-n', '1'])).split()[0]
commits = cmd(*(vec + ['--since', day + 'T00:00Z'])).strip()
n = len(commits.split('\n'))
day = day.replace('-', '')
if n > 1:
day += '.%s' % n
# Branches that are not master are treated as local:
# https://www.python.org/dev/peps/pep-0440/#local-version-identifiers
branch = get_git_branch()
if branch != 'master':
day += '+' + s(branch)
return day | [
"def",
"git_day",
"(",
")",
":",
"vec",
"=",
"[",
"'env'",
",",
"'TZ=UTC'",
",",
"'git'",
",",
"'log'",
",",
"'--date=iso-local'",
",",
"'--pretty=%ad'",
"]",
"day",
"=",
"cmd",
"(",
"*",
"(",
"vec",
"+",
"[",
"'-n'",
",",
"'1'",
"]",
")",
")",
"... | Constructs a version string of the form:
day[.<commit-number-in-day>][+<branch-name-if-not-master>]
Master is understood to be always buildable and thus untagged
versions are treated as patch levels. Branches not master are treated
as PEP-440 "local version identifiers". | [
"Constructs",
"a",
"version",
"string",
"of",
"the",
"form",
":"
] | train | https://github.com/solidsnack/v2/blob/95736855a0188cc892dea451617df0efbfa404de/v2/__init__.py#L103-L124 |
solidsnack/v2 | v2/__init__.py | git_version | def git_version():
"""Constructs a version string of the form:
<tag>[.<distance-from-tag>[+<branch-name-if-not-master>]]
Master is understood to be always buildable and thus untagged
versions are treated as patch levels. Branches not master are treated
as PEP-440 "local version identifiers".
"""
tag = cmd('git', 'describe').strip()
pieces = s(tag).split('-')
dotted = pieces[0]
if len(pieces) < 2:
distance = None
else:
# Distance from the latest tag is treated as a patch level.
distance = pieces[1]
dotted += '.' + s(distance)
# Branches that are not master are treated as local:
# https://www.python.org/dev/peps/pep-0440/#local-version-identifiers
if distance is not None:
branch = get_git_branch()
if branch != 'master':
dotted += '+' + s(branch)
return dotted | python | def git_version():
"""Constructs a version string of the form:
<tag>[.<distance-from-tag>[+<branch-name-if-not-master>]]
Master is understood to be always buildable and thus untagged
versions are treated as patch levels. Branches not master are treated
as PEP-440 "local version identifiers".
"""
tag = cmd('git', 'describe').strip()
pieces = s(tag).split('-')
dotted = pieces[0]
if len(pieces) < 2:
distance = None
else:
# Distance from the latest tag is treated as a patch level.
distance = pieces[1]
dotted += '.' + s(distance)
# Branches that are not master are treated as local:
# https://www.python.org/dev/peps/pep-0440/#local-version-identifiers
if distance is not None:
branch = get_git_branch()
if branch != 'master':
dotted += '+' + s(branch)
return dotted | [
"def",
"git_version",
"(",
")",
":",
"tag",
"=",
"cmd",
"(",
"'git'",
",",
"'describe'",
")",
".",
"strip",
"(",
")",
"pieces",
"=",
"s",
"(",
"tag",
")",
".",
"split",
"(",
"'-'",
")",
"dotted",
"=",
"pieces",
"[",
"0",
"]",
"if",
"len",
"(",
... | Constructs a version string of the form:
<tag>[.<distance-from-tag>[+<branch-name-if-not-master>]]
Master is understood to be always buildable and thus untagged
versions are treated as patch levels. Branches not master are treated
as PEP-440 "local version identifiers". | [
"Constructs",
"a",
"version",
"string",
"of",
"the",
"form",
":"
] | train | https://github.com/solidsnack/v2/blob/95736855a0188cc892dea451617df0efbfa404de/v2/__init__.py#L127-L151 |
solidsnack/v2 | v2/__init__.py | Version.imprint | def imprint(self, path=None):
"""Write the determined version, if any, to ``self.version_file`` or
the path passed as an argument.
"""
if self.version is not None:
with open(path or self.version_file, 'w') as h:
h.write(self.version + '\n')
else:
raise ValueError('Can not write null version to file.')
return self | python | def imprint(self, path=None):
"""Write the determined version, if any, to ``self.version_file`` or
the path passed as an argument.
"""
if self.version is not None:
with open(path or self.version_file, 'w') as h:
h.write(self.version + '\n')
else:
raise ValueError('Can not write null version to file.')
return self | [
"def",
"imprint",
"(",
"self",
",",
"path",
"=",
"None",
")",
":",
"if",
"self",
".",
"version",
"is",
"not",
"None",
":",
"with",
"open",
"(",
"path",
"or",
"self",
".",
"version_file",
",",
"'w'",
")",
"as",
"h",
":",
"h",
".",
"write",
"(",
... | Write the determined version, if any, to ``self.version_file`` or
the path passed as an argument. | [
"Write",
"the",
"determined",
"version",
"if",
"any",
"to",
"self",
".",
"version_file",
"or",
"the",
"path",
"passed",
"as",
"an",
"argument",
"."
] | train | https://github.com/solidsnack/v2/blob/95736855a0188cc892dea451617df0efbfa404de/v2/__init__.py#L21-L30 |
solidsnack/v2 | v2/__init__.py | Version.from_file | def from_file(self, path=None):
"""Look for a version in ``self.version_file``, or in the specified
path if supplied.
"""
if self._version is None:
self._version = file_version(path or self.version_file)
return self | python | def from_file(self, path=None):
"""Look for a version in ``self.version_file``, or in the specified
path if supplied.
"""
if self._version is None:
self._version = file_version(path or self.version_file)
return self | [
"def",
"from_file",
"(",
"self",
",",
"path",
"=",
"None",
")",
":",
"if",
"self",
".",
"_version",
"is",
"None",
":",
"self",
".",
"_version",
"=",
"file_version",
"(",
"path",
"or",
"self",
".",
"version_file",
")",
"return",
"self"
] | Look for a version in ``self.version_file``, or in the specified
path if supplied. | [
"Look",
"for",
"a",
"version",
"in",
"self",
".",
"version_file",
"or",
"in",
"the",
"specified",
"path",
"if",
"supplied",
"."
] | train | https://github.com/solidsnack/v2/blob/95736855a0188cc892dea451617df0efbfa404de/v2/__init__.py#L32-L38 |
solidsnack/v2 | v2/__init__.py | Version.from_git | def from_git(self, path=None, prefer_daily=False):
"""Use Git to determine the package version.
This routine uses the __file__ value of the caller to determine
which Git repository root to use.
"""
if self._version is None:
frame = caller(1)
path = frame.f_globals.get('__file__') or '.'
providers = ([git_day, git_version] if prefer_daily
else [git_version, git_day])
for provider in providers:
if self._version is not None:
break
try:
with cd(path):
self._version = provider()
except CalledProcessError:
pass
except OSError as e:
if e.errno != errno.ENOENT:
raise
return self | python | def from_git(self, path=None, prefer_daily=False):
"""Use Git to determine the package version.
This routine uses the __file__ value of the caller to determine
which Git repository root to use.
"""
if self._version is None:
frame = caller(1)
path = frame.f_globals.get('__file__') or '.'
providers = ([git_day, git_version] if prefer_daily
else [git_version, git_day])
for provider in providers:
if self._version is not None:
break
try:
with cd(path):
self._version = provider()
except CalledProcessError:
pass
except OSError as e:
if e.errno != errno.ENOENT:
raise
return self | [
"def",
"from_git",
"(",
"self",
",",
"path",
"=",
"None",
",",
"prefer_daily",
"=",
"False",
")",
":",
"if",
"self",
".",
"_version",
"is",
"None",
":",
"frame",
"=",
"caller",
"(",
"1",
")",
"path",
"=",
"frame",
".",
"f_globals",
".",
"get",
"(",... | Use Git to determine the package version.
This routine uses the __file__ value of the caller to determine
which Git repository root to use. | [
"Use",
"Git",
"to",
"determine",
"the",
"package",
"version",
"."
] | train | https://github.com/solidsnack/v2/blob/95736855a0188cc892dea451617df0efbfa404de/v2/__init__.py#L45-L67 |
solidsnack/v2 | v2/__init__.py | Version.from_pkg | def from_pkg(self):
"""Use pkg_resources to determine the installed package version.
"""
if self._version is None:
frame = caller(1)
pkg = frame.f_globals.get('__package__')
if pkg is not None:
self._version = pkg_version(pkg)
return self | python | def from_pkg(self):
"""Use pkg_resources to determine the installed package version.
"""
if self._version is None:
frame = caller(1)
pkg = frame.f_globals.get('__package__')
if pkg is not None:
self._version = pkg_version(pkg)
return self | [
"def",
"from_pkg",
"(",
"self",
")",
":",
"if",
"self",
".",
"_version",
"is",
"None",
":",
"frame",
"=",
"caller",
"(",
"1",
")",
"pkg",
"=",
"frame",
".",
"f_globals",
".",
"get",
"(",
"'__package__'",
")",
"if",
"pkg",
"is",
"not",
"None",
":",
... | Use pkg_resources to determine the installed package version. | [
"Use",
"pkg_resources",
"to",
"determine",
"the",
"installed",
"package",
"version",
"."
] | train | https://github.com/solidsnack/v2/blob/95736855a0188cc892dea451617df0efbfa404de/v2/__init__.py#L69-L77 |
cohorte/cohorte-herald | python/herald/transports/peer_contact.py | PeerContact.__load_dump | def __load_dump(self, message):
"""
Calls the hook method to modify the loaded peer description before
giving it to the directory
:param message: The received Herald message
:return: The updated peer description
"""
dump = message.content
if self._hook is not None:
# Call the hook
try:
updated_dump = self._hook(message, dump)
if updated_dump is not None:
# Use the new description
dump = updated_dump
except (TypeError, ValueError) as ex:
self._logger("Invalid description hook: %s", ex)
return dump | python | def __load_dump(self, message):
"""
Calls the hook method to modify the loaded peer description before
giving it to the directory
:param message: The received Herald message
:return: The updated peer description
"""
dump = message.content
if self._hook is not None:
# Call the hook
try:
updated_dump = self._hook(message, dump)
if updated_dump is not None:
# Use the new description
dump = updated_dump
except (TypeError, ValueError) as ex:
self._logger("Invalid description hook: %s", ex)
return dump | [
"def",
"__load_dump",
"(",
"self",
",",
"message",
")",
":",
"dump",
"=",
"message",
".",
"content",
"if",
"self",
".",
"_hook",
"is",
"not",
"None",
":",
"# Call the hook",
"try",
":",
"updated_dump",
"=",
"self",
".",
"_hook",
"(",
"message",
",",
"d... | Calls the hook method to modify the loaded peer description before
giving it to the directory
:param message: The received Herald message
:return: The updated peer description | [
"Calls",
"the",
"hook",
"method",
"to",
"modify",
"the",
"loaded",
"peer",
"description",
"before",
"giving",
"it",
"to",
"the",
"directory"
] | train | https://github.com/cohorte/cohorte-herald/blob/bb3445d0031c8b3abad71e6219cc559b49faa3ee/python/herald/transports/peer_contact.py#L68-L86 |
cohorte/cohorte-herald | python/herald/transports/peer_contact.py | PeerContact.herald_message | def herald_message(self, herald_svc, message):
"""
Handles a message received by Herald
:param herald_svc: Herald service
:param message: Received message
"""
subject = message.subject
if subject == SUBJECT_DISCOVERY_STEP_1:
# Step 1: Register the remote peer and reply with our dump
try:
# Delayed registration
notification = self._directory.register_delayed(
self.__load_dump(message))
peer = notification.peer
if peer is not None:
# Registration succeeded
self.__delayed_notifs[peer.uid] = notification
# Reply with our dump
herald_svc.reply(
message, self._directory.get_local_peer().dump(),
SUBJECT_DISCOVERY_STEP_2)
except ValueError:
self._logger.error("Error registering a discovered peer")
elif subject == SUBJECT_DISCOVERY_STEP_2:
# Step 2: Register the dump, notify local listeners, then let
# the remote peer notify its listeners
try:
# Register the peer
notification = self._directory.register_delayed(
self.__load_dump(message))
if notification.peer is not None:
# Let the remote peer notify its listeners
herald_svc.reply(message, None, SUBJECT_DISCOVERY_STEP_3)
# Now we can notify listeners
notification.notify()
except ValueError:
self._logger.error("Error registering a peer using the "
"description it sent")
elif subject == SUBJECT_DISCOVERY_STEP_3:
# Step 3: notify local listeners about the remote peer
try:
self.__delayed_notifs.pop(message.sender).notify()
except KeyError:
# Unknown peer
pass
else:
# Unknown subject
self._logger.warning("Unknown discovery step: %s", subject) | python | def herald_message(self, herald_svc, message):
"""
Handles a message received by Herald
:param herald_svc: Herald service
:param message: Received message
"""
subject = message.subject
if subject == SUBJECT_DISCOVERY_STEP_1:
# Step 1: Register the remote peer and reply with our dump
try:
# Delayed registration
notification = self._directory.register_delayed(
self.__load_dump(message))
peer = notification.peer
if peer is not None:
# Registration succeeded
self.__delayed_notifs[peer.uid] = notification
# Reply with our dump
herald_svc.reply(
message, self._directory.get_local_peer().dump(),
SUBJECT_DISCOVERY_STEP_2)
except ValueError:
self._logger.error("Error registering a discovered peer")
elif subject == SUBJECT_DISCOVERY_STEP_2:
# Step 2: Register the dump, notify local listeners, then let
# the remote peer notify its listeners
try:
# Register the peer
notification = self._directory.register_delayed(
self.__load_dump(message))
if notification.peer is not None:
# Let the remote peer notify its listeners
herald_svc.reply(message, None, SUBJECT_DISCOVERY_STEP_3)
# Now we can notify listeners
notification.notify()
except ValueError:
self._logger.error("Error registering a peer using the "
"description it sent")
elif subject == SUBJECT_DISCOVERY_STEP_3:
# Step 3: notify local listeners about the remote peer
try:
self.__delayed_notifs.pop(message.sender).notify()
except KeyError:
# Unknown peer
pass
else:
# Unknown subject
self._logger.warning("Unknown discovery step: %s", subject) | [
"def",
"herald_message",
"(",
"self",
",",
"herald_svc",
",",
"message",
")",
":",
"subject",
"=",
"message",
".",
"subject",
"if",
"subject",
"==",
"SUBJECT_DISCOVERY_STEP_1",
":",
"# Step 1: Register the remote peer and reply with our dump",
"try",
":",
"# Delayed reg... | Handles a message received by Herald
:param herald_svc: Herald service
:param message: Received message | [
"Handles",
"a",
"message",
"received",
"by",
"Herald"
] | train | https://github.com/cohorte/cohorte-herald/blob/bb3445d0031c8b3abad71e6219cc559b49faa3ee/python/herald/transports/peer_contact.py#L94-L148 |
clinicedc/edc-notification | edc_notification/mailing_list_manager.py | MailingListManager.api_url | def api_url(self):
"""Returns the api_url or None.
"""
if not self._api_url:
error_msg = (
f"Email is enabled but API_URL is not set. "
f"See settings.{self.api_url_attr}"
)
try:
self._api_url = getattr(settings, self.api_url_attr)
except AttributeError:
raise EmailNotEnabledError(error_msg, code="api_url_attribute_error")
else:
if not self._api_url:
raise EmailNotEnabledError(error_msg, code="api_url_is_none")
return self._api_url | python | def api_url(self):
"""Returns the api_url or None.
"""
if not self._api_url:
error_msg = (
f"Email is enabled but API_URL is not set. "
f"See settings.{self.api_url_attr}"
)
try:
self._api_url = getattr(settings, self.api_url_attr)
except AttributeError:
raise EmailNotEnabledError(error_msg, code="api_url_attribute_error")
else:
if not self._api_url:
raise EmailNotEnabledError(error_msg, code="api_url_is_none")
return self._api_url | [
"def",
"api_url",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_api_url",
":",
"error_msg",
"=",
"(",
"f\"Email is enabled but API_URL is not set. \"",
"f\"See settings.{self.api_url_attr}\"",
")",
"try",
":",
"self",
".",
"_api_url",
"=",
"getattr",
"(",
"se... | Returns the api_url or None. | [
"Returns",
"the",
"api_url",
"or",
"None",
"."
] | train | https://github.com/clinicedc/edc-notification/blob/79e43a44261e37566c63a8780d80b0d8ece89cc9/edc_notification/mailing_list_manager.py#L38-L53 |
clinicedc/edc-notification | edc_notification/mailing_list_manager.py | MailingListManager.api_key | def api_key(self):
"""Returns the api_key or None.
"""
if not self._api_key:
error_msg = (
f"Email is enabled but API_KEY is not set. "
f"See settings.{self.api_key_attr}"
)
try:
self._api_key = getattr(settings, self.api_key_attr)
except AttributeError:
raise EmailNotEnabledError(error_msg, code="api_key_attribute_error")
else:
if not self._api_key:
raise EmailNotEnabledError(error_msg, code="api_key_is_none")
return self._api_key | python | def api_key(self):
"""Returns the api_key or None.
"""
if not self._api_key:
error_msg = (
f"Email is enabled but API_KEY is not set. "
f"See settings.{self.api_key_attr}"
)
try:
self._api_key = getattr(settings, self.api_key_attr)
except AttributeError:
raise EmailNotEnabledError(error_msg, code="api_key_attribute_error")
else:
if not self._api_key:
raise EmailNotEnabledError(error_msg, code="api_key_is_none")
return self._api_key | [
"def",
"api_key",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_api_key",
":",
"error_msg",
"=",
"(",
"f\"Email is enabled but API_KEY is not set. \"",
"f\"See settings.{self.api_key_attr}\"",
")",
"try",
":",
"self",
".",
"_api_key",
"=",
"getattr",
"(",
"se... | Returns the api_key or None. | [
"Returns",
"the",
"api_key",
"or",
"None",
"."
] | train | https://github.com/clinicedc/edc-notification/blob/79e43a44261e37566c63a8780d80b0d8ece89cc9/edc_notification/mailing_list_manager.py#L56-L71 |
clinicedc/edc-notification | edc_notification/mailing_list_manager.py | MailingListManager.subscribe | def subscribe(self, user, verbose=None):
"""Returns a response after attempting to subscribe
a member to the list.
"""
if not self.email_enabled:
raise EmailNotEnabledError("See settings.EMAIL_ENABLED")
if not user.email:
raise UserEmailError(f"User {user}'s email address is not defined.")
response = requests.post(
f"{self.api_url}/{self.address}/members",
auth=("api", self.api_key),
data={
"subscribed": True,
"address": user.email,
"name": f"{user.first_name} {user.last_name}",
"description": f'{user.userprofile.job_title or ""}',
"upsert": "yes",
},
)
if verbose:
sys.stdout.write(
f"Subscribing {user.email} to {self.address}. "
f"Got response={response.status_code}.\n"
)
return response | python | def subscribe(self, user, verbose=None):
"""Returns a response after attempting to subscribe
a member to the list.
"""
if not self.email_enabled:
raise EmailNotEnabledError("See settings.EMAIL_ENABLED")
if not user.email:
raise UserEmailError(f"User {user}'s email address is not defined.")
response = requests.post(
f"{self.api_url}/{self.address}/members",
auth=("api", self.api_key),
data={
"subscribed": True,
"address": user.email,
"name": f"{user.first_name} {user.last_name}",
"description": f'{user.userprofile.job_title or ""}',
"upsert": "yes",
},
)
if verbose:
sys.stdout.write(
f"Subscribing {user.email} to {self.address}. "
f"Got response={response.status_code}.\n"
)
return response | [
"def",
"subscribe",
"(",
"self",
",",
"user",
",",
"verbose",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"email_enabled",
":",
"raise",
"EmailNotEnabledError",
"(",
"\"See settings.EMAIL_ENABLED\"",
")",
"if",
"not",
"user",
".",
"email",
":",
"raise",... | Returns a response after attempting to subscribe
a member to the list. | [
"Returns",
"a",
"response",
"after",
"attempting",
"to",
"subscribe",
"a",
"member",
"to",
"the",
"list",
"."
] | train | https://github.com/clinicedc/edc-notification/blob/79e43a44261e37566c63a8780d80b0d8ece89cc9/edc_notification/mailing_list_manager.py#L73-L97 |
clinicedc/edc-notification | edc_notification/mailing_list_manager.py | MailingListManager.unsubscribe | def unsubscribe(self, user, verbose=None):
"""Returns a response after attempting to unsubscribe
a member from the list.
"""
if not self.email_enabled:
raise EmailNotEnabledError("See settings.EMAIL_ENABLED")
response = requests.put(
f"{self.api_url}/{self.address}/members/{user.email}",
auth=("api", self.api_key),
data={"subscribed": False},
)
if verbose:
sys.stdout.write(
f"Unsubscribing {user.email} from {self.address}. "
f"Got response={response.status_code}.\n"
)
return response | python | def unsubscribe(self, user, verbose=None):
"""Returns a response after attempting to unsubscribe
a member from the list.
"""
if not self.email_enabled:
raise EmailNotEnabledError("See settings.EMAIL_ENABLED")
response = requests.put(
f"{self.api_url}/{self.address}/members/{user.email}",
auth=("api", self.api_key),
data={"subscribed": False},
)
if verbose:
sys.stdout.write(
f"Unsubscribing {user.email} from {self.address}. "
f"Got response={response.status_code}.\n"
)
return response | [
"def",
"unsubscribe",
"(",
"self",
",",
"user",
",",
"verbose",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"email_enabled",
":",
"raise",
"EmailNotEnabledError",
"(",
"\"See settings.EMAIL_ENABLED\"",
")",
"response",
"=",
"requests",
".",
"put",
"(",
... | Returns a response after attempting to unsubscribe
a member from the list. | [
"Returns",
"a",
"response",
"after",
"attempting",
"to",
"unsubscribe",
"a",
"member",
"from",
"the",
"list",
"."
] | train | https://github.com/clinicedc/edc-notification/blob/79e43a44261e37566c63a8780d80b0d8ece89cc9/edc_notification/mailing_list_manager.py#L99-L115 |
clinicedc/edc-notification | edc_notification/mailing_list_manager.py | MailingListManager.create | def create(self, verbose=None):
"""Returns a response after attempting to create the list.
"""
if not self.email_enabled:
raise EmailNotEnabledError("See settings.EMAIL_ENABLED")
response = requests.post(
self.api_url,
auth=("api", self.api_key),
data={
"address": self.address,
"name": self.name,
"description": self.display_name,
},
)
if verbose:
sys.stdout.write(
f"Creating mailing list {self.address}. "
f"Got response={response.status_code}.\n"
)
return response | python | def create(self, verbose=None):
"""Returns a response after attempting to create the list.
"""
if not self.email_enabled:
raise EmailNotEnabledError("See settings.EMAIL_ENABLED")
response = requests.post(
self.api_url,
auth=("api", self.api_key),
data={
"address": self.address,
"name": self.name,
"description": self.display_name,
},
)
if verbose:
sys.stdout.write(
f"Creating mailing list {self.address}. "
f"Got response={response.status_code}.\n"
)
return response | [
"def",
"create",
"(",
"self",
",",
"verbose",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"email_enabled",
":",
"raise",
"EmailNotEnabledError",
"(",
"\"See settings.EMAIL_ENABLED\"",
")",
"response",
"=",
"requests",
".",
"post",
"(",
"self",
".",
"api... | Returns a response after attempting to create the list. | [
"Returns",
"a",
"response",
"after",
"attempting",
"to",
"create",
"the",
"list",
"."
] | train | https://github.com/clinicedc/edc-notification/blob/79e43a44261e37566c63a8780d80b0d8ece89cc9/edc_notification/mailing_list_manager.py#L117-L136 |
clinicedc/edc-notification | edc_notification/mailing_list_manager.py | MailingListManager.delete | def delete(self):
"""Returns a response after attempting to delete the list.
"""
if not self.email_enabled:
raise EmailNotEnabledError("See settings.EMAIL_ENABLED")
return requests.delete(
f"{self.api_url}/{self.address}", auth=("api", self.api_key)
) | python | def delete(self):
"""Returns a response after attempting to delete the list.
"""
if not self.email_enabled:
raise EmailNotEnabledError("See settings.EMAIL_ENABLED")
return requests.delete(
f"{self.api_url}/{self.address}", auth=("api", self.api_key)
) | [
"def",
"delete",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"email_enabled",
":",
"raise",
"EmailNotEnabledError",
"(",
"\"See settings.EMAIL_ENABLED\"",
")",
"return",
"requests",
".",
"delete",
"(",
"f\"{self.api_url}/{self.address}\"",
",",
"auth",
"=",
"... | Returns a response after attempting to delete the list. | [
"Returns",
"a",
"response",
"after",
"attempting",
"to",
"delete",
"the",
"list",
"."
] | train | https://github.com/clinicedc/edc-notification/blob/79e43a44261e37566c63a8780d80b0d8ece89cc9/edc_notification/mailing_list_manager.py#L138-L145 |
clinicedc/edc-notification | edc_notification/mailing_list_manager.py | MailingListManager.delete_member | def delete_member(self, user):
"""Returns a response after attempting to remove
a member from the list.
"""
if not self.email_enabled:
raise EmailNotEnabledError("See settings.EMAIL_ENABLED")
return requests.delete(
f"{self.api_url}/{self.address}/members/{user.email}",
auth=("api", self.api_key),
) | python | def delete_member(self, user):
"""Returns a response after attempting to remove
a member from the list.
"""
if not self.email_enabled:
raise EmailNotEnabledError("See settings.EMAIL_ENABLED")
return requests.delete(
f"{self.api_url}/{self.address}/members/{user.email}",
auth=("api", self.api_key),
) | [
"def",
"delete_member",
"(",
"self",
",",
"user",
")",
":",
"if",
"not",
"self",
".",
"email_enabled",
":",
"raise",
"EmailNotEnabledError",
"(",
"\"See settings.EMAIL_ENABLED\"",
")",
"return",
"requests",
".",
"delete",
"(",
"f\"{self.api_url}/{self.address}/members... | Returns a response after attempting to remove
a member from the list. | [
"Returns",
"a",
"response",
"after",
"attempting",
"to",
"remove",
"a",
"member",
"from",
"the",
"list",
"."
] | train | https://github.com/clinicedc/edc-notification/blob/79e43a44261e37566c63a8780d80b0d8ece89cc9/edc_notification/mailing_list_manager.py#L147-L156 |
scieloorg/processing | accesses/dumpdata.py | fbpe_key | def fbpe_key(code):
"""
input:
'S0102-67202009000300001'
output:
'S0102-6720(09)000300001'
"""
begin = code[0:10]
year = code[12:14]
end = code[14:]
return '%s(%s)%s' % (begin, year, end) | python | def fbpe_key(code):
"""
input:
'S0102-67202009000300001'
output:
'S0102-6720(09)000300001'
"""
begin = code[0:10]
year = code[12:14]
end = code[14:]
return '%s(%s)%s' % (begin, year, end) | [
"def",
"fbpe_key",
"(",
"code",
")",
":",
"begin",
"=",
"code",
"[",
"0",
":",
"10",
"]",
"year",
"=",
"code",
"[",
"12",
":",
"14",
"]",
"end",
"=",
"code",
"[",
"14",
":",
"]",
"return",
"'%s(%s)%s'",
"%",
"(",
"begin",
",",
"year",
",",
"e... | input:
'S0102-67202009000300001'
output:
'S0102-6720(09)000300001' | [
"input",
":",
"S0102",
"-",
"67202009000300001",
"output",
":",
"S0102",
"-",
"6720",
"(",
"09",
")",
"000300001"
] | train | https://github.com/scieloorg/processing/blob/629b50b45ba7a176651cd3bfcdb441dab6fddfcc/accesses/dumpdata.py#L72-L84 |
scieloorg/processing | accesses/dumpdata.py | join_accesses | def join_accesses(unique_id, accesses, from_date, until_date, dayly_granularity):
"""
Esse metodo recebe 1 ou mais chaves para um documento em específico para que
os acessos sejam recuperados no Ratchet e consolidados em um unico id.
Esse processo é necessário pois os acessos de um documento podem ser registrados
para os seguintes ID's (PID, PID FBPE, Path PDF).
PID: Id original do SciELO ex: S0102-67202009000300001
PID FBPE: Id antigo do SciELO ex: S0102-6720(09)000300001
Path PDF: Quando o acesso é feito diretamente para o arquivo PDF no FS do
servidor ex: /pdf/rsp/v12n10/v12n10.pdf
"""
logger.debug('joining accesses for: %s' % unique_id)
joined_data = {}
listed_data = []
def joining_monthly(joined_data, atype, data):
if 'total' in data:
del(data['total'])
for year, months in data.items():
del(months['total'])
for month in months:
dt = '%s-%s' % (year[1:], month[1:])
if not dt >= from_date[:7] or not dt <= until_date[:7]:
continue
joined_data.setdefault(dt, {})
joined_data[dt].setdefault(atype, 0)
joined_data[dt][atype] += data[year][month]['total']
return joined_data
def joining_dayly(joined_data, atype, data):
if 'total' in data:
del(data['total'])
for year, months in data.items():
del(months['total'])
for month, days in months.items():
del(days['total'])
for day in days:
dt = '%s-%s-%s' % (year[1:], month[1:], day[1:])
if not dt >= from_date or not dt <= until_date:
continue
joined_data.setdefault(dt, {})
joined_data[dt].setdefault(atype, 0)
joined_data[dt][atype] += data[year][month][day]
return joined_data
joining = joining_monthly
if dayly_granularity:
joining = joining_dayly
for data in accesses:
for key, value in data.items():
if not key in ['abstract', 'html', 'pdf', 'readcube']:
continue
joined_data = joining(joined_data, key, value)
return joined_data | python | def join_accesses(unique_id, accesses, from_date, until_date, dayly_granularity):
"""
Esse metodo recebe 1 ou mais chaves para um documento em específico para que
os acessos sejam recuperados no Ratchet e consolidados em um unico id.
Esse processo é necessário pois os acessos de um documento podem ser registrados
para os seguintes ID's (PID, PID FBPE, Path PDF).
PID: Id original do SciELO ex: S0102-67202009000300001
PID FBPE: Id antigo do SciELO ex: S0102-6720(09)000300001
Path PDF: Quando o acesso é feito diretamente para o arquivo PDF no FS do
servidor ex: /pdf/rsp/v12n10/v12n10.pdf
"""
logger.debug('joining accesses for: %s' % unique_id)
joined_data = {}
listed_data = []
def joining_monthly(joined_data, atype, data):
if 'total' in data:
del(data['total'])
for year, months in data.items():
del(months['total'])
for month in months:
dt = '%s-%s' % (year[1:], month[1:])
if not dt >= from_date[:7] or not dt <= until_date[:7]:
continue
joined_data.setdefault(dt, {})
joined_data[dt].setdefault(atype, 0)
joined_data[dt][atype] += data[year][month]['total']
return joined_data
def joining_dayly(joined_data, atype, data):
if 'total' in data:
del(data['total'])
for year, months in data.items():
del(months['total'])
for month, days in months.items():
del(days['total'])
for day in days:
dt = '%s-%s-%s' % (year[1:], month[1:], day[1:])
if not dt >= from_date or not dt <= until_date:
continue
joined_data.setdefault(dt, {})
joined_data[dt].setdefault(atype, 0)
joined_data[dt][atype] += data[year][month][day]
return joined_data
joining = joining_monthly
if dayly_granularity:
joining = joining_dayly
for data in accesses:
for key, value in data.items():
if not key in ['abstract', 'html', 'pdf', 'readcube']:
continue
joined_data = joining(joined_data, key, value)
return joined_data | [
"def",
"join_accesses",
"(",
"unique_id",
",",
"accesses",
",",
"from_date",
",",
"until_date",
",",
"dayly_granularity",
")",
":",
"logger",
".",
"debug",
"(",
"'joining accesses for: %s'",
"%",
"unique_id",
")",
"joined_data",
"=",
"{",
"}",
"listed_data",
"="... | Esse metodo recebe 1 ou mais chaves para um documento em específico para que
os acessos sejam recuperados no Ratchet e consolidados em um unico id.
Esse processo é necessário pois os acessos de um documento podem ser registrados
para os seguintes ID's (PID, PID FBPE, Path PDF).
PID: Id original do SciELO ex: S0102-67202009000300001
PID FBPE: Id antigo do SciELO ex: S0102-6720(09)000300001
Path PDF: Quando o acesso é feito diretamente para o arquivo PDF no FS do
servidor ex: /pdf/rsp/v12n10/v12n10.pdf | [
"Esse",
"metodo",
"recebe",
"1",
"ou",
"mais",
"chaves",
"para",
"um",
"documento",
"em",
"específico",
"para",
"que",
"os",
"acessos",
"sejam",
"recuperados",
"no",
"Ratchet",
"e",
"consolidados",
"em",
"um",
"unico",
"id",
".",
"Esse",
"processo",
"é",
"... | train | https://github.com/scieloorg/processing/blob/629b50b45ba7a176651cd3bfcdb441dab6fddfcc/accesses/dumpdata.py#L197-L258 |
MacHu-GWU/pymongo_mate-project | pymongo_mate/pkg/pandas_mate/pkg/rolex/__init__.py | Rolex.str2date | def str2date(self, datestr):
"""Parse date from string. If no template matches this string,
raise Error. Please go
https://github.com/MacHu-GWU/rolex-project/issues
submit your date string. I 'll update templates asap.
This method is faster than :meth:`dateutil.parser.parse`.
:param datestr: a string represent a date
:type datestr: str
:return: a date object
**中文文档**
从string解析date。首先尝试默认模板, 如果失败了, 则尝试所有的模板。
一旦尝试成功, 就将当前成功的模板保存为默认模板。这样做在当你待解析的
字符串非常多, 且模式单一时, 只有第一次尝试耗时较多, 之后就非常快了。
该方法要快过 :meth:`dateutil.parser.parse` 方法。
"""
if datestr is None:
raise ValueError(
"Parser must be a string or character stream, not NoneType")
# try default date template
try:
return datetime.strptime(
datestr, self.default_date_template).date()
except:
pass
# try every datetime templates
for template in DateTemplates:
try:
dt = datetime.strptime(datestr, template)
self.default_date_template = template
return dt.date()
except:
pass
# raise error
raise Exception("Unable to parse date from: %r" % datestr) | python | def str2date(self, datestr):
"""Parse date from string. If no template matches this string,
raise Error. Please go
https://github.com/MacHu-GWU/rolex-project/issues
submit your date string. I 'll update templates asap.
This method is faster than :meth:`dateutil.parser.parse`.
:param datestr: a string represent a date
:type datestr: str
:return: a date object
**中文文档**
从string解析date。首先尝试默认模板, 如果失败了, 则尝试所有的模板。
一旦尝试成功, 就将当前成功的模板保存为默认模板。这样做在当你待解析的
字符串非常多, 且模式单一时, 只有第一次尝试耗时较多, 之后就非常快了。
该方法要快过 :meth:`dateutil.parser.parse` 方法。
"""
if datestr is None:
raise ValueError(
"Parser must be a string or character stream, not NoneType")
# try default date template
try:
return datetime.strptime(
datestr, self.default_date_template).date()
except:
pass
# try every datetime templates
for template in DateTemplates:
try:
dt = datetime.strptime(datestr, template)
self.default_date_template = template
return dt.date()
except:
pass
# raise error
raise Exception("Unable to parse date from: %r" % datestr) | [
"def",
"str2date",
"(",
"self",
",",
"datestr",
")",
":",
"if",
"datestr",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"Parser must be a string or character stream, not NoneType\"",
")",
"# try default date template",
"try",
":",
"return",
"datetime",
".",
"strpt... | Parse date from string. If no template matches this string,
raise Error. Please go
https://github.com/MacHu-GWU/rolex-project/issues
submit your date string. I 'll update templates asap.
This method is faster than :meth:`dateutil.parser.parse`.
:param datestr: a string represent a date
:type datestr: str
:return: a date object
**中文文档**
从string解析date。首先尝试默认模板, 如果失败了, 则尝试所有的模板。
一旦尝试成功, 就将当前成功的模板保存为默认模板。这样做在当你待解析的
字符串非常多, 且模式单一时, 只有第一次尝试耗时较多, 之后就非常快了。
该方法要快过 :meth:`dateutil.parser.parse` 方法。 | [
"Parse",
"date",
"from",
"string",
".",
"If",
"no",
"template",
"matches",
"this",
"string",
"raise",
"Error",
".",
"Please",
"go",
"https",
":",
"//",
"github",
".",
"com",
"/",
"MacHu",
"-",
"GWU",
"/",
"rolex",
"-",
"project",
"/",
"issues",
"submit... | train | https://github.com/MacHu-GWU/pymongo_mate-project/blob/be53170c2db54cb705b9e548d32ef26c773ff7f3/pymongo_mate/pkg/pandas_mate/pkg/rolex/__init__.py#L69-L109 |
MacHu-GWU/pymongo_mate-project | pymongo_mate/pkg/pandas_mate/pkg/rolex/__init__.py | Rolex._str2datetime | def _str2datetime(self, datetimestr):
"""Parse datetime from string. If no template matches this string,
raise Error. Please go
https://github.com/MacHu-GWU/rolex-project/issues
submit your datetime string. I 'll update templates asap.
This method is faster than :meth:`dateutil.parser.parse`.
:param datetimestr: a string represent a datetime
:type datetimestr: str
:return: a datetime object
**中文文档**
从string解析datetime。首先尝试默认模板, 如果失败了, 则尝试所有的模板。
一旦尝试成功, 就将当前成功的模板保存为默认模板。这样做在当你待解析的
字符串非常多, 且模式单一时, 只有第一次尝试耗时较多, 之后就非常快了。
该方法要快过 :meth:`dateutil.parser.parse` 方法。
"""
if datetimestr is None:
raise ValueError(
"Parser must be a string or character stream, not NoneType")
# try default datetime template
try:
return datetime.strptime(
datetimestr, self.default_datetime_template)
except:
pass
# try every datetime templates
for template in DatetimeTemplates:
try:
dt = datetime.strptime(datetimestr, template)
self.default_datetime_template = template
return dt
except:
pass
# raise error
dt = parser.parse(datetimestr)
self.str2datetime = parser.parse
return dt | python | def _str2datetime(self, datetimestr):
"""Parse datetime from string. If no template matches this string,
raise Error. Please go
https://github.com/MacHu-GWU/rolex-project/issues
submit your datetime string. I 'll update templates asap.
This method is faster than :meth:`dateutil.parser.parse`.
:param datetimestr: a string represent a datetime
:type datetimestr: str
:return: a datetime object
**中文文档**
从string解析datetime。首先尝试默认模板, 如果失败了, 则尝试所有的模板。
一旦尝试成功, 就将当前成功的模板保存为默认模板。这样做在当你待解析的
字符串非常多, 且模式单一时, 只有第一次尝试耗时较多, 之后就非常快了。
该方法要快过 :meth:`dateutil.parser.parse` 方法。
"""
if datetimestr is None:
raise ValueError(
"Parser must be a string or character stream, not NoneType")
# try default datetime template
try:
return datetime.strptime(
datetimestr, self.default_datetime_template)
except:
pass
# try every datetime templates
for template in DatetimeTemplates:
try:
dt = datetime.strptime(datetimestr, template)
self.default_datetime_template = template
return dt
except:
pass
# raise error
dt = parser.parse(datetimestr)
self.str2datetime = parser.parse
return dt | [
"def",
"_str2datetime",
"(",
"self",
",",
"datetimestr",
")",
":",
"if",
"datetimestr",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"Parser must be a string or character stream, not NoneType\"",
")",
"# try default datetime template",
"try",
":",
"return",
"datetime"... | Parse datetime from string. If no template matches this string,
raise Error. Please go
https://github.com/MacHu-GWU/rolex-project/issues
submit your datetime string. I 'll update templates asap.
This method is faster than :meth:`dateutil.parser.parse`.
:param datetimestr: a string represent a datetime
:type datetimestr: str
:return: a datetime object
**中文文档**
从string解析datetime。首先尝试默认模板, 如果失败了, 则尝试所有的模板。
一旦尝试成功, 就将当前成功的模板保存为默认模板。这样做在当你待解析的
字符串非常多, 且模式单一时, 只有第一次尝试耗时较多, 之后就非常快了。
该方法要快过 :meth:`dateutil.parser.parse` 方法。 | [
"Parse",
"datetime",
"from",
"string",
".",
"If",
"no",
"template",
"matches",
"this",
"string",
"raise",
"Error",
".",
"Please",
"go",
"https",
":",
"//",
"github",
".",
"com",
"/",
"MacHu",
"-",
"GWU",
"/",
"rolex",
"-",
"project",
"/",
"issues",
"su... | train | https://github.com/MacHu-GWU/pymongo_mate-project/blob/be53170c2db54cb705b9e548d32ef26c773ff7f3/pymongo_mate/pkg/pandas_mate/pkg/rolex/__init__.py#L111-L154 |
MacHu-GWU/pymongo_mate-project | pymongo_mate/pkg/pandas_mate/pkg/rolex/__init__.py | Rolex.parse_date | def parse_date(self, value):
"""A lazy method to parse anything to date.
If input data type is:
- string: parse date from it
- integer: use from ordinal
- datetime: use date part
- date: just return it
"""
if value is None:
raise Exception("Unable to parse date from %r" % value)
elif isinstance(value, string_types):
return self.str2date(value)
elif isinstance(value, int):
return date.fromordinal(value)
elif isinstance(value, datetime):
return value.date()
elif isinstance(value, date):
return value
else:
raise Exception("Unable to parse date from %r" % value) | python | def parse_date(self, value):
"""A lazy method to parse anything to date.
If input data type is:
- string: parse date from it
- integer: use from ordinal
- datetime: use date part
- date: just return it
"""
if value is None:
raise Exception("Unable to parse date from %r" % value)
elif isinstance(value, string_types):
return self.str2date(value)
elif isinstance(value, int):
return date.fromordinal(value)
elif isinstance(value, datetime):
return value.date()
elif isinstance(value, date):
return value
else:
raise Exception("Unable to parse date from %r" % value) | [
"def",
"parse_date",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
"is",
"None",
":",
"raise",
"Exception",
"(",
"\"Unable to parse date from %r\"",
"%",
"value",
")",
"elif",
"isinstance",
"(",
"value",
",",
"string_types",
")",
":",
"return",
"self",... | A lazy method to parse anything to date.
If input data type is:
- string: parse date from it
- integer: use from ordinal
- datetime: use date part
- date: just return it | [
"A",
"lazy",
"method",
"to",
"parse",
"anything",
"to",
"date",
"."
] | train | https://github.com/MacHu-GWU/pymongo_mate-project/blob/be53170c2db54cb705b9e548d32ef26c773ff7f3/pymongo_mate/pkg/pandas_mate/pkg/rolex/__init__.py#L158-L179 |
MacHu-GWU/pymongo_mate-project | pymongo_mate/pkg/pandas_mate/pkg/rolex/__init__.py | Rolex.parse_datetime | def parse_datetime(self, value):
"""A lazy method to parse anything to datetime.
If input data type is:
- string: parse datetime from it
- integer: use from ordinal
- date: use date part and set hour, minute, second to zero
- datetime: just return it
"""
if value is None:
raise Exception("Unable to parse datetime from %r" % value)
elif isinstance(value, string_types):
return self.str2datetime(value)
elif isinstance(value, integer_types):
return self.from_utctimestamp(value)
elif isinstance(value, float):
return self.from_utctimestamp(value)
elif isinstance(value, datetime):
return value
elif isinstance(value, date):
return datetime(value.year, value.month, value.day)
else:
raise Exception("Unable to parse datetime from %r" % value) | python | def parse_datetime(self, value):
"""A lazy method to parse anything to datetime.
If input data type is:
- string: parse datetime from it
- integer: use from ordinal
- date: use date part and set hour, minute, second to zero
- datetime: just return it
"""
if value is None:
raise Exception("Unable to parse datetime from %r" % value)
elif isinstance(value, string_types):
return self.str2datetime(value)
elif isinstance(value, integer_types):
return self.from_utctimestamp(value)
elif isinstance(value, float):
return self.from_utctimestamp(value)
elif isinstance(value, datetime):
return value
elif isinstance(value, date):
return datetime(value.year, value.month, value.day)
else:
raise Exception("Unable to parse datetime from %r" % value) | [
"def",
"parse_datetime",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
"is",
"None",
":",
"raise",
"Exception",
"(",
"\"Unable to parse datetime from %r\"",
"%",
"value",
")",
"elif",
"isinstance",
"(",
"value",
",",
"string_types",
")",
":",
"return",
... | A lazy method to parse anything to datetime.
If input data type is:
- string: parse datetime from it
- integer: use from ordinal
- date: use date part and set hour, minute, second to zero
- datetime: just return it | [
"A",
"lazy",
"method",
"to",
"parse",
"anything",
"to",
"datetime",
"."
] | train | https://github.com/MacHu-GWU/pymongo_mate-project/blob/be53170c2db54cb705b9e548d32ef26c773ff7f3/pymongo_mate/pkg/pandas_mate/pkg/rolex/__init__.py#L181-L204 |
MacHu-GWU/pymongo_mate-project | pymongo_mate/pkg/pandas_mate/pkg/rolex/__init__.py | Rolex.to_utctimestamp | def to_utctimestamp(self, dt):
"""Calculate number of seconds from UTC 1970-01-01 00:00:00.
When:
- dt doesn't have tzinfo: assume it's a utc time
- dt has tzinfo: use tzinfo
WARNING, if your datetime object doens't have ``tzinfo``, make sure
it's a UTC time, but **NOT a LOCAL TIME**.
**中文文档**
计算时间戳
若:
- 不带tzinfo: 则默认为是UTC time
- 带tzinfo: 使用tzinfo
"""
if dt.tzinfo is None:
dt = dt.replace(tzinfo=utc)
delta = dt - datetime(1970, 1, 1, tzinfo=utc)
return delta.total_seconds() | python | def to_utctimestamp(self, dt):
"""Calculate number of seconds from UTC 1970-01-01 00:00:00.
When:
- dt doesn't have tzinfo: assume it's a utc time
- dt has tzinfo: use tzinfo
WARNING, if your datetime object doens't have ``tzinfo``, make sure
it's a UTC time, but **NOT a LOCAL TIME**.
**中文文档**
计算时间戳
若:
- 不带tzinfo: 则默认为是UTC time
- 带tzinfo: 使用tzinfo
"""
if dt.tzinfo is None:
dt = dt.replace(tzinfo=utc)
delta = dt - datetime(1970, 1, 1, tzinfo=utc)
return delta.total_seconds() | [
"def",
"to_utctimestamp",
"(",
"self",
",",
"dt",
")",
":",
"if",
"dt",
".",
"tzinfo",
"is",
"None",
":",
"dt",
"=",
"dt",
".",
"replace",
"(",
"tzinfo",
"=",
"utc",
")",
"delta",
"=",
"dt",
"-",
"datetime",
"(",
"1970",
",",
"1",
",",
"1",
","... | Calculate number of seconds from UTC 1970-01-01 00:00:00.
When:
- dt doesn't have tzinfo: assume it's a utc time
- dt has tzinfo: use tzinfo
WARNING, if your datetime object doens't have ``tzinfo``, make sure
it's a UTC time, but **NOT a LOCAL TIME**.
**中文文档**
计算时间戳
若:
- 不带tzinfo: 则默认为是UTC time
- 带tzinfo: 使用tzinfo | [
"Calculate",
"number",
"of",
"seconds",
"from",
"UTC",
"1970",
"-",
"01",
"-",
"01",
"00",
":",
"00",
":",
"00",
"."
] | train | https://github.com/MacHu-GWU/pymongo_mate-project/blob/be53170c2db54cb705b9e548d32ef26c773ff7f3/pymongo_mate/pkg/pandas_mate/pkg/rolex/__init__.py#L217-L240 |
MacHu-GWU/pymongo_mate-project | pymongo_mate/pkg/pandas_mate/pkg/rolex/__init__.py | Rolex.from_utctimestamp | def from_utctimestamp(self, timestamp):
"""Create a **UTC datetime** object that number of seconds after
UTC 1970-01-01 00:00:00. If you want local time, use
:meth:`Rolex.from_timestamp`
Because python doesn't support negative timestamp to datetime
so we have to implement my own method.
**中文文档**
返回一个在UTC 1970-01-01 00:00:00 之后 #timestamp 秒后的时间。默认为
UTC时间。即返回的datetime不带tzinfo
"""
if timestamp >= 0:
return datetime.utcfromtimestamp(timestamp)
else:
return datetime(1970, 1, 1) + timedelta(seconds=timestamp) | python | def from_utctimestamp(self, timestamp):
"""Create a **UTC datetime** object that number of seconds after
UTC 1970-01-01 00:00:00. If you want local time, use
:meth:`Rolex.from_timestamp`
Because python doesn't support negative timestamp to datetime
so we have to implement my own method.
**中文文档**
返回一个在UTC 1970-01-01 00:00:00 之后 #timestamp 秒后的时间。默认为
UTC时间。即返回的datetime不带tzinfo
"""
if timestamp >= 0:
return datetime.utcfromtimestamp(timestamp)
else:
return datetime(1970, 1, 1) + timedelta(seconds=timestamp) | [
"def",
"from_utctimestamp",
"(",
"self",
",",
"timestamp",
")",
":",
"if",
"timestamp",
">=",
"0",
":",
"return",
"datetime",
".",
"utcfromtimestamp",
"(",
"timestamp",
")",
"else",
":",
"return",
"datetime",
"(",
"1970",
",",
"1",
",",
"1",
")",
"+",
... | Create a **UTC datetime** object that number of seconds after
UTC 1970-01-01 00:00:00. If you want local time, use
:meth:`Rolex.from_timestamp`
Because python doesn't support negative timestamp to datetime
so we have to implement my own method.
**中文文档**
返回一个在UTC 1970-01-01 00:00:00 之后 #timestamp 秒后的时间。默认为
UTC时间。即返回的datetime不带tzinfo | [
"Create",
"a",
"**",
"UTC",
"datetime",
"**",
"object",
"that",
"number",
"of",
"seconds",
"after",
"UTC",
"1970",
"-",
"01",
"-",
"01",
"00",
":",
"00",
":",
"00",
".",
"If",
"you",
"want",
"local",
"time",
"use",
":",
"meth",
":",
"Rolex",
".",
... | train | https://github.com/MacHu-GWU/pymongo_mate-project/blob/be53170c2db54cb705b9e548d32ef26c773ff7f3/pymongo_mate/pkg/pandas_mate/pkg/rolex/__init__.py#L242-L258 |
MacHu-GWU/pymongo_mate-project | pymongo_mate/pkg/pandas_mate/pkg/rolex/__init__.py | Rolex._freq_parser | def _freq_parser(self, freq):
"""Parse timedelta.
Valid keywords "days", "day", "d", "hours", "hour", "h",
"minutes", "minute", "min", "m", "seconds", "second", "sec", "s",
"weeks", "week", "w",
"""
freq = freq.lower().strip()
valid_keywords = [
"days", "day", "d",
"hours", "hour", "h",
"minutes", "minute", "min", "m",
"seconds", "second", "sec", "s",
"weeks", "week", "w",
]
error_message = "'%s' is invalid, use one of %s" % (
freq, valid_keywords)
try:
# day
for surfix in ["days", "day", "d"]:
if freq.endswith(surfix):
freq = freq.replace(surfix, "")
return timedelta(days=int(freq))
# hour
for surfix in ["hours", "hour", "h"]:
if freq.endswith(surfix):
freq = freq.replace(surfix, "")
return timedelta(hours=int(freq))
# minute
for surfix in ["minutes", "minute", "min", "m"]:
if freq.endswith(surfix):
freq = freq.replace(surfix, "")
return timedelta(minutes=int(freq))
# second
for surfix in ["seconds", "second", "sec", "s"]:
if freq.endswith(surfix):
freq = freq.replace(surfix, "")
return timedelta(seconds=int(freq))
# week
for surfix in ["weeks", "week", "w"]:
if freq.endswith(surfix):
freq = freq.replace(surfix, "")
return timedelta(days=int(freq) * 7)
except:
pass
raise ValueError(error_message) | python | def _freq_parser(self, freq):
"""Parse timedelta.
Valid keywords "days", "day", "d", "hours", "hour", "h",
"minutes", "minute", "min", "m", "seconds", "second", "sec", "s",
"weeks", "week", "w",
"""
freq = freq.lower().strip()
valid_keywords = [
"days", "day", "d",
"hours", "hour", "h",
"minutes", "minute", "min", "m",
"seconds", "second", "sec", "s",
"weeks", "week", "w",
]
error_message = "'%s' is invalid, use one of %s" % (
freq, valid_keywords)
try:
# day
for surfix in ["days", "day", "d"]:
if freq.endswith(surfix):
freq = freq.replace(surfix, "")
return timedelta(days=int(freq))
# hour
for surfix in ["hours", "hour", "h"]:
if freq.endswith(surfix):
freq = freq.replace(surfix, "")
return timedelta(hours=int(freq))
# minute
for surfix in ["minutes", "minute", "min", "m"]:
if freq.endswith(surfix):
freq = freq.replace(surfix, "")
return timedelta(minutes=int(freq))
# second
for surfix in ["seconds", "second", "sec", "s"]:
if freq.endswith(surfix):
freq = freq.replace(surfix, "")
return timedelta(seconds=int(freq))
# week
for surfix in ["weeks", "week", "w"]:
if freq.endswith(surfix):
freq = freq.replace(surfix, "")
return timedelta(days=int(freq) * 7)
except:
pass
raise ValueError(error_message) | [
"def",
"_freq_parser",
"(",
"self",
",",
"freq",
")",
":",
"freq",
"=",
"freq",
".",
"lower",
"(",
")",
".",
"strip",
"(",
")",
"valid_keywords",
"=",
"[",
"\"days\"",
",",
"\"day\"",
",",
"\"d\"",
",",
"\"hours\"",
",",
"\"hour\"",
",",
"\"h\"",
","... | Parse timedelta.
Valid keywords "days", "day", "d", "hours", "hour", "h",
"minutes", "minute", "min", "m", "seconds", "second", "sec", "s",
"weeks", "week", "w", | [
"Parse",
"timedelta",
"."
] | train | https://github.com/MacHu-GWU/pymongo_mate-project/blob/be53170c2db54cb705b9e548d32ef26c773ff7f3/pymongo_mate/pkg/pandas_mate/pkg/rolex/__init__.py#L297-L349 |
MacHu-GWU/pymongo_mate-project | pymongo_mate/pkg/pandas_mate/pkg/rolex/__init__.py | Rolex.weekday_series | def weekday_series(self, start, end, weekday, return_date=False):
"""Generate a datetime series with same weekday number.
ISO weekday number: Mon to Sun = 1 to 7
Usage::
>>> start, end = "2014-01-01 06:30:25", "2014-02-01 06:30:25"
>>> rolex.weekday_series(start, end, weekday=2) # All Tuesday
[
datetime(2014, 1, 7, 6, 30, 25),
datetime(2014, 1, 14, 6, 30, 25),
datetime(2014, 1, 21, 6, 30, 25),
datetime(2014, 1, 28, 6, 30, 25),
]
:param weekday: int or list of int
**中文文档**
生成星期数一致的时间序列。
"""
start = self.parse_datetime(start)
end = self.parse_datetime(end)
if isinstance(weekday, integer_types):
weekday = [weekday, ]
series = list()
for i in self.time_series(
start, end, freq="1day", return_date=return_date):
if i.isoweekday() in weekday:
series.append(i)
return series | python | def weekday_series(self, start, end, weekday, return_date=False):
"""Generate a datetime series with same weekday number.
ISO weekday number: Mon to Sun = 1 to 7
Usage::
>>> start, end = "2014-01-01 06:30:25", "2014-02-01 06:30:25"
>>> rolex.weekday_series(start, end, weekday=2) # All Tuesday
[
datetime(2014, 1, 7, 6, 30, 25),
datetime(2014, 1, 14, 6, 30, 25),
datetime(2014, 1, 21, 6, 30, 25),
datetime(2014, 1, 28, 6, 30, 25),
]
:param weekday: int or list of int
**中文文档**
生成星期数一致的时间序列。
"""
start = self.parse_datetime(start)
end = self.parse_datetime(end)
if isinstance(weekday, integer_types):
weekday = [weekday, ]
series = list()
for i in self.time_series(
start, end, freq="1day", return_date=return_date):
if i.isoweekday() in weekday:
series.append(i)
return series | [
"def",
"weekday_series",
"(",
"self",
",",
"start",
",",
"end",
",",
"weekday",
",",
"return_date",
"=",
"False",
")",
":",
"start",
"=",
"self",
".",
"parse_datetime",
"(",
"start",
")",
"end",
"=",
"self",
".",
"parse_datetime",
"(",
"end",
")",
"if"... | Generate a datetime series with same weekday number.
ISO weekday number: Mon to Sun = 1 to 7
Usage::
>>> start, end = "2014-01-01 06:30:25", "2014-02-01 06:30:25"
>>> rolex.weekday_series(start, end, weekday=2) # All Tuesday
[
datetime(2014, 1, 7, 6, 30, 25),
datetime(2014, 1, 14, 6, 30, 25),
datetime(2014, 1, 21, 6, 30, 25),
datetime(2014, 1, 28, 6, 30, 25),
]
:param weekday: int or list of int
**中文文档**
生成星期数一致的时间序列。 | [
"Generate",
"a",
"datetime",
"series",
"with",
"same",
"weekday",
"number",
"."
] | train | https://github.com/MacHu-GWU/pymongo_mate-project/blob/be53170c2db54cb705b9e548d32ef26c773ff7f3/pymongo_mate/pkg/pandas_mate/pkg/rolex/__init__.py#L461-L495 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.