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
sequence
docstring
stringlengths
3
17.3k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
hickeroar/LatLon23
LatLon23/__init__.py
GeoCoord._calc_degreeminutes
def _calc_degreeminutes(decimal_degree): ''' Calculate degree, minute second from decimal degree ''' sign = compare(decimal_degree, 0) # Store whether the coordinate is negative or positive decimal_degree = abs(decimal_degree) degree = decimal_degree//1 # Truncate degree to be an integer decimal_minute = (decimal_degree - degree)*60. # Calculate the decimal minutes minute = decimal_minute//1 # Truncate minute to be an integer second = (decimal_minute - minute)*60. # Calculate the decimal seconds # Finally, re-impose the appropriate sign degree = degree*sign minute = minute*sign second = second*sign return (degree, minute, decimal_minute, second)
python
def _calc_degreeminutes(decimal_degree): ''' Calculate degree, minute second from decimal degree ''' sign = compare(decimal_degree, 0) # Store whether the coordinate is negative or positive decimal_degree = abs(decimal_degree) degree = decimal_degree//1 # Truncate degree to be an integer decimal_minute = (decimal_degree - degree)*60. # Calculate the decimal minutes minute = decimal_minute//1 # Truncate minute to be an integer second = (decimal_minute - minute)*60. # Calculate the decimal seconds # Finally, re-impose the appropriate sign degree = degree*sign minute = minute*sign second = second*sign return (degree, minute, decimal_minute, second)
[ "def", "_calc_degreeminutes", "(", "decimal_degree", ")", ":", "sign", "=", "compare", "(", "decimal_degree", ",", "0", ")", "# Store whether the coordinate is negative or positive", "decimal_degree", "=", "abs", "(", "decimal_degree", ")", "degree", "=", "decimal_degree", "//", "1", "# Truncate degree to be an integer", "decimal_minute", "=", "(", "decimal_degree", "-", "degree", ")", "*", "60.", "# Calculate the decimal minutes", "minute", "=", "decimal_minute", "//", "1", "# Truncate minute to be an integer", "second", "=", "(", "decimal_minute", "-", "minute", ")", "*", "60.", "# Calculate the decimal seconds", "# Finally, re-impose the appropriate sign", "degree", "=", "degree", "*", "sign", "minute", "=", "minute", "*", "sign", "second", "=", "second", "*", "sign", "return", "(", "degree", ",", "minute", ",", "decimal_minute", ",", "second", ")" ]
Calculate degree, minute second from decimal degree
[ "Calculate", "degree", "minute", "second", "from", "decimal", "degree" ]
1ff728216ae51055034f4c915fa715446b34549f
https://github.com/hickeroar/LatLon23/blob/1ff728216ae51055034f4c915fa715446b34549f/LatLon23/__init__.py#L73-L87
train
hickeroar/LatLon23
LatLon23/__init__.py
Longitude.set_hemisphere
def set_hemisphere(self, hemi_str): ''' Given a hemisphere identifier, set the sign of the coordinate to match that hemisphere ''' if hemi_str == 'W': self.degree = abs(self.degree)*-1 self.minute = abs(self.minute)*-1 self.second = abs(self.second)*-1 self._update() elif hemi_str == 'E': self.degree = abs(self.degree) self.minute = abs(self.minute) self.second = abs(self.second) self._update() else: raise ValueError('Hemisphere identifier for longitudes must be E or W')
python
def set_hemisphere(self, hemi_str): ''' Given a hemisphere identifier, set the sign of the coordinate to match that hemisphere ''' if hemi_str == 'W': self.degree = abs(self.degree)*-1 self.minute = abs(self.minute)*-1 self.second = abs(self.second)*-1 self._update() elif hemi_str == 'E': self.degree = abs(self.degree) self.minute = abs(self.minute) self.second = abs(self.second) self._update() else: raise ValueError('Hemisphere identifier for longitudes must be E or W')
[ "def", "set_hemisphere", "(", "self", ",", "hemi_str", ")", ":", "if", "hemi_str", "==", "'W'", ":", "self", ".", "degree", "=", "abs", "(", "self", ".", "degree", ")", "*", "-", "1", "self", ".", "minute", "=", "abs", "(", "self", ".", "minute", ")", "*", "-", "1", "self", ".", "second", "=", "abs", "(", "self", ".", "second", ")", "*", "-", "1", "self", ".", "_update", "(", ")", "elif", "hemi_str", "==", "'E'", ":", "self", ".", "degree", "=", "abs", "(", "self", ".", "degree", ")", "self", ".", "minute", "=", "abs", "(", "self", ".", "minute", ")", "self", ".", "second", "=", "abs", "(", "self", ".", "second", ")", "self", ".", "_update", "(", ")", "else", ":", "raise", "ValueError", "(", "'Hemisphere identifier for longitudes must be E or W'", ")" ]
Given a hemisphere identifier, set the sign of the coordinate to match that hemisphere
[ "Given", "a", "hemisphere", "identifier", "set", "the", "sign", "of", "the", "coordinate", "to", "match", "that", "hemisphere" ]
1ff728216ae51055034f4c915fa715446b34549f
https://github.com/hickeroar/LatLon23/blob/1ff728216ae51055034f4c915fa715446b34549f/LatLon23/__init__.py#L269-L284
train
hickeroar/LatLon23
LatLon23/__init__.py
LatLon.project
def project(self, projection): ''' Return coordinates transformed to a given projection Projection should be a basemap or pyproj projection object or similar ''' x, y = projection(self.lon.decimal_degree, self.lat.decimal_degree) return (x, y)
python
def project(self, projection): ''' Return coordinates transformed to a given projection Projection should be a basemap or pyproj projection object or similar ''' x, y = projection(self.lon.decimal_degree, self.lat.decimal_degree) return (x, y)
[ "def", "project", "(", "self", ",", "projection", ")", ":", "x", ",", "y", "=", "projection", "(", "self", ".", "lon", ".", "decimal_degree", ",", "self", ".", "lat", ".", "decimal_degree", ")", "return", "(", "x", ",", "y", ")" ]
Return coordinates transformed to a given projection Projection should be a basemap or pyproj projection object or similar
[ "Return", "coordinates", "transformed", "to", "a", "given", "projection", "Projection", "should", "be", "a", "basemap", "or", "pyproj", "projection", "object", "or", "similar" ]
1ff728216ae51055034f4c915fa715446b34549f
https://github.com/hickeroar/LatLon23/blob/1ff728216ae51055034f4c915fa715446b34549f/LatLon23/__init__.py#L370-L376
train
hickeroar/LatLon23
LatLon23/__init__.py
LatLon._pyproj_inv
def _pyproj_inv(self, other, ellipse = 'WGS84'): ''' Perform Pyproj's inv operation on two LatLon objects Returns the initial heading and reverse heading in degrees, and the distance in km. ''' lat1, lon1 = self.lat.decimal_degree, self.lon.decimal_degree lat2, lon2 = other.lat.decimal_degree, other.lon.decimal_degree g = pyproj.Geod(ellps = ellipse) heading_initial, heading_reverse, distance = g.inv(lon1, lat1, lon2, lat2, radians = False) distance = distance/1000.0 if heading_initial == 0.0: # Reverse heading not well handled for coordinates that are directly south heading_reverse = 180.0 return {'heading_initial': heading_initial, 'heading_reverse': heading_reverse, 'distance': distance}
python
def _pyproj_inv(self, other, ellipse = 'WGS84'): ''' Perform Pyproj's inv operation on two LatLon objects Returns the initial heading and reverse heading in degrees, and the distance in km. ''' lat1, lon1 = self.lat.decimal_degree, self.lon.decimal_degree lat2, lon2 = other.lat.decimal_degree, other.lon.decimal_degree g = pyproj.Geod(ellps = ellipse) heading_initial, heading_reverse, distance = g.inv(lon1, lat1, lon2, lat2, radians = False) distance = distance/1000.0 if heading_initial == 0.0: # Reverse heading not well handled for coordinates that are directly south heading_reverse = 180.0 return {'heading_initial': heading_initial, 'heading_reverse': heading_reverse, 'distance': distance}
[ "def", "_pyproj_inv", "(", "self", ",", "other", ",", "ellipse", "=", "'WGS84'", ")", ":", "lat1", ",", "lon1", "=", "self", ".", "lat", ".", "decimal_degree", ",", "self", ".", "lon", ".", "decimal_degree", "lat2", ",", "lon2", "=", "other", ".", "lat", ".", "decimal_degree", ",", "other", ".", "lon", ".", "decimal_degree", "g", "=", "pyproj", ".", "Geod", "(", "ellps", "=", "ellipse", ")", "heading_initial", ",", "heading_reverse", ",", "distance", "=", "g", ".", "inv", "(", "lon1", ",", "lat1", ",", "lon2", ",", "lat2", ",", "radians", "=", "False", ")", "distance", "=", "distance", "/", "1000.0", "if", "heading_initial", "==", "0.0", ":", "# Reverse heading not well handled for coordinates that are directly south", "heading_reverse", "=", "180.0", "return", "{", "'heading_initial'", ":", "heading_initial", ",", "'heading_reverse'", ":", "heading_reverse", ",", "'distance'", ":", "distance", "}" ]
Perform Pyproj's inv operation on two LatLon objects Returns the initial heading and reverse heading in degrees, and the distance in km.
[ "Perform", "Pyproj", "s", "inv", "operation", "on", "two", "LatLon", "objects", "Returns", "the", "initial", "heading", "and", "reverse", "heading", "in", "degrees", "and", "the", "distance", "in", "km", "." ]
1ff728216ae51055034f4c915fa715446b34549f
https://github.com/hickeroar/LatLon23/blob/1ff728216ae51055034f4c915fa715446b34549f/LatLon23/__init__.py#L384-L397
train
hickeroar/LatLon23
LatLon23/__init__.py
LatLon.to_string
def to_string(self, formatter = 'D'): ''' Return string representation of lat and lon as a 2-element tuple using the format specified by formatter ''' return (self.lat.to_string(formatter), self.lon.to_string(formatter))
python
def to_string(self, formatter = 'D'): ''' Return string representation of lat and lon as a 2-element tuple using the format specified by formatter ''' return (self.lat.to_string(formatter), self.lon.to_string(formatter))
[ "def", "to_string", "(", "self", ",", "formatter", "=", "'D'", ")", ":", "return", "(", "self", ".", "lat", ".", "to_string", "(", "formatter", ")", ",", "self", ".", "lon", ".", "to_string", "(", "formatter", ")", ")" ]
Return string representation of lat and lon as a 2-element tuple using the format specified by formatter
[ "Return", "string", "representation", "of", "lat", "and", "lon", "as", "a", "2", "-", "element", "tuple", "using", "the", "format", "specified", "by", "formatter" ]
1ff728216ae51055034f4c915fa715446b34549f
https://github.com/hickeroar/LatLon23/blob/1ff728216ae51055034f4c915fa715446b34549f/LatLon23/__init__.py#L458-L463
train
hickeroar/LatLon23
LatLon23/__init__.py
LatLon._sub_latlon
def _sub_latlon(self, other): ''' Called when subtracting a LatLon object from self ''' inv = self._pyproj_inv(other) heading = inv['heading_reverse'] distance = inv['distance'] return GeoVector(initial_heading = heading, distance = distance)
python
def _sub_latlon(self, other): ''' Called when subtracting a LatLon object from self ''' inv = self._pyproj_inv(other) heading = inv['heading_reverse'] distance = inv['distance'] return GeoVector(initial_heading = heading, distance = distance)
[ "def", "_sub_latlon", "(", "self", ",", "other", ")", ":", "inv", "=", "self", ".", "_pyproj_inv", "(", "other", ")", "heading", "=", "inv", "[", "'heading_reverse'", "]", "distance", "=", "inv", "[", "'distance'", "]", "return", "GeoVector", "(", "initial_heading", "=", "heading", ",", "distance", "=", "distance", ")" ]
Called when subtracting a LatLon object from self
[ "Called", "when", "subtracting", "a", "LatLon", "object", "from", "self" ]
1ff728216ae51055034f4c915fa715446b34549f
https://github.com/hickeroar/LatLon23/blob/1ff728216ae51055034f4c915fa715446b34549f/LatLon23/__init__.py#L474-L481
train
hickeroar/LatLon23
LatLon23/__init__.py
GeoVector._update
def _update(self): ''' Calculate heading and distance from dx and dy ''' try: theta_radians = math.atan(float(self.dy)/self.dx) except ZeroDivisionError: if self.dy > 0: theta_radians = 0.5*math.pi elif self.dy < 0: theta_radians = 1.5*math.pi self.magnitude = self.dy else: self.magnitude = 1./(math.cos(theta_radians))*self.dx theta = math.degrees(theta_radians) self.heading = self._angle_or_heading(theta)
python
def _update(self): ''' Calculate heading and distance from dx and dy ''' try: theta_radians = math.atan(float(self.dy)/self.dx) except ZeroDivisionError: if self.dy > 0: theta_radians = 0.5*math.pi elif self.dy < 0: theta_radians = 1.5*math.pi self.magnitude = self.dy else: self.magnitude = 1./(math.cos(theta_radians))*self.dx theta = math.degrees(theta_radians) self.heading = self._angle_or_heading(theta)
[ "def", "_update", "(", "self", ")", ":", "try", ":", "theta_radians", "=", "math", ".", "atan", "(", "float", "(", "self", ".", "dy", ")", "/", "self", ".", "dx", ")", "except", "ZeroDivisionError", ":", "if", "self", ".", "dy", ">", "0", ":", "theta_radians", "=", "0.5", "*", "math", ".", "pi", "elif", "self", ".", "dy", "<", "0", ":", "theta_radians", "=", "1.5", "*", "math", ".", "pi", "self", ".", "magnitude", "=", "self", ".", "dy", "else", ":", "self", ".", "magnitude", "=", "1.", "/", "(", "math", ".", "cos", "(", "theta_radians", ")", ")", "*", "self", ".", "dx", "theta", "=", "math", ".", "degrees", "(", "theta_radians", ")", "self", ".", "heading", "=", "self", ".", "_angle_or_heading", "(", "theta", ")" ]
Calculate heading and distance from dx and dy
[ "Calculate", "heading", "and", "distance", "from", "dx", "and", "dy" ]
1ff728216ae51055034f4c915fa715446b34549f
https://github.com/hickeroar/LatLon23/blob/1ff728216ae51055034f4c915fa715446b34549f/LatLon23/__init__.py#L608-L621
train
exosite-labs/pyonep
pyonep/onep.py
DeferredRequests._authstr
def _authstr(self, auth): """Convert auth to str so that it can be hashed""" if type(auth) is dict: return '{' + ','.join(["{0}:{1}".format(k, auth[k]) for k in sorted(auth.keys())]) + '}' return auth
python
def _authstr(self, auth): """Convert auth to str so that it can be hashed""" if type(auth) is dict: return '{' + ','.join(["{0}:{1}".format(k, auth[k]) for k in sorted(auth.keys())]) + '}' return auth
[ "def", "_authstr", "(", "self", ",", "auth", ")", ":", "if", "type", "(", "auth", ")", "is", "dict", ":", "return", "'{'", "+", "','", ".", "join", "(", "[", "\"{0}:{1}\"", ".", "format", "(", "k", ",", "auth", "[", "k", "]", ")", "for", "k", "in", "sorted", "(", "auth", ".", "keys", "(", ")", ")", "]", ")", "+", "'}'", "return", "auth" ]
Convert auth to str so that it can be hashed
[ "Convert", "auth", "to", "str", "so", "that", "it", "can", "be", "hashed" ]
d27b621b00688a542e0adcc01f3e3354c05238a1
https://github.com/exosite-labs/pyonep/blob/d27b621b00688a542e0adcc01f3e3354c05238a1/pyonep/onep.py#L52-L56
train
exosite-labs/pyonep
pyonep/onep.py
OnepV1._call
def _call(self, method, auth, arg, defer, notimeout=False): """Calls the Exosite One Platform RPC API. If `defer` is False, result is a tuple with this structure: (success (boolean), response) Otherwise, the result is just True. notimeout, if True, ignores the reuseconnection setting, creating a new connection with no timeout. """ if defer: self.deferred.add(auth, method, arg, notimeout=notimeout) return True else: calls = self._composeCalls([(method, arg)]) return self._callJsonRPC(auth, calls, notimeout=notimeout)
python
def _call(self, method, auth, arg, defer, notimeout=False): """Calls the Exosite One Platform RPC API. If `defer` is False, result is a tuple with this structure: (success (boolean), response) Otherwise, the result is just True. notimeout, if True, ignores the reuseconnection setting, creating a new connection with no timeout. """ if defer: self.deferred.add(auth, method, arg, notimeout=notimeout) return True else: calls = self._composeCalls([(method, arg)]) return self._callJsonRPC(auth, calls, notimeout=notimeout)
[ "def", "_call", "(", "self", ",", "method", ",", "auth", ",", "arg", ",", "defer", ",", "notimeout", "=", "False", ")", ":", "if", "defer", ":", "self", ".", "deferred", ".", "add", "(", "auth", ",", "method", ",", "arg", ",", "notimeout", "=", "notimeout", ")", "return", "True", "else", ":", "calls", "=", "self", ".", "_composeCalls", "(", "[", "(", "method", ",", "arg", ")", "]", ")", "return", "self", ".", "_callJsonRPC", "(", "auth", ",", "calls", ",", "notimeout", "=", "notimeout", ")" ]
Calls the Exosite One Platform RPC API. If `defer` is False, result is a tuple with this structure: (success (boolean), response) Otherwise, the result is just True. notimeout, if True, ignores the reuseconnection setting, creating a new connection with no timeout.
[ "Calls", "the", "Exosite", "One", "Platform", "RPC", "API", "." ]
d27b621b00688a542e0adcc01f3e3354c05238a1
https://github.com/exosite-labs/pyonep/blob/d27b621b00688a542e0adcc01f3e3354c05238a1/pyonep/onep.py#L221-L238
train
exosite-labs/pyonep
pyonep/onep.py
OnepV1.create
def create(self, auth, type, desc, defer=False): """ Create something in Exosite. Args: auth: <cik> type: What thing to create. desc: Information about thing. """ return self._call('create', auth, [type, desc], defer)
python
def create(self, auth, type, desc, defer=False): """ Create something in Exosite. Args: auth: <cik> type: What thing to create. desc: Information about thing. """ return self._call('create', auth, [type, desc], defer)
[ "def", "create", "(", "self", ",", "auth", ",", "type", ",", "desc", ",", "defer", "=", "False", ")", ":", "return", "self", ".", "_call", "(", "'create'", ",", "auth", ",", "[", "type", ",", "desc", "]", ",", "defer", ")" ]
Create something in Exosite. Args: auth: <cik> type: What thing to create. desc: Information about thing.
[ "Create", "something", "in", "Exosite", "." ]
d27b621b00688a542e0adcc01f3e3354c05238a1
https://github.com/exosite-labs/pyonep/blob/d27b621b00688a542e0adcc01f3e3354c05238a1/pyonep/onep.py#L279-L287
train
exosite-labs/pyonep
pyonep/onep.py
OnepV1.drop
def drop(self, auth, resource, defer=False): """ Deletes the specified resource. Args: auth: <cik> resource: <ResourceID> """ return self._call('drop', auth, [resource], defer)
python
def drop(self, auth, resource, defer=False): """ Deletes the specified resource. Args: auth: <cik> resource: <ResourceID> """ return self._call('drop', auth, [resource], defer)
[ "def", "drop", "(", "self", ",", "auth", ",", "resource", ",", "defer", "=", "False", ")", ":", "return", "self", ".", "_call", "(", "'drop'", ",", "auth", ",", "[", "resource", "]", ",", "defer", ")" ]
Deletes the specified resource. Args: auth: <cik> resource: <ResourceID>
[ "Deletes", "the", "specified", "resource", "." ]
d27b621b00688a542e0adcc01f3e3354c05238a1
https://github.com/exosite-labs/pyonep/blob/d27b621b00688a542e0adcc01f3e3354c05238a1/pyonep/onep.py#L310-L317
train
exosite-labs/pyonep
pyonep/onep.py
OnepV1.flush
def flush(self, auth, resource, options=None, defer=False): """ Empties the specified resource of data per specified constraints. Args: auth: <cik> resource: resource to empty. options: Time limits. """ args = [resource] if options is not None: args.append(options) return self._call('flush', auth, args, defer)
python
def flush(self, auth, resource, options=None, defer=False): """ Empties the specified resource of data per specified constraints. Args: auth: <cik> resource: resource to empty. options: Time limits. """ args = [resource] if options is not None: args.append(options) return self._call('flush', auth, args, defer)
[ "def", "flush", "(", "self", ",", "auth", ",", "resource", ",", "options", "=", "None", ",", "defer", "=", "False", ")", ":", "args", "=", "[", "resource", "]", "if", "options", "is", "not", "None", ":", "args", ".", "append", "(", "options", ")", "return", "self", ".", "_call", "(", "'flush'", ",", "auth", ",", "args", ",", "defer", ")" ]
Empties the specified resource of data per specified constraints. Args: auth: <cik> resource: resource to empty. options: Time limits.
[ "Empties", "the", "specified", "resource", "of", "data", "per", "specified", "constraints", "." ]
d27b621b00688a542e0adcc01f3e3354c05238a1
https://github.com/exosite-labs/pyonep/blob/d27b621b00688a542e0adcc01f3e3354c05238a1/pyonep/onep.py#L319-L330
train
exosite-labs/pyonep
pyonep/onep.py
OnepV1.grant
def grant(self, auth, resource, permissions, ttl=None, defer=False): """ Grant resources with specific permissions and return a token. Args: auth: <cik> resource: Alias or ID of resource. permissions: permissions of resources. ttl: Time To Live. """ args = [resource, permissions] if ttl is not None: args.append({"ttl": ttl}) return self._call('grant', auth, args, defer)
python
def grant(self, auth, resource, permissions, ttl=None, defer=False): """ Grant resources with specific permissions and return a token. Args: auth: <cik> resource: Alias or ID of resource. permissions: permissions of resources. ttl: Time To Live. """ args = [resource, permissions] if ttl is not None: args.append({"ttl": ttl}) return self._call('grant', auth, args, defer)
[ "def", "grant", "(", "self", ",", "auth", ",", "resource", ",", "permissions", ",", "ttl", "=", "None", ",", "defer", "=", "False", ")", ":", "args", "=", "[", "resource", ",", "permissions", "]", "if", "ttl", "is", "not", "None", ":", "args", ".", "append", "(", "{", "\"ttl\"", ":", "ttl", "}", ")", "return", "self", ".", "_call", "(", "'grant'", ",", "auth", ",", "args", ",", "defer", ")" ]
Grant resources with specific permissions and return a token. Args: auth: <cik> resource: Alias or ID of resource. permissions: permissions of resources. ttl: Time To Live.
[ "Grant", "resources", "with", "specific", "permissions", "and", "return", "a", "token", "." ]
d27b621b00688a542e0adcc01f3e3354c05238a1
https://github.com/exosite-labs/pyonep/blob/d27b621b00688a542e0adcc01f3e3354c05238a1/pyonep/onep.py#L332-L344
train
exosite-labs/pyonep
pyonep/onep.py
OnepV1.info
def info(self, auth, resource, options={}, defer=False): """ Request creation and usage information of specified resource according to the specified options. Args: auth: <cik> resource: Alias or ID of resource options: Options to define what info you would like returned. """ return self._call('info', auth, [resource, options], defer)
python
def info(self, auth, resource, options={}, defer=False): """ Request creation and usage information of specified resource according to the specified options. Args: auth: <cik> resource: Alias or ID of resource options: Options to define what info you would like returned. """ return self._call('info', auth, [resource, options], defer)
[ "def", "info", "(", "self", ",", "auth", ",", "resource", ",", "options", "=", "{", "}", ",", "defer", "=", "False", ")", ":", "return", "self", ".", "_call", "(", "'info'", ",", "auth", ",", "[", "resource", ",", "options", "]", ",", "defer", ")" ]
Request creation and usage information of specified resource according to the specified options. Args: auth: <cik> resource: Alias or ID of resource options: Options to define what info you would like returned.
[ "Request", "creation", "and", "usage", "information", "of", "specified", "resource", "according", "to", "the", "specified", "options", "." ]
d27b621b00688a542e0adcc01f3e3354c05238a1
https://github.com/exosite-labs/pyonep/blob/d27b621b00688a542e0adcc01f3e3354c05238a1/pyonep/onep.py#L346-L355
train
exosite-labs/pyonep
pyonep/onep.py
OnepV1.listing
def listing(self, auth, types, options=None, resource=None, defer=False): """This provides backward compatibility with two previous variants of listing. To use the non-deprecated API, pass both options and resource.""" if options is None: # This variant is deprecated return self._call('listing', auth, [types], defer) else: if resource is None: # This variant is deprecated, too return self._call('listing', auth, [types, options], defer) else: # pass resource to use the non-deprecated variant return self._call('listing', auth, [resource, types, options], defer)
python
def listing(self, auth, types, options=None, resource=None, defer=False): """This provides backward compatibility with two previous variants of listing. To use the non-deprecated API, pass both options and resource.""" if options is None: # This variant is deprecated return self._call('listing', auth, [types], defer) else: if resource is None: # This variant is deprecated, too return self._call('listing', auth, [types, options], defer) else: # pass resource to use the non-deprecated variant return self._call('listing', auth, [resource, types, options], defer)
[ "def", "listing", "(", "self", ",", "auth", ",", "types", ",", "options", "=", "None", ",", "resource", "=", "None", ",", "defer", "=", "False", ")", ":", "if", "options", "is", "None", ":", "# This variant is deprecated", "return", "self", ".", "_call", "(", "'listing'", ",", "auth", ",", "[", "types", "]", ",", "defer", ")", "else", ":", "if", "resource", "is", "None", ":", "# This variant is deprecated, too", "return", "self", ".", "_call", "(", "'listing'", ",", "auth", ",", "[", "types", ",", "options", "]", ",", "defer", ")", "else", ":", "# pass resource to use the non-deprecated variant", "return", "self", ".", "_call", "(", "'listing'", ",", "auth", ",", "[", "resource", ",", "types", ",", "options", "]", ",", "defer", ")" ]
This provides backward compatibility with two previous variants of listing. To use the non-deprecated API, pass both options and resource.
[ "This", "provides", "backward", "compatibility", "with", "two", "previous", "variants", "of", "listing", ".", "To", "use", "the", "non", "-", "deprecated", "API", "pass", "both", "options", "and", "resource", "." ]
d27b621b00688a542e0adcc01f3e3354c05238a1
https://github.com/exosite-labs/pyonep/blob/d27b621b00688a542e0adcc01f3e3354c05238a1/pyonep/onep.py#L357-L376
train
exosite-labs/pyonep
pyonep/onep.py
OnepV1.map
def map(self, auth, resource, alias, defer=False): """ Creates an alias for a resource. Args: auth: <cik> resource: <ResourceID> alias: alias to create (map) """ return self._call('map', auth, ['alias', resource, alias], defer)
python
def map(self, auth, resource, alias, defer=False): """ Creates an alias for a resource. Args: auth: <cik> resource: <ResourceID> alias: alias to create (map) """ return self._call('map', auth, ['alias', resource, alias], defer)
[ "def", "map", "(", "self", ",", "auth", ",", "resource", ",", "alias", ",", "defer", "=", "False", ")", ":", "return", "self", ".", "_call", "(", "'map'", ",", "auth", ",", "[", "'alias'", ",", "resource", ",", "alias", "]", ",", "defer", ")" ]
Creates an alias for a resource. Args: auth: <cik> resource: <ResourceID> alias: alias to create (map)
[ "Creates", "an", "alias", "for", "a", "resource", "." ]
d27b621b00688a542e0adcc01f3e3354c05238a1
https://github.com/exosite-labs/pyonep/blob/d27b621b00688a542e0adcc01f3e3354c05238a1/pyonep/onep.py#L389-L397
train
exosite-labs/pyonep
pyonep/onep.py
OnepV1.move
def move(self, auth, resource, destinationresource, options={"aliases": True}, defer=False): """ Moves a resource from one parent client to another. Args: auth: <cik> resource: Identifed resource to be moved. destinationresource: resource of client resource is being moved to. """ return self._call('move', auth, [resource, destinationresource, options], defer)
python
def move(self, auth, resource, destinationresource, options={"aliases": True}, defer=False): """ Moves a resource from one parent client to another. Args: auth: <cik> resource: Identifed resource to be moved. destinationresource: resource of client resource is being moved to. """ return self._call('move', auth, [resource, destinationresource, options], defer)
[ "def", "move", "(", "self", ",", "auth", ",", "resource", ",", "destinationresource", ",", "options", "=", "{", "\"aliases\"", ":", "True", "}", ",", "defer", "=", "False", ")", ":", "return", "self", ".", "_call", "(", "'move'", ",", "auth", ",", "[", "resource", ",", "destinationresource", ",", "options", "]", ",", "defer", ")" ]
Moves a resource from one parent client to another. Args: auth: <cik> resource: Identifed resource to be moved. destinationresource: resource of client resource is being moved to.
[ "Moves", "a", "resource", "from", "one", "parent", "client", "to", "another", "." ]
d27b621b00688a542e0adcc01f3e3354c05238a1
https://github.com/exosite-labs/pyonep/blob/d27b621b00688a542e0adcc01f3e3354c05238a1/pyonep/onep.py#L399-L407
train
exosite-labs/pyonep
pyonep/onep.py
OnepV1.revoke
def revoke(self, auth, codetype, code, defer=False): """ Given an activation code, the associated entity is revoked after which the activation code can no longer be used. Args: auth: Takes the owner's cik codetype: The type of code to revoke (client | share) code: Code specified by <codetype> (cik | share-activation-code) """ return self._call('revoke', auth, [codetype, code], defer)
python
def revoke(self, auth, codetype, code, defer=False): """ Given an activation code, the associated entity is revoked after which the activation code can no longer be used. Args: auth: Takes the owner's cik codetype: The type of code to revoke (client | share) code: Code specified by <codetype> (cik | share-activation-code) """ return self._call('revoke', auth, [codetype, code], defer)
[ "def", "revoke", "(", "self", ",", "auth", ",", "codetype", ",", "code", ",", "defer", "=", "False", ")", ":", "return", "self", ".", "_call", "(", "'revoke'", ",", "auth", ",", "[", "codetype", ",", "code", "]", ",", "defer", ")" ]
Given an activation code, the associated entity is revoked after which the activation code can no longer be used. Args: auth: Takes the owner's cik codetype: The type of code to revoke (client | share) code: Code specified by <codetype> (cik | share-activation-code)
[ "Given", "an", "activation", "code", "the", "associated", "entity", "is", "revoked", "after", "which", "the", "activation", "code", "can", "no", "longer", "be", "used", "." ]
d27b621b00688a542e0adcc01f3e3354c05238a1
https://github.com/exosite-labs/pyonep/blob/d27b621b00688a542e0adcc01f3e3354c05238a1/pyonep/onep.py#L451-L460
train
exosite-labs/pyonep
pyonep/onep.py
OnepV1.share
def share(self, auth, resource, options={}, defer=False): """ Generates a share code for the given resource. Args: auth: <cik> resource: The identifier of the resource. options: Dictonary of options. """ return self._call('share', auth, [resource, options], defer)
python
def share(self, auth, resource, options={}, defer=False): """ Generates a share code for the given resource. Args: auth: <cik> resource: The identifier of the resource. options: Dictonary of options. """ return self._call('share', auth, [resource, options], defer)
[ "def", "share", "(", "self", ",", "auth", ",", "resource", ",", "options", "=", "{", "}", ",", "defer", "=", "False", ")", ":", "return", "self", ".", "_call", "(", "'share'", ",", "auth", ",", "[", "resource", ",", "options", "]", ",", "defer", ")" ]
Generates a share code for the given resource. Args: auth: <cik> resource: The identifier of the resource. options: Dictonary of options.
[ "Generates", "a", "share", "code", "for", "the", "given", "resource", "." ]
d27b621b00688a542e0adcc01f3e3354c05238a1
https://github.com/exosite-labs/pyonep/blob/d27b621b00688a542e0adcc01f3e3354c05238a1/pyonep/onep.py#L462-L470
train
exosite-labs/pyonep
pyonep/onep.py
OnepV1.update
def update(self, auth, resource, desc={}, defer=False): """ Updates the description of the resource. Args: auth: <cik> for authentication resource: Resource to be updated desc: A Dictionary containing the update for the resource. """ return self._call('update', auth, [resource, desc], defer)
python
def update(self, auth, resource, desc={}, defer=False): """ Updates the description of the resource. Args: auth: <cik> for authentication resource: Resource to be updated desc: A Dictionary containing the update for the resource. """ return self._call('update', auth, [resource, desc], defer)
[ "def", "update", "(", "self", ",", "auth", ",", "resource", ",", "desc", "=", "{", "}", ",", "defer", "=", "False", ")", ":", "return", "self", ".", "_call", "(", "'update'", ",", "auth", ",", "[", "resource", ",", "desc", "]", ",", "defer", ")" ]
Updates the description of the resource. Args: auth: <cik> for authentication resource: Resource to be updated desc: A Dictionary containing the update for the resource.
[ "Updates", "the", "description", "of", "the", "resource", "." ]
d27b621b00688a542e0adcc01f3e3354c05238a1
https://github.com/exosite-labs/pyonep/blob/d27b621b00688a542e0adcc01f3e3354c05238a1/pyonep/onep.py#L478-L486
train
exosite-labs/pyonep
pyonep/onep.py
OnepV1.usage
def usage(self, auth, resource, metric, starttime, endtime, defer=False): """ Returns metric usage for client and its subhierarchy. Args: auth: <cik> for authentication resource: ResourceID metrics: Metric to measure (as string), it may be an entity or consumable. starttime: Start time of window to measure useage (format is ___). endtime: End time of window to measure useage (format is ___). """ return self._call('usage', auth, [resource, metric, starttime, endtime], defer)
python
def usage(self, auth, resource, metric, starttime, endtime, defer=False): """ Returns metric usage for client and its subhierarchy. Args: auth: <cik> for authentication resource: ResourceID metrics: Metric to measure (as string), it may be an entity or consumable. starttime: Start time of window to measure useage (format is ___). endtime: End time of window to measure useage (format is ___). """ return self._call('usage', auth, [resource, metric, starttime, endtime], defer)
[ "def", "usage", "(", "self", ",", "auth", ",", "resource", ",", "metric", ",", "starttime", ",", "endtime", ",", "defer", "=", "False", ")", ":", "return", "self", ".", "_call", "(", "'usage'", ",", "auth", ",", "[", "resource", ",", "metric", ",", "starttime", ",", "endtime", "]", ",", "defer", ")" ]
Returns metric usage for client and its subhierarchy. Args: auth: <cik> for authentication resource: ResourceID metrics: Metric to measure (as string), it may be an entity or consumable. starttime: Start time of window to measure useage (format is ___). endtime: End time of window to measure useage (format is ___).
[ "Returns", "metric", "usage", "for", "client", "and", "its", "subhierarchy", "." ]
d27b621b00688a542e0adcc01f3e3354c05238a1
https://github.com/exosite-labs/pyonep/blob/d27b621b00688a542e0adcc01f3e3354c05238a1/pyonep/onep.py#L488-L499
train
exosite-labs/pyonep
pyonep/onep.py
OnepV1.wait
def wait(self, auth, resource, options, defer=False): """ This is a HTTP Long Polling API which allows a user to wait on specific resources to be updated. Args: auth: <cik> for authentication resource: <ResourceID> to specify what resource to wait on. options: Options for the wait including a timeout (in ms), (max 5min) and start time (null acts as when request is recieved) """ # let the server control the timeout return self._call('wait', auth, [resource, options], defer, notimeout=True)
python
def wait(self, auth, resource, options, defer=False): """ This is a HTTP Long Polling API which allows a user to wait on specific resources to be updated. Args: auth: <cik> for authentication resource: <ResourceID> to specify what resource to wait on. options: Options for the wait including a timeout (in ms), (max 5min) and start time (null acts as when request is recieved) """ # let the server control the timeout return self._call('wait', auth, [resource, options], defer, notimeout=True)
[ "def", "wait", "(", "self", ",", "auth", ",", "resource", ",", "options", ",", "defer", "=", "False", ")", ":", "# let the server control the timeout", "return", "self", ".", "_call", "(", "'wait'", ",", "auth", ",", "[", "resource", ",", "options", "]", ",", "defer", ",", "notimeout", "=", "True", ")" ]
This is a HTTP Long Polling API which allows a user to wait on specific resources to be updated. Args: auth: <cik> for authentication resource: <ResourceID> to specify what resource to wait on. options: Options for the wait including a timeout (in ms), (max 5min) and start time (null acts as when request is recieved)
[ "This", "is", "a", "HTTP", "Long", "Polling", "API", "which", "allows", "a", "user", "to", "wait", "on", "specific", "resources", "to", "be", "updated", "." ]
d27b621b00688a542e0adcc01f3e3354c05238a1
https://github.com/exosite-labs/pyonep/blob/d27b621b00688a542e0adcc01f3e3354c05238a1/pyonep/onep.py#L501-L512
train
exosite-labs/pyonep
pyonep/onep.py
OnepV1.write
def write(self, auth, resource, value, options={}, defer=False): """ Writes a single value to the resource specified. Args: auth: cik for authentication. resource: resource to write to. value: value to write options: options. """ return self._call('write', auth, [resource, value, options], defer)
python
def write(self, auth, resource, value, options={}, defer=False): """ Writes a single value to the resource specified. Args: auth: cik for authentication. resource: resource to write to. value: value to write options: options. """ return self._call('write', auth, [resource, value, options], defer)
[ "def", "write", "(", "self", ",", "auth", ",", "resource", ",", "value", ",", "options", "=", "{", "}", ",", "defer", "=", "False", ")", ":", "return", "self", ".", "_call", "(", "'write'", ",", "auth", ",", "[", "resource", ",", "value", ",", "options", "]", ",", "defer", ")" ]
Writes a single value to the resource specified. Args: auth: cik for authentication. resource: resource to write to. value: value to write options: options.
[ "Writes", "a", "single", "value", "to", "the", "resource", "specified", "." ]
d27b621b00688a542e0adcc01f3e3354c05238a1
https://github.com/exosite-labs/pyonep/blob/d27b621b00688a542e0adcc01f3e3354c05238a1/pyonep/onep.py#L514-L523
train
exosite-labs/pyonep
pyonep/onep.py
OnepV1.writegroup
def writegroup(self, auth, entries, defer=False): """ Writes the given values for the respective resources in the list, all writes have same timestamp. Args: auth: cik for authentication. entries: List of key, value lists. eg. [[key, value], [k,v],,,] """ return self._call('writegroup', auth, [entries], defer)
python
def writegroup(self, auth, entries, defer=False): """ Writes the given values for the respective resources in the list, all writes have same timestamp. Args: auth: cik for authentication. entries: List of key, value lists. eg. [[key, value], [k,v],,,] """ return self._call('writegroup', auth, [entries], defer)
[ "def", "writegroup", "(", "self", ",", "auth", ",", "entries", ",", "defer", "=", "False", ")", ":", "return", "self", ".", "_call", "(", "'writegroup'", ",", "auth", ",", "[", "entries", "]", ",", "defer", ")" ]
Writes the given values for the respective resources in the list, all writes have same timestamp. Args: auth: cik for authentication. entries: List of key, value lists. eg. [[key, value], [k,v],,,]
[ "Writes", "the", "given", "values", "for", "the", "respective", "resources", "in", "the", "list", "all", "writes", "have", "same", "timestamp", "." ]
d27b621b00688a542e0adcc01f3e3354c05238a1
https://github.com/exosite-labs/pyonep/blob/d27b621b00688a542e0adcc01f3e3354c05238a1/pyonep/onep.py#L525-L533
train
SHDShim/pytheos
pytheos/eqn_bm3.py
bm3_p
def bm3_p(v, v0, k0, k0p, p_ref=0.0): """ calculate pressure from 3rd order Birch-Murnathan equation :param v: volume at different pressures :param v0: volume at reference conditions :param k0: bulk modulus at reference conditions :param k0p: pressure derivative of bulk modulus at different conditions :param p_ref: reference pressure (default = 0) :return: pressure """ return cal_p_bm3(v, [v0, k0, k0p], p_ref=p_ref)
python
def bm3_p(v, v0, k0, k0p, p_ref=0.0): """ calculate pressure from 3rd order Birch-Murnathan equation :param v: volume at different pressures :param v0: volume at reference conditions :param k0: bulk modulus at reference conditions :param k0p: pressure derivative of bulk modulus at different conditions :param p_ref: reference pressure (default = 0) :return: pressure """ return cal_p_bm3(v, [v0, k0, k0p], p_ref=p_ref)
[ "def", "bm3_p", "(", "v", ",", "v0", ",", "k0", ",", "k0p", ",", "p_ref", "=", "0.0", ")", ":", "return", "cal_p_bm3", "(", "v", ",", "[", "v0", ",", "k0", ",", "k0p", "]", ",", "p_ref", "=", "p_ref", ")" ]
calculate pressure from 3rd order Birch-Murnathan equation :param v: volume at different pressures :param v0: volume at reference conditions :param k0: bulk modulus at reference conditions :param k0p: pressure derivative of bulk modulus at different conditions :param p_ref: reference pressure (default = 0) :return: pressure
[ "calculate", "pressure", "from", "3rd", "order", "Birch", "-", "Murnathan", "equation" ]
be079624405e92fbec60c5ead253eb5917e55237
https://github.com/SHDShim/pytheos/blob/be079624405e92fbec60c5ead253eb5917e55237/pytheos/eqn_bm3.py#L12-L23
train
SHDShim/pytheos
pytheos/eqn_bm3.py
cal_p_bm3
def cal_p_bm3(v, k, p_ref=0.0): """ calculate pressure from 3rd order Birch-Murnaghan equation :param v: volume at different pressures :param k: [v0, k0, k0p] :param p_ref: reference pressure, default = 0. :return: static pressure """ vvr = v / k[0] p = (p_ref - 0.5 * (3. * k[1] - 5. * p_ref) * (1. - vvr**(-2. / 3.)) + 9. / 8. * k[1] * (k[2] - 4. + 35. / 9. * p_ref / k[1]) * (1. - vvr**(-2. / 3.))**2.) * vvr**(-5. / 3.) return p
python
def cal_p_bm3(v, k, p_ref=0.0): """ calculate pressure from 3rd order Birch-Murnaghan equation :param v: volume at different pressures :param k: [v0, k0, k0p] :param p_ref: reference pressure, default = 0. :return: static pressure """ vvr = v / k[0] p = (p_ref - 0.5 * (3. * k[1] - 5. * p_ref) * (1. - vvr**(-2. / 3.)) + 9. / 8. * k[1] * (k[2] - 4. + 35. / 9. * p_ref / k[1]) * (1. - vvr**(-2. / 3.))**2.) * vvr**(-5. / 3.) return p
[ "def", "cal_p_bm3", "(", "v", ",", "k", ",", "p_ref", "=", "0.0", ")", ":", "vvr", "=", "v", "/", "k", "[", "0", "]", "p", "=", "(", "p_ref", "-", "0.5", "*", "(", "3.", "*", "k", "[", "1", "]", "-", "5.", "*", "p_ref", ")", "*", "(", "1.", "-", "vvr", "**", "(", "-", "2.", "/", "3.", ")", ")", "+", "9.", "/", "8.", "*", "k", "[", "1", "]", "*", "(", "k", "[", "2", "]", "-", "4.", "+", "35.", "/", "9.", "*", "p_ref", "/", "k", "[", "1", "]", ")", "*", "(", "1.", "-", "vvr", "**", "(", "-", "2.", "/", "3.", ")", ")", "**", "2.", ")", "*", "vvr", "**", "(", "-", "5.", "/", "3.", ")", "return", "p" ]
calculate pressure from 3rd order Birch-Murnaghan equation :param v: volume at different pressures :param k: [v0, k0, k0p] :param p_ref: reference pressure, default = 0. :return: static pressure
[ "calculate", "pressure", "from", "3rd", "order", "Birch", "-", "Murnaghan", "equation" ]
be079624405e92fbec60c5ead253eb5917e55237
https://github.com/SHDShim/pytheos/blob/be079624405e92fbec60c5ead253eb5917e55237/pytheos/eqn_bm3.py#L26-L39
train
SHDShim/pytheos
pytheos/eqn_bm3.py
bm3_v_single
def bm3_v_single(p, v0, k0, k0p, p_ref=0.0, min_strain=0.01): """ find volume at given pressure using brenth in scipy.optimize this is for single p value, not vectorized this cannot handle uncertainties :param p: pressure :param v0: volume at reference conditions :param k0: bulk modulus at reference conditions :param k0p: pressure derivative of bulk modulus at different conditions :param p_ref: reference pressure (default = 0) :param min_strain: minimum strain value to find solution (default = 0.01) :return: volume at high pressure """ if p <= 1.e-5: return v0 def f_diff(v, v0, k0, k0p, p, p_ref=0.0): return bm3_p(v, v0, k0, k0p, p_ref=p_ref) - p v = brenth(f_diff, v0, v0 * min_strain, args=(v0, k0, k0p, p, p_ref)) return v
python
def bm3_v_single(p, v0, k0, k0p, p_ref=0.0, min_strain=0.01): """ find volume at given pressure using brenth in scipy.optimize this is for single p value, not vectorized this cannot handle uncertainties :param p: pressure :param v0: volume at reference conditions :param k0: bulk modulus at reference conditions :param k0p: pressure derivative of bulk modulus at different conditions :param p_ref: reference pressure (default = 0) :param min_strain: minimum strain value to find solution (default = 0.01) :return: volume at high pressure """ if p <= 1.e-5: return v0 def f_diff(v, v0, k0, k0p, p, p_ref=0.0): return bm3_p(v, v0, k0, k0p, p_ref=p_ref) - p v = brenth(f_diff, v0, v0 * min_strain, args=(v0, k0, k0p, p, p_ref)) return v
[ "def", "bm3_v_single", "(", "p", ",", "v0", ",", "k0", ",", "k0p", ",", "p_ref", "=", "0.0", ",", "min_strain", "=", "0.01", ")", ":", "if", "p", "<=", "1.e-5", ":", "return", "v0", "def", "f_diff", "(", "v", ",", "v0", ",", "k0", ",", "k0p", ",", "p", ",", "p_ref", "=", "0.0", ")", ":", "return", "bm3_p", "(", "v", ",", "v0", ",", "k0", ",", "k0p", ",", "p_ref", "=", "p_ref", ")", "-", "p", "v", "=", "brenth", "(", "f_diff", ",", "v0", ",", "v0", "*", "min_strain", ",", "args", "=", "(", "v0", ",", "k0", ",", "k0p", ",", "p", ",", "p_ref", ")", ")", "return", "v" ]
find volume at given pressure using brenth in scipy.optimize this is for single p value, not vectorized this cannot handle uncertainties :param p: pressure :param v0: volume at reference conditions :param k0: bulk modulus at reference conditions :param k0p: pressure derivative of bulk modulus at different conditions :param p_ref: reference pressure (default = 0) :param min_strain: minimum strain value to find solution (default = 0.01) :return: volume at high pressure
[ "find", "volume", "at", "given", "pressure", "using", "brenth", "in", "scipy", ".", "optimize", "this", "is", "for", "single", "p", "value", "not", "vectorized", "this", "cannot", "handle", "uncertainties" ]
be079624405e92fbec60c5ead253eb5917e55237
https://github.com/SHDShim/pytheos/blob/be079624405e92fbec60c5ead253eb5917e55237/pytheos/eqn_bm3.py#L42-L62
train
SHDShim/pytheos
pytheos/eqn_bm3.py
bm3_k
def bm3_k(p, v0, k0, k0p): """ calculate bulk modulus, wrapper for cal_k_bm3 cannot handle uncertainties :param p: pressure :param v0: volume at reference conditions :param k0: bulk modulus at reference conditions :param k0p: pressure derivative of bulk modulus at different conditions :return: bulk modulus at high pressure """ return cal_k_bm3(p, [v0, k0, k0p])
python
def bm3_k(p, v0, k0, k0p): """ calculate bulk modulus, wrapper for cal_k_bm3 cannot handle uncertainties :param p: pressure :param v0: volume at reference conditions :param k0: bulk modulus at reference conditions :param k0p: pressure derivative of bulk modulus at different conditions :return: bulk modulus at high pressure """ return cal_k_bm3(p, [v0, k0, k0p])
[ "def", "bm3_k", "(", "p", ",", "v0", ",", "k0", ",", "k0p", ")", ":", "return", "cal_k_bm3", "(", "p", ",", "[", "v0", ",", "k0", ",", "k0p", "]", ")" ]
calculate bulk modulus, wrapper for cal_k_bm3 cannot handle uncertainties :param p: pressure :param v0: volume at reference conditions :param k0: bulk modulus at reference conditions :param k0p: pressure derivative of bulk modulus at different conditions :return: bulk modulus at high pressure
[ "calculate", "bulk", "modulus", "wrapper", "for", "cal_k_bm3", "cannot", "handle", "uncertainties" ]
be079624405e92fbec60c5ead253eb5917e55237
https://github.com/SHDShim/pytheos/blob/be079624405e92fbec60c5ead253eb5917e55237/pytheos/eqn_bm3.py#L96-L107
train
SHDShim/pytheos
pytheos/eqn_bm3.py
cal_k_bm3
def cal_k_bm3(p, k): """ calculate bulk modulus :param p: pressure :param k: [v0, k0, k0p] :return: bulk modulus at high pressure """ v = cal_v_bm3(p, k) return cal_k_bm3_from_v(v, k)
python
def cal_k_bm3(p, k): """ calculate bulk modulus :param p: pressure :param k: [v0, k0, k0p] :return: bulk modulus at high pressure """ v = cal_v_bm3(p, k) return cal_k_bm3_from_v(v, k)
[ "def", "cal_k_bm3", "(", "p", ",", "k", ")", ":", "v", "=", "cal_v_bm3", "(", "p", ",", "k", ")", "return", "cal_k_bm3_from_v", "(", "v", ",", "k", ")" ]
calculate bulk modulus :param p: pressure :param k: [v0, k0, k0p] :return: bulk modulus at high pressure
[ "calculate", "bulk", "modulus" ]
be079624405e92fbec60c5ead253eb5917e55237
https://github.com/SHDShim/pytheos/blob/be079624405e92fbec60c5ead253eb5917e55237/pytheos/eqn_bm3.py#L143-L152
train
SHDShim/pytheos
pytheos/eqn_bm3.py
bm3_g
def bm3_g(p, v0, g0, g0p, k0, k0p): """ calculate shear modulus at given pressure. not fully tested with mdaap. :param p: pressure :param v0: volume at reference condition :param g0: shear modulus at reference condition :param g0p: pressure derivative of shear modulus at reference condition :param k0: bulk modulus at reference condition :param k0p: pressure derivative of bulk modulus at reference condition :return: shear modulus at high pressure """ return cal_g_bm3(p, [g0, g0p], [v0, k0, k0p])
python
def bm3_g(p, v0, g0, g0p, k0, k0p): """ calculate shear modulus at given pressure. not fully tested with mdaap. :param p: pressure :param v0: volume at reference condition :param g0: shear modulus at reference condition :param g0p: pressure derivative of shear modulus at reference condition :param k0: bulk modulus at reference condition :param k0p: pressure derivative of bulk modulus at reference condition :return: shear modulus at high pressure """ return cal_g_bm3(p, [g0, g0p], [v0, k0, k0p])
[ "def", "bm3_g", "(", "p", ",", "v0", ",", "g0", ",", "g0p", ",", "k0", ",", "k0p", ")", ":", "return", "cal_g_bm3", "(", "p", ",", "[", "g0", ",", "g0p", "]", ",", "[", "v0", ",", "k0", ",", "k0p", "]", ")" ]
calculate shear modulus at given pressure. not fully tested with mdaap. :param p: pressure :param v0: volume at reference condition :param g0: shear modulus at reference condition :param g0p: pressure derivative of shear modulus at reference condition :param k0: bulk modulus at reference condition :param k0p: pressure derivative of bulk modulus at reference condition :return: shear modulus at high pressure
[ "calculate", "shear", "modulus", "at", "given", "pressure", ".", "not", "fully", "tested", "with", "mdaap", "." ]
be079624405e92fbec60c5ead253eb5917e55237
https://github.com/SHDShim/pytheos/blob/be079624405e92fbec60c5ead253eb5917e55237/pytheos/eqn_bm3.py#L168-L181
train
SHDShim/pytheos
pytheos/eqn_bm3.py
cal_g_bm3
def cal_g_bm3(p, g, k): """ calculate shear modulus at given pressure :param p: pressure :param g: [g0, g0p] :param k: [v0, k0, k0p] :return: shear modulus at high pressure """ v = cal_v_bm3(p, k) v0 = k[0] k0 = k[1] kp = k[2] g0 = g[0] gp = g[1] f = 0.5 * ((v / v0)**(-2. / 3.) - 1.) return (1. + 2. * f)**(5. / 2.) * (g0 + (3. * k0 * gp - 5. * g0) * f + (6. * k0 * gp - 24. * k0 - 14. * g0 + 9. / 2. * k0 * kp) * f**2.)
python
def cal_g_bm3(p, g, k): """ calculate shear modulus at given pressure :param p: pressure :param g: [g0, g0p] :param k: [v0, k0, k0p] :return: shear modulus at high pressure """ v = cal_v_bm3(p, k) v0 = k[0] k0 = k[1] kp = k[2] g0 = g[0] gp = g[1] f = 0.5 * ((v / v0)**(-2. / 3.) - 1.) return (1. + 2. * f)**(5. / 2.) * (g0 + (3. * k0 * gp - 5. * g0) * f + (6. * k0 * gp - 24. * k0 - 14. * g0 + 9. / 2. * k0 * kp) * f**2.)
[ "def", "cal_g_bm3", "(", "p", ",", "g", ",", "k", ")", ":", "v", "=", "cal_v_bm3", "(", "p", ",", "k", ")", "v0", "=", "k", "[", "0", "]", "k0", "=", "k", "[", "1", "]", "kp", "=", "k", "[", "2", "]", "g0", "=", "g", "[", "0", "]", "gp", "=", "g", "[", "1", "]", "f", "=", "0.5", "*", "(", "(", "v", "/", "v0", ")", "**", "(", "-", "2.", "/", "3.", ")", "-", "1.", ")", "return", "(", "1.", "+", "2.", "*", "f", ")", "**", "(", "5.", "/", "2.", ")", "*", "(", "g0", "+", "(", "3.", "*", "k0", "*", "gp", "-", "5.", "*", "g0", ")", "*", "f", "+", "(", "6.", "*", "k0", "*", "gp", "-", "24.", "*", "k0", "-", "14.", "*", "g0", "+", "9.", "/", "2.", "*", "k0", "*", "kp", ")", "*", "f", "**", "2.", ")" ]
calculate shear modulus at given pressure :param p: pressure :param g: [g0, g0p] :param k: [v0, k0, k0p] :return: shear modulus at high pressure
[ "calculate", "shear", "modulus", "at", "given", "pressure" ]
be079624405e92fbec60c5ead253eb5917e55237
https://github.com/SHDShim/pytheos/blob/be079624405e92fbec60c5ead253eb5917e55237/pytheos/eqn_bm3.py#L184-L202
train
SHDShim/pytheos
pytheos/eqn_bm3.py
bm3_big_F
def bm3_big_F(p, v, v0): """ calculate big F for linearlized form not fully tested :param p: :param f: :return: """ f = bm3_small_f(v, v0) return cal_big_F(p, f)
python
def bm3_big_F(p, v, v0): """ calculate big F for linearlized form not fully tested :param p: :param f: :return: """ f = bm3_small_f(v, v0) return cal_big_F(p, f)
[ "def", "bm3_big_F", "(", "p", ",", "v", ",", "v0", ")", ":", "f", "=", "bm3_small_f", "(", "v", ",", "v0", ")", "return", "cal_big_F", "(", "p", ",", "f", ")" ]
calculate big F for linearlized form not fully tested :param p: :param f: :return:
[ "calculate", "big", "F", "for", "linearlized", "form", "not", "fully", "tested" ]
be079624405e92fbec60c5ead253eb5917e55237
https://github.com/SHDShim/pytheos/blob/be079624405e92fbec60c5ead253eb5917e55237/pytheos/eqn_bm3.py#L217-L227
train
dingusdk/PythonIhcSdk
ihcsdk/ihcsslconnection.py
TLSv1Adapter.init_poolmanager
def init_poolmanager(self, connections, maxsize, block=requests.adapters.DEFAULT_POOLBLOCK, **pool_kwargs): """Initialize poolmanager with cipher and Tlsv1""" context = create_urllib3_context(ciphers=self.CIPHERS, ssl_version=ssl.PROTOCOL_TLSv1) pool_kwargs['ssl_context'] = context return super(TLSv1Adapter, self).init_poolmanager(connections, maxsize, block, **pool_kwargs)
python
def init_poolmanager(self, connections, maxsize, block=requests.adapters.DEFAULT_POOLBLOCK, **pool_kwargs): """Initialize poolmanager with cipher and Tlsv1""" context = create_urllib3_context(ciphers=self.CIPHERS, ssl_version=ssl.PROTOCOL_TLSv1) pool_kwargs['ssl_context'] = context return super(TLSv1Adapter, self).init_poolmanager(connections, maxsize, block, **pool_kwargs)
[ "def", "init_poolmanager", "(", "self", ",", "connections", ",", "maxsize", ",", "block", "=", "requests", ".", "adapters", ".", "DEFAULT_POOLBLOCK", ",", "*", "*", "pool_kwargs", ")", ":", "context", "=", "create_urllib3_context", "(", "ciphers", "=", "self", ".", "CIPHERS", ",", "ssl_version", "=", "ssl", ".", "PROTOCOL_TLSv1", ")", "pool_kwargs", "[", "'ssl_context'", "]", "=", "context", "return", "super", "(", "TLSv1Adapter", ",", "self", ")", ".", "init_poolmanager", "(", "connections", ",", "maxsize", ",", "block", ",", "*", "*", "pool_kwargs", ")" ]
Initialize poolmanager with cipher and Tlsv1
[ "Initialize", "poolmanager", "with", "cipher", "and", "Tlsv1" ]
7e2067e009fe7600b49f30bff1cf91dc72fc891e
https://github.com/dingusdk/PythonIhcSdk/blob/7e2067e009fe7600b49f30bff1cf91dc72fc891e/ihcsdk/ihcsslconnection.py#L47-L55
train
dingusdk/PythonIhcSdk
ihcsdk/ihcsslconnection.py
TLSv1Adapter.proxy_manager_for
def proxy_manager_for(self, proxy, **proxy_kwargs): """Ensure cipher and Tlsv1""" context = create_urllib3_context(ciphers=self.CIPHERS, ssl_version=ssl.PROTOCOL_TLSv1) proxy_kwargs['ssl_context'] = context return super(TLSv1Adapter, self).proxy_manager_for(proxy, **proxy_kwargs)
python
def proxy_manager_for(self, proxy, **proxy_kwargs): """Ensure cipher and Tlsv1""" context = create_urllib3_context(ciphers=self.CIPHERS, ssl_version=ssl.PROTOCOL_TLSv1) proxy_kwargs['ssl_context'] = context return super(TLSv1Adapter, self).proxy_manager_for(proxy, **proxy_kwargs)
[ "def", "proxy_manager_for", "(", "self", ",", "proxy", ",", "*", "*", "proxy_kwargs", ")", ":", "context", "=", "create_urllib3_context", "(", "ciphers", "=", "self", ".", "CIPHERS", ",", "ssl_version", "=", "ssl", ".", "PROTOCOL_TLSv1", ")", "proxy_kwargs", "[", "'ssl_context'", "]", "=", "context", "return", "super", "(", "TLSv1Adapter", ",", "self", ")", ".", "proxy_manager_for", "(", "proxy", ",", "*", "*", "proxy_kwargs", ")" ]
Ensure cipher and Tlsv1
[ "Ensure", "cipher", "and", "Tlsv1" ]
7e2067e009fe7600b49f30bff1cf91dc72fc891e
https://github.com/dingusdk/PythonIhcSdk/blob/7e2067e009fe7600b49f30bff1cf91dc72fc891e/ihcsdk/ihcsslconnection.py#L57-L63
train
aiidateam/aiida-codtools
aiida_codtools/parsers/cif_cell_contents.py
CifCellContentsParser.parse_stdout
def parse_stdout(self, filelike): """Parse the formulae from the content written by the script to standard out. :param filelike: filelike object of stdout :returns: an exit code in case of an error, None otherwise """ from aiida.orm import Dict formulae = {} content = filelike.read().strip() if not content: return self.exit_codes.ERROR_EMPTY_OUTPUT_FILE try: for line in content.split('\n'): datablock, formula = re.split(r'\s+', line.strip(), 1) formulae[datablock] = formula except Exception: # pylint: disable=broad-except self.logger.exception('Failed to parse formulae from the stdout file\n%s', traceback.format_exc()) return self.exit_codes.ERROR_PARSING_OUTPUT_DATA else: self.out('formulae', Dict(dict=formulae)) return
python
def parse_stdout(self, filelike): """Parse the formulae from the content written by the script to standard out. :param filelike: filelike object of stdout :returns: an exit code in case of an error, None otherwise """ from aiida.orm import Dict formulae = {} content = filelike.read().strip() if not content: return self.exit_codes.ERROR_EMPTY_OUTPUT_FILE try: for line in content.split('\n'): datablock, formula = re.split(r'\s+', line.strip(), 1) formulae[datablock] = formula except Exception: # pylint: disable=broad-except self.logger.exception('Failed to parse formulae from the stdout file\n%s', traceback.format_exc()) return self.exit_codes.ERROR_PARSING_OUTPUT_DATA else: self.out('formulae', Dict(dict=formulae)) return
[ "def", "parse_stdout", "(", "self", ",", "filelike", ")", ":", "from", "aiida", ".", "orm", "import", "Dict", "formulae", "=", "{", "}", "content", "=", "filelike", ".", "read", "(", ")", ".", "strip", "(", ")", "if", "not", "content", ":", "return", "self", ".", "exit_codes", ".", "ERROR_EMPTY_OUTPUT_FILE", "try", ":", "for", "line", "in", "content", ".", "split", "(", "'\\n'", ")", ":", "datablock", ",", "formula", "=", "re", ".", "split", "(", "r'\\s+'", ",", "line", ".", "strip", "(", ")", ",", "1", ")", "formulae", "[", "datablock", "]", "=", "formula", "except", "Exception", ":", "# pylint: disable=broad-except", "self", ".", "logger", ".", "exception", "(", "'Failed to parse formulae from the stdout file\\n%s'", ",", "traceback", ".", "format_exc", "(", ")", ")", "return", "self", ".", "exit_codes", ".", "ERROR_PARSING_OUTPUT_DATA", "else", ":", "self", ".", "out", "(", "'formulae'", ",", "Dict", "(", "dict", "=", "formulae", ")", ")", "return" ]
Parse the formulae from the content written by the script to standard out. :param filelike: filelike object of stdout :returns: an exit code in case of an error, None otherwise
[ "Parse", "the", "formulae", "from", "the", "content", "written", "by", "the", "script", "to", "standard", "out", "." ]
da5e4259b7a2e86cf0cc3f997e11dd36d445fa94
https://github.com/aiidateam/aiida-codtools/blob/da5e4259b7a2e86cf0cc3f997e11dd36d445fa94/aiida_codtools/parsers/cif_cell_contents.py#L18-L42
train
xflr6/features
features/__init__.py
make_features
def make_features(context, frmat='table', str_maximal=False): """Return a new feature system from context string in the given format. Args: context (str): Formal context table as plain-text string. frmat: Format of the context string (``'table'``, ``'cxt'``, ``'csv'``). str_maximal (bool): Example: >>> make_features(''' ... |+male|-male|+adult|-adult| ... man | X | | X | | ... woman| | X | X | | ... boy | X | | | X | ... girl | | X | | X | ... ''') # doctest: +ELLIPSIS <FeatureSystem object of 4 atoms 10 featuresets at 0x...> """ config = Config.create(context=context, format=frmat, str_maximal=str_maximal) return FeatureSystem(config)
python
def make_features(context, frmat='table', str_maximal=False): """Return a new feature system from context string in the given format. Args: context (str): Formal context table as plain-text string. frmat: Format of the context string (``'table'``, ``'cxt'``, ``'csv'``). str_maximal (bool): Example: >>> make_features(''' ... |+male|-male|+adult|-adult| ... man | X | | X | | ... woman| | X | X | | ... boy | X | | | X | ... girl | | X | | X | ... ''') # doctest: +ELLIPSIS <FeatureSystem object of 4 atoms 10 featuresets at 0x...> """ config = Config.create(context=context, format=frmat, str_maximal=str_maximal) return FeatureSystem(config)
[ "def", "make_features", "(", "context", ",", "frmat", "=", "'table'", ",", "str_maximal", "=", "False", ")", ":", "config", "=", "Config", ".", "create", "(", "context", "=", "context", ",", "format", "=", "frmat", ",", "str_maximal", "=", "str_maximal", ")", "return", "FeatureSystem", "(", "config", ")" ]
Return a new feature system from context string in the given format. Args: context (str): Formal context table as plain-text string. frmat: Format of the context string (``'table'``, ``'cxt'``, ``'csv'``). str_maximal (bool): Example: >>> make_features(''' ... |+male|-male|+adult|-adult| ... man | X | | X | | ... woman| | X | X | | ... boy | X | | | X | ... girl | | X | | X | ... ''') # doctest: +ELLIPSIS <FeatureSystem object of 4 atoms 10 featuresets at 0x...>
[ "Return", "a", "new", "feature", "system", "from", "context", "string", "in", "the", "given", "format", "." ]
f985304dd642da6ecdc66d85167d00daa4efe5f4
https://github.com/xflr6/features/blob/f985304dd642da6ecdc66d85167d00daa4efe5f4/features/__init__.py#L31-L50
train
SHDShim/pytheos
pytheos/eqn_vinet.py
vinet_p
def vinet_p(v, v0, k0, k0p): """ calculate pressure from vinet equation :param v: unit-cell volume in A^3 :param v0: unit-cell volume in A^3 at 1 bar :param k0: bulk modulus at reference conditions :param k0p: pressure derivative of bulk modulus at reference conditions :return: pressure in GPa """ # unumpy.exp works for both numpy and unumpy # so I set uncertainty default. # if unumpy.exp is used for lmfit, it generates an error return cal_p_vinet(v, [v0, k0, k0p], uncertainties=isuncertainties([v, v0, k0, k0p]))
python
def vinet_p(v, v0, k0, k0p): """ calculate pressure from vinet equation :param v: unit-cell volume in A^3 :param v0: unit-cell volume in A^3 at 1 bar :param k0: bulk modulus at reference conditions :param k0p: pressure derivative of bulk modulus at reference conditions :return: pressure in GPa """ # unumpy.exp works for both numpy and unumpy # so I set uncertainty default. # if unumpy.exp is used for lmfit, it generates an error return cal_p_vinet(v, [v0, k0, k0p], uncertainties=isuncertainties([v, v0, k0, k0p]))
[ "def", "vinet_p", "(", "v", ",", "v0", ",", "k0", ",", "k0p", ")", ":", "# unumpy.exp works for both numpy and unumpy", "# so I set uncertainty default.", "# if unumpy.exp is used for lmfit, it generates an error", "return", "cal_p_vinet", "(", "v", ",", "[", "v0", ",", "k0", ",", "k0p", "]", ",", "uncertainties", "=", "isuncertainties", "(", "[", "v", ",", "v0", ",", "k0", ",", "k0p", "]", ")", ")" ]
calculate pressure from vinet equation :param v: unit-cell volume in A^3 :param v0: unit-cell volume in A^3 at 1 bar :param k0: bulk modulus at reference conditions :param k0p: pressure derivative of bulk modulus at reference conditions :return: pressure in GPa
[ "calculate", "pressure", "from", "vinet", "equation" ]
be079624405e92fbec60c5ead253eb5917e55237
https://github.com/SHDShim/pytheos/blob/be079624405e92fbec60c5ead253eb5917e55237/pytheos/eqn_vinet.py#L13-L27
train
SHDShim/pytheos
pytheos/eqn_vinet.py
vinet_v_single
def vinet_v_single(p, v0, k0, k0p, min_strain=0.01): """ find volume at given pressure using brenth in scipy.optimize this is for single p value, not vectorized :param p: pressure in GPa :param v0: unit-cell volume in A^3 at 1 bar :param k0: bulk modulus at reference conditions :param k0p: pressure derivative of bulk modulus at reference conditions :param min_strain: defining minimum v/v0 value to search volume for :return: unit cell volume at high pressure in A^3 """ if p <= 1.e-5: return v0 def f_diff(v, v0, k0, k0p, p): return vinet_p(v, v0, k0, k0p) - p v = brenth(f_diff, v0, v0 * min_strain, args=(v0, k0, k0p, p)) return v
python
def vinet_v_single(p, v0, k0, k0p, min_strain=0.01): """ find volume at given pressure using brenth in scipy.optimize this is for single p value, not vectorized :param p: pressure in GPa :param v0: unit-cell volume in A^3 at 1 bar :param k0: bulk modulus at reference conditions :param k0p: pressure derivative of bulk modulus at reference conditions :param min_strain: defining minimum v/v0 value to search volume for :return: unit cell volume at high pressure in A^3 """ if p <= 1.e-5: return v0 def f_diff(v, v0, k0, k0p, p): return vinet_p(v, v0, k0, k0p) - p v = brenth(f_diff, v0, v0 * min_strain, args=(v0, k0, k0p, p)) return v
[ "def", "vinet_v_single", "(", "p", ",", "v0", ",", "k0", ",", "k0p", ",", "min_strain", "=", "0.01", ")", ":", "if", "p", "<=", "1.e-5", ":", "return", "v0", "def", "f_diff", "(", "v", ",", "v0", ",", "k0", ",", "k0p", ",", "p", ")", ":", "return", "vinet_p", "(", "v", ",", "v0", ",", "k0", ",", "k0p", ")", "-", "p", "v", "=", "brenth", "(", "f_diff", ",", "v0", ",", "v0", "*", "min_strain", ",", "args", "=", "(", "v0", ",", "k0", ",", "k0p", ",", "p", ")", ")", "return", "v" ]
find volume at given pressure using brenth in scipy.optimize this is for single p value, not vectorized :param p: pressure in GPa :param v0: unit-cell volume in A^3 at 1 bar :param k0: bulk modulus at reference conditions :param k0p: pressure derivative of bulk modulus at reference conditions :param min_strain: defining minimum v/v0 value to search volume for :return: unit cell volume at high pressure in A^3
[ "find", "volume", "at", "given", "pressure", "using", "brenth", "in", "scipy", ".", "optimize", "this", "is", "for", "single", "p", "value", "not", "vectorized" ]
be079624405e92fbec60c5ead253eb5917e55237
https://github.com/SHDShim/pytheos/blob/be079624405e92fbec60c5ead253eb5917e55237/pytheos/eqn_vinet.py#L53-L71
train
SHDShim/pytheos
pytheos/eqn_vinet.py
vinet_v
def vinet_v(p, v0, k0, k0p, min_strain=0.01): """ find volume at given pressure :param p: pressure in GPa :param v0: unit-cell volume in A^3 at 1 bar :param k0: bulk modulus at reference conditions :param k0p: pressure derivative of bulk modulus at reference conditions :param min_strain: defining minimum v/v0 value to search volume for :return: unit cell volume at high pressure in A^3 :note: wrapper function vetorizing vinet_v_single """ if isuncertainties([p, v0, k0, k0p]): f_u = np.vectorize(uct.wrap(vinet_v_single), excluded=[1, 2, 3, 4]) return f_u(p, v0, k0, k0p, min_strain=min_strain) else: f_v = np.vectorize(vinet_v_single, excluded=[1, 2, 3, 4]) return f_v(p, v0, k0, k0p, min_strain=min_strain)
python
def vinet_v(p, v0, k0, k0p, min_strain=0.01): """ find volume at given pressure :param p: pressure in GPa :param v0: unit-cell volume in A^3 at 1 bar :param k0: bulk modulus at reference conditions :param k0p: pressure derivative of bulk modulus at reference conditions :param min_strain: defining minimum v/v0 value to search volume for :return: unit cell volume at high pressure in A^3 :note: wrapper function vetorizing vinet_v_single """ if isuncertainties([p, v0, k0, k0p]): f_u = np.vectorize(uct.wrap(vinet_v_single), excluded=[1, 2, 3, 4]) return f_u(p, v0, k0, k0p, min_strain=min_strain) else: f_v = np.vectorize(vinet_v_single, excluded=[1, 2, 3, 4]) return f_v(p, v0, k0, k0p, min_strain=min_strain)
[ "def", "vinet_v", "(", "p", ",", "v0", ",", "k0", ",", "k0p", ",", "min_strain", "=", "0.01", ")", ":", "if", "isuncertainties", "(", "[", "p", ",", "v0", ",", "k0", ",", "k0p", "]", ")", ":", "f_u", "=", "np", ".", "vectorize", "(", "uct", ".", "wrap", "(", "vinet_v_single", ")", ",", "excluded", "=", "[", "1", ",", "2", ",", "3", ",", "4", "]", ")", "return", "f_u", "(", "p", ",", "v0", ",", "k0", ",", "k0p", ",", "min_strain", "=", "min_strain", ")", "else", ":", "f_v", "=", "np", ".", "vectorize", "(", "vinet_v_single", ",", "excluded", "=", "[", "1", ",", "2", ",", "3", ",", "4", "]", ")", "return", "f_v", "(", "p", ",", "v0", ",", "k0", ",", "k0p", ",", "min_strain", "=", "min_strain", ")" ]
find volume at given pressure :param p: pressure in GPa :param v0: unit-cell volume in A^3 at 1 bar :param k0: bulk modulus at reference conditions :param k0p: pressure derivative of bulk modulus at reference conditions :param min_strain: defining minimum v/v0 value to search volume for :return: unit cell volume at high pressure in A^3 :note: wrapper function vetorizing vinet_v_single
[ "find", "volume", "at", "given", "pressure" ]
be079624405e92fbec60c5ead253eb5917e55237
https://github.com/SHDShim/pytheos/blob/be079624405e92fbec60c5ead253eb5917e55237/pytheos/eqn_vinet.py#L74-L91
train
SHDShim/pytheos
pytheos/eqn_vinet.py
vinet_k
def vinet_k(p, v0, k0, k0p, numerical=False): """ calculate bulk modulus, wrapper for cal_k_vinet cannot handle uncertainties :param p: pressure in GPa :param v0: unit-cell volume in A^3 at 1 bar :param k0: bulk modulus at reference conditions :param k0p: pressure derivative of bulk modulus at reference conditions :return: bulk modulus at high pressure in GPa """ f_u = uct.wrap(cal_k_vinet) return f_u(p, [v0, k0, k0p])
python
def vinet_k(p, v0, k0, k0p, numerical=False): """ calculate bulk modulus, wrapper for cal_k_vinet cannot handle uncertainties :param p: pressure in GPa :param v0: unit-cell volume in A^3 at 1 bar :param k0: bulk modulus at reference conditions :param k0p: pressure derivative of bulk modulus at reference conditions :return: bulk modulus at high pressure in GPa """ f_u = uct.wrap(cal_k_vinet) return f_u(p, [v0, k0, k0p])
[ "def", "vinet_k", "(", "p", ",", "v0", ",", "k0", ",", "k0p", ",", "numerical", "=", "False", ")", ":", "f_u", "=", "uct", ".", "wrap", "(", "cal_k_vinet", ")", "return", "f_u", "(", "p", ",", "[", "v0", ",", "k0", ",", "k0p", "]", ")" ]
calculate bulk modulus, wrapper for cal_k_vinet cannot handle uncertainties :param p: pressure in GPa :param v0: unit-cell volume in A^3 at 1 bar :param k0: bulk modulus at reference conditions :param k0p: pressure derivative of bulk modulus at reference conditions :return: bulk modulus at high pressure in GPa
[ "calculate", "bulk", "modulus", "wrapper", "for", "cal_k_vinet", "cannot", "handle", "uncertainties" ]
be079624405e92fbec60c5ead253eb5917e55237
https://github.com/SHDShim/pytheos/blob/be079624405e92fbec60c5ead253eb5917e55237/pytheos/eqn_vinet.py#L106-L118
train
exosite-labs/pyonep
pyonep/portals/__init__.py
Portals.user_portals_picker
def user_portals_picker(self): """ This function is broken and needs to either be fixed or discarded. User-Interaction function. Allows user to choose which Portal to make the active one. """ # print("Getting Portals list. This could take a few seconds...") portals = self.get_portals_list() done = False while not done: opts = [ (i, p) for i, p in enumerate(portals) ] # print('') for opt, portal in opts: print("\t{0} - {1}".format(opt, portal[1])) # print('') valid_choices = [o[0] for o in opts] choice = _input("Enter choice ({0}): ".format(valid_choices) ) if int(choice) in valid_choices: done = True # loop through all portals until we find an 'id':'rid' match self.set_portal_name( opts[int(choice)][1][1] ) self.set_portal_id( opts[int(choice)][1][0] ) # self.set_portal_rid( opts[int(choice)][1][2][1]['info']['key'] ) # self.__portal_sn_rid_dict = opts[int(choice)][1][2][1]['info']['aliases'] else: print("'{0}' is not a valid choice. Please choose from {1}".format( choice, valid_choices))
python
def user_portals_picker(self): """ This function is broken and needs to either be fixed or discarded. User-Interaction function. Allows user to choose which Portal to make the active one. """ # print("Getting Portals list. This could take a few seconds...") portals = self.get_portals_list() done = False while not done: opts = [ (i, p) for i, p in enumerate(portals) ] # print('') for opt, portal in opts: print("\t{0} - {1}".format(opt, portal[1])) # print('') valid_choices = [o[0] for o in opts] choice = _input("Enter choice ({0}): ".format(valid_choices) ) if int(choice) in valid_choices: done = True # loop through all portals until we find an 'id':'rid' match self.set_portal_name( opts[int(choice)][1][1] ) self.set_portal_id( opts[int(choice)][1][0] ) # self.set_portal_rid( opts[int(choice)][1][2][1]['info']['key'] ) # self.__portal_sn_rid_dict = opts[int(choice)][1][2][1]['info']['aliases'] else: print("'{0}' is not a valid choice. Please choose from {1}".format( choice, valid_choices))
[ "def", "user_portals_picker", "(", "self", ")", ":", "# print(\"Getting Portals list. This could take a few seconds...\")", "portals", "=", "self", ".", "get_portals_list", "(", ")", "done", "=", "False", "while", "not", "done", ":", "opts", "=", "[", "(", "i", ",", "p", ")", "for", "i", ",", "p", "in", "enumerate", "(", "portals", ")", "]", "# print('')", "for", "opt", ",", "portal", "in", "opts", ":", "print", "(", "\"\\t{0} - {1}\"", ".", "format", "(", "opt", ",", "portal", "[", "1", "]", ")", ")", "# print('')", "valid_choices", "=", "[", "o", "[", "0", "]", "for", "o", "in", "opts", "]", "choice", "=", "_input", "(", "\"Enter choice ({0}): \"", ".", "format", "(", "valid_choices", ")", ")", "if", "int", "(", "choice", ")", "in", "valid_choices", ":", "done", "=", "True", "# loop through all portals until we find an 'id':'rid' match", "self", ".", "set_portal_name", "(", "opts", "[", "int", "(", "choice", ")", "]", "[", "1", "]", "[", "1", "]", ")", "self", ".", "set_portal_id", "(", "opts", "[", "int", "(", "choice", ")", "]", "[", "1", "]", "[", "0", "]", ")", "# self.set_portal_rid( opts[int(choice)][1][2][1]['info']['key'] )", "# self.__portal_sn_rid_dict = opts[int(choice)][1][2][1]['info']['aliases']", "else", ":", "print", "(", "\"'{0}' is not a valid choice. Please choose from {1}\"", ".", "format", "(", "choice", ",", "valid_choices", ")", ")" ]
This function is broken and needs to either be fixed or discarded. User-Interaction function. Allows user to choose which Portal to make the active one.
[ "This", "function", "is", "broken", "and", "needs", "to", "either", "be", "fixed", "or", "discarded", "." ]
d27b621b00688a542e0adcc01f3e3354c05238a1
https://github.com/exosite-labs/pyonep/blob/d27b621b00688a542e0adcc01f3e3354c05238a1/pyonep/portals/__init__.py#L59-L88
train
exosite-labs/pyonep
pyonep/portals/__init__.py
Portals.get_portal_by_name
def get_portal_by_name(self, portal_name): """ Set active portal according to the name passed in 'portal_name'. Returns dictionary of device 'serial_number: rid' """ portals = self.get_portals_list() for p in portals: # print("Checking {!r}".format(p)) if portal_name == p[1]: # print("Found Portal!") self.set_portal_name( p[1] ) self.set_portal_id( p[0] ) self.set_portal_cik( p[2][1]['info']['key'] ) # print("Active Portal Details:\nName: {0}\nId: {1}\nCIK: {2}".format( # self.portal_name(), # self.portal_id(), # self.portal_cik())) return p return None
python
def get_portal_by_name(self, portal_name): """ Set active portal according to the name passed in 'portal_name'. Returns dictionary of device 'serial_number: rid' """ portals = self.get_portals_list() for p in portals: # print("Checking {!r}".format(p)) if portal_name == p[1]: # print("Found Portal!") self.set_portal_name( p[1] ) self.set_portal_id( p[0] ) self.set_portal_cik( p[2][1]['info']['key'] ) # print("Active Portal Details:\nName: {0}\nId: {1}\nCIK: {2}".format( # self.portal_name(), # self.portal_id(), # self.portal_cik())) return p return None
[ "def", "get_portal_by_name", "(", "self", ",", "portal_name", ")", ":", "portals", "=", "self", ".", "get_portals_list", "(", ")", "for", "p", "in", "portals", ":", "# print(\"Checking {!r}\".format(p))", "if", "portal_name", "==", "p", "[", "1", "]", ":", "# print(\"Found Portal!\")", "self", ".", "set_portal_name", "(", "p", "[", "1", "]", ")", "self", ".", "set_portal_id", "(", "p", "[", "0", "]", ")", "self", ".", "set_portal_cik", "(", "p", "[", "2", "]", "[", "1", "]", "[", "'info'", "]", "[", "'key'", "]", ")", "# print(\"Active Portal Details:\\nName: {0}\\nId: {1}\\nCIK: {2}\".format(", "# self.portal_name(),", "# self.portal_id(),", "# self.portal_cik()))", "return", "p", "return", "None" ]
Set active portal according to the name passed in 'portal_name'. Returns dictionary of device 'serial_number: rid'
[ "Set", "active", "portal", "according", "to", "the", "name", "passed", "in", "portal_name", "." ]
d27b621b00688a542e0adcc01f3e3354c05238a1
https://github.com/exosite-labs/pyonep/blob/d27b621b00688a542e0adcc01f3e3354c05238a1/pyonep/portals/__init__.py#L91-L111
train
exosite-labs/pyonep
pyonep/portals/__init__.py
Portals.delete_device
def delete_device(self, rid): """ Deletes device object with given rid http://docs.exosite.com/portals/#delete-device """ headers = { 'User-Agent': self.user_agent(), 'Content-Type': self.content_type() } headers.update(self.headers()) r = requests.delete( self.portals_url()+'/devices/'+rid, headers=headers, auth=self.auth()) if HTTP_STATUS.NO_CONTENT == r.status_code: print("Successfully deleted device with rid: {0}".format(rid)) return True else: print("Something went wrong: <{0}>: {1}".format( r.status_code, r.reason)) r.raise_for_status() return False
python
def delete_device(self, rid): """ Deletes device object with given rid http://docs.exosite.com/portals/#delete-device """ headers = { 'User-Agent': self.user_agent(), 'Content-Type': self.content_type() } headers.update(self.headers()) r = requests.delete( self.portals_url()+'/devices/'+rid, headers=headers, auth=self.auth()) if HTTP_STATUS.NO_CONTENT == r.status_code: print("Successfully deleted device with rid: {0}".format(rid)) return True else: print("Something went wrong: <{0}>: {1}".format( r.status_code, r.reason)) r.raise_for_status() return False
[ "def", "delete_device", "(", "self", ",", "rid", ")", ":", "headers", "=", "{", "'User-Agent'", ":", "self", ".", "user_agent", "(", ")", ",", "'Content-Type'", ":", "self", ".", "content_type", "(", ")", "}", "headers", ".", "update", "(", "self", ".", "headers", "(", ")", ")", "r", "=", "requests", ".", "delete", "(", "self", ".", "portals_url", "(", ")", "+", "'/devices/'", "+", "rid", ",", "headers", "=", "headers", ",", "auth", "=", "self", ".", "auth", "(", ")", ")", "if", "HTTP_STATUS", ".", "NO_CONTENT", "==", "r", ".", "status_code", ":", "print", "(", "\"Successfully deleted device with rid: {0}\"", ".", "format", "(", "rid", ")", ")", "return", "True", "else", ":", "print", "(", "\"Something went wrong: <{0}>: {1}\"", ".", "format", "(", "r", ".", "status_code", ",", "r", ".", "reason", ")", ")", "r", ".", "raise_for_status", "(", ")", "return", "False" ]
Deletes device object with given rid http://docs.exosite.com/portals/#delete-device
[ "Deletes", "device", "object", "with", "given", "rid" ]
d27b621b00688a542e0adcc01f3e3354c05238a1
https://github.com/exosite-labs/pyonep/blob/d27b621b00688a542e0adcc01f3e3354c05238a1/pyonep/portals/__init__.py#L272-L293
train
exosite-labs/pyonep
pyonep/portals/__init__.py
Portals.list_device_data_sources
def list_device_data_sources(self, device_rid): """ List data sources of a portal device with rid 'device_rid'. http://docs.exosite.com/portals/#list-device-data-source """ headers = { 'User-Agent': self.user_agent(), } headers.update(self.headers()) r = requests.get( self.portals_url()+'/devices/'+device_rid+'/data-sources', headers=headers, auth=self.auth()) if HTTP_STATUS.OK == r.status_code: return r.json() else: print("Something went wrong: <{0}>: {1}".format( r.status_code, r.reason)) return None
python
def list_device_data_sources(self, device_rid): """ List data sources of a portal device with rid 'device_rid'. http://docs.exosite.com/portals/#list-device-data-source """ headers = { 'User-Agent': self.user_agent(), } headers.update(self.headers()) r = requests.get( self.portals_url()+'/devices/'+device_rid+'/data-sources', headers=headers, auth=self.auth()) if HTTP_STATUS.OK == r.status_code: return r.json() else: print("Something went wrong: <{0}>: {1}".format( r.status_code, r.reason)) return None
[ "def", "list_device_data_sources", "(", "self", ",", "device_rid", ")", ":", "headers", "=", "{", "'User-Agent'", ":", "self", ".", "user_agent", "(", ")", ",", "}", "headers", ".", "update", "(", "self", ".", "headers", "(", ")", ")", "r", "=", "requests", ".", "get", "(", "self", ".", "portals_url", "(", ")", "+", "'/devices/'", "+", "device_rid", "+", "'/data-sources'", ",", "headers", "=", "headers", ",", "auth", "=", "self", ".", "auth", "(", ")", ")", "if", "HTTP_STATUS", ".", "OK", "==", "r", ".", "status_code", ":", "return", "r", ".", "json", "(", ")", "else", ":", "print", "(", "\"Something went wrong: <{0}>: {1}\"", ".", "format", "(", "r", ".", "status_code", ",", "r", ".", "reason", ")", ")", "return", "None" ]
List data sources of a portal device with rid 'device_rid'. http://docs.exosite.com/portals/#list-device-data-source
[ "List", "data", "sources", "of", "a", "portal", "device", "with", "rid", "device_rid", "." ]
d27b621b00688a542e0adcc01f3e3354c05238a1
https://github.com/exosite-labs/pyonep/blob/d27b621b00688a542e0adcc01f3e3354c05238a1/pyonep/portals/__init__.py#L317-L335
train
exosite-labs/pyonep
pyonep/portals/__init__.py
Portals.get_data_source_bulk_request
def get_data_source_bulk_request(self, rids, limit=5): """ This grabs each datasource and its multiple datapoints for a particular device. """ headers = { 'User-Agent': self.user_agent(), 'Content-Type': self.content_type() } headers.update(self.headers()) r = requests.get( self.portals_url() +'/data-sources/[' +",".join(rids) +']/data?limit='+str(limit), headers=headers, auth=self.auth()) if HTTP_STATUS.OK == r.status_code: return r.json() else: print("Something went wrong: <{0}>: {1}".format( r.status_code, r.reason)) return {}
python
def get_data_source_bulk_request(self, rids, limit=5): """ This grabs each datasource and its multiple datapoints for a particular device. """ headers = { 'User-Agent': self.user_agent(), 'Content-Type': self.content_type() } headers.update(self.headers()) r = requests.get( self.portals_url() +'/data-sources/[' +",".join(rids) +']/data?limit='+str(limit), headers=headers, auth=self.auth()) if HTTP_STATUS.OK == r.status_code: return r.json() else: print("Something went wrong: <{0}>: {1}".format( r.status_code, r.reason)) return {}
[ "def", "get_data_source_bulk_request", "(", "self", ",", "rids", ",", "limit", "=", "5", ")", ":", "headers", "=", "{", "'User-Agent'", ":", "self", ".", "user_agent", "(", ")", ",", "'Content-Type'", ":", "self", ".", "content_type", "(", ")", "}", "headers", ".", "update", "(", "self", ".", "headers", "(", ")", ")", "r", "=", "requests", ".", "get", "(", "self", ".", "portals_url", "(", ")", "+", "'/data-sources/['", "+", "\",\"", ".", "join", "(", "rids", ")", "+", "']/data?limit='", "+", "str", "(", "limit", ")", ",", "headers", "=", "headers", ",", "auth", "=", "self", ".", "auth", "(", ")", ")", "if", "HTTP_STATUS", ".", "OK", "==", "r", ".", "status_code", ":", "return", "r", ".", "json", "(", ")", "else", ":", "print", "(", "\"Something went wrong: <{0}>: {1}\"", ".", "format", "(", "r", ".", "status_code", ",", "r", ".", "reason", ")", ")", "return", "{", "}" ]
This grabs each datasource and its multiple datapoints for a particular device.
[ "This", "grabs", "each", "datasource", "and", "its", "multiple", "datapoints", "for", "a", "particular", "device", "." ]
d27b621b00688a542e0adcc01f3e3354c05238a1
https://github.com/exosite-labs/pyonep/blob/d27b621b00688a542e0adcc01f3e3354c05238a1/pyonep/portals/__init__.py#L337-L357
train
exosite-labs/pyonep
pyonep/portals/__init__.py
Portals.get_all_devices_in_portal
def get_all_devices_in_portal(self): """ This loops through the get_multiple_devices method 10 rids at a time. """ rids = self.get_portal_by_name( self.portal_name() )[2][1]['info']['aliases'] # print("RIDS: {0}".format(rids)) device_rids = [ rid.strip() for rid in rids ] blocks_of_ten = [ device_rids[x:x+10] for x in range(0, len(device_rids), 10) ] devices = [] for block_of_ten in blocks_of_ten: retval = self.get_multiple_devices(block_of_ten) if retval is not None: devices.extend( retval ) else: print("Not adding to device list: {!r}".format(retval)) # Parse 'meta' key's raw string values for each device for device in devices: dictify_device_meta(device) return devices
python
def get_all_devices_in_portal(self): """ This loops through the get_multiple_devices method 10 rids at a time. """ rids = self.get_portal_by_name( self.portal_name() )[2][1]['info']['aliases'] # print("RIDS: {0}".format(rids)) device_rids = [ rid.strip() for rid in rids ] blocks_of_ten = [ device_rids[x:x+10] for x in range(0, len(device_rids), 10) ] devices = [] for block_of_ten in blocks_of_ten: retval = self.get_multiple_devices(block_of_ten) if retval is not None: devices.extend( retval ) else: print("Not adding to device list: {!r}".format(retval)) # Parse 'meta' key's raw string values for each device for device in devices: dictify_device_meta(device) return devices
[ "def", "get_all_devices_in_portal", "(", "self", ")", ":", "rids", "=", "self", ".", "get_portal_by_name", "(", "self", ".", "portal_name", "(", ")", ")", "[", "2", "]", "[", "1", "]", "[", "'info'", "]", "[", "'aliases'", "]", "# print(\"RIDS: {0}\".format(rids))", "device_rids", "=", "[", "rid", ".", "strip", "(", ")", "for", "rid", "in", "rids", "]", "blocks_of_ten", "=", "[", "device_rids", "[", "x", ":", "x", "+", "10", "]", "for", "x", "in", "range", "(", "0", ",", "len", "(", "device_rids", ")", ",", "10", ")", "]", "devices", "=", "[", "]", "for", "block_of_ten", "in", "blocks_of_ten", ":", "retval", "=", "self", ".", "get_multiple_devices", "(", "block_of_ten", ")", "if", "retval", "is", "not", "None", ":", "devices", ".", "extend", "(", "retval", ")", "else", ":", "print", "(", "\"Not adding to device list: {!r}\"", ".", "format", "(", "retval", ")", ")", "# Parse 'meta' key's raw string values for each device", "for", "device", "in", "devices", ":", "dictify_device_meta", "(", "device", ")", "return", "devices" ]
This loops through the get_multiple_devices method 10 rids at a time.
[ "This", "loops", "through", "the", "get_multiple_devices", "method", "10", "rids", "at", "a", "time", "." ]
d27b621b00688a542e0adcc01f3e3354c05238a1
https://github.com/exosite-labs/pyonep/blob/d27b621b00688a542e0adcc01f3e3354c05238a1/pyonep/portals/__init__.py#L366-L390
train
exosite-labs/pyonep
pyonep/portals/__init__.py
Portals.map_aliases_to_device_objects
def map_aliases_to_device_objects(self): """ A device object knows its rid, but not its alias. A portal object knows its device rids and aliases. This function adds an 'portals_aliases' key to all of the device objects so they can be sorted by alias. """ all_devices = self.get_all_devices_in_portal() for dev_o in all_devices: dev_o['portals_aliases'] = self.get_portal_by_name( self.portal_name() )[2][1]['info']['aliases'][ dev_o['rid'] ] return all_devices
python
def map_aliases_to_device_objects(self): """ A device object knows its rid, but not its alias. A portal object knows its device rids and aliases. This function adds an 'portals_aliases' key to all of the device objects so they can be sorted by alias. """ all_devices = self.get_all_devices_in_portal() for dev_o in all_devices: dev_o['portals_aliases'] = self.get_portal_by_name( self.portal_name() )[2][1]['info']['aliases'][ dev_o['rid'] ] return all_devices
[ "def", "map_aliases_to_device_objects", "(", "self", ")", ":", "all_devices", "=", "self", ".", "get_all_devices_in_portal", "(", ")", "for", "dev_o", "in", "all_devices", ":", "dev_o", "[", "'portals_aliases'", "]", "=", "self", ".", "get_portal_by_name", "(", "self", ".", "portal_name", "(", ")", ")", "[", "2", "]", "[", "1", "]", "[", "'info'", "]", "[", "'aliases'", "]", "[", "dev_o", "[", "'rid'", "]", "]", "return", "all_devices" ]
A device object knows its rid, but not its alias. A portal object knows its device rids and aliases. This function adds an 'portals_aliases' key to all of the device objects so they can be sorted by alias.
[ "A", "device", "object", "knows", "its", "rid", "but", "not", "its", "alias", ".", "A", "portal", "object", "knows", "its", "device", "rids", "and", "aliases", "." ]
d27b621b00688a542e0adcc01f3e3354c05238a1
https://github.com/exosite-labs/pyonep/blob/d27b621b00688a542e0adcc01f3e3354c05238a1/pyonep/portals/__init__.py#L392-L405
train
exosite-labs/pyonep
pyonep/portals/__init__.py
Portals.search_for_devices_by_serial_number
def search_for_devices_by_serial_number(self, sn): """ Returns a list of device objects that match the serial number in param 'sn'. This will match partial serial numbers. """ import re sn_search = re.compile(sn) matches = [] for dev_o in self.get_all_devices_in_portal(): # print("Checking {0}".format(dev_o['sn'])) try: if sn_search.match(dev_o['sn']): matches.append(dev_o) except TypeError as err: print("Problem checking device {!r}: {!r}".format( dev_o['info']['description']['name'], str(err))) return matches
python
def search_for_devices_by_serial_number(self, sn): """ Returns a list of device objects that match the serial number in param 'sn'. This will match partial serial numbers. """ import re sn_search = re.compile(sn) matches = [] for dev_o in self.get_all_devices_in_portal(): # print("Checking {0}".format(dev_o['sn'])) try: if sn_search.match(dev_o['sn']): matches.append(dev_o) except TypeError as err: print("Problem checking device {!r}: {!r}".format( dev_o['info']['description']['name'], str(err))) return matches
[ "def", "search_for_devices_by_serial_number", "(", "self", ",", "sn", ")", ":", "import", "re", "sn_search", "=", "re", ".", "compile", "(", "sn", ")", "matches", "=", "[", "]", "for", "dev_o", "in", "self", ".", "get_all_devices_in_portal", "(", ")", ":", "# print(\"Checking {0}\".format(dev_o['sn']))", "try", ":", "if", "sn_search", ".", "match", "(", "dev_o", "[", "'sn'", "]", ")", ":", "matches", ".", "append", "(", "dev_o", ")", "except", "TypeError", "as", "err", ":", "print", "(", "\"Problem checking device {!r}: {!r}\"", ".", "format", "(", "dev_o", "[", "'info'", "]", "[", "'description'", "]", "[", "'name'", "]", ",", "str", "(", "err", ")", ")", ")", "return", "matches" ]
Returns a list of device objects that match the serial number in param 'sn'. This will match partial serial numbers.
[ "Returns", "a", "list", "of", "device", "objects", "that", "match", "the", "serial", "number", "in", "param", "sn", "." ]
d27b621b00688a542e0adcc01f3e3354c05238a1
https://github.com/exosite-labs/pyonep/blob/d27b621b00688a542e0adcc01f3e3354c05238a1/pyonep/portals/__init__.py#L407-L429
train
exosite-labs/pyonep
pyonep/portals/__init__.py
Portals.print_device_list
def print_device_list(self, device_list=None): """ Optional parameter is a list of device objects. If omitted, will just print all portal devices objects. """ dev_list = device_list if device_list is not None else self.get_all_devices_in_portal() for dev in dev_list: print('{0}\t\t{1}\t\t{2}'.format( dev['info']['description']['name'], dev['sn'], dev['portals_aliases']\ if len(dev['portals_aliases']) != 1 else dev['portals_aliases'][0] ) )
python
def print_device_list(self, device_list=None): """ Optional parameter is a list of device objects. If omitted, will just print all portal devices objects. """ dev_list = device_list if device_list is not None else self.get_all_devices_in_portal() for dev in dev_list: print('{0}\t\t{1}\t\t{2}'.format( dev['info']['description']['name'], dev['sn'], dev['portals_aliases']\ if len(dev['portals_aliases']) != 1 else dev['portals_aliases'][0] ) )
[ "def", "print_device_list", "(", "self", ",", "device_list", "=", "None", ")", ":", "dev_list", "=", "device_list", "if", "device_list", "is", "not", "None", "else", "self", ".", "get_all_devices_in_portal", "(", ")", "for", "dev", "in", "dev_list", ":", "print", "(", "'{0}\\t\\t{1}\\t\\t{2}'", ".", "format", "(", "dev", "[", "'info'", "]", "[", "'description'", "]", "[", "'name'", "]", ",", "dev", "[", "'sn'", "]", ",", "dev", "[", "'portals_aliases'", "]", "if", "len", "(", "dev", "[", "'portals_aliases'", "]", ")", "!=", "1", "else", "dev", "[", "'portals_aliases'", "]", "[", "0", "]", ")", ")" ]
Optional parameter is a list of device objects. If omitted, will just print all portal devices objects.
[ "Optional", "parameter", "is", "a", "list", "of", "device", "objects", ".", "If", "omitted", "will", "just", "print", "all", "portal", "devices", "objects", "." ]
d27b621b00688a542e0adcc01f3e3354c05238a1
https://github.com/exosite-labs/pyonep/blob/d27b621b00688a542e0adcc01f3e3354c05238a1/pyonep/portals/__init__.py#L431-L446
train
exosite-labs/pyonep
pyonep/portals/__init__.py
Portals.print_sorted_device_list
def print_sorted_device_list(self, device_list=None, sort_key='sn'): """ Takes in a sort key and prints the device list according to that sort. Default sorts on serial number. Current supported sort options are: - name - sn - portals_aliases Can take optional device object list. """ dev_list = device_list if device_list is not None else self.get_all_devices_in_portal() sorted_dev_list = [] if sort_key == 'sn': sort_keys = [ k[sort_key] for k in dev_list if k[sort_key] is not None ] sort_keys = sorted(sort_keys) for key in sort_keys: sorted_dev_list.extend([ d for d in dev_list if d['sn'] == key ]) elif sort_key == 'name': sort_keys = [ k['info']['description'][sort_key]\ for k in dev_list if k['info']['description'][sort_key] is not None ] sort_keys = sorted(sort_keys) for key in sort_keys: sorted_dev_list.extend( [ d for d in dev_list\ if d['info']['description'][sort_key] == key ] ) elif sort_key == 'portals_aliases': sort_keys = [ k[sort_key] for k in dev_list if k[sort_key] is not None ] sort_keys = sorted(sort_keys) for key in sort_keys: sorted_dev_list.extend([ d for d in dev_list if d[sort_key] == key ]) else: print("Sort key {!r} not recognized.".format(sort_key)) sort_keys = None self.print_device_list(device_list=sorted_dev_list)
python
def print_sorted_device_list(self, device_list=None, sort_key='sn'): """ Takes in a sort key and prints the device list according to that sort. Default sorts on serial number. Current supported sort options are: - name - sn - portals_aliases Can take optional device object list. """ dev_list = device_list if device_list is not None else self.get_all_devices_in_portal() sorted_dev_list = [] if sort_key == 'sn': sort_keys = [ k[sort_key] for k in dev_list if k[sort_key] is not None ] sort_keys = sorted(sort_keys) for key in sort_keys: sorted_dev_list.extend([ d for d in dev_list if d['sn'] == key ]) elif sort_key == 'name': sort_keys = [ k['info']['description'][sort_key]\ for k in dev_list if k['info']['description'][sort_key] is not None ] sort_keys = sorted(sort_keys) for key in sort_keys: sorted_dev_list.extend( [ d for d in dev_list\ if d['info']['description'][sort_key] == key ] ) elif sort_key == 'portals_aliases': sort_keys = [ k[sort_key] for k in dev_list if k[sort_key] is not None ] sort_keys = sorted(sort_keys) for key in sort_keys: sorted_dev_list.extend([ d for d in dev_list if d[sort_key] == key ]) else: print("Sort key {!r} not recognized.".format(sort_key)) sort_keys = None self.print_device_list(device_list=sorted_dev_list)
[ "def", "print_sorted_device_list", "(", "self", ",", "device_list", "=", "None", ",", "sort_key", "=", "'sn'", ")", ":", "dev_list", "=", "device_list", "if", "device_list", "is", "not", "None", "else", "self", ".", "get_all_devices_in_portal", "(", ")", "sorted_dev_list", "=", "[", "]", "if", "sort_key", "==", "'sn'", ":", "sort_keys", "=", "[", "k", "[", "sort_key", "]", "for", "k", "in", "dev_list", "if", "k", "[", "sort_key", "]", "is", "not", "None", "]", "sort_keys", "=", "sorted", "(", "sort_keys", ")", "for", "key", "in", "sort_keys", ":", "sorted_dev_list", ".", "extend", "(", "[", "d", "for", "d", "in", "dev_list", "if", "d", "[", "'sn'", "]", "==", "key", "]", ")", "elif", "sort_key", "==", "'name'", ":", "sort_keys", "=", "[", "k", "[", "'info'", "]", "[", "'description'", "]", "[", "sort_key", "]", "for", "k", "in", "dev_list", "if", "k", "[", "'info'", "]", "[", "'description'", "]", "[", "sort_key", "]", "is", "not", "None", "]", "sort_keys", "=", "sorted", "(", "sort_keys", ")", "for", "key", "in", "sort_keys", ":", "sorted_dev_list", ".", "extend", "(", "[", "d", "for", "d", "in", "dev_list", "if", "d", "[", "'info'", "]", "[", "'description'", "]", "[", "sort_key", "]", "==", "key", "]", ")", "elif", "sort_key", "==", "'portals_aliases'", ":", "sort_keys", "=", "[", "k", "[", "sort_key", "]", "for", "k", "in", "dev_list", "if", "k", "[", "sort_key", "]", "is", "not", "None", "]", "sort_keys", "=", "sorted", "(", "sort_keys", ")", "for", "key", "in", "sort_keys", ":", "sorted_dev_list", ".", "extend", "(", "[", "d", "for", "d", "in", "dev_list", "if", "d", "[", "sort_key", "]", "==", "key", "]", ")", "else", ":", "print", "(", "\"Sort key {!r} not recognized.\"", ".", "format", "(", "sort_key", ")", ")", "sort_keys", "=", "None", "self", ".", "print_device_list", "(", "device_list", "=", "sorted_dev_list", ")" ]
Takes in a sort key and prints the device list according to that sort. Default sorts on serial number. Current supported sort options are: - name - sn - portals_aliases Can take optional device object list.
[ "Takes", "in", "a", "sort", "key", "and", "prints", "the", "device", "list", "according", "to", "that", "sort", "." ]
d27b621b00688a542e0adcc01f3e3354c05238a1
https://github.com/exosite-labs/pyonep/blob/d27b621b00688a542e0adcc01f3e3354c05238a1/pyonep/portals/__init__.py#L448-L489
train
exosite-labs/pyonep
pyonep/portals/__init__.py
Portals.get_user_id_from_email
def get_user_id_from_email(self, email): """ Uses the get-all-user-accounts Portals API to retrieve the user-id by supplying an email. """ accts = self.get_all_user_accounts() for acct in accts: if acct['email'] == email: return acct['id'] return None
python
def get_user_id_from_email(self, email): """ Uses the get-all-user-accounts Portals API to retrieve the user-id by supplying an email. """ accts = self.get_all_user_accounts() for acct in accts: if acct['email'] == email: return acct['id'] return None
[ "def", "get_user_id_from_email", "(", "self", ",", "email", ")", ":", "accts", "=", "self", ".", "get_all_user_accounts", "(", ")", "for", "acct", "in", "accts", ":", "if", "acct", "[", "'email'", "]", "==", "email", ":", "return", "acct", "[", "'id'", "]", "return", "None" ]
Uses the get-all-user-accounts Portals API to retrieve the user-id by supplying an email.
[ "Uses", "the", "get", "-", "all", "-", "user", "-", "accounts", "Portals", "API", "to", "retrieve", "the", "user", "-", "id", "by", "supplying", "an", "email", "." ]
d27b621b00688a542e0adcc01f3e3354c05238a1
https://github.com/exosite-labs/pyonep/blob/d27b621b00688a542e0adcc01f3e3354c05238a1/pyonep/portals/__init__.py#L491-L499
train
exosite-labs/pyonep
pyonep/portals/__init__.py
Portals.get_user_permission_from_email
def get_user_permission_from_email(self, email): """ Returns a user's permissions object when given the user email.""" _id = self.get_user_id_from_email(email) return self.get_user_permission(_id)
python
def get_user_permission_from_email(self, email): """ Returns a user's permissions object when given the user email.""" _id = self.get_user_id_from_email(email) return self.get_user_permission(_id)
[ "def", "get_user_permission_from_email", "(", "self", ",", "email", ")", ":", "_id", "=", "self", ".", "get_user_id_from_email", "(", "email", ")", "return", "self", ".", "get_user_permission", "(", "_id", ")" ]
Returns a user's permissions object when given the user email.
[ "Returns", "a", "user", "s", "permissions", "object", "when", "given", "the", "user", "email", "." ]
d27b621b00688a542e0adcc01f3e3354c05238a1
https://github.com/exosite-labs/pyonep/blob/d27b621b00688a542e0adcc01f3e3354c05238a1/pyonep/portals/__init__.py#L501-L504
train
exosite-labs/pyonep
pyonep/portals/__init__.py
Portals.add_dplist_permission_for_user_on_portal
def add_dplist_permission_for_user_on_portal(self, user_email, portal_id): """ Adds the 'd_p_list' permission to a user object when provided a user_email and portal_id.""" _id = self.get_user_id_from_email(user_email) print(self.get_user_permission_from_email(user_email)) retval = self.add_user_permission( _id, json.dumps( [{'access': 'd_p_list', 'oid':{'id': portal_id, 'type':'Portal'}}] ) ) print(self.get_user_permission_from_email(user_email)) return retval
python
def add_dplist_permission_for_user_on_portal(self, user_email, portal_id): """ Adds the 'd_p_list' permission to a user object when provided a user_email and portal_id.""" _id = self.get_user_id_from_email(user_email) print(self.get_user_permission_from_email(user_email)) retval = self.add_user_permission( _id, json.dumps( [{'access': 'd_p_list', 'oid':{'id': portal_id, 'type':'Portal'}}] ) ) print(self.get_user_permission_from_email(user_email)) return retval
[ "def", "add_dplist_permission_for_user_on_portal", "(", "self", ",", "user_email", ",", "portal_id", ")", ":", "_id", "=", "self", ".", "get_user_id_from_email", "(", "user_email", ")", "print", "(", "self", ".", "get_user_permission_from_email", "(", "user_email", ")", ")", "retval", "=", "self", ".", "add_user_permission", "(", "_id", ",", "json", ".", "dumps", "(", "[", "{", "'access'", ":", "'d_p_list'", ",", "'oid'", ":", "{", "'id'", ":", "portal_id", ",", "'type'", ":", "'Portal'", "}", "}", "]", ")", ")", "print", "(", "self", ".", "get_user_permission_from_email", "(", "user_email", ")", ")", "return", "retval" ]
Adds the 'd_p_list' permission to a user object when provided a user_email and portal_id.
[ "Adds", "the", "d_p_list", "permission", "to", "a", "user", "object", "when", "provided", "a", "user_email", "and", "portal_id", "." ]
d27b621b00688a542e0adcc01f3e3354c05238a1
https://github.com/exosite-labs/pyonep/blob/d27b621b00688a542e0adcc01f3e3354c05238a1/pyonep/portals/__init__.py#L506-L516
train
exosite-labs/pyonep
pyonep/portals/__init__.py
Portals.get_portal_cik
def get_portal_cik(self, portal_name): """ Retrieves portal object according to 'portal_name' and returns its cik. """ portal = self.get_portal_by_name(portal_name) cik = portal[2][1]['info']['key'] return cik
python
def get_portal_cik(self, portal_name): """ Retrieves portal object according to 'portal_name' and returns its cik. """ portal = self.get_portal_by_name(portal_name) cik = portal[2][1]['info']['key'] return cik
[ "def", "get_portal_cik", "(", "self", ",", "portal_name", ")", ":", "portal", "=", "self", ".", "get_portal_by_name", "(", "portal_name", ")", "cik", "=", "portal", "[", "2", "]", "[", "1", "]", "[", "'info'", "]", "[", "'key'", "]", "return", "cik" ]
Retrieves portal object according to 'portal_name' and returns its cik.
[ "Retrieves", "portal", "object", "according", "to", "portal_name", "and", "returns", "its", "cik", "." ]
d27b621b00688a542e0adcc01f3e3354c05238a1
https://github.com/exosite-labs/pyonep/blob/d27b621b00688a542e0adcc01f3e3354c05238a1/pyonep/portals/__init__.py#L518-L523
train
chaoss/grimoirelab-cereslib
examples/areas_code.py
init_write_index
def init_write_index(es_write, es_write_index): """Initializes ES write index """ logging.info("Initializing index: " + es_write_index) es_write.indices.delete(es_write_index, ignore=[400, 404]) es_write.indices.create(es_write_index, body=MAPPING_GIT)
python
def init_write_index(es_write, es_write_index): """Initializes ES write index """ logging.info("Initializing index: " + es_write_index) es_write.indices.delete(es_write_index, ignore=[400, 404]) es_write.indices.create(es_write_index, body=MAPPING_GIT)
[ "def", "init_write_index", "(", "es_write", ",", "es_write_index", ")", ":", "logging", ".", "info", "(", "\"Initializing index: \"", "+", "es_write_index", ")", "es_write", ".", "indices", ".", "delete", "(", "es_write_index", ",", "ignore", "=", "[", "400", ",", "404", "]", ")", "es_write", ".", "indices", ".", "create", "(", "es_write_index", ",", "body", "=", "MAPPING_GIT", ")" ]
Initializes ES write index
[ "Initializes", "ES", "write", "index" ]
5110e6ca490a4f24bec3124286ebf51fd4e08bdd
https://github.com/chaoss/grimoirelab-cereslib/blob/5110e6ca490a4f24bec3124286ebf51fd4e08bdd/examples/areas_code.py#L267-L272
train
chaoss/grimoirelab-cereslib
cereslib/enrich/enrich.py
PairProgramming.enrich
def enrich(self, column1, column2): """ This class splits those commits where column1 and column2 values are different :param column1: column to compare to column2 :param column2: column to compare to column1 :type column1: string :type column2: string :returns: self.commits with duplicated rows where the values at columns are different. The original row remains while the second row contains in column1 and 2 the value of column2. :rtype: pandas.DataFrame """ if column1 not in self.commits.columns or \ column2 not in self.commits.columns: return self.commits # Select rows where values in column1 are different from # values in column2 pair_df = self.commits[self.commits[column1] != self.commits[column2]] new_values = list(pair_df[column2]) # Update values from column2 pair_df[column1] = new_values # This adds at the end of the original dataframe those rows duplicating # information and updating the values in column1 return self.commits.append(pair_df)
python
def enrich(self, column1, column2): """ This class splits those commits where column1 and column2 values are different :param column1: column to compare to column2 :param column2: column to compare to column1 :type column1: string :type column2: string :returns: self.commits with duplicated rows where the values at columns are different. The original row remains while the second row contains in column1 and 2 the value of column2. :rtype: pandas.DataFrame """ if column1 not in self.commits.columns or \ column2 not in self.commits.columns: return self.commits # Select rows where values in column1 are different from # values in column2 pair_df = self.commits[self.commits[column1] != self.commits[column2]] new_values = list(pair_df[column2]) # Update values from column2 pair_df[column1] = new_values # This adds at the end of the original dataframe those rows duplicating # information and updating the values in column1 return self.commits.append(pair_df)
[ "def", "enrich", "(", "self", ",", "column1", ",", "column2", ")", ":", "if", "column1", "not", "in", "self", ".", "commits", ".", "columns", "or", "column2", "not", "in", "self", ".", "commits", ".", "columns", ":", "return", "self", ".", "commits", "# Select rows where values in column1 are different from", "# values in column2", "pair_df", "=", "self", ".", "commits", "[", "self", ".", "commits", "[", "column1", "]", "!=", "self", ".", "commits", "[", "column2", "]", "]", "new_values", "=", "list", "(", "pair_df", "[", "column2", "]", ")", "# Update values from column2", "pair_df", "[", "column1", "]", "=", "new_values", "# This adds at the end of the original dataframe those rows duplicating", "# information and updating the values in column1", "return", "self", ".", "commits", ".", "append", "(", "pair_df", ")" ]
This class splits those commits where column1 and column2 values are different :param column1: column to compare to column2 :param column2: column to compare to column1 :type column1: string :type column2: string :returns: self.commits with duplicated rows where the values at columns are different. The original row remains while the second row contains in column1 and 2 the value of column2. :rtype: pandas.DataFrame
[ "This", "class", "splits", "those", "commits", "where", "column1", "and", "column2", "values", "are", "different" ]
5110e6ca490a4f24bec3124286ebf51fd4e08bdd
https://github.com/chaoss/grimoirelab-cereslib/blob/5110e6ca490a4f24bec3124286ebf51fd4e08bdd/cereslib/enrich/enrich.py#L67-L95
train
chaoss/grimoirelab-cereslib
cereslib/enrich/enrich.py
FileType.enrich
def enrich(self, column): """ This method adds a new column depending on the extension of the file. :param column: column where the file path is found :type column: string :return: returns the original dataframe with a new column named as 'filetype' that contains information about its extension :rtype: pandas.DataFrame """ if column not in self.data: return self.data # Insert a new column with default values self.data["filetype"] = 'Other' # Insert 'Code' only in those rows that are # detected as being source code thanks to its extension reg = "\.c$|\.h$|\.cc$|\.cpp$|\.cxx$|\.c\+\+$|\.cp$|\.py$|\.js$|\.java$|\.rs$|\.go$" self.data.loc[self.data[column].str.contains(reg), 'filetype'] = 'Code' return self.data
python
def enrich(self, column): """ This method adds a new column depending on the extension of the file. :param column: column where the file path is found :type column: string :return: returns the original dataframe with a new column named as 'filetype' that contains information about its extension :rtype: pandas.DataFrame """ if column not in self.data: return self.data # Insert a new column with default values self.data["filetype"] = 'Other' # Insert 'Code' only in those rows that are # detected as being source code thanks to its extension reg = "\.c$|\.h$|\.cc$|\.cpp$|\.cxx$|\.c\+\+$|\.cp$|\.py$|\.js$|\.java$|\.rs$|\.go$" self.data.loc[self.data[column].str.contains(reg), 'filetype'] = 'Code' return self.data
[ "def", "enrich", "(", "self", ",", "column", ")", ":", "if", "column", "not", "in", "self", ".", "data", ":", "return", "self", ".", "data", "# Insert a new column with default values", "self", ".", "data", "[", "\"filetype\"", "]", "=", "'Other'", "# Insert 'Code' only in those rows that are", "# detected as being source code thanks to its extension", "reg", "=", "\"\\.c$|\\.h$|\\.cc$|\\.cpp$|\\.cxx$|\\.c\\+\\+$|\\.cp$|\\.py$|\\.js$|\\.java$|\\.rs$|\\.go$\"", "self", ".", "data", ".", "loc", "[", "self", ".", "data", "[", "column", "]", ".", "str", ".", "contains", "(", "reg", ")", ",", "'filetype'", "]", "=", "'Code'", "return", "self", ".", "data" ]
This method adds a new column depending on the extension of the file. :param column: column where the file path is found :type column: string :return: returns the original dataframe with a new column named as 'filetype' that contains information about its extension :rtype: pandas.DataFrame
[ "This", "method", "adds", "a", "new", "column", "depending", "on", "the", "extension", "of", "the", "file", "." ]
5110e6ca490a4f24bec3124286ebf51fd4e08bdd
https://github.com/chaoss/grimoirelab-cereslib/blob/5110e6ca490a4f24bec3124286ebf51fd4e08bdd/cereslib/enrich/enrich.py#L112-L135
train
chaoss/grimoirelab-cereslib
cereslib/enrich/enrich.py
Projects.enrich
def enrich(self, column, projects): """ This method adds a new column named as 'project' that contains information about the associated project that the event in 'column' belongs to. :param column: column with information related to the project :type column: string :param projects: information about item - project :type projects: pandas.DataFrame :returns: original data frame with a new column named 'project' :rtype: pandas.DataFrame """ if column not in self.data.columns: return self.data self.data = pandas.merge(self.data, projects, how='left', on=column) return self.data
python
def enrich(self, column, projects): """ This method adds a new column named as 'project' that contains information about the associated project that the event in 'column' belongs to. :param column: column with information related to the project :type column: string :param projects: information about item - project :type projects: pandas.DataFrame :returns: original data frame with a new column named 'project' :rtype: pandas.DataFrame """ if column not in self.data.columns: return self.data self.data = pandas.merge(self.data, projects, how='left', on=column) return self.data
[ "def", "enrich", "(", "self", ",", "column", ",", "projects", ")", ":", "if", "column", "not", "in", "self", ".", "data", ".", "columns", ":", "return", "self", ".", "data", "self", ".", "data", "=", "pandas", ".", "merge", "(", "self", ".", "data", ",", "projects", ",", "how", "=", "'left'", ",", "on", "=", "column", ")", "return", "self", ".", "data" ]
This method adds a new column named as 'project' that contains information about the associated project that the event in 'column' belongs to. :param column: column with information related to the project :type column: string :param projects: information about item - project :type projects: pandas.DataFrame :returns: original data frame with a new column named 'project' :rtype: pandas.DataFrame
[ "This", "method", "adds", "a", "new", "column", "named", "as", "project", "that", "contains", "information", "about", "the", "associated", "project", "that", "the", "event", "in", "column", "belongs", "to", "." ]
5110e6ca490a4f24bec3124286ebf51fd4e08bdd
https://github.com/chaoss/grimoirelab-cereslib/blob/5110e6ca490a4f24bec3124286ebf51fd4e08bdd/cereslib/enrich/enrich.py#L224-L243
train
chaoss/grimoirelab-cereslib
cereslib/enrich/enrich.py
EmailFlag.__parse_flags
def __parse_flags(self, body): """Parse flags from a message""" flags = [] values = [] lines = body.split('\n') for l in lines: for name in self.FLAGS_REGEX: m = re.match(self.FLAGS_REGEX[name], l) if m: flags.append(name) values.append(m.group("value").strip()) if flags == []: flags = "" values = "" return flags, values
python
def __parse_flags(self, body): """Parse flags from a message""" flags = [] values = [] lines = body.split('\n') for l in lines: for name in self.FLAGS_REGEX: m = re.match(self.FLAGS_REGEX[name], l) if m: flags.append(name) values.append(m.group("value").strip()) if flags == []: flags = "" values = "" return flags, values
[ "def", "__parse_flags", "(", "self", ",", "body", ")", ":", "flags", "=", "[", "]", "values", "=", "[", "]", "lines", "=", "body", ".", "split", "(", "'\\n'", ")", "for", "l", "in", "lines", ":", "for", "name", "in", "self", ".", "FLAGS_REGEX", ":", "m", "=", "re", ".", "match", "(", "self", ".", "FLAGS_REGEX", "[", "name", "]", ",", "l", ")", "if", "m", ":", "flags", ".", "append", "(", "name", ")", "values", ".", "append", "(", "m", ".", "group", "(", "\"value\"", ")", ".", "strip", "(", ")", ")", "if", "flags", "==", "[", "]", ":", "flags", "=", "\"\"", "values", "=", "\"\"", "return", "flags", ",", "values" ]
Parse flags from a message
[ "Parse", "flags", "from", "a", "message" ]
5110e6ca490a4f24bec3124286ebf51fd4e08bdd
https://github.com/chaoss/grimoirelab-cereslib/blob/5110e6ca490a4f24bec3124286ebf51fd4e08bdd/cereslib/enrich/enrich.py#L341-L358
train
chaoss/grimoirelab-cereslib
cereslib/enrich/enrich.py
SplitEmailDomain.enrich
def enrich(self, column): """ This enricher returns the same dataframe with a new column named 'domain'. That column is the result of splitting the email address of another column. If there is not a proper email address an 'unknown' domain is returned. :param column: column where the text to analyze is found :type data: string """ if column not in self.data.columns: return self.data self.data['domain'] = self.data[column].apply(lambda x: self.__parse_email(x)) return self.data
python
def enrich(self, column): """ This enricher returns the same dataframe with a new column named 'domain'. That column is the result of splitting the email address of another column. If there is not a proper email address an 'unknown' domain is returned. :param column: column where the text to analyze is found :type data: string """ if column not in self.data.columns: return self.data self.data['domain'] = self.data[column].apply(lambda x: self.__parse_email(x)) return self.data
[ "def", "enrich", "(", "self", ",", "column", ")", ":", "if", "column", "not", "in", "self", ".", "data", ".", "columns", ":", "return", "self", ".", "data", "self", ".", "data", "[", "'domain'", "]", "=", "self", ".", "data", "[", "column", "]", ".", "apply", "(", "lambda", "x", ":", "self", ".", "__parse_email", "(", "x", ")", ")", "return", "self", ".", "data" ]
This enricher returns the same dataframe with a new column named 'domain'. That column is the result of splitting the email address of another column. If there is not a proper email address an 'unknown' domain is returned. :param column: column where the text to analyze is found :type data: string
[ "This", "enricher", "returns", "the", "same", "dataframe", "with", "a", "new", "column", "named", "domain", ".", "That", "column", "is", "the", "result", "of", "splitting", "the", "email", "address", "of", "another", "column", ".", "If", "there", "is", "not", "a", "proper", "email", "address", "an", "unknown", "domain", "is", "returned", "." ]
5110e6ca490a4f24bec3124286ebf51fd4e08bdd
https://github.com/chaoss/grimoirelab-cereslib/blob/5110e6ca490a4f24bec3124286ebf51fd4e08bdd/cereslib/enrich/enrich.py#L429-L445
train
chaoss/grimoirelab-cereslib
cereslib/enrich/enrich.py
ToUTF8.__remove_surrogates
def __remove_surrogates(self, s, method='replace'): """ Remove surrogates in the specified string """ if type(s) == list and len(s) == 1: if self.__is_surrogate_escaped(s[0]): return s[0].encode('utf-8', method).decode('utf-8') else: return "" if type(s) == list: return "" if type(s) != str: return "" if self.__is_surrogate_escaped(s): return s.encode('utf-8', method).decode('utf-8') return s
python
def __remove_surrogates(self, s, method='replace'): """ Remove surrogates in the specified string """ if type(s) == list and len(s) == 1: if self.__is_surrogate_escaped(s[0]): return s[0].encode('utf-8', method).decode('utf-8') else: return "" if type(s) == list: return "" if type(s) != str: return "" if self.__is_surrogate_escaped(s): return s.encode('utf-8', method).decode('utf-8') return s
[ "def", "__remove_surrogates", "(", "self", ",", "s", ",", "method", "=", "'replace'", ")", ":", "if", "type", "(", "s", ")", "==", "list", "and", "len", "(", "s", ")", "==", "1", ":", "if", "self", ".", "__is_surrogate_escaped", "(", "s", "[", "0", "]", ")", ":", "return", "s", "[", "0", "]", ".", "encode", "(", "'utf-8'", ",", "method", ")", ".", "decode", "(", "'utf-8'", ")", "else", ":", "return", "\"\"", "if", "type", "(", "s", ")", "==", "list", ":", "return", "\"\"", "if", "type", "(", "s", ")", "!=", "str", ":", "return", "\"\"", "if", "self", ".", "__is_surrogate_escaped", "(", "s", ")", ":", "return", "s", ".", "encode", "(", "'utf-8'", ",", "method", ")", ".", "decode", "(", "'utf-8'", ")", "return", "s" ]
Remove surrogates in the specified string
[ "Remove", "surrogates", "in", "the", "specified", "string" ]
5110e6ca490a4f24bec3124286ebf51fd4e08bdd
https://github.com/chaoss/grimoirelab-cereslib/blob/5110e6ca490a4f24bec3124286ebf51fd4e08bdd/cereslib/enrich/enrich.py#L452-L467
train
chaoss/grimoirelab-cereslib
cereslib/enrich/enrich.py
ToUTF8.__is_surrogate_escaped
def __is_surrogate_escaped(self, text): """ Checks if surrogate is escaped """ try: text.encode('utf-8') except UnicodeEncodeError as e: if e.reason == 'surrogates not allowed': return True return False
python
def __is_surrogate_escaped(self, text): """ Checks if surrogate is escaped """ try: text.encode('utf-8') except UnicodeEncodeError as e: if e.reason == 'surrogates not allowed': return True return False
[ "def", "__is_surrogate_escaped", "(", "self", ",", "text", ")", ":", "try", ":", "text", ".", "encode", "(", "'utf-8'", ")", "except", "UnicodeEncodeError", "as", "e", ":", "if", "e", ".", "reason", "==", "'surrogates not allowed'", ":", "return", "True", "return", "False" ]
Checks if surrogate is escaped
[ "Checks", "if", "surrogate", "is", "escaped" ]
5110e6ca490a4f24bec3124286ebf51fd4e08bdd
https://github.com/chaoss/grimoirelab-cereslib/blob/5110e6ca490a4f24bec3124286ebf51fd4e08bdd/cereslib/enrich/enrich.py#L469-L478
train
chaoss/grimoirelab-cereslib
cereslib/enrich/enrich.py
ToUTF8.enrich
def enrich(self, columns): """ This method convert to utf-8 the provided columns :param columns: list of columns to convert to :type columns: list of strings :return: original dataframe with converted strings :rtype: pandas.DataFrame """ for column in columns: if column not in self.data.columns: return self.data for column in columns: a = self.data[column].apply(self.__remove_surrogates) self.data[column] = a return self.data
python
def enrich(self, columns): """ This method convert to utf-8 the provided columns :param columns: list of columns to convert to :type columns: list of strings :return: original dataframe with converted strings :rtype: pandas.DataFrame """ for column in columns: if column not in self.data.columns: return self.data for column in columns: a = self.data[column].apply(self.__remove_surrogates) self.data[column] = a return self.data
[ "def", "enrich", "(", "self", ",", "columns", ")", ":", "for", "column", "in", "columns", ":", "if", "column", "not", "in", "self", ".", "data", ".", "columns", ":", "return", "self", ".", "data", "for", "column", "in", "columns", ":", "a", "=", "self", ".", "data", "[", "column", "]", ".", "apply", "(", "self", ".", "__remove_surrogates", ")", "self", ".", "data", "[", "column", "]", "=", "a", "return", "self", ".", "data" ]
This method convert to utf-8 the provided columns :param columns: list of columns to convert to :type columns: list of strings :return: original dataframe with converted strings :rtype: pandas.DataFrame
[ "This", "method", "convert", "to", "utf", "-", "8", "the", "provided", "columns" ]
5110e6ca490a4f24bec3124286ebf51fd4e08bdd
https://github.com/chaoss/grimoirelab-cereslib/blob/5110e6ca490a4f24bec3124286ebf51fd4e08bdd/cereslib/enrich/enrich.py#L489-L506
train
chaoss/grimoirelab-cereslib
cereslib/enrich/enrich.py
SplitEmail.__parse_addr
def __parse_addr(self, addr): """ Parse email addresses """ from email.utils import parseaddr value = parseaddr(addr) return value[0], value[1]
python
def __parse_addr(self, addr): """ Parse email addresses """ from email.utils import parseaddr value = parseaddr(addr) return value[0], value[1]
[ "def", "__parse_addr", "(", "self", ",", "addr", ")", ":", "from", "email", ".", "utils", "import", "parseaddr", "value", "=", "parseaddr", "(", "addr", ")", "return", "value", "[", "0", "]", ",", "value", "[", "1", "]" ]
Parse email addresses
[ "Parse", "email", "addresses" ]
5110e6ca490a4f24bec3124286ebf51fd4e08bdd
https://github.com/chaoss/grimoirelab-cereslib/blob/5110e6ca490a4f24bec3124286ebf51fd4e08bdd/cereslib/enrich/enrich.py#L515-L522
train
chaoss/grimoirelab-cereslib
cereslib/enrich/enrich.py
SplitLists.enrich
def enrich(self, columns): """ This method appends at the end of the dataframe as many rows as items are found in the list of elemnents in the provided columns. This assumes that the length of the lists for the several specified columns is the same. As an example, for the row A {"C1":"V1", "C2":field1, "C3":field2, "C4":field3} we have three cells with a list of four elements each of them: * field1: [1,2,3,4] * field2: ["a", "b", "c", "d"] * field3: [1.1, 2.2, 3.3, 4.4] This method converts each of the elements of each cell in a new row keeping the columns name: {"C1":"V1", "C2":1, "C3":"a", "C4":1.1} {"C1":"V1", "C2":2, "C3":"b", "C4":2.2} {"C1":"V1", "C2":3, "C3":"c", "C4":3.3} {"C1":"V1", "C2":4, "C3":"d", "C4":4.4} :param columns: list of strings :rtype pandas.DataFrame """ for column in columns: if column not in self.data.columns: return self.data # Looking for the rows with columns with lists of more # than one element first_column = list(self.data[columns[0]]) count = 0 append_df = pandas.DataFrame() for cell in first_column: if len(cell) >= 1: # Interested in those lists with more # than one element df = pandas.DataFrame() # Create a dataframe of N rows from the list for column in columns: df[column] = self.data.loc[count, column] # Repeat the original rows N times extra_df = pandas.DataFrame([self.data.loc[count]] * len(df)) for column in columns: extra_df[column] = list(df[column]) append_df = append_df.append(extra_df, ignore_index=True) extra_df = pandas.DataFrame() count = count + 1 self.data = self.data.append(append_df, ignore_index=True) return self.data
python
def enrich(self, columns): """ This method appends at the end of the dataframe as many rows as items are found in the list of elemnents in the provided columns. This assumes that the length of the lists for the several specified columns is the same. As an example, for the row A {"C1":"V1", "C2":field1, "C3":field2, "C4":field3} we have three cells with a list of four elements each of them: * field1: [1,2,3,4] * field2: ["a", "b", "c", "d"] * field3: [1.1, 2.2, 3.3, 4.4] This method converts each of the elements of each cell in a new row keeping the columns name: {"C1":"V1", "C2":1, "C3":"a", "C4":1.1} {"C1":"V1", "C2":2, "C3":"b", "C4":2.2} {"C1":"V1", "C2":3, "C3":"c", "C4":3.3} {"C1":"V1", "C2":4, "C3":"d", "C4":4.4} :param columns: list of strings :rtype pandas.DataFrame """ for column in columns: if column not in self.data.columns: return self.data # Looking for the rows with columns with lists of more # than one element first_column = list(self.data[columns[0]]) count = 0 append_df = pandas.DataFrame() for cell in first_column: if len(cell) >= 1: # Interested in those lists with more # than one element df = pandas.DataFrame() # Create a dataframe of N rows from the list for column in columns: df[column] = self.data.loc[count, column] # Repeat the original rows N times extra_df = pandas.DataFrame([self.data.loc[count]] * len(df)) for column in columns: extra_df[column] = list(df[column]) append_df = append_df.append(extra_df, ignore_index=True) extra_df = pandas.DataFrame() count = count + 1 self.data = self.data.append(append_df, ignore_index=True) return self.data
[ "def", "enrich", "(", "self", ",", "columns", ")", ":", "for", "column", "in", "columns", ":", "if", "column", "not", "in", "self", ".", "data", ".", "columns", ":", "return", "self", ".", "data", "# Looking for the rows with columns with lists of more", "# than one element", "first_column", "=", "list", "(", "self", ".", "data", "[", "columns", "[", "0", "]", "]", ")", "count", "=", "0", "append_df", "=", "pandas", ".", "DataFrame", "(", ")", "for", "cell", "in", "first_column", ":", "if", "len", "(", "cell", ")", ">=", "1", ":", "# Interested in those lists with more", "# than one element", "df", "=", "pandas", ".", "DataFrame", "(", ")", "# Create a dataframe of N rows from the list", "for", "column", "in", "columns", ":", "df", "[", "column", "]", "=", "self", ".", "data", ".", "loc", "[", "count", ",", "column", "]", "# Repeat the original rows N times", "extra_df", "=", "pandas", ".", "DataFrame", "(", "[", "self", ".", "data", ".", "loc", "[", "count", "]", "]", "*", "len", "(", "df", ")", ")", "for", "column", "in", "columns", ":", "extra_df", "[", "column", "]", "=", "list", "(", "df", "[", "column", "]", ")", "append_df", "=", "append_df", ".", "append", "(", "extra_df", ",", "ignore_index", "=", "True", ")", "extra_df", "=", "pandas", ".", "DataFrame", "(", ")", "count", "=", "count", "+", "1", "self", ".", "data", "=", "self", ".", "data", ".", "append", "(", "append_df", ",", "ignore_index", "=", "True", ")", "return", "self", ".", "data" ]
This method appends at the end of the dataframe as many rows as items are found in the list of elemnents in the provided columns. This assumes that the length of the lists for the several specified columns is the same. As an example, for the row A {"C1":"V1", "C2":field1, "C3":field2, "C4":field3} we have three cells with a list of four elements each of them: * field1: [1,2,3,4] * field2: ["a", "b", "c", "d"] * field3: [1.1, 2.2, 3.3, 4.4] This method converts each of the elements of each cell in a new row keeping the columns name: {"C1":"V1", "C2":1, "C3":"a", "C4":1.1} {"C1":"V1", "C2":2, "C3":"b", "C4":2.2} {"C1":"V1", "C2":3, "C3":"c", "C4":3.3} {"C1":"V1", "C2":4, "C3":"d", "C4":4.4} :param columns: list of strings :rtype pandas.DataFrame
[ "This", "method", "appends", "at", "the", "end", "of", "the", "dataframe", "as", "many", "rows", "as", "items", "are", "found", "in", "the", "list", "of", "elemnents", "in", "the", "provided", "columns", "." ]
5110e6ca490a4f24bec3124286ebf51fd4e08bdd
https://github.com/chaoss/grimoirelab-cereslib/blob/5110e6ca490a4f24bec3124286ebf51fd4e08bdd/cereslib/enrich/enrich.py#L569-L622
train
chaoss/grimoirelab-cereslib
cereslib/enrich/enrich.py
MaxMin.enrich
def enrich(self, columns, groupby): """ This method calculates the maximum and minimum value of a given set of columns depending on another column. This is the usual group by clause in SQL. :param columns: list of columns to apply the max and min values :param groupby: column use to calculate the max/min values :type columns: list of strings """ for column in columns: if column not in self.data.columns: return self.data for column in columns: df_grouped = self.data.groupby([groupby]).agg({column: 'max'}) df_grouped = df_grouped.reset_index() df_grouped.rename(columns={column: 'max_' + column}, inplace=True) self.data = pandas.merge(self.data, df_grouped, how='left', on=[groupby]) df_grouped = self.data.groupby([groupby]).agg({column: 'min'}) df_grouped = df_grouped.reset_index() df_grouped.rename(columns={column: 'min_' + column}, inplace=True) self.data = pandas.merge(self.data, df_grouped, how='left', on=[groupby]) return self.data
python
def enrich(self, columns, groupby): """ This method calculates the maximum and minimum value of a given set of columns depending on another column. This is the usual group by clause in SQL. :param columns: list of columns to apply the max and min values :param groupby: column use to calculate the max/min values :type columns: list of strings """ for column in columns: if column not in self.data.columns: return self.data for column in columns: df_grouped = self.data.groupby([groupby]).agg({column: 'max'}) df_grouped = df_grouped.reset_index() df_grouped.rename(columns={column: 'max_' + column}, inplace=True) self.data = pandas.merge(self.data, df_grouped, how='left', on=[groupby]) df_grouped = self.data.groupby([groupby]).agg({column: 'min'}) df_grouped = df_grouped.reset_index() df_grouped.rename(columns={column: 'min_' + column}, inplace=True) self.data = pandas.merge(self.data, df_grouped, how='left', on=[groupby]) return self.data
[ "def", "enrich", "(", "self", ",", "columns", ",", "groupby", ")", ":", "for", "column", "in", "columns", ":", "if", "column", "not", "in", "self", ".", "data", ".", "columns", ":", "return", "self", ".", "data", "for", "column", "in", "columns", ":", "df_grouped", "=", "self", ".", "data", ".", "groupby", "(", "[", "groupby", "]", ")", ".", "agg", "(", "{", "column", ":", "'max'", "}", ")", "df_grouped", "=", "df_grouped", ".", "reset_index", "(", ")", "df_grouped", ".", "rename", "(", "columns", "=", "{", "column", ":", "'max_'", "+", "column", "}", ",", "inplace", "=", "True", ")", "self", ".", "data", "=", "pandas", ".", "merge", "(", "self", ".", "data", ",", "df_grouped", ",", "how", "=", "'left'", ",", "on", "=", "[", "groupby", "]", ")", "df_grouped", "=", "self", ".", "data", ".", "groupby", "(", "[", "groupby", "]", ")", ".", "agg", "(", "{", "column", ":", "'min'", "}", ")", "df_grouped", "=", "df_grouped", ".", "reset_index", "(", ")", "df_grouped", ".", "rename", "(", "columns", "=", "{", "column", ":", "'min_'", "+", "column", "}", ",", "inplace", "=", "True", ")", "self", ".", "data", "=", "pandas", ".", "merge", "(", "self", ".", "data", ",", "df_grouped", ",", "how", "=", "'left'", ",", "on", "=", "[", "groupby", "]", ")", "return", "self", ".", "data" ]
This method calculates the maximum and minimum value of a given set of columns depending on another column. This is the usual group by clause in SQL. :param columns: list of columns to apply the max and min values :param groupby: column use to calculate the max/min values :type columns: list of strings
[ "This", "method", "calculates", "the", "maximum", "and", "minimum", "value", "of", "a", "given", "set", "of", "columns", "depending", "on", "another", "column", ".", "This", "is", "the", "usual", "group", "by", "clause", "in", "SQL", "." ]
5110e6ca490a4f24bec3124286ebf51fd4e08bdd
https://github.com/chaoss/grimoirelab-cereslib/blob/5110e6ca490a4f24bec3124286ebf51fd4e08bdd/cereslib/enrich/enrich.py#L640-L665
train
chaoss/grimoirelab-cereslib
cereslib/enrich/enrich.py
Gender.enrich
def enrich(self, column): """ This method calculates thanks to the genderize.io API the gender of a given name. This method initially assumes that for the given string, only the first word is the one containing the name eg: Daniel Izquierdo <[email protected]>, Daniel would be the name. If the same class instance is used in later gender searches, this stores in memory a list of names and associated gender and probability. This is intended to have faster identifications of the gender and less number of API accesses. :param column: column where the name is found :type column: string :return: original dataframe with four new columns: * gender: male, female or unknown * gender_probability: value between 0 and 1 * gender_count: number of names found in the Genderized DB * gender_analyzed_name: name that was sent to the API for analysis :rtype: pandas.DataFrame """ if column not in self.data.columns: return self.data splits = self.data[column].str.split(" ") splits = splits.str[0] self.data["gender_analyzed_name"] = splits.fillna("noname") self.data["gender_probability"] = 0 self.data["gender"] = "Unknown" self.data["gender_count"] = 0 names = list(self.data["gender_analyzed_name"].unique()) for name in names: if name in self.gender.keys(): gender_result = self.gender[name] else: try: # TODO: some errors found due to encode utf-8 issues. # Adding a try-except in the meantime. gender_result = self.connection.get([name])[0] except Exception: continue # Store info in the list of users self.gender[name] = gender_result # Update current dataset if gender_result["gender"] is None: gender_result["gender"] = "NotKnown" self.data.loc[self.data["gender_analyzed_name"] == name, 'gender'] =\ gender_result["gender"] if "probability" in gender_result.keys(): self.data.loc[self.data["gender_analyzed_name"] == name, 'gender_probability'] = gender_result["probability"] self.data.loc[self.data["gender_analyzed_name"] == name, 'gender_count'] = gender_result["count"] self.data.fillna("noname") return self.data
python
def enrich(self, column): """ This method calculates thanks to the genderize.io API the gender of a given name. This method initially assumes that for the given string, only the first word is the one containing the name eg: Daniel Izquierdo <[email protected]>, Daniel would be the name. If the same class instance is used in later gender searches, this stores in memory a list of names and associated gender and probability. This is intended to have faster identifications of the gender and less number of API accesses. :param column: column where the name is found :type column: string :return: original dataframe with four new columns: * gender: male, female or unknown * gender_probability: value between 0 and 1 * gender_count: number of names found in the Genderized DB * gender_analyzed_name: name that was sent to the API for analysis :rtype: pandas.DataFrame """ if column not in self.data.columns: return self.data splits = self.data[column].str.split(" ") splits = splits.str[0] self.data["gender_analyzed_name"] = splits.fillna("noname") self.data["gender_probability"] = 0 self.data["gender"] = "Unknown" self.data["gender_count"] = 0 names = list(self.data["gender_analyzed_name"].unique()) for name in names: if name in self.gender.keys(): gender_result = self.gender[name] else: try: # TODO: some errors found due to encode utf-8 issues. # Adding a try-except in the meantime. gender_result = self.connection.get([name])[0] except Exception: continue # Store info in the list of users self.gender[name] = gender_result # Update current dataset if gender_result["gender"] is None: gender_result["gender"] = "NotKnown" self.data.loc[self.data["gender_analyzed_name"] == name, 'gender'] =\ gender_result["gender"] if "probability" in gender_result.keys(): self.data.loc[self.data["gender_analyzed_name"] == name, 'gender_probability'] = gender_result["probability"] self.data.loc[self.data["gender_analyzed_name"] == name, 'gender_count'] = gender_result["count"] self.data.fillna("noname") return self.data
[ "def", "enrich", "(", "self", ",", "column", ")", ":", "if", "column", "not", "in", "self", ".", "data", ".", "columns", ":", "return", "self", ".", "data", "splits", "=", "self", ".", "data", "[", "column", "]", ".", "str", ".", "split", "(", "\" \"", ")", "splits", "=", "splits", ".", "str", "[", "0", "]", "self", ".", "data", "[", "\"gender_analyzed_name\"", "]", "=", "splits", ".", "fillna", "(", "\"noname\"", ")", "self", ".", "data", "[", "\"gender_probability\"", "]", "=", "0", "self", ".", "data", "[", "\"gender\"", "]", "=", "\"Unknown\"", "self", ".", "data", "[", "\"gender_count\"", "]", "=", "0", "names", "=", "list", "(", "self", ".", "data", "[", "\"gender_analyzed_name\"", "]", ".", "unique", "(", ")", ")", "for", "name", "in", "names", ":", "if", "name", "in", "self", ".", "gender", ".", "keys", "(", ")", ":", "gender_result", "=", "self", ".", "gender", "[", "name", "]", "else", ":", "try", ":", "# TODO: some errors found due to encode utf-8 issues.", "# Adding a try-except in the meantime.", "gender_result", "=", "self", ".", "connection", ".", "get", "(", "[", "name", "]", ")", "[", "0", "]", "except", "Exception", ":", "continue", "# Store info in the list of users", "self", ".", "gender", "[", "name", "]", "=", "gender_result", "# Update current dataset", "if", "gender_result", "[", "\"gender\"", "]", "is", "None", ":", "gender_result", "[", "\"gender\"", "]", "=", "\"NotKnown\"", "self", ".", "data", ".", "loc", "[", "self", ".", "data", "[", "\"gender_analyzed_name\"", "]", "==", "name", ",", "'gender'", "]", "=", "gender_result", "[", "\"gender\"", "]", "if", "\"probability\"", "in", "gender_result", ".", "keys", "(", ")", ":", "self", ".", "data", ".", "loc", "[", "self", ".", "data", "[", "\"gender_analyzed_name\"", "]", "==", "name", ",", "'gender_probability'", "]", "=", "gender_result", "[", "\"probability\"", "]", "self", ".", "data", ".", "loc", "[", "self", ".", "data", "[", "\"gender_analyzed_name\"", "]", "==", "name", ",", "'gender_count'", "]", "=", "gender_result", "[", "\"count\"", "]", "self", ".", "data", ".", "fillna", "(", "\"noname\"", ")", "return", "self", ".", "data" ]
This method calculates thanks to the genderize.io API the gender of a given name. This method initially assumes that for the given string, only the first word is the one containing the name eg: Daniel Izquierdo <[email protected]>, Daniel would be the name. If the same class instance is used in later gender searches, this stores in memory a list of names and associated gender and probability. This is intended to have faster identifications of the gender and less number of API accesses. :param column: column where the name is found :type column: string :return: original dataframe with four new columns: * gender: male, female or unknown * gender_probability: value between 0 and 1 * gender_count: number of names found in the Genderized DB * gender_analyzed_name: name that was sent to the API for analysis :rtype: pandas.DataFrame
[ "This", "method", "calculates", "thanks", "to", "the", "genderize", ".", "io", "API", "the", "gender", "of", "a", "given", "name", "." ]
5110e6ca490a4f24bec3124286ebf51fd4e08bdd
https://github.com/chaoss/grimoirelab-cereslib/blob/5110e6ca490a4f24bec3124286ebf51fd4e08bdd/cereslib/enrich/enrich.py#L710-L772
train
chaoss/grimoirelab-cereslib
cereslib/enrich/enrich.py
Uuid.enrich
def enrich(self, columns): """ Merges the original dataframe with corresponding entity uuids based on the given columns. Also merges other additional information associated to uuids provided in the uuids dataframe, if any. :param columns: columns to match for merging :type column: string array :return: original dataframe with at least one new column: * uuid: identity unique identifier :rtype: pandas.DataFrame """ for column in columns: if column not in self.data.columns: return self.data self.data = pandas.merge(self.data, self.uuids_df, how='left', on=columns) self.data = self.data.fillna("notavailable") return self.data
python
def enrich(self, columns): """ Merges the original dataframe with corresponding entity uuids based on the given columns. Also merges other additional information associated to uuids provided in the uuids dataframe, if any. :param columns: columns to match for merging :type column: string array :return: original dataframe with at least one new column: * uuid: identity unique identifier :rtype: pandas.DataFrame """ for column in columns: if column not in self.data.columns: return self.data self.data = pandas.merge(self.data, self.uuids_df, how='left', on=columns) self.data = self.data.fillna("notavailable") return self.data
[ "def", "enrich", "(", "self", ",", "columns", ")", ":", "for", "column", "in", "columns", ":", "if", "column", "not", "in", "self", ".", "data", ".", "columns", ":", "return", "self", ".", "data", "self", ".", "data", "=", "pandas", ".", "merge", "(", "self", ".", "data", ",", "self", ".", "uuids_df", ",", "how", "=", "'left'", ",", "on", "=", "columns", ")", "self", ".", "data", "=", "self", ".", "data", ".", "fillna", "(", "\"notavailable\"", ")", "return", "self", ".", "data" ]
Merges the original dataframe with corresponding entity uuids based on the given columns. Also merges other additional information associated to uuids provided in the uuids dataframe, if any. :param columns: columns to match for merging :type column: string array :return: original dataframe with at least one new column: * uuid: identity unique identifier :rtype: pandas.DataFrame
[ "Merges", "the", "original", "dataframe", "with", "corresponding", "entity", "uuids", "based", "on", "the", "given", "columns", ".", "Also", "merges", "other", "additional", "information", "associated", "to", "uuids", "provided", "in", "the", "uuids", "dataframe", "if", "any", "." ]
5110e6ca490a4f24bec3124286ebf51fd4e08bdd
https://github.com/chaoss/grimoirelab-cereslib/blob/5110e6ca490a4f24bec3124286ebf51fd4e08bdd/cereslib/enrich/enrich.py#L850-L870
train
aiidateam/aiida-codtools
aiida_codtools/common/cli.py
echo_utc
def echo_utc(string): """Echo the string to standard out, prefixed with the current date and time in UTC format. :param string: string to echo """ from datetime import datetime click.echo('{} | {}'.format(datetime.utcnow().isoformat(), string))
python
def echo_utc(string): """Echo the string to standard out, prefixed with the current date and time in UTC format. :param string: string to echo """ from datetime import datetime click.echo('{} | {}'.format(datetime.utcnow().isoformat(), string))
[ "def", "echo_utc", "(", "string", ")", ":", "from", "datetime", "import", "datetime", "click", ".", "echo", "(", "'{} | {}'", ".", "format", "(", "datetime", ".", "utcnow", "(", ")", ".", "isoformat", "(", ")", ",", "string", ")", ")" ]
Echo the string to standard out, prefixed with the current date and time in UTC format. :param string: string to echo
[ "Echo", "the", "string", "to", "standard", "out", "prefixed", "with", "the", "current", "date", "and", "time", "in", "UTC", "format", "." ]
da5e4259b7a2e86cf0cc3f997e11dd36d445fa94
https://github.com/aiidateam/aiida-codtools/blob/da5e4259b7a2e86cf0cc3f997e11dd36d445fa94/aiida_codtools/common/cli.py#L16-L22
train
aiidateam/aiida-codtools
aiida_codtools/common/cli.py
CliParameters.from_string
def from_string(cls, string): """Parse a single string representing all command line parameters.""" if string is None: string = '' if not isinstance(string, six.string_types): raise TypeError('string has to be a string type, got: {}'.format(type(string))) dictionary = {} tokens = [token.strip() for token in shlex.split(string)] def list_tuples(some_iterable): items, nexts = itertools.tee(some_iterable, 2) nexts = itertools.chain(itertools.islice(nexts, 1, None), [None]) return list(zip(items, nexts)) for token_current, token_next in list_tuples(tokens): # If current token starts with a dash, it is a value so we skip it if not token_current.startswith('-'): continue # If the next token is None or starts with a dash, the current token must be a flag, so the value is True if not token_next or token_next.startswith('-'): dictionary[token_current.lstrip('-')] = True # Otherwise the current token is an option with the next token being its value else: dictionary[token_current.lstrip('-')] = token_next return cls.from_dictionary(dictionary)
python
def from_string(cls, string): """Parse a single string representing all command line parameters.""" if string is None: string = '' if not isinstance(string, six.string_types): raise TypeError('string has to be a string type, got: {}'.format(type(string))) dictionary = {} tokens = [token.strip() for token in shlex.split(string)] def list_tuples(some_iterable): items, nexts = itertools.tee(some_iterable, 2) nexts = itertools.chain(itertools.islice(nexts, 1, None), [None]) return list(zip(items, nexts)) for token_current, token_next in list_tuples(tokens): # If current token starts with a dash, it is a value so we skip it if not token_current.startswith('-'): continue # If the next token is None or starts with a dash, the current token must be a flag, so the value is True if not token_next or token_next.startswith('-'): dictionary[token_current.lstrip('-')] = True # Otherwise the current token is an option with the next token being its value else: dictionary[token_current.lstrip('-')] = token_next return cls.from_dictionary(dictionary)
[ "def", "from_string", "(", "cls", ",", "string", ")", ":", "if", "string", "is", "None", ":", "string", "=", "''", "if", "not", "isinstance", "(", "string", ",", "six", ".", "string_types", ")", ":", "raise", "TypeError", "(", "'string has to be a string type, got: {}'", ".", "format", "(", "type", "(", "string", ")", ")", ")", "dictionary", "=", "{", "}", "tokens", "=", "[", "token", ".", "strip", "(", ")", "for", "token", "in", "shlex", ".", "split", "(", "string", ")", "]", "def", "list_tuples", "(", "some_iterable", ")", ":", "items", ",", "nexts", "=", "itertools", ".", "tee", "(", "some_iterable", ",", "2", ")", "nexts", "=", "itertools", ".", "chain", "(", "itertools", ".", "islice", "(", "nexts", ",", "1", ",", "None", ")", ",", "[", "None", "]", ")", "return", "list", "(", "zip", "(", "items", ",", "nexts", ")", ")", "for", "token_current", ",", "token_next", "in", "list_tuples", "(", "tokens", ")", ":", "# If current token starts with a dash, it is a value so we skip it", "if", "not", "token_current", ".", "startswith", "(", "'-'", ")", ":", "continue", "# If the next token is None or starts with a dash, the current token must be a flag, so the value is True", "if", "not", "token_next", "or", "token_next", ".", "startswith", "(", "'-'", ")", ":", "dictionary", "[", "token_current", ".", "lstrip", "(", "'-'", ")", "]", "=", "True", "# Otherwise the current token is an option with the next token being its value", "else", ":", "dictionary", "[", "token_current", ".", "lstrip", "(", "'-'", ")", "]", "=", "token_next", "return", "cls", ".", "from_dictionary", "(", "dictionary", ")" ]
Parse a single string representing all command line parameters.
[ "Parse", "a", "single", "string", "representing", "all", "command", "line", "parameters", "." ]
da5e4259b7a2e86cf0cc3f997e11dd36d445fa94
https://github.com/aiidateam/aiida-codtools/blob/da5e4259b7a2e86cf0cc3f997e11dd36d445fa94/aiida_codtools/common/cli.py#L59-L89
train
aiidateam/aiida-codtools
aiida_codtools/common/cli.py
CliParameters.from_dictionary
def from_dictionary(cls, dictionary): """Parse a dictionary representing all command line parameters.""" if not isinstance(dictionary, dict): raise TypeError('dictionary has to be a dict type, got: {}'.format(type(dictionary))) return cls(dictionary)
python
def from_dictionary(cls, dictionary): """Parse a dictionary representing all command line parameters.""" if not isinstance(dictionary, dict): raise TypeError('dictionary has to be a dict type, got: {}'.format(type(dictionary))) return cls(dictionary)
[ "def", "from_dictionary", "(", "cls", ",", "dictionary", ")", ":", "if", "not", "isinstance", "(", "dictionary", ",", "dict", ")", ":", "raise", "TypeError", "(", "'dictionary has to be a dict type, got: {}'", ".", "format", "(", "type", "(", "dictionary", ")", ")", ")", "return", "cls", "(", "dictionary", ")" ]
Parse a dictionary representing all command line parameters.
[ "Parse", "a", "dictionary", "representing", "all", "command", "line", "parameters", "." ]
da5e4259b7a2e86cf0cc3f997e11dd36d445fa94
https://github.com/aiidateam/aiida-codtools/blob/da5e4259b7a2e86cf0cc3f997e11dd36d445fa94/aiida_codtools/common/cli.py#L92-L97
train
aiidateam/aiida-codtools
aiida_codtools/common/cli.py
CliParameters.get_list
def get_list(self): """Return the command line parameters as a list of options, their values and arguments. :return: list of options, their optional values and arguments """ result = [] for key, value in self.parameters.items(): if value is None: continue if not isinstance(value, list): value = [value] if len(key) == 1: string_key = '-{}'.format(key) else: string_key = '--{}'.format(key) for sub_value in value: if isinstance(sub_value, bool) and sub_value is False: continue result.append(string_key) if not isinstance(sub_value, bool): if ' ' in sub_value: string_value = "'{}'".format(sub_value) else: string_value = sub_value result.append(str(string_value)) return result
python
def get_list(self): """Return the command line parameters as a list of options, their values and arguments. :return: list of options, their optional values and arguments """ result = [] for key, value in self.parameters.items(): if value is None: continue if not isinstance(value, list): value = [value] if len(key) == 1: string_key = '-{}'.format(key) else: string_key = '--{}'.format(key) for sub_value in value: if isinstance(sub_value, bool) and sub_value is False: continue result.append(string_key) if not isinstance(sub_value, bool): if ' ' in sub_value: string_value = "'{}'".format(sub_value) else: string_value = sub_value result.append(str(string_value)) return result
[ "def", "get_list", "(", "self", ")", ":", "result", "=", "[", "]", "for", "key", ",", "value", "in", "self", ".", "parameters", ".", "items", "(", ")", ":", "if", "value", "is", "None", ":", "continue", "if", "not", "isinstance", "(", "value", ",", "list", ")", ":", "value", "=", "[", "value", "]", "if", "len", "(", "key", ")", "==", "1", ":", "string_key", "=", "'-{}'", ".", "format", "(", "key", ")", "else", ":", "string_key", "=", "'--{}'", ".", "format", "(", "key", ")", "for", "sub_value", "in", "value", ":", "if", "isinstance", "(", "sub_value", ",", "bool", ")", "and", "sub_value", "is", "False", ":", "continue", "result", ".", "append", "(", "string_key", ")", "if", "not", "isinstance", "(", "sub_value", ",", "bool", ")", ":", "if", "' '", "in", "sub_value", ":", "string_value", "=", "\"'{}'\"", ".", "format", "(", "sub_value", ")", "else", ":", "string_value", "=", "sub_value", "result", ".", "append", "(", "str", "(", "string_value", ")", ")", "return", "result" ]
Return the command line parameters as a list of options, their values and arguments. :return: list of options, their optional values and arguments
[ "Return", "the", "command", "line", "parameters", "as", "a", "list", "of", "options", "their", "values", "and", "arguments", "." ]
da5e4259b7a2e86cf0cc3f997e11dd36d445fa94
https://github.com/aiidateam/aiida-codtools/blob/da5e4259b7a2e86cf0cc3f997e11dd36d445fa94/aiida_codtools/common/cli.py#L99-L134
train
aiidateam/aiida-codtools
aiida_codtools/common/cli.py
CliRunner.run
def run(self, daemon=False): """Launch the process with the given inputs, by default running in the current interpreter. :param daemon: boolean, if True, will submit the process instead of running it. """ from aiida.engine import launch # If daemon is True, submit the process and return if daemon: node = launch.submit(self.process, **self.inputs) echo.echo_info('Submitted {}<{}>'.format(self.process_name, node.pk)) return # Otherwise we run locally and wait for the process to finish echo.echo_info('Running {}'.format(self.process_name)) try: _, node = launch.run_get_node(self.process, **self.inputs) except Exception as exception: # pylint: disable=broad-except echo.echo_critical('an exception occurred during execution: {}'.format(str(exception))) if node.is_killed: echo.echo_critical('{}<{}> was killed'.format(self.process_name, node.pk)) elif not node.is_finished_ok: arguments = [self.process_name, node.pk, node.exit_status, node.exit_message] echo.echo_warning('{}<{}> failed with exit status {}: {}'.format(*arguments)) else: output = [] echo.echo_success('{}<{}> finished successfully\n'.format(self.process_name, node.pk)) for triple in sorted(node.get_outgoing().all(), key=lambda triple: triple.link_label): output.append([triple.link_label, '{}<{}>'.format(triple.node.__class__.__name__, triple.node.pk)]) echo.echo(tabulate.tabulate(output, headers=['Output label', 'Node']))
python
def run(self, daemon=False): """Launch the process with the given inputs, by default running in the current interpreter. :param daemon: boolean, if True, will submit the process instead of running it. """ from aiida.engine import launch # If daemon is True, submit the process and return if daemon: node = launch.submit(self.process, **self.inputs) echo.echo_info('Submitted {}<{}>'.format(self.process_name, node.pk)) return # Otherwise we run locally and wait for the process to finish echo.echo_info('Running {}'.format(self.process_name)) try: _, node = launch.run_get_node(self.process, **self.inputs) except Exception as exception: # pylint: disable=broad-except echo.echo_critical('an exception occurred during execution: {}'.format(str(exception))) if node.is_killed: echo.echo_critical('{}<{}> was killed'.format(self.process_name, node.pk)) elif not node.is_finished_ok: arguments = [self.process_name, node.pk, node.exit_status, node.exit_message] echo.echo_warning('{}<{}> failed with exit status {}: {}'.format(*arguments)) else: output = [] echo.echo_success('{}<{}> finished successfully\n'.format(self.process_name, node.pk)) for triple in sorted(node.get_outgoing().all(), key=lambda triple: triple.link_label): output.append([triple.link_label, '{}<{}>'.format(triple.node.__class__.__name__, triple.node.pk)]) echo.echo(tabulate.tabulate(output, headers=['Output label', 'Node']))
[ "def", "run", "(", "self", ",", "daemon", "=", "False", ")", ":", "from", "aiida", ".", "engine", "import", "launch", "# If daemon is True, submit the process and return", "if", "daemon", ":", "node", "=", "launch", ".", "submit", "(", "self", ".", "process", ",", "*", "*", "self", ".", "inputs", ")", "echo", ".", "echo_info", "(", "'Submitted {}<{}>'", ".", "format", "(", "self", ".", "process_name", ",", "node", ".", "pk", ")", ")", "return", "# Otherwise we run locally and wait for the process to finish", "echo", ".", "echo_info", "(", "'Running {}'", ".", "format", "(", "self", ".", "process_name", ")", ")", "try", ":", "_", ",", "node", "=", "launch", ".", "run_get_node", "(", "self", ".", "process", ",", "*", "*", "self", ".", "inputs", ")", "except", "Exception", "as", "exception", ":", "# pylint: disable=broad-except", "echo", ".", "echo_critical", "(", "'an exception occurred during execution: {}'", ".", "format", "(", "str", "(", "exception", ")", ")", ")", "if", "node", ".", "is_killed", ":", "echo", ".", "echo_critical", "(", "'{}<{}> was killed'", ".", "format", "(", "self", ".", "process_name", ",", "node", ".", "pk", ")", ")", "elif", "not", "node", ".", "is_finished_ok", ":", "arguments", "=", "[", "self", ".", "process_name", ",", "node", ".", "pk", ",", "node", ".", "exit_status", ",", "node", ".", "exit_message", "]", "echo", ".", "echo_warning", "(", "'{}<{}> failed with exit status {}: {}'", ".", "format", "(", "*", "arguments", ")", ")", "else", ":", "output", "=", "[", "]", "echo", ".", "echo_success", "(", "'{}<{}> finished successfully\\n'", ".", "format", "(", "self", ".", "process_name", ",", "node", ".", "pk", ")", ")", "for", "triple", "in", "sorted", "(", "node", ".", "get_outgoing", "(", ")", ".", "all", "(", ")", ",", "key", "=", "lambda", "triple", ":", "triple", ".", "link_label", ")", ":", "output", ".", "append", "(", "[", "triple", ".", "link_label", ",", "'{}<{}>'", ".", "format", "(", "triple", ".", "node", ".", "__class__", ".", "__name__", ",", "triple", ".", "node", ".", "pk", ")", "]", ")", "echo", ".", "echo", "(", "tabulate", ".", "tabulate", "(", "output", ",", "headers", "=", "[", "'Output label'", ",", "'Node'", "]", ")", ")" ]
Launch the process with the given inputs, by default running in the current interpreter. :param daemon: boolean, if True, will submit the process instead of running it.
[ "Launch", "the", "process", "with", "the", "given", "inputs", "by", "default", "running", "in", "the", "current", "interpreter", "." ]
da5e4259b7a2e86cf0cc3f997e11dd36d445fa94
https://github.com/aiidateam/aiida-codtools/blob/da5e4259b7a2e86cf0cc3f997e11dd36d445fa94/aiida_codtools/common/cli.py#L170-L200
train
Capitains/MyCapytain
MyCapytain/resources/collections/cts.py
_xpathDict
def _xpathDict(xml, xpath, cls, parent, **kwargs): """ Returns a default Dict given certain information :param xml: An xml tree :type xml: etree :param xpath: XPath to find children :type xpath: str :param cls: Class identifying children :type cls: inventory.Resource :param parent: Parent of object :type parent: CtsCollection :rtype: collections.defaultdict.<basestring, inventory.Resource> :returns: Dictionary of children """ children = [] for child in xml.xpath(xpath, namespaces=XPATH_NAMESPACES): children.append(cls.parse( resource=child, parent=parent, **kwargs )) return children
python
def _xpathDict(xml, xpath, cls, parent, **kwargs): """ Returns a default Dict given certain information :param xml: An xml tree :type xml: etree :param xpath: XPath to find children :type xpath: str :param cls: Class identifying children :type cls: inventory.Resource :param parent: Parent of object :type parent: CtsCollection :rtype: collections.defaultdict.<basestring, inventory.Resource> :returns: Dictionary of children """ children = [] for child in xml.xpath(xpath, namespaces=XPATH_NAMESPACES): children.append(cls.parse( resource=child, parent=parent, **kwargs )) return children
[ "def", "_xpathDict", "(", "xml", ",", "xpath", ",", "cls", ",", "parent", ",", "*", "*", "kwargs", ")", ":", "children", "=", "[", "]", "for", "child", "in", "xml", ".", "xpath", "(", "xpath", ",", "namespaces", "=", "XPATH_NAMESPACES", ")", ":", "children", ".", "append", "(", "cls", ".", "parse", "(", "resource", "=", "child", ",", "parent", "=", "parent", ",", "*", "*", "kwargs", ")", ")", "return", "children" ]
Returns a default Dict given certain information :param xml: An xml tree :type xml: etree :param xpath: XPath to find children :type xpath: str :param cls: Class identifying children :type cls: inventory.Resource :param parent: Parent of object :type parent: CtsCollection :rtype: collections.defaultdict.<basestring, inventory.Resource> :returns: Dictionary of children
[ "Returns", "a", "default", "Dict", "given", "certain", "information" ]
b11bbf6b6ae141fc02be70471e3fbf6907be6593
https://github.com/Capitains/MyCapytain/blob/b11bbf6b6ae141fc02be70471e3fbf6907be6593/MyCapytain/resources/collections/cts.py#L79-L100
train
Capitains/MyCapytain
MyCapytain/resources/collections/cts.py
_parse_structured_metadata
def _parse_structured_metadata(obj, xml): """ Parse an XML object for structured metadata :param obj: Object whose metadata are parsed :param xml: XML that needs to be parsed """ for metadata in xml.xpath("cpt:structured-metadata/*", namespaces=XPATH_NAMESPACES): tag = metadata.tag if "{" in tag: ns, tag = tuple(tag.split("}")) tag = URIRef(ns[1:]+tag) s_m = str(metadata) if s_m.startswith("urn:") or s_m.startswith("http:") or s_m.startswith("https:") or s_m.startswith("hdl:"): obj.metadata.add( tag, URIRef(metadata) ) elif '{http://www.w3.org/XML/1998/namespace}lang' in metadata.attrib: obj.metadata.add( tag, s_m, lang=metadata.attrib['{http://www.w3.org/XML/1998/namespace}lang'] ) else: if "{http://www.w3.org/1999/02/22-rdf-syntax-ns#}datatype" in metadata.attrib: datatype = metadata.attrib["{http://www.w3.org/1999/02/22-rdf-syntax-ns#}datatype"] if not datatype.startswith("http") and ":" in datatype: datatype = expand_namespace(metadata.nsmap, datatype) obj.metadata.add(tag, Literal(s_m, datatype=URIRef(datatype))) elif isinstance(metadata, IntElement): obj.metadata.add(tag, Literal(int(metadata), datatype=XSD.integer)) elif isinstance(metadata, FloatElement): obj.metadata.add(tag, Literal(float(metadata), datatype=XSD.float)) else: obj.metadata.add(tag, s_m)
python
def _parse_structured_metadata(obj, xml): """ Parse an XML object for structured metadata :param obj: Object whose metadata are parsed :param xml: XML that needs to be parsed """ for metadata in xml.xpath("cpt:structured-metadata/*", namespaces=XPATH_NAMESPACES): tag = metadata.tag if "{" in tag: ns, tag = tuple(tag.split("}")) tag = URIRef(ns[1:]+tag) s_m = str(metadata) if s_m.startswith("urn:") or s_m.startswith("http:") or s_m.startswith("https:") or s_m.startswith("hdl:"): obj.metadata.add( tag, URIRef(metadata) ) elif '{http://www.w3.org/XML/1998/namespace}lang' in metadata.attrib: obj.metadata.add( tag, s_m, lang=metadata.attrib['{http://www.w3.org/XML/1998/namespace}lang'] ) else: if "{http://www.w3.org/1999/02/22-rdf-syntax-ns#}datatype" in metadata.attrib: datatype = metadata.attrib["{http://www.w3.org/1999/02/22-rdf-syntax-ns#}datatype"] if not datatype.startswith("http") and ":" in datatype: datatype = expand_namespace(metadata.nsmap, datatype) obj.metadata.add(tag, Literal(s_m, datatype=URIRef(datatype))) elif isinstance(metadata, IntElement): obj.metadata.add(tag, Literal(int(metadata), datatype=XSD.integer)) elif isinstance(metadata, FloatElement): obj.metadata.add(tag, Literal(float(metadata), datatype=XSD.float)) else: obj.metadata.add(tag, s_m)
[ "def", "_parse_structured_metadata", "(", "obj", ",", "xml", ")", ":", "for", "metadata", "in", "xml", ".", "xpath", "(", "\"cpt:structured-metadata/*\"", ",", "namespaces", "=", "XPATH_NAMESPACES", ")", ":", "tag", "=", "metadata", ".", "tag", "if", "\"{\"", "in", "tag", ":", "ns", ",", "tag", "=", "tuple", "(", "tag", ".", "split", "(", "\"}\"", ")", ")", "tag", "=", "URIRef", "(", "ns", "[", "1", ":", "]", "+", "tag", ")", "s_m", "=", "str", "(", "metadata", ")", "if", "s_m", ".", "startswith", "(", "\"urn:\"", ")", "or", "s_m", ".", "startswith", "(", "\"http:\"", ")", "or", "s_m", ".", "startswith", "(", "\"https:\"", ")", "or", "s_m", ".", "startswith", "(", "\"hdl:\"", ")", ":", "obj", ".", "metadata", ".", "add", "(", "tag", ",", "URIRef", "(", "metadata", ")", ")", "elif", "'{http://www.w3.org/XML/1998/namespace}lang'", "in", "metadata", ".", "attrib", ":", "obj", ".", "metadata", ".", "add", "(", "tag", ",", "s_m", ",", "lang", "=", "metadata", ".", "attrib", "[", "'{http://www.w3.org/XML/1998/namespace}lang'", "]", ")", "else", ":", "if", "\"{http://www.w3.org/1999/02/22-rdf-syntax-ns#}datatype\"", "in", "metadata", ".", "attrib", ":", "datatype", "=", "metadata", ".", "attrib", "[", "\"{http://www.w3.org/1999/02/22-rdf-syntax-ns#}datatype\"", "]", "if", "not", "datatype", ".", "startswith", "(", "\"http\"", ")", "and", "\":\"", "in", "datatype", ":", "datatype", "=", "expand_namespace", "(", "metadata", ".", "nsmap", ",", "datatype", ")", "obj", ".", "metadata", ".", "add", "(", "tag", ",", "Literal", "(", "s_m", ",", "datatype", "=", "URIRef", "(", "datatype", ")", ")", ")", "elif", "isinstance", "(", "metadata", ",", "IntElement", ")", ":", "obj", ".", "metadata", ".", "add", "(", "tag", ",", "Literal", "(", "int", "(", "metadata", ")", ",", "datatype", "=", "XSD", ".", "integer", ")", ")", "elif", "isinstance", "(", "metadata", ",", "FloatElement", ")", ":", "obj", ".", "metadata", ".", "add", "(", "tag", ",", "Literal", "(", "float", "(", "metadata", ")", ",", "datatype", "=", "XSD", ".", "float", ")", ")", "else", ":", "obj", ".", "metadata", ".", "add", "(", "tag", ",", "s_m", ")" ]
Parse an XML object for structured metadata :param obj: Object whose metadata are parsed :param xml: XML that needs to be parsed
[ "Parse", "an", "XML", "object", "for", "structured", "metadata" ]
b11bbf6b6ae141fc02be70471e3fbf6907be6593
https://github.com/Capitains/MyCapytain/blob/b11bbf6b6ae141fc02be70471e3fbf6907be6593/MyCapytain/resources/collections/cts.py#L103-L137
train
Capitains/MyCapytain
MyCapytain/resources/collections/cts.py
XmlCtsCitation.ingest
def ingest(cls, resource, element=None, xpath="ti:citation"): """ Ingest xml to create a citation :param resource: XML on which to do xpath :param element: Element where the citation should be stored :param xpath: XPath to use to retrieve citation :return: XmlCtsCitation """ # Reuse of of find citation results = resource.xpath(xpath, namespaces=XPATH_NAMESPACES) if len(results) > 0: citation = cls( name=results[0].get("label"), xpath=results[0].get("xpath"), scope=results[0].get("scope") ) if isinstance(element, cls): element.child = citation cls.ingest( resource=results[0], element=element.child ) else: element = citation cls.ingest( resource=results[0], element=element ) return citation return None
python
def ingest(cls, resource, element=None, xpath="ti:citation"): """ Ingest xml to create a citation :param resource: XML on which to do xpath :param element: Element where the citation should be stored :param xpath: XPath to use to retrieve citation :return: XmlCtsCitation """ # Reuse of of find citation results = resource.xpath(xpath, namespaces=XPATH_NAMESPACES) if len(results) > 0: citation = cls( name=results[0].get("label"), xpath=results[0].get("xpath"), scope=results[0].get("scope") ) if isinstance(element, cls): element.child = citation cls.ingest( resource=results[0], element=element.child ) else: element = citation cls.ingest( resource=results[0], element=element ) return citation return None
[ "def", "ingest", "(", "cls", ",", "resource", ",", "element", "=", "None", ",", "xpath", "=", "\"ti:citation\"", ")", ":", "# Reuse of of find citation", "results", "=", "resource", ".", "xpath", "(", "xpath", ",", "namespaces", "=", "XPATH_NAMESPACES", ")", "if", "len", "(", "results", ")", ">", "0", ":", "citation", "=", "cls", "(", "name", "=", "results", "[", "0", "]", ".", "get", "(", "\"label\"", ")", ",", "xpath", "=", "results", "[", "0", "]", ".", "get", "(", "\"xpath\"", ")", ",", "scope", "=", "results", "[", "0", "]", ".", "get", "(", "\"scope\"", ")", ")", "if", "isinstance", "(", "element", ",", "cls", ")", ":", "element", ".", "child", "=", "citation", "cls", ".", "ingest", "(", "resource", "=", "results", "[", "0", "]", ",", "element", "=", "element", ".", "child", ")", "else", ":", "element", "=", "citation", "cls", ".", "ingest", "(", "resource", "=", "results", "[", "0", "]", ",", "element", "=", "element", ")", "return", "citation", "return", "None" ]
Ingest xml to create a citation :param resource: XML on which to do xpath :param element: Element where the citation should be stored :param xpath: XPath to use to retrieve citation :return: XmlCtsCitation
[ "Ingest", "xml", "to", "create", "a", "citation" ]
b11bbf6b6ae141fc02be70471e3fbf6907be6593
https://github.com/Capitains/MyCapytain/blob/b11bbf6b6ae141fc02be70471e3fbf6907be6593/MyCapytain/resources/collections/cts.py#L43-L76
train
Capitains/MyCapytain
MyCapytain/resources/collections/cts.py
XmlCtsTextMetadata.parse_metadata
def parse_metadata(cls, obj, xml): """ Parse a resource to feed the object :param obj: Obj to set metadata of :type obj: XmlCtsTextMetadata :param xml: An xml representation object :type xml: lxml.etree._Element """ for child in xml.xpath("ti:description", namespaces=XPATH_NAMESPACES): lg = child.get("{http://www.w3.org/XML/1998/namespace}lang") if lg is not None: obj.set_cts_property("description", child.text, lg) for child in xml.xpath("ti:label", namespaces=XPATH_NAMESPACES): lg = child.get("{http://www.w3.org/XML/1998/namespace}lang") if lg is not None: obj.set_cts_property("label", child.text, lg) obj.citation = cls.CLASS_CITATION.ingest(xml, obj.citation, "ti:online/ti:citationMapping/ti:citation") # Added for commentary for child in xml.xpath("ti:about", namespaces=XPATH_NAMESPACES): obj.set_link(RDF_NAMESPACES.CTS.term("about"), child.get('urn')) _parse_structured_metadata(obj, xml) """ online = xml.xpath("ti:online", namespaces=NS) if len(online) > 0: online = online[0] obj.docname = online.get("docname") for validate in online.xpath("ti:validate", namespaces=NS): obj.validate = validate.get("schema") for namespaceMapping in online.xpath("ti:namespaceMapping", namespaces=NS): obj.metadata["namespaceMapping"][namespaceMapping.get("abbreviation")] = namespaceMapping.get("nsURI") """
python
def parse_metadata(cls, obj, xml): """ Parse a resource to feed the object :param obj: Obj to set metadata of :type obj: XmlCtsTextMetadata :param xml: An xml representation object :type xml: lxml.etree._Element """ for child in xml.xpath("ti:description", namespaces=XPATH_NAMESPACES): lg = child.get("{http://www.w3.org/XML/1998/namespace}lang") if lg is not None: obj.set_cts_property("description", child.text, lg) for child in xml.xpath("ti:label", namespaces=XPATH_NAMESPACES): lg = child.get("{http://www.w3.org/XML/1998/namespace}lang") if lg is not None: obj.set_cts_property("label", child.text, lg) obj.citation = cls.CLASS_CITATION.ingest(xml, obj.citation, "ti:online/ti:citationMapping/ti:citation") # Added for commentary for child in xml.xpath("ti:about", namespaces=XPATH_NAMESPACES): obj.set_link(RDF_NAMESPACES.CTS.term("about"), child.get('urn')) _parse_structured_metadata(obj, xml) """ online = xml.xpath("ti:online", namespaces=NS) if len(online) > 0: online = online[0] obj.docname = online.get("docname") for validate in online.xpath("ti:validate", namespaces=NS): obj.validate = validate.get("schema") for namespaceMapping in online.xpath("ti:namespaceMapping", namespaces=NS): obj.metadata["namespaceMapping"][namespaceMapping.get("abbreviation")] = namespaceMapping.get("nsURI") """
[ "def", "parse_metadata", "(", "cls", ",", "obj", ",", "xml", ")", ":", "for", "child", "in", "xml", ".", "xpath", "(", "\"ti:description\"", ",", "namespaces", "=", "XPATH_NAMESPACES", ")", ":", "lg", "=", "child", ".", "get", "(", "\"{http://www.w3.org/XML/1998/namespace}lang\"", ")", "if", "lg", "is", "not", "None", ":", "obj", ".", "set_cts_property", "(", "\"description\"", ",", "child", ".", "text", ",", "lg", ")", "for", "child", "in", "xml", ".", "xpath", "(", "\"ti:label\"", ",", "namespaces", "=", "XPATH_NAMESPACES", ")", ":", "lg", "=", "child", ".", "get", "(", "\"{http://www.w3.org/XML/1998/namespace}lang\"", ")", "if", "lg", "is", "not", "None", ":", "obj", ".", "set_cts_property", "(", "\"label\"", ",", "child", ".", "text", ",", "lg", ")", "obj", ".", "citation", "=", "cls", ".", "CLASS_CITATION", ".", "ingest", "(", "xml", ",", "obj", ".", "citation", ",", "\"ti:online/ti:citationMapping/ti:citation\"", ")", "# Added for commentary", "for", "child", "in", "xml", ".", "xpath", "(", "\"ti:about\"", ",", "namespaces", "=", "XPATH_NAMESPACES", ")", ":", "obj", ".", "set_link", "(", "RDF_NAMESPACES", ".", "CTS", ".", "term", "(", "\"about\"", ")", ",", "child", ".", "get", "(", "'urn'", ")", ")", "_parse_structured_metadata", "(", "obj", ",", "xml", ")", "\"\"\"\n online = xml.xpath(\"ti:online\", namespaces=NS)\n if len(online) > 0:\n online = online[0]\n obj.docname = online.get(\"docname\")\n for validate in online.xpath(\"ti:validate\", namespaces=NS):\n obj.validate = validate.get(\"schema\")\n for namespaceMapping in online.xpath(\"ti:namespaceMapping\", namespaces=NS):\n obj.metadata[\"namespaceMapping\"][namespaceMapping.get(\"abbreviation\")] = namespaceMapping.get(\"nsURI\")\n \"\"\"" ]
Parse a resource to feed the object :param obj: Obj to set metadata of :type obj: XmlCtsTextMetadata :param xml: An xml representation object :type xml: lxml.etree._Element
[ "Parse", "a", "resource", "to", "feed", "the", "object" ]
b11bbf6b6ae141fc02be70471e3fbf6907be6593
https://github.com/Capitains/MyCapytain/blob/b11bbf6b6ae141fc02be70471e3fbf6907be6593/MyCapytain/resources/collections/cts.py#L156-L192
train
Capitains/MyCapytain
MyCapytain/resources/collections/cts.py
XmlCtsTextgroupMetadata.parse
def parse(cls, resource, parent=None): """ Parse a textgroup resource :param resource: Element representing the textgroup :param parent: Parent of the textgroup :param _cls_dict: Dictionary of classes to generate subclasses """ xml = xmlparser(resource) o = cls(urn=xml.get("urn"), parent=parent) for child in xml.xpath("ti:groupname", namespaces=XPATH_NAMESPACES): lg = child.get("{http://www.w3.org/XML/1998/namespace}lang") if lg is not None: o.set_cts_property("groupname", child.text, lg) # Parse Works _xpathDict(xml=xml, xpath='ti:work', cls=cls.CLASS_WORK, parent=o) _parse_structured_metadata(o, xml) return o
python
def parse(cls, resource, parent=None): """ Parse a textgroup resource :param resource: Element representing the textgroup :param parent: Parent of the textgroup :param _cls_dict: Dictionary of classes to generate subclasses """ xml = xmlparser(resource) o = cls(urn=xml.get("urn"), parent=parent) for child in xml.xpath("ti:groupname", namespaces=XPATH_NAMESPACES): lg = child.get("{http://www.w3.org/XML/1998/namespace}lang") if lg is not None: o.set_cts_property("groupname", child.text, lg) # Parse Works _xpathDict(xml=xml, xpath='ti:work', cls=cls.CLASS_WORK, parent=o) _parse_structured_metadata(o, xml) return o
[ "def", "parse", "(", "cls", ",", "resource", ",", "parent", "=", "None", ")", ":", "xml", "=", "xmlparser", "(", "resource", ")", "o", "=", "cls", "(", "urn", "=", "xml", ".", "get", "(", "\"urn\"", ")", ",", "parent", "=", "parent", ")", "for", "child", "in", "xml", ".", "xpath", "(", "\"ti:groupname\"", ",", "namespaces", "=", "XPATH_NAMESPACES", ")", ":", "lg", "=", "child", ".", "get", "(", "\"{http://www.w3.org/XML/1998/namespace}lang\"", ")", "if", "lg", "is", "not", "None", ":", "o", ".", "set_cts_property", "(", "\"groupname\"", ",", "child", ".", "text", ",", "lg", ")", "# Parse Works", "_xpathDict", "(", "xml", "=", "xml", ",", "xpath", "=", "'ti:work'", ",", "cls", "=", "cls", ".", "CLASS_WORK", ",", "parent", "=", "o", ")", "_parse_structured_metadata", "(", "o", ",", "xml", ")", "return", "o" ]
Parse a textgroup resource :param resource: Element representing the textgroup :param parent: Parent of the textgroup :param _cls_dict: Dictionary of classes to generate subclasses
[ "Parse", "a", "textgroup", "resource" ]
b11bbf6b6ae141fc02be70471e3fbf6907be6593
https://github.com/Capitains/MyCapytain/blob/b11bbf6b6ae141fc02be70471e3fbf6907be6593/MyCapytain/resources/collections/cts.py#L305-L324
train
infothrill/python-launchd
example.py
install
def install(label, plist): ''' Utility function to store a new .plist file and load it :param label: job label :param plist: a property list dictionary ''' fname = launchd.plist.write(label, plist) launchd.load(fname)
python
def install(label, plist): ''' Utility function to store a new .plist file and load it :param label: job label :param plist: a property list dictionary ''' fname = launchd.plist.write(label, plist) launchd.load(fname)
[ "def", "install", "(", "label", ",", "plist", ")", ":", "fname", "=", "launchd", ".", "plist", ".", "write", "(", "label", ",", "plist", ")", "launchd", ".", "load", "(", "fname", ")" ]
Utility function to store a new .plist file and load it :param label: job label :param plist: a property list dictionary
[ "Utility", "function", "to", "store", "a", "new", ".", "plist", "file", "and", "load", "it" ]
2cd50579e808851b116f5a26f9b871a32b65ce0e
https://github.com/infothrill/python-launchd/blob/2cd50579e808851b116f5a26f9b871a32b65ce0e/example.py#L12-L20
train
infothrill/python-launchd
example.py
uninstall
def uninstall(label): ''' Utility function to remove a .plist file and unload it :param label: job label ''' if launchd.LaunchdJob(label).exists(): fname = launchd.plist.discover_filename(label) launchd.unload(fname) os.unlink(fname)
python
def uninstall(label): ''' Utility function to remove a .plist file and unload it :param label: job label ''' if launchd.LaunchdJob(label).exists(): fname = launchd.plist.discover_filename(label) launchd.unload(fname) os.unlink(fname)
[ "def", "uninstall", "(", "label", ")", ":", "if", "launchd", ".", "LaunchdJob", "(", "label", ")", ".", "exists", "(", ")", ":", "fname", "=", "launchd", ".", "plist", ".", "discover_filename", "(", "label", ")", "launchd", ".", "unload", "(", "fname", ")", "os", ".", "unlink", "(", "fname", ")" ]
Utility function to remove a .plist file and unload it :param label: job label
[ "Utility", "function", "to", "remove", "a", ".", "plist", "file", "and", "unload", "it" ]
2cd50579e808851b116f5a26f9b871a32b65ce0e
https://github.com/infothrill/python-launchd/blob/2cd50579e808851b116f5a26f9b871a32b65ce0e/example.py#L23-L32
train
Grumbel/procmem
procmem/hexdump.py
write_hex
def write_hex(fout, buf, offset, width=16): """Write the content of 'buf' out in a hexdump style Args: fout: file object to write to buf: the buffer to be pretty printed offset: the starting offset of the buffer width: how many bytes should be displayed per row """ skipped_zeroes = 0 for i, chunk in enumerate(chunk_iter(buf, width)): # zero skipping if chunk == (b"\x00" * width): skipped_zeroes += 1 continue elif skipped_zeroes != 0: fout.write(" -- skipped zeroes: {}\n".format(skipped_zeroes)) skipped_zeroes = 0 # starting address of the current line fout.write("{:016x} ".format(i * width + offset)) # bytes column column = " ".join([" ".join(["{:02x}".format(c) for c in subchunk]) for subchunk in chunk_iter(chunk, 8)]) w = width * 2 + (width - 1) + ((width // 8) - 1) if len(column) != w: column += " " * (w - len(column)) fout.write(column) # ASCII character column fout.write(" |") for c in chunk: if c in PRINTABLE_CHARS: fout.write(chr(c)) else: fout.write(".") if len(chunk) < width: fout.write(" " * (width - len(chunk))) fout.write("|") fout.write("\n")
python
def write_hex(fout, buf, offset, width=16): """Write the content of 'buf' out in a hexdump style Args: fout: file object to write to buf: the buffer to be pretty printed offset: the starting offset of the buffer width: how many bytes should be displayed per row """ skipped_zeroes = 0 for i, chunk in enumerate(chunk_iter(buf, width)): # zero skipping if chunk == (b"\x00" * width): skipped_zeroes += 1 continue elif skipped_zeroes != 0: fout.write(" -- skipped zeroes: {}\n".format(skipped_zeroes)) skipped_zeroes = 0 # starting address of the current line fout.write("{:016x} ".format(i * width + offset)) # bytes column column = " ".join([" ".join(["{:02x}".format(c) for c in subchunk]) for subchunk in chunk_iter(chunk, 8)]) w = width * 2 + (width - 1) + ((width // 8) - 1) if len(column) != w: column += " " * (w - len(column)) fout.write(column) # ASCII character column fout.write(" |") for c in chunk: if c in PRINTABLE_CHARS: fout.write(chr(c)) else: fout.write(".") if len(chunk) < width: fout.write(" " * (width - len(chunk))) fout.write("|") fout.write("\n")
[ "def", "write_hex", "(", "fout", ",", "buf", ",", "offset", ",", "width", "=", "16", ")", ":", "skipped_zeroes", "=", "0", "for", "i", ",", "chunk", "in", "enumerate", "(", "chunk_iter", "(", "buf", ",", "width", ")", ")", ":", "# zero skipping", "if", "chunk", "==", "(", "b\"\\x00\"", "*", "width", ")", ":", "skipped_zeroes", "+=", "1", "continue", "elif", "skipped_zeroes", "!=", "0", ":", "fout", ".", "write", "(", "\" -- skipped zeroes: {}\\n\"", ".", "format", "(", "skipped_zeroes", ")", ")", "skipped_zeroes", "=", "0", "# starting address of the current line", "fout", ".", "write", "(", "\"{:016x} \"", ".", "format", "(", "i", "*", "width", "+", "offset", ")", ")", "# bytes column", "column", "=", "\" \"", ".", "join", "(", "[", "\" \"", ".", "join", "(", "[", "\"{:02x}\"", ".", "format", "(", "c", ")", "for", "c", "in", "subchunk", "]", ")", "for", "subchunk", "in", "chunk_iter", "(", "chunk", ",", "8", ")", "]", ")", "w", "=", "width", "*", "2", "+", "(", "width", "-", "1", ")", "+", "(", "(", "width", "//", "8", ")", "-", "1", ")", "if", "len", "(", "column", ")", "!=", "w", ":", "column", "+=", "\" \"", "*", "(", "w", "-", "len", "(", "column", ")", ")", "fout", ".", "write", "(", "column", ")", "# ASCII character column", "fout", ".", "write", "(", "\" |\"", ")", "for", "c", "in", "chunk", ":", "if", "c", "in", "PRINTABLE_CHARS", ":", "fout", ".", "write", "(", "chr", "(", "c", ")", ")", "else", ":", "fout", ".", "write", "(", "\".\"", ")", "if", "len", "(", "chunk", ")", "<", "width", ":", "fout", ".", "write", "(", "\" \"", "*", "(", "width", "-", "len", "(", "chunk", ")", ")", ")", "fout", ".", "write", "(", "\"|\"", ")", "fout", ".", "write", "(", "\"\\n\"", ")" ]
Write the content of 'buf' out in a hexdump style Args: fout: file object to write to buf: the buffer to be pretty printed offset: the starting offset of the buffer width: how many bytes should be displayed per row
[ "Write", "the", "content", "of", "buf", "out", "in", "a", "hexdump", "style" ]
a832a02c4ac79c15f108c72b251820e959a16639
https://github.com/Grumbel/procmem/blob/a832a02c4ac79c15f108c72b251820e959a16639/procmem/hexdump.py#L26-L68
train
jedie/PyHardLinkBackup
PyHardLinkBackup/phlb/config.py
PyHardLinkBackupConfig._read_config
def _read_config(self): """ returns the config as a dict. """ default_config_filepath = Path2(os.path.dirname(__file__), DEAFULT_CONFIG_FILENAME) log.debug("Read defaults from: '%s'" % default_config_filepath) if not default_config_filepath.is_file(): raise RuntimeError( "Internal error: Can't locate the default .ini file here: '%s'" % default_config_filepath ) config = self._read_and_convert(default_config_filepath, all_values=True) log.debug("Defaults: %s", pprint.pformat(config)) self.ini_filepath = get_ini_filepath() if not self.ini_filepath: # No .ini file made by user found # -> Create one into user home self.ini_filepath = get_user_ini_filepath() # We don't use shutil.copyfile here, so the line endings will # be converted e.g. under windows from \n to \n\r with default_config_filepath.open("r") as infile: with self.ini_filepath.open("w") as outfile: outfile.write(infile.read()) print("\n*************************************************************") print("Default config file was created into your home:") print("\t%s" % self.ini_filepath) print("Change it for your needs ;)") print("*************************************************************\n") else: print("\nread user configuration from:") print("\t%s\n" % self.ini_filepath) config.update(self._read_and_convert(self.ini_filepath, all_values=False)) log.debug("RawConfig changed to: %s", pprint.pformat(config)) return config
python
def _read_config(self): """ returns the config as a dict. """ default_config_filepath = Path2(os.path.dirname(__file__), DEAFULT_CONFIG_FILENAME) log.debug("Read defaults from: '%s'" % default_config_filepath) if not default_config_filepath.is_file(): raise RuntimeError( "Internal error: Can't locate the default .ini file here: '%s'" % default_config_filepath ) config = self._read_and_convert(default_config_filepath, all_values=True) log.debug("Defaults: %s", pprint.pformat(config)) self.ini_filepath = get_ini_filepath() if not self.ini_filepath: # No .ini file made by user found # -> Create one into user home self.ini_filepath = get_user_ini_filepath() # We don't use shutil.copyfile here, so the line endings will # be converted e.g. under windows from \n to \n\r with default_config_filepath.open("r") as infile: with self.ini_filepath.open("w") as outfile: outfile.write(infile.read()) print("\n*************************************************************") print("Default config file was created into your home:") print("\t%s" % self.ini_filepath) print("Change it for your needs ;)") print("*************************************************************\n") else: print("\nread user configuration from:") print("\t%s\n" % self.ini_filepath) config.update(self._read_and_convert(self.ini_filepath, all_values=False)) log.debug("RawConfig changed to: %s", pprint.pformat(config)) return config
[ "def", "_read_config", "(", "self", ")", ":", "default_config_filepath", "=", "Path2", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ",", "DEAFULT_CONFIG_FILENAME", ")", "log", ".", "debug", "(", "\"Read defaults from: '%s'\"", "%", "default_config_filepath", ")", "if", "not", "default_config_filepath", ".", "is_file", "(", ")", ":", "raise", "RuntimeError", "(", "\"Internal error: Can't locate the default .ini file here: '%s'\"", "%", "default_config_filepath", ")", "config", "=", "self", ".", "_read_and_convert", "(", "default_config_filepath", ",", "all_values", "=", "True", ")", "log", ".", "debug", "(", "\"Defaults: %s\"", ",", "pprint", ".", "pformat", "(", "config", ")", ")", "self", ".", "ini_filepath", "=", "get_ini_filepath", "(", ")", "if", "not", "self", ".", "ini_filepath", ":", "# No .ini file made by user found", "# -> Create one into user home", "self", ".", "ini_filepath", "=", "get_user_ini_filepath", "(", ")", "# We don't use shutil.copyfile here, so the line endings will", "# be converted e.g. under windows from \\n to \\n\\r", "with", "default_config_filepath", ".", "open", "(", "\"r\"", ")", "as", "infile", ":", "with", "self", ".", "ini_filepath", ".", "open", "(", "\"w\"", ")", "as", "outfile", ":", "outfile", ".", "write", "(", "infile", ".", "read", "(", ")", ")", "print", "(", "\"\\n*************************************************************\"", ")", "print", "(", "\"Default config file was created into your home:\"", ")", "print", "(", "\"\\t%s\"", "%", "self", ".", "ini_filepath", ")", "print", "(", "\"Change it for your needs ;)\"", ")", "print", "(", "\"*************************************************************\\n\"", ")", "else", ":", "print", "(", "\"\\nread user configuration from:\"", ")", "print", "(", "\"\\t%s\\n\"", "%", "self", ".", "ini_filepath", ")", "config", ".", "update", "(", "self", ".", "_read_and_convert", "(", "self", ".", "ini_filepath", ",", "all_values", "=", "False", ")", ")", "log", ".", "debug", "(", "\"RawConfig changed to: %s\"", ",", "pprint", ".", "pformat", "(", "config", ")", ")", "return", "config" ]
returns the config as a dict.
[ "returns", "the", "config", "as", "a", "dict", "." ]
be28666834d2d9e3d8aac1b661cb2d5bd4056c29
https://github.com/jedie/PyHardLinkBackup/blob/be28666834d2d9e3d8aac1b661cb2d5bd4056c29/PyHardLinkBackup/phlb/config.py#L197-L233
train
Capitains/MyCapytain
MyCapytain/common/constants.py
bind_graph
def bind_graph(graph=None): """ Bind a graph with generic MyCapytain prefixes :param graph: Graph (Optional) :return: Bound graph """ if graph is None: graph = Graph() for prefix, ns in GRAPH_BINDINGS.items(): graph.bind(prefix, ns, True) return graph
python
def bind_graph(graph=None): """ Bind a graph with generic MyCapytain prefixes :param graph: Graph (Optional) :return: Bound graph """ if graph is None: graph = Graph() for prefix, ns in GRAPH_BINDINGS.items(): graph.bind(prefix, ns, True) return graph
[ "def", "bind_graph", "(", "graph", "=", "None", ")", ":", "if", "graph", "is", "None", ":", "graph", "=", "Graph", "(", ")", "for", "prefix", ",", "ns", "in", "GRAPH_BINDINGS", ".", "items", "(", ")", ":", "graph", ".", "bind", "(", "prefix", ",", "ns", ",", "True", ")", "return", "graph" ]
Bind a graph with generic MyCapytain prefixes :param graph: Graph (Optional) :return: Bound graph
[ "Bind", "a", "graph", "with", "generic", "MyCapytain", "prefixes" ]
b11bbf6b6ae141fc02be70471e3fbf6907be6593
https://github.com/Capitains/MyCapytain/blob/b11bbf6b6ae141fc02be70471e3fbf6907be6593/MyCapytain/common/constants.py#L123-L133
train
SHDShim/pytheos
pytheos/eqn_electronic.py
zharkov_pel
def zharkov_pel(v, temp, v0, e0, g, n, z, t_ref=300., three_r=3. * constants.R): """ calculate electronic contributions in pressure for the Zharkov equation the equation can be found in Sokolova and Dorogokupets 2013 :param v: unit-cell volume in A^3 :param temp: temperature in K :param v0: unit-cell volume in A^3 at 1 bar :param e0: parameter in K-1 for the Zharkov equation :param g: parameter for the Zharkov equation :param n: number of atoms in a formula unit :param z: number of formula unit in a unit cell :param t_ref: reference temperature, 300 K :param three_r: 3 times gas constant :return: electronic contribution in GPa """ v_mol = vol_uc2mol(v, z) x = v / v0 # a = a0 * np.power(x, m) def f(t): return three_r * n / 2. * e0 * np.power(x, g) * np.power(t, 2.) * \ g / v_mol * 1.e-9 return f(temp) - f(t_ref)
python
def zharkov_pel(v, temp, v0, e0, g, n, z, t_ref=300., three_r=3. * constants.R): """ calculate electronic contributions in pressure for the Zharkov equation the equation can be found in Sokolova and Dorogokupets 2013 :param v: unit-cell volume in A^3 :param temp: temperature in K :param v0: unit-cell volume in A^3 at 1 bar :param e0: parameter in K-1 for the Zharkov equation :param g: parameter for the Zharkov equation :param n: number of atoms in a formula unit :param z: number of formula unit in a unit cell :param t_ref: reference temperature, 300 K :param three_r: 3 times gas constant :return: electronic contribution in GPa """ v_mol = vol_uc2mol(v, z) x = v / v0 # a = a0 * np.power(x, m) def f(t): return three_r * n / 2. * e0 * np.power(x, g) * np.power(t, 2.) * \ g / v_mol * 1.e-9 return f(temp) - f(t_ref)
[ "def", "zharkov_pel", "(", "v", ",", "temp", ",", "v0", ",", "e0", ",", "g", ",", "n", ",", "z", ",", "t_ref", "=", "300.", ",", "three_r", "=", "3.", "*", "constants", ".", "R", ")", ":", "v_mol", "=", "vol_uc2mol", "(", "v", ",", "z", ")", "x", "=", "v", "/", "v0", "# a = a0 * np.power(x, m)", "def", "f", "(", "t", ")", ":", "return", "three_r", "*", "n", "/", "2.", "*", "e0", "*", "np", ".", "power", "(", "x", ",", "g", ")", "*", "np", ".", "power", "(", "t", ",", "2.", ")", "*", "g", "/", "v_mol", "*", "1.e-9", "return", "f", "(", "temp", ")", "-", "f", "(", "t_ref", ")" ]
calculate electronic contributions in pressure for the Zharkov equation the equation can be found in Sokolova and Dorogokupets 2013 :param v: unit-cell volume in A^3 :param temp: temperature in K :param v0: unit-cell volume in A^3 at 1 bar :param e0: parameter in K-1 for the Zharkov equation :param g: parameter for the Zharkov equation :param n: number of atoms in a formula unit :param z: number of formula unit in a unit cell :param t_ref: reference temperature, 300 K :param three_r: 3 times gas constant :return: electronic contribution in GPa
[ "calculate", "electronic", "contributions", "in", "pressure", "for", "the", "Zharkov", "equation", "the", "equation", "can", "be", "found", "in", "Sokolova", "and", "Dorogokupets", "2013" ]
be079624405e92fbec60c5ead253eb5917e55237
https://github.com/SHDShim/pytheos/blob/be079624405e92fbec60c5ead253eb5917e55237/pytheos/eqn_electronic.py#L6-L30
train
SHDShim/pytheos
pytheos/eqn_electronic.py
tsuchiya_pel
def tsuchiya_pel(v, temp, v0, a, b, c, d, n, z, three_r=3. * constants.R, t_ref=300.): """ calculate electronic contributions in pressure for the Tsuchiya equation :param v: unit-cell volume in A^3 :param temp: temperature in K :param v0: unit-cell volume in A^3 at 1 bar :param a: parameter for the Tsuchiya equation :param b: parameter for the Tsuchiya equation :param c: parameter for the Tsuchiya equation :param d: parameter for the Tsuchiya equation :param n: number of atoms in a formula unit :param z: number of formula unit in a unit cell :param t_ref: reference temperature, 300 K :param three_r: 3 times gas constant :return: electronic contribution in GPa :note: n, z, three_r are not used but in there for consistency with other electronic contribution equations """ def f(temp): return a + b * temp + c * np.power(temp, 2.) + d * np.power(temp, 3.) return f(temp) - f(t_ref)
python
def tsuchiya_pel(v, temp, v0, a, b, c, d, n, z, three_r=3. * constants.R, t_ref=300.): """ calculate electronic contributions in pressure for the Tsuchiya equation :param v: unit-cell volume in A^3 :param temp: temperature in K :param v0: unit-cell volume in A^3 at 1 bar :param a: parameter for the Tsuchiya equation :param b: parameter for the Tsuchiya equation :param c: parameter for the Tsuchiya equation :param d: parameter for the Tsuchiya equation :param n: number of atoms in a formula unit :param z: number of formula unit in a unit cell :param t_ref: reference temperature, 300 K :param three_r: 3 times gas constant :return: electronic contribution in GPa :note: n, z, three_r are not used but in there for consistency with other electronic contribution equations """ def f(temp): return a + b * temp + c * np.power(temp, 2.) + d * np.power(temp, 3.) return f(temp) - f(t_ref)
[ "def", "tsuchiya_pel", "(", "v", ",", "temp", ",", "v0", ",", "a", ",", "b", ",", "c", ",", "d", ",", "n", ",", "z", ",", "three_r", "=", "3.", "*", "constants", ".", "R", ",", "t_ref", "=", "300.", ")", ":", "def", "f", "(", "temp", ")", ":", "return", "a", "+", "b", "*", "temp", "+", "c", "*", "np", ".", "power", "(", "temp", ",", "2.", ")", "+", "d", "*", "np", ".", "power", "(", "temp", ",", "3.", ")", "return", "f", "(", "temp", ")", "-", "f", "(", "t_ref", ")" ]
calculate electronic contributions in pressure for the Tsuchiya equation :param v: unit-cell volume in A^3 :param temp: temperature in K :param v0: unit-cell volume in A^3 at 1 bar :param a: parameter for the Tsuchiya equation :param b: parameter for the Tsuchiya equation :param c: parameter for the Tsuchiya equation :param d: parameter for the Tsuchiya equation :param n: number of atoms in a formula unit :param z: number of formula unit in a unit cell :param t_ref: reference temperature, 300 K :param three_r: 3 times gas constant :return: electronic contribution in GPa :note: n, z, three_r are not used but in there for consistency with other electronic contribution equations
[ "calculate", "electronic", "contributions", "in", "pressure", "for", "the", "Tsuchiya", "equation" ]
be079624405e92fbec60c5ead253eb5917e55237
https://github.com/SHDShim/pytheos/blob/be079624405e92fbec60c5ead253eb5917e55237/pytheos/eqn_electronic.py#L33-L55
train
aiidateam/aiida-codtools
aiida_codtools/calculations/cif_base.py
CifBaseCalculation._validate_resources
def _validate_resources(self): """Validate the resources defined in the options.""" resources = self.options.resources for key in ['num_machines', 'num_mpiprocs_per_machine', 'tot_num_mpiprocs']: if key in resources and resources[key] != 1: raise exceptions.FeatureNotAvailable( "Cannot set resource '{}' to value '{}' for {}: parallelization is not supported, " "only a value of '1' is accepted.".format(key, resources[key], self.__class__.__name__))
python
def _validate_resources(self): """Validate the resources defined in the options.""" resources = self.options.resources for key in ['num_machines', 'num_mpiprocs_per_machine', 'tot_num_mpiprocs']: if key in resources and resources[key] != 1: raise exceptions.FeatureNotAvailable( "Cannot set resource '{}' to value '{}' for {}: parallelization is not supported, " "only a value of '1' is accepted.".format(key, resources[key], self.__class__.__name__))
[ "def", "_validate_resources", "(", "self", ")", ":", "resources", "=", "self", ".", "options", ".", "resources", "for", "key", "in", "[", "'num_machines'", ",", "'num_mpiprocs_per_machine'", ",", "'tot_num_mpiprocs'", "]", ":", "if", "key", "in", "resources", "and", "resources", "[", "key", "]", "!=", "1", ":", "raise", "exceptions", ".", "FeatureNotAvailable", "(", "\"Cannot set resource '{}' to value '{}' for {}: parallelization is not supported, \"", "\"only a value of '1' is accepted.\"", ".", "format", "(", "key", ",", "resources", "[", "key", "]", ",", "self", ".", "__class__", ".", "__name__", ")", ")" ]
Validate the resources defined in the options.
[ "Validate", "the", "resources", "defined", "in", "the", "options", "." ]
da5e4259b7a2e86cf0cc3f997e11dd36d445fa94
https://github.com/aiidateam/aiida-codtools/blob/da5e4259b7a2e86cf0cc3f997e11dd36d445fa94/aiida_codtools/calculations/cif_base.py#L58-L66
train
aiidateam/aiida-codtools
aiida_codtools/calculations/cif_base.py
CifBaseCalculation.prepare_for_submission
def prepare_for_submission(self, folder): """This method is called prior to job submission with a set of calculation input nodes. The inputs will be validated and sanitized, after which the necessary input files will be written to disk in a temporary folder. A CalcInfo instance will be returned that contains lists of files that need to be copied to the remote machine before job submission, as well as file lists that are to be retrieved after job completion. :param folder: an aiida.common.folders.Folder to temporarily write files on disk :returns: CalcInfo instance """ from aiida_codtools.common.cli import CliParameters try: parameters = self.inputs.parameters.get_dict() except AttributeError: parameters = {} self._validate_resources() cli_parameters = copy.deepcopy(self._default_cli_parameters) cli_parameters.update(parameters) codeinfo = datastructures.CodeInfo() codeinfo.code_uuid = self.inputs.code.uuid codeinfo.cmdline_params = CliParameters.from_dictionary(cli_parameters).get_list() codeinfo.stdin_name = self.options.input_filename codeinfo.stdout_name = self.options.output_filename codeinfo.stderr_name = self.options.error_filename calcinfo = datastructures.CalcInfo() calcinfo.uuid = str(self.uuid) calcinfo.codes_info = [codeinfo] calcinfo.retrieve_list = [self.options.output_filename, self.options.error_filename] calcinfo.local_copy_list = [(self.inputs.cif.uuid, self.inputs.cif.filename, self.options.input_filename)] calcinfo.remote_copy_list = [] return calcinfo
python
def prepare_for_submission(self, folder): """This method is called prior to job submission with a set of calculation input nodes. The inputs will be validated and sanitized, after which the necessary input files will be written to disk in a temporary folder. A CalcInfo instance will be returned that contains lists of files that need to be copied to the remote machine before job submission, as well as file lists that are to be retrieved after job completion. :param folder: an aiida.common.folders.Folder to temporarily write files on disk :returns: CalcInfo instance """ from aiida_codtools.common.cli import CliParameters try: parameters = self.inputs.parameters.get_dict() except AttributeError: parameters = {} self._validate_resources() cli_parameters = copy.deepcopy(self._default_cli_parameters) cli_parameters.update(parameters) codeinfo = datastructures.CodeInfo() codeinfo.code_uuid = self.inputs.code.uuid codeinfo.cmdline_params = CliParameters.from_dictionary(cli_parameters).get_list() codeinfo.stdin_name = self.options.input_filename codeinfo.stdout_name = self.options.output_filename codeinfo.stderr_name = self.options.error_filename calcinfo = datastructures.CalcInfo() calcinfo.uuid = str(self.uuid) calcinfo.codes_info = [codeinfo] calcinfo.retrieve_list = [self.options.output_filename, self.options.error_filename] calcinfo.local_copy_list = [(self.inputs.cif.uuid, self.inputs.cif.filename, self.options.input_filename)] calcinfo.remote_copy_list = [] return calcinfo
[ "def", "prepare_for_submission", "(", "self", ",", "folder", ")", ":", "from", "aiida_codtools", ".", "common", ".", "cli", "import", "CliParameters", "try", ":", "parameters", "=", "self", ".", "inputs", ".", "parameters", ".", "get_dict", "(", ")", "except", "AttributeError", ":", "parameters", "=", "{", "}", "self", ".", "_validate_resources", "(", ")", "cli_parameters", "=", "copy", ".", "deepcopy", "(", "self", ".", "_default_cli_parameters", ")", "cli_parameters", ".", "update", "(", "parameters", ")", "codeinfo", "=", "datastructures", ".", "CodeInfo", "(", ")", "codeinfo", ".", "code_uuid", "=", "self", ".", "inputs", ".", "code", ".", "uuid", "codeinfo", ".", "cmdline_params", "=", "CliParameters", ".", "from_dictionary", "(", "cli_parameters", ")", ".", "get_list", "(", ")", "codeinfo", ".", "stdin_name", "=", "self", ".", "options", ".", "input_filename", "codeinfo", ".", "stdout_name", "=", "self", ".", "options", ".", "output_filename", "codeinfo", ".", "stderr_name", "=", "self", ".", "options", ".", "error_filename", "calcinfo", "=", "datastructures", ".", "CalcInfo", "(", ")", "calcinfo", ".", "uuid", "=", "str", "(", "self", ".", "uuid", ")", "calcinfo", ".", "codes_info", "=", "[", "codeinfo", "]", "calcinfo", ".", "retrieve_list", "=", "[", "self", ".", "options", ".", "output_filename", ",", "self", ".", "options", ".", "error_filename", "]", "calcinfo", ".", "local_copy_list", "=", "[", "(", "self", ".", "inputs", ".", "cif", ".", "uuid", ",", "self", ".", "inputs", ".", "cif", ".", "filename", ",", "self", ".", "options", ".", "input_filename", ")", "]", "calcinfo", ".", "remote_copy_list", "=", "[", "]", "return", "calcinfo" ]
This method is called prior to job submission with a set of calculation input nodes. The inputs will be validated and sanitized, after which the necessary input files will be written to disk in a temporary folder. A CalcInfo instance will be returned that contains lists of files that need to be copied to the remote machine before job submission, as well as file lists that are to be retrieved after job completion. :param folder: an aiida.common.folders.Folder to temporarily write files on disk :returns: CalcInfo instance
[ "This", "method", "is", "called", "prior", "to", "job", "submission", "with", "a", "set", "of", "calculation", "input", "nodes", "." ]
da5e4259b7a2e86cf0cc3f997e11dd36d445fa94
https://github.com/aiidateam/aiida-codtools/blob/da5e4259b7a2e86cf0cc3f997e11dd36d445fa94/aiida_codtools/calculations/cif_base.py#L68-L104
train
SHDShim/pytheos
pytheos/eqn_hugoniot.py
hugoniot_p
def hugoniot_p(rho, rho0, c0, s): """ calculate pressure along a Hugoniot :param rho: density in g/cm^3 :param rho0: density at 1 bar in g/cm^3 :param c0: velocity at 1 bar in km/s :param s: slope of the velocity change :return: pressure in GPa """ eta = 1. - (rho0 / rho) Ph = rho0 * c0 * c0 * eta / np.power((1. - s * eta), 2.) return Ph
python
def hugoniot_p(rho, rho0, c0, s): """ calculate pressure along a Hugoniot :param rho: density in g/cm^3 :param rho0: density at 1 bar in g/cm^3 :param c0: velocity at 1 bar in km/s :param s: slope of the velocity change :return: pressure in GPa """ eta = 1. - (rho0 / rho) Ph = rho0 * c0 * c0 * eta / np.power((1. - s * eta), 2.) return Ph
[ "def", "hugoniot_p", "(", "rho", ",", "rho0", ",", "c0", ",", "s", ")", ":", "eta", "=", "1.", "-", "(", "rho0", "/", "rho", ")", "Ph", "=", "rho0", "*", "c0", "*", "c0", "*", "eta", "/", "np", ".", "power", "(", "(", "1.", "-", "s", "*", "eta", ")", ",", "2.", ")", "return", "Ph" ]
calculate pressure along a Hugoniot :param rho: density in g/cm^3 :param rho0: density at 1 bar in g/cm^3 :param c0: velocity at 1 bar in km/s :param s: slope of the velocity change :return: pressure in GPa
[ "calculate", "pressure", "along", "a", "Hugoniot" ]
be079624405e92fbec60c5ead253eb5917e55237
https://github.com/SHDShim/pytheos/blob/be079624405e92fbec60c5ead253eb5917e55237/pytheos/eqn_hugoniot.py#L10-L22
train
SHDShim/pytheos
pytheos/eqn_hugoniot.py
_dT_h_delta
def _dT_h_delta(T_in_kK, eta, k, threenk, c_v): """ internal function for calculation of temperature along a Hugoniot :param T_in_kK: temperature in kK scale, see Jamieson for detail :param eta: = 1 - rho0/rho :param k: = [rho0, c0, s, gamma0, q, theta0] :param threenk: see the definition in Jamieson 1983, it is a correction term mostly for Jamieson gold scale :param c_v: manual input of Cv value, if 0 calculated through Debye function :return: eta derivative of temperature """ rho0 = k[0] # g/m^3 gamma0 = k[3] # no unit q = k[4] # no unit theta0_in_kK = k[5] # K, see Jamieson 1983 for detail rho = rho0 / (1. - eta) c0 = k[1] # km/s s = k[2] # no unit dPhdelta_H = rho0 * c0 * c0 * (1. + s * eta) / \ np.power((1. - s * eta), 3.) # [g/cm^3][km/s]^2 = 1e9[kg m^2/s^2] = [GPa] Ph = hugoniot_p(rho, rho0, c0, s) # in [GPa] # calculate Cv gamma = gamma0 * np.power((1. - eta), q) theta_in_kK = theta0_in_kK * np.exp((gamma0 - gamma) / q) x = theta_in_kK / T_in_kK debye3 = debye_E(x) if c_v == 0.: c_v = threenk * (4. * debye3 - 3. * x / (np.exp(x) - 1.)) # [J/g/K] # calculate dYdX dYdX = (gamma / (1. - eta) * T_in_kK) + (dPhdelta_H * eta - Ph) / \ (2. * c_v * rho0) # print('dYdX', dYdX) return dYdX
python
def _dT_h_delta(T_in_kK, eta, k, threenk, c_v): """ internal function for calculation of temperature along a Hugoniot :param T_in_kK: temperature in kK scale, see Jamieson for detail :param eta: = 1 - rho0/rho :param k: = [rho0, c0, s, gamma0, q, theta0] :param threenk: see the definition in Jamieson 1983, it is a correction term mostly for Jamieson gold scale :param c_v: manual input of Cv value, if 0 calculated through Debye function :return: eta derivative of temperature """ rho0 = k[0] # g/m^3 gamma0 = k[3] # no unit q = k[4] # no unit theta0_in_kK = k[5] # K, see Jamieson 1983 for detail rho = rho0 / (1. - eta) c0 = k[1] # km/s s = k[2] # no unit dPhdelta_H = rho0 * c0 * c0 * (1. + s * eta) / \ np.power((1. - s * eta), 3.) # [g/cm^3][km/s]^2 = 1e9[kg m^2/s^2] = [GPa] Ph = hugoniot_p(rho, rho0, c0, s) # in [GPa] # calculate Cv gamma = gamma0 * np.power((1. - eta), q) theta_in_kK = theta0_in_kK * np.exp((gamma0 - gamma) / q) x = theta_in_kK / T_in_kK debye3 = debye_E(x) if c_v == 0.: c_v = threenk * (4. * debye3 - 3. * x / (np.exp(x) - 1.)) # [J/g/K] # calculate dYdX dYdX = (gamma / (1. - eta) * T_in_kK) + (dPhdelta_H * eta - Ph) / \ (2. * c_v * rho0) # print('dYdX', dYdX) return dYdX
[ "def", "_dT_h_delta", "(", "T_in_kK", ",", "eta", ",", "k", ",", "threenk", ",", "c_v", ")", ":", "rho0", "=", "k", "[", "0", "]", "# g/m^3", "gamma0", "=", "k", "[", "3", "]", "# no unit", "q", "=", "k", "[", "4", "]", "# no unit", "theta0_in_kK", "=", "k", "[", "5", "]", "# K, see Jamieson 1983 for detail", "rho", "=", "rho0", "/", "(", "1.", "-", "eta", ")", "c0", "=", "k", "[", "1", "]", "# km/s", "s", "=", "k", "[", "2", "]", "# no unit", "dPhdelta_H", "=", "rho0", "*", "c0", "*", "c0", "*", "(", "1.", "+", "s", "*", "eta", ")", "/", "np", ".", "power", "(", "(", "1.", "-", "s", "*", "eta", ")", ",", "3.", ")", "# [g/cm^3][km/s]^2 = 1e9[kg m^2/s^2] = [GPa]", "Ph", "=", "hugoniot_p", "(", "rho", ",", "rho0", ",", "c0", ",", "s", ")", "# in [GPa]", "# calculate Cv", "gamma", "=", "gamma0", "*", "np", ".", "power", "(", "(", "1.", "-", "eta", ")", ",", "q", ")", "theta_in_kK", "=", "theta0_in_kK", "*", "np", ".", "exp", "(", "(", "gamma0", "-", "gamma", ")", "/", "q", ")", "x", "=", "theta_in_kK", "/", "T_in_kK", "debye3", "=", "debye_E", "(", "x", ")", "if", "c_v", "==", "0.", ":", "c_v", "=", "threenk", "*", "(", "4.", "*", "debye3", "-", "3.", "*", "x", "/", "(", "np", ".", "exp", "(", "x", ")", "-", "1.", ")", ")", "# [J/g/K]", "# calculate dYdX", "dYdX", "=", "(", "gamma", "/", "(", "1.", "-", "eta", ")", "*", "T_in_kK", ")", "+", "(", "dPhdelta_H", "*", "eta", "-", "Ph", ")", "/", "(", "2.", "*", "c_v", "*", "rho0", ")", "# print('dYdX', dYdX)", "return", "dYdX" ]
internal function for calculation of temperature along a Hugoniot :param T_in_kK: temperature in kK scale, see Jamieson for detail :param eta: = 1 - rho0/rho :param k: = [rho0, c0, s, gamma0, q, theta0] :param threenk: see the definition in Jamieson 1983, it is a correction term mostly for Jamieson gold scale :param c_v: manual input of Cv value, if 0 calculated through Debye function :return: eta derivative of temperature
[ "internal", "function", "for", "calculation", "of", "temperature", "along", "a", "Hugoniot" ]
be079624405e92fbec60c5ead253eb5917e55237
https://github.com/SHDShim/pytheos/blob/be079624405e92fbec60c5ead253eb5917e55237/pytheos/eqn_hugoniot.py#L25-L60
train
SHDShim/pytheos
pytheos/eqn_hugoniot.py
hugoniot_t_single
def hugoniot_t_single(rho, rho0, c0, s, gamma0, q, theta0, n, mass, three_r=3. * constants.R, t_ref=300., c_v=0.): """ internal function to calculate pressure along Hugoniot :param rho: density in g/cm^3 :param rho0: density at 1 bar in g/cm^3 :param c0: velocity at 1 bar in km/s :param s: slope of the velocity change :param gamma0: Gruneisen parameter at 1 bar :param q: logarithmic derivative of Gruneisen parameter :param theta0: Debye temperature in K :param n: number of elements in a chemical formula :param mass: molar mass in gram :param three_r: 3 times gas constant. Jamieson modified this value to compensate for mismatches :param t_ref: reference temperature, 300 K :param c_v: heat capacity, see Jamieson 1983 for detail :return: temperature along hugoniot """ eta = 1. - rho0 / rho if eta == 0.0: return 300. threenk = three_r / mass * n # [J/mol/K] / [g/mol] = [J/g/K] k = [rho0, c0, s, gamma0, q, theta0 / 1.e3] t_h = odeint(_dT_h_delta, t_ref / 1.e3, [0., eta], args=(k, threenk, c_v), full_output=1) temp_h = np.squeeze(t_h[0][1]) return temp_h * 1.e3
python
def hugoniot_t_single(rho, rho0, c0, s, gamma0, q, theta0, n, mass, three_r=3. * constants.R, t_ref=300., c_v=0.): """ internal function to calculate pressure along Hugoniot :param rho: density in g/cm^3 :param rho0: density at 1 bar in g/cm^3 :param c0: velocity at 1 bar in km/s :param s: slope of the velocity change :param gamma0: Gruneisen parameter at 1 bar :param q: logarithmic derivative of Gruneisen parameter :param theta0: Debye temperature in K :param n: number of elements in a chemical formula :param mass: molar mass in gram :param three_r: 3 times gas constant. Jamieson modified this value to compensate for mismatches :param t_ref: reference temperature, 300 K :param c_v: heat capacity, see Jamieson 1983 for detail :return: temperature along hugoniot """ eta = 1. - rho0 / rho if eta == 0.0: return 300. threenk = three_r / mass * n # [J/mol/K] / [g/mol] = [J/g/K] k = [rho0, c0, s, gamma0, q, theta0 / 1.e3] t_h = odeint(_dT_h_delta, t_ref / 1.e3, [0., eta], args=(k, threenk, c_v), full_output=1) temp_h = np.squeeze(t_h[0][1]) return temp_h * 1.e3
[ "def", "hugoniot_t_single", "(", "rho", ",", "rho0", ",", "c0", ",", "s", ",", "gamma0", ",", "q", ",", "theta0", ",", "n", ",", "mass", ",", "three_r", "=", "3.", "*", "constants", ".", "R", ",", "t_ref", "=", "300.", ",", "c_v", "=", "0.", ")", ":", "eta", "=", "1.", "-", "rho0", "/", "rho", "if", "eta", "==", "0.0", ":", "return", "300.", "threenk", "=", "three_r", "/", "mass", "*", "n", "# [J/mol/K] / [g/mol] = [J/g/K]", "k", "=", "[", "rho0", ",", "c0", ",", "s", ",", "gamma0", ",", "q", ",", "theta0", "/", "1.e3", "]", "t_h", "=", "odeint", "(", "_dT_h_delta", ",", "t_ref", "/", "1.e3", ",", "[", "0.", ",", "eta", "]", ",", "args", "=", "(", "k", ",", "threenk", ",", "c_v", ")", ",", "full_output", "=", "1", ")", "temp_h", "=", "np", ".", "squeeze", "(", "t_h", "[", "0", "]", "[", "1", "]", ")", "return", "temp_h", "*", "1.e3" ]
internal function to calculate pressure along Hugoniot :param rho: density in g/cm^3 :param rho0: density at 1 bar in g/cm^3 :param c0: velocity at 1 bar in km/s :param s: slope of the velocity change :param gamma0: Gruneisen parameter at 1 bar :param q: logarithmic derivative of Gruneisen parameter :param theta0: Debye temperature in K :param n: number of elements in a chemical formula :param mass: molar mass in gram :param three_r: 3 times gas constant. Jamieson modified this value to compensate for mismatches :param t_ref: reference temperature, 300 K :param c_v: heat capacity, see Jamieson 1983 for detail :return: temperature along hugoniot
[ "internal", "function", "to", "calculate", "pressure", "along", "Hugoniot" ]
be079624405e92fbec60c5ead253eb5917e55237
https://github.com/SHDShim/pytheos/blob/be079624405e92fbec60c5ead253eb5917e55237/pytheos/eqn_hugoniot.py#L63-L91
train
SHDShim/pytheos
pytheos/eqn_hugoniot.py
hugoniot_t
def hugoniot_t(rho, rho0, c0, s, gamma0, q, theta0, n, mass, three_r=3. * constants.R, t_ref=300., c_v=0.): """ calculate temperature along a hugoniot :param rho: density in g/cm^3 :param rho0: density at 1 bar in g/cm^3 :param c0: velocity at 1 bar in km/s :param s: slope of the velocity change :param gamma0: Gruneisen parameter at 1 bar :param q: logarithmic derivative of Gruneisen parameter :param theta0: Debye temperature in K :param n: number of elements in a chemical formula :param mass: molar mass in gram :param three_r: 3 times gas constant. Jamieson modified this value to compensate for mismatches :param t_ref: reference temperature, 300 K :param c_v: heat capacity, see Jamieson 1983 for detail :return: temperature along hugoniot """ if isuncertainties([rho, rho0, c0, s, gamma0, q, theta0]): f_v = np.vectorize(uct.wrap(hugoniot_t_single), excluded=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]) else: f_v = np.vectorize(hugoniot_t_single, excluded=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]) return f_v(rho, rho0, c0, s, gamma0, q, theta0, n, mass, three_r=three_r, t_ref=t_ref, c_v=c_v)
python
def hugoniot_t(rho, rho0, c0, s, gamma0, q, theta0, n, mass, three_r=3. * constants.R, t_ref=300., c_v=0.): """ calculate temperature along a hugoniot :param rho: density in g/cm^3 :param rho0: density at 1 bar in g/cm^3 :param c0: velocity at 1 bar in km/s :param s: slope of the velocity change :param gamma0: Gruneisen parameter at 1 bar :param q: logarithmic derivative of Gruneisen parameter :param theta0: Debye temperature in K :param n: number of elements in a chemical formula :param mass: molar mass in gram :param three_r: 3 times gas constant. Jamieson modified this value to compensate for mismatches :param t_ref: reference temperature, 300 K :param c_v: heat capacity, see Jamieson 1983 for detail :return: temperature along hugoniot """ if isuncertainties([rho, rho0, c0, s, gamma0, q, theta0]): f_v = np.vectorize(uct.wrap(hugoniot_t_single), excluded=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]) else: f_v = np.vectorize(hugoniot_t_single, excluded=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]) return f_v(rho, rho0, c0, s, gamma0, q, theta0, n, mass, three_r=three_r, t_ref=t_ref, c_v=c_v)
[ "def", "hugoniot_t", "(", "rho", ",", "rho0", ",", "c0", ",", "s", ",", "gamma0", ",", "q", ",", "theta0", ",", "n", ",", "mass", ",", "three_r", "=", "3.", "*", "constants", ".", "R", ",", "t_ref", "=", "300.", ",", "c_v", "=", "0.", ")", ":", "if", "isuncertainties", "(", "[", "rho", ",", "rho0", ",", "c0", ",", "s", ",", "gamma0", ",", "q", ",", "theta0", "]", ")", ":", "f_v", "=", "np", ".", "vectorize", "(", "uct", ".", "wrap", "(", "hugoniot_t_single", ")", ",", "excluded", "=", "[", "1", ",", "2", ",", "3", ",", "4", ",", "5", ",", "6", ",", "7", ",", "8", ",", "9", ",", "10", ",", "11", "]", ")", "else", ":", "f_v", "=", "np", ".", "vectorize", "(", "hugoniot_t_single", ",", "excluded", "=", "[", "1", ",", "2", ",", "3", ",", "4", ",", "5", ",", "6", ",", "7", ",", "8", ",", "9", ",", "10", ",", "11", "]", ")", "return", "f_v", "(", "rho", ",", "rho0", ",", "c0", ",", "s", ",", "gamma0", ",", "q", ",", "theta0", ",", "n", ",", "mass", ",", "three_r", "=", "three_r", ",", "t_ref", "=", "t_ref", ",", "c_v", "=", "c_v", ")" ]
calculate temperature along a hugoniot :param rho: density in g/cm^3 :param rho0: density at 1 bar in g/cm^3 :param c0: velocity at 1 bar in km/s :param s: slope of the velocity change :param gamma0: Gruneisen parameter at 1 bar :param q: logarithmic derivative of Gruneisen parameter :param theta0: Debye temperature in K :param n: number of elements in a chemical formula :param mass: molar mass in gram :param three_r: 3 times gas constant. Jamieson modified this value to compensate for mismatches :param t_ref: reference temperature, 300 K :param c_v: heat capacity, see Jamieson 1983 for detail :return: temperature along hugoniot
[ "calculate", "temperature", "along", "a", "hugoniot" ]
be079624405e92fbec60c5ead253eb5917e55237
https://github.com/SHDShim/pytheos/blob/be079624405e92fbec60c5ead253eb5917e55237/pytheos/eqn_hugoniot.py#L94-L121
train
iduartgomez/rustypy
src/rustypy/rswrapper/pytypes.py
PyString.to_str
def to_str(self): """Consumes the wrapper and returns a Python string. Afterwards is not necessary to destruct it as it has already been consumed.""" val = c_backend.pystring_get_str(self._ptr) delattr(self, '_ptr') setattr(self, 'to_str', _dangling_pointer) return val.decode("utf-8")
python
def to_str(self): """Consumes the wrapper and returns a Python string. Afterwards is not necessary to destruct it as it has already been consumed.""" val = c_backend.pystring_get_str(self._ptr) delattr(self, '_ptr') setattr(self, 'to_str', _dangling_pointer) return val.decode("utf-8")
[ "def", "to_str", "(", "self", ")", ":", "val", "=", "c_backend", ".", "pystring_get_str", "(", "self", ".", "_ptr", ")", "delattr", "(", "self", ",", "'_ptr'", ")", "setattr", "(", "self", ",", "'to_str'", ",", "_dangling_pointer", ")", "return", "val", ".", "decode", "(", "\"utf-8\"", ")" ]
Consumes the wrapper and returns a Python string. Afterwards is not necessary to destruct it as it has already been consumed.
[ "Consumes", "the", "wrapper", "and", "returns", "a", "Python", "string", ".", "Afterwards", "is", "not", "necessary", "to", "destruct", "it", "as", "it", "has", "already", "been", "consumed", "." ]
971701a4e18aeffceda16f2538f3a846713e65ff
https://github.com/iduartgomez/rustypy/blob/971701a4e18aeffceda16f2538f3a846713e65ff/src/rustypy/rswrapper/pytypes.py#L39-L46
train
erijo/tellive-py
tellive/tellstick.py
TellstickLiveClient.servers
def servers(self, server='api.telldus.com', port=http.HTTPS_PORT): """Fetch list of servers that can be connected to. :return: list of (address, port) tuples """ logging.debug("Fetching server list from %s:%d", server, port) conn = http.HTTPSConnection(server, port, context=self.ssl_context()) conn.request('GET', "/server/assign?protocolVersion=2") response = conn.getresponse() if response.status != http.OK: raise RuntimeError("Could not connect to {}:{}: {} {}".format( server, port, response.status, response.reason)) servers = [] def extract_servers(name, attributes): if name == "server": servers.append((attributes['address'], int(attributes['port']))) parser = expat.ParserCreate() parser.StartElementHandler = extract_servers parser.ParseFile(response) logging.debug("Found %d available servers", len(servers)) return servers
python
def servers(self, server='api.telldus.com', port=http.HTTPS_PORT): """Fetch list of servers that can be connected to. :return: list of (address, port) tuples """ logging.debug("Fetching server list from %s:%d", server, port) conn = http.HTTPSConnection(server, port, context=self.ssl_context()) conn.request('GET', "/server/assign?protocolVersion=2") response = conn.getresponse() if response.status != http.OK: raise RuntimeError("Could not connect to {}:{}: {} {}".format( server, port, response.status, response.reason)) servers = [] def extract_servers(name, attributes): if name == "server": servers.append((attributes['address'], int(attributes['port']))) parser = expat.ParserCreate() parser.StartElementHandler = extract_servers parser.ParseFile(response) logging.debug("Found %d available servers", len(servers)) return servers
[ "def", "servers", "(", "self", ",", "server", "=", "'api.telldus.com'", ",", "port", "=", "http", ".", "HTTPS_PORT", ")", ":", "logging", ".", "debug", "(", "\"Fetching server list from %s:%d\"", ",", "server", ",", "port", ")", "conn", "=", "http", ".", "HTTPSConnection", "(", "server", ",", "port", ",", "context", "=", "self", ".", "ssl_context", "(", ")", ")", "conn", ".", "request", "(", "'GET'", ",", "\"/server/assign?protocolVersion=2\"", ")", "response", "=", "conn", ".", "getresponse", "(", ")", "if", "response", ".", "status", "!=", "http", ".", "OK", ":", "raise", "RuntimeError", "(", "\"Could not connect to {}:{}: {} {}\"", ".", "format", "(", "server", ",", "port", ",", "response", ".", "status", ",", "response", ".", "reason", ")", ")", "servers", "=", "[", "]", "def", "extract_servers", "(", "name", ",", "attributes", ")", ":", "if", "name", "==", "\"server\"", ":", "servers", ".", "append", "(", "(", "attributes", "[", "'address'", "]", ",", "int", "(", "attributes", "[", "'port'", "]", ")", ")", ")", "parser", "=", "expat", ".", "ParserCreate", "(", ")", "parser", ".", "StartElementHandler", "=", "extract_servers", "parser", ".", "ParseFile", "(", "response", ")", "logging", ".", "debug", "(", "\"Found %d available servers\"", ",", "len", "(", "servers", ")", ")", "return", "servers" ]
Fetch list of servers that can be connected to. :return: list of (address, port) tuples
[ "Fetch", "list", "of", "servers", "that", "can", "be", "connected", "to", "." ]
a84ebb1eb29ee4c69a085e55e523ac5fff0087fc
https://github.com/erijo/tellive-py/blob/a84ebb1eb29ee4c69a085e55e523ac5fff0087fc/tellive/tellstick.py#L56-L83
train
ChrisBeaumont/smother
smother/git.py
execute
def execute(cmd): """Run a shell command and return stdout""" proc = Popen(cmd, stdout=PIPE) stdout, _ = proc.communicate() if proc.returncode != 0: raise CalledProcessError(proc.returncode, " ".join(cmd)) return stdout.decode('utf8')
python
def execute(cmd): """Run a shell command and return stdout""" proc = Popen(cmd, stdout=PIPE) stdout, _ = proc.communicate() if proc.returncode != 0: raise CalledProcessError(proc.returncode, " ".join(cmd)) return stdout.decode('utf8')
[ "def", "execute", "(", "cmd", ")", ":", "proc", "=", "Popen", "(", "cmd", ",", "stdout", "=", "PIPE", ")", "stdout", ",", "_", "=", "proc", ".", "communicate", "(", ")", "if", "proc", ".", "returncode", "!=", "0", ":", "raise", "CalledProcessError", "(", "proc", ".", "returncode", ",", "\" \"", ".", "join", "(", "cmd", ")", ")", "return", "stdout", ".", "decode", "(", "'utf8'", ")" ]
Run a shell command and return stdout
[ "Run", "a", "shell", "command", "and", "return", "stdout" ]
65d1ea6ae0060d213b0dcbb983c5aa8e7fee07bb
https://github.com/ChrisBeaumont/smother/blob/65d1ea6ae0060d213b0dcbb983c5aa8e7fee07bb/smother/git.py#L11-L18
train
SHDShim/pytheos
pytheos/etc.py
isuncertainties
def isuncertainties(arg_list): """ check if the input list contains any elements with uncertainties class :param arg_list: list of arguments :return: True/False """ for arg in arg_list: if isinstance(arg, (list, tuple)) and isinstance(arg[0], uct.UFloat): return True elif isinstance(arg, np.ndarray) and isinstance( np.atleast_1d(arg)[0], uct.UFloat): return True elif isinstance(arg, (float, uct.UFloat)) and \ isinstance(arg, uct.UFloat): return True return False
python
def isuncertainties(arg_list): """ check if the input list contains any elements with uncertainties class :param arg_list: list of arguments :return: True/False """ for arg in arg_list: if isinstance(arg, (list, tuple)) and isinstance(arg[0], uct.UFloat): return True elif isinstance(arg, np.ndarray) and isinstance( np.atleast_1d(arg)[0], uct.UFloat): return True elif isinstance(arg, (float, uct.UFloat)) and \ isinstance(arg, uct.UFloat): return True return False
[ "def", "isuncertainties", "(", "arg_list", ")", ":", "for", "arg", "in", "arg_list", ":", "if", "isinstance", "(", "arg", ",", "(", "list", ",", "tuple", ")", ")", "and", "isinstance", "(", "arg", "[", "0", "]", ",", "uct", ".", "UFloat", ")", ":", "return", "True", "elif", "isinstance", "(", "arg", ",", "np", ".", "ndarray", ")", "and", "isinstance", "(", "np", ".", "atleast_1d", "(", "arg", ")", "[", "0", "]", ",", "uct", ".", "UFloat", ")", ":", "return", "True", "elif", "isinstance", "(", "arg", ",", "(", "float", ",", "uct", ".", "UFloat", ")", ")", "and", "isinstance", "(", "arg", ",", "uct", ".", "UFloat", ")", ":", "return", "True", "return", "False" ]
check if the input list contains any elements with uncertainties class :param arg_list: list of arguments :return: True/False
[ "check", "if", "the", "input", "list", "contains", "any", "elements", "with", "uncertainties", "class" ]
be079624405e92fbec60c5ead253eb5917e55237
https://github.com/SHDShim/pytheos/blob/be079624405e92fbec60c5ead253eb5917e55237/pytheos/etc.py#L5-L21
train
potatolondon/gae-pytz
makezoneinfo.py
filter_tzfiles
def filter_tzfiles(name_list): """Returns a list of tuples for names that are tz data files.""" for src_name in name_list: # pytz-2012j/pytz/zoneinfo/Indian/Christmas parts = src_name.split('/') if len(parts) > 3 and parts[2] == 'zoneinfo': dst_name = '/'.join(parts[2:]) yield src_name, dst_name
python
def filter_tzfiles(name_list): """Returns a list of tuples for names that are tz data files.""" for src_name in name_list: # pytz-2012j/pytz/zoneinfo/Indian/Christmas parts = src_name.split('/') if len(parts) > 3 and parts[2] == 'zoneinfo': dst_name = '/'.join(parts[2:]) yield src_name, dst_name
[ "def", "filter_tzfiles", "(", "name_list", ")", ":", "for", "src_name", "in", "name_list", ":", "# pytz-2012j/pytz/zoneinfo/Indian/Christmas", "parts", "=", "src_name", ".", "split", "(", "'/'", ")", "if", "len", "(", "parts", ")", ">", "3", "and", "parts", "[", "2", "]", "==", "'zoneinfo'", ":", "dst_name", "=", "'/'", ".", "join", "(", "parts", "[", "2", ":", "]", ")", "yield", "src_name", ",", "dst_name" ]
Returns a list of tuples for names that are tz data files.
[ "Returns", "a", "list", "of", "tuples", "for", "names", "that", "are", "tz", "data", "files", "." ]
24741951a7af3e79cd8727ae3f79265decc93fef
https://github.com/potatolondon/gae-pytz/blob/24741951a7af3e79cd8727ae3f79265decc93fef/makezoneinfo.py#L15-L22
train
klen/muffin-admin
muffin_admin/plugin.py
Plugin.setup
def setup(self, app): """ Initialize the application. """ super().setup(app) self.handlers = OrderedDict() # Connect admin templates app.ps.jinja2.cfg.template_folders.append(op.join(PLUGIN_ROOT, 'templates')) @app.ps.jinja2.filter def admtest(value, a, b=None): return a if value else b @app.ps.jinja2.filter def admeq(a, b, result=True): return result if a == b else not result @app.ps.jinja2.register def admurl(request, prefix): qs = {k: v for k, v in request.query.items() if not k.startswith(prefix)} if not qs: qs = {'ap': 0} return "%s?%s" % (request.path, urlparse.urlencode(qs)) if self.cfg.name is None: self.cfg.name = "%s admin" % app.name.title() # Register a base view if not callable(self.cfg.home): def admin_home(request): yield from self.authorize(request) return app.ps.jinja2.render(self.cfg.template_home, active=None) self.cfg.home = admin_home app.register(self.cfg.prefix)(self.cfg.home) if not self.cfg.i18n: app.ps.jinja2.env.globals.update({ '_': lambda s: s, 'gettext': lambda s: s, 'ngettext': lambda s, p, n: (n != 1 and (p,) or (s,))[0], }) return if 'babel' not in app.ps or not isinstance(app.ps.babel, BPlugin): raise PluginException( 'Plugin `%s` requires for plugin `%s` to be installed to the application.' % ( self.name, BPlugin)) # Connect admin locales app.ps.babel.cfg.locales_dirs.append(op.join(PLUGIN_ROOT, 'locales')) if not app.ps.babel.locale_selector_func: app.ps.babel.locale_selector_func = app.ps.babel.select_locale_by_request
python
def setup(self, app): """ Initialize the application. """ super().setup(app) self.handlers = OrderedDict() # Connect admin templates app.ps.jinja2.cfg.template_folders.append(op.join(PLUGIN_ROOT, 'templates')) @app.ps.jinja2.filter def admtest(value, a, b=None): return a if value else b @app.ps.jinja2.filter def admeq(a, b, result=True): return result if a == b else not result @app.ps.jinja2.register def admurl(request, prefix): qs = {k: v for k, v in request.query.items() if not k.startswith(prefix)} if not qs: qs = {'ap': 0} return "%s?%s" % (request.path, urlparse.urlencode(qs)) if self.cfg.name is None: self.cfg.name = "%s admin" % app.name.title() # Register a base view if not callable(self.cfg.home): def admin_home(request): yield from self.authorize(request) return app.ps.jinja2.render(self.cfg.template_home, active=None) self.cfg.home = admin_home app.register(self.cfg.prefix)(self.cfg.home) if not self.cfg.i18n: app.ps.jinja2.env.globals.update({ '_': lambda s: s, 'gettext': lambda s: s, 'ngettext': lambda s, p, n: (n != 1 and (p,) or (s,))[0], }) return if 'babel' not in app.ps or not isinstance(app.ps.babel, BPlugin): raise PluginException( 'Plugin `%s` requires for plugin `%s` to be installed to the application.' % ( self.name, BPlugin)) # Connect admin locales app.ps.babel.cfg.locales_dirs.append(op.join(PLUGIN_ROOT, 'locales')) if not app.ps.babel.locale_selector_func: app.ps.babel.locale_selector_func = app.ps.babel.select_locale_by_request
[ "def", "setup", "(", "self", ",", "app", ")", ":", "super", "(", ")", ".", "setup", "(", "app", ")", "self", ".", "handlers", "=", "OrderedDict", "(", ")", "# Connect admin templates", "app", ".", "ps", ".", "jinja2", ".", "cfg", ".", "template_folders", ".", "append", "(", "op", ".", "join", "(", "PLUGIN_ROOT", ",", "'templates'", ")", ")", "@", "app", ".", "ps", ".", "jinja2", ".", "filter", "def", "admtest", "(", "value", ",", "a", ",", "b", "=", "None", ")", ":", "return", "a", "if", "value", "else", "b", "@", "app", ".", "ps", ".", "jinja2", ".", "filter", "def", "admeq", "(", "a", ",", "b", ",", "result", "=", "True", ")", ":", "return", "result", "if", "a", "==", "b", "else", "not", "result", "@", "app", ".", "ps", ".", "jinja2", ".", "register", "def", "admurl", "(", "request", ",", "prefix", ")", ":", "qs", "=", "{", "k", ":", "v", "for", "k", ",", "v", "in", "request", ".", "query", ".", "items", "(", ")", "if", "not", "k", ".", "startswith", "(", "prefix", ")", "}", "if", "not", "qs", ":", "qs", "=", "{", "'ap'", ":", "0", "}", "return", "\"%s?%s\"", "%", "(", "request", ".", "path", ",", "urlparse", ".", "urlencode", "(", "qs", ")", ")", "if", "self", ".", "cfg", ".", "name", "is", "None", ":", "self", ".", "cfg", ".", "name", "=", "\"%s admin\"", "%", "app", ".", "name", ".", "title", "(", ")", "# Register a base view", "if", "not", "callable", "(", "self", ".", "cfg", ".", "home", ")", ":", "def", "admin_home", "(", "request", ")", ":", "yield", "from", "self", ".", "authorize", "(", "request", ")", "return", "app", ".", "ps", ".", "jinja2", ".", "render", "(", "self", ".", "cfg", ".", "template_home", ",", "active", "=", "None", ")", "self", ".", "cfg", ".", "home", "=", "admin_home", "app", ".", "register", "(", "self", ".", "cfg", ".", "prefix", ")", "(", "self", ".", "cfg", ".", "home", ")", "if", "not", "self", ".", "cfg", ".", "i18n", ":", "app", ".", "ps", ".", "jinja2", ".", "env", ".", "globals", ".", "update", "(", "{", "'_'", ":", "lambda", "s", ":", "s", ",", "'gettext'", ":", "lambda", "s", ":", "s", ",", "'ngettext'", ":", "lambda", "s", ",", "p", ",", "n", ":", "(", "n", "!=", "1", "and", "(", "p", ",", ")", "or", "(", "s", ",", ")", ")", "[", "0", "]", ",", "}", ")", "return", "if", "'babel'", "not", "in", "app", ".", "ps", "or", "not", "isinstance", "(", "app", ".", "ps", ".", "babel", ",", "BPlugin", ")", ":", "raise", "PluginException", "(", "'Plugin `%s` requires for plugin `%s` to be installed to the application.'", "%", "(", "self", ".", "name", ",", "BPlugin", ")", ")", "# Connect admin locales", "app", ".", "ps", ".", "babel", ".", "cfg", ".", "locales_dirs", ".", "append", "(", "op", ".", "join", "(", "PLUGIN_ROOT", ",", "'locales'", ")", ")", "if", "not", "app", ".", "ps", ".", "babel", ".", "locale_selector_func", ":", "app", ".", "ps", ".", "babel", ".", "locale_selector_func", "=", "app", ".", "ps", ".", "babel", ".", "select_locale_by_request" ]
Initialize the application.
[ "Initialize", "the", "application", "." ]
404dc8e5107e943b7c42fa21c679c34ddb4de1d5
https://github.com/klen/muffin-admin/blob/404dc8e5107e943b7c42fa21c679c34ddb4de1d5/muffin_admin/plugin.py#L44-L99
train
klen/muffin-admin
muffin_admin/plugin.py
Plugin.register
def register(self, *handlers, **params): """ Ensure that handler is not registered. """ for handler in handlers: if issubclass(handler, PWModel): handler = type( handler._meta.db_table.title() + 'Admin', (PWAdminHandler,), dict(model=handler, **params)) self.app.register(handler) continue name = handler.name.lower() self.handlers[name] = handler
python
def register(self, *handlers, **params): """ Ensure that handler is not registered. """ for handler in handlers: if issubclass(handler, PWModel): handler = type( handler._meta.db_table.title() + 'Admin', (PWAdminHandler,), dict(model=handler, **params)) self.app.register(handler) continue name = handler.name.lower() self.handlers[name] = handler
[ "def", "register", "(", "self", ",", "*", "handlers", ",", "*", "*", "params", ")", ":", "for", "handler", "in", "handlers", ":", "if", "issubclass", "(", "handler", ",", "PWModel", ")", ":", "handler", "=", "type", "(", "handler", ".", "_meta", ".", "db_table", ".", "title", "(", ")", "+", "'Admin'", ",", "(", "PWAdminHandler", ",", ")", ",", "dict", "(", "model", "=", "handler", ",", "*", "*", "params", ")", ")", "self", ".", "app", ".", "register", "(", "handler", ")", "continue", "name", "=", "handler", ".", "name", ".", "lower", "(", ")", "self", ".", "handlers", "[", "name", "]", "=", "handler" ]
Ensure that handler is not registered.
[ "Ensure", "that", "handler", "is", "not", "registered", "." ]
404dc8e5107e943b7c42fa21c679c34ddb4de1d5
https://github.com/klen/muffin-admin/blob/404dc8e5107e943b7c42fa21c679c34ddb4de1d5/muffin_admin/plugin.py#L101-L113
train
klen/muffin-admin
muffin_admin/plugin.py
Plugin.authorization
def authorization(self, func): """ Define a authorization process. """ if self.app is None: raise PluginException('The plugin must be installed to application.') self.authorize = muffin.to_coroutine(func) return func
python
def authorization(self, func): """ Define a authorization process. """ if self.app is None: raise PluginException('The plugin must be installed to application.') self.authorize = muffin.to_coroutine(func) return func
[ "def", "authorization", "(", "self", ",", "func", ")", ":", "if", "self", ".", "app", "is", "None", ":", "raise", "PluginException", "(", "'The plugin must be installed to application.'", ")", "self", ".", "authorize", "=", "muffin", ".", "to_coroutine", "(", "func", ")", "return", "func" ]
Define a authorization process.
[ "Define", "a", "authorization", "process", "." ]
404dc8e5107e943b7c42fa21c679c34ddb4de1d5
https://github.com/klen/muffin-admin/blob/404dc8e5107e943b7c42fa21c679c34ddb4de1d5/muffin_admin/plugin.py#L115-L121
train
jedie/PyHardLinkBackup
PyHardLinkBackup/phlb/filesystem_walk.py
scandir_limited
def scandir_limited(top, limit, deep=0): """ yields only directories with the given deep limit :param top: source path :param limit: how deep should be scanned? :param deep: internal deep number :return: yields os.DirEntry() instances """ deep += 1 try: scandir_it = Path2(top).scandir() except PermissionError as err: log.error("scandir error: %s" % err) return for entry in scandir_it: if entry.is_dir(follow_symlinks=False): if deep < limit: yield from scandir_limited(entry.path, limit, deep) else: yield entry
python
def scandir_limited(top, limit, deep=0): """ yields only directories with the given deep limit :param top: source path :param limit: how deep should be scanned? :param deep: internal deep number :return: yields os.DirEntry() instances """ deep += 1 try: scandir_it = Path2(top).scandir() except PermissionError as err: log.error("scandir error: %s" % err) return for entry in scandir_it: if entry.is_dir(follow_symlinks=False): if deep < limit: yield from scandir_limited(entry.path, limit, deep) else: yield entry
[ "def", "scandir_limited", "(", "top", ",", "limit", ",", "deep", "=", "0", ")", ":", "deep", "+=", "1", "try", ":", "scandir_it", "=", "Path2", "(", "top", ")", ".", "scandir", "(", ")", "except", "PermissionError", "as", "err", ":", "log", ".", "error", "(", "\"scandir error: %s\"", "%", "err", ")", "return", "for", "entry", "in", "scandir_it", ":", "if", "entry", ".", "is_dir", "(", "follow_symlinks", "=", "False", ")", ":", "if", "deep", "<", "limit", ":", "yield", "from", "scandir_limited", "(", "entry", ".", "path", ",", "limit", ",", "deep", ")", "else", ":", "yield", "entry" ]
yields only directories with the given deep limit :param top: source path :param limit: how deep should be scanned? :param deep: internal deep number :return: yields os.DirEntry() instances
[ "yields", "only", "directories", "with", "the", "given", "deep", "limit" ]
be28666834d2d9e3d8aac1b661cb2d5bd4056c29
https://github.com/jedie/PyHardLinkBackup/blob/be28666834d2d9e3d8aac1b661cb2d5bd4056c29/PyHardLinkBackup/phlb/filesystem_walk.py#L42-L63
train