partition
stringclasses
3 values
func_name
stringlengths
1
134
docstring
stringlengths
1
46.9k
path
stringlengths
4
223
original_string
stringlengths
75
104k
code
stringlengths
75
104k
docstring_tokens
listlengths
1
1.97k
repo
stringlengths
7
55
language
stringclasses
1 value
url
stringlengths
87
315
code_tokens
listlengths
19
28.4k
sha
stringlengths
40
40
train
TrimmedTraceGraph._populate_issues_from_affected_conditions
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...
sapp/sapp/trimmed_trace_graph.py
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, ...
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, ...
[ "Helper", "for", "populating", "reachable", "issue", "instances", "from", "the", "initial", "pre", "/", "postconditions", ".", "Also", "populates", "conditions", "/", "traces", "reachable", "from", "these", "instances", ".", "Traces", "are", "populated", "only", ...
facebook/pyre-check
python
https://github.com/facebook/pyre-check/blob/4a9604d943d28ef20238505a51acfb1f666328d7/sapp/sapp/trimmed_trace_graph.py#L169-L262
[ "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_co...
4a9604d943d28ef20238505a51acfb1f666328d7
train
TrimmedTraceGraph._populate_issue_and_traces
Copies an issue over from the given trace graph, including all its traces and assocs.
sapp/sapp/trimmed_trace_graph.py
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)
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)
[ "Copies", "an", "issue", "over", "from", "the", "given", "trace", "graph", "including", "all", "its", "traces", "and", "assocs", "." ]
facebook/pyre-check
python
https://github.com/facebook/pyre-check/blob/4a9604d943d28ef20238505a51acfb1f666328d7/sapp/sapp/trimmed_trace_graph.py#L264-L269
[ "def", "_populate_issue_and_traces", "(", "self", ",", "graph", ":", "TraceGraph", ",", "instance_id", ":", "int", ")", "->", "None", ":", "self", ".", "_populate_issue", "(", "graph", ",", "instance_id", ")", "self", ".", "_populate_issue_trace", "(", "graph"...
4a9604d943d28ef20238505a51acfb1f666328d7
train
TrimmedTraceGraph._populate_issue
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.
sapp/sapp/trimmed_trace_graph.py
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...
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...
[ "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", ...
facebook/pyre-check
python
https://github.com/facebook/pyre-check/blob/4a9604d943d28ef20238505a51acfb1f666328d7/sapp/sapp/trimmed_trace_graph.py#L284-L307
[ "def", "_populate_issue", "(", "self", ",", "graph", ":", "TraceGraph", ",", "instance_id", ":", "int", ")", "->", "None", ":", "instance", "=", "graph", ".", "_issue_instances", "[", "instance_id", "]", "issue", "=", "graph", ".", "_issues", "[", "instanc...
4a9604d943d28ef20238505a51acfb1f666328d7
train
TrimmedTraceGraph._populate_trace
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
sapp/sapp/trimmed_trace_graph.py
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...
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...
[ "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", ...
facebook/pyre-check
python
https://github.com/facebook/pyre-check/blob/4a9604d943d28ef20238505a51acfb1f666328d7/sapp/sapp/trimmed_trace_graph.py#L309-L331
[ "def", "_populate_trace", "(", "self", ",", "graph", ":", "TraceGraph", ",", "trace_frame_ids", ":", "List", "[", "int", "]", ")", "->", "None", ":", "while", "len", "(", "trace_frame_ids", ")", ">", "0", ":", "trace_frame_id", "=", "trace_frame_ids", ".",...
4a9604d943d28ef20238505a51acfb1f666328d7
train
TrimmedTraceGraph._add_trace_frame
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
sapp/sapp/trimmed_trace_graph.py
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...
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...
[ "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", ...
facebook/pyre-check
python
https://github.com/facebook/pyre-check/blob/4a9604d943d28ef20238505a51acfb1f666328d7/sapp/sapp/trimmed_trace_graph.py#L333-L347
[ "def", "_add_trace_frame", "(", "self", ",", "graph", ":", "TraceGraph", ",", "trace_frame", ":", "TraceFrame", ")", "->", "None", ":", "trace_frame_id", "=", "trace_frame", ".", "id", ".", "local_id", "self", ".", "add_trace_frame", "(", "trace_frame", ")", ...
4a9604d943d28ef20238505a51acfb1f666328d7
train
_compute_symbolic_link_mapping
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...
client/filesystem.py
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. ...
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. ...
[ "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", "exte...
facebook/pyre-check
python
https://github.com/facebook/pyre-check/blob/4a9604d943d28ef20238505a51acfb1f666328d7/client/filesystem.py#L399-L422
[ "def", "_compute_symbolic_link_mapping", "(", "directory", ":", "str", ",", "extensions", ":", "Iterable", "[", "str", "]", ")", "->", "Dict", "[", "str", ",", "str", "]", ":", "symbolic_links", "=", "{", "}", "try", ":", "for", "symbolic_link", "in", "f...
4a9604d943d28ef20238505a51acfb1f666328d7
train
acquire_lock
Raises an OSError if the lock can't be acquired
client/filesystem.py
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...
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...
[ "Raises", "an", "OSError", "if", "the", "lock", "can", "t", "be", "acquired" ]
facebook/pyre-check
python
https://github.com/facebook/pyre-check/blob/4a9604d943d28ef20238505a51acfb1f666328d7/client/filesystem.py#L446-L460
[ "def", "acquire_lock", "(", "path", ":", "str", ",", "blocking", ":", "bool", ")", "->", "Generator", "[", "Optional", "[", "int", "]", ",", "None", ",", "None", "]", ":", "try", ":", "with", "open", "(", "path", ",", "\"w+\"", ")", "as", "lockfile...
4a9604d943d28ef20238505a51acfb1f666328d7
train
AnalysisDirectory.process_updated_files
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...
client/filesystem.py
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...
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...
[ "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"...
facebook/pyre-check
python
https://github.com/facebook/pyre-check/blob/4a9604d943d28ef20238505a51acfb1f666328d7/client/filesystem.py#L103-L116
[ "def", "process_updated_files", "(", "self", ",", "paths", ":", "List", "[", "str", "]", ")", "->", "List", "[", "str", "]", ":", "return", "[", "path", "for", "path", "in", "paths", "if", "self", ".", "_is_tracked", "(", "path", ")", "]" ]
4a9604d943d28ef20238505a51acfb1f666328d7
train
SharedAnalysisDirectory.process_updated_files
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.
client/filesystem.py
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...
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", "paths", "in", "the", "analysis", "directory", "(", "symbolic", "links", ")", "corresponding", "to", "the", "given", "paths", ".", "Result", "also", "includes", "any", "files", "which", "are", "within", "a", "tracked", "directory", "." ]
facebook/pyre-check
python
https://github.com/facebook/pyre-check/blob/4a9604d943d28ef20238505a51acfb1f666328d7/client/filesystem.py#L221-L281
[ "def", "process_updated_files", "(", "self", ",", "paths", ":", "List", "[", "str", "]", ")", "->", "List", "[", "str", "]", ":", "tracked_files", "=", "[", "]", "deleted_paths", "=", "[", "path", "for", "path", "in", "paths", "if", "not", "os", ".",...
4a9604d943d28ef20238505a51acfb1f666328d7
train
Filesystem.list
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...
client/filesystem.py
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` ...
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` ...
[ "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", "." ]
facebook/pyre-check
python
https://github.com/facebook/pyre-check/blob/4a9604d943d28ef20238505a51acfb1f666328d7/client/filesystem.py#L464-L485
[ "def", "list", "(", "self", ",", "root", ":", "str", ",", "patterns", ":", "List", "[", "str", "]", ",", "exclude", ":", "Optional", "[", "List", "[", "str", "]", "]", "=", "None", ")", "->", "List", "[", "str", "]", ":", "command", "=", "[", ...
4a9604d943d28ef20238505a51acfb1f666328d7
train
ModelGenerator._compute_callables_count
Iterate over all issues and count the number of times each callable is seen.
sapp/sapp/model_generator.py
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...
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...
[ "Iterate", "over", "all", "issues", "and", "count", "the", "number", "of", "times", "each", "callable", "is", "seen", "." ]
facebook/pyre-check
python
https://github.com/facebook/pyre-check/blob/4a9604d943d28ef20238505a51acfb1f666328d7/sapp/sapp/model_generator.py#L77-L84
[ "def", "_compute_callables_count", "(", "self", ",", "iters", ":", "Dict", "[", "str", ",", "Any", "]", ")", ":", "count", "=", "dict", ".", "fromkeys", "(", "[", "issue", "[", "\"callable\"", "]", "for", "issue", "in", "iters", "[", "\"issues\"", "]",...
4a9604d943d28ef20238505a51acfb1f666328d7
train
ModelGenerator._create_empty_run
setting boilerplate when creating a Run object
sapp/sapp/model_generator.py
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...
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...
[ "setting", "boilerplate", "when", "creating", "a", "Run", "object" ]
facebook/pyre-check
python
https://github.com/facebook/pyre-check/blob/4a9604d943d28ef20238505a51acfb1f666328d7/sapp/sapp/model_generator.py#L86-L101
[ "def", "_create_empty_run", "(", "self", ",", "status", "=", "RunStatus", ".", "FINISHED", ",", "status_description", "=", "None", ")", "->", "Run", ":", "run", "=", "Run", "(", "job_id", "=", "self", ".", "summary", "[", "\"job_id\"", "]", ",", "issue_i...
4a9604d943d28ef20238505a51acfb1f666328d7
train
ModelGenerator._generate_issue
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
sapp/sapp/model_generator.py
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_...
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_...
[ "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", ".",...
facebook/pyre-check
python
https://github.com/facebook/pyre-check/blob/4a9604d943d28ef20238505a51acfb1f666328d7/sapp/sapp/model_generator.py#L113-L205
[ "def", "_generate_issue", "(", "self", ",", "run", ",", "entry", ",", "callablesCount", ")", ":", "trace_frames", "=", "[", "]", "for", "p", "in", "entry", "[", "\"preconditions\"", "]", ":", "tf", "=", "self", ".", "_generate_issue_precondition", "(", "ru...
4a9604d943d28ef20238505a51acfb1f666328d7
train
HistoryContext.get_history_without_ipython_calls
Remove all lines in execution history added by iPython calls.
client/pyre_ipython.py
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) ...
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) ...
[ "Remove", "all", "lines", "in", "execution", "history", "added", "by", "iPython", "calls", "." ]
facebook/pyre-check
python
https://github.com/facebook/pyre-check/blob/4a9604d943d28ef20238505a51acfb1f666328d7/client/pyre_ipython.py#L21-L31
[ "def", "get_history_without_ipython_calls", "(", "self", ")", ":", "line_count", "=", "0", "filtered_history", "=", "[", "]", "for", "line", "in", "self", ".", "history", ":", "if", "\"get_ipython().\"", "not", "in", "line", ":", "filtered_history", ".", "appe...
4a9604d943d28ef20238505a51acfb1f666328d7
train
DatabaseSaver._prep_save
Prepares the bulk saver to load the trace graph info into the database.
sapp/sapp/database_saver.py
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...
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...
[ "Prepares", "the", "bulk", "saver", "to", "load", "the", "trace", "graph", "info", "into", "the", "database", "." ]
facebook/pyre-check
python
https://github.com/facebook/pyre-check/blob/4a9604d943d28ef20238505a51acfb1f666328d7/sapp/sapp/database_saver.py#L51-L69
[ "def", "_prep_save", "(", "self", ")", ":", "log", ".", "info", "(", "\"Preparing bulk save.\"", ")", "self", ".", "graph", ".", "update_bulk_saver", "(", "self", ".", "bulk_saver", ")", "log", ".", "info", "(", "\"Dropped %d unused preconditions, %d are missing\"...
4a9604d943d28ef20238505a51acfb1f666328d7
train
DatabaseSaver._save
Saves bulk saver's info into the databases in bulk.
sapp/sapp/database_saver.py
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...
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...
[ "Saves", "bulk", "saver", "s", "info", "into", "the", "databases", "in", "bulk", "." ]
facebook/pyre-check
python
https://github.com/facebook/pyre-check/blob/4a9604d943d28ef20238505a51acfb1f666328d7/sapp/sapp/database_saver.py#L71-L127
[ "def", "_save", "(", "self", ")", "->", "RunSummary", ":", "assert", "self", ".", "summary", "[", "\"run\"", "]", "is", "not", "None", ",", "\"Must have called process before\"", "trace_frames", "=", "self", ".", "bulk_saver", ".", "get_items_to_add", "(", "Tr...
4a9604d943d28ef20238505a51acfb1f666328d7
train
Parser._parse_leaves
Returns a list of pairs (leaf_name, distance)
sapp/sapp/pysa_taint_parser.py
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]
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]
[ "Returns", "a", "list", "of", "pairs", "(", "leaf_name", "distance", ")" ]
facebook/pyre-check
python
https://github.com/facebook/pyre-check/blob/4a9604d943d28ef20238505a51acfb1f666328d7/sapp/sapp/pysa_taint_parser.py#L202-L204
[ "def", "_parse_leaves", "(", "self", ",", "leaves", ")", "->", "List", "[", "Tuple", "[", "str", ",", "int", "]", "]", ":", "return", "[", "(", "self", ".", "_leaf_name", "(", "leaf", ")", ",", "0", ")", "for", "leaf", "in", "leaves", "]" ]
4a9604d943d28ef20238505a51acfb1f666328d7
train
AnalysisOutput.file_handles
Generates all file handles represented by the analysis. Callee owns file handle and closes it when the next is yielded or the generator ends.
sapp/sapp/analysis_output.py
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...
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", "handles", "represented", "by", "the", "analysis", ".", "Callee", "owns", "file", "handle", "and", "closes", "it", "when", "the", "next", "is", "yielded", "or", "the", "generator", "ends", "." ]
facebook/pyre-check
python
https://github.com/facebook/pyre-check/blob/4a9604d943d28ef20238505a51acfb1f666328d7/sapp/sapp/analysis_output.py#L107-L119
[ "def", "file_handles", "(", "self", ")", "->", "Iterable", "[", "IO", "[", "str", "]", "]", ":", "if", "self", ".", "file_handle", ":", "yield", "self", ".", "file_handle", "self", ".", "file_handle", ".", "close", "(", ")", "self", ".", "file_handle",...
4a9604d943d28ef20238505a51acfb1f666328d7
train
AnalysisOutput.file_names
Generates all file names that are used to generate file_handles.
sapp/sapp/analysis_output.py
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
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
[ "Generates", "all", "file", "names", "that", "are", "used", "to", "generate", "file_handles", "." ]
facebook/pyre-check
python
https://github.com/facebook/pyre-check/blob/4a9604d943d28ef20238505a51acfb1f666328d7/sapp/sapp/analysis_output.py#L121-L127
[ "def", "file_names", "(", "self", ")", "->", "Iterable", "[", "str", "]", ":", "if", "self", ".", "is_sharded", "(", ")", ":", "yield", "from", "ShardedFile", "(", "self", ".", "filename_spec", ")", ".", "get_filenames", "(", ")", "elif", "self", ".", ...
4a9604d943d28ef20238505a51acfb1f666328d7
train
PrepareMixin.prepare
This is called immediately before the items are written to the database. pkgen is passed in to allow last-minute resolving of ids.
sapp/sapp/models.py
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...
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...
[ "This", "is", "called", "immediately", "before", "the", "items", "are", "written", "to", "the", "database", ".", "pkgen", "is", "passed", "in", "to", "allow", "last", "-", "minute", "resolving", "of", "ids", "." ]
facebook/pyre-check
python
https://github.com/facebook/pyre-check/blob/4a9604d943d28ef20238505a51acfb1f666328d7/sapp/sapp/models.py#L87-L94
[ "def", "prepare", "(", "cls", ",", "session", ",", "pkgen", ",", "items", ")", ":", "for", "item", "in", "cls", ".", "merge", "(", "session", ",", "items", ")", ":", "if", "hasattr", "(", "item", ",", "\"id\"", ")", ":", "item", ".", "id", ".", ...
4a9604d943d28ef20238505a51acfb1f666328d7
train
PrepareMixin._merge_by_keys
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...
sapp/sapp/models.py
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...
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...
[ "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", ")", "." ]
facebook/pyre-check
python
https://github.com/facebook/pyre-check/blob/4a9604d943d28ef20238505a51acfb1f666328d7/sapp/sapp/models.py#L108-L171
[ "def", "_merge_by_keys", "(", "cls", ",", "session", ",", "items", ",", "hash_item", ",", "*", "attrs", ")", ":", "# Note: items is an iterator, not an iterable, 'tee' is a must.", "items_iter1", ",", "items_iter2", "=", "tee", "(", "items", ")", "keys", "=", "{",...
4a9604d943d28ef20238505a51acfb1f666328d7
train
SourceLocationType.process_result_value
SQLAlchemy uses this to convert a string into a SourceLocation object. We separate the fields by a |
sapp/sapp/models.py
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 ...
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 ...
[ "SQLAlchemy", "uses", "this", "to", "convert", "a", "string", "into", "a", "SourceLocation", "object", ".", "We", "separate", "the", "fields", "by", "a", "|" ]
facebook/pyre-check
python
https://github.com/facebook/pyre-check/blob/4a9604d943d28ef20238505a51acfb1f666328d7/sapp/sapp/models.py#L291-L303
[ "def", "process_result_value", "(", "self", ",", "value", ",", "dialect", ")", ":", "if", "value", "is", "None", ":", "return", "None", "p", "=", "value", ".", "split", "(", "\"|\"", ")", "if", "len", "(", "p", ")", "==", "0", ":", "return", "None"...
4a9604d943d28ef20238505a51acfb1f666328d7
train
PrimaryKeyGenerator.reserve
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
sapp/sapp/models.py
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...
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...
[ "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"...
facebook/pyre-check
python
https://github.com/facebook/pyre-check/blob/4a9604d943d28ef20238505a51acfb1f666328d7/sapp/sapp/models.py#L1382-L1403
[ "def", "reserve", "(", "self", ",", "session", ":", "Session", ",", "saving_classes", ":", "List", "[", "Type", "]", ",", "item_counts", ":", "Optional", "[", "Dict", "[", "str", ",", "int", "]", "]", "=", "None", ",", "use_lock", ":", "bool", "=", ...
4a9604d943d28ef20238505a51acfb1f666328d7
train
BaseParser.analysis_output_to_dict_entries
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...
sapp/sapp/base_parser.py
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 ...
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 ...
[ "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", ...
facebook/pyre-check
python
https://github.com/facebook/pyre-check/blob/4a9604d943d28ef20238505a51acfb1f666328d7/sapp/sapp/base_parser.py#L109-L180
[ "def", "analysis_output_to_dict_entries", "(", "self", ",", "inputfile", ":", "AnalysisOutput", ",", "previous_inputfile", ":", "Optional", "[", "AnalysisOutput", "]", ",", "previous_issue_handles", ":", "Optional", "[", "AnalysisOutput", "]", ",", "linemapfile", ":",...
4a9604d943d28ef20238505a51acfb1f666328d7
train
BaseParser.compute_diff_handle
Uses the absolute line and ignores the callable/character offsets. Used only in determining whether new issues are old issues.
sapp/sapp/base_parser.py
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...
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...
[ "Uses", "the", "absolute", "line", "and", "ignores", "the", "callable", "/", "character", "offsets", ".", "Used", "only", "in", "determining", "whether", "new", "issues", "are", "old", "issues", "." ]
facebook/pyre-check
python
https://github.com/facebook/pyre-check/blob/4a9604d943d28ef20238505a51acfb1f666328d7/sapp/sapp/base_parser.py#L224-L231
[ "def", "compute_diff_handle", "(", "filename", ",", "old_line", ",", "code", ")", ":", "key", "=", "\"{filename}:{old_line}:{code}\"", ".", "format", "(", "filename", "=", "filename", ",", "old_line", "=", "old_line", ",", "code", "=", "code", ")", "return", ...
4a9604d943d28ef20238505a51acfb1f666328d7
train
is_capable_terminal
Determine whether we are connected to a capable terminal.
client/__init__.py
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"]
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"]
[ "Determine", "whether", "we", "are", "connected", "to", "a", "capable", "terminal", "." ]
facebook/pyre-check
python
https://github.com/facebook/pyre-check/blob/4a9604d943d28ef20238505a51acfb1f666328d7/client/__init__.py#L54-L62
[ "def", "is_capable_terminal", "(", "file", "=", "sys", ".", "stderr", ")", "->", "bool", ":", "if", "not", "os", ".", "isatty", "(", "file", ".", "fileno", "(", ")", ")", ":", "return", "False", "terminal", "=", "os", ".", "getenv", "(", "\"TERM\"", ...
4a9604d943d28ef20238505a51acfb1f666328d7
train
_find_directory_upwards
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.
client/__init__.py
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 = ...
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 = ...
[ "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...
facebook/pyre-check
python
https://github.com/facebook/pyre-check/blob/4a9604d943d28ef20238505a51acfb1f666328d7/client/__init__.py#L260-L276
[ "def", "_find_directory_upwards", "(", "base", ":", "str", ",", "target", ":", "str", ")", "->", "Optional", "[", "str", "]", ":", "while", "True", ":", "step", "=", "os", ".", "path", ".", "join", "(", "base", ",", "target", ")", "LOG", ".", "debu...
4a9604d943d28ef20238505a51acfb1f666328d7
train
FastBuckBuilder.compute_targets_to_build
Compute the set of targets to build for the given targets using a breadth-first traversal.
client/buck_project_builder/__init__.py
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...
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", "to", "build", "for", "the", "given", "targets", "using", "a", "breadth", "-", "first", "traversal", "." ]
facebook/pyre-check
python
https://github.com/facebook/pyre-check/blob/4a9604d943d28ef20238505a51acfb1f666328d7/client/buck_project_builder/__init__.py#L52-L89
[ "def", "compute_targets_to_build", "(", "self", ",", "targets", ":", "Iterable", "[", "str", "]", ")", "->", "Iterable", "[", "BuildTarget", "]", ":", "normalized_targets", "=", "set", "(", ")", "for", "target", "in", "targets", ":", "normalized_targets", "....
4a9604d943d28ef20238505a51acfb1f666328d7
train
FastBuckBuilder.compute_reverse_dependencies
Compute the set of targets which depend on each target.
client/buck_project_builder/__init__.py
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....
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....
[ "Compute", "the", "set", "of", "targets", "which", "depend", "on", "each", "target", "." ]
facebook/pyre-check
python
https://github.com/facebook/pyre-check/blob/4a9604d943d28ef20238505a51acfb1f666328d7/client/buck_project_builder/__init__.py#L91-L101
[ "def", "compute_reverse_dependencies", "(", "self", ",", "targets", ":", "Iterable", "[", "BuildTarget", "]", ")", "->", "Mapping", "[", "str", ",", "Iterable", "[", "BuildTarget", "]", "]", ":", "result", "=", "defaultdict", "(", "list", ")", "for", "targ...
4a9604d943d28ef20238505a51acfb1f666328d7
train
_ConfigurationFile.consume
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.
client/configuration.py
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...
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...
[ "Consume", "a", "key", "from", "the", "configuration", ".", "When", "a", "key", "is", "consumed", "it", "is", "removed", "from", "the", "configuration", "." ]
facebook/pyre-check
python
https://github.com/facebook/pyre-check/blob/4a9604d943d28ef20238505a51acfb1f666328d7/client/configuration.py#L73-L95
[ "def", "consume", "(", "self", ",", "key", ",", "default", "=", "None", ",", "current", "=", "None", ",", "print_on_success", "=", "False", ")", ":", "value", "=", "self", ".", "_configuration", ".", "pop", "(", "key", ",", "default", ")", "if", "cur...
4a9604d943d28ef20238505a51acfb1f666328d7
train
Interactive.analysis_output
Sets the location of the output from the static analysis tool. Parameters: location: str Filesystem location for the results.
sapp/sapp/interactive.py
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(...
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(...
[ "Sets", "the", "location", "of", "the", "output", "from", "the", "static", "analysis", "tool", "." ]
facebook/pyre-check
python
https://github.com/facebook/pyre-check/blob/4a9604d943d28ef20238505a51acfb1f666328d7/sapp/sapp/interactive.py#L319-L334
[ "def", "analysis_output", "(", "self", ",", "location", ":", "Optional", "[", "str", "]", "=", "None", ")", "->", "None", ":", "try", ":", "if", "not", "location", ":", "location", "=", "self", ".", "prompt", "(", "\"Analysis results: \"", ",", "history_...
4a9604d943d28ef20238505a51acfb1f666328d7
train
Interactive.issue
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.
sapp/sapp/interactive.py
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: ...
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: ...
[ "Select", "an", "issue", "." ]
facebook/pyre-check
python
https://github.com/facebook/pyre-check/blob/4a9604d943d28ef20238505a51acfb1f666328d7/sapp/sapp/interactive.py#L365-L407
[ "def", "issue", "(", "self", ",", "issue_instance_id", ")", ":", "with", "self", ".", "db", ".", "make_session", "(", ")", "as", "session", ":", "selected_issue", "=", "(", "session", ".", "query", "(", "IssueInstance", ")", ".", "filter", "(", "IssueIns...
4a9604d943d28ef20238505a51acfb1f666328d7
train
Interactive.show
More details about the selected issue or trace frame.
sapp/sapp/interactive.py
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()
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()
[ "More", "details", "about", "the", "selected", "issue", "or", "trace", "frame", "." ]
facebook/pyre-check
python
https://github.com/facebook/pyre-check/blob/4a9604d943d28ef20238505a51acfb1f666328d7/sapp/sapp/interactive.py#L411-L420
[ "def", "show", "(", "self", ")", ":", "self", ".", "_verify_entrypoint_selected", "(", ")", "if", "self", ".", "current_issue_instance_id", "!=", "-", "1", ":", "self", ".", "_show_current_issue_instance", "(", ")", "return", "self", ".", "_show_current_trace_fr...
4a9604d943d28ef20238505a51acfb1f666328d7
train
Interactive.issues
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...
sapp/sapp/interactive.py
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 ...
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 ...
[ "Lists", "issues", "for", "the", "selected", "run", "." ]
facebook/pyre-check
python
https://github.com/facebook/pyre-check/blob/4a9604d943d28ef20238505a51acfb1f666328d7/sapp/sapp/interactive.py#L424-L507
[ "def", "issues", "(", "self", ",", "use_pager", ":", "bool", "=", "None", ",", "*", ",", "codes", ":", "Optional", "[", "Union", "[", "int", ",", "List", "[", "int", "]", "]", "]", "=", "None", ",", "callables", ":", "Optional", "[", "Union", "["...
4a9604d943d28ef20238505a51acfb1f666328d7
train
Interactive.frames
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...
sapp/sapp/interactive.py
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...
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...
[ "Display", "trace", "frames", "independent", "of", "the", "current", "issue", "." ]
facebook/pyre-check
python
https://github.com/facebook/pyre-check/blob/4a9604d943d28ef20238505a51acfb1f666328d7/sapp/sapp/interactive.py#L538-L606
[ "def", "frames", "(", "self", ",", "*", ",", "callers", ":", "Optional", "[", "Union", "[", "str", ",", "List", "[", "str", "]", "]", "]", "=", "None", ",", "callees", ":", "Optional", "[", "Union", "[", "str", ",", "List", "[", "str", "]", "]"...
4a9604d943d28ef20238505a51acfb1f666328d7
train
Interactive.next_cursor_location
Move cursor to the next trace frame.
sapp/sapp/interactive.py
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()
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", "next", "trace", "frame", "." ]
facebook/pyre-check
python
https://github.com/facebook/pyre-check/blob/4a9604d943d28ef20238505a51acfb1f666328d7/sapp/sapp/interactive.py#L762-L769
[ "def", "next_cursor_location", "(", "self", ")", ":", "self", ".", "_verify_entrypoint_selected", "(", ")", "self", ".", "current_trace_frame_index", "=", "min", "(", "self", ".", "current_trace_frame_index", "+", "1", ",", "len", "(", "self", ".", "trace_tuples...
4a9604d943d28ef20238505a51acfb1f666328d7
train
Interactive.prev_cursor_location
Move cursor to the previous trace frame.
sapp/sapp/interactive.py
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()
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()
[ "Move", "cursor", "to", "the", "previous", "trace", "frame", "." ]
facebook/pyre-check
python
https://github.com/facebook/pyre-check/blob/4a9604d943d28ef20238505a51acfb1f666328d7/sapp/sapp/interactive.py#L772-L777
[ "def", "prev_cursor_location", "(", "self", ")", ":", "self", ".", "_verify_entrypoint_selected", "(", ")", "self", ".", "current_trace_frame_index", "=", "max", "(", "self", ".", "current_trace_frame_index", "-", "1", ",", "0", ")", "self", ".", "trace", "(",...
4a9604d943d28ef20238505a51acfb1f666328d7
train
Interactive.jump
Jump to a specific trace frame in a trace. Parameters: selected_number: int the trace frame number from trace output
sapp/sapp/interactive.py
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_...
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_...
[ "Jump", "to", "a", "specific", "trace", "frame", "in", "a", "trace", "." ]
facebook/pyre-check
python
https://github.com/facebook/pyre-check/blob/4a9604d943d28ef20238505a51acfb1f666328d7/sapp/sapp/interactive.py#L780-L794
[ "def", "jump", "(", "self", ",", "selected_number", ":", "int", ")", "->", "None", ":", "self", ".", "_verify_entrypoint_selected", "(", ")", "if", "selected_number", "<", "1", "or", "selected_number", ">", "len", "(", "self", ".", "trace_tuples", ")", ":"...
4a9604d943d28ef20238505a51acfb1f666328d7
train
Interactive.branch
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...
sapp/sapp/interactive.py
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...
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", "and", "select", "branches", "for", "a", "branched", "trace", ".", "-", "[", "*", "]", "signifies", "the", "current", "branch", "that", "is", "selected", "-", "will", "prompt", "for", "branch", "selection", "if", "called", "with", "no", "argument",...
facebook/pyre-check
python
https://github.com/facebook/pyre-check/blob/4a9604d943d28ef20238505a51acfb1f666328d7/sapp/sapp/interactive.py#L828-L898
[ "def", "branch", "(", "self", ",", "selected_number", ":", "Optional", "[", "int", "]", "=", "None", ")", "->", "None", ":", "self", ".", "_verify_entrypoint_selected", "(", ")", "self", ".", "_verify_multiple_branches", "(", ")", "with", "self", ".", "db"...
4a9604d943d28ef20238505a51acfb1f666328d7
train
Interactive.list_source_code
Show source code around the current trace frame location. Parameters: context: int number of lines to show above and below trace location (default: 5)
sapp/sapp/interactive.py
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...
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", "source", "code", "around", "the", "current", "trace", "frame", "location", "." ]
facebook/pyre-check
python
https://github.com/facebook/pyre-check/blob/4a9604d943d28ef20238505a51acfb1f666328d7/sapp/sapp/interactive.py#L902-L927
[ "def", "list_source_code", "(", "self", ",", "context", ":", "int", "=", "5", ")", "->", "None", ":", "self", ".", "_verify_entrypoint_selected", "(", ")", "current_trace_frame", "=", "self", ".", "trace_tuples", "[", "self", ".", "current_trace_frame_index", ...
4a9604d943d28ef20238505a51acfb1f666328d7
train
Interactive.details
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)
sapp/sapp/interactive.py
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...
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...
[ "Show", "additional", "info", "about", "the", "current", "trace", "frame", "." ]
facebook/pyre-check
python
https://github.com/facebook/pyre-check/blob/4a9604d943d28ef20238505a51acfb1f666328d7/sapp/sapp/interactive.py#L929-L962
[ "def", "details", "(", "self", ",", "*", ",", "limit", ":", "Optional", "[", "int", "]", "=", "5", ",", "kind", ":", "Optional", "[", "TraceKind", "]", "=", "None", ")", "->", "None", ":", "self", ".", "_verify_entrypoint_selected", "(", ")", "if", ...
4a9604d943d28ef20238505a51acfb1f666328d7
train
Interactive._group_trace_frames
Buckets together trace frames that have the same caller:caller_port.
sapp/sapp/interactive.py
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...
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...
[ "Buckets", "together", "trace", "frames", "that", "have", "the", "same", "caller", ":", "caller_port", "." ]
facebook/pyre-check
python
https://github.com/facebook/pyre-check/blob/4a9604d943d28ef20238505a51acfb1f666328d7/sapp/sapp/interactive.py#L1004-L1017
[ "def", "_group_trace_frames", "(", "self", ",", "trace_frames", ":", "Iterable", "[", "TraceFrameQueryResult", "]", ",", "limit", ":", "int", ")", "->", "Dict", "[", "Tuple", "[", "str", ",", "str", "]", ",", "List", "[", "TraceFrameQueryResult", "]", "]",...
4a9604d943d28ef20238505a51acfb1f666328d7
train
Interactive._next_trace_frames
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.
sapp/sapp/interactive.py
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...
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...
[ "Finds", "all", "trace", "frames", "that", "the", "given", "trace_frame", "flows", "to", "." ]
facebook/pyre-check
python
https://github.com/facebook/pyre-check/blob/4a9604d943d28ef20238505a51acfb1f666328d7/sapp/sapp/interactive.py#L1313-L1381
[ "def", "_next_trace_frames", "(", "self", ",", "session", ":", "Session", ",", "trace_frame", ":", "TraceFrameQueryResult", ",", "visited_ids", ":", "Set", "[", "int", "]", ",", "backwards", ":", "bool", "=", "False", ",", ")", "->", "List", "[", "TraceFra...
4a9604d943d28ef20238505a51acfb1f666328d7
train
Interactive.callable
Show the name of the current callable in the trace
sapp/sapp/interactive.py
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
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
[ "Show", "the", "name", "of", "the", "current", "callable", "in", "the", "trace" ]
facebook/pyre-check
python
https://github.com/facebook/pyre-check/blob/4a9604d943d28ef20238505a51acfb1f666328d7/sapp/sapp/interactive.py#L1568-L1574
[ "def", "callable", "(", "self", ")", "->", "Optional", "[", "str", "]", ":", "if", "self", ".", "current_trace_frame_index", "!=", "-", "1", ":", "return", "self", ".", "_get_callable_from_trace_tuple", "(", "self", ".", "trace_tuples", "[", "self", ".", "...
4a9604d943d28ef20238505a51acfb1f666328d7
train
Interactive._get_callable_from_trace_tuple
Returns either (caller, caller_port) or (callee, callee_port).
sapp/sapp/interactive.py
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...
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...
[ "Returns", "either", "(", "caller", "caller_port", ")", "or", "(", "callee", "callee_port", ")", "." ]
facebook/pyre-check
python
https://github.com/facebook/pyre-check/blob/4a9604d943d28ef20238505a51acfb1f666328d7/sapp/sapp/interactive.py#L1618-L1626
[ "def", "_get_callable_from_trace_tuple", "(", "self", ",", "trace_tuple", ":", "TraceTuple", ")", "->", "Tuple", "[", "str", ",", "str", "]", ":", "trace_frame", "=", "trace_tuple", ".", "trace_frame", "if", "trace_tuple", ".", "placeholder", ":", "return", "t...
4a9604d943d28ef20238505a51acfb1f666328d7
train
require_option
Throw an exception if an option wasn't required. This is useful when its optional in some contexts but required for a subcommand
sapp/sapp/cli_lib.py
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...
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...
[ "Throw", "an", "exception", "if", "an", "option", "wasn", "t", "required", ".", "This", "is", "useful", "when", "its", "optional", "in", "some", "contexts", "but", "required", "for", "a", "subcommand" ]
facebook/pyre-check
python
https://github.com/facebook/pyre-check/blob/4a9604d943d28ef20238505a51acfb1f666328d7/sapp/sapp/cli_lib.py#L33-L52
[ "def", "require_option", "(", "current_ctx", ":", "click", ".", "Context", ",", "param_name", ":", "str", ")", "->", "None", ":", "ctx", "=", "current_ctx", "param_definition", "=", "None", "while", "ctx", "is", "not", "None", ":", "# ctx.command.params has th...
4a9604d943d28ef20238505a51acfb1f666328d7
train
default_database
Try to guess a reasonable database name by looking at the repository path
sapp/sapp/cli_lib.py
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...
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...
[ "Try", "to", "guess", "a", "reasonable", "database", "name", "by", "looking", "at", "the", "repository", "path" ]
facebook/pyre-check
python
https://github.com/facebook/pyre-check/blob/4a9604d943d28ef20238505a51acfb1f666328d7/sapp/sapp/cli_lib.py#L78-L86
[ "def", "default_database", "(", "ctx", ":", "click", ".", "Context", ",", "_param", ":", "Parameter", ",", "value", ":", "Optional", "[", "str", "]", ")", ":", "if", "value", ":", "return", "value", "if", "ctx", ".", "params", "[", "\"repository\"", "]...
4a9604d943d28ef20238505a51acfb1f666328d7
train
lint
Output DB models in a lint-friendly format
sapp/sapp/lint.py
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...
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...
[ "Output", "DB", "models", "in", "a", "lint", "-", "friendly", "format" ]
facebook/pyre-check
python
https://github.com/facebook/pyre-check/blob/4a9604d943d28ef20238505a51acfb1f666328d7/sapp/sapp/lint.py#L29-L95
[ "def", "lint", "(", "click_ctx", ":", "click", ".", "Context", ",", "run_id", ":", "int", ",", "filenames", ":", "List", "[", "str", "]", ")", "->", "None", ":", "ctx", "=", "click_ctx", ".", "obj", "require_option", "(", "click_ctx", ",", "\"repositor...
4a9604d943d28ef20238505a51acfb1f666328d7
train
resolve_source_mapping
Returns a mapping from absolute source path to absolute output path as specified by the sources object. Files are not guaranteed to exist.
client/buck_project_builder/filesystem.py
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...
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...
[ "Returns", "a", "mapping", "from", "absolute", "source", "path", "to", "absolute", "output", "path", "as", "specified", "by", "the", "sources", "object", ".", "Files", "are", "not", "guaranteed", "to", "exist", "." ]
facebook/pyre-check
python
https://github.com/facebook/pyre-check/blob/4a9604d943d28ef20238505a51acfb1f666328d7/client/buck_project_builder/filesystem.py#L33-L58
[ "def", "resolve_source_mapping", "(", "source_directory", ":", "str", ",", "output_directory", ":", "str", ",", "sources", ":", "Sources", ")", "->", "Mapping", "[", "str", ",", "str", "]", ":", "result", "=", "{", "os", ".", "path", ".", "join", "(", ...
4a9604d943d28ef20238505a51acfb1f666328d7
train
resolve_relative_paths
Query buck to obtain a mapping from each absolute path to the relative location in the analysis directory.
client/buck.py
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...
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...
[ "Query", "buck", "to", "obtain", "a", "mapping", "from", "each", "absolute", "path", "to", "the", "relative", "location", "in", "the", "analysis", "directory", "." ]
facebook/pyre-check
python
https://github.com/facebook/pyre-check/blob/4a9604d943d28ef20238505a51acfb1f666328d7/client/buck.py#L190-L245
[ "def", "resolve_relative_paths", "(", "paths", ":", "List", "[", "str", "]", ")", "->", "Dict", "[", "str", ",", "str", "]", ":", "buck_root", "=", "find_buck_root", "(", "os", ".", "getcwd", "(", ")", ")", "if", "buck_root", "is", "None", ":", "LOG"...
4a9604d943d28ef20238505a51acfb1f666328d7
train
SimpleBuckBuilder.build
Shell out to buck to build the targets, then yield the paths to the link trees.
client/buck.py
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 )
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 )
[ "Shell", "out", "to", "buck", "to", "build", "the", "targets", "then", "yield", "the", "paths", "to", "the", "link", "trees", "." ]
facebook/pyre-check
python
https://github.com/facebook/pyre-check/blob/4a9604d943d28ef20238505a51acfb1f666328d7/client/buck.py#L32-L39
[ "def", "build", "(", "self", ",", "targets", ":", "Iterable", "[", "str", "]", ")", "->", "Iterable", "[", "str", "]", ":", "return", "generate_source_directories", "(", "targets", ",", "build", "=", "self", ".", "_build", ",", "prompt", "=", "self", "...
4a9604d943d28ef20238505a51acfb1f666328d7
train
FunctionStub._get_parameter_string
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)
client/infer.py
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"] ...
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"] ...
[ "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", ")" ]
facebook/pyre-check
python
https://github.com/facebook/pyre-check/blob/4a9604d943d28ef20238505a51acfb1f666328d7/client/infer.py#L83-L99
[ "def", "_get_parameter_string", "(", "self", ")", "->", "str", ":", "parameters", "=", "[", "]", "for", "parameter", "in", "self", ".", "parameters", ":", "name", "=", "parameter", "[", "\"name\"", "]", "if", "parameter", "[", "\"type\"", "]", ":", "name...
4a9604d943d28ef20238505a51acfb1f666328d7
train
FunctionStub.is_complete
Determines if a stub completely types a function
client/infer.py
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
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
[ "Determines", "if", "a", "stub", "completely", "types", "a", "function" ]
facebook/pyre-check
python
https://github.com/facebook/pyre-check/blob/4a9604d943d28ef20238505a51acfb1f666328d7/client/infer.py#L110-L117
[ "def", "is_complete", "(", "self", ")", "->", "bool", ":", "if", "not", "self", ".", "actual", ":", "return", "False", "for", "parameter", "in", "self", ".", "parameters", ":", "if", "parameter", "[", "\"name\"", "]", "!=", "\"self\"", "and", "not", "p...
4a9604d943d28ef20238505a51acfb1f666328d7
train
StubFile.to_string
We currently ignore nested classes, i.e.: class X: class Y: [ALL OF THIS IS IGNORED]
client/infer.py
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 ...
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 ...
[ "We", "currently", "ignore", "nested", "classes", "i", ".", "e", ".", ":", "class", "X", ":", "class", "Y", ":", "[", "ALL", "OF", "THIS", "IS", "IGNORED", "]" ]
facebook/pyre-check
python
https://github.com/facebook/pyre-check/blob/4a9604d943d28ef20238505a51acfb1f666328d7/client/infer.py#L239-L279
[ "def", "to_string", "(", "self", ")", "->", "str", ":", "classes", "=", "defaultdict", "(", "list", ")", "typing_imports", "=", "set", "(", ")", "contents", "=", "\"\"", "# import necessary modules from typing", "for", "stub", "in", "self", ".", "_stubs", ":...
4a9604d943d28ef20238505a51acfb1f666328d7
train
download
Download a trained weights, config and preprocessor. Args: url (str): target url.
anago/utils.py
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...
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...
[ "Download", "a", "trained", "weights", "config", "and", "preprocessor", "." ]
Hironsan/anago
python
https://github.com/Hironsan/anago/blob/66a97f91c41f9613b736892e9762dccb9c28f623/anago/utils.py#L12-L24
[ "def", "download", "(", "url", ")", ":", "filepath", "=", "get_file", "(", "fname", "=", "'tmp.zip'", ",", "origin", "=", "url", ",", "extract", "=", "True", ")", "base_dir", "=", "os", ".", "path", ".", "dirname", "(", "filepath", ")", "weights_file",...
66a97f91c41f9613b736892e9762dccb9c28f623
train
load_data_and_labels
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...
anago/utils.py
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...
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", "data", "and", "label", "from", "a", "file", "." ]
Hironsan/anago
python
https://github.com/Hironsan/anago/blob/66a97f91c41f9613b736892e9762dccb9c28f623/anago/utils.py#L27-L75
[ "def", "load_data_and_labels", "(", "filename", ",", "encoding", "=", "'utf-8'", ")", ":", "sents", ",", "labels", "=", "[", "]", ",", "[", "]", "words", ",", "tags", "=", "[", "]", ",", "[", "]", "with", "open", "(", "filename", ",", "encoding", "...
66a97f91c41f9613b736892e9762dccb9c28f623
train
filter_embeddings
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.
anago/utils.py
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): ...
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", "word", "vectors", "in", "numpy", "array", "." ]
Hironsan/anago
python
https://github.com/Hironsan/anago/blob/66a97f91c41f9613b736892e9762dccb9c28f623/anago/utils.py#L246-L264
[ "def", "filter_embeddings", "(", "embeddings", ",", "vocab", ",", "dim", ")", ":", "if", "not", "isinstance", "(", "embeddings", ",", "dict", ")", ":", "return", "_embeddings", "=", "np", ".", "zeros", "(", "[", "len", "(", "vocab", ")", ",", "dim", ...
66a97f91c41f9613b736892e9762dccb9c28f623
train
load_glove
Loads GloVe vectors in numpy array. Args: file (str): a path to a glove file. Return: dict: a dict of numpy arrays.
anago/utils.py
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(' ') ...
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(' ') ...
[ "Loads", "GloVe", "vectors", "in", "numpy", "array", "." ]
Hironsan/anago
python
https://github.com/Hironsan/anago/blob/66a97f91c41f9613b736892e9762dccb9c28f623/anago/utils.py#L267-L284
[ "def", "load_glove", "(", "file", ")", ":", "model", "=", "{", "}", "with", "open", "(", "file", ",", "encoding", "=", "\"utf8\"", ",", "errors", "=", "'ignore'", ")", "as", "f", ":", "for", "line", "in", "f", ":", "line", "=", "line", ".", "spli...
66a97f91c41f9613b736892e9762dccb9c28f623
train
Vocabulary.add_token
Add token to vocabulary. Args: token (str): token to add.
anago/utils.py
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])
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])
[ "Add", "token", "to", "vocabulary", "." ]
Hironsan/anago
python
https://github.com/Hironsan/anago/blob/66a97f91c41f9613b736892e9762dccb9c28f623/anago/utils.py#L128-L135
[ "def", "add_token", "(", "self", ",", "token", ")", ":", "token", "=", "self", ".", "process_token", "(", "token", ")", "self", ".", "_token_count", ".", "update", "(", "[", "token", "]", ")" ]
66a97f91c41f9613b736892e9762dccb9c28f623
train
Vocabulary.add_documents
Update dictionary from a collection of documents. Each document is a list of tokens. Args: docs (list): documents to add.
anago/utils.py
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...
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...
[ "Update", "dictionary", "from", "a", "collection", "of", "documents", ".", "Each", "document", "is", "a", "list", "of", "tokens", "." ]
Hironsan/anago
python
https://github.com/Hironsan/anago/blob/66a97f91c41f9613b736892e9762dccb9c28f623/anago/utils.py#L137-L146
[ "def", "add_documents", "(", "self", ",", "docs", ")", ":", "for", "sent", "in", "docs", ":", "sent", "=", "map", "(", "self", ".", "process_token", ",", "sent", ")", "self", ".", "_token_count", ".", "update", "(", "sent", ")" ]
66a97f91c41f9613b736892e9762dccb9c28f623
train
Vocabulary.doc2id
Get the list of token_id given doc. Args: doc (list): document. Returns: list: int id of doc.
anago/utils.py
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]
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]
[ "Get", "the", "list", "of", "token_id", "given", "doc", "." ]
Hironsan/anago
python
https://github.com/Hironsan/anago/blob/66a97f91c41f9613b736892e9762dccb9c28f623/anago/utils.py#L148-L158
[ "def", "doc2id", "(", "self", ",", "doc", ")", ":", "doc", "=", "map", "(", "self", ".", "process_token", ",", "doc", ")", "return", "[", "self", ".", "token_to_id", "(", "token", ")", "for", "token", "in", "doc", "]" ]
66a97f91c41f9613b736892e9762dccb9c28f623
train
Vocabulary.build
Build vocabulary.
anago/utils.py
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...
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...
[ "Build", "vocabulary", "." ]
Hironsan/anago
python
https://github.com/Hironsan/anago/blob/66a97f91c41f9613b736892e9762dccb9c28f623/anago/utils.py#L171-L184
[ "def", "build", "(", "self", ")", ":", "token_freq", "=", "self", ".", "_token_count", ".", "most_common", "(", "self", ".", "_max_size", ")", "idx", "=", "len", "(", "self", ".", "vocab", ")", "for", "token", ",", "_", "in", "token_freq", ":", "self...
66a97f91c41f9613b736892e9762dccb9c28f623
train
Vocabulary.token_to_id
Get the token_id of given token. Args: token (str): token from vocabulary. Returns: int: int id of token.
anago/utils.py
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)
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)
[ "Get", "the", "token_id", "of", "given", "token", "." ]
Hironsan/anago
python
https://github.com/Hironsan/anago/blob/66a97f91c41f9613b736892e9762dccb9c28f623/anago/utils.py#L204-L214
[ "def", "token_to_id", "(", "self", ",", "token", ")", ":", "token", "=", "self", ".", "process_token", "(", "token", ")", "return", "self", ".", "_token2id", ".", "get", "(", "token", ",", "len", "(", "self", ".", "_token2id", ")", "-", "1", ")" ]
66a97f91c41f9613b736892e9762dccb9c28f623
train
Tagger.predict_proba
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...
anago/tagger.py
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...
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...
[ "Probability", "estimates", "." ]
Hironsan/anago
python
https://github.com/Hironsan/anago/blob/66a97f91c41f9613b736892e9762dccb9c28f623/anago/tagger.py#L22-L42
[ "def", "predict_proba", "(", "self", ",", "text", ")", ":", "assert", "isinstance", "(", "text", ",", "str", ")", "words", "=", "self", ".", "tokenizer", "(", "text", ")", "X", "=", "self", ".", "preprocessor", ".", "transform", "(", "[", "words", "]...
66a97f91c41f9613b736892e9762dccb9c28f623
train
Tagger.analyze
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": [ ...
anago/tagger.py
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) { ...
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) { ...
[ "Analyze", "text", "and", "return", "pretty", "format", "." ]
Hironsan/anago
python
https://github.com/Hironsan/anago/blob/66a97f91c41f9613b736892e9762dccb9c28f623/anago/tagger.py#L78-L124
[ "def", "analyze", "(", "self", ",", "text", ")", ":", "pred", "=", "self", ".", "predict_proba", "(", "text", ")", "tags", "=", "self", ".", "_get_tags", "(", "pred", ")", "prob", "=", "self", ".", "_get_prob", "(", "pred", ")", "res", "=", "self",...
66a97f91c41f9613b736892e9762dccb9c28f623
train
Tagger.predict
Predict using the model. Args: text: string, the input text. Returns: tags: list, shape = (num_words,) Returns predicted values.
anago/tagger.py
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...
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...
[ "Predict", "using", "the", "model", "." ]
Hironsan/anago
python
https://github.com/Hironsan/anago/blob/66a97f91c41f9613b736892e9762dccb9c28f623/anago/tagger.py#L126-L139
[ "def", "predict", "(", "self", ",", "text", ")", ":", "pred", "=", "self", ".", "predict_proba", "(", "text", ")", "tags", "=", "self", ".", "_get_tags", "(", "pred", ")", "return", "tags" ]
66a97f91c41f9613b736892e9762dccb9c28f623
train
pad_nested_sequences
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.
anago/preprocessing.py
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...
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...
[ "Pads", "nested", "sequences", "to", "the", "same", "length", "." ]
Hironsan/anago
python
https://github.com/Hironsan/anago/blob/66a97f91c41f9613b736892e9762dccb9c28f623/anago/preprocessing.py#L169-L194
[ "def", "pad_nested_sequences", "(", "sequences", ",", "dtype", "=", "'int32'", ")", ":", "max_sent_len", "=", "0", "max_word_len", "=", "0", "for", "sent", "in", "sequences", ":", "max_sent_len", "=", "max", "(", "len", "(", "sent", ")", ",", "max_sent_len...
66a97f91c41f9613b736892e9762dccb9c28f623
train
IndexTransformer.fit
Learn vocabulary from training set. Args: X : iterable. An iterable which yields either str, unicode or file objects. Returns: self : IndexTransformer.
anago/preprocessing.py
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(...
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(...
[ "Learn", "vocabulary", "from", "training", "set", "." ]
Hironsan/anago
python
https://github.com/Hironsan/anago/blob/66a97f91c41f9613b736892e9762dccb9c28f623/anago/preprocessing.py#L55-L74
[ "def", "fit", "(", "self", ",", "X", ",", "y", ")", ":", "self", ".", "_word_vocab", ".", "add_documents", "(", "X", ")", "self", ".", "_label_vocab", ".", "add_documents", "(", "y", ")", "if", "self", ".", "_use_char", ":", "for", "doc", "in", "X"...
66a97f91c41f9613b736892e9762dccb9c28f623
train
IndexTransformer.transform
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 ...
anago/preprocessing.py
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...
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...
[ "Transform", "documents", "to", "document", "ids", "." ]
Hironsan/anago
python
https://github.com/Hironsan/anago/blob/66a97f91c41f9613b736892e9762dccb9c28f623/anago/preprocessing.py#L76-L113
[ "def", "transform", "(", "self", ",", "X", ",", "y", "=", "None", ")", ":", "word_ids", "=", "[", "self", ".", "_word_vocab", ".", "doc2id", "(", "doc", ")", "for", "doc", "in", "X", "]", "word_ids", "=", "pad_sequences", "(", "word_ids", ",", "pad...
66a97f91c41f9613b736892e9762dccb9c28f623
train
IndexTransformer.fit_transform
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.
anago/preprocessing.py
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...
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...
[ "Learn", "vocabulary", "and", "return", "document", "id", "matrix", "." ]
Hironsan/anago
python
https://github.com/Hironsan/anago/blob/66a97f91c41f9613b736892e9762dccb9c28f623/anago/preprocessing.py#L115-L128
[ "def", "fit_transform", "(", "self", ",", "X", ",", "y", "=", "None", ",", "*", "*", "params", ")", ":", "return", "self", ".", "fit", "(", "X", ",", "y", ")", ".", "transform", "(", "X", ",", "y", ")" ]
66a97f91c41f9613b736892e9762dccb9c28f623
train
IndexTransformer.inverse_transform
Return label strings. Args: y: label id matrix. lengths: sentences length. Returns: list: list of list of strings.
anago/preprocessing.py
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...
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...
[ "Return", "label", "strings", "." ]
Hironsan/anago
python
https://github.com/Hironsan/anago/blob/66a97f91c41f9613b736892e9762dccb9c28f623/anago/preprocessing.py#L130-L145
[ "def", "inverse_transform", "(", "self", ",", "y", ",", "lengths", "=", "None", ")", ":", "y", "=", "np", ".", "argmax", "(", "y", ",", "-", "1", ")", "inverse_y", "=", "[", "self", ".", "_label_vocab", ".", "id2doc", "(", "ids", ")", "for", "ids...
66a97f91c41f9613b736892e9762dccb9c28f623
train
ELMoTransformer.transform
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 ...
anago/preprocessing.py
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...
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...
[ "Transform", "documents", "to", "document", "ids", "." ]
Hironsan/anago
python
https://github.com/Hironsan/anago/blob/66a97f91c41f9613b736892e9762dccb9c28f623/anago/preprocessing.py#L204-L243
[ "def", "transform", "(", "self", ",", "X", ",", "y", "=", "None", ")", ":", "word_ids", "=", "[", "self", ".", "_word_vocab", ".", "doc2id", "(", "doc", ")", "for", "doc", "in", "X", "]", "word_ids", "=", "pad_sequences", "(", "word_ids", ",", "pad...
66a97f91c41f9613b736892e9762dccb9c28f623
train
Trainer.train
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...
anago/trainer.py
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...
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...
[ "Trains", "the", "model", "for", "a", "fixed", "number", "of", "epochs", "(", "iterations", "on", "a", "dataset", ")", "." ]
Hironsan/anago
python
https://github.com/Hironsan/anago/blob/66a97f91c41f9613b736892e9762dccb9c28f623/anago/trainer.py#L19-L51
[ "def", "train", "(", "self", ",", "x_train", ",", "y_train", ",", "x_valid", "=", "None", ",", "y_valid", "=", "None", ",", "epochs", "=", "1", ",", "batch_size", "=", "32", ",", "verbose", "=", "1", ",", "callbacks", "=", "None", ",", "shuffle", "...
66a97f91c41f9613b736892e9762dccb9c28f623
train
Sequence.fit
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...
anago/wrapper.py
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. ...
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. ...
[ "Fit", "the", "model", "for", "a", "fixed", "number", "of", "epochs", "." ]
Hironsan/anago
python
https://github.com/Hironsan/anago/blob/66a97f91c41f9613b736892e9762dccb9c28f623/anago/wrapper.py#L44-L90
[ "def", "fit", "(", "self", ",", "x_train", ",", "y_train", ",", "x_valid", "=", "None", ",", "y_valid", "=", "None", ",", "epochs", "=", "1", ",", "batch_size", "=", "32", ",", "verbose", "=", "1", ",", "callbacks", "=", "None", ",", "shuffle", "="...
66a97f91c41f9613b736892e9762dccb9c28f623
train
Sequence.predict
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.
anago/wrapper.py
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...
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...
[ "Returns", "the", "prediction", "of", "the", "model", "on", "the", "given", "test", "data", "." ]
Hironsan/anago
python
https://github.com/Hironsan/anago/blob/66a97f91c41f9613b736892e9762dccb9c28f623/anago/wrapper.py#L92-L110
[ "def", "predict", "(", "self", ",", "x_test", ")", ":", "if", "self", ".", "model", ":", "lengths", "=", "map", "(", "len", ",", "x_test", ")", "x_test", "=", "self", ".", "p", ".", "transform", "(", "x_test", ")", "y_pred", "=", "self", ".", "mo...
66a97f91c41f9613b736892e9762dccb9c28f623
train
Sequence.analyze
Analyze text and return pretty format. Args: text: string, the input text. tokenizer: Tokenize input sentence. Default tokenizer is `str.split`. Returns: res: dict.
anago/wrapper.py
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: ...
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: ...
[ "Analyze", "text", "and", "return", "pretty", "format", "." ]
Hironsan/anago
python
https://github.com/Hironsan/anago/blob/66a97f91c41f9613b736892e9762dccb9c28f623/anago/wrapper.py#L135-L150
[ "def", "analyze", "(", "self", ",", "text", ",", "tokenizer", "=", "str", ".", "split", ")", ":", "if", "not", "self", ".", "tagger", ":", "self", ".", "tagger", "=", "Tagger", "(", "self", ".", "model", ",", "preprocessor", "=", "self", ".", "p", ...
66a97f91c41f9613b736892e9762dccb9c28f623
train
CRF.get_log_normalization_constant
Compute logarithm of the normalization constant Z, where Z = sum exp(-E) -> logZ = log sum exp(-E) =: -nlogZ
anago/layers.py
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...
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...
[ "Compute", "logarithm", "of", "the", "normalization", "constant", "Z", "where", "Z", "=", "sum", "exp", "(", "-", "E", ")", "-", ">", "logZ", "=", "log", "sum", "exp", "(", "-", "E", ")", "=", ":", "-", "nlogZ" ]
Hironsan/anago
python
https://github.com/Hironsan/anago/blob/66a97f91c41f9613b736892e9762dccb9c28f623/anago/layers.py#L355-L361
[ "def", "get_log_normalization_constant", "(", "self", ",", "input_energy", ",", "mask", ",", "*", "*", "kwargs", ")", ":", "# should have logZ[:, i] == logZ[:, j] for any i, j", "logZ", "=", "self", ".", "recursion", "(", "input_energy", ",", "mask", ",", "return_se...
66a97f91c41f9613b736892e9762dccb9c28f623
train
CRF.get_energy
Energy = a1' y1 + u1' y1 + y1' U y2 + u2' y2 + y2' U y3 + u3' y3 + an' y3
anago/layers.py
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) ...
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) ...
[ "Energy", "=", "a1", "y1", "+", "u1", "y1", "+", "y1", "U", "y2", "+", "u2", "y2", "+", "y2", "U", "y3", "+", "u3", "y3", "+", "an", "y3" ]
Hironsan/anago
python
https://github.com/Hironsan/anago/blob/66a97f91c41f9613b736892e9762dccb9c28f623/anago/layers.py#L363-L376
[ "def", "get_energy", "(", "self", ",", "y_true", ",", "input_energy", ",", "mask", ")", ":", "input_energy", "=", "K", ".", "sum", "(", "input_energy", "*", "y_true", ",", "2", ")", "# (B, T)", "chain_energy", "=", "K", ".", "sum", "(", "K", ".", "do...
66a97f91c41f9613b736892e9762dccb9c28f623
train
CRF.get_negative_log_likelihood
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
anago/layers.py
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....
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....
[ "Compute", "the", "loss", "i", ".", "e", ".", "negative", "log", "likelihood", "(", "normalize", "by", "number", "of", "time", "steps", ")", "likelihood", "=", "1", "/", "Z", "*", "exp", "(", "-", "E", ")", "-", ">", "neg_log_like", "=", "-", "log"...
Hironsan/anago
python
https://github.com/Hironsan/anago/blob/66a97f91c41f9613b736892e9762dccb9c28f623/anago/layers.py#L378-L392
[ "def", "get_negative_log_likelihood", "(", "self", ",", "y_true", ",", "X", ",", "mask", ")", ":", "input_energy", "=", "self", ".", "activation", "(", "K", ".", "dot", "(", "X", ",", "self", ".", "kernel", ")", "+", "self", ".", "bias", ")", "if", ...
66a97f91c41f9613b736892e9762dccb9c28f623
train
CRF.recursion
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)) ...
anago/layers.py
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 ...
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 ...
[ "Forward", "(", "alpha", ")", "or", "backward", "(", "beta", ")", "recursion", "If", "return_logZ", "=", "True", "compute", "the", "logZ", "the", "normalization", "constant", ":", "\\", "[", "Z", "=", "\\", "sum_", "{", "y1", "y2", "y3", "}", "exp", ...
Hironsan/anago
python
https://github.com/Hironsan/anago/blob/66a97f91c41f9613b736892e9762dccb9c28f623/anago/layers.py#L417-L459
[ "def", "recursion", "(", "self", ",", "input_energy", ",", "mask", "=", "None", ",", "go_backwards", "=", "False", ",", "return_sequences", "=", "True", ",", "return_logZ", "=", "True", ",", "input_length", "=", "None", ")", ":", "chain_energy", "=", "self...
66a97f91c41f9613b736892e9762dccb9c28f623
train
extract_signature
Extracts a minimal signature from a given SQL query :param sql: the SQL statement :return: a string representing the signature
elasticapm/instrumentation/packages/dbapi2.py
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...
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...
[ "Extracts", "a", "minimal", "signature", "from", "a", "given", "SQL", "query", ":", "param", "sql", ":", "the", "SQL", "statement", ":", "return", ":", "a", "string", "representing", "the", "signature" ]
elastic/apm-agent-python
python
https://github.com/elastic/apm-agent-python/blob/2975663d7bd22282dc39336b2c37b37c12c7a774/elasticapm/instrumentation/packages/dbapi2.py#L151-L190
[ "def", "extract_signature", "(", "sql", ")", ":", "sql", "=", "force_text", "(", "sql", ")", "sql", "=", "sql", ".", "strip", "(", ")", "first_space", "=", "sql", ".", "find", "(", "\" \"", ")", "if", "first_space", "<", "0", ":", "return", "sql", ...
2975663d7bd22282dc39336b2c37b37c12c7a774
train
AsyncWorker._timed_queue_join
implementation of Queue.join which takes a 'timeout' argument returns True on success, False on timeout
elasticapm/contrib/async_worker.py
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: ...
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: ...
[ "implementation", "of", "Queue", ".", "join", "which", "takes", "a", "timeout", "argument" ]
elastic/apm-agent-python
python
https://github.com/elastic/apm-agent-python/blob/2975663d7bd22282dc39336b2c37b37c12c7a774/elasticapm/contrib/async_worker.py#L89-L106
[ "def", "_timed_queue_join", "(", "self", ",", "timeout", ")", ":", "deadline", "=", "time", ".", "time", "(", ")", "+", "timeout", "with", "self", ".", "_queue", ".", "all_tasks_done", ":", "while", "self", ".", "_queue", ".", "unfinished_tasks", ":", "d...
2975663d7bd22282dc39336b2c37b37c12c7a774
train
AsyncWorker.start
Starts the task thread.
elasticapm/contrib/async_worker.py
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" ...
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" ...
[ "Starts", "the", "task", "thread", "." ]
elastic/apm-agent-python
python
https://github.com/elastic/apm-agent-python/blob/2975663d7bd22282dc39336b2c37b37c12c7a774/elasticapm/contrib/async_worker.py#L108-L120
[ "def", "start", "(", "self", ")", ":", "self", ".", "_lock", ".", "acquire", "(", ")", "try", ":", "if", "not", "self", ".", "_thread", ":", "self", ".", "_thread", "=", "Thread", "(", "target", "=", "self", ".", "_target", ")", "self", ".", "_th...
2975663d7bd22282dc39336b2c37b37c12c7a774
train
AsyncWorker.stop
Stops the task thread. Synchronous!
elasticapm/contrib/async_worker.py
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 ...
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 ...
[ "Stops", "the", "task", "thread", ".", "Synchronous!" ]
elastic/apm-agent-python
python
https://github.com/elastic/apm-agent-python/blob/2975663d7bd22282dc39336b2c37b37c12c7a774/elasticapm/contrib/async_worker.py#L122-L133
[ "def", "stop", "(", "self", ",", "timeout", "=", "None", ")", ":", "self", ".", "_lock", ".", "acquire", "(", ")", "try", ":", "if", "self", ".", "_thread", ":", "self", ".", "_queue", ".", "put_nowait", "(", "self", ".", "_terminator", ")", "self"...
2975663d7bd22282dc39336b2c37b37c12c7a774
train
get_version
Get version without importing from elasticapm. This avoids any side effects from importing while installing and/or building the module :return: a string, indicating the version
setup.py
def get_version(): """ Get version without importing from elasticapm. This avoids any side effects from importing while installing and/or building the module :return: a string, indicating the version """ version_file = open(os.path.join("elasticapm", "version.py"), encoding="utf-8") for line...
def get_version(): """ Get version without importing from elasticapm. This avoids any side effects from importing while installing and/or building the module :return: a string, indicating the version """ version_file = open(os.path.join("elasticapm", "version.py"), encoding="utf-8") for line...
[ "Get", "version", "without", "importing", "from", "elasticapm", ".", "This", "avoids", "any", "side", "effects", "from", "importing", "while", "installing", "and", "/", "or", "building", "the", "module", ":", "return", ":", "a", "string", "indicating", "the", ...
elastic/apm-agent-python
python
https://github.com/elastic/apm-agent-python/blob/2975663d7bd22282dc39336b2c37b37c12c7a774/setup.py#L88-L99
[ "def", "get_version", "(", ")", ":", "version_file", "=", "open", "(", "os", ".", "path", ".", "join", "(", "\"elasticapm\"", ",", "\"version.py\"", ")", ",", "encoding", "=", "\"utf-8\"", ")", "for", "line", "in", "version_file", ":", "if", "line", ".",...
2975663d7bd22282dc39336b2c37b37c12c7a774
train
get_headers
Returns only proper HTTP headers.
elasticapm/utils/wsgi.py
def get_headers(environ): """ Returns only proper HTTP headers. """ for key, value in compat.iteritems(environ): key = str(key) if key.startswith("HTTP_") and key not in ("HTTP_CONTENT_TYPE", "HTTP_CONTENT_LENGTH"): yield key[5:].replace("_", "-").lower(), value elif ...
def get_headers(environ): """ Returns only proper HTTP headers. """ for key, value in compat.iteritems(environ): key = str(key) if key.startswith("HTTP_") and key not in ("HTTP_CONTENT_TYPE", "HTTP_CONTENT_LENGTH"): yield key[5:].replace("_", "-").lower(), value elif ...
[ "Returns", "only", "proper", "HTTP", "headers", "." ]
elastic/apm-agent-python
python
https://github.com/elastic/apm-agent-python/blob/2975663d7bd22282dc39336b2c37b37c12c7a774/elasticapm/utils/wsgi.py#L46-L55
[ "def", "get_headers", "(", "environ", ")", ":", "for", "key", ",", "value", "in", "compat", ".", "iteritems", "(", "environ", ")", ":", "key", "=", "str", "(", "key", ")", "if", "key", ".", "startswith", "(", "\"HTTP_\"", ")", "and", "key", "not", ...
2975663d7bd22282dc39336b2c37b37c12c7a774
train
get_current_url
A handy helper function that recreates the full URL for the current request or parts of it. Here an example: >>> from werkzeug import create_environ >>> env = create_environ("/?param=foo", "http://localhost/script") >>> get_current_url(env) 'http://localhost/script/?param=foo' >>> get_current_...
elasticapm/utils/wsgi.py
def get_current_url(environ, root_only=False, strip_querystring=False, host_only=False): """A handy helper function that recreates the full URL for the current request or parts of it. Here an example: >>> from werkzeug import create_environ >>> env = create_environ("/?param=foo", "http://localhost/scr...
def get_current_url(environ, root_only=False, strip_querystring=False, host_only=False): """A handy helper function that recreates the full URL for the current request or parts of it. Here an example: >>> from werkzeug import create_environ >>> env = create_environ("/?param=foo", "http://localhost/scr...
[ "A", "handy", "helper", "function", "that", "recreates", "the", "full", "URL", "for", "the", "current", "request", "or", "parts", "of", "it", ".", "Here", "an", "example", ":" ]
elastic/apm-agent-python
python
https://github.com/elastic/apm-agent-python/blob/2975663d7bd22282dc39336b2c37b37c12c7a774/elasticapm/utils/wsgi.py#L91-L124
[ "def", "get_current_url", "(", "environ", ",", "root_only", "=", "False", ",", "strip_querystring", "=", "False", ",", "host_only", "=", "False", ")", ":", "tmp", "=", "[", "environ", "[", "\"wsgi.url_scheme\"", "]", ",", "\"://\"", ",", "get_host", "(", "...
2975663d7bd22282dc39336b2c37b37c12c7a774
train
Transport._flush
Flush the queue. This method should only be called from the event processing queue :param sync: if true, flushes the queue synchronously in the current thread :return: None
elasticapm/transport/base.py
def _flush(self, buffer): """ Flush the queue. This method should only be called from the event processing queue :param sync: if true, flushes the queue synchronously in the current thread :return: None """ if not self.state.should_try(): logger.error("droppin...
def _flush(self, buffer): """ Flush the queue. This method should only be called from the event processing queue :param sync: if true, flushes the queue synchronously in the current thread :return: None """ if not self.state.should_try(): logger.error("droppin...
[ "Flush", "the", "queue", ".", "This", "method", "should", "only", "be", "called", "from", "the", "event", "processing", "queue", ":", "param", "sync", ":", "if", "true", "flushes", "the", "queue", "synchronously", "in", "the", "current", "thread", ":", "re...
elastic/apm-agent-python
python
https://github.com/elastic/apm-agent-python/blob/2975663d7bd22282dc39336b2c37b37c12c7a774/elasticapm/transport/base.py#L193-L211
[ "def", "_flush", "(", "self", ",", "buffer", ")", ":", "if", "not", "self", ".", "state", ".", "should_try", "(", ")", ":", "logger", ".", "error", "(", "\"dropping flushed data due to transport failure back-off\"", ")", "else", ":", "fileobj", "=", "buffer", ...
2975663d7bd22282dc39336b2c37b37c12c7a774
train
Transport.close
Cleans up resources and closes connection :return:
elasticapm/transport/base.py
def close(self): """ Cleans up resources and closes connection :return: """ if self._closed: return self._closed = True self.queue("close", None) if not self._flushed.wait(timeout=self._max_flush_time): raise ValueError("close timed...
def close(self): """ Cleans up resources and closes connection :return: """ if self._closed: return self._closed = True self.queue("close", None) if not self._flushed.wait(timeout=self._max_flush_time): raise ValueError("close timed...
[ "Cleans", "up", "resources", "and", "closes", "connection", ":", "return", ":" ]
elastic/apm-agent-python
python
https://github.com/elastic/apm-agent-python/blob/2975663d7bd22282dc39336b2c37b37c12c7a774/elasticapm/transport/base.py#L231-L241
[ "def", "close", "(", "self", ")", ":", "if", "self", ".", "_closed", ":", "return", "self", ".", "_closed", "=", "True", "self", ".", "queue", "(", "\"close\"", ",", "None", ")", "if", "not", "self", ".", "_flushed", ".", "wait", "(", "timeout", "=...
2975663d7bd22282dc39336b2c37b37c12c7a774
train
Transport.flush
Trigger a flush of the queue. Note: this method will only return once the queue is empty. This means it can block indefinitely if more events are produced in other threads than can be consumed.
elasticapm/transport/base.py
def flush(self): """ Trigger a flush of the queue. Note: this method will only return once the queue is empty. This means it can block indefinitely if more events are produced in other threads than can be consumed. """ self.queue(None, None, flush=True) if not sel...
def flush(self): """ Trigger a flush of the queue. Note: this method will only return once the queue is empty. This means it can block indefinitely if more events are produced in other threads than can be consumed. """ self.queue(None, None, flush=True) if not sel...
[ "Trigger", "a", "flush", "of", "the", "queue", ".", "Note", ":", "this", "method", "will", "only", "return", "once", "the", "queue", "is", "empty", ".", "This", "means", "it", "can", "block", "indefinitely", "if", "more", "events", "are", "produced", "in...
elastic/apm-agent-python
python
https://github.com/elastic/apm-agent-python/blob/2975663d7bd22282dc39336b2c37b37c12c7a774/elasticapm/transport/base.py#L243-L251
[ "def", "flush", "(", "self", ")", ":", "self", ".", "queue", "(", "None", ",", "None", ",", "flush", "=", "True", ")", "if", "not", "self", ".", "_flushed", ".", "wait", "(", "timeout", "=", "self", ".", "_max_flush_time", ")", ":", "raise", "Value...
2975663d7bd22282dc39336b2c37b37c12c7a774
train
Transport.handle_transport_fail
Failure handler called by the transport on send failure
elasticapm/transport/base.py
def handle_transport_fail(self, exception=None, **kwargs): """ Failure handler called by the transport on send failure """ message = str(exception) logger.error("Failed to submit message: %r", message, exc_info=getattr(exception, "print_trace", True)) self.state.set_fail(...
def handle_transport_fail(self, exception=None, **kwargs): """ Failure handler called by the transport on send failure """ message = str(exception) logger.error("Failed to submit message: %r", message, exc_info=getattr(exception, "print_trace", True)) self.state.set_fail(...
[ "Failure", "handler", "called", "by", "the", "transport", "on", "send", "failure" ]
elastic/apm-agent-python
python
https://github.com/elastic/apm-agent-python/blob/2975663d7bd22282dc39336b2c37b37c12c7a774/elasticapm/transport/base.py#L259-L265
[ "def", "handle_transport_fail", "(", "self", ",", "exception", "=", "None", ",", "*", "*", "kwargs", ")", ":", "message", "=", "str", "(", "exception", ")", "logger", ".", "error", "(", "\"Failed to submit message: %r\"", ",", "message", ",", "exc_info", "="...
2975663d7bd22282dc39336b2c37b37c12c7a774
train
ChilledQueue.put
Put an item into the queue. If optional args 'block' is true and 'timeout' is None (the default), block if necessary until a free slot is available. If 'timeout' is a non-negative number, it blocks at most 'timeout' seconds and raises the Full exception if no free slot was available wit...
elasticapm/transport/base.py
def put(self, item, block=True, timeout=None, chill=True): """Put an item into the queue. If optional args 'block' is true and 'timeout' is None (the default), block if necessary until a free slot is available. If 'timeout' is a non-negative number, it blocks at most 'timeout' seconds a...
def put(self, item, block=True, timeout=None, chill=True): """Put an item into the queue. If optional args 'block' is true and 'timeout' is None (the default), block if necessary until a free slot is available. If 'timeout' is a non-negative number, it blocks at most 'timeout' seconds a...
[ "Put", "an", "item", "into", "the", "queue", "." ]
elastic/apm-agent-python
python
https://github.com/elastic/apm-agent-python/blob/2975663d7bd22282dc39336b2c37b37c12c7a774/elasticapm/transport/base.py#L343-L379
[ "def", "put", "(", "self", ",", "item", ",", "block", "=", "True", ",", "timeout", "=", "None", ",", "chill", "=", "True", ")", ":", "with", "self", ".", "not_full", ":", "if", "self", ".", "maxsize", ">", "0", ":", "if", "not", "block", ":", "...
2975663d7bd22282dc39336b2c37b37c12c7a774
train
request_host
Return request-host, as defined by RFC 2965. Variation from RFC: returned value is lowercased, for convenient comparison.
elasticapm/instrumentation/packages/urllib.py
def request_host(request): """Return request-host, as defined by RFC 2965. Variation from RFC: returned value is lowercased, for convenient comparison. """ url = request.get_full_url() parse_result = compat.urlparse.urlparse(url) scheme, host, port = parse_result.scheme, parse_result.hostn...
def request_host(request): """Return request-host, as defined by RFC 2965. Variation from RFC: returned value is lowercased, for convenient comparison. """ url = request.get_full_url() parse_result = compat.urlparse.urlparse(url) scheme, host, port = parse_result.scheme, parse_result.hostn...
[ "Return", "request", "-", "host", "as", "defined", "by", "RFC", "2965", "." ]
elastic/apm-agent-python
python
https://github.com/elastic/apm-agent-python/blob/2975663d7bd22282dc39336b2c37b37c12c7a774/elasticapm/instrumentation/packages/urllib.py#L40-L59
[ "def", "request_host", "(", "request", ")", ":", "url", "=", "request", ".", "get_full_url", "(", ")", "parse_result", "=", "compat", ".", "urlparse", ".", "urlparse", "(", "url", ")", "scheme", ",", "host", ",", "port", "=", "parse_result", ".", "scheme...
2975663d7bd22282dc39336b2c37b37c12c7a774
train
get_client
Get an ElasticAPM client. :param client: :return: :rtype: elasticapm.base.Client
elasticapm/contrib/django/client.py
def get_client(client=None): """ Get an ElasticAPM client. :param client: :return: :rtype: elasticapm.base.Client """ global _client tmp_client = client is not None if not tmp_client: config = getattr(django_settings, "ELASTIC_APM", {}) client = config.get("CLIENT",...
def get_client(client=None): """ Get an ElasticAPM client. :param client: :return: :rtype: elasticapm.base.Client """ global _client tmp_client = client is not None if not tmp_client: config = getattr(django_settings, "ELASTIC_APM", {}) client = config.get("CLIENT",...
[ "Get", "an", "ElasticAPM", "client", "." ]
elastic/apm-agent-python
python
https://github.com/elastic/apm-agent-python/blob/2975663d7bd22282dc39336b2c37b37c12c7a774/elasticapm/contrib/django/client.py#L56-L77
[ "def", "get_client", "(", "client", "=", "None", ")", ":", "global", "_client", "tmp_client", "=", "client", "is", "not", "None", "if", "not", "tmp_client", ":", "config", "=", "getattr", "(", "django_settings", ",", "\"ELASTIC_APM\"", ",", "{", "}", ")", ...
2975663d7bd22282dc39336b2c37b37c12c7a774
train
_get_installed_apps_paths
Generate a list of modules in settings.INSTALLED_APPS.
elasticapm/contrib/django/client.py
def _get_installed_apps_paths(): """ Generate a list of modules in settings.INSTALLED_APPS. """ out = set() for app in django_settings.INSTALLED_APPS: out.add(app) return out
def _get_installed_apps_paths(): """ Generate a list of modules in settings.INSTALLED_APPS. """ out = set() for app in django_settings.INSTALLED_APPS: out.add(app) return out
[ "Generate", "a", "list", "of", "modules", "in", "settings", ".", "INSTALLED_APPS", "." ]
elastic/apm-agent-python
python
https://github.com/elastic/apm-agent-python/blob/2975663d7bd22282dc39336b2c37b37c12c7a774/elasticapm/contrib/django/client.py#L298-L305
[ "def", "_get_installed_apps_paths", "(", ")", ":", "out", "=", "set", "(", ")", "for", "app", "in", "django_settings", ".", "INSTALLED_APPS", ":", "out", ".", "add", "(", "app", ")", "return", "out" ]
2975663d7bd22282dc39336b2c37b37c12c7a774
train
DjangoClient._get_stack_info_for_trace
If the stacktrace originates within the elasticapm module, it will skip frames until some other module comes up.
elasticapm/contrib/django/client.py
def _get_stack_info_for_trace( self, frames, library_frame_context_lines=None, in_app_frame_context_lines=None, with_locals=True, locals_processor_func=None, ): """If the stacktrace originates within the elasticapm module, it will skip frames until som...
def _get_stack_info_for_trace( self, frames, library_frame_context_lines=None, in_app_frame_context_lines=None, with_locals=True, locals_processor_func=None, ): """If the stacktrace originates within the elasticapm module, it will skip frames until som...
[ "If", "the", "stacktrace", "originates", "within", "the", "elasticapm", "module", "it", "will", "skip", "frames", "until", "some", "other", "module", "comes", "up", "." ]
elastic/apm-agent-python
python
https://github.com/elastic/apm-agent-python/blob/2975663d7bd22282dc39336b2c37b37c12c7a774/elasticapm/contrib/django/client.py#L190-L210
[ "def", "_get_stack_info_for_trace", "(", "self", ",", "frames", ",", "library_frame_context_lines", "=", "None", ",", "in_app_frame_context_lines", "=", "None", ",", "with_locals", "=", "True", ",", "locals_processor_func", "=", "None", ",", ")", ":", "return", "l...
2975663d7bd22282dc39336b2c37b37c12c7a774
train
DjangoClient.send
Serializes and signs ``data`` and passes the payload off to ``send_remote`` If ``server`` was passed into the constructor, this will serialize the data and pipe it to the server using ``send_remote()``.
elasticapm/contrib/django/client.py
def send(self, url, **kwargs): """ Serializes and signs ``data`` and passes the payload off to ``send_remote`` If ``server`` was passed into the constructor, this will serialize the data and pipe it to the server using ``send_remote()``. """ if self.config.server_url: ...
def send(self, url, **kwargs): """ Serializes and signs ``data`` and passes the payload off to ``send_remote`` If ``server`` was passed into the constructor, this will serialize the data and pipe it to the server using ``send_remote()``. """ if self.config.server_url: ...
[ "Serializes", "and", "signs", "data", "and", "passes", "the", "payload", "off", "to", "send_remote" ]
elastic/apm-agent-python
python
https://github.com/elastic/apm-agent-python/blob/2975663d7bd22282dc39336b2c37b37c12c7a774/elasticapm/contrib/django/client.py#L212-L223
[ "def", "send", "(", "self", ",", "url", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "config", ".", "server_url", ":", "return", "super", "(", "DjangoClient", ",", "self", ")", ".", "send", "(", "url", ",", "*", "*", "kwargs", ")", "else...
2975663d7bd22282dc39336b2c37b37c12c7a774
train
deprecated
This is a decorator which can be used to mark functions as deprecated. It will result in a warning being emitted when the function is used.
elasticapm/utils/deprecation.py
def deprecated(alternative=None): """This is a decorator which can be used to mark functions as deprecated. It will result in a warning being emitted when the function is used.""" def real_decorator(func): @functools.wraps(func) def new_func(*args, **kwargs): msg = "Call to ...
def deprecated(alternative=None): """This is a decorator which can be used to mark functions as deprecated. It will result in a warning being emitted when the function is used.""" def real_decorator(func): @functools.wraps(func) def new_func(*args, **kwargs): msg = "Call to ...
[ "This", "is", "a", "decorator", "which", "can", "be", "used", "to", "mark", "functions", "as", "deprecated", ".", "It", "will", "result", "in", "a", "warning", "being", "emitted", "when", "the", "function", "is", "used", "." ]
elastic/apm-agent-python
python
https://github.com/elastic/apm-agent-python/blob/2975663d7bd22282dc39336b2c37b37c12c7a774/elasticapm/utils/deprecation.py#L39-L60
[ "def", "deprecated", "(", "alternative", "=", "None", ")", ":", "def", "real_decorator", "(", "func", ")", ":", "@", "functools", ".", "wraps", "(", "func", ")", "def", "new_func", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "msg", "=", "\...
2975663d7bd22282dc39336b2c37b37c12c7a774
train
MetricsRegistry.register
Register a new metric set :param class_path: a string with the import path of the metricset class
elasticapm/metrics/base_metrics.py
def register(self, class_path): """ Register a new metric set :param class_path: a string with the import path of the metricset class """ if class_path in self._metricsets: return else: try: class_obj = import_string(class_path) ...
def register(self, class_path): """ Register a new metric set :param class_path: a string with the import path of the metricset class """ if class_path in self._metricsets: return else: try: class_obj = import_string(class_path) ...
[ "Register", "a", "new", "metric", "set", ":", "param", "class_path", ":", "a", "string", "with", "the", "import", "path", "of", "the", "metricset", "class" ]
elastic/apm-agent-python
python
https://github.com/elastic/apm-agent-python/blob/2975663d7bd22282dc39336b2c37b37c12c7a774/elasticapm/metrics/base_metrics.py#L66-L78
[ "def", "register", "(", "self", ",", "class_path", ")", ":", "if", "class_path", "in", "self", ".", "_metricsets", ":", "return", "else", ":", "try", ":", "class_obj", "=", "import_string", "(", "class_path", ")", "self", ".", "_metricsets", "[", "class_pa...
2975663d7bd22282dc39336b2c37b37c12c7a774
train
MetricsRegistry.collect
Collect metrics from all registered metric sets :return:
elasticapm/metrics/base_metrics.py
def collect(self): """ Collect metrics from all registered metric sets :return: """ logger.debug("Collecting metrics") for name, metricset in compat.iteritems(self._metricsets): data = metricset.collect() if data: self._queue_func(...
def collect(self): """ Collect metrics from all registered metric sets :return: """ logger.debug("Collecting metrics") for name, metricset in compat.iteritems(self._metricsets): data = metricset.collect() if data: self._queue_func(...
[ "Collect", "metrics", "from", "all", "registered", "metric", "sets", ":", "return", ":" ]
elastic/apm-agent-python
python
https://github.com/elastic/apm-agent-python/blob/2975663d7bd22282dc39336b2c37b37c12c7a774/elasticapm/metrics/base_metrics.py#L80-L90
[ "def", "collect", "(", "self", ")", ":", "logger", ".", "debug", "(", "\"Collecting metrics\"", ")", "for", "name", ",", "metricset", "in", "compat", ".", "iteritems", "(", "self", ".", "_metricsets", ")", ":", "data", "=", "metricset", ".", "collect", "...
2975663d7bd22282dc39336b2c37b37c12c7a774