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 read_packets(self):
"""Read packets from the socket and parse them""" |
while self.running:
packet_length = self.client.recv(2)
if len(packet_length) < 2:
self.stop()
continue
packet_length = struct.unpack("<h", packet_length)[0] - 2
data = self.client.recv(packet_length)
packno = data[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 write_packets(self):
"""Write packets from the queue""" |
while self.running:
if len(self.write_queue) > 0:
self.write_queue[0].send(self.client)
self.write_queue.pop(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 start(self):
"""Open sockets to the server and start threads""" |
if not self.writeThread.isAlive() and not self.readThread.isAlive():
self.client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.client.connect(self.ADDR)
self.running = True
self.writeThread.start()
self.readThread.start() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_param(self, name: str, v) -> None: """Add or update an existing parameter.""" |
self.params[zlib.crc32(name.encode())] = v |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_object(self, name: str, pobj: ParameterObject) -> None: """Add or update an existing object.""" |
self.objects[zlib.crc32(name.encode())] = pobj |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_list(self, name: str, plist) -> None: """Add or update an existing list.""" |
self.lists[zlib.crc32(name.encode())] = plist |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def queue_setup(filename, mode, batch_size, num_readers, min_examples):
""" Sets up the queue runners for data input """ |
filename_queue = tf.train.string_input_producer([filename], shuffle=True, capacity=16)
if mode == "train":
examples_queue = tf.RandomShuffleQueue(capacity=min_examples + 3 * batch_size,
min_after_dequeue=min_examples, dtypes=[tf.string])
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def thread_setup(read_and_decode_fn, example_serialized, num_threads):
""" Sets up the threads within each reader """ |
decoded_data = list()
for _ in range(num_threads):
decoded_data.append(read_and_decode_fn(example_serialized))
return decoded_data |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def init_threads(tf_session):
""" Starts threads running """ |
coord = tf.train.Coordinator()
threads = list()
for qr in tf.get_collection(tf.GraphKeys.QUEUE_RUNNERS):
threads.extend(qr.create_threads(tf_session, coord=coord, daemon=True, start=True))
return threads, coord |
<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_config_yaml(self, flags, config_dict):
""" Load config dict and yaml dict and then override both with flags dict. """ |
if config_dict is None:
print('Config File not specified. Using only input flags.')
return flags
try:
config_yaml_dict = self.cfg_from_file(flags['YAML_FILE'], config_dict)
except KeyError:
print('Yaml File not specified. Using only input flags an... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def check_dict_keys(self, config_yaml_flags_dict):
""" Fill in all optional keys with None. Exit in a crucial key is not defined. """ |
crucial_keys = ['MODEL_DIRECTORY', 'SAVE_DIRECTORY']
for key in crucial_keys:
if key not in config_yaml_flags_dict:
print('You must define %s. Now exiting...' % key)
exit()
optional_keys = ['RESTORE_SLIM_FILE', 'RESTORE_META', 'RESTORE_SLIM', 'SEED', ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _check_file_io(self):
""" Create and define logging directory """ |
folder = 'Model' + str(self.flags['RUN_NUM']) + '/'
folder_restore = 'Model' + str(self.flags['MODEL_RESTORE']) + '/'
self.flags['RESTORE_DIRECTORY'] = self.flags['SAVE_DIRECTORY'] + self.flags[
'MODEL_DIRECTORY'] + folder_restore
self.flags['LOGGING_DIRECTORY'] = self.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 _set_tf_functions(self):
""" Sets up summary writer, saver, and session, with configurable gpu visibility """ |
merged = tf.summary.merge_all()
saver = tf.train.Saver()
if type(self.flags['GPU']) is int:
os.environ["CUDA_VISIBLE_DEVICES"] = str(self.flags['GPU'])
print('Using GPU %d' % self.flags['GPU'])
gpu_options = tf.GPUOptions(allow_growth=True)
config = tf.Co... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _restore_meta(self):
""" Restore from meta file. 'RESTORE_META_FILE' is expected to have .meta at the end. """ |
restore_meta_file = self._get_restore_meta_file()
filename = self.flags['RESTORE_DIRECTORY'] + self._get_restore_meta_file()
new_saver = tf.train.import_meta_graph(filename)
new_saver.restore(self.sess, filename[:-5])
print("Model restored from %s" % restore_meta_file) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _initialize_model(self):
""" Initialize the defined network and restore from files is so specified. """ |
# Initialize all variables first
self.sess.run(tf.local_variables_initializer())
self.sess.run(tf.global_variables_initializer())
if self.flags['RESTORE_META'] == 1:
print('Restoring from .meta file')
self._restore_meta()
elif self.flags['RESTORE_SLIM'] =... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _init_uninit_vars(self):
""" Initialize all other trainable variables, i.e. those which are uninitialized """ |
uninit_vars = self.sess.run(tf.report_uninitialized_variables())
vars_list = list()
for v in uninit_vars:
var = v.decode("utf-8")
vars_list.append(var)
uninit_vars_tf = [v for v in tf.global_variables() if v.name.split(':')[0] in vars_list]
self.sess.run(... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _save_model(self, section):
""" Save model in the logging directory """ |
checkpoint_name = self.flags['LOGGING_DIRECTORY'] + 'part_%d' % section + '.ckpt'
save_path = self.saver.save(self.sess, checkpoint_name)
print("Model saved in file: %s" % save_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 _record_training_step(self, summary):
""" Adds summary to writer and increments the step. """ |
self.writer.add_summary(summary=summary, global_step=self.step)
self.step += 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 _set_seed(self):
""" Set random seed for numpy and tensorflow packages """ |
if self.flags['SEED'] is not None:
tf.set_random_seed(self.flags['SEED'])
np.random.seed(self.flags['SEED']) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _summaries(self):
""" Print out summaries for every variable. Can be overriden in main function. """ |
for var in tf.trainable_variables():
tf.summary.histogram(var.name, var)
print(var.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 check_str(obj):
""" Returns a string for various input types """ |
if isinstance(obj, str):
return obj
if isinstance(obj, float):
return str(int(obj))
else:
return str(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 name_in_checkpoint(var):
""" Removes 'model' scoping if it is present in order to properly restore weights. """ |
if var.op.name.startswith('model/'):
return var.op.name[len('model/'):] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _merge_a_into_b(self, a, b):
"""Merge config dictionary a into config dictionary b, clobbering the options in b whenever they are also specified in a. """ |
from easydict import EasyDict as edict
if type(a) is not edict:
return
for k, v in a.items():
# a must specify keys that are in b
if k not in b:
raise KeyError('{} is not a valid config key'.format(k))
# the types must match, too... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _merge_a_into_b_simple(self, a, b):
"""Merge config dictionary a into config dictionary b, clobbering the options in b whenever they are also specified in a.... |
for k, v in a.items():
b[k] = v
return b |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cfg_from_file(self, yaml_filename, config_dict):
"""Load a config file and merge it into the default options.""" |
import yaml
from easydict import EasyDict as edict
with open(yaml_filename, 'r') as f:
yaml_cfg = edict(yaml.load(f))
return self._merge_a_into_b(yaml_cfg, config_dict) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def xor(s, pad):
'''XOR a given string ``s`` with the one-time-pad ``pad``'''
from itertools import cycle
s = bytearray(force_bytes(s, encoding='latin-1'))
pad = bytearray(force_bytes(pad, encoding='latin-1'))
return binary_type(bytearray(x ^ y for x, y in zip(s, cycle(pad)))) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def encrypt_message(data_to_encrypt, enc_alg, encryption_cert):
"""Function encrypts data and returns the generated ASN.1 :param data_to_encrypt: A byte string o... |
enc_alg_list = enc_alg.split('_')
cipher, key_length, mode = enc_alg_list[0], enc_alg_list[1], enc_alg_list[2]
enc_alg_asn1, key, encrypted_content = None, None, None
# Generate the symmetric encryption key and encrypt the message
if cipher == 'tripledes':
key = util.rand_bytes(int(key_le... |
<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_key(key_str, key_pass):
""" Function to load password protected key file in p12 or pem format""" |
try:
# First try to parse as a p12 file
key, cert, _ = asymmetric.load_pkcs12(key_str, key_pass)
except ValueError as e:
# If it fails due to invalid password raise error here
if e.args[0] == 'Password provided is invalid':
raise AS2Excep... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def content(self):
"""Function returns the body of the as2 payload as a bytes object""" |
if not self.payload:
return ''
if self.payload.is_multipart():
message_bytes = mime_to_bytes(
self.payload, 0).replace(b'\n', b'\r\n')
boundary = b'--' + self.payload.get_boundary().encode('utf-8')
temp = message_bytes.split(boundary)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def content(self):
"""Function returns the body of the mdn message as a byte string""" |
if self.payload:
message_bytes = mime_to_bytes(
self.payload, 0).replace(b'\n', b'\r\n')
boundary = b'--' + self.payload.get_boundary().encode('utf-8')
temp = message_bytes.split(boundary)
temp.pop(0)
return boundary + boundary.join(t... |
<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(self, raw_content, find_message_cb):
"""Function parses the RAW AS2 MDN, verifies it and extracts the processing status of the orginal AS2 message. :pa... |
status, detailed_status = None, None
self.payload = parse_mime(raw_content)
self.orig_message_id, orig_recipient = self.detect_mdn()
# Call the find message callback which should return a Message instance
orig_message = find_message_cb(self.orig_message_id, orig_recipient)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def detect_mdn(self):
""" Function checks if the received raw message is an AS2 MDN or not. :raises MDNNotFound: If the received payload is not an MDN then this ... |
mdn_message = None
if self.payload.get_content_type() == 'multipart/report':
mdn_message = self.payload
elif self.payload.get_content_type() == 'multipart/signed':
for part in self.payload.walk():
if part.get_content_type() == 'multipart/report':
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def init_app(self, app):
"""Setup the logging handlers, level and formatters. Level (DEBUG, INFO, CRITICAL, etc) is determined by the app.config['FLASK_LOG_LEVEL... |
config_log_level = app.config.get('FLASK_LOG_LEVEL', None)
# Set up format for default logging
hostname = platform.node().split('.')[0]
formatter = (
'[%(asctime)s] %(levelname)s %(process)d [%(name)s] '
'%(filename)s:%(lineno)d - '
'[{hostname}] - %... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_formatter(log_formatter):
"""Override the default log formatter with your own.""" |
# Add our formatter to all the handlers
root_logger = logging.getLogger()
for handler in root_logger.handlers:
handler.setFormatter(logging.Formatter(log_formatter)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def api_request(path, **kwargs):
"""Make an API request to the Hub to reduce boilerplate repetition. """ |
url = url_path_join(os.environ['JUPYTERHUB_API_URL'], path)
client = AsyncHTTPClient()
headers = {
'Authorization': 'token %s' % os.environ['JUPYTERHUB_API_TOKEN'],
}
if kwargs.get('method') == 'POST':
kwargs.setdefault('body', '')
req = HTTPRequest(url, headers=headers, **kwar... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
async def delete_user(name):
"""Stop a user's server and delete the user""" |
app_log.info("Deleting user %s", name)
await api_request('users/{}/server'.format(name), method='DELETE')
await api_request('users/{}'.format(name), method='DELETE') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def dense_to_one_hot(labels_dense, num_classes):
"""Convert class labels from scalars to one-hot vectors.""" |
num_labels = labels_dense.shape[0]
index_offset = np.arange(num_labels) * num_classes
labels_one_hot = np.zeros((num_labels, num_classes))
labels_one_hot.flat[index_offset + labels_dense.ravel()] = 1
return labels_one_hot |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _render_iteratable(iteratable, level):
"""Renders iteratable sequence of HTML elements.""" |
if isinstance(iteratable, basestring):
return unicode(iteratable)
return ''.join([render(element, level) for element in iteratable]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _serialize_attributes(attributes):
"""Serializes HTML element attributes in a name="value" pair form.""" |
result = ''
for name, value in attributes.items():
if not value:
continue
result += ' ' + _unmangle_attribute_name(name)
result += '="' + escape(value, True) + '"'
return result |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _unmangle_attribute_name(name):
"""Unmangles attribute names so that correct Python variable names are used for mapping attribute names.""" |
# Python keywords cannot be used as variable names, an underscore should
# be appended at the end of each of them when defining attribute names.
name = _PYTHON_KEYWORD_MAP.get(name, name)
# Attribute names are mangled with double underscore, as colon cannot
# be used as a variable character symbo... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def escape(string, quote=False):
"""Standard HTML text escaping, but protecting against the agressive behavior of Jinja 2 `Markup` and the like. """ |
if string is None:
return ''
elif hasattr(string, '__html__'):
return unicode(string)
string = string.replace('&', '&').replace('<', '<').replace('>', '>')
if quote:
string = string.replace('"', """)
return string |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def root_block(template_name=DEFAULT_TEMPLATE_NAME):
"""A decorator that is used to define that the decorated block function will be at the root of the block tem... |
def decorator(block_func):
block = RootBlock(block_func, template_name)
return block_func
return decorator |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def block(context_name, parent_block_func, view_func=None):
"""A decorator that is used for inserting the decorated block function in the block template hierarch... |
def decorator(block_func):
block = Block(block_func, view_func)
parent_block = Block.block_mapping[parent_block_func]
parent_block.append_context_block(context_name, block)
return block_func
return decorator |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def entropy_bits( lst: Union[ List[Union[int, str, float, complex]], Tuple[Union[int, str, float, complex]] ] ) -> float: """Calculate the number of entropy bits ... |
# Based on https://stackoverflow.com/a/45091961
if not isinstance(lst, (list, tuple)):
raise TypeError('lst must be a list or a tuple')
for num in lst:
if not isinstance(num, (int, str, float, complex)):
raise TypeError('lst can only be comprised of int, str, float, '
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def entropy_bits_nrange( minimum: Union[int, float], maximum: Union[int, float] ) -> float: """Calculate the number of entropy bits in a range of numbers.""" |
# Shannon:
# d = fabs(maximum - minimum)
# ent = -(1/d) * log(1/d, 2) * d
# Aprox form: log10(digits) * log2(10)
if not isinstance(minimum, (int, float)):
raise TypeError('minimum can only be int or float')
if not isinstance(maximum, (int, float)):
raise TypeError('maximum can o... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def password_length_needed(entropybits: Union[int, float], chars: str) -> int: """Calculate the length of a password for a given entropy and chars.""" |
if not isinstance(entropybits, (int, float)):
raise TypeError('entropybits can only be int or float')
if entropybits < 0:
raise ValueError('entropybits should be greater than 0')
if not isinstance(chars, str):
raise TypeError('chars can only be string')
if not chars:
rai... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def words_amount_needed(entropybits: Union[int, float], entropy_w: Union[int, float], entropy_n: Union[int, float], amount_n: int) -> int: """Calculate words need... |
# Thanks to @julianor for this tip to calculate default amount of
# entropy: minbitlen/log2(len(wordlist)).
# I set the minimum entropy bits and calculate the amount of words
# needed, cosidering the entropy of the wordlist.
# Then: entropy_w * amount_w + entropy_n * amount_n >= ENTROPY_BITS_MIN
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def password_entropy(length: int, chars: str) -> float: """Calculate the entropy of a password with given length and chars.""" |
if not isinstance(length, int):
raise TypeError('length can only be int')
if length < 0:
raise ValueError('length should be greater than 0')
if not isinstance(chars, str):
raise TypeError('chars can only be string')
if not chars:
raise ValueError("chars can't be null")
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def passphrase_entropy(amount_w: int, entropy_w: Union[int, float], entropy_n: Union[int, float], amount_n: int) -> float: """Calculate the entropy of a passphras... |
if not isinstance(amount_w, int):
raise TypeError('amount_w can only be int')
if not isinstance(entropy_w, (int, float)):
raise TypeError('entropy_w can only be int or float')
if not isinstance(entropy_n, (int, float)):
raise TypeError('entropy_n can only be int or float')
if no... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def entropy_bits( lst: Union[ List[Union[int, str, float, complex]], Tuple[Union[int, str, float, complex]] ] ) -> float: """Calculate the entropy of a wordlist o... |
if not isinstance(lst, (tuple, list)):
raise TypeError('lst must be a list or a tuple')
size = len(lst)
if (
size == 2
and isinstance(lst[0], (int, float))
and isinstance(lst[1], (int, float))
):
return calc_entrop... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def import_words_from_file(self, inputfile: str, is_diceware: bool) -> None: """Import words for the wordlist from a given file. The file can have a single column... |
if not Aux.isfile_notempty(inputfile):
raise FileNotFoundError('Input file does not exists, is not valid '
'or is empty: {}'.format(inputfile))
self._wordlist_entropy_bits = None
if is_diceware:
self._wordlist = self._read_words_from_... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def password_length_needed(self) -> int: """Calculate the needed password length to satisfy the entropy number. This is for the given character set. """ |
characters = self._get_password_characters()
if (
self.entropy_bits_req is None
or not characters
):
raise ValueError("Can't calculate the password length needed: "
"entropy_bits_req isn't set or the character "
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def words_amount_needed(self) -> int: """Calculate the needed amount of words to satisfy the entropy number. This is for the given wordlist. """ |
if (
self.entropy_bits_req is None
or self.amount_n is None
or not self.wordlist
):
raise ValueError("Can't calculate the words amount needed: "
"wordlist is empty or entropy_bits_req or "
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def generated_password_entropy(self) -> float: """Calculate the entropy of a password that would be generated.""" |
characters = self._get_password_characters()
if (
self.passwordlen is None
or not characters
):
raise ValueError("Can't calculate the password entropy: character"
" set is empty or passwordlen isn't set")
if self.... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def generated_passphrase_entropy(self) -> float: """Calculate the entropy of a passphrase that would be generated.""" |
if (
self.amount_w is None
or self.amount_n is None
or not self.wordlist
):
raise ValueError("Can't calculate the passphrase entropy: "
"wordlist is empty or amount_n or "
"amount_w isn... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def generate(self, uppercase: int = None) -> list: """Generate a list of words randomly chosen from a wordlist. Keyword arguments: uppercase -- An integer number ... |
if (
self.amount_n is None
or self.amount_w is None
or not self.wordlist
):
raise ValueError("Can't generate passphrase: "
"wordlist is empty or amount_n or "
"amount_w isn't set")
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def generate_password(self) -> list: """Generate a list of random characters.""" |
characterset = self._get_password_characters()
if (
self.passwordlen is None
or not characterset
):
raise ValueError("Can't generate password: character set is "
"empty or passwordlen isn't set")
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 generate_uuid4(self) -> list: """Generate a list of parts of a UUID version 4 string. Usually, these parts are concatenated together using dashes. """ |
# uuid4: 8-4-4-4-12: xxxxxxxx-xxxx-4xxx-{8,9,a,b}xxx-xxxxxxxxxxxx
# instead of requesting small amounts of bytes, it's better to do it
# for the full amount of them.
hexstr = randhex(30)
uuid4 = [
hexstr[:8],
hexstr[8:12],
'4' + hexstr[12:15]... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def default(self, line):
''' if no other commands was invoked '''
try:
encoding, count = self._ks.asm(line)
machine_code = ""
for opcode in encoding:
machine_code += "\\x" + hexlify(pack("B", opcode)).decode()
print("\"" + machine_code + "\... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _bigger_than_zero(value: str) -> int: """Type evaluator for argparse.""" |
ivalue = int(value)
if ivalue < 0:
raise ArgumentTypeError(
'{} should be bigger than 0'.format(ivalue)
)
return ivalue |
<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_fk_popup_field(cls, *args, **kwargs):
""" generate fk field related to class wait popup crud """ |
kwargs['popup_name'] = cls.get_class_verbose_name()
kwargs['permissions_required'] = cls.permissions_required
if cls.template_name_fk is not None:
kwargs['template_name'] = cls.template_name_fk
return ForeignKeyWidget('{}_popup_create'.format(cls.get_class_name()), *args, **... |
<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_m2m_popup_field(cls, *args, **kwargs):
""" generate m2m field related to class wait popup crud """ |
kwargs['popup_name'] = cls.get_class_verbose_name()
kwargs['permissions_required'] = cls.permissions_required
if cls.template_name_m2m is not None:
kwargs['template_name'] = cls.template_name_m2m
return ManyToManyWidget('{}_popup_create'.format(cls.get_class_name()), *args, ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def make_all_uppercase( lst: Union[list, tuple, str, set] ) -> Union[list, tuple, str, set]: """Make all characters uppercase. It supports characters in a (mix of... |
if not isinstance(lst, (list, tuple, str, set)):
raise TypeError('lst must be a list, a tuple, a set or a string')
if isinstance(lst, str):
return lst.upper()
arr = list(lst)
# enumerate is 70% slower than range
# for i in range(len(lst)):
# ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _make_one_char_uppercase(string: str) -> str: """Make a single char from the string uppercase.""" |
if not isinstance(string, str):
raise TypeError('string must be a string')
if Aux.lowercase_count(string) > 0:
while True:
cindex = randbelow(len(string))
if string[cindex].islower():
aux = list(string)
aux... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def make_chars_uppercase( lst: Union[list, tuple, str, set], uppercase: int ) -> Union[list, tuple, str, set]: """Make uppercase some randomly selected characters... |
if not isinstance(lst, (list, tuple, str, set)):
raise TypeError('lst must be a list, a tuple, a set or a string')
if not isinstance(uppercase, int):
raise TypeError('uppercase must be an integer')
if uppercase < 0:
raise ValueError('uppercase must be bigger ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def isfile_notempty(inputfile: str) -> bool: """Check if the input filename with path is a file and is not empty.""" |
try:
return isfile(inputfile) and getsize(inputfile) > 0
except TypeError:
raise TypeError('inputfile is not a valid type') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def system_entropy():
"""Return the system's entropy bit count, or -1 if unknown.""" |
arg = ['cat', '/proc/sys/kernel/random/entropy_avail']
proc = Popen(arg, stdout=PIPE, stderr=DEVNULL)
response = proc.communicate()[0]
return int(response) if response else -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 issue(self, issuance_spec, metadata, fees):
""" Creates a transaction for issuing an asset. :param TransferParameters issuance_spec: The parameters of the is... |
inputs, total_amount = self._collect_uncolored_outputs(
issuance_spec.unspent_outputs, 2 * self._dust_amount + fees)
return bitcoin.core.CTransaction(
vin=[bitcoin.core.CTxIn(item.out_point, item.output.script) for item in inputs],
vout=[
self._get_c... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def transfer(self, asset_transfer_specs, btc_transfer_spec, fees):
""" Creates a transaction for sending assets and bitcoins. :param list[(bytes, TransferParamet... |
inputs = []
outputs = []
asset_quantities = []
for asset_id, transfer_spec in asset_transfer_specs:
colored_outputs, collected_amount = self._collect_colored_outputs(
transfer_spec.unspent_outputs, asset_id, transfer_spec.amount)
inputs.extend(col... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def transfer_assets(self, asset_id, transfer_spec, btc_change_script, fees):
""" Creates a transaction for sending an asset. :param bytes asset_id: The ID of the... |
return self.transfer(
[(asset_id, transfer_spec)],
TransferParameters(transfer_spec.unspent_outputs, None, btc_change_script, 0),
fees) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def btc_asset_swap(self, btc_transfer_spec, asset_id, asset_transfer_spec, fees):
""" Creates a transaction for swapping assets for bitcoins. :param TransferPara... |
return self.transfer([(asset_id, asset_transfer_spec)], btc_transfer_spec, fees) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def asset_asset_swap( self, asset1_id, asset1_transfer_spec, asset2_id, asset2_transfer_spec, fees):
""" Creates a transaction for swapping an asset for another ... |
btc_transfer_spec = TransferParameters(
asset1_transfer_spec.unspent_outputs, asset1_transfer_spec.to_script, asset1_transfer_spec.change_script, 0)
return self.transfer(
[(asset1_id, asset1_transfer_spec), (asset2_id, asset2_transfer_spec)], btc_transfer_spec, fees) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _collect_uncolored_outputs(unspent_outputs, amount):
""" Returns a list of uncolored outputs for the specified amount. :param list[SpendableOutput] unspent_o... |
total_amount = 0
result = []
for output in unspent_outputs:
if output.output.asset_id is None:
result.append(output)
total_amount += output.output.value
if total_amount >= amount:
return result, total_amount
raise... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _collect_colored_outputs(unspent_outputs, asset_id, asset_quantity):
""" Returns a list of colored outputs for the specified quantity. :param list[SpendableO... |
total_amount = 0
result = []
for output in unspent_outputs:
if output.output.asset_id == asset_id:
result.append(output)
total_amount += output.output.asset_quantity
if total_amount >= asset_quantity:
return result, total_... |
<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_uncolored_output(self, script, value):
""" Creates an uncolored output. :param bytes script: The output script. :param int value: The satoshi value of t... |
if value < self._dust_amount:
raise DustOutputError
return bitcoin.core.CTxOut(value, bitcoin.core.CScript(script)) |
<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_colored_output(self, script):
""" Creates a colored output. :param bytes script: The output script. :return: An object representing the colored output. ... |
return bitcoin.core.CTxOut(self._dust_amount, bitcoin.core.CScript(script)) |
<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_marker_output(self, asset_quantities, metadata):
""" Creates a marker output. :param list[int] asset_quantities: The asset quantity list. :param bytes m... |
payload = openassets.protocol.MarkerOutput(asset_quantities, metadata).serialize_payload()
script = openassets.protocol.MarkerOutput.build_script(payload)
return bitcoin.core.CTxOut(0, script) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def init_app(self, app):
"""Setup the 4 default routes.""" |
app.add_url_rule(self.request_token_url, view_func=self.request_token,
methods=[u'POST'])
app.add_url_rule(self.access_token_url, view_func=self.access_token,
methods=[u'POST'])
app.add_url_rule(self.register_url, view_func=self.register,
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def authorized(self, request_token):
"""Create a verifier for an user authorized client""" |
verifier = generate_token(length=self.verifier_length[1])
self.save_verifier(request_token, verifier)
response = [
(u'oauth_token', request_token),
(u'oauth_verifier', verifier)
]
callback = self.get_callback(request_token)
return redirect(add_par... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def request_token(self):
"""Create an OAuth request token for a valid client request. Defaults to /request_token. Invoked by client applications. """ |
client_key = request.oauth.client_key
realm = request.oauth.realm
# TODO: fallback on default realm?
callback = request.oauth.callback_uri
request_token = generate_token(length=self.request_token_length[1])
token_secret = generate_token(length=self.secret_length)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def access_token(self):
"""Create an OAuth access token for an authorized client. Defaults to /access_token. Invoked by client applications. """ |
access_token = generate_token(length=self.access_token_length[1])
token_secret = generate_token(self.secret_length)
client_key = request.oauth.client_key
self.save_access_token(client_key, access_token,
request.oauth.resource_owner_key, secret=token_secret)
return ur... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def require_oauth(self, realm=None, require_resource_owner=True, require_verifier=False, require_realm=False):
"""Mark the view function f as a protected resourc... |
def decorator(f):
@wraps(f)
def verify_request(*args, **kwargs):
"""Verify OAuth params before running view function f"""
try:
if request.form:
body = request.form.to_dict()
else:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def collect_request_parameters(self, request):
"""Collect parameters in an object for convenient access""" |
class OAuthParameters(object):
"""Used as a parameter container since plain object()s can't"""
pass
# Collect parameters
query = urlparse(request.url.decode("utf-8")).query
content_type = request.headers.get('Content-Type', '')
if request.form:
... |
<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_size(self, name: str) -> int: """Get a resource size from the RSTB.""" |
crc32 = binascii.crc32(name.encode())
if crc32 in self.crc32_map:
return self.crc32_map[crc32]
if name in self.name_map:
return self.name_map[name]
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 set_size(self, name: str, size: int):
"""Set the size of a resource in the RSTB.""" |
if self._needs_to_be_in_name_map(name):
if len(name) >= 128:
raise ValueError("Name is too long")
self.name_map[name] = size
else:
crc32 = binascii.crc32(name.encode())
self.crc32_map[crc32] = size |
<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(self, stream: typing.BinaryIO, be: bool) -> None: """Write the RSTB to the specified stream.""" |
stream.write(b'RSTB')
stream.write(_to_u32(len(self.crc32_map), be))
stream.write(_to_u32(len(self.name_map), be))
# The CRC32 hashmap *must* be sorted because the game performs a binary search.
for crc32, size in sorted(self.crc32_map.items()):
stream.write(_to_u32... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def randint(nbits: int) -> int: """Generate an int with nbits random bits. Raises ValueError if nbits <= 0, and TypeError if it's not an integer. 1871 """ |
if not isinstance(nbits, int):
raise TypeError('number of bits should be an integer')
if nbits <= 0:
raise ValueError('number of bits must be greater than zero')
# https://github.com/python/cpython/blob/3.6/Lib/random.py#L676
nbytes = (nbits + 7) // 8 # bits / 8 a... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def randchoice(seq: Union[str, list, tuple, dict, set]) -> any: """Return a randomly chosen element from the given sequence. Raises TypeError if *seq* is not str,... |
if not isinstance(seq, (str, list, tuple, dict, set)):
raise TypeError('seq must be str, list, tuple, dict or set')
if len(seq) <= 0:
raise IndexError('seq must have at least one element')
if isinstance(seq, set):
values = list(seq)
return randchoice(values)
elif isinst... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def randbelow(num: int) -> int: """Return a random int in the range [0,num). Raises ValueError if num <= 0, and TypeError if it's not an integer. 13 """ |
if not isinstance(num, int):
raise TypeError('number must be an integer')
if num <= 0:
raise ValueError('number must be greater than zero')
if num == 1:
return 0
# https://github.com/python/cpython/blob/3.6/Lib/random.py#L223
nbits = num.bit_length() # don't use (n-1) he... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def randhex(ndigits: int) -> str: """Return a random text string of hexadecimal characters. The string has *ndigits* random digits. Raises ValueError if ndigits <... |
if not isinstance(ndigits, int):
raise TypeError('number of digits must be an integer')
if ndigits <= 0:
raise ValueError('number of digits must be greater than zero')
nbytes = ceil(ndigits / 2)
rbytes = random_randbytes(nbytes)
hexstr = rbytes.hex()[:ndigits]
return hexstr |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def default(self, user_input):
''' if no other command was invoked '''
try:
for i in self._cs.disasm(unhexlify(self.cleanup(user_input)), self.base_address):
print("0x%08x:\t%s\t%s" %(i.address, i.mnemonic, i.op_str))
except CsError as e:
print("Error: %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 setMoveResizeWindow(self, win, gravity=0, x=None, y=None, w=None, h=None):
""" Set the property _NET_MOVERESIZE_WINDOW to move or resize the given window. Fl... |
# indicate source (application)
gravity_flags = gravity | 0b0000100000000000
if x is None:
x = 0
else:
gravity_flags = gravity_flags | 0b0000010000000000
if y is None:
y = 0
else:
gravity_flags = gravity_flags | 0b000000100... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _setProperty(self, _type, data, win=None, mask=None):
""" Send a ClientMessage event to the root window """ |
if not win:
win = self.root
if type(data) is str:
dataSize = 8
else:
data = (data+[0]*(5-len(data)))[:5]
dataSize = 32
ev = protocol.event.ClientMessage(
window=win,
client_type=self.display.get_atom(_type), data=(... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def scoreatpercentile(a, per, limit=(), interpolation_method='fraction', axis=None):
""" Calculate the score at a given percentile of the input sequence. For exa... |
# adapted from NumPy's percentile function
a = np.asarray(a)
if limit:
a = a[(limit[0] <= a) & (a <= limit[1])]
if per == 0:
return a.min(axis=axis)
elif per == 100:
return a.max(axis=axis)
sorted = np.sort(a, axis=axis)
if axis is None:
axis = 0
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 merge_equal_neighbors(self):
""" Merge neighbors with same speaker. """ |
IDX_LENGTH = 3
merged = self.segs.copy()
current_start = 0
j = 0
seg = self.segs.iloc[0]
for i in range(1, self.num_segments):
seg = self.segs.iloc[i]
last = self.segs.iloc[i - 1]
if seg.speaker == last.speaker:
merged... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def format_arguments(*args):
""" Converts a list of arguments from the command line into a list of positional arguments and a dictionary of keyword arguments. Ha... |
positional_args = []
kwargs = {}
split_key = None
for arg in args:
if arg.startswith('--'):
arg = arg[2:]
if '=' in arg:
key, value = arg.split('=', 1)
kwargs[key.replace('-', '_')] = value
else:
split_key = a... |
<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_settings(section='gocd', settings_paths=('~/.gocd/gocd-cli.cfg', '/etc/go/gocd-cli.cfg')):
"""Returns a `gocd_cli.settings.Settings` configured for setti... |
if isinstance(settings_paths, basestring):
settings_paths = (settings_paths,)
config_file = next((path for path in settings_paths if is_file_readable(path)), None)
if config_file:
config_file = expand_user(config_file)
return Settings(prefix=section, section=section, filename=config_f... |
<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_go_server(settings=None):
"""Returns a `gocd.Server` configured by the `settings` object. Args: settings: a `gocd_cli.settings.Settings` object. Default:... |
if not settings:
settings = get_settings()
return gocd.Server(
settings.get('server'),
user=settings.get('user'),
password=settings.get('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 _get_standard_tc_matches(text, full_text, options):
'''
get the standard tab completions.
These are the options which could complete the full_text.
'''
final_matches = [o for o in options if o.startswith(full_text)]
return final_matches |
<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_fuzzy_tc_matches(text, full_text, options):
'''
Get the options that match the full text, then from each option
return only the individual words which have not yet been matched
which also match the text being tab-completed.
'''
print("text: {}, full: {}, options: {}".format(text, full_t... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.