docstring
stringlengths
52
499
function
stringlengths
67
35.2k
__index_level_0__
int64
52.6k
1.16M
Build function with set of words from a corpus. Args: corpus (collection): collection of words to use
def __init__(self, corpus): self.words = corpus self.floor = log10(0.01 / len(self.words))
972,292
Score based on number of words not in the corpus. Example: >>> fitness = Corpus(["example"]) >>> fitness("example") 0 >>> fitness("different") -2.0 Args: text (str): The text to score Returns: Corpus score for text
def __call__(self, text): text = remove(text, string.punctuation) words = text.split() invalid_words = list(filter(lambda word: word and word.lower() not in self.words, words)) return len(invalid_words) * self.floor
972,293
Rank all key periods for ``ciphertext`` up to and including ``max_key_period`` Example: >>> key_periods(ciphertext, 30) [2, 4, 8, 3, ...] Args: ciphertext (str): The text to analyze max_key_period (int): The maximum period the key could be Returns: Sorted list of keys Raises: ValueError: If max_key_period is less than or equal to 0
def key_periods(ciphertext, max_key_period): if max_key_period <= 0: raise ValueError("max_key_period must be a positive integer") key_scores = [] for period in range(1, min(max_key_period, len(ciphertext)) + 1): score = abs(ENGLISH_IC - index_of_coincidence(*split_columns(ciphertext, period))) key_scores.append((period, score)) return [p[0] for p in sorted(key_scores, key=lambda x: x[1])]
972,312
Decrypt Vigenere encrypted ``ciphertext`` using ``key``. Example: >>> decrypt("KEY", "RIJVS") HELLO Args: key (iterable): The key to use ciphertext (str): The text to decrypt Returns: Decrypted ciphertext
def decrypt(key, ciphertext): index = 0 decrypted = "" for char in ciphertext: if char in string.punctuation + string.whitespace + string.digits: decrypted += char continue # Not part of the decryption # Rotate character by the alphabet position of the letter in the key alphabet = string.ascii_uppercase if key[index].isupper() else string.ascii_lowercase decrypted += ''.join(shift.decrypt(int(alphabet.index(key[index])), char)) index = (index + 1) % len(key) return decrypted
972,314
Decrypt Shift enciphered ``ciphertext`` using ``key``. Examples: >>> ''.join(decrypt(3, "KHOOR")) HELLO >> decrypt(15, [0xcf, 0x9e, 0xaf, 0xe0], shift_bytes) [0xde, 0xad, 0xbe, 0xef] Args: key (int): The shift to use ciphertext (iterable): The symbols to decrypt shift_function (function (shift, symbol)): Shift function to apply to symbols in the ciphertext Returns: Decrypted ciphertext, list of plaintext symbols
def decrypt(key, ciphertext, shift_function=shift_case_english): return [shift_function(key, symbol) for symbol in ciphertext]
972,370
Returns an empty ``Document``. Arguments: - ``base_uri``: optional URL used as the basis when expanding relative URLs in the document. - ``draft``: a ``Draft`` instance that selects the version of the spec to which the document should conform. Defaults to ``drafts.AUTO``.
def empty(cls, base_uri=None, draft=AUTO): return cls.from_object({}, base_uri=base_uri, draft=draft)
972,669
Constructor. Parameters ---------- mediafile : str, optional The path to the mediafile to be loaded (default: None) videorenderfunc : callable (default: None) Callback function that takes care of the actual Rendering of the videoframe.\ The specified renderfunc should be able to accept the following arguments: - frame (numpy.ndarray): the videoframe to be rendered play_audio : bool, optional Whether audio of the clip should be played.
def __init__(self, mediafile=None, videorenderfunc=None, play_audio=True): # Create an internal timer self.clock = Timer() # Load a video file if specified, but allow users to do this later # by initializing all variables to None if not self.load_media(mediafile, play_audio): self.reset() # Set callback function if set self.set_videoframerender_callback(videorenderfunc) # Store instance variables self.play_audio = play_audio
973,130
Export the config and rules for a pipeline. Args: url (str): the host url in the form 'http://host:port/'. pipeline_id (str): the ID of of the exported pipeline. auth (tuple): a tuple of username, and password. verify_ssl (bool): whether to verify ssl certificates Returns: dict: the response json
def export_pipeline(url, pipeline_id, auth, verify_ssl): export_result = requests.get(url + '/' + pipeline_id + '/export', headers=X_REQ_BY, auth=auth, verify=verify_ssl) if export_result.status_code == 404: logging.error('Pipeline not found: ' + pipeline_id) export_result.raise_for_status() return export_result.json()
973,236
Retrieve the current status for a pipeline. Args: url (str): the host url in the form 'http://host:port/'. pipeline_id (str): the ID of of the exported pipeline. auth (tuple): a tuple of username, and password. verify_ssl (bool): whether to verify ssl certificates Returns: dict: the response json
def pipeline_status(url, pipeline_id, auth, verify_ssl): status_result = requests.get(url + '/' + pipeline_id + '/status', headers=X_REQ_BY, auth=auth, verify=verify_ssl) status_result.raise_for_status() logging.debug('Status request: ' + url + '/status') logging.debug(status_result.json()) return status_result.json()
973,237
Retrieve the current status for a preview. Args: url (str): the host url in the form 'http://host:port/'. pipeline_id (str): the ID of of the exported pipeline. previewer_id (str): the previewer id created by starting a preview or validation auth (tuple): a tuple of username, and password. verify_ssl (bool): whether to verify ssl certificates Returns: dict: the response json
def preview_status(url, pipeline_id, previewer_id, auth, verify_ssl): preview_status = requests.get(url + '/' + pipeline_id + '/preview/' + previewer_id + "/status", headers=X_REQ_BY, auth=auth, verify=verify_ssl) preview_status.raise_for_status() logging.debug(preview_status.json()) return preview_status.json()
973,238
Stop a running pipeline. The API waits for the pipeline to be 'STOPPED' before returning. Args: url (str): the host url in the form 'http://host:port/'. pipeline_id (str): the ID of of the exported pipeline. auth (tuple): a tuple of username, and password. verify_ssl (bool): whether to verify ssl certificates Returns: dict: the response json
def stop_pipeline(url, pipeline_id, auth, verify_ssl): stop_result = requests.post(url + '/' + pipeline_id + '/stop', headers=X_REQ_BY, auth=auth, verify=verify_ssl) stop_result.raise_for_status() logging.info("Pipeline stop requested.") poll_pipeline_status(STATUS_STOPPED, url, pipeline_id, auth, verify_ssl) logging.info('Pipeline stopped.') return stop_result.json()
973,240
Validate a pipeline and show issues. Args: url (str): the host url in the form 'http://host:port/'. pipeline_id (str): the ID of of the exported pipeline. auth (tuple): a tuple of username, and password. verify_ssl (bool): whether to verify ssl certificates Returns: dict: the response json
def validate_pipeline(url, pipeline_id, auth, verify_ssl): validate_result = requests.get(url + '/' + pipeline_id + '/validate', headers=X_REQ_BY, auth=auth, verify=verify_ssl) validate_result.raise_for_status() previewer_id = validate_result.json()['previewerId'] poll_validation_status(url, pipeline_id, previewer_id, auth, verify_ssl) preview_result = requests.get(url + '/' + pipeline_id + '/preview/' + validate_result.json()['previewerId'], headers=X_REQ_BY, auth=auth, verify=verify_ssl) logging.debug('result content: {}'.format(preview_result.content)) return preview_result.json()
973,241
Create a new pipeline. Args: url (str): the host url in the form 'http://host:port/'. auth (tuple): a tuple of username, and password. json_payload (dict): the exported json paylod as a dictionary. verify_ssl (bool): whether to verify ssl certificates Returns: dict: the response json
def create_pipeline(url, auth, json_payload, verify_ssl): title = json_payload['pipelineConfig']['title'] description = json_payload['pipelineConfig']['description'] params = {'description':description, 'autoGeneratePipelineId':True} logging.info('No destination pipeline ID provided. Creating a new pipeline: ' + title) put_result = requests.put(url + '/' + title, params=params, headers=X_REQ_BY, auth=auth, verify=verify_ssl) put_result.raise_for_status() create_json = put_result.json() logging.debug(create_json) logging.info('Pipeline creation successful.') return create_json
973,244
Retrieve SDC system information. Args: url (str): the host url. auth (tuple): a tuple of username, and password.
def system_info(url, auth, verify_ssl): sysinfo_response = requests.get(url + '/info', headers=X_REQ_BY, auth=auth, verify=verify_ssl) sysinfo_response.raise_for_status() return sysinfo_response.json()
973,245
Returns a new ``Link`` based on a JSON object or array. Arguments: - ``o``: a dictionary holding the deserializated JSON for the new ``Link``, or a ``list`` of such documents. - ``base_uri``: optional URL used as the basis when expanding relative URLs in the link.
def from_object(cls, o, base_uri): if isinstance(o, list): if len(o) == 1: return cls.from_object(o[0], base_uri) return [cls.from_object(x, base_uri) for x in o] return cls(o, base_uri)
973,302
Get the top story objects list params : limit = (default | 5) number of story objects needed json = (default | False) The method uses asynchronous grequest form gevent
def top_stories(self, limit=5, first=None, last=None, json=False): story_ids = requests.get(TOP_STORIES_URL).json() story_urls = [] for story_id in story_ids: url = API_BASE + "item/" + str(story_id) + '.json' story_urls.append(url) if first and last: story_urls = story_urls[first:last] if limit != 5: story_urls[:limit] # default not given else: story_urls = story_urls[:limit] # try: # response_queue = fetch_parallel(story_urls) # if json: # while not response_queue.empty(): # yield response_queue.get() # else: # while not response_queue.empty(): # yield story_parser(response_queue.get()) # except AttributeError: # Exception("Too many requests worker!!") # using gevent response_list = fetch_event(story_urls) if json: yield response_list else: for response in response_list: yield story_parser(response)
974,379
Get the top story objects list params : comment_id = the id of the story object limit = (default = 5) number of story objects needed set limit it to None to get all the comments The method uses asynchronous grequest form gevent
def get_comments(self, comment_id=2921983, limit=5, json=False): try: comment_ids = requests.get( API_BASE + "item/" + str(comment_id) + '.json').json()['kids'] except KeyError: return None comment_urls = [] for comment_id in comment_ids: url = API_BASE + "item/" + str(comment_id) + '.json' comment_urls.append(url) comment_urls[:limit] # default not given # try: # response_queue = fetch_parallel(comment_urls) # if json: # while not response_queue.empty(): # yield response_queue.get() # else: # while not response_queue.empty(): # yield comment_parser(response_queue.get()) # except AttributeError: # Exception("Too many requests worker!!") # using gevent response_list = fetch_event(comment_urls) response_obj = [comment_parser(comment_json) for comment_json in response_list] return response_obj
974,380
Fit the angles to the model Args: pvals (array-like) : positive values nvals (array-like) : negative values Returns: normalized coef_ values
def __get_vtt_angles(self, pvals, nvals): # https://www.khanacademy.org/math/trigonometry/unit-circle-trig-func/inverse_trig_functions/v/inverse-trig-functions--arctan angles = np.arctan2(pvals, nvals)-np.pi/4 norm = np.maximum(np.minimum(angles, np.pi-angles), -1*np.pi-angles) norm = csr_matrix(norm) # Remove any weight from the NER features. These will be added later. for key, value in self.B.items(): norm[0, key] = 0. return norm
974,402
Set the parameters of the estimator. Args: bias (array-like) : bias of the estimator. Also known as the intercept in a linear model. weights (array-like) : weights of the features. Also known as coeficients. NER biases (array-like) : NER entities infering column position on X and bias value. Ex: `b_4=10, b_5=6`. Example: >>> cls = VTT() >>> cls.set_params(b_4=10, b_5=6, b_6=8)
def set_params(self, **params): if 'bias' in params.keys(): self.intercept_ = params['bias'] if 'weights' in params.keys(): self.coef_ = params['weights'] for key in params.keys(): if 'b_' == key[:2]: self.B[int(key[2:])] = params[key] return self
974,404
Get parameters for the estimator. Args: deep (boolean, optional) : If True, will return the parameters for this estimator and contained subobjects that are estimators. Returns: params : mapping of string to any contained subobjects that are estimators.
def get_params(self, deep=True): params = {'weights':self.coef_, 'bias':self.intercept_} if deep: for key, value in self.B.items(): params['b_'+str(key)] = value return params
974,405
Return a `pandas.DataFrame` containing Python type information for the columns in `data_frame`. Args: data_frame (pandas.DataFrame) : Data frame containing data columns. Returns: (pandas.DataFrame) : Data frame indexed by the column names from `data_frame`, with the columns `'i'` and `'dtype'` indicating the index and Python type of the corresponding `data_frame` column, respectively.
def get_py_dtypes(data_frame): df_py_dtypes = data_frame.dtypes.map(get_py_dtype).to_frame('dtype').copy() df_py_dtypes.loc[df_py_dtypes.dtype == object, 'dtype'] = \ (df_py_dtypes.loc[df_py_dtypes.dtype == object].index .map(lambda c: str if data_frame[c] .map(lambda v: isinstance(v, str)).all() else object)) df_py_dtypes.insert(0, 'i', range(df_py_dtypes.shape[0])) df_py_dtypes.index.name = 'column' return df_py_dtypes
974,493
Return a `pandas.DataFrame` containing Python type information for the columns in `data_frame` and a `gtk.ListStore` matching the contents of the data frame. Args: data_frame (pandas.DataFrame) : Data frame containing data columns. Returns: (tuple) : The first element is a data frame as returned by `get_py_dtypes` and the second element is a `gtk.ListStore` matching the contents of the data frame.
def get_list_store(data_frame): df_py_dtypes = get_py_dtypes(data_frame) list_store = gtk.ListStore(*df_py_dtypes.dtype) for i, row_i in data_frame.iterrows(): list_store.append(row_i.tolist()) return df_py_dtypes, list_store
974,494
Add columns to a `gtk.TreeView` for the types listed in `df_py_dtypes`. Args: tree_view (gtk.TreeView) : Tree view to append columns to. df_py_dtypes (pandas.DataFrame) : Data frame containing type information for one or more columns in `list_store`. list_store (gtk.ListStore) : Model data. Returns: None
def add_columns(tree_view, df_py_dtypes, list_store): tree_view.set_model(list_store) for column_i, (i, dtype_i) in df_py_dtypes[['i', 'dtype']].iterrows(): tree_column_i = gtk.TreeViewColumn(column_i) tree_column_i.set_name(column_i) if dtype_i in (int, long): property_name = 'text' cell_renderer_i = gtk.CellRendererSpin() elif dtype_i == float: property_name = 'text' cell_renderer_i = gtk.CellRendererSpin() elif dtype_i in (bool, ): property_name = 'active' cell_renderer_i = gtk.CellRendererToggle() elif dtype_i in (str, ): property_name = 'text' cell_renderer_i = gtk.CellRendererText() else: raise ValueError('No cell renderer for dtype: %s' % dtype_i) cell_renderer_i.set_data('column_i', i) cell_renderer_i.set_data('column', tree_column_i) tree_column_i.pack_start(cell_renderer_i, True) tree_column_i.add_attribute(cell_renderer_i, property_name, i) tree_view.append_column(tree_column_i)
974,495
Records an event to MongoDB. Events can be later viewed in web status. Parameters: name: the name of the event, for example, "Work". etype: the type of the event, can be either "begin", "end" or "single". info: any extra event attributes.
def event(self, name, etype, **info): if etype not in ("begin", "end", "single"): raise ValueError("Event type must any of the following: 'begin', " "'end', 'single'") for handler in logging.getLogger().handlers: if isinstance(handler, MongoLogHandler): data = {"session": handler.log_id, "instance": handler.node_id, "time": time(), "domain": self.__class__.__name__, "name": name, "type": etype} dupkeys = set(data.keys()).intersection(set(info.keys())) if len(dupkeys) > 0: raise ValueError("Event kwargs may not contain %s" % dupkeys) data.update(info) handler.events.insert(data, w=0)
974,524
Computes the cross-entropy cost given in equation (13) Arguments: A2 -- The sigmoid output of the second activation, of shape (1, number of examples) Y -- "true" labels vector of shape (1, number of examples) parameters -- python dictionary containing your parameters W1, b1, W2 and b2 Returns: cost -- cross-entropy cost given equation (13)
def compute_cost(A2, Y): m = Y.shape[1] # number of example # Compute the cross-entropy cost logprobs = np.multiply(np.log(A2), Y) + np.multiply(np.log(1 - A2), (1 - Y)) cost = -np.sum(logprobs) / m cost = np.squeeze(cost) # makes sure cost is the dimension we expect. # E.g., turns [[17]] into 17 assert (isinstance(cost, float)) return cost
974,573
Implement the backward propagation using the instructions above. Arguments: parameters -- python dictionary containing our parameters cache -- a dictionary containing "Z1", "A1", "Z2" and "A2". X -- input data of shape (2, number of examples) Y -- "true" labels vector of shape (1, number of examples) Returns: grads -- python dictionary containing your gradients with respect to different parameters
def backward_propagation(parameters, cache, X, Y): m = X.shape[1] # First, retrieve W1 and W2 from the dictionary "parameters". W1 = parameters["W1"] W2 = parameters["W2"] # Retrieve also A1 and A2 from dictionary "cache". A1 = cache["A1"] A2 = cache["A2"] # Backward propagation: calculate dW1, db1, dW2, db2. dZ2 = A2 - Y dW2 = 1.0 / m * np.dot(dZ2, A1.T) db2 = 1.0 / m * np.sum(dZ2, axis=1, keepdims=True) dZ1 = W2.T * dZ2 * (1 - np.power(A1, 2)) dW1 = 1.0 / m * np.dot(dZ1, X.T) db1 = 1.0 / m * np.sum(dZ1, axis=1, keepdims=True) grads = {"dW1": dW1, "db1": db1, "dW2": dW2, "db2": db2} return grads
974,574
Updates parameters using the gradient descent update rule given above Arguments: parameters -- python dictionary containing your parameters grads -- python dictionary containing your gradients Returns: parameters -- python dictionary containing your updated parameters
def update_parameters(parameters, grads, learning_rate=1.2): # Retrieve each parameter from the dictionary "parameters" W1 = parameters["W1"] b1 = parameters["b1"] W2 = parameters["W2"] b2 = parameters["b2"] # Retrieve each gradient from the dictionary "grads" dW1 = grads["dW1"] db1 = grads["db1"] dW2 = grads["dW2"] db2 = grads["db2"] # Update rule for each parameter W1 -= learning_rate * dW1 b1 -= learning_rate * db1 W2 -= learning_rate * dW2 b2 -= learning_rate * db2 parameters = {"W1": W1, "b1": b1, "W2": W2, "b2": b2} return parameters
974,575
Using the learned parameters, predicts a class for each example in X Arguments: parameters -- python dictionary containing your parameters X -- input data of size (n_x, m) Returns predictions -- vector of predictions of our model (red: 0 / blue: 1)
def predict(parameters, X): # Computes probabilities using forward propagation, # and classifies to 0/1 using 0.5 as the threshold. A2, cache = forward_propagation(X, parameters) predictions = np.array([1 if (i > 0.5) else 0 for i in A2[0]]) return predictions
974,577
Python descriptor protocol `__get__` magic method. Args: instance(object): The instance with descriptor attribute. owner(object): Instance class. Returns: The cached value for the class instance or None.
def __get__(self, instance, owner): if not instance and owner: # pragma: no cover return self value = self._cache.get(instance) if self._cache.get(instance) is not None else self.default if hasattr(instance, 'prepare_' + self.alias): return getattr(instance, 'prepare_' + self.alias)(value) return value
974,704
Python descriptor protocol `__set__` magic method. Args: instance (object): The instance with descriptor attribute. value (object): The value for instance attribute.
def __set__(self, instance, value): if value is None and self.default: self._cache[instance] = self.default else: try: cleaned_value = self.field_value(value) except NodeTypeError as node_error: raise SchemaNodeError('{}.{}: {}'.format( instance.__class__.__name__, self.alias, node_error.args[0]) ) try: self.is_valid(cleaned_value) except SchemaNodeValidatorError as error: raise SchemaNodeError( '{}.{} Error for value `{}` : {}'.format( instance.__class__.__name__, self.alias, value, error.args[0] ) ) self._cache[instance] = cleaned_value
974,705
Validate value before actual instance setting based on type. Args: value (object): The value object for validation. Returns: True if value validation succeeds else False.
def is_valid(self, value): if not self.is_array: return self._valid(value) if isinstance(value, (list, set, tuple)): return all([self._valid(item) for item in value]) return self._valid(value)
974,708
An decorator checking whether date parameter is passing in or not. If not, default date value is all PTT data. Else, return PTT data with right date. Args: func: function you want to decorate. request: WSGI request parameter getten from django. Returns: date: a datetime variable, you can only give year, year + month or year + month + day, three type. The missing part would be assigned default value 1 (for month is Jan, for day is 1).
def date_proc(func): @wraps(func) def wrapped(request, *args, **kwargs): if 'date' in request.GET and request.GET['date'] == '': raise Http404("api does not exist") elif 'date' not in request.GET: date = datetime.today() return func(request, date) else: date = tuple(int(intValue) for intValue in request.GET['date'].split('-')) if len(date) == 3: date = datetime(*date) elif len(date) == 2: date = datetime(*date, day = 1) else: date = datetime(*date, month = 1, day = 1) return func(request, date) return wrapped
974,847
An decorator checking whether queryString key is valid or not Args: str: allowed queryString key Returns: if contains invalid queryString key, it will raise exception.
def queryString_required(strList): def _dec(function): @wraps(function) def _wrap(request, *args, **kwargs): for i in strList: if i not in request.GET: raise Http404("api does not exist") return function(request, *args, **kwargs) return _wrap return _dec
974,848
An decorator checking whether queryString key is valid or not Args: str: allowed queryString key Returns: if contains invalid queryString key, it will raise exception.
def queryString_required_ClassVersion(strList): def _dec(function): @wraps(function) def _wrap(classInstance, request, *args, **kwargs): for i in strList: if i not in request.GET: raise Http404("api does not exist") return function(classInstance, request, *args, **kwargs) return _wrap return _dec
974,849
Return json from querying Web Api Args: view: django view function. request: http request object got from django. Returns: json format dictionary
def getJsonFromApi(view, request): jsonText = view(request) jsonText = json.loads(jsonText.content.decode('utf-8')) return jsonText
974,852
Setup the common UI elements and behavior for a PQ Game UI. Arguments: - base: a tkinter base element in which to create parts
def __init__(self, base, analysis_function, time_limit=5.0): self._base = base self._analysis_function = analysis_function self._tile_images = self._create_tile_images() self._analyze_start_time = None self.time_limit = time_limit self.summaries = None self._parts = self._setup_parts(self._base)
975,080
Default Called when the regular Encoder can't figure out what to do with the type Args: self (CEncoder): A pointer to the current instance obj (mixed): An unknown object that needs to be encoded Returns: str: A valid JSON string representing the object
def default(self, obj): # If we have a datetime object if isinstance(obj, datetime): return obj.strftime('%Y-%m-%d %H:%M:%S') # Else if we have a decimal object elif isinstance(obj, Decimal): return '{0:f}'.format(obj) # Bubble back up to the parent default return json.JSONEncoder.default(self, obj)
975,104
Run all availalbe sanitizers across a configuration. Arguments: configuration - a full project configuration error_fn - A function to call if a sanitizer check fails. The function takes a single argument: a description of the problem; provide specifics if possible, including the componnet, the part of the configuration that presents an issue, etc..
def sanitize(configuration, error_fn): for name, sanitize_fn in _SANITIZERS.items(): sanitize_fn(configuration, lambda warning, n=name: error_fn(n, warning))
975,264
Helper method to reduce some boilerplate with :module:`aiohttp`. Args: term: The term to search for. Optional if doing a random search. random: Whether the search should return a random word. Returns: The JSON response from the API. Raises: UrbanConnectionError: If the response status isn't ``200``. WordNotFoundError: If the response doesn't contain data (i.e. no word found).
async def _get(self, term: str = None, random: bool = False) -> dict: params = None if random: url = self.RANDOM_URL else: params = {'term': term} url = self.API_URL async with self.session.get(url, params=params) as response: if response.status == 200: response = await response.json() else: raise UrbanConnectionError(response.status) if not response['list']: raise WordNotFoundError(term) return response
975,402
Gets the first matching word available. Args: term: The word to be defined. Returns: The closest matching :class:`Word` from UrbanDictionary. Raises: UrbanConnectionError: If the response status isn't ``200``. WordNotFoundError: If the response doesn't contain data (i.e. no word found).
async def get_word(self, term: str) -> 'asyncurban.word.Word': resp = await self._get(term=term) return Word(resp['list'][0])
975,403
Performs a search for a term and returns the raw response. Args: term: The term to be defined. limit: The maximum amount of results you'd like. Defaults to 3. Returns: A list of :class:`dict`\s which contain word information.
async def search_raw(self, term: str, limit: int = 3) -> List[dict]: return (await self._get(term=term))['list'][:limit]
975,406
Create a TaskCommand with defined tasks. This is a helper function to avoid boiletplate when dealing with simple cases (e.g., all cli arguments can be handled by TaskCommand), with no special processing. In general, this means a command only needs to run established tasks. Arguments: tasks - the tasks to execute args - extra arguments to pass to the TargetCommand constructor kwargs - extra keyword arguments to pass to the TargetCommand constructor
def make_command(tasks, *args, **kwargs): command = TaskCommand(tasks=tasks, *args, **kwargs) return command
975,657
Runs the provided command with the given args. Exceptions, if any, are propogated to the caller. Arguments: command - something that extends the Command class args - A list of command line arguments. If args is None, sys.argv (without the first argument--assumed to be the command name) will be used.
def execute_command(command, args): if args is None: args = sys.argv[1:] try: command.execute(args) except IOError as failure: if failure.errno == errno.EPIPE: # This probably means we were piped into something that terminated # (e.g., head). Might be a better way to handle this, but for now # silently swallowing the error isn't terrible. pass except _PartialFailureException as failed: for failure, skipped, message in failed.failed: print("\nTask {} failed".format(failure), file=sys.stderr) print("\tError: {}".format(message), file=sys.stderr) print("\tSkipped: {}".format(skipped), file=sys.stderr) sys.exit(1) except Exception as failure: # pylint: disable=broad-except print("Error: {}".format(str(failure)), file=sys.stderr) sys.exit(1)
975,658
Add the --version string with appropriate output. Arguments: version - the version of whatever provides the command
def set_version(self, version): self.parser.add_argument( "--version", action="version", version="%(prog)s {} (core {})".format( version, devpipeline_core.version.STRING ), )
975,660
Implement the cost function and its gradient for the propagation Arguments: w weights, a numpy array of size (dim, 1) b bias, a scalar X data of size (dim, number of examples) Y true "label" vector of size (1, number of examples) Return: cost negative log-likelihood cost for logistic regression dw gradient of the loss with respect to w, thus same shape as w db gradient of the loss with respect to b, thus same shape as b
def propagate(w, b, X, Y): m = X.shape[1] A = sigmoid(np.dot(w.T, X) + b) cost = -1 / m * np.sum(Y * np.log(A) + (1 - Y) * np.log(1 - A)) # BACKWARD PROPAGATION (TO FIND GRAD) dw = 1.0 / m * np.dot(X, (A - Y).T) db = 1.0 / m * np.sum(A - Y) assert (dw.shape == w.shape) assert (db.dtype == float) cost = np.squeeze(cost) assert (cost.shape == ()) grads = {"dw": dw, "db": db} return grads, cost
975,736
Predict whether the label is 0 or 1 using learned logistic regression parameters (w, b) Arguments: w -- weights, a numpy array of size (num_px * num_px * 3, 1) b -- bias, a scalar X -- data of size (num_px * num_px * 3, number of examples) Returns: Y_prediction -- a numpy array (vector) containing all predictions (0/1) for the examples in X
def LR_predict(w, b, X): m = X.shape[1] Y_prediction = np.zeros((1, m)) w = w.reshape(X.shape[0], 1) A = sigmoid(np.dot(w.T, X) + b) for i in range(A.shape[1]): if A[0, i] > 0.5: Y_prediction[0, i] = 1.0 else: Y_prediction[0, i] = 0.0 assert (Y_prediction.shape == (1, m)) return Y_prediction
975,738
plot learning curve Arguments: d Returned by model function. Dictionary containing information about the model.
def plot_lc(d): costs = np.squeeze(d['costs']) plt.plot(costs) plt.ylabel('cost') plt.xlabel('iterations (per hundreds)') plt.title("Learning rate =" + str(d["learning_rate"])) plt.show()
975,740
Create a path based on component configuration. All paths are relative to the component's configuration directory; usually this will be the same for an entire session, but this function supuports component-specific configuration directories. Arguments: config - the configuration object for a component endings - a list of file paths to append to the component's configuration directory
def make_path(config, *endings): config_dir = config.get("dp.config_dir") return os.path.join(config_dir, *endings)
976,201
Constructor Args: election_type (str): May be one of ``['sp', 'nia', 'pcc', 'naw', 'parl', 'local', 'gla', 'mayor']`` date (date|str): May be either a python date object, or a string in 'Y-m-d' format. ``myid = IdBuilder('local', date(2018, 5, 3))`` and ``myid = IdBuilder('local', '2018-05-03'))`` are functionally equivalent invocations. Returns: IdBuilder
def __init__(self, election_type, date): if election_type == 'ref': raise NotImplementedError() if election_type == 'eu': raise NotImplementedError() self._validate_election_type(election_type) self.election_type = election_type self.spec = RULES[self.election_type] self.date = self._format_date(date) self.subtype = None self.organisation = None self.division = None self.contest_type = None
976,347
Add a subtype segment Args: subtype (str): May be one of ``['a', 'c', 'r']``. See the `Reference Definition <https://elections.democracyclub.org.uk/reference_definition>`_. for valid election type/subtype combinations. Returns: IdBuilder Raises: ValueError
def with_subtype(self, subtype): self._validate_subtype(subtype) self.subtype = subtype return self
976,350
Add an organisation segment. Args: organisation (str): Official name of an administrative body holding an election. Returns: IdBuilder Raises: ValueError
def with_organisation(self, organisation): if organisation is None: organisation = '' organisation = slugify(organisation) self._validate_organisation(organisation) self.organisation = organisation return self
976,351
Add a division segment Args: division (str): Official name of an electoral division. Returns: IdBuilder Raises: ValueError
def with_division(self, division): if division is None: division = '' division = slugify(division) self._validate_division(division) self.division = division return self
976,352
Add a contest_type segment Args: contest_type (str): Invoke with ``contest_type='by'`` or ``contest_type='by-election'`` to add a 'by' segment to the ballot_id. Invoking with ``contest_type='election'`` is valid syntax but has no effect. Returns: IdBuilder Raises: ValueError
def with_contest_type(self, contest_type): self._validate_contest_type(contest_type) if contest_type.lower() in ('by', 'by election', 'by-election'): self.contest_type = 'by' return self
976,353
Find everything with a specific entry_point. Results will be returned as a dictionary, with the name as the key and the entry_point itself as the value. Arguments: entry_point_name - the name of the entry_point to populate
def query_plugins(entry_point_name): entries = {} for entry_point in pkg_resources.iter_entry_points(entry_point_name): entries[entry_point.name] = entry_point.load() return entries
976,730
Extract the edges using Scharr kernel (Sobel optimized for rotation invariance) Parameters: ----------- im: 2d array The image blurRadius: number, default 10 The gaussian blur raduis (The kernel has size 2*blurRadius+1) imblur: 2d array, OUT If not None, will be fille with blurred image Returns: -------- out: 2d array The edges of the images computed with the Scharr algorithm
def Scharr_edge(im, blurRadius=10, imblur=None): im = np.asarray(im, dtype='float32') blurRadius = 2 * blurRadius + 1 im = cv2.GaussianBlur(im, (blurRadius, blurRadius), 0) Gx = cv2.Scharr(im, -1, 0, 1) Gy = cv2.Scharr(im, -1, 1, 0) ret = cv2.magnitude(Gx, Gy) if imblur is not None and imblur.shape == im.shape: imblur[:, :] = im return ret
976,831
Scale the image to uint8 Parameters: ----------- im: 2d array The image Returns: -------- im: 2d array (dtype uint8) The scaled image to uint8
def uint8sc(im): im = np.asarray(im) immin = im.min() immax = im.max() imrange = immax - immin return cv2.convertScaleAbs(im - immin, alpha=255 / imrange)
976,833
Return an actor object matching the one in the game image. Note: Health and mana are based on measured percentage of a fixed maximum rather than the actual maximum in the game. Arguments: name: must be 'player' or 'opponent' game_image: opencv image of the main game area
def _actor_from_game_image(self, name, game_image): HEALTH_MAX = 100 MANA_MAX = 40 # get the set of tools for investigating this actor tools = {'player': self._player_tools, 'opponent': self._oppnt_tools}[name] # setup the arguments to be set: args = [name] # health: t, l, b, r = tools['health_region'].region_in(game_image) health_image = game_image[t:b, l:r] health_image = numpy.rot90(health_image) # upright for the TankLevel how_full = tools['health_tank'].how_full(health_image) if how_full is None: return None # failure health = int(round(HEALTH_MAX * how_full)) args.append((health, HEALTH_MAX)) # mana for color in ('r', 'g', 'b', 'y'): t, l, b, r = tools[color + '_region'].region_in(game_image) mana_image = game_image[t:b, l:r] how_full = tools[color + '_tank'].how_full(mana_image) if how_full is None: return None # failure mana = int(round(MANA_MAX * how_full)) args.append((mana, MANA_MAX)) # experience and coins simply start at zero x_m = (0, 1000), (0, 1000) args.extend(x_m) # hammer and scroll are unused h_c = (0, 0), (0, 0) args.extend(h_c) # build the actor and return it return Actor(*args)
976,852
Simulate a complete turn from one state only and generate each end of turn reached in the simulation. Arguments: Exactly one of: root: a start state with no parent or root_eot: an EOT or ManaDrain transition in the simulation
def ends_of_one_state(self, root=None, root_eot=None): # basic confirmation of valid arguments self._argument_gauntlet(root_eot, root) # setup the starting state if root: start_state = root else: start_state = State(root_eot.parent.board.copy(), root_eot.parent.player.copy(), root_eot.parent.opponent.copy(), root_eot.parent.turn + 1, 1) root_eot.graft_child(start_state) # track states that are stable - i.e. no remaining chain reactions ready_for_action = [start_state] # simulate all actions for each state until reaching EOTs while ready_for_action: ready_state = ready_for_action.pop() # handle states that have run out of actions (end of turn) if ready_state.actions_remaining <= 0: root_eot = self._simulated_EOT(ready_state) yield root_eot continue # no more simulation for an EOT # handle swaps when there are actions remaining for swap_result in self._simulated_swap_results(ready_state): # handle any chain reactions if swap_result.actions_remaining \ >= ready_state.actions_remaining: already_used_bonus = True else: already_used_bonus = False chain_result = self._simulated_chain_result(swap_result, already_used_bonus) # chain results may be filtered so test first if chain_result: ready_for_action.append(chain_result) #at this point all swaps have been tried #if nothing was valid, it's a manadrain if not tuple(ready_state.children): mana_drain_eot = self._simulated_mana_drain(ready_state) yield mana_drain_eot continue # if something was valid, now spells can be simulated else: pass
976,855
Simulate one complete turn to completion and generate each end of turn reached during the simulation. Note on mana drain: Generates but does not continue simulation of mana drains. Arguments: root: a start state with no parent
def ends_of_next_whole_turn(self, root): # simple confirmation that the root is actually a root. # otherwise it may seem to work but would be totally out of spec if root.parent: raise ValueError('Unexpectedly received a node with a parent for' ' root:\n{}'.format(root)) # build the list of eots (or just the root if first turn) to be run leaves = list(root.leaves()) kw_starts = list() if leaves[0] is root: # build ends of state kwargs as only the root kw_starts.append({'root': root}) else: # build ends of state kwargs as eots in the tree for leaf in leaves: # ignore mana drains if not leaf.is_mana_drain: kw_starts.append({'root_eot': leaf}) # run a single turn for each starting point for kw_start in kw_starts: for eot in self.ends_of_one_state(**kw_start): yield eot
976,856
Simulate any chain reactions. Arguments: potential_chain: a state to be tested for chain reactions already_used_bonus: boolean indicating whether a bonus turn was already applied during this action Return: final result state or None (if state is filtered out in capture) Note that if there is no chain reaction, the final result is the same as the original state received.
def _simulated_chain_result(self, potential_chain, already_used_bonus): while potential_chain: # hook for capture game optimizations. no effect in base # warning: only do this ONCE for any given state or it will # always filter the second time if self._disallow_state(potential_chain): potential_chain.graft_child(Filtered()) return None # no more simulation for this filtered state result_board, destroyed_groups = \ potential_chain.board.execute_once(random_fill= self.random_fill) # yield the state if nothing happened during execution (chain done) if not destroyed_groups: # yield this state as the final result of the chain return potential_chain # attach the transition chain = ChainReaction() potential_chain.graft_child(chain) # attach the result state if already_used_bonus: # disallow bonus action if already applied bonus_action = 0 else: # allow bonus action once and then flag as used bonus_action = any(len(group) >= 4 for group in destroyed_groups) already_used_bonus = True cls = potential_chain.__class__ chain_result = cls(board=result_board, turn=potential_chain.turn, actions_remaining= potential_chain.actions_remaining + bonus_action, player=potential_chain.player.copy(), opponent=potential_chain.opponent.copy()) # update the player and opponent base_attack = \ chain_result.active.apply_tile_groups(destroyed_groups) chain_result.passive.apply_attack(base_attack) chain.graft_child(chain_result) # prepare to try for another chain reaction potential_chain = chain_result
976,860
Execute the board only one time. Do not execute chain reactions. Arguments: swap - pair of adjacent positions spell_changes - sequence of (position, tile) changes spell_destructions - sequence of positions to be destroyed Return: (copy of the board, destroyed tile groups)
def execute_once(self, swap=None, spell_changes=None, spell_destructions=None, random_fill=False): bcopy = self.copy() # work with a copy, not self total_destroyed_tile_groups = list() # swap if any bcopy._swap(swap) # spell changes if any bcopy._change(spell_changes) # spell destructions and record if any # first convert simple positions to groups spell_destructions = spell_destructions or tuple() destruction_groups = [[p] for p in spell_destructions] destroyed_tile_groups = bcopy._destroy(destruction_groups) total_destroyed_tile_groups.extend(destroyed_tile_groups) # execute one time only # look for matched groups matched_position_groups = bcopy._match() # destroy and record matched groups destroyed_tile_groups = bcopy._destroy(matched_position_groups) total_destroyed_tile_groups.extend(destroyed_tile_groups) bcopy._fall() if random_fill: bcopy._random_fill() return bcopy, total_destroyed_tile_groups
976,867
Main functionality of _match, but works only on rows. Full matches are found by running this once with original board and once with a transposed board. Arguments: optimized_lines is an optional argument that identifies the lines that need to be matched. transpose indicates whether the match is looking at rows or columns
def __match_rows(self, optimized_lines=None, transpose=False): MIN_LENGTH = 3 a = self._array if transpose: a = a.T rows = optimized_lines or range(8) # check for matches in each row separately for row in rows: NUM_COLUMNS = 8 match_length = 1 start_position = 0 # next tile pointer #set next start position as long as a match is still possible while start_position + MIN_LENGTH <= NUM_COLUMNS: group_type = a[row, start_position] # try to increase match length as long as there is room while start_position + match_length + 1 <= NUM_COLUMNS: next_tile = a[row, start_position + match_length] # if no match, stop looking for further matches if not group_type.matches(next_tile): break # if group_type is wildcard, try to find a real type if group_type.is_wildcard(): group_type = next_tile match_length += 1 #produce a matched position group if the current match qualifies if match_length >= MIN_LENGTH and not group_type.is_wildcard(): row_ = row target_positions = [(row_, col_) for col_ in range(start_position, start_position + match_length)] if transpose: target_positions = [(col_, row_) for row_, col_ in target_positions] yield target_positions #setup for continuing to look for matches after the current one start_position += match_length match_length = 1
976,871
Get a string value from the componnet. Arguments: key - the key to retrieve raw - Control whether the value is interpolated or returned raw. By default, values are interpolated. fallback - The return value if key isn't in the component.
def get(self, key, raw=False, fallback=None): return self._component.get(key, raw=raw, fallback=fallback)
976,916
Retrieve a value in list form. The interpolated value will be split on some key (by default, ',') and the resulting list will be returned. Arguments: key - the key to return fallback - The result to return if key isn't in the component. By default, this will be an empty list. split - The key to split the value on. By default, a comma (,).
def get_list(self, key, fallback=None, split=","): fallback = fallback or [] raw = self.get(key, None) if raw: return [value.strip() for value in raw.split(split)] return fallback
976,917
Set a value in the component. Arguments: key - the key to set value - the new value
def set(self, key, value): if self._component.get(key, raw=True) != value: self._component[key] = value self._main_config.dirty = True
976,918
Base validation method. Check if type is valid, or try brute casting. Args: value (object): A value for validation. Returns: Base_type instance. Raises: SchemaError, if validation or type casting fails.
def validate(self, value): cast_callback = self.cast_callback if self.cast_callback else self.cast_type try: return value if isinstance(value, self.cast_type) else cast_callback(value) except Exception: raise NodeTypeError('Invalid value `{}` for {}.'.format(value, self.cast_type))
977,096
Either return the non-list value or raise an Exception. Arguments: vals - a list of values to process
def join(self, vals): if len(vals) == 1: return vals[0] raise Exception( "Too many values for {}:{}".format(self._component_name, self._key) )
977,217
Update version number. Args: bump (str): bump level ignore_prerelease (bool): ignore the fact that our new version is a prerelease, or issue a warning Returns a two semantic_version objects (the old version and the current version).
def update_version_number(ctx, bump=None, ignore_prerelease=False): if bump is not None and bump.lower() not in VALID_BUMPS: print(textwrap.fill("[{}WARN{}] bump level, as provided on command " "line, is invalid. Trying value given in " "configuration file. Valid values are {}." .format(WARNING_COLOR, RESET_COLOR, VALID_BUMPS_STR), width=text.get_terminal_size().columns - 1, subsequent_indent=' '*7)) bump = None else: update_level = bump # Find current version temp_file = Path(ctx.releaser.version).resolve().parent / ("~" + Path(ctx.releaser.version).name) with temp_file.open(mode='w', encoding='utf-8') as g: with Path(ctx.releaser.version).resolve().open(mode='r', encoding='utf-8') as f: for line in f: version_matches = bare_version_re.match(line) if version_matches: bare_version_str = version_matches.groups(0)[0] if semantic_version.validate(bare_version_str): old_version = Version(bare_version_str) print("{}Current version is {}".format(" "*4, old_version)) else: old_version = Version.coerce(bare_version_str) ans = text.query_yes_quit("{}I think the version is {}." " Use it?".format(" "*4, old_version), default="yes") if ans == text.Answers.QUIT: exit('[{}ERROR{}] Please set an initial version ' 'number to continue.'.format(ERROR_COLOR, RESET_COLOR)) # if bump level not defined by command line options if bump is None: try: update_level = ctx.releaser.version_bump except AttributeError: print("[{}WARN{}] bump level not defined in " "configuration. Use key " "'releaser.version_bump'" .format(WARNING_COLOR, RESET_COLOR)) print(textwrap.fill("{}Valid bump levels are: " "{}. Or use 'quit' to exit." .format(" "*7, VALID_BUMPS_STR), width=text.get_terminal_size().columns - 1, subsequent_indent=' '*7)) my_input = input("What bump level to use? ") if my_input.lower() in ["quit", "q", "exit", "y"]: sys.exit(0) elif my_input.lower() not in VALID_BUMPS: exit("[{}ERROR{}] invalid bump level provided. " "Exiting...".format(ERROR_COLOR, RESET_COLOR)) else: update_level = my_input # Determine new version number if update_level is None or update_level.lower() in ['none']: update_level = None elif update_level is not None: update_level = update_level.lower() if update_level in ['breaking', 'major']: current_version = old_version.next_major() elif update_level in ['feature', 'minor']: current_version = old_version.next_minor() elif update_level in ['bugfix', 'patch']: current_version = old_version.next_patch() elif update_level in ['dev', 'development', 'prerelease']: if not old_version.prerelease: current_version = old_version.next_patch() current_version.prerelease = ('dev', ) else: current_version = old_version elif update_level is None: # don't update version current_version = old_version else: exit('[{}ERROR{}] Cannot update version in {} mode' .format(ERROR_COLOR, RESET_COLOR, update_level)) # warn on pre-release versions if current_version.prerelease and not ignore_prerelease: ans = text.query_yes_quit("[{}WARN{}] Current version " "is a pre-release version. " "Continue anyway?" .format(WARNING_COLOR, RESET_COLOR), default="quit") if ans == text.Answers.QUIT: sys.exit(1) print("{}New version is {}".format(" "*4, current_version)) # Update version number line = '__version__ = "{}"\n'.format(current_version) print(line, file=g, end="") #print('', file=g) # add a blank line at the end of the file shutil.copyfile(str(temp_file), str(Path(ctx.releaser.version).resolve())) os.remove(str(temp_file)) return(old_version, current_version)
977,293
Validate inputs. Raise exception if something is missing. args: actual_inputs: the object/dictionary passed to a subclass of PublishablePayload required_inputs: the object/dictionary containing keys (and subkeys) for required fields. (See get_common_payload_template.) keypath: used internally in recursive function calls. return: Nothing. An exception will be raised if a problem is encountered.
def _validate_inputs(actual_inputs, required_inputs, keypath=None): actual_keys = set(actual_inputs.keys()) required_keys = set(required_inputs.keys()) if actual_keys.intersection(required_keys) != required_keys: prefix = '%s.' if keypath else '' output_keys = {'%s%s' % (prefix, key) for key in required_keys} raise Exception("Missing input fields. Expected %s." % ', '.join(output_keys)) for key in required_keys: # TODO: review the following usage of isinstance. # Will this always be appropriate, given duck typing? if isinstance(required_inputs[key], dict): new_keypath = key if not keypath else '%s.%s' % (keypath, key) _validate_inputs( actual_inputs=actual_inputs[key], required_inputs=required_inputs[key], keypath=new_keypath )
977,433
Confrim a valid configuration. Args: ctx (invoke.context): base_key (str): the base configuration key everything is under. needed_keys (list): sub-keys of the base key that are checked to make sure they exist.
def check_configuration(ctx, base_key, needed_keys): # check for valid configuration if base_key not in ctx.keys(): exit("[{}ERROR{}] missing configuration for '{}'" .format(ERROR_COLOR, RESET_COLOR, base_key)) # TODO: offer to create configuration file if ctx.releaser is None: exit("[{}ERROR{}] empty configuration for '{}' found" .format(ERROR_COLOR, RESET_COLOR, base_key)) # TODO: offer to create configuration file # TODO: allow use of default values for my_key in needed_keys: if my_key not in ctx[base_key].keys(): exit("[{}ERROR{}] missing configuration key '{}.{}'" .format(ERROR_COLOR, RESET_COLOR, base_key, my_key))
977,607
Child A private function to figure out the child node type Arguments: details {dict} -- A dictionary describing a data point Returns: _NodeInterface
def _child(details): # If the details are a list if isinstance(details, list): # Create a list of options for the key return OptionsNode(details) # Else if we got a dictionary elif isinstance(details, dict): # If array is present if '__array__' in details: return ArrayNode(details) # Else if we have a hash elif '__hash__' in details: return HashNode(details) # Else if we have a type elif '__type__' in details: # If the type is a dictionary or list, this is a complex type if isinstance(details['__type__'], (dict,list)): return _child(details['__type__']) # Else it's just a Node else: return Node(details) # Else it's most likely a parent else: return Parent(details) # Else if we got a string elif isinstance(details, basestring): # Use the value as the type return Node(details) # Else raise an error else: raise TypeError('details')
977,635
From File Loads a JSON file and creates a Node instance from it Args: filename (str): The filename to load Returns: _NodeInterface
def fromFile(cls, filename): # Load the file oFile = open(filename) # Convert it to a dictionary dDetails = JSON.decodef(oFile) # Create and return the new instance return cls(dDetails)
977,636
Constructor Initialises the instance Arguments: details {dict} -- Details describing the type of values allowed for the node _class {str} -- The class of the child Raises: ValueError Returns: _BaseNode
def __init__(self, details, _class): # If details is not a dict instance if not isinstance(details, dict): raise ValueError('details in ' + self.__class__.__name__ + '.' + sys._getframe().f_code.co_name + ' must be a dict') # Init the variables used to identify the last falure in validation self.validation_failures = {} # Store the class name self._class = _class # Init the optional flag, assume all nodes are necessary self._optional = False # If the details contains an optional flag if '__optional__' in details: # If it's a valid bool, store it if isinstance(details['__optional__'], bool): self._optional = details['__optional__'] # Else, write a warning to stderr else: sys.stderr.write('"' + str(details['__optional__']) + '" is not a valid value for __optional__, assuming false') # Remove it from details del details['__optional__'] # Init the special dict self._special = {} # If there are any other special fields in the details for k in (tuple(details.keys())): # If key is special oMatch = _specialKey.match(k) if oMatch: # Store it with the other specials then remove it self._special[oMatch.group(1)] = details[k] del details[k]
977,637
Optional Getter/Setter method for optional flag Args: value (bool): If set, the method is a setter Returns: bool | None
def optional(self, value = None): # If there's no value, this is a getter if value is None: return this._optional # Else, set the flag else: this._optional = value and True or False
977,638
Constructor Initialises the instance Arguments: details {dict} -- Details describing the type of values allowed for the node Raises: KeyError ValueError Returns: ArrayNode
def __init__(self, details): # If details is not a dict instance if not isinstance(details, dict): raise ValueError('details') # If the array config is not found if '__array__' not in details: raise KeyError('__array__') # If the value is not a dict if not isinstance(details['__array__'], dict): details['__array__'] = { "type": details['__array__'] } # If the type is missing if not 'type' in details['__array__']: self._type = 'unique' # Or if the type is invalid elif details['__array__']['type'] not in self._VALID_ARRAY: self._type = 'unique' sys.stderr.write('"' + str(details['__array__']['type']) + '" is not a valid type for __array__, assuming "unique"') # Else, store it else: self._type = details['__array__']['type'] # Init the min/max values self._minimum = None self._maximum = None # If there's a minimum or maximum present if 'minimum' in details['__array__'] \ or 'maximum' in details['__array__']: self.minmax( ('minimum' in details['__array__'] and details['__array__']['minimum'] or None), ('maximum' in details['__array__'] and details['__array__']['maximum'] or None) ) # If there's an optional flag somewhere in the mix if '__optional__' in details: bOptional = details['__optional__'] del details['__optional__'] elif 'optional' in details['__array__']: bOptional = details['__array__']['optional'] else: bOptional = None # Remove the __array__ field from details del details['__array__'] # Store the child self._node = _child(details) # If we had an optional flag, add it for the parent constructor if bOptional: details['__optional__'] = sOptional # Call the parent constructor super(ArrayNode, self).__init__(details, 'ArrayNode')
977,641
Clean Goes through each of the values in the list, cleans it, stores it, and returns a new list Arguments: value {list} -- The value to clean Returns: list
def clean(self, value): # If the value is None and it's optional, return as is if value is None and self._optional: return None # If the value is not a list if not isinstance(value, list): raise ValueError('value') # Recurse and return it return [self._node.clean(m) for m in value]
977,642
Valid Checks if a value is valid based on the instance's values Arguments: value {mixed} -- The value to validate Returns: bool
def valid(self, value, level=[]): # Reset validation failures self.validation_failures = [] # If the value is None and it's optional, we're good if value is None and self._optional: return True # If the value isn't a list if not isinstance(value, list): self.validation_failures.append(('.'.join(level), str(value))) return False # Init the return, assume valid bRet = True # Keep track of duplicates if self._type == 'unique': lItems = [] # Go through each item in the list for i in range(len(value)): # Add the field to the level lLevel = level[:] lLevel.append('[%d]' % i) # If the element isn't valid, return false if not self._node.valid(value[i], lLevel): self.validation_failures.extend(self._node.validation_failures[:]) bRet = False; continue; # If we need to check for duplicates if self._type == 'unique': # Try to get an existing item try: # If it is found, we have a duplicate iIndex = lItems.index(value[i]) # Add the error to the list self.validation_failures.append(('.'.join(lLevel), 'duplicate of %s[%d]' % ('.'.join(level), iIndex))) bRet = False continue # If a Value Error is thrown, there is no duplicate, add the # value to the list and continue except ValueError: lItems.append(value[i]) # If there's a minumum if self._minimum is not None: # If we don't have enough if len(value) < self._minimum: self.validation_failures.append(('.'.join(level), 'did not meet minimum')) bRet = False # If there's a maximum if self._maximum is not None: # If we have too many if len(value) > self._maximum: self.validation_failures.append(('.'.join(level), 'exceeds maximum')) bRet = False # Return whatever the result was return bRet
977,645
Constructor Initialises the instance Arguments: details {dict} -- Details describing the type of values allowed for the node Raises: KeyError ValueError Returns: HashNode
def __init__(self, details): # If details is not a dict instance if not isinstance(details, dict): raise ValueError('details') # If the hash config is not found if '__hash__' not in details: raise KeyError('__hash__') # If there's an optional flag somewhere in the mix if '__optional__' in details: bOptional = details['__optional__'] del details['__optional__'] else: bOptional = None # If the hash is simply set to True, make it a string with no # requirements if details['__hash__'] is True: details['__hash__'] = {"__type__":"string"} # Store the key using the hash value self._key = Node(details['__hash__']) # Remove it from details del details['__hash__'] # Store the child self._node = _child(details) # If we had an optional flag, add it for the parent constructor if bOptional: details['__optional__'] = bOptional # Call the parent constructor super(HashNode, self).__init__(details, 'HashNode')
977,646
Clean Makes sure both the key and value are properly stored in their correct representation Arguments: value {mixed} -- The value to clean Raises: ValueError Returns: mixed
def clean(self, value): # If the value is None and it's optional, return as is if value is None and self._optional: return None # If the value is not a dict if not isinstance(value, dict): raise ValueError('value') # Recurse and return it return {str(self._key.clean(k)):self._node.clean(v) for k,v in iteritems(value)}
977,647
Valid Checks if a value is valid based on the instance's values Arguments: value {mixed} -- The value to validate Returns: bool
def valid(self, value, level=[]): # Reset validation failures self.validation_failures = [] # If the value is None and it's optional, we're good if value is None and self._optional: return True # If the value isn't a dictionary if not isinstance(value, dict): self.validation_failures.append(('.'.join(level), str(value))) return False # Init the return, assume valid bRet = True # Go through each key and value for k,v in iteritems(value): # Add the field to the level lLevel = level[:] lLevel.append(k) # If the key isn't valid if not self._key.valid(k): self.validation_failures.append(('.'.join(lLevel), 'invalid key: %s' % str(k))) bRet = False continue # Check the value if not self._node.valid(v, lLevel): self.validation_failures.extend(self._node.validation_failures) bRet = False continue # Return whatever the result was return bRet
977,649
Constructor Initialises the instance Arguments: details {dict} -- Details describing the type of value allowed for the node Raises: KeyError ValueError Returns: Node
def __init__(self, details): # If we got a string if isinstance(details, basestring): details = {"__type__": details} # If details is not a dict instance elif not isinstance(details, dict): raise ValueError('details') # If the type is not found or is invalid if '__type__' not in details or details['__type__'] not in self._VALID_TYPES: raise KeyError('__type__') # Store the type and remove it from the details self._type = details['__type__'] del details['__type__'] # Init the value types self._regex = None self._options = None self._minimum = None self._maximum = None # If there's a regex string available if '__regex__' in details: self.regex(details['__regex__']) del details['__regex__'] # Else if there's a list of options elif '__options__' in details: self.options(details['__options__']) del details['__options__'] # Else else: # If there's a min or max bMin = ('__minimum__' in details and True or False) bMax = ('__maximum__' in details and True or False) if bMin or bMax: self.minmax( (bMin and details['__minimum__'] or None), (bMax and details['__maximum__'] or None) ) if bMin: del details['__minimum__'] if bMax: del details['__maximum__'] # Call the parent constructor super(Node, self).__init__(details, 'Node')
977,650
Compare IPs Compares two IPs and returns a status based on which is greater If first is less than second: -1 If first is equal to second: 0 If first is greater than second: 1 Arguments: first {str} -- A string representing an IP address second {str} -- A string representing an IP address Returns: int
def __compare_ips(first, second): # If the two IPs are the same, return 0 if first == second: return 0 # Create lists from the split of each IP, store them as ints lFirst = [int(i) for i in first.split('.')] lSecond = [int(i) for i in second.split('.')] # Go through each part from left to right until we find the # difference for i in [0, 1, 2, 3]: # If the part of x is greater than the part of y if lFirst[i] > lSecond[i]: return 1 # Else if the part of x is less than the part of y elif lFirst[i] < lSecond[i]: return -1
977,651
Clean Cleans and returns the new value Arguments: value {mixed} -- The value to clean Returns: mixed
def clean(self, value): # If the value is None and it's optional, return as is if value is None and self._optional: return None # If it's an ANY, there is no reasonable expectation that we know what # the value should be, so we return it as is if self._type == 'any': pass # Else if it's a basic string type elif self._type in ['base64', 'ip', 'string', 'uuid']: # And not already a string if not isinstance(value, basestring): value = str(value) # Else if it's a BOOL just check if the value flags as positive elif self._type == 'bool': # If it's specifically a string, it needs to match a specific # pattern to be true if isinstance(value, basestring): value = (value in ('true', 'True', 'TRUE', 't', 'T', 'yes', 'Yes', 'YES', 'y', 'Y', 'x', '1') and True or False); # Else else: value = (value and True or False) # Else if it's a date type elif self._type == 'date': # If it's a python type, use strftime on it if isinstance(value, (datetime.date, datetime.datetime)): value = value.strftime('%Y-%m-%d') # Else if it's already a string elif isinstance(value, basestring): pass # Else convert it to a string else: value = str(value) # Else if it's a datetime type elif self._type == 'datetime': # If it's a python type, use strftime on it if isinstance(value, datetime.datetime): value = value.strftime('%Y-%m-%d %H:%M:%S') elif isinstance(value, datetime.date): value = '%s 00:00:00' % value.strftime('%Y-%m-%d') # Else if it's already a string elif isinstance(value, basestring): pass # Else convert it to a string else: value = str(value) # Else if it's a decimal elif self._type == 'decimal': # If it's not a decimal if not isinstance(value, Decimal): value = Decimal(value) # Convert it to a string value = '{0:f}'.format(value) # Else if it's a float elif self._type == 'float': value = float(value) # Else if it's an int type elif self._type in ['int', 'timestamp', 'uint']: # If the value is a string if isinstance(value, basestring): # If it starts with 0 if value[0] == '0' and len(value) > 1: # If it's followed by X or x, it's hex if value[1] in ['x', 'X'] and len(value) > 2: value = int(value, 16) # Else it's octal else: value = int(value, 8) # Else it's base 10 else: value = int(value) # Else if it's not an int already elif not isinstance(value, int): value = int(value) # Else if it's a JSON type elif self._type == 'json': # If it's already a string if isinstance(value, basestring): pass # Else, encode it else: value = JSON.encode(value) # Else if it's an md5 type elif self._type == 'md5': # If it's a python type, get the hexadecimal digest if isinstance(value, _MD5_TYPE): value = value.hexdigest() # Else if it's a string elif isinstance(value, basestring): pass # Else, try to convert it to a string else: value = str(value) # Else if it's a price type elif self._type == 'price': # If it's not already a Decimal if not isinstance(value, Decimal): value = Decimal(value) # Make sure its got 2 decimal places value = "{0:f}".format(value.quantize(Decimal('1.00'))) # Else if it's a time type elif self._type == 'time': # If it's a python type, use strftime on it if isinstance(value, (datetime.time, datetime.datetime)): value = value.strftime('%H:%M:%S') # Else if it's already a string elif isinstance(value, basestring): pass # Else convert it to a string else: value = str(value) # Else we probably forgot to add a new type else: raise Exception('%s has not been added to .clean()' % self._type) # Return the cleaned value return value
977,652
Min/Max Sets or gets the minimum and/or maximum values for the Node. For getting, returns {"minimum":mixed,"maximum":mixed} Arguments: minimum {mixed} -- The minimum value maximum {mixed} -- The maximum value Raises: TypeError, ValueError Returns: None | dict
def minmax(self, minimum=None, maximum=None): # If neither min or max is set, this is a getter if minimum is None and maximum is None: return {"minimum": self._minimum, "maximum": self._maximum}; # If the minimum is set if minimum != None: # If the current type is a date, datetime, ip, or time if self._type in ['base64', 'date', 'datetime', 'ip', 'time']: # Make sure the value is valid for the type if not isinstance(minimum, basestring) \ or not _typeToRegex[self._type].match(minimum): raise ValueError('__minimum__') # Else if the type is an int (unsigned, timestamp), or a string in # which the min/max are lengths elif self._type in ['int', 'string', 'timestamp', 'uint']: # If the value is not a valid int or long if not isinstance(minimum, (int, long)): # If it's a valid representation of an integer if isinstance(minimum, basestring) \ and _typeToRegex['int'].match(minimum): # Convert it minimum = int(minimum, 0) # Else, raise an error else: raise ValueError('__minimum__') # If the type is meant to be unsigned if self._type in ['base64', 'string', 'timestamp', 'uint']: # And it's below zero if minimum < 0: raise ValueError('__minimum__') # Else if the type is decimal elif self._type == 'decimal': # Store it if it's valid, else throw a ValueError try: minimum = Decimal(minimum) except ValueError: raise ValueError('__minimum__') # Else if the type is float elif self._type == 'float': # Store it if it's valid, else throw a ValueError try: minimum = float(minimum) except ValueError: raise ValueError('__minimum__') # Else if the type is price elif self._type == 'price': # If it's not a valid representation of a price if not isinstance(minimum, basestring) or not _typeToRegex['price'].match(minimum): raise ValueError('__minimum__') # Store it as a Decimal minimum = Decimal(minimum) # Else we can't have a minimum else: raise TypeError('can not set __minimum__ for ' + self._type) # Store the minimum self._minimum = minimum # If the maximum is set if maximum != None: # If the current type is a date, datetime, ip, or time if self._type in ['date', 'datetime', 'ip', 'time']: # Make sure the value is valid for the type if not isinstance(maximum, basestring) \ or not _typeToRegex[self._type].match(maximum): raise ValueError('__maximum__') # Else if the type is an int (unsigned, timestamp), or a string in # which the min/max are lengths elif self._type in ['int', 'string', 'timestamp', 'uint']: # If the value is not a valid int or long if not isinstance(maximum, (int, long)): # If it's a valid representation of an integer if isinstance(maximum, basestring) \ and _typeToRegex['int'].match(maximum): # Convert it maximum = int(maximum, 0) # Else, raise an error else: raise ValueError('__minimum__') # If the type is meant to be unsigned if self._type in ['string', 'timestamp', 'uint']: # And it's below zero if maximum < 0: raise ValueError('__maximum__') # Else if the type is decimal elif self._type == 'decimal': # Store it if it's valid, else throw a ValueError try: maximum = Decimal(maximum) except ValueError: raise ValueError('__maximum__') # Else if the type is float elif self._type == 'float': # Store it if it's valid, else throw a ValueError try: minimum = float(minimum) except ValueError: raise ValueError('__maximum__') # Else if the type is price elif self._type == 'price': # If it's not a valid representation of a price if not isinstance(maximum, basestring) or not _typeToRegex['price'].match(maximum): raise ValueError('__maximum__') # Store it as a Decimal maximum = Decimal(maximum) # Else we can't have a maximum else: raise TypeError('can not set __maximum__ for ' + self._type) # If we also have a minimum if self._minimum is not None: # If the type is an IP if self._type == 'ip': # If the min is above the max, we have a problem if self.__compare_ips(self._minimum, maximum) == 1: raise ValueError('__maximum__') # Else any other data type else: # If the min is above the max, we have a problem if self._minimum > maximum: raise ValueError('__maximum__') # Store the maximum self._maximum = maximum
977,653
Options Sets or gets the list of acceptable values for the Node Arguments: options {list} -- A list of valid values Raises: TypeError, ValueError Returns: None | list
def options(self, options=None): # If opts aren't set, this is a getter if options is None: return self._options # If the options are not a list if not isinstance(options, (list, tuple)): raise ValueError('__options__') # If the type is not one that can have options if self._type not in ['base64', 'date', 'datetime', 'decimal', 'float', \ 'int', 'ip', 'md5', 'price', 'string', 'time', \ 'timestamp', 'uint', 'uuid']: raise TypeError('can not set __options__ for ' + self._type) # Init the list of options to be saved lOpts = [] # Go through each item and make sure it's unique and valid for i in range(len(options)): # Convert the value based on the type # If the type is a string one that we can validate if self._type in ['base64', 'date', 'datetime', 'ip', 'md5', 'time', 'uuid']: # If the value is not a string or doesn't match its regex, raise # an error if not isinstance(options[i], basestring) \ or not _typeToRegex[self._type].match(options[i]): raise ValueError('__options__[%d]' % i) # Else if it's decimal elif self._type == 'decimal': # If it's a Decimal if isinstance(options[i], Decimal): pass # Else if we can't conver it else: try: options[i] = Decimal(options[i]) except ValueError: raise ValueError('__options__[%d]' % i) # Else if it's a float elif self._type == 'float': try: options[i] = float(options[i]) except ValueError: raise ValueError('__options__[%d]' % i) # Else if it's an integer elif self._type in ['int', 'timestamp', 'uint']: # If we don't already have an int if not isinstance(options[i], (int, long)): # And we don't have a string if not isinstance(options[i], basestring): raise ValueError('__options__[%d]' % i) try: options[i] = int(options[i], 0) except ValueError: raise ValueError('__options__[%d]' % i) # If the type is unsigned and negative, raise an error if self._type in ['timestamp', 'uint'] and options[i] < 0: raise ValueError('__options__[' + str(i) + ']') # Else if it's a price elif self._type == 'price': # If it's a Decimal if isinstance(options[i], Decimal): pass # Else if it's not a valid price representation elif not isinstance(options[i], basestring) or not _typeToRegex['price'].match(options[i]): raise ValueError('__options__[%d]' % i) # Store it as a Decimal options[i] = Decimal(options[i]) # Else if the type is a string elif self._type == 'string': # If the value is not a string if not isinstance(options[i], basestring): # If the value can't be turned into a string try: options[i] = str(options[i]) except ValueError: raise ValueError('__options__[%d]' % i) # Else we have no validation for the type else: raise TypeError('can not set __options__ for ' + self._type) # If it's already in the list, raise an error if options[i] in lOpts: sys.stderr.write('__options__[' + str(i) + '] is a duplicate') # Store the option else: lOpts.append(options[i]) # Store the list of options self._options = lOpts
977,654
Regex Sets or gets the regular expression used to validate the Node Arguments: regex {str} -- A standard regular expression string Raises: ValueError Returns: None | str
def regex(self, regex = None): # If regex was not set, this is a getter if regex is None: return self._regex # If the type is not a string if self._type != 'string': sys.stderr.write('can not set __regex__ for %s' % self._type) return # If it's not a valid string or regex if not isinstance(regex, (basestring, _REGEX_TYPE)): raise ValueError('__regex__') # Store the regex self._regex = regex
977,655
Valid Checks if a value is valid based on the instance's values Arguments: value {mixed} -- The value to validate Returns: bool
def valid(self, value, level=[]): # Reset validation failures self.validation_failures = [] # If the value is None and it's optional, we're good if value is None and self._optional: return True # If we are validating an ANY field, immediately return true if self._type == 'any': pass # If we are validating a DATE, DATETIME, IP or TIME data point elif self._type in ['base64', 'date', 'datetime', 'ip', 'md5', 'time', 'uuid']: # If it's a date or datetime type and the value is a python type if self._type == 'date' and isinstance(value, (datetime.date, datetime.datetime)): value = value.strftime('%Y-%m-%d') elif self._type == 'datetime' and isinstance(value, (datetime.date, datetime.datetime)): if isinstance(value, datetime.datetime): value = value.strftime('%Y-%m-%d %H:%M:%S') elif isinstance(value, datetime.date): value = '%s 00:00:00' % value.strftime('%Y-%m-%d') # If it's a time type and the value is a python type elif self._type == 'time' and isinstance(value, (datetime.time, datetime.datetime)): value = value.strftime('%H:%M:%S') # Else if the type is md5 and the value is a python type elif self._type == 'md5' and isinstance(value, _MD5_TYPE): value = value.hexdigest() # If the value is not a string elif not isinstance(value, basestring): self.validation_failures.append(('.'.join(level), 'not a string')) return False # If there's no match if not _typeToRegex[self._type].match(value): self.validation_failures.append(('.'.join(level), 'failed regex (internal)')) return False # If we are checking an IP if self._type == 'ip': # If there's a min or a max if self._minimum is not None or self._maximum is not None: # If the IP is greater than the maximum if self._maximum is not None and self.__compare_ips(value, self._maximum) == 1: self.validation_failures.append(('.'.join(level), 'exceeds maximum')) return False # If the IP is less than the minimum if self._minimum is not None and self.__compare_ips(value, self._minimum) == -1: self.validation_failures.append(('.'.join(level), 'did not meet minimum')) return False # Return OK return True # Else if we are validating some sort of integer elif self._type in ['int', 'timestamp', 'uint']: # If the type is a bool, fail immediately if type(value) == bool: self.validation_failures.append(('.'.join(level), 'is a bool')) return False # If it's not an int if not isinstance(value, (int, long)): # And it's a valid representation of an int if isinstance(value, basestring) \ and _typeToRegex['int'].match(value): # If it starts with 0 if value[0] == '0' and len(value) > 1: # If it's followed by X or x, it's hex if value[1] in ['x', 'X'] and len(value) > 2: value = int(value, 16) # Else it's octal else: value = int(value, 8) # Else it's base 10 else: value = int(value) # Else, return false else: self.validation_failures.append(('.'.join(level), 'not an integer')) return False # If it's not signed if self._type in ['timestamp', 'uint']: # If the value is below 0 if value < 0: self.validation_failures.append(('.'.join(level), 'signed')) return False # Else if we are validating a bool elif self._type == 'bool': # If it's already a bool if isinstance(value, bool): return True # If it's an int or long at 0 or 1 if isinstance(value, (int, long)) and value in [0, 1]: return True # Else if it's a string elif isinstance(value, basestring): # If it's t, T, 1, f, F, or 0 if value in ['true', 'True', 'TRUE', 't', 'T', '1', 'false', 'False', 'FALSE', 'f', 'F', '0']: return True else: self.validation_failures.append(('.'.join(level), 'not a valid string representation of a bool')) return False # Else it's no valid type else: self.validation_failures.append(('.'.join(level), 'not valid bool replacement')) return False # Else if we are validating a decimal value elif self._type == 'decimal': # If the type is a bool, fail immediately if type(value) == bool: self.validation_failures.append(('.'.join(level), 'is a bool')) return False # If it's already a Decimal if isinstance(value, Decimal): pass # Else if we fail to convert the value else: try: value = Decimal(value) except (DecimalInvalid, TypeError, ValueError): self.validation_failures.append(('.'.join(level), 'can not be converted to decimal')) return False # Else if we are validating a floating point value elif self._type == 'float': # If the type is a bool, fail immediately if type(value) == bool: self.validation_failures.append(('.'.join(level), 'is a bool')) return False # If it's already a float if isinstance(value, float): pass # Else if we fail to convert the value else: try: value = float(value) except (ValueError, TypeError): self.validation_failures.append(('.'.join(level), 'can not be converted to float')) return False # Else if we are validating a JSON string elif self._type == 'json': # If it's already a string if isinstance(value, basestring): # Try to decode it try: value = JSON.decode(value) return True except ValueError: self.validation_failures.append(('.'.join(level), 'Can not be decoded from JSON')) return False # Else else: # Try to encode it try: value = JSON.encode(value) return True except (ValueError, TypeError): self.validation_failures.append(('.'.join(level), 'Can not be encoded to JSON')) return False # Else if we are validating a price value elif self._type == 'price': # If the type is a bool, fail immediately if type(value) == bool: self.validation_failures.append(('.'.join(level), 'is a bool')) return False # If it's not a floating point value if not isinstance(value, Decimal): # But it is a valid string representing a price, or a float if isinstance(value, (basestring, float)) \ and _typeToRegex['price'].match(str(value)): # Convert it to a decimal value = Decimal(value).quantize(Decimal('1.00')) # Else if it's an int elif isinstance(value, int): # Convert it to decimal value = Decimal(str(value) + '.00') # Else whatever it is is no good else: self.validation_failures.append(('.'.join(level), 'failed regex (internal)')) return False # Else else: # If the exponent is longer than 2 if abs(value.as_tuple().exponent) > 2: self.validation_failures.append(('.'.join(level), 'too many decimal points')) return False # Else if we are validating a string value elif self._type == 'string': # If the value is not some form of string if not isinstance(value, basestring): self.validation_failures.append(('.'.join(level), 'is not a string')) return False # If we have a regex if self._regex: # If it doesn't match the regex if re.match(self._regex, value) == None: self.validation_failures.append(('.'.join(level), 'failed regex (custom)')) return False # Else elif self._minimum or self._maximum: # If there's a minimum length and we don't reach it if self._minimum and len(value) < self._minimum: self.validation_failures.append(('.'.join(level), 'not long enough')) return False # If there's a maximum length and we surpass it if self._maximum and len(value) > self._maximum: self.validation_failures.append(('.'.join(level), 'too long')) return False # Return OK return True # If there's a list of options if self._options is not None: # Returns based on the option's existance if value not in self._options: self.validation_failures.append(('.'.join(level), 'not in options')) return False else: return True # Else check for basic min/max else: # If the value is less than the minimum if self._minimum and value < self._minimum: self.validation_failures.append(('.'.join(level), 'did not meet minimum')) return False # If the value is greater than the maximum if self._maximum and value > self._maximum: self.validation_failures.append(('.'.join(level), 'exceeds maximum')) return False # Value has no issues return True
977,657
Constructor Initialises the instance Arguments: details {dict} -- Details describing the type of values allowed for the node Raises: ValueError Returns: OptionsNode
def __init__(self, details): # If details is not a list instance if not isinstance(details, list): raise ValueError('details in ' + self.__class__.__name__ + '.' + sys._getframe().f_code.co_name + ' must be a list') # Init the variable used to identify the last falures in validation self.validation_failures = {} # Init the optional flag, assume all nodes are optional until we find # one that isn't self._optional = True # Init the internal list self._nodes = [] # Go through each element in the list for i in range(len(details)): # If it's another Node instance if isinstance(details[i], _BaseNode): self._nodes.append(details[i]) continue # If the element is a dict instance elif isinstance(details[i], (dict, list)): # Store the child self._nodes.append(_child(details[i])) # Whatever was sent is invalid else: raise ValueError('details[' + str(i) + '] in ' + self.__class__.__name__ + '.' + sys._getframe().f_code.co_name + ' must be a dict') # If the element is not optional, then the entire object can't be # optional if not self._nodes[-1]._optional: self._optional = False
977,658
Clean Uses the valid method to check which type the value is, and then calls the correct version of clean on that node Arguments: value {mixed} -- The value to clean Returns: mixed
def clean(self, value): # If the value is None and it's optional, return as is if value is None and self._optional: return None # Go through each of the nodes for i in range(len(self._nodes)): # If it's valid if self._nodes[i].valid(value): # Use it's clean return self._nodes[i].clean(value) # Something went wrong raise ValueError('value', value)
977,659
Valid Checks if a value is valid based on the instance's values Arguments: value {mixed} -- The value to validate Returns: bool
def valid(self, value, level=[]): # Reset validation failures self.validation_failures = [] # If the value is None and it's optional, we're good if value is None and self._optional: return True # Go through each of the nodes for i in range(len(self._nodes)): # If it's valid if self._nodes[i].valid(value): # Return OK return True # Not valid for anything self.validation_failures.append(('.'.join(level), 'no valid option')) return False
977,660
Get Item (__getitem__) Returns a specific key from the parent Arguments: key {str} -- The key to get Raises: KeyError Returns: mixed
def __getitem__(self, key): if key in self._nodes: return self._nodes[key] else: raise KeyError(key)
977,661
Constructor Initialises the instance Arguments: details {dict} -- Details describing the type of values allowed for the node Raises: ValueError Returns: Parent
def __init__(self, details): # If details is not a dict instance if not isinstance(details, dict): raise ValueError('details in ' + self.__class__.__name__ + '.' + sys._getframe().f_code.co_name + ' must be a dict') # Init the nodes and requires dicts self._nodes = {} self._requires = {} # Go through the keys in the details for k in tuple(details.keys()): # If key is standard if _standardField.match(k): # If it's a Node if isinstance(details[k], _NodeInterface): # Store it as is self._nodes[k] = details[k] # Else else: self._nodes[k] = _child(details[k]) # Remove the key from the details del details[k] # If there's a require hash available if '__require__' in details: self.requires(details['__require__']) del details['__require__'] # Call the parent constructor with whatever details are left super(Parent, self).__init__(details, 'Parent')
977,662
Clean Goes through each of the values in the dict, cleans it, stores it, and returns a new dict Arguments: value {dict} -- The value to clean Returns: dict
def clean(self, value): # If the value is None and it's optional, return as is if value is None and self._optional: return None # If the value is not a dict if not isinstance(value, dict): raise ValueError('value') # Init the return value dRet = {} # Go through each value and clean it using the associated node for k in value.keys(): try: dRet[k] = self._nodes[k].clean(value[k]) except KeyError: raise ValueError('%s is not a valid node in the parent' % k) # Return the cleaned values return dRet
977,664
Get Returns the node of a specific key from the parent Arguments: key {str} -- The key to get default {mixed} Value to return if the key does not exist Returns: mixed
def get(self, key, default=None): if key in self._nodes: return self._nodes[key] else: return default
977,665
Requires Sets the require rules used to validate the Parent Arguments: require {dict} -- A dictionary expressing requirements of fields Raises: ValueError Returns: None
def requires(self, require=None): # If require is None, this is a getter if require is None: return self._requires # If it's not a valid dict if not isinstance(require, dict): raise ValueError('__require__') # Go through each key and make sure it goes with a field for k,v in iteritems(require): # If the field doesn't exist if k not in self._nodes: raise ValueError('__require__[%s]' % str(k)) # If the value is a string if isinstance(v, basestring): v = [v] # Else if it's not a list type elif not isinstance(v, (tuple,list)): raise ValueError('__require__[%s]' % str(k)) # Make sure each required field also exists for s in v: if s not in self._nodes: raise ValueError('__require__[%s]: %s' % (str(k), str(v))) # If it's all good self._requires[k] = v
977,667
Valid Checks if a value is valid based on the instance's values Arguments: value {mixed} -- The value to validate Returns: bool
def valid(self, value, level=[]): # Reset validation failures self.validation_failures = [] # If the value is None and it's optional, we're good if value is None and self._optional: return True # If the value isn't a dictionary if not isinstance(value, dict): self.validation_failures.append(('.'.join(level), str(value))) return False # Init the return, assume valid bRet = True # Go through each node in the instance for k in self._nodes: # Add the field to the level lLevel = level[:] lLevel.append(k) # If we are missing a node if k not in value: # If the value is not optional if not self._nodes[k]._optional: self.validation_failures.append(('.'.join(lLevel), 'missing')) bRet = False # Continue to next node continue # If the element isn't valid, return false if not self._nodes[k].valid(value[k], lLevel): self.validation_failures.extend(self._nodes[k].validation_failures) bRet = False continue # If the element requires others if k in self._requires: # Go through each required field for f in self._requires[k]: # If the field doesn't exist in the value if f not in value or value[f] in ('0000-00-00','',None): self.validation_failures.append(('.'.join(lLevel), 'requires \'%s\' to also be set' % str(f))) bRet = False # Return whatever the result was return bRet
977,669
Constructor Initialises the instance Arguments: details {dict} -- Details describing the type of values allowed for the node Raises: KeyError ValueError Returns: Tree
def __init__(self, details): # If details is not a dict instance if not isinstance(details, dict): raise ValueError('details in ' + self.__class__.__name__ + '.' + sys._getframe().f_code.co_name + ' must be a dict') # If the name is not set if '__name__' not in details: raise KeyError('__name__') # If the name is not valid if not _standardField.match(details['__name__']): raise ValueError('__name__') # Store the name then delete it self._name = details['__name__'] del details['__name__'] # If for some reason the array flag is set, remove it if '__array__' in details: del details['__array__'] # Call the parent constructor super(Tree, self).__init__(details) # Overwrite classname self._class = 'Tree'
977,671
Valid Checks if a value is valid based on the instance's values Arguments: value {mixed} -- The value to validate include_name {bool} -- If true, Tree's name will be prepended to all error keys Returns: bool
def valid(self, value, include_name=True): # Call the parent valid method and return the result return super(Tree, self).valid(value, include_name and [self._name] or [])
977,673
Download the data from source url, unless it's already here. Args: filename: string, name of the file in the directory. work_directory: string, path to working directory. source_url: url to download from if file doesn't exist. Returns: Path to resulting file.
def maybe_download(self, filename, work_directory, source_url): if not os.path.exists(work_directory): os.makedirs(work_directory) filepath = os.path.join(work_directory, filename) if not os.path.exists(filepath): temp_file_name, _ = urllib.request.urlretrieve(source_url) copyfile(temp_file_name, filepath) print('Successfully downloaded', filename) return filepath
978,185
Extract the images into a 4D uint8 numpy array [index, y, x, depth]. Args: f: A file object that can be passed into a gzip reader. Returns: data: A 4D unit8 numpy array [index, y, x, depth]. Raises: ValueError: If the bytestream does not start with 2051.
def extract_images(self, f): print('Extracting', f.name) with gzip.GzipFile(fileobj=f) as bytestream: magic = self._read32(bytestream) if magic != 2051: raise ValueError('Invalid magic number %d in MNIST image file: %s' % (magic, f.name)) num_images = self._read32(bytestream) rows = self._read32(bytestream) cols = self._read32(bytestream) buf = bytestream.read(rows * cols * num_images) data = np.frombuffer(buf, dtype=np.uint8) data = data.reshape(num_images, rows, cols, 1) return data
978,186