output
stringlengths
1
928k
instruction
stringlengths
7
928k
system
stringlengths
0
104k
def return_fv_by_seeds(fv, seeds=None, unique_cls=None): """ Return features selected by seeds and unique_cls or selection from features and corresponding seed classes. :param fv: ndarray with lineariezed feature. It's shape is MxN, where M is number of image pixels and N is number of features :par...
Write a Python 3 function that can return features selected by seeds and unique_cls or just fv for whole image.
You are a Python code generator, capable of creating scripts from specifications.
Returns a gutter client.
Make a summary of the following Python 3 code def get_gutter_client( alias='default', cache=CLIENT_CACHE, **kwargs ): """ Creates gutter clients and memoizes them in a registry for future quick access. Args: alias (str or None): Name of the client. Used for caching. ...
As a Python code composer, you craft elegant and concise scripts.
modulo is a wrapper around the mod operator.
How would you explain what the following Python 3 function does def _modulo(self, decimal_argument): _times, remainder = self._context.divmod(decimal_argument, 100) # match the builtin % behavior by adding the N to the result if negative return remainder if remainder >= 0 else remainder + 100
You are a Python code generator, capable of creating scripts from specifications.
Returns True if the switch is enabled for the input.
Make a summary of the following Python 3 code def enabled_for(self, inpt): signals.switch_checked.call(self) signal_decorated = partial(self.__signal_and_return, inpt) if self.state is self.states.GLOBAL: return signal_decorated(True) elif self.state is self.states.DISABLED...
As a Python code analyst, you investigate and solve complex coding mysteries
def call(self, inpt): """ Returns if the condition applies to the ``inpt``. If the class ``inpt`` is an instance of is not the same class as the condition's own ``argument``, then ``False`` is returned. This also applies to the ``NONE`` input. Otherwise, ``argument`` i...
Create a Python 3 function to return if the condition applies to the inpt.
You are a Python code generator, capable of creating scripts from specifications.
def switches(self): """ List of all switches currently registered. """ results = [ switch for name, switch in self.storage.iteritems() if name.startswith(self.__joined_namespace) ] return results
Create a Python 3 function to return a list of all switches currently registered.
You are a Python code architect, reviewing and designing scalable and efficient code
def switch(self, name): """ Returns the switch with the provided ``name``. If ``autocreate`` is set to ``True`` and no switch with that name exists, a ``DISABLED`` switch will be with that name. Keyword Arguments: name -- A name of a switch. """ try: ...
Can you write a function in Python 3 where it returns the switch with the provided name.
As a Python code composer, you craft elegant and concise scripts.
def register(self, switch, signal=signals.switch_registered): ''' Register a switch and persist it to the storage. ''' if not switch.name: raise ValueError('Switch name cannot be blank') switch.manager = self self.__persist(switch) signal.call(switch...
Create a Python 3 function for registering a switch and persist it to the storage.
As a Python code composer, you craft elegant and concise scripts.
A simple interface to stub functions on a given object.
Explain what the following Python 3 code does def when(obj, strict=None): if isinstance(obj, str): obj = get_obj(obj) if strict is None: strict = True theMock = _get_mock(obj, strict=strict) class When(object): def __getattr__(self, method_name): return invocation....
You are a Python code analyst, evaluating scripts for potential improvements.
Stub a function call with the given arguments returning an answer selector that exposes thenReturn thenRaise and thenAnswer.
Given the following Python 3 function, write the documentation def when2(fn, *args, **kwargs): obj, name = get_obj_attr_tuple(fn) theMock = _get_mock(obj, strict=True) return invocation.StubbedInvocation(theMock, name)(*args, **kwargs)
As a Python code composer, you craft elegant and concise scripts.
Stub a function call and set up an expected call count.
Given the following Python 3 function, write the documentation def expect(obj, strict=None, times=None, atleast=None, atmost=None, between=None): """Stub a function call, and set up an expected call count. Usage:: # Given `dog` is an instance of a `Dog` expect(dog, times=1).bark('Wu...
You are a Python code architect, reviewing and designing scalable and efficient code
def verifyZeroInteractions(*objs): """Verify that no methods have been called on given objs. Note that strict mocks usually throw early on unexpected, unstubbed invocations. Partial mocks ('monkeypatched' objects or modules) do not support this functionality at all, bc only for the stubbed invocations ...
How would you implement a function in Python 3 that verifies that no methods have been called on given objs.
As a Python code translator, you convert algorithms and pseudocode into Python.
Verifies that expectations set via expect are met
Can you generate the documentation for the following Python 3 function def verifyNoUnwantedInteractions(*objs): if objs: theMocks = map(_get_mock_or_raise, objs) else: theMocks = mock_registry.get_registered_mocks() for mock in theMocks: for i in mock.stubbed_invocations: ...
You are a Python code generator, capable of creating scripts from specifications.
def verifyStubbedInvocationsAreUsed(*objs): """Ensure stubs are actually used. This functions just ensures that stubbed methods are actually used. Its purpose is to detect interface changes after refactorings. It is meant to be invoked usually without arguments just before :func:`unstub`. """ ...
Can you implement a function in Python 3 that ensures that stubbed methods are actually used.
As a Python code analyst, you investigate and solve complex coding mysteries
Return obj for given dotted path.
Here you have a function in Python 3, explain what it does def get_obj(path): # Since we usually pass in mocks here; duck typing is not appropriate # (mocks respond to every attribute). if not isinstance(path, str): return path if path.startswith('.'): raise TypeError('relative imports ...
You are a Python code analyst, evaluating scripts for potential improvements.
def get_obj_attr_tuple(path): """Split path into (obj, attribute) tuple. Given `path` is 'os.path.exists' will thus return `(os.path, 'exists')` If path is not a str, delegates to `get_function_host(path)` """ if not isinstance(path, str): return get_function_host(path) if path.start...
Write a Python 3 function for splitting path into obj attribute tuple.
As a python code expert, you are capable of creating scripts from specifications.
def spy(object): """Spy an object. Spying means that all functions will behave as before, so they will be side effects, but the interactions can be verified afterwards. Returns Dummy-like, almost empty object as proxy to `object`. The *returned* object must be injected and used by the code under ...
Create a Python 3 function for spying an object. Spying means that all functions will behave as before, so they will be side effects, but the interactions can be verified afterwards. Returns Dummy-like, almost empty object as proxy to `object`. The *returned* object must be injected and used by the code under test; aft...
As a Python code composer, you craft elegant and concise scripts.
Spy usage of given fn.
How would you explain what the following Python 3 function does def spy2(fn): # type: (...) -> None if isinstance(fn, str): answer = get_obj(fn) else: answer = fn when2(fn, Ellipsis).thenAnswer(answer)
As a Python code translator, you convert algorithms and pseudocode into Python.
def mock(config_or_spec=None, spec=None, strict=OMITTED): """Create 'empty' objects ('Mocks'). Will create an empty unconfigured object, that you can pass around. All interactions (method calls) will be recorded and can be verified using :func:`verify` et.al. A plain `mock()` will be not `strict`,...
Implement a function in Python 3 to create an empty mock object.
You are a Python code architect, reviewing and designing scalable and efficient code
def importPuppetClasses(self, smartProxyId): """ Function importPuppetClasses Force the reload of puppet classes @param smartProxyId: smartProxy Id @return RETURN: the API result """ return self.api.create('{}/{}/import_puppetclasses' .form...
How would you implement a function in Python 3 that functions importPuppetClasses Force the reload of puppet classes
As a Python code analyst, you investigate and solve complex coding mysteries
def get_templates(model): """ Return a list of templates usable by a model. """ for template_name, template in templates.items(): if issubclass(template.model, model): yield (template_name, template.layout._meta.verbose_name)
How would you code a function in Python 3 to return a list of templates usable by a model.
As a Python code translator, you convert algorithms and pseudocode into Python.
Decorator for creating admin site classes.
Given the following Python 3 function, write the documentation def attach(*layouts, **kwargs): def _model_admin_wrapper(layout_class): register(layout_class, layouts[0]) return layout_class return _model_admin_wrapper
You are a Python code generator, capable of creating scripts from specifications.
Function enhance Enhance the object with new item or enhanced items
Explain what the following Python 3 code does def enhance(self): self.update({'os_default_templates': SubDict(self.api, self.objName, self.payloadObj, self.key, SubItemOsDefaultTemplate)}) self.update({'config_templates': ...
As a Python code translator, you convert algorithms and pseudocode into Python.
Get required API keys from environment variables.
Can you generate the documentation for the following Python 3 function def get_api_envs(): client_id = os.environ.get('CLIENT_ID') user_id = os.environ.get('USER_ID') if not client_id or not user_id: raise ValueError('API keys are not found in the environment') return client_id, user_id
As a python code expert, you are capable of creating scripts from specifications.
def api_call(method, end_point, params=None, client_id=None, access_token=None): """Call given API end_point with API keys. :param method: HTTP method (e.g. 'get', 'delete'). :param end_point: API endpoint (e.g. 'users/john/sets'). :param params: Dictionary to be sent in the query string (e.g. {'myparam...
Can you create a Python 3 function that calls given API end_point with API keys.
You are a Python code generator, capable of creating scripts from specifications.
Request upload secret for a key
Can you generate the documentation for the following Python 3 function def request_upload_secret(self, secret_id): return self._router.post_request_upload_secret(org_id=self.organizationId, instance_id=self.instanceId, ...
You are a Python code generator, capable of creating scripts from specifications.
Function checkAndCreate Check if a subnet exists and create it if not
Can you generate a brief explanation for the following Python 3 code def checkAndCreate(self, key, payload, domainId): if key not in self: self[key] = payload oid = self[key]['id'] if not oid: return False #~ Ensure subnet contains the domain subnetDomainI...
As a Python code translator, you convert algorithms and pseudocode into Python.
Function removeDomain Delete a domain from a subnet
How would you explain what the following Python 3 function does def removeDomain(self, subnetId, domainId): subnetDomainIds = [] for domain in self[subnetId]['domains']: subnetDomainIds.append(domain['id']) subnetDomainIds.remove(domainId) self[subnetId]["domain_ids"] = subne...
As a Python code composer, you craft elegant and concise scripts.
Decorator for creating a new object that is exclusive across all instances of the object.
Can you tell what is the following Python 3 function doing def exclusive(via=threading.Lock): def make_exclusive(fnc): fnc_guard = via() @functools.wraps(fnc) def exclusive_call(*args, **kwargs): if fnc_guard.acquire(blocking=False): try: retu...
As a Python code analyst, you investigate and solve complex coding mysteries
def execute(self, payload, *args, flavour: ModuleType, **kwargs): """ Synchronously run ``payload`` and provide its output If ``*args*`` and/or ``**kwargs`` are provided, pass them to ``payload`` upon execution. """ if args or kwargs: payload = functools.partial(payl...
Write a Python 3 function for executing a payload asynchronously and provide its output
You are a Python code analyst, evaluating scripts for potential improvements.
Adoptes the payload in the background.
Can you generate the documentation for the following Python 3 function def adopt(self, payload, *args, flavour: ModuleType, **kwargs): if args or kwargs: payload = functools.partial(payload, *args, **kwargs) self._meta_runner.register_payload(payload, flavour=flavour)
You are a Python code analyst, evaluating scripts for potential improvements.
Start accepting synchronous asynchronous and service payloads
Make a summary of the following Python 3 code def accept(self): if self._meta_runner: raise RuntimeError('payloads scheduled for %s before being started' % self) self._must_shutdown = False self._logger.info('%s starting', self.__class__.__name__) # force collecting objects s...
As a Python code translator, you convert algorithms and pseudocode into Python.
Shutdown the accept loop and stop running payloads
Can you generate a brief explanation for the following Python 3 code def shutdown(self): self._must_shutdown = True self._is_shutdown.wait() self._meta_runner.stop()
You are a Python code architect, reviewing and designing scalable and efficient code
def milestones(ctx, list, close): """View/edit/close milestones on github """ repos = get_repos(ctx.parent.agile.get('labels')) if list: _list_milestones(repos) elif close: click.echo('Closing milestones "%s"' % close) _close_milestone(repos, close) else: click.ec...
Can you create a Python 3 function that views / edit / close milestones on github
As a Python code analyst, you investigate and solve complex coding mysteries
Starts a console ; modified from code. interact
Explain what the following Python 3 code does def start_console(local_vars={}): '''Starts a console; modified from code.interact''' transforms.CONSOLE_ACTIVE = True transforms.remove_not_allowed_in_console() sys.ps1 = prompt console = ExperimentalInteractiveConsole(locals=local_vars) console.int...
As a python code expert, you are capable of creating scripts from specifications.
def push(self, line): """Transform and push a line to the interpreter. The line should not have a trailing newline; it may have internal newlines. The line is appended to a buffer and the interpreter's runsource() method is called with the concatenated contents of the buffer as...
Can you implement a function in Python 3 that transforms and push a line to the interpreter.
You are a Python code analyst, evaluating scripts for potential improvements.
Writes a dict object into a TOML file
How would you explain what the following Python 3 function does def dump(obj, f, preserve=False): if not f.write: raise TypeError('You can only dump an object into a file object') encoder = Encoder(f, preserve=preserve) return encoder.write_dict(obj)
As a Python code composer, you craft elegant and concise scripts.
def license_loader(lic_dir=LIC_DIR): """Loads licenses from the given directory.""" lics = [] for ln in os.listdir(lic_dir): lp = os.path.join(lic_dir, ln) with open(lp) as lf: txt = lf.read() lic = License(txt) lics.append(lic) return lics
Create a Python 3 function to load licenses from the given directory.
As a Python code translator, you convert algorithms and pseudocode into Python.
Return pseudo - choice vectors.
Here you have a function in Python 3, explain what it does def get_vector(self, max_choice=3): vec = {} for dim in ['forbidden', 'required', 'permitted']: if self.meta[dim] is None: continue dim_vec = map(lambda x: (x, max_choice), self.meta[dim]) vec[...
As a python code expert, you are capable of creating scripts from specifications.
This function is used to create a new entity for the current user.
Can you generate the documentation for the following Python 3 function def entity(ctx, debug, uncolorize, **kwargs): global PROVIDER_CONFIG if debug: log.basicConfig(level=log.DEBUG) log.getLogger("requests.packages.urllib3.connectionpool").setLevel(log.DEBUG) for (k, v) in kwargs.iteritems...
You are a Python code analyst, evaluating scripts for potential improvements.
def import_app(files, category, overwrite, id, name): """ Upload application from file. By default, file name will be used as application name, with "-vXX.YYY" suffix stripped. Application is looked up by one of these classifiers, in order of priority: app-id, app-name, filename. If app-id is prov...
Write a Python 3 script for uploading application from files to the current user s organization.
You are a Python code analyst, evaluating scripts for potential improvements.
Shows current account in a tonomi api shell - friendly form. Takes into account explicit top - level flags like organization.
Given the following Python 3 function, write the documentation def show_account(): click.echo("# tonomi api") for (key, env) in REVERSE_MAPPING.items(): value = QUBELL.get(key, None) if value: click.echo("export %s='%s'" % (env, value)) if any(map(lambda x: PROVIDER.get(x), REVER...
As a Python code composer, you craft elegant and concise scripts.
def generate_session_token(refresh_token, verbose): """ Generates new session token from the given refresh token. :param refresh_token: refresh token to generate from :param verbose: whether expiration time should be added to output """ platform = _get_platform(authenticated=False) session_...
How would you code a function in Python 3 to generate a new session token from the given refresh token.
You are a Python code architect, reviewing and designing scalable and efficient code
Command to plot the c - M relation and the D08 predictions in black - order.
Given the following Python 3 function, write the documentation def plotcommand(cosmology='WMAP5', plotname=None): # Plot the c-M relation as a functon of redshift xarray = 10**(np.arange(1, 15, 0.2)) yval = 'c' # Specify the redshift range zarray = np.arange(0, 5, 0.5) xtitle = r"Halo Mass (M...
You are a Python code architect, reviewing and designing scalable and efficient code
def enhance(self): """ Function enhance Enhance the object with new item or enhanced items """ self.update({'puppetclasses': SubDict(self.api, self.objName, self.payloadObj, self.key, SubItemPuppetClasses)}) ...
How would you code a function in Python 3 to function enhance Enhance the object with new item or enhanced items
As a Python code analyst, you investigate and solve complex coding mysteries
Extract the transformers names from a line of code of the form from __experimental__ import transformer1 [... ] and add them to the globally known dict
How would you explain what the following Python 3 function does def add_transformers(line): '''Extract the transformers names from a line of code of the form from __experimental__ import transformer1 [,...] and adds them to the globally known dict ''' assert FROM_EXPERIMENTAL.match(line) ...
You are a Python code analyst, evaluating scripts for potential improvements.
def import_transformer(name): '''If needed, import a transformer, and adds it to the globally known dict The code inside a module where a transformer is defined should be standard Python code, which does not need any transformation. So, we disable the import hook, and let the normal module impo...
Write a Python 3 function that can import a transformer and adds it to the globally known dict ATTRIBS.
As a python code expert, you are capable of creating scripts from specifications.
def extract_transformers_from_source(source): '''Scan a source for lines of the form from __experimental__ import transformer1 [,...] identifying transformers to be used. Such line is passed to the add_transformer function, after which it is removed from the code to be executed. ''' ...
Write a Python 3 script to scan a source file for lines of the form from __experimental__ import transformer1...
You are a Python code analyst, evaluating scripts for potential improvements.
This function is called from the console when it starts.
Can you tell what is the following Python 3 function doing def remove_not_allowed_in_console(): '''This function should be called from the console, when it starts. Some transformers are not allowed in the console and they could have been loaded prior to the console being activated. We effectively remove th...
You are a Python code analyst, evaluating scripts for potential improvements.
This function transforms the source code by calling all known transformers and then returning the transformed source.
Here you have a function in Python 3, explain what it does def transform(source): '''Used to convert the source code, making use of known transformers. "transformers" are modules which must contain a function transform_source(source) which returns a tranformed source. Some transfo...
You are a Python code analyst, evaluating scripts for potential improvements.
Match all requests and responses that satisfy the conditions
Explain what the following Python 3 code does def _match(self, request, response): is_html = 'text/html' in response.get('Content-Type', '') if is_html and hasattr(response, 'rendered_content'): correct_path = PATH_MATCHER.match(request.path) is not None not_included = self.inclu...
You are a Python code generator, capable of creating scripts from specifications.
Read the minified CSS file including STATIC_URL in the references to the sprite images.
Explain what the following Python 3 code does def _chosen_css(self): css = render_to_string(self.css_template, {}) for sprite in self.chosen_sprites: # rewrite path to sprites in the css css = css.replace(sprite, settings.STATIC_URL + "img/" + sprite) return css
You are a Python code architect, reviewing and designing scalable and efficient code
def _embed(self, request, response): """Embed Chosen.js directly in html of the response.""" if self._match(request, response): # Render the <link> and the <script> tags to include Chosen. head = render_to_string( "chosenadmin/_head_css.html", {"ch...
Write a Python 3 script to embed Chosen. js directly in html of the response.
As a Python code composer, you craft elegant and concise scripts.
def clean_up(self): """ Close the I2C bus """ self.log.debug("Closing I2C bus for address: 0x%02X" % self.address) self.bus.close()
How would you code a function in Python 3 to clean up the I2C bus.
As a python code expert, you are capable of creating scripts from specifications.
def write_quick(self): """ Send only the read / write bit """ self.bus.write_quick(self.address) self.log.debug("write_quick: Sent the read / write bit")
Write a Python 3 script to send only the read / write bit
You are a Python code generator, capable of creating scripts from specifications.
def write_byte(self, cmd, value): """ Writes an 8-bit byte to the specified command register """ self.bus.write_byte_data(self.address, cmd, value) self.log.debug( "write_byte: Wrote 0x%02X to command register 0x%02X" % ( value, cmd ) ...
Write a Python 3 script for writing an 8 - bit byte to the specified command register.
You are a Python code generator, capable of creating scripts from specifications.
def write_word(self, cmd, value): """ Writes a 16-bit word to the specified command register """ self.bus.write_word_data(self.address, cmd, value) self.log.debug( "write_word: Wrote 0x%04X to command register 0x%02X" % ( value, cmd ) ...
Can you create a Python 3 function that writes a 16 - bit word to the specified command register.
As a Python code analyst, you investigate and solve complex coding mysteries
Writes an 8 - bit byte directly to the bus.
Can you tell what is the following Python 3 function doing def write_raw_byte(self, value): self.bus.write_byte(self.address, value) self.log.debug("write_raw_byte: Wrote 0x%02X" % value)
You are a Python code analyst, evaluating scripts for potential improvements.
Writes a block of bytes to the specified command register.
Can you generate a brief explanation for the following Python 3 code def write_block_data(self, cmd, block): self.bus.write_i2c_block_data(self.address, cmd, block) self.log.debug( "write_block_data: Wrote [%s] to command register 0x%02X" % ( ', '.join(['0x%02X' % x for x in ...
You are a Python code analyst, evaluating scripts for potential improvements.
def read_raw_byte(self): """ Read an 8-bit byte directly from the bus """ result = self.bus.read_byte(self.address) self.log.debug("read_raw_byte: Read 0x%02X from the bus" % result) return result
Write a Python 3 script to read an 8 - bit byte directly from the bus
You are a Python code architect, reviewing and designing scalable and efficient code
Read a block of bytes from the bus from the specified command register.
How would you explain what the following Python 3 function does def read_block_data(self, cmd, length): results = self.bus.read_i2c_block_data(self.address, cmd, length) self.log.debug( "read_block_data: Read [%s] from command register 0x%02X" % ( ', '.join(['0x%02X' % x for ...
You are a Python code architect, reviewing and designing scalable and efficient code
def read_unsigned_byte(self, cmd): """ Read an unsigned byte from the specified command register """ result = self.bus.read_byte_data(self.address, cmd) self.log.debug( "read_unsigned_byte: Read 0x%02X from command register 0x%02X" % ( result, cmd ...
Can you write a function in Python 3 where it reads an unsigned byte from the specified command register.
As a Python code composer, you craft elegant and concise scripts.
def read_unsigned_word(self, cmd, little_endian=True): """ Read an unsigned word from the specified command register We assume the data is in little endian mode, if it is in big endian mode then set little_endian to False """ result = self.bus.read_word_data(self.address,...
Write a Python 3 script to read an unsigned word from the specified command register.
As a Python code translator, you convert algorithms and pseudocode into Python.
def __connect_to_bus(self, bus): """ Attempt to connect to an I2C bus """ def connect(bus_num): try: self.log.debug("Attempting to connect to bus %s..." % bus_num) self.bus = smbus.SMBus(bus_num) self.log.debug("Success") ...
How would you implement a function in Python 3 that attempts to connect to an I2C bus and returns the I2C object.
As a Python code composer, you craft elegant and concise scripts.
Default user to the current version owner.
How would you explain what the following Python 3 function does def get_formset(self, request, obj=None, **kwargs): data = super().get_formset(request, obj, **kwargs) if obj: data.form.base_fields['user'].initial = request.user.id return data
As a Python code composer, you craft elegant and concise scripts.
Function reload Reload the full object to ensure sync
Can you generate a brief explanation for the following Python 3 code def reload(self): realData = self.load() self.clear() self.update(realData)
You are a Python code architect, reviewing and designing scalable and efficient code
Decorator to ensure local dict is sync with remote foreman
Explain what the following Python 3 code does def updateAfterDecorator(function): def _updateAfterDecorator(self, *args, **kwargs): ret = function(self, *args, **kwargs) self.reload() return ret return _updateAfterDecorator
As a Python code composer, you craft elegant and concise scripts.
def updateBeforeDecorator(function): """ Function updateAfterDecorator Decorator to ensure local dict is sync with remote foreman """ def _updateBeforeDecorator(self, *args, **kwargs): if self.forceFullSync: self.reload() return function(self, *arg...
Write a Python 3 function for functioning updateAfterDecorator Decorator to ensure local dict is sync with remote foreman
As a Python code composer, you craft elegant and concise scripts.
def load(self): """ Function load Get the list of all objects @return RETURN: A ForemanItem list """ return {x[self.index]: self.itemType(self.api, x['id'], self.objName, self.payloadObj, x...
Implement a Python 3 function for functioning load Get the list of all objects
As a Python code analyst, you investigate and solve complex coding mysteries
Function checkAndCreate Check if an object exists and create it if not
Here you have a function in Python 3, explain what it does def checkAndCreate(self, key, payload): if key not in self: self[key] = payload return self[key]['id']
You are a Python code generator, capable of creating scripts from specifications.
def operations(): """ Class decorator stores all calls into list. Can be used until .invalidate() is called. :return: decorated class """ def decorator(func): @wraps(func) def wrapped_func(*args, **kwargs): self = args[0] assert self.__can_use, "User oper...
Implement a Python 3 function for classing decorator stores all calls into list.
As a Python code composer, you craft elegant and concise scripts.
def process_actions(action_ids=None): """ Process actions in the publishing schedule. Returns the number of actions processed. """ actions_taken = 0 action_list = PublishAction.objects.prefetch_related( 'content_object', ).filter( scheduled_time__lte=timezone.now(), ) ...
How would you code a function in Python 3 to process the actions in the publishing schedule.
As a Python code composer, you craft elegant and concise scripts.
def celery_enabled(): """ Return a boolean if Celery tasks are enabled for this app. If the ``GLITTER_PUBLISHER_CELERY`` setting is ``True`` or ``False`` - then that value will be used. However if the setting isn't defined, then this will be enabled automatically if Celery is installed. """ ...
Write a Python 3 script to return a boolean if Celery tasks are enabled for this app.
As a Python code translator, you convert algorithms and pseudocode into Python.
Function checkAndCreate Check if an object exists and create it if not
How would you explain what the following Python 3 function does def checkAndCreate(self, key, payload): if key not in self: if 'templates' in payload: templates = payload.pop('templates') self[key] = payload self.reload() return self[key]['id']
As a Python code analyst, you investigate and solve complex coding mysteries
Collect new style ( 44. 1+) return values to old - style kv - list
Explain what the following Python 3 code does def __collect_interfaces_return(interfaces): acc = [] for (interfaceName, interfaceData) in interfaces.items(): signalValues = interfaceData.get("signals", {}) for (signalName, signalValue) in signalValues.items(): pin...
As a python code expert, you are capable of creating scripts from specifications.
def return_values(self): """ Guess what api we are using and return as public api does. Private has {'id':'key', 'value':'keyvalue'} format, public has {'key':'keyvalue'} """ j = self.json() #TODO: FIXME: get rid of old API when its support will be removed public_api_val...
Can you create a Python 3 function that guesses what api we are using and return as private api does.
You are a Python code architect, reviewing and designing scalable and efficient code
Returns an ActivityLog object for this instance.
How would you explain what the following Python 3 function does def get_activitylog(self, after=None, severity=None, start=None, end=None): if after: log_raw = self._router.get_instance_activitylog(org_id=self.organizationId, instance_id=se...
You are a Python code analyst, evaluating scripts for potential improvements.
Returns the JSON representation of the current instance.
How would you explain what the following Python 3 function does def json(self): if self.fresh(): return self.__cached_json # noinspection PyAttributeOutsideInit self.__last_read_time = time.time() self.__cached_json = self._router.get_instance(org_id=self.organizationId, ins...
As a python code expert, you are capable of creating scripts from specifications.
Returns the most recent update time for the current workflow.
Given the following Python 3 function, write the documentation def get_most_recent_update_time(self): def parse_time(t): if t: return time.gmtime(t/1000) return None try: max_wf_started_at = max([i.get('startedAt') for i in self.workflowHistory]) ...
You are a Python code analyst, evaluating scripts for potential improvements.
Determines if the instance was updated since last time.
Can you generate the documentation for the following Python 3 function def _is_projection_updated_instance(self): last = self._last_workflow_started_time if not self._router.public_api_in_use: most_recent = self.get_most_recent_update_time() else: most_recent = None ...
As a Python code translator, you convert algorithms and pseudocode into Python.
Find regexp in activitylog find record as if type is in description.
Here you have a function in Python 3, explain what it does def find(self, item, description='', event_type=''): # TODO: should be refactored, dumb logic if ': ' in item: splited = item.split(': ', 1) if splited[0] in self.TYPES: description = item.split(': ')[1] ...
As a Python code composer, you craft elegant and concise scripts.
This function is a small stub to create an instance of Checker for the passed infile and run all test functions through linting.
Here you have a function in Python 3, explain what it does def do_command_line(infile: typing.IO[str]) -> int: lines = infile.readlines() tree = ast.parse(''.join(lines)) checker = Checker(tree, lines, infile.name) checker.load() errors = [] # type: typing.List[AAAError] for func in checker.all...
As a Python code composer, you craft elegant and concise scripts.
def find_spec(self, fullname, path, target=None): '''finds the appropriate properties (spec) of a module, and sets its loader.''' if not path: path = [os.getcwd()] if "." in fullname: name = fullname.split(".")[-1] else: name = fullname ...
Write a Python 3 script for finding the appropriate properties ( spec ) of a module and sets its loader.
You are a Python code generator, capable of creating scripts from specifications.
def exec_module(self, module): '''import the source code, transforma it before executing it so that it is known to Python.''' global MAIN_MODULE_NAME if module.__name__ == MAIN_MODULE_NAME: module.__name__ = "__main__" MAIN_MODULE_NAME = None with open...
Write a Python 3 script for importing the source code transforma it before executing it so that that it is known to Python.
You are a Python code analyst, evaluating scripts for potential improvements.
def _izip(*iterables): """ Iterate through multiple lists or arrays of equal size """ # This izip routine is from itertools # izip('ABCD', 'xy') --> Ax By iterators = map(iter, iterables) while iterators: yield tuple(map(next, iterators))
Write a Python 3 function for iterating through multiple lists or arrays of equal size.
You are a Python code generator, capable of creating scripts from specifications.
def _checkinput(zi, Mi, z=False, verbose=None): """ Check and convert any input scalar or array to numpy array """ # How many halo redshifts provided? zi = np.array(zi, ndmin=1, dtype=float) # How many halo masses provided? Mi = np.array(Mi, ndmin=1, dtype=float) # Check the input sizes for zi...
Can you write a function in Python 3 where it checks and convert any input scalar or array to numpy array
As a Python code analyst, you investigate and solve complex coding mysteries
Get a list of cosmological parameters for a given cosmology.
Can you generate the documentation for the following Python 3 function def getcosmo(cosmology): defaultcosmologies = {'dragons': cg.DRAGONS(), 'wmap1': cg.WMAP1_Mill(), 'wmap3': cg.WMAP3_ML(), 'wmap5': cg.WMAP5_mean(), 'wmap7': cg.WMAP7_ML(), 'wmap9': cg.WMAP9_ML...
As a Python code analyst, you investigate and solve complex coding mysteries
def _getcosmoheader(cosmo): """ Output the cosmology to a string for writing to file """ cosmoheader = ("# Cosmology (flat) Om:{0:.3f}, Ol:{1:.3f}, h:{2:.2f}, " "sigma8:{3:.3f}, ns:{4:.2f}".format( cosmo['omega_M_0'], cosmo['omega_lambda_0'], cosmo['h'], ...
Can you implement a function in Python 3 that outputs the cosmology to a string for writing to file
As a python code expert, you are capable of creating scripts from specifications.
Return NFW conc from Duffy 08 Table 1 for halo mass and redshift
Can you generate the documentation for the following Python 3 function def cduffy(z, M, vir='200crit', relaxed=True): if(vir == '200crit'): if relaxed: params = [6.71, -0.091, -0.44] else: params = [5.71, -0.084, -0.47] elif(vir == 'tophat'): if relaxed: ...
As a python code expert, you are capable of creating scripts from specifications.
Returns the perturbed A relation between rho_2 and rho_crit for the given cosmology
Can you generate the documentation for the following Python 3 function def _delta_sigma(**cosmo): M8_cosmo = cp.perturbation.radius_to_mass(8, **cosmo) perturbed_A = (0.796/cosmo['sigma_8']) * \ (M8_cosmo/2.5e14)**((cosmo['n']-0.963)/6) return(perturbed_A)
As a Python code composer, you craft elegant and concise scripts.
Returns the normalisation constant between Rho - 2 and Rho_mean for a given cosmology.
Make a summary of the following Python 3 code def getAscaling(cosmology, newcosmo=None): # Values from Correa 15c defaultcosmologies = {'dragons': 887, 'wmap1': 853, 'wmap3': 850, 'wmap5': 887, 'wmap7': 887, 'wmap9': 950, 'wmap1_lss': 853, 'wmap3_mean': 850, ...
You are a Python code architect, reviewing and designing scalable and efficient code
Returns the integral of the linear growth factor from z = 200 to z = z
How would you explain what the following Python 3 function does def _int_growth(z, **cosmo): zmax = 200 if hasattr(z, "__len__"): for zval in z: assert(zval < zmax) else: assert(z < zmax) y, yerr = scipy.integrate.quad( lambda z: (1 + z)/(cosmo['omega_M_0']*(1 + z)...
As a Python code composer, you craft elegant and concise scripts.
Returns the derivative of the linear growth factor at a given cosmology z
Explain what the following Python 3 code does def _deriv_growth(z, **cosmo): inv_h = (cosmo['omega_M_0']*(1 + z)**3 + cosmo['omega_lambda_0'])**(-0.5) fz = (1 + z) * inv_h**3 deriv_g = growthfactor(z, norm=True, **cosmo)*(inv_h**2) *\ 1.5 * cosmo['omega_M_0'] * (1 + z)**2 -\ fz * growthfac...
As a Python code analyst, you investigate and solve complex coding mysteries
def growthfactor(z, norm=True, **cosmo): """ Returns linear growth factor at a given redshift, normalised to z=0 by default, for a given cosmology Parameters ---------- z : float or numpy array The redshift at which the growth factor should be calculated norm : boolean, optional ...
Implement a Python 3 function for returning linear growth factor at a given redshift
As a Python code translator, you convert algorithms and pseudocode into Python.
Minimisation of concentration c for a given z
How would you explain what the following Python 3 function does def _minimize_c(c, z=0, a_tilde=1, b_tilde=-1, Ascaling=900, omega_M_0=0.25, omega_lambda_0=0.75): """ Trial function to solve 2 eqns (17 and 18) from Correa et al. (2015c) for 1 unknown, i.e. concentration, returned by a minimi...
As a Python code analyst, you investigate and solve complex coding mysteries
Rearrange eqn 18 from Correa et al 2015c to return formation redshift at a given redshift
How would you explain what the following Python 3 function does def formationz(c, z, Ascaling=900, omega_M_0=0.25, omega_lambda_0=0.75): Y1 = np.log(2) - 0.5 Yc = np.log(1+c) - c/(1+c) rho_2 = 200*(c**3)*Y1/Yc zf = (((1+z)**3 + omega_lambda_0/omega_M_0) * (rho_2/Ascaling) - omega_lambda_0/ome...
You are a Python code architect, reviewing and designing scalable and efficient code
def calc_ab(zi, Mi, **cosmo): """ Calculate growth rate indices a_tilde and b_tilde Parameters ---------- zi : float Redshift Mi : float Halo mass at redshift 'zi' cosmo : dict Dictionary of cosmological parameters, similar in format to: {'N_nu': 0,'Y_He': 0.24, ...
Can you write a function in Python 3 where it calculates growth rate indices a_tilde and b_tilde for a given redshift Mi and cosmological parameters.
As a python code expert, you are capable of creating scripts from specifications.
Calculates the accretion rate and mass history of a specific redshift z with mass Mi at a lower redshift zi.
Can you generate the documentation for the following Python 3 function def acc_rate(z, zi, Mi, **cosmo): # Find parameters a_tilde and b_tilde for initial redshift # use Eqn 9 and 10 of Correa et al. (2015c) a_tilde, b_tilde = calc_ab(zi, Mi, **cosmo) # Halo mass at z, in Msol # use Eqn 8 in Correa...
You are a Python code analyst, evaluating scripts for potential improvements.
def MAH(z, zi, Mi, **cosmo): """ Calculate mass accretion history by looping function acc_rate over redshift steps 'z' for halo of mass 'Mi' at redshift 'zi' Parameters ---------- z : float / numpy array Redshift to output MAH over. Note zi<z always zi : float Redshift M...
How would you code a function in Python 3 to calculate the mass accretion history for a given redshift and mass at a given redshift.
As a Python code analyst, you investigate and solve complex coding mysteries
def COM(z, M, **cosmo): """ Calculate concentration for halo of mass 'M' at redshift 'z' Parameters ---------- z : float / numpy array Redshift to find concentration of halo M : float / numpy array Halo mass at redshift 'z'. Must be same size as 'z' cosmo : dict Dictiona...
Implement a function in Python 3 to calculate the concentration of the given redshift and mass combination at redshift z.
You are a Python code architect, reviewing and designing scalable and efficient code