_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q227200 | WrappedDash.callback | train | def callback(self, output, inputs=[], state=[], events=[]): # pylint: disable=dangerous-default-value
'Invoke callback, adjusting variable names as needed'
if isinstance(output, (list, tuple)):
fixed_outputs = [self._fix_callback_item(x) for x in output]
# Temporary check; can b... | python | {
"resource": ""
} |
q227201 | WrappedDash.dispatch | train | def dispatch(self):
'Perform dispatch, using request embedded within flask global state'
import flask
body = flask.request.get_json()
return self. dispatch_with_args(body, argMap=dict()) | python | {
"resource": ""
} |
q227202 | WrappedDash.dispatch_with_args | train | def dispatch_with_args(self, body, argMap):
'Perform callback dispatching, with enhanced arguments and recording of response'
inputs = body.get('inputs', [])
state = body.get('state', [])
output = body['output']
try:
output_id = output['id']
output_proper... | python | {
"resource": ""
} |
q227203 | WrappedDash.extra_html_properties | train | def extra_html_properties(self, prefix=None, postfix=None, template_type=None):
'''
Return extra html properties to allow individual apps to be styled separately.
The content returned from this function is injected unescaped into templates.
'''
prefix = prefix if prefix else "d... | python | {
"resource": ""
} |
q227204 | plotly_direct | train | def plotly_direct(context, name=None, slug=None, da=None):
'Direct insertion of a Dash app'
da, app = _locate_daapp(name, slug, da)
view_func = app.locate_endpoint_function()
# Load embedded holder inserted by middleware
eh = context.request.dpd_content_handler.embedded_holder
app.set_embedde... | python | {
"resource": ""
} |
q227205 | plotly_app_identifier | train | def plotly_app_identifier(name=None, slug=None, da=None, postfix=None):
'Return a slug-friendly identifier'
da, app = _locate_daapp(name, slug, da)
slugified_id = app.slugified_id()
if postfix:
return "%s-%s" %(slugified_id, postfix)
return slugified_id | python | {
"resource": ""
} |
q227206 | plotly_class | train | def plotly_class(name=None, slug=None, da=None, prefix=None, postfix=None, template_type=None):
'Return a string of space-separated class names'
da, app = _locate_daapp(name, slug, da)
return app.extra_html_properties(prefix=prefix,
postfix=postfix,
... | python | {
"resource": ""
} |
q227207 | parse_wyckoff_csv | train | def parse_wyckoff_csv(wyckoff_file):
"""Parse Wyckoff.csv
There are 530 data sets. For one example:
9:C 1 2 1:::::::
::4:c:1:(x,y,z):(-x,y,-z)::
::2:b:2:(0,y,1/2):::
::2:a:2:(0,y,0):::
"""
rowdata = []
points = []
hP_nums = [433, 436, 444, 450, 452, 458, 460]
for i, line ... | python | {
"resource": ""
} |
q227208 | get_site_symmetries | train | def get_site_symmetries(wyckoff):
"""List up site symmetries
The data structure is as follows:
wyckoff[0]['wyckoff'][0]['site_symmetry']
Note
----
Maximum length of string is 6.
"""
ssyms = []
for w in wyckoff:
ssyms += ["\"%-6s\"" % w_s['site_symmetry'] for w_s in w... | python | {
"resource": ""
} |
q227209 | transform_model | train | def transform_model(cls) -> None:
"""
Anything that uses the ModelMeta needs _meta and id.
Also keep track of relationships and make them in the related model class.
"""
if cls.name != "Model":
appname = "models"
for mcls in cls.get_children():
if isinstance(mcls, ClassDe... | python | {
"resource": ""
} |
q227210 | apply_type_shim | train | def apply_type_shim(cls, _context=None) -> Iterator:
"""
Morphs model fields to representative type
"""
if cls.name in ["IntField", "SmallIntField"]:
base_nodes = scoped_nodes.builtin_lookup("int")
elif cls.name in ["CharField", "TextField"]:
base_nodes = scoped_nodes.builtin_lookup(... | python | {
"resource": ""
} |
q227211 | list_encoder | train | def list_encoder(values, instance, field: Field):
"""Encodes an iterable of a given field into a database-compatible format."""
return [field.to_db_value(element, instance) for element in values] | python | {
"resource": ""
} |
q227212 | ManyToManyRelationManager.add | train | async def add(self, *instances, using_db=None) -> None:
"""
Adds one or more of ``instances`` to the relation.
If it is already added, it will be silently ignored.
"""
if not instances:
return
if self.instance.id is None:
raise OperationalError(
... | python | {
"resource": ""
} |
q227213 | ManyToManyRelationManager.clear | train | async def clear(self, using_db=None) -> None:
"""
Clears ALL relations.
"""
db = using_db if using_db else self.model._meta.db
through_table = Table(self.field.through)
query = (
db.query_class.from_(through_table)
.where(getattr(through_table, sel... | python | {
"resource": ""
} |
q227214 | ManyToManyRelationManager.remove | train | async def remove(self, *instances, using_db=None) -> None:
"""
Removes one or more of ``instances`` from the relation.
"""
db = using_db if using_db else self.model._meta.db
if not instances:
raise OperationalError("remove() called on no instances")
through_ta... | python | {
"resource": ""
} |
q227215 | register_tortoise | train | def register_tortoise(
app: Quart,
config: Optional[dict] = None,
config_file: Optional[str] = None,
db_url: Optional[str] = None,
modules: Optional[Dict[str, List[str]]] = None,
generate_schemas: bool = False,
) -> None:
"""
Registers ``before_serving`` and ``after_serving`` hooks to se... | python | {
"resource": ""
} |
q227216 | run_async | train | def run_async(coro: Coroutine) -> None:
"""
Simple async runner that cleans up DB connections on exit.
This is meant for simple scripts.
Usage::
from tortoise import Tortoise, run_async
async def do_stuff():
await Tortoise.init(
db_url='sqlite://db.sqlite3'... | python | {
"resource": ""
} |
q227217 | Tortoise.init | train | async def init(
cls,
config: Optional[dict] = None,
config_file: Optional[str] = None,
_create_db: bool = False,
db_url: Optional[str] = None,
modules: Optional[Dict[str, List[str]]] = None,
) -> None:
"""
Sets up Tortoise-ORM.
You can configu... | python | {
"resource": ""
} |
q227218 | in_transaction | train | def in_transaction(connection_name: Optional[str] = None) -> BaseTransactionWrapper:
"""
Transaction context manager.
You can run your code inside ``async with in_transaction():`` statement to run it
into one transaction. If error occurs transaction will rollback.
:param connection_name: name of c... | python | {
"resource": ""
} |
q227219 | atomic | train | def atomic(connection_name: Optional[str] = None) -> Callable:
"""
Transaction decorator.
You can wrap your function with this decorator to run it into one transaction.
If error occurs transaction will rollback.
:param connection_name: name of connection to run with, optional if you have only
... | python | {
"resource": ""
} |
q227220 | start_transaction | train | async def start_transaction(connection_name: Optional[str] = None) -> BaseTransactionWrapper:
"""
Function to manually control your transaction.
Returns transaction object with ``.rollback()`` and ``.commit()`` methods.
All db calls in same coroutine context will run into transaction
before ending ... | python | {
"resource": ""
} |
q227221 | QuerySet.limit | train | def limit(self, limit: int) -> "QuerySet":
"""
Limits QuerySet to given length.
"""
queryset = self._clone()
queryset._limit = limit
return queryset | python | {
"resource": ""
} |
q227222 | QuerySet.offset | train | def offset(self, offset: int) -> "QuerySet":
"""
Query offset for QuerySet.
"""
queryset = self._clone()
queryset._offset = offset
if self.capabilities.requires_limit and queryset._limit is None:
queryset._limit = 1000000
return queryset | python | {
"resource": ""
} |
q227223 | QuerySet.annotate | train | def annotate(self, **kwargs) -> "QuerySet":
"""
Annotate result with aggregation result.
"""
queryset = self._clone()
for key, aggregation in kwargs.items():
if not isinstance(aggregation, Aggregate):
raise TypeError("value is expected to be Aggregate ... | python | {
"resource": ""
} |
q227224 | QuerySet.values_list | train | def values_list(
self, *fields_: str, flat: bool = False
) -> "ValuesListQuery": # pylint: disable=W0621
"""
Make QuerySet returns list of tuples for given args instead of objects.
If ```flat=True`` and only one arg is passed can return flat list.
"""
return ValuesLi... | python | {
"resource": ""
} |
q227225 | QuerySet.values | train | def values(self, *args: str, **kwargs: str) -> "ValuesQuery":
"""
Make QuerySet return dicts instead of objects.
"""
fields_for_select = {} # type: Dict[str, str]
for field in args:
if field in fields_for_select:
raise FieldError("Duplicate key {}".fo... | python | {
"resource": ""
} |
q227226 | QuerySet.delete | train | def delete(self) -> "DeleteQuery":
"""
Delete all objects in QuerySet.
"""
return DeleteQuery(
db=self._db,
model=self.model,
q_objects=self._q_objects,
annotations=self._annotations,
custom_filters=self._custom_filters,
... | python | {
"resource": ""
} |
q227227 | QuerySet.update | train | def update(self, **kwargs) -> "UpdateQuery":
"""
Update all objects in QuerySet with given kwargs.
"""
return UpdateQuery(
db=self._db,
model=self.model,
update_kwargs=kwargs,
q_objects=self._q_objects,
annotations=self._annotat... | python | {
"resource": ""
} |
q227228 | QuerySet.count | train | def count(self) -> "CountQuery":
"""
Return count of objects in queryset instead of objects.
"""
return CountQuery(
db=self._db,
model=self.model,
q_objects=self._q_objects,
annotations=self._annotations,
custom_filters=self._cu... | python | {
"resource": ""
} |
q227229 | QuerySet.first | train | def first(self) -> "QuerySet":
"""
Limit queryset to one object and return one object instead of list.
"""
queryset = self._clone()
queryset._limit = 1
queryset._single = True
return queryset | python | {
"resource": ""
} |
q227230 | QuerySet.get | train | def get(self, *args, **kwargs) -> "QuerySet":
"""
Fetch exactly one object matching the parameters.
"""
queryset = self.filter(*args, **kwargs)
queryset._limit = 2
queryset._get = True
return queryset | python | {
"resource": ""
} |
q227231 | QuerySet.explain | train | async def explain(self) -> Any:
"""Fetch and return information about the query execution plan.
This is done by executing an ``EXPLAIN`` query whose exact prefix depends
on the database backend, as documented below.
- PostgreSQL: ``EXPLAIN (FORMAT JSON, VERBOSE) ...``
- SQLite:... | python | {
"resource": ""
} |
q227232 | QuerySet.using_db | train | def using_db(self, _db: BaseDBAsyncClient) -> "QuerySet":
"""
Executes query in provided db client.
Useful for transactions workaround.
"""
queryset = self._clone()
queryset._db = _db
return queryset | python | {
"resource": ""
} |
q227233 | Model._check_unique_together | train | def _check_unique_together(cls):
"""Check the value of "unique_together" option."""
if cls._meta.unique_together is None:
return
if not isinstance(cls._meta.unique_together, (tuple, list)):
raise ConfigurationError(
"'{}.unique_together' must be a list or... | python | {
"resource": ""
} |
q227234 | write_epub | train | def write_epub(name, book, options=None):
"""
Creates epub file with the content defined in EpubBook.
>>> ebooklib.write_epub('book.epub', book)
:Args:
- name: file name for the output file
- book: instance of EpubBook
- options: extra opions as dictionary (optional)
"""
epub... | python | {
"resource": ""
} |
q227235 | read_epub | train | def read_epub(name, options=None):
"""
Creates new instance of EpubBook with the content defined in the input file.
>>> book = ebooklib.read_epub('book.epub')
:Args:
- name: full path to the input file
- options: extra options as dictionary (optional)
:Returns:
Instance of EpubB... | python | {
"resource": ""
} |
q227236 | EpubItem.get_type | train | def get_type(self):
"""
Guess type according to the file extension. Might not be the best way how to do it, but it works for now.
Items can be of type:
- ITEM_UNKNOWN = 0
- ITEM_IMAGE = 1
- ITEM_STYLE = 2
- ITEM_SCRIPT = 3
- ITEM_NAVIGATION = 4
... | python | {
"resource": ""
} |
q227237 | EpubHtml.add_link | train | def add_link(self, **kwgs):
"""
Add additional link to the document. Links will be embeded only inside of this document.
>>> add_link(href='styles.css', rel='stylesheet', type='text/css')
"""
self.links.append(kwgs)
if kwgs.get('type') == 'text/javascript':
i... | python | {
"resource": ""
} |
q227238 | EpubHtml.get_links_of_type | train | def get_links_of_type(self, link_type):
"""
Returns list of additional links of specific type.
:Returns:
As tuple returns list of links.
"""
return (link for link in self.links if link.get('type', '') == link_type) | python | {
"resource": ""
} |
q227239 | EpubHtml.add_item | train | def add_item(self, item):
"""
Add other item to this document. It will create additional links according to the item type.
:Args:
- item: item we want to add defined as instance of EpubItem
"""
if item.get_type() == ebooklib.ITEM_STYLE:
self.add_link(href=i... | python | {
"resource": ""
} |
q227240 | EpubBook.reset | train | def reset(self):
"Initialises all needed variables to default values"
self.metadata = {}
self.items = []
self.spine = []
self.guide = []
self.pages = []
self.toc = []
self.bindings = []
self.IDENTIFIER_ID = 'id'
self.FOLDER_NAME = 'EPUB'
... | python | {
"resource": ""
} |
q227241 | EpubBook.set_identifier | train | def set_identifier(self, uid):
"""
Sets unique id for this epub
:Args:
- uid: Value of unique identifier for this book
"""
self.uid = uid
self.set_unique_metadata('DC', 'identifier', self.uid, {'id': self.IDENTIFIER_ID}) | python | {
"resource": ""
} |
q227242 | EpubBook.set_title | train | def set_title(self, title):
"""
Set title. You can set multiple titles.
:Args:
- title: Title value
"""
self.title = title
self.add_metadata('DC', 'title', self.title) | python | {
"resource": ""
} |
q227243 | EpubBook.set_cover | train | def set_cover(self, file_name, content, create_page=True):
"""
Set cover and create cover document if needed.
:Args:
- file_name: file name of the cover page
- content: Content for the cover image
- create_page: Should cover page be defined. Defined as bool value (... | python | {
"resource": ""
} |
q227244 | EpubBook.add_author | train | def add_author(self, author, file_as=None, role=None, uid='creator'):
"Add author for this document"
self.add_metadata('DC', 'creator', author, {'id': uid})
if file_as:
self.add_metadata(None, 'meta', file_as, {'refines': '#' + uid,
... | python | {
"resource": ""
} |
q227245 | EpubBook.add_item | train | def add_item(self, item):
"""
Add additional item to the book. If not defined, media type and chapter id will be defined
for the item.
:Args:
- item: Item instance
"""
if item.media_type == '':
(has_guessed, media_type) = guess_type(item.get_name().... | python | {
"resource": ""
} |
q227246 | EpubBook.get_item_with_id | train | def get_item_with_id(self, uid):
"""
Returns item for defined UID.
>>> book.get_item_with_id('image_001')
:Args:
- uid: UID for the item
:Returns:
Returns item object. Returns None if nothing was found.
"""
for item in self.get_items():
... | python | {
"resource": ""
} |
q227247 | EpubBook.get_item_with_href | train | def get_item_with_href(self, href):
"""
Returns item for defined HREF.
>>> book.get_item_with_href('EPUB/document.xhtml')
:Args:
- href: HREF for the item we are searching for
:Returns:
Returns item object. Returns None if nothing was found.
"""
... | python | {
"resource": ""
} |
q227248 | EpubBook.get_items_of_type | train | def get_items_of_type(self, item_type):
"""
Returns all items of specified type.
>>> book.get_items_of_type(epub.ITEM_IMAGE)
:Args:
- item_type: Type for items we are searching for
:Returns:
Returns found items as tuple.
"""
return (item for... | python | {
"resource": ""
} |
q227249 | EpubBook.get_items_of_media_type | train | def get_items_of_media_type(self, media_type):
"""
Returns all items of specified media type.
:Args:
- media_type: Media type for items we are searching for
:Returns:
Returns found items as tuple.
"""
return (item for item in self.items if item.media... | python | {
"resource": ""
} |
q227250 | main | train | def main():
"""
Run ftfy as a command-line utility.
"""
import argparse
parser = argparse.ArgumentParser(
description="ftfy (fixes text for you), version %s" % __version__
)
parser.add_argument('filename', default='-', nargs='?',
help='The file whose Unicode ... | python | {
"resource": ""
} |
q227251 | fix_encoding_and_explain | train | def fix_encoding_and_explain(text):
"""
Re-decodes text that has been decoded incorrectly, and also return a
"plan" indicating all the steps required to fix it.
The resulting plan could be used with :func:`ftfy.fixes.apply_plan`
to fix additional strings that are broken in the same way.
"""
... | python | {
"resource": ""
} |
q227252 | fix_one_step_and_explain | train | def fix_one_step_and_explain(text):
"""
Performs a single step of re-decoding text that's been decoded incorrectly.
Returns the decoded text, plus a "plan" for how to reproduce what it did.
"""
if isinstance(text, bytes):
raise UnicodeError(BYTES_ERROR_TEXT)
if len(text) == 0:
r... | python | {
"resource": ""
} |
q227253 | apply_plan | train | def apply_plan(text, plan):
"""
Apply a plan for fixing the encoding of text.
The plan is a list of tuples of the form (operation, encoding, cost):
- `operation` is 'encode' if it turns a string into bytes, 'decode' if it
turns bytes into a string, and 'transcode' if it keeps the type the same.
... | python | {
"resource": ""
} |
q227254 | _unescape_fixup | train | def _unescape_fixup(match):
"""
Replace one matched HTML entity with the character it represents,
if possible.
"""
text = match.group(0)
if text[:2] == "&#":
# character reference
try:
if text[:3] == "&#x":
codept = int(text[3:-1], 16)
else... | python | {
"resource": ""
} |
q227255 | convert_surrogate_pair | train | def convert_surrogate_pair(match):
"""
Convert a surrogate pair to the single codepoint it represents.
This implements the formula described at:
http://en.wikipedia.org/wiki/Universal_Character_Set_characters#Surrogates
"""
pair = match.group(0)
codept = 0x10000 + (ord(pair[0]) - 0xd800) * ... | python | {
"resource": ""
} |
q227256 | restore_byte_a0 | train | def restore_byte_a0(byts):
"""
Some mojibake has been additionally altered by a process that said "hmm,
byte A0, that's basically a space!" and replaced it with an ASCII space.
When the A0 is part of a sequence that we intend to decode as UTF-8,
changing byte A0 to 20 would make it fail to decode.
... | python | {
"resource": ""
} |
q227257 | fix_partial_utf8_punct_in_1252 | train | def fix_partial_utf8_punct_in_1252(text):
"""
Fix particular characters that seem to be found in the wild encoded in
UTF-8 and decoded in Latin-1 or Windows-1252, even when this fix can't be
consistently applied.
One form of inconsistency we need to deal with is that some character might
be fro... | python | {
"resource": ""
} |
q227258 | display_ljust | train | def display_ljust(text, width, fillchar=' '):
"""
Return `text` left-justified in a Unicode string whose display width,
in a monospaced terminal, should be at least `width` character cells.
The rest of the string will be padded with `fillchar`, which must be
a width-1 character.
"Left" here mea... | python | {
"resource": ""
} |
q227259 | display_center | train | def display_center(text, width, fillchar=' '):
"""
Return `text` centered in a Unicode string whose display width, in a
monospaced terminal, should be at least `width` character cells. The rest
of the string will be padded with `fillchar`, which must be a width-1
character.
>>> lines = ['Table ... | python | {
"resource": ""
} |
q227260 | make_sloppy_codec | train | def make_sloppy_codec(encoding):
"""
Take a codec name, and return a 'sloppy' version of that codec that can
encode and decode the unassigned bytes in that encoding.
Single-byte encodings in the standard library are defined using some
boilerplate classes surrounding the functions that do the actual... | python | {
"resource": ""
} |
q227261 | _make_weirdness_regex | train | def _make_weirdness_regex():
"""
Creates a list of regexes that match 'weird' character sequences.
The more matches there are, the weirder the text is.
"""
groups = []
# Match diacritical marks, except when they modify a non-cased letter or
# another mark.
#
# You wouldn't put a dia... | python | {
"resource": ""
} |
q227262 | sequence_weirdness | train | def sequence_weirdness(text):
"""
Determine how often a text has unexpected characters or sequences of
characters. This metric is used to disambiguate when text should be
re-decoded or left as is.
We start by normalizing text in NFC form, so that penalties for
diacritical marks don't apply to c... | python | {
"resource": ""
} |
q227263 | search_function | train | def search_function(encoding):
"""
Register our "bad codecs" with Python's codecs API. This involves adding
a search function that takes in an encoding name, and returns a codec
for that encoding if it knows one, or None if it doesn't.
The encodings this will match are:
- Encodings of the form... | python | {
"resource": ""
} |
q227264 | IncrementalDecoder._buffer_decode | train | def _buffer_decode(self, input, errors, final):
"""
Decode bytes that may be arriving in a stream, following the Codecs
API.
`input` is the incoming sequence of bytes. `errors` tells us how to
handle errors, though we delegate all error-handling cases to the real
UTF-8 d... | python | {
"resource": ""
} |
q227265 | IncrementalDecoder._buffer_decode_surrogates | train | def _buffer_decode_surrogates(sup, input, errors, final):
"""
When we have improperly encoded surrogates, we can still see the
bits that they were meant to represent.
The surrogates were meant to encode a 20-bit number, to which we
add 0x10000 to get a codepoint. That 20-bit num... | python | {
"resource": ""
} |
q227266 | fix_text | train | def fix_text(text,
*,
fix_entities='auto',
remove_terminal_escapes=True,
fix_encoding=True,
fix_latin_ligatures=True,
fix_character_width=True,
uncurl_quotes=True,
fix_line_breaks=True,
fix_surrogates=Tr... | python | {
"resource": ""
} |
q227267 | fix_file | train | def fix_file(input_file,
encoding=None,
*,
fix_entities='auto',
remove_terminal_escapes=True,
fix_encoding=True,
fix_latin_ligatures=True,
fix_character_width=True,
uncurl_quotes=True,
fix_line_breaks=Tr... | python | {
"resource": ""
} |
q227268 | fix_text_segment | train | def fix_text_segment(text,
*,
fix_entities='auto',
remove_terminal_escapes=True,
fix_encoding=True,
fix_latin_ligatures=True,
fix_character_width=True,
uncurl_quotes=True,
... | python | {
"resource": ""
} |
q227269 | explain_unicode | train | def explain_unicode(text):
"""
A utility method that's useful for debugging mysterious Unicode.
It breaks down a string, showing you for each codepoint its number in
hexadecimal, its glyph, its category in the Unicode standard, and its name
in the Unicode standard.
>>> explain_unicode('(╯°... | python | {
"resource": ""
} |
q227270 | _build_regexes | train | def _build_regexes():
"""
ENCODING_REGEXES contain reasonably fast ways to detect if we
could represent a given string in a given encoding. The simplest one is
the 'ascii' detector, which of course just determines if all characters
are between U+0000 and U+007F.
"""
# Define a regex that mat... | python | {
"resource": ""
} |
q227271 | _build_width_map | train | def _build_width_map():
"""
Build a translate mapping that replaces halfwidth and fullwidth forms
with their standard-width forms.
"""
# Though it's not listed as a fullwidth character, we'll want to convert
# U+3000 IDEOGRAPHIC SPACE to U+20 SPACE on the same principle, so start
# with that... | python | {
"resource": ""
} |
q227272 | set_vml_accuracy_mode | train | def set_vml_accuracy_mode(mode):
"""
Set the accuracy mode for VML operations.
The `mode` parameter can take the values:
- 'high': high accuracy mode (HA), <1 least significant bit
- 'low': low accuracy mode (LA), typically 1-2 least significant bits
- 'fast': enhanced performance mode (EP)
... | python | {
"resource": ""
} |
q227273 | _init_num_threads | train | def _init_num_threads():
"""
Detects the environment variable 'NUMEXPR_MAX_THREADS' to set the threadpool
size, and if necessary the slightly redundant 'NUMEXPR_NUM_THREADS' or
'OMP_NUM_THREADS' env vars to set the initial number of threads used by
the virtual machine.
"""
# Any platform-... | python | {
"resource": ""
} |
q227274 | detect_number_of_cores | train | def detect_number_of_cores():
"""
Detects the number of cores on a system. Cribbed from pp.
"""
# Linux, Unix and MacOS:
if hasattr(os, "sysconf"):
if "SC_NPROCESSORS_ONLN" in os.sysconf_names:
# Linux & Unix:
ncpus = os.sysconf("SC_NPROCESSORS_ONLN")
if i... | python | {
"resource": ""
} |
q227275 | chunkify | train | def chunkify(chunksize):
""" Very stupid "chunk vectorizer" which keeps memory use down.
This version requires all inputs to have the same number of elements,
although it shouldn't be that hard to implement simple broadcasting.
"""
def chunkifier(func):
def wrap(*args):
... | python | {
"resource": ""
} |
q227276 | expressionToAST | train | def expressionToAST(ex):
"""Take an expression tree made out of expressions.ExpressionNode,
and convert to an AST tree.
This is necessary as ExpressionNode overrides many methods to act
like a number.
"""
return ASTNode(ex.astType, ex.astKind, ex.value,
[expressionToAST(c) fo... | python | {
"resource": ""
} |
q227277 | sigPerms | train | def sigPerms(s):
"""Generate all possible signatures derived by upcasting the given
signature.
"""
codes = 'bilfdc'
if not s:
yield ''
elif s[0] in codes:
start = codes.index(s[0])
for x in codes[start:]:
for y in sigPerms(s[1:]):
yield x + y
... | python | {
"resource": ""
} |
q227278 | typeCompileAst | train | def typeCompileAst(ast):
"""Assign appropiate types to each node in the AST.
Will convert opcodes and functions to appropiate upcast version,
and add "cast" ops if needed.
"""
children = list(ast.children)
if ast.astType == 'op':
retsig = ast.typecode()
basesig = ''.join(x.typec... | python | {
"resource": ""
} |
q227279 | stringToExpression | train | def stringToExpression(s, types, context):
"""Given a string, convert it to a tree of ExpressionNode's.
"""
old_ctx = expressions._context.get_current_context()
try:
expressions._context.set_new_context(context)
# first compile to a code object to determine the names
if context.g... | python | {
"resource": ""
} |
q227280 | getInputOrder | train | def getInputOrder(ast, input_order=None):
"""Derive the input order of the variables in an expression.
"""
variables = {}
for a in ast.allOf('variable'):
variables[a.value] = a
variable_names = set(variables.keys())
if input_order:
if variable_names != set(input_order):
... | python | {
"resource": ""
} |
q227281 | assignLeafRegisters | train | def assignLeafRegisters(inodes, registerMaker):
"""Assign new registers to each of the leaf nodes.
"""
leafRegisters = {}
for node in inodes:
key = node.key()
if key in leafRegisters:
node.reg = leafRegisters[key]
else:
node.reg = leafRegisters[key] = regi... | python | {
"resource": ""
} |
q227282 | assignBranchRegisters | train | def assignBranchRegisters(inodes, registerMaker):
"""Assign temporary registers to each of the branch nodes.
"""
for node in inodes:
node.reg = registerMaker(node, temporary=True) | python | {
"resource": ""
} |
q227283 | collapseDuplicateSubtrees | train | def collapseDuplicateSubtrees(ast):
"""Common subexpression elimination.
"""
seen = {}
aliases = []
for a in ast.allOf('op'):
if a in seen:
target = seen[a]
a.astType = 'alias'
a.value = target
a.children = ()
aliases.append(a)
... | python | {
"resource": ""
} |
q227284 | optimizeTemporariesAllocation | train | def optimizeTemporariesAllocation(ast):
"""Attempt to minimize the number of temporaries needed, by
reusing old ones.
"""
nodes = [n for n in ast.postorderWalk() if n.reg.temporary]
users_of = dict((n.reg, set()) for n in nodes)
node_regs = dict((n, set(c.reg for c in n.children if c.reg.tempor... | python | {
"resource": ""
} |
q227285 | setOrderedRegisterNumbers | train | def setOrderedRegisterNumbers(order, start):
"""Given an order of nodes, assign register numbers.
"""
for i, node in enumerate(order):
node.reg.n = start + i
return start + len(order) | python | {
"resource": ""
} |
q227286 | setRegisterNumbersForTemporaries | train | def setRegisterNumbersForTemporaries(ast, start):
"""Assign register numbers for temporary registers, keeping track of
aliases and handling immediate operands.
"""
seen = 0
signature = ''
aliases = []
for node in ast.postorderWalk():
if node.astType == 'alias':
aliases.ap... | python | {
"resource": ""
} |
q227287 | convertASTtoThreeAddrForm | train | def convertASTtoThreeAddrForm(ast):
"""Convert an AST to a three address form.
Three address form is (op, reg1, reg2, reg3), where reg1 is the
destination of the result of the instruction.
I suppose this should be called three register form, but three
address form is found in compiler theory.
... | python | {
"resource": ""
} |
q227288 | compileThreeAddrForm | train | def compileThreeAddrForm(program):
"""Given a three address form of the program, compile it a string that
the VM understands.
"""
def nToChr(reg):
if reg is None:
return b'\xff'
elif reg.n < 0:
raise ValueError("negative value for register number %s" % reg.n)
... | python | {
"resource": ""
} |
q227289 | precompile | train | def precompile(ex, signature=(), context={}):
"""Compile the expression to an intermediate form.
"""
types = dict(signature)
input_order = [name for (name, type_) in signature]
if isinstance(ex, (str, unicode)):
ex = stringToExpression(ex, types, context)
# the AST is like the expressi... | python | {
"resource": ""
} |
q227290 | disassemble | train | def disassemble(nex):
"""
Given a NumExpr object, return a list which is the program disassembled.
"""
rev_opcodes = {}
for op in interpreter.opcodes:
rev_opcodes[interpreter.opcodes[op]] = op
r_constants = 1 + len(nex.signature)
r_temps = r_constants + len(nex.constants)
def ge... | python | {
"resource": ""
} |
q227291 | getArguments | train | def getArguments(names, local_dict=None, global_dict=None):
"""Get the arguments based on the names."""
call_frame = sys._getframe(2)
clear_local_dict = False
if local_dict is None:
local_dict = call_frame.f_locals
clear_local_dict = True
try:
frame_globals = call_frame.f_gl... | python | {
"resource": ""
} |
q227292 | evaluate | train | def evaluate(ex, local_dict=None, global_dict=None,
out=None, order='K', casting='safe', **kwargs):
"""Evaluate a simple array expression element-wise, using the new iterator.
ex is a string forming an expression, like "2*a+3*b". The values for "a"
and "b" will by default be taken from the cal... | python | {
"resource": ""
} |
q227293 | re_evaluate | train | def re_evaluate(local_dict=None):
"""Re-evaluate the previous executed array expression without any check.
This is meant for accelerating loops that are re-evaluating the same
expression repeatedly without changing anything else than the operands.
If unsure, use evaluate() which is safer.
Paramete... | python | {
"resource": ""
} |
q227294 | compute | train | def compute():
"""Compute the polynomial."""
if what == "numpy":
y = eval(expr)
else:
y = ne.evaluate(expr)
return len(y) | python | {
"resource": ""
} |
q227295 | MFA.partial_row_coordinates | train | def partial_row_coordinates(self, X):
"""Returns the row coordinates for each group."""
utils.validation.check_is_fitted(self, 's_')
# Check input
if self.check_input:
utils.check_array(X, dtype=[str, np.number])
# Prepare input
X = self._prepare_input(X)
... | python | {
"resource": ""
} |
q227296 | MFA.column_correlations | train | def column_correlations(self, X):
"""Returns the column correlations."""
utils.validation.check_is_fitted(self, 's_')
X_global = self._build_X_global(X)
row_pc = self._row_coordinates_from_global(X_global)
return pd.DataFrame({
component: {
feature: ... | python | {
"resource": ""
} |
q227297 | CA.eigenvalues_ | train | def eigenvalues_(self):
"""The eigenvalues associated with each principal component."""
utils.validation.check_is_fitted(self, 's_')
return np.square(self.s_).tolist() | python | {
"resource": ""
} |
q227298 | CA.explained_inertia_ | train | def explained_inertia_(self):
"""The percentage of explained inertia per principal component."""
utils.validation.check_is_fitted(self, 'total_inertia_')
return [eig / self.total_inertia_ for eig in self.eigenvalues_] | python | {
"resource": ""
} |
q227299 | CA.row_coordinates | train | def row_coordinates(self, X):
"""The row principal coordinates."""
utils.validation.check_is_fitted(self, 'V_')
_, row_names, _, _ = util.make_labels_and_names(X)
if isinstance(X, pd.SparseDataFrame):
X = X.to_coo().astype(float)
elif isinstance(X, pd.DataFrame):
... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.