code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def partition(list_, columns=2):
"""
Break a list into ``columns`` number of columns.
"""
iter_ = iter(list_)
columns = int(columns)
rows = []
while True:
row = []
for column_number in range(1, columns + 1):
try:
value = six.next(iter_)
... | Break a list into ``columns`` number of columns. |
def stream(self, area_code=values.unset, contains=values.unset,
sms_enabled=values.unset, mms_enabled=values.unset,
voice_enabled=values.unset,
exclude_all_address_required=values.unset,
exclude_local_address_required=values.unset,
exclude_forei... | Streams VoipInstance records from the API as a generator stream.
This operation lazily loads records as efficiently as possible until the limit
is reached.
The results are returned as a generator, so this operation is memory efficient.
:param unicode area_code: The area code of the phon... |
def _fmt_float(cls, x, **kw):
"""Float formatting class-method.
- x parameter is ignored. Instead kw-argument f being x float-converted
will be used.
- precision will be taken from `n` kw-argument.
"""
n = kw.get('n')
return '%.*f' % (n, cls._to_float(x)) | Float formatting class-method.
- x parameter is ignored. Instead kw-argument f being x float-converted
will be used.
- precision will be taken from `n` kw-argument. |
def _api_get(self, url, **kwargs):
"""
A convenience wrapper for _get. Adds headers, auth and base url by
default
"""
kwargs['url'] = self.url + url
kwargs['auth'] = self.auth
headers = deepcopy(self.headers)
headers.update(kwargs.get('headers', {}))
... | A convenience wrapper for _get. Adds headers, auth and base url by
default |
def remove_aspera_coordinator(self, transfer_coordinator):
''' remove entry from the waiting waiting
or remove item from processig queue and add to processed quque
notify background thread as it may be able to process watiign requests
'''
# usually called on processing co... | remove entry from the waiting waiting
or remove item from processig queue and add to processed quque
notify background thread as it may be able to process watiign requests |
def train_associations_SingleSNP(X, Y, U, S, C, numintervals, ldeltamin, ldeltamax):
"""
train_associations_SingleSNP(MatrixXd const & X, MatrixXd const & Y, MatrixXd const & U, MatrixXd const & S, MatrixXd const & C, int numintervals, double ldeltamin, double ldeltamax)
Parameters
----------
X: Ma... | train_associations_SingleSNP(MatrixXd const & X, MatrixXd const & Y, MatrixXd const & U, MatrixXd const & S, MatrixXd const & C, int numintervals, double ldeltamin, double ldeltamax)
Parameters
----------
X: MatrixXd const &
Y: MatrixXd const &
U: MatrixXd const &
S: MatrixXd const &
C: Mat... |
def add_layer_timing_signal_sinusoid_1d(x, layer, num_layers):
"""Add sinusoids of different frequencies as layer (vertical) timing signal.
Args:
x: a Tensor with shape [batch, length, channels]
layer: layer num
num_layers: total number of layers
Returns:
a Tensor the same shape as x.
"""
c... | Add sinusoids of different frequencies as layer (vertical) timing signal.
Args:
x: a Tensor with shape [batch, length, channels]
layer: layer num
num_layers: total number of layers
Returns:
a Tensor the same shape as x. |
def ws010c(self, value=None):
""" Corresponds to IDD Field `ws010c`
Wind speed corresponding to 1.0% cumulative frequency
of occurrence for coldest month;
Args:
value (float): value for IDD Field `ws010c`
Unit: m/s
if `value` is None it will ... | Corresponds to IDD Field `ws010c`
Wind speed corresponding to 1.0% cumulative frequency
of occurrence for coldest month;
Args:
value (float): value for IDD Field `ws010c`
Unit: m/s
if `value` is None it will not be checked against the
... |
def is_valid_int_param(param):
"""Verifica se o parâmetro é um valor inteiro válido.
:param param: Valor para ser validado.
:return: True se o parâmetro tem um valor inteiro válido, ou False, caso contrário.
"""
if param is None:
return False
try:
param = int(param)
if ... | Verifica se o parâmetro é um valor inteiro válido.
:param param: Valor para ser validado.
:return: True se o parâmetro tem um valor inteiro válido, ou False, caso contrário. |
def _init_bins(self, binset):
"""Calculated binned wavelength centers, edges, and flux.
By contrast, the native waveset and flux should be considered
samples of a continuous function.
Thus, it makes sense to interpolate ``self.waveset`` and
``self(self.waveset)``, but not `bins... | Calculated binned wavelength centers, edges, and flux.
By contrast, the native waveset and flux should be considered
samples of a continuous function.
Thus, it makes sense to interpolate ``self.waveset`` and
``self(self.waveset)``, but not `binset` and `binflux`. |
def p_ComplianceModules(self, p):
"""ComplianceModules : ComplianceModules ComplianceModule
| ComplianceModule"""
n = len(p)
if n == 3:
p[0] = ('ComplianceModules', p[1][1] + [p[2]])
elif n == 2:
p[0] = ('ComplianceModules', [p[1]]) | ComplianceModules : ComplianceModules ComplianceModule
| ComplianceModule |
def peek(self, n):
"""Peek an n bit integer from the stream without updating the pointer.
It is not an error to read beyond the end of the stream.
>>> olleke.data[:2]==b'\x1b\x2e' and 0x2e1b==11803
True
>>> olleke.peek(15)
11803
>>> hex(olleke.peek(32))
'0... | Peek an n bit integer from the stream without updating the pointer.
It is not an error to read beyond the end of the stream.
>>> olleke.data[:2]==b'\x1b\x2e' and 0x2e1b==11803
True
>>> olleke.peek(15)
11803
>>> hex(olleke.peek(32))
'0x2e1b' |
def websocket_url_for_server_url(url):
''' Convert an ``http(s)`` URL for a Bokeh server websocket endpoint into
the appropriate ``ws(s)`` URL
Args:
url (str):
An ``http(s)`` URL
Returns:
str:
The corresponding ``ws(s)`` URL ending in ``/ws``
Raises:
... | Convert an ``http(s)`` URL for a Bokeh server websocket endpoint into
the appropriate ``ws(s)`` URL
Args:
url (str):
An ``http(s)`` URL
Returns:
str:
The corresponding ``ws(s)`` URL ending in ``/ws``
Raises:
ValueError:
If the input URL is n... |
def create_pool(self, name, raid_groups, description=None, **kwargs):
"""Create pool based on RaidGroupParameter.
:param name: pool name
:param raid_groups: a list of *RaidGroupParameter*
:param description: pool description
:param alert_threshold: Threshold at which the system ... | Create pool based on RaidGroupParameter.
:param name: pool name
:param raid_groups: a list of *RaidGroupParameter*
:param description: pool description
:param alert_threshold: Threshold at which the system will generate
alerts about the free space in the pool, specified a... |
def get_foreign_keys_in_altered_table(self, diff):
"""
:param diff: The table diff
:type diff: eloquent.dbal.table_diff.TableDiff
:rtype: list
"""
foreign_keys = diff.from_table.get_foreign_keys()
column_names = self.get_column_names_in_altered_table(diff)
... | :param diff: The table diff
:type diff: eloquent.dbal.table_diff.TableDiff
:rtype: list |
def startproject(project_name):
"""
build a full status project
"""
# the destination path
dst_path = os.path.join(os.getcwd(), project_name)
start_init_info(dst_path)
# create dst path
_mkdir_p(dst_path)
# create project tree
os.chdir(dst_path)
# create files
init_code... | build a full status project |
def res_obs_v_sim(pst,logger=None, filename=None, **kwargs):
"""
timeseries plot helper...in progress
"""
if logger is None:
logger=Logger('Default_Loggger.log',echo=False)
logger.log("plot res_obs_v_sim")
if "ensemble" in kwargs:
try:
res=pst_utils.res_from_en(pst... | timeseries plot helper...in progress |
def display_for_value(value, request=None):
"""
Converts humanized value
examples:
boolean True/Talse ==> Yes/No
objects ==> object display name with link if current user has permissions to see the object
datetime ==> in localized format
"""
from is_core.utils.compatibility ... | Converts humanized value
examples:
boolean True/Talse ==> Yes/No
objects ==> object display name with link if current user has permissions to see the object
datetime ==> in localized format |
def min_value(self):
"""
The minimum pixel value of the ``data`` within the source
segment.
"""
if self._is_completely_masked:
return np.nan * self._data_unit
else:
return np.min(self.values) | The minimum pixel value of the ``data`` within the source
segment. |
def dshield_ip_check(ip):
"""Checks dshield for info on an IP address"""
if not is_IPv4Address(ip):
return None
headers = {'User-Agent': useragent}
url = 'https://isc.sans.edu/api/ip/'
response = requests.get('{0}{1}?json'.format(url, ip), headers=headers)
return response.json() | Checks dshield for info on an IP address |
def remove_binding(site, hostheader='', ipaddress='*', port=80):
'''
Remove an IIS binding.
Args:
site (str): The IIS site name.
hostheader (str): The host header of the binding.
ipaddress (str): The IP address of the binding.
port (int): The TCP port of the binding.
Re... | Remove an IIS binding.
Args:
site (str): The IIS site name.
hostheader (str): The host header of the binding.
ipaddress (str): The IP address of the binding.
port (int): The TCP port of the binding.
Returns:
bool: True if successful, otherwise False
CLI Example:
... |
def leaveEvent( self, event ):
"""
Toggles the display for the tracker item.
"""
item = self.trackerItem()
if ( item ):
item.setVisible(False) | Toggles the display for the tracker item. |
def _authenticate_cram_md5(credentials, sock_info):
"""Authenticate using CRAM-MD5 (RFC 2195)
"""
source = credentials.source
username = credentials.username
password = credentials.password
# The password used as the mac key is the
# same as what we use for MONGODB-CR
passwd = _password_... | Authenticate using CRAM-MD5 (RFC 2195) |
def _grouper(iterable, n_args, fillvalue=None):
"""
Banana banana
"""
args = [iter(iterable)] * n_args
return zip_longest(*args, fillvalue=fillvalue) | Banana banana |
def get(self, query, sort, page, size):
"""Get a list of all the communities.
.. http:get:: /communities/(string:id)
Returns a JSON list with all the communities.
**Request**:
.. sourcecode:: http
GET /communities HTTP/1.1
Accept: appl... | Get a list of all the communities.
.. http:get:: /communities/(string:id)
Returns a JSON list with all the communities.
**Request**:
.. sourcecode:: http
GET /communities HTTP/1.1
Accept: application/json
Content-Type: applicat... |
async def async_enqueue_sync(self, func, *func_args):
'''
Enqueue an arbitrary synchronous function.
'''
worker = self.pick_sticky(0) # just pick first always
args = (func,) + func_args
await worker.enqueue(enums.Task.FUNC, args) | Enqueue an arbitrary synchronous function. |
def _list_templates(settings):
"""
List templates from settings.
"""
for idx, option in enumerate(settings.config.get("project_templates"), start=1):
puts(" {0!s:5} {1!s:36}".format(
colored.yellow("[{0}]".format(idx)),
colored.cyan(option.get("name"))
))
... | List templates from settings. |
def output_selector_schema(config_cls):
'''
A decorator for a annotating a function that can take the selected properties
of a ``config_value`` and an instance of a custom type and materialize it.
Args:
config_cls (Selector):
'''
config_type = resolve_config_cls_arg(config_cls)
chec... | A decorator for a annotating a function that can take the selected properties
of a ``config_value`` and an instance of a custom type and materialize it.
Args:
config_cls (Selector): |
def _join_all_filenames_and_text(
self):
"""
*join all file names, driectory names and text content together*
"""
self.log.info('starting the ``_join_all_filenames_and_text`` method')
contentString = u""
for i in self.directoryContents:
contentStr... | *join all file names, driectory names and text content together* |
def predict_encoding(file_path, n_lines=20):
'''Get file encoding of a text file'''
import chardet
# Open the file as binary data
with open(file_path, 'rb') as f:
# Join binary lines for specified number of lines
rawdata = b''.join([f.readline() for _ in range(n_lines)])
return cha... | Get file encoding of a text file |
def pdf_rotate(
input: str,
counter_clockwise: bool = False,
pages: [str] = None,
output: str = None,
):
"""
Rotate the given Pdf files clockwise or counter clockwise.
:param inputs: pdf files
:param counter_clockwise: rotate counter clockwise if true else clockwise
:param pages: lis... | Rotate the given Pdf files clockwise or counter clockwise.
:param inputs: pdf files
:param counter_clockwise: rotate counter clockwise if true else clockwise
:param pages: list of page numbers to rotate, if None all pages will be
rotated |
def _fmt_auto(cls, x, **kw):
"""auto formatting class-method."""
f = cls._to_float(x)
if abs(f) > 1e8:
fn = cls._fmt_exp
else:
if f - round(f) == 0:
fn = cls._fmt_int
else:
fn = cls._fmt_float
return fn(x, **kw) | auto formatting class-method. |
def run_pipelines(pipeline_id_pattern,
root_dir,
use_cache=True,
dirty=False,
force=False,
concurrency=1,
verbose_logs=True,
progress_cb=None,
slave=False):
"""Run a pipeli... | Run a pipeline by pipeline-id.
pipeline-id supports the '%' wildcard for any-suffix matching.
Use 'all' or '%' for running all pipelines |
def from_url(cls, db_url=ALL_SETS_ZIP_URL):
"""Load card data from a URL.
Uses :func:`requests.get` to fetch card data. Also handles zipfiles.
:param db_url: URL to fetch.
:return: A new :class:`~mtgjson.CardDb` instance.
"""
r = requests.get(db_url)
r.raise_for... | Load card data from a URL.
Uses :func:`requests.get` to fetch card data. Also handles zipfiles.
:param db_url: URL to fetch.
:return: A new :class:`~mtgjson.CardDb` instance. |
def detach_framebuffer(self, screen_id, id_p):
"""Removes the graphics updates target for a screen.
in screen_id of type int
in id_p of type str
"""
if not isinstance(screen_id, baseinteger):
raise TypeError("screen_id can only be an instance of type baseinteger")
... | Removes the graphics updates target for a screen.
in screen_id of type int
in id_p of type str |
def compute_evolution_by_frequency(
df,
id_cols: List[str],
date_col: Union[str, Dict[str, str]],
value_col: str,
freq=1,
method: str = 'abs',
format: str = 'column',
offseted_suffix: str = '_offseted',
evolution_col_name: str = 'evolution_computed',
missing_date_as_zero: bool = ... | This function answers the question: how has a value changed on a weekly, monthly, yearly basis ?
---
### Parameters
*mandatory :*
- `id_cols` (*list*): name of the columns used to create each group.
- `date_col` (*str or dict*): either directly the name of the column containing the date or a dict... |
def controller(self, *paths, **query_kwargs):
"""create a new url object using the controller path as a base
if you have a controller `foo.BarController` then this would create a new
Url instance with `host/foo/bar` as the base path, so any *paths will be
appended to `/foo/bar`
... | create a new url object using the controller path as a base
if you have a controller `foo.BarController` then this would create a new
Url instance with `host/foo/bar` as the base path, so any *paths will be
appended to `/foo/bar`
:example:
# controller foo.BarController
... |
def table(self, name=DEFAULT_TABLE, **options):
"""
Get access to a specific table.
Creates a new table, if it hasn't been created before, otherwise it
returns the cached :class:`~tinydb.Table` object.
:param name: The name of the table.
:type name: str
:param c... | Get access to a specific table.
Creates a new table, if it hasn't been created before, otherwise it
returns the cached :class:`~tinydb.Table` object.
:param name: The name of the table.
:type name: str
:param cache_size: How many query results to cache.
:param table_cla... |
def tileAddress(self, zoom, point):
"Returns a tile address based on a zoom level and \
a point in the tile"
[x, y] = point
assert x <= self.MAXX and x >= self.MINX
assert y <= self.MAXY and y >= self.MINY
assert zoom in range(0, len(self.RESOLUTIONS))
tileS = se... | Returns a tile address based on a zoom level and \
a point in the tile |
def return_hdr(self):
"""
subj_id : str
subject identification code
start_time : datetime
start time of the dataset
s_freq : float
sampling frequency
chan_name : list of str
list of all the channels
n_samples : int
... | subj_id : str
subject identification code
start_time : datetime
start time of the dataset
s_freq : float
sampling frequency
chan_name : list of str
list of all the channels
n_samples : int
number of samples in the dataset
... |
def accel_zoom_in(self, *args):
"""Callback to zoom in.
"""
for term in self.get_notebook().iter_terminals():
term.increase_font_size()
return True | Callback to zoom in. |
def _se_all(self):
"""Standard errors (SE) for all parameters, including the intercept."""
err = np.expand_dims(self._ms_err, axis=1)
t1 = np.diagonal(
np.linalg.inv(np.matmul(self.xwins.swapaxes(1, 2), self.xwins)),
axis1=1,
axis2=2,
)
... | Standard errors (SE) for all parameters, including the intercept. |
def _post_run_hook(self, runtime):
''' generates a report showing nine slices, three per axis, of an
arbitrary volume of `in_files`, with the resulting segmentation
overlaid '''
outputs = self.aggregate_outputs(runtime=runtime)
self._anat_file = os.path.join(outputs.subjects_dir,... | generates a report showing nine slices, three per axis, of an
arbitrary volume of `in_files`, with the resulting segmentation
overlaid |
def _get_stddevs(self, C, stddev_types, num_sites):
"""
Return total standard deviation as described in paragraph 5.2 pag 200.
"""
# interevent stddev
sigma_inter = C['tau'] + np.zeros(num_sites)
# intraevent std
sigma_intra = C['sigma'] + np.zeros(num_sites)
... | Return total standard deviation as described in paragraph 5.2 pag 200. |
def docs(ctx, clean=False, browse=False, watch=False):
"""Build the docs."""
if clean:
clean_docs(ctx)
if watch:
watch_docs(ctx, browse=browse)
else:
build_docs(ctx, browse=browse) | Build the docs. |
def elastic_install(self):
"""
elasticsearch install
:return:
"""
with cd('/tmp'):
if not exists('elastic.deb'):
sudo('wget {0} -O elastic.deb'.format(
bigdata_conf.elastic_download_url
))
sudo('dpkg -i ... | elasticsearch install
:return: |
def match(self, metadata, user = None):
"""Does the specified metadata match this template? returns (success,metadata,parameters)"""
assert isinstance(metadata, self.formatclass)
return self.generate(metadata,user) | Does the specified metadata match this template? returns (success,metadata,parameters) |
def configure_cache(app):
""" Sets up an attribute to cache data in the app context """
log = logging.getLogger('ara.webapp.configure_cache')
log.debug('Configuring cache')
if not getattr(app, '_cache', None):
app._cache = {} | Sets up an attribute to cache data in the app context |
def alias_action(self, *args, **kwargs):
"""
Alias one or more actions into another one.
self.alias_action('create', 'read', 'update', 'delete', to='crud')
"""
to = kwargs.pop('to', None)
if not to:
return
error_message = ("You can't specify target (... | Alias one or more actions into another one.
self.alias_action('create', 'read', 'update', 'delete', to='crud') |
def set_memory_params(self, ksm_interval=None, no_swap=None):
"""Set memory related parameters.
:param int ksm_interval: Kernel Samepage Merging frequency option, that can reduce memory usage.
Accepts a number of requests (or master process cycles) to run page scanner after.
..... | Set memory related parameters.
:param int ksm_interval: Kernel Samepage Merging frequency option, that can reduce memory usage.
Accepts a number of requests (or master process cycles) to run page scanner after.
.. note:: Linux only.
* http://uwsgi.readthedocs.io/en/latest/... |
def create_folder(name, location='\\'):
r'''
Create a folder in which to create tasks.
:param str name: The name of the folder. This will be displayed in the task
scheduler.
:param str location: A string value representing the location in which to
create the folder. Default is '\\' whi... | r'''
Create a folder in which to create tasks.
:param str name: The name of the folder. This will be displayed in the task
scheduler.
:param str location: A string value representing the location in which to
create the folder. Default is '\\' which is the root for the task
schedule... |
def locate_ranges(self, starts, stops, strict=True):
"""Locate items within the given ranges.
Parameters
----------
starts : array_like, int
Range start values.
stops : array_like, int
Range stop values.
strict : bool, optional
If True... | Locate items within the given ranges.
Parameters
----------
starts : array_like, int
Range start values.
stops : array_like, int
Range stop values.
strict : bool, optional
If True, raise KeyError if any ranges contain no entries.
Retu... |
def forwards(apps, schema_editor):
"""
Re-save all the Works because something earlier didn't create their slugs.
"""
Work = apps.get_model('spectator_events', 'Work')
for work in Work.objects.all():
if not work.slug:
work.slug = generate_slug(work.pk)
work.save() | Re-save all the Works because something earlier didn't create their slugs. |
def _GetTable(self):
"""Returns table, with column headers and separators.
Returns:
The whole table including headers as a string. Each row is
joined by a newline and each entry by self.separator.
"""
result = []
# Avoid the global lookup cost on each iteration.
lstr = str
for r... | Returns table, with column headers and separators.
Returns:
The whole table including headers as a string. Each row is
joined by a newline and each entry by self.separator. |
def connection_made(self, transport):
'''
override _SiriDBProtocol
'''
self.transport = transport
self.remote_ip, self.port = transport.get_extra_info('peername')[:2]
logging.debug(
'Connection made (address: {} port: {})'
.format(self.remote_ip,... | override _SiriDBProtocol |
def compound_powerspec(data, tbin, Df=None, pointProcess=False):
"""
Calculate the power spectrum of the compound/sum signal.
data is first summed across units, then the power spectrum is calculated.
If pointProcess=True, power spectra are normalized by the length T of
the time series.
Pa... | Calculate the power spectrum of the compound/sum signal.
data is first summed across units, then the power spectrum is calculated.
If pointProcess=True, power spectra are normalized by the length T of
the time series.
Parameters
----------
data : numpy.ndarray,
1st axis unit, 2nd... |
def l2traceroute_result_output_l2_hop_results_l2_hop_ingress_interface_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
l2traceroute_result = ET.Element("l2traceroute_result")
config = l2traceroute_result
output = ET.SubElement(l2traceroute_r... | Auto Generated Code |
async def writelines(self, lines, eof = False, buffering = True):
"""
Write lines to current output stream
"""
for l in lines:
await self.write(l, False, buffering)
if eof:
await self.write(b'', eof, buffering) | Write lines to current output stream |
def __collapseLineOrCol(self, line, d):
"""
Merge tiles in a line or column according to a direction and return a
tuple with the new line and the score for the move on this line
"""
if (d == Board.LEFT or d == Board.UP):
inc = 1
rg = xrange(0, self.__size-... | Merge tiles in a line or column according to a direction and return a
tuple with the new line and the score for the move on this line |
def render_in_page(request, template):
"""return rendered template in standalone mode or ``False``
"""
from leonardo.module.web.models import Page
page = request.leonardo_page if hasattr(
request, 'leonardo_page') else Page.objects.filter(parent=None).first()
if page:
try:
... | return rendered template in standalone mode or ``False`` |
def _get_rules_from_aws(self):
"""
Load the EC2 security rules off AWS into a list of dict.
Returns:
list
"""
list_of_rules = list()
if self.profile:
boto3.setup_default_session(profile_name=self.profile)
if self.region:
ec2 ... | Load the EC2 security rules off AWS into a list of dict.
Returns:
list |
def force_constants(self, force_constants):
"""Set force constants
Parameters
----------
force_constants : array_like
Force constants matrix. If this is given in own condiguous ndarray
with order='C' and dtype='double', internal copy of data is
avoide... | Set force constants
Parameters
----------
force_constants : array_like
Force constants matrix. If this is given in own condiguous ndarray
with order='C' and dtype='double', internal copy of data is
avoided. Therefore some computational resources are saved.
... |
def scan(host, port=80, url=None, https=False, timeout=1, max_size=65535):
"""
Scan a network port
Parameters
----------
host : str
Host or ip address to scan
port : int, optional
Port to scan, default=80
url : str, optional
URL to perform get request to on the hos... | Scan a network port
Parameters
----------
host : str
Host or ip address to scan
port : int, optional
Port to scan, default=80
url : str, optional
URL to perform get request to on the host and port specified
https : bool, optional
Perform ssl connection on the ... |
def disableGroup(self):
"""Disables all radio buttons in the group"""
radioButtonListInGroup = PygWidgetsRadioButton.__PygWidgets__Radio__Buttons__Groups__Dicts__[self.group]
for radioButton in radioButtonListInGroup:
radioButton.disable() | Disables all radio buttons in the group |
def reqHeadTimeStamp(
self, contract: Contract, whatToShow: str,
useRTH: bool, formatDate: int = 1) -> datetime.datetime:
"""
Get the datetime of earliest available historical data
for the contract.
Args:
contract: Contract of interest.
us... | Get the datetime of earliest available historical data
for the contract.
Args:
contract: Contract of interest.
useRTH: If True then only show data from within Regular
Trading Hours, if False then show all data.
formatDate: If set to 2 then the result ... |
def dump_np_vars(self, store_format='csv', delimiter=','):
"""
Dump the TDS simulation data to files by calling subroutines `write_lst` and
`write_np_dat`.
Parameters
-----------
store_format : str
dump format in `('csv', 'txt', 'hdf5')`
delimiter :... | Dump the TDS simulation data to files by calling subroutines `write_lst` and
`write_np_dat`.
Parameters
-----------
store_format : str
dump format in `('csv', 'txt', 'hdf5')`
delimiter : str
delimiter for the `csv` and `txt` format
Returns
... |
def _concat_translations(translations: List[Translation],
stop_ids: Set[int],
length_penalty: LengthPenalty,
brevity_penalty: Optional[BrevityPenalty] = None) -> Translation:
"""
Combines translations through concatenation.
:param t... | Combines translations through concatenation.
:param translations: A list of translations (sequence starting with BOS symbol, attention_matrix), score and length.
:param stop_ids: The EOS symbols.
:param length_penalty: Instance of the LengthPenalty class initialized with alpha and beta.
:param brevity_... |
def load_map(path, value):
'''
Loads the map at the specified path, and returns the specified value from
that map.
CLI Example:
.. code-block:: bash
# Assuming the map is loaded in your formula SLS as follows:
#
# {% from "myformula/map.jinja" import myformula with context... | Loads the map at the specified path, and returns the specified value from
that map.
CLI Example:
.. code-block:: bash
# Assuming the map is loaded in your formula SLS as follows:
#
# {% from "myformula/map.jinja" import myformula with context %}
#
# the following s... |
def adaptive_model_average(X, penalization, method):
"""Run ModelAverage in default mode (QuicGraphicalLassoCV) to obtain proportion
matrix.
NOTE: Only method = 'binary' really makes sense in this case.
"""
n_trials = 100
print("Adaptive ModelAverage with:")
print(" estimator: QuicGraphi... | Run ModelAverage in default mode (QuicGraphicalLassoCV) to obtain proportion
matrix.
NOTE: Only method = 'binary' really makes sense in this case. |
def plot_calibrated_diode(dio_cross,chan_per_coarse=8,feedtype='l',**kwargs):
'''
Plots the corrected noise diode spectrum for a given noise diode measurement
after application of the inverse Mueller matrix for the electronics chain.
'''
#Get full stokes data for the ND observation
obs = Waterfa... | Plots the corrected noise diode spectrum for a given noise diode measurement
after application of the inverse Mueller matrix for the electronics chain. |
def _grab_raw_image(self):
"""
:returns: the current 3-channel image
"""
m = self.ale.getScreenRGB()
return m.reshape((self.height, self.width, 3)) | :returns: the current 3-channel image |
def start(self, blocking=True):
"""Start the producer. This will eventually fire the ``server_start``
and ``running`` events in sequence, which signify that the incoming
TCP request socket is running and the workers have been forked,
respectively. If ``blocking`` is False, control ."""... | Start the producer. This will eventually fire the ``server_start``
and ``running`` events in sequence, which signify that the incoming
TCP request socket is running and the workers have been forked,
respectively. If ``blocking`` is False, control . |
def is_module_function(obj, prop):
"""
Checking and setting type to MODULE_FUNCTION
Args:
obj: ModuleType
prop: FunctionType
Return:
Boolean
Raise:
prop_type_error: When the type of prop is not valid
prop_in_obj_error: When prop is not in the obj(module/class)... | Checking and setting type to MODULE_FUNCTION
Args:
obj: ModuleType
prop: FunctionType
Return:
Boolean
Raise:
prop_type_error: When the type of prop is not valid
prop_in_obj_error: When prop is not in the obj(module/class)
prop_is_func_error: When prop is not a... |
def getargspec(func):
"""
Used because getargspec for python 2.7 does not accept functools.partial
which is the type for pytest fixtures.
getargspec excerpted from:
sphinx.util.inspect
~~~~~~~~~~~~~~~~~~~
Helpers for inspecting Python modules.
:copyright: Copyright 2007-2018 by the Sph... | Used because getargspec for python 2.7 does not accept functools.partial
which is the type for pytest fixtures.
getargspec excerpted from:
sphinx.util.inspect
~~~~~~~~~~~~~~~~~~~
Helpers for inspecting Python modules.
:copyright: Copyright 2007-2018 by the Sphinx team, see AUTHORS.
:licens... |
def from_events(self, instance, ev_args, ctx):
"""
Collect the events and convert them to a single XML subtree, which then
gets appended to the list at `instance`. `ev_args` must be the
arguments of the ``"start"`` event of the new child.
This method is suspendable.
"""
... | Collect the events and convert them to a single XML subtree, which then
gets appended to the list at `instance`. `ev_args` must be the
arguments of the ``"start"`` event of the new child.
This method is suspendable. |
def as_python(self, infile, include_original_shex: bool=False):
""" Return the python representation of the document """
self._context.resolve_circular_references() # add forwards for any circular entries
body = ''
for k in self._context.ordered_elements():
v = sel... | Return the python representation of the document |
def return_xyz(self, labels=None):
"""Returns the location in xy for some channels.
Parameters
----------
labels : list of str, optional
the names of the channels.
Returns
-------
numpy.ndarray
a 3xn vector with the position of a channel.... | Returns the location in xy for some channels.
Parameters
----------
labels : list of str, optional
the names of the channels.
Returns
-------
numpy.ndarray
a 3xn vector with the position of a channel. |
def poa_horizontal_ratio(surface_tilt, surface_azimuth,
solar_zenith, solar_azimuth):
"""
Calculates the ratio of the beam components of the plane of array
irradiance and the horizontal irradiance.
Input all angles in degrees.
Parameters
----------
surface_tilt : n... | Calculates the ratio of the beam components of the plane of array
irradiance and the horizontal irradiance.
Input all angles in degrees.
Parameters
----------
surface_tilt : numeric
Panel tilt from horizontal.
surface_azimuth : numeric
Panel azimuth from north.
solar_zenith... |
def mark(self, partition, offset):
"""
Set the high-water mark in the current context.
In order to know the current partition, it is helpful to initialize
the consumer to provide partition info via:
.. code:: python
consumer.provide_partition_info()
"""
... | Set the high-water mark in the current context.
In order to know the current partition, it is helpful to initialize
the consumer to provide partition info via:
.. code:: python
consumer.provide_partition_info() |
def char_sets():
"""Return a list of the IANA Character Sets, or an empty list if the
IANA website is unreachable.
Store it as a function attribute so that we only build the list once.
"""
if not hasattr(char_sets, 'setlist'):
clist = []
try:
data = requests.get('http://w... | Return a list of the IANA Character Sets, or an empty list if the
IANA website is unreachable.
Store it as a function attribute so that we only build the list once. |
def parse_translation(f, lineno):
"""Read a single translation entry from the file F and return a
tuple with the comments, msgid and msgstr. The comments is returned
as a list of lines which do not end in new-lines. The msgid and
msgstr are strings, possibly with embedded newlines"""
line = f... | Read a single translation entry from the file F and return a
tuple with the comments, msgid and msgstr. The comments is returned
as a list of lines which do not end in new-lines. The msgid and
msgstr are strings, possibly with embedded newlines |
def _render_reward(self, r: np.float32) -> None:
'''Prints reward `r`.'''
print("reward = {:.4f}".format(float(r)))
print() | Prints reward `r`. |
def get_flexports_output_flexport_list_port_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_flexports = ET.Element("get_flexports")
config = get_flexports
output = ET.SubElement(get_flexports, "output")
flexport_list = ET.SubElemen... | Auto Generated Code |
def associate_keys(user_dict, client):
"""
This whole function is black magic, had to however cause of the way we keep key-machine association
"""
added_keys = user_dict['keypairs']
print ">>>Updating Keys-Machines association"
for key in added_keys:
machines = added_keys[key]['machines... | This whole function is black magic, had to however cause of the way we keep key-machine association |
def gc(cn, ns=None, lo=None, iq=None, ico=None, pl=None):
"""
This function is a wrapper for
:meth:`~pywbem.WBEMConnection.GetClass`.
Retrieve a class.
Parameters:
cn (:term:`string` or :class:`~pywbem.CIMClassName`):
Name of the class to be retrieved (case independent).
... | This function is a wrapper for
:meth:`~pywbem.WBEMConnection.GetClass`.
Retrieve a class.
Parameters:
cn (:term:`string` or :class:`~pywbem.CIMClassName`):
Name of the class to be retrieved (case independent).
If specified as a `CIMClassName` object, its `host` attribute will b... |
def get_res(ds, t_srs=None, square=False):
"""Get GDAL Dataset raster resolution
"""
gt = ds.GetGeoTransform()
ds_srs = get_ds_srs(ds)
#This is Xres, Yres
res = [gt[1], np.abs(gt[5])]
if square:
res = [np.mean(res), np.mean(res)]
if t_srs is not None and not ds_srs.IsSame(t_srs):... | Get GDAL Dataset raster resolution |
def fit(self, X, y):
"""Learn vocabulary from training set.
Args:
X : iterable. An iterable which yields either str, unicode or file objects.
Returns:
self : IndexTransformer.
"""
self._word_vocab.add_documents(X)
self._label_vocab.add_documents(... | Learn vocabulary from training set.
Args:
X : iterable. An iterable which yields either str, unicode or file objects.
Returns:
self : IndexTransformer. |
def commit_sell(self, account_id, sell_id, **params):
"""https://developers.coinbase.com/api/v2#commit-a-sell"""
response = self._post(
'v2', 'accounts', account_id, 'sells', sell_id, 'commit', data=params)
return self._make_api_object(response, Sell) | https://developers.coinbase.com/api/v2#commit-a-sell |
def to_dict(self):
"""
Return the node as a dictionary.
Returns
-------
dict: All the attributes of this node as a dictionary (minus the left
and right).
"""
out = {}
for key in self.__dict__.keys():
if key not in ['left', 'right... | Return the node as a dictionary.
Returns
-------
dict: All the attributes of this node as a dictionary (minus the left
and right). |
def copy_directory(src, dest, force=False):
''' Copy an entire directory recursively
'''
if os.path.exists(dest) and force is True:
shutil.rmtree(dest)
try:
shutil.copytree(src, dest)
except OSError as e:
# If the error was caused because the source wasn't a directory
... | Copy an entire directory recursively |
def info(self, msg, indent=0, **kwargs):
"""invoke ``self.info.debug``"""
return self.logger.info(self._indent(msg, indent), **kwargs) | invoke ``self.info.debug`` |
def _collapse_outgroup(tree, taxdicts):
""" collapse outgroup in ete Tree for easier viewing """
## check that all tests have the same outgroup
outg = taxdicts[0]["p4"]
if not all([i["p4"] == outg for i in taxdicts]):
raise Exception("no good")
## prune tree, keep only one sample from ou... | collapse outgroup in ete Tree for easier viewing |
def request_fetch(self, user, repo, request, pull=False, force=False): #pragma: no cover
'''Fetches given request as a branch, and switch if pull is true
:param repo: name of the repository to create
Meant to be implemented by subclasses
'''
raise NotImplementedError | Fetches given request as a branch, and switch if pull is true
:param repo: name of the repository to create
Meant to be implemented by subclasses |
def enable_llama_ha(self, new_llama_host_id, zk_service_name=None,
new_llama_role_name=None):
"""
Enable high availability for an Impala Llama ApplicationMaster.
This command only applies to CDH 5.1+ Impala services.
@param new_llama_host_id: id of the host where the second Llama... | Enable high availability for an Impala Llama ApplicationMaster.
This command only applies to CDH 5.1+ Impala services.
@param new_llama_host_id: id of the host where the second Llama role
will be added.
@param zk_service_name: Name of the ZooKeeper service to use for
... |
def start(vm_name, call=None):
'''
Call GCE 'start on the instance.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt-cloud -a start myinstance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The start action must be called with -a or --ac... | Call GCE 'start on the instance.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt-cloud -a start myinstance |
def get_command_arg_list(self, command_name: str, to_parse: Union[Statement, str],
preserve_quotes: bool) -> Tuple[Statement, List[str]]:
"""
Called by the argument_list and argparse wrappers to retrieve just the arguments being
passed to their do_* methods as a list... | Called by the argument_list and argparse wrappers to retrieve just the arguments being
passed to their do_* methods as a list.
:param command_name: name of the command being run
:param to_parse: what is being passed to the do_* method. It can be one of two types:
1. An ... |
def _HasId(self, schedule, entity_id):
"""Check if the schedule has an entity with the given id.
Args:
schedule: The transitfeed.Schedule instance to look in.
entity_id: The id of the entity.
Returns:
True if the schedule has an entity with the id or False if not.
"""
try:
... | Check if the schedule has an entity with the given id.
Args:
schedule: The transitfeed.Schedule instance to look in.
entity_id: The id of the entity.
Returns:
True if the schedule has an entity with the id or False if not. |
def find_segment(self, ea):
""" do a linear search for the given address in the segment list """
for seg in self.seglist:
if seg.startea <= ea < seg.endea:
return seg | do a linear search for the given address in the segment list |
def edit_by_id(
self,
id_equip_acesso,
id_tipo_acesso,
fqdn,
user,
password,
enable_pass):
"""Edit access type, fqdn, user, password and enable_pass of the relationship of
equipment and access type.
:param id_ti... | Edit access type, fqdn, user, password and enable_pass of the relationship of
equipment and access type.
:param id_tipo_acesso: Access type identifier.
:param id_equip_acesso: Equipment identifier.
:param fqdn: Equipment FQDN.
:param user: User.
:param password: Password... |
def find_visible_elements(self, selector, by=By.CSS_SELECTOR, limit=0):
""" Returns a list of matching WebElements that are visible.
If "limit" is set and > 0, will only return that many elements. """
self.wait_for_ready_state_complete()
if page_utils.is_xpath_selector(selector):
... | Returns a list of matching WebElements that are visible.
If "limit" is set and > 0, will only return that many elements. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.