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
Esri/ArcREST
src/arcrest/ags/_schematicsservice.py
SchematicsService.searchDiagrams
def searchDiagrams(self,whereClause=None,relatedObjects=None, relatedSchematicObjects=None): """ The Schematic Search Diagrams operation is performed on the schematic service resource. The result of this operation is an array of Schematic Diagram Information Object. It is used to search diagrams in the schematic service by criteria; that is, diagrams filtered out via a where clause on any schematic diagram class table field, diagrams that contain schematic features associated with a specific set of GIS features/objects, or diagrams that contain schematic features associated with the same GIS features/ objects related to another set of schematic features. Inputs: whereClause - A where clause for the query filter. Any legal SQL where clause operating on the fields in the schematic diagram class table is allowed. See the Schematic diagram class table fields section below to know the exact list of field names that can be used in this where clause. relatedObjects - An array containing the list of the GIS features/ objects IDs per feature class/table name that are in relation with schematic features in the resulting queried diagrams. Each GIS feature/object ID corresponds to a value of the OBJECTID field in the GIS feature class/table. relatedSchematicObjects - An array containing the list of the schematic feature names per schematic feature class ID that have the same associated GIS features/objects with schematic features in the resulting queried diagrams. Each schematic feature name corresponds to a value of the SCHEMATICTID field in the schematic feature class. """ params = {"f" : "json"} if whereClause: params["where"] = whereClause if relatedObjects: params["relatedObjects"] = relatedObjects if relatedSchematicObjects: params["relatedSchematicObjects"] = relatedSchematicObjects exportURL = self._url + "/searchDiagrams" return self._get(url=exportURL, param_dict=params, securityHandler=self._securityHandler, proxy_url=self._proxy_url, proxy_port=self._proxy_port)
python
def searchDiagrams(self,whereClause=None,relatedObjects=None, relatedSchematicObjects=None): """ The Schematic Search Diagrams operation is performed on the schematic service resource. The result of this operation is an array of Schematic Diagram Information Object. It is used to search diagrams in the schematic service by criteria; that is, diagrams filtered out via a where clause on any schematic diagram class table field, diagrams that contain schematic features associated with a specific set of GIS features/objects, or diagrams that contain schematic features associated with the same GIS features/ objects related to another set of schematic features. Inputs: whereClause - A where clause for the query filter. Any legal SQL where clause operating on the fields in the schematic diagram class table is allowed. See the Schematic diagram class table fields section below to know the exact list of field names that can be used in this where clause. relatedObjects - An array containing the list of the GIS features/ objects IDs per feature class/table name that are in relation with schematic features in the resulting queried diagrams. Each GIS feature/object ID corresponds to a value of the OBJECTID field in the GIS feature class/table. relatedSchematicObjects - An array containing the list of the schematic feature names per schematic feature class ID that have the same associated GIS features/objects with schematic features in the resulting queried diagrams. Each schematic feature name corresponds to a value of the SCHEMATICTID field in the schematic feature class. """ params = {"f" : "json"} if whereClause: params["where"] = whereClause if relatedObjects: params["relatedObjects"] = relatedObjects if relatedSchematicObjects: params["relatedSchematicObjects"] = relatedSchematicObjects exportURL = self._url + "/searchDiagrams" return self._get(url=exportURL, param_dict=params, securityHandler=self._securityHandler, proxy_url=self._proxy_url, proxy_port=self._proxy_port)
[ "def", "searchDiagrams", "(", "self", ",", "whereClause", "=", "None", ",", "relatedObjects", "=", "None", ",", "relatedSchematicObjects", "=", "None", ")", ":", "params", "=", "{", "\"f\"", ":", "\"json\"", "}", "if", "whereClause", ":", "params", "[", "\"where\"", "]", "=", "whereClause", "if", "relatedObjects", ":", "params", "[", "\"relatedObjects\"", "]", "=", "relatedObjects", "if", "relatedSchematicObjects", ":", "params", "[", "\"relatedSchematicObjects\"", "]", "=", "relatedSchematicObjects", "exportURL", "=", "self", ".", "_url", "+", "\"/searchDiagrams\"", "return", "self", ".", "_get", "(", "url", "=", "exportURL", ",", "param_dict", "=", "params", ",", "securityHandler", "=", "self", ".", "_securityHandler", ",", "proxy_url", "=", "self", ".", "_proxy_url", ",", "proxy_port", "=", "self", ".", "_proxy_port", ")" ]
The Schematic Search Diagrams operation is performed on the schematic service resource. The result of this operation is an array of Schematic Diagram Information Object. It is used to search diagrams in the schematic service by criteria; that is, diagrams filtered out via a where clause on any schematic diagram class table field, diagrams that contain schematic features associated with a specific set of GIS features/objects, or diagrams that contain schematic features associated with the same GIS features/ objects related to another set of schematic features. Inputs: whereClause - A where clause for the query filter. Any legal SQL where clause operating on the fields in the schematic diagram class table is allowed. See the Schematic diagram class table fields section below to know the exact list of field names that can be used in this where clause. relatedObjects - An array containing the list of the GIS features/ objects IDs per feature class/table name that are in relation with schematic features in the resulting queried diagrams. Each GIS feature/object ID corresponds to a value of the OBJECTID field in the GIS feature class/table. relatedSchematicObjects - An array containing the list of the schematic feature names per schematic feature class ID that have the same associated GIS features/objects with schematic features in the resulting queried diagrams. Each schematic feature name corresponds to a value of the SCHEMATICTID field in the schematic feature class.
[ "The", "Schematic", "Search", "Diagrams", "operation", "is", "performed", "on", "the", "schematic", "service", "resource", ".", "The", "result", "of", "this", "operation", "is", "an", "array", "of", "Schematic", "Diagram", "Information", "Object", "." ]
ab240fde2b0200f61d4a5f6df033516e53f2f416
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/ags/_schematicsservice.py#L166-L216
train
Esri/ArcREST
src/arcrest/ags/server.py
Server._validateurl
def _validateurl(self, url): """assembles the server url""" parsed = urlparse(url) path = parsed.path.strip("/") if path: parts = path.split("/") url_types = ("admin", "manager", "rest") if any(i in parts for i in url_types): while parts.pop() not in url_types: next elif "services" in parts: while parts.pop() not in "services": next path = "/".join(parts) else: path = "arcgis" self._adminUrl = "%s://%s/%s/admin" % (parsed.scheme, parsed.netloc, path) return "%s://%s/%s/rest/services" % (parsed.scheme, parsed.netloc, path)
python
def _validateurl(self, url): """assembles the server url""" parsed = urlparse(url) path = parsed.path.strip("/") if path: parts = path.split("/") url_types = ("admin", "manager", "rest") if any(i in parts for i in url_types): while parts.pop() not in url_types: next elif "services" in parts: while parts.pop() not in "services": next path = "/".join(parts) else: path = "arcgis" self._adminUrl = "%s://%s/%s/admin" % (parsed.scheme, parsed.netloc, path) return "%s://%s/%s/rest/services" % (parsed.scheme, parsed.netloc, path)
[ "def", "_validateurl", "(", "self", ",", "url", ")", ":", "parsed", "=", "urlparse", "(", "url", ")", "path", "=", "parsed", ".", "path", ".", "strip", "(", "\"/\"", ")", "if", "path", ":", "parts", "=", "path", ".", "split", "(", "\"/\"", ")", "url_types", "=", "(", "\"admin\"", ",", "\"manager\"", ",", "\"rest\"", ")", "if", "any", "(", "i", "in", "parts", "for", "i", "in", "url_types", ")", ":", "while", "parts", ".", "pop", "(", ")", "not", "in", "url_types", ":", "next", "elif", "\"services\"", "in", "parts", ":", "while", "parts", ".", "pop", "(", ")", "not", "in", "\"services\"", ":", "next", "path", "=", "\"/\"", ".", "join", "(", "parts", ")", "else", ":", "path", "=", "\"arcgis\"", "self", ".", "_adminUrl", "=", "\"%s://%s/%s/admin\"", "%", "(", "parsed", ".", "scheme", ",", "parsed", ".", "netloc", ",", "path", ")", "return", "\"%s://%s/%s/rest/services\"", "%", "(", "parsed", ".", "scheme", ",", "parsed", ".", "netloc", ",", "path", ")" ]
assembles the server url
[ "assembles", "the", "server", "url" ]
ab240fde2b0200f61d4a5f6df033516e53f2f416
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/ags/server.py#L57-L74
train
Esri/ArcREST
src/arcrest/ags/server.py
Server.admin
def admin(self): """points to the adminstrative side of ArcGIS Server""" if self._securityHandler is None: raise Exception("Cannot connect to adminstrative server without authentication") from ..manageags import AGSAdministration return AGSAdministration(url=self._adminUrl, securityHandler=self._securityHandler, proxy_url=self._proxy_url, proxy_port=self._proxy_port, initialize=False)
python
def admin(self): """points to the adminstrative side of ArcGIS Server""" if self._securityHandler is None: raise Exception("Cannot connect to adminstrative server without authentication") from ..manageags import AGSAdministration return AGSAdministration(url=self._adminUrl, securityHandler=self._securityHandler, proxy_url=self._proxy_url, proxy_port=self._proxy_port, initialize=False)
[ "def", "admin", "(", "self", ")", ":", "if", "self", ".", "_securityHandler", "is", "None", ":", "raise", "Exception", "(", "\"Cannot connect to adminstrative server without authentication\"", ")", "from", ".", ".", "manageags", "import", "AGSAdministration", "return", "AGSAdministration", "(", "url", "=", "self", ".", "_adminUrl", ",", "securityHandler", "=", "self", ".", "_securityHandler", ",", "proxy_url", "=", "self", ".", "_proxy_url", ",", "proxy_port", "=", "self", ".", "_proxy_port", ",", "initialize", "=", "False", ")" ]
points to the adminstrative side of ArcGIS Server
[ "points", "to", "the", "adminstrative", "side", "of", "ArcGIS", "Server" ]
ab240fde2b0200f61d4a5f6df033516e53f2f416
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/ags/server.py#L118-L127
train
Esri/ArcREST
src/arcrest/manageorg/_parameters.py
InvitationList.addUser
def addUser(self, username, password, firstname, lastname, email, role): """adds a user to the invitation list""" self._invites.append({ "username":username, "password":password, "firstname":firstname, "lastname":lastname, "fullname":"%s %s" % (firstname, lastname), "email":email, "role":role })
python
def addUser(self, username, password, firstname, lastname, email, role): """adds a user to the invitation list""" self._invites.append({ "username":username, "password":password, "firstname":firstname, "lastname":lastname, "fullname":"%s %s" % (firstname, lastname), "email":email, "role":role })
[ "def", "addUser", "(", "self", ",", "username", ",", "password", ",", "firstname", ",", "lastname", ",", "email", ",", "role", ")", ":", "self", ".", "_invites", ".", "append", "(", "{", "\"username\"", ":", "username", ",", "\"password\"", ":", "password", ",", "\"firstname\"", ":", "firstname", ",", "\"lastname\"", ":", "lastname", ",", "\"fullname\"", ":", "\"%s %s\"", "%", "(", "firstname", ",", "lastname", ")", ",", "\"email\"", ":", "email", ",", "\"role\"", ":", "role", "}", ")" ]
adds a user to the invitation list
[ "adds", "a", "user", "to", "the", "invitation", "list" ]
ab240fde2b0200f61d4a5f6df033516e53f2f416
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/manageorg/_parameters.py#L17-L29
train
Esri/ArcREST
src/arcrest/manageorg/_parameters.py
InvitationList.removeByIndex
def removeByIndex(self, index): """removes a user from the invitation list by position""" if index < len(self._invites) -1 and \ index >=0: self._invites.remove(index)
python
def removeByIndex(self, index): """removes a user from the invitation list by position""" if index < len(self._invites) -1 and \ index >=0: self._invites.remove(index)
[ "def", "removeByIndex", "(", "self", ",", "index", ")", ":", "if", "index", "<", "len", "(", "self", ".", "_invites", ")", "-", "1", "and", "index", ">=", "0", ":", "self", ".", "_invites", ".", "remove", "(", "index", ")" ]
removes a user from the invitation list by position
[ "removes", "a", "user", "from", "the", "invitation", "list", "by", "position" ]
ab240fde2b0200f61d4a5f6df033516e53f2f416
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/manageorg/_parameters.py#L31-L35
train
Esri/ArcREST
src/arcrest/manageorg/_parameters.py
PortalParameters.fromDictionary
def fromDictionary(value): """creates the portal properties object from a dictionary""" if isinstance(value, dict): pp = PortalParameters() for k,v in value.items(): setattr(pp, "_%s" % k, v) return pp else: raise AttributeError("Invalid input.")
python
def fromDictionary(value): """creates the portal properties object from a dictionary""" if isinstance(value, dict): pp = PortalParameters() for k,v in value.items(): setattr(pp, "_%s" % k, v) return pp else: raise AttributeError("Invalid input.")
[ "def", "fromDictionary", "(", "value", ")", ":", "if", "isinstance", "(", "value", ",", "dict", ")", ":", "pp", "=", "PortalParameters", "(", ")", "for", "k", ",", "v", "in", "value", ".", "items", "(", ")", ":", "setattr", "(", "pp", ",", "\"_%s\"", "%", "k", ",", "v", ")", "return", "pp", "else", ":", "raise", "AttributeError", "(", "\"Invalid input.\"", ")" ]
creates the portal properties object from a dictionary
[ "creates", "the", "portal", "properties", "object", "from", "a", "dictionary" ]
ab240fde2b0200f61d4a5f6df033516e53f2f416
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/manageorg/_parameters.py#L434-L442
train
Esri/ArcREST
src/arcrest/manageorg/_parameters.py
PublishCSVParameters.value
def value(self): """returns the values as a dictionary""" val = {} for k in self.__allowed_keys: value = getattr(self, "_" + k) if value is not None: val[k] = value return val
python
def value(self): """returns the values as a dictionary""" val = {} for k in self.__allowed_keys: value = getattr(self, "_" + k) if value is not None: val[k] = value return val
[ "def", "value", "(", "self", ")", ":", "val", "=", "{", "}", "for", "k", "in", "self", ".", "__allowed_keys", ":", "value", "=", "getattr", "(", "self", ",", "\"_\"", "+", "k", ")", "if", "value", "is", "not", "None", ":", "val", "[", "k", "]", "=", "value", "return", "val" ]
returns the values as a dictionary
[ "returns", "the", "values", "as", "a", "dictionary" ]
ab240fde2b0200f61d4a5f6df033516e53f2f416
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/manageorg/_parameters.py#L1775-L1782
train
Esri/ArcREST
src/arcrest/ags/_vectortile.py
VectorTileService.tile_fonts
def tile_fonts(self, fontstack, stack_range, out_folder=None): """This resource returns glyphs in PBF format. The template url for this fonts resource is represented in Vector Tile Style resource.""" url = "{url}/resources/fonts/{fontstack}/{stack_range}.pbf".format( url=self._url, fontstack=fontstack, stack_range=stack_range) params = {} if out_folder is None: out_folder = tempfile.gettempdir() return self._get(url=url, param_dict=params, out_folder=out_folder, securityHandler=self._securityHandler, proxy_port=self._proxy_port, proxy_url=self._proxy_host)
python
def tile_fonts(self, fontstack, stack_range, out_folder=None): """This resource returns glyphs in PBF format. The template url for this fonts resource is represented in Vector Tile Style resource.""" url = "{url}/resources/fonts/{fontstack}/{stack_range}.pbf".format( url=self._url, fontstack=fontstack, stack_range=stack_range) params = {} if out_folder is None: out_folder = tempfile.gettempdir() return self._get(url=url, param_dict=params, out_folder=out_folder, securityHandler=self._securityHandler, proxy_port=self._proxy_port, proxy_url=self._proxy_host)
[ "def", "tile_fonts", "(", "self", ",", "fontstack", ",", "stack_range", ",", "out_folder", "=", "None", ")", ":", "url", "=", "\"{url}/resources/fonts/{fontstack}/{stack_range}.pbf\"", ".", "format", "(", "url", "=", "self", ".", "_url", ",", "fontstack", "=", "fontstack", ",", "stack_range", "=", "stack_range", ")", "params", "=", "{", "}", "if", "out_folder", "is", "None", ":", "out_folder", "=", "tempfile", ".", "gettempdir", "(", ")", "return", "self", ".", "_get", "(", "url", "=", "url", ",", "param_dict", "=", "params", ",", "out_folder", "=", "out_folder", ",", "securityHandler", "=", "self", ".", "_securityHandler", ",", "proxy_port", "=", "self", ".", "_proxy_port", ",", "proxy_url", "=", "self", ".", "_proxy_host", ")" ]
This resource returns glyphs in PBF format. The template url for this fonts resource is represented in Vector Tile Style resource.
[ "This", "resource", "returns", "glyphs", "in", "PBF", "format", ".", "The", "template", "url", "for", "this", "fonts", "resource", "is", "represented", "in", "Vector", "Tile", "Style", "resource", "." ]
ab240fde2b0200f61d4a5f6df033516e53f2f416
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/ags/_vectortile.py#L190-L205
train
Esri/ArcREST
src/arcrest/ags/_vectortile.py
VectorTileService.tile_sprite
def tile_sprite(self, out_format="sprite.json", out_folder=None): """ This resource returns sprite image and metadata """ url = "{url}/resources/sprites/{f}".format(url=self._url, f=out_format) if out_folder is None: out_folder = tempfile.gettempdir() return self._get(url=url, param_dict={}, out_folder=out_folder, securityHandler=self._securityHandler, proxy_port=self._proxy_port, proxy_url=self._proxy_host)
python
def tile_sprite(self, out_format="sprite.json", out_folder=None): """ This resource returns sprite image and metadata """ url = "{url}/resources/sprites/{f}".format(url=self._url, f=out_format) if out_folder is None: out_folder = tempfile.gettempdir() return self._get(url=url, param_dict={}, out_folder=out_folder, securityHandler=self._securityHandler, proxy_port=self._proxy_port, proxy_url=self._proxy_host)
[ "def", "tile_sprite", "(", "self", ",", "out_format", "=", "\"sprite.json\"", ",", "out_folder", "=", "None", ")", ":", "url", "=", "\"{url}/resources/sprites/{f}\"", ".", "format", "(", "url", "=", "self", ".", "_url", ",", "f", "=", "out_format", ")", "if", "out_folder", "is", "None", ":", "out_folder", "=", "tempfile", ".", "gettempdir", "(", ")", "return", "self", ".", "_get", "(", "url", "=", "url", ",", "param_dict", "=", "{", "}", ",", "out_folder", "=", "out_folder", ",", "securityHandler", "=", "self", ".", "_securityHandler", ",", "proxy_port", "=", "self", ".", "_proxy_port", ",", "proxy_url", "=", "self", ".", "_proxy_host", ")" ]
This resource returns sprite image and metadata
[ "This", "resource", "returns", "sprite", "image", "and", "metadata" ]
ab240fde2b0200f61d4a5f6df033516e53f2f416
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/ags/_vectortile.py#L226-L239
train
Esri/ArcREST
src/arcrest/ags/services.py
FeatureService.layers
def layers(self): """ gets the layers for the feature service """ if self._layers is None: self.__init() self._getLayers() return self._layers
python
def layers(self): """ gets the layers for the feature service """ if self._layers is None: self.__init() self._getLayers() return self._layers
[ "def", "layers", "(", "self", ")", ":", "if", "self", ".", "_layers", "is", "None", ":", "self", ".", "__init", "(", ")", "self", ".", "_getLayers", "(", ")", "return", "self", ".", "_layers" ]
gets the layers for the feature service
[ "gets", "the", "layers", "for", "the", "feature", "service" ]
ab240fde2b0200f61d4a5f6df033516e53f2f416
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/ags/services.py#L264-L269
train
Esri/ArcREST
src/arcrest/ags/services.py
FeatureService._getLayers
def _getLayers(self): """ gets layers for the featuer service """ params = {"f": "json"} json_dict = self._get(self._url, params, securityHandler=self._securityHandler, proxy_url=self._proxy_url, proxy_port=self._proxy_port) self._layers = [] if 'layers' in json_dict: for l in json_dict["layers"]: self._layers.append( layer.FeatureLayer(url=self._url + "/%s" % l['id'], securityHandler=self._securityHandler, proxy_port=self._proxy_port, proxy_url=self._proxy_url) )
python
def _getLayers(self): """ gets layers for the featuer service """ params = {"f": "json"} json_dict = self._get(self._url, params, securityHandler=self._securityHandler, proxy_url=self._proxy_url, proxy_port=self._proxy_port) self._layers = [] if 'layers' in json_dict: for l in json_dict["layers"]: self._layers.append( layer.FeatureLayer(url=self._url + "/%s" % l['id'], securityHandler=self._securityHandler, proxy_port=self._proxy_port, proxy_url=self._proxy_url) )
[ "def", "_getLayers", "(", "self", ")", ":", "params", "=", "{", "\"f\"", ":", "\"json\"", "}", "json_dict", "=", "self", ".", "_get", "(", "self", ".", "_url", ",", "params", ",", "securityHandler", "=", "self", ".", "_securityHandler", ",", "proxy_url", "=", "self", ".", "_proxy_url", ",", "proxy_port", "=", "self", ".", "_proxy_port", ")", "self", ".", "_layers", "=", "[", "]", "if", "'layers'", "in", "json_dict", ":", "for", "l", "in", "json_dict", "[", "\"layers\"", "]", ":", "self", ".", "_layers", ".", "append", "(", "layer", ".", "FeatureLayer", "(", "url", "=", "self", ".", "_url", "+", "\"/%s\"", "%", "l", "[", "'id'", "]", ",", "securityHandler", "=", "self", ".", "_securityHandler", ",", "proxy_port", "=", "self", ".", "_proxy_port", ",", "proxy_url", "=", "self", ".", "_proxy_url", ")", ")" ]
gets layers for the featuer service
[ "gets", "layers", "for", "the", "featuer", "service" ]
ab240fde2b0200f61d4a5f6df033516e53f2f416
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/ags/services.py#L271-L287
train
Esri/ArcREST
src/arcrest/ags/services.py
FeatureService.query
def query(self, layerDefsFilter=None, geometryFilter=None, timeFilter=None, returnGeometry=True, returnIdsOnly=False, returnCountOnly=False, returnZ=False, returnM=False, outSR=None ): """ The Query operation is performed on a feature service resource """ qurl = self._url + "/query" params = {"f": "json", "returnGeometry": returnGeometry, "returnIdsOnly": returnIdsOnly, "returnCountOnly": returnCountOnly, "returnZ": returnZ, "returnM" : returnM} if not layerDefsFilter is None and \ isinstance(layerDefsFilter, LayerDefinitionFilter): params['layerDefs'] = layerDefsFilter.filter if not geometryFilter is None and \ isinstance(geometryFilter, GeometryFilter): gf = geometryFilter.filter params['geometryType'] = gf['geometryType'] params['spatialRel'] = gf['spatialRel'] params['geometry'] = gf['geometry'] params['inSR'] = gf['inSR'] if not outSR is None and \ isinstance(outSR, SpatialReference): params['outSR'] = outSR.asDictionary if not timeFilter is None and \ isinstance(timeFilter, TimeFilter): params['time'] = timeFilter.filter res = self._post(url=qurl, param_dict=params, securityHandler=self._securityHandler, proxy_url=self._proxy_url, proxy_port=self._proxy_port) if returnIdsOnly == False and returnCountOnly == False: if isinstance(res, str): jd = json.loads(res) return [FeatureSet.fromJSON(json.dumps(lyr)) for lyr in jd['layers']] elif isinstance(res, dict): return [FeatureSet.fromJSON(json.dumps(lyr)) for lyr in res['layers']] else: return res return res
python
def query(self, layerDefsFilter=None, geometryFilter=None, timeFilter=None, returnGeometry=True, returnIdsOnly=False, returnCountOnly=False, returnZ=False, returnM=False, outSR=None ): """ The Query operation is performed on a feature service resource """ qurl = self._url + "/query" params = {"f": "json", "returnGeometry": returnGeometry, "returnIdsOnly": returnIdsOnly, "returnCountOnly": returnCountOnly, "returnZ": returnZ, "returnM" : returnM} if not layerDefsFilter is None and \ isinstance(layerDefsFilter, LayerDefinitionFilter): params['layerDefs'] = layerDefsFilter.filter if not geometryFilter is None and \ isinstance(geometryFilter, GeometryFilter): gf = geometryFilter.filter params['geometryType'] = gf['geometryType'] params['spatialRel'] = gf['spatialRel'] params['geometry'] = gf['geometry'] params['inSR'] = gf['inSR'] if not outSR is None and \ isinstance(outSR, SpatialReference): params['outSR'] = outSR.asDictionary if not timeFilter is None and \ isinstance(timeFilter, TimeFilter): params['time'] = timeFilter.filter res = self._post(url=qurl, param_dict=params, securityHandler=self._securityHandler, proxy_url=self._proxy_url, proxy_port=self._proxy_port) if returnIdsOnly == False and returnCountOnly == False: if isinstance(res, str): jd = json.loads(res) return [FeatureSet.fromJSON(json.dumps(lyr)) for lyr in jd['layers']] elif isinstance(res, dict): return [FeatureSet.fromJSON(json.dumps(lyr)) for lyr in res['layers']] else: return res return res
[ "def", "query", "(", "self", ",", "layerDefsFilter", "=", "None", ",", "geometryFilter", "=", "None", ",", "timeFilter", "=", "None", ",", "returnGeometry", "=", "True", ",", "returnIdsOnly", "=", "False", ",", "returnCountOnly", "=", "False", ",", "returnZ", "=", "False", ",", "returnM", "=", "False", ",", "outSR", "=", "None", ")", ":", "qurl", "=", "self", ".", "_url", "+", "\"/query\"", "params", "=", "{", "\"f\"", ":", "\"json\"", ",", "\"returnGeometry\"", ":", "returnGeometry", ",", "\"returnIdsOnly\"", ":", "returnIdsOnly", ",", "\"returnCountOnly\"", ":", "returnCountOnly", ",", "\"returnZ\"", ":", "returnZ", ",", "\"returnM\"", ":", "returnM", "}", "if", "not", "layerDefsFilter", "is", "None", "and", "isinstance", "(", "layerDefsFilter", ",", "LayerDefinitionFilter", ")", ":", "params", "[", "'layerDefs'", "]", "=", "layerDefsFilter", ".", "filter", "if", "not", "geometryFilter", "is", "None", "and", "isinstance", "(", "geometryFilter", ",", "GeometryFilter", ")", ":", "gf", "=", "geometryFilter", ".", "filter", "params", "[", "'geometryType'", "]", "=", "gf", "[", "'geometryType'", "]", "params", "[", "'spatialRel'", "]", "=", "gf", "[", "'spatialRel'", "]", "params", "[", "'geometry'", "]", "=", "gf", "[", "'geometry'", "]", "params", "[", "'inSR'", "]", "=", "gf", "[", "'inSR'", "]", "if", "not", "outSR", "is", "None", "and", "isinstance", "(", "outSR", ",", "SpatialReference", ")", ":", "params", "[", "'outSR'", "]", "=", "outSR", ".", "asDictionary", "if", "not", "timeFilter", "is", "None", "and", "isinstance", "(", "timeFilter", ",", "TimeFilter", ")", ":", "params", "[", "'time'", "]", "=", "timeFilter", ".", "filter", "res", "=", "self", ".", "_post", "(", "url", "=", "qurl", ",", "param_dict", "=", "params", ",", "securityHandler", "=", "self", ".", "_securityHandler", ",", "proxy_url", "=", "self", ".", "_proxy_url", ",", "proxy_port", "=", "self", ".", "_proxy_port", ")", "if", "returnIdsOnly", "==", "False", "and", "returnCountOnly", "==", "False", ":", "if", "isinstance", "(", "res", ",", "str", ")", ":", "jd", "=", "json", ".", "loads", "(", "res", ")", "return", "[", "FeatureSet", ".", "fromJSON", "(", "json", ".", "dumps", "(", "lyr", ")", ")", "for", "lyr", "in", "jd", "[", "'layers'", "]", "]", "elif", "isinstance", "(", "res", ",", "dict", ")", ":", "return", "[", "FeatureSet", ".", "fromJSON", "(", "json", ".", "dumps", "(", "lyr", ")", ")", "for", "lyr", "in", "res", "[", "'layers'", "]", "]", "else", ":", "return", "res", "return", "res" ]
The Query operation is performed on a feature service resource
[ "The", "Query", "operation", "is", "performed", "on", "a", "feature", "service", "resource" ]
ab240fde2b0200f61d4a5f6df033516e53f2f416
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/ags/services.py#L346-L397
train
Esri/ArcREST
src/arcrest/common/spatial.py
create_feature_layer
def create_feature_layer(ds, sql, name="layer"): """ creates a feature layer object """ if arcpyFound == False: raise Exception("ArcPy is required to use this function") result = arcpy.MakeFeatureLayer_management(in_features=ds, out_layer=name, where_clause=sql) return result[0]
python
def create_feature_layer(ds, sql, name="layer"): """ creates a feature layer object """ if arcpyFound == False: raise Exception("ArcPy is required to use this function") result = arcpy.MakeFeatureLayer_management(in_features=ds, out_layer=name, where_clause=sql) return result[0]
[ "def", "create_feature_layer", "(", "ds", ",", "sql", ",", "name", "=", "\"layer\"", ")", ":", "if", "arcpyFound", "==", "False", ":", "raise", "Exception", "(", "\"ArcPy is required to use this function\"", ")", "result", "=", "arcpy", ".", "MakeFeatureLayer_management", "(", "in_features", "=", "ds", ",", "out_layer", "=", "name", ",", "where_clause", "=", "sql", ")", "return", "result", "[", "0", "]" ]
creates a feature layer object
[ "creates", "a", "feature", "layer", "object" ]
ab240fde2b0200f61d4a5f6df033516e53f2f416
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/common/spatial.py#L16-L23
train
Esri/ArcREST
src/arcrest/common/spatial.py
featureclass_to_json
def featureclass_to_json(fc): """converts a feature class to JSON""" if arcpyFound == False: raise Exception("ArcPy is required to use this function") desc = arcpy.Describe(fc) if desc.dataType == "Table" or desc.dataType == "TableView": return recordset_to_json(table=fc) else: return arcpy.FeatureSet(fc).JSON
python
def featureclass_to_json(fc): """converts a feature class to JSON""" if arcpyFound == False: raise Exception("ArcPy is required to use this function") desc = arcpy.Describe(fc) if desc.dataType == "Table" or desc.dataType == "TableView": return recordset_to_json(table=fc) else: return arcpy.FeatureSet(fc).JSON
[ "def", "featureclass_to_json", "(", "fc", ")", ":", "if", "arcpyFound", "==", "False", ":", "raise", "Exception", "(", "\"ArcPy is required to use this function\"", ")", "desc", "=", "arcpy", ".", "Describe", "(", "fc", ")", "if", "desc", ".", "dataType", "==", "\"Table\"", "or", "desc", ".", "dataType", "==", "\"TableView\"", ":", "return", "recordset_to_json", "(", "table", "=", "fc", ")", "else", ":", "return", "arcpy", ".", "FeatureSet", "(", "fc", ")", ".", "JSON" ]
converts a feature class to JSON
[ "converts", "a", "feature", "class", "to", "JSON" ]
ab240fde2b0200f61d4a5f6df033516e53f2f416
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/common/spatial.py#L25-L33
train
Esri/ArcREST
src/arcrest/common/spatial.py
get_attachment_data
def get_attachment_data(attachmentTable, sql, nameField="ATT_NAME", blobField="DATA", contentTypeField="CONTENT_TYPE", rel_object_field="REL_OBJECTID"): """ gets all the data to pass to a feature service """ if arcpyFound == False: raise Exception("ArcPy is required to use this function") ret_rows = [] with arcpy.da.SearchCursor(attachmentTable, [nameField, blobField, contentTypeField, rel_object_field], where_clause=sql) as rows: for row in rows: temp_f = os.environ['temp'] + os.sep + row[0] writer = open(temp_f,'wb') writer.write(row[1]) writer.flush() writer.close() del writer ret_rows.append({ "name" : row[0], "blob" : temp_f, "content" : row[2], "rel_oid" : row[3] }) del row return ret_rows
python
def get_attachment_data(attachmentTable, sql, nameField="ATT_NAME", blobField="DATA", contentTypeField="CONTENT_TYPE", rel_object_field="REL_OBJECTID"): """ gets all the data to pass to a feature service """ if arcpyFound == False: raise Exception("ArcPy is required to use this function") ret_rows = [] with arcpy.da.SearchCursor(attachmentTable, [nameField, blobField, contentTypeField, rel_object_field], where_clause=sql) as rows: for row in rows: temp_f = os.environ['temp'] + os.sep + row[0] writer = open(temp_f,'wb') writer.write(row[1]) writer.flush() writer.close() del writer ret_rows.append({ "name" : row[0], "blob" : temp_f, "content" : row[2], "rel_oid" : row[3] }) del row return ret_rows
[ "def", "get_attachment_data", "(", "attachmentTable", ",", "sql", ",", "nameField", "=", "\"ATT_NAME\"", ",", "blobField", "=", "\"DATA\"", ",", "contentTypeField", "=", "\"CONTENT_TYPE\"", ",", "rel_object_field", "=", "\"REL_OBJECTID\"", ")", ":", "if", "arcpyFound", "==", "False", ":", "raise", "Exception", "(", "\"ArcPy is required to use this function\"", ")", "ret_rows", "=", "[", "]", "with", "arcpy", ".", "da", ".", "SearchCursor", "(", "attachmentTable", ",", "[", "nameField", ",", "blobField", ",", "contentTypeField", ",", "rel_object_field", "]", ",", "where_clause", "=", "sql", ")", "as", "rows", ":", "for", "row", "in", "rows", ":", "temp_f", "=", "os", ".", "environ", "[", "'temp'", "]", "+", "os", ".", "sep", "+", "row", "[", "0", "]", "writer", "=", "open", "(", "temp_f", ",", "'wb'", ")", "writer", ".", "write", "(", "row", "[", "1", "]", ")", "writer", ".", "flush", "(", ")", "writer", ".", "close", "(", ")", "del", "writer", "ret_rows", ".", "append", "(", "{", "\"name\"", ":", "row", "[", "0", "]", ",", "\"blob\"", ":", "temp_f", ",", "\"content\"", ":", "row", "[", "2", "]", ",", "\"rel_oid\"", ":", "row", "[", "3", "]", "}", ")", "del", "row", "return", "ret_rows" ]
gets all the data to pass to a feature service
[ "gets", "all", "the", "data", "to", "pass", "to", "a", "feature", "service" ]
ab240fde2b0200f61d4a5f6df033516e53f2f416
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/common/spatial.py#L54-L82
train
Esri/ArcREST
src/arcrest/common/spatial.py
get_records_with_attachments
def get_records_with_attachments(attachment_table, rel_object_field="REL_OBJECTID"): """returns a list of ObjectIDs for rows in the attachment table""" if arcpyFound == False: raise Exception("ArcPy is required to use this function") OIDs = [] with arcpy.da.SearchCursor(attachment_table, [rel_object_field]) as rows: for row in rows: if not str(row[0]) in OIDs: OIDs.append("%s" % str(row[0])) del row del rows return OIDs
python
def get_records_with_attachments(attachment_table, rel_object_field="REL_OBJECTID"): """returns a list of ObjectIDs for rows in the attachment table""" if arcpyFound == False: raise Exception("ArcPy is required to use this function") OIDs = [] with arcpy.da.SearchCursor(attachment_table, [rel_object_field]) as rows: for row in rows: if not str(row[0]) in OIDs: OIDs.append("%s" % str(row[0])) del row del rows return OIDs
[ "def", "get_records_with_attachments", "(", "attachment_table", ",", "rel_object_field", "=", "\"REL_OBJECTID\"", ")", ":", "if", "arcpyFound", "==", "False", ":", "raise", "Exception", "(", "\"ArcPy is required to use this function\"", ")", "OIDs", "=", "[", "]", "with", "arcpy", ".", "da", ".", "SearchCursor", "(", "attachment_table", ",", "[", "rel_object_field", "]", ")", "as", "rows", ":", "for", "row", "in", "rows", ":", "if", "not", "str", "(", "row", "[", "0", "]", ")", "in", "OIDs", ":", "OIDs", ".", "append", "(", "\"%s\"", "%", "str", "(", "row", "[", "0", "]", ")", ")", "del", "row", "del", "rows", "return", "OIDs" ]
returns a list of ObjectIDs for rows in the attachment table
[ "returns", "a", "list", "of", "ObjectIDs", "for", "rows", "in", "the", "attachment", "table" ]
ab240fde2b0200f61d4a5f6df033516e53f2f416
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/common/spatial.py#L84-L96
train
Esri/ArcREST
src/arcrest/common/spatial.py
get_OID_field
def get_OID_field(fs): """returns a featureset's object id field""" if arcpyFound == False: raise Exception("ArcPy is required to use this function") desc = arcpy.Describe(fs) if desc.hasOID: return desc.OIDFieldName return None
python
def get_OID_field(fs): """returns a featureset's object id field""" if arcpyFound == False: raise Exception("ArcPy is required to use this function") desc = arcpy.Describe(fs) if desc.hasOID: return desc.OIDFieldName return None
[ "def", "get_OID_field", "(", "fs", ")", ":", "if", "arcpyFound", "==", "False", ":", "raise", "Exception", "(", "\"ArcPy is required to use this function\"", ")", "desc", "=", "arcpy", ".", "Describe", "(", "fs", ")", "if", "desc", ".", "hasOID", ":", "return", "desc", ".", "OIDFieldName", "return", "None" ]
returns a featureset's object id field
[ "returns", "a", "featureset", "s", "object", "id", "field" ]
ab240fde2b0200f61d4a5f6df033516e53f2f416
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/common/spatial.py#L98-L105
train
Esri/ArcREST
src/arcrest/common/spatial.py
merge_feature_class
def merge_feature_class(merges, out_fc, cleanUp=True): """ merges featureclass into a single feature class """ if arcpyFound == False: raise Exception("ArcPy is required to use this function") if cleanUp == False: if len(merges) == 0: return None elif len(merges) == 1: desc = arcpy.Describe(merges[0]) if hasattr(desc, 'shapeFieldName'): return arcpy.CopyFeatures_management(merges[0], out_fc)[0] else: return arcpy.CopyRows_management(merges[0], out_fc)[0] else: return arcpy.Merge_management(inputs=merges, output=out_fc)[0] else: if len(merges) == 0: return None elif len(merges) == 1: desc = arcpy.Describe(merges[0]) if hasattr(desc, 'shapeFieldName'): merged = arcpy.CopyFeatures_management(merges[0], out_fc)[0] else: merged = arcpy.CopyRows_management(merges[0], out_fc)[0] else: merged = arcpy.Merge_management(inputs=merges, output=out_fc)[0] for m in merges: arcpy.Delete_management(m) del m return merged
python
def merge_feature_class(merges, out_fc, cleanUp=True): """ merges featureclass into a single feature class """ if arcpyFound == False: raise Exception("ArcPy is required to use this function") if cleanUp == False: if len(merges) == 0: return None elif len(merges) == 1: desc = arcpy.Describe(merges[0]) if hasattr(desc, 'shapeFieldName'): return arcpy.CopyFeatures_management(merges[0], out_fc)[0] else: return arcpy.CopyRows_management(merges[0], out_fc)[0] else: return arcpy.Merge_management(inputs=merges, output=out_fc)[0] else: if len(merges) == 0: return None elif len(merges) == 1: desc = arcpy.Describe(merges[0]) if hasattr(desc, 'shapeFieldName'): merged = arcpy.CopyFeatures_management(merges[0], out_fc)[0] else: merged = arcpy.CopyRows_management(merges[0], out_fc)[0] else: merged = arcpy.Merge_management(inputs=merges, output=out_fc)[0] for m in merges: arcpy.Delete_management(m) del m return merged
[ "def", "merge_feature_class", "(", "merges", ",", "out_fc", ",", "cleanUp", "=", "True", ")", ":", "if", "arcpyFound", "==", "False", ":", "raise", "Exception", "(", "\"ArcPy is required to use this function\"", ")", "if", "cleanUp", "==", "False", ":", "if", "len", "(", "merges", ")", "==", "0", ":", "return", "None", "elif", "len", "(", "merges", ")", "==", "1", ":", "desc", "=", "arcpy", ".", "Describe", "(", "merges", "[", "0", "]", ")", "if", "hasattr", "(", "desc", ",", "'shapeFieldName'", ")", ":", "return", "arcpy", ".", "CopyFeatures_management", "(", "merges", "[", "0", "]", ",", "out_fc", ")", "[", "0", "]", "else", ":", "return", "arcpy", ".", "CopyRows_management", "(", "merges", "[", "0", "]", ",", "out_fc", ")", "[", "0", "]", "else", ":", "return", "arcpy", ".", "Merge_management", "(", "inputs", "=", "merges", ",", "output", "=", "out_fc", ")", "[", "0", "]", "else", ":", "if", "len", "(", "merges", ")", "==", "0", ":", "return", "None", "elif", "len", "(", "merges", ")", "==", "1", ":", "desc", "=", "arcpy", ".", "Describe", "(", "merges", "[", "0", "]", ")", "if", "hasattr", "(", "desc", ",", "'shapeFieldName'", ")", ":", "merged", "=", "arcpy", ".", "CopyFeatures_management", "(", "merges", "[", "0", "]", ",", "out_fc", ")", "[", "0", "]", "else", ":", "merged", "=", "arcpy", ".", "CopyRows_management", "(", "merges", "[", "0", "]", ",", "out_fc", ")", "[", "0", "]", "else", ":", "merged", "=", "arcpy", ".", "Merge_management", "(", "inputs", "=", "merges", ",", "output", "=", "out_fc", ")", "[", "0", "]", "for", "m", "in", "merges", ":", "arcpy", ".", "Delete_management", "(", "m", ")", "del", "m", "return", "merged" ]
merges featureclass into a single feature class
[ "merges", "featureclass", "into", "a", "single", "feature", "class" ]
ab240fde2b0200f61d4a5f6df033516e53f2f416
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/common/spatial.py#L107-L138
train
Esri/ArcREST
src/arcrest/common/spatial.py
insert_rows
def insert_rows(fc, features, fields, includeOIDField=False, oidField=None): """ inserts rows based on a list features object """ if arcpyFound == False: raise Exception("ArcPy is required to use this function") icur = None if includeOIDField: arcpy.AddField_management(fc, "FSL_OID", "LONG") fields.append("FSL_OID") if len(features) > 0: fields.append("SHAPE@") workspace = os.path.dirname(fc) with arcpy.da.Editor(workspace) as edit: date_fields = getDateFields(fc) icur = arcpy.da.InsertCursor(fc, fields) for feat in features: row = [""] * len(fields) drow = feat.asRow[0] dfields = feat.fields for field in fields: if field in dfields or \ (includeOIDField and field == "FSL_OID"): if field in date_fields: row[fields.index(field)] = toDateTime(drow[dfields.index(field)]) elif field == "FSL_OID": row[fields.index("FSL_OID")] = drow[dfields.index(oidField)] else: row[fields.index(field)] = drow[dfields.index(field)] del field row[fields.index("SHAPE@")] = feat.geometry icur.insertRow(row) del row del drow del dfields del feat del features icur = None del icur del fields return fc else: return fc
python
def insert_rows(fc, features, fields, includeOIDField=False, oidField=None): """ inserts rows based on a list features object """ if arcpyFound == False: raise Exception("ArcPy is required to use this function") icur = None if includeOIDField: arcpy.AddField_management(fc, "FSL_OID", "LONG") fields.append("FSL_OID") if len(features) > 0: fields.append("SHAPE@") workspace = os.path.dirname(fc) with arcpy.da.Editor(workspace) as edit: date_fields = getDateFields(fc) icur = arcpy.da.InsertCursor(fc, fields) for feat in features: row = [""] * len(fields) drow = feat.asRow[0] dfields = feat.fields for field in fields: if field in dfields or \ (includeOIDField and field == "FSL_OID"): if field in date_fields: row[fields.index(field)] = toDateTime(drow[dfields.index(field)]) elif field == "FSL_OID": row[fields.index("FSL_OID")] = drow[dfields.index(oidField)] else: row[fields.index(field)] = drow[dfields.index(field)] del field row[fields.index("SHAPE@")] = feat.geometry icur.insertRow(row) del row del drow del dfields del feat del features icur = None del icur del fields return fc else: return fc
[ "def", "insert_rows", "(", "fc", ",", "features", ",", "fields", ",", "includeOIDField", "=", "False", ",", "oidField", "=", "None", ")", ":", "if", "arcpyFound", "==", "False", ":", "raise", "Exception", "(", "\"ArcPy is required to use this function\"", ")", "icur", "=", "None", "if", "includeOIDField", ":", "arcpy", ".", "AddField_management", "(", "fc", ",", "\"FSL_OID\"", ",", "\"LONG\"", ")", "fields", ".", "append", "(", "\"FSL_OID\"", ")", "if", "len", "(", "features", ")", ">", "0", ":", "fields", ".", "append", "(", "\"SHAPE@\"", ")", "workspace", "=", "os", ".", "path", ".", "dirname", "(", "fc", ")", "with", "arcpy", ".", "da", ".", "Editor", "(", "workspace", ")", "as", "edit", ":", "date_fields", "=", "getDateFields", "(", "fc", ")", "icur", "=", "arcpy", ".", "da", ".", "InsertCursor", "(", "fc", ",", "fields", ")", "for", "feat", "in", "features", ":", "row", "=", "[", "\"\"", "]", "*", "len", "(", "fields", ")", "drow", "=", "feat", ".", "asRow", "[", "0", "]", "dfields", "=", "feat", ".", "fields", "for", "field", "in", "fields", ":", "if", "field", "in", "dfields", "or", "(", "includeOIDField", "and", "field", "==", "\"FSL_OID\"", ")", ":", "if", "field", "in", "date_fields", ":", "row", "[", "fields", ".", "index", "(", "field", ")", "]", "=", "toDateTime", "(", "drow", "[", "dfields", ".", "index", "(", "field", ")", "]", ")", "elif", "field", "==", "\"FSL_OID\"", ":", "row", "[", "fields", ".", "index", "(", "\"FSL_OID\"", ")", "]", "=", "drow", "[", "dfields", ".", "index", "(", "oidField", ")", "]", "else", ":", "row", "[", "fields", ".", "index", "(", "field", ")", "]", "=", "drow", "[", "dfields", ".", "index", "(", "field", ")", "]", "del", "field", "row", "[", "fields", ".", "index", "(", "\"SHAPE@\"", ")", "]", "=", "feat", ".", "geometry", "icur", ".", "insertRow", "(", "row", ")", "del", "row", "del", "drow", "del", "dfields", "del", "feat", "del", "features", "icur", "=", "None", "del", "icur", "del", "fields", "return", "fc", "else", ":", "return", "fc" ]
inserts rows based on a list features object
[ "inserts", "rows", "based", "on", "a", "list", "features", "object" ]
ab240fde2b0200f61d4a5f6df033516e53f2f416
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/common/spatial.py#L164-L208
train
Esri/ArcREST
src/arcrest/common/spatial.py
create_feature_class
def create_feature_class(out_path, out_name, geom_type, wkid, fields, objectIdField): """ creates a feature class in a given gdb or folder """ if arcpyFound == False: raise Exception("ArcPy is required to use this function") arcpy.env.overwriteOutput = True field_names = [] fc =arcpy.CreateFeatureclass_management(out_path=out_path, out_name=out_name, geometry_type=lookUpGeometry(geom_type), spatial_reference=arcpy.SpatialReference(wkid))[0] for field in fields: if field['name'] != objectIdField: field_names.append(field['name']) arcpy.AddField_management(out_path + os.sep + out_name, field['name'], lookUpFieldType(field['type'])) return fc, field_names
python
def create_feature_class(out_path, out_name, geom_type, wkid, fields, objectIdField): """ creates a feature class in a given gdb or folder """ if arcpyFound == False: raise Exception("ArcPy is required to use this function") arcpy.env.overwriteOutput = True field_names = [] fc =arcpy.CreateFeatureclass_management(out_path=out_path, out_name=out_name, geometry_type=lookUpGeometry(geom_type), spatial_reference=arcpy.SpatialReference(wkid))[0] for field in fields: if field['name'] != objectIdField: field_names.append(field['name']) arcpy.AddField_management(out_path + os.sep + out_name, field['name'], lookUpFieldType(field['type'])) return fc, field_names
[ "def", "create_feature_class", "(", "out_path", ",", "out_name", ",", "geom_type", ",", "wkid", ",", "fields", ",", "objectIdField", ")", ":", "if", "arcpyFound", "==", "False", ":", "raise", "Exception", "(", "\"ArcPy is required to use this function\"", ")", "arcpy", ".", "env", ".", "overwriteOutput", "=", "True", "field_names", "=", "[", "]", "fc", "=", "arcpy", ".", "CreateFeatureclass_management", "(", "out_path", "=", "out_path", ",", "out_name", "=", "out_name", ",", "geometry_type", "=", "lookUpGeometry", "(", "geom_type", ")", ",", "spatial_reference", "=", "arcpy", ".", "SpatialReference", "(", "wkid", ")", ")", "[", "0", "]", "for", "field", "in", "fields", ":", "if", "field", "[", "'name'", "]", "!=", "objectIdField", ":", "field_names", ".", "append", "(", "field", "[", "'name'", "]", ")", "arcpy", ".", "AddField_management", "(", "out_path", "+", "os", ".", "sep", "+", "out_name", ",", "field", "[", "'name'", "]", ",", "lookUpFieldType", "(", "field", "[", "'type'", "]", ")", ")", "return", "fc", ",", "field_names" ]
creates a feature class in a given gdb or folder
[ "creates", "a", "feature", "class", "in", "a", "given", "gdb", "or", "folder" ]
ab240fde2b0200f61d4a5f6df033516e53f2f416
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/common/spatial.py#L210-L231
train
Esri/ArcREST
ArcGIS Desktop Installer/Install_ArcRest/Tools/Scripts/install_arcrest.py
download_arcrest
def download_arcrest(): """downloads arcrest to disk""" arcrest_name = "arcrest.zip" arcresthelper_name = "arcresthelper.zip" url = "https://github.com/Esri/ArcREST/archive/master.zip" file_name = os.path.join(arcpy.env.scratchFolder, os.path.basename(url)) scratch_folder = os.path.join(arcpy.env.scratchFolder, "temp34asdf3d") arcrest_zip = os.path.join(scratch_folder, arcrest_name ) arcresthelper_zip = os.path.join(scratch_folder, arcresthelper_name) if sys.version_info.major == 3: import urllib.request urllib.request.urlretrieve(url, file_name) else: import urllib urllib.urlretrieve(url, file_name) if os.path.isdir(scratch_folder): shutil.rmtree(scratch_folder) os.makedirs(scratch_folder) zip_obj = zipfile.ZipFile(file_name, 'r') zip_obj.extractall(scratch_folder) zip_obj.close() del zip_obj zip_obj = zipfile.ZipFile(arcrest_zip, 'w') zipws(path=os.path.join(scratch_folder, "arcrest-master", "src", "arcrest"), zip=zip_obj, keep=True) zip_obj.close() del zip_obj zip_obj = zipfile.ZipFile(arcresthelper_zip, 'w') zipws(path=os.path.join(scratch_folder, "arcrest-master", "src", "arcresthelper"), zip=zip_obj, keep=True) zip_obj.close() del zip_obj shutil.rmtree(os.path.join(scratch_folder, "arcrest-master")) return arcrest_zip, arcresthelper_zip
python
def download_arcrest(): """downloads arcrest to disk""" arcrest_name = "arcrest.zip" arcresthelper_name = "arcresthelper.zip" url = "https://github.com/Esri/ArcREST/archive/master.zip" file_name = os.path.join(arcpy.env.scratchFolder, os.path.basename(url)) scratch_folder = os.path.join(arcpy.env.scratchFolder, "temp34asdf3d") arcrest_zip = os.path.join(scratch_folder, arcrest_name ) arcresthelper_zip = os.path.join(scratch_folder, arcresthelper_name) if sys.version_info.major == 3: import urllib.request urllib.request.urlretrieve(url, file_name) else: import urllib urllib.urlretrieve(url, file_name) if os.path.isdir(scratch_folder): shutil.rmtree(scratch_folder) os.makedirs(scratch_folder) zip_obj = zipfile.ZipFile(file_name, 'r') zip_obj.extractall(scratch_folder) zip_obj.close() del zip_obj zip_obj = zipfile.ZipFile(arcrest_zip, 'w') zipws(path=os.path.join(scratch_folder, "arcrest-master", "src", "arcrest"), zip=zip_obj, keep=True) zip_obj.close() del zip_obj zip_obj = zipfile.ZipFile(arcresthelper_zip, 'w') zipws(path=os.path.join(scratch_folder, "arcrest-master", "src", "arcresthelper"), zip=zip_obj, keep=True) zip_obj.close() del zip_obj shutil.rmtree(os.path.join(scratch_folder, "arcrest-master")) return arcrest_zip, arcresthelper_zip
[ "def", "download_arcrest", "(", ")", ":", "arcrest_name", "=", "\"arcrest.zip\"", "arcresthelper_name", "=", "\"arcresthelper.zip\"", "url", "=", "\"https://github.com/Esri/ArcREST/archive/master.zip\"", "file_name", "=", "os", ".", "path", ".", "join", "(", "arcpy", ".", "env", ".", "scratchFolder", ",", "os", ".", "path", ".", "basename", "(", "url", ")", ")", "scratch_folder", "=", "os", ".", "path", ".", "join", "(", "arcpy", ".", "env", ".", "scratchFolder", ",", "\"temp34asdf3d\"", ")", "arcrest_zip", "=", "os", ".", "path", ".", "join", "(", "scratch_folder", ",", "arcrest_name", ")", "arcresthelper_zip", "=", "os", ".", "path", ".", "join", "(", "scratch_folder", ",", "arcresthelper_name", ")", "if", "sys", ".", "version_info", ".", "major", "==", "3", ":", "import", "urllib", ".", "request", "urllib", ".", "request", ".", "urlretrieve", "(", "url", ",", "file_name", ")", "else", ":", "import", "urllib", "urllib", ".", "urlretrieve", "(", "url", ",", "file_name", ")", "if", "os", ".", "path", ".", "isdir", "(", "scratch_folder", ")", ":", "shutil", ".", "rmtree", "(", "scratch_folder", ")", "os", ".", "makedirs", "(", "scratch_folder", ")", "zip_obj", "=", "zipfile", ".", "ZipFile", "(", "file_name", ",", "'r'", ")", "zip_obj", ".", "extractall", "(", "scratch_folder", ")", "zip_obj", ".", "close", "(", ")", "del", "zip_obj", "zip_obj", "=", "zipfile", ".", "ZipFile", "(", "arcrest_zip", ",", "'w'", ")", "zipws", "(", "path", "=", "os", ".", "path", ".", "join", "(", "scratch_folder", ",", "\"arcrest-master\"", ",", "\"src\"", ",", "\"arcrest\"", ")", ",", "zip", "=", "zip_obj", ",", "keep", "=", "True", ")", "zip_obj", ".", "close", "(", ")", "del", "zip_obj", "zip_obj", "=", "zipfile", ".", "ZipFile", "(", "arcresthelper_zip", ",", "'w'", ")", "zipws", "(", "path", "=", "os", ".", "path", ".", "join", "(", "scratch_folder", ",", "\"arcrest-master\"", ",", "\"src\"", ",", "\"arcresthelper\"", ")", ",", "zip", "=", "zip_obj", ",", "keep", "=", "True", ")", "zip_obj", ".", "close", "(", ")", "del", "zip_obj", "shutil", ".", "rmtree", "(", "os", ".", "path", ".", "join", "(", "scratch_folder", ",", "\"arcrest-master\"", ")", ")", "return", "arcrest_zip", ",", "arcresthelper_zip" ]
downloads arcrest to disk
[ "downloads", "arcrest", "to", "disk" ]
ab240fde2b0200f61d4a5f6df033516e53f2f416
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/ArcGIS Desktop Installer/Install_ArcRest/Tools/Scripts/install_arcrest.py#L36-L68
train
Esri/ArcREST
src/arcrest/security/security.py
NTLMSecurityHandler.handler
def handler(self): """gets the security handler for the class""" if hasNTLM: if self._handler is None: passman = request.HTTPPasswordMgrWithDefaultRealm() passman.add_password(None, self._parsed_org_url, self._login_username, self._password) self._handler = HTTPNtlmAuthHandler.HTTPNtlmAuthHandler(passman) return self._handler else: raise Exception("Missing Ntlm python package.")
python
def handler(self): """gets the security handler for the class""" if hasNTLM: if self._handler is None: passman = request.HTTPPasswordMgrWithDefaultRealm() passman.add_password(None, self._parsed_org_url, self._login_username, self._password) self._handler = HTTPNtlmAuthHandler.HTTPNtlmAuthHandler(passman) return self._handler else: raise Exception("Missing Ntlm python package.")
[ "def", "handler", "(", "self", ")", ":", "if", "hasNTLM", ":", "if", "self", ".", "_handler", "is", "None", ":", "passman", "=", "request", ".", "HTTPPasswordMgrWithDefaultRealm", "(", ")", "passman", ".", "add_password", "(", "None", ",", "self", ".", "_parsed_org_url", ",", "self", ".", "_login_username", ",", "self", ".", "_password", ")", "self", ".", "_handler", "=", "HTTPNtlmAuthHandler", ".", "HTTPNtlmAuthHandler", "(", "passman", ")", "return", "self", ".", "_handler", "else", ":", "raise", "Exception", "(", "\"Missing Ntlm python package.\"", ")" ]
gets the security handler for the class
[ "gets", "the", "security", "handler", "for", "the", "class" ]
ab240fde2b0200f61d4a5f6df033516e53f2f416
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/security/security.py#L343-L352
train
Esri/ArcREST
src/arcrest/security/security.py
PortalServerSecurityHandler.token
def token(self): """gets the AGS server token""" return self._portalTokenHandler.servertoken(serverURL=self._serverUrl, referer=self._referer)
python
def token(self): """gets the AGS server token""" return self._portalTokenHandler.servertoken(serverURL=self._serverUrl, referer=self._referer)
[ "def", "token", "(", "self", ")", ":", "return", "self", ".", "_portalTokenHandler", ".", "servertoken", "(", "serverURL", "=", "self", ".", "_serverUrl", ",", "referer", "=", "self", ".", "_referer", ")" ]
gets the AGS server token
[ "gets", "the", "AGS", "server", "token" ]
ab240fde2b0200f61d4a5f6df033516e53f2f416
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/security/security.py#L598-L601
train
Esri/ArcREST
src/arcrest/security/security.py
OAuthSecurityHandler.token
def token(self): """ obtains a token from the site """ if self._token is None or \ datetime.datetime.now() >= self._token_expires_on: self._generateForOAuthSecurity(self._client_id, self._secret_id, self._token_url) return self._token
python
def token(self): """ obtains a token from the site """ if self._token is None or \ datetime.datetime.now() >= self._token_expires_on: self._generateForOAuthSecurity(self._client_id, self._secret_id, self._token_url) return self._token
[ "def", "token", "(", "self", ")", ":", "if", "self", ".", "_token", "is", "None", "or", "datetime", ".", "datetime", ".", "now", "(", ")", ">=", "self", ".", "_token_expires_on", ":", "self", ".", "_generateForOAuthSecurity", "(", "self", ".", "_client_id", ",", "self", ".", "_secret_id", ",", "self", ".", "_token_url", ")", "return", "self", ".", "_token" ]
obtains a token from the site
[ "obtains", "a", "token", "from", "the", "site" ]
ab240fde2b0200f61d4a5f6df033516e53f2f416
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/security/security.py#L790-L797
train
Esri/ArcREST
src/arcrest/security/security.py
OAuthSecurityHandler._generateForOAuthSecurity
def _generateForOAuthSecurity(self, client_id, secret_id, token_url=None): """ generates a token based on the OAuth security model """ grant_type="client_credentials" if token_url is None: token_url = "https://www.arcgis.com/sharing/rest/oauth2/token" params = { "client_id" : client_id, "client_secret" : secret_id, "grant_type":grant_type, "f" : "json" } token = self._post(url=token_url, param_dict=params, securityHandler=None, proxy_port=self._proxy_port, proxy_url=self._proxy_url) if 'access_token' in token: self._token = token['access_token'] self._expires_in = token['expires_in'] self._token_created_on = datetime.datetime.now() self._token_expires_on = self._token_created_on + datetime.timedelta(seconds=int(token['expires_in'])) self._valid = True self._message = "Token Generated" else: self._token = None self._expires_in = None self._token_created_on = None self._token_expires_on = None self._valid = False self._message = token
python
def _generateForOAuthSecurity(self, client_id, secret_id, token_url=None): """ generates a token based on the OAuth security model """ grant_type="client_credentials" if token_url is None: token_url = "https://www.arcgis.com/sharing/rest/oauth2/token" params = { "client_id" : client_id, "client_secret" : secret_id, "grant_type":grant_type, "f" : "json" } token = self._post(url=token_url, param_dict=params, securityHandler=None, proxy_port=self._proxy_port, proxy_url=self._proxy_url) if 'access_token' in token: self._token = token['access_token'] self._expires_in = token['expires_in'] self._token_created_on = datetime.datetime.now() self._token_expires_on = self._token_created_on + datetime.timedelta(seconds=int(token['expires_in'])) self._valid = True self._message = "Token Generated" else: self._token = None self._expires_in = None self._token_created_on = None self._token_expires_on = None self._valid = False self._message = token
[ "def", "_generateForOAuthSecurity", "(", "self", ",", "client_id", ",", "secret_id", ",", "token_url", "=", "None", ")", ":", "grant_type", "=", "\"client_credentials\"", "if", "token_url", "is", "None", ":", "token_url", "=", "\"https://www.arcgis.com/sharing/rest/oauth2/token\"", "params", "=", "{", "\"client_id\"", ":", "client_id", ",", "\"client_secret\"", ":", "secret_id", ",", "\"grant_type\"", ":", "grant_type", ",", "\"f\"", ":", "\"json\"", "}", "token", "=", "self", ".", "_post", "(", "url", "=", "token_url", ",", "param_dict", "=", "params", ",", "securityHandler", "=", "None", ",", "proxy_port", "=", "self", ".", "_proxy_port", ",", "proxy_url", "=", "self", ".", "_proxy_url", ")", "if", "'access_token'", "in", "token", ":", "self", ".", "_token", "=", "token", "[", "'access_token'", "]", "self", ".", "_expires_in", "=", "token", "[", "'expires_in'", "]", "self", ".", "_token_created_on", "=", "datetime", ".", "datetime", ".", "now", "(", ")", "self", ".", "_token_expires_on", "=", "self", ".", "_token_created_on", "+", "datetime", ".", "timedelta", "(", "seconds", "=", "int", "(", "token", "[", "'expires_in'", "]", ")", ")", "self", ".", "_valid", "=", "True", "self", ".", "_message", "=", "\"Token Generated\"", "else", ":", "self", ".", "_token", "=", "None", "self", ".", "_expires_in", "=", "None", "self", ".", "_token_created_on", "=", "None", "self", ".", "_token_expires_on", "=", "None", "self", ".", "_valid", "=", "False", "self", ".", "_message", "=", "token" ]
generates a token based on the OAuth security model
[ "generates", "a", "token", "based", "on", "the", "OAuth", "security", "model" ]
ab240fde2b0200f61d4a5f6df033516e53f2f416
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/security/security.py#L847-L877
train
Esri/ArcREST
src/arcrest/security/security.py
ArcGISTokenSecurityHandler.referer_url
def referer_url(self, value): """sets the referer url""" if self._referer_url != value: self._token = None self._referer_url = value
python
def referer_url(self, value): """sets the referer url""" if self._referer_url != value: self._token = None self._referer_url = value
[ "def", "referer_url", "(", "self", ",", "value", ")", ":", "if", "self", ".", "_referer_url", "!=", "value", ":", "self", ".", "_token", "=", "None", "self", ".", "_referer_url", "=", "value" ]
sets the referer url
[ "sets", "the", "referer", "url" ]
ab240fde2b0200f61d4a5f6df033516e53f2f416
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/security/security.py#L1026-L1030
train
Esri/ArcREST
src/arcrest/security/security.py
AGOLTokenSecurityHandler.__getRefererUrl
def __getRefererUrl(self, url=None): """ gets the referer url for the token handler """ if url is None: url = "http://www.arcgis.com/sharing/rest/portals/self" params = { "f" : "json", "token" : self.token } val = self._get(url=url, param_dict=params, proxy_url=self._proxy_url, proxy_port=self._proxy_port) self._referer_url = "arcgis.com"#"http://%s.%s" % (val['urlKey'], val['customBaseUrl']) self._token = None return self._referer_url
python
def __getRefererUrl(self, url=None): """ gets the referer url for the token handler """ if url is None: url = "http://www.arcgis.com/sharing/rest/portals/self" params = { "f" : "json", "token" : self.token } val = self._get(url=url, param_dict=params, proxy_url=self._proxy_url, proxy_port=self._proxy_port) self._referer_url = "arcgis.com"#"http://%s.%s" % (val['urlKey'], val['customBaseUrl']) self._token = None return self._referer_url
[ "def", "__getRefererUrl", "(", "self", ",", "url", "=", "None", ")", ":", "if", "url", "is", "None", ":", "url", "=", "\"http://www.arcgis.com/sharing/rest/portals/self\"", "params", "=", "{", "\"f\"", ":", "\"json\"", ",", "\"token\"", ":", "self", ".", "token", "}", "val", "=", "self", ".", "_get", "(", "url", "=", "url", ",", "param_dict", "=", "params", ",", "proxy_url", "=", "self", ".", "_proxy_url", ",", "proxy_port", "=", "self", ".", "_proxy_port", ")", "self", ".", "_referer_url", "=", "\"arcgis.com\"", "#\"http://%s.%s\" % (val['urlKey'], val['customBaseUrl'])", "self", ".", "_token", "=", "None", "return", "self", ".", "_referer_url" ]
gets the referer url for the token handler
[ "gets", "the", "referer", "url", "for", "the", "token", "handler" ]
ab240fde2b0200f61d4a5f6df033516e53f2f416
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/security/security.py#L1236-L1251
train
Esri/ArcREST
src/arcrest/security/security.py
PortalTokenSecurityHandler.servertoken
def servertoken(self,serverURL,referer): """ returns the server token for the server """ if self._server_token is None or self._server_token_expires_on is None or \ datetime.datetime.now() >= self._server_token_expires_on or \ self._server_url != serverURL: self._server_url = serverURL result = self._generateForServerTokenSecurity(serverURL=serverURL, token=self.token, tokenUrl=self._token_url, referer=referer) if 'error' in result: self._valid = False self._message = result else: self._valid = True self._message = "Server Token Generated" return self._server_token
python
def servertoken(self,serverURL,referer): """ returns the server token for the server """ if self._server_token is None or self._server_token_expires_on is None or \ datetime.datetime.now() >= self._server_token_expires_on or \ self._server_url != serverURL: self._server_url = serverURL result = self._generateForServerTokenSecurity(serverURL=serverURL, token=self.token, tokenUrl=self._token_url, referer=referer) if 'error' in result: self._valid = False self._message = result else: self._valid = True self._message = "Server Token Generated" return self._server_token
[ "def", "servertoken", "(", "self", ",", "serverURL", ",", "referer", ")", ":", "if", "self", ".", "_server_token", "is", "None", "or", "self", ".", "_server_token_expires_on", "is", "None", "or", "datetime", ".", "datetime", ".", "now", "(", ")", ">=", "self", ".", "_server_token_expires_on", "or", "self", ".", "_server_url", "!=", "serverURL", ":", "self", ".", "_server_url", "=", "serverURL", "result", "=", "self", ".", "_generateForServerTokenSecurity", "(", "serverURL", "=", "serverURL", ",", "token", "=", "self", ".", "token", ",", "tokenUrl", "=", "self", ".", "_token_url", ",", "referer", "=", "referer", ")", "if", "'error'", "in", "result", ":", "self", ".", "_valid", "=", "False", "self", ".", "_message", "=", "result", "else", ":", "self", ".", "_valid", "=", "True", "self", ".", "_message", "=", "\"Server Token Generated\"", "return", "self", ".", "_server_token" ]
returns the server token for the server
[ "returns", "the", "server", "token", "for", "the", "server" ]
ab240fde2b0200f61d4a5f6df033516e53f2f416
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/security/security.py#L1856-L1872
train
Esri/ArcREST
src/arcrest/manageags/_machines.py
Machine.exportCertificate
def exportCertificate(self, certificate, folder): """gets the SSL Certificates for a given machine""" url = self._url + "/sslcertificates/%s/export" % certificate params = { "f" : "json", } return self._get(url=url, param_dict=params, out_folder=folder)
python
def exportCertificate(self, certificate, folder): """gets the SSL Certificates for a given machine""" url = self._url + "/sslcertificates/%s/export" % certificate params = { "f" : "json", } return self._get(url=url, param_dict=params, out_folder=folder)
[ "def", "exportCertificate", "(", "self", ",", "certificate", ",", "folder", ")", ":", "url", "=", "self", ".", "_url", "+", "\"/sslcertificates/%s/export\"", "%", "certificate", "params", "=", "{", "\"f\"", ":", "\"json\"", ",", "}", "return", "self", ".", "_get", "(", "url", "=", "url", ",", "param_dict", "=", "params", ",", "out_folder", "=", "folder", ")" ]
gets the SSL Certificates for a given machine
[ "gets", "the", "SSL", "Certificates", "for", "a", "given", "machine" ]
ab240fde2b0200f61d4a5f6df033516e53f2f416
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/manageags/_machines.py#L277-L285
train
Esri/ArcREST
src/arcrest/manageorg/administration.py
Administration.currentVersion
def currentVersion(self): """ returns the current version of the site """ if self._currentVersion is None: self.__init(self._url) return self._currentVersion
python
def currentVersion(self): """ returns the current version of the site """ if self._currentVersion is None: self.__init(self._url) return self._currentVersion
[ "def", "currentVersion", "(", "self", ")", ":", "if", "self", ".", "_currentVersion", "is", "None", ":", "self", ".", "__init", "(", "self", ".", "_url", ")", "return", "self", ".", "_currentVersion" ]
returns the current version of the site
[ "returns", "the", "current", "version", "of", "the", "site" ]
ab240fde2b0200f61d4a5f6df033516e53f2f416
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/manageorg/administration.py#L118-L122
train
Esri/ArcREST
src/arcrest/manageorg/administration.py
Administration.portals
def portals(self): """returns the Portals class that provides administration access into a given organization""" url = "%s/portals" % self.root return _portals.Portals(url=url, securityHandler=self._securityHandler, proxy_url=self._proxy_url, proxy_port=self._proxy_port)
python
def portals(self): """returns the Portals class that provides administration access into a given organization""" url = "%s/portals" % self.root return _portals.Portals(url=url, securityHandler=self._securityHandler, proxy_url=self._proxy_url, proxy_port=self._proxy_port)
[ "def", "portals", "(", "self", ")", ":", "url", "=", "\"%s/portals\"", "%", "self", ".", "root", "return", "_portals", ".", "Portals", "(", "url", "=", "url", ",", "securityHandler", "=", "self", ".", "_securityHandler", ",", "proxy_url", "=", "self", ".", "_proxy_url", ",", "proxy_port", "=", "self", ".", "_proxy_port", ")" ]
returns the Portals class that provides administration access into a given organization
[ "returns", "the", "Portals", "class", "that", "provides", "administration", "access", "into", "a", "given", "organization" ]
ab240fde2b0200f61d4a5f6df033516e53f2f416
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/manageorg/administration.py#L125-L132
train
Esri/ArcREST
src/arcrest/manageorg/administration.py
Administration.oauth2
def oauth2(self): """ returns the oauth2 class """ if self._url.endswith("/oauth2"): url = self._url else: url = self._url + "/oauth2" return _oauth2.oauth2(oauth_url=url, securityHandler=self._securityHandler, proxy_url=self._proxy_url, proxy_port=self._proxy_port)
python
def oauth2(self): """ returns the oauth2 class """ if self._url.endswith("/oauth2"): url = self._url else: url = self._url + "/oauth2" return _oauth2.oauth2(oauth_url=url, securityHandler=self._securityHandler, proxy_url=self._proxy_url, proxy_port=self._proxy_port)
[ "def", "oauth2", "(", "self", ")", ":", "if", "self", ".", "_url", ".", "endswith", "(", "\"/oauth2\"", ")", ":", "url", "=", "self", ".", "_url", "else", ":", "url", "=", "self", ".", "_url", "+", "\"/oauth2\"", "return", "_oauth2", ".", "oauth2", "(", "oauth_url", "=", "url", ",", "securityHandler", "=", "self", ".", "_securityHandler", ",", "proxy_url", "=", "self", ".", "_proxy_url", ",", "proxy_port", "=", "self", ".", "_proxy_port", ")" ]
returns the oauth2 class
[ "returns", "the", "oauth2", "class" ]
ab240fde2b0200f61d4a5f6df033516e53f2f416
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/manageorg/administration.py#L135-L146
train
Esri/ArcREST
src/arcrest/manageorg/administration.py
Administration.community
def community(self): """The portal community root covers user and group resources and operations. """ return _community.Community(url=self._url + "/community", securityHandler=self._securityHandler, proxy_url=self._proxy_url, proxy_port=self._proxy_port)
python
def community(self): """The portal community root covers user and group resources and operations. """ return _community.Community(url=self._url + "/community", securityHandler=self._securityHandler, proxy_url=self._proxy_url, proxy_port=self._proxy_port)
[ "def", "community", "(", "self", ")", ":", "return", "_community", ".", "Community", "(", "url", "=", "self", ".", "_url", "+", "\"/community\"", ",", "securityHandler", "=", "self", ".", "_securityHandler", ",", "proxy_url", "=", "self", ".", "_proxy_url", ",", "proxy_port", "=", "self", ".", "_proxy_port", ")" ]
The portal community root covers user and group resources and operations.
[ "The", "portal", "community", "root", "covers", "user", "and", "group", "resources", "and", "operations", "." ]
ab240fde2b0200f61d4a5f6df033516e53f2f416
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/manageorg/administration.py#L149-L156
train
Esri/ArcREST
src/arcrest/manageorg/administration.py
Administration.content
def content(self): """returns access into the site's content""" return _content.Content(url=self._url + "/content", securityHandler=self._securityHandler, proxy_url=self._proxy_url, proxy_port=self._proxy_port)
python
def content(self): """returns access into the site's content""" return _content.Content(url=self._url + "/content", securityHandler=self._securityHandler, proxy_url=self._proxy_url, proxy_port=self._proxy_port)
[ "def", "content", "(", "self", ")", ":", "return", "_content", ".", "Content", "(", "url", "=", "self", ".", "_url", "+", "\"/content\"", ",", "securityHandler", "=", "self", ".", "_securityHandler", ",", "proxy_url", "=", "self", ".", "_proxy_url", ",", "proxy_port", "=", "self", ".", "_proxy_port", ")" ]
returns access into the site's content
[ "returns", "access", "into", "the", "site", "s", "content" ]
ab240fde2b0200f61d4a5f6df033516e53f2f416
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/manageorg/administration.py#L159-L164
train
Esri/ArcREST
src/arcrest/manageorg/administration.py
Administration.search
def search(self, q, t=None, focus=None, bbox=None, start=1, num=10, sortField=None, sortOrder="asc", useSecurity=True): """ This operation searches for content items in the portal. The searches are performed against a high performance index that indexes the most popular fields of an item. See the Search reference page for information on the fields and the syntax of the query. The search index is updated whenever users add, update, or delete content. There can be a lag between the time that the content is updated and the time when it's reflected in the search results. The results of a search only contain items that the user has permission to access. Inputs: q - The query string used to search t - type of content to search for. focus - another content filter. Ex: files bbox - The bounding box for a spatial search defined as minx, miny, maxx, or maxy. Search requires q, bbox, or both. Spatial search is an overlaps/intersects function of the query bbox and the extent of the document. Documents that have no extent (e.g., mxds, 3dds, lyr) will not be found when doing a bbox search. Document extent is assumed to be in the WGS84 geographic coordinate system. start - The number of the first entry in the result set response. The index number is 1-based. The default value of start is 1 (that is, the first search result). The start parameter, along with the num parameter, can be used to paginate the search results. num - The maximum number of results to be included in the result set response. The default value is 10, and the maximum allowed value is 100. The start parameter, along with the num parameter, can be used to paginate the search results. sortField - Field to sort by. You can also sort by multiple fields (comma separated) for an item. The allowed sort field names are title, created, type, owner, modified, avgRating, numRatings, numComments, and numViews. sortOrder - Describes whether the results return in ascending or descending order. Default is ascending. Values: asc | desc useSecurity - boolean value that determines if the security handler object's token will be appended on the search call. If the value is set to False, then the search will be performed without authentication. This means only items that have been shared with everyone on AGOL or portal site will be found. If it is set to True, then all items the user has permission to see based on the query passed will be returned. Output: returns a list of dictionary """ if self._url.endswith("/rest"): url = self._url + "/search" else: url = self._url + "/rest/search" params = { "f" : "json", "q" : q, "sortOrder" : sortOrder, "num" : num, "start" : start, 'restrict' : useSecurity } if not focus is None: params['focus'] = focus if not t is None: params['t'] = t if useSecurity and \ self._securityHandler is not None and \ self._securityHandler.method == "token": params["token"] = self._securityHandler.token if sortField is not None: params['sortField'] = sortField if bbox is not None: params['bbox'] = bbox return self._get(url=url, param_dict=params, securityHandler=self._securityHandler, proxy_url=self._proxy_url, proxy_port=self._proxy_port)
python
def search(self, q, t=None, focus=None, bbox=None, start=1, num=10, sortField=None, sortOrder="asc", useSecurity=True): """ This operation searches for content items in the portal. The searches are performed against a high performance index that indexes the most popular fields of an item. See the Search reference page for information on the fields and the syntax of the query. The search index is updated whenever users add, update, or delete content. There can be a lag between the time that the content is updated and the time when it's reflected in the search results. The results of a search only contain items that the user has permission to access. Inputs: q - The query string used to search t - type of content to search for. focus - another content filter. Ex: files bbox - The bounding box for a spatial search defined as minx, miny, maxx, or maxy. Search requires q, bbox, or both. Spatial search is an overlaps/intersects function of the query bbox and the extent of the document. Documents that have no extent (e.g., mxds, 3dds, lyr) will not be found when doing a bbox search. Document extent is assumed to be in the WGS84 geographic coordinate system. start - The number of the first entry in the result set response. The index number is 1-based. The default value of start is 1 (that is, the first search result). The start parameter, along with the num parameter, can be used to paginate the search results. num - The maximum number of results to be included in the result set response. The default value is 10, and the maximum allowed value is 100. The start parameter, along with the num parameter, can be used to paginate the search results. sortField - Field to sort by. You can also sort by multiple fields (comma separated) for an item. The allowed sort field names are title, created, type, owner, modified, avgRating, numRatings, numComments, and numViews. sortOrder - Describes whether the results return in ascending or descending order. Default is ascending. Values: asc | desc useSecurity - boolean value that determines if the security handler object's token will be appended on the search call. If the value is set to False, then the search will be performed without authentication. This means only items that have been shared with everyone on AGOL or portal site will be found. If it is set to True, then all items the user has permission to see based on the query passed will be returned. Output: returns a list of dictionary """ if self._url.endswith("/rest"): url = self._url + "/search" else: url = self._url + "/rest/search" params = { "f" : "json", "q" : q, "sortOrder" : sortOrder, "num" : num, "start" : start, 'restrict' : useSecurity } if not focus is None: params['focus'] = focus if not t is None: params['t'] = t if useSecurity and \ self._securityHandler is not None and \ self._securityHandler.method == "token": params["token"] = self._securityHandler.token if sortField is not None: params['sortField'] = sortField if bbox is not None: params['bbox'] = bbox return self._get(url=url, param_dict=params, securityHandler=self._securityHandler, proxy_url=self._proxy_url, proxy_port=self._proxy_port)
[ "def", "search", "(", "self", ",", "q", ",", "t", "=", "None", ",", "focus", "=", "None", ",", "bbox", "=", "None", ",", "start", "=", "1", ",", "num", "=", "10", ",", "sortField", "=", "None", ",", "sortOrder", "=", "\"asc\"", ",", "useSecurity", "=", "True", ")", ":", "if", "self", ".", "_url", ".", "endswith", "(", "\"/rest\"", ")", ":", "url", "=", "self", ".", "_url", "+", "\"/search\"", "else", ":", "url", "=", "self", ".", "_url", "+", "\"/rest/search\"", "params", "=", "{", "\"f\"", ":", "\"json\"", ",", "\"q\"", ":", "q", ",", "\"sortOrder\"", ":", "sortOrder", ",", "\"num\"", ":", "num", ",", "\"start\"", ":", "start", ",", "'restrict'", ":", "useSecurity", "}", "if", "not", "focus", "is", "None", ":", "params", "[", "'focus'", "]", "=", "focus", "if", "not", "t", "is", "None", ":", "params", "[", "'t'", "]", "=", "t", "if", "useSecurity", "and", "self", ".", "_securityHandler", "is", "not", "None", "and", "self", ".", "_securityHandler", ".", "method", "==", "\"token\"", ":", "params", "[", "\"token\"", "]", "=", "self", ".", "_securityHandler", ".", "token", "if", "sortField", "is", "not", "None", ":", "params", "[", "'sortField'", "]", "=", "sortField", "if", "bbox", "is", "not", "None", ":", "params", "[", "'bbox'", "]", "=", "bbox", "return", "self", ".", "_get", "(", "url", "=", "url", ",", "param_dict", "=", "params", ",", "securityHandler", "=", "self", ".", "_securityHandler", ",", "proxy_url", "=", "self", ".", "_proxy_url", ",", "proxy_port", "=", "self", ".", "_proxy_port", ")" ]
This operation searches for content items in the portal. The searches are performed against a high performance index that indexes the most popular fields of an item. See the Search reference page for information on the fields and the syntax of the query. The search index is updated whenever users add, update, or delete content. There can be a lag between the time that the content is updated and the time when it's reflected in the search results. The results of a search only contain items that the user has permission to access. Inputs: q - The query string used to search t - type of content to search for. focus - another content filter. Ex: files bbox - The bounding box for a spatial search defined as minx, miny, maxx, or maxy. Search requires q, bbox, or both. Spatial search is an overlaps/intersects function of the query bbox and the extent of the document. Documents that have no extent (e.g., mxds, 3dds, lyr) will not be found when doing a bbox search. Document extent is assumed to be in the WGS84 geographic coordinate system. start - The number of the first entry in the result set response. The index number is 1-based. The default value of start is 1 (that is, the first search result). The start parameter, along with the num parameter, can be used to paginate the search results. num - The maximum number of results to be included in the result set response. The default value is 10, and the maximum allowed value is 100. The start parameter, along with the num parameter, can be used to paginate the search results. sortField - Field to sort by. You can also sort by multiple fields (comma separated) for an item. The allowed sort field names are title, created, type, owner, modified, avgRating, numRatings, numComments, and numViews. sortOrder - Describes whether the results return in ascending or descending order. Default is ascending. Values: asc | desc useSecurity - boolean value that determines if the security handler object's token will be appended on the search call. If the value is set to False, then the search will be performed without authentication. This means only items that have been shared with everyone on AGOL or portal site will be found. If it is set to True, then all items the user has permission to see based on the query passed will be returned. Output: returns a list of dictionary
[ "This", "operation", "searches", "for", "content", "items", "in", "the", "portal", ".", "The", "searches", "are", "performed", "against", "a", "high", "performance", "index", "that", "indexes", "the", "most", "popular", "fields", "of", "an", "item", ".", "See", "the", "Search", "reference", "page", "for", "information", "on", "the", "fields", "and", "the", "syntax", "of", "the", "query", ".", "The", "search", "index", "is", "updated", "whenever", "users", "add", "update", "or", "delete", "content", ".", "There", "can", "be", "a", "lag", "between", "the", "time", "that", "the", "content", "is", "updated", "and", "the", "time", "when", "it", "s", "reflected", "in", "the", "search", "results", ".", "The", "results", "of", "a", "search", "only", "contain", "items", "that", "the", "user", "has", "permission", "to", "access", "." ]
ab240fde2b0200f61d4a5f6df033516e53f2f416
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/manageorg/administration.py#L167-L263
train
Esri/ArcREST
src/arcrest/manageorg/administration.py
Administration.hostingServers
def hostingServers(self): """ Returns the objects to manage site's hosted services. It returns AGSAdministration object if the site is Portal and it returns a hostedservice.Services object if it is AGOL. """ portals = self.portals portal = portals.portalSelf urls = portal.urls if 'error' in urls: print( urls) return services = [] if urls != {}: if 'urls' in urls: if 'features' in urls['urls']: if 'https' in urls['urls']['features']: for https in urls['urls']['features']['https']: if portal.isPortal == True: url = "%s/admin" % https #url = https services.append(AGSAdministration(url=url, securityHandler=self._securityHandler, proxy_url=self._proxy_url, proxy_port=self._proxy_port)) else: url = "https://%s/%s/ArcGIS/rest/admin" % (https, portal.portalId) services.append(Services(url=url, securityHandler=self._securityHandler, proxy_url=self._proxy_url, proxy_port=self._proxy_port)) elif 'http' in urls['urls']['features']: for http in urls['urls']['features']['http']: if (portal.isPortal == True): url = "%s/admin" % http services.append(AGSAdministration(url=url, securityHandler=self._securityHandler, proxy_url=self._proxy_url, proxy_port=self._proxy_port, initialize=True)) else: url = "http://%s/%s/ArcGIS/rest/admin" % (http, portal.portalId) services.append(Services(url=url, securityHandler=self._securityHandler, proxy_url=self._proxy_url, proxy_port=self._proxy_port)) else: print( "Publishing servers not found") else: print ("Publishing servers not found") else: print( "Publishing servers not found") return services else: for server in portal.servers['servers']: url = server['adminUrl'] + "/admin" sh = PortalServerSecurityHandler(tokenHandler=self._securityHandler, serverUrl=url, referer=server['name'].replace(":6080", ":6443") ) services.append( AGSAdministration(url=url, securityHandler=sh, proxy_url=self._proxy_url, proxy_port=self._proxy_port, initialize=False) ) return services
python
def hostingServers(self): """ Returns the objects to manage site's hosted services. It returns AGSAdministration object if the site is Portal and it returns a hostedservice.Services object if it is AGOL. """ portals = self.portals portal = portals.portalSelf urls = portal.urls if 'error' in urls: print( urls) return services = [] if urls != {}: if 'urls' in urls: if 'features' in urls['urls']: if 'https' in urls['urls']['features']: for https in urls['urls']['features']['https']: if portal.isPortal == True: url = "%s/admin" % https #url = https services.append(AGSAdministration(url=url, securityHandler=self._securityHandler, proxy_url=self._proxy_url, proxy_port=self._proxy_port)) else: url = "https://%s/%s/ArcGIS/rest/admin" % (https, portal.portalId) services.append(Services(url=url, securityHandler=self._securityHandler, proxy_url=self._proxy_url, proxy_port=self._proxy_port)) elif 'http' in urls['urls']['features']: for http in urls['urls']['features']['http']: if (portal.isPortal == True): url = "%s/admin" % http services.append(AGSAdministration(url=url, securityHandler=self._securityHandler, proxy_url=self._proxy_url, proxy_port=self._proxy_port, initialize=True)) else: url = "http://%s/%s/ArcGIS/rest/admin" % (http, portal.portalId) services.append(Services(url=url, securityHandler=self._securityHandler, proxy_url=self._proxy_url, proxy_port=self._proxy_port)) else: print( "Publishing servers not found") else: print ("Publishing servers not found") else: print( "Publishing servers not found") return services else: for server in portal.servers['servers']: url = server['adminUrl'] + "/admin" sh = PortalServerSecurityHandler(tokenHandler=self._securityHandler, serverUrl=url, referer=server['name'].replace(":6080", ":6443") ) services.append( AGSAdministration(url=url, securityHandler=sh, proxy_url=self._proxy_url, proxy_port=self._proxy_port, initialize=False) ) return services
[ "def", "hostingServers", "(", "self", ")", ":", "portals", "=", "self", ".", "portals", "portal", "=", "portals", ".", "portalSelf", "urls", "=", "portal", ".", "urls", "if", "'error'", "in", "urls", ":", "print", "(", "urls", ")", "return", "services", "=", "[", "]", "if", "urls", "!=", "{", "}", ":", "if", "'urls'", "in", "urls", ":", "if", "'features'", "in", "urls", "[", "'urls'", "]", ":", "if", "'https'", "in", "urls", "[", "'urls'", "]", "[", "'features'", "]", ":", "for", "https", "in", "urls", "[", "'urls'", "]", "[", "'features'", "]", "[", "'https'", "]", ":", "if", "portal", ".", "isPortal", "==", "True", ":", "url", "=", "\"%s/admin\"", "%", "https", "#url = https", "services", ".", "append", "(", "AGSAdministration", "(", "url", "=", "url", ",", "securityHandler", "=", "self", ".", "_securityHandler", ",", "proxy_url", "=", "self", ".", "_proxy_url", ",", "proxy_port", "=", "self", ".", "_proxy_port", ")", ")", "else", ":", "url", "=", "\"https://%s/%s/ArcGIS/rest/admin\"", "%", "(", "https", ",", "portal", ".", "portalId", ")", "services", ".", "append", "(", "Services", "(", "url", "=", "url", ",", "securityHandler", "=", "self", ".", "_securityHandler", ",", "proxy_url", "=", "self", ".", "_proxy_url", ",", "proxy_port", "=", "self", ".", "_proxy_port", ")", ")", "elif", "'http'", "in", "urls", "[", "'urls'", "]", "[", "'features'", "]", ":", "for", "http", "in", "urls", "[", "'urls'", "]", "[", "'features'", "]", "[", "'http'", "]", ":", "if", "(", "portal", ".", "isPortal", "==", "True", ")", ":", "url", "=", "\"%s/admin\"", "%", "http", "services", ".", "append", "(", "AGSAdministration", "(", "url", "=", "url", ",", "securityHandler", "=", "self", ".", "_securityHandler", ",", "proxy_url", "=", "self", ".", "_proxy_url", ",", "proxy_port", "=", "self", ".", "_proxy_port", ",", "initialize", "=", "True", ")", ")", "else", ":", "url", "=", "\"http://%s/%s/ArcGIS/rest/admin\"", "%", "(", "http", ",", "portal", ".", "portalId", ")", "services", ".", "append", "(", "Services", "(", "url", "=", "url", ",", "securityHandler", "=", "self", ".", "_securityHandler", ",", "proxy_url", "=", "self", ".", "_proxy_url", ",", "proxy_port", "=", "self", ".", "_proxy_port", ")", ")", "else", ":", "print", "(", "\"Publishing servers not found\"", ")", "else", ":", "print", "(", "\"Publishing servers not found\"", ")", "else", ":", "print", "(", "\"Publishing servers not found\"", ")", "return", "services", "else", ":", "for", "server", "in", "portal", ".", "servers", "[", "'servers'", "]", ":", "url", "=", "server", "[", "'adminUrl'", "]", "+", "\"/admin\"", "sh", "=", "PortalServerSecurityHandler", "(", "tokenHandler", "=", "self", ".", "_securityHandler", ",", "serverUrl", "=", "url", ",", "referer", "=", "server", "[", "'name'", "]", ".", "replace", "(", "\":6080\"", ",", "\":6443\"", ")", ")", "services", ".", "append", "(", "AGSAdministration", "(", "url", "=", "url", ",", "securityHandler", "=", "sh", ",", "proxy_url", "=", "self", ".", "_proxy_url", ",", "proxy_port", "=", "self", ".", "_proxy_port", ",", "initialize", "=", "False", ")", ")", "return", "services" ]
Returns the objects to manage site's hosted services. It returns AGSAdministration object if the site is Portal and it returns a hostedservice.Services object if it is AGOL.
[ "Returns", "the", "objects", "to", "manage", "site", "s", "hosted", "services", ".", "It", "returns", "AGSAdministration", "object", "if", "the", "site", "is", "Portal", "and", "it", "returns", "a", "hostedservice", ".", "Services", "object", "if", "it", "is", "AGOL", "." ]
ab240fde2b0200f61d4a5f6df033516e53f2f416
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/manageorg/administration.py#L267-L341
train
Esri/ArcREST
src/arcrest/webmap/domain.py
CodedValueDomain.add_codedValue
def add_codedValue(self, name, code): """ adds a value to the coded value list """ if self._codedValues is None: self._codedValues = [] self._codedValues.append( {"name": name, "code": code} )
python
def add_codedValue(self, name, code): """ adds a value to the coded value list """ if self._codedValues is None: self._codedValues = [] self._codedValues.append( {"name": name, "code": code} )
[ "def", "add_codedValue", "(", "self", ",", "name", ",", "code", ")", ":", "if", "self", ".", "_codedValues", "is", "None", ":", "self", ".", "_codedValues", "=", "[", "]", "self", ".", "_codedValues", ".", "append", "(", "{", "\"name\"", ":", "name", ",", "\"code\"", ":", "code", "}", ")" ]
adds a value to the coded value list
[ "adds", "a", "value", "to", "the", "coded", "value", "list" ]
ab240fde2b0200f61d4a5f6df033516e53f2f416
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/webmap/domain.py#L96-L102
train
Esri/ArcREST
src/arcrest/geometryservice/geometryservice.py
GeometryService.__init
def __init(self): """loads the json values""" res = self._get(url=self._url, param_dict={"f": "json"}, securityHandler=self._securityHandler, proxy_url=self._proxy_url, proxy_port=self._proxy_port) self._json_dict = res self._json_string = json.dumps(self._json_dict) for k,v in self._json_dict.items(): setattr(self, k, v)
python
def __init(self): """loads the json values""" res = self._get(url=self._url, param_dict={"f": "json"}, securityHandler=self._securityHandler, proxy_url=self._proxy_url, proxy_port=self._proxy_port) self._json_dict = res self._json_string = json.dumps(self._json_dict) for k,v in self._json_dict.items(): setattr(self, k, v)
[ "def", "__init", "(", "self", ")", ":", "res", "=", "self", ".", "_get", "(", "url", "=", "self", ".", "_url", ",", "param_dict", "=", "{", "\"f\"", ":", "\"json\"", "}", ",", "securityHandler", "=", "self", ".", "_securityHandler", ",", "proxy_url", "=", "self", ".", "_proxy_url", ",", "proxy_port", "=", "self", ".", "_proxy_port", ")", "self", ".", "_json_dict", "=", "res", "self", ".", "_json_string", "=", "json", ".", "dumps", "(", "self", ".", "_json_dict", ")", "for", "k", ",", "v", "in", "self", ".", "_json_dict", ".", "items", "(", ")", ":", "setattr", "(", "self", ",", "k", ",", "v", ")" ]
loads the json values
[ "loads", "the", "json", "values" ]
ab240fde2b0200f61d4a5f6df033516e53f2f416
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/geometryservice/geometryservice.py#L33-L43
train
Esri/ArcREST
src/arcrest/geometryservice/geometryservice.py
GeometryService.areasAndLengths
def areasAndLengths(self, polygons, lengthUnit, areaUnit, calculationType, ): """ The areasAndLengths operation is performed on a geometry service resource. This operation calculates areas and perimeter lengths for each polygon specified in the input array. Inputs: polygons - The array of polygons whose areas and lengths are to be computed. lengthUnit - The length unit in which the perimeters of polygons will be calculated. If calculationType is planar, then lengthUnit can be any esriUnits constant. If lengthUnit is not specified, the units are derived from sr. If calculationType is not planar, then lengthUnit must be a linear esriUnits constant, such as esriSRUnit_Meter or esriSRUnit_SurveyMile. If lengthUnit is not specified, the units are meters. For a list of valid units, see esriSRUnitType Constants and esriSRUnit2Type Constant. areaUnit - The area unit in which areas of polygons will be calculated. If calculationType is planar, then areaUnit can be any esriUnits constant. If areaUnit is not specified, the units are derived from sr. If calculationType is not planar, then areaUnit must be a linear esriUnits constant such as esriSRUnit_Meter or esriSRUnit_SurveyMile. If areaUnit is not specified, then the units are meters. For a list of valid units, see esriSRUnitType Constants and esriSRUnit2Type constant. The list of valid esriAreaUnits constants include, esriSquareInches | esriSquareFeet | esriSquareYards | esriAcres | esriSquareMiles | esriSquareMillimeters | esriSquareCentimeters | esriSquareDecimeters | esriSquareMeters | esriAres | esriHectares | esriSquareKilometers. calculationType - The type defined for the area and length calculation of the input geometries. The type can be one of the following values: planar - Planar measurements use 2D Euclidean distance to calculate area and length. Th- should only be used if the area or length needs to be calculated in the given spatial reference. Otherwise, use preserveShape. geodesic - Use this type if you want to calculate an area or length using only the vertices of the polygon and define the lines between the points as geodesic segments independent of the actual shape of the polygon. A geodesic segment is the shortest path between two points on an ellipsoid. preserveShape - This type calculates the area or length of the geometry on the surface of the Earth ellipsoid. The shape of the geometry in its coordinate system is preserved. Output: JSON as dictionary """ url = self._url + "/areasAndLengths" params = { "f" : "json", "lengthUnit" : lengthUnit, "areaUnit" : {"areaUnit" : areaUnit}, "calculationType" : calculationType } if isinstance(polygons, list) and len(polygons) > 0: p = polygons[0] if isinstance(p, Polygon): params['sr'] = p.spatialReference['wkid'] params['polygons'] = [poly.asDictionary for poly in polygons] del p else: return "No polygons provided, please submit a list of polygon geometries" return self._get(url=url, param_dict=params, securityHandler=self._securityHandler, proxy_url=self._proxy_url, proxy_port=self._proxy_port)
python
def areasAndLengths(self, polygons, lengthUnit, areaUnit, calculationType, ): """ The areasAndLengths operation is performed on a geometry service resource. This operation calculates areas and perimeter lengths for each polygon specified in the input array. Inputs: polygons - The array of polygons whose areas and lengths are to be computed. lengthUnit - The length unit in which the perimeters of polygons will be calculated. If calculationType is planar, then lengthUnit can be any esriUnits constant. If lengthUnit is not specified, the units are derived from sr. If calculationType is not planar, then lengthUnit must be a linear esriUnits constant, such as esriSRUnit_Meter or esriSRUnit_SurveyMile. If lengthUnit is not specified, the units are meters. For a list of valid units, see esriSRUnitType Constants and esriSRUnit2Type Constant. areaUnit - The area unit in which areas of polygons will be calculated. If calculationType is planar, then areaUnit can be any esriUnits constant. If areaUnit is not specified, the units are derived from sr. If calculationType is not planar, then areaUnit must be a linear esriUnits constant such as esriSRUnit_Meter or esriSRUnit_SurveyMile. If areaUnit is not specified, then the units are meters. For a list of valid units, see esriSRUnitType Constants and esriSRUnit2Type constant. The list of valid esriAreaUnits constants include, esriSquareInches | esriSquareFeet | esriSquareYards | esriAcres | esriSquareMiles | esriSquareMillimeters | esriSquareCentimeters | esriSquareDecimeters | esriSquareMeters | esriAres | esriHectares | esriSquareKilometers. calculationType - The type defined for the area and length calculation of the input geometries. The type can be one of the following values: planar - Planar measurements use 2D Euclidean distance to calculate area and length. Th- should only be used if the area or length needs to be calculated in the given spatial reference. Otherwise, use preserveShape. geodesic - Use this type if you want to calculate an area or length using only the vertices of the polygon and define the lines between the points as geodesic segments independent of the actual shape of the polygon. A geodesic segment is the shortest path between two points on an ellipsoid. preserveShape - This type calculates the area or length of the geometry on the surface of the Earth ellipsoid. The shape of the geometry in its coordinate system is preserved. Output: JSON as dictionary """ url = self._url + "/areasAndLengths" params = { "f" : "json", "lengthUnit" : lengthUnit, "areaUnit" : {"areaUnit" : areaUnit}, "calculationType" : calculationType } if isinstance(polygons, list) and len(polygons) > 0: p = polygons[0] if isinstance(p, Polygon): params['sr'] = p.spatialReference['wkid'] params['polygons'] = [poly.asDictionary for poly in polygons] del p else: return "No polygons provided, please submit a list of polygon geometries" return self._get(url=url, param_dict=params, securityHandler=self._securityHandler, proxy_url=self._proxy_url, proxy_port=self._proxy_port)
[ "def", "areasAndLengths", "(", "self", ",", "polygons", ",", "lengthUnit", ",", "areaUnit", ",", "calculationType", ",", ")", ":", "url", "=", "self", ".", "_url", "+", "\"/areasAndLengths\"", "params", "=", "{", "\"f\"", ":", "\"json\"", ",", "\"lengthUnit\"", ":", "lengthUnit", ",", "\"areaUnit\"", ":", "{", "\"areaUnit\"", ":", "areaUnit", "}", ",", "\"calculationType\"", ":", "calculationType", "}", "if", "isinstance", "(", "polygons", ",", "list", ")", "and", "len", "(", "polygons", ")", ">", "0", ":", "p", "=", "polygons", "[", "0", "]", "if", "isinstance", "(", "p", ",", "Polygon", ")", ":", "params", "[", "'sr'", "]", "=", "p", ".", "spatialReference", "[", "'wkid'", "]", "params", "[", "'polygons'", "]", "=", "[", "poly", ".", "asDictionary", "for", "poly", "in", "polygons", "]", "del", "p", "else", ":", "return", "\"No polygons provided, please submit a list of polygon geometries\"", "return", "self", ".", "_get", "(", "url", "=", "url", ",", "param_dict", "=", "params", ",", "securityHandler", "=", "self", ".", "_securityHandler", ",", "proxy_url", "=", "self", ".", "_proxy_url", ",", "proxy_port", "=", "self", ".", "_proxy_port", ")" ]
The areasAndLengths operation is performed on a geometry service resource. This operation calculates areas and perimeter lengths for each polygon specified in the input array. Inputs: polygons - The array of polygons whose areas and lengths are to be computed. lengthUnit - The length unit in which the perimeters of polygons will be calculated. If calculationType is planar, then lengthUnit can be any esriUnits constant. If lengthUnit is not specified, the units are derived from sr. If calculationType is not planar, then lengthUnit must be a linear esriUnits constant, such as esriSRUnit_Meter or esriSRUnit_SurveyMile. If lengthUnit is not specified, the units are meters. For a list of valid units, see esriSRUnitType Constants and esriSRUnit2Type Constant. areaUnit - The area unit in which areas of polygons will be calculated. If calculationType is planar, then areaUnit can be any esriUnits constant. If areaUnit is not specified, the units are derived from sr. If calculationType is not planar, then areaUnit must be a linear esriUnits constant such as esriSRUnit_Meter or esriSRUnit_SurveyMile. If areaUnit is not specified, then the units are meters. For a list of valid units, see esriSRUnitType Constants and esriSRUnit2Type constant. The list of valid esriAreaUnits constants include, esriSquareInches | esriSquareFeet | esriSquareYards | esriAcres | esriSquareMiles | esriSquareMillimeters | esriSquareCentimeters | esriSquareDecimeters | esriSquareMeters | esriAres | esriHectares | esriSquareKilometers. calculationType - The type defined for the area and length calculation of the input geometries. The type can be one of the following values: planar - Planar measurements use 2D Euclidean distance to calculate area and length. Th- should only be used if the area or length needs to be calculated in the given spatial reference. Otherwise, use preserveShape. geodesic - Use this type if you want to calculate an area or length using only the vertices of the polygon and define the lines between the points as geodesic segments independent of the actual shape of the polygon. A geodesic segment is the shortest path between two points on an ellipsoid. preserveShape - This type calculates the area or length of the geometry on the surface of the Earth ellipsoid. The shape of the geometry in its coordinate system is preserved. Output: JSON as dictionary
[ "The", "areasAndLengths", "operation", "is", "performed", "on", "a", "geometry", "service", "resource", ".", "This", "operation", "calculates", "areas", "and", "perimeter", "lengths", "for", "each", "polygon", "specified", "in", "the", "input", "array", "." ]
ab240fde2b0200f61d4a5f6df033516e53f2f416
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/geometryservice/geometryservice.py#L58-L146
train
Esri/ArcREST
src/arcrest/geometryservice/geometryservice.py
GeometryService.__geometryToGeomTemplate
def __geometryToGeomTemplate(self, geometry): """ Converts a single geometry object to a geometry service geometry template value. Input: geometry - ArcREST geometry object Output: python dictionary of geometry template """ template = {"geometryType": None, "geometry" : None} if isinstance(geometry, Polyline): template['geometryType'] = "esriGeometryPolyline" elif isinstance(geometry, Polygon): template['geometryType'] = "esriGeometryPolygon" elif isinstance(geometry, Point): template['geometryType'] = "esriGeometryPoint" elif isinstance(geometry, MultiPoint): template['geometryType'] = "esriGeometryMultipoint" elif isinstance(geometry, Envelope): template['geometryType'] = "esriGeometryEnvelope" else: raise AttributeError("Invalid geometry type") template['geometry'] = geometry.asDictionary return template
python
def __geometryToGeomTemplate(self, geometry): """ Converts a single geometry object to a geometry service geometry template value. Input: geometry - ArcREST geometry object Output: python dictionary of geometry template """ template = {"geometryType": None, "geometry" : None} if isinstance(geometry, Polyline): template['geometryType'] = "esriGeometryPolyline" elif isinstance(geometry, Polygon): template['geometryType'] = "esriGeometryPolygon" elif isinstance(geometry, Point): template['geometryType'] = "esriGeometryPoint" elif isinstance(geometry, MultiPoint): template['geometryType'] = "esriGeometryMultipoint" elif isinstance(geometry, Envelope): template['geometryType'] = "esriGeometryEnvelope" else: raise AttributeError("Invalid geometry type") template['geometry'] = geometry.asDictionary return template
[ "def", "__geometryToGeomTemplate", "(", "self", ",", "geometry", ")", ":", "template", "=", "{", "\"geometryType\"", ":", "None", ",", "\"geometry\"", ":", "None", "}", "if", "isinstance", "(", "geometry", ",", "Polyline", ")", ":", "template", "[", "'geometryType'", "]", "=", "\"esriGeometryPolyline\"", "elif", "isinstance", "(", "geometry", ",", "Polygon", ")", ":", "template", "[", "'geometryType'", "]", "=", "\"esriGeometryPolygon\"", "elif", "isinstance", "(", "geometry", ",", "Point", ")", ":", "template", "[", "'geometryType'", "]", "=", "\"esriGeometryPoint\"", "elif", "isinstance", "(", "geometry", ",", "MultiPoint", ")", ":", "template", "[", "'geometryType'", "]", "=", "\"esriGeometryMultipoint\"", "elif", "isinstance", "(", "geometry", ",", "Envelope", ")", ":", "template", "[", "'geometryType'", "]", "=", "\"esriGeometryEnvelope\"", "else", ":", "raise", "AttributeError", "(", "\"Invalid geometry type\"", ")", "template", "[", "'geometry'", "]", "=", "geometry", ".", "asDictionary", "return", "template" ]
Converts a single geometry object to a geometry service geometry template value. Input: geometry - ArcREST geometry object Output: python dictionary of geometry template
[ "Converts", "a", "single", "geometry", "object", "to", "a", "geometry", "service", "geometry", "template", "value", "." ]
ab240fde2b0200f61d4a5f6df033516e53f2f416
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/geometryservice/geometryservice.py#L178-L203
train
Esri/ArcREST
src/arcrest/geometryservice/geometryservice.py
GeometryService.__geomToStringArray
def __geomToStringArray(self, geometries, returnType="str"): """ function to convert the geomtries to strings """ listGeoms = [] for g in geometries: if isinstance(g, Point): listGeoms.append(g.asDictionary) elif isinstance(g, Polygon): listGeoms.append(g.asDictionary) #json.dumps( elif isinstance(g, Polyline): listGeoms.append({'paths' : g.asDictionary['paths']}) if returnType == "str": return json.dumps(listGeoms) elif returnType == "list": return listGeoms else: return json.dumps(listGeoms)
python
def __geomToStringArray(self, geometries, returnType="str"): """ function to convert the geomtries to strings """ listGeoms = [] for g in geometries: if isinstance(g, Point): listGeoms.append(g.asDictionary) elif isinstance(g, Polygon): listGeoms.append(g.asDictionary) #json.dumps( elif isinstance(g, Polyline): listGeoms.append({'paths' : g.asDictionary['paths']}) if returnType == "str": return json.dumps(listGeoms) elif returnType == "list": return listGeoms else: return json.dumps(listGeoms)
[ "def", "__geomToStringArray", "(", "self", ",", "geometries", ",", "returnType", "=", "\"str\"", ")", ":", "listGeoms", "=", "[", "]", "for", "g", "in", "geometries", ":", "if", "isinstance", "(", "g", ",", "Point", ")", ":", "listGeoms", ".", "append", "(", "g", ".", "asDictionary", ")", "elif", "isinstance", "(", "g", ",", "Polygon", ")", ":", "listGeoms", ".", "append", "(", "g", ".", "asDictionary", ")", "#json.dumps(", "elif", "isinstance", "(", "g", ",", "Polyline", ")", ":", "listGeoms", ".", "append", "(", "{", "'paths'", ":", "g", ".", "asDictionary", "[", "'paths'", "]", "}", ")", "if", "returnType", "==", "\"str\"", ":", "return", "json", ".", "dumps", "(", "listGeoms", ")", "elif", "returnType", "==", "\"list\"", ":", "return", "listGeoms", "else", ":", "return", "json", ".", "dumps", "(", "listGeoms", ")" ]
function to convert the geomtries to strings
[ "function", "to", "convert", "the", "geomtries", "to", "strings" ]
ab240fde2b0200f61d4a5f6df033516e53f2f416
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/geometryservice/geometryservice.py#L205-L220
train
Esri/ArcREST
src/arcrest/geometryservice/geometryservice.py
GeometryService.autoComplete
def autoComplete(self, polygons=[], polylines=[], sr=None ): """ The autoComplete operation simplifies the process of constructing new polygons that are adjacent to other polygons. It constructs polygons that fill in the gaps between existing polygons and a set of polylines. Inputs: polygons - array of Polygon objects. polylines - list of Polyline objects. sr - spatial reference of the input geometries WKID. """ url = self._url + "/autoComplete" params = {"f":"json"} if sr is not None: params['sr'] = sr params['polygons'] = self.__geomToStringArray(polygons) params['polylines'] = self.__geomToStringArray(polylines) return self._get(url, param_dict=params, securityHandler=self._securityHandler, proxy_url=self._proxy_url, proxy_port=self._proxy_port)
python
def autoComplete(self, polygons=[], polylines=[], sr=None ): """ The autoComplete operation simplifies the process of constructing new polygons that are adjacent to other polygons. It constructs polygons that fill in the gaps between existing polygons and a set of polylines. Inputs: polygons - array of Polygon objects. polylines - list of Polyline objects. sr - spatial reference of the input geometries WKID. """ url = self._url + "/autoComplete" params = {"f":"json"} if sr is not None: params['sr'] = sr params['polygons'] = self.__geomToStringArray(polygons) params['polylines'] = self.__geomToStringArray(polylines) return self._get(url, param_dict=params, securityHandler=self._securityHandler, proxy_url=self._proxy_url, proxy_port=self._proxy_port)
[ "def", "autoComplete", "(", "self", ",", "polygons", "=", "[", "]", ",", "polylines", "=", "[", "]", ",", "sr", "=", "None", ")", ":", "url", "=", "self", ".", "_url", "+", "\"/autoComplete\"", "params", "=", "{", "\"f\"", ":", "\"json\"", "}", "if", "sr", "is", "not", "None", ":", "params", "[", "'sr'", "]", "=", "sr", "params", "[", "'polygons'", "]", "=", "self", ".", "__geomToStringArray", "(", "polygons", ")", "params", "[", "'polylines'", "]", "=", "self", ".", "__geomToStringArray", "(", "polylines", ")", "return", "self", ".", "_get", "(", "url", ",", "param_dict", "=", "params", ",", "securityHandler", "=", "self", ".", "_securityHandler", ",", "proxy_url", "=", "self", ".", "_proxy_url", ",", "proxy_port", "=", "self", ".", "_proxy_port", ")" ]
The autoComplete operation simplifies the process of constructing new polygons that are adjacent to other polygons. It constructs polygons that fill in the gaps between existing polygons and a set of polylines. Inputs: polygons - array of Polygon objects. polylines - list of Polyline objects. sr - spatial reference of the input geometries WKID.
[ "The", "autoComplete", "operation", "simplifies", "the", "process", "of", "constructing", "new", "polygons", "that", "are", "adjacent", "to", "other", "polygons", ".", "It", "constructs", "polygons", "that", "fill", "in", "the", "gaps", "between", "existing", "polygons", "and", "a", "set", "of", "polylines", "." ]
ab240fde2b0200f61d4a5f6df033516e53f2f416
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/geometryservice/geometryservice.py#L222-L247
train
Esri/ArcREST
src/arcrest/geometryservice/geometryservice.py
GeometryService.buffer
def buffer(self, geometries, inSR, distances, units, outSR=None, bufferSR=None, unionResults=True, geodesic=True ): """ The buffer operation is performed on a geometry service resource The result of this operation is buffered polygons at the specified distances for the input geometry array. Options are available to union buffers and to use geodesic distance. Inputs: geometries - array of geometries (structured as JSON geometry objects returned by the ArcGIS REST API). inSR - spatial reference of the input geometries WKID. outSR - spatial reference for the returned geometries. bufferSR - WKID or a spatial reference JSON object in which the geometries are buffered. distances - distances that each of the input geometries is buffered unit - units for calculating each buffer distance. unionResults - if true, all geometries buffered at a given distance are unioned into a single (possibly multipart) polygon, and the unioned geometry is placed in the output array. geodesic - set geodesic to true to buffer the using geodesic distance. """ url = self._url + "/buffer" params = { "f" : "json", "inSR" : inSR, "geodesic" : geodesic, "unionResults" : unionResults } if isinstance(geometries, list) and len(geometries) > 0: g = geometries[0] if isinstance(g, Polygon): params['geometries'] = {"geometryType": "esriGeometryPolygon", "geometries" : self.__geomToStringArray(geometries, "list")} elif isinstance(g, Point): params['geometries'] = {"geometryType": "esriGeometryPoint", "geometries" : self.__geomToStringArray(geometries, "list")} elif isinstance(g, Polyline): params['geometries'] = {"geometryType": "esriGeometryPolyline", "geometries" : self.__geomToStringArray(geometries, "list")} else: return None if isinstance(distances, list): distances = [str(d) for d in distances] params['distances'] = ",".join(distances) else: params['distances'] = str(distances) params['units'] = units if bufferSR is not None: params['bufferSR'] = bufferSR if outSR is not None: params['outSR'] = outSR return self._get(url, param_dict=params, proxy_port=self._proxy_port, securityHandler=self._securityHandler, proxy_url=self._proxy_url)
python
def buffer(self, geometries, inSR, distances, units, outSR=None, bufferSR=None, unionResults=True, geodesic=True ): """ The buffer operation is performed on a geometry service resource The result of this operation is buffered polygons at the specified distances for the input geometry array. Options are available to union buffers and to use geodesic distance. Inputs: geometries - array of geometries (structured as JSON geometry objects returned by the ArcGIS REST API). inSR - spatial reference of the input geometries WKID. outSR - spatial reference for the returned geometries. bufferSR - WKID or a spatial reference JSON object in which the geometries are buffered. distances - distances that each of the input geometries is buffered unit - units for calculating each buffer distance. unionResults - if true, all geometries buffered at a given distance are unioned into a single (possibly multipart) polygon, and the unioned geometry is placed in the output array. geodesic - set geodesic to true to buffer the using geodesic distance. """ url = self._url + "/buffer" params = { "f" : "json", "inSR" : inSR, "geodesic" : geodesic, "unionResults" : unionResults } if isinstance(geometries, list) and len(geometries) > 0: g = geometries[0] if isinstance(g, Polygon): params['geometries'] = {"geometryType": "esriGeometryPolygon", "geometries" : self.__geomToStringArray(geometries, "list")} elif isinstance(g, Point): params['geometries'] = {"geometryType": "esriGeometryPoint", "geometries" : self.__geomToStringArray(geometries, "list")} elif isinstance(g, Polyline): params['geometries'] = {"geometryType": "esriGeometryPolyline", "geometries" : self.__geomToStringArray(geometries, "list")} else: return None if isinstance(distances, list): distances = [str(d) for d in distances] params['distances'] = ",".join(distances) else: params['distances'] = str(distances) params['units'] = units if bufferSR is not None: params['bufferSR'] = bufferSR if outSR is not None: params['outSR'] = outSR return self._get(url, param_dict=params, proxy_port=self._proxy_port, securityHandler=self._securityHandler, proxy_url=self._proxy_url)
[ "def", "buffer", "(", "self", ",", "geometries", ",", "inSR", ",", "distances", ",", "units", ",", "outSR", "=", "None", ",", "bufferSR", "=", "None", ",", "unionResults", "=", "True", ",", "geodesic", "=", "True", ")", ":", "url", "=", "self", ".", "_url", "+", "\"/buffer\"", "params", "=", "{", "\"f\"", ":", "\"json\"", ",", "\"inSR\"", ":", "inSR", ",", "\"geodesic\"", ":", "geodesic", ",", "\"unionResults\"", ":", "unionResults", "}", "if", "isinstance", "(", "geometries", ",", "list", ")", "and", "len", "(", "geometries", ")", ">", "0", ":", "g", "=", "geometries", "[", "0", "]", "if", "isinstance", "(", "g", ",", "Polygon", ")", ":", "params", "[", "'geometries'", "]", "=", "{", "\"geometryType\"", ":", "\"esriGeometryPolygon\"", ",", "\"geometries\"", ":", "self", ".", "__geomToStringArray", "(", "geometries", ",", "\"list\"", ")", "}", "elif", "isinstance", "(", "g", ",", "Point", ")", ":", "params", "[", "'geometries'", "]", "=", "{", "\"geometryType\"", ":", "\"esriGeometryPoint\"", ",", "\"geometries\"", ":", "self", ".", "__geomToStringArray", "(", "geometries", ",", "\"list\"", ")", "}", "elif", "isinstance", "(", "g", ",", "Polyline", ")", ":", "params", "[", "'geometries'", "]", "=", "{", "\"geometryType\"", ":", "\"esriGeometryPolyline\"", ",", "\"geometries\"", ":", "self", ".", "__geomToStringArray", "(", "geometries", ",", "\"list\"", ")", "}", "else", ":", "return", "None", "if", "isinstance", "(", "distances", ",", "list", ")", ":", "distances", "=", "[", "str", "(", "d", ")", "for", "d", "in", "distances", "]", "params", "[", "'distances'", "]", "=", "\",\"", ".", "join", "(", "distances", ")", "else", ":", "params", "[", "'distances'", "]", "=", "str", "(", "distances", ")", "params", "[", "'units'", "]", "=", "units", "if", "bufferSR", "is", "not", "None", ":", "params", "[", "'bufferSR'", "]", "=", "bufferSR", "if", "outSR", "is", "not", "None", ":", "params", "[", "'outSR'", "]", "=", "outSR", "return", "self", ".", "_get", "(", "url", ",", "param_dict", "=", "params", ",", "proxy_port", "=", "self", ".", "_proxy_port", ",", "securityHandler", "=", "self", ".", "_securityHandler", ",", "proxy_url", "=", "self", ".", "_proxy_url", ")" ]
The buffer operation is performed on a geometry service resource The result of this operation is buffered polygons at the specified distances for the input geometry array. Options are available to union buffers and to use geodesic distance. Inputs: geometries - array of geometries (structured as JSON geometry objects returned by the ArcGIS REST API). inSR - spatial reference of the input geometries WKID. outSR - spatial reference for the returned geometries. bufferSR - WKID or a spatial reference JSON object in which the geometries are buffered. distances - distances that each of the input geometries is buffered unit - units for calculating each buffer distance. unionResults - if true, all geometries buffered at a given distance are unioned into a single (possibly multipart) polygon, and the unioned geometry is placed in the output array. geodesic - set geodesic to true to buffer the using geodesic distance.
[ "The", "buffer", "operation", "is", "performed", "on", "a", "geometry", "service", "resource", "The", "result", "of", "this", "operation", "is", "buffered", "polygons", "at", "the", "specified", "distances", "for", "the", "input", "geometry", "array", ".", "Options", "are", "available", "to", "union", "buffers", "and", "to", "use", "geodesic", "distance", "." ]
ab240fde2b0200f61d4a5f6df033516e53f2f416
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/geometryservice/geometryservice.py#L249-L313
train
Esri/ArcREST
src/arcrest/geometryservice/geometryservice.py
GeometryService.findTransformation
def findTransformation(self, inSR, outSR, extentOfInterest=None, numOfResults=1): """ The findTransformations operation is performed on a geometry service resource. This operation returns a list of applicable geographic transformations you should use when projecting geometries from the input spatial reference to the output spatial reference. The transformations are in JSON format and are returned in order of most applicable to least applicable. Recall that a geographic transformation is not needed when the input and output spatial references have the same underlying geographic coordinate systems. In this case, findTransformations returns an empty list. Every returned geographic transformation is a forward transformation meaning that it can be used as-is to project from the input spatial reference to the output spatial reference. In the case where a predefined transformation needs to be applied in the reverse direction, it is returned as a forward composite transformation containing one transformation and a transformForward element with a value of false. Inputs: inSR - The well-known ID (WKID) of the spatial reference or a spatial reference JSON object for the input geometries outSR - The well-known ID (WKID) of the spatial reference or a spatial reference JSON object for the input geometries extentOfInterest - The bounding box of the area of interest specified as a JSON envelope. If provided, the extent of interest is used to return the most applicable geographic transformations for the area. If a spatial reference is not included in the JSON envelope, the inSR is used for the envelope. numOfResults - The number of geographic transformations to return. The default value is 1. If numOfResults has a value of -1, all applicable transformations are returned. """ params = { "f" : "json", "inSR" : inSR, "outSR" : outSR } url = self._url + "/findTransformations" if isinstance(numOfResults, int): params['numOfResults'] = numOfResults if isinstance(extentOfInterest, Envelope): params['extentOfInterest'] = extentOfInterest.asDictionary return self._post(url=url, param_dict=params, securityHandler=self._securityHandler, proxy_url=self._proxy_url, proxy_port=self._proxy_port)
python
def findTransformation(self, inSR, outSR, extentOfInterest=None, numOfResults=1): """ The findTransformations operation is performed on a geometry service resource. This operation returns a list of applicable geographic transformations you should use when projecting geometries from the input spatial reference to the output spatial reference. The transformations are in JSON format and are returned in order of most applicable to least applicable. Recall that a geographic transformation is not needed when the input and output spatial references have the same underlying geographic coordinate systems. In this case, findTransformations returns an empty list. Every returned geographic transformation is a forward transformation meaning that it can be used as-is to project from the input spatial reference to the output spatial reference. In the case where a predefined transformation needs to be applied in the reverse direction, it is returned as a forward composite transformation containing one transformation and a transformForward element with a value of false. Inputs: inSR - The well-known ID (WKID) of the spatial reference or a spatial reference JSON object for the input geometries outSR - The well-known ID (WKID) of the spatial reference or a spatial reference JSON object for the input geometries extentOfInterest - The bounding box of the area of interest specified as a JSON envelope. If provided, the extent of interest is used to return the most applicable geographic transformations for the area. If a spatial reference is not included in the JSON envelope, the inSR is used for the envelope. numOfResults - The number of geographic transformations to return. The default value is 1. If numOfResults has a value of -1, all applicable transformations are returned. """ params = { "f" : "json", "inSR" : inSR, "outSR" : outSR } url = self._url + "/findTransformations" if isinstance(numOfResults, int): params['numOfResults'] = numOfResults if isinstance(extentOfInterest, Envelope): params['extentOfInterest'] = extentOfInterest.asDictionary return self._post(url=url, param_dict=params, securityHandler=self._securityHandler, proxy_url=self._proxy_url, proxy_port=self._proxy_port)
[ "def", "findTransformation", "(", "self", ",", "inSR", ",", "outSR", ",", "extentOfInterest", "=", "None", ",", "numOfResults", "=", "1", ")", ":", "params", "=", "{", "\"f\"", ":", "\"json\"", ",", "\"inSR\"", ":", "inSR", ",", "\"outSR\"", ":", "outSR", "}", "url", "=", "self", ".", "_url", "+", "\"/findTransformations\"", "if", "isinstance", "(", "numOfResults", ",", "int", ")", ":", "params", "[", "'numOfResults'", "]", "=", "numOfResults", "if", "isinstance", "(", "extentOfInterest", ",", "Envelope", ")", ":", "params", "[", "'extentOfInterest'", "]", "=", "extentOfInterest", ".", "asDictionary", "return", "self", ".", "_post", "(", "url", "=", "url", ",", "param_dict", "=", "params", ",", "securityHandler", "=", "self", ".", "_securityHandler", ",", "proxy_url", "=", "self", ".", "_proxy_url", ",", "proxy_port", "=", "self", ".", "_proxy_port", ")" ]
The findTransformations operation is performed on a geometry service resource. This operation returns a list of applicable geographic transformations you should use when projecting geometries from the input spatial reference to the output spatial reference. The transformations are in JSON format and are returned in order of most applicable to least applicable. Recall that a geographic transformation is not needed when the input and output spatial references have the same underlying geographic coordinate systems. In this case, findTransformations returns an empty list. Every returned geographic transformation is a forward transformation meaning that it can be used as-is to project from the input spatial reference to the output spatial reference. In the case where a predefined transformation needs to be applied in the reverse direction, it is returned as a forward composite transformation containing one transformation and a transformForward element with a value of false. Inputs: inSR - The well-known ID (WKID) of the spatial reference or a spatial reference JSON object for the input geometries outSR - The well-known ID (WKID) of the spatial reference or a spatial reference JSON object for the input geometries extentOfInterest - The bounding box of the area of interest specified as a JSON envelope. If provided, the extent of interest is used to return the most applicable geographic transformations for the area. If a spatial reference is not included in the JSON envelope, the inSR is used for the envelope. numOfResults - The number of geographic transformations to return. The default value is 1. If numOfResults has a value of -1, all applicable transformations are returned.
[ "The", "findTransformations", "operation", "is", "performed", "on", "a", "geometry", "service", "resource", ".", "This", "operation", "returns", "a", "list", "of", "applicable", "geographic", "transformations", "you", "should", "use", "when", "projecting", "geometries", "from", "the", "input", "spatial", "reference", "to", "the", "output", "spatial", "reference", ".", "The", "transformations", "are", "in", "JSON", "format", "and", "are", "returned", "in", "order", "of", "most", "applicable", "to", "least", "applicable", ".", "Recall", "that", "a", "geographic", "transformation", "is", "not", "needed", "when", "the", "input", "and", "output", "spatial", "references", "have", "the", "same", "underlying", "geographic", "coordinate", "systems", ".", "In", "this", "case", "findTransformations", "returns", "an", "empty", "list", ".", "Every", "returned", "geographic", "transformation", "is", "a", "forward", "transformation", "meaning", "that", "it", "can", "be", "used", "as", "-", "is", "to", "project", "from", "the", "input", "spatial", "reference", "to", "the", "output", "spatial", "reference", ".", "In", "the", "case", "where", "a", "predefined", "transformation", "needs", "to", "be", "applied", "in", "the", "reverse", "direction", "it", "is", "returned", "as", "a", "forward", "composite", "transformation", "containing", "one", "transformation", "and", "a", "transformForward", "element", "with", "a", "value", "of", "false", "." ]
ab240fde2b0200f61d4a5f6df033516e53f2f416
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/geometryservice/geometryservice.py#L551-L598
train
Esri/ArcREST
src/arcrest/geometryservice/geometryservice.py
GeometryService.fromGeoCoordinateString
def fromGeoCoordinateString(self, sr, strings, conversionType, conversionMode=None): """ The fromGeoCoordinateString operation is performed on a geometry service resource. The operation converts an array of well-known strings into xy-coordinates based on the conversion type and spatial reference supplied by the user. An optional conversion mode parameter is available for some conversion types. Inputs: sr - The well-known ID of the spatial reference or a spatial reference json object. strings - An array of strings formatted as specified by conversionType. Syntax: [<string1>,...,<stringN>] Example: ["01N AA 66021 00000","11S NT 00000 62155", "31U BT 94071 65288"] conversionType - The conversion type of the input strings. Valid conversion types are: MGRS - Military Grid Reference System USNG - United States National Grid UTM - Universal Transverse Mercator GeoRef - World Geographic Reference System GARS - Global Area Reference System DMS - Degree Minute Second DDM - Degree Decimal Minute DD - Decimal Degree conversionMode - Conversion options for MGRS, UTM and GARS conversion types. Conversion options for MGRS and UTM conversion types. Valid conversion modes for MGRS are: mgrsDefault - Default. Uses the spheroid from the given spatial reference. mgrsNewStyle - Treats all spheroids as new, like WGS 1984. The 180 degree longitude falls into Zone 60. mgrsOldStyle - Treats all spheroids as old, like Bessel 1841. The 180 degree longitude falls into Zone 60. mgrsNewWith180InZone01 - Same as mgrsNewStyle except the 180 degree longitude falls into Zone 01. mgrsOldWith180InZone01 - Same as mgrsOldStyle except the 180 degree longitude falls into Zone 01. Valid conversion modes for UTM are: utmDefault - Default. No options. utmNorthSouth - Uses north/south latitude indicators instead of zone numbers. Non-standard. Default is recommended """ url = self._url + "/fromGeoCoordinateString" params = { "f" : "json", "sr" : sr, "strings" : strings, "conversionType" : conversionType } if not conversionMode is None: params['conversionMode'] = conversionMode return self._post(url=url, param_dict=params, securityHandler=self._securityHandler, proxy_url=self._proxy_url, proxy_port=self._proxy_port)
python
def fromGeoCoordinateString(self, sr, strings, conversionType, conversionMode=None): """ The fromGeoCoordinateString operation is performed on a geometry service resource. The operation converts an array of well-known strings into xy-coordinates based on the conversion type and spatial reference supplied by the user. An optional conversion mode parameter is available for some conversion types. Inputs: sr - The well-known ID of the spatial reference or a spatial reference json object. strings - An array of strings formatted as specified by conversionType. Syntax: [<string1>,...,<stringN>] Example: ["01N AA 66021 00000","11S NT 00000 62155", "31U BT 94071 65288"] conversionType - The conversion type of the input strings. Valid conversion types are: MGRS - Military Grid Reference System USNG - United States National Grid UTM - Universal Transverse Mercator GeoRef - World Geographic Reference System GARS - Global Area Reference System DMS - Degree Minute Second DDM - Degree Decimal Minute DD - Decimal Degree conversionMode - Conversion options for MGRS, UTM and GARS conversion types. Conversion options for MGRS and UTM conversion types. Valid conversion modes for MGRS are: mgrsDefault - Default. Uses the spheroid from the given spatial reference. mgrsNewStyle - Treats all spheroids as new, like WGS 1984. The 180 degree longitude falls into Zone 60. mgrsOldStyle - Treats all spheroids as old, like Bessel 1841. The 180 degree longitude falls into Zone 60. mgrsNewWith180InZone01 - Same as mgrsNewStyle except the 180 degree longitude falls into Zone 01. mgrsOldWith180InZone01 - Same as mgrsOldStyle except the 180 degree longitude falls into Zone 01. Valid conversion modes for UTM are: utmDefault - Default. No options. utmNorthSouth - Uses north/south latitude indicators instead of zone numbers. Non-standard. Default is recommended """ url = self._url + "/fromGeoCoordinateString" params = { "f" : "json", "sr" : sr, "strings" : strings, "conversionType" : conversionType } if not conversionMode is None: params['conversionMode'] = conversionMode return self._post(url=url, param_dict=params, securityHandler=self._securityHandler, proxy_url=self._proxy_url, proxy_port=self._proxy_port)
[ "def", "fromGeoCoordinateString", "(", "self", ",", "sr", ",", "strings", ",", "conversionType", ",", "conversionMode", "=", "None", ")", ":", "url", "=", "self", ".", "_url", "+", "\"/fromGeoCoordinateString\"", "params", "=", "{", "\"f\"", ":", "\"json\"", ",", "\"sr\"", ":", "sr", ",", "\"strings\"", ":", "strings", ",", "\"conversionType\"", ":", "conversionType", "}", "if", "not", "conversionMode", "is", "None", ":", "params", "[", "'conversionMode'", "]", "=", "conversionMode", "return", "self", ".", "_post", "(", "url", "=", "url", ",", "param_dict", "=", "params", ",", "securityHandler", "=", "self", ".", "_securityHandler", ",", "proxy_url", "=", "self", ".", "_proxy_url", ",", "proxy_port", "=", "self", ".", "_proxy_port", ")" ]
The fromGeoCoordinateString operation is performed on a geometry service resource. The operation converts an array of well-known strings into xy-coordinates based on the conversion type and spatial reference supplied by the user. An optional conversion mode parameter is available for some conversion types. Inputs: sr - The well-known ID of the spatial reference or a spatial reference json object. strings - An array of strings formatted as specified by conversionType. Syntax: [<string1>,...,<stringN>] Example: ["01N AA 66021 00000","11S NT 00000 62155", "31U BT 94071 65288"] conversionType - The conversion type of the input strings. Valid conversion types are: MGRS - Military Grid Reference System USNG - United States National Grid UTM - Universal Transverse Mercator GeoRef - World Geographic Reference System GARS - Global Area Reference System DMS - Degree Minute Second DDM - Degree Decimal Minute DD - Decimal Degree conversionMode - Conversion options for MGRS, UTM and GARS conversion types. Conversion options for MGRS and UTM conversion types. Valid conversion modes for MGRS are: mgrsDefault - Default. Uses the spheroid from the given spatial reference. mgrsNewStyle - Treats all spheroids as new, like WGS 1984. The 180 degree longitude falls into Zone 60. mgrsOldStyle - Treats all spheroids as old, like Bessel 1841. The 180 degree longitude falls into Zone 60. mgrsNewWith180InZone01 - Same as mgrsNewStyle except the 180 degree longitude falls into Zone 01. mgrsOldWith180InZone01 - Same as mgrsOldStyle except the 180 degree longitude falls into Zone 01. Valid conversion modes for UTM are: utmDefault - Default. No options. utmNorthSouth - Uses north/south latitude indicators instead of zone numbers. Non-standard. Default is recommended
[ "The", "fromGeoCoordinateString", "operation", "is", "performed", "on", "a", "geometry", "service", "resource", ".", "The", "operation", "converts", "an", "array", "of", "well", "-", "known", "strings", "into", "xy", "-", "coordinates", "based", "on", "the", "conversion", "type", "and", "spatial", "reference", "supplied", "by", "the", "user", ".", "An", "optional", "conversion", "mode", "parameter", "is", "available", "for", "some", "conversion", "types", "." ]
ab240fde2b0200f61d4a5f6df033516e53f2f416
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/geometryservice/geometryservice.py#L600-L658
train
Esri/ArcREST
src/arcrest/geometryservice/geometryservice.py
GeometryService.toGeoCoordinateString
def toGeoCoordinateString(self, sr, coordinates, conversionType, conversionMode="mgrsDefault", numOfDigits=None, rounding=True, addSpaces=True ): """ The toGeoCoordinateString operation is performed on a geometry service resource. The operation converts an array of xy-coordinates into well-known strings based on the conversion type and spatial reference supplied by the user. Optional parameters are available for some conversion types. Note that if an optional parameter is not applicable for a particular conversion type, but a value is supplied for that parameter, the value will be ignored. Inputs: sr - The well-known ID of the spatial reference or a spatial reference json object. coordinates - An array of xy-coordinates in JSON format to be converted. Syntax: [[x1,y2],...[xN,yN]] conversionType - The conversion type of the input strings. Allowed Values: MGRS - Military Grid Reference System USNG - United States National Grid UTM - Universal Transverse Mercator GeoRef - World Geographic Reference System GARS - Global Area Reference System DMS - Degree Minute Second DDM - Degree Decimal Minute DD - Decimal Degree conversionMode - Conversion options for MGRS and UTM conversion types. Valid conversion modes for MGRS are: mgrsDefault - Default. Uses the spheroid from the given spatial reference. mgrsNewStyle - Treats all spheroids as new, like WGS 1984. The 180 degree longitude falls into Zone 60. mgrsOldStyle - Treats all spheroids as old, like Bessel 1841. The 180 degree longitude falls into Zone 60. mgrsNewWith180InZone01 - Same as mgrsNewStyle except the 180 degree longitude falls into Zone 01. mgrsOldWith180InZone01 - Same as mgrsOldStyle except the 180 degree longitude falls into Zone 01. Valid conversion modes for UTM are: utmDefault - Default. No options. utmNorthSouth - Uses north/south latitude indicators instead of zone numbers. Non-standard. Default is recommended. numOfDigits - The number of digits to output for each of the numerical portions in the string. The default value for numOfDigits varies depending on conversionType. rounding - If true, then numeric portions of the string are rounded to the nearest whole magnitude as specified by numOfDigits. Otherwise, numeric portions of the string are truncated. The rounding parameter applies only to conversion types MGRS, USNG and GeoRef. The default value is true. addSpaces - If true, then spaces are added between components of the string. The addSpaces parameter applies only to conversion types MGRS, USNG and UTM. The default value for MGRS is false, while the default value for both USNG and UTM is true. """ params = { "f": "json", "sr" : sr, "coordinates" : coordinates, "conversionType": conversionType } url = self._url + "/toGeoCoordinateString" if not conversionMode is None: params['conversionMode'] = conversionMode if isinstance(numOfDigits, int): params['numOfDigits'] = numOfDigits if isinstance(rounding, int): params['rounding'] = rounding if isinstance(addSpaces, bool): params['addSpaces'] = addSpaces return self._post(url=url, param_dict=params, proxy_url=self._proxy_url, proxy_port=self._proxy_port, securityHandler=self._securityHandler)
python
def toGeoCoordinateString(self, sr, coordinates, conversionType, conversionMode="mgrsDefault", numOfDigits=None, rounding=True, addSpaces=True ): """ The toGeoCoordinateString operation is performed on a geometry service resource. The operation converts an array of xy-coordinates into well-known strings based on the conversion type and spatial reference supplied by the user. Optional parameters are available for some conversion types. Note that if an optional parameter is not applicable for a particular conversion type, but a value is supplied for that parameter, the value will be ignored. Inputs: sr - The well-known ID of the spatial reference or a spatial reference json object. coordinates - An array of xy-coordinates in JSON format to be converted. Syntax: [[x1,y2],...[xN,yN]] conversionType - The conversion type of the input strings. Allowed Values: MGRS - Military Grid Reference System USNG - United States National Grid UTM - Universal Transverse Mercator GeoRef - World Geographic Reference System GARS - Global Area Reference System DMS - Degree Minute Second DDM - Degree Decimal Minute DD - Decimal Degree conversionMode - Conversion options for MGRS and UTM conversion types. Valid conversion modes for MGRS are: mgrsDefault - Default. Uses the spheroid from the given spatial reference. mgrsNewStyle - Treats all spheroids as new, like WGS 1984. The 180 degree longitude falls into Zone 60. mgrsOldStyle - Treats all spheroids as old, like Bessel 1841. The 180 degree longitude falls into Zone 60. mgrsNewWith180InZone01 - Same as mgrsNewStyle except the 180 degree longitude falls into Zone 01. mgrsOldWith180InZone01 - Same as mgrsOldStyle except the 180 degree longitude falls into Zone 01. Valid conversion modes for UTM are: utmDefault - Default. No options. utmNorthSouth - Uses north/south latitude indicators instead of zone numbers. Non-standard. Default is recommended. numOfDigits - The number of digits to output for each of the numerical portions in the string. The default value for numOfDigits varies depending on conversionType. rounding - If true, then numeric portions of the string are rounded to the nearest whole magnitude as specified by numOfDigits. Otherwise, numeric portions of the string are truncated. The rounding parameter applies only to conversion types MGRS, USNG and GeoRef. The default value is true. addSpaces - If true, then spaces are added between components of the string. The addSpaces parameter applies only to conversion types MGRS, USNG and UTM. The default value for MGRS is false, while the default value for both USNG and UTM is true. """ params = { "f": "json", "sr" : sr, "coordinates" : coordinates, "conversionType": conversionType } url = self._url + "/toGeoCoordinateString" if not conversionMode is None: params['conversionMode'] = conversionMode if isinstance(numOfDigits, int): params['numOfDigits'] = numOfDigits if isinstance(rounding, int): params['rounding'] = rounding if isinstance(addSpaces, bool): params['addSpaces'] = addSpaces return self._post(url=url, param_dict=params, proxy_url=self._proxy_url, proxy_port=self._proxy_port, securityHandler=self._securityHandler)
[ "def", "toGeoCoordinateString", "(", "self", ",", "sr", ",", "coordinates", ",", "conversionType", ",", "conversionMode", "=", "\"mgrsDefault\"", ",", "numOfDigits", "=", "None", ",", "rounding", "=", "True", ",", "addSpaces", "=", "True", ")", ":", "params", "=", "{", "\"f\"", ":", "\"json\"", ",", "\"sr\"", ":", "sr", ",", "\"coordinates\"", ":", "coordinates", ",", "\"conversionType\"", ":", "conversionType", "}", "url", "=", "self", ".", "_url", "+", "\"/toGeoCoordinateString\"", "if", "not", "conversionMode", "is", "None", ":", "params", "[", "'conversionMode'", "]", "=", "conversionMode", "if", "isinstance", "(", "numOfDigits", ",", "int", ")", ":", "params", "[", "'numOfDigits'", "]", "=", "numOfDigits", "if", "isinstance", "(", "rounding", ",", "int", ")", ":", "params", "[", "'rounding'", "]", "=", "rounding", "if", "isinstance", "(", "addSpaces", ",", "bool", ")", ":", "params", "[", "'addSpaces'", "]", "=", "addSpaces", "return", "self", ".", "_post", "(", "url", "=", "url", ",", "param_dict", "=", "params", ",", "proxy_url", "=", "self", ".", "_proxy_url", ",", "proxy_port", "=", "self", ".", "_proxy_port", ",", "securityHandler", "=", "self", ".", "_securityHandler", ")" ]
The toGeoCoordinateString operation is performed on a geometry service resource. The operation converts an array of xy-coordinates into well-known strings based on the conversion type and spatial reference supplied by the user. Optional parameters are available for some conversion types. Note that if an optional parameter is not applicable for a particular conversion type, but a value is supplied for that parameter, the value will be ignored. Inputs: sr - The well-known ID of the spatial reference or a spatial reference json object. coordinates - An array of xy-coordinates in JSON format to be converted. Syntax: [[x1,y2],...[xN,yN]] conversionType - The conversion type of the input strings. Allowed Values: MGRS - Military Grid Reference System USNG - United States National Grid UTM - Universal Transverse Mercator GeoRef - World Geographic Reference System GARS - Global Area Reference System DMS - Degree Minute Second DDM - Degree Decimal Minute DD - Decimal Degree conversionMode - Conversion options for MGRS and UTM conversion types. Valid conversion modes for MGRS are: mgrsDefault - Default. Uses the spheroid from the given spatial reference. mgrsNewStyle - Treats all spheroids as new, like WGS 1984. The 180 degree longitude falls into Zone 60. mgrsOldStyle - Treats all spheroids as old, like Bessel 1841. The 180 degree longitude falls into Zone 60. mgrsNewWith180InZone01 - Same as mgrsNewStyle except the 180 degree longitude falls into Zone 01. mgrsOldWith180InZone01 - Same as mgrsOldStyle except the 180 degree longitude falls into Zone 01. Valid conversion modes for UTM are: utmDefault - Default. No options. utmNorthSouth - Uses north/south latitude indicators instead of zone numbers. Non-standard. Default is recommended. numOfDigits - The number of digits to output for each of the numerical portions in the string. The default value for numOfDigits varies depending on conversionType. rounding - If true, then numeric portions of the string are rounded to the nearest whole magnitude as specified by numOfDigits. Otherwise, numeric portions of the string are truncated. The rounding parameter applies only to conversion types MGRS, USNG and GeoRef. The default value is true. addSpaces - If true, then spaces are added between components of the string. The addSpaces parameter applies only to conversion types MGRS, USNG and UTM. The default value for MGRS is false, while the default value for both USNG and UTM is true.
[ "The", "toGeoCoordinateString", "operation", "is", "performed", "on", "a", "geometry", "service", "resource", ".", "The", "operation", "converts", "an", "array", "of", "xy", "-", "coordinates", "into", "well", "-", "known", "strings", "based", "on", "the", "conversion", "type", "and", "spatial", "reference", "supplied", "by", "the", "user", ".", "Optional", "parameters", "are", "available", "for", "some", "conversion", "types", ".", "Note", "that", "if", "an", "optional", "parameter", "is", "not", "applicable", "for", "a", "particular", "conversion", "type", "but", "a", "value", "is", "supplied", "for", "that", "parameter", "the", "value", "will", "be", "ignored", "." ]
ab240fde2b0200f61d4a5f6df033516e53f2f416
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/geometryservice/geometryservice.py#L985-L1067
train
Esri/ArcREST
src/arcrest/agol/helperservices/hydrology.py
hydrology.__init_url
def __init_url(self): """loads the information into the class""" portals_self_url = "{}/portals/self".format(self._url) params = { "f" :"json" } if not self._securityHandler is None: params['token'] = self._securityHandler.token res = self._get(url=portals_self_url, param_dict=params, securityHandler=self._securityHandler, proxy_url=self._proxy_url, proxy_port=self._proxy_port) if "helperServices" in res: helper_services = res.get("helperServices") if "hydrology" in helper_services: analysis_service = helper_services.get("elevation") if "url" in analysis_service: self._analysis_url = analysis_service.get("url") self._gpService = GPService(url=self._analysis_url, securityHandler=self._securityHandler, proxy_url=self._proxy_url, proxy_port=self._proxy_port, initialize=False)
python
def __init_url(self): """loads the information into the class""" portals_self_url = "{}/portals/self".format(self._url) params = { "f" :"json" } if not self._securityHandler is None: params['token'] = self._securityHandler.token res = self._get(url=portals_self_url, param_dict=params, securityHandler=self._securityHandler, proxy_url=self._proxy_url, proxy_port=self._proxy_port) if "helperServices" in res: helper_services = res.get("helperServices") if "hydrology" in helper_services: analysis_service = helper_services.get("elevation") if "url" in analysis_service: self._analysis_url = analysis_service.get("url") self._gpService = GPService(url=self._analysis_url, securityHandler=self._securityHandler, proxy_url=self._proxy_url, proxy_port=self._proxy_port, initialize=False)
[ "def", "__init_url", "(", "self", ")", ":", "portals_self_url", "=", "\"{}/portals/self\"", ".", "format", "(", "self", ".", "_url", ")", "params", "=", "{", "\"f\"", ":", "\"json\"", "}", "if", "not", "self", ".", "_securityHandler", "is", "None", ":", "params", "[", "'token'", "]", "=", "self", ".", "_securityHandler", ".", "token", "res", "=", "self", ".", "_get", "(", "url", "=", "portals_self_url", ",", "param_dict", "=", "params", ",", "securityHandler", "=", "self", ".", "_securityHandler", ",", "proxy_url", "=", "self", ".", "_proxy_url", ",", "proxy_port", "=", "self", ".", "_proxy_port", ")", "if", "\"helperServices\"", "in", "res", ":", "helper_services", "=", "res", ".", "get", "(", "\"helperServices\"", ")", "if", "\"hydrology\"", "in", "helper_services", ":", "analysis_service", "=", "helper_services", ".", "get", "(", "\"elevation\"", ")", "if", "\"url\"", "in", "analysis_service", ":", "self", ".", "_analysis_url", "=", "analysis_service", ".", "get", "(", "\"url\"", ")", "self", ".", "_gpService", "=", "GPService", "(", "url", "=", "self", ".", "_analysis_url", ",", "securityHandler", "=", "self", ".", "_securityHandler", ",", "proxy_url", "=", "self", ".", "_proxy_url", ",", "proxy_port", "=", "self", ".", "_proxy_port", ",", "initialize", "=", "False", ")" ]
loads the information into the class
[ "loads", "the", "information", "into", "the", "class" ]
ab240fde2b0200f61d4a5f6df033516e53f2f416
https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/src/arcrest/agol/helperservices/hydrology.py#L51-L74
train
bw2/ConfigArgParse
configargparse.py
get_argument_parser
def get_argument_parser(name=None, **kwargs): """Returns the global ArgumentParser instance with the given name. The 1st time this function is called, a new ArgumentParser instance will be created for the given name, and any args other than "name" will be passed on to the ArgumentParser constructor. """ if name is None: name = "default" if len(kwargs) > 0 or name not in _parsers: init_argument_parser(name, **kwargs) return _parsers[name]
python
def get_argument_parser(name=None, **kwargs): """Returns the global ArgumentParser instance with the given name. The 1st time this function is called, a new ArgumentParser instance will be created for the given name, and any args other than "name" will be passed on to the ArgumentParser constructor. """ if name is None: name = "default" if len(kwargs) > 0 or name not in _parsers: init_argument_parser(name, **kwargs) return _parsers[name]
[ "def", "get_argument_parser", "(", "name", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "name", "is", "None", ":", "name", "=", "\"default\"", "if", "len", "(", "kwargs", ")", ">", "0", "or", "name", "not", "in", "_parsers", ":", "init_argument_parser", "(", "name", ",", "*", "*", "kwargs", ")", "return", "_parsers", "[", "name", "]" ]
Returns the global ArgumentParser instance with the given name. The 1st time this function is called, a new ArgumentParser instance will be created for the given name, and any args other than "name" will be passed on to the ArgumentParser constructor.
[ "Returns", "the", "global", "ArgumentParser", "instance", "with", "the", "given", "name", ".", "The", "1st", "time", "this", "function", "is", "called", "a", "new", "ArgumentParser", "instance", "will", "be", "created", "for", "the", "given", "name", "and", "any", "args", "other", "than", "name", "will", "be", "passed", "on", "to", "the", "ArgumentParser", "constructor", "." ]
8bbc7de67f884184068d62af7f78e723d01c0081
https://github.com/bw2/ConfigArgParse/blob/8bbc7de67f884184068d62af7f78e723d01c0081/configargparse.py#L46-L58
train
bw2/ConfigArgParse
configargparse.py
DefaultConfigFileParser.parse
def parse(self, stream): """Parses the keys + values from a config file.""" items = OrderedDict() for i, line in enumerate(stream): line = line.strip() if not line or line[0] in ["#", ";", "["] or line.startswith("---"): continue white_space = "\\s*" key = "(?P<key>[^:=;#\s]+?)" value = white_space+"[:=\s]"+white_space+"(?P<value>.+?)" comment = white_space+"(?P<comment>\\s[;#].*)?" key_only_match = re.match("^" + key + comment + "$", line) if key_only_match: key = key_only_match.group("key") items[key] = "true" continue key_value_match = re.match("^"+key+value+comment+"$", line) if key_value_match: key = key_value_match.group("key") value = key_value_match.group("value") if value.startswith("[") and value.endswith("]"): # handle special case of lists value = [elem.strip() for elem in value[1:-1].split(",")] items[key] = value continue raise ConfigFileParserException("Unexpected line %s in %s: %s" % (i, getattr(stream, 'name', 'stream'), line)) return items
python
def parse(self, stream): """Parses the keys + values from a config file.""" items = OrderedDict() for i, line in enumerate(stream): line = line.strip() if not line or line[0] in ["#", ";", "["] or line.startswith("---"): continue white_space = "\\s*" key = "(?P<key>[^:=;#\s]+?)" value = white_space+"[:=\s]"+white_space+"(?P<value>.+?)" comment = white_space+"(?P<comment>\\s[;#].*)?" key_only_match = re.match("^" + key + comment + "$", line) if key_only_match: key = key_only_match.group("key") items[key] = "true" continue key_value_match = re.match("^"+key+value+comment+"$", line) if key_value_match: key = key_value_match.group("key") value = key_value_match.group("value") if value.startswith("[") and value.endswith("]"): # handle special case of lists value = [elem.strip() for elem in value[1:-1].split(",")] items[key] = value continue raise ConfigFileParserException("Unexpected line %s in %s: %s" % (i, getattr(stream, 'name', 'stream'), line)) return items
[ "def", "parse", "(", "self", ",", "stream", ")", ":", "items", "=", "OrderedDict", "(", ")", "for", "i", ",", "line", "in", "enumerate", "(", "stream", ")", ":", "line", "=", "line", ".", "strip", "(", ")", "if", "not", "line", "or", "line", "[", "0", "]", "in", "[", "\"#\"", ",", "\";\"", ",", "\"[\"", "]", "or", "line", ".", "startswith", "(", "\"---\"", ")", ":", "continue", "white_space", "=", "\"\\\\s*\"", "key", "=", "\"(?P<key>[^:=;#\\s]+?)\"", "value", "=", "white_space", "+", "\"[:=\\s]\"", "+", "white_space", "+", "\"(?P<value>.+?)\"", "comment", "=", "white_space", "+", "\"(?P<comment>\\\\s[;#].*)?\"", "key_only_match", "=", "re", ".", "match", "(", "\"^\"", "+", "key", "+", "comment", "+", "\"$\"", ",", "line", ")", "if", "key_only_match", ":", "key", "=", "key_only_match", ".", "group", "(", "\"key\"", ")", "items", "[", "key", "]", "=", "\"true\"", "continue", "key_value_match", "=", "re", ".", "match", "(", "\"^\"", "+", "key", "+", "value", "+", "comment", "+", "\"$\"", ",", "line", ")", "if", "key_value_match", ":", "key", "=", "key_value_match", ".", "group", "(", "\"key\"", ")", "value", "=", "key_value_match", ".", "group", "(", "\"value\"", ")", "if", "value", ".", "startswith", "(", "\"[\"", ")", "and", "value", ".", "endswith", "(", "\"]\"", ")", ":", "# handle special case of lists", "value", "=", "[", "elem", ".", "strip", "(", ")", "for", "elem", "in", "value", "[", "1", ":", "-", "1", "]", ".", "split", "(", "\",\"", ")", "]", "items", "[", "key", "]", "=", "value", "continue", "raise", "ConfigFileParserException", "(", "\"Unexpected line %s in %s: %s\"", "%", "(", "i", ",", "getattr", "(", "stream", ",", "'name'", ",", "'stream'", ")", ",", "line", ")", ")", "return", "items" ]
Parses the keys + values from a config file.
[ "Parses", "the", "keys", "+", "values", "from", "a", "config", "file", "." ]
8bbc7de67f884184068d62af7f78e723d01c0081
https://github.com/bw2/ConfigArgParse/blob/8bbc7de67f884184068d62af7f78e723d01c0081/configargparse.py#L146-L179
train
bw2/ConfigArgParse
configargparse.py
YAMLConfigFileParser.parse
def parse(self, stream): """Parses the keys and values from a config file.""" yaml = self._load_yaml() try: parsed_obj = yaml.safe_load(stream) except Exception as e: raise ConfigFileParserException("Couldn't parse config file: %s" % e) if not isinstance(parsed_obj, dict): raise ConfigFileParserException("The config file doesn't appear to " "contain 'key: value' pairs (aka. a YAML mapping). " "yaml.load('%s') returned type '%s' instead of 'dict'." % ( getattr(stream, 'name', 'stream'), type(parsed_obj).__name__)) result = OrderedDict() for key, value in parsed_obj.items(): if isinstance(value, list): result[key] = value else: result[key] = str(value) return result
python
def parse(self, stream): """Parses the keys and values from a config file.""" yaml = self._load_yaml() try: parsed_obj = yaml.safe_load(stream) except Exception as e: raise ConfigFileParserException("Couldn't parse config file: %s" % e) if not isinstance(parsed_obj, dict): raise ConfigFileParserException("The config file doesn't appear to " "contain 'key: value' pairs (aka. a YAML mapping). " "yaml.load('%s') returned type '%s' instead of 'dict'." % ( getattr(stream, 'name', 'stream'), type(parsed_obj).__name__)) result = OrderedDict() for key, value in parsed_obj.items(): if isinstance(value, list): result[key] = value else: result[key] = str(value) return result
[ "def", "parse", "(", "self", ",", "stream", ")", ":", "yaml", "=", "self", ".", "_load_yaml", "(", ")", "try", ":", "parsed_obj", "=", "yaml", ".", "safe_load", "(", "stream", ")", "except", "Exception", "as", "e", ":", "raise", "ConfigFileParserException", "(", "\"Couldn't parse config file: %s\"", "%", "e", ")", "if", "not", "isinstance", "(", "parsed_obj", ",", "dict", ")", ":", "raise", "ConfigFileParserException", "(", "\"The config file doesn't appear to \"", "\"contain 'key: value' pairs (aka. a YAML mapping). \"", "\"yaml.load('%s') returned type '%s' instead of 'dict'.\"", "%", "(", "getattr", "(", "stream", ",", "'name'", ",", "'stream'", ")", ",", "type", "(", "parsed_obj", ")", ".", "__name__", ")", ")", "result", "=", "OrderedDict", "(", ")", "for", "key", ",", "value", "in", "parsed_obj", ".", "items", "(", ")", ":", "if", "isinstance", "(", "value", ",", "list", ")", ":", "result", "[", "key", "]", "=", "value", "else", ":", "result", "[", "key", "]", "=", "str", "(", "value", ")", "return", "result" ]
Parses the keys and values from a config file.
[ "Parses", "the", "keys", "and", "values", "from", "a", "config", "file", "." ]
8bbc7de67f884184068d62af7f78e723d01c0081
https://github.com/bw2/ConfigArgParse/blob/8bbc7de67f884184068d62af7f78e723d01c0081/configargparse.py#L215-L237
train
bw2/ConfigArgParse
configargparse.py
ArgumentParser.write_config_file
def write_config_file(self, parsed_namespace, output_file_paths, exit_after=False): """Write the given settings to output files. Args: parsed_namespace: namespace object created within parse_known_args() output_file_paths: any number of file paths to write the config to exit_after: whether to exit the program after writing the config files """ for output_file_path in output_file_paths: # validate the output file path try: with open(output_file_path, "w") as output_file: pass except IOError as e: raise ValueError("Couldn't open %s for writing: %s" % ( output_file_path, e)) if output_file_paths: # generate the config file contents config_items = self.get_items_for_config_file_output( self._source_to_settings, parsed_namespace) file_contents = self._config_file_parser.serialize(config_items) for output_file_path in output_file_paths: with open(output_file_path, "w") as output_file: output_file.write(file_contents) message = "Wrote config file to " + ", ".join(output_file_paths) if exit_after: self.exit(0, message) else: print(message)
python
def write_config_file(self, parsed_namespace, output_file_paths, exit_after=False): """Write the given settings to output files. Args: parsed_namespace: namespace object created within parse_known_args() output_file_paths: any number of file paths to write the config to exit_after: whether to exit the program after writing the config files """ for output_file_path in output_file_paths: # validate the output file path try: with open(output_file_path, "w") as output_file: pass except IOError as e: raise ValueError("Couldn't open %s for writing: %s" % ( output_file_path, e)) if output_file_paths: # generate the config file contents config_items = self.get_items_for_config_file_output( self._source_to_settings, parsed_namespace) file_contents = self._config_file_parser.serialize(config_items) for output_file_path in output_file_paths: with open(output_file_path, "w") as output_file: output_file.write(file_contents) message = "Wrote config file to " + ", ".join(output_file_paths) if exit_after: self.exit(0, message) else: print(message)
[ "def", "write_config_file", "(", "self", ",", "parsed_namespace", ",", "output_file_paths", ",", "exit_after", "=", "False", ")", ":", "for", "output_file_path", "in", "output_file_paths", ":", "# validate the output file path", "try", ":", "with", "open", "(", "output_file_path", ",", "\"w\"", ")", "as", "output_file", ":", "pass", "except", "IOError", "as", "e", ":", "raise", "ValueError", "(", "\"Couldn't open %s for writing: %s\"", "%", "(", "output_file_path", ",", "e", ")", ")", "if", "output_file_paths", ":", "# generate the config file contents", "config_items", "=", "self", ".", "get_items_for_config_file_output", "(", "self", ".", "_source_to_settings", ",", "parsed_namespace", ")", "file_contents", "=", "self", ".", "_config_file_parser", ".", "serialize", "(", "config_items", ")", "for", "output_file_path", "in", "output_file_paths", ":", "with", "open", "(", "output_file_path", ",", "\"w\"", ")", "as", "output_file", ":", "output_file", ".", "write", "(", "file_contents", ")", "message", "=", "\"Wrote config file to \"", "+", "\", \"", ".", "join", "(", "output_file_paths", ")", "if", "exit_after", ":", "self", ".", "exit", "(", "0", ",", "message", ")", "else", ":", "print", "(", "message", ")" ]
Write the given settings to output files. Args: parsed_namespace: namespace object created within parse_known_args() output_file_paths: any number of file paths to write the config to exit_after: whether to exit the program after writing the config files
[ "Write", "the", "given", "settings", "to", "output", "files", "." ]
8bbc7de67f884184068d62af7f78e723d01c0081
https://github.com/bw2/ConfigArgParse/blob/8bbc7de67f884184068d62af7f78e723d01c0081/configargparse.py#L542-L570
train
bw2/ConfigArgParse
configargparse.py
ArgumentParser.convert_item_to_command_line_arg
def convert_item_to_command_line_arg(self, action, key, value): """Converts a config file or env var key + value to a list of commandline args to append to the commandline. Args: action: The argparse Action object for this setting, or None if this config file setting doesn't correspond to any defined configargparse arg. key: string (config file key or env var name) value: parsed value of type string or list """ args = [] if action is None: command_line_key = \ self.get_command_line_key_for_unknown_config_file_setting(key) else: command_line_key = action.option_strings[-1] # handle boolean value if action is not None and isinstance(action, ACTION_TYPES_THAT_DONT_NEED_A_VALUE): if value.lower() in ("true", "yes", "1"): args.append( command_line_key ) elif value.lower() in ("false", "no", "0"): # don't append when set to "false" / "no" pass else: self.error("Unexpected value for %s: '%s'. Expecting 'true', " "'false', 'yes', 'no', '1' or '0'" % (key, value)) elif isinstance(value, list): if action is None or isinstance(action, argparse._AppendAction): for list_elem in value: args.append( command_line_key ) args.append( str(list_elem) ) elif (isinstance(action, argparse._StoreAction) and action.nargs in ('+', '*')) or ( isinstance(action.nargs, int) and action.nargs > 1): args.append( command_line_key ) for list_elem in value: args.append( str(list_elem) ) else: self.error(("%s can't be set to a list '%s' unless its action type is changed " "to 'append' or nargs is set to '*', '+', or > 1") % (key, value)) elif isinstance(value, str): args.append( command_line_key ) args.append( value ) else: raise ValueError("Unexpected value type %s for value: %s" % ( type(value), value)) return args
python
def convert_item_to_command_line_arg(self, action, key, value): """Converts a config file or env var key + value to a list of commandline args to append to the commandline. Args: action: The argparse Action object for this setting, or None if this config file setting doesn't correspond to any defined configargparse arg. key: string (config file key or env var name) value: parsed value of type string or list """ args = [] if action is None: command_line_key = \ self.get_command_line_key_for_unknown_config_file_setting(key) else: command_line_key = action.option_strings[-1] # handle boolean value if action is not None and isinstance(action, ACTION_TYPES_THAT_DONT_NEED_A_VALUE): if value.lower() in ("true", "yes", "1"): args.append( command_line_key ) elif value.lower() in ("false", "no", "0"): # don't append when set to "false" / "no" pass else: self.error("Unexpected value for %s: '%s'. Expecting 'true', " "'false', 'yes', 'no', '1' or '0'" % (key, value)) elif isinstance(value, list): if action is None or isinstance(action, argparse._AppendAction): for list_elem in value: args.append( command_line_key ) args.append( str(list_elem) ) elif (isinstance(action, argparse._StoreAction) and action.nargs in ('+', '*')) or ( isinstance(action.nargs, int) and action.nargs > 1): args.append( command_line_key ) for list_elem in value: args.append( str(list_elem) ) else: self.error(("%s can't be set to a list '%s' unless its action type is changed " "to 'append' or nargs is set to '*', '+', or > 1") % (key, value)) elif isinstance(value, str): args.append( command_line_key ) args.append( value ) else: raise ValueError("Unexpected value type %s for value: %s" % ( type(value), value)) return args
[ "def", "convert_item_to_command_line_arg", "(", "self", ",", "action", ",", "key", ",", "value", ")", ":", "args", "=", "[", "]", "if", "action", "is", "None", ":", "command_line_key", "=", "self", ".", "get_command_line_key_for_unknown_config_file_setting", "(", "key", ")", "else", ":", "command_line_key", "=", "action", ".", "option_strings", "[", "-", "1", "]", "# handle boolean value", "if", "action", "is", "not", "None", "and", "isinstance", "(", "action", ",", "ACTION_TYPES_THAT_DONT_NEED_A_VALUE", ")", ":", "if", "value", ".", "lower", "(", ")", "in", "(", "\"true\"", ",", "\"yes\"", ",", "\"1\"", ")", ":", "args", ".", "append", "(", "command_line_key", ")", "elif", "value", ".", "lower", "(", ")", "in", "(", "\"false\"", ",", "\"no\"", ",", "\"0\"", ")", ":", "# don't append when set to \"false\" / \"no\"", "pass", "else", ":", "self", ".", "error", "(", "\"Unexpected value for %s: '%s'. Expecting 'true', \"", "\"'false', 'yes', 'no', '1' or '0'\"", "%", "(", "key", ",", "value", ")", ")", "elif", "isinstance", "(", "value", ",", "list", ")", ":", "if", "action", "is", "None", "or", "isinstance", "(", "action", ",", "argparse", ".", "_AppendAction", ")", ":", "for", "list_elem", "in", "value", ":", "args", ".", "append", "(", "command_line_key", ")", "args", ".", "append", "(", "str", "(", "list_elem", ")", ")", "elif", "(", "isinstance", "(", "action", ",", "argparse", ".", "_StoreAction", ")", "and", "action", ".", "nargs", "in", "(", "'+'", ",", "'*'", ")", ")", "or", "(", "isinstance", "(", "action", ".", "nargs", ",", "int", ")", "and", "action", ".", "nargs", ">", "1", ")", ":", "args", ".", "append", "(", "command_line_key", ")", "for", "list_elem", "in", "value", ":", "args", ".", "append", "(", "str", "(", "list_elem", ")", ")", "else", ":", "self", ".", "error", "(", "(", "\"%s can't be set to a list '%s' unless its action type is changed \"", "\"to 'append' or nargs is set to '*', '+', or > 1\"", ")", "%", "(", "key", ",", "value", ")", ")", "elif", "isinstance", "(", "value", ",", "str", ")", ":", "args", ".", "append", "(", "command_line_key", ")", "args", ".", "append", "(", "value", ")", "else", ":", "raise", "ValueError", "(", "\"Unexpected value type %s for value: %s\"", "%", "(", "type", "(", "value", ")", ",", "value", ")", ")", "return", "args" ]
Converts a config file or env var key + value to a list of commandline args to append to the commandline. Args: action: The argparse Action object for this setting, or None if this config file setting doesn't correspond to any defined configargparse arg. key: string (config file key or env var name) value: parsed value of type string or list
[ "Converts", "a", "config", "file", "or", "env", "var", "key", "+", "value", "to", "a", "list", "of", "commandline", "args", "to", "append", "to", "the", "commandline", "." ]
8bbc7de67f884184068d62af7f78e723d01c0081
https://github.com/bw2/ConfigArgParse/blob/8bbc7de67f884184068d62af7f78e723d01c0081/configargparse.py#L632-L681
train
bw2/ConfigArgParse
configargparse.py
ArgumentParser.get_possible_config_keys
def get_possible_config_keys(self, action): """This method decides which actions can be set in a config file and what their keys will be. It returns a list of 0 or more config keys that can be used to set the given action's value in a config file. """ keys = [] # Do not write out the config options for writing out a config file if getattr(action, 'is_write_out_config_file_arg', None): return keys for arg in action.option_strings: if any([arg.startswith(2*c) for c in self.prefix_chars]): keys += [arg[2:], arg] # eg. for '--bla' return ['bla', '--bla'] return keys
python
def get_possible_config_keys(self, action): """This method decides which actions can be set in a config file and what their keys will be. It returns a list of 0 or more config keys that can be used to set the given action's value in a config file. """ keys = [] # Do not write out the config options for writing out a config file if getattr(action, 'is_write_out_config_file_arg', None): return keys for arg in action.option_strings: if any([arg.startswith(2*c) for c in self.prefix_chars]): keys += [arg[2:], arg] # eg. for '--bla' return ['bla', '--bla'] return keys
[ "def", "get_possible_config_keys", "(", "self", ",", "action", ")", ":", "keys", "=", "[", "]", "# Do not write out the config options for writing out a config file", "if", "getattr", "(", "action", ",", "'is_write_out_config_file_arg'", ",", "None", ")", ":", "return", "keys", "for", "arg", "in", "action", ".", "option_strings", ":", "if", "any", "(", "[", "arg", ".", "startswith", "(", "2", "*", "c", ")", "for", "c", "in", "self", ".", "prefix_chars", "]", ")", ":", "keys", "+=", "[", "arg", "[", "2", ":", "]", ",", "arg", "]", "# eg. for '--bla' return ['bla', '--bla']", "return", "keys" ]
This method decides which actions can be set in a config file and what their keys will be. It returns a list of 0 or more config keys that can be used to set the given action's value in a config file.
[ "This", "method", "decides", "which", "actions", "can", "be", "set", "in", "a", "config", "file", "and", "what", "their", "keys", "will", "be", ".", "It", "returns", "a", "list", "of", "0", "or", "more", "config", "keys", "that", "can", "be", "used", "to", "set", "the", "given", "action", "s", "value", "in", "a", "config", "file", "." ]
8bbc7de67f884184068d62af7f78e723d01c0081
https://github.com/bw2/ConfigArgParse/blob/8bbc7de67f884184068d62af7f78e723d01c0081/configargparse.py#L683-L698
train
ihucos/plash
opt/plash/lib/py/plash/eval.py
eval
def eval(lisp): ''' plash lisp is one dimensional lisp. ''' macro_values = [] if not isinstance(lisp, list): raise EvalError('eval root element must be a list') for item in lisp: if not isinstance(item, list): raise EvalError('must evaluate list of list') if not all(isinstance(i, str) for i in item): raise EvalError( 'must evaluate list of list of strings. not a list of strings: {}' .format(item)) name = item[0] args = item[1:] try: macro = state['macros'][name] except KeyError: raise MacroNotFoundError("macro {} not found".format(repr(name))) try: res = macro(*args) except Exception as exc: if os.getenv('PLASH_DEBUG', '').lower() in ('1', 'yes', 'true'): raise if isinstance(exc, MacroError): # only raise that one time and don't have multiple wrapped MacroError raise raise MacroError(macro, name, sys.exc_info()) if not isinstance(res, str) and res is not None: raise EvalError( 'eval macro must return string or None ({} returned {})'. format(name, type(res))) if res is not None: macro_values.append(res) return '\n'.join(macro_values)
python
def eval(lisp): ''' plash lisp is one dimensional lisp. ''' macro_values = [] if not isinstance(lisp, list): raise EvalError('eval root element must be a list') for item in lisp: if not isinstance(item, list): raise EvalError('must evaluate list of list') if not all(isinstance(i, str) for i in item): raise EvalError( 'must evaluate list of list of strings. not a list of strings: {}' .format(item)) name = item[0] args = item[1:] try: macro = state['macros'][name] except KeyError: raise MacroNotFoundError("macro {} not found".format(repr(name))) try: res = macro(*args) except Exception as exc: if os.getenv('PLASH_DEBUG', '').lower() in ('1', 'yes', 'true'): raise if isinstance(exc, MacroError): # only raise that one time and don't have multiple wrapped MacroError raise raise MacroError(macro, name, sys.exc_info()) if not isinstance(res, str) and res is not None: raise EvalError( 'eval macro must return string or None ({} returned {})'. format(name, type(res))) if res is not None: macro_values.append(res) return '\n'.join(macro_values)
[ "def", "eval", "(", "lisp", ")", ":", "macro_values", "=", "[", "]", "if", "not", "isinstance", "(", "lisp", ",", "list", ")", ":", "raise", "EvalError", "(", "'eval root element must be a list'", ")", "for", "item", "in", "lisp", ":", "if", "not", "isinstance", "(", "item", ",", "list", ")", ":", "raise", "EvalError", "(", "'must evaluate list of list'", ")", "if", "not", "all", "(", "isinstance", "(", "i", ",", "str", ")", "for", "i", "in", "item", ")", ":", "raise", "EvalError", "(", "'must evaluate list of list of strings. not a list of strings: {}'", ".", "format", "(", "item", ")", ")", "name", "=", "item", "[", "0", "]", "args", "=", "item", "[", "1", ":", "]", "try", ":", "macro", "=", "state", "[", "'macros'", "]", "[", "name", "]", "except", "KeyError", ":", "raise", "MacroNotFoundError", "(", "\"macro {} not found\"", ".", "format", "(", "repr", "(", "name", ")", ")", ")", "try", ":", "res", "=", "macro", "(", "*", "args", ")", "except", "Exception", "as", "exc", ":", "if", "os", ".", "getenv", "(", "'PLASH_DEBUG'", ",", "''", ")", ".", "lower", "(", ")", "in", "(", "'1'", ",", "'yes'", ",", "'true'", ")", ":", "raise", "if", "isinstance", "(", "exc", ",", "MacroError", ")", ":", "# only raise that one time and don't have multiple wrapped MacroError", "raise", "raise", "MacroError", "(", "macro", ",", "name", ",", "sys", ".", "exc_info", "(", ")", ")", "if", "not", "isinstance", "(", "res", ",", "str", ")", "and", "res", "is", "not", "None", ":", "raise", "EvalError", "(", "'eval macro must return string or None ({} returned {})'", ".", "format", "(", "name", ",", "type", "(", "res", ")", ")", ")", "if", "res", "is", "not", "None", ":", "macro_values", ".", "append", "(", "res", ")", "return", "'\\n'", ".", "join", "(", "macro_values", ")" ]
plash lisp is one dimensional lisp.
[ "plash", "lisp", "is", "one", "dimensional", "lisp", "." ]
2ab2bc956e309d5aa6414c80983bfbf29b0ce572
https://github.com/ihucos/plash/blob/2ab2bc956e309d5aa6414c80983bfbf29b0ce572/opt/plash/lib/py/plash/eval.py#L62-L97
train
ihucos/plash
opt/plash/lib/py/plash/utils.py
plash_map
def plash_map(*args): from subprocess import check_output 'thin wrapper around plash map' out = check_output(['plash', 'map'] + list(args)) if out == '': return None return out.decode().strip('\n')
python
def plash_map(*args): from subprocess import check_output 'thin wrapper around plash map' out = check_output(['plash', 'map'] + list(args)) if out == '': return None return out.decode().strip('\n')
[ "def", "plash_map", "(", "*", "args", ")", ":", "from", "subprocess", "import", "check_output", "out", "=", "check_output", "(", "[", "'plash'", ",", "'map'", "]", "+", "list", "(", "args", ")", ")", "if", "out", "==", "''", ":", "return", "None", "return", "out", ".", "decode", "(", ")", ".", "strip", "(", "'\\n'", ")" ]
thin wrapper around plash map
[ "thin", "wrapper", "around", "plash", "map" ]
2ab2bc956e309d5aa6414c80983bfbf29b0ce572
https://github.com/ihucos/plash/blob/2ab2bc956e309d5aa6414c80983bfbf29b0ce572/opt/plash/lib/py/plash/utils.py#L96-L102
train
ihucos/plash
opt/plash/lib/py/plash/macros/packagemanagers.py
defpm
def defpm(name, *lines): 'define a new package manager' @register_macro(name, group='package managers') @shell_escape_args def package_manager(*packages): if not packages: return sh_packages = ' '.join(pkg for pkg in packages) expanded_lines = [line.format(sh_packages) for line in lines] return eval([['run'] + expanded_lines]) package_manager.__doc__ = "install packages with {}".format(name)
python
def defpm(name, *lines): 'define a new package manager' @register_macro(name, group='package managers') @shell_escape_args def package_manager(*packages): if not packages: return sh_packages = ' '.join(pkg for pkg in packages) expanded_lines = [line.format(sh_packages) for line in lines] return eval([['run'] + expanded_lines]) package_manager.__doc__ = "install packages with {}".format(name)
[ "def", "defpm", "(", "name", ",", "*", "lines", ")", ":", "@", "register_macro", "(", "name", ",", "group", "=", "'package managers'", ")", "@", "shell_escape_args", "def", "package_manager", "(", "*", "packages", ")", ":", "if", "not", "packages", ":", "return", "sh_packages", "=", "' '", ".", "join", "(", "pkg", "for", "pkg", "in", "packages", ")", "expanded_lines", "=", "[", "line", ".", "format", "(", "sh_packages", ")", "for", "line", "in", "lines", "]", "return", "eval", "(", "[", "[", "'run'", "]", "+", "expanded_lines", "]", ")", "package_manager", ".", "__doc__", "=", "\"install packages with {}\"", ".", "format", "(", "name", ")" ]
define a new package manager
[ "define", "a", "new", "package", "manager" ]
2ab2bc956e309d5aa6414c80983bfbf29b0ce572
https://github.com/ihucos/plash/blob/2ab2bc956e309d5aa6414c80983bfbf29b0ce572/opt/plash/lib/py/plash/macros/packagemanagers.py#L5-L17
train
ihucos/plash
opt/plash/lib/py/plash/macros/common.py
layer
def layer(command=None, *args): 'hints the start of a new layer' if not command: return eval([['hint', 'layer']]) # fall back to buildin layer macro else: lst = [['layer']] for arg in args: lst.append([command, arg]) lst.append(['layer']) return eval(lst)
python
def layer(command=None, *args): 'hints the start of a new layer' if not command: return eval([['hint', 'layer']]) # fall back to buildin layer macro else: lst = [['layer']] for arg in args: lst.append([command, arg]) lst.append(['layer']) return eval(lst)
[ "def", "layer", "(", "command", "=", "None", ",", "*", "args", ")", ":", "if", "not", "command", ":", "return", "eval", "(", "[", "[", "'hint'", ",", "'layer'", "]", "]", ")", "# fall back to buildin layer macro", "else", ":", "lst", "=", "[", "[", "'layer'", "]", "]", "for", "arg", "in", "args", ":", "lst", ".", "append", "(", "[", "command", ",", "arg", "]", ")", "lst", ".", "append", "(", "[", "'layer'", "]", ")", "return", "eval", "(", "lst", ")" ]
hints the start of a new layer
[ "hints", "the", "start", "of", "a", "new", "layer" ]
2ab2bc956e309d5aa6414c80983bfbf29b0ce572
https://github.com/ihucos/plash/blob/2ab2bc956e309d5aa6414c80983bfbf29b0ce572/opt/plash/lib/py/plash/macros/common.py#L15-L24
train
ihucos/plash
opt/plash/lib/py/plash/macros/common.py
import_env
def import_env(*envs): 'import environment variables from host' for env in envs: parts = env.split(':', 1) if len(parts) == 1: export_as = env else: env, export_as = parts env_val = os.environ.get(env) if env_val is not None: yield '{}={}'.format(export_as, shlex.quote(env_val))
python
def import_env(*envs): 'import environment variables from host' for env in envs: parts = env.split(':', 1) if len(parts) == 1: export_as = env else: env, export_as = parts env_val = os.environ.get(env) if env_val is not None: yield '{}={}'.format(export_as, shlex.quote(env_val))
[ "def", "import_env", "(", "*", "envs", ")", ":", "for", "env", "in", "envs", ":", "parts", "=", "env", ".", "split", "(", "':'", ",", "1", ")", "if", "len", "(", "parts", ")", "==", "1", ":", "export_as", "=", "env", "else", ":", "env", ",", "export_as", "=", "parts", "env_val", "=", "os", ".", "environ", ".", "get", "(", "env", ")", "if", "env_val", "is", "not", "None", ":", "yield", "'{}={}'", ".", "format", "(", "export_as", ",", "shlex", ".", "quote", "(", "env_val", ")", ")" ]
import environment variables from host
[ "import", "environment", "variables", "from", "host" ]
2ab2bc956e309d5aa6414c80983bfbf29b0ce572
https://github.com/ihucos/plash/blob/2ab2bc956e309d5aa6414c80983bfbf29b0ce572/opt/plash/lib/py/plash/macros/common.py#L40-L50
train
ihucos/plash
opt/plash/lib/py/plash/macros/common.py
write_file
def write_file(fname, *lines): 'write lines to a file' yield 'touch {}'.format(fname) for line in lines: yield "echo {} >> {}".format(line, fname)
python
def write_file(fname, *lines): 'write lines to a file' yield 'touch {}'.format(fname) for line in lines: yield "echo {} >> {}".format(line, fname)
[ "def", "write_file", "(", "fname", ",", "*", "lines", ")", ":", "yield", "'touch {}'", ".", "format", "(", "fname", ")", "for", "line", "in", "lines", ":", "yield", "\"echo {} >> {}\"", ".", "format", "(", "line", ",", "fname", ")" ]
write lines to a file
[ "write", "lines", "to", "a", "file" ]
2ab2bc956e309d5aa6414c80983bfbf29b0ce572
https://github.com/ihucos/plash/blob/2ab2bc956e309d5aa6414c80983bfbf29b0ce572/opt/plash/lib/py/plash/macros/common.py#L62-L66
train
ihucos/plash
opt/plash/lib/py/plash/macros/common.py
eval_file
def eval_file(file): 'evaluate file content as expressions' fname = os.path.realpath(os.path.expanduser(file)) with open(fname) as f: inscript = f.read() sh = run_write_read(['plash', 'eval'], inscript.encode()).decode() # we remove an possibly existing newline # because else this macros would add one if sh.endswith('\n'): return sh[:-1] return sh
python
def eval_file(file): 'evaluate file content as expressions' fname = os.path.realpath(os.path.expanduser(file)) with open(fname) as f: inscript = f.read() sh = run_write_read(['plash', 'eval'], inscript.encode()).decode() # we remove an possibly existing newline # because else this macros would add one if sh.endswith('\n'): return sh[:-1] return sh
[ "def", "eval_file", "(", "file", ")", ":", "fname", "=", "os", ".", "path", ".", "realpath", "(", "os", ".", "path", ".", "expanduser", "(", "file", ")", ")", "with", "open", "(", "fname", ")", "as", "f", ":", "inscript", "=", "f", ".", "read", "(", ")", "sh", "=", "run_write_read", "(", "[", "'plash'", ",", "'eval'", "]", ",", "inscript", ".", "encode", "(", ")", ")", ".", "decode", "(", ")", "# we remove an possibly existing newline", "# because else this macros would add one", "if", "sh", ".", "endswith", "(", "'\\n'", ")", ":", "return", "sh", "[", ":", "-", "1", "]", "return", "sh" ]
evaluate file content as expressions
[ "evaluate", "file", "content", "as", "expressions" ]
2ab2bc956e309d5aa6414c80983bfbf29b0ce572
https://github.com/ihucos/plash/blob/2ab2bc956e309d5aa6414c80983bfbf29b0ce572/opt/plash/lib/py/plash/macros/common.py#L78-L92
train
ihucos/plash
opt/plash/lib/py/plash/macros/common.py
eval_string
def eval_string(stri): 'evaluate expressions passed as string' tokens = shlex.split(stri) return run_write_read(['plash', 'eval'], '\n'.join(tokens).encode()).decode()
python
def eval_string(stri): 'evaluate expressions passed as string' tokens = shlex.split(stri) return run_write_read(['plash', 'eval'], '\n'.join(tokens).encode()).decode()
[ "def", "eval_string", "(", "stri", ")", ":", "tokens", "=", "shlex", ".", "split", "(", "stri", ")", "return", "run_write_read", "(", "[", "'plash'", ",", "'eval'", "]", ",", "'\\n'", ".", "join", "(", "tokens", ")", ".", "encode", "(", ")", ")", ".", "decode", "(", ")" ]
evaluate expressions passed as string
[ "evaluate", "expressions", "passed", "as", "string" ]
2ab2bc956e309d5aa6414c80983bfbf29b0ce572
https://github.com/ihucos/plash/blob/2ab2bc956e309d5aa6414c80983bfbf29b0ce572/opt/plash/lib/py/plash/macros/common.py#L96-L100
train
ihucos/plash
opt/plash/lib/py/plash/macros/common.py
eval_stdin
def eval_stdin(): 'evaluate expressions read from stdin' cmd = ['plash', 'eval'] p = subprocess.Popen(cmd, stdin=sys.stdin, stdout=sys.stdout) exit = p.wait() if exit: raise subprocess.CalledProcessError(exit, cmd)
python
def eval_stdin(): 'evaluate expressions read from stdin' cmd = ['plash', 'eval'] p = subprocess.Popen(cmd, stdin=sys.stdin, stdout=sys.stdout) exit = p.wait() if exit: raise subprocess.CalledProcessError(exit, cmd)
[ "def", "eval_stdin", "(", ")", ":", "cmd", "=", "[", "'plash'", ",", "'eval'", "]", "p", "=", "subprocess", ".", "Popen", "(", "cmd", ",", "stdin", "=", "sys", ".", "stdin", ",", "stdout", "=", "sys", ".", "stdout", ")", "exit", "=", "p", ".", "wait", "(", ")", "if", "exit", ":", "raise", "subprocess", ".", "CalledProcessError", "(", "exit", ",", "cmd", ")" ]
evaluate expressions read from stdin
[ "evaluate", "expressions", "read", "from", "stdin" ]
2ab2bc956e309d5aa6414c80983bfbf29b0ce572
https://github.com/ihucos/plash/blob/2ab2bc956e309d5aa6414c80983bfbf29b0ce572/opt/plash/lib/py/plash/macros/common.py#L104-L110
train
ihucos/plash
opt/plash/lib/py/plash/macros/froms.py
from_map
def from_map(map_key): 'use resolved map as image' image_id = subprocess.check_output(['plash', 'map', map_key]).decode().strip('\n') if not image_id: raise MapDoesNotExist('map {} not found'.format(repr(map_key))) return hint('image', image_id)
python
def from_map(map_key): 'use resolved map as image' image_id = subprocess.check_output(['plash', 'map', map_key]).decode().strip('\n') if not image_id: raise MapDoesNotExist('map {} not found'.format(repr(map_key))) return hint('image', image_id)
[ "def", "from_map", "(", "map_key", ")", ":", "image_id", "=", "subprocess", ".", "check_output", "(", "[", "'plash'", ",", "'map'", ",", "map_key", "]", ")", ".", "decode", "(", ")", ".", "strip", "(", "'\\n'", ")", "if", "not", "image_id", ":", "raise", "MapDoesNotExist", "(", "'map {} not found'", ".", "format", "(", "repr", "(", "map_key", ")", ")", ")", "return", "hint", "(", "'image'", ",", "image_id", ")" ]
use resolved map as image
[ "use", "resolved", "map", "as", "image" ]
2ab2bc956e309d5aa6414c80983bfbf29b0ce572
https://github.com/ihucos/plash/blob/2ab2bc956e309d5aa6414c80983bfbf29b0ce572/opt/plash/lib/py/plash/macros/froms.py#L61-L67
train
dbrgn/drf-dynamic-fields
drf_dynamic_fields/__init__.py
DynamicFieldsMixin.fields
def fields(self): """ Filters the fields according to the `fields` query parameter. A blank `fields` parameter (?fields) will remove all fields. Not passing `fields` will pass all fields individual fields are comma separated (?fields=id,name,url,email). """ fields = super(DynamicFieldsMixin, self).fields if not hasattr(self, '_context'): # We are being called before a request cycle return fields # Only filter if this is the root serializer, or if the parent is the # root serializer with many=True is_root = self.root == self parent_is_list_root = self.parent == self.root and getattr(self.parent, 'many', False) if not (is_root or parent_is_list_root): return fields try: request = self.context['request'] except KeyError: conf = getattr(settings, 'DRF_DYNAMIC_FIELDS', {}) if not conf.get('SUPPRESS_CONTEXT_WARNING', False) is True: warnings.warn('Context does not have access to request. ' 'See README for more information.') return fields # NOTE: drf test framework builds a request object where the query # parameters are found under the GET attribute. params = getattr( request, 'query_params', getattr(request, 'GET', None) ) if params is None: warnings.warn('Request object does not contain query paramters') try: filter_fields = params.get('fields', None).split(',') except AttributeError: filter_fields = None try: omit_fields = params.get('omit', None).split(',') except AttributeError: omit_fields = [] # Drop any fields that are not specified in the `fields` argument. existing = set(fields.keys()) if filter_fields is None: # no fields param given, don't filter. allowed = existing else: allowed = set(filter(None, filter_fields)) # omit fields in the `omit` argument. omitted = set(filter(None, omit_fields)) for field in existing: if field not in allowed: fields.pop(field, None) if field in omitted: fields.pop(field, None) return fields
python
def fields(self): """ Filters the fields according to the `fields` query parameter. A blank `fields` parameter (?fields) will remove all fields. Not passing `fields` will pass all fields individual fields are comma separated (?fields=id,name,url,email). """ fields = super(DynamicFieldsMixin, self).fields if not hasattr(self, '_context'): # We are being called before a request cycle return fields # Only filter if this is the root serializer, or if the parent is the # root serializer with many=True is_root = self.root == self parent_is_list_root = self.parent == self.root and getattr(self.parent, 'many', False) if not (is_root or parent_is_list_root): return fields try: request = self.context['request'] except KeyError: conf = getattr(settings, 'DRF_DYNAMIC_FIELDS', {}) if not conf.get('SUPPRESS_CONTEXT_WARNING', False) is True: warnings.warn('Context does not have access to request. ' 'See README for more information.') return fields # NOTE: drf test framework builds a request object where the query # parameters are found under the GET attribute. params = getattr( request, 'query_params', getattr(request, 'GET', None) ) if params is None: warnings.warn('Request object does not contain query paramters') try: filter_fields = params.get('fields', None).split(',') except AttributeError: filter_fields = None try: omit_fields = params.get('omit', None).split(',') except AttributeError: omit_fields = [] # Drop any fields that are not specified in the `fields` argument. existing = set(fields.keys()) if filter_fields is None: # no fields param given, don't filter. allowed = existing else: allowed = set(filter(None, filter_fields)) # omit fields in the `omit` argument. omitted = set(filter(None, omit_fields)) for field in existing: if field not in allowed: fields.pop(field, None) if field in omitted: fields.pop(field, None) return fields
[ "def", "fields", "(", "self", ")", ":", "fields", "=", "super", "(", "DynamicFieldsMixin", ",", "self", ")", ".", "fields", "if", "not", "hasattr", "(", "self", ",", "'_context'", ")", ":", "# We are being called before a request cycle", "return", "fields", "# Only filter if this is the root serializer, or if the parent is the", "# root serializer with many=True", "is_root", "=", "self", ".", "root", "==", "self", "parent_is_list_root", "=", "self", ".", "parent", "==", "self", ".", "root", "and", "getattr", "(", "self", ".", "parent", ",", "'many'", ",", "False", ")", "if", "not", "(", "is_root", "or", "parent_is_list_root", ")", ":", "return", "fields", "try", ":", "request", "=", "self", ".", "context", "[", "'request'", "]", "except", "KeyError", ":", "conf", "=", "getattr", "(", "settings", ",", "'DRF_DYNAMIC_FIELDS'", ",", "{", "}", ")", "if", "not", "conf", ".", "get", "(", "'SUPPRESS_CONTEXT_WARNING'", ",", "False", ")", "is", "True", ":", "warnings", ".", "warn", "(", "'Context does not have access to request. '", "'See README for more information.'", ")", "return", "fields", "# NOTE: drf test framework builds a request object where the query", "# parameters are found under the GET attribute.", "params", "=", "getattr", "(", "request", ",", "'query_params'", ",", "getattr", "(", "request", ",", "'GET'", ",", "None", ")", ")", "if", "params", "is", "None", ":", "warnings", ".", "warn", "(", "'Request object does not contain query paramters'", ")", "try", ":", "filter_fields", "=", "params", ".", "get", "(", "'fields'", ",", "None", ")", ".", "split", "(", "','", ")", "except", "AttributeError", ":", "filter_fields", "=", "None", "try", ":", "omit_fields", "=", "params", ".", "get", "(", "'omit'", ",", "None", ")", ".", "split", "(", "','", ")", "except", "AttributeError", ":", "omit_fields", "=", "[", "]", "# Drop any fields that are not specified in the `fields` argument.", "existing", "=", "set", "(", "fields", ".", "keys", "(", ")", ")", "if", "filter_fields", "is", "None", ":", "# no fields param given, don't filter.", "allowed", "=", "existing", "else", ":", "allowed", "=", "set", "(", "filter", "(", "None", ",", "filter_fields", ")", ")", "# omit fields in the `omit` argument.", "omitted", "=", "set", "(", "filter", "(", "None", ",", "omit_fields", ")", ")", "for", "field", "in", "existing", ":", "if", "field", "not", "in", "allowed", ":", "fields", ".", "pop", "(", "field", ",", "None", ")", "if", "field", "in", "omitted", ":", "fields", ".", "pop", "(", "field", ",", "None", ")", "return", "fields" ]
Filters the fields according to the `fields` query parameter. A blank `fields` parameter (?fields) will remove all fields. Not passing `fields` will pass all fields individual fields are comma separated (?fields=id,name,url,email).
[ "Filters", "the", "fields", "according", "to", "the", "fields", "query", "parameter", "." ]
d24da8bc321462ea6231821d6c3d210b76d4785b
https://github.com/dbrgn/drf-dynamic-fields/blob/d24da8bc321462ea6231821d6c3d210b76d4785b/drf_dynamic_fields/__init__.py#L16-L84
train
aio-libs/aiohttp_admin
aiohttp_admin/admin.py
setup_admin_on_rest_handlers
def setup_admin_on_rest_handlers(admin, admin_handler): """ Initialize routes. """ add_route = admin.router.add_route add_static = admin.router.add_static static_folder = str(PROJ_ROOT / 'static') a = admin_handler add_route('GET', '', a.index_page, name='admin.index') add_route('POST', '/token', a.token, name='admin.token') add_static('/static', path=static_folder, name='admin.static') add_route('DELETE', '/logout', a.logout, name='admin.logout')
python
def setup_admin_on_rest_handlers(admin, admin_handler): """ Initialize routes. """ add_route = admin.router.add_route add_static = admin.router.add_static static_folder = str(PROJ_ROOT / 'static') a = admin_handler add_route('GET', '', a.index_page, name='admin.index') add_route('POST', '/token', a.token, name='admin.token') add_static('/static', path=static_folder, name='admin.static') add_route('DELETE', '/logout', a.logout, name='admin.logout')
[ "def", "setup_admin_on_rest_handlers", "(", "admin", ",", "admin_handler", ")", ":", "add_route", "=", "admin", ".", "router", ".", "add_route", "add_static", "=", "admin", ".", "router", ".", "add_static", "static_folder", "=", "str", "(", "PROJ_ROOT", "/", "'static'", ")", "a", "=", "admin_handler", "add_route", "(", "'GET'", ",", "''", ",", "a", ".", "index_page", ",", "name", "=", "'admin.index'", ")", "add_route", "(", "'POST'", ",", "'/token'", ",", "a", ".", "token", ",", "name", "=", "'admin.token'", ")", "add_static", "(", "'/static'", ",", "path", "=", "static_folder", ",", "name", "=", "'admin.static'", ")", "add_route", "(", "'DELETE'", ",", "'/logout'", ",", "a", ".", "logout", ",", "name", "=", "'admin.logout'", ")" ]
Initialize routes.
[ "Initialize", "routes", "." ]
82e5032ef14ae8cc3c594fdd45d6c977aab1baad
https://github.com/aio-libs/aiohttp_admin/blob/82e5032ef14ae8cc3c594fdd45d6c977aab1baad/aiohttp_admin/admin.py#L148-L160
train
aio-libs/aiohttp_admin
aiohttp_admin/admin.py
AdminOnRestHandler.index_page
async def index_page(self, request): """ Return index page with initial state for admin """ context = {"initial_state": self.schema.to_json()} return render_template( self.template, request, context, app_key=TEMPLATE_APP_KEY, )
python
async def index_page(self, request): """ Return index page with initial state for admin """ context = {"initial_state": self.schema.to_json()} return render_template( self.template, request, context, app_key=TEMPLATE_APP_KEY, )
[ "async", "def", "index_page", "(", "self", ",", "request", ")", ":", "context", "=", "{", "\"initial_state\"", ":", "self", ".", "schema", ".", "to_json", "(", ")", "}", "return", "render_template", "(", "self", ".", "template", ",", "request", ",", "context", ",", "app_key", "=", "TEMPLATE_APP_KEY", ",", ")" ]
Return index page with initial state for admin
[ "Return", "index", "page", "with", "initial", "state", "for", "admin" ]
82e5032ef14ae8cc3c594fdd45d6c977aab1baad
https://github.com/aio-libs/aiohttp_admin/blob/82e5032ef14ae8cc3c594fdd45d6c977aab1baad/aiohttp_admin/admin.py#L105-L116
train
aio-libs/aiohttp_admin
aiohttp_admin/admin.py
AdminOnRestHandler.logout
async def logout(self, request): """ Simple handler for logout """ if "Authorization" not in request.headers: msg = "Auth header is not present, can not destroy token" raise JsonValidaitonError(msg) response = json_response() await forget(request, response) return response
python
async def logout(self, request): """ Simple handler for logout """ if "Authorization" not in request.headers: msg = "Auth header is not present, can not destroy token" raise JsonValidaitonError(msg) response = json_response() await forget(request, response) return response
[ "async", "def", "logout", "(", "self", ",", "request", ")", ":", "if", "\"Authorization\"", "not", "in", "request", ".", "headers", ":", "msg", "=", "\"Auth header is not present, can not destroy token\"", "raise", "JsonValidaitonError", "(", "msg", ")", "response", "=", "json_response", "(", ")", "await", "forget", "(", "request", ",", "response", ")", "return", "response" ]
Simple handler for logout
[ "Simple", "handler", "for", "logout" ]
82e5032ef14ae8cc3c594fdd45d6c977aab1baad
https://github.com/aio-libs/aiohttp_admin/blob/82e5032ef14ae8cc3c594fdd45d6c977aab1baad/aiohttp_admin/admin.py#L134-L145
train
aio-libs/aiohttp_admin
aiohttp_admin/utils.py
validate_query_structure
def validate_query_structure(query): """Validate query arguments in list request. :param query: mapping with pagination and filtering information """ query_dict = dict(query) filters = query_dict.pop('_filters', None) if filters: try: f = json.loads(filters) except ValueError: msg = '_filters field can not be serialized' raise JsonValidaitonError(msg) else: query_dict['_filters'] = f try: q = ListQuery(query_dict) except t.DataError as exc: msg = '_filters query invalid' raise JsonValidaitonError(msg, **as_dict(exc)) return q
python
def validate_query_structure(query): """Validate query arguments in list request. :param query: mapping with pagination and filtering information """ query_dict = dict(query) filters = query_dict.pop('_filters', None) if filters: try: f = json.loads(filters) except ValueError: msg = '_filters field can not be serialized' raise JsonValidaitonError(msg) else: query_dict['_filters'] = f try: q = ListQuery(query_dict) except t.DataError as exc: msg = '_filters query invalid' raise JsonValidaitonError(msg, **as_dict(exc)) return q
[ "def", "validate_query_structure", "(", "query", ")", ":", "query_dict", "=", "dict", "(", "query", ")", "filters", "=", "query_dict", ".", "pop", "(", "'_filters'", ",", "None", ")", "if", "filters", ":", "try", ":", "f", "=", "json", ".", "loads", "(", "filters", ")", "except", "ValueError", ":", "msg", "=", "'_filters field can not be serialized'", "raise", "JsonValidaitonError", "(", "msg", ")", "else", ":", "query_dict", "[", "'_filters'", "]", "=", "f", "try", ":", "q", "=", "ListQuery", "(", "query_dict", ")", "except", "t", ".", "DataError", "as", "exc", ":", "msg", "=", "'_filters query invalid'", "raise", "JsonValidaitonError", "(", "msg", ",", "*", "*", "as_dict", "(", "exc", ")", ")", "return", "q" ]
Validate query arguments in list request. :param query: mapping with pagination and filtering information
[ "Validate", "query", "arguments", "in", "list", "request", "." ]
82e5032ef14ae8cc3c594fdd45d6c977aab1baad
https://github.com/aio-libs/aiohttp_admin/blob/82e5032ef14ae8cc3c594fdd45d6c977aab1baad/aiohttp_admin/utils.py#L82-L103
train
aio-libs/aiohttp_admin
aiohttp_admin/contrib/admin.py
Schema.to_json
def to_json(self): """ Prepare data for the initial state of the admin-on-rest """ endpoints = [] for endpoint in self.endpoints: list_fields = endpoint.fields resource_type = endpoint.Meta.resource_type table = endpoint.Meta.table data = endpoint.to_dict() data['fields'] = resource_type.get_type_of_fields( list_fields, table, ) endpoints.append(data) data = { 'title': self.title, 'endpoints': sorted(endpoints, key=lambda x: x['name']), } return json.dumps(data)
python
def to_json(self): """ Prepare data for the initial state of the admin-on-rest """ endpoints = [] for endpoint in self.endpoints: list_fields = endpoint.fields resource_type = endpoint.Meta.resource_type table = endpoint.Meta.table data = endpoint.to_dict() data['fields'] = resource_type.get_type_of_fields( list_fields, table, ) endpoints.append(data) data = { 'title': self.title, 'endpoints': sorted(endpoints, key=lambda x: x['name']), } return json.dumps(data)
[ "def", "to_json", "(", "self", ")", ":", "endpoints", "=", "[", "]", "for", "endpoint", "in", "self", ".", "endpoints", ":", "list_fields", "=", "endpoint", ".", "fields", "resource_type", "=", "endpoint", ".", "Meta", ".", "resource_type", "table", "=", "endpoint", ".", "Meta", ".", "table", "data", "=", "endpoint", ".", "to_dict", "(", ")", "data", "[", "'fields'", "]", "=", "resource_type", ".", "get_type_of_fields", "(", "list_fields", ",", "table", ",", ")", "endpoints", ".", "append", "(", "data", ")", "data", "=", "{", "'title'", ":", "self", ".", "title", ",", "'endpoints'", ":", "sorted", "(", "endpoints", ",", "key", "=", "lambda", "x", ":", "x", "[", "'name'", "]", ")", ",", "}", "return", "json", ".", "dumps", "(", "data", ")" ]
Prepare data for the initial state of the admin-on-rest
[ "Prepare", "data", "for", "the", "initial", "state", "of", "the", "admin", "-", "on", "-", "rest" ]
82e5032ef14ae8cc3c594fdd45d6c977aab1baad
https://github.com/aio-libs/aiohttp_admin/blob/82e5032ef14ae8cc3c594fdd45d6c977aab1baad/aiohttp_admin/contrib/admin.py#L30-L52
train
aio-libs/aiohttp_admin
aiohttp_admin/contrib/admin.py
Schema.resources
def resources(self): """ Return list of all registered resources. """ resources = [] for endpoint in self.endpoints: resource_type = endpoint.Meta.resource_type table = endpoint.Meta.table url = endpoint.name resources.append((resource_type, {'table': table, 'url': url})) return resources
python
def resources(self): """ Return list of all registered resources. """ resources = [] for endpoint in self.endpoints: resource_type = endpoint.Meta.resource_type table = endpoint.Meta.table url = endpoint.name resources.append((resource_type, {'table': table, 'url': url})) return resources
[ "def", "resources", "(", "self", ")", ":", "resources", "=", "[", "]", "for", "endpoint", "in", "self", ".", "endpoints", ":", "resource_type", "=", "endpoint", ".", "Meta", ".", "resource_type", "table", "=", "endpoint", ".", "Meta", ".", "table", "url", "=", "endpoint", ".", "name", "resources", ".", "append", "(", "(", "resource_type", ",", "{", "'table'", ":", "table", ",", "'url'", ":", "url", "}", ")", ")", "return", "resources" ]
Return list of all registered resources.
[ "Return", "list", "of", "all", "registered", "resources", "." ]
82e5032ef14ae8cc3c594fdd45d6c977aab1baad
https://github.com/aio-libs/aiohttp_admin/blob/82e5032ef14ae8cc3c594fdd45d6c977aab1baad/aiohttp_admin/contrib/admin.py#L55-L68
train
aio-libs/aiohttp_admin
aiohttp_admin/backends/sa.py
PGResource.get_type_of_fields
def get_type_of_fields(fields, table): """ Return data types of `fields` that are in `table`. If a given parameter is empty return primary key. :param fields: list - list of fields that need to be returned :param table: sa.Table - the current table :return: list - list of the tuples `(field_name, fields_type)` """ if not fields: fields = table.primary_key actual_fields = [ field for field in table.c.items() if field[0] in fields ] data_type_fields = { name: FIELD_TYPES.get(type(field_type.type), rc.TEXT_FIELD.value) for name, field_type in actual_fields } return data_type_fields
python
def get_type_of_fields(fields, table): """ Return data types of `fields` that are in `table`. If a given parameter is empty return primary key. :param fields: list - list of fields that need to be returned :param table: sa.Table - the current table :return: list - list of the tuples `(field_name, fields_type)` """ if not fields: fields = table.primary_key actual_fields = [ field for field in table.c.items() if field[0] in fields ] data_type_fields = { name: FIELD_TYPES.get(type(field_type.type), rc.TEXT_FIELD.value) for name, field_type in actual_fields } return data_type_fields
[ "def", "get_type_of_fields", "(", "fields", ",", "table", ")", ":", "if", "not", "fields", ":", "fields", "=", "table", ".", "primary_key", "actual_fields", "=", "[", "field", "for", "field", "in", "table", ".", "c", ".", "items", "(", ")", "if", "field", "[", "0", "]", "in", "fields", "]", "data_type_fields", "=", "{", "name", ":", "FIELD_TYPES", ".", "get", "(", "type", "(", "field_type", ".", "type", ")", ",", "rc", ".", "TEXT_FIELD", ".", "value", ")", "for", "name", ",", "field_type", "in", "actual_fields", "}", "return", "data_type_fields" ]
Return data types of `fields` that are in `table`. If a given parameter is empty return primary key. :param fields: list - list of fields that need to be returned :param table: sa.Table - the current table :return: list - list of the tuples `(field_name, fields_type)`
[ "Return", "data", "types", "of", "fields", "that", "are", "in", "table", ".", "If", "a", "given", "parameter", "is", "empty", "return", "primary", "key", "." ]
82e5032ef14ae8cc3c594fdd45d6c977aab1baad
https://github.com/aio-libs/aiohttp_admin/blob/82e5032ef14ae8cc3c594fdd45d6c977aab1baad/aiohttp_admin/backends/sa.py#L58-L80
train
aio-libs/aiohttp_admin
aiohttp_admin/backends/sa.py
PGResource.get_type_for_inputs
def get_type_for_inputs(table): """ Return information about table's fields in dictionary type. :param table: sa.Table - the current table :return: list - list of the dictionaries """ return [ dict( type=INPUT_TYPES.get( type(field_type.type), rc.TEXT_INPUT.value ), name=name, isPrimaryKey=(name in table.primary_key), props=None, ) for name, field_type in table.c.items() ]
python
def get_type_for_inputs(table): """ Return information about table's fields in dictionary type. :param table: sa.Table - the current table :return: list - list of the dictionaries """ return [ dict( type=INPUT_TYPES.get( type(field_type.type), rc.TEXT_INPUT.value ), name=name, isPrimaryKey=(name in table.primary_key), props=None, ) for name, field_type in table.c.items() ]
[ "def", "get_type_for_inputs", "(", "table", ")", ":", "return", "[", "dict", "(", "type", "=", "INPUT_TYPES", ".", "get", "(", "type", "(", "field_type", ".", "type", ")", ",", "rc", ".", "TEXT_INPUT", ".", "value", ")", ",", "name", "=", "name", ",", "isPrimaryKey", "=", "(", "name", "in", "table", ".", "primary_key", ")", ",", "props", "=", "None", ",", ")", "for", "name", ",", "field_type", "in", "table", ".", "c", ".", "items", "(", ")", "]" ]
Return information about table's fields in dictionary type. :param table: sa.Table - the current table :return: list - list of the dictionaries
[ "Return", "information", "about", "table", "s", "fields", "in", "dictionary", "type", "." ]
82e5032ef14ae8cc3c594fdd45d6c977aab1baad
https://github.com/aio-libs/aiohttp_admin/blob/82e5032ef14ae8cc3c594fdd45d6c977aab1baad/aiohttp_admin/backends/sa.py#L83-L99
train
aio-libs/aiohttp_admin
aiohttp_admin/__init__.py
_setup
def _setup(app, *, schema, title=None, app_key=APP_KEY, db=None): """Initialize the admin-on-rest admin""" admin = web.Application(loop=app.loop) app[app_key] = admin loader = jinja2.FileSystemLoader([TEMPLATES_ROOT, ]) aiohttp_jinja2.setup(admin, loader=loader, app_key=TEMPLATE_APP_KEY) if title: schema.title = title resources = [ init(db, info['table'], url=info['url']) for init, info in schema.resources ] admin_handler = AdminOnRestHandler( admin, resources=resources, loop=app.loop, schema=schema, ) admin['admin_handler'] = admin_handler setup_admin_on_rest_handlers(admin, admin_handler) return admin
python
def _setup(app, *, schema, title=None, app_key=APP_KEY, db=None): """Initialize the admin-on-rest admin""" admin = web.Application(loop=app.loop) app[app_key] = admin loader = jinja2.FileSystemLoader([TEMPLATES_ROOT, ]) aiohttp_jinja2.setup(admin, loader=loader, app_key=TEMPLATE_APP_KEY) if title: schema.title = title resources = [ init(db, info['table'], url=info['url']) for init, info in schema.resources ] admin_handler = AdminOnRestHandler( admin, resources=resources, loop=app.loop, schema=schema, ) admin['admin_handler'] = admin_handler setup_admin_on_rest_handlers(admin, admin_handler) return admin
[ "def", "_setup", "(", "app", ",", "*", ",", "schema", ",", "title", "=", "None", ",", "app_key", "=", "APP_KEY", ",", "db", "=", "None", ")", ":", "admin", "=", "web", ".", "Application", "(", "loop", "=", "app", ".", "loop", ")", "app", "[", "app_key", "]", "=", "admin", "loader", "=", "jinja2", ".", "FileSystemLoader", "(", "[", "TEMPLATES_ROOT", ",", "]", ")", "aiohttp_jinja2", ".", "setup", "(", "admin", ",", "loader", "=", "loader", ",", "app_key", "=", "TEMPLATE_APP_KEY", ")", "if", "title", ":", "schema", ".", "title", "=", "title", "resources", "=", "[", "init", "(", "db", ",", "info", "[", "'table'", "]", ",", "url", "=", "info", "[", "'url'", "]", ")", "for", "init", ",", "info", "in", "schema", ".", "resources", "]", "admin_handler", "=", "AdminOnRestHandler", "(", "admin", ",", "resources", "=", "resources", ",", "loop", "=", "app", ".", "loop", ",", "schema", "=", "schema", ",", ")", "admin", "[", "'admin_handler'", "]", "=", "admin_handler", "setup_admin_on_rest_handlers", "(", "admin", ",", "admin_handler", ")", "return", "admin" ]
Initialize the admin-on-rest admin
[ "Initialize", "the", "admin", "-", "on", "-", "rest", "admin" ]
82e5032ef14ae8cc3c594fdd45d6c977aab1baad
https://github.com/aio-libs/aiohttp_admin/blob/82e5032ef14ae8cc3c594fdd45d6c977aab1baad/aiohttp_admin/__init__.py#L44-L70
train
aio-libs/aiohttp_admin
aiohttp_admin/contrib/models.py
ModelAdmin.to_dict
def to_dict(self): """ Return dict with the all base information about the instance. """ data = { "name": self.name, "canEdit": self.can_edit, "canCreate": self.can_create, "canDelete": self.can_delete, "perPage": self.per_page, "showPage": self.generate_data_for_show_page(), "editPage": self.generate_data_for_edit_page(), "createPage": self.generate_data_for_create_page(), } return data
python
def to_dict(self): """ Return dict with the all base information about the instance. """ data = { "name": self.name, "canEdit": self.can_edit, "canCreate": self.can_create, "canDelete": self.can_delete, "perPage": self.per_page, "showPage": self.generate_data_for_show_page(), "editPage": self.generate_data_for_edit_page(), "createPage": self.generate_data_for_create_page(), } return data
[ "def", "to_dict", "(", "self", ")", ":", "data", "=", "{", "\"name\"", ":", "self", ".", "name", ",", "\"canEdit\"", ":", "self", ".", "can_edit", ",", "\"canCreate\"", ":", "self", ".", "can_create", ",", "\"canDelete\"", ":", "self", ".", "can_delete", ",", "\"perPage\"", ":", "self", ".", "per_page", ",", "\"showPage\"", ":", "self", ".", "generate_data_for_show_page", "(", ")", ",", "\"editPage\"", ":", "self", ".", "generate_data_for_edit_page", "(", ")", ",", "\"createPage\"", ":", "self", ".", "generate_data_for_create_page", "(", ")", ",", "}", "return", "data" ]
Return dict with the all base information about the instance.
[ "Return", "dict", "with", "the", "all", "base", "information", "about", "the", "instance", "." ]
82e5032ef14ae8cc3c594fdd45d6c977aab1baad
https://github.com/aio-libs/aiohttp_admin/blob/82e5032ef14ae8cc3c594fdd45d6c977aab1baad/aiohttp_admin/contrib/models.py#L30-L45
train
aio-libs/aiohttp_admin
aiohttp_admin/contrib/models.py
ModelAdmin.generate_data_for_edit_page
def generate_data_for_edit_page(self): """ Generate a custom representation of table's fields in dictionary type if exist edit form else use default representation. :return: dict """ if not self.can_edit: return {} if self.edit_form: return self.edit_form.to_dict() return self.generate_simple_data_page()
python
def generate_data_for_edit_page(self): """ Generate a custom representation of table's fields in dictionary type if exist edit form else use default representation. :return: dict """ if not self.can_edit: return {} if self.edit_form: return self.edit_form.to_dict() return self.generate_simple_data_page()
[ "def", "generate_data_for_edit_page", "(", "self", ")", ":", "if", "not", "self", ".", "can_edit", ":", "return", "{", "}", "if", "self", ".", "edit_form", ":", "return", "self", ".", "edit_form", ".", "to_dict", "(", ")", "return", "self", ".", "generate_simple_data_page", "(", ")" ]
Generate a custom representation of table's fields in dictionary type if exist edit form else use default representation. :return: dict
[ "Generate", "a", "custom", "representation", "of", "table", "s", "fields", "in", "dictionary", "type", "if", "exist", "edit", "form", "else", "use", "default", "representation", "." ]
82e5032ef14ae8cc3c594fdd45d6c977aab1baad
https://github.com/aio-libs/aiohttp_admin/blob/82e5032ef14ae8cc3c594fdd45d6c977aab1baad/aiohttp_admin/contrib/models.py#L55-L69
train
aio-libs/aiohttp_admin
aiohttp_admin/contrib/models.py
ModelAdmin.generate_data_for_create_page
def generate_data_for_create_page(self): """ Generate a custom representation of table's fields in dictionary type if exist create form else use default representation. :return: dict """ if not self.can_create: return {} if self.create_form: return self.create_form.to_dict() return self.generate_simple_data_page()
python
def generate_data_for_create_page(self): """ Generate a custom representation of table's fields in dictionary type if exist create form else use default representation. :return: dict """ if not self.can_create: return {} if self.create_form: return self.create_form.to_dict() return self.generate_simple_data_page()
[ "def", "generate_data_for_create_page", "(", "self", ")", ":", "if", "not", "self", ".", "can_create", ":", "return", "{", "}", "if", "self", ".", "create_form", ":", "return", "self", ".", "create_form", ".", "to_dict", "(", ")", "return", "self", ".", "generate_simple_data_page", "(", ")" ]
Generate a custom representation of table's fields in dictionary type if exist create form else use default representation. :return: dict
[ "Generate", "a", "custom", "representation", "of", "table", "s", "fields", "in", "dictionary", "type", "if", "exist", "create", "form", "else", "use", "default", "representation", "." ]
82e5032ef14ae8cc3c594fdd45d6c977aab1baad
https://github.com/aio-libs/aiohttp_admin/blob/82e5032ef14ae8cc3c594fdd45d6c977aab1baad/aiohttp_admin/contrib/models.py#L83-L96
train
aio-libs/aiohttp_admin
demos/motortwit/motortwit/views.py
SiteHandler.register
async def register(self, request): """Registers the user.""" session = await get_session(request) user_id = session.get('user_id') if user_id: return redirect(request, 'timeline') error = None form = None if request.method == 'POST': form = await request.post() user_id = await db.get_user_id(self.mongo.user, form['username']) if not form['username']: error = 'You have to enter a username' elif not form['email'] or '@' not in form['email']: error = 'You have to enter a valid email address' elif not form['password']: error = 'You have to enter a password' elif form['password'] != form['password2']: error = 'The two passwords do not match' elif user_id is not None: error = 'The username is already taken' else: await self.mongo.user.insert( {'username': form['username'], 'email': form['email'], 'pw_hash': generate_password_hash(form['password'])}) return redirect(request, 'login') return {"error": error, "form": form}
python
async def register(self, request): """Registers the user.""" session = await get_session(request) user_id = session.get('user_id') if user_id: return redirect(request, 'timeline') error = None form = None if request.method == 'POST': form = await request.post() user_id = await db.get_user_id(self.mongo.user, form['username']) if not form['username']: error = 'You have to enter a username' elif not form['email'] or '@' not in form['email']: error = 'You have to enter a valid email address' elif not form['password']: error = 'You have to enter a password' elif form['password'] != form['password2']: error = 'The two passwords do not match' elif user_id is not None: error = 'The username is already taken' else: await self.mongo.user.insert( {'username': form['username'], 'email': form['email'], 'pw_hash': generate_password_hash(form['password'])}) return redirect(request, 'login') return {"error": error, "form": form}
[ "async", "def", "register", "(", "self", ",", "request", ")", ":", "session", "=", "await", "get_session", "(", "request", ")", "user_id", "=", "session", ".", "get", "(", "'user_id'", ")", "if", "user_id", ":", "return", "redirect", "(", "request", ",", "'timeline'", ")", "error", "=", "None", "form", "=", "None", "if", "request", ".", "method", "==", "'POST'", ":", "form", "=", "await", "request", ".", "post", "(", ")", "user_id", "=", "await", "db", ".", "get_user_id", "(", "self", ".", "mongo", ".", "user", ",", "form", "[", "'username'", "]", ")", "if", "not", "form", "[", "'username'", "]", ":", "error", "=", "'You have to enter a username'", "elif", "not", "form", "[", "'email'", "]", "or", "'@'", "not", "in", "form", "[", "'email'", "]", ":", "error", "=", "'You have to enter a valid email address'", "elif", "not", "form", "[", "'password'", "]", ":", "error", "=", "'You have to enter a password'", "elif", "form", "[", "'password'", "]", "!=", "form", "[", "'password2'", "]", ":", "error", "=", "'The two passwords do not match'", "elif", "user_id", "is", "not", "None", ":", "error", "=", "'The username is already taken'", "else", ":", "await", "self", ".", "mongo", ".", "user", ".", "insert", "(", "{", "'username'", ":", "form", "[", "'username'", "]", ",", "'email'", ":", "form", "[", "'email'", "]", ",", "'pw_hash'", ":", "generate_password_hash", "(", "form", "[", "'password'", "]", ")", "}", ")", "return", "redirect", "(", "request", ",", "'login'", ")", "return", "{", "\"error\"", ":", "error", ",", "\"form\"", ":", "form", "}" ]
Registers the user.
[ "Registers", "the", "user", "." ]
82e5032ef14ae8cc3c594fdd45d6c977aab1baad
https://github.com/aio-libs/aiohttp_admin/blob/82e5032ef14ae8cc3c594fdd45d6c977aab1baad/demos/motortwit/motortwit/views.py#L116-L145
train
aio-libs/aiohttp_admin
demos/motortwit/motortwit/views.py
SiteHandler.follow_user
async def follow_user(self, request): """Adds the current user as follower of the given user.""" username = request.match_info['username'] session = await get_session(request) user_id = session.get('user_id') if not user_id: raise web.HTTPNotAuthorized() whom_id = await db.get_user_id(self.mongo.user, username) if whom_id is None: raise web.HTTPFound() await self.mongo.follower.update( {'who_id': ObjectId(user_id)}, {'$push': {'whom_id': whom_id}}, upsert=True) return redirect(request, 'user_timeline', parts={"username": username})
python
async def follow_user(self, request): """Adds the current user as follower of the given user.""" username = request.match_info['username'] session = await get_session(request) user_id = session.get('user_id') if not user_id: raise web.HTTPNotAuthorized() whom_id = await db.get_user_id(self.mongo.user, username) if whom_id is None: raise web.HTTPFound() await self.mongo.follower.update( {'who_id': ObjectId(user_id)}, {'$push': {'whom_id': whom_id}}, upsert=True) return redirect(request, 'user_timeline', parts={"username": username})
[ "async", "def", "follow_user", "(", "self", ",", "request", ")", ":", "username", "=", "request", ".", "match_info", "[", "'username'", "]", "session", "=", "await", "get_session", "(", "request", ")", "user_id", "=", "session", ".", "get", "(", "'user_id'", ")", "if", "not", "user_id", ":", "raise", "web", ".", "HTTPNotAuthorized", "(", ")", "whom_id", "=", "await", "db", ".", "get_user_id", "(", "self", ".", "mongo", ".", "user", ",", "username", ")", "if", "whom_id", "is", "None", ":", "raise", "web", ".", "HTTPFound", "(", ")", "await", "self", ".", "mongo", ".", "follower", ".", "update", "(", "{", "'who_id'", ":", "ObjectId", "(", "user_id", ")", "}", ",", "{", "'$push'", ":", "{", "'whom_id'", ":", "whom_id", "}", "}", ",", "upsert", "=", "True", ")", "return", "redirect", "(", "request", ",", "'user_timeline'", ",", "parts", "=", "{", "\"username\"", ":", "username", "}", ")" ]
Adds the current user as follower of the given user.
[ "Adds", "the", "current", "user", "as", "follower", "of", "the", "given", "user", "." ]
82e5032ef14ae8cc3c594fdd45d6c977aab1baad
https://github.com/aio-libs/aiohttp_admin/blob/82e5032ef14ae8cc3c594fdd45d6c977aab1baad/demos/motortwit/motortwit/views.py#L147-L165
train
aio-libs/aiohttp_admin
demos/motortwit/motortwit/views.py
SiteHandler.add_message
async def add_message(self, request): """Registers a new message for the user.""" session = await get_session(request) user_id = session.get('user_id') if not user_id: raise web.HTTPNotAuthorized() form = await request.post() if form.get('text'): user = await self.mongo.user.find_one( {'_id': ObjectId(session['user_id'])}, {'email': 1, 'username': 1}) await self.mongo.message.insert( {'author_id': ObjectId(user_id), 'email': user['email'], 'username': user['username'], 'text': form['text'], 'pub_date': datetime.datetime.utcnow()}) return redirect(request, 'timeline')
python
async def add_message(self, request): """Registers a new message for the user.""" session = await get_session(request) user_id = session.get('user_id') if not user_id: raise web.HTTPNotAuthorized() form = await request.post() if form.get('text'): user = await self.mongo.user.find_one( {'_id': ObjectId(session['user_id'])}, {'email': 1, 'username': 1}) await self.mongo.message.insert( {'author_id': ObjectId(user_id), 'email': user['email'], 'username': user['username'], 'text': form['text'], 'pub_date': datetime.datetime.utcnow()}) return redirect(request, 'timeline')
[ "async", "def", "add_message", "(", "self", ",", "request", ")", ":", "session", "=", "await", "get_session", "(", "request", ")", "user_id", "=", "session", ".", "get", "(", "'user_id'", ")", "if", "not", "user_id", ":", "raise", "web", ".", "HTTPNotAuthorized", "(", ")", "form", "=", "await", "request", ".", "post", "(", ")", "if", "form", ".", "get", "(", "'text'", ")", ":", "user", "=", "await", "self", ".", "mongo", ".", "user", ".", "find_one", "(", "{", "'_id'", ":", "ObjectId", "(", "session", "[", "'user_id'", "]", ")", "}", ",", "{", "'email'", ":", "1", ",", "'username'", ":", "1", "}", ")", "await", "self", ".", "mongo", ".", "message", ".", "insert", "(", "{", "'author_id'", ":", "ObjectId", "(", "user_id", ")", ",", "'email'", ":", "user", "[", "'email'", "]", ",", "'username'", ":", "user", "[", "'username'", "]", ",", "'text'", ":", "form", "[", "'text'", "]", ",", "'pub_date'", ":", "datetime", ".", "datetime", ".", "utcnow", "(", ")", "}", ")", "return", "redirect", "(", "request", ",", "'timeline'", ")" ]
Registers a new message for the user.
[ "Registers", "a", "new", "message", "for", "the", "user", "." ]
82e5032ef14ae8cc3c594fdd45d6c977aab1baad
https://github.com/aio-libs/aiohttp_admin/blob/82e5032ef14ae8cc3c594fdd45d6c977aab1baad/demos/motortwit/motortwit/views.py#L184-L203
train
aio-libs/aiohttp_admin
demos/motortwit/motortwit/utils.py
robo_avatar_url
def robo_avatar_url(user_data, size=80): """Return the gravatar image for the given email address.""" hash = md5(str(user_data).strip().lower().encode('utf-8')).hexdigest() url = "https://robohash.org/{hash}.png?size={size}x{size}".format( hash=hash, size=size) return url
python
def robo_avatar_url(user_data, size=80): """Return the gravatar image for the given email address.""" hash = md5(str(user_data).strip().lower().encode('utf-8')).hexdigest() url = "https://robohash.org/{hash}.png?size={size}x{size}".format( hash=hash, size=size) return url
[ "def", "robo_avatar_url", "(", "user_data", ",", "size", "=", "80", ")", ":", "hash", "=", "md5", "(", "str", "(", "user_data", ")", ".", "strip", "(", ")", ".", "lower", "(", ")", ".", "encode", "(", "'utf-8'", ")", ")", ".", "hexdigest", "(", ")", "url", "=", "\"https://robohash.org/{hash}.png?size={size}x{size}\"", ".", "format", "(", "hash", "=", "hash", ",", "size", "=", "size", ")", "return", "url" ]
Return the gravatar image for the given email address.
[ "Return", "the", "gravatar", "image", "for", "the", "given", "email", "address", "." ]
82e5032ef14ae8cc3c594fdd45d6c977aab1baad
https://github.com/aio-libs/aiohttp_admin/blob/82e5032ef14ae8cc3c594fdd45d6c977aab1baad/demos/motortwit/motortwit/utils.py#L27-L32
train
ponty/PyVirtualDisplay
pyvirtualdisplay/smartdisplay.py
SmartDisplay.waitgrab
def waitgrab(self, timeout=60, autocrop=True, cb_imgcheck=None): '''start process and create screenshot. Repeat screenshot until it is not empty and cb_imgcheck callback function returns True for current screenshot. :param autocrop: True -> crop screenshot :param timeout: int :param cb_imgcheck: None or callback for testing img, True = accept img, False = reject img ''' t = 0 sleep_time = 0.3 # for fast windows repeat_time = 1 while 1: log.debug('sleeping %s secs' % str(sleep_time)) time.sleep(sleep_time) t += sleep_time img = self.grab(autocrop=autocrop) if img: if not cb_imgcheck: break if cb_imgcheck(img): break sleep_time = repeat_time repeat_time += 1 # progressive if t > timeout: msg = 'Timeout! elapsed time:%s timeout:%s ' % (t, timeout) raise DisplayTimeoutError(msg) break log.debug('screenshot is empty, next try..') assert img # if not img: # log.debug('screenshot is empty!') return img
python
def waitgrab(self, timeout=60, autocrop=True, cb_imgcheck=None): '''start process and create screenshot. Repeat screenshot until it is not empty and cb_imgcheck callback function returns True for current screenshot. :param autocrop: True -> crop screenshot :param timeout: int :param cb_imgcheck: None or callback for testing img, True = accept img, False = reject img ''' t = 0 sleep_time = 0.3 # for fast windows repeat_time = 1 while 1: log.debug('sleeping %s secs' % str(sleep_time)) time.sleep(sleep_time) t += sleep_time img = self.grab(autocrop=autocrop) if img: if not cb_imgcheck: break if cb_imgcheck(img): break sleep_time = repeat_time repeat_time += 1 # progressive if t > timeout: msg = 'Timeout! elapsed time:%s timeout:%s ' % (t, timeout) raise DisplayTimeoutError(msg) break log.debug('screenshot is empty, next try..') assert img # if not img: # log.debug('screenshot is empty!') return img
[ "def", "waitgrab", "(", "self", ",", "timeout", "=", "60", ",", "autocrop", "=", "True", ",", "cb_imgcheck", "=", "None", ")", ":", "t", "=", "0", "sleep_time", "=", "0.3", "# for fast windows", "repeat_time", "=", "1", "while", "1", ":", "log", ".", "debug", "(", "'sleeping %s secs'", "%", "str", "(", "sleep_time", ")", ")", "time", ".", "sleep", "(", "sleep_time", ")", "t", "+=", "sleep_time", "img", "=", "self", ".", "grab", "(", "autocrop", "=", "autocrop", ")", "if", "img", ":", "if", "not", "cb_imgcheck", ":", "break", "if", "cb_imgcheck", "(", "img", ")", ":", "break", "sleep_time", "=", "repeat_time", "repeat_time", "+=", "1", "# progressive", "if", "t", ">", "timeout", ":", "msg", "=", "'Timeout! elapsed time:%s timeout:%s '", "%", "(", "t", ",", "timeout", ")", "raise", "DisplayTimeoutError", "(", "msg", ")", "break", "log", ".", "debug", "(", "'screenshot is empty, next try..'", ")", "assert", "img", "# if not img:", "# log.debug('screenshot is empty!')", "return", "img" ]
start process and create screenshot. Repeat screenshot until it is not empty and cb_imgcheck callback function returns True for current screenshot. :param autocrop: True -> crop screenshot :param timeout: int :param cb_imgcheck: None or callback for testing img, True = accept img, False = reject img
[ "start", "process", "and", "create", "screenshot", ".", "Repeat", "screenshot", "until", "it", "is", "not", "empty", "and", "cb_imgcheck", "callback", "function", "returns", "True", "for", "current", "screenshot", "." ]
903841f5ef13bf162be6fdd22daa5c349af45d67
https://github.com/ponty/PyVirtualDisplay/blob/903841f5ef13bf162be6fdd22daa5c349af45d67/pyvirtualdisplay/smartdisplay.py#L54-L90
train
ponty/PyVirtualDisplay
pyvirtualdisplay/abstractdisplay.py
AbstractDisplay._setup_xauth
def _setup_xauth(self): ''' Set up the Xauthority file and the XAUTHORITY environment variable. ''' handle, filename = tempfile.mkstemp(prefix='PyVirtualDisplay.', suffix='.Xauthority') self._xauth_filename = filename os.close(handle) # Save old environment self._old_xauth = {} self._old_xauth['AUTHFILE'] = os.getenv('AUTHFILE') self._old_xauth['XAUTHORITY'] = os.getenv('XAUTHORITY') os.environ['AUTHFILE'] = os.environ['XAUTHORITY'] = filename cookie = xauth.generate_mcookie() xauth.call('add', self.new_display_var, '.', cookie)
python
def _setup_xauth(self): ''' Set up the Xauthority file and the XAUTHORITY environment variable. ''' handle, filename = tempfile.mkstemp(prefix='PyVirtualDisplay.', suffix='.Xauthority') self._xauth_filename = filename os.close(handle) # Save old environment self._old_xauth = {} self._old_xauth['AUTHFILE'] = os.getenv('AUTHFILE') self._old_xauth['XAUTHORITY'] = os.getenv('XAUTHORITY') os.environ['AUTHFILE'] = os.environ['XAUTHORITY'] = filename cookie = xauth.generate_mcookie() xauth.call('add', self.new_display_var, '.', cookie)
[ "def", "_setup_xauth", "(", "self", ")", ":", "handle", ",", "filename", "=", "tempfile", ".", "mkstemp", "(", "prefix", "=", "'PyVirtualDisplay.'", ",", "suffix", "=", "'.Xauthority'", ")", "self", ".", "_xauth_filename", "=", "filename", "os", ".", "close", "(", "handle", ")", "# Save old environment", "self", ".", "_old_xauth", "=", "{", "}", "self", ".", "_old_xauth", "[", "'AUTHFILE'", "]", "=", "os", ".", "getenv", "(", "'AUTHFILE'", ")", "self", ".", "_old_xauth", "[", "'XAUTHORITY'", "]", "=", "os", ".", "getenv", "(", "'XAUTHORITY'", ")", "os", ".", "environ", "[", "'AUTHFILE'", "]", "=", "os", ".", "environ", "[", "'XAUTHORITY'", "]", "=", "filename", "cookie", "=", "xauth", ".", "generate_mcookie", "(", ")", "xauth", ".", "call", "(", "'add'", ",", "self", ".", "new_display_var", ",", "'.'", ",", "cookie", ")" ]
Set up the Xauthority file and the XAUTHORITY environment variable.
[ "Set", "up", "the", "Xauthority", "file", "and", "the", "XAUTHORITY", "environment", "variable", "." ]
903841f5ef13bf162be6fdd22daa5c349af45d67
https://github.com/ponty/PyVirtualDisplay/blob/903841f5ef13bf162be6fdd22daa5c349af45d67/pyvirtualdisplay/abstractdisplay.py#L154-L169
train
ponty/PyVirtualDisplay
pyvirtualdisplay/abstractdisplay.py
AbstractDisplay._clear_xauth
def _clear_xauth(self): ''' Clear the Xauthority file and restore the environment variables. ''' os.remove(self._xauth_filename) for varname in ['AUTHFILE', 'XAUTHORITY']: if self._old_xauth[varname] is None: del os.environ[varname] else: os.environ[varname] = self._old_xauth[varname] self._old_xauth = None
python
def _clear_xauth(self): ''' Clear the Xauthority file and restore the environment variables. ''' os.remove(self._xauth_filename) for varname in ['AUTHFILE', 'XAUTHORITY']: if self._old_xauth[varname] is None: del os.environ[varname] else: os.environ[varname] = self._old_xauth[varname] self._old_xauth = None
[ "def", "_clear_xauth", "(", "self", ")", ":", "os", ".", "remove", "(", "self", ".", "_xauth_filename", ")", "for", "varname", "in", "[", "'AUTHFILE'", ",", "'XAUTHORITY'", "]", ":", "if", "self", ".", "_old_xauth", "[", "varname", "]", "is", "None", ":", "del", "os", ".", "environ", "[", "varname", "]", "else", ":", "os", ".", "environ", "[", "varname", "]", "=", "self", ".", "_old_xauth", "[", "varname", "]", "self", ".", "_old_xauth", "=", "None" ]
Clear the Xauthority file and restore the environment variables.
[ "Clear", "the", "Xauthority", "file", "and", "restore", "the", "environment", "variables", "." ]
903841f5ef13bf162be6fdd22daa5c349af45d67
https://github.com/ponty/PyVirtualDisplay/blob/903841f5ef13bf162be6fdd22daa5c349af45d67/pyvirtualdisplay/abstractdisplay.py#L171-L181
train
jasonrollins/shareplum
shareplum/shareplum.py
Office365.GetCookies
def GetCookies(self): """ Grabs the cookies form your Office Sharepoint site and uses it as Authentication for the rest of the calls """ sectoken = self.GetSecurityToken(self.Username, self.Password) url = self.share_point_site+ '/_forms/default.aspx?wa=wsignin1.0' response = requests.post(url, data=sectoken) return response.cookies
python
def GetCookies(self): """ Grabs the cookies form your Office Sharepoint site and uses it as Authentication for the rest of the calls """ sectoken = self.GetSecurityToken(self.Username, self.Password) url = self.share_point_site+ '/_forms/default.aspx?wa=wsignin1.0' response = requests.post(url, data=sectoken) return response.cookies
[ "def", "GetCookies", "(", "self", ")", ":", "sectoken", "=", "self", ".", "GetSecurityToken", "(", "self", ".", "Username", ",", "self", ".", "Password", ")", "url", "=", "self", ".", "share_point_site", "+", "'/_forms/default.aspx?wa=wsignin1.0'", "response", "=", "requests", ".", "post", "(", "url", ",", "data", "=", "sectoken", ")", "return", "response", ".", "cookies" ]
Grabs the cookies form your Office Sharepoint site and uses it as Authentication for the rest of the calls
[ "Grabs", "the", "cookies", "form", "your", "Office", "Sharepoint", "site", "and", "uses", "it", "as", "Authentication", "for", "the", "rest", "of", "the", "calls" ]
404f320808912619920e2d787f2c4387225a14e0
https://github.com/jasonrollins/shareplum/blob/404f320808912619920e2d787f2c4387225a14e0/shareplum/shareplum.py#L70-L78
train
jasonrollins/shareplum
shareplum/shareplum.py
Site.DeleteList
def DeleteList(self, listName): """Delete a List with given name""" # Build Request soap_request = soap('DeleteList') soap_request.add_parameter('listName', listName) self.last_request = str(soap_request) # Send Request response = self._session.post(url=self._url('Lists'), headers=self._headers('DeleteList'), data=str(soap_request), verify=self._verify_ssl, timeout=self.timeout) # Parse Request if response == 200: return response.text else: return response
python
def DeleteList(self, listName): """Delete a List with given name""" # Build Request soap_request = soap('DeleteList') soap_request.add_parameter('listName', listName) self.last_request = str(soap_request) # Send Request response = self._session.post(url=self._url('Lists'), headers=self._headers('DeleteList'), data=str(soap_request), verify=self._verify_ssl, timeout=self.timeout) # Parse Request if response == 200: return response.text else: return response
[ "def", "DeleteList", "(", "self", ",", "listName", ")", ":", "# Build Request", "soap_request", "=", "soap", "(", "'DeleteList'", ")", "soap_request", ".", "add_parameter", "(", "'listName'", ",", "listName", ")", "self", ".", "last_request", "=", "str", "(", "soap_request", ")", "# Send Request", "response", "=", "self", ".", "_session", ".", "post", "(", "url", "=", "self", ".", "_url", "(", "'Lists'", ")", ",", "headers", "=", "self", ".", "_headers", "(", "'DeleteList'", ")", ",", "data", "=", "str", "(", "soap_request", ")", ",", "verify", "=", "self", ".", "_verify_ssl", ",", "timeout", "=", "self", ".", "timeout", ")", "# Parse Request", "if", "response", "==", "200", ":", "return", "response", ".", "text", "else", ":", "return", "response" ]
Delete a List with given name
[ "Delete", "a", "List", "with", "given", "name" ]
404f320808912619920e2d787f2c4387225a14e0
https://github.com/jasonrollins/shareplum/blob/404f320808912619920e2d787f2c4387225a14e0/shareplum/shareplum.py#L207-L226
train
jasonrollins/shareplum
shareplum/shareplum.py
Site.GetListCollection
def GetListCollection(self): """Returns List information for current Site""" # Build Request soap_request = soap('GetListCollection') self.last_request = str(soap_request) # Send Request response = self._session.post(url=self._url('SiteData'), headers=self._headers('GetListCollection'), data=str(soap_request), verify=self._verify_ssl, timeout=self.timeout) # Parse Response if response.status_code == 200: envelope = etree.fromstring(response.text.encode('utf-8'), parser=etree.XMLParser(huge_tree=self.huge_tree)) result = envelope[0][0][0].text lists = envelope[0][0][1] data = [] for _list in lists: _list_data = {} for item in _list: key = item.tag.replace('{http://schemas.microsoft.com/sharepoint/soap/}', '') value = item.text _list_data[key] = value data.append(_list_data) return data else: return response
python
def GetListCollection(self): """Returns List information for current Site""" # Build Request soap_request = soap('GetListCollection') self.last_request = str(soap_request) # Send Request response = self._session.post(url=self._url('SiteData'), headers=self._headers('GetListCollection'), data=str(soap_request), verify=self._verify_ssl, timeout=self.timeout) # Parse Response if response.status_code == 200: envelope = etree.fromstring(response.text.encode('utf-8'), parser=etree.XMLParser(huge_tree=self.huge_tree)) result = envelope[0][0][0].text lists = envelope[0][0][1] data = [] for _list in lists: _list_data = {} for item in _list: key = item.tag.replace('{http://schemas.microsoft.com/sharepoint/soap/}', '') value = item.text _list_data[key] = value data.append(_list_data) return data else: return response
[ "def", "GetListCollection", "(", "self", ")", ":", "# Build Request", "soap_request", "=", "soap", "(", "'GetListCollection'", ")", "self", ".", "last_request", "=", "str", "(", "soap_request", ")", "# Send Request", "response", "=", "self", ".", "_session", ".", "post", "(", "url", "=", "self", ".", "_url", "(", "'SiteData'", ")", ",", "headers", "=", "self", ".", "_headers", "(", "'GetListCollection'", ")", ",", "data", "=", "str", "(", "soap_request", ")", ",", "verify", "=", "self", ".", "_verify_ssl", ",", "timeout", "=", "self", ".", "timeout", ")", "# Parse Response", "if", "response", ".", "status_code", "==", "200", ":", "envelope", "=", "etree", ".", "fromstring", "(", "response", ".", "text", ".", "encode", "(", "'utf-8'", ")", ",", "parser", "=", "etree", ".", "XMLParser", "(", "huge_tree", "=", "self", ".", "huge_tree", ")", ")", "result", "=", "envelope", "[", "0", "]", "[", "0", "]", "[", "0", "]", ".", "text", "lists", "=", "envelope", "[", "0", "]", "[", "0", "]", "[", "1", "]", "data", "=", "[", "]", "for", "_list", "in", "lists", ":", "_list_data", "=", "{", "}", "for", "item", "in", "_list", ":", "key", "=", "item", ".", "tag", ".", "replace", "(", "'{http://schemas.microsoft.com/sharepoint/soap/}'", ",", "''", ")", "value", "=", "item", ".", "text", "_list_data", "[", "key", "]", "=", "value", "data", ".", "append", "(", "_list_data", ")", "return", "data", "else", ":", "return", "response" ]
Returns List information for current Site
[ "Returns", "List", "information", "for", "current", "Site" ]
404f320808912619920e2d787f2c4387225a14e0
https://github.com/jasonrollins/shareplum/blob/404f320808912619920e2d787f2c4387225a14e0/shareplum/shareplum.py#L228-L257
train
jasonrollins/shareplum
shareplum/shareplum.py
_List._convert_to_internal
def _convert_to_internal(self, data): """From 'Column Title' to 'Column_x0020_Title'""" for _dict in data: keys = list(_dict.keys())[:] for key in keys: if key not in self._disp_cols: raise Exception(key + ' not a column in current List.') _dict[self._disp_cols[key]['name']] = self._sp_type(key, _dict.pop(key))
python
def _convert_to_internal(self, data): """From 'Column Title' to 'Column_x0020_Title'""" for _dict in data: keys = list(_dict.keys())[:] for key in keys: if key not in self._disp_cols: raise Exception(key + ' not a column in current List.') _dict[self._disp_cols[key]['name']] = self._sp_type(key, _dict.pop(key))
[ "def", "_convert_to_internal", "(", "self", ",", "data", ")", ":", "for", "_dict", "in", "data", ":", "keys", "=", "list", "(", "_dict", ".", "keys", "(", ")", ")", "[", ":", "]", "for", "key", "in", "keys", ":", "if", "key", "not", "in", "self", ".", "_disp_cols", ":", "raise", "Exception", "(", "key", "+", "' not a column in current List.'", ")", "_dict", "[", "self", ".", "_disp_cols", "[", "key", "]", "[", "'name'", "]", "]", "=", "self", ".", "_sp_type", "(", "key", ",", "_dict", ".", "pop", "(", "key", ")", ")" ]
From 'Column Title' to 'Column_x0020_Title
[ "From", "Column", "Title", "to", "Column_x0020_Title" ]
404f320808912619920e2d787f2c4387225a14e0
https://github.com/jasonrollins/shareplum/blob/404f320808912619920e2d787f2c4387225a14e0/shareplum/shareplum.py#L358-L365
train
jasonrollins/shareplum
shareplum/shareplum.py
_List._convert_to_display
def _convert_to_display(self, data): """From 'Column_x0020_Title' to 'Column Title'""" for _dict in data: keys = list(_dict.keys())[:] for key in keys: if key not in self._sp_cols: raise Exception(key + ' not a column in current List.') _dict[self._sp_cols[key]['name']] = self._python_type(key, _dict.pop(key))
python
def _convert_to_display(self, data): """From 'Column_x0020_Title' to 'Column Title'""" for _dict in data: keys = list(_dict.keys())[:] for key in keys: if key not in self._sp_cols: raise Exception(key + ' not a column in current List.') _dict[self._sp_cols[key]['name']] = self._python_type(key, _dict.pop(key))
[ "def", "_convert_to_display", "(", "self", ",", "data", ")", ":", "for", "_dict", "in", "data", ":", "keys", "=", "list", "(", "_dict", ".", "keys", "(", ")", ")", "[", ":", "]", "for", "key", "in", "keys", ":", "if", "key", "not", "in", "self", ".", "_sp_cols", ":", "raise", "Exception", "(", "key", "+", "' not a column in current List.'", ")", "_dict", "[", "self", ".", "_sp_cols", "[", "key", "]", "[", "'name'", "]", "]", "=", "self", ".", "_python_type", "(", "key", ",", "_dict", ".", "pop", "(", "key", ")", ")" ]
From 'Column_x0020_Title' to 'Column Title
[ "From", "Column_x0020_Title", "to", "Column", "Title" ]
404f320808912619920e2d787f2c4387225a14e0
https://github.com/jasonrollins/shareplum/blob/404f320808912619920e2d787f2c4387225a14e0/shareplum/shareplum.py#L367-L374
train
jasonrollins/shareplum
shareplum/shareplum.py
_List.GetView
def GetView(self, viewname): """Get Info on View Name """ # Build Request soap_request = soap('GetView') soap_request.add_parameter('listName', self.listName) if viewname == None: views = self.GetViewCollection() for view in views: if 'DefaultView' in view: if views[view]['DefaultView'] == 'TRUE': viewname = view break if self.listName not in ['UserInfo', 'User Information List']: soap_request.add_parameter('viewName', self.views[viewname]['Name'][1:-1]) else: soap_request.add_parameter('viewName', viewname) self.last_request = str(soap_request) # Send Request response = self._session.post(url=self._url('Views'), headers=self._headers('GetView'), data=str(soap_request), verify=self._verify_ssl, timeout=self.timeout) # Parse Response if response.status_code == 200: envelope = etree.fromstring(response.text.encode('utf-8'), parser=etree.XMLParser(huge_tree=self.huge_tree)) view = envelope[0][0][0][0] info = {key: value for (key, value) in view.items()} fields = [x.items()[0][1] for x in view[1]] return {'info': info, 'fields': fields} else: raise Exception("ERROR:", response.status_code, response.text)
python
def GetView(self, viewname): """Get Info on View Name """ # Build Request soap_request = soap('GetView') soap_request.add_parameter('listName', self.listName) if viewname == None: views = self.GetViewCollection() for view in views: if 'DefaultView' in view: if views[view]['DefaultView'] == 'TRUE': viewname = view break if self.listName not in ['UserInfo', 'User Information List']: soap_request.add_parameter('viewName', self.views[viewname]['Name'][1:-1]) else: soap_request.add_parameter('viewName', viewname) self.last_request = str(soap_request) # Send Request response = self._session.post(url=self._url('Views'), headers=self._headers('GetView'), data=str(soap_request), verify=self._verify_ssl, timeout=self.timeout) # Parse Response if response.status_code == 200: envelope = etree.fromstring(response.text.encode('utf-8'), parser=etree.XMLParser(huge_tree=self.huge_tree)) view = envelope[0][0][0][0] info = {key: value for (key, value) in view.items()} fields = [x.items()[0][1] for x in view[1]] return {'info': info, 'fields': fields} else: raise Exception("ERROR:", response.status_code, response.text)
[ "def", "GetView", "(", "self", ",", "viewname", ")", ":", "# Build Request", "soap_request", "=", "soap", "(", "'GetView'", ")", "soap_request", ".", "add_parameter", "(", "'listName'", ",", "self", ".", "listName", ")", "if", "viewname", "==", "None", ":", "views", "=", "self", ".", "GetViewCollection", "(", ")", "for", "view", "in", "views", ":", "if", "'DefaultView'", "in", "view", ":", "if", "views", "[", "view", "]", "[", "'DefaultView'", "]", "==", "'TRUE'", ":", "viewname", "=", "view", "break", "if", "self", ".", "listName", "not", "in", "[", "'UserInfo'", ",", "'User Information List'", "]", ":", "soap_request", ".", "add_parameter", "(", "'viewName'", ",", "self", ".", "views", "[", "viewname", "]", "[", "'Name'", "]", "[", "1", ":", "-", "1", "]", ")", "else", ":", "soap_request", ".", "add_parameter", "(", "'viewName'", ",", "viewname", ")", "self", ".", "last_request", "=", "str", "(", "soap_request", ")", "# Send Request", "response", "=", "self", ".", "_session", ".", "post", "(", "url", "=", "self", ".", "_url", "(", "'Views'", ")", ",", "headers", "=", "self", ".", "_headers", "(", "'GetView'", ")", ",", "data", "=", "str", "(", "soap_request", ")", ",", "verify", "=", "self", ".", "_verify_ssl", ",", "timeout", "=", "self", ".", "timeout", ")", "# Parse Response", "if", "response", ".", "status_code", "==", "200", ":", "envelope", "=", "etree", ".", "fromstring", "(", "response", ".", "text", ".", "encode", "(", "'utf-8'", ")", ",", "parser", "=", "etree", ".", "XMLParser", "(", "huge_tree", "=", "self", ".", "huge_tree", ")", ")", "view", "=", "envelope", "[", "0", "]", "[", "0", "]", "[", "0", "]", "[", "0", "]", "info", "=", "{", "key", ":", "value", "for", "(", "key", ",", "value", ")", "in", "view", ".", "items", "(", ")", "}", "fields", "=", "[", "x", ".", "items", "(", ")", "[", "0", "]", "[", "1", "]", "for", "x", "in", "view", "[", "1", "]", "]", "return", "{", "'info'", ":", "info", ",", "'fields'", ":", "fields", "}", "else", ":", "raise", "Exception", "(", "\"ERROR:\"", ",", "response", ".", "status_code", ",", "response", ".", "text", ")" ]
Get Info on View Name
[ "Get", "Info", "on", "View", "Name" ]
404f320808912619920e2d787f2c4387225a14e0
https://github.com/jasonrollins/shareplum/blob/404f320808912619920e2d787f2c4387225a14e0/shareplum/shareplum.py#L562-L600
train
jasonrollins/shareplum
shareplum/shareplum.py
_List.UpdateListItems
def UpdateListItems(self, data, kind): """Update List Items kind = 'New', 'Update', or 'Delete' New: Provide data like so: data = [{'Title': 'New Title', 'Col1': 'New Value'}] Update: Provide data like so: data = [{'ID': 23, 'Title': 'Updated Title'}, {'ID': 28, 'Col1': 'Updated Value'}] Delete: Just provied a list of ID's data = [23, 28] """ if type(data) != list: raise Exception('data must be a list of dictionaries') # Build Request soap_request = soap('UpdateListItems') soap_request.add_parameter('listName', self.listName) if kind != 'Delete': self._convert_to_internal(data) soap_request.add_actions(data, kind) self.last_request = str(soap_request) # Send Request response = self._session.post(url=self._url('Lists'), headers=self._headers('UpdateListItems'), data=str(soap_request), verify=self._verify_ssl, timeout=self.timeout) # Parse Response if response.status_code == 200: envelope = etree.fromstring(response.text.encode('utf-8'), parser=etree.XMLParser(huge_tree=self.huge_tree)) results = envelope[0][0][0][0] data = {} for result in results: if result.text != '0x00000000' and result[0].text != '0x00000000': data[result.attrib['ID']] = (result[0].text, result[1].text) else: data[result.attrib['ID']] = result[0].text return data else: return response
python
def UpdateListItems(self, data, kind): """Update List Items kind = 'New', 'Update', or 'Delete' New: Provide data like so: data = [{'Title': 'New Title', 'Col1': 'New Value'}] Update: Provide data like so: data = [{'ID': 23, 'Title': 'Updated Title'}, {'ID': 28, 'Col1': 'Updated Value'}] Delete: Just provied a list of ID's data = [23, 28] """ if type(data) != list: raise Exception('data must be a list of dictionaries') # Build Request soap_request = soap('UpdateListItems') soap_request.add_parameter('listName', self.listName) if kind != 'Delete': self._convert_to_internal(data) soap_request.add_actions(data, kind) self.last_request = str(soap_request) # Send Request response = self._session.post(url=self._url('Lists'), headers=self._headers('UpdateListItems'), data=str(soap_request), verify=self._verify_ssl, timeout=self.timeout) # Parse Response if response.status_code == 200: envelope = etree.fromstring(response.text.encode('utf-8'), parser=etree.XMLParser(huge_tree=self.huge_tree)) results = envelope[0][0][0][0] data = {} for result in results: if result.text != '0x00000000' and result[0].text != '0x00000000': data[result.attrib['ID']] = (result[0].text, result[1].text) else: data[result.attrib['ID']] = result[0].text return data else: return response
[ "def", "UpdateListItems", "(", "self", ",", "data", ",", "kind", ")", ":", "if", "type", "(", "data", ")", "!=", "list", ":", "raise", "Exception", "(", "'data must be a list of dictionaries'", ")", "# Build Request", "soap_request", "=", "soap", "(", "'UpdateListItems'", ")", "soap_request", ".", "add_parameter", "(", "'listName'", ",", "self", ".", "listName", ")", "if", "kind", "!=", "'Delete'", ":", "self", ".", "_convert_to_internal", "(", "data", ")", "soap_request", ".", "add_actions", "(", "data", ",", "kind", ")", "self", ".", "last_request", "=", "str", "(", "soap_request", ")", "# Send Request", "response", "=", "self", ".", "_session", ".", "post", "(", "url", "=", "self", ".", "_url", "(", "'Lists'", ")", ",", "headers", "=", "self", ".", "_headers", "(", "'UpdateListItems'", ")", ",", "data", "=", "str", "(", "soap_request", ")", ",", "verify", "=", "self", ".", "_verify_ssl", ",", "timeout", "=", "self", ".", "timeout", ")", "# Parse Response", "if", "response", ".", "status_code", "==", "200", ":", "envelope", "=", "etree", ".", "fromstring", "(", "response", ".", "text", ".", "encode", "(", "'utf-8'", ")", ",", "parser", "=", "etree", ".", "XMLParser", "(", "huge_tree", "=", "self", ".", "huge_tree", ")", ")", "results", "=", "envelope", "[", "0", "]", "[", "0", "]", "[", "0", "]", "[", "0", "]", "data", "=", "{", "}", "for", "result", "in", "results", ":", "if", "result", ".", "text", "!=", "'0x00000000'", "and", "result", "[", "0", "]", ".", "text", "!=", "'0x00000000'", ":", "data", "[", "result", ".", "attrib", "[", "'ID'", "]", "]", "=", "(", "result", "[", "0", "]", ".", "text", ",", "result", "[", "1", "]", ".", "text", ")", "else", ":", "data", "[", "result", ".", "attrib", "[", "'ID'", "]", "]", "=", "result", "[", "0", "]", ".", "text", "return", "data", "else", ":", "return", "response" ]
Update List Items kind = 'New', 'Update', or 'Delete' New: Provide data like so: data = [{'Title': 'New Title', 'Col1': 'New Value'}] Update: Provide data like so: data = [{'ID': 23, 'Title': 'Updated Title'}, {'ID': 28, 'Col1': 'Updated Value'}] Delete: Just provied a list of ID's data = [23, 28]
[ "Update", "List", "Items", "kind", "=", "New", "Update", "or", "Delete" ]
404f320808912619920e2d787f2c4387225a14e0
https://github.com/jasonrollins/shareplum/blob/404f320808912619920e2d787f2c4387225a14e0/shareplum/shareplum.py#L658-L704
train
jasonrollins/shareplum
shareplum/shareplum.py
_List.GetAttachmentCollection
def GetAttachmentCollection(self, _id): """Get Attachments for given List Item ID""" # Build Request soap_request = soap('GetAttachmentCollection') soap_request.add_parameter('listName', self.listName) soap_request.add_parameter('listItemID', _id) self.last_request = str(soap_request) # Send Request response = self._session.post(url=self._url('Lists'), headers=self._headers('GetAttachmentCollection'), data=str(soap_request), verify=False, timeout=self.timeout) # Parse Request if response.status_code == 200: envelope = etree.fromstring(response.text.encode('utf-8'), parser=etree.XMLParser(huge_tree=self.huge_tree)) attaches = envelope[0][0][0][0] attachments = [] for attachment in attaches.getchildren(): attachments.append(attachment.text) return attachments else: return response
python
def GetAttachmentCollection(self, _id): """Get Attachments for given List Item ID""" # Build Request soap_request = soap('GetAttachmentCollection') soap_request.add_parameter('listName', self.listName) soap_request.add_parameter('listItemID', _id) self.last_request = str(soap_request) # Send Request response = self._session.post(url=self._url('Lists'), headers=self._headers('GetAttachmentCollection'), data=str(soap_request), verify=False, timeout=self.timeout) # Parse Request if response.status_code == 200: envelope = etree.fromstring(response.text.encode('utf-8'), parser=etree.XMLParser(huge_tree=self.huge_tree)) attaches = envelope[0][0][0][0] attachments = [] for attachment in attaches.getchildren(): attachments.append(attachment.text) return attachments else: return response
[ "def", "GetAttachmentCollection", "(", "self", ",", "_id", ")", ":", "# Build Request", "soap_request", "=", "soap", "(", "'GetAttachmentCollection'", ")", "soap_request", ".", "add_parameter", "(", "'listName'", ",", "self", ".", "listName", ")", "soap_request", ".", "add_parameter", "(", "'listItemID'", ",", "_id", ")", "self", ".", "last_request", "=", "str", "(", "soap_request", ")", "# Send Request", "response", "=", "self", ".", "_session", ".", "post", "(", "url", "=", "self", ".", "_url", "(", "'Lists'", ")", ",", "headers", "=", "self", ".", "_headers", "(", "'GetAttachmentCollection'", ")", ",", "data", "=", "str", "(", "soap_request", ")", ",", "verify", "=", "False", ",", "timeout", "=", "self", ".", "timeout", ")", "# Parse Request", "if", "response", ".", "status_code", "==", "200", ":", "envelope", "=", "etree", ".", "fromstring", "(", "response", ".", "text", ".", "encode", "(", "'utf-8'", ")", ",", "parser", "=", "etree", ".", "XMLParser", "(", "huge_tree", "=", "self", ".", "huge_tree", ")", ")", "attaches", "=", "envelope", "[", "0", "]", "[", "0", "]", "[", "0", "]", "[", "0", "]", "attachments", "=", "[", "]", "for", "attachment", "in", "attaches", ".", "getchildren", "(", ")", ":", "attachments", ".", "append", "(", "attachment", ".", "text", ")", "return", "attachments", "else", ":", "return", "response" ]
Get Attachments for given List Item ID
[ "Get", "Attachments", "for", "given", "List", "Item", "ID" ]
404f320808912619920e2d787f2c4387225a14e0
https://github.com/jasonrollins/shareplum/blob/404f320808912619920e2d787f2c4387225a14e0/shareplum/shareplum.py#L706-L731
train
jasonrollins/shareplum
shareplum/ListDict.py
changes
def changes(new_cmp_dict, old_cmp_dict, id_column, columns): """Return a list dict of the changes of the rows that exist in both dictionaries User must provide an ID column for old_cmp_dict """ update_ldict = [] same_keys = set(new_cmp_dict).intersection(set(old_cmp_dict)) for same_key in same_keys: # Get the Union of the set of keys # for both dictionaries to account # for missing keys old_dict = old_cmp_dict[same_key] new_dict = new_cmp_dict[same_key] dict_keys = set(old_dict).intersection(set(new_dict)) update_dict = {} for dict_key in columns: old_val = old_dict.get(dict_key, 'NaN') new_val = new_dict.get(dict_key, 'NaN') if old_val != new_val and new_val != 'NaN': if id_column!=None: try: update_dict[id_column] = old_dict[id_column] except KeyError: print("Input Dictionary 'old_cmp_dict' must have ID column") update_dict[dict_key] = new_val if update_dict: update_ldict.append(update_dict) return update_ldict
python
def changes(new_cmp_dict, old_cmp_dict, id_column, columns): """Return a list dict of the changes of the rows that exist in both dictionaries User must provide an ID column for old_cmp_dict """ update_ldict = [] same_keys = set(new_cmp_dict).intersection(set(old_cmp_dict)) for same_key in same_keys: # Get the Union of the set of keys # for both dictionaries to account # for missing keys old_dict = old_cmp_dict[same_key] new_dict = new_cmp_dict[same_key] dict_keys = set(old_dict).intersection(set(new_dict)) update_dict = {} for dict_key in columns: old_val = old_dict.get(dict_key, 'NaN') new_val = new_dict.get(dict_key, 'NaN') if old_val != new_val and new_val != 'NaN': if id_column!=None: try: update_dict[id_column] = old_dict[id_column] except KeyError: print("Input Dictionary 'old_cmp_dict' must have ID column") update_dict[dict_key] = new_val if update_dict: update_ldict.append(update_dict) return update_ldict
[ "def", "changes", "(", "new_cmp_dict", ",", "old_cmp_dict", ",", "id_column", ",", "columns", ")", ":", "update_ldict", "=", "[", "]", "same_keys", "=", "set", "(", "new_cmp_dict", ")", ".", "intersection", "(", "set", "(", "old_cmp_dict", ")", ")", "for", "same_key", "in", "same_keys", ":", "# Get the Union of the set of keys", "# for both dictionaries to account", "# for missing keys", "old_dict", "=", "old_cmp_dict", "[", "same_key", "]", "new_dict", "=", "new_cmp_dict", "[", "same_key", "]", "dict_keys", "=", "set", "(", "old_dict", ")", ".", "intersection", "(", "set", "(", "new_dict", ")", ")", "update_dict", "=", "{", "}", "for", "dict_key", "in", "columns", ":", "old_val", "=", "old_dict", ".", "get", "(", "dict_key", ",", "'NaN'", ")", "new_val", "=", "new_dict", ".", "get", "(", "dict_key", ",", "'NaN'", ")", "if", "old_val", "!=", "new_val", "and", "new_val", "!=", "'NaN'", ":", "if", "id_column", "!=", "None", ":", "try", ":", "update_dict", "[", "id_column", "]", "=", "old_dict", "[", "id_column", "]", "except", "KeyError", ":", "print", "(", "\"Input Dictionary 'old_cmp_dict' must have ID column\"", ")", "update_dict", "[", "dict_key", "]", "=", "new_val", "if", "update_dict", ":", "update_ldict", ".", "append", "(", "update_dict", ")", "return", "update_ldict" ]
Return a list dict of the changes of the rows that exist in both dictionaries User must provide an ID column for old_cmp_dict
[ "Return", "a", "list", "dict", "of", "the", "changes", "of", "the", "rows", "that", "exist", "in", "both", "dictionaries", "User", "must", "provide", "an", "ID", "column", "for", "old_cmp_dict" ]
404f320808912619920e2d787f2c4387225a14e0
https://github.com/jasonrollins/shareplum/blob/404f320808912619920e2d787f2c4387225a14e0/shareplum/ListDict.py#L4-L33
train
jasonrollins/shareplum
shareplum/ListDict.py
unique
def unique(new_cmp_dict, old_cmp_dict): """Return a list dict of the unique keys in new_cmp_dict """ newkeys = set(new_cmp_dict) oldkeys = set(old_cmp_dict) unique = newkeys - oldkeys unique_ldict = [] for key in unique: unique_ldict.append(new_cmp_dict[key]) return unique_ldict
python
def unique(new_cmp_dict, old_cmp_dict): """Return a list dict of the unique keys in new_cmp_dict """ newkeys = set(new_cmp_dict) oldkeys = set(old_cmp_dict) unique = newkeys - oldkeys unique_ldict = [] for key in unique: unique_ldict.append(new_cmp_dict[key]) return unique_ldict
[ "def", "unique", "(", "new_cmp_dict", ",", "old_cmp_dict", ")", ":", "newkeys", "=", "set", "(", "new_cmp_dict", ")", "oldkeys", "=", "set", "(", "old_cmp_dict", ")", "unique", "=", "newkeys", "-", "oldkeys", "unique_ldict", "=", "[", "]", "for", "key", "in", "unique", ":", "unique_ldict", ".", "append", "(", "new_cmp_dict", "[", "key", "]", ")", "return", "unique_ldict" ]
Return a list dict of the unique keys in new_cmp_dict
[ "Return", "a", "list", "dict", "of", "the", "unique", "keys", "in", "new_cmp_dict" ]
404f320808912619920e2d787f2c4387225a14e0
https://github.com/jasonrollins/shareplum/blob/404f320808912619920e2d787f2c4387225a14e0/shareplum/ListDict.py#L35-L45
train
improbable-research/keanu
keanu-python/keanu/plots/traceplot.py
traceplot
def traceplot(trace: sample_types, labels: List[Union[str, Tuple[str, str]]] = None, ax: Any = None, x0: int = 0) -> Any: """ Plot samples values. :param trace: result of MCMC run :param labels: labels of vertices to be plotted. if None, all vertices are plotted. :param ax: Matplotlib axes :param x0: index of first data point, used for sample stream plots """ if labels is None: labels = list(trace.keys()) if ax is None: _, ax = plt.subplots(len(labels), 1, squeeze=False) for index, label in enumerate(labels): data = [sample for sample in trace[label]] ax[index][0].set_title(label) ax[index][0].plot(__integer_xaxis(ax[index][0], x0, len(data)), data) __pause_for_crude_animation() return ax
python
def traceplot(trace: sample_types, labels: List[Union[str, Tuple[str, str]]] = None, ax: Any = None, x0: int = 0) -> Any: """ Plot samples values. :param trace: result of MCMC run :param labels: labels of vertices to be plotted. if None, all vertices are plotted. :param ax: Matplotlib axes :param x0: index of first data point, used for sample stream plots """ if labels is None: labels = list(trace.keys()) if ax is None: _, ax = plt.subplots(len(labels), 1, squeeze=False) for index, label in enumerate(labels): data = [sample for sample in trace[label]] ax[index][0].set_title(label) ax[index][0].plot(__integer_xaxis(ax[index][0], x0, len(data)), data) __pause_for_crude_animation() return ax
[ "def", "traceplot", "(", "trace", ":", "sample_types", ",", "labels", ":", "List", "[", "Union", "[", "str", ",", "Tuple", "[", "str", ",", "str", "]", "]", "]", "=", "None", ",", "ax", ":", "Any", "=", "None", ",", "x0", ":", "int", "=", "0", ")", "->", "Any", ":", "if", "labels", "is", "None", ":", "labels", "=", "list", "(", "trace", ".", "keys", "(", ")", ")", "if", "ax", "is", "None", ":", "_", ",", "ax", "=", "plt", ".", "subplots", "(", "len", "(", "labels", ")", ",", "1", ",", "squeeze", "=", "False", ")", "for", "index", ",", "label", "in", "enumerate", "(", "labels", ")", ":", "data", "=", "[", "sample", "for", "sample", "in", "trace", "[", "label", "]", "]", "ax", "[", "index", "]", "[", "0", "]", ".", "set_title", "(", "label", ")", "ax", "[", "index", "]", "[", "0", "]", ".", "plot", "(", "__integer_xaxis", "(", "ax", "[", "index", "]", "[", "0", "]", ",", "x0", ",", "len", "(", "data", ")", ")", ",", "data", ")", "__pause_for_crude_animation", "(", ")", "return", "ax" ]
Plot samples values. :param trace: result of MCMC run :param labels: labels of vertices to be plotted. if None, all vertices are plotted. :param ax: Matplotlib axes :param x0: index of first data point, used for sample stream plots
[ "Plot", "samples", "values", "." ]
73189a8f569078e156168e795f82c7366c59574b
https://github.com/improbable-research/keanu/blob/73189a8f569078e156168e795f82c7366c59574b/keanu-python/keanu/plots/traceplot.py#L12-L37
train
improbable-research/keanu
docs/bin/snippet_writer.py
read_file_snippets
def read_file_snippets(file, snippet_store): """Parse a file and add all snippets to the snippet_store dictionary""" start_reg = re.compile("(.*%%SNIPPET_START%% )([a-zA-Z0-9]+)") end_reg = re.compile("(.*%%SNIPPET_END%% )([a-zA-Z0-9]+)") open_snippets = {} with open(file, encoding="utf-8") as w: lines = w.readlines() for line in lines: printd("Got Line: {}".format(line)) # Check whether we're entering or leaving a snippet m = start_reg.match(line) if m: printd("Opened Snippet {}".format(m.group(2))) if m.group(2) in snippet_store: record_error("Repeat definition of Snippet {}".format(m.group(2))) elif m.group(2) in open_snippets: record_error("Snippet already opened {}".format(m.group(2))) else: printd("Added {} to open snippets list".format(m.group(2))) open_snippets[m.group(2)] = [] continue m = end_reg.match(line) if m: printd("Found end of Snippet {}".format(m.group(2))) if m.group(2) not in open_snippets: record_error("Reached Snippet End but no start") elif m.group(2) in snippet_store: record_error("Repeat definition of Snippet {}".format(m.group(2))) else: snippet_store[m.group(2)] = open_snippets[m.group(2)] del open_snippets[m.group(2)] continue # If we've got this far, then we're just a normal line, so we can add this to all open snippets for snippet in open_snippets.values(): printd("Adding Line to snippet") snippet.append(line) # Now, warn about any unclosed snippets for opened in open_snippets: record_error("Snippet {} left open - ignoring".format(opened))
python
def read_file_snippets(file, snippet_store): """Parse a file and add all snippets to the snippet_store dictionary""" start_reg = re.compile("(.*%%SNIPPET_START%% )([a-zA-Z0-9]+)") end_reg = re.compile("(.*%%SNIPPET_END%% )([a-zA-Z0-9]+)") open_snippets = {} with open(file, encoding="utf-8") as w: lines = w.readlines() for line in lines: printd("Got Line: {}".format(line)) # Check whether we're entering or leaving a snippet m = start_reg.match(line) if m: printd("Opened Snippet {}".format(m.group(2))) if m.group(2) in snippet_store: record_error("Repeat definition of Snippet {}".format(m.group(2))) elif m.group(2) in open_snippets: record_error("Snippet already opened {}".format(m.group(2))) else: printd("Added {} to open snippets list".format(m.group(2))) open_snippets[m.group(2)] = [] continue m = end_reg.match(line) if m: printd("Found end of Snippet {}".format(m.group(2))) if m.group(2) not in open_snippets: record_error("Reached Snippet End but no start") elif m.group(2) in snippet_store: record_error("Repeat definition of Snippet {}".format(m.group(2))) else: snippet_store[m.group(2)] = open_snippets[m.group(2)] del open_snippets[m.group(2)] continue # If we've got this far, then we're just a normal line, so we can add this to all open snippets for snippet in open_snippets.values(): printd("Adding Line to snippet") snippet.append(line) # Now, warn about any unclosed snippets for opened in open_snippets: record_error("Snippet {} left open - ignoring".format(opened))
[ "def", "read_file_snippets", "(", "file", ",", "snippet_store", ")", ":", "start_reg", "=", "re", ".", "compile", "(", "\"(.*%%SNIPPET_START%% )([a-zA-Z0-9]+)\"", ")", "end_reg", "=", "re", ".", "compile", "(", "\"(.*%%SNIPPET_END%% )([a-zA-Z0-9]+)\"", ")", "open_snippets", "=", "{", "}", "with", "open", "(", "file", ",", "encoding", "=", "\"utf-8\"", ")", "as", "w", ":", "lines", "=", "w", ".", "readlines", "(", ")", "for", "line", "in", "lines", ":", "printd", "(", "\"Got Line: {}\"", ".", "format", "(", "line", ")", ")", "# Check whether we're entering or leaving a snippet", "m", "=", "start_reg", ".", "match", "(", "line", ")", "if", "m", ":", "printd", "(", "\"Opened Snippet {}\"", ".", "format", "(", "m", ".", "group", "(", "2", ")", ")", ")", "if", "m", ".", "group", "(", "2", ")", "in", "snippet_store", ":", "record_error", "(", "\"Repeat definition of Snippet {}\"", ".", "format", "(", "m", ".", "group", "(", "2", ")", ")", ")", "elif", "m", ".", "group", "(", "2", ")", "in", "open_snippets", ":", "record_error", "(", "\"Snippet already opened {}\"", ".", "format", "(", "m", ".", "group", "(", "2", ")", ")", ")", "else", ":", "printd", "(", "\"Added {} to open snippets list\"", ".", "format", "(", "m", ".", "group", "(", "2", ")", ")", ")", "open_snippets", "[", "m", ".", "group", "(", "2", ")", "]", "=", "[", "]", "continue", "m", "=", "end_reg", ".", "match", "(", "line", ")", "if", "m", ":", "printd", "(", "\"Found end of Snippet {}\"", ".", "format", "(", "m", ".", "group", "(", "2", ")", ")", ")", "if", "m", ".", "group", "(", "2", ")", "not", "in", "open_snippets", ":", "record_error", "(", "\"Reached Snippet End but no start\"", ")", "elif", "m", ".", "group", "(", "2", ")", "in", "snippet_store", ":", "record_error", "(", "\"Repeat definition of Snippet {}\"", ".", "format", "(", "m", ".", "group", "(", "2", ")", ")", ")", "else", ":", "snippet_store", "[", "m", ".", "group", "(", "2", ")", "]", "=", "open_snippets", "[", "m", ".", "group", "(", "2", ")", "]", "del", "open_snippets", "[", "m", ".", "group", "(", "2", ")", "]", "continue", "# If we've got this far, then we're just a normal line, so we can add this to all open snippets", "for", "snippet", "in", "open_snippets", ".", "values", "(", ")", ":", "printd", "(", "\"Adding Line to snippet\"", ")", "snippet", ".", "append", "(", "line", ")", "# Now, warn about any unclosed snippets", "for", "opened", "in", "open_snippets", ":", "record_error", "(", "\"Snippet {} left open - ignoring\"", ".", "format", "(", "opened", ")", ")" ]
Parse a file and add all snippets to the snippet_store dictionary
[ "Parse", "a", "file", "and", "add", "all", "snippets", "to", "the", "snippet_store", "dictionary" ]
73189a8f569078e156168e795f82c7366c59574b
https://github.com/improbable-research/keanu/blob/73189a8f569078e156168e795f82c7366c59574b/docs/bin/snippet_writer.py#L31-L73
train
improbable-research/keanu
docs/bin/snippet_writer.py
strip_block_whitespace
def strip_block_whitespace(string_list): """Treats a list of strings as a code block and strips whitespace so that the min whitespace line sits at char 0 of line.""" min_ws = min([(len(x) - len(x.lstrip())) for x in string_list if x != '\n']) return [x[min_ws:] if x != '\n' else x for x in string_list]
python
def strip_block_whitespace(string_list): """Treats a list of strings as a code block and strips whitespace so that the min whitespace line sits at char 0 of line.""" min_ws = min([(len(x) - len(x.lstrip())) for x in string_list if x != '\n']) return [x[min_ws:] if x != '\n' else x for x in string_list]
[ "def", "strip_block_whitespace", "(", "string_list", ")", ":", "min_ws", "=", "min", "(", "[", "(", "len", "(", "x", ")", "-", "len", "(", "x", ".", "lstrip", "(", ")", ")", ")", "for", "x", "in", "string_list", "if", "x", "!=", "'\\n'", "]", ")", "return", "[", "x", "[", "min_ws", ":", "]", "if", "x", "!=", "'\\n'", "else", "x", "for", "x", "in", "string_list", "]" ]
Treats a list of strings as a code block and strips whitespace so that the min whitespace line sits at char 0 of line.
[ "Treats", "a", "list", "of", "strings", "as", "a", "code", "block", "and", "strips", "whitespace", "so", "that", "the", "min", "whitespace", "line", "sits", "at", "char", "0", "of", "line", "." ]
73189a8f569078e156168e795f82c7366c59574b
https://github.com/improbable-research/keanu/blob/73189a8f569078e156168e795f82c7366c59574b/docs/bin/snippet_writer.py#L126-L130
train
aio-libs/aiohttp-sse
aiohttp_sse/__init__.py
EventSourceResponse.prepare
async def prepare(self, request): """Prepare for streaming and send HTTP headers. :param request: regular aiohttp.web.Request. """ if request.method != 'GET': raise HTTPMethodNotAllowed(request.method, ['GET']) if not self.prepared: writer = await super().prepare(request) self._loop = request.app.loop self._ping_task = self._loop.create_task(self._ping()) # explicitly enabling chunked encoding, since content length # usually not known beforehand. self.enable_chunked_encoding() return writer else: # hackish way to check if connection alive # should be updated once we have proper API in aiohttp # https://github.com/aio-libs/aiohttp/issues/3105 if request.protocol.transport is None: # request disconnected raise asyncio.CancelledError()
python
async def prepare(self, request): """Prepare for streaming and send HTTP headers. :param request: regular aiohttp.web.Request. """ if request.method != 'GET': raise HTTPMethodNotAllowed(request.method, ['GET']) if not self.prepared: writer = await super().prepare(request) self._loop = request.app.loop self._ping_task = self._loop.create_task(self._ping()) # explicitly enabling chunked encoding, since content length # usually not known beforehand. self.enable_chunked_encoding() return writer else: # hackish way to check if connection alive # should be updated once we have proper API in aiohttp # https://github.com/aio-libs/aiohttp/issues/3105 if request.protocol.transport is None: # request disconnected raise asyncio.CancelledError()
[ "async", "def", "prepare", "(", "self", ",", "request", ")", ":", "if", "request", ".", "method", "!=", "'GET'", ":", "raise", "HTTPMethodNotAllowed", "(", "request", ".", "method", ",", "[", "'GET'", "]", ")", "if", "not", "self", ".", "prepared", ":", "writer", "=", "await", "super", "(", ")", ".", "prepare", "(", "request", ")", "self", ".", "_loop", "=", "request", ".", "app", ".", "loop", "self", ".", "_ping_task", "=", "self", ".", "_loop", ".", "create_task", "(", "self", ".", "_ping", "(", ")", ")", "# explicitly enabling chunked encoding, since content length", "# usually not known beforehand.", "self", ".", "enable_chunked_encoding", "(", ")", "return", "writer", "else", ":", "# hackish way to check if connection alive", "# should be updated once we have proper API in aiohttp", "# https://github.com/aio-libs/aiohttp/issues/3105", "if", "request", ".", "protocol", ".", "transport", "is", "None", ":", "# request disconnected", "raise", "asyncio", ".", "CancelledError", "(", ")" ]
Prepare for streaming and send HTTP headers. :param request: regular aiohttp.web.Request.
[ "Prepare", "for", "streaming", "and", "send", "HTTP", "headers", "." ]
5148d087f9df75ecea61f574d3c768506680e5dc
https://github.com/aio-libs/aiohttp-sse/blob/5148d087f9df75ecea61f574d3c768506680e5dc/aiohttp_sse/__init__.py#L52-L74
train
aio-libs/aiohttp-sse
aiohttp_sse/__init__.py
EventSourceResponse.send
async def send(self, data, id=None, event=None, retry=None): """Send data using EventSource protocol :param str data: The data field for the message. :param str id: The event ID to set the EventSource object's last event ID value to. :param str event: The event's type. If this is specified, an event will be dispatched on the browser to the listener for the specified event name; the web site would use addEventListener() to listen for named events. The default event type is "message". :param int retry: The reconnection time to use when attempting to send the event. [What code handles this?] This must be an integer, specifying the reconnection time in milliseconds. If a non-integer value is specified, the field is ignored. """ buffer = io.StringIO() if id is not None: buffer.write(self.LINE_SEP_EXPR.sub('', 'id: {}'.format(id))) buffer.write(self._sep) if event is not None: buffer.write(self.LINE_SEP_EXPR.sub('', 'event: {}'.format(event))) buffer.write(self._sep) for chunk in self.LINE_SEP_EXPR.split(data): buffer.write('data: {}'.format(chunk)) buffer.write(self._sep) if retry is not None: if not isinstance(retry, int): raise TypeError('retry argument must be int') buffer.write('retry: {}'.format(retry)) buffer.write(self._sep) buffer.write(self._sep) await self.write(buffer.getvalue().encode('utf-8'))
python
async def send(self, data, id=None, event=None, retry=None): """Send data using EventSource protocol :param str data: The data field for the message. :param str id: The event ID to set the EventSource object's last event ID value to. :param str event: The event's type. If this is specified, an event will be dispatched on the browser to the listener for the specified event name; the web site would use addEventListener() to listen for named events. The default event type is "message". :param int retry: The reconnection time to use when attempting to send the event. [What code handles this?] This must be an integer, specifying the reconnection time in milliseconds. If a non-integer value is specified, the field is ignored. """ buffer = io.StringIO() if id is not None: buffer.write(self.LINE_SEP_EXPR.sub('', 'id: {}'.format(id))) buffer.write(self._sep) if event is not None: buffer.write(self.LINE_SEP_EXPR.sub('', 'event: {}'.format(event))) buffer.write(self._sep) for chunk in self.LINE_SEP_EXPR.split(data): buffer.write('data: {}'.format(chunk)) buffer.write(self._sep) if retry is not None: if not isinstance(retry, int): raise TypeError('retry argument must be int') buffer.write('retry: {}'.format(retry)) buffer.write(self._sep) buffer.write(self._sep) await self.write(buffer.getvalue().encode('utf-8'))
[ "async", "def", "send", "(", "self", ",", "data", ",", "id", "=", "None", ",", "event", "=", "None", ",", "retry", "=", "None", ")", ":", "buffer", "=", "io", ".", "StringIO", "(", ")", "if", "id", "is", "not", "None", ":", "buffer", ".", "write", "(", "self", ".", "LINE_SEP_EXPR", ".", "sub", "(", "''", ",", "'id: {}'", ".", "format", "(", "id", ")", ")", ")", "buffer", ".", "write", "(", "self", ".", "_sep", ")", "if", "event", "is", "not", "None", ":", "buffer", ".", "write", "(", "self", ".", "LINE_SEP_EXPR", ".", "sub", "(", "''", ",", "'event: {}'", ".", "format", "(", "event", ")", ")", ")", "buffer", ".", "write", "(", "self", ".", "_sep", ")", "for", "chunk", "in", "self", ".", "LINE_SEP_EXPR", ".", "split", "(", "data", ")", ":", "buffer", ".", "write", "(", "'data: {}'", ".", "format", "(", "chunk", ")", ")", "buffer", ".", "write", "(", "self", ".", "_sep", ")", "if", "retry", "is", "not", "None", ":", "if", "not", "isinstance", "(", "retry", ",", "int", ")", ":", "raise", "TypeError", "(", "'retry argument must be int'", ")", "buffer", ".", "write", "(", "'retry: {}'", ".", "format", "(", "retry", ")", ")", "buffer", ".", "write", "(", "self", ".", "_sep", ")", "buffer", ".", "write", "(", "self", ".", "_sep", ")", "await", "self", ".", "write", "(", "buffer", ".", "getvalue", "(", ")", ".", "encode", "(", "'utf-8'", ")", ")" ]
Send data using EventSource protocol :param str data: The data field for the message. :param str id: The event ID to set the EventSource object's last event ID value to. :param str event: The event's type. If this is specified, an event will be dispatched on the browser to the listener for the specified event name; the web site would use addEventListener() to listen for named events. The default event type is "message". :param int retry: The reconnection time to use when attempting to send the event. [What code handles this?] This must be an integer, specifying the reconnection time in milliseconds. If a non-integer value is specified, the field is ignored.
[ "Send", "data", "using", "EventSource", "protocol" ]
5148d087f9df75ecea61f574d3c768506680e5dc
https://github.com/aio-libs/aiohttp-sse/blob/5148d087f9df75ecea61f574d3c768506680e5dc/aiohttp_sse/__init__.py#L76-L111
train
aio-libs/aiohttp-sse
aiohttp_sse/__init__.py
EventSourceResponse.wait
async def wait(self): """EventSourceResponse object is used for streaming data to the client, this method returns future, so we can wain until connection will be closed or other task explicitly call ``stop_streaming`` method. """ if self._ping_task is None: raise RuntimeError('Response is not started') with contextlib.suppress(asyncio.CancelledError): await self._ping_task
python
async def wait(self): """EventSourceResponse object is used for streaming data to the client, this method returns future, so we can wain until connection will be closed or other task explicitly call ``stop_streaming`` method. """ if self._ping_task is None: raise RuntimeError('Response is not started') with contextlib.suppress(asyncio.CancelledError): await self._ping_task
[ "async", "def", "wait", "(", "self", ")", ":", "if", "self", ".", "_ping_task", "is", "None", ":", "raise", "RuntimeError", "(", "'Response is not started'", ")", "with", "contextlib", ".", "suppress", "(", "asyncio", ".", "CancelledError", ")", ":", "await", "self", ".", "_ping_task" ]
EventSourceResponse object is used for streaming data to the client, this method returns future, so we can wain until connection will be closed or other task explicitly call ``stop_streaming`` method.
[ "EventSourceResponse", "object", "is", "used", "for", "streaming", "data", "to", "the", "client", "this", "method", "returns", "future", "so", "we", "can", "wain", "until", "connection", "will", "be", "closed", "or", "other", "task", "explicitly", "call", "stop_streaming", "method", "." ]
5148d087f9df75ecea61f574d3c768506680e5dc
https://github.com/aio-libs/aiohttp-sse/blob/5148d087f9df75ecea61f574d3c768506680e5dc/aiohttp_sse/__init__.py#L113-L121
train
aio-libs/aiohttp-sse
aiohttp_sse/__init__.py
EventSourceResponse.ping_interval
def ping_interval(self, value): """Setter for ping_interval property. :param int value: interval in sec between two ping values. """ if not isinstance(value, int): raise TypeError("ping interval must be int") if value < 0: raise ValueError("ping interval must be greater then 0") self._ping_interval = value
python
def ping_interval(self, value): """Setter for ping_interval property. :param int value: interval in sec between two ping values. """ if not isinstance(value, int): raise TypeError("ping interval must be int") if value < 0: raise ValueError("ping interval must be greater then 0") self._ping_interval = value
[ "def", "ping_interval", "(", "self", ",", "value", ")", ":", "if", "not", "isinstance", "(", "value", ",", "int", ")", ":", "raise", "TypeError", "(", "\"ping interval must be int\"", ")", "if", "value", "<", "0", ":", "raise", "ValueError", "(", "\"ping interval must be greater then 0\"", ")", "self", ".", "_ping_interval", "=", "value" ]
Setter for ping_interval property. :param int value: interval in sec between two ping values.
[ "Setter", "for", "ping_interval", "property", "." ]
5148d087f9df75ecea61f574d3c768506680e5dc
https://github.com/aio-libs/aiohttp-sse/blob/5148d087f9df75ecea61f574d3c768506680e5dc/aiohttp_sse/__init__.py#L140-L151
train