_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q237200 | Users.fetchUser | train | def fetchUser(self, username, rawResults = False) :
"""Returns a single user. if rawResults, the result will be a list of python dicts instead of User objects"""
url = "%s/%s" % (self.URL, username)
r = self.connection.session.get(url)
if r.status_code == 200 :
data = r.json... | python | {
"resource": ""
} |
q237201 | Connection.resetSession | train | def resetSession(self, username=None, password=None, verify=True) :
"""resets the session"""
self.disconnectSession()
self.session = AikidoSession(username, password, verify) | python | {
"resource": ""
} |
q237202 | Connection.reload | train | def reload(self) :
"""Reloads the database list.
Because loading a database triggers the loading of all collections and graphs within,
only handles are loaded when this function is called. The full databases are loaded on demand when accessed
"""
r = self.session.get(self.databa... | python | {
"resource": ""
} |
q237203 | Connection.createDatabase | train | def createDatabase(self, name, **dbArgs) :
"use dbArgs for arguments other than name. for a full list of arguments please have a look at arangoDB's doc"
dbArgs['name'] = name
payload = json.dumps(dbArgs, default=str)
url = self.URL + "/database"
r = self.session.post(url, data = ... | python | {
"resource": ""
} |
q237204 | SensuPlugin.output | train | def output(self, args):
'''
Print the output message.
'''
print("SensuPlugin: {}".format(' '.join(str(a) for a in args))) | python | {
"resource": ""
} |
q237205 | SensuPlugin.__make_dynamic | train | def __make_dynamic(self, method):
'''
Create a method for each of the exit codes.
'''
def dynamic(*args):
self.plugin_info['status'] = method
if not args:
args = None
self.output(args)
sys.exit(getattr(self.exit_code, method... | python | {
"resource": ""
} |
q237206 | SensuPlugin.__exitfunction | train | def __exitfunction(self):
'''
Method called by exit hook, ensures that both an exit code and
output is supplied, also catches errors.
'''
if self._hook.exit_code is None and self._hook.exception is None:
print("Check did not exit! You should call an exit code method."... | python | {
"resource": ""
} |
q237207 | SensuHandler.run | train | def run(self):
'''
Set up the event object, global settings and command line
arguments.
'''
# Parse the stdin into a global event object
stdin = self.read_stdin()
self.event = self.read_event(stdin)
# Prepare global settings
self.settings = get_s... | python | {
"resource": ""
} |
q237208 | SensuHandler.filter | train | def filter(self):
'''
Filters exit the proccess if the event should not be handled.
Filtering events is deprecated and will be removed in a future release.
'''
if self.deprecated_filtering_enabled():
print('warning: event filtering in sensu-plugin is deprecated,' +
... | python | {
"resource": ""
} |
q237209 | SensuHandler.bail | train | def bail(self, msg):
'''
Gracefully terminate with message
'''
client_name = self.event['client'].get('name', 'error:no-client-name')
check_name = self.event['check'].get('name', 'error:no-check-name')
print('{}: {}/{}'.format(msg, client_name, check_name))
sys.ex... | python | {
"resource": ""
} |
q237210 | SensuHandler.api_request | train | def api_request(self, method, path):
'''
Query Sensu api for information.
'''
if not hasattr(self, 'api_settings'):
ValueError('api.json settings not found')
if method.lower() == 'get':
_request = requests.get
elif method.lower() == 'post':
... | python | {
"resource": ""
} |
q237211 | SensuHandler.event_exists | train | def event_exists(self, client, check):
'''
Query Sensu API for event.
'''
return self.api_request(
'get',
'events/{}/{}'.format(client, check)
).status_code == 200 | python | {
"resource": ""
} |
q237212 | SensuHandler.filter_silenced | train | def filter_silenced(self):
'''
Determine whether a check is silenced and shouldn't handle.
'''
stashes = [
('client', '/silence/{}'.format(self.event['client']['name'])),
('check', '/silence/{}/{}'.format(
self.event['client']['name'],
... | python | {
"resource": ""
} |
q237213 | SensuHandler.filter_dependencies | train | def filter_dependencies(self):
'''
Determine whether a check has dependencies.
'''
dependencies = self.event['check'].get('dependencies', None)
if dependencies is None or not isinstance(dependencies, list):
return
for dependency in self.event['check']['depende... | python | {
"resource": ""
} |
q237214 | SensuHandler.filter_repeated | train | def filter_repeated(self):
'''
Determine whether a check is repeating.
'''
defaults = {
'occurrences': 1,
'interval': 30,
'refresh': 1800
}
# Override defaults with anything defined in the settings
if isinstance(self.settings['... | python | {
"resource": ""
} |
q237215 | config_files | train | def config_files():
'''
Get list of currently used config files.
'''
sensu_loaded_tempfile = os.environ.get('SENSU_LOADED_TEMPFILE')
sensu_config_files = os.environ.get('SENSU_CONFIG_FILES')
sensu_v1_config = '/etc/sensu/config.json'
sensu_v1_confd = '/etc/sensu/conf.d'
if sensu_loaded_t... | python | {
"resource": ""
} |
q237216 | get_settings | train | def get_settings():
'''
Get all currently loaded settings.
'''
settings = {}
for config_file in config_files():
config_contents = load_config(config_file)
if config_contents is not None:
settings = deep_merge(settings, config_contents)
return settings | python | {
"resource": ""
} |
q237217 | load_config | train | def load_config(filename):
'''
Read contents of config file.
'''
try:
with open(filename, 'r') as config_file:
return json.loads(config_file.read())
except IOError:
pass | python | {
"resource": ""
} |
q237218 | deep_merge | train | def deep_merge(dict_one, dict_two):
'''
Deep merge two dicts.
'''
merged = dict_one.copy()
for key, value in dict_two.items():
# value is equivalent to dict_two[key]
if (key in dict_one and
isinstance(dict_one[key], dict) and
isinstance(value, dict)):
... | python | {
"resource": ""
} |
q237219 | map_v2_event_into_v1 | train | def map_v2_event_into_v1(event):
'''
Helper method to convert Sensu 2.x event into Sensu 1.x event.
'''
# return the event if it has already been mapped
if "v2_event_mapped_into_v1" in event:
return event
# Trigger mapping code if enity exists and client does not
if not bool(event.... | python | {
"resource": ""
} |
q237220 | SensuPluginCheck.check_name | train | def check_name(self, name=None):
'''
Checks the plugin name and sets it accordingly.
Uses name if specified, class name if not set.
'''
if name:
self.plugin_info['check_name'] = name
if self.plugin_info['check_name'] is not None:
return self.plugi... | python | {
"resource": ""
} |
q237221 | Result.sampled_logs | train | def sampled_logs(self, logs_limit=-1):
"""Return up to `logs_limit` logs.
If `logs_limit` is -1, this function will return all logs that belong
to the result.
"""
logs_count = len(self.logs)
if logs_limit == -1 or logs_count <= logs_limit:
return self.logs
... | python | {
"resource": ""
} |
q237222 | Result.serialize_with_sampled_logs | train | def serialize_with_sampled_logs(self, logs_limit=-1):
"""serialize a result with up to `logs_limit` logs.
If `logs_limit` is -1, this function will return a result with all its
logs.
"""
return {
'id': self.id,
'pathName': self.path_name,
'na... | python | {
"resource": ""
} |
q237223 | reporter | train | def reporter(prefix=None, out=None, subdir='', timeout=5, **kwargs):
"""Summary media assets to visualize.
``reporter`` function collects media assets by the ``with`` statement and
aggregates in same row to visualize. This function returns an object which
provides the following methods.
* :meth:`~... | python | {
"resource": ""
} |
q237224 | audio | train | def audio(audio, sample_rate, name=None, out=None, subdir='', timeout=5,
**kwargs):
"""summary audio files to listen on a browser.
An sampled array is converted as WAV audio file, saved to output directory,
and reported to the ChainerUI server. The audio file is saved every called
this functi... | python | {
"resource": ""
} |
q237225 | _Reporter.audio | train | def audio(self, audio, sample_rate, name=None, subdir=''):
"""Summary audio to listen on web browser.
Args:
audio (:class:`numpy.ndarray` or :class:`cupy.ndarray` or \
:class:`chainer.Variable`): sampled wave array.
sample_rate (int): sampling rate.
n... | python | {
"resource": ""
} |
q237226 | Project.create | train | def create(cls, path_name=None, name=None, crawlable=True):
"""initialize an instance and save it to db."""
project = cls(path_name, name, crawlable)
db.session.add(project)
db.session.commit()
return collect_results(project, force=True) | python | {
"resource": ""
} |
q237227 | collect_assets | train | def collect_assets(result, force=False):
"""collect assets from meta file
Collecting assets only when the metafile is updated. If number of assets
are decreased, assets are reset and re-collect the assets.
"""
path_name = result.path_name
info_path = os.path.join(path_name, summary.CHAINERUI_AS... | python | {
"resource": ""
} |
q237228 | save_args | train | def save_args(conditions, out_path):
"""A util function to save experiment condition for job table.
Args:
conditions (:class:`argparse.Namespace` or dict): Experiment conditions
to show on a job table. Keys are show as table header and values
are show at a job row.
out_p... | python | {
"resource": ""
} |
q237229 | _path_insensitive | train | def _path_insensitive(path):
"""
Recursive part of path_insensitive to do the work.
"""
path = str(path)
if path == '' or os.path.exists(path):
return path
base = os.path.basename(path) # may be a directory or a file
dirname = os.path.dirname(path)
suffix = ''
if not base:... | python | {
"resource": ""
} |
q237230 | form_option | train | def form_option(str_opt):
'''generate option name based suffix for URL
:param str_opt: opt name
:type str_opt: str
:return: URL suffix for the specified option
:rtype: str
'''
str_base = '#cmdoption-arg-'
str_opt_x = str_base+str_opt.lower()\
.replace('_', '-')\
.replac... | python | {
"resource": ""
} |
q237231 | gen_url_option | train | def gen_url_option(
str_opt,
set_site=set_site,
set_runcontrol=set_runcontrol,
set_initcond=set_initcond,
source='docs'):
'''construct a URL for option based on source
:param str_opt: option name, defaults to ''
:param str_opt: str, optional
:param source: URL source: 'docs' fo... | python | {
"resource": ""
} |
q237232 | gen_df_forcing | train | def gen_df_forcing(
path_csv_in='SSss_YYYY_data_tt.csv',
url_base=url_repo_input,)->pd.DataFrame:
'''Generate description info of supy forcing data into a dataframe
Parameters
----------
path_csv_in : str, optional
path to the input csv file relative to url_base (the default is ... | python | {
"resource": ""
} |
q237233 | gen_df_output | train | def gen_df_output(
list_csv_in=[
'SSss_YYYY_SUEWS_TT.csv',
'SSss_DailyState.csv',
'SSss_YYYY_snow_TT.csv',
],
url_base=url_repo_output)->Path:
'''Generate description info of supy output results into dataframe
Parameters
----------
list_csv_in... | python | {
"resource": ""
} |
q237234 | gen_opt_str | train | def gen_opt_str(ser_rec: pd.Series)->str:
'''generate rst option string
Parameters
----------
ser_rec : pd.Series
record for specifications
Returns
-------
str
rst string
'''
name = ser_rec.name
indent = r' '
str_opt = f'.. option:: {name}'+'\n\n'
fo... | python | {
"resource": ""
} |
q237235 | init_supy | train | def init_supy(path_init: str)->pd.DataFrame:
'''Initialise supy by loading initial model states.
Parameters
----------
path_init : str
Path to a file that can initialise SuPy, which can be either of the follows:
* SUEWS :ref:`RunControl.nml<suews:RunControl.nml>`: a namelist file fo... | python | {
"resource": ""
} |
q237236 | load_SampleData | train | def load_SampleData()->Tuple[pandas.DataFrame, pandas.DataFrame]:
'''Load sample data for quickly starting a demo run.
Returns
-------
df_state_init, df_forcing: Tuple[pandas.DataFrame, pandas.DataFrame]
- df_state_init: `initial model states <df_state_var>`
- df_forcing: `forcing data ... | python | {
"resource": ""
} |
q237237 | save_supy | train | def save_supy(
df_output: pandas.DataFrame,
df_state_final: pandas.DataFrame,
freq_s: int = 3600,
site: str = '',
path_dir_save: str = Path('.'),
path_runcontrol: str = None,)->list:
'''Save SuPy run results to files
Parameters
----------
df_output : pand... | python | {
"resource": ""
} |
q237238 | load_df_state | train | def load_df_state(path_csv: Path)->pd.DataFrame:
'''load `df_state` from `path_csv`
Parameters
----------
path_csv : Path
path to the csv file that stores `df_state` produced by a supy run
Returns
-------
pd.DataFrame
`df_state` produced by a supy run
'''
df_state ... | python | {
"resource": ""
} |
q237239 | extract_var_suews | train | def extract_var_suews(dict_var_full: dict, var_supy: str)->list:
'''extract related SUEWS variables for a supy variable `var_supy`
Parameters
----------
dict_var_full : dict
dict_var_full = sp.supy_load.exp_dict_full(sp.supy_load.dict_var2SiteSelect)
var_supy : str
supy variable nam... | python | {
"resource": ""
} |
q237240 | gen_df_site | train | def gen_df_site(
list_csv_in=list_table,
url_base=url_repo_input_site)->pd.DataFrame:
'''Generate description info of supy output results as a dataframe
Parameters
----------
path_csv_out : str, optional
path to the output csv file (the default is 'df_output.csv')
list_csv_i... | python | {
"resource": ""
} |
q237241 | gen_rst_url_split_opts | train | def gen_rst_url_split_opts(opts_str):
"""generate option list for RST docs
Parameters
----------
opts_str : str
a string including all SUEWS related options/variables.
e.g. 'SUEWS_a, SUEWS_b'
Returns
-------
list
a list of parsed RST `:ref:` roles.
e.g. [':... | python | {
"resource": ""
} |
q237242 | gen_df_state | train | def gen_df_state(
list_table: list,
set_initcond: set,
set_runcontrol: set,
set_input_runcontrol: set)->pd.DataFrame:
'''generate dataframe of all state variables used by supy
Parameters
----------
list_table : list
csv files for site info: `SUEWS_xx.csv` on gith... | python | {
"resource": ""
} |
q237243 | gen_df_save | train | def gen_df_save(df_grid_group: pd.DataFrame)->pd.DataFrame:
'''generate a dataframe for saving
Parameters
----------
df_output_grid_group : pd.DataFrame
an output dataframe of a single group and grid
Returns
-------
pd.DataFrame
a dataframe with date time info prepended for... | python | {
"resource": ""
} |
q237244 | save_df_output | train | def save_df_output(
df_output: pd.DataFrame,
freq_s: int = 3600,
site: str = '',
path_dir_save: Path = Path('.'),)->list:
'''save supy output dataframe to txt files
Parameters
----------
df_output : pd.DataFrame
output dataframe of supy simulation
freq_s : in... | python | {
"resource": ""
} |
q237245 | save_df_state | train | def save_df_state(
df_state: pd.DataFrame,
site: str = '',
path_dir_save: Path = Path('.'),)->Path:
'''save `df_state` to a csv file
Parameters
----------
df_state : pd.DataFrame
a dataframe of model states produced by a supy run
site : str, optional
site ide... | python | {
"resource": ""
} |
q237246 | gen_FS_DF | train | def gen_FS_DF(df_output):
"""generate DataFrame of scores.
Parameters
----------
df_WS_data : type
Description of parameter `df_WS_data`.
Returns
-------
type
Description of returned object.
"""
df_day = pd.pivot_table(
df_output,
values=['T2', 'U10... | python | {
"resource": ""
} |
q237247 | gen_WS_DF | train | def gen_WS_DF(df_WS_data):
"""generate DataFrame of weighted sums.
Parameters
----------
df_WS_data : type
Description of parameter `df_WS_data`.
Returns
-------
type
Description of returned object.
"""
df_fs = gen_FS_DF(df_WS_data)
list_index = [('mean', 'T2'... | python | {
"resource": ""
} |
q237248 | _geoid_radius | train | def _geoid_radius(latitude: float) -> float:
"""Calculates the GEOID radius at a given latitude
Parameters
----------
latitude : float
Latitude (degrees)
Returns
-------
R : float
GEOID Radius (meters)
"""
lat = deg2rad(latitude)
return sqrt(1/(cos(lat) ** 2 / R... | python | {
"resource": ""
} |
q237249 | geometric2geopotential | train | def geometric2geopotential(z: float, latitude: float) -> float:
"""Converts geometric height to geopoential height
Parameters
----------
z : float
Geometric height (meters)
latitude : float
Latitude (degrees)
Returns
-------
h : float
Geopotential Height (meters... | python | {
"resource": ""
} |
q237250 | geopotential2geometric | train | def geopotential2geometric(h: float, latitude: float) -> float:
"""Converts geopoential height to geometric height
Parameters
----------
h : float
Geopotential height (meters)
latitude : float
Latitude (degrees)
Returns
-------
z : float
Geometric Height (meters... | python | {
"resource": ""
} |
q237251 | get_ser_val_alt | train | def get_ser_val_alt(lat: float, lon: float,
da_alt_x: xr.DataArray,
da_alt: xr.DataArray, da_val: xr.DataArray)->pd.Series:
'''interpolate atmospheric variable to a specified altitude
Parameters
----------
lat : float
latitude of specified site
lon : ... | python | {
"resource": ""
} |
q237252 | get_df_val_alt | train | def get_df_val_alt(lat: float, lon: float, da_alt_meas: xr.DataArray, ds_val: xr.Dataset):
'''interpolate atmospheric variables to a specified altitude
Parameters
----------
lat : float
latitude of specified site
lon : float
longitude of specified site
da_alt_x : xr.DataArray
... | python | {
"resource": ""
} |
q237253 | sel_list_pres | train | def sel_list_pres(ds_sfc_x):
'''
select proper levels for model level data download
'''
p_min, p_max = ds_sfc_x.sp.min().values, ds_sfc_x.sp.max().values
list_pres_level = [
'1', '2', '3',
'5', '7', '10',
'20', '30', '50',
'70', '100', '125',
'150', '175', '20... | python | {
"resource": ""
} |
q237254 | load_world | train | def load_world(filename):
"""
Load a world from the given HDF5 filename.
The return type is determined by ``ecell4_base.core.load_version_information``.
Parameters
----------
filename : str
A HDF5 filename.
Returns
-------
w : World
Return one from ``BDWorld``, ``EG... | python | {
"resource": ""
} |
q237255 | show | train | def show(target, *args, **kwargs):
"""
An utility function to display the given target object in the proper way.
Paramters
---------
target : NumberObserver, TrajectoryObserver, World, str
When a NumberObserver object is given, show it with viz.plot_number_observer.
When a Trajector... | python | {
"resource": ""
} |
q237256 | print_batch_exception | train | def print_batch_exception(batch_exception):
"""Prints the contents of the specified Batch exception.
:param batch_exception:
"""
_log.error('-------------------------------------------')
_log.error('Exception encountered:')
if batch_exception.error and \
batch_exception.error.messag... | python | {
"resource": ""
} |
q237257 | upload_file_to_container | train | def upload_file_to_container(block_blob_client, container_name, file_path):
"""Uploads a local file to an Azure Blob storage container.
:param block_blob_client: A blob service client.
:type block_blob_client: `azure.storage.blob.BlockBlobService`
:param str container_name: The name of the Azure Blob s... | python | {
"resource": ""
} |
q237258 | get_container_sas_token | train | def get_container_sas_token(block_blob_client,
container_name, blob_permissions):
"""Obtains a shared access signature granting the specified permissions to the
container.
:param block_blob_client: A blob service client.
:type block_blob_client: `azure.storage.blob.BlockBlob... | python | {
"resource": ""
} |
q237259 | create_pool | train | def create_pool(batch_service_client, pool_id,
resource_files, publisher, offer, sku,
task_file, vm_size, node_count):
"""Creates a pool of compute nodes with the specified OS settings.
:param batch_service_client: A Batch service client.
:type batch_service_client: `azure.b... | python | {
"resource": ""
} |
q237260 | create_job | train | def create_job(batch_service_client, job_id, pool_id):
"""Creates a job with the specified ID, associated with the specified pool.
:param batch_service_client: A Batch service client.
:type batch_service_client: `azure.batch.BatchServiceClient`
:param str job_id: The ID for the job.
:param str pool... | python | {
"resource": ""
} |
q237261 | add_tasks | train | def add_tasks(batch_service_client, job_id, loads,
output_container_name, output_container_sas_token,
task_file, acount_name):
"""Adds a task for each input file in the collection to the specified job.
:param batch_service_client: A Batch service client.
:type batch_service_clie... | python | {
"resource": ""
} |
q237262 | wait_for_tasks_to_complete | train | def wait_for_tasks_to_complete(batch_service_client, job_ids, timeout):
"""Returns when all tasks in the specified job reach the Completed state.
:param batch_service_client: A Batch service client.
:type batch_service_client: `azure.batch.BatchServiceClient`
:param str job_id: The id of the job whose ... | python | {
"resource": ""
} |
q237263 | download_blobs_from_container | train | def download_blobs_from_container(block_blob_client,
container_name, directory_path,
prefix=None):
"""Downloads all blobs from the specified Azure Blob storage container.
:param block_blob_client: A blob service client.
:type block_blob_cl... | python | {
"resource": ""
} |
q237264 | singlerun | train | def singlerun(job, task_id=0, job_id=0):
"""This task is for an example."""
import ecell4_base
import ecell4
import ecell4.util.simulation
import ecell4.util.decorator
print('ecell4_base.__version__ = {:s}'.format(ecell4_base.__version__))
print('ecell4.__version__ = {:s}'.format(ecell4.__v... | python | {
"resource": ""
} |
q237265 | plot_number_observer | train | def plot_number_observer(*args, **kwargs):
"""
Generate a plot from NumberObservers and show it.
See plot_number_observer_with_matplotlib and _with_nya for details.
Parameters
----------
obs : NumberObserver (e.g. FixedIntervalNumberObserver)
interactive : bool, default False
Choose... | python | {
"resource": ""
} |
q237266 | plot_world | train | def plot_world(*args, **kwargs):
"""
Generate a plot from received instance of World and show it.
See also plot_world_with_elegans and plot_world_with_matplotlib.
Parameters
----------
world : World or str
World or a HDF5 filename to render.
interactive : bool, default True
... | python | {
"resource": ""
} |
q237267 | plot_movie | train | def plot_movie(*args, **kwargs):
"""
Generate a movie from received instances of World and show them.
See also plot_movie_with_elegans and plot_movie_with_matplotlib.
Parameters
----------
worlds : list of World
Worlds to render.
interactive : bool, default True
Choose a vis... | python | {
"resource": ""
} |
q237268 | plot_trajectory | train | def plot_trajectory(*args, **kwargs):
"""
Generate a plot from received instance of TrajectoryObserver and show it
See also plot_trajectory_with_elegans and plot_trajectory_with_matplotlib.
Parameters
----------
obs : TrajectoryObserver
TrajectoryObserver to render.
interactive : bo... | python | {
"resource": ""
} |
q237269 | plot_movie_with_elegans | train | def plot_movie_with_elegans(
worlds, radius=None, width=500, height=500, config=None, grid=False,
species_list=None):
"""
Generate a movie from received instances of World and show them
on IPython notebook.
Parameters
----------
worlds : list of World
Worlds to render.
... | python | {
"resource": ""
} |
q237270 | plot_world_with_elegans | train | def plot_world_with_elegans(
world, radius=None, width=350, height=350, config=None, grid=True,
wireframe=False, species_list=None, debug=None, max_count=1000,
camera_position=(-22, 23, 32), camera_rotation=(-0.6, 0.5, 0.6),
return_id=False, predicator=None):
"""
Generate a plot ... | python | {
"resource": ""
} |
q237271 | generate_html | train | def generate_html(keywords, tmpl_path, package_name='ecell4.util'):
"""
Generate static html file from JSON model and its own id.
Parameters
----------
model : dict
JSON model from which ecell4.viz generates a plot.
model_id : string
Unique id for the plot.
Returns
----... | python | {
"resource": ""
} |
q237272 | plot_trajectory2d_with_matplotlib | train | def plot_trajectory2d_with_matplotlib(
obs, plane='xy', max_count=10, figsize=6, legend=True,
wireframe=False, grid=True, noaxis=False, plot_range=None, **kwargs):
"""
Make a 2D plot from received instance of TrajectoryObserver and show it
on IPython notebook.
Parameters
----------
... | python | {
"resource": ""
} |
q237273 | plot_world2d_with_matplotlib | train | def plot_world2d_with_matplotlib(
world, plane='xy', marker_size=3, figsize=6, grid=True,
wireframe=False, species_list=None, max_count=1000, angle=None,
legend=True, noaxis=False, scale=1.0, **kwargs):
"""
Make a 2D plot from received instance of World and show it on IPython notebook.
... | python | {
"resource": ""
} |
q237274 | plot_world_with_plotly | train | def plot_world_with_plotly(world, species_list=None, max_count=1000):
"""
Plot a World on IPython Notebook
"""
if isinstance(world, str):
from .simulation import load_world
world = load_world(world)
if species_list is None:
species_list = [sp.serial() for sp in world.list_sp... | python | {
"resource": ""
} |
q237275 | getUnitRegistry | train | def getUnitRegistry(length="meter", time="second", substance="item", volume=None, other=()):
"""Return a pint.UnitRegistry made compatible with ecell4.
Parameters
----------
length : str, optional
A default unit for '[length]'. 'meter' is its default.
time : str, optional
A default ... | python | {
"resource": ""
} |
q237276 | biogridDataSource.interactor | train | def interactor(self, geneList=None, org=None):
"""
Supposing geneList returns an unique item.
"""
geneList = geneList or []
organisms = organisms or []
querydata = self.interactions(geneList, org)
returnData = {}
for i in querydata:
if not ret... | python | {
"resource": ""
} |
q237277 | save_sbml | train | def save_sbml(filename, model, y0=None, volume=1.0, is_valid=True):
"""
Save a model in the SBML format.
Parameters
----------
model : NetworkModel
y0 : dict
Initial condition.
volume : Real or Real3, optional
A size of the simulation volume.
is_valid : bool, optional
... | python | {
"resource": ""
} |
q237278 | load_sbml | train | def load_sbml(filename):
"""
Load a model from a SBML file.
Parameters
----------
filename : str
The input SBML filename.
Returns
-------
model : NetworkModel
y0 : dict
Initial condition.
volume : Real or Real3, optional
A size of the simulation volume.
... | python | {
"resource": ""
} |
q237279 | get_model | train | def get_model(is_netfree=False, without_reset=False, seeds=None, effective=False):
"""
Generate a model with parameters in the global scope, ``SPECIES_ATTRIBUTES``
and ``REACTIONRULES``.
Parameters
----------
is_netfree : bool, optional
Return ``NetfreeModel`` if True, and ``NetworkMode... | python | {
"resource": ""
} |
q237280 | run_serial | train | def run_serial(target, jobs, n=1, **kwargs):
"""
Evaluate the given function with each set of arguments, and return a list of results.
This function does in series.
Parameters
----------
target : function
A function to be evaluated. The function must accepts three arguments,
whi... | python | {
"resource": ""
} |
q237281 | run_multiprocessing | train | def run_multiprocessing(target, jobs, n=1, nproc=None, **kwargs):
"""
Evaluate the given function with each set of arguments, and return a list of results.
This function does in parallel by using `multiprocessing`.
Parameters
----------
target : function
A function to be evaluated. The ... | python | {
"resource": ""
} |
q237282 | run_azure | train | def run_azure(target, jobs, n=1, nproc=None, path='.', delete=True, config=None, **kwargs):
"""
Evaluate the given function with each set of arguments, and return a list of results.
This function does in parallel with Microsoft Azure Batch.
This function is the work in progress.
The argument `nproc... | python | {
"resource": ""
} |
q237283 | getseed | train | def getseed(myseed, i):
"""
Return a single seed from a long seed given by `genseeds`.
Parameters
----------
myseed : bytes
A long seed given by `genseeds(n)`.
i : int
An index less than n.
Returns
-------
rndseed : int
A seed (less than (2 ** 31))
"""
... | python | {
"resource": ""
} |
q237284 | list_species | train | def list_species(model, seeds=None):
"""This function is deprecated."""
seeds = None or []
from ecell4_base.core import Species
if not isinstance(seeds, list):
seeds = list(seeds)
expanded = model.expand([Species(serial) for serial in seeds])
species_list = [sp.serial() for sp in expa... | python | {
"resource": ""
} |
q237285 | _escapeCharacters | train | def _escapeCharacters(tag):
"""non-recursively escape underlines and asterisks
in the tag"""
for i,c in enumerate(tag.contents):
if type(c) != bs4.element.NavigableString:
continue
c.replace_with(_escapeCharSub(r'\\\1', c)) | python | {
"resource": ""
} |
q237286 | _breakRemNewlines | train | def _breakRemNewlines(tag):
"""non-recursively break spaces and remove newlines in the tag"""
for i,c in enumerate(tag.contents):
if type(c) != bs4.element.NavigableString:
continue
c.replace_with(re.sub(r' {2,}', ' ', c).replace('\n','')) | python | {
"resource": ""
} |
q237287 | convert | train | def convert(html):
"""converts an html string to markdown while preserving unsupported markup."""
bs = BeautifulSoup(html, 'html.parser')
_markdownify(bs)
ret = unicode(bs).replace(u'\xa0', ' ')
ret = re.sub(r'\n{3,}', r'\n\n', ret)
# ! FIXME: hack
ret = re.sub(r'<<<FLOATING LINK: (.+)>>>'... | python | {
"resource": ""
} |
q237288 | SWFFilterFactory.create | train | def create(cls, type):
""" Return the specified Filter """
if type == 0: return FilterDropShadow(id)
elif type == 1: return FilterBlur(id)
elif type == 2: return FilterGlow(id)
elif type == 3: return FilterBevel(id)
elif type == 4: return FilterGradientGlow(id)
el... | python | {
"resource": ""
} |
q237289 | SWF.export | train | def export(self, exporter=None, force_stroke=False):
"""
Export this SWF using the specified exporter.
When no exporter is passed in the default exporter used
is swf.export.SVGExporter.
Exporters should extend the swf.export.BaseExporter class.
@param ... | python | {
"resource": ""
} |
q237290 | SWF.parse | train | def parse(self, data):
"""
Parses the SWF.
The @data parameter can be a file object or a SWFStream
"""
self._data = data = data if isinstance(data, SWFStream) else SWFStream(data)
self._header = SWFHeader(self._data)
if self._header.compressed:
... | python | {
"resource": ""
} |
q237291 | int32 | train | def int32(x):
""" Return a signed or unsigned int """
if x>0xFFFFFFFF:
raise OverflowError
if x>0x7FFFFFFF:
x=int(0x100000000-x)
if x<2147483648:
return -x
else:
return -2147483648
return x | python | {
"resource": ""
} |
q237292 | SWFStream.bin | train | def bin(self, s):
""" Return a value as a binary string """
return str(s) if s<=1 else bin(s>>1) + str(s&1) | python | {
"resource": ""
} |
q237293 | SWFStream.calc_max_bits | train | def calc_max_bits(self, signed, values):
""" Calculates the maximim needed bits to represent a value """
b = 0
vmax = -10000000
for val in values:
if signed:
b = b | val if val >= 0 else b | ~val << 1
vmax = val if vmax < val else vmax... | python | {
"resource": ""
} |
q237294 | SWFStream.readbits | train | def readbits(self, bits):
"""
Read the specified number of bits from the stream.
Returns 0 for bits == 0.
"""
if bits == 0:
return 0
# fast byte-aligned path
if bits % 8 == 0 and self._bits_pending == 0:
return self._read_... | python | {
"resource": ""
} |
q237295 | SWFStream.readSB | train | def readSB(self, bits):
""" Read a signed int using the specified number of bits """
shift = 32 - bits
return int32(self.readbits(bits) << shift) >> shift | python | {
"resource": ""
} |
q237296 | SWFStream.readEncodedU32 | train | def readEncodedU32(self):
""" Read a encoded unsigned int """
self.reset_bits_pending();
result = self.readUI8();
if result & 0x80 != 0:
result = (result & 0x7f) | (self.readUI8() << 7)
if result & 0x4000 != 0:
result = (result & 0x3fff) | (self.re... | python | {
"resource": ""
} |
q237297 | SWFStream.readFLOAT16 | train | def readFLOAT16(self):
""" Read a 2 byte float """
self.reset_bits_pending()
word = self.readUI16()
sign = -1 if ((word & 0x8000) != 0) else 1
exponent = (word >> 10) & 0x1f
significand = word & 0x3ff
if exponent == 0:
if significand == 0:
... | python | {
"resource": ""
} |
q237298 | SWFStream.readSTYLECHANGERECORD | train | def readSTYLECHANGERECORD(self, states, fill_bits, line_bits, level = 1):
""" Read a SWFShapeRecordStyleChange """
return SWFShapeRecordStyleChange(self, states, fill_bits, line_bits, level) | python | {
"resource": ""
} |
q237299 | SWFStream.readTEXTRECORD | train | def readTEXTRECORD(self, glyphBits, advanceBits, previousRecord=None, level=1):
""" Read a SWFTextRecord """
if self.readUI8() == 0:
return None
else:
self.seek(self.tell() - 1)
return SWFTextRecord(self, glyphBits, advanceBits, previousRecord, level) | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.