_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q58200 | Device.update_driver | train | def update_driver(self, prompt):
"""Update driver based on new prompt."""
prompt = prompt.lstrip()
self.chain.connection.log("({}): Prompt: '{}'".format(self.driver.platform, prompt))
self.prompt = prompt
driver_name = self.driver.update_driver(prompt)
if driver_name is N... | python | {
"resource": ""
} |
q58201 | Device.prepare_terminal_session | train | def prepare_terminal_session(self):
"""Send commands to prepare terminal session configuration."""
for cmd in self.driver.prepare_terminal_session:
try:
self.send(cmd)
except CommandSyntaxError:
self.chain.connection.log("Command not supported or n... | python | {
"resource": ""
} |
q58202 | Device.update_os_type | train | def update_os_type(self):
"""Update os_type attribute."""
self.chain.connection.log("Detecting os type")
os_type = self.driver.get_os_type(self.version_text)
if os_type:
self.chain.connection.log("SW Type: {}".format(os_type))
self.os_type = os_type | python | {
"resource": ""
} |
q58203 | Device.update_os_version | train | def update_os_version(self):
"""Update os_version attribute."""
self.chain.connection.log("Detecting os version")
os_version = self.driver.get_os_version(self.version_text)
if os_version:
self.chain.connection.log("SW Version: {}".format(os_version))
self.os_versi... | python | {
"resource": ""
} |
q58204 | Device.update_family | train | def update_family(self):
"""Update family attribute."""
self.chain.connection.log("Detecting hw family")
family = self.driver.get_hw_family(self.version_text)
if family:
self.chain.connection.log("HW Family: {}".format(family))
self.family = family | python | {
"resource": ""
} |
q58205 | Device.update_platform | train | def update_platform(self):
"""Update platform attribute."""
self.chain.connection.log("Detecting hw platform")
platform = self.driver.get_hw_platform(self.udi)
if platform:
self.chain.connection.log("HW Platform: {}".format(platform))
self.platform = platform | python | {
"resource": ""
} |
q58206 | Device.update_console | train | def update_console(self):
"""Update is_console whether connected via console."""
self.chain.connection.log("Detecting console connection")
is_console = self.driver.is_console(self.users_text)
if is_console is not None:
self.is_console = is_console | python | {
"resource": ""
} |
q58207 | Device.reload | train | def reload(self, reload_timeout, save_config, no_reload_cmd):
"""Reload device."""
if not no_reload_cmd:
self.ctrl.send_command(self.driver.reload_cmd)
return self.driver.reload(reload_timeout, save_config) | python | {
"resource": ""
} |
q58208 | Device.run_fsm | train | def run_fsm(self, name, command, events, transitions, timeout, max_transitions=20):
"""Wrap the FSM code."""
self.ctrl.send_command(command)
return FSM(name, self, events, transitions, timeout=timeout, max_transitions=max_transitions).run() | python | {
"resource": ""
} |
q58209 | Device.config | train | def config(self, configlet, plane, **attributes):
"""Apply config to the device."""
try:
config_text = configlet.format(**attributes)
except KeyError as exp:
raise CommandSyntaxError("Configuration template error: {}".format(str(exp)))
return self.driver.config(c... | python | {
"resource": ""
} |
q58210 | device_gen | train | def device_gen(chain, urls):
"""Device object generator."""
itr = iter(urls)
last = next(itr)
for url in itr:
yield Device(chain, make_hop_info_from_url(last), driver_name='jumphost', is_target=False)
last = url
yield Device(chain, make_hop_info_from_url(last), driver_name='generic',... | python | {
"resource": ""
} |
q58211 | Chain.connect | train | def connect(self):
"""Connect to the target device using the intermediate jumphosts."""
device = None
# logger.debug("Connecting to: {}".format(str(self)))
for device in self.devices:
if not device.connected:
self.connection.emit_message("Connecting {}".format... | python | {
"resource": ""
} |
q58212 | Chain.disconnect | train | def disconnect(self):
"""Disconnect from the device."""
self.target_device.disconnect()
self.ctrl.disconnect()
self.tail_disconnect(-1) | python | {
"resource": ""
} |
q58213 | Chain.is_discovered | train | def is_discovered(self):
"""Return if target device is discovered."""
if self.target_device is None:
return False
if None in (self.target_device.version_text, self.target_device.os_type, self.target_device.os_version,
self.target_device.inventory_text, self.targe... | python | {
"resource": ""
} |
q58214 | Chain.get_previous_prompts | train | def get_previous_prompts(self, device):
"""Return the list of intermediate prompts. All except target."""
device_index = self.devices.index(device)
prompts = [re.compile("(?!x)x")] + \
[dev.prompt_re for dev in self.devices[:device_index] if dev.prompt_re is not None]
r... | python | {
"resource": ""
} |
q58215 | Chain.get_device_index_based_on_prompt | train | def get_device_index_based_on_prompt(self, prompt):
"""Return the device index in the chain based on prompt."""
conn_info = ""
for device in self.devices:
conn_info += str(device) + "->"
if device.prompt == prompt:
self.connection.log("Connected: {}".forma... | python | {
"resource": ""
} |
q58216 | Chain.tail_disconnect | train | def tail_disconnect(self, index):
"""Mark all devices disconnected except target in the chain."""
try:
for device in self.devices[index + 1:]:
device.connected = False
except IndexError:
pass | python | {
"resource": ""
} |
q58217 | Chain.send | train | def send(self, cmd, timeout, wait_for_string, password):
"""Send command to the target device."""
return self.target_device.send(cmd, timeout=timeout, wait_for_string=wait_for_string, password=password) | python | {
"resource": ""
} |
q58218 | Chain.update | train | def update(self, data):
"""Update the chain object with the predefined data."""
if data is None:
for device in self.devices:
device.clear_info()
else:
for device, device_info in zip(self.devices, data):
device.device_info = device_info
... | python | {
"resource": ""
} |
q58219 | action | train | def action(func):
"""Wrap the FSM action function providing extended logging information based on doc string."""
@wraps(func)
def call_action(*args, **kwargs):
"""Wrap the function with logger debug."""
try:
ctx = kwargs['ctx']
except KeyError:
ctx = None
... | python | {
"resource": ""
} |
q58220 | FSM.run | train | def run(self):
"""Start the FSM.
Returns:
boolean: True if FSM reaches the last state or false if the exception or error message was raised
"""
ctx = FSM.Context(self.name, self.device)
transition_counter = 0
timeout = self.timeout
self.log("{} Start... | python | {
"resource": ""
} |
q58221 | build | train | def build(port=8000, fixtures=None):
"""
Builds a server file.
1. Extract mock response details from all valid docstrings in existing views
2. Parse and generate mock values
3. Create a store of all endpoints and data
4. Construct server file
"""
extractor = Extractor()
parser = Par... | python | {
"resource": ""
} |
q58222 | Subtag.preferred | train | def preferred(self):
"""
Get the preferred subtag.
:return: preferred :class:`language_tags.Subtag.Subtag` if exists, otherwise None.
"""
if 'Preferred-Value' in self.data['record']:
preferred = self.data['record']['Preferred-Value']
type = self.data['typ... | python | {
"resource": ""
} |
q58223 | Subtag.format | train | def format(self):
"""
Get the subtag code conventional format according to RFC 5646 section 2.1.1.
:return: string -- subtag code conventional format.
"""
subtag = self.data['subtag']
if self.data['type'] == 'region':
return subtag.upper()
if self.dat... | python | {
"resource": ""
} |
q58224 | AuthorizingClient | train | def AuthorizingClient(
domain,
auth,
request_encoder,
response_decoder,
user_agent=None
):
"""Creates a Freshbooks client for a freshbooks domain, using
an auth object.
"""
http_transport = transport.HttpTransport(
api_url(domain),
build_headers(auth, user_agent)... | python | {
"resource": ""
} |
q58225 | TokenClient | train | def TokenClient(
domain,
token,
user_agent=None,
request_encoder=default_request_encoder,
response_decoder=default_response_decoder,
):
"""Creates a Freshbooks client for a freshbooks domain, using
token-based auth.
The optional request_encoder and response_decoder parameters can be... | python | {
"resource": ""
} |
q58226 | OAuthClient | train | def OAuthClient(
domain,
consumer_key,
consumer_secret,
token,
token_secret,
user_agent=None,
request_encoder=default_request_encoder,
response_decoder=default_response_decoder
):
"""Creates a Freshbooks client for a freshbooks domain, using
OAuth. Token management is assumed to ... | python | {
"resource": ""
} |
q58227 | gpg_decrypt | train | def gpg_decrypt(cfg, gpg_config=None):
"""Decrypt GPG objects in configuration.
Args:
cfg (dict): configuration dictionary
gpg_config (dict): gpg configuration
dict of arguments for gpg including:
homedir, binary, and keyring (require all if any)
example:... | python | {
"resource": ""
} |
q58228 | kms_decrypt | train | def kms_decrypt(cfg, aws_config=None):
"""Decrypt KMS objects in configuration.
Args:
cfg (dict): configuration dictionary
aws_config (dict): aws credentials
dict of arguments passed into boto3 session
example:
aws_creds = {'aws_access_key_id': aws_access... | python | {
"resource": ""
} |
q58229 | Driver.get_version_text | train | def get_version_text(self):
"""Return the version information from the device."""
show_version_brief_not_supported = False
version_text = None
try:
version_text = self.device.send("show version brief", timeout=120)
except CommandError:
show_version_brief_n... | python | {
"resource": ""
} |
q58230 | Driver.get_inventory_text | train | def get_inventory_text(self):
"""Return the inventory information from the device."""
inventory_text = None
if self.inventory_cmd:
try:
inventory_text = self.device.send(self.inventory_cmd, timeout=120)
self.log('Inventory collected')
excep... | python | {
"resource": ""
} |
q58231 | Driver.get_users_text | train | def get_users_text(self):
"""Return the users logged in information from the device."""
users_text = None
if self.users_cmd:
try:
users_text = self.device.send(self.users_cmd, timeout=60)
except CommandError:
self.log('Unable to collect con... | python | {
"resource": ""
} |
q58232 | Driver.get_os_type | train | def get_os_type(self, version_text): # pylint: disable=no-self-use
"""Return the OS type information from the device."""
os_type = None
if version_text is None:
return os_type
match = re.search("(XR|XE|NX-OS)", version_text)
if match:
os_type = match.gro... | python | {
"resource": ""
} |
q58233 | Driver.get_os_version | train | def get_os_version(self, version_text):
"""Return the OS version information from the device."""
os_version = None
if version_text is None:
return os_version
match = re.search(self.version_re, version_text, re.MULTILINE)
if match:
os_version = match.group(... | python | {
"resource": ""
} |
q58234 | Driver.get_hw_family | train | def get_hw_family(self, version_text):
"""Return the HW family information from the device."""
family = None
if version_text is None:
return family
match = re.search(self.platform_re, version_text, re.MULTILINE)
if match:
self.platform_string = match.grou... | python | {
"resource": ""
} |
q58235 | Driver.get_hw_platform | train | def get_hw_platform(self, udi):
"""Return th HW platform information from the device."""
platform = None
try:
pid = udi['pid']
if pid == '':
self.log("Empty PID. Use the hw family from the platform string.")
return self.raw_family
... | python | {
"resource": ""
} |
q58236 | Driver.is_console | train | def is_console(self, users_text):
"""Return if device is connected over console."""
if users_text is None:
self.log("Console information not collected")
return None
for line in users_text.split('\n'):
if '*' in line:
match = re.search(self.vty... | python | {
"resource": ""
} |
q58237 | Driver.wait_for_string | train | def wait_for_string(self, expected_string, timeout=60):
"""Wait for string FSM."""
# 0 1 2 3
events = [self.syntax_error_re, self.connection_closed_re, expected_string, self.press_return_re,
... | python | {
"resource": ""
} |
q58238 | Driver.reload | train | def reload(self, reload_timeout=300, save_config=True):
"""Reload the device and waits for device to boot up.
It posts the informational message to the log if not implemented by device driver.
"""
self.log("Reload not implemented on {} platform".format(self.platform)) | python | {
"resource": ""
} |
q58239 | Driver.base_prompt | train | def base_prompt(self, prompt):
"""Extract the base prompt pattern."""
if prompt is None:
return None
if not self.device.is_target:
return prompt
pattern = pattern_manager.pattern(self.platform, "prompt_dynamic", compiled=False)
pattern = pattern.format(pro... | python | {
"resource": ""
} |
q58240 | Driver.update_config_mode | train | def update_config_mode(self, prompt): # pylint: disable=no-self-use
"""Update config mode based on the prompt analysis."""
mode = 'global'
if prompt:
if 'config' in prompt:
mode = 'config'
elif 'admin' in prompt:
mode = 'admin'
se... | python | {
"resource": ""
} |
q58241 | Driver.update_hostname | train | def update_hostname(self, prompt):
"""Update the hostname based on the prompt analysis."""
result = re.search(self.prompt_re, prompt)
if result:
hostname = result.group('hostname')
self.log("Hostname detected: {}".format(hostname))
else:
hostname = sel... | python | {
"resource": ""
} |
q58242 | Driver.enter_plane | train | def enter_plane(self, plane):
"""Enter the device plane.
Enter the device plane a.k.a. mode, i.e. admin, qnx, calvados
"""
try:
cmd = CONF['driver'][self.platform]['planes'][plane]
self.plane = plane
except KeyError:
cmd = None
if cmd... | python | {
"resource": ""
} |
q58243 | FixtureFactory.handle_other_factory_method | train | def handle_other_factory_method(attr, minimum, maximum):
"""
This is a temporary static method, when there are more factory
methods, we can move this to another class or find a way to maintain
it in a scalable manner
"""
if attr == 'percentage':
if minimum:
... | python | {
"resource": ""
} |
q58244 | FixtureFactory._parse_syntax | train | def _parse_syntax(self, raw):
"""
Retrieves the syntax from the response and goes through each
one to generate and replace it with mock values
"""
raw = str(raw) # treat the value as a string regardless of its actual data type
has_syntax = re.findall(r'<(\^)?(fk__)?(\w+)... | python | {
"resource": ""
} |
q58245 | FixtureFactory.count | train | def count(self, source, target):
"""
The 'count' relationship is used for listing endpoints where a specific attribute
might hold the value to the number of instances of another attribute.
"""
try:
source_value = self._response_holder[source]
except KeyError:
... | python | {
"resource": ""
} |
q58246 | SSH.get_command | train | def get_command(self, version=2):
"""Return the SSH protocol specific command to connect."""
try:
options = _C['options']
options_str = " -o ".join(options)
if options_str:
options_str = "-o " + options_str + " "
except KeyError:
op... | python | {
"resource": ""
} |
q58247 | SSH.connect | train | def connect(self, driver):
"""Connect using the SSH protocol specific FSM."""
# 0 1 2
events = [driver.password_re, self.device.prompt_re, driver.unable_to_connect_re,
# 3 4 5 6 ... | python | {
"resource": ""
} |
q58248 | SSH.authenticate | train | def authenticate(self, driver):
"""Authenticate using the SSH protocol specific FSM."""
# 0 1 2 3
events = [driver.press_return_re, driver.password_re, self.device.prompt_re, pexpect.TIMEOUT]
transitions = [
... | python | {
"resource": ""
} |
q58249 | SSH.disconnect | train | def disconnect(self, driver):
"""Disconnect using the protocol specific method."""
self.log("SSH disconnect")
try:
self.device.ctrl.sendline('\x03')
self.device.ctrl.sendline('\x04')
except OSError:
self.log("Protocol already disconnected") | python | {
"resource": ""
} |
q58250 | SSH.fallback_to_sshv1 | train | def fallback_to_sshv1(self, ctx):
"""Fallback to SSHv1."""
command = self.get_command(version=1)
ctx.spawn_session(command)
return True | python | {
"resource": ""
} |
q58251 | search_meta_tag | train | def search_meta_tag(html_doc, prefix, code):
"""
Checks whether the html_doc contains a meta matching the prefix & code
"""
regex = '<meta\s+(?:name=([\'\"]){0}\\1\s+content=([\'\"]){1}\\2|content=([\'\"]){1}\\3\s+name=([\'\"]){0}\\4)\s*/?>'.format(prefix, code)
meta = re.compile(regex, flags=re.MUL... | python | {
"resource": ""
} |
q58252 | find_postgame | train | def find_postgame(data, size):
"""Find postgame struct.
We can find postgame location by scanning the last few
thousand bytes of the rec and looking for a pattern as
follows:
[action op] [action length] [action type]
01 00 00 00 30 08 00 00 ff
The last occurance of this pa... | python | {
"resource": ""
} |
q58253 | parse_postgame | train | def parse_postgame(handle, size):
"""Parse postgame structure."""
data = handle.read()
postgame = find_postgame(data, size)
if postgame:
pos, length = postgame
try:
return mgz.body.actions.postgame.parse(data[pos:pos + length])
except construct.core.ConstructError:
... | python | {
"resource": ""
} |
q58254 | ach | train | def ach(structure, fields):
"""Get field from achievements structure."""
field = fields.pop(0)
if structure:
if hasattr(structure, field):
structure = getattr(structure, field)
if not fields:
return structure
return ach(structure, fields)
retur... | python | {
"resource": ""
} |
q58255 | Summary.get_postgame | train | def get_postgame(self):
"""Get postgame structure."""
if self._cache['postgame'] is not None:
return self._cache['postgame']
self._handle.seek(0)
try:
self._cache['postgame'] = parse_postgame(self._handle, self.size)
return self._cache['postgame']
... | python | {
"resource": ""
} |
q58256 | Summary.get_duration | train | def get_duration(self):
"""Get game duration."""
postgame = self.get_postgame()
if postgame:
return postgame.duration_int * 1000
duration = self._header.initial.restore_time
try:
while self._handle.tell() < self.size:
operation = mgz.body.o... | python | {
"resource": ""
} |
q58257 | Summary.get_restored | train | def get_restored(self):
"""Check for restored game."""
return self._header.initial.restore_time > 0, self._header.initial.restore_time | python | {
"resource": ""
} |
q58258 | Summary.get_version | train | def get_version(self):
"""Get game version."""
return mgz.const.VERSIONS[self._header.version], str(self._header.sub_version)[:5] | python | {
"resource": ""
} |
q58259 | Summary.get_dataset | train | def get_dataset(self):
"""Get dataset."""
sample = self._header.initial.players[0].attributes.player_stats
if 'mod' in sample and sample.mod['id'] > 0:
return sample.mod
elif 'trickle_food' in sample and sample.trickle_food:
return {
'id': 1,
... | python | {
"resource": ""
} |
q58260 | Summary.get_teams | train | def get_teams(self):
"""Get teams."""
if self._cache['teams']:
return self._cache['teams']
teams = []
for j, player in enumerate(self._header.initial.players):
added = False
for i in range(0, len(self._header.initial.players)):
if playe... | python | {
"resource": ""
} |
q58261 | Summary.get_achievements | train | def get_achievements(self, name):
"""Get achievements for a player.
Must match on name, not index, since order is not always the same.
"""
postgame = self.get_postgame()
if not postgame:
return None
for achievements in postgame.achievements:
# ach... | python | {
"resource": ""
} |
q58262 | Summary._process_body | train | def _process_body(self):
"""Get Voobly ladder.
This is expensive if the rec is not from Voobly,
since it will search the whole file. Returns tuple,
(from_voobly, ladder_name, rated, ratings).
"""
start_time = time.time()
ratings = {}
encoding = self.get_e... | python | {
"resource": ""
} |
q58263 | Summary.get_settings | train | def get_settings(self):
"""Get settings."""
postgame = self.get_postgame()
return {
'type': (
self._header.lobby.game_type_id,
self._header.lobby.game_type
),
'difficulty': (
self._header.scenario.game_settings.d... | python | {
"resource": ""
} |
q58264 | Summary.get_map | train | def get_map(self):
"""Get the map metadata."""
if self._cache['map']:
return self._cache['map']
map_id = self._header.scenario.game_settings.map_id
instructions = self._header.scenario.messages.instructions
size = mgz.const.MAP_SIZES.get(self._header.map_info.size_x)
... | python | {
"resource": ""
} |
q58265 | Summary.get_completed | train | def get_completed(self):
"""Determine if the game was completed.
If there's a postgame, it will indicate completion.
If there is no postgame, guess based on resignation.
"""
postgame = self.get_postgame()
if postgame:
return postgame.complete
else:
... | python | {
"resource": ""
} |
q58266 | Summary.get_mirror | train | def get_mirror(self):
"""Determine mirror match."""
mirror = False
if self.get_diplomacy()['1v1']:
civs = set()
for data in self.get_players():
civs.add(data['civilization'])
mirror = (len(civs) == 1)
return mirror | python | {
"resource": ""
} |
q58267 | Summary.guess_winner | train | def guess_winner(self, i):
"""Guess if a player won.
Find what team the player was on. If anyone
on their team resigned, assume the player lost.
"""
for team in self.get_teams():
if i not in team:
continue
for p in team:
if... | python | {
"resource": ""
} |
q58268 | Event.trigger | train | def trigger(self, *args, **kwargs):
"""Execute the handlers with a message, if any."""
for h in self.handlers:
h(*args, **kwargs) | python | {
"resource": ""
} |
q58269 | Observable.on | train | def on(self, event, handler=None):
"""Create, add or update an event with a handler or more attached."""
if isinstance(event, str) and ' ' in event: # event is list str-based
self.on(event.split(' '), handler)
elif isinstance(event, list): # many events contains same handler
... | python | {
"resource": ""
} |
q58270 | Observable.off | train | def off(self, event, handler=None):
"""Remove an event or a handler from it."""
if handler:
self.events[event].off(handler)
else:
del self.events[event]
delattr(self, event) | python | {
"resource": ""
} |
q58271 | Observable.trigger | train | def trigger(self, *args, **kargs):
"""
Execute all event handlers with optional arguments for the observable.
"""
event = args[0]
if isinstance(event, str) and ' ' in event:
event = event.split(' ') # split event names ...
if isinstance(event, list): # eve... | python | {
"resource": ""
} |
q58272 | _initializer_wrapper | train | def _initializer_wrapper(initializer, *args):
"""
Ignore SIGINT. During typical keyboard interrupts, the parent does the
killing.
"""
signal.signal(signal.SIGINT, signal.SIG_IGN)
if initializer is not None:
initializer(*args) | python | {
"resource": ""
} |
q58273 | BaseExtractor._col_type_set | train | def _col_type_set(self, col, df):
"""
Determines the set of types present in a DataFrame column.
:param str col: A column name.
:param pandas.DataFrame df: The dataset. Usually ``self._data``.
:return: A set of Types.
"""
type_set = set()
if df[col].dtype... | python | {
"resource": ""
} |
q58274 | BaseExtractor.raw | train | def raw(self, drop_collections = False):
"""
Produces the extractor object's data as it is stored internally.
:param bool drop_collections: Defaults to False. Indicates whether columns with lists/dicts/sets will be dropped.
:return: pandas.DataFrame
"""
base_df = self._... | python | {
"resource": ""
} |
q58275 | _walk | train | def _walk(path, follow_links=False, maximum_depth=None):
"""A modified os.walk with support for maximum traversal depth."""
root_level = path.rstrip(os.path.sep).count(os.path.sep)
for root, dirs, files in os.walk(path, followlinks=follow_links):
yield root, dirs, files
if maximum_depth is N... | python | {
"resource": ""
} |
q58276 | ClassLoader.update | train | def update(self, *sources, follow_symlinks: bool=False,
maximum_depth: int=20):
"""Add one or more ClassFile sources to the class loader.
If a given source is a directory path, it is traversed up to the
maximum set depth and all files under it are added to the class loader
... | python | {
"resource": ""
} |
q58277 | ClassLoader.open | train | def open(self, path: str, mode: str='r') -> IO:
"""Open an IO-like object for `path`.
.. note::
Mode *must* be either 'r' or 'w', as the underlying objects
do not understand the full range of modes.
:param path: The path to open.
:param mode: The mode of the fi... | python | {
"resource": ""
} |
q58278 | ClassLoader.load | train | def load(self, path: str) -> ClassFile:
"""Load the class at `path` and return it.
Load will attempt to load the file at `path` and `path` + .class
before failing.
:param path: Fully-qualified path to a ClassFile.
"""
# Try to refresh the class from the cache, loading i... | python | {
"resource": ""
} |
q58279 | ClassLoader.dependencies | train | def dependencies(self, path: str) -> Set[str]:
"""Returns a set of all classes referenced by the ClassFile at
`path` without reading the entire ClassFile.
This is an optimization method that does not load a complete ClassFile,
nor does it add the results to the ClassLoader cache.
... | python | {
"resource": ""
} |
q58280 | ClassLoader.search_constant_pool | train | def search_constant_pool(self, *, path: str, **options):
"""Partially load the class at `path`, yield all matching constants
from the ConstantPool.
This is an optimization method that does not load a complete ClassFile,
nor does it add the results to the ClassLoader cache.
:par... | python | {
"resource": ""
} |
q58281 | ClassLoader.classes | train | def classes(self) -> Iterator[str]:
"""Yield the name of all classes discovered in the path map."""
yield from (
c[:-6]
for c in self.path_map.keys() if c.endswith('.class')
) | python | {
"resource": ""
} |
q58282 | TwitterExtractor._make_object_dict | train | def _make_object_dict(self, obj):
"""
Processes an object, exporting its data as a nested dictionary.
:param obj: An object
:return: A nested dictionary of object data
"""
data = {}
for attr in dir(obj):
if attr[0] is not '_' and attr is not 'status':... | python | {
"resource": ""
} |
q58283 | Field.unpack | train | def unpack(self, source: IO):
"""
Read the Field from the file-like object `fio`.
.. note::
Advanced usage only. You will typically never need to call this
method as it will be called for you when loading a ClassFile.
:param source: Any file-like object providi... | python | {
"resource": ""
} |
q58284 | Field.pack | train | def pack(self, out: IO):
"""
Write the Field to the file-like object `out`.
.. note::
Advanced usage only. You will typically never need to call this
method as it will be called for you when saving a ClassFile.
:param out: Any file-like object providing `write(... | python | {
"resource": ""
} |
q58285 | FieldTable.remove | train | def remove(self, field: Field):
"""
Removes a `Field` from the table by identity.
"""
self._table = [fld for fld in self._table if fld is not field] | python | {
"resource": ""
} |
q58286 | FieldTable.unpack | train | def unpack(self, source: IO):
"""
Read the FieldTable from the file-like object `source`.
.. note::
Advanced usage only. You will typically never need to call this
method as it will be called for you when loading a ClassFile.
:param source: Any file-like object... | python | {
"resource": ""
} |
q58287 | FieldTable.pack | train | def pack(self, out: IO):
"""
Write the FieldTable to the file-like object `out`.
.. note::
Advanced usage only. You will typically never need to call this
method as it will be called for you when saving a ClassFile.
:param out: Any file-like object providing `w... | python | {
"resource": ""
} |
q58288 | FieldTable.find | train | def find(self, *, name: str=None, type_: str=None,
f: Callable=None) -> Iterator[Field]:
"""
Iterates over the fields table, yielding each matching method. Calling
without any arguments is equivalent to iterating over the table.
:param name: The name of the field(s) to find... | python | {
"resource": ""
} |
q58289 | is_valid_host | train | def is_valid_host(value):
"""Check if given value is a valid host string.
:param value: a value to test
:returns: True if the value is valid
"""
host_validators = validators.ipv4, validators.ipv6, validators.domain
return any(f(value) for f in host_validators) | python | {
"resource": ""
} |
q58290 | is_valid_url | train | def is_valid_url(value):
"""Check if given value is a valid URL string.
:param value: a value to test
:returns: True if the value is valid
"""
match = URL_REGEX.match(value)
host_str = urlparse(value).hostname
return match and is_valid_host(host_str) | python | {
"resource": ""
} |
q58291 | accepts_valid_host | train | def accepts_valid_host(func):
"""Return a wrapper that runs given method only for valid hosts.
:param func: a method to be wrapped
:returns: a wrapper that adds argument validation
"""
@functools.wraps(func)
def wrapper(obj, value, *args, **kwargs):
"""Run the function and return a valu... | python | {
"resource": ""
} |
q58292 | accepts_valid_urls | train | def accepts_valid_urls(func):
"""Return a wrapper that runs given method only for valid URLs.
:param func: a method to be wrapped
:returns: a wrapper that adds argument validation
"""
@functools.wraps(func)
def wrapper(obj, urls, *args, **kwargs):
"""Run the function and return a value ... | python | {
"resource": ""
} |
q58293 | ConstantPool.get | train | def get(self, index):
"""
Returns the `Constant` at `index`, raising a KeyError if it
does not exist.
"""
constant = self._pool[index]
if not isinstance(constant, Constant):
constant = _constant_types[constant[0]](self, index, *constant[1:])
self._... | python | {
"resource": ""
} |
q58294 | ConstantPool.find | train | def find(self, type_=None, f=None):
"""
Iterates over the pool, yielding each matching ``Constant``. Calling
without any arguments is equivalent to iterating over the pool.
:param type_: Any subclass of :class:`Constant` or ``None``.
:param f: Any callable which takes one argume... | python | {
"resource": ""
} |
q58295 | ConstantPool.pack | train | def pack(self, fout):
"""
Write the ConstantPool to the file-like object `fout`.
.. note::
Advanced usage only. You will typically never need to call this
method as it will be calle=d for you when saving a ClassFile.
:param fout: Any file-like object providing ... | python | {
"resource": ""
} |
q58296 | checkout_and_create_branch | train | def checkout_and_create_branch(repo, name):
"""Checkout branch. Create it if necessary"""
local_branch = repo.branches[name] if name in repo.branches else None
if not local_branch:
if name in repo.remotes.origin.refs:
# If origin branch exists but not local, git.checkout is the fatest wa... | python | {
"resource": ""
} |
q58297 | checkout_create_push_branch | train | def checkout_create_push_branch(repo, name):
"""Checkout this branch. Create it if necessary, and push it to origin.
"""
try:
repo.git.checkout(name)
_LOGGER.info("Checkout %s success", name)
except GitCommandError:
_LOGGER.info("Checkout %s was impossible (branch does not exist)... | python | {
"resource": ""
} |
q58298 | get_repo_hexsha | train | def get_repo_hexsha(git_folder):
"""Get the SHA1 of the current repo"""
repo = Repo(str(git_folder))
if repo.bare:
not_git_hexsha = "notgitrepo"
_LOGGER.warning("Not a git repo, SHA1 used will be: %s", not_git_hexsha)
return not_git_hexsha
hexsha = repo.head.commit.hexsha
_LO... | python | {
"resource": ""
} |
q58299 | checkout_with_fetch | train | def checkout_with_fetch(git_folder, refspec, repository="origin"):
"""Fetch the refspec, and checkout FETCH_HEAD.
Beware that you will ne in detached head mode.
"""
_LOGGER.info("Trying to fetch and checkout %s", refspec)
repo = Repo(str(git_folder))
repo.git.fetch(repository, refspec) # FETCH_... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.