text:
from __future__ import absolute_import
from __future__ import print_function
from .._abstract.abstract import BaseAGSServer
from ..packages.six.moves.urllib_parse import urlparse
from .parameters import Extension
import os
import json
import tempfile
import xml.etree.ElementTree as ET
########################################################################
class Services(BaseAGSServer):
    """ returns information about the services on AGS """
    _currentURL = None
    _url = None
    _securityHandler = None
    _folderName = None
    _folders = None
    _foldersDetail = None
    _folderDetail = None
    _webEncrypted = None
    _description = None
    _isDefault = None
    _services = None
    _proxy_port = None
    _proxy_url = None
    _json = None
    #----------------------------------------------------------------------
    def __init__(self, url, securityHandler,
                 proxy_url=None, proxy_port=None,
                 initialize=False):
        """Constructor
            Inputs:
               url - admin url
               token_url - url to generate token
               username - admin username
               password - admin password
        """
        self._proxy_url = proxy_url
        self._proxy_port = proxy_port
        self._url = url
        self._currentURL = url
        self._securityHandler = securityHandler
        if initialize:
            self.__init()
    #----------------------------------------------------------------------
    def __init(self):
        """ populates server admin information """
        params = {
            "f" : "json"
        }
        json_dict = self._get(url=self._currentURL,
                                 param_dict=params,
                                 securityHandler=self._securityHandler,
                                 proxy_url=self._proxy_url,
                                 proxy_port=self._proxy_port)
        self._json = json.dumps(json_dict)
        attributes = [attr for attr in dir(self)
                    if not attr.startswith('__') and \
                    not attr.startswith('_')]
        for k,v in json_dict.items():
            if k in attributes:
                setattr(self, "_"+ k, json_dict[k])
            else:
                print( k, " - attribute not implemented manageags.services.")
            del k
            del v
    #----------------------------------------------------------------------
    def __str__(self):
        """returns the object as a string"""
        if self._json is None:
            self.__init()
        return self._json
    #----------------------------------------------------------------------
    @property
    def webEncrypted(self):
        """ returns if the server is web encrypted """
        if self._webEncrypted is None:
            self.__init()
        return self._webEncrypted
    #----------------------------------------------------------------------
    @property
    def folderName(self):
        """ returns current folder """
        return self._folderName
    #----------------------------------------------------------------------
    @folderName.setter
    def folderName(self, folder):
        """gets/set the current folder"""

        if folder == "" or\
             folder == "/":
            self._currentURL = self._url
            self._services = None
            self._description = None
            self._folderName = None
            self._webEncrypted = None
            self.__init()
            self._folderName = folder
        elif folder in self.folders:
            self._currentURL = self._url + "/%s" % folder
            self._services = None
            self._description = None
            self._folderName = None
            self._webEncrypted = None
            self.__init()
            self._folderName = folder
    #----------------------------------------------------------------------
    @property
    def folders(self):
        """ returns a list of all folders """
        if self._folders is None:
            self.__init()
        if "/" not in self._folders:
            self._folders.append("/")
        return self._folders
    #----------------------------------------------------------------------
    @property
    def foldersDetail(self):
        """returns the folder's details"""
        if self._foldersDetail is None:
            self.__init()
        return self._foldersDetail
    #----------------------------------------------------------------------
    @property
    def description(self):
        """ returns the decscription """
        if self._description is None:
            self.__init()
        return self._description
    #----------------------------------------------------------------------
    @property
    def isDefault(self):
        """ returns the is default property """
        if self._isDefault is None:
            self.__init()
        return self._isDefault
    #----------------------------------------------------------------------
    @property
    def services(self):
        """ returns the services in the current folder """
        self._services = []
        params = {
                    "f" : "json"
                }
        json_dict = self._get(url=self._currentURL,
                                 param_dict=params,
                                 securityHandler=self._securityHandler,
                                 proxy_url=self._proxy_url,
                                 proxy_port=self._proxy_port)
        if "services" in json_dict.keys():
            for s in json_dict['services']:
                uURL = self._currentURL + "/%s.%s" % (s['serviceName'], s['type'])
                self._services.append(
                    AGSService(url=uURL,
                               securityHandler=self._securityHandler,
                               proxy_url=self._proxy_url,
                               proxy_port=self._proxy_port)
                )
        return self._services
    #----------------------------------------------------------------------
    def find_services(self, service_type="*"):
        """
            returns a list of a particular service type on AGS
            Input:
              service_type - Type of service to find.  The allowed types
                             are: ("GPSERVER", "GLOBESERVER", "MAPSERVER",
                             "GEOMETRYSERVER", "IMAGESERVER",
                             "SEARCHSERVER", "GEODATASERVER",
                             "GEOCODESERVER", "*").  The default is *
                             meaning find all service names.
            Output:
              returns a list of service names as <folder>/<name>.<type>
        """
        allowed_service_types = ("GPSERVER", "GLOBESERVER", "MAPSERVER",
                                 "GEOMETRYSERVER", "IMAGESERVER",
                                 "SEARCHSERVER", "GEODATASERVER",
                                 "GEOCODESERVER", "*")
        lower_types = [l.lower() for l in service_type.split(',')]
        for v in lower_types:
            if v.upper() not in allowed_service_types:
                return {"message" : "%s is not an allowed service type." % v}
        params = {
            "f" : "json"
        }
        type_services = []
        folders = self.folders
        baseURL = self._url
        for folder in folders:
            if folder == "/":
                url = baseURL
            else:
                url = baseURL + "/%s" % folder
            res = self._get(url, params,
                               securityHandler=self._securityHandler,
                               proxy_url=self._proxy_url,
                               proxy_port=self._proxy_port)
            if "services" in res:
                for service in res['services']:
                    if service_type == "*":
                        service['URL'] = url + "/%s.%s" % (service['serviceName'],
                                                           service['type'])
                        type_services.append(service)
                    if service['type'].lower() in lower_types:
                        service['URL'] = url + "/%s.%s" % (service['serviceName'],
                                                           service_type)
                        type_services.append(service)
                    del service
            del res
            del folder
        return type_services
    #----------------------------------------------------------------------
    def addFolderPermission(self, principal, isAllowed=True, folder=None):
        """
           Assigns a new permission to a role (principal). The permission
           on a parent resource is automatically inherited by all child
           resources
           Input:
              principal - name of role to assign/disassign accesss
              isAllowed -  boolean which allows access
           Output:
              JSON message as dictionary
        """
        if folder is not None:
            uURL = self._url + "/%s/%s" % (folder, "/permissions/add")
        else:
            uURL = self._url + "/permissions/add"
        params = {
            "f" : "json",
            "principal" : principal,
            "isAllowed" : isAllowed
        }
        return self._post(url=uURL, param_dict=params,
                             securityHandler=self._securityHandler,
                             proxy_url=self._proxy_url,
                             proxy_port=self._proxy_port)
    #----------------------------------------------------------------------
    def listFolderPermissions(self,folderName):
        """
           Lists principals which have permissions for the folder.
           Input:
              folderName - name of the folder to list permissions for
           Output:
              JSON Message as Dictionary
        """
        uURL = self._url + "/%s/permissions" % folderName
        params = {
            "f" : "json",
        }
        return self._post(url=uURL, param_dict=params,
                             securityHandler=self._securityHandler,
                             proxy_url=self._proxy_url,
                             proxy_port=self._proxy_port)
    #----------------------------------------------------------------------
    def cleanPermissions(self, principal):
        """
           Cleans all permissions that have been assigned to a role
           (principal). This is typically used when a role is deleted.
           Input:
              principal - name of the role to clean
           Output:
              JSON Message as Dictionary
        """
        uURL = self._url + "/permissions/clean"
        params = {
            "f" : "json",
            "principal" : principal
        }
        return self._post(url=uURL, param_dict=params,
                             securityHandler=self._securityHandler,
                             proxy_url=self._proxy_url,
                             proxy_port=self._proxy_port)
    #----------------------------------------------------------------------
    def createFolder(self, folderName, description=""):
        """
           Creates a unique folder name on AGS
           Inputs:
              folderName - name of folder on AGS
              description - describes the folder
           Output:
              JSON message as dictionary
        """
        params = {
            "f" : "json",
            "folderName" : folderName,
            "description" : description
        }
        uURL = self._url + "/createFolder"
        return self._post(url=uURL, param_dict=params,
                             securityHandler=self._securityHandler,
                             proxy_url=self._proxy_url,
                             proxy_port=self._proxy_port)
    #----------------------------------------------------------------------
    def deleteFolder(self, folderName):
        """
           deletes a folder on AGS
           Inputs:
              folderName - name of folder to remove
           Output:
              JSON message as dictionary
        """
        params = {
            "f" : "json"
        }
        if folderName in self.folders:
            uURL = self._url + "/%s/deleteFolder" % folderName
            return self._post(url=uURL, param_dict=params,
                                 securityHandler=self._securityHandler,
                                 proxy_url=self._proxy_url,
                                 proxy_port=self._proxy_port)
        else:
            return {"error" : "folder does not exist"}
    #----------------------------------------------------------------------
    def deleteService(self, serviceName, serviceType, folder=None):
        """
           deletes a service from AGS
           Inputs:
              serviceName - name of the service
              serviceType - type of the service
              folder - name of the folder the service resides, leave None
                       for root.
           Output:
              JSON message as dictionary
        """
        if folder is None:
            uURL = self._url + "/%s.%s/delete" % (serviceName,
                                                  serviceType)
        else:
            uURL = self._url + "/%s/%s.%s/delete" % (folder,
                                                     serviceName,
                                                     serviceType)
        params = {
            "f" : "json"
        }
        return self._post(url=uURL, param_dict=params,
                             securityHandler=self._securityHandler,
                             proxy_url=self._proxy_url,
                             proxy_port=self._proxy_port)
    def service_report(self, folder=None):
        """
           provides a report on all items in a given folder
           Inputs:
              folder - folder to report on given services. None means root
        """
        items = ["description", "status",
                 "instances", "iteminfo",
                 "properties"]
        if folder is None:
            uURL = self._url + "/report"
        else:
            uURL = self._url + "/%s/report" % folder
        params = {
            "f" : "json",
            "parameters" : items
        }
        return self._get(url=uURL, param_dict=params,
                            securityHandler=self._securityHandler,
                             proxy_url=self._proxy_url,
                             proxy_port=self._proxy_port)
    #----------------------------------------------------------------------
    @property
    def types(self):
        """ returns the allowed services types """
        params = {
            "f" : "json"
        }
        uURL = self._url + "/types"
        return self._get(url=uURL,
                            param_dict=params,
                            securityHandler=self._securityHandler,
                            proxy_url=self._proxy_url,
                            proxy_port=self._proxy_port)
    #----------------------------------------------------------------------
    def rename_service(self, serviceName, serviceType,
                       serviceNewName, folder=None):
        """
           Renames a published AGS Service
           Inputs:
              serviceName - old service name
              serviceType - type of service
              serviceNewName - new service name
              folder - location of where the service lives, none means
                       root folder.
           Output:
              JSON message as dictionary
        """
        params = {
            "f" : "json",
            "serviceName" : serviceName,
            "serviceType" : serviceType,
            "serviceNewName" : serviceNewName
        }
        if folder is None:
            uURL = self._url + "/renameService"
        else:
            uURL = self._url + "/%s/renameService" % folder
        return self._post(url=uURL, param_dict=params,
                             securityHandler=self._securityHandler,
                             proxy_url=self._proxy_url,
                             proxy_port=self._proxy_port)
    #----------------------------------------------------------------------
    def createService(self, service):
        """
        Creates a new GIS service in the folder. A service is created by
        submitting a JSON representation of the service to this operation.
        """
        url = self._url + "/createService"
        params = {
            "f" : "json"
        }
        if isinstance(service, str):
            params['service'] = service
        elif isinstance(service, dict):
            params['service'] = json.dumps(service)
        return self._post(url=url,
                             param_dict=params,
                             securityHandler=self._securityHandler,
                             proxy_url=self._proxy_url,
                             proxy_port=self._proxy_port)
    #----------------------------------------------------------------------
    def stopServices(self, services ):
        """
        Stops serveral services on a single server
        Inputs:
           services - is a list of dictionary objects. Each dictionary
                      object is defined as:
                        folderName - The name of the folder containing the
                        service, for example, "Planning". If the service
                        resides in the root folder, leave the folder
                        property blank ("folderName": "").
                        serviceName - The name of the service, for example,
                        "FireHydrants".
                        type - The service type, for example, "MapServer".
                     Example:
                        [{
                          "folderName" : "",
                          "serviceName" : "SampleWorldCities",
                          "type" : "MapServer"
                        }]
        """
        url = self._url + "/stopServices"
        if isinstance(services, dict):
            services = [services]
        elif isinstance(services, (list, tuple)):
            services = list(services)
        else:
            Exception("Invalid input for parameter services")
        params = {
            "f" : "json",
            "services" : {
                "services":services
            }
        }
        return self._post(url=url,
                             param_dict=params,
                             securityHandler=self._securityHandler,
                             proxy_url=self._proxy_url,
                             proxy_port=self._proxy_port)
    #----------------------------------------------------------------------
    def startServices(self, services ):
        """
        starts serveral services on a single server
        Inputs:
           services - is a list of dictionary objects. Each dictionary
                      object is defined as:
                        folderName - The name of the folder containing the
                        service, for example, "Planning". If the service
                        resides in the root folder, leave the folder
                        property blank ("folderName": "").
                        serviceName - The name of the service, for example,
                        "FireHydrants".
                        type - The service type, for example, "MapServer".
                     Example:
                        [{
                          "folderName" : "",
                          "serviceName" : "SampleWorldCities",
                          "type" : "MapServer"
                        }]
        """
        url = self._url + "/startServices"
        if isinstance(services, dict):
            services = [services]
        elif isinstance(services, (list, tuple)):
            services = list(services)
        else:
            Exception("Invalid input for parameter services")
        params = {
            "f" : "json",
            "services" : {
                "services":services
            }
        }
        return self._post(url=url,
                             param_dict=params,
                             securityHandler=self._securityHandler,
                             proxy_url=self._proxy_url,
                             proxy_port=self._proxy_port)
    #----------------------------------------------------------------------
    def editFolder(self, description, webEncrypted=False):
        """
        This operation allows you to change the description of an existing
        folder or change the web encrypted property.
        The web encrypted property indicates if all the services contained
        in the folder are only accessible over a secure channel (SSL). When
        setting this property to true, you also need to enable the virtual
        directory security in the security configuration.

        Inputs:
           description - a description of the folder
           webEncrypted - boolean to indicate if the services are
            accessible over SSL only.
        """
        url = self._url + "/editFolder"
        params = {
            "f" : "json",
            "webEncrypted" : webEncrypted,
            "description" : "%s" % description
        }
        return self._post(url=url,
                             param_dict=params,
                             securityHandler=self._securityHandler,
                             proxy_url=self._proxy_url,
                             proxy_port=self._proxy_port)
    #----------------------------------------------------------------------
    def exists(self, folderName, serviceName=None, serviceType=None):
        """
        This operation allows you to check whether a folder or a service
        exists. To test if a folder exists, supply only a folderName. To
        test if a service exists in a root folder, supply both serviceName
        and serviceType with folderName=None. To test if a service exists
        in a folder, supply all three parameters.

        Inputs:
           folderName - a folder name
           serviceName - a service name
           serviceType - a service type. Allowed values:
                "GPSERVER", "GLOBESERVER", "MAPSERVER",
                "GEOMETRYSERVER", "IMAGESERVER", "SEARCHSERVER",
                "GEODATASERVER", "GEOCODESERVER"
        """

        url = self._url + "/exists"
        params = {
            "f" : "json",
            "folderName" : folderName,
            "serviceName" : serviceName,
            "type" : serviceType
        }
        return self._post(url=url,
                             param_dict=params,
                             securityHandler=self._securityHandler,
                             proxy_url=self._proxy_url,
                             proxy_port=self._proxy_port)

########################################################################
class AGSService(BaseAGSServer):
    """ Defines a AGS Admin Service """
    _frameworkProperties = None
    _proxy_port = None
    _proxy_url = None
    _securityHandler = None
    _recycleInterval = None
    _instancesPerContainer = None
    _maxWaitTime = None
    _extensions = None
    _minInstancesPerNode = None
    _maxIdleTime = None
    _maxUsageTime = None
    _allowedUploadFileTypes = None
    _datasets = None
    _properties = None
    _recycleStartTime = None
    _clusterName = None
    _description = None
    _isDefault = None
    _type = None
    _serviceName = None
    _isolationLevel = None
    _capabilities = None
    _loadBalancing = None
    _configuredState = None
    _maxStartupTime = None
    _private = None
    _maxUploadFileSize = None
    _keepAliveInterval = None
    _maxInstancesPerNode = None
    _json = None
    _json_dict = None
    _interceptor = None
    _provider = None
    _portalProperties = None
    _jsonProperties = None
    #----------------------------------------------------------------------
    def __init__(self,
                 url,
                 securityHandler,
                 proxy_url=None, proxy_port=None,
                 initialize=False):
        """Constructor
            Inputs:
               url - admin url
               securityHandler - manages site security
               proxy_url - url of proxy
               proxy_port - port value of proxy
               initialize - fills all the properties at object creation is
                            true
        """
        self._proxy_url = proxy_url
        self._proxy_port = proxy_port
        self._url = url
        self._currentURL = url
        self._securityHandler = securityHandler
        if initialize:
            self.__init()
    #----------------------------------------------------------------------
    def __init(self):
        """ populates server admin information """
        params = {
            "f" : "json"
        }
        json_dict = self._get(url=self._currentURL,
                                 param_dict=params,
                                 securityHandler=self._securityHandler,
                                 proxy_url=self._proxy_url,
                                 proxy_port=self._proxy_port)
        self._json = json.dumps(json_dict)
        self._json_dict = json_dict
        attributes = [attr for attr in dir(self)
                    if not attr.startswith('__') and \
                    not attr.startswith('_')]
        for k,v in json_dict.items():
            if k.lower() == "extensions":
                self._extensions = []
                for ext in v:
                    self._extensions.append(Extension.fromJSON(ext))
                    del ext
            elif k in attributes:
                setattr(self, "_"+ k, json_dict[k])
            else:
                print( k, " - attribute not implemented in manageags.AGSService.")
            del k
            del v
    #----------------------------------------------------------------------
    def refreshProperties(self):
        """refreshes the object's values by re-querying the service"""
        self.__init()
    #----------------------------------------------------------------------
    def __str__(self):
        """returns a string of the object"""
        if self._json is None:
            self.__init()
            return self._json
        else:
            val = {"serviceName": self._serviceName,
                   "type": self._type,
                   "description": self._description,
                   "capabilities": self._capabilities,
                   "provider": self._provider,
                   "interceptor": self._interceptor,
                   "clusterName": self._clusterName,
                   "minInstancesPerNode": self._minInstancesPerNode,
                   "maxInstancesPerNode": self._maxInstancesPerNode,
                   "instancesPerContainer": self._instancesPerContainer,
                   "maxWaitTime": self._maxWaitTime,
                   "maxStartupTime": self._maxStartupTime,
                   "maxIdleTime": self._maxIdleTime,
                   "maxUsageTime": self._maxUsageTime,
                   "loadBalancing": self._loadBalancing,
                   "isolationLevel": self._isolationLevel,
                   "configuredState": self._configuredState,
                   "recycleInterval": self._recycleInterval,
                   "recycleStartTime": self._recycleStartTime,
                   "keepAliveInterval": self._keepAliveInterval,
                   "private": self._private,
                   "isDefault": self._isDefault,
                   "maxUploadFileSize": self._maxUploadFileSize,
                   "allowedUploadFileTypes": self._allowedUploadFileTypes,
                   "properties": self._properties,
                   "extensions": [e.value for e in self.extensions],
                   "datasets": self._datasets,
                   }
            if self._jsonProperties is not None:
                val["jsonProperties"] = self._jsonProperties
        return json.dumps(val)
    #----------------------------------------------------------------------
    def __iter__(self):
        """class iterator which yields a key/value pair"""
        if self._json_dict is None:
            self.__init()
        for k,v in self._json_dict.items():
            yield (k,v)
    #----------------------------------------------------------------------
    def jsonProperties(self):
        """returns the jsonProperties"""
        if self._jsonProperties is None:
            self.__init()
        return self._jsonProperties
    #----------------------------------------------------------------------
    @property
    def frameworkProperties(self):
        """returns the framework properties for an AGS instance"""
        if self._frameworkProperties is None:
            self.__init()
        return self._frameworkProperties
    #----------------------------------------------------------------------
    @property
    def portalProperties(self):
        """returns the service's portal properties"""
        if self._portalProperties is None:
            self.__init()
        return self._portalProperties
    #----------------------------------------------------------------------
    @property
    def interceptor(self):
        """returns the interceptor property"""
        if self._interceptor is None:
            self.__init()
        return self._interceptor
    #----------------------------------------------------------------------
    @property
    def provider(self):
        """returns the provider for the service"""
        if self._provider is None:
            self.__init()
        return self._provider
    #----------------------------------------------------------------------
    @property
    def recycleInterval(self):
        if self._recycleInterval is None:
            self.__init()
        return self._recycleInterval
    #----------------------------------------------------------------------
    @property
    def instancesPerContainer(self):
        if self._instancesPerContainer is None:
            self.__init()
        return self._instancesPerContainer
    #----------------------------------------------------------------------
    @property
    def maxWaitTime(self):
        if self._maxWaitTime is None:
            self.__init()
        return self._maxWaitTime
    #----------------------------------------------------------------------
    @property
    def extensions(self):
        if self._extensions is None:
            self.__init()
        return self._extensions
    #----------------------------------------------------------------------
    def modifyExtensions(self,
                         extensionObjects=[]):
        """
        enables/disables a service extension type based on the name
        """

        if len(extensionObjects) > 0 and \
           isinstance(extensionObjects[0], Extension):
            self._extensions = extensionObjects
            res = self.edit(str(self))
            self._json = None
            self.__init()
            return res
    #----------------------------------------------------------------------
    @property
    def minInstancesPerNode(self):
        if self._minInstancesPerNode is None:
            self.__init()
        return self._minInstancesPerNode
    #----------------------------------------------------------------------
    @property
    def maxIdleTime(self):
        if self._maxIdleTime is None:
            self.__init()
        return self._maxIdleTime
    #----------------------------------------------------------------------
    @property
    def maxUsageTime(self):
        if self._maxUsageTime is None:
            self.__init()
        return self._maxUsageTime
    #----------------------------------------------------------------------
    @property
    def allowedUploadFileTypes(self):
        if self._allowedUploadFileTypes is None:
            self.__init()
        return self._allowedUploadFileTypes
    #----------------------------------------------------------------------
    @property
    def datasets(self):
        if self._datasets is None:
            self.__init()
        return self._datasets
    #----------------------------------------------------------------------
    @property
    def properties(self):
        if self._properties is None:
            self.__init()
        return self._properties
    #----------------------------------------------------------------------
    @property
    def recycleStartTime(self):
        if self._recycleStartTime is None:
            self.__init()
        return self._recycleStartTime
    #----------------------------------------------------------------------
    @property
    def clusterName(self):
        if self._clusterName is None:
            self.__init()
        return self._clusterName
    #----------------------------------------------------------------------
    @property
    def description(self):
        if self._description is None:
            self.__init()
        return self._description
    #----------------------------------------------------------------------
    @property
    def isDefault(self):
        if self._isDefault is None:
            self.__init()
        return self._isDefault
    #----------------------------------------------------------------------
    @property
    def type(self):
        if self._type is None:
            self.__init()
        return self._type
    #----------------------------------------------------------------------
    @property
    def maxUploadFileSize(self):
        if self._maxUploadFileSize is None:
            self.__init()
        return self._maxUploadFileSize
    #----------------------------------------------------------------------
    @property
    def keepAliveInterval(self):
        if self._keepAliveInterval is None:
            self.__init()
        return self._keepAliveInterval
    #----------------------------------------------------------------------
    @property
    def maxInstancesPerNode(self):
        if self._maxInstancesPerNode is None:
            self.__init()
        return self._maxInstancesPerNode
    #----------------------------------------------------------------------
    @property
    def private(self):
        if self._private is None:
            self.__init()
        return self._private
    #----------------------------------------------------------------------
    @property
    def maxStartupTime(self):
        if self._maxStartupTime is None:
            self.__init()
        return self._maxStartupTime
    #----------------------------------------------------------------------
    @property
    def loadBalancing(self):
        if self._loadBalancing is None:
            self.__init()
        return self._loadBalancing
    #----------------------------------------------------------------------
    @property
    def configuredState(self):
        if self._configuredState is None:
            self.__init()
        return self._configuredState
    #----------------------------------------------------------------------
    @property
    def capabilities(self):
        if self._capabilities is None:
            self.__init()
        return self._capabilities
    #----------------------------------------------------------------------
    @property
    def isolationLevel(self):
        if self._isolationLevel is None:
            self.__init()
        return self._isolationLevel
    #----------------------------------------------------------------------
    @property
    def serviceName(self):
        if self._serviceName is None:
            self.__init()
        return self._serviceName
    #----------------------------------------------------------------------
    def start_service(self):
        """ starts the specific service """
        params = {
            "f" : "json"
        }
        uURL = self._url + "/start"
        return self._post(url=uURL, param_dict=params,
                             securityHandler=self._securityHandler,
                             proxy_url=self._proxy_url,
                             proxy_port=self._proxy_port)
    #----------------------------------------------------------------------
    def stop_service(self):
        """ stops the current service """
        params = {
            "f" : "json"
        }
        uURL = self._url + "/stop"
        return self._post(url=uURL, param_dict=params,
                             securityHandler=self._securityHandler,
                             proxy_url=self._proxy_url,
                             proxy_port=self._proxy_port)
    #----------------------------------------------------------------------
    def restart_services(self):
        """ restarts the current service """
        self.stop_service()
        self.start_service()
        return {'status': 'success'}
    #----------------------------------------------------------------------
    def delete_service(self):
        """deletes a service from arcgis server"""
        params = {
            "f" : "json",
        }
        uURL = self._url + "/delete"
        return self._post(url=uURL, param_dict=params,
                             securityHandler=self._securityHandler,
                             proxy_url=self._proxy_url,
                             proxy_port=self._proxy_port)
    #----------------------------------------------------------------------
    @property
    def status(self):
        """ returns the status of the service """
        params = {
            "f" : "json",
        }
        uURL = self._url + "/status"
        return self._get(url=uURL, param_dict=params,
                            securityHandler=self._securityHandler,
                             proxy_url=self._proxy_url,
                             proxy_port=self._proxy_port)
    #----------------------------------------------------------------------
    @property
    def statistics(self):
        """ returns the stats for the service """
        params = {
            "f" : "json"
        }
        uURL = self._url + "/statistics"
        return self._get(url=uURL, param_dict=params,
                            securityHandler=self._securityHandler,
                             proxy_url=self._proxy_url,
                             proxy_port=self._proxy_port)
    #----------------------------------------------------------------------
    @property
    def permissions(self):
        """ returns the permissions for the service """
        params = {
            "f" : "json"
        }
        uURL = self._url + "/permissions"
        return self._get(url=uURL, param_dict=params,
                            securityHandler=self._securityHandler,
                             proxy_url=self._proxy_url,
                             proxy_port=self._proxy_port)
    #----------------------------------------------------------------------
    @property
    def iteminfo(self):
        """ returns the item information """
        params = {
            "f" : "json"
        }
        uURL = self._url + "/iteminfo"
        return self._get(url=uURL, param_dict=params,
                            securityHandler=self._securityHandler,
                             proxy_url=self._proxy_url,
                             proxy_port=self._proxy_port)
    #----------------------------------------------------------------------
    def itemInfoUpload(self, folder, filePath):
        """
        Allows for the upload of new itemInfo files such as metadata.xml
        Inputs:
           folder - folder on ArcGIS Server
           filePath - full path of the file to upload
        Output:
           json as dictionary
        """
        files = {}
        url = self._url + "/iteminfo/upload"
        params = {
            "f" : "json",
            "folder" : folder
        }
        files['file'] = filePath
        return self._post(url=url,
                          param_dict=params,
                          files=files,
                          securityHandler=self._securityHandler,
                          proxy_url=self._proxy_url,
                          proxy_port=self._proxy_port)
    #----------------------------------------------------------------------
    def editItemInfo(self, json_dict):
        """
        Allows for the direct edit of the service's item's information.
        To get the current item information, pull the data by calling
        iteminfo property.  This will return the default template then pass
        this object back into the editItemInfo() as a dictionary.

        Inputs:
           json_dict - iteminfo dictionary.
        Output:
           json as dictionary
        """
        url = self._url + "/iteminfo/edit"
        params = {
            "f" : "json",
            "serviceItemInfo" : json.dumps(json_dict)
        }
        return self._post(url=url,
                             param_dict=params,
                             securityHandler=self._securityHandler,
                             proxy_url=self._proxy_url,
                             proxy_port=self._proxy_port)
    #----------------------------------------------------------------------
    def serviceManifest(self, fileType="json"):
        """
        The service manifest resource documents the data and other
        resources that define the service origins and power the service.
        This resource will tell you underlying databases and their location
        along with other supplementary files that make up the service.

        Inputs:
           fileType - this can be json or xml. json returns the
            manifest.json file. xml returns the manifest.xml file. These
            files are stored at \arcgisserver\directories\arcgissystem\
            arcgisinput\%servicename%.%servicetype%\extracted folder.

        Outputs:
            Python dictionary if fileType is json and Python object of
            xml.etree.ElementTree.ElementTree type if fileType is xml.
        """

        url = self._url + "/iteminfo/manifest/manifest.%s" % fileType
        params = {}
        f = self._get(url=url,
                      param_dict=params,
                      securityHandler=self._securityHandler,
                      proxy_url=self._proxy_url,
                      proxy_port=self._proxy_port,
                      out_folder=tempfile.gettempdir(),
                      file_name=os.path.basename(url))
        if fileType == 'json':
            return f
        if fileType == 'xml':
            return ET.ElementTree(ET.fromstring(f))
    #----------------------------------------------------------------------
    def addPermission(self, principal, isAllowed=True):
        """
           Assigns a new permission to a role (principal). The permission
           on a parent resource is automatically inherited by all child
           resources.
           Inputs:
              principal - role to be assigned
              isAllowed - access of resource by boolean
           Output:
              JSON message as dictionary
        """
        uURL = self._url + "/permissions/add"
        params = {
            "f" : "json",
            "principal" : principal,
            "isAllowed" : isAllowed
        }
        return self._post(url=uURL, param_dict=params,
                             securityHandler=self._securityHandler,
                             proxy_url=self._proxy_url,
                             proxy_port=self._proxy_port)
    #----------------------------------------------------------------------
    def edit(self, service):
        """
        To edit a service, you need to submit the complete JSON
        representation of the service, which includes the updates to the
        service properties. Editing a service causes the service to be
        restarted with updated properties.
        """
        url = self._url + "/edit"
        params = {
            "f" : "json"
        }
        if isinstance(service, str):
            params['service'] = service
        elif isinstance(service, dict):
            params['service'] = json.dumps(service)
        return self._post(url=url, param_dict=params,
                             securityHandler=self._securityHandler,
                             proxy_url=self._proxy_url,
                             proxy_port=self._proxy_port)


text:
import getpass
import logging
import os
import pwd
import socket
import sys
import tempfile

from ipalib import api
from ipalib import errors
from ipapython.ipautil import kinit_password
from ipapython.ipautil import run
from ipapython.ipautil import user_input
from novajoin.errors import ConfigurationError

logger = logging.getLogger()

class NovajoinRole(object):
    """One-stop shopping for creating the IPA permissions, privilege and role.

    Assumes that ipalib is imported and initialized and an RPC context
    already exists.
    """

    def __init__(self, keytab='/etc/nova/krb5.keytab', user='nova'):
        self.keytab = keytab
        self.user = user
        self.service = u'nova/%s' % self._get_fqdn()
        self.ccache_name = None

    def _get_fqdn(self):
        """Try to determine the fully-qualfied domain name of this box"""
        fqdn = ""
        try:
            fqdn = socket.getfqdn()
        except Exception:  # pylint: disable=broad-except
            try:
                # assume it is in the IPA domain if it comes back
                # not fully-qualified
                fqdn = socket.gethostname()
                # pylint: disable=no-member
                fqdn = fqdn + '.' + api.env.domain
            except Exception:  # pylint: disable=broad-except
                fqdn = ""
        return fqdn

    def kinit(self, principal, password):
        ccache_dir = tempfile.mkdtemp(prefix='krbcc')
        self.ccache_name = os.path.join(ccache_dir, 'ccache')

        current_ccache = os.environ.get('KRB5CCNAME')
        os.environ['KRB5CCNAME'] = self.ccache_name

        if principal.find('@') == -1:
            # pylint: disable=no-member
            principal = '%s@%s' % (principal, api.env.realm)

        try:
            kinit_password(principal, password, self.ccache_name)
        except RuntimeError as e:
            raise ConfigurationError("Kerberos authentication failed: %s" % e)
        finally:
            if current_ccache:
                os.environ['KRB5CCNAME'] = current_ccache

    def _call_ipa(self, command, args, kw):
        """Call into the IPA API.

        Duplicates are ignored to be idempotent. Other errors are
        ignored implitly because they are encapsulated in the result
        for some calls.
        """
        try:
            api.Command[command](args, **kw)
        except errors.DuplicateEntry:
            pass
        except Exception as e:  # pylint: disable=broad-except
            logger.error("Unhandled exception: %s", e)

    def _add_permissions(self):
        self._call_ipa(u'permission_add', u'Modify host password',
                       {'ipapermright': u'write',
                        'type': u'host',
                        'attrs': u'userpassword'})
        self._call_ipa(u'permission_add', u'Write host certificate',
                       {'ipapermright': u'write',
                        'type': u'host',
                        'attrs': u'usercertificate'})
        self._call_ipa(u'permission_add', u'Modify host userclass',
                       {'ipapermright': u'write',
                        'type': u'host',
                        'attrs': u'userclass'})

    def _add_privileges(self):
        self._call_ipa(u'privilege_add', u'Nova Host Management',
                       {'description': u'Nova Host Management'})

        self._call_ipa(u'privilege_add_permission', u'Nova Host Management',
                       {u'permission': [
                           u'System: add hosts',
                           u'System: remove hosts',
                           u'modify host password',
                           u'modify host userclass',
                           u'modify hosts',
                           u'System: revoke certificate',
                           u'System: manage host keytab',
                           u'System: write host certificate',
                           u'System: retrieve certificates from the ca',
                           u'System: modify services',
                           u'System: manage service keytab',
                           u'System: read dns entries',
                           u'System: remove dns entries',
                           u'System: add dns entries',
                           u'System: update dns entries']})

    def _add_role(self):
        self._call_ipa(u'role_add', u'Nova Host Manager',
                       {'description': u'Nova Host Manager'})
        self._call_ipa(u'role_add_privilege', u'Nova Host Manager',
                       {'privilege': u'Nova Host Management'})
        self._call_ipa(u'role_add_member', u'Nova Host Manager',
                       {u'service': self.service})

    def _add_service(self):
        self._call_ipa(u'service_add', self.service, {'force': True})

    def _get_keytab(self):
        if self.ccache_name:
            current_ccache = os.environ.get('KRB5CCNAME')
            os.environ['KRB5CCNAME'] = self.ccache_name

        try:
            if os.path.exists(self.keytab):
                os.unlink(self.keytab)
        except OSError as e:
            sys.exit('Could not remove %s: %s' % (self.keytab, e))

        try:
            run(['ipa-getkeytab',
                 '-s', api.env.server,  # pylint: disable=no-member
                 '-p', self.service,
                 '-k', self.keytab])
        finally:
            if current_ccache:
                os.environ['KRB5CCNAME'] = current_ccache

        # s/b already validated
        user = pwd.getpwnam(self.user)

        os.chown(self.keytab, user.pw_uid, user.pw_gid)
        os.chmod(self.keytab, 0o600)

    def configure_ipa(self):
        self._add_service()
        self._get_keytab()
        self._add_permissions()
        self._add_privileges()
        self._add_role()

def ipa_options(parser):
    parser.add_argument('--no-kinit',
                        help='Assume the user has already done a kinit',
                        action="store_true", default=False)
    parser.add_argument('--user',
                        help='User that nova services run as',
                        default='nova')
    parser.add_argument('--principal', dest='principal', default='admin',
                        help='principal to use to setup IPA integration')
    parser.add_argument('--password', dest='password',
                        help='password for the principal')
    parser.add_argument('--password-file', dest='passwordfile',
                        help='path to file containing password for '
                             'the principal')
    return parser

def validate_options(args):
    if args.get('no_kinit', False):
        return args

    if not args['principal']:
        args['principal'] = user_input("IPA admin user", "admin",
                                       allow_empty=False)

    if args['passwordfile']:
        try:
            with open(args['passwordfile']) as f:
                args['password'] = f.read()
        except IOError as e:
            raise ConfigurationError('Unable to read password file: %s'
                                     % e)
    if not args['password']:
        try:
            args['password'] = getpass.getpass("Password for %s: " %
                                               args['principal'])
        except EOFError:
            args['password'] = None
        if not args['password']:
            raise ConfigurationError('Password must be provided.')

    try:
        pwd.getpwnam(args['user'])
    except KeyError:
        raise ConfigurationError('User: %s not found on the system' %
                                 args['user'])

redpajama_set_name: RedPajamaGithub


text:
var THREE = require('three');
var createTHREEComponent = require('../../Utils').createTHREEComponent;
var THREEObject3DMixin = require('../../mixins/THREEObject3DMixin');

var THREEOrthographicCamera = createTHREEComponent(
    'OrthographicCamera',
    THREEObject3DMixin,
    {
        createTHREEObject: function() {
            return new THREE.OrthographicCamera();
        },

        applySpecificTHREEProps: function(oldProps, newProps) {
            this.transferTHREEObject3DPropsByName(oldProps, newProps,
                ['left','right','up','bottom','near','far']);

            this._THREEObject3D.updateProjectionMatrix();
        }
    }
);

module.exports = THREEOrthographicCamera;


text:
package org.apache.bookkeeper.tools.common;

import com.google.common.base.Strings;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.file.Paths;
import lombok.extern.slf4j.Slf4j;
import org.apache.bookkeeper.common.net.ServiceURI;
import org.apache.bookkeeper.tools.framework.Cli;
import org.apache.bookkeeper.tools.framework.CliCommand;
import org.apache.bookkeeper.tools.framework.CliFlags;
import org.apache.bookkeeper.tools.framework.CliSpec;
import org.apache.commons.configuration.CompositeConfiguration;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;

/**
 * Base bk command class.
 */
@Slf4j
public abstract class BKCommand<CommandFlagsT extends CliFlags> extends CliCommand<BKFlags, CommandFlagsT> {

    protected BKCommand(CliSpec<CommandFlagsT> spec) {
        super(spec);
    }

    @Override
    public Boolean apply(BKFlags globalFlags, String[] args) {
        CliSpec<CommandFlagsT> newSpec = CliSpec.newBuilder(spec)
            .withRunFunc(cmdFlags -> apply(globalFlags, cmdFlags))
            .build();
        return 0 == Cli.runCli(newSpec, args);
    }

    protected boolean apply(BKFlags bkFlags, CommandFlagsT cmdFlags) {
        ServiceURI serviceURI = null;

        if (null != bkFlags.serviceUri) {
            serviceURI = ServiceURI.create(bkFlags.serviceUri);
            if (!acceptServiceUri(serviceURI)) {
                log.error("Unresolvable service uri by command '{}' : {}",
                    path(), bkFlags.serviceUri);
                return false;
            }
        }

        CompositeConfiguration conf = new CompositeConfiguration();
        if (!Strings.isNullOrEmpty(bkFlags.configFile)) {
            try {
                URL configFileUrl = Paths.get(bkFlags.configFile).toUri().toURL();
                PropertiesConfiguration loadedConf = new PropertiesConfiguration(configFileUrl);
                conf.addConfiguration(loadedConf);
            } catch (MalformedURLException e) {
                log.error("Could not open configuration file : {}", bkFlags.configFile, e);
                throw new IllegalArgumentException(e);
            } catch (ConfigurationException e) {
                log.error("Malformed configuration file : {}", bkFlags.configFile, e);
                throw new IllegalArgumentException(e);
            }
        }

        return apply(serviceURI, conf, bkFlags, cmdFlags);
    }

    protected boolean acceptServiceUri(ServiceURI serviceURI) {
        return true;
    }

    protected abstract boolean apply(ServiceURI serviceURI,
                                     CompositeConfiguration conf,
                                     BKFlags globalFlags,
                                     CommandFlagsT cmdFlags);

}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<TITLE
>CREATE FOREIGN DATA WRAPPER</TITLE
><META
NAME="GENERATOR"
CONTENT="Modular DocBook HTML Stylesheet Version 1.79"><LINK
REV="MADE"
HREF="mailto:pgsql-docs@postgresql.org"><LINK
REL="HOME"
TITLE="PostgreSQL 9.6.2 Documentation"
HREF="index.html"><LINK
REL="UP"
TITLE="SQL Commands"
HREF="sql-commands.html"><LINK
REL="PREVIOUS"
TITLE="CREATE EXTENSION"
HREF="sql-createextension.html"><LINK
REL="NEXT"
TITLE="CREATE FOREIGN TABLE"
HREF="sql-createforeigntable.html"><LINK
REL="STYLESHEET"
TYPE="text/css"
HREF="stylesheet.css"><META
HTTP-EQUIV="Content-Type"
CONTENT="text/html; charset=ISO-8859-1"><META
NAME="creation"
CONTENT="2017-02-06T21:56:32">

PostgreSQL 9.6.2 Documentation

Prev	Up		Next

CREATE FOREIGN DATA WRAPPER

Name
CREATE FOREIGN DATA WRAPPER -- define a new foreign-data wrapper

Synopsis

CREATE FOREIGN DATA WRAPPER <TT
CLASS="REPLACEABLE"
>name</TT
>
    [ HANDLER <TT
CLASS="REPLACEABLE"
>handler_function</TT
> | NO HANDLER ]
    [ VALIDATOR <TT
CLASS="REPLACEABLE"
>validator_function</TT
> | NO VALIDATOR ]
    [ OPTIONS ( <TT
CLASS="REPLACEABLE"
>option</TT
> '<TT
CLASS="REPLACEABLE"
>value</TT
>' [, ... ] ) ]

Description

   <TT
CLASS="COMMAND"
>CREATE FOREIGN DATA WRAPPER</TT
> creates a new
   foreign-data wrapper.  The user who defines a foreign-data wrapper
   becomes its owner.

   The foreign-data wrapper name must be unique within the database.

   Only superusers can create foreign-data wrappers.

Parameters

<TT
CLASS="REPLACEABLE"
>name</TT
>

      The name of the foreign-data wrapper to be created.

<TT
CLASS="LITERAL"
>HANDLER <TT
CLASS="REPLACEABLE"
>handler_function</TT
></TT
>

<TT
CLASS="REPLACEABLE"
>handler_function</TT
> is the
      name of a previously registered function that will be called to
      retrieve the execution functions for foreign tables.
      The handler function must take no arguments, and
      its return type must be <TT
CLASS="TYPE"
>fdw_handler</TT
>.

      It is possible to create a foreign-data wrapper with no handler
      function, but foreign tables using such a wrapper can only be declared,
      not accessed.

<TT
CLASS="LITERAL"
>VALIDATOR <TT
CLASS="REPLACEABLE"
>validator_function</TT
></TT
>

<TT
CLASS="REPLACEABLE"
>validator_function</TT
>
      is the name of a previously registered function that will be called to
      check the generic options given to the foreign-data wrapper, as
      well as options for foreign servers, user mappings and foreign tables
      using the foreign-data wrapper.  If no validator function or <TT
CLASS="LITERAL"
>NO
      VALIDATOR</TT
> is specified, then options will not be
      checked at creation time.  (Foreign-data wrappers will possibly
      ignore or reject invalid option specifications at run time,
      depending on the implementation.)  The validator function must
      take two arguments: one of type <TT
CLASS="TYPE"
>text[]</TT
>, which will
      contain the array of options as stored in the system catalogs,
      and one of type <TT
CLASS="TYPE"
>oid</TT
>, which will be the OID of the
      system catalog containing the options. The return type is ignored;
      the function should report invalid options using the
      ereport(ERROR) function.

<TT
CLASS="LITERAL"
>OPTIONS ( <TT
CLASS="REPLACEABLE"
>option</TT
> '<TT
CLASS="REPLACEABLE"
>value</TT
>' [, ... ] )</TT
>

      This clause specifies options for the new foreign-data wrapper.
      The allowed option names and values are specific to each foreign
      data wrapper and are validated using the foreign-data wrapper's
      validator function.  Option names must be unique.

Notes

   PostgreSQL's foreign-data functionality is still under
   active development.  Optimization of queries is primitive (and mostly left
   to the wrapper, too).  Thus, there is considerable room for future
   performance improvements.

Examples

   Create a useless foreign-data wrapper <TT
CLASS="LITERAL"
>dummy</TT
>:

CREATE FOREIGN DATA WRAPPER dummy;

   Create a foreign-data wrapper <TT
CLASS="LITERAL"
>file</TT
> with
   handler function <TT
CLASS="LITERAL"
>file_fdw_handler</TT
>:

CREATE FOREIGN DATA WRAPPER file HANDLER file_fdw_handler;

   Create a foreign-data wrapper <TT
CLASS="LITERAL"
>mywrapper</TT
> with some
   options:

CREATE FOREIGN DATA WRAPPER mywrapper
    OPTIONS (debug 'true');

Compatibility

   <TT
CLASS="COMMAND"
>CREATE FOREIGN DATA WRAPPER</TT
> conforms to ISO/IEC
   9075-9 (SQL/MED), with the exception that the <TT
CLASS="LITERAL"
>HANDLER</TT
>
   and <TT
CLASS="LITERAL"
>VALIDATOR</TT
> clauses are extensions and the standard
   clauses <TT
CLASS="LITERAL"
>LIBRARY</TT
> and <TT
CLASS="LITERAL"
>LANGUAGE</TT
>
   are not implemented in PostgreSQL.

   Note, however, that the SQL/MED functionality as a whole is not yet
   conforming.

See Also
ALTER FOREIGN DATA WRAPPER, DROP FOREIGN DATA WRAPPER, CREATE SERVER, CREATE USER MAPPING, CREATE FOREIGN TABLE

Prev	Home	Next

CREATE EXTENSION	Up	CREATE FOREIGN TABLE


text:
package com.spotify.helios.system;

import com.spotify.helios.Polling;
import com.spotify.helios.client.HeliosClient;
import com.spotify.helios.common.descriptors.Deployment;
import com.spotify.helios.common.descriptors.Job;
import com.spotify.helios.common.descriptors.JobId;
import com.spotify.helios.common.descriptors.PortMapping;
import com.spotify.helios.common.descriptors.TaskStatus;
import com.spotify.helios.common.protocol.CreateJobResponse;
import com.spotify.helios.common.protocol.JobDeployResponse;

import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.util.concurrent.Callable;

import static com.google.common.base.Preconditions.checkArgument;
import static com.spotify.helios.common.descriptors.Goal.START;
import static com.spotify.helios.common.descriptors.HostStatus.Status.UP;
import static com.spotify.helios.common.descriptors.TaskStatus.State.RUNNING;
import static java.nio.charset.StandardCharsets.UTF_8;
import static java.util.Arrays.asList;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.junit.Assert.assertEquals;

public class VolumeTest extends SystemTestBase {

  private HeliosClient client;
  private Job job;

  @Before
  public void setup() throws Exception {
    startDefaultMaster();

    client = defaultClient();
    startDefaultAgent(testHost());

    job = Job.newBuilder()
        .setName(testJobName)
        .setVersion(testJobVersion)
        .setImage(BUSYBOX)
        .addVolume("/volume")
        .addVolume("/urandom", "/dev/urandom")
        .addVolume("/hostdev", "/dev")
        .setCommand(asList("sh", "-c", "echo foo > /volume/bar; " +
                                       "nc -p 4711 -le dd if=/volume/bar;" +
                                       "nc -p 4712 -lle dd if=/urandom bs=1 count=4"))
        .addPort("bar", PortMapping.of(4711))
        .addPort("urandom", PortMapping.of(4712))
        .setCreatingUser(TEST_USER)
        .build();
  }

  @Test
  public void testClient() throws Exception {
    final CreateJobResponse created = client.createJob(job).get();
    assertEquals(CreateJobResponse.Status.OK, created.getStatus());
    assertVolumes(job.getId());
  }

  @Test
  public void testCli() throws Exception {
    final JobId jobId = createJob(job);
    assertVolumes(jobId);
  }

  public void assertVolumes(final JobId jobId) throws Exception {
    // Wait for agent to come up
    awaitHostRegistered(client, testHost(), LONG_WAIT_SECONDS, SECONDS);
    awaitHostStatus(client, testHost(), UP, LONG_WAIT_SECONDS, SECONDS);

    // Deploy the job on the agent
    final Deployment deployment = Deployment.of(jobId, START);
    final JobDeployResponse deployed = client.deploy(deployment, testHost()).get();
    assertEquals(JobDeployResponse.Status.OK, deployed.getStatus());

    // Wait for the job to run
    final TaskStatus taskStatus = awaitJobState(
        client, testHost(), jobId, RUNNING, LONG_WAIT_SECONDS, SECONDS);
    assertJobEquals(job, taskStatus.getJob());

    final Integer bar = taskStatus.getPorts().get("bar").getExternalPort();
    final Integer urandom = taskStatus.getPorts().get("urandom").getExternalPort();

    assert bar != null;
    assert urandom != null;

    // Read "foo" from /volume/bar
    final String foo = recvUtf8(bar, 3);
    assertEquals("foo", foo);

    // Attempt to read some random bytes from the mounted /dev/urandom
    recv(urandom, 4);
  }

  private String recvUtf8(final int port, final int n) throws Exception {
    final byte[] bytes = recv(port, n);
    return new String(bytes, UTF_8);
  }

  private byte[] recv(final int port, final int n) throws Exception {
    checkArgument(n > 0, "n must be > 0");
    return Polling.await(LONG_WAIT_SECONDS, SECONDS, new Callable<byte[]>() {
      @Override
      public byte[] call() {
        try (final Socket s = new Socket(DOCKER_HOST.address(), port)) {
          final byte[] bytes = new byte[n];
          final InputStream is = s.getInputStream();
          final int first = is.read();
          // Check if the uml kernel slirp driver did an accept->close on us,
          // i.e. the actual listener is not up yet
          if (first == -1) {
            return null;
          }
          bytes[0] = (byte) first;
          for (int i = 1; i < n; i++) {
            bytes[i] = (byte) is.read();
          }
          return bytes;
        } catch (IOException e) {
          return null;
        }
      }
    });
  }
}


text:
package scintuit.util

import scintuit.raw.customer.{Customer, CustomerIO, CustomerOp}
import scintuit.util.auth.AuthConfig
import scintuit.util.cache.Cache
import scintuit.util.capture.Capture

import scintuit.util.http.{Response, Request, Executor}
import scintuit.util.oauth.OAuthToken
import scintuit.util.parse.Decoder
import scintuit.util.prepare.Encoder

import scalaz._
import scalaz.syntax.monad._

object transactor {

  class Transactor[M[_] : Monad : Capture : Catchable](
    config: AuthConfig,
    cache: Cache[M, String, OAuthToken],
    executor: Executor[M]
  )(
    implicit
    encode: Encoder,
    decode: Decoder
  ) {

    import scintuit.util.time._

    def logFor[C: Customer](customer: C, execute: Request => M[Response])(request: Request): M[Response] =
      for {
         start              <- now[M]
         timedResponse      <- timed(execute)(request)
         _                  <- log.logHttp[M, C](customer, start, request, timedResponse._2, timedResponse._1)
      } yield timedResponse._2

    def findToken[C: Customer](customer: C): M[OAuthToken] =
      cache.get(Customer[C].name(customer), oauth.fetchToken(logFor(customer, executor.execute))(config, _))

    def interpK[C: Customer]: CustomerOp ~> Kleisli[M, C, ?] = new (CustomerOp ~> Kleisli[M, C, ?]) {
      def apply[A](op: CustomerOp[A]): Kleisli[M, C, A] =
        for {
          customer <- Kleisli.ask[M, C]
          token    <- findToken(customer).liftM[Kleisli[?[_], C, ?]]
          request  <- prepare.prepareRequest(encode)(op).point[Kleisli[M, C, ?]]
          response <- logFor(customer, executor.sign(config.oauthConsumer, token))(request).liftM[Kleisli[?[_], C, ?]]
          result   <- parse.parseResponse[M, C, A](decode)(customer, op, response).liftM[Kleisli[?[_], C, ?]]
        } yield result
    }

    def transK[C: Customer]: CustomerIO ~> Kleisli[M, C, ?] = new (CustomerIO ~> Kleisli[M, C, ?]) {
      def apply[A](ma: CustomerIO[A]): Kleisli[M, C, A] =
        Free.runFC[CustomerOp, Kleisli[M, C, ?], A](ma)(interpK)
    }

    def trans[C: Customer](customer: C): CustomerIO ~> M = new (CustomerIO ~> M) {
      override def apply[A](ma: CustomerIO[A]): M[A] =
        transK.apply(ma)(customer)
    }
  }

}


text:
namespace LinkedListTraversal
{
    using System;
    using System.Linq;
    using System.Reflection;

    public class StartUp
    {
        public static void Main(string[] args)
        {
            CustomLinkedList<int> customList = new CustomLinkedList<int>();
            int n = int.Parse(Console.ReadLine());

            for (int i = 0; i < n; i++)
            {
                string[] data = Console.ReadLine().Split(new []{' '}, StringSplitOptions.RemoveEmptyEntries);
                string methodName = data[0];
                int value = int.Parse(data[1]);

                MethodInfo method = customList.GetType()
                    .GetMethods(BindingFlags.Instance | BindingFlags.Public)
                    .FirstOrDefault(x => x.Name == methodName);

                method.Invoke(customList, new object[] {value});
            }

            Console.WriteLine(customList.Count);

            foreach (var item in customList)
            {
                Console.Write($"{item} ");
            }

            Console.WriteLine();
        }
    }
}


text:
package raddress

import (
	"bytes"
	"encoding/csv"
	"fmt"
	"github.com/Unknwon/com"
	"github.com/fatih/color"
	"strings"
	"sync"
)

var csvApi *csvapi

type csvapi struct {
	regions []Item
	cities  []Item
}

type Item struct {
	Id       int
	RegionId int
	Name     string
}

var (
	CsvRegion = "cr"
	CsvCity   = "cc"
)

func init() {
	csvApi = new(csvapi)
	loadCsv(CsvRegion)
	loadCsv(CsvCity)
}

func loadCsv(t string) {

	var (
		r  *bytes.Reader
		cr *csv.Reader

		fileName string
		arr      []Item
	)

	switch t {
	case CsvRegion:
		fileName = "region"
	case CsvCity:
		fileName = "city"
	}

	r = bytes.NewReader(MustAsset("data/" + fileName + ".csv"))
	cr = csv.NewReader(r)
	cr.Comma = ';'

	// read header
	_, e := cr.Read()
	if e != nil {
		panic(e)
	}

	for line, e := cr.Read(); e == nil; line, e = cr.Read() {
		if len(line) != 4 {
			color.Red("Line should contain 4 elements, got %d", len(line))
			continue
		}

		// shoose Russia regions
		if line[1] != "3159" {
			continue
		}
		arr = append(arr,
			Item{Id: com.StrTo(line[0]).MustInt(),
				RegionId: com.StrTo(line[2]).MustInt(),
				Name:     line[3]})
	}
	switch t {
	case CsvRegion:
		csvApi.regions = append(csvApi.regions, arr...)
	case CsvCity:
		fileName = "city"
		csvApi.cities = append(csvApi.cities, arr...)
	}
}

func GetCityByName(city string) Item {
	city = strings.ToLower(city)
	for _, v := range csvApi.cities {
		if strings.ToLower(v.Name) == city {
			return v
		}
	}
	return Item{}
}

func GetCityRegion(city string) Item {
	c := GetCityByName(city)
	return GetRegion(c.RegionId)
}

func GetRegion(id int) Item {
	for _, v := range csvApi.regions {
		if v.Id == id {
			return v
		}
	}
	return Item{}
}

var (
	mx     sync.Mutex
	ccache = map[string][]Item{}
)

func GetRegionCities(region string) (res []Item) {
	mx.Lock()
	if res, ok := ccache[region]; ok {
		mx.Unlock()
		return res
	} else {
		mx.Unlock()
	}

	region = strings.ToLower(region)
	region = strings.TrimSuffix(region, " район")
	fmt.Println(region)
	for _, v := range csvApi.regions {
		if strings.HasPrefix(strings.ToLower(v.Name), region) {
			for _, city := range csvApi.cities {
				if city.RegionId == v.Id {
					if hasStr(city.Name, allowedCities) {
						res = append(res, city)
					}
				}
			}
		}
	}
	mx.Lock()
	ccache[region] = res
	mx.Unlock()
	return
}

var allowedCities []string

func AllowCities(arr []string) {
	allowedCities = arr
}

func hasStr(str string, arr []string) bool {
	if arr == nil {
		return true
	}
	for _, v := range arr {
		if strings.ToLower(v) == strings.ToLower(str) {
			return true
		}
	}
	return false
}


text:
package org.opentreeoflife.smasher

import scala.collection.JavaConversions._
import org.semanticweb.owlapi.apibinding.OWLManager
import org.semanticweb.owlapi.model.IRI
import java.io.File

object TranslateTaxonomy extends App {

  val inputDirectory = args(0)
  val outFile = args(1)
  val manager = OWLManager.createOWLOntologyManager
  val taxonomy = new UnionTaxonomy()
  taxonomy.loadTaxonomy(inputDirectory)
  println("Converting nodes")
  val nodes = taxonomy.roots.toSet flatMap TaxonomyTranslator.translateWithDescendants
  println("Converting synonyms")
  val synonyms = TaxonomyTranslator.translateSynonyms(taxonomy.nameIndex)
  println("Building ontology")
  val ontology = manager.createOntology(nodes ++ synonyms)
  println("Writing ontology")
  manager.saveOntology(ontology, IRI.create(new File(outFile)))

}


text:
import { IReadonlyTheme } from '@microsoft/sp-component-base';
import { WebPartContext } from "@microsoft/sp-webpart-base";
import { DisplayMode } from "@microsoft/sp-core-library";
import { IPropertyFieldSite } from '@pnp/spfx-property-controls/lib/PropertyFieldSitePicker';
export interface IMySitesProps {
  title: string;
  context: WebPartContext;
  themeVariant: IReadonlyTheme | undefined;
  displayMode: DisplayMode;
  updateProperty: (value: string) => void;
  itemsPerPage:number;
  defaultSitesToFilter: IPropertyFieldSite[];
  enableFilterSharepointSites:boolean;
  enableFilterO365groups: boolean;
  enableFilterSitesWithSubWebs: boolean;
}


text:
import { moduleForModel, test } from 'ember-qunit';

moduleForModel('code-system-concept', 'Unit | Serializer | CodeSystem_Concept', {
  needs: [
    'serializer:code-system-concept',
    'model:code-system-designation',
    'model:code-system-property-1',
    'model:code-system-concept',
    'model:meta',
    'model:narrative',
    'model:resource',
    'model:extension'
  ]
});

test('it serializes records', function(assert) {
  const record = this.subject(),
    serializeRecord = record.serialize();

  assert.ok(serializeRecord);
});