docstring stringlengths 52 499 | function stringlengths 67 35.2k | __index_level_0__ int64 52.6k 1.16M |
|---|---|---|
Add a new service to the list of ones we know about.
Args:
new_service (WindowsService): the service to add. | def AddService(self, new_service):
for service in self._services:
if new_service == service:
# If this service is the same as one we already know about, we
# just want to add where it came from.
service.sources.append(new_service.sources[0])
return
# We only add a new... | 289,304 |
Produces a human readable multi-line string representing the service.
Args:
service (WindowsService): service to format.
Returns:
str: human readable representation of a Windows Service. | def _FormatServiceText(self, service):
string_segments = [
service.name,
'\tImage Path = {0:s}'.format(service.image_path),
'\tService Type = {0:s}'.format(service.HumanReadableType()),
'\tStart Type = {0:s}'.format(service.HumanReadableStartType()),
'\tService Dl... | 289,306 |
Compiles an analysis report.
Args:
mediator (AnalysisMediator): mediates interactions between analysis
plugins and other components, such as storage and dfvfs.
Returns:
AnalysisReport: report. | def CompileReport(self, mediator):
# TODO: move YAML representation out of plugin and into serialization.
lines_of_text = []
if self._output_format == 'yaml':
lines_of_text.append(
yaml.safe_dump_all(self._service_collection.services))
else:
lines_of_text.append('Listing Windo... | 289,307 |
Analyzes an event and creates Windows Services as required.
At present, this method only handles events extracted from the Registry.
Args:
mediator (AnalysisMediator): mediates interactions between analysis
plugins and other components, such as storage and dfvfs.
event (EventObject): e... | def ExamineEvent(self, mediator, event):
# TODO: Handle event log entries here also (ie, event id 4697).
event_data_type = getattr(event, 'data_type', '')
if event_data_type == 'windows:registry:service':
# Create and store the service.
service = WindowsService.FromEvent(event)
self._... | 289,308 |
Determines the formatted message strings for an event object.
Args:
formatter_mediator (FormatterMediator): mediates the interactions
between formatters and other components, such as storage and Windows
EventLog resources.
event (EventObject): event.
Returns:
tuple(str, s... | def GetMessages(self, formatter_mediator, event):
if self.DATA_TYPE != event.data_type:
raise errors.WrongFormatter('Unsupported data type: {0:s}.'.format(
event.data_type))
event_values = event.CopyToDict()
cookie_flags = event_values.get('flags', None)
if cookie_flags == 0:
... | 289,309 |
Extracts relevant install history entries.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
top_level (dict[str, object]): plist top-level key. | def GetEntries(self, parser_mediator, top_level=None, **unused_kwargs):
for entry in top_level:
datetime_value = entry.get('date', None)
package_identifiers = entry.get('packageIdentifiers', [])
if not datetime_value or not package_identifiers:
continue
display_name = entry.ge... | 289,310 |
Initializes a storage reader.
Args:
path (str): path to the input file. | def __init__(self, path):
super(SQLiteStorageFileReader, self).__init__(path)
self._storage_file = sqlite_file.SQLiteStorageFile()
self._storage_file.Open(path=path) | 289,311 |
Detects which tag file is most appropriate.
Args:
analysis_mediator (AnalysisMediator): analysis mediator.
Returns:
bool: True if a tag file is autodetected. | def _AttemptAutoDetectTagFile(self, analysis_mediator):
self._autodetect_tag_file_attempt = True
if not analysis_mediator.data_location:
return False
operating_system = analysis_mediator.operating_system.lower()
filename = self._OS_TAG_FILES.get(operating_system, None)
if not filename:
... | 289,313 |
Compiles an analysis report.
Args:
mediator (AnalysisMediator): mediates interactions between
analysis plugins and other components, such as storage and dfvfs.
Returns:
AnalysisReport: analysis report. | def CompileReport(self, mediator):
report_text = 'Tagging plugin produced {0:d} tags.\n'.format(
self._number_of_event_tags)
self._number_of_event_tags = 0
return reports.AnalysisReport(plugin_name=self.NAME, text=report_text) | 289,314 |
Analyzes an EventObject and tags it according to rules in the tag file.
Args:
mediator (AnalysisMediator): mediates interactions between analysis
plugins and other components, such as storage and dfvfs.
event (EventObject): event to examine. | def ExamineEvent(self, mediator, event):
if self._tagging_rules is None:
if self._autodetect_tag_file_attempt:
# There's nothing to tag with, and we've already tried to find a good
# tag file, so there's nothing we can do with this event (or any other).
return
if not self._... | 289,315 |
Sets the tag file to be used by the plugin.
Args:
tagging_file_path (str): path of the tagging file. | def SetAndLoadTagFile(self, tagging_file_path):
tag_file = tagging_file.TaggingFile(tagging_file_path)
self._tagging_rules = tag_file.GetEventTaggingRules() | 289,316 |
Writes the body of an event to the output.
Args:
event (EventObject): event. | def WriteEventBody(self, event):
latitude = getattr(event, 'latitude', None)
longitude = getattr(event, 'longitude', None)
if latitude is not None and longitude is not None:
placemark_xml_element = ElementTree.Element('Placemark')
name_xml_element = ElementTree.SubElement(placemark_xml_ele... | 289,317 |
Parses a syslog body that matched one of defined grammars.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
key (str): name of the matching grammar.
date_time (dfdatetime.DateTimeValues): date and time values.... | def ParseMessage(self, parser_mediator, key, date_time, tokens):
if key != 'task_run':
raise ValueError('Unknown grammar key: {0:s}'.format(key))
event_data = CronTaskRunEventData()
event_data.body = tokens.get('body', None)
event_data.command = tokens.get('command', None)
event_data.hos... | 289,320 |
Analyzes a block of data, attempting to match Yara rules to it.
Args:
data(bytes): a block of data. | def Analyze(self, data):
if not self._rules:
return
try:
self._matches = self._rules.match(data=data, timeout=self._MATCH_TIMEOUT)
except yara.YaraTimeoutError:
logger.error('Could not process file within timeout: {0:d}'.format(
self._MATCH_TIMEOUT))
except yara.YaraErro... | 289,322 |
Retrieves the table names in a database.
Args:
database (pyesedb.file): ESE database.
Returns:
list[str]: table names. | def _GetTableNames(self, database):
table_names = []
for esedb_table in database.tables:
table_names.append(esedb_table.name)
return table_names | 289,324 |
Parses an ESE database file-like object.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
file_object (dfvfs.FileIO): file-like object. | def ParseFileObject(self, parser_mediator, file_object):
esedb_file = pyesedb.file()
try:
esedb_file.open_file_object(file_object)
except IOError as exception:
parser_mediator.ProduceExtractionWarning(
'unable to open file with error: {0!s}'.format(exception))
return
#... | 289,325 |
Parses an activity log row.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
query (str): query that created the row.
row (sqlite3.Row): row. | def ParseActivityLogUncompressedRow(
self, parser_mediator, query, row, **unused_kwargs):
query_hash = hash(query)
event_data = ChromeExtensionActivityEventData()
event_data.action_type = self._GetRowValue(query_hash, row, 'action_type')
event_data.activity_id = self._GetRowValue(query_hash,... | 289,327 |
Determines if a specific table exists.
Args:
table_name (str): table name.
Returns:
bool: True if the table exists.
Raises:
RuntimeError: if the database is not opened. | def HasTable(self, table_name):
if not self._connection:
raise RuntimeError(
'Cannot determine if table exists database not opened.')
sql_query = self._HAS_TABLE_QUERY.format(table_name)
self._cursor.execute(sql_query)
if self._cursor.fetchone():
return True
return Fals... | 289,330 |
Retrieves values from a table.
Args:
table_names (list[str]): table names.
column_names (list[str]): column names.
condition (str): query condition such as
"log_source == 'Application Error'".
Yields:
sqlite3.row: row.
Raises:
RuntimeError: if the database is not o... | def GetValues(self, table_names, column_names, condition):
if not self._connection:
raise RuntimeError('Cannot retrieve values database not opened.')
if condition:
condition = ' WHERE {0:s}'.format(condition)
sql_query = 'SELECT {1:s} FROM {0:s}{2:s}'.format(
', '.join(table_names... | 289,331 |
Opens the database file.
Args:
filename (str): filename of the database.
read_only (Optional[bool]): True if the database should be opened in
read-only mode. Since sqlite3 does not support a real read-only
mode we fake it by only permitting SELECT queries.
Returns:
bool: ... | def Open(self, filename, read_only=False):
if self._connection:
raise RuntimeError('Cannot open database already opened.')
self.filename = filename
self.read_only = read_only
try:
self._connection = sqlite3.connect(filename)
except sqlite3.OperationalError:
return False
... | 289,332 |
Retrieves the Event Log provider key.
Args:
log_source (str): Event Log source.
Returns:
str: Event Log provider key or None if not available.
Raises:
RuntimeError: if more than one value is found in the database. | def _GetEventLogProviderKey(self, log_source):
table_names = ['event_log_providers']
column_names = ['event_log_provider_key']
condition = 'log_source == "{0:s}"'.format(log_source)
values_list = list(self._database_file.GetValues(
table_names, column_names, condition))
number_of_valu... | 289,333 |
Retrieves a specific message from a specific message table.
Args:
message_file_key (int): message file key.
lcid (int): language code identifier (LCID).
message_identifier (int): message identifier.
Returns:
str: message string or None if not available.
Raises:
RuntimeError:... | def _GetMessage(self, message_file_key, lcid, message_identifier):
table_name = 'message_table_{0:d}_0x{1:08x}'.format(message_file_key, lcid)
has_table = self._database_file.HasTable(table_name)
if not has_table:
return None
column_names = ['message_string']
condition = 'message_identi... | 289,334 |
Retrieves the message file keys.
Args:
event_log_provider_key (int): Event Log provider key.
Yields:
int: message file key. | def _GetMessageFileKeys(self, event_log_provider_key):
table_names = ['message_file_per_event_log_provider']
column_names = ['message_file_key']
condition = 'event_log_provider_key == {0:d}'.format(
event_log_provider_key)
generator = self._database_file.GetValues(
table_names, col... | 289,335 |
Reformats the message string.
Args:
message_string (str): message string.
Returns:
str: message string in Python format() (PEP 3101) style. | def _ReformatMessageString(self, message_string):
def _PlaceHolderSpecifierReplacer(match_object):
expanded_groups = []
for group in match_object.groups():
try:
place_holder_number = int(group, 10) - 1
expanded_group = '{{{0:d}:s}}'.format(place_holder_number)
... | 289,336 |
Retrieves a specific message for a specific Event Log source.
Args:
log_source (str): Event Log source.
lcid (int): language code identifier (LCID).
message_identifier (int): message identifier.
Returns:
str: message string or None if not available. | def GetMessage(self, log_source, lcid, message_identifier):
event_log_provider_key = self._GetEventLogProviderKey(log_source)
if not event_log_provider_key:
return None
generator = self._GetMessageFileKeys(event_log_provider_key)
if not generator:
return None
# TODO: cache a numbe... | 289,337 |
Retrieves the metadata attribute.
Args:
attribute_name (str): name of the metadata attribute.
Returns:
str: the metadata attribute or None.
Raises:
RuntimeError: if more than one value is found in the database. | def GetMetadataAttribute(self, attribute_name):
table_name = 'metadata'
has_table = self._database_file.HasTable(table_name)
if not has_table:
return None
column_names = ['value']
condition = 'name == "{0:s}"'.format(attribute_name)
values = list(self._database_file.GetValues(
... | 289,338 |
Opens the database reader object.
Args:
filename (str): filename of the database.
Returns:
bool: True if successful.
Raises:
RuntimeError: if the version or string format of the database
is not supported. | def Open(self, filename):
if not super(WinevtResourcesSqlite3DatabaseReader, self).Open(filename):
return False
version = self.GetMetadataAttribute('version')
if not version or version != '20150315':
raise RuntimeError('Unsupported version: {0:s}'.format(version))
string_format = self... | 289,339 |
Initializes the analysis report.
Args:
plugin_name (Optional[str]): name of the analysis plugin that generated
the report.
text (Optional[str]): report text. | def __init__(self, plugin_name=None, text=None):
super(AnalysisReport, self).__init__()
self.filter_string = None
self.plugin_name = plugin_name
self.report_array = None
self.report_dict = None
# TODO: rename text to body?
self.text = text
self.time_compiled = None | 289,340 |
Parses and validates options.
Args:
options (argparse.Namespace): parser options.
configuration_object (CLITool): object to be configured by the argument
helper.
Raises:
BadConfigObject: when the configuration object is of the wrong type. | def ParseOptions(cls, options, configuration_object):
if not isinstance(configuration_object, tools.CLITool):
raise errors.BadConfigObject(
'Configuration object is not an instance of CLITool')
profilers = cls._ParseStringOption(options, 'profilers')
if not profilers:
profilers ... | 289,343 |
Parses and validates options.
Args:
options (argparse.Namespace): parser options.
configuration_object (CLITool): object to be configured by the argument
helper.
Raises:
BadConfigObject: when the configuration object is of the wrong type. | def ParseOptions(cls, options, configuration_object):
if not isinstance(configuration_object, tools.CLITool):
raise errors.BadConfigObject(
'Configuration object is not an instance of CLITool')
data_location = cls._ParseStringOption(options, 'data_location')
if not data_location:
... | 289,345 |
Adds command line arguments the helper supports to an argument group.
This function takes an argument parser or an argument group object and adds
to it all the command line arguments this helper supports.
Args:
argument_group (argparse._ArgumentGroup|argparse.ArgumentParser): group
to appe... | def AddArguments(cls, argument_group):
argument_group.add_argument(
'--nsrlsvr-hash', '--nsrlsvr_hash', dest='nsrlsvr_hash', type=str,
action='store', choices=nsrlsvr.NsrlsvrAnalyzer.SUPPORTED_HASHES,
default=cls._DEFAULT_HASH, metavar='HASH', help=(
'Type of hash to use to ... | 289,346 |
Parses and validates options.
Args:
options (argparse.Namespace): parser options object.
analysis_plugin (NsrlsvrAnalysisPlugin): analysis plugin to configure.
Raises:
BadConfigObject: when the analysis plugin is the wrong type.
BadConfigOption: when unable to connect to nsrlsvr instan... | def ParseOptions(cls, options, analysis_plugin):
if not isinstance(analysis_plugin, nsrlsvr.NsrlsvrAnalysisPlugin):
raise errors.BadConfigObject(
'Analysis plugin is not an instance of NsrlsvrAnalysisPlugin')
label = cls._ParseStringOption(
options, 'nsrlsvr_label', default_value=c... | 289,347 |
Adds command line arguments to an argument group.
This function takes an argument parser or an argument group object and adds
to it all the command line arguments this helper supports.
Args:
argument_group (argparse._ArgumentGroup|argparse.ArgumentParser):
argparse group. | def AddArguments(cls, argument_group):
storage_formats = sorted(definitions.STORAGE_FORMATS)
argument_group.add_argument(
'--storage_format', '--storage-format', action='store',
choices=storage_formats, dest='storage_format', type=str,
metavar='FORMAT', default=definitions.DEFAULT_... | 289,348 |
Parses and validates options.
Args:
options (argparse.Namespace): parser options.
configuration_object (CLITool): object to be configured by the argument
helper.
Raises:
BadConfigObject: when the configuration object is of the wrong type.
BadConfigOption: if the storage forma... | def ParseOptions(cls, options, configuration_object):
if not isinstance(configuration_object, tools.CLITool):
raise errors.BadConfigObject(
'Configuration object is not an instance of CLITool')
storage_format = cls._ParseStringOption(options, 'storage_format')
if not storage_format:
... | 289,349 |
Configures the logging root logger.
Args:
debug_output (Optional[bool]): True if the logging should include debug
output.
filename (Optional[str]): log filename.
mode (Optional[str]): log file access mode.
quiet_mode (Optional[bool]): True if the logging should not include
information... | def ConfigureLogging(
debug_output=False, filename=None, mode='w', quiet_mode=False):
# Remove all possible log handlers. The log handlers cannot be reconfigured
# and therefore must be recreated.
for handler in logging.root.handlers:
logging.root.removeHandler(handler)
logger = logging.getLogger()
... | 289,350 |
Initializes a compressed file logging handler.
Args:
filename (str): name of the log file.
mode (Optional[str]): file access mode.
encoding (Optional[str]): encoding of the log lines. | def __init__(self, filename, mode='a', encoding='utf-8'):
if 't' not in mode and encoding and py2to3.PY_3:
mode = '{0:s}t'.format(mode)
super(CompressedFileHandler, self).__init__(
filename, mode=mode, encoding=encoding, delay=True) | 289,351 |
Do a wikipedia geo search for `latitude` and `longitude`
using HTTP API described in http://www.mediawiki.org/wiki/Extension:GeoData
Arguments:
* latitude (float or decimal.Decimal)
* longitude (float or decimal.Decimal)
Keyword arguments:
* title - The title of an article to search for
* results - th... | def geosearch(latitude, longitude, title=None, results=10, radius=1000):
search_params = {
'list': 'geosearch',
'gsradius': radius,
'gscoord': '{0}|{1}'.format(latitude, longitude),
'gslimit': results
}
if title:
search_params['titles'] = title
raw_results = _wiki_request(search_params)... | 289,650 |
Returns the Longest Subsequence between x and y.
Source: http://www.algorithmist.com/index.php/Longest_Common_Subsequence
Args:
x: sequence of words
y: sequence of words
Returns:
sequence: LCS of x and y | def _recon_lcs(x, y):
i, j = len(x), len(y)
table = _lcs(x, y)
def _recon(i, j):
if i == 0 or j == 0:
return []
elif x[i - 1] == y[j - 1]:
return _recon(i - 1, j - 1) + [(x[i - 1], i)]
elif table[i - 1, j] > table[i, j - 1]:
return _... | 290,226 |
Computes ROUGE-N of two text collections of sentences.
Sourece: http://research.microsoft.com/en-us/um/people/cyl/download/
papers/rouge-working-note-v1.3.1.pdf
Args:
evaluated_sentences: The sentences that have been picked by the summarizer
reference_sentences: The sentences from the referene ... | def rouge_n(evaluated_sentences, reference_sentences, n=2):
if len(evaluated_sentences) <= 0 or len(reference_sentences) <= 0:
raise ValueError("Collections must contain at least 1 sentence.")
evaluated_ngrams = _get_word_ngrams(n, evaluated_sentences)
reference_ngrams = _get_word_ngrams(n, re... | 290,227 |
Class method that will return a Droplet object by ID.
Args:
api_token (str): token
droplet_id (int): droplet id | def get_object(cls, api_token, droplet_id):
droplet = cls(token=api_token, id=droplet_id)
droplet.load()
return droplet | 291,113 |
Perform a droplet action.
Args:
params (dict): parameters of the action
Optional Args:
return_dict (bool): Return a dict when True (default),
otherwise return an Action.
Returns dict or Action | def _perform_action(self, params, return_dict=True):
action = self.get_data(
"droplets/%s/actions/" % self.id,
type=POST,
params=params
)
if return_dict:
return action
else:
action = action[u'action']
return... | 291,118 |
Resize the droplet to a new size slug.
https://developers.digitalocean.com/documentation/v2/#resize-a-droplet
Args:
new_size_slug (str): name of new size
Optional Args:
return_dict (bool): Return a dict when True (default),
otherwise retu... | def resize(self, new_size_slug, return_dict=True, disk=True):
options = {"type": "resize", "size": new_size_slug}
if disk: options["disk"] = "true"
return self._perform_action(options, return_dict) | 291,119 |
Take a snapshot!
Args:
snapshot_name (str): name of snapshot
Optional Args:
return_dict (bool): Return a dict when True (default),
otherwise return an Action.
power_off (bool): Before taking the snapshot the droplet will be
turned off... | def take_snapshot(self, snapshot_name, return_dict=True, power_off=False):
if power_off is True and self.status != "off":
action = self.power_off(return_dict=False)
action.wait()
self.load()
return self._perform_action(
{"type": "snapshot", "name... | 291,120 |
Restore the droplet to an image ( snapshot or backup )
Args:
image_id (int): id of image
Optional Args:
return_dict (bool): Return a dict when True (default),
otherwise return an Action.
Returns dict or Action | def rebuild(self, image_id=None, return_dict=True):
if not image_id:
image_id = self.image['id']
return self._perform_action(
{"type": "rebuild", "image": image_id},
return_dict
) | 291,121 |
Change the kernel to a new one
Args:
kernel : instance of digitalocean.Kernel.Kernel
Optional Args:
return_dict (bool): Return a dict when True (default),
otherwise return an Action.
Returns dict or Action | def change_kernel(self, kernel, return_dict=True):
if type(kernel) != Kernel:
raise BadKernelObject("Use Kernel object")
return self._perform_action(
{'type': 'change_kernel', 'kernel': kernel.id},
return_dict
) | 291,122 |
Returns a specific Action by its ID.
Args:
action_id (int): id of action | def get_action(self, action_id):
return Action.get_object(
api_token=self.token,
action_id=action_id
) | 291,126 |
Class method that will return a FloatingIP object by its IP.
Args:
api_token: str - token
ip: str - floating ip address | def get_object(cls, api_token, ip):
floating_ip = cls(token=api_token, ip=ip)
floating_ip.load()
return floating_ip | 291,139 |
Creates a FloatingIP and assigns it to a Droplet.
Note: Every argument and parameter given to this method will be
assigned to the object.
Args:
droplet_id: int - droplet id | def create(self, *args, **kwargs):
data = self.get_data('floating_ips/',
type=POST,
params={'droplet_id': self.droplet_id})
if data:
self.ip = data['floating_ip']['ip']
self.region = data['floating_ip']['region']... | 291,141 |
Creates a FloatingIP in a region without assigning
it to a specific Droplet.
Note: Every argument and parameter given to this method will be
assigned to the object.
Args:
region_slug: str - region's slug (e.g. 'nyc3') | def reserve(self, *args, **kwargs):
data = self.get_data('floating_ips/',
type=POST,
params={'region': self.region_slug})
if data:
self.ip = data['floating_ip']['ip']
self.region = data['floating_ip']['region']
... | 291,142 |
Assign a FloatingIP to a Droplet.
Args:
droplet_id: int - droplet id | def assign(self, droplet_id):
return self.get_data(
"floating_ips/%s/actions/" % self.ip,
type=POST,
params={"type": "assign", "droplet_id": droplet_id}
) | 291,143 |
Returns a Load Balancer object by its ID.
Args:
id (str): Load Balancer ID | def get_load_balancer(self, id):
return LoadBalancer.get_object(api_token=self.token, id=id) | 291,176 |
Returns a Certificate object by its ID.
Args:
id (str): Certificate ID | def get_certificate(self, id):
return Certificate.get_object(api_token=self.token, cert_id=id) | 291,177 |
Class method that will return a LoadBalancer object by its ID.
Args:
api_token (str): DigitalOcean API token
id (str): Load Balancer ID | def get_object(cls, api_token, id):
load_balancer = cls(token=api_token, id=id)
load_balancer.load()
return load_balancer | 291,191 |
Assign a LoadBalancer to a Droplet.
Args:
droplet_ids (obj:`list` of `int`): A list of Droplet IDs | def add_droplets(self, droplet_ids):
return self.get_data(
"load_balancers/%s/droplets/" % self.id,
type=POST,
params={"droplet_ids": droplet_ids}
) | 291,195 |
Unassign a LoadBalancer.
Args:
droplet_ids (obj:`list` of `int`): A list of Droplet IDs | def remove_droplets(self, droplet_ids):
return self.get_data(
"load_balancers/%s/droplets/" % self.id,
type=DELETE,
params={"droplet_ids": droplet_ids}
) | 291,196 |
Adds new forwarding rules to a LoadBalancer.
Args:
forwarding_rules (obj:`list`): A list of `ForwrdingRules` objects | def add_forwarding_rules(self, forwarding_rules):
rules_dict = [rule.__dict__ for rule in forwarding_rules]
return self.get_data(
"load_balancers/%s/forwarding_rules/" % self.id,
type=POST,
params={"forwarding_rules": rules_dict}
) | 291,197 |
Removes existing forwarding rules from a LoadBalancer.
Args:
forwarding_rules (obj:`list`): A list of `ForwrdingRules` objects | def remove_forwarding_rules(self, forwarding_rules):
rules_dict = [rule.__dict__ for rule in forwarding_rules]
return self.get_data(
"load_balancers/%s/forwarding_rules/" % self.id,
type=DELETE,
params={"forwarding_rules": rules_dict}
) | 291,198 |
Attach a Volume to a Droplet.
Args:
droplet_id: int - droplet id
region: string - slug identifier for the region | def attach(self, droplet_id, region):
return self.get_data(
"volumes/%s/actions/" % self.id,
type=POST,
params={"type": "attach",
"droplet_id": droplet_id,
"region": region}
) | 291,219 |
Detach a Volume to a Droplet.
Args:
size_gigabytes: int - size of the Block Storage volume in GiB
region: string - slug identifier for the region | def resize(self, size_gigabytes, region):
return self.get_data(
"volumes/%s/actions/" % self.id,
type=POST,
params={"type": "resize",
"size_gigabytes": size_gigabytes,
"region": region}
) | 291,220 |
Create a snapshot of the volume.
Args:
name: string - a human-readable name for the snapshot | def snapshot(self, name):
return self.get_data(
"volumes/%s/snapshots/" % self.id,
type=POST,
params={"name": name}
) | 291,221 |
Construct the analogy test set by mapping the words to their
word vector ids.
Arguments:
- test_examples: iterable of 4-word iterables
- dictionay: a mapping from words to ids
- boolean ignore_missing: if True, words in the test set
that are not in the dictionary
... | def construct_analogy_test_set(test_examples, dictionary, ignore_missing=False):
test = []
for example in test_examples:
try:
test.append([dictionary[word] for word in example])
except KeyError:
if ignore_missing:
pass
else:
... | 293,066 |
Estimate the word embeddings.
Parameters:
- scipy.sparse.coo_matrix matrix: coocurrence matrix
- int epochs: number of training epochs
- int no_threads: number of training threads
- bool verbose: print progress messages if True | def fit(self, matrix, epochs=5, no_threads=2, verbose=False):
shape = matrix.shape
if (len(shape) != 2 or
shape[0] != shape[1]):
raise Exception('Coocurrence matrix must be square')
if not sp.isspmatrix_coo(matrix):
raise Exception('Coocurrence mat... | 293,074 |
Scale the DNB data using a histogram equalization method.
Args:
dnb_data (ndarray): Day/Night Band data array
sza_data (ndarray): Solar Zenith Angle data array | def _run_dnb_normalization(self, dnb_data, sza_data):
# convert dask arrays to DataArray objects
dnb_data = xr.DataArray(dnb_data, dims=('y', 'x'))
sza_data = xr.DataArray(sza_data, dims=('y', 'x'))
good_mask = ~(dnb_data.isnull() | sza_data.isnull())
output_dataset = d... | 293,140 |
Scale the DNB data using a adaptive histogram equalization method.
Args:
dnb_data (ndarray): Day/Night Band data array
sza_data (ndarray): Solar Zenith Angle data array | def _run_dnb_normalization(self, dnb_data, sza_data):
# convert dask arrays to DataArray objects
dnb_data = xr.DataArray(dnb_data, dims=('y', 'x'))
sza_data = xr.DataArray(sza_data, dims=('y', 'x'))
good_mask = ~(dnb_data.isnull() | sza_data.isnull())
# good_mask = ~(dn... | 293,143 |
Evaluate a Chebyshev Polynomial
Args:
coefs (list, np.array): Coefficients defining the polynomial
time (int, float): Time where to evaluate the polynomial
domain (list, tuple): Domain (or time interval) for which the polynomial is defined: [left, right]
Reference: Appendix A in the MS... | def chebyshev(coefs, time, domain):
return Chebyshev(coefs, domain=domain)(time) - 0.5 * coefs[0] | 293,181 |
Filer provided key iterable by the provided `DatasetID`.
Note: The `modifiers` attribute of `did` should be `None` to allow for
**any** modifier in the results.
Args:
did (DatasetID): Query parameters to match in the `key_container`.
key_container (iterable): Set, list, tuple, or dic... | def filter_keys_by_dataset_id(did, key_container):
keys = iter(key_container)
for key in DATASET_KEYS:
if getattr(did, key) is not None:
if key == "wavelength":
keys = [k for k in keys
if (getattr(k, key) is not None and
... | 293,205 |
Generator of reader configuration files for one or more readers
Args:
reader (Optional[str]): Yield configs only for this reader
ppp_config_dir (Optional[str]): Additional configuration directory
to search for reader configuration files.
Returns: Generator of lists of configuration... | def configs_for_reader(reader=None, ppp_config_dir=None):
search_paths = (ppp_config_dir,) if ppp_config_dir else tuple()
if reader is not None:
if not isinstance(reader, (list, tuple)):
reader = [reader]
# check for old reader names
new_readers = []
for reader_n... | 293,209 |
Available readers based on current configuration.
Args:
as_dict (bool): Optionally return reader information as a dictionary.
Default: False
Returns: List of available reader names. If `as_dict` is `True` then
a list of dictionaries including additionally reader in... | def available_readers(as_dict=False):
readers = []
for reader_configs in configs_for_reader():
try:
reader_info = read_reader_config(reader_configs)
except (KeyError, IOError, yaml.YAMLError):
LOG.warning("Could not import reader config from: %s", reader_configs)
... | 293,210 |
Collect custom configuration values.
Args:
max_sza (float): Maximum solar zenith angle in degrees that is
considered valid and correctable. Default 95.0. | def __init__(self, max_sza=95.0, **kwargs):
self.max_sza = max_sza
self.max_sza_cos = np.cos(np.deg2rad(max_sza)) if max_sza is not None else None
super(SunZenithCorrectorBase, self).__init__(**kwargs) | 293,237 |
Collect custom configuration values.
Args:
correction_limit (float): Maximum solar zenith angle to apply the
correction in degrees. Pixels beyond this limit have a
constant correction applied. Default 88.
max_sza (float): Maximum solar zenith angle in deg... | def __init__(self, correction_limit=88., **kwargs):
self.correction_limit = correction_limit
super(SunZenithCorrector, self).__init__(**kwargs) | 293,239 |
Collect custom configuration values.
Args:
correction_limit (float): Maximum solar zenith angle to apply the
correction in degrees. Pixels beyond this limit have a
constant correction applied. Default 88.
max_sza (float): Maximum solar zenith angle in deg... | def __init__(self, correction_limit=88., **kwargs):
self.correction_limit = correction_limit
super(EffectiveSolarPathLengthCorrector, self).__init__(**kwargs) | 293,241 |
Collect custom configuration values.
Args:
common_channel_mask (bool): If True, mask all the channels with
a mask that combines all the invalid areas of the given data. | def __init__(self, name, common_channel_mask=True, **kwargs):
self.common_channel_mask = common_channel_mask
super(GenericCompositor, self).__init__(name, **kwargs) | 293,250 |
Collect custom configuration values.
Args:
lim_low (float): lower limit of Sun zenith angle for the
blending of the given channels
lim_high (float): upper limit of Sun zenith angle for the
blending of the given channels | def __init__(self, name, lim_low=85., lim_high=95., **kwargs):
self.lim_low = lim_low
self.lim_high = lim_high
super(DayNightCompositor, self).__init__(name, **kwargs) | 293,260 |
Collect custom configuration values.
Args:
transition_min (float): Values below or equal to this are
clouds -> opaque white
transition_max (float): Values above this are
cloud free -> transparent
transit... | def __init__(self, name, transition_min=258.15, transition_max=298.15,
transition_gamma=3.0, **kwargs):
self.transition_min = transition_min
self.transition_max = transition_max
self.transition_gamma = transition_gamma
super(CloudCompositor, self).__init__(name,... | 293,264 |
Initialize resampler with geolocation information.
Args:
source_geo_def (SwathDefinition, AreaDefinition):
Geolocation definition for the data to be resampled
target_geo_def (CoordinateDefinition, AreaDefinition):
Geolocation definition for the area to re... | def __init__(self, source_geo_def, target_geo_def):
self.source_geo_def = source_geo_def
self.target_geo_def = target_geo_def | 293,280 |
Generator of writer configuration files for one or more writers
Args:
writer (Optional[str]): Yield configs only for this writer
ppp_config_dir (Optional[str]): Additional configuration directory
to search for writer configuration files.
Returns: Generator of lists of configuration... | def configs_for_writer(writer=None, ppp_config_dir=None):
search_paths = (ppp_config_dir,) if ppp_config_dir else tuple()
if writer is not None:
if not isinstance(writer, (list, tuple)):
writer = [writer]
# given a config filename or writer name
config_files = [w if w.en... | 293,369 |
Available writers based on current configuration.
Args:
as_dict (bool): Optionally return writer information as a dictionary.
Default: False
Returns: List of available writer names. If `as_dict` is `True` then
a list of dictionaries including additionally writer in... | def available_writers(as_dict=False):
writers = []
for writer_configs in configs_for_writer():
try:
writer_info = read_writer_config(writer_configs)
except (KeyError, IOError, yaml.YAMLError):
LOG.warning("Could not import writer config from: %s", writer_configs)
... | 293,370 |
convert ``dataset`` into a :class:`~trollimage.xrimage.XRImage` instance.
Convert the ``dataset`` into an instance of the
:class:`~trollimage.xrimage.XRImage` class. This function makes no other
changes. To get an enhanced image, possibly with overlays and decoration,
see :func:`~get_enhanced_image`.... | def to_image(dataset):
dataset = dataset.squeeze()
if dataset.ndim < 2:
raise ValueError("Need at least a 2D array to make an image.")
else:
return XRImage(dataset) | 293,377 |
Compute all the given dask graphs `results` so that the files are
saved.
Args:
results (iterable): Iterable of dask graphs resulting from calls to
`scn.save_datasets(..., compute=False)` | def compute_writer_results(results):
if not results:
return
sources, targets, delayeds = split_results(results)
# one or more writers have targets that we need to close in the future
if targets:
delayeds.append(da.store(sources, targets, compute=False))
if delayeds:
d... | 293,379 |
Create a filename where output data will be saved.
Args:
kwargs (dict): Attributes and other metadata to use for formatting
the previously provided `filename`. | def get_filename(self, **kwargs):
if self.filename_parser is None:
raise RuntimeError("No filename pattern or specific filename provided")
output_filename = self.filename_parser.compose(kwargs)
dirname = os.path.dirname(output_filename)
if dirname and not os.path.isd... | 293,383 |
Initialize an Enhancer instance.
Args:
ppp_config_dir: Points to the base configuration directory
enhancement_config_file: The enhancement configuration to apply, False to leave as is. | def __init__(self, ppp_config_dir=None, enhancement_config_file=None):
self.ppp_config_dir = ppp_config_dir or get_environ_config_dir()
self.enhancement_config_file = enhancement_config_file
# Set enhancement_config_file to False for no enhancements
if self.enhancement_config_fi... | 293,398 |
Check the satpy readers and writers for correct installation.
Args:
readers (list or None): Limit readers checked to those specified
writers (list or None): Limit writers checked to those specified
extras (list or None): Limit extras checked to those specified
Returns: bool
Tru... | def check_satpy(readers=None, writers=None, extras=None):
from satpy.readers import configs_for_reader
from satpy.writers import configs_for_writer
print('Readers')
print('=======')
for reader, res in sorted(check_yaml_configs(configs_for_reader(reader=readers), 'reader').items()):
pri... | 293,493 |
Make sure sensor and platform are consistent
Args:
sensor (str) : Sensor name from YAML dataset definition
Raises:
ValueError if they don't match | def _check_sensor_platform_consistency(self, sensor):
ref_sensor = SENSORS.get(self.platform, None)
if ref_sensor and not sensor == ref_sensor:
logger.error('Sensor-Platform mismatch: {} is not a payload '
'of {}. Did you choose the correct reader?'
... | 293,564 |
Get dataset function
Args:
dsid: Dataset ID
param2: Dataset Information
Returns:
Dask DataArray: Data | def get_dataset(self, dsid, dsinfo):
data = self[dsinfo.get('file_key', dsid.name)]
data.attrs.update(dsinfo)
data.attrs["platform_name"] = self['/attr/satellite_name']
data.attrs["sensor"] = self['/attr/instrument_name']
return data | 293,635 |
Makes sure filepath is valid and then reads data into a Dask DataFrame
Args:
filename: Filename
filename_info: Filename information
filetype_info: Filetype information | def __init__(self, filename, filename_info, filetype_info):
super(VIIRSActiveFiresTextFileHandler, self).__init__(filename, filename_info, filetype_info)
if not os.path.isfile(filename):
return
self.file_content = dd.read_csv(filename, skiprows=15, header=None,
... | 293,636 |
Convert an `numpy.string_` to str.
Args:
value (ndarray): scalar or 1-element numpy array to convert
Raises:
ValueError: if value is array larger than 1-element or it is not of
type `numpy.string_` or it is not a numpy array | def np2str(value):
if hasattr(value, 'dtype') and \
issubclass(value.dtype.type, (np.string_, np.object_)) and value.size == 1:
value = np.asscalar(value)
if not isinstance(value, str):
# python 3 - was scalar numpy array of bytes
# otherwise python 2 - scala... | 293,638 |
Compute a mask of the earth's shape as seen by a geostationary satellite
Args:
area (pyresample.geometry.AreaDefinition) : Corresponding area
definition
Returns:
Boolean mask, True inside the earth's shape, False outside. | def get_geostationary_mask(area):
# Compute projection coordinates at the earth's limb
h = area.proj_dict['h']
xmax, ymax = get_geostationary_angle_extent(area)
xmax *= h
ymax *= h
# Compute projection coordinates at the centre of each pixel
x, y = area.get_proj_coords_dask()
# Co... | 293,640 |
Get the bbox in lon/lats of the valid pixels inside *geos_area*.
Args:
nb_points: Number of points on the polygon | def get_geostationary_bounding_box(geos_area, nb_points=50):
xmax, ymax = get_geostationary_angle_extent(geos_area)
# generate points around the north hemisphere in satellite projection
# make it a bit smaller so that we stay inside the valid area
x = np.cos(np.linspace(-np.pi, 0, nb_points / 2)) ... | 293,642 |
Create a copy of the Scene including dependency information.
Args:
datasets (list, tuple): `DatasetID` objects for the datasets
to include in the new Scene object. | def copy(self, datasets=None):
new_scn = self.__class__()
new_scn.attrs = self.attrs.copy()
new_scn.dep_tree = self.dep_tree.copy()
for ds_id in (datasets or self.keys()):
# NOTE: Must use `.datasets` or side effects of `__setitem__`
# could hurt u... | 293,662 |
Collect all composite prereqs and create the specified composite.
Args:
comp_node (Node): Composite Node to generate a Dataset for
keepables (set): `set` to update if any datasets are needed
when generation is continued later. This can
... | def _generate_composite(self, comp_node, keepables):
if comp_node.name in self.datasets:
# already loaded
return
compositor, prereqs, optional_prereqs = comp_node.data
try:
prereq_datasets = self._get_prereq_datasets(
comp_node.name,
... | 293,675 |
Load datasets from the necessary reader.
Args:
nodes (iterable): DependencyTree Node objects
**kwargs: Keyword arguments to pass to the reader's `load` method.
Returns:
DatasetDict of loaded datasets | def read(self, nodes=None, **kwargs):
if nodes is None:
required_nodes = self.wishlist - set(self.datasets.keys())
nodes = self.dep_tree.leaves(nodes=required_nodes)
return self._read_datasets(nodes, **kwargs) | 293,677 |
Unload all unneeded datasets.
Datasets are considered unneeded if they weren't directly requested
or added to the Scene by the user or they are no longer needed to
generate composites that have yet to be generated.
Args:
keepables (iterable): DatasetIDs to keep whether they... | def unload(self, keepables=None):
to_del = [ds_id for ds_id, projectable in self.datasets.items()
if ds_id not in self.wishlist and (not keepables or ds_id
not in keepables)]
for ds_id in to_del:
LOG.debug("Unloa... | 293,680 |
Merge all xr.DataArrays of a scene to a xr.DataSet.
Parameters:
datasets (list):
List of products to include in the :class:`xarray.Dataset`
Returns: :class:`xarray.Dataset` | def to_xarray_dataset(self, datasets=None):
if datasets is not None:
datasets = [self[ds] for ds in datasets]
else:
datasets = [self.datasets.get(ds) for ds in self.wishlist]
datasets = [ds for ds in datasets if ds is not None]
ds_dict = {i.attrs['na... | 293,687 |
Obtain GCPs and construct latitude and longitude arrays.
Args:
band (gdal band): Measurement band which comes with GCP's
array_shape (tuple) : The size of the data array
Returns:
coordinates (tuple): A tuple with longitude and latitude arrays | def get_lonlatalts(self):
band = self.filehandle
(xpoints, ypoints), (gcp_lons, gcp_lats, gcp_alts), (gcps, crs) = self.get_gcps()
# FIXME: do interpolation on cartesion coordinates if the area is
# problematic.
longitudes = interpolate_xarray(xpoints, ypoints, gcp_lo... | 293,706 |
Read GCP from the GDAL band.
Args:
band (gdal band): Measurement band which comes with GCP's
coordinates (tuple): A tuple with longitude and latitude arrays
Returns:
points (tuple): Pixel and Line indices 1d arrays
gcp_coords (tuple): longitude and latitude ... | def get_gcps(self):
gcps = self.filehandle.gcps
gcp_array = np.array([(p.row, p.col, p.x, p.y, p.z) for p in gcps[0]])
ypoints = np.unique(gcp_array[:, 0])
xpoints = np.unique(gcp_array[:, 1])
gcp_lons = gcp_array[:, 2].reshape(ypoints.shape[0], xpoints.shape[0])
... | 293,707 |
Initialize file reader and adjust geolocation preferences.
Args:
config_files (iterable): yaml config files passed to base class
use_tc (boolean): If `True` use the terrain corrected
files. If `False`, switch to non-TC files. If
... | def __init__(self, config_files, use_tc=None, **kwargs):
super(VIIRSSDRReader, self).__init__(config_files, **kwargs)
self.use_tc = use_tc | 293,728 |
Flatten tree structure to a one level dictionary.
Args:
d (dict, optional): output dictionary to update
Returns:
dict: Node.name -> Node. The returned dictionary includes the
current Node and all its children. | def flatten(self, d=None):
if d is None:
d = {}
if self.name is not None:
d[self.name] = self
for child in self.children:
child.flatten(d=d)
return d | 293,749 |
Get the leaves of the tree starting at this root.
Args:
nodes (iterable): limit leaves for these node names
unique: only include individual leaf nodes once
Returns:
list of leaf nodes | def leaves(self, nodes=None, unique=True):
if nodes is None:
return super(DependencyTree, self).leaves(unique=unique)
res = list()
for child_id in nodes:
for sub_child in self._all_nodes[child_id].leaves(unique=unique):
if not unique or sub_child... | 293,756 |
Find the dependencies for *dataset_key*.
Args:
dataset_key (str, float, DatasetID): Dataset identifier to locate
and find any additional
dependencies for.
**dfilter (dict): Additional filte... | def _find_dependencies(self, dataset_key, **dfilter):
# 0 check if the *exact* dataset is already loaded
try:
node = self.getitem(dataset_key)
LOG.trace("Found exact dataset already loaded: {}".format(node.name))
return node, set()
except KeyError:
... | 293,766 |
Create the dependency tree.
Args:
dataset_keys (iterable): Strings or DatasetIDs to find dependencies for
**dfilter (dict): Additional filter parameters. See
`satpy.readers.get_key` for more details.
Returns:
(Node, set): Root node of t... | def find_dependencies(self, dataset_keys, **dfilter):
unknown_datasets = set()
for key in dataset_keys.copy():
n, unknowns = self._find_dependencies(key, **dfilter)
dataset_keys.discard(key) # remove old non-DatasetID
if n is not None:
datas... | 293,767 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.