Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
12,300 | def create_dimension(ncfile, name, length) -> None:
try:
ncfile.createDimension(name, length)
except BaseException:
objecttools.augment_excmessage(
% (name, length, get_filepath(ncfile))) | Add a new dimension with the given name and length to the given
NetCDF file.
Essentially, |create_dimension| just calls the equally named method
of the NetCDF library, but adds information to possible error messages:
>>> from hydpy import TestIO
>>> from hydpy.core.netcdftools import netcdf4
>... |
12,301 | def showtraceback(self, *args, **kwargs):
try:
type, value, tb = sys.exc_info()
sys.last_type = type
sys.last_value = value
sys.last_traceback = tb
tblist = traceback.extract_tb(tb)
del tblist[:1]
lines = trace... | Display the exception that just occurred. |
12,302 | def _scalar_field_to_json(field, row_value):
converter = _SCALAR_VALUE_TO_JSON_ROW.get(field.field_type)
if converter is None:
return row_value
return converter(row_value) | Maps a field and value to a JSON-safe value.
Args:
field ( \
:class:`~google.cloud.bigquery.schema.SchemaField`, \
):
The SchemaField to use for type conversion and field name.
row_value (any):
Value to be converted, based on the field's type.
Return... |
12,303 | def requires(self):
if self.use_spark:
return AggregateArtistsSpark(self.date_interval)
else:
return AggregateArtists(self.date_interval) | This task's dependencies:
* :py:class:`~.AggregateArtists` or
* :py:class:`~.AggregateArtistsSpark` if :py:attr:`~/.Top10Artists.use_spark` is set.
:return: object (:py:class:`luigi.task.Task`) |
12,304 | def song(self, song_id):
if song_id.startswith():
song_info = self._call(
mc_calls.FetchTrack,
song_id
).body
else:
song_info = next(
(
song
for song in self.songs()
if song[] == song_id
),
None
)
return song_info | Get information about a song.
Parameters:
song_id (str): A song ID.
Returns:
dict: Song information. |
12,305 | def calc_and_plot_sample_orient_check(self):
fit = self.current_fit
if fit == None:
return
pars = fit.get()
if not in list(pars.keys()) or not in list(pars.keys()):
fit.put(self.s, , self.get_PCA_parameters(
self.s, fit, fit.tmin, fit.tm... | If sample orientation is on plots the wrong arrow, wrong compass,
and rotated sample error directions for the current specimen
interpretation on the high level mean plot so that you can check
sample orientation good/bad. |
12,306 | def _get_content(data, which_content):
content =
if data.get(which_content):
if isinstance(data.get(which_content), feedparser.FeedParserDict):
content = data.get(which_content)[]
elif not isinstance(data.get(which_content), str):
if in ... | get the content that could be hidden
in the middle of "content" or "summary detail"
from the data of the provider |
12,307 | def maybe_download(url, filename):
if not os.path.exists(WORK_DIRECTORY):
os.mkdir(WORK_DIRECTORY)
filepath = os.path.join(WORK_DIRECTORY, filename)
if not os.path.exists(filepath):
filepath, _ = request.urlretrieve(url + filename, filepath)
statinfo = os.stat(filepath)
print(, filename, statin... | Download the data from Yann's website, unless it's already here. |
12,308 | def drp_load_data(package, data, confclass=None):
drpdict = yaml.safe_load(data)
ins = load_instrument(package, drpdict, confclass=confclass)
if ins.version == :
pkg = importlib.import_module(package)
ins.version = getattr(pkg, , )
return ins | Load the DRPS from data. |
12,309 | def get_plot(self, normalize_rxn_coordinate=True, label_barrier=True):
plt = pretty_plot(12, 8)
scale = 1 if not normalize_rxn_coordinate else 1 / self.r[-1]
x = np.arange(0, np.max(self.r), 0.01)
y = self.spline(x) * 1000
relative_energies = self.energies - self.energie... | Returns the NEB plot. Uses Henkelman's approach of spline fitting
each section of the reaction path based on tangent force and energies.
Args:
normalize_rxn_coordinate (bool): Whether to normalize the
reaction coordinate to between 0 and 1. Defaults to True.
labe... |
12,310 | def read_string_from_file(path, encoding="utf8"):
with codecs.open(path, "rb", encoding=encoding) as f:
value = f.read()
return value | Read entire contents of file into a string. |
12,311 | def add_role(self, role, term, start_date=None, end_date=None,
**kwargs):
self[].append(dict(role=role, term=term,
start_date=start_date,
end_date=end_date, **kwargs)) | Examples:
leg.add_role('member', term='2009', chamber='upper',
party='Republican', district='10th') |
12,312 | def press(self):
@param_to_property(
key=["home", "back", "left", "right", "up", "down", "center",
"menu", "search", "enter", "delete", "del", "recent",
"volume_up", "volume_down", "volume_mute", "camera", "power"]
)
def _press(key, meta=Non... | press key via name or key code. Supported key name includes:
home, back, left, right, up, down, center, menu, search, enter,
delete(or del), recent(recent apps), volume_up, volume_down,
volume_mute, camera, power.
Usage:
d.press.back() # press back key
d.press.menu() # ... |
12,313 | def _copy_old_features(new_eopatch, old_eopatch, copy_features):
if copy_features:
existing_features = set(new_eopatch.get_feature_list())
for copy_feature_type, copy_feature_name, copy_new_feature_name in copy_features:
new_feature = copy_feature_type, copy_new... | Copy features from old EOPatch
:param new_eopatch: New EOPatch container where the old features will be copied to
:type new_eopatch: EOPatch
:param old_eopatch: Old EOPatch container where the old features are located
:type old_eopatch: EOPatch
:param copy_features: List of tupl... |
12,314 | def OSCBlob(next):
if type(next) == type(""):
length = len(next)
padded = math.ceil((len(next)) / 4.0) * 4
binary = struct.pack(">i%ds" % (padded), length, next)
tag =
else:
tag =
binary =
return (tag, binary) | Convert a string into an OSC Blob,
returning a (typetag, data) tuple. |
12,315 | def _create_deployment_object(self, job_name, job_image,
deployment_name, port=80,
replicas=1,
cmd_string=None,
engine_json_file=,
engine_dir=):
... | Create a kubernetes deployment for the job.
Args:
- job_name (string) : Name of the job and deployment
- job_image (string) : Docker image to launch
KWargs:
- port (integer) : Container port
- replicas : Number of replica containers to maintain
... |
12,316 | def analyze_dir(stats, parent_dir, rel_filepaths, cover_filename, *, ignore_existing=False):
no_metadata = None, None, None
metadata = no_metadata
audio_filepaths = []
for rel_filepath in rel_filepaths:
stats["files"] += 1
try:
ext = os.path.splitext(rel_filepath)[1][1:].lower()
except Inde... | Analyze a directory (non recursively) to get its album metadata if it is one. |
12,317 | def null_concept(self):
cause_repertoire = self.cause_repertoire((), ())
effect_repertoire = self.effect_repertoire((), ())
cause = MaximallyIrreducibleCause(
_null_ria(Direction.CAUSE, (), (), cause_repertoire))
effect = Maximall... | Return the null concept of this subsystem.
The null concept is a point in concept space identified with
the unconstrained cause and effect repertoire of this subsystem. |
12,318 | def find_usb_device_by_address(self, name):
if not isinstance(name, basestring):
raise TypeError("name can only be an instance of type basestring")
device = self._call("findUSBDeviceByAddress",
in_p=[name])
device = IHostUSBDevice(device)
return ... | Searches for a USB device with the given host address.
:py:func:`IUSBDevice.address`
in name of type str
Address of the USB device (as assigned by the host) to
search for.
return device of type :class:`IHostUSBDevice`
Found USB de... |
12,319 | def first_setup(self):
if ATTR_FIRST_SETUP not in self.raw:
return None
return datetime.utcfromtimestamp(self.raw[ATTR_FIRST_SETUP]) | This is a guess of the meaning of this value. |
12,320 | def get_osdp(self, id_or_uri):
uri = self._client.build_subresource_uri(resource_id_or_uri=id_or_uri, subresource_path="osdp")
return self._client.get(uri) | Retrieves facts about Server Profiles and Server Profile Templates that are using Deployment Plan based on the ID or URI provided.
Args:
id_or_uri: ID or URI of the Deployment Plan.
Returns:
dict: Server Profiles and Server Profile Templates |
12,321 | def set_prefix(self, elt, pyobj):
if isinstance(pyobj, tuple):
namespaceURI,localName = pyobj
self.prefix = elt.getPrefix(namespaceURI) | use this method to set the prefix of the QName,
method looks in DOM to find prefix or set new prefix.
This method must be called before get_formatted_content. |
12,322 | def get_index_text(self, modname, name_cls):
if self.objtype in (, ):
if not modname:
return _() % (name_cls[0], self.objtype)
return _() % (name_cls[0], self.objtype, modname)
else:
return | Return index entry text based on object type. |
12,323 | def ability(cls, id_, name, function_type, ability_id, general_id=0):
assert function_type in ABILITY_FUNCTIONS
return cls(id_, name, ability_id, general_id, function_type,
FUNCTION_TYPES[function_type], None) | Define a function represented as a game ability. |
12,324 | def get_external_command_output(command: str) -> bytes:
args = shlex.split(command)
ret = subprocess.check_output(args)
return ret | Takes a command-line command, executes it, and returns its ``stdout``
output.
Args:
command: command string
Returns:
output from the command as ``bytes`` |
12,325 | def _create_ids(self, home_teams, away_teams):
categories = pd.Categorical(np.append(home_teams,away_teams))
home_id, away_id = categories.codes[0:int(len(categories)/2)], categories.codes[int(len(categories)/2):len(categories)+1]
return home_id, away_id | Creates IDs for both players/teams |
12,326 | def from_int(data):
if not isinstance(data, int) and not isinstance(data, long):
raise TypeError()
res = []
while data > 0 or not res:
for j in range(5):
if not j % 2:
res += CONSONANTS[(data & 0xf)]
data >>= 4
else:
... | :params data: integer
:returns: proquint made from input data
:type data: int
:rtype: string |
12,327 | def align_file_position(f, size):
align = (size - 1) - (f.tell() % size)
f.seek(align, 1) | Align the position in the file to the next block of specified size |
12,328 | def mstmap(args):
from jcvi.assembly.geneticmap import MSTMatrix
p = OptionParser(mstmap.__doc__)
p.add_option("--population_type", default="RIL6",
help="Type of population, possible values are DH and RILd")
p.add_option("--missing_threshold", default=.5,
help="Mi... | %prog mstmap LMD50.snps.genotype.txt
Convert LMDs to MSTMAP input. |
12,329 | def from_dict(cls, d):
conf = {}
for k in d["config"]:
v = d["config"][k]
if isinstance(v, dict):
if u"type" in v:
typestr = v[u"type"]
else:
typestr = v["type"]
conf[str(k)] = classe... | Restores an object state from a dictionary, used in de-JSONification.
:param d: the object dictionary
:type d: dict
:return: the object
:rtype: object |
12,330 | def convert_reshape(net, node, module, builder):
input_name, output_name = _get_input_output_name(net, node)
name = node[]
param = _get_attr(node)
target_shape = literal_eval(param[])
if target_shape == (0, -1):
convert_flatten(net, node, module, builder)
return
if any(item... | Converts a reshape layer from mxnet to coreml.
This doesn't currently handle the deprecated parameters for the reshape layer.
Parameters
----------
net: network
An mxnet network object.
node: layer
Node to convert.
module: module
A module for MXNet
builder: Neura... |
12,331 | def get_user(self, username):
User = get_user_model()
try:
user = User.objects.get(**{
User.USERNAME_FIELD: username,
})
if user.is_active:
raise ActivationError(
self.ALREADY_ACTIVATED_MESSAGE,
... | Given the verified username, look up and return the
corresponding user account if it exists, or raising
``ActivationError`` if it doesn't. |
12,332 | def headerData(self, section, orientation, role=Qt.DisplayRole):
if role == Qt.DisplayRole:
if orientation == Qt.Horizontal:
if section < len(self.__horizontal_headers):
return self.__horizontal_headers.keys()[section]
elif orientation == Qt.... | Reimplements the :meth:`QAbstractItemModel.headerData` method.
:param section: Section.
:type section: int
:param orientation: Orientation. ( Qt.Orientation )
:param role: Role.
:type role: int
:return: Header data.
:rtype: QVariant |
12,333 | def intersection(self, *args):
values = self.values()
if args:
values = [val for key,val in self.items() if key in args]
return set(reduce(set.intersection, values)) | Returns the intersection of the values whose keys are in *args. If *args is blank, returns the intersection of all values. |
12,334 | def total_supply(self, block_identifier=):
return self.proxy.contract.functions.totalSupply().call(block_identifier=block_identifier) | Return the total supply of the token at the given block identifier. |
12,335 | def id_generator(size=15, random_state=None):
chars = list(string.ascii_uppercase + string.digits)
return .join(random_state.choice(chars, size, replace=True)) | Helper function to generate random div ids. This is useful for embedding
HTML into ipython notebooks. |
12,336 | def encode(data, scheme=None, size=None):
size = size if size else
size_name = .format(ENCODING_SIZE_PREFIX, size)
if not hasattr(DmtxSymbolSize, size_name):
raise PyLibDMTXError(
.format(
size, ENCODING_SIZE_NAMES
)
)
size = getattr(DmtxSym... | Encodes `data` in a DataMatrix image.
For now bpp is the libdmtx default which is 24
Args:
data: bytes instance
scheme: encoding scheme - one of `ENCODING_SCHEME_NAMES`, or `None`.
If `None`, defaults to 'Ascii'.
size: image dimensions - one of `ENCODING_SIZE_NAMES`, or `No... |
12,337 | def _calc_min_size(self, conv_layers):
input_size = 1
for _, conv_params, max_pooling in reversed(conv_layers):
if max_pooling is not None:
kernel_size, stride = max_pooling
input_size = input_size * stride + (kernel_size - stride)
if conv_params is not None:
kernel_si... | Calculates the minimum size of the input layer.
Given a set of convolutional layers, calculate the minimum value of
the `input_height` and `input_width`, i.e. such that the output has
size 1x1. Assumes snt.VALID padding.
Args:
conv_layers: List of tuples `(output_channels, (kernel_size, stride),... |
12,338 | def getnames():
namestring = ""
addmore = 1
while addmore:
scientist = input("Enter name - <Return> when done ")
if scientist != "":
namestring = namestring + ":" + scientist
else:
namestring = namestring[1:]
addmore = 0
return namestrin... | get mail names |
12,339 | def substitute_selected_state(state, as_template=False, keep_name=False):
assert isinstance(state, State)
from rafcon.core.states.barrier_concurrency_state import DeciderState
if isinstance(state, DeciderState):
raise ValueError("State of type DeciderState can not be substituted.")
sm... | Substitute the selected state with the handed state
:param rafcon.core.states.state.State state: A state of any functional type that derives from State
:param bool as_template: The flag determines if a handed the state of type LibraryState is insert as template
:return: |
12,340 | def _cryptodome_encrypt(cipher_factory, plaintext, key, iv):
encryptor = cipher_factory(key, iv)
return encryptor.encrypt(plaintext) | Use a Pycryptodome cipher factory to encrypt data.
:param cipher_factory: Factory callable that builds a Pycryptodome Cipher
instance based on the key and IV
:type cipher_factory: callable
:param bytes plaintext: Plaintext data to encrypt
:param bytes key: Encryption key
:param bytes IV: In... |
12,341 | def export_organizations(self, outfile):
exporter = SortingHatOrganizationsExporter(self.db)
dump = exporter.export()
try:
outfile.write(dump)
outfile.write()
except IOError as e:
raise RuntimeError(str(e))
return CMD_SUCCESS | Export organizations information to a file.
The method exports information related to organizations, to
the given 'outfile' output file.
:param outfile: destination file object |
12,342 | def switch_region(request, region_name,
redirect_field_name=auth.REDIRECT_FIELD_NAME):
if region_name in request.user.available_services_regions:
request.session[] = region_name
LOG.debug(,
region_name, request.user.username)
redirect_to = request.GET.ge... | Switches the user's region for all services except Identity service.
The region will be switched if the given region is one of the regions
available for the scoped project. Otherwise the region is not switched. |
12,343 | def drawpoint(self, x, y, colour = None):
self.checkforpilimage()
colour = self.defaultcolour(colour)
self.changecolourmode(colour)
self.makedraw()
(pilx, pily) = self.pilcoords((x,y))
self.draw.point((pilx, pily), fill = colour) | Most elementary drawing, single pixel, used mainly for testing purposes.
Coordinates are those of your initial image ! |
12,344 | def _run_snpeff(snp_in, out_format, data):
snpeff_db, datadir = get_db(data)
if not snpeff_db:
return None, None
assert os.path.exists(os.path.join(datadir, snpeff_db)), \
"Did not find %s snpEff genome data in %s" % (snpeff_db, datadir)
ext = utils.splitext_plus(snp_in)[1] if out_... | Run effects prediction with snpEff, skipping if snpEff database not present. |
12,345 | def search(self, query, limit=None):
return self._limit_get(, params=dict(q=query), limit=limit) | Use reddit's search function. Returns :class:`things.Listing` object.
URL: ``http://www.reddit.com/search/?q=<query>&limit=<limit>``
:param query: query string
:param limit: max number of results to get |
12,346 | def make_store(name, min_length=4, **kwargs):
if name not in stores:
raise ValueError(.format(.join(stores)))
if name == :
store = MemcacheStore
elif name == :
store = MemoryStore
elif name == :
store = RedisStore
return store(min_length=min_length, **kwargs) | \
Creates a store with a reasonable keygen.
.. deprecated:: 2.0.0
Instantiate stores directly e.g. ``shorten.MemoryStore(min_length=4)`` |
12,347 | def register_memory():
def get_mem(proc):
if os.name == :
mem = proc.memory_info_ex()
counter = mem.rss
if in mem._fields:
counter -= mem.shared
return counter
else:
return proc.get_memory_i... | Register an approximation of memory used by FTP server process
and all of its children. |
12,348 | def get_scenario(scenario_id,**kwargs):
user_id = kwargs.get()
scen_i = _get_scenario(scenario_id, user_id)
scen_j = JSONObject(scen_i)
rscen_rs = db.DBSession.query(ResourceScenario).filter(ResourceScenario.scenario_id==scenario_id).options(joinedload_all()).all()
for rs in rscen_rs:
... | Get the specified scenario |
12,349 | def load_services(self, services=settings.TH_SERVICES):
kwargs = {}
for class_path in services:
module_name, class_name = class_path.rsplit(, 1)
klass = import_from_path(class_path)
service = klass(None, **kwargs)
self.register(class_name, service... | get the service from the settings |
12,350 | def get_activity_mdata():
return {
: {
: {
: ,
: str(DEFAULT_LANGUAGE_TYPE),
: str(DEFAULT_SCRIPT_TYPE),
: str(DEFAULT_FORMAT_TYPE),
},
: {
: ,
: str(DEFAULT_LANGUAGE_TYPE... | Return default mdata map for Activity |
12,351 | def _filter_choosers_alts(self, choosers, alternatives):
return (
util.apply_filter_query(
choosers, self.choosers_predict_filters),
util.apply_filter_query(
alternatives, self.alts_predict_filters)) | Apply filters to the choosers and alts tables. |
12,352 | def require_meta_and_content(self, content_handler, params, **kwargs):
meta = {
: params
}
content = content_handler(params, meta, **kwargs)
meta[] = params
return meta, content | Require 'meta' and 'content' dictionaries using proper hander.
Args:
content_handler (callable): function that accepts
``params, meta, **kwargs`` argument and returns dictionary
for ``content`` response section
params (dict): dictionary of parsed resource... |
12,353 | def wrapped_request(self, request, *args, **kwargs):
f = tornado_Future()
try:
use_mid = kwargs.get()
timeout = kwargs.get()
mid = kwargs.get()
msg = Message.request(request, *args, mid=mid)
except Exception:
f.set_exc_info(sys... | Create and send a request to the server.
This method implements a very small subset of the options
possible to send an request. It is provided as a shortcut to
sending a simple wrapped request.
Parameters
----------
request : str
The request to call.
... |
12,354 | def compute_csets_TRAM(
connectivity, state_counts, count_matrices, equilibrium_state_counts=None,
ttrajs=None, dtrajs=None, bias_trajs=None, nn=None, factor=1.0, callback=None):
r
return _compute_csets(
connectivity, state_counts, count_matrices, ttrajs, dtrajs, bias_trajs,
nn=nn, equil... | r"""
Computes the largest connected sets in the produce space of Markov state and
thermodynamic states for TRAM data.
Parameters
----------
connectivity : string
one of None, 'reversible_pathways', 'post_hoc_RE' or 'BAR_variance',
'neighbors', 'summed_count_matrix' or None.
... |
12,355 | def update_member_names(oldasndict, pydr_input):
omembers = oldasndict[].copy()
nmembers = {}
translated_names = [f.split()[0] for f in pydr_input]
newkeys = [fileutil.buildNewRootname(file) for file in pydr_input]
keys_map = list(zip(newkeys, pydr_input))
for okey, oval in list(omembers... | Update names in a member dictionary.
Given an association dictionary with rootnames and a list of full
file names, it will update the names in the member dictionary to
contain '_*' extension. For example a rootname of 'u9600201m' will
be replaced by 'u9600201m_c0h' making sure that a MEf file is passed... |
12,356 | def project(self, x, vector):
scale = np.linalg.norm(vector)
if scale == 0.0:
return vector
self.lock[:] = False
normals, signs = self._compute_equations(x)[::3]
if len(normals) == 0:
return vector
vector = vector/scale
mask = sig... | Project a vector (gradient or direction) on the active constraints.
Arguments:
| ``x`` -- The unknowns.
| ``vector`` -- A numpy array with a direction or a gradient.
The return value is a gradient or direction, where the components
that point away from the cons... |
12,357 | def optimize_seq_and_branch_len(self,reuse_branch_len=True, prune_short=True,
marginal_sequences=False, branch_length_mode=,
max_iter=5, infer_gtr=False, **kwargs):
if branch_length_mode==:
marginal_sequences = True
... | Iteratively set branch lengths and reconstruct ancestral sequences until
the values of either former or latter do not change. The algorithm assumes
knowing only the topology of the tree, and requires that sequences are assigned
to all leaves of the tree.
The first step is to pre-reconst... |
12,358 | def get_xy_environment(self, xy):
x = xy[0]
y = xy[1]
for origin, addr in self._slave_origins:
ox = origin[0]
oy = origin[1]
if ox <= x < ox + self.gs[0] and oy <= y < oy + self.gs[1]:
return addr
return None | Get manager address for the environment which should have the agent
with given *xy* coordinate, or None if no such environment is in this
multi-environment. |
12,359 | async def start(self):
if self.connection.connected:
return
await self.connection.connect()
if self.service.device_credentials:
self.srp.pairing_id = Credentials.parse(
self.service.device_credentials).client_id
... | Connect to device and listen to incoming messages. |
12,360 | def cleanParagraph(self):
runs = self.block.content
if not runs:
self.block = None
return
if not self.clean_paragraphs:
return
joinedRuns = []
hasContent = False
for run in runs:
if run.content[0]:
... | Compress text runs, remove whitespace at start and end,
skip empty blocks, etc |
12,361 | def transform(self, X, y=None, copy=None):
check_is_fitted(self, )
copy = copy if copy is not None else self.copy
X = check_array(X, accept_sparse=, copy=copy, warn_on_dtype=True,
estimator=self, dtype=FLOAT_DTYPES)
if sparse.issparse(X):
i... | Perform standardization by centering and scaling using the parameters.
:param X: Data matrix to scale.
:type X: numpy.ndarray, shape [n_samples, n_features]
:param y: Passthrough for scikit-learn ``Pipeline`` compatibility.
:type y: None
:param bool copy: Copy the X matrix.
... |
12,362 | def getresponse(self):
status = self._httprequest.status()
status_text = self._httprequest.status_text()
resp_headers = self._httprequest.get_all_response_headers()
fixed_headers = []
for resp_header in resp_headers.split():
if (resp_header.startswith() or\
... | Gets the response and generates the _Response object |
12,363 | def _bisect(value_and_gradients_function, initial_args, f_lim):
def _loop_cond(curr):
return ~tf.reduce_all(input_tensor=curr.stopped)
def _loop_body(curr):
mid = value_and_gradients_function((curr.left.x + curr.right.x) / 2)
stopped = curr.stopped | failed | (right.df >= 0)
... | Actual implementation of bisect given initial_args in a _BracketResult. |
12,364 | def ahead(self, i, j=None):
if j is None:
return self._stream[self.i + i]
else:
return self._stream[self.i + i: self.i + j] | Raising stopiteration with end the parse. |
12,365 | def getItemTrace(self):
item, path, name, ref = self, [], ,
while not isinstance(item,XMLSchema) and not isinstance(item,WSDLToolsAdapter):
attr = item.getAttribute(name)
if not attr:
attr = item.getAttribute(ref)
if not attr:
... | Returns a node trace up to the <schema> item. |
12,366 | def format(self, data, *args, **kwargs):
sections = OrderedDict()
hot_list = []
normal_list = []
for item in data:
meta = item.get(, [])
if not item.get():
continue
soup = BeautifulSoup(item.get(), "lxml")
... | 将传入的Post列表数据进行格式化处理。此处传入的 ``data`` 格式即为
:meth:`.ZhihuDaily.crawl` 返回的格式,但具体内容可以不同,即此处保留了灵活度,
可以对非当日文章对象进行格式化,制作相关主题的合集书籍
:param data: 待处理的文章列表
:type data: list
:return: 返回符合mobi打包需求的定制化数据结构
:rtype: dict |
12,367 | def _extend_nocheck(self, iterable):
current_length = len(self)
list.extend(self, iterable)
_dict = self._dict
if current_length is 0:
self._generate_index()
return
for i, obj in enumerate(islice(self, current_length, None),
... | extends without checking for uniqueness
This function should only be used internally by DictList when it
can guarantee elements are already unique (as in when coming from
self or other DictList). It will be faster because it skips these
checks. |
12,368 | def get_all_in_collection(self, collection_paths: Union[str, Iterable[str]], load_metadata: bool = True) \
-> Sequence[EntityType]:
| Gets entities contained within the given iRODS collections.
If one or more of the collection_paths does not exist, a `FileNotFound` exception will be raised.
:param collection_paths: the collection(s) to get the entities from
:param load_metadata: whether metadata associated to the entities sho... |
12,369 | def make_named_stemmer(stem=None, min_len=3):
name, stem = stringify(stem), make_stemmer(stem=stem, min_len=min_len)
if hasattr(stem, ):
return stem.__name__, stem
if name.strip().lower() in STEMMER_TYPES:
return name.strip().lower(), stem
if hasattr(stem, ):
return stem.pat... | Construct a callable object and a string sufficient to reconstruct it later (unpickling)
>>> make_named_stemmer('str_lower')
('str_lower', <function str_lower at ...>)
>>> make_named_stemmer('Lancaster')
('lancaster', <Stemmer object at ...>) |
12,370 | def get_teachers_sorted(self):
teachers = self.get_teachers()
teachers = [(u.last_name, u.first_name, u.id) for u in teachers]
for t in teachers:
if t is None or t[0] is None or t[1] is None or t[2] is None:
teachers.remove(t)
for t in teachers:
... | Get teachers sorted by last name.
This is used for the announcement request page. |
12,371 | def mgmt_root(opt_bigip, opt_username, opt_password, opt_port, opt_token):
try:
from pytest import symbols
except ImportError:
m = ManagementRoot(opt_bigip, opt_username, opt_password,
port=opt_port, token=opt_token)
else:
if symbols is not None:
... | bigip fixture |
12,372 | def merge_dict(d0, d1, add_new_keys=False, append_arrays=False):
if d1 is None:
return d0
elif d0 is None:
return d1
elif d0 is None and d1 is None:
return {}
od = {}
for k, v in d0.items():
t0 = None
t1 = None
if k in d0:
t0 = ty... | Recursively merge the contents of python dictionary d0 with
the contents of another python dictionary, d1.
Parameters
----------
d0 : dict
The input dictionary.
d1 : dict
Dictionary to be merged with the input dictionary.
add_new_keys : str
Do not skip keys that only exis... |
12,373 | def _example_broker_queue(quote_ctx):
stock_code_list = ["HK.00700"]
for stk_code in stock_code_list:
ret_status, ret_data = quote_ctx.subscribe(stk_code, ft.SubType.BROKER)
if ret_status != ft.RET_OK:
print(ret_data)
exit()
for stk_code in stock_code_list:
... | 获取经纪队列,输出 买盘卖盘的经纪ID,经纪名称,经纪档位 |
12,374 | def download(self,
files=None,
formats=None,
glob_pattern=None,
dry_run=None,
verbose=None,
silent=None,
ignore_existing=None,
checksum=None,
destdir=None,
... | Download files from an item.
:param files: (optional) Only download files matching given file names.
:type formats: str
:param formats: (optional) Only download files matching the given
Formats.
:type glob_pattern: str
:param glob_pattern: (optional) On... |
12,375 | def pgcd(numa, numb):
int_args = (int(numa) == numa) and (int(numb) == numb)
fraction_args = isinstance(numa, Fraction) and isinstance(numb, Fraction)
if int_args:
numa, numb = int(numa), int(numb)
elif not fraction_args:
numa, numb = float(numa), float(numb)
... | Calculate the greatest common divisor (GCD) of two numbers.
:param numa: First number
:type numa: number
:param numb: Second number
:type numb: number
:rtype: number
For example:
>>> import pmisc, fractions
>>> pmisc.pgcd(10, 15)
5
>>> str(pmisc.pgcd(0.05, ... |
12,376 | def validate_path(path):
if not isinstance(path, six.string_types) or not re.match(, path):
raise InvalidUsage(
"Path validation failed - Expected: '/<component>[/component], got: %s" % path
)
return True | Validates the provided path
:param path: path to validate (string)
:raise:
:InvalidUsage: If validation fails. |
12,377 | def _raise_decomposition_errors(uvw, antenna1, antenna2,
chunks, ant_uvw, max_err):
start = 0
problem_str = []
for ci, chunk in enumerate(chunks):
end = start + chunk
ant1 = antenna1[start:end]
ant2 = antenna2[start:end]
cuvw = uvw[sta... | Raises informative exception for an invalid decomposition |
12,378 | def log_template_errors(logger, log_level=logging.ERROR):
if not (isinstance(log_level, int) and
log_level in logging._levelNames):
raise ValueError( % log_level)
decorators = [
_log_template_string_if_invalid(logger, log_level),
_log_unicode_errors(logger, log_level),
... | Decorator to log template errors to the specified logger.
@log_template_errors(logging.getLogger('mylogger'), logging.INFO)
def my_view(*args):
pass
Will log template errors at INFO. The default log level is ERROR. |
12,379 | def print_logs(query, types=None):
if query is None:
return
for run, log in query:
print(("{0} @ {1} - {2} id: {3} group: {4} status: {5}".format(
run.end, run.experiment_name, run.project_name,
run.experiment_group, run.run_group, log.status)))
print(("comm... | Print status logs. |
12,380 | def ncbi_blast(self, db="nr", megablast=True, sequence=None):
import requests
requests.defaults.max_retries = 4
assert sequence in (None, "cds", "mrna")
seq = self.sequence() if sequence is None else ("".join(self.cds_sequence if sequence == "cds" else self.mrna_sequence))
... | perform an NCBI blast against the sequence of this feature |
12,381 | def process_objects(kls):
if not in kls.__dict__:
kls.Meta = type(, (object,), {})
if not in kls.Meta.__dict__:
kls.Meta.unique_together = []
if not in kls.Meta.__dict__:
kls.Meta.verbose_name = kls.__name__
if not in kls... | Applies default Meta properties. |
12,382 | def map_query(self, variables=None, evidence=None):
if not variables:
variables = set(self.variables)
final_distribution = self._query(variables=variables, operation=, evidence=evidence)
argmax = np.argmax(final_distribution.values)
assig... | MAP Query method using belief propagation.
Note: When multiple variables are passed, it returns the map_query for each
of them individually.
Parameters
----------
variables: list
list of variables for which you want to compute the probability
evidence: dict
... |
12,383 | def clone(self, **kwargs):
child = ChildContextDict(parent=self, threadsafe=self._threadsafe, overrides=kwargs)
return child | Clone this context, and return the ChildContextDict |
12,384 | def _expand_shorthand(model_formula, variables):
wm =
gsr =
rps =
fd =
acc = _get_matches_from_data(, variables)
tcc = _get_matches_from_data(, variables)
dv = _get_matches_from_data(, variables)
dvall = _get_matches_from_data(, variables)
nss = _get_matches_from_data(,
... | Expand shorthand terms in the model formula. |
12,385 | def action_set(values):
cmd = []
for k, v in list(values.items()):
cmd.append(.format(k, v))
subprocess.check_call(cmd) | Sets the values to be returned after the action finishes |
12,386 | def ellipse_from_second_moments(image, labels, indexes, wants_compactness = False):
if len(indexes) == 0:
return (np.zeros((0,2)), np.zeros((0,)), np.zeros((0,)),
np.zeros((0,)),np.zeros((0,)))
i,j = np.argwhere(labels != 0).transpose()
return ellipse_from_second_moments_ijv(i,... | Calculate measurements of ellipses equivalent to the second moments of labels
image - the intensity at each point
labels - for each labeled object, derive an ellipse
indexes - sequence of indexes to process
returns the following arrays:
coordinates of the center of the ellipse
e... |
12,387 | def Back(self, n = 1, dl = 0):
self.Delay(dl)
self.keyboard.tap_key(self.keyboard.backspace_key, n) | 退格键n次 |
12,388 | def _make_valid_state_name(self, state_name):
s = str(state_name)
s_fixed = pp.CharsNotIn(pp.alphanums + "_").setParseAction(pp.replaceWith("_")).transformString(s)
if not s_fixed[0].isalpha():
s_fixed = "state" + s_fixed
return s_fixed | Transform the input state_name into a valid state in XMLBIF.
XMLBIF states must start with a letter an only contain letters,
numbers and underscores. |
12,389 | def delete(self, option=None):
write_pb = _helpers.pb_for_delete(self._document_path, option)
commit_response = self._client._firestore_api.commit(
self._client._database_string,
[write_pb],
transaction=None,
metadata=self._client._rpc_metadata,
... | Delete the current document in the Firestore database.
Args:
option (Optional[~.firestore_v1beta1.client.WriteOption]): A
write option to make assertions / preconditions on the server
state of the document before applying changes.
Returns:
google.p... |
12,390 | def gen_report(report, sdir=, report_name=):
if not os.path.exists(sdir):
os.makedirs(sdir)
if sdir[-1] != :
sdir +=
report_html =
if in report.keys():
report_html += "<h1>Method: " + report[] + "</h1><p>"
for i in report[report[]]:
... | Generates report of derivation and postprocess steps in teneto.derive |
12,391 | def concretize(x, solver, sym_handler):
if solver.symbolic(x):
try:
return solver.eval_one(x)
except SimSolverError:
return sym_handler(x)
else:
return solver.eval(x) | For now a lot of naive concretization is done when handling heap metadata to keep things manageable. This idiom
showed up a lot as a result, so to reduce code repetition this function uses a callback to handle the one or two
operations that varied across invocations.
:param x: the item to be concretized
... |
12,392 | def _find_statements(self):
for bp in self.child_parsers():
for _, l in bp._bytes_lines():
yield l | Find the statements in `self.code`.
Produce a sequence of line numbers that start statements. Recurses
into all code objects reachable from `self.code`. |
12,393 | def _sorted_copy(self, comparison, reversed=False):
sorted = self.copy()
_list.sort(sorted, comparison)
if reversed:
_list.reverse(sorted)
return sorted | Returns a sorted copy with the colors arranged according to the given comparison. |
12,394 | def enqueue_command(self, command_name, args, options):
assert_open(self)
promise = Promise()
self.commands.append((command_name, args, options, promise))
return promise | Enqueue a new command into this pipeline. |
12,395 | def has_segment_tables(xmldoc, name = None):
try:
names = lsctables.SegmentDefTable.get_table(xmldoc).getColumnByName("name")
lsctables.SegmentTable.get_table(xmldoc)
lsctables.SegmentSumTable.get_table(xmldoc)
except (ValueError, KeyError):
return False
return name is None or name in names | Return True if the document contains a complete set of segment
tables. Returns False otherwise. If name is given and not None
then the return value is True only if the document's segment
tables, if present, contain a segment list by that name. |
12,396 | def recommend(self, users=None, k=10, exclude=None, items=None,
new_observation_data=None, new_user_data=None, new_item_data=None,
exclude_known=True, diversity=0, random_seed=None,
verbose=True):
from turicreate._cython.cy_server import QuietProgre... | Recommend the ``k`` highest scored items for each user.
Parameters
----------
users : SArray, SFrame, or list, optional
Users or observation queries for which to make recommendations.
For list, SArray, and single-column inputs, this is simply a set
of user I... |
12,397 | def get_collections_for_image(self, image_id):
result = []
for document in self.collection.find({ : True, : image_id}):
result.append(str(document[]))
return result | Get identifier of all collections that contain a given image.
Parameters
----------
image_id : string
Unique identifierof image object
Returns
-------
List(string)
List of image collection identifier |
12,398 | def update(self):
_LOGGER.debug("Querying the device..")
time = datetime.now()
value = struct.pack(, PROP_INFO_QUERY,
time.year % 100, time.month, time.day,
time.hour, time.minute, time.second)
self._conn.make_request(PROP... | Update the data from the thermostat. Always sets the current time. |
12,399 | def run_processes(self,
procdetails: List[ProcessDetails],
subproc_run_timeout_sec: float = 1,
stop_event_timeout_ms: int = 1000,
kill_timeout_sec: float = 5) -> None:
def cleanup():
self.debug... | Run multiple child processes.
Args:
procdetails: list of :class:`ProcessDetails` objects (q.v.)
subproc_run_timeout_sec: time (in seconds) to wait for each process
when polling child processes to see how they're getting on
(default ``1``)
sto... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.