Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
18,900 | def paint(str,color=):
r
if color in switcher:
str = switcher[color]+str+colorama.Style.RESET_ALL
return str | Utility func, for printing colorful logs in console...
@args:
--
str : String to be modified.
color : color code to which the string will be formed. default is 'r'=RED
@returns:
--
str : final modified string with foreground color as per parameters. |
18,901 | def lomb_scargle_fast(t, y, dy=1, f0=0, df=None, Nf=None,
center_data=True, fit_offset=True,
use_fft=True, freq_oversampling=5, nyquist_factor=2,
trig_sum_kwds=None):
t, y, dy = map(np.ravel, np.broadcast_arrays(t, y, dy))
w = 1. / (dy ... | Compute a lomb-scargle periodogram for the given data
This implements both an O[N^2] method if use_fft==False, or an
O[NlogN] method if use_fft==True.
Parameters
----------
t, y, dy : array_like
times, values, and errors of the data points. These should be
broadcastable to the same... |
18,902 | def open_repository(path, spor_dir=):
root = _find_root_dir(path, spor_dir)
return Repository(root, spor_dir) | Open an existing repository.
Args:
path: Path to any file or directory within the repository.
spor_dir: The name of the directory containing spor data.
Returns: A `Repository` instance.
Raises:
ValueError: No repository is found. |
18,903 | def draw(self, drawDC=None):
DEBUG_MSG("draw()", 1, self)
self.renderer = RendererWx(self.bitmap, self.figure.dpi)
self.figure.draw(self.renderer)
self._isDrawn = True
self.gui_repaint(drawDC=drawDC) | Render the figure using RendererWx instance renderer, or using a
previously defined renderer if none is specified. |
18,904 | def get_username(details, backend, response, *args, **kwargs):
user = details.get()
if not user:
user_uuid = kwargs.get()
if not user_uuid:
return
username = uuid_to_username(user_uuid)
else:
username = user.username
return {
: username
} | Sets the `username` argument.
If the user exists already, use the existing username. Otherwise
generate username from the `new_uuid` using the
`helusers.utils.uuid_to_username` function. |
18,905 | def lf_empirical_accuracies(L, Y):
Y = arraylike_to_numpy(Y)
L = L.toarray()
X = np.where(L == 0, 0, np.where(L == np.vstack([Y] * L.shape[1]).T, 1, -1))
return 0.5 * (X.sum(axis=0) / (L != 0).sum(axis=0) + 1) | Return the **empirical accuracy** against a set of labels Y (e.g. dev
set) for each LF.
Args:
L: an n x m scipy.sparse matrix where L_{i,j} is the label given by the
jth LF to the ith candidate
Y: an [n] or [n, 1] np.ndarray of gold labels |
18,906 | def vcenter_activate(self, **kwargs):
config = ET.Element("config")
vcenter = ET.SubElement(config, "vcenter", xmlns="urn:brocade.com:mgmt:brocade-vswitch")
id_key = ET.SubElement(vcenter, "id")
id_key.text = kwargs.pop()
activate = ET.SubElement(vcenter, "activate")
... | Auto Generated Code |
18,907 | def opt_with_frequency_flattener(cls,
qchem_command,
multimode="openmp",
input_file="mol.qin",
output_file="mol.qout",
qclog_file="mol.... | Optimize a structure and calculate vibrational frequencies to check if the
structure is in a true minima. If a frequency is negative, iteratively
perturbe the geometry, optimize, and recalculate frequencies until all are
positive, aka a true minima has been found.
Args:
qche... |
18,908 | def _assertIndex(self, index):
if type(index) is not int:
raise TypeError()
if index < 0 or index >= self.nelems:
raise IndexError() | Raise TypeError or IndexError if index is not an integer or out of
range for the number of elements in this array, respectively. |
18,909 | def main():
config = Config()
core = HostSearch()
hosts = core.get_hosts(tags=[], up=True)
hosts = [host for host in hosts]
host_ips = ",".join([str(host.address) for host in hosts])
url = config.get(, )
access = config.get(, )
secret = config.get(, )
template_name = config.get... | This function obtains hosts from core and starts a nessus scan on these hosts.
The nessus tag is appended to the host tags. |
18,910 | def get_examples(self, compact=False):
examples = copy.deepcopy(self._examples)
if not compact:
return examples
def make_compact(d):
if not isinstance(d, dict):
return
for key in d:
i... | Returns an OrderedDict mapping labels to Example objects.
Args:
compact (bool): If True, union members of void type are converted
to their compact representation: no ".tag" key or containing
dict, just the tag as a string. |
18,911 | def assign_statement(self):
left = self.variable()
op = self.cur_token
self.eat(TokenTypes.ASSIGN)
right = self.expression()
smt = None
if Features.TYPE_ARRAY in self.features and isinstance(left, GetArrayItem):
smt = SetArrayItem(left.le... | assign smt : variable ASSIGN expression(;)
Feature Type Array adds:
| variable SETITEM expression(;) |
18,912 | def mail_session(self, name, host, username, mail_from, props):
return MailSession(self.__endpoint, name, host, username, mail_from,
props) | Domain mail session.
:param str name:
Mail session name.
:param str host:
Mail host.
:param str username:
Mail username.
:param str mail_from:
Mail "from" address.
:param dict props:
Extra properties.
:rtype:
MailSession |
18,913 | def help_center_article_translation_update(self, article_id, locale, data, **kwargs):
"https://developer.zendesk.com/rest_api/docs/help_center/translations
api_path = "/api/v2/help_center/articles/{article_id}/translations/{locale}.json"
api_path = api_path.format(article_id=article_id, locale=l... | https://developer.zendesk.com/rest_api/docs/help_center/translations#update-translation |
18,914 | def _init_data_map(self):
if self._data_map is None:
self._data_map = {: None}
self._data_map.update({}.fromkeys(self._metadata_props)) | Default data map initialization: MUST be overridden in children |
18,915 | def adb_cmd(self, command, **kwargs):
pull/data/local/tmp/a.png
kwargs[] = kwargs.get(, self._adb_shell_timeout)
if isinstance(command, list) or isinstance(command, tuple):
return self.adb_device.run_cmd(*list(command), **kwargs)
return self.adb_device.run_cmd(command, **kwar... | Run adb command, for example: adb(['pull', '/data/local/tmp/a.png'])
Args:
command: string or list of string
Returns:
command output |
18,916 | def dos_plot_data(self, yscale=1, xmin=-6., xmax=6., colours=None,
plot_total=True, legend_cutoff=3, subplot=False,
zero_to_efermi=True, cache=None):
if cache is None:
cache = colour_cache
dos = self._dos
pdos = self._pdo... | Get the plotting data.
Args:
yscale (:obj:`float`, optional): Scaling factor for the y-axis.
xmin (:obj:`float`, optional): The minimum energy to mask the
energy and density of states data (reduces plotting load).
xmax (:obj:`float`, optional): The maximum en... |
18,917 | async def shuffle_participants(self):
res = await self.connection(, .format(self._id))
self._refresh_participants_from_json(res) | Shuffle participants' seeds
|methcoro|
Note:
|from_api| Randomize seeds among participants. Only applicable before a tournament has started.
Raises:
APIException |
18,918 | def process_response(self, request, response):
add_never_cache_headers(response)
if not hasattr(request, ) or not request._cache_update_cache:
return response
if not response.status_code == 200:
... | Sets the cache, if needed. |
18,919 | def cbpdnmd_xstep(k):
YU0 = mp_Z_Y0[k] + mp_S[k] - mp_Z_U0[k]
YU1 = mp_Z_Y1[k] - mp_Z_U1[k]
if mp_cri.Cd == 1:
b = np.conj(mp_Df) * sl.rfftn(YU0, None, mp_cri.axisN) + \
sl.rfftn(YU1, None, mp_cri.axisN)
Xf = sl.solvedbi_sm(mp_Df, 1.0, b, axis=mp_cri.axisM)
else:
... | Do the X step of the cbpdn stage. The only parameter is the slice
index `k` and there are no return values; all inputs and outputs are
from and to global variables. |
18,920 | def stops(freq, interval=1, count=None, wkst=None, bysetpos=None,
bymonth=None, bymonthday=None, byyearday=None, byeaster=None,
byweekno=None, byweekday=None, byhour=None, byminute=None,
bysecond=None, timezone=, start=None, stop=None):
if all([(start is None or is_datet... | This will create a list of delorean objects the apply to
setting possed in. |
18,921 | def ch_duration(self, *channels: List[Channel]) -> int:
return self.timeslots.ch_duration(*channels) | Return duration of supplied channels.
Args:
*channels: Supplied channels |
18,922 | def tracked(self, tag=None, fromdate=None, todate=None):
return self.call("GET", "/stats/outbound/tracked", tag=tag, fromdate=fromdate, todate=todate) | Gets a total count of emails you’ve sent with open tracking or link tracking enabled. |
18,923 | def _copy_hdxobjects(self, hdxobjects, hdxobjectclass, attribute_to_copy=None):
newhdxobjects = list()
for hdxobject in hdxobjects:
newhdxobjectdata = copy.deepcopy(hdxobject.data)
newhdxobject = hdxobjectclass(newhdxobjectdata, configuration=self.configuration)... | Helper function to make a deep copy of a supplied list of HDX objects
Args:
hdxobjects (List[T <= HDXObject]): list of HDX objects to copy
hdxobjectclass (type): Type of the HDX Objects to be copied
attribute_to_copy (Optional[str]): An attribute to copy over from the HDX ob... |
18,924 | def _gatherLookupIndexes(gpos):
kernFeatureIndexes = [index for index, featureRecord in enumerate(gpos.FeatureList.FeatureRecord) if featureRecord.FeatureTag == "kern"]
scriptKernFeatureIndexes = {}
for scriptRecord in gpos.ScriptList.ScriptRecord:
script = scriptRecord.ScriptTag
... | Gather a mapping of script to lookup indexes
referenced by the kern feature for each script.
Returns a dictionary of this structure:
{
"latn" : [0],
"DFLT" : [0]
} |
18,925 | def series64bitto32bit(s):
if s.dtype == np.float64:
return s.astype()
elif s.dtype == np.int64:
return s.astype()
return s | Convert a Pandas series from 64 bit types to 32 bit types to save
memory or disk space.
Parameters
----------
s : The series to convert
Returns
-------
The converted series |
18,926 | def makestate(im, pos, rad, slab=None, mem_level=):
if slab is not None:
o = comp.ComponentCollection(
[
objs.PlatonicSpheresCollection(pos, rad, zscale=zscale),
slab
],
category=
)
else:
o =... | Workhorse for creating & optimizing states with an initial centroid
guess.
This is an example function that works for a particular microscope. For
your own microscope, you'll need to change particulars such as the psf
type and the orders of the background and illumination.
Parameters
---------... |
18,927 | def get_personal_module(self):
return PersonalModule(
layout=,
draggable=False,
deletable=False,
collapsible=False,
) | Instantiate the :class:`~fluent_dashboard.modules.PersonalModule` for use in the dashboard. |
18,928 | def evalSamples(self, x):
self._N_dv = len(_makeIter(x))
if self.verbose:
print()
if self.surrogate is None:
def fqoi(u):
return self.fqoi(x, u)
def fgrad(u):
return self.jac(x, u)
jac = self.ja... | Evalautes the samples of quantity of interest and its gradient
(if supplied) at the given values of the design variables
:param iterable x: values of the design variables, this is passed as
the first argument to the function fqoi
:return: (values of the quantity of interest, values... |
18,929 | def user_admin_urlname(action):
user = get_user_model()
return % (
user._meta.app_label, user._meta.model_name,
action) | Return the admin URLs for the user app used. |
18,930 | def train_local(self, closest_point, label_vector_description=None, N=None,
pivot=True, **kwargs):
lv = self._cannon_label_vector if label_vector_description is None else\
self._interpret_label_vector(label_vector_description)
if N is None:
N ... | Train the model in a Cannon-like fashion using the grid points as labels
and the intensities as normalsied rest-frame fluxes within some local
regime. |
18,931 | def loadFromDisk(self, calculation):
suffixes = {
: ,
: ,
: ,
: ,
: ,
: ,
: ,
}
self.raw = list()
for spectrumName in self.toPlot:
suffix = suffixes[spectrumName]
path =... | Read the spectra from the files generated by Quanty and store them
as a list of spectum objects. |
18,932 | def get_template(self, R):
centers, widths = self.init_centers_widths(R)
template_prior =\
np.zeros(self.K * (self.n_dim + 2 + self.cov_vec_size))
template_centers_cov = np.cov(R.T) * math.pow(self.K, -2 / 3.0)
template_widths_var = self._get_max_sigma(R)
... | Compute a template on latent factors
Parameters
----------
R : 2D array, in format [n_voxel, n_dim]
The scanner coordinate matrix of one subject's fMRI data
Returns
-------
template_prior : 1D array
The template prior.
template_centers_c... |
18,933 | def visdom_send_metrics(vis, metrics, update=):
visited = {}
sorted_metrics = sorted(metrics.columns, key=_column_original_name)
for metric_basename, metric_list in it.groupby(sorted_metrics, key=_column_original_name):
metric_list = list(metric_list)
for metric in metric_list:
... | Send set of metrics to visdom |
18,934 | def bookmark(ctx):
user, project_name, _group = get_project_group_or_local(ctx.obj.get(),
ctx.obj.get())
try:
PolyaxonClient().experiment_group.bookmark(user, project_name, _group)
except (PolyaxonHTTPError, PolyaxonShouldExitError, P... | Bookmark group.
Uses [Caching](/references/polyaxon-cli/#caching)
Examples:
\b
```bash
$ polyaxon group bookmark
```
\b
```bash
$ polyaxon group -g 2 bookmark
``` |
18,935 | def maskedEqual(array, missingValue):
if array_is_structured(array):
if not isinstance(array, ma.MaskedArray):
array = ma.MaskedArray(array)
for nr, field in enumerate(array.dtype.names):
if hasattr(missingValue, ):
fieldMissingValue = ... | Mask an array where equal to a given (missing)value.
Unfortunately ma.masked_equal does not work with structured arrays. See:
https://mail.scipy.org/pipermail/numpy-discussion/2011-July/057669.html
If the data is a structured array the mask is applied for every field (i.e. forming a
lo... |
18,936 | def __decrypt_assertion(self, dom):
key = self.__settings.get_sp_key()
debug = self.__settings.is_debug_active()
if not key:
raise OneLogin_Saml2_Error(
,
OneLogin_Saml2_Error.PRIVATE_KEY_NOT_FOUND
)
encrypted_assertion_n... | Decrypts the Assertion
:raises: Exception if no private key available
:param dom: Encrypted Assertion
:type dom: Element
:returns: Decrypted Assertion
:rtype: Element |
18,937 | def properties_from_mapping(self, bt_addr):
for addr, properties in self.eddystone_mappings:
if addr == bt_addr:
return properties
return None | Retrieve properties (namespace, instance) for the specified bt address. |
18,938 | def Decode(self, encoded_data):
try:
decoded_data = base64.b64decode(encoded_data)
except (TypeError, binascii.Error) as exception:
raise errors.BackEndError(
.format(
exception))
return decoded_data, b | Decode the encoded data.
Args:
encoded_data (byte): encoded data.
Returns:
tuple(bytes, bytes): decoded data and remaining encoded data.
Raises:
BackEndError: if the base64 stream cannot be decoded. |
18,939 | def fromfuncs(funcs, n_sessions, eqdata, **kwargs):
_skipatstart = kwargs.get(, 0)
_constfeat = kwargs.get(, True)
_outcols = [] if _constfeat else []
_n_allrows = len(eqdata.index)
_n_featrows = _n_allrows - _skipatstart - n_sessions + 1
for _func in funcs:
_outcols += map(partial(... | Generate features using a list of functions to apply to input data
Parameters
----------
funcs : list of function
Functions to apply to eqdata. Each function is expected
to output a dataframe with index identical to a slice of `eqdata`.
The slice must include at least `eqdata.index[... |
18,940 | def _F(self, X):
if isinstance(X, int) or isinstance(X, float):
if X < 1 and X > 0:
a = 1/(X**2-1)*(1-2/np.sqrt(1-X**2)*np.arctanh(np.sqrt((1-X)/(1+X))))
elif X == 1:
a = 1./3
elif X > 1:
a = 1/(X**2-1)*(1-2/np.sqrt(X**... | analytic solution of the projection integral
:param x: R/Rs
:type x: float >0 |
18,941 | def _is_unpacked_egg(path):
return (
_is_egg_path(path) and
os.path.isfile(os.path.join(path, , ))
) | Determine if given path appears to be an unpacked egg. |
18,942 | def remove(self):
title = % self.__class__.__name__
for id, name, mimetype in self._list_directory():
try:
self.drive.delete(fileId=id).execute()
except Exception as err:
if str(err).find() > -1:
pa... | a method to remove all records in the collection
NOTE: this method removes all the files in the collection, but the
collection folder itself created by oauth2 cannot be removed.
only the user can remove access to the app folder
:return: string with con... |
18,943 | def load_raw(path):
_import_pil()
from PIL import Image
return np.array(Image.open(path)) | Load image using PIL/Pillow without any processing. This is particularly
useful for palette images, which will be loaded using their palette index
values as opposed to `load` which will convert them to RGB.
Parameters
----------
path : str
Path to image file. |
18,944 | def _broadcast_arg(U, arg, argtype, name):
if arg is None or isinstance(arg, argtype):
return [arg for _ in range(U.ndim)]
elif np.iterable(arg):
if len(arg) != U.ndim:
raise ValueError(
... | Broadcasts plotting option `arg` to all factors.
Args:
U : KTensor
arg : argument provided by the user
argtype : expected type for arg
name : name of the variable, used for error handling
Returns:
iterable version of arg of length U.ndim |
18,945 | def to_decimal(self):
high = self.__high
low = self.__low
sign = 1 if (high & _SIGN) else 0
if (high & _SNAN) == _SNAN:
return decimal.Decimal((sign, (), ))
elif (high & _NAN) == _NAN:
return decimal.Decimal((sign, (), ))
elif (high & _IN... | Returns an instance of :class:`decimal.Decimal` for this
:class:`Decimal128`. |
18,946 | def text(self):
return self.template.format(name=self.name, type=self.type) | Formatted param definition
Equivalent to ``self.template.format(name=self.name, type=self.type)``. |
18,947 | def _inputrc_enables_vi_mode():
for filepath in (os.path.expanduser(), ):
try:
with open(filepath) as f:
for line in f:
if _setre.fullmatch(line):
return True
except IOError:
continue
return False | Emulate a small bit of readline behavior.
Returns:
(bool) True if current user enabled vi mode ("set editing-mode vi") in .inputrc |
18,948 | def _get_tcntobj(goids, go2obj, **kws):
if in kws or in kws:
_gosubdag = GoSubDag(goids, go2obj, rcntobj=False, prt=None)
return get_tcntobj(_gosubdag.go2obj, **kws) | Get a TermCounts object if the user provides an annotation file, otherwise None. |
18,949 | def find_vasp_calculations():
dir_list = [ + re.sub( r, , path ) for path in glob.iglob( , recursive=True ) ]
gz_dir_list = [ + re.sub( r, , path ) for path in glob.iglob( , recursive=True ) ]
return dir_list + gz_dir_list | Returns a list of all subdirectories that contain either a vasprun.xml file
or a compressed vasprun.xml.gz file.
Args:
None
Returns:
(List): list of all VASP calculation subdirectories. |
18,950 | def encodeMotorInput(self, motorInput):
if not hasattr(motorInput, "__iter__"):
motorInput = list([motorInput])
return self.motorEncoder.encode(motorInput) | Encode motor command to bit vector.
@param motorInput (1D numpy.array)
Motor command to be encoded.
@return (1D numpy.array)
Encoded motor command. |
18,951 | def db_dp990(self, value=None):
if value is not None:
try:
value = float(value)
except ValueError:
raise ValueError(
.format(value))
self._db_dp990 = value | Corresponds to IDD Field `db_dp990`
mean coincident drybulb temperature corresponding to
Dew-point temperature corresponding to 90.0% annual cumulative
frequency of occurrence (cold conditions)
Args:
value (float): value for IDD Field `db_dp990`
Unit: C
... |
18,952 | def get_token_settings(cls, token, default=None):
setting_dict = {}
for key, value in iteritems(cls.__dict__):
if % token in key and not callable(key) and not isinstance(value, tokens.TokenAttr):
setting_dict[key] = cls.__dict__.get(key, default)
return set... | Get the value for a specific token as a dictionary or replace with default
:param token: str, token to query the nomenclate for
:param default: object, substitution if the token is not found
:return: (dict, object, None), token setting dictionary or default |
18,953 | def to_equivalent(self, unit, equivalence, **kwargs):
conv_unit = Unit(unit, registry=self.units.registry)
if self.units.same_dimensions_as(conv_unit):
return self.in_units(conv_unit)
this_equiv = equivalence_registry[equivalence]()
if self.has_equivalent(equivalence... | Return a copy of the unyt_array in the units specified units, assuming
the given equivalency. The dimensions of the specified units and the
dimensions of the original array need not match so long as there is an
appropriate conversion in the specified equivalency.
Parameters
----... |
18,954 | def get_likes(self, likable_type, likable_id):
return _get_request(_LIKES.format(c_api=_C_API_BEGINNING,
api=_API_VERSION,
lt=likable_type,
li=likable_id,
... | likable_type: 'Comment', 'Press', 'Review', 'StartupRole', 'StatusUpdate'
likable_id: id of the object that the likes of it you are interested |
18,955 | def start(self, interval=None, iterations=None):
if self.running:
return | Start the timer.
A timeout event will be generated every *interval* seconds.
If *interval* is None, then self.interval will be used.
If *iterations* is specified, the timer will stop after
emitting that number of events. If unspecified, then
the previous value of self.iteration... |
18,956 | def Laliberte_density_i(T, w_w, c0, c1, c2, c3, c4):
r7647-14-5
t = T - 273.15
return ((c0*(1 - w_w)+c1)*exp(1E-6*(t + c4)**2))/((1 - w_w) + c2 + c3*t) | r'''Calculate the density of a solute using the form proposed by Laliberte [1]_.
Parameters are needed, and a temperature, and water fraction. Units are Kelvin and Pa*s.
.. math::
\rho_{app,i} = \frac{(c_0[1-w_w]+c_1)\exp(10^{-6}[t+c_4]^2)}
{(1-w_w) + c_2 + c_3 t}
Parameters
----------... |
18,957 | def version(self):
if self._version != :
return self._version
if self._version == :
try:
data = self.execute_get()
self._version = data[][0][]
except GhostException:
return self.DEFAULT_VERSION
return... | :return: The version of the server when initialized as 'auto',
otherwise the version passed in at initialization |
18,958 | def instruction_DEC_register(self, opcode, register):
a = register.value
r = self.DEC(a)
register.set(r) | Decrement accumulator |
18,959 | def create_client_socket(self, config):
client_socket = WUDPNetworkNativeTransport.create_client_socket(self, config)
client_socket.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
return client_socket | Create client broadcast socket
:param config: client configuration
:return: socket.socket |
18,960 | def _drop_oldest_chunk(self):
abcdabcdabcdaeff
chunk_id = min(self.chunked_counts.keys())
chunk = self.chunked_counts.pop(chunk_id)
self.n_counts -= len(chunk)
for k, v in list(chunk.items()):
self.counts[k] -= v
self.counts_total -= v | To handle the case when the items comming in the chunk
is more than the maximum capacity of the chunk. Our intent
behind is to remove the oldest chunk. So that the items come
flowing in.
>>> s = StreamCounter(5,5)
>>> data_stream = ['a','b','c','d']
>>> for item in data_s... |
18,961 | def Place(self, x, flags):
N.enforce_number(x, flags)
self.head = self.head - flags.bytewidth
encode.Write(flags.packer_type, self.Bytes, self.Head(), x) | Place prepends a value specified by `flags` to the Builder,
without checking for available space. |
18,962 | def getParameters(self):
parameters = lock_and_call(
lambda: self._impl.getParameters(),
self._lock
)
return EntityMap(parameters, Parameter) | Get all the parameters declared. |
18,963 | def get_sockaddr(host, port, family):
if family == af_unix:
return host.split("://", 1)[1]
try:
res = socket.getaddrinfo(
host, port, family, socket.SOCK_STREAM, socket.IPPROTO_TCP
)
except socket.gaierror:
return host, port
return res[0][4] | Return a fully qualified socket address that can be passed to
:func:`socket.bind`. |
18,964 | def _aggregations(search, definitions):
if definitions:
for name, agg in definitions.items():
search.aggs[name] = agg if not callable(agg) else agg()
return search | Add aggregations to query. |
18,965 | def categorical_to_numeric(table):
def transform(column):
if is_categorical_dtype(column.dtype):
return column.cat.codes
if column.dtype.char == "O":
try:
nc = column.astype(numpy.int64)
except ValueError:
classes = column.drop... | Encode categorical columns to numeric by converting each category to
an integer value.
Parameters
----------
table : pandas.DataFrame
Table with categorical columns to encode.
Returns
-------
encoded : pandas.DataFrame
Table with categorical columns encoded as numeric.
... |
18,966 | def update_distribution(
name,
config,
tags=None,
region=None,
key=None,
keyid=None,
profile=None,
):
{"Comment":"partial configuration","Enabled":true}
distribution_ret = get_distribution(
name,
region=region,
key=key,
keyid=keyid,
p... | Update the config (and optionally tags) for the CloudFront distribution with the given name.
name
Name of the CloudFront distribution
config
Configuration for the distribution
tags
Tags to associate with the distribution
region
Region to connect to
key
Se... |
18,967 | def write_err(self, text):
stderr = self.stderr
if self.stderr.closed:
stderr = sys.stderr
stderr.write(decode_output(u"\r", target_stream=stderr))
stderr.write(decode_output(CLEAR_LINE, target_stream=stderr))
if text is None:
text = ""
te... | Write error text in the terminal without breaking the spinner. |
18,968 | def ris(self):
if self.aggregationType != :
raise ValueError()
template = u
ris = template.format(
title=self.title, journal=self.publicationName,
volume=self.volume, date=self.coverDate, pages=self.pageRange,
year=self.coverDate[0:4], doi... | Bibliographic entry in RIS (Research Information System Format)
format.
Returns
-------
ris : str
The RIS string representing an item.
Raises
------
ValueError : If the item's aggregationType is not Journal. |
18,969 | def _parse_line(self, line):
msg_info = {: line}
if in line:
info, msg = [i.strip() for i in line.split(, 1)]
msg_info[] = msg
info_splits = info.split()
if len(info_splits) == 5:
msg_info[] = .join(info_splits[:3])
... | Parsed result::
{'timestamp':'May 18 14:24:14',
'procname': 'kernel',
'hostname':'lxc-rhel68-sat56',
'message': '...',
'raw_message': '...: ...'
} |
18,970 | def _traverse(summary, function, *args):
function(summary, *args)
for row in summary:
function(row, *args)
for item in row:
function(item, *args) | Traverse all objects of a summary and call function with each as a
parameter.
Using this function, the following objects will be traversed:
- the summary
- each row
- each item of a row |
18,971 | def create_couchdb_admin(username, password):
curl_couchdb(.format(username),
method=,
data=.format(password)) | Create a CouchDB user |
18,972 | def destroy(self):
widget = self.widget
if widget is not None:
del self.widget
super(UiKitToolkitObject, self).destroy() | A reimplemented destructor.
This destructor will clear the reference to the toolkit widget
and set its parent to None. |
18,973 | def search(self,
query,
category,
uid=None,
latitude=None,
longitude=None,
city=None,
region=None):
if isinstance(category, (tuple, list)):
category = .join(category)
data = opt... | 发送语义理解请求
详情请参考
http://mp.weixin.qq.com/wiki/0/0ce78b3c9524811fee34aba3e33f3448.html
:param query: 输入文本串
:param category: 需要使用的服务类型,多个可传入列表
:param uid: 可选,用户唯一id(非开发者id),用户区分公众号下的不同用户(建议填入用户openid)
:param latitude: 可选,纬度坐标,与经度同时传入;与城市二选一传入
:param longitude: 可选,经度坐... |
18,974 | def synchelp(f):
def wrap(*args, **kwargs):
coro = f(*args, **kwargs)
if not iAmLoop():
return sync(coro)
return coro
return wrap | The synchelp decorator allows the transparent execution of
a coroutine using the global loop from a thread other than
the event loop. In both use cases, teh actual work is done
by the global event loop.
Examples:
Use as a decorator::
@s_glob.synchelp
async def stuff(x... |
18,975 | def get_level(level_string):
levels = {: logging.DEBUG, : logging.INFO,
: logging.WARNING, : logging.ERROR,
: logging.CRITICAL}
try:
level = levels[level_string.lower()]
except KeyError:
sys.exit(.format(level_string))
else:
return level | Returns an appropriate logging level integer from a string name |
18,976 | def is_excluded_path(args, filepath):
for regexp_exclude_path in args.regexp:
if re.match(regexp_exclude_path, filepath):
return True
abspath = os.path.abspath(filepath)
if args.include:
out_of_include_dirs = True
for incl_path in args.include:
... | Returns true if the filepath is under the one of the exclude path. |
18,977 | def add(self, transport, address=None):
if not address:
address = str(uuid.uuid1())
if address in self.recipients:
self.recipients[address].add(transport)
else:
self.recipients[address] = RecipientManager(transport, address)
return address | add a new recipient to be addressable by this MessageDispatcher
generate a new uuid address if one is not specified |
18,978 | def set_options(pool_or_cursor,row_instance):
"for connection-level options that need to be set on Row instances"
for option in (,): setattr(row_instance,option,getattr(pool_or_cursor,option,None))
return row_instance | for connection-level options that need to be set on Row instances |
18,979 | def get_viewer(self, v_id, viewer_class=None, width=512, height=512,
force_new=False):
if not force_new:
try:
return self.viewers[v_id]
except KeyError:
pass
window = self.app.make_window("Viewer %s" % v_id, wi... | Get an existing viewer by viewer id. If the viewer does not yet
exist, make a new one. |
18,980 | def clean_columns(columns, valid_regex=r, lower=True, max_len=32):
rettype = None
if isinstance(columns, str):
rettype = type(columns)
columns = [columns]
columns = [c.strip() for c in columns]
columns = [c[:max_len] for c in columns]
columns = np.array(columns) if re... | Ensure all column name strings are valid python variable/attribute names
>>> df = pd.DataFrame(np.zeros((2, 3)), columns=['WAT??', "Don't do th!s, way too long. ya-think????", 'ok-this123.456'])
>>> df.columns = clean_columns(df.columns, max_len=12)
>>> df.head()
wat dont_do_ths_ okthis123456
... |
18,981 | def compress_to(self, archive_path=None):
if archive_path is None:
archive = tempfile.NamedTemporaryFile(delete=False)
tar_args = ()
tar_kwargs = {: archive}
_return = archive.name
else:
tar_args = (archive_path)
tar_kwargs... | Compress the directory with gzip using tarlib.
:type archive_path: str
:param archive_path: Path to the archive, if None, a tempfile is created |
18,982 | def member(self, phlo_id, node_id,
member_id, action,
node_type=):
data = {
: member_id,
: phlo_id,
: node_id,
: node_type
}
member = Member(self.client, data)
return getattr(member, action)() | :param phlo_id:
:param node_id:
:param member_id:
:param action:
:param node_type: default value `conference_bridge`
:return: |
18,983 | def iter_list_market_book(self, market_ids, chunk_size, **kwargs):
return itertools.chain(*(
self.list_market_book(market_chunk, **kwargs)
for market_chunk in utils.get_chunks(market_ids, chunk_size)
)) | Split call to `list_market_book` into separate requests.
:param list market_ids: List of market IDs
:param int chunk_size: Number of records per chunk
:param dict kwargs: Arguments passed to `list_market_book` |
18,984 | def project(self, project, entity=None):
query = gql()
return self.gql(query, variable_values={
: entity, : project})[] | Retrive project
Args:
project (str): The project to get details for
entity (str, optional): The entity to scope this project to.
Returns:
[{"id","name","repo","dockerImage","description"}] |
18,985 | def _importSNPs_CasavaSNP(setName, species, genomeSource, snpsFile) :
"This function will also create an index on start->chromosomeNumber->setName. Warning : pyGeno positions are 0 based"
printf( % (setName, species))
snpData = SNPsTxtFile(snpsFile)
CasavaSNP.dropIndex((, , ))
conf.db.beginTransaction()
pBar... | This function will also create an index on start->chromosomeNumber->setName. Warning : pyGeno positions are 0 based |
18,986 | def __store_record(self, record):
if isinstance(record, WSimpleTrackerStorage.Record) is False:
raise TypeError()
limit = self.record_limit()
if limit is not None and len(self.__registry) >= limit:
self.__registry.pop(0)
self.__registry.append(record) | Save record in a internal storage
:param record: record to save
:return: None |
18,987 | def generate_matches(self, nodes):
if self.content is None:
for count in xrange(self.min, 1 + min(len(nodes), self.max)):
r = {}
if self.name:
r[self.name] = nodes[:count]
yield count, r
elif self.name ... | Generator yielding matches for a sequence of nodes.
Args:
nodes: sequence of nodes
Yields:
(count, results) tuples where:
count: the match comprises nodes[:count];
results: dict containing named submatches. |
18,988 | def create_alarm(deployment_id, metric_name, data, api_key=None, profile="telemetry"):
auth = _auth(api_key, profile)
request_uri = _get_telemetry_base(profile) + "/alerts"
key = "telemetry.{0}.alerts".format(deployment_id)
post_body = {
"deployment": deployment_id,
"filter"... | create an telemetry alarms.
data is a dict of alert configuration data.
Returns (bool success, str message) tuple.
CLI Example:
salt myminion telemetry.create_alarm rs-ds033197 {} profile=telemetry |
18,989 | def get_current(self, channel, unit=):
values = self._get_adc_value(address=self._ch_map[channel][][])
raw = values[self._ch_map[channel][][]]
dac_offset = self._ch_cal[channel][][]
dac_gain = self._ch_cal[channel][][]
if in channel:
current = ((raw - dac_o... | Reading current |
18,990 | def validate_allowed_to_pay(self):
re allowed to pay, otherwise raise
a ValidationError. '
self._refresh()
if not self.invoice.is_unpaid:
raise ValidationError("You can only pay for unpaid invoices.")
if not self.invoice.cart:
return
if not sel... | Passes cleanly if we're allowed to pay, otherwise raise
a ValidationError. |
18,991 | def fromdeltas(cls, deltas):
return cls((key, value) for (refkey, key), value in deltas.items()) | Construct an offsetvector from a dictionary of offset
deltas as returned by the .deltas attribute.
Example:
>>> x = offsetvector({"H1": 0, "L1": 10, "V1": 20})
>>> y = offsetvector.fromdeltas(x.deltas)
>>> y
offsetvector({'V1': 20, 'H1': 0, 'L1': 10})
>>> y == x
True
See also .deltas, .fromkeys() |
18,992 | def license_is_oa(license):
for oal in OA_LICENSES:
if re.search(oal, license):
return True
return False | Return True if license is compatible with Open Access |
18,993 | def nodal_production_balance(
network,
snapshot=,
scaling=0.00001,
filename=None):
fig, ax = plt.subplots(1, 1)
gen = network.generators_t.p.groupby(network.generators.bus, axis=1).sum()
load = network.loads_t.p.groupby(network.loads.bus, axis=1).sum()
if sna... | Plots the nodal difference between generation and consumption.
Parameters
----------
network : PyPSA network container
Holds topology of grid including results from powerflow analysis
snapshot : int or 'all'
Snapshot to plot.
default 'all'
scaling : int
Scaling t... |
18,994 | def can_update_topics_to_sticky_topics(self, forum, user):
return (
self._perform_basic_permission_check(forum, user, ) and
self._perform_basic_permission_check(forum, user, )
) | Given a forum, checks whether the user can change its topic types to sticky topics. |
18,995 | def _check_rules(browser, rules_js, config):
audit_run_script = dedent(u).format(
rules_js=rules_js,
custom_rules=config.custom_rules,
context=config.context,
options=config.rules
)
audit_results_script = dedent(u)
browser.execut... | Run an accessibility audit on the page using the axe-core ruleset.
Args:
browser: a browser instance.
rules_js: the ruleset JavaScript as a string.
config: an AxsAuditConfig instance.
Returns:
A list of violations.
Related documentation:
... |
18,996 | def ahrs_send(self, omegaIx, omegaIy, omegaIz, accel_weight, renorm_val, error_rp, error_yaw, force_mavlink1=False):
return self.send(self.ahrs_encode(omegaIx, omegaIy, omegaIz, accel_weight, renorm_val, error_rp, error_yaw), force_mavlink1=force_mavlink1) | Status of DCM attitude estimator
omegaIx : X gyro drift estimate rad/s (float)
omegaIy : Y gyro drift estimate rad/s (float)
omegaIz : Z gyro drift estimate rad/s (float)
accel_weight : av... |
18,997 | def is_enum_type(type_):
return isinstance(type_, type) and issubclass(type_, tuple(_get_types(Types.ENUM))) | Checks if the given type is an enum type.
:param type_: The type to check
:return: True if the type is a enum type, otherwise False
:rtype: bool |
18,998 | def fms(x, y, z, context=None):
return _apply_function_in_current_context(
BigFloat,
mpfr.mpfr_fms,
(
BigFloat._implicit_convert(x),
BigFloat._implicit_convert(y),
BigFloat._implicit_convert(z),
),
context,
) | Return (x * y) - z, with a single rounding according to the current
context. |
18,999 | def actions_delete():
filename = action_listlocal()
ONTOSPY_LOCAL_MODELS = get_home_location()
if filename:
fullpath = ONTOSPY_LOCAL_MODELS + filename
if os.path.exists(fullpath):
var = input("Are you sure you want to delete this file? (y/n)")
if ... | DEPRECATED (v 1.9.4)
delete an ontology from the local repo |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.