text
stringlengths
81
112k
Set or change the objective function of the polynomial optimization problem. :param objective: Describes the objective function. :type objective: :class:`sympy.core.expr.Expr` :param extraobjexpr: Optional parameter of a string expression of a linear combina...
Calculates the block_struct array for the output file. def _calculate_block_structure(self, inequalities, equalities, momentinequalities, momentequalities, extramomentmatrix, removeequalities, block_struct=None): ...
Write the relaxation to a file. :param filename: The name of the file to write to. The type can be autodetected from the extension: .dat-s for SDPA, .task for mosek, .csv for human readable format, or .txt for a symbolic export ...
There's a bug in Python3.4+, see http://bugs.python.org/issue23773, remove this and use sys._getframe(3) when bug is fixed def get_outerframe_skip_importlib_frame(level): """ There's a bug in Python3.4+, see http://bugs.python.org/issue23773, remove this and use sys._getframe(3) when bu...
template function of public api def public_api(self,url): ''' template function of public api''' try : url in api_urls return ast.literal_eval(requests.get(base_url + api_urls.get(url)).text) except Exception as e: print(e)
r""" Returns a list of strings or format dictionaries to describe the strings. May raise a ValueError if it can't be parsed. >>> parse(">>> []") ['>>> []'] >>> #parse("\x1b[33m[\x1b[39m\x1b[33m]\x1b[39m\x1b[33m[\x1b[39m\x1b[33m]\x1b[39m\x1b[33m[\x1b[39m\x1b[33m]\x1b[39m\x1b[33m[\x1b[39m") def par...
r"""Returns processed text, the next token, and unprocessed text >>> front, d, rest = peel_off_esc_code('somestuff') >>> front, rest ('some', 'stuff') >>> d == {'numbers': [2], 'command': 'A', 'intermed': '', 'private': '', 'csi': '\x1b[', 'seq': '\x1b[2A'} True def peel_off_esc_code(s): r...
Return key pressed from bytes_ or None Return a key name or None meaning it's an incomplete sequence of bytes (more bytes needed to determine the key pressed) encoding is how the bytes should be translated to unicode - it should match the terminal encoding. keynames is a string describing how key...
Whether seq bytes might create a char in encoding if more bytes were added def could_be_unfinished_char(seq, encoding): """Whether seq bytes might create a char in encoding if more bytes were added""" if decodable(seq, encoding): return False # any sensible encoding surely doesn't require lookahead (ri...
Returns pretty representation of an Event or keypress def pp_event(seq): """Returns pretty representation of an Event or keypress""" if isinstance(seq, Event): return str(seq) # Get the original sequence back if seq is a pretty name already rev_curses = dict((v, k) for k, v in CURSES_NAMES.it...
Return a string of random nouns up to max number def create_nouns(max=2): """ Return a string of random nouns up to max number """ nouns = [] for noun in range(0, max): nouns.append(random.choice(noun_list)) return " ".join(nouns)
Create a random valid date If past, then dates can be in the past If into the future, then no more than max_years into the future If it's not, then it can't be any older than max_years_past def create_date(past=False, max_years_future=10, max_years_past=10): """ Create a random valid date If pa...
Create a random birthday fomr someone between the ages of min_age and max_age def create_birthday(min_age=18, max_age=80): """ Create a random birthday fomr someone between the ages of min_age and max_age """ age = random.randint(min_age, max_age) start = datetime.date.today() - datetime.timedelta(...
Create a random password From Stackoverflow: http://stackoverflow.com/questions/7479442/high-quality-simple-random-password-generator Create a random password with the specified length and no. of digit, upper and lower case letters. :param length: Maximum no. of characters in the password :typ...
Run through some simple examples def show_examples(): """ Run through some simple examples """ first, last = create_name() add = create_street() zip, city, state = create_city_state_zip() phone = create_phone(zip) print(first, last) print(add) print("{0:s} {1:s} {2:s}".format(city, ...
MOSEK requires a specific sparse format to define the lower-triangular part of a symmetric matrix. This function does the conversion from the sparse upper triangular matrix format of Ncpol2SDPA. def convert_to_mosek_index(block_struct, row_offsets, block_offsets, row): """MOSEK requires a specific sparse f...
Converts the entire sparse representation of the Fi constraint matrices to sparse MOSEK matrices. def convert_to_mosek_matrix(sdp): """Converts the entire sparse representation of the Fi constraint matrices to sparse MOSEK matrices. """ barci = [] barcj = [] barcval = [] barai = [] ...
Convert an SDP relaxation to a MOSEK task. :param sdp: The SDP relaxation to convert. :type sdp: :class:`ncpol2sdpa.sdp`. :returns: :class:`mosek.Task`. def convert_to_mosek(sdp): """Convert an SDP relaxation to a MOSEK task. :param sdp: The SDP relaxation to convert. :type sdp: :class:`ncpo...
If ``text`` is not empty, append a new Text node to the most recent pending node, if there is any, or to the new nodes, if there are no pending nodes. def _add_text(self, text): """ If ``text`` is not empty, append a new Text node to the most recent pending node, if there is any...
Return version string. def version(): """Return version string.""" with open(os.path.join('curtsies', '__init__.py')) as input_file: for line in input_file: if line.startswith('__version__'): return ast.parse(line).body[0].value.s
fsarray(list_of_FmtStrs_or_strings, width=None) -> FSArray Returns a new FSArray of width of the maximum size of the provided strings, or width provided, and height of the number of strings provided. If a width is provided, raises a ValueError if any of the strings are of length greater than this width...
Returns two FSArrays with differences underlined def diff(cls, a, b, ignore_formatting=False): """Returns two FSArrays with differences underlined""" def underline(x): return u'\x1b[4m%s\x1b[0m' % (x,) def blink(x): return u'\x1b[5m%s\x1b[0m' % (x,) a_rows = [] b_rows = [] ...
create new order function :param rate: float :param amount: float :param order_type: str; set 'buy' or 'sell' :param pair: str; set 'btc_jpy' def create(self,rate, amount, order_type, pair): ''' create new order function :param rate: float :param amount: float ...
cancel the specified order :param order_id: order_id to be canceled def cancel(self,order_id): ''' cancel the specified order :param order_id: order_id to be canceled ''' url= 'https://coincheck.com/api/exchange/orders/' + order_id headers = make_header(url,access_key=se...
show payment history def history(self): ''' show payment history ''' url= 'https://coincheck.com/api/exchange/orders/transactions' headers = make_header(url,access_key=self.access_key,secret_key=self.secret_key) r = requests.get(url,headers=headers) return json.loads(r.t...
Returns the length hint of an object. def _length_hint(obj): """Returns the length hint of an object.""" try: return len(obj) except TypeError: try: get_hint = type(obj).__length_hint__ except AttributeError: return None try: hint = get_hi...
Decide what method to use for paging through text. def pager(text, color=None): """Decide what method to use for paging through text.""" stdout = _default_text_stdout() if not isatty(sys.stdin) or not isatty(stdout): return _nullpager(stdout, text, color) if 'PAGER' in os.environ: if WI...
Backwards-compatibility for the old retries format. def from_int(cls, retries, redirect=True, default=None): """ Backwards-compatibility for the old retries format.""" if retries is None: retries = default if default is not None else cls.DEFAULT if isinstance(retries, Retry): ...
Formula for computing the current backoff :rtype: float def get_backoff_time(self): """ Formula for computing the current backoff :rtype: float """ if self._observed_errors <= 1: return 0 backoff_value = self.backoff_factor * (2 ** (self._observed_errors -...
Is this method/status code retryable? (Based on method/codes whitelists) def is_forced_retry(self, method, status_code): """ Is this method/status code retryable? (Based on method/codes whitelists) """ if self.method_whitelist and method.upper() not in self.method_whitelist: return ...
Converts a callable or python ty into the most appropriate param ty. def convert_type(ty, default=None): """Converts a callable or python ty into the most appropriate param ty. """ if isinstance(ty, tuple): return Tuple(ty) if isinstance(ty, ParamType): return ty guessed_typ...
A helper function that intelligently wraps text. By default, it assumes that it operates on a single paragraph of text but if the `preserve_paragraphs` parameter is provided it will intelligently handle paragraphs (defined by two empty lines). If paragraphs are handled, a paragraph can be prefixed wit...
Writes a usage line into the buffer. :param prog: the program name. :param args: whitespace separated list of arguments. :param prefix: the prefix for the first line. def write_usage(self, prog, args='', prefix='Usage: '): """Writes a usage line into the buffer. :param prog: t...
Set the current topics to `topics` Environment: BE_PROJECT: First topic BE_CWD: Current `be` working directory BE_TOPICS: Arguments to `in` BE_DEVELOPMENTDIR: Absolute path to current development directory BE_PROJECTROOT: Absolute path to current project BE_PROJECTSR...
Create new default preset \b Usage: $ be new ad "blue_unicorn" created $ be new film --name spiderman "spiderman" created def new(preset, name, silent, update): """Create new default preset \b Usage: $ be new ad "blue_unicorn" created $ be n...
Update a local preset This command will cause `be` to pull a preset already available locally. \b Usage: $ be update ad Updating "ad".. def update(preset, clean): """Update a local preset This command will cause `be` to pull a preset already available locally. \b ...
Utility sub-command for tabcompletion This command is meant to be called by a tab completion function and is given a the currently entered topics, along with a boolean indicating whether or not the last entered argument is complete. def tab(topics, complete): """Utility sub-command for tabcompleti...
Enter into an environment with support for tab-completion This command drops you into a subshell, similar to the one generated via `be in ...`, except no topic is present and instead it enables tab-completion for supported shells. See documentation for further information. https://github.com/motto...
List contents of current context \b Usage: $ be ls - spiderman - hulk $ be ls spiderman - peter - mjay $ be ls spiderman seq01 - 1000 - 2000 - 2500 Return codes: 0 Normal 2 When insufficient arguments are suppl...
Create directory with template for topic of the current environment def mkdir(dir, enter): """Create directory with template for topic of the current environment """ if not os.path.exists(dir): os.makedirs(dir)
List presets \b Usage: $ be preset ls - ad - game - film def preset_ls(remote): """List presets \b Usage: $ be preset ls - ad - game - film """ if self.isactive(): lib.echo("ERROR: Exit current project first") ...
Find preset from hub \b $ be find ad https://github.com/mottosso/be-ad.git def preset_find(query): """Find preset from hub \b $ be find ad https://github.com/mottosso/be-ad.git """ if self.isactive(): lib.echo("ERROR: Exit current project first") sys.exit(lib.USE...
Print current environment Environment is outputted in a YAML-friendly format \b Usage: $ be dump Prefixed: - BE_TOPICS=hulk bruce animation - ... def dump(): """Print current environment Environment is outputted in a YAML-friendly format \b Usage: ...
Print current topics def what(): """Print current topics""" if not self.isactive(): lib.echo("No topic") sys.exit(lib.USER_ERROR) lib.echo(os.environ.get("BE_TOPICS", "This is a bug"))
Returns the Requests tuple auth for a given url from netrc. def get_netrc_auth(url): """Returns the Requests tuple auth for a given url from netrc.""" try: from netrc import netrc, NetrcParseError netrc_path = None for f in NETRC_FILES: try: loc = os.path....
Returns a CookieJar from a key/value dictionary. :param cj: CookieJar to insert cookies into. :param cookie_dict: Dict of key/values to insert into CookieJar. def add_dict_to_cookiejar(cj, cookie_dict): """Returns a CookieJar from a key/value dictionary. :param cj: CookieJar to insert cookies into. ...
Returns whether we should bypass proxies or not. def should_bypass_proxies(url): """ Returns whether we should bypass proxies or not. """ get_proxy = lambda k: os.environ.get(k) or os.environ.get(k.upper()) # First check whether no_proxy is defined. If it is, check that the URL # we're getting...
Return a string representing the default user agent. def default_user_agent(name="python-requests"): """Return a string representing the default user agent.""" _implementation = platform.python_implementation() if _implementation == 'CPython': _implementation_version = platform.python_version() ...
Given a string object, regardless of type, returns a representation of that string in the native string type, encoding and decoding where necessary. This assumes ASCII unless told otherwise. def to_native_string(string, encoding='ascii'): """ Given a string object, regardless of type, returns a represe...
Internal handler for the bash completion support. def _bashcomplete(cmd, prog_name, complete_var=None): """Internal handler for the bash completion support.""" if complete_var is None: complete_var = '_%s_COMPLETE' % (prog_name.replace('-', '_')).upper() complete_instr = os.environ.get(complete_var...
Invokes a command callback in exactly the way it expects. There are two ways to invoke this method: 1. the first argument can be a callback and all other arguments and keyword arguments are forwarded directly to the function. 2. the first argument is a click command object. In t...
This function when given an info name and arguments will kick off the parsing and create a new :class:`Context`. It does not invoke the actual command callback though. :param info_name: the info name for this invokation. Generally this is the most descriptive name fo...
This is the way to invoke a script with all the bells and whistles as a command line application. This will always terminate the application after a call. If this is not wanted, ``SystemExit`` needs to be caught. This method is also available by directly calling the instance of ...
Creates the underlying option parser for this command. def make_parser(self, ctx): """Creates the underlying option parser for this command.""" parser = OptionParser(ctx) parser.allow_interspersed_args = ctx.allow_interspersed_args parser.ignore_unknown_options = ctx.ignore_unknown_opti...
Writes the help text to the formatter if it exists. def format_help_text(self, ctx, formatter): """Writes the help text to the formatter if it exists.""" if self.help: formatter.write_paragraph() with formatter.indentation(): formatter.write_text(self.help)
Registers another :class:`Command` with this group. If the name is not provided, the name of the command is used. def add_command(self, cmd, name=None): """Registers another :class:`Command` with this group. If the name is not provided, the name of the command is used. """ nam...
Similar to :func:`pass_context`, but only pass the object on the context onwards (:attr:`Context.obj`). This is useful if that object represents the state of a nested system. def pass_obj(f): """Similar to :func:`pass_context`, but only pass the object on the context onwards (:attr:`Context.obj`). Th...
Attaches an option to the command. All positional arguments are passed as parameter declarations to :class:`Option`; all keyword arguments are forwarded unchanged (except ``cls``). This is equivalent to creating an :class:`Option` instance manually and attaching it to the :attr:`Command.params` list. ...
Adds a ``--version`` option which immediately ends the program printing out the version number. This is implemented as an eager option that prints the version and exits the program in the callback. :param version: the version number to show. If not provided Click attempts an auto disc...
Returns a Basic Auth string. def _basic_auth_str(username, password): """Returns a Basic Auth string.""" authstr = 'Basic ' + to_native_string( b64encode(('%s:%s' % (username, password)).encode('latin1')).strip() ) return authstr
List topic from external datastore Arguments: topic (str): One or more topics, e.g. ("project", "item", "task") root (str, optional): Absolute path to where projects reside, defaults to os.getcwd() backend (callable, optional): Function to call with absolute path as ...
Dump current environment as a dictionary Arguments: context (dict, optional): Current context, defaults to the current environment. def dump(context=os.environ): """Dump current environment as a dictionary Arguments: context (dict, optional): Current context, defaults ...
Return the be current working directory def cwd(): """Return the be current working directory""" cwd = os.environ.get("BE_CWD") if cwd and not os.path.isdir(cwd): sys.stderr.write("ERROR: %s is not a directory" % cwd) sys.exit(lib.USER_ERROR) return cwd or os.getcwd().replace("\\", "/")
Write script to a temporary directory Arguments: script (list): Commands which to put into a file Returns: Absolute path to script def write_script(script, tempdir): """Write script to a temporary directory Arguments: script (list): Commands which to put into a file Retu...
Write aliases to temporary directory Arguments: aliases (dict): {name: value} dict of aliases tempdir (str): Absolute path to where aliases will be stored def write_aliases(aliases, tempdir): """Write aliases to temporary directory Arguments: aliases (dict): {name: value} dict of ...
Return presets directory def presets_dir(): """Return presets directory""" default_presets_dir = os.path.join( os.path.expanduser("~"), ".be", "presets") presets_dir = os.environ.get(BE_PRESETSDIR) or default_presets_dir if not os.path.exists(presets_dir): os.makedirs(presets_dir) r...
Physically delete local preset Arguments: preset (str): Name of preset def remove_preset(preset): """Physically delete local preset Arguments: preset (str): Name of preset """ preset_dir = os.path.join(presets_dir(), preset) try: shutil.rmtree(preset_dir) except...
requests.get wrapper def get(path, **kwargs): """requests.get wrapper""" token = os.environ.get(BE_GITHUB_API_TOKEN) if token: kwargs["headers"] = { "Authorization": "token %s" % token } try: response = requests.get(path, verify=False, **kwargs) if response....
Evaluate whether gist is a be package Arguments: gist (str): username/id pair e.g. mottosso/2bb4651a05af85711cde def _gist_is_preset(repo): """Evaluate whether gist is a be package Arguments: gist (str): username/id pair e.g. mottosso/2bb4651a05af85711cde """ _, gistid = repo.sp...
Evaluate whether GitHub repository is a be package Arguments: gist (str): username/id pair e.g. mottosso/be-ad def _repo_is_preset(repo): """Evaluate whether GitHub repository is a be package Arguments: gist (str): username/id pair e.g. mottosso/be-ad """ package_template = "htt...
Return remote presets hosted on GitHub def github_presets(): """Return remote presets hosted on GitHub""" addr = ("https://raw.githubusercontent.com" "/mottosso/be-presets/master/presets.json") response = get(addr) if response.status_code == 404: lib.echo("Could not connect with pr...
Copy contents of preset into new project If package.json contains the key "contents", limit the files copied to those present in this list. Arguments: preset_dir (str): Absolute path to preset project_dir (str): Absolute path to new project def copy_preset(preset_dir, project_dir): ""...
Resolve {@} occurences by expansion Given a dictionary {"a": "{@b}/x", "b": "{key}/y"} Return {"a", "{key}/y/x", "b": "{key}/y"} { key: {@reference}/{variable} # pattern } In plain english, it looks within `pattern` for references and replaces them with the value of the matching k...
Adds a (name, value) pair, doesn't overwrite the value if it already exists. >>> headers = HTTPHeaderDict(foo='bar') >>> headers.add('Foo', 'baz') >>> headers['foo'] 'bar, baz' def add(self, key, val): """Adds a (name, value) pair, doesn't overwrite the value if it alre...
Returns a list of all the values for the named field. Returns an empty list if the key doesn't exist. def getlist(self, key): """Returns a list of all the values for the named field. Returns an empty list if the key doesn't exist.""" try: vals = _dict_getitem(self, key.lower...
Iterate over all header lines, including duplicate ones. def iteritems(self): """Iterate over all header lines, including duplicate ones.""" for key in self: vals = _dict_getitem(self, key) for val in vals[1:]: yield vals[0], val
Iterate over all headers, merging duplicate ones together. def itermerged(self): """Iterate over all headers, merging duplicate ones together.""" for key in self: val = _dict_getitem(self, key) yield val[0], ', '.join(val[1:])
Read headers from a Python 2 httplib message object. def from_httplib(cls, message, duplicates=('set-cookie',)): # Python 2 """Read headers from a Python 2 httplib message object.""" ret = cls(message.items()) # ret now contains only the last header line for each duplicate. # Importing ...
Make a request using :meth:`urlopen` with the ``fields`` encoded in the url. This is useful for request methods like GET, HEAD, DELETE, etc. def request_encode_url(self, method, url, fields=None, **urlopen_kw): """ Make a request using :meth:`urlopen` with the ``fields`` encoded in the ...
Converts a value into a valid string. def make_str(value): """Converts a value into a valid string.""" if isinstance(value, bytes): try: return value.decode(sys.getfilesystemencoding()) except UnicodeError: return value.decode('utf-8', 'replace') return text_type(val...
Prints a message plus a newline to the given file or stdout. On first sight, this looks like the print function, but it has improved support for handling Unicode and binary data that does not fail no matter how badly configured the system is. Primarily it means that you can print binary data as well a...
Determine subshell matching the currently running shell The shell is determined by either a pre-defined BE_SHELL environment variable, or, if none is found, via psutil which looks at the parent process directly through system-level calls. For example, is `be` is run from cmd.exe, then the full ...
Return platform for the current shell, e.g. windows or unix def platform(): """Return platform for the current shell, e.g. windows or unix""" executable = parent() basename = os.path.basename(executable) basename, _ = os.path.splitext(basename) if basename in ("bash", "sh"): return "unix" ...
Determine subshell command for subprocess.call Arguments: parent (str): Absolute path to parent shell executable def cmd(parent): """Determine subshell command for subprocess.call Arguments: parent (str): Absolute path to parent shell executable """ shell_name = os.path.basename...
Produce the be environment The environment is an exact replica of the active environment of the current process, with a few additional variables, all of which are listed below. def context(root, project=""): """Produce the be environment The environment is an exact replica of the active envir...
Return a random name Example: >> random_name() dizzy_badge >> random_name() evasive_cactus def random_name(): """Return a random name Example: >> random_name() dizzy_badge >> random_name() evasive_cactus """ adj = _data.adjectives[...
Return whether or not `path` is a project Arguments: path (str): Absolute path def isproject(path): """Return whether or not `path` is a project Arguments: path (str): Absolute path """ try: if os.path.basename(path)[0] in (".", "_"): return False if ...
Print to the console Arguments: text (str): Text to print to the console silen (bool, optional): Whether or not to produce any output newline (bool, optional): Whether or not to append a newline. def echo(text, silent=False, newline=True): """Print to the console Arguments: ...
List projects at `root` Arguments: root (str): Absolute path to the `be` root directory, typically the current working directory. def list_projects(root, backend=os.listdir): """List projects at `root` Arguments: root (str): Absolute path to the `be` root directory, ...
List a projects inventory Given a project, simply list the contents of `inventory.yaml` Arguments: root (str): Absolute path to the `be` root directory, typically the current working directory. inventory (dict): inventory.yaml def list_inventory(inventory): """List a projects ...
List contents for resolved template Resolve a template as far as possible via the given `topics`. For example, if a template supports 5 arguments, but only 3 are given, resolve the template until its 4th argument and list the contents thereafter. In some cases, an additional path is present follow...
Return {item: binding} from {binding: item} Protect against items with additional metadata and items whose type is a number Returns: Dictionary of inverted inventory def invert_inventory(inventory): """Return {item: binding} from {binding: item} Protect against items with additional meta...
Return absolute path to development directory Arguments: templates (dict): templates.yaml inventory (dict): inventory.yaml context (dict): The be context, from context() topics (list): Arguments to `in` user (str): Current `be` user item (str): Item from template-bin...
Return absolute path to development directory Arguments: templates (dict): templates.yaml inventory (dict): inventory.yaml context (dict): The be context, from context() topics (list): Arguments to `in` user (str): Current `be` user def fixed_development_directory(templates...
Convert context replacement fields Example: BE_KEY=value -> {"key": "value} Arguments: context (dict): The current context def replacement_fields_from_context(context): """Convert context replacement fields Example: BE_KEY=value -> {"key": "value} Arguments: cont...
Get binding from `topics` via `key` Example: {0} == hello --> be in hello world {1} == world --> be in hello world Returns: Single topic matching the key Raises: IndexError (int): With number of required arguments for the key def item_from_topics(key, topics):...
Return pattern for name Arguments: templates (dict): Current templates name (str): Name of name def pattern_from_template(templates, name): """Return pattern for name Arguments: templates (dict): Current templates name (str): Name of name """ if name not in templ...
Return binding for `item` Example: asset: - myasset The binding is "asset" Arguments: project: Name of project item (str): Name of item def binding_from_item(inventory, item): """Return binding for `item` Example: asset: - myasset The...
Resolve the be.yaml environment key Features: - Lists, e.g. ["/path1", "/path2"] - Environment variable references, via $ - Replacement field references, e.g. {key} - Topic references, e.g. {1} def parse_environment(fields, context, topics): """Resolve the be.yaml environment k...
Resolve the be.yaml redirect key Arguments: redirect (dict): Source/destination pairs, e.g. {BE_ACTIVE: ACTIVE} topics (tuple): Topics from which to sample, e.g. (project, item, task) context (dict): Context from which to sample def parse_redirect(redirect, topics, context): """Resolve...