text_prompt stringlengths 157 13.1k | code_prompt stringlengths 7 19.8k ⌀ |
|---|---|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def nl_cb_err(cb, kind, func, arg):
"""Set up an error callback. Updates `cb` in place. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/handlers.c#L343 Pos... |
if kind < 0 or kind > NL_CB_KIND_MAX:
return -NLE_RANGE
if kind == NL_CB_CUSTOM:
cb.cb_err = func
cb.cb_err_arg = arg
else:
cb.cb_err = cb_err_def[kind]
cb.cb_err_arg = arg
return 0 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ifi_index(self, value):
"""Index setter.""" |
self.bytearray[self._get_slicers(3)] = bytearray(c_int(value or 0)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ifi_change(self, value):
"""Change setter.""" |
self.bytearray[self._get_slicers(5)] = bytearray(c_uint(value or 0)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _class_factory(base):
"""Create subclasses of ctypes. Positional arguments: base -- base class to subclass. Returns: New class definition. """ |
class ClsPyPy(base):
def __repr__(self):
return repr(base(super(ClsPyPy, self).value))
@classmethod
def from_buffer(cls, ba):
try:
integer = struct.unpack_from(getattr(cls, '_type_'), ba)[0]
except struct.error:
len_ = len... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pid(self, value):
"""Process ID setter.""" |
self.bytearray[self._get_slicers(0)] = bytearray(c_int32(value or 0)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def uid(self, value):
"""User ID setter.""" |
self.bytearray[self._get_slicers(1)] = bytearray(c_int32(value or 0)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def gid(self, value):
"""Group ID setter.""" |
self.bytearray[self._get_slicers(2)] = bytearray(c_int32(value or 0)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def put_skeleton_files_on_disk(metadata_type, where, github_template=None, params={}):
""" Generates file based on jinja2 templates """ |
api_name = params["api_name"]
file_name = github_template["file_name"]
template_source = config.connection.get_plugin_client_setting('mm_template_source', 'joeferraro/MavensMate-Templates/master')
template_location = config.connection.get_plugin_client_setting('mm_template_location', 'remote')
try... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def genl_ctrl_probe_by_name(sk, name):
"""Look up generic Netlink family by family name querying the kernel directly. https://github.com/thom311/libnl/blob/libnl... |
ret = genl_family_alloc()
if not ret:
return None
genl_family_set_name(ret, name)
msg = nlmsg_alloc()
orig = nl_socket_get_cb(sk)
cb = nl_cb_clone(orig)
genlmsg_put(msg, NL_AUTO_PORT, NL_AUTO_SEQ, GENL_ID_CTRL, 0, 0, CTRL_CMD_GETFAMILY, 1)
nla_put_string(msg, CTRL_ATTR_FAMILY_N... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def genl_ctrl_resolve(sk, name):
"""Resolve Generic Netlink family name to numeric identifier. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/genl/ctrl.c#... |
family = genl_ctrl_probe_by_name(sk, name)
if family is None:
return -NLE_OBJ_NOTFOUND
return int(genl_family_get_id(family)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def genl_ctrl_resolve_grp(sk, family_name, grp_name):
"""Resolve Generic Netlink family group name. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/genl/ct... |
family = genl_ctrl_probe_by_name(sk, family_name)
if family is None:
return -NLE_OBJ_NOTFOUND
return genl_ctrl_grp_by_name(family, grp_name) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _safe_read(path, length):
"""Read file contents.""" |
if not os.path.exists(os.path.join(HERE, path)):
return ''
file_handle = codecs.open(os.path.join(HERE, path), encoding='utf-8')
contents = file_handle.read(length)
file_handle.close()
return contents |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def error_handler(_, err, arg):
"""Update the mutable integer `arg` with the error code.""" |
arg.value = err.error
return libnl.handlers.NL_STOP |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def callback_trigger(msg, arg):
"""Called when the kernel is done scanning. Only signals if it was successful or if it failed. No other data. Positional argument... |
gnlh = genlmsghdr(nlmsg_data(nlmsg_hdr(msg)))
if gnlh.cmd == nl80211.NL80211_CMD_SCAN_ABORTED:
arg.value = 1 # The scan was aborted for some reason.
elif gnlh.cmd == nl80211.NL80211_CMD_NEW_SCAN_RESULTS:
arg.value = 0 # The scan completed successfully. `callback_dump` will collect the res... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def callback_dump(msg, results):
"""Here is where SSIDs and their data is decoded from the binary data sent by the kernel. This function is called once per SSID.... |
bss = dict() # To be filled by nla_parse_nested().
# First we must parse incoming data into manageable chunks and check for errors.
gnlh = genlmsghdr(nlmsg_data(nlmsg_hdr(msg)))
tb = dict((i, None) for i in range(nl80211.NL80211_ATTR_MAX + 1))
nla_parse(tb, nl80211.NL80211_ATTR_MAX, genlmsg_attrd... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def do_scan_trigger(sk, if_index, driver_id, mcid):
"""Issue a scan request to the kernel and wait for it to reply with a signal. This function issues NL80211_CM... |
# First get the "scan" membership group ID and join the socket to the group.
_LOGGER.debug('Joining group %d.', mcid)
ret = nl_socket_add_membership(sk, mcid) # Listen for results of scan requests (aborted or new results).
if ret < 0:
return ret
# Build the message to be sent to the kerne... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def eta_letters(seconds):
"""Convert seconds remaining into human readable strings. From https://github.com/Robpol86/etaprogress/blob/ad934d4/etaprogress/compone... |
final_days, final_hours, final_minutes, final_seconds = 0, 0, 0, seconds
if final_seconds >= 86400:
final_days = int(final_seconds / 86400.0)
final_seconds -= final_days * 86400
if final_seconds >= 3600:
final_hours = int(final_seconds / 3600.0)
final_seconds -= final_hours ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def print_table(data):
"""Print the table of detected SSIDs and their data to screen. Positional arguments: data -- list of dictionaries. """ |
table = AsciiTable([COLUMNS])
table.justify_columns[2] = 'right'
table.justify_columns[3] = 'right'
table.justify_columns[4] = 'right'
table_data = list()
for row_in in data:
row_out = [
str(row_in.get('ssid', '')).replace('\0', ''),
str(row_in.get('security', ''... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def generateObject(self, sObjectType):
'''
Generate a Salesforce object, such as a Lead or Contact
'''
obj = self._sforce.factory.create('ens:sObject')
obj.type = sObjectType
return obj |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _marshallSObjects(self, sObjects, tag = 'sObjects'):
'''
Marshall generic sObjects into a list of SAX elements
This code is going away ASAP
tag param is for nested objects (e.g. MergeRequest) where
key: object must be in <key/>, not <sObjects/>
'''
if not isinstance(sObjects, (tuple, l... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _setHeaders(self, call = None, **kwargs):
'''
Attach particular SOAP headers to the request depending on the method call made
'''
# All calls, including utility calls, set the session header
headers = {'SessionHeader': self._sessionHeader}
if 'debug_categories' in kwargs:
#ERROR, WARN... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def invalidateSessions(self, sessionIds):
'''
Invalidate a Salesforce session
This should be used with extreme caution, for the following (undocumented) reason:
All API connections for a given user share a single session ID
This will call logout() WHICH LOGS OUT THAT USER FROM EVERY CONCURRENT SESS... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def query(self, queryString):
'''
Executes a query against the specified object and returns data that matches
the specified criteria.
'''
self._setHeaders('query')
return self._sforce.service.query(queryString) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def queryAll(self, queryString):
'''
Retrieves data from specified objects, whether or not they have been deleted.
'''
self._setHeaders('queryAll')
return self._sforce.service.queryAll(queryString) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def queryMore(self, queryLocator):
'''
Retrieves the next batch of objects from a query.
'''
self._setHeaders('queryMore')
return self._sforce.service.queryMore(queryLocator) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def resetPassword(self, userId):
'''
Changes a user's password to a system-generated value.
'''
self._setHeaders('resetPassword')
return self._sforce.service.resetPassword(userId) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def setPassword(self, userId, password):
'''
Sets the specified user's password to the specified value.
'''
self._setHeaders('setPassword')
return self._sforce.service.setPassword(userId, password) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def nl_msgtype_lookup(ops, msgtype):
"""Lookup message type cache association. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/cache_mngt.c#L189 Searches f... |
for i in ops.co_msgtypes:
if i.mt_id == msgtype:
return i
return None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def nl_cache_mngt_register(ops):
"""Register a set of cache operations. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/cache_mngt.c#L252 Called by users o... |
global cache_ops
if not ops.co_name or not ops.co_obj_ops:
return -NLE_INVAL
with cache_ops_lock:
if _nl_cache_ops_lookup(ops.co_name):
return -NLE_EXIST
ops.co_refcnt = 0
ops.co_next = cache_ops
cache_ops = ops
_LOGGER.debug('Registered cache oper... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def nl_connect(sk, protocol):
"""Create file descriptor and bind socket. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/nl.c#L96 Creates a new Netlink soc... |
flags = getattr(socket, 'SOCK_CLOEXEC', 0)
if sk.s_fd != -1:
return -NLE_BAD_SOCK
try:
sk.socket_instance = socket.socket(getattr(socket, 'AF_NETLINK', -1), socket.SOCK_RAW | flags, protocol)
except OSError as exc:
return -nl_syserr2nlerr(exc.errno)
if not sk.s_flags & NL_S... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def nl_complete_msg(sk, msg):
"""Finalize Netlink message. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/nl.c#L450 This function finalizes a Netlink mess... |
nlh = msg.nm_nlh
if nlh.nlmsg_pid == NL_AUTO_PORT:
nlh.nlmsg_pid = nl_socket_get_local_port(sk)
if nlh.nlmsg_seq == NL_AUTO_SEQ:
nlh.nlmsg_seq = sk.s_seq_next
sk.s_seq_next += 1
if msg.nm_protocol == -1:
msg.nm_protocol = sk.s_proto
nlh.nlmsg_flags |= NLM_F_REQUEST
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def nl_send_simple(sk, type_, flags, buf=None, size=0):
"""Construct and transmit a Netlink message. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/nl.c#L... |
msg = nlmsg_alloc_simple(type_, flags)
if buf is not None and size:
err = nlmsg_append(msg, buf, size, NLMSG_ALIGNTO)
if err < 0:
return err
return nl_send_auto(sk, msg) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def nl_recv(sk, nla, buf, creds=None):
"""Receive data from Netlink socket. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/nl.c#L625 Receives data from a ... |
flags = 0
page_size = resource.getpagesize() * 4
if sk.s_flags & NL_MSG_PEEK:
flags |= socket.MSG_PEEK | socket.MSG_TRUNC
iov_len = sk.s_bufsize or page_size
if creds and sk.s_flags & NL_SOCK_PASSCRED:
raise NotImplementedError # TODO https://github.com/Robpol86/libnl/issues/2
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def nl_recvmsgs_report(sk, cb):
"""Receive a set of messages from a Netlink socket and report parsed messages. https://github.com/thom311/libnl/blob/libnl3_2_25/... |
if cb.cb_recvmsgs_ow:
return int(cb.cb_recvmsgs_ow(sk, cb))
return int(recvmsgs(sk, cb)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def nl_recvmsgs(sk, cb):
"""Receive a set of messages from a Netlink socket. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/nl.c#L1023 Repeatedly calls nl... |
err = nl_recvmsgs_report(sk, cb)
if err > 0:
return 0
return int(err) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def nl_wait_for_ack(sk):
"""Wait for ACK. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/nl.c#L1058 Waits until an ACK is received for the latest not yet ... |
cb = nl_cb_clone(sk.s_cb)
nl_cb_set(cb, NL_CB_ACK, NL_CB_CUSTOM, lambda *_: NL_STOP, None)
return int(nl_recvmsgs(sk, cb)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def get_plugin_client_settings(self):
settings = {}
user_path = self.get_plugin_settings_path("User")
def_path = self.get_plugin_settings_path("MavensMate")
'''
if the default path for settings is none, we're either dealing with a bad client setup or
a new client... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def nlmsg_for_each_attr(nlh, hdrlen, rem):
"""Iterate over a stream of attributes in a message. https://github.com/thom311/libnl/blob/libnl3_2_25/include/netlink... |
return nla_for_each_attr(nlmsg_attrdata(nlh, hdrlen), nlmsg_attrlen(nlh, hdrlen), rem) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def nlmsg_attrdata(nlh, hdrlen):
"""Head of attributes data. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/msg.c#L143 Positional arguments: nlh -- Netlin... |
data = nlmsg_data(nlh)
return libnl.linux_private.netlink.nlattr(bytearray_ptr(data, libnl.linux_private.netlink.NLMSG_ALIGN(hdrlen))) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def nlmsg_attrlen(nlh, hdrlen):
"""Length of attributes data. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/msg.c#L154 nlh -- Netlink message header (nlm... |
return max(nlmsg_len(nlh) - libnl.linux_private.netlink.NLMSG_ALIGN(hdrlen), 0) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def nlmsg_ok(nlh, remaining):
"""Check if the Netlink message fits into the remaining bytes. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/msg.c#L179 Pos... |
sizeof = libnl.linux_private.netlink.nlmsghdr.SIZEOF
return remaining.value >= sizeof and sizeof <= nlh.nlmsg_len <= remaining.value |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def nlmsg_next(nlh, remaining):
"""Next Netlink message in message stream. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/msg.c#L194 Positional arguments:... |
totlen = libnl.linux_private.netlink.NLMSG_ALIGN(nlh.nlmsg_len)
remaining.value -= totlen
return libnl.linux_private.netlink.nlmsghdr(bytearray_ptr(nlh.bytearray, totlen)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def nlmsg_parse(nlh, hdrlen, tb, maxtype, policy):
"""Parse attributes of a Netlink message. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/msg.c#L213 Pos... |
if not nlmsg_valid_hdr(nlh, hdrlen):
return -NLE_MSG_TOOSHORT
return nla_parse(tb, maxtype, nlmsg_attrdata(nlh, hdrlen), nlmsg_attrlen(nlh, hdrlen), policy) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def nlmsg_find_attr(nlh, hdrlen, attrtype):
"""Find a specific attribute in a Netlink message. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/msg.c#L231 P... |
return nla_find(nlmsg_attrdata(nlh, hdrlen), nlmsg_attrlen(nlh, hdrlen), attrtype) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def nlmsg_alloc(len_=default_msg_size):
"""Allocate a new Netlink message with maximum payload size specified. https://github.com/thom311/libnl/blob/libnl3_2_25/... |
len_ = max(libnl.linux_private.netlink.nlmsghdr.SIZEOF, len_)
nm = nl_msg()
nm.nm_refcnt = 1
nm.nm_nlh = libnl.linux_private.netlink.nlmsghdr(bytearray(b'\0') * len_)
nm.nm_protocol = -1
nm.nm_size = len_
nm.nm_nlh.nlmsg_len = nlmsg_total_size(0)
_LOGGER.debug('msg 0x%x: Allocated new m... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def nlmsg_inherit(hdr=None):
"""Allocate a new Netlink message and inherit Netlink message header. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/msg.c#L3... |
nm = nlmsg_alloc()
if hdr:
new = nm.nm_nlh
new.nlmsg_type = hdr.nlmsg_type
new.nlmsg_flags = hdr.nlmsg_flags
new.nlmsg_seq = hdr.nlmsg_seq
new.nlmsg_pid = hdr.nlmsg_pid
return nm |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def nlmsg_alloc_simple(nlmsgtype, flags):
"""Allocate a new Netlink message. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/msg.c#L346 Positional argument... |
nlh = libnl.linux_private.netlink.nlmsghdr(nlmsg_type=nlmsgtype, nlmsg_flags=flags)
msg = nlmsg_inherit(nlh)
_LOGGER.debug('msg 0x%x: Allocated new simple message', id(msg))
return msg |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def nlmsg_convert(hdr):
"""Convert a Netlink message received from a Netlink socket to an nl_msg. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/msg.c#L38... |
nm = nlmsg_alloc(hdr.nlmsg_len)
if not nm:
return None
nm.nm_nlh.bytearray = hdr.bytearray.copy()[:hdr.nlmsg_len]
return nm |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def nlmsg_reserve(n, len_, pad):
"""Reserve room for additional data in a Netlink message. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/msg.c#L407 Reser... |
nlmsg_len_ = n.nm_nlh.nlmsg_len
tlen = len_ if not pad else ((len_ + (pad - 1)) & ~(pad - 1))
if tlen + nlmsg_len_ > n.nm_size:
return None
buf = bytearray_ptr(n.nm_nlh.bytearray, nlmsg_len_)
n.nm_nlh.nlmsg_len += tlen
if tlen > len_:
bytearray_ptr(buf, len_, tlen)[:] = bytear... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def nlmsg_append(n, data, len_, pad):
"""Append data to tail of a Netlink message. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/msg.c#L442 Extends the N... |
tmp = nlmsg_reserve(n, len_, pad)
if tmp is None:
return -NLE_NOMEM
tmp[:len_] = data.bytearray[:len_]
_LOGGER.debug('msg 0x%x: Appended %d bytes with padding %d', id(n), len_, pad)
return 0 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def nlmsg_put(n, pid, seq, type_, payload, flags):
"""Add a Netlink message header to a Netlink message. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/ms... |
if n.nm_nlh.nlmsg_len < libnl.linux_private.netlink.NLMSG_HDRLEN:
raise BUG
nlh = n.nm_nlh
nlh.nlmsg_type = type_
nlh.nlmsg_flags = flags
nlh.nlmsg_pid = pid
nlh.nlmsg_seq = seq
_LOGGER.debug('msg 0x%x: Added netlink header type=%d, flags=%d, pid=%d, seq=%d', id(n), type_, flags, ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def nl_nlmsg_flags2str(flags, buf, _=None):
"""Netlink Message Flags Translations. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/msg.c#L664 Positional ar... |
del buf[:]
all_flags = (
('REQUEST', libnl.linux_private.netlink.NLM_F_REQUEST),
('MULTI', libnl.linux_private.netlink.NLM_F_MULTI),
('ACK', libnl.linux_private.netlink.NLM_F_ACK),
('ECHO', libnl.linux_private.netlink.NLM_F_ECHO),
('ROOT', libnl.linux_private.netlink.NLM... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def dump_hex(ofd, start, len_, prefix=0):
"""Convert `start` to hex and logs it, 16 bytes per log statement. https://github.com/thom311/libnl/blob/libnl3_2_25/li... |
prefix_whitespaces = ' ' * prefix
limit = 16 - (prefix * 2)
start_ = start[:len_]
for line in (start_[i:i + limit] for i in range(0, len(start_), limit)): # stackoverflow.com/a/9475354/1198943
hex_lines, ascii_lines = list(), list()
for c in line:
hex_lines.append('{0:02x}... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def nl_msg_dump(msg, ofd=_LOGGER.debug):
"""Dump message in human readable format to callable. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/msg.c#L970 P... |
hdr = nlmsg_hdr(msg)
ofd('-------------------------- BEGIN NETLINK MESSAGE ---------------------------')
ofd(' [NETLINK HEADER] %d octets', hdr.SIZEOF)
print_hdr(ofd, msg)
if hdr.nlmsg_type == libnl.linux_private.netlink.NLMSG_ERROR:
dump_error_msg(msg, ofd)
elif nlmsg_len(hdr) > ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def nl_object_alloc(ops):
"""Allocate a new object of kind specified by the operations handle. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/object.c#L54... |
new = nl_object()
nl_init_list_head(new.ce_list)
new.ce_ops = ops
if ops.oo_constructor:
ops.oo_constructor(new)
_LOGGER.debug('Allocated new object 0x%x', id(new))
return new |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def genl_register_family(ops):
"""Register Generic Netlink family and associated commands. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/genl/mngt.c#L164... |
if not ops.o_name or (ops.o_cmds and ops.o_ncmds <= 0):
return -NLE_INVAL
if ops.o_id and lookup_family(ops.o_id):
return -NLE_EXIST
if lookup_family_by_name(ops.o_name):
return -NLE_EXIST
nl_list_add_tail(ops.o_list, genl_ops_list)
return 0 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def genl_register(ops):
"""Register Generic Netlink family backed cache. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/genl/mngt.c#L241 Same as genl_regi... |
if ops.co_protocol != NETLINK_GENERIC:
return -NLE_PROTO_MISMATCH
if ops.co_hdrsize < GENL_HDRSIZE(0):
return -NLE_INVAL
if ops.co_genl is None:
return -NLE_INVAL
ops.co_genl.o_cache_ops = ops
ops.co_genl.o_hdrsize = ops.co_hdrsize - GENL_HDRLEN
ops.co_genl.o_name = ops... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def __setup_connection(self):
""" each operation requested represents a session the session holds information about the plugin running it and establishes a proje... |
if self.payload != None and type(self.payload) is dict and 'settings' in self.payload:
config.plugin_client_settings = self.payload['settings']
config.offline = self.args.offline
config.connection = PluginConnection(
client=self.args.client or 'SUBLIME_TEXT_3',
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def execute(self):
""" Executes requested command """ |
try:
self.__setup_connection()
#if the arg switch argument is included, the request is to launch the out of box
#MavensMate UI, so we generate the HTML for the UI and launch the process
#example: mm -o new_project --ui
if self.args.ui_switch == True:... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_alert(self, alert):
""" Recieves a day as an argument and returns the prediction for that alert if is available. If not, function will return None. """ |
if alert > self.alerts_count() or self.alerts_count() is None:
return None
else:
return self.get()[alert-1] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_forecast(self, latitude, longitude):
""" Gets the weather data from darksky api and stores it in the respective dictionaries if available. This function ... |
reply = self.http_get(self.url_builder(latitude, longitude))
self.forecast = json.loads(reply)
for item in self.forecast.keys():
setattr(self, item, self.forecast[item]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_forecast_fromstr(self, reply):
""" Gets the weather data from a darksky api response string and stores it in the respective dictionaries if available. Th... |
self.forecast = json.loads(reply)
for item in self.forecast.keys():
setattr(self, item, self.forecast[item]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def url_builder(self, latitude, longitude):
""" This function is used to build the correct url to make the request to the forecast.io api. Recieves the latitude ... |
try:
float(latitude)
float(longitude)
except TypeError:
raise TypeError('Latitude (%s) and Longitude (%s) must be a float number' % (latitude, longitude))
url = self._darksky_url + self.forecast_io_api_key + '/'
url += str(latitude).strip() + ',' + st... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def http_get(self, request_url):
""" This function recieves the request url and it is used internally to get the information via http. Returns the response conte... |
try:
headers = {'Accept-Encoding': 'gzip, deflate'}
response = requests.get(request_url, headers=headers)
except requests.exceptions.Timeout as ext:
log.error('Error: Timeout', ext)
except requests.exceptions.TooManyRedirects as extmr:
log.error('... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _map_or_starmap(function, iterable, args, kwargs, map_or_starmap):
""" Shared function between parmap.map and parmap.starmap. Refer to those functions for de... |
arg_newarg = (("parallel", "pm_parallel"), ("chunksize", "pm_chunksize"),
("pool", "pm_pool"), ("processes", "pm_processes"),
("parmap_progress", "pm_pbar"))
kwargs = _deprecated_kwargs(kwargs, arg_newarg)
chunksize = kwargs.pop("pm_chunksize", None)
progress = kwarg... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _map_or_starmap_async(function, iterable, args, kwargs, map_or_starmap):
""" Shared function between parmap.map_async and parmap.starmap_async. Refer to thos... |
arg_newarg = (("parallel", "pm_parallel"), ("chunksize", "pm_chunksize"),
("pool", "pm_pool"), ("processes", "pm_processes"),
("callback", "pm_callback"),
("error_callback", "pm_error_callback"))
kwargs = _deprecated_kwargs(kwargs, arg_newarg)
chunksize... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def map_async(function, iterable, *args, **kwargs):
"""This function is the multiprocessing.Pool.map_async version that supports multiple arguments. :param pm_pa... |
return _map_or_starmap_async(function, iterable, args, kwargs, "map") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def starmap_async(function, iterables, *args, **kwargs):
"""This function is the multiprocessing.Pool.starmap_async version that supports multiple arguments. :pa... |
return _map_or_starmap_async(function, iterables, args, kwargs, "starmap") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def lookup_domain(domain, nameservers=[], rtype="A", exclude_nameservers=[], timeout=2):
"""Wrapper for DNSQuery method""" |
dns_exp = DNSQuery(domains=[domain], nameservers=nameservers, rtype=rtype,
exclude_nameservers=exclude_nameservers, timeout=timeout)
return dns_exp.lookup_domain(domain) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parse_out_ips(message):
"""Given a message, parse out the ips in the answer""" |
ips = []
for entry in message.answer:
for rdata in entry.items:
ips.append(rdata.to_text())
return ips |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def send_chaos_queries(self):
"""Send chaos queries to identify the DNS server and its manufacturer Note: we send 2 queries for BIND stuff per RFC 4892 and 1 que... |
names = ["HOSTNAME.BIND", "VERSION.BIND", "ID.SERVER"]
self.results = {'exp-name': "chaos-queries"}
for name in names:
self.results[name] = {}
for nameserver in self.nameservers:
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def lookup_domains(self):
"""More complex DNS primitive that looks up domains concurrently Note: if you want to lookup multiple domains, you should use this func... |
thread_error = False
thread_wait_timeout = 200
ind = 1
total_item_count = len(self.domains)
for domain in self.domains:
for nameserver in self.nameservers:
wait_time = 0
while threading.active_count() > self.max_threads:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def start(self, timeout=None):
"""Start running the command""" |
self.thread.start()
start_time = time.time()
if not timeout:
timeout = self.timeout
# every second, check the condition of the thread and return
# control to the user if appropriate
while start_time + timeout > time.time():
self.thread.join(1)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def stop(self, timeout=None):
"""Stop the given command""" |
if not timeout:
timeout = self.timeout
self.kill_switch()
# Send the signal to all the process groups
self.process.kill()
self.thread.join(timeout)
try:
os.killpg(os.getpgid(self.process.pid), signal.SIGTERM)
except:
pass
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def traceroute_batch(input_list, results={}, method="udp", cmd_arguments=None, delay_time=0.1, max_threads=100):
""" This is a parallel version of the traceroute... |
threads = []
thread_error = False
thread_wait_timeout = 200
ind = 1
total_item_count = len(input_list)
for domain in input_list:
wait_time = 0
while threading.active_count() > max_threads:
time.sleep(1)
wait_time += 1
if wait_time > thread_wai... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _traceroute_callback(self, line, kill_switch):
""" Callback function to handle traceroute. :param self: :param line: :param kill_switch: :return: """ |
line = line.lower()
if "traceroute to" in line:
self.started = True
# need to run as root but not running as root.
# usually happens when doing TCP and ICMP traceroute.
if "enough privileges" in line:
self.error = True
self.kill_switch()
self.stopped = True
# na... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def output_callback(self, line, kill_switch):
"""Set status of openvpn according to what we process""" |
self.notifications += line + "\n"
if "Initialization Sequence Completed" in line:
self.started = True
if "ERROR:" in line or "Cannot resolve host address:" in line:
self.error = True
if "process exiting" in line:
self.stopped = True |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def load_experiments(self):
"""This function will return the list of experiments. """ |
logging.debug("Loading experiments.")
# look for experiments in experiments directory
exp_dir = self.config['dirs']['experiments_dir']
for path in glob.glob(os.path.join(exp_dir, '[!_]*.py')):
# get name of file and path
name, ext = os.path.splitext(os.path.basen... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _tcpdump_callback(self, line, kill_switch):
"""Callback function to handle tcpdump""" |
line = line.lower()
if ("listening" in line) or ("reading" in line):
self.started = True
if ("no suitable device" in line):
self.error = True
self.kill_switch()
if "by kernel" in line:
self.stopped = True |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _run():
"""Entry point for package and cli uses""" |
args = parse_args()
# parse custom parameters
custom_meta = None
if args.custom_meta:
print "Adding custom parameters:"
custom_meta = {}
try:
for item in args.custom_meta.split(','):
key, value = item.split(':')
custom_meta[key] = va... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_fingerprint_batch(input_list, results={}, default_port=443, delay_time=0.5, max_threads=100):
""" This is a parallel version of the TLS fingerprint primi... |
threads = []
thread_error = False
thread_wait_timeout = 200
ind = 1
total_item_count = len(input_list)
for row in input_list:
if len(row.split(":")) == 2:
host, port = row.split(":")
elif len(row.split(":")) == 1:
host = row
port = default_por... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def meta_redirect(content):
""" Returns redirecting URL if there is a HTML refresh meta tag, returns None otherwise :param content: HTML content """ |
decoded = content.decode("utf-8", errors="replace")
try:
soup = BeautifulSoup.BeautifulSoup(decoded)
except Exception as e:
return None
result = soup.find("meta", attrs={"http-equiv": re.compile("^refresh$", re.I)})
if result:
try:
wait, text = result["content"... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_http_request(netloc, path="/", headers=None, ssl=False):
""" Actually gets the http. Moved this to it's own private method since it is called several ti... |
if ssl:
port = 443
else:
port = 80
host = netloc
if len(netloc.split(":")) == 2:
host, port = netloc.split(":")
request = {"host": host,
"port": port,
"path": path,
"ssl": ssl,
"method": "GET"}
if headers:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_requests_batch(input_list, results={}, delay_time=0.5, max_threads=100):
""" This is a parallel version of the HTTP GET primitive. :param input_list: the... |
threads = []
thread_error = False
thread_wait_timeout = 200
ind = 1
total_item_count = len(input_list)
# randomly select one user agent for one input list
user_agent = random.choice(user_agent_pool)
for row in input_list:
headers = {}
path = "/"
ssl = False
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create_script_for_location(content, destination):
"""Create a script with the given content, mv it to the destination, and make it executable Parameters: con... |
temp = tempfile.NamedTemporaryFile(mode='w', delete=False)
temp.write(content)
temp.close()
shutil.move(temp.name, destination)
cur_perms = os.stat(destination).st_mode
set_perms = cur_perms | stat.S_IXOTH | stat.S_IXGRP | stat.S_IXUSR
os.chmod(destination, set_perms) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def daemonize(package, bin_loc, user):
"""Create crontab entries to run centinel every hour and autoupdate every day Parameters: package- name of the currently i... |
path = "/etc/cron.hourly/centinel-" + user
if user != "root":
# create a script to run centinel every hour as the current user
hourly = "".join(["#!/bin/bash\n",
"# cron job for centinel\n",
"su ", user, " -c '", bin_loc, " --sync'\n",
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create_config_files(directory):
"""Create all available VPN configuration files in the given directory Note: I am basically just following along with what th... |
# get the config file template
template_url = ("https://securenetconnection.com/vpnconfig/"
"openvpn-template.ovpn")
resp = requests.get(template_url)
resp.raise_for_status()
template = resp.content
# get the available servers and create a config file for each server
se... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def sync_scheduler(self):
"""Download the scheduler.info file and perform a smart comparison with what we currently have so that we don't overwrite the last_run ... |
# get the server scheduler.info file
url = "%s/%s/%s" % (self.config['server']['server_url'],
"experiments", "scheduler.info")
try:
req = requests.get(url, proxies=self.config['proxy']['proxy'],
auth=self.auth,
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def informed_consent(self):
"""Create a URL for the user to give their consent through""" |
if self.typeable_handle is None:
consent_url = [self.config['server']['server_url'],
"/get_initial_consent?username="]
consent_url.append(urlsafe_b64encode(self.username))
consent_url.append("&password=")
consent_url.append(urlsafe_b64e... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def return_abs_path(directory, path):
""" Unfortunately, Python is not smart enough to return an absolute path with tilde expansion, so I writing functionality t... |
if directory is None or path is None:
return
directory = os.path.expanduser(directory)
return os.path.abspath(os.path.join(directory, path)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _run():
"""Entry point for all uses of centinel""" |
args = parse_args()
# register signal handler
signal.signal(signal.SIGTERM, signal_handler)
signal.signal(signal.SIGINT, signal_handler)
# set up logging
log_formatter = logging.Formatter("%(asctime)s %(filename)s(line %(lineno)d) "
"%(levelname)s: %(mess... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parse_config(self, config_file):
""" Given a configuration file, read in and interpret the results :param config_file: :return: """ |
with open(config_file, 'r') as f:
config = json.load(f)
self.params = config
if self.params['proxy']['proxy_type']:
self.params['proxy'] = {self.params['proxy']['proxy_type']:
self.params['proxy']['proxy_url']} |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def update(self, old, backup_path=None):
""" Update the old configuration file with new values. :param old: old configuration to update. :param backup_path: path... |
for category in old.params.keys():
for parameter in old.params[category].keys():
if (category in self.params and parameter in self.params[category] and
(old.params[category][parameter] != self.params[category][parameter]) and
(category... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def write_out_config(self, config_file):
""" Write out the configuration file :param config_file: :return: Note: this will erase all comments from the config fil... |
with open(config_file, 'w') as f:
json.dump(self.params, f, indent=2,
separators=(',', ': ')) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def divide_url(self, url):
""" divide url into host and path two parts """ |
if 'https://' in url:
host = url[8:].split('/')[0]
path = url[8 + len(host):]
elif 'http://' in url:
host = url[7:].split('/')[0]
path = url[7 + len(host):]
else:
host = url.split('/')[0]
path = url[len(host):]
retu... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def hash_folder(folder, regex='[!_]*'):
""" Get the md5 sum of each file in the folder and return to the user :param folder: the folder to compute the sums over ... |
file_hashes = {}
for path in glob.glob(os.path.join(folder, regex)):
# exclude folders
if not os.path.isfile(path):
continue
with open(path, 'r') as fileP:
md5_hash = hashlib.md5(fileP.read()).digest()
file_name = os.path.basename(path)
file_has... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def compute_files_to_download(client_hashes, server_hashes):
""" Given a dictionary of file hashes from the client and the server, specify which files should be ... |
to_dload, to_delete = [], []
for filename in server_hashes:
if filename not in client_hashes:
to_dload.append(filename)
continue
if client_hashes[filename] != server_hashes[filename]:
to_dload.append(filename)
for filename in client_hashes:
if fi... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def spinner(beep=False, disable=False, force=False):
"""This function creates a context manager that is used to display a spinner on stdout as long as the contex... |
return Spinner(beep, disable, force) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def verifier(self, url):
""" Will ask user to click link to accept app and write code """ |
webbrowser.open(url)
print('A browser should have opened up with a link to allow us to access')
print('your account, follow the instructions on the link and paste the verifier')
print('Code into here to give us access, if the browser didn\'t open, the link is:')
print(url)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def write_config(self):
""" Write config to file """ |
if not os.path.exists(os.path.dirname(self.config_file)):
os.makedirs(os.path.dirname(self.config_file))
with open(self.config_file, 'w') as f:
f.write(json.dumps(self.config))
f.close() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.