repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
52
3.87M
func_code_tokens
listlengths
15
672k
func_documentation_string
stringlengths
1
47.2k
func_documentation_tokens
listlengths
1
3.92k
split_name
stringclasses
1 value
func_code_url
stringlengths
85
339
Kunstmord/datalib
src/dataset.py
DataSetBase.extract_feature
def extract_feature(self, extractor, force_extraction=False, verbose=0, add_args=None, custom_name=None): """ Extracts a feature and stores it in the database Parameters ---------- extractor : function, which takes the path of a data point and *args as parameters and returns a feature force_extraction : boolean, if True - will re-extract feature even if a feature with this name already exists in the database, otherwise, will only extract if the feature doesn't exist in the database. default value: False verbose : int, if bigger than 0, will print the current number of the file for which data is being extracted add_args : optional arguments for the extractor (list/dictionary/tuple/whatever). if None, the extractor should take only one input argument - the file path. default value: None custom_name : string, optional name for the feature (it will be stored in the database with the custom_name instead of extractor function name). if None, the extractor function name will be used. default value: None Returns ------- None """ if self._prepopulated is False: raise errors.EmptyDatabase(self.dbpath) else: return extract_feature_base(self.dbpath, self.path_to_set, self._set_object, extractor, force_extraction, verbose, add_args, custom_name)
python
def extract_feature(self, extractor, force_extraction=False, verbose=0, add_args=None, custom_name=None): """ Extracts a feature and stores it in the database Parameters ---------- extractor : function, which takes the path of a data point and *args as parameters and returns a feature force_extraction : boolean, if True - will re-extract feature even if a feature with this name already exists in the database, otherwise, will only extract if the feature doesn't exist in the database. default value: False verbose : int, if bigger than 0, will print the current number of the file for which data is being extracted add_args : optional arguments for the extractor (list/dictionary/tuple/whatever). if None, the extractor should take only one input argument - the file path. default value: None custom_name : string, optional name for the feature (it will be stored in the database with the custom_name instead of extractor function name). if None, the extractor function name will be used. default value: None Returns ------- None """ if self._prepopulated is False: raise errors.EmptyDatabase(self.dbpath) else: return extract_feature_base(self.dbpath, self.path_to_set, self._set_object, extractor, force_extraction, verbose, add_args, custom_name)
[ "def", "extract_feature", "(", "self", ",", "extractor", ",", "force_extraction", "=", "False", ",", "verbose", "=", "0", ",", "add_args", "=", "None", ",", "custom_name", "=", "None", ")", ":", "if", "self", ".", "_prepopulated", "is", "False", ":", "ra...
Extracts a feature and stores it in the database Parameters ---------- extractor : function, which takes the path of a data point and *args as parameters and returns a feature force_extraction : boolean, if True - will re-extract feature even if a feature with this name already exists in the database, otherwise, will only extract if the feature doesn't exist in the database. default value: False verbose : int, if bigger than 0, will print the current number of the file for which data is being extracted add_args : optional arguments for the extractor (list/dictionary/tuple/whatever). if None, the extractor should take only one input argument - the file path. default value: None custom_name : string, optional name for the feature (it will be stored in the database with the custom_name instead of extractor function name). if None, the extractor function name will be used. default value: None Returns ------- None
[ "Extracts", "a", "feature", "and", "stores", "it", "in", "the", "database" ]
train
https://github.com/Kunstmord/datalib/blob/9d7db3e7c3a5feeeb5d19eb0dbee858bd2b50886/src/dataset.py#L650-L674
Kunstmord/datalib
src/dataset.py
DataSetBase.extract_feature_dependent_feature
def extract_feature_dependent_feature(self, extractor, force_extraction=False, verbose=0, add_args=None, custom_name=None): """ Extracts a feature which may be dependent on other features and stores it in the database Parameters ---------- extractor : function, which takes the path of a data point, a dictionary of all other features and *args as parameters and returns a feature force_extraction : boolean, if True - will re-extract feature even if a feature with this name already exists in the database, otherwise, will only extract if the feature doesn't exist in the database. default value: False verbose : int, if bigger than 0, will print the current number of the file for which data is being extracted add_args : optional arguments for the extractor (list/dictionary/tuple/whatever). if None, the extractor should take only one input argument - the file path. default value: None custom_name : string, optional name for the feature (it will be stored in the database with the custom_name instead of extractor function name). if None, the extractor function name will be used. default value: None Returns ------- None """ if self._prepopulated is False: raise errors.EmptyDatabase(self.dbpath) else: return extract_feature_dependent_feature_base(self.dbpath, self.path_to_set, self._set_object, extractor, force_extraction, verbose, add_args, custom_name)
python
def extract_feature_dependent_feature(self, extractor, force_extraction=False, verbose=0, add_args=None, custom_name=None): """ Extracts a feature which may be dependent on other features and stores it in the database Parameters ---------- extractor : function, which takes the path of a data point, a dictionary of all other features and *args as parameters and returns a feature force_extraction : boolean, if True - will re-extract feature even if a feature with this name already exists in the database, otherwise, will only extract if the feature doesn't exist in the database. default value: False verbose : int, if bigger than 0, will print the current number of the file for which data is being extracted add_args : optional arguments for the extractor (list/dictionary/tuple/whatever). if None, the extractor should take only one input argument - the file path. default value: None custom_name : string, optional name for the feature (it will be stored in the database with the custom_name instead of extractor function name). if None, the extractor function name will be used. default value: None Returns ------- None """ if self._prepopulated is False: raise errors.EmptyDatabase(self.dbpath) else: return extract_feature_dependent_feature_base(self.dbpath, self.path_to_set, self._set_object, extractor, force_extraction, verbose, add_args, custom_name)
[ "def", "extract_feature_dependent_feature", "(", "self", ",", "extractor", ",", "force_extraction", "=", "False", ",", "verbose", "=", "0", ",", "add_args", "=", "None", ",", "custom_name", "=", "None", ")", ":", "if", "self", ".", "_prepopulated", "is", "Fa...
Extracts a feature which may be dependent on other features and stores it in the database Parameters ---------- extractor : function, which takes the path of a data point, a dictionary of all other features and *args as parameters and returns a feature force_extraction : boolean, if True - will re-extract feature even if a feature with this name already exists in the database, otherwise, will only extract if the feature doesn't exist in the database. default value: False verbose : int, if bigger than 0, will print the current number of the file for which data is being extracted add_args : optional arguments for the extractor (list/dictionary/tuple/whatever). if None, the extractor should take only one input argument - the file path. default value: None custom_name : string, optional name for the feature (it will be stored in the database with the custom_name instead of extractor function name). if None, the extractor function name will be used. default value: None Returns ------- None
[ "Extracts", "a", "feature", "which", "may", "be", "dependent", "on", "other", "features", "and", "stores", "it", "in", "the", "database" ]
train
https://github.com/Kunstmord/datalib/blob/9d7db3e7c3a5feeeb5d19eb0dbee858bd2b50886/src/dataset.py#L676-L702
Kunstmord/datalib
src/dataset.py
DataSetBase.return_features
def return_features(self, names='all'): """ Returns a list of extracted features from the database Parameters ---------- names : list of strings, a list of feature names which are to be retrieved from the database, if equal to 'all', the all features will be returned, default value: 'all' Returns ------- A list of lists, each 'inside list' corresponds to a single data point, each element of the 'inside list' is a feature (can be of any type) """ if self._prepopulated is False: raise errors.EmptyDatabase(self.dbpath) else: return return_features_base(self.dbpath, self._set_object, names)
python
def return_features(self, names='all'): """ Returns a list of extracted features from the database Parameters ---------- names : list of strings, a list of feature names which are to be retrieved from the database, if equal to 'all', the all features will be returned, default value: 'all' Returns ------- A list of lists, each 'inside list' corresponds to a single data point, each element of the 'inside list' is a feature (can be of any type) """ if self._prepopulated is False: raise errors.EmptyDatabase(self.dbpath) else: return return_features_base(self.dbpath, self._set_object, names)
[ "def", "return_features", "(", "self", ",", "names", "=", "'all'", ")", ":", "if", "self", ".", "_prepopulated", "is", "False", ":", "raise", "errors", ".", "EmptyDatabase", "(", "self", ".", "dbpath", ")", "else", ":", "return", "return_features_base", "(...
Returns a list of extracted features from the database Parameters ---------- names : list of strings, a list of feature names which are to be retrieved from the database, if equal to 'all', the all features will be returned, default value: 'all' Returns ------- A list of lists, each 'inside list' corresponds to a single data point, each element of the 'inside list' is a feature (can be of any type)
[ "Returns", "a", "list", "of", "extracted", "features", "from", "the", "database" ]
train
https://github.com/Kunstmord/datalib/blob/9d7db3e7c3a5feeeb5d19eb0dbee858bd2b50886/src/dataset.py#L704-L721
Kunstmord/datalib
src/dataset.py
DataSetBase.return_features_numpy
def return_features_numpy(self, names='all'): """ Returns a 2d numpy array of extracted features Parameters ---------- names : list of strings, a list of feature names which are to be retrieved from the database, if equal to 'all', all features will be returned, default value: 'all' Returns ------- A numpy array of features, each row corresponds to a single datapoint. If a single feature is a 1d numpy array, then it will be unrolled into the resulting array. Higher-dimensional numpy arrays are not supported. """ if self._prepopulated is False: raise errors.EmptyDatabase(self.dbpath) else: return return_features_numpy_base(self.dbpath, self._set_object, self.points_amt, names)
python
def return_features_numpy(self, names='all'): """ Returns a 2d numpy array of extracted features Parameters ---------- names : list of strings, a list of feature names which are to be retrieved from the database, if equal to 'all', all features will be returned, default value: 'all' Returns ------- A numpy array of features, each row corresponds to a single datapoint. If a single feature is a 1d numpy array, then it will be unrolled into the resulting array. Higher-dimensional numpy arrays are not supported. """ if self._prepopulated is False: raise errors.EmptyDatabase(self.dbpath) else: return return_features_numpy_base(self.dbpath, self._set_object, self.points_amt, names)
[ "def", "return_features_numpy", "(", "self", ",", "names", "=", "'all'", ")", ":", "if", "self", ".", "_prepopulated", "is", "False", ":", "raise", "errors", ".", "EmptyDatabase", "(", "self", ".", "dbpath", ")", "else", ":", "return", "return_features_numpy...
Returns a 2d numpy array of extracted features Parameters ---------- names : list of strings, a list of feature names which are to be retrieved from the database, if equal to 'all', all features will be returned, default value: 'all' Returns ------- A numpy array of features, each row corresponds to a single datapoint. If a single feature is a 1d numpy array, then it will be unrolled into the resulting array. Higher-dimensional numpy arrays are not supported.
[ "Returns", "a", "2d", "numpy", "array", "of", "extracted", "features" ]
train
https://github.com/Kunstmord/datalib/blob/9d7db3e7c3a5feeeb5d19eb0dbee858bd2b50886/src/dataset.py#L723-L740
Kunstmord/datalib
src/dataset.py
DataSetBase.return_real_id
def return_real_id(self): """ Returns a list of real_id's Parameters ---------- Returns ------- A list of real_id values for the dataset (a real_id is the filename minus the suffix and prefix) """ if self._prepopulated is False: raise errors.EmptyDatabase(self.dbpath) else: return return_real_id_base(self.dbpath, self._set_object)
python
def return_real_id(self): """ Returns a list of real_id's Parameters ---------- Returns ------- A list of real_id values for the dataset (a real_id is the filename minus the suffix and prefix) """ if self._prepopulated is False: raise errors.EmptyDatabase(self.dbpath) else: return return_real_id_base(self.dbpath, self._set_object)
[ "def", "return_real_id", "(", "self", ")", ":", "if", "self", ".", "_prepopulated", "is", "False", ":", "raise", "errors", ".", "EmptyDatabase", "(", "self", ".", "dbpath", ")", "else", ":", "return", "return_real_id_base", "(", "self", ".", "dbpath", ",",...
Returns a list of real_id's Parameters ---------- Returns ------- A list of real_id values for the dataset (a real_id is the filename minus the suffix and prefix)
[ "Returns", "a", "list", "of", "real_id", "s" ]
train
https://github.com/Kunstmord/datalib/blob/9d7db3e7c3a5feeeb5d19eb0dbee858bd2b50886/src/dataset.py#L742-L756
Kunstmord/datalib
src/dataset.py
DataSetBase.copy_features
def copy_features(self, dbpath_origin, force_copy=False): """ Copies features from one database to another (base object should be of the same type) Parameters ---------- dbpath_origin : string, path to SQLite database file from which the features will be copied force_copy : boolean, if True - will overwrite features with same name when copying, if False, won't; default value: False Returns ------- None """ copy_features_base(dbpath_origin, self.dbpath, self._set_object, force_copy) return None
python
def copy_features(self, dbpath_origin, force_copy=False): """ Copies features from one database to another (base object should be of the same type) Parameters ---------- dbpath_origin : string, path to SQLite database file from which the features will be copied force_copy : boolean, if True - will overwrite features with same name when copying, if False, won't; default value: False Returns ------- None """ copy_features_base(dbpath_origin, self.dbpath, self._set_object, force_copy) return None
[ "def", "copy_features", "(", "self", ",", "dbpath_origin", ",", "force_copy", "=", "False", ")", ":", "copy_features_base", "(", "dbpath_origin", ",", "self", ".", "dbpath", ",", "self", ".", "_set_object", ",", "force_copy", ")", "return", "None" ]
Copies features from one database to another (base object should be of the same type) Parameters ---------- dbpath_origin : string, path to SQLite database file from which the features will be copied force_copy : boolean, if True - will overwrite features with same name when copying, if False, won't; default value: False Returns ------- None
[ "Copies", "features", "from", "one", "database", "to", "another", "(", "base", "object", "should", "be", "of", "the", "same", "type", ")" ]
train
https://github.com/Kunstmord/datalib/blob/9d7db3e7c3a5feeeb5d19eb0dbee858bd2b50886/src/dataset.py#L785-L800
Kunstmord/datalib
src/dataset.py
DataSetBase.return_single_convert_numpy
def return_single_convert_numpy(self, object_id, converter, add_args=None): """ Converts an object specified by the object_id into a numpy array and returns the array, the conversion is done by the 'converter' function Parameters ---------- object_id : int, id of object in database converter : function, which takes the path of a data point and *args as parameters and returns a numpy array add_args : optional arguments for the converter (list/dictionary/tuple/whatever). if None, the converter should take only one input argument - the file path. default value: None Returns ------- result : ndarray """ return return_single_convert_numpy_base(self.dbpath, self.path_to_set, self._set_object, object_id, converter, add_args)
python
def return_single_convert_numpy(self, object_id, converter, add_args=None): """ Converts an object specified by the object_id into a numpy array and returns the array, the conversion is done by the 'converter' function Parameters ---------- object_id : int, id of object in database converter : function, which takes the path of a data point and *args as parameters and returns a numpy array add_args : optional arguments for the converter (list/dictionary/tuple/whatever). if None, the converter should take only one input argument - the file path. default value: None Returns ------- result : ndarray """ return return_single_convert_numpy_base(self.dbpath, self.path_to_set, self._set_object, object_id, converter, add_args)
[ "def", "return_single_convert_numpy", "(", "self", ",", "object_id", ",", "converter", ",", "add_args", "=", "None", ")", ":", "return", "return_single_convert_numpy_base", "(", "self", ".", "dbpath", ",", "self", ".", "path_to_set", ",", "self", ".", "_set_obje...
Converts an object specified by the object_id into a numpy array and returns the array, the conversion is done by the 'converter' function Parameters ---------- object_id : int, id of object in database converter : function, which takes the path of a data point and *args as parameters and returns a numpy array add_args : optional arguments for the converter (list/dictionary/tuple/whatever). if None, the converter should take only one input argument - the file path. default value: None Returns ------- result : ndarray
[ "Converts", "an", "object", "specified", "by", "the", "object_id", "into", "a", "numpy", "array", "and", "returns", "the", "array", "the", "conversion", "is", "done", "by", "the", "converter", "function" ]
train
https://github.com/Kunstmord/datalib/blob/9d7db3e7c3a5feeeb5d19eb0dbee858bd2b50886/src/dataset.py#L845-L862
Kunstmord/datalib
src/dataset.py
DataSetBase.return_multiple_convert_numpy
def return_multiple_convert_numpy(self, start_id, end_id, converter, add_args=None): """ Converts several objects, with ids in the range (start_id, end_id) into a 2d numpy array and returns the array, the conversion is done by the 'converter' function Parameters ---------- start_id : the id of the first object to be converted end_id : the id of the last object to be converted, if equal to -1, will convert all data points in range (start_id, <id of last element in database>) converter : function, which takes the path of a data point and *args as parameters and returns a numpy array add_args : optional arguments for the converter (list/dictionary/tuple/whatever). if None, the converter should take only one input argument - the file path. default value: None Returns ------- result : 2-dimensional ndarray """ if end_id == -1: end_id = self.points_amt return return_multiple_convert_numpy_base(self.dbpath, self.path_to_set, self._set_object, start_id, end_id, converter, add_args)
python
def return_multiple_convert_numpy(self, start_id, end_id, converter, add_args=None): """ Converts several objects, with ids in the range (start_id, end_id) into a 2d numpy array and returns the array, the conversion is done by the 'converter' function Parameters ---------- start_id : the id of the first object to be converted end_id : the id of the last object to be converted, if equal to -1, will convert all data points in range (start_id, <id of last element in database>) converter : function, which takes the path of a data point and *args as parameters and returns a numpy array add_args : optional arguments for the converter (list/dictionary/tuple/whatever). if None, the converter should take only one input argument - the file path. default value: None Returns ------- result : 2-dimensional ndarray """ if end_id == -1: end_id = self.points_amt return return_multiple_convert_numpy_base(self.dbpath, self.path_to_set, self._set_object, start_id, end_id, converter, add_args)
[ "def", "return_multiple_convert_numpy", "(", "self", ",", "start_id", ",", "end_id", ",", "converter", ",", "add_args", "=", "None", ")", ":", "if", "end_id", "==", "-", "1", ":", "end_id", "=", "self", ".", "points_amt", "return", "return_multiple_convert_num...
Converts several objects, with ids in the range (start_id, end_id) into a 2d numpy array and returns the array, the conversion is done by the 'converter' function Parameters ---------- start_id : the id of the first object to be converted end_id : the id of the last object to be converted, if equal to -1, will convert all data points in range (start_id, <id of last element in database>) converter : function, which takes the path of a data point and *args as parameters and returns a numpy array add_args : optional arguments for the converter (list/dictionary/tuple/whatever). if None, the converter should take only one input argument - the file path. default value: None Returns ------- result : 2-dimensional ndarray
[ "Converts", "several", "objects", "with", "ids", "in", "the", "range", "(", "start_id", "end_id", ")", "into", "a", "2d", "numpy", "array", "and", "returns", "the", "array", "the", "conversion", "is", "done", "by", "the", "converter", "function" ]
train
https://github.com/Kunstmord/datalib/blob/9d7db3e7c3a5feeeb5d19eb0dbee858bd2b50886/src/dataset.py#L864-L885
Kunstmord/datalib
src/dataset.py
DataSetBase.dump_feature
def dump_feature(self, feature_name, feature, force_extraction=True): """ Dumps a list of lists or ndarray of features into database (allows to copy features from a pre-existing .txt/.csv/.whatever file, for example) Parameters ---------- feature : list of lists or ndarray, contains the data to be written to the database force_extraction : boolean, if True - will overwrite any existing feature with this name default value: False Returns ------- None """ dump_feature_base(self.dbpath, self._set_object, self.points_amt, feature_name, feature, force_extraction) return None
python
def dump_feature(self, feature_name, feature, force_extraction=True): """ Dumps a list of lists or ndarray of features into database (allows to copy features from a pre-existing .txt/.csv/.whatever file, for example) Parameters ---------- feature : list of lists or ndarray, contains the data to be written to the database force_extraction : boolean, if True - will overwrite any existing feature with this name default value: False Returns ------- None """ dump_feature_base(self.dbpath, self._set_object, self.points_amt, feature_name, feature, force_extraction) return None
[ "def", "dump_feature", "(", "self", ",", "feature_name", ",", "feature", ",", "force_extraction", "=", "True", ")", ":", "dump_feature_base", "(", "self", ".", "dbpath", ",", "self", ".", "_set_object", ",", "self", ".", "points_amt", ",", "feature_name", ",...
Dumps a list of lists or ndarray of features into database (allows to copy features from a pre-existing .txt/.csv/.whatever file, for example) Parameters ---------- feature : list of lists or ndarray, contains the data to be written to the database force_extraction : boolean, if True - will overwrite any existing feature with this name default value: False Returns ------- None
[ "Dumps", "a", "list", "of", "lists", "or", "ndarray", "of", "features", "into", "database", "(", "allows", "to", "copy", "features", "from", "a", "pre", "-", "existing", ".", "txt", "/", ".", "csv", "/", ".", "whatever", "file", "for", "example", ")" ]
train
https://github.com/Kunstmord/datalib/blob/9d7db3e7c3a5feeeb5d19eb0dbee858bd2b50886/src/dataset.py#L887-L903
Kunstmord/datalib
src/dataset.py
LabeledDataSet.return_labels
def return_labels(self, original=False): """ Returns the labels of the dataset Parameters ---------- original : if True, will return original labels, if False, will return transformed labels (as defined by label_dict), default value: False Returns ------- A list of lists, each 'inside list' corresponds to a single data point, each element of the 'inside list' is a label """ if self._prepopulated is False: raise errors.EmptyDatabase(self.dbpath) else: engine = create_engine('sqlite:////' + self.dbpath) trainset.Base.metadata.create_all(engine) session_cl = sessionmaker(bind=engine) session = session_cl() return_list = [] for i in session.query(trainset.TrainSet).order_by(trainset.TrainSet.id): if original is True: row_list = i.labels['original'] else: row_list = i.labels['transformed'] return_list.append(row_list[:]) session.close() return return_list
python
def return_labels(self, original=False): """ Returns the labels of the dataset Parameters ---------- original : if True, will return original labels, if False, will return transformed labels (as defined by label_dict), default value: False Returns ------- A list of lists, each 'inside list' corresponds to a single data point, each element of the 'inside list' is a label """ if self._prepopulated is False: raise errors.EmptyDatabase(self.dbpath) else: engine = create_engine('sqlite:////' + self.dbpath) trainset.Base.metadata.create_all(engine) session_cl = sessionmaker(bind=engine) session = session_cl() return_list = [] for i in session.query(trainset.TrainSet).order_by(trainset.TrainSet.id): if original is True: row_list = i.labels['original'] else: row_list = i.labels['transformed'] return_list.append(row_list[:]) session.close() return return_list
[ "def", "return_labels", "(", "self", ",", "original", "=", "False", ")", ":", "if", "self", ".", "_prepopulated", "is", "False", ":", "raise", "errors", ".", "EmptyDatabase", "(", "self", ".", "dbpath", ")", "else", ":", "engine", "=", "create_engine", "...
Returns the labels of the dataset Parameters ---------- original : if True, will return original labels, if False, will return transformed labels (as defined by label_dict), default value: False Returns ------- A list of lists, each 'inside list' corresponds to a single data point, each element of the 'inside list' is a label
[ "Returns", "the", "labels", "of", "the", "dataset" ]
train
https://github.com/Kunstmord/datalib/blob/9d7db3e7c3a5feeeb5d19eb0dbee858bd2b50886/src/dataset.py#L961-L990
Kunstmord/datalib
src/dataset.py
LabeledDataSet.return_labels_numpy
def return_labels_numpy(self, original=False): """ Returns a 2d numpy array of labels Parameters ---------- original : if True, will return original labels, if False, will return transformed labels (as defined by label_dict), default value: False Returns ------- A numpy array of labels, each row corresponds to a single datapoint """ if self._prepopulated is False: raise errors.EmptyDatabase(self.dbpath) else: engine = create_engine('sqlite:////' + self.dbpath) trainset.Base.metadata.create_all(engine) session_cl = sessionmaker(bind=engine) session = session_cl() tmp_object = session.query(trainset.TrainSet).get(1) columns_amt = len(tmp_object.labels['original']) return_array = np.zeros([self.points_amt, columns_amt]) for i in enumerate(session.query(trainset.TrainSet).order_by(trainset.TrainSet.id)): if original is False: return_array[i[0], :] = i[1].labels['transformed'] else: return_array[i[0], :] = i[1].labels['original'] session.close() return return_array
python
def return_labels_numpy(self, original=False): """ Returns a 2d numpy array of labels Parameters ---------- original : if True, will return original labels, if False, will return transformed labels (as defined by label_dict), default value: False Returns ------- A numpy array of labels, each row corresponds to a single datapoint """ if self._prepopulated is False: raise errors.EmptyDatabase(self.dbpath) else: engine = create_engine('sqlite:////' + self.dbpath) trainset.Base.metadata.create_all(engine) session_cl = sessionmaker(bind=engine) session = session_cl() tmp_object = session.query(trainset.TrainSet).get(1) columns_amt = len(tmp_object.labels['original']) return_array = np.zeros([self.points_amt, columns_amt]) for i in enumerate(session.query(trainset.TrainSet).order_by(trainset.TrainSet.id)): if original is False: return_array[i[0], :] = i[1].labels['transformed'] else: return_array[i[0], :] = i[1].labels['original'] session.close() return return_array
[ "def", "return_labels_numpy", "(", "self", ",", "original", "=", "False", ")", ":", "if", "self", ".", "_prepopulated", "is", "False", ":", "raise", "errors", ".", "EmptyDatabase", "(", "self", ".", "dbpath", ")", "else", ":", "engine", "=", "create_engine...
Returns a 2d numpy array of labels Parameters ---------- original : if True, will return original labels, if False, will return transformed labels (as defined by label_dict), default value: False Returns ------- A numpy array of labels, each row corresponds to a single datapoint
[ "Returns", "a", "2d", "numpy", "array", "of", "labels" ]
train
https://github.com/Kunstmord/datalib/blob/9d7db3e7c3a5feeeb5d19eb0dbee858bd2b50886/src/dataset.py#L992-L1022
Kunstmord/datalib
src/dataset.py
LabeledDataSet.return_single_labels
def return_single_labels(self, object_id): """ Returns all labels for an object specified by the object_id Parameters ---------- object_id : int, id of object in database Returns ------- result : list of labels """ engine = create_engine('sqlite:////' + self.dbpath) trainset.Base.metadata.create_all(engine) session_cl = sessionmaker(bind=engine) session = session_cl() tmp_object = session.query(trainset.TrainSet).get(object_id) return tmp_object.labels
python
def return_single_labels(self, object_id): """ Returns all labels for an object specified by the object_id Parameters ---------- object_id : int, id of object in database Returns ------- result : list of labels """ engine = create_engine('sqlite:////' + self.dbpath) trainset.Base.metadata.create_all(engine) session_cl = sessionmaker(bind=engine) session = session_cl() tmp_object = session.query(trainset.TrainSet).get(object_id) return tmp_object.labels
[ "def", "return_single_labels", "(", "self", ",", "object_id", ")", ":", "engine", "=", "create_engine", "(", "'sqlite:////'", "+", "self", ".", "dbpath", ")", "trainset", ".", "Base", ".", "metadata", ".", "create_all", "(", "engine", ")", "session_cl", "=",...
Returns all labels for an object specified by the object_id Parameters ---------- object_id : int, id of object in database Returns ------- result : list of labels
[ "Returns", "all", "labels", "for", "an", "object", "specified", "by", "the", "object_id" ]
train
https://github.com/Kunstmord/datalib/blob/9d7db3e7c3a5feeeb5d19eb0dbee858bd2b50886/src/dataset.py#L1024-L1041
benley/butcher
butcher/cache.py
CacheManager.path_in_cache
def path_in_cache(self, filename, metahash): """Generates the path to a file in the mh cache. The generated path does not imply the file's existence! Args: filename: Filename relative to buildroot rule: A targets.SomeBuildRule object metahash: hash object """ cpath = self._genpath(filename, metahash) if os.path.exists(cpath): return cpath else: raise CacheMiss
python
def path_in_cache(self, filename, metahash): """Generates the path to a file in the mh cache. The generated path does not imply the file's existence! Args: filename: Filename relative to buildroot rule: A targets.SomeBuildRule object metahash: hash object """ cpath = self._genpath(filename, metahash) if os.path.exists(cpath): return cpath else: raise CacheMiss
[ "def", "path_in_cache", "(", "self", ",", "filename", ",", "metahash", ")", ":", "cpath", "=", "self", ".", "_genpath", "(", "filename", ",", "metahash", ")", "if", "os", ".", "path", ".", "exists", "(", "cpath", ")", ":", "return", "cpath", "else", ...
Generates the path to a file in the mh cache. The generated path does not imply the file's existence! Args: filename: Filename relative to buildroot rule: A targets.SomeBuildRule object metahash: hash object
[ "Generates", "the", "path", "to", "a", "file", "in", "the", "mh", "cache", "." ]
train
https://github.com/benley/butcher/blob/8b18828ea040af56b7835beab5fd03eab23cc9ee/butcher/cache.py#L41-L55
benley/butcher
butcher/cache.py
CacheManager._genpath
def _genpath(self, filename, mhash): """Generate the path to a file in the cache. Does not check to see if the file exists. Just constructs the path where it should be. """ mhash = mhash.hexdigest() return os.path.join(self.mh_cachedir, mhash[0:2], mhash[2:4], mhash, filename)
python
def _genpath(self, filename, mhash): """Generate the path to a file in the cache. Does not check to see if the file exists. Just constructs the path where it should be. """ mhash = mhash.hexdigest() return os.path.join(self.mh_cachedir, mhash[0:2], mhash[2:4], mhash, filename)
[ "def", "_genpath", "(", "self", ",", "filename", ",", "mhash", ")", ":", "mhash", "=", "mhash", ".", "hexdigest", "(", ")", "return", "os", ".", "path", ".", "join", "(", "self", ".", "mh_cachedir", ",", "mhash", "[", "0", ":", "2", "]", ",", "mh...
Generate the path to a file in the cache. Does not check to see if the file exists. Just constructs the path where it should be.
[ "Generate", "the", "path", "to", "a", "file", "in", "the", "cache", "." ]
train
https://github.com/benley/butcher/blob/8b18828ea040af56b7835beab5fd03eab23cc9ee/butcher/cache.py#L57-L65
benley/butcher
butcher/cache.py
CacheManager.putfile
def putfile(self, filepath, buildroot, metahash): """Put a file in the cache. Args: filepath: Path to file on disk. buildroot: Path to buildroot buildrule: The rule that generated this file. metahash: hash object """ def gen_obj_path(filename): filehash = util.hash_file(filepath).hexdigest() return filehash, os.path.join(self.obj_cachedir, filehash[0:2], filehash[2:4], filehash) filepath_relative = filepath.split(buildroot)[1][1:] # Strip leading / # Path for the metahashed reference: incachepath = self._genpath(filepath_relative, metahash) filehash, obj_path = gen_obj_path(filepath) if not os.path.exists(obj_path): obj_dir = os.path.dirname(obj_path) if not os.path.exists(obj_dir): os.makedirs(obj_dir) log.debug('Adding to obj cache: %s -> %s', filepath, obj_path) os.link(filepath, obj_path) if os.path.exists(incachepath): existingfile_hash = util.hash_file(incachepath).hexdigest() if filehash != existingfile_hash: log.warn('File found in mh cache, but checksum differs. ' 'Replacing with this new version. (File: %s)', filepath) log.warn('Possible reasons for this:') log.warn(' 1. This build is not hermetic, and something ' 'differs about the build environment compared to the ' 'previous build.') log.warn(' 2. This file has a timestamp or other build-time ' 'related data encoded into it, which will always ' 'cause the checksum to differ when built.') log.warn(' 3. Everything is terrible and nothing works.') os.unlink(incachepath) if not os.path.exists(incachepath): log.debug('Adding to mh cache: %s -> %s', filepath, incachepath) if not os.path.exists(os.path.dirname(incachepath)): os.makedirs(os.path.dirname(incachepath)) os.link(obj_path, incachepath)
python
def putfile(self, filepath, buildroot, metahash): """Put a file in the cache. Args: filepath: Path to file on disk. buildroot: Path to buildroot buildrule: The rule that generated this file. metahash: hash object """ def gen_obj_path(filename): filehash = util.hash_file(filepath).hexdigest() return filehash, os.path.join(self.obj_cachedir, filehash[0:2], filehash[2:4], filehash) filepath_relative = filepath.split(buildroot)[1][1:] # Strip leading / # Path for the metahashed reference: incachepath = self._genpath(filepath_relative, metahash) filehash, obj_path = gen_obj_path(filepath) if not os.path.exists(obj_path): obj_dir = os.path.dirname(obj_path) if not os.path.exists(obj_dir): os.makedirs(obj_dir) log.debug('Adding to obj cache: %s -> %s', filepath, obj_path) os.link(filepath, obj_path) if os.path.exists(incachepath): existingfile_hash = util.hash_file(incachepath).hexdigest() if filehash != existingfile_hash: log.warn('File found in mh cache, but checksum differs. ' 'Replacing with this new version. (File: %s)', filepath) log.warn('Possible reasons for this:') log.warn(' 1. This build is not hermetic, and something ' 'differs about the build environment compared to the ' 'previous build.') log.warn(' 2. This file has a timestamp or other build-time ' 'related data encoded into it, which will always ' 'cause the checksum to differ when built.') log.warn(' 3. Everything is terrible and nothing works.') os.unlink(incachepath) if not os.path.exists(incachepath): log.debug('Adding to mh cache: %s -> %s', filepath, incachepath) if not os.path.exists(os.path.dirname(incachepath)): os.makedirs(os.path.dirname(incachepath)) os.link(obj_path, incachepath)
[ "def", "putfile", "(", "self", ",", "filepath", ",", "buildroot", ",", "metahash", ")", ":", "def", "gen_obj_path", "(", "filename", ")", ":", "filehash", "=", "util", ".", "hash_file", "(", "filepath", ")", ".", "hexdigest", "(", ")", "return", "filehas...
Put a file in the cache. Args: filepath: Path to file on disk. buildroot: Path to buildroot buildrule: The rule that generated this file. metahash: hash object
[ "Put", "a", "file", "in", "the", "cache", "." ]
train
https://github.com/benley/butcher/blob/8b18828ea040af56b7835beab5fd03eab23cc9ee/butcher/cache.py#L67-L113
benley/butcher
butcher/cache.py
CacheManager.in_cache
def in_cache(self, objpath, metahash): """Returns true if object is cached. Args: objpath: Filename relative to buildroot. metahash: hash object """ try: self.path_in_cache(objpath, metahash) return True except CacheMiss: return False
python
def in_cache(self, objpath, metahash): """Returns true if object is cached. Args: objpath: Filename relative to buildroot. metahash: hash object """ try: self.path_in_cache(objpath, metahash) return True except CacheMiss: return False
[ "def", "in_cache", "(", "self", ",", "objpath", ",", "metahash", ")", ":", "try", ":", "self", ".", "path_in_cache", "(", "objpath", ",", "metahash", ")", "return", "True", "except", "CacheMiss", ":", "return", "False" ]
Returns true if object is cached. Args: objpath: Filename relative to buildroot. metahash: hash object
[ "Returns", "true", "if", "object", "is", "cached", "." ]
train
https://github.com/benley/butcher/blob/8b18828ea040af56b7835beab5fd03eab23cc9ee/butcher/cache.py#L115-L126
benley/butcher
butcher/cache.py
CacheManager.get_obj
def get_obj(self, objpath, metahash, dst_path): """Get object from cache, write it to dst_path. Args: objpath: filename relative to buildroot (example: mini-boot/blahblah/somefile.bin) metahash: metahash. See targets/base.py dst_path: Absolute path where the file should be written. Raises: CacheMiss: if the item is not in the cache """ incachepath = self.path_in_cache(objpath, metahash) if not os.path.exists(incachepath): raise CacheMiss('%s not in cache.' % incachepath) else: log.debug('Cache hit! %s~%s', objpath, metahash.hexdigest()) if not os.path.exists(os.path.dirname(dst_path)): os.makedirs(os.path.dirname(dst_path)) os.link(incachepath, dst_path)
python
def get_obj(self, objpath, metahash, dst_path): """Get object from cache, write it to dst_path. Args: objpath: filename relative to buildroot (example: mini-boot/blahblah/somefile.bin) metahash: metahash. See targets/base.py dst_path: Absolute path where the file should be written. Raises: CacheMiss: if the item is not in the cache """ incachepath = self.path_in_cache(objpath, metahash) if not os.path.exists(incachepath): raise CacheMiss('%s not in cache.' % incachepath) else: log.debug('Cache hit! %s~%s', objpath, metahash.hexdigest()) if not os.path.exists(os.path.dirname(dst_path)): os.makedirs(os.path.dirname(dst_path)) os.link(incachepath, dst_path)
[ "def", "get_obj", "(", "self", ",", "objpath", ",", "metahash", ",", "dst_path", ")", ":", "incachepath", "=", "self", ".", "path_in_cache", "(", "objpath", ",", "metahash", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "incachepath", ")", "...
Get object from cache, write it to dst_path. Args: objpath: filename relative to buildroot (example: mini-boot/blahblah/somefile.bin) metahash: metahash. See targets/base.py dst_path: Absolute path where the file should be written. Raises: CacheMiss: if the item is not in the cache
[ "Get", "object", "from", "cache", "write", "it", "to", "dst_path", "." ]
train
https://github.com/benley/butcher/blob/8b18828ea040af56b7835beab5fd03eab23cc9ee/butcher/cache.py#L128-L146
cohorte/cohorte-herald
python/snippets/herald_mqtt/core.py
Herald._get_link
def _get_link(self, peer): """ Returns a link to the given peer :return: A Link object :raise ValueError: Unknown peer """ assert isinstance(peer, beans.Peer) # Look for a link to the peer, using routers for router in self._routers: link = router.get_link(peer) if link: return link # Not found raise ValueError("No link to peer {0}".format(peer))
python
def _get_link(self, peer): """ Returns a link to the given peer :return: A Link object :raise ValueError: Unknown peer """ assert isinstance(peer, beans.Peer) # Look for a link to the peer, using routers for router in self._routers: link = router.get_link(peer) if link: return link # Not found raise ValueError("No link to peer {0}".format(peer))
[ "def", "_get_link", "(", "self", ",", "peer", ")", ":", "assert", "isinstance", "(", "peer", ",", "beans", ".", "Peer", ")", "# Look for a link to the peer, using routers", "for", "router", "in", "self", ".", "_routers", ":", "link", "=", "router", ".", "get...
Returns a link to the given peer :return: A Link object :raise ValueError: Unknown peer
[ "Returns", "a", "link", "to", "the", "given", "peer" ]
train
https://github.com/cohorte/cohorte-herald/blob/bb3445d0031c8b3abad71e6219cc559b49faa3ee/python/snippets/herald_mqtt/core.py#L22-L38
cohorte/cohorte-herald
python/snippets/herald_mqtt/core.py
Herald.send
def send(self, peer_id, message): """ Synchronously sends a message :param peer_id: UUID of a peer :param message: Message to send to the peer :raise KeyError: Unknown peer :raise ValueError: No link to the peer """ assert isinstance(message, beans.RawMessage) # Get peer description (raises KeyError) peer = self._directory.get_peer(peer_id) # Get a link to the peer (raises ValueError) link = self._get_link(peer) assert isinstance(link, beans.AbstractLink) # Call the link, and return its result return link.send(message)
python
def send(self, peer_id, message): """ Synchronously sends a message :param peer_id: UUID of a peer :param message: Message to send to the peer :raise KeyError: Unknown peer :raise ValueError: No link to the peer """ assert isinstance(message, beans.RawMessage) # Get peer description (raises KeyError) peer = self._directory.get_peer(peer_id) # Get a link to the peer (raises ValueError) link = self._get_link(peer) assert isinstance(link, beans.AbstractLink) # Call the link, and return its result return link.send(message)
[ "def", "send", "(", "self", ",", "peer_id", ",", "message", ")", ":", "assert", "isinstance", "(", "message", ",", "beans", ".", "RawMessage", ")", "# Get peer description (raises KeyError)", "peer", "=", "self", ".", "_directory", ".", "get_peer", "(", "peer_...
Synchronously sends a message :param peer_id: UUID of a peer :param message: Message to send to the peer :raise KeyError: Unknown peer :raise ValueError: No link to the peer
[ "Synchronously", "sends", "a", "message" ]
train
https://github.com/cohorte/cohorte-herald/blob/bb3445d0031c8b3abad71e6219cc559b49faa3ee/python/snippets/herald_mqtt/core.py#L41-L60
mozilla/socorrolib
socorrolib/lib/converters.py
str_to_classes_in_namespaces_converter
def str_to_classes_in_namespaces_converter( template_for_namespace="%(name)s", list_splitter_fn=_default_list_splitter, class_extractor=_default_class_extractor, name_of_class_option='qualified_class_name', instantiate_classes=False, ): """ parameters: template_for_namespace - a template for the names of the namespaces that will contain the classes and their associated required config options. There are two template variables available: %(name)s - the name of the class to be contained in the namespace; %(index)d - the sequential index number of the namespace. list_converter - a function that will take the string list of classes and break it up into a sequence if individual elements class_extractor - a function that will return the string version of a classname from the result of the list_converter """ # ------------------------------------------------------------------------- def class_list_converter(class_list_str): """This function becomes the actual converter used by configman to take a string and convert it into the nested sequence of Namespaces, one for each class in the list. It does this by creating a proxy class stuffed with its own 'required_config' that's dynamically generated.""" if isinstance(class_list_str, basestring): class_str_list = list_splitter_fn(class_list_str) else: raise TypeError('must be derivative of a basestring') # ===================================================================== class InnerClassList(RequiredConfig): """This nested class is a proxy list for the classes. It collects all the config requirements for the listed classes and places them each into their own Namespace. """ # we're dynamically creating a class here. The following block of # code is actually adding class level attributes to this new class # 1st requirement for configman required_config = Namespace() # to help the programmer know what Namespaces we added subordinate_namespace_names = [] # save the template for future reference namespace_template = template_for_namespace # for display original_input = class_list_str.replace('\n', '\\n') # for each class in the class list class_list = [] for namespace_index, class_list_element in enumerate( class_str_list ): a_class = class_converter( class_extractor(class_list_element) ) # figure out the Namespace name namespace_name_dict = { 'name': a_class.__name__, 'index': namespace_index } namespace_name = template_for_namespace % namespace_name_dict class_list.append((a_class.__name__, a_class, namespace_name)) subordinate_namespace_names.append(namespace_name) # create the new Namespace required_config.namespace(namespace_name) a_class_namespace = required_config[namespace_name] a_class_namespace.add_option( name_of_class_option, doc='fully qualified classname', default=class_list_element, from_string_converter=class_converter, likely_to_be_changed=True, ) @classmethod def to_str(cls): """this method takes this inner class object and turns it back into the original string of classnames. This is used primarily as for the output of the 'help' option""" return "'%s'" % cls.original_input return InnerClassList # result of class_list_converter return class_list_converter
python
def str_to_classes_in_namespaces_converter( template_for_namespace="%(name)s", list_splitter_fn=_default_list_splitter, class_extractor=_default_class_extractor, name_of_class_option='qualified_class_name', instantiate_classes=False, ): """ parameters: template_for_namespace - a template for the names of the namespaces that will contain the classes and their associated required config options. There are two template variables available: %(name)s - the name of the class to be contained in the namespace; %(index)d - the sequential index number of the namespace. list_converter - a function that will take the string list of classes and break it up into a sequence if individual elements class_extractor - a function that will return the string version of a classname from the result of the list_converter """ # ------------------------------------------------------------------------- def class_list_converter(class_list_str): """This function becomes the actual converter used by configman to take a string and convert it into the nested sequence of Namespaces, one for each class in the list. It does this by creating a proxy class stuffed with its own 'required_config' that's dynamically generated.""" if isinstance(class_list_str, basestring): class_str_list = list_splitter_fn(class_list_str) else: raise TypeError('must be derivative of a basestring') # ===================================================================== class InnerClassList(RequiredConfig): """This nested class is a proxy list for the classes. It collects all the config requirements for the listed classes and places them each into their own Namespace. """ # we're dynamically creating a class here. The following block of # code is actually adding class level attributes to this new class # 1st requirement for configman required_config = Namespace() # to help the programmer know what Namespaces we added subordinate_namespace_names = [] # save the template for future reference namespace_template = template_for_namespace # for display original_input = class_list_str.replace('\n', '\\n') # for each class in the class list class_list = [] for namespace_index, class_list_element in enumerate( class_str_list ): a_class = class_converter( class_extractor(class_list_element) ) # figure out the Namespace name namespace_name_dict = { 'name': a_class.__name__, 'index': namespace_index } namespace_name = template_for_namespace % namespace_name_dict class_list.append((a_class.__name__, a_class, namespace_name)) subordinate_namespace_names.append(namespace_name) # create the new Namespace required_config.namespace(namespace_name) a_class_namespace = required_config[namespace_name] a_class_namespace.add_option( name_of_class_option, doc='fully qualified classname', default=class_list_element, from_string_converter=class_converter, likely_to_be_changed=True, ) @classmethod def to_str(cls): """this method takes this inner class object and turns it back into the original string of classnames. This is used primarily as for the output of the 'help' option""" return "'%s'" % cls.original_input return InnerClassList # result of class_list_converter return class_list_converter
[ "def", "str_to_classes_in_namespaces_converter", "(", "template_for_namespace", "=", "\"%(name)s\"", ",", "list_splitter_fn", "=", "_default_list_splitter", ",", "class_extractor", "=", "_default_class_extractor", ",", "name_of_class_option", "=", "'qualified_class_name'", ",", ...
parameters: template_for_namespace - a template for the names of the namespaces that will contain the classes and their associated required config options. There are two template variables available: %(name)s - the name of the class to be contained in the namespace; %(index)d - the sequential index number of the namespace. list_converter - a function that will take the string list of classes and break it up into a sequence if individual elements class_extractor - a function that will return the string version of a classname from the result of the list_converter
[ "parameters", ":", "template_for_namespace", "-", "a", "template", "for", "the", "names", "of", "the", "namespaces", "that", "will", "contain", "the", "classes", "and", "their", "associated", "required", "config", "options", ".", "There", "are", "two", "template...
train
https://github.com/mozilla/socorrolib/blob/4ec08c6a4ee2c8a69150268afdd324f5f22b90c8/socorrolib/lib/converters.py#L17-L109
mozilla/socorrolib
socorrolib/lib/converters.py
web_services_from_str
def web_services_from_str( list_splitter_fn=ujson.loads, ): """ parameters: list_splitter_fn - a function that will take the json compatible string rerpesenting a list of mappings. """ # ------------------------------------------------------------------------- def class_list_converter(collector_services_str): """This function becomes the actual converter used by configman to take a string and convert it into the nested sequence of Namespaces, one for each class in the list. It does this by creating a proxy class stuffed with its own 'required_config' that's dynamically generated.""" if isinstance(collector_services_str, basestring): all_collector_services = list_splitter_fn(collector_services_str) else: raise TypeError('must be derivative of a basestring') # ===================================================================== class InnerClassList(RequiredConfig): """This nested class is a proxy list for the classes. It collects all the config requirements for the listed classes and places them each into their own Namespace. """ # we're dynamically creating a class here. The following block of # code is actually adding class level attributes to this new class # 1st requirement for configman required_config = Namespace() # to help the programmer know what Namespaces we added subordinate_namespace_names = [] # for display original_input = collector_services_str.replace('\n', '\\n') # for each class in the class list service_list = [] for namespace_index, collector_service_element in enumerate( all_collector_services ): service_name = collector_service_element['name'] service_uri = collector_service_element['uri'] service_implementation_class = class_converter( collector_service_element['service_implementation_class'] ) service_list.append( ( service_name, service_uri, service_implementation_class, ) ) subordinate_namespace_names.append(service_name) # create the new Namespace required_config.namespace(service_name) a_class_namespace = required_config[service_name] a_class_namespace.add_option( "service_implementation_class", doc='fully qualified classname for a class that implements' 'the action associtated with the URI', default=service_implementation_class, from_string_converter=class_converter, likely_to_be_changed=True, ) a_class_namespace.add_option( "uri", doc='uri for this service', default=service_uri, likely_to_be_changed=True, ) @classmethod def to_str(cls): """this method takes this inner class object and turns it back into the original string of classnames. This is used primarily as for the output of the 'help' option""" return "'%s'" % cls.original_input return InnerClassList # result of class_list_converter return class_list_converter
python
def web_services_from_str( list_splitter_fn=ujson.loads, ): """ parameters: list_splitter_fn - a function that will take the json compatible string rerpesenting a list of mappings. """ # ------------------------------------------------------------------------- def class_list_converter(collector_services_str): """This function becomes the actual converter used by configman to take a string and convert it into the nested sequence of Namespaces, one for each class in the list. It does this by creating a proxy class stuffed with its own 'required_config' that's dynamically generated.""" if isinstance(collector_services_str, basestring): all_collector_services = list_splitter_fn(collector_services_str) else: raise TypeError('must be derivative of a basestring') # ===================================================================== class InnerClassList(RequiredConfig): """This nested class is a proxy list for the classes. It collects all the config requirements for the listed classes and places them each into their own Namespace. """ # we're dynamically creating a class here. The following block of # code is actually adding class level attributes to this new class # 1st requirement for configman required_config = Namespace() # to help the programmer know what Namespaces we added subordinate_namespace_names = [] # for display original_input = collector_services_str.replace('\n', '\\n') # for each class in the class list service_list = [] for namespace_index, collector_service_element in enumerate( all_collector_services ): service_name = collector_service_element['name'] service_uri = collector_service_element['uri'] service_implementation_class = class_converter( collector_service_element['service_implementation_class'] ) service_list.append( ( service_name, service_uri, service_implementation_class, ) ) subordinate_namespace_names.append(service_name) # create the new Namespace required_config.namespace(service_name) a_class_namespace = required_config[service_name] a_class_namespace.add_option( "service_implementation_class", doc='fully qualified classname for a class that implements' 'the action associtated with the URI', default=service_implementation_class, from_string_converter=class_converter, likely_to_be_changed=True, ) a_class_namespace.add_option( "uri", doc='uri for this service', default=service_uri, likely_to_be_changed=True, ) @classmethod def to_str(cls): """this method takes this inner class object and turns it back into the original string of classnames. This is used primarily as for the output of the 'help' option""" return "'%s'" % cls.original_input return InnerClassList # result of class_list_converter return class_list_converter
[ "def", "web_services_from_str", "(", "list_splitter_fn", "=", "ujson", ".", "loads", ",", ")", ":", "# -------------------------------------------------------------------------", "def", "class_list_converter", "(", "collector_services_str", ")", ":", "\"\"\"This function becomes ...
parameters: list_splitter_fn - a function that will take the json compatible string rerpesenting a list of mappings.
[ "parameters", ":", "list_splitter_fn", "-", "a", "function", "that", "will", "take", "the", "json", "compatible", "string", "rerpesenting", "a", "list", "of", "mappings", "." ]
train
https://github.com/mozilla/socorrolib/blob/4ec08c6a4ee2c8a69150268afdd324f5f22b90c8/socorrolib/lib/converters.py#L113-L198
mozilla/socorrolib
socorrolib/lib/converters.py
change_default
def change_default( kls, key, new_default, new_converter=None, new_reference_value=None, ): """return a new configman Option object that is a copy of an existing one, giving the new one a different default value""" an_option = kls.get_required_config()[key].copy() an_option.default = new_default if new_converter: an_option.from_string_converter = new_converter if new_reference_value: an_option.reference_value_from = new_reference_value return an_option
python
def change_default( kls, key, new_default, new_converter=None, new_reference_value=None, ): """return a new configman Option object that is a copy of an existing one, giving the new one a different default value""" an_option = kls.get_required_config()[key].copy() an_option.default = new_default if new_converter: an_option.from_string_converter = new_converter if new_reference_value: an_option.reference_value_from = new_reference_value return an_option
[ "def", "change_default", "(", "kls", ",", "key", ",", "new_default", ",", "new_converter", "=", "None", ",", "new_reference_value", "=", "None", ",", ")", ":", "an_option", "=", "kls", ".", "get_required_config", "(", ")", "[", "key", "]", ".", "copy", "...
return a new configman Option object that is a copy of an existing one, giving the new one a different default value
[ "return", "a", "new", "configman", "Option", "object", "that", "is", "a", "copy", "of", "an", "existing", "one", "giving", "the", "new", "one", "a", "different", "default", "value" ]
train
https://github.com/mozilla/socorrolib/blob/4ec08c6a4ee2c8a69150268afdd324f5f22b90c8/socorrolib/lib/converters.py#L202-L217
aerogear/digger-build-cli
digger/builds/ant.py
AntBuild.get_target
def get_target(self): """ Reads the android target based on project.properties file. Returns A string containing the project target (android-23 being the default if none is found) """ with open('%s/project.properties' % self.path) as f: for line in f.readlines(): matches = re.findall(r'^target=(.*)', line) if len(matches) == 0: continue return matches[0].replace('\n', '') return 'android-%s' % (config.sdk_version)
python
def get_target(self): """ Reads the android target based on project.properties file. Returns A string containing the project target (android-23 being the default if none is found) """ with open('%s/project.properties' % self.path) as f: for line in f.readlines(): matches = re.findall(r'^target=(.*)', line) if len(matches) == 0: continue return matches[0].replace('\n', '') return 'android-%s' % (config.sdk_version)
[ "def", "get_target", "(", "self", ")", ":", "with", "open", "(", "'%s/project.properties'", "%", "self", ".", "path", ")", "as", "f", ":", "for", "line", "in", "f", ".", "readlines", "(", ")", ":", "matches", "=", "re", ".", "findall", "(", "r'^targe...
Reads the android target based on project.properties file. Returns A string containing the project target (android-23 being the default if none is found)
[ "Reads", "the", "android", "target", "based", "on", "project", ".", "properties", "file", "." ]
train
https://github.com/aerogear/digger-build-cli/blob/8b88a31063526ec7222dbea6a87309686ad21320/digger/builds/ant.py#L12-L25
aerogear/digger-build-cli
digger/builds/ant.py
AntBuild.sign
def sign(self, storepass=None, keypass=None, keystore=None, apk=None, alias=None, name='app'): """ Signs (jarsign and zipalign) a target apk file based on keystore information, uses default debug keystore file by default. :param storepass(str): keystore file storepass :param keypass(str): keystore file keypass :param keystore(str): keystore file path :param apk(str): apk file path to be signed :param alias(str): keystore file alias :param name(str): signed apk name to be used by zipalign """ target = self.get_target() build_tool = android_helper.get_highest_build_tool(target.split('-')[1]) if keystore is None: (keystore, storepass, keypass, alias) = android_helper.get_default_keystore() dist = '%s/%s.apk' % ('/'.join(apk.split('/')[:-1]), name) android_helper.jarsign(storepass, keypass, keystore, apk, alias, path=self.path) android_helper.zipalign(apk, dist, build_tool=build_tool, path=self.path)
python
def sign(self, storepass=None, keypass=None, keystore=None, apk=None, alias=None, name='app'): """ Signs (jarsign and zipalign) a target apk file based on keystore information, uses default debug keystore file by default. :param storepass(str): keystore file storepass :param keypass(str): keystore file keypass :param keystore(str): keystore file path :param apk(str): apk file path to be signed :param alias(str): keystore file alias :param name(str): signed apk name to be used by zipalign """ target = self.get_target() build_tool = android_helper.get_highest_build_tool(target.split('-')[1]) if keystore is None: (keystore, storepass, keypass, alias) = android_helper.get_default_keystore() dist = '%s/%s.apk' % ('/'.join(apk.split('/')[:-1]), name) android_helper.jarsign(storepass, keypass, keystore, apk, alias, path=self.path) android_helper.zipalign(apk, dist, build_tool=build_tool, path=self.path)
[ "def", "sign", "(", "self", ",", "storepass", "=", "None", ",", "keypass", "=", "None", ",", "keystore", "=", "None", ",", "apk", "=", "None", ",", "alias", "=", "None", ",", "name", "=", "'app'", ")", ":", "target", "=", "self", ".", "get_target",...
Signs (jarsign and zipalign) a target apk file based on keystore information, uses default debug keystore file by default. :param storepass(str): keystore file storepass :param keypass(str): keystore file keypass :param keystore(str): keystore file path :param apk(str): apk file path to be signed :param alias(str): keystore file alias :param name(str): signed apk name to be used by zipalign
[ "Signs", "(", "jarsign", "and", "zipalign", ")", "a", "target", "apk", "file", "based", "on", "keystore", "information", "uses", "default", "debug", "keystore", "file", "by", "default", "." ]
train
https://github.com/aerogear/digger-build-cli/blob/8b88a31063526ec7222dbea6a87309686ad21320/digger/builds/ant.py#L27-L44
aerogear/digger-build-cli
digger/builds/ant.py
AntBuild.prepare
def prepare(self): """ Prepares the android project to the build process. Prepare the ant project to be built """ cmd = [ 'android', 'update', 'project', '-p', self.path, '-t', self.get_target() ] self.run_cmd(cmd, 'prepare')
python
def prepare(self): """ Prepares the android project to the build process. Prepare the ant project to be built """ cmd = [ 'android', 'update', 'project', '-p', self.path, '-t', self.get_target() ] self.run_cmd(cmd, 'prepare')
[ "def", "prepare", "(", "self", ")", ":", "cmd", "=", "[", "'android'", ",", "'update'", ",", "'project'", ",", "'-p'", ",", "self", ".", "path", ",", "'-t'", ",", "self", ".", "get_target", "(", ")", "]", "self", ".", "run_cmd", "(", "cmd", ",", ...
Prepares the android project to the build process. Prepare the ant project to be built
[ "Prepares", "the", "android", "project", "to", "the", "build", "process", "." ]
train
https://github.com/aerogear/digger-build-cli/blob/8b88a31063526ec7222dbea6a87309686ad21320/digger/builds/ant.py#L46-L57
okTurtles/pydnschain
dnschain/server.py
Server.lookup
def lookup(self, name, host_override=None): """ Looks up a name from the DNSChain server. Throws exception if the data is not valid JSON or if the namecoin entry does not exist in the blockchain. @param name: The name to lookup, e.g. 'id/dionyziz', note this $NAMESPACE/$NAME format is not guaranteed. Additionally the caller must perform appropriate url encoding _before_ the name is passed to urllib2.urlopen """ if host_override is not None: self.headers['Host'] = host_override full_url = "http://%s/%s" % (self.addr, name) request = urllib2.Request(full_url, None, self.headers) try: response = urllib2.urlopen(request) except urllib2.HTTPError, e: if e.code == 404: e = DataNotFound(e, name, self.headers['Host']) if e.code < 200 or e.code > 299: self._log.debug("%s" % (e.msg,), exc_info=True) raise e namecoin_string = response.read() try: data = json.loads(namecoin_string) except ValueError: raise MalformedJSON("%s\n%s" % (ValueError, namecoin_string)) return data
python
def lookup(self, name, host_override=None): """ Looks up a name from the DNSChain server. Throws exception if the data is not valid JSON or if the namecoin entry does not exist in the blockchain. @param name: The name to lookup, e.g. 'id/dionyziz', note this $NAMESPACE/$NAME format is not guaranteed. Additionally the caller must perform appropriate url encoding _before_ the name is passed to urllib2.urlopen """ if host_override is not None: self.headers['Host'] = host_override full_url = "http://%s/%s" % (self.addr, name) request = urllib2.Request(full_url, None, self.headers) try: response = urllib2.urlopen(request) except urllib2.HTTPError, e: if e.code == 404: e = DataNotFound(e, name, self.headers['Host']) if e.code < 200 or e.code > 299: self._log.debug("%s" % (e.msg,), exc_info=True) raise e namecoin_string = response.read() try: data = json.loads(namecoin_string) except ValueError: raise MalformedJSON("%s\n%s" % (ValueError, namecoin_string)) return data
[ "def", "lookup", "(", "self", ",", "name", ",", "host_override", "=", "None", ")", ":", "if", "host_override", "is", "not", "None", ":", "self", ".", "headers", "[", "'Host'", "]", "=", "host_override", "full_url", "=", "\"http://%s/%s\"", "%", "(", "sel...
Looks up a name from the DNSChain server. Throws exception if the data is not valid JSON or if the namecoin entry does not exist in the blockchain. @param name: The name to lookup, e.g. 'id/dionyziz', note this $NAMESPACE/$NAME format is not guaranteed. Additionally the caller must perform appropriate url encoding _before_ the name is passed to urllib2.urlopen
[ "Looks", "up", "a", "name", "from", "the", "DNSChain", "server", ".", "Throws", "exception", "if", "the", "data", "is", "not", "valid", "JSON", "or", "if", "the", "namecoin", "entry", "does", "not", "exist", "in", "the", "blockchain", "." ]
train
https://github.com/okTurtles/pydnschain/blob/9032e4ef7e2dfc42712e322e36f3194decaf6d6f/dnschain/server.py#L40-L68
hangyan/shaw
shaw/django/decorator.py
cache_function
def cache_function(length): """ Caches a function, using the function itself as the key, and the return value as the value saved. It passes all arguments on to the function, as it should. The decorator itself takes a length argument, which is the number of seconds the cache will keep the result around. It will put in a MethodNotFinishedError in the cache while the function is processing. This should not matter in most cases, but if the app is using threads, you won't be able to get the previous value, and will need to wait until the function finishes. If this is not desired behavior, you can remove the first two lines after the ``else``. """ def decorator(func): def inner_func(*args, **kwargs): from django.core.cache import cache value = cache.get(func) if func in cache: return value else: # This will set a temporary value while ``func`` is being # processed. When using threads, this is vital, as otherwise # the function can be called several times before it finishes # and is put into the cache. class MethodNotFinishedError(Exception): pass cache.set(func, MethodNotFinishedError( 'The function %s has not finished processing yet. This \ value will be replaced when it finishes.' % (func.__name__) ), length) result = func(*args, **kwargs) cache.set(func, result, length) return result return inner_func return decorator
python
def cache_function(length): """ Caches a function, using the function itself as the key, and the return value as the value saved. It passes all arguments on to the function, as it should. The decorator itself takes a length argument, which is the number of seconds the cache will keep the result around. It will put in a MethodNotFinishedError in the cache while the function is processing. This should not matter in most cases, but if the app is using threads, you won't be able to get the previous value, and will need to wait until the function finishes. If this is not desired behavior, you can remove the first two lines after the ``else``. """ def decorator(func): def inner_func(*args, **kwargs): from django.core.cache import cache value = cache.get(func) if func in cache: return value else: # This will set a temporary value while ``func`` is being # processed. When using threads, this is vital, as otherwise # the function can be called several times before it finishes # and is put into the cache. class MethodNotFinishedError(Exception): pass cache.set(func, MethodNotFinishedError( 'The function %s has not finished processing yet. This \ value will be replaced when it finishes.' % (func.__name__) ), length) result = func(*args, **kwargs) cache.set(func, result, length) return result return inner_func return decorator
[ "def", "cache_function", "(", "length", ")", ":", "def", "decorator", "(", "func", ")", ":", "def", "inner_func", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "from", "django", ".", "core", ".", "cache", "import", "cache", "value", "=", "cach...
Caches a function, using the function itself as the key, and the return value as the value saved. It passes all arguments on to the function, as it should. The decorator itself takes a length argument, which is the number of seconds the cache will keep the result around. It will put in a MethodNotFinishedError in the cache while the function is processing. This should not matter in most cases, but if the app is using threads, you won't be able to get the previous value, and will need to wait until the function finishes. If this is not desired behavior, you can remove the first two lines after the ``else``.
[ "Caches", "a", "function", "using", "the", "function", "itself", "as", "the", "key", "and", "the", "return", "value", "as", "the", "value", "saved", ".", "It", "passes", "all", "arguments", "on", "to", "the", "function", "as", "it", "should", "." ]
train
https://github.com/hangyan/shaw/blob/63d01d35e225ba4edb9c61edaf351e1bc0e8fd15/shaw/django/decorator.py#L8-L45
henzk/ape
ape/feaquencer/check_order.py
_get_formatted_feature_dependencies
def _get_formatted_feature_dependencies(data): """ Takes the format of the feature_order.json in featuremodel pool. Creates a list of conditions in the following format: ] dict( name='django_productline.features.admin', subject='django_productline', ctype='after' ) ] :param data: :return: list """ conditions = list() for k, v in data.items(): for feature in v.get('after', list()): conditions.append(dict( name=k, subject=feature, ctype='after' )) if v.get('first', False): conditions.append(dict( name=k, subject=None, ctype='first' )) if v.get('last', False): conditions.append(dict( name=k, subject=None, ctype='last' )) return conditions
python
def _get_formatted_feature_dependencies(data): """ Takes the format of the feature_order.json in featuremodel pool. Creates a list of conditions in the following format: ] dict( name='django_productline.features.admin', subject='django_productline', ctype='after' ) ] :param data: :return: list """ conditions = list() for k, v in data.items(): for feature in v.get('after', list()): conditions.append(dict( name=k, subject=feature, ctype='after' )) if v.get('first', False): conditions.append(dict( name=k, subject=None, ctype='first' )) if v.get('last', False): conditions.append(dict( name=k, subject=None, ctype='last' )) return conditions
[ "def", "_get_formatted_feature_dependencies", "(", "data", ")", ":", "conditions", "=", "list", "(", ")", "for", "k", ",", "v", "in", "data", ".", "items", "(", ")", ":", "for", "feature", "in", "v", ".", "get", "(", "'after'", ",", "list", "(", ")",...
Takes the format of the feature_order.json in featuremodel pool. Creates a list of conditions in the following format: ] dict( name='django_productline.features.admin', subject='django_productline', ctype='after' ) ] :param data: :return: list
[ "Takes", "the", "format", "of", "the", "feature_order", ".", "json", "in", "featuremodel", "pool", ".", "Creates", "a", "list", "of", "conditions", "in", "the", "following", "format", ":", "]", "dict", "(", "name", "=", "django_productline", ".", "features",...
train
https://github.com/henzk/ape/blob/a1b7ea5e5b25c42beffeaaa5c32d94ad82634819/ape/feaquencer/check_order.py#L89-L123
henzk/ape
ape/feaquencer/check_order.py
_get_condition_instances
def _get_condition_instances(data): """ Returns a list of OrderingCondition instances created from the passed data structure. The structure should be a list of dicts containing the necessary information: [ dict( name='featureA', subject='featureB', ctype='after' ), ] Example says: featureA needs to be after featureB. :param data: :return: """ conditions = list() for cond in data: conditions.append(OrderingCondition( name=cond.get('name'), subject=cond.get('subject'), ctype=cond.get('ctype') )) return conditions
python
def _get_condition_instances(data): """ Returns a list of OrderingCondition instances created from the passed data structure. The structure should be a list of dicts containing the necessary information: [ dict( name='featureA', subject='featureB', ctype='after' ), ] Example says: featureA needs to be after featureB. :param data: :return: """ conditions = list() for cond in data: conditions.append(OrderingCondition( name=cond.get('name'), subject=cond.get('subject'), ctype=cond.get('ctype') )) return conditions
[ "def", "_get_condition_instances", "(", "data", ")", ":", "conditions", "=", "list", "(", ")", "for", "cond", "in", "data", ":", "conditions", ".", "append", "(", "OrderingCondition", "(", "name", "=", "cond", ".", "get", "(", "'name'", ")", ",", "subjec...
Returns a list of OrderingCondition instances created from the passed data structure. The structure should be a list of dicts containing the necessary information: [ dict( name='featureA', subject='featureB', ctype='after' ), ] Example says: featureA needs to be after featureB. :param data: :return:
[ "Returns", "a", "list", "of", "OrderingCondition", "instances", "created", "from", "the", "passed", "data", "structure", ".", "The", "structure", "should", "be", "a", "list", "of", "dicts", "containing", "the", "necessary", "information", ":", "[", "dict", "("...
train
https://github.com/henzk/ape/blob/a1b7ea5e5b25c42beffeaaa5c32d94ad82634819/ape/feaquencer/check_order.py#L126-L148
Synerty/peek-plugin-base
peek_plugin_base/client/PluginClientEntryHookABC.py
PluginClientEntryHookABC.angularFrontendAppDir
def angularFrontendAppDir(self) -> str: """ Angular Frontend Dir This directory will be linked into the angular app when it is compiled. :return: The absolute path of the Angular2 app directory. """ relDir = self._packageCfg.config.plugin.title(require_string) dir = os.path.join(self._pluginRoot, relDir) if not os.path.isdir(dir): raise NotADirectoryError(dir) return dir
python
def angularFrontendAppDir(self) -> str: """ Angular Frontend Dir This directory will be linked into the angular app when it is compiled. :return: The absolute path of the Angular2 app directory. """ relDir = self._packageCfg.config.plugin.title(require_string) dir = os.path.join(self._pluginRoot, relDir) if not os.path.isdir(dir): raise NotADirectoryError(dir) return dir
[ "def", "angularFrontendAppDir", "(", "self", ")", "->", "str", ":", "relDir", "=", "self", ".", "_packageCfg", ".", "config", ".", "plugin", ".", "title", "(", "require_string", ")", "dir", "=", "os", ".", "path", ".", "join", "(", "self", ".", "_plugi...
Angular Frontend Dir This directory will be linked into the angular app when it is compiled. :return: The absolute path of the Angular2 app directory.
[ "Angular", "Frontend", "Dir" ]
train
https://github.com/Synerty/peek-plugin-base/blob/276101d028e1ee0678af514c761b74cce5a5cda9/peek_plugin_base/client/PluginClientEntryHookABC.py#L31-L41
skylander86/uriutils
uriutils/storages.py
BaseURI.join
def join(self, path): """ Similar to :func:`os.path.join` but returns a storage object instead. :param str path: path to join on to this object's URI :returns: a storage object :rtype: BaseURI """ return self.parse_uri(urlparse(os.path.join(str(self), path)), storage_args=self.storage_args)
python
def join(self, path): """ Similar to :func:`os.path.join` but returns a storage object instead. :param str path: path to join on to this object's URI :returns: a storage object :rtype: BaseURI """ return self.parse_uri(urlparse(os.path.join(str(self), path)), storage_args=self.storage_args)
[ "def", "join", "(", "self", ",", "path", ")", ":", "return", "self", ".", "parse_uri", "(", "urlparse", "(", "os", ".", "path", ".", "join", "(", "str", "(", "self", ")", ",", "path", ")", ")", ",", "storage_args", "=", "self", ".", "storage_args",...
Similar to :func:`os.path.join` but returns a storage object instead. :param str path: path to join on to this object's URI :returns: a storage object :rtype: BaseURI
[ "Similar", "to", ":", "func", ":", "os", ".", "path", ".", "join", "but", "returns", "a", "storage", "object", "instead", "." ]
train
https://github.com/skylander86/uriutils/blob/e756d9483ee884973bf3a0c9ad27ae362fbe7fc6/uriutils/storages.py#L165-L174
skylander86/uriutils
uriutils/storages.py
S3URI.exists
def exists(self): """Uses ``HEAD`` requests for efficiency.""" try: self.s3_object.load() return True except botocore.exceptions.ClientError: return False
python
def exists(self): """Uses ``HEAD`` requests for efficiency.""" try: self.s3_object.load() return True except botocore.exceptions.ClientError: return False
[ "def", "exists", "(", "self", ")", ":", "try", ":", "self", ".", "s3_object", ".", "load", "(", ")", "return", "True", "except", "botocore", ".", "exceptions", ".", "ClientError", ":", "return", "False" ]
Uses ``HEAD`` requests for efficiency.
[ "Uses", "HEAD", "requests", "for", "efficiency", "." ]
train
https://github.com/skylander86/uriutils/blob/e756d9483ee884973bf3a0c9ad27ae362fbe7fc6/uriutils/storages.py#L307-L313
skylander86/uriutils
uriutils/storages.py
S3URI.list_dir
def list_dir(self): """ Non-recursive file listing. :returns: A generator over files in this "directory" for efficiency. """ bucket = self.s3_object.Bucket() prefix = self.s3_object.key if not prefix.endswith('/'): prefix += '/' for obj in bucket.objects.filter(Delimiter='/', Prefix=prefix): yield 's3://{}/{}'.format(obj.bucket_name, obj.key)
python
def list_dir(self): """ Non-recursive file listing. :returns: A generator over files in this "directory" for efficiency. """ bucket = self.s3_object.Bucket() prefix = self.s3_object.key if not prefix.endswith('/'): prefix += '/' for obj in bucket.objects.filter(Delimiter='/', Prefix=prefix): yield 's3://{}/{}'.format(obj.bucket_name, obj.key)
[ "def", "list_dir", "(", "self", ")", ":", "bucket", "=", "self", ".", "s3_object", ".", "Bucket", "(", ")", "prefix", "=", "self", ".", "s3_object", ".", "key", "if", "not", "prefix", ".", "endswith", "(", "'/'", ")", ":", "prefix", "+=", "'/'", "f...
Non-recursive file listing. :returns: A generator over files in this "directory" for efficiency.
[ "Non", "-", "recursive", "file", "listing", "." ]
train
https://github.com/skylander86/uriutils/blob/e756d9483ee884973bf3a0c9ad27ae362fbe7fc6/uriutils/storages.py#L322-L334
skylander86/uriutils
uriutils/storages.py
GoogleCloudStorageURI.put_content
def put_content(self, content): """ The default content type is set to ``application/octet-stream`` and content encoding set to ``None``. """ self.blob.content_encoding = self.content_encoding self.blob.metadata = self.metadata return self.blob.upload_from_string(content, content_type=self.content_type)
python
def put_content(self, content): """ The default content type is set to ``application/octet-stream`` and content encoding set to ``None``. """ self.blob.content_encoding = self.content_encoding self.blob.metadata = self.metadata return self.blob.upload_from_string(content, content_type=self.content_type)
[ "def", "put_content", "(", "self", ",", "content", ")", ":", "self", ".", "blob", ".", "content_encoding", "=", "self", ".", "content_encoding", "self", ".", "blob", ".", "metadata", "=", "self", ".", "metadata", "return", "self", ".", "blob", ".", "uplo...
The default content type is set to ``application/octet-stream`` and content encoding set to ``None``.
[ "The", "default", "content", "type", "is", "set", "to", "application", "/", "octet", "-", "stream", "and", "content", "encoding", "set", "to", "None", "." ]
train
https://github.com/skylander86/uriutils/blob/e756d9483ee884973bf3a0c9ad27ae362fbe7fc6/uriutils/storages.py#L385-L392
skylander86/uriutils
uriutils/storages.py
GoogleCloudStorageURI.exists
def exists(self): """Uses ``HEAD`` requests for efficiency.""" try: self.blob.reload() return True except google.cloud.exceptions.NotFound: return False
python
def exists(self): """Uses ``HEAD`` requests for efficiency.""" try: self.blob.reload() return True except google.cloud.exceptions.NotFound: return False
[ "def", "exists", "(", "self", ")", ":", "try", ":", "self", ".", "blob", ".", "reload", "(", ")", "return", "True", "except", "google", ".", "cloud", ".", "exceptions", ".", "NotFound", ":", "return", "False" ]
Uses ``HEAD`` requests for efficiency.
[ "Uses", "HEAD", "requests", "for", "efficiency", "." ]
train
https://github.com/skylander86/uriutils/blob/e756d9483ee884973bf3a0c9ad27ae362fbe7fc6/uriutils/storages.py#L408-L414
skylander86/uriutils
uriutils/storages.py
GoogleCloudStorageURI.list_dir
def list_dir(self): """ Non-recursive file listing. :returns: A generator over files in this "directory" for efficiency. """ bucket = self.blob.bucket prefix = self.blob.name if not prefix.endswith('/'): prefix += '/' for blob in bucket.list_blobs(prefix=prefix, delimiter='/'): yield 'gs://{}/{}'.format(blob.bucket.name, blob.name)
python
def list_dir(self): """ Non-recursive file listing. :returns: A generator over files in this "directory" for efficiency. """ bucket = self.blob.bucket prefix = self.blob.name if not prefix.endswith('/'): prefix += '/' for blob in bucket.list_blobs(prefix=prefix, delimiter='/'): yield 'gs://{}/{}'.format(blob.bucket.name, blob.name)
[ "def", "list_dir", "(", "self", ")", ":", "bucket", "=", "self", ".", "blob", ".", "bucket", "prefix", "=", "self", ".", "blob", ".", "name", "if", "not", "prefix", ".", "endswith", "(", "'/'", ")", ":", "prefix", "+=", "'/'", "for", "blob", "in", ...
Non-recursive file listing. :returns: A generator over files in this "directory" for efficiency.
[ "Non", "-", "recursive", "file", "listing", "." ]
train
https://github.com/skylander86/uriutils/blob/e756d9483ee884973bf3a0c9ad27ae362fbe7fc6/uriutils/storages.py#L421-L433
skylander86/uriutils
uriutils/storages.py
HTTPURI.put_content
def put_content(self, content): """ Makes a ``PUT`` request with the content in the body. :raise: An :exc:`requests.RequestException` if it is not 2xx. """ r = requests.request(self.method if self.method else 'PUT', self.url, data=content, **self.storage_args) if self.raise_for_status: r.raise_for_status()
python
def put_content(self, content): """ Makes a ``PUT`` request with the content in the body. :raise: An :exc:`requests.RequestException` if it is not 2xx. """ r = requests.request(self.method if self.method else 'PUT', self.url, data=content, **self.storage_args) if self.raise_for_status: r.raise_for_status()
[ "def", "put_content", "(", "self", ",", "content", ")", ":", "r", "=", "requests", ".", "request", "(", "self", ".", "method", "if", "self", ".", "method", "else", "'PUT'", ",", "self", ".", "url", ",", "data", "=", "content", ",", "*", "*", "self"...
Makes a ``PUT`` request with the content in the body. :raise: An :exc:`requests.RequestException` if it is not 2xx.
[ "Makes", "a", "PUT", "request", "with", "the", "content", "in", "the", "body", "." ]
train
https://github.com/skylander86/uriutils/blob/e756d9483ee884973bf3a0c9ad27ae362fbe7fc6/uriutils/storages.py#L482-L490
skylander86/uriutils
uriutils/storages.py
HTTPURI.dir_exists
def dir_exists(self): """ Makes a ``HEAD`` requests to the URI. :returns: ``True`` if status code is 2xx. """ r = requests.request(self.method if self.method else 'HEAD', self.url, **self.storage_args) try: r.raise_for_status() except Exception: return False return True
python
def dir_exists(self): """ Makes a ``HEAD`` requests to the URI. :returns: ``True`` if status code is 2xx. """ r = requests.request(self.method if self.method else 'HEAD', self.url, **self.storage_args) try: r.raise_for_status() except Exception: return False return True
[ "def", "dir_exists", "(", "self", ")", ":", "r", "=", "requests", ".", "request", "(", "self", ".", "method", "if", "self", ".", "method", "else", "'HEAD'", ",", "self", ".", "url", ",", "*", "*", "self", ".", "storage_args", ")", "try", ":", "r", ...
Makes a ``HEAD`` requests to the URI. :returns: ``True`` if status code is 2xx.
[ "Makes", "a", "HEAD", "requests", "to", "the", "URI", "." ]
train
https://github.com/skylander86/uriutils/blob/e756d9483ee884973bf3a0c9ad27ae362fbe7fc6/uriutils/storages.py#L516-L527
skylander86/uriutils
uriutils/storages.py
SNSURI.put_content
def put_content(self, content): """ Publishes a message straight to SNS. :param bytes content: raw bytes content to publish, will decode to ``UTF-8`` if string is detected """ if not isinstance(content, str): content = content.decode('utf-8') self.topic.publish(Message=content, **self.storage_args)
python
def put_content(self, content): """ Publishes a message straight to SNS. :param bytes content: raw bytes content to publish, will decode to ``UTF-8`` if string is detected """ if not isinstance(content, str): content = content.decode('utf-8') self.topic.publish(Message=content, **self.storage_args)
[ "def", "put_content", "(", "self", ",", "content", ")", ":", "if", "not", "isinstance", "(", "content", ",", "str", ")", ":", "content", "=", "content", ".", "decode", "(", "'utf-8'", ")", "self", ".", "topic", ".", "publish", "(", "Message", "=", "c...
Publishes a message straight to SNS. :param bytes content: raw bytes content to publish, will decode to ``UTF-8`` if string is detected
[ "Publishes", "a", "message", "straight", "to", "SNS", "." ]
train
https://github.com/skylander86/uriutils/blob/e756d9483ee884973bf3a0c9ad27ae362fbe7fc6/uriutils/storages.py#L592-L601
klahnakoski/mo-times
mo_times/durations.py
_string2Duration
def _string2Duration(text): """ CONVERT SIMPLE <float><type> TO A DURATION OBJECT """ if text == "" or text == "zero": return ZERO amount, interval = re.match(r"([\d\.]*)(.*)", text).groups() amount = int(amount) if amount else 1 if MILLI_VALUES[interval] == None: from mo_logs import Log Log.error( "{{interval|quote}} in {{text|quote}} is not a recognized duration type (did you use the pural form by mistake?", interval=interval, text=text ) output = Duration(0) if MONTH_VALUES[interval] == 0: output.milli = amount * MILLI_VALUES[interval] else: output.milli = amount * MONTH_VALUES[interval] * MILLI_VALUES.month output.month = amount * MONTH_VALUES[interval] return output
python
def _string2Duration(text): """ CONVERT SIMPLE <float><type> TO A DURATION OBJECT """ if text == "" or text == "zero": return ZERO amount, interval = re.match(r"([\d\.]*)(.*)", text).groups() amount = int(amount) if amount else 1 if MILLI_VALUES[interval] == None: from mo_logs import Log Log.error( "{{interval|quote}} in {{text|quote}} is not a recognized duration type (did you use the pural form by mistake?", interval=interval, text=text ) output = Duration(0) if MONTH_VALUES[interval] == 0: output.milli = amount * MILLI_VALUES[interval] else: output.milli = amount * MONTH_VALUES[interval] * MILLI_VALUES.month output.month = amount * MONTH_VALUES[interval] return output
[ "def", "_string2Duration", "(", "text", ")", ":", "if", "text", "==", "\"\"", "or", "text", "==", "\"zero\"", ":", "return", "ZERO", "amount", ",", "interval", "=", "re", ".", "match", "(", "r\"([\\d\\.]*)(.*)\"", ",", "text", ")", ".", "groups", "(", ...
CONVERT SIMPLE <float><type> TO A DURATION OBJECT
[ "CONVERT", "SIMPLE", "<float", ">", "<type", ">", "TO", "A", "DURATION", "OBJECT" ]
train
https://github.com/klahnakoski/mo-times/blob/e64a720b9796e076adeb0d5773ec6915ca045b9d/mo_times/durations.py#L313-L338
Laufire/ec
ec/modules/hooks.py
registerExitCall
def registerExitCall(): r"""Registers an exit call to start the core. The core would be started after the main module is loaded. Ec would be exited from the core. """ if state.isExitHooked: return state.isExitHooked = True from atexit import register register(core.start)
python
def registerExitCall(): r"""Registers an exit call to start the core. The core would be started after the main module is loaded. Ec would be exited from the core. """ if state.isExitHooked: return state.isExitHooked = True from atexit import register register(core.start)
[ "def", "registerExitCall", "(", ")", ":", "if", "state", ".", "isExitHooked", ":", "return", "state", ".", "isExitHooked", "=", "True", "from", "atexit", "import", "register", "register", "(", "core", ".", "start", ")" ]
r"""Registers an exit call to start the core. The core would be started after the main module is loaded. Ec would be exited from the core.
[ "r", "Registers", "an", "exit", "call", "to", "start", "the", "core", "." ]
train
https://github.com/Laufire/ec/blob/63e84a1daef9234487d7de538e5da233a7d13071/ec/modules/hooks.py#L74-L86
timothydmorton/obliquity
obliquity/kappa_inference.py
fisher
def fisher(x,k): """Fisher distribution """ return k/(2*np.sinh(k)) * np.exp(k*np.cos(x))*np.sin(x)
python
def fisher(x,k): """Fisher distribution """ return k/(2*np.sinh(k)) * np.exp(k*np.cos(x))*np.sin(x)
[ "def", "fisher", "(", "x", ",", "k", ")", ":", "return", "k", "/", "(", "2", "*", "np", ".", "sinh", "(", "k", ")", ")", "*", "np", ".", "exp", "(", "k", "*", "np", ".", "cos", "(", "x", ")", ")", "*", "np", ".", "sin", "(", "x", ")" ...
Fisher distribution
[ "Fisher", "distribution" ]
train
https://github.com/timothydmorton/obliquity/blob/ae0a237ae2ca7ba0f7c71f0ee391f52e809da235/obliquity/kappa_inference.py#L20-L23
timothydmorton/obliquity
obliquity/kappa_inference.py
sin_fisher
def sin_fisher(y,k): """pdf for y=sin(x) if x is fisher-distributed with parameter k. Support is [0,1). """ return 1/np.sqrt(1-y**2) * (k/(np.sinh(k)) * y * (np.cosh(k*np.sqrt(1-y**2))))
python
def sin_fisher(y,k): """pdf for y=sin(x) if x is fisher-distributed with parameter k. Support is [0,1). """ return 1/np.sqrt(1-y**2) * (k/(np.sinh(k)) * y * (np.cosh(k*np.sqrt(1-y**2))))
[ "def", "sin_fisher", "(", "y", ",", "k", ")", ":", "return", "1", "/", "np", ".", "sqrt", "(", "1", "-", "y", "**", "2", ")", "*", "(", "k", "/", "(", "np", ".", "sinh", "(", "k", ")", ")", "*", "y", "*", "(", "np", ".", "cosh", "(", ...
pdf for y=sin(x) if x is fisher-distributed with parameter k. Support is [0,1).
[ "pdf", "for", "y", "=", "sin", "(", "x", ")", "if", "x", "is", "fisher", "-", "distributed", "with", "parameter", "k", ".", "Support", "is", "[", "0", "1", ")", "." ]
train
https://github.com/timothydmorton/obliquity/blob/ae0a237ae2ca7ba0f7c71f0ee391f52e809da235/obliquity/kappa_inference.py#L35-L38
timothydmorton/obliquity
obliquity/kappa_inference.py
cosi_pdf
def cosi_pdf(z,k=1): """Equation (11) of Morton & Winn (2014) """ return 2*k/(np.pi*np.sinh(k)) * quad(cosi_integrand,z,1,args=(k,z))[0]
python
def cosi_pdf(z,k=1): """Equation (11) of Morton & Winn (2014) """ return 2*k/(np.pi*np.sinh(k)) * quad(cosi_integrand,z,1,args=(k,z))[0]
[ "def", "cosi_pdf", "(", "z", ",", "k", "=", "1", ")", ":", "return", "2", "*", "k", "/", "(", "np", ".", "pi", "*", "np", ".", "sinh", "(", "k", ")", ")", "*", "quad", "(", "cosi_integrand", ",", "z", ",", "1", ",", "args", "=", "(", "k",...
Equation (11) of Morton & Winn (2014)
[ "Equation", "(", "11", ")", "of", "Morton", "&", "Winn", "(", "2014", ")" ]
train
https://github.com/timothydmorton/obliquity/blob/ae0a237ae2ca7ba0f7c71f0ee391f52e809da235/obliquity/kappa_inference.py#L46-L49
timothydmorton/obliquity
obliquity/kappa_inference.py
generate_veq
def generate_veq(R=1.3, dR=0.1, Prot=6, dProt=0.1,nsamples=1e4,plot=False, R_samples=None,Prot_samples=None): """ Returns the mean and std equatorial velocity given R,dR,Prot,dProt Assumes all distributions are normal. This will be used mainly for testing purposes; I can use MC-generated v_eq distributions when we go for real. """ if R_samples is None: R_samples = R*(1 + rand.normal(size=nsamples)*dR) else: inds = rand.randint(len(R_samples),size=nsamples) R_samples = R_samples[inds] if Prot_samples is None: Prot_samples = Prot*(1 + rand.normal(size=nsamples)*dProt) else: inds = rand.randint(len(Prot_samples),size=nsamples) Prot_samples = Prot_samples[inds] veq_samples = 2*np.pi*R_samples*RSUN/(Prot_samples*DAY)/1e5 if plot: plt.hist(veq_samples,histtype='step',color='k',bins=50,normed=True) d = stats.norm(scale=veq_samples.std(),loc=veq_samples.mean()) vs = np.linspace(veq_samples.min(),veq_samples.max(),1e4) plt.plot(vs,d.pdf(vs),'r') return veq_samples.mean(),veq_samples.std()
python
def generate_veq(R=1.3, dR=0.1, Prot=6, dProt=0.1,nsamples=1e4,plot=False, R_samples=None,Prot_samples=None): """ Returns the mean and std equatorial velocity given R,dR,Prot,dProt Assumes all distributions are normal. This will be used mainly for testing purposes; I can use MC-generated v_eq distributions when we go for real. """ if R_samples is None: R_samples = R*(1 + rand.normal(size=nsamples)*dR) else: inds = rand.randint(len(R_samples),size=nsamples) R_samples = R_samples[inds] if Prot_samples is None: Prot_samples = Prot*(1 + rand.normal(size=nsamples)*dProt) else: inds = rand.randint(len(Prot_samples),size=nsamples) Prot_samples = Prot_samples[inds] veq_samples = 2*np.pi*R_samples*RSUN/(Prot_samples*DAY)/1e5 if plot: plt.hist(veq_samples,histtype='step',color='k',bins=50,normed=True) d = stats.norm(scale=veq_samples.std(),loc=veq_samples.mean()) vs = np.linspace(veq_samples.min(),veq_samples.max(),1e4) plt.plot(vs,d.pdf(vs),'r') return veq_samples.mean(),veq_samples.std()
[ "def", "generate_veq", "(", "R", "=", "1.3", ",", "dR", "=", "0.1", ",", "Prot", "=", "6", ",", "dProt", "=", "0.1", ",", "nsamples", "=", "1e4", ",", "plot", "=", "False", ",", "R_samples", "=", "None", ",", "Prot_samples", "=", "None", ")", ":"...
Returns the mean and std equatorial velocity given R,dR,Prot,dProt Assumes all distributions are normal. This will be used mainly for testing purposes; I can use MC-generated v_eq distributions when we go for real.
[ "Returns", "the", "mean", "and", "std", "equatorial", "velocity", "given", "R", "dR", "Prot", "dProt" ]
train
https://github.com/timothydmorton/obliquity/blob/ae0a237ae2ca7ba0f7c71f0ee391f52e809da235/obliquity/kappa_inference.py#L66-L93
timothydmorton/obliquity
obliquity/kappa_inference.py
like_cosi
def like_cosi(cosi,vsini_dist,veq_dist,vgrid=None): """likelihood of Data (vsini_dist, veq_dist) given cosi """ sini = np.sqrt(1-cosi**2) def integrand(v): #return vsini_dist(v)*veq_dist(v/sini) return vsini_dist(v*sini)*veq_dist(v) if vgrid is None: return quad(integrand,0,np.inf)[0] else: return np.trapz(integrand(vgrid),vgrid)
python
def like_cosi(cosi,vsini_dist,veq_dist,vgrid=None): """likelihood of Data (vsini_dist, veq_dist) given cosi """ sini = np.sqrt(1-cosi**2) def integrand(v): #return vsini_dist(v)*veq_dist(v/sini) return vsini_dist(v*sini)*veq_dist(v) if vgrid is None: return quad(integrand,0,np.inf)[0] else: return np.trapz(integrand(vgrid),vgrid)
[ "def", "like_cosi", "(", "cosi", ",", "vsini_dist", ",", "veq_dist", ",", "vgrid", "=", "None", ")", ":", "sini", "=", "np", ".", "sqrt", "(", "1", "-", "cosi", "**", "2", ")", "def", "integrand", "(", "v", ")", ":", "#return vsini_dist(v)*veq_dist(v/s...
likelihood of Data (vsini_dist, veq_dist) given cosi
[ "likelihood", "of", "Data", "(", "vsini_dist", "veq_dist", ")", "given", "cosi" ]
train
https://github.com/timothydmorton/obliquity/blob/ae0a237ae2ca7ba0f7c71f0ee391f52e809da235/obliquity/kappa_inference.py#L95-L105
timothydmorton/obliquity
obliquity/kappa_inference.py
cosi_posterior
def cosi_posterior(vsini_dist,veq_dist,vgrid=None,npts=100,vgrid_pts=1000): """returns posterior of cosI given dists for vsini and veq (incorporates unc. in vsini) """ if vgrid is None: vgrid = np.linspace(min(veq_dist.ppf(0.001),vsini_dist.ppf(0.001)), max(veq_dist.ppf(0.999),vsini_dist.ppf(0.999)), vgrid_pts) logging.debug('vgrid: {} pts, {} to {}'.format(vgrid_pts, vgrid[0], vgrid[-1])) #vgrid = np.linspace(vsini_dist.ppf(0.005),vsini_dist.ppf(0.995),vgrid_pts) cs = np.linspace(0,1,npts) Ls = cs*0 for i,c in enumerate(cs): Ls[i] = like_cosi(c,vsini_dist,veq_dist,vgrid=vgrid) if np.isnan(Ls[-1]): #hack to prevent nan when cos=1 Ls[-1] = Ls[-2] Ls /= np.trapz(Ls,cs) return cs,Ls
python
def cosi_posterior(vsini_dist,veq_dist,vgrid=None,npts=100,vgrid_pts=1000): """returns posterior of cosI given dists for vsini and veq (incorporates unc. in vsini) """ if vgrid is None: vgrid = np.linspace(min(veq_dist.ppf(0.001),vsini_dist.ppf(0.001)), max(veq_dist.ppf(0.999),vsini_dist.ppf(0.999)), vgrid_pts) logging.debug('vgrid: {} pts, {} to {}'.format(vgrid_pts, vgrid[0], vgrid[-1])) #vgrid = np.linspace(vsini_dist.ppf(0.005),vsini_dist.ppf(0.995),vgrid_pts) cs = np.linspace(0,1,npts) Ls = cs*0 for i,c in enumerate(cs): Ls[i] = like_cosi(c,vsini_dist,veq_dist,vgrid=vgrid) if np.isnan(Ls[-1]): #hack to prevent nan when cos=1 Ls[-1] = Ls[-2] Ls /= np.trapz(Ls,cs) return cs,Ls
[ "def", "cosi_posterior", "(", "vsini_dist", ",", "veq_dist", ",", "vgrid", "=", "None", ",", "npts", "=", "100", ",", "vgrid_pts", "=", "1000", ")", ":", "if", "vgrid", "is", "None", ":", "vgrid", "=", "np", ".", "linspace", "(", "min", "(", "veq_dis...
returns posterior of cosI given dists for vsini and veq (incorporates unc. in vsini)
[ "returns", "posterior", "of", "cosI", "given", "dists", "for", "vsini", "and", "veq", "(", "incorporates", "unc", ".", "in", "vsini", ")" ]
train
https://github.com/timothydmorton/obliquity/blob/ae0a237ae2ca7ba0f7c71f0ee391f52e809da235/obliquity/kappa_inference.py#L107-L125
timothydmorton/obliquity
obliquity/kappa_inference.py
sample_posterior
def sample_posterior(x,post,nsamples=1): """ Returns nsamples from a tabulated posterior (not necessarily normalized) """ cdf = post.cumsum() cdf /= cdf.max() u = rand.random(size=nsamples) inds = np.digitize(u,cdf) return x[inds]
python
def sample_posterior(x,post,nsamples=1): """ Returns nsamples from a tabulated posterior (not necessarily normalized) """ cdf = post.cumsum() cdf /= cdf.max() u = rand.random(size=nsamples) inds = np.digitize(u,cdf) return x[inds]
[ "def", "sample_posterior", "(", "x", ",", "post", ",", "nsamples", "=", "1", ")", ":", "cdf", "=", "post", ".", "cumsum", "(", ")", "cdf", "/=", "cdf", ".", "max", "(", ")", "u", "=", "rand", ".", "random", "(", "size", "=", "nsamples", ")", "i...
Returns nsamples from a tabulated posterior (not necessarily normalized)
[ "Returns", "nsamples", "from", "a", "tabulated", "posterior", "(", "not", "necessarily", "normalized", ")" ]
train
https://github.com/timothydmorton/obliquity/blob/ae0a237ae2ca7ba0f7c71f0ee391f52e809da235/obliquity/kappa_inference.py#L128-L135
timothydmorton/obliquity
obliquity/kappa_inference.py
v_posts_from_dataframe
def v_posts_from_dataframe(df,N=1e4,alpha=0.23,l0=20,sigl=20): """ names: Prot, e_Prot, R, e_R, vsini, e_vsini """ vsini_posts = [] veq_posts = [] if 'ep_R' in df: for R,dR_p,dR_m,P,dP,v,dv in zip(df['R'],df['ep_R'],df['em_R'], df['Prot'],df['e_Prot'], df['vsini'],df['e_vsini']): vsini_posts.append(stats.norm(v,dv)) if dR_p==dR_m: veq_posts.append(Veq_Posterior(R,dR_p,P,dP)) else: R_dist = dists.fit_doublegauss(R,dR_m,dR_p) Prot_dist = stats.norm(P,dP) veq_posts.append(Veq_Posterior_General(R_dist,Prot_dist,N=N, l0=l0,sigl=sigl)) else: for R,dR,P,dP,v,dv in zip(df['R'],df['e_R'], df['Prot'],df['e_Prot'], df['vsini'],df['e_vsini']): vsini_posts.append(stats.norm(v,dv)) veq_posts.append(Veq_Posterior(R,dR,P,dP)) return vsini_posts,veq_posts
python
def v_posts_from_dataframe(df,N=1e4,alpha=0.23,l0=20,sigl=20): """ names: Prot, e_Prot, R, e_R, vsini, e_vsini """ vsini_posts = [] veq_posts = [] if 'ep_R' in df: for R,dR_p,dR_m,P,dP,v,dv in zip(df['R'],df['ep_R'],df['em_R'], df['Prot'],df['e_Prot'], df['vsini'],df['e_vsini']): vsini_posts.append(stats.norm(v,dv)) if dR_p==dR_m: veq_posts.append(Veq_Posterior(R,dR_p,P,dP)) else: R_dist = dists.fit_doublegauss(R,dR_m,dR_p) Prot_dist = stats.norm(P,dP) veq_posts.append(Veq_Posterior_General(R_dist,Prot_dist,N=N, l0=l0,sigl=sigl)) else: for R,dR,P,dP,v,dv in zip(df['R'],df['e_R'], df['Prot'],df['e_Prot'], df['vsini'],df['e_vsini']): vsini_posts.append(stats.norm(v,dv)) veq_posts.append(Veq_Posterior(R,dR,P,dP)) return vsini_posts,veq_posts
[ "def", "v_posts_from_dataframe", "(", "df", ",", "N", "=", "1e4", ",", "alpha", "=", "0.23", ",", "l0", "=", "20", ",", "sigl", "=", "20", ")", ":", "vsini_posts", "=", "[", "]", "veq_posts", "=", "[", "]", "if", "'ep_R'", "in", "df", ":", "for",...
names: Prot, e_Prot, R, e_R, vsini, e_vsini
[ "names", ":", "Prot", "e_Prot", "R", "e_R", "vsini", "e_vsini" ]
train
https://github.com/timothydmorton/obliquity/blob/ae0a237ae2ca7ba0f7c71f0ee391f52e809da235/obliquity/kappa_inference.py#L163-L187
hzdg/django-ecstatic
ecstatic/storage.py
LaxPostProcessorMixin.post_process
def post_process(self, paths, dry_run=False, **options): """ Overridden to work around https://code.djangoproject.com/ticket/19111 """ with post_process_error_counter(self): with patched_name_fn(self, 'hashed_name', 'hashed name'): with patched_name_fn(self, 'url', 'url'): for result in super(LaxPostProcessorMixin, self).post_process(paths, dry_run, **options): yield result error_count = self._post_process_error_count if error_count: print('%s post-processing error%s.' % (error_count, '' if error_count == 1 else 's'))
python
def post_process(self, paths, dry_run=False, **options): """ Overridden to work around https://code.djangoproject.com/ticket/19111 """ with post_process_error_counter(self): with patched_name_fn(self, 'hashed_name', 'hashed name'): with patched_name_fn(self, 'url', 'url'): for result in super(LaxPostProcessorMixin, self).post_process(paths, dry_run, **options): yield result error_count = self._post_process_error_count if error_count: print('%s post-processing error%s.' % (error_count, '' if error_count == 1 else 's'))
[ "def", "post_process", "(", "self", ",", "paths", ",", "dry_run", "=", "False", ",", "*", "*", "options", ")", ":", "with", "post_process_error_counter", "(", "self", ")", ":", "with", "patched_name_fn", "(", "self", ",", "'hashed_name'", ",", "'hashed name'...
Overridden to work around https://code.djangoproject.com/ticket/19111
[ "Overridden", "to", "work", "around", "https", ":", "//", "code", ".", "djangoproject", ".", "com", "/", "ticket", "/", "19111" ]
train
https://github.com/hzdg/django-ecstatic/blob/e2b9bd57ae19938449315457b31130c8df831911/ecstatic/storage.py#L56-L69
hzdg/django-ecstatic
ecstatic/storage.py
CachedFilesMixin.post_process
def post_process(self, paths, dry_run=False, **options): """ Overridden to allow some files to be excluded (using ``postprocess_exclusions``) """ if self.postprocess_exclusions: paths = dict((k, v) for k, v in paths.items() if not self.exclude_file(k)) return super(CachedFilesMixin, self).post_process(paths, dry_run, **options)
python
def post_process(self, paths, dry_run=False, **options): """ Overridden to allow some files to be excluded (using ``postprocess_exclusions``) """ if self.postprocess_exclusions: paths = dict((k, v) for k, v in paths.items() if not self.exclude_file(k)) return super(CachedFilesMixin, self).post_process(paths, dry_run, **options)
[ "def", "post_process", "(", "self", ",", "paths", ",", "dry_run", "=", "False", ",", "*", "*", "options", ")", ":", "if", "self", ".", "postprocess_exclusions", ":", "paths", "=", "dict", "(", "(", "k", ",", "v", ")", "for", "k", ",", "v", "in", ...
Overridden to allow some files to be excluded (using ``postprocess_exclusions``)
[ "Overridden", "to", "allow", "some", "files", "to", "be", "excluded", "(", "using", "postprocess_exclusions", ")" ]
train
https://github.com/hzdg/django-ecstatic/blob/e2b9bd57ae19938449315457b31130c8df831911/ecstatic/storage.py#L89-L99
henzk/ape
ape/installtools/venv.py
VirtualEnv.get_paths
def get_paths(self): ''' get list of module paths ''' # guess site package dir of virtualenv (system dependent) venv_site_packages = '%s/lib/site-packages' % self.venv_dir if not os.path.isdir(venv_site_packages): venv_site_packages_glob = glob.glob('%s/lib/*/site-packages' % self.venv_dir) if len(venv_site_packages_glob): venv_site_packages = venv_site_packages_glob[0] return [ self.venv_dir, venv_site_packages ]
python
def get_paths(self): ''' get list of module paths ''' # guess site package dir of virtualenv (system dependent) venv_site_packages = '%s/lib/site-packages' % self.venv_dir if not os.path.isdir(venv_site_packages): venv_site_packages_glob = glob.glob('%s/lib/*/site-packages' % self.venv_dir) if len(venv_site_packages_glob): venv_site_packages = venv_site_packages_glob[0] return [ self.venv_dir, venv_site_packages ]
[ "def", "get_paths", "(", "self", ")", ":", "# guess site package dir of virtualenv (system dependent)", "venv_site_packages", "=", "'%s/lib/site-packages'", "%", "self", ".", "venv_dir", "if", "not", "os", ".", "path", ".", "isdir", "(", "venv_site_packages", ")", ":"...
get list of module paths
[ "get", "list", "of", "module", "paths" ]
train
https://github.com/henzk/ape/blob/a1b7ea5e5b25c42beffeaaa5c32d94ad82634819/ape/installtools/venv.py#L23-L40
henzk/ape
ape/installtools/venv.py
VirtualEnv.create_virtualenv
def create_virtualenv(venv_dir, use_venv_module=True): """ creates a new virtualenv in venv_dir By default, the built-in venv module is used. On older versions of python, you may set use_venv_module to False to use virtualenv """ if not use_venv_module: try: check_call(['virtualenv', venv_dir, '--no-site-packages']) except OSError: raise Exception('You probably dont have virtualenv installed: sudo apt-get install python-virtualenv') else: check_call([sys.executable or 'python', '-m', 'venv', venv_dir])
python
def create_virtualenv(venv_dir, use_venv_module=True): """ creates a new virtualenv in venv_dir By default, the built-in venv module is used. On older versions of python, you may set use_venv_module to False to use virtualenv """ if not use_venv_module: try: check_call(['virtualenv', venv_dir, '--no-site-packages']) except OSError: raise Exception('You probably dont have virtualenv installed: sudo apt-get install python-virtualenv') else: check_call([sys.executable or 'python', '-m', 'venv', venv_dir])
[ "def", "create_virtualenv", "(", "venv_dir", ",", "use_venv_module", "=", "True", ")", ":", "if", "not", "use_venv_module", ":", "try", ":", "check_call", "(", "[", "'virtualenv'", ",", "venv_dir", ",", "'--no-site-packages'", "]", ")", "except", "OSError", ":...
creates a new virtualenv in venv_dir By default, the built-in venv module is used. On older versions of python, you may set use_venv_module to False to use virtualenv
[ "creates", "a", "new", "virtualenv", "in", "venv_dir" ]
train
https://github.com/henzk/ape/blob/a1b7ea5e5b25c42beffeaaa5c32d94ad82634819/ape/installtools/venv.py#L52-L66
shaypal5/barn
barn/cfg.py
data_dirpath
def data_dirpath(task=None, **kwargs): """Get the path of the corresponding data directory. Parameters ---------- task : str, optional The task for which datasets in the desired directory are used for. If not given, a path for the corresponding task-agnostic directory is returned. **kwargs : extra keyword arguments Extra keyword arguments, representing additional attributes of the datasets, are used to generate additional sub-folders on the path. For example, providing 'lang=en' will results in a path such as '/barn_base_dir/regression/lang_en/mydataset.csv'. Hierarchy always matches lexicographical order of keyword argument names, so 'lang=en' and 'animal=dog' will result in a path such as 'barn_base_dir/task_name/animal_dof/lang_en/dset.csv'. Returns ------- str The path to the desired dir. """ path = _base_dir() if task: path = os.path.join(path, _snail_case(task)) for k, v in sorted(kwargs.items()): subdir_name = '{}_{}'.format(_snail_case(k), _snail_case(v)) path = os.path.join(path, subdir_name) os.makedirs(path, exist_ok=True) return path
python
def data_dirpath(task=None, **kwargs): """Get the path of the corresponding data directory. Parameters ---------- task : str, optional The task for which datasets in the desired directory are used for. If not given, a path for the corresponding task-agnostic directory is returned. **kwargs : extra keyword arguments Extra keyword arguments, representing additional attributes of the datasets, are used to generate additional sub-folders on the path. For example, providing 'lang=en' will results in a path such as '/barn_base_dir/regression/lang_en/mydataset.csv'. Hierarchy always matches lexicographical order of keyword argument names, so 'lang=en' and 'animal=dog' will result in a path such as 'barn_base_dir/task_name/animal_dof/lang_en/dset.csv'. Returns ------- str The path to the desired dir. """ path = _base_dir() if task: path = os.path.join(path, _snail_case(task)) for k, v in sorted(kwargs.items()): subdir_name = '{}_{}'.format(_snail_case(k), _snail_case(v)) path = os.path.join(path, subdir_name) os.makedirs(path, exist_ok=True) return path
[ "def", "data_dirpath", "(", "task", "=", "None", ",", "*", "*", "kwargs", ")", ":", "path", "=", "_base_dir", "(", ")", "if", "task", ":", "path", "=", "os", ".", "path", ".", "join", "(", "path", ",", "_snail_case", "(", "task", ")", ")", "for",...
Get the path of the corresponding data directory. Parameters ---------- task : str, optional The task for which datasets in the desired directory are used for. If not given, a path for the corresponding task-agnostic directory is returned. **kwargs : extra keyword arguments Extra keyword arguments, representing additional attributes of the datasets, are used to generate additional sub-folders on the path. For example, providing 'lang=en' will results in a path such as '/barn_base_dir/regression/lang_en/mydataset.csv'. Hierarchy always matches lexicographical order of keyword argument names, so 'lang=en' and 'animal=dog' will result in a path such as 'barn_base_dir/task_name/animal_dof/lang_en/dset.csv'. Returns ------- str The path to the desired dir.
[ "Get", "the", "path", "of", "the", "corresponding", "data", "directory", "." ]
train
https://github.com/shaypal5/barn/blob/85958a0f9ac94943729605e70527ee726d3f3007/barn/cfg.py#L23-L53
shaypal5/barn
barn/cfg.py
dataset_dirpath
def dataset_dirpath(dataset_name=None, task=None, **kwargs): """Get the path of the corresponding dataset file. Parameters ---------- dataset_name : str, optional The name of the dataset. Used to define a sub-directory to contain all instances of the dataset. If not given, a dataset-agnostic directory path is returned. task : str, optional The task for which datasets in the desired path are used for. If not given, a path for the corresponding task-agnostic directory is returned. **kwargs : extra keyword arguments Extra keyword arguments, representing additional attributes of the datasets, are used to determine additional sub-folders on the path. For example, providing 'lang=en' will results in a path such as '/barn_base_dir/regression/lang_en/mydataset.csv'. Hierarchy always matches lexicographical order of keyword argument names, so 'lang=en' and 'animal=dog' will result in a path such as 'barn_base_dir/task_name/animal_dof/lang_en/dset.csv'. Returns ------- str The path to the desired dataset file. """ dataset_dir_path = data_dirpath(task=task, **kwargs) if dataset_name: dataset_dir_name = _snail_case(dataset_name) dataset_dir_path = os.path.join(dataset_dir_path, dataset_dir_name) os.makedirs(dataset_dir_path, exist_ok=True) return dataset_dir_path
python
def dataset_dirpath(dataset_name=None, task=None, **kwargs): """Get the path of the corresponding dataset file. Parameters ---------- dataset_name : str, optional The name of the dataset. Used to define a sub-directory to contain all instances of the dataset. If not given, a dataset-agnostic directory path is returned. task : str, optional The task for which datasets in the desired path are used for. If not given, a path for the corresponding task-agnostic directory is returned. **kwargs : extra keyword arguments Extra keyword arguments, representing additional attributes of the datasets, are used to determine additional sub-folders on the path. For example, providing 'lang=en' will results in a path such as '/barn_base_dir/regression/lang_en/mydataset.csv'. Hierarchy always matches lexicographical order of keyword argument names, so 'lang=en' and 'animal=dog' will result in a path such as 'barn_base_dir/task_name/animal_dof/lang_en/dset.csv'. Returns ------- str The path to the desired dataset file. """ dataset_dir_path = data_dirpath(task=task, **kwargs) if dataset_name: dataset_dir_name = _snail_case(dataset_name) dataset_dir_path = os.path.join(dataset_dir_path, dataset_dir_name) os.makedirs(dataset_dir_path, exist_ok=True) return dataset_dir_path
[ "def", "dataset_dirpath", "(", "dataset_name", "=", "None", ",", "task", "=", "None", ",", "*", "*", "kwargs", ")", ":", "dataset_dir_path", "=", "data_dirpath", "(", "task", "=", "task", ",", "*", "*", "kwargs", ")", "if", "dataset_name", ":", "dataset_...
Get the path of the corresponding dataset file. Parameters ---------- dataset_name : str, optional The name of the dataset. Used to define a sub-directory to contain all instances of the dataset. If not given, a dataset-agnostic directory path is returned. task : str, optional The task for which datasets in the desired path are used for. If not given, a path for the corresponding task-agnostic directory is returned. **kwargs : extra keyword arguments Extra keyword arguments, representing additional attributes of the datasets, are used to determine additional sub-folders on the path. For example, providing 'lang=en' will results in a path such as '/barn_base_dir/regression/lang_en/mydataset.csv'. Hierarchy always matches lexicographical order of keyword argument names, so 'lang=en' and 'animal=dog' will result in a path such as 'barn_base_dir/task_name/animal_dof/lang_en/dset.csv'. Returns ------- str The path to the desired dataset file.
[ "Get", "the", "path", "of", "the", "corresponding", "dataset", "file", "." ]
train
https://github.com/shaypal5/barn/blob/85958a0f9ac94943729605e70527ee726d3f3007/barn/cfg.py#L56-L88
shaypal5/barn
barn/cfg.py
dataset_filepath
def dataset_filepath(filename, dataset_name=None, task=None, **kwargs): """Get the path of the corresponding dataset file. Parameters ---------- filename : str The name of the file. dataset_name : str, optional The name of the dataset. Used to define a sub-directory to contain all instances of the dataset. If not given, a dataset-specific directory is not created. task : str, optional The task for which the dataset in the desired path is used for. If not given, a path for the corresponding task-agnostic directory is returned. **kwargs : extra keyword arguments Extra keyword arguments, representing additional attributes of the dataset, are used to generate additional sub-folders on the path. For example, providing 'lang=en' will results in a path such as '/barn_base_dir/regression/lang_en/mydataset.csv'. Hierarchy always matches lexicographical order of keyword argument names, so 'lang=en' and 'animal=dog' will result in a path such as 'barn_base_dir/task_name/animal_dof/lang_en/dset.csv'. Returns ------- str The path to the desired dataset file. """ dataset_dir_path = dataset_dirpath( dataset_name=dataset_name, task=task, **kwargs) return os.path.join(dataset_dir_path, filename)
python
def dataset_filepath(filename, dataset_name=None, task=None, **kwargs): """Get the path of the corresponding dataset file. Parameters ---------- filename : str The name of the file. dataset_name : str, optional The name of the dataset. Used to define a sub-directory to contain all instances of the dataset. If not given, a dataset-specific directory is not created. task : str, optional The task for which the dataset in the desired path is used for. If not given, a path for the corresponding task-agnostic directory is returned. **kwargs : extra keyword arguments Extra keyword arguments, representing additional attributes of the dataset, are used to generate additional sub-folders on the path. For example, providing 'lang=en' will results in a path such as '/barn_base_dir/regression/lang_en/mydataset.csv'. Hierarchy always matches lexicographical order of keyword argument names, so 'lang=en' and 'animal=dog' will result in a path such as 'barn_base_dir/task_name/animal_dof/lang_en/dset.csv'. Returns ------- str The path to the desired dataset file. """ dataset_dir_path = dataset_dirpath( dataset_name=dataset_name, task=task, **kwargs) return os.path.join(dataset_dir_path, filename)
[ "def", "dataset_filepath", "(", "filename", ",", "dataset_name", "=", "None", ",", "task", "=", "None", ",", "*", "*", "kwargs", ")", ":", "dataset_dir_path", "=", "dataset_dirpath", "(", "dataset_name", "=", "dataset_name", ",", "task", "=", "task", ",", ...
Get the path of the corresponding dataset file. Parameters ---------- filename : str The name of the file. dataset_name : str, optional The name of the dataset. Used to define a sub-directory to contain all instances of the dataset. If not given, a dataset-specific directory is not created. task : str, optional The task for which the dataset in the desired path is used for. If not given, a path for the corresponding task-agnostic directory is returned. **kwargs : extra keyword arguments Extra keyword arguments, representing additional attributes of the dataset, are used to generate additional sub-folders on the path. For example, providing 'lang=en' will results in a path such as '/barn_base_dir/regression/lang_en/mydataset.csv'. Hierarchy always matches lexicographical order of keyword argument names, so 'lang=en' and 'animal=dog' will result in a path such as 'barn_base_dir/task_name/animal_dof/lang_en/dset.csv'. Returns ------- str The path to the desired dataset file.
[ "Get", "the", "path", "of", "the", "corresponding", "dataset", "file", "." ]
train
https://github.com/shaypal5/barn/blob/85958a0f9ac94943729605e70527ee726d3f3007/barn/cfg.py#L91-L122
quikmile/trelliopg
trelliopg/sql.py
async_atomic
def async_atomic(on_exception=None, raise_exception=True, **kwargs): ''' first argument will be a conn object :param func: :return: ''' if not raise_exception and not on_exception: async def default_on_exception(exc): resp_dict = {} resp_dict['status'] = type(exc) resp_dict['message'] = str(exc) return resp_dict on_exception = default_on_exception elif raise_exception and not on_exception: async def raise_exception(exp_args): raise exp_args on_exception = raise_exception _db_adapter = get_db_adapter() def decorator(func): @functools.wraps(func) async def wrapped(self, *args, **kwargs): conn = None for i in itertools.chain(args, kwargs.values()): if type(i) is Connection: conn = i break if not conn: pool = await _db_adapter.get_pool() async with pool.acquire() as conn: try: async with conn.transaction(): kwargs['conn'] = conn return await func(self, *args, **kwargs) except Exception as e: return await on_exception(e) else: try: async with conn.transaction(): kwargs['conn'] = conn return await func(self, *args, **kwargs) except Exception as e: return await on_exception(e) return wrapped return decorator
python
def async_atomic(on_exception=None, raise_exception=True, **kwargs): ''' first argument will be a conn object :param func: :return: ''' if not raise_exception and not on_exception: async def default_on_exception(exc): resp_dict = {} resp_dict['status'] = type(exc) resp_dict['message'] = str(exc) return resp_dict on_exception = default_on_exception elif raise_exception and not on_exception: async def raise_exception(exp_args): raise exp_args on_exception = raise_exception _db_adapter = get_db_adapter() def decorator(func): @functools.wraps(func) async def wrapped(self, *args, **kwargs): conn = None for i in itertools.chain(args, kwargs.values()): if type(i) is Connection: conn = i break if not conn: pool = await _db_adapter.get_pool() async with pool.acquire() as conn: try: async with conn.transaction(): kwargs['conn'] = conn return await func(self, *args, **kwargs) except Exception as e: return await on_exception(e) else: try: async with conn.transaction(): kwargs['conn'] = conn return await func(self, *args, **kwargs) except Exception as e: return await on_exception(e) return wrapped return decorator
[ "def", "async_atomic", "(", "on_exception", "=", "None", ",", "raise_exception", "=", "True", ",", "*", "*", "kwargs", ")", ":", "if", "not", "raise_exception", "and", "not", "on_exception", ":", "async", "def", "default_on_exception", "(", "exc", ")", ":", ...
first argument will be a conn object :param func: :return:
[ "first", "argument", "will", "be", "a", "conn", "object", ":", "param", "func", ":", ":", "return", ":" ]
train
https://github.com/quikmile/trelliopg/blob/5777c4f06b9be774a9b05e726b3dcf9d965edb9a/trelliopg/sql.py#L57-L106
salesking/salesking_python_sdk
salesking/resources.py
get_model_class
def get_model_class( klass, api = None, use_request_api = True): """ Generates the Model Class based on the klass loads automatically the corresponding json schema file form schemes folder :param klass: json schema filename :param use_request_api: if True autoinitializes request class if api is None :param api: the transportation api if none the default settings are taken an instantiated """ if api is None and use_request_api: api = APIClient() _type = klass if isinstance(klass, dict): _type = klass['type'] schema = loaders.load_schema_raw(_type) model_cls = model_factory(schema, base_class = RemoteResource) model_cls.__api__ = api return model_cls
python
def get_model_class( klass, api = None, use_request_api = True): """ Generates the Model Class based on the klass loads automatically the corresponding json schema file form schemes folder :param klass: json schema filename :param use_request_api: if True autoinitializes request class if api is None :param api: the transportation api if none the default settings are taken an instantiated """ if api is None and use_request_api: api = APIClient() _type = klass if isinstance(klass, dict): _type = klass['type'] schema = loaders.load_schema_raw(_type) model_cls = model_factory(schema, base_class = RemoteResource) model_cls.__api__ = api return model_cls
[ "def", "get_model_class", "(", "klass", ",", "api", "=", "None", ",", "use_request_api", "=", "True", ")", ":", "if", "api", "is", "None", "and", "use_request_api", ":", "api", "=", "APIClient", "(", ")", "_type", "=", "klass", "if", "isinstance", "(", ...
Generates the Model Class based on the klass loads automatically the corresponding json schema file form schemes folder :param klass: json schema filename :param use_request_api: if True autoinitializes request class if api is None :param api: the transportation api if none the default settings are taken an instantiated
[ "Generates", "the", "Model", "Class", "based", "on", "the", "klass", "loads", "automatically", "the", "corresponding", "json", "schema", "file", "form", "schemes", "folder", ":", "param", "klass", ":", "json", "schema", "filename", ":", "param", "use_request_api...
train
https://github.com/salesking/salesking_python_sdk/blob/0d5a95c5ee4e16a85562ceaf67bb11b55e47ee4c/salesking/resources.py#L333-L350
salesking/salesking_python_sdk
salesking/resources.py
ValidateAbleResource.validate
def validate(self, data): """Apply a JSON schema to an object""" try: schema_path = os.path.normpath(SCHEMA_ROOT) location = u'file://%s' % (schema_path) fs_resolver = resolver.LocalRefResolver(location, self.schema) jsonschema.Draft3Validator(self.schema, resolver=fs_resolver).validate(data) except jsonschema.ValidationError as exc: # print "data %s" % (data) raise jsonschema.exceptions.ValidationError(str(exc))
python
def validate(self, data): """Apply a JSON schema to an object""" try: schema_path = os.path.normpath(SCHEMA_ROOT) location = u'file://%s' % (schema_path) fs_resolver = resolver.LocalRefResolver(location, self.schema) jsonschema.Draft3Validator(self.schema, resolver=fs_resolver).validate(data) except jsonschema.ValidationError as exc: # print "data %s" % (data) raise jsonschema.exceptions.ValidationError(str(exc))
[ "def", "validate", "(", "self", ",", "data", ")", ":", "try", ":", "schema_path", "=", "os", ".", "path", ".", "normpath", "(", "SCHEMA_ROOT", ")", "location", "=", "u'file://%s'", "%", "(", "schema_path", ")", "fs_resolver", "=", "resolver", ".", "Local...
Apply a JSON schema to an object
[ "Apply", "a", "JSON", "schema", "to", "an", "object" ]
train
https://github.com/salesking/salesking_python_sdk/blob/0d5a95c5ee4e16a85562ceaf67bb11b55e47ee4c/salesking/resources.py#L49-L59
salesking/salesking_python_sdk
salesking/resources.py
Resource.save
def save(self, *args, **kwargs): """ saves creates or updates current resource returns new resource """ self._pre_save(*args, **kwargs) response = self._save(*args, **kwargs) response = self._post_save(response, *args, **kwargs) return response
python
def save(self, *args, **kwargs): """ saves creates or updates current resource returns new resource """ self._pre_save(*args, **kwargs) response = self._save(*args, **kwargs) response = self._post_save(response, *args, **kwargs) return response
[ "def", "save", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "_pre_save", "(", "*", "args", ",", "*", "*", "kwargs", ")", "response", "=", "self", ".", "_save", "(", "*", "args", ",", "*", "*", "kwargs", ")", ...
saves creates or updates current resource returns new resource
[ "saves", "creates", "or", "updates", "current", "resource", "returns", "new", "resource" ]
train
https://github.com/salesking/salesking_python_sdk/blob/0d5a95c5ee4e16a85562ceaf67bb11b55e47ee4c/salesking/resources.py#L88-L96
salesking/salesking_python_sdk
salesking/resources.py
Resource.load
def load(self, id, *args, **kwargs): """ loads a remote resource by id """ self._pre_load(id, *args, **kwargs) response = self._load(id, *args, **kwargs) response = self._post_load(response, *args, **kwargs) return response
python
def load(self, id, *args, **kwargs): """ loads a remote resource by id """ self._pre_load(id, *args, **kwargs) response = self._load(id, *args, **kwargs) response = self._post_load(response, *args, **kwargs) return response
[ "def", "load", "(", "self", ",", "id", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "_pre_load", "(", "id", ",", "*", "args", ",", "*", "*", "kwargs", ")", "response", "=", "self", ".", "_load", "(", "id", ",", "*", "args...
loads a remote resource by id
[ "loads", "a", "remote", "resource", "by", "id" ]
train
https://github.com/salesking/salesking_python_sdk/blob/0d5a95c5ee4e16a85562ceaf67bb11b55e47ee4c/salesking/resources.py#L110-L117
salesking/salesking_python_sdk
salesking/resources.py
Resource.delete
def delete(self, *args, **kwargs): """ deletes current resource returns response from api """ self._pre_delete(*args, **kwargs) response = self._delete(*args, **kwargs) response = self._post_delete(response, *args, **kwargs) return response
python
def delete(self, *args, **kwargs): """ deletes current resource returns response from api """ self._pre_delete(*args, **kwargs) response = self._delete(*args, **kwargs) response = self._post_delete(response, *args, **kwargs) return response
[ "def", "delete", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "_pre_delete", "(", "*", "args", ",", "*", "*", "kwargs", ")", "response", "=", "self", ".", "_delete", "(", "*", "args", ",", "*", "*", "kwargs", "...
deletes current resource returns response from api
[ "deletes", "current", "resource", "returns", "response", "from", "api" ]
train
https://github.com/salesking/salesking_python_sdk/blob/0d5a95c5ee4e16a85562ceaf67bb11b55e47ee4c/salesking/resources.py#L131-L139
salesking/salesking_python_sdk
salesking/resources.py
BaseResource.to_json
def to_json(self): """ put the object to json and remove the internal stuff salesking schema stores the type in the title """ data = json.dumps(self) out = u'{"%s":%s}' % (self.schema['title'], data) return out
python
def to_json(self): """ put the object to json and remove the internal stuff salesking schema stores the type in the title """ data = json.dumps(self) out = u'{"%s":%s}' % (self.schema['title'], data) return out
[ "def", "to_json", "(", "self", ")", ":", "data", "=", "json", ".", "dumps", "(", "self", ")", "out", "=", "u'{\"%s\":%s}'", "%", "(", "self", ".", "schema", "[", "'title'", "]", ",", "data", ")", "return", "out" ]
put the object to json and remove the internal stuff salesking schema stores the type in the title
[ "put", "the", "object", "to", "json", "and", "remove", "the", "internal", "stuff", "salesking", "schema", "stores", "the", "type", "in", "the", "title" ]
train
https://github.com/salesking/salesking_python_sdk/blob/0d5a95c5ee4e16a85562ceaf67bb11b55e47ee4c/salesking/resources.py#L165-L173
salesking/salesking_python_sdk
salesking/resources.py
RemoteResource._do_api_call
def _do_api_call(self, call_type=u'', id = None): """ returns a response if it is a valid call otherwise the corresponding error """ endpoint = None url = None # print "call_type %s" % (call_type) if call_type == u'load': endpoint = self.get_endpoint("self") if id is None: raise APIException("LOAD_IDNOTSET", "could not load object") elif call_type == u'delete' or (call_type == u"destroy"): endpoint = self.get_endpoint("destroy") if id is None: raise APIException("DELETE_IDNOTSET", "could not delete object") elif call_type == u'update': endpoint = self.get_endpoint("update") if id is None: raise APIException("UPDATE_IDNOTSET", "could not load object") elif call_type == u'create': endpoint = self.get_endpoint("create") url = u"%s%s%s" % (self.__api__.base_url, API_BASE_PATH, endpoint['href']) # post? elif call_type == u'schema': # add schema gethering functionality # hackisch endpoint = self.get_endpoint("create") url = u"%s%s%s/schema" % (self.__api__.base_url, API_BASE_PATH, endpoint['href']) endpoint['method'] = u'GET' if id is not None: url = u"%s%s%s" % (self.__api__.base_url, API_BASE_PATH, endpoint['href'].replace(u"{id}",id)) ## excecute the api request payload = self.to_json() if u'method' in endpoint.keys(): method = endpoint['method'] else: method = u'GET' # request raises exceptions if something goes wrong obj = None try: # dbg msg = u"url: %s method:%s p: %s" % (url, method, payload) #print msg response = self.__api__.request(url, method, data=payload) #load update create success if ((response.status_code == 200 and call_type in ['load', 'update']) or (response.status_code == 201 and call_type == 'create')): msg = "call_type: %s successfully completed" % call_type log.info(msg) return self.to_instance(response) elif (response.status_code == 200 and call_type in ['delete', 'destroy']): #delete success msg ="call_type: %s successfully completed" % call_type log.info(msg) return self._try_to_serialize(response) elif 200 <= response.status_code <= 299: return self._try_to_serialize(response) except Exception as e: msg = "Exception occoured %s url: %s" % (e, url) log.error(msg) raise e
python
def _do_api_call(self, call_type=u'', id = None): """ returns a response if it is a valid call otherwise the corresponding error """ endpoint = None url = None # print "call_type %s" % (call_type) if call_type == u'load': endpoint = self.get_endpoint("self") if id is None: raise APIException("LOAD_IDNOTSET", "could not load object") elif call_type == u'delete' or (call_type == u"destroy"): endpoint = self.get_endpoint("destroy") if id is None: raise APIException("DELETE_IDNOTSET", "could not delete object") elif call_type == u'update': endpoint = self.get_endpoint("update") if id is None: raise APIException("UPDATE_IDNOTSET", "could not load object") elif call_type == u'create': endpoint = self.get_endpoint("create") url = u"%s%s%s" % (self.__api__.base_url, API_BASE_PATH, endpoint['href']) # post? elif call_type == u'schema': # add schema gethering functionality # hackisch endpoint = self.get_endpoint("create") url = u"%s%s%s/schema" % (self.__api__.base_url, API_BASE_PATH, endpoint['href']) endpoint['method'] = u'GET' if id is not None: url = u"%s%s%s" % (self.__api__.base_url, API_BASE_PATH, endpoint['href'].replace(u"{id}",id)) ## excecute the api request payload = self.to_json() if u'method' in endpoint.keys(): method = endpoint['method'] else: method = u'GET' # request raises exceptions if something goes wrong obj = None try: # dbg msg = u"url: %s method:%s p: %s" % (url, method, payload) #print msg response = self.__api__.request(url, method, data=payload) #load update create success if ((response.status_code == 200 and call_type in ['load', 'update']) or (response.status_code == 201 and call_type == 'create')): msg = "call_type: %s successfully completed" % call_type log.info(msg) return self.to_instance(response) elif (response.status_code == 200 and call_type in ['delete', 'destroy']): #delete success msg ="call_type: %s successfully completed" % call_type log.info(msg) return self._try_to_serialize(response) elif 200 <= response.status_code <= 299: return self._try_to_serialize(response) except Exception as e: msg = "Exception occoured %s url: %s" % (e, url) log.error(msg) raise e
[ "def", "_do_api_call", "(", "self", ",", "call_type", "=", "u''", ",", "id", "=", "None", ")", ":", "endpoint", "=", "None", "url", "=", "None", "# print \"call_type %s\" % (call_type)", "if", "call_type", "==", "u'load'", ":", "endpoint", "=", "self", ".", ...
returns a response if it is a valid call otherwise the corresponding error
[ "returns", "a", "response", "if", "it", "is", "a", "valid", "call", "otherwise", "the", "corresponding", "error" ]
train
https://github.com/salesking/salesking_python_sdk/blob/0d5a95c5ee4e16a85562ceaf67bb11b55e47ee4c/salesking/resources.py#L227-L290
salesking/salesking_python_sdk
salesking/resources.py
RemoteResource.to_instance
def to_instance(self, response): """ transforms the content to a new instace of object self.schema['title'] :param content: valid response :returns new instance of current class """ klass = self.schema['title'] cls = get_model_class(klass, api=self.__api__) jdict = json.loads(response.content, encoding="utf-8") ### check if we have a response properties_dict = jdict[self.schema['title']] # @todo: find a way to handle the data # validation fails if the none values are not removed new_dict = helpers.remove_properties_containing_None(properties_dict) #jdict[self.schema['title']] = new_dict obj = cls(new_dict) #obj.links = jdict[self.schema['title']]['links'] return obj
python
def to_instance(self, response): """ transforms the content to a new instace of object self.schema['title'] :param content: valid response :returns new instance of current class """ klass = self.schema['title'] cls = get_model_class(klass, api=self.__api__) jdict = json.loads(response.content, encoding="utf-8") ### check if we have a response properties_dict = jdict[self.schema['title']] # @todo: find a way to handle the data # validation fails if the none values are not removed new_dict = helpers.remove_properties_containing_None(properties_dict) #jdict[self.schema['title']] = new_dict obj = cls(new_dict) #obj.links = jdict[self.schema['title']]['links'] return obj
[ "def", "to_instance", "(", "self", ",", "response", ")", ":", "klass", "=", "self", ".", "schema", "[", "'title'", "]", "cls", "=", "get_model_class", "(", "klass", ",", "api", "=", "self", ".", "__api__", ")", "jdict", "=", "json", ".", "loads", "("...
transforms the content to a new instace of object self.schema['title'] :param content: valid response :returns new instance of current class
[ "transforms", "the", "content", "to", "a", "new", "instace", "of", "object", "self", ".", "schema", "[", "title", "]", ":", "param", "content", ":", "valid", "response", ":", "returns", "new", "instance", "of", "current", "class" ]
train
https://github.com/salesking/salesking_python_sdk/blob/0d5a95c5ee4e16a85562ceaf67bb11b55e47ee4c/salesking/resources.py#L292-L310
salesking/salesking_python_sdk
salesking/resources.py
RemoteResource.dict_to_instance
def dict_to_instance(self, content): """ transforms the content to a new instace of object self.schema['title'] :param content: valid response :returns new instance of current class """ klass = self.schema['title'] cls = get_model_class(klass, api=self.__api__) # jdict = json.loads(content, encoding="utf-8") ### check if we have a response properties_dict = content[self.schema['title']][self.schema['title']] #@todo: find a way to handle the data # validation fails if the none values are not removed new_dict = helpers.remove_properties_containing_None(properties_dict) obj = cls(new_dict) #obj.links = content[self.schema['title']]['links'] return obj
python
def dict_to_instance(self, content): """ transforms the content to a new instace of object self.schema['title'] :param content: valid response :returns new instance of current class """ klass = self.schema['title'] cls = get_model_class(klass, api=self.__api__) # jdict = json.loads(content, encoding="utf-8") ### check if we have a response properties_dict = content[self.schema['title']][self.schema['title']] #@todo: find a way to handle the data # validation fails if the none values are not removed new_dict = helpers.remove_properties_containing_None(properties_dict) obj = cls(new_dict) #obj.links = content[self.schema['title']]['links'] return obj
[ "def", "dict_to_instance", "(", "self", ",", "content", ")", ":", "klass", "=", "self", ".", "schema", "[", "'title'", "]", "cls", "=", "get_model_class", "(", "klass", ",", "api", "=", "self", ".", "__api__", ")", "# jdict = json.loads(content, encoding=\"utf...
transforms the content to a new instace of object self.schema['title'] :param content: valid response :returns new instance of current class
[ "transforms", "the", "content", "to", "a", "new", "instace", "of", "object", "self", ".", "schema", "[", "title", "]", ":", "param", "content", ":", "valid", "response", ":", "returns", "new", "instance", "of", "current", "class" ]
train
https://github.com/salesking/salesking_python_sdk/blob/0d5a95c5ee4e16a85562ceaf67bb11b55e47ee4c/salesking/resources.py#L312-L329
CodyKochmann/strict_functions
strict_functions/trace2.py
get_locals
def get_locals(f): ''' returns a formatted view of the local variables in a frame ''' return pformat({i:f.f_locals[i] for i in f.f_locals if not i.startswith('__')})
python
def get_locals(f): ''' returns a formatted view of the local variables in a frame ''' return pformat({i:f.f_locals[i] for i in f.f_locals if not i.startswith('__')})
[ "def", "get_locals", "(", "f", ")", ":", "return", "pformat", "(", "{", "i", ":", "f", ".", "f_locals", "[", "i", "]", "for", "i", "in", "f", ".", "f_locals", "if", "not", "i", ".", "startswith", "(", "'__'", ")", "}", ")" ]
returns a formatted view of the local variables in a frame
[ "returns", "a", "formatted", "view", "of", "the", "local", "variables", "in", "a", "frame" ]
train
https://github.com/CodyKochmann/strict_functions/blob/adaf78084c66929552d80c95f980e7e0c4331478/strict_functions/trace2.py#L59-L61
CodyKochmann/strict_functions
strict_functions/trace2.py
default_profiler
def default_profiler(f, _type, _value): ''' inspects an input frame and pretty prints the following: <src-path>:<src-line> -> <function-name> <source-code> <local-variables> ---------------------------------------- ''' try: profile_print( '\n'.join([ get_frame_src(f), get_locals(f), '----------------------------------------' ]) ) except: pass
python
def default_profiler(f, _type, _value): ''' inspects an input frame and pretty prints the following: <src-path>:<src-line> -> <function-name> <source-code> <local-variables> ---------------------------------------- ''' try: profile_print( '\n'.join([ get_frame_src(f), get_locals(f), '----------------------------------------' ]) ) except: pass
[ "def", "default_profiler", "(", "f", ",", "_type", ",", "_value", ")", ":", "try", ":", "profile_print", "(", "'\\n'", ".", "join", "(", "[", "get_frame_src", "(", "f", ")", ",", "get_locals", "(", "f", ")", ",", "'----------------------------------------'",...
inspects an input frame and pretty prints the following: <src-path>:<src-line> -> <function-name> <source-code> <local-variables> ----------------------------------------
[ "inspects", "an", "input", "frame", "and", "pretty", "prints", "the", "following", ":" ]
train
https://github.com/CodyKochmann/strict_functions/blob/adaf78084c66929552d80c95f980e7e0c4331478/strict_functions/trace2.py#L63-L80
coded-by-hand/mass
env/lib/python2.7/site-packages/pip-1.0.2-py2.7.egg/pip/basecommand.py
open_logfile
def open_logfile(filename, mode='a'): """Open the named log file in append mode. If the file already exists, a separator will also be printed to the file to separate past activity from current activity. """ filename = os.path.expanduser(filename) filename = os.path.abspath(filename) dirname = os.path.dirname(filename) if not os.path.exists(dirname): os.makedirs(dirname) exists = os.path.exists(filename) log_fp = open(filename, mode) if exists: log_fp.write('%s\n' % ('-'*60)) log_fp.write('%s run on %s\n' % (sys.argv[0], time.strftime('%c'))) return log_fp
python
def open_logfile(filename, mode='a'): """Open the named log file in append mode. If the file already exists, a separator will also be printed to the file to separate past activity from current activity. """ filename = os.path.expanduser(filename) filename = os.path.abspath(filename) dirname = os.path.dirname(filename) if not os.path.exists(dirname): os.makedirs(dirname) exists = os.path.exists(filename) log_fp = open(filename, mode) if exists: log_fp.write('%s\n' % ('-'*60)) log_fp.write('%s run on %s\n' % (sys.argv[0], time.strftime('%c'))) return log_fp
[ "def", "open_logfile", "(", "filename", ",", "mode", "=", "'a'", ")", ":", "filename", "=", "os", ".", "path", ".", "expanduser", "(", "filename", ")", "filename", "=", "os", ".", "path", ".", "abspath", "(", "filename", ")", "dirname", "=", "os", "....
Open the named log file in append mode. If the file already exists, a separator will also be printed to the file to separate past activity from current activity.
[ "Open", "the", "named", "log", "file", "in", "append", "mode", "." ]
train
https://github.com/coded-by-hand/mass/blob/59005479efed3cd8598a8f0c66791a4482071899/env/lib/python2.7/site-packages/pip-1.0.2-py2.7.egg/pip/basecommand.py#L167-L184
Scille/mestr
mestr/mestr.py
authenticate
def authenticate(realm, authid, details): """ application_name : name of your application version : version of your application required_components dictionary of components required for you application and their version required { "component" : "1.1", "component2" : "0.1", ... } when all the different component required has been register your component will be allow to authenticate with a role build only for your application with only the right right for it to works """ global _start global _waiting import json ticket = json.loads(details['ticket'] ) if 'application_name' not in ticket and 'version' not in ticket: raise ApplicationError( 'could not start the authentication of an app,\ field application_name or version is missing') application_name = ticket['application_name'] version = ticket['version'] required_components = ticket[ 'required_components'] if 'required_components' in ticket else {} if not _try_to_start_app(application_name, version, required_components): ready_defered = defer.Deferred() ready_defered.addCallback(defer_try_start_app, application_name=application_name, version=version, required_components=required_components) _waiting[application_name]['defer'] = ready_defered yield ready_defered print("[MESTR] start app: ", _start) print("[MESTR] waiting app: ", _waiting) for k in _start: if k in _waiting: _waiting = remove_element(_waiting, k) # backend role must be contains in the config.json # since we can't create them dynamically for the moment returnValue("backend")
python
def authenticate(realm, authid, details): """ application_name : name of your application version : version of your application required_components dictionary of components required for you application and their version required { "component" : "1.1", "component2" : "0.1", ... } when all the different component required has been register your component will be allow to authenticate with a role build only for your application with only the right right for it to works """ global _start global _waiting import json ticket = json.loads(details['ticket'] ) if 'application_name' not in ticket and 'version' not in ticket: raise ApplicationError( 'could not start the authentication of an app,\ field application_name or version is missing') application_name = ticket['application_name'] version = ticket['version'] required_components = ticket[ 'required_components'] if 'required_components' in ticket else {} if not _try_to_start_app(application_name, version, required_components): ready_defered = defer.Deferred() ready_defered.addCallback(defer_try_start_app, application_name=application_name, version=version, required_components=required_components) _waiting[application_name]['defer'] = ready_defered yield ready_defered print("[MESTR] start app: ", _start) print("[MESTR] waiting app: ", _waiting) for k in _start: if k in _waiting: _waiting = remove_element(_waiting, k) # backend role must be contains in the config.json # since we can't create them dynamically for the moment returnValue("backend")
[ "def", "authenticate", "(", "realm", ",", "authid", ",", "details", ")", ":", "global", "_start", "global", "_waiting", "import", "json", "ticket", "=", "json", ".", "loads", "(", "details", "[", "'ticket'", "]", ")", "if", "'application_name'", "not", "in...
application_name : name of your application version : version of your application required_components dictionary of components required for you application and their version required { "component" : "1.1", "component2" : "0.1", ... } when all the different component required has been register your component will be allow to authenticate with a role build only for your application with only the right right for it to works
[ "application_name", ":", "name", "of", "your", "application", "version", ":", "version", "of", "your", "application", "required_components", "dictionary", "of", "components", "required", "for", "you", "application", "and", "their", "version", "required" ]
train
https://github.com/Scille/mestr/blob/344092aac77ad222fb6cd62927c7801c2ece33fc/mestr/mestr.py#L61-L109
TangentMicroServices/PythonClient
microclient/clients.py
ServiceBase.info
def info(self, resource): ''' prints information/documentation on a provided resource ''' service_def, resource_def, path = self._get_service_information( resource) print (resource) print ("*******************************************") print ("Base URL: {0}" . format (self.tld)) print ("Resource path: {0}" . format (resource_def.get("endpoint"))) print ("Required parameters: {0}" . format (resource_def.get("required_params"))) print ("Optional parameters" . format (resource_def.get("optional_params")))
python
def info(self, resource): ''' prints information/documentation on a provided resource ''' service_def, resource_def, path = self._get_service_information( resource) print (resource) print ("*******************************************") print ("Base URL: {0}" . format (self.tld)) print ("Resource path: {0}" . format (resource_def.get("endpoint"))) print ("Required parameters: {0}" . format (resource_def.get("required_params"))) print ("Optional parameters" . format (resource_def.get("optional_params")))
[ "def", "info", "(", "self", ",", "resource", ")", ":", "service_def", ",", "resource_def", ",", "path", "=", "self", ".", "_get_service_information", "(", "resource", ")", "print", "(", "resource", ")", "print", "(", "\"*******************************************\...
prints information/documentation on a provided resource
[ "prints", "information", "/", "documentation", "on", "a", "provided", "resource" ]
train
https://github.com/TangentMicroServices/PythonClient/blob/98cc4b3027fa1b2e8a66146a7efe76370fc225f0/microclient/clients.py#L120-L132
TangentMicroServices/PythonClient
microclient/clients.py
ServiceBase.create
def create(self, resource, data): ''' A base function that performs a default create POST request for a given object ''' service_def, resource_def, path = self._get_service_information( resource) self._validate(resource, data) return self.call(path=path, data=data, method='post')
python
def create(self, resource, data): ''' A base function that performs a default create POST request for a given object ''' service_def, resource_def, path = self._get_service_information( resource) self._validate(resource, data) return self.call(path=path, data=data, method='post')
[ "def", "create", "(", "self", ",", "resource", ",", "data", ")", ":", "service_def", ",", "resource_def", ",", "path", "=", "self", ".", "_get_service_information", "(", "resource", ")", "self", ".", "_validate", "(", "resource", ",", "data", ")", "return"...
A base function that performs a default create POST request for a given object
[ "A", "base", "function", "that", "performs", "a", "default", "create", "POST", "request", "for", "a", "given", "object" ]
train
https://github.com/TangentMicroServices/PythonClient/blob/98cc4b3027fa1b2e8a66146a7efe76370fc225f0/microclient/clients.py#L148-L157
TangentMicroServices/PythonClient
microclient/clients.py
ServiceBase.update
def update(self, resource, resource_id, data): ''' A base function that performs a default create PATCH request for a given object ''' service_def, resource_def, path = self._get_service_information( resource) update_path = "{0}{1}/" . format(path, resource_id) return self.call(path=update_path, data=data, method='patch')
python
def update(self, resource, resource_id, data): ''' A base function that performs a default create PATCH request for a given object ''' service_def, resource_def, path = self._get_service_information( resource) update_path = "{0}{1}/" . format(path, resource_id) return self.call(path=update_path, data=data, method='patch')
[ "def", "update", "(", "self", ",", "resource", ",", "resource_id", ",", "data", ")", ":", "service_def", ",", "resource_def", ",", "path", "=", "self", ".", "_get_service_information", "(", "resource", ")", "update_path", "=", "\"{0}{1}/\"", ".", "format", "...
A base function that performs a default create PATCH request for a given object
[ "A", "base", "function", "that", "performs", "a", "default", "create", "PATCH", "request", "for", "a", "given", "object" ]
train
https://github.com/TangentMicroServices/PythonClient/blob/98cc4b3027fa1b2e8a66146a7efe76370fc225f0/microclient/clients.py#L159-L167
TangentMicroServices/PythonClient
microclient/clients.py
ServiceBase.delete
def delete(self, resource, resource_id): ''' A base function that performs a default delete DELETE request for a given object ''' service_def, resource_def, path = self._get_service_information( resource) delete_path = "{0}{1}/" . format(path, resource_id) return self.call(path=delete_path, method="delete")
python
def delete(self, resource, resource_id): ''' A base function that performs a default delete DELETE request for a given object ''' service_def, resource_def, path = self._get_service_information( resource) delete_path = "{0}{1}/" . format(path, resource_id) return self.call(path=delete_path, method="delete")
[ "def", "delete", "(", "self", ",", "resource", ",", "resource_id", ")", ":", "service_def", ",", "resource_def", ",", "path", "=", "self", ".", "_get_service_information", "(", "resource", ")", "delete_path", "=", "\"{0}{1}/\"", ".", "format", "(", "path", "...
A base function that performs a default delete DELETE request for a given object
[ "A", "base", "function", "that", "performs", "a", "default", "delete", "DELETE", "request", "for", "a", "given", "object" ]
train
https://github.com/TangentMicroServices/PythonClient/blob/98cc4b3027fa1b2e8a66146a7efe76370fc225f0/microclient/clients.py#L169-L177
TangentMicroServices/PythonClient
microclient/clients.py
ServiceBase._make_api
def _make_api(self, service_name): ''' not yet in use .. ''' resources = [resource for resource, resource_details in service_definitions.get(service_name, {}).get("resources", {}).items()] for resource in resources: setattr(self, 'list_{0}' . format(resource), self.list) setattr(self, 'get_{0}' . format(resource), self.get) setattr(self, 'create_{0}' . format(resource), self.create) setattr(self, 'update_{0}' . format(resource), self.update) setattr(self, 'delete_{0}' . format(resource), self.delete)
python
def _make_api(self, service_name): ''' not yet in use .. ''' resources = [resource for resource, resource_details in service_definitions.get(service_name, {}).get("resources", {}).items()] for resource in resources: setattr(self, 'list_{0}' . format(resource), self.list) setattr(self, 'get_{0}' . format(resource), self.get) setattr(self, 'create_{0}' . format(resource), self.create) setattr(self, 'update_{0}' . format(resource), self.update) setattr(self, 'delete_{0}' . format(resource), self.delete)
[ "def", "_make_api", "(", "self", ",", "service_name", ")", ":", "resources", "=", "[", "resource", "for", "resource", ",", "resource_details", "in", "service_definitions", ".", "get", "(", "service_name", ",", "{", "}", ")", ".", "get", "(", "\"resources\"",...
not yet in use ..
[ "not", "yet", "in", "use", ".." ]
train
https://github.com/TangentMicroServices/PythonClient/blob/98cc4b3027fa1b2e8a66146a7efe76370fc225f0/microclient/clients.py#L179-L192
GustavePate/distarkcli
distarkcli/utils/NetInfo.py
NetInfo.getSystemIps
def getSystemIps(): """ will not return the localhost one """ IPs = [] for interface in NetInfo.getSystemIfs(): if not interface.startswith('lo'): ip = netinfo.get_ip(interface) IPs.append(ip) return IPs
python
def getSystemIps(): """ will not return the localhost one """ IPs = [] for interface in NetInfo.getSystemIfs(): if not interface.startswith('lo'): ip = netinfo.get_ip(interface) IPs.append(ip) return IPs
[ "def", "getSystemIps", "(", ")", ":", "IPs", "=", "[", "]", "for", "interface", "in", "NetInfo", ".", "getSystemIfs", "(", ")", ":", "if", "not", "interface", ".", "startswith", "(", "'lo'", ")", ":", "ip", "=", "netinfo", ".", "get_ip", "(", "interf...
will not return the localhost one
[ "will", "not", "return", "the", "localhost", "one" ]
train
https://github.com/GustavePate/distarkcli/blob/44b0e637e94ebb2687a1b7e2f6c5d0658d775238/distarkcli/utils/NetInfo.py#L25-L32
GustavePate/distarkcli
distarkcli/utils/NetInfo.py
NetInfo.getIPString
def getIPString(): """ return comma delimited string of all the system IPs""" if not(NetInfo.systemip): NetInfo.systemip = ",".join(NetInfo.getSystemIps()) return NetInfo.systemip
python
def getIPString(): """ return comma delimited string of all the system IPs""" if not(NetInfo.systemip): NetInfo.systemip = ",".join(NetInfo.getSystemIps()) return NetInfo.systemip
[ "def", "getIPString", "(", ")", ":", "if", "not", "(", "NetInfo", ".", "systemip", ")", ":", "NetInfo", ".", "systemip", "=", "\",\"", ".", "join", "(", "NetInfo", ".", "getSystemIps", "(", ")", ")", "return", "NetInfo", ".", "systemip" ]
return comma delimited string of all the system IPs
[ "return", "comma", "delimited", "string", "of", "all", "the", "system", "IPs" ]
train
https://github.com/GustavePate/distarkcli/blob/44b0e637e94ebb2687a1b7e2f6c5d0658d775238/distarkcli/utils/NetInfo.py#L35-L39
calve/prof
prof/tools.py
check_update
def check_update(): """ Return True if an update is available on pypi """ r = requests.get("https://pypi.python.org/pypi/prof/json") data = r.json() if versiontuple(data['info']['version']) > versiontuple(__version__): return True return False
python
def check_update(): """ Return True if an update is available on pypi """ r = requests.get("https://pypi.python.org/pypi/prof/json") data = r.json() if versiontuple(data['info']['version']) > versiontuple(__version__): return True return False
[ "def", "check_update", "(", ")", ":", "r", "=", "requests", ".", "get", "(", "\"https://pypi.python.org/pypi/prof/json\"", ")", "data", "=", "r", ".", "json", "(", ")", "if", "versiontuple", "(", "data", "[", "'info'", "]", "[", "'version'", "]", ")", ">...
Return True if an update is available on pypi
[ "Return", "True", "if", "an", "update", "is", "available", "on", "pypi" ]
train
https://github.com/calve/prof/blob/c6e034f45ab60908dea661e8271bc44758aeedcf/prof/tools.py#L9-L17
scivision/gridaurora
gridaurora/__init__.py
to_ut1unix
def to_ut1unix(time: Union[str, datetime, float, np.ndarray]) -> np.ndarray: """ converts time inputs to UT1 seconds since Unix epoch """ # keep this order time = totime(time) if isinstance(time, (float, int)): return time if isinstance(time, (tuple, list, np.ndarray)): assert isinstance(time[0], datetime), f'expected datetime, not {type(time[0])}' return np.array(list(map(dt2ut1, time))) else: assert isinstance(time, datetime) return dt2ut1(time)
python
def to_ut1unix(time: Union[str, datetime, float, np.ndarray]) -> np.ndarray: """ converts time inputs to UT1 seconds since Unix epoch """ # keep this order time = totime(time) if isinstance(time, (float, int)): return time if isinstance(time, (tuple, list, np.ndarray)): assert isinstance(time[0], datetime), f'expected datetime, not {type(time[0])}' return np.array(list(map(dt2ut1, time))) else: assert isinstance(time, datetime) return dt2ut1(time)
[ "def", "to_ut1unix", "(", "time", ":", "Union", "[", "str", ",", "datetime", ",", "float", ",", "np", ".", "ndarray", "]", ")", "->", "np", ".", "ndarray", ":", "# keep this order", "time", "=", "totime", "(", "time", ")", "if", "isinstance", "(", "t...
converts time inputs to UT1 seconds since Unix epoch
[ "converts", "time", "inputs", "to", "UT1", "seconds", "since", "Unix", "epoch" ]
train
https://github.com/scivision/gridaurora/blob/c3957b93c2201afff62bd104e0acead52c0d9e90/gridaurora/__init__.py#L28-L43
scivision/gridaurora
gridaurora/__init__.py
chapman_profile
def chapman_profile(Z0: float, zKM: np.ndarray, H: float): """ Z0: altitude [km] of intensity peak zKM: altitude grid [km] H: scale height [km] example: pz = chapman_profile(110,np.arange(90,200,1),20) """ return np.exp(.5*(1-(zKM-Z0)/H - np.exp((Z0-zKM)/H)))
python
def chapman_profile(Z0: float, zKM: np.ndarray, H: float): """ Z0: altitude [km] of intensity peak zKM: altitude grid [km] H: scale height [km] example: pz = chapman_profile(110,np.arange(90,200,1),20) """ return np.exp(.5*(1-(zKM-Z0)/H - np.exp((Z0-zKM)/H)))
[ "def", "chapman_profile", "(", "Z0", ":", "float", ",", "zKM", ":", "np", ".", "ndarray", ",", "H", ":", "float", ")", ":", "return", "np", ".", "exp", "(", ".5", "*", "(", "1", "-", "(", "zKM", "-", "Z0", ")", "/", "H", "-", "np", ".", "ex...
Z0: altitude [km] of intensity peak zKM: altitude grid [km] H: scale height [km] example: pz = chapman_profile(110,np.arange(90,200,1),20)
[ "Z0", ":", "altitude", "[", "km", "]", "of", "intensity", "peak", "zKM", ":", "altitude", "grid", "[", "km", "]", "H", ":", "scale", "height", "[", "km", "]" ]
train
https://github.com/scivision/gridaurora/blob/c3957b93c2201afff62bd104e0acead52c0d9e90/gridaurora/__init__.py#L64-L73
coded-by-hand/mass
env/lib/python2.7/site-packages/pip-1.0.2-py2.7.egg/pip/req.py
parse_editable
def parse_editable(editable_req, default_vcs=None): """Parses svn+http://blahblah@rev#egg=Foobar into a requirement (Foobar) and a URL""" url = editable_req if os.path.isdir(url) and os.path.exists(os.path.join(url, 'setup.py')): # Treating it as code that has already been checked out url = path_to_url(url) if url.lower().startswith('file:'): return None, url for version_control in vcs: if url.lower().startswith('%s:' % version_control): url = '%s+%s' % (version_control, url) if '+' not in url: if default_vcs: url = default_vcs + '+' + url else: raise InstallationError( '--editable=%s should be formatted with svn+URL, git+URL, hg+URL or bzr+URL' % editable_req) vc_type = url.split('+', 1)[0].lower() if not vcs.get_backend(vc_type): raise InstallationError( 'For --editable=%s only svn (svn+URL), Git (git+URL), Mercurial (hg+URL) and Bazaar (bzr+URL) is currently supported' % editable_req) match = re.search(r'(?:#|#.*?&)egg=([^&]*)', editable_req) if (not match or not match.group(1)) and vcs.get_backend(vc_type): parts = [p for p in editable_req.split('#', 1)[0].split('/') if p] if parts[-2] in ('tags', 'branches', 'tag', 'branch'): req = parts[-3] elif parts[-1] == 'trunk': req = parts[-2] else: raise InstallationError( '--editable=%s is not the right format; it must have #egg=Package' % editable_req) else: req = match.group(1) ## FIXME: use package_to_requirement? match = re.search(r'^(.*?)(?:-dev|-\d.*)$', req) if match: # Strip off -dev, -0.2, etc. req = match.group(1) return req, url
python
def parse_editable(editable_req, default_vcs=None): """Parses svn+http://blahblah@rev#egg=Foobar into a requirement (Foobar) and a URL""" url = editable_req if os.path.isdir(url) and os.path.exists(os.path.join(url, 'setup.py')): # Treating it as code that has already been checked out url = path_to_url(url) if url.lower().startswith('file:'): return None, url for version_control in vcs: if url.lower().startswith('%s:' % version_control): url = '%s+%s' % (version_control, url) if '+' not in url: if default_vcs: url = default_vcs + '+' + url else: raise InstallationError( '--editable=%s should be formatted with svn+URL, git+URL, hg+URL or bzr+URL' % editable_req) vc_type = url.split('+', 1)[0].lower() if not vcs.get_backend(vc_type): raise InstallationError( 'For --editable=%s only svn (svn+URL), Git (git+URL), Mercurial (hg+URL) and Bazaar (bzr+URL) is currently supported' % editable_req) match = re.search(r'(?:#|#.*?&)egg=([^&]*)', editable_req) if (not match or not match.group(1)) and vcs.get_backend(vc_type): parts = [p for p in editable_req.split('#', 1)[0].split('/') if p] if parts[-2] in ('tags', 'branches', 'tag', 'branch'): req = parts[-3] elif parts[-1] == 'trunk': req = parts[-2] else: raise InstallationError( '--editable=%s is not the right format; it must have #egg=Package' % editable_req) else: req = match.group(1) ## FIXME: use package_to_requirement? match = re.search(r'^(.*?)(?:-dev|-\d.*)$', req) if match: # Strip off -dev, -0.2, etc. req = match.group(1) return req, url
[ "def", "parse_editable", "(", "editable_req", ",", "default_vcs", "=", "None", ")", ":", "url", "=", "editable_req", "if", "os", ".", "path", ".", "isdir", "(", "url", ")", "and", "os", ".", "path", ".", "exists", "(", "os", ".", "path", ".", "join",...
Parses svn+http://blahblah@rev#egg=Foobar into a requirement (Foobar) and a URL
[ "Parses", "svn", "+", "http", ":", "//", "blahblah" ]
train
https://github.com/coded-by-hand/mass/blob/59005479efed3cd8598a8f0c66791a4482071899/env/lib/python2.7/site-packages/pip-1.0.2-py2.7.egg/pip/req.py#L1268-L1308
coded-by-hand/mass
env/lib/python2.7/site-packages/pip-1.0.2-py2.7.egg/pip/req.py
InstallRequirement.from_line
def from_line(cls, name, comes_from=None): """Creates an InstallRequirement from a name, which might be a requirement, directory containing 'setup.py', filename, or URL. """ url = None name = name.strip() req = None path = os.path.normpath(os.path.abspath(name)) link = None if is_url(name): link = Link(name) elif os.path.isdir(path) and (os.path.sep in name or name.startswith('.')): if not is_installable_dir(path): raise InstallationError("Directory %r is not installable. File 'setup.py' not found.", name) link = Link(path_to_url(name)) elif is_archive_file(path): if not os.path.isfile(path): logger.warn('Requirement %r looks like a filename, but the file does not exist', name) link = Link(path_to_url(name)) # If the line has an egg= definition, but isn't editable, pull the requirement out. # Otherwise, assume the name is the req for the non URL/path/archive case. if link and req is None: url = link.url_fragment req = link.egg_fragment # Handle relative file URLs if link.scheme == 'file' and re.search(r'\.\./', url): url = path_to_url(os.path.normpath(os.path.abspath(link.path))) else: req = name return cls(req, comes_from, url=url)
python
def from_line(cls, name, comes_from=None): """Creates an InstallRequirement from a name, which might be a requirement, directory containing 'setup.py', filename, or URL. """ url = None name = name.strip() req = None path = os.path.normpath(os.path.abspath(name)) link = None if is_url(name): link = Link(name) elif os.path.isdir(path) and (os.path.sep in name or name.startswith('.')): if not is_installable_dir(path): raise InstallationError("Directory %r is not installable. File 'setup.py' not found.", name) link = Link(path_to_url(name)) elif is_archive_file(path): if not os.path.isfile(path): logger.warn('Requirement %r looks like a filename, but the file does not exist', name) link = Link(path_to_url(name)) # If the line has an egg= definition, but isn't editable, pull the requirement out. # Otherwise, assume the name is the req for the non URL/path/archive case. if link and req is None: url = link.url_fragment req = link.egg_fragment # Handle relative file URLs if link.scheme == 'file' and re.search(r'\.\./', url): url = path_to_url(os.path.normpath(os.path.abspath(link.path))) else: req = name return cls(req, comes_from, url=url)
[ "def", "from_line", "(", "cls", ",", "name", ",", "comes_from", "=", "None", ")", ":", "url", "=", "None", "name", "=", "name", ".", "strip", "(", ")", "req", "=", "None", "path", "=", "os", ".", "path", ".", "normpath", "(", "os", ".", "path", ...
Creates an InstallRequirement from a name, which might be a requirement, directory containing 'setup.py', filename, or URL.
[ "Creates", "an", "InstallRequirement", "from", "a", "name", "which", "might", "be", "a", "requirement", "directory", "containing", "setup", ".", "py", "filename", "or", "URL", "." ]
train
https://github.com/coded-by-hand/mass/blob/59005479efed3cd8598a8f0c66791a4482071899/env/lib/python2.7/site-packages/pip-1.0.2-py2.7.egg/pip/req.py#L70-L104
coded-by-hand/mass
env/lib/python2.7/site-packages/pip-1.0.2-py2.7.egg/pip/req.py
InstallRequirement.remove_temporary_source
def remove_temporary_source(self): """Remove the source files from this requirement, if they are marked for deletion""" if self.is_bundle or os.path.exists(self.delete_marker_filename): logger.info('Removing source in %s' % self.source_dir) if self.source_dir: rmtree(self.source_dir) self.source_dir = None if self._temp_build_dir and os.path.exists(self._temp_build_dir): rmtree(self._temp_build_dir) self._temp_build_dir = None
python
def remove_temporary_source(self): """Remove the source files from this requirement, if they are marked for deletion""" if self.is_bundle or os.path.exists(self.delete_marker_filename): logger.info('Removing source in %s' % self.source_dir) if self.source_dir: rmtree(self.source_dir) self.source_dir = None if self._temp_build_dir and os.path.exists(self._temp_build_dir): rmtree(self._temp_build_dir) self._temp_build_dir = None
[ "def", "remove_temporary_source", "(", "self", ")", ":", "if", "self", ".", "is_bundle", "or", "os", ".", "path", ".", "exists", "(", "self", ".", "delete_marker_filename", ")", ":", "logger", ".", "info", "(", "'Removing source in %s'", "%", "self", ".", ...
Remove the source files from this requirement, if they are marked for deletion
[ "Remove", "the", "source", "files", "from", "this", "requirement", "if", "they", "are", "marked", "for", "deletion" ]
train
https://github.com/coded-by-hand/mass/blob/59005479efed3cd8598a8f0c66791a4482071899/env/lib/python2.7/site-packages/pip-1.0.2-py2.7.egg/pip/req.py#L607-L617
coded-by-hand/mass
env/lib/python2.7/site-packages/pip-1.0.2-py2.7.egg/pip/req.py
InstallRequirement.check_if_exists
def check_if_exists(self): """Find an installed distribution that satisfies or conflicts with this requirement, and set self.satisfied_by or self.conflicts_with appropriately.""" if self.req is None: return False try: self.satisfied_by = pkg_resources.get_distribution(self.req) except pkg_resources.DistributionNotFound: return False except pkg_resources.VersionConflict: self.conflicts_with = pkg_resources.get_distribution(self.req.project_name) return True
python
def check_if_exists(self): """Find an installed distribution that satisfies or conflicts with this requirement, and set self.satisfied_by or self.conflicts_with appropriately.""" if self.req is None: return False try: self.satisfied_by = pkg_resources.get_distribution(self.req) except pkg_resources.DistributionNotFound: return False except pkg_resources.VersionConflict: self.conflicts_with = pkg_resources.get_distribution(self.req.project_name) return True
[ "def", "check_if_exists", "(", "self", ")", ":", "if", "self", ".", "req", "is", "None", ":", "return", "False", "try", ":", "self", ".", "satisfied_by", "=", "pkg_resources", ".", "get_distribution", "(", "self", ".", "req", ")", "except", "pkg_resources"...
Find an installed distribution that satisfies or conflicts with this requirement, and set self.satisfied_by or self.conflicts_with appropriately.
[ "Find", "an", "installed", "distribution", "that", "satisfies", "or", "conflicts", "with", "this", "requirement", "and", "set", "self", ".", "satisfied_by", "or", "self", ".", "conflicts_with", "appropriately", "." ]
train
https://github.com/coded-by-hand/mass/blob/59005479efed3cd8598a8f0c66791a4482071899/env/lib/python2.7/site-packages/pip-1.0.2-py2.7.egg/pip/req.py#L647-L659
six8/corona-cipr
fabfile.py
release
def release(): """ Release current version to pypi """ with settings(warn_only=True): r = local(clom.git['diff-files']('--quiet', '--ignore-submodules', '--')) if r.return_code != 0: abort('There are uncommitted changes, commit or stash them before releasing') version = open('VERSION.txt').read().strip() print('Releasing %s...' % version) local(clom.git.flow.release.start(version)) local(clom.git.flow.release.finish(version, m='Release-%s' % version)) local(clom.git.push('origin', 'master', 'develop', tags=True)) local(clom.python('setup.py', 'sdist', 'upload'))
python
def release(): """ Release current version to pypi """ with settings(warn_only=True): r = local(clom.git['diff-files']('--quiet', '--ignore-submodules', '--')) if r.return_code != 0: abort('There are uncommitted changes, commit or stash them before releasing') version = open('VERSION.txt').read().strip() print('Releasing %s...' % version) local(clom.git.flow.release.start(version)) local(clom.git.flow.release.finish(version, m='Release-%s' % version)) local(clom.git.push('origin', 'master', 'develop', tags=True)) local(clom.python('setup.py', 'sdist', 'upload'))
[ "def", "release", "(", ")", ":", "with", "settings", "(", "warn_only", "=", "True", ")", ":", "r", "=", "local", "(", "clom", ".", "git", "[", "'diff-files'", "]", "(", "'--quiet'", ",", "'--ignore-submodules'", ",", "'--'", ")", ")", "if", "r", ".",...
Release current version to pypi
[ "Release", "current", "version", "to", "pypi" ]
train
https://github.com/six8/corona-cipr/blob/a2f45761080c874afa39bf95fd5c4467c8eae272/fabfile.py#L5-L22
pulseenergy/vacation
vacation/transactions.py
execute
def execute(tokens): """ Perform the actions described by the input tokens. """ if not validate_rc(): print('Your .vacationrc file has errors!') echo_vacation_rc() return for action, value in tokens: if action == 'show': show() elif action == 'log': log_vacation_days() elif action == 'echo': echo_vacation_rc() elif action == 'take': take(value) elif action == 'cancel': cancel(value) elif action == 'setrate': setrate(value) elif action == 'setdays': setdays(value)
python
def execute(tokens): """ Perform the actions described by the input tokens. """ if not validate_rc(): print('Your .vacationrc file has errors!') echo_vacation_rc() return for action, value in tokens: if action == 'show': show() elif action == 'log': log_vacation_days() elif action == 'echo': echo_vacation_rc() elif action == 'take': take(value) elif action == 'cancel': cancel(value) elif action == 'setrate': setrate(value) elif action == 'setdays': setdays(value)
[ "def", "execute", "(", "tokens", ")", ":", "if", "not", "validate_rc", "(", ")", ":", "print", "(", "'Your .vacationrc file has errors!'", ")", "echo_vacation_rc", "(", ")", "return", "for", "action", ",", "value", "in", "tokens", ":", "if", "action", "==", ...
Perform the actions described by the input tokens.
[ "Perform", "the", "actions", "described", "by", "the", "input", "tokens", "." ]
train
https://github.com/pulseenergy/vacation/blob/23c6122590852a5e55d84d366143469af6602839/vacation/transactions.py#L20-L41
pulseenergy/vacation
vacation/transactions.py
unique
def unique(transactions): """ Remove any duplicate entries. """ seen = set() # TODO: Handle comments return [x for x in transactions if not (x in seen or seen.add(x))]
python
def unique(transactions): """ Remove any duplicate entries. """ seen = set() # TODO: Handle comments return [x for x in transactions if not (x in seen or seen.add(x))]
[ "def", "unique", "(", "transactions", ")", ":", "seen", "=", "set", "(", ")", "# TODO: Handle comments", "return", "[", "x", "for", "x", "in", "transactions", "if", "not", "(", "x", "in", "seen", "or", "seen", ".", "add", "(", "x", ")", ")", "]" ]
Remove any duplicate entries.
[ "Remove", "any", "duplicate", "entries", "." ]
train
https://github.com/pulseenergy/vacation/blob/23c6122590852a5e55d84d366143469af6602839/vacation/transactions.py#L78-L82
pulseenergy/vacation
vacation/transactions.py
sort
def sort(transactions): """ Return a list of sorted transactions by date. """ return transactions.sort(key=lambda x: datetime.datetime.strptime(x.split(':')[0], '%Y-%m-%d'))[:]
python
def sort(transactions): """ Return a list of sorted transactions by date. """ return transactions.sort(key=lambda x: datetime.datetime.strptime(x.split(':')[0], '%Y-%m-%d'))[:]
[ "def", "sort", "(", "transactions", ")", ":", "return", "transactions", ".", "sort", "(", "key", "=", "lambda", "x", ":", "datetime", ".", "datetime", ".", "strptime", "(", "x", ".", "split", "(", "':'", ")", "[", "0", "]", ",", "'%Y-%m-%d'", ")", ...
Return a list of sorted transactions by date.
[ "Return", "a", "list", "of", "sorted", "transactions", "by", "date", "." ]
train
https://github.com/pulseenergy/vacation/blob/23c6122590852a5e55d84d366143469af6602839/vacation/transactions.py#L85-L87
pulseenergy/vacation
vacation/transactions.py
validate_rc
def validate_rc(): """ Before we execute any actions, let's validate our .vacationrc. """ transactions = rc.read() if not transactions: print('Your .vacationrc file is empty! Set days and rate.') return False transactions = sort(unique(transactions)) return validate_setup(transactions)
python
def validate_rc(): """ Before we execute any actions, let's validate our .vacationrc. """ transactions = rc.read() if not transactions: print('Your .vacationrc file is empty! Set days and rate.') return False transactions = sort(unique(transactions)) return validate_setup(transactions)
[ "def", "validate_rc", "(", ")", ":", "transactions", "=", "rc", ".", "read", "(", ")", "if", "not", "transactions", ":", "print", "(", "'Your .vacationrc file is empty! Set days and rate.'", ")", "return", "False", "transactions", "=", "sort", "(", "unique", "("...
Before we execute any actions, let's validate our .vacationrc.
[ "Before", "we", "execute", "any", "actions", "let", "s", "validate", "our", ".", "vacationrc", "." ]
train
https://github.com/pulseenergy/vacation/blob/23c6122590852a5e55d84d366143469af6602839/vacation/transactions.py#L90-L97
pulseenergy/vacation
vacation/transactions.py
validate_setup
def validate_setup(transactions): """ First two transactions must set rate & days. """ if not transactions: return True try: first, second = transactions[:2] except ValueError: print('Error: vacationrc file must have both initial days and rates entries') return False parts1, parts2 = first.split(), second.split() if parts1[0] != parts2[0]: print('Error: First two entries in vacationrc must have the same date') return False # Dates must match if 'rate' not in (parts1[1], parts2[1]) or 'days' not in (parts1[1], parts2[1]): print('Error: First two entries in vacationrc must set days and rate') return False return True
python
def validate_setup(transactions): """ First two transactions must set rate & days. """ if not transactions: return True try: first, second = transactions[:2] except ValueError: print('Error: vacationrc file must have both initial days and rates entries') return False parts1, parts2 = first.split(), second.split() if parts1[0] != parts2[0]: print('Error: First two entries in vacationrc must have the same date') return False # Dates must match if 'rate' not in (parts1[1], parts2[1]) or 'days' not in (parts1[1], parts2[1]): print('Error: First two entries in vacationrc must set days and rate') return False return True
[ "def", "validate_setup", "(", "transactions", ")", ":", "if", "not", "transactions", ":", "return", "True", "try", ":", "first", ",", "second", "=", "transactions", "[", ":", "2", "]", "except", "ValueError", ":", "print", "(", "'Error: vacationrc file must ha...
First two transactions must set rate & days.
[ "First", "two", "transactions", "must", "set", "rate", "&", "days", "." ]
train
https://github.com/pulseenergy/vacation/blob/23c6122590852a5e55d84d366143469af6602839/vacation/transactions.py#L100-L120
pulseenergy/vacation
vacation/transactions.py
_parse_transaction_entry
def _parse_transaction_entry(entry): """ Validate & parse a transaction into (date, action, value) tuple. """ parts = entry.split() date_string = parts[0] try: date = datetime.datetime.strptime(date_string[:-1], '%Y-%m-%d').date() except ValueError: raise ValueError('Invalid date in vacationrc for entry: {}'.format(entry)) if len(parts) < 2: raise ValueError('.vacationrc missing an action for entry: {}'.format(entry)) action = parts[1].lower() if action not in ('days', 'rate', 'off', 'adjust', 'show'): raise ValueError('Invalid action in vacationrc for entry: {}'.format(entry)) try: value = float(parts[2]) except IndexError: value = None except (ValueError, TypeError): raise ValueError('Invalid value in vacationrc for entry: {}'.format(entry)) return (date, action, value)
python
def _parse_transaction_entry(entry): """ Validate & parse a transaction into (date, action, value) tuple. """ parts = entry.split() date_string = parts[0] try: date = datetime.datetime.strptime(date_string[:-1], '%Y-%m-%d').date() except ValueError: raise ValueError('Invalid date in vacationrc for entry: {}'.format(entry)) if len(parts) < 2: raise ValueError('.vacationrc missing an action for entry: {}'.format(entry)) action = parts[1].lower() if action not in ('days', 'rate', 'off', 'adjust', 'show'): raise ValueError('Invalid action in vacationrc for entry: {}'.format(entry)) try: value = float(parts[2]) except IndexError: value = None except (ValueError, TypeError): raise ValueError('Invalid value in vacationrc for entry: {}'.format(entry)) return (date, action, value)
[ "def", "_parse_transaction_entry", "(", "entry", ")", ":", "parts", "=", "entry", ".", "split", "(", ")", "date_string", "=", "parts", "[", "0", "]", "try", ":", "date", "=", "datetime", ".", "datetime", ".", "strptime", "(", "date_string", "[", ":", "...
Validate & parse a transaction into (date, action, value) tuple.
[ "Validate", "&", "parse", "a", "transaction", "into", "(", "date", "action", "value", ")", "tuple", "." ]
train
https://github.com/pulseenergy/vacation/blob/23c6122590852a5e55d84d366143469af6602839/vacation/transactions.py#L123-L146
pulseenergy/vacation
vacation/transactions.py
stat_holidays
def stat_holidays(province='BC', year=2015): """ Returns a list of holiday dates for a province and year. """ return holidays.Canada(state=province, years=year).keys()
python
def stat_holidays(province='BC', year=2015): """ Returns a list of holiday dates for a province and year. """ return holidays.Canada(state=province, years=year).keys()
[ "def", "stat_holidays", "(", "province", "=", "'BC'", ",", "year", "=", "2015", ")", ":", "return", "holidays", ".", "Canada", "(", "state", "=", "province", ",", "years", "=", "year", ")", ".", "keys", "(", ")" ]
Returns a list of holiday dates for a province and year.
[ "Returns", "a", "list", "of", "holiday", "dates", "for", "a", "province", "and", "year", "." ]
train
https://github.com/pulseenergy/vacation/blob/23c6122590852a5e55d84d366143469af6602839/vacation/transactions.py#L149-L151
pulseenergy/vacation
vacation/transactions.py
sum_transactions
def sum_transactions(transactions): """ Sums transactions into a total of remaining vacation days. """ workdays_per_year = 250 previous_date = None rate = 0 day_sum = 0 for transaction in transactions: date, action, value = _parse_transaction_entry(transaction) if previous_date is None: previous_date = date elapsed = workdays.networkdays(previous_date, date, stat_holidays()) - 1 if action == 'rate': rate = float(value) / workdays_per_year elif action == 'off': elapsed -= 1 # Didn't work that day day_sum -= 1 # And we used a day day_sum += rate * elapsed if action == 'days': day_sum = value # Fixed value as of this entry previous_date = date return day_sum
python
def sum_transactions(transactions): """ Sums transactions into a total of remaining vacation days. """ workdays_per_year = 250 previous_date = None rate = 0 day_sum = 0 for transaction in transactions: date, action, value = _parse_transaction_entry(transaction) if previous_date is None: previous_date = date elapsed = workdays.networkdays(previous_date, date, stat_holidays()) - 1 if action == 'rate': rate = float(value) / workdays_per_year elif action == 'off': elapsed -= 1 # Didn't work that day day_sum -= 1 # And we used a day day_sum += rate * elapsed if action == 'days': day_sum = value # Fixed value as of this entry previous_date = date return day_sum
[ "def", "sum_transactions", "(", "transactions", ")", ":", "workdays_per_year", "=", "250", "previous_date", "=", "None", "rate", "=", "0", "day_sum", "=", "0", "for", "transaction", "in", "transactions", ":", "date", ",", "action", ",", "value", "=", "_parse...
Sums transactions into a total of remaining vacation days.
[ "Sums", "transactions", "into", "a", "total", "of", "remaining", "vacation", "days", "." ]
train
https://github.com/pulseenergy/vacation/blob/23c6122590852a5e55d84d366143469af6602839/vacation/transactions.py#L154-L178
pulseenergy/vacation
vacation/transactions.py
get_days_off
def get_days_off(transactions): """ Return the dates for any 'take day off' transactions. """ days_off = [] for trans in transactions: date, action, _ = _parse_transaction_entry(trans) if action == 'off': days_off.append(date) return days_off
python
def get_days_off(transactions): """ Return the dates for any 'take day off' transactions. """ days_off = [] for trans in transactions: date, action, _ = _parse_transaction_entry(trans) if action == 'off': days_off.append(date) return days_off
[ "def", "get_days_off", "(", "transactions", ")", ":", "days_off", "=", "[", "]", "for", "trans", "in", "transactions", ":", "date", ",", "action", ",", "_", "=", "_parse_transaction_entry", "(", "trans", ")", "if", "action", "==", "'off'", ":", "days_off",...
Return the dates for any 'take day off' transactions.
[ "Return", "the", "dates", "for", "any", "take", "day", "off", "transactions", "." ]
train
https://github.com/pulseenergy/vacation/blob/23c6122590852a5e55d84d366143469af6602839/vacation/transactions.py#L181-L188
pulseenergy/vacation
vacation/transactions.py
log_vacation_days
def log_vacation_days(): """ Sum and report taken days off. """ days_off = get_days_off(rc.read()) pretty_days = map(lambda day: day.strftime('%a %b %d %Y'), days_off) for day in pretty_days: print(day)
python
def log_vacation_days(): """ Sum and report taken days off. """ days_off = get_days_off(rc.read()) pretty_days = map(lambda day: day.strftime('%a %b %d %Y'), days_off) for day in pretty_days: print(day)
[ "def", "log_vacation_days", "(", ")", ":", "days_off", "=", "get_days_off", "(", "rc", ".", "read", "(", ")", ")", "pretty_days", "=", "map", "(", "lambda", "day", ":", "day", ".", "strftime", "(", "'%a %b %d %Y'", ")", ",", "days_off", ")", "for", "da...
Sum and report taken days off.
[ "Sum", "and", "report", "taken", "days", "off", "." ]
train
https://github.com/pulseenergy/vacation/blob/23c6122590852a5e55d84d366143469af6602839/vacation/transactions.py#L191-L196
pulseenergy/vacation
vacation/transactions.py
echo_vacation_rc
def echo_vacation_rc(): """ Display all our .vacationrc file. """ contents = rc.read() print('.vacationrc\n===========') for line in contents: print(line.rstrip())
python
def echo_vacation_rc(): """ Display all our .vacationrc file. """ contents = rc.read() print('.vacationrc\n===========') for line in contents: print(line.rstrip())
[ "def", "echo_vacation_rc", "(", ")", ":", "contents", "=", "rc", ".", "read", "(", ")", "print", "(", "'.vacationrc\\n==========='", ")", "for", "line", "in", "contents", ":", "print", "(", "line", ".", "rstrip", "(", ")", ")" ]
Display all our .vacationrc file.
[ "Display", "all", "our", ".", "vacationrc", "file", "." ]
train
https://github.com/pulseenergy/vacation/blob/23c6122590852a5e55d84d366143469af6602839/vacation/transactions.py#L199-L204
solocompt/plugs-mail
plugs_mail/utils.py
to_email
def to_email(email_class, email, language=None, **data): """ Send email to specified email address """ if language: email_class().send([email], language=language, **data) else: email_class().send([email], translation.get_language(), **data)
python
def to_email(email_class, email, language=None, **data): """ Send email to specified email address """ if language: email_class().send([email], language=language, **data) else: email_class().send([email], translation.get_language(), **data)
[ "def", "to_email", "(", "email_class", ",", "email", ",", "language", "=", "None", ",", "*", "*", "data", ")", ":", "if", "language", ":", "email_class", "(", ")", ".", "send", "(", "[", "email", "]", ",", "language", "=", "language", ",", "*", "*"...
Send email to specified email address
[ "Send", "email", "to", "specified", "email", "address" ]
train
https://github.com/solocompt/plugs-mail/blob/6139fa79ddb437562db1769d03bd3098c25a06fa/plugs_mail/utils.py#L8-L15
solocompt/plugs-mail
plugs_mail/utils.py
to_user
def to_user(email_class, user, **data): """ Email user """ try: email_class().send([user.email], user.language, **data) except AttributeError: # this is a fallback in case the user model does not have the language field email_class().send([user.email], translation.get_language(), **data)
python
def to_user(email_class, user, **data): """ Email user """ try: email_class().send([user.email], user.language, **data) except AttributeError: # this is a fallback in case the user model does not have the language field email_class().send([user.email], translation.get_language(), **data)
[ "def", "to_user", "(", "email_class", ",", "user", ",", "*", "*", "data", ")", ":", "try", ":", "email_class", "(", ")", ".", "send", "(", "[", "user", ".", "email", "]", ",", "user", ".", "language", ",", "*", "*", "data", ")", "except", "Attrib...
Email user
[ "Email", "user" ]
train
https://github.com/solocompt/plugs-mail/blob/6139fa79ddb437562db1769d03bd3098c25a06fa/plugs_mail/utils.py#L17-L25
solocompt/plugs-mail
plugs_mail/utils.py
to_staff
def to_staff(email_class, **data): """ Email staff users """ for user in get_user_model().objects.filter(is_staff=True): try: email_class().send([user.email], user.language, **data) except AttributeError: email_class().send([user.email], translation.get_language(), **data)
python
def to_staff(email_class, **data): """ Email staff users """ for user in get_user_model().objects.filter(is_staff=True): try: email_class().send([user.email], user.language, **data) except AttributeError: email_class().send([user.email], translation.get_language(), **data)
[ "def", "to_staff", "(", "email_class", ",", "*", "*", "data", ")", ":", "for", "user", "in", "get_user_model", "(", ")", ".", "objects", ".", "filter", "(", "is_staff", "=", "True", ")", ":", "try", ":", "email_class", "(", ")", ".", "send", "(", "...
Email staff users
[ "Email", "staff", "users" ]
train
https://github.com/solocompt/plugs-mail/blob/6139fa79ddb437562db1769d03bd3098c25a06fa/plugs_mail/utils.py#L27-L35
solocompt/plugs-mail
plugs_mail/utils.py
to_superuser
def to_superuser(email_class, **data): """ Email superusers """ for user in get_user_model().objects.filter(is_superuser=True): try: email_class().send([user.email], user.language, **data) except AttributeError: email_class().send([user.email], translation.get_language(), **data)
python
def to_superuser(email_class, **data): """ Email superusers """ for user in get_user_model().objects.filter(is_superuser=True): try: email_class().send([user.email], user.language, **data) except AttributeError: email_class().send([user.email], translation.get_language(), **data)
[ "def", "to_superuser", "(", "email_class", ",", "*", "*", "data", ")", ":", "for", "user", "in", "get_user_model", "(", ")", ".", "objects", ".", "filter", "(", "is_superuser", "=", "True", ")", ":", "try", ":", "email_class", "(", ")", ".", "send", ...
Email superusers
[ "Email", "superusers" ]
train
https://github.com/solocompt/plugs-mail/blob/6139fa79ddb437562db1769d03bd3098c25a06fa/plugs_mail/utils.py#L37-L45