_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q237800
HSClient.get_embedded_object
train
def get_embedded_object(self, signature_id): ''' Retrieves a embedded signing object Retrieves an embedded object containing a signature url that can be opened in an iFrame. Args: signature_id (str): The id of the signature to get a signature url for Returns: ...
python
{ "resource": "" }
q237801
HSClient.get_template_edit_url
train
def get_template_edit_url(self, template_id): ''' Retrieves a embedded template for editing Retrieves an embedded object containing a template url that can be opened in an iFrame. Args: template_id (str): The id of the template to get a signature url for Returns: ...
python
{ "resource": "" }
q237802
HSClient.get_oauth_data
train
def get_oauth_data(self, code, client_id, client_secret, state): ''' Get Oauth data from HelloSign Args: code (str): Code returned by HelloSign for our callback url client_id (str): Client id of the associated app client_secret (str): Secret ...
python
{ "resource": "" }
q237803
HSClient.refresh_access_token
train
def refresh_access_token(self, refresh_token): ''' Refreshes the current access token. Gets a new access token, updates client auth and returns it. Args: refresh_token (str): Refresh token to use Returns: The new access token ''' request = ...
python
{ "resource": "" }
q237804
HSClient._get_request
train
def _get_request(self, auth=None): ''' Return an http request object auth: Auth data to use Returns: A HSRequest object ''' self.request = HSRequest(auth or self.auth, self.env) self.request.response_callback = self.response_callback retu...
python
{ "resource": "" }
q237805
HSClient._authenticate
train
def _authenticate(self, email_address=None, password=None, api_key=None, access_token=None, access_token_type=None): ''' Create authentication object to send requests Args: email_address (str): Email address of the account to make the requests password (str): ...
python
{ "resource": "" }
q237806
HSClient._check_required_fields
train
def _check_required_fields(self, fields=None, either_fields=None): ''' Check the values of the fields If no value found in `fields`, an exception will be raised. `either_fields` are the fields that one of them must have a value Raises: HSException: If no value found in at l...
python
{ "resource": "" }
q237807
HSClient._send_signature_request
train
def _send_signature_request(self, test_mode=False, client_id=None, files=None, file_urls=None, title=None, subject=None, message=None, signing_redirect_url=None, signers=None, cc_email_addresses=None, form_fields_per_document=None, use_text_tags=False, hide_text_tags=False, metadata=None, ux_version=None, allow_decline...
python
{ "resource": "" }
q237808
HSClient._send_signature_request_with_template
train
def _send_signature_request_with_template(self, test_mode=False, client_id=None, template_id=None, template_ids=None, title=None, subject=None, message=None, signing_redirect_url=None, signers=None, ccs=None, custom_fields=None, metadata=None, ux_version=None, allow_decline=False): ''' To share the same logic b...
python
{ "resource": "" }
q237809
HSClient._add_remove_user_template
train
def _add_remove_user_template(self, url, template_id, account_id=None, email_address=None): ''' Add or Remove user from a Template We use this function for two tasks because they have the same API call Args: template_id (str): The id of the template account_id (s...
python
{ "resource": "" }
q237810
HSClient._add_remove_team_member
train
def _add_remove_team_member(self, url, email_address=None, account_id=None): ''' Add or Remove a team member We use this function for two different tasks because they have the same API call Args: email_address (str): Email address of the Account to add/remove ...
python
{ "resource": "" }
q237811
HSClient._create_embedded_template_draft
train
def _create_embedded_template_draft(self, client_id, signer_roles, test_mode=False, files=None, file_urls=None, title=None, subject=None, message=None, cc_roles=None, merge_fields=None, use_preexisting_fields=False): ''' Helper method for creating embedded template drafts. See public function for pa...
python
{ "resource": "" }
q237812
HSClient._create_embedded_unclaimed_draft_with_template
train
def _create_embedded_unclaimed_draft_with_template(self, test_mode=False, client_id=None, is_for_embedded_signing=False, template_id=None, template_ids=None, requester_email_address=None, title=None, subject=None, message=None, signers=None, ccs=None, signing_redirect_url=None, requesting_redirect_url=None, metadata=No...
python
{ "resource": "" }
q237813
HSRequest.get_file
train
def get_file(self, url, path_or_file=None, headers=None, filename=None): ''' Get a file from a url and save it as `filename` Args: url (str): URL to send the request to path_or_file (str or file): A writable File-like object or a path to save the file to. filename ...
python
{ "resource": "" }
q237814
HSRequest.get
train
def get(self, url, headers=None, parameters=None, get_json=True): ''' Send a GET request with custome headers and parameters Args: url (str): URL to send the request to headers (str, optional): custom headers parameters (str, optional): optional parameters R...
python
{ "resource": "" }
q237815
HSRequest.post
train
def post(self, url, data=None, files=None, headers=None, get_json=True): ''' Make POST request to a url Args: url (str): URL to send the request to data (dict, optional): Data to send files (dict, optional): Files to send with the request headers (str, op...
python
{ "resource": "" }
q237816
HSRequest._get_json_response
train
def _get_json_response(self, resp): ''' Parse a JSON response ''' if resp is not None and resp.text is not None: try: text = resp.text.strip('\n') if len(text) > 0: return json.loads(text) except ValueError as e: ...
python
{ "resource": "" }
q237817
HSRequest._process_json_response
train
def _process_json_response(self, response): ''' Process a given response ''' json_response = self._get_json_response(response) if self.response_callback is not None: json_response = self.response_callback(json_response) response._content = json.dumps(json_respon...
python
{ "resource": "" }
q237818
HSRequest._check_error
train
def _check_error(self, response, json_response=None): ''' Check for HTTP error code from the response, raise exception if there's any Args: response (object): Object returned by requests' `get` and `post` methods json_response (dict): JSON response, if applicabl...
python
{ "resource": "" }
q237819
HSRequest._check_warnings
train
def _check_warnings(self, json_response): ''' Extract warnings from the response to make them accessible Args: json_response (dict): JSON response ''' self.warnings = None if json_response: self.warnings = json_response.get('warnings') ...
python
{ "resource": "" }
q237820
HSAccessTokenAuth.from_response
train
def from_response(self, response_data): ''' Builds a new HSAccessTokenAuth straight from response data Args: response_data (dict): Response data to use Returns: A HSAccessTokenAuth objet ''' return HSAccessTokenAuth( response_data['access_t...
python
{ "resource": "" }
q237821
SignatureRequest.find_response_component
train
def find_response_component(self, api_id=None, signature_id=None): ''' Find one or many repsonse components. Args: api_id (str): Api id associated with the component(s) to be retrieved. signature_id (str): Signature id associated with the component(s)...
python
{ "resource": "" }
q237822
SignatureRequest.find_signature
train
def find_signature(self, signature_id=None, signer_email_address=None): ''' Return a signature for the given parameters Args: signature_id (str): Id of the signature to retrieve. signer_email_address (str): Email address of the associated signer for ...
python
{ "resource": "" }
q237823
api_resource._uncamelize
train
def _uncamelize(self, s): ''' Convert a camel-cased string to using underscores ''' res = '' if s: for i in range(len(s)): if i > 0 and s[i].lower() != s[i]: res += '_' res += s[i].lower() return res
python
{ "resource": "" }
q237824
HSFormat.format_file_params
train
def format_file_params(files): ''' Utility method for formatting file parameters for transmission ''' files_payload = {} if files: for idx, filename in enumerate(files): files_payload["file[" + str(idx) + "]"] = open(filename, 'rb') return ...
python
{ "resource": "" }
q237825
HSFormat.format_file_url_params
train
def format_file_url_params(file_urls): ''' Utility method for formatting file URL parameters for transmission ''' file_urls_payload = {} if file_urls: for idx, fileurl in enumerate(file_urls): file_urls_payload["file_url[" + str(idx) + "]"] = fileu...
python
{ "resource": "" }
q237826
HSFormat.format_single_dict
train
def format_single_dict(dictionary, output_name): ''' Currently used for metadata fields ''' output_payload = {} if dictionary: for (k, v) in dictionary.items(): output_payload[output_name + '[' + k + ']'] = v return output_payload
python
{ "resource": "" }
q237827
HSFormat.format_custom_fields
train
def format_custom_fields(list_of_custom_fields): ''' Custom fields formatting for submission ''' output_payload = {} if list_of_custom_fields: # custom_field: {"name": value} for custom_field in list_of_custom_fields: for key, value in ...
python
{ "resource": "" }
q237828
Setup.read
train
def read(fname, fail_silently=False): """ Read the content of the given file. The path is evaluated from the directory containing this file. """ try: filepath = os.path.join(os.path.dirname(__file__), fname) with io.open(filepath, 'rt', encoding='utf8') as...
python
{ "resource": "" }
q237829
pass_verbosity
train
def pass_verbosity(f): """ Marks a callback as wanting to receive the verbosity as a keyword argument. """ def new_func(*args, **kwargs): kwargs['verbosity'] = click.get_current_context().verbosity return f(*args, **kwargs) return update_wrapper(new_func, f)
python
{ "resource": "" }
q237830
DjangoCommandMixin.run_from_argv
train
def run_from_argv(self, argv): """ Called when run from the command line. """ try: return self.main(args=argv[2:], standalone_mode=False) except click.ClickException as e: if getattr(e.ctx, 'traceback', False): raise e.show() ...
python
{ "resource": "" }
q237831
encrypt
train
def encrypt(data, key): '''encrypt the data with the key''' data = __tobytes(data) data_len = len(data) data = ffi.from_buffer(data) key = ffi.from_buffer(__tobytes(key)) out_len = ffi.new('size_t *') result = lib.xxtea_encrypt(data, data_len, key, out_len) ret = ffi.buffer(result, out_l...
python
{ "resource": "" }
q237832
decrypt
train
def decrypt(data, key): '''decrypt the data with the key''' data_len = len(data) data = ffi.from_buffer(data) key = ffi.from_buffer(__tobytes(key)) out_len = ffi.new('size_t *') result = lib.xxtea_decrypt(data, data_len, key, out_len) ret = ffi.buffer(result, out_len[0])[:] lib.free(resu...
python
{ "resource": "" }
q237833
flaskrun
train
def flaskrun(app, default_host="127.0.0.1", default_port="8000"): """ Takes a flask.Flask instance and runs it. Parses command-line flags to configure the app. """ # Set up the command-line options parser = optparse.OptionParser() parser.add_option( "-H", "--host", h...
python
{ "resource": "" }
q237834
CuratedWhitelistCache.get_randomized_guid_sample
train
def get_randomized_guid_sample(self, item_count): """ Fetch a subset of randomzied GUIDs from the whitelist """ dataset = self.get_whitelist() random.shuffle(dataset) return dataset[:item_count]
python
{ "resource": "" }
q237835
CuratedRecommender.can_recommend
train
def can_recommend(self, client_data, extra_data={}): """The Curated recommender will always be able to recommend something""" self.logger.info("Curated can_recommend: {}".format(True)) return True
python
{ "resource": "" }
q237836
CuratedRecommender.recommend
train
def recommend(self, client_data, limit, extra_data={}): """ Curated recommendations are just random selections """ guids = self._curated_wl.get_randomized_guid_sample(limit) results = [(guid, 1.0) for guid in guids] log_data = (client_data["client_id"], str(guids)) ...
python
{ "resource": "" }
q237837
HybridRecommender.recommend
train
def recommend(self, client_data, limit, extra_data={}): """ Hybrid recommendations simply select half recommendations from the ensemble recommender, and half from the curated one. Duplicate recommendations are accomodated by rank ordering by weight. """ preinsta...
python
{ "resource": "" }
q237838
EnsembleRecommender._recommend
train
def _recommend(self, client_data, limit, extra_data={}): """ Ensemble recommendations are aggregated from individual recommenders. The ensemble recommender applies a weight to the recommendation outputs of each recommender to reorder the recommendations to be a better fit. ...
python
{ "resource": "" }
q237839
LazyJSONLoader.get
train
def get(self, transform=None): """ Return the JSON defined at the S3 location in the constructor. The get method will reload the S3 object after the TTL has expired. Fetch the JSON object from cache or S3 if necessary """ if not self.has_expired() and self._cache...
python
{ "resource": "" }
q237840
hashed_download
train
def hashed_download(url, temp, digest): """Download ``url`` to ``temp``, make sure it has the SHA-256 ``digest``, and return its path.""" # Based on pip 1.4.1's URLOpener but with cert verification removed def opener(): opener = build_opener(HTTPSHandler()) # Strip out HTTPHandler to pre...
python
{ "resource": "" }
q237841
SimilarityRecommender._build_features_caches
train
def _build_features_caches(self): """This function build two feature cache matrices. That's the self.categorical_features and self.continuous_features attributes. One matrix is for the continuous features and the other is for the categorical features. This is needed to speed up...
python
{ "resource": "" }
q237842
RecommendationManager.recommend
train
def recommend(self, client_id, limit, extra_data={}): """Return recommendations for the given client. The recommendation logic will go through each recommender and pick the first one that "can_recommend". :param client_id: the client unique id. :param limit: the maximum number ...
python
{ "resource": "" }
q237843
ProfileController.get_client_profile
train
def get_client_profile(self, client_id): """This fetches a single client record out of DynamoDB """ try: response = self._table.get_item(Key={'client_id': client_id}) compressed_bytes = response['Item']['json_payload'].value json_byte_data = zlib.decompress(co...
python
{ "resource": "" }
q237844
clean_promoted_guids
train
def clean_promoted_guids(raw_promoted_guids): """ Verify that the promoted GUIDs are formatted correctly, otherwise strip it down into an empty list. """ valid = True for row in raw_promoted_guids: if len(row) != 2: valid = False break if not ( (...
python
{ "resource": "" }
q237845
TahomaApi.login
train
def login(self): """Login to Tahoma API.""" if self.__logged_in: return login = {'userId': self.__username, 'userPassword': self.__password} header = BASE_HEADERS.copy() request = requests.post(BASE_URL + 'login', data=login, ...
python
{ "resource": "" }
q237846
TahomaApi.get_user
train
def get_user(self): """Get the user informations from the server. :return: a dict with all the informations :rtype: dict raises ValueError in case of protocol issues :Example: >>> "creationTime": <time>, >>> "lastUpdateTime": <time>, >>> "userId": "<em...
python
{ "resource": "" }
q237847
TahomaApi._get_setup
train
def _get_setup(self, result): """Internal method which process the results from the server.""" self.__devices = {} if ('setup' not in result.keys() or 'devices' not in result['setup'].keys()): raise Exception( "Did not find device definition.") ...
python
{ "resource": "" }
q237848
TahomaApi.apply_actions
train
def apply_actions(self, name_of_action, actions): """Start to execute an action or a group of actions. This method takes a bunch of actions and runs them on your Tahoma box. :param name_of_action: the label/name for the action :param actions: an array of Action objects ...
python
{ "resource": "" }
q237849
TahomaApi.get_events
train
def get_events(self): """Return a set of events. Which have been occured since the last call of this method. This method should be called regulary to get all occuring Events. There are three different Event types/classes which can be returned: - DeviceStateChangedEvent...
python
{ "resource": "" }
q237850
TahomaApi._get_events
train
def _get_events(self, result): """"Internal method for being able to run unit tests.""" events = [] for event_data in result: event = Event.factory(event_data) if event is not None: events.append(event) if isinstance(event, DeviceStateCh...
python
{ "resource": "" }
q237851
TahomaApi.get_current_executions
train
def get_current_executions(self): """Get all current running executions. :return: Returns a set of running Executions or empty list. :rtype: list raises ValueError in case of protocol issues :Seealso: - apply_actions - launch_action_group - get_history...
python
{ "resource": "" }
q237852
TahomaApi.get_action_groups
train
def get_action_groups(self): """Get all Action Groups. :return: List of Action Groups """ header = BASE_HEADERS.copy() header['Cookie'] = self.__cookie request = requests.get(BASE_URL + "getActionGroups", headers=header, ...
python
{ "resource": "" }
q237853
TahomaApi.launch_action_group
train
def launch_action_group(self, action_id): """Start action group.""" header = BASE_HEADERS.copy() header['Cookie'] = self.__cookie request = requests.get( BASE_URL + 'launchActionGroup?oid=' + action_id, headers=header, timeout=10) ...
python
{ "resource": "" }
q237854
TahomaApi.get_states
train
def get_states(self, devices): """Get States of Devices.""" header = BASE_HEADERS.copy() header['Cookie'] = self.__cookie json_data = self._create_get_state_request(devices) request = requests.post( BASE_URL + 'getStates', headers=header, dat...
python
{ "resource": "" }
q237855
TahomaApi._create_get_state_request
train
def _create_get_state_request(self, given_devices): """Create state request.""" dev_list = [] if isinstance(given_devices, list): devices = given_devices else: devices = [] for dev_name, item in self.__devices.items(): if item: ...
python
{ "resource": "" }
q237856
TahomaApi._get_states
train
def _get_states(self, result): """Get states of devices.""" if 'devices' not in result.keys(): return for device_states in result['devices']: device = self.__devices[device_states['deviceURL']] try: device.set_active_states(device_states['stat...
python
{ "resource": "" }
q237857
TahomaApi.refresh_all_states
train
def refresh_all_states(self): """Update all states.""" header = BASE_HEADERS.copy() header['Cookie'] = self.__cookie request = requests.get( BASE_URL + "refreshAllStates", headers=header, timeout=10) if request.status_code != 200: self.__logged_in = Fals...
python
{ "resource": "" }
q237858
Device.set_active_state
train
def set_active_state(self, name, value): """Set active state.""" if name not in self.__active_states.keys(): raise ValueError("Can not set unknown state '" + name + "'") if (isinstance(self.__active_states[name], int) and isinstance(value, str)): # we get...
python
{ "resource": "" }
q237859
Action.add_command
train
def add_command(self, cmd_name, *args): """Add command to action.""" self.__commands.append(Command(cmd_name, args))
python
{ "resource": "" }
q237860
Action.serialize
train
def serialize(self): """Serialize action.""" commands = [] for cmd in self.commands: commands.append(cmd.serialize()) out = {'commands': commands, 'deviceURL': self.__device_url} return out
python
{ "resource": "" }
q237861
Event.factory
train
def factory(data): """Tahoma Event factory.""" if data['name'] is "DeviceStateChangedEvent": return DeviceStateChangedEvent(data) elif data['name'] is "ExecutionStateChangedEvent": return ExecutionStateChangedEvent(data) elif data['name'] is "CommandExecutionState...
python
{ "resource": "" }
q237862
parse
train
def parse(date, dayfirst=True): '''Parse a `date` into a `FlexiDate`. @param date: the date to parse - may be a string, datetime.date, datetime.datetime or FlexiDate. TODO: support for quarters e.g. Q4 1980 or 1954 Q3 TODO: support latin stuff like M.DCC.LIII TODO: convert '-' to '?' when used...
python
{ "resource": "" }
q237863
FlexiDate.as_datetime
train
def as_datetime(self): '''Get as python datetime.datetime. Require year to be a valid datetime year. Default month and day to 1 if do not exist. @return: datetime.datetime object. ''' year = int(self.year) month = int(self.month) if self.month else 1 day...
python
{ "resource": "" }
q237864
md5sum
train
def md5sum( string ): """ Generate the md5 checksum for a string Args: string (Str): The string to be checksummed. Returns: (Str): The hex checksum. """ h = hashlib.new( 'md5' ) h.update( string.encode( 'utf-8' ) ) return h.hexdigest()
python
{ "resource": "" }
q237865
file_md5
train
def file_md5( filename ): """ Generate the md5 checksum for a file Args: filename (Str): The file to be checksummed. Returns: (Str): The hex checksum Notes: If the file is gzipped, the md5 checksum returned is for the uncompressed ASCII file. """ with zopen...
python
{ "resource": "" }
q237866
validate_checksum
train
def validate_checksum( filename, md5sum ): """ Compares the md5 checksum of a file with an expected value. If the calculated and expected checksum values are not equal, ValueError is raised. If the filename `foo` is not found, will try to read a gzipped file named `foo.gz`. In this case, the ch...
python
{ "resource": "" }
q237867
to_matrix
train
def to_matrix( xx, yy, zz, xy, yz, xz ): """ Convert a list of matrix components to a symmetric 3x3 matrix. Inputs should be in the order xx, yy, zz, xy, yz, xz. Args: xx (float): xx component of the matrix. yy (float): yy component of the matrix. zz (float): zz component of the...
python
{ "resource": "" }
q237868
absorption_coefficient
train
def absorption_coefficient( dielectric ): """ Calculate the optical absorption coefficient from an input set of pymatgen vasprun dielectric constant data. Args: dielectric (list): A list containing the dielectric response function in the pymatgen vasprun format. ...
python
{ "resource": "" }
q237869
Configuration.dr
train
def dr( self, atom1, atom2 ): """ Calculate the distance between two atoms. Args: atom1 (vasppy.Atom): Atom 1. atom2 (vasppy.Atom): Atom 2. Returns: (float): The distance between Atom 1 and Atom 2. """ return self.cell.dr( atom1.r, at...
python
{ "resource": "" }
q237870
area_of_a_triangle_in_cartesian_space
train
def area_of_a_triangle_in_cartesian_space( a, b, c ): """ Returns the area of a triangle defined by three points in Cartesian space. Args: a (np.array): Cartesian coordinates of point A. b (np.array): Cartesian coordinates of point B. c (np.array): Cartesian coordinates of point C. ...
python
{ "resource": "" }
q237871
points_are_in_a_straight_line
train
def points_are_in_a_straight_line( points, tolerance=1e-7 ): """ Check whether a set of points fall on a straight line. Calculates the areas of triangles formed by triplets of the points. Returns False is any of these areas are larger than the tolerance. Args: points (list(np.array)): list ...
python
{ "resource": "" }
q237872
two_point_effective_mass
train
def two_point_effective_mass( cartesian_k_points, eigenvalues ): """ Calculate the effective mass given eigenvalues at two k-points. Reimplemented from Aron Walsh's original effective mass Fortran code. Args: cartesian_k_points (np.array): 2D numpy array containing the k-points in (reciprocal) ...
python
{ "resource": "" }
q237873
least_squares_effective_mass
train
def least_squares_effective_mass( cartesian_k_points, eigenvalues ): """ Calculate the effective mass using a least squares quadratic fit. Args: cartesian_k_points (np.array): Cartesian reciprocal coordinates for the k-points eigenvalues (np.array): Energy eigenvalues at each k-point...
python
{ "resource": "" }
q237874
Procar.read_from_file
train
def read_from_file( self, filename, negative_occupancies='warn' ): """ Reads the projected wavefunction character of each band from a VASP PROCAR file. Args: filename (str): Filename of the PROCAR file. negative_occupancies (:obj:Str, optional): Sets the behaviour for ha...
python
{ "resource": "" }
q237875
load_vasp_summary
train
def load_vasp_summary( filename ): """ Reads a `vasp_summary.yaml` format YAML file and returns a dictionary of dictionaries. Each YAML document in the file corresponds to one sub-dictionary, with the corresponding top-level key given by the `title` value. Example: The file: ...
python
{ "resource": "" }
q237876
potcar_spec
train
def potcar_spec( filename ): """ Returns a dictionary specifying the pseudopotentials contained in a POTCAR file. Args: filename (Str): The name of the POTCAR file to process. Returns: (Dict): A dictionary of pseudopotential filename: dataset pairs, e.g. { 'Fe_pv': 'PBE...
python
{ "resource": "" }
q237877
find_vasp_calculations
train
def find_vasp_calculations(): """ Returns a list of all subdirectories that contain either a vasprun.xml file or a compressed vasprun.xml.gz file. Args: None Returns: (List): list of all VASP calculation subdirectories. """ dir_list = [ './' + re.sub( r'vasprun\.xml', '', p...
python
{ "resource": "" }
q237878
Summary.parse_vasprun
train
def parse_vasprun( self ): """ Read in `vasprun.xml` as a pymatgen Vasprun object. Args: None Returns: None None: If the vasprun.xml is not well formed this method will catch the ParseError and set self.vasprun = None. ""...
python
{ "resource": "" }
q237879
Doscar.read_projected_dos
train
def read_projected_dos( self ): """ Read the projected density of states data into """ pdos_list = [] for i in range( self.number_of_atoms ): df = self.read_atomic_dos_as_df( i+1 ) pdos_list.append( df ) self.pdos = np.vstack( [ np.array( df ) for df in pd...
python
{ "resource": "" }
q237880
Doscar.pdos_select
train
def pdos_select( self, atoms=None, spin=None, l=None, m=None ): """ Returns a subset of the projected density of states array. Args: atoms (int or list(int)): Atom numbers to include in the selection. Atom numbers count from 1. Default is to selec...
python
{ "resource": "" }
q237881
Calculation.scale_stoichiometry
train
def scale_stoichiometry( self, scaling ): """ Scale the Calculation stoichiometry Returns the stoichiometry, scaled by the argument scaling. Args: scaling (float): The scaling factor. Returns: (Counter(Str:Int)): The scaled stoichiometry as a Counter of ...
python
{ "resource": "" }
q237882
angle
train
def angle( x, y ): """ Calculate the angle between two vectors, in degrees. Args: x (np.array): one vector. y (np.array): the other vector. Returns: (float): the angle between x and y in degrees. """ dot = np.dot( x, y ) x_mod = np.linalg.norm( x ) y_mod = ...
python
{ "resource": "" }
q237883
Cell.minimum_image
train
def minimum_image( self, r1, r2 ): """ Find the minimum image vector from point r1 to point r2. Args: r1 (np.array): fractional coordinates of point r1. r2 (np.array): fractional coordinates of point r2. Returns: (np.array): the fractional coordinate...
python
{ "resource": "" }
q237884
Cell.minimum_image_dr
train
def minimum_image_dr( self, r1, r2, cutoff=None ): """ Calculate the shortest distance between two points in the cell, accounting for periodic boundary conditions. Args: r1 (np.array): fractional coordinates of point r1. r2 (np.array): fractional coordinates of ...
python
{ "resource": "" }
q237885
Cell.lengths
train
def lengths( self ): """ The cell lengths. Args: None Returns: (np.array(a,b,c)): The cell lengths. """ return( np.array( [ math.sqrt( sum( row**2 ) ) for row in self.matrix ] ) )
python
{ "resource": "" }
q237886
Cell.inside_cell
train
def inside_cell( self, r ): """ Given a fractional-coordinate, if this lies outside the cell return the equivalent point inside the cell. Args: r (np.array): Fractional coordinates of a point (this may be outside the cell boundaries). Returns: (np.array): Fracti...
python
{ "resource": "" }
q237887
Cell.volume
train
def volume( self ): """ The cell volume. Args: None Returns: (float): The cell volume. """ return np.dot( self.matrix[0], np.cross( self.matrix[1], self.matrix[2] ) )
python
{ "resource": "" }
q237888
VASPMeta.from_file
train
def from_file( cls, filename ): """ Create a VASPMeta object by reading a `vaspmeta.yaml` file Args: filename (Str): filename to read in. Returns: (vasppy.VASPMeta): the VASPMeta object """ with open( filename, 'r' ) as stream: data =...
python
{ "resource": "" }
q237889
vasp_version_from_outcar
train
def vasp_version_from_outcar( filename='OUTCAR' ): """ Returns the first line from a VASP OUTCAR file, to get the VASP source version string. Args: filename (Str, optional): OUTCAR filename. Defaults to 'OUTCAR'. Returns: (Str): The first line read from the OUTCAR file. """ wit...
python
{ "resource": "" }
q237890
potcar_eatom_list_from_outcar
train
def potcar_eatom_list_from_outcar( filename='OUTCAR' ): """ Returns a list of EATOM values for the pseudopotentials used. Args: filename (Str, optional): OUTCAR filename. Defaults to 'OUTCAR'. Returns: (List(Float)): A list of EATOM values, in the order they appear in the OUTCAR. "...
python
{ "resource": "" }
q237891
build_description
train
def build_description(node=None): """Return a multi-line string describing a `logging_tree.nodes.Node`. If no `node` argument is provided, then the entire tree of currently active `logging` loggers is printed out. """ if node is None: from logging_tree.nodes import tree node = tree...
python
{ "resource": "" }
q237892
_describe
train
def _describe(node, parent): """Generate lines describing the given `node` tuple. This is the recursive back-end that powers ``describe()``. With its extra ``parent`` parameter, this routine remembers the nearest non-placeholder ancestor so that it can compare it against the actual value of the ``...
python
{ "resource": "" }
q237893
describe_filter
train
def describe_filter(f): """Return text describing the logging filter `f`.""" if f.__class__ is logging.Filter: # using type() breaks in Python <= 2.6 return 'name=%r' % f.name return repr(f)
python
{ "resource": "" }
q237894
describe_handler
train
def describe_handler(h): """Yield one or more lines describing the logging handler `h`.""" t = h.__class__ # using type() breaks in Python <= 2.6 format = handler_formats.get(t) if format is not None: yield format % h.__dict__ else: yield repr(h) level = getattr(h, 'level', logg...
python
{ "resource": "" }
q237895
tree
train
def tree(): """Return a tree of tuples representing the logger layout. Each tuple looks like ``('logger-name', <Logger>, [...])`` where the third element is a list of zero or more child tuples that share the same layout. """ root = ('', logging.root, []) nodes = {} items = list(logging...
python
{ "resource": "" }
q237896
patched_str
train
def patched_str(self): """ Try to pretty-print the exception, if this is going on screen. """ def red(words): return u("\033[31m\033[49m%s\033[0m") % words def white(words): return u("\033[37m\033[49m%s\033[0m") % words def blue(words): return u("\033[34m\033[49m%s\033[0m") % words ...
python
{ "resource": "" }
q237897
ScoreMixin.h
train
def h(self): r""" Returns the step size to be used in numerical differentiation with respect to the model parameters. The step size is given as a vector with length ``n_modelparams`` so that each model parameter can be weighted independently. """ if np....
python
{ "resource": "" }
q237898
DirectViewParallelizedModel.clear_cache
train
def clear_cache(self): """ Clears any cache associated with the serial model and the engines seen by the direct view. """ self.underlying_model.clear_cache() try: logger.info('DirectView results has {} items. Clearing.'.format( len(self._dv.res...
python
{ "resource": "" }
q237899
SMCUpdater._maybe_resample
train
def _maybe_resample(self): """ Checks the resample threshold and conditionally resamples. """ ess = self.n_ess if ess <= 10: warnings.warn( "Extremely small n_ess encountered ({}). " "Resampling is likely to fail. Consider adding partic...
python
{ "resource": "" }