Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
3,900 | def on_m_open_file(self,event):
dlg = wx.FileDialog(
self, message="choose orient file",
defaultDir=self.WD,
defaultFile="",
style=wx.FD_OPEN | wx.FD_CHANGE_DIR
)
if dlg.ShowModal() == wx.ID_OK:
orient_file = dlg.GetPath()
... | open orient.txt
read the data
display the data from the file in a new grid |
3,901 | def _set_mpls_reopt_lsp(self, v, load=False):
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=mpls_reopt_lsp.mpls_reopt_lsp, is_leaf=True, yang_name="mpls-reopt-lsp", rest_name="mpls-reopt-lsp", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, regis... | Setter method for mpls_reopt_lsp, mapped from YANG variable /brocade_mpls_rpc/mpls_reopt_lsp (rpc)
If this variable is read-only (config: false) in the
source YANG file, then _set_mpls_reopt_lsp is considered as a private
method. Backends looking to populate this variable should
do so via calling thisOb... |
3,902 | def upload_site(self):
if not os.path.isdir(self._config[]):
message = .format(self._config[])
self._logger.error(message)
raise RuntimeError(message)
ltdclient.upload(self._config) | Upload a previously-built site to LSST the Docs. |
3,903 | def density(a_M, *args, **kwargs):
rows, cols = a_M.shape
a_Mmask = ones( (rows, cols) )
if len(args):
a_Mmask = args[0]
a_M *= a_Mmask
f_binaryMass = float(size(nonzero(a_M)[0]))
f_actualMass = a_M.sum()
f_area = float(size(nonzero(a_Mmask)[0]))... | ARGS
a_M matrix to analyze
*args[0] optional mask matrix; if passed, calculate
density of a_M using non-zero elements of
args[0] as a mask.
DESC
Determine the "density" of a passed matrix. Two densities are retu... |
3,904 | def compute_venn3_colors(set_colors):
rgb
ccv = ColorConverter()
base_colors = [np.array(ccv.to_rgb(c)) for c in set_colors]
return (base_colors[0], base_colors[1], mix_colors(base_colors[0], base_colors[1]), base_colors[2],
mix_colors(base_colors[0], base_colors[2]), mix_colors(base_colors[... | Given three base colors, computes combinations of colors corresponding to all regions of the venn diagram.
returns a list of 7 elements, providing colors for regions (100, 010, 110, 001, 101, 011, 111).
>>> compute_venn3_colors(['r', 'g', 'b'])
(array([ 1., 0., 0.]),..., array([ 0.4, 0.2, 0.4])) |
3,905 | def get_parsed_content(metadata_content):
_import_parsers()
xml_tree = None
if metadata_content is None:
raise NoContent()
else:
if isinstance(metadata_content, MetadataParser):
xml_tree = deepcopy(metadata_content._xml_tree)
elif isinstance(metadata_content... | Parses any of the following types of content:
1. XML string or file object: parses XML content
2. MetadataParser instance: deep copies xml_tree
3. Dictionary with nested objects containing:
- name (required): the name of the element tag
- text: the text contained by element
- tail: t... |
3,906 | def add_legend(self, labels=None, **kwargs):
if in kwargs:
if not in kwargs:
kwargs[] = {: kwargs[]}
else:
kwargs[][] = kwargs[]
del kwargs[]
self.legend.add_legend = True
self.legend.legend_labels = labels
se... | Specify legend for a plot.
Adds labels and basic legend specifications for specific plot.
For the optional Args, refer to
https://matplotlib.org/api/_as_gen/matplotlib.pyplot.legend.html
for more information.
# TODO: Add legend capabilities for Loss/Gain plots. This is possibl... |
3,907 | def deploy_script(self, synchronous=True, **kwargs):
kwargs = kwargs.copy()
kwargs.update(self._server_config.get_client_kwargs())
response = client.get(self.path(), **kwargs)
return _handle_response(response, self._server_config, synchronous) | Helper for Config's deploy_script method.
:param synchronous: What should happen if the server returns an HTTP
202 (accepted) status code? Wait for the task to complete if
``True``. Immediately return the server's response otherwise.
:param kwargs: Arguments to pass to requests.... |
3,908 | def unhexlify(blob):
lines = blob.split()[1:]
output = []
for line in lines:
output.append(binascii.unhexlify(line[9:-2]))
if (output[0][0:2].decode() != u):
return
output[0] = output[0][4:]
output[-1] = output[-1].strip(b)
script = b.join(output... | Takes a hexlified script and turns it back into a string of Python code. |
3,909 | def _increment_504_stat(self, request):
for key in self.stats_dict:
if key == :
unique = request.url + str(time.time())
self.stats_dict[key].increment(unique)
else:
self.stats_dict[key].increment()
self.logger.debug("Increm... | Increments the 504 stat counters
@param request: The scrapy request in the spider |
3,910 | def get_record(self, **kwargs):
if not self._initialized:
raise pycdlibexception.PyCdlibInvalidInput()
num_paths = 0
for key in kwargs:
if key in [, , , ]:
if kwargs[key] is not None:
num_paths += 1
else:
... | Get the directory record for a particular path.
Parameters:
iso_path - The absolute path on the ISO9660 filesystem to get the
record for.
rr_path - The absolute path on the Rock Ridge filesystem to get the
record for.
joliet_path - The absolute ... |
3,911 | def _clone_block_and_wires(block_in):
block_in.sanity_check()
block_out = block_in.__class__()
temp_wv_map = {}
with set_working_block(block_out, no_sanity_check=True):
for wirevector in block_in.wirevector_subset():
new_wv = clone_wire(wirevector)
temp_wv_map[wire... | This is a generic function to copy the WireVectors for another round of
synthesis This does not split a WireVector with multiple wires.
:param block_in: The block to change
:param synth_name: a name to prepend to all new copies of a wire
:return: the resulting block and a WireVector map |
3,912 | def create(self, create_missing=None):
return UserGroup(
self._server_config,
id=self.create_json(create_missing)[],
).read() | Do extra work to fetch a complete set of attributes for this entity.
For more information, see `Bugzilla #1301658
<https://bugzilla.redhat.com/show_bug.cgi?id=1301658>`_. |
3,913 | def update_dist_caches(dist_path, fix_zipimporter_caches):
normalized_path = normalize_path(dist_path)
_uncache(normalized_path, sys.path_importer_cache)
if fix_zipimporter_caches:
_replace_zip_directory_cache_data(normalized_path)
else... | Fix any globally cached `dist_path` related data
`dist_path` should be a path of a newly installed egg distribution (zipped
or unzipped).
sys.path_importer_cache contains finder objects that have been cached when
importing data from the original distribution. Any such finders need to be
cleared si... |
3,914 | def check_exists(subreddit):
req = get( % subreddit, headers={: })
if req.json().get() == :
return False
return req.status_code == 200 | Make sure that a subreddit actually exists. |
3,915 | def CheckForQuestionPending(task):
vm = task.info.entity
if vm is not None and isinstance(vm, vim.VirtualMachine):
qst = vm.runtime.question
if qst is not None:
raise TaskBlocked("Task blocked, User Intervention required") | Check to see if VM needs to ask a question, throw exception |
3,916 | def make_token(cls, ephemeral_token: ) -> str:
value = ephemeral_token.key
if ephemeral_token.scope:
value += .join(ephemeral_token.scope)
return get_hmac(cls.KEY_SALT + ephemeral_token.salt, value)[::2] | Returns a token to be used x number of times to allow a user account to access
certain resource. |
3,917 | def fprint(self, obj, stream=None, **kwargs):
if stream is None:
stream = sys.stdout
options = self.options
options.update(kwargs)
if isinstance(obj, dimod.SampleSet):
self._print_sampleset(obj, stream, **options)
return
raise TypeE... | Prints the formatted representation of the object on stream |
3,918 | def get_branding_metadata(self):
metadata = dict(self._branding_metadata)
metadata.update({: self.my_osid_object_form._my_map[]})
return Metadata(**metadata) | Gets the metadata for the asset branding.
return: (osid.Metadata) - metadata for the asset branding.
*compliance: mandatory -- This method must be implemented.* |
3,919 | def require(self, path=None, contents=None, source=None, url=None, md5=None,
use_sudo=False, owner=None, group=, mode=None, verify_remote=True,
temp_dir=):
func = use_sudo and run_as_root or self.run
if path and not (contents or source or url):
assert pat... | Require a file to exist and have specific contents and properties.
You can provide either:
- *contents*: the required contents of the file::
from fabtools import require
require.file('/tmp/hello.txt', contents='Hello, world')
- *source*: the local path of a file to u... |
3,920 | def list_all_zones_by_name(region=None, key=None, keyid=None, profile=None):
ret = describe_hosted_zones(region=region, key=key, keyid=keyid,
profile=profile)
return [r[] for r in ret] | List, by their FQDNs, all hosted zones in the bound account.
region
Region to connect to.
key
Secret key to be used.
keyid
Access key to be used.
profile
A dict with region, key and keyid, or a pillar key (string) that
contains a dict with region, key and keyi... |
3,921 | def cli(ctx, config, debug, language, verbose):
ctx.obj = {}
try:
ctx.obj[] = Config(normalizations=config,
language=language,
debug=debug,
verbose=verbose)
except ConfigError as e:
... | Cucco allows to apply normalizations to a given text or file.
This normalizations include, among others, removal of accent
marks, stop words an extra white spaces, replacement of
punctuation symbols, emails, emojis, etc.
For more info on how to use and configure Cucco, check the
project website at ... |
3,922 | def format_row(self, row, key, color):
value = row[key]
if isinstance(value, bool) or value is None:
return if value else
if not isinstance(value, Number):
return value
is_integer = float(value).is_integer()
template = if is_integer... | For a given row from the table, format it (i.e. floating
points and color if applicable). |
3,923 | def authorize_application(
request,
redirect_uri = % (FACEBOOK_APPLICATION_DOMAIN, FACEBOOK_APPLICATION_NAMESPACE),
permissions = FACEBOOK_APPLICATION_INITIAL_PERMISSIONS
):
query = {
: FACEBOOK_APPLICATION_ID,
: redirect_uri
}
if permissions:
query[] = .join(p... | Redirect the user to authorize the application.
Redirection is done by rendering a JavaScript snippet that redirects the parent
window to the authorization URI, since Facebook will not allow this inside an iframe. |
3,924 | def end_namespace(self, prefix):
del self._ns[prefix]
self._g.endPrefixMapping(prefix) | Undeclare a namespace prefix. |
3,925 | def redraw(self, reset_camera=False):
self.ren.RemoveAllViewProps()
self.picker = None
self.add_picker_fixed()
self.helptxt_mapper = vtk.vtkTextMapper()
tprops = self.helptxt_mapper.GetTextProperty()
tprops.SetFontSize(14)
tprops.SetFontFamilyToTimes()
... | Redraw the render window.
Args:
reset_camera: Set to True to reset the camera to a
pre-determined default for each structure. Defaults to False. |
3,926 | def validate(self):
self.normalize()
if self._node is None:
logging.debug()
return False
if self._schema is None:
self._schema = XMLSchema(self._schemadoc)
is_valid = self._schema.validate(self._node)
for msg in self._schema.error_... | Validate the current file against the SLD schema. This first normalizes
the SLD document, then validates it. Any schema validation error messages
are logged at the INFO level.
@rtype: boolean
@return: A flag indicating if the SLD is valid. |
3,927 | def get_local_lb(self, loadbal_id, **kwargs):
if not in kwargs:
kwargs[] = (
)
return self.lb_svc.getObject(id=loadbal_id, **kwargs) | Returns a specified local load balancer given the id.
:param int loadbal_id: The id of the load balancer to retrieve
:returns: A dictionary containing the details of the load balancer |
3,928 | def autobuild_release(family=None):
if family is None:
family = utilities.get_family()
env = Environment(tools=[])
env[] = family.tile
target = env.Command([], [],
action=env.Action(create_release_settings_action, "Creating release manifest"))
env.AlwaysBuild... | Copy necessary files into build/output so that this component can be used by others
Args:
family (ArchitectureGroup): The architecture group that we are targeting. If not
provided, it is assumed that we are building in the current directory and the
module_settings.json file is read... |
3,929 | def query_singleton_edges_from_network(self, network: Network) -> sqlalchemy.orm.query.Query:
ne1 = aliased(network_edge, name=)
ne2 = aliased(network_edge, name=)
singleton_edge_ids_for_network = (
self.session
.query(ne1.c.edge_id)
.outerjoi... | Return a query selecting all edge ids that only belong to the given network. |
3,930 | def ec_number(self, ec_number=None, entry_name=None, limit=None, as_df=False):
q = self.session.query(models.ECNumber)
q = self.get_model_queries(q, ((ec_number, models.ECNumber.ec_number),))
q = self.get_one_to_many_queries(q, ((entry_name, models.Entry.name),))
return self.... | Method to query :class:`.models.ECNumber` objects in database
:param ec_number: Enzyme Commission number(s)
:type ec_number: str or tuple(str) or None
:param entry_name: name(s) in :class:`.models.Entry`
:type entry_name: str or tuple(str) or None
:param limit:
- i... |
3,931 | def new(cls, package):
partname = package.next_partname("/word/footer%d.xml")
content_type = CT.WML_FOOTER
element = parse_xml(cls._default_footer_xml())
return cls(partname, content_type, element, package) | Return newly created footer part. |
3,932 | def fit(self, Z):
check_rdd(Z, {: (sp.spmatrix, np.ndarray)})
return self._spark_fit(SparkLinearRegression, Z) | Fit linear model.
Parameters
----------
Z : DictRDD with (X, y) values
X containing numpy array or sparse matrix - The training data
y containing the target values
Returns
-------
self : returns an instance of self. |
3,933 | def value(self) -> Decimal:
assert isinstance(self.price, Decimal)
return self.quantity * self.price | Value of the holdings in exchange currency.
Value = Quantity * Price |
3,934 | def _handle_response(self, response):
if isinstance(response, Exception):
logging.error("dropped chunk %s" % response)
elif response.json().get("limits"):
parsed = response.json()
self._api.dynamic_settings.update(parsed["limits"]) | Logs dropped chunks and updates dynamic settings |
3,935 | def calc_point_distance(self, chi_coords):
chi1_bin, chi2_bin = self.find_point_bin(chi_coords)
min_dist = 1000000000
indexes = None
for chi1_bin_offset, chi2_bin_offset in self.bin_loop_order:
curr_chi1_bin = chi1_bin + chi1_bin_offset
curr_chi2_bin = ch... | Calculate distance between point and the bank. Return the closest
distance.
Parameters
-----------
chi_coords : numpy.array
The position of the point in the chi coordinates.
Returns
--------
min_dist : float
The smallest **SQUARED** metri... |
3,936 | def run_sphinx():
old_dir = here_directory()
os.chdir(str(doc_directory()))
doc_status = subprocess.check_call([, ], shell=True)
os.chdir(str(old_dir))
if doc_status is not 0:
exit(Fore.RED + ) | Runs Sphinx via it's `make html` command |
3,937 | def __get_state_by_id(cls, job_id):
state = model.MapreduceState.get_by_job_id(job_id)
if state is None:
raise ValueError("Job state for job %s is missing." % job_id)
return state | Get job state by id.
Args:
job_id: job id.
Returns:
model.MapreduceState for the job.
Raises:
ValueError: if the job state is missing. |
3,938 | def from_twodim_list(cls, datalist, tsformat=None):
ts = TimeSeries()
ts.set_timeformat(tsformat)
for entry in datalist:
ts.add_entry(*entry[:2])
ts._normalized = ts.is_normalized()
ts.sort_timeseries()
return ts | Creates a new TimeSeries instance from the data stored inside a two dimensional list.
:param list datalist: List containing multiple iterables with at least two values.
The first item will always be used as timestamp in the predefined format,
the second represents the value. All othe... |
3,939 | def display_message(
self, subject=, message="This is a note",
sounds=False
):
data = json.dumps(
{
: self.content[],
: subject,
: sounds,
: True,
: message
}
)
se... | Send a request to the device to play a sound.
It's possible to pass a custom message by changing the `subject`. |
3,940 | def chebyshev(x, y):
result = 0.0
for i in range(x.shape[0]):
result = max(result, np.abs(x[i] - y[i]))
return result | Chebyshev or l-infinity distance.
..math::
D(x, y) = \max_i |x_i - y_i| |
3,941 | def collect_loaded_packages() -> List[Tuple[str, str]]:
dists = get_installed_distributions()
get_dist_files = DistFilesFinder()
file_table = {}
for dist in dists:
for file in get_dist_files(dist):
file_table[file] = dist
used_dists = set()
for module in list(s... | Return the currently loaded package names and their versions. |
3,942 | def unique(seq):
try:
return list(OrderedDict.fromkeys(seq))
except TypeError:
unique_values = []
for i in seq:
if i not in unique_values:
unique_values.append(i)
return unique_values | Return the unique values in a sequence.
Parameters
----------
seq : sequence
Sequence with (possibly duplicate) elements.
Returns
-------
unique : list
Unique elements of ``seq``.
Order is guaranteed to be the same as in seq.
Examples
--------
Determine uni... |
3,943 | def human_or_11(X, y, model_generator, method_name):
return _human_or(X, model_generator, method_name, True, True) | OR (true/true)
This tests how well a feature attribution method agrees with human intuition
for an OR operation combined with linear effects. This metric deals
specifically with the question of credit allocation for the following function
when all three inputs are true:
if fever: +2 points
if c... |
3,944 | async def trigger_all(self, *args, **kwargs):
:meth:`act` return values.
Given arguments and keyword arguments are passed down to each agents manager agent, i.e. if the environment
has :attr:`manager`, is excluded from acting.
'
tasks = []
for a in self.get_agents(a... | Trigger all agents in the environment to act asynchronously.
:returns: A list of agents' :meth:`act` return values.
Given arguments and keyword arguments are passed down to each agent's
:meth:`creamas.core.agent.CreativeAgent.act`.
.. note::
By design, the environment's m... |
3,945 | def get_log_hierarchy_id(self):
if self._catalog_session is not None:
return self._catalog_session.get_catalog_hierarchy_id()
return self._hierarchy_session.get_hierarchy_id() | Gets the hierarchy ``Id`` associated with this session.
return: (osid.id.Id) - the hierarchy ``Id`` associated with this
session
*compliance: mandatory -- This method must be implemented.* |
3,946 | def upload_file(self, body,
key=None,
metadata=None,
headers=None,
access_key=None,
secret_key=None,
queue_derive=None,
verbose=None,
verify=None,
... | Upload a single file to an item. The item will be created
if it does not exist.
:type body: Filepath or file-like object.
:param body: File or data to be uploaded.
:type key: str
:param key: (optional) Remote filename.
:type metadata: dict
:param metadata: (opt... |
3,947 | def do_child_count(self, params):
for child, level in self._zk.tree(params.path, params.depth, full_path=True):
self.show_output("%s: %d", child, self._zk.child_count(child)) | \x1b[1mNAME\x1b[0m
child_count - Prints the child count for paths
\x1b[1mSYNOPSIS\x1b[0m
child_count [path] [depth]
\x1b[1mOPTIONS\x1b[0m
* path: the path (default: cwd)
* max_depth: max recursion limit (0 is no limit) (default: 1)
\x1b[1mEXAMPLES\x1b[0m
> child-count /
... |
3,948 | def _get_phrase_list_from_words(self, word_list):
groups = groupby(word_list, lambda x: x not in self.to_ignore)
phrases = [tuple(group[1]) for group in groups if group[0]]
return list(
filter(
lambda x: self.min_length <= len(x) <= self.max_length, phrases
... | Method to create contender phrases from the list of words that form
a sentence by dropping stopwords and punctuations and grouping the left
words into phrases. Only phrases in the given length range (both limits
inclusive) would be considered to build co-occurrence matrix. Ex:
Sentence:... |
3,949 | def gene_ids(self, contig=None, strand=None):
return self._all_feature_values(
column="gene_id",
feature="gene",
contig=contig,
strand=strand) | What are all the gene IDs
(optionally restrict to a given chromosome/contig and/or strand) |
3,950 | def model(self):
try:
return self.data.get().get()
except (KeyError, AttributeError):
return self.device_status_simple() | Return the model name of the printer. |
3,951 | def db_parse( block_id, txid, vtxindex, op, data, senders, inputs, outputs, fee, db_state=None, **virtualchain_hints ):
if len(senders) == 0:
raise Exception("No senders given")
if not check_tx_sender_types(senders, block_id):
log.warning(.format(txid))
return None
assert in... | (required by virtualchain state engine)
Parse a blockstack operation from a transaction. The transaction fields are as follows:
* `block_id` is the blockchain height at which this transaction occurs
* `txid` is the transaction ID
* `data` is the scratch area of the transaction that contains the actual ... |
3,952 | def trimmed(self, n_peaks):
result = self.copy()
result.trim(n_peaks)
return result | :param n_peaks: number of peaks to keep
:returns: an isotope pattern with removed low-intensity peaks
:rtype: CentroidedSpectrum |
3,953 | def make_parent_dirs(path, mode=0o777):
parent = os.path.dirname(path)
if parent:
make_all_dirs(parent, mode)
return path | Ensure parent directories of a file are created as needed. |
3,954 | def next(self):
rv = self.current
self.pos = (self.pos + 1) % len(self.items)
return rv | Goes one item ahead and returns it. |
3,955 | def get_band_qpoints(band_paths, npoints=51, rec_lattice=None):
npts = _get_npts(band_paths, npoints, rec_lattice)
qpoints_of_paths = []
c = 0
for band_path in band_paths:
nd = len(band_path)
for i in range(nd - 1):
delta = np.subtract(band_path[i + 1], band_path[i]) / ... | Generate qpoints for band structure path
Note
----
Behavior changes with and without rec_lattice given.
Parameters
----------
band_paths: list of array_likes
Sets of end points of paths
dtype='double'
shape=(sets of paths, paths, 3)
example:
[[[0, ... |
3,956 | def diff(self, n, axis=1):
new_values = algos.diff(self.values, n, axis=axis)
return [self.make_block(values=new_values)] | return block for the diff of the values |
3,957 | def _configure(self, *args):
gldrawable = self.get_gl_drawable()
glcontext = self.get_gl_context()
if not gldrawable or not gldrawable.gl_begin(glcontext):
return False
glViewport(0, 0, self.get_allocation().width, self.... | Configure viewport
This method is called when the widget is resized or something triggers a redraw. The method configures the
view to show all elements in an orthogonal perspective. |
3,958 | def update(self, request, id):
if self.readonly:
return HTTPMethodNotAllowed(headers={: })
session = self.Session()
obj = session.query(self.mapped_class).get(id)
if obj is None:
return HTTPNotFound()
feature = loads(request.body, object_hook=GeoJ... | Read the GeoJSON feature from the request body and update the
corresponding object in the database. |
3,959 | def _submit_and_wait(cmd, cores, config, output_dir):
batch_script = "submit_bcl2fastq.sh"
if not os.path.exists(batch_script + ".finished"):
if os.path.exists(batch_script + ".failed"):
os.remove(batch_script + ".failed")
with open(batch_script, "w") as out_handle:
... | Submit command with batch script specified in configuration, wait until finished |
3,960 | def splitext( filename ):
index = filename.find()
if index == 0:
index = 1+filename[1:].find()
if index == -1:
return filename,
return filename[:index], filename[index:]
return os.path.splitext(filename) | Return the filename and extension according to the first dot in the filename.
This helps date stamping .tar.bz2 or .ext.gz files properly. |
3,961 | def _bdd(node):
try:
bdd = _BDDS[node]
except KeyError:
bdd = _BDDS[node] = BinaryDecisionDiagram(node)
return bdd | Return a unique BDD. |
3,962 | def _make_file_dict(self, f):
if isinstance(f, dict):
file_obj = f[]
if in f:
file_name = f[]
else:
file_name = file_obj.name
else:
file_obj = f
file_name = f.name
b64_data = base64.b64encode(f... | Make a dictionary with filename and base64 file data |
3,963 | def generate_listall_output(lines, resources, aws_config, template, arguments, nodup = False):
for line in lines:
output = []
for resource in resources:
current_path = resource.split()
outline = line[1]
for key in line[2]:
outline = outline.re... | Format and print the output of ListAll
:param lines:
:param resources:
:param aws_config:
:param template:
:param arguments:
:param nodup:
:return: |
3,964 | def is_ancestor_of_objective_bank(self, id_, objective_bank_id):
if self._catalog_session is not None:
return self._catalog_session.is_ancestor_of_catalog(id_=id_, catalog_id=objective_bank_id)
return self._hierarchy_session.is_ancestor(id_=id_, ancestor_id=objecti... | Tests if an ``Id`` is an ancestor of an objective bank.
arg: id (osid.id.Id): an ``Id``
arg: objective_bank_id (osid.id.Id): the ``Id`` of an
objective bank
return: (boolean) - ``true`` if this ``id`` is an ancestor of
``objective_bank_id,`` ``false`` other... |
3,965 | def equals(df1, df2, ignore_order=set(), ignore_indices=set(), all_close=False, _return_reason=False):
re equal, the latter is `None` if
equal or a short explanation of why the data frames arens ``NaN``. Values needni1i2i3index1c1c2c3columns1i3i1i2c2c1c3i3i1i2other
result = _equals(df1, df2, ignore_orde... | Get whether 2 data frames are equal.
``NaN`` is considered equal to ``NaN`` and `None`.
Parameters
----------
df1 : ~pandas.DataFrame
Data frame to compare.
df2 : ~pandas.DataFrame
Data frame to compare.
ignore_order : ~typing.Set[int]
Axi in which to ignore order.
... |
3,966 | def get_default_pandas_converters() -> List[Union[Converter[Any, pd.DataFrame],
Converter[pd.DataFrame, Any]]]:
return [ConverterFunction(from_type=pd.DataFrame, to_type=dict, conversion_method=single_row_or_col_df_to_dict),
ConverterFunction(from_t... | Utility method to return the default converters associated to dataframes (from dataframe to other type,
and from other type to dataframe)
:return: |
3,967 | def grasstruth(args):
p = OptionParser(grasstruth.__doc__)
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(not p.print_help())
james, = args
fp = open(james)
pairs = set()
for row in fp:
atoms = row.split()
genes = []
idx = {}
for i,... | %prog grasstruth james-pan-grass.txt
Prepare truth pairs for 4 grasses. |
3,968 | def add_username(user, apps):
if not user:
return None
apps = [a for a in apps if a.instance == user.instance]
if not apps:
return None
from toot.api import verify_credentials
creds = verify_credentials(apps.pop(), user)
return User(user.instance, creds[], user.access_to... | When using broser login, username was not stored so look it up |
3,969 | def translate_y(self, d):
mat = numpy.array([
[1, 0, 0, 0],
[0, 1, 0, 0],
[0, 0, 1, 0],
[0, d, 0, 1]
])
self.vectors = self.vectors.dot(mat)
return self | Translate mesh for y-direction
:param float d: Amount to translate |
3,970 | def evaluate(self, env, engine, parser, term_type, eval_in_python):
if engine == :
res = self(env)
else:
left = self.lhs.evaluate(env, engine=engine, parser=parser,
term_type=term_type,
... | Evaluate a binary operation *before* being passed to the engine.
Parameters
----------
env : Scope
engine : str
parser : str
term_type : type
eval_in_python : list
Returns
-------
term_type
The "pre-evaluated" expression as an... |
3,971 | def find_path_package(thepath):
pname = find_path_package_name(thepath)
if not pname:
return None
fromlist = b if six.PY2 else
return __import__(pname, globals(), locals(), [fromlist]) | Takes a file system path and returns the module object of the python
package the said path belongs to. If the said path can not be
determined, it returns None. |
3,972 | def sample_stats_to_xarray(self):
dtypes = {"divergent__": bool, "n_leapfrog__": np.int64, "treedepth__": np.int64}
dims = deepcopy(self.dims) if self.dims is not None else {}
coords = deepcopy(self.coords) if self.coords is not None else {}
sampler_params = self.samp... | Extract sample_stats from fit. |
3,973 | def removed(self):
def _removed(diffs, prefix):
keys = []
for key in diffs.keys():
if isinstance(diffs[key], dict) and not in diffs[key]:
keys.extend(_removed(diffs[key],
prefix=.format(prefix, key)))
... | Returns all keys that have been removed.
If the keys are in child dictionaries they will be represented with
. notation |
3,974 | def int_to_bin(i):
i1 = i % 256
i2 = int(i / 256)
return chr(i1) + chr(i2) | Integer to two bytes |
3,975 | def get_one_over_n_factorial(counter_entry):
r
factos = [sp.factorial(c) for c in counter_entry]
prod = product(factos)
return sp.Integer(1)/sp.S(prod) | r"""
Calculates the :math:`\frac{1}{\mathbf{n!}}` of eq. 6 (see Ale et al. 2013).
That is the invert of a product of factorials.
:param counter_entry: an entry of counter. That is an array of integers of length equal to the number of variables.
For instance, `counter_entry` could be `[1,0,1]` for three... |
3,976 | def _set_range(self, init):
self._speed *= 0.0
w, h = self._viewbox.size
w, h = float(w), float(h)
x1, y1, z1 = self._xlim[0], self._ylim[0], self._zlim[0]
x2, y2, z2 = self._xlim[1], self._ylim[1], self._zlim[1]
rx, ry, rz... | Reset the view. |
3,977 | def __select_alternatives (self, property_set_, debug):
best = None
best_properties = None
if len (self.alternatives_) == 0:
return None
if len (self.alternatives_) == 1:
return self.alternatives_ [0... | Returns the best viable alternative for this property_set
See the documentation for selection rules.
# TODO: shouldn't this be 'alternative' (singular)? |
3,978 | def get_template_names(self):
names = super(EasyUIDatagridView, self).get_template_names()
names.append()
return names | datagrid的默认模板 |
3,979 | def sg_input(shape=None, dtype=sg_floatx, name=None):
r
if shape is None:
return tf.placeholder(dtype, shape=None, name=name)
else:
if not isinstance(shape, (list, tuple)):
shape = [shape]
return tf.placeholder(dtype, shape=[None] + list(shape), name=name) | r"""Creates a placeholder.
Args:
shape: A tuple/list of integers. If an integers is given, it will turn to a list.
dtype: A data type. Default is float32.
name: A name for the placeholder.
Returns:
A wrapped placeholder `Tensor`. |
3,980 | def check_extracted_paths(namelist, subdir=None):
def relpath(p):
q = os.path.relpath(p)
if p.endswith(os.path.sep) or p.endswith():
q += os.path.sep
return q
parent = os.path.abspath()
if subdir:
if os.path.isabs(subdir):
raise... | Check whether zip file paths are all relative, and optionally in a
specified subdirectory, raises an exception if not
namelist: A list of paths from the zip file
subdir: If specified then check whether all paths in the zip file are
under this subdirectory
Python docs are unclear about the securi... |
3,981 | def replace_header(self, name, value):
name_lower = name.lower()
for index in range(len(self.headers) - 1, -1, -1):
curr_name, curr_value = self.headers[index]
if curr_name.lower() == name_lower:
self.headers[index] = (curr_name, value)
re... | replace header with new value or add new header
return old header value, if any |
3,982 | def images(arrays, labels=None, domain=None, w=None):
s =
for i, array in enumerate(arrays):
url = _image_url(array)
label = labels[i] if labels is not None else i
s += .format(label=label, url=url)
s += "</div>"
_display_html(s) | Display a list of images with optional labels.
Args:
arrays: A list of NumPy arrays representing images
labels: A list of strings to label each image.
Defaults to show index if None
domain: Domain of pixel values, inferred from min & max values if None
w: width of output image, scaled using nea... |
3,983 | def p_subind_strTO(p):
p[0] = (make_typecast(TYPE.uinteger, make_number(0, lineno=p.lineno(2)),
p.lineno(1)),
make_typecast(TYPE.uinteger, p[3], p.lineno(2))) | substr : LP TO expr RP |
3,984 | def participants(self):
if self._participants is None:
self._participants = ParticipantList(
self._version,
account_sid=self._solution[],
conference_sid=self._solution[],
)
return self._participants | Access the participants
:returns: twilio.rest.api.v2010.account.conference.participant.ParticipantList
:rtype: twilio.rest.api.v2010.account.conference.participant.ParticipantList |
3,985 | def from_object(self, obj: Union[str, Any]) -> None:
if isinstance(obj, str):
obj = importer.import_object_str(obj)
for key in dir(obj):
if key.isupper():
value = getattr(obj, key)
self._setattr(key, value)
logger.info("Config is... | Load values from an object. |
3,986 | def users_text(self):
if self._users_text is None:
self.chain.connection.log("Getting connected users text")
self._users_text = self.driver.get_users_text()
if self._users_text:
self.chain.connection.log("Users text collected")
else:
... | Return connected users information and collect if not available. |
3,987 | def update_from_delta(self, delta, *args):
for (node, extant) in delta.get(, {}).items():
if extant:
if node in delta.get(, {}) \
and in delta[][node]\
and node not in self.pawn:
self.add_pawn(node)
... | Apply the changes described in the dict ``delta``. |
3,988 | def load_country_map_data():
csv_bytes = get_example_data(
, is_gzip=False, make_bytes=True)
data = pd.read_csv(csv_bytes, encoding=)
data[] = datetime.datetime.now().date()
data.to_sql(
,
db.engine,
if_exists=,
chunksize=500,
dtype={
: ... | Loading data for map with country map |
3,989 | def _sanity_check_all_marked_locations_are_registered(ir_blocks, query_metadata_table):
registered_locations = {
location
for location, _ in query_metadata_table.registered_locations
}
ir_encountered_locations = {
block.location
for block in ir_blocks
... | Assert that all locations in MarkLocation blocks have registered and valid metadata. |
3,990 | def cancel_capture(self):
command = const.CMD_CANCELCAPTURE
cmd_response = self.__send_command(command)
return bool(cmd_response.get()) | cancel capturing finger
:return: bool |
3,991 | def check_base(path, base, os_sep=os.sep):
return (
check_path(path, base, os_sep) or
check_under_base(path, base, os_sep)
) | Check if given absolute path is under or given base.
:param path: absolute path
:type path: str
:param base: absolute base path
:type base: str
:param os_sep: path separator, defaults to os.sep
:return: wether path is under given base or not
:rtype: bool |
3,992 | def get_source_var_declaration(self, var):
return next((x.source_mapping for x in self.variables if x.name == var)) | Return the source mapping where the variable is declared
Args:
var (str): variable name
Returns:
(dict): sourceMapping |
3,993 | def calc_A(Z, x):
if (type(x) is pd.DataFrame) or (type(x) is pd.Series):
x = x.values
if (type(x) is not np.ndarray) and (x == 0):
recix = 0
else:
with warnings.catch_warnings():
warnings.simplefilter()
recix = 1/x
recix... | Calculate the A matrix (coefficients) from Z and x
Parameters
----------
Z : pandas.DataFrame or numpy.array
Symmetric input output table (flows)
x : pandas.DataFrame or numpy.array
Industry output column vector
Returns
-------
pandas.DataFrame or numpy.array
Symmet... |
3,994 | def as_cpf(numero):
_num = digitos(numero)
if is_cpf(_num):
return .format(_num[:3], _num[3:6], _num[6:9], _num[9:])
return numero | Formata um número de CPF. Se o número não for um CPF válido apenas
retorna o argumento sem qualquer modificação. |
3,995 | def to_array(self):
array = super(ContactMessage, self).to_array()
array[] = u(self.phone_number)
array[] = u(self.first_name)
if self.receiver is not None:
if isinstance(self.receiver, None):
array[] = None(self.receiver)
arra... | Serializes this ContactMessage to a dictionary.
:return: dictionary representation of this object.
:rtype: dict |
3,996 | def build_archive_file(archive_contents, zip_file):
for root_dir, _, files in os.walk(archive_contents):
relative_dir = os.path.relpath(root_dir, archive_contents)
for f in files:
temp_file_full_path = os.path.join(
archive_contents, relative_dir, f)
... | Build a Tableau-compatible archive file. |
3,997 | def process_request(self, method, data=None):
self._validate_request_method(method)
attempts = 3
for i in range(attempts):
response = self._send_request(method, data)
if self._is_token_response(response):
... | Process request over HTTP to ubersmith instance.
method: Ubersmith API method string
data: dict of method arguments |
3,998 | def push(self, task, func, *args, **kwargs):
task.to_call(func, *args, **kwargs)
data = task.serialize()
if task.async:
task.task_id = self.backend.push(
self.queue_name,
task.task_id,
data
)
else:
... | Pushes a configured task onto the queue.
Typically, you'll favor using the ``Gator.task`` method or
``Gator.options`` context manager for creating a task. Call this
only if you have specific needs or know what you're doing.
If the ``Task`` has the ``async = False`` option, the task wil... |
3,999 | def delete(self, path, payload=None, headers=None):
return self._request(, path, payload, headers) | HTTP DELETE operation.
:param path: URI Path
:param payload: HTTP Body
:param headers: HTTP Headers
:raises ApiError: Raises if the remote server encountered an error.
:raises ApiConnectionError: Raises if there was a connectivity issue.
:return: Response |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.