Search is not available for this dataset
text
stringlengths
75
104k
def save_game(self): """ save_game() asks the underlying game object (_g) to dump the contents of itself as JSON and then returns the JSON to :return: A JSON representation of the game object """ logging.debug("save_game called.") logging.debug("Validating game object") self._validate_game_object(op="save_game") logging.debug("Dumping JSON from GameObject") return self._g.to_json()
def guess(self, *args): """ guess() allows a guess to be made. Before the guess is made, the method checks to see if the game has been won, lost, or there are no tries remaining. It then creates a return object stating the number of bulls (direct matches), cows (indirect matches), an analysis of the guess (a list of analysis objects), and a status. :param args: any number of integers (or string representations of integers) to the number of Digits in the answer; i.e. in normal mode, there would be a DigitWord to guess of 4 digits, so guess would expect guess(1, 2, 3, 4) and a shorter (guess(1, 2)) or longer (guess(1, 2, 3, 4, 5)) sequence will raise an exception. :return: a JSON object containing the analysis of the guess: { "cows": {"type": "integer"}, "bulls": {"type": "integer"}, "analysis": {"type": "array of DigitWordAnalysis"}, "status": {"type": "string"} } """ logging.debug("guess called.") logging.debug("Validating game object") self._validate_game_object(op="guess") logging.debug("Building return object") _return_results = { "cows": None, "bulls": None, "analysis": [], "status": "" } logging.debug("Check if game already won, lost, or too many tries.") if self._g.status.lower() == "won": _return_results["message"] = self._start_again("You already won!") elif self._g.status.lower() == "lost": _return_results["message"] = self._start_again("You have made too many guesses_allowed, you lost!") elif self._g.guesses_remaining < 1: _return_results["message"] = self._start_again("You have run out of tries, sorry!") elif self._g.ttl < time(): _return_results["message"] = self._start_again("Sorry, you ran out of time to complete the puzzle!") else: logging.debug("Creating a DigitWord for the guess.") _wordtype = DigitWord.HEXDIGIT if self._g.mode.lower() == 'hex' else DigitWord.DIGIT guess = DigitWord(*args, wordtype=_wordtype) logging.debug("Validating guess.") self._g.guesses_remaining -= 1 self._g.guesses_made += 1 logging.debug("Initializing return object.") _return_results["analysis"] = [] _return_results["cows"] = 0 _return_results["bulls"] = 0 logging.debug("Asking the underlying GameObject to compare itself to the guess.") for i in self._g.answer.compare(guess): logging.debug("Iteration of guesses_allowed. Processing guess {}".format(i.index)) if i.match is True: logging.debug("Bull found. +1") _return_results["bulls"] += 1 elif i.in_word is True: logging.debug("Cow found. +1") _return_results["cows"] += 1 logging.debug("Add analysis to return object") _return_results["analysis"].append(i.get_object()) logging.debug("Checking if game won or lost.") if _return_results["bulls"] == len(self._g.answer.word): logging.debug("Game was won.") self._g.status = "won" self._g.guesses_remaining = 0 _return_results["message"] = "Well done! You won the game with your " \ "answers {}".format(self._get_text_answer()) elif self._g.guesses_remaining < 1: logging.debug("Game was lost.") self._g.status = "lost" _return_results["message"] = "Sorry, you lost! The correct answer was " \ "{}".format(self._get_text_answer()) _return_results["status"] = self._g.status logging.debug("Returning results.") return _return_results
def _start_again(self, message=None): """Simple method to form a start again message and give the answer in readable form.""" logging.debug("Start again message delivered: {}".format(message)) the_answer = self._get_text_answer() return "{0} The correct answer was {1}. Please start a new game.".format( message, the_answer )
def _validate_game_object(self, op="unknown"): """ A helper method to provide validation of the game object (_g). If the game object does not exist or if (for any reason) the object is not a GameObject, then an exception will be raised. :param op: A string describing the operation (e.g. guess, save, etc.) taking place :return: Nothing """ if self._g is None: raise ValueError( "Game must be instantiated properly before using - call new_game() " "or load_game(jsonstr='{...}')" ) if not isinstance(self._g, GameObject): raise TypeError( "Unexpected error during {0}! GameObject (_g) is not a GameObject!".format(op) )
def extra_context(request): """Adds useful global items to the context for use in templates. * *request*: the request object * *HOST*: host name of server * *IN_ADMIN*: True if you are in the django admin area """ host = os.environ.get('DJANGO_LIVE_TEST_SERVER_ADDRESS', None) \ or request.get_host() d = { 'request':request, 'HOST':host, 'IN_ADMIN':request.path.startswith('/admin/'), } return d
def fft(values, freq=None, timestamps=None, fill_missing=False): """ Adds options to :func:`scipy.fftpack.rfft`: * *freq* is the frequency the samples were taken at * *timestamps* is the time the samples were taken, to help with filling in missing data if *fill_missing* is true """ # ====================================== # Get frequency # ====================================== if freq is None: from .. import qt freq = qt.getDouble(title='Fourier Analysis', text='Frequency samples taken at:', min=0, decimals=2, value=1.0) freq = freq.input if fill_missing: (t_x, x_filled) = fill_missing_timestamps(timestamps, values) else: x_filled = values num_samples = _np.size(x_filled) xfft = _sp.fftpack.rfft(x_filled) factor = freq/num_samples num_fft = _np.size(xfft) f = factor * _np.linspace(1, num_fft, num_fft) xpow = _np.abs(xfft*_np.conj(xfft)) # ====================================== # No DC term # ====================================== xpow = xpow[1:] f = f[1:] return (f, xpow)
def create(self, server): """Create the challenge on the server""" return server.post( 'challenge_admin', self.as_payload(), replacements={'slug': self.slug})
def update(self, server): """Update existing challenge on the server""" return server.put( 'challenge_admin', self.as_payload(), replacements={'slug': self.slug})
def exists(self, server): """Check if a challenge exists on the server""" try: server.get( 'challenge', replacements={'slug': self.slug}) except Exception: return False return True
def from_server(cls, server, slug): """Retrieve a challenge from the MapRoulette server :type server """ challenge = server.get( 'challenge', replacements={'slug': slug}) return cls( **challenge)
def django_logging_dict(log_dir, handlers=['file'], filename='debug.log'): """Extends :func:`logthing.utils.default_logging_dict` with django specific values. """ d = default_logging_dict(log_dir, handlers, filename) d['handlers'].update({ 'mail_admins':{ 'level':'ERROR', 'class':'django.utils.log.AdminEmailHandler', } }) d['loggers'].update({ 'django.db.backends': { # stop SQL debug from going to main logger 'handlers': ['file', 'mail_admins'], 'level': 'ERROR', 'propagate': False, }, 'django.request': { 'handlers': ['file', 'mail_admins'], 'level': 'ERROR', 'propagate': False, }, }) return d
def get_position(self, position_id): """ Returns position data. http://dev.wheniwork.com/#get-existing-position """ url = "/2/positions/%s" % position_id return self.position_from_json(self._get_resource(url)["position"])
def get_positions(self): """ Returns a list of positions. http://dev.wheniwork.com/#listing-positions """ url = "/2/positions" data = self._get_resource(url) positions = [] for entry in data['positions']: positions.append(self.position_from_json(entry)) return positions
def create_position(self, params={}): """ Creates a position http://dev.wheniwork.com/#create-update-position """ url = "/2/positions/" body = params data = self._post_resource(url, body) return self.position_from_json(data["position"])
def print2elog(author='', title='', text='', link=None, file=None, now=None): """ Prints to the elog. Parameters ---------- author : str, optional Author of the elog. title : str, optional Title of the elog. link : str, optional Path to a thumbnail. file : str, optional Path to a file. now : :class:`datetime.datetime` Time of the elog. """ # ============================ # Get current time # ============================ if now is None: now = _dt.datetime.now() fulltime = now.strftime('%Y-%m-%dT%H:%M:%S-00') # ============================ # Copy files # ============================ if not ((link is None) ^ (file is None)): link_copied = _copy_file(link, fulltime) file_copied = _copy_file(file, fulltime) else: raise ValueError('Need both file and its thumbnail!') # ============================ # Jinja templating # ============================ loader = _jj.PackageLoader('pytools.facettools', 'resources/templates') env = _jj.Environment(loader=loader, trim_blocks=True) template = env.get_template('facetelog.xml') stream = template.stream(author=author, title=title, text=text, link=link_copied, file=file_copied, now=now) # ============================ # Write xml # ============================ with _tempfile.TemporaryDirectory() as dirname: filename = '{}.xml'.format(fulltime) filepath = _os.path.join(dirname, filename) with open(filepath, 'w+') as fid: # stream.disable_buffering() stream.dump(fid) finalpath = _os.path.join(basedir, filename) # _shutil.copyfile(filepath, 'new.xml') _shutil.copyfile(filepath, finalpath)
def fopen(name, mode='r', buffering=-1): """Similar to Python's built-in `open()` function.""" f = _fopen(name, mode, buffering) return _FileObjectThreadWithContext(f, mode, buffering)
def sloccount(): '''Print "Source Lines of Code" and export to file. Export is hudson_ plugin_ compatible: sloccount.sc requirements: - sloccount_ should be installed. - tee and pipes are used options.paved.pycheck.sloccount.param .. _sloccount: http://www.dwheeler.com/sloccount/ .. _hudson: http://hudson-ci.org/ .. _plugin: http://wiki.hudson-ci.org/display/HUDSON/SLOCCount+Plugin ''' # filter out subpackages setup = options.get('setup') packages = options.get('packages') if setup else None if packages: dirs = [x for x in packages if '.' not in x] else: dirs = ['.'] # sloccount has strange behaviour with directories, # can cause exception in hudson sloccount plugin. # Better to call it with file list ls=[] for d in dirs: ls += list(path(d).walkfiles()) #ls=list(set(ls)) files=' '.join(ls) param=options.paved.pycheck.sloccount.param sh('sloccount {param} {files} | tee sloccount.sc'.format(param=param, files=files))
def pyflakes(): '''passive check of python programs by pyflakes. requirements: - pyflakes_ should be installed. ``easy_install pyflakes`` options.paved.pycheck.pyflakes.param .. _pyflakes: http://pypi.python.org/pypi/pyflakes ''' # filter out subpackages packages = [x for x in options.setup.packages if '.' not in x] sh('pyflakes {param} {files}'.format(param=options.paved.pycheck.pyflakes.param, files=' '.join(packages)))
def gaussian(x, mu, sigma): """ Gaussian function of the form :math:`\\frac{1}{\\sqrt{2 \\pi}\\sigma} e^{-\\frac{(x-\\mu)^2}{2\\sigma^2}}`. .. versionadded:: 1.5 Parameters ---------- x : float Function variable :math:`x`. mu : float Mean of the Gaussian function. sigma : float Standard deviation of the Gaussian function. """ return _np.exp(-(x-mu)**2/(2*sigma**2)) / (_np.sqrt(2*_np.pi) * sigma)
def http_exception_error_handler( exception): """ Handle HTTP exception :param werkzeug.exceptions.HTTPException exception: Raised exception A response is returned, as formatted by the :py:func:`response` function. """ assert issubclass(type(exception), HTTPException), type(exception) assert hasattr(exception, "code") assert hasattr(exception, "description") return response(exception.code, exception.description)
def is_colour(value): """Returns True if the value given is a valid CSS colour, i.e. matches one of the regular expressions in the module or is in the list of predetefined values by the browser. """ global PREDEFINED, HEX_MATCH, RGB_MATCH, RGBA_MATCH, HSL_MATCH, HSLA_MATCH value = value.strip() # hex match if HEX_MATCH.match(value) or RGB_MATCH.match(value) or \ RGBA_MATCH.match(value) or HSL_MATCH.match(value) or \ HSLA_MATCH.match(value) or value in PREDEFINED: return True return False
def format_time(seconds): """Formats time as the string "HH:MM:SS".""" timedelta = datetime.timedelta(seconds=int(seconds)) mm, ss = divmod(timedelta.seconds, 60) if mm < 60: return "%02d:%02d" % (mm, ss) hh, mm = divmod(mm, 60) if hh < 24: return "%02d:%02d:%02d" % (hh, mm, ss) dd, hh = divmod(mm, 24) return "%d days %02d:%02d:%02d" % (dd, hh, mm, ss)
def frictional_resistance_coef(length, speed, **kwargs): """ Flat plate frictional resistance of the ship according to ITTC formula. ref: https://ittc.info/media/2021/75-02-02-02.pdf :param length: metres length of the vehicle :param speed: m/s speed of the vehicle :param kwargs: optional could take in temperature to take account change of water property :return: Frictional resistance coefficient of the vehicle """ Cf = 0.075 / (np.log10(reynolds_number(length, speed, **kwargs)) - 2) ** 2 return Cf
def reynolds_number(length, speed, temperature=25): """ Reynold number utility function that return Reynold number for vehicle at specific length and speed. Optionally, it can also take account of temperature effect of sea water. Kinematic viscosity from: http://web.mit.edu/seawater/2017_MIT_Seawater_Property_Tables_r2.pdf :param length: metres length of the vehicle :param speed: m/s speed of the vehicle :param temperature: degree C :return: Reynolds number of the vehicle (dimensionless) """ kinematic_viscosity = interpolate.interp1d([0, 10, 20, 25, 30, 40], np.array([18.54, 13.60, 10.50, 9.37, 8.42, 6.95]) / 10 ** 7) # Data from http://web.mit.edu/seawater/2017_MIT_Seawater_Property_Tables_r2.pdf Re = length * speed / kinematic_viscosity(temperature) return Re
def froude_number(speed, length): """ Froude number utility function that return Froude number for vehicle at specific length and speed. :param speed: m/s speed of the vehicle :param length: metres length of the vehicle :return: Froude number of the vehicle (dimensionless) """ g = 9.80665 # conventional standard value m/s^2 Fr = speed / np.sqrt(g * length) return Fr
def residual_resistance_coef(slenderness, prismatic_coef, froude_number): """ Residual resistance coefficient estimation from slenderness function, prismatic coefficient and Froude number. :param slenderness: Slenderness coefficient dimensionless :math:`L/(βˆ‡^{1/3})` where L is length of ship, βˆ‡ is displacement :param prismatic_coef: Prismatic coefficient dimensionless :math:`βˆ‡/(L\cdot A_m)` where L is length of ship, βˆ‡ is displacement Am is midsection area of the ship :param froude_number: Froude number of the ship dimensionless :return: Residual resistance of the ship """ Cr = cr(slenderness, prismatic_coef, froude_number) if math.isnan(Cr): Cr = cr_nearest(slenderness, prismatic_coef, froude_number) # if Froude number is out of interpolation range, nearest extrapolation is used return Cr
def dimension(self, length, draught, beam, speed, slenderness_coefficient, prismatic_coefficient): """ Assign values for the main dimension of a ship. :param length: metres length of the vehicle :param draught: metres draught of the vehicle :param beam: metres beam of the vehicle :param speed: m/s speed of the vehicle :param slenderness_coefficient: Slenderness coefficient dimensionless :math:`L/(βˆ‡^{1/3})` where L is length of ship, βˆ‡ is displacement :param prismatic_coefficient: Prismatic coefficient dimensionless :math:`βˆ‡/(L\cdot A_m)` where L is length of ship, βˆ‡ is displacement Am is midsection area of the ship """ self.length = length self.draught = draught self.beam = beam self.speed = speed self.slenderness_coefficient = slenderness_coefficient self.prismatic_coefficient = prismatic_coefficient self.displacement = (self.length / self.slenderness_coefficient) ** 3 self.surface_area = 1.025 * (1.7 * self.length * self.draught + self.displacement / self.draught)
def resistance(self): """ Return resistance of the vehicle. :return: newton the resistance of the ship """ self.total_resistance_coef = frictional_resistance_coef(self.length, self.speed) + \ residual_resistance_coef(self.slenderness_coefficient, self.prismatic_coefficient, froude_number(self.speed, self.length)) RT = 1 / 2 * self.total_resistance_coef * 1025 * self.surface_area * self.speed ** 2 return RT
def maximum_deck_area(self, water_plane_coef=0.88): """ Return the maximum deck area of the ship :param water_plane_coef: optional water plane coefficient :return: Area of the deck """ AD = self.beam * self.length * water_plane_coef return AD
def prop_power(self, propulsion_eff=0.7, sea_margin=0.2): """ Total propulsion power of the ship. :param propulsion_eff: Shaft efficiency of the ship :param sea_margin: Sea margin take account of interaction between ship and the sea, e.g. wave :return: Watts shaft propulsion power of the ship """ PP = (1 + sea_margin) * self.resistance() * self.speed/propulsion_eff return PP
def axesfontsize(ax, fontsize): """ Change the font size for the title, x and y labels, and x and y tick labels for axis *ax* to *fontsize*. """ items = ([ax.title, ax.xaxis.label, ax.yaxis.label] + ax.get_xticklabels() + ax.get_yticklabels()) for item in items: item.set_fontsize(fontsize)
def less_labels(ax, x_fraction=0.5, y_fraction=0.5): """ Scale the number of tick labels in x and y by *x_fraction* and *y_fraction* respectively. """ nbins = _np.size(ax.get_xticklabels()) ax.locator_params(nbins=_np.floor(nbins*x_fraction), axis='x') nbins = _np.size(ax.get_yticklabels()) ax.locator_params(nbins=_np.floor(nbins*y_fraction), axis='y')
def configure(self, url=None, token=None, test=False): """ Configure the api to use given url and token or to get them from the Config. """ if url is None: url = Config.get_value("url") if token is None: token = Config.get_value("token") self.server_url = url self.auth_header = {"Authorization": "Basic {0}".format(token)} self.configured = True if test: self.test_connection() Config.set("url", url) Config.set("token", token)
def send_zip(self, exercise, file, params): """ Send zipfile to TMC for given exercise """ resp = self.post( exercise.return_url, params=params, files={ "submission[file]": ('submission.zip', file) }, data={ "commit": "Submit" } ) return self._to_json(resp)
def _make_url(self, slug): """ Ensures that the request url is valid. Sometimes we have URLs that the server gives that are preformatted, sometimes we need to form our own. """ if slug.startswith("http"): return slug return "{0}{1}".format(self.server_url, slug)
def _do_request(self, method, slug, **kwargs): """ Does HTTP request sending / response validation. Prevents RequestExceptions from propagating """ # ensure we are configured if not self.configured: self.configure() url = self._make_url(slug) # 'defaults' are values associated with every request. # following will make values in kwargs override them. defaults = {"headers": self.auth_header, "params": self.params} for item in defaults.keys(): # override default's value with kwargs's one if existing. kwargs[item] = dict(defaults[item], **(kwargs.get(item, {}))) # request() can raise connectivity related exceptions. # raise_for_status raises an exception ONLY if the response # status_code is "not-OK" i.e 4XX, 5XX.. # # All of these inherit from RequestException # which is "translated" into an APIError. try: resp = request(method, url, **kwargs) resp.raise_for_status() except RequestException as e: reason = "HTTP {0} request to {1} failed: {2}" raise APIError(reason.format(method, url, repr(e))) return resp
def _to_json(self, resp): """ Extract json from a response. Assumes response is valid otherwise. Internal use only. """ try: json = resp.json() except ValueError as e: reason = "TMC Server did not send valid JSON: {0}" raise APIError(reason.format(repr(e))) return json
def _normalize_instancemethod(instance_method): """ wraps(instancemethod) returns a function, not an instancemethod so its repr() is all messed up; we want the original repr to show up in the logs, therefore we do this trick """ if not hasattr(instance_method, 'im_self'): return instance_method def _func(*args, **kwargs): return instance_method(*args, **kwargs) _func.__name__ = repr(instance_method) return _func
def safe_joinall(greenlets, timeout=None, raise_error=False): """ Wrapper for gevent.joinall if the greenlet that waits for the joins is killed, it kills all the greenlets it joins for. """ greenlets = list(greenlets) try: gevent.joinall(greenlets, timeout=timeout, raise_error=raise_error) except gevent.GreenletExit: [greenlet.kill() for greenlet in greenlets if not greenlet.ready()] raise return greenlets
def imshow_batch(images, cbar=True, show=True, pdf=None, figsize=(16, 12), rows=2, columns=2, cmap=None, **kwargs): """ Plots an array of *images* to a single window of size *figsize* with *rows* and *columns*. * *cmap*: Specifies color map * *cbar*: Add color bars * *show*: If false, dismisses each window after it is created and optionally saved * *pdf*: Save to a pdf of filename *pdf* * *\*\*kwargs* passed to :class:`matplotlib.axis.imshow` """ # ====================================== # Set up grid # ====================================== images = _np.array(images) gs = _gridspec.GridSpec(rows, columns) num_imgs = images.shape[0] max_ind = num_imgs-1 # ====================================== # Split into pages # ====================================== per_page = rows*columns num_pages = _np.int(_np.ceil(num_imgs/per_page)) fig_array = _np.empty(shape=num_pages, dtype=object) if num_pages > 1: logger.info('Multiple pages necessary') if pdf is not None: f = _PdfPages(pdf) for p in range(num_pages): # ====================================== # Make figure # ====================================== fig_array[p] = _plt.figure(figsize=figsize) # ====================================== # Get number of rows on page # ====================================== pg_max_ind = _np.min( [(p+1) * per_page - 1, max_ind] ) num_rows = _np.int(_np.ceil((pg_max_ind+1 - p * per_page) / columns)) for i in range(num_rows): # ====================================== # Get images for column # ====================================== i_min_ind = p * per_page + i * columns col_max_ind = _np.min([i_min_ind + columns - 1, max_ind]) for j, image in enumerate(images[i_min_ind:col_max_ind+1]): ax = fig_array[p].add_subplot(gs[i, j]) try: if _np.issubdtype(image.dtype, _np.integer): image = _np.array(image, dtype=float) except: pass plot = ax.imshow(image, **kwargs) if cmap is not None: plot.set_cmap(cmap) if cbar: fig_array[p].colorbar(plot) fig_array[p].tight_layout() if pdf is not None: f.savefig(fig_array[p]) if not show: _plt.close(fig_array[p]) if pdf is not None: f.close() return fig_array
def error(code: int, *args, **kwargs) -> HedgehogCommandError: """ Creates an error from the given code, and args and kwargs. :param code: The acknowledgement code :param args: Exception args :param kwargs: Exception kwargs :return: the error for the given acknowledgement code """ # TODO add proper error code if code == FAILED_COMMAND and len(args) >= 1 and args[0] == "Emergency Shutdown activated": return EmergencyShutdown(*args, **kwargs) return _errors[code](*args, **kwargs)
def to_message(self): """ Creates an error Acknowledgement message. The message's code and message are taken from this exception. :return: the message representing this exception """ from .messages import ack return ack.Acknowledgement(self.code, self.args[0] if len(self.args) > 0 else '')
def clean(options, info): """Clean up extra files littering the source tree. options.paved.clean.dirs: directories to search recursively options.paved.clean.patterns: patterns to search for and remove """ info("Cleaning patterns %s", options.paved.clean.patterns) for wd in options.paved.clean.dirs: info("Cleaning in %s", wd) for p in options.paved.clean.patterns: for f in wd.walkfiles(p): f.remove()
def printoptions(): '''print paver options. Prettified by json. `long_description` is removed ''' x = json.dumps(environment.options, indent=4, sort_keys=True, skipkeys=True, cls=MyEncoder) print(x)
def parse(self, data: RawMessage) -> Message: """\ Parses a binary protobuf message into a Message object. """ try: return self.receiver.parse(data) except KeyError as err: raise UnknownCommandError from err except DecodeError as err: raise UnknownCommandError(f"{err}") from err
def setup_axes(rows=1, cols=1, figsize=(8, 6), expand=True, tight_layout=None, **kwargs): """ Sets up a figure of size *figsize* with a number of rows (*rows*) and columns (*cols*). \*\*kwargs passed through to :meth:`matplotlib.figure.Figure.add_subplot`. .. versionadded:: 1.2 Parameters ---------- rows : int Number of rows to create. cols : int Number of columns to create. figsize : tuple Size of figure to create. expand : bool Make the entire figure with size `figsize`. Returns ------- fig : :class:`matplotlib.figure.Figure` The figure. axes : :class:`numpy.ndarray` An array of all of the axes. (Unless there's only one axis, in which case it returns an object instance :class:`matplotlib.axis.Axis`.) """ if expand: figsize = (figsize[0]*cols, figsize[1]*rows) figargs = {} if isinstance(tight_layout, dict): figargs["tight_layout"] = tight_layout elif tight_layout == "pdf": figargs["tight_layout"] = {"rect": (0, 0, 1, 0.95)} dpi = kwargs.pop('dpi', None) fig, gs = _setup_figure(rows=rows, cols=cols, figsize=figsize, dpi=dpi, **figargs) axes = _np.empty(shape=(rows, cols), dtype=object) for i in range(rows): for j in range(cols): axes[i, j] = fig.add_subplot(gs[i, j], **kwargs) if axes.shape == (1, 1): return fig, axes[0, 0] else: return fig, axes
def factory(cls, data_class, **kwargs): """Creates a ``DCCGraph``, a root :class:`Node`: and the node's associated data class instance. This factory is used to get around the chicken-and-egg problem of the ``DCCGraph`` and ``Nodes`` within it having pointers to each other. :param data_class: django model class that extends :class:`BaseNodeData` and is used to associate information with the nodes in this graph :param kwargs: arguments to pass to constructor of the data class instance that is to be created for the root node :returns: instance of the newly created ``DCCGraph`` """ if not issubclass(data_class, BaseNodeData): raise AttributeError('data_class must be a BaseNodeData extender') content_type = ContentType.objects.get_for_model(data_class) graph = DCCGraph.objects.create(data_content_type=content_type) node = Node.objects.create(graph=graph) data_class.objects.create(node=node, **kwargs) graph.root = node graph.save() return graph
def factory_from_graph(cls, data_class, root_args, children): """Creates a ``DCCGraph`` and corresponding nodes. The root_args parm is a dictionary specifying the parameters for creating a :class:`Node` and its corresponding :class:`BaseNodeData` subclass from the data_class specified. The children parm is an iterable containing pairs of dictionaries and iterables, where the dictionaries specify the parameters for a :class:`BaseNodeData` subclass and the iterable the list of children. Example:: DCCGraph.factory_from_graph(Label, {'name':'A'}, [ ({'name':'B', []), ({'name':'C', []) ]) creates the graph:: A / \ B C :param data_class: django model class that extends :class:`BaseNodeData` and is used to associate information with the Nodes in this graph :param root_args: dictionary of arguments to pass to constructor of the data class instance that is to be created for the root node :param children: iterable with a list of dictionary and iterable pairs :returns: instance of the newly created ``DCCGraph`` """ graph = cls.factory(data_class, **root_args) for child in children: cls._depth_create(graph.root, child[0], child[1]) return graph
def find_nodes(self, **kwargs): """Searches the data nodes that are associated with this graph using the key word arguments as a filter and returns a :class:`django.db.models.query.QuerySet`` of the attached :class:`Node` objects. :param kwargs: filter arguments applied to searching the :class:`BaseNodeData` subclass associated with this graph. :returns: ``QuerySet`` of :class:`Node` objects """ filter_args = {} classname = self.data_content_type.model_class().__name__.lower() for key, value in kwargs.items(): filter_args['%s__%s' % (classname, key)] = value return Node.objects.filter(**filter_args)
def add_child(self, **kwargs): """Creates a new ``Node`` based on the extending class and adds it as a child to this ``Node``. :param kwargs: arguments for constructing the data object associated with this ``Node`` :returns: extender of the ``Node`` class """ data_class = self.graph.data_content_type.model_class() node = Node.objects.create(graph=self.graph) data_class.objects.create(node=node, **kwargs) node.parents.add(self) self.children.add(node) return node
def connect_child(self, node): """Adds the given node as a child to this one. No new nodes are created, only connections are made. :param node: a ``Node`` object to connect """ if node.graph != self.graph: raise AttributeError('cannot connect nodes from different graphs') node.parents.add(self) self.children.add(node)
def ancestors(self): """Returns a list of the ancestors of this node.""" ancestors = set([]) self._depth_ascend(self, ancestors) try: ancestors.remove(self) except KeyError: # we weren't ancestor of ourself, that's ok pass return list(ancestors)
def ancestors_root(self): """Returns a list of the ancestors of this node but does not pass the root node, even if the root has parents due to cycles.""" if self.is_root(): return [] ancestors = set([]) self._depth_ascend(self, ancestors, True) try: ancestors.remove(self) except KeyError: # we weren't ancestor of ourself, that's ok pass return list(ancestors)
def descendents(self): """Returns a list of descendents of this node.""" visited = set([]) self._depth_descend(self, visited) try: visited.remove(self) except KeyError: # we weren't descendent of ourself, that's ok pass return list(visited)
def descendents_root(self): """Returns a list of descendents of this node, if the root node is in the list (due to a cycle) it will be included but will not pass through it. """ visited = set([]) self._depth_descend(self, visited, True) try: visited.remove(self) except KeyError: # we weren't descendent of ourself, that's ok pass return list(visited)
def can_remove(self): """Returns True if it is legal to remove this node and still leave the graph as a single connected entity, not splitting it into a forest. Only nodes with no children or those who cause a cycle can be deleted. """ if self.children.count() == 0: return True ancestors = set(self.ancestors_root()) children = set(self.children.all()) return children.issubset(ancestors)
def remove(self): """Removes the node from the graph. Note this does not remove the associated data object. See :func:`Node.can_remove` for limitations on what can be deleted. :returns: :class:`BaseNodeData` subclass associated with the deleted Node :raises AttributeError: if called on a ``Node`` that cannot be deleted """ if not self.can_remove(): raise AttributeError('this node cannot be deleted') data = self.data self.parents.remove(self) self.delete() return data
def prune(self): """Removes the node and all descendents without looping back past the root. Note this does not remove the associated data objects. :returns: list of :class:`BaseDataNode` subclassers associated with the removed ``Node`` objects. """ targets = self.descendents_root() try: targets.remove(self.graph.root) except ValueError: # root wasn't in the target list, no problem pass results = [n.data for n in targets] results.append(self.data) for node in targets: node.delete() for parent in self.parents.all(): parent.children.remove(self) self.delete() return results
def prune_list(self): """Returns a list of nodes that would be removed if prune were called on this element. """ targets = self.descendents_root() try: targets.remove(self.graph.root) except ValueError: # root wasn't in the target list, no problem pass targets.append(self) return targets
def _child_allowed(self, child_rule): """Called to verify that the given rule can become a child of the current node. :raises AttributeError: if the child is not allowed """ num_kids = self.node.children.count() num_kids_allowed = len(self.rule.children) if not self.rule.multiple_paths: num_kids_allowed = 1 if num_kids >= num_kids_allowed: raise AttributeError('Rule %s only allows %s children' % ( self.rule_name, self.num_kids_allowed)) # verify not a duplicate for node in self.node.children.all(): if node.data.rule_label == child_rule.class_label: raise AttributeError('Child rule already exists') # check if the given rule is allowed as a child if child_rule not in self.rule.children: raise AttributeError('Rule %s is not a valid child of Rule %s' % ( child_rule.__name__, self.rule_name))
def add_child_rule(self, child_rule): """Add a child path in the :class:`Flow` graph using the given :class:`Rule` subclass. This will create a new child :class:`Node` in the associated :class:`Flow` object's state graph with a new :class:`FlowNodeData` instance attached. The :class:`Rule` must be allowed at this stage of the flow according to the hierarchy of rules. :param child_rule: :class:`Rule` class to add to the flow as a child of :class:`Node` that this object owns :returns: ``FlowNodeData`` that was added """ self._child_allowed(child_rule) child_node = self.node.add_child(rule_label=child_rule.class_label) return child_node.data
def connect_child(self, child_node): """Adds a connection to an existing rule in the :class`Flow` graph. The given :class`Rule` subclass must be allowed to be connected at this stage of the flow according to the hierarchy of rules. :param child_node: ``FlowNodeData`` to attach as a child """ self._child_allowed(child_node.rule) self.node.connect_child(child_node.node)
def in_use(self): """Returns True if there is a :class:`State` object that uses this ``Flow``""" state = State.objects.filter(flow=self).first() return bool(state)
def start(self, flow): """Factory method for a running state based on a flow. Creates and returns a ``State`` object and calls the associated :func:`Rule.on_enter` method. :param flow: :class:`Flow` which defines this state machine :returns: newly created instance """ state = State.objects.create(flow=flow, current_node=flow.state_graph.root) flow.state_graph.root.data.rule.on_enter(state) return state
def next_state(self, rule=None): """Proceeds to the next step in the flow. Calls the associated :func:`Rule.on_leave` method for the for the current rule and the :func:`Rule.on_enter` for the rule being entered. If the current step in the flow is multipath then a valid :class:`Rule` subclass must be passed into this call. If there is only one possible path in the flow and a :class:`Rule` is given it will be ignored. :param rule: if the current :class:`Rule` in the :class:`Flow` is multipath then the next :class:`Rule` in the flow must be provided. """ num_kids = self.current_node.children.count() next_node = None if num_kids == 0: raise AttributeError('No next state in this Flow id=%s' % ( self.flow.id)) elif num_kids == 1: next_node = self.current_node.children.first() else: if not rule: raise AttributeError(('Current Rule %s is multipath but no ' 'choice was passed in') % self.current_node.data.rule_name) for node in self.current_node.children.all(): if node.data.rule_label == rule.class_label: next_node = node break if not next_node: raise AttributeError(('Current Rule %s is multipath and the ' 'Rule choice passed in was not in the Flow') % ( self.current_node.data.rule_name)) self.current_node.data.rule.on_leave(self) next_node.data.rule.on_enter(self) self.current_node = next_node self.save()
def get_location(self, location_id): """ Returns location data. http://dev.wheniwork.com/#get-existing-location """ url = "/2/locations/%s" % location_id return self.location_from_json(self._get_resource(url)["location"])
def get_locations(self): """ Returns a list of locations. http://dev.wheniwork.com/#listing-locations """ url = "/2/locations" data = self._get_resource(url) locations = [] for entry in data['locations']: locations.append(self.location_from_json(entry)) return locations
def X(self): """ The :math:`X` weighted properly by the errors from *y_error* """ if self._X is None: X = _copy.deepcopy(self.X_unweighted) # print 'X shape is {}'.format(X.shape) for i, el in enumerate(X): X[i, :] = el/self.y_error[i] # print 'New X shape is {}'.format(X.shape) self._X = X return self._X
def y(self): """ The :math:`X` weighted properly by the errors from *y_error* """ if self._y is None: self._y = self.y_unweighted/self.y_error return self._y
def y_fit(self): """ Using the result of the linear least squares, the result of :math:`X_{ij}\\beta_i` """ if self._y_fit is None: self._y_fit = _np.dot(self.X_unweighted, self.beta) return self._y_fit
def beta(self): """ The result :math:`\\beta` of the linear least squares """ if self._beta is None: # This is the linear least squares matrix formalism self._beta = _np.dot(_np.linalg.pinv(self.X) , self.y) return self._beta
def covar(self): """ The covariance matrix for the result :math:`\\beta` """ if self._covar is None: self._covar = _np.linalg.inv(_np.dot(_np.transpose(self.X), self.X)) return self._covar
def chisq_red(self): """ The reduced chi-square of the linear least squares """ if self._chisq_red is None: self._chisq_red = chisquare(self.y_unweighted.transpose(), _np.dot(self.X_unweighted, self.beta), self.y_error, ddof=3, verbose=False) return self._chisq_red
def create(self, server): """Create the task on the server""" if len(self.geometries) == 0: raise Exception('no geometries') return server.post( 'task_admin', self.as_payload(), replacements={ 'slug': self.__challenge__.slug, 'identifier': self.identifier})
def update(self, server): """Update existing task on the server""" return server.put( 'task_admin', self.as_payload(), replacements={ 'slug': self.__challenge__.slug, 'identifier': self.identifier})
def from_server(cls, server, slug, identifier): """Retrieve a task from the server""" task = server.get( 'task', replacements={ 'slug': slug, 'identifier': identifier}) return cls(**task)
def formatter(color, s): """ Formats a string with color """ if no_coloring: return s return "{begin}{s}{reset}".format(begin=color, s=s, reset=Colors.RESET)
def reload(self, *fields, **kwargs): """Reloads all attributes from the database. :param fields: (optional) args list of fields to reload :param max_depth: (optional) depth of dereferencing to follow .. versionadded:: 0.1.2 .. versionchanged:: 0.6 Now chainable .. versionchanged:: 0.9 Can provide specific fields to reload """ max_depth = 1 if fields and isinstance(fields[0], int): max_depth = fields[0] fields = fields[1:] elif "max_depth" in kwargs: max_depth = kwargs["max_depth"] if not self.pk: raise self.DoesNotExist("Document does not exist") obj = self._qs.read_preference(ReadPreference.PRIMARY).filter( **self._object_key).only(*fields).limit(1 ).select_related(max_depth=max_depth) if obj: obj = obj[0] else: raise self.DoesNotExist("Document does not exist") for field in self._fields_ordered: if not fields or field in fields: try: setattr(self, field, self._reload(field, obj[field])) except KeyError: # If field is removed from the database while the object # is in memory, a reload would cause a KeyError # i.e. obj.update(unset__field=1) followed by obj.reload() delattr(self, field) # BUG FIX BY US HERE: if not fields: self._changed_fields = obj._changed_fields else: for field in fields: field = self._db_field_map.get(field, field) if field in self._changed_fields: self._changed_fields.remove(field) self._created = False return self
def pdf2png(file_in, file_out): """ Uses `ImageMagick <http://www.imagemagick.org/>`_ to convert an input *file_in* pdf to a *file_out* png. (Untested with other formats.) Parameters ---------- file_in : str The path to the pdf file to be converted. file_out : str The path to the png file to be written. """ command = 'convert -display 37.5 {} -resize 600 -append {}'.format(file_in, file_out) _subprocess.call(_shlex.split(command))
def get_user(self, user_id): """ Returns user profile data. http://dev.wheniwork.com/#get-existing-user """ url = "/2/users/%s" % user_id return self.user_from_json(self._get_resource(url)["user"])
def get_users(self, params={}): """ Returns a list of users. http://dev.wheniwork.com/#listing-users """ param_list = [(k, params[k]) for k in sorted(params)] url = "/2/users/?%s" % urlencode(param_list) data = self._get_resource(url) users = [] for entry in data["users"]: users.append(self.user_from_json(entry)) return users
def _setVirtualEnv(): """Attempt to set the virtualenv activate command, if it hasn't been specified. """ try: activate = options.virtualenv.activate_cmd except AttributeError: activate = None if activate is None: virtualenv = path(os.environ.get('VIRTUAL_ENV', '')) if not virtualenv: virtualenv = options.paved.cwd else: virtualenv = path(virtualenv) activate = virtualenv / 'bin' / 'activate' if activate.exists(): info('Using default virtualenv at %s' % activate) options.setdotted('virtualenv.activate_cmd', 'source %s' % activate)
def shv(command, capture=False, ignore_error=False, cwd=None): """Run the given command inside the virtual environment, if available: """ _setVirtualEnv() try: command = "%s; %s" % (options.virtualenv.activate_cmd, command) except AttributeError: pass return bash(command, capture=capture, ignore_error=ignore_error, cwd=cwd)
def update(dst, src): """Recursively update the destination dict-like object with the source dict-like object. Useful for merging options and Bunches together! Based on: http://code.activestate.com/recipes/499335-recursively-update-a-dictionary-without-hitting-py/#c1 """ stack = [(dst, src)] def isdict(o): return hasattr(o, 'keys') while stack: current_dst, current_src = stack.pop() for key in current_src: if key not in current_dst: current_dst[key] = current_src[key] else: if isdict(current_src[key]) and isdict(current_dst[key]): stack.append((current_dst[key], current_src[key])) else: current_dst[key] = current_src[key] return dst
def pip_install(*args): """Send the given arguments to `pip install`. """ download_cache = ('--download-cache=%s ' % options.paved.pip.download_cache) if options.paved.pip.download_cache else '' shv('pip install %s%s' % (download_cache, ' '.join(args)))
def _get_resource(self, url, data_key=None): """ When I Work GET method. Return representation of the requested resource. """ headers = {"Accept": "application/json"} if self.token: headers["W-Token"] = "%s" % self.token response = WhenIWork_DAO().getURL(url, headers) if response.status != 200: raise DataFailureException(url, response.status, response.data) return json.loads(response.data)
def _put_resource(self, url, body): """ When I Work PUT method. """ headers = {"Content-Type": "application/json", "Accept": "application/json"} if self.token: headers["W-Token"] = "%s" % self.token response = WhenIWork_DAO().putURL(url, headers, json.dumps(body)) if not (response.status == 200 or response.status == 201 or response.status == 204): raise DataFailureException(url, response.status, response.data) return json.loads(response.data)
def _post_resource(self, url, body): """ When I Work POST method. """ headers = {"Content-Type": "application/json", "Accept": "application/json"} if self.token: headers["W-Token"] = "%s" % self.token response = WhenIWork_DAO().postURL(url, headers, json.dumps(body)) if not (response.status == 200 or response.status == 204): raise DataFailureException(url, response.status, response.data) return json.loads(response.data)
def _delete_resource(self, url): """ When I Work DELETE method. """ headers = {"Content-Type": "application/json", "Accept": "application/json"} if self.token: headers["W-Token"] = "%s" % self.token response = WhenIWork_DAO().deleteURL(url, headers) if not (response.status == 200 or response.status == 201 or response.status == 204): raise DataFailureException(url, response.status, response.data) return json.loads(response.data)
def get_shifts(self, params={}): """ List shifts http://dev.wheniwork.com/#listing-shifts """ param_list = [(k, params[k]) for k in sorted(params)] url = "/2/shifts/?%s" % urlencode(param_list) data = self._get_resource(url) shifts = [] locations = {} sites = {} positions = {} users = {} for entry in data.get("locations", []): location = Locations.location_from_json(entry) locations[location.location_id] = location for entry in data.get("sites", []): site = Sites.site_from_json(entry) sites[site.site_id] = site for entry in data.get("positions", []): position = Positions.position_from_json(entry) positions[position.position_id] = position for entry in data.get("users", []): user = Users.user_from_json(entry) users[user.user_id] = user for entry in data["shifts"]: shift = self.shift_from_json(entry) shifts.append(shift) for shift in shifts: shift.location = locations.get(shift.location_id, None) shift.site = sites.get(shift.site_id, None) shift.position = positions.get(shift.position_id, None) shift.user = users.get(shift.user_id, None) return shifts
def create_shift(self, params={}): """ Creates a shift http://dev.wheniwork.com/#create/update-shift """ url = "/2/shifts/" body = params data = self._post_resource(url, body) shift = self.shift_from_json(data["shift"]) return shift
def delete_shifts(self, shifts): """ Delete existing shifts. http://dev.wheniwork.com/#delete-shift """ url = "/2/shifts/?%s" % urlencode( {'ids': ",".join(str(s) for s in shifts)}) data = self._delete_resource(url) return data
def delete_past_events(self): """ Removes old events. This is provided largely as a convenience for maintenance purposes (daily_cleanup). if an Event has passed by more than X days as defined by Lapsed and has no related special events it will be deleted to free up the event name and remove clutter. For best results, set this up to run regularly as a cron job. """ lapsed = datetime.datetime.now() - datetime.timedelta(days=90) for event in self.filter(start_date__lte=lapsed, featured=0, recap=''): event.delete()
def recently_ended(self): """ Determines if event ended recently (within 5 days). Useful for attending list. """ if self.ended(): end_date = self.end_date if self.end_date else self.start_date if end_date >= offset.date(): return True
def all_comments(self): """ Returns combined list of event and update comments. """ ctype = ContentType.objects.get(app_label__exact="happenings", model__exact='event') update_ctype = ContentType.objects.get(app_label__exact="happenings", model__exact='update') update_ids = self.update_set.values_list('id', flat=True) return Comment.objects.filter( Q(content_type=ctype.id, object_pk=self.id) | Q(content_type=update_ctype.id, object_pk__in=update_ids) )
def get_all_images(self): """ Returns chained list of event and update images. """ self_imgs = self.image_set.all() update_ids = self.update_set.values_list('id', flat=True) u_images = UpdateImage.objects.filter(update__id__in=update_ids) return list(chain(self_imgs, u_images))
def get_all_images_count(self): """ Gets count of all images from both event and updates. """ self_imgs = self.image_set.count() update_ids = self.update_set.values_list('id', flat=True) u_images = UpdateImage.objects.filter(update__id__in=update_ids).count() count = self_imgs + u_images return count
def get_top_assets(self): """ Gets images and videos to populate top assets. Map is built separately. """ images = self.get_all_images()[0:14] video = [] if supports_video: video = self.eventvideo_set.all()[0:10] return list(chain(images, video))[0:15]
def plot_featured(*args, **kwargs): """ Wrapper for matplotlib.pyplot.plot() / errorbar(). Takes options: * 'error': if true, use :func:`matplotlib.pyplot.errorbar` instead of :func:`matplotlib.pyplot.plot`. *\*args* and *\*\*kwargs* passed through here. * 'fig': figure to use. * 'figlabel': figure label. * 'legend': legend location. * 'toplabel': top label of plot. * 'xlabel': x-label of plot. * 'ylabel': y-label of plot. """ # Strip off options specific to plot_featured toplabel = kwargs.pop('toplabel', None) xlabel = kwargs.pop('xlabel', None) ylabel = kwargs.pop('ylabel', None) legend = kwargs.pop('legend', None) error = kwargs.pop('error', None) # save = kwargs.pop('save', False) figlabel = kwargs.pop('figlabel', None) fig = kwargs.pop('fig', None) if figlabel is not None: fig = _figure(figlabel) elif fig is None: try: fig = _plt.gcf() except: fig = _plt.fig() # Pass everything else to plot if error is None: _plt.plot(*args, **kwargs) else: _plt.errorbar(*args, **kwargs) # Format plot as desired _addlabel(toplabel, xlabel, ylabel, fig=fig) if legend is not None: _plt.legend(legend) return fig
def decorate(msg="", waitmsg="Please wait"): """ Decorated methods progress will be displayed to the user as a spinner. Mostly for slower functions that do some network IO. """ def decorator(func): @functools.wraps(func) def wrapper(*args, **kwargs): spin = Spinner(msg=msg, waitmsg=waitmsg) spin.start() a = None try: a = func(*args, **kwargs) except Exception as e: spin.msg = "Something went wrong: " spin.stop_spinning() spin.join() raise e spin.stop_spinning() spin.join() return a return wrapper return decorator