INSTRUCTION stringlengths 1 46.3k | RESPONSE stringlengths 75 80.2k |
|---|---|
Helper function to generate a single row of a price table.
Args:
header: A str containing the header text of this row.
description: A str description of this row in the price table.
final_url: A str containing the final URL after all cross domain redirects.
price_in_micros: An int indicating the pric... | def CreatePriceTableRow(header, description, final_url, price_in_micros,
currency_code, price_unit, final_mobile_url=None):
"""Helper function to generate a single row of a price table.
Args:
header: A str containing the header text of this row.
description: A str description of thi... |
Creates a bidding strategy object.
Args:
client: AdWordsClient the client to run the example with.
Returns:
dict An object representing a bidding strategy. | def CreateBiddingStrategy(client):
"""Creates a bidding strategy object.
Args:
client: AdWordsClient the client to run the example with.
Returns:
dict An object representing a bidding strategy.
"""
# Initialize appropriate service.
bidding_strategy_service = client.GetService(
'BiddingStrate... |
Creates an explicit budget to be used only to create the Campaign.
Args:
client: AdWordsClient the client to run the example with.
Returns:
dict An object representing a shared budget. | def CreateSharedBudget(client):
"""Creates an explicit budget to be used only to create the Campaign.
Args:
client: AdWordsClient the client to run the example with.
Returns:
dict An object representing a shared budget.
"""
# Initialize appropriate service.
budget_service = client.GetService('Budg... |
Create a Campaign with a Shared Bidding Strategy.
Args:
client: AdWordsClient the client to run the example with.
bidding_strategy_id: string the bidding strategy ID to use.
budget_id: string the shared budget ID to use.
Returns:
dict An object representing a campaign. | def CreateCampaignWithBiddingStrategy(client, bidding_strategy_id, budget_id):
"""Create a Campaign with a Shared Bidding Strategy.
Args:
client: AdWordsClient the client to run the example with.
bidding_strategy_id: string the bidding strategy ID to use.
budget_id: string the shared budget ID to use.
... |
Helper function used by ReportWorker to download customer report.
Note that multiprocessing differs between Windows / Unix environments. A
Process or its subclasses in Windows must be serializable with pickle, but
that is not possible for AdWordsClient or ReportDownloader. This top-level
function is used as a ... | def _DownloadReport(process_id, report_download_directory, customer_id,
report_definition):
"""Helper function used by ReportWorker to download customer report.
Note that multiprocessing differs between Windows / Unix environments. A
Process or its subclasses in Windows must be serializable w... |
Retrieves all CustomerIds in the account hierarchy.
Note that your configuration file must specify a client_customer_id belonging
to an AdWords manager account.
Args:
client: an AdWordsClient instance.
Raises:
Exception: if no CustomerIds could be found.
Returns:
A Queue instance containing all ... | def GetCustomerIDs(client):
"""Retrieves all CustomerIds in the account hierarchy.
Note that your configuration file must specify a client_customer_id belonging
to an AdWords manager account.
Args:
client: an AdWordsClient instance.
Raises:
Exception: if no CustomerIds could be found.
Returns:
... |
Handle get request. | def get(self):
"""Handle get request."""
client_customer_id = self.request.get('clientCustomerId')
template_values = {
'back_url': '/showAccounts',
'back_msg': 'View Accounts.',
'ccid': client_customer_id,
'logout_url': users.create_logout_url('/'),
'user_nickname': ... |
Handle post request. | def post(self):
"""Handle post request."""
client_customer_id = self.request.get('clientCustomerId')
if not client_customer_id:
self.redirect('/')
else:
self.redirect('/showCampaigns?clientCustomerId=%s' % client_customer_id) |
Creates a dynamic remarketing campaign.
Args:
client: an AdWordsClient instance.
campaign_id: an int campaign ID.
Returns:
The ad group that was successfully created. | def CreateAdGroup(client, campaign_id):
"""Creates a dynamic remarketing campaign.
Args:
client: an AdWordsClient instance.
campaign_id: an int campaign ID.
Returns:
The ad group that was successfully created.
"""
ad_group_service = client.GetService('AdGroupService', 'v201809')
ad_group = {
... |
Creates a ResponsiveDisplayAd.
Args:
client: an AdWordsClient instance.
opener: an OpenerDirector instance.
ad_group_id: an int ad group ID.
Returns:
The ad group ad that was successfully created. | def CreateAd(client, opener, ad_group_id):
"""Creates a ResponsiveDisplayAd.
Args:
client: an AdWordsClient instance.
opener: an OpenerDirector instance.
ad_group_id: an int ad group ID.
Returns:
The ad group ad that was successfully created.
"""
ad_group_ad_service = client.GetService('AdGr... |
Links the provided ad group and user list.
Args:
client: an AdWordsClient instance.
ad_group_id: an int ad group ID.
user_list_id: an int user list ID.
Returns:
The ad group criterion that was successfully created. | def AttachUserList(client, ad_group_id, user_list_id):
"""Links the provided ad group and user list.
Args:
client: an AdWordsClient instance.
ad_group_id: an int ad group ID.
user_list_id: an int user list ID.
Returns:
The ad group criterion that was successfully created.
"""
ad_group_criter... |
Creates dynamic display ad settings.
Args:
client: an AdWordsClient instance.
opener: an OpenerDirector instance.
Returns:
A dict containing the dynamic display ad settings. | def CreateDynamicDisplayAdSettings(client, opener):
"""Creates dynamic display ad settings.
Args:
client: an AdWordsClient instance.
opener: an OpenerDirector instance.
Returns:
A dict containing the dynamic display ad settings.
"""
media_service = client.GetService('MediaService', 'v201809')
... |
Retrieves the scope for the given API name.
Args:
api_name: A string identifying the name of the API we want to retrieve a
scope for.
Returns:
A string that is the scope for the given API name.
Raises:
GoogleAdsValueError: If the given api_name is invalid; accepted values are
"adwor... | def GetAPIScope(api_name):
"""Retrieves the scope for the given API name.
Args:
api_name: A string identifying the name of the API we want to retrieve a
scope for.
Returns:
A string that is the scope for the given API name.
Raises:
GoogleAdsValueError: If the given api_name is invalid; ac... |
Creates an OAuth2 HTTP header.
The OAuth2 credentials will be refreshed as necessary. In the event that
the credentials fail to refresh, a message is logged but no exception is
raised.
Returns:
A dictionary containing one entry: the OAuth2 Bearer header under the
'Authorization' key.
... | def CreateHttpHeader(self):
"""Creates an OAuth2 HTTP header.
The OAuth2 credentials will be refreshed as necessary. In the event that
the credentials fail to refresh, a message is logged but no exception is
raised.
Returns:
A dictionary containing one entry: the OAuth2 Bearer header under t... |
Creates an OAuth2 HTTP header.
The OAuth2 credentials will be refreshed as necessary. In the event that
the credentials fail to refresh, a message is logged but no exception is
raised.
Returns:
A dictionary containing one entry: the OAuth2 Bearer header under the
'Authorization' key.
... | def CreateHttpHeader(self):
"""Creates an OAuth2 HTTP header.
The OAuth2 credentials will be refreshed as necessary. In the event that
the credentials fail to refresh, a message is logged but no exception is
raised.
Returns:
A dictionary containing one entry: the OAuth2 Bearer header under t... |
Uses the Refresh Token to retrieve and set a new Access Token.
Raises:
google.auth.exceptions.RefreshError: If the refresh fails. | def Refresh(self):
"""Uses the Refresh Token to retrieve and set a new Access Token.
Raises:
google.auth.exceptions.RefreshError: If the refresh fails.
"""
with requests.Session() as session:
session.proxies = self.proxy_config.proxies
session.verify = not self.proxy_config.disable_ce... |
Creates the feed for DSA page URLs.
Args:
client: an AdWordsClient instance.
Returns:
A _DSAFeedDetails instance containing details about the created feed. | def _CreateFeed(client):
"""Creates the feed for DSA page URLs.
Args:
client: an AdWordsClient instance.
Returns:
A _DSAFeedDetails instance containing details about the created feed.
"""
# Get the FeedService.
feed_service = client.GetService('FeedService', version='v201809')
# Create operatio... |
Creates the feed mapping for DSA page feeds.
Args:
client: an AdWordsClient instance.
feed_details: a _DSAFeedDetails instance. | def _CreateFeedMapping(client, feed_details):
"""Creates the feed mapping for DSA page feeds.
Args:
client: an AdWordsClient instance.
feed_details: a _DSAFeedDetails instance.
"""
# Get the FeedMappingService.
feed_mapping_service = client.GetService('FeedMappingService',
... |
Creates the page URLs in the DSA page feed.
Args:
client: an AdWordsClient instance.
feed_details: a _DSAFeedDetails instance.
label_name: a str containing the page feed URL label. | def _CreateFeedItems(client, feed_details, label_name):
"""Creates the page URLs in the DSA page feed.
Args:
client: an AdWordsClient instance.
feed_details: a _DSAFeedDetails instance.
label_name: a str containing the page feed URL label.
"""
# Get the FeedItemService.
feed_item_service = client... |
Updates the campaign DSA setting to DSA pagefeeds.
Args:
client: an AdWordsClient instance.
campaign_id: a str Campaign ID.
feed_id: a str page Feed ID.
Raises:
ValueError: If the given campaign is found not to be a dynamic search ad
campaign. | def _UpdateCampaignDSASetting(client, campaign_id, feed_id):
"""Updates the campaign DSA setting to DSA pagefeeds.
Args:
client: an AdWordsClient instance.
campaign_id: a str Campaign ID.
feed_id: a str page Feed ID.
Raises:
ValueError: If the given campaign is found not to be a dynamic search a... |
Set custom targeting for the page feed URLs based on a list of labels.
Args:
client: an AdWordsClient instance.
ad_group_id: a str AdGroup ID.
label_name: a str label name.
Returns:
A suds.sudsobject.Object representing the newly created webpage criterion. | def _AddDSATargeting(client, ad_group_id, label_name):
"""Set custom targeting for the page feed URLs based on a list of labels.
Args:
client: an AdWordsClient instance.
ad_group_id: a str AdGroup ID.
label_name: a str label name.
Returns:
A suds.sudsobject.Object representing the newly created ... |
returns a value calculated from bits
:param length: length of signal in bits
:param is_float: value is float
:param bits: value as bits (array/iterable)
:param is_signed: value is signed
:return: | def unpack_bitstring(length, is_float, is_signed, bits):
# type: (int, bool, bool, typing.Any) -> typing.Union[float, int]
"""
returns a value calculated from bits
:param length: length of signal in bits
:param is_float: value is float
:param bits: value as bits (array/iterable)
:param is_si... |
returns a value in bits
:param length: length of signal in bits
:param is_float: value is float
:param value: value to encode
:param signed: value is signed
:return: | def pack_bitstring(length, is_float, value, signed):
"""
returns a value in bits
:param length: length of signal in bits
:param is_float: value is float
:param value: value to encode
:param signed: value is signed
:return:
"""
if is_float:
types = {
32: '>f',
... |
Set Definition default value.
:param default: default value; number, str or quoted str ("value") | def set_default(self, default): # type: (typing.Any) -> None
"""Set Definition default value.
:param default: default value; number, str or quoted str ("value")
"""
if default is not None and len(default) > 1 and default[0] == '"' and default[-1] == '"':
default = default[1... |
Get signal arxml-type and size based on the Signal properties. | def get_base_type_of_signal(signal):
# type: (canmatrix.Signal) -> typing.Tuple[str, int]
"""Get signal arxml-type and size based on the Signal properties."""
if signal.is_float:
if signal.size > 32:
create_type = "double"
size = 64
else:
create_type = "si... |
Parse the xml tree into ArTree objects. | def fill_tree_from_xml(tag, ar_tree, namespace):
# type: (_Element, ArTree, str) -> None
"""Parse the xml tree into ArTree objects."""
for child in tag: # type: _Element
name_elem = child.find('./' + namespace + 'SHORT-NAME')
# long_name = child.find('./' + namespace + 'LONG-NAME')
... |
Get path in translation-dictionary. | def ar_path_to_x_path(ar_path, dest_element=None):
# type: (str, typing.Optional[str]) -> str
"""Get path in translation-dictionary."""
ar_path_elements = ar_path.strip('/').split('/')
xpath = "."
for element in ar_path_elements[:-1]:
xpath += "//A:SHORT-NAME[text()='" + element + "']/.."
... |
Find sub-element of given path with given short name. | def get_element_by_path(tree, path_and_name, namespace):
# type: (_Element, str, str) -> typing.Union[_Element, None]
"""Find sub-element of given path with given short name."""
global xml_element_cache
namespace_map = {'A': namespace[1:-1]}
base_path, element_name = path_and_name.rsplit('/', 1)
... |
Get element from ArTree by path. | def get_cached_element_by_path(data_tree, path):
# type: (ArTree, str) -> typing.Optional[_Element]
"""Get element from ArTree by path."""
if not isinstance(data_tree, ArTree):
logger.warning("%s not called with ArTree, return None", get_cached_element_by_path.__name__)
return None
ptr =... |
Get first sub-child or referenced sub-child with given name. | def get_child(parent, tag_name, root_or_cache, namespace):
# type: (_Element, str, _DocRoot, str) -> typing.Optional[_Element]
"""Get first sub-child or referenced sub-child with given name."""
# logger.debug("get_child: " + tag_name)
if parent is None:
return None
ret = parent.find('.//' + ... |
Get element short name. | def get_element_name(parent, ns):
# type: (_Element, str) -> str
"""Get element short name."""
name = parent.find('./' + ns + 'SHORT-NAME')
if name is not None and name.text is not None:
return name.text
return "" |
Add signals from xml to the Frame. | def get_signals(signal_array, frame, root_or_cache, ns, multiplex_id, float_factory):
# type: (typing.Sequence[_Element], canmatrix.Frame, _DocRoot, str, _MultiplexId, typing.Callable) -> None
"""Add signals from xml to the Frame."""
global signal_rxs
group_id = 1
if signal_array is None: # Empty s... |
Get element description from XML. | def get_element_desc(element, ar_tree, ns):
# type: (_Element, _DocRoot, str) -> str
"""Get element description from XML."""
desc = get_child(element, "DESC", ar_tree, ns)
txt = get_child(desc, 'L-2[@L="DE"]', ar_tree, ns)
if txt is None:
txt = get_child(desc, 'L-2[@L="EN"]', ar_tree, ns)
... |
Extract signal from ECUc file. | def ecuc_extract_signal(signal_node, ns):
# type: (_Element, str) -> canmatrix.Signal
"""Extract signal from ECUc file."""
attributes = signal_node.findall(".//" + ns + "DEFINITION-REF") # type: typing.Sequence[_Element]
start_bit = None
size = 0
is_little = False
# endianness = None
# ... |
Append new child and return it. | def append_child(self, name, child): # type: (str, typing.Any) -> ArTree
"""Append new child and return it."""
temp = ArTree(name, child)
self._array.append(temp)
return temp |
Setup the root logger. Return the logger instance for possible further setting and use.
To be used from CLI scripts only. | def setup_logger(): # type: () -> logging.Logger
"""Setup the root logger. Return the logger instance for possible further setting and use.
To be used from CLI scripts only.
"""
formatter = logging.Formatter(
fmt='%(levelname)s - %(module)s - %(message)s')
handler = logging.StreamHandler(... |
Dynamic reconfiguration of the log level | def set_log_level(logger, level): # type: (logging.Logger, int) -> None
"""Dynamic reconfiguration of the log level"""
if level > 2:
level = 2
if level < -1:
level = -1
levels = {
-1: logging.ERROR,
0: logging.WARN,
1: logging.INFO,
2: logging.DEBUG
... |
export canmatrix-object as .sym file (compatible to PEAK-Systems) | def dump(db, f, **options): # type: (canmatrix.CanMatrix, typing.IO, **typing.Any) -> None
"""
export canmatrix-object as .sym file (compatible to PEAK-Systems)
"""
global enum_dict
global enums
sym_encoding = options.get('symExportEncoding', 'iso-8859-1')
enum_dict = {}
enums = "{ENUM... |
Get all PGN values for given frame.
:param db: CanMatrix database
:return: tuple of [pgn] and [arbitration_id] | def list_pgn(db):
# type: (canmatrix.CanMatrix) -> typing.Tuple[typing.List[int], typing.List[canmatrix.ArbitrationId]]
"""
Get all PGN values for given frame.
:param db: CanMatrix database
:return: tuple of [pgn] and [arbitration_id]
"""
id_list = [x.arbitration_id for x in db.frames]
... |
Yield arbitration ids which has the same pgn. | def ids_sharing_same_pgn(id_x, pgn_x, id_y, pgn_y):
# type: (typing.Sequence[canmatrix.ArbitrationId], typing.Sequence[int], typing.Sequence[canmatrix.ArbitrationId], typing.Sequence[int]) -> typing.Iterable[typing.Tuple[canmatrix.ArbitrationId, canmatrix.ArbitrationId]]
"""Yield arbitration ids which has the s... |
Get string value for common strings.
Method is far from complete but helping with odd arxml files.
:param text_value: value in text like "true"
:return: string for value like "1" | def guess_value(text_value): # type: (str) -> str
"""
Get string value for common strings.
Method is far from complete but helping with odd arxml files.
:param text_value: value in text like "true"
:return: string for value like "1"
"""
if sys.version_info >= (3, 0):
text_value = t... |
Create, populate and return the VersioneerConfig() object. | def get_config():
"""Create, populate and return the VersioneerConfig() object."""
# these strings are filled in when 'setup.py versioneer' creates
# _version.py
cfg = VersioneerConfig()
cfg.VCS = "git"
cfg.style = "pep440-post"
cfg.tag_prefix = ""
cfg.parentdir_prefix = "None"
cfg.v... |
Decorator to mark a method as the handler for a particular VCS. | def register_vcs_handler(vcs, method): # tyoe: (str, str) -> typing.Callable # decorator
"""Decorator to mark a method as the handler for a particular VCS."""
def decorate(f):
"""Store f in HANDLERS[vcs][method]."""
if vcs not in HANDLERS:
HANDLERS[vcs] = {}
HANDLERS[vcs][m... |
Get version from 'git describe' in the root of the source tree.
This only gets called if the git-archive 'subst' keywords were *not*
expanded, and _version.py hasn't already been rewritten with a short
version string, meaning we're inside a checked out source tree. | def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command):
"""Get version from 'git describe' in the root of the source tree.
This only gets called if the git-archive 'subst' keywords were *not*
expanded, and _version.py hasn't already been rewritten with a short
version string, meani... |
Get version information or return default if unable to do so. | def get_versions():
"""Get version information or return default if unable to do so."""
# I am in _version.py, which lives at ROOT/VERSIONFILE_SOURCE. If we have
# __file__, we can work backwards from there to the root. Some
# py2exe/bbfreeze/non-CPython implementations don't do __file__, in which
#... |
Copy ECU(s) identified by Name or as Object from source CAN matrix to target CAN matrix.
This function additionally copy all relevant Defines.
:param ecu_or_glob: Ecu instance or glob pattern for Ecu name
:param source_db: Source CAN matrix
:param target_db: Destination CAN matrix | def copy_ecu(ecu_or_glob, source_db, target_db):
# type: (typing.Union[cm.Ecu, str], cm.CanMatrix, cm.CanMatrix) -> None
"""
Copy ECU(s) identified by Name or as Object from source CAN matrix to target CAN matrix.
This function additionally copy all relevant Defines.
:param ecu_or_glob: Ecu instanc... |
Copy ECU(s) identified by Name or as Object from source CAN matrix to target CAN matrix.
This function additionally copy all relevant Frames and Defines.
:param ecu_or_glob: Ecu instance or glob pattern for Ecu name
:param source_db: Source CAN matrix
:param target_db: Destination CAN matrix | def copy_ecu_with_frames(ecu_or_glob, source_db, target_db):
# type: (typing.Union[cm.Ecu, str], cm.CanMatrix, cm.CanMatrix) -> None
"""
Copy ECU(s) identified by Name or as Object from source CAN matrix to target CAN matrix.
This function additionally copy all relevant Frames and Defines.
:param e... |
Copy Signals identified by name from source CAN matrix to target CAN matrix.
In target CanMatrix the signal is put without frame, just on top level.
:param signal_glob: Signal glob pattern
:param source_db: Source CAN matrix
:param target_db: Destination CAN matrix | def copy_signal(signal_glob, source_db, target_db):
# type: (str, cm.CanMatrix, cm.CanMatrix) -> None
"""
Copy Signals identified by name from source CAN matrix to target CAN matrix.
In target CanMatrix the signal is put without frame, just on top level.
:param signal_glob: Signal glob pattern
... |
Copy a Frame identified by ArbitrationId from source CAN matrix to target CAN matrix.
This function additionally copy all relevant ECUs and Defines.
:param frame_id: Frame arbitration od
:param source_db: Source CAN matrix
:param target_db: Destination CAN matrix | def copy_frame(frame_id, source_db, target_db):
# type: (cm.ArbitrationId, cm.CanMatrix, cm.CanMatrix) -> bool
"""
Copy a Frame identified by ArbitrationId from source CAN matrix to target CAN matrix.
This function additionally copy all relevant ECUs and Defines.
:param frame_id: Frame arbitration ... |
Lazy init yaml because canmatrix might not be fully loaded when loading this format. | def __init_yaml():
"""Lazy init yaml because canmatrix might not be fully loaded when loading this format."""
global _yaml_initialized
if not _yaml_initialized:
_yaml_initialized = True
yaml.add_constructor(u'tag:yaml.org,2002:Frame', _frame_constructor)
yaml.add_constructor(u'tag:ya... |
Gets the XML field object of the given name. | def get_field(self, name):
"""
Gets the XML field object of the given name.
"""
# Quicker in case the exact name was used.
field = self._all_fields.get(name)
if field is not None:
return field
for field_name, field in self._all_fields.items():
... |
Tries getting the value of the given field.
Tries it in the following order: show (standard nice display), value (raw value), showname (extended nice display).
:param name: The name of the field
:param raw: Only return raw value
:return: str of value | def get_field_value(self, name, raw=False):
"""
Tries getting the value of the given field.
Tries it in the following order: show (standard nice display), value (raw value), showname (extended nice display).
:param name: The name of the field
:param raw: Only return raw value
... |
Sanitizes an XML field name (since it might have characters which would make it inaccessible as a python attribute). | def _sanitize_field_name(self, field_name):
"""
Sanitizes an XML field name (since it might have characters which would make it inaccessible as a python attribute).
"""
field_name = field_name.replace(self._field_prefix, '')
return field_name.replace('.', '_').replace('-', '_').l... |
Returns all lines that represent the fields of the layer (both their names and values). | def _get_all_field_lines(self):
"""
Returns all lines that represent the fields of the layer (both their names and values).
"""
for field in self._get_all_fields_with_alternates():
# Change to yield from
for line in self._get_field_or_layer_repr(field):
... |
Gets a field by its "showname"
(the name that appears in Wireshark's detailed display i.e. in 'User-Agent: Mozilla...', 'User-Agent' is the
showname)
Returns None if not found. | def get_field_by_showname(self, showname):
"""
Gets a field by its "showname"
(the name that appears in Wireshark's detailed display i.e. in 'User-Agent: Mozilla...', 'User-Agent' is the
showname)
Returns None if not found.
"""
for field in self._get_all_fields... |
Gets a field by its full or partial name. | def get_field(self, name):
"""Gets a field by its full or partial name."""
# We only make the wrappers here (lazily) to avoid creating a ton of objects needlessly.
field = self._wrapped_fields.get(name)
if field is None:
is_fake = False
field = self._get_internal_... |
Gets the field by name, or None if not found. | def _get_internal_field_by_name(self, name):
"""Gets the field by name, or None if not found."""
field = self._all_fields.get(name, self._all_fields.get('%s.%s' % (self._full_name, name)))
if field is not None:
return field
for field_name in self._all_fields:
# Sp... |
Creates the field lazily.
If it's a simple field, wraps it in a container that adds extra features.
If it's a nested layer, creates a layer for it.
If it's an intermediate layer, copies over the relevant fields and creates a new layer for
it. | def _make_wrapped_field(self, name, field, is_fake=False, full_name=None):
"""Creates the field lazily.
If it's a simple field, wraps it in a container that adds extra features.
If it's a nested layer, creates a layer for it.
If it's an intermediate layer, copies over the relevant field... |
Checks whether the layer has the given field name.
Can get a dotted name, i.e. layer.sublayer.subsublayer.field | def has_field(self, dotted_name):
"""
Checks whether the layer has the given field name.
Can get a dotted name, i.e. layer.sublayer.subsublayer.field
"""
parts = dotted_name.split('.')
cur_layer = self
for part in parts:
if part in cur_layer.field_name... |
Returns the special tshark parameters to be used according to the configuration of this class. | def get_parameters(self, packet_count=None):
"""
Returns the special tshark parameters to be used according to the configuration of this class.
"""
params = super(InMemCapture, self).get_parameters(packet_count=packet_count)
params += ['-i', '-']
return params |
Parses binary packets and return a list of parsed packets.
DOES NOT CLOSE tshark. It must be closed manually by calling close() when you're done
working with it. | def parse_packets(self, binary_packets):
"""
Parses binary packets and return a list of parsed packets.
DOES NOT CLOSE tshark. It must be closed manually by calling close() when you're done
working with it.
"""
if not binary_packets:
raise ValueError("Must su... |
DEPRECATED. Use parse_packet instead.
This function adds the packet to the packets list, and also closes and reopens tshark for
each packet.
==============
Gets a binary (string) packet and parses & adds it to this capture.
Returns the added packet.
Use feed_packets if ... | def feed_packet(self, binary_packet, linktype=LinkTypes.ETHERNET):
"""
DEPRECATED. Use parse_packet instead.
This function adds the packet to the packets list, and also closes and reopens tshark for
each packet.
==============
Gets a binary (string) packet and parses & a... |
Gets a list of binary packets, parses them using tshark and returns their parsed values.
Keeps the packets in the internal packet list as well.
By default, assumes the packets are ethernet packets. For another link type, supply the linktype argument (most
can be found in the class LinkTypes) | def feed_packets(self, binary_packets, linktype=LinkTypes.ETHERNET):
"""
Gets a list of binary packets, parses them using tshark and returns their parsed values.
Keeps the packets in the internal packet list as well.
By default, assumes the packets are ethernet packets. For another link... |
Finds the path of the tshark executable. If the user has provided a path
or specified a location in config.ini it will be used. Otherwise default
locations will be searched.
:param tshark_path: Path of the tshark binary
:raises TSharkNotFoundException in case TShark is not found in any location. | def get_process_path(tshark_path=None, process_name="tshark"):
"""
Finds the path of the tshark executable. If the user has provided a path
or specified a location in config.ini it will be used. Otherwise default
locations will be searched.
:param tshark_path: Path of the tshark binary
:raises ... |
Returns a list of interface numbers from the output tshark -D. Used
internally to capture on multiple interfaces. | def get_tshark_interfaces(tshark_path=None):
"""
Returns a list of interface numbers from the output tshark -D. Used
internally to capture on multiple interfaces.
"""
parameters = [get_process_path(tshark_path), '-D']
with open(os.devnull, 'w') as null:
tshark_interfaces = subprocess.che... |
Returns the special tshark parameters to be used according to the configuration of this class. | def get_parameters(self, packet_count=None):
"""
Returns the special tshark parameters to be used according to the configuration of this class.
"""
params = super(PipeCapture, self).get_parameters(packet_count=packet_count)
params += ['-r', '-']
return params |
Returns a list of all the layers in the packet that are of the layer type (an incase-sensitive string).
This is in order to retrieve layers which appear multiple times in the same packet (i.e. double VLAN) which cannot be
retrieved by easier means. | def get_multiple_layers(self, layer_name):
"""
Returns a list of all the layers in the packet that are of the layer type (an incase-sensitive string).
This is in order to retrieve layers which appear multiple times in the same packet (i.e. double VLAN) which cannot be
retrieved by easier... |
Make lists out of duplicate keys. | def duplicate_object_hook(ordered_pairs):
"""Make lists out of duplicate keys."""
json_dict = {}
for key, val in ordered_pairs:
existing_val = json_dict.get(key)
if not existing_val:
json_dict[key] = val
else:
if isinstance(existing_val, list):
... |
Returns the next packet in the cap.
If the capture's keep_packets flag is True, will also keep it in the internal packet list. | def next(self):
"""
Returns the next packet in the cap.
If the capture's keep_packets flag is True, will also keep it in the internal packet list.
"""
if not self.keep_packets:
return self._packet_generator.send(None)
elif self._current_packet >= len(self._pac... |
Gets a TShark XML packet object or string, and returns a pyshark Packet objec.t
:param xml_pkt: str or xml object.
:param psml_structure: a list of the fields in each packet summary in the psml data. If given, packets will
be returned as a PacketSummary object.
:return: Packet object. | def packet_from_xml_packet(xml_pkt, psml_structure=None):
"""
Gets a TShark XML packet object or string, and returns a pyshark Packet objec.t
:param xml_pkt: str or xml object.
:param psml_structure: a list of the fields in each packet summary in the psml data. If given, packets will
be returned as... |
Returns the special tshark parameters to be used according to the configuration of this class. | def get_parameters(self, packet_count=None):
"""
Returns the special tshark parameters to be used according to the configuration of this class.
"""
params = super(LiveRingCapture, self).get_parameters(packet_count=packet_count)
params += ['-b', 'filesize:' + str(self.ring_file_si... |
Returns the special tshark parameters to be used according to the configuration of this class. | def get_parameters(self, packet_count=None):
"""
Returns the special tshark parameters to be used according to the configuration of this class.
"""
params = super(LiveCapture, self).get_parameters(packet_count=packet_count)
# Read from STDIN
params += ['-r', '-']
... |
Reads the packets from the source (cap, interface, etc.) and adds it to the internal list.
If 0 as the packet_count is given, reads forever
:param packet_count: The amount of packets to add to the packet list (0 to read forever)
:param timeout: If given, automatically stops after a given amount... | def load_packets(self, packet_count=0, timeout=None):
"""
Reads the packets from the source (cap, interface, etc.) and adds it to the internal list.
If 0 as the packet_count is given, reads forever
:param packet_count: The amount of packets to add to the packet list (0 to read forever)
... |
Sets the capture to debug mode (or turns it off if specified). | def set_debug(self, set_to=True):
"""
Sets the capture to debug mode (or turns it off if specified).
"""
if set_to:
StreamHandler(sys.stdout).push_application()
self._log.level = logbook.DEBUG
self.debug = set_to |
Sets up a new eventloop as the current one according to the OS. | def _setup_eventloop(self):
"""
Sets up a new eventloop as the current one according to the OS.
"""
if os.name == 'nt':
self.eventloop = asyncio.ProactorEventLoop()
else:
self.eventloop = asyncio.new_event_loop()
asyncio.set_event_loop(self.eventlo... |
Gets data containing a (part of) tshark xml.
If the given tag is found in it, returns the tag data and the remaining data.
Otherwise returns None and the same data.
:param data: string of a partial tshark xml.
:return: a tuple of (tag, data). tag will be None if none is found. | def _extract_tag_from_data(self, data, tag_name=b'packet'):
"""Gets data containing a (part of) tshark xml.
If the given tag is found in it, returns the tag data and the remaining data.
Otherwise returns None and the same data.
:param data: string of a partial tshark xml.
:retu... |
Returns a generator of packets.
This is the sync version of packets_from_tshark. It wait for the completion of each coroutine and
reimplements reading packets in a sync way, yielding each packet as it arrives.
:param packet_count: If given, stops after this amount of packets is captured. | def _packets_from_tshark_sync(self, packet_count=None, existing_process=None):
"""
Returns a generator of packets.
This is the sync version of packets_from_tshark. It wait for the completion of each coroutine and
reimplements reading packets in a sync way, yielding each packet as it arr... |
Runs through all packets and calls the given callback (a function) with each one as it is read.
If the capture is infinite (i.e. a live capture), it will run forever, otherwise it will complete after all
packets have been read.
Example usage:
def print_callback(pkt):
print(p... | def apply_on_packets(self, callback, timeout=None, packet_count=None):
"""
Runs through all packets and calls the given callback (a function) with each one as it is read.
If the capture is infinite (i.e. a live capture), it will run forever, otherwise it will complete after all
packets h... |
A coroutine which creates a tshark process, runs the given callback on each packet that is received from it and
closes the process when it is done.
Do not use interactively. Can be used in order to insert packets into your own eventloop. | async def packets_from_tshark(self, packet_callback, packet_count=None, close_tshark=True):
"""
A coroutine which creates a tshark process, runs the given callback on each packet that is received from it and
closes the process when it is done.
Do not use interactively. Can be used in or... |
A coroutine which goes through a stream and calls a given callback for each XML packet seen in it. | async def _go_through_packets_from_fd(self, fd, packet_callback, packet_count=None):
"""A coroutine which goes through a stream and calls a given callback for each XML packet seen in it."""
packets_captured = 0
self._log.debug('Starting to go through packets')
psml_struct, data = await ... |
Gets the current PSML (packet summary xml) structure in a tuple ((None, leftover_data)),
only if the capture is configured to return it, else returns (None, leftover_data).
A coroutine. | async def _get_psml_struct(self, fd):
"""Gets the current PSML (packet summary xml) structure in a tuple ((None, leftover_data)),
only if the capture is configured to return it, else returns (None, leftover_data).
A coroutine.
"""
data = b''
psml_struct = None
i... |
A coroutine which returns a single packet if it can be read from the given StreamReader.
:return a tuple of (packet, remaining_data). The packet will be None if there was not enough XML data to create
a packet. remaining_data is the leftover data which was not enough to create a packet from.
:r... | async def _get_packet_from_stream(self, stream, existing_data, got_first_packet=True, psml_structure=None):
"""A coroutine which returns a single packet if it can be read from the given StreamReader.
:return a tuple of (packet, remaining_data). The packet will be None if there was not enough XML data t... |
Returns a new tshark process with previously-set parameters. | async def _get_tshark_process(self, packet_count=None, stdin=None):
"""
Returns a new tshark process with previously-set parameters.
"""
if self.use_json:
output_type = 'json'
if not tshark_supports_json(self.tshark_path):
raise TSharkVersionExcept... |
Kill the given process and properly closes any pipes connected to it. | async def _cleanup_subprocess(self, process):
"""
Kill the given process and properly closes any pipes connected to it.
"""
if process.returncode is None:
try:
process.kill()
return await asyncio.wait_for(process.wait(), 1)
except c... |
Returns the special tshark parameters to be used according to the configuration of this class. | def get_parameters(self, packet_count=None):
"""
Returns the special tshark parameters to be used according to the configuration of this class.
"""
params = []
if self._capture_filter:
params += ['-f', self._capture_filter]
if self._display_filter:
... |
Gets the best 'value' string this field has. | def get_default_value(self):
"""
Gets the best 'value' string this field has.
"""
val = self.show
if not val:
val = self.raw_value
if not val:
val = self.showname
return val |
Converts this field to binary (assuming it's a binary string) | def binary_value(self):
"""
Converts this field to binary (assuming it's a binary string)
"""
str_raw_value = str(self.raw_value)
if len(str_raw_value) % 2 == 1:
str_raw_value = '0' + str_raw_value
return binascii.unhexlify(str_raw_value) |
Build callgraph of func_list, ignoring
built-in functions | def callgraph(G, stmt_list):
"""
Build callgraph of func_list, ignoring
built-in functions
"""
func_list = []
for stmt in stmt_list:
try:
G.add_node(stmt.head.ident.name)
func_list.append(stmt)
except:
pass
for func in func_list:
as... |
Returns a new class with named fields.
@keyword field_defaults: A mapping from (a subset of) field names to default
values.
@keyword default: If provided, the default value for all fields without an
explicit default in `field_defaults`.
>>> Point = recordtype('Point', 'x y', default=0)
... | def recordtype(typename, field_names, verbose=False, **default_kwds):
'''Returns a new class with named fields.
@keyword field_defaults: A mapping from (a subset of) field names to default
values.
@keyword default: If provided, the default value for all fields without an
explicit default i... |
one-dimensional arrays having shape [N],
row and column matrices having shape [1 N] and
[N 1] correspondingly, and their generalizations
having shape [1 1 ... N ... 1 1 1].
Scalars have shape [1 1 ... 1].
Empty arrays dont count | def isvector_or_scalar(a):
"""
one-dimensional arrays having shape [N],
row and column matrices having shape [1 N] and
[N 1] correspondingly, and their generalizations
having shape [1 1 ... N ... 1 1 1].
Scalars have shape [1 1 ... 1].
Empty arrays dont count
"""
try:
return ... |
>>> a=arange(1,10) # 1:10
>>> size(a)
matlabarray([[ 1, 10]]) | def arange(start,stop,step=1,**kwargs):
"""
>>> a=arange(1,10) # 1:10
>>> size(a)
matlabarray([[ 1, 10]])
"""
expand_value = 1 if step > 0 else -1
return matlabarray(np.arange(start,
stop+expand_value,
step,
... |
>>> concat([1,2,3,4,5] , [1,2,3,4,5]])
[1, 2, 3, 4, 5, 1, 2, 3, 4, 5] | def concat(args):
"""
>>> concat([1,2,3,4,5] , [1,2,3,4,5]])
[1, 2, 3, 4, 5, 1, 2, 3, 4, 5]
"""
import pdb
pdb.set_trace()
t = [matlabarray(a) for a in args]
return np.concatenate(t) |
>>> size(zeros(3,3)) + 1
matlabarray([[4, 4]]) | def size(a, b=0, nargout=1):
"""
>>> size(zeros(3,3)) + 1
matlabarray([[4, 4]])
"""
s = np.asarray(a).shape
if s is ():
return 1 if b else (1,)*nargout
# a is not a scalar
try:
if b:
return s[b-1]
else:
return matlabarray(s) if nargout <= 1... |
top :
| top stmt | def p_top(p):
"""
top :
| top stmt
"""
if len(p) == 1:
p[0] = node.stmt_list()
else:
p[0] = p[1]
p[0].append(p[2]) |
top : top END_FUNCTION | def p_end_function(p):
"""
top : top END_FUNCTION
"""
p[0] = p[1]
p[0].append(node.return_stmt(ret=ret_expr))
p[0].append(node.comment_stmt("\nif __name__ == '__main__':\n pass")) |
arg1 : STRING
| NUMBER
| IDENT
| GLOBAL | def p_arg1(p):
"""
arg1 : STRING
| NUMBER
| IDENT
| GLOBAL
"""
# a hack to support "clear global"
p[0] = node.string(value=str(p[1]), lineno=p.lineno(1), lexpos=p.lexpos(1)) |
arg_list : ident_init_opt
| arg_list COMMA ident_init_opt | def p_arg_list(p):
"""
arg_list : ident_init_opt
| arg_list COMMA ident_init_opt
"""
if len(p) == 2:
p[0] = node.expr_list([p[1]])
elif len(p) == 4:
p[0] = p[1]
p[0].append(p[3])
else:
assert 0
assert isinstance(p[0], node.expr_list) |
args : arg1
| args arg1 | def p_args(p):
"""
args : arg1
| args arg1
"""
if len(p) == 2:
p[0] = node.expr_list([p[1]])
else:
p[0] = p[1]
p[0].append(p[2]) |
case_list :
| CASE expr sep stmt_list_opt case_list
| CASE expr error stmt_list_opt case_list
| OTHERWISE stmt_list | def p_case_list(p):
"""
case_list :
| CASE expr sep stmt_list_opt case_list
| CASE expr error stmt_list_opt case_list
| OTHERWISE stmt_list
"""
if len(p) == 1:
p[0] = node.stmt_list()
elif len(p) == 3:
assert isinstance(p[2], node.stmt_list)
... |
cellarray : LBRACE RBRACE
| LBRACE expr_list RBRACE
| LBRACE concat_list RBRACE
| LBRACE concat_list SEMI RBRACE | def p_cellarray(p):
"""
cellarray : LBRACE RBRACE
| LBRACE expr_list RBRACE
| LBRACE concat_list RBRACE
| LBRACE concat_list SEMI RBRACE
"""
if len(p) == 3:
p[0] = node.cellarray(op="{}", args=node.expr_list())
else:
p[0] = node.cellarray(op=... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.