_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
31
13.1k
language
stringclasses
1 value
meta_information
dict
q246700
API.multi_call
train
def multi_call(self, calls): """Performs a multi-call to the API. :param calls: A list of call 2-tuples with method name and params (for example, ('Get', dict(typeName='Trip')) ). :type calls: list((str, dict)) :raise MyGeotabException: Raises when an exception occ...
python
{ "resource": "" }
q246701
API.authenticate
train
def authenticate(self, is_global=True): """Authenticates against the API server. :param is_global: If True, authenticate globally. Local login if False. :raise AuthenticationException: Raises if there was an issue with authenticating or logging in. :raise MyGeotabException: Raises when ...
python
{ "resource": "" }
q246702
API.from_credentials
train
def from_credentials(credentials): """Returns a new API object from an existing Credentials object. :param credentials: The existing saved credentials. :type credentials: Credentials :return: A new API object populated with MyGeotab credentials. :rtype: API """
python
{ "resource": "" }
q246703
ExceptionDataFeedListener._populate_sub_entity
train
def _populate_sub_entity(self, entity, type_name): """ Simple API-backed cache for populating MyGeotab entities :param entity: The entity to populate a sub-entity for :param type_name: The type of the sub-entity to populate """ key = type_name.lower() if isinstan...
python
{ "resource": "" }
q246704
ExceptionDataFeedListener.on_data
train
def on_data(self, data): """ The function called when new data has arrived. :param data: The list of data records received. """ for d in data: self._populate_sub_entity(d, 'Device') self._populate_sub_entity(d, 'Rule') date = dates.localize_da...
python
{ "resource": "" }
q246705
_should_allocate_port
train
def _should_allocate_port(pid): """Determine if we should allocate a port for use by the given process id.""" if pid <= 0: log.info('Not allocating a port to invalid pid') return False if pid == 1: # The client probably meant to send us its parent pid but # had been reparente...
python
{ "resource": "" }
q246706
_parse_command_line
train
def _parse_command_line(): """Configure and parse our command line flags.""" parser = argparse.ArgumentParser() parser.add_argument( '--portserver_static_pool', type=str, default='15000-24999', help='Comma separated N-P Range(s) of ports to manage (inclusive).') parser.ad...
python
{ "resource": "" }
q246707
_parse_port_ranges
train
def _parse_port_ranges(pool_str): """Given a 'N-P,X-Y' description of port ranges, return a set of ints.""" ports = set() for range_str in pool_str.split(','): try: a, b = range_str.split('-', 1)
python
{ "resource": "" }
q246708
_configure_logging
train
def _configure_logging(verbose=False, debug=False): """Configure the log global, message format, and verbosity settings.""" overall_level = logging.DEBUG if debug else logging.INFO logging.basicConfig( format=('{levelname[0]}{asctime}.{msecs:03.0f} {thread} '
python
{ "resource": "" }
q246709
_PortPool.get_port_for_process
train
def get_port_for_process(self, pid): """Allocates and returns port for pid or 0 if none could be allocated.""" if not self._port_queue: raise RuntimeError('No ports being managed.') # Avoid an infinite loop if all ports are currently assigned. check_count = 0 max_por...
python
{ "resource": "" }
q246710
_PortPool.add_port_to_free_pool
train
def add_port_to_free_pool(self, port): """Add a new port to the free pool for allocation.""" if port < 1 or port > 65535: raise ValueError( 'Port must be in the
python
{ "resource": "" }
q246711
_PortServerRequestHandler._handle_port_request
train
def _handle_port_request(self, client_data, writer): """Given a port request body, parse it and respond appropriately. Args: client_data: The request bytes from the client. writer: The asyncio Writer for the response to be written to. """ try: pid = int(c...
python
{ "resource": "" }
q246712
_PortServerRequestHandler.dump_stats
train
def dump_stats(self): """Logs statistics of our operation.""" log.info('Dumping statistics:') stats = [] stats.append( 'client-request-errors {}'.format(self._client_request_errors)) stats.append('denied-allocations {}'.format(self._denied_allocations)) stats....
python
{ "resource": "" }
q246713
return_port
train
def return_port(port): """Return a port that is no longer being used so it can be reused.""" if port in _random_ports: _random_ports.remove(port) elif port in _owned_ports: _owned_ports.remove(port) _free_ports.add(port) elif port in _free_ports: logging.info("Returning a
python
{ "resource": "" }
q246714
bind
train
def bind(port, socket_type, socket_proto): """Try to bind to a socket of the specified type, protocol, and port. This is primarily a helper function for PickUnusedPort, used to see if a particular port number is available. For the port to be considered available, the kernel must support at least o...
python
{ "resource": "" }
q246715
pick_unused_port
train
def pick_unused_port(pid=None, portserver_address=None): """A pure python implementation of PickUnusedPort. Args: pid: PID to tell the portserver to associate the reservation with. If None, the current process's PID is used. portserver_address: The address (path) of a unix domain socket ...
python
{ "resource": "" }
q246716
_pick_unused_port_without_server
train
def _pick_unused_port_without_server(): # Protected. pylint: disable=invalid-name """Pick an available network port without the help of a port server. This code ensures that the port is available on both TCP and UDP. This function is an implementation detail of PickUnusedPort(), and should not be cal...
python
{ "resource": "" }
q246717
get_port_from_port_server
train
def get_port_from_port_server(portserver_address, pid=None): """Request a free a port from a system-wide portserver. This follows a very simple portserver protocol: The request consists of our pid (in ASCII) followed by a newline. The response is a port number and a newline, 0 on failure. This fun...
python
{ "resource": "" }
q246718
main
train
def main(argv): """If passed an arg, treat it as a PID, otherwise portpicker uses getpid.""" port = pick_unused_port(pid=int(argv[1]) if len(argv)
python
{ "resource": "" }
q246719
RemoteControl.soap_request
train
def soap_request(self, url, urn, action, params, body_elem="m"): """Send a SOAP request to the TV.""" soap_body = ( '<?xml version="1.0" encoding="utf-8"?>' '<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"' ' s:encodingStyle="http://schemas.xmlsoap.org...
python
{ "resource": "" }
q246720
RemoteControl._get_local_ip
train
def _get_local_ip(self): """Try to determine the local IP address of the machine.""" try: sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # Use Google Public DNS server to determine own IP
python
{ "resource": "" }
q246721
RemoteControl.open_webpage
train
def open_webpage(self, url): """Launch Web Browser and open url""" params = ('<X_AppType>vc_app</X_AppType>' '<X_LaunchKeyword>resource_id={resource_id}</X_LaunchKeyword>' ).format(resource_id=1063) res = self.soap_request(URL_CONTROL_NRC, URN_REMOTE_CONTROL, ...
python
{ "resource": "" }
q246722
RemoteControl.get_volume
train
def get_volume(self): """Return the current volume level.""" params = '<InstanceID>0</InstanceID><Channel>Master</Channel>' res = self.soap_request(URL_CONTROL_DMR, URN_RENDERING_CONTROL, 'GetVolume', params)
python
{ "resource": "" }
q246723
RemoteControl.set_volume
train
def set_volume(self, volume): """Set a new volume level.""" if volume > 100 or volume < 0: raise Exception('Bad request to volume control. ' 'Must be between 0 and 100') params = ('<InstanceID>0</InstanceID><Channel>Master</Channel>'
python
{ "resource": "" }
q246724
RemoteControl.get_mute
train
def get_mute(self): """Return if the TV is muted.""" params = '<InstanceID>0</InstanceID><Channel>Master</Channel>' res = self.soap_request(URL_CONTROL_DMR, URN_RENDERING_CONTROL, 'GetMute', params)
python
{ "resource": "" }
q246725
RemoteControl.set_mute
train
def set_mute(self, enable): """Mute or unmute the TV.""" data = '1' if enable else '0' params = ('<InstanceID>0</InstanceID><Channel>Master</Channel>'
python
{ "resource": "" }
q246726
RemoteControl.send_key
train
def send_key(self, key): """Send a key command to the TV.""" if isinstance(key, Keys): key = key.value params = '<X_KeyEvent>{}</X_KeyEvent>'.format(key)
python
{ "resource": "" }
q246727
main
train
def main(): """ Handle command line execution. """ parser = argparse.ArgumentParser(prog='panasonic_viera', description='Remote control a Panasonic Viera TV.') parser.add_argument('host', metavar='host', type=str, help='Address of the Panasonic Viera TV') parser.a...
python
{ "resource": "" }
q246728
Keychain.item
train
def item(self, name, fuzzy_threshold=100): """ Extract a password from an unlocked Keychain using fuzzy matching. ``fuzzy_threshold`` can be an integer between 0 and 100, where 100 is an exact match. """ match = process.extractOne( name, self._item...
python
{ "resource": "" }
q246729
Keychain.key
train
def key(self, identifier=None, security_level=None): """ Tries to find an encryption key, first using the ``identifier`` and if that fails or isn't provided using the ``security_level``. Returns ``None`` if nothing matches. """ if identifier: try: ...
python
{ "resource": "" }
q246730
CLI.run
train
def run(self): """ The main entry point, performs the appropriate action for the given arguments. """ self._unlock_keychain() item = self.keychain.item( self.arguments.item, fuzzy_threshold=self._fuzzy_threshold(), ) if item is no...
python
{ "resource": "" }
q246731
is_text
train
def is_text(bytesio): """Return whether the first KB of contents seems to be binary. This is roughly based on libmagic's binary/text detection: https://github.com/file/file/blob/df74b09b9027676088c797528edcaae5a9ce9ad0/src/encoding.c#L203-L228
python
{ "resource": "" }
q246732
parse_shebang
train
def parse_shebang(bytesio): """Parse the shebang from a file opened for reading binary.""" if bytesio.read(2) != b'#!': return () first_line = bytesio.readline() try: first_line = first_line.decode('UTF-8') except UnicodeDecodeError: return () # Require only printable as...
python
{ "resource": "" }
q246733
parse_shebang_from_file
train
def parse_shebang_from_file(path): """Parse the shebang given a file path.""" if not os.path.lexists(path):
python
{ "resource": "" }
q246734
license_id
train
def license_id(filename): """Return the spdx id for the license contained in `filename`. If no license is detected, returns `None`. spdx: https://spdx.org/licenses/ licenses from choosealicense.com: https://github.com/choosealicense.com Approximate algorithm: 1. strip copyright line 2. n...
python
{ "resource": "" }
q246735
Credentials.access_token
train
def access_token(self): """Get access_token.""" if self.cache_token:
python
{ "resource": "" }
q246736
Credentials._credentials_found_in_envars
train
def _credentials_found_in_envars(): """Check for credentials in envars. Returns: bool: ``True`` if at least one is found, otherwise ``False``. """ return any([os.getenv('PAN_ACCESS_TOKEN'),
python
{ "resource": "" }
q246737
Credentials._resolve_credential
train
def _resolve_credential(self, credential): """Resolve credential from envars or credentials store. Args: credential (str): Credential to resolve. Returns: str or None: Resolved credential or ``None``. """ if self._credentials_found_in_instance: ...
python
{ "resource": "" }
q246738
Credentials.decode_jwt_payload
train
def decode_jwt_payload(self, access_token=None): """Extract payload field from JWT. Args: access_token (str): Access token to decode. Defaults to ``None``. Returns: dict: JSON object that contains the claims conveyed by the JWT. """ c = self.get_credent...
python
{ "resource": "" }
q246739
Credentials._decode_exp
train
def _decode_exp(self, access_token=None): """Extract exp field from access token. Args: access_token (str): Access token to decode. Defaults to ``None``. Returns: int: JWT expiration in epoch seconds. """ c = self.get_credentials() jwt = access_...
python
{ "resource": "" }
q246740
Credentials.fetch_tokens
train
def fetch_tokens(self, client_id=None, client_secret=None, code=None, redirect_uri=None, **kwargs): """Exchange authorization code for token. Args: client_id (str): OAuth2 client ID. Defaults to ``None``. client_secret (str): OAuth2 client secret. Defaults t...
python
{ "resource": "" }
q246741
Credentials.get_authorization_url
train
def get_authorization_url(self, client_id=None, instance_id=None, redirect_uri=None, region=None, scope=None, state=None): """Generate authorization URL. Args: client_id (str): OAuth2 client ID. Defaults to ``None``. in...
python
{ "resource": "" }
q246742
Credentials.get_credentials
train
def get_credentials(self): """Get read-only credentials. Returns: class: Read-only credentials.
python
{ "resource": "" }
q246743
Credentials.jwt_is_expired
train
def jwt_is_expired(self, access_token=None, leeway=0): """Validate JWT access token expiration. Args: access_token (str): Access token to validate. Defaults to ``None``. leeway (float): Time in seconds to adjust for local clock
python
{ "resource": "" }
q246744
Credentials.refresh
train
def refresh(self, access_token=None, **kwargs): """Refresh access and refresh tokens. Args: access_token (str): Access token to refresh. Defaults to ``None``. Returns: str: Refreshed access token. """ if not self.token_lock.locked(): with se...
python
{ "resource": "" }
q246745
Credentials.revoke_access_token
train
def revoke_access_token(self, **kwargs): """Revoke access token.""" c = self.get_credentials() data = { 'client_id': c.client_id, 'client_secret': c.client_secret, 'token': c.access_token, 'token_type_hint': 'access_token' } r = sel...
python
{ "resource": "" }
q246746
LoggingService.delete
train
def delete(self, query_id=None, **kwargs): # pragma: no cover """Delete a query job. Uses the DELETE HTTP method to delete a query job. After calling this endpoint, it is an error to poll for query results using the queryId specified here. Args: query_id (str): Spe...
python
{ "resource": "" }
q246747
LoggingService.iter_poll
train
def iter_poll(self, query_id=None, sequence_no=None, params=None, **kwargs): # pragma: no cover """Retrieve pages iteratively in a non-greedy manner. Automatically increments the sequenceNo as it continues to poll for results until the endpoint reports JOB_FINISHED or ...
python
{ "resource": "" }
q246748
LoggingService.poll
train
def poll(self, query_id=None, sequence_no=None, params=None, **kwargs): # pragma: no cover """Poll for asynchronous query results. Continue to poll for results until this endpoint reports JOB_FINISHED or JOB_FAILED. The results of queries can be returned in multiple pages,...
python
{ "resource": "" }
q246749
LoggingService.xpoll
train
def xpoll(self, query_id=None, sequence_no=None, params=None, delete_query=True, **kwargs): # pragma: no cover """Retrieve individual logs iteratively in a non-greedy manner. Generator function to return individual log entries from poll API request. Args: par...
python
{ "resource": "" }
q246750
LoggingService.write
train
def write(self, vendor_id=None, log_type=None, json=None, **kwargs): """Write log records to the Logging Service. This API requires a JSON array in its request body, each element of which represents a single log record. Log records are provided as JSON objects. Every log record must inc...
python
{ "resource": "" }
q246751
TinyDBStore.fetch_credential
train
def fetch_credential(self, credential=None, profile=None): """Fetch credential from credentials file. Args: credential (str): Credential to fetch. profile (str): Credentials profile. Defaults to ``'default'``. Returns: str,
python
{ "resource": "" }
q246752
TinyDBStore.remove_profile
train
def remove_profile(self, profile=None): """Remove profile from credentials file. Args: profile (str): Credentials profile to
python
{ "resource": "" }
q246753
EventService.nack
train
def nack(self, channel_id=None, **kwargs): # pragma: no cover """Send a negative read-acknowledgement to the service. Causes the channel's read point to move to its previous position prior to the last poll. Args: channel_id (str): The channel ID. **kwargs: Supp...
python
{ "resource": "" }
q246754
EventService.poll
train
def poll(self, channel_id=None, json=None, **kwargs): # pragma: no cover """Read one or more events from a channel. Reads events (log records) from the identified channel. Events are read in chronological order. Args: channel_id (str): The channel ID. json (dic...
python
{ "resource": "" }
q246755
EventService.xpoll
train
def xpoll(self, channel_id=None, json=None, ack=False, follow=False, pause=None, **kwargs): """Retrieve logType, event entries iteratively in a non-greedy manner. Generator function to return logType, event entries from poll API request. Args: channel_id (str)...
python
{ "resource": "" }
q246756
HTTPClient._apply_credentials
train
def _apply_credentials(auto_refresh=True, credentials=None, headers=None): """Update Authorization header. Update request headers with latest `access_token`. Perform token `refresh` if token is ``None``. Args: auto_refresh (bool): Perform token re...
python
{ "resource": "" }
q246757
HTTPClient.request
train
def request(self, **kwargs): """Generate HTTP request using given parameters. The request method prepares HTTP requests using class or method-level attributes/variables. Class-level attributes may be overridden by method-level variables offering greater flexibility and efficienc...
python
{ "resource": "" }
q246758
DirectorySyncService.query
train
def query(self, object_class=None, json=None, **kwargs): # pragma: no cover """Query data stored in directory. Retrieves directory data by querying a Directory Sync Service cloud-based instance. The directory data is stored with the Directory Sync Service instance using an agent that i...
python
{ "resource": "" }
q246759
Command.handle
train
def handle(self, *args, **options): """ Forward to the right sub-handler """ if options["sub_command"] == "add": self.handle_add(options) elif options["sub_command"] == "update": self.handle_update(options) elif options["sub_command"] == "details":
python
{ "resource": "" }
q246760
Command.handle_update
train
def handle_update(self, options): # pylint: disable=no-self-use """ Update existing user""" username = options["username"] try: user = User.objects.get(username=username) except User.DoesNotExist: raise CommandError("User %s does not exist" % username)
python
{ "resource": "" }
q246761
Command.handle_details
train
def handle_details(self, username): """ Print user details """ try: user = User.objects.get(username=username) except User.DoesNotExist: raise CommandError("Unable to find user '%s'" % username) self.stdout.write("username : %s" % username) self.stdout...
python
{ "resource": "" }
q246762
apply_plugins
train
def apply_plugins(plugin_names): """ This function should be used by code in the SQUAD core to trigger functionality from plugins. The ``plugin_names`` argument is list of plugins names to be used. Most probably, you will want to pass the list of plugins enabled for a given
python
{ "resource": "" }
q246763
Build.metadata
train
def metadata(self): """ The build metadata is the union of the metadata in its test runs. Common keys with different values are transformed into a list with each of the different values. """ if self.__metadata__ is None: metadata = {} for test_run ...
python
{ "resource": "" }
q246764
ProjectViewSet.builds
train
def builds(self, request, pk=None): """ List of builds for the current project. """ builds = self.get_object().builds.prefetch_related('test_runs').order_by('-datetime') page = self.paginate_queryset(builds)
python
{ "resource": "" }
q246765
ProjectViewSet.suites
train
def suites(self, request, pk=None): """ List of test suite names available in this project """ suites_names = self.get_object().suites.values_list('slug') suites_metadata = SuiteMetadata.objects.filter(kind='suite', suite__in=suites_names) page = self.paginate_queryset(su...
python
{ "resource": "" }
q246766
main
train
def main( source, repo_source_files, requirements_file, local_source_file, work_dir): """ Bundle up a deployment package for AWS Lambda. From your local filesystem: \b $ make-lambda-package . ... dist/lambda-package.zip Or from a rem...
python
{ "resource": "" }
q246767
_default_ising_beta_range
train
def _default_ising_beta_range(h, J): """Determine the starting and ending beta from h J Args: h (dict) J (dict) Assume each variable in J is also in h. We use the minimum bias to give a lower bound on the minimum energy gap, such at the final sweeps we are highly likely to settle...
python
{ "resource": "" }
q246768
ReliefF._getMultiClassMap
train
def _getMultiClassMap(self): """ Relief algorithms handle the scoring updates a little differently for data with multiclass outcomes. In ReBATE we implement multiclass scoring in line with the strategy described by Kononenko 1994 within the RELIEF-F variant which was suggested to outperform the RELIEF-E...
python
{ "resource": "" }
q246769
ReliefF._distarray_missing
train
def _distarray_missing(self, xc, xd, cdiffs): """Distance array calculation for data with missing values""" cindices = [] dindices = [] # Get Boolean mask locating missing values for continuous and discrete features separately. These correspond to xc and xd respectively. for i in...
python
{ "resource": "" }
q246770
SURFstar._find_neighbors
train
def _find_neighbors(self, inst, avg_dist): """ Identify nearest as well as farthest hits and misses within radius defined by average distance over whole distance array. This works the same regardless of endpoint type. """ NN_near = [] NN_far = [] min_indices = [] max_indi...
python
{ "resource": "" }
q246771
get_row_missing
train
def get_row_missing(xc, xd, cdiffs, index, cindices, dindices): """ Calculate distance between index instance and all other instances. """ row = np.empty(0, dtype=np.double) # initialize empty row cinst1 = xc[index] # continuous-valued features for index instance dinst1 = xd[index] # discrete-val...
python
{ "resource": "" }
q246772
ramp_function
train
def ramp_function(data_type, attr, fname, xinstfeature, xNNifeature): """ Our own user simplified variation of the ramp function suggested by Hong 1994, 1997. Hong's method requires the user to specifiy two thresholds that indicate the max difference before a score of 1 is given, as well a min difference befo...
python
{ "resource": "" }
q246773
ReliefF_compute_scores
train
def ReliefF_compute_scores(inst, attr, nan_entries, num_attributes, mcmap, NN, headers, class_type, X, y, labels_std, data_type): """ Unique scoring procedure for ReliefF algorithm. Scoring based on k nearest hits and misses of
python
{ "resource": "" }
q246774
SURFstar_compute_scores
train
def SURFstar_compute_scores(inst, attr, nan_entries, num_attributes, mcmap, NN_near, NN_far, headers, class_type, X, y, labels_std, data_type): """ Unique scoring procedure for SURFstar algorithm. Scoring based on nearest neighbors within defined radius, as well as 'anti-scoring' of far instances outside of r...
python
{ "resource": "" }
q246775
MultiSURFstar._find_neighbors
train
def _find_neighbors(self, inst): """ Identify nearest as well as farthest hits and misses within radius defined by average distance and standard deviation of distances from target instanace. This works the same regardless of endpoint type. """ dist_vect = [] for j in range(self._datalen)...
python
{ "resource": "" }
q246776
SURF._find_neighbors
train
def _find_neighbors(self, inst, avg_dist): """ Identify nearest hits and misses within radius defined by average distance over whole distance array. This works the same regardless of endpoint type. """ NN = [] min_indicies = [] for i in range(self._datalen): if inst ...
python
{ "resource": "" }
q246777
StringQuoteChecker.leave_module
train
def leave_module(self, node): """Leave module and check remaining triple quotes. Args: node: the module node we are leaving. """ for triple_quote in self._tokenized_triple_quotes.values():
python
{ "resource": "" }
q246778
StringQuoteChecker._process_for_docstring
train
def _process_for_docstring(self, node, node_type): """Check for docstring quote consistency. Args: node: the AST node being visited. node_type: the type of node being operated on. """ # if there is no docstring, don't need to do anything. if node.doc is n...
python
{ "resource": "" }
q246779
StringQuoteChecker._find_docstring_line_for_no_body
train
def _find_docstring_line_for_no_body(self, start): """Find the docstring associated with a definition with no body in the node. In these cases, the provided start and end line number for that element are the same, so we must get the docstring based on the sequential position of ...
python
{ "resource": "" }
q246780
StringQuoteChecker._find_docstring_line
train
def _find_docstring_line(self, start, end): """Find the row where a docstring starts in a function or class. This will search for the first match of a triple quote token in row sequence from the start of the class or function. Args: start: the row where the class / function...
python
{ "resource": "" }
q246781
StringQuoteChecker.process_tokens
train
def process_tokens(self, tokens): """Process the token stream. This is required to override the parent class' implementation. Args: tokens: the tokens from the token stream to process. """ for tok_type, token, (start_row, start_col), _, _ in tokens: if t...
python
{ "resource": "" }
q246782
StringQuoteChecker._process_string_token
train
def _process_string_token(self, token, start_row, start_col): """Internal method for identifying and checking string tokens from the token stream. Args: token: the token to check. start_row: the line on which the token was found. start_col: the column on whic...
python
{ "resource": "" }
q246783
StringQuoteChecker._check_triple_quotes
train
def _check_triple_quotes(self, quote_record): """Check if the triple quote from tokenization is valid. Args: quote_record: a tuple containing the info about the string from tokenization, giving the (token, quote, row number, column). """
python
{ "resource": "" }
q246784
StringQuoteChecker._check_docstring_quotes
train
def _check_docstring_quotes(self, quote_record): """Check if the docstring quote from tokenization is valid. Args: quote_record: a tuple containing the info about the string from tokenization, giving the (token, quote, row number). """
python
{ "resource": "" }
q246785
StringQuoteChecker._invalid_string_quote
train
def _invalid_string_quote(self, quote, row, correct_quote=None, col=None): """Add a message for an invalid string literal quote. Args: quote: The quote characters that were found. row: The row number the quote character was found on. correct_quote: The quote characte...
python
{ "resource": "" }
q246786
StringQuoteChecker._invalid_triple_quote
train
def _invalid_triple_quote(self, quote, row, col=None): """Add a message for an invalid triple quote. Args: quote: The quote characters that were found. row: The row number the quote characters were found on. col: The column the quote characters were found on. ...
python
{ "resource": "" }
q246787
StringQuoteChecker._invalid_docstring_quote
train
def _invalid_docstring_quote(self, quote, row, col=None): """Add a message for an invalid docstring quote. Args: quote: The quote characters that were found. row: The row number the quote characters were found on. col: The column the quote characters were found on. ...
python
{ "resource": "" }
q246788
get_live_data_dir
train
def get_live_data_dir(): """ pygeth needs a base directory to store it's chain data. By default this is the directory that `geth` uses as it's `datadir`. """ if sys.platform == 'darwin': data_dir = os.path.expanduser(os.path.join( "~", "Library", "Ethereu...
python
{ "resource": "" }
q246789
get_accounts
train
def get_accounts(data_dir, **geth_kwargs): """ Returns all geth accounts as tuple of hex encoded strings >>> geth_accounts() ... ('0x...', '0x...') """ command, proc = spawn_geth(dict( data_dir=data_dir, suffix_args=['account', 'list'], **geth_kwargs )) stdoutdat...
python
{ "resource": "" }
q246790
create_new_account
train
def create_new_account(data_dir, password, **geth_kwargs): """Creates a new Ethereum account on geth. This is useful for testing when you want to stress interaction (transfers) between Ethereum accounts. This command communicates with ``geth`` command over terminal interaction. It creates keystore...
python
{ "resource": "" }
q246791
compare
train
def compare(left, right): """ yields EVENT,ENTRY pairs describing the differences between left and right, which are filenames for a pair of zip files """
python
{ "resource": "" }
q246792
compare_zips
train
def compare_zips(left, right): """ yields EVENT,ENTRY pairs describing the differences between left and right ZipFile instances """ ll = set(left.namelist()) rl = set(right.namelist()) for f in ll: if f in rl: rl.remove(f) if f[-1] == '/': #...
python
{ "resource": "" }
q246793
_different
train
def _different(left, right, f): """ true if entry f is different between left and right ZipFile instances """ l = left.getinfo(f) r = right.getinfo(f) if (l.file_size == r.file_size) and (l.CRC == r.CRC):
python
{ "resource": "" }
q246794
_deep_different
train
def _deep_different(left, right, entry): """ checks that entry is identical between ZipFile instances left and right """ left = chunk_zip_entry(left, entry) right = chunk_zip_entry(right, entry)
python
{ "resource": "" }
q246795
collect_compare_into
train
def collect_compare_into(left, right, added, removed, altered, same): """ collects the differences between left and right, which are filenames for valid zip files, into the lists added, removed, altered, and same. Returns a tuple of added, removed, altered, same """ with open_zip(left) as ...
python
{ "resource": "" }
q246796
collect_compare_zips_into
train
def collect_compare_zips_into(left, right, added, removed, altered, same): """ collects the differences between left and right ZipFile instances into the lists added, removed, altered, and same. Returns a tuple of added, removed, altered, same """ for event, filename in compare_zips(left, righ...
python
{ "resource": "" }
q246797
is_zipstream
train
def is_zipstream(data): """ just like zipfile.is_zipfile, but works upon buffers and streams rather than filenames. If data supports the read method, it will be treated as a stream and read from to test whether it is a valid ZipFile. If data also supports the tell and seek methods, it will be ...
python
{ "resource": "" }
q246798
file_crc32
train
def file_crc32(filename, chunksize=_CHUNKSIZE): """ calculate the CRC32 of the contents of filename """ check = 0 with open(filename, 'rb') as fd:
python
{ "resource": "" }
q246799
_collect_infos
train
def _collect_infos(dirname): """ Utility function used by ExplodedZipFile to generate ZipInfo entries for all of the files and directories under dirname """ for r, _ds, fs in walk(dirname): if not islink(r) and r != dirname: i = ZipInfo() i.filename = join(relpath(r, dirnam...
python
{ "resource": "" }