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
iamteem/redisco
redisco/models/base.py
Model._initialize_id
def _initialize_id(self): """Initializes the id of the instance.""" self.id = str(self.db.incr(self._key['id']))
python
def _initialize_id(self): """Initializes the id of the instance.""" self.id = str(self.db.incr(self._key['id']))
[ "def", "_initialize_id", "(", "self", ")", ":", "self", ".", "id", "=", "str", "(", "self", ".", "db", ".", "incr", "(", "self", ".", "_key", "[", "'id'", "]", ")", ")" ]
Initializes the id of the instance.
[ "Initializes", "the", "id", "of", "the", "instance", "." ]
a7ba19ff3c38061d6d8bc0c10fa754baadcfeb91
https://github.com/iamteem/redisco/blob/a7ba19ff3c38061d6d8bc0c10fa754baadcfeb91/redisco/models/base.py#L333-L335
train
40,900
iamteem/redisco
redisco/models/base.py
Model._write
def _write(self, _new=False): """Writes the values of the attributes to the datastore. This method also creates the indices and saves the lists associated to the object. """ pipeline = self.db.pipeline() self._create_membership(pipeline) self._update_indices(pipeline) h = {} # attributes for k, v in self.attributes.iteritems(): if isinstance(v, DateTimeField): if v.auto_now: setattr(self, k, datetime.now()) if v.auto_now_add and _new: setattr(self, k, datetime.now()) elif isinstance(v, DateField): if v.auto_now: setattr(self, k, date.today()) if v.auto_now_add and _new: setattr(self, k, date.today()) for_storage = getattr(self, k) if for_storage is not None: h[k] = v.typecast_for_storage(for_storage) # indices for index in self.indices: if index not in self.lists and index not in self.attributes: v = getattr(self, index) if callable(v): v = v() if v: try: h[index] = unicode(v) except UnicodeError: h[index] = unicode(v.decode('utf-8')) pipeline.delete(self.key()) if h: pipeline.hmset(self.key(), h) # lists for k, v in self.lists.iteritems(): l = List(self.key()[k], pipeline=pipeline) l.clear() values = getattr(self, k) if values: if v._redisco_model: l.extend([item.id for item in values]) else: l.extend(values) pipeline.execute()
python
def _write(self, _new=False): """Writes the values of the attributes to the datastore. This method also creates the indices and saves the lists associated to the object. """ pipeline = self.db.pipeline() self._create_membership(pipeline) self._update_indices(pipeline) h = {} # attributes for k, v in self.attributes.iteritems(): if isinstance(v, DateTimeField): if v.auto_now: setattr(self, k, datetime.now()) if v.auto_now_add and _new: setattr(self, k, datetime.now()) elif isinstance(v, DateField): if v.auto_now: setattr(self, k, date.today()) if v.auto_now_add and _new: setattr(self, k, date.today()) for_storage = getattr(self, k) if for_storage is not None: h[k] = v.typecast_for_storage(for_storage) # indices for index in self.indices: if index not in self.lists and index not in self.attributes: v = getattr(self, index) if callable(v): v = v() if v: try: h[index] = unicode(v) except UnicodeError: h[index] = unicode(v.decode('utf-8')) pipeline.delete(self.key()) if h: pipeline.hmset(self.key(), h) # lists for k, v in self.lists.iteritems(): l = List(self.key()[k], pipeline=pipeline) l.clear() values = getattr(self, k) if values: if v._redisco_model: l.extend([item.id for item in values]) else: l.extend(values) pipeline.execute()
[ "def", "_write", "(", "self", ",", "_new", "=", "False", ")", ":", "pipeline", "=", "self", ".", "db", ".", "pipeline", "(", ")", "self", ".", "_create_membership", "(", "pipeline", ")", "self", ".", "_update_indices", "(", "pipeline", ")", "h", "=", ...
Writes the values of the attributes to the datastore. This method also creates the indices and saves the lists associated to the object.
[ "Writes", "the", "values", "of", "the", "attributes", "to", "the", "datastore", "." ]
a7ba19ff3c38061d6d8bc0c10fa754baadcfeb91
https://github.com/iamteem/redisco/blob/a7ba19ff3c38061d6d8bc0c10fa754baadcfeb91/redisco/models/base.py#L337-L387
train
40,901
iamteem/redisco
redisco/models/base.py
Model._create_membership
def _create_membership(self, pipeline=None): """Adds the id of the object to the set of all objects of the same class. """ Set(self._key['all'], pipeline=pipeline).add(self.id)
python
def _create_membership(self, pipeline=None): """Adds the id of the object to the set of all objects of the same class. """ Set(self._key['all'], pipeline=pipeline).add(self.id)
[ "def", "_create_membership", "(", "self", ",", "pipeline", "=", "None", ")", ":", "Set", "(", "self", ".", "_key", "[", "'all'", "]", ",", "pipeline", "=", "pipeline", ")", ".", "add", "(", "self", ".", "id", ")" ]
Adds the id of the object to the set of all objects of the same class.
[ "Adds", "the", "id", "of", "the", "object", "to", "the", "set", "of", "all", "objects", "of", "the", "same", "class", "." ]
a7ba19ff3c38061d6d8bc0c10fa754baadcfeb91
https://github.com/iamteem/redisco/blob/a7ba19ff3c38061d6d8bc0c10fa754baadcfeb91/redisco/models/base.py#L393-L397
train
40,902
iamteem/redisco
redisco/models/base.py
Model._delete_membership
def _delete_membership(self, pipeline=None): """Removes the id of the object to the set of all objects of the same class. """ Set(self._key['all'], pipeline=pipeline).remove(self.id)
python
def _delete_membership(self, pipeline=None): """Removes the id of the object to the set of all objects of the same class. """ Set(self._key['all'], pipeline=pipeline).remove(self.id)
[ "def", "_delete_membership", "(", "self", ",", "pipeline", "=", "None", ")", ":", "Set", "(", "self", ".", "_key", "[", "'all'", "]", ",", "pipeline", "=", "pipeline", ")", ".", "remove", "(", "self", ".", "id", ")" ]
Removes the id of the object to the set of all objects of the same class.
[ "Removes", "the", "id", "of", "the", "object", "to", "the", "set", "of", "all", "objects", "of", "the", "same", "class", "." ]
a7ba19ff3c38061d6d8bc0c10fa754baadcfeb91
https://github.com/iamteem/redisco/blob/a7ba19ff3c38061d6d8bc0c10fa754baadcfeb91/redisco/models/base.py#L399-L403
train
40,903
iamteem/redisco
redisco/models/base.py
Model._add_to_indices
def _add_to_indices(self, pipeline): """Adds the base64 encoded values of the indices.""" for att in self.indices: self._add_to_index(att, pipeline=pipeline)
python
def _add_to_indices(self, pipeline): """Adds the base64 encoded values of the indices.""" for att in self.indices: self._add_to_index(att, pipeline=pipeline)
[ "def", "_add_to_indices", "(", "self", ",", "pipeline", ")", ":", "for", "att", "in", "self", ".", "indices", ":", "self", ".", "_add_to_index", "(", "att", ",", "pipeline", "=", "pipeline", ")" ]
Adds the base64 encoded values of the indices.
[ "Adds", "the", "base64", "encoded", "values", "of", "the", "indices", "." ]
a7ba19ff3c38061d6d8bc0c10fa754baadcfeb91
https://github.com/iamteem/redisco/blob/a7ba19ff3c38061d6d8bc0c10fa754baadcfeb91/redisco/models/base.py#L415-L418
train
40,904
iamteem/redisco
redisco/models/base.py
Model._add_to_index
def _add_to_index(self, att, val=None, pipeline=None): """ Adds the id to the index. This also adds to the _indices set of the object. """ index = self._index_key_for(att) if index is None: return t, index = index if t == 'attribute': pipeline.sadd(index, self.id) pipeline.sadd(self.key()['_indices'], index) elif t == 'list': for i in index: pipeline.sadd(i, self.id) pipeline.sadd(self.key()['_indices'], i) elif t == 'sortedset': zindex, index = index pipeline.sadd(index, self.id) pipeline.sadd(self.key()['_indices'], index) descriptor = self.attributes[att] score = descriptor.typecast_for_storage(getattr(self, att)) pipeline.zadd(zindex, self.id, score) pipeline.sadd(self.key()['_zindices'], zindex)
python
def _add_to_index(self, att, val=None, pipeline=None): """ Adds the id to the index. This also adds to the _indices set of the object. """ index = self._index_key_for(att) if index is None: return t, index = index if t == 'attribute': pipeline.sadd(index, self.id) pipeline.sadd(self.key()['_indices'], index) elif t == 'list': for i in index: pipeline.sadd(i, self.id) pipeline.sadd(self.key()['_indices'], i) elif t == 'sortedset': zindex, index = index pipeline.sadd(index, self.id) pipeline.sadd(self.key()['_indices'], index) descriptor = self.attributes[att] score = descriptor.typecast_for_storage(getattr(self, att)) pipeline.zadd(zindex, self.id, score) pipeline.sadd(self.key()['_zindices'], zindex)
[ "def", "_add_to_index", "(", "self", ",", "att", ",", "val", "=", "None", ",", "pipeline", "=", "None", ")", ":", "index", "=", "self", ".", "_index_key_for", "(", "att", ")", "if", "index", "is", "None", ":", "return", "t", ",", "index", "=", "ind...
Adds the id to the index. This also adds to the _indices set of the object.
[ "Adds", "the", "id", "to", "the", "index", "." ]
a7ba19ff3c38061d6d8bc0c10fa754baadcfeb91
https://github.com/iamteem/redisco/blob/a7ba19ff3c38061d6d8bc0c10fa754baadcfeb91/redisco/models/base.py#L420-L444
train
40,905
iamteem/redisco
redisco/models/base.py
Model._index_key_for
def _index_key_for(self, att, value=None): """Returns a key based on the attribute and its value. The key is used for indexing. """ if value is None: value = getattr(self, att) if callable(value): value = value() if value is None: return None if att not in self.lists: return self._get_index_key_for_non_list_attr(att, value) else: return self._tuple_for_index_key_attr_list(att, value)
python
def _index_key_for(self, att, value=None): """Returns a key based on the attribute and its value. The key is used for indexing. """ if value is None: value = getattr(self, att) if callable(value): value = value() if value is None: return None if att not in self.lists: return self._get_index_key_for_non_list_attr(att, value) else: return self._tuple_for_index_key_attr_list(att, value)
[ "def", "_index_key_for", "(", "self", ",", "att", ",", "value", "=", "None", ")", ":", "if", "value", "is", "None", ":", "value", "=", "getattr", "(", "self", ",", "att", ")", "if", "callable", "(", "value", ")", ":", "value", "=", "value", "(", ...
Returns a key based on the attribute and its value. The key is used for indexing.
[ "Returns", "a", "key", "based", "on", "the", "attribute", "and", "its", "value", "." ]
a7ba19ff3c38061d6d8bc0c10fa754baadcfeb91
https://github.com/iamteem/redisco/blob/a7ba19ff3c38061d6d8bc0c10fa754baadcfeb91/redisco/models/base.py#L460-L474
train
40,906
iamteem/redisco
redisco/containers.py
Set.isdisjoint
def isdisjoint(self, other): """Return True if the set has no elements in common with other.""" return not bool(self.db.sinter([self.key, other.key]))
python
def isdisjoint(self, other): """Return True if the set has no elements in common with other.""" return not bool(self.db.sinter([self.key, other.key]))
[ "def", "isdisjoint", "(", "self", ",", "other", ")", ":", "return", "not", "bool", "(", "self", ".", "db", ".", "sinter", "(", "[", "self", ".", "key", ",", "other", ".", "key", "]", ")", ")" ]
Return True if the set has no elements in common with other.
[ "Return", "True", "if", "the", "set", "has", "no", "elements", "in", "common", "with", "other", "." ]
a7ba19ff3c38061d6d8bc0c10fa754baadcfeb91
https://github.com/iamteem/redisco/blob/a7ba19ff3c38061d6d8bc0c10fa754baadcfeb91/redisco/containers.py#L86-L88
train
40,907
iamteem/redisco
redisco/containers.py
Set.union
def union(self, key, *others): """Return a new set with elements from the set and all others.""" if not isinstance(key, str): raise ValueError("String expected.") self.db.sunionstore(key, [self.key] + [o.key for o in others]) return Set(key)
python
def union(self, key, *others): """Return a new set with elements from the set and all others.""" if not isinstance(key, str): raise ValueError("String expected.") self.db.sunionstore(key, [self.key] + [o.key for o in others]) return Set(key)
[ "def", "union", "(", "self", ",", "key", ",", "*", "others", ")", ":", "if", "not", "isinstance", "(", "key", ",", "str", ")", ":", "raise", "ValueError", "(", "\"String expected.\"", ")", "self", ".", "db", ".", "sunionstore", "(", "key", ",", "[", ...
Return a new set with elements from the set and all others.
[ "Return", "a", "new", "set", "with", "elements", "from", "the", "set", "and", "all", "others", "." ]
a7ba19ff3c38061d6d8bc0c10fa754baadcfeb91
https://github.com/iamteem/redisco/blob/a7ba19ff3c38061d6d8bc0c10fa754baadcfeb91/redisco/containers.py#L124-L129
train
40,908
iamteem/redisco
redisco/containers.py
Set.intersection
def intersection(self, key, *others): """Return a new set with elements common to the set and all others.""" if not isinstance(key, str): raise ValueError("String expected.") self.db.sinterstore(key, [self.key] + [o.key for o in others]) return Set(key)
python
def intersection(self, key, *others): """Return a new set with elements common to the set and all others.""" if not isinstance(key, str): raise ValueError("String expected.") self.db.sinterstore(key, [self.key] + [o.key for o in others]) return Set(key)
[ "def", "intersection", "(", "self", ",", "key", ",", "*", "others", ")", ":", "if", "not", "isinstance", "(", "key", ",", "str", ")", ":", "raise", "ValueError", "(", "\"String expected.\"", ")", "self", ".", "db", ".", "sinterstore", "(", "key", ",", ...
Return a new set with elements common to the set and all others.
[ "Return", "a", "new", "set", "with", "elements", "common", "to", "the", "set", "and", "all", "others", "." ]
a7ba19ff3c38061d6d8bc0c10fa754baadcfeb91
https://github.com/iamteem/redisco/blob/a7ba19ff3c38061d6d8bc0c10fa754baadcfeb91/redisco/containers.py#L131-L136
train
40,909
iamteem/redisco
redisco/containers.py
Set.difference
def difference(self, key, *others): """Return a new set with elements in the set that are not in the others.""" if not isinstance(key, str): raise ValueError("String expected.") self.db.sdiffstore(key, [self.key] + [o.key for o in others]) return Set(key)
python
def difference(self, key, *others): """Return a new set with elements in the set that are not in the others.""" if not isinstance(key, str): raise ValueError("String expected.") self.db.sdiffstore(key, [self.key] + [o.key for o in others]) return Set(key)
[ "def", "difference", "(", "self", ",", "key", ",", "*", "others", ")", ":", "if", "not", "isinstance", "(", "key", ",", "str", ")", ":", "raise", "ValueError", "(", "\"String expected.\"", ")", "self", ".", "db", ".", "sdiffstore", "(", "key", ",", "...
Return a new set with elements in the set that are not in the others.
[ "Return", "a", "new", "set", "with", "elements", "in", "the", "set", "that", "are", "not", "in", "the", "others", "." ]
a7ba19ff3c38061d6d8bc0c10fa754baadcfeb91
https://github.com/iamteem/redisco/blob/a7ba19ff3c38061d6d8bc0c10fa754baadcfeb91/redisco/containers.py#L138-L143
train
40,910
iamteem/redisco
redisco/containers.py
Set.update
def update(self, *others): """Update the set, adding elements from all others.""" self.db.sunionstore(self.key, [self.key] + [o.key for o in others])
python
def update(self, *others): """Update the set, adding elements from all others.""" self.db.sunionstore(self.key, [self.key] + [o.key for o in others])
[ "def", "update", "(", "self", ",", "*", "others", ")", ":", "self", ".", "db", ".", "sunionstore", "(", "self", ".", "key", ",", "[", "self", ".", "key", "]", "+", "[", "o", ".", "key", "for", "o", "in", "others", "]", ")" ]
Update the set, adding elements from all others.
[ "Update", "the", "set", "adding", "elements", "from", "all", "others", "." ]
a7ba19ff3c38061d6d8bc0c10fa754baadcfeb91
https://github.com/iamteem/redisco/blob/a7ba19ff3c38061d6d8bc0c10fa754baadcfeb91/redisco/containers.py#L145-L147
train
40,911
iamteem/redisco
redisco/containers.py
Set.intersection_update
def intersection_update(self, *others): """Update the set, keeping only elements found in it and all others.""" self.db.sinterstore(self.key, [o.key for o in [self.key] + others])
python
def intersection_update(self, *others): """Update the set, keeping only elements found in it and all others.""" self.db.sinterstore(self.key, [o.key for o in [self.key] + others])
[ "def", "intersection_update", "(", "self", ",", "*", "others", ")", ":", "self", ".", "db", ".", "sinterstore", "(", "self", ".", "key", ",", "[", "o", ".", "key", "for", "o", "in", "[", "self", ".", "key", "]", "+", "others", "]", ")" ]
Update the set, keeping only elements found in it and all others.
[ "Update", "the", "set", "keeping", "only", "elements", "found", "in", "it", "and", "all", "others", "." ]
a7ba19ff3c38061d6d8bc0c10fa754baadcfeb91
https://github.com/iamteem/redisco/blob/a7ba19ff3c38061d6d8bc0c10fa754baadcfeb91/redisco/containers.py#L153-L155
train
40,912
iamteem/redisco
redisco/containers.py
Set.difference_update
def difference_update(self, *others): """Update the set, removing elements found in others.""" self.db.sdiffstore(self.key, [o.key for o in [self.key] + others])
python
def difference_update(self, *others): """Update the set, removing elements found in others.""" self.db.sdiffstore(self.key, [o.key for o in [self.key] + others])
[ "def", "difference_update", "(", "self", ",", "*", "others", ")", ":", "self", ".", "db", ".", "sdiffstore", "(", "self", ".", "key", ",", "[", "o", ".", "key", "for", "o", "in", "[", "self", ".", "key", "]", "+", "others", "]", ")" ]
Update the set, removing elements found in others.
[ "Update", "the", "set", "removing", "elements", "found", "in", "others", "." ]
a7ba19ff3c38061d6d8bc0c10fa754baadcfeb91
https://github.com/iamteem/redisco/blob/a7ba19ff3c38061d6d8bc0c10fa754baadcfeb91/redisco/containers.py#L161-L163
train
40,913
iamteem/redisco
redisco/containers.py
Set.copy
def copy(self, key): """Copy the set to another key and return the new Set. WARNING: If the key exists, it overwrites it. """ copy = Set(key=key, db=self.db) copy.clear() copy |= self return copy
python
def copy(self, key): """Copy the set to another key and return the new Set. WARNING: If the key exists, it overwrites it. """ copy = Set(key=key, db=self.db) copy.clear() copy |= self return copy
[ "def", "copy", "(", "self", ",", "key", ")", ":", "copy", "=", "Set", "(", "key", "=", "key", ",", "db", "=", "self", ".", "db", ")", "copy", ".", "clear", "(", ")", "copy", "|=", "self", "return", "copy" ]
Copy the set to another key and return the new Set. WARNING: If the key exists, it overwrites it.
[ "Copy", "the", "set", "to", "another", "key", "and", "return", "the", "new", "Set", "." ]
a7ba19ff3c38061d6d8bc0c10fa754baadcfeb91
https://github.com/iamteem/redisco/blob/a7ba19ff3c38061d6d8bc0c10fa754baadcfeb91/redisco/containers.py#L173-L181
train
40,914
iamteem/redisco
redisco/containers.py
Set.sinter
def sinter(self, *other_sets): """Performs an intersection between Sets. Returns a set of common members. Uses Redis.sinter. """ return self.db.sinter([self.key] + [s.key for s in other_sets])
python
def sinter(self, *other_sets): """Performs an intersection between Sets. Returns a set of common members. Uses Redis.sinter. """ return self.db.sinter([self.key] + [s.key for s in other_sets])
[ "def", "sinter", "(", "self", ",", "*", "other_sets", ")", ":", "return", "self", ".", "db", ".", "sinter", "(", "[", "self", ".", "key", "]", "+", "[", "s", ".", "key", "for", "s", "in", "other_sets", "]", ")" ]
Performs an intersection between Sets. Returns a set of common members. Uses Redis.sinter.
[ "Performs", "an", "intersection", "between", "Sets", "." ]
a7ba19ff3c38061d6d8bc0c10fa754baadcfeb91
https://github.com/iamteem/redisco/blob/a7ba19ff3c38061d6d8bc0c10fa754baadcfeb91/redisco/containers.py#L187-L192
train
40,915
iamteem/redisco
redisco/containers.py
List.reverse
def reverse(self): """Reverse in place.""" r = self[:] r.reverse() self.clear() self.extend(r)
python
def reverse(self): """Reverse in place.""" r = self[:] r.reverse() self.clear() self.extend(r)
[ "def", "reverse", "(", "self", ")", ":", "r", "=", "self", "[", ":", "]", "r", ".", "reverse", "(", ")", "self", ".", "clear", "(", ")", "self", ".", "extend", "(", "r", ")" ]
Reverse in place.
[ "Reverse", "in", "place", "." ]
a7ba19ff3c38061d6d8bc0c10fa754baadcfeb91
https://github.com/iamteem/redisco/blob/a7ba19ff3c38061d6d8bc0c10fa754baadcfeb91/redisco/containers.py#L275-L280
train
40,916
iamteem/redisco
redisco/containers.py
List.copy
def copy(self, key): """Copy the list to a new list. WARNING: If key exists, it clears it before copying. """ copy = List(key, self.db) copy.clear() copy.extend(self) return copy
python
def copy(self, key): """Copy the list to a new list. WARNING: If key exists, it clears it before copying. """ copy = List(key, self.db) copy.clear() copy.extend(self) return copy
[ "def", "copy", "(", "self", ",", "key", ")", ":", "copy", "=", "List", "(", "key", ",", "self", ".", "db", ")", "copy", ".", "clear", "(", ")", "copy", ".", "extend", "(", "self", ")", "return", "copy" ]
Copy the list to a new list. WARNING: If key exists, it clears it before copying.
[ "Copy", "the", "list", "to", "a", "new", "list", "." ]
a7ba19ff3c38061d6d8bc0c10fa754baadcfeb91
https://github.com/iamteem/redisco/blob/a7ba19ff3c38061d6d8bc0c10fa754baadcfeb91/redisco/containers.py#L282-L290
train
40,917
iamteem/redisco
redisco/containers.py
SortedSet.lt
def lt(self, v, limit=None, offset=None): """Returns the list of the members of the set that have scores less than v. """ if limit is not None and offset is None: offset = 0 return self.zrangebyscore(self._min_score, "(%f" % v, start=offset, num=limit)
python
def lt(self, v, limit=None, offset=None): """Returns the list of the members of the set that have scores less than v. """ if limit is not None and offset is None: offset = 0 return self.zrangebyscore(self._min_score, "(%f" % v, start=offset, num=limit)
[ "def", "lt", "(", "self", ",", "v", ",", "limit", "=", "None", ",", "offset", "=", "None", ")", ":", "if", "limit", "is", "not", "None", "and", "offset", "is", "None", ":", "offset", "=", "0", "return", "self", ".", "zrangebyscore", "(", "self", ...
Returns the list of the members of the set that have scores less than v.
[ "Returns", "the", "list", "of", "the", "members", "of", "the", "set", "that", "have", "scores", "less", "than", "v", "." ]
a7ba19ff3c38061d6d8bc0c10fa754baadcfeb91
https://github.com/iamteem/redisco/blob/a7ba19ff3c38061d6d8bc0c10fa754baadcfeb91/redisco/containers.py#L457-L464
train
40,918
iamteem/redisco
redisco/containers.py
SortedSet.gt
def gt(self, v, limit=None, offset=None): """Returns the list of the members of the set that have scores greater than v. """ if limit is not None and offset is None: offset = 0 return self.zrangebyscore("(%f" % v, self._max_score, start=offset, num=limit)
python
def gt(self, v, limit=None, offset=None): """Returns the list of the members of the set that have scores greater than v. """ if limit is not None and offset is None: offset = 0 return self.zrangebyscore("(%f" % v, self._max_score, start=offset, num=limit)
[ "def", "gt", "(", "self", ",", "v", ",", "limit", "=", "None", ",", "offset", "=", "None", ")", ":", "if", "limit", "is", "not", "None", "and", "offset", "is", "None", ":", "offset", "=", "0", "return", "self", ".", "zrangebyscore", "(", "\"(%f\"",...
Returns the list of the members of the set that have scores greater than v.
[ "Returns", "the", "list", "of", "the", "members", "of", "the", "set", "that", "have", "scores", "greater", "than", "v", "." ]
a7ba19ff3c38061d6d8bc0c10fa754baadcfeb91
https://github.com/iamteem/redisco/blob/a7ba19ff3c38061d6d8bc0c10fa754baadcfeb91/redisco/containers.py#L475-L482
train
40,919
iamteem/redisco
redisco/containers.py
SortedSet.between
def between(self, min, max, limit=None, offset=None): """Returns the list of the members of the set that have scores between min and max. """ if limit is not None and offset is None: offset = 0 return self.zrangebyscore(min, max, start=offset, num=limit)
python
def between(self, min, max, limit=None, offset=None): """Returns the list of the members of the set that have scores between min and max. """ if limit is not None and offset is None: offset = 0 return self.zrangebyscore(min, max, start=offset, num=limit)
[ "def", "between", "(", "self", ",", "min", ",", "max", ",", "limit", "=", "None", ",", "offset", "=", "None", ")", ":", "if", "limit", "is", "not", "None", "and", "offset", "is", "None", ":", "offset", "=", "0", "return", "self", ".", "zrangebyscor...
Returns the list of the members of the set that have scores between min and max.
[ "Returns", "the", "list", "of", "the", "members", "of", "the", "set", "that", "have", "scores", "between", "min", "and", "max", "." ]
a7ba19ff3c38061d6d8bc0c10fa754baadcfeb91
https://github.com/iamteem/redisco/blob/a7ba19ff3c38061d6d8bc0c10fa754baadcfeb91/redisco/containers.py#L493-L500
train
40,920
nakagami/pyfirebirdsql
firebirdsql/utils.py
hex_to_bytes
def hex_to_bytes(s): """ convert hex string to bytes """ if len(s) % 2: s = b'0' + s ia = [int(s[i:i+2], 16) for i in range(0, len(s), 2)] # int array return bs(ia) if PYTHON_MAJOR_VER == 3 else b''.join([chr(c) for c in ia])
python
def hex_to_bytes(s): """ convert hex string to bytes """ if len(s) % 2: s = b'0' + s ia = [int(s[i:i+2], 16) for i in range(0, len(s), 2)] # int array return bs(ia) if PYTHON_MAJOR_VER == 3 else b''.join([chr(c) for c in ia])
[ "def", "hex_to_bytes", "(", "s", ")", ":", "if", "len", "(", "s", ")", "%", "2", ":", "s", "=", "b'0'", "+", "s", "ia", "=", "[", "int", "(", "s", "[", "i", ":", "i", "+", "2", "]", ",", "16", ")", "for", "i", "in", "range", "(", "0", ...
convert hex string to bytes
[ "convert", "hex", "string", "to", "bytes" ]
5ce366c2fc8318510444f4a89801442f3e9e52ca
https://github.com/nakagami/pyfirebirdsql/blob/5ce366c2fc8318510444f4a89801442f3e9e52ca/firebirdsql/utils.py#L43-L50
train
40,921
nakagami/pyfirebirdsql
firebirdsql/decfloat.py
decimal128_to_decimal
def decimal128_to_decimal(b): "decimal128 bytes to Decimal" v = decimal128_to_sign_digits_exponent(b) if isinstance(v, Decimal): return v sign, digits, exponent = v return Decimal((sign, Decimal(digits).as_tuple()[1], exponent))
python
def decimal128_to_decimal(b): "decimal128 bytes to Decimal" v = decimal128_to_sign_digits_exponent(b) if isinstance(v, Decimal): return v sign, digits, exponent = v return Decimal((sign, Decimal(digits).as_tuple()[1], exponent))
[ "def", "decimal128_to_decimal", "(", "b", ")", ":", "v", "=", "decimal128_to_sign_digits_exponent", "(", "b", ")", "if", "isinstance", "(", "v", ",", "Decimal", ")", ":", "return", "v", "sign", ",", "digits", ",", "exponent", "=", "v", "return", "Decimal",...
decimal128 bytes to Decimal
[ "decimal128", "bytes", "to", "Decimal" ]
5ce366c2fc8318510444f4a89801442f3e9e52ca
https://github.com/nakagami/pyfirebirdsql/blob/5ce366c2fc8318510444f4a89801442f3e9e52ca/firebirdsql/decfloat.py#L216-L222
train
40,922
bennylope/pygeocodio
geocodio/client.py
error_response
def error_response(response): """ Raises errors matching the response code """ if response.status_code >= 500: raise exceptions.GeocodioServerError elif response.status_code == 403: raise exceptions.GeocodioAuthError elif response.status_code == 422: raise exceptions.GeocodioDataError(response.json()["error"]) else: raise exceptions.GeocodioError( "Unknown service error (HTTP {0})".format(response.status_code) )
python
def error_response(response): """ Raises errors matching the response code """ if response.status_code >= 500: raise exceptions.GeocodioServerError elif response.status_code == 403: raise exceptions.GeocodioAuthError elif response.status_code == 422: raise exceptions.GeocodioDataError(response.json()["error"]) else: raise exceptions.GeocodioError( "Unknown service error (HTTP {0})".format(response.status_code) )
[ "def", "error_response", "(", "response", ")", ":", "if", "response", ".", "status_code", ">=", "500", ":", "raise", "exceptions", ".", "GeocodioServerError", "elif", "response", ".", "status_code", "==", "403", ":", "raise", "exceptions", ".", "GeocodioAuthErro...
Raises errors matching the response code
[ "Raises", "errors", "matching", "the", "response", "code" ]
4c33d3d34f6b63d4b8fe85fe571ae02b9f67d6c3
https://github.com/bennylope/pygeocodio/blob/4c33d3d34f6b63d4b8fe85fe571ae02b9f67d6c3/geocodio/client.py#L47-L63
train
40,923
bennylope/pygeocodio
geocodio/client.py
GeocodioClient._req
def _req(self, method="get", verb=None, headers={}, params={}, data={}): """ Method to wrap all request building :return: a Response object based on the specified method and request values. """ url = self.BASE_URL.format(verb=verb) request_headers = {"content-type": "application/json"} request_params = {"api_key": self.API_KEY} request_headers.update(headers) request_params.update(params) return getattr(requests, method)( url, params=request_params, headers=request_headers, data=data )
python
def _req(self, method="get", verb=None, headers={}, params={}, data={}): """ Method to wrap all request building :return: a Response object based on the specified method and request values. """ url = self.BASE_URL.format(verb=verb) request_headers = {"content-type": "application/json"} request_params = {"api_key": self.API_KEY} request_headers.update(headers) request_params.update(params) return getattr(requests, method)( url, params=request_params, headers=request_headers, data=data )
[ "def", "_req", "(", "self", ",", "method", "=", "\"get\"", ",", "verb", "=", "None", ",", "headers", "=", "{", "}", ",", "params", "=", "{", "}", ",", "data", "=", "{", "}", ")", ":", "url", "=", "self", ".", "BASE_URL", ".", "format", "(", "...
Method to wrap all request building :return: a Response object based on the specified method and request values.
[ "Method", "to", "wrap", "all", "request", "building" ]
4c33d3d34f6b63d4b8fe85fe571ae02b9f67d6c3
https://github.com/bennylope/pygeocodio/blob/4c33d3d34f6b63d4b8fe85fe571ae02b9f67d6c3/geocodio/client.py#L94-L107
train
40,924
bennylope/pygeocodio
geocodio/client.py
GeocodioClient.geocode_address
def geocode_address(self, address, **kwargs): """ Returns a Location dictionary with the components of the queried address and the geocoded location. >>> client = GeocodioClient('some_api_key') >>> client.geocode("1600 Pennsylvania Ave, Washington DC") { "input": { "address_components": { "number": "1600", "street": "Pennsylvania", "suffix": "Ave", "city": "Washington", "state": "DC" }, "formatted_address": "1600 Pennsylvania Ave, Washington DC" }, "results": [ { "address_components": { "number": "1600", "street": "Pennsylvania", "suffix": "Ave", "city": "Washington", "state": "DC", "zip": "20500" }, "formatted_address": "1600 Pennsylvania Ave, Washington DC, 20500", "location": { "lat": 38.897700000000, "lng": -77.03650000000, }, "accuracy": 1 }, { "address_components": { "number": "1600", "street": "Pennsylvania", "suffix": "Ave", "city": "Washington", "state": "DC", "zip": "20500" }, "formatted_address": "1600 Pennsylvania Ave, Washington DC, 20500", "location": { "lat": 38.897700000000, "lng": -77.03650000000, }, "accuracy": 0.8 } ] } """ fields = ",".join(kwargs.pop("fields", [])) response = self._req(verb="geocode", params={"q": address, "fields": fields}) if response.status_code != 200: return error_response(response) return Location(response.json())
python
def geocode_address(self, address, **kwargs): """ Returns a Location dictionary with the components of the queried address and the geocoded location. >>> client = GeocodioClient('some_api_key') >>> client.geocode("1600 Pennsylvania Ave, Washington DC") { "input": { "address_components": { "number": "1600", "street": "Pennsylvania", "suffix": "Ave", "city": "Washington", "state": "DC" }, "formatted_address": "1600 Pennsylvania Ave, Washington DC" }, "results": [ { "address_components": { "number": "1600", "street": "Pennsylvania", "suffix": "Ave", "city": "Washington", "state": "DC", "zip": "20500" }, "formatted_address": "1600 Pennsylvania Ave, Washington DC, 20500", "location": { "lat": 38.897700000000, "lng": -77.03650000000, }, "accuracy": 1 }, { "address_components": { "number": "1600", "street": "Pennsylvania", "suffix": "Ave", "city": "Washington", "state": "DC", "zip": "20500" }, "formatted_address": "1600 Pennsylvania Ave, Washington DC, 20500", "location": { "lat": 38.897700000000, "lng": -77.03650000000, }, "accuracy": 0.8 } ] } """ fields = ",".join(kwargs.pop("fields", [])) response = self._req(verb="geocode", params={"q": address, "fields": fields}) if response.status_code != 200: return error_response(response) return Location(response.json())
[ "def", "geocode_address", "(", "self", ",", "address", ",", "*", "*", "kwargs", ")", ":", "fields", "=", "\",\"", ".", "join", "(", "kwargs", ".", "pop", "(", "\"fields\"", ",", "[", "]", ")", ")", "response", "=", "self", ".", "_req", "(", "verb",...
Returns a Location dictionary with the components of the queried address and the geocoded location. >>> client = GeocodioClient('some_api_key') >>> client.geocode("1600 Pennsylvania Ave, Washington DC") { "input": { "address_components": { "number": "1600", "street": "Pennsylvania", "suffix": "Ave", "city": "Washington", "state": "DC" }, "formatted_address": "1600 Pennsylvania Ave, Washington DC" }, "results": [ { "address_components": { "number": "1600", "street": "Pennsylvania", "suffix": "Ave", "city": "Washington", "state": "DC", "zip": "20500" }, "formatted_address": "1600 Pennsylvania Ave, Washington DC, 20500", "location": { "lat": 38.897700000000, "lng": -77.03650000000, }, "accuracy": 1 }, { "address_components": { "number": "1600", "street": "Pennsylvania", "suffix": "Ave", "city": "Washington", "state": "DC", "zip": "20500" }, "formatted_address": "1600 Pennsylvania Ave, Washington DC, 20500", "location": { "lat": 38.897700000000, "lng": -77.03650000000, }, "accuracy": 0.8 } ] }
[ "Returns", "a", "Location", "dictionary", "with", "the", "components", "of", "the", "queried", "address", "and", "the", "geocoded", "location", "." ]
4c33d3d34f6b63d4b8fe85fe571ae02b9f67d6c3
https://github.com/bennylope/pygeocodio/blob/4c33d3d34f6b63d4b8fe85fe571ae02b9f67d6c3/geocodio/client.py#L152-L211
train
40,925
bennylope/pygeocodio
geocodio/client.py
GeocodioClient.geocode
def geocode(self, address_data, **kwargs): """ Returns geocoding data for either a list of addresses or a single address represented as a string. Provides a single point of access for end users. """ if isinstance(address_data, list): return self.batch_geocode(address_data, **kwargs) return self.geocode_address(address_data, **kwargs)
python
def geocode(self, address_data, **kwargs): """ Returns geocoding data for either a list of addresses or a single address represented as a string. Provides a single point of access for end users. """ if isinstance(address_data, list): return self.batch_geocode(address_data, **kwargs) return self.geocode_address(address_data, **kwargs)
[ "def", "geocode", "(", "self", ",", "address_data", ",", "*", "*", "kwargs", ")", ":", "if", "isinstance", "(", "address_data", ",", "list", ")", ":", "return", "self", ".", "batch_geocode", "(", "address_data", ",", "*", "*", "kwargs", ")", "return", ...
Returns geocoding data for either a list of addresses or a single address represented as a string. Provides a single point of access for end users.
[ "Returns", "geocoding", "data", "for", "either", "a", "list", "of", "addresses", "or", "a", "single", "address", "represented", "as", "a", "string", "." ]
4c33d3d34f6b63d4b8fe85fe571ae02b9f67d6c3
https://github.com/bennylope/pygeocodio/blob/4c33d3d34f6b63d4b8fe85fe571ae02b9f67d6c3/geocodio/client.py#L214-L224
train
40,926
bennylope/pygeocodio
geocodio/client.py
GeocodioClient.reverse_point
def reverse_point(self, latitude, longitude, **kwargs): """ Method for identifying an address from a geographic point """ fields = ",".join(kwargs.pop("fields", [])) point_param = "{0},{1}".format(latitude, longitude) response = self._req( verb="reverse", params={"q": point_param, "fields": fields} ) if response.status_code != 200: return error_response(response) return Location(response.json())
python
def reverse_point(self, latitude, longitude, **kwargs): """ Method for identifying an address from a geographic point """ fields = ",".join(kwargs.pop("fields", [])) point_param = "{0},{1}".format(latitude, longitude) response = self._req( verb="reverse", params={"q": point_param, "fields": fields} ) if response.status_code != 200: return error_response(response) return Location(response.json())
[ "def", "reverse_point", "(", "self", ",", "latitude", ",", "longitude", ",", "*", "*", "kwargs", ")", ":", "fields", "=", "\",\"", ".", "join", "(", "kwargs", ".", "pop", "(", "\"fields\"", ",", "[", "]", ")", ")", "point_param", "=", "\"{0},{1}\"", ...
Method for identifying an address from a geographic point
[ "Method", "for", "identifying", "an", "address", "from", "a", "geographic", "point" ]
4c33d3d34f6b63d4b8fe85fe571ae02b9f67d6c3
https://github.com/bennylope/pygeocodio/blob/4c33d3d34f6b63d4b8fe85fe571ae02b9f67d6c3/geocodio/client.py#L227-L239
train
40,927
bennylope/pygeocodio
geocodio/client.py
GeocodioClient.reverse
def reverse(self, points, **kwargs): """ General method for reversing addresses, either a single address or multiple. *args should either be a longitude/latitude pair or a list of such pairs:: >>> multiple_locations = reverse([(40, -19), (43, 112)]) >>> single_location = reverse((40, -19)) """ if isinstance(points, list): return self.batch_reverse(points, **kwargs) if self.order == "lat": x, y = points else: y, x = points return self.reverse_point(x, y, **kwargs)
python
def reverse(self, points, **kwargs): """ General method for reversing addresses, either a single address or multiple. *args should either be a longitude/latitude pair or a list of such pairs:: >>> multiple_locations = reverse([(40, -19), (43, 112)]) >>> single_location = reverse((40, -19)) """ if isinstance(points, list): return self.batch_reverse(points, **kwargs) if self.order == "lat": x, y = points else: y, x = points return self.reverse_point(x, y, **kwargs)
[ "def", "reverse", "(", "self", ",", "points", ",", "*", "*", "kwargs", ")", ":", "if", "isinstance", "(", "points", ",", "list", ")", ":", "return", "self", ".", "batch_reverse", "(", "points", ",", "*", "*", "kwargs", ")", "if", "self", ".", "orde...
General method for reversing addresses, either a single address or multiple. *args should either be a longitude/latitude pair or a list of such pairs:: >>> multiple_locations = reverse([(40, -19), (43, 112)]) >>> single_location = reverse((40, -19))
[ "General", "method", "for", "reversing", "addresses", "either", "a", "single", "address", "or", "multiple", "." ]
4c33d3d34f6b63d4b8fe85fe571ae02b9f67d6c3
https://github.com/bennylope/pygeocodio/blob/4c33d3d34f6b63d4b8fe85fe571ae02b9f67d6c3/geocodio/client.py#L257-L276
train
40,928
nakagami/pyfirebirdsql
firebirdsql/wireprotocol.py
WireProtocol.str_to_bytes
def str_to_bytes(self, s): "convert str to bytes" if (PYTHON_MAJOR_VER == 3 or (PYTHON_MAJOR_VER == 2 and type(s) == unicode)): return s.encode(charset_map.get(self.charset, self.charset)) return s
python
def str_to_bytes(self, s): "convert str to bytes" if (PYTHON_MAJOR_VER == 3 or (PYTHON_MAJOR_VER == 2 and type(s) == unicode)): return s.encode(charset_map.get(self.charset, self.charset)) return s
[ "def", "str_to_bytes", "(", "self", ",", "s", ")", ":", "if", "(", "PYTHON_MAJOR_VER", "==", "3", "or", "(", "PYTHON_MAJOR_VER", "==", "2", "and", "type", "(", "s", ")", "==", "unicode", ")", ")", ":", "return", "s", ".", "encode", "(", "charset_map"...
convert str to bytes
[ "convert", "str", "to", "bytes" ]
5ce366c2fc8318510444f4a89801442f3e9e52ca
https://github.com/nakagami/pyfirebirdsql/blob/5ce366c2fc8318510444f4a89801442f3e9e52ca/firebirdsql/wireprotocol.py#L227-L232
train
40,929
nakagami/pyfirebirdsql
firebirdsql/wireprotocol.py
WireProtocol.bytes_to_str
def bytes_to_str(self, b): "convert bytes array to raw string" if PYTHON_MAJOR_VER == 3: return b.decode(charset_map.get(self.charset, self.charset)) return b
python
def bytes_to_str(self, b): "convert bytes array to raw string" if PYTHON_MAJOR_VER == 3: return b.decode(charset_map.get(self.charset, self.charset)) return b
[ "def", "bytes_to_str", "(", "self", ",", "b", ")", ":", "if", "PYTHON_MAJOR_VER", "==", "3", ":", "return", "b", ".", "decode", "(", "charset_map", ".", "get", "(", "self", ".", "charset", ",", "self", ".", "charset", ")", ")", "return", "b" ]
convert bytes array to raw string
[ "convert", "bytes", "array", "to", "raw", "string" ]
5ce366c2fc8318510444f4a89801442f3e9e52ca
https://github.com/nakagami/pyfirebirdsql/blob/5ce366c2fc8318510444f4a89801442f3e9e52ca/firebirdsql/wireprotocol.py#L234-L238
train
40,930
nakagami/pyfirebirdsql
firebirdsql/wireprotocol.py
WireProtocol.bytes_to_ustr
def bytes_to_ustr(self, b): "convert bytes array to unicode string" return b.decode(charset_map.get(self.charset, self.charset))
python
def bytes_to_ustr(self, b): "convert bytes array to unicode string" return b.decode(charset_map.get(self.charset, self.charset))
[ "def", "bytes_to_ustr", "(", "self", ",", "b", ")", ":", "return", "b", ".", "decode", "(", "charset_map", ".", "get", "(", "self", ".", "charset", ",", "self", ".", "charset", ")", ")" ]
convert bytes array to unicode string
[ "convert", "bytes", "array", "to", "unicode", "string" ]
5ce366c2fc8318510444f4a89801442f3e9e52ca
https://github.com/nakagami/pyfirebirdsql/blob/5ce366c2fc8318510444f4a89801442f3e9e52ca/firebirdsql/wireprotocol.py#L240-L242
train
40,931
nakagami/pyfirebirdsql
firebirdsql/xsqlvar.py
calc_blr
def calc_blr(xsqlda): "Calculate BLR from XSQLVAR array." ln = len(xsqlda) * 2 blr = [5, 2, 4, 0, ln & 255, ln >> 8] for x in xsqlda: sqltype = x.sqltype if sqltype == SQL_TYPE_VARYING: blr += [37, x.sqllen & 255, x.sqllen >> 8] elif sqltype == SQL_TYPE_TEXT: blr += [14, x.sqllen & 255, x.sqllen >> 8] elif sqltype == SQL_TYPE_LONG: blr += [8, x.sqlscale] elif sqltype == SQL_TYPE_SHORT: blr += [7, x.sqlscale] elif sqltype == SQL_TYPE_INT64: blr += [16, x.sqlscale] elif sqltype == SQL_TYPE_QUAD: blr += [9, x.sqlscale] elif sqltype == SQL_TYPE_DEC_FIXED: blr += [26, x.sqlscale] else: blr += sqltype2blr[sqltype] blr += [7, 0] # [blr_short, 0] blr += [255, 76] # [blr_end, blr_eoc] # x.sqlscale value shoud be negative, so b convert to range(0, 256) return bs(256 + b if b < 0 else b for b in blr)
python
def calc_blr(xsqlda): "Calculate BLR from XSQLVAR array." ln = len(xsqlda) * 2 blr = [5, 2, 4, 0, ln & 255, ln >> 8] for x in xsqlda: sqltype = x.sqltype if sqltype == SQL_TYPE_VARYING: blr += [37, x.sqllen & 255, x.sqllen >> 8] elif sqltype == SQL_TYPE_TEXT: blr += [14, x.sqllen & 255, x.sqllen >> 8] elif sqltype == SQL_TYPE_LONG: blr += [8, x.sqlscale] elif sqltype == SQL_TYPE_SHORT: blr += [7, x.sqlscale] elif sqltype == SQL_TYPE_INT64: blr += [16, x.sqlscale] elif sqltype == SQL_TYPE_QUAD: blr += [9, x.sqlscale] elif sqltype == SQL_TYPE_DEC_FIXED: blr += [26, x.sqlscale] else: blr += sqltype2blr[sqltype] blr += [7, 0] # [blr_short, 0] blr += [255, 76] # [blr_end, blr_eoc] # x.sqlscale value shoud be negative, so b convert to range(0, 256) return bs(256 + b if b < 0 else b for b in blr)
[ "def", "calc_blr", "(", "xsqlda", ")", ":", "ln", "=", "len", "(", "xsqlda", ")", "*", "2", "blr", "=", "[", "5", ",", "2", ",", "4", ",", "0", ",", "ln", "&", "255", ",", "ln", ">>", "8", "]", "for", "x", "in", "xsqlda", ":", "sqltype", ...
Calculate BLR from XSQLVAR array.
[ "Calculate", "BLR", "from", "XSQLVAR", "array", "." ]
5ce366c2fc8318510444f4a89801442f3e9e52ca
https://github.com/nakagami/pyfirebirdsql/blob/5ce366c2fc8318510444f4a89801442f3e9e52ca/firebirdsql/xsqlvar.py#L216-L242
train
40,932
nakagami/pyfirebirdsql
firebirdsql/xsqlvar.py
XSQLVAR._parse_date
def _parse_date(self, raw_value): "Convert raw data to datetime.date" nday = bytes_to_bint(raw_value) + 678882 century = (4 * nday - 1) // 146097 nday = 4 * nday - 1 - 146097 * century day = nday // 4 nday = (4 * day + 3) // 1461 day = 4 * day + 3 - 1461 * nday day = (day + 4) // 4 month = (5 * day - 3) // 153 day = 5 * day - 3 - 153 * month day = (day + 5) // 5 year = 100 * century + nday if month < 10: month += 3 else: month -= 9 year += 1 return year, month, day
python
def _parse_date(self, raw_value): "Convert raw data to datetime.date" nday = bytes_to_bint(raw_value) + 678882 century = (4 * nday - 1) // 146097 nday = 4 * nday - 1 - 146097 * century day = nday // 4 nday = (4 * day + 3) // 1461 day = 4 * day + 3 - 1461 * nday day = (day + 4) // 4 month = (5 * day - 3) // 153 day = 5 * day - 3 - 153 * month day = (day + 5) // 5 year = 100 * century + nday if month < 10: month += 3 else: month -= 9 year += 1 return year, month, day
[ "def", "_parse_date", "(", "self", ",", "raw_value", ")", ":", "nday", "=", "bytes_to_bint", "(", "raw_value", ")", "+", "678882", "century", "=", "(", "4", "*", "nday", "-", "1", ")", "//", "146097", "nday", "=", "4", "*", "nday", "-", "1", "-", ...
Convert raw data to datetime.date
[ "Convert", "raw", "data", "to", "datetime", ".", "date" ]
5ce366c2fc8318510444f4a89801442f3e9e52ca
https://github.com/nakagami/pyfirebirdsql/blob/5ce366c2fc8318510444f4a89801442f3e9e52ca/firebirdsql/xsqlvar.py#L118-L138
train
40,933
nakagami/pyfirebirdsql
firebirdsql/xsqlvar.py
XSQLVAR._parse_time
def _parse_time(self, raw_value): "Convert raw data to datetime.time" n = bytes_to_bint(raw_value) s = n // 10000 m = s // 60 h = m // 60 m = m % 60 s = s % 60 return (h, m, s, (n % 10000) * 100)
python
def _parse_time(self, raw_value): "Convert raw data to datetime.time" n = bytes_to_bint(raw_value) s = n // 10000 m = s // 60 h = m // 60 m = m % 60 s = s % 60 return (h, m, s, (n % 10000) * 100)
[ "def", "_parse_time", "(", "self", ",", "raw_value", ")", ":", "n", "=", "bytes_to_bint", "(", "raw_value", ")", "s", "=", "n", "//", "10000", "m", "=", "s", "//", "60", "h", "=", "m", "//", "60", "m", "=", "m", "%", "60", "s", "=", "s", "%",...
Convert raw data to datetime.time
[ "Convert", "raw", "data", "to", "datetime", ".", "time" ]
5ce366c2fc8318510444f4a89801442f3e9e52ca
https://github.com/nakagami/pyfirebirdsql/blob/5ce366c2fc8318510444f4a89801442f3e9e52ca/firebirdsql/xsqlvar.py#L140-L148
train
40,934
pv8/noipy
noipy/main.py
execute_update
def execute_update(args): """Execute the update based on command line args and returns a dictionary with 'execution result, ''response code', 'response info' and 'process friendly message'. """ provider_class = getattr(dnsupdater, dnsupdater.AVAILABLE_PLUGINS.get(args.provider)) updater_options = {} process_message = None auth = None if args.store: # --store argument if provider_class.auth_type == 'T': user_arg = args.usertoken or utils.read_input( "Paste your auth token: ") auth = authinfo.ApiAuth(usertoken=user_arg) else: user_arg = args.usertoken or utils.read_input( "Type your username: ") pass_arg = args.password or getpass.getpass("Type your password: ") auth = authinfo.ApiAuth(user_arg, pass_arg) authinfo.store(auth, args.provider, args.config) exec_result = EXECUTION_RESULT_OK if not args.hostname: update_ddns = False process_message = "Auth info stored." else: update_ddns = True # informations arguments elif args.usertoken and args.hostname: if provider_class.auth_type == 'T': auth = authinfo.ApiAuth(args.usertoken) else: auth = authinfo.ApiAuth(args.usertoken, args.password) update_ddns = True exec_result = EXECUTION_RESULT_OK elif args.hostname: if authinfo.exists(args.provider, args.config): auth = authinfo.load(args.provider, args.config) update_ddns = True exec_result = EXECUTION_RESULT_OK else: update_ddns = False exec_result = EXECUTION_RESULT_NOK process_message = "No stored auth information found for " \ "provider: '%s'" % args.provider else: # no arguments update_ddns = False exec_result = EXECUTION_RESULT_NOK process_message = "Warning: The hostname to be updated must be " \ "provided.\nUsertoken and password can be either " \ "provided via command line or stored with --store " \ "option.\nExecute noipy --help for more details." if update_ddns and args.provider == 'generic': if args.url: if not URL_RE.match(args.url): process_message = "Malformed URL." exec_result = EXECUTION_RESULT_NOK update_ddns = False else: updater_options['url'] = args.url else: process_message = "Must use --url if --provider is 'generic' " \ "(default)" exec_result = EXECUTION_RESULT_NOK update_ddns = False response_code = None response_text = None if update_ddns: ip_address = args.ip if args.ip else utils.get_ip() if not ip_address: process_message = "Unable to get IP address. Check connection." exec_result = EXECUTION_RESULT_NOK elif ip_address == utils.get_dns_ip(args.hostname): process_message = "No update required." else: updater = provider_class(auth, args.hostname, updater_options) print("Updating hostname '%s' with IP address %s " "[provider: '%s']..." % (args.hostname, ip_address, args.provider)) response_code, response_text = updater.update_dns(ip_address) process_message = updater.status_message proc_result = { 'exec_result': exec_result, 'response_code': response_code, 'response_text': response_text, 'process_message': process_message, } return proc_result
python
def execute_update(args): """Execute the update based on command line args and returns a dictionary with 'execution result, ''response code', 'response info' and 'process friendly message'. """ provider_class = getattr(dnsupdater, dnsupdater.AVAILABLE_PLUGINS.get(args.provider)) updater_options = {} process_message = None auth = None if args.store: # --store argument if provider_class.auth_type == 'T': user_arg = args.usertoken or utils.read_input( "Paste your auth token: ") auth = authinfo.ApiAuth(usertoken=user_arg) else: user_arg = args.usertoken or utils.read_input( "Type your username: ") pass_arg = args.password or getpass.getpass("Type your password: ") auth = authinfo.ApiAuth(user_arg, pass_arg) authinfo.store(auth, args.provider, args.config) exec_result = EXECUTION_RESULT_OK if not args.hostname: update_ddns = False process_message = "Auth info stored." else: update_ddns = True # informations arguments elif args.usertoken and args.hostname: if provider_class.auth_type == 'T': auth = authinfo.ApiAuth(args.usertoken) else: auth = authinfo.ApiAuth(args.usertoken, args.password) update_ddns = True exec_result = EXECUTION_RESULT_OK elif args.hostname: if authinfo.exists(args.provider, args.config): auth = authinfo.load(args.provider, args.config) update_ddns = True exec_result = EXECUTION_RESULT_OK else: update_ddns = False exec_result = EXECUTION_RESULT_NOK process_message = "No stored auth information found for " \ "provider: '%s'" % args.provider else: # no arguments update_ddns = False exec_result = EXECUTION_RESULT_NOK process_message = "Warning: The hostname to be updated must be " \ "provided.\nUsertoken and password can be either " \ "provided via command line or stored with --store " \ "option.\nExecute noipy --help for more details." if update_ddns and args.provider == 'generic': if args.url: if not URL_RE.match(args.url): process_message = "Malformed URL." exec_result = EXECUTION_RESULT_NOK update_ddns = False else: updater_options['url'] = args.url else: process_message = "Must use --url if --provider is 'generic' " \ "(default)" exec_result = EXECUTION_RESULT_NOK update_ddns = False response_code = None response_text = None if update_ddns: ip_address = args.ip if args.ip else utils.get_ip() if not ip_address: process_message = "Unable to get IP address. Check connection." exec_result = EXECUTION_RESULT_NOK elif ip_address == utils.get_dns_ip(args.hostname): process_message = "No update required." else: updater = provider_class(auth, args.hostname, updater_options) print("Updating hostname '%s' with IP address %s " "[provider: '%s']..." % (args.hostname, ip_address, args.provider)) response_code, response_text = updater.update_dns(ip_address) process_message = updater.status_message proc_result = { 'exec_result': exec_result, 'response_code': response_code, 'response_text': response_text, 'process_message': process_message, } return proc_result
[ "def", "execute_update", "(", "args", ")", ":", "provider_class", "=", "getattr", "(", "dnsupdater", ",", "dnsupdater", ".", "AVAILABLE_PLUGINS", ".", "get", "(", "args", ".", "provider", ")", ")", "updater_options", "=", "{", "}", "process_message", "=", "N...
Execute the update based on command line args and returns a dictionary with 'execution result, ''response code', 'response info' and 'process friendly message'.
[ "Execute", "the", "update", "based", "on", "command", "line", "args", "and", "returns", "a", "dictionary", "with", "execution", "result", "response", "code", "response", "info", "and", "process", "friendly", "message", "." ]
e37342505a463d02ea81b18a060eb7d84a5d1c27
https://github.com/pv8/noipy/blob/e37342505a463d02ea81b18a060eb7d84a5d1c27/noipy/main.py#L37-L132
train
40,935
pv8/noipy
noipy/dnsupdater.py
DnsUpdaterPlugin.update_dns
def update_dns(self, new_ip): """Call No-IP API based on dict login_info and return the status code. """ headers = None if self.auth_type == 'T': api_call_url = self._base_url.format(hostname=self.hostname, token=self.auth.token, ip=new_ip) else: api_call_url = self._base_url.format(hostname=self.hostname, ip=new_ip) headers = { 'Authorization': "Basic %s" % self.auth.base64key.decode('utf-8'), 'User-Agent': "%s/%s %s" % (__title__, __version__, __email__) } r = requests.get(api_call_url, headers=headers) self.last_ddns_response = str(r.text).strip() return r.status_code, r.text
python
def update_dns(self, new_ip): """Call No-IP API based on dict login_info and return the status code. """ headers = None if self.auth_type == 'T': api_call_url = self._base_url.format(hostname=self.hostname, token=self.auth.token, ip=new_ip) else: api_call_url = self._base_url.format(hostname=self.hostname, ip=new_ip) headers = { 'Authorization': "Basic %s" % self.auth.base64key.decode('utf-8'), 'User-Agent': "%s/%s %s" % (__title__, __version__, __email__) } r = requests.get(api_call_url, headers=headers) self.last_ddns_response = str(r.text).strip() return r.status_code, r.text
[ "def", "update_dns", "(", "self", ",", "new_ip", ")", ":", "headers", "=", "None", "if", "self", ".", "auth_type", "==", "'T'", ":", "api_call_url", "=", "self", ".", "_base_url", ".", "format", "(", "hostname", "=", "self", ".", "hostname", ",", "toke...
Call No-IP API based on dict login_info and return the status code.
[ "Call", "No", "-", "IP", "API", "based", "on", "dict", "login_info", "and", "return", "the", "status", "code", "." ]
e37342505a463d02ea81b18a060eb7d84a5d1c27
https://github.com/pv8/noipy/blob/e37342505a463d02ea81b18a060eb7d84a5d1c27/noipy/dnsupdater.py#L79-L100
train
40,936
pv8/noipy
noipy/dnsupdater.py
DnsUpdaterPlugin.status_message
def status_message(self): """Return friendly response from API based on response code. """ msg = None if self.last_ddns_response in response_messages.keys(): return response_messages.get(self.last_ddns_response) if 'good' in self.last_ddns_response: ip = re.search(r'(\d{1,3}\.?){4}', self.last_ddns_response).group() msg = "SUCCESS: DNS hostname IP (%s) successfully updated." % ip elif 'nochg' in self.last_ddns_response: ip = re.search(r'(\d{1,3}\.?){4}', self.last_ddns_response).group() msg = "SUCCESS: IP address (%s) is up to date, nothing was changed. " \ "Additional 'nochg' updates may be considered abusive." % ip else: msg = "ERROR: Ooops! Something went wrong !!!" return msg
python
def status_message(self): """Return friendly response from API based on response code. """ msg = None if self.last_ddns_response in response_messages.keys(): return response_messages.get(self.last_ddns_response) if 'good' in self.last_ddns_response: ip = re.search(r'(\d{1,3}\.?){4}', self.last_ddns_response).group() msg = "SUCCESS: DNS hostname IP (%s) successfully updated." % ip elif 'nochg' in self.last_ddns_response: ip = re.search(r'(\d{1,3}\.?){4}', self.last_ddns_response).group() msg = "SUCCESS: IP address (%s) is up to date, nothing was changed. " \ "Additional 'nochg' updates may be considered abusive." % ip else: msg = "ERROR: Ooops! Something went wrong !!!" return msg
[ "def", "status_message", "(", "self", ")", ":", "msg", "=", "None", "if", "self", ".", "last_ddns_response", "in", "response_messages", ".", "keys", "(", ")", ":", "return", "response_messages", ".", "get", "(", "self", ".", "last_ddns_response", ")", "if", ...
Return friendly response from API based on response code.
[ "Return", "friendly", "response", "from", "API", "based", "on", "response", "code", "." ]
e37342505a463d02ea81b18a060eb7d84a5d1c27
https://github.com/pv8/noipy/blob/e37342505a463d02ea81b18a060eb7d84a5d1c27/noipy/dnsupdater.py#L103-L120
train
40,937
pv8/noipy
noipy/utils.py
get_ip
def get_ip(): """Return machine's origin IP address. """ try: r = requests.get(HTTPBIN_URL) ip, _ = r.json()['origin'].split(',') return ip if r.status_code == 200 else None except requests.exceptions.ConnectionError: return None
python
def get_ip(): """Return machine's origin IP address. """ try: r = requests.get(HTTPBIN_URL) ip, _ = r.json()['origin'].split(',') return ip if r.status_code == 200 else None except requests.exceptions.ConnectionError: return None
[ "def", "get_ip", "(", ")", ":", "try", ":", "r", "=", "requests", ".", "get", "(", "HTTPBIN_URL", ")", "ip", ",", "_", "=", "r", ".", "json", "(", ")", "[", "'origin'", "]", ".", "split", "(", "','", ")", "return", "ip", "if", "r", ".", "stat...
Return machine's origin IP address.
[ "Return", "machine", "s", "origin", "IP", "address", "." ]
e37342505a463d02ea81b18a060eb7d84a5d1c27
https://github.com/pv8/noipy/blob/e37342505a463d02ea81b18a060eb7d84a5d1c27/noipy/utils.py#L24-L32
train
40,938
pv8/noipy
noipy/authinfo.py
store
def store(auth, provider, config_location=DEFAULT_CONFIG_DIR): """Store auth info in file for specified provider """ auth_file = None try: # only for custom locations _create_config_dir(config_location, "Creating custom config directory [%s]... ") config_dir = os.path.join(config_location, NOIPY_CONFIG) _create_config_dir(config_dir, "Creating directory [%s]... ") auth_file = os.path.join(config_dir, provider) print("Creating auth info file [%s]... " % auth_file, end="") with open(auth_file, 'w') as f: buff = auth.base64key.decode('utf-8') f.write(buff) print("OK.") except IOError as e: print('{0}: "{1}"'.format(e.strerror, auth_file)) raise e
python
def store(auth, provider, config_location=DEFAULT_CONFIG_DIR): """Store auth info in file for specified provider """ auth_file = None try: # only for custom locations _create_config_dir(config_location, "Creating custom config directory [%s]... ") config_dir = os.path.join(config_location, NOIPY_CONFIG) _create_config_dir(config_dir, "Creating directory [%s]... ") auth_file = os.path.join(config_dir, provider) print("Creating auth info file [%s]... " % auth_file, end="") with open(auth_file, 'w') as f: buff = auth.base64key.decode('utf-8') f.write(buff) print("OK.") except IOError as e: print('{0}: "{1}"'.format(e.strerror, auth_file)) raise e
[ "def", "store", "(", "auth", ",", "provider", ",", "config_location", "=", "DEFAULT_CONFIG_DIR", ")", ":", "auth_file", "=", "None", "try", ":", "# only for custom locations", "_create_config_dir", "(", "config_location", ",", "\"Creating custom config directory [%s]... \...
Store auth info in file for specified provider
[ "Store", "auth", "info", "in", "file", "for", "specified", "provider" ]
e37342505a463d02ea81b18a060eb7d84a5d1c27
https://github.com/pv8/noipy/blob/e37342505a463d02ea81b18a060eb7d84a5d1c27/noipy/authinfo.py#L60-L81
train
40,939
pv8/noipy
noipy/authinfo.py
load
def load(provider, config_location=DEFAULT_CONFIG_DIR): """Load provider specific auth info from file """ auth = None auth_file = None try: config_dir = os.path.join(config_location, NOIPY_CONFIG) print("Loading stored auth info [%s]... " % config_dir, end="") auth_file = os.path.join(config_dir, provider) with open(auth_file) as f: auth_key = f.read() auth = ApiAuth.get_instance(auth_key.encode('utf-8')) print("OK.") except IOError as e: print('{0}: "{1}"'.format(e.strerror, auth_file)) raise e return auth
python
def load(provider, config_location=DEFAULT_CONFIG_DIR): """Load provider specific auth info from file """ auth = None auth_file = None try: config_dir = os.path.join(config_location, NOIPY_CONFIG) print("Loading stored auth info [%s]... " % config_dir, end="") auth_file = os.path.join(config_dir, provider) with open(auth_file) as f: auth_key = f.read() auth = ApiAuth.get_instance(auth_key.encode('utf-8')) print("OK.") except IOError as e: print('{0}: "{1}"'.format(e.strerror, auth_file)) raise e return auth
[ "def", "load", "(", "provider", ",", "config_location", "=", "DEFAULT_CONFIG_DIR", ")", ":", "auth", "=", "None", "auth_file", "=", "None", "try", ":", "config_dir", "=", "os", ".", "path", ".", "join", "(", "config_location", ",", "NOIPY_CONFIG", ")", "pr...
Load provider specific auth info from file
[ "Load", "provider", "specific", "auth", "info", "from", "file" ]
e37342505a463d02ea81b18a060eb7d84a5d1c27
https://github.com/pv8/noipy/blob/e37342505a463d02ea81b18a060eb7d84a5d1c27/noipy/authinfo.py#L84-L101
train
40,940
pv8/noipy
noipy/authinfo.py
exists
def exists(provider, config_location=DEFAULT_CONFIG_DIR): """Check whether provider info is already stored """ config_dir = os.path.join(config_location, NOIPY_CONFIG) auth_file = os.path.join(config_dir, provider) return os.path.exists(auth_file)
python
def exists(provider, config_location=DEFAULT_CONFIG_DIR): """Check whether provider info is already stored """ config_dir = os.path.join(config_location, NOIPY_CONFIG) auth_file = os.path.join(config_dir, provider) return os.path.exists(auth_file)
[ "def", "exists", "(", "provider", ",", "config_location", "=", "DEFAULT_CONFIG_DIR", ")", ":", "config_dir", "=", "os", ".", "path", ".", "join", "(", "config_location", ",", "NOIPY_CONFIG", ")", "auth_file", "=", "os", ".", "path", ".", "join", "(", "conf...
Check whether provider info is already stored
[ "Check", "whether", "provider", "info", "is", "already", "stored" ]
e37342505a463d02ea81b18a060eb7d84a5d1c27
https://github.com/pv8/noipy/blob/e37342505a463d02ea81b18a060eb7d84a5d1c27/noipy/authinfo.py#L104-L109
train
40,941
pv8/noipy
noipy/authinfo.py
ApiAuth.get_instance
def get_instance(cls, encoded_key): """Return an ApiAuth instance from an encoded key """ login_str = base64.b64decode(encoded_key).decode('utf-8') usertoken, password = login_str.strip().split(':', 1) instance = cls(usertoken, password) return instance
python
def get_instance(cls, encoded_key): """Return an ApiAuth instance from an encoded key """ login_str = base64.b64decode(encoded_key).decode('utf-8') usertoken, password = login_str.strip().split(':', 1) instance = cls(usertoken, password) return instance
[ "def", "get_instance", "(", "cls", ",", "encoded_key", ")", ":", "login_str", "=", "base64", ".", "b64decode", "(", "encoded_key", ")", ".", "decode", "(", "'utf-8'", ")", "usertoken", ",", "password", "=", "login_str", ".", "strip", "(", ")", ".", "spli...
Return an ApiAuth instance from an encoded key
[ "Return", "an", "ApiAuth", "instance", "from", "an", "encoded", "key" ]
e37342505a463d02ea81b18a060eb7d84a5d1c27
https://github.com/pv8/noipy/blob/e37342505a463d02ea81b18a060eb7d84a5d1c27/noipy/authinfo.py#L36-L44
train
40,942
ChristopherRabotin/bungiesearch
bungiesearch/utils.py
create_indexed_document
def create_indexed_document(index_instance, model_items, action): ''' Creates the document that will be passed into the bulk index function. Either a list of serialized objects to index, or a a dictionary specifying the primary keys of items to be delete. ''' data = [] if action == 'delete': for pk in model_items: data.append({'_id': pk, '_op_type': action}) else: for doc in model_items: if index_instance.matches_indexing_condition(doc): data.append(index_instance.serialize_object(doc)) return data
python
def create_indexed_document(index_instance, model_items, action): ''' Creates the document that will be passed into the bulk index function. Either a list of serialized objects to index, or a a dictionary specifying the primary keys of items to be delete. ''' data = [] if action == 'delete': for pk in model_items: data.append({'_id': pk, '_op_type': action}) else: for doc in model_items: if index_instance.matches_indexing_condition(doc): data.append(index_instance.serialize_object(doc)) return data
[ "def", "create_indexed_document", "(", "index_instance", ",", "model_items", ",", "action", ")", ":", "data", "=", "[", "]", "if", "action", "==", "'delete'", ":", "for", "pk", "in", "model_items", ":", "data", ".", "append", "(", "{", "'_id'", ":", "pk"...
Creates the document that will be passed into the bulk index function. Either a list of serialized objects to index, or a a dictionary specifying the primary keys of items to be delete.
[ "Creates", "the", "document", "that", "will", "be", "passed", "into", "the", "bulk", "index", "function", ".", "Either", "a", "list", "of", "serialized", "objects", "to", "index", "or", "a", "a", "dictionary", "specifying", "the", "primary", "keys", "of", ...
13768342bc2698b214eb0003c2d113b6e273c30d
https://github.com/ChristopherRabotin/bungiesearch/blob/13768342bc2698b214eb0003c2d113b6e273c30d/bungiesearch/utils.py#L90-L103
train
40,943
ChristopherRabotin/bungiesearch
bungiesearch/utils.py
filter_model_items
def filter_model_items(index_instance, model_items, model_name, start_date, end_date): ''' Filters the model items queryset based on start and end date.''' if index_instance.updated_field is None: logger.warning("No updated date field found for {} - not restricting with start and end date".format(model_name)) else: if start_date: model_items = model_items.filter(**{'{}__gte'.format(index_instance.updated_field): __str_to_tzdate__(start_date)}) if end_date: model_items = model_items.filter(**{'{}__lte'.format(index_instance.updated_field): __str_to_tzdate__(end_date)}) return model_items
python
def filter_model_items(index_instance, model_items, model_name, start_date, end_date): ''' Filters the model items queryset based on start and end date.''' if index_instance.updated_field is None: logger.warning("No updated date field found for {} - not restricting with start and end date".format(model_name)) else: if start_date: model_items = model_items.filter(**{'{}__gte'.format(index_instance.updated_field): __str_to_tzdate__(start_date)}) if end_date: model_items = model_items.filter(**{'{}__lte'.format(index_instance.updated_field): __str_to_tzdate__(end_date)}) return model_items
[ "def", "filter_model_items", "(", "index_instance", ",", "model_items", ",", "model_name", ",", "start_date", ",", "end_date", ")", ":", "if", "index_instance", ".", "updated_field", "is", "None", ":", "logger", ".", "warning", "(", "\"No updated date field found fo...
Filters the model items queryset based on start and end date.
[ "Filters", "the", "model", "items", "queryset", "based", "on", "start", "and", "end", "date", "." ]
13768342bc2698b214eb0003c2d113b6e273c30d
https://github.com/ChristopherRabotin/bungiesearch/blob/13768342bc2698b214eb0003c2d113b6e273c30d/bungiesearch/utils.py#L106-L116
train
40,944
ponty/EasyProcess
easyprocess/__init__.py
extract_version
def extract_version(txt): """This function tries to extract the version from the help text of any program.""" words = txt.replace(',', ' ').split() version = None for x in reversed(words): if len(x) > 2: if x[0].lower() == 'v': x = x[1:] if '.' in x and x[0].isdigit(): version = x break return version
python
def extract_version(txt): """This function tries to extract the version from the help text of any program.""" words = txt.replace(',', ' ').split() version = None for x in reversed(words): if len(x) > 2: if x[0].lower() == 'v': x = x[1:] if '.' in x and x[0].isdigit(): version = x break return version
[ "def", "extract_version", "(", "txt", ")", ":", "words", "=", "txt", ".", "replace", "(", "','", ",", "' '", ")", ".", "split", "(", ")", "version", "=", "None", "for", "x", "in", "reversed", "(", "words", ")", ":", "if", "len", "(", "x", ")", ...
This function tries to extract the version from the help text of any program.
[ "This", "function", "tries", "to", "extract", "the", "version", "from", "the", "help", "text", "of", "any", "program", "." ]
81c2923339e09a86b6a2b8c12dc960f1bc67db9c
https://github.com/ponty/EasyProcess/blob/81c2923339e09a86b6a2b8c12dc960f1bc67db9c/easyprocess/__init__.py#L421-L433
train
40,945
ponty/EasyProcess
easyprocess/__init__.py
EasyProcess.check
def check(self, return_code=0): """Run command with arguments. Wait for command to complete. If the exit code was as expected and there is no exception then return, otherwise raise EasyProcessError. :param return_code: int, expected return code :rtype: self """ ret = self.call().return_code ok = ret == return_code if not ok: raise EasyProcessError( self, 'check error, return code is not {0}!'.format(return_code)) return self
python
def check(self, return_code=0): """Run command with arguments. Wait for command to complete. If the exit code was as expected and there is no exception then return, otherwise raise EasyProcessError. :param return_code: int, expected return code :rtype: self """ ret = self.call().return_code ok = ret == return_code if not ok: raise EasyProcessError( self, 'check error, return code is not {0}!'.format(return_code)) return self
[ "def", "check", "(", "self", ",", "return_code", "=", "0", ")", ":", "ret", "=", "self", ".", "call", "(", ")", ".", "return_code", "ok", "=", "ret", "==", "return_code", "if", "not", "ok", ":", "raise", "EasyProcessError", "(", "self", ",", "'check ...
Run command with arguments. Wait for command to complete. If the exit code was as expected and there is no exception then return, otherwise raise EasyProcessError. :param return_code: int, expected return code :rtype: self
[ "Run", "command", "with", "arguments", ".", "Wait", "for", "command", "to", "complete", ".", "If", "the", "exit", "code", "was", "as", "expected", "and", "there", "is", "no", "exception", "then", "return", "otherwise", "raise", "EasyProcessError", "." ]
81c2923339e09a86b6a2b8c12dc960f1bc67db9c
https://github.com/ponty/EasyProcess/blob/81c2923339e09a86b6a2b8c12dc960f1bc67db9c/easyprocess/__init__.py#L152-L166
train
40,946
ponty/EasyProcess
easyprocess/__init__.py
EasyProcess.call
def call(self, timeout=None): """Run command with arguments. Wait for command to complete. same as: 1. :meth:`start` 2. :meth:`wait` 3. :meth:`stop` :rtype: self """ self.start().wait(timeout=timeout) if self.is_alive(): self.stop() return self
python
def call(self, timeout=None): """Run command with arguments. Wait for command to complete. same as: 1. :meth:`start` 2. :meth:`wait` 3. :meth:`stop` :rtype: self """ self.start().wait(timeout=timeout) if self.is_alive(): self.stop() return self
[ "def", "call", "(", "self", ",", "timeout", "=", "None", ")", ":", "self", ".", "start", "(", ")", ".", "wait", "(", "timeout", "=", "timeout", ")", "if", "self", ".", "is_alive", "(", ")", ":", "self", ".", "stop", "(", ")", "return", "self" ]
Run command with arguments. Wait for command to complete. same as: 1. :meth:`start` 2. :meth:`wait` 3. :meth:`stop` :rtype: self
[ "Run", "command", "with", "arguments", ".", "Wait", "for", "command", "to", "complete", "." ]
81c2923339e09a86b6a2b8c12dc960f1bc67db9c
https://github.com/ponty/EasyProcess/blob/81c2923339e09a86b6a2b8c12dc960f1bc67db9c/easyprocess/__init__.py#L185-L199
train
40,947
ponty/EasyProcess
easyprocess/__init__.py
EasyProcess.start
def start(self): """start command in background and does not wait for it. :rtype: self """ if self.is_started: raise EasyProcessError(self, 'process was started twice!') if self.use_temp_files: self._stdout_file = tempfile.TemporaryFile(prefix='stdout_') self._stderr_file = tempfile.TemporaryFile(prefix='stderr_') stdout = self._stdout_file stderr = self._stderr_file else: stdout = subprocess.PIPE stderr = subprocess.PIPE cmd = list(map(uniencode, self.cmd)) try: self.popen = subprocess.Popen(cmd, stdout=stdout, stderr=stderr, cwd=self.cwd, env=self.env, ) except OSError as oserror: log.debug('OSError exception: %s', oserror) self.oserror = oserror raise EasyProcessError(self, 'start error') self.is_started = True log.debug('process was started (pid=%s)', self.pid) return self
python
def start(self): """start command in background and does not wait for it. :rtype: self """ if self.is_started: raise EasyProcessError(self, 'process was started twice!') if self.use_temp_files: self._stdout_file = tempfile.TemporaryFile(prefix='stdout_') self._stderr_file = tempfile.TemporaryFile(prefix='stderr_') stdout = self._stdout_file stderr = self._stderr_file else: stdout = subprocess.PIPE stderr = subprocess.PIPE cmd = list(map(uniencode, self.cmd)) try: self.popen = subprocess.Popen(cmd, stdout=stdout, stderr=stderr, cwd=self.cwd, env=self.env, ) except OSError as oserror: log.debug('OSError exception: %s', oserror) self.oserror = oserror raise EasyProcessError(self, 'start error') self.is_started = True log.debug('process was started (pid=%s)', self.pid) return self
[ "def", "start", "(", "self", ")", ":", "if", "self", ".", "is_started", ":", "raise", "EasyProcessError", "(", "self", ",", "'process was started twice!'", ")", "if", "self", ".", "use_temp_files", ":", "self", ".", "_stdout_file", "=", "tempfile", ".", "Tem...
start command in background and does not wait for it. :rtype: self
[ "start", "command", "in", "background", "and", "does", "not", "wait", "for", "it", "." ]
81c2923339e09a86b6a2b8c12dc960f1bc67db9c
https://github.com/ponty/EasyProcess/blob/81c2923339e09a86b6a2b8c12dc960f1bc67db9c/easyprocess/__init__.py#L201-L235
train
40,948
ponty/EasyProcess
easyprocess/__init__.py
EasyProcess.wait
def wait(self, timeout=None): """Wait for command to complete. Timeout: - discussion: http://stackoverflow.com/questions/1191374/subprocess-with-timeout - implementation: threading :rtype: self """ if timeout is not None: if not self._thread: self._thread = threading.Thread(target=self._wait4process) self._thread.daemon = 1 self._thread.start() if self._thread: self._thread.join(timeout=timeout) self.timeout_happened = self.timeout_happened or self._thread.isAlive() else: # no timeout and no existing thread self._wait4process() return self
python
def wait(self, timeout=None): """Wait for command to complete. Timeout: - discussion: http://stackoverflow.com/questions/1191374/subprocess-with-timeout - implementation: threading :rtype: self """ if timeout is not None: if not self._thread: self._thread = threading.Thread(target=self._wait4process) self._thread.daemon = 1 self._thread.start() if self._thread: self._thread.join(timeout=timeout) self.timeout_happened = self.timeout_happened or self._thread.isAlive() else: # no timeout and no existing thread self._wait4process() return self
[ "def", "wait", "(", "self", ",", "timeout", "=", "None", ")", ":", "if", "timeout", "is", "not", "None", ":", "if", "not", "self", ".", "_thread", ":", "self", ".", "_thread", "=", "threading", ".", "Thread", "(", "target", "=", "self", ".", "_wait...
Wait for command to complete. Timeout: - discussion: http://stackoverflow.com/questions/1191374/subprocess-with-timeout - implementation: threading :rtype: self
[ "Wait", "for", "command", "to", "complete", "." ]
81c2923339e09a86b6a2b8c12dc960f1bc67db9c
https://github.com/ponty/EasyProcess/blob/81c2923339e09a86b6a2b8c12dc960f1bc67db9c/easyprocess/__init__.py#L248-L272
train
40,949
Pipoline/rocket-python
rocketchat/api.py
RocketChatAPI.send_message
def send_message(self, message, room_id, **kwargs): """ Send a message to a given room """ return SendMessage(settings=self.settings, **kwargs).call( message=message, room_id=room_id, **kwargs )
python
def send_message(self, message, room_id, **kwargs): """ Send a message to a given room """ return SendMessage(settings=self.settings, **kwargs).call( message=message, room_id=room_id, **kwargs )
[ "def", "send_message", "(", "self", ",", "message", ",", "room_id", ",", "*", "*", "kwargs", ")", ":", "return", "SendMessage", "(", "settings", "=", "self", ".", "settings", ",", "*", "*", "kwargs", ")", ".", "call", "(", "message", "=", "message", ...
Send a message to a given room
[ "Send", "a", "message", "to", "a", "given", "room" ]
643ece8a9db106922e019984a859ca04283262ff
https://github.com/Pipoline/rocket-python/blob/643ece8a9db106922e019984a859ca04283262ff/rocketchat/api.py#L29-L37
train
40,950
Pipoline/rocket-python
rocketchat/api.py
RocketChatAPI.get_private_rooms
def get_private_rooms(self, **kwargs): """ Get a listing of all private rooms with their names and IDs """ return GetPrivateRooms(settings=self.settings, **kwargs).call(**kwargs)
python
def get_private_rooms(self, **kwargs): """ Get a listing of all private rooms with their names and IDs """ return GetPrivateRooms(settings=self.settings, **kwargs).call(**kwargs)
[ "def", "get_private_rooms", "(", "self", ",", "*", "*", "kwargs", ")", ":", "return", "GetPrivateRooms", "(", "settings", "=", "self", ".", "settings", ",", "*", "*", "kwargs", ")", ".", "call", "(", "*", "*", "kwargs", ")" ]
Get a listing of all private rooms with their names and IDs
[ "Get", "a", "listing", "of", "all", "private", "rooms", "with", "their", "names", "and", "IDs" ]
643ece8a9db106922e019984a859ca04283262ff
https://github.com/Pipoline/rocket-python/blob/643ece8a9db106922e019984a859ca04283262ff/rocketchat/api.py#L39-L43
train
40,951
Pipoline/rocket-python
rocketchat/api.py
RocketChatAPI.get_private_room_history
def get_private_room_history(self, room_id, oldest=None, **kwargs): """ Get various history of specific private group in this case private :param room_id: :param kwargs: :return: """ return GetPrivateRoomHistory(settings=self.settings, **kwargs).call( room_id=room_id, oldest=oldest, **kwargs )
python
def get_private_room_history(self, room_id, oldest=None, **kwargs): """ Get various history of specific private group in this case private :param room_id: :param kwargs: :return: """ return GetPrivateRoomHistory(settings=self.settings, **kwargs).call( room_id=room_id, oldest=oldest, **kwargs )
[ "def", "get_private_room_history", "(", "self", ",", "room_id", ",", "oldest", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "GetPrivateRoomHistory", "(", "settings", "=", "self", ".", "settings", ",", "*", "*", "kwargs", ")", ".", "call", "(...
Get various history of specific private group in this case private :param room_id: :param kwargs: :return:
[ "Get", "various", "history", "of", "specific", "private", "group", "in", "this", "case", "private" ]
643ece8a9db106922e019984a859ca04283262ff
https://github.com/Pipoline/rocket-python/blob/643ece8a9db106922e019984a859ca04283262ff/rocketchat/api.py#L45-L57
train
40,952
Pipoline/rocket-python
rocketchat/api.py
RocketChatAPI.get_public_rooms
def get_public_rooms(self, **kwargs): """ Get a listing of all public rooms with their names and IDs """ return GetPublicRooms(settings=self.settings, **kwargs).call(**kwargs)
python
def get_public_rooms(self, **kwargs): """ Get a listing of all public rooms with their names and IDs """ return GetPublicRooms(settings=self.settings, **kwargs).call(**kwargs)
[ "def", "get_public_rooms", "(", "self", ",", "*", "*", "kwargs", ")", ":", "return", "GetPublicRooms", "(", "settings", "=", "self", ".", "settings", ",", "*", "*", "kwargs", ")", ".", "call", "(", "*", "*", "kwargs", ")" ]
Get a listing of all public rooms with their names and IDs
[ "Get", "a", "listing", "of", "all", "public", "rooms", "with", "their", "names", "and", "IDs" ]
643ece8a9db106922e019984a859ca04283262ff
https://github.com/Pipoline/rocket-python/blob/643ece8a9db106922e019984a859ca04283262ff/rocketchat/api.py#L59-L63
train
40,953
Pipoline/rocket-python
rocketchat/api.py
RocketChatAPI.get_private_room_info
def get_private_room_info(self, room_id, **kwargs): """ Get various information about a specific private group :param room_id: :param kwargs: :return: """ return GetPrivateRoomInfo(settings=self.settings, **kwargs).call( room_id=room_id, **kwargs )
python
def get_private_room_info(self, room_id, **kwargs): """ Get various information about a specific private group :param room_id: :param kwargs: :return: """ return GetPrivateRoomInfo(settings=self.settings, **kwargs).call( room_id=room_id, **kwargs )
[ "def", "get_private_room_info", "(", "self", ",", "room_id", ",", "*", "*", "kwargs", ")", ":", "return", "GetPrivateRoomInfo", "(", "settings", "=", "self", ".", "settings", ",", "*", "*", "kwargs", ")", ".", "call", "(", "room_id", "=", "room_id", ",",...
Get various information about a specific private group :param room_id: :param kwargs: :return:
[ "Get", "various", "information", "about", "a", "specific", "private", "group" ]
643ece8a9db106922e019984a859ca04283262ff
https://github.com/Pipoline/rocket-python/blob/643ece8a9db106922e019984a859ca04283262ff/rocketchat/api.py#L95-L106
train
40,954
ChristopherRabotin/bungiesearch
bungiesearch/__init__.py
Bungiesearch._clone
def _clone(self): ''' Must clone additional fields to those cloned by elasticsearch-dsl-py. ''' instance = super(Bungiesearch, self)._clone() instance._raw_results_only = self._raw_results_only return instance
python
def _clone(self): ''' Must clone additional fields to those cloned by elasticsearch-dsl-py. ''' instance = super(Bungiesearch, self)._clone() instance._raw_results_only = self._raw_results_only return instance
[ "def", "_clone", "(", "self", ")", ":", "instance", "=", "super", "(", "Bungiesearch", ",", "self", ")", ".", "_clone", "(", ")", "instance", ".", "_raw_results_only", "=", "self", ".", "_raw_results_only", "return", "instance" ]
Must clone additional fields to those cloned by elasticsearch-dsl-py.
[ "Must", "clone", "additional", "fields", "to", "those", "cloned", "by", "elasticsearch", "-", "dsl", "-", "py", "." ]
13768342bc2698b214eb0003c2d113b6e273c30d
https://github.com/ChristopherRabotin/bungiesearch/blob/13768342bc2698b214eb0003c2d113b6e273c30d/bungiesearch/__init__.py#L266-L272
train
40,955
ChristopherRabotin/bungiesearch
bungiesearch/__init__.py
Bungiesearch.execute
def execute(self, return_results=True): ''' Executes the query and attempts to create model objects from results. ''' if self.results: return self.results if return_results else None self.execute_raw() if self._raw_results_only: self.results = self.raw_results else: self.map_results() if return_results: return self.results
python
def execute(self, return_results=True): ''' Executes the query and attempts to create model objects from results. ''' if self.results: return self.results if return_results else None self.execute_raw() if self._raw_results_only: self.results = self.raw_results else: self.map_results() if return_results: return self.results
[ "def", "execute", "(", "self", ",", "return_results", "=", "True", ")", ":", "if", "self", ".", "results", ":", "return", "self", ".", "results", "if", "return_results", "else", "None", "self", ".", "execute_raw", "(", ")", "if", "self", ".", "_raw_resul...
Executes the query and attempts to create model objects from results.
[ "Executes", "the", "query", "and", "attempts", "to", "create", "model", "objects", "from", "results", "." ]
13768342bc2698b214eb0003c2d113b6e273c30d
https://github.com/ChristopherRabotin/bungiesearch/blob/13768342bc2698b214eb0003c2d113b6e273c30d/bungiesearch/__init__.py#L283-L298
train
40,956
ChristopherRabotin/bungiesearch
bungiesearch/__init__.py
Bungiesearch.hook_alias
def hook_alias(self, alias, model_obj=None): ''' Returns the alias function, if it exists and if it can be applied to this model. ''' try: search_alias = self._alias_hooks[alias] except KeyError: raise AttributeError('Could not find search alias named {}. Is this alias defined in BUNGIESEARCH["ALIASES"]?'.format(alias)) else: if search_alias._applicable_models and \ ((model_obj and model_obj not in search_alias._applicable_models) or \ not any([app_model_obj.__name__ in self._doc_type for app_model_obj in search_alias._applicable_models])): raise ValueError('Search alias {} is not applicable to model/doc_types {}.'.format(alias, model_obj if model_obj else self._doc_type)) return search_alias.prepare(self, model_obj).alias_for
python
def hook_alias(self, alias, model_obj=None): ''' Returns the alias function, if it exists and if it can be applied to this model. ''' try: search_alias = self._alias_hooks[alias] except KeyError: raise AttributeError('Could not find search alias named {}. Is this alias defined in BUNGIESEARCH["ALIASES"]?'.format(alias)) else: if search_alias._applicable_models and \ ((model_obj and model_obj not in search_alias._applicable_models) or \ not any([app_model_obj.__name__ in self._doc_type for app_model_obj in search_alias._applicable_models])): raise ValueError('Search alias {} is not applicable to model/doc_types {}.'.format(alias, model_obj if model_obj else self._doc_type)) return search_alias.prepare(self, model_obj).alias_for
[ "def", "hook_alias", "(", "self", ",", "alias", ",", "model_obj", "=", "None", ")", ":", "try", ":", "search_alias", "=", "self", ".", "_alias_hooks", "[", "alias", "]", "except", "KeyError", ":", "raise", "AttributeError", "(", "'Could not find search alias n...
Returns the alias function, if it exists and if it can be applied to this model.
[ "Returns", "the", "alias", "function", "if", "it", "exists", "and", "if", "it", "can", "be", "applied", "to", "this", "model", "." ]
13768342bc2698b214eb0003c2d113b6e273c30d
https://github.com/ChristopherRabotin/bungiesearch/blob/13768342bc2698b214eb0003c2d113b6e273c30d/bungiesearch/__init__.py#L358-L371
train
40,957
ChristopherRabotin/bungiesearch
bungiesearch/managers.py
BungiesearchManager.custom_search
def custom_search(self, index, doc_type): ''' Performs a search on a custom elasticsearch index and mapping. Will not attempt to map result objects. ''' from bungiesearch import Bungiesearch return Bungiesearch(raw_results=True).index(index).doc_type(doc_type)
python
def custom_search(self, index, doc_type): ''' Performs a search on a custom elasticsearch index and mapping. Will not attempt to map result objects. ''' from bungiesearch import Bungiesearch return Bungiesearch(raw_results=True).index(index).doc_type(doc_type)
[ "def", "custom_search", "(", "self", ",", "index", ",", "doc_type", ")", ":", "from", "bungiesearch", "import", "Bungiesearch", "return", "Bungiesearch", "(", "raw_results", "=", "True", ")", ".", "index", "(", "index", ")", ".", "doc_type", "(", "doc_type",...
Performs a search on a custom elasticsearch index and mapping. Will not attempt to map result objects.
[ "Performs", "a", "search", "on", "a", "custom", "elasticsearch", "index", "and", "mapping", ".", "Will", "not", "attempt", "to", "map", "result", "objects", "." ]
13768342bc2698b214eb0003c2d113b6e273c30d
https://github.com/ChristopherRabotin/bungiesearch/blob/13768342bc2698b214eb0003c2d113b6e273c30d/bungiesearch/managers.py#L24-L29
train
40,958
ChristopherRabotin/bungiesearch
bungiesearch/managers.py
BungiesearchManager.contribute_to_class
def contribute_to_class(self, cls, name): ''' Sets up the signal processor. Since self.model is not available in the constructor, we perform this operation here. ''' super(BungiesearchManager, self).contribute_to_class(cls, name) from . import Bungiesearch from .signals import get_signal_processor settings = Bungiesearch.BUNGIE if 'SIGNALS' in settings: self.signal_processor = get_signal_processor() self.signal_processor.setup(self.model)
python
def contribute_to_class(self, cls, name): ''' Sets up the signal processor. Since self.model is not available in the constructor, we perform this operation here. ''' super(BungiesearchManager, self).contribute_to_class(cls, name) from . import Bungiesearch from .signals import get_signal_processor settings = Bungiesearch.BUNGIE if 'SIGNALS' in settings: self.signal_processor = get_signal_processor() self.signal_processor.setup(self.model)
[ "def", "contribute_to_class", "(", "self", ",", "cls", ",", "name", ")", ":", "super", "(", "BungiesearchManager", ",", "self", ")", ".", "contribute_to_class", "(", "cls", ",", "name", ")", "from", ".", "import", "Bungiesearch", "from", ".", "signals", "i...
Sets up the signal processor. Since self.model is not available in the constructor, we perform this operation here.
[ "Sets", "up", "the", "signal", "processor", ".", "Since", "self", ".", "model", "is", "not", "available", "in", "the", "constructor", "we", "perform", "this", "operation", "here", "." ]
13768342bc2698b214eb0003c2d113b6e273c30d
https://github.com/ChristopherRabotin/bungiesearch/blob/13768342bc2698b214eb0003c2d113b6e273c30d/bungiesearch/managers.py#L31-L43
train
40,959
ChristopherRabotin/bungiesearch
bungiesearch/fields.py
django_field_to_index
def django_field_to_index(field, **attr): ''' Returns the index field type that would likely be associated with each Django type. ''' dj_type = field.get_internal_type() if dj_type in ('DateField', 'DateTimeField'): return DateField(**attr) elif dj_type in ('BooleanField', 'NullBooleanField'): return BooleanField(**attr) elif dj_type in ('DecimalField', 'FloatField'): return NumberField(coretype='float', **attr) elif dj_type in ('PositiveSmallIntegerField', 'SmallIntegerField'): return NumberField(coretype='short', **attr) elif dj_type in ('IntegerField', 'PositiveIntegerField', 'AutoField'): return NumberField(coretype='integer', **attr) elif dj_type in ('BigIntegerField'): return NumberField(coretype='long', **attr) return StringField(**attr)
python
def django_field_to_index(field, **attr): ''' Returns the index field type that would likely be associated with each Django type. ''' dj_type = field.get_internal_type() if dj_type in ('DateField', 'DateTimeField'): return DateField(**attr) elif dj_type in ('BooleanField', 'NullBooleanField'): return BooleanField(**attr) elif dj_type in ('DecimalField', 'FloatField'): return NumberField(coretype='float', **attr) elif dj_type in ('PositiveSmallIntegerField', 'SmallIntegerField'): return NumberField(coretype='short', **attr) elif dj_type in ('IntegerField', 'PositiveIntegerField', 'AutoField'): return NumberField(coretype='integer', **attr) elif dj_type in ('BigIntegerField'): return NumberField(coretype='long', **attr) return StringField(**attr)
[ "def", "django_field_to_index", "(", "field", ",", "*", "*", "attr", ")", ":", "dj_type", "=", "field", ".", "get_internal_type", "(", ")", "if", "dj_type", "in", "(", "'DateField'", ",", "'DateTimeField'", ")", ":", "return", "DateField", "(", "*", "*", ...
Returns the index field type that would likely be associated with each Django type.
[ "Returns", "the", "index", "field", "type", "that", "would", "likely", "be", "associated", "with", "each", "Django", "type", "." ]
13768342bc2698b214eb0003c2d113b6e273c30d
https://github.com/ChristopherRabotin/bungiesearch/blob/13768342bc2698b214eb0003c2d113b6e273c30d/bungiesearch/fields.py#L145-L165
train
40,960
ponty/EasyProcess
easyprocess/unicodeutil.py
split_command
def split_command(cmd, posix=None): ''' - cmd is string list -> nothing to do - cmd is string -> split it using shlex :param cmd: string ('ls -l') or list of strings (['ls','-l']) :rtype: string list ''' if not isinstance(cmd, string_types): # cmd is string list pass else: if not PY3: # cmd is string # The shlex module currently does not support Unicode input (in # 2.x)! if isinstance(cmd, unicode): try: cmd = unicodedata.normalize( 'NFKD', cmd).encode('ascii', 'strict') except UnicodeEncodeError: raise EasyProcessUnicodeError('unicode command "%s" can not be processed.' % cmd + 'Use string list instead of string') log.debug('unicode is normalized') if posix is None: posix = 'win' not in sys.platform cmd = shlex.split(cmd, posix=posix) return cmd
python
def split_command(cmd, posix=None): ''' - cmd is string list -> nothing to do - cmd is string -> split it using shlex :param cmd: string ('ls -l') or list of strings (['ls','-l']) :rtype: string list ''' if not isinstance(cmd, string_types): # cmd is string list pass else: if not PY3: # cmd is string # The shlex module currently does not support Unicode input (in # 2.x)! if isinstance(cmd, unicode): try: cmd = unicodedata.normalize( 'NFKD', cmd).encode('ascii', 'strict') except UnicodeEncodeError: raise EasyProcessUnicodeError('unicode command "%s" can not be processed.' % cmd + 'Use string list instead of string') log.debug('unicode is normalized') if posix is None: posix = 'win' not in sys.platform cmd = shlex.split(cmd, posix=posix) return cmd
[ "def", "split_command", "(", "cmd", ",", "posix", "=", "None", ")", ":", "if", "not", "isinstance", "(", "cmd", ",", "string_types", ")", ":", "# cmd is string list", "pass", "else", ":", "if", "not", "PY3", ":", "# cmd is string", "# The shlex module currentl...
- cmd is string list -> nothing to do - cmd is string -> split it using shlex :param cmd: string ('ls -l') or list of strings (['ls','-l']) :rtype: string list
[ "-", "cmd", "is", "string", "list", "-", ">", "nothing", "to", "do", "-", "cmd", "is", "string", "-", ">", "split", "it", "using", "shlex" ]
81c2923339e09a86b6a2b8c12dc960f1bc67db9c
https://github.com/ponty/EasyProcess/blob/81c2923339e09a86b6a2b8c12dc960f1bc67db9c/easyprocess/unicodeutil.py#L20-L47
train
40,961
ChristopherRabotin/bungiesearch
bungiesearch/indices.py
ModelIndex.get_mapping
def get_mapping(self, meta_fields=True): ''' Returns the mapping for the index as a dictionary. :param meta_fields: Also include elasticsearch meta fields in the dictionary. :return: a dictionary which can be used to generate the elasticsearch index mapping for this doctype. ''' return {'properties': dict((name, field.json()) for name, field in iteritems(self.fields) if meta_fields or name not in AbstractField.meta_fields)}
python
def get_mapping(self, meta_fields=True): ''' Returns the mapping for the index as a dictionary. :param meta_fields: Also include elasticsearch meta fields in the dictionary. :return: a dictionary which can be used to generate the elasticsearch index mapping for this doctype. ''' return {'properties': dict((name, field.json()) for name, field in iteritems(self.fields) if meta_fields or name not in AbstractField.meta_fields)}
[ "def", "get_mapping", "(", "self", ",", "meta_fields", "=", "True", ")", ":", "return", "{", "'properties'", ":", "dict", "(", "(", "name", ",", "field", ".", "json", "(", ")", ")", "for", "name", ",", "field", "in", "iteritems", "(", "self", ".", ...
Returns the mapping for the index as a dictionary. :param meta_fields: Also include elasticsearch meta fields in the dictionary. :return: a dictionary which can be used to generate the elasticsearch index mapping for this doctype.
[ "Returns", "the", "mapping", "for", "the", "index", "as", "a", "dictionary", "." ]
13768342bc2698b214eb0003c2d113b6e273c30d
https://github.com/ChristopherRabotin/bungiesearch/blob/13768342bc2698b214eb0003c2d113b6e273c30d/bungiesearch/indices.py#L71-L78
train
40,962
ChristopherRabotin/bungiesearch
bungiesearch/indices.py
ModelIndex.serialize_object
def serialize_object(self, obj, obj_pk=None): ''' Serializes an object for it to be added to the index. :param obj: Object to be serialized. Optional if obj_pk is passed. :param obj_pk: Object primary key. Superseded by `obj` if available. :return: A dictionary representing the object as defined in the mapping. ''' if not obj: try: # We're using `filter` followed by `values` in order to only fetch the required fields. obj = self.model.objects.filter(pk=obj_pk).values(*self.fields_to_fetch)[0] except Exception as e: raise ValueError('Could not find object of primary key = {} in model {} (model index class {}). (Original exception: {}.)'.format(obj_pk, self.model, self.__class__.__name__, e)) serialized_object = {} for name, field in iteritems(self.fields): if hasattr(self, "prepare_%s" % name): value = getattr(self, "prepare_%s" % name)(obj) else: value = field.value(obj) serialized_object[name] = value return serialized_object
python
def serialize_object(self, obj, obj_pk=None): ''' Serializes an object for it to be added to the index. :param obj: Object to be serialized. Optional if obj_pk is passed. :param obj_pk: Object primary key. Superseded by `obj` if available. :return: A dictionary representing the object as defined in the mapping. ''' if not obj: try: # We're using `filter` followed by `values` in order to only fetch the required fields. obj = self.model.objects.filter(pk=obj_pk).values(*self.fields_to_fetch)[0] except Exception as e: raise ValueError('Could not find object of primary key = {} in model {} (model index class {}). (Original exception: {}.)'.format(obj_pk, self.model, self.__class__.__name__, e)) serialized_object = {} for name, field in iteritems(self.fields): if hasattr(self, "prepare_%s" % name): value = getattr(self, "prepare_%s" % name)(obj) else: value = field.value(obj) serialized_object[name] = value return serialized_object
[ "def", "serialize_object", "(", "self", ",", "obj", ",", "obj_pk", "=", "None", ")", ":", "if", "not", "obj", ":", "try", ":", "# We're using `filter` followed by `values` in order to only fetch the required fields.", "obj", "=", "self", ".", "model", ".", "objects"...
Serializes an object for it to be added to the index. :param obj: Object to be serialized. Optional if obj_pk is passed. :param obj_pk: Object primary key. Superseded by `obj` if available. :return: A dictionary representing the object as defined in the mapping.
[ "Serializes", "an", "object", "for", "it", "to", "be", "added", "to", "the", "index", "." ]
13768342bc2698b214eb0003c2d113b6e273c30d
https://github.com/ChristopherRabotin/bungiesearch/blob/13768342bc2698b214eb0003c2d113b6e273c30d/bungiesearch/indices.py#L104-L129
train
40,963
ChristopherRabotin/bungiesearch
bungiesearch/indices.py
ModelIndex._get_fields
def _get_fields(self, fields, excludes, hotfixes): ''' Given any explicit fields to include and fields to exclude, add additional fields based on the associated model. If the field needs a hotfix, apply it. ''' final_fields = {} fields = fields or [] excludes = excludes or [] for f in self.model._meta.fields: # If the field name is already present, skip if f.name in self.fields: continue # If field is not present in explicit field listing, skip if fields and f.name not in fields: continue # If field is in exclude list, skip if excludes and f.name in excludes: continue # If field is a relation, skip. if getattr(f, 'rel'): continue attr = {'model_attr': f.name} if f.has_default(): attr['null_value'] = f.default if f.name in hotfixes: attr.update(hotfixes[f.name]) final_fields[f.name] = django_field_to_index(f, **attr) return final_fields
python
def _get_fields(self, fields, excludes, hotfixes): ''' Given any explicit fields to include and fields to exclude, add additional fields based on the associated model. If the field needs a hotfix, apply it. ''' final_fields = {} fields = fields or [] excludes = excludes or [] for f in self.model._meta.fields: # If the field name is already present, skip if f.name in self.fields: continue # If field is not present in explicit field listing, skip if fields and f.name not in fields: continue # If field is in exclude list, skip if excludes and f.name in excludes: continue # If field is a relation, skip. if getattr(f, 'rel'): continue attr = {'model_attr': f.name} if f.has_default(): attr['null_value'] = f.default if f.name in hotfixes: attr.update(hotfixes[f.name]) final_fields[f.name] = django_field_to_index(f, **attr) return final_fields
[ "def", "_get_fields", "(", "self", ",", "fields", ",", "excludes", ",", "hotfixes", ")", ":", "final_fields", "=", "{", "}", "fields", "=", "fields", "or", "[", "]", "excludes", "=", "excludes", "or", "[", "]", "for", "f", "in", "self", ".", "model",...
Given any explicit fields to include and fields to exclude, add additional fields based on the associated model. If the field needs a hotfix, apply it.
[ "Given", "any", "explicit", "fields", "to", "include", "and", "fields", "to", "exclude", "add", "additional", "fields", "based", "on", "the", "associated", "model", ".", "If", "the", "field", "needs", "a", "hotfix", "apply", "it", "." ]
13768342bc2698b214eb0003c2d113b6e273c30d
https://github.com/ChristopherRabotin/bungiesearch/blob/13768342bc2698b214eb0003c2d113b6e273c30d/bungiesearch/indices.py#L131-L166
train
40,964
cwacek/python-jsonschema-objects
python_jsonschema_objects/wrapper_types.py
ArrayWrapper.validate_items
def validate_items(self): """ Validates the items in the backing array, including performing type validation. Sets the _typed property and clears the dirty flag as a side effect Returns: The typed array """ logger.debug(fmt("Validating {}", self)) from python_jsonschema_objects import classbuilder if self.__itemtype__ is None: return type_checks = self.__itemtype__ if not isinstance(type_checks, (tuple, list)): # we were given items = {'type': 'blah'} ; thus ensure the type for all data. type_checks = [type_checks] * len(self.data) elif len(type_checks) > len(self.data): raise ValidationError( "{1} does not have sufficient elements to validate against {0}" .format(self.__itemtype__, self.data)) typed_elems = [] for elem, typ in zip(self.data, type_checks): if isinstance(typ, dict): for param, paramval in six.iteritems(typ): validator = registry(param) if validator is not None: validator(paramval, elem, typ) typed_elems.append(elem) elif util.safe_issubclass(typ, classbuilder.LiteralValue): val = typ(elem) val.validate() typed_elems.append(val) elif util.safe_issubclass(typ, classbuilder.ProtocolBase): if not isinstance(elem, typ): try: if isinstance(elem, (six.string_types, six.integer_types, float)): val = typ(elem) else: val = typ(**util.coerce_for_expansion(elem)) except TypeError as e: raise ValidationError("'{0}' is not a valid value for '{1}': {2}" .format(elem, typ, e)) else: val = elem val.validate() typed_elems.append(val) elif util.safe_issubclass(typ, ArrayWrapper): val = typ(elem) val.validate() typed_elems.append(val) elif isinstance(typ, (classbuilder.TypeProxy, classbuilder.TypeRef)): try: if isinstance(elem, (six.string_types, six.integer_types, float)): val = typ(elem) else: val = typ(**util.coerce_for_expansion(elem)) except TypeError as e: raise ValidationError("'{0}' is not a valid value for '{1}': {2}" .format(elem, typ, e)) else: val.validate() typed_elems.append(val) self._dirty = False self._typed = typed_elems return typed_elems
python
def validate_items(self): """ Validates the items in the backing array, including performing type validation. Sets the _typed property and clears the dirty flag as a side effect Returns: The typed array """ logger.debug(fmt("Validating {}", self)) from python_jsonschema_objects import classbuilder if self.__itemtype__ is None: return type_checks = self.__itemtype__ if not isinstance(type_checks, (tuple, list)): # we were given items = {'type': 'blah'} ; thus ensure the type for all data. type_checks = [type_checks] * len(self.data) elif len(type_checks) > len(self.data): raise ValidationError( "{1} does not have sufficient elements to validate against {0}" .format(self.__itemtype__, self.data)) typed_elems = [] for elem, typ in zip(self.data, type_checks): if isinstance(typ, dict): for param, paramval in six.iteritems(typ): validator = registry(param) if validator is not None: validator(paramval, elem, typ) typed_elems.append(elem) elif util.safe_issubclass(typ, classbuilder.LiteralValue): val = typ(elem) val.validate() typed_elems.append(val) elif util.safe_issubclass(typ, classbuilder.ProtocolBase): if not isinstance(elem, typ): try: if isinstance(elem, (six.string_types, six.integer_types, float)): val = typ(elem) else: val = typ(**util.coerce_for_expansion(elem)) except TypeError as e: raise ValidationError("'{0}' is not a valid value for '{1}': {2}" .format(elem, typ, e)) else: val = elem val.validate() typed_elems.append(val) elif util.safe_issubclass(typ, ArrayWrapper): val = typ(elem) val.validate() typed_elems.append(val) elif isinstance(typ, (classbuilder.TypeProxy, classbuilder.TypeRef)): try: if isinstance(elem, (six.string_types, six.integer_types, float)): val = typ(elem) else: val = typ(**util.coerce_for_expansion(elem)) except TypeError as e: raise ValidationError("'{0}' is not a valid value for '{1}': {2}" .format(elem, typ, e)) else: val.validate() typed_elems.append(val) self._dirty = False self._typed = typed_elems return typed_elems
[ "def", "validate_items", "(", "self", ")", ":", "logger", ".", "debug", "(", "fmt", "(", "\"Validating {}\"", ",", "self", ")", ")", "from", "python_jsonschema_objects", "import", "classbuilder", "if", "self", ".", "__itemtype__", "is", "None", ":", "return", ...
Validates the items in the backing array, including performing type validation. Sets the _typed property and clears the dirty flag as a side effect Returns: The typed array
[ "Validates", "the", "items", "in", "the", "backing", "array", "including", "performing", "type", "validation", "." ]
54c82bfaec9c099c472663742abfc7de373a5e49
https://github.com/cwacek/python-jsonschema-objects/blob/54c82bfaec9c099c472663742abfc7de373a5e49/python_jsonschema_objects/wrapper_types.py#L149-L221
train
40,965
cwacek/python-jsonschema-objects
python_jsonschema_objects/markdown_support.py
SpecialFencedCodeExtension.extendMarkdown
def extendMarkdown(self, md, md_globals): """ Add FencedBlockPreprocessor to the Markdown instance. """ md.registerExtension(self) md.preprocessors.add('fenced_code_block', SpecialFencePreprocessor(md), ">normalize_whitespace")
python
def extendMarkdown(self, md, md_globals): """ Add FencedBlockPreprocessor to the Markdown instance. """ md.registerExtension(self) md.preprocessors.add('fenced_code_block', SpecialFencePreprocessor(md), ">normalize_whitespace")
[ "def", "extendMarkdown", "(", "self", ",", "md", ",", "md_globals", ")", ":", "md", ".", "registerExtension", "(", "self", ")", "md", ".", "preprocessors", ".", "add", "(", "'fenced_code_block'", ",", "SpecialFencePreprocessor", "(", "md", ")", ",", "\">norm...
Add FencedBlockPreprocessor to the Markdown instance.
[ "Add", "FencedBlockPreprocessor", "to", "the", "Markdown", "instance", "." ]
54c82bfaec9c099c472663742abfc7de373a5e49
https://github.com/cwacek/python-jsonschema-objects/blob/54c82bfaec9c099c472663742abfc7de373a5e49/python_jsonschema_objects/markdown_support.py#L28-L34
train
40,966
cwacek/python-jsonschema-objects
python_jsonschema_objects/util.py
propmerge
def propmerge(into, data_from): """ Merge JSON schema requirements into a dictionary """ newprops = copy.deepcopy(into) for prop, propval in six.iteritems(data_from): if prop not in newprops: newprops[prop] = propval continue new_sp = newprops[prop] for subprop, spval in six.iteritems(propval): if subprop not in new_sp: new_sp[subprop] = spval elif subprop == 'enum': new_sp[subprop] = set(spval) & set(new_sp[subprop]) elif subprop == 'type': if spval != new_sp[subprop]: raise TypeError("Type cannot conflict in allOf'") elif subprop in ('minLength', 'minimum'): new_sp[subprop] = (new_sp[subprop] if new_sp[subprop] > spval else spval) elif subprop in ('maxLength', 'maximum'): new_sp[subprop] = (new_sp[subprop] if new_sp[subprop] < spval else spval) elif subprop == 'multipleOf': if new_sp[subprop] % spval == 0: new_sp[subprop] = spval else: raise AttributeError( "Cannot set conflicting multipleOf values") else: new_sp[subprop] = spval newprops[prop] = new_sp return newprops
python
def propmerge(into, data_from): """ Merge JSON schema requirements into a dictionary """ newprops = copy.deepcopy(into) for prop, propval in six.iteritems(data_from): if prop not in newprops: newprops[prop] = propval continue new_sp = newprops[prop] for subprop, spval in six.iteritems(propval): if subprop not in new_sp: new_sp[subprop] = spval elif subprop == 'enum': new_sp[subprop] = set(spval) & set(new_sp[subprop]) elif subprop == 'type': if spval != new_sp[subprop]: raise TypeError("Type cannot conflict in allOf'") elif subprop in ('minLength', 'minimum'): new_sp[subprop] = (new_sp[subprop] if new_sp[subprop] > spval else spval) elif subprop in ('maxLength', 'maximum'): new_sp[subprop] = (new_sp[subprop] if new_sp[subprop] < spval else spval) elif subprop == 'multipleOf': if new_sp[subprop] % spval == 0: new_sp[subprop] = spval else: raise AttributeError( "Cannot set conflicting multipleOf values") else: new_sp[subprop] = spval newprops[prop] = new_sp return newprops
[ "def", "propmerge", "(", "into", ",", "data_from", ")", ":", "newprops", "=", "copy", ".", "deepcopy", "(", "into", ")", "for", "prop", ",", "propval", "in", "six", ".", "iteritems", "(", "data_from", ")", ":", "if", "prop", "not", "in", "newprops", ...
Merge JSON schema requirements into a dictionary
[ "Merge", "JSON", "schema", "requirements", "into", "a", "dictionary" ]
54c82bfaec9c099c472663742abfc7de373a5e49
https://github.com/cwacek/python-jsonschema-objects/blob/54c82bfaec9c099c472663742abfc7de373a5e49/python_jsonschema_objects/util.py#L68-L106
train
40,967
cwacek/python-jsonschema-objects
python_jsonschema_objects/classbuilder.py
ProtocolBase.as_dict
def as_dict(self): """ Return a dictionary containing the current values of the object. Returns: (dict): The object represented as a dictionary """ out = {} for prop in self: propval = getattr(self, prop) if hasattr(propval, 'for_json'): out[prop] = propval.for_json() elif isinstance(propval, list): out[prop] = [getattr(x, 'for_json', lambda:x)() for x in propval] elif isinstance(propval, (ProtocolBase, LiteralValue)): out[prop] = propval.as_dict() elif propval is not None: out[prop] = propval return out
python
def as_dict(self): """ Return a dictionary containing the current values of the object. Returns: (dict): The object represented as a dictionary """ out = {} for prop in self: propval = getattr(self, prop) if hasattr(propval, 'for_json'): out[prop] = propval.for_json() elif isinstance(propval, list): out[prop] = [getattr(x, 'for_json', lambda:x)() for x in propval] elif isinstance(propval, (ProtocolBase, LiteralValue)): out[prop] = propval.as_dict() elif propval is not None: out[prop] = propval return out
[ "def", "as_dict", "(", "self", ")", ":", "out", "=", "{", "}", "for", "prop", "in", "self", ":", "propval", "=", "getattr", "(", "self", ",", "prop", ")", "if", "hasattr", "(", "propval", ",", "'for_json'", ")", ":", "out", "[", "prop", "]", "=",...
Return a dictionary containing the current values of the object. Returns: (dict): The object represented as a dictionary
[ "Return", "a", "dictionary", "containing", "the", "current", "values", "of", "the", "object", "." ]
54c82bfaec9c099c472663742abfc7de373a5e49
https://github.com/cwacek/python-jsonschema-objects/blob/54c82bfaec9c099c472663742abfc7de373a5e49/python_jsonschema_objects/classbuilder.py#L47-L67
train
40,968
cwacek/python-jsonschema-objects
python_jsonschema_objects/classbuilder.py
ProtocolBase.from_json
def from_json(cls, jsonmsg): """ Create an object directly from a JSON string. Applies general validation after creating the object to check whether all required fields are present. Args: jsonmsg (str): An object encoded as a JSON string Returns: An object of the generated type Raises: ValidationError: if `jsonmsg` does not match the schema `cls` was generated from """ import json msg = json.loads(jsonmsg) obj = cls(**msg) obj.validate() return obj
python
def from_json(cls, jsonmsg): """ Create an object directly from a JSON string. Applies general validation after creating the object to check whether all required fields are present. Args: jsonmsg (str): An object encoded as a JSON string Returns: An object of the generated type Raises: ValidationError: if `jsonmsg` does not match the schema `cls` was generated from """ import json msg = json.loads(jsonmsg) obj = cls(**msg) obj.validate() return obj
[ "def", "from_json", "(", "cls", ",", "jsonmsg", ")", ":", "import", "json", "msg", "=", "json", ".", "loads", "(", "jsonmsg", ")", "obj", "=", "cls", "(", "*", "*", "msg", ")", "obj", ".", "validate", "(", ")", "return", "obj" ]
Create an object directly from a JSON string. Applies general validation after creating the object to check whether all required fields are present. Args: jsonmsg (str): An object encoded as a JSON string Returns: An object of the generated type Raises: ValidationError: if `jsonmsg` does not match the schema `cls` was generated from
[ "Create", "an", "object", "directly", "from", "a", "JSON", "string", "." ]
54c82bfaec9c099c472663742abfc7de373a5e49
https://github.com/cwacek/python-jsonschema-objects/blob/54c82bfaec9c099c472663742abfc7de373a5e49/python_jsonschema_objects/classbuilder.py#L96-L117
train
40,969
cwacek/python-jsonschema-objects
python_jsonschema_objects/classbuilder.py
ProtocolBase.validate
def validate(self): """ Applies all defined validation to the current state of the object, and raises an error if they are not all met. Raises: ValidationError: if validations do not pass """ missing = self.missing_property_names() if len(missing) > 0: raise validators.ValidationError( "'{0}' are required attributes for {1}" .format(missing, self.__class__.__name__)) for prop, val in six.iteritems(self._properties): if val is None: continue if isinstance(val, ProtocolBase): val.validate() elif getattr(val, 'isLiteralClass', None) is True: val.validate() elif isinstance(val, list): for subval in val: subval.validate() else: # This object is of the wrong type, but just try setting it # The property setter will enforce its correctness # and handily coerce its type at the same time setattr(self, prop, val) return True
python
def validate(self): """ Applies all defined validation to the current state of the object, and raises an error if they are not all met. Raises: ValidationError: if validations do not pass """ missing = self.missing_property_names() if len(missing) > 0: raise validators.ValidationError( "'{0}' are required attributes for {1}" .format(missing, self.__class__.__name__)) for prop, val in six.iteritems(self._properties): if val is None: continue if isinstance(val, ProtocolBase): val.validate() elif getattr(val, 'isLiteralClass', None) is True: val.validate() elif isinstance(val, list): for subval in val: subval.validate() else: # This object is of the wrong type, but just try setting it # The property setter will enforce its correctness # and handily coerce its type at the same time setattr(self, prop, val) return True
[ "def", "validate", "(", "self", ")", ":", "missing", "=", "self", ".", "missing_property_names", "(", ")", "if", "len", "(", "missing", ")", ">", "0", ":", "raise", "validators", ".", "ValidationError", "(", "\"'{0}' are required attributes for {1}\"", ".", "f...
Applies all defined validation to the current state of the object, and raises an error if they are not all met. Raises: ValidationError: if validations do not pass
[ "Applies", "all", "defined", "validation", "to", "the", "current", "state", "of", "the", "object", "and", "raises", "an", "error", "if", "they", "are", "not", "all", "met", "." ]
54c82bfaec9c099c472663742abfc7de373a5e49
https://github.com/cwacek/python-jsonschema-objects/blob/54c82bfaec9c099c472663742abfc7de373a5e49/python_jsonschema_objects/classbuilder.py#L258-L291
train
40,970
cwacek/python-jsonschema-objects
python_jsonschema_objects/classbuilder.py
ProtocolBase.missing_property_names
def missing_property_names(self): """ Returns a list of properties which are required and missing. Properties are excluded from this list if they are allowed to be null. :return: list of missing properties. """ propname = lambda x: self.__prop_names__[x] missing = [] for x in self.__required__: # Allow the null type propinfo = self.propinfo(propname(x)) null_type = False if 'type' in propinfo: type_info = propinfo['type'] null_type = (type_info == 'null' or isinstance(type_info, (list, tuple)) and 'null' in type_info) elif 'oneOf' in propinfo: for o in propinfo['oneOf']: type_info = o.get('type') if type_info and type_info == 'null' \ or isinstance(type_info, (list, tuple)) \ and 'null' in type_info: null_type = True break if (propname(x) not in self._properties and null_type) or \ (self._properties[propname(x)] is None and not null_type): missing.append(x) return missing
python
def missing_property_names(self): """ Returns a list of properties which are required and missing. Properties are excluded from this list if they are allowed to be null. :return: list of missing properties. """ propname = lambda x: self.__prop_names__[x] missing = [] for x in self.__required__: # Allow the null type propinfo = self.propinfo(propname(x)) null_type = False if 'type' in propinfo: type_info = propinfo['type'] null_type = (type_info == 'null' or isinstance(type_info, (list, tuple)) and 'null' in type_info) elif 'oneOf' in propinfo: for o in propinfo['oneOf']: type_info = o.get('type') if type_info and type_info == 'null' \ or isinstance(type_info, (list, tuple)) \ and 'null' in type_info: null_type = True break if (propname(x) not in self._properties and null_type) or \ (self._properties[propname(x)] is None and not null_type): missing.append(x) return missing
[ "def", "missing_property_names", "(", "self", ")", ":", "propname", "=", "lambda", "x", ":", "self", ".", "__prop_names__", "[", "x", "]", "missing", "=", "[", "]", "for", "x", "in", "self", ".", "__required__", ":", "# Allow the null type", "propinfo", "=...
Returns a list of properties which are required and missing. Properties are excluded from this list if they are allowed to be null. :return: list of missing properties.
[ "Returns", "a", "list", "of", "properties", "which", "are", "required", "and", "missing", "." ]
54c82bfaec9c099c472663742abfc7de373a5e49
https://github.com/cwacek/python-jsonschema-objects/blob/54c82bfaec9c099c472663742abfc7de373a5e49/python_jsonschema_objects/classbuilder.py#L293-L327
train
40,971
cwacek/python-jsonschema-objects
python_jsonschema_objects/classbuilder.py
ClassBuilder.construct
def construct(self, uri, *args, **kw): """ Wrapper to debug things """ logger.debug(util.lazy_format("Constructing {0}", uri)) if ('override' not in kw or kw['override'] is False) \ and uri in self.resolved: logger.debug(util.lazy_format("Using existing {0}", uri)) return self.resolved[uri] else: ret = self._construct(uri, *args, **kw) logger.debug(util.lazy_format("Constructed {0}", ret)) return ret
python
def construct(self, uri, *args, **kw): """ Wrapper to debug things """ logger.debug(util.lazy_format("Constructing {0}", uri)) if ('override' not in kw or kw['override'] is False) \ and uri in self.resolved: logger.debug(util.lazy_format("Using existing {0}", uri)) return self.resolved[uri] else: ret = self._construct(uri, *args, **kw) logger.debug(util.lazy_format("Constructed {0}", ret)) return ret
[ "def", "construct", "(", "self", ",", "uri", ",", "*", "args", ",", "*", "*", "kw", ")", ":", "logger", ".", "debug", "(", "util", ".", "lazy_format", "(", "\"Constructing {0}\"", ",", "uri", ")", ")", "if", "(", "'override'", "not", "in", "kw", "o...
Wrapper to debug things
[ "Wrapper", "to", "debug", "things" ]
54c82bfaec9c099c472663742abfc7de373a5e49
https://github.com/cwacek/python-jsonschema-objects/blob/54c82bfaec9c099c472663742abfc7de373a5e49/python_jsonschema_objects/classbuilder.py#L413-L424
train
40,972
cwacek/python-jsonschema-objects
python_jsonschema_objects/__init__.py
ObjectBuilder.build_classes
def build_classes(self,strict=False, named_only=False, standardize_names=True): """ Build all of the classes named in the JSONSchema. Class names will be transformed using inflection by default, so names with spaces in the schema will be camelcased, while names without spaces will have internal capitalization dropped. Thus "Home Address" becomes "HomeAddress", while "HomeAddress" becomes "Homeaddress" To disable this behavior, pass standardize_names=False, but be aware that accessing names with spaces from the namespace can be problematic. Args: strict: (bool) use this to validate required fields while creating the class named_only: (bool) If true, only properties with an actual title attribute will be included in the resulting namespace (although all will be generated). standardize_names: (bool) If true (the default), class names will be tranformed by camel casing Returns: A namespace containing all the generated classes """ kw = {"strict": strict} builder = classbuilder.ClassBuilder(self.resolver) for nm, defn in iteritems(self.schema.get('definitions', {})): uri = python_jsonschema_objects.util.resolve_ref_uri( self.resolver.resolution_scope, "#/definitions/" + nm) builder.construct(uri, defn, **kw) if standardize_names: name_transform = lambda t: inflection.camelize(inflection.parameterize(six.text_type(t), '_')) else: name_transform = lambda t: t nm = self.schema['title'] if 'title' in self.schema else self.schema['id'] nm = inflection.parameterize(six.text_type(nm), '_') builder.construct(nm, self.schema,**kw) self._resolved = builder.resolved classes = {} for uri, klass in six.iteritems(builder.resolved): title = getattr(klass, '__title__', None) if title is not None: classes[name_transform(title)] = klass elif not named_only: classes[name_transform(uri.split('/')[-1])] = klass return python_jsonschema_objects.util.Namespace.from_mapping(classes)
python
def build_classes(self,strict=False, named_only=False, standardize_names=True): """ Build all of the classes named in the JSONSchema. Class names will be transformed using inflection by default, so names with spaces in the schema will be camelcased, while names without spaces will have internal capitalization dropped. Thus "Home Address" becomes "HomeAddress", while "HomeAddress" becomes "Homeaddress" To disable this behavior, pass standardize_names=False, but be aware that accessing names with spaces from the namespace can be problematic. Args: strict: (bool) use this to validate required fields while creating the class named_only: (bool) If true, only properties with an actual title attribute will be included in the resulting namespace (although all will be generated). standardize_names: (bool) If true (the default), class names will be tranformed by camel casing Returns: A namespace containing all the generated classes """ kw = {"strict": strict} builder = classbuilder.ClassBuilder(self.resolver) for nm, defn in iteritems(self.schema.get('definitions', {})): uri = python_jsonschema_objects.util.resolve_ref_uri( self.resolver.resolution_scope, "#/definitions/" + nm) builder.construct(uri, defn, **kw) if standardize_names: name_transform = lambda t: inflection.camelize(inflection.parameterize(six.text_type(t), '_')) else: name_transform = lambda t: t nm = self.schema['title'] if 'title' in self.schema else self.schema['id'] nm = inflection.parameterize(six.text_type(nm), '_') builder.construct(nm, self.schema,**kw) self._resolved = builder.resolved classes = {} for uri, klass in six.iteritems(builder.resolved): title = getattr(klass, '__title__', None) if title is not None: classes[name_transform(title)] = klass elif not named_only: classes[name_transform(uri.split('/')[-1])] = klass return python_jsonschema_objects.util.Namespace.from_mapping(classes)
[ "def", "build_classes", "(", "self", ",", "strict", "=", "False", ",", "named_only", "=", "False", ",", "standardize_names", "=", "True", ")", ":", "kw", "=", "{", "\"strict\"", ":", "strict", "}", "builder", "=", "classbuilder", ".", "ClassBuilder", "(", ...
Build all of the classes named in the JSONSchema. Class names will be transformed using inflection by default, so names with spaces in the schema will be camelcased, while names without spaces will have internal capitalization dropped. Thus "Home Address" becomes "HomeAddress", while "HomeAddress" becomes "Homeaddress" To disable this behavior, pass standardize_names=False, but be aware that accessing names with spaces from the namespace can be problematic. Args: strict: (bool) use this to validate required fields while creating the class named_only: (bool) If true, only properties with an actual title attribute will be included in the resulting namespace (although all will be generated). standardize_names: (bool) If true (the default), class names will be tranformed by camel casing Returns: A namespace containing all the generated classes
[ "Build", "all", "of", "the", "classes", "named", "in", "the", "JSONSchema", "." ]
54c82bfaec9c099c472663742abfc7de373a5e49
https://github.com/cwacek/python-jsonschema-objects/blob/54c82bfaec9c099c472663742abfc7de373a5e49/python_jsonschema_objects/__init__.py#L95-L145
train
40,973
pytroll/python-geotiepoints
geotiepoints/basic_interpolator.py
BasicSatelliteInterpolator.interpolate
def interpolate(self): """Do the interpolation and return resulting longitudes and latitudes. """ self.latitude = self._interp(self.lat_tiepoint) self.longitude = self._interp(self.lon_tiepoint) return self.latitude, self.longitude
python
def interpolate(self): """Do the interpolation and return resulting longitudes and latitudes. """ self.latitude = self._interp(self.lat_tiepoint) self.longitude = self._interp(self.lon_tiepoint) return self.latitude, self.longitude
[ "def", "interpolate", "(", "self", ")", ":", "self", ".", "latitude", "=", "self", ".", "_interp", "(", "self", ".", "lat_tiepoint", ")", "self", ".", "longitude", "=", "self", ".", "_interp", "(", "self", ".", "lon_tiepoint", ")", "return", "self", "....
Do the interpolation and return resulting longitudes and latitudes.
[ "Do", "the", "interpolation", "and", "return", "resulting", "longitudes", "and", "latitudes", "." ]
7c5cc8a887f8534cc2839c716c2c560aeaf77659
https://github.com/pytroll/python-geotiepoints/blob/7c5cc8a887f8534cc2839c716c2c560aeaf77659/geotiepoints/basic_interpolator.py#L82-L88
train
40,974
EliotBerriot/lifter
lifter/caches.py
Cache.get
def get(self, key, default=None, reraise=False): """ Get the given key from the cache, if present. A default value can be provided in case the requested key is not present, otherwise, None will be returned. :param key: the key to query :type key: str :param default: the value to return if the key does not exist in cache :param reraise: wether an exception should be thrown if now value is found, defaults to False. :type key: bool Example usage: .. code-block:: python cache.set('my_key', 'my_value') cache.get('my_key') >>> 'my_value' cache.get('not_present', 'default_value') >>> 'default_value' cache.get('not_present', reraise=True) >>> raise lifter.exceptions.NotInCache """ if not self.enabled: if reraise: raise exceptions.DisabledCache() return default try: return self._get(key) except exceptions.NotInCache: if reraise: raise return default
python
def get(self, key, default=None, reraise=False): """ Get the given key from the cache, if present. A default value can be provided in case the requested key is not present, otherwise, None will be returned. :param key: the key to query :type key: str :param default: the value to return if the key does not exist in cache :param reraise: wether an exception should be thrown if now value is found, defaults to False. :type key: bool Example usage: .. code-block:: python cache.set('my_key', 'my_value') cache.get('my_key') >>> 'my_value' cache.get('not_present', 'default_value') >>> 'default_value' cache.get('not_present', reraise=True) >>> raise lifter.exceptions.NotInCache """ if not self.enabled: if reraise: raise exceptions.DisabledCache() return default try: return self._get(key) except exceptions.NotInCache: if reraise: raise return default
[ "def", "get", "(", "self", ",", "key", ",", "default", "=", "None", ",", "reraise", "=", "False", ")", ":", "if", "not", "self", ".", "enabled", ":", "if", "reraise", ":", "raise", "exceptions", ".", "DisabledCache", "(", ")", "return", "default", "t...
Get the given key from the cache, if present. A default value can be provided in case the requested key is not present, otherwise, None will be returned. :param key: the key to query :type key: str :param default: the value to return if the key does not exist in cache :param reraise: wether an exception should be thrown if now value is found, defaults to False. :type key: bool Example usage: .. code-block:: python cache.set('my_key', 'my_value') cache.get('my_key') >>> 'my_value' cache.get('not_present', 'default_value') >>> 'default_value' cache.get('not_present', reraise=True) >>> raise lifter.exceptions.NotInCache
[ "Get", "the", "given", "key", "from", "the", "cache", "if", "present", ".", "A", "default", "value", "can", "be", "provided", "in", "case", "the", "requested", "key", "is", "not", "present", "otherwise", "None", "will", "be", "returned", "." ]
9b4394b476cddd952b2af9540affc03f2977163d
https://github.com/EliotBerriot/lifter/blob/9b4394b476cddd952b2af9540affc03f2977163d/lifter/caches.py#L30-L68
train
40,975
EliotBerriot/lifter
lifter/utils.py
resolve_attr
def resolve_attr(obj, name): """A custom attrgetter that operates both on dictionaries and objects""" # TODO: setup some hinting, so we can go directly to the correct # Maybe it's a dict ? Let's try dict lookup, it's the fastest try: return obj[name] except TypeError: pass except KeyError: raise exceptions.MissingField('Dict {0} has no attribute or key "{1}"'.format(obj, name)) # Okay, it's not a dict, what if we try to access the value as for a regular object attribute? try: # Slight hack for better speed, since accessing dict is fast return obj.__dict__[name] except (KeyError, AttributeError): pass try: # Lookup using regular attribute return getattr(obj, name) except AttributeError: pass # Last possible choice, it's an iterable if isinstance(obj, collections.Iterable): return IterableAttr(obj, name) raise exceptions.MissingField('Object {0} has no attribute or key "{1}"'.format(obj, name))
python
def resolve_attr(obj, name): """A custom attrgetter that operates both on dictionaries and objects""" # TODO: setup some hinting, so we can go directly to the correct # Maybe it's a dict ? Let's try dict lookup, it's the fastest try: return obj[name] except TypeError: pass except KeyError: raise exceptions.MissingField('Dict {0} has no attribute or key "{1}"'.format(obj, name)) # Okay, it's not a dict, what if we try to access the value as for a regular object attribute? try: # Slight hack for better speed, since accessing dict is fast return obj.__dict__[name] except (KeyError, AttributeError): pass try: # Lookup using regular attribute return getattr(obj, name) except AttributeError: pass # Last possible choice, it's an iterable if isinstance(obj, collections.Iterable): return IterableAttr(obj, name) raise exceptions.MissingField('Object {0} has no attribute or key "{1}"'.format(obj, name))
[ "def", "resolve_attr", "(", "obj", ",", "name", ")", ":", "# TODO: setup some hinting, so we can go directly to the correct", "# Maybe it's a dict ? Let's try dict lookup, it's the fastest", "try", ":", "return", "obj", "[", "name", "]", "except", "TypeError", ":", "pass", ...
A custom attrgetter that operates both on dictionaries and objects
[ "A", "custom", "attrgetter", "that", "operates", "both", "on", "dictionaries", "and", "objects" ]
9b4394b476cddd952b2af9540affc03f2977163d
https://github.com/EliotBerriot/lifter/blob/9b4394b476cddd952b2af9540affc03f2977163d/lifter/utils.py#L56-L84
train
40,976
EliotBerriot/lifter
lifter/query.py
QuerySet.build_filter_from_kwargs
def build_filter_from_kwargs(self, **kwargs): """Convert django-s like lookup to SQLAlchemy ones""" query = None for path_to_convert, value in kwargs.items(): path_parts = path_to_convert.split('__') lookup_class = None try: # We check if the path ends with something such as __gte, __lte... lookup_class = lookups.registry[path_parts[-1]] path_to_convert = '__'.join(path_parts[:-1]) except KeyError: pass path = lookup_to_path(path_to_convert) if lookup_class: q = QueryNode(path, lookup=lookup_class(value)) else: q = path == value if query: query = query & q else: query = q return query
python
def build_filter_from_kwargs(self, **kwargs): """Convert django-s like lookup to SQLAlchemy ones""" query = None for path_to_convert, value in kwargs.items(): path_parts = path_to_convert.split('__') lookup_class = None try: # We check if the path ends with something such as __gte, __lte... lookup_class = lookups.registry[path_parts[-1]] path_to_convert = '__'.join(path_parts[:-1]) except KeyError: pass path = lookup_to_path(path_to_convert) if lookup_class: q = QueryNode(path, lookup=lookup_class(value)) else: q = path == value if query: query = query & q else: query = q return query
[ "def", "build_filter_from_kwargs", "(", "self", ",", "*", "*", "kwargs", ")", ":", "query", "=", "None", "for", "path_to_convert", ",", "value", "in", "kwargs", ".", "items", "(", ")", ":", "path_parts", "=", "path_to_convert", ".", "split", "(", "'__'", ...
Convert django-s like lookup to SQLAlchemy ones
[ "Convert", "django", "-", "s", "like", "lookup", "to", "SQLAlchemy", "ones" ]
9b4394b476cddd952b2af9540affc03f2977163d
https://github.com/EliotBerriot/lifter/blob/9b4394b476cddd952b2af9540affc03f2977163d/lifter/query.py#L345-L369
train
40,977
pytroll/python-geotiepoints
geotiepoints/__init__.py
get_scene_splits
def get_scene_splits(nlines_swath, nlines_scan, n_cpus): """Calculate the line numbers where the swath will be split in smaller granules for parallel processing""" nscans = nlines_swath // nlines_scan if nscans < n_cpus: nscans_subscene = 1 else: nscans_subscene = nscans // n_cpus nlines_subscene = nscans_subscene * nlines_scan return range(nlines_subscene, nlines_swath, nlines_subscene)
python
def get_scene_splits(nlines_swath, nlines_scan, n_cpus): """Calculate the line numbers where the swath will be split in smaller granules for parallel processing""" nscans = nlines_swath // nlines_scan if nscans < n_cpus: nscans_subscene = 1 else: nscans_subscene = nscans // n_cpus nlines_subscene = nscans_subscene * nlines_scan return range(nlines_subscene, nlines_swath, nlines_subscene)
[ "def", "get_scene_splits", "(", "nlines_swath", ",", "nlines_scan", ",", "n_cpus", ")", ":", "nscans", "=", "nlines_swath", "//", "nlines_scan", "if", "nscans", "<", "n_cpus", ":", "nscans_subscene", "=", "1", "else", ":", "nscans_subscene", "=", "nscans", "//...
Calculate the line numbers where the swath will be split in smaller granules for parallel processing
[ "Calculate", "the", "line", "numbers", "where", "the", "swath", "will", "be", "split", "in", "smaller", "granules", "for", "parallel", "processing" ]
7c5cc8a887f8534cc2839c716c2c560aeaf77659
https://github.com/pytroll/python-geotiepoints/blob/7c5cc8a887f8534cc2839c716c2c560aeaf77659/geotiepoints/__init__.py#L40-L51
train
40,978
pytroll/python-geotiepoints
geotiepoints/__init__.py
metop20kmto1km
def metop20kmto1km(lons20km, lats20km): """Getting 1km geolocation for metop avhrr from 20km tiepoints. """ cols20km = np.array([0] + list(range(4, 2048, 20)) + [2047]) cols1km = np.arange(2048) lines = lons20km.shape[0] rows20km = np.arange(lines) rows1km = np.arange(lines) along_track_order = 1 cross_track_order = 3 satint = SatelliteInterpolator((lons20km, lats20km), (rows20km, cols20km), (rows1km, cols1km), along_track_order, cross_track_order) return satint.interpolate()
python
def metop20kmto1km(lons20km, lats20km): """Getting 1km geolocation for metop avhrr from 20km tiepoints. """ cols20km = np.array([0] + list(range(4, 2048, 20)) + [2047]) cols1km = np.arange(2048) lines = lons20km.shape[0] rows20km = np.arange(lines) rows1km = np.arange(lines) along_track_order = 1 cross_track_order = 3 satint = SatelliteInterpolator((lons20km, lats20km), (rows20km, cols20km), (rows1km, cols1km), along_track_order, cross_track_order) return satint.interpolate()
[ "def", "metop20kmto1km", "(", "lons20km", ",", "lats20km", ")", ":", "cols20km", "=", "np", ".", "array", "(", "[", "0", "]", "+", "list", "(", "range", "(", "4", ",", "2048", ",", "20", ")", ")", "+", "[", "2047", "]", ")", "cols1km", "=", "np...
Getting 1km geolocation for metop avhrr from 20km tiepoints.
[ "Getting", "1km", "geolocation", "for", "metop", "avhrr", "from", "20km", "tiepoints", "." ]
7c5cc8a887f8534cc2839c716c2c560aeaf77659
https://github.com/pytroll/python-geotiepoints/blob/7c5cc8a887f8534cc2839c716c2c560aeaf77659/geotiepoints/__init__.py#L54-L71
train
40,979
pytroll/python-geotiepoints
geotiepoints/__init__.py
modis5kmto1km
def modis5kmto1km(lons5km, lats5km): """Getting 1km geolocation for modis from 5km tiepoints. http://www.icare.univ-lille1.fr/tutorials/MODIS_geolocation """ cols5km = np.arange(2, 1354, 5) / 5.0 cols1km = np.arange(1354) / 5.0 lines = lons5km.shape[0] * 5 rows5km = np.arange(2, lines, 5) / 5.0 rows1km = np.arange(lines) / 5.0 along_track_order = 1 cross_track_order = 3 satint = SatelliteInterpolator((lons5km, lats5km), (rows5km, cols5km), (rows1km, cols1km), along_track_order, cross_track_order, chunk_size=10) satint.fill_borders("y", "x") lons1km, lats1km = satint.interpolate() return lons1km, lats1km
python
def modis5kmto1km(lons5km, lats5km): """Getting 1km geolocation for modis from 5km tiepoints. http://www.icare.univ-lille1.fr/tutorials/MODIS_geolocation """ cols5km = np.arange(2, 1354, 5) / 5.0 cols1km = np.arange(1354) / 5.0 lines = lons5km.shape[0] * 5 rows5km = np.arange(2, lines, 5) / 5.0 rows1km = np.arange(lines) / 5.0 along_track_order = 1 cross_track_order = 3 satint = SatelliteInterpolator((lons5km, lats5km), (rows5km, cols5km), (rows1km, cols1km), along_track_order, cross_track_order, chunk_size=10) satint.fill_borders("y", "x") lons1km, lats1km = satint.interpolate() return lons1km, lats1km
[ "def", "modis5kmto1km", "(", "lons5km", ",", "lats5km", ")", ":", "cols5km", "=", "np", ".", "arange", "(", "2", ",", "1354", ",", "5", ")", "/", "5.0", "cols1km", "=", "np", ".", "arange", "(", "1354", ")", "/", "5.0", "lines", "=", "lons5km", "...
Getting 1km geolocation for modis from 5km tiepoints. http://www.icare.univ-lille1.fr/tutorials/MODIS_geolocation
[ "Getting", "1km", "geolocation", "for", "modis", "from", "5km", "tiepoints", "." ]
7c5cc8a887f8534cc2839c716c2c560aeaf77659
https://github.com/pytroll/python-geotiepoints/blob/7c5cc8a887f8534cc2839c716c2c560aeaf77659/geotiepoints/__init__.py#L74-L96
train
40,980
pytroll/python-geotiepoints
geotiepoints/__init__.py
_multi
def _multi(fun, lons, lats, chunk_size, cores=1): """Work on multiple cores. """ pool = Pool(processes=cores) splits = get_scene_splits(lons.shape[0], chunk_size, cores) lons_parts = np.vsplit(lons, splits) lats_parts = np.vsplit(lats, splits) results = [pool.apply_async(fun, (lons_parts[i], lats_parts[i])) for i in range(len(lons_parts))] pool.close() pool.join() lons, lats = zip(*(res.get() for res in results)) return np.vstack(lons), np.vstack(lats)
python
def _multi(fun, lons, lats, chunk_size, cores=1): """Work on multiple cores. """ pool = Pool(processes=cores) splits = get_scene_splits(lons.shape[0], chunk_size, cores) lons_parts = np.vsplit(lons, splits) lats_parts = np.vsplit(lats, splits) results = [pool.apply_async(fun, (lons_parts[i], lats_parts[i])) for i in range(len(lons_parts))] pool.close() pool.join() lons, lats = zip(*(res.get() for res in results)) return np.vstack(lons), np.vstack(lats)
[ "def", "_multi", "(", "fun", ",", "lons", ",", "lats", ",", "chunk_size", ",", "cores", "=", "1", ")", ":", "pool", "=", "Pool", "(", "processes", "=", "cores", ")", "splits", "=", "get_scene_splits", "(", "lons", ".", "shape", "[", "0", "]", ",", ...
Work on multiple cores.
[ "Work", "on", "multiple", "cores", "." ]
7c5cc8a887f8534cc2839c716c2c560aeaf77659
https://github.com/pytroll/python-geotiepoints/blob/7c5cc8a887f8534cc2839c716c2c560aeaf77659/geotiepoints/__init__.py#L99-L119
train
40,981
pytroll/python-geotiepoints
geotiepoints/__init__.py
modis1kmto500m
def modis1kmto500m(lons1km, lats1km, cores=1): """Getting 500m geolocation for modis from 1km tiepoints. http://www.icare.univ-lille1.fr/tutorials/MODIS_geolocation """ if cores > 1: return _multi(modis1kmto500m, lons1km, lats1km, 10, cores) cols1km = np.arange(1354) cols500m = np.arange(1354 * 2) / 2.0 lines = lons1km.shape[0] rows1km = np.arange(lines) rows500m = (np.arange(lines * 2) - 0.5) / 2. along_track_order = 1 cross_track_order = 3 satint = SatelliteInterpolator((lons1km, lats1km), (rows1km, cols1km), (rows500m, cols500m), along_track_order, cross_track_order, chunk_size=20) satint.fill_borders("y", "x") lons500m, lats500m = satint.interpolate() return lons500m, lats500m
python
def modis1kmto500m(lons1km, lats1km, cores=1): """Getting 500m geolocation for modis from 1km tiepoints. http://www.icare.univ-lille1.fr/tutorials/MODIS_geolocation """ if cores > 1: return _multi(modis1kmto500m, lons1km, lats1km, 10, cores) cols1km = np.arange(1354) cols500m = np.arange(1354 * 2) / 2.0 lines = lons1km.shape[0] rows1km = np.arange(lines) rows500m = (np.arange(lines * 2) - 0.5) / 2. along_track_order = 1 cross_track_order = 3 satint = SatelliteInterpolator((lons1km, lats1km), (rows1km, cols1km), (rows500m, cols500m), along_track_order, cross_track_order, chunk_size=20) satint.fill_borders("y", "x") lons500m, lats500m = satint.interpolate() return lons500m, lats500m
[ "def", "modis1kmto500m", "(", "lons1km", ",", "lats1km", ",", "cores", "=", "1", ")", ":", "if", "cores", ">", "1", ":", "return", "_multi", "(", "modis1kmto500m", ",", "lons1km", ",", "lats1km", ",", "10", ",", "cores", ")", "cols1km", "=", "np", "....
Getting 500m geolocation for modis from 1km tiepoints. http://www.icare.univ-lille1.fr/tutorials/MODIS_geolocation
[ "Getting", "500m", "geolocation", "for", "modis", "from", "1km", "tiepoints", "." ]
7c5cc8a887f8534cc2839c716c2c560aeaf77659
https://github.com/pytroll/python-geotiepoints/blob/7c5cc8a887f8534cc2839c716c2c560aeaf77659/geotiepoints/__init__.py#L122-L147
train
40,982
pytroll/python-geotiepoints
geotiepoints/__init__.py
modis1kmto250m
def modis1kmto250m(lons1km, lats1km, cores=1): """Getting 250m geolocation for modis from 1km tiepoints. http://www.icare.univ-lille1.fr/tutorials/MODIS_geolocation """ if cores > 1: return _multi(modis1kmto250m, lons1km, lats1km, 10, cores) cols1km = np.arange(1354) cols250m = np.arange(1354 * 4) / 4.0 along_track_order = 1 cross_track_order = 3 lines = lons1km.shape[0] rows1km = np.arange(lines) rows250m = (np.arange(lines * 4) - 1.5) / 4.0 satint = SatelliteInterpolator((lons1km, lats1km), (rows1km, cols1km), (rows250m, cols250m), along_track_order, cross_track_order, chunk_size=40) satint.fill_borders("y", "x") lons250m, lats250m = satint.interpolate() return lons250m, lats250m
python
def modis1kmto250m(lons1km, lats1km, cores=1): """Getting 250m geolocation for modis from 1km tiepoints. http://www.icare.univ-lille1.fr/tutorials/MODIS_geolocation """ if cores > 1: return _multi(modis1kmto250m, lons1km, lats1km, 10, cores) cols1km = np.arange(1354) cols250m = np.arange(1354 * 4) / 4.0 along_track_order = 1 cross_track_order = 3 lines = lons1km.shape[0] rows1km = np.arange(lines) rows250m = (np.arange(lines * 4) - 1.5) / 4.0 satint = SatelliteInterpolator((lons1km, lats1km), (rows1km, cols1km), (rows250m, cols250m), along_track_order, cross_track_order, chunk_size=40) satint.fill_borders("y", "x") lons250m, lats250m = satint.interpolate() return lons250m, lats250m
[ "def", "modis1kmto250m", "(", "lons1km", ",", "lats1km", ",", "cores", "=", "1", ")", ":", "if", "cores", ">", "1", ":", "return", "_multi", "(", "modis1kmto250m", ",", "lons1km", ",", "lats1km", ",", "10", ",", "cores", ")", "cols1km", "=", "np", "....
Getting 250m geolocation for modis from 1km tiepoints. http://www.icare.univ-lille1.fr/tutorials/MODIS_geolocation
[ "Getting", "250m", "geolocation", "for", "modis", "from", "1km", "tiepoints", "." ]
7c5cc8a887f8534cc2839c716c2c560aeaf77659
https://github.com/pytroll/python-geotiepoints/blob/7c5cc8a887f8534cc2839c716c2c560aeaf77659/geotiepoints/__init__.py#L150-L177
train
40,983
pytroll/python-geotiepoints
geotiepoints/interpolator.py
generic_modis5kmto1km
def generic_modis5kmto1km(*data5km): """Getting 1km data for modis from 5km tiepoints. """ cols5km = np.arange(2, 1354, 5) cols1km = np.arange(1354) lines = data5km[0].shape[0] * 5 rows5km = np.arange(2, lines, 5) rows1km = np.arange(lines) along_track_order = 1 cross_track_order = 3 satint = Interpolator(list(data5km), (rows5km, cols5km), (rows1km, cols1km), along_track_order, cross_track_order, chunk_size=10) satint.fill_borders("y", "x") return satint.interpolate()
python
def generic_modis5kmto1km(*data5km): """Getting 1km data for modis from 5km tiepoints. """ cols5km = np.arange(2, 1354, 5) cols1km = np.arange(1354) lines = data5km[0].shape[0] * 5 rows5km = np.arange(2, lines, 5) rows1km = np.arange(lines) along_track_order = 1 cross_track_order = 3 satint = Interpolator(list(data5km), (rows5km, cols5km), (rows1km, cols1km), along_track_order, cross_track_order, chunk_size=10) satint.fill_borders("y", "x") return satint.interpolate()
[ "def", "generic_modis5kmto1km", "(", "*", "data5km", ")", ":", "cols5km", "=", "np", ".", "arange", "(", "2", ",", "1354", ",", "5", ")", "cols1km", "=", "np", ".", "arange", "(", "1354", ")", "lines", "=", "data5km", "[", "0", "]", ".", "shape", ...
Getting 1km data for modis from 5km tiepoints.
[ "Getting", "1km", "data", "for", "modis", "from", "5km", "tiepoints", "." ]
7c5cc8a887f8534cc2839c716c2c560aeaf77659
https://github.com/pytroll/python-geotiepoints/blob/7c5cc8a887f8534cc2839c716c2c560aeaf77659/geotiepoints/interpolator.py#L29-L48
train
40,984
pytroll/python-geotiepoints
geotiepoints/interpolator.py
Interpolator.fill_borders
def fill_borders(self, *args): """Extrapolate tiepoint lons and lats to fill in the border of the chunks. """ to_run = [] cases = {"y": self._fill_row_borders, "x": self._fill_col_borders} for dim in args: try: to_run.append(cases[dim]) except KeyError: raise NameError("Unrecognized dimension: " + str(dim)) for fun in to_run: fun()
python
def fill_borders(self, *args): """Extrapolate tiepoint lons and lats to fill in the border of the chunks. """ to_run = [] cases = {"y": self._fill_row_borders, "x": self._fill_col_borders} for dim in args: try: to_run.append(cases[dim]) except KeyError: raise NameError("Unrecognized dimension: " + str(dim)) for fun in to_run: fun()
[ "def", "fill_borders", "(", "self", ",", "*", "args", ")", ":", "to_run", "=", "[", "]", "cases", "=", "{", "\"y\"", ":", "self", ".", "_fill_row_borders", ",", "\"x\"", ":", "self", ".", "_fill_col_borders", "}", "for", "dim", "in", "args", ":", "tr...
Extrapolate tiepoint lons and lats to fill in the border of the chunks.
[ "Extrapolate", "tiepoint", "lons", "and", "lats", "to", "fill", "in", "the", "border", "of", "the", "chunks", "." ]
7c5cc8a887f8534cc2839c716c2c560aeaf77659
https://github.com/pytroll/python-geotiepoints/blob/7c5cc8a887f8534cc2839c716c2c560aeaf77659/geotiepoints/interpolator.py#L113-L128
train
40,985
pytroll/python-geotiepoints
geotiepoints/interpolator.py
Interpolator._extrapolate_cols
def _extrapolate_cols(self, data, first=True, last=True): """Extrapolate the column of data, to get the first and last together with the data. """ if first: pos = self.col_indices[:2] first_column = _linear_extrapolate(pos, (data[:, 0], data[:, 1]), self.hcol_indices[0]) if last: pos = self.col_indices[-2:] last_column = _linear_extrapolate(pos, (data[:, -2], data[:, -1]), self.hcol_indices[-1]) if first and last: return np.hstack((np.expand_dims(first_column, 1), data, np.expand_dims(last_column, 1))) elif first: return np.hstack((np.expand_dims(first_column, 1), data)) elif last: return np.hstack((data, np.expand_dims(last_column, 1))) else: return data
python
def _extrapolate_cols(self, data, first=True, last=True): """Extrapolate the column of data, to get the first and last together with the data. """ if first: pos = self.col_indices[:2] first_column = _linear_extrapolate(pos, (data[:, 0], data[:, 1]), self.hcol_indices[0]) if last: pos = self.col_indices[-2:] last_column = _linear_extrapolate(pos, (data[:, -2], data[:, -1]), self.hcol_indices[-1]) if first and last: return np.hstack((np.expand_dims(first_column, 1), data, np.expand_dims(last_column, 1))) elif first: return np.hstack((np.expand_dims(first_column, 1), data)) elif last: return np.hstack((data, np.expand_dims(last_column, 1))) else: return data
[ "def", "_extrapolate_cols", "(", "self", ",", "data", ",", "first", "=", "True", ",", "last", "=", "True", ")", ":", "if", "first", ":", "pos", "=", "self", ".", "col_indices", "[", ":", "2", "]", "first_column", "=", "_linear_extrapolate", "(", "pos",...
Extrapolate the column of data, to get the first and last together with the data.
[ "Extrapolate", "the", "column", "of", "data", "to", "get", "the", "first", "and", "last", "together", "with", "the", "data", "." ]
7c5cc8a887f8534cc2839c716c2c560aeaf77659
https://github.com/pytroll/python-geotiepoints/blob/7c5cc8a887f8534cc2839c716c2c560aeaf77659/geotiepoints/interpolator.py#L130-L158
train
40,986
pytroll/python-geotiepoints
geotiepoints/interpolator.py
Interpolator._fill_col_borders
def _fill_col_borders(self): """Add the first and last column to the data by extrapolation. """ first = True last = True if self.col_indices[0] == self.hcol_indices[0]: first = False if self.col_indices[-1] == self.hcol_indices[-1]: last = False for num, data in enumerate(self.tie_data): self.tie_data[num] = self._extrapolate_cols(data, first, last) if first and last: self.col_indices = np.concatenate((np.array([self.hcol_indices[0]]), self.col_indices, np.array([self.hcol_indices[-1]]))) elif first: self.col_indices = np.concatenate((np.array([self.hcol_indices[0]]), self.col_indices)) elif last: self.col_indices = np.concatenate((self.col_indices, np.array([self.hcol_indices[-1]])))
python
def _fill_col_borders(self): """Add the first and last column to the data by extrapolation. """ first = True last = True if self.col_indices[0] == self.hcol_indices[0]: first = False if self.col_indices[-1] == self.hcol_indices[-1]: last = False for num, data in enumerate(self.tie_data): self.tie_data[num] = self._extrapolate_cols(data, first, last) if first and last: self.col_indices = np.concatenate((np.array([self.hcol_indices[0]]), self.col_indices, np.array([self.hcol_indices[-1]]))) elif first: self.col_indices = np.concatenate((np.array([self.hcol_indices[0]]), self.col_indices)) elif last: self.col_indices = np.concatenate((self.col_indices, np.array([self.hcol_indices[-1]])))
[ "def", "_fill_col_borders", "(", "self", ")", ":", "first", "=", "True", "last", "=", "True", "if", "self", ".", "col_indices", "[", "0", "]", "==", "self", ".", "hcol_indices", "[", "0", "]", ":", "first", "=", "False", "if", "self", ".", "col_indic...
Add the first and last column to the data by extrapolation.
[ "Add", "the", "first", "and", "last", "column", "to", "the", "data", "by", "extrapolation", "." ]
7c5cc8a887f8534cc2839c716c2c560aeaf77659
https://github.com/pytroll/python-geotiepoints/blob/7c5cc8a887f8534cc2839c716c2c560aeaf77659/geotiepoints/interpolator.py#L160-L182
train
40,987
pytroll/python-geotiepoints
geotiepoints/interpolator.py
Interpolator._extrapolate_rows
def _extrapolate_rows(self, data, row_indices, first_index, last_index): """Extrapolate the rows of data, to get the first and last together with the data. """ pos = row_indices[:2] first_row = _linear_extrapolate(pos, (data[0, :], data[1, :]), first_index) pos = row_indices[-2:] last_row = _linear_extrapolate(pos, (data[-2, :], data[-1, :]), last_index) return np.vstack((np.expand_dims(first_row, 0), data, np.expand_dims(last_row, 0)))
python
def _extrapolate_rows(self, data, row_indices, first_index, last_index): """Extrapolate the rows of data, to get the first and last together with the data. """ pos = row_indices[:2] first_row = _linear_extrapolate(pos, (data[0, :], data[1, :]), first_index) pos = row_indices[-2:] last_row = _linear_extrapolate(pos, (data[-2, :], data[-1, :]), last_index) return np.vstack((np.expand_dims(first_row, 0), data, np.expand_dims(last_row, 0)))
[ "def", "_extrapolate_rows", "(", "self", ",", "data", ",", "row_indices", ",", "first_index", ",", "last_index", ")", ":", "pos", "=", "row_indices", "[", ":", "2", "]", "first_row", "=", "_linear_extrapolate", "(", "pos", ",", "(", "data", "[", "0", ","...
Extrapolate the rows of data, to get the first and last together with the data.
[ "Extrapolate", "the", "rows", "of", "data", "to", "get", "the", "first", "and", "last", "together", "with", "the", "data", "." ]
7c5cc8a887f8534cc2839c716c2c560aeaf77659
https://github.com/pytroll/python-geotiepoints/blob/7c5cc8a887f8534cc2839c716c2c560aeaf77659/geotiepoints/interpolator.py#L184-L199
train
40,988
pytroll/python-geotiepoints
geotiepoints/interpolator.py
Interpolator._fill_row_borders
def _fill_row_borders(self): """Add the first and last rows to the data by extrapolation. """ lines = len(self.hrow_indices) chunk_size = self.chunk_size or lines factor = len(self.hrow_indices) / len(self.row_indices) tmp_data = [] for num in range(len(self.tie_data)): tmp_data.append([]) row_indices = [] for index in range(0, lines, chunk_size): indices = np.logical_and(self.row_indices >= index / factor, self.row_indices < (index + chunk_size) / factor) ties = np.argwhere(indices).squeeze() tiepos = self.row_indices[indices].squeeze() for num, data in enumerate(self.tie_data): to_extrapolate = data[ties, :] if len(to_extrapolate) > 0: extrapolated = self._extrapolate_rows(to_extrapolate, tiepos, self.hrow_indices[ index], self.hrow_indices[index + chunk_size - 1]) tmp_data[num].append(extrapolated) row_indices.append(np.array([self.hrow_indices[index]])) row_indices.append(tiepos) row_indices.append(np.array([self.hrow_indices[index + chunk_size - 1]])) for num in range(len(self.tie_data)): self.tie_data[num] = np.vstack(tmp_data[num]) self.row_indices = np.concatenate(row_indices)
python
def _fill_row_borders(self): """Add the first and last rows to the data by extrapolation. """ lines = len(self.hrow_indices) chunk_size = self.chunk_size or lines factor = len(self.hrow_indices) / len(self.row_indices) tmp_data = [] for num in range(len(self.tie_data)): tmp_data.append([]) row_indices = [] for index in range(0, lines, chunk_size): indices = np.logical_and(self.row_indices >= index / factor, self.row_indices < (index + chunk_size) / factor) ties = np.argwhere(indices).squeeze() tiepos = self.row_indices[indices].squeeze() for num, data in enumerate(self.tie_data): to_extrapolate = data[ties, :] if len(to_extrapolate) > 0: extrapolated = self._extrapolate_rows(to_extrapolate, tiepos, self.hrow_indices[ index], self.hrow_indices[index + chunk_size - 1]) tmp_data[num].append(extrapolated) row_indices.append(np.array([self.hrow_indices[index]])) row_indices.append(tiepos) row_indices.append(np.array([self.hrow_indices[index + chunk_size - 1]])) for num in range(len(self.tie_data)): self.tie_data[num] = np.vstack(tmp_data[num]) self.row_indices = np.concatenate(row_indices)
[ "def", "_fill_row_borders", "(", "self", ")", ":", "lines", "=", "len", "(", "self", ".", "hrow_indices", ")", "chunk_size", "=", "self", ".", "chunk_size", "or", "lines", "factor", "=", "len", "(", "self", ".", "hrow_indices", ")", "/", "len", "(", "s...
Add the first and last rows to the data by extrapolation.
[ "Add", "the", "first", "and", "last", "rows", "to", "the", "data", "by", "extrapolation", "." ]
7c5cc8a887f8534cc2839c716c2c560aeaf77659
https://github.com/pytroll/python-geotiepoints/blob/7c5cc8a887f8534cc2839c716c2c560aeaf77659/geotiepoints/interpolator.py#L201-L237
train
40,989
pytroll/python-geotiepoints
geotiepoints/interpolator.py
Interpolator._interp
def _interp(self): """Interpolate the cartesian coordinates. """ if np.all(self.hrow_indices == self.row_indices): return self._interp1d() xpoints, ypoints = np.meshgrid(self.hrow_indices, self.hcol_indices) for num, data in enumerate(self.tie_data): spl = RectBivariateSpline(self.row_indices, self.col_indices, data, s=0, kx=self.kx_, ky=self.ky_) new_data_ = spl.ev(xpoints.ravel(), ypoints.ravel()) self.new_data[num] = new_data_.reshape(xpoints.shape).T.copy(order='C')
python
def _interp(self): """Interpolate the cartesian coordinates. """ if np.all(self.hrow_indices == self.row_indices): return self._interp1d() xpoints, ypoints = np.meshgrid(self.hrow_indices, self.hcol_indices) for num, data in enumerate(self.tie_data): spl = RectBivariateSpline(self.row_indices, self.col_indices, data, s=0, kx=self.kx_, ky=self.ky_) new_data_ = spl.ev(xpoints.ravel(), ypoints.ravel()) self.new_data[num] = new_data_.reshape(xpoints.shape).T.copy(order='C')
[ "def", "_interp", "(", "self", ")", ":", "if", "np", ".", "all", "(", "self", ".", "hrow_indices", "==", "self", ".", "row_indices", ")", ":", "return", "self", ".", "_interp1d", "(", ")", "xpoints", ",", "ypoints", "=", "np", ".", "meshgrid", "(", ...
Interpolate the cartesian coordinates.
[ "Interpolate", "the", "cartesian", "coordinates", "." ]
7c5cc8a887f8534cc2839c716c2c560aeaf77659
https://github.com/pytroll/python-geotiepoints/blob/7c5cc8a887f8534cc2839c716c2c560aeaf77659/geotiepoints/interpolator.py#L239-L257
train
40,990
pytroll/python-geotiepoints
geotiepoints/interpolator.py
Interpolator._interp1d
def _interp1d(self): """Interpolate in one dimension. """ lines = len(self.hrow_indices) for num, data in enumerate(self.tie_data): self.new_data[num] = np.empty((len(self.hrow_indices), len(self.hcol_indices)), data.dtype) for cnt in range(lines): tck = splrep(self.col_indices, data[cnt, :], k=self.ky_, s=0) self.new_data[num][cnt, :] = splev( self.hcol_indices, tck, der=0)
python
def _interp1d(self): """Interpolate in one dimension. """ lines = len(self.hrow_indices) for num, data in enumerate(self.tie_data): self.new_data[num] = np.empty((len(self.hrow_indices), len(self.hcol_indices)), data.dtype) for cnt in range(lines): tck = splrep(self.col_indices, data[cnt, :], k=self.ky_, s=0) self.new_data[num][cnt, :] = splev( self.hcol_indices, tck, der=0)
[ "def", "_interp1d", "(", "self", ")", ":", "lines", "=", "len", "(", "self", ".", "hrow_indices", ")", "for", "num", ",", "data", "in", "enumerate", "(", "self", ".", "tie_data", ")", ":", "self", ".", "new_data", "[", "num", "]", "=", "np", ".", ...
Interpolate in one dimension.
[ "Interpolate", "in", "one", "dimension", "." ]
7c5cc8a887f8534cc2839c716c2c560aeaf77659
https://github.com/pytroll/python-geotiepoints/blob/7c5cc8a887f8534cc2839c716c2c560aeaf77659/geotiepoints/interpolator.py#L259-L272
train
40,991
pytroll/python-geotiepoints
geotiepoints/geointerpolator.py
get_lats_from_cartesian
def get_lats_from_cartesian(x__, y__, z__, thr=0.8): """Get latitudes from cartesian coordinates. """ # if we are at low latitudes - small z, then get the # latitudes only from z. If we are at high latitudes (close to the poles) # then derive the latitude using x and y: lats = np.where(np.logical_and(np.less(z__, thr * EARTH_RADIUS), np.greater(z__, -1. * thr * EARTH_RADIUS)), 90 - rad2deg(arccos(z__/EARTH_RADIUS)), sign(z__) * (90 - rad2deg(arcsin(sqrt(x__ ** 2 + y__ ** 2) / EARTH_RADIUS)))) return lats
python
def get_lats_from_cartesian(x__, y__, z__, thr=0.8): """Get latitudes from cartesian coordinates. """ # if we are at low latitudes - small z, then get the # latitudes only from z. If we are at high latitudes (close to the poles) # then derive the latitude using x and y: lats = np.where(np.logical_and(np.less(z__, thr * EARTH_RADIUS), np.greater(z__, -1. * thr * EARTH_RADIUS)), 90 - rad2deg(arccos(z__/EARTH_RADIUS)), sign(z__) * (90 - rad2deg(arcsin(sqrt(x__ ** 2 + y__ ** 2) / EARTH_RADIUS)))) return lats
[ "def", "get_lats_from_cartesian", "(", "x__", ",", "y__", ",", "z__", ",", "thr", "=", "0.8", ")", ":", "# if we are at low latitudes - small z, then get the", "# latitudes only from z. If we are at high latitudes (close to the poles)", "# then derive the latitude using x and y:", ...
Get latitudes from cartesian coordinates.
[ "Get", "latitudes", "from", "cartesian", "coordinates", "." ]
7c5cc8a887f8534cc2839c716c2c560aeaf77659
https://github.com/pytroll/python-geotiepoints/blob/7c5cc8a887f8534cc2839c716c2c560aeaf77659/geotiepoints/geointerpolator.py#L92-L105
train
40,992
pytroll/python-geotiepoints
geotiepoints/geointerpolator.py
GeoInterpolator.set_tiepoints
def set_tiepoints(self, lon, lat): """Defines the lon,lat tie points. """ self.lon_tiepoint = lon self.lat_tiepoint = lat
python
def set_tiepoints(self, lon, lat): """Defines the lon,lat tie points. """ self.lon_tiepoint = lon self.lat_tiepoint = lat
[ "def", "set_tiepoints", "(", "self", ",", "lon", ",", "lat", ")", ":", "self", ".", "lon_tiepoint", "=", "lon", "self", ".", "lat_tiepoint", "=", "lat" ]
Defines the lon,lat tie points.
[ "Defines", "the", "lon", "lat", "tie", "points", "." ]
7c5cc8a887f8534cc2839c716c2c560aeaf77659
https://github.com/pytroll/python-geotiepoints/blob/7c5cc8a887f8534cc2839c716c2c560aeaf77659/geotiepoints/geointerpolator.py#L75-L79
train
40,993
pytroll/python-geotiepoints
geotiepoints/modisinterpolator.py
compute_expansion_alignment
def compute_expansion_alignment(satz_a, satz_b, satz_c, satz_d): """All angles in radians.""" zeta_a = satz_a zeta_b = satz_b phi_a = compute_phi(zeta_a) phi_b = compute_phi(zeta_b) theta_a = compute_theta(zeta_a, phi_a) theta_b = compute_theta(zeta_b, phi_b) phi = (phi_a + phi_b) / 2 zeta = compute_zeta(phi) theta = compute_theta(zeta, phi) c_expansion = 4 * (((theta_a + theta_b) / 2 - theta) / (theta_a - theta_b)) sin_beta_2 = scan_width / (2 * H) d = ((R + H) / R * np.cos(phi) - np.cos(zeta)) * sin_beta_2 e = np.cos(zeta) - np.sqrt(np.cos(zeta) ** 2 - d ** 2) c_alignment = 4 * e * np.sin(zeta) / (theta_a - theta_b) return c_expansion, c_alignment
python
def compute_expansion_alignment(satz_a, satz_b, satz_c, satz_d): """All angles in radians.""" zeta_a = satz_a zeta_b = satz_b phi_a = compute_phi(zeta_a) phi_b = compute_phi(zeta_b) theta_a = compute_theta(zeta_a, phi_a) theta_b = compute_theta(zeta_b, phi_b) phi = (phi_a + phi_b) / 2 zeta = compute_zeta(phi) theta = compute_theta(zeta, phi) c_expansion = 4 * (((theta_a + theta_b) / 2 - theta) / (theta_a - theta_b)) sin_beta_2 = scan_width / (2 * H) d = ((R + H) / R * np.cos(phi) - np.cos(zeta)) * sin_beta_2 e = np.cos(zeta) - np.sqrt(np.cos(zeta) ** 2 - d ** 2) c_alignment = 4 * e * np.sin(zeta) / (theta_a - theta_b) return c_expansion, c_alignment
[ "def", "compute_expansion_alignment", "(", "satz_a", ",", "satz_b", ",", "satz_c", ",", "satz_d", ")", ":", "zeta_a", "=", "satz_a", "zeta_b", "=", "satz_b", "phi_a", "=", "compute_phi", "(", "zeta_a", ")", "phi_b", "=", "compute_phi", "(", "zeta_b", ")", ...
All angles in radians.
[ "All", "angles", "in", "radians", "." ]
7c5cc8a887f8534cc2839c716c2c560aeaf77659
https://github.com/pytroll/python-geotiepoints/blob/7c5cc8a887f8534cc2839c716c2c560aeaf77659/geotiepoints/modisinterpolator.py#L51-L73
train
40,994
pytroll/python-geotiepoints
geotiepoints/modisinterpolator.py
lonlat2xyz
def lonlat2xyz(lons, lats): """Convert lons and lats to cartesian coordinates.""" R = 6370997.0 x_coords = R * da.cos(da.deg2rad(lats)) * da.cos(da.deg2rad(lons)) y_coords = R * da.cos(da.deg2rad(lats)) * da.sin(da.deg2rad(lons)) z_coords = R * da.sin(da.deg2rad(lats)) return x_coords, y_coords, z_coords
python
def lonlat2xyz(lons, lats): """Convert lons and lats to cartesian coordinates.""" R = 6370997.0 x_coords = R * da.cos(da.deg2rad(lats)) * da.cos(da.deg2rad(lons)) y_coords = R * da.cos(da.deg2rad(lats)) * da.sin(da.deg2rad(lons)) z_coords = R * da.sin(da.deg2rad(lats)) return x_coords, y_coords, z_coords
[ "def", "lonlat2xyz", "(", "lons", ",", "lats", ")", ":", "R", "=", "6370997.0", "x_coords", "=", "R", "*", "da", ".", "cos", "(", "da", ".", "deg2rad", "(", "lats", ")", ")", "*", "da", ".", "cos", "(", "da", ".", "deg2rad", "(", "lons", ")", ...
Convert lons and lats to cartesian coordinates.
[ "Convert", "lons", "and", "lats", "to", "cartesian", "coordinates", "." ]
7c5cc8a887f8534cc2839c716c2c560aeaf77659
https://github.com/pytroll/python-geotiepoints/blob/7c5cc8a887f8534cc2839c716c2c560aeaf77659/geotiepoints/modisinterpolator.py#L250-L256
train
40,995
EliotBerriot/lifter
lifter/backends/base.py
setup_fields
def setup_fields(attrs): """ Collect all fields declared on the class and remove them from attrs """ fields = {} iterator = list(attrs.items()) for key, value in iterator: if not isinstance(value, Field): continue fields[key] = value del attrs[key] return fields
python
def setup_fields(attrs): """ Collect all fields declared on the class and remove them from attrs """ fields = {} iterator = list(attrs.items()) for key, value in iterator: if not isinstance(value, Field): continue fields[key] = value del attrs[key] return fields
[ "def", "setup_fields", "(", "attrs", ")", ":", "fields", "=", "{", "}", "iterator", "=", "list", "(", "attrs", ".", "items", "(", ")", ")", "for", "key", ",", "value", "in", "iterator", ":", "if", "not", "isinstance", "(", "value", ",", "Field", ")...
Collect all fields declared on the class and remove them from attrs
[ "Collect", "all", "fields", "declared", "on", "the", "class", "and", "remove", "them", "from", "attrs" ]
9b4394b476cddd952b2af9540affc03f2977163d
https://github.com/EliotBerriot/lifter/blob/9b4394b476cddd952b2af9540affc03f2977163d/lifter/backends/base.py#L20-L31
train
40,996
openstax/cnxml
cnxml/jing.py
_parse_jing_line
def _parse_jing_line(line): """Parse a line of jing output to a list of line, column, type and message. """ parts = line.split(':', 4) filename, line, column, type_, message = [x.strip() for x in parts] if type_ == 'fatal': if message in KNOWN_FATAL_MESSAGES_MAPPING: message = KNOWN_FATAL_MESSAGES_MAPPING[message] return ErrorLine(filename, line, column, type_, message)
python
def _parse_jing_line(line): """Parse a line of jing output to a list of line, column, type and message. """ parts = line.split(':', 4) filename, line, column, type_, message = [x.strip() for x in parts] if type_ == 'fatal': if message in KNOWN_FATAL_MESSAGES_MAPPING: message = KNOWN_FATAL_MESSAGES_MAPPING[message] return ErrorLine(filename, line, column, type_, message)
[ "def", "_parse_jing_line", "(", "line", ")", ":", "parts", "=", "line", ".", "split", "(", "':'", ",", "4", ")", "filename", ",", "line", ",", "column", ",", "type_", ",", "message", "=", "[", "x", ".", "strip", "(", ")", "for", "x", "in", "parts...
Parse a line of jing output to a list of line, column, type and message.
[ "Parse", "a", "line", "of", "jing", "output", "to", "a", "list", "of", "line", "column", "type", "and", "message", "." ]
ddce4016ef204c509861cdc328815ddc361378c9
https://github.com/openstax/cnxml/blob/ddce4016ef204c509861cdc328815ddc361378c9/cnxml/jing.py#L25-L35
train
40,997
openstax/cnxml
cnxml/jing.py
_parse_jing_output
def _parse_jing_output(output): """Parse the jing output into a tuple of line, column, type and message. """ output = output.strip() values = [_parse_jing_line(l) for l in output.split('\n') if l] return tuple(values)
python
def _parse_jing_output(output): """Parse the jing output into a tuple of line, column, type and message. """ output = output.strip() values = [_parse_jing_line(l) for l in output.split('\n') if l] return tuple(values)
[ "def", "_parse_jing_output", "(", "output", ")", ":", "output", "=", "output", ".", "strip", "(", ")", "values", "=", "[", "_parse_jing_line", "(", "l", ")", "for", "l", "in", "output", ".", "split", "(", "'\\n'", ")", "if", "l", "]", "return", "tupl...
Parse the jing output into a tuple of line, column, type and message.
[ "Parse", "the", "jing", "output", "into", "a", "tuple", "of", "line", "column", "type", "and", "message", "." ]
ddce4016ef204c509861cdc328815ddc361378c9
https://github.com/openstax/cnxml/blob/ddce4016ef204c509861cdc328815ddc361378c9/cnxml/jing.py#L38-L44
train
40,998
openstax/cnxml
cnxml/jing.py
jing
def jing(rng_filepath, *xml_filepaths): """Run jing.jar using the RNG file against the given XML file.""" cmd = ['java', '-jar'] cmd.extend([str(JING_JAR), str(rng_filepath)]) for xml_filepath in xml_filepaths: cmd.append(str(xml_filepath)) proc = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True) out, err = proc.communicate() return _parse_jing_output(out.decode('utf-8'))
python
def jing(rng_filepath, *xml_filepaths): """Run jing.jar using the RNG file against the given XML file.""" cmd = ['java', '-jar'] cmd.extend([str(JING_JAR), str(rng_filepath)]) for xml_filepath in xml_filepaths: cmd.append(str(xml_filepath)) proc = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True) out, err = proc.communicate() return _parse_jing_output(out.decode('utf-8'))
[ "def", "jing", "(", "rng_filepath", ",", "*", "xml_filepaths", ")", ":", "cmd", "=", "[", "'java'", ",", "'-jar'", "]", "cmd", ".", "extend", "(", "[", "str", "(", "JING_JAR", ")", ",", "str", "(", "rng_filepath", ")", "]", ")", "for", "xml_filepath"...
Run jing.jar using the RNG file against the given XML file.
[ "Run", "jing", ".", "jar", "using", "the", "RNG", "file", "against", "the", "given", "XML", "file", "." ]
ddce4016ef204c509861cdc328815ddc361378c9
https://github.com/openstax/cnxml/blob/ddce4016ef204c509861cdc328815ddc361378c9/cnxml/jing.py#L47-L59
train
40,999