INSTRUCTION stringlengths 1 46.3k | RESPONSE stringlengths 75 80.2k |
|---|---|
Find a user with an email address.
Args:
email (str): An email address belonging to a user in the workspace.
e.g. 'spengler@ghostbusters.example.com' | def users_lookupByEmail(self, *, email: str, **kwargs) -> SlackResponse:
"""Find a user with an email address.
Args:
email (str): An email address belonging to a user in the workspace.
e.g. 'spengler@ghostbusters.example.com'
"""
kwargs.update({"email": email... |
Set the user profile photo
Args:
image (str): Supply the path of the image you'd like to upload.
e.g. 'myimage.png' | def users_setPhoto(self, *, image: Union[str, IOBase], **kwargs) -> SlackResponse:
"""Set the user profile photo
Args:
image (str): Supply the path of the image you'd like to upload.
e.g. 'myimage.png'
"""
self._validate_xoxp_token()
return self.api_c... |
Retrieves a user's profile information. | def users_profile_get(self, **kwargs) -> SlackResponse:
"""Retrieves a user's profile information."""
self._validate_xoxp_token()
return self.api_call("users.profile.get", http_verb="GET", params=kwargs) |
Manually sets user presence.
Args:
presence (str): Either 'auto' or 'away'. | def users_setPresence(self, *, presence: str, **kwargs) -> SlackResponse:
"""Manually sets user presence.
Args:
presence (str): Either 'auto' or 'away'.
"""
kwargs.update({"presence": presence})
return self.api_call("users.setPresence", json=kwargs) |
Set the profile information for a user. | def users_profile_set(self, **kwargs) -> SlackResponse:
"""Set the profile information for a user."""
self._validate_xoxp_token()
return self.api_call("users.profile.set", json=kwargs) |
Ensures that an xoxp token is used when the specified method is called.
Raises:
BotUserAccessError: If the API method is called with a Bot User OAuth Access Token. | def _validate_xoxp_token(self):
"""Ensures that an xoxp token is used when the specified method is called.
Raises:
BotUserAccessError: If the API method is called with a Bot User OAuth Access Token.
"""
if self.token.startswith("xoxb"):
method_name = inspect.sta... |
Sends the request out for transmission.
Args:
http_verb (str): The HTTP verb. e.g. 'GET' or 'POST'.
api_url (str): The Slack API url. e.g. 'https://slack.com/api/chat.postMessage'
req_args (dict): The request arguments to be attached to the request.
e.g.
... | async def _send(self, http_verb, api_url, req_args):
"""Sends the request out for transmission.
Args:
http_verb (str): The HTTP verb. e.g. 'GET' or 'POST'.
api_url (str): The Slack API url. e.g. 'https://slack.com/api/chat.postMessage'
req_args (dict): The request ar... |
Submit the HTTP request with the running session or a new session.
Returns:
A dictionary of the response data. | async def _request(self, *, http_verb, api_url, req_args):
"""Submit the HTTP request with the running session or a new session.
Returns:
A dictionary of the response data.
"""
if self.session and not self.session.closed:
async with self.session.request(http_verb,... |
Construct the user-agent header with the package info,
Python version and OS version.
Returns:
The user agent string.
e.g. 'Python/3.6.7 slack/2.0.0 Darwin/17.7.0' | def _get_user_agent():
"""Construct the user-agent header with the package info,
Python version and OS version.
Returns:
The user agent string.
e.g. 'Python/3.6.7 slack/2.0.0 Darwin/17.7.0'
"""
# __name__ returns all classes, we only want the client
... |
Check if the response from Slack was successful.
Returns:
(SlackResponse)
This method returns it's own object. e.g. 'self'
Raises:
SlackApiError: The request to the Slack API failed. | def validate(self):
"""Check if the response from Slack was successful.
Returns:
(SlackResponse)
This method returns it's own object. e.g. 'self'
Raises:
SlackApiError: The request to the Slack API failed.
"""
if self.status_code == 200 a... |
Create and send an onboarding welcome message to new users. Save the
time stamp of this message so we can update this message in the future. | def onboarding_message(**payload):
"""Create and send an onboarding welcome message to new users. Save the
time stamp of this message so we can update this message in the future.
"""
# Get WebClient so you can communicate back to Slack.
web_client = payload["web_client"]
# Get the id of the Sla... |
Log the time it takes to run a function. It's sort of like timeit, but
prettier. | def log_time(func: Callable[..., Any]) -> Callable[..., Any]:
"""Log the time it takes to run a function. It's sort of like timeit, but
prettier.
"""
def wrapper(*args, **kwargs):
start_time = time.time()
log.info("%s starting...", func.__name__.title())
ret = func(*args, **kwar... |
We double-fork here to detach the daemon process from the parent.
If we were to just fork the child as a daemon, we'd have to worry about the
parent process exiting zombifying the daemon. | def daemonize(self) -> None:
"""We double-fork here to detach the daemon process from the parent.
If we were to just fork the child as a daemon, we'd have to worry about the
parent process exiting zombifying the daemon."""
if os.fork() == 0:
pid = os.fork()
... |
Populates this graph from the given one based on affected_files | def populate_from_trace_graph(self, graph: TraceGraph) -> None:
"""Populates this graph from the given one based on affected_files
"""
# Track which trace frames have been visited as we populate the full
# traces of the graph.
self._visited_trace_frame_ids: Set[int] = set()
... |
Populates the trimmed graph with issues whose locations are in
affected_files based on data in the input graph. Since these issues
exist in the affected files, all traces are copied as well. | def _populate_affected_issues(self, graph: TraceGraph) -> None:
"""Populates the trimmed graph with issues whose locations are in
affected_files based on data in the input graph. Since these issues
exist in the affected files, all traces are copied as well.
"""
affected_instance_... |
TraceFrames found in affected_files should be reachable via some
issue instance. Follow traces of graph to find them and
populate this TrimmedGraph with it. | def _populate_issues_from_affected_trace_frames(self, graph: TraceGraph) -> None:
"""TraceFrames found in affected_files should be reachable via some
issue instance. Follow traces of graph to find them and
populate this TrimmedGraph with it.
"""
initial_trace_frames = [
... |
Helper for populating reachable issue instances from the initial
pre/postconditions. Also populates conditions/traces reachable from
these instances. Traces are populated only in the direction this is
called from: i.e. if initial_conditions are preconditions, only the
backward trace is p... | def _populate_issues_from_affected_conditions(
self,
initial_conditions,
graph: TraceGraph,
get_issue_instances_from_condition_id,
get_condition_parent,
get_instance_leaves,
get_condition_leaves,
add_instance_condition_assoc,
add_condition,
... |
Copies an issue over from the given trace graph, including all its
traces and assocs. | def _populate_issue_and_traces(self, graph: TraceGraph, instance_id: int) -> None:
""" Copies an issue over from the given trace graph, including all its
traces and assocs.
"""
self._populate_issue(graph, instance_id)
self._populate_issue_trace(graph, instance_id) |
Adds an issue to the trace graph along with relevant information
pertaining to the issue (e.g. instance, fix_info, sources/sinks)
The issue is identified by its corresponding instance's ID in the input
trace graph. | def _populate_issue(self, graph: TraceGraph, instance_id: int) -> None:
"""Adds an issue to the trace graph along with relevant information
pertaining to the issue (e.g. instance, fix_info, sources/sinks)
The issue is identified by its corresponding instance's ID in the input
trace graph... |
Populates (from the given trace graph) the forward and backward
traces reachable from the given traces (including input trace frames).
Make sure to respect trace kind in successors | def _populate_trace(self, graph: TraceGraph, trace_frame_ids: List[int]) -> None:
""" Populates (from the given trace graph) the forward and backward
traces reachable from the given traces (including input trace frames).
Make sure to respect trace kind in successors
"""
while len... |
Copies the trace frame from 'graph' to this (self) graph.
Also copies all the trace_frame-leaf assocs since we don't
know which ones are needed until we know the issue that reaches it | def _add_trace_frame(self, graph: TraceGraph, trace_frame: TraceFrame) -> None:
""" Copies the trace frame from 'graph' to this (self) graph.
Also copies all the trace_frame-leaf assocs since we don't
know which ones are needed until we know the issue that reaches it
"""
trace_fr... |
Given a shared analysis directory, produce a mapping from actual source files
to files contained within this directory. Only includes files which have
one of the provided extensions.
Watchman watches actual source files, so when a change is detected to a
file, this mapping can be used t... | def _compute_symbolic_link_mapping(
directory: str, extensions: Iterable[str]
) -> Dict[str, str]:
"""
Given a shared analysis directory, produce a mapping from actual source files
to files contained within this directory. Only includes files which have
one of the provided extensions.
... |
Raises an OSError if the lock can't be acquired | def acquire_lock(path: str, blocking: bool) -> Generator[Optional[int], None, None]:
"""Raises an OSError if the lock can't be acquired"""
try:
with open(path, "w+") as lockfile:
if not blocking:
lock_command = fcntl.LOCK_EX | fcntl.LOCK_NB
else:
l... |
Process a list of paths which were added/removed/updated, making any
necessary changes to the directory:
- For an AnalysisDirectory, nothing needs to be changed, since
the mapping from source file to analysis file is 1:1.
- For a SharedAnalysisDirectory, the... | def process_updated_files(self, paths: List[str]) -> List[str]:
"""
Process a list of paths which were added/removed/updated, making any
necessary changes to the directory:
- For an AnalysisDirectory, nothing needs to be changed, since
the mapping from s... |
Return the paths in the analysis directory (symbolic links)
corresponding to the given paths.
Result also includes any files which are within a tracked directory.
This method will remove/add symbolic links for deleted/new files. | def process_updated_files(self, paths: List[str]) -> List[str]:
"""
Return the paths in the analysis directory (symbolic links)
corresponding to the given paths.
Result also includes any files which are within a tracked directory.
This method will remove/add symb... |
Return the list of files that match any of the patterns within root.
If exclude is provided, files that match an exclude pattern are omitted.
Note: The `find` command does not understand globs properly.
e.g. 'a/*.py' will match 'a/b/c.py'
For this reason, avoid calli... | def list(
self, root: str, patterns: List[str], exclude: Optional[List[str]] = None
) -> List[str]:
"""
Return the list of files that match any of the patterns within root.
If exclude is provided, files that match an exclude pattern are omitted.
Note: The `find` ... |
setting boilerplate when creating a Run object | def _create_empty_run(
self, status=RunStatus.FINISHED, status_description=None
) -> Run:
"""setting boilerplate when creating a Run object"""
run = Run(
job_id=self.summary["job_id"],
issue_instances=[],
date=datetime.datetime.now(),
status=st... |
Iterate over all issues and count the number of times each callable
is seen. | def _compute_callables_count(self, iters: Dict[str, Any]):
"""Iterate over all issues and count the number of times each callable
is seen."""
count = dict.fromkeys([issue["callable"] for issue in iters["issues"]], 0)
for issue in iters["issues"]:
count[issue["callable"]] += 1... |
Insert the issue instance into a run. This includes creating (for
new issues) or finding (for existing issues) Issue objects to associate
with the instances.
Also create sink entries and associate related issues | def _generate_issue(self, run, entry, callablesCount):
"""Insert the issue instance into a run. This includes creating (for
new issues) or finding (for existing issues) Issue objects to associate
with the instances.
Also create sink entries and associate related issues"""
trace_... |
Remove all lines in execution history added by iPython calls. | def get_history_without_ipython_calls(self):
"""
Remove all lines in execution history added by iPython calls.
"""
line_count = 0
filtered_history = []
for line in self.history:
if "get_ipython()." not in line:
filtered_history.append(line)
... |
Prepares the bulk saver to load the trace graph info into the
database. | def _prep_save(self):
""" Prepares the bulk saver to load the trace graph info into the
database.
"""
log.info("Preparing bulk save.")
self.graph.update_bulk_saver(self.bulk_saver)
log.info(
"Dropped %d unused preconditions, %d are missing",
sum(l... |
Saves bulk saver's info into the databases in bulk. | def _save(self) -> RunSummary:
""" Saves bulk saver's info into the databases in bulk.
"""
assert self.summary["run"] is not None, "Must have called process before"
trace_frames = self.bulk_saver.get_items_to_add(TraceFrame)
log.info(
"Saving %d issues, %d trace fram... |
Returns a list of pairs (leaf_name, distance) | def _parse_leaves(self, leaves) -> List[Tuple[str, int]]:
"""Returns a list of pairs (leaf_name, distance)"""
return [(self._leaf_name(leaf), 0) for leaf in leaves] |
Generates all file handles represented by the analysis.
Callee owns file handle and closes it when the next is yielded or the
generator ends. | def file_handles(self) -> Iterable[IO[str]]:
"""Generates all file handles represented by the analysis.
Callee owns file handle and closes it when the next is yielded or the
generator ends.
"""
if self.file_handle:
yield self.file_handle
self.file_handle.c... |
Generates all file names that are used to generate file_handles. | def file_names(self) -> Iterable[str]:
"""Generates all file names that are used to generate file_handles.
"""
if self.is_sharded():
yield from ShardedFile(self.filename_spec).get_filenames()
elif self.filename_spec:
yield self.filename_spec |
This is called immediately before the items are written to the
database. pkgen is passed in to allow last-minute resolving of ids. | def prepare(cls, session, pkgen, items):
"""This is called immediately before the items are written to the
database. pkgen is passed in to allow last-minute resolving of ids.
"""
for item in cls.merge(session, items):
if hasattr(item, "id"):
item.id.resolve(id... |
An object can have multiple attributes as its key. This merges the
items to be added with existing items in the database based on their
key(s).
session: Session object for querying the DB.
items: Iterator of items to be added to the DB.
hash_item: Function that takes as in put t... | def _merge_by_keys(cls, session, items, hash_item, *attrs):
"""An object can have multiple attributes as its key. This merges the
items to be added with existing items in the database based on their
key(s).
session: Session object for querying the DB.
items: Iterator of items to... |
SQLAlchemy uses this to convert a string into a SourceLocation object.
We separate the fields by a | | def process_result_value(self, value, dialect):
"""
SQLAlchemy uses this to convert a string into a SourceLocation object.
We separate the fields by a |
"""
if value is None:
return None
p = value.split("|")
if len(p) == 0:
return None
... |
session - Session for DB operations.
saving_classes - class objects that need to be saved e.g. Issue, Run
item_counts - map from class name to the number of items, for preallocating
id ranges | def reserve(
self,
session: Session,
saving_classes: List[Type],
item_counts: Optional[Dict[str, int]] = None,
use_lock: bool = False,
) -> "PrimaryKeyGenerator":
"""
session - Session for DB operations.
saving_classes - class objects that need to be s... |
Here we take input generators and return a dict with issues,
preconditions, and postconditions separated. If there is only a single
generator file, it's simple. If we also pass in a generator from a
previous inputfile then there are a couple extra steps:
1. If an issue was seen in the p... | def analysis_output_to_dict_entries(
self,
inputfile: AnalysisOutput,
previous_inputfile: Optional[AnalysisOutput],
previous_issue_handles: Optional[AnalysisOutput],
linemapfile: Optional[str],
) -> DictEntries:
"""Here we take input generators and return a dict with ... |
Uses the absolute line and ignores the callable/character offsets.
Used only in determining whether new issues are old issues. | def compute_diff_handle(filename, old_line, code):
"""Uses the absolute line and ignores the callable/character offsets.
Used only in determining whether new issues are old issues.
"""
key = "{filename}:{old_line}:{code}".format(
filename=filename, old_line=old_line, code=cod... |
Determine whether we are connected to a capable terminal. | def is_capable_terminal(file=sys.stderr) -> bool:
"""
Determine whether we are connected to a capable terminal.
"""
if not os.isatty(file.fileno()):
return False
terminal = os.getenv("TERM", "dumb")
# Hardcoded list of non-capable terminals.
return terminal not in ["dumb", "emacs"] |
Walk directories upwards from base, until the root directory is
reached. At each step, check if the target directory exist, and return
it if found. Return None if the search is unsuccessful. | def _find_directory_upwards(base: str, target: str) -> Optional[str]:
"""
Walk directories upwards from base, until the root directory is
reached. At each step, check if the target directory exist, and return
it if found. Return None if the search is unsuccessful.
"""
while True:
step = ... |
Compute the set of targets to build for the given targets using a
breadth-first traversal. | def compute_targets_to_build(self, targets: Iterable[str]) -> Iterable[BuildTarget]:
"""
Compute the set of targets to build for the given targets using a
breadth-first traversal.
"""
normalized_targets = set()
for target in targets:
normalized_targets... |
Compute the set of targets which depend on each target. | def compute_reverse_dependencies(
self, targets: Iterable[BuildTarget]
) -> Mapping[str, Iterable[BuildTarget]]:
"""
Compute the set of targets which depend on each target.
"""
result = defaultdict(list)
for target in targets:
for dependency in target.... |
Consume a key from the configuration. When a key is consumed, it
is removed from the configuration.
If not found, the default is returned. If the current value is not
None, it will be returned instead, but the key will still be
considered consumed. | def consume(self, key, default=None, current=None, print_on_success=False):
"""
Consume a key from the configuration. When a key is consumed, it
is removed from the configuration.
If not found, the default is returned. If the current value is not
None, it will be returned instea... |
Sets the location of the output from the static analysis tool.
Parameters:
location: str Filesystem location for the results. | def analysis_output(self, location: Optional[str] = None) -> None:
"""Sets the location of the output from the static analysis tool.
Parameters:
location: str Filesystem location for the results.
"""
try:
if not location:
location = self.prompt(... |
Select an issue.
Parameters:
issue_instance_id: int id of the issue instance to select
Note: We are selecting issue instances, even though the command is called
issue. | def issue(self, issue_instance_id):
"""Select an issue.
Parameters:
issue_instance_id: int id of the issue instance to select
Note: We are selecting issue instances, even though the command is called
issue.
"""
with self.db.make_session() as session:
... |
More details about the selected issue or trace frame. | def show(self):
""" More details about the selected issue or trace frame.
"""
self._verify_entrypoint_selected()
if self.current_issue_instance_id != -1:
self._show_current_issue_instance()
return
self._show_current_trace_frame() |
Lists issues for the selected run.
Parameters (all optional):
use_pager: bool use a unix style pager for output
codes: int or list[int] issue codes to filter on
callables: str or list[str] callables to filter on (supports wildcards)
filen... | def issues(
self,
use_pager: bool = None,
*,
codes: Optional[Union[int, List[int]]] = None,
callables: Optional[Union[str, List[str]]] = None,
filenames: Optional[Union[str, List[str]]] = None,
):
"""Lists issues for the selected run.
Parameters (all ... |
Display trace frames independent of the current issue.
Parameters (all optional):
callers: str or list[str] filter traces by this caller name
callees: str or list[str] filter traces by this callee name
kind: precondition|postcondition the type of tra... | def frames(
self,
*,
callers: Optional[Union[str, List[str]]] = None,
callees: Optional[Union[str, List[str]]] = None,
kind: Optional[TraceKind] = None,
limit: Optional[int] = 10,
):
"""Display trace frames independent of the current issue.
Parameters... |
Move cursor to the next trace frame. | def next_cursor_location(self):
"""Move cursor to the next trace frame.
"""
self._verify_entrypoint_selected()
self.current_trace_frame_index = min(
self.current_trace_frame_index + 1, len(self.trace_tuples) - 1
)
self.trace() |
Move cursor to the previous trace frame. | def prev_cursor_location(self):
"""Move cursor to the previous trace frame.
"""
self._verify_entrypoint_selected()
self.current_trace_frame_index = max(self.current_trace_frame_index - 1, 0)
self.trace() |
Jump to a specific trace frame in a trace.
Parameters:
selected_number: int the trace frame number from trace output | def jump(self, selected_number: int) -> None:
"""Jump to a specific trace frame in a trace.
Parameters:
selected_number: int the trace frame number from trace output
"""
self._verify_entrypoint_selected()
if selected_number < 1 or selected_number > len(self.trace_... |
Show and select branches for a branched trace.
- [*] signifies the current branch that is selected
- will prompt for branch selection if called with no argument
- will automatically select a branch if called with an argument
Parameters (optional):
selected_number: int bra... | def branch(self, selected_number: Optional[int] = None) -> None:
"""Show and select branches for a branched trace.
- [*] signifies the current branch that is selected
- will prompt for branch selection if called with no argument
- will automatically select a branch if called with an argu... |
Show source code around the current trace frame location.
Parameters:
context: int number of lines to show above and below trace location
(default: 5) | def list_source_code(self, context: int = 5) -> None:
"""Show source code around the current trace frame location.
Parameters:
context: int number of lines to show above and below trace location
(default: 5)
"""
self._verify_entrypoint_selected... |
Show additional info about the current trace frame.
Parameters (all optional):
limit: int number of related post/pre conditions to show
(pass limit=None to show all) | def details(
self, *, limit: Optional[int] = 5, kind: Optional[TraceKind] = None
) -> None:
"""Show additional info about the current trace frame.
Parameters (all optional):
limit: int number of related post/pre conditions to show
(pass limit=None to... |
Buckets together trace frames that have the same caller:caller_port. | def _group_trace_frames(
self, trace_frames: Iterable[TraceFrameQueryResult], limit: int
) -> Dict[Tuple[str, str], List[TraceFrameQueryResult]]:
"""Buckets together trace frames that have the same caller:caller_port.
"""
# pyre-fixme[9]: caller_buckets has type `DefaultDict[Tuple[st... |
Finds all trace frames that the given trace_frame flows to.
When backwards=True, the result will include the parameter trace_frame,
since we are filtering on the parameter's callee. | def _next_trace_frames(
self,
session: Session,
trace_frame: TraceFrameQueryResult,
visited_ids: Set[int],
backwards: bool = False,
) -> List[TraceFrameQueryResult]:
"""Finds all trace frames that the given trace_frame flows to.
When backwards=True, the resul... |
Show the name of the current callable in the trace | def callable(self) -> Optional[str]:
"""Show the name of the current callable in the trace"""
if self.current_trace_frame_index != -1:
return self._get_callable_from_trace_tuple(
self.trace_tuples[self.current_trace_frame_index]
)[0]
return None |
Returns either (caller, caller_port) or (callee, callee_port). | def _get_callable_from_trace_tuple(
self, trace_tuple: TraceTuple
) -> Tuple[str, str]:
"""Returns either (caller, caller_port) or (callee, callee_port).
"""
trace_frame = trace_tuple.trace_frame
if trace_tuple.placeholder:
return trace_frame.caller, trace_frame.c... |
Throw an exception if an option wasn't required. This is useful when its
optional in some contexts but required for a subcommand | def require_option(current_ctx: click.Context, param_name: str) -> None:
"""Throw an exception if an option wasn't required. This is useful when its
optional in some contexts but required for a subcommand"""
ctx = current_ctx
param_definition = None
while ctx is not None:
# ctx.command.para... |
Try to guess a reasonable database name by looking at the repository path | def default_database(ctx: click.Context, _param: Parameter, value: Optional[str]):
"""Try to guess a reasonable database name by looking at the repository path"""
if value:
return value
if ctx.params["repository"]:
return os.path.join(ctx.params["repository"], DB.DEFAULT_DB_FILE)
raise... |
Output DB models in a lint-friendly format | def lint(click_ctx: click.Context, run_id: int, filenames: List[str]) -> None:
"""Output DB models in a lint-friendly format"""
ctx = click_ctx.obj
require_option(click_ctx, "repository")
paths = [Path(p).resolve() for p in filenames]
root = Path(ctx.repository).resolve()
relative = [str(Path(f... |
Returns a mapping from absolute source path to absolute output path as specified
by the sources object. Files are not guaranteed to exist. | def resolve_source_mapping(
source_directory: str, output_directory: str, sources: Sources
) -> Mapping[str, str]:
"""
Returns a mapping from absolute source path to absolute output path as specified
by the sources object. Files are not guaranteed to exist.
"""
result = {
os.path... |
Query buck to obtain a mapping from each absolute path to the relative
location in the analysis directory. | def resolve_relative_paths(paths: List[str]) -> Dict[str, str]:
"""
Query buck to obtain a mapping from each absolute path to the relative
location in the analysis directory.
"""
buck_root = find_buck_root(os.getcwd())
if buck_root is None:
LOG.error(
"Buck root could... |
Shell out to buck to build the targets, then yield the paths to the
link trees. | def build(self, targets: Iterable[str]) -> Iterable[str]:
"""
Shell out to buck to build the targets, then yield the paths to the
link trees.
"""
return generate_source_directories(
targets, build=self._build, prompt=self._prompt
) |
Depending on if an argument has a type, the style for default values
changes. E.g.
def fun(x=5)
def fun(x : int = 5) | def _get_parameter_string(self) -> str:
""" Depending on if an argument has a type, the style for default values
changes. E.g.
def fun(x=5)
def fun(x : int = 5)
"""
parameters = []
for parameter in self.parameters:
name = parameter["name"]
... |
Determines if a stub completely types a function | def is_complete(self) -> bool:
""" Determines if a stub completely types a function """
if not self.actual:
return False
for parameter in self.parameters:
if parameter["name"] != "self" and not parameter["type"]:
return False
return True |
We currently ignore nested classes, i.e.:
class X:
class Y:
[ALL OF THIS IS IGNORED] | def to_string(self) -> str:
"""We currently ignore nested classes, i.e.:
class X:
class Y:
[ALL OF THIS IS IGNORED]
"""
classes = defaultdict(list)
typing_imports = set()
contents = ""
# import necessary modules from typing
... |
Download a trained weights, config and preprocessor.
Args:
url (str): target url. | def download(url):
"""Download a trained weights, config and preprocessor.
Args:
url (str): target url.
"""
filepath = get_file(fname='tmp.zip', origin=url, extract=True)
base_dir = os.path.dirname(filepath)
weights_file = os.path.join(base_dir, 'weights.h5')
params_file = os.path.j... |
Loads data and label from a file.
Args:
filename (str): path to the file.
encoding (str): file encoding format.
The file format is tab-separated values.
A blank line is required at the end of a sentence.
For example:
```
EU B-ORG
rejects O
G... | def load_data_and_labels(filename, encoding='utf-8'):
"""Loads data and label from a file.
Args:
filename (str): path to the file.
encoding (str): file encoding format.
The file format is tab-separated values.
A blank line is required at the end of a sentence.
For exam... |
Loads word vectors in numpy array.
Args:
embeddings (dict): a dictionary of numpy array.
vocab (dict): word_index lookup table.
Returns:
numpy array: an array of word embeddings. | def filter_embeddings(embeddings, vocab, dim):
"""Loads word vectors in numpy array.
Args:
embeddings (dict): a dictionary of numpy array.
vocab (dict): word_index lookup table.
Returns:
numpy array: an array of word embeddings.
"""
if not isinstance(embeddings, dict):
... |
Loads GloVe vectors in numpy array.
Args:
file (str): a path to a glove file.
Return:
dict: a dict of numpy arrays. | def load_glove(file):
"""Loads GloVe vectors in numpy array.
Args:
file (str): a path to a glove file.
Return:
dict: a dict of numpy arrays.
"""
model = {}
with open(file, encoding="utf8", errors='ignore') as f:
for line in f:
line = line.split(' ')
... |
Add token to vocabulary.
Args:
token (str): token to add. | def add_token(self, token):
"""Add token to vocabulary.
Args:
token (str): token to add.
"""
token = self.process_token(token)
self._token_count.update([token]) |
Update dictionary from a collection of documents. Each document is a list
of tokens.
Args:
docs (list): documents to add. | def add_documents(self, docs):
"""Update dictionary from a collection of documents. Each document is a list
of tokens.
Args:
docs (list): documents to add.
"""
for sent in docs:
sent = map(self.process_token, sent)
self._token_count.update(sen... |
Get the list of token_id given doc.
Args:
doc (list): document.
Returns:
list: int id of doc. | def doc2id(self, doc):
"""Get the list of token_id given doc.
Args:
doc (list): document.
Returns:
list: int id of doc.
"""
doc = map(self.process_token, doc)
return [self.token_to_id(token) for token in doc] |
Build vocabulary. | def build(self):
"""
Build vocabulary.
"""
token_freq = self._token_count.most_common(self._max_size)
idx = len(self.vocab)
for token, _ in token_freq:
self._token2id[token] = idx
self._id2token.append(token)
idx += 1
if self._u... |
Get the token_id of given token.
Args:
token (str): token from vocabulary.
Returns:
int: int id of token. | def token_to_id(self, token):
"""Get the token_id of given token.
Args:
token (str): token from vocabulary.
Returns:
int: int id of token.
"""
token = self.process_token(token)
return self._token2id.get(token, len(self._token2id) - 1) |
Probability estimates.
The returned estimates for all classes are ordered by the
label of classes.
Args:
text : string, the input text.
Returns:
y : array-like, shape = [num_words, num_classes]
Returns the probability of the word for each class in t... | def predict_proba(self, text):
"""Probability estimates.
The returned estimates for all classes are ordered by the
label of classes.
Args:
text : string, the input text.
Returns:
y : array-like, shape = [num_words, num_classes]
Returns the p... |
Analyze text and return pretty format.
Args:
text: string, the input text.
Returns:
res: dict.
Examples:
>>> text = 'President Obama is speaking at the White House.'
>>> model.analyze(text)
{
"words": [
... | def analyze(self, text):
"""Analyze text and return pretty format.
Args:
text: string, the input text.
Returns:
res: dict.
Examples:
>>> text = 'President Obama is speaking at the White House.'
>>> model.analyze(text)
{
... |
Predict using the model.
Args:
text: string, the input text.
Returns:
tags: list, shape = (num_words,)
Returns predicted values. | def predict(self, text):
"""Predict using the model.
Args:
text: string, the input text.
Returns:
tags: list, shape = (num_words,)
Returns predicted values.
"""
pred = self.predict_proba(text)
tags = self._get_tags(pred)
retu... |
Pads nested sequences to the same length.
This function transforms a list of list sequences
into a 3D Numpy array of shape `(num_samples, max_sent_len, max_word_len)`.
Args:
sequences: List of lists of lists.
dtype: Type of the output sequences.
# Returns
x: Numpy array. | def pad_nested_sequences(sequences, dtype='int32'):
"""Pads nested sequences to the same length.
This function transforms a list of list sequences
into a 3D Numpy array of shape `(num_samples, max_sent_len, max_word_len)`.
Args:
sequences: List of lists of lists.
dtype: Type of the out... |
Learn vocabulary from training set.
Args:
X : iterable. An iterable which yields either str, unicode or file objects.
Returns:
self : IndexTransformer. | def fit(self, X, y):
"""Learn vocabulary from training set.
Args:
X : iterable. An iterable which yields either str, unicode or file objects.
Returns:
self : IndexTransformer.
"""
self._word_vocab.add_documents(X)
self._label_vocab.add_documents(... |
Transform documents to document ids.
Uses the vocabulary learned by fit.
Args:
X : iterable
an iterable which yields either str, unicode or file objects.
y : iterabl, label strings.
Returns:
features: document id matrix.
y: label id ... | def transform(self, X, y=None):
"""Transform documents to document ids.
Uses the vocabulary learned by fit.
Args:
X : iterable
an iterable which yields either str, unicode or file objects.
y : iterabl, label strings.
Returns:
features: d... |
Learn vocabulary and return document id matrix.
This is equivalent to fit followed by transform.
Args:
X : iterable
an iterable which yields either str, unicode or file objects.
Returns:
list : document id matrix.
list: label id matrix. | def fit_transform(self, X, y=None, **params):
"""Learn vocabulary and return document id matrix.
This is equivalent to fit followed by transform.
Args:
X : iterable
an iterable which yields either str, unicode or file objects.
Returns:
list : docume... |
Return label strings.
Args:
y: label id matrix.
lengths: sentences length.
Returns:
list: list of list of strings. | def inverse_transform(self, y, lengths=None):
"""Return label strings.
Args:
y: label id matrix.
lengths: sentences length.
Returns:
list: list of list of strings.
"""
y = np.argmax(y, -1)
inverse_y = [self._label_vocab.id2doc(ids) fo... |
Transform documents to document ids.
Uses the vocabulary learned by fit.
Args:
X : iterable
an iterable which yields either str, unicode or file objects.
y : iterabl, label strings.
Returns:
features: document id matrix.
y: label id ... | def transform(self, X, y=None):
"""Transform documents to document ids.
Uses the vocabulary learned by fit.
Args:
X : iterable
an iterable which yields either str, unicode or file objects.
y : iterabl, label strings.
Returns:
features: d... |
Trains the model for a fixed number of epochs (iterations on a dataset).
Args:
x_train: list of training data.
y_train: list of training target (label) data.
x_valid: list of validation data.
y_valid: list of validation target (label) data.
batch_size... | def train(self, x_train, y_train, x_valid=None, y_valid=None,
epochs=1, batch_size=32, verbose=1, callbacks=None, shuffle=True):
"""Trains the model for a fixed number of epochs (iterations on a dataset).
Args:
x_train: list of training data.
y_train: list of train... |
Fit the model for a fixed number of epochs.
Args:
x_train: list of training data.
y_train: list of training target (label) data.
x_valid: list of validation data.
y_valid: list of validation target (label) data.
batch_size: Integer.
Nu... | def fit(self, x_train, y_train, x_valid=None, y_valid=None,
epochs=1, batch_size=32, verbose=1, callbacks=None, shuffle=True):
"""Fit the model for a fixed number of epochs.
Args:
x_train: list of training data.
y_train: list of training target (label) data.
... |
Returns the prediction of the model on the given test data.
Args:
x_test : array-like, shape = (n_samples, sent_length)
Test samples.
Returns:
y_pred : array-like, shape = (n_smaples, sent_length)
Prediction labels for x. | def predict(self, x_test):
"""Returns the prediction of the model on the given test data.
Args:
x_test : array-like, shape = (n_samples, sent_length)
Test samples.
Returns:
y_pred : array-like, shape = (n_smaples, sent_length)
Prediction labels f... |
Analyze text and return pretty format.
Args:
text: string, the input text.
tokenizer: Tokenize input sentence. Default tokenizer is `str.split`.
Returns:
res: dict. | def analyze(self, text, tokenizer=str.split):
"""Analyze text and return pretty format.
Args:
text: string, the input text.
tokenizer: Tokenize input sentence. Default tokenizer is `str.split`.
Returns:
res: dict.
"""
if not self.tagger:
... |
Compute logarithm of the normalization constant Z, where
Z = sum exp(-E) -> logZ = log sum exp(-E) =: -nlogZ | def get_log_normalization_constant(self, input_energy, mask, **kwargs):
"""Compute logarithm of the normalization constant Z, where
Z = sum exp(-E) -> logZ = log sum exp(-E) =: -nlogZ
"""
# should have logZ[:, i] == logZ[:, j] for any i, j
logZ = self.recursion(input_energy, mask... |
Energy = a1' y1 + u1' y1 + y1' U y2 + u2' y2 + y2' U y3 + u3' y3 + an' y3 | def get_energy(self, y_true, input_energy, mask):
"""Energy = a1' y1 + u1' y1 + y1' U y2 + u2' y2 + y2' U y3 + u3' y3 + an' y3
"""
input_energy = K.sum(input_energy * y_true, 2) # (B, T)
chain_energy = K.sum(K.dot(y_true[:, :-1, :], self.chain_kernel) * y_true[:, 1:, :], 2) # (B, T-1)
... |
Compute the loss, i.e., negative log likelihood (normalize by number of time steps)
likelihood = 1/Z * exp(-E) -> neg_log_like = - log(1/Z * exp(-E)) = logZ + E | def get_negative_log_likelihood(self, y_true, X, mask):
"""Compute the loss, i.e., negative log likelihood (normalize by number of time steps)
likelihood = 1/Z * exp(-E) -> neg_log_like = - log(1/Z * exp(-E)) = logZ + E
"""
input_energy = self.activation(K.dot(X, self.kernel) + self.... |
Forward (alpha) or backward (beta) recursion
If `return_logZ = True`, compute the logZ, the normalization constant:
\[ Z = \sum_{y1, y2, y3} exp(-E) # energy
= \sum_{y1, y2, y3} exp(-(u1' y1 + y1' W y2 + u2' y2 + y2' W y3 + u3' y3))
= sum_{y2, y3} (exp(-(u2' y2 + y2' W y3 + u3' y3)) ... | def recursion(self, input_energy, mask=None, go_backwards=False, return_sequences=True, return_logZ=True, input_length=None):
"""Forward (alpha) or backward (beta) recursion
If `return_logZ = True`, compute the logZ, the normalization constant:
\[ Z = \sum_{y1, y2, y3} exp(-E) # energy
... |
Extracts a minimal signature from a given SQL query
:param sql: the SQL statement
:return: a string representing the signature | def extract_signature(sql):
"""
Extracts a minimal signature from a given SQL query
:param sql: the SQL statement
:return: a string representing the signature
"""
sql = force_text(sql)
sql = sql.strip()
first_space = sql.find(" ")
if first_space < 0:
return sql
second_sp... |
implementation of Queue.join which takes a 'timeout' argument
returns True on success, False on timeout | def _timed_queue_join(self, timeout):
"""
implementation of Queue.join which takes a 'timeout' argument
returns True on success, False on timeout
"""
deadline = time.time() + timeout
with self._queue.all_tasks_done:
while self._queue.unfinished_tasks:
... |
Starts the task thread. | def start(self):
"""
Starts the task thread.
"""
self._lock.acquire()
try:
if not self._thread:
self._thread = Thread(target=self._target)
self._thread.setDaemon(True)
self._thread.name = "elasticapm sender thread"
... |
Stops the task thread. Synchronous! | def stop(self, timeout=None):
"""
Stops the task thread. Synchronous!
"""
self._lock.acquire()
try:
if self._thread:
self._queue.put_nowait(self._terminator)
self._thread.join(timeout=timeout)
self._thread = None
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.