repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
absent1706/sqlalchemy-mixins
sqlalchemy_mixins/serialize.py
SerializeMixin.to_dict
def to_dict(self, nested=False): """Return dict object with model's data. :param nested: flag to return nested relationships' data if true :type: bool :return: dict """ result = dict() for key in self.columns: result[key] = getattr(self, key) if nested: for key in self.relations: obj = getattr(self, key) if isinstance(obj, SerializeMixin): result[key] = obj.to_dict() elif isinstance(obj, Iterable): result[key] = [o.to_dict() for o in obj] return result
python
def to_dict(self, nested=False): """Return dict object with model's data. :param nested: flag to return nested relationships' data if true :type: bool :return: dict """ result = dict() for key in self.columns: result[key] = getattr(self, key) if nested: for key in self.relations: obj = getattr(self, key) if isinstance(obj, SerializeMixin): result[key] = obj.to_dict() elif isinstance(obj, Iterable): result[key] = [o.to_dict() for o in obj] return result
[ "def", "to_dict", "(", "self", ",", "nested", "=", "False", ")", ":", "result", "=", "dict", "(", ")", "for", "key", "in", "self", ".", "columns", ":", "result", "[", "key", "]", "=", "getattr", "(", "self", ",", "key", ")", "if", "nested", ":", ...
Return dict object with model's data. :param nested: flag to return nested relationships' data if true :type: bool :return: dict
[ "Return", "dict", "object", "with", "model", "s", "data", "." ]
a111e69fc5edc5d81a31dca45755f21c8c512ed1
https://github.com/absent1706/sqlalchemy-mixins/blob/a111e69fc5edc5d81a31dca45755f21c8c512ed1/sqlalchemy_mixins/serialize.py#L11-L31
train
34,300
absent1706/sqlalchemy-mixins
sqlalchemy_mixins/inspection.py
InspectionMixin.primary_keys_full
def primary_keys_full(cls): """Get primary key properties for a SQLAlchemy cls. Taken from marshmallow_sqlalchemy """ mapper = cls.__mapper__ return [ mapper.get_property_by_column(column) for column in mapper.primary_key ]
python
def primary_keys_full(cls): """Get primary key properties for a SQLAlchemy cls. Taken from marshmallow_sqlalchemy """ mapper = cls.__mapper__ return [ mapper.get_property_by_column(column) for column in mapper.primary_key ]
[ "def", "primary_keys_full", "(", "cls", ")", ":", "mapper", "=", "cls", ".", "__mapper__", "return", "[", "mapper", ".", "get_property_by_column", "(", "column", ")", "for", "column", "in", "mapper", ".", "primary_key", "]" ]
Get primary key properties for a SQLAlchemy cls. Taken from marshmallow_sqlalchemy
[ "Get", "primary", "key", "properties", "for", "a", "SQLAlchemy", "cls", ".", "Taken", "from", "marshmallow_sqlalchemy" ]
a111e69fc5edc5d81a31dca45755f21c8c512ed1
https://github.com/absent1706/sqlalchemy-mixins/blob/a111e69fc5edc5d81a31dca45755f21c8c512ed1/sqlalchemy_mixins/inspection.py#L20-L28
train
34,301
absent1706/sqlalchemy-mixins
sqlalchemy_mixins/activerecord.py
ActiveRecordMixin.save
def save(self): """Saves the updated model to the current entity db. """ self.session.add(self) self.session.flush() return self
python
def save(self): """Saves the updated model to the current entity db. """ self.session.add(self) self.session.flush() return self
[ "def", "save", "(", "self", ")", ":", "self", ".", "session", ".", "add", "(", "self", ")", "self", ".", "session", ".", "flush", "(", ")", "return", "self" ]
Saves the updated model to the current entity db.
[ "Saves", "the", "updated", "model", "to", "the", "current", "entity", "db", "." ]
a111e69fc5edc5d81a31dca45755f21c8c512ed1
https://github.com/absent1706/sqlalchemy-mixins/blob/a111e69fc5edc5d81a31dca45755f21c8c512ed1/sqlalchemy_mixins/activerecord.py#L26-L31
train
34,302
diogobaeder/pycket
pycket/session.py
SessionManager.get
def get(self, name, default=None): ''' Gets the object for "name", or None if there's no such object. If "default" is provided, return it if no object is found. ''' session = self.__get_session_from_db() return session.get(name, default)
python
def get(self, name, default=None): ''' Gets the object for "name", or None if there's no such object. If "default" is provided, return it if no object is found. ''' session = self.__get_session_from_db() return session.get(name, default)
[ "def", "get", "(", "self", ",", "name", ",", "default", "=", "None", ")", ":", "session", "=", "self", ".", "__get_session_from_db", "(", ")", "return", "session", ".", "get", "(", "name", ",", "default", ")" ]
Gets the object for "name", or None if there's no such object. If "default" is provided, return it if no object is found.
[ "Gets", "the", "object", "for", "name", "or", "None", "if", "there", "s", "no", "such", "object", ".", "If", "default", "is", "provided", "return", "it", "if", "no", "object", "is", "found", "." ]
b21d1553b4100d820a6922eeb55baa2329bc02c2
https://github.com/diogobaeder/pycket/blob/b21d1553b4100d820a6922eeb55baa2329bc02c2/pycket/session.py#L89-L97
train
34,303
diogobaeder/pycket
pycket/session.py
SessionManager.delete
def delete(self, *names): ''' Deletes the object with "name" from the session, if exists. ''' def change(session): keys = session.keys() names_in_common = [name for name in names if name in keys] for name in names_in_common: del session[name] self.__change_session(change)
python
def delete(self, *names): ''' Deletes the object with "name" from the session, if exists. ''' def change(session): keys = session.keys() names_in_common = [name for name in names if name in keys] for name in names_in_common: del session[name] self.__change_session(change)
[ "def", "delete", "(", "self", ",", "*", "names", ")", ":", "def", "change", "(", "session", ")", ":", "keys", "=", "session", ".", "keys", "(", ")", "names_in_common", "=", "[", "name", "for", "name", "in", "names", "if", "name", "in", "keys", "]",...
Deletes the object with "name" from the session, if exists.
[ "Deletes", "the", "object", "with", "name", "from", "the", "session", "if", "exists", "." ]
b21d1553b4100d820a6922eeb55baa2329bc02c2
https://github.com/diogobaeder/pycket/blob/b21d1553b4100d820a6922eeb55baa2329bc02c2/pycket/session.py#L99-L109
train
34,304
occrp-attic/exactitude
exactitude/date.py
DateType.validate
def validate(self, obj, **kwargs): """Check if a thing is a valid date.""" obj = stringify(obj) if obj is None: return False return self.DATE_RE.match(obj) is not None
python
def validate(self, obj, **kwargs): """Check if a thing is a valid date.""" obj = stringify(obj) if obj is None: return False return self.DATE_RE.match(obj) is not None
[ "def", "validate", "(", "self", ",", "obj", ",", "*", "*", "kwargs", ")", ":", "obj", "=", "stringify", "(", "obj", ")", "if", "obj", "is", "None", ":", "return", "False", "return", "self", ".", "DATE_RE", ".", "match", "(", "obj", ")", "is", "no...
Check if a thing is a valid date.
[ "Check", "if", "a", "thing", "is", "a", "valid", "date", "." ]
9fe13aa70f1aac644dbc999e0b21683db507f02d
https://github.com/occrp-attic/exactitude/blob/9fe13aa70f1aac644dbc999e0b21683db507f02d/exactitude/date.py#L18-L23
train
34,305
occrp-attic/exactitude
exactitude/date.py
DateType._clean_datetime
def _clean_datetime(self, obj): """Python objects want to be text.""" if isinstance(obj, datetime): # if it's not naive, put it on zulu time first: if obj.tzinfo is not None: obj = obj.astimezone(pytz.utc) return obj.isoformat()[:self.MAX_LENGTH] if isinstance(obj, date): return obj.isoformat()
python
def _clean_datetime(self, obj): """Python objects want to be text.""" if isinstance(obj, datetime): # if it's not naive, put it on zulu time first: if obj.tzinfo is not None: obj = obj.astimezone(pytz.utc) return obj.isoformat()[:self.MAX_LENGTH] if isinstance(obj, date): return obj.isoformat()
[ "def", "_clean_datetime", "(", "self", ",", "obj", ")", ":", "if", "isinstance", "(", "obj", ",", "datetime", ")", ":", "# if it's not naive, put it on zulu time first:", "if", "obj", ".", "tzinfo", "is", "not", "None", ":", "obj", "=", "obj", ".", "astimezo...
Python objects want to be text.
[ "Python", "objects", "want", "to", "be", "text", "." ]
9fe13aa70f1aac644dbc999e0b21683db507f02d
https://github.com/occrp-attic/exactitude/blob/9fe13aa70f1aac644dbc999e0b21683db507f02d/exactitude/date.py#L25-L33
train
34,306
incf-nidash/nidmresults
nidmresults/exporter.py
NIDMExporter.parse
def parse(self): """ Parse a result directory to extract the pieces information to be stored in NIDM-Results. """ try: # Methods: find_software, find_model_fitting, find_contrasts and # find_inferences should be defined in the children classes and # return a list of NIDM Objects as specified in the objects module # Object of type Software describing the neuroimaging software # package used for the analysis self.software = self._find_software() # List of objects of type ModelFitting describing the # model fitting step in NIDM-Results (main activity: Model # Parameters Estimation) self.model_fittings = self._find_model_fitting() # Dictionary of (key, value) pairs where where key is a tuple # containing the identifier of a ModelParametersEstimation object # and a tuple of identifiers of ParameterEstimateMap objects and # value is an object of type Contrast describing the contrast # estimation step in NIDM-Results (main activity: Contrast # Estimation) self.contrasts = self._find_contrasts() # Inference activity and entities # Dictionary of (key, value) pairs where key is the identifier of a # ContrastEstimation object and value is an object of type # Inference describing the inference step in NIDM-Results (main # activity: Inference) self.inferences = self._find_inferences() except Exception: self.cleanup() raise
python
def parse(self): """ Parse a result directory to extract the pieces information to be stored in NIDM-Results. """ try: # Methods: find_software, find_model_fitting, find_contrasts and # find_inferences should be defined in the children classes and # return a list of NIDM Objects as specified in the objects module # Object of type Software describing the neuroimaging software # package used for the analysis self.software = self._find_software() # List of objects of type ModelFitting describing the # model fitting step in NIDM-Results (main activity: Model # Parameters Estimation) self.model_fittings = self._find_model_fitting() # Dictionary of (key, value) pairs where where key is a tuple # containing the identifier of a ModelParametersEstimation object # and a tuple of identifiers of ParameterEstimateMap objects and # value is an object of type Contrast describing the contrast # estimation step in NIDM-Results (main activity: Contrast # Estimation) self.contrasts = self._find_contrasts() # Inference activity and entities # Dictionary of (key, value) pairs where key is the identifier of a # ContrastEstimation object and value is an object of type # Inference describing the inference step in NIDM-Results (main # activity: Inference) self.inferences = self._find_inferences() except Exception: self.cleanup() raise
[ "def", "parse", "(", "self", ")", ":", "try", ":", "# Methods: find_software, find_model_fitting, find_contrasts and", "# find_inferences should be defined in the children classes and", "# return a list of NIDM Objects as specified in the objects module", "# Object of type Software describing ...
Parse a result directory to extract the pieces information to be stored in NIDM-Results.
[ "Parse", "a", "result", "directory", "to", "extract", "the", "pieces", "information", "to", "be", "stored", "in", "NIDM", "-", "Results", "." ]
438f7cce6abc4a4379b629bd76f4d427891e033f
https://github.com/incf-nidash/nidmresults/blob/438f7cce6abc4a4379b629bd76f4d427891e033f/nidmresults/exporter.py#L81-L117
train
34,307
incf-nidash/nidmresults
nidmresults/exporter.py
NIDMExporter.add_object
def add_object(self, nidm_object, export_file=True): """ Add a NIDMObject to a NIDM-Results export. """ if not export_file: export_dir = None else: export_dir = self.export_dir if not isinstance(nidm_object, NIDMFile): nidm_object.export(self.version, export_dir) else: nidm_object.export(self.version, export_dir, self.prepend_path) # ProvDocument: add object to the bundle if nidm_object.prov_type == PROV['Activity']: self.bundle.activity(nidm_object.id, other_attributes=nidm_object.attributes) elif nidm_object.prov_type == PROV['Entity']: self.bundle.entity(nidm_object.id, other_attributes=nidm_object.attributes) elif nidm_object.prov_type == PROV['Agent']: self.bundle.agent(nidm_object.id, other_attributes=nidm_object.attributes)
python
def add_object(self, nidm_object, export_file=True): """ Add a NIDMObject to a NIDM-Results export. """ if not export_file: export_dir = None else: export_dir = self.export_dir if not isinstance(nidm_object, NIDMFile): nidm_object.export(self.version, export_dir) else: nidm_object.export(self.version, export_dir, self.prepend_path) # ProvDocument: add object to the bundle if nidm_object.prov_type == PROV['Activity']: self.bundle.activity(nidm_object.id, other_attributes=nidm_object.attributes) elif nidm_object.prov_type == PROV['Entity']: self.bundle.entity(nidm_object.id, other_attributes=nidm_object.attributes) elif nidm_object.prov_type == PROV['Agent']: self.bundle.agent(nidm_object.id, other_attributes=nidm_object.attributes)
[ "def", "add_object", "(", "self", ",", "nidm_object", ",", "export_file", "=", "True", ")", ":", "if", "not", "export_file", ":", "export_dir", "=", "None", "else", ":", "export_dir", "=", "self", ".", "export_dir", "if", "not", "isinstance", "(", "nidm_ob...
Add a NIDMObject to a NIDM-Results export.
[ "Add", "a", "NIDMObject", "to", "a", "NIDM", "-", "Results", "export", "." ]
438f7cce6abc4a4379b629bd76f4d427891e033f
https://github.com/incf-nidash/nidmresults/blob/438f7cce6abc4a4379b629bd76f4d427891e033f/nidmresults/exporter.py#L123-L145
train
34,308
incf-nidash/nidmresults
nidmresults/exporter.py
NIDMExporter._get_model_fitting
def _get_model_fitting(self, mf_id): """ Retreive model fitting with identifier 'mf_id' from the list of model fitting objects stored in self.model_fitting """ for model_fitting in self.model_fittings: if model_fitting.activity.id == mf_id: return model_fitting raise Exception("Model fitting activity with id: " + str(mf_id) + " not found.")
python
def _get_model_fitting(self, mf_id): """ Retreive model fitting with identifier 'mf_id' from the list of model fitting objects stored in self.model_fitting """ for model_fitting in self.model_fittings: if model_fitting.activity.id == mf_id: return model_fitting raise Exception("Model fitting activity with id: " + str(mf_id) + " not found.")
[ "def", "_get_model_fitting", "(", "self", ",", "mf_id", ")", ":", "for", "model_fitting", "in", "self", ".", "model_fittings", ":", "if", "model_fitting", ".", "activity", ".", "id", "==", "mf_id", ":", "return", "model_fitting", "raise", "Exception", "(", "...
Retreive model fitting with identifier 'mf_id' from the list of model fitting objects stored in self.model_fitting
[ "Retreive", "model", "fitting", "with", "identifier", "mf_id", "from", "the", "list", "of", "model", "fitting", "objects", "stored", "in", "self", ".", "model_fitting" ]
438f7cce6abc4a4379b629bd76f4d427891e033f
https://github.com/incf-nidash/nidmresults/blob/438f7cce6abc4a4379b629bd76f4d427891e033f/nidmresults/exporter.py#L534-L544
train
34,309
incf-nidash/nidmresults
nidmresults/exporter.py
NIDMExporter._get_contrast
def _get_contrast(self, con_id): """ Retreive contrast with identifier 'con_id' from the list of contrast objects stored in self.contrasts """ for contrasts in list(self.contrasts.values()): for contrast in contrasts: if contrast.estimation.id == con_id: return contrast raise Exception("Contrast activity with id: " + str(con_id) + " not found.")
python
def _get_contrast(self, con_id): """ Retreive contrast with identifier 'con_id' from the list of contrast objects stored in self.contrasts """ for contrasts in list(self.contrasts.values()): for contrast in contrasts: if contrast.estimation.id == con_id: return contrast raise Exception("Contrast activity with id: " + str(con_id) + " not found.")
[ "def", "_get_contrast", "(", "self", ",", "con_id", ")", ":", "for", "contrasts", "in", "list", "(", "self", ".", "contrasts", ".", "values", "(", ")", ")", ":", "for", "contrast", "in", "contrasts", ":", "if", "contrast", ".", "estimation", ".", "id",...
Retreive contrast with identifier 'con_id' from the list of contrast objects stored in self.contrasts
[ "Retreive", "contrast", "with", "identifier", "con_id", "from", "the", "list", "of", "contrast", "objects", "stored", "in", "self", ".", "contrasts" ]
438f7cce6abc4a4379b629bd76f4d427891e033f
https://github.com/incf-nidash/nidmresults/blob/438f7cce6abc4a4379b629bd76f4d427891e033f/nidmresults/exporter.py#L546-L556
train
34,310
incf-nidash/nidmresults
nidmresults/exporter.py
NIDMExporter._add_namespaces
def _add_namespaces(self): """ Add namespaces to NIDM document. """ self.doc.add_namespace(NIDM) self.doc.add_namespace(NIIRI) self.doc.add_namespace(CRYPTO) self.doc.add_namespace(DCT) self.doc.add_namespace(DC) self.doc.add_namespace(NFO) self.doc.add_namespace(OBO) self.doc.add_namespace(SCR) self.doc.add_namespace(NIF)
python
def _add_namespaces(self): """ Add namespaces to NIDM document. """ self.doc.add_namespace(NIDM) self.doc.add_namespace(NIIRI) self.doc.add_namespace(CRYPTO) self.doc.add_namespace(DCT) self.doc.add_namespace(DC) self.doc.add_namespace(NFO) self.doc.add_namespace(OBO) self.doc.add_namespace(SCR) self.doc.add_namespace(NIF)
[ "def", "_add_namespaces", "(", "self", ")", ":", "self", ".", "doc", ".", "add_namespace", "(", "NIDM", ")", "self", ".", "doc", ".", "add_namespace", "(", "NIIRI", ")", "self", ".", "doc", ".", "add_namespace", "(", "CRYPTO", ")", "self", ".", "doc", ...
Add namespaces to NIDM document.
[ "Add", "namespaces", "to", "NIDM", "document", "." ]
438f7cce6abc4a4379b629bd76f4d427891e033f
https://github.com/incf-nidash/nidmresults/blob/438f7cce6abc4a4379b629bd76f4d427891e033f/nidmresults/exporter.py#L558-L570
train
34,311
incf-nidash/nidmresults
nidmresults/exporter.py
NIDMExporter._create_bundle
def _create_bundle(self, version): """ Initialise NIDM-Results bundle. """ # *** Bundle entity if not hasattr(self, 'bundle_ent'): self.bundle_ent = NIDMResultsBundle(nidm_version=version['num']) self.bundle = ProvBundle(identifier=self.bundle_ent.id) self.bundle_ent.export(self.version, self.export_dir) # # provn export # self.bundle = ProvBundle(identifier=bundle_id) self.doc.entity(self.bundle_ent.id, other_attributes=self.bundle_ent.attributes) # *** NIDM-Results Export Activity if version['num'] not in ["1.0.0", "1.1.0"]: if not hasattr(self, 'export_act'): self.export_act = NIDMResultsExport() self.export_act.export(self.version, self.export_dir) # self.doc.update(self.export_act.p) self.doc.activity(self.export_act.id, other_attributes=self.export_act.attributes) # *** bundle was Generated by NIDM-Results Export Activity if not hasattr(self, 'export_time'): self.export_time = str(datetime.datetime.now().time()) if version['num'] in ["1.0.0", "1.1.0"]: self.doc.wasGeneratedBy(entity=self.bundle_ent.id, time=self.export_time) else: # provn self.doc.wasGeneratedBy( entity=self.bundle_ent.id, activity=self.export_act.id, time=self.export_time) # *** NIDM-Results Exporter (Software Agent) if version['num'] not in ["1.0.0", "1.1.0"]: if not hasattr(self, 'exporter'): self.exporter = self._get_exporter() self.exporter.export(self.version, self.export_dir) # self.doc.update(self.exporter.p) self.doc.agent(self.exporter.id, other_attributes=self.exporter.attributes) self.doc.wasAssociatedWith(self.export_act.id, self.exporter.id)
python
def _create_bundle(self, version): """ Initialise NIDM-Results bundle. """ # *** Bundle entity if not hasattr(self, 'bundle_ent'): self.bundle_ent = NIDMResultsBundle(nidm_version=version['num']) self.bundle = ProvBundle(identifier=self.bundle_ent.id) self.bundle_ent.export(self.version, self.export_dir) # # provn export # self.bundle = ProvBundle(identifier=bundle_id) self.doc.entity(self.bundle_ent.id, other_attributes=self.bundle_ent.attributes) # *** NIDM-Results Export Activity if version['num'] not in ["1.0.0", "1.1.0"]: if not hasattr(self, 'export_act'): self.export_act = NIDMResultsExport() self.export_act.export(self.version, self.export_dir) # self.doc.update(self.export_act.p) self.doc.activity(self.export_act.id, other_attributes=self.export_act.attributes) # *** bundle was Generated by NIDM-Results Export Activity if not hasattr(self, 'export_time'): self.export_time = str(datetime.datetime.now().time()) if version['num'] in ["1.0.0", "1.1.0"]: self.doc.wasGeneratedBy(entity=self.bundle_ent.id, time=self.export_time) else: # provn self.doc.wasGeneratedBy( entity=self.bundle_ent.id, activity=self.export_act.id, time=self.export_time) # *** NIDM-Results Exporter (Software Agent) if version['num'] not in ["1.0.0", "1.1.0"]: if not hasattr(self, 'exporter'): self.exporter = self._get_exporter() self.exporter.export(self.version, self.export_dir) # self.doc.update(self.exporter.p) self.doc.agent(self.exporter.id, other_attributes=self.exporter.attributes) self.doc.wasAssociatedWith(self.export_act.id, self.exporter.id)
[ "def", "_create_bundle", "(", "self", ",", "version", ")", ":", "# *** Bundle entity", "if", "not", "hasattr", "(", "self", ",", "'bundle_ent'", ")", ":", "self", ".", "bundle_ent", "=", "NIDMResultsBundle", "(", "nidm_version", "=", "version", "[", "'num'", ...
Initialise NIDM-Results bundle.
[ "Initialise", "NIDM", "-", "Results", "bundle", "." ]
438f7cce6abc4a4379b629bd76f4d427891e033f
https://github.com/incf-nidash/nidmresults/blob/438f7cce6abc4a4379b629bd76f4d427891e033f/nidmresults/exporter.py#L572-L621
train
34,312
incf-nidash/nidmresults
nidmresults/exporter.py
NIDMExporter._get_model_parameters_estimations
def _get_model_parameters_estimations(self, error_model): """ Infer model estimation method from the 'error_model'. Return an object of type ModelParametersEstimation. """ if error_model.dependance == NIDM_INDEPEDENT_ERROR: if error_model.variance_homo: estimation_method = STATO_OLS else: estimation_method = STATO_WLS else: estimation_method = STATO_GLS mpe = ModelParametersEstimation(estimation_method, self.software.id) return mpe
python
def _get_model_parameters_estimations(self, error_model): """ Infer model estimation method from the 'error_model'. Return an object of type ModelParametersEstimation. """ if error_model.dependance == NIDM_INDEPEDENT_ERROR: if error_model.variance_homo: estimation_method = STATO_OLS else: estimation_method = STATO_WLS else: estimation_method = STATO_GLS mpe = ModelParametersEstimation(estimation_method, self.software.id) return mpe
[ "def", "_get_model_parameters_estimations", "(", "self", ",", "error_model", ")", ":", "if", "error_model", ".", "dependance", "==", "NIDM_INDEPEDENT_ERROR", ":", "if", "error_model", ".", "variance_homo", ":", "estimation_method", "=", "STATO_OLS", "else", ":", "es...
Infer model estimation method from the 'error_model'. Return an object of type ModelParametersEstimation.
[ "Infer", "model", "estimation", "method", "from", "the", "error_model", ".", "Return", "an", "object", "of", "type", "ModelParametersEstimation", "." ]
438f7cce6abc4a4379b629bd76f4d427891e033f
https://github.com/incf-nidash/nidmresults/blob/438f7cce6abc4a4379b629bd76f4d427891e033f/nidmresults/exporter.py#L623-L638
train
34,313
incf-nidash/nidmresults
nidmresults/exporter.py
NIDMExporter.save_prov_to_files
def save_prov_to_files(self, showattributes=False): """ Write-out provn serialisation to nidm.provn. """ self.doc.add_bundle(self.bundle) # provn_file = os.path.join(self.export_dir, 'nidm.provn') # provn_fid = open(provn_file, 'w') # # FIXME None # # provn_fid.write(self.doc.get_provn(4).replace("None", "-")) # provn_fid.close() ttl_file = os.path.join(self.export_dir, 'nidm.ttl') ttl_txt = self.doc.serialize(format='rdf', rdf_format='turtle') ttl_txt, json_context = self.use_prefixes(ttl_txt) # Add namespaces to json-ld context for namespace in self.doc._namespaces.get_registered_namespaces(): json_context[namespace._prefix] = namespace._uri for namespace in \ list(self.doc._namespaces._default_namespaces.values()): json_context[namespace._prefix] = namespace._uri json_context["xsd"] = "http://www.w3.org/2000/01/rdf-schema#" # Work-around to issue with INF value in rdflib (reported in # https://github.com/RDFLib/rdflib/pull/655) ttl_txt = ttl_txt.replace(' inf ', ' "INF"^^xsd:float ') with open(ttl_file, 'w') as ttl_fid: ttl_fid.write(ttl_txt) # print(json_context) jsonld_file = os.path.join(self.export_dir, 'nidm.json') jsonld_txt = self.doc.serialize(format='rdf', rdf_format='json-ld', context=json_context) with open(jsonld_file, 'w') as jsonld_fid: jsonld_fid.write(jsonld_txt) # provjsonld_file = os.path.join(self.export_dir, 'nidm.provjsonld') # provjsonld_txt = self.doc.serialize(format='jsonld') # with open(provjsonld_file, 'w') as provjsonld_fid: # provjsonld_fid.write(provjsonld_txt) # provn_file = os.path.join(self.export_dir, 'nidm.provn') # provn_txt = self.doc.serialize(format='provn') # with open(provn_file, 'w') as provn_fid: # provn_fid.write(provn_txt) # Post-processing if not self.zipped: # Just rename temp directory to output_path os.rename(self.export_dir, self.out_dir) else: # Create a zip file that contains the content of the temp directory os.chdir(self.export_dir) zf = zipfile.ZipFile(os.path.join("..", self.out_dir), mode='w') try: for root, dirnames, filenames in os.walk("."): for filename in filenames: zf.write(os.path.join(filename)) finally: zf.close() # Need to move up before deleting the folder os.chdir("..") shutil.rmtree(os.path.join("..", self.export_dir))
python
def save_prov_to_files(self, showattributes=False): """ Write-out provn serialisation to nidm.provn. """ self.doc.add_bundle(self.bundle) # provn_file = os.path.join(self.export_dir, 'nidm.provn') # provn_fid = open(provn_file, 'w') # # FIXME None # # provn_fid.write(self.doc.get_provn(4).replace("None", "-")) # provn_fid.close() ttl_file = os.path.join(self.export_dir, 'nidm.ttl') ttl_txt = self.doc.serialize(format='rdf', rdf_format='turtle') ttl_txt, json_context = self.use_prefixes(ttl_txt) # Add namespaces to json-ld context for namespace in self.doc._namespaces.get_registered_namespaces(): json_context[namespace._prefix] = namespace._uri for namespace in \ list(self.doc._namespaces._default_namespaces.values()): json_context[namespace._prefix] = namespace._uri json_context["xsd"] = "http://www.w3.org/2000/01/rdf-schema#" # Work-around to issue with INF value in rdflib (reported in # https://github.com/RDFLib/rdflib/pull/655) ttl_txt = ttl_txt.replace(' inf ', ' "INF"^^xsd:float ') with open(ttl_file, 'w') as ttl_fid: ttl_fid.write(ttl_txt) # print(json_context) jsonld_file = os.path.join(self.export_dir, 'nidm.json') jsonld_txt = self.doc.serialize(format='rdf', rdf_format='json-ld', context=json_context) with open(jsonld_file, 'w') as jsonld_fid: jsonld_fid.write(jsonld_txt) # provjsonld_file = os.path.join(self.export_dir, 'nidm.provjsonld') # provjsonld_txt = self.doc.serialize(format='jsonld') # with open(provjsonld_file, 'w') as provjsonld_fid: # provjsonld_fid.write(provjsonld_txt) # provn_file = os.path.join(self.export_dir, 'nidm.provn') # provn_txt = self.doc.serialize(format='provn') # with open(provn_file, 'w') as provn_fid: # provn_fid.write(provn_txt) # Post-processing if not self.zipped: # Just rename temp directory to output_path os.rename(self.export_dir, self.out_dir) else: # Create a zip file that contains the content of the temp directory os.chdir(self.export_dir) zf = zipfile.ZipFile(os.path.join("..", self.out_dir), mode='w') try: for root, dirnames, filenames in os.walk("."): for filename in filenames: zf.write(os.path.join(filename)) finally: zf.close() # Need to move up before deleting the folder os.chdir("..") shutil.rmtree(os.path.join("..", self.export_dir))
[ "def", "save_prov_to_files", "(", "self", ",", "showattributes", "=", "False", ")", ":", "self", ".", "doc", ".", "add_bundle", "(", "self", ".", "bundle", ")", "# provn_file = os.path.join(self.export_dir, 'nidm.provn')", "# provn_fid = open(provn_file, 'w')", "# # FIXME...
Write-out provn serialisation to nidm.provn.
[ "Write", "-", "out", "provn", "serialisation", "to", "nidm", ".", "provn", "." ]
438f7cce6abc4a4379b629bd76f4d427891e033f
https://github.com/incf-nidash/nidmresults/blob/438f7cce6abc4a4379b629bd76f4d427891e033f/nidmresults/exporter.py#L659-L721
train
34,314
occrp-attic/exactitude
exactitude/phone.py
PhoneType.clean_text
def clean_text(self, number, countries=None, country=None, **kwargs): """Parse a phone number and return in international format. If no valid phone number can be detected, None is returned. If a country code is supplied, this will be used to infer the prefix. https://github.com/daviddrysdale/python-phonenumbers """ for code in self._clean_countries(countries, country): try: num = parse_number(number, code) if is_possible_number(num): if is_valid_number(num): return format_number(num, PhoneNumberFormat.E164) except NumberParseException: pass
python
def clean_text(self, number, countries=None, country=None, **kwargs): """Parse a phone number and return in international format. If no valid phone number can be detected, None is returned. If a country code is supplied, this will be used to infer the prefix. https://github.com/daviddrysdale/python-phonenumbers """ for code in self._clean_countries(countries, country): try: num = parse_number(number, code) if is_possible_number(num): if is_valid_number(num): return format_number(num, PhoneNumberFormat.E164) except NumberParseException: pass
[ "def", "clean_text", "(", "self", ",", "number", ",", "countries", "=", "None", ",", "country", "=", "None", ",", "*", "*", "kwargs", ")", ":", "for", "code", "in", "self", ".", "_clean_countries", "(", "countries", ",", "country", ")", ":", "try", "...
Parse a phone number and return in international format. If no valid phone number can be detected, None is returned. If a country code is supplied, this will be used to infer the prefix. https://github.com/daviddrysdale/python-phonenumbers
[ "Parse", "a", "phone", "number", "and", "return", "in", "international", "format", "." ]
9fe13aa70f1aac644dbc999e0b21683db507f02d
https://github.com/occrp-attic/exactitude/blob/9fe13aa70f1aac644dbc999e0b21683db507f02d/exactitude/phone.py#L23-L39
train
34,315
occrp-attic/exactitude
exactitude/ip.py
IpType.validate
def validate(self, ip, **kwargs): """Check to see if this is a valid ip address.""" if ip is None: return False ip = stringify(ip) if self.IPV4_REGEX.match(ip): try: socket.inet_pton(socket.AF_INET, ip) return True except AttributeError: # no inet_pton here, sorry try: socket.inet_aton(ip) except socket.error: return False return ip.count('.') == 3 except socket.error: # not a valid address return False if self.IPV6_REGEX.match(ip): try: socket.inet_pton(socket.AF_INET6, ip) except socket.error: # not a valid address return False return True
python
def validate(self, ip, **kwargs): """Check to see if this is a valid ip address.""" if ip is None: return False ip = stringify(ip) if self.IPV4_REGEX.match(ip): try: socket.inet_pton(socket.AF_INET, ip) return True except AttributeError: # no inet_pton here, sorry try: socket.inet_aton(ip) except socket.error: return False return ip.count('.') == 3 except socket.error: # not a valid address return False if self.IPV6_REGEX.match(ip): try: socket.inet_pton(socket.AF_INET6, ip) except socket.error: # not a valid address return False return True
[ "def", "validate", "(", "self", ",", "ip", ",", "*", "*", "kwargs", ")", ":", "if", "ip", "is", "None", ":", "return", "False", "ip", "=", "stringify", "(", "ip", ")", "if", "self", ".", "IPV4_REGEX", ".", "match", "(", "ip", ")", ":", "try", "...
Check to see if this is a valid ip address.
[ "Check", "to", "see", "if", "this", "is", "a", "valid", "ip", "address", "." ]
9fe13aa70f1aac644dbc999e0b21683db507f02d
https://github.com/occrp-attic/exactitude/blob/9fe13aa70f1aac644dbc999e0b21683db507f02d/exactitude/ip.py#L15-L42
train
34,316
incf-nidash/nidmresults
nidmresults/objects/generic.py
NIDMFile.export
def export(self, nidm_version, export_dir, prepend_path): """ Copy file over of export_dir and create corresponding triples """ if self.path is not None: if export_dir is not None: # Copy file only if export_dir is not None new_file = os.path.join(export_dir, self.filename) if not self.path == new_file: if prepend_path.endswith('.zip'): with zipfile.ZipFile(prepend_path) as z: extracted = z.extract(str(self.path), export_dir) shutil.move(extracted, new_file) else: if prepend_path: file_copied = os.path.join(prepend_path, self.path) else: file_copied = self.path shutil.copy(file_copied, new_file) if self.temporary: os.remove(self.path) else: new_file = self.path if nidm_version['num'] in ["1.0.0", "1.1.0"]: loc = Identifier("file://./" + self.filename) else: loc = Identifier(self.filename) self.add_attributes([(NFO['fileName'], self.filename)]) if export_dir: self.add_attributes([(PROV['atLocation'], loc)]) if nidm_version['num'] in ("1.0.0", "1.1.0"): path, org_filename = os.path.split(self.path) if (org_filename is not self.filename) \ and (not self.temporary): self.add_attributes([(NFO['fileName'], org_filename)]) if self.is_nifti(): if self.sha is None: self.sha = self.get_sha_sum(new_file) if self.fmt is None: self.fmt = "image/nifti" self.add_attributes([ (CRYPTO['sha512'], self.sha), (DCT['format'], self.fmt) ])
python
def export(self, nidm_version, export_dir, prepend_path): """ Copy file over of export_dir and create corresponding triples """ if self.path is not None: if export_dir is not None: # Copy file only if export_dir is not None new_file = os.path.join(export_dir, self.filename) if not self.path == new_file: if prepend_path.endswith('.zip'): with zipfile.ZipFile(prepend_path) as z: extracted = z.extract(str(self.path), export_dir) shutil.move(extracted, new_file) else: if prepend_path: file_copied = os.path.join(prepend_path, self.path) else: file_copied = self.path shutil.copy(file_copied, new_file) if self.temporary: os.remove(self.path) else: new_file = self.path if nidm_version['num'] in ["1.0.0", "1.1.0"]: loc = Identifier("file://./" + self.filename) else: loc = Identifier(self.filename) self.add_attributes([(NFO['fileName'], self.filename)]) if export_dir: self.add_attributes([(PROV['atLocation'], loc)]) if nidm_version['num'] in ("1.0.0", "1.1.0"): path, org_filename = os.path.split(self.path) if (org_filename is not self.filename) \ and (not self.temporary): self.add_attributes([(NFO['fileName'], org_filename)]) if self.is_nifti(): if self.sha is None: self.sha = self.get_sha_sum(new_file) if self.fmt is None: self.fmt = "image/nifti" self.add_attributes([ (CRYPTO['sha512'], self.sha), (DCT['format'], self.fmt) ])
[ "def", "export", "(", "self", ",", "nidm_version", ",", "export_dir", ",", "prepend_path", ")", ":", "if", "self", ".", "path", "is", "not", "None", ":", "if", "export_dir", "is", "not", "None", ":", "# Copy file only if export_dir is not None", "new_file", "=...
Copy file over of export_dir and create corresponding triples
[ "Copy", "file", "over", "of", "export_dir", "and", "create", "corresponding", "triples" ]
438f7cce6abc4a4379b629bd76f4d427891e033f
https://github.com/incf-nidash/nidmresults/blob/438f7cce6abc4a4379b629bd76f4d427891e033f/nidmresults/objects/generic.py#L289-L339
train
34,317
incf-nidash/nidmresults
nidmresults/objects/generic.py
Image.export
def export(self, nidm_version, export_dir): """ Create prov entity. """ if self.file is not None: self.add_attributes([ (PROV['type'], self.type), (DCT['format'], "image/png"), ])
python
def export(self, nidm_version, export_dir): """ Create prov entity. """ if self.file is not None: self.add_attributes([ (PROV['type'], self.type), (DCT['format'], "image/png"), ])
[ "def", "export", "(", "self", ",", "nidm_version", ",", "export_dir", ")", ":", "if", "self", ".", "file", "is", "not", "None", ":", "self", ".", "add_attributes", "(", "[", "(", "PROV", "[", "'type'", "]", ",", "self", ".", "type", ")", ",", "(", ...
Create prov entity.
[ "Create", "prov", "entity", "." ]
438f7cce6abc4a4379b629bd76f4d427891e033f
https://github.com/incf-nidash/nidmresults/blob/438f7cce6abc4a4379b629bd76f4d427891e033f/nidmresults/objects/generic.py#L376-L384
train
34,318
occrp-attic/exactitude
exactitude/address.py
AddressType.normalize
def normalize(self, address, **kwargs): """Make the address more compareable.""" # TODO: normalize well-known parts like "Street", "Road", etc. # TODO: consider using https://github.com/openvenues/pypostal addresses = super(AddressType, self).normalize(address, **kwargs) return addresses
python
def normalize(self, address, **kwargs): """Make the address more compareable.""" # TODO: normalize well-known parts like "Street", "Road", etc. # TODO: consider using https://github.com/openvenues/pypostal addresses = super(AddressType, self).normalize(address, **kwargs) return addresses
[ "def", "normalize", "(", "self", ",", "address", ",", "*", "*", "kwargs", ")", ":", "# TODO: normalize well-known parts like \"Street\", \"Road\", etc.", "# TODO: consider using https://github.com/openvenues/pypostal", "addresses", "=", "super", "(", "AddressType", ",", "self...
Make the address more compareable.
[ "Make", "the", "address", "more", "compareable", "." ]
9fe13aa70f1aac644dbc999e0b21683db507f02d
https://github.com/occrp-attic/exactitude/blob/9fe13aa70f1aac644dbc999e0b21683db507f02d/exactitude/address.py#L19-L24
train
34,319
occrp-attic/exactitude
exactitude/url.py
UrlType.clean_text
def clean_text(self, url, **kwargs): """Perform intensive care on URLs, see `urlnormalizer`.""" try: return normalize_url(url) except UnicodeDecodeError: log.warning("Invalid URL: %r", url)
python
def clean_text(self, url, **kwargs): """Perform intensive care on URLs, see `urlnormalizer`.""" try: return normalize_url(url) except UnicodeDecodeError: log.warning("Invalid URL: %r", url)
[ "def", "clean_text", "(", "self", ",", "url", ",", "*", "*", "kwargs", ")", ":", "try", ":", "return", "normalize_url", "(", "url", ")", "except", "UnicodeDecodeError", ":", "log", ".", "warning", "(", "\"Invalid URL: %r\"", ",", "url", ")" ]
Perform intensive care on URLs, see `urlnormalizer`.
[ "Perform", "intensive", "care", "on", "URLs", "see", "urlnormalizer", "." ]
9fe13aa70f1aac644dbc999e0b21683db507f02d
https://github.com/occrp-attic/exactitude/blob/9fe13aa70f1aac644dbc999e0b21683db507f02d/exactitude/url.py#L15-L20
train
34,320
occrp-attic/exactitude
exactitude/country.py
CountryType.clean_text
def clean_text(self, country, guess=False, **kwargs): """Determine a two-letter country code based on an input. The input may be a country code, a country name, etc. """ code = country.lower().strip() if code in self.names: return code country = countrynames.to_code(country, fuzzy=guess) if country is not None: return country.lower()
python
def clean_text(self, country, guess=False, **kwargs): """Determine a two-letter country code based on an input. The input may be a country code, a country name, etc. """ code = country.lower().strip() if code in self.names: return code country = countrynames.to_code(country, fuzzy=guess) if country is not None: return country.lower()
[ "def", "clean_text", "(", "self", ",", "country", ",", "guess", "=", "False", ",", "*", "*", "kwargs", ")", ":", "code", "=", "country", ".", "lower", "(", ")", ".", "strip", "(", ")", "if", "code", "in", "self", ".", "names", ":", "return", "cod...
Determine a two-letter country code based on an input. The input may be a country code, a country name, etc.
[ "Determine", "a", "two", "-", "letter", "country", "code", "based", "on", "an", "input", "." ]
9fe13aa70f1aac644dbc999e0b21683db507f02d
https://github.com/occrp-attic/exactitude/blob/9fe13aa70f1aac644dbc999e0b21683db507f02d/exactitude/country.py#L35-L45
train
34,321
occrp-attic/exactitude
exactitude/email.py
EmailType.validate
def validate(self, email, **kwargs): """Check to see if this is a valid email address.""" email = stringify(email) if email is None: return if not self.EMAIL_REGEX.match(email): return False mailbox, domain = email.rsplit('@', 1) return self.domains.validate(domain, **kwargs)
python
def validate(self, email, **kwargs): """Check to see if this is a valid email address.""" email = stringify(email) if email is None: return if not self.EMAIL_REGEX.match(email): return False mailbox, domain = email.rsplit('@', 1) return self.domains.validate(domain, **kwargs)
[ "def", "validate", "(", "self", ",", "email", ",", "*", "*", "kwargs", ")", ":", "email", "=", "stringify", "(", "email", ")", "if", "email", "is", "None", ":", "return", "if", "not", "self", ".", "EMAIL_REGEX", ".", "match", "(", "email", ")", ":"...
Check to see if this is a valid email address.
[ "Check", "to", "see", "if", "this", "is", "a", "valid", "email", "address", "." ]
9fe13aa70f1aac644dbc999e0b21683db507f02d
https://github.com/occrp-attic/exactitude/blob/9fe13aa70f1aac644dbc999e0b21683db507f02d/exactitude/email.py#L15-L23
train
34,322
occrp-attic/exactitude
exactitude/email.py
EmailType.clean_text
def clean_text(self, email, **kwargs): """Parse and normalize an email address. Returns None if this is not an email address. """ if not self.EMAIL_REGEX.match(email): return None email = strip_quotes(email) mailbox, domain = email.rsplit('@', 1) domain = self.domains.clean(domain, **kwargs) if domain is None or mailbox is None: return return '@'.join((mailbox, domain))
python
def clean_text(self, email, **kwargs): """Parse and normalize an email address. Returns None if this is not an email address. """ if not self.EMAIL_REGEX.match(email): return None email = strip_quotes(email) mailbox, domain = email.rsplit('@', 1) domain = self.domains.clean(domain, **kwargs) if domain is None or mailbox is None: return return '@'.join((mailbox, domain))
[ "def", "clean_text", "(", "self", ",", "email", ",", "*", "*", "kwargs", ")", ":", "if", "not", "self", ".", "EMAIL_REGEX", ".", "match", "(", "email", ")", ":", "return", "None", "email", "=", "strip_quotes", "(", "email", ")", "mailbox", ",", "doma...
Parse and normalize an email address. Returns None if this is not an email address.
[ "Parse", "and", "normalize", "an", "email", "address", "." ]
9fe13aa70f1aac644dbc999e0b21683db507f02d
https://github.com/occrp-attic/exactitude/blob/9fe13aa70f1aac644dbc999e0b21683db507f02d/exactitude/email.py#L25-L37
train
34,323
incf-nidash/nidmresults
nidmresults/graph.py
NIDMResults.fix_for_specific_versions
def fix_for_specific_versions(self, rdf_data, to_replace): """ Fixes of the RDF before loading the graph. All of these are workaround to circuvent known issues of the SPM and FSL exporters. """ # Load the graph as is so that we can query g = self.parse(rdf_data) # Retreive the exporter name and version query = """ prefix nidm_spm_results_nidm: <http://purl.org/nidash/nidm#NIDM_0000168> prefix nidm_nidmfsl: <http://purl.org/nidash/nidm#NIDM_0000167> prefix nidm_softwareVersion: <http://purl.org/nidash/nidm#NIDM_0000122> SELECT DISTINCT ?type ?version ?exp_act WHERE { {?exporter a nidm_nidmfsl: .} UNION {?exporter a nidm_spm_results_nidm: .}. ?exporter a ?type ; nidm_softwareVersion: ?version . ?exp_act prov:wasAssociatedWith ?exporter . FILTER ( ?type NOT IN (prov:SoftwareAgent, prov:Agent)) } """ sd = g.query(query) objects = dict() if sd: for row in sd: argums = row.asdict() if (argums['type'] == NIDM_SPM_RESULTS_NIDM and (argums['version'].eq('12.6903') or argums['version'].eq('12.575ac2c'))): warnings.warn('Applying fixes for SPM exporter ' + str(argums['version'])) # crypto namespace inconsistent with NIDM-Results spec to_replace[('http://id.loc.gov/vocabulary/preservation/' + 'cryptographicHashFunctions/')] = ( 'http://id.loc.gov/vocabulary/preservation/' + 'cryptographicHashFunctions#') # Missing 'activity' attribute in qualified Generation to_replace['a prov:Generation .'] = ( 'a prov:Generation ; prov:activity <' + str(argums['exp_act']) + '> .') # Avoid confusion between attribute and # class uncorrected p-value # cf. https://github.com/incf-nidash/nidm/issues/421 to_replace[('@prefix nidm_PValueUncorrected: ' + '<http://purl.org/nidash/nidm#NIDM_0000160>')] = ( '@prefix nidm_UncorrectedPValue: ' + '<http://purl.org/nidash/nidm#NIDM_0000160>') to_replace['nidm_PValueUncorrected'] = 'nidm_UncorrectedPValue' if to_replace is not None: for to_rep, replacement in to_replace.items(): rdf_data = rdf_data.replace(to_rep, replacement) return rdf_data
python
def fix_for_specific_versions(self, rdf_data, to_replace): """ Fixes of the RDF before loading the graph. All of these are workaround to circuvent known issues of the SPM and FSL exporters. """ # Load the graph as is so that we can query g = self.parse(rdf_data) # Retreive the exporter name and version query = """ prefix nidm_spm_results_nidm: <http://purl.org/nidash/nidm#NIDM_0000168> prefix nidm_nidmfsl: <http://purl.org/nidash/nidm#NIDM_0000167> prefix nidm_softwareVersion: <http://purl.org/nidash/nidm#NIDM_0000122> SELECT DISTINCT ?type ?version ?exp_act WHERE { {?exporter a nidm_nidmfsl: .} UNION {?exporter a nidm_spm_results_nidm: .}. ?exporter a ?type ; nidm_softwareVersion: ?version . ?exp_act prov:wasAssociatedWith ?exporter . FILTER ( ?type NOT IN (prov:SoftwareAgent, prov:Agent)) } """ sd = g.query(query) objects = dict() if sd: for row in sd: argums = row.asdict() if (argums['type'] == NIDM_SPM_RESULTS_NIDM and (argums['version'].eq('12.6903') or argums['version'].eq('12.575ac2c'))): warnings.warn('Applying fixes for SPM exporter ' + str(argums['version'])) # crypto namespace inconsistent with NIDM-Results spec to_replace[('http://id.loc.gov/vocabulary/preservation/' + 'cryptographicHashFunctions/')] = ( 'http://id.loc.gov/vocabulary/preservation/' + 'cryptographicHashFunctions#') # Missing 'activity' attribute in qualified Generation to_replace['a prov:Generation .'] = ( 'a prov:Generation ; prov:activity <' + str(argums['exp_act']) + '> .') # Avoid confusion between attribute and # class uncorrected p-value # cf. https://github.com/incf-nidash/nidm/issues/421 to_replace[('@prefix nidm_PValueUncorrected: ' + '<http://purl.org/nidash/nidm#NIDM_0000160>')] = ( '@prefix nidm_UncorrectedPValue: ' + '<http://purl.org/nidash/nidm#NIDM_0000160>') to_replace['nidm_PValueUncorrected'] = 'nidm_UncorrectedPValue' if to_replace is not None: for to_rep, replacement in to_replace.items(): rdf_data = rdf_data.replace(to_rep, replacement) return rdf_data
[ "def", "fix_for_specific_versions", "(", "self", ",", "rdf_data", ",", "to_replace", ")", ":", "# Load the graph as is so that we can query", "g", "=", "self", ".", "parse", "(", "rdf_data", ")", "# Retreive the exporter name and version", "query", "=", "\"\"\"\nprefix ni...
Fixes of the RDF before loading the graph. All of these are workaround to circuvent known issues of the SPM and FSL exporters.
[ "Fixes", "of", "the", "RDF", "before", "loading", "the", "graph", ".", "All", "of", "these", "are", "workaround", "to", "circuvent", "known", "issues", "of", "the", "SPM", "and", "FSL", "exporters", "." ]
438f7cce6abc4a4379b629bd76f4d427891e033f
https://github.com/incf-nidash/nidmresults/blob/438f7cce6abc4a4379b629bd76f4d427891e033f/nidmresults/graph.py#L59-L118
train
34,324
incf-nidash/nidmresults
nidmresults/graph.py
NIDMResults._get_model_fitting
def _get_model_fitting(self, con_est_id): """ Retreive model fitting that corresponds to contrast with identifier 'con_id' from the list of model fitting objects stored in self.model_fittings """ for (mpe_id, pe_ids), contrasts in self.contrasts.items(): for contrast in contrasts: if contrast.estimation.id == con_est_id: model_fitting_id = mpe_id pe_map_ids = pe_ids break for model_fitting in self.model_fittings: if model_fitting.activity.id == model_fitting_id: return (model_fitting, pe_map_ids) raise Exception("Model fitting of contrast : " + str(con_est_id) + " not found.")
python
def _get_model_fitting(self, con_est_id): """ Retreive model fitting that corresponds to contrast with identifier 'con_id' from the list of model fitting objects stored in self.model_fittings """ for (mpe_id, pe_ids), contrasts in self.contrasts.items(): for contrast in contrasts: if contrast.estimation.id == con_est_id: model_fitting_id = mpe_id pe_map_ids = pe_ids break for model_fitting in self.model_fittings: if model_fitting.activity.id == model_fitting_id: return (model_fitting, pe_map_ids) raise Exception("Model fitting of contrast : " + str(con_est_id) + " not found.")
[ "def", "_get_model_fitting", "(", "self", ",", "con_est_id", ")", ":", "for", "(", "mpe_id", ",", "pe_ids", ")", ",", "contrasts", "in", "self", ".", "contrasts", ".", "items", "(", ")", ":", "for", "contrast", "in", "contrasts", ":", "if", "contrast", ...
Retreive model fitting that corresponds to contrast with identifier 'con_id' from the list of model fitting objects stored in self.model_fittings
[ "Retreive", "model", "fitting", "that", "corresponds", "to", "contrast", "with", "identifier", "con_id", "from", "the", "list", "of", "model", "fitting", "objects", "stored", "in", "self", ".", "model_fittings" ]
438f7cce6abc4a4379b629bd76f4d427891e033f
https://github.com/incf-nidash/nidmresults/blob/438f7cce6abc4a4379b629bd76f4d427891e033f/nidmresults/graph.py#L358-L376
train
34,325
occrp-attic/exactitude
exactitude/common.py
ExactitudeType.validate
def validate(self, text, **kwargs): """Returns a boolean to indicate if this is a valid instance of the type.""" cleaned = self.clean(text, **kwargs) return cleaned is not None
python
def validate(self, text, **kwargs): """Returns a boolean to indicate if this is a valid instance of the type.""" cleaned = self.clean(text, **kwargs) return cleaned is not None
[ "def", "validate", "(", "self", ",", "text", ",", "*", "*", "kwargs", ")", ":", "cleaned", "=", "self", ".", "clean", "(", "text", ",", "*", "*", "kwargs", ")", "return", "cleaned", "is", "not", "None" ]
Returns a boolean to indicate if this is a valid instance of the type.
[ "Returns", "a", "boolean", "to", "indicate", "if", "this", "is", "a", "valid", "instance", "of", "the", "type", "." ]
9fe13aa70f1aac644dbc999e0b21683db507f02d
https://github.com/occrp-attic/exactitude/blob/9fe13aa70f1aac644dbc999e0b21683db507f02d/exactitude/common.py#L12-L16
train
34,326
occrp-attic/exactitude
exactitude/common.py
ExactitudeType.normalize
def normalize(self, text, cleaned=False, **kwargs): """Create a represenation ideal for comparisons, but not to be shown to the user.""" if not cleaned: text = self.clean(text, **kwargs) return ensure_list(text)
python
def normalize(self, text, cleaned=False, **kwargs): """Create a represenation ideal for comparisons, but not to be shown to the user.""" if not cleaned: text = self.clean(text, **kwargs) return ensure_list(text)
[ "def", "normalize", "(", "self", ",", "text", ",", "cleaned", "=", "False", ",", "*", "*", "kwargs", ")", ":", "if", "not", "cleaned", ":", "text", "=", "self", ".", "clean", "(", "text", ",", "*", "*", "kwargs", ")", "return", "ensure_list", "(", ...
Create a represenation ideal for comparisons, but not to be shown to the user.
[ "Create", "a", "represenation", "ideal", "for", "comparisons", "but", "not", "to", "be", "shown", "to", "the", "user", "." ]
9fe13aa70f1aac644dbc999e0b21683db507f02d
https://github.com/occrp-attic/exactitude/blob/9fe13aa70f1aac644dbc999e0b21683db507f02d/exactitude/common.py#L28-L33
train
34,327
occrp-attic/exactitude
exactitude/common.py
ExactitudeType.normalize_set
def normalize_set(self, items, **kwargs): """Utility to normalize a whole set of values and get unique values.""" values = set() for item in ensure_list(items): values.update(self.normalize(item, **kwargs)) return list(values)
python
def normalize_set(self, items, **kwargs): """Utility to normalize a whole set of values and get unique values.""" values = set() for item in ensure_list(items): values.update(self.normalize(item, **kwargs)) return list(values)
[ "def", "normalize_set", "(", "self", ",", "items", ",", "*", "*", "kwargs", ")", ":", "values", "=", "set", "(", ")", "for", "item", "in", "ensure_list", "(", "items", ")", ":", "values", ".", "update", "(", "self", ".", "normalize", "(", "item", "...
Utility to normalize a whole set of values and get unique values.
[ "Utility", "to", "normalize", "a", "whole", "set", "of", "values", "and", "get", "unique", "values", "." ]
9fe13aa70f1aac644dbc999e0b21683db507f02d
https://github.com/occrp-attic/exactitude/blob/9fe13aa70f1aac644dbc999e0b21683db507f02d/exactitude/common.py#L35-L41
train
34,328
occrp-attic/exactitude
exactitude/domain.py
DomainType.validate
def validate(self, obj, **kwargs): """Check if a thing is a valid domain name.""" text = stringify(obj) if text is None: return False if '.' not in text: return False if '@' in text or ':' in text: return False if len(text) < 4: return False return True
python
def validate(self, obj, **kwargs): """Check if a thing is a valid domain name.""" text = stringify(obj) if text is None: return False if '.' not in text: return False if '@' in text or ':' in text: return False if len(text) < 4: return False return True
[ "def", "validate", "(", "self", ",", "obj", ",", "*", "*", "kwargs", ")", ":", "text", "=", "stringify", "(", "obj", ")", "if", "text", "is", "None", ":", "return", "False", "if", "'.'", "not", "in", "text", ":", "return", "False", "if", "'@'", "...
Check if a thing is a valid domain name.
[ "Check", "if", "a", "thing", "is", "a", "valid", "domain", "name", "." ]
9fe13aa70f1aac644dbc999e0b21683db507f02d
https://github.com/occrp-attic/exactitude/blob/9fe13aa70f1aac644dbc999e0b21683db507f02d/exactitude/domain.py#L20-L31
train
34,329
occrp-attic/exactitude
exactitude/domain.py
DomainType.clean_text
def clean_text(self, domain, **kwargs): """Try to extract only the domain bit from the """ try: # handle URLs by extracting the domain name domain = urlparse(domain).hostname or domain domain = domain.lower() # get rid of port specs domain = domain.rsplit(':', 1)[0] domain = domain.rstrip('.') # handle unicode domain = domain.encode("idna").decode('ascii') except ValueError: return None if self.validate(domain): return domain
python
def clean_text(self, domain, **kwargs): """Try to extract only the domain bit from the """ try: # handle URLs by extracting the domain name domain = urlparse(domain).hostname or domain domain = domain.lower() # get rid of port specs domain = domain.rsplit(':', 1)[0] domain = domain.rstrip('.') # handle unicode domain = domain.encode("idna").decode('ascii') except ValueError: return None if self.validate(domain): return domain
[ "def", "clean_text", "(", "self", ",", "domain", ",", "*", "*", "kwargs", ")", ":", "try", ":", "# handle URLs by extracting the domain name", "domain", "=", "urlparse", "(", "domain", ")", ".", "hostname", "or", "domain", "domain", "=", "domain", ".", "lowe...
Try to extract only the domain bit from the
[ "Try", "to", "extract", "only", "the", "domain", "bit", "from", "the" ]
9fe13aa70f1aac644dbc999e0b21683db507f02d
https://github.com/occrp-attic/exactitude/blob/9fe13aa70f1aac644dbc999e0b21683db507f02d/exactitude/domain.py#L33-L47
train
34,330
incf-nidash/nidmresults
nidmresults/load.py
load
def load(filename, to_replace=dict()): ''' Load NIDM-Results file given filename, guessing if it is a NIDM-Results pack or a JSON file Parameters ---------- filename : string specification of file to load Returns ------- nidmres : ``NIDMResults`` NIDM-Results object ''' if not os.path.exists(filename): raise IOException('File does not exist: %s' % filename) if filename.endswith('.json'): raise Exception('Minimal json file: not handled yet') elif filename.endswith('.nidm.zip'): nidm = NIDMResults.load_from_pack(filename, to_replace=to_replace) else: raise Exception('Unhandled format ' + filename) return nidm
python
def load(filename, to_replace=dict()): ''' Load NIDM-Results file given filename, guessing if it is a NIDM-Results pack or a JSON file Parameters ---------- filename : string specification of file to load Returns ------- nidmres : ``NIDMResults`` NIDM-Results object ''' if not os.path.exists(filename): raise IOException('File does not exist: %s' % filename) if filename.endswith('.json'): raise Exception('Minimal json file: not handled yet') elif filename.endswith('.nidm.zip'): nidm = NIDMResults.load_from_pack(filename, to_replace=to_replace) else: raise Exception('Unhandled format ' + filename) return nidm
[ "def", "load", "(", "filename", ",", "to_replace", "=", "dict", "(", ")", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "filename", ")", ":", "raise", "IOException", "(", "'File does not exist: %s'", "%", "filename", ")", "if", "filename"...
Load NIDM-Results file given filename, guessing if it is a NIDM-Results pack or a JSON file Parameters ---------- filename : string specification of file to load Returns ------- nidmres : ``NIDMResults`` NIDM-Results object
[ "Load", "NIDM", "-", "Results", "file", "given", "filename", "guessing", "if", "it", "is", "a", "NIDM", "-", "Results", "pack", "or", "a", "JSON", "file" ]
438f7cce6abc4a4379b629bd76f4d427891e033f
https://github.com/incf-nidash/nidmresults/blob/438f7cce6abc4a4379b629bd76f4d427891e033f/nidmresults/load.py#L7-L30
train
34,331
myint/cppclean
cpp/tokenize.py
_find
def _find(string, sub_string, start_index): """Return index of sub_string in string. Raise TokenError if sub_string is not found. """ result = string.find(sub_string, start_index) if result == -1: raise TokenError("expected '{0}'".format(sub_string)) return result
python
def _find(string, sub_string, start_index): """Return index of sub_string in string. Raise TokenError if sub_string is not found. """ result = string.find(sub_string, start_index) if result == -1: raise TokenError("expected '{0}'".format(sub_string)) return result
[ "def", "_find", "(", "string", ",", "sub_string", ",", "start_index", ")", ":", "result", "=", "string", ".", "find", "(", "sub_string", ",", "start_index", ")", "if", "result", "==", "-", "1", ":", "raise", "TokenError", "(", "\"expected '{0}'\"", ".", ...
Return index of sub_string in string. Raise TokenError if sub_string is not found.
[ "Return", "index", "of", "sub_string", "in", "string", "." ]
8a20c943dca1049e87d57137938f92d7735828dc
https://github.com/myint/cppclean/blob/8a20c943dca1049e87d57137938f92d7735828dc/cpp/tokenize.py#L289-L297
train
34,332
myint/cppclean
cpp/ast.py
builder_from_source
def builder_from_source(source, filename, system_includes, nonsystem_includes, quiet=False): """Utility method that returns an ASTBuilder from source code. Args: source: 'C++ source code' filename: 'file1' Returns: ASTBuilder """ return ASTBuilder(tokenize.get_tokens(source), filename, system_includes, nonsystem_includes, quiet=quiet)
python
def builder_from_source(source, filename, system_includes, nonsystem_includes, quiet=False): """Utility method that returns an ASTBuilder from source code. Args: source: 'C++ source code' filename: 'file1' Returns: ASTBuilder """ return ASTBuilder(tokenize.get_tokens(source), filename, system_includes, nonsystem_includes, quiet=quiet)
[ "def", "builder_from_source", "(", "source", ",", "filename", ",", "system_includes", ",", "nonsystem_includes", ",", "quiet", "=", "False", ")", ":", "return", "ASTBuilder", "(", "tokenize", ".", "get_tokens", "(", "source", ")", ",", "filename", ",", "system...
Utility method that returns an ASTBuilder from source code. Args: source: 'C++ source code' filename: 'file1' Returns: ASTBuilder
[ "Utility", "method", "that", "returns", "an", "ASTBuilder", "from", "source", "code", "." ]
8a20c943dca1049e87d57137938f92d7735828dc
https://github.com/myint/cppclean/blob/8a20c943dca1049e87d57137938f92d7735828dc/cpp/ast.py#L1654-L1669
train
34,333
myint/cppclean
cpp/ast.py
VariableDeclaration.to_string
def to_string(self): """Return a string that tries to reconstitute the variable decl.""" suffix = '%s %s' % (self.type, self.name) if self.initial_value: suffix += ' = ' + self.initial_value return suffix
python
def to_string(self): """Return a string that tries to reconstitute the variable decl.""" suffix = '%s %s' % (self.type, self.name) if self.initial_value: suffix += ' = ' + self.initial_value return suffix
[ "def", "to_string", "(", "self", ")", ":", "suffix", "=", "'%s %s'", "%", "(", "self", ".", "type", ",", "self", ".", "name", ")", "if", "self", ".", "initial_value", ":", "suffix", "+=", "' = '", "+", "self", ".", "initial_value", "return", "suffix" ]
Return a string that tries to reconstitute the variable decl.
[ "Return", "a", "string", "that", "tries", "to", "reconstitute", "the", "variable", "decl", "." ]
8a20c943dca1049e87d57137938f92d7735828dc
https://github.com/myint/cppclean/blob/8a20c943dca1049e87d57137938f92d7735828dc/cpp/ast.py#L201-L206
train
34,334
myint/cppclean
cpp/symbols.py
SymbolTable._lookup_namespace
def _lookup_namespace(self, symbol, namespace): """Helper for lookup_symbol that only looks up variables in a namespace. Args: symbol: Symbol namespace: pointer into self.namespaces """ for namespace_part in symbol.parts: namespace = namespace.get(namespace_part) if namespace is None: break if not isinstance(namespace, dict): return namespace raise Error('%s not found' % symbol.name)
python
def _lookup_namespace(self, symbol, namespace): """Helper for lookup_symbol that only looks up variables in a namespace. Args: symbol: Symbol namespace: pointer into self.namespaces """ for namespace_part in symbol.parts: namespace = namespace.get(namespace_part) if namespace is None: break if not isinstance(namespace, dict): return namespace raise Error('%s not found' % symbol.name)
[ "def", "_lookup_namespace", "(", "self", ",", "symbol", ",", "namespace", ")", ":", "for", "namespace_part", "in", "symbol", ".", "parts", ":", "namespace", "=", "namespace", ".", "get", "(", "namespace_part", ")", "if", "namespace", "is", "None", ":", "br...
Helper for lookup_symbol that only looks up variables in a namespace. Args: symbol: Symbol namespace: pointer into self.namespaces
[ "Helper", "for", "lookup_symbol", "that", "only", "looks", "up", "variables", "in", "a", "namespace", "." ]
8a20c943dca1049e87d57137938f92d7735828dc
https://github.com/myint/cppclean/blob/8a20c943dca1049e87d57137938f92d7735828dc/cpp/symbols.py#L48-L62
train
34,335
myint/cppclean
cpp/symbols.py
SymbolTable._lookup_global
def _lookup_global(self, symbol): """Helper for lookup_symbol that only looks up global variables. Args: symbol: Symbol """ assert symbol.parts namespace = self.namespaces if len(symbol.parts) == 1: # If there is only one part, look in globals. namespace = self.namespaces[None] try: # Try to do a normal, global namespace lookup. return self._lookup_namespace(symbol, namespace) except Error as orig_exc: try: # The normal lookup can fail if all of the parts aren't # namespaces. This happens with OuterClass::Inner. namespace = self.namespaces[None] return self._lookup_namespace(symbol, namespace) except Error: raise orig_exc
python
def _lookup_global(self, symbol): """Helper for lookup_symbol that only looks up global variables. Args: symbol: Symbol """ assert symbol.parts namespace = self.namespaces if len(symbol.parts) == 1: # If there is only one part, look in globals. namespace = self.namespaces[None] try: # Try to do a normal, global namespace lookup. return self._lookup_namespace(symbol, namespace) except Error as orig_exc: try: # The normal lookup can fail if all of the parts aren't # namespaces. This happens with OuterClass::Inner. namespace = self.namespaces[None] return self._lookup_namespace(symbol, namespace) except Error: raise orig_exc
[ "def", "_lookup_global", "(", "self", ",", "symbol", ")", ":", "assert", "symbol", ".", "parts", "namespace", "=", "self", ".", "namespaces", "if", "len", "(", "symbol", ".", "parts", ")", "==", "1", ":", "# If there is only one part, look in globals.", "names...
Helper for lookup_symbol that only looks up global variables. Args: symbol: Symbol
[ "Helper", "for", "lookup_symbol", "that", "only", "looks", "up", "global", "variables", "." ]
8a20c943dca1049e87d57137938f92d7735828dc
https://github.com/myint/cppclean/blob/8a20c943dca1049e87d57137938f92d7735828dc/cpp/symbols.py#L64-L85
train
34,336
myint/cppclean
cpp/symbols.py
SymbolTable._lookup_in_all_namespaces
def _lookup_in_all_namespaces(self, symbol): """Helper for lookup_symbol that looks for symbols in all namespaces. Args: symbol: Symbol """ namespace = self.namespaces # Create a stack of namespaces. namespace_stack = [] for current in symbol.namespace_stack: namespace = namespace.get(current) if namespace is None or not isinstance(namespace, dict): break namespace_stack.append(namespace) # Iterate through the stack in reverse order. Need to go from # innermost namespace to outermost. for namespace in reversed(namespace_stack): try: return self._lookup_namespace(symbol, namespace) except Error: pass return None
python
def _lookup_in_all_namespaces(self, symbol): """Helper for lookup_symbol that looks for symbols in all namespaces. Args: symbol: Symbol """ namespace = self.namespaces # Create a stack of namespaces. namespace_stack = [] for current in symbol.namespace_stack: namespace = namespace.get(current) if namespace is None or not isinstance(namespace, dict): break namespace_stack.append(namespace) # Iterate through the stack in reverse order. Need to go from # innermost namespace to outermost. for namespace in reversed(namespace_stack): try: return self._lookup_namespace(symbol, namespace) except Error: pass return None
[ "def", "_lookup_in_all_namespaces", "(", "self", ",", "symbol", ")", ":", "namespace", "=", "self", ".", "namespaces", "# Create a stack of namespaces.", "namespace_stack", "=", "[", "]", "for", "current", "in", "symbol", ".", "namespace_stack", ":", "namespace", ...
Helper for lookup_symbol that looks for symbols in all namespaces. Args: symbol: Symbol
[ "Helper", "for", "lookup_symbol", "that", "looks", "for", "symbols", "in", "all", "namespaces", "." ]
8a20c943dca1049e87d57137938f92d7735828dc
https://github.com/myint/cppclean/blob/8a20c943dca1049e87d57137938f92d7735828dc/cpp/symbols.py#L87-L109
train
34,337
myint/cppclean
cpp/symbols.py
SymbolTable.lookup_symbol
def lookup_symbol(self, name, namespace_stack): """Returns AST node and module for symbol if found. Args: name: 'name of the symbol to lookup' namespace_stack: None or ['namespaces', 'in', 'current', 'scope'] Returns: (ast.Node, module (ie, any object stored with symbol)) if found Raises: Error if the symbol cannot be found. """ # TODO(nnorwitz): a convenient API for this depends on the # representation of the name. e.g., does symbol_name contain # ::, is symbol_name a list of colon separated names, how are # names prefixed with :: handled. These have different lookup # semantics (if leading ::) or change the desirable API. # For now assume that the symbol_name contains :: and parse it. symbol = Symbol(name, name.split('::'), namespace_stack) assert symbol.parts if symbol.parts[0] == '': # Handle absolute (global) ::symbol_names. symbol.parts = symbol.parts[1:] elif namespace_stack is not None: result = self._lookup_in_all_namespaces(symbol) if result: return result return self._lookup_global(symbol)
python
def lookup_symbol(self, name, namespace_stack): """Returns AST node and module for symbol if found. Args: name: 'name of the symbol to lookup' namespace_stack: None or ['namespaces', 'in', 'current', 'scope'] Returns: (ast.Node, module (ie, any object stored with symbol)) if found Raises: Error if the symbol cannot be found. """ # TODO(nnorwitz): a convenient API for this depends on the # representation of the name. e.g., does symbol_name contain # ::, is symbol_name a list of colon separated names, how are # names prefixed with :: handled. These have different lookup # semantics (if leading ::) or change the desirable API. # For now assume that the symbol_name contains :: and parse it. symbol = Symbol(name, name.split('::'), namespace_stack) assert symbol.parts if symbol.parts[0] == '': # Handle absolute (global) ::symbol_names. symbol.parts = symbol.parts[1:] elif namespace_stack is not None: result = self._lookup_in_all_namespaces(symbol) if result: return result return self._lookup_global(symbol)
[ "def", "lookup_symbol", "(", "self", ",", "name", ",", "namespace_stack", ")", ":", "# TODO(nnorwitz): a convenient API for this depends on the", "# representation of the name. e.g., does symbol_name contain", "# ::, is symbol_name a list of colon separated names, how are", "# names prefix...
Returns AST node and module for symbol if found. Args: name: 'name of the symbol to lookup' namespace_stack: None or ['namespaces', 'in', 'current', 'scope'] Returns: (ast.Node, module (ie, any object stored with symbol)) if found Raises: Error if the symbol cannot be found.
[ "Returns", "AST", "node", "and", "module", "for", "symbol", "if", "found", "." ]
8a20c943dca1049e87d57137938f92d7735828dc
https://github.com/myint/cppclean/blob/8a20c943dca1049e87d57137938f92d7735828dc/cpp/symbols.py#L111-L141
train
34,338
myint/cppclean
cpp/symbols.py
SymbolTable._add
def _add(self, symbol_name, namespace, node, module): """Helper function for adding symbols. See add_symbol(). """ result = symbol_name in namespace namespace[symbol_name] = node, module return not result
python
def _add(self, symbol_name, namespace, node, module): """Helper function for adding symbols. See add_symbol(). """ result = symbol_name in namespace namespace[symbol_name] = node, module return not result
[ "def", "_add", "(", "self", ",", "symbol_name", ",", "namespace", ",", "node", ",", "module", ")", ":", "result", "=", "symbol_name", "in", "namespace", "namespace", "[", "symbol_name", "]", "=", "node", ",", "module", "return", "not", "result" ]
Helper function for adding symbols. See add_symbol().
[ "Helper", "function", "for", "adding", "symbols", "." ]
8a20c943dca1049e87d57137938f92d7735828dc
https://github.com/myint/cppclean/blob/8a20c943dca1049e87d57137938f92d7735828dc/cpp/symbols.py#L143-L150
train
34,339
myint/cppclean
cpp/symbols.py
SymbolTable.add_symbol
def add_symbol(self, symbol_name, namespace_stack, node, module): """Adds symbol_name defined in namespace_stack to the symbol table. Args: symbol_name: 'name of the symbol to lookup' namespace_stack: None or ['namespaces', 'symbol', 'defined', 'in'] node: ast.Node that defines this symbol module: module (any object) this symbol is defined in Returns: bool(if symbol was *not* already present) """ # TODO(nnorwitz): verify symbol_name doesn't contain :: ? if namespace_stack: # Handle non-global symbols (ie, in some namespace). last_namespace = self.namespaces for namespace in namespace_stack: last_namespace = last_namespace.setdefault(namespace, {}) else: last_namespace = self.namespaces[None] return self._add(symbol_name, last_namespace, node, module)
python
def add_symbol(self, symbol_name, namespace_stack, node, module): """Adds symbol_name defined in namespace_stack to the symbol table. Args: symbol_name: 'name of the symbol to lookup' namespace_stack: None or ['namespaces', 'symbol', 'defined', 'in'] node: ast.Node that defines this symbol module: module (any object) this symbol is defined in Returns: bool(if symbol was *not* already present) """ # TODO(nnorwitz): verify symbol_name doesn't contain :: ? if namespace_stack: # Handle non-global symbols (ie, in some namespace). last_namespace = self.namespaces for namespace in namespace_stack: last_namespace = last_namespace.setdefault(namespace, {}) else: last_namespace = self.namespaces[None] return self._add(symbol_name, last_namespace, node, module)
[ "def", "add_symbol", "(", "self", ",", "symbol_name", ",", "namespace_stack", ",", "node", ",", "module", ")", ":", "# TODO(nnorwitz): verify symbol_name doesn't contain :: ?", "if", "namespace_stack", ":", "# Handle non-global symbols (ie, in some namespace).", "last_namespace...
Adds symbol_name defined in namespace_stack to the symbol table. Args: symbol_name: 'name of the symbol to lookup' namespace_stack: None or ['namespaces', 'symbol', 'defined', 'in'] node: ast.Node that defines this symbol module: module (any object) this symbol is defined in Returns: bool(if symbol was *not* already present)
[ "Adds", "symbol_name", "defined", "in", "namespace_stack", "to", "the", "symbol", "table", "." ]
8a20c943dca1049e87d57137938f92d7735828dc
https://github.com/myint/cppclean/blob/8a20c943dca1049e87d57137938f92d7735828dc/cpp/symbols.py#L152-L172
train
34,340
myint/cppclean
cpp/symbols.py
SymbolTable.get_namespace
def get_namespace(self, name_seq): """Returns the prefix of names from name_seq that are known namespaces. Args: name_seq: ['names', 'of', 'possible', 'namespace', 'to', 'find'] Returns: ['names', 'that', 'are', 'namespaces', 'possibly', 'empty', 'list'] """ namespaces = self.namespaces result = [] for name in name_seq: namespaces = namespaces.get(name) if not namespaces: break result.append(name) return result
python
def get_namespace(self, name_seq): """Returns the prefix of names from name_seq that are known namespaces. Args: name_seq: ['names', 'of', 'possible', 'namespace', 'to', 'find'] Returns: ['names', 'that', 'are', 'namespaces', 'possibly', 'empty', 'list'] """ namespaces = self.namespaces result = [] for name in name_seq: namespaces = namespaces.get(name) if not namespaces: break result.append(name) return result
[ "def", "get_namespace", "(", "self", ",", "name_seq", ")", ":", "namespaces", "=", "self", ".", "namespaces", "result", "=", "[", "]", "for", "name", "in", "name_seq", ":", "namespaces", "=", "namespaces", ".", "get", "(", "name", ")", "if", "not", "na...
Returns the prefix of names from name_seq that are known namespaces. Args: name_seq: ['names', 'of', 'possible', 'namespace', 'to', 'find'] Returns: ['names', 'that', 'are', 'namespaces', 'possibly', 'empty', 'list']
[ "Returns", "the", "prefix", "of", "names", "from", "name_seq", "that", "are", "known", "namespaces", "." ]
8a20c943dca1049e87d57137938f92d7735828dc
https://github.com/myint/cppclean/blob/8a20c943dca1049e87d57137938f92d7735828dc/cpp/symbols.py#L174-L190
train
34,341
myint/cppclean
cpp/find_warnings.py
WarningHunter._verify_forward_declarations_used
def _verify_forward_declarations_used(self, forward_declarations, decl_uses, file_uses): """Find all the forward declarations that are not used.""" for cls in forward_declarations: if cls in file_uses: if not decl_uses[cls] & USES_DECLARATION: node = forward_declarations[cls] msg = ("'{}' forward declared, " 'but needs to be #included'.format(cls)) self._add_warning(msg, node) else: if decl_uses[cls] == UNUSED: node = forward_declarations[cls] msg = "'{}' not used".format(cls) self._add_warning(msg, node)
python
def _verify_forward_declarations_used(self, forward_declarations, decl_uses, file_uses): """Find all the forward declarations that are not used.""" for cls in forward_declarations: if cls in file_uses: if not decl_uses[cls] & USES_DECLARATION: node = forward_declarations[cls] msg = ("'{}' forward declared, " 'but needs to be #included'.format(cls)) self._add_warning(msg, node) else: if decl_uses[cls] == UNUSED: node = forward_declarations[cls] msg = "'{}' not used".format(cls) self._add_warning(msg, node)
[ "def", "_verify_forward_declarations_used", "(", "self", ",", "forward_declarations", ",", "decl_uses", ",", "file_uses", ")", ":", "for", "cls", "in", "forward_declarations", ":", "if", "cls", "in", "file_uses", ":", "if", "not", "decl_uses", "[", "cls", "]", ...
Find all the forward declarations that are not used.
[ "Find", "all", "the", "forward", "declarations", "that", "are", "not", "used", "." ]
8a20c943dca1049e87d57137938f92d7735828dc
https://github.com/myint/cppclean/blob/8a20c943dca1049e87d57137938f92d7735828dc/cpp/find_warnings.py#L223-L237
train
34,342
myint/cppclean
cpp/find_warnings.py
WarningHunter._check_public_functions
def _check_public_functions(self, primary_header, all_headers): """Verify all the public functions are also declared in a header file.""" public_symbols = {} declared_only_symbols = {} if primary_header: for name, symbol in primary_header.public_symbols.items(): if isinstance(symbol, ast.Function): public_symbols[name] = symbol declared_only_symbols = dict.fromkeys(public_symbols, True) for node in self.ast_list: # Make sure we have a function that should be exported. if not isinstance(node, ast.Function): continue if isinstance(node, ast.Method): # Ensure that for Foo::Bar, Foo is *not* a namespace. # If Foo is a namespace, we have a function and not a method. names = [n.name for n in node.in_class] if names != self.symbol_table.get_namespace(names): continue if not (node.is_definition() and node.is_exportable()): continue # This function should be declared in a header file. name = node.name if name in public_symbols: declared_only_symbols[name] = False else: self._find_public_function_warnings(node, name, primary_header, all_headers) for name, declared_only in declared_only_symbols.items(): if declared_only: node = public_symbols[name] if node.templated_types is None: msg = "'{}' declared but not defined".format(name) self._add_warning(msg, node, primary_header.filename)
python
def _check_public_functions(self, primary_header, all_headers): """Verify all the public functions are also declared in a header file.""" public_symbols = {} declared_only_symbols = {} if primary_header: for name, symbol in primary_header.public_symbols.items(): if isinstance(symbol, ast.Function): public_symbols[name] = symbol declared_only_symbols = dict.fromkeys(public_symbols, True) for node in self.ast_list: # Make sure we have a function that should be exported. if not isinstance(node, ast.Function): continue if isinstance(node, ast.Method): # Ensure that for Foo::Bar, Foo is *not* a namespace. # If Foo is a namespace, we have a function and not a method. names = [n.name for n in node.in_class] if names != self.symbol_table.get_namespace(names): continue if not (node.is_definition() and node.is_exportable()): continue # This function should be declared in a header file. name = node.name if name in public_symbols: declared_only_symbols[name] = False else: self._find_public_function_warnings(node, name, primary_header, all_headers) for name, declared_only in declared_only_symbols.items(): if declared_only: node = public_symbols[name] if node.templated_types is None: msg = "'{}' declared but not defined".format(name) self._add_warning(msg, node, primary_header.filename)
[ "def", "_check_public_functions", "(", "self", ",", "primary_header", ",", "all_headers", ")", ":", "public_symbols", "=", "{", "}", "declared_only_symbols", "=", "{", "}", "if", "primary_header", ":", "for", "name", ",", "symbol", "in", "primary_header", ".", ...
Verify all the public functions are also declared in a header file.
[ "Verify", "all", "the", "public", "functions", "are", "also", "declared", "in", "a", "header", "file", "." ]
8a20c943dca1049e87d57137938f92d7735828dc
https://github.com/myint/cppclean/blob/8a20c943dca1049e87d57137938f92d7735828dc/cpp/find_warnings.py#L521-L560
train
34,343
myint/cppclean
cpp/static_data.py
_find_unused_static_warnings
def _find_unused_static_warnings(filename, lines, ast_list): """Warn about unused static variables.""" static_declarations = dict(_get_static_declarations(ast_list)) def find_variables_use(body): for child in body: if child.name in static_declarations: static_use_counts[child.name] += 1 static_use_counts = collections.Counter() for node in ast_list: if isinstance(node, ast.Function) and node.body: find_variables_use(node.body) elif isinstance(node, ast.Class) and node.body: for child in node.body: if isinstance(child, ast.Function) and child.body: find_variables_use(child.body) count = 0 for (name, _) in sorted(static_declarations.items(), key=lambda x: x[1].start): if not static_use_counts[name]: print("{}:{}: unused variable '{}'".format( filename, lines.get_line_number(static_declarations[name].start), name)) count += 1 return count
python
def _find_unused_static_warnings(filename, lines, ast_list): """Warn about unused static variables.""" static_declarations = dict(_get_static_declarations(ast_list)) def find_variables_use(body): for child in body: if child.name in static_declarations: static_use_counts[child.name] += 1 static_use_counts = collections.Counter() for node in ast_list: if isinstance(node, ast.Function) and node.body: find_variables_use(node.body) elif isinstance(node, ast.Class) and node.body: for child in node.body: if isinstance(child, ast.Function) and child.body: find_variables_use(child.body) count = 0 for (name, _) in sorted(static_declarations.items(), key=lambda x: x[1].start): if not static_use_counts[name]: print("{}:{}: unused variable '{}'".format( filename, lines.get_line_number(static_declarations[name].start), name)) count += 1 return count
[ "def", "_find_unused_static_warnings", "(", "filename", ",", "lines", ",", "ast_list", ")", ":", "static_declarations", "=", "dict", "(", "_get_static_declarations", "(", "ast_list", ")", ")", "def", "find_variables_use", "(", "body", ")", ":", "for", "child", "...
Warn about unused static variables.
[ "Warn", "about", "unused", "static", "variables", "." ]
8a20c943dca1049e87d57137938f92d7735828dc
https://github.com/myint/cppclean/blob/8a20c943dca1049e87d57137938f92d7735828dc/cpp/static_data.py#L84-L112
train
34,344
myint/cppclean
cpp/utils.py
read_file
def read_file(filename, print_error=True): """Returns the contents of a file.""" try: for encoding in ['utf-8', 'latin1']: try: with io.open(filename, encoding=encoding) as fp: return fp.read() except UnicodeDecodeError: pass except IOError as exception: if print_error: print(exception, file=sys.stderr) return None
python
def read_file(filename, print_error=True): """Returns the contents of a file.""" try: for encoding in ['utf-8', 'latin1']: try: with io.open(filename, encoding=encoding) as fp: return fp.read() except UnicodeDecodeError: pass except IOError as exception: if print_error: print(exception, file=sys.stderr) return None
[ "def", "read_file", "(", "filename", ",", "print_error", "=", "True", ")", ":", "try", ":", "for", "encoding", "in", "[", "'utf-8'", ",", "'latin1'", "]", ":", "try", ":", "with", "io", ".", "open", "(", "filename", ",", "encoding", "=", "encoding", ...
Returns the contents of a file.
[ "Returns", "the", "contents", "of", "a", "file", "." ]
8a20c943dca1049e87d57137938f92d7735828dc
https://github.com/myint/cppclean/blob/8a20c943dca1049e87d57137938f92d7735828dc/cpp/utils.py#L29-L41
train
34,345
dbrattli/OSlash
oslash/reader.py
Reader.map
def map(self, fn: Callable[[Any], Any]) -> 'Reader': r"""Map a function over the Reader. Haskell: fmap f m = Reader $ \r -> f (runReader m r). fmap f g = (\x -> f (g x)) """ def _compose(x: Any) -> Any: try: ret = fn(self.run(x)) except TypeError: ret = partial(fn, self.run(x)) return ret return Reader(_compose)
python
def map(self, fn: Callable[[Any], Any]) -> 'Reader': r"""Map a function over the Reader. Haskell: fmap f m = Reader $ \r -> f (runReader m r). fmap f g = (\x -> f (g x)) """ def _compose(x: Any) -> Any: try: ret = fn(self.run(x)) except TypeError: ret = partial(fn, self.run(x)) return ret return Reader(_compose)
[ "def", "map", "(", "self", ",", "fn", ":", "Callable", "[", "[", "Any", "]", ",", "Any", "]", ")", "->", "'Reader'", ":", "def", "_compose", "(", "x", ":", "Any", ")", "->", "Any", ":", "try", ":", "ret", "=", "fn", "(", "self", ".", "run", ...
r"""Map a function over the Reader. Haskell: fmap f m = Reader $ \r -> f (runReader m r). fmap f g = (\x -> f (g x))
[ "r", "Map", "a", "function", "over", "the", "Reader", "." ]
ffdc714c5d454f7519f740254de89f70850929eb
https://github.com/dbrattli/OSlash/blob/ffdc714c5d454f7519f740254de89f70850929eb/oslash/reader.py#L40-L53
train
34,346
dbrattli/OSlash
oslash/reader.py
Reader.bind
def bind(self, fn: "Callable[[Any], Reader]") -> 'Reader': r"""Bind a monadic function to the Reader. Haskell: Reader: m >>= k = Reader $ \r -> runReader (k (runReader m r)) r Function: h >>= f = \w -> f (h w) w """ return Reader(lambda x: fn(self.run(x)).run(x))
python
def bind(self, fn: "Callable[[Any], Reader]") -> 'Reader': r"""Bind a monadic function to the Reader. Haskell: Reader: m >>= k = Reader $ \r -> runReader (k (runReader m r)) r Function: h >>= f = \w -> f (h w) w """ return Reader(lambda x: fn(self.run(x)).run(x))
[ "def", "bind", "(", "self", ",", "fn", ":", "\"Callable[[Any], Reader]\"", ")", "->", "'Reader'", ":", "return", "Reader", "(", "lambda", "x", ":", "fn", "(", "self", ".", "run", "(", "x", ")", ")", ".", "run", "(", "x", ")", ")" ]
r"""Bind a monadic function to the Reader. Haskell: Reader: m >>= k = Reader $ \r -> runReader (k (runReader m r)) r Function: h >>= f = \w -> f (h w) w
[ "r", "Bind", "a", "monadic", "function", "to", "the", "Reader", "." ]
ffdc714c5d454f7519f740254de89f70850929eb
https://github.com/dbrattli/OSlash/blob/ffdc714c5d454f7519f740254de89f70850929eb/oslash/reader.py#L55-L62
train
34,347
dbrattli/OSlash
oslash/reader.py
Reader.run
def run(self, *args, **kwargs) -> Callable: """Return wrapped function. Haskell: runReader :: Reader r a -> r -> a This is the inverse of unit and returns the wrapped function. """ return self.fn(*args, **kwargs) if args or kwargs else self.fn
python
def run(self, *args, **kwargs) -> Callable: """Return wrapped function. Haskell: runReader :: Reader r a -> r -> a This is the inverse of unit and returns the wrapped function. """ return self.fn(*args, **kwargs) if args or kwargs else self.fn
[ "def", "run", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", "->", "Callable", ":", "return", "self", ".", "fn", "(", "*", "args", ",", "*", "*", "kwargs", ")", "if", "args", "or", "kwargs", "else", "self", ".", "fn" ]
Return wrapped function. Haskell: runReader :: Reader r a -> r -> a This is the inverse of unit and returns the wrapped function.
[ "Return", "wrapped", "function", "." ]
ffdc714c5d454f7519f740254de89f70850929eb
https://github.com/dbrattli/OSlash/blob/ffdc714c5d454f7519f740254de89f70850929eb/oslash/reader.py#L85-L92
train
34,348
dbrattli/OSlash
oslash/reader.py
MonadReader.asks
def asks(cls, fn: Callable) -> Reader: """ Given a function it returns a Reader which evaluates that function and returns the result. asks :: (e -> a) -> R e a asks f = do e <- ask return $ f e asks sel = ask >>= return . sel """ return cls.ask().bind(Reader(lambda x: cls.unit(fn(x))))
python
def asks(cls, fn: Callable) -> Reader: """ Given a function it returns a Reader which evaluates that function and returns the result. asks :: (e -> a) -> R e a asks f = do e <- ask return $ f e asks sel = ask >>= return . sel """ return cls.ask().bind(Reader(lambda x: cls.unit(fn(x))))
[ "def", "asks", "(", "cls", ",", "fn", ":", "Callable", ")", "->", "Reader", ":", "return", "cls", ".", "ask", "(", ")", ".", "bind", "(", "Reader", "(", "lambda", "x", ":", "cls", ".", "unit", "(", "fn", "(", "x", ")", ")", ")", ")" ]
Given a function it returns a Reader which evaluates that function and returns the result. asks :: (e -> a) -> R e a asks f = do e <- ask return $ f e asks sel = ask >>= return . sel
[ "Given", "a", "function", "it", "returns", "a", "Reader", "which", "evaluates", "that", "function", "and", "returns", "the", "result", "." ]
ffdc714c5d454f7519f740254de89f70850929eb
https://github.com/dbrattli/OSlash/blob/ffdc714c5d454f7519f740254de89f70850929eb/oslash/reader.py#L132-L144
train
34,349
dbrattli/OSlash
oslash/monadic.py
compose
def compose(f: Callable[[Any], Monad], g: Callable[[Any], Monad]) -> Callable[[Any], Monad]: r"""Monadic compose function. Right-to-left Kleisli composition of two monadic functions. (<=<) :: Monad m => (b -> m c) -> (a -> m b) -> a -> m c f <=< g = \x -> g x >>= f """ return lambda x: g(x).bind(f)
python
def compose(f: Callable[[Any], Monad], g: Callable[[Any], Monad]) -> Callable[[Any], Monad]: r"""Monadic compose function. Right-to-left Kleisli composition of two monadic functions. (<=<) :: Monad m => (b -> m c) -> (a -> m b) -> a -> m c f <=< g = \x -> g x >>= f """ return lambda x: g(x).bind(f)
[ "def", "compose", "(", "f", ":", "Callable", "[", "[", "Any", "]", ",", "Monad", "]", ",", "g", ":", "Callable", "[", "[", "Any", "]", ",", "Monad", "]", ")", "->", "Callable", "[", "[", "Any", "]", ",", "Monad", "]", ":", "return", "lambda", ...
r"""Monadic compose function. Right-to-left Kleisli composition of two monadic functions. (<=<) :: Monad m => (b -> m c) -> (a -> m b) -> a -> m c f <=< g = \x -> g x >>= f
[ "r", "Monadic", "compose", "function", "." ]
ffdc714c5d454f7519f740254de89f70850929eb
https://github.com/dbrattli/OSlash/blob/ffdc714c5d454f7519f740254de89f70850929eb/oslash/monadic.py#L12-L20
train
34,350
dbrattli/OSlash
oslash/util/fn.py
compose
def compose(*funcs: Callable) -> Callable: """Compose multiple functions right to left. Composes zero or more functions into a functional composition. The functions are composed right to left. A composition of zero functions gives back the identity function. compose()(x) == x compose(f)(x) == f(x) compose(g, f)(x) == g(f(x)) compose(h, g, f)(x) == h(g(f(x))) ... Returns the composed function. """ def _compose(*args, **kw): """Reduce functions to a single function.""" ret = reduce(lambda acc, x: lambda f: f(acc(x)), funcs[::-1], lambda f: f(*args, **kw)) return ret(lambda x: x) return _compose
python
def compose(*funcs: Callable) -> Callable: """Compose multiple functions right to left. Composes zero or more functions into a functional composition. The functions are composed right to left. A composition of zero functions gives back the identity function. compose()(x) == x compose(f)(x) == f(x) compose(g, f)(x) == g(f(x)) compose(h, g, f)(x) == h(g(f(x))) ... Returns the composed function. """ def _compose(*args, **kw): """Reduce functions to a single function.""" ret = reduce(lambda acc, x: lambda f: f(acc(x)), funcs[::-1], lambda f: f(*args, **kw)) return ret(lambda x: x) return _compose
[ "def", "compose", "(", "*", "funcs", ":", "Callable", ")", "->", "Callable", ":", "def", "_compose", "(", "*", "args", ",", "*", "*", "kw", ")", ":", "\"\"\"Reduce functions to a single function.\"\"\"", "ret", "=", "reduce", "(", "lambda", "acc", ",", "x"...
Compose multiple functions right to left. Composes zero or more functions into a functional composition. The functions are composed right to left. A composition of zero functions gives back the identity function. compose()(x) == x compose(f)(x) == f(x) compose(g, f)(x) == g(f(x)) compose(h, g, f)(x) == h(g(f(x))) ... Returns the composed function.
[ "Compose", "multiple", "functions", "right", "to", "left", "." ]
ffdc714c5d454f7519f740254de89f70850929eb
https://github.com/dbrattli/OSlash/blob/ffdc714c5d454f7519f740254de89f70850929eb/oslash/util/fn.py#L6-L27
train
34,351
dbrattli/OSlash
oslash/state.py
State.run
def run(self, state: Any) -> Tuple[Any, Any]: """Return wrapped state computation. This is the inverse of unit and returns the wrapped function. """ return self._value(state)
python
def run(self, state: Any) -> Tuple[Any, Any]: """Return wrapped state computation. This is the inverse of unit and returns the wrapped function. """ return self._value(state)
[ "def", "run", "(", "self", ",", "state", ":", "Any", ")", "->", "Tuple", "[", "Any", ",", "Any", "]", ":", "return", "self", ".", "_value", "(", "state", ")" ]
Return wrapped state computation. This is the inverse of unit and returns the wrapped function.
[ "Return", "wrapped", "state", "computation", "." ]
ffdc714c5d454f7519f740254de89f70850929eb
https://github.com/dbrattli/OSlash/blob/ffdc714c5d454f7519f740254de89f70850929eb/oslash/state.py#L63-L68
train
34,352
dbrattli/OSlash
oslash/writer.py
Writer.map
def map(self, func: Callable[[Tuple[Any, Log]], Tuple[Any, Log]]) -> 'Writer': """Map a function func over the Writer value. Haskell: fmap f m = Writer $ let (a, w) = runWriter m in (f a, w) Keyword arguments: func -- Mapper function: """ a, w = self.run() b, _w = func((a, w)) return Writer(b, _w)
python
def map(self, func: Callable[[Tuple[Any, Log]], Tuple[Any, Log]]) -> 'Writer': """Map a function func over the Writer value. Haskell: fmap f m = Writer $ let (a, w) = runWriter m in (f a, w) Keyword arguments: func -- Mapper function: """ a, w = self.run() b, _w = func((a, w)) return Writer(b, _w)
[ "def", "map", "(", "self", ",", "func", ":", "Callable", "[", "[", "Tuple", "[", "Any", ",", "Log", "]", "]", ",", "Tuple", "[", "Any", ",", "Log", "]", "]", ")", "->", "'Writer'", ":", "a", ",", "w", "=", "self", ".", "run", "(", ")", "b",...
Map a function func over the Writer value. Haskell: fmap f m = Writer $ let (a, w) = runWriter m in (f a, w) Keyword arguments: func -- Mapper function:
[ "Map", "a", "function", "func", "over", "the", "Writer", "value", "." ]
ffdc714c5d454f7519f740254de89f70850929eb
https://github.com/dbrattli/OSlash/blob/ffdc714c5d454f7519f740254de89f70850929eb/oslash/writer.py#L23-L34
train
34,353
dbrattli/OSlash
oslash/writer.py
Writer.bind
def bind(self, func: Callable[[Any], 'Writer']) -> 'Writer': """Flat is better than nested. Haskell: (Writer (x, v)) >>= f = let (Writer (y, v')) = f x in Writer (y, v `append` v') """ a, w = self.run() b, w_ = func(a).run() if isinstance(w_, Monoid): w__ = cast(Monoid, w).append(w_) else: w__ = w + w_ return Writer(b, w__)
python
def bind(self, func: Callable[[Any], 'Writer']) -> 'Writer': """Flat is better than nested. Haskell: (Writer (x, v)) >>= f = let (Writer (y, v')) = f x in Writer (y, v `append` v') """ a, w = self.run() b, w_ = func(a).run() if isinstance(w_, Monoid): w__ = cast(Monoid, w).append(w_) else: w__ = w + w_ return Writer(b, w__)
[ "def", "bind", "(", "self", ",", "func", ":", "Callable", "[", "[", "Any", "]", ",", "'Writer'", "]", ")", "->", "'Writer'", ":", "a", ",", "w", "=", "self", ".", "run", "(", ")", "b", ",", "w_", "=", "func", "(", "a", ")", ".", "run", "(",...
Flat is better than nested. Haskell: (Writer (x, v)) >>= f = let (Writer (y, v')) = f x in Writer (y, v `append` v')
[ "Flat", "is", "better", "than", "nested", "." ]
ffdc714c5d454f7519f740254de89f70850929eb
https://github.com/dbrattli/OSlash/blob/ffdc714c5d454f7519f740254de89f70850929eb/oslash/writer.py#L36-L51
train
34,354
dbrattli/OSlash
oslash/writer.py
Writer.apply_log
def apply_log(a: tuple, func: Callable[[Any], Tuple[Any, Log]]) -> Tuple[Any, Log]: """Apply a function to a value with a log. Helper function to apply a function to a value with a log tuple. """ value, log = a new, entry = func(value) return new, log + entry
python
def apply_log(a: tuple, func: Callable[[Any], Tuple[Any, Log]]) -> Tuple[Any, Log]: """Apply a function to a value with a log. Helper function to apply a function to a value with a log tuple. """ value, log = a new, entry = func(value) return new, log + entry
[ "def", "apply_log", "(", "a", ":", "tuple", ",", "func", ":", "Callable", "[", "[", "Any", "]", ",", "Tuple", "[", "Any", ",", "Log", "]", "]", ")", "->", "Tuple", "[", "Any", ",", "Log", "]", ":", "value", ",", "log", "=", "a", "new", ",", ...
Apply a function to a value with a log. Helper function to apply a function to a value with a log tuple.
[ "Apply", "a", "function", "to", "a", "value", "with", "a", "log", "." ]
ffdc714c5d454f7519f740254de89f70850929eb
https://github.com/dbrattli/OSlash/blob/ffdc714c5d454f7519f740254de89f70850929eb/oslash/writer.py#L79-L86
train
34,355
dbrattli/OSlash
oslash/writer.py
Writer.create
def create(cls, class_name: str, monoid_type=Union[Monoid, str]): """Create Writer subclass using specified monoid type. lets us create a Writer that uses a different monoid than str for the log. """ def unit(cls, value): if hasattr(monoid_type, "empty"): log = monoid_type.empty() else: log = monoid_type() return cls(value, log) return type(class_name, (Writer, ), dict(unit=classmethod(unit)))
python
def create(cls, class_name: str, monoid_type=Union[Monoid, str]): """Create Writer subclass using specified monoid type. lets us create a Writer that uses a different monoid than str for the log. """ def unit(cls, value): if hasattr(monoid_type, "empty"): log = monoid_type.empty() else: log = monoid_type() return cls(value, log) return type(class_name, (Writer, ), dict(unit=classmethod(unit)))
[ "def", "create", "(", "cls", ",", "class_name", ":", "str", ",", "monoid_type", "=", "Union", "[", "Monoid", ",", "str", "]", ")", ":", "def", "unit", "(", "cls", ",", "value", ")", ":", "if", "hasattr", "(", "monoid_type", ",", "\"empty\"", ")", "...
Create Writer subclass using specified monoid type. lets us create a Writer that uses a different monoid than str for the log.
[ "Create", "Writer", "subclass", "using", "specified", "monoid", "type", "." ]
ffdc714c5d454f7519f740254de89f70850929eb
https://github.com/dbrattli/OSlash/blob/ffdc714c5d454f7519f740254de89f70850929eb/oslash/writer.py#L98-L113
train
34,356
dbrattli/OSlash
oslash/identity.py
Identity.map
def map(self, mapper: Callable[[Any], Any]) -> 'Identity': """Map a function over wrapped values.""" value = self._value try: result = mapper(value) except TypeError: result = partial(mapper, value) return Identity(result)
python
def map(self, mapper: Callable[[Any], Any]) -> 'Identity': """Map a function over wrapped values.""" value = self._value try: result = mapper(value) except TypeError: result = partial(mapper, value) return Identity(result)
[ "def", "map", "(", "self", ",", "mapper", ":", "Callable", "[", "[", "Any", "]", ",", "Any", "]", ")", "->", "'Identity'", ":", "value", "=", "self", ".", "_value", "try", ":", "result", "=", "mapper", "(", "value", ")", "except", "TypeError", ":",...
Map a function over wrapped values.
[ "Map", "a", "function", "over", "wrapped", "values", "." ]
ffdc714c5d454f7519f740254de89f70850929eb
https://github.com/dbrattli/OSlash/blob/ffdc714c5d454f7519f740254de89f70850929eb/oslash/identity.py#L24-L32
train
34,357
dbrattli/OSlash
oslash/ioaction.py
Put.run
def run(self, world: int) -> IO: """Run IO action""" text, action = self._value new_world = pure_print(world, text) return action(world=new_world)
python
def run(self, world: int) -> IO: """Run IO action""" text, action = self._value new_world = pure_print(world, text) return action(world=new_world)
[ "def", "run", "(", "self", ",", "world", ":", "int", ")", "->", "IO", ":", "text", ",", "action", "=", "self", ".", "_value", "new_world", "=", "pure_print", "(", "world", ",", "text", ")", "return", "action", "(", "world", "=", "new_world", ")" ]
Run IO action
[ "Run", "IO", "action" ]
ffdc714c5d454f7519f740254de89f70850929eb
https://github.com/dbrattli/OSlash/blob/ffdc714c5d454f7519f740254de89f70850929eb/oslash/ioaction.py#L79-L84
train
34,358
dbrattli/OSlash
oslash/abc/monad.py
Monad.lift
def lift(self, func): """Map function over monadic value. Takes a function and a monadic value and maps the function over the monadic value Haskell: liftM :: (Monad m) => (a -> b) -> m a -> m b This is really the same function as Functor.fmap, but is instead implemented using bind, and does not rely on us inheriting from Functor. """ return self.bind(lambda x: self.unit(func(x)))
python
def lift(self, func): """Map function over monadic value. Takes a function and a monadic value and maps the function over the monadic value Haskell: liftM :: (Monad m) => (a -> b) -> m a -> m b This is really the same function as Functor.fmap, but is instead implemented using bind, and does not rely on us inheriting from Functor. """ return self.bind(lambda x: self.unit(func(x)))
[ "def", "lift", "(", "self", ",", "func", ")", ":", "return", "self", ".", "bind", "(", "lambda", "x", ":", "self", ".", "unit", "(", "func", "(", "x", ")", ")", ")" ]
Map function over monadic value. Takes a function and a monadic value and maps the function over the monadic value Haskell: liftM :: (Monad m) => (a -> b) -> m a -> m b This is really the same function as Functor.fmap, but is instead implemented using bind, and does not rely on us inheriting from Functor.
[ "Map", "function", "over", "monadic", "value", "." ]
ffdc714c5d454f7519f740254de89f70850929eb
https://github.com/dbrattli/OSlash/blob/ffdc714c5d454f7519f740254de89f70850929eb/oslash/abc/monad.py#L58-L71
train
34,359
dbrattli/OSlash
oslash/observable.py
Observable.map
def map(self, mapper: Callable[[Any], Any]) -> 'Observable': r"""Map a function over an observable. Haskell: fmap f m = Cont $ \c -> runCont m (c . f) """ source = self return Observable(lambda on_next: source.subscribe(compose(on_next, mapper)))
python
def map(self, mapper: Callable[[Any], Any]) -> 'Observable': r"""Map a function over an observable. Haskell: fmap f m = Cont $ \c -> runCont m (c . f) """ source = self return Observable(lambda on_next: source.subscribe(compose(on_next, mapper)))
[ "def", "map", "(", "self", ",", "mapper", ":", "Callable", "[", "[", "Any", "]", ",", "Any", "]", ")", "->", "'Observable'", ":", "source", "=", "self", "return", "Observable", "(", "lambda", "on_next", ":", "source", ".", "subscribe", "(", "compose", ...
r"""Map a function over an observable. Haskell: fmap f m = Cont $ \c -> runCont m (c . f)
[ "r", "Map", "a", "function", "over", "an", "observable", "." ]
ffdc714c5d454f7519f740254de89f70850929eb
https://github.com/dbrattli/OSlash/blob/ffdc714c5d454f7519f740254de89f70850929eb/oslash/observable.py#L39-L45
train
34,360
dbrattli/OSlash
oslash/observable.py
Observable.filter
def filter(self, predicate) -> 'Observable': """Filter the on_next continuation functions""" source = self def subscribe(on_next): def _next(x): if predicate(x): on_next(x) return source.subscribe(_next) return Observable(subscribe)
python
def filter(self, predicate) -> 'Observable': """Filter the on_next continuation functions""" source = self def subscribe(on_next): def _next(x): if predicate(x): on_next(x) return source.subscribe(_next) return Observable(subscribe)
[ "def", "filter", "(", "self", ",", "predicate", ")", "->", "'Observable'", ":", "source", "=", "self", "def", "subscribe", "(", "on_next", ")", ":", "def", "_next", "(", "x", ")", ":", "if", "predicate", "(", "x", ")", ":", "on_next", "(", "x", ")"...
Filter the on_next continuation functions
[ "Filter", "the", "on_next", "continuation", "functions" ]
ffdc714c5d454f7519f740254de89f70850929eb
https://github.com/dbrattli/OSlash/blob/ffdc714c5d454f7519f740254de89f70850929eb/oslash/observable.py#L56-L66
train
34,361
dbrattli/OSlash
oslash/maybe.py
Just.bind
def bind(self, func: Callable[[Any], Maybe]) -> Maybe: """Just x >>= f = f x.""" value = self._value return func(value)
python
def bind(self, func: Callable[[Any], Maybe]) -> Maybe: """Just x >>= f = f x.""" value = self._value return func(value)
[ "def", "bind", "(", "self", ",", "func", ":", "Callable", "[", "[", "Any", "]", ",", "Maybe", "]", ")", "->", "Maybe", ":", "value", "=", "self", ".", "_value", "return", "func", "(", "value", ")" ]
Just x >>= f = f x.
[ "Just", "x", ">>", "=", "f", "=", "f", "x", "." ]
ffdc714c5d454f7519f740254de89f70850929eb
https://github.com/dbrattli/OSlash/blob/ffdc714c5d454f7519f740254de89f70850929eb/oslash/maybe.py#L113-L117
train
34,362
dbrattli/OSlash
oslash/list.py
List.cons
def cons(self, element: Any) -> 'List': """Add element to front of List.""" tail = self._get_value() return List(lambda sel: sel(element, tail))
python
def cons(self, element: Any) -> 'List': """Add element to front of List.""" tail = self._get_value() return List(lambda sel: sel(element, tail))
[ "def", "cons", "(", "self", ",", "element", ":", "Any", ")", "->", "'List'", ":", "tail", "=", "self", ".", "_get_value", "(", ")", "return", "List", "(", "lambda", "sel", ":", "sel", "(", "element", ",", "tail", ")", ")" ]
Add element to front of List.
[ "Add", "element", "to", "front", "of", "List", "." ]
ffdc714c5d454f7519f740254de89f70850929eb
https://github.com/dbrattli/OSlash/blob/ffdc714c5d454f7519f740254de89f70850929eb/oslash/list.py#L22-L26
train
34,363
dbrattli/OSlash
oslash/list.py
List.head
def head(self) -> Any: """Retrive first element in List.""" lambda_list = self._get_value() return lambda_list(lambda head, _: head)
python
def head(self) -> Any: """Retrive first element in List.""" lambda_list = self._get_value() return lambda_list(lambda head, _: head)
[ "def", "head", "(", "self", ")", "->", "Any", ":", "lambda_list", "=", "self", ".", "_get_value", "(", ")", "return", "lambda_list", "(", "lambda", "head", ",", "_", ":", "head", ")" ]
Retrive first element in List.
[ "Retrive", "first", "element", "in", "List", "." ]
ffdc714c5d454f7519f740254de89f70850929eb
https://github.com/dbrattli/OSlash/blob/ffdc714c5d454f7519f740254de89f70850929eb/oslash/list.py#L28-L32
train
34,364
dbrattli/OSlash
oslash/list.py
List.tail
def tail(self) -> 'List': """Return tail of List.""" lambda_list = self._get_value() return List(lambda_list(lambda _, tail: tail))
python
def tail(self) -> 'List': """Return tail of List.""" lambda_list = self._get_value() return List(lambda_list(lambda _, tail: tail))
[ "def", "tail", "(", "self", ")", "->", "'List'", ":", "lambda_list", "=", "self", ".", "_get_value", "(", ")", "return", "List", "(", "lambda_list", "(", "lambda", "_", ",", "tail", ":", "tail", ")", ")" ]
Return tail of List.
[ "Return", "tail", "of", "List", "." ]
ffdc714c5d454f7519f740254de89f70850929eb
https://github.com/dbrattli/OSlash/blob/ffdc714c5d454f7519f740254de89f70850929eb/oslash/list.py#L34-L38
train
34,365
dbrattli/OSlash
oslash/list.py
List.map
def map(self, mapper: Callable[[Any], Any]) -> 'List': """Map a function over a List.""" try: ret = List.from_iterable([mapper(x) for x in self]) except TypeError: ret = List.from_iterable([partial(mapper, x) for x in self]) return ret
python
def map(self, mapper: Callable[[Any], Any]) -> 'List': """Map a function over a List.""" try: ret = List.from_iterable([mapper(x) for x in self]) except TypeError: ret = List.from_iterable([partial(mapper, x) for x in self]) return ret
[ "def", "map", "(", "self", ",", "mapper", ":", "Callable", "[", "[", "Any", "]", ",", "Any", "]", ")", "->", "'List'", ":", "try", ":", "ret", "=", "List", ".", "from_iterable", "(", "[", "mapper", "(", "x", ")", "for", "x", "in", "self", "]", ...
Map a function over a List.
[ "Map", "a", "function", "over", "a", "List", "." ]
ffdc714c5d454f7519f740254de89f70850929eb
https://github.com/dbrattli/OSlash/blob/ffdc714c5d454f7519f740254de89f70850929eb/oslash/list.py#L51-L57
train
34,366
dbrattli/OSlash
oslash/list.py
List.append
def append(self, other: 'List') -> 'List': """Append other list to this list.""" if self.null(): return other return (self.tail().append(other)).cons(self.head())
python
def append(self, other: 'List') -> 'List': """Append other list to this list.""" if self.null(): return other return (self.tail().append(other)).cons(self.head())
[ "def", "append", "(", "self", ",", "other", ":", "'List'", ")", "->", "'List'", ":", "if", "self", ".", "null", "(", ")", ":", "return", "other", "return", "(", "self", ".", "tail", "(", ")", ".", "append", "(", "other", ")", ")", ".", "cons", ...
Append other list to this list.
[ "Append", "other", "list", "to", "this", "list", "." ]
ffdc714c5d454f7519f740254de89f70850929eb
https://github.com/dbrattli/OSlash/blob/ffdc714c5d454f7519f740254de89f70850929eb/oslash/list.py#L73-L78
train
34,367
dbrattli/OSlash
oslash/list.py
List.bind
def bind(self, fn: Callable[[Any], 'List']) -> 'List': """Flatten and map the List. Haskell: xs >>= f = concat (map f xs) """ return List.concat(self.map(fn))
python
def bind(self, fn: Callable[[Any], 'List']) -> 'List': """Flatten and map the List. Haskell: xs >>= f = concat (map f xs) """ return List.concat(self.map(fn))
[ "def", "bind", "(", "self", ",", "fn", ":", "Callable", "[", "[", "Any", "]", ",", "'List'", "]", ")", "->", "'List'", ":", "return", "List", ".", "concat", "(", "self", ".", "map", "(", "fn", ")", ")" ]
Flatten and map the List. Haskell: xs >>= f = concat (map f xs)
[ "Flatten", "and", "map", "the", "List", "." ]
ffdc714c5d454f7519f740254de89f70850929eb
https://github.com/dbrattli/OSlash/blob/ffdc714c5d454f7519f740254de89f70850929eb/oslash/list.py#L80-L85
train
34,368
dbrattli/OSlash
oslash/list.py
List.from_iterable
def from_iterable(cls, iterable: Iterable) -> 'List': """Create list from iterable.""" iterator = iter(iterable) def recurse() -> List: try: value = next(iterator) except StopIteration: return List.empty() return List.unit(value).append(recurse()) return List.empty().append(recurse())
python
def from_iterable(cls, iterable: Iterable) -> 'List': """Create list from iterable.""" iterator = iter(iterable) def recurse() -> List: try: value = next(iterator) except StopIteration: return List.empty() return List.unit(value).append(recurse()) return List.empty().append(recurse())
[ "def", "from_iterable", "(", "cls", ",", "iterable", ":", "Iterable", ")", "->", "'List'", ":", "iterator", "=", "iter", "(", "iterable", ")", "def", "recurse", "(", ")", "->", "List", ":", "try", ":", "value", "=", "next", "(", "iterator", ")", "exc...
Create list from iterable.
[ "Create", "list", "from", "iterable", "." ]
ffdc714c5d454f7519f740254de89f70850929eb
https://github.com/dbrattli/OSlash/blob/ffdc714c5d454f7519f740254de89f70850929eb/oslash/list.py#L88-L100
train
34,369
dbrattli/OSlash
oslash/cont.py
Cont.map
def map(self, fn: Callable[[Any], Any]) -> 'Cont': r"""Map a function over a continuation. Haskell: fmap f m = Cont $ \c -> runCont m (c . f) """ return Cont(lambda c: self.run(compose(c, fn)))
python
def map(self, fn: Callable[[Any], Any]) -> 'Cont': r"""Map a function over a continuation. Haskell: fmap f m = Cont $ \c -> runCont m (c . f) """ return Cont(lambda c: self.run(compose(c, fn)))
[ "def", "map", "(", "self", ",", "fn", ":", "Callable", "[", "[", "Any", "]", ",", "Any", "]", ")", "->", "'Cont'", ":", "return", "Cont", "(", "lambda", "c", ":", "self", ".", "run", "(", "compose", "(", "c", ",", "fn", ")", ")", ")" ]
r"""Map a function over a continuation. Haskell: fmap f m = Cont $ \c -> runCont m (c . f)
[ "r", "Map", "a", "function", "over", "a", "continuation", "." ]
ffdc714c5d454f7519f740254de89f70850929eb
https://github.com/dbrattli/OSlash/blob/ffdc714c5d454f7519f740254de89f70850929eb/oslash/cont.py#L38-L43
train
34,370
romanvm/python-web-pdb
web_pdb/wsgi_app.py
compress
def compress(func): """ Compress route return data with gzip compression """ @wraps(func) def wrapper(*args, **kwargs): result = func(*args, **kwargs) if ('gzip' in bottle.request.headers.get('Accept-Encoding', '') and isinstance(result, string_type) and len(result) > 1024): if isinstance(result, unicode): result = result.encode('utf-8') tmp_fo = BytesIO() with gzip.GzipFile(mode='wb', fileobj=tmp_fo) as gzip_fo: gzip_fo.write(result) result = tmp_fo.getvalue() bottle.response.add_header('Content-Encoding', 'gzip') return result return wrapper
python
def compress(func): """ Compress route return data with gzip compression """ @wraps(func) def wrapper(*args, **kwargs): result = func(*args, **kwargs) if ('gzip' in bottle.request.headers.get('Accept-Encoding', '') and isinstance(result, string_type) and len(result) > 1024): if isinstance(result, unicode): result = result.encode('utf-8') tmp_fo = BytesIO() with gzip.GzipFile(mode='wb', fileobj=tmp_fo) as gzip_fo: gzip_fo.write(result) result = tmp_fo.getvalue() bottle.response.add_header('Content-Encoding', 'gzip') return result return wrapper
[ "def", "compress", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "result", "=", "func", "(", "*", "args", ",", "*", "*", "kwargs", ")", "if", "(", "'gzip'", "in", ...
Compress route return data with gzip compression
[ "Compress", "route", "return", "data", "with", "gzip", "compression" ]
f2df2207e870dbf50a4bb30ca12a59cab39a809f
https://github.com/romanvm/python-web-pdb/blob/f2df2207e870dbf50a4bb30ca12a59cab39a809f/web_pdb/wsgi_app.py#L49-L67
train
34,371
romanvm/python-web-pdb
web_pdb/__init__.py
set_trace
def set_trace(host='', port=5555, patch_stdstreams=False): """ Start the debugger This method suspends execution of the current script and starts a PDB debugging session. The web-interface is opened on the specified port (default: ``5555``). Example:: import web_pdb;web_pdb.set_trace() Subsequent :func:`set_trace` calls can be used as hardcoded breakpoints. :param host: web-UI hostname or IP-address :type host: str :param port: web-UI port. If ``port=-1``, choose a random port value between 32768 and 65536. :type port: int :param patch_stdstreams: redirect all standard input and output streams to the web-UI. :type patch_stdstreams: bool """ pdb = WebPdb.active_instance if pdb is None: pdb = WebPdb(host, port, patch_stdstreams) else: # If the debugger is still attached reset trace to a new location pdb.remove_trace() pdb.set_trace(sys._getframe().f_back)
python
def set_trace(host='', port=5555, patch_stdstreams=False): """ Start the debugger This method suspends execution of the current script and starts a PDB debugging session. The web-interface is opened on the specified port (default: ``5555``). Example:: import web_pdb;web_pdb.set_trace() Subsequent :func:`set_trace` calls can be used as hardcoded breakpoints. :param host: web-UI hostname or IP-address :type host: str :param port: web-UI port. If ``port=-1``, choose a random port value between 32768 and 65536. :type port: int :param patch_stdstreams: redirect all standard input and output streams to the web-UI. :type patch_stdstreams: bool """ pdb = WebPdb.active_instance if pdb is None: pdb = WebPdb(host, port, patch_stdstreams) else: # If the debugger is still attached reset trace to a new location pdb.remove_trace() pdb.set_trace(sys._getframe().f_back)
[ "def", "set_trace", "(", "host", "=", "''", ",", "port", "=", "5555", ",", "patch_stdstreams", "=", "False", ")", ":", "pdb", "=", "WebPdb", ".", "active_instance", "if", "pdb", "is", "None", ":", "pdb", "=", "WebPdb", "(", "host", ",", "port", ",", ...
Start the debugger This method suspends execution of the current script and starts a PDB debugging session. The web-interface is opened on the specified port (default: ``5555``). Example:: import web_pdb;web_pdb.set_trace() Subsequent :func:`set_trace` calls can be used as hardcoded breakpoints. :param host: web-UI hostname or IP-address :type host: str :param port: web-UI port. If ``port=-1``, choose a random port value between 32768 and 65536. :type port: int :param patch_stdstreams: redirect all standard input and output streams to the web-UI. :type patch_stdstreams: bool
[ "Start", "the", "debugger" ]
f2df2207e870dbf50a4bb30ca12a59cab39a809f
https://github.com/romanvm/python-web-pdb/blob/f2df2207e870dbf50a4bb30ca12a59cab39a809f/web_pdb/__init__.py#L249-L278
train
34,372
romanvm/python-web-pdb
web_pdb/__init__.py
post_mortem
def post_mortem(tb=None, host='', port=5555, patch_stdstreams=False): """ Start post-mortem debugging for the provided traceback object If no traceback is provided the debugger tries to obtain a traceback for the last unhandled exception. Example:: try: # Some error-prone code assert ham == spam except: web_pdb.post_mortem() :param tb: traceback for post-mortem debugging :type tb: types.TracebackType :param host: web-UI hostname or IP-address :type host: str :param port: web-UI port. If ``port=-1``, choose a random port value between 32768 and 65536. :type port: int :param patch_stdstreams: redirect all standard input and output streams to the web-UI. :type patch_stdstreams: bool :raises ValueError: if no valid traceback is provided and the Python interpreter is not handling any exception """ # handling the default if tb is None: # sys.exc_info() returns (type, value, traceback) if an exception is # being handled, otherwise it returns (None, None, None) t, v, tb = sys.exc_info() exc_data = traceback.format_exception(t, v, tb) else: exc_data = traceback.format_tb(tb) if tb is None: raise ValueError('A valid traceback must be passed if no ' 'exception is being handled') pdb = WebPdb.active_instance if pdb is None: pdb = WebPdb(host, port, patch_stdstreams) else: pdb.remove_trace() pdb.console.writeline('*** Web-PDB post-mortem ***\n') pdb.console.writeline(''.join(exc_data)) pdb.reset() pdb.interaction(None, tb)
python
def post_mortem(tb=None, host='', port=5555, patch_stdstreams=False): """ Start post-mortem debugging for the provided traceback object If no traceback is provided the debugger tries to obtain a traceback for the last unhandled exception. Example:: try: # Some error-prone code assert ham == spam except: web_pdb.post_mortem() :param tb: traceback for post-mortem debugging :type tb: types.TracebackType :param host: web-UI hostname or IP-address :type host: str :param port: web-UI port. If ``port=-1``, choose a random port value between 32768 and 65536. :type port: int :param patch_stdstreams: redirect all standard input and output streams to the web-UI. :type patch_stdstreams: bool :raises ValueError: if no valid traceback is provided and the Python interpreter is not handling any exception """ # handling the default if tb is None: # sys.exc_info() returns (type, value, traceback) if an exception is # being handled, otherwise it returns (None, None, None) t, v, tb = sys.exc_info() exc_data = traceback.format_exception(t, v, tb) else: exc_data = traceback.format_tb(tb) if tb is None: raise ValueError('A valid traceback must be passed if no ' 'exception is being handled') pdb = WebPdb.active_instance if pdb is None: pdb = WebPdb(host, port, patch_stdstreams) else: pdb.remove_trace() pdb.console.writeline('*** Web-PDB post-mortem ***\n') pdb.console.writeline(''.join(exc_data)) pdb.reset() pdb.interaction(None, tb)
[ "def", "post_mortem", "(", "tb", "=", "None", ",", "host", "=", "''", ",", "port", "=", "5555", ",", "patch_stdstreams", "=", "False", ")", ":", "# handling the default", "if", "tb", "is", "None", ":", "# sys.exc_info() returns (type, value, traceback) if an excep...
Start post-mortem debugging for the provided traceback object If no traceback is provided the debugger tries to obtain a traceback for the last unhandled exception. Example:: try: # Some error-prone code assert ham == spam except: web_pdb.post_mortem() :param tb: traceback for post-mortem debugging :type tb: types.TracebackType :param host: web-UI hostname or IP-address :type host: str :param port: web-UI port. If ``port=-1``, choose a random port value between 32768 and 65536. :type port: int :param patch_stdstreams: redirect all standard input and output streams to the web-UI. :type patch_stdstreams: bool :raises ValueError: if no valid traceback is provided and the Python interpreter is not handling any exception
[ "Start", "post", "-", "mortem", "debugging", "for", "the", "provided", "traceback", "object" ]
f2df2207e870dbf50a4bb30ca12a59cab39a809f
https://github.com/romanvm/python-web-pdb/blob/f2df2207e870dbf50a4bb30ca12a59cab39a809f/web_pdb/__init__.py#L281-L328
train
34,373
romanvm/python-web-pdb
web_pdb/__init__.py
catch_post_mortem
def catch_post_mortem(host='', port=5555, patch_stdstreams=False): """ A context manager for tracking potentially error-prone code If an unhandled exception is raised inside context manager's code block, the post-mortem debugger is started automatically. Example:: with web_pdb.catch_post_mortem() # Some error-prone code assert ham == spam :param host: web-UI hostname or IP-address :type host: str :param port: web-UI port. If ``port=-1``, choose a random port value between 32768 and 65536. :type port: int :param patch_stdstreams: redirect all standard input and output streams to the web-UI. :type patch_stdstreams: bool """ try: yield except Exception: post_mortem(None, host, port, patch_stdstreams)
python
def catch_post_mortem(host='', port=5555, patch_stdstreams=False): """ A context manager for tracking potentially error-prone code If an unhandled exception is raised inside context manager's code block, the post-mortem debugger is started automatically. Example:: with web_pdb.catch_post_mortem() # Some error-prone code assert ham == spam :param host: web-UI hostname or IP-address :type host: str :param port: web-UI port. If ``port=-1``, choose a random port value between 32768 and 65536. :type port: int :param patch_stdstreams: redirect all standard input and output streams to the web-UI. :type patch_stdstreams: bool """ try: yield except Exception: post_mortem(None, host, port, patch_stdstreams)
[ "def", "catch_post_mortem", "(", "host", "=", "''", ",", "port", "=", "5555", ",", "patch_stdstreams", "=", "False", ")", ":", "try", ":", "yield", "except", "Exception", ":", "post_mortem", "(", "None", ",", "host", ",", "port", ",", "patch_stdstreams", ...
A context manager for tracking potentially error-prone code If an unhandled exception is raised inside context manager's code block, the post-mortem debugger is started automatically. Example:: with web_pdb.catch_post_mortem() # Some error-prone code assert ham == spam :param host: web-UI hostname or IP-address :type host: str :param port: web-UI port. If ``port=-1``, choose a random port value between 32768 and 65536. :type port: int :param patch_stdstreams: redirect all standard input and output streams to the web-UI. :type patch_stdstreams: bool
[ "A", "context", "manager", "for", "tracking", "potentially", "error", "-", "prone", "code" ]
f2df2207e870dbf50a4bb30ca12a59cab39a809f
https://github.com/romanvm/python-web-pdb/blob/f2df2207e870dbf50a4bb30ca12a59cab39a809f/web_pdb/__init__.py#L332-L357
train
34,374
romanvm/python-web-pdb
web_pdb/__init__.py
WebPdb.do_quit
def do_quit(self, arg): """ quit || exit || q Stop and quit the current debugging session """ for name, fh in self._backup: setattr(sys, name, fh) self.console.writeline('*** Aborting program ***\n') self.console.flush() self.console.close() WebPdb.active_instance = None return Pdb.do_quit(self, arg)
python
def do_quit(self, arg): """ quit || exit || q Stop and quit the current debugging session """ for name, fh in self._backup: setattr(sys, name, fh) self.console.writeline('*** Aborting program ***\n') self.console.flush() self.console.close() WebPdb.active_instance = None return Pdb.do_quit(self, arg)
[ "def", "do_quit", "(", "self", ",", "arg", ")", ":", "for", "name", ",", "fh", "in", "self", ".", "_backup", ":", "setattr", "(", "sys", ",", "name", ",", "fh", ")", "self", ".", "console", ".", "writeline", "(", "'*** Aborting program ***\\n'", ")", ...
quit || exit || q Stop and quit the current debugging session
[ "quit", "||", "exit", "||", "q", "Stop", "and", "quit", "the", "current", "debugging", "session" ]
f2df2207e870dbf50a4bb30ca12a59cab39a809f
https://github.com/romanvm/python-web-pdb/blob/f2df2207e870dbf50a4bb30ca12a59cab39a809f/web_pdb/__init__.py#L88-L99
train
34,375
romanvm/python-web-pdb
web_pdb/__init__.py
WebPdb._get_repr
def _get_repr(obj, pretty=False, indent=1): """ Get string representation of an object :param obj: object :type obj: object :param pretty: use pretty formatting :type pretty: bool :param indent: indentation for pretty formatting :type indent: int :return: string representation :rtype: str """ if pretty: repr_value = pformat(obj, indent) else: repr_value = repr(obj) if sys.version_info[0] == 2: # Try to convert Unicode string to human-readable form try: repr_value = repr_value.decode('raw_unicode_escape') except UnicodeError: repr_value = repr_value.decode('utf-8', 'replace') return repr_value
python
def _get_repr(obj, pretty=False, indent=1): """ Get string representation of an object :param obj: object :type obj: object :param pretty: use pretty formatting :type pretty: bool :param indent: indentation for pretty formatting :type indent: int :return: string representation :rtype: str """ if pretty: repr_value = pformat(obj, indent) else: repr_value = repr(obj) if sys.version_info[0] == 2: # Try to convert Unicode string to human-readable form try: repr_value = repr_value.decode('raw_unicode_escape') except UnicodeError: repr_value = repr_value.decode('utf-8', 'replace') return repr_value
[ "def", "_get_repr", "(", "obj", ",", "pretty", "=", "False", ",", "indent", "=", "1", ")", ":", "if", "pretty", ":", "repr_value", "=", "pformat", "(", "obj", ",", "indent", ")", "else", ":", "repr_value", "=", "repr", "(", "obj", ")", "if", "sys",...
Get string representation of an object :param obj: object :type obj: object :param pretty: use pretty formatting :type pretty: bool :param indent: indentation for pretty formatting :type indent: int :return: string representation :rtype: str
[ "Get", "string", "representation", "of", "an", "object" ]
f2df2207e870dbf50a4bb30ca12a59cab39a809f
https://github.com/romanvm/python-web-pdb/blob/f2df2207e870dbf50a4bb30ca12a59cab39a809f/web_pdb/__init__.py#L132-L155
train
34,376
romanvm/python-web-pdb
web_pdb/__init__.py
WebPdb.get_current_frame_data
def get_current_frame_data(self): """ Get all date about the current execution frame :return: current frame data :rtype: dict :raises AttributeError: if the debugger does hold any execution frame. :raises IOError: if source code for the current execution frame is not accessible. """ filename = self.curframe.f_code.co_filename lines, start_line = inspect.findsource(self.curframe) if sys.version_info[0] == 2: lines = [line.decode('utf-8') for line in lines] return { 'dirname': os.path.dirname(os.path.abspath(filename)) + os.path.sep, 'filename': os.path.basename(filename), 'file_listing': ''.join(lines), 'current_line': self.curframe.f_lineno, 'breakpoints': self.get_file_breaks(filename), 'globals': self.get_globals(), 'locals': self.get_locals() }
python
def get_current_frame_data(self): """ Get all date about the current execution frame :return: current frame data :rtype: dict :raises AttributeError: if the debugger does hold any execution frame. :raises IOError: if source code for the current execution frame is not accessible. """ filename = self.curframe.f_code.co_filename lines, start_line = inspect.findsource(self.curframe) if sys.version_info[0] == 2: lines = [line.decode('utf-8') for line in lines] return { 'dirname': os.path.dirname(os.path.abspath(filename)) + os.path.sep, 'filename': os.path.basename(filename), 'file_listing': ''.join(lines), 'current_line': self.curframe.f_lineno, 'breakpoints': self.get_file_breaks(filename), 'globals': self.get_globals(), 'locals': self.get_locals() }
[ "def", "get_current_frame_data", "(", "self", ")", ":", "filename", "=", "self", ".", "curframe", ".", "f_code", ".", "co_filename", "lines", ",", "start_line", "=", "inspect", ".", "findsource", "(", "self", ".", "curframe", ")", "if", "sys", ".", "versio...
Get all date about the current execution frame :return: current frame data :rtype: dict :raises AttributeError: if the debugger does hold any execution frame. :raises IOError: if source code for the current execution frame is not accessible.
[ "Get", "all", "date", "about", "the", "current", "execution", "frame" ]
f2df2207e870dbf50a4bb30ca12a59cab39a809f
https://github.com/romanvm/python-web-pdb/blob/f2df2207e870dbf50a4bb30ca12a59cab39a809f/web_pdb/__init__.py#L172-L193
train
34,377
romanvm/python-web-pdb
web_pdb/__init__.py
WebPdb.remove_trace
def remove_trace(self, frame=None): """ Detach the debugger from the execution stack :param frame: the lowest frame to detach the debugger from. :type frame: types.FrameType """ sys.settrace(None) if frame is None: frame = self.curframe while frame and frame is not self.botframe: del frame.f_trace frame = frame.f_back
python
def remove_trace(self, frame=None): """ Detach the debugger from the execution stack :param frame: the lowest frame to detach the debugger from. :type frame: types.FrameType """ sys.settrace(None) if frame is None: frame = self.curframe while frame and frame is not self.botframe: del frame.f_trace frame = frame.f_back
[ "def", "remove_trace", "(", "self", ",", "frame", "=", "None", ")", ":", "sys", ".", "settrace", "(", "None", ")", "if", "frame", "is", "None", ":", "frame", "=", "self", ".", "curframe", "while", "frame", "and", "frame", "is", "not", "self", ".", ...
Detach the debugger from the execution stack :param frame: the lowest frame to detach the debugger from. :type frame: types.FrameType
[ "Detach", "the", "debugger", "from", "the", "execution", "stack" ]
f2df2207e870dbf50a4bb30ca12a59cab39a809f
https://github.com/romanvm/python-web-pdb/blob/f2df2207e870dbf50a4bb30ca12a59cab39a809f/web_pdb/__init__.py#L234-L246
train
34,378
romanvm/python-web-pdb
web_pdb/web_console.py
WebConsole.flush
def flush(self): """ Wait until history is read but no more than 10 cycles in case a browser session is closed. """ i = 0 while self._frame_data.is_dirty and i < 10: i += 1 time.sleep(0.1)
python
def flush(self): """ Wait until history is read but no more than 10 cycles in case a browser session is closed. """ i = 0 while self._frame_data.is_dirty and i < 10: i += 1 time.sleep(0.1)
[ "def", "flush", "(", "self", ")", ":", "i", "=", "0", "while", "self", ".", "_frame_data", ".", "is_dirty", "and", "i", "<", "10", ":", "i", "+=", "1", "time", ".", "sleep", "(", "0.1", ")" ]
Wait until history is read but no more than 10 cycles in case a browser session is closed.
[ "Wait", "until", "history", "is", "read", "but", "no", "more", "than", "10", "cycles", "in", "case", "a", "browser", "session", "is", "closed", "." ]
f2df2207e870dbf50a4bb30ca12a59cab39a809f
https://github.com/romanvm/python-web-pdb/blob/f2df2207e870dbf50a4bb30ca12a59cab39a809f/web_pdb/web_console.py#L176-L184
train
34,379
cvxgrp/qcqp
qcqp/qcqp.py
solve_spectral
def solve_spectral(prob, *args, **kwargs): """Solve the spectral relaxation with lambda = 1. """ # TODO: do this efficiently without SDP lifting # lifted variables and semidefinite constraint X = cvx.Semidef(prob.n + 1) W = prob.f0.homogeneous_form() rel_obj = cvx.Minimize(cvx.sum_entries(cvx.mul_elemwise(W, X))) W1 = sum([f.homogeneous_form() for f in prob.fs if f.relop == '<=']) W2 = sum([f.homogeneous_form() for f in prob.fs if f.relop == '==']) rel_prob = cvx.Problem( rel_obj, [ cvx.sum_entries(cvx.mul_elemwise(W1, X)) <= 0, cvx.sum_entries(cvx.mul_elemwise(W2, X)) == 0, X[-1, -1] == 1 ] ) rel_prob.solve(*args, **kwargs) if rel_prob.status not in [cvx.OPTIMAL, cvx.OPTIMAL_INACCURATE]: raise Exception("Relaxation problem status: %s" % rel_prob.status) (w, v) = LA.eig(X.value) return np.sqrt(np.max(w))*np.asarray(v[:-1, np.argmax(w)]).flatten(), rel_prob.value
python
def solve_spectral(prob, *args, **kwargs): """Solve the spectral relaxation with lambda = 1. """ # TODO: do this efficiently without SDP lifting # lifted variables and semidefinite constraint X = cvx.Semidef(prob.n + 1) W = prob.f0.homogeneous_form() rel_obj = cvx.Minimize(cvx.sum_entries(cvx.mul_elemwise(W, X))) W1 = sum([f.homogeneous_form() for f in prob.fs if f.relop == '<=']) W2 = sum([f.homogeneous_form() for f in prob.fs if f.relop == '==']) rel_prob = cvx.Problem( rel_obj, [ cvx.sum_entries(cvx.mul_elemwise(W1, X)) <= 0, cvx.sum_entries(cvx.mul_elemwise(W2, X)) == 0, X[-1, -1] == 1 ] ) rel_prob.solve(*args, **kwargs) if rel_prob.status not in [cvx.OPTIMAL, cvx.OPTIMAL_INACCURATE]: raise Exception("Relaxation problem status: %s" % rel_prob.status) (w, v) = LA.eig(X.value) return np.sqrt(np.max(w))*np.asarray(v[:-1, np.argmax(w)]).flatten(), rel_prob.value
[ "def", "solve_spectral", "(", "prob", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# TODO: do this efficiently without SDP lifting", "# lifted variables and semidefinite constraint", "X", "=", "cvx", ".", "Semidef", "(", "prob", ".", "n", "+", "1", ")", ...
Solve the spectral relaxation with lambda = 1.
[ "Solve", "the", "spectral", "relaxation", "with", "lambda", "=", "1", "." ]
6b7a9804ad7429b72094c9a8da3b29d807037fe9
https://github.com/cvxgrp/qcqp/blob/6b7a9804ad7429b72094c9a8da3b29d807037fe9/qcqp/qcqp.py#L41-L70
train
34,380
cvxgrp/qcqp
qcqp/qcqp.py
solve_sdr
def solve_sdr(prob, *args, **kwargs): """Solve the SDP relaxation. """ # lifted variables and semidefinite constraint X = cvx.Semidef(prob.n + 1) W = prob.f0.homogeneous_form() rel_obj = cvx.Minimize(cvx.sum_entries(cvx.mul_elemwise(W, X))) rel_constr = [X[-1, -1] == 1] for f in prob.fs: W = f.homogeneous_form() lhs = cvx.sum_entries(cvx.mul_elemwise(W, X)) if f.relop == '==': rel_constr.append(lhs == 0) else: rel_constr.append(lhs <= 0) rel_prob = cvx.Problem(rel_obj, rel_constr) rel_prob.solve(*args, **kwargs) if rel_prob.status not in [cvx.OPTIMAL, cvx.OPTIMAL_INACCURATE]: raise Exception("Relaxation problem status: %s" % rel_prob.status) return X.value, rel_prob.value
python
def solve_sdr(prob, *args, **kwargs): """Solve the SDP relaxation. """ # lifted variables and semidefinite constraint X = cvx.Semidef(prob.n + 1) W = prob.f0.homogeneous_form() rel_obj = cvx.Minimize(cvx.sum_entries(cvx.mul_elemwise(W, X))) rel_constr = [X[-1, -1] == 1] for f in prob.fs: W = f.homogeneous_form() lhs = cvx.sum_entries(cvx.mul_elemwise(W, X)) if f.relop == '==': rel_constr.append(lhs == 0) else: rel_constr.append(lhs <= 0) rel_prob = cvx.Problem(rel_obj, rel_constr) rel_prob.solve(*args, **kwargs) if rel_prob.status not in [cvx.OPTIMAL, cvx.OPTIMAL_INACCURATE]: raise Exception("Relaxation problem status: %s" % rel_prob.status) return X.value, rel_prob.value
[ "def", "solve_sdr", "(", "prob", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# lifted variables and semidefinite constraint", "X", "=", "cvx", ".", "Semidef", "(", "prob", ".", "n", "+", "1", ")", "W", "=", "prob", ".", "f0", ".", "homogeneou...
Solve the SDP relaxation.
[ "Solve", "the", "SDP", "relaxation", "." ]
6b7a9804ad7429b72094c9a8da3b29d807037fe9
https://github.com/cvxgrp/qcqp/blob/6b7a9804ad7429b72094c9a8da3b29d807037fe9/qcqp/qcqp.py#L72-L97
train
34,381
cvxgrp/qcqp
qcqp/utilities.py
get_qcqp_form
def get_qcqp_form(prob): """Returns the problem metadata in QCQP class """ # Check quadraticity if not prob.objective.args[0].is_quadratic(): raise Exception("Objective is not quadratic.") if not all([constr._expr.is_quadratic() for constr in prob.constraints]): raise Exception("Not all constraints are quadratic.") if prob.is_dcp(): logging.warning("Problem is already convex; specifying solve method is unnecessary.") extractor = QuadCoeffExtractor(*get_id_map(prob.variables())) P0, q0, r0 = extractor.get_coeffs(prob.objective.args[0]) # unpacking values P0, q0, r0 = (P0[0]+P0[0].T)/2., q0.T.tocsc(), r0[0] if prob.objective.NAME == "maximize": P0, q0, r0 = -P0, -q0, -r0 f0 = QuadraticFunction(P0, q0, r0) fs = [] for constr in prob.constraints: sz = constr._expr.size[0]*constr._expr.size[1] Pc, qc, rc = extractor.get_coeffs(constr._expr) for i in range(sz): fs.append(QuadraticFunction((Pc[i]+Pc[i].T)/2., qc[i, :].T.tocsc(), rc[i], constr.OP_NAME)) return QCQPForm(f0, fs)
python
def get_qcqp_form(prob): """Returns the problem metadata in QCQP class """ # Check quadraticity if not prob.objective.args[0].is_quadratic(): raise Exception("Objective is not quadratic.") if not all([constr._expr.is_quadratic() for constr in prob.constraints]): raise Exception("Not all constraints are quadratic.") if prob.is_dcp(): logging.warning("Problem is already convex; specifying solve method is unnecessary.") extractor = QuadCoeffExtractor(*get_id_map(prob.variables())) P0, q0, r0 = extractor.get_coeffs(prob.objective.args[0]) # unpacking values P0, q0, r0 = (P0[0]+P0[0].T)/2., q0.T.tocsc(), r0[0] if prob.objective.NAME == "maximize": P0, q0, r0 = -P0, -q0, -r0 f0 = QuadraticFunction(P0, q0, r0) fs = [] for constr in prob.constraints: sz = constr._expr.size[0]*constr._expr.size[1] Pc, qc, rc = extractor.get_coeffs(constr._expr) for i in range(sz): fs.append(QuadraticFunction((Pc[i]+Pc[i].T)/2., qc[i, :].T.tocsc(), rc[i], constr.OP_NAME)) return QCQPForm(f0, fs)
[ "def", "get_qcqp_form", "(", "prob", ")", ":", "# Check quadraticity", "if", "not", "prob", ".", "objective", ".", "args", "[", "0", "]", ".", "is_quadratic", "(", ")", ":", "raise", "Exception", "(", "\"Objective is not quadratic.\"", ")", "if", "not", "all...
Returns the problem metadata in QCQP class
[ "Returns", "the", "problem", "metadata", "in", "QCQP", "class" ]
6b7a9804ad7429b72094c9a8da3b29d807037fe9
https://github.com/cvxgrp/qcqp/blob/6b7a9804ad7429b72094c9a8da3b29d807037fe9/qcqp/utilities.py#L318-L347
train
34,382
rytilahti/python-eq3bt
eq3bt/connection.py
BTLEConnection.make_request
def make_request(self, handle, value, timeout=DEFAULT_TIMEOUT, with_response=True): """Write a GATT Command without callback - not utf-8.""" try: with self: _LOGGER.debug("Writing %s to %s with with_response=%s", codecs.encode(value, 'hex'), handle, with_response) self._conn.writeCharacteristic(handle, value, withResponse=with_response) if timeout: _LOGGER.debug("Waiting for notifications for %s", timeout) self._conn.waitForNotifications(timeout) except btle.BTLEException as ex: _LOGGER.debug("Got exception from bluepy while making a request: %s", ex) raise
python
def make_request(self, handle, value, timeout=DEFAULT_TIMEOUT, with_response=True): """Write a GATT Command without callback - not utf-8.""" try: with self: _LOGGER.debug("Writing %s to %s with with_response=%s", codecs.encode(value, 'hex'), handle, with_response) self._conn.writeCharacteristic(handle, value, withResponse=with_response) if timeout: _LOGGER.debug("Waiting for notifications for %s", timeout) self._conn.waitForNotifications(timeout) except btle.BTLEException as ex: _LOGGER.debug("Got exception from bluepy while making a request: %s", ex) raise
[ "def", "make_request", "(", "self", ",", "handle", ",", "value", ",", "timeout", "=", "DEFAULT_TIMEOUT", ",", "with_response", "=", "True", ")", ":", "try", ":", "with", "self", ":", "_LOGGER", ".", "debug", "(", "\"Writing %s to %s with with_response=%s\"", "...
Write a GATT Command without callback - not utf-8.
[ "Write", "a", "GATT", "Command", "without", "callback", "-", "not", "utf", "-", "8", "." ]
595459d9885920cf13b7059a1edd2cf38cede1f0
https://github.com/rytilahti/python-eq3bt/blob/595459d9885920cf13b7059a1edd2cf38cede1f0/eq3bt/connection.py#L68-L79
train
34,383
rytilahti/python-eq3bt
eq3bt/eq3cli.py
cli
def cli(ctx, mac, debug): """ Tool to query and modify the state of EQ3 BT smart thermostat. """ if debug: logging.basicConfig(level=logging.DEBUG) else: logging.basicConfig(level=logging.INFO) thermostat = Thermostat(mac) thermostat.update() ctx.obj = thermostat if ctx.invoked_subcommand is None: ctx.invoke(state)
python
def cli(ctx, mac, debug): """ Tool to query and modify the state of EQ3 BT smart thermostat. """ if debug: logging.basicConfig(level=logging.DEBUG) else: logging.basicConfig(level=logging.INFO) thermostat = Thermostat(mac) thermostat.update() ctx.obj = thermostat if ctx.invoked_subcommand is None: ctx.invoke(state)
[ "def", "cli", "(", "ctx", ",", "mac", ",", "debug", ")", ":", "if", "debug", ":", "logging", ".", "basicConfig", "(", "level", "=", "logging", ".", "DEBUG", ")", "else", ":", "logging", ".", "basicConfig", "(", "level", "=", "logging", ".", "INFO", ...
Tool to query and modify the state of EQ3 BT smart thermostat.
[ "Tool", "to", "query", "and", "modify", "the", "state", "of", "EQ3", "BT", "smart", "thermostat", "." ]
595459d9885920cf13b7059a1edd2cf38cede1f0
https://github.com/rytilahti/python-eq3bt/blob/595459d9885920cf13b7059a1edd2cf38cede1f0/eq3bt/eq3cli.py#L26-L38
train
34,384
rytilahti/python-eq3bt
eq3bt/eq3cli.py
temp
def temp(dev, target): """ Gets or sets the target temperature.""" click.echo("Current target temp: %s" % dev.target_temperature) if target: click.echo("Setting target temp: %s" % target) dev.target_temperature = target
python
def temp(dev, target): """ Gets or sets the target temperature.""" click.echo("Current target temp: %s" % dev.target_temperature) if target: click.echo("Setting target temp: %s" % target) dev.target_temperature = target
[ "def", "temp", "(", "dev", ",", "target", ")", ":", "click", ".", "echo", "(", "\"Current target temp: %s\"", "%", "dev", ".", "target_temperature", ")", "if", "target", ":", "click", ".", "echo", "(", "\"Setting target temp: %s\"", "%", "target", ")", "dev"...
Gets or sets the target temperature.
[ "Gets", "or", "sets", "the", "target", "temperature", "." ]
595459d9885920cf13b7059a1edd2cf38cede1f0
https://github.com/rytilahti/python-eq3bt/blob/595459d9885920cf13b7059a1edd2cf38cede1f0/eq3bt/eq3cli.py#L44-L49
train
34,385
rytilahti/python-eq3bt
eq3bt/eq3cli.py
mode
def mode(dev, target): """ Gets or sets the active mode. """ click.echo("Current mode: %s" % dev.mode_readable) if target: click.echo("Setting mode: %s" % target) dev.mode = target
python
def mode(dev, target): """ Gets or sets the active mode. """ click.echo("Current mode: %s" % dev.mode_readable) if target: click.echo("Setting mode: %s" % target) dev.mode = target
[ "def", "mode", "(", "dev", ",", "target", ")", ":", "click", ".", "echo", "(", "\"Current mode: %s\"", "%", "dev", ".", "mode_readable", ")", "if", "target", ":", "click", ".", "echo", "(", "\"Setting mode: %s\"", "%", "target", ")", "dev", ".", "mode", ...
Gets or sets the active mode.
[ "Gets", "or", "sets", "the", "active", "mode", "." ]
595459d9885920cf13b7059a1edd2cf38cede1f0
https://github.com/rytilahti/python-eq3bt/blob/595459d9885920cf13b7059a1edd2cf38cede1f0/eq3bt/eq3cli.py#L55-L60
train
34,386
rytilahti/python-eq3bt
eq3bt/eq3cli.py
boost
def boost(dev, target): """ Gets or sets the boost mode. """ click.echo("Boost: %s" % dev.boost) if target is not None: click.echo("Setting boost: %s" % target) dev.boost = target
python
def boost(dev, target): """ Gets or sets the boost mode. """ click.echo("Boost: %s" % dev.boost) if target is not None: click.echo("Setting boost: %s" % target) dev.boost = target
[ "def", "boost", "(", "dev", ",", "target", ")", ":", "click", ".", "echo", "(", "\"Boost: %s\"", "%", "dev", ".", "boost", ")", "if", "target", "is", "not", "None", ":", "click", ".", "echo", "(", "\"Setting boost: %s\"", "%", "target", ")", "dev", "...
Gets or sets the boost mode.
[ "Gets", "or", "sets", "the", "boost", "mode", "." ]
595459d9885920cf13b7059a1edd2cf38cede1f0
https://github.com/rytilahti/python-eq3bt/blob/595459d9885920cf13b7059a1edd2cf38cede1f0/eq3bt/eq3cli.py#L66-L71
train
34,387
rytilahti/python-eq3bt
eq3bt/eq3cli.py
locked
def locked(dev, target): """ Gets or sets the lock. """ click.echo("Locked: %s" % dev.locked) if target is not None: click.echo("Setting lock: %s" % target) dev.locked = target
python
def locked(dev, target): """ Gets or sets the lock. """ click.echo("Locked: %s" % dev.locked) if target is not None: click.echo("Setting lock: %s" % target) dev.locked = target
[ "def", "locked", "(", "dev", ",", "target", ")", ":", "click", ".", "echo", "(", "\"Locked: %s\"", "%", "dev", ".", "locked", ")", "if", "target", "is", "not", "None", ":", "click", ".", "echo", "(", "\"Setting lock: %s\"", "%", "target", ")", "dev", ...
Gets or sets the lock.
[ "Gets", "or", "sets", "the", "lock", "." ]
595459d9885920cf13b7059a1edd2cf38cede1f0
https://github.com/rytilahti/python-eq3bt/blob/595459d9885920cf13b7059a1edd2cf38cede1f0/eq3bt/eq3cli.py#L84-L89
train
34,388
rytilahti/python-eq3bt
eq3bt/eq3cli.py
window_open
def window_open(dev, temp, duration): """ Gets and sets the window open settings. """ click.echo("Window open: %s" % dev.window_open) if temp and duration: click.echo("Setting window open conf, temp: %s duration: %s" % (temp, duration)) dev.window_open_config(temp, duration)
python
def window_open(dev, temp, duration): """ Gets and sets the window open settings. """ click.echo("Window open: %s" % dev.window_open) if temp and duration: click.echo("Setting window open conf, temp: %s duration: %s" % (temp, duration)) dev.window_open_config(temp, duration)
[ "def", "window_open", "(", "dev", ",", "temp", ",", "duration", ")", ":", "click", ".", "echo", "(", "\"Window open: %s\"", "%", "dev", ".", "window_open", ")", "if", "temp", "and", "duration", ":", "click", ".", "echo", "(", "\"Setting window open conf, tem...
Gets and sets the window open settings.
[ "Gets", "and", "sets", "the", "window", "open", "settings", "." ]
595459d9885920cf13b7059a1edd2cf38cede1f0
https://github.com/rytilahti/python-eq3bt/blob/595459d9885920cf13b7059a1edd2cf38cede1f0/eq3bt/eq3cli.py#L103-L108
train
34,389
rytilahti/python-eq3bt
eq3bt/eq3cli.py
presets
def presets(dev, comfort, eco): """ Sets the preset temperatures for auto mode. """ click.echo("Setting presets: comfort %s, eco %s" % (comfort, eco)) dev.temperature_presets(comfort, eco)
python
def presets(dev, comfort, eco): """ Sets the preset temperatures for auto mode. """ click.echo("Setting presets: comfort %s, eco %s" % (comfort, eco)) dev.temperature_presets(comfort, eco)
[ "def", "presets", "(", "dev", ",", "comfort", ",", "eco", ")", ":", "click", ".", "echo", "(", "\"Setting presets: comfort %s, eco %s\"", "%", "(", "comfort", ",", "eco", ")", ")", "dev", ".", "temperature_presets", "(", "comfort", ",", "eco", ")" ]
Sets the preset temperatures for auto mode.
[ "Sets", "the", "preset", "temperatures", "for", "auto", "mode", "." ]
595459d9885920cf13b7059a1edd2cf38cede1f0
https://github.com/rytilahti/python-eq3bt/blob/595459d9885920cf13b7059a1edd2cf38cede1f0/eq3bt/eq3cli.py#L115-L118
train
34,390
rytilahti/python-eq3bt
eq3bt/eq3cli.py
schedule
def schedule(dev): """ Gets the schedule from the thermostat. """ # TODO: expose setting the schedule somehow? for d in range(7): dev.query_schedule(d) for day in dev.schedule.values(): click.echo("Day %s, base temp: %s" % (day.day, day.base_temp)) current_hour = day.next_change_at for hour in day.hours: if current_hour == 0: continue click.echo("\t[%s-%s] %s" % (current_hour, hour.next_change_at, hour.target_temp)) current_hour = hour.next_change_at
python
def schedule(dev): """ Gets the schedule from the thermostat. """ # TODO: expose setting the schedule somehow? for d in range(7): dev.query_schedule(d) for day in dev.schedule.values(): click.echo("Day %s, base temp: %s" % (day.day, day.base_temp)) current_hour = day.next_change_at for hour in day.hours: if current_hour == 0: continue click.echo("\t[%s-%s] %s" % (current_hour, hour.next_change_at, hour.target_temp)) current_hour = hour.next_change_at
[ "def", "schedule", "(", "dev", ")", ":", "# TODO: expose setting the schedule somehow?", "for", "d", "in", "range", "(", "7", ")", ":", "dev", ".", "query_schedule", "(", "d", ")", "for", "day", "in", "dev", ".", "schedule", ".", "values", "(", ")", ":",...
Gets the schedule from the thermostat.
[ "Gets", "the", "schedule", "from", "the", "thermostat", "." ]
595459d9885920cf13b7059a1edd2cf38cede1f0
https://github.com/rytilahti/python-eq3bt/blob/595459d9885920cf13b7059a1edd2cf38cede1f0/eq3bt/eq3cli.py#L122-L133
train
34,391
rytilahti/python-eq3bt
eq3bt/eq3cli.py
away
def away(dev, away_end, temperature): """ Enables or disables the away mode. """ if away_end: click.echo("Setting away until %s, temperature: %s" % (away_end, temperature)) else: click.echo("Disabling away mode") dev.set_away(away_end, temperature)
python
def away(dev, away_end, temperature): """ Enables or disables the away mode. """ if away_end: click.echo("Setting away until %s, temperature: %s" % (away_end, temperature)) else: click.echo("Disabling away mode") dev.set_away(away_end, temperature)
[ "def", "away", "(", "dev", ",", "away_end", ",", "temperature", ")", ":", "if", "away_end", ":", "click", ".", "echo", "(", "\"Setting away until %s, temperature: %s\"", "%", "(", "away_end", ",", "temperature", ")", ")", "else", ":", "click", ".", "echo", ...
Enables or disables the away mode.
[ "Enables", "or", "disables", "the", "away", "mode", "." ]
595459d9885920cf13b7059a1edd2cf38cede1f0
https://github.com/rytilahti/python-eq3bt/blob/595459d9885920cf13b7059a1edd2cf38cede1f0/eq3bt/eq3cli.py#L147-L153
train
34,392
rytilahti/python-eq3bt
eq3bt/eq3cli.py
state
def state(ctx): """ Prints out all available information. """ dev = ctx.obj click.echo(dev) ctx.forward(locked) ctx.forward(low_battery) ctx.forward(window_open) ctx.forward(boost) ctx.forward(temp) # ctx.forward(presets) ctx.forward(mode) ctx.forward(valve_state)
python
def state(ctx): """ Prints out all available information. """ dev = ctx.obj click.echo(dev) ctx.forward(locked) ctx.forward(low_battery) ctx.forward(window_open) ctx.forward(boost) ctx.forward(temp) # ctx.forward(presets) ctx.forward(mode) ctx.forward(valve_state)
[ "def", "state", "(", "ctx", ")", ":", "dev", "=", "ctx", ".", "obj", "click", ".", "echo", "(", "dev", ")", "ctx", ".", "forward", "(", "locked", ")", "ctx", ".", "forward", "(", "low_battery", ")", "ctx", ".", "forward", "(", "window_open", ")", ...
Prints out all available information.
[ "Prints", "out", "all", "available", "information", "." ]
595459d9885920cf13b7059a1edd2cf38cede1f0
https://github.com/rytilahti/python-eq3bt/blob/595459d9885920cf13b7059a1edd2cf38cede1f0/eq3bt/eq3cli.py#L157-L168
train
34,393
rytilahti/python-eq3bt
eq3bt/eq3btsmart.py
Thermostat.parse_schedule
def parse_schedule(self, data): """Parses the device sent schedule.""" sched = Schedule.parse(data) _LOGGER.debug("Got schedule data for day '%s'", sched.day) return sched
python
def parse_schedule(self, data): """Parses the device sent schedule.""" sched = Schedule.parse(data) _LOGGER.debug("Got schedule data for day '%s'", sched.day) return sched
[ "def", "parse_schedule", "(", "self", ",", "data", ")", ":", "sched", "=", "Schedule", ".", "parse", "(", "data", ")", "_LOGGER", ".", "debug", "(", "\"Got schedule data for day '%s'\"", ",", "sched", ".", "day", ")", "return", "sched" ]
Parses the device sent schedule.
[ "Parses", "the", "device", "sent", "schedule", "." ]
595459d9885920cf13b7059a1edd2cf38cede1f0
https://github.com/rytilahti/python-eq3bt/blob/595459d9885920cf13b7059a1edd2cf38cede1f0/eq3bt/eq3btsmart.py#L108-L113
train
34,394
rytilahti/python-eq3bt
eq3bt/eq3btsmart.py
Thermostat.update
def update(self): """Update the data from the thermostat. Always sets the current time.""" _LOGGER.debug("Querying the device..") time = datetime.now() value = struct.pack('BBBBBBB', PROP_INFO_QUERY, time.year % 100, time.month, time.day, time.hour, time.minute, time.second) self._conn.make_request(PROP_WRITE_HANDLE, value)
python
def update(self): """Update the data from the thermostat. Always sets the current time.""" _LOGGER.debug("Querying the device..") time = datetime.now() value = struct.pack('BBBBBBB', PROP_INFO_QUERY, time.year % 100, time.month, time.day, time.hour, time.minute, time.second) self._conn.make_request(PROP_WRITE_HANDLE, value)
[ "def", "update", "(", "self", ")", ":", "_LOGGER", ".", "debug", "(", "\"Querying the device..\"", ")", "time", "=", "datetime", ".", "now", "(", ")", "value", "=", "struct", ".", "pack", "(", "'BBBBBBB'", ",", "PROP_INFO_QUERY", ",", "time", ".", "year"...
Update the data from the thermostat. Always sets the current time.
[ "Update", "the", "data", "from", "the", "thermostat", ".", "Always", "sets", "the", "current", "time", "." ]
595459d9885920cf13b7059a1edd2cf38cede1f0
https://github.com/rytilahti/python-eq3bt/blob/595459d9885920cf13b7059a1edd2cf38cede1f0/eq3bt/eq3btsmart.py#L155-L163
train
34,395
rytilahti/python-eq3bt
eq3bt/eq3btsmart.py
Thermostat.set_schedule
def set_schedule(self, data): """Sets the schedule for the given day. """ value = Schedule.build(data) self._conn.make_request(PROP_WRITE_HANDLE, value)
python
def set_schedule(self, data): """Sets the schedule for the given day. """ value = Schedule.build(data) self._conn.make_request(PROP_WRITE_HANDLE, value)
[ "def", "set_schedule", "(", "self", ",", "data", ")", ":", "value", "=", "Schedule", ".", "build", "(", "data", ")", "self", ".", "_conn", ".", "make_request", "(", "PROP_WRITE_HANDLE", ",", "value", ")" ]
Sets the schedule for the given day.
[ "Sets", "the", "schedule", "for", "the", "given", "day", "." ]
595459d9885920cf13b7059a1edd2cf38cede1f0
https://github.com/rytilahti/python-eq3bt/blob/595459d9885920cf13b7059a1edd2cf38cede1f0/eq3bt/eq3btsmart.py#L182-L185
train
34,396
rytilahti/python-eq3bt
eq3bt/eq3btsmart.py
Thermostat.target_temperature
def target_temperature(self, temperature): """Set new target temperature.""" dev_temp = int(temperature * 2) if temperature == EQ3BT_OFF_TEMP or temperature == EQ3BT_ON_TEMP: dev_temp |= 0x40 value = struct.pack('BB', PROP_MODE_WRITE, dev_temp) else: self._verify_temperature(temperature) value = struct.pack('BB', PROP_TEMPERATURE_WRITE, dev_temp) self._conn.make_request(PROP_WRITE_HANDLE, value)
python
def target_temperature(self, temperature): """Set new target temperature.""" dev_temp = int(temperature * 2) if temperature == EQ3BT_OFF_TEMP or temperature == EQ3BT_ON_TEMP: dev_temp |= 0x40 value = struct.pack('BB', PROP_MODE_WRITE, dev_temp) else: self._verify_temperature(temperature) value = struct.pack('BB', PROP_TEMPERATURE_WRITE, dev_temp) self._conn.make_request(PROP_WRITE_HANDLE, value)
[ "def", "target_temperature", "(", "self", ",", "temperature", ")", ":", "dev_temp", "=", "int", "(", "temperature", "*", "2", ")", "if", "temperature", "==", "EQ3BT_OFF_TEMP", "or", "temperature", "==", "EQ3BT_ON_TEMP", ":", "dev_temp", "|=", "0x40", "value", ...
Set new target temperature.
[ "Set", "new", "target", "temperature", "." ]
595459d9885920cf13b7059a1edd2cf38cede1f0
https://github.com/rytilahti/python-eq3bt/blob/595459d9885920cf13b7059a1edd2cf38cede1f0/eq3bt/eq3btsmart.py#L193-L203
train
34,397
rytilahti/python-eq3bt
eq3bt/eq3btsmart.py
Thermostat.mode
def mode(self, mode): """Set the operation mode.""" _LOGGER.debug("Setting new mode: %s", mode) if self.mode == Mode.Boost and mode != Mode.Boost: self.boost = False if mode == Mode.Boost: self.boost = True return elif mode == Mode.Away: end = datetime.now() + self._away_duration return self.set_away(end, self._away_temp) elif mode == Mode.Closed: return self.set_mode(0x40 | int(EQ3BT_OFF_TEMP * 2)) elif mode == Mode.Open: return self.set_mode(0x40 | int(EQ3BT_ON_TEMP * 2)) if mode == Mode.Manual: temperature = max(min(self._target_temperature, self.max_temp), self.min_temp) return self.set_mode(0x40 | int(temperature * 2)) else: return self.set_mode(0)
python
def mode(self, mode): """Set the operation mode.""" _LOGGER.debug("Setting new mode: %s", mode) if self.mode == Mode.Boost and mode != Mode.Boost: self.boost = False if mode == Mode.Boost: self.boost = True return elif mode == Mode.Away: end = datetime.now() + self._away_duration return self.set_away(end, self._away_temp) elif mode == Mode.Closed: return self.set_mode(0x40 | int(EQ3BT_OFF_TEMP * 2)) elif mode == Mode.Open: return self.set_mode(0x40 | int(EQ3BT_ON_TEMP * 2)) if mode == Mode.Manual: temperature = max(min(self._target_temperature, self.max_temp), self.min_temp) return self.set_mode(0x40 | int(temperature * 2)) else: return self.set_mode(0)
[ "def", "mode", "(", "self", ",", "mode", ")", ":", "_LOGGER", ".", "debug", "(", "\"Setting new mode: %s\"", ",", "mode", ")", "if", "self", ".", "mode", "==", "Mode", ".", "Boost", "and", "mode", "!=", "Mode", ".", "Boost", ":", "self", ".", "boost"...
Set the operation mode.
[ "Set", "the", "operation", "mode", "." ]
595459d9885920cf13b7059a1edd2cf38cede1f0
https://github.com/rytilahti/python-eq3bt/blob/595459d9885920cf13b7059a1edd2cf38cede1f0/eq3bt/eq3btsmart.py#L211-L234
train
34,398
rytilahti/python-eq3bt
eq3bt/eq3btsmart.py
Thermostat.set_away
def set_away(self, away_end=None, temperature=EQ3BT_AWAY_TEMP): """ Sets away mode with target temperature. When called without parameters disables away mode.""" if not away_end: _LOGGER.debug("Disabling away, going to auto mode.") return self.set_mode(0x00) _LOGGER.debug("Setting away until %s, temp %s", away_end, temperature) adapter = AwayDataAdapter(Byte[4]) packed = adapter.build(away_end) self.set_mode(0x80 | int(temperature * 2), packed)
python
def set_away(self, away_end=None, temperature=EQ3BT_AWAY_TEMP): """ Sets away mode with target temperature. When called without parameters disables away mode.""" if not away_end: _LOGGER.debug("Disabling away, going to auto mode.") return self.set_mode(0x00) _LOGGER.debug("Setting away until %s, temp %s", away_end, temperature) adapter = AwayDataAdapter(Byte[4]) packed = adapter.build(away_end) self.set_mode(0x80 | int(temperature * 2), packed)
[ "def", "set_away", "(", "self", ",", "away_end", "=", "None", ",", "temperature", "=", "EQ3BT_AWAY_TEMP", ")", ":", "if", "not", "away_end", ":", "_LOGGER", ".", "debug", "(", "\"Disabling away, going to auto mode.\"", ")", "return", "self", ".", "set_mode", "...
Sets away mode with target temperature. When called without parameters disables away mode.
[ "Sets", "away", "mode", "with", "target", "temperature", ".", "When", "called", "without", "parameters", "disables", "away", "mode", "." ]
595459d9885920cf13b7059a1edd2cf38cede1f0
https://github.com/rytilahti/python-eq3bt/blob/595459d9885920cf13b7059a1edd2cf38cede1f0/eq3bt/eq3btsmart.py#L240-L251
train
34,399