Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
15,500 | def getitem(self, index, context=None):
return _container_getitem(self, self.elts, index, context=context) | Get an item from this node.
:param index: The node to use as a subscript index.
:type index: Const or Slice |
15,501 | def mlp(feature, hparams, name="mlp"):
with tf.variable_scope(name, "mlp", values=[feature]):
num_mlp_layers = hparams.num_mlp_layers
mlp_size = hparams.mlp_size
for _ in range(num_mlp_layers):
feature = common_layers.dense(feature, mlp_size, activation=None)
utils.collect_named_outputs("no... | Multi layer perceptron with dropout and relu activation. |
15,502 | def colorize(occurence,maxoccurence,minoccurence):
if occurence == maxoccurence:
color = (255,0,0)
elif occurence == minoccurence:
color = (0,0,255)
else:
color = (int((float(occurence)/maxoccurence*255)),0,int(float(minoccurence)/occurence*255))
return color | A formula for determining colors. |
15,503 | def find_usage(self):
logger.debug("Checking usage for service %s", self.service_name)
self.connect()
for lim in self.limits.values():
lim._reset_usage()
self._find_usage_applications()
self._find_usage_application_versions()
self._find_usage_environm... | Determine the current usage for each limit of this service,
and update corresponding Limit via
:py:meth:`~.AwsLimit._add_current_usage`. |
15,504 | def to_table(self, sort_key="wall_time", stop=None):
table = [list(AbinitTimerSection.FIELDS), ]
ord_sections = self.order_sections(sort_key)
if stop is not None:
ord_sections = ord_sections[:stop]
for osect in ord_sections:
row = [str(item) for item in... | Return a table (list of lists) with timer data |
15,505 | def _on_set_auth(self, sock, token):
self.log.info(f"Token received: {token}")
sock.setAuthtoken(token) | Set Auth request received from websocket |
15,506 | def scale(self, new_max_value=1):
f = new_max_value / self.max
return ColorRGB(self.r * f,
self.g * f,
self.b * f,
max_value=new_max_value) | Scale R, G and B parameters
:param new_max_value: how much to scale
:return: a new ColorRGB instance |
15,507 | def _front_delta(self):
if self.flags & self.NO_MOVE:
return Separator(0, 0)
if self.clicked and self.hovered:
delta = 2
elif self.hovered and not self.flags & self.NO_HOVER:
delta = 0
else:
delta = 0
return Separator... | Return the offset of the colored part. |
15,508 | def bulkCmd(snmpDispatcher, authData, transportTarget,
nonRepeaters, maxRepetitions, *varBinds, **options):
def _cbFun(snmpDispatcher, stateHandle, errorIndication, rspPdu, _cbCtx):
if not cbFun:
return
if errorIndication:
cbFun(errorIndication, pMod.Intege... | Initiate SNMP GETBULK query over SNMPv2c.
Based on passed parameters, prepares SNMP GETBULK packet
(:RFC:`1905#section-4.2.3`) and schedules its transmission by
I/O framework at a later point of time.
Parameters
----------
snmpDispatcher: :py:class:`~pysnmp.hlapi.v1arch.asyncore.SnmpDispatcher... |
15,509 | def append(self, symbol, metadata, start_time=None):
if start_time is None:
start_time = dt.utcnow()
old_metadata = self.find_one({: symbol}, sort=[(, pymongo.DESCENDING)])
if old_metadata is not None:
if old_metadata[] >= start_time:
raise ValueE... | Update metadata entry for `symbol`
Parameters
----------
symbol : `str`
symbol name for the item
metadata : `dict`
to be persisted
start_time : `datetime.datetime`
when metadata becomes effective
Default: datetime.datetime.utcnow() |
15,510 | def loop_position(self):
for i, v in enumerate(self._sort_loop):
if v == glances_processes.sort_key:
return i
return 0 | Return the current sort in the loop |
15,511 | def adj_nodes_gcp(gcp_nodes):
for node in gcp_nodes:
node.cloud = "gcp"
node.cloud_disp = "GCP"
node.private_ips = ip_to_str(node.private_ips)
node.public_ips = ip_to_str(node.public_ips)
node.zone = node.extra[].name
return gcp_nodes | Adjust details specific to GCP. |
15,512 | def add_job(self, task, inputdata, debug=False):
if not self._user_manager.session_logged_in():
raise Exception("A user must be logged in to submit an object")
username = self._user_manager.session_username()
waiting_submission = self._database.submissions.find_on... | Add a job in the queue and returns a submission id.
:param task: Task instance
:type task: inginious.frontend.tasks.WebAppTask
:param inputdata: the input as a dictionary
:type inputdata: dict
:param debug: If debug is true, more debug data will be saved
:type debug: boo... |
15,513 | def switch_off(self):
success = self.set_status(CONST.STATUS_OFF_INT)
if success:
self._json_state[] = CONST.STATUS_OFF
return success | Turn the switch off. |
15,514 | def alter_old_distutils_request(request: WSGIRequest):
body = request.body
if request.POST or request.FILES:
return
new_body = BytesIO()
content_type, opts = parse_header(request.META[].encode())
parts = body.split(b + opts[] + b)
for part in parts:
if b not... | Alter the request body for compatibility with older distutils clients
Due to a bug in the Python distutils library, the request post is sent
using \n as a separator instead of the \r\n that the HTTP spec demands.
This breaks the Django form parser and therefore we have to write a
custom parser.
Th... |
15,515 | def get_collection(self, collection, database_name=None, username=None, password=None):
_db = self.get_database(database_name, username, password)
return _db[collection] | Get a pymongo collection handle.
:param collection: Name of collection
:param database_name: (optional) Name of database
:param username: (optional) Username to login with
:param password: (optional) Password to login with
:return: Pymongo collection object |
15,516 | def add(self, *args):
if len(args) > 2:
name, template = args[:2]
args = args[2:]
else:
name = None
template = args[0]
args = args[1:]
if isinstance(template, tuple):
template, type_converters = template
... | Add a path template and handler.
:param name: Optional. If specified, allows reverse path lookup with
:meth:`reverse`.
:param template: A string or :class:`~potpy.template.Template`
instance used to match paths against. Strings will be wrapped in a
Template instance.... |
15,517 | def rewrap_bytes(data):
return b.join(
data[index:index+70] for index in range(0, len(data), 70)
) | Rewrap characters to 70 character width.
Intended to rewrap base64 content. |
15,518 | def default_is_local(hadoop_conf=None, hadoop_home=None):
params = pydoop.hadoop_params(hadoop_conf, hadoop_home)
for k in , :
if not params.get(k, ).startswith():
return False
return True | \
Is Hadoop configured to use the local file system?
By default, it is. A DFS must be explicitly configured. |
15,519 | def get_type_data(name):
name = name.upper()
try:
return {
: ,
: ,
: name,
: ,
: JEFFS_COORDINATE_FORMAT_TYPES[name] + ,
: JEFFS_COORDINATE_FORMAT_TYPES[name],
: ( +
JEFFS_COORDINATE_FORM... | Return dictionary representation of type.
Can be used to initialize primordium.type.primitives.Type |
15,520 | def sync_scheduler(self):
url = "%s/%s/%s" % (self.config[][],
"experiments", "scheduler.info")
try:
req = requests.get(url, proxies=self.config[][],
auth=self.auth,
verify=self.verify... | Download the scheduler.info file and perform a smart comparison
with what we currently have so that we don't overwrite the
last_run timestamp
To do a smart comparison, we go over each entry in the
server's scheduler file. If a scheduler entry is not present
in the server copy, w... |
15,521 | def append(self, event):
self._events.append(event)
self._events_by_baseclass[event.baseclass].append(event) | Add an event to the list. |
15,522 | def _purge(self):
if len(self.cache) <= self.max_size:
return
cache = self.cache
refcount = self.refcount
queue = self.queue
max_size = self.max_size
while len(cache) > max_size:
refc = 1
while refc:
... | Trim the cache down to max_size by evicting the
least-recently-used entries. |
15,523 | def eye_plot(x,L,S=0):
plt.figure(figsize=(6,4))
idx = np.arange(0,L+1)
plt.plot(idx,x[S:S+L+1],)
k_max = int((len(x) - S)/L)-1
for k in range(1,k_max):
plt.plot(idx,x[S+k*L:S+L+1+k*L],)
plt.grid()
plt.xlabel()
plt.ylabel()
plt.title()
return 0 | Eye pattern plot of a baseband digital communications waveform.
The signal must be real, but can be multivalued in terms of the underlying
modulation scheme. Used for BPSK eye plots in the Case Study article.
Parameters
----------
x : ndarray of the real input data vector/array
L : display len... |
15,524 | def remove_edge_fun(graph):
rm_edge, rm_node = graph.remove_edge, graph.remove_node
from networkx import is_isolate
def remove_edge(u, v):
rm_edge(u, v)
if is_isolate(graph, v):
rm_node(v)
return remove_edge | Returns a function that removes an edge from the `graph`.
..note:: The out node is removed if this is isolate.
:param graph:
A directed graph.
:type graph: networkx.classes.digraph.DiGraph
:return:
A function that remove an edge from the `graph`.
:rtype: callable |
15,525 | def get_branches(aliases):
ignore = [, , , ]
branches = []
for k, v in aliases.items():
tokens = re.sub(, , v).split()
for t in tokens:
if bool(re.search(r, t)) or len(t) <= 3:
continue
if bool(re.search(r, t)) and t not in ignore:
... | Get unique branch names from an alias dictionary. |
15,526 | def read_index(self, fh, indexed_fh, rec_iterator=None,
rec_hash_func=None, parse_hash=str, flush=True,
no_reindex=True, verbose=False):
if rec_iterator is not None:
self.record_iterator = rec_iterator
if rec_hash_func is not None:
self.record_hash_functio... | Populate this index from a file. Input format is just a tab-separated file,
one record per line. The last column is the file location for the record
and all columns before that are collectively considered to be the hash key
for that record (which is probably only 1 column, but this allows us to
permit t... |
15,527 | def filter_search(self, code=None, name=None, abilities=None,
attributes=None, info=None):
command = "SELECT code, name FROM CARDS "
command += Where_filter_gen(("code", code), ("name", name),
("abilities", abilities),
... | Return a list of codes and names pertaining to cards that have the
given information values stored.
Can take a code integer, name string, abilities dict {phase: ability
list/"*"}, attributes list, info dict {key, value list/"*"}.
In the above argument examples "*" is a string that may ... |
15,528 | def perform_oauth(email, master_token, android_id, service, app, client_sig,
device_country=, operatorCountry=, lang=,
sdk_version=17):
data = {
: ,
: email,
: 1,
: master_token,
: service,
: ,
: android_id,
... | Use a master token from master_login to perform OAuth to a specific Google
service.
Return a dict, eg::
{
'Auth': '...',
'LSID': '...',
'SID': '..',
'issueAdvice': 'auto',
'services': 'hist,mail,googleme,...'
}
To authenticate re... |
15,529 | def MGMT_ACTIVE_SET(self, sAddr=, xCommissioningSessionId=None, listActiveTimestamp=None, listChannelMask=None, xExtendedPanId=None,
sNetworkName=None, sPSKc=None, listSecurityPolicy=None, xChannel=None, sMeshLocalPrefix=None, xMasterKey=None,
xPanId=None, xTmfPort=None, ... | send MGMT_ACTIVE_SET command
Returns:
True: successful to send MGMT_ACTIVE_SET
False: fail to send MGMT_ACTIVE_SET |
15,530 | def daemon_start(self):
if daemon_status() == "SUN not running":
subprocess.call("{0} &".format(self.cmd), shell=True) | Start daemon when gtk loaded |
15,531 | def geturl(urllib2_resp):
url = urllib2_resp.geturl()
scheme, rest = url.split(, 1)
if rest.startswith():
return url
else:
return % (scheme, rest) | Use instead of urllib.addinfourl.geturl(), which appears to have
some issues with dropping the double slash for certain schemes
(e.g. file://). This implementation is probably over-eager, as it
always restores '://' if it is missing, and it appears some url
schemata aren't always followed by '//' after... |
15,532 | def _parse_attribute(
self,
element,
attribute,
state
):
parsed_value = self._default
attribute_value = element.get(attribute, None)
if attribute_value is not None:
parsed_value = self._parser_func(attribute... | Parse the primitive value within the XML element's attribute. |
15,533 | def encode_sid(cls, secret, sid):
secret_bytes = secret.encode("utf-8")
sid_bytes = sid.encode("utf-8")
sig = hmac.new(secret_bytes, sid_bytes, hashlib.sha512).hexdigest()
return "%s%s" % (sig, sid) | Computes the HMAC for the given session id. |
15,534 | def unbind(self, callback):
handlers = self._handlers
if handlers:
filtered_callbacks = [f for f in handlers if f != callback]
removed_count = len(handlers) - len(filtered_callbacks)
if removed_count:
self._handlers = filtered_callbacks
... | Remove a callback from the list |
15,535 | def keep(self, diff):
(toUUID, fromUUID) = self.toArg.diff(diff)
self._client.keep(toUUID, fromUUID)
logger.debug("Kept %s", diff) | Mark this diff (or volume) to be kept in path. |
15,536 | def _split_refextract_authors_str(authors_str):
author_seq = (x.strip() for x in RE_SPLIT_AUTH.split(authors_str) if x)
res = []
current =
for author in author_seq:
if not isinstance(author, six.text_type):
author = six.text_type(author.decode(, ))
author = r... | Extract author names out of refextract authors output. |
15,537 | def get_create_security_group_commands(self, sg_id, sg_rules):
cmds = []
in_rules, eg_rules = self._format_rules_for_eos(sg_rules)
cmds.append("ip access-list %s dynamic" %
self._acl_name(sg_id, n_const.INGRESS_DIRECTION))
for in_rule in in_rules:
... | Commands for creating ACL |
15,538 | async def update_server_data(server):
data = datatools.get_data()
"The prefix is currently `!`, and can be changed at any time using `!prefix`\n\n" + \
"You can use `!help` to get help commands for all modules, " + \
"or ... | Updates the server info for the given server
Args:
server: The Discord server to update info for |
15,539 | def ParseCall(self, parser_mediator, query, row, **unused_kwargs):
query_hash = hash(query)
guid = self._GetRowValue(query_hash, row, )
is_incoming = self._GetRowValue(query_hash, row, )
videostatus = self._GetRowValue(query_hash, row, )
try:
aux = guid
if aux:
aux_list = ... | Parses a call.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
query (str): query that created the row.
row (sqlite3.Row): row resulting from query.
query (Optional[str]): query. |
15,540 | def multigrid(bounds, points_count):
if len(bounds)==1:
return np.linspace(bounds[0][0], bounds[0][1], points_count).reshape(points_count, 1)
x_grid_rows = np.meshgrid(*[np.linspace(b[0], b[1], points_count) for b in bounds])
x_grid_columns = np.vstack([x.flatten(order=) for x in x_grid_rows]).... | Generates a multidimensional lattice
:param bounds: box constraints
:param points_count: number of points per dimension. |
15,541 | def _get_ukko_report():
s report from the fixed URL.
'
with urllib.request.urlopen(URL_UKKO_REPORT) as response:
ret = str(response.read())
return ret | Get Ukko's report from the fixed URL. |
15,542 | def optimal_partitions(sizes, counts, num_part):
if num_part < 2:
return [(sizes[0], sizes[-1])]
if num_part >= len(sizes):
partitions = [(x, x) for x in sizes]
return partitions
nfps = _compute_nfps_real(counts, sizes)
partitions, _, _ = _compute_best_partitions(num_part, s... | Compute the optimal partitions given a distribution of set sizes.
Args:
sizes (numpy.array): The complete domain of set sizes in ascending
order.
counts (numpy.array): The frequencies of all set sizes in the same
order as `sizes`.
num_part (int): The number of partit... |
15,543 | def _concatenate_shape(input_shape, axis=-1):
ax = axis % len(input_shape[0])
concat_size = sum(shape[ax] for shape in input_shape)
out_shape = input_shape[0][:ax] + (concat_size,) + input_shape[0][ax+1:]
return out_shape | Helper to determine the shape of Concatenate output. |
15,544 | def check_num_slices(num_slices, img_shape=None, num_dims=3):
if not isinstance(num_slices, Iterable) or len(num_slices) == 1:
num_slices = np.repeat(num_slices, num_dims)
if img_shape is not None:
if len(num_slices) != len(img_shape):
raise ValueError(
... | Ensures requested number of slices is valid.
Atleast 1 and atmost the image size, if available |
15,545 | def loads(cls, s):
with closing(StringIO(s)) as fileobj:
return cls.load(fileobj) | Load an instance of this class from YAML. |
15,546 | def show_exception_only(self, etype, evalue):
ostream = self.ostream
ostream.flush()
ostream.write(.join(self.get_exception_only(etype, evalue)))
ostream.flush() | Only print the exception type and message, without a traceback.
Parameters
----------
etype : exception type
value : exception value |
15,547 | def sparse_or_dense_matvecmul(sparse_or_dense_matrix,
dense_vector,
validate_args=False,
name=None,
**kwargs):
with tf.compat.v1.name_scope(name, ,
[sparse_or_dense... | Returns (batched) matmul of a (sparse) matrix with a column vector.
Args:
sparse_or_dense_matrix: `SparseTensor` or `Tensor` representing a (batch of)
matrices.
dense_vector: `Tensor` representing a (batch of) vectors, with the same
batch shape as `sparse_or_dense_matrix`. The shape must be compa... |
15,548 | def iteritems(self):
for key in self:
vals = self._container[key.lower()]
for val in vals[1:]:
yield vals[0], val | Iterate over all header lines, including duplicate ones. |
15,549 | def static_get_pdb_object(pdb_id, bio_cache = None, cache_dir = None):
pdb_id = pdb_id.upper()
if bio_cache:
return bio_cache.get_pdb_object(pdb_id)
if cache_dir:
filepath = os.path.join(cache_dir, .format(pdb_id))
if os.path.exists(fil... | This method does not necessarily use a BioCache but it seems to fit here. |
15,550 | def call_api(self,
action,
params=None,
method=(, , ),
**kwargs):
urltype, methodname, content_type = method
if urltype == :
url = self.sms_host
else:
url = self.api_host
if content_type ... | :param method: methodName
:param action: MethodUrl,
:param params: Dictionary,form params for api.
:param timeout: (optional) Float describing the timeout of the request.
:return: |
15,551 | def scrape_metrics(self, scraper_config):
response = self.poll(scraper_config)
try:
if not scraper_config[]:
scraper_config[] = False
elif not scraper_config[]:
for val in itervalues(scraper_config[]):
... | Poll the data from prometheus and return the metrics as a generator. |
15,552 | def extract_public_key(args):
sk = _load_ecdsa_signing_key(args)
vk = sk.get_verifying_key()
args.public_keyfile.write(vk.to_string())
print("%s public key extracted to %s" % (args.keyfile.name, args.public_keyfile.name)) | Load an ECDSA private key and extract the embedded public key as raw binary data. |
15,553 | def read(self, entity=None, attrs=None, ignore=None, params=None):
if entity is None:
entity = type(self)(
self._server_config,
content_view_filter=self.content_view_filter,
)
if attrs is None:
attrs = self.rea... | Do not read certain fields.
Do not expect the server to return the ``content_view_filter``
attribute. This has no practical impact, as the attribute must be
provided when a :class:`nailgun.entities.ContentViewFilterRule` is
instantiated.
Also, ignore any field that is not retur... |
15,554 | def run(self):
"Get jobs from the queue and perform them as they arrive."
while 1:
job = self.jobs.get()
try:
job.run()
self.jobs.task_done()
except TerminationNotice:
self.jobs.task_done()
... | Get jobs from the queue and perform them as they arrive. |
15,555 | def register_token(platform, user_id, token, on_error=None, on_success=None):
__device_token(platform, True, user_id, token=token, on_error=on_error, on_success=on_success) | Register a device token for a user.
:param str platform The platform which to register token on. One of either
Google Cloud Messaging (outbound.GCM) or Apple Push Notification Service
(outbound.APNS).
:param str | number user_id: the id you use to identify a user. this should
be static for the lif... |
15,556 | def _scrape_song_lyrics_from_url(self, url):
page = requests.get(url)
if page.status_code == 404:
return None
html = BeautifulSoup(page.text, "html.parser")
div = html.find("div", class_="lyrics")
if not div:
return None
return ... | Use BeautifulSoup to scrape song info off of a Genius song URL
:param url: URL for the web page to scrape lyrics from |
15,557 | def _send_unsigned_long(self,value):
raise OverflowError(err)
return struct.pack(self.board.unsigned_long_type,value) | Convert a numerical value into an integer, then to a bytes object.
Check bounds for unsigned long. |
15,558 | def create_bot(self, name, avatar_url=None, callback_url=None, dm_notification=None,
**kwargs):
return self._bots.create(name=name, group_id=self.group_id,
avatar_url=avatar_url, callback_url=callback_url,
dm_notificat... | Create a new bot in a particular group.
:param str name: bot name
:param str avatar_url: the URL of an image to use as an avatar
:param str callback_url: a POST-back URL for each new message
:param bool dm_notification: whether to POST-back for direct messages?
:return: the new ... |
15,559 | def dumps_tabledata(value, format_name="rst_grid_table", **kwargs):
from ._factory import TableWriterFactory
if not value:
raise TypeError("value must be a tabledata.TableData instance")
writer = TableWriterFactory.create_from_format_name(format_name)
for attr_name, attr_value in kwargs... | :param tabledata.TableData value: Tabular data to dump.
:param str format_name:
Dumped format name of tabular data.
Available formats are described in
:py:meth:`~pytablewriter.TableWriterFactory.create_from_format_name`
:Example:
.. code:: python
>>> dumps_tabledata... |
15,560 | def radius(self):
try:
return self._radius
except AttributeError:
pass
self._radius = Point(1, 1, 0)
return self._radius | Radius of the ellipse, Point class. |
15,561 | def location_based_search(self, lng, lat, distance, unit="miles", attribute_map=None, page=0, limit=50):
if unit == "miles":
distance = float(distance/69)
else:
distance = float(distance/111.045)
query = {
"loc" : {
... | Search based on location and other attribute filters
:param long lng: Longitude parameter
:param long lat: Latitude parameter
:param int distance: The radius of the query
:param str unit: The unit of measure for the query, defaults to miles
:param dict attribute_map: Additional ... |
15,562 | def _add_helpingmaterials(config, helping_file, helping_type):
try:
project = find_project_by_short_name(config.project[],
config.pbclient,
config.all)
data = _load_data(helping_file, helping_type)
... | Add helping materials to a project. |
15,563 | def ending_long_process(self, message=""):
QApplication.restoreOverrideCursor()
self.show_message(message, timeout=2000)
QApplication.processEvents() | Clear main window's status bar and restore mouse cursor. |
15,564 | def clone(name_a, name_b, **kwargs):
property1value1property2value2*
flags = []
target = []
filesystem_properties = kwargs.get(, {})
if kwargs.get(, False):
flags.append()
target.append(name_a)
target.append(name_b)
res = __salt__[](
__ut... | Creates a clone of the given snapshot.
name_a : string
name of snapshot
name_b : string
name of filesystem or volume
create_parent : boolean
creates all the non-existing parent datasets. any property specified on the
command line using the -o option is ignored.
propertie... |
15,565 | async def keep_alive(self, period=1, margin=.3):
if period < 0:
period = 0
if period > 10:
period = 10
self.period = period
if margin < .1:
margin = .1
if margin > .9:
margin = .9
self.margin = margin
self.k... | Periodically send a keep alive message to the Arduino.
Frequency of keep alive transmission is calculated as follows:
keep_alive_sent = period - (period * margin)
:param period: Time period between keepalives. Range is 0-10 seconds.
0 disables the keepalive mechanism.
... |
15,566 | def run(self, debug=False, reload=None):
loop = asyncio.get_event_loop()
logging.basicConfig(level=logging.DEBUG if debug else logging.INFO)
if reload is None:
reload = debug
bot_loop = asyncio.ensure_future(self.loop())
try:
if reload:
... | Convenience method for running bots in getUpdates mode
:param bool debug: Enable debug logging and automatic reloading
:param bool reload: Automatically reload bot on code change
:Example:
>>> if __name__ == '__main__':
>>> bot.run() |
15,567 | def update(self, friendly_name=None, description=None, expiry=None, schema=None):
self._load_info()
if friendly_name is not None:
self._info[] = friendly_name
if description is not None:
self._info[] = description
if expiry is not None:
if isinstance(expiry, datetime.datetime):
... | Selectively updates Table information.
Any parameters that are omitted or None are not updated.
Args:
friendly_name: if not None, the new friendly name.
description: if not None, the new description.
expiry: if not None, the new expiry time, either as a DateTime or milliseconds since epoch.
... |
15,568 | def _do_functions(self, rule, p_selectors, p_parents, p_children, scope, media, c_lineno, c_property, c_codestr, code, name):
if name:
funct, params, _ = name.partition()
funct = funct.strip()
params = split_params(depar(params + _))
defaults = {}
... | Implements @mixin and @function |
15,569 | def check_work_done(self, grp):
id_ = self.get_id(grp)
concat_file = os.path.join(self.cache_dir, .format(id_))
result_file = os.path.join(self.cache_dir, .format(id_, self.task_interface.name))
return os.path.exists(concat_file), os.path.exists(result_file) | Check for the existence of alignment and result files. |
15,570 | def detect_encoding(readline):
bom_found = False
encoding = None
default =
def read_or_stop():
try:
return readline()
except StopIteration:
return bytes()
def find_cookie(line):
try:
line_string = line.decode()
except Unicode... | The detect_encoding() function is used to detect the encoding that should
be used to decode a Python source file. It requires one argment, readline,
in the same way as the tokenize() generator.
It will call readline a maximum of twice, and return the encoding used
(as a string) and a list of any lines ... |
15,571 | def write_stilde(self, stilde_dict, group=None):
subgroup = self.data_group + "/{ifo}/stilde"
if group is None:
group = subgroup
else:
group = .join([group, subgroup])
for ifo, stilde in stilde_dict.items():
self[group.format(ifo=ifo)] = stild... | Writes stilde for each IFO to file.
Parameters
-----------
stilde : {dict, FrequencySeries}
A dict of FrequencySeries where the key is the IFO.
group : {None, str}
The group to write the strain to. If None, will write to the top
level. |
15,572 | def update(self, feedforwardInputI, feedforwardInputE, v, recurrent=True,
envelope=False, iSpeedTuning=False, enforceDale=True):
np.matmul(self.activationsP * self.placeGainI, self.weightsPI,
self.instantaneousI)
np.matmul(self.activationsP* self.placeGainE, self.weightsPEL,
... | Do one update of the CAN network, of length self.dt.
:param feedforwardInputI: The feedforward input to inhibitory cells.
:param feedforwardInputR: The feedforward input to excitatory cells.
:param placeActivity: Activity of the place code.
:param v: The current velocity.
:param recurrent: Whether o... |
15,573 | def run_script(self,
script,
shutit_pexpect_child=None,
in_shell=True,
echo=None,
note=None,
loglevel=logging.DEBUG):
shutit_global.shutit_global_object.yield_to_draw()
shutit_pexpect_child = shutit_pexpect_child or s... | Run the passed-in string as a script on the target's command line.
@param script: String representing the script. It will be de-indented
and stripped before being run.
@param shutit_pexpect_child: See send()
@param in_shell: Indicate whether we are in a shell or not. (Default: True)
@param note: ... |
15,574 | def parse(self, data, path=None):
assert not self.exhausted,
self.path = path
parsed_data = self.yacc.parse(data, lexer=self.lexer, debug=self.debug)
for err_msg, lineno in self.lexer.errors[::-1]:
self.errors.insert(0, (err_msg, lineno, s... | Args:
data (str): Raw specification text.
path (Optional[str]): Path to specification on filesystem. Only
used to tag tokens with the file they originated from. |
15,575 | def swap_dims(self, dims_dict, inplace=None):
inplace = _check_inplace(inplace)
for k, v in dims_dict.items():
if k not in self.dims:
raise ValueError(
% k)
if self.variables[v].dims != (k,):
... | Returns a new object with swapped dimensions.
Parameters
----------
dims_dict : dict-like
Dictionary whose keys are current dimension names and whose values
are new names. Each value must already be a variable in the
dataset.
inplace : bool, optional
... |
15,576 | def get_record_params(args):
name, rtype, content, ttl, priority = (
args.name, args.rtype, args.content, args.ttl, args.priority)
return name, rtype, content, ttl, priority | Get record parameters from command options.
Argument:
args: arguments object |
15,577 | def render_json_response(self, context_dict, status=200):
json_context = json.dumps(
context_dict,
cls=DjangoJSONEncoder,
**self.get_json_dumps_kwargs()
).encode(u)
return HttpResponse(
json_context,
content_type=self.get_conte... | Limited serialization for shipping plain data. Do not use for models
or other complex or custom objects. |
15,578 | def do_gen(argdict):
site = make_site_obj(argdict)
try:
st = time.time()
site.generate()
et = time.time()
print "Generated Site in %f seconds."% (et-st)
except ValueError as e:
print "Cannot generate. You are not within a simplystatic \
tree and you didn't speci... | Generate the whole site. |
15,579 | def template_substitute(text, **kwargs):
for name, value in kwargs.items():
placeholder_pattern = "{%s}" % name
if placeholder_pattern in text:
text = text.replace(placeholder_pattern, value)
return text | Replace placeholders in text by using the data mapping.
Other placeholders that is not represented by data is left untouched.
:param text: Text to search and replace placeholders.
:param data: Data mapping/dict for placeholder key and values.
:return: Potentially modified text with replaced placeho... |
15,580 | def copy_from(self,
container: Container,
fn_container: str,
fn_host: str
) -> None:
logger.debug("Copying file from container, %s: %s -> %s",
container.uid, fn_container, fn_host)
cmd = "docker cp ".f... | Copies a given file from the container to a specified location on the
host machine. |
15,581 | def todate(val):
if not val:
raise ValueError("Value not provided")
if isinstance(val, datetime):
return val.date()
elif isinstance(val, date):
return val
else:
try:
ival = int(val)
sval = str(ival)
if len(sval) == 8:
... | Convert val to a datetime.date instance by trying several
conversion algorithm.
If it fails it raise a ValueError exception. |
15,582 | def fetchGroupInfo(self, *group_ids):
threads = self.fetchThreadInfo(*group_ids)
groups = {}
for id_, thread in threads.items():
if thread.type == ThreadType.GROUP:
groups[id_] = thread
else:
raise FBchatUserError("Thread {} was no... | Get groups' info from IDs, unordered
:param group_ids: One or more group ID(s) to query
:return: :class:`models.Group` objects, labeled by their ID
:rtype: dict
:raises: FBchatException if request failed |
15,583 | def request(self, path,
args=[], files=[], opts={}, stream=False,
decoder=None, headers={}, data=None):
url = self.base + path
params = []
params.append((, ))
for opt in opts.items():
params.append(opt)
for arg in args:
... | Makes an HTTP request to the IPFS daemon.
This function returns the contents of the HTTP response from the IPFS
daemon.
Raises
------
~ipfsapi.exceptions.ErrorResponse
~ipfsapi.exceptions.ConnectionError
~ipfsapi.exceptions.ProtocolError
~ipfsapi.excepti... |
15,584 | def randomSize(cls, widthLimits, heightLimits, origin=None):
r = cls(0, 0, origin)
r.w = random.randint(widthLimits[0], widthLimits[1])
r.h = random.randint(heightLimits[0], heightLimits[1])
return r | :param: widthLimits - iterable of integers with length >= 2
:param: heightLimits - iterable of integers with length >= 2
:param: origin - optional Point subclass
:return: Rectangle |
15,585 | def load(self, **kwargs):
kwargs[] = True
kwargs = self._mutate_name(kwargs)
return self._load(**kwargs) | Loads a given resource
Loads a given resource provided a 'name' and an optional 'slot'
parameter. The 'slot' parameter is not a required load parameter
because it is provided as an optional way of constructing the
correct 'name' of the vCMP resource.
:param kwargs:
:ret... |
15,586 | def count_generator(generator, memory_efficient=True):
if memory_efficient:
counter = 0
for _ in generator:
counter += 1
return counter
else:
return len(list(generator)) | Count number of item in generator.
memory_efficient=True, 3 times slower, but memory_efficient.
memory_efficient=False, faster, but cost more memory. |
15,587 | def parse(self, argv, tokenizer=DefaultTokenizer):
args = tokenizer.tokenize(argv)
_lang = tokenizer.language_definition()
pass | Parse command line to out tree
:type argv object
:type tokenizer AbstractTokenizer |
15,588 | def ready(self):
self.log(, len(schemastore), ,
len(configschemastore), , lvl=debug) | Sets up the application after startup. |
15,589 | def listunion(ListOfLists):
u = []
for s in ListOfLists:
if s != None:
u.extend(s)
return u | Take the union of a list of lists.
Take a Python list of Python lists::
[[l11,l12, ...], [l21,l22, ...], ... , [ln1, ln2, ...]]
and return the aggregated list::
[l11,l12, ..., l21, l22 , ...]
For a list of two lists, e.g. `[a, b]`, this is like::
a.extend(b)
**... |
15,590 | def is_blocking_notifications(self, notification_period, hosts, services, n_type, t_wished):
logger.debug("Checking if a service %s (%s) notification is blocked...",
self.get_full_name(), self.state)
host = hosts[self.host]
if t_wished is None:
... | Check if a notification is blocked by the service.
Conditions are ONE of the following::
* enable_notification is False (global)
* not in a notification_period
* notifications_enable is False (local)
* notification_options is 'n' or matches the state ('UNKNOWN' <=> 'u' ...)
... |
15,591 | def traverse_tree_recursive(odb, tree_sha, path_prefix):
entries = []
data = tree_entries_from_data(odb.stream(tree_sha).read())
for sha, mode, name in data:
if S_ISDIR(mode):
entries.extend(traverse_tree_recursive(odb, sha, path_prefix + name + ))
else:
en... | :return: list of entries of the tree pointed to by the binary tree_sha. An entry
has the following format:
* [0] 20 byte sha
* [1] mode as int
* [2] path relative to the repository
:param path_prefix: prefix to prepend to the front of all returned paths |
15,592 | def collect(self):
if pymongo is None:
self.log.error()
return
if in self.config:
self.config[] = [self.config[]]
if self.config[]:
self.config[] = int(
self.config[])
if in self.con... | Collect number values from db.serverStatus() and db.engineStatus() |
15,593 | def _speak_as(
self,
element,
regular_expression,
data_property_value,
operation
):
children = []
pattern = re.compile(regular_expression)
content = element.get_text_content()
while content:
matches = pattern.search(conten... | Execute a operation by regular expression for element only.
:param element: The element.
:type element: hatemile.util.html.htmldomelement.HTMLDOMElement
:param regular_expression: The regular expression.
:type regular_expression: str
:param data_property_value: The value of cust... |
15,594 | def setDevice(self, device):
print(self.pre, "setDevice :", device)
if (not device and not self.device):
return
if (self.device):
if self.device == device:
print(self.pre, "setDevice : same device")
return
... | Sets the video stream
:param device: A rather generic device class. In this case DataModel.RTSPCameraDevice. |
15,595 | def uploadFile(self, filename, ispickle=False, athome=False):
print("Uploading file {} to Redunda.".format(filename))
_, tail = os.path.split(filename)
url = "https://redunda.sobotics.org/bots/data/{}?key={}".format(tail, self.key)
header = {"Content-... | Uploads a single file to Redunda.
:param str filename: The name of the file to upload
:param bool ispickle: Optional variable to be set to True is the file is a pickle; default is False.
:returns: returns nothing |
15,596 | def __parse_domain_to_employer_stream(self, stream):
if not stream:
return
f = self.__parse_domain_to_employer_line
for o in self.__parse_stream(stream, f):
org = o[0]
dom = o[1]
if org not in self.__raw_orgs:
self.__raw... | Parse domain to employer stream.
Each line of the stream has to contain a domain and a organization,
or employer, separated by tabs. Comment lines start with the hash
character (#)
Example:
# Domains from domains.txt
example.org Example
example.com ... |
15,597 | def getargs():
from argparse import ArgumentParser
parser = ArgumentParser(description=)
parser.add_argument("question", type=str, help="A question to ask.")
return parser.parse_args() | Return arguments |
15,598 | def get_commits_since(check_name, target_tag=None):
root = get_root()
target_path = os.path.join(root, check_name)
command = .format( if target_tag is None else .format(target_tag), target_path)
with chdir(root):
return run_command(command, capture=True).stdout.splitlines() | Get the list of commits from `target_tag` to `HEAD` for the given check |
15,599 | def register(self,flag):
super(Flags,self).__setitem__(flag.name,flag) | Register a new :class:`Flag` instance with the Flags registry. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.