code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def nmap_smb_vulnscan():
"""
Scans available smb services in the database for smb signing and ms17-010.
"""
service_search = ServiceSearch()
services = service_search.get_services(ports=['445'], tags=['!smb_vulnscan'], up=True)
services = [service for service in services]
service_dict = ... | Scans available smb services in the database for smb signing and ms17-010. |
def main(command_line=True, **kwargs):
"""
NAME
iodp_jr6_magic.py
DESCRIPTION
converts shipboard .jr6 format files to magic_measurements format files
SYNTAX
iodp_jr6_magic.py [command line options]
OPTIONS
-h: prints the help message and quits.
-f FILE: spe... | NAME
iodp_jr6_magic.py
DESCRIPTION
converts shipboard .jr6 format files to magic_measurements format files
SYNTAX
iodp_jr6_magic.py [command line options]
OPTIONS
-h: prints the help message and quits.
-f FILE: specify input file, or
-F FILE: specify outpu... |
def use(cls, ec):
"""
use will duplicate a new Model class and bind ec
ec is Engine name or Sesstion object
"""
if isinstance(ec, (str, unicode)):
m = get_model(cls._alias, ec, signal=False)
else:
m = cls._use(ec)
return m | use will duplicate a new Model class and bind ec
ec is Engine name or Sesstion object |
def is_orderable(cls):
"""
Checks if the provided class is specified as an orderable in
settings.ORDERABLE_MODELS. If it is return its settings.
"""
if not getattr(settings, 'ORDERABLE_MODELS', None):
return False
labels = resolve_labels(cls)
if labels['app_model'] in settings.ORDER... | Checks if the provided class is specified as an orderable in
settings.ORDERABLE_MODELS. If it is return its settings. |
def ensure_matplotlib_figure(obj):
"""Extract the current figure from a matplotlib object or return the object if it's a figure.
raises ValueError if the object can't be converted.
"""
import matplotlib
from matplotlib.figure import Figure
if obj == matplotlib.pyplot:
obj = obj.gcf()
... | Extract the current figure from a matplotlib object or return the object if it's a figure.
raises ValueError if the object can't be converted. |
def set(
self,
key,
value,
loader_identifier=None,
tomlfy=False,
dotted_lookup=True,
is_secret=False,
):
"""Set a value storing references for the loader
:param key: The key to store
:param value: The value to store
:param load... | Set a value storing references for the loader
:param key: The key to store
:param value: The value to store
:param loader_identifier: Optional loader name e.g: toml, yaml etc.
:param tomlfy: Bool define if value is parsed by toml (defaults False)
:param is_secret: Bool define if... |
def _write_init_models(self, filenames):
""" Write init file
Args:
filenames (dict): dict of filename and classes
"""
self.write(destination=self.output_directory, filename="__init__.py", template_name="__init_model__.py.tpl",
filenames=self._pre... | Write init file
Args:
filenames (dict): dict of filename and classes |
def link(self, stream_instance):
"""Set my input stream"""
if isinstance(stream_instance, collections.Iterable):
self.input_stream = stream_instance
elif getattr(stream_instance, 'output_stream', None):
self.input_stream = stream_instance.output_stream
else:
... | Set my input stream |
def _is_gs_folder(cls, result):
"""Return ``True`` if GS standalone folder object.
GS will create a 0 byte ``<FOLDER NAME>_$folder$`` key as a
pseudo-directory place holder if there are no files present.
"""
return (cls.is_key(result) and
result.size == 0 and
... | Return ``True`` if GS standalone folder object.
GS will create a 0 byte ``<FOLDER NAME>_$folder$`` key as a
pseudo-directory place holder if there are no files present. |
def buttonbox(msg="", title=" ", choices=("Button[1]", "Button[2]", "Button[3]"), image=None, root=None, default_choice=None, cancel_choice=None):
"""
Display a msg, a title, an image, and a set of buttons.
The buttons are defined by the members of the choices list.
:param str msg: the msg to be displa... | Display a msg, a title, an image, and a set of buttons.
The buttons are defined by the members of the choices list.
:param str msg: the msg to be displayed
:param str title: the window title
:param list choices: a list or tuple of the choices to be displayed
:param str image: Filename of image to d... |
def draw_flat_samples(**kwargs):
''' Draw samples for uniform in mass
Parameters
----------
**kwargs: string
Keyword arguments as model parameters and number of samples
Returns
-------
array
The first mass
array
The second ma... | Draw samples for uniform in mass
Parameters
----------
**kwargs: string
Keyword arguments as model parameters and number of samples
Returns
-------
array
The first mass
array
The second mass |
def safe_urlencode(params, doseq=0):
"""
UTF-8-safe version of safe_urlencode
The stdlib safe_urlencode prior to Python 3.x chokes on UTF-8 values
which can't fail down to ascii.
"""
if IS_PY3:
return urlencode(params, doseq)
if hasattr(params, "items"):
params = params.ite... | UTF-8-safe version of safe_urlencode
The stdlib safe_urlencode prior to Python 3.x chokes on UTF-8 values
which can't fail down to ascii. |
def handle_json_GET_routepatterns(self, params):
"""Given a route_id generate a list of patterns of the route. For each
pattern include some basic information and a few sample trips."""
schedule = self.server.schedule
route = schedule.GetRoute(params.get('route', None))
if not route:
self.send... | Given a route_id generate a list of patterns of the route. For each
pattern include some basic information and a few sample trips. |
def start(self):
"""
Handle EventHub events for SmartContract decorators
"""
self._events_to_write = []
self._new_contracts_to_write = []
@events.on(SmartContractEvent.CONTRACT_CREATED)
@events.on(SmartContractEvent.CONTRACT_MIGRATED)
def call_on_success_... | Handle EventHub events for SmartContract decorators |
def update_table(self, tablename, throughput=None, global_indexes=None,
index_updates=None):
"""
Update the throughput of a table and/or global indexes
Parameters
----------
tablename : str
Name of the table to update
throughput : :class:... | Update the throughput of a table and/or global indexes
Parameters
----------
tablename : str
Name of the table to update
throughput : :class:`~dynamo3.fields.Throughput`, optional
The new throughput of the table
global_indexes : dict, optional
... |
def getChecked(self):
"""Gets the checked attributes
:returns: list<str> -- checked attribute names
"""
attrs = []
layout = self.layout()
for i in range(layout.count()):
w = layout.itemAt(i).widget()
if w.isChecked():
attrs.append(... | Gets the checked attributes
:returns: list<str> -- checked attribute names |
def get_passage(self, objectId, subreference):
""" Retrieve the passage identified by the parameters
:param objectId: Collection Identifier
:type objectId: str
:param subreference: Subreference of the passage
:type subreference: str
:return: An object bearing metadata an... | Retrieve the passage identified by the parameters
:param objectId: Collection Identifier
:type objectId: str
:param subreference: Subreference of the passage
:type subreference: str
:return: An object bearing metadata and its text
:rtype: InteractiveTextualNode |
def stage_name(self):
"""
Get stage name of current job instance.
Because instantiating job instance could be performed in different ways and those return different results,
we have to check where from to get name of the stage.
:return: stage name.
"""
if 'stage... | Get stage name of current job instance.
Because instantiating job instance could be performed in different ways and those return different results,
we have to check where from to get name of the stage.
:return: stage name. |
def _write_family(family, filename):
"""
Write a family to a csv file.
:type family: :class:`eqcorrscan.core.match_filter.Family`
:param family: Family to write to file
:type filename: str
:param filename: File to write to.
"""
with open(filename, 'w') as f:
for detection in fam... | Write a family to a csv file.
:type family: :class:`eqcorrscan.core.match_filter.Family`
:param family: Family to write to file
:type filename: str
:param filename: File to write to. |
def _get_MAP_spikes(F, c_hat, theta, dt, tol=1E-6, maxiter=100, verbosity=0):
"""
Used internally by deconvolve to compute the maximum a posteriori
spike train for a given set of fluorescence traces and model parameters.
See the documentation for deconvolve for the meaning of the
arguments
Ret... | Used internally by deconvolve to compute the maximum a posteriori
spike train for a given set of fluorescence traces and model parameters.
See the documentation for deconvolve for the meaning of the
arguments
Returns: n_hat_best, c_hat_best, LL_best |
def _socket_reconnect_and_wait_ready(self):
"""
sync_socket & async_socket recreate
:return: (ret, msg)
"""
logger.info("Start connecting: host={}; port={};".format(self.__host, self.__port))
with self._lock:
self._status = ContextStatus.Connecting
... | sync_socket & async_socket recreate
:return: (ret, msg) |
def pick(self, filenames: Iterable[str]) -> str:
"""Pick one filename based on priority rules."""
filenames = sorted(filenames, reverse=True) # e.g., v2 before v1
for priority in sorted(self.rules.keys(), reverse=True):
patterns = self.rules[priority]
for pattern in patt... | Pick one filename based on priority rules. |
def solveConsKinkedR(solution_next,IncomeDstn,LivPrb,DiscFac,CRRA,Rboro,Rsave,
PermGroFac,BoroCnstArt,aXtraGrid,vFuncBool,CubicBool):
'''
Solves a single period consumption-saving problem with CRRA utility and risky
income (subject to permanent and transitory shocks), and ... | Solves a single period consumption-saving problem with CRRA utility and risky
income (subject to permanent and transitory shocks), and different interest
factors on borrowing and saving. Restriction: Rboro >= Rsave. Currently
cannot construct a cubic spline consumption function, only linear. Can gen-
... |
def main(argv=None):
"""ben-elastic entry point"""
arguments = cli_common(__doc__, argv=argv)
es_export = ESExporter(arguments['CAMPAIGN-DIR'], arguments['--es'])
es_export.export()
if argv is not None:
return es_export | ben-elastic entry point |
def get_sources(src_dir='src', ending='.cpp'):
"""Function to get a list of files ending with `ending` in `src_dir`."""
return [os.path.join(src_dir, fnm) for fnm in os.listdir(src_dir) if fnm.endswith(ending)] | Function to get a list of files ending with `ending` in `src_dir`. |
def command_gen(self, *names):
'''
Runs generator functions.
Run `docs` generator function::
./manage.py sqla:gen docs
Run `docs` generator function with `count=10`::
./manage.py sqla:gen docs:10
'''
if not names:
sys.exit('Please p... | Runs generator functions.
Run `docs` generator function::
./manage.py sqla:gen docs
Run `docs` generator function with `count=10`::
./manage.py sqla:gen docs:10 |
def pdftojpg(filehandle, meta):
"""Converts a PDF to a JPG and places it back onto the FileStorage instance
passed to it as a BytesIO object.
Optional meta arguments are:
* resolution: int or (int, int) used for wand to determine resolution,
defaults to 300.
* width: new width of th... | Converts a PDF to a JPG and places it back onto the FileStorage instance
passed to it as a BytesIO object.
Optional meta arguments are:
* resolution: int or (int, int) used for wand to determine resolution,
defaults to 300.
* width: new width of the image for resizing, defaults to 1080
... |
def filter(self, query: Query, entity: type) -> Tuple[Query, Any]:
"""Apply the `_method` to all childs of the node.
:param query: The sqlachemy query.
:type query: Query
:param entity: The entity model of the query.
:type entity: type
:return: A tuple with in ... | Apply the `_method` to all childs of the node.
:param query: The sqlachemy query.
:type query: Query
:param entity: The entity model of the query.
:type entity: type
:return: A tuple with in first place the updated query and in second
place the list of filt... |
def clear(self):
"""
Clears grid to be EMPTY
"""
self.grid = [[EMPTY for dummy_col in range(self.grid_width)] for dummy_row in range(self.grid_height)] | Clears grid to be EMPTY |
def writeRunSetInfoToLog(self, runSet):
"""
This method writes the information about a run set into the txt_file.
"""
runSetInfo = "\n\n"
if runSet.name:
runSetInfo += runSet.name + "\n"
runSetInfo += "Run set {0} of {1} with options '{2}' and propertyfile '{... | This method writes the information about a run set into the txt_file. |
def dmp_path(regex, kwargs=None, name=None, app_name=None):
'''
Creates a DMP-style, convention-based pattern that resolves
to various view functions based on the 'dmp_page' value.
The following should exist as 1) regex named groups or
2) items in the kwargs dict:
dmp_app Should res... | Creates a DMP-style, convention-based pattern that resolves
to various view functions based on the 'dmp_page' value.
The following should exist as 1) regex named groups or
2) items in the kwargs dict:
dmp_app Should resolve to a name in INSTALLED_APPS.
If missing, de... |
def ex6_2(n):
"""
Generate a triangle pulse as described in Example 6-2
of Chapter 6.
You need to supply an index array n that covers at least [-2, 5].
The function returns the hard-coded signal of the example.
Parameters
----------
n : time index ndarray covering at least -2 ... | Generate a triangle pulse as described in Example 6-2
of Chapter 6.
You need to supply an index array n that covers at least [-2, 5].
The function returns the hard-coded signal of the example.
Parameters
----------
n : time index ndarray covering at least -2 to +5.
Returns
... |
def addResource(self, key, filePath, text):
"""
The add resource operation allows the administrator to add a file
resource, for example, the organization's logo or custom banner.
The resource can be used by any member of the organization. File
resources use storage space from you... | The add resource operation allows the administrator to add a file
resource, for example, the organization's logo or custom banner.
The resource can be used by any member of the organization. File
resources use storage space from your quota and are scanned for
viruses.
Inputs:
... |
def reading_order(e1, e2):
"""
A comparator to sort bboxes from top to bottom, left to right
"""
b1 = e1.bbox
b2 = e2.bbox
if round(b1[y0]) == round(b2[y0]) or round(b1[y1]) == round(b2[y1]):
return float_cmp(b1[x0], b2[x0])
return float_cmp(b1[y0], b2[y0]) | A comparator to sort bboxes from top to bottom, left to right |
def _adjustSyllabification(adjustedPhoneList, syllableList):
'''
Inserts spaces into a syllable if needed
Originally the phone list and syllable list contained the same number
of phones. But the adjustedPhoneList may have some insertions which are
not accounted for in the syllableList.
'''... | Inserts spaces into a syllable if needed
Originally the phone list and syllable list contained the same number
of phones. But the adjustedPhoneList may have some insertions which are
not accounted for in the syllableList. |
def publish(self, topic, obj, reference_message=None):
"""
Sends an object out over the pubsub connection, properly formatted,
and conforming to the protocol. Handles pickling for the wire, etc.
This method should *not* be subclassed.
"""
logging.debug("Publishing topic ... | Sends an object out over the pubsub connection, properly formatted,
and conforming to the protocol. Handles pickling for the wire, etc.
This method should *not* be subclassed. |
def _getch_unix(_getall=False):
"""
# --- current algorithm ---
# 1. switch to char-by-char input mode
# 2. turn off echo
# 3. wait for at least one char to appear
# 4. read the rest of the character buffer (_getall=True)
# 5. return list of characters (_getall on)
# or a single c... | # --- current algorithm ---
# 1. switch to char-by-char input mode
# 2. turn off echo
# 3. wait for at least one char to appear
# 4. read the rest of the character buffer (_getall=True)
# 5. return list of characters (_getall on)
# or a single char (_getall off) |
async def send_nym(self, did: str, verkey: str = None, alias: str = None, role: Role = None) -> None:
"""
Send input anchor's cryptonym (including DID, verification key, plus optional alias and role)
to the distributed ledger.
Raise BadLedgerTxn on failure, BadIdentifier for bad DID, or... | Send input anchor's cryptonym (including DID, verification key, plus optional alias and role)
to the distributed ledger.
Raise BadLedgerTxn on failure, BadIdentifier for bad DID, or BadRole for bad role.
:param did: anchor DID to send to ledger
:param verkey: optional anchor verificati... |
def parse_legacy_argstring(argstring):
'''
Preparses CLI input:
``arg1,arg2`` => ``['arg1', 'arg2']``
``[item1, item2],arg2`` => ``[['item1', 'item2'], arg2]``
'''
argstring = argstring.replace(',', ' , ')
argstring = argstring.replace('[', ' [ ')
argstring = argstring.replace(']', ' ]... | Preparses CLI input:
``arg1,arg2`` => ``['arg1', 'arg2']``
``[item1, item2],arg2`` => ``[['item1', 'item2'], arg2]`` |
def handle_read(self):
"""We got some output from a remote shell, this is one of the state
machine"""
if self.state == STATE_DEAD:
return
global nr_handle_read
nr_handle_read += 1
new_data = self._handle_read_chunk()
if self.debug:
self.pri... | We got some output from a remote shell, this is one of the state
machine |
def config_diff(args):
"""Compare method configuration definitions across workspaces. Ignores
methodConfigVersion if the verbose argument is not set"""
config_1 = config_get(args).splitlines()
args.project = args.Project
args.workspace = args.Workspace
cfg_1_name = args.config
if args.Con... | Compare method configuration definitions across workspaces. Ignores
methodConfigVersion if the verbose argument is not set |
def create_build(self, tarball_url, env=None, app_name=None):
"""Creates an app-setups build. Returns response data as a dict.
:param tarball_url: URL of a tarball containing an ``app.json``.
:param env: Dict containing environment variable overrides.
:param app_name: Name of the Heroku... | Creates an app-setups build. Returns response data as a dict.
:param tarball_url: URL of a tarball containing an ``app.json``.
:param env: Dict containing environment variable overrides.
:param app_name: Name of the Heroku app to create.
:returns: Response data as a ``dict``. |
def compact_interval_string(value_list):
"""Compact a list of integers into a comma-separated string of intervals.
Args:
value_list: A list of sortable integers such as a list of numbers
Returns:
A compact string representation, such as "1-5,8,12-15"
"""
if not value_list:
return ''
value_li... | Compact a list of integers into a comma-separated string of intervals.
Args:
value_list: A list of sortable integers such as a list of numbers
Returns:
A compact string representation, such as "1-5,8,12-15" |
def write(self, inline):
"""
Write a line to stdout if it isn't in a blacklist
Try to get the name of the calling module to see if we want
to filter it. If there is no calling module, use current
frame in case there's a traceback before there is any calling module
"""
... | Write a line to stdout if it isn't in a blacklist
Try to get the name of the calling module to see if we want
to filter it. If there is no calling module, use current
frame in case there's a traceback before there is any calling module |
def rollout(self, batch_info: BatchInfo, model: RlModel, number_of_steps: int) -> Rollout:
""" Calculate env rollout """
assert not model.is_recurrent, "Replay env roller does not support recurrent models"
accumulator = TensorAccumulator()
episode_information = [] # List of dictionarie... | Calculate env rollout |
def _sendline(self, line):
"""Send exactly one line to the device
Args:
line str: data send to device
"""
self.lines = []
try:
self._read()
except socket.error:
logging.debug('Nothing cleared')
logger.debug('sending [%s]', lin... | Send exactly one line to the device
Args:
line str: data send to device |
def decorate(decorator_cls, *args, **kwargs):
"""Creates a decorator function that applies the decorator_cls that was passed in."""
global _wrappers
wrapper_cls = _wrappers.get(decorator_cls, None)
if wrapper_cls is None:
class PythonWrapper(decorator_cls):
pass
wrapper_cl... | Creates a decorator function that applies the decorator_cls that was passed in. |
def import_orm(self):
#TODO: check docstring
""" Import ORM classes for oedb access depending on input in config in
self.config which is loaded from 'config_db_tables.cfg'
Returns
-------
int
Descr #TODO check type
"""
orm = {}
... | Import ORM classes for oedb access depending on input in config in
self.config which is loaded from 'config_db_tables.cfg'
Returns
-------
int
Descr #TODO check type |
def dumps(self):
r"""Turn the Latex Object into a string in Latex format."""
string = ""
if self.row_height is not None:
row_height = Command('renewcommand', arguments=[
NoEscape(r'\arraystretch'),
self.row_height])
string += row_height.d... | r"""Turn the Latex Object into a string in Latex format. |
def visit_List(self, node: ast.List) -> List[Any]:
"""Visit the elements and assemble the results into a list."""
if isinstance(node.ctx, ast.Store):
raise NotImplementedError("Can not compute the value of a Store on a list")
result = [self.visit(node=elt) for elt in node.elts]
... | Visit the elements and assemble the results into a list. |
def reindex_like(self, other, method=None, tolerance=None, copy=True):
"""Conform this object onto the indexes of another object, filling
in missing values with NaN.
Parameters
----------
other : Dataset or DataArray
Object with an 'indexes' attribute giving a mappin... | Conform this object onto the indexes of another object, filling
in missing values with NaN.
Parameters
----------
other : Dataset or DataArray
Object with an 'indexes' attribute giving a mapping from dimension
names to pandas.Index objects, which provides coordin... |
def get(self, url=None, delimiter="/"):
"""Path is an s3 url. Ommiting the path or providing "s3://" as the
path will return a list of all buckets. Otherwise, all subdirectories
and their contents will be shown.
"""
params = {'Delimiter': delimiter}
bucket, obj_key = _par... | Path is an s3 url. Ommiting the path or providing "s3://" as the
path will return a list of all buckets. Otherwise, all subdirectories
and their contents will be shown. |
def get_id_constraints(pkname, pkey):
"""Returns primary key consraints.
:pkname: if a string, returns a dict with pkname=pkey. pkname and pkey must be enumerables of
matching length.
"""
if isinstance(pkname, str):
return {pkname: pkey}
else:
return dict(zip(pkname, pkey)) | Returns primary key consraints.
:pkname: if a string, returns a dict with pkname=pkey. pkname and pkey must be enumerables of
matching length. |
def _get_lane_properties(self, node):
"""
Parses the given XML node
Args:
node (xml): XML node.
.. code-block:: xml
<bpmn2:lane id="Lane_8" name="Lane 8">
<bpmn2:extensionElements>
<camunda:properties>
... | Parses the given XML node
Args:
node (xml): XML node.
.. code-block:: xml
<bpmn2:lane id="Lane_8" name="Lane 8">
<bpmn2:extensionElements>
<camunda:properties>
<camunda:property value="foo,bar" name="perms"/>
... |
def get_volume_object_info(self, location):
"""
Fetches information about single volume object - usually file
:param location: object location
:return:
"""
param = {'location': location}
data = self._api.get(url=self._URL['object'].format(
id=self.id),... | Fetches information about single volume object - usually file
:param location: object location
:return: |
def start(self, exceptions):
"""Start the Heartbeat Checker.
:param list exceptions:
:return:
"""
if not self._interval:
return False
self._running.set()
with self._lock:
self._threshold = 0
self._reads_since_check = 0
... | Start the Heartbeat Checker.
:param list exceptions:
:return: |
def GetFormattedMessages(self, event):
"""Retrieves the formatted messages related to the event.
Args:
event (EventObject): event.
Returns:
tuple: containing:
str: full message string or None if no event formatter was found.
str: short message string or None if no event format... | Retrieves the formatted messages related to the event.
Args:
event (EventObject): event.
Returns:
tuple: containing:
str: full message string or None if no event formatter was found.
str: short message string or None if no event formatter was found. |
def generic_visit(self, node):
"""Surround node statement with a try/except block to catch errors.
This method is called for every node of the parsed code, and only
changes statement lines.
Args:
node (ast.AST): node statement to surround.
"""
if (isinstance... | Surround node statement with a try/except block to catch errors.
This method is called for every node of the parsed code, and only
changes statement lines.
Args:
node (ast.AST): node statement to surround. |
def calculate(self, **state):
"""
Calculate dynamic viscosity at the specified temperature and
composition:
:param T: [K] temperature
:param y: [mass fraction] composition dictionary , e.g. \
{'SiO2': 0.25, 'CaO': 0.25, 'MgO': 0.25, 'FeO': 0.25}
:returns: [Pa.s]... | Calculate dynamic viscosity at the specified temperature and
composition:
:param T: [K] temperature
:param y: [mass fraction] composition dictionary , e.g. \
{'SiO2': 0.25, 'CaO': 0.25, 'MgO': 0.25, 'FeO': 0.25}
:returns: [Pa.s] dynamic viscosity
The **state parameter ... |
def search_directory(self, **kwargs):
"""
SearchAccount is deprecated, using SearchDirectory
:param query: Query string - should be an LDAP-style filter
string (RFC 2254)
:param limit: The maximum number of accounts to return
(0 is default and means all)
:param o... | SearchAccount is deprecated, using SearchDirectory
:param query: Query string - should be an LDAP-style filter
string (RFC 2254)
:param limit: The maximum number of accounts to return
(0 is default and means all)
:param offset: The starting offset (0, 25, etc)
:param dom... |
def update(self, obj, **kwargs):
"Update the tree item when the object name changes"
# search for the old name:
child = self.tree.FindItem(self.root, kwargs['name'])
if DEBUG: print "update child", child, kwargs
if child:
self.tree.ScrollTo(child)
self.tre... | Update the tree item when the object name changes |
def mtie_phase_fast(phase, rate=1.0, data_type="phase", taus=None):
""" fast binary decomposition algorithm for MTIE
See: STEFANO BREGNI "Fast Algorithms for TVAR and MTIE Computation in
Characterization of Network Synchronization Performance"
"""
rate = float(rate)
phase = np.asarray(p... | fast binary decomposition algorithm for MTIE
See: STEFANO BREGNI "Fast Algorithms for TVAR and MTIE Computation in
Characterization of Network Synchronization Performance" |
def trust_key(keyid=None,
fingerprint=None,
trust_level=None,
user=None):
'''
Set the trust level for a key in GPG keychain
keyid
The keyid of the key to set the trust level for.
fingerprint
The fingerprint of the key to set the trust level for... | Set the trust level for a key in GPG keychain
keyid
The keyid of the key to set the trust level for.
fingerprint
The fingerprint of the key to set the trust level for.
trust_level
The trust level to set for the specified key, must be one
of the following:
expired, ... |
def _block(self, rdd, bsize, dtype):
"""Execute the blocking process on the given rdd.
Parameters
----------
rdd : pyspark.rdd.RDD
Distributed data to block
bsize : int or None
The desired size of the blocks
Returns
-------
rdd : ... | Execute the blocking process on the given rdd.
Parameters
----------
rdd : pyspark.rdd.RDD
Distributed data to block
bsize : int or None
The desired size of the blocks
Returns
-------
rdd : pyspark.rdd.RDD
Blocked rdd. |
def _pop_import_LOAD_ATTRs(module_name, queue):
"""
Pop LOAD_ATTR instructions for an import of the form::
import a.b.c as d
which should generate bytecode like this::
1 0 LOAD_CONST 0 (0)
3 LOAD_CONST 1 (None)
... | Pop LOAD_ATTR instructions for an import of the form::
import a.b.c as d
which should generate bytecode like this::
1 0 LOAD_CONST 0 (0)
3 LOAD_CONST 1 (None)
6 IMPORT_NAME 0 (a.b.c.d)
9... |
def on_all_ok(self):
"""
This method is called when all tasks reach S_OK
Ir runs `mrgddb` in sequential on the local machine to produce
the final DDB file in the outdir of the `Work`.
"""
# Merge DDB files.
out_ddb = self.merge_ddb_files()
return self.Resu... | This method is called when all tasks reach S_OK
Ir runs `mrgddb` in sequential on the local machine to produce
the final DDB file in the outdir of the `Work`. |
def linear_reaction_coefficients(model, reactions=None):
"""Coefficient for the reactions in a linear objective.
Parameters
----------
model : cobra model
the model object that defined the objective
reactions : list
an optional list for the reactions to get the coefficients for. All... | Coefficient for the reactions in a linear objective.
Parameters
----------
model : cobra model
the model object that defined the objective
reactions : list
an optional list for the reactions to get the coefficients for. All
reactions if left missing.
Returns
-------
... |
def describe_alarms(self, action_prefix=None, alarm_name_prefix=None,
alarm_names=None, max_records=None, state_value=None,
next_token=None):
"""
Retrieves alarms with the specified names. If no name is specified, all
alarms for the user are return... | Retrieves alarms with the specified names. If no name is specified, all
alarms for the user are returned. Alarms can be retrieved by using only
a prefix for the alarm name, the alarm state, or a prefix for any
action.
:type action_prefix: string
:param action_name: The action na... |
def _check_hla_alleles(
alleles,
valid_alleles=None):
"""
Given a list of HLA alleles and an optional list of valid
HLA alleles, return a set of alleles that we will pass into
the MHC binding predictor.
"""
require_iterable_of(alleles, string_types... | Given a list of HLA alleles and an optional list of valid
HLA alleles, return a set of alleles that we will pass into
the MHC binding predictor. |
def which(program, add_win_suffixes=True):
"""Mimic 'which' command behavior.
Adapted from https://stackoverflow.com/a/377028
"""
def is_exe(fpath):
"""Determine if program exists and is executable."""
return os.path.isfile(fpath) and os.access(fpath, os.X_OK)
fpath, fname = os.pat... | Mimic 'which' command behavior.
Adapted from https://stackoverflow.com/a/377028 |
def prettify_json_file(file_list):
""" prettify JSON testcase format
"""
for json_file in set(file_list):
if not json_file.endswith(".json"):
logger.log_warning("Only JSON file format can be prettified, skip: {}".format(json_file))
continue
logger.color_print("Start ... | prettify JSON testcase format |
def latexify(obj, **kwargs):
"""Render an object in LaTeX appropriately.
"""
if hasattr(obj, '__pk_latex__'):
return obj.__pk_latex__(**kwargs)
if isinstance(obj, text_type):
from .unicode_to_latex import unicode_to_latex
return unicode_to_latex(obj)
if isinstance(obj, boo... | Render an object in LaTeX appropriately. |
def _asarray(self, vec):
"""Convert ``x`` to an array.
Here the indices are changed such that the "outer" indices come last
in order to have the access order as `numpy.linalg.svd` needs it.
This is the inverse of `_asvector`.
"""
shape = self.domain[0, 0].shape + self.p... | Convert ``x`` to an array.
Here the indices are changed such that the "outer" indices come last
in order to have the access order as `numpy.linalg.svd` needs it.
This is the inverse of `_asvector`. |
def file_download(context, id, file_id, target):
"""file_download(context, id, path)
Download a job file
>>> dcictl job-download-file [OPTIONS]
:param string id: ID of the job to download file [required]
:param string file_id: ID of the job file to download [required]
:param string target: De... | file_download(context, id, path)
Download a job file
>>> dcictl job-download-file [OPTIONS]
:param string id: ID of the job to download file [required]
:param string file_id: ID of the job file to download [required]
:param string target: Destination file [required] |
def add(addon, dev, interactive):
"""Add a dependency.
Examples:
$ django add dynamic-rest==1.5.0
+ dynamic-rest == 1.5.0
"""
application = get_current_application()
application.add(
addon,
dev=dev,
interactive=interactive
) | Add a dependency.
Examples:
$ django add dynamic-rest==1.5.0
+ dynamic-rest == 1.5.0 |
def get_locale():
'''
Get the current system locale
CLI Example:
.. code-block:: bash
salt '*' locale.get_locale
'''
ret = ''
lc_ctl = salt.utils.systemd.booted(__context__)
# localectl on SLE12 is installed but the integration is still broken in latest SP3 due to
# config... | Get the current system locale
CLI Example:
.. code-block:: bash
salt '*' locale.get_locale |
def libvlc_media_list_player_new(p_instance):
'''Create new media_list_player.
@param p_instance: libvlc instance.
@return: media list player instance or NULL on error.
'''
f = _Cfunctions.get('libvlc_media_list_player_new', None) or \
_Cfunction('libvlc_media_list_player_new', ((1,),), clas... | Create new media_list_player.
@param p_instance: libvlc instance.
@return: media list player instance or NULL on error. |
def cv(params, dtrain, num_boost_round=10, nfold=3, stratified=False, folds=None,
metrics=(), obj=None, feval=None, maximize=False, early_stopping_rounds=None,
fpreproc=None, as_pandas=True, verbose_eval=None, show_stdv=True,
seed=0, callbacks=None, shuffle=True):
# pylint: disable = invalid-na... | Cross-validation with given parameters.
Parameters
----------
params : dict
Booster params.
dtrain : DMatrix
Data to be trained.
num_boost_round : int
Number of boosting iterations.
nfold : int
Number of folds in CV.
stratified : bool
Perform stratifi... |
def resample_melody_series(times, frequencies, voicing,
times_new, kind='linear'):
"""Resamples frequency and voicing time series to a new timescale. Maintains
any zero ("unvoiced") values in frequencies.
If ``times`` and ``times_new`` are equivalent, no resampling will be
pe... | Resamples frequency and voicing time series to a new timescale. Maintains
any zero ("unvoiced") values in frequencies.
If ``times`` and ``times_new`` are equivalent, no resampling will be
performed.
Parameters
----------
times : np.ndarray
Times of each frequency value
frequencies ... |
def set_eol_chars(self, text):
"""Set widget end-of-line (EOL) characters from text (analyzes text)"""
if not is_text_string(text): # testing for QString (PyQt API#1)
text = to_text_string(text)
eol_chars = sourcecode.get_eol_chars(text)
is_document_modified = eol_chars ... | Set widget end-of-line (EOL) characters from text (analyzes text) |
def flip(self):
""" Provide flip view to compare how key/value pair is defined in each
environment for administrative usage.
:rtype: dict
"""
self._load()
groups = self.config.keys()
tabular = {}
for g in groups:
config = self.config[g]
... | Provide flip view to compare how key/value pair is defined in each
environment for administrative usage.
:rtype: dict |
def contains_rva(self, rva):
"""Check whether the section contains the address provided."""
# Check if the SizeOfRawData is realistic. If it's bigger than the size of
# the whole PE file minus the start address of the section it could be
# either truncated or the SizeOfRawData contains ... | Check whether the section contains the address provided. |
def find_best_root(self, force_positive=True, slope=None):
"""
determine the position on the tree that minimizes the bilinear
product of the inverse covariance and the data vectors.
Returns
-------
best_root : (dict)
dictionary with the node, the fraction `x... | determine the position on the tree that minimizes the bilinear
product of the inverse covariance and the data vectors.
Returns
-------
best_root : (dict)
dictionary with the node, the fraction `x` at which the branch
is to be split, and the regression parameters |
def pipe_dateformat(context=None, _INPUT=None, conf=None, **kwargs):
"""Formats a datetime value. Loopable.
Parameters
----------
context : pipe2py.Context object
_INPUT : pipedatebuilder pipe like object (iterable of date timetuples)
conf : {
'format': {'value': <'%B %d, %Y'>},
... | Formats a datetime value. Loopable.
Parameters
----------
context : pipe2py.Context object
_INPUT : pipedatebuilder pipe like object (iterable of date timetuples)
conf : {
'format': {'value': <'%B %d, %Y'>},
'timezone': {'value': <'EST'>}
}
Yields
------
_OUTPUT : f... |
def add(self, device):
"""Add device."""
if not isinstance(device, Device):
raise TypeError()
self.__devices.append(device) | Add device. |
def connect(self, From, to,
protocolName, clientFactory,
chooser):
"""
Issue an INBOUND command, creating a virtual connection to the peer,
given identifying information about the endpoint to connect to, and a
protocol factory.
@param clientFactor... | Issue an INBOUND command, creating a virtual connection to the peer,
given identifying information about the endpoint to connect to, and a
protocol factory.
@param clientFactory: a *Client* ProtocolFactory instance which will
generate a protocol upon connect.
@return: a Deferre... |
def pickle_dump(self):
"""Save the status of the object in pickle format."""
with open(os.path.join(self.workdir, self.PICKLE_FNAME), mode="wb") as fh:
pickle.dump(self, fh) | Save the status of the object in pickle format. |
def mcp_als(X, rank, mask, random_state=None, init='randn', **options):
"""Fits CP Decomposition with missing data using Alternating Least Squares (ALS).
Parameters
----------
X : (I_1, ..., I_N) array_like
A tensor with ``X.ndim >= 3``.
rank : integer
The `rank` sets the number of... | Fits CP Decomposition with missing data using Alternating Least Squares (ALS).
Parameters
----------
X : (I_1, ..., I_N) array_like
A tensor with ``X.ndim >= 3``.
rank : integer
The `rank` sets the number of components to be computed.
mask : (I_1, ..., I_N) array_like
A bi... |
def display_task_progress(
self, instance, project, region, request_id=None, user=None,
poll_interval=60):
"""Displays the overall progress of tasks in a Turbinia job.
Args:
instance (string): The name of the Turbinia instance
project (string): The project containing the disk to process... | Displays the overall progress of tasks in a Turbinia job.
Args:
instance (string): The name of the Turbinia instance
project (string): The project containing the disk to process
region (string): Region where turbinia is configured.
request_id (string): The request ID provided by Turbinia.
... |
def is_valid_filename(filename, return_ext=False):
"""Check whether the argument is a filename."""
ext = Path(filename).suffixes
if len(ext) > 2:
logg.warn('Your filename has more than two extensions: {}.\n'
'Only considering the two last: {}.'.format(ext, ext[-2:]))
ext =... | Check whether the argument is a filename. |
def fuzzy_get_value(obj, approximate_key, default=None, **kwargs):
""" Like fuzzy_get, but assume the obj is dict-like and return the value without the key
Notes:
Argument order is in reverse order relative to `fuzzywuzzy.process.extractOne()`
but in the same order as get(self, key) method on dic... | Like fuzzy_get, but assume the obj is dict-like and return the value without the key
Notes:
Argument order is in reverse order relative to `fuzzywuzzy.process.extractOne()`
but in the same order as get(self, key) method on dicts
Arguments:
obj (dict-like): object to run the get method on u... |
def render(self, template, context=None, at_paths=None,
at_encoding=anytemplate.compat.ENCODING, **kwargs):
"""
:param template: Template file path
:param context: A dict or dict-like object to instantiate given
template file
:param at_paths: Template search pa... | :param template: Template file path
:param context: A dict or dict-like object to instantiate given
template file
:param at_paths: Template search paths
:param at_encoding: Template encoding
:param kwargs: Keyword arguments passed to the template engine to
render ... |
def covar(X, remove_mean=False, modify_data=False, weights=None, sparse_mode='auto', sparse_tol=0.0):
""" Computes the covariance matrix of X
Computes
.. math:
C_XX &=& X^\top X
while exploiting zero or constant columns in the data matrix.
WARNING: Directly use moments_XX if you can. This... | Computes the covariance matrix of X
Computes
.. math:
C_XX &=& X^\top X
while exploiting zero or constant columns in the data matrix.
WARNING: Directly use moments_XX if you can. This function does an additional
constant-matrix multiplication and does not return the mean.
Parameters
... |
def asset_path(path, format_kwargs={}, keep_slash=False):
"""Get absolute path to asset in package.
``path`` can be just a package name like 'package' or it can be
a package name and a relative file system path like 'package:util'.
If ``path`` ends with a slash, it will be stripped unless
``keep_s... | Get absolute path to asset in package.
``path`` can be just a package name like 'package' or it can be
a package name and a relative file system path like 'package:util'.
If ``path`` ends with a slash, it will be stripped unless
``keep_slash`` is set (for use with ``rsync``, for example).
>>> fil... |
def price_options(S=100.0, K=100.0, sigma=0.25, r=0.05, days=260, paths=10000):
"""
Price European and Asian options using a Monte Carlo method.
Parameters
----------
S : float
The initial price of the stock.
K : float
The strike price of the option.
sigma : float
Th... | Price European and Asian options using a Monte Carlo method.
Parameters
----------
S : float
The initial price of the stock.
K : float
The strike price of the option.
sigma : float
The volatility of the stock.
r : float
The risk free interest rate.
days : int... |
def _add_constraints(self, relation):
"""Add the given relation as one or more constraints.
Return a list of the names of the constraints added.
"""
expression = relation.expression
constr_count = sum(True for _ in expression.value_sets())
if constr_count == 0:
... | Add the given relation as one or more constraints.
Return a list of the names of the constraints added. |
def format_path(path):
'''Formats a path as a string, placing / between each component.
@param path A path in rtctree format, as a tuple with the port name as the
second component.
Examples:
>>> format_path((['localhost:30000', 'manager', 'comp0.rtc'], None))
'localhost:3... | Formats a path as a string, placing / between each component.
@param path A path in rtctree format, as a tuple with the port name as the
second component.
Examples:
>>> format_path((['localhost:30000', 'manager', 'comp0.rtc'], None))
'localhost:30000/manager/comp0.rtc'
... |
def add_pegasus_profile(self, namespace, key, value):
"""
Add a Pegasus profile to this job which will be written to the dax as
<profile namespace="NAMESPACE" key="KEY">VALUE</profile>
This can be used to add classads to particular jobs in the DAX
@param namespace: A valid Pegasus namespace, e.g. co... | Add a Pegasus profile to this job which will be written to the dax as
<profile namespace="NAMESPACE" key="KEY">VALUE</profile>
This can be used to add classads to particular jobs in the DAX
@param namespace: A valid Pegasus namespace, e.g. condor.
@param key: The name of the attribute.
@param value:... |
def repackage_to_staging(output_path):
"""Repackage it from local installed location and copy it to GCS."""
import google.datalab.ml as ml
# Find the package root. __file__ is under [package_root]/mltoolbox/image/classification.
package_root = os.path.join(os.path.dirname(__file__), '../../../')
# We deploy... | Repackage it from local installed location and copy it to GCS. |
def create_qualification_type(Name=None, Keywords=None, Description=None, QualificationTypeStatus=None, RetryDelayInSeconds=None, Test=None, AnswerKey=None, TestDurationInSeconds=None, AutoGranted=None, AutoGrantedValue=None):
"""
The CreateQualificationType operation creates a new Qualification type, which is ... | The CreateQualificationType operation creates a new Qualification type, which is represented by a QualificationType data structure.
See also: AWS API Documentation
:example: response = client.create_qualification_type(
Name='string',
Keywords='string',
Description='string',
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.