Search is not available for this dataset
text
stringlengths
75
104k
def has_import( state, name, same_as=False, not_imported_msg="Did you import `{{pkg}}`?", incorrect_as_msg="Did you import `{{pkg}}` as `{{alias}}`?", ): """Checks whether student imported a package or function correctly. Python features many ways to import packages. All of these differ...
def has_output(state, text, pattern=True, no_output_msg=None): """Search student output for a pattern. Among the student and solution process, the student submission and solution code as a string, the ``Ex()`` state also contains the output that a student generated with his or her submission. With ``h...
def has_printout( state, index, not_printed_msg=None, pre_code=None, name=None, copy=False ): """Check if the right printouts happened. ``has_printout()`` will look for the printout in the solution code that you specified with ``index`` (0 in this case), rerun the ``print()`` call in the solution proce...
def has_no_error( state, incorrect_msg="Have a look at the console: your code contains an error. Fix it and try again!", ): """Check whether the submission did not generate a runtime error. If all SCTs for an exercise pass, before marking the submission as correct pythonwhat will automatically check wh...
def has_chosen(state, correct, msgs): """Test multiple choice exercise. Test for a MultipleChoiceExercise. The correct answer (as an integer) and feedback messages are passed to this function. Args: correct (int): the index of the correct answer (should be an instruction). Starts at 1. ...
def check_function( state, name, index=0, missing_msg=None, params_not_matched_msg=None, expand_msg=None, signature=True, ): """Check whether a particular function is called. ``check_function()`` is typically followed by: - ``check_args()`` to check whether the arguments we...
def process_task(f): """Decorator to (optionally) run function in a process.""" sig = inspect.signature(f) @wraps(f) def wrapper(*args, **kwargs): # get bound arguments for call ba = sig.bind_partial(*args, **kwargs) # when process is specified, remove from args and use to execu...
def getResultFromProcess(res, tempname, process): """Get a value from process, return tuple of value, res if succesful""" if not isinstance(res, (UndefinedValue, Exception)): value = getRepresentation(tempname, process) return value, res else: return res, str(res)
def assign_from_ast(node, expr): """ Creates code to assign name (or tuple of names) node from expr This is useful for recreating destructuring assignment behavior, like a, *b = [1,2,3]. """ if isinstance(expr, str): expr = ast.Name(id=expr, ctx=ast.Load()) mod = ast.Module([ast.Ass...
def override(state, solution): """Override the solution code with something arbitrary. There might be cases in which you want to temporarily override the solution code so you can allow for alternative ways of solving an exercise. When you use ``override()`` in an SCT chain, the remainder of that SCT ch...
def set_context(state, *args, **kwargs): """Update context values for student and solution environments. When ``has_equal_x()`` is used after this, the context values (in ``for`` loops and function definitions, for example) will have the values specified through his function. It is the function equival...
def set_env(state, **kwargs): """Update/set environemnt variables for student and solution environments. When ``has_equal_x()`` is used after this, the variables specified through this function will be available in the student and solution process. Note that you will not see these variables in the stud...
def check_object( state, index, missing_msg=None, expand_msg=None, typestr="variable" ): """Check object existence (and equality) Check whether an object is defined in the student's process, and zoom in on its value in both student and solution process to inspect quality (with has_equal_value(). I...
def is_instance(state, inst, not_instance_msg=None): """Check whether an object is an instance of a certain class. ``is_instance()`` can currently only be used when chained from ``check_object()``, the function that is used to 'zoom in' on the object of interest. Args: inst (class): The class ...
def check_df( state, index, missing_msg=None, not_instance_msg=None, expand_msg=None ): """Check whether a DataFrame was defined and it is the right type ``check_df()`` is a combo of ``check_object()`` and ``is_instance()`` that checks whether the specified object exists and whether the specified o...
def check_keys(state, key, missing_msg=None, expand_msg=None): """Check whether an object (dict, DataFrame, etc) has a key. ``check_keys()`` can currently only be used when chained from ``check_object()``, the function that is used to 'zoom in' on the object of interest. Args: key (str): Name ...
def defined_items(self): """Return copy of instance, omitting entries that are EMPTY""" return self.__class__( [(k, v) for k, v in self.items() if v is not self.EMPTY], is_empty=False )
def to_child(self, append_message="", node_name="", **kwargs): """Dive into nested tree. Set the current state as a state with a subtree of this syntax tree as student tree and solution tree. This is necessary when testing if statements or for loops for example. """ base...
def _getx(self, Parser, ext_attr, tree): """getter for Parser outputs""" # return cached output if possible cache_key = Parser.__name__ + str(hash(tree)) if self._parser_cache.get(cache_key): p = self._parser_cache[cache_key] else: # otherwise, run parser ...
def has_context_loop(state, incorrect_msg, exact_names): """When dispatched on loops, has_context the target vars are the attribute _target_vars. Note: This is to allow people to call has_context on a node (e.g. for_loop) rather than one of its attributes (e.g. body). Purely for convenience. """ ...
def has_context_with(state, incorrect_msg, exact_names): """When dispatched on with statements, has_context loops over each context manager. Note: This is to allow people to call has_context on the with statement, rather than having to manually loop over each context manager. e.g. Ex().che...
def check_part(state, name, part_msg, missing_msg=None, expand_msg=None): """Return child state with name part as its ast tree""" if missing_msg is None: missing_msg = "Are you sure you defined the {{part}}? " if expand_msg is None: expand_msg = "Did you correctly specify the {{part}}? " ...
def check_part_index(state, name, index, part_msg, missing_msg=None, expand_msg=None): """Return child state with indexed name part as its ast tree. ``index`` can be: - an integer, in which case the student/solution_parts are indexed by position. - a string, in which case the student/solution_parts ar...
def check_args(state, name, missing_msg=None): """Check whether a function argument is specified. This function can follow ``check_function()`` in an SCT chain and verifies whether an argument is specified. If you want to go on and check whether the argument was correctly specified, you can can continue ch...
def check_call(state, callstr, argstr=None, expand_msg=None): """When checking a function definition of lambda function, prepare has_equal_x for checking the call of a user-defined function. Args: callstr (str): call string that specifies how the function should be called, e.g. `f(1, a = 2)`. ...
def detect_openmp(): """Does this compiler support OpenMP parallelization?""" compiler = new_compiler() print("Checking for OpenMP support... ") hasopenmp = hasfunction(compiler, 'omp_get_num_threads()') needs_gomp = hasopenmp if not hasopenmp: compiler.add_library('gomp') hasopenmp = hasfunction(compiler, 'om...
def make_plots(): import matplotlib.pyplot as plt """zs = np.linspace(0., 1., 1000) rp = 0.1 wrapped = wrapper(_quadratic_ld._quadratic_ld, zs, rp, 0.1, 0.3, 1) t = timeit.timeit(wrapped,number=10000) print("time:", t)""" """zs = np.linspace(0., 1., 1000) rp = 0.1 u = [0., 0.7, 0.0, -0.3] f = _nonlinear_ld._n...
def light_curve(self, params): """ Calculate a model light curve. :param params: Transit parameters :type params: A `TransitParams` instance :return: Relative flux :rtype: ndarray :Example: >>> flux = m.light_curve(params) """ #recalculates rsky and fac if necessary if params.t0 != self.t0 or...
def get_t_periastron(self, params): """ Return the time of periastron passage (calculated using `params.t0`). """ phase = self._get_phase(params, "primary") return params.t0 - params.per*phase
def get_t_secondary(self, params): """ Return the time of secondary eclipse center (calculated using `params.t0`). """ phase = self._get_phase(params, "primary") phase2 = self._get_phase(params, "secondary") return params.t0 + params.per*(phase2-phase)
def get_t_conjunction(self, params): """ Return the time of primary transit center (calculated using `params.t_secondary`). """ phase = self._get_phase(params, "primary") phase2 = self._get_phase(params, "secondary") return params.t_secondary + params.per*(phase-phase2)
def get_true_anomaly(self): """ Return the true anomaly at each time """ self.f = _rsky._getf(self.t_supersample, self.t0, self.per, self.a, self.inc*pi/180., self.ecc, self.w*pi/180., self.transittype, self.nthreads) return self.f
def detect(): """Does this compiler support OpenMP parallelization?""" compiler = new_compiler() hasopenmp = hasfunction(compiler, 'omp_get_num_threads()') needs_gomp = hasopenmp if not hasopenmp: compiler.add_library('gomp') hasopenmp = hasfunction(compiler, 'omp_get_num_threads()') needs_gomp = hasopenmp re...
def validate_ldap(self): logging.debug('Validating LDAPLoginForm against LDAP') 'Validate the username/password data against ldap directory' ldap_mgr = current_app.ldap3_login_manager username = self.username.data password = self.password.data result = ldap_mgr.authentic...
def validate(self, *args, **kwargs): """ Validates the form by calling `validate` on each field, passing any extra `Form.validate_<fieldname>` validators to the field validator. also calls `validate_ldap` """ valid = FlaskForm.validate(self, *args, **kwargs) if ...
def init_app(self, app): ''' Configures this extension with the given app. This registers an ``teardown_appcontext`` call, and attaches this ``LDAP3LoginManager`` to it as ``app.ldap3_login_manager``. Args: app (flask.Flask): The flask app to initialise with ...
def init_config(self, config): ''' Configures this extension with a given configuration dictionary. This allows use of this extension without a flask app. Args: config (dict): A dictionary with configuration keys ''' self.config.update(config) self....
def add_server(self, hostname, port, use_ssl, tls_ctx=None): """ Add an additional server to the server pool and return the freshly created server. Args: hostname (str): Hostname of the server port (int): Port of the server use_ssl (bool): True if SSL...
def _contextualise_connection(self, connection): """ Add a connection to the appcontext so it can be freed/unbound at a later time if an exception occured and it was not freed. Args: connection (ldap3.Connection): Connection to add to the appcontext """ ctx...
def _decontextualise_connection(self, connection): """ Remove a connection from the appcontext. Args: connection (ldap3.Connection): connection to remove from the appcontext """ ctx = stack.top if ctx is not None and connection in ctx.ldap3_...
def teardown(self, exception): """ Cleanup after a request. Close any open connections. """ ctx = stack.top if ctx is not None: if hasattr(ctx, 'ldap3_manager_connections'): for connection in ctx.ldap3_manager_connections: self.des...
def authenticate(self, username, password): """ An abstracted authentication method. Decides whether to perform a direct bind or a search bind based upon the login attribute configured in the config. Args: username (str): Username of the user to bind pass...
def authenticate_direct_credentials(self, username, password): """ Performs a direct bind, however using direct credentials. Can be used if interfacing with an Active Directory domain controller which authenticates using username@domain.com directly. Performing this kind of look...
def authenticate_direct_bind(self, username, password): """ Performs a direct bind. We can do this since the RDN is the same as the login attribute. Hence we just string together a dn to find this user with. Args: username (str): Username of the user to bind (the fie...
def authenticate_search_bind(self, username, password): """ Performs a search bind to authenticate a user. This is required when a the login attribute is not the same as the RDN, since we cannot string together their DN on the fly, instead we have to find it in the LDAP, then att...
def get_user_groups(self, dn, group_search_dn=None, _connection=None): """ Gets a list of groups a user at dn is a member of Args: dn (str): The dn of the user to find memberships for. _connection (ldap3.Connection): A connection object to use when search...
def get_user_info(self, dn, _connection=None): """ Gets info about a user specified at dn. Args: dn (str): The dn of the user to find _connection (ldap3.Connection): A connection object to use when searching. If not given, a temporary connection will be ...
def get_user_info_for_username(self, username, _connection=None): """ Gets info about a user at a specified username by searching the Users DN. Username attribute is the same as specified as LDAP_USER_LOGIN_ATTR. Args: username (str): Username of the user to search ...
def get_object(self, dn, filter, attributes, _connection=None): """ Gets an object at the specified dn and returns it. Args: dn (str): The dn of the object to find. filter (str): The LDAP syntax search filter. attributes (list): A list of LDAP attributes to g...
def connection(self): """ Convenience property for externally accessing an authenticated connection to the server. This connection is automatically handled by the appcontext, so you do not have to perform an unbind. Returns: ldap3.Connection: A bound ldap3.Connection...
def make_connection(self, bind_user=None, bind_password=None, **kwargs): """ Make a connection to the LDAP Directory. Args: bind_user (str): User to bind with. If `None`, AUTH_ANONYMOUS is used, otherwise authentication specified with config['LDAP_BIN...
def _make_connection(self, bind_user=None, bind_password=None, contextualise=True, **kwargs): """ Make a connection. Args: bind_user (str): User to bind with. If `None`, AUTH_ANONYMOUS is used, otherwise authentication specified with ...
def destroy_connection(self, connection): """ Destroys a connection. Removes the connection from the appcontext, and unbinds it. Args: connection (ldap3.Connection): The connnection to destroy """ log.debug("Destroying connection at <{0}>".format(hex(id(con...
def compiled_sub_dn(self, prepend): """ Returns: str: A DN with the DN Base appended to the end. Args: prepend (str): The dn to prepend to the base. """ prepend = prepend.strip() if prepend == '': return self.config.get('LDAP_BASE_DN')...
def search(self, query=None, args=None): '''query a s3 endpoint for an image based on a string EXAMPLE QUERIES: [empty] list all container collections vsoch/dinosaur look for containers with name vsoch/dinosaur ''' if query is not None: return self._container_se...
def search_all(self, quiet=False): '''a "show all" search that doesn't require a query Parameters ========== quiet: if quiet is True, we only are using the function to return rows of results. ''' results = [] for obj in self.bucket.objects.all(): subsr...
def container_search(self, query, across_collections=False): '''search for a specific container. If across collections is False, the query is parsed as a full container name and a specific container is returned. If across_collections is True, the container is searched for across collections. If across c...
def search(self, query=None, args=None): '''query a Singularity registry for a list of images. If query is None, collections are listed. EXAMPLE QUERIES: [empty] list all collections in registry vsoch do a general search for the expression "vsoch" vsoch/ ...
def collection_search(self, query): '''collection search will list all containers for a specific collection. We assume query is the name of a collection''' query = query.lower().strip('/') url = '%s/collection/%s' %(self.base, query) result = self._get(url) if len(result) == 0: bot.inf...
def label_search(self, key=None, value=None): '''search across labels''' if key is not None: key = key.lower() if value is not None: value = value.lower() show_details = True if key is None and value is None: url = '%s/labels/search' % (self.base) show_details = Fa...
def container_search(self, query, across_collections=False): '''search for a specific container. If across collections is False, the query is parsed as a full container name and a specific container is returned. If across_collections is True, the container is searched for across collections. If across c...
def search(self, query=None, args=None): '''query a GitLab artifacts folder for a list of images. If query is None, collections are listed. ''' if query is None: bot.exit('You must include a collection query, <collection>/<repo>') # or default to listing (searching) all things. retur...
def search_all(self, collection, job_id=None): '''a "show all" search that doesn't require a query the user is shown URLs to ''' results = [['job_id', 'browser']] url = "%s/projects/%s/jobs" %(self.api_base, quote_plus(collection.strip('/'))) response =...
def _client_tagged(self, tags): '''ensure that the client name is included in a list of tags. This is important for matching builders to the correct client. We exit on fail. Parameters ========== tags: a list of tags to look for client name in ...
def speak(self): ''' a function for the client to announce him or herself, depending on the level specified. If you want your client to have additional announced things here, then implement the class `_speak` for your client. ''' if self.quiet is Fals...
def announce(self, command=None): '''the client will announce itself given that a command is not in a particular predefined list. ''' if command is not None: if command not in ['get'] and self.quiet is False: self.speak()
def _update_secrets(self): '''The user is required to have an application secrets file in his or her environment. The client exists with error if the variable isn't found. ''' env = 'SREGISTRY_GOOGLE_DRIVE_CREDENTIALS' self._secrets = self._get_and_update_setting(e...
def _get_service(self, version='v3'): '''get service client for the google drive API :param version: version to use (default is v3) ''' invalid = True # The user hasn't disabled cache of credentials if self._credential_cache is not None: storage = Storage(sel...
def add(self, image_path=None, image_uri=None, image_name=None, url=None, metadata=None, save=True, copy=False): '''dummy add simple returns an object that mimics a database entry, so the calling function (in push or pull) ...
def search(self, query=None, **kwargs): '''query a Singularity registry for a list of images. If query is None, collections are listed. EXAMPLE QUERIES: [empty] list all collections in singularity hub vsoch do a general search for collection "vsoch" vsoch/dinosaur ...
def list_all(self, **kwargs): '''a "show all" search that doesn't require a query''' quiet=False if "quiet" in kwargs: quiet = kwargs['quiet'] bot.spinner.start() url = '%s/collections/' %self.base results = self._paginate_get(url) bot.spinner.stop() if len(results) == 0: ...
def search_collection(self, query): '''collection search will list all containers for a specific collection. We assume query is the name of a collection''' query = query.lower().strip('/') q = parse_image_name(remove_uri(query), defaults=False) # Workaround for now - the Singularity Hub search...
def pull(self, images, file_name=None, save=True, **kwargs): '''pull an image from gitlab. The image is found based on the uri that should correspond to a gitlab repository, and then the branch, job name, artifact folder, and tag of the container. The minimum that we need are the job id, colle...
def run(self, func, tasks, func2=None): '''run will send a list of tasks, a tuple with arguments, through a function. the arguments should be ordered correctly. :param func: the function to run with multiprocessing.pool :param tasks: a list of tasks, each a tuple ...
def get_cache(subfolder=None, quiet=False): '''get_cache will return the user's cache for singularity. :param subfolder: a subfolder in the cache base to retrieve, specifically ''' DISABLE_CACHE = convert2boolean(getenv("SINGULARITY_DISABLE_CACHE", default=Fal...
def push(self, path, name, tag=None): '''push an image to Google Cloud Storage, meaning uploading it path: should correspond to an absolte image path (or derive it) name: should be the complete uri that the user has requested to push. tag: should correspond with an image tag. This is provided to mi...
def upload(self, source, destination, bucket, chunk_size = 2 * 1024 * 1024, metadata=None, keep_private=True): '''upload a file from a source to a destination. The client is expected to have a bucket (self._bucket) that ...
def update_headers(self,fields=None): '''update headers with a token & other fields ''' do_reset = True if hasattr(self, 'headers'): if self.headers is not None: do_reset = False if do_reset is True: self._reset_headers() if fields is not None: for key,value...
def download_task(url, headers, destination, download_type='layer'): '''download an image layer (.tar.gz) to a specified download folder. This task is done by using local versions of the same download functions that are used for the client. core stream/download functions of the parent client. ...
def post(url,data=None,return_json=True): '''post will use requests to get a particular url ''' bot.debug("POST %s" %url) return call(url, headers=headers, func=requests.post, data=data, return_json=return_json)
def get(url,headers=None,token=None,data=None,return_json=True): '''get will use requests to get a particular url ''' bot.debug("GET %s" %url) return call(url, headers=headers, func=requests.get, data=data, return_json=return_json)
def call(url, func, data=None, headers=None, return_json=True, stream=False, retry=True): '''call will issue the call, and issue a refresh token given a 401 response, and if the client has a _update_token function Parameters ========== func: the function (...
def require_secrets(self, params=None): '''require secrets ensures that the client has the secrets file, and specifically has one or more parameters defined. If params is None, only a check is done for the file. Parameters ========== params: a list of keys to lookup in the client...
def auth_flow(self, url): '''auth flow is a function to present the user with a url to retrieve some token/code, and then copy paste it back in the terminal. Parameters ========== url should be a url that is generated for the user to go to and accept getting a credential in t...
def download(url, file_name, headers=None, show_progress=True): '''stream to a temporary file, rename on successful completion Parameters ========== file_name: the file name to stream to url: the url to stream from headers: additional headers to add ''' fd, tmp_file...
def stream(url, headers, stream_to=None, retry=True): '''stream is a get that will stream to file_name. Since this is a worker task, it differs from the client provided version in that it requires headers. ''' bot.debug("GET %s" % url) if DISABLE_SSL_CHECK is True: bot.warning('Ve...
def update_token(headers): '''update_token uses HTTP basic authentication to attempt to authenticate given a 401 response. We take as input previous headers, and update them. Parameters ========== response: the http request response to parse for the challenge. ''' try: fro...
def get_or_create_folder(self, folder): '''create a folder at the drive root. If the folder already exists, it is simply returned. folder = self._get_or_create_folder(self._base) $ folder {'id': '1pXR5S8wufELh9Q-jDkhCoYu-BL1NqN9y'} ''' q = "mimeType='application/v...
def create_folder(self, folder): '''create a folder with a particular name. Be careful, if the folder already exists you can still create one (a different one) with the equivalent name! ''' folder_metadata = { 'name': os.path.basename(folder), 'mimeType': 'application/...
def _read_response(self,response, field="detail"): '''attempt to read the detail provided by the response. If none, default to using the reason''' try: message = json.loads(response._content.decode('utf-8'))[field] except: message = response.reason retur...
def get_bucket_name(self): '''get or return the s3 bucket name. If not yet defined via an environment variable or setting, we create a name with the pattern. sregistry-<robotnamer>-<1234> You can use the following environment variables to determine interacti...
def get_bucket(self): '''given a bucket name and a client that is initialized, get or create the bucket. ''' for attr in ['bucket_name', 's3']: if not hasattr(self, attr): bot.exit('client is missing attribute %s' %(attr)) # See if the bucket is al...
def get_resource(self): '''use the user provided endpoint and keys (from environment) to connect to the resource. We can share the aws environment variables: AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY https://docs.aws.amazon.com/cli/latest/userguide/cli-conf...
def _update_secrets(self, base=None): '''update secrets will update/get the base for the server, along with the bucket name, defaulting to sregistry. ''' # We are required to have a base, either from environment or terminal self.base = self._get_and_update_setting('SREGISTRY_S...
def _add_https(self, q): '''for push, pull, and other api interactions, the user can optionally define a custom registry. If the registry name doesn't include http or https, add it. Parameters ========== q: the parsed image query (names), including the or...
def _update_secrets(self): '''update secrets will take a secrets credential file either located at .sregistry or the environment variable SREGISTRY_CLIENT_SECRETS and update the current client secrets as well as the associated API base. ''' self.secrets = read_client_sec...
def _init_clients(self): '''init_ cliends will obtain the tranfer and access tokens, and then use them to create a transfer client. ''' self._client = globus_sdk.NativeAppAuthClient(self._client_id) self._load_secrets()
def _load_secrets(self): '''load the secrets credentials file with the Globus OAuthTokenResponse ''' # Second priority: load from cache self.auth = self._get_and_update_setting('GLOBUS_AUTH_RESPONSE') self.transfer = self._get_and_update_setting('GLOBUS_TRANSFER_RESPONSE...
def _tokens_need_update(self): '''return boolean True or False if the client tokens (self._auth and self._transfer) need updating. ''' # Assumes that auth and transfer have same refresh time needs_update = True if self.auth is not None: if self.auth['expi...
def _update_tokens(self): '''Present the client with authentication flow to get tokens from code. This simply updates the client _response to be used to get tokens for auth and transfer (both use access_token as index). We call this not on client initialization, but when the cli...