_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q43700 | get_product_version | train | def get_product_version(path: typing.Union[str, Path]) -> VersionInfo:
"""
Get version info from executable
Args:
path: path to the executable
Returns: VersionInfo
"""
path = Path(path).absolute()
pe_info = pefile.PE(str(path))
try:
for file_info in pe_info.FileInfo: ... | python | {
"resource": ""
} |
q43701 | ThreadedTaskManager.start | train | def start(self):
"""this function will start the queing thread that executes the
iterator and feeds jobs into the queue. It also starts the worker
threads that just sit and wait for items to appear on the queue. This
is a non blocking call, so the executing thread is free to do other
... | python | {
"resource": ""
} |
q43702 | ThreadedTaskManager.wait_for_completion | train | def wait_for_completion(self, waiting_func=None):
"""This is a blocking function call that will wait for the queuing
thread to complete.
parameters:
waiting_func - this function will be called every one second while
waiting for the queuing thread to quit. ... | python | {
"resource": ""
} |
q43703 | ThreadedTaskManager.wait_for_empty_queue | train | def wait_for_empty_queue(self, wait_log_interval=0, wait_reason=''):
"""Sit around and wait for the queue to become empty
parameters:
wait_log_interval - while sleeping, it is helpful if the thread
periodically announces itself so that we
... | python | {
"resource": ""
} |
q43704 | ThreadedTaskManager._responsive_join | train | def _responsive_join(self, thread, waiting_func=None):
"""similar to the responsive sleep, a join function blocks a thread
until some other thread dies. If that takes a long time, we'd like to
have some indicaition as to what the waiting thread is doing. This
method will wait for anoth... | python | {
"resource": ""
} |
q43705 | ThreadedTaskManager._queuing_thread_func | train | def _queuing_thread_func(self):
"""This is the function responsible for reading the iterator and
putting contents into the queue. It loops as long as there are items
in the iterator. Should something go wrong with this thread, or it
detects the quit flag, it will calmly kill its worker... | python | {
"resource": ""
} |
q43706 | patch | train | def patch(module, external=(), internal=()):
"""
Temporarily monkey-patch dependencies which can be external to, or internal
to the supplied module.
:param module: Module object
:param external: External dependencies to patch (full paths as strings)
:param internal: Internal dependencies to pat... | python | {
"resource": ""
} |
q43707 | _linear_interp | train | def _linear_interp(curve, test_x, round_result=False):
"""
Take a series of points and interpolate between them at ``test_x``.
Args:
curve (list[tuple]): A list of ``(x, y)`` points sorted in
nondecreasing ``x`` value. If multiple points have the same
``x`` value, all but th... | python | {
"resource": ""
} |
q43708 | _clamp_value | train | def _clamp_value(value, minimum, maximum):
"""
Clamp a value to fit between a minimum and a maximum.
* If ``value`` is between ``minimum`` and ``maximum``, return ``value``
* If ``value`` is below ``minimum``, return ``minimum``
* If ``value is above ``maximum``, return ``maximum``
Args:
... | python | {
"resource": ""
} |
q43709 | _normal_function | train | def _normal_function(x, mean, variance):
"""
Find a value in the cumulative distribution function of a normal curve.
See https://en.wikipedia.org/wiki/Normal_distribution
Args:
x (float): Value to feed into the normal function
mean (float): Mean of the normal function
variance ... | python | {
"resource": ""
} |
q43710 | _is_valid_options_weights_list | train | def _is_valid_options_weights_list(value):
'''Check whether ``values`` is a valid argument for ``weighted_choice``.'''
return ((isinstance(value, list)) and
len(value) > 1 and
(all(isinstance(opt, tuple) and
len(opt) == 2 and
isinstance(opt[1], (int, flo... | python | {
"resource": ""
} |
q43711 | bound_weights | train | def bound_weights(weights, minimum=None, maximum=None):
"""
Bound a weight list so that all outcomes fit within specified bounds.
The probability distribution within the ``minimum`` and ``maximum``
values remains the same. Weights in the list with outcomes outside of
``minimum`` and ``maximum`` are... | python | {
"resource": ""
} |
q43712 | normal_distribution | train | def normal_distribution(mean, variance,
minimum=None, maximum=None, weight_count=23):
"""
Return a list of weights approximating a normal distribution.
Args:
mean (float): The mean of the distribution
variance (float): The variance of the distribution
minimum... | python | {
"resource": ""
} |
q43713 | weighted_rand | train | def weighted_rand(weights, round_result=False):
"""
Generate a non-uniform random value based on a list of weight tuples.
Treats weights as coordinates for a probability distribution curve and
rolls accordingly. Constructs a piece-wise linear curve according to
coordinates given in ``weights`` and ... | python | {
"resource": ""
} |
q43714 | weighted_choice | train | def weighted_choice(weights, as_index_and_value_tuple=False):
"""
Generate a non-uniform random choice based on a list of option tuples.
Treats each outcome as a discreet unit with a chance to occur.
Args:
weights (list): a list of options where each option
is a tuple of form ``(An... | python | {
"resource": ""
} |
q43715 | weighted_order | train | def weighted_order(weights):
"""
Non-uniformally order a list according to weighted priorities.
``weights`` is a list of tuples of form ``(Any, float or int)``
corresponding to ``(item, strength)``. The output list is constructed
by repeatedly calling ``weighted_choice()`` on the weights, adding it... | python | {
"resource": ""
} |
q43716 | SocialLM.tokenize | train | def tokenize(cls, text, mode='c'):
""" Converts text into tokens
:param text: string to be tokenized
:param mode: split into chars (c) or words (w)
"""
if mode == 'c':
return [ch for ch in text]
else:
return [w for w in text.split()] | python | {
"resource": ""
} |
q43717 | SocialLM.karbasa | train | def karbasa(self, result):
""" Finding if class probabilities are close to eachother
Ratio of the distance between 1st and 2nd class,
to the distance between 1st and last class.
:param result: The dict returned by LM.calculate()
"""
probs = result['all_probs'... | python | {
"resource": ""
} |
q43718 | SocialLM.is_mention_line | train | def is_mention_line(cls, word):
""" Detects links and mentions
:param word: Token to be evaluated
"""
if word.startswith('@'):
return True
elif word.startswith('http://'):
return True
elif word.startswith('https://'):
return True
... | python | {
"resource": ""
} |
q43719 | SocialLM.strip_mentions_links | train | def strip_mentions_links(self, text):
""" Strips Mentions and Links
:param text: Text to be stripped from.
"""
#print 'Before:', text
new_text = [word for word in text.split() if not self.is_mention_line(word)]
#print 'After:', u' '.join(new_text)
return u' '... | python | {
"resource": ""
} |
q43720 | SocialLM.normalize | train | def normalize(self, text):
""" Normalizes text.
Converts to lowercase,
Unicode NFC normalization
and removes mentions and links
:param text: Text to be normalized.
"""
#print 'Normalize...\n'
text = text.lower()
text = unicodedata.... | python | {
"resource": ""
} |
q43721 | VirtualTarget.output_files | train | def output_files(self):
"""Returns all output files from all of the current module's rules."""
for dep in self.subgraph.successors(self.address):
dep_rule = self.subgraph.node[dep]['target_obj']
for out_file in dep_rule.output_files:
yield out_file | python | {
"resource": ""
} |
q43722 | HttpClientProtocol.write_request | train | async def write_request(
self, method: constants.HttpRequestMethod, *,
uri: str="/", authority: Optional[str]=None,
scheme: Optional[str]=None,
headers: Optional[_HeaderType]=None) -> \
"writers.HttpRequestWriter":
"""
Send next request to the server.
... | python | {
"resource": ""
} |
q43723 | Interval.is_disjoint | train | def is_disjoint(self,other):
"""
Check whether two Intervals are disjoint.
:param Interval other: The Interval to check disjointedness with.
"""
if self.is_empty() or other.is_empty():
return True
if self.bounds[0] < other.bounds[0]:
i1,i2 = self... | python | {
"resource": ""
} |
q43724 | Interval.intersection | train | def intersection(self,other):
"""
Return a new Interval with the intersection of the two intervals,
i.e. all elements that are in both self and other.
:param Interval other: Interval to intersect with
:rtype: Interval
"""
if self.bounds[0] < other.bounds[0]:
... | python | {
"resource": ""
} |
q43725 | Interval.is_empty | train | def is_empty(self):
"""
Check whether this interval is empty.
:rtype: bool
"""
if self.bounds[1] < self.bounds[0]:
return True
if self.bounds[1] == self.bounds[0]:
return not (self.included[0] and self.included[1]) | python | {
"resource": ""
} |
q43726 | Interval.is_discrete | train | def is_discrete(self):
"""
Check whether this interval contains exactly one number
:rtype: bool
"""
return self.bounds[1] == self.bounds[0] and\
self.included == (True,True) | python | {
"resource": ""
} |
q43727 | IntervalSet.intersection | train | def intersection(self,other):
"""
Return a new IntervalSet with the intersection of the two sets, i.e.
all elements that are both in self and other.
:param IntervalSet other: Set to intersect with
:rtype: IntervalSet
"""
res = []
for i1 in self.ints:
... | python | {
"resource": ""
} |
q43728 | IntervalSet.difference | train | def difference(self,other):
"""
Return a new IntervalSet with the difference of the two sets, i.e.
all elements that are in self but not in other.
:param IntervalSet other: Set to subtract
:rtype: IntervalSet
"""
res = IntervalSet.everything()
for j in ot... | python | {
"resource": ""
} |
q43729 | DiscreteSet.intersection | train | def intersection(self,other):
"""
Return a new DiscreteSet with the intersection of the two sets, i.e.
all elements that are in both self and other.
:param DiscreteSet other: Set to intersect with
:rtype: DiscreteSet
"""
if self.everything:
if other.e... | python | {
"resource": ""
} |
q43730 | DiscreteSet.difference | train | def difference(self,other):
"""
Return a new DiscreteSet with the difference of the two sets, i.e.
all elements that are in self but not in other.
:param DiscreteSet other: Set to subtract
:rtype: DiscreteSet
:raises ValueError: if self is a set of everything
"""... | python | {
"resource": ""
} |
q43731 | DiscreteSet.union | train | def union(self,other):
"""
Return a new DiscreteSet with the union of the two sets, i.e.
all elements that are in self or in other.
:param DiscreteSet other: Set to unite with
:rtype: DiscreteSet
"""
if self.everything:
return self
elif other.... | python | {
"resource": ""
} |
q43732 | Patch.intersection | train | def intersection(self,other):
"intersection with another patch"
res = {}
if set(self.sets.keys()) != set(other.sets.keys()):
raise KeyError('Incompatible patches in intersection')
for name,s1 in self.sets.items():
s2 = other.sets[name]
res[name] = s1.i... | python | {
"resource": ""
} |
q43733 | Patch.iter_points | train | def iter_points(self):
"returns a list of tuples of names and values"
if not self.is_discrete():
raise ValueError("Patch is not discrete")
names = sorted(self.sets.keys())
icoords = [self.sets[name].iter_members() for name in names]
for coordinates in product(*icoords... | python | {
"resource": ""
} |
q43734 | FormLabelModelAdminMixin.update_form_labels | train | def update_form_labels(self, request=None, obj=None, form=None):
"""Returns a form obj after modifying form labels
referred to in custom_form_labels.
"""
for form_label in self.custom_form_labels:
if form_label.field in form.base_fields:
label = form_label.get... | python | {
"resource": ""
} |
q43735 | open_filezip | train | def open_filezip(file_path, find_str):
"""
Open the wrapped file.
Read directly from the zip without extracting its content.
"""
if zipfile.is_zipfile(file_path):
zipf = zipfile.ZipFile(file_path)
interesting_files = [f for f in zipf.infolist() if find_str in f]
for inside_f... | python | {
"resource": ""
} |
q43736 | extract_filezip | train | def extract_filezip(path_to_file, dest_path, target_zipfiles=None):
"""
Extract file zip to destiny path folder targeting only some kind of files.
"""
target_zipfiles = ['.*'] if target_zipfiles is None else target_zipfiles
files = []
_, ext = os.path.splitext(path_to_file)
if ext == '.zi... | python | {
"resource": ""
} |
q43737 | copy_remote_file | train | def copy_remote_file(web_file, destination):
"""
Check if exist the destination path, and copy the online resource
file to local.
Args:
:web_file: reference to online file resource to take.
:destination: path to store the file.
"""
size = 0
dir_name = os.path.dirname(destina... | python | {
"resource": ""
} |
q43738 | remove_file | train | def remove_file(paths):
"""
Remove file from paths introduced.
"""
for path in force_list(paths):
if os.path.exists(path):
os.remove(path) | python | {
"resource": ""
} |
q43739 | Signature.generate_headers | train | def generate_headers(self, client_type, client_id, secret):
"""
generate_headers is used to generate the headers automatically for your http request
:param client_type (str): remoteci or feeder
:param client_id (str): remoteci or feeder id
:param secret (str): api secret
... | python | {
"resource": ""
} |
q43740 | addLadder | train | def addLadder(settings):
"""define a new Ladder setting and save to disk file"""
ladder = Ladder(settings)
ladder.save()
getKnownLadders()[ladder.name] = ladder
return ladder | python | {
"resource": ""
} |
q43741 | delLadder | train | def delLadder(name):
"""forget about a previously defined Ladder setting by deleting its disk file"""
ladders = getKnownLadders()
try:
ladder = ladders[name]
os.remove(ladder.filename) # delete from disk
del ladders[name] # deallocate object
return ladder
except KeyError:... | python | {
"resource": ""
} |
q43742 | getKnownLadders | train | def getKnownLadders(reset=False):
"""identify all of the currently defined ladders"""
if not ladderCache or reset:
jsonFiles = os.path.join(c.LADDER_FOLDER, "*.json")
for ladderFilepath in glob.glob(jsonFiles):
filename = os.path.basename(ladderFilepath)
name = re.search(... | python | {
"resource": ""
} |
q43743 | Oscillator.get_samples | train | def get_samples(self, sample_count):
"""
Fetch a number of samples from self.wave_cache
Args:
sample_count (int): Number of samples to fetch
Returns: ndarray
"""
if self.amplitude.value <= 0:
return None
# Build samples by rolling the per... | python | {
"resource": ""
} |
q43744 | LinterOutput._cmp_key | train | def _cmp_key(self, obj=None):
"""Comparison key for sorting results from all linters.
The sort should group files and lines from different linters to make it
easier for refactoring.
"""
if not obj:
obj = self
line_nr = int(obj.line_nr) if obj.line_nr else 0
... | python | {
"resource": ""
} |
q43745 | Linter._get_relative_path | train | def _get_relative_path(self, full_path):
"""Return the relative path from current path."""
try:
rel_path = Path(full_path).relative_to(Path().absolute())
except ValueError:
LOG.error("%s: Couldn't find relative path of '%s' from '%s'.",
self.name, fu... | python | {
"resource": ""
} |
q43746 | Linter._parse_by_pattern | train | def _parse_by_pattern(self, lines, pattern):
"""Match pattern line by line and return Results.
Use ``_create_output_from_match`` to convert pattern match groups to
Result instances.
Args:
lines (iterable): Output lines to be parsed.
pattern: Compiled pattern to ... | python | {
"resource": ""
} |
q43747 | Linter._create_output_from_match | train | def _create_output_from_match(self, match_result):
"""Create Result instance from pattern match results.
Args:
match: Pattern match.
"""
if isinstance(match_result, dict):
return LinterOutput(self.name, **match_result)
return LinterOutput(self.name, *matc... | python | {
"resource": ""
} |
q43748 | plain_storage.get_single_file_info | train | def get_single_file_info(self, rel_path):
""" Gets last change time for a single file """
f_path = self.get_full_file_path(rel_path)
return get_single_file_info(f_path, rel_path) | python | {
"resource": ""
} |
q43749 | plain_storage.read_local_manifest | train | def read_local_manifest(self):
""" Read the file manifest, or create a new one if there isn't one already """
manifest = file_or_default(self.get_full_file_path(self.manifest_file), {
'format_version' : 2,
'root' : '/',
'have_revision' : 'root',
... | python | {
"resource": ""
} |
q43750 | plain_storage.fs_put | train | def fs_put(self, rpath, data):
""" Add a file to the FS """
try:
self.begin()
# Add the file to the fs
self.file_put_contents(rpath, data)
# Add to the manifest
manifest = self.read_local_manifest()
manifest['files'][rpath] = self... | python | {
"resource": ""
} |
q43751 | respond_to_SIGTERM | train | def respond_to_SIGTERM(signal_number, frame, target=None):
""" these classes are instrumented to respond to a KeyboardInterrupt by
cleanly shutting down. This function, when given as a handler to for
a SIGTERM event, will make the program respond to a SIGTERM as neatly
as it responds to ^C.
This f... | python | {
"resource": ""
} |
q43752 | TaskManager.blocking_start | train | def blocking_start(self, waiting_func=None):
"""this function starts the task manager running to do tasks. The
waiting_func is normally used to do something while other threads
are running, but here we don't have other threads. So the waiting
func will never get called. I can see want... | python | {
"resource": ""
} |
q43753 | FSong.makePartitions | train | def makePartitions(self):
"""Make partitions with gmane help.
"""
class NetworkMeasures:
pass
self.nm=nm=NetworkMeasures()
nm.degrees=self.network.degree()
nm.nodes_= sorted(self.network.nodes(), key=lambda x : nm.degrees[x])
nm.degrees_=[nm.degrees[i]... | python | {
"resource": ""
} |
q43754 | FSong.makeImages | train | def makeImages(self):
"""Make spiral images in sectors and steps.
Plain, reversed,
sectorialized, negative sectorialized
outline, outline reversed, lonely
only nodes, only edges, both
"""
# make layout
self.makeLayout()
self.setAgraph()
# ... | python | {
"resource": ""
} |
q43755 | FSong.makeSong | train | def makeSong(self):
"""Render abstract animation
"""
self.makeVisualSong()
self.makeAudibleSong()
if self.make_video:
self.makeAnimation() | python | {
"resource": ""
} |
q43756 | cutoff_filename | train | def cutoff_filename(prefix, suffix, input_str):
"""
Cuts off the start and end of a string, as specified by 2 parameters
Parameters
----------
prefix : string, if input_str starts with prefix, will cut off prefix
suffix : string, if input_str end with suffix, will cut off suffix
input_str :... | python | {
"resource": ""
} |
q43757 | get_frame_src | train | def get_frame_src(f:Frame) -> str:
''' inspects a frame and returns a string with the following
<src-path>:<src-line> -> <function-name>
<source-code>
'''
path, line, src, fn = _get_frame(
inspect.getframeinfo(f)
)
return '{}:{} -> {}\n{}'.format(
path.split(os.sep)[... | python | {
"resource": ""
} |
q43758 | trace | train | def trace(fn=None, profiler=None) -> Callable:
''' This decorator allows you to visually trace
the steps of a function as it executes to see
what happens to the data as things are being
processed.
If you want to use a custom profiler, use the
@trace(profiler=my_custom_profil... | python | {
"resource": ""
} |
q43759 | MoveFileCallback.on_close | train | def on_close(self, filename):
"""Move this file to destination folder."""
shutil.move(filename, self.destination_folder)
path, fn = os.path.split(filename)
return os.path.join(self.destination_folder, fn) | python | {
"resource": ""
} |
q43760 | CRCPubkey.from_str | train | def from_str(cls: Type[CRCPubkeyType], crc_pubkey: str) -> CRCPubkeyType:
"""
Return CRCPubkey instance from CRC public key string
:param crc_pubkey: CRC public key
:return:
"""
data = CRCPubkey.re_crc_pubkey.match(crc_pubkey)
if data is None:
raise E... | python | {
"resource": ""
} |
q43761 | CRCPubkey.from_pubkey | train | def from_pubkey(cls: Type[CRCPubkeyType], pubkey: str) -> CRCPubkeyType:
"""
Return CRCPubkey instance from public key string
:param pubkey: Public key
:return:
"""
hash_root = hashlib.sha256()
hash_root.update(base58.b58decode(pubkey))
hash_squared = has... | python | {
"resource": ""
} |
q43762 | Statement.delete | train | def delete(self):
"""Remove the statement from a ProcmailRC structure, raise a
RuntimeError if the statement is not inside a ProcmailRC structure
return the parent id"""
if self.parent is None:
raise RuntimeError(
"Current statement has no parent, so it cannot... | python | {
"resource": ""
} |
q43763 | GenRuleBuilder._metahash | train | def _metahash(self):
"""Include genrule cmd in the metahash."""
if self._cached_metahash:
return self._cached_metahash
mhash = base.BaseBuilder._metahash(self)
log.debug('[%s]: Metahash input: cmd="%s"', self.address, self.cmd)
mhash.update(self.cmd)
self._cac... | python | {
"resource": ""
} |
q43764 | GenRule.output_files | train | def output_files(self):
"""Returns list of output files from this rule, relative to buildroot.
In this case it's simple (for now) - the output files are enumerated in
the rule definition.
"""
outs = [os.path.join(self.address.repo, self.address.path, x)
for x in ... | python | {
"resource": ""
} |
q43765 | Repo.tag | train | def tag(self, tag: str, overwrite: bool = False) -> None:
"""
Tags the current commit
:param tag: tag
:type tag: str
:param overwrite: overwrite existing tag
:type overwrite: bool
"""
LOGGER.info('tagging repo: %s', tag)
try:
self.repo... | python | {
"resource": ""
} |
q43766 | Repo.list_tags | train | def list_tags(self, pattern: str = None) -> typing.List[str]:
"""
Returns list of tags, optionally matching "pattern"
:param pattern: optional pattern to filter results
:type pattern: str
:return: existing tags
:rtype: list of str
"""
tags: typing.List[st... | python | {
"resource": ""
} |
q43767 | Repo.stash | train | def stash(self, stash_name: str):
"""
Stashes the current working tree changes
:param stash_name: name of the stash
:type stash_name: str
"""
if self.stashed:
LOGGER.error('already stashed')
sys.exit(-1)
else:
if not self.index... | python | {
"resource": ""
} |
q43768 | Repo.unstash | train | def unstash(self):
"""
Pops the last stash if EPAB made a stash before
"""
if not self.stashed:
LOGGER.error('no stash')
else:
LOGGER.info('popping stash')
self.repo.git.stash('pop')
self.stashed = False | python | {
"resource": ""
} |
q43769 | Repo.ensure | train | def ensure():
"""
Makes sure the current working directory is a Git repository.
"""
LOGGER.debug('checking repository')
if not os.path.exists('.git'):
LOGGER.error('This command is meant to be ran in a Git repository.')
sys.exit(-1)
LOGGER.debug('r... | python | {
"resource": ""
} |
q43770 | Repo.stage_all | train | def stage_all(self):
"""
Stages all changed and untracked files
"""
LOGGER.info('Staging all files')
self.repo.git.add(A=True) | python | {
"resource": ""
} |
q43771 | Repo.stage_subset | train | def stage_subset(self, *files_to_add: str):
"""
Stages a subset of files
:param files_to_add: files to stage
:type files_to_add: str
"""
LOGGER.info('staging files: %s', files_to_add)
self.repo.git.add(*files_to_add, A=True) | python | {
"resource": ""
} |
q43772 | Repo.commit | train | def commit(
self,
message: str,
files_to_add: typing.Optional[typing.Union[typing.List[str], str]] = None,
allow_empty: bool = False,
):
"""
Commits changes to the repo
:param message: first line of the message
:type message: str
... | python | {
"resource": ""
} |
q43773 | Repo.amend_commit | train | def amend_commit(
self,
append_to_msg: typing.Optional[str] = None,
new_message: typing.Optional[str] = None,
files_to_add: typing.Optional[typing.Union[typing.List[str], str]] = None,
):
"""
Amends last commit with either an entirely new commit messag... | python | {
"resource": ""
} |
q43774 | Repo.merge | train | def merge(self, ref_name: str):
"""
Merges two refs
Args:
ref_name: ref to merge in the current one
"""
if self.is_dirty():
LOGGER.error('repository is dirty; cannot merge: %s', ref_name)
sys.exit(-1)
LOGGER.info('merging ref: "%s" int... | python | {
"resource": ""
} |
q43775 | Repo.checkout | train | def checkout(self, reference: str):
"""
Checks out a reference.
If the index is dirty, or if the repository contains untracked files, the function will fail.
:param reference: reference to check out
:type reference: str
"""
LOGGER.info('checking out: %s', refere... | python | {
"resource": ""
} |
q43776 | Repo.create_branch | train | def create_branch(self, branch_name: str):
"""
Creates a new branch
Args:
branch_name: name of the branch
"""
LOGGER.info('creating branch: %s', branch_name)
self._validate_branch_name(branch_name)
if branch_name in self.list_branches():
... | python | {
"resource": ""
} |
q43777 | Repo.create_branch_and_checkout | train | def create_branch_and_checkout(self, branch_name: str):
"""
Creates a new branch if it doesn't exist
Args:
branch_name: branch name
"""
self.create_branch(branch_name)
self.checkout(branch_name) | python | {
"resource": ""
} |
q43778 | Repo.is_dirty | train | def is_dirty(self, untracked=False) -> bool:
"""
Checks if the current repository contains uncommitted or untracked changes
Returns: true if the repository is clean
"""
result = False
if not self.index_is_empty():
LOGGER.error('index is not empty')
... | python | {
"resource": ""
} |
q43779 | Text.startswith | train | def startswith(text, ignore_case=True):
"""
Test if a string-field start with ``text``.
Example::
filters = {"path": Text.startswith(r"C:\\")}
"""
if ignore_case:
compiled = re.compile(
"^%s" % text.replace("\\", "\\\\"), re.IGNORECASE)
... | python | {
"resource": ""
} |
q43780 | Text.fulltext | train | def fulltext(search, lang=Lang.English, ignore_case=True):
"""Full text search.
Example::
filters = Text.fulltext("python pymongo_mate")
.. note::
This field doesn't need to specify field.
"""
return {
"$text": {
"$search": ... | python | {
"resource": ""
} |
q43781 | Geo2DSphere.near | train | def near(lat, lng, max_dist=None, unit_miles=False):
"""Find document near a point.
For example:: find all document with in 25 miles radius from 32.0, -73.0.
"""
filters = {
"$nearSphere": {
"$geometry": {
"type": "Point",
... | python | {
"resource": ""
} |
q43782 | FSNode.children | train | def children(self) :
"If the FSNode is a directory, returns a list of the children"
if not self.isdir() : raise Exception("FSQuery tried to return the children of a node which is not a directory : %s" % self.abs)
return [FSNode(self.abs + "/" + x,self.root,self.depth+1) for x in os.listdir(self.... | python | {
"resource": ""
} |
q43783 | FSNode.add_file | train | def add_file(self,fName,content) :
"""If this FSNode is a directory, write a file called fName containing content inside it"""
if not self.isdir() : raise Exception("FSQuery tried to add a file in a node which is not a directory : %s" % self.abs)
self.write_file("%s/%s"%(self.abs,fName),content) | python | {
"resource": ""
} |
q43784 | FSNode.open_file | train | def open_file(self) :
"""If this FSNode is a file, open it for reading and return the file handle"""
if self.isdir() : raise Exception("FSQuery tried to open a directory as a file : %s" % self.abs)
return open(self.abs) | python | {
"resource": ""
} |
q43785 | FSNode.mk_dir | train | def mk_dir(self) :
"""If this FSNode doesn't currently exist, then make a directory with this name."""
if not os.path.exists(self.abs) :
os.makedirs(self.abs) | python | {
"resource": ""
} |
q43786 | FSQuery.walk | train | def walk(self,depth=0,fsNode=None) :
"""Note, this is a filtered walk"""
if not fsNode :
fsNode = FSNode(self.init_path,self.init_path,0)
if fsNode.isdir() :
if self.check_dir(fsNode) :
if self.check_return(fsNode) :
yield ... | python | {
"resource": ""
} |
q43787 | FSQuery.shadow | train | def shadow(self,new_root,visitor) :
""" Runs through the query, creating a clone directory structure in the new_root. Then applies process"""
for n in self.walk() :
sn = n.clone(new_root)
if n.isdir() :
visitor.process_dir(n,sn)
else :
... | python | {
"resource": ""
} |
q43788 | FSQuery.DirContains | train | def DirContains(self,f) :
""" Matches dirs that have a child that matches filter f"""
def match(fsNode) :
if not fsNode.isdir() : return False
for c in fsNode.children() :
if f(c) : return True
return False
return self.make_return(match) | python | {
"resource": ""
} |
q43789 | Directory.register | train | def register(self, peer):
"""
Registers a peer according to its description
:param peer: A Peer description bean
:raise KeyError:
"""
assert isinstance(peer, beans.Peer)
with self.__lock:
# Check presence
peer_id = peer.peer_id
... | python | {
"resource": ""
} |
q43790 | Directory.unregister | train | def unregister(self, peer_id):
"""
Unregisters the given peer
:param peer_id: A peer UUID
:raise KeyError: Unknown peer
"""
with self.__lock:
# Pop it from accesses (will raise a KeyError if absent)
peer = self.peers.pop(peer_id)
asser... | python | {
"resource": ""
} |
q43791 | canonicalize_spec | train | def canonicalize_spec(spec, parent_context):
"""Push all context declarations to the leaves of a nested test specification."""
test_specs = {k:v for (k,v) in spec.items() if k.startswith("Test")}
local_context = {k:v for (k,v) in spec.items() if not k.startswith("Test")}
context = reduce_contexts(parent_conte... | python | {
"resource": ""
} |
q43792 | flatten_spec | train | def flatten_spec(spec, prefix,joiner=" :: "):
"""Flatten a canonical specification with nesting into one without nesting.
When building unique names, concatenate the given prefix to the local test
name without the "Test " tag."""
if any(filter(operator.methodcaller("startswith","Test"),spec.keys())):
flat_... | python | {
"resource": ""
} |
q43793 | load_stanzas | train | def load_stanzas(stanzas_file):
"""
Load stanzas from gold standard file
"""
f = stanzas_file.readlines()
stanzas = []
for i, line in enumerate(f):
if i % 4 == 0:
stanza_words = line.strip().split()[1:]
stanzas.append(Stanza(stanza_words))
return stanzas | python | {
"resource": ""
} |
q43794 | get_wordlist | train | def get_wordlist(stanzas):
"""
Get an iterable of all final words in all stanzas
"""
return sorted(list(set().union(*[stanza.words for stanza in stanzas]))) | python | {
"resource": ""
} |
q43795 | get_rhymelists | train | def get_rhymelists(stanza, scheme):
"""
Returns ordered lists of the stanza's word indices as defined by given scheme
"""
rhymelists = defaultdict(list)
for rhyme_group, word_index in zip(scheme, stanza.word_indices):
rhymelists[rhyme_group].append(word_index)
return list(rhymelists.valu... | python | {
"resource": ""
} |
q43796 | init_distance_ttable | train | def init_distance_ttable(wordlist, distance_function):
"""
Initialize pair-wise rhyme strenghts according to the given word distance function
"""
n = len(wordlist)
t_table = numpy.zeros((n, n + 1))
# Initialize P(c|r) accordingly
for r, w in enumerate(wordlist):
for c, v in enumerat... | python | {
"resource": ""
} |
q43797 | post_prob_scheme | train | def post_prob_scheme(t_table, stanza, scheme):
"""
Compute posterior probability of a scheme for a stanza, with probability of every word in rhymelist
rhyming with all the ones before it
"""
myprob = 1
rhymelists = get_rhymelists(stanza, scheme)
for rhymelist in rhymelists:
for i, wo... | python | {
"resource": ""
} |
q43798 | expectation_step | train | def expectation_step(t_table, stanzas, schemes, rprobs):
"""
Compute posterior probability of schemes for each stanza
"""
probs = numpy.zeros((len(stanzas), schemes.num_schemes))
for i, stanza in enumerate(stanzas):
scheme_indices = schemes.get_schemes_for_len(len(stanza))
for schem... | python | {
"resource": ""
} |
q43799 | maximization_step | train | def maximization_step(num_words, stanzas, schemes, probs):
"""
Update latent variables t_table, rprobs
"""
t_table = numpy.zeros((num_words, num_words + 1))
rprobs = numpy.ones(schemes.num_schemes)
for i, stanza in enumerate(stanzas):
scheme_indices = schemes.get_schemes_for_len(len(stan... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.