output stringlengths 1 928k | instruction stringlengths 7 928k | system stringlengths 0 104k |
|---|---|---|
A function to run length decode an int array. | How would you explain what the following Python 3 function does
def run_length_decode(in_array):
switch=False
out_array=[]
for item in in_array:
if switch==False:
this_item = item
switch=True
else:
switch=False
out_array.extend([this_item]*int(... | You are a Python code analyst, evaluating scripts for potential improvements. |
A function to delta decode an int array. | Can you tell what is the following Python 3 function doing
def delta_decode(in_array):
if len(in_array) == 0:
return []
this_ans = in_array[0]
out_array = [this_ans]
for i in range(1, len(in_array)):
this_ans += in_array[i]
out_array.append(this_ans)
return out_array | As a python code expert, you are capable of creating scripts from specifications. |
def convert_bytes_to_ints(in_bytes, num):
"""Convert a byte array into an integer array. The number of bytes forming an integer
is defined by num
:param in_bytes: the input bytes
:param num: the number of bytes per int
:return the integer array"""
dt = numpy.dtype('>i' + str(num))
return nu... | Create a Python 3 function for
converting a byte array into an integer array. | As a Python code analyst, you investigate and solve complex coding mysteries |
Convert a list of bytes to a list of strings. Each string is of length mmtf. CHAIN_LEN
. | Make a summary of the following Python 3 code
def decode_chain_list(in_bytes):
bstrings = numpy.frombuffer(in_bytes, numpy.dtype('S' + str(mmtf.utils.constants.CHAIN_LEN)))
return [s.decode("ascii").strip(mmtf.utils.constants.NULL_BYTE) for s in bstrings] | As a Python code composer, you craft elegant and concise scripts. |
def recursive_index_decode(int_array, max=32767, min=-32768):
"""Unpack an array of integers using recursive indexing.
:param int_array: the input array of integers
:param max: the maximum integer size
:param min: the minimum integer size
:return the array of integers after recursive index decoding... | Create a Python 3 function for
unpacking an array of integers using recursive indexing. | As a Python code composer, you craft elegant and concise scripts. |
Function to decode the input data and place it onto the class. | Given the following Python 3 function, write the documentation
def decode_data(self, input_data):
self.group_type_list = decode_array(input_data["groupTypeList"])
self.x_coord_list = decode_array(input_data["xCoordList"])
self.y_coord_list = decode_array(input_data["yCoordList"])
self.z_... | As a Python code composer, you craft elegant and concise scripts. |
Write the data from the getters to the setters. | Explain what the following Python 3 code does
def pass_data_on(self, data_setters):
data_setters.init_structure(self.num_bonds, len(self.x_coord_list), len(self.group_type_list),
len(self.chain_id_list), len(self.chains_per_model), self.structure_id)
decoder_utils.add... | As a Python code analyst, you investigate and solve complex coding mysteries |
Checks to see if the internet is on by pinging the given IP or address. | Make a summary of the following Python 3 code
def _internet_on(address):
try:
urllib2.urlopen(address, timeout=1)
return True
except urllib2.URLError as err:
return False | You are a Python code analyst, evaluating scripts for potential improvements. |
API function to write data as MMTF to a file | Can you tell what is the following Python 3 function doing
def write_mmtf(file_path, input_data, input_function):
mmtf_encoder = MMTFEncoder()
pass_data_on(input_data, input_function, mmtf_encoder)
mmtf_encoder.write_file(file_path) | As a python code expert, you are capable of creating scripts from specifications. |
def get_raw_data_from_url(pdb_id, reduced=False):
"""" Get the msgpack unpacked data given a PDB id.
:param pdb_id: the input PDB id
:return the unpacked data (a dict) """
url = get_url(pdb_id,reduced)
request = urllib2.Request(url)
request.add_header('Accept-encoding', 'gzip')
response = u... | Create a Python 3 function to
get the msgpack unpacked data given a PDB id. | As a python code expert, you are capable of creating scripts from specifications. |
def parse(file_path):
"""Return a decoded API to the data from a file path.
:param file_path: the input file path. Data is not entropy compressed (e.g. gzip)
:return an API to decoded data """
newDecoder = MMTFDecoder()
with open(file_path, "rb") as fh:
newDecoder.decode_data(_unpack(fh))
... | Create a Python 3 function to
return a decoded API to the data from a file path. | You are a Python code architect, reviewing and designing scalable and efficient code |
Return a decoded API to the data from a gzip compressed file. | Here you have a function in Python 3, explain what it does
def parse_gzip(file_path):
newDecoder = MMTFDecoder()
newDecoder.decode_data(_unpack(gzip.open(file_path, "rb")))
return newDecoder | As a Python code translator, you convert algorithms and pseudocode into Python. |
Returns a string of data after gzip decoding
| Can you generate a brief explanation for the following Python 3 code
def ungzip_data(input_data):
buf = StringIO(input_data)
f = gzip.GzipFile(fileobj=buf)
return f | As a Python code composer, you craft elegant and concise scripts. |
Parse the header and return it along with the input array minus the header. | Can you generate the documentation for the following Python 3 function
def parse_header(input_array):
codec = struct.unpack(mmtf.utils.constants.NUM_DICT[4], input_array[0:4])[0]
length = struct.unpack(mmtf.utils.constants.NUM_DICT[4], input_array[4:8])[0]
param = struct.unpack(mmtf.utils.constants.NUM_DICT... | As a python code expert, you are capable of creating scripts from specifications. |
Add the header to the appropriate array. | Make a summary of the following Python 3 code
def add_header(input_array, codec, length, param):
return struct.pack(mmtf.utils.constants.NUM_DICT[4], codec) + \
struct.pack(mmtf.utils.constants.NUM_DICT[4], length) + \
struct.pack(mmtf.utils.constants.NUM_DICT[4], param) + input_array | You are a Python code architect, reviewing and designing scalable and efficient code |
def convert_bytes_to_ints(in_bytes, num):
"""Convert a byte array into an integer array. The number of bytes forming an integer
is defined by num
:param in_bytes: the input bytes
:param num: the number of bytes per int
:return the integer array"""
out_arr = []
for i in range(len(in_bytes)//n... | Can you implement a function in Python 3 that
converts a byte array into an integer array. | You are a Python code analyst, evaluating scripts for potential improvements. |
Convert an integer array into a byte array. | Here you have a function in Python 3, explain what it does
def convert_ints_to_bytes(in_ints, num):
out_bytes= b""
for val in in_ints:
out_bytes+=struct.pack(mmtf.utils.constants.NUM_DICT[num], val)
return out_bytes | You are a Python code analyst, evaluating scripts for potential improvements. |
Convert a list of bytes to a list of strings. Each string is of length mmtf. CHAIN_LEN
. | How would you explain what the following Python 3 function does
def decode_chain_list(in_bytes):
tot_strings = len(in_bytes) // mmtf.utils.constants.CHAIN_LEN
out_strings = []
for i in range(tot_strings):
out_s = in_bytes[i * mmtf.utils.constants.CHAIN_LEN:i * mmtf.utils.constants.CHAIN_LEN + mmtf.u... | You are a Python code architect, reviewing and designing scalable and efficient code |
def encode_chain_list(in_strings):
"""Convert a list of strings to a list of byte arrays.
:param in_strings: the input strings
:return the encoded list of byte arrays"""
out_bytes = b""
for in_s in in_strings:
out_bytes+=in_s.encode('ascii')
for i in range(mmtf.utils.constants.CHAIN... | Write a Python 3 script for
converting a list of strings to a list of byte arrays. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def recursive_index_encode(int_array, max=32767, min=-32768):
"""Pack an integer array using recursive indexing.
:param int_array: the input array of integers
:param max: the maximum integer size
:param min: the minimum integer size
:return the array of integers after recursive index encoding"""
... | Write a Python 3 script to
pack an integer array using recursive indexing. | As a Python code composer, you craft elegant and concise scripts. |
def recursive_index_decode(int_array, max=32767, min=-32768):
"""Unpack an array of integers using recursive indexing.
:param int_array: the input array of integers
:param max: the maximum integer size
:param min: the minimum integer size
:return the array of integers after recursive index decoding"... | Create a Python 3 function to
unpack an array of integers using recursive indexing. | As a Python code analyst, you investigate and solve complex coding mysteries |
def build(algo, init):
'''Build and return an optimizer for the rosenbrock function.
In downhill, an optimizer can be constructed using the build() top-level
function. This function requires several Theano quantities such as the loss
being optimized and the parameters to update during optimization.
... | Can you create a Python 3 function that
builds and return an optimizer for the rosenbrock function. | You are a Python code architect, reviewing and designing scalable and efficient code |
def build_and_trace(algo, init, limit=100, **kwargs):
'''Run an optimizer on the rosenbrock function. Return xs, ys, and losses.
In downhill, optimization algorithms can be iterated over to progressively
minimize the loss. At each iteration, the optimizer yields a dictionary of
monitor values that were... | Create a Python 3 function for
running an optimizer on the rosenbrock function. Return xs ys and losses. | As a python code expert, you are capable of creating scripts from specifications. |
def minimize(loss, train, valid=None, params=None, inputs=None, algo='rmsprop',
updates=(), monitors=(), monitor_gradients=False, batch_size=32,
train_batches=None, valid_batches=None, **kwargs):
'''Minimize a loss function with respect to some symbolic parameters.
Additional keyword ... | Write a Python 3 script for
minimizing a loss function with respect to some symbolic parameters. | You are a Python code analyst, evaluating scripts for potential improvements. |
def make_label(loss, key):
'''Create a legend label for an optimization run.'''
algo, rate, mu, half, reg = key
slots, args = ['{:.3f}', '{}', 'm={:.3f}'], [loss, algo, mu]
if algo in 'SGD NAG RMSProp Adam ESGD'.split():
slots.append('lr={:.2e}')
args.append(rate)
if algo in 'RMSProp... | Implement a function in Python 3 to
create a legend label for an optimization run. | You are a Python code generator, capable of creating scripts from specifications. |
def iterate(self, shuffle=True):
'''Iterate over batches in the dataset.
This method generates ``iteration_size`` batches from the dataset and
then returns.
Parameters
----------
shuffle : bool, optional
Shuffle the batches in this dataset if the iteration r... | Write a Python 3 function for
iterating over batches in the dataset and return them as a generator. | You are a Python code analyst, evaluating scripts for potential improvements. |
Create a Theano shared variable like an existing parameter. | Can you generate a brief explanation for the following Python 3 code
def shared_like(param, suffix, init=0):
'''Create a Theano shared variable like an existing parameter.
Parameters
----------
param : Theano variable
Theano variable to use for shape information.
suffix : str
Suffix... | You are a Python code analyst, evaluating scripts for potential improvements. |
Walk a computation graph and extract root variables. | How would you explain what the following Python 3 function does
def find_inputs_and_params(node):
'''Walk a computation graph and extract root variables.
Parameters
----------
node : Theano expression
A symbolic Theano expression to walk.
Returns
-------
inputs : list Theano variab... | As a Python code composer, you craft elegant and concise scripts. |
def log(msg, *args, **kwargs):
'''Log a message to the console.
Parameters
----------
msg : str
A string to display on the console. This can contain {}-style
formatting commands; the remaining positional and keyword arguments
will be used to fill them in.
'''
now = datet... | Can you write a function in Python 3 where it
logs a message to the console. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Log a parameter value to the console. | Explain what the following Python 3 code does
def log_param(name, value):
'''Log a parameter value to the console.
Parameters
----------
name : str
Name of the parameter being logged.
value : any
Value of the parameter being logged.
'''
log('setting {} = {}', click.style(str... | You are a Python code architect, reviewing and designing scalable and efficient code |
def load_mnist():
'''Load the MNIST digits dataset.'''
mnist = skdata.mnist.dataset.MNIST()
mnist.meta # trigger download if needed.
def arr(n, dtype):
arr = mnist.arrays[n]
return arr.reshape((len(arr), -1)).astype(dtype)
train_images = arr('train_images', np.float32) / 128 - 1
... | Can you create a Python 3 function that
loads the MNIST digits dataset. | As a Python code analyst, you investigate and solve complex coding mysteries |
def build(algo, loss, params=None, inputs=None, updates=(), monitors=(),
monitor_gradients=False):
'''Construct an optimizer by name.
Parameters
----------
algo : str
The name of the optimization algorithm to build.
loss : Theano expression
Loss function to minimize. This ... | Can you write a function in Python 3 where it
constructs an optimizer by name. | You are a Python code analyst, evaluating scripts for potential improvements. |
Compile the Theano functions for evaluating and updating our model. | Can you generate the documentation for the following Python 3 function
def _compile(self, **kwargs):
'''Compile the Theano functions for evaluating and updating our model.
'''
util.log('compiling evaluation function')
self.f_eval = theano.function(self._inputs,
... | As a Python code analyst, you investigate and solve complex coding mysteries |
def get_updates(self, **kwargs):
'''Get parameter update expressions for performing optimization.
Keyword arguments can be applied here to set any of the global
optimizer attributes.
Yields
------
updates : (parameter, expression) tuples
A sequence of parame... | Write a Python 3 script to
yield the set of parameter updates for performing optimization. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def _differentiate(self, params=None):
'''Return a sequence of gradients for our parameters.
If this optimizer has been configured with a gradient norm limit, or
with elementwise gradient clipping, this method applies the appropriate
rescaling and clipping operations before returning th... | How would you implement a function in Python 3 that
returns a sequence of gradients for our parameters. | You are a Python code generator, capable of creating scripts from specifications. |
def set_params(self, targets=None):
'''Set the values of the parameters to the given target values.
Parameters
----------
targets : sequence of ndarray, optional
Arrays for setting the parameters of our model. If this is not
provided, the current best parameters ... | Write a Python 3 function that can
set the values of the parameters to the given target values. | You are a Python code generator, capable of creating scripts from specifications. |
def _log(self, monitors, iteration, label='', suffix=''):
'''Log the state of the optimizer on the console.
Parameters
----------
monitors : OrderedDict
A dictionary of monitor names mapped to values. These names and
values are what is being logged.
itera... | Write a Python 3 script to
log the state of the optimizer on the console. | You are a Python code architect, reviewing and designing scalable and efficient code |
Evaluate the current model parameters on a dataset. | Can you generate a brief explanation for the following Python 3 code
def evaluate(self, dataset):
'''Evaluate the current model parameters on a dataset.
Parameters
----------
dataset : :class:`Dataset <downhill.dataset.Dataset>`
A set of data to use for evaluating the model.... | As a Python code analyst, you investigate and solve complex coding mysteries |
def _prepare(self, **kwargs):
'''Set up properties for optimization.
This method can be overridden by base classes to provide parameters that
are specific to a particular optimization technique (e.g., setting up a
learning rate value).
'''
self.learning_rate = util.as_fl... | Create a Python 3 function to
set up properties for optimization. | You are a Python code analyst, evaluating scripts for potential improvements. |
This method is used to iterate over the training and validation data for a single iteration of the optimization. | Here you have a function in Python 3, explain what it does
def iterate(self, train=None, valid=None, max_updates=None, **kwargs):
r'''Optimize a loss iteratively using a training and validation dataset.
This method yields a series of monitor values to the caller. After every
optimization epoch,... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def minimize(self, *args, **kwargs):
'''Optimize our loss exhaustively.
This method is a thin wrapper over the :func:`iterate` method. It simply
exhausts the iterative optimization process and returns the final
monitor values.
Returns
-------
train_monitors : di... | How would you implement a function in Python 3 that
optimizes our loss exhaustively. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def _step(self, dataset):
'''Advance the state of the optimizer by one step.
Parameters
----------
dataset : :class:`Dataset <downhill.dataset.Dataset>`
A dataset for optimizing the model.
Returns
-------
train_monitors : dict
A dictionar... | Implement a function in Python 3 to
advance the state of the optimizer by one step. | You are a Python code architect, reviewing and designing scalable and efficient code |
def accept_arguments(method, number_of_arguments=1):
"""Returns True if the given method will accept the given number of arguments
method: the method to perform introspection on
number_of_arguments: the number_of_arguments
"""
if 'method' in method.__class__.__name__:
number_of_argume... | Create a Python 3 function for
returning True if the given method will accept the given number of arguments AttributeNames | You are a Python code generator, capable of creating scripts from specifications. |
def emit(self, signal, value=None, gather=False):
"""Emits a signal, causing all slot methods connected with the signal to be called (optionally w/ related value)
signal: the name of the signal to emit, must be defined in the classes 'signals' list.
value: the value to pass to all connect... | Write a Python 3 function that can
emit a signal causing all slot methods connected with the signal to be called with the given value. | You are a Python code analyst, evaluating scripts for potential improvements. |
def connect(self, signal, slot, transform=None, condition=None):
"""Defines a connection between this objects signal and another objects slot
signal: the signal this class will emit, to cause the slot method to be called
receiver: the object containing the slot method to be called
... | Can you write a function in Python 3 where it
defines a connection between this object and another object. | As a Python code composer, you craft elegant and concise scripts. |
def disconnect(self, signal=None, slot=None, transform=None, condition=None):
"""Removes connection(s) between this objects signal and connected slot(s)
signal: the signal this class will emit, to cause the slot method to be called
receiver: the object containing the slot method to be cal... | Can you implement a function in Python 3 that
removes all connections between this object signal and connected slot ( s | You are a Python code generator, capable of creating scripts from specifications. |
def get(self, key):
""" Returns context data for a given app, can be an ID or a case insensitive name """
keystr = str(key)
res = None
try:
res = self.ctx[keystr]
except KeyError:
for k, v in self.ctx.items():
if "name" in v and v["name"].... | Can you implement a function in Python 3 that
returns the context data for a given app. Can be an ID or a case insensitive name. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Return the quality of the item. | Make a summary of the following Python 3 code
def quality(self):
try:
qid = int((self.tool_metadata or {}).get("quality", 0))
except:
qid = 0
# We might be able to get the quality strings from the item's tags
internal_name, name = "normal", "Normal"
if se... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def get(cls):
"""Get the current API key.
if one has not been given via 'set' the env var STEAMODD_API_KEY will
be checked instead.
"""
apikey = cls.__api_key or cls.__api_key_env_var
if apikey:
return apikey
else:
raise APIKeyMissingError... | How would you implement a function in Python 3 that
gets the current API key. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Make the API call again and fetch fresh data. | Make a summary of the following Python 3 code
def call(self):
data = self._downloader.download()
# Only try to pass errors arg if supported
if sys.version >= "2.7":
data = data.decode("utf-8", errors="ignore")
else:
data = data.decode("utf-8")
self.updat... | As a python code expert, you are capable of creating scripts from specifications. |
Returns the attribute definition dict of a given attribute ID | Explain what the following Python 3 code does
def _attribute_definition(self, attrid):
attrs = self._schema["attributes"]
try:
# Make a new dict to avoid side effects
return dict(attrs[attrid])
except KeyError:
attr_names = self._schema["attribute_names"]
... | You are a Python code architect, reviewing and designing scalable and efficient code |
Returns the ID and localized name of the given quality | Can you generate the documentation for the following Python 3 function
def _quality_definition(self, qid):
qualities = self._schema["qualities"]
try:
return qualities[qid]
except KeyError:
qid = self._schema["quality_names"].get(str(qid).lower(), 0)
return qu... | You are a Python code analyst, evaluating scripts for potential improvements. |
def attributes(self):
""" Returns all attributes in the schema """
attrs = self._schema["attributes"]
return [item_attribute(attr) for attr in sorted(attrs.values(),
key=operator.itemgetter("defindex"))] | Can you create a Python 3 function that
returns all attributes in the schema | As a Python code translator, you convert algorithms and pseudocode into Python. |
Returns a localized origin name for a given ID | How would you explain what the following Python 3 function does
def origin_id_to_name(self, origin):
try:
oid = int(origin)
except (ValueError, TypeError):
return None
return self.origins.get(oid) | You are a Python code architect, reviewing and designing scalable and efficient code |
def attributes(self):
""" Returns a list of attributes """
overridden_attrs = self._attributes
sortmap = {"neutral": 1, "positive": 2,
"negative": 3}
sortedattrs = list(overridden_attrs.values())
sortedattrs.sort(key=operator.itemgetter("defindex"))
s... | Can you implement a function in Python 3 that
returns a list of attributes that are available in the current object. | You are a Python code architect, reviewing and designing scalable and efficient code |
def equipped(self):
""" Returns a dict of classes that have the item equipped and in what slot """
equipped = self._item.get("equipped", [])
# WORKAROUND: 0 is probably an off-by-one error
# WORKAROUND: 65535 actually serves a purpose (according to Valve)
return dict([(eq["class... | Implement a Python 3 function for
returning a dict of classes that have the item equipped and in what slot | You are a Python code generator, capable of creating scripts from specifications. |
def equipable_classes(self):
""" Returns a list of classes that _can_ use the item. """
sitem = self._schema_item
return [c for c in sitem.get("used_by_classes", self.equipped.keys()) if c] | Can you create a Python 3 function that
returns a list of classes that can be used by the item. | You are a Python code generator, capable of creating scripts from specifications. |
def contents(self):
""" Returns the item in the container, if there is one.
This will be a standard item object. """
rawitem = self._item.get("contained_item")
if rawitem:
return self.__class__(rawitem, self._schema) | Can you write a function in Python 3 where it
returns the item in the container if there is one. | You are a Python code analyst, evaluating scripts for potential improvements. |
def rank(self):
"""
Returns the item's rank (if it has one)
as a dict that includes required score, name, and level.
"""
if self._rank != {}:
# Don't bother doing attribute lookups again
return self._rank
try:
# The eater determining ... | Implement a function in Python 3 to
return the item s rank if it has one. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def available_styles(self):
""" Returns a list of all styles defined for the item """
styles = self._schema_item.get("styles", [])
return list(map(operator.itemgetter("name"), styles)) | Create a Python 3 function for
returning a list of all styles defined for the item | As a Python code translator, you convert algorithms and pseudocode into Python. |
Returns a formatted value for the current object. | Can you generate the documentation for the following Python 3 function
def formatted_value(self):
# TODO: Cleanup all of this, it's just weird and unnatural maths
val = self.value
pval = val
ftype = self.value_type
if ftype == "percentage":
pval = int(round(val * 100... | You are a Python code generator, capable of creating scripts from specifications. |
def formatted_description(self):
""" Returns a formatted description string (%s* tokens replaced) or None if unavailable """
desc = self.description
if desc:
return desc.replace("%s1", self.formatted_value)
else:
return None | Create a Python 3 function to
return a formatted description string for the current object. | As a Python code analyst, you investigate and solve complex coding mysteries |
The type of the value in the item. | Given the following Python 3 function, write the documentation
def value_type(self):
redundantprefix = "value_is_"
vtype = self._attribute.get("description_format")
if vtype and vtype.startswith(redundantprefix):
return vtype[len(redundantprefix):]
else:
return v... | You are a Python code architect, reviewing and designing scalable and efficient code |
A dict with two keys persona and id64. | Here you have a function in Python 3, explain what it does
def account_info(self):
account_info = self._attribute.get("account_info")
if account_info:
return {"persona": account_info.get("personaname", ""),
"id64": account_info["steamid"]}
else:
return... | You are a Python code generator, capable of creating scripts from specifications. |
def tags(self):
""" Returns a dict containing tags and their localized labels as values """
return dict([(t, self._catalog.tags.get(t, t)) for t in self._asset.get("tags", [])]) | Can you write a function in Python 3 where it
returns a dict containing tags and their localized labels as values | You are a Python code analyst, evaluating scripts for potential improvements. |
def vanity(self):
""" Returns the user's vanity url if it exists, None otherwise """
purl = self.profile_url.strip('/')
if purl.find("/id/") != -1:
return os.path.basename(purl) | Write a Python 3 function for
returning the user s vanity url if it exists None otherwise. | You are a Python code generator, capable of creating scripts from specifications. |
def creation_date(self):
""" Returns the account creation date as a localtime time.struct_time
struct if public"""
timestamp = self._prof.get("timecreated")
if timestamp:
return time.localtime(timestamp) | Can you implement a function in Python 3 that
returns the creation date as a localtime. struct_time struct if public | As a Python code composer, you craft elegant and concise scripts. |
Returns a tuple of 3 elements each of which may be None | Can you tell what is the following Python 3 function doing
def current_game(self):
obj = self._prof
gameid = obj.get("gameid")
gameserverip = obj.get("gameserverip")
gameextrainfo = obj.get("gameextrainfo")
return (int(gameid) if gameid else None, gameserverip, gameextrainfo) | As a python code expert, you are capable of creating scripts from specifications. |
def level(self):
"""
Returns the the user's profile level, note that this runs a separate
request because the profile level data isn't in the standard player summary
output even though it should be. Which is also why it's not implemented
as a separate class. You won't need this o... | Write a Python 3 function that can
return the user s profile level | As a python code expert, you are capable of creating scripts from specifications. |
Builds a profile object from a raw player summary object | Can you tell what is the following Python 3 function doing
def from_def(cls, obj):
prof = cls(obj["steamid"])
prof._cache = obj
return prof | You are a Python code architect, reviewing and designing scalable and efficient code |
Called when a status is withheld | Explain what the following Python 3 code does
def on_status_withheld(self, status_id, user_id, countries):
logger.info('Status %s withheld for user %s', status_id, user_id)
return True | As a Python code translator, you convert algorithms and pseudocode into Python. |
Called when a disconnect is received | Explain what the following Python 3 code does
def on_disconnect(self, code, stream_name, reason):
logger.error('Disconnect message: %s %s %s', code, stream_name, reason)
return True | You are a Python code analyst, evaluating scripts for potential improvements. |
def on_error(self, status_code):
"""Called when a non-200 status code is returned"""
logger.error('Twitter returned error code %s', status_code)
self.error = status_code
return False | Implement a Python 3 function for
calling when a non - 200 status code is returned | You are a Python code generator, capable of creating scripts from specifications. |
Called when an exception occurs in the streaming thread | Explain what the following Python 3 code does
def on_exception(self, exception):
logger.error('Exception from stream!', exc_info=True)
self.streaming_exception = exception | You are a Python code architect, reviewing and designing scalable and efficient code |
def check(self):
"""
Checks if the list of tracked terms has changed.
Returns True if changed, otherwise False.
"""
new_tracking_terms = self.update_tracking_terms()
terms_changed = False
# any deleted terms?
if self._tracking_terms_set > new_tracking_t... | Write a Python 3 function that can
check if the list of tracked terms has changed. Returns True if changed otherwise False. | You are a Python code generator, capable of creating scripts from specifications. |
Update the tracking terms of the current node. | How would you explain what the following Python 3 function does
def update_tracking_terms(self):
import codecs
with codecs.open(self.filename,"r", encoding='utf8') as input:
# read all the lines
lines = input.readlines()
# build a set of terms
new_terms =... | As a Python code composer, you craft elegant and concise scripts. |
def launch_debugger(frame, stream=None):
"""
Interrupt running process, and provide a python prompt for
interactive debugging.
"""
d = {'_frame': frame} # Allow access to frame object.
d.update(frame.f_globals) # Unless shadowed by global
d.update(frame.f_locals)
import code, traceba... | Write a Python 3 script to
interrupt running process, and provide a python prompt for interactive debugging. | As a Python code analyst, you investigate and solve complex coding mysteries |
Break into a debugger if receives the SIGUSR1 signal | How would you explain what the following Python 3 function does
def set_debug_listener(stream):
def debugger(sig, frame):
launch_debugger(frame, stream)
if hasattr(signal, 'SIGUSR1'):
signal.signal(signal.SIGUSR1, debugger)
else:
logger.warn("Cannot set SIGUSR1 signal for debug mod... | As a python code expert, you are capable of creating scripts from specifications. |
def set_terminate_listeners(stream):
"""Die on SIGTERM or SIGINT"""
def stop(signum, frame):
terminate(stream.listener)
# Installs signal handlers for handling SIGINT and SIGTERM
# gracefully.
signal.signal(signal.SIGINT, stop)
signal.signal(signal.SIGTERM, stop) | Create a Python 3 function for
setting up signal handlers for handling SIGTERM and SIGINT. | You are a Python code analyst, evaluating scripts for potential improvements. |
def get_tweepy_auth(twitter_api_key,
twitter_api_secret,
twitter_access_token,
twitter_access_token_secret):
"""Make a tweepy auth object"""
auth = tweepy.OAuthHandler(twitter_api_key, twitter_api_secret)
auth.set_access_token(twitter_access_token,... | Can you implement a function in Python 3 that
creates a tweepy auth object | You are a Python code generator, capable of creating scripts from specifications. |
def construct_listener(outfile=None):
"""Create the listener that prints tweets"""
if outfile is not None:
if os.path.exists(outfile):
raise IOError("File %s already exists" % outfile)
outfile = open(outfile, 'wb')
return PrintingListener(out=outfile) | Can you implement a function in Python 3 that
creates the listener that prints tweets | As a Python code translator, you convert algorithms and pseudocode into Python. |
def begin_stream_loop(stream, poll_interval):
"""Start and maintain the streaming connection..."""
while should_continue():
try:
stream.start_polling(poll_interval)
except Exception as e:
# Infinite restart
logger.error("Exception while polling. Restarting in ... | Create a Python 3 function for
starting and maintain the streaming connection... | You are a Python code analyst, evaluating scripts for potential improvements. |
def on_status(self, status):
"""Print out some tweets"""
self.out.write(json.dumps(status))
self.out.write(os.linesep)
self.received += 1
return not self.terminate | Write a Python 3 script for
printing out some tweets | You are a Python code analyst, evaluating scripts for potential improvements. |
def print_status(self):
"""Print out the current tweet rate and reset the counter"""
tweets = self.received
now = time.time()
diff = now - self.since
self.since = now
self.received = 0
if diff > 0:
logger.info("Receiving tweets at %s tps", tweets / dif... | Create a Python 3 function for
printing out the current status and reset the counter | As a python code expert, you are capable of creating scripts from specifications. |
Start polling for term updates and streaming. | Make a summary of the following Python 3 code
def start_polling(self, interval):
interval = float(interval)
self.polling = True
# clear the stored list of terms - we aren't tracking any
self.term_checker.reset()
logger.info("Starting polling for changes to the track list")
... | You are a Python code generator, capable of creating scripts from specifications. |
def update_stream(self):
"""
Restarts the stream with the current list of tracking terms.
"""
need_to_restart = False
# If we think we are running, but something has gone wrong in the streaming thread
# Restart it.
if self.stream is not None and not self.stream.... | Can you implement a function in Python 3 that
restarts the stream with the current list of tracking terms. | You are a Python code architect, reviewing and designing scalable and efficient code |
def start_stream(self):
"""Starts a stream with teh current tracking terms"""
tracking_terms = self.term_checker.tracking_terms()
if len(tracking_terms) > 0 or self.unfiltered:
# we have terms to track, so build a new stream
self.stream = tweepy.Stream(self.auth, self.l... | Write a Python 3 script for
starting a new stream with teh current tracking terms | You are a Python code architect, reviewing and designing scalable and efficient code |
Stops the current stream. | Can you tell what is the following Python 3 function doing
def stop_stream(self):
if self.stream is not None:
# There is a streaming thread
logger.warning("Stopping twitter stream...")
self.stream.disconnect()
self.stream = None
# wait a few second... | You are a Python code generator, capable of creating scripts from specifications. |
Apply the local presentation logic to the fetched data. | Make a summary of the following Python 3 code
def enrich(self, tweet):
tweet = urlize_tweet(expand_tweet_urls(tweet))
# parses created_at "Wed Aug 27 13:08:45 +0000 2008"
if settings.USE_TZ:
tweet['datetime'] = datetime.strptime(tweet['created_at'], '%a %b %d %H:%M:%S +0000 %Y').rep... | As a python code expert, you are capable of creating scripts from specifications. |
Generate suitable key to cache twitter tag context | Here you have a function in Python 3, explain what it does
def get_user_cache_key(**kwargs):
key = 'get_tweets_%s' % ('_'.join([str(kwargs[key]) for key in sorted(kwargs) if kwargs[key]]))
not_allowed = re.compile('[^%s]' % ''.join([chr(i) for i in range(33, 128)]))
key = not_allowed.sub('', key)
return... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Generate suitable key to cache twitter tag context | Given the following Python 3 function, write the documentation
def get_search_cache_key(prefix, *args):
key = '%s_%s' % (prefix, '_'.join([str(arg) for arg in args if arg]))
not_allowed = re.compile('[^%s]' % ''.join([chr(i) for i in range(33, 128)]))
key = not_allowed.sub('', key)
return key | As a python code expert, you are capable of creating scripts from specifications. |
Turn the text in a tweet to Twitter hyperlinks | Given the following Python 3 function, write the documentation
def urlize_tweet(tweet):
text = tweet.get('html', tweet['text'])
for hash in tweet['entities']['hashtags']:
text = text.replace('#%s' % hash['text'], TWITTER_HASHTAG_URL % (quote(hash['text'].encode("utf-8")), hash['text']))
for mention ... | As a Python code composer, you craft elegant and concise scripts. |
Replace shortened URLs with long URLs in the twitter status and add the RT flag. | How would you explain what the following Python 3 function does
def expand_tweet_urls(tweet):
if 'retweeted_status' in tweet:
text = 'RT @{user}: {text}'.format(user=tweet['retweeted_status']['user']['screen_name'],
text=tweet['retweeted_status']['text'])
u... | You are a Python code architect, reviewing and designing scalable and efficient code |
safe_power - Calculates the power of two numbers | Given the following Python 3 function, write the documentation
def safe_power(a, b):
if abs(a) > MAX_POWER or abs(b) > MAX_POWER:
raise ValueError('Number too high!')
return a ** b | As a Python code translator, you convert algorithms and pseudocode into Python. |
def rabin_miller(p):
"""
Performs a rabin-miller primality test
:param p: Number to test
:return: Bool of whether num is prime
"""
# From this stackoverflow answer: https://codegolf.stackexchange.com/questions/26739/super-speedy-totient-function
if p < 2:
return False
if p != 2 ... | Create a Python 3 function for
performing a rabin-miller primality test :param p: Number to test :return: Bool of whether num is prime | You are a Python code analyst, evaluating scripts for potential improvements. |
Split a string on a regex that only matches zero - width strings
| Make a summary of the following Python 3 code
def zero_width_split(pattern, string):
splits = list((m.start(), m.end()) for m in regex.finditer(pattern, string, regex.VERBOSE))
starts = [0] + [i[1] for i in splits]
ends = [i[0] for i in splits] + [len(string)]
return [string[start:end] for start, end in... | As a Python code composer, you craft elegant and concise scripts. |
Rolls a group of dice in 2d6 3d10 d12 etc. format
| Explain what the following Python 3 code does
def roll_group(group):
group = regex.match(r'^(\d*)d(\d+)$', group, regex.IGNORECASE)
num_of_dice = int(group[1]) if group[1] != '' else 1
type_of_dice = int(group[2])
assert num_of_dice > 0
result = []
for i in range(num_of_dice):
result.ap... | You are a Python code generator, capable of creating scripts from specifications. |
Returns the number of elements in a list that pass a comparison on a dice roll
| Can you generate a brief explanation for the following Python 3 code
def num_equal(result, operator, comparator):
if operator == '<':
return len([x for x in result if x < comparator])
elif operator == '>':
return len([x for x in result if x > comparator])
elif operator == '=':
return... | You are a Python code architect, reviewing and designing scalable and efficient code |
Rolls dice in dice notation with advanced syntax used according to tinyurl. com. | Can you tell what is the following Python 3 function doing
def roll_dice(roll, *, functions=True, floats=True):
roll = ''.join(roll.split())
roll = regex.sub(r'(?<=d)%', '100', roll, regex.IGNORECASE)
roll = roll.replace('^', '**')
roll = zero_width_split(r'((?<=[\(\),%^\/+*-])(?=.))|((?<=.)(?=[\(\),%^\... | You are a Python code architect, reviewing and designing scalable and efficient code |
Evaluate an expression and return the result. | Given the following Python 3 function, write the documentation
def eval(self, expr):
# set a copy of the expression aside, so we can give nice errors...
self.expr = expr
# and evaluate:
return self._eval(ast.parse(expr.strip()).body[0].value) | As a Python code analyst, you investigate and solve complex coding mysteries |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.