_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q8400 | IrcObject.from_config | train | def from_config(cls, cfg, **kwargs):
"""return an instance configured with the ``cfg`` dict"""
cfg = dict(cfg, **kwargs)
pythonpath = cfg.get('pythonpath', [])
if 'here' in cfg:
pythonpath.append(cfg['here'])
for path in pythonpath:
sys.path.append(os.path... | python | {
"resource": ""
} |
q8401 | AsyncLibrary.async_run | train | def async_run(self, keyword, *args, **kwargs):
''' Executes the provided Robot Framework keyword in a separate thread and immediately returns a handle to be used with async_get '''
handle = self._last_thread_handle
thread = self._threaded(keyword, *args, **kwargs)
thread.start()
... | python | {
"resource": ""
} |
q8402 | AsyncLibrary.async_get | train | def async_get(self, handle):
''' Blocks until the thread created by async_run returns '''
assert handle in self._thread_pool, 'Invalid async call handle'
result = self._thread_pool[handle].result_queue.get()
del self._thread_pool[handle]
return result | python | {
"resource": ""
} |
q8403 | AsyncLibrary._get_handler_from_keyword | train | def _get_handler_from_keyword(self, keyword):
''' Gets the Robot Framework handler associated with the given keyword '''
if EXECUTION_CONTEXTS.current is None:
raise RobotNotRunningError('Cannot access execution context')
return EXECUTION_CONTEXTS.current.get_handler(keyword) | python | {
"resource": ""
} |
q8404 | PMMail._set_attachments | train | def _set_attachments(self, value):
'''
A special set function to ensure
we're setting with a list
'''
if value is None:
setattr(self, '_PMMail__attachments', [])
elif isinstance(value, list):
setattr(self, '_PMMail__attachments', value)
els... | python | {
"resource": ""
} |
q8405 | PMMail._check_values | train | def _check_values(self):
'''
Make sure all values are of the appropriate
type and are not missing.
'''
if not self.__api_key:
raise PMMailMissingValueException('Cannot send an e-mail without a Postmark API Key')
elif not self.__sender:
raise PMMail... | python | {
"resource": ""
} |
q8406 | PMMail.send | train | def send(self, test=None):
'''
Send the email through the Postmark system.
Pass test=True to just print out the resulting
JSON message being sent to Postmark
'''
self._check_values()
# Set up message dictionary
json_message = self.to_json_message()
... | python | {
"resource": ""
} |
q8407 | PMBatchMail.remove_message | train | def remove_message(self, message):
'''
Remove a message from the batch
'''
if message in self.__messages:
self.__messages.remove(message) | python | {
"resource": ""
} |
q8408 | PMBounceManager.delivery_stats | train | def delivery_stats(self):
'''
Returns a summary of inactive emails and bounces by type.
'''
self._check_values()
req = Request(
__POSTMARK_URL__ + 'deliverystats',
None,
{
'Accept': 'application/json',
'Content-... | python | {
"resource": ""
} |
q8409 | PMBounceManager.get_all | train | def get_all(self, inactive='', email_filter='', tag='', count=25, offset=0):
'''
Fetches a portion of bounces according to the specified input criteria. The count and offset
parameters are mandatory. You should never retrieve all bounces as that could be excessively
slow for your applica... | python | {
"resource": ""
} |
q8410 | PMBounceManager.activate | train | def activate(self, bounce_id):
'''
Activates a deactivated bounce.
'''
self._check_values()
req_url = '/bounces/' + str(bounce_id) + '/activate'
# print req_url
h1 = HTTPConnection('api.postmarkapp.com')
dta = urlencode({"data": "blank"}).encode('utf8')
... | python | {
"resource": ""
} |
q8411 | EmailBackend._build_message | train | def _build_message(self, message):
"""A helper method to convert a PMEmailMessage to a PMMail"""
if not message.recipients():
return False
recipients = ','.join(message.to)
recipients_cc = ','.join(message.cc)
recipients_bcc = ','.join(message.bcc)
text_body ... | python | {
"resource": ""
} |
q8412 | Nature.handle_starttag | train | def handle_starttag(self, tag, attrs):
'''
PDF link handler; never gets explicitly called by user
'''
if tag == 'a' and ( ('class', 'download-pdf') in attrs or ('id', 'download-pdf') in attrs ):
for attr in attrs:
if attr[0] == 'href':
self.download_link = 'http://www.natur... | python | {
"resource": ""
} |
q8413 | genpass | train | def genpass(pattern=r'[\w]{32}'):
"""generates a password with random chararcters
"""
try:
return rstr.xeger(pattern)
except re.error as e:
raise ValueError(str(e)) | python | {
"resource": ""
} |
q8414 | CStruct.unpack | train | def unpack(self, string):
"""
Unpack the string containing packed C structure data
"""
if string is None:
string = CHAR_ZERO * self.__size__
data = struct.unpack(self.__fmt__, string)
i = 0
for field in self.__fields__:
(vtype, vlen) = self... | python | {
"resource": ""
} |
q8415 | CStruct.pack | train | def pack(self):
"""
Pack the structure data into a string
"""
data = []
for field in self.__fields__:
(vtype, vlen) = self.__fields_types__[field]
if vtype == 'char': # string
data.append(getattr(self, field))
elif isinstance(vt... | python | {
"resource": ""
} |
q8416 | get_all | train | def get_all():
"""Get all subclasses of BaseImporter from module and return and generator
"""
_import_all_importer_files()
for module in (value for key, value in globals().items()
if key in __all__):
for klass_name, klass in inspect.getmembers(module, inspect.isclass):
... | python | {
"resource": ""
} |
q8417 | list_database | train | def list_database(db):
"""Print credential as a table"""
credentials = db.credentials()
if credentials:
table = Table(
db.config['headers'],
table_format=db.config['table_format'],
colors=db.config['colors'],
hidden=db.config['hidden'],
hid... | python | {
"resource": ""
} |
q8418 | check_config | train | def check_config(db, level):
"""Show current configuration for shell"""
if level == 'global':
configuration = config.read(config.HOMEDIR, '.passpierc')
elif level == 'local':
configuration = config.read(os.path.join(db.path))
elif level == 'current':
configuration = db.config
... | python | {
"resource": ""
} |
q8419 | RequestHandler.process | train | def process(self, data=None):
"""Fetch incoming data from the Flask request object when no data is supplied
to the process method. By default, the RequestHandler expects the
incoming data to be sent as JSON.
"""
return super(RequestHandler, self).process(data=data or self.get_r... | python | {
"resource": ""
} |
q8420 | DBMixin.save | train | def save(self, obj):
"""Add ``obj`` to the SQLAlchemy session and commit the changes back to
the database.
:param obj: SQLAlchemy object being saved
:returns: The saved object
"""
session = self.get_db_session()
session.add(obj)
session.commit()
... | python | {
"resource": ""
} |
q8421 | DBObjectMixin.filter_by_id | train | def filter_by_id(self, query):
"""Apply the primary key filter to query to filter the results for a specific
instance by id.
The filter applied by the this method by default can be controlled using the
url_id_param
:param query: SQLAlchemy Query
:returns: A SQLAlchemy Q... | python | {
"resource": ""
} |
q8422 | DBObjectMixin.delete_object | train | def delete_object(self, obj):
"""Deletes an object from the session by calling session.delete and then commits
the changes to the database.
:param obj: The SQLAlchemy instance being deleted
:returns: None
"""
session = self.get_db_session()
session.delete(obj)
... | python | {
"resource": ""
} |
q8423 | ArrestedAPI.init_app | train | def init_app(self, app):
"""Initialise the ArrestedAPI object by storing a pointer to a Flask app object.
This method is typically used when initialisation is deferred.
:param app: Flask application object
Usage::
app = Flask(__name__)
ap1_v1 = ArrestedAPI()
... | python | {
"resource": ""
} |
q8424 | Endpoint.dispatch_request | train | def dispatch_request(self, *args, **kwargs):
"""Dispatch the incoming HTTP request to the appropriate handler.
"""
self.args = args
self.kwargs = kwargs
self.meth = request.method.lower()
self.resource = current_app.blueprints.get(request.blueprint, None)
if not ... | python | {
"resource": ""
} |
q8425 | Endpoint.return_error | train | def return_error(self, status, payload=None):
"""Error handler called by request handlers when an error occurs and the request
should be aborted.
Usage::
def handle_post_request(self, *args, **kwargs):
self.request_handler = self.get_request_handler()
... | python | {
"resource": ""
} |
q8426 | KimResponseHandler.handle | train | def handle(self, data, **kwargs):
"""Run serialization for the specified mapper_class.
Supports both .serialize and .many().serialize Kim interfaces.
:param data: Objects to be serialized.
:returns: Serialized data according to mapper configuration
"""
if self.many:
... | python | {
"resource": ""
} |
q8427 | KimRequestHandler.handle_error | train | def handle_error(self, exp):
"""Called if a Mapper returns MappingInvalid. Should handle the error
and return it in the appropriate format, can be overridden in order
to change the error format.
:param exp: MappingInvalid exception raised
"""
payload = {
"mes... | python | {
"resource": ""
} |
q8428 | KimRequestHandler.handle | train | def handle(self, data, **kwargs):
"""Run marshalling for the specified mapper_class.
Supports both .marshal and .many().marshal Kim interfaces. Handles errors raised
during marshalling and automatically returns a HTTP error response.
:param data: Data to be marshaled.
:returns... | python | {
"resource": ""
} |
q8429 | KimEndpoint.get_response_handler_params | train | def get_response_handler_params(self, **params):
"""Return a config object that will be used to configure the KimResponseHandler
:returns: a dictionary of config options
:rtype: dict
"""
params = super(KimEndpoint, self).get_response_handler_params(**params)
params['map... | python | {
"resource": ""
} |
q8430 | KimEndpoint.get_request_handler_params | train | def get_request_handler_params(self, **params):
"""Return a config object that will be used to configure the KimRequestHandler
:returns: a dictionary of config options
:rtype: dict
"""
params = super(KimEndpoint, self).get_request_handler_params(**params)
params['mapper... | python | {
"resource": ""
} |
q8431 | GetListMixin.list_response | train | def list_response(self, status=200):
"""Pull the processed data from the response_handler and return a response.
:param status: The HTTP status code returned with the response
.. seealso:
:meth:`Endpoint.make_response`
:meth:`Endpoint.handle_get_request`
"""
... | python | {
"resource": ""
} |
q8432 | CreateMixin.create_response | train | def create_response(self, status=201):
"""Generate a Response object for a POST request. By default, the newly created
object will be passed to the specified ResponseHandler and will be serialized
as the response body.
"""
self.response = self.get_response_handler()
self... | python | {
"resource": ""
} |
q8433 | fsm.concatenate | train | def concatenate(*fsms):
'''
Concatenate arbitrarily many finite state machines together.
'''
alphabet = set().union(*[fsm.alphabet for fsm in fsms])
def connect_all(i, substate):
'''
Take a state in the numbered FSM and return a set containing it, plus
(if it's final) the first state from the nex... | python | {
"resource": ""
} |
q8434 | fsm.times | train | def times(self, multiplier):
'''
Given an FSM and a multiplier, return the multiplied FSM.
'''
if multiplier < 0:
raise Exception("Can't multiply an FSM by " + repr(multiplier))
alphabet = self.alphabet
# metastate is a set of iterations+states
initial = {(self.initial, 0)}
def final(state):
'... | python | {
"resource": ""
} |
q8435 | fsm.everythingbut | train | def everythingbut(self):
'''
Return a finite state machine which will accept any string NOT
accepted by self, and will not accept any string accepted by self.
This is more complicated if there are missing transitions, because the
missing "dead" state must now be reified.
'''
alphabet = self.alphabet
... | python | {
"resource": ""
} |
q8436 | fsm.islive | train | def islive(self, state):
'''A state is "live" if a final state can be reached from it.'''
reachable = [state]
i = 0
while i < len(reachable):
current = reachable[i]
if current in self.finals:
return True
if current in self.map:
for symbol in self.map[current]:
next = self.map[current][symb... | python | {
"resource": ""
} |
q8437 | fsm.cardinality | train | def cardinality(self):
'''
Consider the FSM as a set of strings and return the cardinality of that
set, or raise an OverflowError if there are infinitely many
'''
num_strings = {}
def get_num_strings(state):
# Many FSMs have at least one oblivion state
if self.islive(state):
if state in num_stri... | python | {
"resource": ""
} |
q8438 | call_fsm | train | def call_fsm(method):
'''
Take a method which acts on 0 or more regular expression objects... return a
new method which simply converts them all to FSMs, calls the FSM method
on them instead, then converts the result back to a regular expression.
We do this for several of the more annoying operations.
'''
fs... | python | {
"resource": ""
} |
q8439 | from_fsm | train | def from_fsm(f):
'''
Turn the supplied finite state machine into a `lego` object. This is
accomplished using the Brzozowski algebraic method.
'''
# Make sure the supplied alphabet is kosher. It must contain only single-
# character strings or `fsm.anything_else`.
for symbol in f.alphabet:
if symbol == fsm.an... | python | {
"resource": ""
} |
q8440 | multiplier.common | train | def common(self, other):
'''
Find the shared part of two multipliers. This is the largest multiplier
which can be safely subtracted from both the originals. This may
return the "zero" multiplier.
'''
mandatory = min(self.mandatory, other.mandatory)
optional = min(self.optional, other.optional)
return... | python | {
"resource": ""
} |
q8441 | conc.dock | train | def dock(self, other):
'''
Subtract another conc from this one.
This is the opposite of concatenation. For example, if ABC + DEF = ABCDEF,
then logically ABCDEF - DEF = ABC.
'''
# e.g. self has mults at indices [0, 1, 2, 3, 4, 5, 6] len=7
# e.g. other has mults at indices [0, 1, 2] len=3
new = list(... | python | {
"resource": ""
} |
q8442 | pattern.dock | train | def dock(self, other):
'''
The opposite of concatenation. Remove a common suffix from the present
pattern; that is, from each of its constituent concs.
AYZ|BYZ|CYZ - YZ = A|B|C.
'''
return pattern(*[c.dock(other) for c in self.concs]) | python | {
"resource": ""
} |
q8443 | delete_name | train | def delete_name(name):
''' This function don't use the plugin. '''
session = create_session()
try:
user = session.query(User).filter_by(name=name).first()
session.delete(user)
session.commit()
except SQLAlchemyError, e:
session.rollback()
raise bottle.HTTPError(50... | python | {
"resource": ""
} |
q8444 | SQLAlchemyPlugin.setup | train | def setup(self, app):
''' Make sure that other installed plugins don't affect the same
keyword argument and check if metadata is available.'''
for other in app.plugins:
if not isinstance(other, SQLAlchemyPlugin):
continue
if other.keyword == self.keywo... | python | {
"resource": ""
} |
q8445 | GreenSocket.send_multipart | train | def send_multipart(self, *args, **kwargs):
"""wrap send_multipart to prevent state_changed on each partial send"""
self.__in_send_multipart = True
try:
msg = super(GreenSocket, self).send_multipart(*args, **kwargs)
finally:
self.__in_send_multipart = False
... | python | {
"resource": ""
} |
q8446 | GreenSocket.recv_multipart | train | def recv_multipart(self, *args, **kwargs):
"""wrap recv_multipart to prevent state_changed on each partial recv"""
self.__in_recv_multipart = True
try:
msg = super(GreenSocket, self).recv_multipart(*args, **kwargs)
finally:
self.__in_recv_multipart = False
... | python | {
"resource": ""
} |
q8447 | archive | train | def archive(source, archive, path_in_arc=None, remove_source=False,
compression=zipfile.ZIP_DEFLATED, compresslevel=-1):
"""Archives a MRIO database as zip file
This function is a wrapper around zipfile.write,
to ease the writing of an archive and removing the source data.
Note
----
... | python | {
"resource": ""
} |
q8448 | parse_exio12_ext | train | def parse_exio12_ext(ext_file, index_col, name, drop_compartment=True,
version=None, year=None, iosystem=None, sep=','):
""" Parse an EXIOBASE version 1 or 2 like extension file into pymrio.Extension
EXIOBASE like extensions files are assumed to have two
rows which are used as columns ... | python | {
"resource": ""
} |
q8449 | get_exiobase12_version | train | def get_exiobase12_version(filename):
""" Returns the EXIOBASE version for the given filename,
None if not found
"""
try:
ver_match = re.search(r'(\d+\w*(\.|\-|\_))*\d+\w*', filename)
version = ver_match.string[ver_match.start():ver_match.end()]
if re.search('\_\d\d\d\d', ver... | python | {
"resource": ""
} |
q8450 | parse_exiobase1 | train | def parse_exiobase1(path):
""" Parse the exiobase1 raw data files.
This function works with
- pxp_ita_44_regions_coeff_txt
- ixi_fpa_44_regions_coeff_txt
- pxp_ita_44_regions_coeff_src_txt
- ixi_fpa_44_regions_coeff_src_txt
which can be found on www.exiobase.eu
The parser works with ... | python | {
"resource": ""
} |
q8451 | parse_exiobase3 | train | def parse_exiobase3(path):
""" Parses the public EXIOBASE 3 system
This parser works with either the compressed zip
archive as downloaded or the extracted system.
Note
----
The exiobase 3 parser does so far not include
population and characterization data.
Parameters
----------
... | python | {
"resource": ""
} |
q8452 | __get_WIOD_SEA_extension | train | def __get_WIOD_SEA_extension(root_path, year, data_sheet='DATA'):
""" Utility function to get the extension data from the SEA file in WIOD
This function is based on the structure in the WIOD_SEA_July14 file.
Missing values are set to zero.
The function works if the SEA file is either in path or in a s... | python | {
"resource": ""
} |
q8453 | MRIOMetaData._add_history | train | def _add_history(self, entry_type, entry):
""" Generic method to add entry as entry_type to the history """
meta_string = "{time} - {etype} - {entry}".format(
time=self._time(),
etype=entry_type.upper(),
entry=entry)
self._content['history'].insert(0, meta_s... | python | {
"resource": ""
} |
q8454 | MRIOMetaData.change_meta | train | def change_meta(self, para, new_value, log=True):
""" Changes the meta data
This function does nothing if None is passed as new_value.
To set a certain value to None pass the str 'None'
Parameters
----------
para: str
Meta data entry to change
new_v... | python | {
"resource": ""
} |
q8455 | MRIOMetaData.save | train | def save(self, location=None):
""" Saves the current status of the metadata
This saves the metadata at the location of the previously loaded
metadata or at the file/path given in location.
Specify a location if the metadata should be stored in a different
location or was never ... | python | {
"resource": ""
} |
q8456 | calc_x | train | def calc_x(Z, Y):
""" Calculate the industry output x from the Z and Y matrix
Parameters
----------
Z : pandas.DataFrame or numpy.array
Symmetric input output table (flows)
Y : pandas.DataFrame or numpy.array
final demand with categories (1.order) for each country (2.order)
Ret... | python | {
"resource": ""
} |
q8457 | calc_x_from_L | train | def calc_x_from_L(L, y):
""" Calculate the industry output x from L and a y vector
Parameters
----------
L : pandas.DataFrame or numpy.array
Symmetric input output Leontief table
y : pandas.DataFrame or numpy.array
a column vector of the total final demand
Returns
-------
... | python | {
"resource": ""
} |
q8458 | calc_L | train | def calc_L(A):
""" Calculate the Leontief L from A
Parameters
----------
A : pandas.DataFrame or numpy.array
Symmetric input output table (coefficients)
Returns
-------
pandas.DataFrame or numpy.array
Leontief input output table L
The type is determined by the type ... | python | {
"resource": ""
} |
q8459 | recalc_M | train | def recalc_M(S, D_cba, Y, nr_sectors):
""" Calculate Multipliers based on footprints.
Parameters
----------
D_cba : pandas.DataFrame or numpy array
Footprint per sector and country
Y : pandas.DataFrame or numpy array
Final demand: aggregated across categories or just one category, o... | python | {
"resource": ""
} |
q8460 | calc_accounts | train | def calc_accounts(S, L, Y, nr_sectors):
""" Calculate sector specific cba and pba based accounts, imp and exp accounts
The total industry output x for the calculation
is recalculated from L and y
Parameters
----------
L : pandas.DataFrame
Leontief input output table L
S : pandas.Da... | python | {
"resource": ""
} |
q8461 | _get_url_datafiles | train | def _get_url_datafiles(url_db_view, url_db_content,
mrio_regex, access_cookie=None):
""" Urls of mrio files by parsing url content for mrio_regex
Parameters
----------
url_db_view: url str
Url which shows the list of mrios in the db
url_db_content: url str
U... | python | {
"resource": ""
} |
q8462 | _download_urls | train | def _download_urls(url_list, storage_folder, overwrite_existing,
meta_handler, access_cookie=None):
""" Save url from url_list to storage_folder
Parameters
----------
url_list: list of str
Valid url to download
storage_folder: str, valid path
Location to store th... | python | {
"resource": ""
} |
q8463 | download_wiod2013 | train | def download_wiod2013(storage_folder, years=None, overwrite_existing=False,
satellite_urls=WIOD_CONFIG['satellite_urls']):
""" Downloads the 2013 wiod release
Note
----
Currently, pymrio only works with the 2013 release of the wiod tables. The
more recent 2016 release so far (... | python | {
"resource": ""
} |
q8464 | get_timestamp | train | def get_timestamp(length):
"""Get a timestamp of `length` in string"""
s = '%.6f' % time.time()
whole, frac = map(int, s.split('.'))
res = '%d%d' % (whole, frac)
return res[:length] | python | {
"resource": ""
} |
q8465 | mkdir_p | train | def mkdir_p(path):
"""mkdir -p path"""
if PY3:
return os.makedirs(path, exist_ok=True)
try:
os.makedirs(path)
except OSError as exc:
if exc.errno == errno.EEXIST and os.path.isdir(path):
pass
else:
raise | python | {
"resource": ""
} |
q8466 | monkey_patch | train | def monkey_patch():
"""
Monkey patches `zmq.Context` and `zmq.Socket`
If test_suite is True, the pyzmq test suite will be patched for
compatibility as well.
"""
ozmq = __import__('zmq')
ozmq.Socket = zmq.Socket
ozmq.Context = zmq.Context
ozmq.Poller = zmq.Poller
ioloop = __impor... | python | {
"resource": ""
} |
q8467 | CoreSystem.reset_to_coefficients | train | def reset_to_coefficients(self):
""" Keeps only the coefficient.
This can be used to recalculate the IO tables for a new finald demand.
Note
-----
The system can not be reconstructed after this steps
because all absolute data is removed. Save the Y data in case
... | python | {
"resource": ""
} |
q8468 | CoreSystem.copy | train | def copy(self, new_name=None):
""" Returns a deep copy of the system
Parameters
-----------
new_name: str, optional
Set a new meta name parameter.
Default: <old_name>_copy
"""
_tmp = copy.deepcopy(self)
if not new_name:
new_na... | python | {
"resource": ""
} |
q8469 | CoreSystem.get_Y_categories | train | def get_Y_categories(self, entries=None):
""" Returns names of y cat. of the IOSystem as unique names in order
Parameters
----------
entries : List, optional
If given, retuns an list with None for all values not in entries.
Returns
-------
Index
... | python | {
"resource": ""
} |
q8470 | CoreSystem.get_index | train | def get_index(self, as_dict=False, grouping_pattern=None):
""" Returns the index of the DataFrames in the system
Parameters
----------
as_dict: boolean, optional
If True, returns a 1:1 key-value matching for further processing
prior to groupby functions. Otherwis... | python | {
"resource": ""
} |
q8471 | CoreSystem.set_index | train | def set_index(self, index):
""" Sets the pd dataframe index of all dataframes in the system to index
"""
for df in self.get_DataFrame(data=True, with_population=False):
df.index = index | python | {
"resource": ""
} |
q8472 | CoreSystem.get_DataFrame | train | def get_DataFrame(self, data=False, with_unit=True, with_population=True):
""" Yields all panda.DataFrames or there names
Notes
-----
For IOSystem this does not include the DataFrames in the extensions.
Parameters
----------
data : boolean, optional
... | python | {
"resource": ""
} |
q8473 | CoreSystem.save | train | def save(self, path, table_format='txt', sep='\t',
table_ext=None, float_format='%.12g'):
""" Saving the system to path
Parameters
----------
path : pathlib.Path or string
path for the saved data (will be created if necessary, data
within will be ov... | python | {
"resource": ""
} |
q8474 | CoreSystem.rename_regions | train | def rename_regions(self, regions):
""" Sets new names for the regions
Parameters
----------
regions : list or dict
In case of dict: {'old_name' : 'new_name'} with a
entry for each old_name which should be renamed
In case of list: List of new name... | python | {
"resource": ""
} |
q8475 | CoreSystem.rename_sectors | train | def rename_sectors(self, sectors):
""" Sets new names for the sectors
Parameters
----------
sectors : list or dict
In case of dict: {'old_name' : 'new_name'} with an
entry for each old_name which should be renamed
In case of list: List of new nam... | python | {
"resource": ""
} |
q8476 | CoreSystem.rename_Y_categories | train | def rename_Y_categories(self, Y_categories):
""" Sets new names for the Y_categories
Parameters
----------
Y_categories : list or dict
In case of dict: {'old_name' : 'new_name'} with an
entry for each old_name which should be renamed
In case of l... | python | {
"resource": ""
} |
q8477 | Extension.get_rows | train | def get_rows(self):
""" Returns the name of the rows of the extension"""
possible_dataframes = ['F', 'FY', 'M', 'S',
'D_cba', 'D_pba', 'D_imp', 'D_exp',
'D_cba_reg', 'D_pba_reg',
'D_imp_reg', 'D_exp_reg',
... | python | {
"resource": ""
} |
q8478 | Extension.get_row_data | train | def get_row_data(self, row, name=None):
""" Returns a dict with all available data for a row in the extension
Parameters
----------
row : tuple, list, string
A valid index for the extension DataFrames
name : string, optional
If given, adds a key 'name' wi... | python | {
"resource": ""
} |
q8479 | Extension.diag_stressor | train | def diag_stressor(self, stressor, name=None):
""" Diagonalize one row of the stressor matrix for a flow analysis.
This method takes one row of the F matrix and diagonalize
to the full region/sector format. Footprints calculation based
on this matrix show the flow of embodied stressors f... | python | {
"resource": ""
} |
q8480 | IOSystem.calc_system | train | def calc_system(self):
"""
Calculates the missing part of the core IOSystem
The method checks Z, x, A, L and calculates all which are None
"""
# Possible cases:
# 1) Z given, rest can be None and calculated
# 2) A and x given, rest can be calculated
# 3)... | python | {
"resource": ""
} |
q8481 | IOSystem.calc_extensions | train | def calc_extensions(self, extensions=None, Y_agg=None):
""" Calculates the extension and their accounts
For the calculation, y is aggregated across specified y categories
The method calls .calc_system of each extension (or these given in the
extensions parameter)
Parameters
... | python | {
"resource": ""
} |
q8482 | IOSystem.report_accounts | train | def report_accounts(self, path, per_region=True,
per_capita=False, pic_size=1000,
format='rst', **kwargs):
""" Generates a report to the given path for all extension
This method calls .report_accounts for all extensions
Notes
-----
... | python | {
"resource": ""
} |
q8483 | IOSystem.get_extensions | train | def get_extensions(self, data=False):
""" Yields the extensions or their names
Parameters
----------
data : boolean, optional
If True, returns a generator which yields the extensions.
If False, returns a generator which yields the names of
the extensions... | python | {
"resource": ""
} |
q8484 | IOSystem.reset_all_to_flows | train | def reset_all_to_flows(self, force=False):
""" Resets the IOSystem and all extensions to absolute flows
This method calls reset_to_flows for the IOSystem and for
all Extensions in the system.
Parameters
----------
force: boolean, optional
If True, reset to ... | python | {
"resource": ""
} |
q8485 | IOSystem.reset_all_to_coefficients | train | def reset_all_to_coefficients(self):
""" Resets the IOSystem and all extensions to coefficients.
This method calls reset_to_coefficients for the IOSystem and for
all Extensions in the system
Note
-----
The system can not be reconstructed after this steps
becaus... | python | {
"resource": ""
} |
q8486 | IOSystem.save_all | train | def save_all(self, path, table_format='txt', sep='\t',
table_ext=None, float_format='%.12g'):
""" Saves the system and all extensions
Extensions are saved in separate folders (names based on extension)
Parameters are passed to the .save methods of the IOSystem and
Exte... | python | {
"resource": ""
} |
q8487 | IOSystem.remove_extension | train | def remove_extension(self, ext=None):
""" Remove extension from IOSystem
For single Extensions the same can be achieved with del
IOSystem_name.Extension_name
Parameters
----------
ext : string or list, optional
The extension to remove, this can be given as t... | python | {
"resource": ""
} |
q8488 | is_vector | train | def is_vector(inp):
""" Returns true if the input can be interpreted as a 'true' vector
Note
----
Does only check dimensions, not if type is numeric
Parameters
----------
inp : numpy.ndarray or something that can be converted into ndarray
Returns
-------
Boolean
True f... | python | {
"resource": ""
} |
q8489 | get_file_para | train | def get_file_para(path, path_in_arc=''):
""" Generic method to read the file parameter file
Helper function to consistently read the file parameter file, which can
either be uncompressed or included in a zip archive. By default, the file
name is to be expected as set in DEFAULT_FILE_NAMES['filepara'] ... | python | {
"resource": ""
} |
q8490 | build_agg_matrix | train | def build_agg_matrix(agg_vector, pos_dict=None):
""" Agg. matrix based on mapping given in input as numerical or str vector.
The aggregation matrix has the from nxm with
-n new classificaction
-m old classification
Parameters
----------
agg_vector : list or vector like numpy ndarray... | python | {
"resource": ""
} |
q8491 | diagonalize_blocks | train | def diagonalize_blocks(arr, blocksize):
""" Diagonalize sections of columns of an array for the whole array
Parameters
----------
arr : numpy array
Input array
blocksize : int
number of rows/colums forming one block
Returns
-------
numpy ndarray with shape (columns 'a... | python | {
"resource": ""
} |
q8492 | set_block | train | def set_block(arr, arr_block):
""" Sets the diagonal blocks of an array to an given array
Parameters
----------
arr : numpy ndarray
the original array
block_arr : numpy ndarray
the block array for the new diagonal
Returns
-------
numpy ndarray (the modified array)
... | python | {
"resource": ""
} |
q8493 | unique_element | train | def unique_element(ll):
""" returns unique elements from a list preserving the original order """
seen = {}
result = []
for item in ll:
if item in seen:
continue
seen[item] = 1
result.append(item)
return result | python | {
"resource": ""
} |
q8494 | build_agg_vec | train | def build_agg_vec(agg_vec, **source):
""" Builds an combined aggregation vector based on various classifications
This function build an aggregation vector based on the order in agg_vec.
The naming and actual mapping is given in source, either explicitly or by
pointing to a folder with the mapping.
... | python | {
"resource": ""
} |
q8495 | find_first_number | train | def find_first_number(ll):
""" Returns nr of first entry parseable to float in ll, None otherwise"""
for nr, entry in enumerate(ll):
try:
float(entry)
except (ValueError, TypeError) as e:
pass
else:
return nr
return None | python | {
"resource": ""
} |
q8496 | sniff_csv_format | train | def sniff_csv_format(csv_file,
potential_sep=['\t', ',', ';', '|', '-', '_'],
max_test_lines=10,
zip_file=None):
""" Tries to get the separator, nr of index cols and header rows in a csv file
Parameters
----------
csv_file: str
Pat... | python | {
"resource": ""
} |
q8497 | GreenPoller._get_descriptors | train | def _get_descriptors(self):
"""Returns three elements tuple with socket descriptors ready
for gevent.select.select
"""
rlist = []
wlist = []
xlist = []
for socket, flags in self.sockets.items():
if isinstance(socket, zmq.Socket):
rlist... | python | {
"resource": ""
} |
q8498 | GreenPoller.poll | train | def poll(self, timeout=-1):
"""Overridden method to ensure that the green version of
Poller is used.
Behaves the same as :meth:`zmq.core.Poller.poll`
"""
if timeout is None:
timeout = -1
if timeout < 0:
timeout = -1
rlist = None
... | python | {
"resource": ""
} |
q8499 | _instantiate_task | train | def _instantiate_task(api, kwargs):
"""Create a Task object from raw kwargs"""
file_id = kwargs['file_id']
kwargs['file_id'] = file_id if str(file_id).strip() else None
kwargs['cid'] = kwargs['file_id'] or None
kwargs['rate_download'] = kwargs['rateDownload']
kwargs['percent_done'] = kwargs['per... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.