code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
diff_violations = self._diff_violations().get(src_path) if diff_violations is None: return [] return sorted(diff_violations.lines)
def violation_lines(self, src_path)
Return a list of lines in violation (integers) in `src_path` that were changed. If we have no coverage information for `src_path`, returns an empty list.
5.222091
4.331433
1.205626
return sum([len(summary.measured_lines) for summary in self._diff_violations().values()])
def total_num_lines(self)
Return the total number of lines in the diff for which we have coverage info.
27.103415
14.624793
1.853251
return sum( len(summary.lines) for summary in self._diff_violations().values() )
def total_num_violations(self)
Returns the total number of lines in the diff that are in violation.
14.623086
7.943929
1.840788
total_lines = self.total_num_lines() if total_lines > 0: num_covered = total_lines - self.total_num_violations() return int(float(num_covered) / total_lines * 100) else: return 100
def total_percent_covered(self)
Returns the float percent of lines in the diff that are covered. (only counting lines for which we have coverage info).
3.150877
2.810769
1.121002
if not self._diff_violations_dict: self._diff_violations_dict = { src_path: DiffViolations( self._violations.violations(src_path), self._violations.measured_lines(src_path), self._diff.lines_changed(...
def _diff_violations(self)
Returns a dictionary of the form: { SRC_PATH: DiffViolations(SRC_PATH) } where `SRC_PATH` is the path to the source file. To make this efficient, we cache and reuse the result.
3.717401
3.256019
1.141701
if self.TEMPLATE_NAME is not None: template = TEMPLATE_ENV.get_template(self.TEMPLATE_NAME) report = template.render(self._context()) if isinstance(report, six.string_types): report = report.encode('utf-8') output_file.write(report)
def generate_report(self, output_file)
See base class. output_file must be a file handler that takes in bytes!
3.072335
2.848299
1.078656
if self.CSS_TEMPLATE_NAME is not None: template = TEMPLATE_ENV.get_template(self.CSS_TEMPLATE_NAME) style = template.render(self._context()) if isinstance(style, six.string_types): style = style.encode('utf-8') output_file.write(style)
def generate_css(self, output_file)
Generate an external style sheet file. output_file must be a file handler that takes in bytes!
3.461627
3.315305
1.044135
# Calculate the information to pass to the template src_stats = { src: self._src_path_stats(src) for src in self.src_paths() } # Include snippet style info if we're displaying # source code snippets if self.INCLUDE_SNIPPETS: snippet_styl...
def _context(self)
Return the context to pass to the template. The context is a dict of the form: { 'css_url': CSS_URL, 'report_name': REPORT_NAME, 'diff_name': DIFF_NAME, 'src_stats': {SRC_PATH: { 'percent_covered': PERCENT_COVERED, ...
4.144144
2.453046
1.689387
combine_template = "{0}-{1}" combined_list = [] # Add a terminating value of `None` to list line_numbers.append(None) start = line_numbers[0] end = None for line_number in line_numbers[1:]: # If the current number is adjacent to the previous...
def combine_adjacent_lines(line_numbers)
Given a sorted collection of line numbers this will turn them to strings and combine adjacent values [1, 2, 5, 6, 100] -> ["1-2", "5-6", "100"]
3.170775
3.110315
1.019438
# Find violation lines violation_lines = self.violation_lines(src_path) violations = sorted(self._diff_violations()[src_path].violations) # Load source snippets (if the report will display them) # If we cannot load the file, then fail gracefully if self.INCLUDE...
def _src_path_stats(self, src_path)
Return a dict of statistics for the source file at `src_path`.
6.085907
5.994686
1.015217
parser = argparse.ArgumentParser(description=DESCRIPTION) parser.add_argument( 'coverage_xml', type=str, help=COVERAGE_XML_HELP, nargs='+' ) parser.add_argument( '--html-report', metavar='FILENAME', type=str, default=None, he...
def parse_coverage_args(argv)
Parse command line arguments, returning a dict of valid options: { 'coverage_xml': COVERAGE_XML, 'html_report': None | HTML_REPORT, 'external_css_file': None | CSS_FILE, } where `COVERAGE_XML`, `HTML_REPORT`, and `CSS_FILE` are paths. The path strings m...
1.767292
1.650609
1.070691
diff = GitDiffReporter( compare_branch, git_diff=GitDiffTool(), ignore_staged=ignore_staged, ignore_unstaged=ignore_unstaged, exclude=exclude) xml_roots = [cElementTree.parse(xml_root) for xml_root in coverage_xml] coverage = XmlCoverageReporter(xml_roots, src_roots) # Build a rep...
def generate_coverage_report(coverage_xml, compare_branch, html_report=None, css_file=None, ignore_staged=False, ignore_unstaged=False, exclude=None, src_roots=None)
Generate the diff coverage report, using kwargs from `parse_args()`.
2.702107
2.743314
0.984979
logging.basicConfig(format='%(message)s') argv = argv or sys.argv arg_dict = parse_coverage_args(argv[1:]) GitPathTool.set_cwd(directory) fail_under = arg_dict.get('fail_under') percent_covered = generate_coverage_report( arg_dict['coverage_xml'], arg_dict['compare_branch']...
def main(argv=None, directory=None)
Main entry point for the tool, used by setup.py Returns a value that can be passed into exit() specifying the exit code. 1 is an error 0 is successful run
3.790645
3.788648
1.000527
stdout_pipe = subprocess.PIPE process = subprocess.Popen( command, stdout=stdout_pipe, stderr=stdout_pipe ) try: stdout, stderr = process.communicate() except OSError: sys.stderr.write(" ".join( [cmd.decode(sys.getfilesystemencoding()) ...
def execute(command, exit_codes=[0])
Execute provided command returning the stdout Args: command (list[str]): list of tokens to execute as your command. exit_codes (list[int]): exit codes which do not indicate error. subprocess_mod (module): Defaults to pythons subprocess module but you can optionally pass in another. T...
3.048021
3.182713
0.95768
process = subprocess.Popen( command, stdout=subprocess.PIPE, stderr=subprocess.PIPE ) process.communicate() exit_code = process.returncode return exit_code
def run_command_for_code(command)
Returns command's exit code.
2.286844
2.143485
1.066881
if isinstance(text, six.binary_type): return text.decode(sys.getfilesystemencoding(), 'replace') else: return text
def _ensure_unicode(text)
Ensures the text passed in becomes unicode Args: text (str|unicode) Returns: unicode
2.530595
3.265939
0.774844
violations_dict = defaultdict(list) for report in reports: xml_document = cElementTree.fromstring("".join(report)) files = xml_document.findall(".//file") for file_tree in files: for error in file_tree.findall('error'): lin...
def parse_reports(self, reports)
Args: reports: list[str] - output from the report Return: A dict[Str:Violation] Violation is a simple named tuple Defined above
3.641391
3.534553
1.030227
violations_dict = defaultdict(list) for report in reports: xml_document = cElementTree.fromstring("".join(report)) bugs = xml_document.findall(".//BugInstance") for bug in bugs: category = bug.get('category') short_message = bu...
def parse_reports(self, reports)
Args: reports: list[str] - output from the report Return: A dict[Str:Violation] Violation is a simple named tuple Defined above
3.053304
2.966969
1.029099
formatter = HtmlFormatter() formatter.style.highlight_color = cls.VIOLATION_COLOR return formatter.get_style_defs()
def style_defs(cls)
Return the CSS style definitions required by the formatted snippet.
8.907605
8.643761
1.030524
formatter = HtmlFormatter( cssclass=self.DIV_CSS_CLASS, linenos=True, linenostart=self._start_line, hl_lines=self._shift_lines( self._violation_lines, self._start_line ), lineanchors=self._src_filena...
def html(self)
Return an HTML representation of the snippet.
6.384935
5.990792
1.065791
num_lines = len(self.text().split('\n')) end_line = self._start_line + num_lines - 1 return (self._start_line, end_line)
def line_range(self)
Return a tuple of the form `(start_line, end_line)` indicating the start and end line number of the snippet.
3.503406
2.920176
1.199724
snippet_list = cls.load_snippets(src_path, violation_lines) return [snippet.html() for snippet in snippet_list]
def load_snippets_html(cls, src_path, violation_lines)
Load snippets from the file at `src_path` and format them as HTML. See `load_snippets()` for details.
3.663021
3.247129
1.12808
# Load the contents of the file with openpy(GitPathTool.relative_path(src_path)) as src_file: contents = src_file.read() # Convert the source file to unicode (Python < 3) if isinstance(contents, six.binary_type): contents = contents.decode('utf-8', 'repl...
def load_snippets(cls, src_path, violation_lines)
Load snippets from the file at `src_path` to show violations on lines in the list `violation_lines` (list of line numbers, starting at index 0). The file at `src_path` should be a text file (not binary). Returns a list of `Snippet` instances. Raises an `IOError` if the file co...
3.722293
3.886051
0.95786
# Parse the source into tokens try: lexer = guess_lexer_for_filename(src_filename, src_contents) except ClassNotFound: lexer = TextLexer() # Ensure that we don't strip newlines from # the source file when lexing. lexer.stripnl = False ...
def _parse_src(cls, src_contents, src_filename)
Return a stream of `(token_type, value)` tuples parsed from `src_contents` (str) Uses `src_filename` to guess the type of file so it can highlight syntax correctly.
4.343834
3.95887
1.097241
# Create a map from ranges (start/end tuples) to tokens token_map = {rng: [] for rng in range_list} # Keep track of the current line number; we will # increment this as we encounter newlines in token values line_num = 1 for ttype, val in token_stream: ...
def _group_tokens(cls, token_stream, range_list)
Group tokens into snippet ranges. `token_stream` is a generator that produces `(token_type, value)` tuples, `range_list` is a list of `(start, end)` tuples representing the (inclusive) range of line numbers for each snippet. Assumes that `range_list` is an ascending order by s...
3.352681
3.122912
1.073575
current_range = (None, None) lines_since_last_violation = 0 snippet_ranges = [] for line_num in range(1, num_src_lines + 1): # If we have not yet started a snippet, # check if we can (is this line a violation?) if current_range[0] is None: ...
def _snippet_ranges(cls, num_src_lines, violation_lines)
Given the number of source file lines and list of violation line numbers, return a list of snippet ranges of the form `(start_line, end_line)`. Each snippet contains a few extra lines of context before/after the first/last violation. Nearby violations are grouped within the sam...
2.604485
2.491807
1.045219
contents = [] for file_handle in report_files: # Convert to unicode, replacing unreadable chars contents.append( file_handle.read().decode( 'utf-8', 'replace' ) ) return contents
def _load_reports(self, report_files)
Args: report_files: list[file] reports to read in
5.56101
5.387481
1.03221
if not any(src_path.endswith(ext) for ext in self.driver.supported_extensions): return [] if src_path not in self.violations_dict: if self.reports: self.violations_dict = self.driver.parse_reports(self.reports) else: if self.dr...
def violations(self, src_path)
Return a list of Violations recorded in `src_path`.
2.992333
2.901613
1.031265
violations_dict = defaultdict(list) for report in reports: if self.expression.flags & re.MULTILINE: matches = (match for match in re.finditer(self.expression, report)) else: matches = (self.expression.match(line)...
def parse_reports(self, reports)
Args: reports: list[str] - output from the report Return: A dict[Str:Violation] Violation is a simple named tuple Defined above
3.147907
3.035537
1.037018
init_py = open('{0}.py'.format(module)).read() return re.search("__version__ = ['\"]([^'\"]+)['\"]", init_py).group(1)
def get_version(module)
Return package version as listed in `__version__`.
2.673784
2.31198
1.156491
if dotenv is None: frame_filename = sys._getframe().f_back.f_code.co_filename dotenv = os.path.join(os.path.dirname(frame_filename), '.env') if os.path.isdir(dotenv) and os.path.isfile(os.path.join(dotenv, '.env')): dotenv = os.path.join(dotenv, '.env') if os.path.exists(doten...
def read_dotenv(dotenv=None, override=False)
Read a .env file into os.environ. If not given a path to a dotenv path, does filthy magic stack backtracking to find manage.py and then find the dotenv. If tests rely on .env files, setting the overwrite flag to True is a safe way to ensure tests run consistently across all environments. :param o...
2.010646
2.187109
0.919317
self.transport = transport self.username = auth.username self.address = address self.port = port
def configure(self, transport, auth, address, port)
Connect paramiko transport :type auth: :py:class`margaritashotgun.auth.AuthMethods` :param auth: authentication object :type address: str :param address: remote server ip or hostname :type port: int :param port: remote server port :type hostkey: :py:class:`parami...
2.959331
3.399721
0.870463
self.local_port = local_port self.remote_address = remote_address self.remote_port = remote_port logger.debug(("Starting ssh tunnel {0}:{1}:{2} for " "{3}@{4}".format(local_port, remote_address, remote_port, self.user...
def start(self, local_port, remote_address, remote_port)
Start ssh tunnel type: local_port: int param: local_port: local tunnel endpoint ip binding type: remote_address: str param: remote_address: Remote tunnel endpoing ip binding type: remote_port: int param: remote_port: Remote tunnel endpoint port binding
2.729621
2.643497
1.032579
if self.local_port is not None: logger.debug(("Stopping ssh tunnel {0}:{1}:{2} for " "{3}@{4}".format(self.local_port, self.remote_address, self.remote_port, ...
def cleanup(self)
Cleanup resources used during execution
3.417866
3.425733
0.997704
if format_string is None: format_string = "%(asctime)s - %(name)s - %(levelname)s - %(message)s" time_format = "%Y-%m-%dT%H:%M:%S" logger = logging.getLogger(name) logger.setLevel(level) handler = logging.StreamHandler() handler.setLevel(level) formatter = logging.Formatter(fo...
def set_stream_logger(name='margaritashotgun', level=logging.INFO, format_string=None)
Add a stream handler for the provided name and level to the logging module. >>> import margaritashotgun >>> margaritashotgun.set_stream_logger('marsho', logging.DEBUG) :type name: string :param name: Log name :type level: int :param level: Logging level :type format_string: str ...
1.515395
1.587839
0.954376
if port is None: self.remote_port = 22 else: self.remote_port = int(port) auth = Auth(username=username, password=password, key=key) if jump_host is not None: jump_auth = Auth(username=jump_host['username'], passw...
def connect(self, username, password, key, address, port, jump_host)
Connect ssh tunnel and shell executor to remote host :type username: str :param username: username for authentication :type password: str :param password: password for authentication, may be used to unlock rsa key :type key: str :param key: path to rsa key for authentica...
2.46589
2.707025
0.910922
self.tunnel.start(local_port, remote_address, remote_port) self.tunnel_port = local_port
def start_tunnel(self, local_port, remote_address, remote_port)
Start ssh forward tunnel :type local_port: int :param local_port: local port binding for ssh tunnel :type remote_address: str :param remote_address: remote tunnel endpoint bind address :type remote_port: int :param remote_port: remote tunnel endpoint bind port
2.974425
3.461511
0.859285
result = self.shell.execute(self.commands.mem_size.value) stdout = self.shell.decode(result['stdout']) stderr = self.shell.decode(result['stderr']) return int(stdout)
def mem_size(self)
Returns the memory size in bytes of the remote host
5.037837
4.417768
1.140358
result = self.shell.execute(self.commands.kernel_version.value) stdout = self.shell.decode(result['stdout']) stderr = self.shell.decode(result['stderr']) return stdout
def kernel_version(self)
Returns the kernel kernel version of the remote host
4.770094
4.149145
1.149657
tries = 0 pattern = self.commands.lime_pattern.value.format(listen_address, listen_port) lime_loaded = False while tries < max_tries and lime_loaded is False: lime_loaded = self.check_for_lime(pattern) ...
def wait_for_lime(self, listen_port, listen_address="0.0.0.0", max_tries=20, wait=1)
Wait for lime to load unless max_retries is exceeded :type listen_port: int :param listen_port: port LiME is listening for connections on :type listen_address: str :param listen_address: address LiME is listening for connections on :type max_tries: int :param max_tries: ...
3.716432
3.973773
0.93524
check = self.commands.lime_check.value lime_loaded = False result = self.shell.execute(check) stdout = self.shell.decode(result['stdout']) connections = self.net_parser.parse(stdout) for conn in connections: local_addr, remote_addr = conn ...
def check_for_lime(self, pattern)
Check to see if LiME has loaded on the remote system :type pattern: str :param pattern: pattern to check output against :type listen_port: int :param listen_port: port LiME is listening for connections on
5.754609
6.118891
0.940466
if local_path is None: raise FileNotFoundFoundError(local_path) self.shell.upload_file(local_path, remote_path)
def upload_module(self, local_path=None, remote_path="/tmp/lime.ko")
Upload LiME kernel module to remote host :type local_path: str :param local_path: local path to lime kernel module :type remote_path: str :param remote_path: remote path to upload lime kernel module
5.257835
7.334074
0.716905
load_command = self.commands.load_lime.value.format(remote_path, listen_port, dump_format) self.shell.execute_async(load_command)
def load_lime(self, remote_path, listen_port, dump_format='lime')
Load LiME kernel module from remote filesystem :type remote_path: str :param remote_path: path to LiME kernel module on remote host :type listen_port: int :param listen_port: port LiME uses to listen to remote connections :type dump_format: str :param dump_format: LiME m...
4.324305
5.800249
0.745538
try: self.unload_lime() except AttributeError as ex: pass self.tunnel.cleanup() self.shell.cleanup()
def cleanup(self)
Release resources used by supporting classes
11.937627
11.18446
1.067341
try: self.target_address = address sock = None if jump_host is not None: self.jump_host_ssh = paramiko.SSHClient() self.jump_host_ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) self.connect_with_auth(self.ju...
def connect(self, auth, address, port, jump_host, jump_auth)
Creates an ssh session to a remote host :type auth: :py:class:`margaritashotgun.auth.AuthMethods` :param auth: Authentication object :type address: str :param address: remote server address :type port: int :param port: remote server port
2.369913
2.418875
0.979758
ssh.connect(username=username, password=password, hostname=address, port=port, sock=sock, timeout=timeout)
def connect_with_password(self, ssh, username, password, address, port, sock, timeout=20)
Create an ssh session to a remote host with a username and password :type username: str :param username: username used for ssh authentication :type password: str :param password: password used for ssh authentication :type address: str :param address: remote server addres...
2.300349
2.94755
0.780427
ssh.connect(hostname=address, port=port, username=username, pkey=key, sock=sock, timeout=timeout)
def connect_with_key(self, ssh, username, key, address, port, sock, timeout=20)
Create an ssh session to a remote host with a username and rsa key :type username: str :param username: username used for ssh authentication :type key: :py:class:`paramiko.key.RSAKey` :param key: paramiko rsa key used for ssh authentication :type address: str :param addr...
2.204936
2.991531
0.737059
try: if self.ssh.get_transport() is not None: logger.debug('{0}: executing "{1}"'.format(self.target_address, command)) stdin, stdout, stderr = self.ssh.exec_command(command) return di...
def execute(self, command)
Executes command on remote hosts :type command: str :param command: command to be run on remote host
3.218577
3.294606
0.976923
try: logger.debug(('{0}: execute async "{1}"' 'with callback {2}'.format(self.target_address, command, callback))) future = self.executor.submit(se...
def execute_async(self, command, callback=None)
Executes command on remote hosts without blocking :type command: str :param command: command to be run on remote host :type callback: function :param callback: function to call when execution completes
3.688943
3.879975
0.950765
data = stream.read().decode(encoding).strip("\n") if data != "": logger.debug(('{0}: decoded "{1}" with encoding ' '{2}'.format(self.target_address, data, encoding))) return data
def decode(self, stream, encoding='utf-8')
Convert paramiko stream into a string :type stream: :param stream: stream to convert :type encoding: str :param encoding: stream encoding
6.872019
7.105217
0.967179
logger.debug("{0}: uploading {1} to {0}:{2}".format(self.target_address, local_path, remote_path)) try: sftp = paramiko.SFTPClient.from_transport(self.transport())...
def upload_file(self, local_path, remote_path)
Upload a file from the local filesystem to the remote host :type local_path: str :param local_path: path of local file to upload :type remote_path: str :param remote_path: destination path of upload on remote host
3.651904
3.940446
0.926774
for future in self.futures: future.cancel() self.executor.shutdown(wait=10) if self.ssh.get_transport() != None: self.ssh.close()
def cleanup(self)
Release resources used during shell execution
4.721013
4.242183
1.112873
parser = argparse.ArgumentParser( description='Remote memory aquisition wrapper for LiME') root = parser.add_mutually_exclusive_group(required=True) root.add_argument('-c', '--config', help='path to config.yml') root.add_argument('--server', ...
def parse_args(self, args)
Parse arguments and return an arguments object >>> from margaritashotgun.cli import Cli >>> cli = CLi() >>> cli.parse_args(sys.argv[1:]) :type args: list :param args: list of arguments
2.853743
2.891803
0.986839
if arguments is not None: args_config = self.configure_args(arguments) base_config = copy.deepcopy(default_config) working_config = self.merge_config(base_config, args_config) if config is not None: self.validate_config(config) base_c...
def configure(self, arguments=None, config=None)
Merge command line arguments, config files, and default configs :type arguments: argparse.Namespace :params arguments: Arguments produced by Cli.parse_args :type config: dict :params config: configuration dict to merge and validate
2.928768
2.872027
1.019757
if variable in os.environ: env_var = os.environ[variable] else: env_var = default return env_var
def get_env_default(self, variable, default)
Fetch environment variables, returning a default if not found
2.280808
2.172511
1.049849
module, key, config_path = self.check_file_paths(arguments.module, arguments.key, arguments.config) log_dir = self.check_directory_paths(arguments.log_dir) if arguments.re...
def configure_args(self, arguments)
Create configuration has from command line arguments :type arguments: :py:class:`argparse.Namespace` :params arguments: arguments produced by :py:meth:`Cli.parse_args()`
2.890359
2.895008
0.998394
for path in enumerate(args): path = path[1] if path is not None: try: self.check_file_path(path) except OSError as ex: logger.warn(ex) raise return args
def check_file_paths(self, *args)
Ensure all arguments provided correspond to a file
3.914475
3.986073
0.982038
if os.path.exists(path) is not True: msg = "File Not Found {}".format(path) raise OSError(msg)
def check_file_path(self, path)
Ensure file exists at the provided path :type path: string :param path: path to directory to check
4.246131
5.536074
0.766993
for path in enumerate(args): path = path[1] if path is not None: try: self.check_directory_path(path) except OSError as ex: logger.warn(ex) raise return args
def check_directory_paths(self, *args)
Ensure all arguments correspond to directories
3.888583
3.825269
1.016551
if os.path.isdir(path) is not True: msg = "Directory Does Not Exist {}".format(path) raise OSError(msg)
def check_directory_path(self, path)
Ensure directory exists at the provided path :type path: string :param path: path to directory to check
4.135379
5.381303
0.768472
try: hosts = config['hosts'] except KeyError: raise InvalidConfigurationError('hosts', "", reason=('hosts configuration ' 'section is required')) for key in config.k...
def validate_config(self, config)
Validate configuration dict keys are supported :type config: dict :param config: configuration dictionary
2.182309
2.187618
0.997573
try: return paramiko.RSAKey.from_private_key_file(key_path) except PasswordRequiredException as ex: return paramiko.RSAKey.from_private_key_file(key_path, password=password)
def load_key(self, key_path, password)
Creates paramiko rsa key :type key_path: str :param key_path: path to rsa key :type password: str :param password: password to try if rsa key is encrypted
2.915753
2.711267
1.075421
logger = logging.getLogger(__name__) try: # Check repository GPG settings before starting workers # Handling this here prevents subprocesses from needing stdin access repo_conf = self.config['repository'] repo = None if repo_conf['enab...
def run(self)
Captures remote hosts memory
5.160416
5.064718
1.018895
if filename is None: raise MemoryCaptureAttributeMissingError('filename') if destination == OutputDestinations.local: logger.info("{0}: dumping to file://{1}".format(self.remote_addr, filename)) resu...
def capture(self, tunnel_addr, tunnel_port, filename=None, bucket=None, destination=None)
Captures memory based on the provided OutputDestination :type tunnel_addr: str :param tunnel_port: ssh tunnel hostname or ip :type tunnel_port: int :param tunnel_port: ssh tunnel port :type filename: str :param filename: memory dump output filename :type bucket: ...
3.223049
3.036053
1.061592
if self.progressbar: self.bar = ProgressBar(widgets=self.widgets, maxval=self.max_size).start() self.bar.start() with open(filename, 'wb') as self.outfile: self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) ...
def to_file(self, filename, tunnel_addr, tunnel_port)
Writes memory dump to a local file :type filename: str :param filename: memory dump output filename :type tunnel_addr: str :param tunnel_port: ssh tunnel hostname or ip :type tunnel_port: int :param tunnel_port: ssh tunnel port
2.458319
2.504362
0.981615
if self.progressbar: try: self.bar.update(self.transfered) except Exception as e: logger.debug("{0}: {1}, {2} exceeds memsize {3}".format( self.remote_addr, e, ...
def update_progress(self, complete=False)
Logs capture progress :type complete: bool :params complete: toggle to finish ncurses progress bar
3.777926
3.864919
0.977492
if self.sock is not None: self.sock.close() if self.outfile is not None: self.outfile.close() if self.bar is not None: self.update_progress(complete=True)
def cleanup(self)
Release resources used during memory capture
4.219525
4.072774
1.036032
if self.gpg_verify: logger.debug("gpg verification enabled, initializing gpg") gpg_home = os.path.expanduser('~/.gnupg') self.gpg = gnupg.GPG(gnupghome=gpg_home) self.key_path, self.key_info = self.get_signing_key() logger.debug("{0} {1}".form...
def init_gpg(self)
Initialize gpg object and check if repository signing key is trusted
3.077661
2.786882
1.104338
tmp_key_path = "/tmp/{0}".format(self.repo_signing_key) tmp_metadata_path = "/tmp/{0}".format(self.key_metadata) repo_key_path = "{0}/{1}".format(self.url, self.repo_signing_key) repo_metadata_path = "{0}/{1}".format(self.url, self.key_metadata) req_key = re...
def get_signing_key(self)
Download a local copy of repo signing key for installation
2.585096
2.489487
1.038405
user_keys = self.gpg.list_keys() if len(user_keys) > 0: trusted = False for key in user_keys: if key['fingerprint'] == self.key_info['fingerprint']: trusted = True logger.debug(("repo signing key trusted in user key...
def check_signing_key(self)
Check that repo signing key is trusted by gpg keychain
3.782913
3.162547
1.19616
print(self.key_info) repo_key_url = "{0}/{1}".format(self.url, self.repo_signing_key) print(("warning: Repository key untrusted \n" "Importing GPG key 0x{0}:\n" " Userid: \"{1}\"\n" " From : {2}".format(self.key_info['fingerprint'], ...
def prompt_for_install(self)
Prompt user to install untrusted repo signing key
5.652788
4.972608
1.136785
logger.info(("importing repository signing key {0} " "{1}".format(self.key_info['fingerprint'], self.key_info['uids'][0]))) import_result = self.gpg.import_keys(key_data) logger.debug("import results: {0}".format(import_result.resul...
def install_key(self, key_data)
Install untrusted repo signing key
5.328328
4.508336
1.181884
metadata = self.get_metadata() logger.debug("parsed metadata: {0}".format(metadata)) manifest = self.get_manifest(metadata['manifests'][manifest_type]) try: module = manifest[kernel_version] logger.debug("found module {0}".format(module)) except ...
def fetch(self, kernel_version, manifest_type)
Search repository for kernel module matching kernel_version :type kernel_version: str :param kernel_version: kernel version to search repository on :type manifest_type: str :param manifest_type: kernel module manifest to search on
3.950704
3.895552
1.014158
metadata_path = "{}/{}/{}".format(self.url, self.metadata_dir, self.metadata_file) metadata_sig_path = "{}/{}/{}.sig".format(self.url.rstrip('/'), self.metadata_...
def get_metadata(self)
Fetch repository repomd.xml file
3.241595
3.038123
1.066973
try: metadata = dict() mdata = xmltodict.parse(metadata_xml)['metadata'] metadata['revision'] = mdata['revision'] metadata['manifests'] = dict() # check if multiple manifests are present if type(mdata['data']) is list: ...
def parse_metadata(self, metadata_xml)
Parse repomd.xml file :type metadata_xml: str :param metadata_xml: raw xml representation of repomd.xml
2.615275
2.596328
1.007297
manifest_path = "{0}/{1}".format(self.url, metadata['location']) req = requests.get(manifest_path, stream=True) if req.status_code is 200: gz_manifest = req.raw.read() self.verify_checksum(gz_manifest, metadata['checksum'], metadata['loc...
def get_manifest(self, metadata)
Get latest manifest as specified in repomd.xml :type metadata: dict :param metadata: dictionary representation of repomd.xml
3.743744
3.906025
0.958454
buf = BytesIO(raw_manifest) f = gzip.GzipFile(fileobj=buf) manifest = f.read() return manifest
def unzip_manifest(self, raw_manifest)
Decompress gzip encoded manifest :type raw_manifest: str :param raw_manifest: compressed gzip manifest file content
3.47102
3.682117
0.94267
manifest = dict() try: mdata = xmltodict.parse(manifest_xml)['modules']['module'] for module in mdata: mod = dict() mod['type'] = module['@type'] mod['name'] = module['name'] mod['arch'] = module['arch'] ...
def parse_manifest(self, manifest_xml)
Parse manifest xml file :type manifest_xml: str :param manifest_xml: raw xml content of manifest file
2.529219
2.63149
0.961136
tm = int(time.time()) datestamp = datetime.utcfromtimestamp(tm).isoformat() filename = "lime-{0}-{1}.ko".format(datestamp, module['version']) url = "{0}/{1}".format(self.url, module['location']) logger.info("downloading {0} as {1}".format(url, filename)) req = re...
def fetch_module(self, module)
Download and verify kernel module :type module: str :param module: kernel module path
3.442024
3.379702
1.01844
with open(filename, 'rb') as f: module_data = f.read() self.verify_checksum(module_data, module['checksum'], module['location']) if self.gpg_verify: signature_url = "{0}/{1}".format(self.url, module['signature']) file_url...
def verify_module(self, filename, module, verify_signature)
Verify kernel module checksum and signature :type filename: str :param filename: downloaded kernel module path :type module: dict :param module: kernel module metadata :type verify_signature: bool :param verify_signature: enable/disable signature verification
3.258243
3.143055
1.036648
calculated_checksum = hashlib.sha256(data).hexdigest() logger.debug("calculated checksum {0} for {1}".format(calculated_checksum, filename)) if calculated_checksum != checksum: raise RepositoryError("{0}/{1}".form...
def verify_checksum(self, data, checksum, filename)
Verify sha256 checksum vs calculated checksum :type data: str :param data: data used to calculate checksum :type checksum: str :param checksum: expected checksum of data :type filename: str :param checksum: original filename
3.207325
3.518197
0.911639
req = requests.get(signature_url) if req.status_code is 200: tm = int(time.time()) datestamp = datetime.utcfromtimestamp(tm).isoformat() sigfile = "repo-{0}-tmp.sig".format(datestamp) logger.debug("writing {0} to {1}".format(signature_url, sigfil...
def verify_data_signature(self, signature_url, data_url, data)
Verify data against it's remote signature :type signature_url: str :param signature_url: remote path to signature for data_url :type data_url: str :param data_url: url from which data was fetched :type data: str :param data: content of remote file at file_url
2.785059
2.756694
1.010289
req = requests.get(signature_url, stream=True) if req.status_code is 200: sigfile = req.raw else: raise RepositoryMissingSignatureError(signature_url) verified = self.gpg.verify_file(sigfile, filename) if verified.valid is True: log...
def verify_file_signature(self, signature_url, file_url, filename)
Verify a local file against it's remote signature :type signature_url: str :param signature_url: remote path to signature for file_url :type file_url: str :param file_url: url from which file at filename was fetched :type filename: str :param filename: filename of local ...
3.186564
3.262406
0.976753
if tick.time is '': return event = Event(type_=EVENT_TINY_TICK) event.dict_['data'] = tick self._event_engine.put(event)
def _notify_new_tick_event(self, tick)
tick推送
7.54716
5.989641
1.260035
if not self._market_opened: return event = Event(type_=EVENT_QUOTE_CHANGE) event.dict_['data'] = tiny_quote self._rt_tiny_quote[tiny_quote.symbol] = tiny_quote self._event_engine.put(event)
def _notify_quote_change_event(self, tiny_quote)
推送
4.939542
4.223138
1.169638
for ix, row in data.iterrows(): symbol = row['code'] tick = self._tick_dict.get(symbol, None) if not tick: tick = TinyQuoteData() tick.symbol = symbol self._tick_dict[symbol] = tick tick.date = row['data_d...
def process_quote(self, data)
报价推送
4.030687
3.830492
1.052263
symbol = data['code'] tick = self._tick_dict.get(symbol, None) if not tick: tick = TinyQuoteData() tick.symbol = symbol self._tick_dict[symbol] = tick d = tick.__dict__ for i in range(5): bid_data = data['Bid'][i] ...
def process_orderbook(self, data)
订单簿推送
2.633316
2.578897
1.021102
# 每一次推送, 只会是同一个symbole + kltype bars_data = [] symbol = "" ktype = "" for ix, row in data.iterrows(): symbol = row['code'] ktype = row['k_type'] bar = TinyBarData() bar.open = row['open'] bar.close = row['close'...
def process_curkline(self, data)
k线实时数据推送
3.555325
3.427727
1.037225
ret_type = rsp_pb.retType ret_msg = rsp_pb.retMsg if ret_type != RET_OK: return RET_ERROR, ret_msg, None res = {} if rsp_pb.HasField('s2c'): res['server_version'] = rsp_pb.s2c.serverVer res['login_user_id'] = rsp_pb.s2c.loginUserID ...
def unpack_rsp(cls, rsp_pb)
Unpack the init connect response
2.665846
2.482751
1.073747
if rsp_pb.retType != RET_OK: return RET_ERROR, rsp_pb.retMsg, None return RET_OK, "", None
def unpack_unsubscribe_rsp(cls, rsp_pb)
Unpack the un-subscribed response
4.657768
4.294046
1.084704
currentFolder = os.getcwd() currentJsonPath = os.path.join(currentFolder, name) if os.path.isfile(currentJsonPath): return currentJsonPath else: moduleFolder = os.path.abspath(os.path.dirname(moduleFile)) moduleJsonPath = os.path.join(moduleFolder, '.', name) return ...
def getJsonPath(name, moduleFile)
获取JSON配置文件的路径: 1. 优先从当前工作目录查找JSON文件 2. 若无法找到则前往模块所在目录查找
2.255021
2.101379
1.073115
ret, data = self._trade_ctx.place_order(price=price, qty=volume, code=symbol, trd_side=ft.TrdSide.BUY, order_type=order_type, adjust_limit=adjust_limit, trd_env=self._env_type, acc_id=acc_id) if ret ...
def buy(self, price, volume, symbol, order_type=ft.OrderType.NORMAL, adjust_limit=0, acc_id=0)
买入
2.725494
2.796842
0.97449
ret, data = self._trade_ctx.modify_order(ft.ModifyOrderOp.CANCEL, order_id=order_id, qty=0, price=0, adjust_limit=0, trd_env=self._env_type, acc_id=acc_id) # ret不为0时, data为错误字符串 if ret == ft.RET_OK: return ret, '' els...
def cancel_order(self, order_id, acc_id=0)
取消订单
6.491694
6.357588
1.021094
ret, data = self._trade_ctx.order_list_query(order_id=order_id, status_filter_list=[], code='', start='', end='', trd_env=self._env_type, acc_id=acc_id) if ret != ft.RET_OK: return ret, data order = TinyTradeOrder() ...
def get_tiny_trade_order(self, order_id, acc_id=0)
得到订单信息
2.857558
2.833004
1.008667
ret, data = self._trade_ctx.position_list_query(code=symbol, trd_env=self._env_type, acc_id=acc_id) if 0 != ret: return None for _, row in data.iterrows(): if row['code'] != symbol: continue pos = TinyPosition() pos.symbol...
def get_tiny_position(self, symbol, acc_id=0)
得到股票持仓
3.474982
3.312977
1.0489
with open(self.settingfilePath, 'rb') as f: df = f.read() f.close() if type(df) is not str: df = ft.str_utf8(df) self._global_settings = json.loads(df) if self._global_settings is None or 'frame' not in self._global_settings: ...
def __loadSetting(self)
读取策略配置
3.205628
3.131042
1.023821
SysConfig.CLINET_ID = client_id SysConfig.CLIENT_VER = client_ver
def set_client_info(cls, client_id, client_ver)
.. py:function:: set_client_info(cls, client_id, client_ver) 设置调用api的客户端信息, 非必调接口 :param client_id: str, 客户端标识 :param client_ver: int, 客户端版本号 :return: None :example: .. code:: python from futuquant import * SysConfig.set_client_info("MyFutuQuant", ...
7.537393
6.70531
1.124093
# auto subscriber resub_count = 0 subtype_list = [] code_list = [] resub_dict = copy(self._ctx_subscribe) subtype_all_cnt = len(resub_dict.keys()) subtype_cur_cnt = 0 ret_code = RET_OK ret_msg = '' for subtype in resub_dict.keys...
def on_api_socket_reconnected(self)
for API socket reconnected
2.668232
2.655956
1.004622
if market is None or is_str(market) is False: error_str = ERROR_STR_PREFIX + "the type of market param is wrong" return RET_ERROR, error_str ret, msg, start, end = normalize_start_end_date(start, end, 365) if ret != RET_OK: return ret, msg q...
def get_trading_days(self, market, start=None, end=None)
获取交易日 :param market: 市场类型,Market_ :param start: 起始日期。例如'2018-01-01'。 :param end: 结束日期。例如'2018-01-01'。 start和end的组合如下: ========== ========== ======================================== start类型 end类型 说明 ========== ========== =================...
3.457942
3.313507
1.04359
param_table = {'market': market, 'stock_type': stock_type} for x in param_table: param = param_table[x] if param is None or is_str(param) is False: error_str = ERROR_STR_PREFIX + "the type of %s param is wrong" % x return RET_ERROR, error_...
def get_stock_basicinfo(self, market, stock_type=SecurityType.STOCK, code_list=None)
获取指定市场中特定类型的股票基本信息 :param market: 市场类型,futuquant.common.constant.Market :param stock_type: 股票类型, futuquant.common.constant.SecurityType :param code_list: 如果不为None,应该是股票code的iterable类型,将只返回指定的股票信息 :return: (ret_code, content) ret_code 等于RET_OK时, content为Pandas.DataFrame数据,...
2.822995
2.280389
1.237945