positive stringlengths 100 30.3k | anchor stringlengths 1 15k |
|---|---|
def ck_portf_004(self):
''' 價走平一個半月。(箱型整理、盤整) '''
return self.a.SD < 0.25 and self.a.stock_vol[-1] > 1000*1000 and self.a.raw_data[-1] > 10 | 價走平一個半月。(箱型整理、盤整) |
def __modify(self, subscription_id, **kwargs):
"""Call documentation: `/subscription/modify
<https://www.wepay.com/developer/reference/subscription#modify>`_, plus
extra keyword parameters:
:keyword str access_token: will be used instead of instance's
``access_token``... | Call documentation: `/subscription/modify
<https://www.wepay.com/developer/reference/subscription#modify>`_, plus
extra keyword parameters:
:keyword str access_token: will be used instead of instance's
``access_token``, with ``batch_mode=True`` will set `authorization`
... |
def from_mult_iters(cls, name=None, idx=None, **kwargs):
"""Load values from multiple iters
Parameters
----------
name : string, default None
Name of the data set. If None (default), the name will be set to
``'table'``.
idx: string, default None
... | Load values from multiple iters
Parameters
----------
name : string, default None
Name of the data set. If None (default), the name will be set to
``'table'``.
idx: string, default None
Iterable to use for the data index
**kwargs : dict of ite... |
def source(self):
"""Parameters for saving zip backups"""
with gui.FlexForm(self.title, auto_size_text=True, default_element_size=(40, 1)) as form:
layout = [
[gui.Text('Zip Backup utility', size=(30, 1), font=("Helvetica", 30), text_color='blue')],
[gui.Text(... | Parameters for saving zip backups |
def dumps(obj, indent=None, default=None, sort_keys=False, **kw):
"""Dump string."""
return YAMLEncoder(indent=indent, default=default, sort_keys=sort_keys, **kw).encode(obj) | Dump string. |
def process_vlen(data_header, array):
"""Process vlen coming back from NCStream v2.
This takes the array of values and slices into an object array, with entries containing
the appropriate pieces of the original array. Sizes are controlled by the passed in
`data_header`.
Parameters
----------
... | Process vlen coming back from NCStream v2.
This takes the array of values and slices into an object array, with entries containing
the appropriate pieces of the original array. Sizes are controlled by the passed in
`data_header`.
Parameters
----------
data_header : Header
array : :class:`n... |
def add_build_tags(self, tags, project, build_id):
"""AddBuildTags.
Adds tags to a build.
:param [str] tags: The tags to add.
:param str project: Project ID or project name
:param int build_id: The ID of the build.
:rtype: [str]
"""
route_values = {}
... | AddBuildTags.
Adds tags to a build.
:param [str] tags: The tags to add.
:param str project: Project ID or project name
:param int build_id: The ID of the build.
:rtype: [str] |
def process(self, endpoint, **kwargs):
"""
Polls the data from prometheus and pushes them as gauges
`endpoint` is the metrics endpoint to use to poll metrics from Prometheus
Note that if the instance has a 'tags' attribute, it will be pushed
automatically as additional custom ta... | Polls the data from prometheus and pushes them as gauges
`endpoint` is the metrics endpoint to use to poll metrics from Prometheus
Note that if the instance has a 'tags' attribute, it will be pushed
automatically as additional custom tags and added to the metrics |
def get_bookmarks(self):
"""
Get the stored bookmarks from the server. Causes signals to be
fired to reflect the changes.
:returns: a list of bookmarks
"""
with (yield from self._lock):
bookmarks = yield from self._get_bookmarks()
self._diff_emit_... | Get the stored bookmarks from the server. Causes signals to be
fired to reflect the changes.
:returns: a list of bookmarks |
def alter_database_admin(self, username, is_admin):
"""Alter the database admin."""
url = "db/{0}/users/{1}".format(self._database, username)
data = {'admin': is_admin}
self.request(
url=url,
method='POST',
data=data,
expected_response_co... | Alter the database admin. |
def add_comment(self, comment):
"""
Add a comment to the database.
Args:
comment (hotdoc.core.Comment): comment to add
"""
if not comment:
return
self.__comments[comment.name] = comment
self.comment_added_signal(self, comment) | Add a comment to the database.
Args:
comment (hotdoc.core.Comment): comment to add |
def init_host(self):
"""
Initial host
"""
env.host_string = self.host_string
env.user = self.host_user
env.password = self.host_passwd
env.key_filename = self.host_keyfile | Initial host |
def get_items_by_ids(self, item_ids, item_type=None):
"""Given a list of item ids, return all the Item objects
Args:
item_ids (obj): List of item IDs to query
item_type (str): (optional) Item type to filter results with
Returns:
List of `Item` objects for gi... | Given a list of item ids, return all the Item objects
Args:
item_ids (obj): List of item IDs to query
item_type (str): (optional) Item type to filter results with
Returns:
List of `Item` objects for given item IDs and given item type |
def list2pd(all_data, subjindex=None, listindex=None):
"""
Makes multi-indexed dataframe of subject data
Parameters
----------
all_data : list of lists of strings
strings are either all presented or all recalled items, in the order of presentation or recall
*should also work for pre... | Makes multi-indexed dataframe of subject data
Parameters
----------
all_data : list of lists of strings
strings are either all presented or all recalled items, in the order of presentation or recall
*should also work for presented / recalled ints and floats, if desired
Returns
---... |
def find_all(self, cls):
"""Required functionality."""
final_results = []
table = self.get_class_table(cls)
for db_result in table.scan():
obj = cls.from_data(db_result['value'])
final_results.append(obj)
return final_results | Required functionality. |
def count_SMS(self, conditions={}):
"""
Count all certified sms
"""
url = self.SMS_COUNT_URL + "?"
for key, value in conditions.items():
if key is 'ids':
value = ",".join(value)
url += '&%s=%s' % (key, value)
connection = Connect... | Count all certified sms |
def tag_subcat_info( mrf_lines, subcat_rules ):
''' Adds subcategorization information (hashtags) to verbs and adpositions;
Argument subcat_rules must be a dict containing subcategorization information,
loaded via method load_subcat_info();
Performs word lemma lookups in subcat_rul... | Adds subcategorization information (hashtags) to verbs and adpositions;
Argument subcat_rules must be a dict containing subcategorization information,
loaded via method load_subcat_info();
Performs word lemma lookups in subcat_rules, and in case of a match, checks
word part-of... |
def parse_declaration_expressn_memberaccess(self, lhsAST, rhsAST, es):
"""
Instead of "Class.variablename", use "Class.rv('variablename')".
:param lhsAST:
:param rhsAST:
:param es:
:return:
"""
if isinstance(lhsAST, wdl_parser.Terminal):
es = ... | Instead of "Class.variablename", use "Class.rv('variablename')".
:param lhsAST:
:param rhsAST:
:param es:
:return: |
def supported_types_for_non_geo_entity(country_code):
"""Returns the types for a country-code belonging to a non-geographical entity
which the library has metadata for. Will not include FIXED_LINE_OR_MOBILE
(if numbers for this non-geographical entity could be classified as
FIXED_LINE_OR_MOBILE, both FI... | Returns the types for a country-code belonging to a non-geographical entity
which the library has metadata for. Will not include FIXED_LINE_OR_MOBILE
(if numbers for this non-geographical entity could be classified as
FIXED_LINE_OR_MOBILE, both FIXED_LINE and MOBILE would be present) and
UNKNOWN.
N... |
def merge_adjacent(dom, tag_name):
"""
Merge all adjacent tags with the specified tag name.
Return the number of merges performed.
"""
for node in dom.getElementsByTagName(tag_name):
prev_sib = node.previousSibling
if prev_sib and prev_sib.nodeName == node.tagName:
for ch... | Merge all adjacent tags with the specified tag name.
Return the number of merges performed. |
def render_files(self, root=None):
""" Render the file path as accordions
"""
if root is None:
tmp = os.environ.get('TMP')
root = sys.path[1 if tmp and tmp in sys.path else 0]
items = []
for filename in os.listdir(root):
# for subdirname in di... | Render the file path as accordions |
def get_machine_group_applied_configs(self, project_name, group_name):
""" get the logtail config names applied in a machine group
Unsuccessful opertaion will cause an LogException.
:type project_name: string
:param project_name: the Project name
:type group_name: strin... | get the logtail config names applied in a machine group
Unsuccessful opertaion will cause an LogException.
:type project_name: string
:param project_name: the Project name
:type group_name: string
:param group_name: the group name list
:return: GetMachineGrou... |
def device_connect(device_id):
""" Force a connection attempt via HTTP GET. """
success = False
if device_id in devices:
devices[device_id].connect()
success = True
return jsonify(success=success) | Force a connection attempt via HTTP GET. |
def proportion_merge(brands, exemplars):
""" Return the proportion of a brand's followers who also follower an
exemplar. We merge all exemplar followers into one big pseudo-account."""
scores = {}
exemplar_followers = set()
for followers in exemplars.values():
exemplar_followers |= followers... | Return the proportion of a brand's followers who also follower an
exemplar. We merge all exemplar followers into one big pseudo-account. |
def get_analysis_question(hazard, exposure):
"""Construct analysis question based on hazard and exposure.
:param hazard: A hazard definition.
:type hazard: dict
:param exposure: An exposure definition.
:type exposure: dict
:returns: Analysis question based on reporting standards.
:rtype: ... | Construct analysis question based on hazard and exposure.
:param hazard: A hazard definition.
:type hazard: dict
:param exposure: An exposure definition.
:type exposure: dict
:returns: Analysis question based on reporting standards.
:rtype: str |
def parse(yaml, validate=True):
"""
Parse the given YAML data into a `Config` object, optionally validating it first.
:param yaml: YAML data (either a string, a stream, or pre-parsed Python dict/list)
:type yaml: list|dict|str|file
:param validate: Whether to validate the data before attempting to ... | Parse the given YAML data into a `Config` object, optionally validating it first.
:param yaml: YAML data (either a string, a stream, or pre-parsed Python dict/list)
:type yaml: list|dict|str|file
:param validate: Whether to validate the data before attempting to parse it.
:type validate: bool
:retu... |
def input_value(self, locator, text):
"""Sets the given value into text field identified by `locator`. This is an IOS only keyword, input value makes use of set_value
See `introduction` for details about locating elements.
"""
self._info("Setting text '%s' into text field '%s'" % (... | Sets the given value into text field identified by `locator`. This is an IOS only keyword, input value makes use of set_value
See `introduction` for details about locating elements. |
def evaluate_binop_math(self, operation, left, right, **kwargs):
"""
Evaluate given mathematical binary operation with given operands.
"""
if not operation in self.binops_math:
raise ValueError("Invalid math binary operation '{}'".format(operation))
if left is None or... | Evaluate given mathematical binary operation with given operands. |
def code(ctx, show_hidden, query, single):
"""
Generate codes.
Generate codes from credentials stored on your YubiKey.
Provide a query string to match one or more specific credentials.
Touch and HOTP credentials require a single match to be triggered.
"""
ensure_validated(ctx)
control... | Generate codes.
Generate codes from credentials stored on your YubiKey.
Provide a query string to match one or more specific credentials.
Touch and HOTP credentials require a single match to be triggered. |
def update_course_settings(self, course_id, allow_student_discussion_editing=None, allow_student_discussion_topics=None, allow_student_forum_attachments=None, allow_student_organized_groups=None, hide_distribution_graphs=None, hide_final_grades=None, home_page_announcement_limit=None, lock_all_announcements=None, restr... | Update course settings.
Can update the following course settings: |
def download(cls, url, filename=None):
"""
Download a file into the correct cache directory.
"""
return utility.download(url, cls.directory(), filename) | Download a file into the correct cache directory. |
def process(self, salt_data, token, opts):
'''
Process events and publish data
'''
parts = salt_data['tag'].split('/')
if len(parts) < 2:
return
# TBD: Simplify these conditional expressions
if parts[1] == 'job':
if parts[3] == 'new':
... | Process events and publish data |
def _check_team_exists(team):
"""
Check that the team registry actually exists.
"""
if team is None:
return
hostname = urlparse(get_registry_url(team)).hostname
try:
socket.gethostbyname(hostname)
except IOError:
try:
# Do we have internet?
so... | Check that the team registry actually exists. |
def roundrobin(*iterables):
"""roundrobin('ABC', 'D', 'EF') --> A D E B F C"""
raise NotImplementedError('not sure if this implementation is correct')
# http://stackoverflow.com/questions/11125212/interleaving-lists-in-python
#sentinel = object()
#return (x for x in chain(*zip_longest(fillvalue=sent... | roundrobin('ABC', 'D', 'EF') --> A D E B F C |
def limitsSql(startIndex=0, maxResults=0):
"""
Construct a SQL LIMIT clause
"""
if startIndex and maxResults:
return " LIMIT {}, {}".format(startIndex, maxResults)
elif startIndex:
raise Exception("startIndex was provided, but maxResults was not")
elif maxResults:
return ... | Construct a SQL LIMIT clause |
def all_characters(self):
'''
Returns a queryset of all characters associated with this node and its descendants,
excluding any duplicates.
'''
qs = self.assoc_characters.all()
for node in self.get_descendants():
qs2 = node.assoc_characters.all()
q... | Returns a queryset of all characters associated with this node and its descendants,
excluding any duplicates. |
def _build_memory_regions(self):
"""! @brief Creates memory region instances for the device.
For each `<memory>` element in the device info, a memory region object is created and
added to the `_regions` attribute. IROM or non-writable memories are created as RomRegions
by this m... | ! @brief Creates memory region instances for the device.
For each `<memory>` element in the device info, a memory region object is created and
added to the `_regions` attribute. IROM or non-writable memories are created as RomRegions
by this method. They will be converted to FlashRegion... |
def parse(self, xml_file):
"Get a list of parsed recipes from BeerXML input"
recipes = []
with open(xml_file, "rt") as f:
tree = ElementTree.parse(f)
for recipeNode in tree.iter():
if self.to_lower(recipeNode.tag) != "recipe":
continue
... | Get a list of parsed recipes from BeerXML input |
def connect(self):
""" Connects to the Responsys soap service
Uses the credentials passed to the client init to login and setup the session id returned.
Returns True on successful connection, otherwise False.
"""
if self.session and self.session.is_expired:
# Close ... | Connects to the Responsys soap service
Uses the credentials passed to the client init to login and setup the session id returned.
Returns True on successful connection, otherwise False. |
def QA_save_tdx_to_mongo(file_dir, client=DATABASE):
"""save file
Arguments:
file_dir {str:direction} -- 文件的地址
Keyword Arguments:
client {Mongodb:Connection} -- Mongo Connection (default: {DATABASE})
"""
reader = TdxMinBarReader()
__coll = client.stock_min_five
for... | save file
Arguments:
file_dir {str:direction} -- 文件的地址
Keyword Arguments:
client {Mongodb:Connection} -- Mongo Connection (default: {DATABASE}) |
def make_batched_timer(self, bucket_seconds, chunk_size=100):
"""
Creates and returns an object implementing
:class:`txaio.IBatchedTimer`.
:param bucket_seconds: the number of seconds in each bucket. That
is, a value of 5 means that any timeout within a 5 second
... | Creates and returns an object implementing
:class:`txaio.IBatchedTimer`.
:param bucket_seconds: the number of seconds in each bucket. That
is, a value of 5 means that any timeout within a 5 second
window will be in the same bucket, and get notified at the
same time. ... |
def screenshot(self, viewID, filename):
"""screenshot(string, string) -> None
Save a screenshot for the given view to the given filename.
The fileformat is guessed from the extension, the available
formats differ from platform to platform but should at least
include ps, svg and ... | screenshot(string, string) -> None
Save a screenshot for the given view to the given filename.
The fileformat is guessed from the extension, the available
formats differ from platform to platform but should at least
include ps, svg and pdf, on linux probably gif, png and jpg as well. |
def with_headers(self, headers=None, **params):
"""
Add headers to the request.
:param headers: A dict, or a list of key, value pairs
:param params: A dict of key value pairs
"""
if isinstance(headers, (tuple, list)):
headers = dict(head... | Add headers to the request.
:param headers: A dict, or a list of key, value pairs
:param params: A dict of key value pairs |
def _init_metadata(self):
"""stub"""
self._first_angle_metadata = {
'element_id': Id(self.my_osid_object_form._authority,
self.my_osid_object_form._namespace,
'first_angle'),
'element_label': 'First Angle',
'in... | stub |
def _run_variantcall_batch_multicore(items, regions, final_file):
"""Run variant calling on a batch of items using multiple cores.
"""
batch_name = _get_batch_name(items)
variantcaller = _get_batch_variantcaller(items)
work_bams = [dd.get_work_bam(d) or dd.get_align_bam(d) for d in items]
def sp... | Run variant calling on a batch of items using multiple cores. |
def update_custom_service_account(self, account, nickname, password):
"""
修改客服帐号。
:param account: 客服账号的用户名
:param nickname: 客服账号的昵称
:param password: 客服账号的密码
:return: 返回的 JSON 数据包
"""
return self.post(
url="https://api.weixin.qq.com/customservi... | 修改客服帐号。
:param account: 客服账号的用户名
:param nickname: 客服账号的昵称
:param password: 客服账号的密码
:return: 返回的 JSON 数据包 |
def _writeFile(cls, filePath, content, encoding = None):
"""Safe file writing. Most common mistakes are checked against and reported before write
operation. After that, if anything unexpected happens, user won't be left without data or
with corrupted one as this method writes to a temporary file... | Safe file writing. Most common mistakes are checked against and reported before write
operation. After that, if anything unexpected happens, user won't be left without data or
with corrupted one as this method writes to a temporary file and then simply renames it
(which should be atomic operatio... |
def get_current_user():
"""Get current user object from middleware"""
thread_local = AutomatedLoggingMiddleware.thread_local
if hasattr(thread_local, 'current_user'):
user = thread_local.current_user
if isinstance(user, AnonymousUser):
user = None
else:
user = None
... | Get current user object from middleware |
def group_members_add(self, device_group_id, body, **kwargs): # noqa: E501
"""Add a device to a group # noqa: E501
Add one device to a group # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass asynchronous=True
... | Add a device to a group # noqa: E501
Add one device to a group # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass asynchronous=True
>>> thread = api.group_members_add(device_group_id, body, asynchronous=True)
... |
def sendline(self, s=''):
'''Wraps send(), sending string ``s`` to child process, with os.linesep
automatically appended. Returns number of bytes written. '''
n = self.send(s)
return n + self.send(self.linesep) | Wraps send(), sending string ``s`` to child process, with os.linesep
automatically appended. Returns number of bytes written. |
def input(self, file_data, **kwargs):
"""
Required by ply.yacc for this to quack (duck typing) like a ply lexer.
:param str file_data: Contents of the file to lex.
"""
self.lex = lex.lex(module=self, **kwargs)
self.tokens_queue = []
self.cur_indent = 0
# ... | Required by ply.yacc for this to quack (duck typing) like a ply lexer.
:param str file_data: Contents of the file to lex. |
async def get_chat(self, chat_id: typing.Union[base.Integer, base.String]) -> types.Chat:
"""
Use this method to get up to date information about the chat
(current name of the user for one-on-one conversations, current username of a user, group or channel, etc.).
Source: https://core.te... | Use this method to get up to date information about the chat
(current name of the user for one-on-one conversations, current username of a user, group or channel, etc.).
Source: https://core.telegram.org/bots/api#getchat
:param chat_id: Unique identifier for the target chat or username of the ... |
def save(self, filename, strip_prefix=''):
"""Save parameters to file.
Parameters
----------
filename : str
Path to parameter file.
strip_prefix : str, default ''
Strip prefix from parameter names before saving.
"""
arg_dict = {}
f... | Save parameters to file.
Parameters
----------
filename : str
Path to parameter file.
strip_prefix : str, default ''
Strip prefix from parameter names before saving. |
def construct_txt_file(self):
"""Construct the header of the txt file"""
textlines = ['Prediction of noncovalent interactions for PDB structure %s' % self.mol.pymol_name.upper(), ]
textlines.append("=" * len(textlines[0]))
textlines.append('Created on %s using PLIP v%s\n' % (time.strftim... | Construct the header of the txt file |
def _default_pad(self, data_type, num_elms): # @NoSelf
'''
The default pad values by CDF data type
'''
order = self._convert_option()
if (data_type == 51 or data_type == 52):
return str(' '*num_elms)
if (data_type == 1) or (data_type == 41):
pad_... | The default pad values by CDF data type |
def get_qpimage(self, idx):
"""Return background-corrected QPImage of data at index `idx`"""
if self._bgdata:
# The user has explicitly chosen different background data
# using `get_qpimage_raw`.
qpi = super(SeriesHdf5Qpimage, self).get_qpimage(idx)
else:
... | Return background-corrected QPImage of data at index `idx` |
def read_in_chunks(file_object, chunk_size=CHUNK_SIZE):
"""Generator to read a file piece by piece."""
while True:
data = file_object.read(chunk_size)
if not data:
break
yield data | Generator to read a file piece by piece. |
def parse_hh_mm_ss(self):
"""Parses raw time
:return: Time parsed
"""
split_count = self.raw.count(":")
if split_count == 2: # hh:mm:ss
return datetime.strptime(str(self.raw).strip(), "%H:%M:%S").time()
elif split_count == 1: # mm:ss
return dat... | Parses raw time
:return: Time parsed |
def is_cached(self, path, saltenv='base', cachedir=None):
'''
Returns the full path to a file if it is cached locally on the minion
otherwise returns a blank string
'''
if path.startswith('salt://'):
path, senv = salt.utils.url.parse(path)
if senv:
... | Returns the full path to a file if it is cached locally on the minion
otherwise returns a blank string |
def _detect_available_configs():
"""
Returns all currently used channels as well as
one other currently unused channel.
.. note::
This method will run into problems if thousands of
autodetected busses are used at once.
"""
with channels_lock:
... | Returns all currently used channels as well as
one other currently unused channel.
.. note::
This method will run into problems if thousands of
autodetected busses are used at once. |
def properties(self, rel_path=None):
""" Return a dictionary with all svn-properties associated with a
relative path.
:param rel_path: relative path in the svn repo to query the
properties from
:returns: a dictionary with the property name as key and the cont... | Return a dictionary with all svn-properties associated with a
relative path.
:param rel_path: relative path in the svn repo to query the
properties from
:returns: a dictionary with the property name as key and the content
as value |
def contents(self):
"""The raw file contents as a string."""
if not self._contents:
if self._path:
# Read file into memory so we don't run out of file descriptors
f = open(self._path, "rb")
self._contents = f.read()
f.close()
... | The raw file contents as a string. |
def collect_iptable(self, tablename):
""" When running the iptables command, it unfortunately auto-loads
the modules before trying to get output. Some people explicitly
don't want this, so check if the modules are loaded before running
the command. If they aren't loaded, there can't po... | When running the iptables command, it unfortunately auto-loads
the modules before trying to get output. Some people explicitly
don't want this, so check if the modules are loaded before running
the command. If they aren't loaded, there can't possibly be any
relevant rules in that table |
def run_script(module_name):
'''Take script input (from script_input above), run the run() function, and
render the results in the appropriate template'''
filename = ''
file_stream = ''
if len(request.files) > 0:
# Get the name of the uploaded file
f = request.files['file_upload']
... | Take script input (from script_input above), run the run() function, and
render the results in the appropriate template |
def get_slab_stats(self):
"""Retrieve slab stats from memcached."""
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((self.host, self.port))
s.send("stats slabs\n")
try:
data = ""
while True:
data += s.recv(4096)
... | Retrieve slab stats from memcached. |
def WhatMustIUnderstand(self):
'''Return a list of (uri,localname) tuples for all elements in the
header that have mustUnderstand set.
'''
return [ ( E.namespaceURI, E.localName )
for E in self.header_elements if _find_mu(E) == "1" ] | Return a list of (uri,localname) tuples for all elements in the
header that have mustUnderstand set. |
def _filter_namespaces_by_route_whitelist(self):
"""
Given a parsed API in IR form, filter the user-defined datatypes
so that they include only the route datatypes and their direct dependencies.
"""
assert self._routes is not None, "Missing route whitelist"
assert 'route_... | Given a parsed API in IR form, filter the user-defined datatypes
so that they include only the route datatypes and their direct dependencies. |
def has_perf_results(self):
'''
Figure out if any submission for this assignment has performance data being available.
'''
num_results = SubmissionTestResult.objects.filter(perf_data__isnull=False).filter(submission_file__submissions__assignment=self).count()
return num_resul... | Figure out if any submission for this assignment has performance data being available. |
def display_dialog(self, *args, **kwargs):
"""Display form and success message when set"""
form = kwargs.pop('form_instance', None)
success_message = kwargs.pop('success_message', None)
if not form:
form = self.get_form_class()(initial=kwargs, instance=self.object)
... | Display form and success message when set |
def set_row_stretch(self, row=0, stretch=10):
"""
Sets the row stretch. Larger numbers mean it will expand more to fill
space.
"""
self._layout.setRowStretch(row, stretch)
return self | Sets the row stretch. Larger numbers mean it will expand more to fill
space. |
def genHidden(self,nHidden=10,vTot=0.5,vCommon=0.1):
""" generate """
vSpecific = vTot-vCommon
# generate hidden
X = self.genWeights(self.N,nHidden)
# common effect
H = self.genWeights(nHidden,self.P)
Bc = SP.dot(H,self.genTraitEffect())
Yc = SP.dot(X... | generate |
def get_likelihood(self, uni_matrix):
"""Compute likelihood of the tree given an U matrix.
Args:
uni_matrix(numpy.array): univariate matrix to evaluate likelihood on.
Returns:
tuple[float, numpy.array]:
likelihood of the current tree, next level conditio... | Compute likelihood of the tree given an U matrix.
Args:
uni_matrix(numpy.array): univariate matrix to evaluate likelihood on.
Returns:
tuple[float, numpy.array]:
likelihood of the current tree, next level conditional univariate matrix |
def render(n_frames=1, axis=np.array([0.,0.,1.]), clf=True, **kwargs):
"""Render frames from the viewer.
Parameters
----------
n_frames : int
Number of frames to render. If more than one, the scene will animate.
axis : (3,) float or None
If present, the a... | Render frames from the viewer.
Parameters
----------
n_frames : int
Number of frames to render. If more than one, the scene will animate.
axis : (3,) float or None
If present, the animation will rotate about the given axis in world coordinates.
Otherw... |
def parse_config(path):
"""parse either the config file we found, or use some canned defaults"""
config = configparser.ConfigParser()
if path: # if user has config with user creds in it, this will grab it
config.read(path)
try:
return {k: v for k, v in config["... | parse either the config file we found, or use some canned defaults |
def user_remove(self, domain, userid):
"""
Remove a user
:param AuthDomain domain: The authentication domain for the user.
:param userid: The user ID to remove
:raise: :exc:`couchbase.exceptions.HTTPError` if the user does not exist.
:return: :class:`~.HttpResult`
... | Remove a user
:param AuthDomain domain: The authentication domain for the user.
:param userid: The user ID to remove
:raise: :exc:`couchbase.exceptions.HTTPError` if the user does not exist.
:return: :class:`~.HttpResult` |
def add_gate_option_group(parser):
"""Adds the options needed to apply gates to data.
Parameters
----------
parser : object
ArgumentParser instance.
"""
gate_group = parser.add_argument_group("Options for gating data.")
gate_group.add_argument("--gate", nargs="+", type=str,
... | Adds the options needed to apply gates to data.
Parameters
----------
parser : object
ArgumentParser instance. |
def _is_in_try_again(self, x, y):
"""Checks if the game is to be restarted."""
if self.won == 1:
# Checks if in try button on won screen.
x1, y1, x2, y2 = self._won_try_again
return x1 <= x < x2 and y1 <= y < y2
elif self.lost:
# Checks if in try b... | Checks if the game is to be restarted. |
def _ReadString(
self, file_object, file_offset, data_type_map, description):
"""Reads a string.
Args:
file_object (FileIO): file-like object.
file_offset (int): offset of the data relative from the start of
the file-like object.
data_type_map (dtfabric.DataTypeMap): data type... | Reads a string.
Args:
file_object (FileIO): file-like object.
file_offset (int): offset of the data relative from the start of
the file-like object.
data_type_map (dtfabric.DataTypeMap): data type map of the string.
description (str): description of the string.
Returns:
... |
def routingAreaUpdateAccept(PTmsiSignature_presence=0,
MobileId_presence=0, MobileId_presence1=0,
ReceiveNpduNumbersList_presence=0,
GprsTimer_presence=0, GmmCause_presence=0):
"""ROUTING AREA UPDATE ACCEPT Section 9.4.15"""
a =... | ROUTING AREA UPDATE ACCEPT Section 9.4.15 |
def set_chat_photo(self, *args, **kwargs):
"""See :func:`set_chat_photo`"""
return set_chat_photo(*args, **self._merge_overrides(**kwargs)).run() | See :func:`set_chat_photo` |
async def publish(self, message):
"""Push a new message to the client. The data will be
available as a JSON object with the key ``data``.
"""
try:
self.write_message(dict(data=message))
except WebSocketClosedError:
self._close() | Push a new message to the client. The data will be
available as a JSON object with the key ``data``. |
def get(self, request, bot_id, id, format=None):
"""
Get hook by id
---
serializer: HookSerializer
responseMessages:
- code: 401
message: Not authenticated
"""
return super(HookDetail, self).get(request, bot_id, id, format) | Get hook by id
---
serializer: HookSerializer
responseMessages:
- code: 401
message: Not authenticated |
def taskotron_task_particular_or_changed_outcome(config, message,
outcome='FAILED,NEEDS_INSPECTION'):
""" Taskotron task any particular or changed outcome(s)
With this rule, you can limit messages to only those task results
with any particular outcome(s) (FA... | Taskotron task any particular or changed outcome(s)
With this rule, you can limit messages to only those task results
with any particular outcome(s) (FAILED and NEEDS_INSPECTION by default)
or those with changed outcomes. This rule is a handy way of filtering
a very useful use case - being notified whe... |
def _GetDayOfYear(self, year, month, day_of_month):
"""Retrieves the day of the year for a specific day of a month in a year.
Args:
year (int): year e.g. 1970.
month (int): month, where 1 represents January.
day_of_month (int): day of the month, where 1 represents the first day.
Returns:... | Retrieves the day of the year for a specific day of a month in a year.
Args:
year (int): year e.g. 1970.
month (int): month, where 1 represents January.
day_of_month (int): day of the month, where 1 represents the first day.
Returns:
int: day of year.
Raises:
ValueError: if ... |
def check_compatibility(datasets, reqd_num_features=None):
"""
Checks whether the given MLdataset instances are compatible
i.e. with same set of subjects, each beloning to the same class in all instances.
Checks the first dataset in the list against the rest, and returns a boolean array.
Paramete... | Checks whether the given MLdataset instances are compatible
i.e. with same set of subjects, each beloning to the same class in all instances.
Checks the first dataset in the list against the rest, and returns a boolean array.
Parameters
----------
datasets : Iterable
A list of n datasets
... |
def disable_branching_model(self, project, repository):
"""
Disable branching model
:param project:
:param repository:
:return:
"""
url = 'rest/branch-utils/1.0/projects/{project}/repos/{repository}/branchmodel/configuration'.format(
project=project,
... | Disable branching model
:param project:
:param repository:
:return: |
def sync_headers(cloud_obj, headers=None, header_patterns=HEADER_PATTERNS):
"""
Overwrites the given cloud_obj's headers with the ones given as ``headers`
and adds additional headers as defined in the HEADERS setting depending on
the cloud_obj's file name.
"""
if headers is None:
headers... | Overwrites the given cloud_obj's headers with the ones given as ``headers`
and adds additional headers as defined in the HEADERS setting depending on
the cloud_obj's file name. |
def get_value(self, default=None):
"""Get selection from widget.
Parameters
----------
default : str
str for use by widget
Returns
-------
str
selected item from the combobox
"""
if default is None:
default = ... | Get selection from widget.
Parameters
----------
default : str
str for use by widget
Returns
-------
str
selected item from the combobox |
def update(self, pk, data, **kwargs):
"""
Updates the object by primary_key:
.. code-block:: python
DBSession.sacrud(Users).update(1, {'name': 'Petya'})
DBSession.sacrud(Users).update('1', {'name': 'Petya'})
DBSession.sacrud(User2Groups).update({'user_id': 4... | Updates the object by primary_key:
.. code-block:: python
DBSession.sacrud(Users).update(1, {'name': 'Petya'})
DBSession.sacrud(Users).update('1', {'name': 'Petya'})
DBSession.sacrud(User2Groups).update({'user_id': 4, 'group_id': 2},
... |
def patched_web3_eth_estimate_gas(self, transaction, block_identifier=None):
""" Temporary workaround until next web3.py release (5.X.X)
Current master of web3.py has this implementation already:
https://github.com/ethereum/web3.py/blob/2a67ea9f0ab40bb80af2b803dce742d6cad5943e/web3/eth.py#L311
"""
... | Temporary workaround until next web3.py release (5.X.X)
Current master of web3.py has this implementation already:
https://github.com/ethereum/web3.py/blob/2a67ea9f0ab40bb80af2b803dce742d6cad5943e/web3/eth.py#L311 |
def system_supports_plotting():
"""
Check if x server is running
Returns
-------
system_supports_plotting : bool
True when on Linux and running an xserver. Returns None when
on a non-linux platform.
"""
try:
if os.environ['ALLOW_PLOTTING'].lower() == 'true':
... | Check if x server is running
Returns
-------
system_supports_plotting : bool
True when on Linux and running an xserver. Returns None when
on a non-linux platform. |
def render_template(self, template_parameters, template_id):
"""RenderTemplate.
[Preview API]
:param :class:`<TemplateParameters> <azure.devops.v5_1.cix.models.TemplateParameters>` template_parameters:
:param str template_id:
:rtype: :class:`<Template> <azure.devops.v5_1.cix.mode... | RenderTemplate.
[Preview API]
:param :class:`<TemplateParameters> <azure.devops.v5_1.cix.models.TemplateParameters>` template_parameters:
:param str template_id:
:rtype: :class:`<Template> <azure.devops.v5_1.cix.models.Template>` |
def cublasDsyr2(handle, uplo, n, alpha, x, incx, y, incy, A, lda):
"""
Rank-2 operation on real symmetric matrix.
"""
status = _libcublas.cublasDsyr2_v2(handle,
_CUBLAS_FILL_MODE[uplo], n,
ctypes.byref(ctypes.c_double(alph... | Rank-2 operation on real symmetric matrix. |
def pathencode (path):
"""Encode a path string with the platform file system encoding."""
if isinstance(path, unicode) and not os.path.supports_unicode_filenames:
path = path.encode(FSCODING, "replace")
return path | Encode a path string with the platform file system encoding. |
def get_identity(self, subject_id, entities=None):
""" Get all the identity information that has been received and
are still valid about the subject.
:param subject_id: The identifier of the subject
:param entities: The identifiers of the entities whoes assertions are
intere... | Get all the identity information that has been received and
are still valid about the subject.
:param subject_id: The identifier of the subject
:param entities: The identifiers of the entities whoes assertions are
interesting. If the list is empty all entities are interesting.
... |
def reload_all_manifests(self):
"""
Reloads all loaded manifests, and loads any new manifests
"""
self._logger.debug("Reloading all manifests.")
self._manifests = []
self.load_manifests()
self._logger.debug("All manifests reloaded.") | Reloads all loaded manifests, and loads any new manifests |
def overlay_gateway_site_bfd_params_bfd_shutdown(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
overlay_gateway = ET.SubElement(config, "overlay-gateway", xmlns="urn:brocade.com:mgmt:brocade-tunnels")
name_key = ET.SubElement(overlay_gateway, "name")
... | Auto Generated Code |
def dumpBlock(self, block_name):
"""
API the list all information related with the block_name
:param block_name: Name of block to be dumped (Required)
:type block_name: str
"""
try:
return self.dbsBlock.dumpBlock(block_name)
except HTTPError as he:
... | API the list all information related with the block_name
:param block_name: Name of block to be dumped (Required)
:type block_name: str |
def locationUpdatingAccept(MobileId_presence=0,
FollowOnProceed_presence=0,
CtsPermission_presence=0):
"""LOCATION UPDATING ACCEPT Section 9.2.13"""
a = TpPd(pd=0x5)
b = MessageType(mesType=0x02) # 00000010
c = LocalAreaId()
packet = a / b / c
... | LOCATION UPDATING ACCEPT Section 9.2.13 |
def contains(self, key):
'''Returns whether the object named by `key` exists.
LoggingDatastore logs the access.
'''
self.logger.info('%s: contains %s' % (self, key))
return super(LoggingDatastore, self).contains(key) | Returns whether the object named by `key` exists.
LoggingDatastore logs the access. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.