code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
if isinstance(path_or_doc, string_types):
doc = load(path_or_doc)
else:
# Recover the OpenDocumentText instance.
if isinstance(path_or_doc, ODFDocument):
doc = path_or_doc._doc
else:
doc = path_or_doc
assert isinstance(doc, OpenDocument), doc
... | def load_styles(path_or_doc) | Return a dictionary of all styles contained in an ODF document. | 3.746426 | 3.319595 | 1.128579 |
tag = item['tag']
style = item.get('style', None)
if tag == 'p':
if style is None or 'paragraph' in style:
return 'paragraph'
else:
return style
elif tag == 'span':
if style in (None, 'normal-text'):
return 'text'
elif style == 'ur... | def _item_type(item) | Indicate to the ODF reader the type of the block or text. | 3.537336 | 3.255119 | 1.086699 |
for stylename in sorted(styles):
self._doc.styles.addElement(styles[stylename]) | def add_styles(self, **styles) | Add ODF styles to the current document. | 6.6444 | 4.638978 | 1.432298 |
# Convert stylename strings to actual style elements.
kwargs = self._replace_stylename(kwargs)
el = cls(**kwargs)
self._doc.text.addElement(el) | def _add_element(self, cls, **kwargs) | Add an element. | 10.731535 | 9.759947 | 1.099549 |
if el.attributes is None:
return None
style_field = ('urn:oasis:names:tc:opendocument:xmlns:text:1.0',
'style-name')
name = el.attributes.get(style_field, None)
if not name:
return None
return self._get_style_name(name) | def _style_name(self, el) | Return the style name of an element. | 3.279888 | 3.047411 | 1.076287 |
# Convert stylename strings to actual style elements.
kwargs = self._replace_stylename(kwargs)
# Create the container.
container = cls(**kwargs)
self._containers.append(container) | def start_container(self, cls, **kwargs) | Append a new container. | 7.022392 | 6.617144 | 1.061242 |
if not self._containers:
return
container = self._containers.pop()
if len(self._containers) >= 1:
parent = self._containers[-1]
else:
parent = self._doc.text
if not cancel:
parent.addElement(container) | def end_container(self, cancel=None) | Finishes and registers the currently-active container, unless
'cancel' is True. | 3.87897 | 3.901067 | 0.994335 |
self.start_container(cls, **kwargs)
yield
self.end_container() | def container(self, cls, **kwargs) | Container context manager. | 6.317796 | 3.944621 | 1.601623 |
# Use the next paragraph style if one was set.
if stylename is None:
stylename = self._next_p_style or 'normal-paragraph'
self.start_container(P, stylename=stylename) | def start_paragraph(self, stylename=None) | Start a new paragraph. | 6.509 | 5.874132 | 1.108079 |
if self._containers and _is_paragraph(self._containers[-1]):
return False
else:
self.start_paragraph()
return True | def require_paragraph(self) | Create a new paragraph unless the currently-active container
is already a paragraph. | 6.627504 | 4.502259 | 1.47204 |
assert self._containers
container = self._containers[-1]
# Handle extra spaces.
text = line
while text:
if text.startswith(' '):
r = re.match(r'(^ +)', text)
n = len(r.group(1))
container.addElement(S(c=n))
... | def _code_line(self, line) | Add a code line. | 4.08994 | 3.858107 | 1.06009 |
# WARNING: lang is discarded currently.
with self.paragraph(stylename='code'):
lines = text.splitlines()
for line in lines[:-1]:
self._code_line(line)
self.linebreak()
self._code_line(lines[-1]) | def code(self, text, lang=None) | Add a code block. | 6.010719 | 5.466398 | 1.099576 |
self._ordered = True
self.start_container(List, stylename='_numbered_list')
self.set_next_paragraph_style('numbered-list-paragraph'
if self._item_level <= 0
else 'sublist-paragraph') | def start_numbered_list(self) | Start a numbered list. | 10.513759 | 9.939459 | 1.05778 |
self._ordered = False
self.start_container(List)
self.set_next_paragraph_style('list-paragraph'
if self._item_level <= 0
else 'sublist-paragraph') | def start_list(self) | Start a list. | 12.471486 | 10.510187 | 1.186609 |
assert self._containers
container = self._containers[-1]
if stylename is not None:
stylename = self._get_style_name(stylename)
container.addElement(Span(stylename=stylename, text=text))
else:
container.addElement(Span(text=text)) | def text(self, text, stylename=None) | Add text within the current container. | 3.352093 | 2.991693 | 1.120467 |
outputs = cell.get('outputs', [])
# Add stdout.
stdout = ('\n'.join(_ensure_string(output.get('text', ''))
for output in outputs)).rstrip()
# Add text output.
text_outputs = []
for output in outputs:
out = output.get('data', {}).get('text/plain', [])
... | def _cell_output(cell) | Return the output of an ipynb cell. | 4.131298 | 3.499776 | 1.180446 |
'Post-processing to add some nice-ish spacing for deeper map/list levels.'
if isinstance(vspacing, int):
vspacing = ['\n']*(vspacing+1)
buff.seek(0)
result = list()
for line in buff:
level = 0
line = line.decode('utf-8')
result.append(line)
if ':' in line or re.search(r'---(\s*$|\s)', line):
while lin... | def dump_add_vspacing(buff, vspacing) | Post-processing to add some nice-ish spacing for deeper map/list levels. | 4.420139 | 3.192681 | 1.38446 |
if grep:
return self.adb_shell('dumpsys {0} | grep "{1}"'.format(service, grep))
return self.adb_shell('dumpsys {0}'.format(service)) | def _dump(self, service, grep=None) | Perform a service dump.
:param service: Service to dump.
:param grep: Grep for this string.
:returns: Dump, optionally grepped. | 2.897279 | 3.271578 | 0.885591 |
dump_grep = self._dump(service, grep=grep)
if not dump_grep:
return False
return dump_grep.strip().find(search) > -1 | def _dump_has(self, service, grep, search) | Check if a dump has particular content.
:param service: Service to dump.
:param grep: Grep for this string.
:param search: Check for this substring.
:returns: Found or not. | 5.166377 | 7.027076 | 0.73521 |
if not self.available:
return
result = []
ps = self.adb_streaming_shell('ps')
try:
for bad_line in ps:
# The splitting of the StreamingShell doesn't always work
# this is to ensure that we get only one line
... | def _ps(self, search='') | Perform a ps command with optional filtering.
:param search: Check for this substring.
:returns: List of matching fields | 7.266543 | 7.349918 | 0.988656 |
self._adb_lock.acquire(**LOCK_KWARGS)
try:
if not self.adb_server_ip:
# python-adb
try:
if self.adbkey:
signer = Signer(self.adbkey)
# Connect to the device
s... | def connect(self, always_log_errors=True) | Connect to an Amazon Fire TV device.
Will attempt to establish ADB connection to the given host.
Failure sets state to UNKNOWN and disables sending actions.
:returns: True if successful, False otherwise | 3.068944 | 2.967185 | 1.034295 |
# The `screen_on`, `awake`, `wake_lock_size`, `current_app`, and `running_apps` properties.
screen_on, awake, wake_lock_size, _current_app, running_apps = self.get_properties(get_running_apps=get_running_apps, lazy=True)
# Check if device is off.
if not screen_on:
s... | def update(self, get_running_apps=True) | Get the state of the device, the current app, and the running apps.
:param get_running_apps: whether or not to get the ``running_apps`` property
:return state: the state of the device
:return current_app: the current app
:return running_apps: the running apps | 2.713167 | 2.7154 | 0.999178 |
if not self.available or not self.screen_on:
return STATE_OFF
if self.current_app["package"] == app:
return STATE_ON
return STATE_OFF | def app_state(self, app) | Informs if application is running. | 6.183901 | 5.189744 | 1.191562 |
# Check if device is disconnected.
if not self.available:
return STATE_UNKNOWN
# Check if device is off.
if not self.screen_on:
return STATE_OFF
# Check if screen saver is on.
if not self.awake:
return STATE_IDLE
# Chec... | def state(self) | Compute and return the device state.
:returns: Device state. | 4.153677 | 4.023136 | 1.032448 |
if not self.adb_server_ip:
# python-adb
return bool(self._adb)
# pure-python-adb
try:
# make sure the server is available
adb_devices = self._adb_client.devices()
# make sure the device is available
try:
... | def available(self) | Check whether the ADB connection is intact. | 3.922847 | 3.654759 | 1.073353 |
ps = self.adb_shell(RUNNING_APPS_CMD)
if ps:
return [line.strip().rsplit(' ', 1)[-1] for line in ps.splitlines() if line.strip()]
return [] | def running_apps(self) | Return a list of running user applications. | 4.03749 | 3.73679 | 1.08047 |
current_focus = self.adb_shell(CURRENT_APP_CMD)
if current_focus is None:
return None
current_focus = current_focus.replace("\r", "")
matches = WINDOW_REGEX.search(current_focus)
# case 1: current app was successfully found
if matches:
(... | def current_app(self) | Return the current app. | 4.145256 | 3.932049 | 1.054223 |
output = self.adb_shell(WAKE_LOCK_SIZE_CMD)
if not output:
return None
return int(output.split("=")[1].strip()) | def wake_lock_size(self) | Get the size of the current wake lock. | 4.757697 | 4.135121 | 1.150558 |
if get_running_apps:
output = self.adb_shell(SCREEN_ON_CMD + (SUCCESS1 if lazy else SUCCESS1_FAILURE0) + " && " +
AWAKE_CMD + (SUCCESS1 if lazy else SUCCESS1_FAILURE0) + " && " +
WAKE_LOCK_SIZE_CMD + " && " +
... | def get_properties(self, get_running_apps=True, lazy=False) | Get the ``screen_on``, ``awake``, ``wake_lock_size``, ``current_app``, and ``running_apps`` properties. | 2.172234 | 1.926846 | 1.127352 |
valid = valid_device_id.match(device_id)
if not valid:
logging.error("A valid device identifier contains "
"only ascii word characters or dashes. "
"Device '%s' not added.", device_id)
return valid | def is_valid_device_id(device_id) | Check if device identifier is valid.
A valid device identifier contains only ascii word characters or dashes.
:param device_id: Device identifier
:returns: Valid or not. | 7.179301 | 4.498484 | 1.595938 |
valid = is_valid_device_id(device_id) and is_valid_host(host)
if valid:
devices[device_id] = FireTV(str(host), str(adbkey), str(adb_server_ip), str(adb_server_port))
return valid | def add(device_id, host, adbkey='', adb_server_ip='', adb_server_port=5037) | Add a device.
Creates FireTV instance associated with device identifier.
:param device_id: Device identifier.
:param host: Host in <address>:<port> format.
:param adbkey: The path to the "adbkey" file
:param adb_server_ip: the IP address for the ADB server
:param adb_server_port: the port for ... | 2.818333 | 2.72976 | 1.032447 |
req = request.get_json()
success = False
if 'device_id' in req and 'host' in req:
success = add(req['device_id'], req['host'], req.get('adbkey', ''), req.get('adb_server_ip', ''), req.get('adb_server_port', 5037))
return jsonify(success=success) | def add_device() | Add a device via HTTP POST.
POST JSON in the following format ::
{
"device_id": "<your_device_id>",
"host": "<address>:<port>",
"adbkey": "<path to the adbkey file>"
} | 3.290849 | 2.782597 | 1.182654 |
output = {}
for device_id, device in devices.items():
output[device_id] = {
'host': device.host,
'state': device.state
}
return jsonify(devices=output) | def list_devices() | List devices via HTTP GET. | 3.188352 | 3.107516 | 1.026013 |
if device_id not in devices:
return jsonify(success=False)
return jsonify(state=devices[device_id].state) | def device_state(device_id) | Get device state via HTTP GET. | 3.500927 | 3.961143 | 0.883817 |
if not is_valid_device_id(device_id):
abort(403)
if device_id not in devices:
abort(404)
current = devices[device_id].current_app
if current is None:
abort(404)
return jsonify(current_app=current) | def current_app(device_id) | Get currently running app. | 2.450363 | 2.468327 | 0.992722 |
if not is_valid_device_id(device_id):
abort(403)
if device_id not in devices:
abort(404)
return jsonify(running_apps=devices[device_id].running_apps) | def running_apps(device_id) | Get running apps via HTTP GET. | 2.606177 | 2.692565 | 0.967916 |
if not is_valid_app_id(app_id):
abort(403)
if not is_valid_device_id(device_id):
abort(403)
if device_id not in devices:
abort(404)
app_state = devices[device_id].app_state(app_id)
return jsonify(state=app_state, status=app_state) | def get_app_state(device_id, app_id) | Get the state of the requested app | 2.28653 | 2.276205 | 1.004536 |
success = False
if device_id in devices:
input_cmd = getattr(devices[device_id], action_id, None)
if callable(input_cmd):
input_cmd()
success = True
return jsonify(success=success) | def device_action(device_id, action_id) | Initiate device action via HTTP GET. | 3.319788 | 3.560539 | 0.932383 |
if not is_valid_app_id(app_id):
abort(403)
if not is_valid_device_id(device_id):
abort(403)
if device_id not in devices:
abort(404)
success = devices[device_id].launch_app(app_id)
return jsonify(success=success) | def app_start(device_id, app_id) | Starts an app with corresponding package name | 2.206415 | 2.222938 | 0.992567 |
if not is_valid_app_id(app_id):
abort(403)
if not is_valid_device_id(device_id):
abort(403)
if device_id not in devices:
abort(404)
success = devices[device_id].stop_app(app_id)
return jsonify(success=success) | def app_stop(device_id, app_id) | stops an app with corresponding package name | 2.120993 | 2.102356 | 1.008865 |
success = False
if device_id in devices:
devices[device_id].connect()
success = True
return jsonify(success=success) | def device_connect(device_id) | Force a connection attempt via HTTP GET. | 3.400551 | 3.613303 | 0.94112 |
config_file = open(config_file_path, 'r')
config = yaml.load(config_file)
config_file.close()
return config | def _parse_config(config_file_path) | Parse Config File from yaml file. | 2.195587 | 1.723808 | 1.273684 |
config = _parse_config(args.config)
for device in config['devices']:
if args.default:
if device == "default":
raise ValueError('devicename "default" in config is not allowed if default param is set')
if config['devices'][device]['host'] == args.default:
... | def _add_devices_from_config(args) | Add devices from config. | 4.068524 | 3.917095 | 1.038658 |
parser = argparse.ArgumentParser(description='AFTV Server')
parser.add_argument('-p', '--port', type=int, help='listen port', default=5556)
parser.add_argument('-d', '--default', help='default Amazon Fire TV host', nargs='?')
parser.add_argument('-c', '--config', type=str, help='Path to config file... | def main() | Set up the server. | 3.676073 | 3.561544 | 1.032157 |
with open(self._words_file, 'r') as f:
self._censor_list = [line.strip() for line in f.readlines()] | def _load_words(self) | Loads the list of profane words from file. | 3.849836 | 2.942184 | 1.308496 |
# TODO: what if character isn't str()-able?
if isinstance(character, int):
character = str(character)
self._censor_char = character | def set_censor(self, character) | Replaces the original censor character '*' with ``character``. | 6.62479 | 5.954524 | 1.112564 |
profane_words = []
if self._custom_censor_list:
profane_words = [w for w in self._custom_censor_list] # Previous versions of Python don't have list.copy()
else:
profane_words = [w for w in self._censor_list]
profane_words.extend(self._extra_censor_list... | def get_profane_words(self) | Returns all profane words currently in use. | 4.053548 | 4.007121 | 1.011586 |
bad_words = self.get_profane_words()
res = input_text
for word in bad_words:
# Apply word boundaries to the bad word
regex_string = r'{0}' if self._no_word_boundaries else r'\b{0}\b'
regex_string = regex_string.format(word)
regex = re.c... | def censor(self, input_text) | Returns input_text with any profane words censored. | 3.321332 | 3.080147 | 1.078303 |
chunks = []
while data:
info = SMB2NetworkInterfaceInfo()
data = info.unpack(data)
chunks.append(info)
return chunks | def unpack_multiple(data) | Get's a list of SMB2NetworkInterfaceInfo messages from the byte value
passed in. This is the raw buffer value that is set on the
SMB2IOCTLResponse message.
:param data: bytes of the messages
:return: List of SMB2NetworkInterfaceInfo messages | 7.675019 | 3.963559 | 1.936396 |
return {
CreateContextName.SMB2_CREATE_DURABLE_HANDLE_REQUEST:
SMB2CreateDurableHandleResponse(),
CreateContextName.SMB2_CREATE_DURABLE_HANDLE_RECONNECT:
SMB2CreateDurableHandleReconnect(),
CreateContextName.SMB2_CREATE_QUERY_MAXIMAL_A... | def get_response_structure(name) | Returns the response structure for a know list of create context
responses.
:param name: The constant value above
:return: The response structure or None if unknown | 2.298054 | 2.194152 | 1.047354 |
buffer_name = self['buffer_name'].get_value()
structure = CreateContextName.get_response_structure(buffer_name)
if structure:
structure.unpack(self['buffer_data'].get_value())
return structure
else:
# unknown structure, just return the raw byt... | def get_context_data(self) | Get the buffer_data value of a context response and try to convert it
to the relevant structure based on the buffer_name used. If it is an
unknown structure then the raw bytes are returned.
:return: relevant Structure of buffer_data or bytes if unknown name | 6.357072 | 4.186457 | 1.518485 |
data = b""
msg_count = len(messages)
for i, msg in enumerate(messages):
if i == msg_count - 1:
msg['next_entry_offset'] = 0
else:
# because the end padding val won't be populated if the entry
# offset is 0, we set t... | def pack_multiple(messages) | Converts a list of SMB2CreateEABuffer structures and packs them as a
bytes object used when setting to the SMB2CreateContextRequest
buffer_data field. This should be used as it would calculate the
correct next_entry_offset field value for each buffer entry.
:param messages: List of SMB2... | 5.00319 | 4.691438 | 1.066451 |
print_bytes = print_name.encode('utf-16-le')
sub_bytes = substitute_name.encode('utf-16-le')
path_buffer = print_bytes + sub_bytes
self['print_name_offset'].set_value(0)
self['print_name_length'].set_value(len(print_bytes))
self['substitute_name_offset'].set_val... | def set_name(self, print_name, substitute_name) | Set's the path_buffer and print/substitute name length of the message
with the values passed in. These values should be a string and not a
byte string as it is encoded in this function.
:param print_name: The print name string to set
:param substitute_name: The substitute name string to... | 2.066052 | 1.967339 | 1.050176 |
log.info("Session: %s - Creating connection to share %s"
% (self.session.username, self.share_name))
utf_share_name = self.share_name.encode('utf-16-le')
connect = SMB2TreeConnectRequest()
connect['buffer'] = utf_share_name
log.info("Session: %s - Sendi... | def connect(self, require_secure_negotiate=True) | Connect to the share.
:param require_secure_negotiate: For Dialects 3.0 and 3.0.2, will
verify the negotiation parameters with the server to prevent
SMB downgrade attacks | 2.796909 | 2.724298 | 1.026653 |
if not self._connected:
return
log.info("Session: %s, Tree: %s - Disconnecting from Tree Connect"
% (self.session.username, self.share_name))
req = SMB2TreeDisconnect()
log.info("Session: %s, Tree: %s - Sending Tree Disconnect message"
... | def disconnect(self) | Disconnects the tree connection. | 2.852148 | 2.639244 | 1.080668 |
log.info("Setting up transport connection")
self.transport.connect()
log.info("Starting negotiation with SMB server")
smb_response = self._send_smb2_negotiate(dialect, timeout)
log.info("Negotiated dialect: %s"
% str(smb_response['dialect_revision']))
... | def connect(self, dialect=None, timeout=60) | Will connect to the target server and negotiate the capabilities
with the client. Once setup, the client MUST call the disconnect()
function to close the listener thread. This function will populate
various connection properties that denote the capabilities of the
server.
:param... | 2.633231 | 2.598356 | 1.013422 |
if close:
for session in list(self.session_table.values()):
session.disconnect(True)
log.info("Disconnecting transport connection")
self.transport.disconnect() | def disconnect(self, close=True) | Closes the connection as well as logs off any of the
Disconnects the TCP connection and shuts down the socket listener
running in a thread.
:param close: Will close all sessions in the connection as well as the
tree connections of each session. | 6.139377 | 7.479328 | 0.820846 |
header = self._generate_packet_header(message, sid, tid,
credit_request)
# get the actual Session and TreeConnect object instead of the IDs
session = self.session_table.get(sid, None) if sid else None
tree = None
if tid and... | def send(self, message, sid=None, tid=None, credit_request=None) | Will send a message to the server that is passed in. The final
unencrypted header is returned to the function that called this.
:param message: An SMB message structure to send
:param sid: A session_id that the message is sent for
:param tid: A tree_id object that the message is sent fo... | 4.199358 | 3.974149 | 1.056668 |
send_data = b""
session = self.session_table[sid]
tree = session.tree_connect_table[tid]
requests = []
total_requests = len(messages)
for i, message in enumerate(messages):
if i == total_requests - 1:
next_command = 0
... | def send_compound(self, messages, sid, tid, related=False) | Sends multiple messages within 1 TCP request, will fail if the size
of the total length exceeds the maximum of the transport max.
:param messages: A list of messages to send to the server
:param sid: The session_id that the request is sent for
:param tid: A tree_id object that the messa... | 3.799263 | 3.696969 | 1.02767 |
start_time = time.time()
# check if we have received a response
while True:
self._flush_message_buffer()
status = request.response['status'].get_value() if \
request.response else None
if status is not None and (wait and
... | def receive(self, request, wait=True, timeout=None) | Polls the message buffer of the TCP connection and waits until a valid
message is received based on the message_id passed in.
:param request: The Request object to wait get the response for
:param wait: Wait for the final response in the case of a
STATUS_PENDING response, the pendin... | 3.744974 | 3.405751 | 1.099603 |
log.info("Sending Echo request with a timeout of %d and credit "
"request of %d" % (timeout, credit_request))
echo_msg = SMB2Echo()
log.debug(str(echo_msg))
req = self.send(echo_msg, sid=sid, credit_request=credit_request)
log.info("Receiving Echo resp... | def echo(self, sid=0, timeout=60, credit_request=1) | Sends an SMB2 Echo request to the server. This can be used to request
more credits from the server with the credit_request param.
On a Samba server, the sid can be 0 but for a Windows SMB Server, the
sid of an authenticated session must be passed into this function or
else the socket wi... | 3.371056 | 3.09437 | 1.089416 |
while True:
message_bytes = self.transport.receive()
# there were no messages receives, so break from the loop
if message_bytes is None:
break
# check if the message is encrypted and decrypt if necessary
if message_bytes[:4] ... | def _flush_message_buffer(self) | Loops through the transport message_buffer until there are no messages
left in the queue. Each response is assigned to the Request object
based on the message_id which are then available in
self.outstanding_requests | 3.669548 | 3.535239 | 1.037992 |
credit_size = 65536
if not self.supports_multi_credit:
credit_charge = 0
elif message.COMMAND == Commands.SMB2_READ:
max_size = message['length'].get_value() + \
message['read_channel_info_length'].get_value() - 1
credit_charge... | def _calculate_credit_charge(self, message) | Calculates the credit charge for a request based on the command. If
connection.supports_multi_credit is not True then the credit charge
isn't valid so it returns 0.
The credit charge is the number of credits that are required for
sending/receiving data over 64 kilobytes, in the existing... | 2.305194 | 2.028613 | 1.13634 |
if not self._connected:
# already disconnected so let's return
return
if close:
for open in list(self.open_table.values()):
open.close(False)
for tree in list(self.tree_connect_table.values()):
tree.disconnect()
... | def disconnect(self, close=True) | Logs off the session
:param close: Will close all tree connects in a session | 3.49579 | 3.224981 | 1.083972 |
kdf = KBKDFHMAC(
algorithm=hashes.SHA256(),
mode=Mode.CounterMode,
length=16,
rlen=4,
llen=4,
location=CounterLocation.BeforeFixed,
label=label,
context=context,
fixed=None,
backend=d... | def _smb3kdf(self, ki, label, context) | See SMB 3.x key derivation function
https://blogs.msdn.microsoft.com/openspecification/2017/05/26/smb-2-and-smb-3-security-in-windows-10-the-anatomy-of-signing-and-cryptographic-keys/
:param ki: The session key is the KDK used as an input to the KDF
:param label: The purpose of this derived key... | 3.688459 | 4.095804 | 0.900546 |
value = self._get_calculated_value(self.value)
packed_value = self._pack_value(value)
size = self._get_calculated_size(self.size, packed_value)
if len(packed_value) != size:
raise ValueError("Invalid packed data length for field %s of %d "
... | def pack(self) | Packs the field value into a byte string so it can be sent to the
server.
:param structure: The message structure class object
:return: A byte string of the packed field's value | 3.786149 | 3.856693 | 0.981709 |
parsed_value = self._parse_value(value)
self.value = parsed_value | def set_value(self, value) | Parses, and sets the value attribute for the field.
:param value: The value to be parsed and set, the allowed input types
vary depending on the Field used | 4.971091 | 5.603873 | 0.887081 |
size = self._get_calculated_size(self.size, data)
self.set_value(data[0:size])
return data[len(self):] | def unpack(self, data) | Takes in a byte string and set's the field value based on field
definition.
:param structure: The message structure class object
:param data: The byte string of the data to unpack
:return: The remaining data for subsequent fields | 6.831242 | 6.502886 | 1.050494 |
if isinstance(value, types.LambdaType):
expanded_value = value(self.structure)
return self._get_calculated_value(expanded_value)
else:
# perform one final parsing of the value in case lambda value
# returned a different type
return sel... | def _get_calculated_value(self, value) | Get's the final value of the field and runs the lambda functions
recursively until a final value is derived.
:param value: The value to calculate/expand
:return: The final value | 6.643018 | 6.488593 | 1.0238 |
# if the size is derived from a lambda function, run it now; otherwise
# return the value we passed in or the length of the data if the size
# is None (last field value)
if size is None:
return len(data)
elif isinstance(size, types.LambdaType):
ex... | def _get_calculated_size(self, size, data) | Get's the final size of the field and runs the lambda functions
recursively until a final size is derived. If size is None then it
will just return the length of the data as it is assumed it is the
final field (None should only be set on size for the final field).
:param size: The size ... | 5.433995 | 4.602952 | 1.180546 |
if isinstance(size, types.LambdaType):
size = size(self.structure)
struct_format = {
1: 'B',
2: 'H',
4: 'L',
8: 'Q'
}
if size not in struct_format.keys():
raise InvalidFieldDefinition("Cannot struct format ... | def _get_struct_format(self, size) | Get's the format specified for use in struct. This is only designed
for 1, 2, 4, or 8 byte values and will throw an exception if it is
anything else.
:param size: The size as an int
:return: The struct format specifier for the size specified | 3.663051 | 3.959809 | 0.925057 |
structs = smbprotocol.query_info
resp_structure = {
FileInformationClass.FILE_DIRECTORY_INFORMATION:
structs.FileDirectoryInformation,
FileInformationClass.FILE_NAMES_INFORMATION:
structs.FileNamesInformation,
FileInformationCl... | def unpack_response(file_information_class, buffer) | Pass in the buffer value from the response object to unpack it and
return a list of query response structures for the request.
:param buffer: The raw bytes value of the SMB2QueryDirectoryResponse
buffer field.
:return: List of query_info.* structures based on the
FileInf... | 2.392245 | 2.157133 | 1.108993 |
create = SMB2CreateRequest()
create['impersonation_level'] = impersonation_level
create['desired_access'] = desired_access
create['file_attributes'] = file_attributes
create['share_access'] = share_access
create['create_disposition'] = create_disposition
... | def create(self, impersonation_level, desired_access, file_attributes,
share_access, create_disposition, create_options,
create_contexts=None, send=True) | This will open the file based on the input parameters supplied. Any
file open should also be called with Open.close() when it is finished.
More details on how each option affects the open process can be found
here https://msdn.microsoft.com/en-us/library/cc246502.aspx.
Supports out of ... | 2.469712 | 2.446656 | 1.009423 |
if length > self.connection.max_read_size:
raise SMBException("The requested read length %d is greater than "
"the maximum negotiated read size %d"
% (length, self.connection.max_read_size))
read = SMB2ReadRequest()
... | def read(self, offset, length, min_length=0, unbuffered=False, wait=True,
send=True) | Reads from an opened file or pipe
Supports out of band send function, call this function with send=False
to return a tuple of (SMB2ReadRequest, receive_func) instead of
sending the the request and waiting for the response. The receive_func
can be used to get the response from the server... | 3.181997 | 3.057421 | 1.040745 |
data_len = len(data)
if data_len > self.connection.max_write_size:
raise SMBException("The requested write length %d is greater than "
"the maximum negotiated write size %d"
% (data_len, self.connection.max_write_size))
... | def write(self, data, offset=0, write_through=False, unbuffered=False,
wait=True, send=True) | Writes data to an opened file.
Supports out of band send function, call this function with send=False
to return a tuple of (SMBWriteRequest, receive_func) instead of
sending the the request and waiting for the response. The receive_func
can be used to get the response from the server by... | 2.423855 | 2.331074 | 1.039802 |
flush = SMB2FlushRequest()
flush['file_id'] = self.file_id
if not send:
return flush, self._flush_response
log.info("Session: %s, Tree Connect: %s - sending SMB2 Flush Request "
"for file %s" % (self.tree_connect.session.username,
... | def flush(self, send=True) | A command sent by the client to request that a server flush all cached
file information for the opened file.
Supports out of band send function, call this function with send=False
to return a tuple of (SMB2FlushRequest, receive_func) instead of
sending the the request and waiting for th... | 3.737654 | 3.584403 | 1.042755 |
query = SMB2QueryDirectoryRequest()
query['file_information_class'] = file_information_class
query['flags'] = flags
query['file_index'] = file_index
query['file_id'] = self.file_id
query['output_buffer_length'] = max_output
query['buffer'] = pattern.encod... | def query_directory(self, pattern, file_information_class, flags=None,
file_index=0, max_output=65536, send=True) | Run a Query/Find on an opened directory based on the params passed in.
Supports out of band send function, call this function with send=False
to return a tuple of (SMB2QueryDirectoryRequest, receive_func) instead
of sending the the request and waiting for the response. The
receive_func ... | 2.674908 | 2.770301 | 0.965566 |
# it is already closed and this isn't for an out of band request
if not self._connected and send:
return
close = SMB2CloseRequest()
close['file_id'] = self.file_id
if get_attributes:
close['flags'] = CloseFlags.SMB2_CLOSE_FLAG_POSTQUERY_ATTRIB
... | def close(self, get_attributes=False, send=True) | Closes an opened file.
Supports out of band send function, call this function with send=False
to return a tuple of (SMB2CloseRequest, receive_func) instead of
sending the the request and waiting for the response. The receive_func
can be used to get the response from the server by passin... | 4.778839 | 4.372494 | 1.092932 |
if not sid_string.startswith("S-"):
raise ValueError("A SID string must start with S-")
sid_entries = sid_string.split("-")
if len(sid_entries) < 3:
raise ValueError("A SID string must start with S and contain a "
"revision and ident... | def from_string(self, sid_string) | Used to set the structure parameters based on the input string
:param sid_string: String of the sid in S-x-x-x-x form | 2.948179 | 3.139393 | 0.939092 |
if not self.status["done"]:
r = Request("get", self.url + ".json", {"token": self.payload["token"]})
for param, when in MessageRequest.params.iteritems():
self.status[param] = bool(r.answer[param])
self.status[when] = int(r.answer[when])
... | def poll(self) | If the message request has a priority of 2, Pushover keeps sending
the same notification until the client acknowledges it. Calling the
:func:`poll` function fetches the status of the :class:`MessageRequest`
object until the notifications either expires, is acknowledged by the
client, or ... | 4.230202 | 4.033097 | 1.048872 |
if not Pushover._SOUNDS:
request = Request("get", SOUND_URL, {"token": self.token})
Pushover._SOUNDS = request.answer["sounds"]
return Pushover._SOUNDS | def sounds(self) | Return a dictionary of sounds recognized by Pushover and that can be
used in a notification message. | 8.380565 | 6.20283 | 1.351087 |
payload = {"user": user, "token": self.token}
if device:
payload["device"] = device
try:
request = Request("post", USER_URL, payload)
except RequestError:
return None
else:
return request.answer["devices"] | def verify(self, user, device=None) | Verify that the `user` and optional `device` exist. Returns
`None` when the user/device does not exist or a list of the user's
devices otherwise. | 5.426257 | 4.670197 | 1.16189 |
payload = {"message": message, "user": user, "token": self.token}
for key, value in kwargs.iteritems():
if key not in Pushover.message_keywords:
raise ValueError("{0}: invalid message parameter".format(key))
elif key == "timestamp" and value is True:
... | def message(self, user, message, **kwargs) | Send `message` to the user specified by `user`. It is possible
to specify additional properties of the message by passing keyword
arguments. The list of valid keywords is ``title, priority, sound,
callback, timestamp, url, url_title, device, retry, expire and html``
which are described i... | 3.469647 | 2.609223 | 1.329762 |
payload = {"user": user, "token": self.token}
for key, value in kwargs.iteritems():
if key not in Pushover.glance_keywords:
raise ValueError("{0}: invalid glance parameter".format(key))
else:
payload[key] = value
return Request("... | def glance(self, user, **kwargs) | Send a glance to the user. The default property is ``text``, as this
is used on most glances, however a valid glance does not need to
require text and can be constructed using any combination of valid
keyword properties. The list of valid keywords is ``title, text,
subtext, count, percen... | 4.961055 | 3.644927 | 1.361085 |
# Ensure inputs are numpy arrays
w = np.array(w)
v = np.array(v)
# Check dimensions
if(len(w.shape) != 2):
raise TypeError('Estimated coefficients must be in NxM matrix')
if(len(v.shape) != 1):
raise TypeError('Real coefficients must be in 1d array')
# Ensure equal lengt... | def mswe(w, v) | Calculate mean squared weight error between estimated and true filter
coefficients, in respect to iterations.
Parameters
----------
v : array-like
True coefficients used to generate desired signal, must be a
one-dimensional array.
w : array-like
Estimated coefficients from a... | 3.145776 | 2.807203 | 1.120609 |
adb_full_cmd = [v.ADB_COMMAND_PREFIX, v.ADB_COMMAND_BUGREPORT]
try:
dest_file_handler = open(dest_file, "w")
except IOError:
print("IOError: Failed to create a log file")
# We have to check if device is available or not before executing this command
# as adb bugreport will ... | def bugreport(dest_file="default.log") | Prints dumpsys, dumpstate, and logcat data to the screen, for the purposes of bug reporting
:return: result of _exec_command() execution | 6.422838 | 6.267801 | 1.024735 |
adb_full_cmd = [v.ADB_COMMAND_PREFIX, v.ADB_COMMAND_PUSH, src, dest]
return _exec_command(adb_full_cmd) | def push(src, dest) | Push object from host to target
:param src: string path to source object on host
:param dest: string destination path on target
:return: result of _exec_command() execution | 5.991015 | 5.548427 | 1.079768 |
adb_full_cmd = [v.ADB_COMMAND_PREFIX, v.ADB_COMMAND_PULL, src, dest]
return _exec_command(adb_full_cmd) | def pull(src, dest) | Pull object from target to host
:param src: string path of object on target
:param dest: string destination path on host
:return: result of _exec_command() execution | 6.087822 | 5.493781 | 1.10813 |
adb_full_cmd = [v.ADB_COMMAND_PREFIX, v.ADB_COMMAND_DEVICES, _convert_opts(opts)]
return _exec_command(adb_full_cmd) | def devices(opts=[]) | Get list of all available devices including emulators
:param opts: list command options (e.g. ["-r", "-a"])
:return: result of _exec_command() execution | 6.638703 | 6.566708 | 1.010964 |
adb_full_cmd = [v.ADB_COMMAND_PREFIX, v.ADB_COMMAND_SHELL, cmd]
return _exec_command(adb_full_cmd) | def shell(cmd) | Execute shell command on target
:param cmd: string shell command to execute
:return: result of _exec_command() execution | 6.16681 | 5.747232 | 1.073005 |
adb_full_cmd = [v.ADB_COMMAND_PREFIX, v.ADB_COMMAND_INSTALL, _convert_opts(opts), apk]
return _exec_command(adb_full_cmd) | def install(apk, opts=[]) | Install *.apk on target
:param apk: string path to apk on host to install
:param opts: list command options (e.g. ["-r", "-a"])
:return: result of _exec_command() execution | 6.200609 | 5.610373 | 1.105205 |
adb_full_cmd = [v.ADB_COMMAND_PREFIX, v.ADB_COMMAND_UNINSTALL, _convert_opts(opts), app]
return _exec_command(adb_full_cmd) | def uninstall(app, opts=[]) | Uninstall app from target
:param app: app name to uninstall from target (e.g. "com.example.android.valid")
:param opts: list command options (e.g. ["-r", "-a"])
:return: result of _exec_command() execution | 7.016722 | 5.995275 | 1.170375 |
adb_full_cmd = [v.ADB_COMMAND_PREFIX, v.ADB_COMMAND_SHELL ,v.ADB_COMMAND_SYNC]
return _exec_command(adb_full_cmd) | def sync() | Copy host->device only if changed
:return: result of _exec_command() execution | 6.946085 | 5.91874 | 1.173575 |
t = tempfile.TemporaryFile()
final_adb_cmd = []
for e in adb_cmd:
if e != '': # avoid items with empty string...
final_adb_cmd.append(e) # ... so that final command doesn't
# contain extra spaces
print('\n*** Executing ' + ' '.join(adb_cmd) + ' ' + 'command')
... | def _exec_command(adb_cmd) | Format adb command and execute it in shell
:param adb_cmd: list adb command to execute
:return: string '0' and shell command output if successful, otherwise
raise CalledProcessError exception and return error code | 4.371 | 4.29271 | 1.018238 |
t = tempfile.TemporaryFile()
final_adb_cmd = []
for e in adb_cmd:
if e != '': # avoid items with empty string...
final_adb_cmd.append(e) # ... so that final command doesn't
# contain extra spaces
print('\n*** Executing ' + ' '.join(adb_cmd) + ' ' + 'command')
... | def _exec_command_to_file(adb_cmd, dest_file_handler) | Format adb command and execute it in shell and redirects to a file
:param adb_cmd: list adb command to execute
:param dest_file_handler: file handler to which output will be redirected
:return: string '0' and writes shell command output to file if successful, otherwise
raise CalledProcessError exception... | 4.429555 | 4.234411 | 1.046085 |
"Detects if the data was changed. This is added in 1.6."
if initial is None and data is None:
return False
if data and not hasattr(data, '__iter__'):
data = self.widget.decompress(data)
initial = self.to_python(initial)
data = self.to_python(data)
... | def has_changed(self, initial, data) | Detects if the data was changed. This is added in 1.6. | 3.881357 | 3.019745 | 1.285326 |
# Wrap function to maintian the original doc string, etc
@wraps(func)
def decorator(lookup_cls):
# Construct a class decorator from the original function
original = lookup_cls.results
def inner(self, request):
# Wrap lookup_cls.results by first calling func and check... | def results_decorator(func) | Helper for constructing simple decorators around Lookup.results.
func is a function which takes a request as the first parameter. If func
returns an HttpReponse it is returned otherwise the original Lookup.results
is returned. | 6.023503 | 5.072611 | 1.187456 |
"Lookup decorator to require the user to be authenticated."
user = getattr(request, 'user', None)
if user is None or not user.is_authenticated:
return HttpResponse(status=401) | def login_required(request) | Lookup decorator to require the user to be authenticated. | 4.252019 | 2.777143 | 1.531077 |
"Lookup decorator to require the user is a staff member."
user = getattr(request, 'user', None)
if user is None or not user.is_authenticated:
return HttpResponse(status=401) # Unauthorized
elif not user.is_staff:
return HttpResponseForbidden() | def staff_member_required(request) | Lookup decorator to require the user is a staff member. | 3.867361 | 2.835388 | 1.363962 |
"Construct result dictionary for the match item."
result = {
'id': self.get_item_id(item),
'value': self.get_item_value(item),
'label': self.get_item_label(item),
}
for key in settings.SELECTABLE_ESCAPED_KEYS:
if key in result:
... | def format_item(self, item) | Construct result dictionary for the match item. | 4.420635 | 3.287766 | 1.344571 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.