code
stringlengths
1
18.2k
The period of *data*. """ if min_period >= max_period: return min_period coarse_period = periodogram(data, coarse_precision, min_period, max_period, period_jobs=period_jobs) return coarse_period if coarse_precision <= fine_precision else \ periodogram(data, fine_precision, coarse_period - coarse_precision, coarse_perio...
def rephase(data, period=1.0, shift=0.0, col=0, copy=True): """ Returns *data* (or a copy) phased with *period*, and shifted by a phase-shift *shift*. **Parameters** data : array-like, shape = [n_samples, n_cols] Array containing the time or phase values to be rephased in column *col*. period : number, optional Period ...
def update_xml_element(self): """ Updates the xml element contents to matches the instance contents. :returns: Updated XML element. :rtype: lxml.etree._Element """ if not hasattr(self, 'xml_element'): self.xml_element = etree.Element(self.name, nsmap=NSMAP) self.xml_element.set('system', str(self.system)) self.xml_elem...
def to_xml_string(self): """ Exports the element in XML format. :returns: element in XML format. :rtype: str """ self.update_xml_element() xml = self.xml_element return etree.tostring(xml, pretty_print=True).decode('utf-8')
def fetch(self): """Fetch data corresponding to this draft and store it as ``self.data``.""" if self.message_id is None: raise Exception(".message_id not set.") response = self.session.request("find:Message.content", [ self.message_id ]) if response == None: raise Exception("Message not found.") self.data = response re...
def save(self): """Save current draft state.""" response = self.session.request("save:Message", [ self.data ]) self.data = response self.message_id = self.data["id"] return self
def send_preview(self): # pragma: no cover """Send a preview of this draft.""" response = self.session.request("method:queuePreview", [ self.data ]) self.data = response return self
def send(self): # pragma: no cover """Send the draft.""" response = self.session.request("method:queue", [ self.data ]) self.data = response return self
def delete(self): """Delete the draft.""" response = self.session.request("delete:Message", [ self.message_id ]) self.data = response return self
def _get_query_sets_for_object(o): """ Determines the correct query set based on the object. If the object is a literal, it will return a query set over LiteralStatements. If the object is a URIRef or BNode, it will return a query set over Statements. If the object is unknown, it will return both the LiteralStatement a...
def _get_named_graph(context): """ Returns the named graph for this context. """ if context is None: return None return models.NamedGraph.objects.get_or_create(identifier=context.identifier)[0]
def destroy(self, configuration=None): """ Completely destroys a store and all the contexts and triples in the store. >>> store = DjangoStore() >>> g = rdflib.Graph(store=store) >>> g.open(configuration=None, create=True) == rdflib.store.VALID_STORE True >>> g.open(configuration=None, create=False) == rdflib.store.VALI...
def add(self, (s, p, o), context, quoted=False): """ Adds a triple to the store. >>> from rdflib.term import URIRef >>> from rdflib.namespace import RDF >>> subject = URIRef('http://zoowizard.org/resource/Artis') >>> object = URIRef('http://schema.org/Zoo') >>> g = rdflib.Graph('Django') >>> g.add((subject, RDF.type, o...
def remove(self, (s, p, o), context=None): """ Removes a triple from the store. """ named_graph = _get_named_graph(context) query_sets = _get_query_sets_for_object(o) filter_parameters = dict() if named_graph is not None: filter_parameters['context_id'] = named_graph.id if s: filter_parameters['subject'] = s if p: filt...
def triples(self, (s, p, o), context=None): """ Returns all triples in the current store. """ named_graph = _get_named_graph(context) query_sets = _get_query_sets_for_object(o) filter_parameters = dict() if named_graph is not None: filter_parameters['context_id'] = named_graph.id if s: filter_parameters['subject'] = s ...
def addNew(label, version, baseVersion, dataHash="", fixedHash="", replayHash=""): """ Add a new version record to the database to be tracked VERSION RECORD EXAMPLE: "base-version": 55505, "data-hash": "60718A7CA50D0DF42987A30CF87BCB80", "fixed-hash": "0189B2804E2F6BA4C4591222089E63B2", "label": "3.16", "replay-hash": ...
uniqueValHeaders.remove("base-version") record = {"base-version" : baseVersion} #print("%15s : %s (%s)"%("base-version", baseVersion, type(baseVersion))) for k,v in zip(uniqueValHeaders, [label, version, dataHash, fixedHash, replayHash]): # new attr values must be unique within all handler records record[k] = v # conve...
def load(self): """load ALL_VERS_DATA from disk""" basepath = os.path.dirname(os.path.abspath(__file__)) filename = os.sep.join([basepath, c.FOLDER_JSON, c.FILE_GAME_VERSIONS]) Handler.ALL_VERS_DATA = {} # reset known data; do not retain defunct information with open(filename, "r") as f: data = json.loads( f.read() ) s...
def save(self, new=None, timeout=2): """write ALL_VERS_DATA to disk in 'pretty' format""" if new: self.update(new) # allow two operations (update + save) with a single command if not self._updated: return # nothing to do thisPkg = os.path.dirname(__file__) filename = os.path.join(thisPkg, c.FOLDER_JSON, c.FILE_GAME_VER...
python3 requires encoding str => bytes to write to file self._updated = False return except IOError: pass # continue waiting for file to be available raise # after timeout, prior exception is what matters
def search(self, *args, **kwargs): """match all records that have any args in any key/field that also match key/value requirements specified in kwargs""" ret = [] for record in Handler.ALL_VERS_DATA.values(): matchArgs = list(kwargs.keys()) for k,v in iteritems(kwargs): # restrict records based on key-value match requi...
def update(self, data): """update known data with with newly provided data""" if not isinstance(data, list): data = [data] # otherwise no conversion is necessary master = Handler.ALL_VERS_DATA for record in data: #print(record) for k,v in iteritems(record): # ensure record contents aretyped appropriately try: record[k]...
determine whether master needs to be updated try: if masterLabel[k] == v: continue # whether an entry in the record needs to be updated (doesn't match) except KeyError: pass # this condition means that k is a new key, so the record must be updated self._updated = True try: master[label].update(record) # index each reco...
def getLocalIPaddress(): """visible to other machines on LAN""" try: s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect(('google.com', 0)) my_local_ip = s.getsockname()[0] # takes ~0.005s #from netifaces import interfaces, ifaddresses, AF_INET #full solution in the event of multiple NICs (network interface ...
def getPublicIPaddress(timeout=c.DEFAULT_TIMEOUT): """visible on public internet""" start = time.time() my_public_ip = None e = Exception while my_public_ip == None: if time.time() - start > timeout: break try: #httpbin.org -- site is useful to test scripts / applications. my_public_ip = json.load(urlopen('http://httpb...
takes ~0.33s if my_public_ip: break except Exception as e: print(type(e), e, "https://api.ipify.org/") try: #ip.42.pl -- This is very convenient for scripts, you don't need JSON parsing here. my_public_ip = urlopen('http://ip.42.pl/raw').read() # takes ~0.35s if my_public_ip: break except Exception as e: print(type(e),...
def bits_to_dict(bits): """Convert a Django template tag's kwargs into a dictionary of Python types. The only necessary types are number, boolean, list, and string. http://pygments.org/docs/formatters/#HtmlFormatter from: ["style='monokai'", "cssclass='cssclass',", "boolean='true',", 'num=0,', "list='[]'"] to: {'style'...
def pygmentify(value, **kwargs): """Return a highlighted code block with Pygments.""" soup = BeautifulSoup(value, 'html.parser') for pre in soup.find_all('pre'): # Get code code = ''.join([to_string(item) for item in pre.contents]) code = code.replace('&lt;', '<') code = code.replace('&gt;', '>') code = code.replace('&...
Get formatter formatter = HtmlFormatter(**kwargs) # Highlight code highlighted = highlight(code, lexer, formatter) class_string = ' '.join([c for c in class_list]) highlighted = highlighted.replace( '<div class="%s"><pre>' % kwargs['cssclass'], '<div class="%s"><pre class="%s">' % (kwargs['cssclass'], class_string) ) p...
def get_analyzer_for(language_code, default='snowball'): """ Get the available language analyzer for the given language code or else the default. :param language_code: Django language code :param default: The analyzer to return if no language analyzer has been found. Defaults to 'snowball'. :return: The Haystack langua...
return languages[language_code] elif language_code[:2] in languages: return languages[language_code[:2]] return default
def _encode_multipart_formdata(fields, files): """ Create a multipart encoded form for use in PUTing and POSTing. fields is a sequence of (name, value) elements for regular form fields. files is a sequence of (name, filename, value) elements for data to be uploaded as files Return (content_type, body) ready for httplib...
def _generate_read_callable(name, display_name, arguments, regex, doc, supported): """ Returns a callable which conjures the URL for the resource and GETs a response """ def f(self, *args, **kwargs): url = self._generate_url(regex, args) if 'params' in kwargs: url += "?" + urllib.urlencode(kwargs['params']) return self...
def _generate_create_callable(name, display_name, arguments, regex, doc, supported, post_arguments, is_action): """ Returns a callable which conjures the URL for the resource and POSTs data """ def f(self, *args, **kwargs): for key, value in args[-1].items(): if type(value) == file: return self._put_or_post_multipart('...
def _split_regex(regex): """ Return an array of the URL split at each regex match like (?P<id>[\d]+) Call with a regex of '^/foo/(?P<id>[\d]+)/bar/$' and you will receive ['/foo/', '/bar/'] """ if regex[0] == '^': regex = regex[1:] if regex[-1] == '$': regex = regex[0:-1] results = [] line = '' for c in regex: if c == ...
def print_help(self): """ Prints the api method info to stdout for debugging. """ keyfunc = lambda x: (x.resource_name, x.__doc__.strip()) resources = groupby(sorted(filter(lambda x: (hasattr(x, 'is_api_call') and x.is_api_call and x.is_supported_api), [getattr(self, resource) for resource in dir(self)]), key=keyfunc),...
if r.__name__.startswith('delete'): method_desc = 'Corresponding API call: DELETE to ' + r._resource_uri print '\t\t', method_header, ' - ', method_desc print
def _construct_request(self): """ Utility for constructing the request header and connection """ if self.parsed_endpoint.scheme == 'https': conn = httplib.HTTPSConnection(self.parsed_endpoint.netloc) else: conn = httplib.HTTPConnection(self.parsed_endpoint.netloc) head = { "Accept": "application/json", "User-Agent": US...
def _delete_resource(self, url): """ DELETEs the resource at url """ conn, head = self._construct_request() conn.request("DELETE", url, "", head) resp = conn.getresponse() self._handle_response_errors('DELETE', url, resp)
def _get_data(self, url, accept=None): """ GETs the resource at url and returns the raw response If the accept parameter is not None, the request passes is as the Accept header """ if self.parsed_endpoint.scheme == 'https': conn = httplib.HTTPSConnection(self.parsed_endpoint.netloc) else: conn = httplib.HTTPConnection(...
def _put_or_post_multipart(self, method, url, data): """ encodes the data as a multipart form and PUTs or POSTs to the url the response is parsed as JSON and the returns the resulting data structure """ fields = [] files = [] for key, value in data.items(): if type(value) == file: files.append((key, value.name, value.r...
def _put_or_post_json(self, method, url, data): """ urlencodes the data and PUTs it to the url the response is parsed as JSON and the resulting data type is returned """ if self.parsed_endpoint.scheme == 'https': conn = httplib.HTTPSConnection(self.parsed_endpoint.netloc) else: conn = httplib.HTTPConnection(self.parsed...
def _generate_url(self, regex, arguments): """ Uses the regex (of the type defined in Django's url patterns) and the arguments to return a relative URL For example, if the regex is '^/api/shreddr/job/(?P<id>[\d]+)$' and arguments is ['23'] then return would be '/api/shreddr/job/23' """ regex_tokens = _split_regex(regex...
def launch_job(self, job_id): """ Convenience method for launching a job. We use POST for actions outside of HTTP verbs (job launch in this case). """ assert self.api_version.lower() in ['0.01a', '0.1'], \ 'This method is only supported in BETA (0.01) and ALPHA (0.01a) versions' try: self.create_job(job_id, {'submit_jo...
def find_importer_frame(): """Returns the outer frame importing this "end" module. If this module is being imported by other means than import statement, None is returned. Returns: A frame object or None. """ byte = lambda ch: ord(ch) if PY2 else ch frame = inspect.currentframe() try: while frame: code = frame.f_code l...
def is_end_node(node): """Checks if a node is the "end" keyword. Args: node: AST node. Returns: True if the node is the "end" keyword, otherwise False. """ return (isinstance(node, ast.Expr) and isinstance(node.value, ast.Name) and node.value.id == 'end')
def get_compound_bodies(node): """Returns a list of bodies of a compound statement node. Args: node: AST node. Returns: A list of bodies of the node. If the given node does not represent a compound statement, an empty list is returned. """ if isinstance(node, (ast.Module, ast.FunctionDef, ast.ClassDef, ast.With)): retu...
def check_end_blocks(frame): """Performs end-block check. Args: frame: A frame object of the module to be checked. Raises: SyntaxError: If check failed. """ try: try: module_name = frame.f_globals['__name__'] except KeyError: warnings.warn( 'Can not get the source of an uknown module. ' 'End-of-block syntax check is sk...
try-except-finally # statement which is parsed as ast.TryExcept in ast.TryFinally in # Python 2. if (PY2 and isinstance(node, ast.TryFinally) and len(node.body) == 1 and isinstance(node.body[0], ast.TryExcept)): continue end for body in bodies: skip_next = False for i, child in enumerate(body): if skip_next: skip_next ...
def install_import_hook(): """Installs __import__ hook.""" saved_import = builtins.__import__ @functools.wraps(saved_import) def import_hook(name, *args, **kwargs): if name == 'end': process_import() end return saved_import(name, *args, **kwargs) end builtins.__import__ = import_hook
def metadata_to_buffers(metadata): """ Transform a dict of metadata into a sequence of buffers. :param metadata: The metadata, as a dict. :returns: A list of buffers. """ results = [] for key, value in metadata.items(): assert len(key) < 256 assert len(value) < 2 ** 32 results.extend([ struct.pack('!B', len(key)), key,...
def buffer_to_metadata(buffer): """ Transform a buffer to a metadata dictionary. :param buffer: The buffer, as received in a READY command. :returns: A metadata dictionary, with its keys normalized (in lowercase). """ offset = 0 size = len(buffer) metadata = {} while offset < size: name_size = struct.unpack_from('B', b...
def _status(self): ''' Internal: Do not call. Returns the status list for a list of job_ids Args: self Returns: [status...] : Status list of all jobs ''' job_id_list = ' '.join(self.resources.keys()) jobs_missing = list(self.resources.keys()) retcode, stdout, stderr = self.channel.execute_wait("qstat {0}".format(job_id...
def submit(self, command, blocksize, job_name="parsl.auto"): ''' Submits the command onto an Local Resource Manager job of blocksize parallel elements. Submit returns an ID that corresponds to the task that was just submitted. If tasks_per_node < 1 : ! This is illegal. tasks_per_node should be integer If tasks_per_node...
later to avoid confusing behavior. # We should always allocate blocks in integer counts of node_granularity if blocksize < self.nodes_per_block: blocksize = self.nodes_per_block # Set job name job_name = "parsl.{0}.{1}".format(job_name, time.time()) # Set script path script_path = "{0}/{1}.submit".format(self.script_di...
self.account is not None: submit_options = '{0} -A {1}'.format(submit_options, self.account) launch_cmd = "qsub {0} {1}".format(submit_options, channel_script_path) retcode, stdout, stderr = self.channel.execute_wait(launch_cmd, 10) job_id = None if retcode == 0: for line in stdout.split('\n'): if line.strip(): job_id ...
def cancel(self, job_ids): ''' Cancels the jobs specified by a list of job ids Args: job_ids : [<job_id> ...] Returns : [True/False...] : If the cancel operation fails the entire list will be False. ''' job_id_list = ' '.join(job_ids) retcode, stdout, stderr = self.channel.execute_wait("qdel {0}".format(job_id_list), 3...
def generate_identity(self): """ Generate a unique but random identity. """ identity = struct.pack('!BI', 0, self._base_identity) self._base_identity += 1 if self._base_identity >= 2 ** 32: self._base_identity = 0 return identity
async def _wait_peers(self): """ Blocks until at least one non-dead peer is available. """ # Make sure we remove dead peers. for p in self._peers[:]: if p.dead: self._peers.remove(p) while not self._peers: await self._peers.wait_not_empty()
async def _fair_get_in_peer(self): """ Get the first available available inbound peer in a fair manner. :returns: A `Peer` inbox, whose inbox is guaranteed not to be empty (and thus can be read from without blocking). """ peer = None while not peer: await self._wait_peers() # This rotates the list, implementing fair-qu...
async def _fair_recv(self): """ Receive from all the existing peers, rotating the list of peers every time. :returns: The frames. """ with await self._read_lock: peer = await self._fair_get_in_peer() result = peer.inbox.read_nowait() return result
async def _fair_get_out_peer(self): """ Get the first available peer, with non-blocking inbox or wait until one meets the condition. :returns: The peer whose outbox is ready to be written to. """ peer = None while not peer: await self._wait_peers() # This rotates the list, implementing fair-queuing. peers = list(self._...
async def _fair_send(self, frames): """ Send from the first available, non-blocking peer or wait until one meets the condition. :params frames: The frames to write. :returns: The peer that was used. """ peer = await self._fair_get_out_peer() peer.outbox.write_nowait(frames) return peer
async def subscribe(self, topic): """ Subscribe the socket to the specified topic. :param topic: The topic to subscribe to. """ if self.socket_type not in {SUB, XSUB}: raise AssertionError( "A %s socket cannot subscribe." % self.socket_type.decode(), ) # Do this **BEFORE** awaiting so that new connections created durin...
async def unsubscribe(self, topic): """ Unsubscribe the socket from the specified topic. :param topic: The topic to unsubscribe from. """ if self.socket_type not in {SUB, XSUB}: raise AssertionError( "A %s socket cannot unsubscribe." % self.socket_type.decode(), ) # Do this **BEFORE** awaiting so that new connections c...
def migrate(action): " Migration utils [create, run, undo, redo]. " from flaskext.evolution import Evolution from flask import current_app evolution = Evolution(current_app) evolution.manager(action)
def playerSurrendered(cfg): """the player has forceibly left the game""" if cfg.numAgents + cfg.numBots == 2: otherResult = c.RESULT_VICTORY else: otherResult = c.RESULT_UNDECIDED # if multiple players remain, they need to finish the match return assignValue(cfg, c.RESULT_DEFEAT, otherResult)
def assignValue(cfg, playerValue, otherValue): """artificially determine match results given match circumstances. WARNING: cheating will be detected and your player will be banned from server""" player = cfg.whoAmI() result = {} for p in cfg.players: if p.name == player.name: val = playerValue else: val = otherValue re...
def idPlayerResults(cfg, rawResult): """interpret standard rawResult for all players with known IDs""" result = {} knownPlayers = [] dictResult = {plyrRes.player_id : plyrRes.result for plyrRes in rawResult} for p in cfg.players: if p.playerID and p.playerID in dictResult: # identified player w/ result knownPlayers.app...
def save_model(self, request, obj, form, change): """Add an ObjectPosition to the object.""" super(GenericPositionsAdmin, self).save_model(request, obj, form, change) c_type = ContentType.objects.get_for_model(obj) try: ObjectPosition.objects.get(content_type__pk=c_type.id, object_id=obj.id) except ObjectPosition.DoesN...
def as_dict(self): """ Serializes the object necessary data in a dictionary. :returns: Serialized data in a dictionary. :rtype: dict """ result_dict = super(Profile, self).as_dict() statuses = list() version = None titles = list() descriptions = list() platforms = list() selects = list() for child in self.children: if ...
def update_xml_element(self): """ Updates the xml element contents to matches the instance contents. :returns: Updated XML element. :rtype: lxml.etree._Element """ if not hasattr(self, 'xml_element'): self.xml_element = etree.Element(self.name, nsmap=NSMAP) self.xml_element.clear() if hasattr(self, 'abstract'): self.xm...
def managed(name, packages=None, requirements=None, saltenv='base', user=None): """ Create and install python requirements in a conda enviroment pip is installed by default in the new enviroment name : path to the enviroment to be created packages : None single package or list of packages to install i.e. numpy, scipy=0...
Exception as e: ret['comment'] = e ret['result'] = False return ret # Install packages if packages is not None: installation_ret = installed(packages, env=name, saltenv=saltenv, user=user) ret['result'] = ret['result'] and installation_ret['result'] comments.append('From list [%s]' % installation_ret['comment']) ret['c...
def installed(name, env=None, saltenv='base', user=None): """ Installs a single package, list of packages (comma separated) or packages in a requirements.txt Checks if the package is already in the environment. Check ocurres here so is only needed to `conda list` and `pip freeze` once name name of the package(s) or pat...
= __salt__['cp.get_file_str'](name, saltenv) lines = lines.split('\n') elif os.path.exists(name): f = open(name, mode='r') lines = f.readlines() f.close() for line in lines: line = line.strip() if line != '' and not line.startswith('#'): line = line.split('#')[0].strip() # Remove inline comments packages.append(line) e...
not in conda_list: installation = __salt__['conda.install'](package, env=env, user=user) if installation['retcode'] == 0: ret['changes'][package] = 'installed' installed += 1 else: ret['changes'][package] = installation failed += 1 else: old += 1 comments = [] if installed > 0: comments.append('{0} installed'.format(in...
def get_configs(self, command): """Compose a dictionary with information for writing the submit script.""" logger.debug("Requesting one block with {} nodes per block and {} tasks per node".format( self.nodes_per_block, self.tasks_per_node)) job_config = {} job_config["submit_script_dir"] = self.channel.script_dir job_c...
def submit(self, command="", blocksize=1, job_name="parsl.auto"): ''' The submit method takes the command string to be executed upon instantiation of a resource most often to start a pilot (such as IPP engine or even Swift-T engines). Args : - command (str) : The bash command string to be executed. - blocksize (int) : ...
path script_path = "{0}/{1}.submit".format(self.script_dir, job_name) script_path = os.path.abspath(script_path) job_config = self.get_configs(command, blocksize) logger.debug("Writing submit script") self._write_submit_script(template_string, script_path, job_name, job_config) channel_script_path = self.channel.push_f...
def update(instance, full_clean=True, post_save=False, **kwargs): "Atomically update instance, setting field/value pairs from kwargs" # apply the updated args to the instance to mimic the change # note that these might slightly differ from the true database values # as the DB could have been updated by another thread. ...
def qr2scad(stream): """Convert black pixels to OpenSCAD cubes.""" img = Image.open(stream) # Convert to black and white 8-bit if img.mode != 'L': img = img.convert('L') # Invert color to get the right bounding box img = ImageOps.invert(img) bbox = img.getbbox() # Crop to only contain contents within the PDPs img = img...
{\n' result += ' cube([%(block_side)s, %(block_side)s, 1]);\n' % { 'block_side': BLOCK_SIDE } result += '}\n' result += 'module qr_code() {\n' for row in range(qr_side): for column in range(qr_side): if img_matrix[column, row] != 0: result += ' translate([%(x)s, %(y)s, 0])' % { 'x': BLOCK_SIZE * column - qr_side / 2, '...
def run(*args): """Load given `envfile` and run `command` with `params`""" if not args: args = sys.argv[1:] if len(args) < 2: print('Usage: runenv <envfile> <command> <params>') sys.exit(0) os.environ.update(create_env(args[0])) os.environ['_RUNENV_WRAPPED'] = '1' runnable_path = args[1] if not runnable_path.startswith...
def create_env(env_file): """Create environ dictionary from current os.environ and variables got from given `env_file`""" environ = {} with open(env_file, 'r') as f: for line in f.readlines(): line = line.rstrip(os.linesep) if '=' not in line: continue if line.startswith('#'): continue key, value = line.split('=', 1) e...
def info(args): " Show information about site. " site = find_site(args.PATH) print_header("%s -- install information" % site.get_name()) LOGGER.debug(site.get_info(full=True)) return True
def ls(args): """ List sites ---------- Show list of installed sites. :: usage: makesite ls [-h] [-v] [-p PATH] Show list of installed sites. optional arguments: -p PATH, --path PATH path to makesite sites instalation dir. you can set it in $makesite_home env variable. Examples: :: makesite ls """ assert args.path, "No...
def update(args): """ Run site update --------------- Run updates for site or all installed. :: usage: main.py update [-h] [-v] [-p PATH] [SITE] Run site update positional arguments: SITE Path to site or name (project.branch) optional arguments: -p PATH, --path PATH path to makesite sites instalation dir. you can set i...
def module(args): " Copy module source to current directory. " mod = op.join(settings.MOD_DIR, args.MODULE) assert op.exists(mod), "Not found module: %s" % args.MODULE if not args.DEST.startswith(op.sep): args.DEST = op.join(getcwd(), args.DEST) print_header("Copy module source") copytree(mod, args.DEST)
def uninstall(args): " Uninstall site. " site = find_site(args.PATH) site.run_remove() site.clean() if not listdir(op.dirname(site.deploy_dir)): call('sudo rm -rf %s' % op.dirname(site.deploy_dir))
def template(args): " Add or remove templates from site. " site = Site(args.PATH) if args.ACTION == "add": return site.add_template(args.TEMPLATE) return site.remove_template(args.TEMPLATE)
def shell(args): " A helper command to be used for shell integration " print print "# Makesite integration " print "# ==================== " print "export MAKESITE_HOME=%s" % args.path print "source %s" % op.join(settings.BASEDIR, 'shell.sh') print
def install(args): " Install site from sources or module " # Deactivate virtualenv if 'VIRTUAL_ENV' in environ: LOGGER.warning('Virtualenv enabled: %s' % environ['VIRTUAL_ENV']) # Install from base modules if args.module: args.src = op.join(settings.MOD_DIR, args.module) assert op.exists(args.src), "Not found module: %...
def autocomplete(force=False): " Shell autocompletion support. " if 'MAKESITE_AUTO_COMPLETE' not in environ and not force: return commands = filter(lambda cmd: cmd != 'main', ACTIONS.keys()) cwords = environ['COMP_WORDS'].split()[1:] cword = int(environ['COMP_CWORD']) try: current = cwords[cword - 1] except IndexError:...
== '-t' or (current and cwords[-2] == '-t')): print ' '.join(tpl for tpl in get_base_templates( ) if tpl.startswith(current)) elif sub_action == 'module': print ' '.join( tpl for tpl in get_base_modules() if tpl.startswith(current)) except IndexError: print (' '.join(a for a in commands if a.startswith(current))) sys.e...
def main(args=None): " Base dispather " try: start = datetime.now() LOGGER.info('MAKESITE Version %s' % version) LOGGER.info('Started at %s' % start.strftime("%Y-%m-%d %H:%M:%S")) LOGGER.info('Logfile: %s' % LOGFILE_HANDLER.stream.name) LOGGER.info('-' * 60) if args.host: cmd = "makesite %s %s" % (args.action, ' '.join...
def console(): " Enter point " autocomplete() config = settings.MakesiteParser() config.read([ settings.BASECONFIG, settings.HOMECONFIG, op.join(settings.MAKESITE_HOME or '', settings.CFGNAME), op.join(op.curdir, settings.CFGNAME), ]) argv = [] alias = dict(config.items('alias')) names = alias.keys() for arg in sys.arg...
def _gradient(self, diff, d, coords): """Compute the gradient. Args: diff (`array-like`): [`m`, `m`] matrix. `D` - `d` d (`array-like`): [`m`, `m`] matrix. coords (`array-like`): [`m`, `n`] matrix. Returns: `np.array`: Gradient, shape [`m`, `n`]. """ denom = np.copy(d) denom[denom == 0] = 1e-5 with np.errstate(divide='...
def _error_and_gradient(self, x): """Compute the error and the gradient. This is the function optimized by :obj:`scipy.optimize.minimize`. Args: x (`array-like`): [`m` * `n`, ] matrix. Returns: `tuple`: containing: - Error (`float`) - Gradient (`np.array`) [`m`, `n`] """ coords = x.reshape((self.m, self.n)) d = squaref...
def optimize(self, start=None, n=2): """Run multidimensional scaling on this distance matrix. Args: start (`None` or `array-like`): Starting coordinates. If `start=None`, random starting coordinates are used. If `array-like` must have shape [`m` * `n`, ]. n (`int`): Number of dimensions to embed samples in. Examples: ....