code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def standardGeographyQuery(self, sourceCountry=None, optionalCountryDataset=None, geographyLayers=None, geographyIDs=None, geographyQuery=None, returnSubGeographyLayer=False, subGeographyLayer=None, subGeographyQuery=None, outSR=4326, returnGeometry=False, returnCentroids=False, generalizationLevel=0, useFuzzySearch=False, featureLimit=1000): """ The GeoEnrichment service provides a helper method that returns standard geography IDs and features for the supported geographic levels in the United States and Canada. As indicated throughout this documentation guide, the GeoEnrichment service uses the concept of a study area to define the location of the point or area that you want to enrich with additional information. Locations can also be passed as one or many named statistical areas. This form of a study area lets you define an area by the ID of a standard geographic statistical feature, such as a census or postal area. For example, to obtain enrichment information for a U.S. state, county or ZIP Code or a Canadian province or postal code, the Standard Geography Query helper method allows you to search and query standard geography areas so that they can be used in the GeoEnrichment method to obtain facts about the location. The most common workflow for this service is to find a FIPS (standard geography ID) for a geographic name. For example, you can use this service to find the FIPS for the county of San Diego which is 06073. You can then use this FIPS ID within the GeoEnrichment service study area definition to get geometry and optional demographic data for the county. This study area definition is passed as a parameter to the GeoEnrichment service to return data defined in the enrichment pack and optionally return geometry for the feature. For examples and more help with this function see: http://resources.arcgis.com/en/help/arcgis-rest-api/#/Standard_geography_query/02r30000000q000000/ Inputs: sourceCountry - Optional parameter to specify the source country for the search. Use this parameter to limit the search and query of standard geographic features to one country. This parameter supports both the two-digit and three-digit country codes illustrated in the coverage table. optionalCountryDataset - Optional parameter to specify a specific dataset within a defined country. geographyLayers - Optional parameter to specify which standard geography layers are being queried or searched. If this parameter is not provided, all layers within the defined country will be queried. geographyIDs - Optional parameter to specify which IDs for the standard geography layers are being queried or searched. You can use this parameter to return attributes and/or geometry for standard geographic areas for administrative areas where you already know the ID, for example, if you know the Federal Information Processing Standard (FIPS) Codes for a U.S. state or county; or, in Canada, to return the geometry and attributes for a Forward Sortation Area (FSA). geographyQuery - Optional parameter to specify the text to query and search the standard geography layers specified. You can use this parameter to query and find standard geography features that meet an input term, for example, for a list of all the U.S. counties that contain the word "orange". The geographyQuery parameter can be a string that contains one or more words. returnSubGeographyLayer - Use this optional parameter to return all the subgeographic areas that are within a parent geography. For example, you could return all the U.S. counties for a given U.S. state or you could return all the Canadian postal areas (FSAs) within a Census Metropolitan Area (city). When this parameter is set to true, the output features will be defined in the subGeographyLayer. The output geometries will be in the spatial reference system defined by outSR. subGeographyLayer - Use this optional parameter to return all the subgeographic areas that are within a parent geography. For example, you could return all the U.S. counties within a given U.S. state or you could return all the Canadian postal areas (FSAs) within a Census Metropolitan Areas (city). When this parameter is set to true, the output features will be defined in the subGeographyLayer. The output geometries will be in the spatial reference system defined by outSR. subGeographyQuery - Optional parameter to filter the results of the subgeography features that are returned by a search term. You can use this parameter to query and find subgeography features that meet an input term. This parameter is used to filter the list of subgeography features that are within a parent geography. For example, you may want a list of all the ZIP Codes that are within "San Diego County" and filter the results so that only ZIP Codes that start with "921" are included in the output response. The subgeography query is a string that contains one or more words. outSR - Optional parameter to request the output geometries in a specified spatial reference system. returnGeometry - Optional parameter to request the output geometries in the response. returnCentroids - Optional Boolean parameter to request the output geometry to return the center point for each feature. Use this parameter to return all the geometries as points. For example, you could return all U.S. ZIP Code centroids (points) rather than providing the boundaries. generalizationLevel - Optional integer that specifies the level of generalization or detail in the area representations of the administrative boundary or standard geographic data layers. Values must be whole integers from 0 through 6, where 0 is most detailed and 6 is most generalized. useFuzzySearch - Optional Boolean parameter to define if text provided in the geographyQuery parameter should utilize fuzzy search logic. Fuzzy searches are based on the Levenshtein Distance or Edit Distance algorithm. featureLimit - Optional integer value where you can limit the number of features that are returned from the geographyQuery. """ url = self._base_url + self._url_standard_geography_query_execute params = { "f" : "json" } if not sourceCountry is None: params['sourceCountry'] = sourceCountry if not optionalCountryDataset is None: params['optionalCountryDataset'] = optionalCountryDataset if not geographyLayers is None: params['geographylayers'] = geographyLayers if not geographyIDs is None: params['geographyids'] = json.dumps(geographyIDs) if not geographyQuery is None: params['geographyQuery'] = geographyQuery if not returnSubGeographyLayer is None and \ isinstance(returnSubGeographyLayer, bool): params['returnSubGeographyLayer'] = returnSubGeographyLayer if not subGeographyLayer is None: params['subGeographyLayer'] = json.dumps(subGeographyLayer) if not subGeographyQuery is None: params['subGeographyQuery'] = subGeographyQuery if not outSR is None and \ isinstance(outSR, int): params['outSR'] = outSR if not returnGeometry is None and \ isinstance(returnGeometry, bool): params['returnGeometry'] = returnGeometry if not returnCentroids is None and \ isinstance(returnCentroids, bool): params['returnCentroids'] = returnCentroids if not generalizationLevel is None and \ isinstance(generalizationLevel, int): params['generalizationLevel'] = generalizationLevel if not useFuzzySearch is None and \ isinstance(useFuzzySearch, bool): params['useFuzzySearch'] = json.dumps(useFuzzySearch) if featureLimit is None: featureLimit = 1000 elif isinstance(featureLimit, int): params['featureLimit'] = featureLimit else: params['featureLimit'] = 1000 return self._post(url=url, param_dict=params, securityHandler=self._securityHandler, proxy_url=self._proxy_url, proxy_port=self._proxy_port)
The GeoEnrichment service provides a helper method that returns standard geography IDs and features for the supported geographic levels in the United States and Canada. As indicated throughout this documentation guide, the GeoEnrichment service uses the concept of a study area to define the location of the point or area that you want to enrich with additional information. Locations can also be passed as one or many named statistical areas. This form of a study area lets you define an area by the ID of a standard geographic statistical feature, such as a census or postal area. For example, to obtain enrichment information for a U.S. state, county or ZIP Code or a Canadian province or postal code, the Standard Geography Query helper method allows you to search and query standard geography areas so that they can be used in the GeoEnrichment method to obtain facts about the location. The most common workflow for this service is to find a FIPS (standard geography ID) for a geographic name. For example, you can use this service to find the FIPS for the county of San Diego which is 06073. You can then use this FIPS ID within the GeoEnrichment service study area definition to get geometry and optional demographic data for the county. This study area definition is passed as a parameter to the GeoEnrichment service to return data defined in the enrichment pack and optionally return geometry for the feature. For examples and more help with this function see: http://resources.arcgis.com/en/help/arcgis-rest-api/#/Standard_geography_query/02r30000000q000000/ Inputs: sourceCountry - Optional parameter to specify the source country for the search. Use this parameter to limit the search and query of standard geographic features to one country. This parameter supports both the two-digit and three-digit country codes illustrated in the coverage table. optionalCountryDataset - Optional parameter to specify a specific dataset within a defined country. geographyLayers - Optional parameter to specify which standard geography layers are being queried or searched. If this parameter is not provided, all layers within the defined country will be queried. geographyIDs - Optional parameter to specify which IDs for the standard geography layers are being queried or searched. You can use this parameter to return attributes and/or geometry for standard geographic areas for administrative areas where you already know the ID, for example, if you know the Federal Information Processing Standard (FIPS) Codes for a U.S. state or county; or, in Canada, to return the geometry and attributes for a Forward Sortation Area (FSA). geographyQuery - Optional parameter to specify the text to query and search the standard geography layers specified. You can use this parameter to query and find standard geography features that meet an input term, for example, for a list of all the U.S. counties that contain the word "orange". The geographyQuery parameter can be a string that contains one or more words. returnSubGeographyLayer - Use this optional parameter to return all the subgeographic areas that are within a parent geography. For example, you could return all the U.S. counties for a given U.S. state or you could return all the Canadian postal areas (FSAs) within a Census Metropolitan Area (city). When this parameter is set to true, the output features will be defined in the subGeographyLayer. The output geometries will be in the spatial reference system defined by outSR. subGeographyLayer - Use this optional parameter to return all the subgeographic areas that are within a parent geography. For example, you could return all the U.S. counties within a given U.S. state or you could return all the Canadian postal areas (FSAs) within a Census Metropolitan Areas (city). When this parameter is set to true, the output features will be defined in the subGeographyLayer. The output geometries will be in the spatial reference system defined by outSR. subGeographyQuery - Optional parameter to filter the results of the subgeography features that are returned by a search term. You can use this parameter to query and find subgeography features that meet an input term. This parameter is used to filter the list of subgeography features that are within a parent geography. For example, you may want a list of all the ZIP Codes that are within "San Diego County" and filter the results so that only ZIP Codes that start with "921" are included in the output response. The subgeography query is a string that contains one or more words. outSR - Optional parameter to request the output geometries in a specified spatial reference system. returnGeometry - Optional parameter to request the output geometries in the response. returnCentroids - Optional Boolean parameter to request the output geometry to return the center point for each feature. Use this parameter to return all the geometries as points. For example, you could return all U.S. ZIP Code centroids (points) rather than providing the boundaries. generalizationLevel - Optional integer that specifies the level of generalization or detail in the area representations of the administrative boundary or standard geographic data layers. Values must be whole integers from 0 through 6, where 0 is most detailed and 6 is most generalized. useFuzzySearch - Optional Boolean parameter to define if text provided in the geographyQuery parameter should utilize fuzzy search logic. Fuzzy searches are based on the Levenshtein Distance or Edit Distance algorithm. featureLimit - Optional integer value where you can limit the number of features that are returned from the geographyQuery.
Below is the the instruction that describes the task: ### Input: The GeoEnrichment service provides a helper method that returns standard geography IDs and features for the supported geographic levels in the United States and Canada. As indicated throughout this documentation guide, the GeoEnrichment service uses the concept of a study area to define the location of the point or area that you want to enrich with additional information. Locations can also be passed as one or many named statistical areas. This form of a study area lets you define an area by the ID of a standard geographic statistical feature, such as a census or postal area. For example, to obtain enrichment information for a U.S. state, county or ZIP Code or a Canadian province or postal code, the Standard Geography Query helper method allows you to search and query standard geography areas so that they can be used in the GeoEnrichment method to obtain facts about the location. The most common workflow for this service is to find a FIPS (standard geography ID) for a geographic name. For example, you can use this service to find the FIPS for the county of San Diego which is 06073. You can then use this FIPS ID within the GeoEnrichment service study area definition to get geometry and optional demographic data for the county. This study area definition is passed as a parameter to the GeoEnrichment service to return data defined in the enrichment pack and optionally return geometry for the feature. For examples and more help with this function see: http://resources.arcgis.com/en/help/arcgis-rest-api/#/Standard_geography_query/02r30000000q000000/ Inputs: sourceCountry - Optional parameter to specify the source country for the search. Use this parameter to limit the search and query of standard geographic features to one country. This parameter supports both the two-digit and three-digit country codes illustrated in the coverage table. optionalCountryDataset - Optional parameter to specify a specific dataset within a defined country. geographyLayers - Optional parameter to specify which standard geography layers are being queried or searched. If this parameter is not provided, all layers within the defined country will be queried. geographyIDs - Optional parameter to specify which IDs for the standard geography layers are being queried or searched. You can use this parameter to return attributes and/or geometry for standard geographic areas for administrative areas where you already know the ID, for example, if you know the Federal Information Processing Standard (FIPS) Codes for a U.S. state or county; or, in Canada, to return the geometry and attributes for a Forward Sortation Area (FSA). geographyQuery - Optional parameter to specify the text to query and search the standard geography layers specified. You can use this parameter to query and find standard geography features that meet an input term, for example, for a list of all the U.S. counties that contain the word "orange". The geographyQuery parameter can be a string that contains one or more words. returnSubGeographyLayer - Use this optional parameter to return all the subgeographic areas that are within a parent geography. For example, you could return all the U.S. counties for a given U.S. state or you could return all the Canadian postal areas (FSAs) within a Census Metropolitan Area (city). When this parameter is set to true, the output features will be defined in the subGeographyLayer. The output geometries will be in the spatial reference system defined by outSR. subGeographyLayer - Use this optional parameter to return all the subgeographic areas that are within a parent geography. For example, you could return all the U.S. counties within a given U.S. state or you could return all the Canadian postal areas (FSAs) within a Census Metropolitan Areas (city). When this parameter is set to true, the output features will be defined in the subGeographyLayer. The output geometries will be in the spatial reference system defined by outSR. subGeographyQuery - Optional parameter to filter the results of the subgeography features that are returned by a search term. You can use this parameter to query and find subgeography features that meet an input term. This parameter is used to filter the list of subgeography features that are within a parent geography. For example, you may want a list of all the ZIP Codes that are within "San Diego County" and filter the results so that only ZIP Codes that start with "921" are included in the output response. The subgeography query is a string that contains one or more words. outSR - Optional parameter to request the output geometries in a specified spatial reference system. returnGeometry - Optional parameter to request the output geometries in the response. returnCentroids - Optional Boolean parameter to request the output geometry to return the center point for each feature. Use this parameter to return all the geometries as points. For example, you could return all U.S. ZIP Code centroids (points) rather than providing the boundaries. generalizationLevel - Optional integer that specifies the level of generalization or detail in the area representations of the administrative boundary or standard geographic data layers. Values must be whole integers from 0 through 6, where 0 is most detailed and 6 is most generalized. useFuzzySearch - Optional Boolean parameter to define if text provided in the geographyQuery parameter should utilize fuzzy search logic. Fuzzy searches are based on the Levenshtein Distance or Edit Distance algorithm. featureLimit - Optional integer value where you can limit the number of features that are returned from the geographyQuery. ### Response: def standardGeographyQuery(self, sourceCountry=None, optionalCountryDataset=None, geographyLayers=None, geographyIDs=None, geographyQuery=None, returnSubGeographyLayer=False, subGeographyLayer=None, subGeographyQuery=None, outSR=4326, returnGeometry=False, returnCentroids=False, generalizationLevel=0, useFuzzySearch=False, featureLimit=1000): """ The GeoEnrichment service provides a helper method that returns standard geography IDs and features for the supported geographic levels in the United States and Canada. As indicated throughout this documentation guide, the GeoEnrichment service uses the concept of a study area to define the location of the point or area that you want to enrich with additional information. Locations can also be passed as one or many named statistical areas. This form of a study area lets you define an area by the ID of a standard geographic statistical feature, such as a census or postal area. For example, to obtain enrichment information for a U.S. state, county or ZIP Code or a Canadian province or postal code, the Standard Geography Query helper method allows you to search and query standard geography areas so that they can be used in the GeoEnrichment method to obtain facts about the location. The most common workflow for this service is to find a FIPS (standard geography ID) for a geographic name. For example, you can use this service to find the FIPS for the county of San Diego which is 06073. You can then use this FIPS ID within the GeoEnrichment service study area definition to get geometry and optional demographic data for the county. This study area definition is passed as a parameter to the GeoEnrichment service to return data defined in the enrichment pack and optionally return geometry for the feature. For examples and more help with this function see: http://resources.arcgis.com/en/help/arcgis-rest-api/#/Standard_geography_query/02r30000000q000000/ Inputs: sourceCountry - Optional parameter to specify the source country for the search. Use this parameter to limit the search and query of standard geographic features to one country. This parameter supports both the two-digit and three-digit country codes illustrated in the coverage table. optionalCountryDataset - Optional parameter to specify a specific dataset within a defined country. geographyLayers - Optional parameter to specify which standard geography layers are being queried or searched. If this parameter is not provided, all layers within the defined country will be queried. geographyIDs - Optional parameter to specify which IDs for the standard geography layers are being queried or searched. You can use this parameter to return attributes and/or geometry for standard geographic areas for administrative areas where you already know the ID, for example, if you know the Federal Information Processing Standard (FIPS) Codes for a U.S. state or county; or, in Canada, to return the geometry and attributes for a Forward Sortation Area (FSA). geographyQuery - Optional parameter to specify the text to query and search the standard geography layers specified. You can use this parameter to query and find standard geography features that meet an input term, for example, for a list of all the U.S. counties that contain the word "orange". The geographyQuery parameter can be a string that contains one or more words. returnSubGeographyLayer - Use this optional parameter to return all the subgeographic areas that are within a parent geography. For example, you could return all the U.S. counties for a given U.S. state or you could return all the Canadian postal areas (FSAs) within a Census Metropolitan Area (city). When this parameter is set to true, the output features will be defined in the subGeographyLayer. The output geometries will be in the spatial reference system defined by outSR. subGeographyLayer - Use this optional parameter to return all the subgeographic areas that are within a parent geography. For example, you could return all the U.S. counties within a given U.S. state or you could return all the Canadian postal areas (FSAs) within a Census Metropolitan Areas (city). When this parameter is set to true, the output features will be defined in the subGeographyLayer. The output geometries will be in the spatial reference system defined by outSR. subGeographyQuery - Optional parameter to filter the results of the subgeography features that are returned by a search term. You can use this parameter to query and find subgeography features that meet an input term. This parameter is used to filter the list of subgeography features that are within a parent geography. For example, you may want a list of all the ZIP Codes that are within "San Diego County" and filter the results so that only ZIP Codes that start with "921" are included in the output response. The subgeography query is a string that contains one or more words. outSR - Optional parameter to request the output geometries in a specified spatial reference system. returnGeometry - Optional parameter to request the output geometries in the response. returnCentroids - Optional Boolean parameter to request the output geometry to return the center point for each feature. Use this parameter to return all the geometries as points. For example, you could return all U.S. ZIP Code centroids (points) rather than providing the boundaries. generalizationLevel - Optional integer that specifies the level of generalization or detail in the area representations of the administrative boundary or standard geographic data layers. Values must be whole integers from 0 through 6, where 0 is most detailed and 6 is most generalized. useFuzzySearch - Optional Boolean parameter to define if text provided in the geographyQuery parameter should utilize fuzzy search logic. Fuzzy searches are based on the Levenshtein Distance or Edit Distance algorithm. featureLimit - Optional integer value where you can limit the number of features that are returned from the geographyQuery. """ url = self._base_url + self._url_standard_geography_query_execute params = { "f" : "json" } if not sourceCountry is None: params['sourceCountry'] = sourceCountry if not optionalCountryDataset is None: params['optionalCountryDataset'] = optionalCountryDataset if not geographyLayers is None: params['geographylayers'] = geographyLayers if not geographyIDs is None: params['geographyids'] = json.dumps(geographyIDs) if not geographyQuery is None: params['geographyQuery'] = geographyQuery if not returnSubGeographyLayer is None and \ isinstance(returnSubGeographyLayer, bool): params['returnSubGeographyLayer'] = returnSubGeographyLayer if not subGeographyLayer is None: params['subGeographyLayer'] = json.dumps(subGeographyLayer) if not subGeographyQuery is None: params['subGeographyQuery'] = subGeographyQuery if not outSR is None and \ isinstance(outSR, int): params['outSR'] = outSR if not returnGeometry is None and \ isinstance(returnGeometry, bool): params['returnGeometry'] = returnGeometry if not returnCentroids is None and \ isinstance(returnCentroids, bool): params['returnCentroids'] = returnCentroids if not generalizationLevel is None and \ isinstance(generalizationLevel, int): params['generalizationLevel'] = generalizationLevel if not useFuzzySearch is None and \ isinstance(useFuzzySearch, bool): params['useFuzzySearch'] = json.dumps(useFuzzySearch) if featureLimit is None: featureLimit = 1000 elif isinstance(featureLimit, int): params['featureLimit'] = featureLimit else: params['featureLimit'] = 1000 return self._post(url=url, param_dict=params, securityHandler=self._securityHandler, proxy_url=self._proxy_url, proxy_port=self._proxy_port)
def find_complement(am, sites=None, bonds=None, asmask=False): r""" Finds the complementary sites (or bonds) to a given set of inputs Parameters ---------- am : scipy.sparse matrix The adjacency matrix of the network. sites : array_like (optional) The set of sites for which the complement is sought bonds : array_like (optional) The set of bonds for which the complement is sought asmask : boolean If set to ``True`` the result is returned as a boolean mask of the correct length with ``True`` values indicate the complements. The default is ``False`` which returns a list of indices instead. Returns ------- An array containing indices of the sites (or bonds) that are not part of the input list. Notes ----- Either ``sites`` or ``bonds`` must be specified """ if (sites is not None) and (bonds is None): inds = sp.unique(sites) N = am.shape[0] elif (bonds is not None) and (sites is None): inds = sp.unique(bonds) N = int(am.nnz/2) elif (bonds is not None) and (sites is not None): raise Exception('Only one of sites or bonds can be specified') else: raise Exception('Either sites or bonds must be specified') mask = sp.ones(shape=N, dtype=bool) mask[inds] = False if asmask: return mask else: return sp.arange(N)[mask]
r""" Finds the complementary sites (or bonds) to a given set of inputs Parameters ---------- am : scipy.sparse matrix The adjacency matrix of the network. sites : array_like (optional) The set of sites for which the complement is sought bonds : array_like (optional) The set of bonds for which the complement is sought asmask : boolean If set to ``True`` the result is returned as a boolean mask of the correct length with ``True`` values indicate the complements. The default is ``False`` which returns a list of indices instead. Returns ------- An array containing indices of the sites (or bonds) that are not part of the input list. Notes ----- Either ``sites`` or ``bonds`` must be specified
Below is the the instruction that describes the task: ### Input: r""" Finds the complementary sites (or bonds) to a given set of inputs Parameters ---------- am : scipy.sparse matrix The adjacency matrix of the network. sites : array_like (optional) The set of sites for which the complement is sought bonds : array_like (optional) The set of bonds for which the complement is sought asmask : boolean If set to ``True`` the result is returned as a boolean mask of the correct length with ``True`` values indicate the complements. The default is ``False`` which returns a list of indices instead. Returns ------- An array containing indices of the sites (or bonds) that are not part of the input list. Notes ----- Either ``sites`` or ``bonds`` must be specified ### Response: def find_complement(am, sites=None, bonds=None, asmask=False): r""" Finds the complementary sites (or bonds) to a given set of inputs Parameters ---------- am : scipy.sparse matrix The adjacency matrix of the network. sites : array_like (optional) The set of sites for which the complement is sought bonds : array_like (optional) The set of bonds for which the complement is sought asmask : boolean If set to ``True`` the result is returned as a boolean mask of the correct length with ``True`` values indicate the complements. The default is ``False`` which returns a list of indices instead. Returns ------- An array containing indices of the sites (or bonds) that are not part of the input list. Notes ----- Either ``sites`` or ``bonds`` must be specified """ if (sites is not None) and (bonds is None): inds = sp.unique(sites) N = am.shape[0] elif (bonds is not None) and (sites is None): inds = sp.unique(bonds) N = int(am.nnz/2) elif (bonds is not None) and (sites is not None): raise Exception('Only one of sites or bonds can be specified') else: raise Exception('Either sites or bonds must be specified') mask = sp.ones(shape=N, dtype=bool) mask[inds] = False if asmask: return mask else: return sp.arange(N)[mask]
def setBaseLocale(self, locale): """ Sets the base locale that is used with in this widget. All displayed information will be translated to this locale. :param locale | <str> """ locale = str(locale) if self._baseLocale == locale: return try: babel.Locale.parse(locale) except (babel.UnknownLocaleError, StandardError): return False self._baseLocale = locale self.setCurrentLocale(locale) self.setDirty() return True
Sets the base locale that is used with in this widget. All displayed information will be translated to this locale. :param locale | <str>
Below is the the instruction that describes the task: ### Input: Sets the base locale that is used with in this widget. All displayed information will be translated to this locale. :param locale | <str> ### Response: def setBaseLocale(self, locale): """ Sets the base locale that is used with in this widget. All displayed information will be translated to this locale. :param locale | <str> """ locale = str(locale) if self._baseLocale == locale: return try: babel.Locale.parse(locale) except (babel.UnknownLocaleError, StandardError): return False self._baseLocale = locale self.setCurrentLocale(locale) self.setDirty() return True
def standin_for(obj, **attrs): """ Returns an object that can be used as a standin for the original object. The standin object will have extra attrs, which you can define passed as keyword arguments. Use standin like this: >>> a = u'I am E.T.' >>> b = standin_for(a, origin='outerspace', package='easymode.utils.standin') >>> b u'I am E.T.' >>> b == a True >>> b.origin 'outerspace' >>> b.package 'easymode.utils.standin' >>> isinstance(b, unicode) True >>> type(b) <class 'easymode.utils.standin.unicodeStandInWithOriginAndPackageAttributes'> >>> import pickle >>> b_pickle = pickle.dumps(b, pickle.HIGHEST_PROTOCOL) >>> c = pickle.loads(b_pickle) >>> b == c True >>> c u'I am E.T.' >>> c.origin 'outerspace' >>> c.package 'easymode.utils.standin' Some types are not supported by standin_for. This is because these types are often used in statements like:: a = True if a is True: print 'hi' The *is* keyword checks for equal memory adress, and in case of a standin that can never be *True*. Also, since it is impossible to extend :class:`bool` and :class:`~types.NoneType` you can never get:: isinstance(standin, bool) isinstance(standin, NoneType) To work with anything else but the real thing. This is why :class:`bool` and :class:`~types.NoneType` instances are returned unmodified: >>> a = False >>> b = standin_for(a, crazy=True) >>> b False >>> b.crazy Traceback (most recent call last): ... AttributeError: 'bool' object has no attribute 'crazy' :param obj: An instance of some class :param **attrs: Attributes that will be added to the standin for *obj* :rtype: A new object that can be used where the original was used. However it has extra attributes. """ obj_class = obj.__class__ if obj_class is bool or obj_class is NoneType: # we can not have a standing for bool or NoneType # because too many code uses a is True or a is None. # Also you can never get isinstance(standin, bool) and # isinstance(standin, NoneType) to work because you can # never extend these types. return obj attr_names = attrs.keys() attr_names.sort() # Contruct __reduce__ method, so the resulting class can be pickled attrs_org = attrs.copy() # Create a copy to be used for the recude method def __reduce__(self, ignore=None): return (_standin_with_dict_for, (obj, attrs_org)) attrs['__reduce__'] = __reduce__ attrs['__reduce_ex__']= __reduce__ # create a readable class name eg. unicodeStandinWithTitleAndDescriptionAttributes additions = 'And'.join(map(capfirst, attr_names)) id = "%sStandInWith%sAttributes" % (obj_class.__name__, additions.encode('ascii', 'ignore')) # if we allready know this type don't create it again. cached_type = _defined_standins.get(id, None) if not cached_type: cls_attrs = dict([(attr_name, None) for attr_name in attr_names]) cached_type = type(id, (obj_class, object), cls_attrs) _defined_standins[id] = cached_type # create new object based on original and copy all properties try: stand_in = cached_type(obj) except (AttributeError, TypeError): try: stand_in = cached_type() stand_in.__dict__.update(obj.__dict__) except (AttributeError, TypeError): stand_in = obj # add extra attrs try: for (key, value) in attrs.iteritems(): setattr(stand_in, key, value) except AttributeError: # if nothing works return original object return obj return stand_in
Returns an object that can be used as a standin for the original object. The standin object will have extra attrs, which you can define passed as keyword arguments. Use standin like this: >>> a = u'I am E.T.' >>> b = standin_for(a, origin='outerspace', package='easymode.utils.standin') >>> b u'I am E.T.' >>> b == a True >>> b.origin 'outerspace' >>> b.package 'easymode.utils.standin' >>> isinstance(b, unicode) True >>> type(b) <class 'easymode.utils.standin.unicodeStandInWithOriginAndPackageAttributes'> >>> import pickle >>> b_pickle = pickle.dumps(b, pickle.HIGHEST_PROTOCOL) >>> c = pickle.loads(b_pickle) >>> b == c True >>> c u'I am E.T.' >>> c.origin 'outerspace' >>> c.package 'easymode.utils.standin' Some types are not supported by standin_for. This is because these types are often used in statements like:: a = True if a is True: print 'hi' The *is* keyword checks for equal memory adress, and in case of a standin that can never be *True*. Also, since it is impossible to extend :class:`bool` and :class:`~types.NoneType` you can never get:: isinstance(standin, bool) isinstance(standin, NoneType) To work with anything else but the real thing. This is why :class:`bool` and :class:`~types.NoneType` instances are returned unmodified: >>> a = False >>> b = standin_for(a, crazy=True) >>> b False >>> b.crazy Traceback (most recent call last): ... AttributeError: 'bool' object has no attribute 'crazy' :param obj: An instance of some class :param **attrs: Attributes that will be added to the standin for *obj* :rtype: A new object that can be used where the original was used. However it has extra attributes.
Below is the the instruction that describes the task: ### Input: Returns an object that can be used as a standin for the original object. The standin object will have extra attrs, which you can define passed as keyword arguments. Use standin like this: >>> a = u'I am E.T.' >>> b = standin_for(a, origin='outerspace', package='easymode.utils.standin') >>> b u'I am E.T.' >>> b == a True >>> b.origin 'outerspace' >>> b.package 'easymode.utils.standin' >>> isinstance(b, unicode) True >>> type(b) <class 'easymode.utils.standin.unicodeStandInWithOriginAndPackageAttributes'> >>> import pickle >>> b_pickle = pickle.dumps(b, pickle.HIGHEST_PROTOCOL) >>> c = pickle.loads(b_pickle) >>> b == c True >>> c u'I am E.T.' >>> c.origin 'outerspace' >>> c.package 'easymode.utils.standin' Some types are not supported by standin_for. This is because these types are often used in statements like:: a = True if a is True: print 'hi' The *is* keyword checks for equal memory adress, and in case of a standin that can never be *True*. Also, since it is impossible to extend :class:`bool` and :class:`~types.NoneType` you can never get:: isinstance(standin, bool) isinstance(standin, NoneType) To work with anything else but the real thing. This is why :class:`bool` and :class:`~types.NoneType` instances are returned unmodified: >>> a = False >>> b = standin_for(a, crazy=True) >>> b False >>> b.crazy Traceback (most recent call last): ... AttributeError: 'bool' object has no attribute 'crazy' :param obj: An instance of some class :param **attrs: Attributes that will be added to the standin for *obj* :rtype: A new object that can be used where the original was used. However it has extra attributes. ### Response: def standin_for(obj, **attrs): """ Returns an object that can be used as a standin for the original object. The standin object will have extra attrs, which you can define passed as keyword arguments. Use standin like this: >>> a = u'I am E.T.' >>> b = standin_for(a, origin='outerspace', package='easymode.utils.standin') >>> b u'I am E.T.' >>> b == a True >>> b.origin 'outerspace' >>> b.package 'easymode.utils.standin' >>> isinstance(b, unicode) True >>> type(b) <class 'easymode.utils.standin.unicodeStandInWithOriginAndPackageAttributes'> >>> import pickle >>> b_pickle = pickle.dumps(b, pickle.HIGHEST_PROTOCOL) >>> c = pickle.loads(b_pickle) >>> b == c True >>> c u'I am E.T.' >>> c.origin 'outerspace' >>> c.package 'easymode.utils.standin' Some types are not supported by standin_for. This is because these types are often used in statements like:: a = True if a is True: print 'hi' The *is* keyword checks for equal memory adress, and in case of a standin that can never be *True*. Also, since it is impossible to extend :class:`bool` and :class:`~types.NoneType` you can never get:: isinstance(standin, bool) isinstance(standin, NoneType) To work with anything else but the real thing. This is why :class:`bool` and :class:`~types.NoneType` instances are returned unmodified: >>> a = False >>> b = standin_for(a, crazy=True) >>> b False >>> b.crazy Traceback (most recent call last): ... AttributeError: 'bool' object has no attribute 'crazy' :param obj: An instance of some class :param **attrs: Attributes that will be added to the standin for *obj* :rtype: A new object that can be used where the original was used. However it has extra attributes. """ obj_class = obj.__class__ if obj_class is bool or obj_class is NoneType: # we can not have a standing for bool or NoneType # because too many code uses a is True or a is None. # Also you can never get isinstance(standin, bool) and # isinstance(standin, NoneType) to work because you can # never extend these types. return obj attr_names = attrs.keys() attr_names.sort() # Contruct __reduce__ method, so the resulting class can be pickled attrs_org = attrs.copy() # Create a copy to be used for the recude method def __reduce__(self, ignore=None): return (_standin_with_dict_for, (obj, attrs_org)) attrs['__reduce__'] = __reduce__ attrs['__reduce_ex__']= __reduce__ # create a readable class name eg. unicodeStandinWithTitleAndDescriptionAttributes additions = 'And'.join(map(capfirst, attr_names)) id = "%sStandInWith%sAttributes" % (obj_class.__name__, additions.encode('ascii', 'ignore')) # if we allready know this type don't create it again. cached_type = _defined_standins.get(id, None) if not cached_type: cls_attrs = dict([(attr_name, None) for attr_name in attr_names]) cached_type = type(id, (obj_class, object), cls_attrs) _defined_standins[id] = cached_type # create new object based on original and copy all properties try: stand_in = cached_type(obj) except (AttributeError, TypeError): try: stand_in = cached_type() stand_in.__dict__.update(obj.__dict__) except (AttributeError, TypeError): stand_in = obj # add extra attrs try: for (key, value) in attrs.iteritems(): setattr(stand_in, key, value) except AttributeError: # if nothing works return original object return obj return stand_in
def parents(self): """~TermList: the parents of all the terms in the list. """ return TermList(unique_everseen( y for x in self for y in x.parents ))
~TermList: the parents of all the terms in the list.
Below is the the instruction that describes the task: ### Input: ~TermList: the parents of all the terms in the list. ### Response: def parents(self): """~TermList: the parents of all the terms in the list. """ return TermList(unique_everseen( y for x in self for y in x.parents ))
def to_dict(self): """Transform to dictionary Returns: dict: dictionary with same content """ return {sect: self.__getitem__(sect).to_dict() for sect in self.sections()}
Transform to dictionary Returns: dict: dictionary with same content
Below is the the instruction that describes the task: ### Input: Transform to dictionary Returns: dict: dictionary with same content ### Response: def to_dict(self): """Transform to dictionary Returns: dict: dictionary with same content """ return {sect: self.__getitem__(sect).to_dict() for sect in self.sections()}
def beam_fit(psf, cdelt1, cdelt2): """ The following contructs a restoring beam from the psf. This is accoplished by fitting an elliptical Gaussian to the central lobe of the PSF. INPUTS: psf (no default): Array containing the psf for the image in question. cdelt1, cdelt2 (no default): Header of the psf. """ if psf.shape>512: psf_slice = tuple([slice(psf.shape[0]/2-256, psf.shape[0]/2+256),slice(psf.shape[1]/2-256, psf.shape[1]/2+256)]) else: psf_slice = tuple([slice(0, psf.shape[0]),slice(0, psf.shape[1])]) psf_centre = psf[psf_slice]/np.max(psf[psf_slice]) max_location = np.unravel_index(np.argmax(psf_centre), psf_centre.shape) threshold_psf = np.where(psf_centre>0.5 , psf_centre, 0) labelled_psf, labels = ndimage.label(threshold_psf) extracted_primary_beam = np.where(labelled_psf==labelled_psf[max_location], psf_centre, 0) # Following creates row and column values of interest for the central PSF lobe and then selects those values # from the PSF using np.where. Additionally, the inputs for the fitting are created by reshaping the x,y, # and z data into columns. x = np.arange(-max_location[1],-max_location[1]+psf_centre.shape[1],1) y = np.arange(-max_location[0],-max_location[0]+psf_centre.shape[0],1) z = extracted_primary_beam gridx, gridy = np.meshgrid(x,-y) xyz = np.column_stack((gridx.reshape(-1,1),gridy.reshape(-1,1),z.reshape(-1,1,order="C"))) # Elliptical gaussian which can be fit to the central lobe of the PSF. xy must be an Nx2 array consisting of # pairs of row and column values for the region of interest. def ellipgauss(xy,A,xsigma,ysigma,theta): return A*np.exp(-1*(((xy[:,0]*np.cos(theta)-xy[:,1]*np.sin(theta))**2)/(2*(xsigma**2)) + ((xy[:,0]*np.sin(theta)+xy[:,1]*np.cos(theta))**2)/(2*(ysigma**2)))) # This command from scipy performs the fitting of the 2D gaussian, and returns the optimal coefficients in opt. opt = curve_fit(ellipgauss, xyz[:,0:2],xyz[:,2],(1,1,1,0))[0] # Following create the data for the new images. The cleanbeam has to be reshaped to reclaim it in 2D. clean_beam = np.zeros_like(psf) clean_beam[psf_slice] = ellipgauss(xyz[:,0:2],opt[0],opt[1],opt[2],opt[3]).reshape(psf_centre.shape,order="C") # Experimental - forces the beam to be normalised. This should be redundant, but helps when the PSF is bad. clean_beam = clean_beam/np.max(clean_beam) bmaj = 2*np.sqrt(2*np.log(2))*max(opt[1],opt[2])*cdelt1 bmin = 2*np.sqrt(2*np.log(2))*min(opt[1],opt[2])*cdelt2 bpa = np.degrees(opt[3])%360 - 90 beam_params = [abs(bmaj), abs(bmin), bpa] return clean_beam, beam_params
The following contructs a restoring beam from the psf. This is accoplished by fitting an elliptical Gaussian to the central lobe of the PSF. INPUTS: psf (no default): Array containing the psf for the image in question. cdelt1, cdelt2 (no default): Header of the psf.
Below is the the instruction that describes the task: ### Input: The following contructs a restoring beam from the psf. This is accoplished by fitting an elliptical Gaussian to the central lobe of the PSF. INPUTS: psf (no default): Array containing the psf for the image in question. cdelt1, cdelt2 (no default): Header of the psf. ### Response: def beam_fit(psf, cdelt1, cdelt2): """ The following contructs a restoring beam from the psf. This is accoplished by fitting an elliptical Gaussian to the central lobe of the PSF. INPUTS: psf (no default): Array containing the psf for the image in question. cdelt1, cdelt2 (no default): Header of the psf. """ if psf.shape>512: psf_slice = tuple([slice(psf.shape[0]/2-256, psf.shape[0]/2+256),slice(psf.shape[1]/2-256, psf.shape[1]/2+256)]) else: psf_slice = tuple([slice(0, psf.shape[0]),slice(0, psf.shape[1])]) psf_centre = psf[psf_slice]/np.max(psf[psf_slice]) max_location = np.unravel_index(np.argmax(psf_centre), psf_centre.shape) threshold_psf = np.where(psf_centre>0.5 , psf_centre, 0) labelled_psf, labels = ndimage.label(threshold_psf) extracted_primary_beam = np.where(labelled_psf==labelled_psf[max_location], psf_centre, 0) # Following creates row and column values of interest for the central PSF lobe and then selects those values # from the PSF using np.where. Additionally, the inputs for the fitting are created by reshaping the x,y, # and z data into columns. x = np.arange(-max_location[1],-max_location[1]+psf_centre.shape[1],1) y = np.arange(-max_location[0],-max_location[0]+psf_centre.shape[0],1) z = extracted_primary_beam gridx, gridy = np.meshgrid(x,-y) xyz = np.column_stack((gridx.reshape(-1,1),gridy.reshape(-1,1),z.reshape(-1,1,order="C"))) # Elliptical gaussian which can be fit to the central lobe of the PSF. xy must be an Nx2 array consisting of # pairs of row and column values for the region of interest. def ellipgauss(xy,A,xsigma,ysigma,theta): return A*np.exp(-1*(((xy[:,0]*np.cos(theta)-xy[:,1]*np.sin(theta))**2)/(2*(xsigma**2)) + ((xy[:,0]*np.sin(theta)+xy[:,1]*np.cos(theta))**2)/(2*(ysigma**2)))) # This command from scipy performs the fitting of the 2D gaussian, and returns the optimal coefficients in opt. opt = curve_fit(ellipgauss, xyz[:,0:2],xyz[:,2],(1,1,1,0))[0] # Following create the data for the new images. The cleanbeam has to be reshaped to reclaim it in 2D. clean_beam = np.zeros_like(psf) clean_beam[psf_slice] = ellipgauss(xyz[:,0:2],opt[0],opt[1],opt[2],opt[3]).reshape(psf_centre.shape,order="C") # Experimental - forces the beam to be normalised. This should be redundant, but helps when the PSF is bad. clean_beam = clean_beam/np.max(clean_beam) bmaj = 2*np.sqrt(2*np.log(2))*max(opt[1],opt[2])*cdelt1 bmin = 2*np.sqrt(2*np.log(2))*min(opt[1],opt[2])*cdelt2 bpa = np.degrees(opt[3])%360 - 90 beam_params = [abs(bmaj), abs(bmin), bpa] return clean_beam, beam_params
def update_standings(semester=None, pool_hours=None, moment=None): """ This function acts to update a list of PoolHours objects to adjust their current standing based on the time in the semester. Parameters ---------- semester : workshift.models.Semester, optional pool_hours : list of workshift.models.PoolHours, optional If None, runs on all pool hours for semester. moment : datetime, optional """ if semester is None: try: semester = Semester.objects.get(current=True) except (Semester.DoesNotExist, Semester.MultipleObjectsReturned): return [] if moment is None: moment = localtime(now()) if pool_hours is None: pool_hours = PoolHours.objects.filter(pool__semester=semester) for hours in pool_hours: # Don't update hours after the semester ends if hours.last_updated and \ hours.last_updated.date() > semester.end_date: continue # Calculate the number of periods (n weeks / once per semester) that # have passed since last update periods = hours.periods_since_last_update(moment=moment) # Update the actual standings if periods > 0: hours.standing -= hours.hours * periods hours.last_updated = moment hours.save(update_fields=["standing", "last_updated"])
This function acts to update a list of PoolHours objects to adjust their current standing based on the time in the semester. Parameters ---------- semester : workshift.models.Semester, optional pool_hours : list of workshift.models.PoolHours, optional If None, runs on all pool hours for semester. moment : datetime, optional
Below is the the instruction that describes the task: ### Input: This function acts to update a list of PoolHours objects to adjust their current standing based on the time in the semester. Parameters ---------- semester : workshift.models.Semester, optional pool_hours : list of workshift.models.PoolHours, optional If None, runs on all pool hours for semester. moment : datetime, optional ### Response: def update_standings(semester=None, pool_hours=None, moment=None): """ This function acts to update a list of PoolHours objects to adjust their current standing based on the time in the semester. Parameters ---------- semester : workshift.models.Semester, optional pool_hours : list of workshift.models.PoolHours, optional If None, runs on all pool hours for semester. moment : datetime, optional """ if semester is None: try: semester = Semester.objects.get(current=True) except (Semester.DoesNotExist, Semester.MultipleObjectsReturned): return [] if moment is None: moment = localtime(now()) if pool_hours is None: pool_hours = PoolHours.objects.filter(pool__semester=semester) for hours in pool_hours: # Don't update hours after the semester ends if hours.last_updated and \ hours.last_updated.date() > semester.end_date: continue # Calculate the number of periods (n weeks / once per semester) that # have passed since last update periods = hours.periods_since_last_update(moment=moment) # Update the actual standings if periods > 0: hours.standing -= hours.hours * periods hours.last_updated = moment hours.save(update_fields=["standing", "last_updated"])
def _sample_names(files, kwargs): """ Make sample (or other) names. Parameters: ----------- files : list of string Typically a list of file paths although could be any list of strings that you want to make names for. If neither names nor define_sample_name are provided, then files is returned as is. kwargs : dict kwargs from another function. Can include the following keys with appropriate arguments. names : list of strings Names to use. Overrides define_sample_name if provided. define_sample_name : function that takes string as input Function mapping string to name. For instance, you may have a sample name in a file path and use a regex to extract it. """ if 'define_sample_name' not in kwargs.keys(): define_sample_name = lambda x: x else: define_sample_name = kwargs['define_sample_name'] if 'names' in kwargs.keys(): names = kwargs['names'] else: names = [define_sample_name(f) for f in files] assert len(names) == len(files) return names
Make sample (or other) names. Parameters: ----------- files : list of string Typically a list of file paths although could be any list of strings that you want to make names for. If neither names nor define_sample_name are provided, then files is returned as is. kwargs : dict kwargs from another function. Can include the following keys with appropriate arguments. names : list of strings Names to use. Overrides define_sample_name if provided. define_sample_name : function that takes string as input Function mapping string to name. For instance, you may have a sample name in a file path and use a regex to extract it.
Below is the the instruction that describes the task: ### Input: Make sample (or other) names. Parameters: ----------- files : list of string Typically a list of file paths although could be any list of strings that you want to make names for. If neither names nor define_sample_name are provided, then files is returned as is. kwargs : dict kwargs from another function. Can include the following keys with appropriate arguments. names : list of strings Names to use. Overrides define_sample_name if provided. define_sample_name : function that takes string as input Function mapping string to name. For instance, you may have a sample name in a file path and use a regex to extract it. ### Response: def _sample_names(files, kwargs): """ Make sample (or other) names. Parameters: ----------- files : list of string Typically a list of file paths although could be any list of strings that you want to make names for. If neither names nor define_sample_name are provided, then files is returned as is. kwargs : dict kwargs from another function. Can include the following keys with appropriate arguments. names : list of strings Names to use. Overrides define_sample_name if provided. define_sample_name : function that takes string as input Function mapping string to name. For instance, you may have a sample name in a file path and use a regex to extract it. """ if 'define_sample_name' not in kwargs.keys(): define_sample_name = lambda x: x else: define_sample_name = kwargs['define_sample_name'] if 'names' in kwargs.keys(): names = kwargs['names'] else: names = [define_sample_name(f) for f in files] assert len(names) == len(files) return names
def qos_map_cos_traffic_class_name(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") qos = ET.SubElement(config, "qos", xmlns="urn:brocade.com:mgmt:brocade-qos") map = ET.SubElement(qos, "map") cos_traffic_class = ET.SubElement(map, "cos-traffic-class") name = ET.SubElement(cos_traffic_class, "name") name.text = kwargs.pop('name') callback = kwargs.pop('callback', self._callback) return callback(config)
Auto Generated Code
Below is the the instruction that describes the task: ### Input: Auto Generated Code ### Response: def qos_map_cos_traffic_class_name(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") qos = ET.SubElement(config, "qos", xmlns="urn:brocade.com:mgmt:brocade-qos") map = ET.SubElement(qos, "map") cos_traffic_class = ET.SubElement(map, "cos-traffic-class") name = ET.SubElement(cos_traffic_class, "name") name.text = kwargs.pop('name') callback = kwargs.pop('callback', self._callback) return callback(config)
def min_conflicts(csp, max_steps=100000): """Solve a CSP by stochastic hillclimbing on the number of conflicts.""" # Generate a complete assignment for all vars (probably with conflicts) csp.current = current = {} for var in csp.vars: val = min_conflicts_value(csp, var, current) csp.assign(var, val, current) # Now repeatedly choose a random conflicted variable and change it for i in range(max_steps): conflicted = csp.conflicted_vars(current) if not conflicted: return current var = random.choice(conflicted) val = min_conflicts_value(csp, var, current) csp.assign(var, val, current) return None
Solve a CSP by stochastic hillclimbing on the number of conflicts.
Below is the the instruction that describes the task: ### Input: Solve a CSP by stochastic hillclimbing on the number of conflicts. ### Response: def min_conflicts(csp, max_steps=100000): """Solve a CSP by stochastic hillclimbing on the number of conflicts.""" # Generate a complete assignment for all vars (probably with conflicts) csp.current = current = {} for var in csp.vars: val = min_conflicts_value(csp, var, current) csp.assign(var, val, current) # Now repeatedly choose a random conflicted variable and change it for i in range(max_steps): conflicted = csp.conflicted_vars(current) if not conflicted: return current var = random.choice(conflicted) val = min_conflicts_value(csp, var, current) csp.assign(var, val, current) return None
def maskrcnn_loss(mask_logits, fg_labels, fg_target_masks): """ Args: mask_logits: #fg x #category xhxw fg_labels: #fg, in 1~#class, int64 fg_target_masks: #fgxhxw, float32 """ num_fg = tf.size(fg_labels, out_type=tf.int64) indices = tf.stack([tf.range(num_fg), fg_labels - 1], axis=1) # #fgx2 mask_logits = tf.gather_nd(mask_logits, indices) # #fgxhxw mask_probs = tf.sigmoid(mask_logits) # add some training visualizations to tensorboard with tf.name_scope('mask_viz'): viz = tf.concat([fg_target_masks, mask_probs], axis=1) viz = tf.expand_dims(viz, 3) viz = tf.cast(viz * 255, tf.uint8, name='viz') tf.summary.image('mask_truth|pred', viz, max_outputs=10) loss = tf.nn.sigmoid_cross_entropy_with_logits( labels=fg_target_masks, logits=mask_logits) loss = tf.reduce_mean(loss, name='maskrcnn_loss') pred_label = mask_probs > 0.5 truth_label = fg_target_masks > 0.5 accuracy = tf.reduce_mean( tf.cast(tf.equal(pred_label, truth_label), tf.float32), name='accuracy') pos_accuracy = tf.logical_and( tf.equal(pred_label, truth_label), tf.equal(truth_label, True)) pos_accuracy = tf.reduce_mean(tf.cast(pos_accuracy, tf.float32), name='pos_accuracy') fg_pixel_ratio = tf.reduce_mean(tf.cast(truth_label, tf.float32), name='fg_pixel_ratio') add_moving_summary(loss, accuracy, fg_pixel_ratio, pos_accuracy) return loss
Args: mask_logits: #fg x #category xhxw fg_labels: #fg, in 1~#class, int64 fg_target_masks: #fgxhxw, float32
Below is the the instruction that describes the task: ### Input: Args: mask_logits: #fg x #category xhxw fg_labels: #fg, in 1~#class, int64 fg_target_masks: #fgxhxw, float32 ### Response: def maskrcnn_loss(mask_logits, fg_labels, fg_target_masks): """ Args: mask_logits: #fg x #category xhxw fg_labels: #fg, in 1~#class, int64 fg_target_masks: #fgxhxw, float32 """ num_fg = tf.size(fg_labels, out_type=tf.int64) indices = tf.stack([tf.range(num_fg), fg_labels - 1], axis=1) # #fgx2 mask_logits = tf.gather_nd(mask_logits, indices) # #fgxhxw mask_probs = tf.sigmoid(mask_logits) # add some training visualizations to tensorboard with tf.name_scope('mask_viz'): viz = tf.concat([fg_target_masks, mask_probs], axis=1) viz = tf.expand_dims(viz, 3) viz = tf.cast(viz * 255, tf.uint8, name='viz') tf.summary.image('mask_truth|pred', viz, max_outputs=10) loss = tf.nn.sigmoid_cross_entropy_with_logits( labels=fg_target_masks, logits=mask_logits) loss = tf.reduce_mean(loss, name='maskrcnn_loss') pred_label = mask_probs > 0.5 truth_label = fg_target_masks > 0.5 accuracy = tf.reduce_mean( tf.cast(tf.equal(pred_label, truth_label), tf.float32), name='accuracy') pos_accuracy = tf.logical_and( tf.equal(pred_label, truth_label), tf.equal(truth_label, True)) pos_accuracy = tf.reduce_mean(tf.cast(pos_accuracy, tf.float32), name='pos_accuracy') fg_pixel_ratio = tf.reduce_mean(tf.cast(truth_label, tf.float32), name='fg_pixel_ratio') add_moving_summary(loss, accuracy, fg_pixel_ratio, pos_accuracy) return loss
def get_subgraphs(graph=None): """ Given a graph of possibly disconnected components, generate all graphs of connected components. graph is a dictionary of dependencies. Keys are components, and values are sets of components on which they depend. """ graph = graph or DEPENDENCIES keys = set(graph) frontier = set() seen = set() while keys: frontier.add(keys.pop()) while frontier: component = frontier.pop() seen.add(component) frontier |= set([d for d in get_dependencies(component) if d in graph]) frontier |= set([d for d in get_dependents(component) if d in graph]) frontier -= seen yield dict((s, get_dependencies(s)) for s in seen) keys -= seen seen.clear()
Given a graph of possibly disconnected components, generate all graphs of connected components. graph is a dictionary of dependencies. Keys are components, and values are sets of components on which they depend.
Below is the the instruction that describes the task: ### Input: Given a graph of possibly disconnected components, generate all graphs of connected components. graph is a dictionary of dependencies. Keys are components, and values are sets of components on which they depend. ### Response: def get_subgraphs(graph=None): """ Given a graph of possibly disconnected components, generate all graphs of connected components. graph is a dictionary of dependencies. Keys are components, and values are sets of components on which they depend. """ graph = graph or DEPENDENCIES keys = set(graph) frontier = set() seen = set() while keys: frontier.add(keys.pop()) while frontier: component = frontier.pop() seen.add(component) frontier |= set([d for d in get_dependencies(component) if d in graph]) frontier |= set([d for d in get_dependents(component) if d in graph]) frontier -= seen yield dict((s, get_dependencies(s)) for s in seen) keys -= seen seen.clear()
def _readable(self, watcher, events): """Called by the pyev watcher (self.read_watcher) whenever the socket is readable. This means either the socket has been closed or there is a new client connection waiting. """ protocol = self.factory.build(self.loop) try: sock, address = self.sock.accept() connection = Connection(self.loop, sock, address, protocol, self) self.connections.add(connection) connection.make_connection() logger.debug("added connection") except IOError as e: self.shutdown(e)
Called by the pyev watcher (self.read_watcher) whenever the socket is readable. This means either the socket has been closed or there is a new client connection waiting.
Below is the the instruction that describes the task: ### Input: Called by the pyev watcher (self.read_watcher) whenever the socket is readable. This means either the socket has been closed or there is a new client connection waiting. ### Response: def _readable(self, watcher, events): """Called by the pyev watcher (self.read_watcher) whenever the socket is readable. This means either the socket has been closed or there is a new client connection waiting. """ protocol = self.factory.build(self.loop) try: sock, address = self.sock.accept() connection = Connection(self.loop, sock, address, protocol, self) self.connections.add(connection) connection.make_connection() logger.debug("added connection") except IOError as e: self.shutdown(e)
def integratedAutocorrelationTimeMultiple(A_kn, fast=False): """Estimate the integrated autocorrelation time from multiple timeseries. See Also -------- statisticalInefficiencyMultiple """ g = statisticalInefficiencyMultiple(A_kn, fast, False) tau = (g - 1.0) / 2.0 return tau
Estimate the integrated autocorrelation time from multiple timeseries. See Also -------- statisticalInefficiencyMultiple
Below is the the instruction that describes the task: ### Input: Estimate the integrated autocorrelation time from multiple timeseries. See Also -------- statisticalInefficiencyMultiple ### Response: def integratedAutocorrelationTimeMultiple(A_kn, fast=False): """Estimate the integrated autocorrelation time from multiple timeseries. See Also -------- statisticalInefficiencyMultiple """ g = statisticalInefficiencyMultiple(A_kn, fast, False) tau = (g - 1.0) / 2.0 return tau
def install_strategy_plugins(directories): """ Loads the given strategy plugins, which is a list of directories, a string with a single directory or a string with multiple directories separated by colon. As these plugins are globally loaded and cached by Ansible we do the same here. We could try to bind those plugins to the Api instance, but that's probably not something we'd ever have much of a use for. Call this function before using custom strategies on the :class:`Api` class. """ if isinstance(directories, str): directories = directories.split(':') for directory in directories: strategy_loader.add_directory(directory)
Loads the given strategy plugins, which is a list of directories, a string with a single directory or a string with multiple directories separated by colon. As these plugins are globally loaded and cached by Ansible we do the same here. We could try to bind those plugins to the Api instance, but that's probably not something we'd ever have much of a use for. Call this function before using custom strategies on the :class:`Api` class.
Below is the the instruction that describes the task: ### Input: Loads the given strategy plugins, which is a list of directories, a string with a single directory or a string with multiple directories separated by colon. As these plugins are globally loaded and cached by Ansible we do the same here. We could try to bind those plugins to the Api instance, but that's probably not something we'd ever have much of a use for. Call this function before using custom strategies on the :class:`Api` class. ### Response: def install_strategy_plugins(directories): """ Loads the given strategy plugins, which is a list of directories, a string with a single directory or a string with multiple directories separated by colon. As these plugins are globally loaded and cached by Ansible we do the same here. We could try to bind those plugins to the Api instance, but that's probably not something we'd ever have much of a use for. Call this function before using custom strategies on the :class:`Api` class. """ if isinstance(directories, str): directories = directories.split(':') for directory in directories: strategy_loader.add_directory(directory)
def get_stem(self, noun, gender, mimation=True): """Return the stem of a noun, given its gender""" stem = '' if mimation and noun[-1:] == 'm': # noun = noun[:-1] pass # Take off ending if gender == 'm': if noun[-2:] in list(self.endings['m']['singular'].values()) + \ list(self.endings['m']['dual'].values()): stem = noun[:-2] elif noun[-1] in list(self.endings['m']['plural'].values()): stem = noun[:-1] else: print("Unknown masculine noun: {}".format(noun)) elif gender == 'f': if noun[-4:] in self.endings['f']['plural']['nominative'] + \ self.endings['f']['plural']['oblique']: stem = noun[:-4] + 't' elif noun[-3:] in list(self.endings['f']['singular'].values()) + \ list(self.endings['f']['dual'].values()): stem = noun[:-3] + 't' elif noun[-2:] in list(self.endings['m']['singular'].values()) + \ list(self.endings['m']['dual'].values()): stem = noun[:-2] else: print("Unknown feminine noun: {}".format(noun)) else: print("Unknown noun: {}".format(noun)) return stem
Return the stem of a noun, given its gender
Below is the the instruction that describes the task: ### Input: Return the stem of a noun, given its gender ### Response: def get_stem(self, noun, gender, mimation=True): """Return the stem of a noun, given its gender""" stem = '' if mimation and noun[-1:] == 'm': # noun = noun[:-1] pass # Take off ending if gender == 'm': if noun[-2:] in list(self.endings['m']['singular'].values()) + \ list(self.endings['m']['dual'].values()): stem = noun[:-2] elif noun[-1] in list(self.endings['m']['plural'].values()): stem = noun[:-1] else: print("Unknown masculine noun: {}".format(noun)) elif gender == 'f': if noun[-4:] in self.endings['f']['plural']['nominative'] + \ self.endings['f']['plural']['oblique']: stem = noun[:-4] + 't' elif noun[-3:] in list(self.endings['f']['singular'].values()) + \ list(self.endings['f']['dual'].values()): stem = noun[:-3] + 't' elif noun[-2:] in list(self.endings['m']['singular'].values()) + \ list(self.endings['m']['dual'].values()): stem = noun[:-2] else: print("Unknown feminine noun: {}".format(noun)) else: print("Unknown noun: {}".format(noun)) return stem
def check_auth(self, request): """ to ensure that nobody can get your data via json simply by knowing the URL. public facing forms should write a custom LookupChannel to implement as you wish. also you could choose to return HttpResponseForbidden("who are you?") instead of raising PermissionDenied (401 response) """ if not request.user.is_authenticated: raise PermissionDenied if not is_admin(request): raise PermissionDenied
to ensure that nobody can get your data via json simply by knowing the URL. public facing forms should write a custom LookupChannel to implement as you wish. also you could choose to return HttpResponseForbidden("who are you?") instead of raising PermissionDenied (401 response)
Below is the the instruction that describes the task: ### Input: to ensure that nobody can get your data via json simply by knowing the URL. public facing forms should write a custom LookupChannel to implement as you wish. also you could choose to return HttpResponseForbidden("who are you?") instead of raising PermissionDenied (401 response) ### Response: def check_auth(self, request): """ to ensure that nobody can get your data via json simply by knowing the URL. public facing forms should write a custom LookupChannel to implement as you wish. also you could choose to return HttpResponseForbidden("who are you?") instead of raising PermissionDenied (401 response) """ if not request.user.is_authenticated: raise PermissionDenied if not is_admin(request): raise PermissionDenied
def decode_mst(energy: numpy.ndarray, length: int, has_labels: bool = True) -> Tuple[numpy.ndarray, numpy.ndarray]: """ Note: Counter to typical intuition, this function decodes the _maximum_ spanning tree. Decode the optimal MST tree with the Chu-Liu-Edmonds algorithm for maximum spanning arborescences on graphs. Parameters ---------- energy : ``numpy.ndarray``, required. A tensor with shape (num_labels, timesteps, timesteps) containing the energy of each edge. If has_labels is ``False``, the tensor should have shape (timesteps, timesteps) instead. length : ``int``, required. The length of this sequence, as the energy may have come from a padded batch. has_labels : ``bool``, optional, (default = True) Whether the graph has labels or not. """ if has_labels and energy.ndim != 3: raise ConfigurationError("The dimension of the energy array is not equal to 3.") elif not has_labels and energy.ndim != 2: raise ConfigurationError("The dimension of the energy array is not equal to 2.") input_shape = energy.shape max_length = input_shape[-1] # Our energy matrix might have been batched - # here we clip it to contain only non padded tokens. if has_labels: energy = energy[:, :length, :length] # get best label for each edge. label_id_matrix = energy.argmax(axis=0) energy = energy.max(axis=0) else: energy = energy[:length, :length] label_id_matrix = None # get original score matrix original_score_matrix = energy # initialize score matrix to original score matrix score_matrix = numpy.array(original_score_matrix, copy=True) old_input = numpy.zeros([length, length], dtype=numpy.int32) old_output = numpy.zeros([length, length], dtype=numpy.int32) current_nodes = [True for _ in range(length)] representatives: List[Set[int]] = [] for node1 in range(length): original_score_matrix[node1, node1] = 0.0 score_matrix[node1, node1] = 0.0 representatives.append({node1}) for node2 in range(node1 + 1, length): old_input[node1, node2] = node1 old_output[node1, node2] = node2 old_input[node2, node1] = node2 old_output[node2, node1] = node1 final_edges: Dict[int, int] = {} # The main algorithm operates inplace. chu_liu_edmonds(length, score_matrix, current_nodes, final_edges, old_input, old_output, representatives) heads = numpy.zeros([max_length], numpy.int32) if has_labels: head_type = numpy.ones([max_length], numpy.int32) else: head_type = None for child, parent in final_edges.items(): heads[child] = parent if has_labels: head_type[child] = label_id_matrix[parent, child] return heads, head_type
Note: Counter to typical intuition, this function decodes the _maximum_ spanning tree. Decode the optimal MST tree with the Chu-Liu-Edmonds algorithm for maximum spanning arborescences on graphs. Parameters ---------- energy : ``numpy.ndarray``, required. A tensor with shape (num_labels, timesteps, timesteps) containing the energy of each edge. If has_labels is ``False``, the tensor should have shape (timesteps, timesteps) instead. length : ``int``, required. The length of this sequence, as the energy may have come from a padded batch. has_labels : ``bool``, optional, (default = True) Whether the graph has labels or not.
Below is the the instruction that describes the task: ### Input: Note: Counter to typical intuition, this function decodes the _maximum_ spanning tree. Decode the optimal MST tree with the Chu-Liu-Edmonds algorithm for maximum spanning arborescences on graphs. Parameters ---------- energy : ``numpy.ndarray``, required. A tensor with shape (num_labels, timesteps, timesteps) containing the energy of each edge. If has_labels is ``False``, the tensor should have shape (timesteps, timesteps) instead. length : ``int``, required. The length of this sequence, as the energy may have come from a padded batch. has_labels : ``bool``, optional, (default = True) Whether the graph has labels or not. ### Response: def decode_mst(energy: numpy.ndarray, length: int, has_labels: bool = True) -> Tuple[numpy.ndarray, numpy.ndarray]: """ Note: Counter to typical intuition, this function decodes the _maximum_ spanning tree. Decode the optimal MST tree with the Chu-Liu-Edmonds algorithm for maximum spanning arborescences on graphs. Parameters ---------- energy : ``numpy.ndarray``, required. A tensor with shape (num_labels, timesteps, timesteps) containing the energy of each edge. If has_labels is ``False``, the tensor should have shape (timesteps, timesteps) instead. length : ``int``, required. The length of this sequence, as the energy may have come from a padded batch. has_labels : ``bool``, optional, (default = True) Whether the graph has labels or not. """ if has_labels and energy.ndim != 3: raise ConfigurationError("The dimension of the energy array is not equal to 3.") elif not has_labels and energy.ndim != 2: raise ConfigurationError("The dimension of the energy array is not equal to 2.") input_shape = energy.shape max_length = input_shape[-1] # Our energy matrix might have been batched - # here we clip it to contain only non padded tokens. if has_labels: energy = energy[:, :length, :length] # get best label for each edge. label_id_matrix = energy.argmax(axis=0) energy = energy.max(axis=0) else: energy = energy[:length, :length] label_id_matrix = None # get original score matrix original_score_matrix = energy # initialize score matrix to original score matrix score_matrix = numpy.array(original_score_matrix, copy=True) old_input = numpy.zeros([length, length], dtype=numpy.int32) old_output = numpy.zeros([length, length], dtype=numpy.int32) current_nodes = [True for _ in range(length)] representatives: List[Set[int]] = [] for node1 in range(length): original_score_matrix[node1, node1] = 0.0 score_matrix[node1, node1] = 0.0 representatives.append({node1}) for node2 in range(node1 + 1, length): old_input[node1, node2] = node1 old_output[node1, node2] = node2 old_input[node2, node1] = node2 old_output[node2, node1] = node1 final_edges: Dict[int, int] = {} # The main algorithm operates inplace. chu_liu_edmonds(length, score_matrix, current_nodes, final_edges, old_input, old_output, representatives) heads = numpy.zeros([max_length], numpy.int32) if has_labels: head_type = numpy.ones([max_length], numpy.int32) else: head_type = None for child, parent in final_edges.items(): heads[child] = parent if has_labels: head_type[child] = label_id_matrix[parent, child] return heads, head_type
def printUnusedImports(self): """Produce a report of unused imports.""" for module in self.listModules(): names = [(unused.lineno, unused.name) for unused in module.unused_names] names.sort() for lineno, name in names: if not self.all_unused: line = linecache.getline(module.filename, lineno) if '#' in line: # assume there's a comment explaining why it's not used continue print("%s:%s: %s not used" % (module.filename, lineno, name))
Produce a report of unused imports.
Below is the the instruction that describes the task: ### Input: Produce a report of unused imports. ### Response: def printUnusedImports(self): """Produce a report of unused imports.""" for module in self.listModules(): names = [(unused.lineno, unused.name) for unused in module.unused_names] names.sort() for lineno, name in names: if not self.all_unused: line = linecache.getline(module.filename, lineno) if '#' in line: # assume there's a comment explaining why it's not used continue print("%s:%s: %s not used" % (module.filename, lineno, name))
def evenCompare(a: str, b: str) -> bool: """ A deterministic but more evenly distributed comparator than simple alphabetical. Useful when comparing consecutive strings and an even distribution is needed. Provides an even chance of returning true as often as false """ ab = a.encode('utf-8') bb = b.encode('utf-8') ac = crypto_hash_sha256(ab) bc = crypto_hash_sha256(bb) return ac < bc
A deterministic but more evenly distributed comparator than simple alphabetical. Useful when comparing consecutive strings and an even distribution is needed. Provides an even chance of returning true as often as false
Below is the the instruction that describes the task: ### Input: A deterministic but more evenly distributed comparator than simple alphabetical. Useful when comparing consecutive strings and an even distribution is needed. Provides an even chance of returning true as often as false ### Response: def evenCompare(a: str, b: str) -> bool: """ A deterministic but more evenly distributed comparator than simple alphabetical. Useful when comparing consecutive strings and an even distribution is needed. Provides an even chance of returning true as often as false """ ab = a.encode('utf-8') bb = b.encode('utf-8') ac = crypto_hash_sha256(ab) bc = crypto_hash_sha256(bb) return ac < bc
def files(obj, commit='HEAD', skip_merge_commits=False): """Check the files of the commits.""" from ..kwalitee import check_file, SUPPORTED_FILES from ..hooks import run options = obj.options repository = obj.repository if options.get('colors') is not False: colorama.init(autoreset=True) reset = colorama.Style.RESET_ALL yellow = colorama.Fore.YELLOW green = colorama.Fore.GREEN red = colorama.Fore.RED else: reset = yellow = green = red = '' try: sha = 'oid' commits = _pygit2_commits(commit, repository) except ImportError: try: sha = 'hexsha' commits = _git_commits(commit, repository) except ImportError: click.echo( 'To use this feature, please install pygit2. GitPython will ' 'also work but is not recommended (python <= 2.7 only).', file=sys.stderr) click.exit(2) template = '{0}commit {{commit.{1}}}{2}\n\n'.format(yellow, sha, reset) template += '{message}{errors}\n' error_template = '\n{0}{{filename}}\n{1}{{errors}}{0}'.format(reset, red) no_errors = ['\n{0}Everything is OK.{1}'.format(green, reset)] msg_file_excluded = '\n{0}{{filename}} excluded.{1}'.format(yellow, reset) def _get_files_modified(commit): """Get the list of modified files that are Python or Jinja2.""" cmd = "git show --no-commit-id --name-only --diff-filter=ACMRTUXB {0}" _, files_modified, _ = run(cmd.format(commit)) extensions = [re.escape(ext) for ext in list(SUPPORTED_FILES) + [".rst"]] test = "(?:{0})$".format("|".join(extensions)) return list(filter(lambda f: re.search(test, f), files_modified)) def _ensure_directory(filename): dir_ = os.path.dirname(filename) if not os.path.exists(dir_): os.makedirs(dir_) def _format_errors(args): filename, errors = args if errors is None: return msg_file_excluded.format(filename=filename) else: return error_template.format(filename=filename, errors='\n'.join( errors if len(errors) else no_errors)) count = 0 ident = ' ' re_line = re.compile('^', re.MULTILINE) for commit in commits: if skip_merge_commits and _is_merge_commit(commit): continue message = commit.message commit_sha = getattr(commit, sha) tmpdir = mkdtemp() errors = {} try: for filename in _get_files_modified(commit): cmd = "git show {commit_sha}:{filename}" _, out, _ = run(cmd.format(commit_sha=commit_sha, filename=filename), raw_output=True) destination = os.path.join(tmpdir, filename) _ensure_directory(destination) with open(destination, 'w+') as f: f.write(out) errors[filename] = check_file(destination, **options) finally: shutil.rmtree(tmpdir, ignore_errors=True) message = re.sub(re_line, ident, message) if len(errors): count += 1 errors = map(_format_errors, errors.items()) else: errors = no_errors click.echo(template.format(commit=commit, message=message.encode('utf-8'), errors='\n'.join(errors))) if min(count, 1): raise click.Abort
Check the files of the commits.
Below is the the instruction that describes the task: ### Input: Check the files of the commits. ### Response: def files(obj, commit='HEAD', skip_merge_commits=False): """Check the files of the commits.""" from ..kwalitee import check_file, SUPPORTED_FILES from ..hooks import run options = obj.options repository = obj.repository if options.get('colors') is not False: colorama.init(autoreset=True) reset = colorama.Style.RESET_ALL yellow = colorama.Fore.YELLOW green = colorama.Fore.GREEN red = colorama.Fore.RED else: reset = yellow = green = red = '' try: sha = 'oid' commits = _pygit2_commits(commit, repository) except ImportError: try: sha = 'hexsha' commits = _git_commits(commit, repository) except ImportError: click.echo( 'To use this feature, please install pygit2. GitPython will ' 'also work but is not recommended (python <= 2.7 only).', file=sys.stderr) click.exit(2) template = '{0}commit {{commit.{1}}}{2}\n\n'.format(yellow, sha, reset) template += '{message}{errors}\n' error_template = '\n{0}{{filename}}\n{1}{{errors}}{0}'.format(reset, red) no_errors = ['\n{0}Everything is OK.{1}'.format(green, reset)] msg_file_excluded = '\n{0}{{filename}} excluded.{1}'.format(yellow, reset) def _get_files_modified(commit): """Get the list of modified files that are Python or Jinja2.""" cmd = "git show --no-commit-id --name-only --diff-filter=ACMRTUXB {0}" _, files_modified, _ = run(cmd.format(commit)) extensions = [re.escape(ext) for ext in list(SUPPORTED_FILES) + [".rst"]] test = "(?:{0})$".format("|".join(extensions)) return list(filter(lambda f: re.search(test, f), files_modified)) def _ensure_directory(filename): dir_ = os.path.dirname(filename) if not os.path.exists(dir_): os.makedirs(dir_) def _format_errors(args): filename, errors = args if errors is None: return msg_file_excluded.format(filename=filename) else: return error_template.format(filename=filename, errors='\n'.join( errors if len(errors) else no_errors)) count = 0 ident = ' ' re_line = re.compile('^', re.MULTILINE) for commit in commits: if skip_merge_commits and _is_merge_commit(commit): continue message = commit.message commit_sha = getattr(commit, sha) tmpdir = mkdtemp() errors = {} try: for filename in _get_files_modified(commit): cmd = "git show {commit_sha}:{filename}" _, out, _ = run(cmd.format(commit_sha=commit_sha, filename=filename), raw_output=True) destination = os.path.join(tmpdir, filename) _ensure_directory(destination) with open(destination, 'w+') as f: f.write(out) errors[filename] = check_file(destination, **options) finally: shutil.rmtree(tmpdir, ignore_errors=True) message = re.sub(re_line, ident, message) if len(errors): count += 1 errors = map(_format_errors, errors.items()) else: errors = no_errors click.echo(template.format(commit=commit, message=message.encode('utf-8'), errors='\n'.join(errors))) if min(count, 1): raise click.Abort
def LoadState( self, config_parser ): """Set our window state from the given config_parser instance""" if not config_parser: return if ( not config_parser.has_section( 'window' ) or ( config_parser.has_option( 'window','maximized' ) and config_parser.getboolean( 'window', 'maximized' ) ) ): self.Maximize(True) try: width,height,x,y = [ config_parser.getint( 'window',key ) for key in ['width','height','x','y'] ] self.SetPosition( (x,y)) self.SetSize( (width,height)) except ConfigParser.NoSectionError, err: # the file isn't written yet, so don't even warn... pass except Exception, err: # this is just convenience, if it breaks in *any* way, ignore it... log.error( "Unable to load window preferences, ignoring: %s", traceback.format_exc() ) try: font_size = config_parser.getint('window', 'font_size') except Exception: pass # use the default, by default else: font = wx.SystemSettings_GetFont(wx.SYS_DEFAULT_GUI_FONT) font.SetPointSize(font_size) for ctrl in self.ProfileListControls: ctrl.SetFont(font) for control in self.ProfileListControls: control.LoadState( config_parser ) self.config = config_parser wx.EVT_CLOSE( self, self.OnCloseWindow )
Set our window state from the given config_parser instance
Below is the the instruction that describes the task: ### Input: Set our window state from the given config_parser instance ### Response: def LoadState( self, config_parser ): """Set our window state from the given config_parser instance""" if not config_parser: return if ( not config_parser.has_section( 'window' ) or ( config_parser.has_option( 'window','maximized' ) and config_parser.getboolean( 'window', 'maximized' ) ) ): self.Maximize(True) try: width,height,x,y = [ config_parser.getint( 'window',key ) for key in ['width','height','x','y'] ] self.SetPosition( (x,y)) self.SetSize( (width,height)) except ConfigParser.NoSectionError, err: # the file isn't written yet, so don't even warn... pass except Exception, err: # this is just convenience, if it breaks in *any* way, ignore it... log.error( "Unable to load window preferences, ignoring: %s", traceback.format_exc() ) try: font_size = config_parser.getint('window', 'font_size') except Exception: pass # use the default, by default else: font = wx.SystemSettings_GetFont(wx.SYS_DEFAULT_GUI_FONT) font.SetPointSize(font_size) for ctrl in self.ProfileListControls: ctrl.SetFont(font) for control in self.ProfileListControls: control.LoadState( config_parser ) self.config = config_parser wx.EVT_CLOSE( self, self.OnCloseWindow )
def _set_automatic_tag(self, v, load=False): """ Setter method for automatic_tag, mapped from YANG variable /routing_system/route_map/content/set/automatic_tag (container) If this variable is read-only (config: false) in the source YANG file, then _set_automatic_tag is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_automatic_tag() directly. YANG Description: Automatically compute TAG value """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=automatic_tag.automatic_tag, is_container='container', presence=False, yang_name="automatic-tag", rest_name="automatic-tag", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'Automatically compute TAG value', u'cli-full-no': None}}, namespace='urn:brocade.com:mgmt:brocade-ip-policy', defining_module='brocade-ip-policy', yang_type='container', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """automatic_tag must be of a type compatible with container""", 'defined-type': "container", 'generated-type': """YANGDynClass(base=automatic_tag.automatic_tag, is_container='container', presence=False, yang_name="automatic-tag", rest_name="automatic-tag", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'Automatically compute TAG value', u'cli-full-no': None}}, namespace='urn:brocade.com:mgmt:brocade-ip-policy', defining_module='brocade-ip-policy', yang_type='container', is_config=True)""", }) self.__automatic_tag = t if hasattr(self, '_set'): self._set()
Setter method for automatic_tag, mapped from YANG variable /routing_system/route_map/content/set/automatic_tag (container) If this variable is read-only (config: false) in the source YANG file, then _set_automatic_tag is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_automatic_tag() directly. YANG Description: Automatically compute TAG value
Below is the the instruction that describes the task: ### Input: Setter method for automatic_tag, mapped from YANG variable /routing_system/route_map/content/set/automatic_tag (container) If this variable is read-only (config: false) in the source YANG file, then _set_automatic_tag is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_automatic_tag() directly. YANG Description: Automatically compute TAG value ### Response: def _set_automatic_tag(self, v, load=False): """ Setter method for automatic_tag, mapped from YANG variable /routing_system/route_map/content/set/automatic_tag (container) If this variable is read-only (config: false) in the source YANG file, then _set_automatic_tag is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_automatic_tag() directly. YANG Description: Automatically compute TAG value """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=automatic_tag.automatic_tag, is_container='container', presence=False, yang_name="automatic-tag", rest_name="automatic-tag", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'Automatically compute TAG value', u'cli-full-no': None}}, namespace='urn:brocade.com:mgmt:brocade-ip-policy', defining_module='brocade-ip-policy', yang_type='container', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """automatic_tag must be of a type compatible with container""", 'defined-type': "container", 'generated-type': """YANGDynClass(base=automatic_tag.automatic_tag, is_container='container', presence=False, yang_name="automatic-tag", rest_name="automatic-tag", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'Automatically compute TAG value', u'cli-full-no': None}}, namespace='urn:brocade.com:mgmt:brocade-ip-policy', defining_module='brocade-ip-policy', yang_type='container', is_config=True)""", }) self.__automatic_tag = t if hasattr(self, '_set'): self._set()
def normalize_cmd(cmd): """Fixes for the following issues on windows - https://bugs.python.org/issue8557 - windows does not parse shebangs This function also makes deep-path shebangs work just fine """ # Use PATH to determine the executable exe = normexe(cmd[0]) # Figure out the shebang from the resulting command cmd = parse_filename(exe) + (exe,) + cmd[1:] # This could have given us back another bare executable exe = normexe(cmd[0]) return (exe,) + cmd[1:]
Fixes for the following issues on windows - https://bugs.python.org/issue8557 - windows does not parse shebangs This function also makes deep-path shebangs work just fine
Below is the the instruction that describes the task: ### Input: Fixes for the following issues on windows - https://bugs.python.org/issue8557 - windows does not parse shebangs This function also makes deep-path shebangs work just fine ### Response: def normalize_cmd(cmd): """Fixes for the following issues on windows - https://bugs.python.org/issue8557 - windows does not parse shebangs This function also makes deep-path shebangs work just fine """ # Use PATH to determine the executable exe = normexe(cmd[0]) # Figure out the shebang from the resulting command cmd = parse_filename(exe) + (exe,) + cmd[1:] # This could have given us back another bare executable exe = normexe(cmd[0]) return (exe,) + cmd[1:]
def Bool(value: "__builtins__.bool", annotations: Annotations = None) -> bool.Bool: """ Creates a Bool with concrete value :param value: The boolean value :param annotations: The annotations to initialize the bool with :return: The freshly created Bool() """ raw = z3.BoolVal(value) return Bool(raw, annotations)
Creates a Bool with concrete value :param value: The boolean value :param annotations: The annotations to initialize the bool with :return: The freshly created Bool()
Below is the the instruction that describes the task: ### Input: Creates a Bool with concrete value :param value: The boolean value :param annotations: The annotations to initialize the bool with :return: The freshly created Bool() ### Response: def Bool(value: "__builtins__.bool", annotations: Annotations = None) -> bool.Bool: """ Creates a Bool with concrete value :param value: The boolean value :param annotations: The annotations to initialize the bool with :return: The freshly created Bool() """ raw = z3.BoolVal(value) return Bool(raw, annotations)
def get_absolute_url(self, endpoint): """Get absolute for secret link (using https scheme). The endpoint is passed to ``url_for`` with ``token`` and ``extra_data`` as keyword arguments. E.g.:: >>> link.extra_data dict(recid=1) >>> link.get_absolute_url('record.metadata') translates into:: >>> url_for('record.metadata', token="...", recid=1, ) """ copy = deepcopy(self.extra_data) if 'recid' in copy: copy['pid_value'] = copy.pop('recid') return url_for( endpoint, token=self.token, _external=True, **(copy or {}) )
Get absolute for secret link (using https scheme). The endpoint is passed to ``url_for`` with ``token`` and ``extra_data`` as keyword arguments. E.g.:: >>> link.extra_data dict(recid=1) >>> link.get_absolute_url('record.metadata') translates into:: >>> url_for('record.metadata', token="...", recid=1, )
Below is the the instruction that describes the task: ### Input: Get absolute for secret link (using https scheme). The endpoint is passed to ``url_for`` with ``token`` and ``extra_data`` as keyword arguments. E.g.:: >>> link.extra_data dict(recid=1) >>> link.get_absolute_url('record.metadata') translates into:: >>> url_for('record.metadata', token="...", recid=1, ) ### Response: def get_absolute_url(self, endpoint): """Get absolute for secret link (using https scheme). The endpoint is passed to ``url_for`` with ``token`` and ``extra_data`` as keyword arguments. E.g.:: >>> link.extra_data dict(recid=1) >>> link.get_absolute_url('record.metadata') translates into:: >>> url_for('record.metadata', token="...", recid=1, ) """ copy = deepcopy(self.extra_data) if 'recid' in copy: copy['pid_value'] = copy.pop('recid') return url_for( endpoint, token=self.token, _external=True, **(copy or {}) )
def batch(inputs, max_sequence_length=None): """ Args: inputs: list of sentences (integer lists) max_sequence_length: integer specifying how large should `max_time` dimension be. If None, maximum sequence length would be used Outputs: inputs_time_major: input sentences transformed into time-major matrix (shape [max_time, batch_size]) padded with 0s sequence_lengths: batch-sized list of integers specifying amount of active time steps in each input sequence """ sequence_lengths = [len(seq) for seq in inputs] batch_size = len(inputs) if max_sequence_length is None: max_sequence_length = max(sequence_lengths) inputs_batch_major = np.zeros(shape=[batch_size, max_sequence_length], dtype=np.int32) # == PAD for i, seq in enumerate(inputs): for j, element in enumerate(seq): inputs_batch_major[i, j] = element # [batch_size, max_time] -> [max_time, batch_size] inputs_time_major = inputs_batch_major.swapaxes(0, 1) return inputs_time_major, sequence_lengths
Args: inputs: list of sentences (integer lists) max_sequence_length: integer specifying how large should `max_time` dimension be. If None, maximum sequence length would be used Outputs: inputs_time_major: input sentences transformed into time-major matrix (shape [max_time, batch_size]) padded with 0s sequence_lengths: batch-sized list of integers specifying amount of active time steps in each input sequence
Below is the the instruction that describes the task: ### Input: Args: inputs: list of sentences (integer lists) max_sequence_length: integer specifying how large should `max_time` dimension be. If None, maximum sequence length would be used Outputs: inputs_time_major: input sentences transformed into time-major matrix (shape [max_time, batch_size]) padded with 0s sequence_lengths: batch-sized list of integers specifying amount of active time steps in each input sequence ### Response: def batch(inputs, max_sequence_length=None): """ Args: inputs: list of sentences (integer lists) max_sequence_length: integer specifying how large should `max_time` dimension be. If None, maximum sequence length would be used Outputs: inputs_time_major: input sentences transformed into time-major matrix (shape [max_time, batch_size]) padded with 0s sequence_lengths: batch-sized list of integers specifying amount of active time steps in each input sequence """ sequence_lengths = [len(seq) for seq in inputs] batch_size = len(inputs) if max_sequence_length is None: max_sequence_length = max(sequence_lengths) inputs_batch_major = np.zeros(shape=[batch_size, max_sequence_length], dtype=np.int32) # == PAD for i, seq in enumerate(inputs): for j, element in enumerate(seq): inputs_batch_major[i, j] = element # [batch_size, max_time] -> [max_time, batch_size] inputs_time_major = inputs_batch_major.swapaxes(0, 1) return inputs_time_major, sequence_lengths
def supplement(self,coordsys='gal'): """ Add some supplemental columns """ from ugali.utils.projector import gal2cel, gal2cel_angle from ugali.utils.projector import cel2gal, cel2gal_angle coordsys = coordsys.lower() kwargs = dict(usemask=False, asrecarray=True) out = copy.deepcopy(self) if ('lon' in out.names) and ('lat' in out.names): # Ignore entries that are all zero zeros = np.all(self.ndarray==0,axis=1) if coordsys == 'gal': ra,dec = gal2cel(out.lon,out.lat) glon,glat = out.lon,out.lat else: ra,dec = out.lon,out.lat glon,glat = cel2gal(out.lon,out.lat) ra[zeros] = 0; dec[zeros] = 0 glon[zeros] = 0; glat[zeros] = 0 names = ['ra','dec','glon','glat'] arrs = [ra,dec,glon,glat] out = mlab.rec_append_fields(out,names,arrs).view(Samples) #out = recfuncs.append_fields(out,names,arrs,**kwargs).view(Samples) if 'position_angle' in out.names: if coordsys == 'gal': pa_gal = out.position_angle pa_cel = gal2cel_angle(out.lon,out.lat,out.position_angle) pa_cel = pa_cel - 180.*(pa_cel > 180.) else: pa_gal = cel2gal_angle(out.lon,out.lat,out.position_angle) pa_cel = out.position_angle pa_gal = pa_gal - 180.*(pa_gal > 180.) pa_gal[zeros] = 0; pa_cel[zeros] = 0 names = ['position_angle_gal','position_angle_cel'] arrs = [pa_gal,pa_cel] out = recfuncs.append_fields(out,names,arrs,**kwargs).view(Samples) return out
Add some supplemental columns
Below is the the instruction that describes the task: ### Input: Add some supplemental columns ### Response: def supplement(self,coordsys='gal'): """ Add some supplemental columns """ from ugali.utils.projector import gal2cel, gal2cel_angle from ugali.utils.projector import cel2gal, cel2gal_angle coordsys = coordsys.lower() kwargs = dict(usemask=False, asrecarray=True) out = copy.deepcopy(self) if ('lon' in out.names) and ('lat' in out.names): # Ignore entries that are all zero zeros = np.all(self.ndarray==0,axis=1) if coordsys == 'gal': ra,dec = gal2cel(out.lon,out.lat) glon,glat = out.lon,out.lat else: ra,dec = out.lon,out.lat glon,glat = cel2gal(out.lon,out.lat) ra[zeros] = 0; dec[zeros] = 0 glon[zeros] = 0; glat[zeros] = 0 names = ['ra','dec','glon','glat'] arrs = [ra,dec,glon,glat] out = mlab.rec_append_fields(out,names,arrs).view(Samples) #out = recfuncs.append_fields(out,names,arrs,**kwargs).view(Samples) if 'position_angle' in out.names: if coordsys == 'gal': pa_gal = out.position_angle pa_cel = gal2cel_angle(out.lon,out.lat,out.position_angle) pa_cel = pa_cel - 180.*(pa_cel > 180.) else: pa_gal = cel2gal_angle(out.lon,out.lat,out.position_angle) pa_cel = out.position_angle pa_gal = pa_gal - 180.*(pa_gal > 180.) pa_gal[zeros] = 0; pa_cel[zeros] = 0 names = ['position_angle_gal','position_angle_cel'] arrs = [pa_gal,pa_cel] out = recfuncs.append_fields(out,names,arrs,**kwargs).view(Samples) return out
def gettextdelimiter(self, retaintokenisation=False): """See :meth:`AbstractElement.gettextdelimiter`""" for e in self: if isinstance(e, New) or isinstance(e, Current): return e.gettextdelimiter(retaintokenisation) return ""
See :meth:`AbstractElement.gettextdelimiter`
Below is the the instruction that describes the task: ### Input: See :meth:`AbstractElement.gettextdelimiter` ### Response: def gettextdelimiter(self, retaintokenisation=False): """See :meth:`AbstractElement.gettextdelimiter`""" for e in self: if isinstance(e, New) or isinstance(e, Current): return e.gettextdelimiter(retaintokenisation) return ""
def cio_close(cio): """Wraps openjpeg library function cio_close. """ OPENJPEG.opj_cio_close.argtypes = [ctypes.POINTER(CioType)] OPENJPEG.opj_cio_close(cio)
Wraps openjpeg library function cio_close.
Below is the the instruction that describes the task: ### Input: Wraps openjpeg library function cio_close. ### Response: def cio_close(cio): """Wraps openjpeg library function cio_close. """ OPENJPEG.opj_cio_close.argtypes = [ctypes.POINTER(CioType)] OPENJPEG.opj_cio_close(cio)
def combine_ranked_stations(rankings): """ Combine :any:`pandas.DataFrame` s of candidate weather stations to form a hybrid ranking dataframe. Parameters ---------- rankings : list of :any:`pandas.DataFrame` Dataframes of ranked weather station candidates and metadata. All ranking dataframes should have the same columns and must be sorted by rank. Returns ------- ranked_filtered_candidates : :any:`pandas.DataFrame` Dataframe has a rank column and the same columns given in the source dataframes. """ if len(rankings) == 0: raise ValueError("Requires at least one ranking.") combined_ranking = rankings[0] for ranking in rankings[1:]: filtered_ranking = ranking[~ranking.index.isin(combined_ranking.index)] combined_ranking = pd.concat([combined_ranking, filtered_ranking]) combined_ranking["rank"] = range(1, 1 + len(combined_ranking)) return combined_ranking
Combine :any:`pandas.DataFrame` s of candidate weather stations to form a hybrid ranking dataframe. Parameters ---------- rankings : list of :any:`pandas.DataFrame` Dataframes of ranked weather station candidates and metadata. All ranking dataframes should have the same columns and must be sorted by rank. Returns ------- ranked_filtered_candidates : :any:`pandas.DataFrame` Dataframe has a rank column and the same columns given in the source dataframes.
Below is the the instruction that describes the task: ### Input: Combine :any:`pandas.DataFrame` s of candidate weather stations to form a hybrid ranking dataframe. Parameters ---------- rankings : list of :any:`pandas.DataFrame` Dataframes of ranked weather station candidates and metadata. All ranking dataframes should have the same columns and must be sorted by rank. Returns ------- ranked_filtered_candidates : :any:`pandas.DataFrame` Dataframe has a rank column and the same columns given in the source dataframes. ### Response: def combine_ranked_stations(rankings): """ Combine :any:`pandas.DataFrame` s of candidate weather stations to form a hybrid ranking dataframe. Parameters ---------- rankings : list of :any:`pandas.DataFrame` Dataframes of ranked weather station candidates and metadata. All ranking dataframes should have the same columns and must be sorted by rank. Returns ------- ranked_filtered_candidates : :any:`pandas.DataFrame` Dataframe has a rank column and the same columns given in the source dataframes. """ if len(rankings) == 0: raise ValueError("Requires at least one ranking.") combined_ranking = rankings[0] for ranking in rankings[1:]: filtered_ranking = ranking[~ranking.index.isin(combined_ranking.index)] combined_ranking = pd.concat([combined_ranking, filtered_ranking]) combined_ranking["rank"] = range(1, 1 + len(combined_ranking)) return combined_ranking
def parallel(func, inputs, n_jobs, expand_args=False): """ Convenience wrapper around joblib's parallelization. """ if expand_args: return Parallel(n_jobs=n_jobs)(delayed(func)(*args) for args in inputs) else: return Parallel(n_jobs=n_jobs)(delayed(func)(arg) for arg in inputs)
Convenience wrapper around joblib's parallelization.
Below is the the instruction that describes the task: ### Input: Convenience wrapper around joblib's parallelization. ### Response: def parallel(func, inputs, n_jobs, expand_args=False): """ Convenience wrapper around joblib's parallelization. """ if expand_args: return Parallel(n_jobs=n_jobs)(delayed(func)(*args) for args in inputs) else: return Parallel(n_jobs=n_jobs)(delayed(func)(arg) for arg in inputs)
def add_product_version_to_build_configuration(id=None, name=None, product_version_id=None): """ Associate an existing ProductVersion with a BuildConfiguration """ data = remove_product_version_from_build_configuration_raw(id, name, product_version_id) if data: return utils.format_json_list(data)
Associate an existing ProductVersion with a BuildConfiguration
Below is the the instruction that describes the task: ### Input: Associate an existing ProductVersion with a BuildConfiguration ### Response: def add_product_version_to_build_configuration(id=None, name=None, product_version_id=None): """ Associate an existing ProductVersion with a BuildConfiguration """ data = remove_product_version_from_build_configuration_raw(id, name, product_version_id) if data: return utils.format_json_list(data)
def canonical_name(name): """Find the canonical name for the given window in scipy.signal Parameters ---------- name : `str` the name of the window you want Returns ------- realname : `str` the name of the window as implemented in `scipy.signal.window` Raises ------- ValueError if ``name`` cannot be resolved to a window function in `scipy.signal` Examples -------- >>> from gwpy.signal.window import canonical_name >>> canonical_name('hanning') 'hann' >>> canonical_name('ksr') 'kaiser' """ if name.lower() == 'planck': # make sure to handle the Planck window return 'planck' try: # use equivalence introduced in scipy 0.16.0 # pylint: disable=protected-access return scipy_windows._win_equiv[name.lower()].__name__ except AttributeError: # old scipy try: return getattr(scipy_windows, name.lower()).__name__ except AttributeError: # no match pass # raise later except KeyError: # no match pass # raise later raise ValueError('no window function in scipy.signal equivalent to %r' % name,)
Find the canonical name for the given window in scipy.signal Parameters ---------- name : `str` the name of the window you want Returns ------- realname : `str` the name of the window as implemented in `scipy.signal.window` Raises ------- ValueError if ``name`` cannot be resolved to a window function in `scipy.signal` Examples -------- >>> from gwpy.signal.window import canonical_name >>> canonical_name('hanning') 'hann' >>> canonical_name('ksr') 'kaiser'
Below is the the instruction that describes the task: ### Input: Find the canonical name for the given window in scipy.signal Parameters ---------- name : `str` the name of the window you want Returns ------- realname : `str` the name of the window as implemented in `scipy.signal.window` Raises ------- ValueError if ``name`` cannot be resolved to a window function in `scipy.signal` Examples -------- >>> from gwpy.signal.window import canonical_name >>> canonical_name('hanning') 'hann' >>> canonical_name('ksr') 'kaiser' ### Response: def canonical_name(name): """Find the canonical name for the given window in scipy.signal Parameters ---------- name : `str` the name of the window you want Returns ------- realname : `str` the name of the window as implemented in `scipy.signal.window` Raises ------- ValueError if ``name`` cannot be resolved to a window function in `scipy.signal` Examples -------- >>> from gwpy.signal.window import canonical_name >>> canonical_name('hanning') 'hann' >>> canonical_name('ksr') 'kaiser' """ if name.lower() == 'planck': # make sure to handle the Planck window return 'planck' try: # use equivalence introduced in scipy 0.16.0 # pylint: disable=protected-access return scipy_windows._win_equiv[name.lower()].__name__ except AttributeError: # old scipy try: return getattr(scipy_windows, name.lower()).__name__ except AttributeError: # no match pass # raise later except KeyError: # no match pass # raise later raise ValueError('no window function in scipy.signal equivalent to %r' % name,)
def get_constant(value): """ When `value` is a string, get the corresponding constant from [`scipy.constants`][1]. [1]: http://docs.scipy.org/doc/scipy/reference/constants.html """ if type(value) is str: if hasattr(scipy.constants, value): return getattr(scipy.constants, value) else: return scipy.constants.physical_constants[value][0] else: return value
When `value` is a string, get the corresponding constant from [`scipy.constants`][1]. [1]: http://docs.scipy.org/doc/scipy/reference/constants.html
Below is the the instruction that describes the task: ### Input: When `value` is a string, get the corresponding constant from [`scipy.constants`][1]. [1]: http://docs.scipy.org/doc/scipy/reference/constants.html ### Response: def get_constant(value): """ When `value` is a string, get the corresponding constant from [`scipy.constants`][1]. [1]: http://docs.scipy.org/doc/scipy/reference/constants.html """ if type(value) is str: if hasattr(scipy.constants, value): return getattr(scipy.constants, value) else: return scipy.constants.physical_constants[value][0] else: return value
def _get_inst_repo(self, namespace=None): """ Test support method that returns instances from the repository with no processing. It uses the default namespace if input parameter for namespace is None """ if namespace is None: namespace = self.default_namespace return self.instances[namespace]
Test support method that returns instances from the repository with no processing. It uses the default namespace if input parameter for namespace is None
Below is the the instruction that describes the task: ### Input: Test support method that returns instances from the repository with no processing. It uses the default namespace if input parameter for namespace is None ### Response: def _get_inst_repo(self, namespace=None): """ Test support method that returns instances from the repository with no processing. It uses the default namespace if input parameter for namespace is None """ if namespace is None: namespace = self.default_namespace return self.instances[namespace]
def get_assessment_basic_authoring_session(self, proxy): """Gets the ``OsidSession`` associated with the assessment authoring service. arg: proxy (osid.proxy.Proxy): a proxy return: (osid.assessment.AssessmentBasicAuthoringSession) - an ``AssessmentBasicAuthoringSession`` raise: NullArgument - ``proxy`` is ``null`` raise: OperationFailed - unable to complete request raise: Unimplemented - ``supports_assessment_basic_authoring()`` is ``false`` *compliance: optional -- This method must be implemented if ``supports_assessment_basic_authoring()`` is ``true``.* """ if not self.supports_assessment_basic_authoring(): raise errors.Unimplemented() # pylint: disable=no-member return sessions.AssessmentBasicAuthoringSession(proxy=proxy, runtime=self._runtime)
Gets the ``OsidSession`` associated with the assessment authoring service. arg: proxy (osid.proxy.Proxy): a proxy return: (osid.assessment.AssessmentBasicAuthoringSession) - an ``AssessmentBasicAuthoringSession`` raise: NullArgument - ``proxy`` is ``null`` raise: OperationFailed - unable to complete request raise: Unimplemented - ``supports_assessment_basic_authoring()`` is ``false`` *compliance: optional -- This method must be implemented if ``supports_assessment_basic_authoring()`` is ``true``.*
Below is the the instruction that describes the task: ### Input: Gets the ``OsidSession`` associated with the assessment authoring service. arg: proxy (osid.proxy.Proxy): a proxy return: (osid.assessment.AssessmentBasicAuthoringSession) - an ``AssessmentBasicAuthoringSession`` raise: NullArgument - ``proxy`` is ``null`` raise: OperationFailed - unable to complete request raise: Unimplemented - ``supports_assessment_basic_authoring()`` is ``false`` *compliance: optional -- This method must be implemented if ``supports_assessment_basic_authoring()`` is ``true``.* ### Response: def get_assessment_basic_authoring_session(self, proxy): """Gets the ``OsidSession`` associated with the assessment authoring service. arg: proxy (osid.proxy.Proxy): a proxy return: (osid.assessment.AssessmentBasicAuthoringSession) - an ``AssessmentBasicAuthoringSession`` raise: NullArgument - ``proxy`` is ``null`` raise: OperationFailed - unable to complete request raise: Unimplemented - ``supports_assessment_basic_authoring()`` is ``false`` *compliance: optional -- This method must be implemented if ``supports_assessment_basic_authoring()`` is ``true``.* """ if not self.supports_assessment_basic_authoring(): raise errors.Unimplemented() # pylint: disable=no-member return sessions.AssessmentBasicAuthoringSession(proxy=proxy, runtime=self._runtime)
def level_i18n_name(self): """In use within templates for dynamic translations.""" for level, name in spatial_granularities: if self.level == level: return name return self.level_name
In use within templates for dynamic translations.
Below is the the instruction that describes the task: ### Input: In use within templates for dynamic translations. ### Response: def level_i18n_name(self): """In use within templates for dynamic translations.""" for level, name in spatial_granularities: if self.level == level: return name return self.level_name
def get_extra_functions(self) -> Dict[str, Callable]: """Get a list of additional features Returns: Dict[str, Callable]: A dict of methods marked as additional features. Method can be called with ``get_extra_functions()["methodName"]()``. """ methods = {} for mName in dir(self): m = getattr(self, mName) if callable(m) and getattr(m, "extra_fn", False): methods[mName] = m return methods
Get a list of additional features Returns: Dict[str, Callable]: A dict of methods marked as additional features. Method can be called with ``get_extra_functions()["methodName"]()``.
Below is the the instruction that describes the task: ### Input: Get a list of additional features Returns: Dict[str, Callable]: A dict of methods marked as additional features. Method can be called with ``get_extra_functions()["methodName"]()``. ### Response: def get_extra_functions(self) -> Dict[str, Callable]: """Get a list of additional features Returns: Dict[str, Callable]: A dict of methods marked as additional features. Method can be called with ``get_extra_functions()["methodName"]()``. """ methods = {} for mName in dir(self): m = getattr(self, mName) if callable(m) and getattr(m, "extra_fn", False): methods[mName] = m return methods
def create_multi_output_factor(self, tool, source, splitting_node, sink): """ Creates a multi-output factor. This takes a single node, applies a MultiOutputTool to create multiple nodes on a new plate Instantiates a single tool for all of the input plate values, and connects the source and sink nodes with that tool. Note that the tool parameters these are currently fixed over a plate. For parameters that vary over a plate, an extra input stream should be used :param tool: The tool to use. This is either an instantiated Tool object or a dict with "name" and "parameters" :param source: The source node :param splitting_node: The node over which to split :param sink: The sink node :return: The factor object :type tool: MultiOutputTool | dict :type source: Node | None :type sink: Node :rtype: Factor """ if source and not isinstance(source, Node): raise ValueError("Expected Node, got {}".format(type(source))) if not isinstance(sink, Node): raise ValueError("Expected Node, got {}".format(type(sink))) # if isinstance(tool, dict): # tool = self.channels.get_tool(**tool) if not isinstance(tool, MultiOutputTool): raise ValueError("Expected MultiOutputTool, got {}".format(type(tool))) # Check that the input_plate are compatible - note this is the opposite way round to a normal factor input_plates = source.plates if source else [] output_plates = sink.plates if len(input_plates) > 1: raise NotImplementedError if len(output_plates) == 0: raise ValueError("No output plate found") if len(output_plates) == 1: if not self.check_multi_output_plate_compatibility(input_plates, output_plates[0]): raise IncompatiblePlatesError("Parent plate does not match input plate") factor = MultiOutputFactor(tool=tool, source_node=source, splitting_node=splitting_node, sink_node=sink, input_plate=input_plates[0] if input_plates else None, output_plates=output_plates[0]) else: # The output plates should be the same as the input plates, except for one # additional plate. Since we're currently only supporting one input plate, # we can safely assume that there is a single matching plate. # Finally, note that the output plate must either have no parents # (i.e. it is at the root of the tree), or the parent plate is somewhere # in the input plate's ancestry if len(output_plates) > 2: raise NotImplementedError if len(input_plates) != 1: raise IncompatiblePlatesError("Require an input plate to match all but one of the output plates") if output_plates[0] == input_plates[0]: # Found a match, so the output plate should be the other plate output_plate = output_plates[1] else: if output_plates[1].plate_id != input_plates[0].plate_id: raise IncompatiblePlatesError("Require an input plate to match all but one of the output plates") output_plate = output_plates[0] # Swap them round so the new plate is the last plate - this is required by the factor output_plates[1], output_plates[0] = output_plates[0], output_plates[1] if not output_plate.is_root: # We need to walk up the input plate's parent tree match = False parent = input_plates[0].parent while parent is not None: if parent.plate_id == output_plate.parent.plate_id: match = True break parent = parent.parent if not match: raise IncompatiblePlatesError("Require an input plate to match all but one of the output plates") factor = MultiOutputFactor( tool=tool, source_node=source, sink_node=sink, splitting_node=splitting_node, input_plate=input_plates[0], output_plates=output_plates) self._add_factor(factor) return factor
Creates a multi-output factor. This takes a single node, applies a MultiOutputTool to create multiple nodes on a new plate Instantiates a single tool for all of the input plate values, and connects the source and sink nodes with that tool. Note that the tool parameters these are currently fixed over a plate. For parameters that vary over a plate, an extra input stream should be used :param tool: The tool to use. This is either an instantiated Tool object or a dict with "name" and "parameters" :param source: The source node :param splitting_node: The node over which to split :param sink: The sink node :return: The factor object :type tool: MultiOutputTool | dict :type source: Node | None :type sink: Node :rtype: Factor
Below is the the instruction that describes the task: ### Input: Creates a multi-output factor. This takes a single node, applies a MultiOutputTool to create multiple nodes on a new plate Instantiates a single tool for all of the input plate values, and connects the source and sink nodes with that tool. Note that the tool parameters these are currently fixed over a plate. For parameters that vary over a plate, an extra input stream should be used :param tool: The tool to use. This is either an instantiated Tool object or a dict with "name" and "parameters" :param source: The source node :param splitting_node: The node over which to split :param sink: The sink node :return: The factor object :type tool: MultiOutputTool | dict :type source: Node | None :type sink: Node :rtype: Factor ### Response: def create_multi_output_factor(self, tool, source, splitting_node, sink): """ Creates a multi-output factor. This takes a single node, applies a MultiOutputTool to create multiple nodes on a new plate Instantiates a single tool for all of the input plate values, and connects the source and sink nodes with that tool. Note that the tool parameters these are currently fixed over a plate. For parameters that vary over a plate, an extra input stream should be used :param tool: The tool to use. This is either an instantiated Tool object or a dict with "name" and "parameters" :param source: The source node :param splitting_node: The node over which to split :param sink: The sink node :return: The factor object :type tool: MultiOutputTool | dict :type source: Node | None :type sink: Node :rtype: Factor """ if source and not isinstance(source, Node): raise ValueError("Expected Node, got {}".format(type(source))) if not isinstance(sink, Node): raise ValueError("Expected Node, got {}".format(type(sink))) # if isinstance(tool, dict): # tool = self.channels.get_tool(**tool) if not isinstance(tool, MultiOutputTool): raise ValueError("Expected MultiOutputTool, got {}".format(type(tool))) # Check that the input_plate are compatible - note this is the opposite way round to a normal factor input_plates = source.plates if source else [] output_plates = sink.plates if len(input_plates) > 1: raise NotImplementedError if len(output_plates) == 0: raise ValueError("No output plate found") if len(output_plates) == 1: if not self.check_multi_output_plate_compatibility(input_plates, output_plates[0]): raise IncompatiblePlatesError("Parent plate does not match input plate") factor = MultiOutputFactor(tool=tool, source_node=source, splitting_node=splitting_node, sink_node=sink, input_plate=input_plates[0] if input_plates else None, output_plates=output_plates[0]) else: # The output plates should be the same as the input plates, except for one # additional plate. Since we're currently only supporting one input plate, # we can safely assume that there is a single matching plate. # Finally, note that the output plate must either have no parents # (i.e. it is at the root of the tree), or the parent plate is somewhere # in the input plate's ancestry if len(output_plates) > 2: raise NotImplementedError if len(input_plates) != 1: raise IncompatiblePlatesError("Require an input plate to match all but one of the output plates") if output_plates[0] == input_plates[0]: # Found a match, so the output plate should be the other plate output_plate = output_plates[1] else: if output_plates[1].plate_id != input_plates[0].plate_id: raise IncompatiblePlatesError("Require an input plate to match all but one of the output plates") output_plate = output_plates[0] # Swap them round so the new plate is the last plate - this is required by the factor output_plates[1], output_plates[0] = output_plates[0], output_plates[1] if not output_plate.is_root: # We need to walk up the input plate's parent tree match = False parent = input_plates[0].parent while parent is not None: if parent.plate_id == output_plate.parent.plate_id: match = True break parent = parent.parent if not match: raise IncompatiblePlatesError("Require an input plate to match all but one of the output plates") factor = MultiOutputFactor( tool=tool, source_node=source, sink_node=sink, splitting_node=splitting_node, input_plate=input_plates[0], output_plates=output_plates) self._add_factor(factor) return factor
def real_filename_complete(self, text, line, begidx, endidx): """Figure out what filenames match the completion.""" # line contains the full command line that's been entered so far. # text contains the portion of the line that readline is trying to complete # text should correspond to line[begidx:endidx] # # The way the completer works text will start after one of the characters # in DELIMS. So if the filename entered so far was "embedded\ sp" then # text will point to the s in sp. # # The following bit of logic backs up to find the real beginning of the # filename. if begidx >= len(line): # This happens when you hit TAB on an empty filename before_match = begidx else: for before_match in range(begidx, 0, -1): if line[before_match] in DELIMS and before_match >= 1 and line[before_match - 1] != '\\': break # We set fixed to be the portion of the filename which is before text # and match is the full portion of the filename that's been entered so # far (that's the part we use for matching files). # # When we return a list of completions, the bit that we return should # just be the portion that we replace 'text' with. fixed = unescape(line[before_match+1:begidx]) # fixed portion of the match match = unescape(line[before_match+1:endidx]) # portion to match filenames against # We do the following to cover the case that the current directory # is / and the path being entered is relative. strip = '' if len(match) > 0 and match[0] == '/': abs_match = match elif cur_dir == '/': abs_match = cur_dir + match strip = cur_dir else: abs_match = cur_dir + '/' + match strip = cur_dir + '/' completions = [] prepend = '' if abs_match.rfind('/') == 0: # match is in the root directory # This means that we're looking for matches in the root directory # (i.e. abs_match is /foo and the user hit TAB). # So we'll supply the matching board names as possible completions. # Since they're all treated as directories we leave the trailing slash. with DEV_LOCK: if match[0] == '/': completions += [dev.name_path for dev in DEVS if dev.name_path.startswith(abs_match)] else: completions += [dev.name_path[1:] for dev in DEVS if dev.name_path.startswith(abs_match)] if DEFAULT_DEV: # Add root directories of the default device (i.e. /flash/ and /sd/) if match[0] == '/': completions += [root_dir for root_dir in DEFAULT_DEV.root_dirs if root_dir.startswith(match)] else: completions += [root_dir[1:] for root_dir in DEFAULT_DEV.root_dirs if root_dir[1:].startswith(match)] else: # This means that there are at least 2 slashes in abs_match. If one # of them matches a board name then we need to remove the board # name from fixed. Since the results from listdir_matches won't # contain the board name, we need to prepend each of the completions. with DEV_LOCK: for dev in DEVS: if abs_match.startswith(dev.name_path): prepend = dev.name_path[:-1] break paths = sorted(auto(listdir_matches, abs_match)) for path in paths: path = prepend + path if path.startswith(strip): path = path[len(strip):] completions.append(escape(path.replace(fixed, '', 1))) return completions
Figure out what filenames match the completion.
Below is the the instruction that describes the task: ### Input: Figure out what filenames match the completion. ### Response: def real_filename_complete(self, text, line, begidx, endidx): """Figure out what filenames match the completion.""" # line contains the full command line that's been entered so far. # text contains the portion of the line that readline is trying to complete # text should correspond to line[begidx:endidx] # # The way the completer works text will start after one of the characters # in DELIMS. So if the filename entered so far was "embedded\ sp" then # text will point to the s in sp. # # The following bit of logic backs up to find the real beginning of the # filename. if begidx >= len(line): # This happens when you hit TAB on an empty filename before_match = begidx else: for before_match in range(begidx, 0, -1): if line[before_match] in DELIMS and before_match >= 1 and line[before_match - 1] != '\\': break # We set fixed to be the portion of the filename which is before text # and match is the full portion of the filename that's been entered so # far (that's the part we use for matching files). # # When we return a list of completions, the bit that we return should # just be the portion that we replace 'text' with. fixed = unescape(line[before_match+1:begidx]) # fixed portion of the match match = unescape(line[before_match+1:endidx]) # portion to match filenames against # We do the following to cover the case that the current directory # is / and the path being entered is relative. strip = '' if len(match) > 0 and match[0] == '/': abs_match = match elif cur_dir == '/': abs_match = cur_dir + match strip = cur_dir else: abs_match = cur_dir + '/' + match strip = cur_dir + '/' completions = [] prepend = '' if abs_match.rfind('/') == 0: # match is in the root directory # This means that we're looking for matches in the root directory # (i.e. abs_match is /foo and the user hit TAB). # So we'll supply the matching board names as possible completions. # Since they're all treated as directories we leave the trailing slash. with DEV_LOCK: if match[0] == '/': completions += [dev.name_path for dev in DEVS if dev.name_path.startswith(abs_match)] else: completions += [dev.name_path[1:] for dev in DEVS if dev.name_path.startswith(abs_match)] if DEFAULT_DEV: # Add root directories of the default device (i.e. /flash/ and /sd/) if match[0] == '/': completions += [root_dir for root_dir in DEFAULT_DEV.root_dirs if root_dir.startswith(match)] else: completions += [root_dir[1:] for root_dir in DEFAULT_DEV.root_dirs if root_dir[1:].startswith(match)] else: # This means that there are at least 2 slashes in abs_match. If one # of them matches a board name then we need to remove the board # name from fixed. Since the results from listdir_matches won't # contain the board name, we need to prepend each of the completions. with DEV_LOCK: for dev in DEVS: if abs_match.startswith(dev.name_path): prepend = dev.name_path[:-1] break paths = sorted(auto(listdir_matches, abs_match)) for path in paths: path = prepend + path if path.startswith(strip): path = path[len(strip):] completions.append(escape(path.replace(fixed, '', 1))) return completions
def _thread_return(cls, minion_instance, opts, data): ''' This method should be used as a threading target, start the actual minion side execution. ''' fn_ = os.path.join(minion_instance.proc_dir, data['jid']) if opts['multiprocessing'] and not salt.utils.platform.is_windows(): # Shutdown the multiprocessing before daemonizing salt.log.setup.shutdown_multiprocessing_logging() salt.utils.process.daemonize_if(opts) # Reconfigure multiprocessing logging after daemonizing salt.log.setup.setup_multiprocessing_logging() salt.utils.process.appendproctitle('{0}._thread_return {1}'.format(cls.__name__, data['jid'])) sdata = {'pid': os.getpid()} sdata.update(data) log.info('Starting a new job %s with PID %s', data['jid'], sdata['pid']) with salt.utils.files.fopen(fn_, 'w+b') as fp_: fp_.write(minion_instance.serial.dumps(sdata)) ret = {'success': False} function_name = data['fun'] executors = data.get('module_executors') or \ getattr(minion_instance, 'module_executors', []) or \ opts.get('module_executors', ['direct_call']) allow_missing_funcs = any([ minion_instance.executors['{0}.allow_missing_func'.format(executor)](function_name) for executor in executors if '{0}.allow_missing_func' in minion_instance.executors ]) if function_name in minion_instance.functions or allow_missing_funcs is True: try: minion_blackout_violation = False if minion_instance.connected and minion_instance.opts['pillar'].get('minion_blackout', False): whitelist = minion_instance.opts['pillar'].get('minion_blackout_whitelist', []) # this minion is blacked out. Only allow saltutil.refresh_pillar and the whitelist if function_name != 'saltutil.refresh_pillar' and function_name not in whitelist: minion_blackout_violation = True # use minion_blackout_whitelist from grains if it exists if minion_instance.opts['grains'].get('minion_blackout', False): whitelist = minion_instance.opts['grains'].get('minion_blackout_whitelist', []) if function_name != 'saltutil.refresh_pillar' and function_name not in whitelist: minion_blackout_violation = True if minion_blackout_violation: raise SaltInvocationError('Minion in blackout mode. Set \'minion_blackout\' ' 'to False in pillar or grains to resume operations. Only ' 'saltutil.refresh_pillar allowed in blackout mode.') if function_name in minion_instance.functions: func = minion_instance.functions[function_name] args, kwargs = load_args_and_kwargs( func, data['arg'], data) else: # only run if function_name is not in minion_instance.functions and allow_missing_funcs is True func = function_name args, kwargs = data['arg'], data minion_instance.functions.pack['__context__']['retcode'] = 0 if isinstance(executors, six.string_types): executors = [executors] elif not isinstance(executors, list) or not executors: raise SaltInvocationError("Wrong executors specification: {0}. String or non-empty list expected". format(executors)) if opts.get('sudo_user', '') and executors[-1] != 'sudo': executors[-1] = 'sudo' # replace the last one with sudo log.trace('Executors list %s', executors) # pylint: disable=no-member for name in executors: fname = '{0}.execute'.format(name) if fname not in minion_instance.executors: raise SaltInvocationError("Executor '{0}' is not available".format(name)) return_data = minion_instance.executors[fname](opts, data, func, args, kwargs) if return_data is not None: break if isinstance(return_data, types.GeneratorType): ind = 0 iret = {} for single in return_data: if isinstance(single, dict) and isinstance(iret, dict): iret.update(single) else: if not iret: iret = [] iret.append(single) tag = tagify([data['jid'], 'prog', opts['id'], six.text_type(ind)], 'job') event_data = {'return': single} minion_instance._fire_master(event_data, tag) ind += 1 ret['return'] = iret else: ret['return'] = return_data retcode = minion_instance.functions.pack['__context__'].get( 'retcode', salt.defaults.exitcodes.EX_OK ) if retcode == salt.defaults.exitcodes.EX_OK: # No nonzero retcode in __context__ dunder. Check if return # is a dictionary with a "result" or "success" key. try: func_result = all(return_data.get(x, True) for x in ('result', 'success')) except Exception: # return data is not a dict func_result = True if not func_result: retcode = salt.defaults.exitcodes.EX_GENERIC ret['retcode'] = retcode ret['success'] = retcode == salt.defaults.exitcodes.EX_OK except CommandNotFoundError as exc: msg = 'Command required for \'{0}\' not found'.format( function_name ) log.debug(msg, exc_info=True) ret['return'] = '{0}: {1}'.format(msg, exc) ret['out'] = 'nested' ret['retcode'] = salt.defaults.exitcodes.EX_GENERIC except CommandExecutionError as exc: log.error( 'A command in \'%s\' had a problem: %s', function_name, exc, exc_info_on_loglevel=logging.DEBUG ) ret['return'] = 'ERROR: {0}'.format(exc) ret['out'] = 'nested' ret['retcode'] = salt.defaults.exitcodes.EX_GENERIC except SaltInvocationError as exc: log.error( 'Problem executing \'%s\': %s', function_name, exc, exc_info_on_loglevel=logging.DEBUG ) ret['return'] = 'ERROR executing \'{0}\': {1}'.format( function_name, exc ) ret['out'] = 'nested' ret['retcode'] = salt.defaults.exitcodes.EX_GENERIC except TypeError as exc: msg = 'Passed invalid arguments to {0}: {1}\n{2}'.format( function_name, exc, func.__doc__ or '' ) log.warning(msg, exc_info_on_loglevel=logging.DEBUG) ret['return'] = msg ret['out'] = 'nested' ret['retcode'] = salt.defaults.exitcodes.EX_GENERIC except Exception: msg = 'The minion function caused an exception' log.warning(msg, exc_info_on_loglevel=True) salt.utils.error.fire_exception(salt.exceptions.MinionError(msg), opts, job=data) ret['return'] = '{0}: {1}'.format(msg, traceback.format_exc()) ret['out'] = 'nested' ret['retcode'] = salt.defaults.exitcodes.EX_GENERIC else: docs = minion_instance.functions['sys.doc']('{0}*'.format(function_name)) if docs: docs[function_name] = minion_instance.functions.missing_fun_string(function_name) ret['return'] = docs else: ret['return'] = minion_instance.functions.missing_fun_string(function_name) mod_name = function_name.split('.')[0] if mod_name in minion_instance.function_errors: ret['return'] += ' Possible reasons: \'{0}\''.format( minion_instance.function_errors[mod_name] ) ret['success'] = False ret['retcode'] = salt.defaults.exitcodes.EX_GENERIC ret['out'] = 'nested' ret['jid'] = data['jid'] ret['fun'] = data['fun'] ret['fun_args'] = data['arg'] if 'master_id' in data: ret['master_id'] = data['master_id'] if 'metadata' in data: if isinstance(data['metadata'], dict): ret['metadata'] = data['metadata'] else: log.warning('The metadata parameter must be a dictionary. Ignoring.') if minion_instance.connected: minion_instance._return_pub( ret, timeout=minion_instance._return_retry_timer() ) # Add default returners from minion config # Should have been coverted to comma-delimited string already if isinstance(opts.get('return'), six.string_types): if data['ret']: data['ret'] = ','.join((data['ret'], opts['return'])) else: data['ret'] = opts['return'] log.debug('minion return: %s', ret) # TODO: make a list? Seems odd to split it this late :/ if data['ret'] and isinstance(data['ret'], six.string_types): if 'ret_config' in data: ret['ret_config'] = data['ret_config'] if 'ret_kwargs' in data: ret['ret_kwargs'] = data['ret_kwargs'] ret['id'] = opts['id'] for returner in set(data['ret'].split(',')): try: returner_str = '{0}.returner'.format(returner) if returner_str in minion_instance.returners: minion_instance.returners[returner_str](ret) else: returner_err = minion_instance.returners.missing_fun_string(returner_str) log.error( 'Returner %s could not be loaded: %s', returner_str, returner_err ) except Exception as exc: log.exception( 'The return failed for job %s: %s', data['jid'], exc )
This method should be used as a threading target, start the actual minion side execution.
Below is the the instruction that describes the task: ### Input: This method should be used as a threading target, start the actual minion side execution. ### Response: def _thread_return(cls, minion_instance, opts, data): ''' This method should be used as a threading target, start the actual minion side execution. ''' fn_ = os.path.join(minion_instance.proc_dir, data['jid']) if opts['multiprocessing'] and not salt.utils.platform.is_windows(): # Shutdown the multiprocessing before daemonizing salt.log.setup.shutdown_multiprocessing_logging() salt.utils.process.daemonize_if(opts) # Reconfigure multiprocessing logging after daemonizing salt.log.setup.setup_multiprocessing_logging() salt.utils.process.appendproctitle('{0}._thread_return {1}'.format(cls.__name__, data['jid'])) sdata = {'pid': os.getpid()} sdata.update(data) log.info('Starting a new job %s with PID %s', data['jid'], sdata['pid']) with salt.utils.files.fopen(fn_, 'w+b') as fp_: fp_.write(minion_instance.serial.dumps(sdata)) ret = {'success': False} function_name = data['fun'] executors = data.get('module_executors') or \ getattr(minion_instance, 'module_executors', []) or \ opts.get('module_executors', ['direct_call']) allow_missing_funcs = any([ minion_instance.executors['{0}.allow_missing_func'.format(executor)](function_name) for executor in executors if '{0}.allow_missing_func' in minion_instance.executors ]) if function_name in minion_instance.functions or allow_missing_funcs is True: try: minion_blackout_violation = False if minion_instance.connected and minion_instance.opts['pillar'].get('minion_blackout', False): whitelist = minion_instance.opts['pillar'].get('minion_blackout_whitelist', []) # this minion is blacked out. Only allow saltutil.refresh_pillar and the whitelist if function_name != 'saltutil.refresh_pillar' and function_name not in whitelist: minion_blackout_violation = True # use minion_blackout_whitelist from grains if it exists if minion_instance.opts['grains'].get('minion_blackout', False): whitelist = minion_instance.opts['grains'].get('minion_blackout_whitelist', []) if function_name != 'saltutil.refresh_pillar' and function_name not in whitelist: minion_blackout_violation = True if minion_blackout_violation: raise SaltInvocationError('Minion in blackout mode. Set \'minion_blackout\' ' 'to False in pillar or grains to resume operations. Only ' 'saltutil.refresh_pillar allowed in blackout mode.') if function_name in minion_instance.functions: func = minion_instance.functions[function_name] args, kwargs = load_args_and_kwargs( func, data['arg'], data) else: # only run if function_name is not in minion_instance.functions and allow_missing_funcs is True func = function_name args, kwargs = data['arg'], data minion_instance.functions.pack['__context__']['retcode'] = 0 if isinstance(executors, six.string_types): executors = [executors] elif not isinstance(executors, list) or not executors: raise SaltInvocationError("Wrong executors specification: {0}. String or non-empty list expected". format(executors)) if opts.get('sudo_user', '') and executors[-1] != 'sudo': executors[-1] = 'sudo' # replace the last one with sudo log.trace('Executors list %s', executors) # pylint: disable=no-member for name in executors: fname = '{0}.execute'.format(name) if fname not in minion_instance.executors: raise SaltInvocationError("Executor '{0}' is not available".format(name)) return_data = minion_instance.executors[fname](opts, data, func, args, kwargs) if return_data is not None: break if isinstance(return_data, types.GeneratorType): ind = 0 iret = {} for single in return_data: if isinstance(single, dict) and isinstance(iret, dict): iret.update(single) else: if not iret: iret = [] iret.append(single) tag = tagify([data['jid'], 'prog', opts['id'], six.text_type(ind)], 'job') event_data = {'return': single} minion_instance._fire_master(event_data, tag) ind += 1 ret['return'] = iret else: ret['return'] = return_data retcode = minion_instance.functions.pack['__context__'].get( 'retcode', salt.defaults.exitcodes.EX_OK ) if retcode == salt.defaults.exitcodes.EX_OK: # No nonzero retcode in __context__ dunder. Check if return # is a dictionary with a "result" or "success" key. try: func_result = all(return_data.get(x, True) for x in ('result', 'success')) except Exception: # return data is not a dict func_result = True if not func_result: retcode = salt.defaults.exitcodes.EX_GENERIC ret['retcode'] = retcode ret['success'] = retcode == salt.defaults.exitcodes.EX_OK except CommandNotFoundError as exc: msg = 'Command required for \'{0}\' not found'.format( function_name ) log.debug(msg, exc_info=True) ret['return'] = '{0}: {1}'.format(msg, exc) ret['out'] = 'nested' ret['retcode'] = salt.defaults.exitcodes.EX_GENERIC except CommandExecutionError as exc: log.error( 'A command in \'%s\' had a problem: %s', function_name, exc, exc_info_on_loglevel=logging.DEBUG ) ret['return'] = 'ERROR: {0}'.format(exc) ret['out'] = 'nested' ret['retcode'] = salt.defaults.exitcodes.EX_GENERIC except SaltInvocationError as exc: log.error( 'Problem executing \'%s\': %s', function_name, exc, exc_info_on_loglevel=logging.DEBUG ) ret['return'] = 'ERROR executing \'{0}\': {1}'.format( function_name, exc ) ret['out'] = 'nested' ret['retcode'] = salt.defaults.exitcodes.EX_GENERIC except TypeError as exc: msg = 'Passed invalid arguments to {0}: {1}\n{2}'.format( function_name, exc, func.__doc__ or '' ) log.warning(msg, exc_info_on_loglevel=logging.DEBUG) ret['return'] = msg ret['out'] = 'nested' ret['retcode'] = salt.defaults.exitcodes.EX_GENERIC except Exception: msg = 'The minion function caused an exception' log.warning(msg, exc_info_on_loglevel=True) salt.utils.error.fire_exception(salt.exceptions.MinionError(msg), opts, job=data) ret['return'] = '{0}: {1}'.format(msg, traceback.format_exc()) ret['out'] = 'nested' ret['retcode'] = salt.defaults.exitcodes.EX_GENERIC else: docs = minion_instance.functions['sys.doc']('{0}*'.format(function_name)) if docs: docs[function_name] = minion_instance.functions.missing_fun_string(function_name) ret['return'] = docs else: ret['return'] = minion_instance.functions.missing_fun_string(function_name) mod_name = function_name.split('.')[0] if mod_name in minion_instance.function_errors: ret['return'] += ' Possible reasons: \'{0}\''.format( minion_instance.function_errors[mod_name] ) ret['success'] = False ret['retcode'] = salt.defaults.exitcodes.EX_GENERIC ret['out'] = 'nested' ret['jid'] = data['jid'] ret['fun'] = data['fun'] ret['fun_args'] = data['arg'] if 'master_id' in data: ret['master_id'] = data['master_id'] if 'metadata' in data: if isinstance(data['metadata'], dict): ret['metadata'] = data['metadata'] else: log.warning('The metadata parameter must be a dictionary. Ignoring.') if minion_instance.connected: minion_instance._return_pub( ret, timeout=minion_instance._return_retry_timer() ) # Add default returners from minion config # Should have been coverted to comma-delimited string already if isinstance(opts.get('return'), six.string_types): if data['ret']: data['ret'] = ','.join((data['ret'], opts['return'])) else: data['ret'] = opts['return'] log.debug('minion return: %s', ret) # TODO: make a list? Seems odd to split it this late :/ if data['ret'] and isinstance(data['ret'], six.string_types): if 'ret_config' in data: ret['ret_config'] = data['ret_config'] if 'ret_kwargs' in data: ret['ret_kwargs'] = data['ret_kwargs'] ret['id'] = opts['id'] for returner in set(data['ret'].split(',')): try: returner_str = '{0}.returner'.format(returner) if returner_str in minion_instance.returners: minion_instance.returners[returner_str](ret) else: returner_err = minion_instance.returners.missing_fun_string(returner_str) log.error( 'Returner %s could not be loaded: %s', returner_str, returner_err ) except Exception as exc: log.exception( 'The return failed for job %s: %s', data['jid'], exc )
def get(self, user_id): """Returns a specific user""" user = db.User.find_one(User.user_id == user_id) roles = db.Role.all() if not user: return self.make_response('Unable to find the user requested, might have been removed', HTTP.NOT_FOUND) return self.make_response({ 'user': user.to_json(), 'roles': roles }, HTTP.OK)
Returns a specific user
Below is the the instruction that describes the task: ### Input: Returns a specific user ### Response: def get(self, user_id): """Returns a specific user""" user = db.User.find_one(User.user_id == user_id) roles = db.Role.all() if not user: return self.make_response('Unable to find the user requested, might have been removed', HTTP.NOT_FOUND) return self.make_response({ 'user': user.to_json(), 'roles': roles }, HTTP.OK)
def words_diff(before_words, after_words): '''Diff the words in two strings. This is intended for use in diffing prose and other forms of text where line breaks have little semantic value. Parameters ---------- before_words : str A string to be used as the baseline version. after_words : str A string to be compared against the baseline. Returns ------- diff_result : A list of dictionaries containing diff information. ''' before_comps = before_words.split() after_comps = after_words.split() diff_result = diff( before_comps, after_comps ) return diff_result
Diff the words in two strings. This is intended for use in diffing prose and other forms of text where line breaks have little semantic value. Parameters ---------- before_words : str A string to be used as the baseline version. after_words : str A string to be compared against the baseline. Returns ------- diff_result : A list of dictionaries containing diff information.
Below is the the instruction that describes the task: ### Input: Diff the words in two strings. This is intended for use in diffing prose and other forms of text where line breaks have little semantic value. Parameters ---------- before_words : str A string to be used as the baseline version. after_words : str A string to be compared against the baseline. Returns ------- diff_result : A list of dictionaries containing diff information. ### Response: def words_diff(before_words, after_words): '''Diff the words in two strings. This is intended for use in diffing prose and other forms of text where line breaks have little semantic value. Parameters ---------- before_words : str A string to be used as the baseline version. after_words : str A string to be compared against the baseline. Returns ------- diff_result : A list of dictionaries containing diff information. ''' before_comps = before_words.split() after_comps = after_words.split() diff_result = diff( before_comps, after_comps ) return diff_result
def fromMarkdown(md, *args, **kwargs): """ Creates abstraction using path to file :param str path: path to markdown file :return: TreeOfContents object """ return TOC.fromHTML(markdown(md, *args, **kwargs))
Creates abstraction using path to file :param str path: path to markdown file :return: TreeOfContents object
Below is the the instruction that describes the task: ### Input: Creates abstraction using path to file :param str path: path to markdown file :return: TreeOfContents object ### Response: def fromMarkdown(md, *args, **kwargs): """ Creates abstraction using path to file :param str path: path to markdown file :return: TreeOfContents object """ return TOC.fromHTML(markdown(md, *args, **kwargs))
def QA_fetch_index_min_adv( code, start, end=None, frequence='1min', if_drop_index=True, collections=DATABASE.index_min): ''' '获取股票分钟线' :param code: :param start: :param end: :param frequence: :param if_drop_index: :param collections: :return: ''' if frequence in ['1min', '1m']: frequence = '1min' elif frequence in ['5min', '5m']: frequence = '5min' elif frequence in ['15min', '15m']: frequence = '15min' elif frequence in ['30min', '30m']: frequence = '30min' elif frequence in ['60min', '60m']: frequence = '60min' # __data = [] 没有使用 end = start if end is None else end if len(start) == 10: start = '{} 09:30:00'.format(start) if len(end) == 10: end = '{} 15:00:00'.format(end) # 🛠 todo 报告错误 如果开始时间 在 结束时间之后 # if start == end: # 🛠 todo 如果相等,根据 frequence 获取开始时间的 时间段 QA_fetch_index_min_adv, 不支持start end是相等的 #print("QA Error QA_fetch_index_min_adv parameter code=%s , start=%s, end=%s is equal, should have time span! " % (code, start, end)) # return None res = QA_fetch_index_min( code, start, end, format='pd', frequence=frequence) if res is None: print("QA Error QA_fetch_index_min_adv parameter code=%s start=%s end=%s frequence=%s call QA_fetch_index_min return None" % ( code, start, end, frequence)) else: res_reset_index = res.set_index( ['datetime', 'code'], drop=if_drop_index) # if res_reset_index is None: # print("QA Error QA_fetch_index_min_adv set index 'date, code' return None") return QA_DataStruct_Index_min(res_reset_index)
'获取股票分钟线' :param code: :param start: :param end: :param frequence: :param if_drop_index: :param collections: :return:
Below is the the instruction that describes the task: ### Input: '获取股票分钟线' :param code: :param start: :param end: :param frequence: :param if_drop_index: :param collections: :return: ### Response: def QA_fetch_index_min_adv( code, start, end=None, frequence='1min', if_drop_index=True, collections=DATABASE.index_min): ''' '获取股票分钟线' :param code: :param start: :param end: :param frequence: :param if_drop_index: :param collections: :return: ''' if frequence in ['1min', '1m']: frequence = '1min' elif frequence in ['5min', '5m']: frequence = '5min' elif frequence in ['15min', '15m']: frequence = '15min' elif frequence in ['30min', '30m']: frequence = '30min' elif frequence in ['60min', '60m']: frequence = '60min' # __data = [] 没有使用 end = start if end is None else end if len(start) == 10: start = '{} 09:30:00'.format(start) if len(end) == 10: end = '{} 15:00:00'.format(end) # 🛠 todo 报告错误 如果开始时间 在 结束时间之后 # if start == end: # 🛠 todo 如果相等,根据 frequence 获取开始时间的 时间段 QA_fetch_index_min_adv, 不支持start end是相等的 #print("QA Error QA_fetch_index_min_adv parameter code=%s , start=%s, end=%s is equal, should have time span! " % (code, start, end)) # return None res = QA_fetch_index_min( code, start, end, format='pd', frequence=frequence) if res is None: print("QA Error QA_fetch_index_min_adv parameter code=%s start=%s end=%s frequence=%s call QA_fetch_index_min return None" % ( code, start, end, frequence)) else: res_reset_index = res.set_index( ['datetime', 'code'], drop=if_drop_index) # if res_reset_index is None: # print("QA Error QA_fetch_index_min_adv set index 'date, code' return None") return QA_DataStruct_Index_min(res_reset_index)
def tags(self): '''Display tag information for all samples in database''' tags = self.workbench.get_all_tags() if not tags: return tag_df = pd.DataFrame(tags) tag_df = self.vectorize(tag_df, 'tags') print '\n%sSamples in Database%s' % (color.LightPurple, color.Normal) self.top_corr(tag_df)
Display tag information for all samples in database
Below is the the instruction that describes the task: ### Input: Display tag information for all samples in database ### Response: def tags(self): '''Display tag information for all samples in database''' tags = self.workbench.get_all_tags() if not tags: return tag_df = pd.DataFrame(tags) tag_df = self.vectorize(tag_df, 'tags') print '\n%sSamples in Database%s' % (color.LightPurple, color.Normal) self.top_corr(tag_df)
def get_context_data(self, **kwargs): """Adds the ``tab_group`` variable to the context data.""" context = super(TabView, self).get_context_data(**kwargs) try: tab_group = self.get_tabs(self.request, **kwargs) context["tab_group"] = tab_group # Make sure our data is pre-loaded to capture errors. context["tab_group"].load_tab_data() except Exception: exceptions.handle(self.request) return context
Adds the ``tab_group`` variable to the context data.
Below is the the instruction that describes the task: ### Input: Adds the ``tab_group`` variable to the context data. ### Response: def get_context_data(self, **kwargs): """Adds the ``tab_group`` variable to the context data.""" context = super(TabView, self).get_context_data(**kwargs) try: tab_group = self.get_tabs(self.request, **kwargs) context["tab_group"] = tab_group # Make sure our data is pre-loaded to capture errors. context["tab_group"].load_tab_data() except Exception: exceptions.handle(self.request) return context
def set_revision_limit(self, limit): """ Sets the limit of historical revisions to store for any single document in the current remote database. :param int limit: Number of revisions to store for any single document in the current remote database. :returns: Revision limit set operation status in JSON format """ url = '/'.join((self.database_url, '_revs_limit')) resp = self.r_session.put(url, data=json.dumps(limit, cls=self.client.encoder)) resp.raise_for_status() return response_to_json_dict(resp)
Sets the limit of historical revisions to store for any single document in the current remote database. :param int limit: Number of revisions to store for any single document in the current remote database. :returns: Revision limit set operation status in JSON format
Below is the the instruction that describes the task: ### Input: Sets the limit of historical revisions to store for any single document in the current remote database. :param int limit: Number of revisions to store for any single document in the current remote database. :returns: Revision limit set operation status in JSON format ### Response: def set_revision_limit(self, limit): """ Sets the limit of historical revisions to store for any single document in the current remote database. :param int limit: Number of revisions to store for any single document in the current remote database. :returns: Revision limit set operation status in JSON format """ url = '/'.join((self.database_url, '_revs_limit')) resp = self.r_session.put(url, data=json.dumps(limit, cls=self.client.encoder)) resp.raise_for_status() return response_to_json_dict(resp)
def update(cls, customer_id, **kwargs): """ Static method defined to update paystack customer data by id. Args: customer_id: paystack customer id. first_name: customer's first name(optional). last_name: customer's last name(optional). email: customer's email address(optional). phone:customer's phone number(optional). Returns: Json data from paystack API. """ return cls().requests.put('customer/{customer_id}'.format(**locals()), data=kwargs)
Static method defined to update paystack customer data by id. Args: customer_id: paystack customer id. first_name: customer's first name(optional). last_name: customer's last name(optional). email: customer's email address(optional). phone:customer's phone number(optional). Returns: Json data from paystack API.
Below is the the instruction that describes the task: ### Input: Static method defined to update paystack customer data by id. Args: customer_id: paystack customer id. first_name: customer's first name(optional). last_name: customer's last name(optional). email: customer's email address(optional). phone:customer's phone number(optional). Returns: Json data from paystack API. ### Response: def update(cls, customer_id, **kwargs): """ Static method defined to update paystack customer data by id. Args: customer_id: paystack customer id. first_name: customer's first name(optional). last_name: customer's last name(optional). email: customer's email address(optional). phone:customer's phone number(optional). Returns: Json data from paystack API. """ return cls().requests.put('customer/{customer_id}'.format(**locals()), data=kwargs)
def add_single(self, hostname, ports, nickname=None, **kws): ''' Explicitly add a single entry. Hostname is a FQDN and ports is either a single int (assumed to be TCP port) or Electrum protocol/port number specification with spaces in between. ''' nickname = nickname or hostname self[hostname.lower()] = ServerInfo(nickname, hostname, ports, **kws)
Explicitly add a single entry. Hostname is a FQDN and ports is either a single int (assumed to be TCP port) or Electrum protocol/port number specification with spaces in between.
Below is the the instruction that describes the task: ### Input: Explicitly add a single entry. Hostname is a FQDN and ports is either a single int (assumed to be TCP port) or Electrum protocol/port number specification with spaces in between. ### Response: def add_single(self, hostname, ports, nickname=None, **kws): ''' Explicitly add a single entry. Hostname is a FQDN and ports is either a single int (assumed to be TCP port) or Electrum protocol/port number specification with spaces in between. ''' nickname = nickname or hostname self[hostname.lower()] = ServerInfo(nickname, hostname, ports, **kws)
def putcell(self, columnname, rownr, value): """Put a value into one or more table cells. The columnname and (0-relative) rownrs indicate the table cells. rownr can be a single row number or a sequence of row numbers. If multiple rownrs are given, the given value is put in all those rows. The given value has to be convertible to the data type of the column. If the column contains scalar values, the given value must be a scalar. The value for a column holding arrays can be given as: - a scalar resulting in a 1-dim array of 1 element - a sequence (list, tuple) resulting in a 1-dim array - a numpy array of any dimensionality Note that the arrays in a column may have a fixed dimensionality or shape. In that case the dimensionality or shape of the array to put has to conform. """ self._putcell(columnname, rownr, value)
Put a value into one or more table cells. The columnname and (0-relative) rownrs indicate the table cells. rownr can be a single row number or a sequence of row numbers. If multiple rownrs are given, the given value is put in all those rows. The given value has to be convertible to the data type of the column. If the column contains scalar values, the given value must be a scalar. The value for a column holding arrays can be given as: - a scalar resulting in a 1-dim array of 1 element - a sequence (list, tuple) resulting in a 1-dim array - a numpy array of any dimensionality Note that the arrays in a column may have a fixed dimensionality or shape. In that case the dimensionality or shape of the array to put has to conform.
Below is the the instruction that describes the task: ### Input: Put a value into one or more table cells. The columnname and (0-relative) rownrs indicate the table cells. rownr can be a single row number or a sequence of row numbers. If multiple rownrs are given, the given value is put in all those rows. The given value has to be convertible to the data type of the column. If the column contains scalar values, the given value must be a scalar. The value for a column holding arrays can be given as: - a scalar resulting in a 1-dim array of 1 element - a sequence (list, tuple) resulting in a 1-dim array - a numpy array of any dimensionality Note that the arrays in a column may have a fixed dimensionality or shape. In that case the dimensionality or shape of the array to put has to conform. ### Response: def putcell(self, columnname, rownr, value): """Put a value into one or more table cells. The columnname and (0-relative) rownrs indicate the table cells. rownr can be a single row number or a sequence of row numbers. If multiple rownrs are given, the given value is put in all those rows. The given value has to be convertible to the data type of the column. If the column contains scalar values, the given value must be a scalar. The value for a column holding arrays can be given as: - a scalar resulting in a 1-dim array of 1 element - a sequence (list, tuple) resulting in a 1-dim array - a numpy array of any dimensionality Note that the arrays in a column may have a fixed dimensionality or shape. In that case the dimensionality or shape of the array to put has to conform. """ self._putcell(columnname, rownr, value)
def get_answer(message, answers='Yn', default='Y', quit=''): """ Get an answer from stdin, the answers should be 'Y/n' etc. If you don't want the user can quit in the loop, then quit should be None. """ if quit and quit not in answers: answers = answers + quit message = message + '(' + '/'.join(answers) + ')[' + default + ']:' ans = raw_input(message).strip().upper() if default and not ans: ans = default.upper() while ans not in answers.upper(): ans = raw_input(message).strip().upper() if quit and ans == quit.upper(): print "Command be cancelled!" sys.exit(0) return ans
Get an answer from stdin, the answers should be 'Y/n' etc. If you don't want the user can quit in the loop, then quit should be None.
Below is the the instruction that describes the task: ### Input: Get an answer from stdin, the answers should be 'Y/n' etc. If you don't want the user can quit in the loop, then quit should be None. ### Response: def get_answer(message, answers='Yn', default='Y', quit=''): """ Get an answer from stdin, the answers should be 'Y/n' etc. If you don't want the user can quit in the loop, then quit should be None. """ if quit and quit not in answers: answers = answers + quit message = message + '(' + '/'.join(answers) + ')[' + default + ']:' ans = raw_input(message).strip().upper() if default and not ans: ans = default.upper() while ans not in answers.upper(): ans = raw_input(message).strip().upper() if quit and ans == quit.upper(): print "Command be cancelled!" sys.exit(0) return ans
def spiceFoundExceptionThrower(f): """ Decorator for wrapping functions that use status codes """ @functools.wraps(f) def wrapper(*args, **kwargs): res = f(*args, **kwargs) if config.catch_false_founds: found = res[-1] if isinstance(found, bool) and not found: raise stypes.SpiceyError("Spice returns not found for function: {}".format(f.__name__), found=found) elif hasattr(found, '__iter__') and not all(found): raise stypes.SpiceyError("Spice returns not found in a series of calls for function: {}".format(f.__name__), found=found) else: actualres = res[0:-1] if len(actualres) == 1: return actualres[0] else: return actualres else: return res return wrapper
Decorator for wrapping functions that use status codes
Below is the the instruction that describes the task: ### Input: Decorator for wrapping functions that use status codes ### Response: def spiceFoundExceptionThrower(f): """ Decorator for wrapping functions that use status codes """ @functools.wraps(f) def wrapper(*args, **kwargs): res = f(*args, **kwargs) if config.catch_false_founds: found = res[-1] if isinstance(found, bool) and not found: raise stypes.SpiceyError("Spice returns not found for function: {}".format(f.__name__), found=found) elif hasattr(found, '__iter__') and not all(found): raise stypes.SpiceyError("Spice returns not found in a series of calls for function: {}".format(f.__name__), found=found) else: actualres = res[0:-1] if len(actualres) == 1: return actualres[0] else: return actualres else: return res return wrapper
def GetStatus(self): """Requests and waits for status. Returns: status dictionary. """ # status packet format STATUS_FORMAT = ">BBBhhhHhhhHBBBxBbHBHHHHBbbHHBBBbbbbbbbbbBH" STATUS_FIELDS = [ "packetType", "firmwareVersion", "protocolVersion", "mainFineCurrent", "usbFineCurrent", "auxFineCurrent", "voltage1", "mainCoarseCurrent", "usbCoarseCurrent", "auxCoarseCurrent", "voltage2", "outputVoltageSetting", "temperature", "status", "leds", "mainFineResistor", "serialNumber", "sampleRate", "dacCalLow", "dacCalHigh", "powerUpCurrentLimit", "runTimeCurrentLimit", "powerUpTime", "usbFineResistor", "auxFineResistor", "initialUsbVoltage", "initialAuxVoltage", "hardwareRevision", "temperatureLimit", "usbPassthroughMode", "mainCoarseResistor", "usbCoarseResistor", "auxCoarseResistor", "defMainFineResistor", "defUsbFineResistor", "defAuxFineResistor", "defMainCoarseResistor", "defUsbCoarseResistor", "defAuxCoarseResistor", "eventCode", "eventData", ] self._SendStruct("BBB", 0x01, 0x00, 0x00) while 1: # Keep reading, discarding non-status packets read_bytes = self._ReadPacket() if not read_bytes: return None calsize = struct.calcsize(STATUS_FORMAT) if len(read_bytes) != calsize or read_bytes[0] != 0x10: logging.warning("Wanted status, dropped type=0x%02x, len=%d", read_bytes[0], len(read_bytes)) continue status = dict( zip(STATUS_FIELDS, struct.unpack(STATUS_FORMAT, read_bytes))) p_type = status["packetType"] if p_type != 0x10: raise MonsoonError("Package type %s is not 0x10." % p_type) for k in status.keys(): if k.endswith("VoltageSetting"): status[k] = 2.0 + status[k] * 0.01 elif k.endswith("FineCurrent"): pass # needs calibration data elif k.endswith("CoarseCurrent"): pass # needs calibration data elif k.startswith("voltage") or k.endswith("Voltage"): status[k] = status[k] * 0.000125 elif k.endswith("Resistor"): status[k] = 0.05 + status[k] * 0.0001 if k.startswith("aux") or k.startswith("defAux"): status[k] += 0.05 elif k.endswith("CurrentLimit"): status[k] = 8 * (1023 - status[k]) / 1023.0 return status
Requests and waits for status. Returns: status dictionary.
Below is the the instruction that describes the task: ### Input: Requests and waits for status. Returns: status dictionary. ### Response: def GetStatus(self): """Requests and waits for status. Returns: status dictionary. """ # status packet format STATUS_FORMAT = ">BBBhhhHhhhHBBBxBbHBHHHHBbbHHBBBbbbbbbbbbBH" STATUS_FIELDS = [ "packetType", "firmwareVersion", "protocolVersion", "mainFineCurrent", "usbFineCurrent", "auxFineCurrent", "voltage1", "mainCoarseCurrent", "usbCoarseCurrent", "auxCoarseCurrent", "voltage2", "outputVoltageSetting", "temperature", "status", "leds", "mainFineResistor", "serialNumber", "sampleRate", "dacCalLow", "dacCalHigh", "powerUpCurrentLimit", "runTimeCurrentLimit", "powerUpTime", "usbFineResistor", "auxFineResistor", "initialUsbVoltage", "initialAuxVoltage", "hardwareRevision", "temperatureLimit", "usbPassthroughMode", "mainCoarseResistor", "usbCoarseResistor", "auxCoarseResistor", "defMainFineResistor", "defUsbFineResistor", "defAuxFineResistor", "defMainCoarseResistor", "defUsbCoarseResistor", "defAuxCoarseResistor", "eventCode", "eventData", ] self._SendStruct("BBB", 0x01, 0x00, 0x00) while 1: # Keep reading, discarding non-status packets read_bytes = self._ReadPacket() if not read_bytes: return None calsize = struct.calcsize(STATUS_FORMAT) if len(read_bytes) != calsize or read_bytes[0] != 0x10: logging.warning("Wanted status, dropped type=0x%02x, len=%d", read_bytes[0], len(read_bytes)) continue status = dict( zip(STATUS_FIELDS, struct.unpack(STATUS_FORMAT, read_bytes))) p_type = status["packetType"] if p_type != 0x10: raise MonsoonError("Package type %s is not 0x10." % p_type) for k in status.keys(): if k.endswith("VoltageSetting"): status[k] = 2.0 + status[k] * 0.01 elif k.endswith("FineCurrent"): pass # needs calibration data elif k.endswith("CoarseCurrent"): pass # needs calibration data elif k.startswith("voltage") or k.endswith("Voltage"): status[k] = status[k] * 0.000125 elif k.endswith("Resistor"): status[k] = 0.05 + status[k] * 0.0001 if k.startswith("aux") or k.startswith("defAux"): status[k] += 0.05 elif k.endswith("CurrentLimit"): status[k] = 8 * (1023 - status[k]) / 1023.0 return status
def render_node(_node_id, value=None, noderequest={}, **kw): "Recursively render a node's value" if value == None: kw.update( noderequest ) results = _query(_node_id, **kw) current_app.logger.debug("results: %s", results) if results: values = [] for (result, cols) in results: if set(cols) == set(['node_id', 'name', 'value']): for subresult in result: #if subresult.get('name') == kw.get('name'): # This is a link node current_app.logger.debug("sub: %s", subresult) name = subresult['name'] if noderequest.get('_no_template'): # For debugging or just simply viewing with the # operate script we append the node_id to the name # of each. This doesn't work with templates. name = "{0} ({1})".format(name, subresult['node_id']) values.append( {name: render_node( subresult['node_id'], noderequest=noderequest, **subresult )} ) #elif 'node_id' and 'name' in cols: # for subresult in result: # current_app.logger.debug("sub2: %s", subresult) # values.append( {subresult.get('name'): render_node( subresult.get('node_id'), **subresult )} ) else: values.append( result ) value = values value = _short_circuit(value) if not noderequest.get('_no_template'): value = _template(_node_id, value) return value
Recursively render a node's value
Below is the the instruction that describes the task: ### Input: Recursively render a node's value ### Response: def render_node(_node_id, value=None, noderequest={}, **kw): "Recursively render a node's value" if value == None: kw.update( noderequest ) results = _query(_node_id, **kw) current_app.logger.debug("results: %s", results) if results: values = [] for (result, cols) in results: if set(cols) == set(['node_id', 'name', 'value']): for subresult in result: #if subresult.get('name') == kw.get('name'): # This is a link node current_app.logger.debug("sub: %s", subresult) name = subresult['name'] if noderequest.get('_no_template'): # For debugging or just simply viewing with the # operate script we append the node_id to the name # of each. This doesn't work with templates. name = "{0} ({1})".format(name, subresult['node_id']) values.append( {name: render_node( subresult['node_id'], noderequest=noderequest, **subresult )} ) #elif 'node_id' and 'name' in cols: # for subresult in result: # current_app.logger.debug("sub2: %s", subresult) # values.append( {subresult.get('name'): render_node( subresult.get('node_id'), **subresult )} ) else: values.append( result ) value = values value = _short_circuit(value) if not noderequest.get('_no_template'): value = _template(_node_id, value) return value
def extract_signature(sql): """ Extracts a minimal signature from a given SQL query :param sql: the SQL statement :return: a string representing the signature """ sql = force_text(sql) sql = sql.strip() first_space = sql.find(" ") if first_space < 0: return sql second_space = sql.find(" ", first_space + 1) sql_type = sql[0:first_space].upper() if sql_type in ["INSERT", "DELETE"]: keyword = "INTO" if sql_type == "INSERT" else "FROM" sql_type = sql_type + " " + keyword table_name = look_for_table(sql, keyword) elif sql_type in ["CREATE", "DROP"]: # 2nd word is part of SQL type sql_type = sql_type + sql[first_space:second_space] table_name = "" elif sql_type == "UPDATE": table_name = look_for_table(sql, "UPDATE") elif sql_type == "SELECT": # Name is first table try: sql_type = "SELECT FROM" table_name = look_for_table(sql, "FROM") except Exception: table_name = "" else: # No name table_name = "" signature = " ".join(filter(bool, [sql_type, table_name])) return signature
Extracts a minimal signature from a given SQL query :param sql: the SQL statement :return: a string representing the signature
Below is the the instruction that describes the task: ### Input: Extracts a minimal signature from a given SQL query :param sql: the SQL statement :return: a string representing the signature ### Response: def extract_signature(sql): """ Extracts a minimal signature from a given SQL query :param sql: the SQL statement :return: a string representing the signature """ sql = force_text(sql) sql = sql.strip() first_space = sql.find(" ") if first_space < 0: return sql second_space = sql.find(" ", first_space + 1) sql_type = sql[0:first_space].upper() if sql_type in ["INSERT", "DELETE"]: keyword = "INTO" if sql_type == "INSERT" else "FROM" sql_type = sql_type + " " + keyword table_name = look_for_table(sql, keyword) elif sql_type in ["CREATE", "DROP"]: # 2nd word is part of SQL type sql_type = sql_type + sql[first_space:second_space] table_name = "" elif sql_type == "UPDATE": table_name = look_for_table(sql, "UPDATE") elif sql_type == "SELECT": # Name is first table try: sql_type = "SELECT FROM" table_name = look_for_table(sql, "FROM") except Exception: table_name = "" else: # No name table_name = "" signature = " ".join(filter(bool, [sql_type, table_name])) return signature
def mac_address(value, allow_empty = False, **kwargs): """Validate that ``value`` is a valid MAC address. :param value: The value to validate. :type value: :class:`str <python:str>` / :obj:`None <python:None>` :param allow_empty: If ``True``, returns :obj:`None <python:None>` if ``value`` is empty. If ``False``, raises a :class:`EmptyValueError <validator_collection.errors.EmptyValueError>` if ``value`` is empty. Defaults to ``False``. :type allow_empty: :class:`bool <python:bool>` :returns: ``value`` / :obj:`None <python:None>` :rtype: :class:`str <python:str>` / :obj:`None <python:None>` :raises EmptyValueError: if ``value`` is empty and ``allow_empty`` is ``False`` :raises CannotCoerceError: if ``value`` is not a valid :class:`str <python:str>` or string-like object :raises InvalidMACAddressError: if ``value`` is not a valid MAC address or empty with ``allow_empty`` set to ``True`` """ if not value and not allow_empty: raise errors.EmptyValueError('value (%s) was empty' % value) elif not value: return None if not isinstance(value, basestring): raise errors.CannotCoerceError('value must be a valid string, ' 'was %s' % type(value)) if '-' in value: value = value.replace('-', ':') value = value.lower().strip() is_valid = MAC_ADDRESS_REGEX.match(value) if not is_valid: raise errors.InvalidMACAddressError('value (%s) is not a valid MAC ' 'address' % value) return value
Validate that ``value`` is a valid MAC address. :param value: The value to validate. :type value: :class:`str <python:str>` / :obj:`None <python:None>` :param allow_empty: If ``True``, returns :obj:`None <python:None>` if ``value`` is empty. If ``False``, raises a :class:`EmptyValueError <validator_collection.errors.EmptyValueError>` if ``value`` is empty. Defaults to ``False``. :type allow_empty: :class:`bool <python:bool>` :returns: ``value`` / :obj:`None <python:None>` :rtype: :class:`str <python:str>` / :obj:`None <python:None>` :raises EmptyValueError: if ``value`` is empty and ``allow_empty`` is ``False`` :raises CannotCoerceError: if ``value`` is not a valid :class:`str <python:str>` or string-like object :raises InvalidMACAddressError: if ``value`` is not a valid MAC address or empty with ``allow_empty`` set to ``True``
Below is the the instruction that describes the task: ### Input: Validate that ``value`` is a valid MAC address. :param value: The value to validate. :type value: :class:`str <python:str>` / :obj:`None <python:None>` :param allow_empty: If ``True``, returns :obj:`None <python:None>` if ``value`` is empty. If ``False``, raises a :class:`EmptyValueError <validator_collection.errors.EmptyValueError>` if ``value`` is empty. Defaults to ``False``. :type allow_empty: :class:`bool <python:bool>` :returns: ``value`` / :obj:`None <python:None>` :rtype: :class:`str <python:str>` / :obj:`None <python:None>` :raises EmptyValueError: if ``value`` is empty and ``allow_empty`` is ``False`` :raises CannotCoerceError: if ``value`` is not a valid :class:`str <python:str>` or string-like object :raises InvalidMACAddressError: if ``value`` is not a valid MAC address or empty with ``allow_empty`` set to ``True`` ### Response: def mac_address(value, allow_empty = False, **kwargs): """Validate that ``value`` is a valid MAC address. :param value: The value to validate. :type value: :class:`str <python:str>` / :obj:`None <python:None>` :param allow_empty: If ``True``, returns :obj:`None <python:None>` if ``value`` is empty. If ``False``, raises a :class:`EmptyValueError <validator_collection.errors.EmptyValueError>` if ``value`` is empty. Defaults to ``False``. :type allow_empty: :class:`bool <python:bool>` :returns: ``value`` / :obj:`None <python:None>` :rtype: :class:`str <python:str>` / :obj:`None <python:None>` :raises EmptyValueError: if ``value`` is empty and ``allow_empty`` is ``False`` :raises CannotCoerceError: if ``value`` is not a valid :class:`str <python:str>` or string-like object :raises InvalidMACAddressError: if ``value`` is not a valid MAC address or empty with ``allow_empty`` set to ``True`` """ if not value and not allow_empty: raise errors.EmptyValueError('value (%s) was empty' % value) elif not value: return None if not isinstance(value, basestring): raise errors.CannotCoerceError('value must be a valid string, ' 'was %s' % type(value)) if '-' in value: value = value.replace('-', ':') value = value.lower().strip() is_valid = MAC_ADDRESS_REGEX.match(value) if not is_valid: raise errors.InvalidMACAddressError('value (%s) is not a valid MAC ' 'address' % value) return value
def max(self, expr, extra_constraints=(), solver=None, model_callback=None): """ Return the maximum value of expr. :param expr: expression (an AST) to evaluate :param solver: a solver object, native to the backend, to assist in the evaluation (for example, a z3.Solver) :param extra_constraints: extra constraints (as ASTs) to add to the solver for this solve :param model_callback: a function that will be executed with recovered models (if any) :return: the maximum possible value of expr (backend object) """ if self._solver_required and solver is None: raise BackendError("%s requires a solver for evaluation" % self.__class__.__name__) return self._max(self.convert(expr), extra_constraints=self.convert_list(extra_constraints), solver=solver, model_callback=model_callback)
Return the maximum value of expr. :param expr: expression (an AST) to evaluate :param solver: a solver object, native to the backend, to assist in the evaluation (for example, a z3.Solver) :param extra_constraints: extra constraints (as ASTs) to add to the solver for this solve :param model_callback: a function that will be executed with recovered models (if any) :return: the maximum possible value of expr (backend object)
Below is the the instruction that describes the task: ### Input: Return the maximum value of expr. :param expr: expression (an AST) to evaluate :param solver: a solver object, native to the backend, to assist in the evaluation (for example, a z3.Solver) :param extra_constraints: extra constraints (as ASTs) to add to the solver for this solve :param model_callback: a function that will be executed with recovered models (if any) :return: the maximum possible value of expr (backend object) ### Response: def max(self, expr, extra_constraints=(), solver=None, model_callback=None): """ Return the maximum value of expr. :param expr: expression (an AST) to evaluate :param solver: a solver object, native to the backend, to assist in the evaluation (for example, a z3.Solver) :param extra_constraints: extra constraints (as ASTs) to add to the solver for this solve :param model_callback: a function that will be executed with recovered models (if any) :return: the maximum possible value of expr (backend object) """ if self._solver_required and solver is None: raise BackendError("%s requires a solver for evaluation" % self.__class__.__name__) return self._max(self.convert(expr), extra_constraints=self.convert_list(extra_constraints), solver=solver, model_callback=model_callback)
def do_pdef(self, arg): """The debugger interface to magic_pdef""" namespaces = [('Locals', self.curframe.f_locals), ('Globals', self.curframe.f_globals)] self.shell.find_line_magic('pdef')(arg, namespaces=namespaces)
The debugger interface to magic_pdef
Below is the the instruction that describes the task: ### Input: The debugger interface to magic_pdef ### Response: def do_pdef(self, arg): """The debugger interface to magic_pdef""" namespaces = [('Locals', self.curframe.f_locals), ('Globals', self.curframe.f_globals)] self.shell.find_line_magic('pdef')(arg, namespaces=namespaces)
def to_serializable(self, use_bytes=False, bias_dtype=np.float32, bytes_type=bytes): """Convert the binary quadratic model to a serializable object. Args: use_bytes (bool, optional, default=False): If True, a compact representation representing the biases as bytes is used. bias_dtype (numpy.dtype, optional, default=numpy.float32): If `use_bytes` is True, this numpy dtype will be used to represent the bias values in the serialized format. bytes_type (class, optional, default=bytes): This class will be used to wrap the bytes objects in the serialization if `use_bytes` is true. Useful for when using Python 2 and using BSON encoding, which will not accept the raw `bytes` type, so `bson.Binary` can be used instead. Returns: dict: An object that can be serialized. Examples: Encode using JSON >>> import dimod >>> import json ... >>> bqm = dimod.BinaryQuadraticModel({'a': -1.0, 'b': 1.0}, {('a', 'b'): -1.0}, 0.0, dimod.SPIN) >>> s = json.dumps(bqm.to_serializable()) Encode using BSON_ in python 3.5+ >>> import dimod >>> import bson ... >>> bqm = dimod.BinaryQuadraticModel({'a': -1.0, 'b': 1.0}, {('a', 'b'): -1.0}, 0.0, dimod.SPIN) >>> doc = bqm.to_serializable(use_bytes=True) >>> b = bson.BSON.encode(doc) # doctest: +SKIP Encode using BSON in python 2.7. Because :class:`bytes` is an alias for :class:`str`, we need to signal to the encoder that it should encode the biases and labels as binary data. >>> import dimod >>> import bson ... >>> bqm = dimod.BinaryQuadraticModel({'a': -1.0, 'b': 1.0}, {('a', 'b'): -1.0}, 0.0, dimod.SPIN) >>> doc = bqm.to_serializable(use_bytes=True, bytes_type=bson.Binary) >>> b = bson.BSON.encode(doc) # doctest: +SKIP See also: :meth:`~.BinaryQuadraticModel.from_serializable` :func:`json.dumps`, :func:`json.dump` JSON encoding functions :meth:`bson.BSON.encode` BSON encoding method .. _BSON: http://bsonspec.org/ """ from dimod.package_info import __version__ schema_version = "2.0.0" try: variables = sorted(self.variables) except TypeError: # sorting unlike types in py3 variables = list(self.variables) num_variables = len(variables) # when doing byte encoding we can use less space depending on the # total number of variables index_dtype = np.uint16 if num_variables <= 2**16 else np.uint32 ldata, (irow, icol, qdata), offset = self.to_numpy_vectors( dtype=bias_dtype, index_dtype=index_dtype, sort_indices=True, variable_order=variables) doc = {"basetype": "BinaryQuadraticModel", "type": type(self).__name__, "version": {"dimod": __version__, "bqm_schema": schema_version}, "variable_labels": variables, "variable_type": self.vartype.name, "info": self.info, "offset": float(offset), "use_bytes": bool(use_bytes) } if use_bytes: doc.update({'linear_biases': array2bytes(ldata, bytes_type=bytes_type), 'quadratic_biases': array2bytes(qdata, bytes_type=bytes_type), 'quadratic_head': array2bytes(irow, bytes_type=bytes_type), 'quadratic_tail': array2bytes(icol, bytes_type=bytes_type)}) else: doc.update({'linear_biases': ldata.tolist(), 'quadratic_biases': qdata.tolist(), 'quadratic_head': irow.tolist(), 'quadratic_tail': icol.tolist()}) return doc
Convert the binary quadratic model to a serializable object. Args: use_bytes (bool, optional, default=False): If True, a compact representation representing the biases as bytes is used. bias_dtype (numpy.dtype, optional, default=numpy.float32): If `use_bytes` is True, this numpy dtype will be used to represent the bias values in the serialized format. bytes_type (class, optional, default=bytes): This class will be used to wrap the bytes objects in the serialization if `use_bytes` is true. Useful for when using Python 2 and using BSON encoding, which will not accept the raw `bytes` type, so `bson.Binary` can be used instead. Returns: dict: An object that can be serialized. Examples: Encode using JSON >>> import dimod >>> import json ... >>> bqm = dimod.BinaryQuadraticModel({'a': -1.0, 'b': 1.0}, {('a', 'b'): -1.0}, 0.0, dimod.SPIN) >>> s = json.dumps(bqm.to_serializable()) Encode using BSON_ in python 3.5+ >>> import dimod >>> import bson ... >>> bqm = dimod.BinaryQuadraticModel({'a': -1.0, 'b': 1.0}, {('a', 'b'): -1.0}, 0.0, dimod.SPIN) >>> doc = bqm.to_serializable(use_bytes=True) >>> b = bson.BSON.encode(doc) # doctest: +SKIP Encode using BSON in python 2.7. Because :class:`bytes` is an alias for :class:`str`, we need to signal to the encoder that it should encode the biases and labels as binary data. >>> import dimod >>> import bson ... >>> bqm = dimod.BinaryQuadraticModel({'a': -1.0, 'b': 1.0}, {('a', 'b'): -1.0}, 0.0, dimod.SPIN) >>> doc = bqm.to_serializable(use_bytes=True, bytes_type=bson.Binary) >>> b = bson.BSON.encode(doc) # doctest: +SKIP See also: :meth:`~.BinaryQuadraticModel.from_serializable` :func:`json.dumps`, :func:`json.dump` JSON encoding functions :meth:`bson.BSON.encode` BSON encoding method .. _BSON: http://bsonspec.org/
Below is the the instruction that describes the task: ### Input: Convert the binary quadratic model to a serializable object. Args: use_bytes (bool, optional, default=False): If True, a compact representation representing the biases as bytes is used. bias_dtype (numpy.dtype, optional, default=numpy.float32): If `use_bytes` is True, this numpy dtype will be used to represent the bias values in the serialized format. bytes_type (class, optional, default=bytes): This class will be used to wrap the bytes objects in the serialization if `use_bytes` is true. Useful for when using Python 2 and using BSON encoding, which will not accept the raw `bytes` type, so `bson.Binary` can be used instead. Returns: dict: An object that can be serialized. Examples: Encode using JSON >>> import dimod >>> import json ... >>> bqm = dimod.BinaryQuadraticModel({'a': -1.0, 'b': 1.0}, {('a', 'b'): -1.0}, 0.0, dimod.SPIN) >>> s = json.dumps(bqm.to_serializable()) Encode using BSON_ in python 3.5+ >>> import dimod >>> import bson ... >>> bqm = dimod.BinaryQuadraticModel({'a': -1.0, 'b': 1.0}, {('a', 'b'): -1.0}, 0.0, dimod.SPIN) >>> doc = bqm.to_serializable(use_bytes=True) >>> b = bson.BSON.encode(doc) # doctest: +SKIP Encode using BSON in python 2.7. Because :class:`bytes` is an alias for :class:`str`, we need to signal to the encoder that it should encode the biases and labels as binary data. >>> import dimod >>> import bson ... >>> bqm = dimod.BinaryQuadraticModel({'a': -1.0, 'b': 1.0}, {('a', 'b'): -1.0}, 0.0, dimod.SPIN) >>> doc = bqm.to_serializable(use_bytes=True, bytes_type=bson.Binary) >>> b = bson.BSON.encode(doc) # doctest: +SKIP See also: :meth:`~.BinaryQuadraticModel.from_serializable` :func:`json.dumps`, :func:`json.dump` JSON encoding functions :meth:`bson.BSON.encode` BSON encoding method .. _BSON: http://bsonspec.org/ ### Response: def to_serializable(self, use_bytes=False, bias_dtype=np.float32, bytes_type=bytes): """Convert the binary quadratic model to a serializable object. Args: use_bytes (bool, optional, default=False): If True, a compact representation representing the biases as bytes is used. bias_dtype (numpy.dtype, optional, default=numpy.float32): If `use_bytes` is True, this numpy dtype will be used to represent the bias values in the serialized format. bytes_type (class, optional, default=bytes): This class will be used to wrap the bytes objects in the serialization if `use_bytes` is true. Useful for when using Python 2 and using BSON encoding, which will not accept the raw `bytes` type, so `bson.Binary` can be used instead. Returns: dict: An object that can be serialized. Examples: Encode using JSON >>> import dimod >>> import json ... >>> bqm = dimod.BinaryQuadraticModel({'a': -1.0, 'b': 1.0}, {('a', 'b'): -1.0}, 0.0, dimod.SPIN) >>> s = json.dumps(bqm.to_serializable()) Encode using BSON_ in python 3.5+ >>> import dimod >>> import bson ... >>> bqm = dimod.BinaryQuadraticModel({'a': -1.0, 'b': 1.0}, {('a', 'b'): -1.0}, 0.0, dimod.SPIN) >>> doc = bqm.to_serializable(use_bytes=True) >>> b = bson.BSON.encode(doc) # doctest: +SKIP Encode using BSON in python 2.7. Because :class:`bytes` is an alias for :class:`str`, we need to signal to the encoder that it should encode the biases and labels as binary data. >>> import dimod >>> import bson ... >>> bqm = dimod.BinaryQuadraticModel({'a': -1.0, 'b': 1.0}, {('a', 'b'): -1.0}, 0.0, dimod.SPIN) >>> doc = bqm.to_serializable(use_bytes=True, bytes_type=bson.Binary) >>> b = bson.BSON.encode(doc) # doctest: +SKIP See also: :meth:`~.BinaryQuadraticModel.from_serializable` :func:`json.dumps`, :func:`json.dump` JSON encoding functions :meth:`bson.BSON.encode` BSON encoding method .. _BSON: http://bsonspec.org/ """ from dimod.package_info import __version__ schema_version = "2.0.0" try: variables = sorted(self.variables) except TypeError: # sorting unlike types in py3 variables = list(self.variables) num_variables = len(variables) # when doing byte encoding we can use less space depending on the # total number of variables index_dtype = np.uint16 if num_variables <= 2**16 else np.uint32 ldata, (irow, icol, qdata), offset = self.to_numpy_vectors( dtype=bias_dtype, index_dtype=index_dtype, sort_indices=True, variable_order=variables) doc = {"basetype": "BinaryQuadraticModel", "type": type(self).__name__, "version": {"dimod": __version__, "bqm_schema": schema_version}, "variable_labels": variables, "variable_type": self.vartype.name, "info": self.info, "offset": float(offset), "use_bytes": bool(use_bytes) } if use_bytes: doc.update({'linear_biases': array2bytes(ldata, bytes_type=bytes_type), 'quadratic_biases': array2bytes(qdata, bytes_type=bytes_type), 'quadratic_head': array2bytes(irow, bytes_type=bytes_type), 'quadratic_tail': array2bytes(icol, bytes_type=bytes_type)}) else: doc.update({'linear_biases': ldata.tolist(), 'quadratic_biases': qdata.tolist(), 'quadratic_head': irow.tolist(), 'quadratic_tail': icol.tolist()}) return doc
def get_s2_like_s1(self, struct1, struct2, include_ignored_species=True): """ Performs transformations on struct2 to put it in a basis similar to struct1 (without changing any of the inter-site distances) Args: struct1 (Structure): Reference structure struct2 (Structure): Structure to transform. include_ignored_species (bool): Defaults to True, the ignored_species is also transformed to the struct1 lattice orientation, though obviously there is no direct matching to existing sites. Returns: A structure object similar to struct1, obtained by making a supercell, sorting, and translating struct2. """ s1, s2 = self._process_species([struct1, struct2]) trans = self.get_transformation(s1, s2) if trans is None: return None sc, t, mapping = trans sites = [site for site in s2] # Append the ignored sites at the end. sites.extend([site for site in struct2 if site not in s2]) temp = Structure.from_sites(sites) temp.make_supercell(sc) temp.translate_sites(list(range(len(temp))), t) # translate sites to correct unit cell for i, j in enumerate(mapping[:len(s1)]): if j is not None: vec = np.round(struct1[i].frac_coords - temp[j].frac_coords) temp.translate_sites(j, vec, to_unit_cell=False) sites = [temp.sites[i] for i in mapping if i is not None] if include_ignored_species: start = int(round(len(temp) / len(struct2) * len(s2))) sites.extend(temp.sites[start:]) return Structure.from_sites(sites)
Performs transformations on struct2 to put it in a basis similar to struct1 (without changing any of the inter-site distances) Args: struct1 (Structure): Reference structure struct2 (Structure): Structure to transform. include_ignored_species (bool): Defaults to True, the ignored_species is also transformed to the struct1 lattice orientation, though obviously there is no direct matching to existing sites. Returns: A structure object similar to struct1, obtained by making a supercell, sorting, and translating struct2.
Below is the the instruction that describes the task: ### Input: Performs transformations on struct2 to put it in a basis similar to struct1 (without changing any of the inter-site distances) Args: struct1 (Structure): Reference structure struct2 (Structure): Structure to transform. include_ignored_species (bool): Defaults to True, the ignored_species is also transformed to the struct1 lattice orientation, though obviously there is no direct matching to existing sites. Returns: A structure object similar to struct1, obtained by making a supercell, sorting, and translating struct2. ### Response: def get_s2_like_s1(self, struct1, struct2, include_ignored_species=True): """ Performs transformations on struct2 to put it in a basis similar to struct1 (without changing any of the inter-site distances) Args: struct1 (Structure): Reference structure struct2 (Structure): Structure to transform. include_ignored_species (bool): Defaults to True, the ignored_species is also transformed to the struct1 lattice orientation, though obviously there is no direct matching to existing sites. Returns: A structure object similar to struct1, obtained by making a supercell, sorting, and translating struct2. """ s1, s2 = self._process_species([struct1, struct2]) trans = self.get_transformation(s1, s2) if trans is None: return None sc, t, mapping = trans sites = [site for site in s2] # Append the ignored sites at the end. sites.extend([site for site in struct2 if site not in s2]) temp = Structure.from_sites(sites) temp.make_supercell(sc) temp.translate_sites(list(range(len(temp))), t) # translate sites to correct unit cell for i, j in enumerate(mapping[:len(s1)]): if j is not None: vec = np.round(struct1[i].frac_coords - temp[j].frac_coords) temp.translate_sites(j, vec, to_unit_cell=False) sites = [temp.sites[i] for i in mapping if i is not None] if include_ignored_species: start = int(round(len(temp) / len(struct2) * len(s2))) sites.extend(temp.sites[start:]) return Structure.from_sites(sites)
def render_to_response(self, context, **response_kwargs): """ Returns a PDF response with a template rendered with the given context. """ filename = response_kwargs.pop('filename', None) cmd_options = response_kwargs.pop('cmd_options', None) if issubclass(self.response_class, PDFTemplateResponse): if filename is None: filename = self.get_filename() if cmd_options is None: cmd_options = self.get_cmd_options() return super(PDFTemplateView, self).render_to_response( context=context, filename=filename, show_content_in_browser=self.show_content_in_browser, header_template=self.header_template, footer_template=self.footer_template, cmd_options=cmd_options, cover_template=self.cover_template, **response_kwargs ) else: return super(PDFTemplateView, self).render_to_response( context=context, **response_kwargs )
Returns a PDF response with a template rendered with the given context.
Below is the the instruction that describes the task: ### Input: Returns a PDF response with a template rendered with the given context. ### Response: def render_to_response(self, context, **response_kwargs): """ Returns a PDF response with a template rendered with the given context. """ filename = response_kwargs.pop('filename', None) cmd_options = response_kwargs.pop('cmd_options', None) if issubclass(self.response_class, PDFTemplateResponse): if filename is None: filename = self.get_filename() if cmd_options is None: cmd_options = self.get_cmd_options() return super(PDFTemplateView, self).render_to_response( context=context, filename=filename, show_content_in_browser=self.show_content_in_browser, header_template=self.header_template, footer_template=self.footer_template, cmd_options=cmd_options, cover_template=self.cover_template, **response_kwargs ) else: return super(PDFTemplateView, self).render_to_response( context=context, **response_kwargs )
def get_resources_by_search(self, resource_query, resource_search): """Pass through to provider ResourceSearchSession.get_resources_by_search""" # Implemented from azosid template for - # osid.resource.ResourceSearchSession.get_resources_by_search_template if not self._can('search'): raise PermissionDenied() return self._provider_session.get_resources_by_search(resource_query, resource_search)
Pass through to provider ResourceSearchSession.get_resources_by_search
Below is the the instruction that describes the task: ### Input: Pass through to provider ResourceSearchSession.get_resources_by_search ### Response: def get_resources_by_search(self, resource_query, resource_search): """Pass through to provider ResourceSearchSession.get_resources_by_search""" # Implemented from azosid template for - # osid.resource.ResourceSearchSession.get_resources_by_search_template if not self._can('search'): raise PermissionDenied() return self._provider_session.get_resources_by_search(resource_query, resource_search)
def send_async(self, transaction, headers=None): """Submit a transaction to the Federation with the mode `async`. Args: transaction (dict): the transaction to be sent to the Federation node(s). headers (dict): Optional headers to pass to the request. Returns: dict: The transaction sent to the Federation node(s). """ return self.transport.forward_request( method='POST', path=self.path, json=transaction, params={'mode': 'async'}, headers=headers)
Submit a transaction to the Federation with the mode `async`. Args: transaction (dict): the transaction to be sent to the Federation node(s). headers (dict): Optional headers to pass to the request. Returns: dict: The transaction sent to the Federation node(s).
Below is the the instruction that describes the task: ### Input: Submit a transaction to the Federation with the mode `async`. Args: transaction (dict): the transaction to be sent to the Federation node(s). headers (dict): Optional headers to pass to the request. Returns: dict: The transaction sent to the Federation node(s). ### Response: def send_async(self, transaction, headers=None): """Submit a transaction to the Federation with the mode `async`. Args: transaction (dict): the transaction to be sent to the Federation node(s). headers (dict): Optional headers to pass to the request. Returns: dict: The transaction sent to the Federation node(s). """ return self.transport.forward_request( method='POST', path=self.path, json=transaction, params={'mode': 'async'}, headers=headers)
def smoothed(self, angle=.4): """ Return a version of the current mesh which will render nicely, without changing source mesh. Parameters ------------- angle : float Angle in radians, face pairs with angles smaller than this value will appear smoothed Returns --------- smoothed : trimesh.Trimesh Non watertight version of current mesh which will render nicely with smooth shading """ # smooth should be recomputed if visuals change self.visual._verify_crc() cached = self.visual._cache['smoothed'] if cached is not None: return cached smoothed = graph.smoothed(self, angle) self.visual._cache['smoothed'] = smoothed return smoothed
Return a version of the current mesh which will render nicely, without changing source mesh. Parameters ------------- angle : float Angle in radians, face pairs with angles smaller than this value will appear smoothed Returns --------- smoothed : trimesh.Trimesh Non watertight version of current mesh which will render nicely with smooth shading
Below is the the instruction that describes the task: ### Input: Return a version of the current mesh which will render nicely, without changing source mesh. Parameters ------------- angle : float Angle in radians, face pairs with angles smaller than this value will appear smoothed Returns --------- smoothed : trimesh.Trimesh Non watertight version of current mesh which will render nicely with smooth shading ### Response: def smoothed(self, angle=.4): """ Return a version of the current mesh which will render nicely, without changing source mesh. Parameters ------------- angle : float Angle in radians, face pairs with angles smaller than this value will appear smoothed Returns --------- smoothed : trimesh.Trimesh Non watertight version of current mesh which will render nicely with smooth shading """ # smooth should be recomputed if visuals change self.visual._verify_crc() cached = self.visual._cache['smoothed'] if cached is not None: return cached smoothed = graph.smoothed(self, angle) self.visual._cache['smoothed'] = smoothed return smoothed
def has_previous_assessment_section(self, assessment_section_id): """Tests if there is a previous assessment section in the assessment following the given assessment section ``Id``. arg: assessment_section_id (osid.id.Id): ``Id`` of the ``AssessmentSection`` return: (boolean) - ``true`` if there is a previous assessment section, ``false`` otherwise raise: IllegalState - ``has_assessment_begun()`` is ``false`` raise: NotFound - ``assessment_section_id`` is not found raise: NullArgument - ``assessment_section_id`` is ``null`` raise: OperationFailed - unable to complete request raise: PermissionDenied - authorization failure occurred *compliance: mandatory -- This method must be implemented.* """ try: self.get_previous_assessment_section(assessment_section_id) except errors.IllegalState: return False else: return True
Tests if there is a previous assessment section in the assessment following the given assessment section ``Id``. arg: assessment_section_id (osid.id.Id): ``Id`` of the ``AssessmentSection`` return: (boolean) - ``true`` if there is a previous assessment section, ``false`` otherwise raise: IllegalState - ``has_assessment_begun()`` is ``false`` raise: NotFound - ``assessment_section_id`` is not found raise: NullArgument - ``assessment_section_id`` is ``null`` raise: OperationFailed - unable to complete request raise: PermissionDenied - authorization failure occurred *compliance: mandatory -- This method must be implemented.*
Below is the the instruction that describes the task: ### Input: Tests if there is a previous assessment section in the assessment following the given assessment section ``Id``. arg: assessment_section_id (osid.id.Id): ``Id`` of the ``AssessmentSection`` return: (boolean) - ``true`` if there is a previous assessment section, ``false`` otherwise raise: IllegalState - ``has_assessment_begun()`` is ``false`` raise: NotFound - ``assessment_section_id`` is not found raise: NullArgument - ``assessment_section_id`` is ``null`` raise: OperationFailed - unable to complete request raise: PermissionDenied - authorization failure occurred *compliance: mandatory -- This method must be implemented.* ### Response: def has_previous_assessment_section(self, assessment_section_id): """Tests if there is a previous assessment section in the assessment following the given assessment section ``Id``. arg: assessment_section_id (osid.id.Id): ``Id`` of the ``AssessmentSection`` return: (boolean) - ``true`` if there is a previous assessment section, ``false`` otherwise raise: IllegalState - ``has_assessment_begun()`` is ``false`` raise: NotFound - ``assessment_section_id`` is not found raise: NullArgument - ``assessment_section_id`` is ``null`` raise: OperationFailed - unable to complete request raise: PermissionDenied - authorization failure occurred *compliance: mandatory -- This method must be implemented.* """ try: self.get_previous_assessment_section(assessment_section_id) except errors.IllegalState: return False else: return True
def subprocess_manager(self, exec_args): ''' Bro subprocess manager ''' try: sp = gevent.subprocess.Popen(exec_args, stdout=gevent.subprocess.PIPE, stderr=gevent.subprocess.PIPE) except OSError: raise RuntimeError('Could not run bro executable (either not installed or not in path): %s' % (exec_args)) out, err = sp.communicate() if out: print 'standard output of subprocess: %s' % out if err: raise RuntimeError('%s\npcap_bro had output on stderr: %s' % (exec_args, err)) if sp.returncode: raise RuntimeError('%s\npcap_bro had returncode: %d' % (exec_args, sp.returncode))
Bro subprocess manager
Below is the the instruction that describes the task: ### Input: Bro subprocess manager ### Response: def subprocess_manager(self, exec_args): ''' Bro subprocess manager ''' try: sp = gevent.subprocess.Popen(exec_args, stdout=gevent.subprocess.PIPE, stderr=gevent.subprocess.PIPE) except OSError: raise RuntimeError('Could not run bro executable (either not installed or not in path): %s' % (exec_args)) out, err = sp.communicate() if out: print 'standard output of subprocess: %s' % out if err: raise RuntimeError('%s\npcap_bro had output on stderr: %s' % (exec_args, err)) if sp.returncode: raise RuntimeError('%s\npcap_bro had returncode: %d' % (exec_args, sp.returncode))
def connect_post_namespaced_pod_exec(self, name, namespace, **kwargs): # noqa: E501 """connect_post_namespaced_pod_exec # noqa: E501 connect POST requests to exec of Pod # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.connect_post_namespaced_pod_exec(name, namespace, async_req=True) >>> result = thread.get() :param async_req bool :param str name: name of the PodExecOptions (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param str command: Command is the remote command to execute. argv array. Not executed within a shell. :param str container: Container in which to execute the command. Defaults to only container if there is only one container in the pod. :param bool stderr: Redirect the standard error stream of the pod for this call. Defaults to true. :param bool stdin: Redirect the standard input stream of the pod for this call. Defaults to false. :param bool stdout: Redirect the standard output stream of the pod for this call. Defaults to true. :param bool tty: TTY if true indicates that a tty will be allocated for the exec call. Defaults to false. :return: str If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.connect_post_namespaced_pod_exec_with_http_info(name, namespace, **kwargs) # noqa: E501 else: (data) = self.connect_post_namespaced_pod_exec_with_http_info(name, namespace, **kwargs) # noqa: E501 return data
connect_post_namespaced_pod_exec # noqa: E501 connect POST requests to exec of Pod # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.connect_post_namespaced_pod_exec(name, namespace, async_req=True) >>> result = thread.get() :param async_req bool :param str name: name of the PodExecOptions (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param str command: Command is the remote command to execute. argv array. Not executed within a shell. :param str container: Container in which to execute the command. Defaults to only container if there is only one container in the pod. :param bool stderr: Redirect the standard error stream of the pod for this call. Defaults to true. :param bool stdin: Redirect the standard input stream of the pod for this call. Defaults to false. :param bool stdout: Redirect the standard output stream of the pod for this call. Defaults to true. :param bool tty: TTY if true indicates that a tty will be allocated for the exec call. Defaults to false. :return: str If the method is called asynchronously, returns the request thread.
Below is the the instruction that describes the task: ### Input: connect_post_namespaced_pod_exec # noqa: E501 connect POST requests to exec of Pod # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.connect_post_namespaced_pod_exec(name, namespace, async_req=True) >>> result = thread.get() :param async_req bool :param str name: name of the PodExecOptions (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param str command: Command is the remote command to execute. argv array. Not executed within a shell. :param str container: Container in which to execute the command. Defaults to only container if there is only one container in the pod. :param bool stderr: Redirect the standard error stream of the pod for this call. Defaults to true. :param bool stdin: Redirect the standard input stream of the pod for this call. Defaults to false. :param bool stdout: Redirect the standard output stream of the pod for this call. Defaults to true. :param bool tty: TTY if true indicates that a tty will be allocated for the exec call. Defaults to false. :return: str If the method is called asynchronously, returns the request thread. ### Response: def connect_post_namespaced_pod_exec(self, name, namespace, **kwargs): # noqa: E501 """connect_post_namespaced_pod_exec # noqa: E501 connect POST requests to exec of Pod # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.connect_post_namespaced_pod_exec(name, namespace, async_req=True) >>> result = thread.get() :param async_req bool :param str name: name of the PodExecOptions (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param str command: Command is the remote command to execute. argv array. Not executed within a shell. :param str container: Container in which to execute the command. Defaults to only container if there is only one container in the pod. :param bool stderr: Redirect the standard error stream of the pod for this call. Defaults to true. :param bool stdin: Redirect the standard input stream of the pod for this call. Defaults to false. :param bool stdout: Redirect the standard output stream of the pod for this call. Defaults to true. :param bool tty: TTY if true indicates that a tty will be allocated for the exec call. Defaults to false. :return: str If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.connect_post_namespaced_pod_exec_with_http_info(name, namespace, **kwargs) # noqa: E501 else: (data) = self.connect_post_namespaced_pod_exec_with_http_info(name, namespace, **kwargs) # noqa: E501 return data
def delete_response(self, publisher_name, extension_name, question_id, response_id): """DeleteResponse. [Preview API] Deletes a response for an extension. (soft delete) :param str publisher_name: Name of the publisher who published the extension. :param str extension_name: Name of the extension. :param long question_id: Identifies the question whose response is to be deleted. :param long response_id: Identifies the response to be deleted. """ route_values = {} if publisher_name is not None: route_values['publisherName'] = self._serialize.url('publisher_name', publisher_name, 'str') if extension_name is not None: route_values['extensionName'] = self._serialize.url('extension_name', extension_name, 'str') if question_id is not None: route_values['questionId'] = self._serialize.url('question_id', question_id, 'long') if response_id is not None: route_values['responseId'] = self._serialize.url('response_id', response_id, 'long') self._send(http_method='DELETE', location_id='7f8ae5e0-46b0-438f-b2e8-13e8513517bd', version='5.1-preview.1', route_values=route_values)
DeleteResponse. [Preview API] Deletes a response for an extension. (soft delete) :param str publisher_name: Name of the publisher who published the extension. :param str extension_name: Name of the extension. :param long question_id: Identifies the question whose response is to be deleted. :param long response_id: Identifies the response to be deleted.
Below is the the instruction that describes the task: ### Input: DeleteResponse. [Preview API] Deletes a response for an extension. (soft delete) :param str publisher_name: Name of the publisher who published the extension. :param str extension_name: Name of the extension. :param long question_id: Identifies the question whose response is to be deleted. :param long response_id: Identifies the response to be deleted. ### Response: def delete_response(self, publisher_name, extension_name, question_id, response_id): """DeleteResponse. [Preview API] Deletes a response for an extension. (soft delete) :param str publisher_name: Name of the publisher who published the extension. :param str extension_name: Name of the extension. :param long question_id: Identifies the question whose response is to be deleted. :param long response_id: Identifies the response to be deleted. """ route_values = {} if publisher_name is not None: route_values['publisherName'] = self._serialize.url('publisher_name', publisher_name, 'str') if extension_name is not None: route_values['extensionName'] = self._serialize.url('extension_name', extension_name, 'str') if question_id is not None: route_values['questionId'] = self._serialize.url('question_id', question_id, 'long') if response_id is not None: route_values['responseId'] = self._serialize.url('response_id', response_id, 'long') self._send(http_method='DELETE', location_id='7f8ae5e0-46b0-438f-b2e8-13e8513517bd', version='5.1-preview.1', route_values=route_values)
def _get_arguments(): # pragma: no cover """ Handle the command line arguments given to this program """ LOG.debug('Parse command line argument') parser = argparse.ArgumentParser( description='Command line interface for the MQ² program') parser.add_argument( '-z', '--zipfile', dest='inputzip', default=None, help='Zip file containing the input files.') parser.add_argument( '-d', '--dir', dest='inputdir', default=None, help='Path to a local folder containing the input files.') parser.add_argument( '-f', '--file', dest='inputfile', default=None, help='Path to a local input file.') parser.add_argument( '--lod', default=3, help='LOD threshold to use to assess the significance of a LOD \ value for a QTL.') parser.add_argument( '--session', default=None, help='Session to analyze if required.') parser.add_argument( '--verbose', action='store_true', help="Gives more info about what's going on") parser.add_argument( '--debug', action='store_true', help="Outputs debugging information") parser.add_argument( '--version', action='version', version='MQ² version: %s' % __version__) return parser.parse_args()
Handle the command line arguments given to this program
Below is the the instruction that describes the task: ### Input: Handle the command line arguments given to this program ### Response: def _get_arguments(): # pragma: no cover """ Handle the command line arguments given to this program """ LOG.debug('Parse command line argument') parser = argparse.ArgumentParser( description='Command line interface for the MQ² program') parser.add_argument( '-z', '--zipfile', dest='inputzip', default=None, help='Zip file containing the input files.') parser.add_argument( '-d', '--dir', dest='inputdir', default=None, help='Path to a local folder containing the input files.') parser.add_argument( '-f', '--file', dest='inputfile', default=None, help='Path to a local input file.') parser.add_argument( '--lod', default=3, help='LOD threshold to use to assess the significance of a LOD \ value for a QTL.') parser.add_argument( '--session', default=None, help='Session to analyze if required.') parser.add_argument( '--verbose', action='store_true', help="Gives more info about what's going on") parser.add_argument( '--debug', action='store_true', help="Outputs debugging information") parser.add_argument( '--version', action='version', version='MQ² version: %s' % __version__) return parser.parse_args()
def find_usage(self): """ Determine the current usage for each limit of this service, and update corresponding Limit via :py:meth:`~.AwsLimit._add_current_usage`. """ logger.debug("Checking usage for service %s", self.service_name) self.connect() for lim in self.limits.values(): lim._reset_usage() self._find_usage_apis() self._find_usage_api_keys() self._find_usage_certs() self._find_usage_plans() self._find_usage_vpc_links() self._have_usage = True logger.debug("Done checking usage.")
Determine the current usage for each limit of this service, and update corresponding Limit via :py:meth:`~.AwsLimit._add_current_usage`.
Below is the the instruction that describes the task: ### Input: Determine the current usage for each limit of this service, and update corresponding Limit via :py:meth:`~.AwsLimit._add_current_usage`. ### Response: def find_usage(self): """ Determine the current usage for each limit of this service, and update corresponding Limit via :py:meth:`~.AwsLimit._add_current_usage`. """ logger.debug("Checking usage for service %s", self.service_name) self.connect() for lim in self.limits.values(): lim._reset_usage() self._find_usage_apis() self._find_usage_api_keys() self._find_usage_certs() self._find_usage_plans() self._find_usage_vpc_links() self._have_usage = True logger.debug("Done checking usage.")
def _get_broker_offsets(self, instance, topics): """ Fetch highwater offsets for each topic/partition from Kafka cluster. Do this for all partitions in the cluster because even if it has no consumers, we may want to measure whether producers are successfully producing. No need to limit this for performance because fetching broker offsets from Kafka is a relatively inexpensive operation. Sends one OffsetRequest per broker to get offsets for all partitions where that broker is the leader: https://cwiki.apache.org/confluence/display/KAFKA/A+Guide+To+The+Kafka+Protocol#AGuideToTheKafkaProtocol-OffsetAPI(AKAListOffset) Can we cleanup connections on agent restart? Brokers before 0.9 - accumulate stale connections on restarts. In 0.9 Kafka added connections.max.idle.ms https://issues.apache.org/jira/browse/KAFKA-1282 """ # Connect to Kafka highwater_offsets = {} topic_partitions_without_a_leader = [] topics_to_fetch = defaultdict(set) cli = self._get_kafka_client(instance) for topic, partitions in iteritems(topics): # if no partitions are provided # we're falling back to all available partitions (?) if len(partitions) == 0: partitions = cli.cluster.available_partitions_for_topic(topic) topics_to_fetch[topic].update(partitions) leader_tp = defaultdict(lambda: defaultdict(set)) for topic, partitions in iteritems(topics_to_fetch): for partition in partitions: partition_leader = cli.cluster.leader_for_partition(TopicPartition(topic, partition)) if partition_leader is not None and partition_leader >= 0: leader_tp[partition_leader][topic].add(partition) max_offsets = 1 for node_id, tps in iteritems(leader_tp): # Construct the OffsetRequest request = OffsetRequest[0]( replica_id=-1, topics=[ (topic, [(partition, OffsetResetStrategy.LATEST, max_offsets) for partition in partitions]) for topic, partitions in iteritems(tps) ], ) response = self._make_blocking_req(cli, request, node_id=node_id) offsets, unled = self._process_highwater_offsets(response) highwater_offsets.update(offsets) topic_partitions_without_a_leader.extend(unled) return highwater_offsets, list(set(topic_partitions_without_a_leader))
Fetch highwater offsets for each topic/partition from Kafka cluster. Do this for all partitions in the cluster because even if it has no consumers, we may want to measure whether producers are successfully producing. No need to limit this for performance because fetching broker offsets from Kafka is a relatively inexpensive operation. Sends one OffsetRequest per broker to get offsets for all partitions where that broker is the leader: https://cwiki.apache.org/confluence/display/KAFKA/A+Guide+To+The+Kafka+Protocol#AGuideToTheKafkaProtocol-OffsetAPI(AKAListOffset) Can we cleanup connections on agent restart? Brokers before 0.9 - accumulate stale connections on restarts. In 0.9 Kafka added connections.max.idle.ms https://issues.apache.org/jira/browse/KAFKA-1282
Below is the the instruction that describes the task: ### Input: Fetch highwater offsets for each topic/partition from Kafka cluster. Do this for all partitions in the cluster because even if it has no consumers, we may want to measure whether producers are successfully producing. No need to limit this for performance because fetching broker offsets from Kafka is a relatively inexpensive operation. Sends one OffsetRequest per broker to get offsets for all partitions where that broker is the leader: https://cwiki.apache.org/confluence/display/KAFKA/A+Guide+To+The+Kafka+Protocol#AGuideToTheKafkaProtocol-OffsetAPI(AKAListOffset) Can we cleanup connections on agent restart? Brokers before 0.9 - accumulate stale connections on restarts. In 0.9 Kafka added connections.max.idle.ms https://issues.apache.org/jira/browse/KAFKA-1282 ### Response: def _get_broker_offsets(self, instance, topics): """ Fetch highwater offsets for each topic/partition from Kafka cluster. Do this for all partitions in the cluster because even if it has no consumers, we may want to measure whether producers are successfully producing. No need to limit this for performance because fetching broker offsets from Kafka is a relatively inexpensive operation. Sends one OffsetRequest per broker to get offsets for all partitions where that broker is the leader: https://cwiki.apache.org/confluence/display/KAFKA/A+Guide+To+The+Kafka+Protocol#AGuideToTheKafkaProtocol-OffsetAPI(AKAListOffset) Can we cleanup connections on agent restart? Brokers before 0.9 - accumulate stale connections on restarts. In 0.9 Kafka added connections.max.idle.ms https://issues.apache.org/jira/browse/KAFKA-1282 """ # Connect to Kafka highwater_offsets = {} topic_partitions_without_a_leader = [] topics_to_fetch = defaultdict(set) cli = self._get_kafka_client(instance) for topic, partitions in iteritems(topics): # if no partitions are provided # we're falling back to all available partitions (?) if len(partitions) == 0: partitions = cli.cluster.available_partitions_for_topic(topic) topics_to_fetch[topic].update(partitions) leader_tp = defaultdict(lambda: defaultdict(set)) for topic, partitions in iteritems(topics_to_fetch): for partition in partitions: partition_leader = cli.cluster.leader_for_partition(TopicPartition(topic, partition)) if partition_leader is not None and partition_leader >= 0: leader_tp[partition_leader][topic].add(partition) max_offsets = 1 for node_id, tps in iteritems(leader_tp): # Construct the OffsetRequest request = OffsetRequest[0]( replica_id=-1, topics=[ (topic, [(partition, OffsetResetStrategy.LATEST, max_offsets) for partition in partitions]) for topic, partitions in iteritems(tps) ], ) response = self._make_blocking_req(cli, request, node_id=node_id) offsets, unled = self._process_highwater_offsets(response) highwater_offsets.update(offsets) topic_partitions_without_a_leader.extend(unled) return highwater_offsets, list(set(topic_partitions_without_a_leader))
def reverse_pivot_to_fact(self, staging_table, piv_column, piv_list, from_column, meas_names, meas_values, new_line): """ For each column in the piv_list, append ALL from_column's using the group_list e.g. Input Table YEAR Person Q1 Q2 2010 Fred Spain 14 2010 Jane Spain 13.995 Output Table Year Person Question Result 2010 Fred Q1 Spain 2010 Fred Q2 14 2010 Jane Q1 Spain 2010 Jane Q2 13.995 You would use: from_column = [YEAR, Person] pivot_column = 'Question' piv_list = [Q1, Q2] meas_names = [Result] meas_values = [Result] # this can be SQL such as count(*) or count(distinct COL_NAME) To get the result: INSERT INTO C_UES2014_FT ( YEAR, Person, Question, Result, REC_EXTRACT_DATE) ( SELECT YEAR, Person, 'Q1', Q1, SYSDATE FROM S_UES2014_RAW); INSERT INTO C_UES2014_FT ( YEAR, Person, Question, Result, REC_EXTRACT_DATE) ( SELECT YEAR, Person, 'Q2', Q2, SYSDATE FROM S_UES2014_RAW); COMMIT; """ self.sql_text += '\n-----------------------------\n--Reverse Pivot\n--------------------------\n\n' num_chars_on_line = 0 for piv_num in range(len(piv_list)): # INSERT columns self.sql_text += 'INSERT INTO ' + self.fact_table + ' (' + new_line if piv_column not in from_column: self.sql_text += piv_column + ', ' #pass for g in meas_names: self.sql_text += g + ', ' for c in from_column: if c not in meas_names: if c == piv_column: # dont insert the same column twice print("Error - do NOT specify pivot column in the fact list") exit(1) else: self.sql_text += c + ', ' num_chars_on_line += len(c) + 2 if num_chars_on_line > 100: self.sql_text += new_line num_chars_on_line = 0 self.sql_text += '' + self.date_updated_col + ') (\n' # SELECT columns self.sql_text += 'SELECT ' + new_line num_chars_on_line = 0 self.sql_text += "'" + piv_list[piv_num] + "', " for meas_num, _ in enumerate(meas_names): if meas_values[meas_num] == '': self.sql_text += piv_list[piv_num] + ', ' else: self.sql_text += meas_values[meas_num] + ', ' for c in from_column: if c not in meas_names: # dont insert the same column twice self.sql_text += c + ', ' num_chars_on_line += len(c) + 2 if num_chars_on_line > 100: self.sql_text += new_line num_chars_on_line = 0 self.sql_text += 'SYSDATE \nFROM ' + staging_table self.sql_text += ');\n'
For each column in the piv_list, append ALL from_column's using the group_list e.g. Input Table YEAR Person Q1 Q2 2010 Fred Spain 14 2010 Jane Spain 13.995 Output Table Year Person Question Result 2010 Fred Q1 Spain 2010 Fred Q2 14 2010 Jane Q1 Spain 2010 Jane Q2 13.995 You would use: from_column = [YEAR, Person] pivot_column = 'Question' piv_list = [Q1, Q2] meas_names = [Result] meas_values = [Result] # this can be SQL such as count(*) or count(distinct COL_NAME) To get the result: INSERT INTO C_UES2014_FT ( YEAR, Person, Question, Result, REC_EXTRACT_DATE) ( SELECT YEAR, Person, 'Q1', Q1, SYSDATE FROM S_UES2014_RAW); INSERT INTO C_UES2014_FT ( YEAR, Person, Question, Result, REC_EXTRACT_DATE) ( SELECT YEAR, Person, 'Q2', Q2, SYSDATE FROM S_UES2014_RAW); COMMIT;
Below is the the instruction that describes the task: ### Input: For each column in the piv_list, append ALL from_column's using the group_list e.g. Input Table YEAR Person Q1 Q2 2010 Fred Spain 14 2010 Jane Spain 13.995 Output Table Year Person Question Result 2010 Fred Q1 Spain 2010 Fred Q2 14 2010 Jane Q1 Spain 2010 Jane Q2 13.995 You would use: from_column = [YEAR, Person] pivot_column = 'Question' piv_list = [Q1, Q2] meas_names = [Result] meas_values = [Result] # this can be SQL such as count(*) or count(distinct COL_NAME) To get the result: INSERT INTO C_UES2014_FT ( YEAR, Person, Question, Result, REC_EXTRACT_DATE) ( SELECT YEAR, Person, 'Q1', Q1, SYSDATE FROM S_UES2014_RAW); INSERT INTO C_UES2014_FT ( YEAR, Person, Question, Result, REC_EXTRACT_DATE) ( SELECT YEAR, Person, 'Q2', Q2, SYSDATE FROM S_UES2014_RAW); COMMIT; ### Response: def reverse_pivot_to_fact(self, staging_table, piv_column, piv_list, from_column, meas_names, meas_values, new_line): """ For each column in the piv_list, append ALL from_column's using the group_list e.g. Input Table YEAR Person Q1 Q2 2010 Fred Spain 14 2010 Jane Spain 13.995 Output Table Year Person Question Result 2010 Fred Q1 Spain 2010 Fred Q2 14 2010 Jane Q1 Spain 2010 Jane Q2 13.995 You would use: from_column = [YEAR, Person] pivot_column = 'Question' piv_list = [Q1, Q2] meas_names = [Result] meas_values = [Result] # this can be SQL such as count(*) or count(distinct COL_NAME) To get the result: INSERT INTO C_UES2014_FT ( YEAR, Person, Question, Result, REC_EXTRACT_DATE) ( SELECT YEAR, Person, 'Q1', Q1, SYSDATE FROM S_UES2014_RAW); INSERT INTO C_UES2014_FT ( YEAR, Person, Question, Result, REC_EXTRACT_DATE) ( SELECT YEAR, Person, 'Q2', Q2, SYSDATE FROM S_UES2014_RAW); COMMIT; """ self.sql_text += '\n-----------------------------\n--Reverse Pivot\n--------------------------\n\n' num_chars_on_line = 0 for piv_num in range(len(piv_list)): # INSERT columns self.sql_text += 'INSERT INTO ' + self.fact_table + ' (' + new_line if piv_column not in from_column: self.sql_text += piv_column + ', ' #pass for g in meas_names: self.sql_text += g + ', ' for c in from_column: if c not in meas_names: if c == piv_column: # dont insert the same column twice print("Error - do NOT specify pivot column in the fact list") exit(1) else: self.sql_text += c + ', ' num_chars_on_line += len(c) + 2 if num_chars_on_line > 100: self.sql_text += new_line num_chars_on_line = 0 self.sql_text += '' + self.date_updated_col + ') (\n' # SELECT columns self.sql_text += 'SELECT ' + new_line num_chars_on_line = 0 self.sql_text += "'" + piv_list[piv_num] + "', " for meas_num, _ in enumerate(meas_names): if meas_values[meas_num] == '': self.sql_text += piv_list[piv_num] + ', ' else: self.sql_text += meas_values[meas_num] + ', ' for c in from_column: if c not in meas_names: # dont insert the same column twice self.sql_text += c + ', ' num_chars_on_line += len(c) + 2 if num_chars_on_line > 100: self.sql_text += new_line num_chars_on_line = 0 self.sql_text += 'SYSDATE \nFROM ' + staging_table self.sql_text += ');\n'
def flatten(*sequence): """Flatten nested sequences into one.""" result = [] for entry in sequence: if isinstance(entry, list): result += Select.flatten(*entry) elif isinstance(entry, tuple): result += Select.flatten(*entry) else: result.append(entry) return result
Flatten nested sequences into one.
Below is the the instruction that describes the task: ### Input: Flatten nested sequences into one. ### Response: def flatten(*sequence): """Flatten nested sequences into one.""" result = [] for entry in sequence: if isinstance(entry, list): result += Select.flatten(*entry) elif isinstance(entry, tuple): result += Select.flatten(*entry) else: result.append(entry) return result
def add(self, synchronous=True, **kwargs): """Add provided Content View Component. :param synchronous: What should happen if the server returns an HTTP 202 (accepted) status code? Wait for the task to complete if ``True``. Immediately return the server's response otherwise. :param kwargs: Arguments to pass to requests. :returns: The server's response, with all JSON decoded. :raises: ``requests.exceptions.HTTPError`` If the server responds with an HTTP 4XX or 5XX message. """ kwargs = kwargs.copy() # shadow the passed-in kwargs if 'data' not in kwargs: # data is required kwargs['data'] = dict() if 'component_ids' not in kwargs['data']: kwargs['data']['components'] = [_payload(self.get_fields(), self.get_values())] kwargs.update(self._server_config.get_client_kwargs()) response = client.put(self.path('add'), **kwargs) return _handle_response(response, self._server_config, synchronous)
Add provided Content View Component. :param synchronous: What should happen if the server returns an HTTP 202 (accepted) status code? Wait for the task to complete if ``True``. Immediately return the server's response otherwise. :param kwargs: Arguments to pass to requests. :returns: The server's response, with all JSON decoded. :raises: ``requests.exceptions.HTTPError`` If the server responds with an HTTP 4XX or 5XX message.
Below is the the instruction that describes the task: ### Input: Add provided Content View Component. :param synchronous: What should happen if the server returns an HTTP 202 (accepted) status code? Wait for the task to complete if ``True``. Immediately return the server's response otherwise. :param kwargs: Arguments to pass to requests. :returns: The server's response, with all JSON decoded. :raises: ``requests.exceptions.HTTPError`` If the server responds with an HTTP 4XX or 5XX message. ### Response: def add(self, synchronous=True, **kwargs): """Add provided Content View Component. :param synchronous: What should happen if the server returns an HTTP 202 (accepted) status code? Wait for the task to complete if ``True``. Immediately return the server's response otherwise. :param kwargs: Arguments to pass to requests. :returns: The server's response, with all JSON decoded. :raises: ``requests.exceptions.HTTPError`` If the server responds with an HTTP 4XX or 5XX message. """ kwargs = kwargs.copy() # shadow the passed-in kwargs if 'data' not in kwargs: # data is required kwargs['data'] = dict() if 'component_ids' not in kwargs['data']: kwargs['data']['components'] = [_payload(self.get_fields(), self.get_values())] kwargs.update(self._server_config.get_client_kwargs()) response = client.put(self.path('add'), **kwargs) return _handle_response(response, self._server_config, synchronous)
def to_jd(year, month, day, method=None): '''Obtain Julian day from a given French Revolutionary calendar date.''' method = method or 'equinox' if day < 1 or day > 30: raise ValueError("Invalid day for this calendar") if month > 13: raise ValueError("Invalid month for this calendar") if month == 13 and day > 5 + leap(year, method=method): raise ValueError("Invalid day for this month in this calendar") if method == 'equinox': return _to_jd_equinox(year, month, day) else: return _to_jd_schematic(year, month, day, method)
Obtain Julian day from a given French Revolutionary calendar date.
Below is the the instruction that describes the task: ### Input: Obtain Julian day from a given French Revolutionary calendar date. ### Response: def to_jd(year, month, day, method=None): '''Obtain Julian day from a given French Revolutionary calendar date.''' method = method or 'equinox' if day < 1 or day > 30: raise ValueError("Invalid day for this calendar") if month > 13: raise ValueError("Invalid month for this calendar") if month == 13 and day > 5 + leap(year, method=method): raise ValueError("Invalid day for this month in this calendar") if method == 'equinox': return _to_jd_equinox(year, month, day) else: return _to_jd_schematic(year, month, day, method)
def get_id(name=None, tags=None, region=None, key=None, keyid=None, profile=None, in_states=None, filters=None): ''' Given instance properties, return the instance id if it exists. CLI Example: .. code-block:: bash salt myminion boto_ec2.get_id myinstance ''' instance_ids = find_instances(name=name, tags=tags, region=region, key=key, keyid=keyid, profile=profile, in_states=in_states, filters=filters) if instance_ids: log.info("Instance ids: %s", " ".join(instance_ids)) if len(instance_ids) == 1: return instance_ids[0] else: raise CommandExecutionError('Found more than one instance ' 'matching the criteria.') else: log.warning('Could not find instance.') return None
Given instance properties, return the instance id if it exists. CLI Example: .. code-block:: bash salt myminion boto_ec2.get_id myinstance
Below is the the instruction that describes the task: ### Input: Given instance properties, return the instance id if it exists. CLI Example: .. code-block:: bash salt myminion boto_ec2.get_id myinstance ### Response: def get_id(name=None, tags=None, region=None, key=None, keyid=None, profile=None, in_states=None, filters=None): ''' Given instance properties, return the instance id if it exists. CLI Example: .. code-block:: bash salt myminion boto_ec2.get_id myinstance ''' instance_ids = find_instances(name=name, tags=tags, region=region, key=key, keyid=keyid, profile=profile, in_states=in_states, filters=filters) if instance_ids: log.info("Instance ids: %s", " ".join(instance_ids)) if len(instance_ids) == 1: return instance_ids[0] else: raise CommandExecutionError('Found more than one instance ' 'matching the criteria.') else: log.warning('Could not find instance.') return None
def c3(x, lag): """ This function calculates the value of .. math:: \\frac{1}{n-2lag} \sum_{i=0}^{n-2lag} x_{i + 2 \cdot lag}^2 \cdot x_{i + lag} \cdot x_{i} which is .. math:: \\mathbb{E}[L^2(X)^2 \cdot L(X) \cdot X] where :math:`\\mathbb{E}` is the mean and :math:`L` is the lag operator. It was proposed in [1] as a measure of non linearity in the time series. .. rubric:: References | [1] Schreiber, T. and Schmitz, A. (1997). | Discrimination power of measures for nonlinearity in a time series | PHYSICAL REVIEW E, VOLUME 55, NUMBER 5 :param x: the time series to calculate the feature of :type x: numpy.ndarray :param lag: the lag that should be used in the calculation of the feature :type lag: int :return: the value of this feature :return type: float """ if not isinstance(x, (np.ndarray, pd.Series)): x = np.asarray(x) n = x.size if 2 * lag >= n: return 0 else: return np.mean((_roll(x, 2 * -lag) * _roll(x, -lag) * x)[0:(n - 2 * lag)])
This function calculates the value of .. math:: \\frac{1}{n-2lag} \sum_{i=0}^{n-2lag} x_{i + 2 \cdot lag}^2 \cdot x_{i + lag} \cdot x_{i} which is .. math:: \\mathbb{E}[L^2(X)^2 \cdot L(X) \cdot X] where :math:`\\mathbb{E}` is the mean and :math:`L` is the lag operator. It was proposed in [1] as a measure of non linearity in the time series. .. rubric:: References | [1] Schreiber, T. and Schmitz, A. (1997). | Discrimination power of measures for nonlinearity in a time series | PHYSICAL REVIEW E, VOLUME 55, NUMBER 5 :param x: the time series to calculate the feature of :type x: numpy.ndarray :param lag: the lag that should be used in the calculation of the feature :type lag: int :return: the value of this feature :return type: float
Below is the the instruction that describes the task: ### Input: This function calculates the value of .. math:: \\frac{1}{n-2lag} \sum_{i=0}^{n-2lag} x_{i + 2 \cdot lag}^2 \cdot x_{i + lag} \cdot x_{i} which is .. math:: \\mathbb{E}[L^2(X)^2 \cdot L(X) \cdot X] where :math:`\\mathbb{E}` is the mean and :math:`L` is the lag operator. It was proposed in [1] as a measure of non linearity in the time series. .. rubric:: References | [1] Schreiber, T. and Schmitz, A. (1997). | Discrimination power of measures for nonlinearity in a time series | PHYSICAL REVIEW E, VOLUME 55, NUMBER 5 :param x: the time series to calculate the feature of :type x: numpy.ndarray :param lag: the lag that should be used in the calculation of the feature :type lag: int :return: the value of this feature :return type: float ### Response: def c3(x, lag): """ This function calculates the value of .. math:: \\frac{1}{n-2lag} \sum_{i=0}^{n-2lag} x_{i + 2 \cdot lag}^2 \cdot x_{i + lag} \cdot x_{i} which is .. math:: \\mathbb{E}[L^2(X)^2 \cdot L(X) \cdot X] where :math:`\\mathbb{E}` is the mean and :math:`L` is the lag operator. It was proposed in [1] as a measure of non linearity in the time series. .. rubric:: References | [1] Schreiber, T. and Schmitz, A. (1997). | Discrimination power of measures for nonlinearity in a time series | PHYSICAL REVIEW E, VOLUME 55, NUMBER 5 :param x: the time series to calculate the feature of :type x: numpy.ndarray :param lag: the lag that should be used in the calculation of the feature :type lag: int :return: the value of this feature :return type: float """ if not isinstance(x, (np.ndarray, pd.Series)): x = np.asarray(x) n = x.size if 2 * lag >= n: return 0 else: return np.mean((_roll(x, 2 * -lag) * _roll(x, -lag) * x)[0:(n - 2 * lag)])
def make_ready_all(self): """ Marks all targets in a task ready for execution. This is used when the interface needs every target Node to be visited--the canonical example being the "scons -c" option. """ T = self.tm.trace if T: T.write(self.trace_message('Task.make_ready_all()', self.node)) self.out_of_date = self.targets[:] for t in self.targets: t.disambiguate().set_state(NODE_EXECUTING) for s in t.side_effects: # add disambiguate here to mirror the call on targets above s.disambiguate().set_state(NODE_EXECUTING)
Marks all targets in a task ready for execution. This is used when the interface needs every target Node to be visited--the canonical example being the "scons -c" option.
Below is the the instruction that describes the task: ### Input: Marks all targets in a task ready for execution. This is used when the interface needs every target Node to be visited--the canonical example being the "scons -c" option. ### Response: def make_ready_all(self): """ Marks all targets in a task ready for execution. This is used when the interface needs every target Node to be visited--the canonical example being the "scons -c" option. """ T = self.tm.trace if T: T.write(self.trace_message('Task.make_ready_all()', self.node)) self.out_of_date = self.targets[:] for t in self.targets: t.disambiguate().set_state(NODE_EXECUTING) for s in t.side_effects: # add disambiguate here to mirror the call on targets above s.disambiguate().set_state(NODE_EXECUTING)
def check_type_of_param_list_elements(param_list): """ Ensures that all elements of param_list are ndarrays or None. Raises a helpful ValueError if otherwise. """ try: assert isinstance(param_list[0], np.ndarray) assert all([(x is None or isinstance(x, np.ndarray)) for x in param_list]) except AssertionError: msg = "param_list[0] must be a numpy array." msg_2 = "All other elements must be numpy arrays or None." total_msg = msg + "\n" + msg_2 raise TypeError(total_msg) return None
Ensures that all elements of param_list are ndarrays or None. Raises a helpful ValueError if otherwise.
Below is the the instruction that describes the task: ### Input: Ensures that all elements of param_list are ndarrays or None. Raises a helpful ValueError if otherwise. ### Response: def check_type_of_param_list_elements(param_list): """ Ensures that all elements of param_list are ndarrays or None. Raises a helpful ValueError if otherwise. """ try: assert isinstance(param_list[0], np.ndarray) assert all([(x is None or isinstance(x, np.ndarray)) for x in param_list]) except AssertionError: msg = "param_list[0] must be a numpy array." msg_2 = "All other elements must be numpy arrays or None." total_msg = msg + "\n" + msg_2 raise TypeError(total_msg) return None
def instance(cls, *args, **kwargs): """Returns a global instance of this class. This method create a new instance if none have previously been created and returns a previously created instance is one already exists. The arguments and keyword arguments passed to this method are passed on to the :meth:`__init__` method of the class upon instantiation. Examples -------- Create a singleton class using instance, and retrieve it:: >>> from IPython.config.configurable import SingletonConfigurable >>> class Foo(SingletonConfigurable): pass >>> foo = Foo.instance() >>> foo == Foo.instance() True Create a subclass that is retrived using the base class instance:: >>> class Bar(SingletonConfigurable): pass >>> class Bam(Bar): pass >>> bam = Bam.instance() >>> bam == Bar.instance() True """ # Create and save the instance if cls._instance is None: inst = cls(*args, **kwargs) # Now make sure that the instance will also be returned by # parent classes' _instance attribute. for subclass in cls._walk_mro(): subclass._instance = inst if isinstance(cls._instance, cls): return cls._instance else: raise MultipleInstanceError( 'Multiple incompatible subclass instances of ' '%s are being created.' % cls.__name__ )
Returns a global instance of this class. This method create a new instance if none have previously been created and returns a previously created instance is one already exists. The arguments and keyword arguments passed to this method are passed on to the :meth:`__init__` method of the class upon instantiation. Examples -------- Create a singleton class using instance, and retrieve it:: >>> from IPython.config.configurable import SingletonConfigurable >>> class Foo(SingletonConfigurable): pass >>> foo = Foo.instance() >>> foo == Foo.instance() True Create a subclass that is retrived using the base class instance:: >>> class Bar(SingletonConfigurable): pass >>> class Bam(Bar): pass >>> bam = Bam.instance() >>> bam == Bar.instance() True
Below is the the instruction that describes the task: ### Input: Returns a global instance of this class. This method create a new instance if none have previously been created and returns a previously created instance is one already exists. The arguments and keyword arguments passed to this method are passed on to the :meth:`__init__` method of the class upon instantiation. Examples -------- Create a singleton class using instance, and retrieve it:: >>> from IPython.config.configurable import SingletonConfigurable >>> class Foo(SingletonConfigurable): pass >>> foo = Foo.instance() >>> foo == Foo.instance() True Create a subclass that is retrived using the base class instance:: >>> class Bar(SingletonConfigurable): pass >>> class Bam(Bar): pass >>> bam = Bam.instance() >>> bam == Bar.instance() True ### Response: def instance(cls, *args, **kwargs): """Returns a global instance of this class. This method create a new instance if none have previously been created and returns a previously created instance is one already exists. The arguments and keyword arguments passed to this method are passed on to the :meth:`__init__` method of the class upon instantiation. Examples -------- Create a singleton class using instance, and retrieve it:: >>> from IPython.config.configurable import SingletonConfigurable >>> class Foo(SingletonConfigurable): pass >>> foo = Foo.instance() >>> foo == Foo.instance() True Create a subclass that is retrived using the base class instance:: >>> class Bar(SingletonConfigurable): pass >>> class Bam(Bar): pass >>> bam = Bam.instance() >>> bam == Bar.instance() True """ # Create and save the instance if cls._instance is None: inst = cls(*args, **kwargs) # Now make sure that the instance will also be returned by # parent classes' _instance attribute. for subclass in cls._walk_mro(): subclass._instance = inst if isinstance(cls._instance, cls): return cls._instance else: raise MultipleInstanceError( 'Multiple incompatible subclass instances of ' '%s are being created.' % cls.__name__ )
def font_size_to_pixels(size): """ Convert a fontsize to a pixel value """ if size is None or not isinstance(size, basestring): return conversions = {'em': 16, 'pt': 16/12.} val = re.findall('\d+', size) unit = re.findall('[a-z]+', size) if (val and not unit) or (val and unit[0] == 'px'): return int(val[0]) elif val and unit[0] in conversions: return (int(int(val[0]) * conversions[unit[0]]))
Convert a fontsize to a pixel value
Below is the the instruction that describes the task: ### Input: Convert a fontsize to a pixel value ### Response: def font_size_to_pixels(size): """ Convert a fontsize to a pixel value """ if size is None or not isinstance(size, basestring): return conversions = {'em': 16, 'pt': 16/12.} val = re.findall('\d+', size) unit = re.findall('[a-z]+', size) if (val and not unit) or (val and unit[0] == 'px'): return int(val[0]) elif val and unit[0] in conversions: return (int(int(val[0]) * conversions[unit[0]]))
def _make_stream_reader(cls, stream): """ Return a |StreamReader| instance with wrapping *stream* and having "endian-ness" determined by the 'MM' or 'II' indicator in the TIFF stream header. """ endian = cls._detect_endian(stream) return StreamReader(stream, endian)
Return a |StreamReader| instance with wrapping *stream* and having "endian-ness" determined by the 'MM' or 'II' indicator in the TIFF stream header.
Below is the the instruction that describes the task: ### Input: Return a |StreamReader| instance with wrapping *stream* and having "endian-ness" determined by the 'MM' or 'II' indicator in the TIFF stream header. ### Response: def _make_stream_reader(cls, stream): """ Return a |StreamReader| instance with wrapping *stream* and having "endian-ness" determined by the 'MM' or 'II' indicator in the TIFF stream header. """ endian = cls._detect_endian(stream) return StreamReader(stream, endian)
def _objdump_lexer_tokens(asm_lexer): """ Common objdump lexer tokens to wrap an ASM lexer. """ hex_re = r'[0-9A-Za-z]' return { 'root': [ # File name & format: ('(.*?)(:)( +file format )(.*?)$', bygroups(Name.Label, Punctuation, Text, String)), # Section header ('(Disassembly of section )(.*?)(:)$', bygroups(Text, Name.Label, Punctuation)), # Function labels # (With offset) ('('+hex_re+'+)( )(<)(.*?)([-+])(0[xX][A-Za-z0-9]+)(>:)$', bygroups(Number.Hex, Text, Punctuation, Name.Function, Punctuation, Number.Hex, Punctuation)), # (Without offset) ('('+hex_re+'+)( )(<)(.*?)(>:)$', bygroups(Number.Hex, Text, Punctuation, Name.Function, Punctuation)), # Code line with disassembled instructions ('( *)('+hex_re+r'+:)(\t)((?:'+hex_re+hex_re+' )+)( *\t)([a-zA-Z].*?)$', bygroups(Text, Name.Label, Text, Number.Hex, Text, using(asm_lexer))), # Code line with ascii ('( *)('+hex_re+r'+:)(\t)((?:'+hex_re+hex_re+' )+)( *)(.*?)$', bygroups(Text, Name.Label, Text, Number.Hex, Text, String)), # Continued code line, only raw opcodes without disassembled # instruction ('( *)('+hex_re+r'+:)(\t)((?:'+hex_re+hex_re+' )+)$', bygroups(Text, Name.Label, Text, Number.Hex)), # Skipped a few bytes (r'\t\.\.\.$', Text), # Relocation line # (With offset) (r'(\t\t\t)('+hex_re+r'+:)( )([^\t]+)(\t)(.*?)([-+])(0x'+hex_re+'+)$', bygroups(Text, Name.Label, Text, Name.Property, Text, Name.Constant, Punctuation, Number.Hex)), # (Without offset) (r'(\t\t\t)('+hex_re+r'+:)( )([^\t]+)(\t)(.*?)$', bygroups(Text, Name.Label, Text, Name.Property, Text, Name.Constant)), (r'[^\n]+\n', Other) ] }
Common objdump lexer tokens to wrap an ASM lexer.
Below is the the instruction that describes the task: ### Input: Common objdump lexer tokens to wrap an ASM lexer. ### Response: def _objdump_lexer_tokens(asm_lexer): """ Common objdump lexer tokens to wrap an ASM lexer. """ hex_re = r'[0-9A-Za-z]' return { 'root': [ # File name & format: ('(.*?)(:)( +file format )(.*?)$', bygroups(Name.Label, Punctuation, Text, String)), # Section header ('(Disassembly of section )(.*?)(:)$', bygroups(Text, Name.Label, Punctuation)), # Function labels # (With offset) ('('+hex_re+'+)( )(<)(.*?)([-+])(0[xX][A-Za-z0-9]+)(>:)$', bygroups(Number.Hex, Text, Punctuation, Name.Function, Punctuation, Number.Hex, Punctuation)), # (Without offset) ('('+hex_re+'+)( )(<)(.*?)(>:)$', bygroups(Number.Hex, Text, Punctuation, Name.Function, Punctuation)), # Code line with disassembled instructions ('( *)('+hex_re+r'+:)(\t)((?:'+hex_re+hex_re+' )+)( *\t)([a-zA-Z].*?)$', bygroups(Text, Name.Label, Text, Number.Hex, Text, using(asm_lexer))), # Code line with ascii ('( *)('+hex_re+r'+:)(\t)((?:'+hex_re+hex_re+' )+)( *)(.*?)$', bygroups(Text, Name.Label, Text, Number.Hex, Text, String)), # Continued code line, only raw opcodes without disassembled # instruction ('( *)('+hex_re+r'+:)(\t)((?:'+hex_re+hex_re+' )+)$', bygroups(Text, Name.Label, Text, Number.Hex)), # Skipped a few bytes (r'\t\.\.\.$', Text), # Relocation line # (With offset) (r'(\t\t\t)('+hex_re+r'+:)( )([^\t]+)(\t)(.*?)([-+])(0x'+hex_re+'+)$', bygroups(Text, Name.Label, Text, Name.Property, Text, Name.Constant, Punctuation, Number.Hex)), # (Without offset) (r'(\t\t\t)('+hex_re+r'+:)( )([^\t]+)(\t)(.*?)$', bygroups(Text, Name.Label, Text, Name.Property, Text, Name.Constant)), (r'[^\n]+\n', Other) ] }
def leaf_handler(self,*args): '''#leaf child handler''' desc = self.desc pdesc = self.pdesc desc['leaf'] = True desc['sons_count'] = 0 pdesc['leaf_son_paths'].append(copy.deepcopy(desc['path'])) pdesc['leaf_descendant_paths'].append(copy.deepcopy(desc['path']))
#leaf child handler
Below is the the instruction that describes the task: ### Input: #leaf child handler ### Response: def leaf_handler(self,*args): '''#leaf child handler''' desc = self.desc pdesc = self.pdesc desc['leaf'] = True desc['sons_count'] = 0 pdesc['leaf_son_paths'].append(copy.deepcopy(desc['path'])) pdesc['leaf_descendant_paths'].append(copy.deepcopy(desc['path']))
def size(self): """The size of the schema. If the underlying data source changes, it may be outdated. """ if self._size is None: self._size = 0 for csv_file in self.files: self._size += sum(1 if line else 0 for line in _util.open_local_or_gcs(csv_file, 'r')) return self._size
The size of the schema. If the underlying data source changes, it may be outdated.
Below is the the instruction that describes the task: ### Input: The size of the schema. If the underlying data source changes, it may be outdated. ### Response: def size(self): """The size of the schema. If the underlying data source changes, it may be outdated. """ if self._size is None: self._size = 0 for csv_file in self.files: self._size += sum(1 if line else 0 for line in _util.open_local_or_gcs(csv_file, 'r')) return self._size
def SetFillStyle(self, style): """ *style* may be any fill style understood by ROOT or matplotlib. For full documentation of accepted *style* arguments, see :class:`rootpy.plotting.style.FillStyle`. """ self._fillstyle = FillStyle(style) if isinstance(self, ROOT.TAttFill): ROOT.TAttFill.SetFillStyle(self, self._fillstyle('root'))
*style* may be any fill style understood by ROOT or matplotlib. For full documentation of accepted *style* arguments, see :class:`rootpy.plotting.style.FillStyle`.
Below is the the instruction that describes the task: ### Input: *style* may be any fill style understood by ROOT or matplotlib. For full documentation of accepted *style* arguments, see :class:`rootpy.plotting.style.FillStyle`. ### Response: def SetFillStyle(self, style): """ *style* may be any fill style understood by ROOT or matplotlib. For full documentation of accepted *style* arguments, see :class:`rootpy.plotting.style.FillStyle`. """ self._fillstyle = FillStyle(style) if isinstance(self, ROOT.TAttFill): ROOT.TAttFill.SetFillStyle(self, self._fillstyle('root'))
def hsv2rgb_raw(hsv): """ Converts an HSV tuple to RGB. Intended for internal use. You should use hsv2rgb_spectrum or hsv2rgb_rainbow instead. """ HSV_SECTION_3 = 0x40 h, s, v = hsv # The brightness floor is minimum number that all of # R, G, and B will be set to. invsat = 255 - s brightness_floor = (v * invsat) // 256 # The color amplitude is the maximum amount of R, G, and B # that will be added on top of the brightness_floor to # create the specific hue desired. color_amplitude = v - brightness_floor # figure out which section of the hue wheel we're in, # and how far offset we are within that section section = h // HSV_SECTION_3 # 0..2 offset = h % HSV_SECTION_3 # 0..63 rampup = offset rampdown = (HSV_SECTION_3 - 1) - offset # compute color-amplitude-scaled-down versions of rampup and rampdown rampup_amp_adj = (rampup * color_amplitude) // (256 // 4) rampdown_amp_adj = (rampdown * color_amplitude) // (256 // 4) # add brightness_floor offset to everything rampup_adj_with_floor = rampup_amp_adj + brightness_floor rampdown_adj_with_floor = rampdown_amp_adj + brightness_floor r, g, b = (0, 0, 0) if section: if section == 1: # section 1: 0x40..0x7F r = brightness_floor g = rampdown_adj_with_floor b = rampup_adj_with_floor else: # section 2; 0x80..0xBF r = rampup_adj_with_floor g = brightness_floor b = rampdown_adj_with_floor else: # section 0: 0x00..0x3F r = rampdown_adj_with_floor g = rampup_adj_with_floor b = brightness_floor return (r, g, b)
Converts an HSV tuple to RGB. Intended for internal use. You should use hsv2rgb_spectrum or hsv2rgb_rainbow instead.
Below is the the instruction that describes the task: ### Input: Converts an HSV tuple to RGB. Intended for internal use. You should use hsv2rgb_spectrum or hsv2rgb_rainbow instead. ### Response: def hsv2rgb_raw(hsv): """ Converts an HSV tuple to RGB. Intended for internal use. You should use hsv2rgb_spectrum or hsv2rgb_rainbow instead. """ HSV_SECTION_3 = 0x40 h, s, v = hsv # The brightness floor is minimum number that all of # R, G, and B will be set to. invsat = 255 - s brightness_floor = (v * invsat) // 256 # The color amplitude is the maximum amount of R, G, and B # that will be added on top of the brightness_floor to # create the specific hue desired. color_amplitude = v - brightness_floor # figure out which section of the hue wheel we're in, # and how far offset we are within that section section = h // HSV_SECTION_3 # 0..2 offset = h % HSV_SECTION_3 # 0..63 rampup = offset rampdown = (HSV_SECTION_3 - 1) - offset # compute color-amplitude-scaled-down versions of rampup and rampdown rampup_amp_adj = (rampup * color_amplitude) // (256 // 4) rampdown_amp_adj = (rampdown * color_amplitude) // (256 // 4) # add brightness_floor offset to everything rampup_adj_with_floor = rampup_amp_adj + brightness_floor rampdown_adj_with_floor = rampdown_amp_adj + brightness_floor r, g, b = (0, 0, 0) if section: if section == 1: # section 1: 0x40..0x7F r = brightness_floor g = rampdown_adj_with_floor b = rampup_adj_with_floor else: # section 2; 0x80..0xBF r = rampup_adj_with_floor g = brightness_floor b = rampdown_adj_with_floor else: # section 0: 0x00..0x3F r = rampdown_adj_with_floor g = rampup_adj_with_floor b = brightness_floor return (r, g, b)
def set_level(self, level): """ Sets :attr:loglevel to @level @level: #str one or several :attr:levels """ if not level: return None self.levelmap = set() for char in level: self.levelmap = self.levelmap.union(self.levels[char]) self.loglevel = level return self.loglevel
Sets :attr:loglevel to @level @level: #str one or several :attr:levels
Below is the the instruction that describes the task: ### Input: Sets :attr:loglevel to @level @level: #str one or several :attr:levels ### Response: def set_level(self, level): """ Sets :attr:loglevel to @level @level: #str one or several :attr:levels """ if not level: return None self.levelmap = set() for char in level: self.levelmap = self.levelmap.union(self.levels[char]) self.loglevel = level return self.loglevel
def get_attribute_by_name_and_dimension(name, dimension_id=None,**kwargs): """ Get a specific attribute by its name. dimension_id can be None, because in attribute the dimension_id is not anymore mandatory """ try: attr_i = db.DBSession.query(Attr).filter(and_(Attr.name==name, Attr.dimension_id==dimension_id)).one() log.debug("Attribute retrieved") return attr_i except NoResultFound: return None
Get a specific attribute by its name. dimension_id can be None, because in attribute the dimension_id is not anymore mandatory
Below is the the instruction that describes the task: ### Input: Get a specific attribute by its name. dimension_id can be None, because in attribute the dimension_id is not anymore mandatory ### Response: def get_attribute_by_name_and_dimension(name, dimension_id=None,**kwargs): """ Get a specific attribute by its name. dimension_id can be None, because in attribute the dimension_id is not anymore mandatory """ try: attr_i = db.DBSession.query(Attr).filter(and_(Attr.name==name, Attr.dimension_id==dimension_id)).one() log.debug("Attribute retrieved") return attr_i except NoResultFound: return None
def get_extract_method(path): """Returns `ExtractMethod` to use on resource at path. Cannot be None.""" info_path = _get_info_path(path) info = _read_info(info_path) fname = info.get('original_fname', path) if info else path return _guess_extract_method(fname)
Returns `ExtractMethod` to use on resource at path. Cannot be None.
Below is the the instruction that describes the task: ### Input: Returns `ExtractMethod` to use on resource at path. Cannot be None. ### Response: def get_extract_method(path): """Returns `ExtractMethod` to use on resource at path. Cannot be None.""" info_path = _get_info_path(path) info = _read_info(info_path) fname = info.get('original_fname', path) if info else path return _guess_extract_method(fname)
def get_string_camel_patterns(cls, name, min_length=0): """ Finds all permutations of possible camel casing of the given name :param name: str, the name we need to get all possible permutations and abbreviations for :param min_length: int, minimum length we want for abbreviations :return: list(list(str)), list casing permutations of list of abbreviations """ # Have to check for longest first and remove duplicates patterns = [] abbreviations = list(set(cls._get_abbreviations(name, output_length=min_length))) abbreviations.sort(key=len, reverse=True) for abbr in abbreviations: # We won't check for abbreviations that are stupid eg something with apparent camel casing within # the word itself like LeF, sorting from: # http://stackoverflow.com/questions/13954841/python-sort-upper-case-and-lower-case casing_permutations = list(set(cls._get_casing_permutations(abbr))) casing_permutations.sort(key=lambda v: (v.upper(), v[0].islower(), len(v))) permutations = [permutation for permutation in casing_permutations if cls.is_valid_camel(permutation) or len(permutation) <= 2] if permutations: patterns.append(permutations) return patterns
Finds all permutations of possible camel casing of the given name :param name: str, the name we need to get all possible permutations and abbreviations for :param min_length: int, minimum length we want for abbreviations :return: list(list(str)), list casing permutations of list of abbreviations
Below is the the instruction that describes the task: ### Input: Finds all permutations of possible camel casing of the given name :param name: str, the name we need to get all possible permutations and abbreviations for :param min_length: int, minimum length we want for abbreviations :return: list(list(str)), list casing permutations of list of abbreviations ### Response: def get_string_camel_patterns(cls, name, min_length=0): """ Finds all permutations of possible camel casing of the given name :param name: str, the name we need to get all possible permutations and abbreviations for :param min_length: int, minimum length we want for abbreviations :return: list(list(str)), list casing permutations of list of abbreviations """ # Have to check for longest first and remove duplicates patterns = [] abbreviations = list(set(cls._get_abbreviations(name, output_length=min_length))) abbreviations.sort(key=len, reverse=True) for abbr in abbreviations: # We won't check for abbreviations that are stupid eg something with apparent camel casing within # the word itself like LeF, sorting from: # http://stackoverflow.com/questions/13954841/python-sort-upper-case-and-lower-case casing_permutations = list(set(cls._get_casing_permutations(abbr))) casing_permutations.sort(key=lambda v: (v.upper(), v[0].islower(), len(v))) permutations = [permutation for permutation in casing_permutations if cls.is_valid_camel(permutation) or len(permutation) <= 2] if permutations: patterns.append(permutations) return patterns
def parse_value_object(self, tup_tree): """ :: <!ELEMENT VALUE.OBJECT (CLASS | INSTANCE)> """ self.check_node(tup_tree, 'VALUE.OBJECT') child = self.one_child(tup_tree, ('CLASS', 'INSTANCE')) return (name(tup_tree), attrs(tup_tree), child)
:: <!ELEMENT VALUE.OBJECT (CLASS | INSTANCE)>
Below is the the instruction that describes the task: ### Input: :: <!ELEMENT VALUE.OBJECT (CLASS | INSTANCE)> ### Response: def parse_value_object(self, tup_tree): """ :: <!ELEMENT VALUE.OBJECT (CLASS | INSTANCE)> """ self.check_node(tup_tree, 'VALUE.OBJECT') child = self.one_child(tup_tree, ('CLASS', 'INSTANCE')) return (name(tup_tree), attrs(tup_tree), child)
def sign(self, msg): """sign a message""" signature = SHA256.new() signature.update(self._mackey1) signature.update(msg) signature.update(self._mackey2) return signature.digest()
sign a message
Below is the the instruction that describes the task: ### Input: sign a message ### Response: def sign(self, msg): """sign a message""" signature = SHA256.new() signature.update(self._mackey1) signature.update(msg) signature.update(self._mackey2) return signature.digest()
def _run(name, cmd, output=None, no_start=False, stdin=None, python_shell=True, preserve_state=False, output_loglevel='debug', ignore_retcode=False, use_vt=False, keep_env=None): ''' Common logic for nspawn.run functions ''' orig_state = state(name) exc = None try: ret = __salt__['container_resource.run']( name, cmd, container_type=__virtualname__, exec_driver=EXEC_DRIVER, output=output, no_start=no_start, stdin=stdin, python_shell=python_shell, output_loglevel=output_loglevel, ignore_retcode=ignore_retcode, use_vt=use_vt, keep_env=keep_env) except Exception: raise finally: # Make sure we stop the container if necessary, even if an exception # was raised. if preserve_state \ and orig_state == 'stopped' \ and state(name) != 'stopped': stop(name) if output in (None, 'all'): return ret else: return ret[output]
Common logic for nspawn.run functions
Below is the the instruction that describes the task: ### Input: Common logic for nspawn.run functions ### Response: def _run(name, cmd, output=None, no_start=False, stdin=None, python_shell=True, preserve_state=False, output_loglevel='debug', ignore_retcode=False, use_vt=False, keep_env=None): ''' Common logic for nspawn.run functions ''' orig_state = state(name) exc = None try: ret = __salt__['container_resource.run']( name, cmd, container_type=__virtualname__, exec_driver=EXEC_DRIVER, output=output, no_start=no_start, stdin=stdin, python_shell=python_shell, output_loglevel=output_loglevel, ignore_retcode=ignore_retcode, use_vt=use_vt, keep_env=keep_env) except Exception: raise finally: # Make sure we stop the container if necessary, even if an exception # was raised. if preserve_state \ and orig_state == 'stopped' \ and state(name) != 'stopped': stop(name) if output in (None, 'all'): return ret else: return ret[output]
def _ping_check(self, ping=1, reconnect=True): """Check whether the connection is still alive using ping(). If the the underlying connection is not active and the ping parameter is set accordingly, the connection will be recreated unless the connection is currently inside a transaction. """ if ping & self._ping: try: # if possible, ping the connection alive = self._con.ping() except (AttributeError, IndexError, TypeError, ValueError): self._ping = 0 # ping() is not available alive = None reconnect = False except Exception: alive = False else: if alive is None: alive = True if alive: reconnect = False if reconnect and not self._transaction: try: # try to reopen the connection con = self._create() except Exception: pass else: self._close() self._store(con) alive = True return alive
Check whether the connection is still alive using ping(). If the the underlying connection is not active and the ping parameter is set accordingly, the connection will be recreated unless the connection is currently inside a transaction.
Below is the the instruction that describes the task: ### Input: Check whether the connection is still alive using ping(). If the the underlying connection is not active and the ping parameter is set accordingly, the connection will be recreated unless the connection is currently inside a transaction. ### Response: def _ping_check(self, ping=1, reconnect=True): """Check whether the connection is still alive using ping(). If the the underlying connection is not active and the ping parameter is set accordingly, the connection will be recreated unless the connection is currently inside a transaction. """ if ping & self._ping: try: # if possible, ping the connection alive = self._con.ping() except (AttributeError, IndexError, TypeError, ValueError): self._ping = 0 # ping() is not available alive = None reconnect = False except Exception: alive = False else: if alive is None: alive = True if alive: reconnect = False if reconnect and not self._transaction: try: # try to reopen the connection con = self._create() except Exception: pass else: self._close() self._store(con) alive = True return alive
def equals_order_sensitive(self, other): """Order-sensitive equality check. *See also* :ref:`eq-order-insensitive` """ # Same short-circuit as BidictBase.__eq__. Factoring out not worth function call overhead. if not isinstance(other, Mapping) or len(self) != len(other): return False return all(i == j for (i, j) in izip(iteritems(self), iteritems(other)))
Order-sensitive equality check. *See also* :ref:`eq-order-insensitive`
Below is the the instruction that describes the task: ### Input: Order-sensitive equality check. *See also* :ref:`eq-order-insensitive` ### Response: def equals_order_sensitive(self, other): """Order-sensitive equality check. *See also* :ref:`eq-order-insensitive` """ # Same short-circuit as BidictBase.__eq__. Factoring out not worth function call overhead. if not isinstance(other, Mapping) or len(self) != len(other): return False return all(i == j for (i, j) in izip(iteritems(self), iteritems(other)))
def set_keras_backend(backend=None, gpu_device_nums=None, num_threads=None): """ Configure Keras backend to use GPU or CPU. Only tensorflow is supported. Parameters ---------- backend : string, optional one of 'tensorflow-default', 'tensorflow-cpu', 'tensorflow-gpu' gpu_device_nums : list of int, optional GPU devices to potentially use num_threads : int, optional Tensorflow threads to use """ os.environ["KERAS_BACKEND"] = "tensorflow" original_backend = backend if not backend: backend = "tensorflow-default" if gpu_device_nums is not None: os.environ["CUDA_VISIBLE_DEVICES"] = ",".join( [str(i) for i in gpu_device_nums]) if backend == "tensorflow-cpu" or gpu_device_nums == []: print("Forcing tensorflow/CPU backend.") os.environ["CUDA_VISIBLE_DEVICES"] = "" device_count = {'CPU': 1, 'GPU': 0} elif backend == "tensorflow-gpu": print("Forcing tensorflow/GPU backend.") device_count = {'CPU': 0, 'GPU': 1} elif backend == "tensorflow-default": print("Forcing tensorflow backend.") device_count = None else: raise ValueError("Unsupported backend: %s" % backend) import tensorflow from keras import backend as K if K.backend() == 'tensorflow': config = tensorflow.ConfigProto(device_count=device_count) config.gpu_options.allow_growth = True if num_threads: config.inter_op_parallelism_threads = num_threads config.intra_op_parallelism_threads = num_threads session = tensorflow.Session(config=config) K.set_session(session) else: if original_backend or gpu_device_nums or num_threads: warnings.warn( "Only tensorflow backend can be customized. Ignoring " " customization. Backend: %s" % K.backend())
Configure Keras backend to use GPU or CPU. Only tensorflow is supported. Parameters ---------- backend : string, optional one of 'tensorflow-default', 'tensorflow-cpu', 'tensorflow-gpu' gpu_device_nums : list of int, optional GPU devices to potentially use num_threads : int, optional Tensorflow threads to use
Below is the the instruction that describes the task: ### Input: Configure Keras backend to use GPU or CPU. Only tensorflow is supported. Parameters ---------- backend : string, optional one of 'tensorflow-default', 'tensorflow-cpu', 'tensorflow-gpu' gpu_device_nums : list of int, optional GPU devices to potentially use num_threads : int, optional Tensorflow threads to use ### Response: def set_keras_backend(backend=None, gpu_device_nums=None, num_threads=None): """ Configure Keras backend to use GPU or CPU. Only tensorflow is supported. Parameters ---------- backend : string, optional one of 'tensorflow-default', 'tensorflow-cpu', 'tensorflow-gpu' gpu_device_nums : list of int, optional GPU devices to potentially use num_threads : int, optional Tensorflow threads to use """ os.environ["KERAS_BACKEND"] = "tensorflow" original_backend = backend if not backend: backend = "tensorflow-default" if gpu_device_nums is not None: os.environ["CUDA_VISIBLE_DEVICES"] = ",".join( [str(i) for i in gpu_device_nums]) if backend == "tensorflow-cpu" or gpu_device_nums == []: print("Forcing tensorflow/CPU backend.") os.environ["CUDA_VISIBLE_DEVICES"] = "" device_count = {'CPU': 1, 'GPU': 0} elif backend == "tensorflow-gpu": print("Forcing tensorflow/GPU backend.") device_count = {'CPU': 0, 'GPU': 1} elif backend == "tensorflow-default": print("Forcing tensorflow backend.") device_count = None else: raise ValueError("Unsupported backend: %s" % backend) import tensorflow from keras import backend as K if K.backend() == 'tensorflow': config = tensorflow.ConfigProto(device_count=device_count) config.gpu_options.allow_growth = True if num_threads: config.inter_op_parallelism_threads = num_threads config.intra_op_parallelism_threads = num_threads session = tensorflow.Session(config=config) K.set_session(session) else: if original_backend or gpu_device_nums or num_threads: warnings.warn( "Only tensorflow backend can be customized. Ignoring " " customization. Backend: %s" % K.backend())