repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
ThreatResponse/margaritashotgun | margaritashotgun/cli.py | Cli.check_directory_path | def check_directory_path(self, path):
"""
Ensure directory exists at the provided path
:type path: string
:param path: path to directory to check
"""
if os.path.isdir(path) is not True:
msg = "Directory Does Not Exist {}".format(path)
raise OSError(msg) | python | def check_directory_path(self, path):
"""
Ensure directory exists at the provided path
:type path: string
:param path: path to directory to check
"""
if os.path.isdir(path) is not True:
msg = "Directory Does Not Exist {}".format(path)
raise OSError(msg) | [
"def",
"check_directory_path",
"(",
"self",
",",
"path",
")",
":",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"path",
")",
"is",
"not",
"True",
":",
"msg",
"=",
"\"Directory Does Not Exist {}\"",
".",
"format",
"(",
"path",
")",
"raise",
"OSError",
"(",... | Ensure directory exists at the provided path
:type path: string
:param path: path to directory to check | [
"Ensure",
"directory",
"exists",
"at",
"the",
"provided",
"path"
] | 6dee53ef267959b214953439968244cc46a19690 | https://github.com/ThreatResponse/margaritashotgun/blob/6dee53ef267959b214953439968244cc46a19690/margaritashotgun/cli.py#L285-L294 | train | 212,000 |
ThreatResponse/margaritashotgun | margaritashotgun/cli.py | Cli.validate_config | def validate_config(self, config):
"""
Validate configuration dict keys are supported
:type config: dict
:param config: configuration dictionary
"""
try:
hosts = config['hosts']
except KeyError:
raise InvalidConfigurationError('hosts', "",
reason=('hosts configuration '
'section is required'))
for key in config.keys():
if key not in default_allowed_keys:
raise InvalidConfigurationError(key, config[key])
bucket = False
# optional configuration
try:
for key in config['aws'].keys():
if key == 'bucket' and config['aws'][key] is not None:
bucket = True
if key not in aws_allowed_keys:
raise InvalidConfigurationError(key, config['aws'][key])
except KeyError:
pass
# optional configuration
try:
for key in config['logging'].keys():
if key not in logging_allowed_keys:
raise InvalidConfigurationError(key, config['logging'][key])
except KeyError:
pass
# optional configuration
try:
for key in config['repository'].keys():
if key not in repository_allowed_keys:
raise InvalidConfigurationError(key, config['repository'][key])
except KeyError:
pass
# required configuration
if type(config['hosts']) is not list:
raise InvalidConfigurationError('hosts', config['hosts'],
reason="hosts must be a list")
filename = False
for host in config['hosts']:
for key in host.keys():
if key == 'filename' and host['filename'] is not None:
filename = True
if key == 'jump_host' and host['jump_host'] is not None:
for jump_key in host['jump_host'].keys():
if jump_key not in jump_host_allowed_keys:
raise InvalidConfigurationError(key, host['jump_host'])
if key not in host_allowed_keys:
raise InvalidConfigurationError(key, host[key])
if bucket and filename:
raise InvalidConfigurationError('bucket', config['aws']['bucket'],
reason=('bucket configuration is'
'incompatible with filename'
'configuration in hosts')) | python | def validate_config(self, config):
"""
Validate configuration dict keys are supported
:type config: dict
:param config: configuration dictionary
"""
try:
hosts = config['hosts']
except KeyError:
raise InvalidConfigurationError('hosts', "",
reason=('hosts configuration '
'section is required'))
for key in config.keys():
if key not in default_allowed_keys:
raise InvalidConfigurationError(key, config[key])
bucket = False
# optional configuration
try:
for key in config['aws'].keys():
if key == 'bucket' and config['aws'][key] is not None:
bucket = True
if key not in aws_allowed_keys:
raise InvalidConfigurationError(key, config['aws'][key])
except KeyError:
pass
# optional configuration
try:
for key in config['logging'].keys():
if key not in logging_allowed_keys:
raise InvalidConfigurationError(key, config['logging'][key])
except KeyError:
pass
# optional configuration
try:
for key in config['repository'].keys():
if key not in repository_allowed_keys:
raise InvalidConfigurationError(key, config['repository'][key])
except KeyError:
pass
# required configuration
if type(config['hosts']) is not list:
raise InvalidConfigurationError('hosts', config['hosts'],
reason="hosts must be a list")
filename = False
for host in config['hosts']:
for key in host.keys():
if key == 'filename' and host['filename'] is not None:
filename = True
if key == 'jump_host' and host['jump_host'] is not None:
for jump_key in host['jump_host'].keys():
if jump_key not in jump_host_allowed_keys:
raise InvalidConfigurationError(key, host['jump_host'])
if key not in host_allowed_keys:
raise InvalidConfigurationError(key, host[key])
if bucket and filename:
raise InvalidConfigurationError('bucket', config['aws']['bucket'],
reason=('bucket configuration is'
'incompatible with filename'
'configuration in hosts')) | [
"def",
"validate_config",
"(",
"self",
",",
"config",
")",
":",
"try",
":",
"hosts",
"=",
"config",
"[",
"'hosts'",
"]",
"except",
"KeyError",
":",
"raise",
"InvalidConfigurationError",
"(",
"'hosts'",
",",
"\"\"",
",",
"reason",
"=",
"(",
"'hosts configurat... | Validate configuration dict keys are supported
:type config: dict
:param config: configuration dictionary | [
"Validate",
"configuration",
"dict",
"keys",
"are",
"supported"
] | 6dee53ef267959b214953439968244cc46a19690 | https://github.com/ThreatResponse/margaritashotgun/blob/6dee53ef267959b214953439968244cc46a19690/margaritashotgun/cli.py#L306-L372 | train | 212,001 |
ThreatResponse/margaritashotgun | margaritashotgun/auth.py | Auth.load_key | def load_key(self, key_path, password):
"""
Creates paramiko rsa key
:type key_path: str
:param key_path: path to rsa key
:type password: str
:param password: password to try if rsa key is encrypted
"""
try:
return paramiko.RSAKey.from_private_key_file(key_path)
except PasswordRequiredException as ex:
return paramiko.RSAKey.from_private_key_file(key_path,
password=password) | python | def load_key(self, key_path, password):
"""
Creates paramiko rsa key
:type key_path: str
:param key_path: path to rsa key
:type password: str
:param password: password to try if rsa key is encrypted
"""
try:
return paramiko.RSAKey.from_private_key_file(key_path)
except PasswordRequiredException as ex:
return paramiko.RSAKey.from_private_key_file(key_path,
password=password) | [
"def",
"load_key",
"(",
"self",
",",
"key_path",
",",
"password",
")",
":",
"try",
":",
"return",
"paramiko",
".",
"RSAKey",
".",
"from_private_key_file",
"(",
"key_path",
")",
"except",
"PasswordRequiredException",
"as",
"ex",
":",
"return",
"paramiko",
".",
... | Creates paramiko rsa key
:type key_path: str
:param key_path: path to rsa key
:type password: str
:param password: password to try if rsa key is encrypted | [
"Creates",
"paramiko",
"rsa",
"key"
] | 6dee53ef267959b214953439968244cc46a19690 | https://github.com/ThreatResponse/margaritashotgun/blob/6dee53ef267959b214953439968244cc46a19690/margaritashotgun/auth.py#L42-L56 | train | 212,002 |
ThreatResponse/margaritashotgun | margaritashotgun/client.py | Client.run | def run(self):
"""
Captures remote hosts memory
"""
logger = logging.getLogger(__name__)
try:
# Check repository GPG settings before starting workers
# Handling this here prevents subprocesses from needing stdin access
repo_conf = self.config['repository']
repo = None
if repo_conf['enabled'] and repo_conf['gpg_verify']:
try:
repo = Repository(repo_conf['url'],
repo_conf['gpg_verify'])
repo.init_gpg()
except Exception as ex:
# Do not prompt to install gpg keys unless running interactively
if repo is not None and self.library is False:
if isinstance(ex, RepositoryUntrustedSigningKeyError):
installed = repo.prompt_for_install()
if installed is False:
logger.critical(("repository signature not "
"installed, install the "
"signature manually or use "
"the --gpg-no-verify flag "
"to bypass this check"))
quit(1)
else:
logger.critical(ex)
quit(1)
conf = self.map_config()
workers = Workers(conf, self.config['workers'], name=self.name, library=self.library)
description = 'memory capture action'
results = workers.spawn(description)
self.statistics(results)
if self.library is True:
return dict([('total', self.total),
('completed', self.completed_addresses),
('failed', self.failed_addresses)])
else:
logger.info(("{0} hosts processed. completed: {1} "
"failed {2}".format(self.total, self.completed,
self.failed)))
logger.info("completed_hosts: {0}".format(self.completed_addresses))
logger.info("failed_hosts: {0}".format(self.failed_addresses))
quit()
except KeyboardInterrupt:
workers.cleanup(terminate=True)
if self.library:
raise
else:
quit(1) | python | def run(self):
"""
Captures remote hosts memory
"""
logger = logging.getLogger(__name__)
try:
# Check repository GPG settings before starting workers
# Handling this here prevents subprocesses from needing stdin access
repo_conf = self.config['repository']
repo = None
if repo_conf['enabled'] and repo_conf['gpg_verify']:
try:
repo = Repository(repo_conf['url'],
repo_conf['gpg_verify'])
repo.init_gpg()
except Exception as ex:
# Do not prompt to install gpg keys unless running interactively
if repo is not None and self.library is False:
if isinstance(ex, RepositoryUntrustedSigningKeyError):
installed = repo.prompt_for_install()
if installed is False:
logger.critical(("repository signature not "
"installed, install the "
"signature manually or use "
"the --gpg-no-verify flag "
"to bypass this check"))
quit(1)
else:
logger.critical(ex)
quit(1)
conf = self.map_config()
workers = Workers(conf, self.config['workers'], name=self.name, library=self.library)
description = 'memory capture action'
results = workers.spawn(description)
self.statistics(results)
if self.library is True:
return dict([('total', self.total),
('completed', self.completed_addresses),
('failed', self.failed_addresses)])
else:
logger.info(("{0} hosts processed. completed: {1} "
"failed {2}".format(self.total, self.completed,
self.failed)))
logger.info("completed_hosts: {0}".format(self.completed_addresses))
logger.info("failed_hosts: {0}".format(self.failed_addresses))
quit()
except KeyboardInterrupt:
workers.cleanup(terminate=True)
if self.library:
raise
else:
quit(1) | [
"def",
"run",
"(",
"self",
")",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"__name__",
")",
"try",
":",
"# Check repository GPG settings before starting workers",
"# Handling this here prevents subprocesses from needing stdin access",
"repo_conf",
"=",
"self",
".... | Captures remote hosts memory | [
"Captures",
"remote",
"hosts",
"memory"
] | 6dee53ef267959b214953439968244cc46a19690 | https://github.com/ThreatResponse/margaritashotgun/blob/6dee53ef267959b214953439968244cc46a19690/margaritashotgun/client.py#L51-L104 | train | 212,003 |
ThreatResponse/margaritashotgun | margaritashotgun/memory.py | Memory.capture | def capture(self, tunnel_addr, tunnel_port, filename=None,
bucket=None, destination=None):
"""
Captures memory based on the provided OutputDestination
:type tunnel_addr: str
:param tunnel_port: ssh tunnel hostname or ip
:type tunnel_port: int
:param tunnel_port: ssh tunnel port
:type filename: str
:param filename: memory dump output filename
:type bucket: str
:param bucket: output s3 bucket
:type destination: :py:class:`margaritashotgun.memory.OutputDestinations`
:param destination: OutputDestinations member
"""
if filename is None:
raise MemoryCaptureAttributeMissingError('filename')
if destination == OutputDestinations.local:
logger.info("{0}: dumping to file://{1}".format(self.remote_addr,
filename))
result = self.to_file(filename, tunnel_addr, tunnel_port)
elif destination == OutputDestinations.s3:
if bucket is None:
raise MemoryCaptureAttributeMissingError('bucket')
logger.info(("{0}: dumping memory to s3://{1}/"
"{2}".format(self.remote_addr, bucket, filename)))
result = self.to_s3(bucket, filename, tunnel_addr, tunnel_port)
else:
raise MemoryCaptureOutputMissingError(self.remote_addr)
return result | python | def capture(self, tunnel_addr, tunnel_port, filename=None,
bucket=None, destination=None):
"""
Captures memory based on the provided OutputDestination
:type tunnel_addr: str
:param tunnel_port: ssh tunnel hostname or ip
:type tunnel_port: int
:param tunnel_port: ssh tunnel port
:type filename: str
:param filename: memory dump output filename
:type bucket: str
:param bucket: output s3 bucket
:type destination: :py:class:`margaritashotgun.memory.OutputDestinations`
:param destination: OutputDestinations member
"""
if filename is None:
raise MemoryCaptureAttributeMissingError('filename')
if destination == OutputDestinations.local:
logger.info("{0}: dumping to file://{1}".format(self.remote_addr,
filename))
result = self.to_file(filename, tunnel_addr, tunnel_port)
elif destination == OutputDestinations.s3:
if bucket is None:
raise MemoryCaptureAttributeMissingError('bucket')
logger.info(("{0}: dumping memory to s3://{1}/"
"{2}".format(self.remote_addr, bucket, filename)))
result = self.to_s3(bucket, filename, tunnel_addr, tunnel_port)
else:
raise MemoryCaptureOutputMissingError(self.remote_addr)
return result | [
"def",
"capture",
"(",
"self",
",",
"tunnel_addr",
",",
"tunnel_port",
",",
"filename",
"=",
"None",
",",
"bucket",
"=",
"None",
",",
"destination",
"=",
"None",
")",
":",
"if",
"filename",
"is",
"None",
":",
"raise",
"MemoryCaptureAttributeMissingError",
"(... | Captures memory based on the provided OutputDestination
:type tunnel_addr: str
:param tunnel_port: ssh tunnel hostname or ip
:type tunnel_port: int
:param tunnel_port: ssh tunnel port
:type filename: str
:param filename: memory dump output filename
:type bucket: str
:param bucket: output s3 bucket
:type destination: :py:class:`margaritashotgun.memory.OutputDestinations`
:param destination: OutputDestinations member | [
"Captures",
"memory",
"based",
"on",
"the",
"provided",
"OutputDestination"
] | 6dee53ef267959b214953439968244cc46a19690 | https://github.com/ThreatResponse/margaritashotgun/blob/6dee53ef267959b214953439968244cc46a19690/margaritashotgun/memory.py#L63-L94 | train | 212,004 |
ThreatResponse/margaritashotgun | margaritashotgun/memory.py | Memory.to_file | def to_file(self, filename, tunnel_addr, tunnel_port):
"""
Writes memory dump to a local file
:type filename: str
:param filename: memory dump output filename
:type tunnel_addr: str
:param tunnel_port: ssh tunnel hostname or ip
:type tunnel_port: int
:param tunnel_port: ssh tunnel port
"""
if self.progressbar:
self.bar = ProgressBar(widgets=self.widgets,
maxval=self.max_size).start()
self.bar.start()
with open(filename, 'wb') as self.outfile:
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock.connect((tunnel_addr, tunnel_port))
self.sock.settimeout(self.sock_timeout)
bytes_since_update = 0
while True:
try:
data = self.sock.recv(self.recv_size)
data_length = len(data)
if not data:
break
self.outfile.write(data)
self.transfered = self.transfered + data_length
bytes_since_update += data_length
data = None
data_length = 0
if bytes_since_update > self.update_threshold:
self.update_progress()
bytes_since_update = 0
except (socket.timeout, socket.error) as ex:
if isinstance(ex, socket.timeout):
break
elif isinstance(ex, socket.error):
if ex.errno == errno.EINTR:
pass
else:
self.cleanup()
raise
else:
self.cleanup()
raise
self.cleanup()
logger.info('{0}: capture complete: {1}'.format(self.remote_addr,
filename))
return True | python | def to_file(self, filename, tunnel_addr, tunnel_port):
"""
Writes memory dump to a local file
:type filename: str
:param filename: memory dump output filename
:type tunnel_addr: str
:param tunnel_port: ssh tunnel hostname or ip
:type tunnel_port: int
:param tunnel_port: ssh tunnel port
"""
if self.progressbar:
self.bar = ProgressBar(widgets=self.widgets,
maxval=self.max_size).start()
self.bar.start()
with open(filename, 'wb') as self.outfile:
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock.connect((tunnel_addr, tunnel_port))
self.sock.settimeout(self.sock_timeout)
bytes_since_update = 0
while True:
try:
data = self.sock.recv(self.recv_size)
data_length = len(data)
if not data:
break
self.outfile.write(data)
self.transfered = self.transfered + data_length
bytes_since_update += data_length
data = None
data_length = 0
if bytes_since_update > self.update_threshold:
self.update_progress()
bytes_since_update = 0
except (socket.timeout, socket.error) as ex:
if isinstance(ex, socket.timeout):
break
elif isinstance(ex, socket.error):
if ex.errno == errno.EINTR:
pass
else:
self.cleanup()
raise
else:
self.cleanup()
raise
self.cleanup()
logger.info('{0}: capture complete: {1}'.format(self.remote_addr,
filename))
return True | [
"def",
"to_file",
"(",
"self",
",",
"filename",
",",
"tunnel_addr",
",",
"tunnel_port",
")",
":",
"if",
"self",
".",
"progressbar",
":",
"self",
".",
"bar",
"=",
"ProgressBar",
"(",
"widgets",
"=",
"self",
".",
"widgets",
",",
"maxval",
"=",
"self",
".... | Writes memory dump to a local file
:type filename: str
:param filename: memory dump output filename
:type tunnel_addr: str
:param tunnel_port: ssh tunnel hostname or ip
:type tunnel_port: int
:param tunnel_port: ssh tunnel port | [
"Writes",
"memory",
"dump",
"to",
"a",
"local",
"file"
] | 6dee53ef267959b214953439968244cc46a19690 | https://github.com/ThreatResponse/margaritashotgun/blob/6dee53ef267959b214953439968244cc46a19690/margaritashotgun/memory.py#L96-L148 | train | 212,005 |
ThreatResponse/margaritashotgun | margaritashotgun/memory.py | Memory.update_progress | def update_progress(self, complete=False):
"""
Logs capture progress
:type complete: bool
:params complete: toggle to finish ncurses progress bar
"""
if self.progressbar:
try:
self.bar.update(self.transfered)
except Exception as e:
logger.debug("{0}: {1}, {2} exceeds memsize {3}".format(
self.remote_addr,
e,
self.transfered,
self.max_size))
if complete:
self.bar.update(self.max_size)
self.bar.finish()
else:
percent = int(100 * float(self.transfered) / float(self.max_size))
# printe a message at 10%, 20%, etc...
if percent % 10 == 0:
if self.progress != percent:
logger.info("{0}: capture {1}% complete".format(
self.remote_addr, percent))
self.progress = percent | python | def update_progress(self, complete=False):
"""
Logs capture progress
:type complete: bool
:params complete: toggle to finish ncurses progress bar
"""
if self.progressbar:
try:
self.bar.update(self.transfered)
except Exception as e:
logger.debug("{0}: {1}, {2} exceeds memsize {3}".format(
self.remote_addr,
e,
self.transfered,
self.max_size))
if complete:
self.bar.update(self.max_size)
self.bar.finish()
else:
percent = int(100 * float(self.transfered) / float(self.max_size))
# printe a message at 10%, 20%, etc...
if percent % 10 == 0:
if self.progress != percent:
logger.info("{0}: capture {1}% complete".format(
self.remote_addr, percent))
self.progress = percent | [
"def",
"update_progress",
"(",
"self",
",",
"complete",
"=",
"False",
")",
":",
"if",
"self",
".",
"progressbar",
":",
"try",
":",
"self",
".",
"bar",
".",
"update",
"(",
"self",
".",
"transfered",
")",
"except",
"Exception",
"as",
"e",
":",
"logger",
... | Logs capture progress
:type complete: bool
:params complete: toggle to finish ncurses progress bar | [
"Logs",
"capture",
"progress"
] | 6dee53ef267959b214953439968244cc46a19690 | https://github.com/ThreatResponse/margaritashotgun/blob/6dee53ef267959b214953439968244cc46a19690/margaritashotgun/memory.py#L214-L240 | train | 212,006 |
ThreatResponse/margaritashotgun | margaritashotgun/memory.py | Memory.cleanup | def cleanup(self):
"""
Release resources used during memory capture
"""
if self.sock is not None:
self.sock.close()
if self.outfile is not None:
self.outfile.close()
if self.bar is not None:
self.update_progress(complete=True) | python | def cleanup(self):
"""
Release resources used during memory capture
"""
if self.sock is not None:
self.sock.close()
if self.outfile is not None:
self.outfile.close()
if self.bar is not None:
self.update_progress(complete=True) | [
"def",
"cleanup",
"(",
"self",
")",
":",
"if",
"self",
".",
"sock",
"is",
"not",
"None",
":",
"self",
".",
"sock",
".",
"close",
"(",
")",
"if",
"self",
".",
"outfile",
"is",
"not",
"None",
":",
"self",
".",
"outfile",
".",
"close",
"(",
")",
"... | Release resources used during memory capture | [
"Release",
"resources",
"used",
"during",
"memory",
"capture"
] | 6dee53ef267959b214953439968244cc46a19690 | https://github.com/ThreatResponse/margaritashotgun/blob/6dee53ef267959b214953439968244cc46a19690/margaritashotgun/memory.py#L242-L251 | train | 212,007 |
ThreatResponse/margaritashotgun | margaritashotgun/repository.py | Repository.init_gpg | def init_gpg(self):
"""
Initialize gpg object and check if repository signing key is trusted
"""
if self.gpg_verify:
logger.debug("gpg verification enabled, initializing gpg")
gpg_home = os.path.expanduser('~/.gnupg')
self.gpg = gnupg.GPG(gnupghome=gpg_home)
self.key_path, self.key_info = self.get_signing_key()
logger.debug("{0} {1}".format(self.key_path, self.key_info))
self.check_signing_key() | python | def init_gpg(self):
"""
Initialize gpg object and check if repository signing key is trusted
"""
if self.gpg_verify:
logger.debug("gpg verification enabled, initializing gpg")
gpg_home = os.path.expanduser('~/.gnupg')
self.gpg = gnupg.GPG(gnupghome=gpg_home)
self.key_path, self.key_info = self.get_signing_key()
logger.debug("{0} {1}".format(self.key_path, self.key_info))
self.check_signing_key() | [
"def",
"init_gpg",
"(",
"self",
")",
":",
"if",
"self",
".",
"gpg_verify",
":",
"logger",
".",
"debug",
"(",
"\"gpg verification enabled, initializing gpg\"",
")",
"gpg_home",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"'~/.gnupg'",
")",
"self",
".",
"g... | Initialize gpg object and check if repository signing key is trusted | [
"Initialize",
"gpg",
"object",
"and",
"check",
"if",
"repository",
"signing",
"key",
"is",
"trusted"
] | 6dee53ef267959b214953439968244cc46a19690 | https://github.com/ThreatResponse/margaritashotgun/blob/6dee53ef267959b214953439968244cc46a19690/margaritashotgun/repository.py#L45-L55 | train | 212,008 |
ThreatResponse/margaritashotgun | margaritashotgun/repository.py | Repository.get_signing_key | def get_signing_key(self):
"""
Download a local copy of repo signing key for installation
"""
"""
Download a local copy of repo signing key key metadata.
Fixes #17 Scan Keys no available in all GPG versions.
"""
tmp_key_path = "/tmp/{0}".format(self.repo_signing_key)
tmp_metadata_path = "/tmp/{0}".format(self.key_metadata)
repo_key_path = "{0}/{1}".format(self.url, self.repo_signing_key)
repo_metadata_path = "{0}/{1}".format(self.url, self.key_metadata)
req_key = requests.get(repo_key_path)
req_metadata = requests.get(repo_metadata_path)
# Fetch the key to disk
if req_key.status_code is 200:
logger.debug(("found repository signing key at "
"{0}".format(repo_key_path)))
self.raw_key = req_key.content
with open(tmp_key_path, 'wb') as f:
f.write(self.raw_key)
else:
raise RepositoryMissingSigningKeyError(repo_key_path)
# Fetch the fingerprint from the metadata
if req_metadata.status_code is 200:
logger.debug(("found key metadata at "
"{0}".format(repo_metadata_path)))
print(req_metadata.content)
key_info = json.loads(req_metadata.content.decode('utf-8'))
else:
RepositoryMissingKeyMetadataError
return (tmp_key_path, key_info) | python | def get_signing_key(self):
"""
Download a local copy of repo signing key for installation
"""
"""
Download a local copy of repo signing key key metadata.
Fixes #17 Scan Keys no available in all GPG versions.
"""
tmp_key_path = "/tmp/{0}".format(self.repo_signing_key)
tmp_metadata_path = "/tmp/{0}".format(self.key_metadata)
repo_key_path = "{0}/{1}".format(self.url, self.repo_signing_key)
repo_metadata_path = "{0}/{1}".format(self.url, self.key_metadata)
req_key = requests.get(repo_key_path)
req_metadata = requests.get(repo_metadata_path)
# Fetch the key to disk
if req_key.status_code is 200:
logger.debug(("found repository signing key at "
"{0}".format(repo_key_path)))
self.raw_key = req_key.content
with open(tmp_key_path, 'wb') as f:
f.write(self.raw_key)
else:
raise RepositoryMissingSigningKeyError(repo_key_path)
# Fetch the fingerprint from the metadata
if req_metadata.status_code is 200:
logger.debug(("found key metadata at "
"{0}".format(repo_metadata_path)))
print(req_metadata.content)
key_info = json.loads(req_metadata.content.decode('utf-8'))
else:
RepositoryMissingKeyMetadataError
return (tmp_key_path, key_info) | [
"def",
"get_signing_key",
"(",
"self",
")",
":",
"\"\"\"\n Download a local copy of repo signing key key metadata.\n Fixes #17 Scan Keys no available in all GPG versions.\n \"\"\"",
"tmp_key_path",
"=",
"\"/tmp/{0}\"",
".",
"format",
"(",
"self",
".",
"repo_signing... | Download a local copy of repo signing key for installation | [
"Download",
"a",
"local",
"copy",
"of",
"repo",
"signing",
"key",
"for",
"installation"
] | 6dee53ef267959b214953439968244cc46a19690 | https://github.com/ThreatResponse/margaritashotgun/blob/6dee53ef267959b214953439968244cc46a19690/margaritashotgun/repository.py#L57-L95 | train | 212,009 |
ThreatResponse/margaritashotgun | margaritashotgun/repository.py | Repository.check_signing_key | def check_signing_key(self):
"""
Check that repo signing key is trusted by gpg keychain
"""
user_keys = self.gpg.list_keys()
if len(user_keys) > 0:
trusted = False
for key in user_keys:
if key['fingerprint'] == self.key_info['fingerprint']:
trusted = True
logger.debug(("repo signing key trusted in user keyring, "
"fingerprint {0}".format(key['fingerprint'])))
else:
trusted = False
if trusted is False:
repo_key_url = "{0}/{1}".format(self.url, self.repo_signing_key)
raise RepositoryUntrustedSigningKeyError(repo_key_url,
self.key_info['fingerprint']) | python | def check_signing_key(self):
"""
Check that repo signing key is trusted by gpg keychain
"""
user_keys = self.gpg.list_keys()
if len(user_keys) > 0:
trusted = False
for key in user_keys:
if key['fingerprint'] == self.key_info['fingerprint']:
trusted = True
logger.debug(("repo signing key trusted in user keyring, "
"fingerprint {0}".format(key['fingerprint'])))
else:
trusted = False
if trusted is False:
repo_key_url = "{0}/{1}".format(self.url, self.repo_signing_key)
raise RepositoryUntrustedSigningKeyError(repo_key_url,
self.key_info['fingerprint']) | [
"def",
"check_signing_key",
"(",
"self",
")",
":",
"user_keys",
"=",
"self",
".",
"gpg",
".",
"list_keys",
"(",
")",
"if",
"len",
"(",
"user_keys",
")",
">",
"0",
":",
"trusted",
"=",
"False",
"for",
"key",
"in",
"user_keys",
":",
"if",
"key",
"[",
... | Check that repo signing key is trusted by gpg keychain | [
"Check",
"that",
"repo",
"signing",
"key",
"is",
"trusted",
"by",
"gpg",
"keychain"
] | 6dee53ef267959b214953439968244cc46a19690 | https://github.com/ThreatResponse/margaritashotgun/blob/6dee53ef267959b214953439968244cc46a19690/margaritashotgun/repository.py#L97-L114 | train | 212,010 |
ThreatResponse/margaritashotgun | margaritashotgun/repository.py | Repository.prompt_for_install | def prompt_for_install(self):
"""
Prompt user to install untrusted repo signing key
"""
print(self.key_info)
repo_key_url = "{0}/{1}".format(self.url, self.repo_signing_key)
print(("warning: Repository key untrusted \n"
"Importing GPG key 0x{0}:\n"
" Userid: \"{1}\"\n"
" From : {2}".format(self.key_info['fingerprint'],
self.key_info['uids'][0],
repo_key_url)))
response = prompt(u'Is this ok: [y/N] ')
if response == 'y':
self.install_key(self.raw_key)
return True
else:
return False | python | def prompt_for_install(self):
"""
Prompt user to install untrusted repo signing key
"""
print(self.key_info)
repo_key_url = "{0}/{1}".format(self.url, self.repo_signing_key)
print(("warning: Repository key untrusted \n"
"Importing GPG key 0x{0}:\n"
" Userid: \"{1}\"\n"
" From : {2}".format(self.key_info['fingerprint'],
self.key_info['uids'][0],
repo_key_url)))
response = prompt(u'Is this ok: [y/N] ')
if response == 'y':
self.install_key(self.raw_key)
return True
else:
return False | [
"def",
"prompt_for_install",
"(",
"self",
")",
":",
"print",
"(",
"self",
".",
"key_info",
")",
"repo_key_url",
"=",
"\"{0}/{1}\"",
".",
"format",
"(",
"self",
".",
"url",
",",
"self",
".",
"repo_signing_key",
")",
"print",
"(",
"(",
"\"warning: Repository k... | Prompt user to install untrusted repo signing key | [
"Prompt",
"user",
"to",
"install",
"untrusted",
"repo",
"signing",
"key"
] | 6dee53ef267959b214953439968244cc46a19690 | https://github.com/ThreatResponse/margaritashotgun/blob/6dee53ef267959b214953439968244cc46a19690/margaritashotgun/repository.py#L116-L133 | train | 212,011 |
ThreatResponse/margaritashotgun | margaritashotgun/repository.py | Repository.install_key | def install_key(self, key_data):
"""
Install untrusted repo signing key
"""
logger.info(("importing repository signing key {0} "
"{1}".format(self.key_info['fingerprint'],
self.key_info['uids'][0])))
import_result = self.gpg.import_keys(key_data)
logger.debug("import results: {0}".format(import_result.results)) | python | def install_key(self, key_data):
"""
Install untrusted repo signing key
"""
logger.info(("importing repository signing key {0} "
"{1}".format(self.key_info['fingerprint'],
self.key_info['uids'][0])))
import_result = self.gpg.import_keys(key_data)
logger.debug("import results: {0}".format(import_result.results)) | [
"def",
"install_key",
"(",
"self",
",",
"key_data",
")",
":",
"logger",
".",
"info",
"(",
"(",
"\"importing repository signing key {0} \"",
"\"{1}\"",
".",
"format",
"(",
"self",
".",
"key_info",
"[",
"'fingerprint'",
"]",
",",
"self",
".",
"key_info",
"[",
... | Install untrusted repo signing key | [
"Install",
"untrusted",
"repo",
"signing",
"key"
] | 6dee53ef267959b214953439968244cc46a19690 | https://github.com/ThreatResponse/margaritashotgun/blob/6dee53ef267959b214953439968244cc46a19690/margaritashotgun/repository.py#L135-L143 | train | 212,012 |
ThreatResponse/margaritashotgun | margaritashotgun/repository.py | Repository.fetch | def fetch(self, kernel_version, manifest_type):
"""
Search repository for kernel module matching kernel_version
:type kernel_version: str
:param kernel_version: kernel version to search repository on
:type manifest_type: str
:param manifest_type: kernel module manifest to search on
"""
metadata = self.get_metadata()
logger.debug("parsed metadata: {0}".format(metadata))
manifest = self.get_manifest(metadata['manifests'][manifest_type])
try:
module = manifest[kernel_version]
logger.debug("found module {0}".format(module))
except KeyError:
raise KernelModuleNotFoundError(kernel_version, self.url)
path = self.fetch_module(module)
return path | python | def fetch(self, kernel_version, manifest_type):
"""
Search repository for kernel module matching kernel_version
:type kernel_version: str
:param kernel_version: kernel version to search repository on
:type manifest_type: str
:param manifest_type: kernel module manifest to search on
"""
metadata = self.get_metadata()
logger.debug("parsed metadata: {0}".format(metadata))
manifest = self.get_manifest(metadata['manifests'][manifest_type])
try:
module = manifest[kernel_version]
logger.debug("found module {0}".format(module))
except KeyError:
raise KernelModuleNotFoundError(kernel_version, self.url)
path = self.fetch_module(module)
return path | [
"def",
"fetch",
"(",
"self",
",",
"kernel_version",
",",
"manifest_type",
")",
":",
"metadata",
"=",
"self",
".",
"get_metadata",
"(",
")",
"logger",
".",
"debug",
"(",
"\"parsed metadata: {0}\"",
".",
"format",
"(",
"metadata",
")",
")",
"manifest",
"=",
... | Search repository for kernel module matching kernel_version
:type kernel_version: str
:param kernel_version: kernel version to search repository on
:type manifest_type: str
:param manifest_type: kernel module manifest to search on | [
"Search",
"repository",
"for",
"kernel",
"module",
"matching",
"kernel_version"
] | 6dee53ef267959b214953439968244cc46a19690 | https://github.com/ThreatResponse/margaritashotgun/blob/6dee53ef267959b214953439968244cc46a19690/margaritashotgun/repository.py#L145-L165 | train | 212,013 |
ThreatResponse/margaritashotgun | margaritashotgun/repository.py | Repository.get_metadata | def get_metadata(self):
"""
Fetch repository repomd.xml file
"""
metadata_path = "{}/{}/{}".format(self.url,
self.metadata_dir,
self.metadata_file)
metadata_sig_path = "{}/{}/{}.sig".format(self.url.rstrip('/'),
self.metadata_dir,
self.metadata_file)
# load metadata
req = requests.get(metadata_path)
if req.status_code is 200:
raw_metadata = req.content
else:
raise RepositoryError(metadata_path, ("status code not 200: "
"{}".format(req.status_code)))
if self.gpg_verify:
self.verify_data_signature(metadata_sig_path, metadata_path,
raw_metadata)
return self.parse_metadata(raw_metadata) | python | def get_metadata(self):
"""
Fetch repository repomd.xml file
"""
metadata_path = "{}/{}/{}".format(self.url,
self.metadata_dir,
self.metadata_file)
metadata_sig_path = "{}/{}/{}.sig".format(self.url.rstrip('/'),
self.metadata_dir,
self.metadata_file)
# load metadata
req = requests.get(metadata_path)
if req.status_code is 200:
raw_metadata = req.content
else:
raise RepositoryError(metadata_path, ("status code not 200: "
"{}".format(req.status_code)))
if self.gpg_verify:
self.verify_data_signature(metadata_sig_path, metadata_path,
raw_metadata)
return self.parse_metadata(raw_metadata) | [
"def",
"get_metadata",
"(",
"self",
")",
":",
"metadata_path",
"=",
"\"{}/{}/{}\"",
".",
"format",
"(",
"self",
".",
"url",
",",
"self",
".",
"metadata_dir",
",",
"self",
".",
"metadata_file",
")",
"metadata_sig_path",
"=",
"\"{}/{}/{}.sig\"",
".",
"format",
... | Fetch repository repomd.xml file | [
"Fetch",
"repository",
"repomd",
".",
"xml",
"file"
] | 6dee53ef267959b214953439968244cc46a19690 | https://github.com/ThreatResponse/margaritashotgun/blob/6dee53ef267959b214953439968244cc46a19690/margaritashotgun/repository.py#L167-L189 | train | 212,014 |
ThreatResponse/margaritashotgun | margaritashotgun/repository.py | Repository.parse_metadata | def parse_metadata(self, metadata_xml):
"""
Parse repomd.xml file
:type metadata_xml: str
:param metadata_xml: raw xml representation of repomd.xml
"""
try:
metadata = dict()
mdata = xmltodict.parse(metadata_xml)['metadata']
metadata['revision'] = mdata['revision']
metadata['manifests'] = dict()
# check if multiple manifests are present
if type(mdata['data']) is list:
manifests = mdata['data']
else:
manifests = [mdata['data']]
for manifest in manifests:
manifest_dict = dict()
manifest_dict['type'] = manifest['@type']
manifest_dict['checksum'] = manifest['checksum']
manifest_dict['open_checksum'] = manifest['open_checksum']
manifest_dict['location'] = manifest['location']['@href']
manifest_dict['timestamp'] = datetime.fromtimestamp(
int(manifest['timestamp']))
manifest_dict['size'] = int(manifest['size'])
manifest_dict['open_size'] = int(manifest['open_size'])
metadata['manifests'][manifest['@type']] = manifest_dict
except Exception as e:
raise RepositoryError("{0}/{1}".format(self.url,self.metadata_dir,
self.metadata_file), e)
return metadata | python | def parse_metadata(self, metadata_xml):
"""
Parse repomd.xml file
:type metadata_xml: str
:param metadata_xml: raw xml representation of repomd.xml
"""
try:
metadata = dict()
mdata = xmltodict.parse(metadata_xml)['metadata']
metadata['revision'] = mdata['revision']
metadata['manifests'] = dict()
# check if multiple manifests are present
if type(mdata['data']) is list:
manifests = mdata['data']
else:
manifests = [mdata['data']]
for manifest in manifests:
manifest_dict = dict()
manifest_dict['type'] = manifest['@type']
manifest_dict['checksum'] = manifest['checksum']
manifest_dict['open_checksum'] = manifest['open_checksum']
manifest_dict['location'] = manifest['location']['@href']
manifest_dict['timestamp'] = datetime.fromtimestamp(
int(manifest['timestamp']))
manifest_dict['size'] = int(manifest['size'])
manifest_dict['open_size'] = int(manifest['open_size'])
metadata['manifests'][manifest['@type']] = manifest_dict
except Exception as e:
raise RepositoryError("{0}/{1}".format(self.url,self.metadata_dir,
self.metadata_file), e)
return metadata | [
"def",
"parse_metadata",
"(",
"self",
",",
"metadata_xml",
")",
":",
"try",
":",
"metadata",
"=",
"dict",
"(",
")",
"mdata",
"=",
"xmltodict",
".",
"parse",
"(",
"metadata_xml",
")",
"[",
"'metadata'",
"]",
"metadata",
"[",
"'revision'",
"]",
"=",
"mdata... | Parse repomd.xml file
:type metadata_xml: str
:param metadata_xml: raw xml representation of repomd.xml | [
"Parse",
"repomd",
".",
"xml",
"file"
] | 6dee53ef267959b214953439968244cc46a19690 | https://github.com/ThreatResponse/margaritashotgun/blob/6dee53ef267959b214953439968244cc46a19690/margaritashotgun/repository.py#L191-L226 | train | 212,015 |
ThreatResponse/margaritashotgun | margaritashotgun/repository.py | Repository.get_manifest | def get_manifest(self, metadata):
"""
Get latest manifest as specified in repomd.xml
:type metadata: dict
:param metadata: dictionary representation of repomd.xml
"""
manifest_path = "{0}/{1}".format(self.url, metadata['location'])
req = requests.get(manifest_path, stream=True)
if req.status_code is 200:
gz_manifest = req.raw.read()
self.verify_checksum(gz_manifest, metadata['checksum'],
metadata['location'])
manifest = self.unzip_manifest(gz_manifest)
self.verify_checksum(manifest, metadata['open_checksum'],
metadata['location'].rstrip('.gz'))
return self.parse_manifest(manifest) | python | def get_manifest(self, metadata):
"""
Get latest manifest as specified in repomd.xml
:type metadata: dict
:param metadata: dictionary representation of repomd.xml
"""
manifest_path = "{0}/{1}".format(self.url, metadata['location'])
req = requests.get(manifest_path, stream=True)
if req.status_code is 200:
gz_manifest = req.raw.read()
self.verify_checksum(gz_manifest, metadata['checksum'],
metadata['location'])
manifest = self.unzip_manifest(gz_manifest)
self.verify_checksum(manifest, metadata['open_checksum'],
metadata['location'].rstrip('.gz'))
return self.parse_manifest(manifest) | [
"def",
"get_manifest",
"(",
"self",
",",
"metadata",
")",
":",
"manifest_path",
"=",
"\"{0}/{1}\"",
".",
"format",
"(",
"self",
".",
"url",
",",
"metadata",
"[",
"'location'",
"]",
")",
"req",
"=",
"requests",
".",
"get",
"(",
"manifest_path",
",",
"stre... | Get latest manifest as specified in repomd.xml
:type metadata: dict
:param metadata: dictionary representation of repomd.xml | [
"Get",
"latest",
"manifest",
"as",
"specified",
"in",
"repomd",
".",
"xml"
] | 6dee53ef267959b214953439968244cc46a19690 | https://github.com/ThreatResponse/margaritashotgun/blob/6dee53ef267959b214953439968244cc46a19690/margaritashotgun/repository.py#L228-L246 | train | 212,016 |
ThreatResponse/margaritashotgun | margaritashotgun/repository.py | Repository.unzip_manifest | def unzip_manifest(self, raw_manifest):
"""
Decompress gzip encoded manifest
:type raw_manifest: str
:param raw_manifest: compressed gzip manifest file content
"""
buf = BytesIO(raw_manifest)
f = gzip.GzipFile(fileobj=buf)
manifest = f.read()
return manifest | python | def unzip_manifest(self, raw_manifest):
"""
Decompress gzip encoded manifest
:type raw_manifest: str
:param raw_manifest: compressed gzip manifest file content
"""
buf = BytesIO(raw_manifest)
f = gzip.GzipFile(fileobj=buf)
manifest = f.read()
return manifest | [
"def",
"unzip_manifest",
"(",
"self",
",",
"raw_manifest",
")",
":",
"buf",
"=",
"BytesIO",
"(",
"raw_manifest",
")",
"f",
"=",
"gzip",
".",
"GzipFile",
"(",
"fileobj",
"=",
"buf",
")",
"manifest",
"=",
"f",
".",
"read",
"(",
")",
"return",
"manifest"
... | Decompress gzip encoded manifest
:type raw_manifest: str
:param raw_manifest: compressed gzip manifest file content | [
"Decompress",
"gzip",
"encoded",
"manifest"
] | 6dee53ef267959b214953439968244cc46a19690 | https://github.com/ThreatResponse/margaritashotgun/blob/6dee53ef267959b214953439968244cc46a19690/margaritashotgun/repository.py#L248-L259 | train | 212,017 |
ThreatResponse/margaritashotgun | margaritashotgun/repository.py | Repository.parse_manifest | def parse_manifest(self, manifest_xml):
"""
Parse manifest xml file
:type manifest_xml: str
:param manifest_xml: raw xml content of manifest file
"""
manifest = dict()
try:
mdata = xmltodict.parse(manifest_xml)['modules']['module']
for module in mdata:
mod = dict()
mod['type'] = module['@type']
mod['name'] = module['name']
mod['arch'] = module['arch']
mod['checksum'] = module['checksum']
mod['version'] = module['version']
mod['packager'] = module['packager']
mod['location'] = module['location']['@href']
mod['signature'] = module['signature']['@href']
mod['platform'] = module['platform']
manifest[mod['version']] = mod
except Exception as e:
raise
return manifest | python | def parse_manifest(self, manifest_xml):
"""
Parse manifest xml file
:type manifest_xml: str
:param manifest_xml: raw xml content of manifest file
"""
manifest = dict()
try:
mdata = xmltodict.parse(manifest_xml)['modules']['module']
for module in mdata:
mod = dict()
mod['type'] = module['@type']
mod['name'] = module['name']
mod['arch'] = module['arch']
mod['checksum'] = module['checksum']
mod['version'] = module['version']
mod['packager'] = module['packager']
mod['location'] = module['location']['@href']
mod['signature'] = module['signature']['@href']
mod['platform'] = module['platform']
manifest[mod['version']] = mod
except Exception as e:
raise
return manifest | [
"def",
"parse_manifest",
"(",
"self",
",",
"manifest_xml",
")",
":",
"manifest",
"=",
"dict",
"(",
")",
"try",
":",
"mdata",
"=",
"xmltodict",
".",
"parse",
"(",
"manifest_xml",
")",
"[",
"'modules'",
"]",
"[",
"'module'",
"]",
"for",
"module",
"in",
"... | Parse manifest xml file
:type manifest_xml: str
:param manifest_xml: raw xml content of manifest file | [
"Parse",
"manifest",
"xml",
"file"
] | 6dee53ef267959b214953439968244cc46a19690 | https://github.com/ThreatResponse/margaritashotgun/blob/6dee53ef267959b214953439968244cc46a19690/margaritashotgun/repository.py#L261-L288 | train | 212,018 |
ThreatResponse/margaritashotgun | margaritashotgun/repository.py | Repository.fetch_module | def fetch_module(self, module):
"""
Download and verify kernel module
:type module: str
:param module: kernel module path
"""
tm = int(time.time())
datestamp = datetime.utcfromtimestamp(tm).isoformat()
filename = "lime-{0}-{1}.ko".format(datestamp, module['version'])
url = "{0}/{1}".format(self.url, module['location'])
logger.info("downloading {0} as {1}".format(url, filename))
req = requests.get(url, stream=True)
with open(filename, 'wb') as f:
f.write(req.raw.read())
self.verify_module(filename, module, self.gpg_verify)
return filename | python | def fetch_module(self, module):
"""
Download and verify kernel module
:type module: str
:param module: kernel module path
"""
tm = int(time.time())
datestamp = datetime.utcfromtimestamp(tm).isoformat()
filename = "lime-{0}-{1}.ko".format(datestamp, module['version'])
url = "{0}/{1}".format(self.url, module['location'])
logger.info("downloading {0} as {1}".format(url, filename))
req = requests.get(url, stream=True)
with open(filename, 'wb') as f:
f.write(req.raw.read())
self.verify_module(filename, module, self.gpg_verify)
return filename | [
"def",
"fetch_module",
"(",
"self",
",",
"module",
")",
":",
"tm",
"=",
"int",
"(",
"time",
".",
"time",
"(",
")",
")",
"datestamp",
"=",
"datetime",
".",
"utcfromtimestamp",
"(",
"tm",
")",
".",
"isoformat",
"(",
")",
"filename",
"=",
"\"lime-{0}-{1}.... | Download and verify kernel module
:type module: str
:param module: kernel module path | [
"Download",
"and",
"verify",
"kernel",
"module"
] | 6dee53ef267959b214953439968244cc46a19690 | https://github.com/ThreatResponse/margaritashotgun/blob/6dee53ef267959b214953439968244cc46a19690/margaritashotgun/repository.py#L290-L308 | train | 212,019 |
ThreatResponse/margaritashotgun | margaritashotgun/repository.py | Repository.verify_module | def verify_module(self, filename, module, verify_signature):
"""
Verify kernel module checksum and signature
:type filename: str
:param filename: downloaded kernel module path
:type module: dict
:param module: kernel module metadata
:type verify_signature: bool
:param verify_signature: enable/disable signature verification
"""
with open(filename, 'rb') as f:
module_data = f.read()
self.verify_checksum(module_data, module['checksum'],
module['location'])
if self.gpg_verify:
signature_url = "{0}/{1}".format(self.url, module['signature'])
file_url = "{0}/{1}".format(self.url, module['location'])
self.verify_file_signature(signature_url, file_url, filename) | python | def verify_module(self, filename, module, verify_signature):
"""
Verify kernel module checksum and signature
:type filename: str
:param filename: downloaded kernel module path
:type module: dict
:param module: kernel module metadata
:type verify_signature: bool
:param verify_signature: enable/disable signature verification
"""
with open(filename, 'rb') as f:
module_data = f.read()
self.verify_checksum(module_data, module['checksum'],
module['location'])
if self.gpg_verify:
signature_url = "{0}/{1}".format(self.url, module['signature'])
file_url = "{0}/{1}".format(self.url, module['location'])
self.verify_file_signature(signature_url, file_url, filename) | [
"def",
"verify_module",
"(",
"self",
",",
"filename",
",",
"module",
",",
"verify_signature",
")",
":",
"with",
"open",
"(",
"filename",
",",
"'rb'",
")",
"as",
"f",
":",
"module_data",
"=",
"f",
".",
"read",
"(",
")",
"self",
".",
"verify_checksum",
"... | Verify kernel module checksum and signature
:type filename: str
:param filename: downloaded kernel module path
:type module: dict
:param module: kernel module metadata
:type verify_signature: bool
:param verify_signature: enable/disable signature verification | [
"Verify",
"kernel",
"module",
"checksum",
"and",
"signature"
] | 6dee53ef267959b214953439968244cc46a19690 | https://github.com/ThreatResponse/margaritashotgun/blob/6dee53ef267959b214953439968244cc46a19690/margaritashotgun/repository.py#L310-L329 | train | 212,020 |
ThreatResponse/margaritashotgun | margaritashotgun/repository.py | Repository.verify_checksum | def verify_checksum(self, data, checksum, filename):
"""
Verify sha256 checksum vs calculated checksum
:type data: str
:param data: data used to calculate checksum
:type checksum: str
:param checksum: expected checksum of data
:type filename: str
:param checksum: original filename
"""
calculated_checksum = hashlib.sha256(data).hexdigest()
logger.debug("calculated checksum {0} for {1}".format(calculated_checksum,
filename))
if calculated_checksum != checksum:
raise RepositoryError("{0}/{1}".format(self.url, filename),
("checksum verification failed, expected "
"{0} got {1}".format(checksum,
calculated_checksum))) | python | def verify_checksum(self, data, checksum, filename):
"""
Verify sha256 checksum vs calculated checksum
:type data: str
:param data: data used to calculate checksum
:type checksum: str
:param checksum: expected checksum of data
:type filename: str
:param checksum: original filename
"""
calculated_checksum = hashlib.sha256(data).hexdigest()
logger.debug("calculated checksum {0} for {1}".format(calculated_checksum,
filename))
if calculated_checksum != checksum:
raise RepositoryError("{0}/{1}".format(self.url, filename),
("checksum verification failed, expected "
"{0} got {1}".format(checksum,
calculated_checksum))) | [
"def",
"verify_checksum",
"(",
"self",
",",
"data",
",",
"checksum",
",",
"filename",
")",
":",
"calculated_checksum",
"=",
"hashlib",
".",
"sha256",
"(",
"data",
")",
".",
"hexdigest",
"(",
")",
"logger",
".",
"debug",
"(",
"\"calculated checksum {0} for {1}\... | Verify sha256 checksum vs calculated checksum
:type data: str
:param data: data used to calculate checksum
:type checksum: str
:param checksum: expected checksum of data
:type filename: str
:param checksum: original filename | [
"Verify",
"sha256",
"checksum",
"vs",
"calculated",
"checksum"
] | 6dee53ef267959b214953439968244cc46a19690 | https://github.com/ThreatResponse/margaritashotgun/blob/6dee53ef267959b214953439968244cc46a19690/margaritashotgun/repository.py#L331-L349 | train | 212,021 |
ThreatResponse/margaritashotgun | margaritashotgun/repository.py | Repository.verify_data_signature | def verify_data_signature(self, signature_url, data_url, data):
"""
Verify data against it's remote signature
:type signature_url: str
:param signature_url: remote path to signature for data_url
:type data_url: str
:param data_url: url from which data was fetched
:type data: str
:param data: content of remote file at file_url
"""
req = requests.get(signature_url)
if req.status_code is 200:
tm = int(time.time())
datestamp = datetime.utcfromtimestamp(tm).isoformat()
sigfile = "repo-{0}-tmp.sig".format(datestamp)
logger.debug("writing {0} to {1}".format(signature_url, sigfile))
with open(sigfile, 'wb') as f:
f.write(req.content)
else:
raise RepositoryMissingSignatureError(signature_url)
verified = self.gpg.verify_data(sigfile, data)
try:
os.remove(sigfile)
except OSError:
pass
if verified.valid is True:
logger.debug("verified {0} against {1}".format(data_url,
signature_url))
else:
raise RepositorySignatureError(data_url, signature_url) | python | def verify_data_signature(self, signature_url, data_url, data):
"""
Verify data against it's remote signature
:type signature_url: str
:param signature_url: remote path to signature for data_url
:type data_url: str
:param data_url: url from which data was fetched
:type data: str
:param data: content of remote file at file_url
"""
req = requests.get(signature_url)
if req.status_code is 200:
tm = int(time.time())
datestamp = datetime.utcfromtimestamp(tm).isoformat()
sigfile = "repo-{0}-tmp.sig".format(datestamp)
logger.debug("writing {0} to {1}".format(signature_url, sigfile))
with open(sigfile, 'wb') as f:
f.write(req.content)
else:
raise RepositoryMissingSignatureError(signature_url)
verified = self.gpg.verify_data(sigfile, data)
try:
os.remove(sigfile)
except OSError:
pass
if verified.valid is True:
logger.debug("verified {0} against {1}".format(data_url,
signature_url))
else:
raise RepositorySignatureError(data_url, signature_url) | [
"def",
"verify_data_signature",
"(",
"self",
",",
"signature_url",
",",
"data_url",
",",
"data",
")",
":",
"req",
"=",
"requests",
".",
"get",
"(",
"signature_url",
")",
"if",
"req",
".",
"status_code",
"is",
"200",
":",
"tm",
"=",
"int",
"(",
"time",
... | Verify data against it's remote signature
:type signature_url: str
:param signature_url: remote path to signature for data_url
:type data_url: str
:param data_url: url from which data was fetched
:type data: str
:param data: content of remote file at file_url | [
"Verify",
"data",
"against",
"it",
"s",
"remote",
"signature"
] | 6dee53ef267959b214953439968244cc46a19690 | https://github.com/ThreatResponse/margaritashotgun/blob/6dee53ef267959b214953439968244cc46a19690/margaritashotgun/repository.py#L351-L384 | train | 212,022 |
ThreatResponse/margaritashotgun | margaritashotgun/repository.py | Repository.verify_file_signature | def verify_file_signature(self, signature_url, file_url, filename):
"""
Verify a local file against it's remote signature
:type signature_url: str
:param signature_url: remote path to signature for file_url
:type file_url: str
:param file_url: url from which file at filename was fetched
:type filename: str
:param filename: filename of local file downloaded from file_url
"""
req = requests.get(signature_url, stream=True)
if req.status_code is 200:
sigfile = req.raw
else:
raise RepositoryMissingSignatureError(signature_url)
verified = self.gpg.verify_file(sigfile, filename)
if verified.valid is True:
logger.debug("verified {0} against {1}".format(filename, signature_url))
else:
raise RepositorySignatureError(file_url, signature_url) | python | def verify_file_signature(self, signature_url, file_url, filename):
"""
Verify a local file against it's remote signature
:type signature_url: str
:param signature_url: remote path to signature for file_url
:type file_url: str
:param file_url: url from which file at filename was fetched
:type filename: str
:param filename: filename of local file downloaded from file_url
"""
req = requests.get(signature_url, stream=True)
if req.status_code is 200:
sigfile = req.raw
else:
raise RepositoryMissingSignatureError(signature_url)
verified = self.gpg.verify_file(sigfile, filename)
if verified.valid is True:
logger.debug("verified {0} against {1}".format(filename, signature_url))
else:
raise RepositorySignatureError(file_url, signature_url) | [
"def",
"verify_file_signature",
"(",
"self",
",",
"signature_url",
",",
"file_url",
",",
"filename",
")",
":",
"req",
"=",
"requests",
".",
"get",
"(",
"signature_url",
",",
"stream",
"=",
"True",
")",
"if",
"req",
".",
"status_code",
"is",
"200",
":",
"... | Verify a local file against it's remote signature
:type signature_url: str
:param signature_url: remote path to signature for file_url
:type file_url: str
:param file_url: url from which file at filename was fetched
:type filename: str
:param filename: filename of local file downloaded from file_url | [
"Verify",
"a",
"local",
"file",
"against",
"it",
"s",
"remote",
"signature"
] | 6dee53ef267959b214953439968244cc46a19690 | https://github.com/ThreatResponse/margaritashotgun/blob/6dee53ef267959b214953439968244cc46a19690/margaritashotgun/repository.py#L386-L409 | train | 212,023 |
FutunnOpen/futuquant | futuquant/quote/quote_query.py | InitConnect.unpack_rsp | def unpack_rsp(cls, rsp_pb):
"""Unpack the init connect response"""
ret_type = rsp_pb.retType
ret_msg = rsp_pb.retMsg
if ret_type != RET_OK:
return RET_ERROR, ret_msg, None
res = {}
if rsp_pb.HasField('s2c'):
res['server_version'] = rsp_pb.s2c.serverVer
res['login_user_id'] = rsp_pb.s2c.loginUserID
res['conn_id'] = rsp_pb.s2c.connID
res['conn_key'] = rsp_pb.s2c.connAESKey
res['keep_alive_interval'] = rsp_pb.s2c.keepAliveInterval
else:
return RET_ERROR, "rsp_pb error", None
return RET_OK, "", res | python | def unpack_rsp(cls, rsp_pb):
"""Unpack the init connect response"""
ret_type = rsp_pb.retType
ret_msg = rsp_pb.retMsg
if ret_type != RET_OK:
return RET_ERROR, ret_msg, None
res = {}
if rsp_pb.HasField('s2c'):
res['server_version'] = rsp_pb.s2c.serverVer
res['login_user_id'] = rsp_pb.s2c.loginUserID
res['conn_id'] = rsp_pb.s2c.connID
res['conn_key'] = rsp_pb.s2c.connAESKey
res['keep_alive_interval'] = rsp_pb.s2c.keepAliveInterval
else:
return RET_ERROR, "rsp_pb error", None
return RET_OK, "", res | [
"def",
"unpack_rsp",
"(",
"cls",
",",
"rsp_pb",
")",
":",
"ret_type",
"=",
"rsp_pb",
".",
"retType",
"ret_msg",
"=",
"rsp_pb",
".",
"retMsg",
"if",
"ret_type",
"!=",
"RET_OK",
":",
"return",
"RET_ERROR",
",",
"ret_msg",
",",
"None",
"res",
"=",
"{",
"}... | Unpack the init connect response | [
"Unpack",
"the",
"init",
"connect",
"response"
] | 1512b321845f92ec9c578ce2689aa4e8482669e4 | https://github.com/FutunnOpen/futuquant/blob/1512b321845f92ec9c578ce2689aa4e8482669e4/futuquant/quote/quote_query.py#L40-L58 | train | 212,024 |
FutunnOpen/futuquant | futuquant/quote/quote_query.py | SubscriptionQuery.unpack_unsubscribe_rsp | def unpack_unsubscribe_rsp(cls, rsp_pb):
"""Unpack the un-subscribed response"""
if rsp_pb.retType != RET_OK:
return RET_ERROR, rsp_pb.retMsg, None
return RET_OK, "", None | python | def unpack_unsubscribe_rsp(cls, rsp_pb):
"""Unpack the un-subscribed response"""
if rsp_pb.retType != RET_OK:
return RET_ERROR, rsp_pb.retMsg, None
return RET_OK, "", None | [
"def",
"unpack_unsubscribe_rsp",
"(",
"cls",
",",
"rsp_pb",
")",
":",
"if",
"rsp_pb",
".",
"retType",
"!=",
"RET_OK",
":",
"return",
"RET_ERROR",
",",
"rsp_pb",
".",
"retMsg",
",",
"None",
"return",
"RET_OK",
",",
"\"\"",
",",
"None"
] | Unpack the un-subscribed response | [
"Unpack",
"the",
"un",
"-",
"subscribed",
"response"
] | 1512b321845f92ec9c578ce2689aa4e8482669e4 | https://github.com/FutunnOpen/futuquant/blob/1512b321845f92ec9c578ce2689aa4e8482669e4/futuquant/quote/quote_query.py#L875-L880 | train | 212,025 |
FutunnOpen/futuquant | futuquant/common/pbjson.py | dict2pb | def dict2pb(cls, adict, strict=False):
"""
Takes a class representing the ProtoBuf Message and fills it with data from
the dict.
"""
obj = cls()
for field in obj.DESCRIPTOR.fields:
if not field.label == field.LABEL_REQUIRED:
continue
if not field.has_default_value:
continue
if not field.name in adict:
raise ConvertException('Field "%s" missing from descriptor dictionary.'
% field.name)
field_names = set([field.name for field in obj.DESCRIPTOR.fields])
if strict:
for key in adict.keys():
if key not in field_names:
raise ConvertException(
'Key "%s" can not be mapped to field in %s class.'
% (key, type(obj)))
for field in obj.DESCRIPTOR.fields:
if not field.name in adict:
continue
msg_type = field.message_type
if field.label == FD.LABEL_REPEATED:
if field.type == FD.TYPE_MESSAGE:
for sub_dict in adict[field.name]:
item = getattr(obj, field.name).add()
item.CopyFrom(dict2pb(msg_type._concrete_class, sub_dict))
else:
# fix python3 map用法变更
list(map(getattr(obj, field.name).append, adict[field.name]))
else:
if field.type == FD.TYPE_MESSAGE:
value = dict2pb(msg_type._concrete_class, adict[field.name])
getattr(obj, field.name).CopyFrom(value)
elif field.type in [FD.TYPE_UINT64, FD.TYPE_INT64, FD.TYPE_SINT64]:
setattr(obj, field.name, int(adict[field.name]))
else:
setattr(obj, field.name, adict[field.name])
return obj | python | def dict2pb(cls, adict, strict=False):
"""
Takes a class representing the ProtoBuf Message and fills it with data from
the dict.
"""
obj = cls()
for field in obj.DESCRIPTOR.fields:
if not field.label == field.LABEL_REQUIRED:
continue
if not field.has_default_value:
continue
if not field.name in adict:
raise ConvertException('Field "%s" missing from descriptor dictionary.'
% field.name)
field_names = set([field.name for field in obj.DESCRIPTOR.fields])
if strict:
for key in adict.keys():
if key not in field_names:
raise ConvertException(
'Key "%s" can not be mapped to field in %s class.'
% (key, type(obj)))
for field in obj.DESCRIPTOR.fields:
if not field.name in adict:
continue
msg_type = field.message_type
if field.label == FD.LABEL_REPEATED:
if field.type == FD.TYPE_MESSAGE:
for sub_dict in adict[field.name]:
item = getattr(obj, field.name).add()
item.CopyFrom(dict2pb(msg_type._concrete_class, sub_dict))
else:
# fix python3 map用法变更
list(map(getattr(obj, field.name).append, adict[field.name]))
else:
if field.type == FD.TYPE_MESSAGE:
value = dict2pb(msg_type._concrete_class, adict[field.name])
getattr(obj, field.name).CopyFrom(value)
elif field.type in [FD.TYPE_UINT64, FD.TYPE_INT64, FD.TYPE_SINT64]:
setattr(obj, field.name, int(adict[field.name]))
else:
setattr(obj, field.name, adict[field.name])
return obj | [
"def",
"dict2pb",
"(",
"cls",
",",
"adict",
",",
"strict",
"=",
"False",
")",
":",
"obj",
"=",
"cls",
"(",
")",
"for",
"field",
"in",
"obj",
".",
"DESCRIPTOR",
".",
"fields",
":",
"if",
"not",
"field",
".",
"label",
"==",
"field",
".",
"LABEL_REQUI... | Takes a class representing the ProtoBuf Message and fills it with data from
the dict. | [
"Takes",
"a",
"class",
"representing",
"the",
"ProtoBuf",
"Message",
"and",
"fills",
"it",
"with",
"data",
"from",
"the",
"dict",
"."
] | 1512b321845f92ec9c578ce2689aa4e8482669e4 | https://github.com/FutunnOpen/futuquant/blob/1512b321845f92ec9c578ce2689aa4e8482669e4/futuquant/common/pbjson.py#L40-L81 | train | 212,026 |
FutunnOpen/futuquant | futuquant/common/pbjson.py | pb2dict | def pb2dict(obj):
"""
Takes a ProtoBuf Message obj and convertes it to a dict.
"""
adict = {}
if not obj.IsInitialized():
return None
for field in obj.DESCRIPTOR.fields:
if not getattr(obj, field.name):
continue
if not field.label == FD.LABEL_REPEATED:
if not field.type == FD.TYPE_MESSAGE:
adict[field.name] = getattr(obj, field.name)
else:
value = pb2dict(getattr(obj, field.name))
if value:
adict[field.name] = value
else:
if field.type == FD.TYPE_MESSAGE:
adict[field.name] = \
[pb2dict(v) for v in getattr(obj, field.name)]
else:
adict[field.name] = [v for v in getattr(obj, field.name)]
return adict | python | def pb2dict(obj):
"""
Takes a ProtoBuf Message obj and convertes it to a dict.
"""
adict = {}
if not obj.IsInitialized():
return None
for field in obj.DESCRIPTOR.fields:
if not getattr(obj, field.name):
continue
if not field.label == FD.LABEL_REPEATED:
if not field.type == FD.TYPE_MESSAGE:
adict[field.name] = getattr(obj, field.name)
else:
value = pb2dict(getattr(obj, field.name))
if value:
adict[field.name] = value
else:
if field.type == FD.TYPE_MESSAGE:
adict[field.name] = \
[pb2dict(v) for v in getattr(obj, field.name)]
else:
adict[field.name] = [v for v in getattr(obj, field.name)]
return adict | [
"def",
"pb2dict",
"(",
"obj",
")",
":",
"adict",
"=",
"{",
"}",
"if",
"not",
"obj",
".",
"IsInitialized",
"(",
")",
":",
"return",
"None",
"for",
"field",
"in",
"obj",
".",
"DESCRIPTOR",
".",
"fields",
":",
"if",
"not",
"getattr",
"(",
"obj",
",",
... | Takes a ProtoBuf Message obj and convertes it to a dict. | [
"Takes",
"a",
"ProtoBuf",
"Message",
"obj",
"and",
"convertes",
"it",
"to",
"a",
"dict",
"."
] | 1512b321845f92ec9c578ce2689aa4e8482669e4 | https://github.com/FutunnOpen/futuquant/blob/1512b321845f92ec9c578ce2689aa4e8482669e4/futuquant/common/pbjson.py#L84-L107 | train | 212,027 |
FutunnOpen/futuquant | futuquant/common/pbjson.py | json2pb | def json2pb(cls, json, strict=False):
"""
Takes a class representing the Protobuf Message and fills it with data from
the json string.
"""
return dict2pb(cls, simplejson.loads(json), strict) | python | def json2pb(cls, json, strict=False):
"""
Takes a class representing the Protobuf Message and fills it with data from
the json string.
"""
return dict2pb(cls, simplejson.loads(json), strict) | [
"def",
"json2pb",
"(",
"cls",
",",
"json",
",",
"strict",
"=",
"False",
")",
":",
"return",
"dict2pb",
"(",
"cls",
",",
"simplejson",
".",
"loads",
"(",
"json",
")",
",",
"strict",
")"
] | Takes a class representing the Protobuf Message and fills it with data from
the json string. | [
"Takes",
"a",
"class",
"representing",
"the",
"Protobuf",
"Message",
"and",
"fills",
"it",
"with",
"data",
"from",
"the",
"json",
"string",
"."
] | 1512b321845f92ec9c578ce2689aa4e8482669e4 | https://github.com/FutunnOpen/futuquant/blob/1512b321845f92ec9c578ce2689aa4e8482669e4/futuquant/common/pbjson.py#L110-L115 | train | 212,028 |
FutunnOpen/futuquant | futuquant/trade/open_trade_context.py | OpenTradeContextBase._split_stock_code | def _split_stock_code(self, code):
stock_str = str(code)
split_loc = stock_str.find(".")
'''do not use the built-in split function in python.
The built-in function cannot handle some stock strings correctly.
for instance, US..DJI, where the dot . itself is a part of original code'''
if 0 <= split_loc < len(
stock_str) - 1 and stock_str[0:split_loc] in MKT_MAP:
market_str = stock_str[0:split_loc]
partial_stock_str = stock_str[split_loc + 1:]
return RET_OK, (market_str, partial_stock_str)
else:
error_str = ERROR_STR_PREFIX + "format of %s is wrong. (US.AAPL, HK.00700, SZ.000001)" % stock_str
return RET_ERROR, error_str | python | def _split_stock_code(self, code):
stock_str = str(code)
split_loc = stock_str.find(".")
'''do not use the built-in split function in python.
The built-in function cannot handle some stock strings correctly.
for instance, US..DJI, where the dot . itself is a part of original code'''
if 0 <= split_loc < len(
stock_str) - 1 and stock_str[0:split_loc] in MKT_MAP:
market_str = stock_str[0:split_loc]
partial_stock_str = stock_str[split_loc + 1:]
return RET_OK, (market_str, partial_stock_str)
else:
error_str = ERROR_STR_PREFIX + "format of %s is wrong. (US.AAPL, HK.00700, SZ.000001)" % stock_str
return RET_ERROR, error_str | [
"def",
"_split_stock_code",
"(",
"self",
",",
"code",
")",
":",
"stock_str",
"=",
"str",
"(",
"code",
")",
"split_loc",
"=",
"stock_str",
".",
"find",
"(",
"\".\"",
")",
"if",
"0",
"<=",
"split_loc",
"<",
"len",
"(",
"stock_str",
")",
"-",
"1",
"and"... | do not use the built-in split function in python.
The built-in function cannot handle some stock strings correctly.
for instance, US..DJI, where the dot . itself is a part of original code | [
"do",
"not",
"use",
"the",
"built",
"-",
"in",
"split",
"function",
"in",
"python",
".",
"The",
"built",
"-",
"in",
"function",
"cannot",
"handle",
"some",
"stock",
"strings",
"correctly",
".",
"for",
"instance",
"US",
"..",
"DJI",
"where",
"the",
"dot",... | 1512b321845f92ec9c578ce2689aa4e8482669e4 | https://github.com/FutunnOpen/futuquant/blob/1512b321845f92ec9c578ce2689aa4e8482669e4/futuquant/trade/open_trade_context.py#L293-L308 | train | 212,029 |
FutunnOpen/futuquant | futuquant/trade/open_trade_context.py | OpenTradeContextBase.position_list_query | def position_list_query(self, code='', pl_ratio_min=None,
pl_ratio_max=None, trd_env=TrdEnv.REAL, acc_id=0, acc_index=0):
"""for querying the position list"""
ret, msg = self._check_trd_env(trd_env)
if ret != RET_OK:
return ret, msg
ret, msg, acc_id = self._check_acc_id_and_acc_index(trd_env, acc_id, acc_index)
if ret != RET_OK:
return ret, msg
ret, msg, stock_code = self._check_stock_code(code)
if ret != RET_OK:
return ret, msg
query_processor = self._get_sync_query_processor(
PositionListQuery.pack_req, PositionListQuery.unpack_rsp)
kargs = {
'code': str(stock_code),
'pl_ratio_min': pl_ratio_min,
'pl_ratio_max': pl_ratio_max,
'trd_mkt': self.__trd_mkt,
'trd_env': trd_env,
'acc_id': acc_id,
'conn_id': self.get_sync_conn_id()
}
ret_code, msg, position_list = query_processor(**kargs)
if ret_code != RET_OK:
return RET_ERROR, msg
col_list = [
"code", "stock_name", "qty", "can_sell_qty", "cost_price",
"cost_price_valid", "market_val", "nominal_price", "pl_ratio",
"pl_ratio_valid", "pl_val", "pl_val_valid", "today_buy_qty",
"today_buy_val", "today_pl_val", "today_sell_qty", "today_sell_val",
"position_side"
]
position_list_table = pd.DataFrame(position_list, columns=col_list)
return RET_OK, position_list_table | python | def position_list_query(self, code='', pl_ratio_min=None,
pl_ratio_max=None, trd_env=TrdEnv.REAL, acc_id=0, acc_index=0):
"""for querying the position list"""
ret, msg = self._check_trd_env(trd_env)
if ret != RET_OK:
return ret, msg
ret, msg, acc_id = self._check_acc_id_and_acc_index(trd_env, acc_id, acc_index)
if ret != RET_OK:
return ret, msg
ret, msg, stock_code = self._check_stock_code(code)
if ret != RET_OK:
return ret, msg
query_processor = self._get_sync_query_processor(
PositionListQuery.pack_req, PositionListQuery.unpack_rsp)
kargs = {
'code': str(stock_code),
'pl_ratio_min': pl_ratio_min,
'pl_ratio_max': pl_ratio_max,
'trd_mkt': self.__trd_mkt,
'trd_env': trd_env,
'acc_id': acc_id,
'conn_id': self.get_sync_conn_id()
}
ret_code, msg, position_list = query_processor(**kargs)
if ret_code != RET_OK:
return RET_ERROR, msg
col_list = [
"code", "stock_name", "qty", "can_sell_qty", "cost_price",
"cost_price_valid", "market_val", "nominal_price", "pl_ratio",
"pl_ratio_valid", "pl_val", "pl_val_valid", "today_buy_qty",
"today_buy_val", "today_pl_val", "today_sell_qty", "today_sell_val",
"position_side"
]
position_list_table = pd.DataFrame(position_list, columns=col_list)
return RET_OK, position_list_table | [
"def",
"position_list_query",
"(",
"self",
",",
"code",
"=",
"''",
",",
"pl_ratio_min",
"=",
"None",
",",
"pl_ratio_max",
"=",
"None",
",",
"trd_env",
"=",
"TrdEnv",
".",
"REAL",
",",
"acc_id",
"=",
"0",
",",
"acc_index",
"=",
"0",
")",
":",
"ret",
"... | for querying the position list | [
"for",
"querying",
"the",
"position",
"list"
] | 1512b321845f92ec9c578ce2689aa4e8482669e4 | https://github.com/FutunnOpen/futuquant/blob/1512b321845f92ec9c578ce2689aa4e8482669e4/futuquant/trade/open_trade_context.py#L310-L351 | train | 212,030 |
FutunnOpen/futuquant | futuquant/trade/open_trade_context.py | OpenTradeContextBase.deal_list_query | def deal_list_query(self, code="", trd_env=TrdEnv.REAL, acc_id=0, acc_index=0):
"""for querying deal list"""
ret, msg = self._check_trd_env(trd_env)
if ret != RET_OK:
return ret, msg
ret, msg, acc_id = self._check_acc_id_and_acc_index(trd_env, acc_id, acc_index)
if ret != RET_OK:
return ret, msg
ret, msg, stock_code = self._check_stock_code(code)
if ret != RET_OK:
return ret, msg
query_processor = self._get_sync_query_processor(
DealListQuery.pack_req, DealListQuery.unpack_rsp)
kargs = {
'code': stock_code,
'trd_mkt': self.__trd_mkt,
'trd_env': trd_env,
'acc_id': acc_id,
'conn_id': self.get_sync_conn_id()
}
ret_code, msg, deal_list = query_processor(**kargs)
if ret_code != RET_OK:
return RET_ERROR, msg
col_list = [
"code", "stock_name", "deal_id", "order_id", "qty", "price",
"trd_side", "create_time", "counter_broker_id", "counter_broker_name"
]
deal_list_table = pd.DataFrame(deal_list, columns=col_list)
return RET_OK, deal_list_table | python | def deal_list_query(self, code="", trd_env=TrdEnv.REAL, acc_id=0, acc_index=0):
"""for querying deal list"""
ret, msg = self._check_trd_env(trd_env)
if ret != RET_OK:
return ret, msg
ret, msg, acc_id = self._check_acc_id_and_acc_index(trd_env, acc_id, acc_index)
if ret != RET_OK:
return ret, msg
ret, msg, stock_code = self._check_stock_code(code)
if ret != RET_OK:
return ret, msg
query_processor = self._get_sync_query_processor(
DealListQuery.pack_req, DealListQuery.unpack_rsp)
kargs = {
'code': stock_code,
'trd_mkt': self.__trd_mkt,
'trd_env': trd_env,
'acc_id': acc_id,
'conn_id': self.get_sync_conn_id()
}
ret_code, msg, deal_list = query_processor(**kargs)
if ret_code != RET_OK:
return RET_ERROR, msg
col_list = [
"code", "stock_name", "deal_id", "order_id", "qty", "price",
"trd_side", "create_time", "counter_broker_id", "counter_broker_name"
]
deal_list_table = pd.DataFrame(deal_list, columns=col_list)
return RET_OK, deal_list_table | [
"def",
"deal_list_query",
"(",
"self",
",",
"code",
"=",
"\"\"",
",",
"trd_env",
"=",
"TrdEnv",
".",
"REAL",
",",
"acc_id",
"=",
"0",
",",
"acc_index",
"=",
"0",
")",
":",
"ret",
",",
"msg",
"=",
"self",
".",
"_check_trd_env",
"(",
"trd_env",
")",
... | for querying deal list | [
"for",
"querying",
"deal",
"list"
] | 1512b321845f92ec9c578ce2689aa4e8482669e4 | https://github.com/FutunnOpen/futuquant/blob/1512b321845f92ec9c578ce2689aa4e8482669e4/futuquant/trade/open_trade_context.py#L534-L568 | train | 212,031 |
FutunnOpen/futuquant | futuquant/common/sync_network_manager.py | _SyncNetworkQueryCtx.is_sock_ok | def is_sock_ok(self, timeout_select):
"""check if socket is OK"""
self._socket_lock.acquire()
try:
ret = self._is_socket_ok(timeout_select)
finally:
self._socket_lock.release()
return ret | python | def is_sock_ok(self, timeout_select):
"""check if socket is OK"""
self._socket_lock.acquire()
try:
ret = self._is_socket_ok(timeout_select)
finally:
self._socket_lock.release()
return ret | [
"def",
"is_sock_ok",
"(",
"self",
",",
"timeout_select",
")",
":",
"self",
".",
"_socket_lock",
".",
"acquire",
"(",
")",
"try",
":",
"ret",
"=",
"self",
".",
"_is_socket_ok",
"(",
"timeout_select",
")",
"finally",
":",
"self",
".",
"_socket_lock",
".",
... | check if socket is OK | [
"check",
"if",
"socket",
"is",
"OK"
] | 1512b321845f92ec9c578ce2689aa4e8482669e4 | https://github.com/FutunnOpen/futuquant/blob/1512b321845f92ec9c578ce2689aa4e8482669e4/futuquant/common/sync_network_manager.py#L46-L53 | train | 212,032 |
FutunnOpen/futuquant | futuquant/common/utils.py | check_date_str_format | def check_date_str_format(s, default_time="00:00:00"):
"""Check the format of date string"""
try:
str_fmt = s
if ":" not in s:
str_fmt = '{} {}'.format(s, default_time)
dt_obj = datetime.strptime(str_fmt, "%Y-%m-%d %H:%M:%S")
return RET_OK, dt_obj
except ValueError:
error_str = ERROR_STR_PREFIX + "wrong time or time format"
return RET_ERROR, error_str | python | def check_date_str_format(s, default_time="00:00:00"):
"""Check the format of date string"""
try:
str_fmt = s
if ":" not in s:
str_fmt = '{} {}'.format(s, default_time)
dt_obj = datetime.strptime(str_fmt, "%Y-%m-%d %H:%M:%S")
return RET_OK, dt_obj
except ValueError:
error_str = ERROR_STR_PREFIX + "wrong time or time format"
return RET_ERROR, error_str | [
"def",
"check_date_str_format",
"(",
"s",
",",
"default_time",
"=",
"\"00:00:00\"",
")",
":",
"try",
":",
"str_fmt",
"=",
"s",
"if",
"\":\"",
"not",
"in",
"s",
":",
"str_fmt",
"=",
"'{} {}'",
".",
"format",
"(",
"s",
",",
"default_time",
")",
"dt_obj",
... | Check the format of date string | [
"Check",
"the",
"format",
"of",
"date",
"string"
] | 1512b321845f92ec9c578ce2689aa4e8482669e4 | https://github.com/FutunnOpen/futuquant/blob/1512b321845f92ec9c578ce2689aa4e8482669e4/futuquant/common/utils.py#L23-L36 | train | 212,033 |
FutunnOpen/futuquant | futuquant/common/utils.py | normalize_date_format | def normalize_date_format(date_str, default_time="00:00:00"):
"""normalize the format of data"""
ret_code, ret_data = check_date_str_format(date_str, default_time)
if ret_code != RET_OK:
return ret_code, ret_data
return RET_OK, ret_data.strftime("%Y-%m-%d %H:%M:%S") | python | def normalize_date_format(date_str, default_time="00:00:00"):
"""normalize the format of data"""
ret_code, ret_data = check_date_str_format(date_str, default_time)
if ret_code != RET_OK:
return ret_code, ret_data
return RET_OK, ret_data.strftime("%Y-%m-%d %H:%M:%S") | [
"def",
"normalize_date_format",
"(",
"date_str",
",",
"default_time",
"=",
"\"00:00:00\"",
")",
":",
"ret_code",
",",
"ret_data",
"=",
"check_date_str_format",
"(",
"date_str",
",",
"default_time",
")",
"if",
"ret_code",
"!=",
"RET_OK",
":",
"return",
"ret_code",
... | normalize the format of data | [
"normalize",
"the",
"format",
"of",
"data"
] | 1512b321845f92ec9c578ce2689aa4e8482669e4 | https://github.com/FutunnOpen/futuquant/blob/1512b321845f92ec9c578ce2689aa4e8482669e4/futuquant/common/utils.py#L39-L45 | train | 212,034 |
FutunnOpen/futuquant | futuquant/common/utils.py | extract_pls_rsp | def extract_pls_rsp(rsp_str):
"""Extract the response of PLS"""
try:
rsp = json.loads(rsp_str)
except ValueError:
traceback.print_exc()
err = sys.exc_info()[1]
err_str = ERROR_STR_PREFIX + str(err)
return RET_ERROR, err_str, None
error_code = int(rsp['retType'])
if error_code != 1:
error_str = ERROR_STR_PREFIX + rsp['retMsg']
return RET_ERROR, error_str, None
return RET_OK, "", rsp | python | def extract_pls_rsp(rsp_str):
"""Extract the response of PLS"""
try:
rsp = json.loads(rsp_str)
except ValueError:
traceback.print_exc()
err = sys.exc_info()[1]
err_str = ERROR_STR_PREFIX + str(err)
return RET_ERROR, err_str, None
error_code = int(rsp['retType'])
if error_code != 1:
error_str = ERROR_STR_PREFIX + rsp['retMsg']
return RET_ERROR, error_str, None
return RET_OK, "", rsp | [
"def",
"extract_pls_rsp",
"(",
"rsp_str",
")",
":",
"try",
":",
"rsp",
"=",
"json",
".",
"loads",
"(",
"rsp_str",
")",
"except",
"ValueError",
":",
"traceback",
".",
"print_exc",
"(",
")",
"err",
"=",
"sys",
".",
"exc_info",
"(",
")",
"[",
"1",
"]",
... | Extract the response of PLS | [
"Extract",
"the",
"response",
"of",
"PLS"
] | 1512b321845f92ec9c578ce2689aa4e8482669e4 | https://github.com/FutunnOpen/futuquant/blob/1512b321845f92ec9c578ce2689aa4e8482669e4/futuquant/common/utils.py#L113-L129 | train | 212,035 |
FutunnOpen/futuquant | futuquant/common/utils.py | split_stock_str | def split_stock_str(stock_str_param):
"""split the stock string"""
stock_str = str(stock_str_param)
split_loc = stock_str.find(".")
'''do not use the built-in split function in python.
The built-in function cannot handle some stock strings correctly.
for instance, US..DJI, where the dot . itself is a part of original code'''
if 0 <= split_loc < len(
stock_str) - 1 and stock_str[0:split_loc] in MKT_MAP:
market_str = stock_str[0:split_loc]
market_code = MKT_MAP[market_str]
partial_stock_str = stock_str[split_loc + 1:]
return RET_OK, (market_code, partial_stock_str)
else:
error_str = ERROR_STR_PREFIX + "format of %s is wrong. (US.AAPL, HK.00700, SZ.000001)" % stock_str
return RET_ERROR, error_str | python | def split_stock_str(stock_str_param):
"""split the stock string"""
stock_str = str(stock_str_param)
split_loc = stock_str.find(".")
'''do not use the built-in split function in python.
The built-in function cannot handle some stock strings correctly.
for instance, US..DJI, where the dot . itself is a part of original code'''
if 0 <= split_loc < len(
stock_str) - 1 and stock_str[0:split_loc] in MKT_MAP:
market_str = stock_str[0:split_loc]
market_code = MKT_MAP[market_str]
partial_stock_str = stock_str[split_loc + 1:]
return RET_OK, (market_code, partial_stock_str)
else:
error_str = ERROR_STR_PREFIX + "format of %s is wrong. (US.AAPL, HK.00700, SZ.000001)" % stock_str
return RET_ERROR, error_str | [
"def",
"split_stock_str",
"(",
"stock_str_param",
")",
":",
"stock_str",
"=",
"str",
"(",
"stock_str_param",
")",
"split_loc",
"=",
"stock_str",
".",
"find",
"(",
"\".\"",
")",
"'''do not use the built-in split function in python.\n The built-in function cannot handle some... | split the stock string | [
"split",
"the",
"stock",
"string"
] | 1512b321845f92ec9c578ce2689aa4e8482669e4 | https://github.com/FutunnOpen/futuquant/blob/1512b321845f92ec9c578ce2689aa4e8482669e4/futuquant/common/utils.py#L132-L149 | train | 212,036 |
FutunnOpen/futuquant | futuquant/common/open_context_base.py | OpenContextBase.set_pre_handler | def set_pre_handler(self, handler):
'''set pre handler'''
with self._lock:
if self._handler_ctx is not None:
return self._handler_ctx.set_pre_handler(handler)
return RET_ERROR | python | def set_pre_handler(self, handler):
'''set pre handler'''
with self._lock:
if self._handler_ctx is not None:
return self._handler_ctx.set_pre_handler(handler)
return RET_ERROR | [
"def",
"set_pre_handler",
"(",
"self",
",",
"handler",
")",
":",
"with",
"self",
".",
"_lock",
":",
"if",
"self",
".",
"_handler_ctx",
"is",
"not",
"None",
":",
"return",
"self",
".",
"_handler_ctx",
".",
"set_pre_handler",
"(",
"handler",
")",
"return",
... | set pre handler | [
"set",
"pre",
"handler"
] | 1512b321845f92ec9c578ce2689aa4e8482669e4 | https://github.com/FutunnOpen/futuquant/blob/1512b321845f92ec9c578ce2689aa4e8482669e4/futuquant/common/open_context_base.py#L143-L148 | train | 212,037 |
honmaple/flask-msearch | flask_msearch/whoosh_backend.py | WhooshSearch.msearch | def msearch(self, m, query, fields=None, limit=None, or_=True):
'''
set limit make search faster
'''
ix = self._index(m)
if fields is None:
fields = ix.fields
group = OrGroup if or_ else AndGroup
parser = MultifieldParser(fields, ix.schema, group=group)
return ix.search(parser.parse(query), limit=limit) | python | def msearch(self, m, query, fields=None, limit=None, or_=True):
'''
set limit make search faster
'''
ix = self._index(m)
if fields is None:
fields = ix.fields
group = OrGroup if or_ else AndGroup
parser = MultifieldParser(fields, ix.schema, group=group)
return ix.search(parser.parse(query), limit=limit) | [
"def",
"msearch",
"(",
"self",
",",
"m",
",",
"query",
",",
"fields",
"=",
"None",
",",
"limit",
"=",
"None",
",",
"or_",
"=",
"True",
")",
":",
"ix",
"=",
"self",
".",
"_index",
"(",
"m",
")",
"if",
"fields",
"is",
"None",
":",
"fields",
"=",
... | set limit make search faster | [
"set",
"limit",
"make",
"search",
"faster"
] | 4d4dacbe83aa23e852e66a02c51f6f4b1da4445f | https://github.com/honmaple/flask-msearch/blob/4d4dacbe83aa23e852e66a02c51f6f4b1da4445f/flask_msearch/whoosh_backend.py#L188-L197 | train | 212,038 |
honmaple/flask-msearch | flask_msearch/elasticsearch_backend.py | Index.update | def update(self, **kwargs):
"Update document not update index."
kw = dict(index=self.name, doc_type=self.doc_type, ignore=[404])
kw.update(**kwargs)
return self._client.update(**kw) | python | def update(self, **kwargs):
"Update document not update index."
kw = dict(index=self.name, doc_type=self.doc_type, ignore=[404])
kw.update(**kwargs)
return self._client.update(**kw) | [
"def",
"update",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"kw",
"=",
"dict",
"(",
"index",
"=",
"self",
".",
"name",
",",
"doc_type",
"=",
"self",
".",
"doc_type",
",",
"ignore",
"=",
"[",
"404",
"]",
")",
"kw",
".",
"update",
"(",
"*",
... | Update document not update index. | [
"Update",
"document",
"not",
"update",
"index",
"."
] | 4d4dacbe83aa23e852e66a02c51f6f4b1da4445f | https://github.com/honmaple/flask-msearch/blob/4d4dacbe83aa23e852e66a02c51f6f4b1da4445f/flask_msearch/elasticsearch_backend.py#L67-L71 | train | 212,039 |
atztogo/phono3py | phono3py/phonon3/conductivity_LBTE.py | diagonalize_collision_matrix | def diagonalize_collision_matrix(collision_matrices,
i_sigma=None,
i_temp=None,
pinv_solver=0,
log_level=0):
"""Diagonalize collision matrices.
Note
----
collision_matricies is overwritten by eigenvectors.
Parameters
----------
collision_matricies : ndarray, optional
Collision matrix. This ndarray has to have the following size and
flags.
shapes:
(sigmas, temperatures, prod(mesh), num_band, prod(mesh), num_band)
(sigmas, temperatures, ir_grid_points, num_band, 3,
ir_grid_points, num_band, 3)
(size, size)
dtype='double', order='C'
i_sigma : int, optional
Index of BZ integration methods, tetrahedron method and smearing
method with widths. Default is None.
i_temp : int, optional
Index of temperature. Default is None.
pinv_solver : int, optional
Diagnalization solver choice.
log_level : int, optional
Verbosity level. Smaller is more quiet. Default is 0.
Returns
-------
w : ndarray, optional
Eigenvalues.
shape=(size_of_collision_matrix,), dtype='double'
"""
start = time.time()
# Matrix size of collision matrix to be diagonalized.
# The following value is expected:
# ir-colmat: num_ir_grid_points * num_band * 3
# red-colmat: num_mesh_points * num_band
shape = collision_matrices.shape
if len(shape) == 6:
size = shape[2] * shape[3]
assert size == shape[4] * shape[5]
elif len(shape) == 8:
size = np.prod(shape[2:5])
assert size == np.prod(shape[5:8])
elif len(shape) == 2:
size = shape[0]
assert size == shape[1]
solver = _select_solver(pinv_solver)
# [1] dsyev: safer and slower than dsyevd and smallest memory usage
# [2] dsyevd: faster than dsyev and largest memory usage
if solver in [1, 2]:
if log_level:
routine = ['dsyev', 'dsyevd'][solver - 1]
sys.stdout.write("Diagonalizing by lapacke %s... " % routine)
sys.stdout.flush()
import phono3py._phono3py as phono3c
w = np.zeros(size, dtype='double')
if i_sigma is None:
_i_sigma = 0
else:
_i_sigma = i_sigma
if i_temp is None:
_i_temp = 0
else:
_i_temp = i_temp
phono3c.diagonalize_collision_matrix(collision_matrices,
w,
_i_sigma,
_i_temp,
0.0,
(solver + 1) % 2,
0) # only diagonalization
elif solver == 3: # np.linalg.eigh depends on dsyevd.
if log_level:
sys.stdout.write("Diagonalizing by np.linalg.eigh... ")
sys.stdout.flush()
col_mat = collision_matrices[i_sigma, i_temp].reshape(
size, size)
w, col_mat[:] = np.linalg.eigh(col_mat)
elif solver == 4: # fully scipy dsyev
if log_level:
sys.stdout.write("Diagonalizing by "
"scipy.linalg.lapack.dsyev... ")
sys.stdout.flush()
import scipy.linalg
col_mat = collision_matrices[i_sigma, i_temp].reshape(
size, size)
w, _, info = scipy.linalg.lapack.dsyev(col_mat.T, overwrite_a=1)
elif solver == 5: # fully scipy dsyevd
if log_level:
sys.stdout.write("Diagonalizing by "
"scipy.linalg.lapack.dsyevd... ")
sys.stdout.flush()
import scipy.linalg
col_mat = collision_matrices[i_sigma, i_temp].reshape(
size, size)
w, _, info = scipy.linalg.lapack.dsyevd(col_mat.T, overwrite_a=1)
if log_level:
print("[%.3fs]" % (time.time() - start))
sys.stdout.flush()
return w | python | def diagonalize_collision_matrix(collision_matrices,
i_sigma=None,
i_temp=None,
pinv_solver=0,
log_level=0):
"""Diagonalize collision matrices.
Note
----
collision_matricies is overwritten by eigenvectors.
Parameters
----------
collision_matricies : ndarray, optional
Collision matrix. This ndarray has to have the following size and
flags.
shapes:
(sigmas, temperatures, prod(mesh), num_band, prod(mesh), num_band)
(sigmas, temperatures, ir_grid_points, num_band, 3,
ir_grid_points, num_band, 3)
(size, size)
dtype='double', order='C'
i_sigma : int, optional
Index of BZ integration methods, tetrahedron method and smearing
method with widths. Default is None.
i_temp : int, optional
Index of temperature. Default is None.
pinv_solver : int, optional
Diagnalization solver choice.
log_level : int, optional
Verbosity level. Smaller is more quiet. Default is 0.
Returns
-------
w : ndarray, optional
Eigenvalues.
shape=(size_of_collision_matrix,), dtype='double'
"""
start = time.time()
# Matrix size of collision matrix to be diagonalized.
# The following value is expected:
# ir-colmat: num_ir_grid_points * num_band * 3
# red-colmat: num_mesh_points * num_band
shape = collision_matrices.shape
if len(shape) == 6:
size = shape[2] * shape[3]
assert size == shape[4] * shape[5]
elif len(shape) == 8:
size = np.prod(shape[2:5])
assert size == np.prod(shape[5:8])
elif len(shape) == 2:
size = shape[0]
assert size == shape[1]
solver = _select_solver(pinv_solver)
# [1] dsyev: safer and slower than dsyevd and smallest memory usage
# [2] dsyevd: faster than dsyev and largest memory usage
if solver in [1, 2]:
if log_level:
routine = ['dsyev', 'dsyevd'][solver - 1]
sys.stdout.write("Diagonalizing by lapacke %s... " % routine)
sys.stdout.flush()
import phono3py._phono3py as phono3c
w = np.zeros(size, dtype='double')
if i_sigma is None:
_i_sigma = 0
else:
_i_sigma = i_sigma
if i_temp is None:
_i_temp = 0
else:
_i_temp = i_temp
phono3c.diagonalize_collision_matrix(collision_matrices,
w,
_i_sigma,
_i_temp,
0.0,
(solver + 1) % 2,
0) # only diagonalization
elif solver == 3: # np.linalg.eigh depends on dsyevd.
if log_level:
sys.stdout.write("Diagonalizing by np.linalg.eigh... ")
sys.stdout.flush()
col_mat = collision_matrices[i_sigma, i_temp].reshape(
size, size)
w, col_mat[:] = np.linalg.eigh(col_mat)
elif solver == 4: # fully scipy dsyev
if log_level:
sys.stdout.write("Diagonalizing by "
"scipy.linalg.lapack.dsyev... ")
sys.stdout.flush()
import scipy.linalg
col_mat = collision_matrices[i_sigma, i_temp].reshape(
size, size)
w, _, info = scipy.linalg.lapack.dsyev(col_mat.T, overwrite_a=1)
elif solver == 5: # fully scipy dsyevd
if log_level:
sys.stdout.write("Diagonalizing by "
"scipy.linalg.lapack.dsyevd... ")
sys.stdout.flush()
import scipy.linalg
col_mat = collision_matrices[i_sigma, i_temp].reshape(
size, size)
w, _, info = scipy.linalg.lapack.dsyevd(col_mat.T, overwrite_a=1)
if log_level:
print("[%.3fs]" % (time.time() - start))
sys.stdout.flush()
return w | [
"def",
"diagonalize_collision_matrix",
"(",
"collision_matrices",
",",
"i_sigma",
"=",
"None",
",",
"i_temp",
"=",
"None",
",",
"pinv_solver",
"=",
"0",
",",
"log_level",
"=",
"0",
")",
":",
"start",
"=",
"time",
".",
"time",
"(",
")",
"# Matrix size of coll... | Diagonalize collision matrices.
Note
----
collision_matricies is overwritten by eigenvectors.
Parameters
----------
collision_matricies : ndarray, optional
Collision matrix. This ndarray has to have the following size and
flags.
shapes:
(sigmas, temperatures, prod(mesh), num_band, prod(mesh), num_band)
(sigmas, temperatures, ir_grid_points, num_band, 3,
ir_grid_points, num_band, 3)
(size, size)
dtype='double', order='C'
i_sigma : int, optional
Index of BZ integration methods, tetrahedron method and smearing
method with widths. Default is None.
i_temp : int, optional
Index of temperature. Default is None.
pinv_solver : int, optional
Diagnalization solver choice.
log_level : int, optional
Verbosity level. Smaller is more quiet. Default is 0.
Returns
-------
w : ndarray, optional
Eigenvalues.
shape=(size_of_collision_matrix,), dtype='double' | [
"Diagonalize",
"collision",
"matrices",
"."
] | edfcf36cdc7c5392906a9df57d3ee0f3141404df | https://github.com/atztogo/phono3py/blob/edfcf36cdc7c5392906a9df57d3ee0f3141404df/phono3py/phonon3/conductivity_LBTE.py#L609-L724 | train | 212,040 |
atztogo/phono3py | phono3py/phonon3/conductivity_LBTE.py | Conductivity_LBTE._get_weights | def _get_weights(self):
"""Returns weights used for collision matrix and |X> and |f>
self._rot_grid_points : ndarray
shape=(ir_grid_points, point_operations), dtype='uintp'
r_gps : grid points of arms of k-star with duplicates
len(r_gps) == order of crystallographic point group
len(unique(r_gps)) == number of arms of the k-star
Returns
-------
weights : list
sqrt(g_k)/|g|, where g is the crystallographic point group and
g_k is the number of arms of k-star.
"""
weights = []
n = float(self._rot_grid_points.shape[1])
for r_gps in self._rot_grid_points:
weights.append(np.sqrt(len(np.unique(r_gps)) / n))
return weights | python | def _get_weights(self):
"""Returns weights used for collision matrix and |X> and |f>
self._rot_grid_points : ndarray
shape=(ir_grid_points, point_operations), dtype='uintp'
r_gps : grid points of arms of k-star with duplicates
len(r_gps) == order of crystallographic point group
len(unique(r_gps)) == number of arms of the k-star
Returns
-------
weights : list
sqrt(g_k)/|g|, where g is the crystallographic point group and
g_k is the number of arms of k-star.
"""
weights = []
n = float(self._rot_grid_points.shape[1])
for r_gps in self._rot_grid_points:
weights.append(np.sqrt(len(np.unique(r_gps)) / n))
return weights | [
"def",
"_get_weights",
"(",
"self",
")",
":",
"weights",
"=",
"[",
"]",
"n",
"=",
"float",
"(",
"self",
".",
"_rot_grid_points",
".",
"shape",
"[",
"1",
"]",
")",
"for",
"r_gps",
"in",
"self",
".",
"_rot_grid_points",
":",
"weights",
".",
"append",
"... | Returns weights used for collision matrix and |X> and |f>
self._rot_grid_points : ndarray
shape=(ir_grid_points, point_operations), dtype='uintp'
r_gps : grid points of arms of k-star with duplicates
len(r_gps) == order of crystallographic point group
len(unique(r_gps)) == number of arms of the k-star
Returns
-------
weights : list
sqrt(g_k)/|g|, where g is the crystallographic point group and
g_k is the number of arms of k-star. | [
"Returns",
"weights",
"used",
"for",
"collision",
"matrix",
"and",
"|X",
">",
"and",
"|f",
">"
] | edfcf36cdc7c5392906a9df57d3ee0f3141404df | https://github.com/atztogo/phono3py/blob/edfcf36cdc7c5392906a9df57d3ee0f3141404df/phono3py/phonon3/conductivity_LBTE.py#L1211-L1232 | train | 212,041 |
atztogo/phono3py | phono3py/phonon3/conductivity_LBTE.py | Conductivity_LBTE._get_I | def _get_I(self, a, b, size, plus_transpose=True):
"""Return I matrix in Chaput's PRL paper.
None is returned if I is zero matrix.
"""
r_sum = np.zeros((3, 3), dtype='double', order='C')
for r in self._rotations_cartesian:
for i in range(3):
for j in range(3):
r_sum[i, j] += r[a, i] * r[b, j]
if plus_transpose:
r_sum += r_sum.T
# Return None not to consume computer for diagonalization
if (np.abs(r_sum) < 1e-10).all():
return None
# Same as np.kron(np.eye(size), r_sum), but writen as below
# to be sure the values in memory C-congiguous with 'double'.
I_mat = np.zeros((3 * size, 3 * size), dtype='double', order='C')
for i in range(size):
I_mat[(i * 3):((i + 1) * 3), (i * 3):((i + 1) * 3)] = r_sum
return I_mat | python | def _get_I(self, a, b, size, plus_transpose=True):
"""Return I matrix in Chaput's PRL paper.
None is returned if I is zero matrix.
"""
r_sum = np.zeros((3, 3), dtype='double', order='C')
for r in self._rotations_cartesian:
for i in range(3):
for j in range(3):
r_sum[i, j] += r[a, i] * r[b, j]
if plus_transpose:
r_sum += r_sum.T
# Return None not to consume computer for diagonalization
if (np.abs(r_sum) < 1e-10).all():
return None
# Same as np.kron(np.eye(size), r_sum), but writen as below
# to be sure the values in memory C-congiguous with 'double'.
I_mat = np.zeros((3 * size, 3 * size), dtype='double', order='C')
for i in range(size):
I_mat[(i * 3):((i + 1) * 3), (i * 3):((i + 1) * 3)] = r_sum
return I_mat | [
"def",
"_get_I",
"(",
"self",
",",
"a",
",",
"b",
",",
"size",
",",
"plus_transpose",
"=",
"True",
")",
":",
"r_sum",
"=",
"np",
".",
"zeros",
"(",
"(",
"3",
",",
"3",
")",
",",
"dtype",
"=",
"'double'",
",",
"order",
"=",
"'C'",
")",
"for",
... | Return I matrix in Chaput's PRL paper.
None is returned if I is zero matrix. | [
"Return",
"I",
"matrix",
"in",
"Chaput",
"s",
"PRL",
"paper",
"."
] | edfcf36cdc7c5392906a9df57d3ee0f3141404df | https://github.com/atztogo/phono3py/blob/edfcf36cdc7c5392906a9df57d3ee0f3141404df/phono3py/phonon3/conductivity_LBTE.py#L1418-L1442 | train | 212,042 |
atztogo/phono3py | phono3py/phonon3/conductivity_LBTE.py | Conductivity_LBTE._set_mode_kappa_Chaput | def _set_mode_kappa_Chaput(self, i_sigma, i_temp, weights):
"""Calculate mode kappa by the way in Laurent Chaput's PRL paper.
This gives the different result from _set_mode_kappa and requires more
memory space.
"""
X = self._get_X(i_temp, weights, self._gv).ravel()
num_ir_grid_points = len(self._ir_grid_points)
num_band = self._primitive.get_number_of_atoms() * 3
size = num_ir_grid_points * num_band * 3
v = self._collision_matrix[i_sigma, i_temp].reshape(size, size)
solver = _select_solver(self._pinv_solver)
if solver in [1, 2, 4, 5]:
v = v.T
e = self._get_eigvals_pinv(i_sigma, i_temp)
t = self._temperatures[i_temp]
omega_inv = np.empty(v.shape, dtype='double', order='C')
np.dot(v, (e * v).T, out=omega_inv)
Y = np.dot(omega_inv, X)
self._set_f_vectors(Y, num_ir_grid_points, weights)
elems = ((0, 0), (1, 1), (2, 2), (1, 2), (0, 2), (0, 1))
for i, vxf in enumerate(elems):
mat = self._get_I(vxf[0], vxf[1], num_ir_grid_points * num_band)
self._mode_kappa[i_sigma, i_temp, :, :, i] = 0
if mat is not None:
np.dot(mat, omega_inv, out=mat)
# vals = (X ** 2 * np.diag(mat)).reshape(-1, 3).sum(axis=1)
# vals = vals.reshape(num_ir_grid_points, num_band)
# self._mode_kappa[i_sigma, i_temp, :, :, i] = vals
w = diagonalize_collision_matrix(mat,
pinv_solver=self._pinv_solver,
log_level=self._log_level)
if solver in [1, 2, 4, 5]:
mat = mat.T
spectra = np.dot(mat.T, X) ** 2 * w
for s, eigvec in zip(spectra, mat.T):
vals = s * (eigvec ** 2).reshape(-1, 3).sum(axis=1)
vals = vals.reshape(num_ir_grid_points, num_band)
self._mode_kappa[i_sigma, i_temp, :, :, i] += vals
factor = self._conversion_factor * Kb * t ** 2
self._mode_kappa[i_sigma, i_temp] *= factor | python | def _set_mode_kappa_Chaput(self, i_sigma, i_temp, weights):
"""Calculate mode kappa by the way in Laurent Chaput's PRL paper.
This gives the different result from _set_mode_kappa and requires more
memory space.
"""
X = self._get_X(i_temp, weights, self._gv).ravel()
num_ir_grid_points = len(self._ir_grid_points)
num_band = self._primitive.get_number_of_atoms() * 3
size = num_ir_grid_points * num_band * 3
v = self._collision_matrix[i_sigma, i_temp].reshape(size, size)
solver = _select_solver(self._pinv_solver)
if solver in [1, 2, 4, 5]:
v = v.T
e = self._get_eigvals_pinv(i_sigma, i_temp)
t = self._temperatures[i_temp]
omega_inv = np.empty(v.shape, dtype='double', order='C')
np.dot(v, (e * v).T, out=omega_inv)
Y = np.dot(omega_inv, X)
self._set_f_vectors(Y, num_ir_grid_points, weights)
elems = ((0, 0), (1, 1), (2, 2), (1, 2), (0, 2), (0, 1))
for i, vxf in enumerate(elems):
mat = self._get_I(vxf[0], vxf[1], num_ir_grid_points * num_band)
self._mode_kappa[i_sigma, i_temp, :, :, i] = 0
if mat is not None:
np.dot(mat, omega_inv, out=mat)
# vals = (X ** 2 * np.diag(mat)).reshape(-1, 3).sum(axis=1)
# vals = vals.reshape(num_ir_grid_points, num_band)
# self._mode_kappa[i_sigma, i_temp, :, :, i] = vals
w = diagonalize_collision_matrix(mat,
pinv_solver=self._pinv_solver,
log_level=self._log_level)
if solver in [1, 2, 4, 5]:
mat = mat.T
spectra = np.dot(mat.T, X) ** 2 * w
for s, eigvec in zip(spectra, mat.T):
vals = s * (eigvec ** 2).reshape(-1, 3).sum(axis=1)
vals = vals.reshape(num_ir_grid_points, num_band)
self._mode_kappa[i_sigma, i_temp, :, :, i] += vals
factor = self._conversion_factor * Kb * t ** 2
self._mode_kappa[i_sigma, i_temp] *= factor | [
"def",
"_set_mode_kappa_Chaput",
"(",
"self",
",",
"i_sigma",
",",
"i_temp",
",",
"weights",
")",
":",
"X",
"=",
"self",
".",
"_get_X",
"(",
"i_temp",
",",
"weights",
",",
"self",
".",
"_gv",
")",
".",
"ravel",
"(",
")",
"num_ir_grid_points",
"=",
"len... | Calculate mode kappa by the way in Laurent Chaput's PRL paper.
This gives the different result from _set_mode_kappa and requires more
memory space. | [
"Calculate",
"mode",
"kappa",
"by",
"the",
"way",
"in",
"Laurent",
"Chaput",
"s",
"PRL",
"paper",
"."
] | edfcf36cdc7c5392906a9df57d3ee0f3141404df | https://github.com/atztogo/phono3py/blob/edfcf36cdc7c5392906a9df57d3ee0f3141404df/phono3py/phonon3/conductivity_LBTE.py#L1591-L1635 | train | 212,043 |
atztogo/phono3py | phono3py/phonon3/displacement_fc3.py | get_third_order_displacements | def get_third_order_displacements(cell,
symmetry,
is_plusminus='auto',
is_diagonal=False):
"""Create dispalcement dataset
Note
----
Atoms 1, 2, and 3 are defined as follows:
Atom 1: The first displaced atom. Third order force constant
between Atoms 1, 2, and 3 is calculated.
Atom 2: The second displaced atom. Second order force constant
between Atoms 2 and 3 is calculated.
Atom 3: Force is mesuared on this atom.
Parameters
----------
cell : PhonopyAtoms
Supercell
symmetry : Symmetry
Symmetry of supercell
is_plusminus : str or bool, optional
Type of displacements, plus only (False), always plus and minus (True),
and plus and minus depending on site symmetry ('auto').
is_diagonal : bool, optional
Whether allow diagonal displacements of Atom 2 or not
Returns
-------
dict
Data structure is like:
{'natom': 64,
'cutoff_distance': 4.000000,
'first_atoms':
[{'number': atom1,
'displacement': [0.03, 0., 0.],
'second_atoms': [ {'number': atom2,
'displacement': [0., -0.03, 0.],
'distance': 2.353},
{'number': ... }, ... ] },
{'number': atom1, ... } ]}
"""
positions = cell.get_scaled_positions()
lattice = cell.get_cell().T
# Least displacements of first atoms (Atom 1) are searched by
# using respective site symmetries of the original crystal.
# 'is_diagonal=False' below is made intentionally to expect
# better accuracy.
disps_first = get_least_displacements(symmetry,
is_plusminus=is_plusminus,
is_diagonal=False)
symprec = symmetry.get_symmetry_tolerance()
dds = []
for disp in disps_first:
atom1 = disp[0]
disp1 = disp[1:4]
site_sym = symmetry.get_site_symmetry(atom1)
dds_atom1 = {'number': atom1,
'direction': disp1,
'second_atoms': []}
# Reduced site symmetry at the first atom with respect to
# the displacement of the first atoms.
reduced_site_sym = get_reduced_site_symmetry(site_sym, disp1, symprec)
# Searching orbits (second atoms) with respect to
# the first atom and its reduced site symmetry.
second_atoms = get_least_orbits(atom1,
cell,
reduced_site_sym,
symprec)
for atom2 in second_atoms:
dds_atom2 = get_next_displacements(atom1,
atom2,
reduced_site_sym,
lattice,
positions,
symprec,
is_diagonal)
min_vec = get_equivalent_smallest_vectors(atom1,
atom2,
cell,
symprec)[0]
min_distance = np.linalg.norm(np.dot(lattice, min_vec))
dds_atom2['distance'] = min_distance
dds_atom1['second_atoms'].append(dds_atom2)
dds.append(dds_atom1)
return dds | python | def get_third_order_displacements(cell,
symmetry,
is_plusminus='auto',
is_diagonal=False):
"""Create dispalcement dataset
Note
----
Atoms 1, 2, and 3 are defined as follows:
Atom 1: The first displaced atom. Third order force constant
between Atoms 1, 2, and 3 is calculated.
Atom 2: The second displaced atom. Second order force constant
between Atoms 2 and 3 is calculated.
Atom 3: Force is mesuared on this atom.
Parameters
----------
cell : PhonopyAtoms
Supercell
symmetry : Symmetry
Symmetry of supercell
is_plusminus : str or bool, optional
Type of displacements, plus only (False), always plus and minus (True),
and plus and minus depending on site symmetry ('auto').
is_diagonal : bool, optional
Whether allow diagonal displacements of Atom 2 or not
Returns
-------
dict
Data structure is like:
{'natom': 64,
'cutoff_distance': 4.000000,
'first_atoms':
[{'number': atom1,
'displacement': [0.03, 0., 0.],
'second_atoms': [ {'number': atom2,
'displacement': [0., -0.03, 0.],
'distance': 2.353},
{'number': ... }, ... ] },
{'number': atom1, ... } ]}
"""
positions = cell.get_scaled_positions()
lattice = cell.get_cell().T
# Least displacements of first atoms (Atom 1) are searched by
# using respective site symmetries of the original crystal.
# 'is_diagonal=False' below is made intentionally to expect
# better accuracy.
disps_first = get_least_displacements(symmetry,
is_plusminus=is_plusminus,
is_diagonal=False)
symprec = symmetry.get_symmetry_tolerance()
dds = []
for disp in disps_first:
atom1 = disp[0]
disp1 = disp[1:4]
site_sym = symmetry.get_site_symmetry(atom1)
dds_atom1 = {'number': atom1,
'direction': disp1,
'second_atoms': []}
# Reduced site symmetry at the first atom with respect to
# the displacement of the first atoms.
reduced_site_sym = get_reduced_site_symmetry(site_sym, disp1, symprec)
# Searching orbits (second atoms) with respect to
# the first atom and its reduced site symmetry.
second_atoms = get_least_orbits(atom1,
cell,
reduced_site_sym,
symprec)
for atom2 in second_atoms:
dds_atom2 = get_next_displacements(atom1,
atom2,
reduced_site_sym,
lattice,
positions,
symprec,
is_diagonal)
min_vec = get_equivalent_smallest_vectors(atom1,
atom2,
cell,
symprec)[0]
min_distance = np.linalg.norm(np.dot(lattice, min_vec))
dds_atom2['distance'] = min_distance
dds_atom1['second_atoms'].append(dds_atom2)
dds.append(dds_atom1)
return dds | [
"def",
"get_third_order_displacements",
"(",
"cell",
",",
"symmetry",
",",
"is_plusminus",
"=",
"'auto'",
",",
"is_diagonal",
"=",
"False",
")",
":",
"positions",
"=",
"cell",
".",
"get_scaled_positions",
"(",
")",
"lattice",
"=",
"cell",
".",
"get_cell",
"(",... | Create dispalcement dataset
Note
----
Atoms 1, 2, and 3 are defined as follows:
Atom 1: The first displaced atom. Third order force constant
between Atoms 1, 2, and 3 is calculated.
Atom 2: The second displaced atom. Second order force constant
between Atoms 2 and 3 is calculated.
Atom 3: Force is mesuared on this atom.
Parameters
----------
cell : PhonopyAtoms
Supercell
symmetry : Symmetry
Symmetry of supercell
is_plusminus : str or bool, optional
Type of displacements, plus only (False), always plus and minus (True),
and plus and minus depending on site symmetry ('auto').
is_diagonal : bool, optional
Whether allow diagonal displacements of Atom 2 or not
Returns
-------
dict
Data structure is like:
{'natom': 64,
'cutoff_distance': 4.000000,
'first_atoms':
[{'number': atom1,
'displacement': [0.03, 0., 0.],
'second_atoms': [ {'number': atom2,
'displacement': [0., -0.03, 0.],
'distance': 2.353},
{'number': ... }, ... ] },
{'number': atom1, ... } ]} | [
"Create",
"dispalcement",
"dataset"
] | edfcf36cdc7c5392906a9df57d3ee0f3141404df | https://github.com/atztogo/phono3py/blob/edfcf36cdc7c5392906a9df57d3ee0f3141404df/phono3py/phonon3/displacement_fc3.py#L52-L148 | train | 212,044 |
atztogo/phono3py | phono3py/phonon3/displacement_fc3.py | get_bond_symmetry | def get_bond_symmetry(site_symmetry,
lattice,
positions,
atom_center,
atom_disp,
symprec=1e-5):
"""
Bond symmetry is the symmetry operations that keep the symmetry
of the cell containing two fixed atoms.
"""
bond_sym = []
pos = positions
for rot in site_symmetry:
rot_pos = (np.dot(pos[atom_disp] - pos[atom_center], rot.T) +
pos[atom_center])
diff = pos[atom_disp] - rot_pos
diff -= np.rint(diff)
dist = np.linalg.norm(np.dot(lattice, diff))
if dist < symprec:
bond_sym.append(rot)
return np.array(bond_sym) | python | def get_bond_symmetry(site_symmetry,
lattice,
positions,
atom_center,
atom_disp,
symprec=1e-5):
"""
Bond symmetry is the symmetry operations that keep the symmetry
of the cell containing two fixed atoms.
"""
bond_sym = []
pos = positions
for rot in site_symmetry:
rot_pos = (np.dot(pos[atom_disp] - pos[atom_center], rot.T) +
pos[atom_center])
diff = pos[atom_disp] - rot_pos
diff -= np.rint(diff)
dist = np.linalg.norm(np.dot(lattice, diff))
if dist < symprec:
bond_sym.append(rot)
return np.array(bond_sym) | [
"def",
"get_bond_symmetry",
"(",
"site_symmetry",
",",
"lattice",
",",
"positions",
",",
"atom_center",
",",
"atom_disp",
",",
"symprec",
"=",
"1e-5",
")",
":",
"bond_sym",
"=",
"[",
"]",
"pos",
"=",
"positions",
"for",
"rot",
"in",
"site_symmetry",
":",
"... | Bond symmetry is the symmetry operations that keep the symmetry
of the cell containing two fixed atoms. | [
"Bond",
"symmetry",
"is",
"the",
"symmetry",
"operations",
"that",
"keep",
"the",
"symmetry",
"of",
"the",
"cell",
"containing",
"two",
"fixed",
"atoms",
"."
] | edfcf36cdc7c5392906a9df57d3ee0f3141404df | https://github.com/atztogo/phono3py/blob/edfcf36cdc7c5392906a9df57d3ee0f3141404df/phono3py/phonon3/displacement_fc3.py#L194-L215 | train | 212,045 |
atztogo/phono3py | phono3py/phonon3/displacement_fc3.py | get_least_orbits | def get_least_orbits(atom_index, cell, site_symmetry, symprec=1e-5):
"""Find least orbits for a centering atom"""
orbits = _get_orbits(atom_index, cell, site_symmetry, symprec)
mapping = np.arange(cell.get_number_of_atoms())
for i, orb in enumerate(orbits):
for num in np.unique(orb):
if mapping[num] > mapping[i]:
mapping[num] = mapping[i]
return np.unique(mapping) | python | def get_least_orbits(atom_index, cell, site_symmetry, symprec=1e-5):
"""Find least orbits for a centering atom"""
orbits = _get_orbits(atom_index, cell, site_symmetry, symprec)
mapping = np.arange(cell.get_number_of_atoms())
for i, orb in enumerate(orbits):
for num in np.unique(orb):
if mapping[num] > mapping[i]:
mapping[num] = mapping[i]
return np.unique(mapping) | [
"def",
"get_least_orbits",
"(",
"atom_index",
",",
"cell",
",",
"site_symmetry",
",",
"symprec",
"=",
"1e-5",
")",
":",
"orbits",
"=",
"_get_orbits",
"(",
"atom_index",
",",
"cell",
",",
"site_symmetry",
",",
"symprec",
")",
"mapping",
"=",
"np",
".",
"ara... | Find least orbits for a centering atom | [
"Find",
"least",
"orbits",
"for",
"a",
"centering",
"atom"
] | edfcf36cdc7c5392906a9df57d3ee0f3141404df | https://github.com/atztogo/phono3py/blob/edfcf36cdc7c5392906a9df57d3ee0f3141404df/phono3py/phonon3/displacement_fc3.py#L218-L228 | train | 212,046 |
atztogo/phono3py | phono3py/file_IO.py | write_fc3_to_hdf5 | def write_fc3_to_hdf5(fc3,
filename='fc3.hdf5',
p2s_map=None,
compression=None):
"""Write third-order force constants in hdf5 format.
Parameters
----------
force_constants : ndarray
Force constants
shape=(n_satom, n_satom, n_satom, 3, 3, 3) or
(n_patom, n_satom, n_satom,3,3,3), dtype=double
filename : str
Filename to be used.
p2s_map : ndarray, optional
Primitive atom indices in supercell index system
shape=(n_patom,), dtype=intc
compression : str or int, optional
h5py's lossless compression filters (e.g., "gzip", "lzf").
See the detail at docstring of h5py.Group.create_dataset. Default is
None.
"""
with h5py.File(filename, 'w') as w:
w.create_dataset('fc3', data=fc3, compression=compression)
if p2s_map is not None:
w.create_dataset('p2s_map', data=p2s_map) | python | def write_fc3_to_hdf5(fc3,
filename='fc3.hdf5',
p2s_map=None,
compression=None):
"""Write third-order force constants in hdf5 format.
Parameters
----------
force_constants : ndarray
Force constants
shape=(n_satom, n_satom, n_satom, 3, 3, 3) or
(n_patom, n_satom, n_satom,3,3,3), dtype=double
filename : str
Filename to be used.
p2s_map : ndarray, optional
Primitive atom indices in supercell index system
shape=(n_patom,), dtype=intc
compression : str or int, optional
h5py's lossless compression filters (e.g., "gzip", "lzf").
See the detail at docstring of h5py.Group.create_dataset. Default is
None.
"""
with h5py.File(filename, 'w') as w:
w.create_dataset('fc3', data=fc3, compression=compression)
if p2s_map is not None:
w.create_dataset('p2s_map', data=p2s_map) | [
"def",
"write_fc3_to_hdf5",
"(",
"fc3",
",",
"filename",
"=",
"'fc3.hdf5'",
",",
"p2s_map",
"=",
"None",
",",
"compression",
"=",
"None",
")",
":",
"with",
"h5py",
".",
"File",
"(",
"filename",
",",
"'w'",
")",
"as",
"w",
":",
"w",
".",
"create_dataset... | Write third-order force constants in hdf5 format.
Parameters
----------
force_constants : ndarray
Force constants
shape=(n_satom, n_satom, n_satom, 3, 3, 3) or
(n_patom, n_satom, n_satom,3,3,3), dtype=double
filename : str
Filename to be used.
p2s_map : ndarray, optional
Primitive atom indices in supercell index system
shape=(n_patom,), dtype=intc
compression : str or int, optional
h5py's lossless compression filters (e.g., "gzip", "lzf").
See the detail at docstring of h5py.Group.create_dataset. Default is
None. | [
"Write",
"third",
"-",
"order",
"force",
"constants",
"in",
"hdf5",
"format",
"."
] | edfcf36cdc7c5392906a9df57d3ee0f3141404df | https://github.com/atztogo/phono3py/blob/edfcf36cdc7c5392906a9df57d3ee0f3141404df/phono3py/file_IO.py#L184-L211 | train | 212,047 |
atztogo/phono3py | phono3py/file_IO.py | write_unitary_matrix_to_hdf5 | def write_unitary_matrix_to_hdf5(temperature,
mesh,
unitary_matrix=None,
sigma=None,
sigma_cutoff=None,
solver=None,
filename=None,
verbose=False):
"""Write eigenvectors of collision matrices at temperatures.
Depending on the choice of the solver, eigenvectors are sotred in
either column-wise or row-wise.
"""
suffix = _get_filename_suffix(mesh,
sigma=sigma,
sigma_cutoff=sigma_cutoff,
filename=filename)
hdf5_filename = "unitary" + suffix + ".hdf5"
with h5py.File(hdf5_filename, 'w') as w:
w.create_dataset('temperature', data=temperature)
if unitary_matrix is not None:
w.create_dataset('unitary_matrix', data=unitary_matrix)
if solver is not None:
w.create_dataset('solver', data=solver)
if verbose:
if len(temperature) > 1:
text = "Unitary matrices "
else:
text = "Unitary matrix "
if sigma is not None:
text += "at sigma %s " % _del_zeros(sigma)
if sigma_cutoff is not None:
text += "(%4.2f SD) " % sigma_cutoff
if len(temperature) > 1:
text += "were written into "
else:
text += "was written into "
if sigma is not None:
text += "\n"
text += "\"%s\"." % hdf5_filename
print(text) | python | def write_unitary_matrix_to_hdf5(temperature,
mesh,
unitary_matrix=None,
sigma=None,
sigma_cutoff=None,
solver=None,
filename=None,
verbose=False):
"""Write eigenvectors of collision matrices at temperatures.
Depending on the choice of the solver, eigenvectors are sotred in
either column-wise or row-wise.
"""
suffix = _get_filename_suffix(mesh,
sigma=sigma,
sigma_cutoff=sigma_cutoff,
filename=filename)
hdf5_filename = "unitary" + suffix + ".hdf5"
with h5py.File(hdf5_filename, 'w') as w:
w.create_dataset('temperature', data=temperature)
if unitary_matrix is not None:
w.create_dataset('unitary_matrix', data=unitary_matrix)
if solver is not None:
w.create_dataset('solver', data=solver)
if verbose:
if len(temperature) > 1:
text = "Unitary matrices "
else:
text = "Unitary matrix "
if sigma is not None:
text += "at sigma %s " % _del_zeros(sigma)
if sigma_cutoff is not None:
text += "(%4.2f SD) " % sigma_cutoff
if len(temperature) > 1:
text += "were written into "
else:
text += "was written into "
if sigma is not None:
text += "\n"
text += "\"%s\"." % hdf5_filename
print(text) | [
"def",
"write_unitary_matrix_to_hdf5",
"(",
"temperature",
",",
"mesh",
",",
"unitary_matrix",
"=",
"None",
",",
"sigma",
"=",
"None",
",",
"sigma_cutoff",
"=",
"None",
",",
"solver",
"=",
"None",
",",
"filename",
"=",
"None",
",",
"verbose",
"=",
"False",
... | Write eigenvectors of collision matrices at temperatures.
Depending on the choice of the solver, eigenvectors are sotred in
either column-wise or row-wise. | [
"Write",
"eigenvectors",
"of",
"collision",
"matrices",
"at",
"temperatures",
"."
] | edfcf36cdc7c5392906a9df57d3ee0f3141404df | https://github.com/atztogo/phono3py/blob/edfcf36cdc7c5392906a9df57d3ee0f3141404df/phono3py/file_IO.py#L546-L589 | train | 212,048 |
atztogo/phono3py | phono3py/phonon3/__init__.py | Phono3py.get_frequency_shift | def get_frequency_shift(
self,
grid_points,
temperatures=np.arange(0, 1001, 10, dtype='double'),
epsilons=None,
output_filename=None):
"""Frequency shift from lowest order diagram is calculated.
Args:
epslins(list of float):
The value to avoid divergence. When multiple values are given
frequency shifts for those values are returned.
"""
if self._interaction is None:
self.set_phph_interaction()
if epsilons is None:
_epsilons = [0.1]
else:
_epsilons = epsilons
self._grid_points = grid_points
get_frequency_shift(self._interaction,
self._grid_points,
self._band_indices,
_epsilons,
temperatures,
output_filename=output_filename,
log_level=self._log_level) | python | def get_frequency_shift(
self,
grid_points,
temperatures=np.arange(0, 1001, 10, dtype='double'),
epsilons=None,
output_filename=None):
"""Frequency shift from lowest order diagram is calculated.
Args:
epslins(list of float):
The value to avoid divergence. When multiple values are given
frequency shifts for those values are returned.
"""
if self._interaction is None:
self.set_phph_interaction()
if epsilons is None:
_epsilons = [0.1]
else:
_epsilons = epsilons
self._grid_points = grid_points
get_frequency_shift(self._interaction,
self._grid_points,
self._band_indices,
_epsilons,
temperatures,
output_filename=output_filename,
log_level=self._log_level) | [
"def",
"get_frequency_shift",
"(",
"self",
",",
"grid_points",
",",
"temperatures",
"=",
"np",
".",
"arange",
"(",
"0",
",",
"1001",
",",
"10",
",",
"dtype",
"=",
"'double'",
")",
",",
"epsilons",
"=",
"None",
",",
"output_filename",
"=",
"None",
")",
... | Frequency shift from lowest order diagram is calculated.
Args:
epslins(list of float):
The value to avoid divergence. When multiple values are given
frequency shifts for those values are returned. | [
"Frequency",
"shift",
"from",
"lowest",
"order",
"diagram",
"is",
"calculated",
"."
] | edfcf36cdc7c5392906a9df57d3ee0f3141404df | https://github.com/atztogo/phono3py/blob/edfcf36cdc7c5392906a9df57d3ee0f3141404df/phono3py/phonon3/__init__.py#L667-L695 | train | 212,049 |
atztogo/phono3py | phono3py/phonon3/triplets.py | _get_triplets_reciprocal_mesh_at_q | def _get_triplets_reciprocal_mesh_at_q(fixed_grid_number,
mesh,
rotations,
is_time_reversal=True,
swappable=True):
"""Search symmetry reduced triplets fixing one q-point
Triplets of (q0, q1, q2) are searched.
Parameters
----------
fixed_grid_number : int
Grid point of q0
mesh : array_like
Mesh numbers
dtype='intc'
shape=(3,)
rotations : array_like
Rotation matrices in real space. Note that those in reciprocal space
mean these matrices transposed (local terminology).
dtype='intc'
shape=(n_rot, 3, 3)
is_time_reversal : bool
Inversion symemtry is added if it doesn't exist.
swappable : bool
q1 and q2 can be swapped. By this number of triplets decreases.
"""
import phono3py._phono3py as phono3c
map_triplets = np.zeros(np.prod(mesh), dtype='uintp')
map_q = np.zeros(np.prod(mesh), dtype='uintp')
grid_address = np.zeros((np.prod(mesh), 3), dtype='intc')
phono3c.triplets_reciprocal_mesh_at_q(
map_triplets,
map_q,
grid_address,
fixed_grid_number,
np.array(mesh, dtype='intc'),
is_time_reversal * 1,
np.array(rotations, dtype='intc', order='C'),
swappable * 1)
return map_triplets, map_q, grid_address | python | def _get_triplets_reciprocal_mesh_at_q(fixed_grid_number,
mesh,
rotations,
is_time_reversal=True,
swappable=True):
"""Search symmetry reduced triplets fixing one q-point
Triplets of (q0, q1, q2) are searched.
Parameters
----------
fixed_grid_number : int
Grid point of q0
mesh : array_like
Mesh numbers
dtype='intc'
shape=(3,)
rotations : array_like
Rotation matrices in real space. Note that those in reciprocal space
mean these matrices transposed (local terminology).
dtype='intc'
shape=(n_rot, 3, 3)
is_time_reversal : bool
Inversion symemtry is added if it doesn't exist.
swappable : bool
q1 and q2 can be swapped. By this number of triplets decreases.
"""
import phono3py._phono3py as phono3c
map_triplets = np.zeros(np.prod(mesh), dtype='uintp')
map_q = np.zeros(np.prod(mesh), dtype='uintp')
grid_address = np.zeros((np.prod(mesh), 3), dtype='intc')
phono3c.triplets_reciprocal_mesh_at_q(
map_triplets,
map_q,
grid_address,
fixed_grid_number,
np.array(mesh, dtype='intc'),
is_time_reversal * 1,
np.array(rotations, dtype='intc', order='C'),
swappable * 1)
return map_triplets, map_q, grid_address | [
"def",
"_get_triplets_reciprocal_mesh_at_q",
"(",
"fixed_grid_number",
",",
"mesh",
",",
"rotations",
",",
"is_time_reversal",
"=",
"True",
",",
"swappable",
"=",
"True",
")",
":",
"import",
"phono3py",
".",
"_phono3py",
"as",
"phono3c",
"map_triplets",
"=",
"np",... | Search symmetry reduced triplets fixing one q-point
Triplets of (q0, q1, q2) are searched.
Parameters
----------
fixed_grid_number : int
Grid point of q0
mesh : array_like
Mesh numbers
dtype='intc'
shape=(3,)
rotations : array_like
Rotation matrices in real space. Note that those in reciprocal space
mean these matrices transposed (local terminology).
dtype='intc'
shape=(n_rot, 3, 3)
is_time_reversal : bool
Inversion symemtry is added if it doesn't exist.
swappable : bool
q1 and q2 can be swapped. By this number of triplets decreases. | [
"Search",
"symmetry",
"reduced",
"triplets",
"fixing",
"one",
"q",
"-",
"point"
] | edfcf36cdc7c5392906a9df57d3ee0f3141404df | https://github.com/atztogo/phono3py/blob/edfcf36cdc7c5392906a9df57d3ee0f3141404df/phono3py/phonon3/triplets.py#L476-L521 | train | 212,050 |
atztogo/phono3py | phono3py/phonon3/interaction.py | Interaction.get_averaged_interaction | def get_averaged_interaction(self):
"""Return sum over phonon triplets of interaction strength
See Eq.(21) of PRB 91, 094306 (2015)
"""
# v[triplet, band0, band, band]
v = self._interaction_strength
w = self._weights_at_q
v_sum = np.dot(w, v.sum(axis=2).sum(axis=2))
return v_sum / np.prod(v.shape[2:]) | python | def get_averaged_interaction(self):
"""Return sum over phonon triplets of interaction strength
See Eq.(21) of PRB 91, 094306 (2015)
"""
# v[triplet, band0, band, band]
v = self._interaction_strength
w = self._weights_at_q
v_sum = np.dot(w, v.sum(axis=2).sum(axis=2))
return v_sum / np.prod(v.shape[2:]) | [
"def",
"get_averaged_interaction",
"(",
"self",
")",
":",
"# v[triplet, band0, band, band]",
"v",
"=",
"self",
".",
"_interaction_strength",
"w",
"=",
"self",
".",
"_weights_at_q",
"v_sum",
"=",
"np",
".",
"dot",
"(",
"w",
",",
"v",
".",
"sum",
"(",
"axis",
... | Return sum over phonon triplets of interaction strength
See Eq.(21) of PRB 91, 094306 (2015) | [
"Return",
"sum",
"over",
"phonon",
"triplets",
"of",
"interaction",
"strength"
] | edfcf36cdc7c5392906a9df57d3ee0f3141404df | https://github.com/atztogo/phono3py/blob/edfcf36cdc7c5392906a9df57d3ee0f3141404df/phono3py/phonon3/interaction.py#L160-L171 | train | 212,051 |
atztogo/phono3py | phono3py/other/alm_wrapper.py | optimize | def optimize(lattice,
positions,
numbers,
displacements,
forces,
alm_options=None,
p2s_map=None,
p2p_map=None,
log_level=0):
"""Calculate force constants
lattice : array_like
Basis vectors. a, b, c are given as column vectors.
shape=(3, 3), dtype='double'
positions : array_like
Fractional coordinates of atomic points.
shape=(num_atoms, 3), dtype='double'
numbers : array_like
Atomic numbers.
shape=(num_atoms,), dtype='intc'
displacements : array_like
Atomic displacement patterns in supercells in Cartesian.
dtype='double', shape=(supercells, num_atoms, 3)
forces : array_like
Forces in supercells.
dtype='double', shape=(supercells, num_atoms, 3)
alm_options : dict, optional
Default is None.
List of keys
cutoff_distance : float
solver : str
Either 'SimplicialLDLT' or 'dense'. Default is
'SimplicialLDLT'.
"""
from alm import ALM
with ALM(lattice, positions, numbers) as alm:
natom = len(numbers)
alm.set_verbosity(log_level)
nkd = len(np.unique(numbers))
if 'cutoff_distance' not in alm_options:
rcs = -np.ones((2, nkd, nkd), dtype='double')
elif type(alm_options['cutoff_distance']) is float:
rcs = np.ones((2, nkd, nkd), dtype='double')
rcs[0] *= -1
rcs[1] *= alm_options['cutoff_distance']
alm.define(2, rcs)
alm.set_displacement_and_force(displacements, forces)
if 'solver' in alm_options:
solver = alm_options['solver']
else:
solver = 'SimplicialLDLT'
info = alm.optimize(solver=solver)
fc2 = extract_fc2_from_alm(alm,
natom,
atom_list=p2s_map,
p2s_map=p2s_map,
p2p_map=p2p_map)
fc3 = _extract_fc3_from_alm(alm,
natom,
p2s_map=p2s_map,
p2p_map=p2p_map)
return fc2, fc3 | python | def optimize(lattice,
positions,
numbers,
displacements,
forces,
alm_options=None,
p2s_map=None,
p2p_map=None,
log_level=0):
"""Calculate force constants
lattice : array_like
Basis vectors. a, b, c are given as column vectors.
shape=(3, 3), dtype='double'
positions : array_like
Fractional coordinates of atomic points.
shape=(num_atoms, 3), dtype='double'
numbers : array_like
Atomic numbers.
shape=(num_atoms,), dtype='intc'
displacements : array_like
Atomic displacement patterns in supercells in Cartesian.
dtype='double', shape=(supercells, num_atoms, 3)
forces : array_like
Forces in supercells.
dtype='double', shape=(supercells, num_atoms, 3)
alm_options : dict, optional
Default is None.
List of keys
cutoff_distance : float
solver : str
Either 'SimplicialLDLT' or 'dense'. Default is
'SimplicialLDLT'.
"""
from alm import ALM
with ALM(lattice, positions, numbers) as alm:
natom = len(numbers)
alm.set_verbosity(log_level)
nkd = len(np.unique(numbers))
if 'cutoff_distance' not in alm_options:
rcs = -np.ones((2, nkd, nkd), dtype='double')
elif type(alm_options['cutoff_distance']) is float:
rcs = np.ones((2, nkd, nkd), dtype='double')
rcs[0] *= -1
rcs[1] *= alm_options['cutoff_distance']
alm.define(2, rcs)
alm.set_displacement_and_force(displacements, forces)
if 'solver' in alm_options:
solver = alm_options['solver']
else:
solver = 'SimplicialLDLT'
info = alm.optimize(solver=solver)
fc2 = extract_fc2_from_alm(alm,
natom,
atom_list=p2s_map,
p2s_map=p2s_map,
p2p_map=p2p_map)
fc3 = _extract_fc3_from_alm(alm,
natom,
p2s_map=p2s_map,
p2p_map=p2p_map)
return fc2, fc3 | [
"def",
"optimize",
"(",
"lattice",
",",
"positions",
",",
"numbers",
",",
"displacements",
",",
"forces",
",",
"alm_options",
"=",
"None",
",",
"p2s_map",
"=",
"None",
",",
"p2p_map",
"=",
"None",
",",
"log_level",
"=",
"0",
")",
":",
"from",
"alm",
"i... | Calculate force constants
lattice : array_like
Basis vectors. a, b, c are given as column vectors.
shape=(3, 3), dtype='double'
positions : array_like
Fractional coordinates of atomic points.
shape=(num_atoms, 3), dtype='double'
numbers : array_like
Atomic numbers.
shape=(num_atoms,), dtype='intc'
displacements : array_like
Atomic displacement patterns in supercells in Cartesian.
dtype='double', shape=(supercells, num_atoms, 3)
forces : array_like
Forces in supercells.
dtype='double', shape=(supercells, num_atoms, 3)
alm_options : dict, optional
Default is None.
List of keys
cutoff_distance : float
solver : str
Either 'SimplicialLDLT' or 'dense'. Default is
'SimplicialLDLT'. | [
"Calculate",
"force",
"constants"
] | edfcf36cdc7c5392906a9df57d3ee0f3141404df | https://github.com/atztogo/phono3py/blob/edfcf36cdc7c5392906a9df57d3ee0f3141404df/phono3py/other/alm_wrapper.py#L94-L158 | train | 212,052 |
atztogo/phono3py | phono3py/other/alm_wrapper.py | _get_alm_disp_fc3 | def _get_alm_disp_fc3(disp_dataset):
"""Create displacements of atoms for ALM input
Note
----
Dipslacements of all atoms in supercells for all displacement
configurations in phono3py are returned, i.e., most of
displacements are zero. Only the configurations with 'included' ==
True are included in the list of indices that is returned, too.
Parameters
----------
disp_dataset : dict
Displacement dataset that may be obtained by
file_IO.parse_disp_fc3_yaml.
Returns
-------
disp : ndarray
Displacements of atoms in supercells of all displacement
configurations.
shape=(ndisp, natom, 3)
dtype='double'
indices : list of int
The indices of the displacement configurations with 'included' == True.
"""
natom = disp_dataset['natom']
ndisp = len(disp_dataset['first_atoms'])
for disp1 in disp_dataset['first_atoms']:
ndisp += len(disp1['second_atoms'])
disp = np.zeros((ndisp, natom, 3), dtype='double', order='C')
indices = []
count = 0
for disp1 in disp_dataset['first_atoms']:
indices.append(count)
disp[count, disp1['number']] = disp1['displacement']
count += 1
for disp1 in disp_dataset['first_atoms']:
for disp2 in disp1['second_atoms']:
if 'included' in disp2:
if disp2['included']:
indices.append(count)
else:
indices.append(count)
disp[count, disp1['number']] = disp1['displacement']
disp[count, disp2['number']] = disp2['displacement']
count += 1
return disp, indices | python | def _get_alm_disp_fc3(disp_dataset):
"""Create displacements of atoms for ALM input
Note
----
Dipslacements of all atoms in supercells for all displacement
configurations in phono3py are returned, i.e., most of
displacements are zero. Only the configurations with 'included' ==
True are included in the list of indices that is returned, too.
Parameters
----------
disp_dataset : dict
Displacement dataset that may be obtained by
file_IO.parse_disp_fc3_yaml.
Returns
-------
disp : ndarray
Displacements of atoms in supercells of all displacement
configurations.
shape=(ndisp, natom, 3)
dtype='double'
indices : list of int
The indices of the displacement configurations with 'included' == True.
"""
natom = disp_dataset['natom']
ndisp = len(disp_dataset['first_atoms'])
for disp1 in disp_dataset['first_atoms']:
ndisp += len(disp1['second_atoms'])
disp = np.zeros((ndisp, natom, 3), dtype='double', order='C')
indices = []
count = 0
for disp1 in disp_dataset['first_atoms']:
indices.append(count)
disp[count, disp1['number']] = disp1['displacement']
count += 1
for disp1 in disp_dataset['first_atoms']:
for disp2 in disp1['second_atoms']:
if 'included' in disp2:
if disp2['included']:
indices.append(count)
else:
indices.append(count)
disp[count, disp1['number']] = disp1['displacement']
disp[count, disp2['number']] = disp2['displacement']
count += 1
return disp, indices | [
"def",
"_get_alm_disp_fc3",
"(",
"disp_dataset",
")",
":",
"natom",
"=",
"disp_dataset",
"[",
"'natom'",
"]",
"ndisp",
"=",
"len",
"(",
"disp_dataset",
"[",
"'first_atoms'",
"]",
")",
"for",
"disp1",
"in",
"disp_dataset",
"[",
"'first_atoms'",
"]",
":",
"ndi... | Create displacements of atoms for ALM input
Note
----
Dipslacements of all atoms in supercells for all displacement
configurations in phono3py are returned, i.e., most of
displacements are zero. Only the configurations with 'included' ==
True are included in the list of indices that is returned, too.
Parameters
----------
disp_dataset : dict
Displacement dataset that may be obtained by
file_IO.parse_disp_fc3_yaml.
Returns
-------
disp : ndarray
Displacements of atoms in supercells of all displacement
configurations.
shape=(ndisp, natom, 3)
dtype='double'
indices : list of int
The indices of the displacement configurations with 'included' == True. | [
"Create",
"displacements",
"of",
"atoms",
"for",
"ALM",
"input"
] | edfcf36cdc7c5392906a9df57d3ee0f3141404df | https://github.com/atztogo/phono3py/blob/edfcf36cdc7c5392906a9df57d3ee0f3141404df/phono3py/other/alm_wrapper.py#L188-L239 | train | 212,053 |
rocioar/flake8-django | flake8_django/checkers/urls.py | URLChecker.capture_dash_in_url_name | def capture_dash_in_url_name(self, node):
"""
Capture dash in URL name
"""
for keyword in node.keywords:
if keyword.arg == 'name' and '-' in keyword.value.s:
return DJ04(
lineno=node.lineno,
col=node.col_offset,
) | python | def capture_dash_in_url_name(self, node):
"""
Capture dash in URL name
"""
for keyword in node.keywords:
if keyword.arg == 'name' and '-' in keyword.value.s:
return DJ04(
lineno=node.lineno,
col=node.col_offset,
) | [
"def",
"capture_dash_in_url_name",
"(",
"self",
",",
"node",
")",
":",
"for",
"keyword",
"in",
"node",
".",
"keywords",
":",
"if",
"keyword",
".",
"arg",
"==",
"'name'",
"and",
"'-'",
"in",
"keyword",
".",
"value",
".",
"s",
":",
"return",
"DJ04",
"(",... | Capture dash in URL name | [
"Capture",
"dash",
"in",
"URL",
"name"
] | 917f196e2518412bda6e841c1ed3de312004fc67 | https://github.com/rocioar/flake8-django/blob/917f196e2518412bda6e841c1ed3de312004fc67/flake8_django/checkers/urls.py#L35-L44 | train | 212,054 |
rocioar/flake8-django | flake8_django/checkers/urls.py | URLChecker.capture_url_missing_namespace | def capture_url_missing_namespace(self, node):
"""
Capture missing namespace in url include.
"""
for arg in node.args:
if not(isinstance(arg, ast.Call) and isinstance(arg.func, ast.Name)):
continue
if arg.func.id != 'include':
continue
for keyword in arg.keywords:
if keyword.arg == 'namespace':
return
return DJ05(
lineno=node.lineno,
col=node.col_offset,
) | python | def capture_url_missing_namespace(self, node):
"""
Capture missing namespace in url include.
"""
for arg in node.args:
if not(isinstance(arg, ast.Call) and isinstance(arg.func, ast.Name)):
continue
if arg.func.id != 'include':
continue
for keyword in arg.keywords:
if keyword.arg == 'namespace':
return
return DJ05(
lineno=node.lineno,
col=node.col_offset,
) | [
"def",
"capture_url_missing_namespace",
"(",
"self",
",",
"node",
")",
":",
"for",
"arg",
"in",
"node",
".",
"args",
":",
"if",
"not",
"(",
"isinstance",
"(",
"arg",
",",
"ast",
".",
"Call",
")",
"and",
"isinstance",
"(",
"arg",
".",
"func",
",",
"as... | Capture missing namespace in url include. | [
"Capture",
"missing",
"namespace",
"in",
"url",
"include",
"."
] | 917f196e2518412bda6e841c1ed3de312004fc67 | https://github.com/rocioar/flake8-django/blob/917f196e2518412bda6e841c1ed3de312004fc67/flake8_django/checkers/urls.py#L46-L62 | train | 212,055 |
rocioar/flake8-django | flake8_django/checkers/checker.py | Checker.get_call_name | def get_call_name(self, node):
"""
Return call name for the given node.
"""
if isinstance(node.func, ast.Attribute):
return node.func.attr
elif isinstance(node.func, ast.Name):
return node.func.id | python | def get_call_name(self, node):
"""
Return call name for the given node.
"""
if isinstance(node.func, ast.Attribute):
return node.func.attr
elif isinstance(node.func, ast.Name):
return node.func.id | [
"def",
"get_call_name",
"(",
"self",
",",
"node",
")",
":",
"if",
"isinstance",
"(",
"node",
".",
"func",
",",
"ast",
".",
"Attribute",
")",
":",
"return",
"node",
".",
"func",
".",
"attr",
"elif",
"isinstance",
"(",
"node",
".",
"func",
",",
"ast",
... | Return call name for the given node. | [
"Return",
"call",
"name",
"for",
"the",
"given",
"node",
"."
] | 917f196e2518412bda6e841c1ed3de312004fc67 | https://github.com/rocioar/flake8-django/blob/917f196e2518412bda6e841c1ed3de312004fc67/flake8_django/checkers/checker.py#L9-L16 | train | 212,056 |
rocioar/flake8-django | flake8_django/checkers/issue.py | Issue.message | def message(self):
"""
Return issue message.
"""
message = self.description.format(**self.parameters)
return '{code} {message}'.format(code=self.code, message=message) | python | def message(self):
"""
Return issue message.
"""
message = self.description.format(**self.parameters)
return '{code} {message}'.format(code=self.code, message=message) | [
"def",
"message",
"(",
"self",
")",
":",
"message",
"=",
"self",
".",
"description",
".",
"format",
"(",
"*",
"*",
"self",
".",
"parameters",
")",
"return",
"'{code} {message}'",
".",
"format",
"(",
"code",
"=",
"self",
".",
"code",
",",
"message",
"="... | Return issue message. | [
"Return",
"issue",
"message",
"."
] | 917f196e2518412bda6e841c1ed3de312004fc67 | https://github.com/rocioar/flake8-django/blob/917f196e2518412bda6e841c1ed3de312004fc67/flake8_django/checkers/issue.py#L14-L19 | train | 212,057 |
rocioar/flake8-django | flake8_django/checkers/model_form.py | ModelFormChecker.run | def run(self, node):
"""
Captures the use of exclude in ModelForm Meta
"""
if not self.checker_applies(node):
return
issues = []
for body in node.body:
if not isinstance(body, ast.ClassDef):
continue
for element in body.body:
if not isinstance(element, ast.Assign):
continue
for target in element.targets:
if target.id == 'fields' and self.is_string_dunder_all(element):
issues.append(
DJ07(
lineno=node.lineno,
col=node.col_offset,
)
)
elif target.id == 'exclude':
issues.append(
DJ06(
lineno=node.lineno,
col=node.col_offset,
)
)
return issues | python | def run(self, node):
"""
Captures the use of exclude in ModelForm Meta
"""
if not self.checker_applies(node):
return
issues = []
for body in node.body:
if not isinstance(body, ast.ClassDef):
continue
for element in body.body:
if not isinstance(element, ast.Assign):
continue
for target in element.targets:
if target.id == 'fields' and self.is_string_dunder_all(element):
issues.append(
DJ07(
lineno=node.lineno,
col=node.col_offset,
)
)
elif target.id == 'exclude':
issues.append(
DJ06(
lineno=node.lineno,
col=node.col_offset,
)
)
return issues | [
"def",
"run",
"(",
"self",
",",
"node",
")",
":",
"if",
"not",
"self",
".",
"checker_applies",
"(",
"node",
")",
":",
"return",
"issues",
"=",
"[",
"]",
"for",
"body",
"in",
"node",
".",
"body",
":",
"if",
"not",
"isinstance",
"(",
"body",
",",
"... | Captures the use of exclude in ModelForm Meta | [
"Captures",
"the",
"use",
"of",
"exclude",
"in",
"ModelForm",
"Meta"
] | 917f196e2518412bda6e841c1ed3de312004fc67 | https://github.com/rocioar/flake8-django/blob/917f196e2518412bda6e841c1ed3de312004fc67/flake8_django/checkers/model_form.py#L39-L68 | train | 212,058 |
frictionlessdata/tabulator-py | tabulator/helpers.py | detect_scheme_and_format | def detect_scheme_and_format(source):
"""Detect scheme and format based on source and return as a tuple.
Scheme is a minimum 2 letters before `://` (will be lower cased).
For example `http` from `http://example.com/table.csv`
"""
# Scheme: stream
if hasattr(source, 'read'):
return ('stream', None)
# Format: inline
if not isinstance(source, six.string_types):
return (None, 'inline')
# Format: gsheet
if 'docs.google.com/spreadsheets' in source:
if 'export' not in source and 'pub' not in source:
return (None, 'gsheet')
elif 'csv' in source:
return ('https', 'csv')
# Format: sql
for sql_scheme in config.SQL_SCHEMES:
if source.startswith('%s://' % sql_scheme):
return (None, 'sql')
# General
parsed = urlparse(source)
scheme = parsed.scheme.lower()
if len(scheme) < 2:
scheme = config.DEFAULT_SCHEME
format = os.path.splitext(parsed.path or parsed.netloc)[1][1:].lower() or None
if format is None:
# Test if query string contains a "format=" parameter.
query_string = parse_qs(parsed.query)
query_string_format = query_string.get("format")
if query_string_format is not None and len(query_string_format) == 1:
format = query_string_format[0]
# Format: datapackage
if parsed.path.endswith('datapackage.json'):
return (None, 'datapackage')
return (scheme, format) | python | def detect_scheme_and_format(source):
"""Detect scheme and format based on source and return as a tuple.
Scheme is a minimum 2 letters before `://` (will be lower cased).
For example `http` from `http://example.com/table.csv`
"""
# Scheme: stream
if hasattr(source, 'read'):
return ('stream', None)
# Format: inline
if not isinstance(source, six.string_types):
return (None, 'inline')
# Format: gsheet
if 'docs.google.com/spreadsheets' in source:
if 'export' not in source and 'pub' not in source:
return (None, 'gsheet')
elif 'csv' in source:
return ('https', 'csv')
# Format: sql
for sql_scheme in config.SQL_SCHEMES:
if source.startswith('%s://' % sql_scheme):
return (None, 'sql')
# General
parsed = urlparse(source)
scheme = parsed.scheme.lower()
if len(scheme) < 2:
scheme = config.DEFAULT_SCHEME
format = os.path.splitext(parsed.path or parsed.netloc)[1][1:].lower() or None
if format is None:
# Test if query string contains a "format=" parameter.
query_string = parse_qs(parsed.query)
query_string_format = query_string.get("format")
if query_string_format is not None and len(query_string_format) == 1:
format = query_string_format[0]
# Format: datapackage
if parsed.path.endswith('datapackage.json'):
return (None, 'datapackage')
return (scheme, format) | [
"def",
"detect_scheme_and_format",
"(",
"source",
")",
":",
"# Scheme: stream",
"if",
"hasattr",
"(",
"source",
",",
"'read'",
")",
":",
"return",
"(",
"'stream'",
",",
"None",
")",
"# Format: inline",
"if",
"not",
"isinstance",
"(",
"source",
",",
"six",
".... | Detect scheme and format based on source and return as a tuple.
Scheme is a minimum 2 letters before `://` (will be lower cased).
For example `http` from `http://example.com/table.csv` | [
"Detect",
"scheme",
"and",
"format",
"based",
"on",
"source",
"and",
"return",
"as",
"a",
"tuple",
"."
] | 06c25845a7139d919326388cc6335f33f909db8c | https://github.com/frictionlessdata/tabulator-py/blob/06c25845a7139d919326388cc6335f33f909db8c/tabulator/helpers.py#L20-L65 | train | 212,059 |
frictionlessdata/tabulator-py | tabulator/helpers.py | detect_encoding | def detect_encoding(sample, encoding=None):
"""Detect encoding of a byte string sample.
"""
# To reduce tabulator import time
from cchardet import detect
if encoding is not None:
return normalize_encoding(sample, encoding)
result = detect(sample)
confidence = result['confidence'] or 0
encoding = result['encoding'] or 'ascii'
encoding = normalize_encoding(sample, encoding)
if confidence < config.ENCODING_CONFIDENCE:
encoding = config.DEFAULT_ENCODING
if encoding == 'ascii':
encoding = config.DEFAULT_ENCODING
return encoding | python | def detect_encoding(sample, encoding=None):
"""Detect encoding of a byte string sample.
"""
# To reduce tabulator import time
from cchardet import detect
if encoding is not None:
return normalize_encoding(sample, encoding)
result = detect(sample)
confidence = result['confidence'] or 0
encoding = result['encoding'] or 'ascii'
encoding = normalize_encoding(sample, encoding)
if confidence < config.ENCODING_CONFIDENCE:
encoding = config.DEFAULT_ENCODING
if encoding == 'ascii':
encoding = config.DEFAULT_ENCODING
return encoding | [
"def",
"detect_encoding",
"(",
"sample",
",",
"encoding",
"=",
"None",
")",
":",
"# To reduce tabulator import time",
"from",
"cchardet",
"import",
"detect",
"if",
"encoding",
"is",
"not",
"None",
":",
"return",
"normalize_encoding",
"(",
"sample",
",",
"encoding"... | Detect encoding of a byte string sample. | [
"Detect",
"encoding",
"of",
"a",
"byte",
"string",
"sample",
"."
] | 06c25845a7139d919326388cc6335f33f909db8c | https://github.com/frictionlessdata/tabulator-py/blob/06c25845a7139d919326388cc6335f33f909db8c/tabulator/helpers.py#L68-L83 | train | 212,060 |
frictionlessdata/tabulator-py | tabulator/helpers.py | normalize_encoding | def normalize_encoding(sample, encoding):
"""Normalize encoding including 'utf-8-sig', 'utf-16-be', utf-16-le tweaks.
"""
encoding = codecs.lookup(encoding).name
# Work around 'Incorrect detection of utf-8-sig encoding'
# <https://github.com/PyYoshi/cChardet/issues/28>
if encoding == 'utf-8':
if sample.startswith(codecs.BOM_UTF8):
encoding = 'utf-8-sig'
# Use the BOM stripping name (without byte-order) for UTF-16 encodings
elif encoding == 'utf-16-be':
if sample.startswith(codecs.BOM_UTF16_BE):
encoding = 'utf-16'
elif encoding == 'utf-16-le':
if sample.startswith(codecs.BOM_UTF16_LE):
encoding = 'utf-16'
return encoding | python | def normalize_encoding(sample, encoding):
"""Normalize encoding including 'utf-8-sig', 'utf-16-be', utf-16-le tweaks.
"""
encoding = codecs.lookup(encoding).name
# Work around 'Incorrect detection of utf-8-sig encoding'
# <https://github.com/PyYoshi/cChardet/issues/28>
if encoding == 'utf-8':
if sample.startswith(codecs.BOM_UTF8):
encoding = 'utf-8-sig'
# Use the BOM stripping name (without byte-order) for UTF-16 encodings
elif encoding == 'utf-16-be':
if sample.startswith(codecs.BOM_UTF16_BE):
encoding = 'utf-16'
elif encoding == 'utf-16-le':
if sample.startswith(codecs.BOM_UTF16_LE):
encoding = 'utf-16'
return encoding | [
"def",
"normalize_encoding",
"(",
"sample",
",",
"encoding",
")",
":",
"encoding",
"=",
"codecs",
".",
"lookup",
"(",
"encoding",
")",
".",
"name",
"# Work around 'Incorrect detection of utf-8-sig encoding'",
"# <https://github.com/PyYoshi/cChardet/issues/28>",
"if",
"encod... | Normalize encoding including 'utf-8-sig', 'utf-16-be', utf-16-le tweaks. | [
"Normalize",
"encoding",
"including",
"utf",
"-",
"8",
"-",
"sig",
"utf",
"-",
"16",
"-",
"be",
"utf",
"-",
"16",
"-",
"le",
"tweaks",
"."
] | 06c25845a7139d919326388cc6335f33f909db8c | https://github.com/frictionlessdata/tabulator-py/blob/06c25845a7139d919326388cc6335f33f909db8c/tabulator/helpers.py#L86-L102 | train | 212,061 |
frictionlessdata/tabulator-py | tabulator/helpers.py | detect_html | def detect_html(text):
"""Detect if text is HTML.
"""
pattern = re.compile('\\s*<(!doctype|html)', re.IGNORECASE)
return bool(pattern.match(text)) | python | def detect_html(text):
"""Detect if text is HTML.
"""
pattern = re.compile('\\s*<(!doctype|html)', re.IGNORECASE)
return bool(pattern.match(text)) | [
"def",
"detect_html",
"(",
"text",
")",
":",
"pattern",
"=",
"re",
".",
"compile",
"(",
"'\\\\s*<(!doctype|html)'",
",",
"re",
".",
"IGNORECASE",
")",
"return",
"bool",
"(",
"pattern",
".",
"match",
"(",
"text",
")",
")"
] | Detect if text is HTML. | [
"Detect",
"if",
"text",
"is",
"HTML",
"."
] | 06c25845a7139d919326388cc6335f33f909db8c | https://github.com/frictionlessdata/tabulator-py/blob/06c25845a7139d919326388cc6335f33f909db8c/tabulator/helpers.py#L105-L109 | train | 212,062 |
frictionlessdata/tabulator-py | tabulator/helpers.py | reset_stream | def reset_stream(stream):
"""Reset stream pointer to the first element.
If stream is not seekable raise Exception.
"""
try:
position = stream.tell()
except Exception:
position = True
if position != 0:
try:
stream.seek(0)
except Exception:
message = 'It\'s not possible to reset this stream'
raise exceptions.TabulatorException(message) | python | def reset_stream(stream):
"""Reset stream pointer to the first element.
If stream is not seekable raise Exception.
"""
try:
position = stream.tell()
except Exception:
position = True
if position != 0:
try:
stream.seek(0)
except Exception:
message = 'It\'s not possible to reset this stream'
raise exceptions.TabulatorException(message) | [
"def",
"reset_stream",
"(",
"stream",
")",
":",
"try",
":",
"position",
"=",
"stream",
".",
"tell",
"(",
")",
"except",
"Exception",
":",
"position",
"=",
"True",
"if",
"position",
"!=",
"0",
":",
"try",
":",
"stream",
".",
"seek",
"(",
"0",
")",
"... | Reset stream pointer to the first element.
If stream is not seekable raise Exception. | [
"Reset",
"stream",
"pointer",
"to",
"the",
"first",
"element",
"."
] | 06c25845a7139d919326388cc6335f33f909db8c | https://github.com/frictionlessdata/tabulator-py/blob/06c25845a7139d919326388cc6335f33f909db8c/tabulator/helpers.py#L112-L127 | train | 212,063 |
frictionlessdata/tabulator-py | tabulator/helpers.py | requote_uri | def requote_uri(uri):
"""Requote uri if it contains non-ascii chars, spaces etc.
"""
# To reduce tabulator import time
import requests.utils
if six.PY2:
def url_encode_non_ascii(bytes):
pattern = '[\x80-\xFF]'
replace = lambda c: ('%%%02x' % ord(c.group(0))).upper()
return re.sub(pattern, replace, bytes)
parts = urlparse(uri)
uri = urlunparse(
part.encode('idna') if index == 1
else url_encode_non_ascii(part.encode('utf-8'))
for index, part in enumerate(parts))
return requests.utils.requote_uri(uri) | python | def requote_uri(uri):
"""Requote uri if it contains non-ascii chars, spaces etc.
"""
# To reduce tabulator import time
import requests.utils
if six.PY2:
def url_encode_non_ascii(bytes):
pattern = '[\x80-\xFF]'
replace = lambda c: ('%%%02x' % ord(c.group(0))).upper()
return re.sub(pattern, replace, bytes)
parts = urlparse(uri)
uri = urlunparse(
part.encode('idna') if index == 1
else url_encode_non_ascii(part.encode('utf-8'))
for index, part in enumerate(parts))
return requests.utils.requote_uri(uri) | [
"def",
"requote_uri",
"(",
"uri",
")",
":",
"# To reduce tabulator import time",
"import",
"requests",
".",
"utils",
"if",
"six",
".",
"PY2",
":",
"def",
"url_encode_non_ascii",
"(",
"bytes",
")",
":",
"pattern",
"=",
"'[\\x80-\\xFF]'",
"replace",
"=",
"lambda",... | Requote uri if it contains non-ascii chars, spaces etc. | [
"Requote",
"uri",
"if",
"it",
"contains",
"non",
"-",
"ascii",
"chars",
"spaces",
"etc",
"."
] | 06c25845a7139d919326388cc6335f33f909db8c | https://github.com/frictionlessdata/tabulator-py/blob/06c25845a7139d919326388cc6335f33f909db8c/tabulator/helpers.py#L138-L153 | train | 212,064 |
frictionlessdata/tabulator-py | tabulator/helpers.py | import_attribute | def import_attribute(path):
"""Import attribute by path like `package.module.attribute`
"""
module_name, attribute_name = path.rsplit('.', 1)
module = import_module(module_name)
attribute = getattr(module, attribute_name)
return attribute | python | def import_attribute(path):
"""Import attribute by path like `package.module.attribute`
"""
module_name, attribute_name = path.rsplit('.', 1)
module = import_module(module_name)
attribute = getattr(module, attribute_name)
return attribute | [
"def",
"import_attribute",
"(",
"path",
")",
":",
"module_name",
",",
"attribute_name",
"=",
"path",
".",
"rsplit",
"(",
"'.'",
",",
"1",
")",
"module",
"=",
"import_module",
"(",
"module_name",
")",
"attribute",
"=",
"getattr",
"(",
"module",
",",
"attrib... | Import attribute by path like `package.module.attribute` | [
"Import",
"attribute",
"by",
"path",
"like",
"package",
".",
"module",
".",
"attribute"
] | 06c25845a7139d919326388cc6335f33f909db8c | https://github.com/frictionlessdata/tabulator-py/blob/06c25845a7139d919326388cc6335f33f909db8c/tabulator/helpers.py#L156-L162 | train | 212,065 |
frictionlessdata/tabulator-py | tabulator/helpers.py | extract_options | def extract_options(options, names):
"""Return options for names and remove it from given options in-place.
"""
result = {}
for name, value in copy(options).items():
if name in names:
result[name] = value
del options[name]
return result | python | def extract_options(options, names):
"""Return options for names and remove it from given options in-place.
"""
result = {}
for name, value in copy(options).items():
if name in names:
result[name] = value
del options[name]
return result | [
"def",
"extract_options",
"(",
"options",
",",
"names",
")",
":",
"result",
"=",
"{",
"}",
"for",
"name",
",",
"value",
"in",
"copy",
"(",
"options",
")",
".",
"items",
"(",
")",
":",
"if",
"name",
"in",
"names",
":",
"result",
"[",
"name",
"]",
... | Return options for names and remove it from given options in-place. | [
"Return",
"options",
"for",
"names",
"and",
"remove",
"it",
"from",
"given",
"options",
"in",
"-",
"place",
"."
] | 06c25845a7139d919326388cc6335f33f909db8c | https://github.com/frictionlessdata/tabulator-py/blob/06c25845a7139d919326388cc6335f33f909db8c/tabulator/helpers.py#L165-L173 | train | 212,066 |
frictionlessdata/tabulator-py | tabulator/helpers.py | stringify_value | def stringify_value(value):
"""Convert any value to string.
"""
if value is None:
return u''
isoformat = getattr(value, 'isoformat', None)
if isoformat is not None:
value = isoformat()
return type(u'')(value) | python | def stringify_value(value):
"""Convert any value to string.
"""
if value is None:
return u''
isoformat = getattr(value, 'isoformat', None)
if isoformat is not None:
value = isoformat()
return type(u'')(value) | [
"def",
"stringify_value",
"(",
"value",
")",
":",
"if",
"value",
"is",
"None",
":",
"return",
"u''",
"isoformat",
"=",
"getattr",
"(",
"value",
",",
"'isoformat'",
",",
"None",
")",
"if",
"isoformat",
"is",
"not",
"None",
":",
"value",
"=",
"isoformat",
... | Convert any value to string. | [
"Convert",
"any",
"value",
"to",
"string",
"."
] | 06c25845a7139d919326388cc6335f33f909db8c | https://github.com/frictionlessdata/tabulator-py/blob/06c25845a7139d919326388cc6335f33f909db8c/tabulator/helpers.py#L176-L184 | train | 212,067 |
frictionlessdata/tabulator-py | tabulator/stream.py | Stream.reset | def reset(self):
'''Resets the stream pointer to the beginning of the file.'''
if self.__row_number > self.__sample_size:
self.__parser.reset()
self.__extract_sample()
self.__extract_headers()
self.__row_number = 0 | python | def reset(self):
'''Resets the stream pointer to the beginning of the file.'''
if self.__row_number > self.__sample_size:
self.__parser.reset()
self.__extract_sample()
self.__extract_headers()
self.__row_number = 0 | [
"def",
"reset",
"(",
"self",
")",
":",
"if",
"self",
".",
"__row_number",
">",
"self",
".",
"__sample_size",
":",
"self",
".",
"__parser",
".",
"reset",
"(",
")",
"self",
".",
"__extract_sample",
"(",
")",
"self",
".",
"__extract_headers",
"(",
")",
"s... | Resets the stream pointer to the beginning of the file. | [
"Resets",
"the",
"stream",
"pointer",
"to",
"the",
"beginning",
"of",
"the",
"file",
"."
] | 06c25845a7139d919326388cc6335f33f909db8c | https://github.com/frictionlessdata/tabulator-py/blob/06c25845a7139d919326388cc6335f33f909db8c/tabulator/stream.py#L282-L288 | train | 212,068 |
frictionlessdata/tabulator-py | tabulator/stream.py | Stream.sample | def sample(self):
'''Returns the stream's rows used as sample.
These sample rows are used internally to infer characteristics of the
source file (e.g. encoding, headers, ...).
'''
sample = []
iterator = iter(self.__sample_extended_rows)
iterator = self.__apply_processors(iterator)
for row_number, headers, row in iterator:
sample.append(row)
return sample | python | def sample(self):
'''Returns the stream's rows used as sample.
These sample rows are used internally to infer characteristics of the
source file (e.g. encoding, headers, ...).
'''
sample = []
iterator = iter(self.__sample_extended_rows)
iterator = self.__apply_processors(iterator)
for row_number, headers, row in iterator:
sample.append(row)
return sample | [
"def",
"sample",
"(",
"self",
")",
":",
"sample",
"=",
"[",
"]",
"iterator",
"=",
"iter",
"(",
"self",
".",
"__sample_extended_rows",
")",
"iterator",
"=",
"self",
".",
"__apply_processors",
"(",
"iterator",
")",
"for",
"row_number",
",",
"headers",
",",
... | Returns the stream's rows used as sample.
These sample rows are used internally to infer characteristics of the
source file (e.g. encoding, headers, ...). | [
"Returns",
"the",
"stream",
"s",
"rows",
"used",
"as",
"sample",
"."
] | 06c25845a7139d919326388cc6335f33f909db8c | https://github.com/frictionlessdata/tabulator-py/blob/06c25845a7139d919326388cc6335f33f909db8c/tabulator/stream.py#L307-L318 | train | 212,069 |
frictionlessdata/tabulator-py | tabulator/stream.py | Stream.iter | def iter(self, keyed=False, extended=False):
'''Iterate over the rows.
Each row is returned in a format that depends on the arguments `keyed`
and `extended`. By default, each row is returned as list of their
values.
Args:
keyed (bool, optional): When True, each returned row will be a
`dict` mapping the header name to its value in the current row.
For example, `[{'name': 'J Smith', 'value': '10'}]`. Ignored if
``extended`` is True. Defaults to False.
extended (bool, optional): When True, returns each row as a tuple
with row number (starts at 1), list of headers, and list of row
values. For example, `(1, ['name', 'value'], ['J Smith', '10'])`.
Defaults to False.
Returns:
Iterator[Union[List[Any], Dict[str, Any], Tuple[int, List[str], List[Any]]]]:
The row itself. The format depends on the values of `keyed` and
`extended` arguments.
Raises:
exceptions.TabulatorException: If the stream is closed.
'''
# Error if closed
if self.closed:
message = 'Stream is closed. Please call "stream.open()" first.'
raise exceptions.TabulatorException(message)
# Create iterator
iterator = chain(
self.__sample_extended_rows,
self.__parser.extended_rows)
iterator = self.__apply_processors(iterator)
# Yield rows from iterator
for row_number, headers, row in iterator:
if row_number > self.__row_number:
self.__row_number = row_number
if extended:
yield (row_number, headers, row)
elif keyed:
yield dict(zip(headers, row))
else:
yield row | python | def iter(self, keyed=False, extended=False):
'''Iterate over the rows.
Each row is returned in a format that depends on the arguments `keyed`
and `extended`. By default, each row is returned as list of their
values.
Args:
keyed (bool, optional): When True, each returned row will be a
`dict` mapping the header name to its value in the current row.
For example, `[{'name': 'J Smith', 'value': '10'}]`. Ignored if
``extended`` is True. Defaults to False.
extended (bool, optional): When True, returns each row as a tuple
with row number (starts at 1), list of headers, and list of row
values. For example, `(1, ['name', 'value'], ['J Smith', '10'])`.
Defaults to False.
Returns:
Iterator[Union[List[Any], Dict[str, Any], Tuple[int, List[str], List[Any]]]]:
The row itself. The format depends on the values of `keyed` and
`extended` arguments.
Raises:
exceptions.TabulatorException: If the stream is closed.
'''
# Error if closed
if self.closed:
message = 'Stream is closed. Please call "stream.open()" first.'
raise exceptions.TabulatorException(message)
# Create iterator
iterator = chain(
self.__sample_extended_rows,
self.__parser.extended_rows)
iterator = self.__apply_processors(iterator)
# Yield rows from iterator
for row_number, headers, row in iterator:
if row_number > self.__row_number:
self.__row_number = row_number
if extended:
yield (row_number, headers, row)
elif keyed:
yield dict(zip(headers, row))
else:
yield row | [
"def",
"iter",
"(",
"self",
",",
"keyed",
"=",
"False",
",",
"extended",
"=",
"False",
")",
":",
"# Error if closed",
"if",
"self",
".",
"closed",
":",
"message",
"=",
"'Stream is closed. Please call \"stream.open()\" first.'",
"raise",
"exceptions",
".",
"Tabulat... | Iterate over the rows.
Each row is returned in a format that depends on the arguments `keyed`
and `extended`. By default, each row is returned as list of their
values.
Args:
keyed (bool, optional): When True, each returned row will be a
`dict` mapping the header name to its value in the current row.
For example, `[{'name': 'J Smith', 'value': '10'}]`. Ignored if
``extended`` is True. Defaults to False.
extended (bool, optional): When True, returns each row as a tuple
with row number (starts at 1), list of headers, and list of row
values. For example, `(1, ['name', 'value'], ['J Smith', '10'])`.
Defaults to False.
Returns:
Iterator[Union[List[Any], Dict[str, Any], Tuple[int, List[str], List[Any]]]]:
The row itself. The format depends on the values of `keyed` and
`extended` arguments.
Raises:
exceptions.TabulatorException: If the stream is closed. | [
"Iterate",
"over",
"the",
"rows",
"."
] | 06c25845a7139d919326388cc6335f33f909db8c | https://github.com/frictionlessdata/tabulator-py/blob/06c25845a7139d919326388cc6335f33f909db8c/tabulator/stream.py#L320-L366 | train | 212,070 |
frictionlessdata/tabulator-py | tabulator/stream.py | Stream.save | def save(self, target, format=None, encoding=None, **options):
'''Save stream to the local filesystem.
Args:
target (str): Path where to save the stream.
format (str, optional): The format the stream will be saved as. If
None, detects from the ``target`` path. Defaults to None.
encoding (str, optional): Saved file encoding. Defaults to
``config.DEFAULT_ENCODING``.
**options: Extra options passed to the writer.
'''
# Get encoding/format
if encoding is None:
encoding = config.DEFAULT_ENCODING
if format is None:
_, format = helpers.detect_scheme_and_format(target)
# Prepare writer class
writer_class = self.__custom_writers.get(format)
if writer_class is None:
if format not in config.WRITERS:
message = 'Format "%s" is not supported' % format
raise exceptions.FormatError(message)
writer_class = helpers.import_attribute(config.WRITERS[format])
# Prepare writer options
writer_options = helpers.extract_options(options, writer_class.options)
if options:
message = 'Not supported options "%s" for format "%s"'
message = message % (', '.join(options), format)
raise exceptions.TabulatorException(message)
# Write data to target
writer = writer_class(**writer_options)
writer.write(self.iter(), target, headers=self.headers, encoding=encoding) | python | def save(self, target, format=None, encoding=None, **options):
'''Save stream to the local filesystem.
Args:
target (str): Path where to save the stream.
format (str, optional): The format the stream will be saved as. If
None, detects from the ``target`` path. Defaults to None.
encoding (str, optional): Saved file encoding. Defaults to
``config.DEFAULT_ENCODING``.
**options: Extra options passed to the writer.
'''
# Get encoding/format
if encoding is None:
encoding = config.DEFAULT_ENCODING
if format is None:
_, format = helpers.detect_scheme_and_format(target)
# Prepare writer class
writer_class = self.__custom_writers.get(format)
if writer_class is None:
if format not in config.WRITERS:
message = 'Format "%s" is not supported' % format
raise exceptions.FormatError(message)
writer_class = helpers.import_attribute(config.WRITERS[format])
# Prepare writer options
writer_options = helpers.extract_options(options, writer_class.options)
if options:
message = 'Not supported options "%s" for format "%s"'
message = message % (', '.join(options), format)
raise exceptions.TabulatorException(message)
# Write data to target
writer = writer_class(**writer_options)
writer.write(self.iter(), target, headers=self.headers, encoding=encoding) | [
"def",
"save",
"(",
"self",
",",
"target",
",",
"format",
"=",
"None",
",",
"encoding",
"=",
"None",
",",
"*",
"*",
"options",
")",
":",
"# Get encoding/format",
"if",
"encoding",
"is",
"None",
":",
"encoding",
"=",
"config",
".",
"DEFAULT_ENCODING",
"if... | Save stream to the local filesystem.
Args:
target (str): Path where to save the stream.
format (str, optional): The format the stream will be saved as. If
None, detects from the ``target`` path. Defaults to None.
encoding (str, optional): Saved file encoding. Defaults to
``config.DEFAULT_ENCODING``.
**options: Extra options passed to the writer. | [
"Save",
"stream",
"to",
"the",
"local",
"filesystem",
"."
] | 06c25845a7139d919326388cc6335f33f909db8c | https://github.com/frictionlessdata/tabulator-py/blob/06c25845a7139d919326388cc6335f33f909db8c/tabulator/stream.py#L390-L425 | train | 212,071 |
frictionlessdata/tabulator-py | tabulator/validate.py | validate | def validate(source, scheme=None, format=None):
'''Check if tabulator is able to load the source.
Args:
source (Union[str, IO]): The source path or IO object.
scheme (str, optional): The source scheme. Auto-detect by default.
format (str, optional): The source file format. Auto-detect by default.
Returns:
bool: Whether tabulator is able to load the source file.
Raises:
`tabulator.exceptions.SchemeError`: The file scheme is not supported.
`tabulator.exceptions.FormatError`: The file format is not supported.
'''
# Get scheme and format
detected_scheme, detected_format = helpers.detect_scheme_and_format(source)
scheme = scheme or detected_scheme
format = format or detected_format
# Validate scheme and format
if scheme is not None:
if scheme not in config.LOADERS:
raise exceptions.SchemeError('Scheme "%s" is not supported' % scheme)
if format not in config.PARSERS:
raise exceptions.FormatError('Format "%s" is not supported' % format)
return True | python | def validate(source, scheme=None, format=None):
'''Check if tabulator is able to load the source.
Args:
source (Union[str, IO]): The source path or IO object.
scheme (str, optional): The source scheme. Auto-detect by default.
format (str, optional): The source file format. Auto-detect by default.
Returns:
bool: Whether tabulator is able to load the source file.
Raises:
`tabulator.exceptions.SchemeError`: The file scheme is not supported.
`tabulator.exceptions.FormatError`: The file format is not supported.
'''
# Get scheme and format
detected_scheme, detected_format = helpers.detect_scheme_and_format(source)
scheme = scheme or detected_scheme
format = format or detected_format
# Validate scheme and format
if scheme is not None:
if scheme not in config.LOADERS:
raise exceptions.SchemeError('Scheme "%s" is not supported' % scheme)
if format not in config.PARSERS:
raise exceptions.FormatError('Format "%s" is not supported' % format)
return True | [
"def",
"validate",
"(",
"source",
",",
"scheme",
"=",
"None",
",",
"format",
"=",
"None",
")",
":",
"# Get scheme and format",
"detected_scheme",
",",
"detected_format",
"=",
"helpers",
".",
"detect_scheme_and_format",
"(",
"source",
")",
"scheme",
"=",
"scheme"... | Check if tabulator is able to load the source.
Args:
source (Union[str, IO]): The source path or IO object.
scheme (str, optional): The source scheme. Auto-detect by default.
format (str, optional): The source file format. Auto-detect by default.
Returns:
bool: Whether tabulator is able to load the source file.
Raises:
`tabulator.exceptions.SchemeError`: The file scheme is not supported.
`tabulator.exceptions.FormatError`: The file format is not supported. | [
"Check",
"if",
"tabulator",
"is",
"able",
"to",
"load",
"the",
"source",
"."
] | 06c25845a7139d919326388cc6335f33f909db8c | https://github.com/frictionlessdata/tabulator-py/blob/06c25845a7139d919326388cc6335f33f909db8c/tabulator/validate.py#L14-L42 | train | 212,072 |
stefankoegl/kdtree | kdtree.py | require_axis | def require_axis(f):
""" Check if the object of the function has axis and sel_axis members """
@wraps(f)
def _wrapper(self, *args, **kwargs):
if None in (self.axis, self.sel_axis):
raise ValueError('%(func_name) requires the node %(node)s '
'to have an axis and a sel_axis function' %
dict(func_name=f.__name__, node=repr(self)))
return f(self, *args, **kwargs)
return _wrapper | python | def require_axis(f):
""" Check if the object of the function has axis and sel_axis members """
@wraps(f)
def _wrapper(self, *args, **kwargs):
if None in (self.axis, self.sel_axis):
raise ValueError('%(func_name) requires the node %(node)s '
'to have an axis and a sel_axis function' %
dict(func_name=f.__name__, node=repr(self)))
return f(self, *args, **kwargs)
return _wrapper | [
"def",
"require_axis",
"(",
"f",
")",
":",
"@",
"wraps",
"(",
"f",
")",
"def",
"_wrapper",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"None",
"in",
"(",
"self",
".",
"axis",
",",
"self",
".",
"sel_axis",
")",
":",
... | Check if the object of the function has axis and sel_axis members | [
"Check",
"if",
"the",
"object",
"of",
"the",
"function",
"has",
"axis",
"and",
"sel_axis",
"members"
] | 587edc7056d7735177ad56a84ad5abccdea91693 | https://github.com/stefankoegl/kdtree/blob/587edc7056d7735177ad56a84ad5abccdea91693/kdtree.py#L187-L199 | train | 212,073 |
stefankoegl/kdtree | kdtree.py | create | def create(point_list=None, dimensions=None, axis=0, sel_axis=None):
""" Creates a kd-tree from a list of points
All points in the list must be of the same dimensionality.
If no point_list is given, an empty tree is created. The number of
dimensions has to be given instead.
If both a point_list and dimensions are given, the numbers must agree.
Axis is the axis on which the root-node should split.
sel_axis(axis) is used when creating subnodes of a node. It receives the
axis of the parent node and returns the axis of the child node. """
if not point_list and not dimensions:
raise ValueError('either point_list or dimensions must be provided')
elif point_list:
dimensions = check_dimensionality(point_list, dimensions)
# by default cycle through the axis
sel_axis = sel_axis or (lambda prev_axis: (prev_axis+1) % dimensions)
if not point_list:
return KDNode(sel_axis=sel_axis, axis=axis, dimensions=dimensions)
# Sort point list and choose median as pivot element
point_list = list(point_list)
point_list.sort(key=lambda point: point[axis])
median = len(point_list) // 2
loc = point_list[median]
left = create(point_list[:median], dimensions, sel_axis(axis))
right = create(point_list[median + 1:], dimensions, sel_axis(axis))
return KDNode(loc, left, right, axis=axis, sel_axis=sel_axis, dimensions=dimensions) | python | def create(point_list=None, dimensions=None, axis=0, sel_axis=None):
""" Creates a kd-tree from a list of points
All points in the list must be of the same dimensionality.
If no point_list is given, an empty tree is created. The number of
dimensions has to be given instead.
If both a point_list and dimensions are given, the numbers must agree.
Axis is the axis on which the root-node should split.
sel_axis(axis) is used when creating subnodes of a node. It receives the
axis of the parent node and returns the axis of the child node. """
if not point_list and not dimensions:
raise ValueError('either point_list or dimensions must be provided')
elif point_list:
dimensions = check_dimensionality(point_list, dimensions)
# by default cycle through the axis
sel_axis = sel_axis or (lambda prev_axis: (prev_axis+1) % dimensions)
if not point_list:
return KDNode(sel_axis=sel_axis, axis=axis, dimensions=dimensions)
# Sort point list and choose median as pivot element
point_list = list(point_list)
point_list.sort(key=lambda point: point[axis])
median = len(point_list) // 2
loc = point_list[median]
left = create(point_list[:median], dimensions, sel_axis(axis))
right = create(point_list[median + 1:], dimensions, sel_axis(axis))
return KDNode(loc, left, right, axis=axis, sel_axis=sel_axis, dimensions=dimensions) | [
"def",
"create",
"(",
"point_list",
"=",
"None",
",",
"dimensions",
"=",
"None",
",",
"axis",
"=",
"0",
",",
"sel_axis",
"=",
"None",
")",
":",
"if",
"not",
"point_list",
"and",
"not",
"dimensions",
":",
"raise",
"ValueError",
"(",
"'either point_list or d... | Creates a kd-tree from a list of points
All points in the list must be of the same dimensionality.
If no point_list is given, an empty tree is created. The number of
dimensions has to be given instead.
If both a point_list and dimensions are given, the numbers must agree.
Axis is the axis on which the root-node should split.
sel_axis(axis) is used when creating subnodes of a node. It receives the
axis of the parent node and returns the axis of the child node. | [
"Creates",
"a",
"kd",
"-",
"tree",
"from",
"a",
"list",
"of",
"points"
] | 587edc7056d7735177ad56a84ad5abccdea91693 | https://github.com/stefankoegl/kdtree/blob/587edc7056d7735177ad56a84ad5abccdea91693/kdtree.py#L576-L611 | train | 212,074 |
stefankoegl/kdtree | kdtree.py | level_order | def level_order(tree, include_all=False):
""" Returns an iterator over the tree in level-order
If include_all is set to True, empty parts of the tree are filled
with dummy entries and the iterator becomes infinite. """
q = deque()
q.append(tree)
while q:
node = q.popleft()
yield node
if include_all or node.left:
q.append(node.left or node.__class__())
if include_all or node.right:
q.append(node.right or node.__class__()) | python | def level_order(tree, include_all=False):
""" Returns an iterator over the tree in level-order
If include_all is set to True, empty parts of the tree are filled
with dummy entries and the iterator becomes infinite. """
q = deque()
q.append(tree)
while q:
node = q.popleft()
yield node
if include_all or node.left:
q.append(node.left or node.__class__())
if include_all or node.right:
q.append(node.right or node.__class__()) | [
"def",
"level_order",
"(",
"tree",
",",
"include_all",
"=",
"False",
")",
":",
"q",
"=",
"deque",
"(",
")",
"q",
".",
"append",
"(",
"tree",
")",
"while",
"q",
":",
"node",
"=",
"q",
".",
"popleft",
"(",
")",
"yield",
"node",
"if",
"include_all",
... | Returns an iterator over the tree in level-order
If include_all is set to True, empty parts of the tree are filled
with dummy entries and the iterator becomes infinite. | [
"Returns",
"an",
"iterator",
"over",
"the",
"tree",
"in",
"level",
"-",
"order"
] | 587edc7056d7735177ad56a84ad5abccdea91693 | https://github.com/stefankoegl/kdtree/blob/587edc7056d7735177ad56a84ad5abccdea91693/kdtree.py#L624-L640 | train | 212,075 |
stefankoegl/kdtree | kdtree.py | visualize | def visualize(tree, max_level=100, node_width=10, left_padding=5):
""" Prints the tree to stdout """
height = min(max_level, tree.height()-1)
max_width = pow(2, height)
per_level = 1
in_level = 0
level = 0
for node in level_order(tree, include_all=True):
if in_level == 0:
print()
print()
print(' '*left_padding, end=' ')
width = int(max_width*node_width/per_level)
node_str = (str(node.data) if node else '').center(width)
print(node_str, end=' ')
in_level += 1
if in_level == per_level:
in_level = 0
per_level *= 2
level += 1
if level > height:
break
print()
print() | python | def visualize(tree, max_level=100, node_width=10, left_padding=5):
""" Prints the tree to stdout """
height = min(max_level, tree.height()-1)
max_width = pow(2, height)
per_level = 1
in_level = 0
level = 0
for node in level_order(tree, include_all=True):
if in_level == 0:
print()
print()
print(' '*left_padding, end=' ')
width = int(max_width*node_width/per_level)
node_str = (str(node.data) if node else '').center(width)
print(node_str, end=' ')
in_level += 1
if in_level == per_level:
in_level = 0
per_level *= 2
level += 1
if level > height:
break
print()
print() | [
"def",
"visualize",
"(",
"tree",
",",
"max_level",
"=",
"100",
",",
"node_width",
"=",
"10",
",",
"left_padding",
"=",
"5",
")",
":",
"height",
"=",
"min",
"(",
"max_level",
",",
"tree",
".",
"height",
"(",
")",
"-",
"1",
")",
"max_width",
"=",
"po... | Prints the tree to stdout | [
"Prints",
"the",
"tree",
"to",
"stdout"
] | 587edc7056d7735177ad56a84ad5abccdea91693 | https://github.com/stefankoegl/kdtree/blob/587edc7056d7735177ad56a84ad5abccdea91693/kdtree.py#L644-L677 | train | 212,076 |
stefankoegl/kdtree | kdtree.py | Node.is_leaf | def is_leaf(self):
""" Returns True if a Node has no subnodes
>>> Node().is_leaf
True
>>> Node( 1, left=Node(2) ).is_leaf
False
"""
return (not self.data) or \
(all(not bool(c) for c, p in self.children)) | python | def is_leaf(self):
""" Returns True if a Node has no subnodes
>>> Node().is_leaf
True
>>> Node( 1, left=Node(2) ).is_leaf
False
"""
return (not self.data) or \
(all(not bool(c) for c, p in self.children)) | [
"def",
"is_leaf",
"(",
"self",
")",
":",
"return",
"(",
"not",
"self",
".",
"data",
")",
"or",
"(",
"all",
"(",
"not",
"bool",
"(",
"c",
")",
"for",
"c",
",",
"p",
"in",
"self",
".",
"children",
")",
")"
] | Returns True if a Node has no subnodes
>>> Node().is_leaf
True
>>> Node( 1, left=Node(2) ).is_leaf
False | [
"Returns",
"True",
"if",
"a",
"Node",
"has",
"no",
"subnodes"
] | 587edc7056d7735177ad56a84ad5abccdea91693 | https://github.com/stefankoegl/kdtree/blob/587edc7056d7735177ad56a84ad5abccdea91693/kdtree.py#L38-L48 | train | 212,077 |
stefankoegl/kdtree | kdtree.py | Node.children | def children(self):
"""
Returns an iterator for the non-empty children of the Node
The children are returned as (Node, pos) tuples where pos is 0 for the
left subnode and 1 for the right.
>>> len(list(create(dimensions=2).children))
0
>>> len(list(create([ (1, 2) ]).children))
0
>>> len(list(create([ (2, 2), (2, 1), (2, 3) ]).children))
2
"""
if self.left and self.left.data is not None:
yield self.left, 0
if self.right and self.right.data is not None:
yield self.right, 1 | python | def children(self):
"""
Returns an iterator for the non-empty children of the Node
The children are returned as (Node, pos) tuples where pos is 0 for the
left subnode and 1 for the right.
>>> len(list(create(dimensions=2).children))
0
>>> len(list(create([ (1, 2) ]).children))
0
>>> len(list(create([ (2, 2), (2, 1), (2, 3) ]).children))
2
"""
if self.left and self.left.data is not None:
yield self.left, 0
if self.right and self.right.data is not None:
yield self.right, 1 | [
"def",
"children",
"(",
"self",
")",
":",
"if",
"self",
".",
"left",
"and",
"self",
".",
"left",
".",
"data",
"is",
"not",
"None",
":",
"yield",
"self",
".",
"left",
",",
"0",
"if",
"self",
".",
"right",
"and",
"self",
".",
"right",
".",
"data",
... | Returns an iterator for the non-empty children of the Node
The children are returned as (Node, pos) tuples where pos is 0 for the
left subnode and 1 for the right.
>>> len(list(create(dimensions=2).children))
0
>>> len(list(create([ (1, 2) ]).children))
0
>>> len(list(create([ (2, 2), (2, 1), (2, 3) ]).children))
2 | [
"Returns",
"an",
"iterator",
"for",
"the",
"non",
"-",
"empty",
"children",
"of",
"the",
"Node"
] | 587edc7056d7735177ad56a84ad5abccdea91693 | https://github.com/stefankoegl/kdtree/blob/587edc7056d7735177ad56a84ad5abccdea91693/kdtree.py#L103-L123 | train | 212,078 |
stefankoegl/kdtree | kdtree.py | Node.set_child | def set_child(self, index, child):
""" Sets one of the node's children
index 0 refers to the left, 1 to the right child """
if index == 0:
self.left = child
else:
self.right = child | python | def set_child(self, index, child):
""" Sets one of the node's children
index 0 refers to the left, 1 to the right child """
if index == 0:
self.left = child
else:
self.right = child | [
"def",
"set_child",
"(",
"self",
",",
"index",
",",
"child",
")",
":",
"if",
"index",
"==",
"0",
":",
"self",
".",
"left",
"=",
"child",
"else",
":",
"self",
".",
"right",
"=",
"child"
] | Sets one of the node's children
index 0 refers to the left, 1 to the right child | [
"Sets",
"one",
"of",
"the",
"node",
"s",
"children"
] | 587edc7056d7735177ad56a84ad5abccdea91693 | https://github.com/stefankoegl/kdtree/blob/587edc7056d7735177ad56a84ad5abccdea91693/kdtree.py#L126-L134 | train | 212,079 |
stefankoegl/kdtree | kdtree.py | Node.get_child_pos | def get_child_pos(self, child):
""" Returns the position if the given child
If the given node is the left child, 0 is returned. If its the right
child, 1 is returned. Otherwise None """
for c, pos in self.children:
if child == c:
return pos | python | def get_child_pos(self, child):
""" Returns the position if the given child
If the given node is the left child, 0 is returned. If its the right
child, 1 is returned. Otherwise None """
for c, pos in self.children:
if child == c:
return pos | [
"def",
"get_child_pos",
"(",
"self",
",",
"child",
")",
":",
"for",
"c",
",",
"pos",
"in",
"self",
".",
"children",
":",
"if",
"child",
"==",
"c",
":",
"return",
"pos"
] | Returns the position if the given child
If the given node is the left child, 0 is returned. If its the right
child, 1 is returned. Otherwise None | [
"Returns",
"the",
"position",
"if",
"the",
"given",
"child"
] | 587edc7056d7735177ad56a84ad5abccdea91693 | https://github.com/stefankoegl/kdtree/blob/587edc7056d7735177ad56a84ad5abccdea91693/kdtree.py#L156-L164 | train | 212,080 |
stefankoegl/kdtree | kdtree.py | KDNode.add | def add(self, point):
"""
Adds a point to the current node or iteratively
descends to one of its children.
Users should call add() only to the topmost tree.
"""
current = self
while True:
check_dimensionality([point], dimensions=current.dimensions)
# Adding has hit an empty leaf-node, add here
if current.data is None:
current.data = point
return current
# split on self.axis, recurse either left or right
if point[current.axis] < current.data[current.axis]:
if current.left is None:
current.left = current.create_subnode(point)
return current.left
else:
current = current.left
else:
if current.right is None:
current.right = current.create_subnode(point)
return current.right
else:
current = current.right | python | def add(self, point):
"""
Adds a point to the current node or iteratively
descends to one of its children.
Users should call add() only to the topmost tree.
"""
current = self
while True:
check_dimensionality([point], dimensions=current.dimensions)
# Adding has hit an empty leaf-node, add here
if current.data is None:
current.data = point
return current
# split on self.axis, recurse either left or right
if point[current.axis] < current.data[current.axis]:
if current.left is None:
current.left = current.create_subnode(point)
return current.left
else:
current = current.left
else:
if current.right is None:
current.right = current.create_subnode(point)
return current.right
else:
current = current.right | [
"def",
"add",
"(",
"self",
",",
"point",
")",
":",
"current",
"=",
"self",
"while",
"True",
":",
"check_dimensionality",
"(",
"[",
"point",
"]",
",",
"dimensions",
"=",
"current",
".",
"dimensions",
")",
"# Adding has hit an empty leaf-node, add here",
"if",
"... | Adds a point to the current node or iteratively
descends to one of its children.
Users should call add() only to the topmost tree. | [
"Adds",
"a",
"point",
"to",
"the",
"current",
"node",
"or",
"iteratively",
"descends",
"to",
"one",
"of",
"its",
"children",
"."
] | 587edc7056d7735177ad56a84ad5abccdea91693 | https://github.com/stefankoegl/kdtree/blob/587edc7056d7735177ad56a84ad5abccdea91693/kdtree.py#L224-L253 | train | 212,081 |
stefankoegl/kdtree | kdtree.py | KDNode.create_subnode | def create_subnode(self, data):
""" Creates a subnode for the current node """
return self.__class__(data,
axis=self.sel_axis(self.axis),
sel_axis=self.sel_axis,
dimensions=self.dimensions) | python | def create_subnode(self, data):
""" Creates a subnode for the current node """
return self.__class__(data,
axis=self.sel_axis(self.axis),
sel_axis=self.sel_axis,
dimensions=self.dimensions) | [
"def",
"create_subnode",
"(",
"self",
",",
"data",
")",
":",
"return",
"self",
".",
"__class__",
"(",
"data",
",",
"axis",
"=",
"self",
".",
"sel_axis",
"(",
"self",
".",
"axis",
")",
",",
"sel_axis",
"=",
"self",
".",
"sel_axis",
",",
"dimensions",
... | Creates a subnode for the current node | [
"Creates",
"a",
"subnode",
"for",
"the",
"current",
"node"
] | 587edc7056d7735177ad56a84ad5abccdea91693 | https://github.com/stefankoegl/kdtree/blob/587edc7056d7735177ad56a84ad5abccdea91693/kdtree.py#L257-L263 | train | 212,082 |
stefankoegl/kdtree | kdtree.py | KDNode.find_replacement | def find_replacement(self):
""" Finds a replacement for the current node
The replacement is returned as a
(replacement-node, replacements-parent-node) tuple """
if self.right:
child, parent = self.right.extreme_child(min, self.axis)
else:
child, parent = self.left.extreme_child(max, self.axis)
return (child, parent if parent is not None else self) | python | def find_replacement(self):
""" Finds a replacement for the current node
The replacement is returned as a
(replacement-node, replacements-parent-node) tuple """
if self.right:
child, parent = self.right.extreme_child(min, self.axis)
else:
child, parent = self.left.extreme_child(max, self.axis)
return (child, parent if parent is not None else self) | [
"def",
"find_replacement",
"(",
"self",
")",
":",
"if",
"self",
".",
"right",
":",
"child",
",",
"parent",
"=",
"self",
".",
"right",
".",
"extreme_child",
"(",
"min",
",",
"self",
".",
"axis",
")",
"else",
":",
"child",
",",
"parent",
"=",
"self",
... | Finds a replacement for the current node
The replacement is returned as a
(replacement-node, replacements-parent-node) tuple | [
"Finds",
"a",
"replacement",
"for",
"the",
"current",
"node"
] | 587edc7056d7735177ad56a84ad5abccdea91693 | https://github.com/stefankoegl/kdtree/blob/587edc7056d7735177ad56a84ad5abccdea91693/kdtree.py#L267-L278 | train | 212,083 |
stefankoegl/kdtree | kdtree.py | KDNode.remove | def remove(self, point, node=None):
""" Removes the node with the given point from the tree
Returns the new root node of the (sub)tree.
If there are multiple points matching "point", only one is removed. The
optional "node" parameter is used for checking the identity, once the
removeal candidate is decided."""
# Recursion has reached an empty leaf node, nothing here to delete
if not self:
return
# Recursion has reached the node to be deleted
if self.should_remove(point, node):
return self._remove(point)
# Remove direct subnode
if self.left and self.left.should_remove(point, node):
self.left = self.left._remove(point)
elif self.right and self.right.should_remove(point, node):
self.right = self.right._remove(point)
# Recurse to subtrees
if point[self.axis] <= self.data[self.axis]:
if self.left:
self.left = self.left.remove(point, node)
if point[self.axis] >= self.data[self.axis]:
if self.right:
self.right = self.right.remove(point, node)
return self | python | def remove(self, point, node=None):
""" Removes the node with the given point from the tree
Returns the new root node of the (sub)tree.
If there are multiple points matching "point", only one is removed. The
optional "node" parameter is used for checking the identity, once the
removeal candidate is decided."""
# Recursion has reached an empty leaf node, nothing here to delete
if not self:
return
# Recursion has reached the node to be deleted
if self.should_remove(point, node):
return self._remove(point)
# Remove direct subnode
if self.left and self.left.should_remove(point, node):
self.left = self.left._remove(point)
elif self.right and self.right.should_remove(point, node):
self.right = self.right._remove(point)
# Recurse to subtrees
if point[self.axis] <= self.data[self.axis]:
if self.left:
self.left = self.left.remove(point, node)
if point[self.axis] >= self.data[self.axis]:
if self.right:
self.right = self.right.remove(point, node)
return self | [
"def",
"remove",
"(",
"self",
",",
"point",
",",
"node",
"=",
"None",
")",
":",
"# Recursion has reached an empty leaf node, nothing here to delete",
"if",
"not",
"self",
":",
"return",
"# Recursion has reached the node to be deleted",
"if",
"self",
".",
"should_remove",
... | Removes the node with the given point from the tree
Returns the new root node of the (sub)tree.
If there are multiple points matching "point", only one is removed. The
optional "node" parameter is used for checking the identity, once the
removeal candidate is decided. | [
"Removes",
"the",
"node",
"with",
"the",
"given",
"point",
"from",
"the",
"tree"
] | 587edc7056d7735177ad56a84ad5abccdea91693 | https://github.com/stefankoegl/kdtree/blob/587edc7056d7735177ad56a84ad5abccdea91693/kdtree.py#L290-L323 | train | 212,084 |
stefankoegl/kdtree | kdtree.py | KDNode.axis_dist | def axis_dist(self, point, axis):
"""
Squared distance at the given axis between
the current Node and the given point
"""
return math.pow(self.data[axis] - point[axis], 2) | python | def axis_dist(self, point, axis):
"""
Squared distance at the given axis between
the current Node and the given point
"""
return math.pow(self.data[axis] - point[axis], 2) | [
"def",
"axis_dist",
"(",
"self",
",",
"point",
",",
"axis",
")",
":",
"return",
"math",
".",
"pow",
"(",
"self",
".",
"data",
"[",
"axis",
"]",
"-",
"point",
"[",
"axis",
"]",
",",
"2",
")"
] | Squared distance at the given axis between
the current Node and the given point | [
"Squared",
"distance",
"at",
"the",
"given",
"axis",
"between",
"the",
"current",
"Node",
"and",
"the",
"given",
"point"
] | 587edc7056d7735177ad56a84ad5abccdea91693 | https://github.com/stefankoegl/kdtree/blob/587edc7056d7735177ad56a84ad5abccdea91693/kdtree.py#L382-L387 | train | 212,085 |
stefankoegl/kdtree | kdtree.py | KDNode.dist | def dist(self, point):
"""
Squared distance between the current Node
and the given point
"""
r = range(self.dimensions)
return sum([self.axis_dist(point, i) for i in r]) | python | def dist(self, point):
"""
Squared distance between the current Node
and the given point
"""
r = range(self.dimensions)
return sum([self.axis_dist(point, i) for i in r]) | [
"def",
"dist",
"(",
"self",
",",
"point",
")",
":",
"r",
"=",
"range",
"(",
"self",
".",
"dimensions",
")",
"return",
"sum",
"(",
"[",
"self",
".",
"axis_dist",
"(",
"point",
",",
"i",
")",
"for",
"i",
"in",
"r",
"]",
")"
] | Squared distance between the current Node
and the given point | [
"Squared",
"distance",
"between",
"the",
"current",
"Node",
"and",
"the",
"given",
"point"
] | 587edc7056d7735177ad56a84ad5abccdea91693 | https://github.com/stefankoegl/kdtree/blob/587edc7056d7735177ad56a84ad5abccdea91693/kdtree.py#L390-L396 | train | 212,086 |
stefankoegl/kdtree | kdtree.py | KDNode.search_knn | def search_knn(self, point, k, dist=None):
""" Return the k nearest neighbors of point and their distances
point must be an actual point, not a node.
k is the number of results to return. The actual results can be less
(if there aren't more nodes to return) or more in case of equal
distances.
dist is a distance function, expecting two points and returning a
distance value. Distance values can be any comparable type.
The result is an ordered list of (node, distance) tuples.
"""
if k < 1:
raise ValueError("k must be greater than 0.")
if dist is None:
get_dist = lambda n: n.dist(point)
else:
get_dist = lambda n: dist(n.data, point)
results = []
self._search_node(point, k, results, get_dist, itertools.count())
# We sort the final result by the distance in the tuple
# (<KdNode>, distance).
return [(node, -d) for d, _, node in sorted(results, reverse=True)] | python | def search_knn(self, point, k, dist=None):
""" Return the k nearest neighbors of point and their distances
point must be an actual point, not a node.
k is the number of results to return. The actual results can be less
(if there aren't more nodes to return) or more in case of equal
distances.
dist is a distance function, expecting two points and returning a
distance value. Distance values can be any comparable type.
The result is an ordered list of (node, distance) tuples.
"""
if k < 1:
raise ValueError("k must be greater than 0.")
if dist is None:
get_dist = lambda n: n.dist(point)
else:
get_dist = lambda n: dist(n.data, point)
results = []
self._search_node(point, k, results, get_dist, itertools.count())
# We sort the final result by the distance in the tuple
# (<KdNode>, distance).
return [(node, -d) for d, _, node in sorted(results, reverse=True)] | [
"def",
"search_knn",
"(",
"self",
",",
"point",
",",
"k",
",",
"dist",
"=",
"None",
")",
":",
"if",
"k",
"<",
"1",
":",
"raise",
"ValueError",
"(",
"\"k must be greater than 0.\"",
")",
"if",
"dist",
"is",
"None",
":",
"get_dist",
"=",
"lambda",
"n",
... | Return the k nearest neighbors of point and their distances
point must be an actual point, not a node.
k is the number of results to return. The actual results can be less
(if there aren't more nodes to return) or more in case of equal
distances.
dist is a distance function, expecting two points and returning a
distance value. Distance values can be any comparable type.
The result is an ordered list of (node, distance) tuples. | [
"Return",
"the",
"k",
"nearest",
"neighbors",
"of",
"point",
"and",
"their",
"distances"
] | 587edc7056d7735177ad56a84ad5abccdea91693 | https://github.com/stefankoegl/kdtree/blob/587edc7056d7735177ad56a84ad5abccdea91693/kdtree.py#L399-L428 | train | 212,087 |
stefankoegl/kdtree | kdtree.py | KDNode.search_nn | def search_nn(self, point, dist=None):
"""
Search the nearest node of the given point
point must be an actual point, not a node. The nearest node to the
point is returned. If a location of an actual node is used, the Node
with this location will be returned (not its neighbor).
dist is a distance function, expecting two points and returning a
distance value. Distance values can be any comparable type.
The result is a (node, distance) tuple.
"""
return next(iter(self.search_knn(point, 1, dist)), None) | python | def search_nn(self, point, dist=None):
"""
Search the nearest node of the given point
point must be an actual point, not a node. The nearest node to the
point is returned. If a location of an actual node is used, the Node
with this location will be returned (not its neighbor).
dist is a distance function, expecting two points and returning a
distance value. Distance values can be any comparable type.
The result is a (node, distance) tuple.
"""
return next(iter(self.search_knn(point, 1, dist)), None) | [
"def",
"search_nn",
"(",
"self",
",",
"point",
",",
"dist",
"=",
"None",
")",
":",
"return",
"next",
"(",
"iter",
"(",
"self",
".",
"search_knn",
"(",
"point",
",",
"1",
",",
"dist",
")",
")",
",",
"None",
")"
] | Search the nearest node of the given point
point must be an actual point, not a node. The nearest node to the
point is returned. If a location of an actual node is used, the Node
with this location will be returned (not its neighbor).
dist is a distance function, expecting two points and returning a
distance value. Distance values can be any comparable type.
The result is a (node, distance) tuple. | [
"Search",
"the",
"nearest",
"node",
"of",
"the",
"given",
"point"
] | 587edc7056d7735177ad56a84ad5abccdea91693 | https://github.com/stefankoegl/kdtree/blob/587edc7056d7735177ad56a84ad5abccdea91693/kdtree.py#L478-L492 | train | 212,088 |
stefankoegl/kdtree | kdtree.py | KDNode.search_nn_dist | def search_nn_dist(self, point, distance, best=None):
"""
Search the n nearest nodes of the given point which are within given
distance
point must be a location, not a node. A list containing the n nearest
nodes to the point within the distance will be returned.
"""
results = []
get_dist = lambda n: n.dist(point)
self._search_nn_dist(point, distance, results, get_dist)
return results | python | def search_nn_dist(self, point, distance, best=None):
"""
Search the n nearest nodes of the given point which are within given
distance
point must be a location, not a node. A list containing the n nearest
nodes to the point within the distance will be returned.
"""
results = []
get_dist = lambda n: n.dist(point)
self._search_nn_dist(point, distance, results, get_dist)
return results | [
"def",
"search_nn_dist",
"(",
"self",
",",
"point",
",",
"distance",
",",
"best",
"=",
"None",
")",
":",
"results",
"=",
"[",
"]",
"get_dist",
"=",
"lambda",
"n",
":",
"n",
".",
"dist",
"(",
"point",
")",
"self",
".",
"_search_nn_dist",
"(",
"point",... | Search the n nearest nodes of the given point which are within given
distance
point must be a location, not a node. A list containing the n nearest
nodes to the point within the distance will be returned. | [
"Search",
"the",
"n",
"nearest",
"nodes",
"of",
"the",
"given",
"point",
"which",
"are",
"within",
"given",
"distance"
] | 587edc7056d7735177ad56a84ad5abccdea91693 | https://github.com/stefankoegl/kdtree/blob/587edc7056d7735177ad56a84ad5abccdea91693/kdtree.py#L517-L530 | train | 212,089 |
stefankoegl/kdtree | kdtree.py | KDNode.is_valid | def is_valid(self):
""" Checks recursively if the tree is valid
It is valid if each node splits correctly """
if not self:
return True
if self.left and self.data[self.axis] < self.left.data[self.axis]:
return False
if self.right and self.data[self.axis] > self.right.data[self.axis]:
return False
return all(c.is_valid() for c, _ in self.children) or self.is_leaf | python | def is_valid(self):
""" Checks recursively if the tree is valid
It is valid if each node splits correctly """
if not self:
return True
if self.left and self.data[self.axis] < self.left.data[self.axis]:
return False
if self.right and self.data[self.axis] > self.right.data[self.axis]:
return False
return all(c.is_valid() for c, _ in self.children) or self.is_leaf | [
"def",
"is_valid",
"(",
"self",
")",
":",
"if",
"not",
"self",
":",
"return",
"True",
"if",
"self",
".",
"left",
"and",
"self",
".",
"data",
"[",
"self",
".",
"axis",
"]",
"<",
"self",
".",
"left",
".",
"data",
"[",
"self",
".",
"axis",
"]",
":... | Checks recursively if the tree is valid
It is valid if each node splits correctly | [
"Checks",
"recursively",
"if",
"the",
"tree",
"is",
"valid"
] | 587edc7056d7735177ad56a84ad5abccdea91693 | https://github.com/stefankoegl/kdtree/blob/587edc7056d7735177ad56a84ad5abccdea91693/kdtree.py#L534-L548 | train | 212,090 |
stefankoegl/kdtree | kdtree.py | KDNode.extreme_child | def extreme_child(self, sel_func, axis):
""" Returns a child of the subtree and its parent
The child is selected by sel_func which is either min or max
(or a different function with similar semantics). """
max_key = lambda child_parent: child_parent[0].data[axis]
# we don't know our parent, so we include None
me = [(self, None)] if self else []
child_max = [c.extreme_child(sel_func, axis) for c, _ in self.children]
# insert self for unknown parents
child_max = [(c, p if p is not None else self) for c, p in child_max]
candidates = me + child_max
if not candidates:
return None, None
return sel_func(candidates, key=max_key) | python | def extreme_child(self, sel_func, axis):
""" Returns a child of the subtree and its parent
The child is selected by sel_func which is either min or max
(or a different function with similar semantics). """
max_key = lambda child_parent: child_parent[0].data[axis]
# we don't know our parent, so we include None
me = [(self, None)] if self else []
child_max = [c.extreme_child(sel_func, axis) for c, _ in self.children]
# insert self for unknown parents
child_max = [(c, p if p is not None else self) for c, p in child_max]
candidates = me + child_max
if not candidates:
return None, None
return sel_func(candidates, key=max_key) | [
"def",
"extreme_child",
"(",
"self",
",",
"sel_func",
",",
"axis",
")",
":",
"max_key",
"=",
"lambda",
"child_parent",
":",
"child_parent",
"[",
"0",
"]",
".",
"data",
"[",
"axis",
"]",
"# we don't know our parent, so we include None",
"me",
"=",
"[",
"(",
"... | Returns a child of the subtree and its parent
The child is selected by sel_func which is either min or max
(or a different function with similar semantics). | [
"Returns",
"a",
"child",
"of",
"the",
"subtree",
"and",
"its",
"parent"
] | 587edc7056d7735177ad56a84ad5abccdea91693 | https://github.com/stefankoegl/kdtree/blob/587edc7056d7735177ad56a84ad5abccdea91693/kdtree.py#L551-L572 | train | 212,091 |
tomoh1r/ansible-vault | ansible_vault/api.py | Vault.dump_raw | def dump_raw(self, text, stream=None):
"""Encrypt raw data and write to stream."""
encrypted = self.vault.encrypt(text)
if stream:
stream.write(encrypted)
else:
return encrypted | python | def dump_raw(self, text, stream=None):
"""Encrypt raw data and write to stream."""
encrypted = self.vault.encrypt(text)
if stream:
stream.write(encrypted)
else:
return encrypted | [
"def",
"dump_raw",
"(",
"self",
",",
"text",
",",
"stream",
"=",
"None",
")",
":",
"encrypted",
"=",
"self",
".",
"vault",
".",
"encrypt",
"(",
"text",
")",
"if",
"stream",
":",
"stream",
".",
"write",
"(",
"encrypted",
")",
"else",
":",
"return",
... | Encrypt raw data and write to stream. | [
"Encrypt",
"raw",
"data",
"and",
"write",
"to",
"stream",
"."
] | 6c97b4e64193848fff585443bdd506761f66d595 | https://github.com/tomoh1r/ansible-vault/blob/6c97b4e64193848fff585443bdd506761f66d595/ansible_vault/api.py#L52-L58 | train | 212,092 |
tomoh1r/ansible-vault | ansible_vault/api.py | Vault.dump | def dump(self, data, stream=None):
"""Encrypt data and print stdout or write to stream."""
yaml_text = yaml.dump(
data,
default_flow_style=False,
allow_unicode=True)
return self.dump_raw(yaml_text, stream=stream) | python | def dump(self, data, stream=None):
"""Encrypt data and print stdout or write to stream."""
yaml_text = yaml.dump(
data,
default_flow_style=False,
allow_unicode=True)
return self.dump_raw(yaml_text, stream=stream) | [
"def",
"dump",
"(",
"self",
",",
"data",
",",
"stream",
"=",
"None",
")",
":",
"yaml_text",
"=",
"yaml",
".",
"dump",
"(",
"data",
",",
"default_flow_style",
"=",
"False",
",",
"allow_unicode",
"=",
"True",
")",
"return",
"self",
".",
"dump_raw",
"(",
... | Encrypt data and print stdout or write to stream. | [
"Encrypt",
"data",
"and",
"print",
"stdout",
"or",
"write",
"to",
"stream",
"."
] | 6c97b4e64193848fff585443bdd506761f66d595 | https://github.com/tomoh1r/ansible-vault/blob/6c97b4e64193848fff585443bdd506761f66d595/ansible_vault/api.py#L64-L70 | train | 212,093 |
jazzband/django-simple-menu | menu/menu.py | Menu.add_item | def add_item(c, name, item):
"""
add_item adds MenuItems to the menu identified by 'name'
"""
if isinstance(item, MenuItem):
if name not in c.items:
c.items[name] = []
c.items[name].append(item)
c.sorted[name] = False | python | def add_item(c, name, item):
"""
add_item adds MenuItems to the menu identified by 'name'
"""
if isinstance(item, MenuItem):
if name not in c.items:
c.items[name] = []
c.items[name].append(item)
c.sorted[name] = False | [
"def",
"add_item",
"(",
"c",
",",
"name",
",",
"item",
")",
":",
"if",
"isinstance",
"(",
"item",
",",
"MenuItem",
")",
":",
"if",
"name",
"not",
"in",
"c",
".",
"items",
":",
"c",
".",
"items",
"[",
"name",
"]",
"=",
"[",
"]",
"c",
".",
"ite... | add_item adds MenuItems to the menu identified by 'name' | [
"add_item",
"adds",
"MenuItems",
"to",
"the",
"menu",
"identified",
"by",
"name"
] | c9d8c4f1246655a7f9763555f7c96b88dd770791 | https://github.com/jazzband/django-simple-menu/blob/c9d8c4f1246655a7f9763555f7c96b88dd770791/menu/menu.py#L37-L45 | train | 212,094 |
jazzband/django-simple-menu | menu/menu.py | Menu.load_menus | def load_menus(c):
"""
load_menus loops through INSTALLED_APPS and loads the menu.py
files from them.
"""
# we don't need to do this more than once
if c.loaded:
return
# Fetch all installed app names
app_names = settings.INSTALLED_APPS
if apps:
app_names = [
app_config.name
for app_config in apps.get_app_configs()
]
# loop through our INSTALLED_APPS
for app in app_names:
# skip any django apps
if app.startswith("django."):
continue
menu_module = '%s.menus' % app
try:
__import__(menu_module, fromlist=["menu", ])
except ImportError:
pass
c.loaded = True | python | def load_menus(c):
"""
load_menus loops through INSTALLED_APPS and loads the menu.py
files from them.
"""
# we don't need to do this more than once
if c.loaded:
return
# Fetch all installed app names
app_names = settings.INSTALLED_APPS
if apps:
app_names = [
app_config.name
for app_config in apps.get_app_configs()
]
# loop through our INSTALLED_APPS
for app in app_names:
# skip any django apps
if app.startswith("django."):
continue
menu_module = '%s.menus' % app
try:
__import__(menu_module, fromlist=["menu", ])
except ImportError:
pass
c.loaded = True | [
"def",
"load_menus",
"(",
"c",
")",
":",
"# we don't need to do this more than once",
"if",
"c",
".",
"loaded",
":",
"return",
"# Fetch all installed app names",
"app_names",
"=",
"settings",
".",
"INSTALLED_APPS",
"if",
"apps",
":",
"app_names",
"=",
"[",
"app_conf... | load_menus loops through INSTALLED_APPS and loads the menu.py
files from them. | [
"load_menus",
"loops",
"through",
"INSTALLED_APPS",
"and",
"loads",
"the",
"menu",
".",
"py",
"files",
"from",
"them",
"."
] | c9d8c4f1246655a7f9763555f7c96b88dd770791 | https://github.com/jazzband/django-simple-menu/blob/c9d8c4f1246655a7f9763555f7c96b88dd770791/menu/menu.py#L48-L78 | train | 212,095 |
jazzband/django-simple-menu | menu/menu.py | Menu.sort_menus | def sort_menus(c):
"""
sort_menus goes through the items and sorts them based on
their weight
"""
for name in c.items:
if not c.sorted[name]:
c.items[name].sort(key=lambda x: x.weight)
c.sorted[name] = True | python | def sort_menus(c):
"""
sort_menus goes through the items and sorts them based on
their weight
"""
for name in c.items:
if not c.sorted[name]:
c.items[name].sort(key=lambda x: x.weight)
c.sorted[name] = True | [
"def",
"sort_menus",
"(",
"c",
")",
":",
"for",
"name",
"in",
"c",
".",
"items",
":",
"if",
"not",
"c",
".",
"sorted",
"[",
"name",
"]",
":",
"c",
".",
"items",
"[",
"name",
"]",
".",
"sort",
"(",
"key",
"=",
"lambda",
"x",
":",
"x",
".",
"... | sort_menus goes through the items and sorts them based on
their weight | [
"sort_menus",
"goes",
"through",
"the",
"items",
"and",
"sorts",
"them",
"based",
"on",
"their",
"weight"
] | c9d8c4f1246655a7f9763555f7c96b88dd770791 | https://github.com/jazzband/django-simple-menu/blob/c9d8c4f1246655a7f9763555f7c96b88dd770791/menu/menu.py#L81-L89 | train | 212,096 |
jazzband/django-simple-menu | menu/menu.py | Menu.process | def process(c, request, name=None):
"""
process uses the current request to determine which menus
should be visible, which are selected, etc.
"""
# make sure we're loaded & sorted
c.load_menus()
c.sort_menus()
if name is None:
# special case, process all menus
items = {}
for name in c.items:
items[name] = c.process(request, name)
return items
if name not in c.items:
return []
items = copy.deepcopy(c.items[name])
curitem = None
for item in items:
item.process(request)
if item.visible:
item.selected = False
if item.match_url(request):
if curitem is None or len(curitem.url) < len(item.url):
curitem = item
if curitem is not None:
curitem.selected = True
# return only visible items
visible = [
item
for item in items
if item.visible
]
# determine if we should apply 'selected' to parents when one of their
# children is the 'selected' menu
if getattr(settings, 'MENU_SELECT_PARENTS', False):
def is_child_selected(item):
for child in item.children:
if child.selected or is_child_selected(child):
return True
for item in visible:
if is_child_selected(item):
item.selected = True
return visible | python | def process(c, request, name=None):
"""
process uses the current request to determine which menus
should be visible, which are selected, etc.
"""
# make sure we're loaded & sorted
c.load_menus()
c.sort_menus()
if name is None:
# special case, process all menus
items = {}
for name in c.items:
items[name] = c.process(request, name)
return items
if name not in c.items:
return []
items = copy.deepcopy(c.items[name])
curitem = None
for item in items:
item.process(request)
if item.visible:
item.selected = False
if item.match_url(request):
if curitem is None or len(curitem.url) < len(item.url):
curitem = item
if curitem is not None:
curitem.selected = True
# return only visible items
visible = [
item
for item in items
if item.visible
]
# determine if we should apply 'selected' to parents when one of their
# children is the 'selected' menu
if getattr(settings, 'MENU_SELECT_PARENTS', False):
def is_child_selected(item):
for child in item.children:
if child.selected or is_child_selected(child):
return True
for item in visible:
if is_child_selected(item):
item.selected = True
return visible | [
"def",
"process",
"(",
"c",
",",
"request",
",",
"name",
"=",
"None",
")",
":",
"# make sure we're loaded & sorted",
"c",
".",
"load_menus",
"(",
")",
"c",
".",
"sort_menus",
"(",
")",
"if",
"name",
"is",
"None",
":",
"# special case, process all menus",
"it... | process uses the current request to determine which menus
should be visible, which are selected, etc. | [
"process",
"uses",
"the",
"current",
"request",
"to",
"determine",
"which",
"menus",
"should",
"be",
"visible",
"which",
"are",
"selected",
"etc",
"."
] | c9d8c4f1246655a7f9763555f7c96b88dd770791 | https://github.com/jazzband/django-simple-menu/blob/c9d8c4f1246655a7f9763555f7c96b88dd770791/menu/menu.py#L92-L143 | train | 212,097 |
jazzband/django-simple-menu | menu/menu.py | MenuItem.check | def check(self, request):
"""
Evaluate if we should be visible for this request
"""
if callable(self.check_func):
self.visible = self.check_func(request) | python | def check(self, request):
"""
Evaluate if we should be visible for this request
"""
if callable(self.check_func):
self.visible = self.check_func(request) | [
"def",
"check",
"(",
"self",
",",
"request",
")",
":",
"if",
"callable",
"(",
"self",
".",
"check_func",
")",
":",
"self",
".",
"visible",
"=",
"self",
".",
"check_func",
"(",
"request",
")"
] | Evaluate if we should be visible for this request | [
"Evaluate",
"if",
"we",
"should",
"be",
"visible",
"for",
"this",
"request"
] | c9d8c4f1246655a7f9763555f7c96b88dd770791 | https://github.com/jazzband/django-simple-menu/blob/c9d8c4f1246655a7f9763555f7c96b88dd770791/menu/menu.py#L188-L193 | train | 212,098 |
jazzband/django-simple-menu | menu/menu.py | MenuItem.process | def process(self, request):
"""
process determines if this item should visible, if its selected, etc...
"""
# if we're not visible we return since we don't need to do anymore processing
self.check(request)
if not self.visible:
return
# evaluate our title
if callable(self.title):
self.title = self.title(request)
# if no title is set turn it into a slug
if self.slug is None:
# in python3 we don't need to convert to unicode, in python2 slugify
# requires a unicode string
if sys.version_info > (3, 0):
self.slug = slugify(self.title)
else:
self.slug = slugify(unicode(self.title))
# evaluate children
if callable(self.children):
children = list(self.children(request))
else:
children = list(self.children)
for child in children:
child.parent = self
child.process(request)
self.children = [
child
for child in children
if child.visible
]
self.children.sort(key=lambda child: child.weight)
# if we have no children and MENU_HIDE_EMPTY then we are not visible and should return
hide_empty = getattr(settings, 'MENU_HIDE_EMPTY', False)
if hide_empty and len(self.children) == 0:
self.visible = False
return
# find out if one of our children is selected, and mark it as such
curitem = None
for item in self.children:
item.selected = False
if item.match_url(request):
if curitem is None or len(curitem.url) < len(item.url):
curitem = item
if curitem is not None:
curitem.selected = True | python | def process(self, request):
"""
process determines if this item should visible, if its selected, etc...
"""
# if we're not visible we return since we don't need to do anymore processing
self.check(request)
if not self.visible:
return
# evaluate our title
if callable(self.title):
self.title = self.title(request)
# if no title is set turn it into a slug
if self.slug is None:
# in python3 we don't need to convert to unicode, in python2 slugify
# requires a unicode string
if sys.version_info > (3, 0):
self.slug = slugify(self.title)
else:
self.slug = slugify(unicode(self.title))
# evaluate children
if callable(self.children):
children = list(self.children(request))
else:
children = list(self.children)
for child in children:
child.parent = self
child.process(request)
self.children = [
child
for child in children
if child.visible
]
self.children.sort(key=lambda child: child.weight)
# if we have no children and MENU_HIDE_EMPTY then we are not visible and should return
hide_empty = getattr(settings, 'MENU_HIDE_EMPTY', False)
if hide_empty and len(self.children) == 0:
self.visible = False
return
# find out if one of our children is selected, and mark it as such
curitem = None
for item in self.children:
item.selected = False
if item.match_url(request):
if curitem is None or len(curitem.url) < len(item.url):
curitem = item
if curitem is not None:
curitem.selected = True | [
"def",
"process",
"(",
"self",
",",
"request",
")",
":",
"# if we're not visible we return since we don't need to do anymore processing",
"self",
".",
"check",
"(",
"request",
")",
"if",
"not",
"self",
".",
"visible",
":",
"return",
"# evaluate our title",
"if",
"call... | process determines if this item should visible, if its selected, etc... | [
"process",
"determines",
"if",
"this",
"item",
"should",
"visible",
"if",
"its",
"selected",
"etc",
"..."
] | c9d8c4f1246655a7f9763555f7c96b88dd770791 | https://github.com/jazzband/django-simple-menu/blob/c9d8c4f1246655a7f9763555f7c96b88dd770791/menu/menu.py#L195-L250 | train | 212,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.