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 fo...
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 k...
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, ...
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 i...
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 decryp...
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...
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 followin...
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 call...
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 ...
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() ...
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 certificate...
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()) ret...
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 o...
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...
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 (b...
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, aut...
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...
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, pipel...
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...
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 ne...
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...
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: ...
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:...
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) # Re...
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_...
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 `...
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: isin...
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...
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) ...
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...
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, MongoL...
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: ...
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 [[1...
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 example...
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:...
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"] db...
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, '...
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('{}.{}: ...
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, y...
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 r...
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 _d...
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 se...
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, ...
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 ...
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. ...
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 ...
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``. WordNotFoun...
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 - ...
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) wil...
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...
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-likelih...
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....
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) contai...
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_pr...
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 compo...
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...
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[...
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 ...
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. Retu...
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 wi...
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 ...
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 are...
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: a...
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(), ...
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' ' ...
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) ...
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._di...
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 cha...
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 indica...
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 ...
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...
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(v...
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 " "configura...
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_templat...
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, k...
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 ...
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 ...
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.validat...
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):...
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(...
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 detail...
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...
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(('.'...
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 detai...
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: ...
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 unt...
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 ...
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...
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...
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(re...
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 a...
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_fail...
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(va...
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]...
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 throu...
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 t...
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): ...
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(('.'...
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__') ...
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 fi...
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(so...
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' % ...
978,186