code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def lstm_posterior_builder(getter, name, *args, **kwargs):
"""A builder for a particular diagonal gaussian posterior.
Args:
getter: The `getter` passed to a `custom_getter`. Please see the
documentation for `tf.get_variable`.
name: The `name` argument passed to `tf.get_variable`.
*args: Positiona... | A builder for a particular diagonal gaussian posterior.
Args:
getter: The `getter` passed to a `custom_getter`. Please see the
documentation for `tf.get_variable`.
name: The `name` argument passed to `tf.get_variable`.
*args: Positional arguments forwarded by `tf.get_variable`.
**kwargs: Keywor... |
def _proxy(self):
"""
Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: FunctionVersionContext for this FunctionVersionInstance
:rtype: twilio.rest.serverless.v1.service... | Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: FunctionVersionContext for this FunctionVersionInstance
:rtype: twilio.rest.serverless.v1.service.function.function_version.FunctionVer... |
def _load_background_color(self):
""" Loads the data related to the fill color """
url = self.build_url(self._endpoints.get('fill'))
response = self.session.get(url)
if not response:
return None
data = response.json()
self._background_color = data.get('color',... | Loads the data related to the fill color |
def create_relocate_package(cls, package_name, shade_prefix=None, recursive=True):
"""Convenience constructor for a package relocation rule.
Essentially equivalent to just using ``shading_relocate('package_name.**')``.
:param string package_name: Package name to shade (eg, ``org.pantsbuild.example``).
... | Convenience constructor for a package relocation rule.
Essentially equivalent to just using ``shading_relocate('package_name.**')``.
:param string package_name: Package name to shade (eg, ``org.pantsbuild.example``).
:param string shade_prefix: Optional prefix to apply to the package. Defaults to
``... |
def get_words_iterable( letters, tamil_only=False ):
""" given a list of UTF-8 letters section them into words, grouping them at spaces """
# correct algorithm for get-tamil-words
buf = []
for idx,let in enumerate(letters):
if not let.isspace():
if istamil(let) or (not tamil_only):
... | given a list of UTF-8 letters section them into words, grouping them at spaces |
def add_slices(self, dashboard_id):
"""Add and save slices to a dashboard"""
data = json.loads(request.form.get('data'))
session = db.session()
Slice = models.Slice # noqa
dash = (
session.query(models.Dashboard).filter_by(id=dashboard_id).first())
check_owne... | Add and save slices to a dashboard |
def rooms(self):
"""
:rtype: twilio.rest.video.v1.room.RoomList
"""
if self._rooms is None:
self._rooms = RoomList(self)
return self._rooms | :rtype: twilio.rest.video.v1.room.RoomList |
def runs_to_xml(self, runSet, runs, blockname=None):
"""
This function creates the XML structure for a list of runs
"""
# copy benchmarkinfo, limits, columntitles, systeminfo from xml_header
runsElem = util.copy_of_xml_element(self.xml_header)
runsElem.set("options", " ".... | This function creates the XML structure for a list of runs |
def p_If(p):
'''
If : IfBlock
| IfBlock ELSE COLON Terminator Block
'''
if len(p) == 2:
p[0] = If(p[1], None, None)
else:
p[0] = If(p[1], p[5], p[4]) | If : IfBlock
| IfBlock ELSE COLON Terminator Block |
def generate(env):
"""Add Builders and construction variables for Ghostscript to an
Environment."""
global GhostscriptAction
# The following try-except block enables us to use the Tool
# in standalone mode (without the accompanying pdf.py),
# whenever we need an explicit call of gs via the Gs()
... | Add Builders and construction variables for Ghostscript to an
Environment. |
def image_undo():
"""
Undoes the last coarsen or smooth command.
"""
if len(image_undo_list) <= 0:
print("no undos in memory")
return
[image, Z] = image_undo_list.pop(-1)
image.set_array(Z)
_pylab.draw() | Undoes the last coarsen or smooth command. |
def isbn(self, fmt: Optional[ISBNFormat] = None,
locale: str = 'en') -> str:
"""Generate ISBN for current locale.
To change ISBN format, pass parameter ``fmt`` with needed value of
the enum object :class:`~mimesis.enums.ISBNFormat`
:param fmt: ISBN format.
:param l... | Generate ISBN for current locale.
To change ISBN format, pass parameter ``fmt`` with needed value of
the enum object :class:`~mimesis.enums.ISBNFormat`
:param fmt: ISBN format.
:param locale: Locale code.
:return: ISBN.
:raises NonEnumerableError: if fmt is not enum ISB... |
def get(self, section, option, as_list=False):
'''
Adds an optional "as_list" argument to ensure a list is returned. This
is helpful when iterating over an option which may or may not be a
multivar.
'''
ret = super(GitConfigParser, self).get(section, option)
if as... | Adds an optional "as_list" argument to ensure a list is returned. This
is helpful when iterating over an option which may or may not be a
multivar. |
def photo_url(self):
"""获取话题头像图片地址.
:return: 话题头像url
:rtype: str
"""
img = self.soup.find('a', id='zh-avartar-edit-form').img['src']
return img.replace('_m', '_r') | 获取话题头像图片地址.
:return: 话题头像url
:rtype: str |
def do_size(self, w, h):
"""Record size."""
if (w is None):
self.sw = self.rw
self.sh = self.rh
else:
self.sw = w
self.sh = h
# Now we have region and size, generate the image
image = Image.new("RGB", (self.sw, self.sh), self.gen.ba... | Record size. |
def collect(config, pconn):
"""
All the heavy lifting done here
"""
# initialize collection target
# tar files
if config.analyze_file:
logger.debug("Client analyzing a compress filesystem.")
target = {'type': 'compressed_file',
'name': os.path.splitext(
... | All the heavy lifting done here |
def find_throat_facets(self, throats=None):
r"""
Finds the indicies of the Voronoi nodes that define the facet or
ridge between the Delaunay nodes connected by the given throat.
Parameters
----------
throats : array_like
The throats whose facets are sought. ... | r"""
Finds the indicies of the Voronoi nodes that define the facet or
ridge between the Delaunay nodes connected by the given throat.
Parameters
----------
throats : array_like
The throats whose facets are sought. The given throats should be
from the 'de... |
def check_is_working(self):
""" Returns True if the wash alert web interface seems to be
working properly, or False otherwise.
>>> l.check_is_working()
"""
try:
r = requests.post("http://{}/".format(LAUNDRY_DOMAIN), timeout=60, data={
"locationid": "5... | Returns True if the wash alert web interface seems to be
working properly, or False otherwise.
>>> l.check_is_working() |
def read_in_chunks(file_obj, chunk_size):
"""Generator to read a file piece by piece."""
offset = 0
while True:
data = file_obj.read(chunk_size)
if not data:
break
yield data, offset
offset += len(data) | Generator to read a file piece by piece. |
def image_id(self):
""" this container is created from image with id..."""
try:
# docker >= 1.9
image_id = self.data["ImageID"]
except KeyError:
# docker <= 1.8
image_id = self.metadata_get(["Image"])
return image_id | this container is created from image with id... |
def info(self):
"""Formatted string to display the available choices"""
if self.descriptions is None:
choice_list = ['"{}"'.format(choice) for choice in self.choices]
else:
choice_list = [
'"{}" ({})'.format(choice, self.descriptions[choice])
... | Formatted string to display the available choices |
def get_all(self):
"""Return the complete context as dict including the exported
variables. For optimizations reasons this might not return an
actual copy so be careful with using it.
"""
if not self.vars:
return self.parent
if not self.parent:
re... | Return the complete context as dict including the exported
variables. For optimizations reasons this might not return an
actual copy so be careful with using it. |
def _find_newest_ckpt(ckpt_dir):
"""Returns path to most recently modified checkpoint."""
full_paths = [
os.path.join(ckpt_dir, fname) for fname in os.listdir(ckpt_dir)
if fname.startswith("experiment_state") and fname.endswith(".json")
]
return max(full_paths) | Returns path to most recently modified checkpoint. |
def headers(self):
"""Response headers.
Response headers is a dict with all keys in lower case.
>>> import urlfetch
>>> response = urlfetch.get("http://docs.python.org/")
>>> response.headers
{
'content-length': '8719',
'x-cache': 'MISS from loca... | Response headers.
Response headers is a dict with all keys in lower case.
>>> import urlfetch
>>> response = urlfetch.get("http://docs.python.org/")
>>> response.headers
{
'content-length': '8719',
'x-cache': 'MISS from localhost',
'accept-ra... |
def get_boto_ses_connection():
"""
Shortcut for instantiating and returning a boto SESConnection object.
:rtype: boto.ses.SESConnection
:returns: A boto SESConnection object, from which email sending is done.
"""
access_key_id = getattr(
settings, 'CUCUMBER_SES_ACCESS_KEY_ID',
... | Shortcut for instantiating and returning a boto SESConnection object.
:rtype: boto.ses.SESConnection
:returns: A boto SESConnection object, from which email sending is done. |
async def stream(self,
event_type: Type[TStreamEvent],
num_events: Optional[int] = None) -> AsyncGenerator[TStreamEvent, None]:
"""
Stream all events that match the specified event type. This returns an
``AsyncIterable[BaseEvent]`` which can be consumed ... | Stream all events that match the specified event type. This returns an
``AsyncIterable[BaseEvent]`` which can be consumed through an ``async for`` loop.
An optional ``num_events`` parameter can be passed to stop streaming after a maximum amount
of events was received. |
def from_database(cls, database):
"""Initialize migrator by db."""
if isinstance(database, PostgresqlDatabase):
return PostgresqlMigrator(database)
if isinstance(database, SqliteDatabase):
return SqliteMigrator(database)
if isinstance(database, MySQLDatabase):
... | Initialize migrator by db. |
def c_Duffy(z, m, h=h):
"""Concentration from c(M) relation published in Duffy et al. (2008).
Parameters
----------
z : float or array_like
Redshift(s) of halos.
m : float or array_like
Mass(es) of halos (m200 definition), in units of solar masses.
h : float, optional
Hu... | Concentration from c(M) relation published in Duffy et al. (2008).
Parameters
----------
z : float or array_like
Redshift(s) of halos.
m : float or array_like
Mass(es) of halos (m200 definition), in units of solar masses.
h : float, optional
Hubble parameter. Default is from... |
def _runOPF(self):
""" Computes dispatch points and LMPs using OPF.
"""
if self.decommit:
solver = UDOPF(self.case, dc=(self.locationalAdjustment == "dc"))
elif self.locationalAdjustment == "dc":
solver = OPF(self.case, dc=True)
else:
solver = ... | Computes dispatch points and LMPs using OPF. |
def get_init(self):
"""Return initial name.
"""
suffix = self._separator + "%s" % str(self._counter_init)
return self._base_name + suffix | Return initial name. |
def _get_dvs_portgroup(dvs, portgroup_name):
'''
Return a portgroup object corresponding to the portgroup name on the dvs
:param dvs: DVS object
:param portgroup_name: Name of portgroup to return
:return: Portgroup object
'''
for portgroup in dvs.portgroup:
if portgroup.name == port... | Return a portgroup object corresponding to the portgroup name on the dvs
:param dvs: DVS object
:param portgroup_name: Name of portgroup to return
:return: Portgroup object |
def get_device_model():
"""
Returns the Device model that is active in this project.
"""
try:
return apps.get_model(settings.GCM_DEVICE_MODEL)
except ValueError:
raise ImproperlyConfigured("GCM_DEVICE_MODEL must be of the form 'app_label.model_name'")
except LookupError:
... | Returns the Device model that is active in this project. |
def from_shapely(geometry, label=None):
"""
Create a MultiPolygon from a Shapely MultiPolygon, a Shapely Polygon or a Shapely GeometryCollection.
This also creates all necessary Polygons contained by this MultiPolygon.
Parameters
----------
geometry : shapely.geometry.M... | Create a MultiPolygon from a Shapely MultiPolygon, a Shapely Polygon or a Shapely GeometryCollection.
This also creates all necessary Polygons contained by this MultiPolygon.
Parameters
----------
geometry : shapely.geometry.MultiPolygon or shapely.geometry.Polygon\
... |
def from_masked_images(cls: Type[T], masked_images: Iterable[np.ndarray],
n_subjects: int) -> T:
"""Create a new instance of MaskedMultiSubjecData from masked images.
Parameters
----------
masked_images : iterator
Images from multiple subjects to s... | Create a new instance of MaskedMultiSubjecData from masked images.
Parameters
----------
masked_images : iterator
Images from multiple subjects to stack along 3rd dimension
n_subjects : int
Number of subjects; must match the number of images
Returns
... |
def store(self, name, data, version, size=0,
compressed=False, digest=None, logical_size=None):
"""Adds a new file to the storage.
If the file with the same name existed before, it's not
guaranteed that the link for the old version will exist until
the operation co... | Adds a new file to the storage.
If the file with the same name existed before, it's not
guaranteed that the link for the old version will exist until
the operation completes, but it's guaranteed that the link
will never point to an invalid blob.
Args:
name: ... |
def play(self):
"""Starts a playback"""
if self._proc.state() == QProcess.Running:
if self.isPlaying is False:
self._execute("pause")
self._changePlayingState(True)
elif self._filePath is not None:
self._kill()
self._run(self._f... | Starts a playback |
def nfa_word_acceptance(nfa: dict, word: list) -> bool:
""" Checks if a given word is accepted by a NFA.
The word w is accepted by a NFA if exists at least an
accepting run on w.
:param dict nfa: input NFA;
:param list word: list of symbols ∈ nfa['alphabet'];
:return: *(bool)*, True if the wor... | Checks if a given word is accepted by a NFA.
The word w is accepted by a NFA if exists at least an
accepting run on w.
:param dict nfa: input NFA;
:param list word: list of symbols ∈ nfa['alphabet'];
:return: *(bool)*, True if the word is accepted, False otherwise. |
def beginning_offsets(self, partitions):
"""Get the first offset for the given partitions.
This method does not change the current consumer position of the
partitions.
Note:
This method may block indefinitely if the partition does not exist.
Arguments:
... | Get the first offset for the given partitions.
This method does not change the current consumer position of the
partitions.
Note:
This method may block indefinitely if the partition does not exist.
Arguments:
partitions (list): List of TopicPartition instances ... |
def write(path, pid, timestamp):
"""
Write the contents of a LockFile.
Arguments:
path (str): Path to lockfile.
pid (int): The integer process ID.
timestamp (datetime): The time the lock was aquired.
"""
with open(path, "w") as lockfile:
... | Write the contents of a LockFile.
Arguments:
path (str): Path to lockfile.
pid (int): The integer process ID.
timestamp (datetime): The time the lock was aquired. |
def uniform_filter(data, size=7, res_g=None, sub_blocks=(1, 1, 1), normalized = True):
"""
mean filter of given size
Parameters
----------
data: 2 or 3 dimensional ndarray or OCLArray of type float32
input data
size: scalar, tuple
the size of the patch to consider
res_g:... | mean filter of given size
Parameters
----------
data: 2 or 3 dimensional ndarray or OCLArray of type float32
input data
size: scalar, tuple
the size of the patch to consider
res_g: OCLArray
store result in buffer if given
sub_blocks:
perform over subblock tiling ... |
def sendData(self, data):
"""Write data to server"""
# Not set up yet
if self.client_log is None:
self.client_log_buffer.append(data)
else:
self.client_log.write(data)
self.transport.write(data) | Write data to server |
def get_options(self):
"""Get the options that have been set.
Called after the user has added all their own options
and is ready to use the variables.
"""
(options, args) = self.parser.parse_args()
# Set values from .visdkrc, but only if they haven't already been set
... | Get the options that have been set.
Called after the user has added all their own options
and is ready to use the variables. |
def CreateDevice(self, device_address):
'''Create a new device '''
device_name = 'dev_' + device_address.replace(':', '_').upper()
adapter_path = self.path
path = adapter_path + '/' + device_name
if path not in mockobject.objects:
raise dbus.exceptions.DBusException(
'Could not ... | Create a new device |
def set_policy_alert_threshold(self, policy_ids, alert_threshold):
"""Set the alert theshold for the given policies."""
for policy_id in policy_ids:
self.logger.debug('Setting alert threshold for policy {0} to {1}'.format(policy_id, alert_threshold))
result = self.zap.ascan.set_p... | Set the alert theshold for the given policies. |
def support_autoupload_param_password(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
support = ET.SubElement(config, "support", xmlns="urn:brocade.com:mgmt:brocade-ras")
autoupload_param = ET.SubElement(support, "autoupload-param")
password = ET... | Auto Generated Code |
def window_features(idx, window_size=100, overlap=10):
""" Generate indexes for a sliding window with overlap
:param array idx: The indexes that need to be windowed.
:param int window_size: The size of the window.
:param int overlap: How much should each window overlap.
... | Generate indexes for a sliding window with overlap
:param array idx: The indexes that need to be windowed.
:param int window_size: The size of the window.
:param int overlap: How much should each window overlap.
:return array view: The indexes for the windows with overlap. |
def make_future_info(first_sid,
root_symbols,
years,
notice_date_func,
expiration_date_func,
start_date_func,
month_codes=None,
multiplier=500):
"""
Create a DataFra... | Create a DataFrame representing futures for `root_symbols` during `year`.
Generates a contract per triple of (symbol, year, month) supplied to
`root_symbols`, `years`, and `month_codes`.
Parameters
----------
first_sid : int
The first sid to use for assigning sids to the created contracts.... |
def __dbfHeader(self):
"""Reads a dbf header. Xbase-related code borrows heavily from ActiveState Python Cookbook Recipe 362715 by Raymond Hettinger"""
if not self.dbf:
raise ShapefileException("Shapefile Reader requires a shapefile or file-like object. (no dbf file found)")
dbf ... | Reads a dbf header. Xbase-related code borrows heavily from ActiveState Python Cookbook Recipe 362715 by Raymond Hettinger |
def _append_zeros_if_too_small(self, value):
""" Appends zeros to the points stored if the value we are trying to
fit is bigger
"""
size_diff = len(value) - len(self.array)
if size_diff:
self.array = np.append(
self.array, np.zeros(size_diff, dtype=sel... | Appends zeros to the points stored if the value we are trying to
fit is bigger |
def _check_module_attrs(self, node, module, module_names):
"""check that module_names (list of string) are accessible through the
given module
if the latest access name corresponds to a module, return it
"""
assert isinstance(module, astroid.Module), module
while module_n... | check that module_names (list of string) are accessible through the
given module
if the latest access name corresponds to a module, return it |
def reorder(self, dst_order, arr, src_order=None):
"""Reorder the output array to match that needed by the viewer."""
if dst_order is None:
dst_order = self.viewer.rgb_order
if src_order is None:
src_order = self.rgb_order
if src_order != dst_order:
ar... | Reorder the output array to match that needed by the viewer. |
def _hrf_kernel(hrf_model, tr, oversampling=50, fir_delays=None):
""" Given the specification of the hemodynamic model and time parameters,
return the list of matching kernels
Parameters
----------
hrf_model : string or None,
identifier of the hrf model
tr : float
the repetitio... | Given the specification of the hemodynamic model and time parameters,
return the list of matching kernels
Parameters
----------
hrf_model : string or None,
identifier of the hrf model
tr : float
the repetition time in seconds
oversampling : int, optional
temporal overs... |
def send_script_sync(self, conn_id, data, progress_callback):
"""Asynchronously send a a script to this IOTile device
Args:
conn_id (int): A unique identifier that will refer to this connection
data (string): the script to send to the device
progress_callback (callab... | Asynchronously send a a script to this IOTile device
Args:
conn_id (int): A unique identifier that will refer to this connection
data (string): the script to send to the device
progress_callback (callable): A function to be called with status on our progress, called as:
... |
def findWalkthrough(self, name):
"""
Looks up the walkthrough based on the given name.
:param name | <str>
"""
for walkthrough in self._walkthroughs:
if walkthrough.name() == name:
return walkthrough
return None | Looks up the walkthrough based on the given name.
:param name | <str> |
def df_representative_structures(self):
"""DataFrame: Get a dataframe of representative protein structure information."""
rep_struct_pre_df = []
df_cols = ['gene', 'id', 'is_experimental', 'file_type', 'structure_file']
for g in self.genes_with_a_representative_structure:
re... | DataFrame: Get a dataframe of representative protein structure information. |
def r(self, **kwargs):
"""
Resolve the object.
This returns default (if present) or fails on an Empty.
"""
# by using kwargs we ensure that usage of positional arguments, as if
# this object were another kind of function, will fail-fast and raise
# a TypeError
... | Resolve the object.
This returns default (if present) or fails on an Empty. |
def delete(cls, cert_id, background=False):
""" Delete a certificate."""
result = cls.call('cert.delete', cert_id)
if background:
return result
cls.echo("Deleting your certificate.")
cls.display_progress(result)
cls.echo('Your certificate %s has been deleted... | Delete a certificate. |
def setModelData(self, editor, model, index):
""" Gets data from the editor widget and stores it in the specified model at the item index.
Does this by calling getEditorValue of the config tree item at the index.
:type editor: QWidget
:type model: ConfigTreeModel
... | Gets data from the editor widget and stores it in the specified model at the item index.
Does this by calling getEditorValue of the config tree item at the index.
:type editor: QWidget
:type model: ConfigTreeModel
:type index: QModelIndex
Reimplemented from ... |
def get_customer_group_by_id(cls, customer_group_id, **kwargs):
"""Find CustomerGroup
Return single instance of CustomerGroup by its ID.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.get_cus... | Find CustomerGroup
Return single instance of CustomerGroup by its ID.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.get_customer_group_by_id(customer_group_id, async=True)
>>> result = threa... |
def findTextBackward(self, block, column, needle):
"""Search for a needle and return (block, column)
Raise ValueError, if not found
"""
if column is not None:
index = block.text()[:column].rfind(needle)
else:
index = block.text().rfind(needle)
if ... | Search for a needle and return (block, column)
Raise ValueError, if not found |
def get_key_names(self):
"""
Gets keys of all elements stored in this map.
:return: a list with all map keys.
"""
names = []
for (k, _) in self.items():
names.append(k)
return names | Gets keys of all elements stored in this map.
:return: a list with all map keys. |
def user_add_link(self):
'''
Create link by user.
'''
if self.check_post_role()['ADD']:
pass
else:
return False
post_data = self.get_post_data()
post_data['user_name'] = self.get_current_user()
cur_uid = tools.get_uudd(2)
... | Create link by user. |
def with_ascendants_for_slug(self, slug, **kwargs):
"""
Given a slug, returns a list of pages from ascendants to
descendants, that form the parent/child page relationships
for that slug. The main concern is to do this in a single
database query rather than querying the database f... | Given a slug, returns a list of pages from ascendants to
descendants, that form the parent/child page relationships
for that slug. The main concern is to do this in a single
database query rather than querying the database for parents
of a given page.
Primarily used in ``PageMid... |
def scale(self, w=1.0, h=1.0):
"""Resizes the layer to the given width and height.
When width w or height h is a floating-point number,
scales percentual,
otherwise scales to the given size in pixels.
"""
from types import FloatType
w0, h0 = self.... | Resizes the layer to the given width and height.
When width w or height h is a floating-point number,
scales percentual,
otherwise scales to the given size in pixels. |
def base_style(self):
"""
Sibling CT_Style element this style is based on or |None| if no base
style or base style not found.
"""
basedOn = self.basedOn
if basedOn is None:
return None
styles = self.getparent()
base_style = styles.get_by_id(bas... | Sibling CT_Style element this style is based on or |None| if no base
style or base style not found. |
def configure(configFile=None, baseConfig="ProductionConfig",
port=8000, extraConfig={}):
"""
TODO Document this critical function! What does it do? What does
it assume?
"""
file_handler = StreamHandler()
file_handler.setLevel(logging.WARNING)
app.logger.addHandler(file_handler... | TODO Document this critical function! What does it do? What does
it assume? |
def force_atlas2_layout(graph,
pos_list=None,
node_masses=None,
iterations=100,
outbound_attraction_distribution=False,
lin_log_mode=False,
prevent_overlapping=False,
... | Position nodes using ForceAtlas2 force-directed algorithm
Parameters
----------
graph: NetworkX graph
A position will be assigned to every node in G.
pos_list : dict or None optional (default=None)
Initial positions for nodes as a dictionary with node as keys
and values as a c... |
def _get_gecos(name, root=None):
'''
Retrieve GECOS field info and return it in dictionary form
'''
if root is not None and __grains__['kernel'] != 'AIX':
getpwnam = functools.partial(_getpwnam, root=root)
else:
getpwnam = functools.partial(pwd.getpwnam)
gecos_field = salt.utils.... | Retrieve GECOS field info and return it in dictionary form |
def encrypted_score(self, x):
"""Compute the score of `x` by multiplying with the encrypted model,
which is a vector of `paillier.EncryptedNumber`"""
score = self.intercept
_, idx = x.nonzero()
for i in idx:
score += x[0, i] * self.weights[i]
return score | Compute the score of `x` by multiplying with the encrypted model,
which is a vector of `paillier.EncryptedNumber` |
def map_reduce(iterable, keyfunc, valuefunc=None, reducefunc=None):
"""Return a dictionary that maps the items in *iterable* to categories
defined by *keyfunc*, transforms them with *valuefunc*, and
then summarizes them by category with *reducefunc*.
*valuefunc* defaults to the identity function if it ... | Return a dictionary that maps the items in *iterable* to categories
defined by *keyfunc*, transforms them with *valuefunc*, and
then summarizes them by category with *reducefunc*.
*valuefunc* defaults to the identity function if it is unspecified.
If *reducefunc* is unspecified, no summarization takes ... |
def substitute_placeholders(inputstring, placeholders):
"""
Take a string with placeholders, and return the strings with substitutions.
"""
newst = inputstring.format(link=placeholders.link,
filename=placeholders.filename,
directory=placehold... | Take a string with placeholders, and return the strings with substitutions. |
def get_ajd_bound(mesh):
"""
Determine triangular elements adjacend to the boundary elements
"""
print('Get elements adjacent to boundaries')
boundary_elements = []
str_adj_boundaries = ''
# for boundary in mesh['elements']['1']:
boundaries = mesh['boundaries']['12'] + mesh['boundaries']... | Determine triangular elements adjacend to the boundary elements |
def serialize(self, obj, *args, **kwargs):
"""Serialize user as per Meteor accounts serialization."""
# use default serialization, then modify to suit our needs.
data = super(Users, self).serialize(obj, *args, **kwargs)
# everything that isn't handled explicitly ends up in `profile`
... | Serialize user as per Meteor accounts serialization. |
def list_device_data_sources(self, device_rid):
"""
List data sources of a portal device with rid 'device_rid'.
http://docs.exosite.com/portals/#list-device-data-source
"""
headers = {
'User-Agent': self.user_agent(),
}
headers.update(self... | List data sources of a portal device with rid 'device_rid'.
http://docs.exosite.com/portals/#list-device-data-source |
def _expand_parameters(specification, parameters, original=None):
"""Expand parameters inside comands for Serial workflow specifications.
:param specification: Full valid Serial workflow specification.
:param parameters: Parameters to be extended on a Serial specification.
:param original: Flag which, ... | Expand parameters inside comands for Serial workflow specifications.
:param specification: Full valid Serial workflow specification.
:param parameters: Parameters to be extended on a Serial specification.
:param original: Flag which, determins type of specifications to return.
:returns: If 'original' p... |
def _set_data(self, action):
"""
capture Wikidata API response data
"""
if action == 'labels':
self._set_labels()
if action == 'wikidata':
self._set_wikidata()
self.get_labels(show=False) | capture Wikidata API response data |
def optimize_for_size(self):
'''
http://www.avrfreaks.net/index.php?name=PNphpBB2&file=viewtopic&t=90752
http://www.avrfreaks.net/index.php?name=PNphpBB2&file=viewtopic&t=69813
'''
self.optimization = 's'
self.relax = True
self.gc_sections = True
self.ffu... | http://www.avrfreaks.net/index.php?name=PNphpBB2&file=viewtopic&t=90752
http://www.avrfreaks.net/index.php?name=PNphpBB2&file=viewtopic&t=69813 |
def make_chart(self):
'''
Returns
-------
altair.Chart
'''
task_df = self.get_task_df()
import altair as alt
chart = alt.Chart(task_df).mark_bar().encode(
x='start',
x2='end',
y='term',
)
return chart | Returns
-------
altair.Chart |
def update(self, z, R2=None):
"""
Add a new measurement (z) to the kalman filter. If z is None, nothing
is changed.
Parameters
----------
z : np.array
measurement for this update.
R2 : np.array, scalar, or None
Sqrt of meaaurement noize.... | Add a new measurement (z) to the kalman filter. If z is None, nothing
is changed.
Parameters
----------
z : np.array
measurement for this update.
R2 : np.array, scalar, or None
Sqrt of meaaurement noize. Optionally provide to override the
me... |
def poster(self):
""" Returns the considered user. """
user_model = get_user_model()
return get_object_or_404(user_model, pk=self.kwargs[self.user_pk_url_kwarg]) | Returns the considered user. |
def equation(self):
"""Mix-in class that returns matrix rows for difference in head between inside and
outside equals zeros
Returns matrix part (nunknowns,neq)
Returns rhs part nunknowns
"""
mat = np.empty((self.nunknowns, self.model.neq))
rhs = np.zeros(self.nunk... | Mix-in class that returns matrix rows for difference in head between inside and
outside equals zeros
Returns matrix part (nunknowns,neq)
Returns rhs part nunknowns |
def metaclass(*metaclasses):
# type: (*type) -> Callable[[type], type]
"""Create the class using all metaclasses.
Args:
metaclasses: A tuple of metaclasses that will be used to generate and
replace a specified class.
Returns:
A decorator that will recreate the class using t... | Create the class using all metaclasses.
Args:
metaclasses: A tuple of metaclasses that will be used to generate and
replace a specified class.
Returns:
A decorator that will recreate the class using the specified
metaclasses. |
def get_import_status(self, sis_import):
"""
Get the status of an already created SIS import.
https://canvas.instructure.com/doc/api/sis_imports.html#method.sis_imports_api.show
"""
if not self._canvas_account_id:
raise MissingAccountID()
url = SIS_IMPORTS_A... | Get the status of an already created SIS import.
https://canvas.instructure.com/doc/api/sis_imports.html#method.sis_imports_api.show |
def register_iq_request_handler(self, type_, payload_cls, cb, *,
with_send_reply=False):
"""
Register a coroutine function or a function returning an awaitable to
run when an IQ request is received.
:param type_: IQ type to react to (must be a request... | Register a coroutine function or a function returning an awaitable to
run when an IQ request is received.
:param type_: IQ type to react to (must be a request type).
:type type_: :class:`~aioxmpp.IQType`
:param payload_cls: Payload class to react to (subclass of
:class:`~xso... |
def start_prompt(self):
"""Start the interpreter."""
logger.show("Coconut Interpreter:")
logger.show("(type 'exit()' or press Ctrl-D to end)")
self.start_running()
while self.running:
try:
code = self.get_input()
if code:
... | Start the interpreter. |
def convert_padding(params, w_name, scope_name, inputs, layers, weights, names):
"""
Convert padding layer.
Args:
params: dictionary with layer parameters
w_name: name prefix in state_dict
scope_name: pytorch scope name
inputs: pytorch node inputs
layers: dictionary ... | Convert padding layer.
Args:
params: dictionary with layer parameters
w_name: name prefix in state_dict
scope_name: pytorch scope name
inputs: pytorch node inputs
layers: dictionary with keras tensors
weights: pytorch state_dict
names: use short names for ker... |
def transform_hits(hits):
"""
The list from pypi is really a list of versions. We want a list of
packages with the list of versions stored inline. This converts the
list from pypi into one we can use.
"""
packages = {}
for hit in hits:
name = hit['name']
summary = hit['summar... | The list from pypi is really a list of versions. We want a list of
packages with the list of versions stored inline. This converts the
list from pypi into one we can use. |
def _find_usage_vpc_links(self):
"""
Find usage on VPC Links. Update `self.limits`.
"""
logger.debug('Finding usage for VPC Links')
link_count = 0
paginator = self.conn.get_paginator('get_vpc_links')
for resp in paginator.paginate():
link_count += len(... | Find usage on VPC Links. Update `self.limits`. |
def fetch_search_document(self, *, index):
"""Fetch the object's document from a search index by id."""
assert self.pk, "Object must have a primary key before being indexed."
client = get_client()
return client.get(index=index, doc_type=self.search_doc_type, id=self.pk) | Fetch the object's document from a search index by id. |
def enable_page_breakpoint(self, dwProcessId, address):
"""
Enables the page breakpoint at the given address.
@see:
L{define_page_breakpoint},
L{has_page_breakpoint},
L{get_page_breakpoint},
L{enable_one_shot_page_breakpoint},
L{disabl... | Enables the page breakpoint at the given address.
@see:
L{define_page_breakpoint},
L{has_page_breakpoint},
L{get_page_breakpoint},
L{enable_one_shot_page_breakpoint},
L{disable_page_breakpoint}
L{erase_page_breakpoint},
@type dwP... |
def load(self):
"""Load the data file, do some basic type conversions
"""
df = pd.read_csv(self.input_file,
encoding='utf8')
df['wiki_id'] = df['painting'].str.split('/').str[-1]
df['creator_wiki_id'] = df['creator'].str.split('/').str[-1]
df['d... | Load the data file, do some basic type conversions |
def _deserialize_dict(cls, cls_target, dict_):
"""
:type cls_target: T|type
:type dict_: dict
:rtype: T
"""
instance = cls_target.__new__(cls_target)
dict_deserialized = cls._deserialize_dict_attributes(cls_target, dict_)
instance.__dict__ = cls._fill_de... | :type cls_target: T|type
:type dict_: dict
:rtype: T |
def reset(self):
"""
Clear the active cells.
"""
self.bumpPhases = np.empty((2,0), dtype="float")
self.phaseDisplacement = np.empty((0,2), dtype="float")
self.cellsForActivePhases = np.empty(0, dtype="int")
self.activeCells = np.empty(0, dtype="int")
self.learningCells = np.empty(0, dtyp... | Clear the active cells. |
def command_line_runner():
""" I run functions from the command-line! """
filename = sys.argv[-1]
if not filename.endswith(".rst"):
print("ERROR! Please enter a ReStructuredText filename!")
sys.exit()
print(rst_to_json(file_opener(filename))) | I run functions from the command-line! |
def _AddSerializeToStringMethod(message_descriptor, cls):
"""Helper for _AddMessageMethods()."""
def SerializeToString(self):
# Check if the message has all of its required fields set.
errors = []
if not self.IsInitialized():
raise message_mod.EncodeError(
'Message %s is missing require... | Helper for _AddMessageMethods(). |
def get_or_search(self) -> List[GridQubit]:
"""Starts the search or gives previously calculated sequence.
Returns:
The linear qubit sequence found.
"""
if not self._sequence:
self._sequence = self._find_sequence()
return self._sequence | Starts the search or gives previously calculated sequence.
Returns:
The linear qubit sequence found. |
def __get_category(self, category, name, vivify=False):
"""
Gets recusively requested category, alternately if **vivify** argument is set,
the category will be created.
:param category: Base category.
:type category: dict
:param name: Category to retrieve or vivify.
... | Gets recusively requested category, alternately if **vivify** argument is set,
the category will be created.
:param category: Base category.
:type category: dict
:param name: Category to retrieve or vivify.
:type name: unicode
:param vivify: Vivify missing parents in the... |
def accuracy(links_true, links_pred=None, total=None):
"""accuracy(links_true, links_pred, total)
Compute the accuracy.
The accuracy is given by (TP+TN)/(TP+FP+TN+FN).
Parameters
----------
links_true: pandas.MultiIndex, pandas.DataFrame, pandas.Series
The true (or actual) collection ... | accuracy(links_true, links_pred, total)
Compute the accuracy.
The accuracy is given by (TP+TN)/(TP+FP+TN+FN).
Parameters
----------
links_true: pandas.MultiIndex, pandas.DataFrame, pandas.Series
The true (or actual) collection of links.
links_pred: pandas.MultiIndex, pandas.DataFrame,... |
def wait_for_string(self, expected_string, timeout=60):
"""Wait for string FSM."""
# 0 1 2 3
events = [self.syntax_error_re, self.connection_closed_re, expected_string, self.press_return_re,
... | Wait for string FSM. |
def resetPassword(self, userId):
'''
Changes a user's password to a system-generated value.
'''
self._setHeaders('resetPassword')
return self._sforce.service.resetPassword(userId) | Changes a user's password to a system-generated value. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.