Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
383,200 | def hull(self):
from scipy.spatial import ConvexHull
if len(self.coordinates) >= 4:
inds = ConvexHull(self.coordinates).vertices
return self.coordinates[inds]
else:
return self.coordinates | Bounding polygon as a convex hull. |
383,201 | def lagcrp_helper(egg, match=, distance=,
ts=None, features=None):
def lagcrp(rec, lstlen):
def check_pair(a, b):
if (a>0 and b>0) and (a!=b):
return True
else:
return False
def compute_actual(rec, lstlen):
... | Computes probabilities for each transition distance (probability that a word
recalled will be a given distance--in presentation order--from the previous
recalled word).
Parameters
----------
egg : quail.Egg
Data to analyze
match : str (exact, best or smooth)
Matching approach t... |
383,202 | def import_teamocil(sconf):
tmuxp_config = {}
if in sconf:
sconf = sconf[]
if in sconf:
tmuxp_config[] = sconf[]
else:
tmuxp_config[] = None
if in sconf:
tmuxp_config[] = sconf.pop()
tmuxp_config[] = []
for w in sconf[]:
windowdict = {: ... | Return tmuxp config from a `teamocil`_ yaml config.
.. _teamocil: https://github.com/remiprev/teamocil
Parameters
----------
sconf : dict
python dict for session configuration
Notes
-----
Todos:
- change 'root' to a cd or start_directory
- width in pane -> main-pain-wid... |
383,203 | def _swap_optimizer_allows(self, p1, p2):
a = self._array
tile1 = a[p1]
tile2 = a[p2]
if tile1 == tile2:
return False
if tile1.matches(tile2) and not any(t.is_wildcard()
for t in (tile1, t... | Identify easily discarded meaningless swaps.
This is motivated by the cost of millions of swaps being simulated. |
383,204 | def order_by(self, key):
if key is None:
raise NullArgumentError(u"No key for sorting given")
kf = [OrderingDirection(key, reverse=False)]
return SortedEnumerable(key_funcs=kf, data=self._data) | Returns new Enumerable sorted in ascending order by given key
:param key: key to sort by as lambda expression
:return: new Enumerable object |
383,205 | def thread_safe(method):
@functools.wraps(method)
def _locker(self, *args, **kwargs):
assert hasattr(self, ), \
\
.format(self.__class__.__name__, method.__name__)
try:
self.lock.acquire()
return method(self, *args, **kwargs)
finally... | wraps method with lock acquire/release cycle
decorator requires class instance to have field self.lock of type threading.Lock or threading.RLock |
383,206 | def save_task(task, broker):
if not existing_task.success:
existing_task.stopped = task[]
existing_task.result = task[]
existing_task.success = task[]
existing_task.save()
else:
Task.objects.create(id=task[],
... | Saves the task package to Django or the cache |
383,207 | def save(self, **kwargs):
entry = super(FormForForm, self).save(commit=False)
entry.form = self.form
entry.entry_time = now()
entry.save()
entry_fields = entry.fields.values_list("field_id", flat=True)
new_entry_fields = []
for field in self.form_fields:
... | Create a ``FormEntry`` instance and related ``FieldEntry``
instances for each form field. |
383,208 | def add_subtract(st, max_iter=7, max_npart=, max_mem=2e8,
always_check_remove=False, **kwargs):
if max_npart == :
max_npart = 0.05 * st.obj_get_positions().shape[0]
total_changed = 0
_change_since_opt = 0
removed_poses = []
added_poses0 = []
added_poses = []
n... | Automatically adds and subtracts missing & extra particles.
Operates by removing bad particles then adding missing particles on
repeat, until either no particles are added/removed or after `max_iter`
attempts.
Parameters
----------
st: :class:`peri.states.State`
The state to add and su... |
383,209 | def transform_y(self, tfms:TfmList=None, **kwargs):
"Set `tfms` to be applied to the targets only."
_check_kwargs(self.y, tfms, **kwargs)
self.tfm_y=True
if tfms is None:
self.tfms_y = list(filter(lambda t: t.use_on_y, listify(self.tfms)))
self.tfmargs_y = {**self... | Set `tfms` to be applied to the targets only. |
383,210 | def write(self, str):
if self.closed: raise ValueError()
if self._mode in _allowed_read:
raise Exception()
if self._valid is not None:
raise Exception()
if not self._done_header:
self._write_header()
encrypted = self._cryp... | Write string str to the underlying file.
Note that due to buffering, flush() or close() may be needed before
the file on disk reflects the data written. |
383,211 | def exists(self):
if self._create:
return False
try:
self.getProfile()
return True
except RequestFailed:
return False | :type: bool
True when the object actually exists (and can be accessed by
the current user) in Fedora |
383,212 | def fetch(self):
params = values.of({})
payload = self._version.fetch(
,
self._uri,
params=params,
)
return ChallengeInstance(
self._version,
payload,
service_sid=self._solution[],
identity=sel... | Fetch a ChallengeInstance
:returns: Fetched ChallengeInstance
:rtype: twilio.rest.authy.v1.service.entity.factor.challenge.ChallengeInstance |
383,213 | def add_row(self, label, row_data, columns=""):
if len(columns):
if sorted(self.df.columns) == sorted(columns):
self.df.columns = columns
else:
new_columns = []
new_columns.extend(columns)
for col ... | Add a row with data.
If any new keys are present in row_data dictionary,
that column will be added to the dataframe.
This is done inplace |
383,214 | def set_cell(self, index, value):
if self._sort:
exists, i = sorted_exists(self._index, index)
if not exists:
self._insert_row(i, index)
else:
try:
i = self._index.index(index)
except ValueError:
i =... | Sets the value of a single cell. If the index is not in the current index then a new index will be created.
:param index: index value
:param value: value to set
:return: nothing |
383,215 | def returner(ret):
signaled = dispatch.Signal(providing_args=[]).send(sender=, ret=ret)
for signal in signaled:
log.debug(
returner\
, signal[0], signal[1]
) | Signal a Django server that a return is available |
383,216 | def norm_package_version(version):
if version:
version = .join(v.strip() for v in version.split()).strip()
if version.startswith() and version.endswith():
version = version[1:-1]
version = .join(v for v in version if v.strip())
else:
version =
return vers... | Normalize a version by removing extra spaces and parentheses. |
383,217 | def dict_array_bytes(ary, template):
shape = shape_from_str_tuple(ary[], template)
dtype = dtype_from_str(ary[], template)
return array_bytes(shape, dtype) | Return the number of bytes required by an array
Arguments
---------------
ary : dict
Dictionary representation of an array
template : dict
A dictionary of key-values, used to replace any
string values in the array with concrete integral
values
Returns
----------... |
383,218 | def check(a, b):
aencrypt = encrypt(a)
bencrypt = encrypt(b)
return a == b or a == bencrypt or aencrypt == b | Checks to see if the two values are equal to each other.
:param a | <str>
b | <str>
:return <bool> |
383,219 | def from_shapely(polygon_shapely, label=None):
import shapely.geometry
ia.do_assert(isinstance(polygon_shapely, shapely.geometry.Polygon))
if polygon_shapely.exterior is None or len(polygon_shapely.exterior.coords) == 0:
return Polygon([], label=label)
... | Create a polygon from a Shapely polygon.
Note: This will remove any holes in the Shapely polygon.
Parameters
----------
polygon_shapely : shapely.geometry.Polygon
The shapely polygon.
label : None or str, optional
The label of the new polygon.
... |
383,220 | def delete(self, *keys):
return self._execute([b] + list(keys), len(keys)) | Removes the specified keys. A key is ignored if it does not exist.
Returns :data:`True` if all keys are removed.
.. note::
**Time complexity**: ``O(N)`` where ``N`` is the number of keys that
will be removed. When a key to remove holds a value other than a
string, the ... |
383,221 | def _handle_ping(client, topic, dct):
if dct[] == :
resp = {
: ,
: client.name,
: dct
}
client.publish(, resp) | Internal method that will be called when receiving ping message. |
383,222 | def __system_multiCall(calls, **kwargs):
if not isinstance(calls, list):
raise RPCInvalidParams(.format(type(calls)))
handler = kwargs.get(HANDLER_KEY)
results = []
for call in calls:
try:
result = handler.execute_procedure(call[], args=call.get())
... | Call multiple RPC methods at once.
:param calls: An array of struct like {"methodName": string, "params": array }
:param kwargs: Internal data
:type calls: list
:type kwargs: dict
:return: |
383,223 | def serialize(self, obj, method=, beautify=False, raise_exception=False):
return self.helper.string.serialization.serialize(
obj=obj, method=method, beautify=beautify, raise_exception=raise_exception) | Alias of helper.string.serialization.serialize |
383,224 | def cidr_to_ipv4_netmask(cidr_bits):
try:
cidr_bits = int(cidr_bits)
if not 1 <= cidr_bits <= 32:
return
except ValueError:
return
netmask =
for idx in range(4):
if idx:
netmask +=
if cidr_bits >= 8:
netmask +=
... | Returns an IPv4 netmask |
383,225 | def _parse_rd(self, config):
match = RD_RE.search(config)
if match:
value = match.group()
else:
value = match
return dict(rd=value) | _parse_rd scans the provided configuration block and extracts
the vrf rd. The return dict is intended to be merged into the response
dict.
Args:
config (str): The vrf configuration block from the nodes running
configuration
Returns:
dict: resourc... |
383,226 | def SkyCoord(self,*args,**kwargs):
kwargs.pop(,None)
_check_roSet(self,kwargs,)
radec= self._radec(*args,**kwargs)
tdist= self.dist(quantity=False,*args,**kwargs)
if not _APY3:
return coordinates.SkyCoord(radec[:,0]*units.degree,
... | NAME:
SkyCoord
PURPOSE:
return the position as an astropy SkyCoord
INPUT:
t - (optional) time at which to get the position
obs=[X,Y,Z] - (optional) position of observer (in kpc)
(default=Object-wide default)
O... |
383,227 | def d3logpdf_df3(self, f, y, Y_metadata=None):
if isinstance(self.gp_link, link_functions.Identity):
d3logpdf_df3 = self.d3logpdf_dlink3(f, y, Y_metadata=Y_metadata)
else:
inv_link_f = self.gp_link.transf(f)
d3logpdf_dlink3 = self.d3logpdf_dlink3(inv_link_f, ... | Evaluates the link function link(f) then computes the third derivative of log likelihood using it
Uses the Faa di Bruno's formula for the chain rule
.. math::
\\frac{d^{3}\\log p(y|\\lambda(f))}{df^{3}} = \\frac{d^{3}\\log p(y|\\lambda(f)}{d\\lambda(f)^{3}}\\left(\\frac{d\\lambda(f)}{df}\\r... |
383,228 | def canonical_url(configs, endpoint_type=PUBLIC):
scheme = _get_scheme(configs)
address = resolve_address(endpoint_type)
if is_ipv6(address):
address = "[{}]".format(address)
return % (scheme, address) | Returns the correct HTTP URL to this host given the state of HTTPS
configuration, hacluster and charm configuration.
:param configs: OSTemplateRenderer config templating object to inspect
for a complete https context.
:param endpoint_type: str endpoint type to resolve.
:param return... |
383,229 | def setVersion(self, date_issued, version_id=None):
if date_issued is not None:
self.set_date_issued(date_issued)
elif version_id is not None:
self.set_version_by_num(version_id)
else:
LOG.error("date or version not set!")
re... | Legacy function...
should use the other set_* for version and date
as of 2016-10-20 used in:
dipper/sources/HPOAnnotations.py 139:
dipper/sources/CTD.py 99:
dipper/sources/BioGrid.py 100:
dipper/sources/MGI.py 255:
dipper/sourc... |
383,230 | def _dict_rpartition(
in_dict,
keys,
delimiter=DEFAULT_TARGET_DELIM,
ordered_dict=False):
:
if delimiter in keys:
all_but_last_keys, _, last_key = keys.rpartition(delimiter)
ensure_dict_key(in_dict,
all_but_last_keys,
... | Helper function to:
- Ensure all but the last key in `keys` exist recursively in `in_dict`.
- Return the dict at the one-to-last key, and the last key
:param dict in_dict: The dict to work with.
:param str keys: The delimited string with one or more keys.
:param str delimiter: The delimiter to use ... |
383,231 | def plane_intersection(strike1, dip1, strike2, dip2):
norm1 = sph2cart(*pole(strike1, dip1))
norm2 = sph2cart(*pole(strike2, dip2))
norm1, norm2 = np.array(norm1), np.array(norm2)
lon, lat = cart2sph(*np.cross(norm1, norm2, axis=0))
return geographic2plunge_bearing(lon, lat) | Finds the intersection of two planes. Returns a plunge/bearing of the linear
intersection of the two planes.
Also accepts sequences of strike1s, dip1s, strike2s, dip2s.
Parameters
----------
strike1, dip1 : numbers or sequences of numbers
The strike and dip (in degrees, following the right... |
383,232 | def _openResources(self):
logger.info("Opening: {}".format(self._fileName))
self._ncGroup = Dataset(self._fileName) | Opens the root Dataset. |
383,233 | def uuid_from_time(time_arg, node=None, clock_seq=None):
if hasattr(time_arg, ):
seconds = int(calendar.timegm(time_arg.utctimetuple()))
microseconds = (seconds * 1e6) + time_arg.time().microsecond
else:
microseconds = int(time_arg * 1e6)
intervals = int(microseconds ... | Converts a datetime or timestamp to a type 1 :class:`uuid.UUID`.
:param time_arg:
The time to use for the timestamp portion of the UUID.
This can either be a :class:`datetime` object or a timestamp
in seconds (as returned from :meth:`time.time()`).
:type datetime: :class:`datetime` or timesta... |
383,234 | def Or(*xs, simplify=True):
xs = [Expression.box(x).node for x in xs]
y = exprnode.or_(*xs)
if simplify:
y = y.simplify()
return _expr(y) | Expression disjunction (sum, OR) operator
If *simplify* is ``True``, return a simplified expression. |
383,235 | def delete(self, path):
path = normalize_api_path(path)
if path in self.managers:
raise HTTPError(
400, "Can't delete root of %s" % self.managers[path]
)
return self.__delete(path) | Ensure that roots of our managers can't be deleted. This should be
enforced by https://github.com/ipython/ipython/pull/8168, but rogue
implementations might override this behavior. |
383,236 | def _sign_block(self, block):
block_header = block.block_header
header_bytes = block_header.SerializeToString()
signature = self._identity_signer.sign(header_bytes)
block.set_signature(signature)
return block | The block should be complete and the final
signature from the publishing validator (this validator) needs to
be added. |
383,237 | def get_contents_static(self, block_alias, context):
if not in context:
elif resolved_view_name in lookup_area:
static_block_contents = choice(lookup_area[resolved_view_name])
else:
for url, contents in lookup_area.items():
if url.m... | Returns contents of a static block. |
383,238 | def messages(self):
if self._session:
result = []
for msg in self._session.messages:
ex = _create_exception_by_message(msg)
result.append((type(ex), ex))
return result
else:
return None | Messages generated by server, see http://legacy.python.org/dev/peps/pep-0249/#cursor-messages |
383,239 | def lowwrap(self, fname):
fun = getattr(self, fname)
if fname in (, ):
def wrap(*a, **kw):
res = fun(*a, **kw)
if not res or type(res) == type(0):
return res
else:
return (res, type(res) != Fuse... | Wraps the fname method when the C code expects a different kind of
callback than we have in the fusepy API. (The wrapper is usually for
performing some checks or transfromations which could be done in C but
is simpler if done in Python.)
Currently `open` and `create` are wrapped: a bool... |
383,240 | def order_target_value(self,
asset,
target,
limit_price=None,
stop_price=None,
style=None):
if not self._can_order_asset(asset):
return None
target... | Place an order to adjust a position to a target value. If
the position doesn't already exist, this is equivalent to placing a new
order. If the position does exist, this is equivalent to placing an
order for the difference between the target value and the
current value.
If the As... |
383,241 | def geojson_handler(geojson, hType=):
hType_dict = {
: [, ],
: [, ],
: [, ],
}
oldlist = [x for x in geojson[] if x[][].lower() in hType_dict[hType]]
newlist = []
for each_dict in oldlist:
geojson_type = each_dict[][].lower()
if hType == :
newlist... | Restructure a GeoJSON object in preparation to be added directly by add_map_data or add_data_set methods.
The geojson will be broken down to fit a specific Highcharts (highmaps) type, either map, mapline or mappoint.
Meta data in GeoJSON's properties object will be copied directly over to object['properties']... |
383,242 | def list_unique(cls):
query = meta.Session.query(Predicate).distinct(Predicate.namespace)
return query.all() | Return all unique namespaces
:returns: a list of all predicates
:rtype: list of ckan.model.semantictag.Predicate objects |
383,243 | def list_security_groups(call=None):
s groups.
.. versionadded:: 2016.3.0
CLI Example:
.. code-block:: bash
salt-cloud -f list_security_groups opennebula
actionThe list_security_groups function must be called with -f or --function.:NAME').text] = _xml_to_dict(group)
return groups | Lists all security groups available to the user and the user's groups.
.. versionadded:: 2016.3.0
CLI Example:
.. code-block:: bash
salt-cloud -f list_security_groups opennebula |
383,244 | def __to_file(self, message_no):
filename = self.__create_file_name(message_no)
try:
with codecs.open(filename, mode=,
encoding=self.messages[message_no].encoding)\
as file__:
file__.write(self.messages[message_no].out... | Write a single message to file |
383,245 | def absolute_path(path=None, base_dir=None):
if path_is_remote(path):
return path
else:
if os.path.isabs(path):
return path
else:
if base_dir is None or not os.path.isabs(base_dir):
raise TypeError("base_dir must be an absolute path.")
... | Return absolute path if path is local.
Parameters:
-----------
path : path to file
base_dir : base directory used for absolute path
Returns:
--------
absolute path |
383,246 | def start(self):
if self.running:
raise Exception()
if self.io_loop is None:
self.io_loop = tornado.ioloop.IOLoop.current()
self.running = True
answer = tornado.gen.Future()
self._schedule_ad(0, answer)
return answer | Starts the advertise loop.
Returns the result of the first ad request. |
383,247 | def apply_handler_to_all_logs(handler: logging.Handler,
remove_existing: bool = False) -> None:
for name, obj in logging.Logger.manager.loggerDict.items():
if remove_existing:
obj.handlers = []
obj.addHandler(handler) | Applies a handler to all logs, optionally removing existing handlers.
Should ONLY be called from the ``if __name__ == 'main'`` script;
see https://docs.python.org/3.4/howto/logging.html#library-config.
Generally MORE SENSIBLE just to apply a handler to the root logger.
Args:
handler: the hand... |
383,248 | def _save_or_update(self):
with self._resource_lock:
if not self._config or not self._config._storage_path:
raise Exception("self._config._storage path is undefined")
if not self._config._base_name:
raise Exception("self._config._base_name is unde... | Save or update the private state needed by the cloud provider. |
383,249 | def by_image_seq(blocks, image_seq):
return list(filter(lambda block: blocks[block].ec_hdr.image_seq == image_seq, blocks)) | Filter blocks to return only those associated with the provided image_seq number.
Argument:
List:blocks -- List of block objects to sort.
Int:image_seq -- image_seq number found in ec_hdr.
Returns:
List -- List of block indexes matching image_seq number. |
383,250 | def subscribe_to_events(config, subscriber, events, model=None):
kwargs = {}
if model is not None:
kwargs[] = model
for evt in events:
config.add_subscriber(subscriber, evt, **kwargs) | Helper function to subscribe to group of events.
:param config: Pyramid contig instance.
:param subscriber: Event subscriber function.
:param events: Sequence of events to subscribe to.
:param model: Model predicate value. |
383,251 | def ssh_cmd(self, name, ssh_command):
if not self.container_exists(name=name):
exit("Unknown container {0}".format(name))
if not self.container_running(name=name):
exit("Container {0} is not running".format(name))
ip = self.get_container_ip(name)
if not... | SSH into given container and executre command if given |
383,252 | def open_bucket(bucket_name,
aws_access_key_id=None, aws_secret_access_key=None,
aws_profile=None):
session = boto3.session.Session(
profile_name=aws_profile,
aws_access_key_id=aws_access_key_id,
aws_secret_access_key=aws_secret_access_key)
s3 = sessi... | Open an S3 Bucket resource.
Parameters
----------
bucket_name : `str`
Name of the S3 bucket.
aws_access_key_id : `str`, optional
The access key for your AWS account. Also set
``aws_secret_access_key``.
aws_secret_access_key : `str`, optional
The secret key for your A... |
383,253 | def detrend(arr, x=None, deg=5, tol=1e-3, maxloop=10):
xx = numpy.arange(len(arr)) if x is None else x
base = arr.copy()
trend = base
pol = numpy.ones((deg + 1,))
for _ in range(maxloop):
pol_new = numpy.polyfit(xx, base, deg)
pol_norm = numpy.linalg.norm(pol)
diff_pol_... | Compute a baseline trend of a signal |
383,254 | def refresh(self):
r = self._client.request(, self.url)
return self._deserialize(r.json(), self._manager) | Refresh this model from the server.
Updates attributes with the server-defined values. This is useful where the Model
instance came from a partial response (eg. a list query) and additional details
are required.
Existing attribute values will be overwritten. |
383,255 | def update_host_datetime(host, username, password, protocol=None, port=None, host_names=None):
**[esxi-1.host.com, esxi-2.host.com]
service_instance = salt.utils.vmware.get_service_instance(host=host,
username=username,
... | Update the date/time on the given host or list of host_names. This function should be
used with caution since network delays and execution delays can result in time skews.
host
The location of the host.
username
The username used to login to the host, such as ``root``.
password
... |
383,256 | def send_file(self, fp, headers=None, cb=None, num_cb=10,
query_args=None, chunked_transfer=False, size=None):
provider = self.bucket.connection.provider
try:
spos = fp.tell()
except IOError:
spos = None
self.read_from_stream = False... | Upload a file to a key into a bucket on S3.
:type fp: file
:param fp: The file pointer to upload. The file pointer must point
point at the offset from which you wish to upload.
ie. if uploading the full file, it should point at the
start of the f... |
383,257 | def _list_metric_descriptors(args, _):
project_id = args[]
pattern = args[] or
descriptors = gcm.MetricDescriptors(project_id=project_id)
dataframe = descriptors.as_dataframe(pattern=pattern)
return _render_dataframe(dataframe) | Lists the metric descriptors in the project. |
383,258 | def bootstrap_paginate(parser, token):
bits = token.split_contents()
if len(bits) < 2:
raise TemplateSyntaxError(" takes at least one argument"
" (Page object reference)" % bits[0])
page = parser.compile_filter(bits[1])
kwargs = {}
bits = bits[2:]
... | Renders a Page object as a Twitter Bootstrap styled pagination bar.
Compatible with Bootstrap 3.x and 4.x only.
Example::
{% bootstrap_paginate page_obj range=10 %}
Named Parameters::
range - The size of the pagination bar (ie, if set to 10 then, at most,
10 page numbers... |
383,259 | def get_countries(is_legacy_xml=False):
countries = {}
if sys.platform == and getattr(sys, , False):
data_dir = path.dirname(sys.executable)
else:
data_dir = path.dirname(__file__)
if is_legacy_xml:
log.debug(.format(
str(data_dir) + ))
... | The function to generate a dictionary containing ISO_3166-1 country codes
to names.
Args:
is_legacy_xml (:obj:`bool`): Whether to use the older country code
list (iso_3166-1_list_en.xml).
Returns:
dict: A mapping of country codes as the keys to the country names as
... |
383,260 | def get_romfile_path(game, inttype=Integrations.DEFAULT):
for extension in EMU_EXTENSIONS.keys():
possible_path = get_file_path(game, "rom" + extension, inttype)
if possible_path:
return possible_path
raise FileNotFoundError("No romfiles found for game: %s" % game) | Return the path to a given game's romfile |
383,261 | def mac_address_table_static_mac_address(self, **kwargs):
config = ET.Element("config")
mac_address_table = ET.SubElement(config, "mac-address-table", xmlns="urn:brocade.com:mgmt:brocade-mac-address-table")
static = ET.SubElement(mac_address_table, "static")
forward_key = ET.Sub... | Auto Generated Code |
383,262 | def send_wrapped(self, text):
lines = word_wrap(text, self.columns)
for line in lines:
self.send_cc(line + ) | Send text padded and wrapped to the user's screen width. |
383,263 | def date_this_century(self, before_today=True, after_today=False):
today = date.today()
this_century_start = date(today.year - (today.year % 100), 1, 1)
next_century_start = date(this_century_start.year + 100, 1, 1)
if before_today and after_today:
return self.date_... | Gets a Date object for the current century.
:param before_today: include days in current century before today
:param after_today: include days in current century after today
:example Date('2012-04-04')
:return Date |
383,264 | def char(self, c: str) -> None:
if self.peek() == c:
self.offset += 1
else:
raise UnexpectedInput(self, f"char ") | Parse the specified character.
Args:
c: One-character string.
Raises:
EndOfInput: If past the end of `self.input`.
UnexpectedInput: If the next character is different from `c`. |
383,265 | def import_locations(self, gpx_file):
self._gpx_file = gpx_file
data = utils.prepare_xml_read(gpx_file, objectify=True)
try:
self.metadata.import_metadata(data.metadata)
except AttributeError:
pass
for waypoint in data.wpt:
latitude ... | Import GPX data files.
``import_locations()`` returns a list with :class:`~gpx.Waypoint`
objects.
It expects data files in GPX format, as specified in `GPX 1.1 Schema
Documentation`_, which is XML such as::
<?xml version="1.0" encoding="utf-8" standalone="no"?>
... |
383,266 | def is_reversible(P):
import msmtools.analysis as msmana
sets = connected_sets(P, strong=False)
for s in sets:
Ps = P[s, :][:, s]
if not msmana.is_transition_matrix(Ps):
return False
pi = msmana.stationary_distribution(Ps)
X = pi[:, None] * Ps
... | Returns if P is reversible on its weakly connected sets |
383,267 | def get_operation_pattern(server_url, request_url_pattern):
if server_url[-1] == "/":
server_url = server_url[:-1]
if is_absolute(server_url):
return request_url_pattern.replace(server_url, "", 1)
return path_qs(request_url_pattern).replace(server_url, "", 1) | Return an updated request URL pattern with the server URL removed. |
383,268 | def create_mon_path(path, uid=-1, gid=-1):
if not os.path.exists(path):
os.makedirs(path)
os.chown(path, uid, gid); | create the mon path if it does not exist |
383,269 | def get_first_comments_or_remarks(recID=-1,
ln=CFG_SITE_LANG,
nb_comments=,
nb_reviews=,
voted=-1,
reported=-1,
user... | Gets nb number comments/reviews or remarks.
In the case of comments, will get both comments and reviews
Comments and remarks sorted by most recent date, reviews sorted by highest helpful score
:param recID: record id
:param ln: language
:param nb_comments: number of comment or remarks to get
:pa... |
383,270 | async def set_failover_mode(mode):
jar = aiohttp.CookieJar(unsafe=True)
websession = aiohttp.ClientSession(cookie_jar=jar)
try:
modem = eternalegypt.Modem(hostname=sys.argv[1], websession=websession)
await modem.login(password=sys.argv[2])
await modem.set_failover_mode(mode)
... | Example of printing the current upstream. |
383,271 | def seektime(self, disk):
args = {
: disk,
}
self._seektime_chk.check(args)
return self._client.json("disk.seektime", args) | Gives seek latency on disk which is a very good indication to the `type` of the disk.
it's a very good way to verify if the underlying disk type is SSD or HDD
:param disk: disk path or name (/dev/sda, or sda)
:return: a dict as follows {'device': '<device-path>', 'elapsed': <seek-time in us', '... |
383,272 | def bootstrapping_dtrajs(dtrajs, lag, N_full, nbs=10000, active_set=None):
Q = len(dtrajs)
if active_set is not None:
N = active_set.size
else:
N = N_full
traj_ind = []
state1 = []
state2 = []
q = 0
for traj in dtrajs:
traj_ind.append(q*np.one... | Perform trajectory based re-sampling.
Parameters
----------
dtrajs : list of discrete trajectories
lag : int
lag time
N_full : int
Number of states in discrete trajectories.
nbs : int, optional
Number of bootstrapping samples
active_set : ndarray
Indices of... |
383,273 | def file_md5(self, resource):
warnings.warn(
"file_md5 is deprecated; use resource_md5 instead",
DeprecationWarning, stacklevel=2)
return self.resource_md5(resource) | Deprecated alias for *resource_md5*. |
383,274 | def enterEvent(self, event):
super(XViewPanelItem, self).enterEvent(event)
self._hovered = True
self.update() | Mark the hovered state as being true.
:param event | <QtCore.QEnterEvent> |
383,275 | def reboot(name, call=None):
action
datacenter_id = get_datacenter_id()
conn = get_conn()
node = get_node(conn, name)
conn.reboot_server(datacenter_id=datacenter_id, server_id=node[])
return True | reboot a machine by name
:param name: name given to the machine
:param call: call value in this case is 'action'
:return: true if successful
CLI Example:
.. code-block:: bash
salt-cloud -a reboot vm_name |
383,276 | def _get(self, uri, params=None, headers=None):
if not headers:
headers = self._get_headers()
logging.debug("URI=" + str(uri))
logging.debug("HEADERS=" + str(headers))
response = self.session.get(uri, headers=headers, params=params)
logging.debug("STATUS=" ... | Simple GET request for a given path. |
383,277 | def create_install_template_skin(self):
ckan_extension_template(self.name, self.target)
self.install_package_develop( + self.name + ) | Create an example ckan extension for this environment and install it |
383,278 | def to_xdr_object(self):
selling = self.selling.to_xdr_object()
buying = self.buying.to_xdr_object()
price = Operation.to_xdr_price(self.price)
price = Xdr.types.Price(price[], price[])
amount = Operation.to_xdr_amount(self.amount)
create_passive_offer_op = Xd... | Creates an XDR Operation object that represents this
:class:`CreatePassiveOffer`. |
383,279 | def email_domain_disposable(value):
domain = helpers.get_domain_from_email_address(value)
if domain.lower() in disposable_domains:
raise ValidationError(MESSAGE_USE_COMPANY_EMAIL) | Confirms that the email address is not using a disposable service.
@param {str} value
@returns {None}
@raises AssertionError |
383,280 | def get_tags(self):
j, _ = self.datacenter.request(, self.path + )
return j | ::
GET /:login/machines/:id/tags
:Returns: complete set of tags for this machine
:rtype: :py:class:`dict`
A local copy is not kept because these are essentially search keys. |
383,281 | def delete_location(self, location_name):
location = self.find_by_name(location_name, self.locations)
if not location:
return False
sites = location.sites
self.locations.remove(location)
for site in sites:
if site:
site.location = ... | Remove location with name location_name from self.locations.
If the location had any sites, change site.location to "". |
383,282 | def get(self, remote, local=None):
if isinstance(local, file_type):
local_file = local
elif local is None:
local_file = buffer_type()
else:
local_file = open(local, )
self.conn.retrbinary("RETR %s" % remote, local_file.write)
i... | Gets the file from FTP server
local can be:
a file: opened for writing, left open
a string: path to output file
None: contents are returned |
383,283 | def expiry_time(ns, cavs):
prefix = ns.resolve(STD_NAMESPACE)
time_before_cond = condition_with_prefix(
prefix, COND_TIME_BEFORE)
t = None
for cav in cavs:
if not cav.first_party():
continue
cav = cav.caveat_id_bytes.decode()
name, rest = parse_caveat(cav... | Returns the minimum time of any time-before caveats found
in the given list or None if no such caveats were found.
The ns parameter is
:param ns: used to determine the standard namespace prefix - if
the standard namespace is not found, the empty prefix is assumed.
:param cavs: a list of pymacaroons... |
383,284 | def Enumerate():
hid_guid = GUID()
hid.HidD_GetHidGuid(ctypes.byref(hid_guid))
devices = setupapi.SetupDiGetClassDevsA(
ctypes.byref(hid_guid), None, None, 0x12)
index = 0
interface_info = DeviceInterfaceData()
interface_info.cbSize = ctypes.sizeof(DeviceInterfaceData)
out =... | See base class. |
383,285 | def _get_socket_addresses(self):
family = socket.AF_UNSPEC
if not socket.has_ipv6:
family = socket.AF_INET
try:
addresses = socket.getaddrinfo(self._parameters[],
self._parameters[], family,
... | Get Socket address information.
:rtype: list |
383,286 | def _compose_chapters(self):
for count in range(self.chapter_count):
chapter_num = count + 1
c = Chapter(self.markov, chapter_num)
self.chapters.append(c) | Creates a chapters
and appends them to list |
383,287 | def iter_markers(self):
marker_finder = _MarkerFinder.from_stream(self._stream)
start = 0
marker_code = None
while marker_code != JPEG_MARKER_CODE.EOI:
marker_code, segment_offset = marker_finder.next(start)
marker = _MarkerFactory(
marker... | Generate a (marker_code, segment_offset) 2-tuple for each marker in
the JPEG *stream*, in the order they occur in the stream. |
383,288 | def _deep_value(*args, **kwargs):
node, keys = args[0], args[1:]
for key in keys:
node = node.get(key, {})
default = kwargs.get(, {})
if node in ({}, [], None):
node = default
return node | Drills down into tree using the keys |
383,289 | def row_contributions(self, X):
utils.validation.check_is_fitted(self, )
return np.square(self.row_coordinates(X)).div(self.eigenvalues_, axis=) | Returns the row contributions towards each principal component.
Each row contribution towards each principal component is equivalent to the amount of
inertia it contributes. This is calculated by dividing the squared row coordinates by the
eigenvalue associated to each principal component. |
383,290 | def unpickler(zone, utcoffset=None, dstoffset=None, tzname=None):
tz = pytz.timezone(zone)
if utcoffset is None:
return tz
utcoffset = memorized_timedelta(utcoffset)
dstoffset = memorized_timedelta(dstoffset)
try:
return tz._tzinfos[(utcoffse... | Factory function for unpickling pytz tzinfo instances.
This is shared for both StaticTzInfo and DstTzInfo instances, because
database changes could cause a zones implementation to switch between
these two base classes and we can't break pickles on a pytz version
upgrade. |
383,291 | def save(self, filename, format=None):
if format is None:
if filename.endswith((, )):
format =
elif filename.endswith(()):
format =
else:
format =
else:
if format is :
if not file... | Save the SFrame to a file system for later use.
Parameters
----------
filename : string
The location to save the SFrame. Either a local directory or a
remote URL. If the format is 'binary', a directory will be created
at the location which will contain the sf... |
383,292 | def add_identity_parser(subparsers, parent_parser):
parser = subparsers.add_parser(
,
help=,
description=)
identity_parsers = parser.add_subparsers(
title="subcommands",
dest="subcommand")
identity_parsers.required = True
policy_parser = identity... | Creates the arg parsers needed for the identity command and
its subcommands. |
383,293 | def _isinstance(expr, classname):
for cls in type(expr).__mro__:
if cls.__name__ == classname:
return True
return False | Check whether `expr` is an instance of the class with name
`classname`
This is like the builtin `isinstance`, but it take the `classname` a
string, instead of the class directly. Useful for when we don't want to
import the class for which we want to check (also, remember that
pr... |
383,294 | def _watchdog_queue(self):
while not self.quit:
k = self.queue.get()
if k == :
self.quit = True
self.switch_queue.put() | 从queue里取出字符执行命令 |
383,295 | def _SGraphFromJsonTree(json_str):
g = json.loads(json_str)
vertices = [_Vertex(x[],
dict([(str(k), v) for k, v in _six.iteritems(x) if k != ]))
for x in g[]]
edges = [_Edge(x[], x[],
dict([(str(k), v) for k, v in _six.i... | Convert the Json Tree to SGraph |
383,296 | def generate_payload(self, config=None, context=None):
for name, plugin in iteritems(self._registered):
if plugin.supports(config, context):
logger.debug( % name)
return plugin.generate_payload(config, context)
logger.debug()
return {
... | Generate payload by iterating over registered plugins. Merges .
:param context: current context.
:param config: honeybadger configuration.
:return: a dict with the generated payload. |
383,297 | def __make_id(receiver):
if __is_bound_method(receiver):
return (id(receiver.__func__), id(receiver.__self__))
return id(receiver) | Generate an identifier for a callable signal receiver.
This is used when disconnecting receivers, where we need to correctly
establish equivalence between the input receiver and the receivers assigned
to a signal.
Args:
receiver: A callable object.
Returns:
An identifier for the r... |
383,298 | def do_authorization(self, transactionid, amt):
args = self._sanitize_locals(locals())
return self._call(, **args) | Shortcut for the DoAuthorization method.
Use the TRANSACTIONID from DoExpressCheckoutPayment for the
``transactionid``. The latest version of the API does not support the
creation of an Order from `DoDirectPayment`.
The `amt` should be the same as passed to `DoExpressCheckoutPayment`.
... |
383,299 | def __detect_os_identity_api_version(self):
ver = os.getenv(, )
if ver == :
log.debug(
"Using OpenStack Identity API v3"
" because of environmental variable setting `OS_IDENTITY_API_VERSION=3`")
return
elif ver == or ver.startswi... | Return preferred OpenStack Identity API version (either one of the two strings ``'2'`` or ``'3'``) or ``None``.
The following auto-detection strategies are tried (in this order):
#. Read the environmental variable `OS_IDENTITY_API_VERSION` and check if its value is one of the two strings ``'2'`` or ``... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.