uid
stringlengths
24
24
split
stringclasses
1 value
category
stringclasses
2 values
content
stringlengths
5
482k
signature
stringlengths
1
14k
suffix
stringlengths
1
482k
prefix
stringlengths
9
14k
prefix_token_count
int64
3
5.01k
prefix_token_budget
int64
64
256
element_token_count
int64
1
292k
signature_token_count
int64
1
5.01k
prefix_context_token_count
int64
0
255
repo
stringlengths
7
112
path
stringlengths
4
208
language
stringclasses
1 value
name
stringlengths
1
218
qualname
stringlengths
1
218
start_line
int64
1
26.7k
end_line
int64
1
26.7k
signature_start_line
int64
1
26.7k
signature_end_line
int64
1
26.7k
source_hash
stringlengths
40
40
source_dataset
stringclasses
1 value
source_split
stringclasses
1 value
60598a2ca5df0d5486cc6dc9
train
class
class DeviceFlowInfo(collections.namedtuple('DeviceFlowInfo', ( 'device_code', 'user_code', 'interval', 'verification_url', 'user_code_expiry'))): """Intermediate information the OAuth2 for devices flow.""" @classmethod def FromResponse(cls, response): """Create a DeviceFlowInfo fro...
class DeviceFlowInfo(collections.namedtuple('DeviceFlowInfo', ( 'device_code', 'user_code', 'interval', 'verification_url', 'user_code_expiry'))):
"""Intermediate information the OAuth2 for devices flow.""" @classmethod def FromResponse(cls, response): """Create a DeviceFlowInfo from a server response. The response should be a dict containing entries as described here: http://tools.ietf.org/html/draft-ietf-oauth-v2-05#sectio...
invalid. """ flow = flow_from_clientsecrets(filename, scope, message=message, cache=cache, redirect_uri=redirect_uri, device_uri=device_uri) credentials = flow.step2_exchange(code, http=htt...
92
92
309
38
53
craigcitro/oauth2client
oauth2client/client.py
Python
DeviceFlowInfo
DeviceFlowInfo
1,740
1,775
1,740
1,742
aaf3439d805736a599701c72da2844cb63dfd919
bigcode/the-stack
train
22aa880890e894646a13d44e
train
function
def _detect_gce_environment(): """Determine if the current environment is Compute Engine. Returns: Boolean indicating whether or not the current environment is Google Compute Engine. """ # NOTE: The explicit ``timeout`` is a workaround. The underlying # issue is that resolving...
def _detect_gce_environment():
"""Determine if the current environment is Compute Engine. Returns: Boolean indicating whether or not the current environment is Google Compute Engine. """ # NOTE: The explicit ``timeout`` is a workaround. The underlying # issue is that resolving an unknown host on some networ...
is expired or invalid and can\'t be refreshed.') def _revoke(self, http): """Revokes the access_token and deletes the store if available. Args: http: an object to be used to make HTTP requests. """ self._do_revoke(http, self.access_token) def _detect_gce_environment():...
71
71
239
7
64
craigcitro/oauth2client
oauth2client/client.py
Python
_detect_gce_environment
_detect_gce_environment
983
1,005
983
983
5d879f101a89506ed6fe74cd3e5583a0dd4e042f
bigcode/the-stack
train
a001dbc47554bc93538db940
train
class
class GoogleCredentials(OAuth2Credentials): """Application Default Credentials for use in calling Google APIs. The Application Default Credentials are being constructed as a function of the environment where the code is being run. More details can be found on this page: https://developers.google.co...
class GoogleCredentials(OAuth2Credentials):
"""Application Default Credentials for use in calling Google APIs. The Application Default Credentials are being constructed as a function of the environment where the code is being run. More details can be found on this page: https://developers.google.com/accounts/docs/application-default-credenti...
Detects if the code is running in the App Engine environment. Returns: True if running in the GAE environment, False otherwise. """ if SETTINGS.env_name is not None: return SETTINGS.env_name in ('GAE_PRODUCTION', 'GAE_LOCAL') try: import google.appengine # noqa: unused import ...
256
256
1,839
8
247
craigcitro/oauth2client
oauth2client/client.py
Python
GoogleCredentials
GoogleCredentials
1,048
1,300
1,048
1,048
31c75dae9f5da224ea6a4131180c615a47511033
bigcode/the-stack
train
369a0bf3920d193f59c6feb4
train
class
class UnknownClientSecretsFlowError(Error): """The client secrets file called for an unknown type of OAuth 2.0 flow."""
class UnknownClientSecretsFlowError(Error):
"""The client secrets file called for an unknown type of OAuth 2.0 flow."""
access token.""" def __init__(self, *args, **kwargs): super(HttpAccessTokenRefreshError, self).__init__(*args) self.status = kwargs.get('status') class TokenRevokeError(Error): """Error trying to revoke a token.""" class UnknownClientSecretsFlowError(Error):
63
64
27
8
55
craigcitro/oauth2client
oauth2client/client.py
Python
UnknownClientSecretsFlowError
UnknownClientSecretsFlowError
155
156
155
155
f536dfac253b6cac8df74c3fb2757a19a5e2bd66
bigcode/the-stack
train
1ad39d07f49ac3f49a461514
train
function
@_helpers.positional(2) def verify_id_token(id_token, audience, http=None, cert_uri=ID_TOKEN_VERIFICATION_CERTS): """Verifies a signed JWT id_token. This function requires PyOpenSSL and because of that it does not work on App Engine. Args: id_token: string, A Signed JWT. ...
@_helpers.positional(2) def verify_id_token(id_token, audience, http=None, cert_uri=ID_TOKEN_VERIFICATION_CERTS):
"""Verifies a signed JWT id_token. This function requires PyOpenSSL and because of that it does not work on App Engine. Args: id_token: string, A Signed JWT. audience: string, The audience 'aud' that the token should be for. http: httplib2.Http, instance to use to make the HTTP...
The oauth2client.crypt module requires either PyCrypto or PyOpenSSL to be available in order to function, but these are optional dependencies. """ if not HAS_CRYPTO: raise CryptoUnavailableError('No crypto library available') @_helpers.positional(2) def verify_id_token(id_token, audience, http=...
84
84
282
31
53
craigcitro/oauth2client
oauth2client/client.py
Python
verify_id_token
verify_id_token
1,529
1,561
1,529
1,531
84a9608fbd471f21b11dde221714898a2d735d70
bigcode/the-stack
train
abeb191079d847e531bace7c
train
function
def save_to_well_known_file(credentials, well_known_file=None): """Save the provided GoogleCredentials to the well known file. Args: credentials: the credentials to be saved to the well known file; it should be an instance of GoogleCredentials well_known_file: the name of t...
def save_to_well_known_file(credentials, well_known_file=None):
"""Save the provided GoogleCredentials to the well known file. Args: credentials: the credentials to be saved to the well known file; it should be an instance of GoogleCredentials well_known_file: the name of the file where the credentials are to be ...
0o600) with os.fdopen(file_desc, 'w') as file_handle: json.dump(json_contents, file_handle, sort_keys=True, indent=2, separators=(',', ': ')) shutil.move(temp_filename, filename) def save_to_well_known_file(credentials, well_known_file=None):
64
64
205
14
50
craigcitro/oauth2client
oauth2client/client.py
Python
save_to_well_known_file
save_to_well_known_file
1,318
1,340
1,318
1,318
604a3be7c0299564b98cd69e82da9b9a6a93acbc
bigcode/the-stack
train
294b6287e19dbf67d56f6ef2
train
class
class Flow(object): """Base class for all Flow objects.""" pass
class Flow(object):
"""Base class for all Flow objects.""" pass
Instantiate a Credentials object from a JSON description of it. The JSON should have been produced by calling .to_json() on the object. Args: unused_data: dict, A deserialized JSON object. Returns: An instance of a Credentials subclass. """ return Crede...
64
64
16
4
60
craigcitro/oauth2client
oauth2client/client.py
Python
Flow
Flow
331
333
331
331
b795540af1e6fcbbfcf9f2e7d51a888d11443895
bigcode/the-stack
train
acf03a66794895fcebe71f87
train
function
def _raise_exception_for_reading_json(credential_file, extra_help, error): raise ApplicationDefaultCredentialsError( 'An error was encountered while reading json file: ' + credential_file + extra_help + ': ' + str(error))
def _raise_exception_for_reading_json(credential_file, extra_help, error):
raise ApplicationDefaultCredentialsError( 'An error was encountered while reading json file: ' + credential_file + extra_help + ': ' + str(error))
file_dict( client_credentials) def _raise_exception_for_missing_fields(missing_fields): raise ApplicationDefaultCredentialsError( 'The following field(s) must be defined: ' + ', '.join(missing_fields)) def _raise_exception_for_reading_json(credential_file, ...
64
64
52
19
45
craigcitro/oauth2client
oauth2client/client.py
Python
_raise_exception_for_reading_json
_raise_exception_for_reading_json
1,424
1,429
1,424
1,426
835d77251f1cbf60e6f8b05cb055d516780b7a55
bigcode/the-stack
train
876dfa6f365b4bf3c7b987b2
train
class
class OAuth2DeviceCodeError(Error): """Error trying to retrieve a device code."""
class OAuth2DeviceCodeError(Error):
"""Error trying to retrieve a device code."""
possible.""" class VerifyJwtTokenError(Error): """Could not retrieve certificates for validation.""" class NonAsciiHeaderError(Error): """Header names and values must be ASCII strings.""" class ApplicationDefaultCredentialsError(Error): """Error retrieving the Application Default Credentials.""" clas...
63
64
18
8
55
craigcitro/oauth2client
oauth2client/client.py
Python
OAuth2DeviceCodeError
OAuth2DeviceCodeError
175
176
175
175
d7001423c54eca93a12f87b011c344d0911137f5
bigcode/the-stack
train
7072e18420d62588857b7fdb
train
class
class OAuth2WebServerFlow(Flow): """Does the Web Server Flow for OAuth 2.0. OAuth2WebServerFlow objects may be safely pickled and unpickled. """ @_helpers.positional(4) def __init__(self, client_id, client_secret=None, scope=None, redirect_uri=Non...
class OAuth2WebServerFlow(Flow):
"""Does the Web Server Flow for OAuth 2.0. OAuth2WebServerFlow objects may be safely pickled and unpickled. """ @_helpers.positional(4) def __init__(self, client_id, client_secret=None, scope=None, redirect_uri=None, user_agent=No...
_url # expires_in and interval are optional. kwargs.update({ 'interval': response.get('interval'), 'user_code_expiry': None, }) if 'expires_in' in response: kwargs['user_code_expiry'] = ( _UTCNOW() + datetime.timedelta(s...
256
256
2,550
9
246
craigcitro/oauth2client
oauth2client/client.py
Python
OAuth2WebServerFlow
OAuth2WebServerFlow
1,805
2,089
1,805
1,805
5468fa01d6328daf03db87a295aa0d2d61d2f67c
bigcode/the-stack
train
7d083afd6f39b5327731f58e
train
class
class Error(Exception): """Base error for this module."""
class Error(Exception):
"""Base error for this module."""
module but have been # moved into `oauth2client.transport`, clean_headers = transport.clean_headers MemoryCache = transport.MemoryCache REFRESH_STATUS_CODES = transport.REFRESH_STATUS_CODES class SETTINGS(object): """Settings namespace for globally defined values.""" env_name = None class Error(Excepti...
64
64
12
4
59
craigcitro/oauth2client
oauth2client/client.py
Python
Error
Error
132
133
132
132
966f593bf5d7f4149b9e9c3ec85635fc4ad05bd2
bigcode/the-stack
train
bc7cc54b792e878fe1f448c0
train
class
class Credentials(object): """Base class for all Credentials objects. Subclasses must define an authorize() method that applies the credentials to an HTTP transport. Subclasses must also specify a classmethod named 'from_json' that takes a JSON string as input and returns an instantiated Credentia...
class Credentials(object):
"""Base class for all Credentials objects. Subclasses must define an authorize() method that applies the credentials to an HTTP transport. Subclasses must also specify a classmethod named 'from_json' that takes a JSON string as input and returns an instantiated Credentials object. """ NON...
"""Error (with HTTP status) trying to refresh an expired access token.""" def __init__(self, *args, **kwargs): super(HttpAccessTokenRefreshError, self).__init__(*args) self.status = kwargs.get('status') class TokenRevokeError(Error): """Error trying to revoke a token.""" class UnknownCli...
256
256
1,000
4
251
craigcitro/oauth2client
oauth2client/client.py
Python
Credentials
Credentials
190
328
190
190
74e69b757efd0f398e71dae20c4bb47e8f4b078c
bigcode/the-stack
train
c95ddb093deaea7e707b38b8
train
function
def _get_application_default_credential_GAE(): from oauth2client.contrib.appengine import AppAssertionCredentials return AppAssertionCredentials([])
def _get_application_default_credential_GAE():
from oauth2client.contrib.appengine import AppAssertionCredentials return AppAssertionCredentials([])
_fields)) def _raise_exception_for_reading_json(credential_file, extra_help, error): raise ApplicationDefaultCredentialsError( 'An error was encountered while reading json file: ' + credential_file + extra_help + ': ' + st...
64
64
29
10
54
craigcitro/oauth2client
oauth2client/client.py
Python
_get_application_default_credential_GAE
_get_application_default_credential_GAE
1,432
1,435
1,432
1,432
5206e3028150023aeaec136612b60456a0225b8a
bigcode/the-stack
train
257b9cb2ad6eab96a1765f54
train
function
def _extract_id_token(id_token): """Extract the JSON payload from a JWT. Does the extraction w/o checking the signature. Args: id_token: string or bytestring, OAuth 2.0 id_token. Returns: object, The deserialized JSON payload. """ if type(id_token) == bytes: segments =...
def _extract_id_token(id_token):
"""Extract the JSON payload from a JWT. Does the extraction w/o checking the signature. Args: id_token: string or bytestring, OAuth 2.0 id_token. Returns: object, The deserialized JSON payload. """ if type(id_token) == bytes: segments = id_token.split(b'.') else: ...
== http_client.OK: certs = json.loads(_helpers._from_bytes(content)) return crypt.verify_signed_jwt_with_certs(id_token, certs, audience) else: raise VerifyJwtTokenError('Status code: {0}'.format(resp.status)) def _extract_id_token(id_token):
64
64
149
8
56
craigcitro/oauth2client
oauth2client/client.py
Python
_extract_id_token
_extract_id_token
1,564
1,585
1,564
1,564
5e690c1f567201b2e9921d24cdf75dac6d14d27c
bigcode/the-stack
train
fe5e07220118badb3ee5e08d
train
function
def _get_application_default_credential_from_file(filename): """Build the Application Default Credentials from file.""" # read the credentials from the file with open(filename) as file_obj: client_credentials = json.load(file_obj) credentials_type = client_credentials.get('type') if credent...
def _get_application_default_credential_from_file(filename):
"""Build the Application Default Credentials from file.""" # read the credentials from the file with open(filename) as file_obj: client_credentials = json.load(file_obj) credentials_type = client_credentials.get('type') if credentials_type == AUTHORIZED_USER: required_fields = set([...
.environ.get('SystemDrive', 'C:') default_config_dir = os.path.join(drive, '\\', _CLOUDSDK_CONFIG_DIRECTORY) else: default_config_dir = os.path.join(os.path.expanduser('~'), '.config', ...
91
91
305
11
80
craigcitro/oauth2client
oauth2client/client.py
Python
_get_application_default_credential_from_file
_get_application_default_credential_from_file
1,382
1,416
1,382
1,382
0b3d89b2d008f86b1d836f50603e12af2b636499
bigcode/the-stack
train
9e0899e5f73284d83435b477
train
function
@_helpers.positional(2) def flow_from_clientsecrets(filename, scope, redirect_uri=None, message=None, cache=None, login_hint=None, device_uri=None, pkce=None, code_verifier=None): """Create a Flow from a clientsecrets file. Will create the right kind of F...
@_helpers.positional(2) def flow_from_clientsecrets(filename, scope, redirect_uri=None, message=None, cache=None, login_hint=None, device_uri=None, pkce=None, code_verifier=None):
"""Create a Flow from a clientsecrets file. Will create the right kind of Flow based on the contents of the clientsecrets file or will raise InvalidClientSecretsError for unknown types of Flows. Args: filename: string, File name of client secrets. scope: string or iterable of strin...
_id, self.client_secret, refresh_token, token_expiry, self.token_uri, self.user_agent, revoke_uri=self.revoke_uri, id_token=extracted_id_token, id_token_jwt=id_token_jwt, token_response=d, scopes=self.scope, token_info_uri=self.token_info_uri) else...
199
199
665
47
152
craigcitro/oauth2client
oauth2client/client.py
Python
flow_from_clientsecrets
flow_from_clientsecrets
2,092
2,163
2,092
2,095
e586b462b30971f1d6c8c5c60d970b02ff2220eb
bigcode/the-stack
train
4f03afdb0be2a52c414bf814
train
class
class AccessTokenRefreshError(Error): """Error trying to refresh an expired access token."""
class AccessTokenRefreshError(Error):
"""Error trying to refresh an expired access token."""
RESH_STATUS_CODES class SETTINGS(object): """Settings namespace for globally defined values.""" env_name = None class Error(Exception): """Base error for this module.""" class FlowExchangeError(Error): """Error trying to exchange an authorization grant for an access token.""" class AccessTokenRefr...
63
64
18
7
56
craigcitro/oauth2client
oauth2client/client.py
Python
AccessTokenRefreshError
AccessTokenRefreshError
140
141
140
140
33a8a9af80814844bffcd90c63dcf7888dc5980a
bigcode/the-stack
train
459f184051c19552d139b115
train
function
def _get_environment_variable_file(): application_default_credential_filename = ( os.environ.get(GOOGLE_APPLICATION_CREDENTIALS, None)) if application_default_credential_filename: if os.path.isfile(application_default_credential_filename): return application_default_credential_filen...
def _get_environment_variable_file():
application_default_credential_filename = ( os.environ.get(GOOGLE_APPLICATION_CREDENTIALS, None)) if application_default_credential_filename: if os.path.isfile(application_default_credential_filename): return application_default_credential_filename else: raise Ap...
.path.dirname(well_known_file) if not os.path.isdir(config_dir): raise OSError( 'Config directory does not exist: {0}'.format(config_dir)) credentials_data = credentials.serialization_data _save_private_file(well_known_file, credentials_data) def _get_environment_variable_file():
64
64
101
7
57
craigcitro/oauth2client
oauth2client/client.py
Python
_get_environment_variable_file
_get_environment_variable_file
1,343
1,355
1,343
1,343
15d145cce122f8b9081ecaf6aa8923f30d513f9b
bigcode/the-stack
train
2a44ad9db6d18893250c82c8
train
class
class FlowExchangeError(Error): """Error trying to exchange an authorization grant for an access token."""
class FlowExchangeError(Error):
"""Error trying to exchange an authorization grant for an access token."""
clean_headers = transport.clean_headers MemoryCache = transport.MemoryCache REFRESH_STATUS_CODES = transport.REFRESH_STATUS_CODES class SETTINGS(object): """Settings namespace for globally defined values.""" env_name = None class Error(Exception): """Base error for this module.""" class FlowExchangeErro...
63
64
20
6
57
craigcitro/oauth2client
oauth2client/client.py
Python
FlowExchangeError
FlowExchangeError
136
137
136
136
5c6903d870de43c44d1b388fcc7b57f5de0b25b6
bigcode/the-stack
train
7639965c207ce291a085384f
train
class
class SETTINGS(object): """Settings namespace for globally defined values.""" env_name = None
class SETTINGS(object):
"""Settings namespace for globally defined values.""" env_name = None
). _UTCNOW = datetime.datetime.utcnow # NOTE: These names were previously defined in this module but have been # moved into `oauth2client.transport`, clean_headers = transport.clean_headers MemoryCache = transport.MemoryCache REFRESH_STATUS_CODES = transport.REFRESH_STATUS_CODES class SETTINGS(object):
64
64
19
4
59
craigcitro/oauth2client
oauth2client/client.py
Python
SETTINGS
SETTINGS
127
129
127
127
317f4f9dace422b4b038e240c2e4a6c3cb489898
bigcode/the-stack
train
53e98a4c8803a66283183799
train
class
class AssertionCredentials(GoogleCredentials): """Abstract Credentials object used for OAuth 2.0 assertion grants. This credential does not require a flow to instantiate because it represents a two legged flow, and therefore has all of the required information to generate and refresh its own access tok...
class AssertionCredentials(GoogleCredentials):
"""Abstract Credentials object used for OAuth 2.0 assertion grants. This credential does not require a flow to instantiate because it represents a two legged flow, and therefore has all of the required information to generate and refresh its own access tokens. It must be subclassed to generate the ...
_fields(missing_fields): raise ApplicationDefaultCredentialsError( 'The following field(s) must be defined: ' + ', '.join(missing_fields)) def _raise_exception_for_reading_json(credential_file, extra_help, error): raise Applic...
150
150
502
7
143
craigcitro/oauth2client
oauth2client/client.py
Python
AssertionCredentials
AssertionCredentials
1,444
1,515
1,444
1,444
d147680ebe452290d80c7de308e68b325e490715
bigcode/the-stack
train
19c4e5d1e170cdf158a7a97b
train
class
class OAuth2Credentials(Credentials): """Credentials object for OAuth 2.0. Credentials can be applied to an httplib2.Http object using the authorize() method, which then adds the OAuth 2.0 access token to each request. OAuth2Credentials objects may be safely pickled and unpickled. """ @_helpe...
class OAuth2Credentials(Credentials):
"""Credentials object for OAuth 2.0. Credentials can be applied to an httplib2.Http object using the authorize() method, which then adds the OAuth 2.0 access token to each request. OAuth2Credentials objects may be safely pickled and unpickled. """ @_helpers.positional(8) def __init__(self...
when this is called. Args: credentials: Credentials, the credentials to store. """ raise NotImplementedError def locked_delete(self): """Delete a credential. The Storage lock must be held when this is called. """ raise NotImplementedError ...
256
256
3,538
7
249
craigcitro/oauth2client
oauth2client/client.py
Python
OAuth2Credentials
OAuth2Credentials
441
902
441
441
651682b660a333be2156b4376e478573c76be832
bigcode/the-stack
train
c991494b6a0adb5617ccf2aa
train
function
@_helpers.positional(4) def credentials_from_code(client_id, client_secret, scope, code, redirect_uri='postmessage', http=None, user_agent=None, token_uri=oauth2client.GOOGLE_TOKEN_URI, auth_uri=oauth2client.GOOGLE_A...
@_helpers.positional(4) def credentials_from_code(client_id, client_secret, scope, code, redirect_uri='postmessage', http=None, user_agent=None, token_uri=oauth2client.GOOGLE_TOKEN_URI, auth_uri=oauth2client.GOOGLE_A...
"""Exchanges an authorization code for an OAuth2Credentials object. Args: client_id: string, client identifier. client_secret: string, client secret. scope: string or iterable of strings, scope(s) to request. code: string, An authorization code, most likely passed down from ...
libs raise different exceptions, # so we just do a catch-all here resp = _helpers.parse_unique_urlencoded(content) # some providers respond with 'expires', others with 'expires_in' if resp and 'expires' in resp: resp['expires_in'] = resp.pop('expires') return resp @_helpers.positi...
185
185
617
117
67
craigcitro/oauth2client
oauth2client/client.py
Python
credentials_from_code
credentials_from_code
1,617
1,680
1,617
1,627
5e5093b2c035409ab118e8be895d9e11c5780f9c
bigcode/the-stack
train
ad287edae7f1228cfa64bfa4
train
class
class Storage(object): """Base class for all Storage objects. Store and retrieve a single credential. This class supports locking such that multiple processes and threads can operate on a single store. """ def __init__(self, lock=None): """Create a Storage instance. Args: ...
class Storage(object):
"""Base class for all Storage objects. Store and retrieve a single credential. This class supports locking such that multiple processes and threads can operate on a single store. """ def __init__(self, lock=None): """Create a Storage instance. Args: lock: An optiona...
googleapiclient', '') module_obj = __import__(module_name) module_obj = __import__(module_name, fromlist=module_name.split('.')[:-1]) kls = getattr(module_obj, data['_class']) return kls.from_json(json_data_as_unicode) @classmethod def from_j...
155
155
518
4
150
craigcitro/oauth2client
oauth2client/client.py
Python
Storage
Storage
336
438
336
336
96369ddb8c4c02360d6b80a77edafbaa1523dd10
bigcode/the-stack
train
d68520211771ff922159d94d
train
class
class CryptoUnavailableError(Error, NotImplementedError): """Raised when a crypto library is required, but none is available."""
class CryptoUnavailableError(Error, NotImplementedError):
"""Raised when a crypto library is required, but none is available."""
NonAsciiHeaderError(Error): """Header names and values must be ASCII strings.""" class ApplicationDefaultCredentialsError(Error): """Error retrieving the Application Default Credentials.""" class OAuth2DeviceCodeError(Error): """Error trying to retrieve a device code.""" class CryptoUnavailableError(Er...
63
64
25
10
53
craigcitro/oauth2client
oauth2client/client.py
Python
CryptoUnavailableError
CryptoUnavailableError
179
180
179
179
14ecbbc0be3c06c759fff3338384a3cd7477b4fa
bigcode/the-stack
train
001dc67b8ffb3edc3bd71c00
train
function
def _in_gce_environment(): """Detect if the code is running in the Compute Engine environment. Returns: True if running in the GCE environment, False otherwise. """ if SETTINGS.env_name is not None: return SETTINGS.env_name == 'GCE_PRODUCTION' if NO_GCE_CHECK != 'True' and _detect_...
def _in_gce_environment():
"""Detect if the code is running in the Compute Engine environment. Returns: True if running in the GCE environment, False otherwise. """ if SETTINGS.env_name is not None: return SETTINGS.env_name == 'GCE_PRODUCTION' if NO_GCE_CHECK != 'True' and _detect_gce_environment(): ...
, '') if server_software.startswith('Google App Engine/'): SETTINGS.env_name = 'GAE_PRODUCTION' return True elif server_software.startswith('Development/'): SETTINGS.env_name = 'GAE_LOCAL' return True return False def _in_gce_environment():
64
64
96
7
56
craigcitro/oauth2client
oauth2client/client.py
Python
_in_gce_environment
_in_gce_environment
1,033
1,045
1,033
1,033
9143570127dc006736fe677b2f20d87288b2b4bf
bigcode/the-stack
train
93887cfd469915c9cf3af09e
train
function
def _save_private_file(filename, json_contents): """Saves a file with read-write permissions on for the owner. Args: filename: String. Absolute path to file. json_contents: JSON serializable object to be saved. """ temp_filename = tempfile.mktemp() file_desc = os.open(temp_filename,...
def _save_private_file(filename, json_contents):
"""Saves a file with read-write permissions on for the owner. Args: filename: String. Absolute path to file. json_contents: JSON serializable object to be saved. """ temp_filename = tempfile.mktemp() file_desc = os.open(temp_filename, os.O_WRONLY | os.O_CREAT, 0o600) with os.fdo...
_stream() method)') _raise_exception_for_reading_json(credential_filename, extra_help, error) else: raise ApplicationDefaultCredentialsError( 'The parameter passed to t...
63
64
129
10
53
craigcitro/oauth2client
oauth2client/client.py
Python
_save_private_file
_save_private_file
1,303
1,315
1,303
1,303
8ff72fe7720ceec8475701f91af77fd323ee30c7
bigcode/the-stack
train
666fd63398ce17cc8f299eab
train
class
class TestUnique: def test_unique_1d(self): def check_all(a, b, i1, i2, c, dt): base_msg = 'check {0} failed for type {1}' msg = base_msg.format('values', dt) v = unique(a) assert_array_equal(v, b, msg) msg = base_msg.format('return_index', dt)...
class TestUnique:
def test_unique_1d(self): def check_all(a, b, i1, i2, c, dt): base_msg = 'check {0} failed for type {1}' msg = base_msg.format('values', dt) v = unique(a) assert_array_equal(v, b, msg) msg = base_msg.format('return_index', dt) v, j =...
(setdiff1d(a, []).dtype, np.uint32) def test_setdiff1d_unique(self): a = np.array([3, 2, 1]) b = np.array([7, 5, 2]) expected = np.array([3, 1]) actual = setdiff1d(a, b, assume_unique=True) assert_equal(actual, expected) def test_setdiff1d_char_array(self): a = ...
256
256
2,849
4
252
abhayaman669/numpy
numpy/lib/tests/test_arraysetops.py
Python
TestUnique
TestUnique
453
710
453
454
59184dc6136d4fa4f5523e981c0c930ffca148fc
bigcode/the-stack
train
dbdc336f28bb32c67f3b750b
train
class
class TestSetOps: def test_intersect1d(self): # unique inputs a = np.array([5, 7, 1, 2]) b = np.array([2, 4, 3, 1, 5]) ec = np.array([1, 2, 5]) c = intersect1d(a, b, assume_unique=True) assert_array_equal(c, ec) # non-unique inputs a = np.array([5, ...
class TestSetOps:
def test_intersect1d(self): # unique inputs a = np.array([5, 7, 1, 2]) b = np.array([2, 4, 3, 1, 5]) ec = np.array([1, 2, 5]) c = intersect1d(a, b, assume_unique=True) assert_array_equal(c, ec) # non-unique inputs a = np.array([5, 5, 7, 1, 2]) ...
"""Test functions for 1D array set operations. """ import numpy as np from numpy.testing import (assert_array_equal, assert_equal, assert_raises, assert_raises_regex) from numpy.lib.arraysetops import ( ediff1d, intersect1d, setxor1d, union1d, setdiff1d, unique, in1d, isin ) import ...
89
256
4,814
5
83
abhayaman669/numpy
numpy/lib/tests/test_arraysetops.py
Python
TestSetOps
TestSetOps
14
450
14
15
e9db9f0fe89b9100d42ae4031dd46a222d4465c2
bigcode/the-stack
train
95c5ab80b0185d0f14b62c36
train
class
class Solution: def wordBreak(self, s: str, wordDict: List[str]) -> List[str]: words = set(wordDict) @lru_cache(None) def helper(lo): if lo == len(s): return [[]] ans = [] for i in range(lo + 1, len(s) + 1): word = s[lo:i] ...
class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> List[str]: words = set(wordDict) @lru_cache(None) def helper(lo): if lo == len(s): return [[]] ans = [] for i in range(lo + 1, len(s) + 1): word = s[lo:i] i...
from functools import lru_cache class Solution:
10
64
129
3
6
wyaadarsh/LeetCode-Solutions
Python3/0140-Word-Break-II/soln-1.py
Python
Solution
Solution
2
17
2
2
7241538818c108c640caebecbec257f27ab8ff80
bigcode/the-stack
train
0fc0152b6f2ec3004595c5a2
train
class
class Comment(models.Model): name = models.CharField(max_length=50, verbose_name=u'姓名') email = models.EmailField(max_length=255, verbose_name=u'邮箱') url = models.URLField(blank=True, verbose_name=u'链接') text = models.TextField(verbose_name=u'内容') created_time = models.DateTimeField(auto_now_add=Tr...
class Comment(models.Model):
name = models.CharField(max_length=50, verbose_name=u'姓名') email = models.EmailField(max_length=255, verbose_name=u'邮箱') url = models.URLField(blank=True, verbose_name=u'链接') text = models.TextField(verbose_name=u'内容') created_time = models.DateTimeField(auto_now_add=True, verbose_name=u'留言创建时间') ...
from django.db import models # Create your models here. class Comment(models.Model):
17
64
119
5
12
LittleBai0606/django_blog2
comments/models.py
Python
Comment
Comment
5
16
5
6
212ca1cb08133f4ea4fcfcc8b95b2e862bb665ae
bigcode/the-stack
train
24e7ab34d90d5e14eff1e2fe
train
function
@decorators.public.init @decorators.delete.init def init(update, context): bot = context.bot languages(update,context) chat = update.effective_message.chat_id chat_title = update.message.chat.title list_buttons = [] list_buttons.append(InlineKeyboardButton(languages.rules_button, callback_data='...
@decorators.public.init @decorators.delete.init def init(update, context):
bot = context.bot languages(update,context) chat = update.effective_message.chat_id chat_title = update.message.chat.title list_buttons = [] list_buttons.append(InlineKeyboardButton(languages.rules_button, callback_data='openRules')) menu = build_menu(list_buttons,1) bot.send_message(cha...
# Copyright SquirrelNetwork from core import decorators from core.utilities.menu import build_menu from languages.getLang import languages from core.database.repository.group import GroupRepository from telegram import InlineKeyboardButton, InlineKeyboardMarkup @decorators.public.init @decorators.delete.init def init(u...
64
64
111
18
45
Smashulica/nebula8
core/commands/public/rules.py
Python
init
init
11
21
11
13
00400421ce77e08e7716d84282617c3963791d22
bigcode/the-stack
train
ce7f5c4762d892b99444b690
train
function
def update_rules(update,context): query = update.callback_query if query.data == 'openRules': languages(update,context) chat = update.effective_message.chat_id row = GroupRepository().getById([chat]) query.edit_message_text(languages.rules.format(row['rules_text']),parse_mode='HT...
def update_rules(update,context):
query = update.callback_query if query.data == 'openRules': languages(update,context) chat = update.effective_message.chat_id row = GroupRepository().getById([chat]) query.edit_message_text(languages.rules.format(row['rules_text']),parse_mode='HTML')
list_buttons.append(InlineKeyboardButton(languages.rules_button, callback_data='openRules')) menu = build_menu(list_buttons,1) bot.send_message(chat,languages.rules_main.format(chat_title,chat),reply_markup=InlineKeyboardMarkup(menu),parse_mode='HTML') def update_rules(update,context):
64
64
70
7
57
Smashulica/nebula8
core/commands/public/rules.py
Python
update_rules
update_rules
24
30
24
24
0bfddf156213ca76f7c44ff1b07ed5df461a1653
bigcode/the-stack
train
3ab760f389d194d2f4b812d5
train
function
def Prim(G,vs): MST=NewAdjMatrix(G) Vg=[vs] Vr=list(G.keys()) Vr.remove(vs) while Vr: me=None for u in Vg: for v in Vr: if G[u][v]!=0 and (not me or me[2]>G[u][v]): me=(u,v,G[u][v]) if me: Vg.append(me[1]) ...
def Prim(G,vs):
MST=NewAdjMatrix(G) Vg=[vs] Vr=list(G.keys()) Vr.remove(vs) while Vr: me=None for u in Vg: for v in Vr: if G[u][v]!=0 and (not me or me[2]>G[u][v]): me=(u,v,G[u][v]) if me: Vg.append(me[1]) Vr.remove(me[1...
from General import * def Prim(G,vs):
10
64
140
6
4
FER-NASP/AdvancedAlgorithms
Prim.py
Python
Prim
Prim
3
18
3
3
2666011278dbcebdb24b5d7e85bb6bc28ac38861
bigcode/the-stack
train
dd7385dd94d4eb56d4b177f7
train
class
class GoodsChannelGroup(BaseModel): """商品频道组""" name = models.CharField(max_length=20, verbose_name='频道组名') class Meta: db_table = 'tb_channel_group' verbose_name = '商品频道组' verbose_name_plural = verbose_name def __str__(self): return self.name
class GoodsChannelGroup(BaseModel):
"""商品频道组""" name = models.CharField(max_length=20, verbose_name='频道组名') class Meta: db_table = 'tb_channel_group' verbose_name = '商品频道组' verbose_name_plural = verbose_name def __str__(self): return self.name
=True, blank=True, on_delete=models.CASCADE, verbose_name='父类别') class Meta: db_table = 'tb_goods_category' verbose_name = '商品类别' verbose_name_plural = verbose_name def __str__(self): return self.name class GoodsChannelGroup(BaseModel):
64
64
73
7
56
ct891719746/meiduo_project
meiduo_mall/meiduo_mall/apps/goods/models.py
Python
GoodsChannelGroup
GoodsChannelGroup
20
30
20
20
1046d445062efb13827e34a7ac6d5f2241f5ab8f
bigcode/the-stack
train
f78a7a089730eacb1e2e5d26
train
class
class SPUSpecification(BaseModel): """商品SPU规格""" spu = models.ForeignKey(SPU, on_delete=models.CASCADE, related_name='specs', verbose_name='商品SPU') name = models.CharField(max_length=20, verbose_name='规格名称') class Meta: db_table = 'tb_spu_specification' verbose_name = '商品SPU规格' ...
class SPUSpecification(BaseModel):
"""商品SPU规格""" spu = models.ForeignKey(SPU, on_delete=models.CASCADE, related_name='specs', verbose_name='商品SPU') name = models.CharField(max_length=20, verbose_name='规格名称') class Meta: db_table = 'tb_spu_specification' verbose_name = '商品SPU规格' verbose_name_plural = verbose_name ...
图片') class Meta: db_table = 'tb_sku_image' verbose_name = 'SKU图片' verbose_name_plural = verbose_name def __str__(self): return '%s %s' % (self.sku.name, self.id) class SPUSpecification(BaseModel):
64
64
117
8
56
ct891719746/meiduo_project
meiduo_mall/meiduo_mall/apps/goods/models.py
Python
SPUSpecification
SPUSpecification
124
135
124
124
9737bd5f6a3067f293bdf05414448d17eb64076a
bigcode/the-stack
train
2abdb065caa1a9725eb3055d
train
class
class SpecificationOption(BaseModel): """规格选项""" spec = models.ForeignKey(SPUSpecification, related_name='options', on_delete=models.CASCADE, verbose_name='规格') value = models.CharField(max_length=20, verbose_name='选项值') class Meta: db_table = 'tb_specification_option' verbose_name = '规...
class SpecificationOption(BaseModel):
"""规格选项""" spec = models.ForeignKey(SPUSpecification, related_name='options', on_delete=models.CASCADE, verbose_name='规格') value = models.CharField(max_length=20, verbose_name='选项值') class Meta: db_table = 'tb_specification_option' verbose_name = '规格选项' verbose_name_plural = ver...
class Meta: db_table = 'tb_spu_specification' verbose_name = '商品SPU规格' verbose_name_plural = verbose_name def __str__(self): return '%s: %s' % (self.spu.name, self.name) class SpecificationOption(BaseModel):
64
64
111
6
58
ct891719746/meiduo_project
meiduo_mall/meiduo_mall/apps/goods/models.py
Python
SpecificationOption
SpecificationOption
138
149
138
138
1fa08444466e6c423176b25a197e5887ce2b2732
bigcode/the-stack
train
fa9658ac66fab3e761429907
train
class
class Brand(BaseModel): """品牌""" name = models.CharField(max_length=20, verbose_name='名称') logo = models.ImageField(verbose_name='Logo图片') first_letter = models.CharField(max_length=1, verbose_name='品牌首字母') class Meta: db_table = 'tb_brand' verbose_name = '品牌' verbose_name_p...
class Brand(BaseModel):
"""品牌""" name = models.CharField(max_length=20, verbose_name='名称') logo = models.ImageField(verbose_name='Logo图片') first_letter = models.CharField(max_length=1, verbose_name='品牌首字母') class Meta: db_table = 'tb_brand' verbose_name = '品牌' verbose_name_plural = verbose_name ...
页面链接') sequence = models.IntegerField(verbose_name='组内顺序') class Meta: db_table = 'tb_goods_channel' verbose_name = '商品频道' verbose_name_plural = verbose_name def __str__(self): return self.category.name class Brand(BaseModel):
64
64
96
5
58
ct891719746/meiduo_project
meiduo_mall/meiduo_mall/apps/goods/models.py
Python
Brand
Brand
49
61
49
49
f7bcc927fca35d3c383b54a5f3e969b8ebc45475
bigcode/the-stack
train
bd69a598cbe6ca993d655bf6
train
class
class GoodsVisitCount(BaseModel): """统计分类商品访问量模型类""" category = models.ForeignKey(GoodsCategory, on_delete=models.CASCADE, verbose_name='商品分类') count = models.IntegerField(verbose_name='访问量', default=0) date = models.DateField(auto_now_add=True, verbose_name='统计日期') class Meta: db_table = '...
class GoodsVisitCount(BaseModel):
"""统计分类商品访问量模型类""" category = models.ForeignKey(GoodsCategory, on_delete=models.CASCADE, verbose_name='商品分类') count = models.IntegerField(verbose_name='访问量', default=0) date = models.DateField(auto_now_add=True, verbose_name='统计日期') class Meta: db_table = 'tb_goods_visit' verbose_na...
_table = 'tb_sku_specification' verbose_name = 'SKU规格' verbose_name_plural = verbose_name def __str__(self): return '%s: %s - %s' % (self.sku, self.spec.name, self.option.value) class GoodsVisitCount(BaseModel):
64
64
103
7
57
ct891719746/meiduo_project
meiduo_mall/meiduo_mall/apps/goods/models.py
Python
GoodsVisitCount
GoodsVisitCount
166
175
166
166
d63524d92cc7d610e8199dc7008b6ecfb1923da6
bigcode/the-stack
train
38da6d58a9bc3f93ebc019c1
train
class
class SPU(BaseModel): """商品SPU""" name = models.CharField(max_length=50, verbose_name='名称') brand = models.ForeignKey(Brand, on_delete=models.PROTECT, verbose_name='品牌') category1 = models.ForeignKey(GoodsCategory, on_delete=models.PROTECT, related_name='cat1_spu', verbose_name='一级类别') category2 = m...
class SPU(BaseModel):
"""商品SPU""" name = models.CharField(max_length=50, verbose_name='名称') brand = models.ForeignKey(Brand, on_delete=models.PROTECT, verbose_name='品牌') category1 = models.ForeignKey(GoodsCategory, on_delete=models.PROTECT, related_name='cat1_spu', verbose_name='一级类别') category2 = models.ForeignKey(Goods...
') logo = models.ImageField(verbose_name='Logo图片') first_letter = models.CharField(max_length=1, verbose_name='品牌首字母') class Meta: db_table = 'tb_brand' verbose_name = '品牌' verbose_name_plural = verbose_name def __str__(self): return self.name class SPU(BaseModel):
78
78
261
6
71
ct891719746/meiduo_project
meiduo_mall/meiduo_mall/apps/goods/models.py
Python
SPU
SPU
64
83
64
64
5ac6ea8477d0d5fa9616ac74ebe6695c04a2a98d
bigcode/the-stack
train
38cb5476fa24ef3078f8665e
train
class
class GoodsCategory(BaseModel): """商品类别""" name = models.CharField(max_length=10, verbose_name='名称') parent = models.ForeignKey('self', related_name='subs', null=True, blank=True, on_delete=models.CASCADE, verbose_name='父类别') class Meta: db_table = 'tb_goods_category' verbose_name = '商品...
class GoodsCategory(BaseModel):
"""商品类别""" name = models.CharField(max_length=10, verbose_name='名称') parent = models.ForeignKey('self', related_name='subs', null=True, blank=True, on_delete=models.CASCADE, verbose_name='父类别') class Meta: db_table = 'tb_goods_category' verbose_name = '商品类别' verbose_name_plural ...
from django.db import models from meiduo_mall.utils.models import BaseModel class GoodsCategory(BaseModel):
23
64
99
6
16
ct891719746/meiduo_project
meiduo_mall/meiduo_mall/apps/goods/models.py
Python
GoodsCategory
GoodsCategory
6
17
6
6
78ea34dec187020d188859dd194af7b384bf9644
bigcode/the-stack
train
346d79a4c4294d6ddeb8267b
train
class
class SKUImage(BaseModel): """SKU图片""" sku = models.ForeignKey(SKU, on_delete=models.CASCADE, verbose_name='sku') image = models.ImageField(verbose_name='图片') class Meta: db_table = 'tb_sku_image' verbose_name = 'SKU图片' verbose_name_plural = verbose_name def __str__(self): ...
class SKUImage(BaseModel):
"""SKU图片""" sku = models.ForeignKey(SKU, on_delete=models.CASCADE, verbose_name='sku') image = models.ImageField(verbose_name='图片') class Meta: db_table = 'tb_sku_image' verbose_name = 'SKU图片' verbose_name_plural = verbose_name def __str__(self): return '%s %s' % (s...
verbose_name='默认图片') class Meta: db_table = 'tb_sku' verbose_name = '商品SKU' verbose_name_plural = verbose_name def __str__(self): return '%s: %s' % (self.id, self.name) class SKUImage(BaseModel):
64
64
95
6
58
ct891719746/meiduo_project
meiduo_mall/meiduo_mall/apps/goods/models.py
Python
SKUImage
SKUImage
110
121
110
110
a04356d61a1a7cdc79e677dea4393c48613985b2
bigcode/the-stack
train
4b02457251c1952e8013b4c3
train
class
class SKU(BaseModel): """商品SKU""" name = models.CharField(max_length=50, verbose_name='名称') caption = models.CharField(max_length=100, verbose_name='副标题') spu = models.ForeignKey(SPU, on_delete=models.CASCADE, verbose_name='商品') category = models.ForeignKey(GoodsCategory, on_delete=models.PROTECT, v...
class SKU(BaseModel):
"""商品SKU""" name = models.CharField(max_length=50, verbose_name='名称') caption = models.CharField(max_length=100, verbose_name='副标题') spu = models.ForeignKey(SPU, on_delete=models.CASCADE, verbose_name='商品') category = models.ForeignKey(GoodsCategory, on_delete=models.PROTECT, verbose_name='从属类别') ...
.TextField(default='', verbose_name='详细介绍') desc_pack = models.TextField(default='', verbose_name='包装信息') desc_service = models.TextField(default='', verbose_name='售后服务') class Meta: db_table = 'tb_spu' verbose_name = '商品SPU' verbose_name_plural = verbose_name def __str__(self)...
88
88
296
5
82
ct891719746/meiduo_project
meiduo_mall/meiduo_mall/apps/goods/models.py
Python
SKU
SKU
86
107
86
86
5e053bf61b8bc249a13674348725944fa6ae6ca8
bigcode/the-stack
train
2bb5643d7bb31f1c72e8fbb4
train
class
class GoodsChannel(BaseModel): """商品频道""" group = models.ForeignKey(GoodsChannelGroup, verbose_name='频道组名') category = models.ForeignKey(GoodsCategory, on_delete=models.CASCADE, verbose_name='顶级商品类别') url = models.CharField(max_length=50, verbose_name='频道页面链接') sequence = models.IntegerField(verbose...
class GoodsChannel(BaseModel):
"""商品频道""" group = models.ForeignKey(GoodsChannelGroup, verbose_name='频道组名') category = models.ForeignKey(GoodsCategory, on_delete=models.CASCADE, verbose_name='顶级商品类别') url = models.CharField(max_length=50, verbose_name='频道页面链接') sequence = models.IntegerField(verbose_name='组内顺序') class Meta: ...
= models.CharField(max_length=20, verbose_name='频道组名') class Meta: db_table = 'tb_channel_group' verbose_name = '商品频道组' verbose_name_plural = verbose_name def __str__(self): return self.name class GoodsChannel(BaseModel):
64
64
126
6
57
ct891719746/meiduo_project
meiduo_mall/meiduo_mall/apps/goods/models.py
Python
GoodsChannel
GoodsChannel
33
46
33
33
1a6d54fa0807657e6ae6c52f93214b568fc9b06f
bigcode/the-stack
train
c24e480a3d2d7ec6412c93ea
train
class
class SKUSpecification(BaseModel): """SKU具体规格""" sku = models.ForeignKey(SKU, related_name='specs', on_delete=models.CASCADE, verbose_name='sku') spec = models.ForeignKey(SPUSpecification, on_delete=models.PROTECT, verbose_name='规格名称') option = models.ForeignKey(SpecificationOption, on_delete=models.PRO...
class SKUSpecification(BaseModel):
"""SKU具体规格""" sku = models.ForeignKey(SKU, related_name='specs', on_delete=models.CASCADE, verbose_name='sku') spec = models.ForeignKey(SPUSpecification, on_delete=models.PROTECT, verbose_name='规格名称') option = models.ForeignKey(SpecificationOption, on_delete=models.PROTECT, verbose_name='规格值') clas...
值') class Meta: db_table = 'tb_specification_option' verbose_name = '规格选项' verbose_name_plural = verbose_name def __str__(self): return '%s - %s' % (self.spec, self.value) class SKUSpecification(BaseModel):
64
64
149
8
56
ct891719746/meiduo_project
meiduo_mall/meiduo_mall/apps/goods/models.py
Python
SKUSpecification
SKUSpecification
152
164
152
152
46589a914f843a92efaa1ac88408f0921b6cf1a5
bigcode/the-stack
train
a47322fa9264719fbb5588a9
train
function
def db_version(): """Display the current database version.""" return IMPL.db_version()
def db_version():
"""Display the current database version.""" return IMPL.db_version()
Pluggable('backend', config_group='database', sqlalchemy='nova.db.sqlalchemy.migration') INIT_VERSION = 132 def db_sync(version=None): """Migrate the database to `version` or the most recent version.""" return IMPL.db_sync(version=version) def db_version(...
64
64
19
4
60
bopopescu/nova_audit
nova/db/migration.py
Python
db_version
db_version
36
38
36
36
bae5a91fbd5afa6b39d486bf7ca87212d77019c1
bigcode/the-stack
train
584c73d3b762c279e40b7293
train
function
def db_sync(version=None): """Migrate the database to `version` or the most recent version.""" return IMPL.db_sync(version=version)
def db_sync(version=None):
"""Migrate the database to `version` or the most recent version.""" return IMPL.db_sync(version=version)
language governing permissions and limitations # under the License. """Database setup and migration commands.""" from nova import utils IMPL = utils.LazyPluggable('backend', config_group='database', sqlalchemy='nova.db.sqlalchemy.migration') INIT_VERSION = ...
64
64
32
6
57
bopopescu/nova_audit
nova/db/migration.py
Python
db_sync
db_sync
31
33
31
31
1b89f2090fb7e55a619f528ebb03aa3a839e0a4a
bigcode/the-stack
train
3e3a1dcebe668ed8d1e0f9fb
train
class
class LC_Master(Common_to_all_POMs): """ This class implements the Logistic Classifier model, run at Master node. It inherits from Common_to_all_POMs. """ def __init__(self, master_address, workers_addresses, model_type, comms, logger, verbose=True, **kwargs): """ Create a :class...
class LC_Master(Common_to_all_POMs):
""" This class implements the Logistic Classifier model, run at Master node. It inherits from Common_to_all_POMs. """ def __init__(self, master_address, workers_addresses, model_type, comms, logger, verbose=True, **kwargs): """ Create a :class:`LC_Master` instance. Para...
NI, 1)) y = ((np.sign(np.dot(X, w)) + 1) / 2.0).ravel() export_model.fit(X, y) export_model.coef_ = self.w[1:].T export_model.intercept_ = self.w[0] from sklearn2pmml import s...
256
256
5,984
10
245
Musketeer-H2020/MMLL-Robust
MMLL/models/POM4/LC/LC.py
Python
LC_Master
LC_Master
161
807
161
161
b403b2699b68adbba4128753f5114c501de8cd86
bigcode/the-stack
train
30c9cdd295a142a671c8129c
train
class
class Model(): """ Logistic Classifier model. """ def __init__(self): self.w = None self.is_trained = False self.supported_formats = ['pkl', 'onnx', 'pmml'] t = time.time() seed = int((t - int(t)) * 10000) np.random.seed(seed=seed) def sig...
class Model():
""" Logistic Classifier model. """ def __init__(self): self.w = None self.is_trained = False self.supported_formats = ['pkl', 'onnx', 'pmml'] t = time.time() seed = int((t - int(t)) * 10000) np.random.seed(seed=seed) def sigm(self, x): ...
# -*- coding: utf-8 -*- ''' Logistic Classifier model under POM4 ''' __author__ = "Angel Navia-Vázquez" __date__ = "Dec. 2020" import numpy as np from MMLL.models.Common_to_all_POMs import Common_to_all_POMs from transitions import State from transitions.extensions import GraphMachine from sklearn.line...
118
256
1,280
3
114
Musketeer-H2020/MMLL-Robust
MMLL/models/POM4/LC/LC.py
Python
Model
Model
20
158
20
20
517a8779ffdd4a9836bcf867ca7846169388129a
bigcode/the-stack
train
10427a48bc083a8f7c4c33a0
train
class
class LC_Crypto(Common_to_all_POMs): ''' Class implementing Logistic Classification, run at Crypto ''' def __init__(self, cryptonode_address, master_address, model_type, comms, logger, verbose=True): """ Create a :class:`LR_Crypto` instance. Parameters -----...
class LC_Crypto(Common_to_all_POMs):
''' Class implementing Logistic Classification, run at Crypto ''' def __init__(self, cryptonode_address, master_address, model_type, comms, logger, verbose=True): """ Create a :class:`LR_Crypto` instance. Parameters ---------- master_address: string ...
% (packet['action'], sender, str(packet['message_id'])), verbose=False) except: self.display('WORKER MISSING message_id in %s from %s' % (packet['action'], sender), verbose=False) pass try: # Exit the process if packet['action'...
256
256
863
11
244
Musketeer-H2020/MMLL-Robust
MMLL/models/POM4/LC/LC.py
Python
LC_Crypto
LC_Crypto
1,002
1,127
1,002
1,002
0c459ad172e32efcb9c94ca5059b6703ed9dc806
bigcode/the-stack
train
26e6f67db756cb6ddc96e9cb
train
class
class LC_Worker(Common_to_all_POMs): ''' Class implementing Linear Regression, run at Worker ''' def __init__(self, master_address, worker_address, model_type, comms, logger, verbose=True, Xtr_b=None, ytr=None, cryptonode_address=None): """ Create a :class:`LC_Worker` instance....
class LC_Worker(Common_to_all_POMs):
''' Class implementing Linear Regression, run at Worker ''' def __init__(self, master_address, worker_address, model_type, comms, logger, verbose=True, Xtr_b=None, ytr=None, cryptonode_address=None): """ Create a :class:`LC_Worker` instance. Parameters ------...
self.grads_dict.update({sender: packet['data']['grad_encr']}) if packet['action'] == 'ACK_sent_XB_bl_encr_dict': self.XB_bl_encr_dict = packet['data']['XB_bl_encr_dict'] self.FSMmaster.done_mult_XB(self) if packet['action'] == 'ACK_sent_dec...
256
256
1,491
11
244
Musketeer-H2020/MMLL-Robust
MMLL/models/POM4/LC/LC.py
Python
LC_Worker
LC_Worker
813
995
813
813
4d618fe6717cc4f017d7f7e8ff4372a218e3507f
bigcode/the-stack
train
cab19fbcc3187f49c3a64dff
train
function
def test_equivocating_node_shutdown_and_other_nodes_are_working_ok(three_node_network): network = three_node_network nodes = network.docker_nodes account = GENESIS_ACCOUNT block_hash = nodes[0].deploy_and_get_block_hash(account, Contract.HELLO_NAME_DEFINE) wait_for_block_hash_propagated_to_all_node...
def test_equivocating_node_shutdown_and_other_nodes_are_working_ok(three_node_network):
network = three_node_network nodes = network.docker_nodes account = GENESIS_ACCOUNT block_hash = nodes[0].deploy_and_get_block_hash(account, Contract.HELLO_NAME_DEFINE) wait_for_block_hash_propagated_to_all_nodes(nodes, block_hash) # Clear state of node-0 so when we restart it # it doesn't...
import pytest from itertools import count from casperlabs_local_net.casperlabs_accounts import GENESIS_ACCOUNT from casperlabs_local_net.common import Contract from casperlabs_local_net.wait import wait_for_block_hash_propagated_to_all_nodes def test_equivocating_node_shutdown_and_other_nodes_are_working_ok(three_node_...
72
196
654
20
51
arcolife/CasperLabs
integration-testing/test/test_equivocating_node_shutdown.py
Python
test_equivocating_node_shutdown_and_other_nodes_are_working_ok
test_equivocating_node_shutdown_and_other_nodes_are_working_ok
8
73
8
8
2f7ecce27abe43f1361f6c526da7abab14b5c2f6
bigcode/the-stack
train
c3f3a02a67cde8e733ee8217
train
function
def move_mouse_when_unable_to_move(expected_mouse_position): if expected_mouse_position != mouse.position: mouse.position = (0, 0)
def move_mouse_when_unable_to_move(expected_mouse_position):
if expected_mouse_position != mouse.position: mouse.position = (0, 0)
: MOVE_MOUSE = True print(get_now_timestamp(), "Mouse is enabled, moving", PIXELS_TO_MOVE, 'pixels') print(get_now_timestamp(), 'Running every', str(move_mouse_every_seconds), 'seconds') print('--------') def move_mouse_when_unable_to_move(expected_mouse_position):
64
64
31
12
52
ldpmatic/keep-presence
keep-presence.py
Python
move_mouse_when_unable_to_move
move_mouse_when_unable_to_move
67
69
67
67
2d7dc9636635b599f62badfd5f82978db1a295fb
bigcode/the-stack
train
4e4353d75be0dc95cd749765
train
function
def press_shift_key(): keyboard.press(Key.shift) keyboard.release(Key.shift) print(get_now_timestamp(), 'Shift key pressed')
def press_shift_key():
keyboard.press(Key.shift) keyboard.release(Key.shift) print(get_now_timestamp(), 'Shift key pressed')
_TO_MOVE new_position = (new_x, new_y) mouse.position = new_position move_mouse_when_unable_to_move(new_position) current_position = mouse.position print(get_now_timestamp(), 'Moved mouse to: ', current_position) return current_position def press_shift_key():
64
64
28
5
58
ldpmatic/keep-presence
keep-presence.py
Python
press_shift_key
press_shift_key
88
91
88
88
4a3747f018b65f85ce0034a20ae0d04cd9941b45
bigcode/the-stack
train
37da72c319f3bacbb95299c7
train
function
def define_custom_seconds(): global move_mouse_every_seconds, PIXELS_TO_MOVE, PRESS_SHIFT_KEY, MOVE_MOUSE parser = argparse.ArgumentParser( description="This program moves the mouse or press a key when it detects that you are away. " "It won't do anything if you are using your compu...
def define_custom_seconds():
global move_mouse_every_seconds, PIXELS_TO_MOVE, PRESS_SHIFT_KEY, MOVE_MOUSE parser = argparse.ArgumentParser( description="This program moves the mouse or press a key when it detects that you are away. " "It won't do anything if you are using your computer. " "U...
import argparse import time from datetime import datetime from pynput.mouse import Controller as MouseController from pynput.keyboard import Key, Controller as KeyboardController mouse = MouseController() keyboard = KeyboardController() MOVE_MOUSE = False PRESS_SHIFT_KEY = False PIXELS_TO_MOVE = 1 move_mouse_every_s...
75
126
420
5
69
ldpmatic/keep-presence
keep-presence.py
Python
define_custom_seconds
define_custom_seconds
17
64
17
17
7b702348da83a70ebb08cba87a08175348e2bbcf
bigcode/the-stack
train
51ac40a2f27cd53d2fe54c35
train
function
def get_now_timestamp(): now = datetime.now() return now.strftime("%H:%M:%S")
def get_now_timestamp():
now = datetime.now() return now.strftime("%H:%M:%S")
_move(new_position) current_position = mouse.position print(get_now_timestamp(), 'Moved mouse to: ', current_position) return current_position def press_shift_key(): keyboard.press(Key.shift) keyboard.release(Key.shift) print(get_now_timestamp(), 'Shift key pressed') def get_now_timestamp()...
64
64
22
5
59
ldpmatic/keep-presence
keep-presence.py
Python
get_now_timestamp
get_now_timestamp
94
96
94
94
05b47886b4f88569eaefe79d3294cad11aa3282c
bigcode/the-stack
train
82a2073300f370d4e167e1ba
train
function
def move_mouse(): new_x = currentPosition[0] + PIXELS_TO_MOVE new_y = currentPosition[1] + PIXELS_TO_MOVE new_position = (new_x, new_y) mouse.position = new_position move_mouse_when_unable_to_move(new_position) current_position = mouse.position print(get_now_timestamp(), 'Moved mouse to:...
def move_mouse():
new_x = currentPosition[0] + PIXELS_TO_MOVE new_y = currentPosition[1] + PIXELS_TO_MOVE new_position = (new_x, new_y) mouse.position = new_position move_mouse_when_unable_to_move(new_position) current_position = mouse.position print(get_now_timestamp(), 'Moved mouse to: ', current_positi...
_MOVE, 'pixels') print(get_now_timestamp(), 'Running every', str(move_mouse_every_seconds), 'seconds') print('--------') def move_mouse_when_unable_to_move(expected_mouse_position): if expected_mouse_position != mouse.position: mouse.position = (0, 0) def move_mouse():
64
64
90
4
60
ldpmatic/keep-presence
keep-presence.py
Python
move_mouse
move_mouse
72
85
72
72
bdb472a3516da5911464eb1857c871d0c653c41b
bigcode/the-stack
train
0d380075a52a24f876851773
train
function
def execute_keep_awake_action(): print(get_now_timestamp(), 'Idle detection') if MOVE_MOUSE: move_mouse() if PRESS_SHIFT_KEY: press_shift_key()
def execute_keep_awake_action():
print(get_now_timestamp(), 'Idle detection') if MOVE_MOUSE: move_mouse() if PRESS_SHIFT_KEY: press_shift_key()
_position) return current_position def press_shift_key(): keyboard.press(Key.shift) keyboard.release(Key.shift) print(get_now_timestamp(), 'Shift key pressed') def get_now_timestamp(): now = datetime.now() return now.strftime("%H:%M:%S") def execute_keep_awake_action():
64
64
37
7
57
ldpmatic/keep-presence
keep-presence.py
Python
execute_keep_awake_action
execute_keep_awake_action
99
106
99
99
31973e01ec947c85809268cbc6f85bf0a0ca1486
bigcode/the-stack
train
710ef5ecabd1be323c692a5c
train
function
def vsis3_init(): gdaltest.aws_vars = {} for var in ('AWS_SECRET_ACCESS_KEY', 'AWS_ACCESS_KEY_ID', 'AWS_TIMESTAMP', 'AWS_HTTPS', 'AWS_VIRTUAL_HOSTING', 'AWS_S3_ENDPOINT', 'AWS_REQUEST_PAYER', 'AWS_DEFAULT_REGION', 'AWS_DEFAULT_PROFILE', 'AWS_NO_SIGN_REQUEST'): gdaltest.aws_vars[var] = gdal.GetConfigOpt...
def vsis3_init():
gdaltest.aws_vars = {} for var in ('AWS_SECRET_ACCESS_KEY', 'AWS_ACCESS_KEY_ID', 'AWS_TIMESTAMP', 'AWS_HTTPS', 'AWS_VIRTUAL_HOSTING', 'AWS_S3_ENDPOINT', 'AWS_REQUEST_PAYER', 'AWS_DEFAULT_REGION', 'AWS_DEFAULT_PROFILE', 'AWS_NO_SIGN_REQUEST'): gdaltest.aws_vars[var] = gdal.GetConfigOption(var) if...
sys.path.append( '../pymod' ) import gdaltest import webserver def open_for_read(uri): """ Opens a test file for reading. """ return gdal.VSIFOpenExL(uri, 'rb', 1) ############################################################################### def vsis3_init():
64
64
193
6
58
vincentsarago/gdal
autotest/gcore/vsis3.py
Python
vsis3_init
vsis3_init
48
62
48
49
01ee7c99a2a4a9007e002f3b5eca7f3747c1827c
bigcode/the-stack
train
707acf166e361b14b26754c3
train
function
def vsis3_no_sign_request(): if not gdaltest.built_against_curl(): return 'skip' with gdaltest.config_option('AWS_NO_SIGN_REQUEST', 'YES'): f = open_for_read('/vsis3/landsat-pds/L8/001/002/LC80010022016230LGN00/LC80010022016230LGN00_B1.TIF') if f is None: if gdaltest.gdalurlopen('h...
def vsis3_no_sign_request():
if not gdaltest.built_against_curl(): return 'skip' with gdaltest.config_option('AWS_NO_SIGN_REQUEST', 'YES'): f = open_for_read('/vsis3/landsat-pds/L8/001/002/LC80010022016230LGN00/LC80010022016230LGN00_B1.TIF') if f is None: if gdaltest.gdalurlopen('https://landsat-pds.s3.amazonaw...
WS_CREDENTIALS_FILE', '') gdal.SetConfigOption('AWS_CONFIG_FILE', '') gdal.SetConfigOption('CPL_AWS_EC2_CREDENTIALS_URL', '') return 'success' ############################################################################### # Test AWS_NO_SIGN_REQUEST=YES def vsis3_no_sign_request():
64
64
180
8
55
vincentsarago/gdal
autotest/gcore/vsis3.py
Python
vsis3_no_sign_request
vsis3_no_sign_request
67
81
67
68
accb066e616320969a2a21b5ee161f4e6501bf85
bigcode/the-stack
train
5381e0593b9b70653dbaf69a
train
function
def vsis3_7(): if gdaltest.webserver_port == 0: return 'skip' handler = webserver.SequentialHandler() handler.add('GET', '/s3_bucket_test_mkdir/dir/', 404, {'Connection':'close'}) handler.add('PUT', '/s3_bucket_test_mkdir/dir/', 200) with webserver.install_http_handler(handler): re...
def vsis3_7():
if gdaltest.webserver_port == 0: return 'skip' handler = webserver.SequentialHandler() handler.add('GET', '/s3_bucket_test_mkdir/dir/', 404, {'Connection':'close'}) handler.add('PUT', '/s3_bucket_test_mkdir/dir/', 200) with webserver.install_http_handler(handler): ret = gdal.Mkdir('...
vsis3/s3_fake_bucket4/large_file_completemultipart_403_error.bin' with webserver.install_http_handler(handler): with gdaltest.config_option('VSIS3_CHUNK_SIZE', '1'): # 1 MB f = gdal.VSIFOpenL(filename, 'wb') if f is None: gdaltest.post_reason('fail') p...
214
214
715
7
207
vincentsarago/gdal
autotest/gcore/vsis3.py
Python
vsis3_7
vsis3_7
1,532
1,602
1,532
1,533
c0ebc559a5907c85b5f99c9df5e0c40de2d01c85
bigcode/the-stack
train
88cc7bbd1fdce0045fdac77a
train
function
def vsis3_4(): if gdaltest.webserver_port == 0: return 'skip' with webserver.install_http_handler(webserver.SequentialHandler()): with gdaltest.error_handler(): f = gdal.VSIFOpenL('/vsis3/s3_fake_bucket3', 'wb') if f is not None: gdaltest.post_reason('fail') ret...
def vsis3_4():
if gdaltest.webserver_port == 0: return 'skip' with webserver.install_http_handler(webserver.SequentialHandler()): with gdaltest.error_handler(): f = gdal.VSIFOpenL('/vsis3/s3_fake_bucket3', 'wb') if f is not None: gdaltest.post_reason('fail') return 'fail' ...
print(dir_contents) return 'fail' # Retry on the same bucket and check that the redirection was indeed temporary handler = webserver.SequentialHandler() h = HandlerClass("""<?xml version="1.0" encoding="UTF-8"?> <ListBucketResult> <Prefix>/test/</Prefix> ...
256
256
1,985
7
248
vincentsarago/gdal
autotest/gcore/vsis3.py
Python
vsis3_4
vsis3_4
991
1,200
991
992
b8b3b457f1c69cd73a333820afda6eca15cb1062
bigcode/the-stack
train
4251684ba2dc75a60a8e26db
train
function
def vsis3_read_config_file(): if gdaltest.webserver_port == 0: return 'skip' gdal.SetConfigOption('AWS_SECRET_ACCESS_KEY', '') gdal.SetConfigOption('AWS_ACCESS_KEY_ID', '') gdal.SetConfigOption('AWS_CONFIG_FILE', '/vsimem/aws_config') gdal.VSICurlClearCache() gdal.FileFromMemBuffer(...
def vsis3_read_config_file():
if gdaltest.webserver_port == 0: return 'skip' gdal.SetConfigOption('AWS_SECRET_ACCESS_KEY', '') gdal.SetConfigOption('AWS_ACCESS_KEY_ID', '') gdal.SetConfigOption('AWS_CONFIG_FILE', '/vsimem/aws_config') gdal.VSICurlClearCache() gdal.FileFromMemBuffer('/vsimem/aws_config', """ [unre...
4, f).decode('ascii') gdal.VSIFCloseL(f) if data != 'foo': gdaltest.post_reason('fail') print(data) return 'fail' gdal.SetConfigOption('CPL_AWS_CREDENTIALS_FILE', '') gdal.Unlink('/vsimem/aws_credentials') return 'success' #############################################...
97
97
326
8
88
vincentsarago/gdal
autotest/gcore/vsis3.py
Python
vsis3_read_config_file
vsis3_read_config_file
1,700
1,743
1,700
1,701
b6e3695abec4727b495c62eb95a44baaf7e1fec2
bigcode/the-stack
train
942b0bfb276e93cddaa4c9a6
train
function
def vsis3_read_credentials_ec2(): if gdaltest.webserver_port == 0: return 'skip' if sys.platform not in ('linux', 'linux2', 'win32'): return 'skip' gdal.SetConfigOption('CPL_AWS_CREDENTIALS_FILE', '') gdal.SetConfigOption('AWS_CONFIG_FILE', '') gdal.SetConfigOption('AWS_SECRET_ACC...
def vsis3_read_credentials_ec2():
if gdaltest.webserver_port == 0: return 'skip' if sys.platform not in ('linux', 'linux2', 'win32'): return 'skip' gdal.SetConfigOption('CPL_AWS_CREDENTIALS_FILE', '') gdal.SetConfigOption('AWS_CONFIG_FILE', '') gdal.SetConfigOption('AWS_SECRET_ACCESS_KEY', '') gdal.SetConfigOpt...
') return 'fail' if gdal.GetLastErrorMsg() == '': # Expected 'aws_access_key_id defined in both /vsimem/aws_credentials and /vsimem/aws_config' gdaltest.post_reason('fail') return 'fail' data = gdal.VSIFReadL(1, 4, f).decode('ascii') gdal.VSIFClose...
191
191
637
9
181
vincentsarago/gdal
autotest/gcore/vsis3.py
Python
vsis3_read_credentials_ec2
vsis3_read_credentials_ec2
1,944
2,008
1,944
1,945
0a5544cce21238437d721ba0b3809ee8e7019fec
bigcode/the-stack
train
62e2c0faa8158574abf9a0a4
train
function
def vsis3_start_webserver(): gdaltest.webserver_process = None gdaltest.webserver_port = 0 if not gdaltest.built_against_curl(): return 'skip' (gdaltest.webserver_process, gdaltest.webserver_port) = webserver.launch(handler = webserver.DispatcherHttpHandler) if gdaltest.webserver_port == ...
def vsis3_start_webserver():
gdaltest.webserver_process = None gdaltest.webserver_port = 0 if not gdaltest.built_against_curl(): return 'skip' (gdaltest.webserver_process, gdaltest.webserver_port) = webserver.launch(handler = webserver.DispatcherHttpHandler) if gdaltest.webserver_port == 0: return 'skip' ...
ing/foo/bar.baz') if f is not None or gdal.VSIGetLastErrorMsg() == '': gdaltest.post_reason('fail') print(gdal.VSIGetLastErrorMsg()) return 'fail' return 'success' ############################################################################### def vsis3_start_webserver():
64
64
214
8
56
vincentsarago/gdal
autotest/gcore/vsis3.py
Python
vsis3_start_webserver
vsis3_start_webserver
145
164
145
146
2b9f7ea5b2fb09db0f7b82733fd75677e91ec924
bigcode/the-stack
train
0688f95b12717a7f829f893a
train
function
def open_for_read(uri): """ Opens a test file for reading. """ return gdal.VSIFOpenExL(uri, 'rb', 1)
def open_for_read(uri):
""" Opens a test file for reading. """ return gdal.VSIFOpenExL(uri, 'rb', 1)
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER # DEALINGS IN THE SOFTWARE. ############################################################################### import os.path import stat import sys from osgeo import gdal sys.path.append( '../pymod' ) import gdaltest import webserver def open_for_read(uri)...
64
64
36
6
57
vincentsarago/gdal
autotest/gcore/vsis3.py
Python
open_for_read
open_for_read
41
45
41
41
5af7b774155a78848f9aec6d362170e399d91244
bigcode/the-stack
train
4c8614a0ca5028a2fe429d86
train
function
def vsis3_6(): if gdaltest.webserver_port == 0: return 'skip' with gdaltest.config_option('VSIS3_CHUNK_SIZE', '1'): # 1 MB with webserver.install_http_handler(webserver.SequentialHandler()): f = gdal.VSIFOpenL('/vsis3/s3_fake_bucket4/large_file.bin', 'wb') if f is None: ...
def vsis3_6():
if gdaltest.webserver_port == 0: return 'skip' with gdaltest.config_option('VSIS3_CHUNK_SIZE', '1'): # 1 MB with webserver.install_http_handler(webserver.SequentialHandler()): f = gdal.VSIFOpenL('/vsis3/s3_fake_bucket4/large_file.bin', 'wb') if f is None: gdaltest.post_r...
response = '%x\r\n%s\r\n0\r\n\r\n' % (len(response), response) request.send_header('Content-type', 'application/xml') request.send_header('Transfer-Encoding', 'chunked') request.end_headers() request.wfile.write(response.encode('ascii')) elif request.h...
256
256
2,735
7
248
vincentsarago/gdal
autotest/gcore/vsis3.py
Python
vsis3_6
vsis3_6
1,294
1,527
1,294
1,295
c92b0a72a2cc2bc7ba244d96fad3e19205d9cb9c
bigcode/the-stack
train
0ea239ee5debd92c8b5eb2cf
train
function
def vsis3_8(): if gdaltest.webserver_port == 0: return 'skip' handler = webserver.SequentialHandler() handler.add('GET', '/vsis3_8/?delimiter=%2F', 200, { 'Content-type': 'application/xml' }, """<?xml version="1.0" encoding="UTF-8"?> <ListBucke...
def vsis3_8():
if gdaltest.webserver_port == 0: return 'skip' handler = webserver.SequentialHandler() handler.add('GET', '/vsis3_8/?delimiter=%2F', 200, { 'Content-type': 'application/xml' }, """<?xml version="1.0" encoding="UTF-8"?> <ListBucketResult> ...
.000Z</LastModified> <Size>40</Size> </Contents> </ListBucketResult> """) with webserver.install_http_handler(handler): ret = gdal.Rmdir('/vsis3/s3_bucket_test_mkdir/dir_nonempty') if ret == 0: gdaltest.post_...
105
105
351
7
97
vincentsarago/gdal
autotest/gcore/vsis3.py
Python
vsis3_8
vsis3_8
1,607
1,648
1,607
1,608
979974f1a71870ad6b64bf63dc647cb994d5dbaf
bigcode/the-stack
train
c2c777618f79d1aad2c68ab1
train
function
def vsis3_cleanup(): for var in gdaltest.aws_vars: gdal.SetConfigOption(var, gdaltest.aws_vars[var]) gdal.SetConfigOption('CPL_AWS_CREDENTIALS_FILE', None) gdal.SetConfigOption('AWS_CONFIG_FILE', None) gdal.SetConfigOption('CPL_AWS_EC2_CREDENTIALS_URL', None) return 'success'
def vsis3_cleanup():
for var in gdaltest.aws_vars: gdal.SetConfigOption(var, gdaltest.aws_vars[var]) gdal.SetConfigOption('CPL_AWS_CREDENTIALS_FILE', None) gdal.SetConfigOption('AWS_CONFIG_FILE', None) gdal.SetConfigOption('CPL_AWS_EC2_CREDENTIALS_URL', None) return 'success'
/' + gdal.GetConfigOption('S3_RESOURCE') + '/invalid_resource.baz') if f is not None: gdaltest.post_reason('fail') print(gdal.VSIGetLastErrorMsg()) return 'fail' return 'success' ############################################################################### def vsis3_cleanup():
64
64
88
6
58
vincentsarago/gdal
autotest/gcore/vsis3.py
Python
vsis3_cleanup
vsis3_cleanup
2,264
2,273
2,264
2,265
423ca64387d6c6a655e726bf73813b7e5b9dbc88
bigcode/the-stack
train
92b9a3565240bd9d37abf72d
train
function
def vsis3_3(): if gdaltest.webserver_port == 0: return 'skip' handler = webserver.SequentialHandler() def method(request): request.protocol_version = 'HTTP/1.1' if request.headers['Authorization'].find('us-east-1') >= 0: request.send_response(400) response ...
def vsis3_3():
if gdaltest.webserver_port == 0: return 'skip' handler = webserver.SequentialHandler() def method(request): request.protocol_version = 'HTTP/1.1' if request.headers['Authorization'].find('us-east-1') >= 0: request.send_response(400) response = '<?xml version...
).decode('ascii') gdal.VSIFCloseL(f) if data != 'foo': gdaltest.post_reason('fail') print(data) return 'fail' # Retry on the same bucket and check that the redirection was indeed temporary handler = webserver.SequentialHandler() h = HandlerClass('bar') handler.add(...
256
256
3,421
7
248
vincentsarago/gdal
autotest/gcore/vsis3.py
Python
vsis3_3
vsis3_3
637
986
637
638
d8d4eed64ef8ee5688194f9016491fb4e1d66308
bigcode/the-stack
train
cb3b3fd8d630d92a02e4c802
train
function
def vsis3_1(): if not gdaltest.built_against_curl(): return 'skip' # Missing AWS_SECRET_ACCESS_KEY gdal.ErrorReset() with gdaltest.error_handler(): f = open_for_read('/vsis3/foo/bar') if f is not None or gdal.VSIGetLastErrorMsg().find('AWS_SECRET_ACCESS_KEY') < 0: gdaltest....
def vsis3_1():
if not gdaltest.built_against_curl(): return 'skip' # Missing AWS_SECRET_ACCESS_KEY gdal.ErrorReset() with gdaltest.error_handler(): f = open_for_read('/vsis3/foo/bar') if f is not None or gdal.VSIGetLastErrorMsg().find('AWS_SECRET_ACCESS_KEY') < 0: gdaltest.post_reason('fai...
_SIGN_REQUEST', 'YES'): f = open_for_read('/vsis3/landsat-pds/L8/001/002/LC80010022016230LGN00/LC80010022016230LGN00_B1.TIF') if f is None: if gdaltest.gdalurlopen('https://landsat-pds.s3.amazonaws.com/L8/001/002/LC80010022016230LGN00/LC80010022016230LGN00_B1.TIF') is None: print('cannot...
157
157
525
7
149
vincentsarago/gdal
autotest/gcore/vsis3.py
Python
vsis3_1
vsis3_1
86
142
86
87
26415b1285a44fac716612691474933103c57847
bigcode/the-stack
train
8388cf5435cb8c980605b577
train
function
def vsis3_read_credentials_ec2_expiration(): if gdaltest.webserver_port == 0: return 'skip' if sys.platform not in ('linux', 'linux2', 'win32'): return 'skip' gdal.SetConfigOption('CPL_AWS_CREDENTIALS_FILE', '') gdal.SetConfigOption('AWS_CONFIG_FILE', '') gdal.SetConfigOption('AWS...
def vsis3_read_credentials_ec2_expiration():
if gdaltest.webserver_port == 0: return 'skip' if sys.platform not in ('linux', 'linux2', 'win32'): return 'skip' gdal.SetConfigOption('CPL_AWS_CREDENTIALS_FILE', '') gdal.SetConfigOption('AWS_CONFIG_FILE', '') gdal.SetConfigOption('AWS_SECRET_ACCESS_KEY', '') gdal.SetConfigOpt...
(handler): f = open_for_read('/vsis3/s3_fake_bucket/bar') if f is None: gdaltest.post_reason('fail') return 'fail' data = gdal.VSIFReadL(1, 4, f).decode('ascii') gdal.VSIFCloseL(f) if data != 'bar': gdaltest.post_reason('fail') print(data) ...
171
171
570
11
159
vincentsarago/gdal
autotest/gcore/vsis3.py
Python
vsis3_read_credentials_ec2_expiration
vsis3_read_credentials_ec2_expiration
2,014
2,068
2,014
2,015
885466efc1bcd1b5d980e82464717cf5aa46972d
bigcode/the-stack
train
a9c460b5c827703c088ccd29
train
function
def vsis3_read_credentials_config_file_inconsistent(): if gdaltest.webserver_port == 0: return 'skip' gdal.SetConfigOption('AWS_SECRET_ACCESS_KEY', '') gdal.SetConfigOption('AWS_ACCESS_KEY_ID', '') gdal.SetConfigOption('CPL_AWS_CREDENTIALS_FILE', '/vsimem/aws_credentials') gdal.SetConfigO...
def vsis3_read_credentials_config_file_inconsistent():
if gdaltest.webserver_port == 0: return 'skip' gdal.SetConfigOption('AWS_SECRET_ACCESS_KEY', '') gdal.SetConfigOption('AWS_ACCESS_KEY_ID', '') gdal.SetConfigOption('CPL_AWS_CREDENTIALS_FILE', '/vsimem/aws_credentials') gdal.SetConfigOption('AWS_CONFIG_FILE', '/vsimem/aws_config') gdal...
fail' data = gdal.VSIFReadL(1, 4, f).decode('ascii') gdal.VSIFCloseL(f) if data != 'foo': gdaltest.post_reason('fail') print(data) return 'fail' gdal.SetConfigOption('CPL_AWS_CREDENTIALS_FILE', '') gdal.Unlink('/vsimem/aws_credentials') gdal.SetConfigOption('AWS...
157
157
525
11
145
vincentsarago/gdal
autotest/gcore/vsis3.py
Python
vsis3_read_credentials_config_file_inconsistent
vsis3_read_credentials_config_file_inconsistent
1,875
1,939
1,875
1,876
b81432264e279a7b1436236cd3ed188440960180
bigcode/the-stack
train
36d904f50ce1f41b47f4bf52
train
function
def vsis3_read_credentials_config_file(): if gdaltest.webserver_port == 0: return 'skip' gdal.SetConfigOption('AWS_SECRET_ACCESS_KEY', '') gdal.SetConfigOption('AWS_ACCESS_KEY_ID', '') gdal.SetConfigOption('CPL_AWS_CREDENTIALS_FILE', '/vsimem/aws_credentials') gdal.SetConfigOption('AWS_CO...
def vsis3_read_credentials_config_file():
if gdaltest.webserver_port == 0: return 'skip' gdal.SetConfigOption('AWS_SECRET_ACCESS_KEY', '') gdal.SetConfigOption('AWS_ACCESS_KEY_ID', '') gdal.SetConfigOption('CPL_AWS_CREDENTIALS_FILE', '/vsimem/aws_credentials') gdal.SetConfigOption('AWS_CONFIG_FILE', '/vsimem/aws_config') gdal...
3_fake_bucket/resource') if f is None: gdaltest.post_reason('fail') return 'fail' data = gdal.VSIFReadL(1, 4, f).decode('ascii') gdal.VSIFCloseL(f) if data != 'foo': gdaltest.post_reason('fail') print(data) return 'fail' gdal.SetConfigOpt...
136
136
455
9
126
vincentsarago/gdal
autotest/gcore/vsis3.py
Python
vsis3_read_credentials_config_file
vsis3_read_credentials_config_file
1,748
1,806
1,748
1,749
0976d4adeba8d3769f034d9172ddc3e069d685b3
bigcode/the-stack
train
0a2d3dafb48dd3e44ffdaffa
train
function
def vsis3_stop_webserver(): if gdaltest.webserver_port == 0: return 'skip' # Clearcache needed to close all connections, since the Python server # can only handle one connection at a time gdal.VSICurlClearCache() webserver.server_stop(gdaltest.webserver_process, gdaltest.webserver_port) ...
def vsis3_stop_webserver():
if gdaltest.webserver_port == 0: return 'skip' # Clearcache needed to close all connections, since the Python server # can only handle one connection at a time gdal.VSICurlClearCache() webserver.server_stop(gdaltest.webserver_process, gdaltest.webserver_port) return 'success'
('fail') return 'fail' gdal.SetConfigOption('CPL_AWS_EC2_CREDENTIALS_URL','') gdal.SetConfigOption('CPL_AWS_CHECK_HYPERVISOR_UUID', None) return 'success' ############################################################################### def vsis3_stop_webserver():
64
64
85
8
56
vincentsarago/gdal
autotest/gcore/vsis3.py
Python
vsis3_stop_webserver
vsis3_stop_webserver
2,071
2,082
2,071
2,072
334ec864b36f6575189215250ba09496cde1b2c4
bigcode/the-stack
train
4d88b1bda5f891b43bdb1f9a
train
function
def vsis3_2(): if gdaltest.webserver_port == 0: return 'skip' handler = webserver.SequentialHandler() handler.add('GET', '/s3_fake_bucket/resource', custom_method = get_s3_fake_bucket_resource_method) with webserver.install_http_handler(handler): f = open_for_read('/vsis3/s3_fake_buck...
def vsis3_2():
if gdaltest.webserver_port == 0: return 'skip' handler = webserver.SequentialHandler() handler.add('GET', '/s3_fake_bucket/resource', custom_method = get_s3_fake_bucket_resource_method) with webserver.install_http_handler(handler): f = open_for_read('/vsis3/s3_fake_bucket/resource') ...
46b865b12ac492bc005bb394ca8d60c098b68db57c084fac686a932f9e' expected_authorization_8081 = 'AWS4-HMAC-SHA256 Credential=AWS_ACCESS_KEY_ID/20150101/us-east-1/s3/aws4_request,SignedHeaders=host;x-amz-content-sha256;x-amz-date,Signature=9f623b7ffce76188a456c70fb4813eb31969e88d130d6b4d801b3accbf050d6c' if request.he...
256
256
4,813
7
248
vincentsarago/gdal
autotest/gcore/vsis3.py
Python
vsis3_2
vsis3_2
190
632
190
191
f295e8995627befac47540493a722e5239e11f73
bigcode/the-stack
train
2cb9b96f5c4c5b988f7bce2e
train
function
def vsis3_read_credentials_file(): if gdaltest.webserver_port == 0: return 'skip' gdal.SetConfigOption('AWS_SECRET_ACCESS_KEY', '') gdal.SetConfigOption('AWS_ACCESS_KEY_ID', '') gdal.SetConfigOption('CPL_AWS_CREDENTIALS_FILE', '/vsimem/aws_credentials') gdal.VSICurlClearCache() gdal...
def vsis3_read_credentials_file():
if gdaltest.webserver_port == 0: return 'skip' gdal.SetConfigOption('AWS_SECRET_ACCESS_KEY', '') gdal.SetConfigOption('AWS_ACCESS_KEY_ID', '') gdal.SetConfigOption('CPL_AWS_CREDENTIALS_FILE', '/vsimem/aws_credentials') gdal.VSICurlClearCache() gdal.FileFromMemBuffer('/vsimem/aws_cred...
): gdaltest.post_reason('fail') return 'fail' handler = webserver.SequentialHandler() with webserver.install_http_handler(handler): if not stat.S_ISDIR(gdal.VSIStatL('/vsis3/vsis3_8/test/').mode): gdaltest.post_reason('fail') return 'fail' return 'su...
98
98
329
8
89
vincentsarago/gdal
autotest/gcore/vsis3.py
Python
vsis3_read_credentials_file
vsis3_read_credentials_file
1,653
1,695
1,653
1,654
e59beca6e92c0a112ff28d8c9e1594736a070421
bigcode/the-stack
train
1b39d51070dfefe1b5f38fee
train
function
def vsis3_5(): if gdaltest.webserver_port == 0: return 'skip' with webserver.install_http_handler(webserver.SequentialHandler()): with gdaltest.error_handler(): ret = gdal.Unlink('/vsis3/foo') if ret == 0: gdaltest.post_reason('fail') return 'fail' handler ...
def vsis3_5():
if gdaltest.webserver_port == 0: return 'skip' with webserver.install_http_handler(webserver.SequentialHandler()): with gdaltest.error_handler(): ret = gdal.Unlink('/vsis3/foo') if ret == 0: gdaltest.post_reason('fail') return 'fail' handler = webserver.Sequ...
request.rfile.read(6).decode('ascii') if content != 'foobar': sys.stderr.write('Did not get expected content: %s\n' % content) request.send_response(400) request.send_header('Content-Length', 0) request.end_headers() return ...
243
243
812
7
235
vincentsarago/gdal
autotest/gcore/vsis3.py
Python
vsis3_5
vsis3_5
1,205
1,289
1,205
1,206
2e85a332dc77f875ef7283ff6703eb639dd390c6
bigcode/the-stack
train
29a7eb40a1ab3ab7a13c3da2
train
function
def vsis3_extra_1(): if not gdaltest.built_against_curl(): return 'skip' credentials_filename = gdal.GetConfigOption('HOME', gdal.GetConfigOption('USERPROFILE', '')) + '/.aws/credentials' # Either a bucket name or bucket/filename s3_resource = gdal.GetConfigOption('S3_RESOURCE') ...
def vsis3_extra_1():
if not gdaltest.built_against_curl(): return 'skip' credentials_filename = gdal.GetConfigOption('HOME', gdal.GetConfigOption('USERPROFILE', '')) + '/.aws/credentials' # Either a bucket name or bucket/filename s3_resource = gdal.GetConfigOption('S3_RESOURCE') if not os.path.exists(...
data != 'foo': gdaltest.post_reason('fail') print(data) return 'fail' # Set a fake URL to demonstrate we try to re-fetch credentials gdal.SetConfigOption('CPL_AWS_EC2_CREDENTIALS_URL', '') with gdaltest.error_handler(): f = open_for_read('/vsis3/s3_fake_bucket/bar') if...
256
256
1,507
8
248
vincentsarago/gdal
autotest/gcore/vsis3.py
Python
vsis3_extra_1
vsis3_extra_1
2,087
2,261
2,087
2,088
3526427179c8d0617b089079d8fc565650792ca6
bigcode/the-stack
train
67561f1553b3e70a0752d439
train
function
def vsis3_read_credentials_config_file_non_default(): if gdaltest.webserver_port == 0: return 'skip' gdal.SetConfigOption('AWS_SECRET_ACCESS_KEY', '') gdal.SetConfigOption('AWS_ACCESS_KEY_ID', '') gdal.SetConfigOption('CPL_AWS_CREDENTIALS_FILE', '/vsimem/aws_credentials') gdal.SetConfigOp...
def vsis3_read_credentials_config_file_non_default():
if gdaltest.webserver_port == 0: return 'skip' gdal.SetConfigOption('AWS_SECRET_ACCESS_KEY', '') gdal.SetConfigOption('AWS_ACCESS_KEY_ID', '') gdal.SetConfigOption('CPL_AWS_CREDENTIALS_FILE', '/vsimem/aws_credentials') gdal.SetConfigOption('AWS_CONFIG_FILE', '/vsimem/aws_config') gdal....
(1, 4, f).decode('ascii') gdal.VSIFCloseL(f) if data != 'foo': gdaltest.post_reason('fail') print(data) return 'fail' gdal.SetConfigOption('CPL_AWS_CREDENTIALS_FILE', '') gdal.Unlink('/vsimem/aws_credentials') gdal.SetConfigOption('AWS_CONFIG_FILE', '') gdal.Unlink(...
139
139
466
11
127
vincentsarago/gdal
autotest/gcore/vsis3.py
Python
vsis3_read_credentials_config_file_non_default
vsis3_read_credentials_config_file_non_default
1,812
1,870
1,812
1,813
5e1dda28224f2c7eb806e6e38c0981b4f7fcc906
bigcode/the-stack
train
0fa2d3098a10768d5c130ebe
train
function
def get_s3_fake_bucket_resource_method(request): request.protocol_version = 'HTTP/1.1' if 'Authorization' not in request.headers: sys.stderr.write('Bad headers: %s\n' % str(request.headers)) request.send_response(403) return expected_authorization_8080 = 'AWS4-HMAC-SHA256 Credential...
def get_s3_fake_bucket_resource_method(request):
request.protocol_version = 'HTTP/1.1' if 'Authorization' not in request.headers: sys.stderr.write('Bad headers: %s\n' % str(request.headers)) request.send_response(403) return expected_authorization_8080 = 'AWS4-HMAC-SHA256 Credential=AWS_ACCESS_KEY_ID/20150101/us-east-1/s3/aws4_req...
AWS_ACCESS_KEY_ID', 'AWS_ACCESS_KEY_ID') gdal.SetConfigOption('AWS_TIMESTAMP', '20150101T000000Z') gdal.SetConfigOption('AWS_HTTPS', 'NO') gdal.SetConfigOption('AWS_VIRTUAL_HOSTING', 'NO') gdal.SetConfigOption('AWS_S3_ENDPOINT', '127.0.0.1:%d' % gdaltest.webserver_port) return 'success' def get_s3_...
106
106
354
10
96
vincentsarago/gdal
autotest/gcore/vsis3.py
Python
get_s3_fake_bucket_resource_method
get_s3_fake_bucket_resource_method
166
185
166
166
9dbe08e356e347cc03fdb6131c13f10aa332eff3
bigcode/the-stack
train
6f60b78bc7b1738d3bad1b96
train
class
class TestPickleDict(object): def test_int(self, mydict): mydict['test_int'] = 42 assert mydict['test_int'] == 42 def test_string(self, mydict): mydict['test_string'] = 'foo' assert mydict['test_string'] == 'foo' d = {'foo':'bar'} mydict['test_string_dict'] = d ...
class TestPickleDict(object):
def test_int(self, mydict): mydict['test_int'] = 42 assert mydict['test_int'] == 42 def test_string(self, mydict): mydict['test_string'] = 'foo' assert mydict['test_string'] == 'foo' d = {'foo':'bar'} mydict['test_string_dict'] = d assert mydict['test_st...
from __future__ import absolute_import from __future__ import print_function from __future__ import unicode_literals import pandas as pd import pytest from nodebook.pickledict import PickleDict @pytest.fixture(params=[None, 'tmpdir'], ids=['mode_memory', 'mode_disk']) def mydict(request, tmpdir): if request.param...
122
163
545
7
115
UoA-eResearch/nodebook
tests/test_pickledict.py
Python
TestPickleDict
TestPickleDict
19
80
19
19
ac6fbea43fd783ccb2873a8136b3e2af1bdc18d5
bigcode/the-stack
train
a16b6282483f0e4c92d8fa8c
train
function
@pytest.fixture(params=[None, 'tmpdir'], ids=['mode_memory', 'mode_disk']) def mydict(request, tmpdir): if request.param == 'tmpdir': persist_path = tmpdir.strpath print(persist_path) else: persist_path = None return PickleDict(persist_path=persist_path)
@pytest.fixture(params=[None, 'tmpdir'], ids=['mode_memory', 'mode_disk']) def mydict(request, tmpdir):
if request.param == 'tmpdir': persist_path = tmpdir.strpath print(persist_path) else: persist_path = None return PickleDict(persist_path=persist_path)
_import from __future__ import print_function from __future__ import unicode_literals import pandas as pd import pytest from nodebook.pickledict import PickleDict @pytest.fixture(params=[None, 'tmpdir'], ids=['mode_memory', 'mode_disk']) def mydict(request, tmpdir):
64
64
72
27
36
UoA-eResearch/nodebook
tests/test_pickledict.py
Python
mydict
mydict
9
16
9
10
d4a53264ad22664e41b30b3ad69725eb7e6c3180
bigcode/the-stack
train
be823f47b3e1fe21968a87a4
train
function
def test(): import pyre.xml from pyre.xml.Node import Node from pyre.xml.Document import Document class Inventory(Node): """The top level document element""" def notify(self, parent, locator): """do nothing""" def __init__(self, parent, attributes, locator): ...
def test():
import pyre.xml from pyre.xml.Node import Node from pyre.xml.Document import Document class Inventory(Node): """The top level document element""" def notify(self, parent, locator): """do nothing""" def __init__(self, parent, attributes, locator): """do...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # michael a.g. aïvázis # orthologue # (c) 1998-2020 all rights reserved # """ Read an empty document """ def test():
56
64
167
3
53
rtburns-jpl/pyre
tests/pyre.pkg/xml/schema.py
Python
test
test
14
46
14
14
bc5697d92167417c3a80ea0b6d58a8b27b91221d
bigcode/the-stack
train
7fffb8772a072aec18173719
train
function
def bootup(): # Enable VT100 Escape Sequence for WINDOWS 10 Ver. 1607 if sys.platform == "win32": os.system("") # nosec try: if os.name == "nt": # pylint: disable=E1101 sys.stdin.reconfigure(encoding="utf-8") # pylint: disable=E1101 sys.stdou...
def bootup(): # Enable VT100 Escape Sequence for WINDOWS 10 Ver. 1607
if sys.platform == "win32": os.system("") # nosec try: if os.name == "nt": # pylint: disable=E1101 sys.stdin.reconfigure(encoding="utf-8") # pylint: disable=E1101 sys.stdout.reconfigure(encoding="utf-8") except Exception as e: logger....
. " "GST and any provider of the data contained in this website will not accept liability for any loss or damage " "as a result of your trading, or your reliance on the information displayed.[/red]\n" ) def bootup(): # Enable VT100 Escape Sequence for WINDOWS 10 Ver. 1607
70
70
236
21
49
GarnixJu2015/GamestonkTerminal
gamestonk_terminal/terminal_helper.py
Python
bootup
bootup
380
408
380
381
c64ecff21328bf3f8e7dfd4ace6c301a6fcaaac4
bigcode/the-stack
train
19f96e8c528f4334aca90b44
train
function
def reset(queue: List[str] = None): """Resets the terminal. Allows for checking code or keys without quitting""" console.print("resetting...") plt.close("all") if queue and len(queue) > 0: completed_process = subprocess.run( # nosec f"{sys.executable} terminal.py {'/'.join(queue) ...
def reset(queue: List[str] = None):
"""Resets the terminal. Allows for checking code or keys without quitting""" console.print("resetting...") plt.close("all") if queue and len(queue) > 0: completed_process = subprocess.run( # nosec f"{sys.executable} terminal.py {'/'.join(queue) if len(queue) > 0 else ''}", ...
ff.ENABLE_THOUGHTS_DAY: console.print("-------------------") try: thought.get_thought_of_the_day() except Exception as e: logger.exception("%s", type(e).__name__) console.print(e) console.print("") def reset(queue: List[str] = None):
63
64
159
10
53
GarnixJu2015/GamestonkTerminal
gamestonk_terminal/terminal_helper.py
Python
reset
reset
411
429
411
411
5df70d95a5671611dacc20d5ea51f67f8c7dd85a
bigcode/the-stack
train
2677732e1a310898ce6958a3
train
function
def check_api_keys(): """Check api keys and if they are supplied""" key_dict = {} if cfg.API_KEY_ALPHAVANTAGE == "REPLACE_ME": # pragma: allowlist secret key_dict["ALPHA_VANTAGE"] = "Not defined" else: df = TimeSeries( key=cfg.API_KEY_ALPHAVANTAGE, output_format="pandas" ...
def check_api_keys():
"""Check api keys and if they are supplied""" key_dict = {} if cfg.API_KEY_ALPHAVANTAGE == "REPLACE_ME": # pragma: allowlist secret key_dict["ALPHA_VANTAGE"] = "Not defined" else: df = TimeSeries( key=cfg.API_KEY_ALPHAVANTAGE, output_format="pandas" ).get_intraday(s...
"""Terminal helper""" __docformat__ = "numpy" import hashlib import logging import os import random import subprocess # nosec import sys from datetime import datetime from typing import List import matplotlib.pyplot as plt import pandas as pd import praw import pyEX import quandl import requests from alpha_vantage.ti...
200
256
2,394
5
195
GarnixJu2015/GamestonkTerminal
gamestonk_terminal/terminal_helper.py
Python
check_api_keys
check_api_keys
34
285
34
34
913cd58d1f5e0eb48c303f9d41d78481baacf5ed
bigcode/the-stack
train
e213ba4c770cdd463f80d537
train
function
def about_us(): """Prints an about us section""" console.print( "[green]Thanks for using Gamestonk Terminal. This is our way![/green]\n" "\n" "[cyan]Join our community on discord: [/cyan]https://discord.gg/Up2QGbMKHY\n" "[cyan]Follow our twitter for updates: [/cyan]https://twitte...
def about_us():
"""Prints an about us section""" console.print( "[green]Thanks for using Gamestonk Terminal. This is our way![/green]\n" "\n" "[cyan]Join our community on discord: [/cyan]https://discord.gg/Up2QGbMKHY\n" "[cyan]Follow our twitter for updates: [/cyan]https://twitter.com/gamestonkt...
if poetry_hash == new_poetry_hash: console.print("Great, seems like poetry hasn't been updated!") return completed_process.returncode console.print( "Seems like more modules have been added, grab a coke, this may take a while." ) completed_process = subprocess.run( "poetry ...
107
107
358
4
102
GarnixJu2015/GamestonkTerminal
gamestonk_terminal/terminal_helper.py
Python
about_us
about_us
356
377
356
356
d5c08147cb9ac16749e578129591511c1eb4879e
bigcode/the-stack
train
21ed02612b3be098fe5e7ab2
train
function
def sha256sum(filename): h = hashlib.sha256() b = bytearray(128 * 1024) mv = memoryview(b) with open(filename, "rb", buffering=0) as f: for n in iter(lambda: f.readinto(mv), 0): h.update(mv[:n]) return h.hexdigest()
def sha256sum(filename):
h = hashlib.sha256() b = bytearray(128 * 1024) mv = memoryview(b) with open(filename, "rb", buffering=0) as f: for n in iter(lambda: f.readinto(mv), 0): h.update(mv[:n]) return h.hexdigest()
else: goodbye_msg_time = "Go get some rest soldier!" console.print( # nosec goodbye_msg[random.randint(0, len(goodbye_msg) - 1)] + goodbye_msg_time + "\n" ) logger.info("Terminal stopped") def sha256sum(filename):
64
64
77
6
58
GarnixJu2015/GamestonkTerminal
gamestonk_terminal/terminal_helper.py
Python
sha256sum
sha256sum
320
327
320
320
86e4a7cb633bcb6b0481893a263b49188c1af993
bigcode/the-stack
train
d0a827d31b274a045d71927f
train
function
def print_goodbye(): """Prints a goodbye message when quitting the terminal""" goodbye_msg = [ "An informed ape, is a strong ape. ", "Remember that stonks only go up. ", "Diamond hands. ", "Apes together strong. ", "This is our way. ", "Keep the spacesuit ape, we ...
def print_goodbye():
"""Prints a goodbye message when quitting the terminal""" goodbye_msg = [ "An informed ape, is a strong ape. ", "Remember that stonks only go up. ", "Diamond hands. ", "Apes together strong. ", "This is our way. ", "Keep the spacesuit ape, we haven't reached the m...
OR"] = "Defined, test passed" else: key_dict["SENTIMENT_INVESTOR"] = "Defined, test unsuccessful" print( tabulate( pd.DataFrame(key_dict.items()), showindex=False, headers=[], tablefmt="fancy_grid", ), "\n", ) def print...
75
75
251
5
70
GarnixJu2015/GamestonkTerminal
gamestonk_terminal/terminal_helper.py
Python
print_goodbye
print_goodbye
288
317
288
288
adea8d42fc4acbce4035f934a502926a2e138e83
bigcode/the-stack
train
9eb93d8445c7a746bb897756
train
function
def update_terminal(): """Updates the terminal by running git pull in the directory. Runs poetry install if needed""" poetry_hash = sha256sum("poetry.lock") completed_process = subprocess.run("git pull", shell=True, check=False) # nosec if completed_process.returncode != 0: return completed_p...
def update_terminal():
"""Updates the terminal by running git pull in the directory. Runs poetry install if needed""" poetry_hash = sha256sum("poetry.lock") completed_process = subprocess.run("git pull", shell=True, check=False) # nosec if completed_process.returncode != 0: return completed_process.returncode ...
array(128 * 1024) mv = memoryview(b) with open(filename, "rb", buffering=0) as f: for n in iter(lambda: f.readinto(mv), 0): h.update(mv[:n]) return h.hexdigest() def update_terminal():
64
64
192
4
60
GarnixJu2015/GamestonkTerminal
gamestonk_terminal/terminal_helper.py
Python
update_terminal
update_terminal
330
353
330
330
f6edb71de76855b78ad14b235533e077c45a3b89
bigcode/the-stack
train
392a1e7b2289e6da885c29c8
train
class
class Sender(Module): def __init__(self, name: str, menv: msat_env, enc: LTLEncoder, in_c, x_in_c, out_c, x_out_c, delta): super().__init__(name, menv, enc) bool_type = msat_get_bool_type(menv) int_type = msat_get_integer_type(menv) real_type = msat_get_rational_typ...
class Sender(Module):
def __init__(self, name: str, menv: msat_env, enc: LTLEncoder, in_c, x_in_c, out_c, x_out_c, delta): super().__init__(name, menv, enc) bool_type = msat_get_bool_type(menv) int_type = msat_get_integer_type(menv) real_type = msat_get_rational_type(menv) loc, x...
G (s.wait_ack -> F s.send) lhs = enc.make_G(enc.make_F(msat_make_not(menv, sender.stutter))) rhs = enc.make_G(msat_make_impl(menv, sender.wait_ack, enc.make_F(sender.send))) ltl = msat_make_impl(menv, lhs, rhs) return TermMap(curr2next), init, trans, ltl class Modu...
256
256
1,581
4
252
EnricoMagnago/F3
benchmarks/f3_wrong_hints_permutations/scaling_ltl_timed_transition_system/17-sender_receiver_37.py
Python
Sender
Sender
157
287
157
157
433aae4a3982373c712889177fa3b8c3bb2c06fd
bigcode/the-stack
train
209bad37de9043e3eccfba2e
train
function
def make_enum(menv, v_name: str, enum_size: int): bool_type = msat_get_bool_type(menv) num_bits = ceil(log(enum_size, 2)) b_vars = [] for idx in range(num_bits): c_name = "{}{}".format(v_name, idx) b_vars.append(tuple(decl_consts(menv, c_name, bool_type))) vals = [] x_vals = [] ...
def make_enum(menv, v_name: str, enum_size: int):
bool_type = msat_get_bool_type(menv) num_bits = ceil(log(enum_size, 2)) b_vars = [] for idx in range(num_bits): c_name = "{}{}".format(v_name, idx) b_vars.append(tuple(decl_consts(menv, c_name, bool_type))) vals = [] x_vals = [] for enum_val in range(enum_size): bit_v...
not name.startswith("_"), name s = msat_declare_function(menv, name, c_type) s = msat_make_constant(menv, s) x_s = msat_declare_function(menv, name_next(name), c_type) x_s = msat_make_constant(menv, x_s) return s, x_s def make_enum(menv, v_name: str, enum_size: int):
91
91
304
16
74
EnricoMagnago/F3
benchmarks/f3_wrong_hints_permutations/scaling_ltl_timed_transition_system/17-sender_receiver_37.py
Python
make_enum
make_enum
31
57
31
31
6f40058273179024dd97843c5848eacb9296b965
bigcode/the-stack
train
8778da5de959ea69b93f01c9
train
function
def msat_make_impl(menv: msat_env, arg0: msat_term, arg1: msat_term): n_arg0 = msat_make_not(menv, arg0) return msat_make_or(menv, n_arg0, arg1)
def msat_make_impl(menv: msat_env, arg0: msat_term, arg1: msat_term):
n_arg0 = msat_make_not(menv, arg0) return msat_make_or(menv, n_arg0, arg1)
, arg1: msat_term): leq = msat_make_leq(menv, arg0, arg1) return msat_make_not(menv, leq) def msat_make_impl(menv: msat_env, arg0: msat_term, arg1: msat_term):
64
64
57
26
38
EnricoMagnago/F3
benchmarks/f3_wrong_hints_permutations/scaling_ltl_timed_transition_system/17-sender_receiver_37.py
Python
msat_make_impl
msat_make_impl
80
82
80
80
6517b33753958b928ace2c9a49a92b8749eb6875
bigcode/the-stack
train
19628962c1ce74f4d8e3763c
train
function
def msat_make_geq(menv: msat_env, arg0: msat_term, arg1: msat_term): return msat_make_leq(menv, arg1, arg0)
def msat_make_geq(menv: msat_env, arg0: msat_term, arg1: msat_term):
return msat_make_leq(menv, arg1, arg0)
arg1: msat_term): geq = msat_make_geq(menv, arg0, arg1) return msat_make_not(menv, geq) def msat_make_geq(menv: msat_env, arg0: msat_term, arg1: msat_term):
64
64
43
27
37
EnricoMagnago/F3
benchmarks/f3_wrong_hints_permutations/scaling_ltl_timed_transition_system/17-sender_receiver_37.py
Python
msat_make_geq
msat_make_geq
71
72
71
71
b508b807d803a8843eb678982d7c937a8b671e86
bigcode/the-stack
train
f460806ae1c6918d454a8a4b
train
function
def decl_consts(menv: msat_env, name: str, c_type) -> tuple: assert not name.startswith("_"), name s = msat_declare_function(menv, name, c_type) s = msat_make_constant(menv, s) x_s = msat_declare_function(menv, name_next(name), c_type) x_s = msat_make_constant(menv, x_s) return s, x_s
def decl_consts(menv: msat_env, name: str, c_type) -> tuple:
assert not name.startswith("_"), name s = msat_declare_function(menv, name, c_type) s = msat_make_constant(menv, s) x_s = msat_declare_function(menv, name_next(name), c_type) x_s = msat_make_constant(menv, x_s) return s, x_s
import pysmt.typing as types from ltl.ltl import TermMap, LTLEncoder from utils import name_next, symb_to_next from hint import Hint, Location delta_name = "delta" def decl_consts(menv: msat_env, name: str, c_type) -> tuple:
64
64
97
20
44
EnricoMagnago/F3
benchmarks/f3_wrong_hints_permutations/scaling_ltl_timed_transition_system/17-sender_receiver_37.py
Python
decl_consts
decl_consts
22
28
22
22
c4ecf1f5e126ec75d8eb9ef6e31b305b569d35be
bigcode/the-stack
train
a6b84d38e950fe1a738abc4f
train
class
class Module: def __init__(self, name: str, menv: msat_env, enc: LTLEncoder, *args, **kwargs): self.name = name self.menv = menv self.enc = enc self.symb2next = {} true = msat_make_true(menv) self.init = true self.trans = true def _symb(s...
class Module:
def __init__(self, name: str, menv: msat_env, enc: LTLEncoder, *args, **kwargs): self.name = name self.menv = menv self.enc = enc self.symb2next = {} true = msat_make_true(menv) self.init = true self.trans = true def _symb(self, v_name, v...
(menv, sender.stutter))) rhs = enc.make_G(msat_make_impl(menv, sender.wait_ack, enc.make_F(sender.send))) ltl = msat_make_impl(menv, lhs, rhs) return TermMap(curr2next), init, trans, ltl class Module:
64
64
168
3
60
EnricoMagnago/F3
benchmarks/f3_wrong_hints_permutations/scaling_ltl_timed_transition_system/17-sender_receiver_37.py
Python
Module
Module
137
154
137
137
1df951df4e384526ae7251d61c59eee88edafeeb
bigcode/the-stack
train
ad7fb05c2cb1aea61a6e0d04
train
function
def check_ltl(menv: msat_env, enc: LTLEncoder) -> (Iterable, msat_term, msat_term, msat_term): assert menv assert isinstance(menv, msat_env) assert enc assert isinstance(enc, LTLEncoder) int_type = msat_get_integer_type(menv) real_type = msat_ge...
def check_ltl(menv: msat_env, enc: LTLEncoder) -> (Iterable, msat_term, msat_term, msat_term):
assert menv assert isinstance(menv, msat_env) assert enc assert isinstance(enc, LTLEncoder) int_type = msat_get_integer_type(menv) real_type = msat_get_rational_type(menv) r2s, x_r2s = decl_consts(menv, "r2s", int_type) s2r, x_s2r = decl_consts(menv, "s2r", int_type) delta, x_delta =...
0, arg1) return msat_make_not(menv, leq) def msat_make_impl(menv: msat_env, arg0: msat_term, arg1: msat_term): n_arg0 = msat_make_not(menv, arg0) return msat_make_or(menv, n_arg0, arg1) def diverging_symbs(menv: msat_env) -> frozenset: real_type = msat_get_rational_type(menv) delta = msat_declar...
174
174
582
33
141
EnricoMagnago/F3
benchmarks/f3_wrong_hints_permutations/scaling_ltl_timed_transition_system/17-sender_receiver_37.py
Python
check_ltl
check_ltl
92
134
92
93
c5b5ab0268bf90901fb127d8beeeb6d18e40ef34
bigcode/the-stack
train
9936e17d22f0d467f2f685bc
train
function
def msat_make_gt(menv: msat_env, arg0: msat_term, arg1: msat_term): leq = msat_make_leq(menv, arg0, arg1) return msat_make_not(menv, leq)
def msat_make_gt(menv: msat_env, arg0: msat_term, arg1: msat_term):
leq = msat_make_leq(menv, arg0, arg1) return msat_make_not(menv, leq)
q(menv: msat_env, arg0: msat_term, arg1: msat_term): return msat_make_leq(menv, arg1, arg0) def msat_make_gt(menv: msat_env, arg0: msat_term, arg1: msat_term):
64
64
56
26
38
EnricoMagnago/F3
benchmarks/f3_wrong_hints_permutations/scaling_ltl_timed_transition_system/17-sender_receiver_37.py
Python
msat_make_gt
msat_make_gt
75
77
75
75
6ebfbc8ba8c3ffb3ba712af6009f476ff9bc91f6
bigcode/the-stack
train
d8a673742869191edce5fb33
train
class
class Receiver(Module): def __init__(self, name: str, menv: msat_env, enc: LTLEncoder, in_c, x_in_c, out_c, x_out_c, delta): super().__init__(name, menv, enc) bool_type = msat_get_bool_type(menv) loc, x_loc = self._symb("l", bool_type) self.wait = loc self....
class Receiver(Module):
def __init__(self, name: str, menv: msat_env, enc: LTLEncoder, in_c, x_in_c, out_c, x_out_c, delta): super().__init__(name, menv, enc) bool_type = msat_get_bool_type(menv) loc, x_loc = self._symb("l", bool_type) self.wait = loc self.work = msat_make_not(men...
_make_and(menv, disc_t, self.wait_ack) rhs = msat_make_iff(menv, self.x_send, msat_make_and(menv, msat_make_equal(menv, in_c, msg_id), msat_make_lt(menv, c, timeout))) self.trans = msat_make_a...
178
178
594
4
174
EnricoMagnago/F3
benchmarks/f3_wrong_hints_permutations/scaling_ltl_timed_transition_system/17-sender_receiver_37.py
Python
Receiver
Receiver
290
339
290
290
a6252a2abab9f9e2231191273b9dd082b68e6e47
bigcode/the-stack
train