Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
3,800 | def GetChildrenByPriority(self, allow_external=True):
for child in sorted(self.OpenChildren(), key=lambda x: x.PRIORITY):
if not allow_external and child.EXTERNAL:
continue
if child.Get(child.Schema.ACTIVE):
yield child | Generator that yields active filestore children in priority order. |
3,801 | def freeze_parameter(self, name):
i = self.get_parameter_names(include_frozen=True).index(name)
self.unfrozen_mask[i] = False | Freeze a parameter by name
Args:
name: The name of the parameter |
3,802 | def add_row(self, id_):
row = self._parser.new_row(id_)
self._rows.append(row)
return row | Add a new row to the pattern.
:param id_: the id of the row |
3,803 | def boundary_maximum_linear(graph, xxx_todo_changeme1):
r
(gradient_image, spacing) = xxx_todo_changeme1
gradient_image = scipy.asarray(gradient_image)
max_intensity = float(numpy.abs(gradient_image).max())
def boundary_term_linear(intensities):
intensities /... | r"""
Boundary term processing adjacent voxels maximum value using a linear relationship.
An implementation of a boundary term, suitable to be used with the
`~medpy.graphcut.generate.graph_from_voxels` function.
The same as `boundary_difference_linear`, but working on the gradient image instea... |
3,804 | def namedb_get_name_from_name_hash128( cur, name_hash128, block_number ):
unexpired_query, unexpired_args = namedb_select_where_unexpired_names( block_number )
select_query = "SELECT name FROM name_records JOIN namespaces ON name_records.namespace_id = namespaces.namespace_id " + \
"WH... | Given the hexlified 128-bit hash of a name, get the name. |
3,805 | def append_value_continuation(self, linenum, indent, continuation):
frame = self.current_frame()
assert isinstance(frame,FieldFrame) or isinstance(frame,ValueContinuationFrame)
if isinstance(frame, FieldFrame):
assert frame.indent < indent and frame.container.contains(ROOT_P... | :param linenum: The line number of the frame.
:type linenum: int
:param indent: The indentation level of the frame.
:type indent: int
:param continuation:
:type continuation: str |
3,806 | def _distance(self):
return np.average(self.min_kl, weights=self.f.weights) | Compute the distance function d(f,g,\pi), Eq. (3) |
3,807 | def match(self, node, results=None):
if not isinstance(node, Leaf):
return False
return BasePattern.match(self, node, results) | Override match() to insist on a leaf node. |
3,808 | def get_download_url(self, instance, default=None):
download = default
download = "{url}/@@download/{fieldname}/{filename}".format(
url=api.get_url(instance),
fieldname=self.get_field_name(),
filename=self.get_filename(instance),
)
re... | Calculate the download url |
3,809 | def fromMimeData(self, data):
if data.hasText():
self.insert(data.text())
return (QtCore.QByteArray(), False) | Paste the clipboard data at the current cursor position.
This method also adds another undo-object to the undo-stack.
..note: This method forcefully interrupts the ``QsciInternal``
pasting mechnism by returning an empty MIME data element.
This is not an elegant implemen... |
3,810 | def heartbeat(self):
unique_id = self.new_unique_id()
message = {
: ,
: unique_id,
}
self._send(message)
return unique_id | Heartbeat request to keep session alive. |
3,811 | def space_acl(args):
r = fapi.get_workspace_acl(args.project, args.workspace)
fapi._check_response_code(r, 200)
result = dict()
for user, info in sorted(r.json()[].items()):
result[user] = info[]
return result | Retrieve access control list for a workspace |
3,812 | def ruamelindex(self, strictindex):
return (
self.key_association.get(strictindex, strictindex)
if self.is_mapping()
else strictindex
) | Get the ruamel equivalent of a strict parsed index.
E.g. 0 -> 0, 1 -> 2, parsed-via-slugify -> Parsed via slugify |
3,813 | def send_packet(self, pk, expected_reply=(), resend=False, timeout=0.2):
self._send_lock.acquire()
if self.link is not None:
if len(expected_reply) > 0 and not resend and \
self.link.needs_resending:
pattern = (pk.header,) + expected_reply
... | Send a packet through the link interface.
pk -- Packet to send
expect_answer -- True if a packet from the Crazyflie is expected to
be sent back, otherwise false |
3,814 | def _maybeCleanSessions(self):
sinceLast = self._clock.seconds() - self._lastClean
if sinceLast > self.sessionCleanFrequency:
self._cleanSessions() | Clean expired sessions if it's been long enough since the last clean. |
3,815 | def _get_best_effort_ndims(x,
expect_ndims=None,
expect_ndims_at_least=None,
expect_ndims_no_more_than=None):
ndims_static = _get_static_ndims(
x,
expect_ndims=expect_ndims,
expect_ndims_at_least=expect_ndims_at_leas... | Get static ndims if possible. Fallback on `tf.rank(x)`. |
3,816 | def total_members_in_score_range_in(
self, leaderboard_name, min_score, max_score):
return self.redis_connection.zcount(
leaderboard_name, min_score, max_score) | Retrieve the total members in a given score range from the named leaderboard.
@param leaderboard_name Name of the leaderboard.
@param min_score [float] Minimum score.
@param max_score [float] Maximum score.
@return the total members in a given score range from the named leaderboard. |
3,817 | def delayed_redraw(self):
with self._defer_lock:
whence = self._defer_whence
self._defer_whence = self._defer_whence_reset
flag = self._defer_flag
self._defer_flag = False
if flag:
self.redraw_now(w... | Handle delayed redrawing of the canvas. |
3,818 | def apply_transform(self, matrix):
matrix = np.asanyarray(matrix,
order=,
dtype=np.float64)
if matrix.shape != (4, 4):
raise ValueError()
self.face_normals = new_face_normals
s... | Transform mesh by a homogenous transformation matrix.
Does the bookkeeping to avoid recomputing things so this function
should be used rather than directly modifying self.vertices
if possible.
Parameters
----------
matrix : (4, 4) float
Homogenous transformati... |
3,819 | def update_browsers(self, *args, **kwargs):
sel = self.prjbrws.selected_indexes(0)
if not sel:
return
prjindex = sel[0]
if not prjindex.isValid():
prj = None
else:
prjitem = prjindex.internalPointer()
prj = prjitem.internal... | Update the shot and the assetbrowsers
:returns: None
:rtype: None
:raises: None |
3,820 | def train(self):
start = time.time()
result = self._train()
assert isinstance(result, dict), "_train() needs to return a dict."
if RESULT_DUPLICATE in result:
return result
result = result.copy()
self._iteration += 1
self._iterati... | Runs one logical iteration of training.
Subclasses should override ``_train()`` instead to return results.
This class automatically fills the following fields in the result:
`done` (bool): training is terminated. Filled only if not provided.
`time_this_iter_s` (float): Time in... |
3,821 | def get_language(query: str) -> str:
query = query.lower()
for language in LANGUAGES:
if query.endswith(language):
return language
return | Tries to work out the highlight.js language of a given file name or
shebang. Returns an empty string if none match. |
3,822 | def setCheckedRecords(self, records, column=0, parent=None):
if parent is None:
for i in range(self.topLevelItemCount()):
item = self.topLevelItem(i)
try:
has_record = item.record() in records
except AttributeError:
... | Sets the checked items based on the inputed list of records.
:param records | [<orb.Table>, ..]
parent | <QTreeWidgetItem> || None |
3,823 | def save(self, request):
comment = self.get_comment_object()
obj = comment.content_object
if request.user.is_authenticated():
comment.user = request.user
comment.by_author = request.user == getattr(obj, "user", None)
comment.ip_address = ip_for_request(reques... | Saves a new comment and sends any notification emails. |
3,824 | def publish(self, message):
message_data = self._to_data(message)
self._encode_invoke(topic_publish_codec, message=message_data) | Publishes the message to all subscribers of this topic
:param message: (object), the message to be published. |
3,825 | def _set_alert(self, v, load=False):
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=alert.alert, is_container=, presence=False, yang_name="alert", rest_name="alert", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={... | Setter method for alert, mapped from YANG variable /rbridge_id/threshold_monitor/interface/policy/area/alert (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_alert is considered as a private
method. Backends looking to populate this variable should
do so via c... |
3,826 | def is_pure_name(path):
return (
not os.path.isabs(path)
and len(os.path.dirname(path)) == 0
and not os.path.splitext(path)[1]
and path !=
and path !=
) | Return True if path is a name and not a file path.
Parameters
----------
path : str
Path (can be absolute, relative, etc.)
Returns
-------
bool
True if path is a name of config in config dir, not file path. |
3,827 | def _flatten_lane_details(runinfo):
out = []
for ldetail in runinfo["details"]:
if "project_name" not in ldetail and ldetail["description"] == "control":
ldetail["project_name"] = "control"
for i, barcode in enumerate(ldetail.get("multiplex", [{}])):
cur = c... | Provide flattened lane information with multiplexed barcodes separated. |
3,828 | def dbg(*objects, file=sys.stderr, flush=True, **kwargs):
"Helper function to print to stderr and flush"
print(*objects, file=file, flush=flush, **kwargs) | Helper function to print to stderr and flush |
3,829 | def GetOrderKey(self):
context_attributes = []
context_attributes.extend(ExceptionWithContext.CONTEXT_PARTS)
context_attributes.extend(self._GetExtraOrderAttributes())
tokens = []
for context_attribute in context_attributes:
tokens.append(getattr(self, context_attribute, None))
retur... | Return a tuple that can be used to sort problems into a consistent order.
Returns:
A list of values. |
3,830 | def get_option(self, option):
value = getattr(self, option, None)
if value is not None:
return value
return getattr(settings, "COUNTRIES_{0}".format(option.upper())) | Get a configuration option, trying the options attribute first and
falling back to a Django project setting. |
3,831 | def swd_write(self, output, value, nbits):
pDir = binpacker.pack(output, nbits)
pIn = binpacker.pack(value, nbits)
bitpos = self._dll.JLINK_SWD_StoreRaw(pDir, pIn, nbits)
if bitpos < 0:
raise errors.JLinkException(bitpos)
return bitpos | Writes bytes over SWD (Serial Wire Debug).
Args:
self (JLink): the ``JLink`` instance
output (int): the output buffer offset to write to
value (int): the value to write to the output buffer
nbits (int): the number of bits needed to represent the ``output`` and
... |
3,832 | def operations(self, op_types=None):
if not op_types:
op_types = [, , , , ]
while self._handle.tell() < self._eof:
current_time = mgz.util.convert_to_timestamp(self._time / 1000)
try:
operation = mgz.body.operation.parse_stream(self._handle)
... | Process operation stream. |
3,833 | def top(num_processes=5, interval=3):
**
result = []
start_usage = {}
for pid in psutil.pids():
try:
process = psutil.Process(pid)
user, system = process.cpu_times()
except ValueError:
user, system, _, _ = process.cpu_times()
except psutil.NoSu... | Return a list of top CPU consuming processes during the interval.
num_processes = return the top N CPU consuming processes
interval = the number of seconds to sample CPU usage over
CLI Examples:
.. code-block:: bash
salt '*' ps.top
salt '*' ps.top 5 10 |
3,834 | def check_columns(self, check_views=True):
if check_views:
query = .format(self.exclude_schema)
else:
query = .format(self.exclude_schema)
return self.__check_equals(query) | Check if the columns in all tables are equals.
Parameters
----------
check_views: bool
if True, check the columns of all the tables and views, if
False check only the columns of the tables
Returns
-------
bool
... |
3,835 | def _parse_bands(self, band_input):
all_bands = AwsConstants.S2_L1C_BANDS if self.data_source is DataSource.SENTINEL2_L1C else \
AwsConstants.S2_L2A_BANDS
if band_input is None:
return all_bands
if isinstance(band_input, str):
band_list = band_input.... | Parses class input and verifies band names.
:param band_input: input parameter `bands`
:type band_input: str or list(str) or None
:return: verified list of bands
:rtype: list(str) |
3,836 | def tril(array, k=0):
try:
tril_array = np.tril(array, k=k)
except:
tril_array = np.zeros_like(array)
shape = array.shape
otherdims = shape[:-2]
for index in np.ndindex(otherdims):
tril_array[index] = np.tril(array[index], k=k)
return tril_ar... | Lower triangle of an array.
Return a copy of an array with elements above the k-th diagonal zeroed.
Need a multi-dimensional version here because numpy.tril does not
broadcast for numpy verison < 1.9. |
3,837 | def encrypt(self, wif):
if not self.unlocked():
raise WalletLocked
return format(bip38.encrypt(str(wif), self.masterkey), "encwif") | Encrypt the content according to BIP38
:param str wif: Unencrypted key |
3,838 | def find_requirement(self, req, upgrade, ignore_compatibility=False):
all_candidates = self.find_all_candidates(req.name)
[str(c.version) for c in all_candidates],
prereleases=(
self.allow_all_prere... | Try to find a Link matching req
Expects req, an InstallRequirement and upgrade, a boolean
Returns a Link if found,
Raises DistributionNotFound or BestVersionAlreadyInstalled otherwise |
3,839 | def select_edges_by(docgraph, layer=None, edge_type=None, data=False):
edge_type_eval = "edge_attribs[] == ".format(edge_type)
layer_eval = " in edge_attribs[]".format(layer)
if layer is not None:
if edge_type is not None:
return select_edges(docgraph, data=data,
... | get all edges with the given edge type and layer.
Parameters
----------
docgraph : DiscourseDocumentGraph
document graph from which the nodes will be extracted
layer : str
name of the layer
edge_type : str
Type of the edges to be extracted (Edge types are defined in the
... |
3,840 | def create_nginx_config(self):
cfg = .format(self._project_name)
if not self._shared_hosting:
if self._user:
cfg += .format(self._user)
cfg += .format(os.path.join(self._log_dir, \
self._project_name), os.path.joi... | Creates the Nginx configuration for the project |
3,841 | def __update_offset_table(self, fileobj, fmt, atom, delta, offset):
if atom.offset > offset:
atom.offset += delta
fileobj.seek(atom.offset + 12)
data = fileobj.read(atom.length - 12)
fmt = fmt % cdata.uint_be(data[:4])
offsets = struct.unpack(fmt, data[4:])
... | Update offset table in the specified atom. |
3,842 | def on_left_click(self, event, grid, choices):
row, col = event.GetRow(), event.GetCol()
if col == 0 and self.grid.name != :
default_val = self.grid.GetCellValue(row, col)
msg = "Choose a new name for {}.\nThe new value will propagate throughout the contribution.".format... | creates popup menu when user clicks on the column
if that column is in the list of choices that get a drop-down menu.
allows user to edit the column, but only from available values |
3,843 | def set_insn(self, insn):
self.insn = insn
self.size = len(self.insn) | Set a new raw buffer to disassemble
:param insn: the buffer
:type insn: string |
3,844 | def get_referenced_object(self):
if self._BunqMeTab is not None:
return self._BunqMeTab
if self._BunqMeTabResultResponse is not None:
return self._BunqMeTabResultResponse
if self._BunqMeFundraiserResult is not None:
return self._BunqMeFundraiserRes... | :rtype: core.BunqModel
:raise: BunqException |
3,845 | def _docstring_parse(self, blocks):
result = {}
for block, docline, doclength, key in blocks:
doctext = "<doc>{}</doc>".format(" ".join(block))
try:
docs = ET.XML(doctext)
docstart = self.parser.charindex(docline, 0, self.context)
... | Parses the XML from the specified blocks of docstrings. |
3,846 | def calls(self):
return WebhookWebhooksCallProxy(self._client, self.sys[].id, self.sys[]) | Provides access to call overview for the given webhook.
API reference: https://www.contentful.com/developers/docs/references/content-management-api/#/reference/webhook-calls
:return: :class:`WebhookWebhooksCallProxy <contentful_management.webhook_webhooks_call_proxy.WebhookWebhooksCallProxy>` object.
... |
3,847 | def write(self, data):
report_size = self.packet_size
if self.ep_out:
report_size = self.ep_out.wMaxPacketSize
for _ in range(report_size - len(data)):
data.append(0)
self.read_sem.release()
if not self.ep_out:
bmRequestType = 0x21... | write data on the OUT endpoint associated to the HID interface |
3,848 | def parse(file_or_string):
from mysqlparse.grammar.sql_file import sql_file_syntax
if hasattr(file_or_string, ) and hasattr(file_or_string.read, ):
return sql_file_syntax.parseString(file_or_string.read())
elif isinstance(file_or_string, six.string_types):
return sql_file_syntax.parseS... | Parse a file-like object or string.
Args:
file_or_string (file, str): File-like object or string.
Returns:
ParseResults: instance of pyparsing parse results. |
3,849 | def get_clean_url(self):
if self.needs_auth:
self.prompt_auth()
url = RepositoryURL(self.url.full_url)
url.username = self.username
url.password = self.password
return url | Retrieve the clean, full URL - including username/password. |
3,850 | def make_action_list(self, item_list, **kwargs):
action_list = []
es_index = get2(kwargs, "es_index", self.es_index)
action_type = kwargs.get("action_type","index")
action_settings = {: action_type,
: es_index}
doc_type = kwargs.get("d... | Generates a list of actions for sending to Elasticsearch |
3,851 | def predict_subsequences(self, sequence_dict, peptide_lengths=None):
sequence_dict = check_sequence_dictionary(sequence_dict)
peptide_lengths = self._check_peptide_lengths(peptide_lengths)
binding_predictions = []
expected_peptides = set([])
normalize... | Given a dictionary mapping unique keys to amino acid sequences,
run MHC binding predictions on all candidate epitopes extracted from
sequences and return a EpitopeCollection.
Parameters
----------
fasta_dictionary : dict or string
Mapping of protein identifiers to pr... |
3,852 | def _glslify(r):
if isinstance(r, string_types):
return r
else:
assert 2 <= len(r) <= 4
return .format(len(r), .join(map(str, r))) | Transform a string or a n-tuple to a valid GLSL expression. |
3,853 | def getFilenameSet(self):
result = set(self.file_dict)
result.discard(inspect.currentframe().f_code.co_filename)
return result | Returns a set of profiled file names.
Note: "file name" is used loosely here. See python documentation for
co_filename, linecache module and PEP302. It may not be a valid
filesystem path. |
3,854 | def print_list(extracted_list, file=None):
if file is None:
file = sys.stderr
for filename, lineno, name, line in extracted_list:
_print(file,
% (filename,lineno,name))
if line:
_print(file, % line.strip()) | Print the list of tuples as returned by extract_tb() or
extract_stack() as a formatted stack trace to the given file. |
3,855 | def flows(args):
def flow_if_not(fun):
if isinstance(fun, iterator):
return fun
elif isinstance(fun, type) and in str(fun.__class__):
return fun
else:
try:
return flow(fun)
except AttributeError:
... | todo : add some example
:param args:
:return: |
3,856 | def find_copies(input_dir, exclude_list):
copies = []
def copy_finder(copies, dirname):
for obj in os.listdir(dirname):
pathname = os.path.join(dirname, obj)
if os.path.isdir(pathname):
continue
if obj in exclude_list:
continue
... | find files that are not templates and not
in the exclude_list for copying from template to image |
3,857 | def user_topic_ids(user):
if user.is_super_admin() or user.is_read_only_user():
query = sql.select([models.TOPICS])
else:
query = (sql.select([models.JOINS_TOPICS_TEAMS.c.topic_id])
.select_from(
models.JOINS_TOPICS_TEAMS.join(
... | Retrieve the list of topics IDs a user has access to. |
3,858 | def solve_discrete_lyapunov(A, B, max_it=50, method="doubling"):
r
if method == "doubling":
A, B = list(map(np.atleast_2d, [A, B]))
alpha0 = A
gamma0 = B
diff = 5
n_its = 1
while diff > 1e-15:
alpha1 = alpha0.dot(alpha0)
gamma1 = gamma0 ... | r"""
Computes the solution to the discrete lyapunov equation
.. math::
AXA' - X + B = 0
:math:`X` is computed by using a doubling algorithm. In particular, we
iterate to convergence on :math:`X_j` with the following recursions for
:math:`j = 1, 2, \dots` starting from :math:`X_0 = B`, :ma... |
3,859 | def get_widget(self, request):
return self._update_widget_choices(self.field.formfield(widget=RestrictedSelectWidget).widget) | Field widget is replaced with "RestrictedSelectWidget" because we not want to use modified widgets for
filtering. |
3,860 | async def jsk_vc_join(self, ctx: commands.Context, *,
destination: typing.Union[discord.VoiceChannel, discord.Member] = None):
destination = destination or ctx.author
if isinstance(destination, discord.Member):
if destination.voice and destination.voice.c... | Joins a voice channel, or moves to it if already connected.
Passing a voice channel uses that voice channel.
Passing a member will use that member's current voice channel.
Passing nothing will use the author's voice channel. |
3,861 | def add_edge(self, fr, to):
fr = self.add_vertex(fr)
to = self.add_vertex(to)
self.adjacency[fr].children.add(to)
self.adjacency[to].parents.add(fr) | Add an edge to the graph. Multiple edges between the same vertices will quietly be ignored. N-partite graphs
can be used to permit multiple edges by partitioning the graph into vertices and edges.
:param fr: The name of the origin vertex.
:param to: The name of the destination vertex.
:... |
3,862 | def build_idx_set(branch_id, start_date):
code_set = branch_id.split("/")
code_set.insert(3, "Rates")
idx_set = {
"sec": "/".join([code_set[0], code_set[1], "Sections"]),
"mag": "/".join([code_set[0], code_set[1], code_set[2], "Magnitude"])}
idx_set["rate"] = "/".join(code_set)
... | Builds a dictionary of keys based on the branch code |
3,863 | def parse(self, valstr):
if self._initialized:
raise pycdlibexception.PyCdlibInternalError()
(self.header_indicator, self.platform_id, self.num_section_entries,
self.id_string) = struct.unpack_from(self.FMT, valstr, 0)
self._initialized = True | Parse an El Torito section header from a string.
Parameters:
valstr - The string to parse.
Returns:
Nothing. |
3,864 | def close_files(self):
for name in self:
if getattr(self, % name):
file_ = getattr(self, % name)
file_.close() | Close all files with an activated disk flag. |
3,865 | def _update_counters(self, ti_status):
for key, ti in list(ti_status.running.items()):
ti.refresh_from_db()
if ti.state == State.SUCCESS:
ti_status.succeeded.add(key)
self.log.debug("Task instance %s succeeded. Dont rerun.", ti)
ti... | Updates the counters per state of the tasks that were running. Can re-add
to tasks to run in case required.
:param ti_status: the internal status of the backfill job tasks
:type ti_status: BackfillJob._DagRunTaskStatus |
3,866 | def to_bson_voronoi_list2(self):
bson_nb_voro_list2 = [None] * len(self.voronoi_list2)
for ivoro, voro in enumerate(self.voronoi_list2):
if voro is None or voro == :
continue
site_voro = []
f... | Transforms the voronoi_list into a vlist + bson_nb_voro_list, that are BSON-encodable.
:return: [vlist, bson_nb_voro_list], to be used in the as_dict method |
3,867 | def sync(self):
LOGGER.debug("Company.sync")
params = None
if self.id is not None:
params = {: self.id}
elif self.name is not None:
params = {: self.name}
if params is not None:
args = {: , : , : params}
response = Company... | synchronize self from Ariane server according its id (prioritary) or name
:return: |
3,868 | def to_language(locale):
p = locale.find()
if p >= 0:
return locale[:p].lower() + + locale[p + 1:].lower()
else:
return locale.lower() | Turns a locale name (en_US) into a language name (en-us).
Taken `from Django <http://bit.ly/1vWACbE>`_. |
3,869 | async def issueClaim(self, schemaId: ID, claimRequest: ClaimRequest,
iA=None,
i=None) -> (Claims, Dict[str, ClaimAttributeValues]):
schemaKey = (await self.wallet.getSchema(schemaId)).getKey()
attributes = self._attrRepo.getAttributes(schemaKey... | Issue a claim for the given user and schema.
:param schemaId: The schema ID (reference to claim
definition schema)
:param claimRequest: A claim request containing prover ID and
prover-generated values
:param iA: accumulator ID
:param i: claim's sequence number within acc... |
3,870 | def swallow_stdout(stream=None):
saved = sys.stdout
if stream is None:
stream = StringIO()
sys.stdout = stream
try:
yield
finally:
sys.stdout = saved | Divert stdout into the given stream
>>> string = StringIO()
>>> with swallow_stdout(string):
... print('hello')
>>> assert string.getvalue().rstrip() == 'hello' |
3,871 | def call_inputhook(self, input_is_ready_func):
self._input_is_ready = input_is_ready_func
def thread():
input_is_ready_func(wait=True)
os.write(self._w, b)
threading.Thread(target=thread).start()
self.inputhook(self)
... | Call the inputhook. (Called by a prompt-toolkit eventloop.) |
3,872 | def get_long_short_pos(positions):
pos_wo_cash = positions.drop(, axis=1)
longs = pos_wo_cash[pos_wo_cash > 0].sum(axis=1).fillna(0)
shorts = pos_wo_cash[pos_wo_cash < 0].sum(axis=1).fillna(0)
cash = positions.cash
net_liquidation = longs + shorts + cash
df_pos = pd.DataFrame({: longs.divi... | Determines the long and short allocations in a portfolio.
Parameters
----------
positions : pd.DataFrame
The positions that the strategy takes over time.
Returns
-------
df_long_short : pd.DataFrame
Long and short allocations as a decimal
percentage of the total net liq... |
3,873 | def _decorate_urlconf(urlpatterns, decorator=require_auth, *args, **kwargs):
if isinstance(urlpatterns, (list, tuple)):
for pattern in urlpatterns:
if getattr(pattern, , None):
pattern._callback = decorator(
pattern.callback, *args, **kwargs)
... | Decorate all urlpatterns by specified decorator |
3,874 | def parse_allele_name(name, species_prefix=None):
original = name
name = name.strip()
if len(name) == 0:
raise ValueError("Cant have allele families
return AlleleName("H-2", gene, "", allele_code)
if len(name) == 0:
raise AlleleParseError("Incomplete MHC allele name: %s" %... | Takes an allele name and splits it into four parts:
1) species prefix
2) gene name
3) allele family
4) allele code
If species_prefix is provided, that is used instead of getting the species prefix from the name.
(And in that case, a species prefix in the name will result in an e... |
3,875 | def create_replication_instance(ReplicationInstanceIdentifier=None, AllocatedStorage=None, ReplicationInstanceClass=None, VpcSecurityGroupIds=None, AvailabilityZone=None, ReplicationSubnetGroupIdentifier=None, PreferredMaintenanceWindow=None, MultiAZ=None, EngineVersion=None, AutoMinorVersionUpgrade=None, Tags=None, Km... | Creates the replication instance using the specified parameters.
See also: AWS API Documentation
:example: response = client.create_replication_instance(
ReplicationInstanceIdentifier='string',
AllocatedStorage=123,
ReplicationInstanceClass='string',
VpcSecurityGroupIds... |
3,876 | def main_loop(self, steps_per_epoch, starting_epoch, max_epoch):
with self.sess.as_default():
self.loop.config(steps_per_epoch, starting_epoch, max_epoch)
self.loop.update_global_step()
try:
self._callbacks.before_train()
... | Run the main training loop.
Args:
steps_per_epoch, starting_epoch, max_epoch (int): |
3,877 | def list_nodes(conn=None, call=None):
if call == :
raise SaltCloudSystemExit(
)
if not conn:
conn = get_conn()
nodes = conn.list_nodes()
ret = {}
for node in nodes:
ret[node.name] = {
: node.id,
: node.image,
... | Return a list of the VMs that are on the provider |
3,878 | def solution_violations(solution, events, slots):
array = converter.solution_to_array(solution, events, slots)
return array_violations(array, events, slots) | Take a solution and return a list of violated constraints
Parameters
----------
solution: list or tuple
a schedule in solution form
events : list or tuple
of resources.Event instances
slots : list or tuple
of resources.Slot instances
Returns
... |
3,879 | def get_args():
parser = argparse.ArgumentParser(description=)
parser.Add_argument(
, ,
required=True,
action=,
help=
)
parser.add_argument(
, ,
type=int,
default=443,
action=,
help=
)
parser.add_argument(
, ,
... | Parse CLI args |
3,880 | def _mirror_groups(self):
target_group_names = frozenset(self._get_groups().get_group_names())
current_group_names = frozenset(
self._user.groups.values_list("name", flat=True).iterator()
)
MIRROR_GROUPS_EXCEPT = self.settings.MIRROR_GROUPS_EXCEPT
M... | Mirrors the user's LDAP groups in the Django database and updates the
user's membership. |
3,881 | def query_item(self, key, abis):
try:
key = int(key)
field =
except ValueError:
try:
key = int(key, 16)
field =
except ValueError:
field =
arg = and_(getattr(Item, field) == key,
... | Query items based on system call number or name. |
3,882 | def _set_extensions(self):
self._critical_extensions = set()
for extension in self[]:
name = extension[].native
attribute_name = % name
if hasattr(self, attribute_name):
setattr(self, attribute_name, extension[].parsed)
if exten... | Sets common named extensions to private attributes and creates a list
of critical extensions |
3,883 | def touch_member(config, dcs):
p = Postgresql(config[])
p.set_state()
p.set_role()
def restapi_connection_string(config):
protocol = if config.get() else
connect_address = config.get()
listen = config[]
return .format(protocol, connect_address or listen)
data... | Rip-off of the ha.touch_member without inter-class dependencies |
3,884 | def _get_event_source_obj(awsclient, evt_source):
event_source_map = {
: event_source.dynamodb_stream.DynamoDBStreamEventSource,
: event_source.kinesis.KinesisEventSource,
: event_source.s3.S3EventSource,
: event_source.sns.SNSEventSource,
: event_source.cloudwatch.Cloud... | Given awsclient, event_source dictionary item
create an event_source object of the appropriate event type
to schedule this event, and return the object. |
3,885 | def run_analysis(self, argv):
args = self._parser.parse_args(argv)
obs = BinnedAnalysis.BinnedObs(irfs=args.irfs,
expCube=args.expcube,
srcMaps=args.srcmaps,
binnedExpMap=args.b... | Run this analysis |
3,886 | def naturalsortkey(s):
return [int(part) if part.isdigit() else part
for part in re.split(, s)] | Natural sort order |
3,887 | def view_surface_app_activity(self) -> str:
output, error = self._execute(
, self.device_sn, , , , )
return re.findall(r"name=([a-zA-Z0-9\.]+/.[a-zA-Z0-9\.]+)", output) | Get package with activity of applications that are running in the foreground. |
3,888 | def get(self, path):
path = path or
path = path.lstrip()
parts = path.split()
if not parts[0]:
parts = parts[1:]
statDict = util.lookup(scales.getStats(), parts)
if statDict is None:
self.set_status(404)
self.finish()
return
outputFormat = self.get_argument(,... | Renders a GET request, by showing this nodes stats and children. |
3,889 | def ip_allocate(self, public=False):
result = self._client.post(
"{}/ips".format(Instance.api_endpoint),
model=self,
data={
"type": "ipv4",
"public": public,
})
if not in result:
raise UnexpectedRespon... | Allocates a new :any:`IPAddress` for this Instance. Additional public
IPs require justification, and you may need to open a :any:`SupportTicket`
before you can add one. You may only have, at most, one private IP per
Instance.
:param public: If the new IP should be public or private. ... |
3,890 | def iterator_chain(variables: VarType, parent: str = None) -> Iterable[VarMatrix]:
logger.debug("Yielding from append iterator")
if not isinstance(variables, list):
raise ValueError(
f"Append keyword only takes a list of arguments, got {variables} of type {type(variables)}"
)
... | This successively appends each element of an array to a single list of values.
This takes a list of values and puts all the values generated for each element in
the list into a single list of values. It uses the :func:`itertools.chain` function to
achieve this. This function is particularly useful for spec... |
3,891 | def get_exe_path(cls):
return os.path.abspath(os.path.join(ROOT, cls.bmds_version_dir, cls.exe + ".exe")) | Return the full path to the executable. |
3,892 | def update_vm(vm_ref, vm_config_spec):
vm_name = get_managed_object_name(vm_ref)
log.trace(%s\, vm_name)
try:
task = vm_ref.ReconfigVM_Task(vm_config_spec)
except vim.fault.NoPermission as exc:
log.exception(exc)
raise salt.exceptions.VMwareApiError(
... | Updates the virtual machine configuration with the given object
vm_ref
Virtual machine managed object reference
vm_config_spec
Virtual machine config spec object to update |
3,893 | def get_subhash(hash):
idx = [0xe, 0x3, 0x6, 0x8, 0x2]
mul = [2, 2, 5, 4, 3]
add = [0, 0xd, 0x10, 0xb, 0x5]
b = []
for i in range(len(idx)):
a = add[i]
m = mul[i]
i = idx[i]
t = a + int(hash[i], 16)
v = int(hash[t:t + 2], 16)
b.append(( % (v * m)... | Get a second hash based on napiprojekt's hash.
:param str hash: napiprojekt's hash.
:return: the subhash.
:rtype: str |
3,894 | def _apply_policy_config(policy_spec, policy_dict):
log.trace(, policy_dict)
if policy_dict.get():
policy_spec.name = policy_dict[]
if policy_dict.get():
policy_spec.description = policy_dict[]
if policy_dict.get():
policy_spec.constraints = pbm.pr... | Applies a policy dictionary to a policy spec |
3,895 | def best_model(self):
if hasattr(self, ):
model = self._params[](
*self.parse_individual(self.halloffame[0]))
model.pack_new_sequences(self._params[])
return model
else:
raise NameError() | Rebuilds the top scoring model from an optimisation.
Returns
-------
model: AMPAL
Returns an AMPAL model of the top scoring parameters.
Raises
------
NameError:
Raises a name error if the optimiser has not been run. |
3,896 | def _calculate_values(self, tree, bar_d):
if all([
isinstance(tree, dict),
type(tree) != BarDescriptor
]):
max_val = 0
value = 0
for k in tree:
bar_desc = self._calculate_values(tree[k], ba... | Calculate values for drawing bars of non-leafs in ``tree``
Recurses through ``tree``, replaces ``dict``s with
``(BarDescriptor, dict)`` so ``ProgressTree._draw`` can use
the ``BarDescriptor``s to draw the tree |
3,897 | def can_handle(self, data):
r
try:
requestline, _ = decode_from_bytes(data).split(CRLF, 1)
method, path, version = self._parse_requestline(requestline)
except ValueError:
try:
return self == Mocket._last_entry
except AttributeError:... | r"""
>>> e = Entry('http://www.github.com/?bar=foo&foobar', Entry.GET, (Response(b'<html/>'),))
>>> e.can_handle(b'GET /?bar=foo HTTP/1.1\r\nHost: github.com\r\nAccept-Encoding: gzip, deflate\r\nConnection: keep-alive\r\nUser-Agent: python-requests/2.7.0 CPython/3.4.3 Linux/3.19.0-16-generic\r\nAccept: ... |
3,898 | def fade(self, fade_in_len=0.0, fade_out_len=0.0, fade_shape=):
qqhtlp
fade_shapes = [, , , , ]
if fade_shape not in fade_shapes:
raise ValueError(
"Fade shape must be one of {}".format(" ".join(fade_shapes))
)
if not is_number(fade_in_len) or fade... | Add a fade in and/or fade out to an audio file.
Default fade shape is 1/4 sine wave.
Parameters
----------
fade_in_len : float, default=0.0
Length of fade-in (seconds). If fade_in_len = 0,
no fade in is applied.
fade_out_len : float, defaut=0.0
... |
3,899 | def get_align(text):
"Return (halign, valign, angle) of the <text>."
(x1, x2, h, v, a) = unaligned_get_dimension(text)
return (h, v, a) | Return (halign, valign, angle) of the <text>. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.