code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
r # https://www.sharelatex.com/learn/List_of_Greek_letters_and_math_symbols if x is None or k is None or theta is None: return None # noinspection PyUnresolvedReferences return 1 / (1 + np.exp(-k * (x - theta)))
def logistic(x: Union[float, np.ndarray], k: float, theta: float) -> Optional[float]
r""" Standard logistic function. .. math:: y = \frac {1} {1 + e^{-k (x - \theta)}} Args: x: :math:`x` k: :math:`k` theta: :math:`\theta` Returns: :math:`y`
4.594197
5.227521
0.878848
r if y is None or k is None or theta is None: return None # noinspection PyUnresolvedReferences return (np.log((1 / y) - 1) / -k) + theta
def inv_logistic(y: Union[float, np.ndarray], k: float, theta: float) -> Optional[float]
r""" Inverse standard logistic function: .. math:: x = ( log( \frac {1} {y} - 1) / -k ) + \theta Args: y: :math:`y` k: :math:`k` theta: :math:`\theta` Returns: :math:`x`
4.829741
3.964132
1.21836
# first search bounding boxes # idx.intersection method modifies input if it is a list try: tmp = tuple(point) except TypeError: return None # point must be in the form (minx, miny, maxx, maxy) or (x, y) if len(tmp) not in [2, 4]: ...
def get_object(self, point, buffer_size=0, multiple=False)
lookup object based on point as [longitude, latitude]
5.829327
5.887565
0.990108
geojson = json.loads(self.read(src)) idx = index.Index() data_store = {} for i, feature in enumerate(geojson['features']): feature = self._build_obj(feature) idx.insert(i, feature['geometry'].bounds) data_store[i] = feature return data...
def _build_from_geojson(self, src)
Build a RTree index to disk using bounding box of each feature
3.922487
3.512157
1.116831
lon, lat = point geohash = Geohash.encode(lat, lon, precision=self.precision) key = (geohash, buffer_size, multiple) if key in self.geohash_cache: # cache hit on geohash self.hit += 1 #print self.hit, self.miss return self.geohash_...
def get(self, point, buffer_size=0, multiple=False)
lookup state and county based on geohash of coordinates from tweet
3.530353
3.455351
1.021706
suites = Converter.read_nose(in_file_nose) Converter.write_unitth(suites, out_dir_unitth)
def run(in_file_nose, out_dir_unitth)
Convert nose-style test reports to UnitTH-style test reports by splitting modules into separate XML files Args: in_file_nose (:obj:`str`): path to nose-style test report out_file_unitth (:obj:`str`): path to save UnitTH-style test reports
4.80436
4.885655
0.98336
suites = {} doc_xml = minidom.parse(in_file) suite_xml = doc_xml.getElementsByTagName("testsuite")[0] for case_xml in suite_xml.getElementsByTagName('testcase'): classname = case_xml.getAttribute('classname') if classname not in suites: su...
def read_nose(in_file)
Parse nose-style test reports into a `dict` Args: in_file (:obj:`str`): path to nose-style test report Returns: :obj:`dict`: dictionary of test suites
1.49655
1.505374
0.994138
if not os.path.isdir(out_dir): os.mkdir(out_dir) for classname, cases in suites.items(): doc_xml = minidom.Document() suite_xml = doc_xml.createElement('testsuite') suite_xml.setAttribute('name', classname) suite_xml.setAttribute('te...
def write_unitth(suites, out_dir)
Write UnitTH-style test reports Args: suites (:obj:`dict`): dictionary of test suites out_dir (:obj:`str`): path to save UnitTH-style test reports
1.36245
1.370997
0.993766
ax = kwargs.pop("ax",current_axes()) lon,lat = pca.plane_errors('upper', n=1000) ax.plot(lon,lat,'-') lon,lat = pca.plane_errors('lower', n=1000) ax.plot(lon,lat,'-') ax.plane(*pca.strike_dip())
def error_asymptotes(pca,**kwargs)
Plots asymptotic error bounds for hyperbola on a stereonet.
5.571469
5.478981
1.01688
result = session.execute(sql) # type: ResultProxy fieldnames = result.keys() rows = result.fetchall() return rows, fieldnames
def get_rows_fieldnames_from_raw_sql( session: Union[Session, Engine, Connection], sql: str) -> Tuple[Sequence[Sequence[Any]], Sequence[str]]
Returns results and column names from a query. Args: session: SQLAlchemy :class:`Session`, :class:`Engine`, or :class:`Connection` object sql: raw SQL to execure Returns: ``(rows, fieldnames)`` where ``rows`` is the usual set of results and ``fieldnames`` are the na...
3.173371
3.512466
0.90346
# works if you pass a connection or a session or an engine; all have # the execute() method query = select([func.count()]).select_from(table(tablename)) for criterion in criteria: query = query.where(criterion) return session.execute(query).scalar()
def count_star(session: Union[Session, Engine, Connection], tablename: str, *criteria: Any) -> int
Returns the result of ``COUNT(*)`` from the specified table (with additional ``WHERE`` criteria if desired). Args: session: SQLAlchemy :class:`Session`, :class:`Engine`, or :class:`Connection` object tablename: name of the table criteria: optional SQLAlchemy "where" criteria...
5.324663
6.987205
0.762059
exists_clause = exists().select_from(table_) # ... EXISTS (SELECT * FROM tablename) for criterion in criteria: exists_clause = exists_clause.where(criterion) # ... EXISTS (SELECT * FROM tablename WHERE ...) if session.get_bind().dialect.name == SqlaDialectName.MSSQL: query = se...
def exists_in_table(session: Session, table_: Table, *criteria: Any) -> bool
Implements an efficient way of detecting if a record or records exist; should be faster than ``COUNT(*)`` in some circumstances. Args: session: SQLAlchemy :class:`Session`, :class:`Engine`, or :class:`Connection` object table_: SQLAlchemy :class:`Table` object criteria: opti...
3.0126
3.382131
0.89074
return exists_in_table(session, table(tablename), *criteria)
def exists_plain(session: Session, tablename: str, *criteria: Any) -> bool
Implements an efficient way of detecting if a record or records exist; should be faster than COUNT(*) in some circumstances. Args: session: SQLAlchemy :class:`Session`, :class:`Engine`, or :class:`Connection` object tablename: name of the table criteria: optional SQLAlchemy ...
11.834219
12.469987
0.949016
rows = session.execute(select_statement) # type: ResultProxy try: return [row[0] for row in rows] except ValueError as e: raise MultipleResultsFound(str(e))
def fetch_all_first_values(session: Session, select_statement: Select) -> List[Any]
Returns a list of the first values in each row returned by a ``SELECT`` query. A Core version of this sort of thing: http://xion.io/post/code/sqlalchemy-query-values.html Args: session: SQLAlchemy :class:`Session` object select_statement: SQLAlchemy :class:`Select` object Returns:...
3.459984
4.119025
0.840001
opens_up = kwargs.pop('opens_up', True) center = kwargs.pop('center', defaults['center']) th = N.linspace(0,2*N.pi,kwargs.pop('n', 500)) vals = [N.tan(th),1/N.cos(th)] if not opens_up: vals = vals[::-1] x = axes[0]*vals[0]+center[0] y = axes[1]*vals[1]+center[1] extrema =...
def hyperbola(axes, **kwargs)
Plots a hyperbola that opens along y axis
3.811562
3.825517
0.996352
ax1 = axes.copy()[::-1]*scalar center = ax1[1]*N.sqrt(2)*scalar return ax1, center
def __reverse_ellipse(axes, scalar=1)
This method doesn't work as well
16.347496
14.789935
1.105312
# noqa engine = get_engine_from_session(session) if is_sqlserver(engine): quoted_tablename = quote_identifier(tablename, engine) session.execute( "ALTER TABLE {} NOCHECK CONSTRAINT all".format( quoted_tablename)) yield session.execute( ...
def if_sqlserver_disable_constraints(session: SqlASession, tablename: str) -> None
If we're running under SQL Server, disable constraint checking for the specified table while the resource is held. Args: session: SQLAlchemy :class:`Session` tablename: table name See https://stackoverflow.com/questions/123558/sql-server-2005-t-sql-to-temporarily-disable-a-trigger
3.579114
3.655969
0.978978
with if_sqlserver_disable_constraints(session, tablename): with if_sqlserver_disable_triggers(session, tablename): yield
def if_sqlserver_disable_constraints_triggers(session: SqlASession, tablename: str) -> None
If we're running under SQL Server, disable triggers AND constraints for the specified table while the resource is held. Args: session: SQLAlchemy :class:`Session` tablename: table name
3.555211
4.575619
0.77699
# when given a string, assume user wants to index raw json if isinstance(data, string_types): return '{"index": {}}', data # make sure we don't alter the action data = data.copy() op_type = data.pop(EsBulk.OP_TYPE, EsBulk.INDEX) action = ActionParse...
def expand_action(data)
From one document or action definition passed in by the user extract the action/data lines needed for elasticsearch's :meth:`~elasticsearch.Elasticsearch.bulk` api. :return es format to bulk doc
8.500357
7.789841
1.091211
inserted = [] errors = [] all = [] for deferred_bulk in self.streaming_bulk(actions, **kwargs): bulk_results = yield deferred_bulk for ok, item in bulk_results: # go through request-response pairs and detect failures all.a...
def bulk(self, actions, stats_only=False, verbose=False, **kwargs)
Helper for the :meth:`~elasticsearch.Elasticsearch.bulk` api that provides a more human friendly interface - it consumes an iterator of actions and sends them to elasticsearch in chunks. It returns a tuple with summary information - number of successfully executed actions and either list of ...
5.668608
5.555952
1.020277
actions = list(map(expand_action_callback, actions)) for bulk_actions in self._chunk_actions(actions, chunk_size, max_chunk_bytes): yield self._process_bulk_chunk(bulk_actions, raise_on_exception, raise_on_error, **kwargs)
def streaming_bulk(self, actions, chunk_size=500, max_chunk_bytes=100 * 1024 * 1024, raise_on_error=True, expand_action_callback=ActionParser.expand_action, raise_on_exception=True, **kwargs)
Streaming bulk consumes actions from the iterable passed in and return the results of all bulk data :func:`~elasticsearch.helpers.bulk` which is a wrapper around streaming bulk that returns summary information about the bulk operation once the entire input is consumed and sent. :arg acti...
2.521049
3.835706
0.657258
# if raise on error is set, we need to collect errors per chunk before # raising them resp = None try: # send the actual request actions = "{}\n".format('\n'.join(bulk_actions)) resp = yield self.client.bulk(actions, **kwargs) except ...
def _process_bulk_chunk(self, bulk_actions, raise_on_exception=True, raise_on_error=True, **kwargs)
Send a bulk request to elasticsearch and process the output.
4.98183
4.897813
1.017154
return % { 'LanguageCode': language, 'SiteKey': site_key, 'Theme': theme, 'Type': d_type, 'Size': size, 'Fallback': fallback, }
def displayhtml(site_key, language='', theme='light', fallback=False, d_type='image', size='normal')
Gets the HTML to display for reCAPTCHA site_key -- The site key language -- The language code for the widget. theme -- The color theme of the widget. `light` or `dark` fallback -- Old version recaptcha. d_type -- The type of CAPTCHA to serve. `image` or `audio` size -- The size of the dispalyed...
3.527226
3.706818
0.951551
if not (recaptcha_response_field and len(recaptcha_response_field)): return RecaptchaResponse( is_valid=False, error_code='incorrect-captcha-sol' ) def encode_if_necessary(s): if isinstance(s, unicode): return s.encode('utf-8') return s ...
def submit(recaptcha_response_field, secret_key, remoteip, verify_server=VERIFY_SERVER)
Submits a reCAPTCHA request for verification. Returns RecaptchaResponse for the request recaptcha_response_field -- The value from the form secret_key -- your reCAPTCHA secret key remoteip -- the user's ip address
1.950544
1.962263
0.994028
if alembic_base_dir is None: alembic_base_dir = os.path.dirname(alembic_config_filename) os.chdir(alembic_base_dir) # so the directory in the config file works config = Config(alembic_config_filename) script = ScriptDirectory.from_config(config) with EnvironmentContext(config, ...
def get_head_revision_from_alembic( alembic_config_filename: str, alembic_base_dir: str = None, version_table: str = DEFAULT_ALEMBIC_VERSION_TABLE) -> str
Ask Alembic what its head revision is (i.e. where the Python code would like the database to be at). Arguments: alembic_config_filename: config filename alembic_base_dir: directory to start in, so relative paths in the config file work. version_table: table name for Alembic ...
2.640147
2.552226
1.034449
engine = create_engine(database_url) conn = engine.connect() opts = {'version_table': version_table} mig_context = MigrationContext.configure(conn, opts=opts) return mig_context.get_current_revision()
def get_current_revision( database_url: str, version_table: str = DEFAULT_ALEMBIC_VERSION_TABLE) -> str
Ask the database what its current revision is. Arguments: database_url: SQLAlchemy URL for the database version_table: table name for Alembic versions
4.049372
3.274796
1.236526
# Where we are head_revision = get_head_revision_from_alembic( alembic_config_filename=alembic_config_filename, alembic_base_dir=alembic_base_dir, version_table=version_table ) log.info("Intended database version: {}", head_revision) # Where we want to be current_re...
def get_current_and_head_revision( database_url: str, alembic_config_filename: str, alembic_base_dir: str = None, version_table: str = DEFAULT_ALEMBIC_VERSION_TABLE) -> Tuple[str, str]
Returns a tuple of ``(current_revision, head_revision)``; see :func:`get_current_revision` and :func:`get_head_revision_from_alembic`. Arguments: database_url: SQLAlchemy URL for the database alembic_config_filename: config filename alembic_base_dir: directory to start in, so relative p...
2.425182
2.473118
0.980617
if alembic_base_dir is None: alembic_base_dir = os.path.dirname(alembic_config_filename) os.chdir(alembic_base_dir) # so the directory in the config file works config = Config(alembic_config_filename) script = ScriptDirectory.from_config(config) # noinspection PyUnusedLocal,PyProtect...
def upgrade_database( alembic_config_filename: str, alembic_base_dir: str = None, starting_revision: str = None, destination_revision: str = "head", version_table: str = DEFAULT_ALEMBIC_VERSION_TABLE, as_sql: bool = False) -> None
Use Alembic to upgrade our database. See http://alembic.readthedocs.org/en/latest/api/runtime.html but also, in particular, ``site-packages/alembic/command.py`` Arguments: alembic_config_filename: config filename alembic_base_dir: directory to start in, so relative...
2.841984
2.897255
0.980923
# noqa _, _, existing_version_filenames = next(os.walk(alembic_versions_dir), (None, None, [])) existing_version_filenames = [ x for x in existing_version_filenames if x != "__init__.py"] log.debug("Existing Alembic version script filenames: {!r}", ...
def create_database_migration_numbered_style( alembic_ini_file: str, alembic_versions_dir: str, message: str, n_sequence_chars: int = 4) -> None
Create a new Alembic migration script. Alembic compares the **state of the database** to the **state of the metadata**, and generates a migration that brings the former up to the latter. (It does **not** compare the most recent revision to the current metadata, so make sure your database is up to d...
2.405195
2.272548
1.058369
# noqa script = ScriptDirectory.from_config(config) starting_rev = None if ":" in revision: if not sql: raise CommandError("Range revision not allowed") starting_rev, revision = revision.split(':', 2) # noinspection PyUnusedLocal def do_stamp(rev: str, context): ...
def stamp_allowing_unusual_version_table( config: Config, revision: str, sql: bool = False, tag: str = None, version_table: str = DEFAULT_ALEMBIC_VERSION_TABLE) -> None
Stamps the Alembic version table with the given revision; don't run any migrations. This function is a clone of ``alembic.command.stamp()``, but allowing ``version_table`` to change. See http://alembic.zzzcomputing.com/en/latest/api/commands.html#alembic.command.stamp
4.46009
3.810395
1.170506
safe_add_http_request_context_to_behave_context(context) table_as_json = dict(context.table) url_path = url_path_str_format % table_as_json context.http_request_context.url_path = url_path
def set_url_path_with_params(context, url_path_str_format)
Parameters: +------+--------+ | key | value | +======+========+ | key1 | value1 | +------+--------+ | key2 | value2 | +------+--------+
5.189147
5.865863
0.884635
safe_add_http_request_context_to_behave_context(context) headers = dict() for row in context.table: headers[row["header_name"]] = row["header_value"] context.http_request_context.headers = headers
def set_headers(context)
Parameters: +--------------+---------------+ | header_name | header_value | +==============+===============+ | header1 | value1 | +--------------+---------------+ | header2 | value2 | +--------------+---------------+
5.79729
5.165192
1.122377
safe_add_http_request_context_to_behave_context(context) context.http_request_context.body_params = get_parameters(context) context.http_request_context.renderer = FormRenderer()
def set_form_parameters(context)
Parameters: +-------------+--------------+ | param_name | param_value | +=============+==============+ | param1 | value1 | +-------------+--------------+ | param2 | value2 | +-------------+--------------+
7.98461
8.958776
0.891261
safe_add_http_request_context_to_behave_context(context) files = dict() for row in context.table: files[row["param_name"]] = row["path_to_file"] context.http_request_context.files = files
def set_body_files(context)
Parameters: +-------------+--------------+ | param_name | path_to_file | +=============+==============+ | param1 | value1 | +-------------+--------------+ | param2 | value2 | +-------------+--------------+
6.711713
5.546677
1.210042
safe_add_http_request_context_to_behave_context(context) set_query_parameters(context) send_http_request(context, method)
def send_http_request_with_query_parameters(context, method)
Parameters: +-------------+--------------+ | param_name | param_value | +=============+==============+ | param1 | value1 | +-------------+--------------+ | param2 | value2 | +-------------+--------------+
6.522861
7.601023
0.858156
safe_add_http_request_context_to_behave_context(context) set_body_parameters(context) send_http_request(context, method)
def send_http_request_with_body_parameters(context, method)
Parameters: +-------------+--------------+ | param_name | param_value | +=============+==============+ | param1 | value1 | +-------------+--------------+ | param2 | value2 | +-------------+--------------+
6.436985
7.722753
0.833509
safe_add_http_request_context_to_behave_context(context) set_form_parameters(context) send_http_request(context, method)
def send_http_request_with_form_parameters(context, method)
Parameters: +-------------+--------------+ | param_name | param_value | +=============+==============+ | param1 | value1 | +-------------+--------------+ | param2 | value2 | +-------------+--------------+
6.473761
7.684319
0.842464
safe_add_http_request_context_to_behave_context(context) context.http_request_context.body_params = json.loads(context.text) context.http_request_context.renderer = JSONRenderer() send_http_request(context, method)
def send_http_request_with_json(context, method)
Parameters: .. code-block:: json { "param1": "value1", "param2": "value2", "param3": { "param31": "value31" } }
4.831185
5.082429
0.950566
args = shlex.split(command) ret = subprocess.check_output(args) # this needs Python 2.7 or higher return ret
def get_external_command_output(command: str) -> bytes
Takes a command-line command, executes it, and returns its ``stdout`` output. Args: command: command string Returns: output from the command as ``bytes``
6.854086
8.436994
0.812385
# Python arrays indexes are zero-based, i.e. an array is indexed from # 0 to len(array)-1. # The range/xrange commands, by default, start at 0 and go to one less # than the maximum specified. # print commands processes = [] # type: List[subprocess.Popen] for i in range(len(commands)):...
def get_pipe_series_output(commands: Sequence[str], stdinput: BinaryIO = None) -> bytes
Get the output from a piped series of commands. Args: commands: sequence of command strings stdinput: optional ``stdin`` data to feed into the start of the pipe Returns: ``stdout`` from the end of the pipe
3.60055
3.755575
0.958721
log.info("Launching external file: {!r}", filename) try: if sys.platform.startswith('linux'): cmdargs = ["xdg-open", filename] # log.debug("... command: {!r}", cmdargs) subprocess.call(cmdargs) else: # log.debug("... with os.startfile()") ...
def launch_external_file(filename: str, raise_if_fails: bool = False) -> None
Launches a file using the operating system's standard launcher. Args: filename: file to launch raise_if_fails: raise any exceptions from ``subprocess.call(["xdg-open", filename])`` (Linux) or ``os.startfile(filename)`` (otherwise)? If not, exceptions are suppress...
3.449233
3.105215
1.110787
# noqa parent = psutil.Process(pid) to_kill = parent.children(recursive=True) # type: List[psutil.Process] if including_parent: to_kill.append(parent) for proc in to_kill: proc.kill() # SIGKILL gone, still_alive = psutil.wait_procs(to_kill, timeout=timeout_s) return gone,...
def kill_proc_tree(pid: int, including_parent: bool = True, timeout_s: float = 5) \ -> Tuple[Set[psutil.Process], Set[psutil.Process]]
Kills a tree of processes, starting with the parent. Slightly modified from https://stackoverflow.com/questions/1230669/subprocess-deleting-child-processes-in-windows. Args: pid: process ID of the parent including_parent: kill the parent too? timeout_s: timeout to wait for processes...
2.104906
2.436064
0.86406
return "mysql+{driver}://{u}:{p}@{host}:{port}/{db}?charset={cs}".format( driver=driver, host=host, port=port, db=dbname, u=username, p=password, cs=charset, )
def make_mysql_url(username: str, password: str, dbname: str, driver: str = "mysqldb", host: str = "localhost", port: int = 3306, charset: str = "utf8") -> str
Makes an SQLAlchemy URL for a MySQL database.
2.47173
2.18035
1.133639
absfile = os.path.abspath(filename) return "sqlite://{host}/{path}".format(host="", path=absfile)
def make_sqlite_url(filename: str) -> str
Makes an SQLAlchemy URL for a SQLite database.
8.446456
6.657257
1.268759
engine = dbsession.bind assert isinstance(engine, Engine) return engine
def get_engine_from_session(dbsession: Session) -> Engine
Gets the SQLAlchemy :class:`Engine` from a SQLAlchemy :class:`Session`.
4.65756
3.262853
1.42745
raw_url = engine.url # type: str url_obj = make_url(raw_url) # type: URL return repr(url_obj)
def get_safe_url_from_engine(engine: Engine) -> str
Gets a URL from an :class:`Engine`, obscuring the password.
5.767156
4.639493
1.243058
return int(text) if text.isdigit() else text
def atoi(text: str) -> Union[int, str]
Converts strings to integers if they're composed of digits; otherwise returns the strings unchanged. One way of sorting strings with numbers; it will mean that ``"11"`` is more than ``"2"``.
3.035286
5.204561
0.583197
# noqa return [atoi(c) for c in re.split(r'(\d+)', text)]
def natural_keys(text: str) -> List[Union[int, str]]
Sort key function. Returns text split into string/number parts, for natural sorting; as per http://stackoverflow.com/questions/5967500/how-to-correctly-sort-a-string-with-a-number-inside Example (as per the source above): .. code-block:: python >>> from cardinal_pythonlib.sort...
2.51326
6.658477
0.377453
try: if CONTENT_TYPE_HEADER_NAME in headers: if XMLRenderer.DEFAULT_CONTENT_TYPE == headers[CONTENT_TYPE_HEADER_NAME]: xml_parsed = parseString(body) pretty_xml_as_string = xml_parsed.toprettyxml() return pretty_xml_as_string elif ...
def _get_pretty_body(headers, body)
Return a pretty printed body using the Content-Type header information. :param headers: Headers for the request/response (dict) :param body: Body to pretty print (string) :return: Body pretty printed (string)
2.530465
2.441604
1.036394
log_msg = '\n>>>>>>>>>>>>>>>>>>>>> Request >>>>>>>>>>>>>>>>>>> \n' log_msg += '\t> Method: %s\n' % method log_msg += '\t> Url: %s\n' % url if query_params is not None: log_msg += '\t> Query params: {}\n'.format(str(query_params)) if headers is not None: log_msg += '\t> Headers:...
def log_print_request(method, url, query_params=None, headers=None, body=None)
Log an HTTP request data in a user-friendly representation. :param method: HTTP method :param url: URL :param query_params: Query parameters in the URL :param headers: Headers (dict) :param body: Body (raw body, string) :return: None
2.462744
2.499528
0.985283
log_msg = '\n<<<<<<<<<<<<<<<<<<<<<< Response <<<<<<<<<<<<<<<<<<\n' log_msg += '\t< Response code: {}\n'.format(str(status_code)) if headers is not None: log_msg += '\t< Headers:\n{}\n'.format(json.dumps(dict(headers), sort_keys=True, indent=4)) try: log_msg += '\t< Payload received...
def log_print_response(status_code, response, headers=None)
Log an HTTP response data in a user-friendly representation. :param status_code: HTTP Status Code :param response: Raw response content (string) :param headers: Headers in the response (dict) :return: None
2.975578
2.986777
0.996251
return {ARGS_LABEL: args, KWARGS_LABEL: kwargs}
def args_kwargs_to_initdict(args: ArgsList, kwargs: KwargsDict) -> InitDict
Converts a set of ``args`` and ``kwargs`` to an ``InitDict``.
9.86857
8.128315
1.214098
newdict = {} for k, v in d.items(): if k.startswith('_'): k = k[1:] if k in newdict: raise ValueError("Attribute conflict: _{k}, {k}".format(k=k)) newdict[k] = v return newdict
def strip_leading_underscores_from_keys(d: Dict) -> Dict
Clones a dictionary, removing leading underscores from key names. Raises ``ValueError`` if this causes an attribute conflict.
3.395251
2.669064
1.272076
if (not isinstance(initdict, dict) or ARGS_LABEL not in initdict or KWARGS_LABEL not in initdict): raise ValueError("Not an InitDict dictionary")
def verify_initdict(initdict: InitDict) -> None
Ensures that its parameter is a proper ``InitDict``, or raises ``ValueError``.
6.447123
5.787374
1.113998
args = d.get(ARGS_LABEL, []) kwargs = d.get(KWARGS_LABEL, {}) # noinspection PyArgumentList return cls(*args, **kwargs)
def initdict_to_instance(d: InitDict, cls: ClassType) -> Any
Converse of simple_to_dict(). Given that JSON dictionary, we will end up re-instantiating the class with .. code-block:: python d = {'a': 1, 'b': 2, 'c': 3} new_x = SimpleClass(**d) We'll also support arbitrary creation, by using both ``*args`` and ``**kwargs``.
4.082651
4.595021
0.888494
def wrapper(obj: Instance) -> InitDict: result = init_kwargs_fn(obj) if check_result: if not isinstance(result, dict): raise ValueError( "Class {} failed to provide a kwargs dict and " "provided instead: {}".format(typename, re...
def wrap_kwargs_to_initdict(init_kwargs_fn: InitKwargsFnType, typename: str, check_result: bool = True) \ -> InstanceToInitDictFnType
Wraps a function producing a ``KwargsDict``, making it into a function producing an ``InitDict``.
4.018341
4.005485
1.00321
def wrapper(obj: Instance) -> InitDict: result = init_args_kwargs_fn(obj) if check_result: if (not isinstance(result, tuple) or not len(result) == 2 or not isinstance(result[0], list) or not isinstance(result[1], dict)): ...
def wrap_args_kwargs_to_initdict(init_args_kwargs_fn: InitArgsKwargsFnType, typename: str, check_result: bool = True) \ -> InstanceToInitDictFnType
Wraps a function producing a ``KwargsDict``, making it into a function producing an ``InitDict``.
3.088799
3.093281
0.998551
def custom_instance_to_initdict(x: Instance) -> InitDict: kwargs = {} for a in attributes: kwargs[a] = getattr(x, a) return kwargs_to_initdict(kwargs) return custom_instance_to_initdict
def make_instance_to_initdict(attributes: List[str]) -> InstanceToDictFnType
Returns a function that takes an object (instance) and produces an ``InitDict`` enabling its re-creation.
2.869761
2.983288
0.961946
typename = cls.__qualname__ # preferable to __name__ # ... __name__ looks like "Thing" and is ambiguous # ... __qualname__ looks like "my.module.Thing" and is not if obj_to_dict_fn and dict_to_obj_fn: descriptor = JsonDescriptor( typename=typename, obj_to_dict_fn=ob...
def register_class_for_json( cls: ClassType, method: str = METHOD_SIMPLE, obj_to_dict_fn: InstanceToDictFnType = None, dict_to_obj_fn: DictToInstanceFnType = initdict_to_instance, default_factory: DefaultFactoryFnType = None) -> None
Registers the class cls for JSON serialization. - If both ``obj_to_dict_fn`` and dict_to_obj_fn are registered, the framework uses these to convert instances of the class to/from Python dictionaries, which are in turn serialized to JSON. - Otherwise: .. code-block:: python if metho...
2.542264
2.436228
1.043525
pp = pprint.PrettyPrinter(indent=4, stream=file) print("Type map: ", file=file) pp.pprint(TYPE_MAP)
def dump_map(file: TextIO = sys.stdout) -> None
Prints the JSON "registered types" map to the specified file.
4.965281
3.723939
1.333341
if TYPE_LABEL in d: typename = d.get(TYPE_LABEL) if typename in TYPE_MAP: if DEBUG: log.debug("Deserializing: {!r}", d) d.pop(TYPE_LABEL) descriptor = TYPE_MAP[typename] obj = descriptor.to_obj(d) if DEBUG: ...
def json_class_decoder_hook(d: Dict) -> Any
Provides a JSON decoder that converts dictionaries to Python objects if suitable methods are found in our ``TYPE_MAP``.
4.344158
3.73734
1.162366
return json.dumps(obj, cls=JsonClassEncoder, **kwargs)
def json_encode(obj: Instance, **kwargs) -> str
Encodes an object to JSON using our custom encoder. The ``**kwargs`` can be used to pass things like ``'indent'``, for formatting.
7.701848
6.995598
1.100956
try: return json.JSONDecoder(object_hook=json_class_decoder_hook).decode(s) except json.JSONDecodeError: log.warning("Failed to decode JSON (returning None): {!r}", s) return None
def json_decode(s: str) -> Any
Decodes an object from JSON using our custom decoder.
4.220192
3.7695
1.119563
return enum_class[d['name']]
def dict_to_enum_fn(d: Dict[str, Any], enum_class: Type[Enum]) -> Enum
Converts an ``dict`` to a ``Enum``.
11.269623
9.189829
1.226315
if len(args) == 1 and len(kwargs) == 0 and callable(args[0]): # called as @register_enum_for_json cls = args[0] # type: ClassType register_class_for_json( cls, obj_to_dict_fn=enum_to_dict_fn, dict_to_obj_fn=dict_to_enum_fn ) return cl...
def register_enum_for_json(*args, **kwargs) -> Any
Class decorator to register ``Enum``-derived classes with our JSON system. See comments/help for ``@register_for_json``, above.
3.773603
2.868313
1.315618
return pendulum.parse(d['iso'])
def dict_to_pendulum(d: Dict[str, Any], pendulum_class: ClassType) -> DateTime
Converts a ``dict`` object back to a ``Pendulum``.
12.112317
18.285164
0.662412
# noinspection PyTypeChecker return pendulum.parse(d['iso']).date()
def dict_to_pendulumdate(d: Dict[str, Any], pendulumdate_class: ClassType) -> Date
Converts a ``dict`` object back to a ``pendulum.Date``.
8.657722
8.683893
0.996986
return all(getattr(one, a) == getattr(two, a) for a in attrs)
def simple_eq(one: Instance, two: Instance, attrs: List[str]) -> bool
Test if two objects are equal, based on a comparison of the specified attributes ``attrs``.
3.286098
3.564986
0.92177
# https://stackoverflow.com/questions/17602878/how-to-handle-both-with-open-and-sys-stdout-nicely # noqa # https://stackoverflow.com/questions/1744989/read-from-file-or-stdin/29824059#29824059 # noqa if filename == '-': if mode is None or mode == '' or 'r' in mode: fh = sys.stdin ...
def smart_open(filename: str, mode: str = 'Ur', buffering: int = -1, encoding: str = None, errors: str = None, newline: str = None, closefd: bool = True) -> IO
Context manager (for use with ``with``) that opens a filename and provides a :class:`IO` object. If the filename is ``'-'``, however, then ``sys.stdin`` is used for reading and ``sys.stdout`` is used for writing.
2.990661
2.959994
1.010361
# noqa fileobj.write('\n'.join(lines) + '\n')
def writelines_nl(fileobj: TextIO, lines: Iterable[str]) -> None
Writes lines, plus terminating newline characters, to the file. (Since :func:`fileobj.writelines` doesn't add newlines... http://stackoverflow.com/questions/13730107/writelines-writes-lines-without-newline-just-fills-the-file)
4.44798
5.328588
0.834739
with open(filename, 'w') as f: # type: TextIO print(text, file=f)
def write_text(filename: str, text: str) -> None
Writes text to a file.
4.882354
3.304701
1.477396
# noqa zipfilename = basefilename + '.gz' compresslevel = 9 mtime = 0 with open(zipfilename, 'wb') as f: with gzip.GzipFile(basefilename, 'wb', compresslevel, f, mtime) as gz: with io.TextIOWrapper(gz) as tw: tw.write(text)
def write_gzipped_text(basefilename: str, text: str) -> None
Writes text to a file compressed with ``gzip`` (a ``.gz`` file). The filename is used directly for the "inner" file and the extension ``.gz`` is appended to the "outer" (zipped) file's name. This function exists primarily because Lintian wants non-timestamped gzip files, or it complains: - http...
3.264273
3.434283
0.950496
lines = [] with open(filename) as f: for line in f: line = line.partition('#')[0] # the part before the first # line = line.rstrip() line = line.lstrip() if line: lines.append(line) return lines
def get_lines_without_comments(filename: str) -> List[str]
Reads a file, and returns all lines as a list, left- and right-stripping the lines and removing everything on a line after the first ``#``. NOTE: does not cope well with quoted ``#`` symbols!
2.552807
2.50894
1.017484
for filename in filenames: with open(filename) as f: yield f
def gen_textfiles_from_filenames( filenames: Iterable[str]) -> Generator[TextIO, None, None]
Generates file-like objects from a list of filenames. Args: filenames: iterable of filenames Yields: each file as a :class:`TextIO` object
3.462669
5.358698
0.646177
for file in files: for line in file: yield line
def gen_lines_from_textfiles( files: Iterable[TextIO]) -> Generator[str, None, None]
Generates lines from file-like objects. Args: files: iterable of :class:`TextIO` objects Yields: each line of all the files
4.267392
6.523424
0.654164
for string in x: yield string.lower()
def gen_lower(x: Iterable[str]) -> Generator[str, None, None]
Args: x: iterable of strings Yields: each string in lower case
6.128474
9.485737
0.646073
for file in files: for byteline in file: line = byteline.decode(encoding).strip() yield line
def gen_lines_from_binary_files( files: Iterable[BinaryIO], encoding: str = UTF8) -> Generator[str, None, None]
Generates lines from binary files. Strips out newlines. Args: files: iterable of :class:`BinaryIO` file-like objects encoding: encoding to use Yields: each line of all the files
4.678674
5.67037
0.825109
for line in lines: parts = line.split(splitter) yield parts[part_index]
def gen_part_from_line(lines: Iterable[str], part_index: int, splitter: str = None) -> Generator[str, None, None]
Splits lines with ``splitter`` and yields a specified part by index. Args: lines: iterable of strings part_index: index of part to yield splitter: string to split the lines on Yields: the specified part for each line
3.133231
4.020871
0.779242
r # RST: make part of word bold/italic: # https://stackoverflow.com/questions/12771480/part-of-a-word-bold-in-restructuredtext # noqa for iterable in iterables: yield iterable[part_index]
def gen_part_from_iterables(iterables: Iterable[Any], part_index: int) -> Generator[Any, None, None]
r""" Yields the *n*\ th part of each thing in ``iterables``. Args: iterables: iterable of anything part_index: part index Yields: ``item[part_index] for item in iterable``
8.471575
9.388826
0.902304
dialect = csv_reader_kwargs.pop('dialect', None) for csv_file_bin in csv_files: # noinspection PyTypeChecker csv_file = io.TextIOWrapper(csv_file_bin, encoding=encoding) thisfile_dialect = dialect if thisfile_dialect is None: thisfile_dialect = csv.Sniffer().snif...
def gen_rows_from_csv_binfiles( csv_files: Iterable[BinaryIO], encoding: str = UTF8, skip_header: bool = False, **csv_reader_kwargs) -> Generator[Iterable[str], None, None]
Iterate through binary file-like objects that are CSV files in a specified encoding. Yield each row. Args: csv_files: iterable of :class:`BinaryIO` objects encoding: encoding to use skip_header: skip the header (first) row of each file? csv_reader_kwargs: arguments to pass to :f...
2.076547
2.292852
0.905661
with open(srcfilename) as infile, open(destfilename, 'w') as ofile: for line_ in infile: ofile.write(escape(line_))
def webify_file(srcfilename: str, destfilename: str) -> None
Rewrites a file from ``srcfilename`` to ``destfilename``, HTML-escaping it in the process.
4.323764
3.461234
1.249197
gzip_args = gzip_args or [ "-9", # maximum compression (or Lintian moans) "-n", ] # gzip/gunzip operate on SINGLE files with tempfile.TemporaryDirectory() as dir_: basezipfilename = os.path.basename(filename) newzip = os.path.join(dir_, basezipfilename) with...
def remove_gzip_timestamp(filename: str, gunzip_executable: str = "gunzip", gzip_executable: str = "gzip", gzip_args: List[str] = None) -> None
Uses external ``gunzip``/``gzip`` tools to remove a ``gzip`` timestamp. Necessary for Lintian.
4.42898
4.207152
1.052727
log.info("Amending {}: {} -> {}", filename, repr(text_from), repr(text_to)) with open(filename) as infile: contents = infile.read() contents = contents.replace(text_from, text_to) with open(filename, 'w') as outfile: outfile.write(contents)
def replace_in_file(filename: str, text_from: str, text_to: str) -> None
Replaces text in a file. Args: filename: filename to process (modifying it in place) text_from: original text to replace text_to: replacement text
2.891794
2.684143
1.077362
with open(filename) as infile: contents = infile.read() for text_from, text_to in replacements: log.info("Amending {}: {} -> {}", filename, repr(text_from), repr(text_to)) contents = contents.replace(text_from, text_to) with open(filename, 'w') as outfile: ...
def replace_multiple_in_file(filename: str, replacements: List[Tuple[str, str]]) -> None
Replaces multiple from/to string pairs within a single file. Args: filename: filename to process (modifying it in place) replacements: list of ``(from_text, to_text)`` tuples
2.83498
2.763016
1.026045
assert to_unix != to_windows with open(filename, "rb") as f: contents = f.read() windows_eol = b"\r\n" # CR LF unix_eol = b"\n" # LF if to_unix: log.info("Converting from Windows to UNIX line endings: {!r}", filename) src = windows_eol dst = un...
def convert_line_endings(filename: str, to_unix: bool = False, to_windows: bool = False) -> None
Converts a file (in place) from UNIX to Windows line endings, or the reverse. Args: filename: filename to modify (in place) to_unix: convert Windows (CR LF) to UNIX (LF) to_windows: convert UNIX (LF) to Windows (CR LF)
2.654416
2.717802
0.976678
assert "\n" not in line with open(filename, "r") as file: for fileline in file: if fileline == line: return True return False
def is_line_in_file(filename: str, line: str) -> bool
Detects whether a line is present within a file. Args: filename: file to check line: line to search for (as an exact match)
3.898276
4.366488
0.892772
assert "\n" not in line if not is_line_in_file(filename, line): log.info("Appending line {!r} to file {!r}", line, filename) with open(filename, "a") as file: file.writelines([line])
def add_line_if_absent(filename: str, line: str) -> None
Adds a line (at the end) if it's not already in the file somewhere. Args: filename: filename to modify (in place) line: line to append (which must not have a newline in)
3.443381
3.209895
1.072739
return results and EsConst.FOUND in results and results[EsConst.FOUND] and EsConst.FIELDS in results
def is_get_query_with_results(results)
:param results: the response from Elasticsearch :return: true if the get query returned a result, false otherwise
16.107962
14.433486
1.116013
if results[EsConst.SHARDS][EsConst.FAILED] and results[EsConst.SHARDS][EsConst.FAILED] > 0: raise ScanError( 'Scroll request has failed on %d shards out of %d.' % (results[EsConst.SHARDS][EsConst.FAILED], results[EsConst.SHARDS][EsConst.TOTAL]) )
def validate_scan_result(results)
Check if there's a failed shard in the scan query
3.812436
3.053589
1.24851
if value is None: return None if isinstance(value, (str, bytes, bool, int)): raise ValueError('cannot encode objects that are not 2-tuples') if isinstance(value, collections.Mapping): value = value.items() if sort and not insensitive: values = sorted(value) el...
def to_key_val_list(value, sort=False, insensitive=False)
Take an object and test to see if it can be represented as a dictionary. If it can be, return a list of tuples, e.g., :: >>> to_key_val_list([('key', 'val')]) [('key', 'val')] >>> to_key_val_list({'key': 'val'}) [('key', 'val')] >>> to_key_val_list({'key': 'val'}, sort=Tr...
2.9397
2.55366
1.151171
if values is None: return {} if isinstance(values, (str, bytes, bool, int)): raise ValueError('cannot encode objects that are not 2-tuples') if isinstance(values, collections.Mapping): values = values.items() dict_to_return = dict() for k, v in values: if k in...
def to_key_val_dict(values)
Take an object and test to see if it can be represented as a dictionary. If it can be, return a list of tuples, e.g., :: >>> to_key_val_dict([('key', 'val')]) {'key': 'val'} >>> to_key_val_dict({'key': 'val'}) {'key': 'val'} >>> to_key_val_dict('string') ValueErro...
1.903349
1.989902
0.956504
parser = ArgumentParser( description="Remove duplicate files" ) parser.add_argument( "directory", nargs="+", help="Files and/or directories to check and remove duplicates from." ) parser.add_argument( "--recursive", action="store_true", help="Recurse thro...
def main() -> None
Command-line processor. See ``--help`` for details.
3.607691
3.502151
1.030136
return strvalue in [str(x[0]) for x in choices]
def valid_choice(strvalue: str, choices: Iterable[Tuple[str, str]]) -> bool
Checks that value is one of the valid option in choices, where choices is a list/tuple of 2-tuples (option, description). Note that parameters sent by URLconf are always strings (https://docs.djangoproject.com/en/1.8/topics/http/urls/) but Python is happy with a string-to-integer-PK lookup, e.g. ....
6.213203
7.424091
0.836898
for k, v in choices: if k == value: return v return ''
def choice_explanation(value: str, choices: Iterable[Tuple[str, str]]) -> str
Returns the explanation associated with a Django choice tuple-list.
5.557685
3.183844
1.74559
r # noqa def fanout(_infile: IO, *_files: IO): for line in iter(_infile.readline, ''): for f in _files: f.write(line) infile.close() t = Thread(target=fanout, args=(infile,) + files) t.daemon = True t.start() return t
def tee(infile: IO, *files: IO) -> Thread
r""" Print the file-like object ``infile`` to the file-like object(s) ``files`` in a separate thread. Starts and returns that thread. The type (text, binary) must MATCH across all files. From https://stackoverflow.com/questions/4984428/python-subprocess-get-childrens-output-to-file-a...
4.393299
4.870349
0.90205
# noqa # Make a copy so we can append without damaging the original: stdout_targets = stdout_targets.copy() if stdout_targets else [] # type: List[TextIO] # noqa stderr_targets = stderr_targets.copy() if stderr_targets else [] # type: List[TextIO] # noqa p = Popen(cmd_args, stdout=PIPE, stderr...
def teed_call(cmd_args, stdout_targets: List[TextIO] = None, stderr_targets: List[TextIO] = None, encoding: str = sys.getdefaultencoding(), **kwargs)
Runs a command and captures its output via :func:`tee` to one or more destinations. The output is always captured (otherwise we would lose control of the output and ability to ``tee`` it); if no destination is specified, we add a null handler. We insist on ``TextIO`` output files to match ``sys.stdo...
2.501982
2.550534
0.980964
handler = get_monochrome_handler(stream=tee_file) handler.setLevel(loglevel) rootlogger = logging.getLogger() rootlogger.addHandler(handler) # Tee the main stdout/stderr as required. with TeeContextManager(tee_file, capture_stdout=True): with TeeContextManager(tee_file, capture_stde...
def tee_log(tee_file: TextIO, loglevel: int) -> None
Context manager to add a file output stream to our logging system. Args: tee_file: file-like object to write to loglevel: log level (e.g. ``logging.DEBUG``) to use for this stream
3.456158
3.670869
0.941509
self.underlying_stream.write(message) self.file.write(message)
def write(self, message: str) -> None
To act as a file.
9.636057
6.103459
1.578786
self.underlying_stream.flush() self.file.flush() os.fsync(self.file.fileno())
def flush(self) -> None
To act as a file.
4.989989
3.839063
1.299793
if self.underlying_stream: if self.using_stdout: sys.stdout = self.underlying_stream else: sys.stderr = self.underlying_stream self.underlying_stream = None if self.file: # Do NOT close the file; we don't own it. ...
def close(self) -> None
To act as a file.
5.005894
4.391635
1.13987