output stringlengths 1 928k | instruction stringlengths 7 928k | system stringlengths 0 104k |
|---|---|---|
def validate(self, obj):
"""check if obj has this api param"""
if self.path:
for i in self.path:
obj = obj[i]
obj = obj[self.field]
raise NotImplementedError('Validation is not implemented yet') | Can you implement a function in Python 3 that
checks if obj has this api param | You are a Python code architect, reviewing and designing scalable and efficient code |
make a nice docstring for ipython | Can you tell what is the following Python 3 function doing
def render_docstring(self):
default = (' = ' + str(self.default)) if self.default else ''
opt = 'optional' if self.is_optional else ''
can_be = ' '.join(self.possible_values) if self.possible_values else ''
can_be = 'one of [{}]'... | As a Python code composer, you craft elegant and concise scripts. |
validator for plumbum prompt | Here you have a function in Python 3, explain what it does
def is_uuid(u):
if isinstance(u, str) and u.replace('-', '') == uuid.UUID(u).hex:
return u
return False | As a Python code translator, you convert algorithms and pseudocode into Python. |
Load the AUTH_CONF file and return the config dict. | Can you tell what is the following Python 3 function doing
def load_conf(configfile, config=None):
default_login = 'your-login-for-api-here'
default_password = 'your-password-for-api-here'
config = config or {}
configfile = local.path(configfile)
if not configfile.exists():
configfile.dirnam... | As a python code expert, you are capable of creating scripts from specifications. |
get content from server or cache | Given the following Python 3 function, write the documentation
def get_content(api, rebuild_cache=False):
if hasattr(get_content, 'cache') and not rebuild_cache:
return get_content.cache
if not os.path.exists(CONTENT_JSON) or rebuild_cache:
import locale
content_endpoint = api.content.ge... | As a python code expert, you are capable of creating scripts from specifications. |
returns list of non - user rewards | Make a summary of the following Python 3 code
def get_additional_rewards(api):
c = get_content(api)
tasks = [c[i] for i in ['potion', 'armoire']]
tasks.extend(api.user.inventory.buy.get())
for task in tasks:
task['id'] = task['alias'] = task['key']
return tasks | You are a Python code architect, reviewing and designing scalable and efficient code |
Augment the existing cls. __init__ method with a new one which also initialises the field generators and similar bookkeeping. | Can you generate the documentation for the following Python 3 function
def augment_init_method(cls):
orig_init = cls.__init__
def new_init(self, *args, **kwargs):
super(CustomGenerator, self).__init__() # TODO: does this behave correctly with longer inheritance chains?
orig_init(self, *args,... | As a python code expert, you are capable of creating scripts from specifications. |
def find_field_generators(obj):
"""
Return dictionary with the names and instances of
all tohu.BaseGenerator occurring in the given
object's class & instance namespaces.
"""
cls_dict = obj.__class__.__dict__
obj_dict = obj.__dict__
#debug_print_dict(cls_dict, 'cls_dict')
#debug_prin... | Write a Python 3 script for
finding all tohu. BaseGenerator occurring in the given object s class & instance namespaces. | You are a Python code analyst, evaluating scripts for potential improvements. |
def set_item_class_name(cls_obj):
"""
Return the first part of the class name of this custom generator.
This will be used for the class name of the items produced by this
generator.
Examples:
FoobarGenerator -> Foobar
QuuxGenerator -> Quux
"""
if '__tohu__items__name__' in... | How would you implement a function in Python 3 that
sets the class name of the items produced by this custom generator. | As a python code expert, you are capable of creating scripts from specifications. |
Returns the class name for the item class for the given custom generator instance. | Can you tell what is the following Python 3 function doing
def make_item_class_for_custom_generator(obj):
clsname = obj.__tohu_items_name__
attr_names = obj.field_gens.keys()
return make_item_class(clsname, attr_names) | You are a Python code architect, reviewing and designing scalable and efficient code |
Add a new init method to obj. | Can you generate a brief explanation for the following Python 3 code
def add_new_init_method(obj):
orig_init = obj.__init__
def new_init(self, *args, **kwargs):
logger.debug(f"Initialising new {self}")
# Call original __init__ function to ensure we pick up
# any tohu generators that a... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def add_new_reset_method(obj):
"""
Attach a new `reset()` method to `obj` which resets the internal
seed generator of `obj` and then resets each of its constituent
field generators found in `obj.field_gens`.
"""
#
# Create and assign automatically generated reset() method
#
def ne... | Write a Python 3 function for
adding a new reset method to obj which resets the internal internal | As a Python code translator, you convert algorithms and pseudocode into Python. |
Add a method to obj that returns the next item in the hierarchy. | Given the following Python 3 function, write the documentation
def add_new_next_method(obj):
def new_next(self):
field_values = [next(g) for g in self.field_gens.values()]
return self.item_cls(*field_values)
obj.__next__ = new_next | As a Python code composer, you craft elegant and concise scripts. |
Add a new spawn method to the object. | Make a summary of the following Python 3 code
def add_new_spawn_method(obj):
def new_spawn(self):
# TODO/FIXME: Check that this does the right thing:
# (i) the spawned generator is independent of the original one (i.e. they can be reset independently without altering the other's behaviour)
... | You are a Python code architect, reviewing and designing scalable and efficient code |
Helper function to check that the operator op can be applied to items produced by g1 and g2. | Explain what the following Python 3 code does
def check_that_operator_can_be_applied_to_produces_items(op, g1, g2):
g1_tmp_copy = g1.spawn()
g2_tmp_copy = g2.spawn()
sample_item_1 = next(g1_tmp_copy)
sample_item_2 = next(g2_tmp_copy)
try:
op(sample_item_1, sample_item_2)
except TypeError... | You are a Python code generator, capable of creating scripts from specifications. |
Add a new init method to the class. | Make a summary of the following Python 3 code
def add_new_init_method(cls):
orig_init = cls.__init__
def new_init(self, *args, **kwargs):
self._dependent_generators = []
orig_init(self, *args, **kwargs)
cls.__init__ = new_init | As a python code expert, you are capable of creating scripts from specifications. |
def add_new_repr_method(cls):
"""
Add default __repr__ method in case no user-defined one is present.
"""
if isinstance(cls.__repr__, WrapperDescriptorType):
cls.__repr__ = lambda self: f"<{self.__class__.__name__}, id={hex(id(self))}>"
else:
# Keep the user-defined __repr__ method
... | Can you create a Python 3 function that
adds default __repr__ method in case no user - defined one is present. | You are a Python code analyst, evaluating scripts for potential improvements. |
Add a new reset method to the class which also replaces existing cls. reset method with a new one which also adds a new reset method which also adds a new reset method to any clones. | Given the following Python 3 function, write the documentation
def add_new_reset_method(cls):
orig_reset = cls.reset
def new_reset(self, seed=None):
logger.debug(f"Calling reset() on {self} (seed={seed})")
orig_reset(self, seed)
for c in self._dependent_generators:
c.reset_d... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Generate a sequence of N elements from the current generator. | Can you generate the documentation for the following Python 3 function
def generate(self, N, *, seed=None, progressbar=False):
if seed is not None:
self.reset(seed)
items = islice(self, N)
if progressbar:
items = tqdm(items, total=N)
item_list = [x for x in items... | You are a Python code architect, reviewing and designing scalable and efficient code |
Return the tohu id of the current object. | Here you have a function in Python 3, explain what it does
def tohu_id(self):
myhash = hashlib.md5(str(id(self)).encode()).hexdigest()
return myhash[:12] | You are a Python code generator, capable of creating scripts from specifications. |
def _set_item_class(self):
"""
cls:
The custom generator class for which to create an item-class
"""
clsname = self.__tohu_items_name__
self.item_cls = make_item_class(clsname, self.field_names) | Implement a Python 3 function for
setting the item class for which to generate the item. | You are a Python code generator, capable of creating scripts from specifications. |
Find all tohu generators defined in the class and instance namespace
and return a dictionary of the form {name : field_generator containing
all tohu generators defined in the class and instance namespace
. | Can you generate the documentation for the following Python 3 function
def _find_field_generator_templates(self):
field_gen_templates = {}
# Extract field generators from class dict
for name, g in self.__class__.__dict__.items():
if isinstance(g, TohuBaseGenerator):
... | As a python code expert, you are capable of creating scripts from specifications. |
def _extract_schema_if_given(table_name):
"""
Return a pair (schema, table) derived from the given `table_name`
(anything before the first '.' if the name contains one; otherwise
the return value of `schema` is None).
Examples:
>>> _extract_schema_if_given('some_schema.my_table')
(... | How would you code a function in Python 3 to
extract schema and table from a given table name. | As a Python code composer, you craft elegant and concise scripts. |
def to_df(self, fields=None):
"""
Export items as rows in a pandas dataframe table.
Parameters
----------
fields: list or dict
List of field names to export, or dictionary mapping output column names
to attribute names of the generators.
Exa... | Create a Python 3 function to
export items as rows in a pandas dataframe table. | As a python code expert, you are capable of creating scripts from specifications. |
def to_csv(self, filename=None, *, fields=None, append=False, header=True, header_prefix='', sep=',', newline='\n'):
"""
Parameters
----------
filename: str or None
The file to which output will be written. By default, any existing content is
overwritten. Use `app... | Write a Python 3 script for
exporting the current state of the object to a CSV file. | As a Python code analyst, you investigate and solve complex coding mysteries |
def spawn_generator(self, g):
"""
Return a fresh spawn of g unless g is already
contained in this SpawnMapping, in which case
return the previously spawned generator.
"""
try:
return self.mapping[g]
except KeyError:
return g._spawn(self) | Can you write a function in Python 3 where it
returns a fresh spawn of g unless g is already there. | As a Python code composer, you craft elegant and concise scripts. |
Spawn a new generator which behaves the same way as this one. | Can you tell what is the following Python 3 function doing
def spawn(self, spawn_mapping=None):
spawn_mapping = spawn_mapping or SpawnMapping()
if self.parent is not None:
if self.parent in spawn_mapping:
# Return new clone of the mapped parent
return spawn_m... | As a python code expert, you are capable of creating scripts from specifications. |
def clone(self, spawn_mapping=None):
"""
Return an exact copy of this generator which behaves the same way
(i.e., produces the same elements in the same order) and which is
automatically reset whenever the original generator is reset.
"""
c = self.spawn(spawn_mapping)
... | Write a Python 3 function that can
return an exact copy of this generator which behaves the same way returns the same copy and which is the same elements in the same order as the original generator. | You are a Python code architect, reviewing and designing scalable and efficient code |
Iterate over all generators in the context. | Can you generate a brief explanation for the following Python 3 code
def all_generators(self):
for arg_gen in self.arg_gens:
yield arg_gen
for kwarg_gen in self.kwarg_gens.values():
yield kwarg_gen | You are a Python code analyst, evaluating scripts for potential improvements. |
Splits a generator into individual generators. | Here you have a function in Python 3, explain what it does
def Split(g, *, maxbuffer=10, tuple_len=None):
if tuple_len is None:
try:
tuple_len = g.tuple_len
except AttributeError:
raise ValueError("Argument 'tuple_len' must be given since generator is not of type TupleGenerat... | You are a Python code generator, capable of creating scripts from specifications. |
Returns the length of the tuple produced by this generator. | Explain what the following Python 3 code does
def tuple_len(self):
try:
return self._tuple_len
except AttributeError:
raise NotImplementedError("Class {} does not implement attribute 'tuple_len'.".format(self.__class__.__name__)) | As a Python code translator, you convert algorithms and pseudocode into Python. |
def show_faults():
"""
Return all valid/active faults ordered by ID to allow the user to pick and choose.
:return: List of Tuples where the Tuple elements are: (fault id, fault template)
"""
cursor = CONN.cursor()
query = "select fau_id, fault from surfaults where fau_is_valid = 'y' order by... | Write a Python 3 function for
returning all valid and active faults ordered by ID. | You are a Python code analyst, evaluating scripts for potential improvements. |
Return all valid and active sentences ordered by ID. | Explain what the following Python 3 code does
def show_sentences():
cursor = CONN.cursor()
query = "select sen_id, sentence from sursentences where sen_is_valid = 'y' order by sen_id asc"
cursor.execute(query)
result = cursor.fetchall()
response_dict = {}
for row in result:
response_d... | As a Python code analyst, you investigate and solve complex coding mysteries |
def get_fault(fault_id=None):
"""Retrieve a randomly-generated error message as a unicode string.
:param fault_id:
Allows you to optionally specify an integer representing the fault_id
from the database table. This allows you to retrieve a specific fault
each time, albeit... | How would you implement a function in Python 3 that
retrieves a randomly - generated error message as a unicode string. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Retrieves a randomly - generated sentence from the database table. | Given the following Python 3 function, write the documentation
def get_sentence(sentence_id=None):
counts = __get_table_limits()
result = None
id_ = 0
try:
if isinstance(sentence_id, int):
id_ = sentence_id
elif isinstance(sentence_id, float):
print("""ValueErro... | As a python code expert, you are capable of creating scripts from specifications. |
Let s fetch a random sentence that we then need to substitute bits of... | How would you explain what the following Python 3 function does
def __get_sentence(counts, sentence_id=None):
# First of all we need a cursor and a query to retrieve our ID's
cursor = CONN.cursor()
check_query = "select sen_id from sursentences"
# Now we fetch the result of the query and save it into ... | You are a Python code analyst, evaluating scripts for potential improvements. |
Let s fetch a VERB by random number | Can you generate a brief explanation for the following Python 3 code
def __get_verb(counts):
cursor = CONN.cursor()
check_query = "select verb_id from surverbs"
cursor.execute(check_query)
check_result = cursor.fetchall()
id_list = []
for row in check_result:
id_list.append(row[0])
... | You are a Python code generator, capable of creating scripts from specifications. |
This function takes a count of each of the database tables so we know our max_adjectives max_names max_nouns max_sentences max_faults max_verbs and max_verb to the calling function... | Here you have a function in Python 3, explain what it does
def __get_table_limits():
table_counts = {
'max_adjectives': None,
'max_names': None,
'max_nouns': None,
'max_sentences': None,
'max_faults': None,
'max_verbs': None
}
cursor = CONN.cursor()
cur... | You are a Python code analyst, evaluating scripts for potential improvements. |
process a single sentence from the tuple | Make a summary of the following Python 3 code
def __process_sentence(sentence_tuple, counts):
sentence = sentence_tuple[2]
# now we start replacing words one type at a time...
sentence = __replace_verbs(sentence, counts)
sentence = __replace_nouns(sentence, counts)
sentence = ___replace_adjectiv... | You are a Python code analyst, evaluating scripts for potential improvements. |
def __replace_verbs(sentence, counts):
"""Lets find and replace all instances of #VERB
:param _sentence:
:param counts:
"""
if sentence is not None:
while sentence.find('#VERB') != -1:
sentence = sentence.replace('#VERB', str(__get_verb(counts)), 1)
if sentence.find... | Create a Python 3 function for
letting find and replace all instances of verbs with the same value | You are a Python code generator, capable of creating scripts from specifications. |
Lets find and replace all instances of NOUN with the corresponding number | Given the following Python 3 function, write the documentation
def __replace_nouns(sentence, counts):
if sentence is not None:
while sentence.find('#NOUN') != -1:
sentence = sentence.replace('#NOUN', str(__get_noun(counts)), 1)
if sentence.find('#NOUN') == -1:
retur... | As a Python code composer, you craft elegant and concise scripts. |
Lets find and replace all instances of ADJECTIVE_MAYBE and ADJECTIVE_MAYBE with the appropriate value. | Given the following Python 3 function, write the documentation
def ___replace_adjective_maybe(sentence, counts):
random_decision = random.randint(0, 1)
if sentence is not None:
while sentence.find('#ADJECTIVE_MAYBE') != -1:
if random_decision % 2 == 0:
sentence = sentence... | You are a Python code generator, capable of creating scripts from specifications. |
def __replace_adjective(sentence, counts):
"""Lets find and replace all instances of #ADJECTIVE
:param _sentence:
:param counts:
"""
if sentence is not None:
while sentence.find('#ADJECTIVE') != -1:
sentence = sentence.replace('#ADJECTIVE',
... | Write a Python 3 script for
letting find and replace all instances of ADJECTIVE and get the correct ID | As a Python code translator, you convert algorithms and pseudocode into Python. |
def __replace_names(sentence, counts):
"""Lets find and replace all instances of #NAME
:param _sentence:
:param counts:
"""
if sentence is not None:
while sentence.find('#NAME') != -1:
sentence = sentence.replace('#NAME', str(__get_name(counts)), 1)
if sentence.fin... | Write a Python 3 script to
let find and replace all instances of NAME with the corresponding names. | You are a Python code generator, capable of creating scripts from specifications. |
def __replace_an(sentence):
"""Lets find and replace all instances of #AN
This is a little different, as this depends on whether the next
word starts with a vowel or a consonant.
:param _sentence:
"""
if sentence is not None:
while sentence.find('#AN') != -1:
an_index = sen... | Can you create a Python 3 function that
lets find and replace all instances of an in the next A sequence. | You are a Python code analyst, evaluating scripts for potential improvements. |
def __replace_random(sentence):
"""Lets find and replace all instances of #RANDOM
:param _sentence:
"""
sub_list = None
choice = None
if sentence is not None:
while sentence.find('#RANDOM') != -1:
random_index = sentence.find('#RANDOM')
start_index = sentence.... | Can you write a function in Python 3 where it
lets find and replace all instances of RANDOM with a random one. | As a python code expert, you are capable of creating scripts from specifications. |
Replaces repeating random elements in a word sentence. | Can you tell what is the following Python 3 function doing
def __replace_repeat(sentence):
######### USE SENTENCE_ID 47 for testing!
repeat_dict = {}
if sentence is not None:
while sentence.find('#DEFINE_REPEAT') != -1:
begin_index = sentence.find('#DEFINE_REPEAT')
start_... | As a Python code analyst, you investigate and solve complex coding mysteries |
This function replaces all instances of the uppercase and cap the next word in the sentence. | Explain what the following Python 3 code does
def __replace_capitalise(sentence):
if sentence is not None:
while sentence.find('#CAPITALISE') != -1:
cap_index = _sentence.find('#CAPITALISE')
part1 = sentence[:cap_index]
part2 = sentence[cap_index + 12:cap_index + 13]
... | You are a Python code analyst, evaluating scripts for potential improvements. |
replace all CAPALL with uppercase | Explain what the following Python 3 code does
def __replace_capall(sentence):
# print "\nReplacing CAPITALISE: "
if sentence is not None:
while sentence.find('#CAPALL') != -1:
# _cap_index = _sentence.find('#CAPALL')
sentence = sentence.upper()
sentence = sentence.... | As a Python code analyst, you investigate and solve complex coding mysteries |
def explode_columns(df, colnames):
"""
Given a dataframe with certain columns that contain lists,
return another dataframe where the elements in each list
are "exploded" into individual rows.
Example:
>>> df
col1 col2 col3 col4
0 foo 11 [DDD, AAA, CCC] [dd... | How would you code a function in Python 3 to
give a dataframe with certain columns that contain lists return another dataframe where the elements in each list are "exploded" into individual rows. | As a Python code composer, you craft elegant and concise scripts. |
Helper function which prints a sequence of num items produced by the random generator gen. | Here you have a function in Python 3, explain what it does
def print_generated_sequence(gen, num, *, sep=", ", fmt='', seed=None):
if seed:
gen.reset(seed)
elems = [format(next(gen), fmt) for _ in range(num)]
sep_initial = "\n\n" if '\n' in sep else " "
print("Generated sequence:{}{}".format(sep... | You are a Python code generator, capable of creating scripts from specifications. |
def ensure_is_date_object(x):
"""
Ensure input represents a valid date and return the corresponding `datetime.date` object.
Valid inputs:
- string of the form "YYYY-MM-DD"
- dt.date object
- pd.Timestamp of the form "YYYY-MM-DD 00:00:00" with freq='D' (as is generated by pd.date_range())... | Can you create a Python 3 function that
ensures input represents a valid date and return the corresponding datetime. date object. | As a python code expert, you are capable of creating scripts from specifications. |
Return all generators in this namespace which are not clones. | Can you generate the documentation for the following Python 3 function
def all_independent_generators(self):
return {g: name for g, name in self._ns.items() if not is_clone(g)} | As a python code expert, you are capable of creating scripts from specifications. |
def make_tohu_items_class(clsname, attr_names):
"""
Parameters
----------
clsname: string
Name of the class to be created
attr_names: list of strings
Names of the attributes of the class to be created
"""
item_cls = attr.make_class(clsname, {name: attr.ib() for name in attr... | Can you write a function in Python 3 where it
creates a new class which can be used to create a tohu items class. | As a python code expert, you are capable of creating scripts from specifications. |
Returns a string which defines the name of the class which will be used by the custom generator. | How would you explain what the following Python 3 function does
def get_tohu_items_name(cls):
assert issubclass(cls, TohuBaseGenerator)
try:
tohu_items_name = cls.__dict__['__tohu_items_name__']
logger.debug(f"Using item class name '{tohu_items_name}' (derived from attribute '__tohu_items_name_... | You are a Python code analyst, evaluating scripts for potential improvements. |
Initializes the random generator to be used for picking elements from the input sequence. | Make a summary of the following Python 3 code
def _init_randgen(self):
if self.p is None:
self.randgen = Random()
self.func_random_choice = self.randgen.choice
else:
self.randgen = np.random.RandomState()
self.func_random_choice = partial(self.randgen.choi... | As a Python code composer, you craft elegant and concise scripts. |
Transfer the internal state from other to self. | Given the following Python 3 function, write the documentation
def _set_random_state_from(self, other):
try:
# this works if randgen is an instance of random.Random()
self.randgen.setstate(other.randgen.getstate())
except AttributeError:
# this works if randgen is an ... | You are a Python code analyst, evaluating scripts for potential improvements. |
Initializes the random generator to be used for picking elements from the input sequence. | Make a summary of the following Python 3 code
def _init_randgen(self):
if self.p is None:
self.randgen = Random()
self.func_random_choice = partial(self.randgen.choices, k=self.num)
else:
self.randgen = np.random.RandomState()
self.func_random_choice = par... | As a Python code analyst, you investigate and solve complex coding mysteries |
Helper function which updates the dict field_gens with any items in the dict adict that are instances of TohuUltraBaseGenerator. | Can you generate a brief explanation for the following Python 3 code
def update_with_tohu_generators(field_gens, adict):
for name, gen in adict.items():
if isinstance(gen, TohuUltraBaseGenerator):
field_gens[name] = gen | As a Python code translator, you convert algorithms and pseudocode into Python. |
def find_field_generator_templates(obj):
"""
Return dictionary with the names and instances of
all tohu.BaseGenerator occurring in the given
object's class & instance namespaces.
"""
cls_dict = obj.__class__.__dict__
obj_dict = obj.__dict__
#debug_print_dict(cls_dict, 'cls_dict')
#d... | Write a Python 3 function that can
find all tohu. BaseGenerator templates occurring in the given object. | As a Python code analyst, you investigate and solve complex coding mysteries |
Set the class name of the items to be produced by the custom generator class. | Can you generate the documentation for the following Python 3 function
def set_item_class_name_on_custom_generator_class(cls):
if '__tohu__items__name__' in cls.__dict__:
logger.debug(
f"Using item class name '{cls.__tohu_items_name__}' (derived from attribute '__tohu_items_name__')")
else:
... | You are a Python code generator, capable of creating scripts from specifications. |
Returns the class that is used to create the item class for the given custom generator class. | Can you generate a brief explanation for the following Python 3 code
def make_item_class_for_custom_generator_class(cls):
clsname = cls.__tohu_items_name__
attr_names = cls.field_gens.keys()
return make_item_class(clsname, attr_names) | As a Python code translator, you convert algorithms and pseudocode into Python. |
Add a new init method to the class. | Here you have a function in Python 3, explain what it does
def _add_new_init_method(cls):
orig_init = cls.__init__
def new_init_method(self, *args, **kwargs):
logger.debug(f"Initialising new {self} (type: {type(self)})")
# Call original __init__ function to ensure we pick up
# any toh... | As a python code expert, you are capable of creating scripts from specifications. |
def _add_new_next_method(cls):
"""
TODO
"""
def new_next(self):
field_values = [next(g) for g in self.field_gens.values()]
return self.item_cls(*field_values)
cls.__next__ = new_next | Implement a Python 3 function for
adding a new next method to the class. | As a Python code analyst, you investigate and solve complex coding mysteries |
def _add_new_reset_method(cls):
"""
Attach a new `reset()` method to `cls` which resets the internal
seed generator of `cls` and then resets each of its constituent
field generators found in `cls.field_gens`.
"""
#
# Create and assign automatically generated reset() method
#
def n... | How would you implement a function in Python 3 that
adds a new reset method to cls which resets the internal internal | You are a Python code analyst, evaluating scripts for potential improvements. |
Add a new spawn method to the class. | Here you have a function in Python 3, explain what it does
def _add_new_spawn_method(cls):
def new_spawn_method(self, dependency_mapping):
# TODO/FIXME: Check that this does the right thing:
# (i) the spawned generator is independent of the original one (i.e. they can be reset independently without... | As a Python code composer, you craft elegant and concise scripts. |
Reset all input generators to the derived generator. | Here you have a function in Python 3, explain what it does
def reset_input_generators(self, seed):
seed_generator = SeedGenerator().reset(seed=seed)
for gen in self.input_generators:
gen.reset(next(seed_generator))
try:
# In case `gen` is itself a derived generat... | As a Python code analyst, you investigate and solve complex coding mysteries |
Helper function to spot - check that the items produces by this generator have the attribute name. | Here you have a function in Python 3, explain what it does
def _spot_check_that_elements_produced_by_this_generator_have_attribute(self, name):
g_tmp = self.values_gen.spawn()
sample_element = next(g_tmp)[0]
try:
getattr(sample_element, name)
except AttributeError:
... | As a Python code composer, you craft elegant and concise scripts. |
def to_df(self, fields=None, fields_to_explode=None):
"""
Export items as rows in a pandas dataframe table.
Parameters
----------
fields: list or dict
List of field names to export, or dictionary mapping output column names
to attribute names of the gene... | How would you implement a function in Python 3 that
exports items as rows in a pandas dataframe table. | You are a Python code generator, capable of creating scripts from specifications. |
Exports the current state of the entry to a CSV file. | Can you generate the documentation for the following Python 3 function
def to_csv(self, output_file=None, *, fields=None, fields_to_explode=None, append=False, header=True, header_prefix='', sep=',', newline='\n'):
assert isinstance(append, bool)
if fields is None:
raise NotImplementedError... | As a Python code analyst, you investigate and solve complex coding mysteries |
Export items in a PostgreSQL table. | Can you generate a brief explanation for the following Python 3 code
def to_sql(self, url, table_name, *, schema=None, fields=None, fields_to_explode=None, if_exists="fail", dtype=None):
if schema is None:
schema, table_name = _extract_schema_if_given(table_name)
engine = create_engine(url)... | You are a Python code architect, reviewing and designing scalable and efficient code |
Reset this generator s seed generator and any clones. | Here you have a function in Python 3, explain what it does
def reset(self, seed):
logger.debug(f'Resetting {self} (seed={seed})')
self.seed_generator.reset(seed)
for c in self.clones:
c.reset(seed) | You are a Python code architect, reviewing and designing scalable and efficient code |
Load the config from the object. | Make a summary of the following Python 3 code
def _load_config(initial_namespace=None, defaults=None):
# type: (Optional[str], Optional[str]) -> ConfigLoader
"""
Kwargs:
initial_namespace:
defaults:
"""
# load defaults
if defaults:
config = ConfigLoader()
config.u... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Override environment vars and reload the Settings object | Make a summary of the following Python 3 code
def override_environment(settings, **kwargs):
# type: (Settings, **str) -> Generator
"""
Override env vars and reload the Settings object
NOTE:
Obviously this context has to be in place before you import any
module which reads env values at import t... | You are a Python code analyst, evaluating scripts for potential improvements. |
Imports a YAML file into a configuration object | How would you explain what the following Python 3 function does
def _import_yaml(config_file_path):
try:
logger.info('Importing config %s...', config_file_path)
with open(config_file_path) as config_file:
return yaml.safe_load(config_file.read())
except IOError as ex:
raise R... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Get all files under base_dir that match filename_regex. | Make a summary of the following Python 3 code
def _get_all_files(filename_regex,
path,
base_dir,
excluded_paths=None,
excluded_filename_regex=None):
"""Get all files for processing.
This starts iterating from `base_dir` and checks for ... | As a Python code composer, you craft elegant and concise scripts. |
Check if the user provided tags match the tags set in the config. | Explain what the following Python 3 code does
def _match_tags(repex_tags, path_tags):
if 'any' in repex_tags or (not repex_tags and not path_tags):
return True
elif set(repex_tags) & set(path_tags):
return True
return False | You are a Python code generator, capable of creating scripts from specifications. |
def iterate(config_file_path=None,
config=None,
variables=None,
tags=None,
validate=True,
validate_only=False,
with_diff=False):
"""Iterate over all paths in `config_file_path`
:param string config_file_path: a path to a repex config file
... | How would you code a function in Python 3 to
iterate over all paths in config_file_path and process each. | You are a Python code architect, reviewing and designing scalable and efficient code |
def handle_path(pathobj, variables=None, diff=False):
"""Iterate over all chosen files in a path
:param dict pathobj: a dict of a specific path in the config
:param dict variables: a dict of variables (can be None)
"""
logger.info('Handling path with description: %s',
pathobj.get('d... | Implement a function in Python 3 to
handle a path in a single or multiple files in a single archive. | You are a Python code architect, reviewing and designing scalable and efficient code |
def _build_vars_dict(vars_file='', variables=None):
"""Merge variables into a single dictionary
Applies to CLI provided variables only
"""
repex_vars = {}
if vars_file:
with open(vars_file) as varsfile:
repex_vars = yaml.safe_load(varsfile.read())
for var in variables:
... | Create a Python 3 function to
build a dictionary of variables that can be used to create a new node. | You are a Python code analyst, evaluating scripts for potential improvements. |
This function is used to run the repex command line interface. | Can you generate a brief explanation for the following Python 3 code
def main(verbose, **kwargs):
config = kwargs['config']
if not config and not kwargs['regex_path']:
click.echo('Must either provide a path or a viable repex config file.')
sys.exit(1)
if verbose:
set_verbose()
... | As a Python code analyst, you investigate and solve complex coding mysteries |
This function expands a variable in a file and returns a dict with the expanded variables. | Can you generate the documentation for the following Python 3 function
def expand(self, repex_vars, fields):
logger.debug('Expanding variables...')
unexpanded_instances = set()
# Expand variables in variables
# TODO: This should be done in the global scope.
# _VariableHandler i... | You are a Python code generator, capable of creating scripts from specifications. |
def _expand_var(self, in_string, available_variables):
"""Expand variable to its corresponding value in_string
:param string variable: variable name
:param value: value to replace with
:param string in_string: the string to replace in
"""
instances = self._get_instances(... | Can you implement a function in Python 3 that
expands variable to its corresponding value in_string | You are a Python code generator, capable of creating scripts from specifications. |
def validate_before(self, content, file_to_handle):
"""Verify that all required strings are in the file
"""
logger.debug('Looking for required strings: %s', self.must_include)
included = True
for string in self.must_include:
if not re.search(r'{0}'.format(string), con... | Write a Python 3 function that can
verify that all required strings are in the file_to_handle and that all required strings are in the file_to_handle. | You are a Python code architect, reviewing and designing scalable and efficient code |
def find_matches(self, content, file_to_handle):
"""Find all matches of an expression in a file
"""
# look for all match groups in the content
groups = [match.groupdict() for match in
self.match_expression.finditer(content)]
# filter out content not in the match... | Create a Python 3 function to
find all matches of an expression in a file | You are a Python code generator, capable of creating scripts from specifications. |
def replace(self, match, content):
"""Replace all occurences of the regex in all matches
from a file with a specific value.
"""
new_string = self.replace_expression.sub(self.replace_with, match)
logger.info('Replacing: [ %s ] --> [ %s ]', match, new_string)
new_content = ... | Implement a function in Python 3 to
replace all occurences of the regex in all matches from a file with a specific value. | As a Python code analyst, you investigate and solve complex coding mysteries |
Set exit events on certain events. | Explain what the following Python 3 code does
def set_exit_events(self, no_workers=None, idle=None, reload=None, sig_term=None):
self._set('die-on-no-workers', no_workers, cast=bool)
self._set('exit-on-reload', reload, cast=bool)
self._set('die-on-term', sig_term, cast=bool)
self.set_idl... | As a Python code composer, you craft elegant and concise scripts. |
def set_exception_handling_params(self, handler=None, catch=None, no_write_exception=None):
"""Exception handling related params.
:param str|unicode|list[str|unicode] handler: Register one or more exception handling C-functions.
:param bool catch: Catch exceptions and report them as http outpu... | Create a Python 3 function to
set exception handling related params. | You are a Python code analyst, evaluating scripts for potential improvements. |
def set_idle_params(self, timeout=None, exit=None):
"""Activate idle mode - put uWSGI in cheap mode after inactivity timeout.
:param int timeout: Inactivity timeout in seconds.
:param bool exit: Shutdown uWSGI when idle.
"""
self._set('idle', timeout)
self._set('die-on... | How would you implement a function in Python 3 that
activates idle mode - put uWSGI in cheap mode after inactivity timeout in seconds. exit - shutdown uWSGI when idle. | You are a Python code architect, reviewing and designing scalable and efficient code |
Set reload related params. | Here you have a function in Python 3, explain what it does
def set_reload_params(self, mercy=None, exit=None):
self._set('reload-mercy', mercy)
self.set_exit_events(reload=exit)
return self._section | You are a Python code analyst, evaluating scripts for potential improvements. |
def add_cron_task(
self, command, weekday=None, month=None, day=None, hour=None, minute=None,
legion=None, unique=None, harakiri=None):
"""Adds a cron task running the given command on the given schedule.
http://uwsgi.readthedocs.io/en/latest/Cron.html
HINTS:
... | Write a Python 3 script for
adding a cron task to the schedule. | You are a Python code generator, capable of creating scripts from specifications. |
def attach_process_classic(self, command_or_pid_path, background, control=False, for_legion=False):
"""Attaches a command/daemon to the master process optionally managed by a pidfile.
This will allow the uWSGI master to control/monitor/respawn this process.
.. note:: This uses old classic uWSG... | Write a Python 3 function for
attaching a command or pid to the master process optionally managed by a pidfile. | As a Python code analyst, you investigate and solve complex coding mysteries |
Attaches a command to a daemon process. | Here you have a function in Python 3, explain what it does
def attach_process(
self, command, for_legion=False, broken_counter=None, pidfile=None, control=None, daemonize=None,
touch_reload=None, signal_stop=None, signal_reload=None, honour_stdin=None,
uid=None, gid=None, new_pid_ns=... | As a Python code composer, you craft elegant and concise scripts. |
def set_basic_params(
self, check_interval_busy=None,
busy_max=None, busy_min=None,
idle_cycles_max=None, idle_cycles_penalty=None,
verbose=None):
"""
:param int check_interval_busy: Interval (sec) to check worker busyness.
:param int busy_max: Ma... | Can you write a function in Python 3 where it
sets basic parameters for ChEMERGENCY and CLEAR. | You are a Python code generator, capable of creating scripts from specifications. |
def set_emergency_params(
self, workers_step=None, idle_cycles_max=None, queue_size=None, queue_nonzero_delay=None):
"""Sets busyness algorithm emergency workers related params.
Emergency workers could be spawned depending upon uWSGI backlog state.
.. note:: These options are Linux... | Write a Python 3 function that can
set busyness algorithm emergency workers related params. | You are a Python code architect, reviewing and designing scalable and efficient code |
Sets basic parameters for the application. | How would you explain what the following Python 3 function does
def set_basic_params(
self, spawn_on_request=None,
cheaper_algo=None, workers_min=None, workers_startup=None, workers_step=None):
"""
:param bool spawn_on_request: Spawn workers only after the first request.
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Sets worker memory limits for cheapening. | Can you tell what is the following Python 3 function doing
def set_memory_limits(self, rss_soft=None, rss_hard=None):
self._set('cheaper-rss-limit-soft', rss_soft)
self._set('cheaper-rss-limit-hard', rss_hard)
return self._section | You are a Python code generator, capable of creating scripts from specifications. |
def get_version(self, as_tuple=False):
"""Returns uWSGI version string or tuple.
:param bool as_tuple:
:rtype: str|tuple
"""
if as_tuple:
return uwsgi.version_info
return decode(uwsgi.version) | Write a Python 3 script to
return uWSGI version string or tuple. | As a python code expert, you are capable of creating scripts from specifications. |
def register_route(self, route_rules, label=None):
"""Registers a routing rule.
:param RouteRule|list[RouteRule] route_rules:
:param str|unicode label: Label to mark the given set of rules.
This can be used in conjunction with ``do_goto`` rule action.
* http://uwsgi.re... | Can you implement a function in Python 3 that
registers a routing rule. | You are a Python code generator, capable of creating scripts from specifications. |
def set_error_page(self, status, html_fpath):
"""Add an error page (html) for managed 403, 404, 500 response.
:param int status: HTTP status code.
:param str|unicode html_fpath: HTML page file path.
"""
statuses = [403, 404, 500]
status = int(status)
if statu... | Write a Python 3 script for
adding an error page for managed 403 404 500 response. | You are a Python code analyst, evaluating scripts for potential improvements. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.