repo
stringlengths
7
55
path
stringlengths
4
223
func_name
stringlengths
1
134
original_string
stringlengths
75
104k
language
stringclasses
1 value
code
stringlengths
75
104k
code_tokens
listlengths
19
28.4k
docstring
stringlengths
1
46.9k
docstring_tokens
listlengths
1
1.97k
sha
stringlengths
40
40
url
stringlengths
87
315
partition
stringclasses
1 value
wdm0006/sklearn-extensions
sklearn_extensions/extreme_learning_machines/random_layer.py
GRBFRandomLayer._compute_radii
def _compute_radii(self): """Generate radii""" denom = pow(-np.log(self.grbf_lambda), 1.0/self.tau_vals) self.components_['radii'] = self.dF_vals/denom
python
def _compute_radii(self): """Generate radii""" denom = pow(-np.log(self.grbf_lambda), 1.0/self.tau_vals) self.components_['radii'] = self.dF_vals/denom
[ "def", "_compute_radii", "(", "self", ")", ":", "denom", "=", "pow", "(", "-", "np", ".", "log", "(", "self", ".", "grbf_lambda", ")", ",", "1.0", "/", "self", ".", "tau_vals", ")", "self", ".", "components_", "[", "'radii'", "]", "=", "self", ".",...
Generate radii
[ "Generate", "radii" ]
329f3efdb8c3c3a367b264f7c76c76411a784530
https://github.com/wdm0006/sklearn-extensions/blob/329f3efdb8c3c3a367b264f7c76c76411a784530/sklearn_extensions/extreme_learning_machines/random_layer.py#L521-L525
train
wdm0006/sklearn-extensions
sklearn_extensions/extreme_learning_machines/elm.py
GenELMRegressor._fit_regression
def _fit_regression(self, y): """ fit regression using pseudo-inverse or supplied regressor """ if self.regressor is None: self.coefs_ = safe_sparse_dot(pinv2(self.hidden_activations_), y) else: self.regressor.fit(self.hidden_activations_, y) ...
python
def _fit_regression(self, y): """ fit regression using pseudo-inverse or supplied regressor """ if self.regressor is None: self.coefs_ = safe_sparse_dot(pinv2(self.hidden_activations_), y) else: self.regressor.fit(self.hidden_activations_, y) ...
[ "def", "_fit_regression", "(", "self", ",", "y", ")", ":", "if", "self", ".", "regressor", "is", "None", ":", "self", ".", "coefs_", "=", "safe_sparse_dot", "(", "pinv2", "(", "self", ".", "hidden_activations_", ")", ",", "y", ")", "else", ":", "self",...
fit regression using pseudo-inverse or supplied regressor
[ "fit", "regression", "using", "pseudo", "-", "inverse", "or", "supplied", "regressor" ]
329f3efdb8c3c3a367b264f7c76c76411a784530
https://github.com/wdm0006/sklearn-extensions/blob/329f3efdb8c3c3a367b264f7c76c76411a784530/sklearn_extensions/extreme_learning_machines/elm.py#L149-L160
train
wdm0006/sklearn-extensions
sklearn_extensions/extreme_learning_machines/elm.py
GenELMRegressor.fit
def fit(self, X, y): """ Fit the model using X, y as training data. Parameters ---------- X : {array-like, sparse matrix} of shape [n_samples, n_features] Training vectors, where n_samples is the number of samples and n_features is the number of features....
python
def fit(self, X, y): """ Fit the model using X, y as training data. Parameters ---------- X : {array-like, sparse matrix} of shape [n_samples, n_features] Training vectors, where n_samples is the number of samples and n_features is the number of features....
[ "def", "fit", "(", "self", ",", "X", ",", "y", ")", ":", "# fit random hidden layer and compute the hidden layer activations", "self", ".", "hidden_activations_", "=", "self", ".", "hidden_layer", ".", "fit_transform", "(", "X", ")", "# solve the regression from hidden ...
Fit the model using X, y as training data. Parameters ---------- X : {array-like, sparse matrix} of shape [n_samples, n_features] Training vectors, where n_samples is the number of samples and n_features is the number of features. y : array-like of shape [n_samp...
[ "Fit", "the", "model", "using", "X", "y", "as", "training", "data", "." ]
329f3efdb8c3c3a367b264f7c76c76411a784530
https://github.com/wdm0006/sklearn-extensions/blob/329f3efdb8c3c3a367b264f7c76c76411a784530/sklearn_extensions/extreme_learning_machines/elm.py#L162-L188
train
wdm0006/sklearn-extensions
sklearn_extensions/extreme_learning_machines/elm.py
GenELMRegressor._get_predictions
def _get_predictions(self): """ get predictions using internal least squares/supplied regressor """ if self.regressor is None: preds = safe_sparse_dot(self.hidden_activations_, self.coefs_) else: preds = self.regressor.predict(self.hidden_activations_) ...
python
def _get_predictions(self): """ get predictions using internal least squares/supplied regressor """ if self.regressor is None: preds = safe_sparse_dot(self.hidden_activations_, self.coefs_) else: preds = self.regressor.predict(self.hidden_activations_) ...
[ "def", "_get_predictions", "(", "self", ")", ":", "if", "self", ".", "regressor", "is", "None", ":", "preds", "=", "safe_sparse_dot", "(", "self", ".", "hidden_activations_", ",", "self", ".", "coefs_", ")", "else", ":", "preds", "=", "self", ".", "regre...
get predictions using internal least squares/supplied regressor
[ "get", "predictions", "using", "internal", "least", "squares", "/", "supplied", "regressor" ]
329f3efdb8c3c3a367b264f7c76c76411a784530
https://github.com/wdm0006/sklearn-extensions/blob/329f3efdb8c3c3a367b264f7c76c76411a784530/sklearn_extensions/extreme_learning_machines/elm.py#L190-L199
train
wdm0006/sklearn-extensions
sklearn_extensions/extreme_learning_machines/elm.py
GenELMRegressor.predict
def predict(self, X): """ Predict values using the model Parameters ---------- X : {array-like, sparse matrix} of shape [n_samples, n_features] Returns ------- C : numpy array of shape [n_samples, n_outputs] Predicted values. """ ...
python
def predict(self, X): """ Predict values using the model Parameters ---------- X : {array-like, sparse matrix} of shape [n_samples, n_features] Returns ------- C : numpy array of shape [n_samples, n_outputs] Predicted values. """ ...
[ "def", "predict", "(", "self", ",", "X", ")", ":", "if", "not", "self", ".", "fitted_", ":", "raise", "ValueError", "(", "\"ELMRegressor not fitted\"", ")", "# compute hidden layer activations", "self", ".", "hidden_activations_", "=", "self", ".", "hidden_layer",...
Predict values using the model Parameters ---------- X : {array-like, sparse matrix} of shape [n_samples, n_features] Returns ------- C : numpy array of shape [n_samples, n_outputs] Predicted values.
[ "Predict", "values", "using", "the", "model" ]
329f3efdb8c3c3a367b264f7c76c76411a784530
https://github.com/wdm0006/sklearn-extensions/blob/329f3efdb8c3c3a367b264f7c76c76411a784530/sklearn_extensions/extreme_learning_machines/elm.py#L201-L223
train
wdm0006/sklearn-extensions
sklearn_extensions/extreme_learning_machines/elm.py
GenELMClassifier.fit
def fit(self, X, y): """ Fit the model using X, y as training data. Parameters ---------- X : {array-like, sparse matrix} of shape [n_samples, n_features] Training vectors, where n_samples is the number of samples and n_features is the number of features....
python
def fit(self, X, y): """ Fit the model using X, y as training data. Parameters ---------- X : {array-like, sparse matrix} of shape [n_samples, n_features] Training vectors, where n_samples is the number of samples and n_features is the number of features....
[ "def", "fit", "(", "self", ",", "X", ",", "y", ")", ":", "self", ".", "classes_", "=", "np", ".", "unique", "(", "y", ")", "y_bin", "=", "self", ".", "binarizer", ".", "fit_transform", "(", "y", ")", "self", ".", "genelm_regressor_", ".", "fit", ...
Fit the model using X, y as training data. Parameters ---------- X : {array-like, sparse matrix} of shape [n_samples, n_features] Training vectors, where n_samples is the number of samples and n_features is the number of features. y : array-like of shape [n_samp...
[ "Fit", "the", "model", "using", "X", "y", "as", "training", "data", "." ]
329f3efdb8c3c3a367b264f7c76c76411a784530
https://github.com/wdm0006/sklearn-extensions/blob/329f3efdb8c3c3a367b264f7c76c76411a784530/sklearn_extensions/extreme_learning_machines/elm.py#L299-L324
train
wdm0006/sklearn-extensions
sklearn_extensions/extreme_learning_machines/elm.py
GenELMClassifier.predict
def predict(self, X): """Predict values using the model Parameters ---------- X : {array-like, sparse matrix} of shape [n_samples, n_features] Returns ------- C : numpy array of shape [n_samples, n_outputs] Predicted values. """ raw_p...
python
def predict(self, X): """Predict values using the model Parameters ---------- X : {array-like, sparse matrix} of shape [n_samples, n_features] Returns ------- C : numpy array of shape [n_samples, n_outputs] Predicted values. """ raw_p...
[ "def", "predict", "(", "self", ",", "X", ")", ":", "raw_predictions", "=", "self", ".", "decision_function", "(", "X", ")", "class_predictions", "=", "self", ".", "binarizer", ".", "inverse_transform", "(", "raw_predictions", ")", "return", "class_predictions" ]
Predict values using the model Parameters ---------- X : {array-like, sparse matrix} of shape [n_samples, n_features] Returns ------- C : numpy array of shape [n_samples, n_outputs] Predicted values.
[ "Predict", "values", "using", "the", "model" ]
329f3efdb8c3c3a367b264f7c76c76411a784530
https://github.com/wdm0006/sklearn-extensions/blob/329f3efdb8c3c3a367b264f7c76c76411a784530/sklearn_extensions/extreme_learning_machines/elm.py#L326-L341
train
wdm0006/sklearn-extensions
sklearn_extensions/extreme_learning_machines/elm.py
ELMRegressor._create_random_layer
def _create_random_layer(self): """Pass init params to RandomLayer""" return RandomLayer(n_hidden=self.n_hidden, alpha=self.alpha, random_state=self.random_state, activation_func=self.activation_func, ...
python
def _create_random_layer(self): """Pass init params to RandomLayer""" return RandomLayer(n_hidden=self.n_hidden, alpha=self.alpha, random_state=self.random_state, activation_func=self.activation_func, ...
[ "def", "_create_random_layer", "(", "self", ")", ":", "return", "RandomLayer", "(", "n_hidden", "=", "self", ".", "n_hidden", ",", "alpha", "=", "self", ".", "alpha", ",", "random_state", "=", "self", ".", "random_state", ",", "activation_func", "=", "self",...
Pass init params to RandomLayer
[ "Pass", "init", "params", "to", "RandomLayer" ]
329f3efdb8c3c3a367b264f7c76c76411a784530
https://github.com/wdm0006/sklearn-extensions/blob/329f3efdb8c3c3a367b264f7c76c76411a784530/sklearn_extensions/extreme_learning_machines/elm.py#L430-L439
train
wdm0006/sklearn-extensions
sklearn_extensions/extreme_learning_machines/elm.py
ELMRegressor.fit
def fit(self, X, y): """ Fit the model using X, y as training data. Parameters ---------- X : {array-like, sparse matrix} of shape [n_samples, n_features] Training vectors, where n_samples is the number of samples and n_features is the number of features....
python
def fit(self, X, y): """ Fit the model using X, y as training data. Parameters ---------- X : {array-like, sparse matrix} of shape [n_samples, n_features] Training vectors, where n_samples is the number of samples and n_features is the number of features....
[ "def", "fit", "(", "self", ",", "X", ",", "y", ")", ":", "rhl", "=", "self", ".", "_create_random_layer", "(", ")", "self", ".", "_genelm_regressor", "=", "GenELMRegressor", "(", "hidden_layer", "=", "rhl", ",", "regressor", "=", "self", ".", "regressor"...
Fit the model using X, y as training data. Parameters ---------- X : {array-like, sparse matrix} of shape [n_samples, n_features] Training vectors, where n_samples is the number of samples and n_features is the number of features. y : array-like of shape [n_samp...
[ "Fit", "the", "model", "using", "X", "y", "as", "training", "data", "." ]
329f3efdb8c3c3a367b264f7c76c76411a784530
https://github.com/wdm0006/sklearn-extensions/blob/329f3efdb8c3c3a367b264f7c76c76411a784530/sklearn_extensions/extreme_learning_machines/elm.py#L441-L465
train
wdm0006/sklearn-extensions
sklearn_extensions/extreme_learning_machines/elm.py
ELMRegressor.predict
def predict(self, X): """ Predict values using the model Parameters ---------- X : {array-like, sparse matrix} of shape [n_samples, n_features] Returns ------- C : numpy array of shape [n_samples, n_outputs] Predicted values. """ ...
python
def predict(self, X): """ Predict values using the model Parameters ---------- X : {array-like, sparse matrix} of shape [n_samples, n_features] Returns ------- C : numpy array of shape [n_samples, n_outputs] Predicted values. """ ...
[ "def", "predict", "(", "self", ",", "X", ")", ":", "if", "self", ".", "_genelm_regressor", "is", "None", ":", "raise", "ValueError", "(", "\"SimpleELMRegressor not fitted\"", ")", "return", "self", ".", "_genelm_regressor", ".", "predict", "(", "X", ")" ]
Predict values using the model Parameters ---------- X : {array-like, sparse matrix} of shape [n_samples, n_features] Returns ------- C : numpy array of shape [n_samples, n_outputs] Predicted values.
[ "Predict", "values", "using", "the", "model" ]
329f3efdb8c3c3a367b264f7c76c76411a784530
https://github.com/wdm0006/sklearn-extensions/blob/329f3efdb8c3c3a367b264f7c76c76411a784530/sklearn_extensions/extreme_learning_machines/elm.py#L467-L483
train
wdm0006/sklearn-extensions
sklearn_extensions/extreme_learning_machines/elm.py
ELMClassifier.fit
def fit(self, X, y): """ Fit the model using X, y as training data. Parameters ---------- X : {array-like, sparse matrix} of shape [n_samples, n_features] Training vectors, where n_samples is the number of samples and n_features is the number of features....
python
def fit(self, X, y): """ Fit the model using X, y as training data. Parameters ---------- X : {array-like, sparse matrix} of shape [n_samples, n_features] Training vectors, where n_samples is the number of samples and n_features is the number of features....
[ "def", "fit", "(", "self", ",", "X", ",", "y", ")", ":", "self", ".", "classes_", "=", "np", ".", "unique", "(", "y", ")", "y_bin", "=", "self", ".", "binarizer", ".", "fit_transform", "(", "y", ")", "super", "(", "ELMClassifier", ",", "self", ")...
Fit the model using X, y as training data. Parameters ---------- X : {array-like, sparse matrix} of shape [n_samples, n_features] Training vectors, where n_samples is the number of samples and n_features is the number of features. y : array-like of shape [n_samp...
[ "Fit", "the", "model", "using", "X", "y", "as", "training", "data", "." ]
329f3efdb8c3c3a367b264f7c76c76411a784530
https://github.com/wdm0006/sklearn-extensions/blob/329f3efdb8c3c3a367b264f7c76c76411a784530/sklearn_extensions/extreme_learning_machines/elm.py#L572-L598
train
wdm0006/sklearn-extensions
sklearn_extensions/extreme_learning_machines/elm.py
ELMClassifier.score
def score(self, X, y): """Force use of accuracy score since we don't inherit from ClassifierMixin""" from sklearn.metrics import accuracy_score return accuracy_score(y, self.predict(X))
python
def score(self, X, y): """Force use of accuracy score since we don't inherit from ClassifierMixin""" from sklearn.metrics import accuracy_score return accuracy_score(y, self.predict(X))
[ "def", "score", "(", "self", ",", "X", ",", "y", ")", ":", "from", "sklearn", ".", "metrics", "import", "accuracy_score", "return", "accuracy_score", "(", "y", ",", "self", ".", "predict", "(", "X", ")", ")" ]
Force use of accuracy score since we don't inherit from ClassifierMixin
[ "Force", "use", "of", "accuracy", "score", "since", "we", "don", "t", "inherit", "from", "ClassifierMixin" ]
329f3efdb8c3c3a367b264f7c76c76411a784530
https://github.com/wdm0006/sklearn-extensions/blob/329f3efdb8c3c3a367b264f7c76c76411a784530/sklearn_extensions/extreme_learning_machines/elm.py#L618-L623
train
raphaelgyory/django-rest-messaging
rest_messaging/compat.py
compat_serializer_check_is_valid
def compat_serializer_check_is_valid(serializer): """ http://www.django-rest-framework.org/topics/3.0-announcement/#using-is_validraise_exceptiontrue """ if DRFVLIST[0] >= 3: serializer.is_valid(raise_exception=True) else: if not serializer.is_valid(): serializers.ValidationError...
python
def compat_serializer_check_is_valid(serializer): """ http://www.django-rest-framework.org/topics/3.0-announcement/#using-is_validraise_exceptiontrue """ if DRFVLIST[0] >= 3: serializer.is_valid(raise_exception=True) else: if not serializer.is_valid(): serializers.ValidationError...
[ "def", "compat_serializer_check_is_valid", "(", "serializer", ")", ":", "if", "DRFVLIST", "[", "0", "]", ">=", "3", ":", "serializer", ".", "is_valid", "(", "raise_exception", "=", "True", ")", "else", ":", "if", "not", "serializer", ".", "is_valid", "(", ...
http://www.django-rest-framework.org/topics/3.0-announcement/#using-is_validraise_exceptiontrue
[ "http", ":", "//", "www", ".", "django", "-", "rest", "-", "framework", ".", "org", "/", "topics", "/", "3", ".", "0", "-", "announcement", "/", "#using", "-", "is_validraise_exceptiontrue" ]
c9d5405fed7db2d79ec5c93c721a8fe42ea86958
https://github.com/raphaelgyory/django-rest-messaging/blob/c9d5405fed7db2d79ec5c93c721a8fe42ea86958/rest_messaging/compat.py#L23-L29
train
raphaelgyory/django-rest-messaging
rest_messaging/compat.py
compat_serializer_attr
def compat_serializer_attr(serializer, obj): """ Required only for DRF 3.1, which does not make dynamically added attribute available in obj in serializer. This is a quick solution but works without breajing anything. """ if DRFVLIST[0] == 3 and DRFVLIST[1] == 1: for i in serializer.instance...
python
def compat_serializer_attr(serializer, obj): """ Required only for DRF 3.1, which does not make dynamically added attribute available in obj in serializer. This is a quick solution but works without breajing anything. """ if DRFVLIST[0] == 3 and DRFVLIST[1] == 1: for i in serializer.instance...
[ "def", "compat_serializer_attr", "(", "serializer", ",", "obj", ")", ":", "if", "DRFVLIST", "[", "0", "]", "==", "3", "and", "DRFVLIST", "[", "1", "]", "==", "1", ":", "for", "i", "in", "serializer", ".", "instance", ":", "if", "i", ".", "id", "=="...
Required only for DRF 3.1, which does not make dynamically added attribute available in obj in serializer. This is a quick solution but works without breajing anything.
[ "Required", "only", "for", "DRF", "3", ".", "1", "which", "does", "not", "make", "dynamically", "added", "attribute", "available", "in", "obj", "in", "serializer", ".", "This", "is", "a", "quick", "solution", "but", "works", "without", "breajing", "anything"...
c9d5405fed7db2d79ec5c93c721a8fe42ea86958
https://github.com/raphaelgyory/django-rest-messaging/blob/c9d5405fed7db2d79ec5c93c721a8fe42ea86958/rest_messaging/compat.py#L40-L50
train
raphaelgyory/django-rest-messaging
rest_messaging/compat.py
compat_get_paginated_response
def compat_get_paginated_response(view, page): """ get_paginated_response is unknown to DRF 3.0 """ if DRFVLIST[0] == 3 and DRFVLIST[1] >= 1: from rest_messaging.serializers import ComplexMessageSerializer # circular import serializer = ComplexMessageSerializer(page, many=True) return v...
python
def compat_get_paginated_response(view, page): """ get_paginated_response is unknown to DRF 3.0 """ if DRFVLIST[0] == 3 and DRFVLIST[1] >= 1: from rest_messaging.serializers import ComplexMessageSerializer # circular import serializer = ComplexMessageSerializer(page, many=True) return v...
[ "def", "compat_get_paginated_response", "(", "view", ",", "page", ")", ":", "if", "DRFVLIST", "[", "0", "]", "==", "3", "and", "DRFVLIST", "[", "1", "]", ">=", "1", ":", "from", "rest_messaging", ".", "serializers", "import", "ComplexMessageSerializer", "# c...
get_paginated_response is unknown to DRF 3.0
[ "get_paginated_response", "is", "unknown", "to", "DRF", "3", ".", "0" ]
c9d5405fed7db2d79ec5c93c721a8fe42ea86958
https://github.com/raphaelgyory/django-rest-messaging/blob/c9d5405fed7db2d79ec5c93c721a8fe42ea86958/rest_messaging/compat.py#L67-L75
train
raphaelgyory/django-rest-messaging
rest_messaging/compat.py
compat_pagination_messages
def compat_pagination_messages(cls): """ For DRF 3.1 and higher, pagination is defined at the paginator level (see http://www.django-rest-framework.org/topics/3.2-announcement/). For DRF 3.0 and lower, it can be handled at the view level. """ if DRFVLIST[0] == 3 and DRFVLIST[1] >= 1: setattr...
python
def compat_pagination_messages(cls): """ For DRF 3.1 and higher, pagination is defined at the paginator level (see http://www.django-rest-framework.org/topics/3.2-announcement/). For DRF 3.0 and lower, it can be handled at the view level. """ if DRFVLIST[0] == 3 and DRFVLIST[1] >= 1: setattr...
[ "def", "compat_pagination_messages", "(", "cls", ")", ":", "if", "DRFVLIST", "[", "0", "]", "==", "3", "and", "DRFVLIST", "[", "1", "]", ">=", "1", ":", "setattr", "(", "cls", ",", "\"pagination_class\"", ",", "MessagePagination", ")", "return", "cls", "...
For DRF 3.1 and higher, pagination is defined at the paginator level (see http://www.django-rest-framework.org/topics/3.2-announcement/). For DRF 3.0 and lower, it can be handled at the view level.
[ "For", "DRF", "3", ".", "1", "and", "higher", "pagination", "is", "defined", "at", "the", "paginator", "level", "(", "see", "http", ":", "//", "www", ".", "django", "-", "rest", "-", "framework", ".", "org", "/", "topics", "/", "3", ".", "2", "-", ...
c9d5405fed7db2d79ec5c93c721a8fe42ea86958
https://github.com/raphaelgyory/django-rest-messaging/blob/c9d5405fed7db2d79ec5c93c721a8fe42ea86958/rest_messaging/compat.py#L78-L89
train
raphaelgyory/django-rest-messaging
rest_messaging/serializers.py
ThreadSerializer.get_participants
def get_participants(self, obj): """ Allows to define a callback for serializing information about the user. """ # we set the many to many serialization to False, because we only want it with retrieve requests if self.callback is None: return [participant.id for participant in obj.pa...
python
def get_participants(self, obj): """ Allows to define a callback for serializing information about the user. """ # we set the many to many serialization to False, because we only want it with retrieve requests if self.callback is None: return [participant.id for participant in obj.pa...
[ "def", "get_participants", "(", "self", ",", "obj", ")", ":", "# we set the many to many serialization to False, because we only want it with retrieve requests", "if", "self", ".", "callback", "is", "None", ":", "return", "[", "participant", ".", "id", "for", "participant...
Allows to define a callback for serializing information about the user.
[ "Allows", "to", "define", "a", "callback", "for", "serializing", "information", "about", "the", "user", "." ]
c9d5405fed7db2d79ec5c93c721a8fe42ea86958
https://github.com/raphaelgyory/django-rest-messaging/blob/c9d5405fed7db2d79ec5c93c721a8fe42ea86958/rest_messaging/serializers.py#L26-L33
train
raphaelgyory/django-rest-messaging
rest_messaging/serializers.py
ComplexMessageSerializer.get_is_notification
def get_is_notification(self, obj): """ We say if the message should trigger a notification """ try: o = compat_serializer_attr(self, obj) return o.is_notification except Exception: return False
python
def get_is_notification(self, obj): """ We say if the message should trigger a notification """ try: o = compat_serializer_attr(self, obj) return o.is_notification except Exception: return False
[ "def", "get_is_notification", "(", "self", ",", "obj", ")", ":", "try", ":", "o", "=", "compat_serializer_attr", "(", "self", ",", "obj", ")", "return", "o", ".", "is_notification", "except", "Exception", ":", "return", "False" ]
We say if the message should trigger a notification
[ "We", "say", "if", "the", "message", "should", "trigger", "a", "notification" ]
c9d5405fed7db2d79ec5c93c721a8fe42ea86958
https://github.com/raphaelgyory/django-rest-messaging/blob/c9d5405fed7db2d79ec5c93c721a8fe42ea86958/rest_messaging/serializers.py#L57-L63
train
raphaelgyory/django-rest-messaging
rest_messaging/serializers.py
ComplexMessageSerializer.get_readers
def get_readers(self, obj): """ Return the ids of the people who read the message instance. """ try: o = compat_serializer_attr(self, obj) return o.readers except Exception: return []
python
def get_readers(self, obj): """ Return the ids of the people who read the message instance. """ try: o = compat_serializer_attr(self, obj) return o.readers except Exception: return []
[ "def", "get_readers", "(", "self", ",", "obj", ")", ":", "try", ":", "o", "=", "compat_serializer_attr", "(", "self", ",", "obj", ")", "return", "o", ".", "readers", "except", "Exception", ":", "return", "[", "]" ]
Return the ids of the people who read the message instance.
[ "Return", "the", "ids", "of", "the", "people", "who", "read", "the", "message", "instance", "." ]
c9d5405fed7db2d79ec5c93c721a8fe42ea86958
https://github.com/raphaelgyory/django-rest-messaging/blob/c9d5405fed7db2d79ec5c93c721a8fe42ea86958/rest_messaging/serializers.py#L65-L71
train
raphaelgyory/django-rest-messaging
rest_messaging/models.py
ThreadManager.get_threads_where_participant_is_active
def get_threads_where_participant_is_active(self, participant_id): """ Gets all the threads in which the current participant is involved. The method excludes threads where the participant has left. """ participations = Participation.objects.\ filter(participant__id=participant_id).\ ...
python
def get_threads_where_participant_is_active(self, participant_id): """ Gets all the threads in which the current participant is involved. The method excludes threads where the participant has left. """ participations = Participation.objects.\ filter(participant__id=participant_id).\ ...
[ "def", "get_threads_where_participant_is_active", "(", "self", ",", "participant_id", ")", ":", "participations", "=", "Participation", ".", "objects", ".", "filter", "(", "participant__id", "=", "participant_id", ")", ".", "exclude", "(", "date_left__lte", "=", "no...
Gets all the threads in which the current participant is involved. The method excludes threads where the participant has left.
[ "Gets", "all", "the", "threads", "in", "which", "the", "current", "participant", "is", "involved", ".", "The", "method", "excludes", "threads", "where", "the", "participant", "has", "left", "." ]
c9d5405fed7db2d79ec5c93c721a8fe42ea86958
https://github.com/raphaelgyory/django-rest-messaging/blob/c9d5405fed7db2d79ec5c93c721a8fe42ea86958/rest_messaging/models.py#L34-L44
train
raphaelgyory/django-rest-messaging
rest_messaging/models.py
ThreadManager.get_active_threads_involving_all_participants
def get_active_threads_involving_all_participants(self, *participant_ids): """ Gets the threads where the specified participants are active and no one has left. """ query = Thread.objects.\ exclude(participation__date_left__lte=now()).\ annotate(count_participants=Count('partici...
python
def get_active_threads_involving_all_participants(self, *participant_ids): """ Gets the threads where the specified participants are active and no one has left. """ query = Thread.objects.\ exclude(participation__date_left__lte=now()).\ annotate(count_participants=Count('partici...
[ "def", "get_active_threads_involving_all_participants", "(", "self", ",", "*", "participant_ids", ")", ":", "query", "=", "Thread", ".", "objects", ".", "exclude", "(", "participation__date_left__lte", "=", "now", "(", ")", ")", ".", "annotate", "(", "count_partic...
Gets the threads where the specified participants are active and no one has left.
[ "Gets", "the", "threads", "where", "the", "specified", "participants", "are", "active", "and", "no", "one", "has", "left", "." ]
c9d5405fed7db2d79ec5c93c721a8fe42ea86958
https://github.com/raphaelgyory/django-rest-messaging/blob/c9d5405fed7db2d79ec5c93c721a8fe42ea86958/rest_messaging/models.py#L46-L57
train
raphaelgyory/django-rest-messaging
rest_messaging/models.py
ThreadManager.get_or_create_thread
def get_or_create_thread(self, request, name=None, *participant_ids): """ When a Participant posts a message to other participants without specifying an existing Thread, we must 1. Create a new Thread if they have not yet opened the discussion. 2. If they have already opened the ...
python
def get_or_create_thread(self, request, name=None, *participant_ids): """ When a Participant posts a message to other participants without specifying an existing Thread, we must 1. Create a new Thread if they have not yet opened the discussion. 2. If they have already opened the ...
[ "def", "get_or_create_thread", "(", "self", ",", "request", ",", "name", "=", "None", ",", "*", "participant_ids", ")", ":", "# we get the current participant", "# or create him if he does not exit", "participant_ids", "=", "list", "(", "participant_ids", ")", "if", "...
When a Participant posts a message to other participants without specifying an existing Thread, we must 1. Create a new Thread if they have not yet opened the discussion. 2. If they have already opened the discussion and multiple Threads are not allowed for the same users, we must re...
[ "When", "a", "Participant", "posts", "a", "message", "to", "other", "participants", "without", "specifying", "an", "existing", "Thread", "we", "must", "1", ".", "Create", "a", "new", "Thread", "if", "they", "have", "not", "yet", "opened", "the", "discussion"...
c9d5405fed7db2d79ec5c93c721a8fe42ea86958
https://github.com/raphaelgyory/django-rest-messaging/blob/c9d5405fed7db2d79ec5c93c721a8fe42ea86958/rest_messaging/models.py#L59-L96
train
raphaelgyory/django-rest-messaging
rest_messaging/models.py
MessageManager.return_daily_messages_count
def return_daily_messages_count(self, sender): """ Returns the number of messages sent in the last 24 hours so we can ensure the user does not exceed his messaging limits """ h24 = now() - timedelta(days=1) return Message.objects.filter(sender=sender, sent_at__gte=h24).count()
python
def return_daily_messages_count(self, sender): """ Returns the number of messages sent in the last 24 hours so we can ensure the user does not exceed his messaging limits """ h24 = now() - timedelta(days=1) return Message.objects.filter(sender=sender, sent_at__gte=h24).count()
[ "def", "return_daily_messages_count", "(", "self", ",", "sender", ")", ":", "h24", "=", "now", "(", ")", "-", "timedelta", "(", "days", "=", "1", ")", "return", "Message", ".", "objects", ".", "filter", "(", "sender", "=", "sender", ",", "sent_at__gte", ...
Returns the number of messages sent in the last 24 hours so we can ensure the user does not exceed his messaging limits
[ "Returns", "the", "number", "of", "messages", "sent", "in", "the", "last", "24", "hours", "so", "we", "can", "ensure", "the", "user", "does", "not", "exceed", "his", "messaging", "limits" ]
c9d5405fed7db2d79ec5c93c721a8fe42ea86958
https://github.com/raphaelgyory/django-rest-messaging/blob/c9d5405fed7db2d79ec5c93c721a8fe42ea86958/rest_messaging/models.py#L191-L194
train
raphaelgyory/django-rest-messaging
rest_messaging/models.py
MessageManager.check_who_read
def check_who_read(self, messages): """ Check who read each message. """ # we get the corresponding Participation objects for m in messages: readers = [] for p in m.thread.participation_set.all(): if p.date_last_check is None: pass ...
python
def check_who_read(self, messages): """ Check who read each message. """ # we get the corresponding Participation objects for m in messages: readers = [] for p in m.thread.participation_set.all(): if p.date_last_check is None: pass ...
[ "def", "check_who_read", "(", "self", ",", "messages", ")", ":", "# we get the corresponding Participation objects", "for", "m", "in", "messages", ":", "readers", "=", "[", "]", "for", "p", "in", "m", ".", "thread", ".", "participation_set", ".", "all", "(", ...
Check who read each message.
[ "Check", "who", "read", "each", "message", "." ]
c9d5405fed7db2d79ec5c93c721a8fe42ea86958
https://github.com/raphaelgyory/django-rest-messaging/blob/c9d5405fed7db2d79ec5c93c721a8fe42ea86958/rest_messaging/models.py#L196-L209
train
raphaelgyory/django-rest-messaging
rest_messaging/models.py
MessageManager.check_is_notification
def check_is_notification(self, participant_id, messages): """ Check if each message requires a notification for the specified participant. """ try: # we get the last check last_check = NotificationCheck.objects.filter(participant__id=participant_id).latest('id').date_check ...
python
def check_is_notification(self, participant_id, messages): """ Check if each message requires a notification for the specified participant. """ try: # we get the last check last_check = NotificationCheck.objects.filter(participant__id=participant_id).latest('id').date_check ...
[ "def", "check_is_notification", "(", "self", ",", "participant_id", ",", "messages", ")", ":", "try", ":", "# we get the last check", "last_check", "=", "NotificationCheck", ".", "objects", ".", "filter", "(", "participant__id", "=", "participant_id", ")", ".", "l...
Check if each message requires a notification for the specified participant.
[ "Check", "if", "each", "message", "requires", "a", "notification", "for", "the", "specified", "participant", "." ]
c9d5405fed7db2d79ec5c93c721a8fe42ea86958
https://github.com/raphaelgyory/django-rest-messaging/blob/c9d5405fed7db2d79ec5c93c721a8fe42ea86958/rest_messaging/models.py#L211-L228
train
raphaelgyory/django-rest-messaging
rest_messaging/models.py
MessageManager.get_lasts_messages_of_threads
def get_lasts_messages_of_threads(self, participant_id, check_who_read=True, check_is_notification=True): """ Returns the last message in each thread """ # we get the last message for each thread # we must query the messages using two queries because only Postgres supports .order_by('thread', '-...
python
def get_lasts_messages_of_threads(self, participant_id, check_who_read=True, check_is_notification=True): """ Returns the last message in each thread """ # we get the last message for each thread # we must query the messages using two queries because only Postgres supports .order_by('thread', '-...
[ "def", "get_lasts_messages_of_threads", "(", "self", ",", "participant_id", ",", "check_who_read", "=", "True", ",", "check_is_notification", "=", "True", ")", ":", "# we get the last message for each thread", "# we must query the messages using two queries because only Postgres su...
Returns the last message in each thread
[ "Returns", "the", "last", "message", "in", "each", "thread" ]
c9d5405fed7db2d79ec5c93c721a8fe42ea86958
https://github.com/raphaelgyory/django-rest-messaging/blob/c9d5405fed7db2d79ec5c93c721a8fe42ea86958/rest_messaging/models.py#L230-L250
train
raphaelgyory/django-rest-messaging
rest_messaging/models.py
MessageManager.get_all_messages_in_thread
def get_all_messages_in_thread(self, participant_id, thread_id, check_who_read=True): """ Returns all the messages in a thread. """ try: messages = Message.objects.filter(thread__id=thread_id).\ order_by('-id').\ select_related('thread').\ pref...
python
def get_all_messages_in_thread(self, participant_id, thread_id, check_who_read=True): """ Returns all the messages in a thread. """ try: messages = Message.objects.filter(thread__id=thread_id).\ order_by('-id').\ select_related('thread').\ pref...
[ "def", "get_all_messages_in_thread", "(", "self", ",", "participant_id", ",", "thread_id", ",", "check_who_read", "=", "True", ")", ":", "try", ":", "messages", "=", "Message", ".", "objects", ".", "filter", "(", "thread__id", "=", "thread_id", ")", ".", "or...
Returns all the messages in a thread.
[ "Returns", "all", "the", "messages", "in", "a", "thread", "." ]
c9d5405fed7db2d79ec5c93c721a8fe42ea86958
https://github.com/raphaelgyory/django-rest-messaging/blob/c9d5405fed7db2d79ec5c93c721a8fe42ea86958/rest_messaging/models.py#L252-L263
train
raphaelgyory/django-rest-messaging
rest_messaging/views.py
ThreadView.create
def create(self, request, *args, **kwargs): """ We ensure the Thread only involves eligible participants. """ serializer = self.get_serializer(data=compat_get_request_data(request)) compat_serializer_check_is_valid(serializer) self.perform_create(request, serializer) headers = se...
python
def create(self, request, *args, **kwargs): """ We ensure the Thread only involves eligible participants. """ serializer = self.get_serializer(data=compat_get_request_data(request)) compat_serializer_check_is_valid(serializer) self.perform_create(request, serializer) headers = se...
[ "def", "create", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "serializer", "=", "self", ".", "get_serializer", "(", "data", "=", "compat_get_request_data", "(", "request", ")", ")", "compat_serializer_check_is_valid", "(...
We ensure the Thread only involves eligible participants.
[ "We", "ensure", "the", "Thread", "only", "involves", "eligible", "participants", "." ]
c9d5405fed7db2d79ec5c93c721a8fe42ea86958
https://github.com/raphaelgyory/django-rest-messaging/blob/c9d5405fed7db2d79ec5c93c721a8fe42ea86958/rest_messaging/views.py#L36-L42
train
raphaelgyory/django-rest-messaging
rest_messaging/views.py
ThreadView.mark_thread_as_read
def mark_thread_as_read(self, request, pk=None): """ Pk is the pk of the Thread to which the messages belong. """ # we get the thread and check for permission thread = Thread.objects.get(id=pk) self.check_object_permissions(request, thread) # we save the date try: ...
python
def mark_thread_as_read(self, request, pk=None): """ Pk is the pk of the Thread to which the messages belong. """ # we get the thread and check for permission thread = Thread.objects.get(id=pk) self.check_object_permissions(request, thread) # we save the date try: ...
[ "def", "mark_thread_as_read", "(", "self", ",", "request", ",", "pk", "=", "None", ")", ":", "# we get the thread and check for permission", "thread", "=", "Thread", ".", "objects", ".", "get", "(", "id", "=", "pk", ")", "self", ".", "check_object_permissions", ...
Pk is the pk of the Thread to which the messages belong.
[ "Pk", "is", "the", "pk", "of", "the", "Thread", "to", "which", "the", "messages", "belong", "." ]
c9d5405fed7db2d79ec5c93c721a8fe42ea86958
https://github.com/raphaelgyory/django-rest-messaging/blob/c9d5405fed7db2d79ec5c93c721a8fe42ea86958/rest_messaging/views.py#L107-L121
train
letuananh/chirptext
chirptext/chirpnet.py
SmartURL.process
def process(self, quoted=False): ''' Parse an URL ''' self.p = urlparse(self.raw) self.scheme = self.p.scheme self.netloc = self.p.netloc self.opath = self.p.path if not quoted else quote(self.p.path) self.path = [x for x in self.opath.split('/') if x] self.params...
python
def process(self, quoted=False): ''' Parse an URL ''' self.p = urlparse(self.raw) self.scheme = self.p.scheme self.netloc = self.p.netloc self.opath = self.p.path if not quoted else quote(self.p.path) self.path = [x for x in self.opath.split('/') if x] self.params...
[ "def", "process", "(", "self", ",", "quoted", "=", "False", ")", ":", "self", ".", "p", "=", "urlparse", "(", "self", ".", "raw", ")", "self", ".", "scheme", "=", "self", ".", "p", ".", "scheme", "self", ".", "netloc", "=", "self", ".", "p", "....
Parse an URL
[ "Parse", "an", "URL" ]
ce60b47257b272a587c8703ea1f86cd1a45553a7
https://github.com/letuananh/chirptext/blob/ce60b47257b272a587c8703ea1f86cd1a45553a7/chirptext/chirpnet.py#L61-L70
train
letuananh/chirptext
chirptext/chirpnet.py
WebHelper.fetch
def fetch(self, url, encoding=None, force_refetch=False, nocache=False, quiet=True): ''' Fetch a HTML file as binary''' try: if not force_refetch and self.cache is not None and url in self.cache: # try to look for content in cache logging.debug('Retrieving con...
python
def fetch(self, url, encoding=None, force_refetch=False, nocache=False, quiet=True): ''' Fetch a HTML file as binary''' try: if not force_refetch and self.cache is not None and url in self.cache: # try to look for content in cache logging.debug('Retrieving con...
[ "def", "fetch", "(", "self", ",", "url", ",", "encoding", "=", "None", ",", "force_refetch", "=", "False", ",", "nocache", "=", "False", ",", "quiet", "=", "True", ")", ":", "try", ":", "if", "not", "force_refetch", "and", "self", ".", "cache", "is",...
Fetch a HTML file as binary
[ "Fetch", "a", "HTML", "file", "as", "binary" ]
ce60b47257b272a587c8703ea1f86cd1a45553a7
https://github.com/letuananh/chirptext/blob/ce60b47257b272a587c8703ea1f86cd1a45553a7/chirptext/chirpnet.py#L90-L125
train
letuananh/chirptext
chirptext/chirpnet.py
WebHelper.download
def download(self, url, path, force_refetch=False, nocache=False): ''' Download a file at $url and save it to $path ''' # Enable cache if os.path.isfile(path): getLogger().info("File exists, download task skipped -> {path}".format(path=path)) return True t...
python
def download(self, url, path, force_refetch=False, nocache=False): ''' Download a file at $url and save it to $path ''' # Enable cache if os.path.isfile(path): getLogger().info("File exists, download task skipped -> {path}".format(path=path)) return True t...
[ "def", "download", "(", "self", ",", "url", ",", "path", ",", "force_refetch", "=", "False", ",", "nocache", "=", "False", ")", ":", "# Enable cache", "if", "os", ".", "path", ".", "isfile", "(", "path", ")", ":", "getLogger", "(", ")", ".", "info", ...
Download a file at $url and save it to $path
[ "Download", "a", "file", "at", "$url", "and", "save", "it", "to", "$path" ]
ce60b47257b272a587c8703ea1f86cd1a45553a7
https://github.com/letuananh/chirptext/blob/ce60b47257b272a587c8703ea1f86cd1a45553a7/chirptext/chirpnet.py#L134-L162
train
cgtobi/PyRMVtransport
RMVtransport/rmvjourney.py
RMVJourney._platform
def _platform(self) -> Optional[str]: """Extract platform.""" try: return str(self.journey.MainStop.BasicStop.Dep.Platform.text) except AttributeError: return None
python
def _platform(self) -> Optional[str]: """Extract platform.""" try: return str(self.journey.MainStop.BasicStop.Dep.Platform.text) except AttributeError: return None
[ "def", "_platform", "(", "self", ")", "->", "Optional", "[", "str", "]", ":", "try", ":", "return", "str", "(", "self", ".", "journey", ".", "MainStop", ".", "BasicStop", ".", "Dep", ".", "Platform", ".", "text", ")", "except", "AttributeError", ":", ...
Extract platform.
[ "Extract", "platform", "." ]
20a0d68ecfdedceb32e8ca96c381fdec7e2069c7
https://github.com/cgtobi/PyRMVtransport/blob/20a0d68ecfdedceb32e8ca96c381fdec7e2069c7/RMVtransport/rmvjourney.py#L35-L40
train
cgtobi/PyRMVtransport
RMVtransport/rmvjourney.py
RMVJourney._delay
def _delay(self) -> int: """Extract departure delay.""" try: return int(self.journey.MainStop.BasicStop.Dep.Delay.text) except AttributeError: return 0
python
def _delay(self) -> int: """Extract departure delay.""" try: return int(self.journey.MainStop.BasicStop.Dep.Delay.text) except AttributeError: return 0
[ "def", "_delay", "(", "self", ")", "->", "int", ":", "try", ":", "return", "int", "(", "self", ".", "journey", ".", "MainStop", ".", "BasicStop", ".", "Dep", ".", "Delay", ".", "text", ")", "except", "AttributeError", ":", "return", "0" ]
Extract departure delay.
[ "Extract", "departure", "delay", "." ]
20a0d68ecfdedceb32e8ca96c381fdec7e2069c7
https://github.com/cgtobi/PyRMVtransport/blob/20a0d68ecfdedceb32e8ca96c381fdec7e2069c7/RMVtransport/rmvjourney.py#L42-L47
train
cgtobi/PyRMVtransport
RMVtransport/rmvjourney.py
RMVJourney._departure
def _departure(self) -> datetime: """Extract departure time.""" departure_time = datetime.strptime( self.journey.MainStop.BasicStop.Dep.Time.text, "%H:%M" ).time() if departure_time > (self.now - timedelta(hours=1)).time(): return datetime.combine(self.now.date(),...
python
def _departure(self) -> datetime: """Extract departure time.""" departure_time = datetime.strptime( self.journey.MainStop.BasicStop.Dep.Time.text, "%H:%M" ).time() if departure_time > (self.now - timedelta(hours=1)).time(): return datetime.combine(self.now.date(),...
[ "def", "_departure", "(", "self", ")", "->", "datetime", ":", "departure_time", "=", "datetime", ".", "strptime", "(", "self", ".", "journey", ".", "MainStop", ".", "BasicStop", ".", "Dep", ".", "Time", ".", "text", ",", "\"%H:%M\"", ")", ".", "time", ...
Extract departure time.
[ "Extract", "departure", "time", "." ]
20a0d68ecfdedceb32e8ca96c381fdec7e2069c7
https://github.com/cgtobi/PyRMVtransport/blob/20a0d68ecfdedceb32e8ca96c381fdec7e2069c7/RMVtransport/rmvjourney.py#L49-L56
train
cgtobi/PyRMVtransport
RMVtransport/rmvjourney.py
RMVJourney._extract
def _extract(self, attribute) -> str: """Extract train information.""" attr_data = self.journey.JourneyAttributeList.JourneyAttribute[ self.attr_types.index(attribute) ].Attribute attr_variants = attr_data.xpath("AttributeVariant/@type") data = attr_data.AttributeVari...
python
def _extract(self, attribute) -> str: """Extract train information.""" attr_data = self.journey.JourneyAttributeList.JourneyAttribute[ self.attr_types.index(attribute) ].Attribute attr_variants = attr_data.xpath("AttributeVariant/@type") data = attr_data.AttributeVari...
[ "def", "_extract", "(", "self", ",", "attribute", ")", "->", "str", ":", "attr_data", "=", "self", ".", "journey", ".", "JourneyAttributeList", ".", "JourneyAttribute", "[", "self", ".", "attr_types", ".", "index", "(", "attribute", ")", "]", ".", "Attribu...
Extract train information.
[ "Extract", "train", "information", "." ]
20a0d68ecfdedceb32e8ca96c381fdec7e2069c7
https://github.com/cgtobi/PyRMVtransport/blob/20a0d68ecfdedceb32e8ca96c381fdec7e2069c7/RMVtransport/rmvjourney.py#L66-L73
train
cgtobi/PyRMVtransport
RMVtransport/rmvjourney.py
RMVJourney._info
def _info(self) -> Optional[str]: """Extract journey information.""" try: return str(html.unescape(self.journey.InfoTextList.InfoText.get("text"))) except AttributeError: return None
python
def _info(self) -> Optional[str]: """Extract journey information.""" try: return str(html.unescape(self.journey.InfoTextList.InfoText.get("text"))) except AttributeError: return None
[ "def", "_info", "(", "self", ")", "->", "Optional", "[", "str", "]", ":", "try", ":", "return", "str", "(", "html", ".", "unescape", "(", "self", ".", "journey", ".", "InfoTextList", ".", "InfoText", ".", "get", "(", "\"text\"", ")", ")", ")", "exc...
Extract journey information.
[ "Extract", "journey", "information", "." ]
20a0d68ecfdedceb32e8ca96c381fdec7e2069c7
https://github.com/cgtobi/PyRMVtransport/blob/20a0d68ecfdedceb32e8ca96c381fdec7e2069c7/RMVtransport/rmvjourney.py#L75-L80
train
cgtobi/PyRMVtransport
RMVtransport/rmvjourney.py
RMVJourney._info_long
def _info_long(self) -> Optional[str]: """Extract journey information.""" try: return str( html.unescape(self.journey.InfoTextList.InfoText.get("textL")).replace( "<br />", "\n" ) ) except AttributeError: ret...
python
def _info_long(self) -> Optional[str]: """Extract journey information.""" try: return str( html.unescape(self.journey.InfoTextList.InfoText.get("textL")).replace( "<br />", "\n" ) ) except AttributeError: ret...
[ "def", "_info_long", "(", "self", ")", "->", "Optional", "[", "str", "]", ":", "try", ":", "return", "str", "(", "html", ".", "unescape", "(", "self", ".", "journey", ".", "InfoTextList", ".", "InfoText", ".", "get", "(", "\"textL\"", ")", ")", ".", ...
Extract journey information.
[ "Extract", "journey", "information", "." ]
20a0d68ecfdedceb32e8ca96c381fdec7e2069c7
https://github.com/cgtobi/PyRMVtransport/blob/20a0d68ecfdedceb32e8ca96c381fdec7e2069c7/RMVtransport/rmvjourney.py#L82-L91
train
cgtobi/PyRMVtransport
RMVtransport/rmvjourney.py
RMVJourney._pass_list
def _pass_list(self) -> List[Dict[str, Any]]: """Extract next stops along the journey.""" stops: List[Dict[str, Any]] = [] for stop in self.journey.PassList.BasicStop: index = stop.get("index") station = stop.Location.Station.HafasName.Text.text station_id = s...
python
def _pass_list(self) -> List[Dict[str, Any]]: """Extract next stops along the journey.""" stops: List[Dict[str, Any]] = [] for stop in self.journey.PassList.BasicStop: index = stop.get("index") station = stop.Location.Station.HafasName.Text.text station_id = s...
[ "def", "_pass_list", "(", "self", ")", "->", "List", "[", "Dict", "[", "str", ",", "Any", "]", "]", ":", "stops", ":", "List", "[", "Dict", "[", "str", ",", "Any", "]", "]", "=", "[", "]", "for", "stop", "in", "self", ".", "journey", ".", "Pa...
Extract next stops along the journey.
[ "Extract", "next", "stops", "along", "the", "journey", "." ]
20a0d68ecfdedceb32e8ca96c381fdec7e2069c7
https://github.com/cgtobi/PyRMVtransport/blob/20a0d68ecfdedceb32e8ca96c381fdec7e2069c7/RMVtransport/rmvjourney.py#L93-L101
train
pyout/pyout
pyout/elements.py
validate
def validate(style): """Check `style` against pyout.styling.schema. Parameters ---------- style : dict Style object to validate. Raises ------ StyleValidationError if `style` is not valid. """ try: import jsonschema except ImportError: return try: ...
python
def validate(style): """Check `style` against pyout.styling.schema. Parameters ---------- style : dict Style object to validate. Raises ------ StyleValidationError if `style` is not valid. """ try: import jsonschema except ImportError: return try: ...
[ "def", "validate", "(", "style", ")", ":", "try", ":", "import", "jsonschema", "except", "ImportError", ":", "return", "try", ":", "jsonschema", ".", "validate", "(", "style", ",", "schema", ")", "except", "jsonschema", ".", "ValidationError", "as", "exc", ...
Check `style` against pyout.styling.schema. Parameters ---------- style : dict Style object to validate. Raises ------ StyleValidationError if `style` is not valid.
[ "Check", "style", "against", "pyout", ".", "styling", ".", "schema", "." ]
d9ff954bdedb6fc70f21f4fe77ad4bf926b201b0
https://github.com/pyout/pyout/blob/d9ff954bdedb6fc70f21f4fe77ad4bf926b201b0/pyout/elements.py#L241-L265
train
pyout/pyout
pyout/elements.py
value_type
def value_type(value): """Classify `value` of bold, color, and underline keys. Parameters ---------- value : style value Returns ------- str, {"simple", "lookup", "re_lookup", "interval"} """ try: keys = list(value.keys()) except AttributeError: return "simple" ...
python
def value_type(value): """Classify `value` of bold, color, and underline keys. Parameters ---------- value : style value Returns ------- str, {"simple", "lookup", "re_lookup", "interval"} """ try: keys = list(value.keys()) except AttributeError: return "simple" ...
[ "def", "value_type", "(", "value", ")", ":", "try", ":", "keys", "=", "list", "(", "value", ".", "keys", "(", ")", ")", "except", "AttributeError", ":", "return", "\"simple\"", "if", "keys", "in", "[", "[", "\"lookup\"", "]", ",", "[", "\"re_lookup\"",...
Classify `value` of bold, color, and underline keys. Parameters ---------- value : style value Returns ------- str, {"simple", "lookup", "re_lookup", "interval"}
[ "Classify", "value", "of", "bold", "color", "and", "underline", "keys", "." ]
d9ff954bdedb6fc70f21f4fe77ad4bf926b201b0
https://github.com/pyout/pyout/blob/d9ff954bdedb6fc70f21f4fe77ad4bf926b201b0/pyout/elements.py#L268-L285
train
letuananh/chirptext
chirptext/dekomecab.py
_register_mecab_loc
def _register_mecab_loc(location): ''' Set MeCab binary location ''' global MECAB_LOC if not os.path.isfile(location): logging.getLogger(__name__).warning("Provided mecab binary location does not exist {}".format(location)) logging.getLogger(__name__).info("Mecab binary is switched to: {}"....
python
def _register_mecab_loc(location): ''' Set MeCab binary location ''' global MECAB_LOC if not os.path.isfile(location): logging.getLogger(__name__).warning("Provided mecab binary location does not exist {}".format(location)) logging.getLogger(__name__).info("Mecab binary is switched to: {}"....
[ "def", "_register_mecab_loc", "(", "location", ")", ":", "global", "MECAB_LOC", "if", "not", "os", ".", "path", ".", "isfile", "(", "location", ")", ":", "logging", ".", "getLogger", "(", "__name__", ")", ".", "warning", "(", "\"Provided mecab binary location ...
Set MeCab binary location
[ "Set", "MeCab", "binary", "location" ]
ce60b47257b272a587c8703ea1f86cd1a45553a7
https://github.com/letuananh/chirptext/blob/ce60b47257b272a587c8703ea1f86cd1a45553a7/chirptext/dekomecab.py#L43-L49
train
letuananh/chirptext
chirptext/dekomecab.py
run_mecab_process
def run_mecab_process(content, *args, **kwargs): ''' Use subprocess to run mecab ''' encoding = 'utf-8' if 'encoding' not in kwargs else kwargs['encoding'] mecab_loc = kwargs['mecab_loc'] if 'mecab_loc' in kwargs else None if mecab_loc is None: mecab_loc = MECAB_LOC proc_args = [mecab_...
python
def run_mecab_process(content, *args, **kwargs): ''' Use subprocess to run mecab ''' encoding = 'utf-8' if 'encoding' not in kwargs else kwargs['encoding'] mecab_loc = kwargs['mecab_loc'] if 'mecab_loc' in kwargs else None if mecab_loc is None: mecab_loc = MECAB_LOC proc_args = [mecab_...
[ "def", "run_mecab_process", "(", "content", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "encoding", "=", "'utf-8'", "if", "'encoding'", "not", "in", "kwargs", "else", "kwargs", "[", "'encoding'", "]", "mecab_loc", "=", "kwargs", "[", "'mecab_loc'"...
Use subprocess to run mecab
[ "Use", "subprocess", "to", "run", "mecab" ]
ce60b47257b272a587c8703ea1f86cd1a45553a7
https://github.com/letuananh/chirptext/blob/ce60b47257b272a587c8703ea1f86cd1a45553a7/chirptext/dekomecab.py#L57-L70
train
letuananh/chirptext
chirptext/dekomecab.py
parse
def parse(content, *args, **kwargs): ''' Use mecab-python3 by default to parse JP text. Fall back to mecab binary app if needed ''' global MECAB_PYTHON3 if 'mecab_loc' not in kwargs and MECAB_PYTHON3 and 'MeCab' in globals(): return MeCab.Tagger(*args).parse(content) else: return r...
python
def parse(content, *args, **kwargs): ''' Use mecab-python3 by default to parse JP text. Fall back to mecab binary app if needed ''' global MECAB_PYTHON3 if 'mecab_loc' not in kwargs and MECAB_PYTHON3 and 'MeCab' in globals(): return MeCab.Tagger(*args).parse(content) else: return r...
[ "def", "parse", "(", "content", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "global", "MECAB_PYTHON3", "if", "'mecab_loc'", "not", "in", "kwargs", "and", "MECAB_PYTHON3", "and", "'MeCab'", "in", "globals", "(", ")", ":", "return", "MeCab", ".", ...
Use mecab-python3 by default to parse JP text. Fall back to mecab binary app if needed
[ "Use", "mecab", "-", "python3", "by", "default", "to", "parse", "JP", "text", ".", "Fall", "back", "to", "mecab", "binary", "app", "if", "needed" ]
ce60b47257b272a587c8703ea1f86cd1a45553a7
https://github.com/letuananh/chirptext/blob/ce60b47257b272a587c8703ea1f86cd1a45553a7/chirptext/dekomecab.py#L73-L79
train
meng89/ipodshuffle
ipodshuffle/shuffle.py
Shuffle.create_track
def create_track(self, path_in_ipod=None, checksum=None): """ :param path_in_ipod: the path of audio file in the iPod base :param checksum: CHECKSUM of the audio file in member audiodb :return: a new Track, you may want append it to the playlist.tracks """ if bool(path_in...
python
def create_track(self, path_in_ipod=None, checksum=None): """ :param path_in_ipod: the path of audio file in the iPod base :param checksum: CHECKSUM of the audio file in member audiodb :return: a new Track, you may want append it to the playlist.tracks """ if bool(path_in...
[ "def", "create_track", "(", "self", ",", "path_in_ipod", "=", "None", ",", "checksum", "=", "None", ")", ":", "if", "bool", "(", "path_in_ipod", ")", "==", "bool", "(", "checksum", ")", ":", "raise", "Exception", "if", "not", "path_in_ipod", ":", "path_i...
:param path_in_ipod: the path of audio file in the iPod base :param checksum: CHECKSUM of the audio file in member audiodb :return: a new Track, you may want append it to the playlist.tracks
[ ":", "param", "path_in_ipod", ":", "the", "path", "of", "audio", "file", "in", "the", "iPod", "base", ":", "param", "checksum", ":", "CHECKSUM", "of", "the", "audio", "file", "in", "member", "audiodb", ":", "return", ":", "a", "new", "Track", "you", "m...
c9093dbb5cdac609376ebd3b4ef1b0fc58107d96
https://github.com/meng89/ipodshuffle/blob/c9093dbb5cdac609376ebd3b4ef1b0fc58107d96/ipodshuffle/shuffle.py#L180-L194
train
meng89/ipodshuffle
ipodshuffle/shuffle.py
_Voice.voice
def voice(self): """tuple. contain text and lang code """ dbid = self.lldb.dbid text, lang = self._voiceoverdb.get_text_lang(dbid) return text, lang
python
def voice(self): """tuple. contain text and lang code """ dbid = self.lldb.dbid text, lang = self._voiceoverdb.get_text_lang(dbid) return text, lang
[ "def", "voice", "(", "self", ")", ":", "dbid", "=", "self", ".", "lldb", ".", "dbid", "text", ",", "lang", "=", "self", ".", "_voiceoverdb", ".", "get_text_lang", "(", "dbid", ")", "return", "text", ",", "lang" ]
tuple. contain text and lang code
[ "tuple", ".", "contain", "text", "and", "lang", "code" ]
c9093dbb5cdac609376ebd3b4ef1b0fc58107d96
https://github.com/meng89/ipodshuffle/blob/c9093dbb5cdac609376ebd3b4ef1b0fc58107d96/ipodshuffle/shuffle.py#L229-L234
train
meng89/ipodshuffle
ipodshuffle/shuffle.py
AudioDB.add
def add(self, src): """ store an audio file to storage dir :param src: audio file path :return: checksum value """ if not audio.get_type(src): raise TypeError('The type of this file is not supported.') return super().add(src)
python
def add(self, src): """ store an audio file to storage dir :param src: audio file path :return: checksum value """ if not audio.get_type(src): raise TypeError('The type of this file is not supported.') return super().add(src)
[ "def", "add", "(", "self", ",", "src", ")", ":", "if", "not", "audio", ".", "get_type", "(", "src", ")", ":", "raise", "TypeError", "(", "'The type of this file is not supported.'", ")", "return", "super", "(", ")", ".", "add", "(", "src", ")" ]
store an audio file to storage dir :param src: audio file path :return: checksum value
[ "store", "an", "audio", "file", "to", "storage", "dir" ]
c9093dbb5cdac609376ebd3b4ef1b0fc58107d96
https://github.com/meng89/ipodshuffle/blob/c9093dbb5cdac609376ebd3b4ef1b0fc58107d96/ipodshuffle/shuffle.py#L390-L399
train
alefnula/tea
tea/process/posix_process.py
_get_cmd
def _get_cmd(command, arguments): """Merge command with arguments.""" if arguments is None: arguments = [] if command.endswith(".py") or command.endswith(".pyw"): return [sys.executable, command] + list(arguments) else: return [command] + list(arguments)
python
def _get_cmd(command, arguments): """Merge command with arguments.""" if arguments is None: arguments = [] if command.endswith(".py") or command.endswith(".pyw"): return [sys.executable, command] + list(arguments) else: return [command] + list(arguments)
[ "def", "_get_cmd", "(", "command", ",", "arguments", ")", ":", "if", "arguments", "is", "None", ":", "arguments", "=", "[", "]", "if", "command", ".", "endswith", "(", "\".py\"", ")", "or", "command", ".", "endswith", "(", "\".pyw\"", ")", ":", "return...
Merge command with arguments.
[ "Merge", "command", "with", "arguments", "." ]
f5a0a724a425ec4f9dd2c7fe966ef06faf3a15a3
https://github.com/alefnula/tea/blob/f5a0a724a425ec4f9dd2c7fe966ef06faf3a15a3/tea/process/posix_process.py#L42-L49
train
MainRo/cyclotron-std
cyclotron_std/argparse.py
argparse
def argparse(argv, parser, arguments): """ A command line argument parser. Parses arguments coming from the argv Observable and outputs them as Argument items in the output observable. Parameters ----------- argv : Observable An Observable of strings. parser : Observable An ...
python
def argparse(argv, parser, arguments): """ A command line argument parser. Parses arguments coming from the argv Observable and outputs them as Argument items in the output observable. Parameters ----------- argv : Observable An Observable of strings. parser : Observable An ...
[ "def", "argparse", "(", "argv", ",", "parser", ",", "arguments", ")", ":", "def", "add_arg", "(", "parser", ",", "arg_spec", ")", ":", "parser", ".", "add_argument", "(", "arg_spec", ".", "name", ",", "help", "=", "arg_spec", ".", "help", ")", "return"...
A command line argument parser. Parses arguments coming from the argv Observable and outputs them as Argument items in the output observable. Parameters ----------- argv : Observable An Observable of strings. parser : Observable An Observable containing one Parser item. argu...
[ "A", "command", "line", "argument", "parser", ".", "Parses", "arguments", "coming", "from", "the", "argv", "Observable", "and", "outputs", "them", "as", "Argument", "items", "in", "the", "output", "observable", "." ]
da4188f1c99aafc3a491803c23e01b44b52a15b1
https://github.com/MainRo/cyclotron-std/blob/da4188f1c99aafc3a491803c23e01b44b52a15b1/cyclotron_std/argparse.py#L22-L65
train
lingfeiwang/findr-python
findr/pij.py
gassists_pv
def gassists_pv(self,dg,dt,dt2,na=None,memlimit=-1): """Calculates p-values of gene i regulating gene j with genotype data assisted method with multiple tests. dg: numpy.ndarray(nt,ns,dtype=gtype(='u1' by default)) Genotype data. Entry dg[i,j] is genotype i's value for sample j. Each value must be among 0,1,...,n...
python
def gassists_pv(self,dg,dt,dt2,na=None,memlimit=-1): """Calculates p-values of gene i regulating gene j with genotype data assisted method with multiple tests. dg: numpy.ndarray(nt,ns,dtype=gtype(='u1' by default)) Genotype data. Entry dg[i,j] is genotype i's value for sample j. Each value must be among 0,1,...,n...
[ "def", "gassists_pv", "(", "self", ",", "dg", ",", "dt", ",", "dt2", ",", "na", "=", "None", ",", "memlimit", "=", "-", "1", ")", ":", "if", "self", ".", "lib", "is", "None", ":", "raise", "ValueError", "(", "\"Not initialized.\"", ")", "import", "...
Calculates p-values of gene i regulating gene j with genotype data assisted method with multiple tests. dg: numpy.ndarray(nt,ns,dtype=gtype(='u1' by default)) Genotype data. Entry dg[i,j] is genotype i's value for sample j. Each value must be among 0,1,...,na. Genotype i must be best (and significant) eQTL of ge...
[ "Calculates", "p", "-", "values", "of", "gene", "i", "regulating", "gene", "j", "with", "genotype", "data", "assisted", "method", "with", "multiple", "tests", ".", "dg", ":", "numpy", ".", "ndarray", "(", "nt", "ns", "dtype", "=", "gtype", "(", "=", "u...
417f163e658fee6ef311571f7048f96069a0cf1f
https://github.com/lingfeiwang/findr-python/blob/417f163e658fee6ef311571f7048f96069a0cf1f/findr/pij.py#L23-L96
train
lingfeiwang/findr-python
findr/pij.py
_gassist_any
def _gassist_any(self,dg,dt,dt2,name,na=None,nodiag=False,memlimit=-1): """Calculates probability of gene i regulating gene j with genotype data assisted method, with the recommended combination of multiple tests. dg: numpy.ndarray(nt,ns,dtype=gtype(='u1' by default)) Genotype data. Entry dg[i,j] is genotype i's v...
python
def _gassist_any(self,dg,dt,dt2,name,na=None,nodiag=False,memlimit=-1): """Calculates probability of gene i regulating gene j with genotype data assisted method, with the recommended combination of multiple tests. dg: numpy.ndarray(nt,ns,dtype=gtype(='u1' by default)) Genotype data. Entry dg[i,j] is genotype i's v...
[ "def", "_gassist_any", "(", "self", ",", "dg", ",", "dt", ",", "dt2", ",", "name", ",", "na", "=", "None", ",", "nodiag", "=", "False", ",", "memlimit", "=", "-", "1", ")", ":", "if", "self", ".", "lib", "is", "None", ":", "raise", "ValueError", ...
Calculates probability of gene i regulating gene j with genotype data assisted method, with the recommended combination of multiple tests. dg: numpy.ndarray(nt,ns,dtype=gtype(='u1' by default)) Genotype data. Entry dg[i,j] is genotype i's value for sample j. Each value must be among 0,1,...,na. Genotype i must ...
[ "Calculates", "probability", "of", "gene", "i", "regulating", "gene", "j", "with", "genotype", "data", "assisted", "method", "with", "the", "recommended", "combination", "of", "multiple", "tests", ".", "dg", ":", "numpy", ".", "ndarray", "(", "nt", "ns", "dt...
417f163e658fee6ef311571f7048f96069a0cf1f
https://github.com/lingfeiwang/findr-python/blob/417f163e658fee6ef311571f7048f96069a0cf1f/findr/pij.py#L187-L254
train
lingfeiwang/findr-python
findr/pij.py
gassist
def gassist(self,dg,dt,dt2,na=None,nodiag=False,memlimit=-1): """Calculates probability of gene i regulating gene j with genotype data assisted method, with the recommended combination of multiple tests. Probabilities are converted from likelihood ratios separately for each A. This gives better predictions when the...
python
def gassist(self,dg,dt,dt2,na=None,nodiag=False,memlimit=-1): """Calculates probability of gene i regulating gene j with genotype data assisted method, with the recommended combination of multiple tests. Probabilities are converted from likelihood ratios separately for each A. This gives better predictions when the...
[ "def", "gassist", "(", "self", ",", "dg", ",", "dt", ",", "dt2", ",", "na", "=", "None", ",", "nodiag", "=", "False", ",", "memlimit", "=", "-", "1", ")", ":", "return", "_gassist_any", "(", "self", ",", "dg", ",", "dt", ",", "dt2", ",", "\"pij...
Calculates probability of gene i regulating gene j with genotype data assisted method, with the recommended combination of multiple tests. Probabilities are converted from likelihood ratios separately for each A. This gives better predictions when the number of secondary targets (dt2) is large. (Check program warnin...
[ "Calculates", "probability", "of", "gene", "i", "regulating", "gene", "j", "with", "genotype", "data", "assisted", "method", "with", "the", "recommended", "combination", "of", "multiple", "tests", ".", "Probabilities", "are", "converted", "from", "likelihood", "ra...
417f163e658fee6ef311571f7048f96069a0cf1f
https://github.com/lingfeiwang/findr-python/blob/417f163e658fee6ef311571f7048f96069a0cf1f/findr/pij.py#L256-L287
train
lingfeiwang/findr-python
findr/pij.py
_cassists_any
def _cassists_any(self,dc,dt,dt2,name,nodiag=False,memlimit=-1): """Calculates probability of gene i regulating gene j with continuous anchor data assisted method, with multiple tests, by converting log likelihoods into probabilities per A for all B. dc: numpy.ndarray(nt,ns,dtype=ftype(='f4' by default)) Continuous ...
python
def _cassists_any(self,dc,dt,dt2,name,nodiag=False,memlimit=-1): """Calculates probability of gene i regulating gene j with continuous anchor data assisted method, with multiple tests, by converting log likelihoods into probabilities per A for all B. dc: numpy.ndarray(nt,ns,dtype=ftype(='f4' by default)) Continuous ...
[ "def", "_cassists_any", "(", "self", ",", "dc", ",", "dt", ",", "dt2", ",", "name", ",", "nodiag", "=", "False", ",", "memlimit", "=", "-", "1", ")", ":", "if", "self", ".", "lib", "is", "None", ":", "raise", "ValueError", "(", "\"Not initialized.\""...
Calculates probability of gene i regulating gene j with continuous anchor data assisted method, with multiple tests, by converting log likelihoods into probabilities per A for all B. dc: numpy.ndarray(nt,ns,dtype=ftype(='f4' by default)) Continuous anchor data. Entry dc[i,j] is anchor i's value for sample j. Anch...
[ "Calculates", "probability", "of", "gene", "i", "regulating", "gene", "j", "with", "continuous", "anchor", "data", "assisted", "method", "with", "multiple", "tests", "by", "converting", "log", "likelihoods", "into", "probabilities", "per", "A", "for", "all", "B"...
417f163e658fee6ef311571f7048f96069a0cf1f
https://github.com/lingfeiwang/findr-python/blob/417f163e658fee6ef311571f7048f96069a0cf1f/findr/pij.py#L383-L454
train
lingfeiwang/findr-python
findr/pij.py
cassists
def cassists(self,dc,dt,dt2,nodiag=False,memlimit=-1): """Calculates probability of gene i regulating gene j with continuous data assisted method, with multiple tests, by converting log likelihoods into probabilities per A for all B. Probabilities are converted from likelihood ratios separately for each A. This give...
python
def cassists(self,dc,dt,dt2,nodiag=False,memlimit=-1): """Calculates probability of gene i regulating gene j with continuous data assisted method, with multiple tests, by converting log likelihoods into probabilities per A for all B. Probabilities are converted from likelihood ratios separately for each A. This give...
[ "def", "cassists", "(", "self", ",", "dc", ",", "dt", ",", "dt2", ",", "nodiag", "=", "False", ",", "memlimit", "=", "-", "1", ")", ":", "return", "_cassists_any", "(", "self", ",", "dc", ",", "dt", ",", "dt2", ",", "\"pijs_cassist\"", ",", "nodiag...
Calculates probability of gene i regulating gene j with continuous data assisted method, with multiple tests, by converting log likelihoods into probabilities per A for all B. Probabilities are converted from likelihood ratios separately for each A. This gives better predictions when the number of secondary targets ...
[ "Calculates", "probability", "of", "gene", "i", "regulating", "gene", "j", "with", "continuous", "data", "assisted", "method", "with", "multiple", "tests", "by", "converting", "log", "likelihoods", "into", "probabilities", "per", "A", "for", "all", "B", ".", "...
417f163e658fee6ef311571f7048f96069a0cf1f
https://github.com/lingfeiwang/findr-python/blob/417f163e658fee6ef311571f7048f96069a0cf1f/findr/pij.py#L456-L493
train
lingfeiwang/findr-python
findr/pij.py
_cassist_any
def _cassist_any(self,dc,dt,dt2,name,nodiag=False,memlimit=-1): """Calculates probability of gene i regulating gene j with continuous data assisted method, with the recommended combination of multiple tests. dc: numpy.ndarray(nt,ns,dtype=ftype(='f4' by default)) Continuous anchor data. Entry dc[i,j] is anchor i's ...
python
def _cassist_any(self,dc,dt,dt2,name,nodiag=False,memlimit=-1): """Calculates probability of gene i regulating gene j with continuous data assisted method, with the recommended combination of multiple tests. dc: numpy.ndarray(nt,ns,dtype=ftype(='f4' by default)) Continuous anchor data. Entry dc[i,j] is anchor i's ...
[ "def", "_cassist_any", "(", "self", ",", "dc", ",", "dt", ",", "dt2", ",", "name", ",", "nodiag", "=", "False", ",", "memlimit", "=", "-", "1", ")", ":", "if", "self", ".", "lib", "is", "None", ":", "raise", "ValueError", "(", "\"Not initialized.\"",...
Calculates probability of gene i regulating gene j with continuous data assisted method, with the recommended combination of multiple tests. dc: numpy.ndarray(nt,ns,dtype=ftype(='f4' by default)) Continuous anchor data. Entry dc[i,j] is anchor i's value for sample j. Anchor i is used to infer the probability of g...
[ "Calculates", "probability", "of", "gene", "i", "regulating", "gene", "j", "with", "continuous", "data", "assisted", "method", "with", "the", "recommended", "combination", "of", "multiple", "tests", ".", "dc", ":", "numpy", ".", "ndarray", "(", "nt", "ns", "...
417f163e658fee6ef311571f7048f96069a0cf1f
https://github.com/lingfeiwang/findr-python/blob/417f163e658fee6ef311571f7048f96069a0cf1f/findr/pij.py#L495-L549
train
lingfeiwang/findr-python
findr/pij.py
cassist
def cassist(self,dc,dt,dt2,nodiag=False,memlimit=-1): """Calculates probability of gene i regulating gene j with continuous data assisted method, with the recommended combination of multiple tests. Probabilities are converted from likelihood ratios separately for each A. This gives better predictions when the numbe...
python
def cassist(self,dc,dt,dt2,nodiag=False,memlimit=-1): """Calculates probability of gene i regulating gene j with continuous data assisted method, with the recommended combination of multiple tests. Probabilities are converted from likelihood ratios separately for each A. This gives better predictions when the numbe...
[ "def", "cassist", "(", "self", ",", "dc", ",", "dt", ",", "dt2", ",", "nodiag", "=", "False", ",", "memlimit", "=", "-", "1", ")", ":", "return", "_cassist_any", "(", "self", ",", "dc", ",", "dt", ",", "dt2", ",", "\"pij_cassist\"", ",", "nodiag", ...
Calculates probability of gene i regulating gene j with continuous data assisted method, with the recommended combination of multiple tests. Probabilities are converted from likelihood ratios separately for each A. This gives better predictions when the number of secondary targets (dt2) is large. (Check program warn...
[ "Calculates", "probability", "of", "gene", "i", "regulating", "gene", "j", "with", "continuous", "data", "assisted", "method", "with", "the", "recommended", "combination", "of", "multiple", "tests", ".", "Probabilities", "are", "converted", "from", "likelihood", "...
417f163e658fee6ef311571f7048f96069a0cf1f
https://github.com/lingfeiwang/findr-python/blob/417f163e658fee6ef311571f7048f96069a0cf1f/findr/pij.py#L551-L578
train
lingfeiwang/findr-python
findr/pij.py
rank_pv
def rank_pv(self,dt,dt2,memlimit=-1): """Calculates p-values of gene i correlating with gene j by converting log likelihoods into probabilities per A for all B. dt: numpy.ndarray(nt,ns,dtype=ftype(='=f4' by default)) Gene expression data for A Entry dt[i,j] is gene i's expression level for sample j. dt2:numpy.ndar...
python
def rank_pv(self,dt,dt2,memlimit=-1): """Calculates p-values of gene i correlating with gene j by converting log likelihoods into probabilities per A for all B. dt: numpy.ndarray(nt,ns,dtype=ftype(='=f4' by default)) Gene expression data for A Entry dt[i,j] is gene i's expression level for sample j. dt2:numpy.ndar...
[ "def", "rank_pv", "(", "self", ",", "dt", ",", "dt2", ",", "memlimit", "=", "-", "1", ")", ":", "if", "self", ".", "lib", "is", "None", ":", "raise", "ValueError", "(", "\"Not initialized.\"", ")", "import", "numpy", "as", "np", "from", ".", "auto", ...
Calculates p-values of gene i correlating with gene j by converting log likelihoods into probabilities per A for all B. dt: numpy.ndarray(nt,ns,dtype=ftype(='=f4' by default)) Gene expression data for A Entry dt[i,j] is gene i's expression level for sample j. dt2:numpy.ndarray(nt2,ns,dtype=ftype(='=f4' by default))...
[ "Calculates", "p", "-", "values", "of", "gene", "i", "correlating", "with", "gene", "j", "by", "converting", "log", "likelihoods", "into", "probabilities", "per", "A", "for", "all", "B", ".", "dt", ":", "numpy", ".", "ndarray", "(", "nt", "ns", "dtype", ...
417f163e658fee6ef311571f7048f96069a0cf1f
https://github.com/lingfeiwang/findr-python/blob/417f163e658fee6ef311571f7048f96069a0cf1f/findr/pij.py#L606-L648
train
Duke-QCD/hic
hic/flow.py
qn
def qn(phi, *n): """ Calculate the complex flow vector `Q_n`. :param array-like phi: Azimuthal angles. :param int n: One or more harmonics to calculate. :returns: A single complex number if only one ``n`` was given or a complex array for multiple ``n``. """ phi = np.ravel...
python
def qn(phi, *n): """ Calculate the complex flow vector `Q_n`. :param array-like phi: Azimuthal angles. :param int n: One or more harmonics to calculate. :returns: A single complex number if only one ``n`` was given or a complex array for multiple ``n``. """ phi = np.ravel...
[ "def", "qn", "(", "phi", ",", "*", "n", ")", ":", "phi", "=", "np", ".", "ravel", "(", "phi", ")", "n", "=", "np", ".", "asarray", "(", "n", ")", "i_n_phi", "=", "np", ".", "zeros", "(", "(", "n", ".", "size", ",", "phi", ".", "size", ")"...
Calculate the complex flow vector `Q_n`. :param array-like phi: Azimuthal angles. :param int n: One or more harmonics to calculate. :returns: A single complex number if only one ``n`` was given or a complex array for multiple ``n``.
[ "Calculate", "the", "complex", "flow", "vector", "Q_n", "." ]
9afb141735b1ac228d296a2349225d2bdcdb68f0
https://github.com/Duke-QCD/hic/blob/9afb141735b1ac228d296a2349225d2bdcdb68f0/hic/flow.py#L13-L36
train
Duke-QCD/hic
hic/flow.py
Cumulant.correlation
def correlation(self, n, k, error=False): r""" Calculate `\langle k \rangle_n`, the `k`-particle correlation function for `n`\ th-order anisotropy. :param int n: Anisotropy order. :param int k: Correlation order. :param bool error: Whether to calculate stati...
python
def correlation(self, n, k, error=False): r""" Calculate `\langle k \rangle_n`, the `k`-particle correlation function for `n`\ th-order anisotropy. :param int n: Anisotropy order. :param int k: Correlation order. :param bool error: Whether to calculate stati...
[ "def", "correlation", "(", "self", ",", "n", ",", "k", ",", "error", "=", "False", ")", ":", "self", ".", "_calculate_corr", "(", "n", ",", "k", ")", "corr_nk", "=", "self", ".", "_corr", "[", "n", "]", "[", "k", "]", "if", "error", ":", "self"...
r""" Calculate `\langle k \rangle_n`, the `k`-particle correlation function for `n`\ th-order anisotropy. :param int n: Anisotropy order. :param int k: Correlation order. :param bool error: Whether to calculate statistical error (for `\langle 2 \rangle` ...
[ "r", "Calculate", "\\", "langle", "k", "\\", "rangle_n", "the", "k", "-", "particle", "correlation", "function", "for", "n", "\\", "th", "-", "order", "anisotropy", "." ]
9afb141735b1ac228d296a2349225d2bdcdb68f0
https://github.com/Duke-QCD/hic/blob/9afb141735b1ac228d296a2349225d2bdcdb68f0/hic/flow.py#L154-L175
train
Duke-QCD/hic
hic/flow.py
Cumulant.cumulant
def cumulant(self, n, k, error=False): r""" Calculate `c_n\{k\}`, the `k`-particle cumulant for `n`\ th-order anisotropy. :param int n: Anisotropy order. :param int k: Correlation order. :param bool error: Whether to calculate statistical error (for `c_n\{2\...
python
def cumulant(self, n, k, error=False): r""" Calculate `c_n\{k\}`, the `k`-particle cumulant for `n`\ th-order anisotropy. :param int n: Anisotropy order. :param int k: Correlation order. :param bool error: Whether to calculate statistical error (for `c_n\{2\...
[ "def", "cumulant", "(", "self", ",", "n", ",", "k", ",", "error", "=", "False", ")", ":", "corr_nk", "=", "self", ".", "correlation", "(", "n", ",", "k", ",", "error", "=", "error", ")", "if", "k", "==", "2", ":", "return", "corr_nk", "elif", "...
r""" Calculate `c_n\{k\}`, the `k`-particle cumulant for `n`\ th-order anisotropy. :param int n: Anisotropy order. :param int k: Correlation order. :param bool error: Whether to calculate statistical error (for `c_n\{2\}` only). If true, return a tuple `...
[ "r", "Calculate", "c_n", "\\", "{", "k", "\\", "}", "the", "k", "-", "particle", "cumulant", "for", "n", "\\", "th", "-", "order", "anisotropy", "." ]
9afb141735b1ac228d296a2349225d2bdcdb68f0
https://github.com/Duke-QCD/hic/blob/9afb141735b1ac228d296a2349225d2bdcdb68f0/hic/flow.py#L177-L196
train
Duke-QCD/hic
hic/flow.py
Cumulant.flow
def flow(self, n, k, error=False, imaginary='nan'): r""" Calculate `v_n\{k\}`, the estimate of flow coefficient `v_n` from the `k`-particle cumulant. :param int n: Anisotropy order. :param int k: Correlation order. :param bool error: Whether to calculate sta...
python
def flow(self, n, k, error=False, imaginary='nan'): r""" Calculate `v_n\{k\}`, the estimate of flow coefficient `v_n` from the `k`-particle cumulant. :param int n: Anisotropy order. :param int k: Correlation order. :param bool error: Whether to calculate sta...
[ "def", "flow", "(", "self", ",", "n", ",", "k", ",", "error", "=", "False", ",", "imaginary", "=", "'nan'", ")", ":", "cnk", "=", "self", ".", "cumulant", "(", "n", ",", "k", ",", "error", "=", "error", ")", "if", "error", ":", "cnk", ",", "c...
r""" Calculate `v_n\{k\}`, the estimate of flow coefficient `v_n` from the `k`-particle cumulant. :param int n: Anisotropy order. :param int k: Correlation order. :param bool error: Whether to calculate statistical error (for `v_n\{2\}` only). If true, r...
[ "r", "Calculate", "v_n", "\\", "{", "k", "\\", "}", "the", "estimate", "of", "flow", "coefficient", "v_n", "from", "the", "k", "-", "particle", "cumulant", "." ]
9afb141735b1ac228d296a2349225d2bdcdb68f0
https://github.com/Duke-QCD/hic/blob/9afb141735b1ac228d296a2349225d2bdcdb68f0/hic/flow.py#L200-L242
train
Duke-QCD/hic
hic/flow.py
Sampler._pdf
def _pdf(self, phi): """ Evaluate the _unnormalized_ flow PDF. """ pdf = np.inner(self._vn, np.cos(np.outer(phi, self._n))) pdf *= 2. pdf += 1. return pdf
python
def _pdf(self, phi): """ Evaluate the _unnormalized_ flow PDF. """ pdf = np.inner(self._vn, np.cos(np.outer(phi, self._n))) pdf *= 2. pdf += 1. return pdf
[ "def", "_pdf", "(", "self", ",", "phi", ")", ":", "pdf", "=", "np", ".", "inner", "(", "self", ".", "_vn", ",", "np", ".", "cos", "(", "np", ".", "outer", "(", "phi", ",", "self", ".", "_n", ")", ")", ")", "pdf", "*=", "2.", "pdf", "+=", ...
Evaluate the _unnormalized_ flow PDF.
[ "Evaluate", "the", "_unnormalized_", "flow", "PDF", "." ]
9afb141735b1ac228d296a2349225d2bdcdb68f0
https://github.com/Duke-QCD/hic/blob/9afb141735b1ac228d296a2349225d2bdcdb68f0/hic/flow.py#L279-L288
train
Duke-QCD/hic
hic/flow.py
Sampler._uniform_phi
def _uniform_phi(M): """ Generate M random numbers in [-pi, pi). """ return np.random.uniform(-np.pi, np.pi, M)
python
def _uniform_phi(M): """ Generate M random numbers in [-pi, pi). """ return np.random.uniform(-np.pi, np.pi, M)
[ "def", "_uniform_phi", "(", "M", ")", ":", "return", "np", ".", "random", ".", "uniform", "(", "-", "np", ".", "pi", ",", "np", ".", "pi", ",", "M", ")" ]
Generate M random numbers in [-pi, pi).
[ "Generate", "M", "random", "numbers", "in", "[", "-", "pi", "pi", ")", "." ]
9afb141735b1ac228d296a2349225d2bdcdb68f0
https://github.com/Duke-QCD/hic/blob/9afb141735b1ac228d296a2349225d2bdcdb68f0/hic/flow.py#L291-L296
train
Duke-QCD/hic
hic/flow.py
Sampler.pdf
def pdf(self, phi): r""" Evaluate the flow PDF `dN/d\phi`. :param array-like phi: Azimuthal angles. :returns: The flow PDF evaluated at ``phi``. """ if self._n is None: pdf = np.empty_like(phi) pdf.fill(.5/np.pi) return pdf ...
python
def pdf(self, phi): r""" Evaluate the flow PDF `dN/d\phi`. :param array-like phi: Azimuthal angles. :returns: The flow PDF evaluated at ``phi``. """ if self._n is None: pdf = np.empty_like(phi) pdf.fill(.5/np.pi) return pdf ...
[ "def", "pdf", "(", "self", ",", "phi", ")", ":", "if", "self", ".", "_n", "is", "None", ":", "pdf", "=", "np", ".", "empty_like", "(", "phi", ")", "pdf", ".", "fill", "(", ".5", "/", "np", ".", "pi", ")", "return", "pdf", "phi", "=", "np", ...
r""" Evaluate the flow PDF `dN/d\phi`. :param array-like phi: Azimuthal angles. :returns: The flow PDF evaluated at ``phi``.
[ "r", "Evaluate", "the", "flow", "PDF", "dN", "/", "d", "\\", "phi", "." ]
9afb141735b1ac228d296a2349225d2bdcdb68f0
https://github.com/Duke-QCD/hic/blob/9afb141735b1ac228d296a2349225d2bdcdb68f0/hic/flow.py#L298-L317
train
Duke-QCD/hic
hic/flow.py
Sampler.sample
def sample(self, multiplicity): r""" Randomly sample azimuthal angles `\phi`. :param int multiplicity: Number to sample. :returns: Array of sampled angles. """ if self._n is None: return self._uniform_phi(multiplicity) # Since the flow PDF does not...
python
def sample(self, multiplicity): r""" Randomly sample azimuthal angles `\phi`. :param int multiplicity: Number to sample. :returns: Array of sampled angles. """ if self._n is None: return self._uniform_phi(multiplicity) # Since the flow PDF does not...
[ "def", "sample", "(", "self", ",", "multiplicity", ")", ":", "if", "self", ".", "_n", "is", "None", ":", "return", "self", ".", "_uniform_phi", "(", "multiplicity", ")", "# Since the flow PDF does not have an analytic inverse CDF, I use a", "# simple accept-reject sampl...
r""" Randomly sample azimuthal angles `\phi`. :param int multiplicity: Number to sample. :returns: Array of sampled angles.
[ "r", "Randomly", "sample", "azimuthal", "angles", "\\", "phi", "." ]
9afb141735b1ac228d296a2349225d2bdcdb68f0
https://github.com/Duke-QCD/hic/blob/9afb141735b1ac228d296a2349225d2bdcdb68f0/hic/flow.py#L319-L354
train
letuananh/chirptext
chirptext/anhxa.py
dumps
def dumps(obj, *args, **kwargs): ''' Typeless dump an object to json string ''' return json.dumps(obj, *args, cls=TypelessSONEncoder, ensure_ascii=False, **kwargs)
python
def dumps(obj, *args, **kwargs): ''' Typeless dump an object to json string ''' return json.dumps(obj, *args, cls=TypelessSONEncoder, ensure_ascii=False, **kwargs)
[ "def", "dumps", "(", "obj", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "json", ".", "dumps", "(", "obj", ",", "*", "args", ",", "cls", "=", "TypelessSONEncoder", ",", "ensure_ascii", "=", "False", ",", "*", "*", "kwargs", ")" ]
Typeless dump an object to json string
[ "Typeless", "dump", "an", "object", "to", "json", "string" ]
ce60b47257b272a587c8703ea1f86cd1a45553a7
https://github.com/letuananh/chirptext/blob/ce60b47257b272a587c8703ea1f86cd1a45553a7/chirptext/anhxa.py#L81-L83
train
letuananh/chirptext
chirptext/anhxa.py
flex_update_obj
def flex_update_obj(source, target, __silent, *fields, **field_map): ''' Pull data from source to target. Target's __dict__ (object data) will be used by default. Otherwise, it'll be treated as a dictionary ''' source_dict = source.__dict__ if hasattr(source, '__dict__') else source if not fields: ...
python
def flex_update_obj(source, target, __silent, *fields, **field_map): ''' Pull data from source to target. Target's __dict__ (object data) will be used by default. Otherwise, it'll be treated as a dictionary ''' source_dict = source.__dict__ if hasattr(source, '__dict__') else source if not fields: ...
[ "def", "flex_update_obj", "(", "source", ",", "target", ",", "__silent", ",", "*", "fields", ",", "*", "*", "field_map", ")", ":", "source_dict", "=", "source", ".", "__dict__", "if", "hasattr", "(", "source", ",", "'__dict__'", ")", "else", "source", "i...
Pull data from source to target. Target's __dict__ (object data) will be used by default. Otherwise, it'll be treated as a dictionary
[ "Pull", "data", "from", "source", "to", "target", ".", "Target", "s", "__dict__", "(", "object", "data", ")", "will", "be", "used", "by", "default", ".", "Otherwise", "it", "ll", "be", "treated", "as", "a", "dictionary" ]
ce60b47257b272a587c8703ea1f86cd1a45553a7
https://github.com/letuananh/chirptext/blob/ce60b47257b272a587c8703ea1f86cd1a45553a7/chirptext/anhxa.py#L90-L100
train
letuananh/chirptext
chirptext/anhxa.py
to_obj
def to_obj(cls, obj_data=None, *fields, **field_map): ''' Use obj_data (dict-like) to construct an object of type cls prioritize obj_dict when there are conficts ''' if not fields: fields = obj_data.keys() try: kwargs = {field(f, field_map): obj_data[f] for f in fields if f in obj_data} ...
python
def to_obj(cls, obj_data=None, *fields, **field_map): ''' Use obj_data (dict-like) to construct an object of type cls prioritize obj_dict when there are conficts ''' if not fields: fields = obj_data.keys() try: kwargs = {field(f, field_map): obj_data[f] for f in fields if f in obj_data} ...
[ "def", "to_obj", "(", "cls", ",", "obj_data", "=", "None", ",", "*", "fields", ",", "*", "*", "field_map", ")", ":", "if", "not", "fields", ":", "fields", "=", "obj_data", ".", "keys", "(", ")", "try", ":", "kwargs", "=", "{", "field", "(", "f", ...
Use obj_data (dict-like) to construct an object of type cls prioritize obj_dict when there are conficts
[ "Use", "obj_data", "(", "dict", "-", "like", ")", "to", "construct", "an", "object", "of", "type", "cls", "prioritize", "obj_dict", "when", "there", "are", "conficts" ]
ce60b47257b272a587c8703ea1f86cd1a45553a7
https://github.com/letuananh/chirptext/blob/ce60b47257b272a587c8703ea1f86cd1a45553a7/chirptext/anhxa.py#L113-L126
train
letuananh/chirptext
chirptext/deko.py
is_kana
def is_kana(text): ''' Check if a text if written in kana only (hiragana & katakana) if text is empty then return True ''' if text is None: raise ValueError("text cannot be None") for c in text: if c not in HIRAGANA and c not in KATAKANA: return False return True
python
def is_kana(text): ''' Check if a text if written in kana only (hiragana & katakana) if text is empty then return True ''' if text is None: raise ValueError("text cannot be None") for c in text: if c not in HIRAGANA and c not in KATAKANA: return False return True
[ "def", "is_kana", "(", "text", ")", ":", "if", "text", "is", "None", ":", "raise", "ValueError", "(", "\"text cannot be None\"", ")", "for", "c", "in", "text", ":", "if", "c", "not", "in", "HIRAGANA", "and", "c", "not", "in", "KATAKANA", ":", "return",...
Check if a text if written in kana only (hiragana & katakana) if text is empty then return True
[ "Check", "if", "a", "text", "if", "written", "in", "kana", "only", "(", "hiragana", "&", "katakana", ")", "if", "text", "is", "empty", "then", "return", "True" ]
ce60b47257b272a587c8703ea1f86cd1a45553a7
https://github.com/letuananh/chirptext/blob/ce60b47257b272a587c8703ea1f86cd1a45553a7/chirptext/deko.py#L62-L71
train
letuananh/chirptext
chirptext/deko.py
txt2mecab
def txt2mecab(text, **kwargs): ''' Use mecab to parse one sentence ''' mecab_out = _internal_mecab_parse(text, **kwargs).splitlines() tokens = [MeCabToken.parse(x) for x in mecab_out] return MeCabSent(text, tokens)
python
def txt2mecab(text, **kwargs): ''' Use mecab to parse one sentence ''' mecab_out = _internal_mecab_parse(text, **kwargs).splitlines() tokens = [MeCabToken.parse(x) for x in mecab_out] return MeCabSent(text, tokens)
[ "def", "txt2mecab", "(", "text", ",", "*", "*", "kwargs", ")", ":", "mecab_out", "=", "_internal_mecab_parse", "(", "text", ",", "*", "*", "kwargs", ")", ".", "splitlines", "(", ")", "tokens", "=", "[", "MeCabToken", ".", "parse", "(", "x", ")", "for...
Use mecab to parse one sentence
[ "Use", "mecab", "to", "parse", "one", "sentence" ]
ce60b47257b272a587c8703ea1f86cd1a45553a7
https://github.com/letuananh/chirptext/blob/ce60b47257b272a587c8703ea1f86cd1a45553a7/chirptext/deko.py#L250-L254
train
letuananh/chirptext
chirptext/deko.py
lines2mecab
def lines2mecab(lines, **kwargs): ''' Use mecab to parse many lines ''' sents = [] for line in lines: sent = txt2mecab(line, **kwargs) sents.append(sent) return sents
python
def lines2mecab(lines, **kwargs): ''' Use mecab to parse many lines ''' sents = [] for line in lines: sent = txt2mecab(line, **kwargs) sents.append(sent) return sents
[ "def", "lines2mecab", "(", "lines", ",", "*", "*", "kwargs", ")", ":", "sents", "=", "[", "]", "for", "line", "in", "lines", ":", "sent", "=", "txt2mecab", "(", "line", ",", "*", "*", "kwargs", ")", "sents", ".", "append", "(", "sent", ")", "retu...
Use mecab to parse many lines
[ "Use", "mecab", "to", "parse", "many", "lines" ]
ce60b47257b272a587c8703ea1f86cd1a45553a7
https://github.com/letuananh/chirptext/blob/ce60b47257b272a587c8703ea1f86cd1a45553a7/chirptext/deko.py#L257-L263
train
letuananh/chirptext
chirptext/deko.py
tokenize_sent
def tokenize_sent(mtokens, raw='', auto_strip=True): ''' Tokenize a text to multiple sentences ''' sents = [] bucket = [] cfrom = 0 cto = 0 token_cfrom = 0 logger = getLogger() logger.debug("raw text: {}".format(raw)) logger.debug("tokens: {}".format(mtokens)) for t in mtokens: ...
python
def tokenize_sent(mtokens, raw='', auto_strip=True): ''' Tokenize a text to multiple sentences ''' sents = [] bucket = [] cfrom = 0 cto = 0 token_cfrom = 0 logger = getLogger() logger.debug("raw text: {}".format(raw)) logger.debug("tokens: {}".format(mtokens)) for t in mtokens: ...
[ "def", "tokenize_sent", "(", "mtokens", ",", "raw", "=", "''", ",", "auto_strip", "=", "True", ")", ":", "sents", "=", "[", "]", "bucket", "=", "[", "]", "cfrom", "=", "0", "cto", "=", "0", "token_cfrom", "=", "0", "logger", "=", "getLogger", "(", ...
Tokenize a text to multiple sentences
[ "Tokenize", "a", "text", "to", "multiple", "sentences" ]
ce60b47257b272a587c8703ea1f86cd1a45553a7
https://github.com/letuananh/chirptext/blob/ce60b47257b272a587c8703ea1f86cd1a45553a7/chirptext/deko.py#L274-L308
train
letuananh/chirptext
chirptext/deko.py
analyse
def analyse(content, splitlines=True, format=None, **kwargs): ''' Japanese text > tokenize/txt/html ''' sents = DekoText.parse(content, splitlines=splitlines, **kwargs) doc = [] final = sents # Generate output if format == 'html': for sent in sents: doc.append(sent.to_ruby())...
python
def analyse(content, splitlines=True, format=None, **kwargs): ''' Japanese text > tokenize/txt/html ''' sents = DekoText.parse(content, splitlines=splitlines, **kwargs) doc = [] final = sents # Generate output if format == 'html': for sent in sents: doc.append(sent.to_ruby())...
[ "def", "analyse", "(", "content", ",", "splitlines", "=", "True", ",", "format", "=", "None", ",", "*", "*", "kwargs", ")", ":", "sents", "=", "DekoText", ".", "parse", "(", "content", ",", "splitlines", "=", "splitlines", ",", "*", "*", "kwargs", ")...
Japanese text > tokenize/txt/html
[ "Japanese", "text", ">", "tokenize", "/", "txt", "/", "html" ]
ce60b47257b272a587c8703ea1f86cd1a45553a7
https://github.com/letuananh/chirptext/blob/ce60b47257b272a587c8703ea1f86cd1a45553a7/chirptext/deko.py#L311-L327
train
letuananh/chirptext
chirptext/deko.py
MeCabToken.pos3
def pos3(self): ''' Use pos-sc1-sc2 as POS ''' parts = [self.pos] if self.sc1 and self.sc1 != '*': parts.append(self.sc1) if self.sc2 and self.sc2 != '*': parts.append(self.sc2) return '-'.join(parts)
python
def pos3(self): ''' Use pos-sc1-sc2 as POS ''' parts = [self.pos] if self.sc1 and self.sc1 != '*': parts.append(self.sc1) if self.sc2 and self.sc2 != '*': parts.append(self.sc2) return '-'.join(parts)
[ "def", "pos3", "(", "self", ")", ":", "parts", "=", "[", "self", ".", "pos", "]", "if", "self", ".", "sc1", "and", "self", ".", "sc1", "!=", "'*'", ":", "parts", ".", "append", "(", "self", ".", "sc1", ")", "if", "self", ".", "sc2", "and", "s...
Use pos-sc1-sc2 as POS
[ "Use", "pos", "-", "sc1", "-", "sc2", "as", "POS" ]
ce60b47257b272a587c8703ea1f86cd1a45553a7
https://github.com/letuananh/chirptext/blob/ce60b47257b272a587c8703ea1f86cd1a45553a7/chirptext/deko.py#L113-L120
train
letuananh/chirptext
chirptext/deko.py
MeCabToken.to_ruby
def to_ruby(self): ''' Convert one MeCabToken into HTML ''' if self.need_ruby(): surface = self.surface reading = self.reading_hira() return '<ruby><rb>{sur}</rb><rt>{read}</rt></ruby>'.format(sur=surface, read=reading) elif self.is_eos: return '' ...
python
def to_ruby(self): ''' Convert one MeCabToken into HTML ''' if self.need_ruby(): surface = self.surface reading = self.reading_hira() return '<ruby><rb>{sur}</rb><rt>{read}</rt></ruby>'.format(sur=surface, read=reading) elif self.is_eos: return '' ...
[ "def", "to_ruby", "(", "self", ")", ":", "if", "self", ".", "need_ruby", "(", ")", ":", "surface", "=", "self", ".", "surface", "reading", "=", "self", ".", "reading_hira", "(", ")", "return", "'<ruby><rb>{sur}</rb><rt>{read}</rt></ruby>'", ".", "format", "(...
Convert one MeCabToken into HTML
[ "Convert", "one", "MeCabToken", "into", "HTML" ]
ce60b47257b272a587c8703ea1f86cd1a45553a7
https://github.com/letuananh/chirptext/blob/ce60b47257b272a587c8703ea1f86cd1a45553a7/chirptext/deko.py#L122-L131
train
letuananh/chirptext
chirptext/deko.py
DekoText.add
def add(self, sentence_text, **kwargs): ''' Parse a text string and add it to this doc ''' sent = MeCabSent.parse(sentence_text, **kwargs) self.sents.append(sent) return sent
python
def add(self, sentence_text, **kwargs): ''' Parse a text string and add it to this doc ''' sent = MeCabSent.parse(sentence_text, **kwargs) self.sents.append(sent) return sent
[ "def", "add", "(", "self", ",", "sentence_text", ",", "*", "*", "kwargs", ")", ":", "sent", "=", "MeCabSent", ".", "parse", "(", "sentence_text", ",", "*", "*", "kwargs", ")", "self", ".", "sents", ".", "append", "(", "sent", ")", "return", "sent" ]
Parse a text string and add it to this doc
[ "Parse", "a", "text", "string", "and", "add", "it", "to", "this", "doc" ]
ce60b47257b272a587c8703ea1f86cd1a45553a7
https://github.com/letuananh/chirptext/blob/ce60b47257b272a587c8703ea1f86cd1a45553a7/chirptext/deko.py#L214-L218
train
alefnula/tea
tea/utils/encoding.py
smart_text
def smart_text(s, encoding="utf-8", strings_only=False, errors="strict"): """Return a unicode object representing 's'. Treats bytes using the 'encoding' codec. If strings_only is True, don't convert (some) non-string-like objects. """ if isinstance(s, six.text_type): return s ...
python
def smart_text(s, encoding="utf-8", strings_only=False, errors="strict"): """Return a unicode object representing 's'. Treats bytes using the 'encoding' codec. If strings_only is True, don't convert (some) non-string-like objects. """ if isinstance(s, six.text_type): return s ...
[ "def", "smart_text", "(", "s", ",", "encoding", "=", "\"utf-8\"", ",", "strings_only", "=", "False", ",", "errors", "=", "\"strict\"", ")", ":", "if", "isinstance", "(", "s", ",", "six", ".", "text_type", ")", ":", "return", "s", "if", "strings_only", ...
Return a unicode object representing 's'. Treats bytes using the 'encoding' codec. If strings_only is True, don't convert (some) non-string-like objects.
[ "Return", "a", "unicode", "object", "representing", "s", ".", "Treats", "bytes", "using", "the", "encoding", "codec", ".", "If", "strings_only", "is", "True", "don", "t", "convert", "(", "some", ")", "non", "-", "string", "-", "like", "objects", "." ]
f5a0a724a425ec4f9dd2c7fe966ef06faf3a15a3
https://github.com/alefnula/tea/blob/f5a0a724a425ec4f9dd2c7fe966ef06faf3a15a3/tea/utils/encoding.py#L8-L35
train
alefnula/tea
tea/utils/encoding.py
smart_bytes
def smart_bytes(s, encoding="utf-8", strings_only=False, errors="strict"): """Return a bytes version of 's' encoded as specified in 'encoding'. If strings_only is True, don't convert (some) non-string-like objects. """ if isinstance(s, six.binary_type): if encoding == "utf-8": ...
python
def smart_bytes(s, encoding="utf-8", strings_only=False, errors="strict"): """Return a bytes version of 's' encoded as specified in 'encoding'. If strings_only is True, don't convert (some) non-string-like objects. """ if isinstance(s, six.binary_type): if encoding == "utf-8": ...
[ "def", "smart_bytes", "(", "s", ",", "encoding", "=", "\"utf-8\"", ",", "strings_only", "=", "False", ",", "errors", "=", "\"strict\"", ")", ":", "if", "isinstance", "(", "s", ",", "six", ".", "binary_type", ")", ":", "if", "encoding", "==", "\"utf-8\"",...
Return a bytes version of 's' encoded as specified in 'encoding'. If strings_only is True, don't convert (some) non-string-like objects.
[ "Return", "a", "bytes", "version", "of", "s", "encoded", "as", "specified", "in", "encoding", ".", "If", "strings_only", "is", "True", "don", "t", "convert", "(", "some", ")", "non", "-", "string", "-", "like", "objects", "." ]
f5a0a724a425ec4f9dd2c7fe966ef06faf3a15a3
https://github.com/alefnula/tea/blob/f5a0a724a425ec4f9dd2c7fe966ef06faf3a15a3/tea/utils/encoding.py#L38-L59
train
hufman/flask_rdf
flask_rdf/common_decorators.py
ViewDecorator.output
def output(self, response, accepts): """ Formats a response from a view to handle any RDF graphs If a view function returns an RDF graph, serialize it based on Accept header If it's not an RDF graph, return it without any special handling """ graph = self.get_graph(response) if graph is not None: ...
python
def output(self, response, accepts): """ Formats a response from a view to handle any RDF graphs If a view function returns an RDF graph, serialize it based on Accept header If it's not an RDF graph, return it without any special handling """ graph = self.get_graph(response) if graph is not None: ...
[ "def", "output", "(", "self", ",", "response", ",", "accepts", ")", ":", "graph", "=", "self", ".", "get_graph", "(", "response", ")", "if", "graph", "is", "not", "None", ":", "# decide the format", "mimetype", ",", "format", "=", "self", ".", "format_se...
Formats a response from a view to handle any RDF graphs If a view function returns an RDF graph, serialize it based on Accept header If it's not an RDF graph, return it without any special handling
[ "Formats", "a", "response", "from", "a", "view", "to", "handle", "any", "RDF", "graphs", "If", "a", "view", "function", "returns", "an", "RDF", "graph", "serialize", "it", "based", "on", "Accept", "header", "If", "it", "s", "not", "an", "RDF", "graph", ...
9bf86023288171eb0665c15fb28070250f80310c
https://github.com/hufman/flask_rdf/blob/9bf86023288171eb0665c15fb28070250f80310c/flask_rdf/common_decorators.py#L45-L68
train
hufman/flask_rdf
flask_rdf/common_decorators.py
ViewDecorator.decorate
def decorate(self, view): """ Wraps a view function to return formatted RDF graphs Uses content negotiation to serialize the graph to the client-preferred format Passes other content through unmodified """ from functools import wraps @wraps(view) def decorated(*args, **kwargs): response = view...
python
def decorate(self, view): """ Wraps a view function to return formatted RDF graphs Uses content negotiation to serialize the graph to the client-preferred format Passes other content through unmodified """ from functools import wraps @wraps(view) def decorated(*args, **kwargs): response = view...
[ "def", "decorate", "(", "self", ",", "view", ")", ":", "from", "functools", "import", "wraps", "@", "wraps", "(", "view", ")", "def", "decorated", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "response", "=", "view", "(", "*", "args", ",", ...
Wraps a view function to return formatted RDF graphs Uses content negotiation to serialize the graph to the client-preferred format Passes other content through unmodified
[ "Wraps", "a", "view", "function", "to", "return", "formatted", "RDF", "graphs", "Uses", "content", "negotiation", "to", "serialize", "the", "graph", "to", "the", "client", "-", "preferred", "format", "Passes", "other", "content", "through", "unmodified" ]
9bf86023288171eb0665c15fb28070250f80310c
https://github.com/hufman/flask_rdf/blob/9bf86023288171eb0665c15fb28070250f80310c/flask_rdf/common_decorators.py#L70-L82
train
Duke-QCD/hic
hic/initial.py
IC.ecc
def ecc(self, n): r""" Calculate eccentricity harmonic `\varepsilon_n`. :param int n: Eccentricity order. """ ny, nx = self._profile.shape xmax, ymax = self._xymax xcm, ycm = self._cm # create (X, Y) grids relative to CM Y, X = np.mgrid[ymax:-ym...
python
def ecc(self, n): r""" Calculate eccentricity harmonic `\varepsilon_n`. :param int n: Eccentricity order. """ ny, nx = self._profile.shape xmax, ymax = self._xymax xcm, ycm = self._cm # create (X, Y) grids relative to CM Y, X = np.mgrid[ymax:-ym...
[ "def", "ecc", "(", "self", ",", "n", ")", ":", "ny", ",", "nx", "=", "self", ".", "_profile", ".", "shape", "xmax", ",", "ymax", "=", "self", ".", "_xymax", "xcm", ",", "ycm", "=", "self", ".", "_cm", "# create (X, Y) grids relative to CM", "Y", ",",...
r""" Calculate eccentricity harmonic `\varepsilon_n`. :param int n: Eccentricity order.
[ "r", "Calculate", "eccentricity", "harmonic", "\\", "varepsilon_n", "." ]
9afb141735b1ac228d296a2349225d2bdcdb68f0
https://github.com/Duke-QCD/hic/blob/9afb141735b1ac228d296a2349225d2bdcdb68f0/hic/initial.py#L63-L102
train
alefnula/tea
tea/dsa/config.py
Config.get
def get(self, var, default=None): """Return a value from configuration. Safe version which always returns a default value if the value is not found. """ try: return self.__get(var) except (KeyError, IndexError): return default
python
def get(self, var, default=None): """Return a value from configuration. Safe version which always returns a default value if the value is not found. """ try: return self.__get(var) except (KeyError, IndexError): return default
[ "def", "get", "(", "self", ",", "var", ",", "default", "=", "None", ")", ":", "try", ":", "return", "self", ".", "__get", "(", "var", ")", "except", "(", "KeyError", ",", "IndexError", ")", ":", "return", "default" ]
Return a value from configuration. Safe version which always returns a default value if the value is not found.
[ "Return", "a", "value", "from", "configuration", "." ]
f5a0a724a425ec4f9dd2c7fe966ef06faf3a15a3
https://github.com/alefnula/tea/blob/f5a0a724a425ec4f9dd2c7fe966ef06faf3a15a3/tea/dsa/config.py#L211-L220
train
alefnula/tea
tea/dsa/config.py
Config.insert
def insert(self, var, value, index=None): """Insert at the index. If the index is not provided appends to the end of the list. """ current = self.__get(var) if not isinstance(current, list): raise KeyError("%s: is not a list" % var) if index is None: ...
python
def insert(self, var, value, index=None): """Insert at the index. If the index is not provided appends to the end of the list. """ current = self.__get(var) if not isinstance(current, list): raise KeyError("%s: is not a list" % var) if index is None: ...
[ "def", "insert", "(", "self", ",", "var", ",", "value", ",", "index", "=", "None", ")", ":", "current", "=", "self", ".", "__get", "(", "var", ")", "if", "not", "isinstance", "(", "current", ",", "list", ")", ":", "raise", "KeyError", "(", "\"%s: i...
Insert at the index. If the index is not provided appends to the end of the list.
[ "Insert", "at", "the", "index", "." ]
f5a0a724a425ec4f9dd2c7fe966ef06faf3a15a3
https://github.com/alefnula/tea/blob/f5a0a724a425ec4f9dd2c7fe966ef06faf3a15a3/tea/dsa/config.py#L238-L251
train
alefnula/tea
tea/dsa/config.py
MultiConfig.keys
def keys(self): """Return a merged set of top level keys from all configurations.""" s = set() for config in self.__configs: s |= config.keys() return s
python
def keys(self): """Return a merged set of top level keys from all configurations.""" s = set() for config in self.__configs: s |= config.keys() return s
[ "def", "keys", "(", "self", ")", ":", "s", "=", "set", "(", ")", "for", "config", "in", "self", ".", "__configs", ":", "s", "|=", "config", ".", "keys", "(", ")", "return", "s" ]
Return a merged set of top level keys from all configurations.
[ "Return", "a", "merged", "set", "of", "top", "level", "keys", "from", "all", "configurations", "." ]
f5a0a724a425ec4f9dd2c7fe966ef06faf3a15a3
https://github.com/alefnula/tea/blob/f5a0a724a425ec4f9dd2c7fe966ef06faf3a15a3/tea/dsa/config.py#L328-L333
train
alefnula/tea
tea/logger/win_handlers.py
FileHandler.close
def close(self): """Close the stream.""" self.flush() self.stream.close() logging.StreamHandler.close(self)
python
def close(self): """Close the stream.""" self.flush() self.stream.close() logging.StreamHandler.close(self)
[ "def", "close", "(", "self", ")", ":", "self", ".", "flush", "(", ")", "self", ".", "stream", ".", "close", "(", ")", "logging", ".", "StreamHandler", ".", "close", "(", "self", ")" ]
Close the stream.
[ "Close", "the", "stream", "." ]
f5a0a724a425ec4f9dd2c7fe966ef06faf3a15a3
https://github.com/alefnula/tea/blob/f5a0a724a425ec4f9dd2c7fe966ef06faf3a15a3/tea/logger/win_handlers.py#L22-L26
train
alefnula/tea
tea/logger/win_handlers.py
BaseRotatingHandler.emit
def emit(self, record): """Emit a record. Output the record to the file, catering for rollover as described in doRollover(). """ try: if self.shouldRollover(record): self.doRollover() FileHandler.emit(self, record) except (Keyboard...
python
def emit(self, record): """Emit a record. Output the record to the file, catering for rollover as described in doRollover(). """ try: if self.shouldRollover(record): self.doRollover() FileHandler.emit(self, record) except (Keyboard...
[ "def", "emit", "(", "self", ",", "record", ")", ":", "try", ":", "if", "self", ".", "shouldRollover", "(", "record", ")", ":", "self", ".", "doRollover", "(", ")", "FileHandler", ".", "emit", "(", "self", ",", "record", ")", "except", "(", "KeyboardI...
Emit a record. Output the record to the file, catering for rollover as described in doRollover().
[ "Emit", "a", "record", "." ]
f5a0a724a425ec4f9dd2c7fe966ef06faf3a15a3
https://github.com/alefnula/tea/blob/f5a0a724a425ec4f9dd2c7fe966ef06faf3a15a3/tea/logger/win_handlers.py#L42-L55
train
alefnula/tea
tea/logger/win_handlers.py
RotatingFileHandler.doRollover
def doRollover(self): """Do a rollover, as described in __init__().""" self.stream.close() try: if self.backupCount > 0: tmp_location = "%s.0" % self.baseFilename os.rename(self.baseFilename, tmp_location) for i in range(self.backupCoun...
python
def doRollover(self): """Do a rollover, as described in __init__().""" self.stream.close() try: if self.backupCount > 0: tmp_location = "%s.0" % self.baseFilename os.rename(self.baseFilename, tmp_location) for i in range(self.backupCoun...
[ "def", "doRollover", "(", "self", ")", ":", "self", ".", "stream", ".", "close", "(", ")", "try", ":", "if", "self", ".", "backupCount", ">", "0", ":", "tmp_location", "=", "\"%s.0\"", "%", "self", ".", "baseFilename", "os", ".", "rename", "(", "self...
Do a rollover, as described in __init__().
[ "Do", "a", "rollover", "as", "described", "in", "__init__", "()", "." ]
f5a0a724a425ec4f9dd2c7fe966ef06faf3a15a3
https://github.com/alefnula/tea/blob/f5a0a724a425ec4f9dd2c7fe966ef06faf3a15a3/tea/logger/win_handlers.py#L93-L114
train
alefnula/tea
tea/logger/win_handlers.py
RotatingFileHandler.shouldRollover
def shouldRollover(self, record): """Determine if rollover should occur. Basically, see if the supplied record would cause the file to exceed the size limit we have. """ if self.maxBytes > 0: # are we rolling over? msg = "%s\n" % self.format(record) self...
python
def shouldRollover(self, record): """Determine if rollover should occur. Basically, see if the supplied record would cause the file to exceed the size limit we have. """ if self.maxBytes > 0: # are we rolling over? msg = "%s\n" % self.format(record) self...
[ "def", "shouldRollover", "(", "self", ",", "record", ")", ":", "if", "self", ".", "maxBytes", ">", "0", ":", "# are we rolling over?", "msg", "=", "\"%s\\n\"", "%", "self", ".", "format", "(", "record", ")", "self", ".", "stream", ".", "seek", "(", "0"...
Determine if rollover should occur. Basically, see if the supplied record would cause the file to exceed the size limit we have.
[ "Determine", "if", "rollover", "should", "occur", "." ]
f5a0a724a425ec4f9dd2c7fe966ef06faf3a15a3
https://github.com/alefnula/tea/blob/f5a0a724a425ec4f9dd2c7fe966ef06faf3a15a3/tea/logger/win_handlers.py#L116-L127
train
alefnula/tea
tea/shell/__init__.py
split
def split(s, posix=True): """Split the string s using shell-like syntax. Args: s (str): String to split posix (bool): Use posix split Returns: list of str: List of string parts """ if isinstance(s, six.binary_type): s = s.decode("utf-8") return shlex.split(s, po...
python
def split(s, posix=True): """Split the string s using shell-like syntax. Args: s (str): String to split posix (bool): Use posix split Returns: list of str: List of string parts """ if isinstance(s, six.binary_type): s = s.decode("utf-8") return shlex.split(s, po...
[ "def", "split", "(", "s", ",", "posix", "=", "True", ")", ":", "if", "isinstance", "(", "s", ",", "six", ".", "binary_type", ")", ":", "s", "=", "s", ".", "decode", "(", "\"utf-8\"", ")", "return", "shlex", ".", "split", "(", "s", ",", "posix", ...
Split the string s using shell-like syntax. Args: s (str): String to split posix (bool): Use posix split Returns: list of str: List of string parts
[ "Split", "the", "string", "s", "using", "shell", "-", "like", "syntax", "." ]
f5a0a724a425ec4f9dd2c7fe966ef06faf3a15a3
https://github.com/alefnula/tea/blob/f5a0a724a425ec4f9dd2c7fe966ef06faf3a15a3/tea/shell/__init__.py#L25-L37
train
alefnula/tea
tea/shell/__init__.py
search
def search(path, matcher="*", dirs=False, files=True): """Recursive search function. Args: path (str): Path to search recursively matcher (str or callable): String pattern to search for or function that returns True/False for a file argument dirs (bool): if True returns dire...
python
def search(path, matcher="*", dirs=False, files=True): """Recursive search function. Args: path (str): Path to search recursively matcher (str or callable): String pattern to search for or function that returns True/False for a file argument dirs (bool): if True returns dire...
[ "def", "search", "(", "path", ",", "matcher", "=", "\"*\"", ",", "dirs", "=", "False", ",", "files", "=", "True", ")", ":", "if", "callable", "(", "matcher", ")", ":", "def", "fnmatcher", "(", "items", ")", ":", "return", "list", "(", "filter", "("...
Recursive search function. Args: path (str): Path to search recursively matcher (str or callable): String pattern to search for or function that returns True/False for a file argument dirs (bool): if True returns directories that match the pattern files(bool): if True re...
[ "Recursive", "search", "function", "." ]
f5a0a724a425ec4f9dd2c7fe966ef06faf3a15a3
https://github.com/alefnula/tea/blob/f5a0a724a425ec4f9dd2c7fe966ef06faf3a15a3/tea/shell/__init__.py#L40-L70
train
alefnula/tea
tea/shell/__init__.py
chdir
def chdir(directory): """Change the current working directory. Args: directory (str): Directory to go to. """ directory = os.path.abspath(directory) logger.info("chdir -> %s" % directory) try: if not os.path.isdir(directory): logger.error( "chdir -> %...
python
def chdir(directory): """Change the current working directory. Args: directory (str): Directory to go to. """ directory = os.path.abspath(directory) logger.info("chdir -> %s" % directory) try: if not os.path.isdir(directory): logger.error( "chdir -> %...
[ "def", "chdir", "(", "directory", ")", ":", "directory", "=", "os", ".", "path", ".", "abspath", "(", "directory", ")", "logger", ".", "info", "(", "\"chdir -> %s\"", "%", "directory", ")", "try", ":", "if", "not", "os", ".", "path", ".", "isdir", "(...
Change the current working directory. Args: directory (str): Directory to go to.
[ "Change", "the", "current", "working", "directory", "." ]
f5a0a724a425ec4f9dd2c7fe966ef06faf3a15a3
https://github.com/alefnula/tea/blob/f5a0a724a425ec4f9dd2c7fe966ef06faf3a15a3/tea/shell/__init__.py#L73-L91
train
alefnula/tea
tea/shell/__init__.py
goto
def goto(directory, create=False): """Context object for changing directory. Args: directory (str): Directory to go to. create (bool): Create directory if it doesn't exists. Usage:: >>> with goto(directory) as ok: ... if not ok: ... print 'Error' ...
python
def goto(directory, create=False): """Context object for changing directory. Args: directory (str): Directory to go to. create (bool): Create directory if it doesn't exists. Usage:: >>> with goto(directory) as ok: ... if not ok: ... print 'Error' ...
[ "def", "goto", "(", "directory", ",", "create", "=", "False", ")", ":", "current", "=", "os", ".", "getcwd", "(", ")", "directory", "=", "os", ".", "path", ".", "abspath", "(", "directory", ")", "if", "os", ".", "path", ".", "isdir", "(", "director...
Context object for changing directory. Args: directory (str): Directory to go to. create (bool): Create directory if it doesn't exists. Usage:: >>> with goto(directory) as ok: ... if not ok: ... print 'Error' ... else: ... print ...
[ "Context", "object", "for", "changing", "directory", "." ]
f5a0a724a425ec4f9dd2c7fe966ef06faf3a15a3
https://github.com/alefnula/tea/blob/f5a0a724a425ec4f9dd2c7fe966ef06faf3a15a3/tea/shell/__init__.py#L95-L127
train
alefnula/tea
tea/shell/__init__.py
mkdir
def mkdir(path, mode=0o755, delete=False): """Make a directory. Create a leaf directory and all intermediate ones. Works like ``mkdir``, except that any intermediate path segment (not just the rightmost) will be created if it does not exist. This is recursive. Args: path (str): Directory t...
python
def mkdir(path, mode=0o755, delete=False): """Make a directory. Create a leaf directory and all intermediate ones. Works like ``mkdir``, except that any intermediate path segment (not just the rightmost) will be created if it does not exist. This is recursive. Args: path (str): Directory t...
[ "def", "mkdir", "(", "path", ",", "mode", "=", "0o755", ",", "delete", "=", "False", ")", ":", "logger", ".", "info", "(", "\"mkdir: %s\"", "%", "path", ")", "if", "os", ".", "path", ".", "isdir", "(", "path", ")", ":", "if", "not", "delete", ":"...
Make a directory. Create a leaf directory and all intermediate ones. Works like ``mkdir``, except that any intermediate path segment (not just the rightmost) will be created if it does not exist. This is recursive. Args: path (str): Directory to create mode (int): Directory mode ...
[ "Make", "a", "directory", "." ]
f5a0a724a425ec4f9dd2c7fe966ef06faf3a15a3
https://github.com/alefnula/tea/blob/f5a0a724a425ec4f9dd2c7fe966ef06faf3a15a3/tea/shell/__init__.py#L130-L156
train
alefnula/tea
tea/shell/__init__.py
__copyfile
def __copyfile(source, destination): """Copy data and mode bits ("cp source destination"). The destination may be a directory. Args: source (str): Source file (file to copy). destination (str): Destination file or directory (where to copy). Returns: bool: True if the operation...
python
def __copyfile(source, destination): """Copy data and mode bits ("cp source destination"). The destination may be a directory. Args: source (str): Source file (file to copy). destination (str): Destination file or directory (where to copy). Returns: bool: True if the operation...
[ "def", "__copyfile", "(", "source", ",", "destination", ")", ":", "logger", ".", "info", "(", "\"copyfile: %s -> %s\"", "%", "(", "source", ",", "destination", ")", ")", "try", ":", "__create_destdir", "(", "destination", ")", "shutil", ".", "copy", "(", "...
Copy data and mode bits ("cp source destination"). The destination may be a directory. Args: source (str): Source file (file to copy). destination (str): Destination file or directory (where to copy). Returns: bool: True if the operation is successful, False otherwise.
[ "Copy", "data", "and", "mode", "bits", "(", "cp", "source", "destination", ")", "." ]
f5a0a724a425ec4f9dd2c7fe966ef06faf3a15a3
https://github.com/alefnula/tea/blob/f5a0a724a425ec4f9dd2c7fe966ef06faf3a15a3/tea/shell/__init__.py#L166-L187
train
alefnula/tea
tea/shell/__init__.py
__copyfile2
def __copyfile2(source, destination): """Copy data and all stat info ("cp -p source destination"). The destination may be a directory. Args: source (str): Source file (file to copy). destination (str): Destination file or directory (where to copy). Returns: bool: True if the o...
python
def __copyfile2(source, destination): """Copy data and all stat info ("cp -p source destination"). The destination may be a directory. Args: source (str): Source file (file to copy). destination (str): Destination file or directory (where to copy). Returns: bool: True if the o...
[ "def", "__copyfile2", "(", "source", ",", "destination", ")", ":", "logger", ".", "info", "(", "\"copyfile2: %s -> %s\"", "%", "(", "source", ",", "destination", ")", ")", "try", ":", "__create_destdir", "(", "destination", ")", "shutil", ".", "copy2", "(", ...
Copy data and all stat info ("cp -p source destination"). The destination may be a directory. Args: source (str): Source file (file to copy). destination (str): Destination file or directory (where to copy). Returns: bool: True if the operation is successful, False otherwise.
[ "Copy", "data", "and", "all", "stat", "info", "(", "cp", "-", "p", "source", "destination", ")", "." ]
f5a0a724a425ec4f9dd2c7fe966ef06faf3a15a3
https://github.com/alefnula/tea/blob/f5a0a724a425ec4f9dd2c7fe966ef06faf3a15a3/tea/shell/__init__.py#L190-L211
train
alefnula/tea
tea/shell/__init__.py
__copytree
def __copytree(source, destination, symlinks=False): """Copy a directory tree recursively using copy2(). The destination directory must not already exist. If the optional symlinks flag is true, symbolic links in the source tree result in symbolic links in the destination tree; if it is false, the ...
python
def __copytree(source, destination, symlinks=False): """Copy a directory tree recursively using copy2(). The destination directory must not already exist. If the optional symlinks flag is true, symbolic links in the source tree result in symbolic links in the destination tree; if it is false, the ...
[ "def", "__copytree", "(", "source", ",", "destination", ",", "symlinks", "=", "False", ")", ":", "logger", ".", "info", "(", "\"copytree: %s -> %s\"", "%", "(", "source", ",", "destination", ")", ")", "try", ":", "__create_destdir", "(", "destination", ")", ...
Copy a directory tree recursively using copy2(). The destination directory must not already exist. If the optional symlinks flag is true, symbolic links in the source tree result in symbolic links in the destination tree; if it is false, the contents of the files pointed to by symbolic links are c...
[ "Copy", "a", "directory", "tree", "recursively", "using", "copy2", "()", "." ]
f5a0a724a425ec4f9dd2c7fe966ef06faf3a15a3
https://github.com/alefnula/tea/blob/f5a0a724a425ec4f9dd2c7fe966ef06faf3a15a3/tea/shell/__init__.py#L214-L241
train
alefnula/tea
tea/shell/__init__.py
copy
def copy(source, destination): """Copy file or directory. Args: source (str): Source file or directory destination (str): Destination file or directory (where to copy). Returns: bool: True if the operation is successful, False otherwise. """ if os.path.isdir(source): ...
python
def copy(source, destination): """Copy file or directory. Args: source (str): Source file or directory destination (str): Destination file or directory (where to copy). Returns: bool: True if the operation is successful, False otherwise. """ if os.path.isdir(source): ...
[ "def", "copy", "(", "source", ",", "destination", ")", ":", "if", "os", ".", "path", ".", "isdir", "(", "source", ")", ":", "return", "__copytree", "(", "source", ",", "destination", ")", "else", ":", "return", "__copyfile2", "(", "source", ",", "desti...
Copy file or directory. Args: source (str): Source file or directory destination (str): Destination file or directory (where to copy). Returns: bool: True if the operation is successful, False otherwise.
[ "Copy", "file", "or", "directory", "." ]
f5a0a724a425ec4f9dd2c7fe966ef06faf3a15a3
https://github.com/alefnula/tea/blob/f5a0a724a425ec4f9dd2c7fe966ef06faf3a15a3/tea/shell/__init__.py#L244-L257
train
alefnula/tea
tea/shell/__init__.py
gcopy
def gcopy(pattern, destination): """Copy all file found by glob.glob(pattern) to destination directory. Args: pattern (str): Glob pattern destination (str): Path to the destination directory. Returns: bool: True if the operation is successful, False otherwise. """ for item ...
python
def gcopy(pattern, destination): """Copy all file found by glob.glob(pattern) to destination directory. Args: pattern (str): Glob pattern destination (str): Path to the destination directory. Returns: bool: True if the operation is successful, False otherwise. """ for item ...
[ "def", "gcopy", "(", "pattern", ",", "destination", ")", ":", "for", "item", "in", "glob", ".", "glob", "(", "pattern", ")", ":", "if", "not", "copy", "(", "item", ",", "destination", ")", ":", "return", "False", "return", "True" ]
Copy all file found by glob.glob(pattern) to destination directory. Args: pattern (str): Glob pattern destination (str): Path to the destination directory. Returns: bool: True if the operation is successful, False otherwise.
[ "Copy", "all", "file", "found", "by", "glob", ".", "glob", "(", "pattern", ")", "to", "destination", "directory", "." ]
f5a0a724a425ec4f9dd2c7fe966ef06faf3a15a3
https://github.com/alefnula/tea/blob/f5a0a724a425ec4f9dd2c7fe966ef06faf3a15a3/tea/shell/__init__.py#L260-L273
train
alefnula/tea
tea/shell/__init__.py
move
def move(source, destination): """Move a file or directory (recursively) to another location. If the destination is on our current file system, then simply use rename. Otherwise, copy source to the destination and then remove source. Args: source (str): Source file or directory (file or di...
python
def move(source, destination): """Move a file or directory (recursively) to another location. If the destination is on our current file system, then simply use rename. Otherwise, copy source to the destination and then remove source. Args: source (str): Source file or directory (file or di...
[ "def", "move", "(", "source", ",", "destination", ")", ":", "logger", ".", "info", "(", "\"Move: %s -> %s\"", "%", "(", "source", ",", "destination", ")", ")", "try", ":", "__create_destdir", "(", "destination", ")", "shutil", ".", "move", "(", "source", ...
Move a file or directory (recursively) to another location. If the destination is on our current file system, then simply use rename. Otherwise, copy source to the destination and then remove source. Args: source (str): Source file or directory (file or directory to move). destination ...
[ "Move", "a", "file", "or", "directory", "(", "recursively", ")", "to", "another", "location", "." ]
f5a0a724a425ec4f9dd2c7fe966ef06faf3a15a3
https://github.com/alefnula/tea/blob/f5a0a724a425ec4f9dd2c7fe966ef06faf3a15a3/tea/shell/__init__.py#L276-L297
train
alefnula/tea
tea/shell/__init__.py
gmove
def gmove(pattern, destination): """Move all file found by glob.glob(pattern) to destination directory. Args: pattern (str): Glob pattern destination (str): Path to the destination directory. Returns: bool: True if the operation is successful, False otherwise. """ for item ...
python
def gmove(pattern, destination): """Move all file found by glob.glob(pattern) to destination directory. Args: pattern (str): Glob pattern destination (str): Path to the destination directory. Returns: bool: True if the operation is successful, False otherwise. """ for item ...
[ "def", "gmove", "(", "pattern", ",", "destination", ")", ":", "for", "item", "in", "glob", ".", "glob", "(", "pattern", ")", ":", "if", "not", "move", "(", "item", ",", "destination", ")", ":", "return", "False", "return", "True" ]
Move all file found by glob.glob(pattern) to destination directory. Args: pattern (str): Glob pattern destination (str): Path to the destination directory. Returns: bool: True if the operation is successful, False otherwise.
[ "Move", "all", "file", "found", "by", "glob", ".", "glob", "(", "pattern", ")", "to", "destination", "directory", "." ]
f5a0a724a425ec4f9dd2c7fe966ef06faf3a15a3
https://github.com/alefnula/tea/blob/f5a0a724a425ec4f9dd2c7fe966ef06faf3a15a3/tea/shell/__init__.py#L300-L313
train