blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
616
content_id
stringlengths
40
40
detected_licenses
sequencelengths
0
112
license_type
stringclasses
2 values
repo_name
stringlengths
5
115
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
777 values
visit_date
timestamp[us]date
2015-08-06 10:31:46
2023-09-06 10:44:38
revision_date
timestamp[us]date
1970-01-01 02:38:32
2037-05-03 13:00:00
committer_date
timestamp[us]date
1970-01-01 02:38:32
2023-09-06 01:08:06
github_id
int64
4.92k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]date
2012-06-04 01:52:49
2023-09-14 21:59:50
gha_created_at
timestamp[us]date
2008-05-22 07:58:19
2023-08-21 12:35:19
gha_language
stringclasses
149 values
src_encoding
stringclasses
26 values
language
stringclasses
1 value
is_vendor
bool
2 classes
is_generated
bool
2 classes
length_bytes
int64
3
10.2M
extension
stringclasses
188 values
content
stringlengths
3
10.2M
authors
sequencelengths
1
1
author_id
stringlengths
1
132
df0e78b60bfc72c412b3fa914ea00ef5c830d3b3
234df74b8d2ff67e1ec1e44df6128e9506ad8ab1
/sgim/apps/catalogo/views.py
f2afa8b7e3b90431b4c76df2159ca9f2a62b26f6
[]
no_license
edxavier/tesis2015
c1289bc648c054edde082e200beda1cfb6e9e27f
d04b20b67f9f1ef2e6d97a18b7bfa6466223384f
refs/heads/master
2021-01-23T03:33:27.149595
2016-02-17T21:51:37
2016-02-17T21:51:37
33,018,981
0
0
null
null
null
null
UTF-8
Python
false
false
2,473
py
from django.shortcuts import render from django.views.generic import View from django.http import JsonResponse from rest_framework import viewsets from .serializers import (TipoDispSerializer, EdificioSerializer, OficinaSerializer, EstadoOpeSerializer, SistemaSerializer, TipoComponenteSerializer, PersonalSerializer, CargoSerializer, EstadoManttoSerializer, TipoIncidenteSerializer) from .models import (TipoDispositivo, Edificio, Oficina, EstadoOperacional, Sistema, TipoComponente, Personal, Cargo, TipoIncidente, EstadoMantenimiento) # Create your views here. class TipoDispoViewSet(viewsets.ModelViewSet): queryset = TipoDispositivo.objects.filter(activo=True) serializer_class = TipoDispSerializer class EdificioViewSet(viewsets.ModelViewSet): queryset = Edificio.objects.filter(activo=True) serializer_class = EdificioSerializer class OficinaViewSet(viewsets.ModelViewSet): queryset = Oficina.objects.filter(activo=True) serializer_class = OficinaSerializer filter_fields = ('edificio',) class EstadoOpeViewSet(viewsets.ModelViewSet): queryset = EstadoOperacional.objects.filter(activo=True) serializer_class = EstadoOpeSerializer class SistemaViewSet(viewsets.ModelViewSet): queryset = Sistema.objects.filter(activo=True) serializer_class = SistemaSerializer class TipoComponenteViewSet(viewsets.ModelViewSet): queryset = TipoComponente.objects.filter(activo=True) serializer_class = TipoComponenteSerializer class PersonalViewSet(viewsets.ModelViewSet): queryset = Personal.objects.filter(activo=True) serializer_class = PersonalSerializer filter_fields = ('cargo',) class CargoViewSet(viewsets.ModelViewSet): queryset = Cargo.objects.filter(activo=True) serializer_class = CargoSerializer class TipoIncidenteViewSet(viewsets.ModelViewSet): queryset = TipoIncidente.objects.filter(activo=True) serializer_class = TipoIncidenteSerializer class EstadoManttoViewSet(viewsets.ModelViewSet): queryset = EstadoMantenimiento.objects.filter(activo=True) serializer_class = EstadoManttoSerializer class Listar(View): def get(self, request, *args, **kwargs): data = TipoDispSerializer(TipoDispositivo.objects.all(), many=True) return JsonResponse({'items':data.data, 'status': "success"})
8d59c63bb569d0b06ceed76e1ba3e92ddfc89ae5
612325535126eaddebc230d8c27af095c8e5cc2f
/src/build/android/pylib/utils/device_dependencies_test.py
40a9c3791fd32e20a2ab0f1ae30c53831e561944
[ "BSD-3-Clause" ]
permissive
TrellixVulnTeam/proto-quic_1V94
1a3a03ac7a08a494b3d4e9857b24bb8f2c2cd673
feee14d96ee95313f236e0f0e3ff7719246c84f7
refs/heads/master
2023-04-01T14:36:53.888576
2019-10-17T02:23:04
2019-10-17T02:23:04
null
0
0
null
null
null
null
UTF-8
Python
false
false
2,048
py
#! /usr/bin/env python # Copyright 2016 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import os import unittest from pylib import constants from pylib.utils import device_dependencies class DevicePathComponentsForTest(unittest.TestCase): def testCheckedInFile(self): test_path = os.path.join(constants.DIR_SOURCE_ROOT, 'foo', 'bar', 'baz.txt') output_directory = os.path.join( constants.DIR_SOURCE_ROOT, 'out-foo', 'Release') self.assertEquals( [None, 'foo', 'bar', 'baz.txt'], device_dependencies.DevicePathComponentsFor( test_path, output_directory)) def testOutputDirectoryFile(self): test_path = os.path.join(constants.DIR_SOURCE_ROOT, 'out-foo', 'Release', 'icudtl.dat') output_directory = os.path.join( constants.DIR_SOURCE_ROOT, 'out-foo', 'Release') self.assertEquals( [None, 'icudtl.dat'], device_dependencies.DevicePathComponentsFor( test_path, output_directory)) def testOutputDirectorySubdirFile(self): test_path = os.path.join(constants.DIR_SOURCE_ROOT, 'out-foo', 'Release', 'test_dir', 'icudtl.dat') output_directory = os.path.join( constants.DIR_SOURCE_ROOT, 'out-foo', 'Release') self.assertEquals( [None, 'test_dir', 'icudtl.dat'], device_dependencies.DevicePathComponentsFor( test_path, output_directory)) def testOutputDirectoryPakFile(self): test_path = os.path.join(constants.DIR_SOURCE_ROOT, 'out-foo', 'Release', 'foo.pak') output_directory = os.path.join( constants.DIR_SOURCE_ROOT, 'out-foo', 'Release') self.assertEquals( [None, 'paks', 'foo.pak'], device_dependencies.DevicePathComponentsFor( test_path, output_directory)) if __name__ == '__main__': unittest.main()
2bd5f95e415955fef9fb486aa9150da591fc22ec
a9a90eae727590f0ccffaa255ffeaa194309fbe9
/Codekata/year.py
7d9971890b54ef34045a6604b8e13f06aa36b4b5
[]
no_license
dhanuskarthikeyan/guvi
18c39674d3ee8e0012caef781d7905e541792174
671d64189f6039ffad8d91cab13942aafa87bf29
refs/heads/master
2020-06-03T00:07:45.041170
2019-07-08T17:39:33
2019-07-08T17:39:33
191,355,054
0
3
null
null
null
null
UTF-8
Python
false
false
62
py
yr=int(input()) if(yr%4==0): print "yes" else: print "no"
555ca6a9c3244b0a09c9f72a46fa206069398e23
7dfa21d74dae975082c6d5deaa01248bac1dcc26
/tools/amd_build/pyHIPIFY/cuda_to_hip_mappings.py
31f69ec6a06383d6a969a1da3d79e906ea76c8e4
[ "BSD-3-Clause", "BSD-2-Clause", "LicenseRef-scancode-generic-cla", "Apache-2.0" ]
permissive
mruberry/pytorch
88cf536ed58d20a409c1e5119be4ec04ec960082
19f73180cfb39eb67110d2a1d541975a49211453
refs/heads/master
2022-02-03T16:25:31.070089
2019-04-22T17:52:28
2019-04-22T17:58:15
130,132,886
4
1
NOASSERTION
2020-01-16T16:51:39
2018-04-18T23:24:38
C++
UTF-8
Python
false
false
216,197
py
import collections from pyHIPIFY.constants import * """ Mapping of CUDA functions, include files, constants, and types to ROCm/HIP equivalents This closely follows the implementation in hipify-clang https://github.com/ROCm-Developer-Tools/HIP/blob/master/hipify-clang/src/CUDA2HipMap.cpp and its structure. There are different maps for fundamental names, include files, identifies, sparse, and PyTorch specific translations. Each of the entries in these maps translates a CUDA string to a tuple containing the ROCm/HIP string, a type and API annotation and - optionally - an annotation if it is not supported in ROCm/HIP yet. """ # List of math functions that should be replaced inside device code only. MATH_TRANSPILATIONS = collections.OrderedDict([ ("std::max", ("::max")), ("std::min", ("::min")), ("std::ceil", ("::ceil")), ("std::floor", ("::floor")), ("std::exp", ("::exp")), ("std::log", ("::log")), ("std::pow", ("::pow")), ("std::fabs", ("::fabs")), ("std::fmod", ("::fmod")), ("std::remainder", ("::remainder")), ]) CUDA_TYPE_NAME_MAP = collections.OrderedDict([ ("CUresult", ("hipError_t", CONV_TYPE, API_DRIVER)), ("cudaError_t", ("hipError_t", CONV_TYPE, API_RUNTIME)), ("CUDA_ARRAY3D_DESCRIPTOR", ("HIP_ARRAY3D_DESCRIPTOR", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CUDA_ARRAY_DESCRIPTOR", ("HIP_ARRAY_DESCRIPTOR", CONV_TYPE, API_DRIVER)), ("CUDA_MEMCPY2D", ("hip_Memcpy2D", CONV_TYPE, API_DRIVER)), ("CUDA_MEMCPY3D", ("HIP_MEMCPY3D", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CUDA_MEMCPY3D_PEER", ("HIP_MEMCPY3D_PEER", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CUDA_POINTER_ATTRIBUTE_P2P_TOKENS", ("HIP_POINTER_ATTRIBUTE_P2P_TOKENS", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CUDA_RESOURCE_DESC", ("HIP_RESOURCE_DESC", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CUDA_RESOURCE_VIEW_DESC", ("HIP_RESOURCE_VIEW_DESC", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CUipcEventHandle", ("hipIpcEventHandle", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CUipcMemHandle", ("hipIpcMemHandle", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CUaddress_mode", ("hipAddress_mode", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CUarray_cubemap_face", ("hipArray_cubemap_face", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CUarray_format", ("hipArray_format", CONV_TYPE, API_DRIVER)), ("CUcomputemode", ("hipComputemode", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CUmem_advise", ("hipMemAdvise", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CUmem_range_attribute", ("hipMemRangeAttribute", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CUctx_flags", ("hipCctx_flags", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CUdevice", ("hipDevice_t", CONV_TYPE, API_DRIVER)), ("CUdevice_attribute_enum", ("hipDeviceAttribute_t", CONV_TYPE, API_DRIVER)), ("CUdevice_attribute", ("hipDeviceAttribute_t", CONV_TYPE, API_DRIVER)), ("CUdeviceptr", ("hipDeviceptr_t", CONV_TYPE, API_DRIVER)), ("CUarray_st", ("hipArray", CONV_TYPE, API_DRIVER)), ("CUarray", ("hipArray *", CONV_TYPE, API_DRIVER)), ("CUdevprop_st", ("hipDeviceProp_t", CONV_TYPE, API_DRIVER)), ("CUdevprop", ("hipDeviceProp_t", CONV_TYPE, API_DRIVER)), ("CUfunction", ("hipFunction_t", CONV_TYPE, API_DRIVER)), ("CUgraphicsResource", ("hipGraphicsResource_t", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CUmipmappedArray", ("hipMipmappedArray_t", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CUfunction_attribute", ("hipFuncAttribute_t", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CUfunction_attribute_enum", ("hipFuncAttribute_t", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CUgraphicsMapResourceFlags", ("hipGraphicsMapFlags", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CUgraphicsMapResourceFlags_enum", ("hipGraphicsMapFlags", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CUgraphicsRegisterFlags", ("hipGraphicsRegisterFlags", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CUgraphicsRegisterFlags_enum", ("hipGraphicsRegisterFlags", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CUoccupancy_flags", ("hipOccupancyFlags", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CUoccupancy_flags_enum", ("hipOccupancyFlags", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CUfunc_cache_enum", ("hipFuncCache", CONV_TYPE, API_DRIVER)), ("CUfunc_cache", ("hipFuncCache", CONV_TYPE, API_DRIVER)), ("CUipcMem_flags", ("hipIpcMemFlags", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CUipcMem_flags_enum", ("hipIpcMemFlags", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CUjit_cacheMode", ("hipJitCacheMode", CONV_JIT, API_DRIVER, HIP_UNSUPPORTED)), ("CUjit_cacheMode_enum", ("hipJitCacheMode", CONV_JIT, API_DRIVER, HIP_UNSUPPORTED)), ("CUjit_fallback", ("hipJitFallback", CONV_JIT, API_DRIVER, HIP_UNSUPPORTED)), ("CUjit_fallback_enum", ("hipJitFallback", CONV_JIT, API_DRIVER, HIP_UNSUPPORTED)), ("CUjit_option", ("hipJitOption", CONV_JIT, API_DRIVER)), ("CUjit_option_enum", ("hipJitOption", CONV_JIT, API_DRIVER)), ("CUjit_target", ("hipJitTarget", CONV_JIT, API_DRIVER, HIP_UNSUPPORTED)), ("CUjit_target_enum", ("hipJitTarget", CONV_JIT, API_DRIVER, HIP_UNSUPPORTED)), ("CUjitInputType", ("hipJitInputType", CONV_JIT, API_DRIVER, HIP_UNSUPPORTED)), ("CUjitInputType_enum", ("hipJitInputType", CONV_JIT, API_DRIVER, HIP_UNSUPPORTED)), ("CUlimit", ("hipLimit_t", CONV_TYPE, API_DRIVER)), ("CUlimit_enum", ("hipLimit_t", CONV_TYPE, API_DRIVER)), ("CUmemAttach_flags", ("hipMemAttachFlags_t", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CUmemAttach_flags_enum", ("hipMemAttachFlags_t", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CUmemorytype", ("hipMemType_t", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CUmemorytype_enum", ("hipMemType_t", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CUresourcetype", ("hipResourceType", CONV_TEX, API_DRIVER, HIP_UNSUPPORTED)), ("CUresourcetype_enum", ("hipResourceType", CONV_TEX, API_DRIVER, HIP_UNSUPPORTED)), ("CUresourceViewFormat", ("hipResourceViewFormat", CONV_TEX, API_DRIVER)), ("CUresourceViewFormat_enum", ("hipResourceViewFormat", CONV_TEX, API_DRIVER)), ("CUsharedconfig", ("hipSharedMemConfig", CONV_TYPE, API_DRIVER)), ("CUsharedconfig_enum", ("hipSharedMemConfig", CONV_TYPE, API_DRIVER)), ("CUcontext", ("hipCtx_t", CONV_TYPE, API_DRIVER)), ("CUmodule", ("hipModule_t", CONV_TYPE, API_DRIVER)), ("CUstream", ("hipStream_t", CONV_TYPE, API_DRIVER)), ("CUstream_st", ("ihipStream_t", CONV_TYPE, API_DRIVER)), ("CUstreamCallback", ("hipStreamCallback_t", CONV_TYPE, API_DRIVER)), ("CUsurfObject", ("hipSurfaceObject", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CUsurfref", ("hipSurfaceReference_t", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CUtexObject", ("hipTextureObject_t", CONV_TYPE, API_DRIVER)), ("CUtexref", ("textureReference", CONV_TYPE, API_DRIVER)), ("CUstream_flags", ("hipStreamFlags", CONV_TYPE, API_DRIVER)), ("CUstreamWaitValue_flags", ("hipStreamWaitValueFlags", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CUstreamWriteValue_flags", ("hipStreamWriteValueFlags", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CUstreamBatchMemOpType", ("hipStreamBatchMemOpType", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CUdevice_P2PAttribute", ("hipDeviceP2PAttribute", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CUevent", ("hipEvent_t", CONV_TYPE, API_DRIVER)), ("CUevent_flags", ("hipEventFlags", CONV_EVENT, API_DRIVER, HIP_UNSUPPORTED)), ("CUfilter_mode", ("hipTextureFilterMode", CONV_TEX, API_DRIVER)), ("CUGLDeviceList", ("hipGLDeviceList", CONV_GL, API_DRIVER, HIP_UNSUPPORTED)), ("CUGLmap_flags", ("hipGLMapFlags", CONV_GL, API_DRIVER, HIP_UNSUPPORTED)), ("CUd3d9DeviceList", ("hipD3D9DeviceList", CONV_D3D9, API_DRIVER, HIP_UNSUPPORTED)), ("CUd3d9map_flags", ("hipD3D9MapFlags", CONV_D3D9, API_DRIVER, HIP_UNSUPPORTED)), ("CUd3d9register_flags", ("hipD3D9RegisterFlags", CONV_D3D9, API_DRIVER, HIP_UNSUPPORTED)), ("CUd3d10DeviceList", ("hipd3d10DeviceList", CONV_D3D10, API_DRIVER, HIP_UNSUPPORTED)), ("CUd3d10map_flags", ("hipD3D10MapFlags", CONV_D3D10, API_DRIVER, HIP_UNSUPPORTED)), ("CUd3d10register_flags", ("hipD3D10RegisterFlags", CONV_D3D10, API_DRIVER, HIP_UNSUPPORTED)), ("CUd3d11DeviceList", ("hipd3d11DeviceList", CONV_D3D11, API_DRIVER, HIP_UNSUPPORTED)), ("CUeglStreamConnection_st", ("hipEglStreamConnection", CONV_EGL, API_DRIVER, HIP_UNSUPPORTED)), ("CUeglStreamConnection", ("hipEglStreamConnection", CONV_EGL, API_DRIVER, HIP_UNSUPPORTED)), ("libraryPropertyType_t", ("hipLibraryPropertyType_t", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("libraryPropertyType", ("hipLibraryPropertyType_t", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaStreamCallback_t", ("hipStreamCallback_t", CONV_TYPE, API_RUNTIME)), ("cudaArray", ("hipArray", CONV_MEM, API_RUNTIME)), ("cudaArray_t", ("hipArray_t", CONV_MEM, API_RUNTIME)), ("cudaArray_const_t", ("hipArray_const_t", CONV_MEM, API_RUNTIME)), ("cudaMipmappedArray_t", ("hipMipmappedArray_t", CONV_MEM, API_RUNTIME)), ("cudaMipmappedArray_const_t", ("hipMipmappedArray_const_t", CONV_MEM, API_RUNTIME)), ("cudaArrayDefault", ("hipArrayDefault", CONV_MEM, API_RUNTIME)), ("cudaArrayLayered", ("hipArrayLayered", CONV_MEM, API_RUNTIME)), ("cudaArraySurfaceLoadStore", ("hipArraySurfaceLoadStore", CONV_MEM, API_RUNTIME)), ("cudaArrayCubemap", ("hipArrayCubemap", CONV_MEM, API_RUNTIME)), ("cudaArrayTextureGather", ("hipArrayTextureGather", CONV_MEM, API_RUNTIME)), ("cudaMemoryAdvise", ("hipMemAdvise", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaMemRangeAttribute", ("hipMemRangeAttribute", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaMemcpyKind", ("hipMemcpyKind", CONV_MEM, API_RUNTIME)), ("cudaMemoryType", ("hipMemoryType", CONV_MEM, API_RUNTIME)), ("cudaExtent", ("hipExtent", CONV_MEM, API_RUNTIME)), ("cudaPitchedPtr", ("hipPitchedPtr", CONV_MEM, API_RUNTIME)), ("cudaPos", ("hipPos", CONV_MEM, API_RUNTIME)), ("cudaEvent_t", ("hipEvent_t", CONV_TYPE, API_RUNTIME)), ("cudaStream_t", ("hipStream_t", CONV_TYPE, API_RUNTIME)), ("cudaPointerAttributes", ("hipPointerAttribute_t", CONV_TYPE, API_RUNTIME)), ("cudaDeviceAttr", ("hipDeviceAttribute_t", CONV_TYPE, API_RUNTIME)), ("cudaDeviceProp", ("hipDeviceProp_t", CONV_TYPE, API_RUNTIME)), ("cudaDeviceP2PAttr", ("hipDeviceP2PAttribute", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaComputeMode", ("hipComputeMode", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaFuncCache", ("hipFuncCache_t", CONV_CACHE, API_RUNTIME)), ("cudaFuncAttributes", ("hipFuncAttributes", CONV_EXEC, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaSharedMemConfig", ("hipSharedMemConfig", CONV_TYPE, API_RUNTIME)), ("cudaLimit", ("hipLimit_t", CONV_TYPE, API_RUNTIME)), ("cudaOutputMode", ("hipOutputMode", CONV_OTHER, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaTextureReadMode", ("hipTextureReadMode", CONV_TEX, API_RUNTIME)), ("cudaTextureFilterMode", ("hipTextureFilterMode", CONV_TEX, API_RUNTIME)), ("cudaChannelFormatKind", ("hipChannelFormatKind", CONV_TEX, API_RUNTIME)), ("cudaChannelFormatDesc", ("hipChannelFormatDesc", CONV_TEX, API_RUNTIME)), ("cudaResourceDesc", ("hipResourceDesc", CONV_TEX, API_RUNTIME)), ("cudaResourceViewDesc", ("hipResourceViewDesc", CONV_TEX, API_RUNTIME)), ("cudaTextureDesc", ("hipTextureDesc", CONV_TEX, API_RUNTIME)), ("surfaceReference", ("hipSurfaceReference", CONV_SURFACE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaTextureObject_t", ("hipTextureObject_t", CONV_TEX, API_RUNTIME)), ("cudaResourceType", ("hipResourceType", CONV_TEX, API_RUNTIME)), ("cudaResourceViewFormat", ("hipResourceViewFormat", CONV_TEX, API_RUNTIME)), ("cudaTextureAddressMode", ("hipTextureAddressMode", CONV_TEX, API_RUNTIME)), ("cudaSurfaceBoundaryMode", ("hipSurfaceBoundaryMode", CONV_SURFACE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaSurfaceFormatMode", ("hipSurfaceFormatMode", CONV_SURFACE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaTextureType1D", ("hipTextureType1D", CONV_TEX, API_RUNTIME)), ("cudaTextureType2D", ("hipTextureType2D", CONV_TEX, API_RUNTIME)), ("cudaTextureType3D", ("hipTextureType3D", CONV_TEX, API_RUNTIME)), ("cudaTextureTypeCubemap", ("hipTextureTypeCubemap", CONV_TEX, API_RUNTIME)), ("cudaTextureType1DLayered", ("hipTextureType1DLayered", CONV_TEX, API_RUNTIME)), ("cudaTextureType2DLayered", ("hipTextureType2DLayered", CONV_TEX, API_RUNTIME)), ("cudaTextureTypeCubemapLayered", ("hipTextureTypeCubemapLayered", CONV_TEX, API_RUNTIME)), ("cudaIpcEventHandle_t", ("hipIpcEventHandle_t", CONV_TYPE, API_RUNTIME)), ("cudaIpcEventHandle_st", ("hipIpcEventHandle_t", CONV_TYPE, API_RUNTIME)), ("cudaIpcMemHandle_t", ("hipIpcMemHandle_t", CONV_TYPE, API_RUNTIME)), ("cudaIpcMemHandle_st", ("hipIpcMemHandle_t", CONV_TYPE, API_RUNTIME)), ("cudaGraphicsCubeFace", ("hipGraphicsCubeFace", CONV_GRAPHICS, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaGraphicsMapFlags", ("hipGraphicsMapFlags", CONV_GRAPHICS, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaGraphicsRegisterFlags", ("hipGraphicsRegisterFlags", CONV_GRAPHICS, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaGLDeviceList", ("hipGLDeviceList", CONV_GL, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaGLMapFlags", ("hipGLMapFlags", CONV_GL, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaD3D9DeviceList", ("hipD3D9DeviceList", CONV_D3D9, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaD3D9MapFlags", ("hipD3D9MapFlags", CONV_D3D9, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaD3D9RegisterFlags", ("hipD3D9RegisterFlags", CONV_D3D9, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaD3D10DeviceList", ("hipd3d10DeviceList", CONV_D3D10, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaD3D10MapFlags", ("hipD3D10MapFlags", CONV_D3D10, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaD3D10RegisterFlags", ("hipD3D10RegisterFlags", CONV_D3D10, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaD3D11DeviceList", ("hipd3d11DeviceList", CONV_D3D11, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaEglStreamConnection", ("hipEglStreamConnection", CONV_EGL, API_RUNTIME, HIP_UNSUPPORTED)), ("cublasHandle_t", ("rocblas_handle", CONV_TYPE, API_BLAS)), ("cublasOperation_t", ("rocblas_operation", CONV_TYPE, API_BLAS)), ("cublasStatus_t", ("rocblas_status", CONV_TYPE, API_BLAS)), ("cublasFillMode_t", ("rocblas_fill", CONV_TYPE, API_BLAS)), ("cublasDiagType_t", ("rocblas_diagonal", CONV_TYPE, API_BLAS)), ("cublasSideMode_t", ("rocblas_side", CONV_TYPE, API_BLAS)), ("cublasPointerMode_t", ("rocblas_pointer_mode", CONV_TYPE, API_BLAS)), ("cublasAtomicsMode_t", ("rocblas_atomics_mode", CONV_TYPE, API_BLAS, HIP_UNSUPPORTED)), ("cublasDataType_t", ("rocblas_data_type", CONV_TYPE, API_BLAS, HIP_UNSUPPORTED)), ("curandStatus", ("hiprandStatus_t", CONV_TYPE, API_RAND)), ("curandStatus_t", ("hiprandStatus_t", CONV_TYPE, API_RAND)), ("curandRngType", ("hiprandRngType_t", CONV_TYPE, API_RAND)), ("curandRngType_t", ("hiprandRngType_t", CONV_TYPE, API_RAND)), ("curandGenerator_st", ("hiprandGenerator_st", CONV_TYPE, API_RAND)), ("curandGenerator_t", ("hiprandGenerator_t", CONV_TYPE, API_RAND)), ("curandDirectionVectorSet", ("hiprandDirectionVectorSet_t", CONV_TYPE, API_RAND, HIP_UNSUPPORTED)), ("curandDirectionVectorSet_t", ("hiprandDirectionVectorSet_t", CONV_TYPE, API_RAND, HIP_UNSUPPORTED)), ("curandOrdering", ("hiprandOrdering_t", CONV_TYPE, API_RAND, HIP_UNSUPPORTED)), ("curandOrdering_t", ("hiprandOrdering_t", CONV_TYPE, API_RAND, HIP_UNSUPPORTED)), ("curandDistribution_st", ("hiprandDistribution_st", CONV_TYPE, API_RAND, HIP_UNSUPPORTED)), ("curandHistogramM2V_st", ("hiprandDistribution_st", CONV_TYPE, API_RAND, HIP_UNSUPPORTED)), ("curandDistribution_t", ("hiprandDistribution_t", CONV_TYPE, API_RAND, HIP_UNSUPPORTED)), ("curandHistogramM2V_t", ("hiprandDistribution_t", CONV_TYPE, API_RAND, HIP_UNSUPPORTED)), ("curandDistributionShift_st", ("hiprandDistributionShift_st", CONV_TYPE, API_RAND, HIP_UNSUPPORTED)), ("curandDistributionShift_t", ("hiprandDistributionShift_t", CONV_TYPE, API_RAND, HIP_UNSUPPORTED)), ("curandDistributionM2Shift_st", ("hiprandDistributionM2Shift_st", CONV_TYPE, API_RAND, HIP_UNSUPPORTED)), ("curandDistributionM2Shift_t", ("hiprandDistributionM2Shift_t", CONV_TYPE, API_RAND, HIP_UNSUPPORTED)), ("curandHistogramM2_st", ("hiprandHistogramM2_st", CONV_TYPE, API_RAND, HIP_UNSUPPORTED)), ("curandHistogramM2_t", ("hiprandHistogramM2_t", CONV_TYPE, API_RAND, HIP_UNSUPPORTED)), ("curandHistogramM2K_st", ("hiprandHistogramM2K_st", CONV_TYPE, API_RAND, HIP_UNSUPPORTED)), ("curandHistogramM2K_t", ("hiprandHistogramM2K_t", CONV_TYPE, API_RAND, HIP_UNSUPPORTED)), ("curandDiscreteDistribution_st", ("hiprandDiscreteDistribution_st", CONV_TYPE, API_RAND)), ("curandDiscreteDistribution_t", ("hiprandDiscreteDistribution_t", CONV_TYPE, API_RAND)), ("curandMethod", ("hiprandMethod_t", CONV_TYPE, API_RAND, HIP_UNSUPPORTED)), ("curandMethod_t", ("hiprandMethod_t", CONV_TYPE, API_RAND, HIP_UNSUPPORTED)), ("curandDirectionVectors32_t", ("hiprandDirectionVectors32_t", CONV_TYPE, API_RAND)), ("curandDirectionVectors64_t", ("hiprandDirectionVectors64_t", CONV_TYPE, API_RAND, HIP_UNSUPPORTED)), ("curandStateMtgp32_t", ("hiprandStateMtgp32_t", CONV_TYPE, API_RAND)), ("curandStateMtgp32", ("hiprandStateMtgp32_t", CONV_TYPE, API_RAND)), ("curandStateScrambledSobol64_t", ("hiprandStateScrambledSobol64_t", CONV_TYPE, API_RAND, HIP_UNSUPPORTED)), ("curandStateSobol64_t", ("hiprandStateSobol64_t", CONV_TYPE, API_RAND, HIP_UNSUPPORTED)), ("curandStateScrambledSobol32_t", ("hiprandStateScrambledSobol32_t", CONV_TYPE, API_RAND, HIP_UNSUPPORTED)), ("curandStateSobol32_t", ("hiprandStateSobol32_t", CONV_TYPE, API_RAND)), ("curandStateMRG32k3a_t", ("hiprandStateMRG32k3a_t", CONV_TYPE, API_RAND)), ("curandStatePhilox4_32_10_t", ("hiprandStatePhilox4_32_10_t", CONV_TYPE, API_RAND)), ("curandStateXORWOW_t", ("hiprandStateXORWOW_t", CONV_TYPE, API_RAND)), ("curandState_t", ("hiprandState_t", CONV_TYPE, API_RAND)), ("curandState", ("hiprandState_t", CONV_TYPE, API_RAND)), ]) CUDA_INCLUDE_MAP = collections.OrderedDict([ # since pytorch uses "\b{pattern}\b" as the actual re pattern, # patterns listed here have to begin and end with alnum chars ("include <cuda.h", ("include <hip/hip_runtime.h", CONV_INCLUDE_CUDA_MAIN_H, API_DRIVER)), ('include "cuda.h', ('include "hip/hip_runtime.h', CONV_INCLUDE_CUDA_MAIN_H, API_DRIVER)), ("cuda_runtime.h", ("hip/hip_runtime.h", CONV_INCLUDE_CUDA_MAIN_H, API_RUNTIME)), ("cuda_runtime_api.h", ("hip/hip_runtime_api.h", CONV_INCLUDE, API_RUNTIME)), ("channel_descriptor.h", ("hip/channel_descriptor.h", CONV_INCLUDE, API_RUNTIME)), ("device_functions.h", ("hip/device_functions.h", CONV_INCLUDE, API_RUNTIME)), ("driver_types.h", ("hip/driver_types.h", CONV_INCLUDE, API_RUNTIME)), ("cuComplex.h", ("hip/hip_complex.h", CONV_INCLUDE, API_RUNTIME)), ("cuda_fp16.h", ("hip/hip_fp16.h", CONV_INCLUDE, API_RUNTIME)), ("cuda_texture_types.h", ("hip/hip_texture_types.h", CONV_INCLUDE, API_RUNTIME)), ("vector_types.h", ("hip/hip_vector_types.h", CONV_INCLUDE, API_RUNTIME)), ("cublas.h", ("rocblas.h", CONV_INCLUDE_CUDA_MAIN_H, API_BLAS)), ("cublas_v2.h", ("rocblas.h", CONV_INCLUDE_CUDA_MAIN_H, API_BLAS)), ("curand.h", ("hiprand.h", CONV_INCLUDE_CUDA_MAIN_H, API_RAND)), ("curand_kernel.h", ("hiprand_kernel.h", CONV_INCLUDE, API_RAND)), ("curand_discrete.h", ("hiprand_kernel.h", CONV_INCLUDE, API_RAND)), ("curand_discrete2.h", ("hiprand_kernel.h", CONV_INCLUDE, API_RAND)), ("curand_globals.h", ("hiprand_kernel.h", CONV_INCLUDE, API_RAND)), ("curand_lognormal.h", ("hiprand_kernel.h", CONV_INCLUDE, API_RAND)), ("curand_mrg32k3a.h", ("hiprand_kernel.h", CONV_INCLUDE, API_RAND)), ("curand_mtgp32.h", ("hiprand_kernel.h", CONV_INCLUDE, API_RAND)), ("curand_mtgp32_host.h", ("hiprand_mtgp32_host.h", CONV_INCLUDE, API_RAND)), ("curand_mtgp32_kernel.h", ("hiprand_kernel.h", CONV_INCLUDE, API_RAND)), ("curand_mtgp32dc_p_11213.h", ("rocrand_mtgp32_11213.h", CONV_INCLUDE, API_RAND)), ("curand_normal.h", ("hiprand_kernel.h", CONV_INCLUDE, API_RAND)), ("curand_normal_static.h", ("hiprand_kernel.h", CONV_INCLUDE, API_RAND)), ("curand_philox4x32_x.h", ("hiprand_kernel.h", CONV_INCLUDE, API_RAND)), ("curand_poisson.h", ("hiprand_kernel.h", CONV_INCLUDE, API_RAND)), ("curand_precalc.h", ("hiprand_kernel.h", CONV_INCLUDE, API_RAND)), ("curand_uniform.h", ("hiprand_kernel.h", CONV_INCLUDE, API_RAND)), ("cusparse.h", ("hipsparse.h", CONV_INCLUDE, API_RAND)), ("cufft.h", ("hipfft.h", CONV_INCLUDE, API_BLAS)), ("cufftXt.h", ("hipfft.h", CONV_INCLUDE, API_BLAS)), ]) CUDA_IDENTIFIER_MAP = collections.OrderedDict([ ("__CUDACC__", ("__HIPCC__", CONV_DEF, API_RUNTIME)), ("CUDA_ERROR_INVALID_CONTEXT", ("hipErrorInvalidContext", CONV_TYPE, API_DRIVER)), ("CUDA_ERROR_CONTEXT_ALREADY_CURRENT", ("hipErrorContextAlreadyCurrent", CONV_TYPE, API_DRIVER)), ("CUDA_ERROR_ARRAY_IS_MAPPED", ("hipErrorArrayIsMapped", CONV_TYPE, API_DRIVER)), ("CUDA_ERROR_ALREADY_MAPPED", ("hipErrorAlreadyMapped", CONV_TYPE, API_DRIVER)), ("CUDA_ERROR_ALREADY_ACQUIRED", ("hipErrorAlreadyAcquired", CONV_TYPE, API_DRIVER)), ("CUDA_ERROR_NOT_MAPPED", ("hipErrorNotMapped", CONV_TYPE, API_DRIVER)), ("CUDA_ERROR_NOT_MAPPED_AS_ARRAY", ("hipErrorNotMappedAsArray", CONV_TYPE, API_DRIVER)), ("CUDA_ERROR_NOT_MAPPED_AS_POINTER", ("hipErrorNotMappedAsPointer", CONV_TYPE, API_DRIVER)), ("CUDA_ERROR_CONTEXT_ALREADY_IN_USE", ("hipErrorContextAlreadyInUse", CONV_TYPE, API_DRIVER)), ("CUDA_ERROR_INVALID_SOURCE", ("hipErrorInvalidSource", CONV_TYPE, API_DRIVER)), ("CUDA_ERROR_FILE_NOT_FOUND", ("hipErrorFileNotFound", CONV_TYPE, API_DRIVER)), ("CUDA_ERROR_NOT_FOUND", ("hipErrorNotFound", CONV_TYPE, API_DRIVER)), ("CUDA_ERROR_LAUNCH_INCOMPATIBLE_TEXTURING", ("hipErrorLaunchIncompatibleTexturing", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CUDA_ERROR_PRIMARY_CONTEXT_ACTIVE", ("hipErrorPrimaryContextActive", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CUDA_ERROR_CONTEXT_IS_DESTROYED", ("hipErrorContextIsDestroyed", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CUDA_ERROR_NOT_PERMITTED", ("hipErrorNotPermitted", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CUDA_ERROR_NOT_SUPPORTED", ("hipErrorNotSupported", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("cudaErrorMissingConfiguration", ("hipErrorMissingConfiguration", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaErrorPriorLaunchFailure", ("hipErrorPriorLaunchFailure", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaErrorInvalidDeviceFunction", ("hipErrorInvalidDeviceFunction", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaErrorInvalidConfiguration", ("hipErrorInvalidConfiguration", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaErrorInvalidPitchValue", ("hipErrorInvalidPitchValue", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaErrorInvalidSymbol", ("hipErrorInvalidSymbol", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaErrorInvalidHostPointer", ("hipErrorInvalidHostPointer", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaErrorInvalidDevicePointer", ("hipErrorInvalidDevicePointer", CONV_TYPE, API_RUNTIME)), ("cudaErrorInvalidTexture", ("hipErrorInvalidTexture", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaErrorInvalidTextureBinding", ("hipErrorInvalidTextureBinding", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaErrorInvalidChannelDescriptor", ("hipErrorInvalidChannelDescriptor", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaErrorInvalidMemcpyDirection", ("hipErrorInvalidMemcpyDirection", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaErrorAddressOfConstant", ("hipErrorAddressOfConstant", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaErrorTextureFetchFailed", ("hipErrorTextureFetchFailed", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaErrorTextureNotBound", ("hipErrorTextureNotBound", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaErrorSynchronizationError", ("hipErrorSynchronizationError", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaErrorInvalidFilterSetting", ("hipErrorInvalidFilterSetting", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaErrorInvalidNormSetting", ("hipErrorInvalidNormSetting", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaErrorMixedDeviceExecution", ("hipErrorMixedDeviceExecution", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaErrorNotYetImplemented", ("hipErrorNotYetImplemented", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaErrorMemoryValueTooLarge", ("hipErrorMemoryValueTooLarge", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaErrorInsufficientDriver", ("hipErrorInsufficientDriver", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaErrorSetOnActiveProcess", ("hipErrorSetOnActiveProcess", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaErrorInvalidSurface", ("hipErrorInvalidSurface", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaErrorDuplicateVariableName", ("hipErrorDuplicateVariableName", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaErrorDuplicateTextureName", ("hipErrorDuplicateTextureName", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaErrorDuplicateSurfaceName", ("hipErrorDuplicateSurfaceName", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaErrorDevicesUnavailable", ("hipErrorDevicesUnavailable", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaErrorIncompatibleDriverContext", ("hipErrorIncompatibleDriverContext", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaErrorDeviceAlreadyInUse", ("hipErrorDeviceAlreadyInUse", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaErrorLaunchMaxDepthExceeded", ("hipErrorLaunchMaxDepthExceeded", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaErrorLaunchFileScopedTex", ("hipErrorLaunchFileScopedTex", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaErrorLaunchFileScopedSurf", ("hipErrorLaunchFileScopedSurf", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaErrorSyncDepthExceeded", ("hipErrorSyncDepthExceeded", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaErrorLaunchPendingCountExceeded", ("hipErrorLaunchPendingCountExceeded", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaErrorNotPermitted", ("hipErrorNotPermitted", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaErrorNotSupported", ("hipErrorNotSupported", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaErrorStartupFailure", ("hipErrorStartupFailure", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaErrorApiFailureBase", ("hipErrorApiFailureBase", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("CUDA_SUCCESS", ("hipSuccess", CONV_TYPE, API_DRIVER)), ("cudaSuccess", ("hipSuccess", CONV_TYPE, API_RUNTIME)), ("CUDA_ERROR_INVALID_VALUE", ("hipErrorInvalidValue", CONV_TYPE, API_DRIVER)), ("cudaErrorInvalidValue", ("hipErrorInvalidValue", CONV_TYPE, API_RUNTIME)), ("CUDA_ERROR_OUT_OF_MEMORY", ("hipErrorMemoryAllocation", CONV_TYPE, API_DRIVER)), ("cudaErrorMemoryAllocation", ("hipErrorMemoryAllocation", CONV_TYPE, API_RUNTIME)), ("CUDA_ERROR_NOT_INITIALIZED", ("hipErrorNotInitialized", CONV_TYPE, API_DRIVER)), ("cudaErrorInitializationError", ("hipErrorInitializationError", CONV_TYPE, API_RUNTIME)), ("CUDA_ERROR_DEINITIALIZED", ("hipErrorDeinitialized", CONV_TYPE, API_DRIVER)), ("cudaErrorCudartUnloading", ("hipErrorDeinitialized", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("CUDA_ERROR_PROFILER_DISABLED", ("hipErrorProfilerDisabled", CONV_TYPE, API_DRIVER)), ("cudaErrorProfilerDisabled", ("hipErrorProfilerDisabled", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("CUDA_ERROR_PROFILER_NOT_INITIALIZED", ("hipErrorProfilerNotInitialized", CONV_TYPE, API_DRIVER)), ("cudaErrorProfilerNotInitialized", ("hipErrorProfilerNotInitialized", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("CUDA_ERROR_PROFILER_ALREADY_STARTED", ("hipErrorProfilerAlreadyStarted", CONV_TYPE, API_DRIVER)), ("cudaErrorProfilerAlreadyStarted", ("hipErrorProfilerAlreadyStarted", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("CUDA_ERROR_PROFILER_ALREADY_STOPPED", ("hipErrorProfilerAlreadyStopped", CONV_TYPE, API_DRIVER)), ("cudaErrorProfilerAlreadyStopped", ("hipErrorProfilerAlreadyStopped", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("CUDA_ERROR_NO_DEVICE", ("hipErrorNoDevice", CONV_TYPE, API_DRIVER)), ("cudaErrorNoDevice", ("hipErrorNoDevice", CONV_TYPE, API_RUNTIME)), ("CUDA_ERROR_INVALID_DEVICE", ("hipErrorInvalidDevice", CONV_TYPE, API_DRIVER)), ("cudaErrorInvalidDevice", ("hipErrorInvalidDevice", CONV_TYPE, API_RUNTIME)), ("CUDA_ERROR_INVALID_IMAGE", ("hipErrorInvalidImage", CONV_TYPE, API_DRIVER)), ("cudaErrorInvalidKernelImage", ("hipErrorInvalidImage", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("CUDA_ERROR_MAP_FAILED", ("hipErrorMapFailed", CONV_TYPE, API_DRIVER)), ("cudaErrorMapBufferObjectFailed", ("hipErrorMapFailed", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("CUDA_ERROR_UNMAP_FAILED", ("hipErrorUnmapFailed", CONV_TYPE, API_DRIVER)), ("cudaErrorUnmapBufferObjectFailed", ("hipErrorUnmapFailed", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("CUDA_ERROR_NO_BINARY_FOR_GPU", ("hipErrorNoBinaryForGpu", CONV_TYPE, API_DRIVER)), ("cudaErrorNoKernelImageForDevice", ("hipErrorNoBinaryForGpu", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("CUDA_ERROR_ECC_UNCORRECTABLE", ("hipErrorECCNotCorrectable", CONV_TYPE, API_DRIVER)), ("cudaErrorECCUncorrectable", ("hipErrorECCNotCorrectable", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("CUDA_ERROR_UNSUPPORTED_LIMIT", ("hipErrorUnsupportedLimit", CONV_TYPE, API_DRIVER)), ("cudaErrorUnsupportedLimit", ("hipErrorUnsupportedLimit", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("CUDA_ERROR_PEER_ACCESS_UNSUPPORTED", ("hipErrorPeerAccessUnsupported", CONV_TYPE, API_DRIVER)), ("cudaErrorPeerAccessUnsupported", ("hipErrorPeerAccessUnsupported", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("CUDA_ERROR_INVALID_PTX", ("hipErrorInvalidKernelFile", CONV_TYPE, API_DRIVER)), ("cudaErrorInvalidPtx", ("hipErrorInvalidKernelFile", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("CUDA_ERROR_INVALID_GRAPHICS_CONTEXT", ("hipErrorInvalidGraphicsContext", CONV_TYPE, API_DRIVER)), ("cudaErrorInvalidGraphicsContext", ("hipErrorInvalidGraphicsContext", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("CUDA_ERROR_NVLINK_UNCORRECTABLE", ("hipErrorNvlinkUncorrectable", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("cudaErrorNvlinkUncorrectable", ("hipErrorNvlinkUncorrectable", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("CUDA_ERROR_SHARED_OBJECT_SYMBOL_NOT_FOUND", ("hipErrorSharedObjectSymbolNotFound", CONV_TYPE, API_DRIVER)), ("cudaErrorSharedObjectSymbolNotFound", ("hipErrorSharedObjectSymbolNotFound", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("CUDA_ERROR_SHARED_OBJECT_INIT_FAILED", ("hipErrorSharedObjectInitFailed", CONV_TYPE, API_DRIVER)), ("cudaErrorSharedObjectInitFailed", ("hipErrorSharedObjectInitFailed", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("CUDA_ERROR_OPERATING_SYSTEM", ("hipErrorOperatingSystem", CONV_TYPE, API_DRIVER)), ("cudaErrorOperatingSystem", ("hipErrorOperatingSystem", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("CUDA_ERROR_INVALID_HANDLE", ("hipErrorInvalidResourceHandle", CONV_TYPE, API_DRIVER)), ("cudaErrorInvalidResourceHandle", ("hipErrorInvalidResourceHandle", CONV_TYPE, API_RUNTIME)), ("CUDA_ERROR_NOT_READY", ("hipErrorNotReady", CONV_TYPE, API_DRIVER)), ("cudaErrorNotReady", ("hipErrorNotReady", CONV_TYPE, API_RUNTIME)), ("CUDA_ERROR_ILLEGAL_ADDRESS", ("hipErrorIllegalAddress", CONV_TYPE, API_DRIVER)), ("cudaErrorIllegalAddress", ("hipErrorIllegalAddress", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("CUDA_ERROR_LAUNCH_OUT_OF_RESOURCES", ("hipErrorLaunchOutOfResources", CONV_TYPE, API_DRIVER)), ("cudaErrorLaunchOutOfResources", ("hipErrorLaunchOutOfResources", CONV_TYPE, API_RUNTIME)), ("CUDA_ERROR_LAUNCH_TIMEOUT", ("hipErrorLaunchTimeOut", CONV_TYPE, API_DRIVER)), ("cudaErrorLaunchTimeout", ("hipErrorLaunchTimeOut", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("CUDA_ERROR_PEER_ACCESS_ALREADY_ENABLED", ("hipErrorPeerAccessAlreadyEnabled", CONV_TYPE, API_DRIVER)), ("cudaErrorPeerAccessAlreadyEnabled", ("hipErrorPeerAccessAlreadyEnabled", CONV_TYPE, API_RUNTIME)), ("CUDA_ERROR_PEER_ACCESS_NOT_ENABLED", ("hipErrorPeerAccessNotEnabled", CONV_TYPE, API_DRIVER)), ("cudaErrorPeerAccessNotEnabled", ("hipErrorPeerAccessNotEnabled", CONV_TYPE, API_RUNTIME)), ("CUDA_ERROR_ASSERT", ("hipErrorAssert", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("cudaErrorAssert", ("hipErrorAssert", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("CUDA_ERROR_TOO_MANY_PEERS", ("hipErrorTooManyPeers", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("cudaErrorTooManyPeers", ("hipErrorTooManyPeers", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("CUDA_ERROR_HOST_MEMORY_ALREADY_REGISTERED", ("hipErrorHostMemoryAlreadyRegistered", CONV_TYPE, API_DRIVER)), ("cudaErrorHostMemoryAlreadyRegistered", ("hipErrorHostMemoryAlreadyRegistered", CONV_TYPE, API_RUNTIME)), ("CUDA_ERROR_HOST_MEMORY_NOT_REGISTERED", ("hipErrorHostMemoryNotRegistered", CONV_TYPE, API_DRIVER)), ("cudaErrorHostMemoryNotRegistered", ("hipErrorHostMemoryNotRegistered", CONV_TYPE, API_RUNTIME)), ("CUDA_ERROR_HARDWARE_STACK_ERROR", ("hipErrorHardwareStackError", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("cudaErrorHardwareStackError", ("hipErrorHardwareStackError", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("CUDA_ERROR_ILLEGAL_INSTRUCTION", ("hipErrorIllegalInstruction", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("cudaErrorIllegalInstruction", ("hipErrorIllegalInstruction", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("CUDA_ERROR_MISALIGNED_ADDRESS", ("hipErrorMisalignedAddress", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("cudaErrorMisalignedAddress", ("hipErrorMisalignedAddress", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("CUDA_ERROR_INVALID_ADDRESS_SPACE", ("hipErrorInvalidAddressSpace", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("cudaErrorInvalidAddressSpace", ("hipErrorInvalidAddressSpace", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("CUDA_ERROR_INVALID_PC", ("hipErrorInvalidPc", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("cudaErrorInvalidPc", ("hipErrorInvalidPc", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("CUDA_ERROR_LAUNCH_FAILED", ("hipErrorLaunchFailure", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("cudaErrorLaunchFailure", ("hipErrorLaunchFailure", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("CUDA_ERROR_UNKNOWN", ("hipErrorUnknown", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("cudaErrorUnknown", ("hipErrorUnknown", CONV_TYPE, API_RUNTIME)), ("CU_TR_ADDRESS_MODE_WRAP", ("HIP_TR_ADDRESS_MODE_WRAP", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_TR_ADDRESS_MODE_CLAMP", ("HIP_TR_ADDRESS_MODE_CLAMP", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_TR_ADDRESS_MODE_MIRROR", ("HIP_TR_ADDRESS_MODE_MIRROR", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_TR_ADDRESS_MODE_BORDER", ("HIP_TR_ADDRESS_MODE_BORDER", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_CUBEMAP_FACE_POSITIVE_X", ("HIP_CUBEMAP_FACE_POSITIVE_X", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_CUBEMAP_FACE_NEGATIVE_X", ("HIP_CUBEMAP_FACE_NEGATIVE_X", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_CUBEMAP_FACE_POSITIVE_Y", ("HIP_CUBEMAP_FACE_POSITIVE_Y", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_CUBEMAP_FACE_NEGATIVE_Y", ("HIP_CUBEMAP_FACE_NEGATIVE_Y", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_CUBEMAP_FACE_POSITIVE_Z", ("HIP_CUBEMAP_FACE_POSITIVE_Z", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_CUBEMAP_FACE_NEGATIVE_Z", ("HIP_CUBEMAP_FACE_NEGATIVE_Z", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_AD_FORMAT_UNSIGNED_INT8", ("HIP_AD_FORMAT_UNSIGNED_INT8", CONV_TYPE, API_DRIVER)), ("CU_AD_FORMAT_UNSIGNED_INT16", ("HIP_AD_FORMAT_UNSIGNED_INT16", CONV_TYPE, API_DRIVER)), ("CU_AD_FORMAT_UNSIGNED_INT32", ("HIP_AD_FORMAT_UNSIGNED_INT32", CONV_TYPE, API_DRIVER)), ("CU_AD_FORMAT_SIGNED_INT8", ("HIP_AD_FORMAT_SIGNED_INT8", CONV_TYPE, API_DRIVER)), ("CU_AD_FORMAT_SIGNED_INT16", ("HIP_AD_FORMAT_SIGNED_INT16", CONV_TYPE, API_DRIVER)), ("CU_AD_FORMAT_SIGNED_INT32", ("HIP_AD_FORMAT_SIGNED_INT32", CONV_TYPE, API_DRIVER)), ("CU_AD_FORMAT_HALF", ("HIP_AD_FORMAT_HALF", CONV_TYPE, API_DRIVER)), ("CU_AD_FORMAT_FLOAT", ("HIP_AD_FORMAT_FLOAT", CONV_TYPE, API_DRIVER)), ("CU_COMPUTEMODE_DEFAULT", ("hipComputeModeDefault", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_COMPUTEMODE_EXCLUSIVE", ("hipComputeModeExclusive", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_COMPUTEMODE_PROHIBITED", ("hipComputeModeProhibited", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_COMPUTEMODE_EXCLUSIVE_PROCESS", ("hipComputeModeExclusiveProcess", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_MEM_ADVISE_SET_READ_MOSTLY", ("hipMemAdviseSetReadMostly", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_MEM_ADVISE_UNSET_READ_MOSTLY", ("hipMemAdviseUnsetReadMostly", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_MEM_ADVISE_SET_PREFERRED_LOCATION", ("hipMemAdviseSetPreferredLocation", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_MEM_ADVISE_UNSET_PREFERRED_LOCATION", ("hipMemAdviseUnsetPreferredLocation", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_MEM_ADVISE_SET_ACCESSED_BY", ("hipMemAdviseSetAccessedBy", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_MEM_ADVISE_UNSET_ACCESSED_BY", ("hipMemAdviseUnsetAccessedBy", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_MEM_RANGE_ATTRIBUTE_READ_MOSTLY", ("hipMemRangeAttributeReadMostly", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_MEM_RANGE_ATTRIBUTE_PREFERRED_LOCATION", ("hipMemRangeAttributePreferredLocation", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_MEM_RANGE_ATTRIBUTE_ACCESSED_BY", ("hipMemRangeAttributeAccessedBy", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_MEM_RANGE_ATTRIBUTE_LAST_PREFETCH_LOCATION", ("hipMemRangeAttributeLastPrefetchLocation", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_CTX_SCHED_AUTO", ("HIP_CTX_SCHED_AUTO", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_CTX_SCHED_SPIN", ("HIP_CTX_SCHED_SPIN", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_CTX_SCHED_YIELD", ("HIP_CTX_SCHED_YIELD", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_CTX_SCHED_BLOCKING_SYNC", ("HIP_CTX_SCHED_BLOCKING_SYNC", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_CTX_BLOCKING_SYNC", ("HIP_CTX_BLOCKING_SYNC", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_CTX_SCHED_MASK", ("HIP_CTX_SCHED_MASK", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_CTX_MAP_HOST", ("HIP_CTX_MAP_HOST", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_CTX_LMEM_RESIZE_TO_MAX", ("HIP_CTX_LMEM_RESIZE_TO_MAX", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_CTX_FLAGS_MASK", ("HIP_CTX_FLAGS_MASK", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_LAUNCH_PARAM_BUFFER_POINTER", ("HIP_LAUNCH_PARAM_BUFFER_POINTER", CONV_TYPE, API_DRIVER)), ("CU_LAUNCH_PARAM_BUFFER_SIZE", ("HIP_LAUNCH_PARAM_BUFFER_SIZE", CONV_TYPE, API_DRIVER)), ("CU_LAUNCH_PARAM_END", ("HIP_LAUNCH_PARAM_END", CONV_TYPE, API_DRIVER)), ("CU_IPC_HANDLE_SIZE", ("HIP_LAUNCH_PARAM_END", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_MEMHOSTALLOC_DEVICEMAP", ("HIP_MEMHOSTALLOC_DEVICEMAP", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_MEMHOSTALLOC_PORTABLE", ("HIP_MEMHOSTALLOC_PORTABLE", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_MEMHOSTALLOC_WRITECOMBINED", ("HIP_MEMHOSTALLOC_WRITECOMBINED", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_MEMHOSTREGISTER_DEVICEMAP", ("HIP_MEMHOSTREGISTER_DEVICEMAP", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_MEMHOSTREGISTER_IOMEMORY", ("HIP_MEMHOSTREGISTER_IOMEMORY", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_MEMHOSTREGISTER_PORTABLE", ("HIP_MEMHOSTREGISTER_PORTABLE", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_PARAM_TR_DEFAULT", ("HIP_PARAM_TR_DEFAULT", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_STREAM_LEGACY", ("HIP_STREAM_LEGACY", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_STREAM_PER_THREAD", ("HIP_STREAM_PER_THREAD", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_TRSA_OVERRIDE_FORMAT", ("HIP_TRSA_OVERRIDE_FORMAT", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_TRSF_NORMALIZED_COORDINATES", ("HIP_TRSF_NORMALIZED_COORDINATES", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_TRSF_READ_AS_INTEGER", ("HIP_TRSF_READ_AS_INTEGER", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_TRSF_SRGB", ("HIP_TRSF_SRGB", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CUDA_ARRAY3D_2DARRAY", ("HIP_ARRAY3D_LAYERED", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CUDA_ARRAY3D_CUBEMAP", ("HIP_ARRAY3D_CUBEMAP", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CUDA_ARRAY3D_DEPTH_TEXTURE", ("HIP_ARRAY3D_DEPTH_TEXTURE", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CUDA_ARRAY3D_LAYERED", ("HIP_ARRAY3D_LAYERED", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CUDA_ARRAY3D_SURFACE_LDST", ("HIP_ARRAY3D_SURFACE_LDST", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CUDA_ARRAY3D_TEXTURE_GATHER", ("HIP_ARRAY3D_TEXTURE_GATHER", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), # ("CUDA_VERSION", ("HIP_VERSION", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_DEVICE_ATTRIBUTE_MAX_THREADS_PER_BLOCK", ("hipDeviceAttributeMaxThreadsPerBlock", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_DEVICE_ATTRIBUTE_MAX_BLOCK_DIM_X", ("hipDeviceAttributeMaxBlockDimX", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_DEVICE_ATTRIBUTE_MAX_BLOCK_DIM_Y", ("hipDeviceAttributeMaxBlockDimY", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_DEVICE_ATTRIBUTE_MAX_BLOCK_DIM_Z", ("hipDeviceAttributeMaxBlockDimZ", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_DEVICE_ATTRIBUTE_MAX_GRID_DIM_X", ("hipDeviceAttributeMaxGridDimX", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_DEVICE_ATTRIBUTE_MAX_GRID_DIM_Y", ("hipDeviceAttributeMaxGridDimY", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_DEVICE_ATTRIBUTE_MAX_GRID_DIM_Z", ("hipDeviceAttributeMaxGridDimZ", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_DEVICE_ATTRIBUTE_MAX_SHARED_MEMORY_PER_BLOCK", ("hipDeviceAttributeMaxSharedMemoryPerBlock", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_DEVICE_ATTRIBUTE_SHARED_MEMORY_PER_BLOCK", ("hipDeviceAttributeMaxSharedMemoryPerBlock", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_DEVICE_ATTRIBUTE_TOTAL_CONSTANT_MEMORY", ("hipDeviceAttributeTotalConstantMemory", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_DEVICE_ATTRIBUTE_WARP_SIZE", ("hipDeviceAttributeWarpSize", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_DEVICE_ATTRIBUTE_MAX_PITCH", ("hipDeviceAttributeMaxPitch", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_DEVICE_ATTRIBUTE_MAX_REGISTERS_PER_BLOCK", ("hipDeviceAttributeMaxRegistersPerBlock", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_DEVICE_ATTRIBUTE_REGISTERS_PER_BLOCK", ("hipDeviceAttributeMaxRegistersPerBlock", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_DEVICE_ATTRIBUTE_CLOCK_RATE", ("hipDeviceAttributeClockRate", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_DEVICE_ATTRIBUTE_TEXTURE_ALIGNMENT", ("hipDeviceAttributeTextureAlignment", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_DEVICE_ATTRIBUTE_GPU_OVERLAP", ("hipDeviceAttributeAsyncEngineCount", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_DEVICE_ATTRIBUTE_MULTIPROCESSOR_COUNT", ("hipDeviceAttributeMultiprocessorCount", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_DEVICE_ATTRIBUTE_KERNEL_EXEC_TIMEOUT", ("hipDeviceAttributeKernelExecTimeout", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_DEVICE_ATTRIBUTE_INTEGRATED", ("hipDeviceAttributeIntegrated", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_DEVICE_ATTRIBUTE_CAN_MAP_HOST_MEMORY", ("hipDeviceAttributeCanMapHostMemory", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_DEVICE_ATTRIBUTE_COMPUTE_MODE", ("hipDeviceAttributeComputeMode", CONV_TYPE, API_DRIVER)), ("CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE1D_WIDTH", ("hipDeviceAttributeMaxTexture1DWidth", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_WIDTH", ("hipDeviceAttributeMaxTexture2DWidth", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_HEIGHT", ("hipDeviceAttributeMaxTexture2DHeight", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE3D_WIDTH", ("hipDeviceAttributeMaxTexture3DWidth", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE3D_HEIGHT", ("hipDeviceAttributeMaxTexture3DHeight", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE3D_DEPTH", ("hipDeviceAttributeMaxTexture3DDepth", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_LAYERED_WIDTH", ("hipDeviceAttributeMaxTexture2DLayeredWidth", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_LAYERED_HEIGHT", ("hipDeviceAttributeMaxTexture2DLayeredHeight", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_LAYERED_LAYERS", ("hipDeviceAttributeMaxTexture2DLayeredLayers", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_ARRAY_WIDTH", ("hipDeviceAttributeMaxTexture2DLayeredWidth", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_ARRAY_HEIGHT", ("hipDeviceAttributeMaxTexture2DLayeredHeight", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_ARRAY_NUMSLICES", ("hipDeviceAttributeMaxTexture2DLayeredLayers", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_DEVICE_ATTRIBUTE_SURFACE_ALIGNMENT", ("hipDeviceAttributeSurfaceAlignment", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_DEVICE_ATTRIBUTE_CONCURRENT_KERNELS", ("hipDeviceAttributeConcurrentKernels", CONV_TYPE, API_DRIVER)), ("CU_DEVICE_ATTRIBUTE_ECC_ENABLED", ("hipDeviceAttributeEccEnabled", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_DEVICE_ATTRIBUTE_PCI_BUS_ID", ("hipDeviceAttributePciBusId", CONV_TYPE, API_DRIVER)), ("CU_DEVICE_ATTRIBUTE_PCI_DEVICE_ID", ("hipDeviceAttributePciDeviceId", CONV_TYPE, API_DRIVER)), ("CU_DEVICE_ATTRIBUTE_TCC_DRIVER", ("hipDeviceAttributeTccDriver", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_DEVICE_ATTRIBUTE_MEMORY_CLOCK_RATE", ("hipDeviceAttributeMemoryClockRate", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_DEVICE_ATTRIBUTE_GLOBAL_MEMORY_BUS_WIDTH", ("hipDeviceAttributeMemoryBusWidth", CONV_TYPE, API_DRIVER)), ("CU_DEVICE_ATTRIBUTE_L2_CACHE_SIZE", ("hipDeviceAttributeL2CacheSize", CONV_TYPE, API_DRIVER)), ("CU_DEVICE_ATTRIBUTE_MAX_THREADS_PER_MULTIPROCESSOR", ("hipDeviceAttributeMaxThreadsPerMultiProcessor", CONV_TYPE, API_DRIVER)), ("CU_DEVICE_ATTRIBUTE_ASYNC_ENGINE_COUNT", ("hipDeviceAttributeAsyncEngineCount", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_DEVICE_ATTRIBUTE_UNIFIED_ADDRESSING", ("hipDeviceAttributeUnifiedAddressing", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE1D_LAYERED_WIDTH", ("hipDeviceAttributeMaxTexture1DLayeredWidth", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE1D_LAYERED_LAYERS", ("hipDeviceAttributeMaxTexture1DLayeredLayers", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_DEVICE_ATTRIBUTE_CAN_TEX2D_GATHER", ("hipDeviceAttributeCanTex2DGather", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_GATHER_WIDTH", ("hipDeviceAttributeMaxTexture2DGatherWidth", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_GATHER_HEIGHT", ("hipDeviceAttributeMaxTexture2DGatherHeight", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE3D_WIDTH_ALTERNATE", ("hipDeviceAttributeMaxTexture3DWidthAlternate", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE3D_HEIGHT_ALTERNATE", ("hipDeviceAttributeMaxTexture3DHeightAlternate", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE3D_DEPTH_ALTERNATE", ("hipDeviceAttributeMaxTexture3DDepthAlternate", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_DEVICE_ATTRIBUTE_PCI_DOMAIN_ID", ("hipDeviceAttributePciDomainId", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_DEVICE_ATTRIBUTE_TEXTURE_PITCH_ALIGNMENT", ("hipDeviceAttributeTexturePitchAlignment", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURECUBEMAP_WIDTH", ("hipDeviceAttributeMaxTextureCubemapWidth", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURECUBEMAP_LAYERED_WIDTH", ("hipDeviceAttributeMaxTextureCubemapLayeredWidth", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURECUBEMAP_LAYERED_LAYERS", ("hipDeviceAttributeMaxTextureCubemapLayeredLayers", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACE1D_WIDTH", ("hipDeviceAttributeMaxSurface1DWidth", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACE2D_WIDTH", ("hipDeviceAttributeMaxSurface2DWidth", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACE2D_HEIGHT", ("hipDeviceAttributeMaxSurface2DHeight", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACE3D_WIDTH", ("hipDeviceAttributeMaxSurface3DWidth", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACE3D_HEIGHT", ("hipDeviceAttributeMaxSurface3DHeight", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACE3D_DEPTH", ("hipDeviceAttributeMaxSurface3DDepth", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACE1D_LAYERED_WIDTH", ("hipDeviceAttributeMaxSurface1DLayeredWidth", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACE1D_LAYERED_LAYERS", ("hipDeviceAttributeMaxSurface1DLayeredLayers", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACE2D_LAYERED_WIDTH", ("hipDeviceAttributeMaxSurface2DLayeredWidth", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACE2D_LAYERED_HEIGHT", ("hipDeviceAttributeMaxSurface2DLayeredHeight", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACE2D_LAYERED_LAYERS", ("hipDeviceAttributeMaxSurface2DLayeredLayers", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACECUBEMAP_WIDTH", ("hipDeviceAttributeMaxSurfaceCubemapWidth", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACECUBEMAP_LAYERED_WIDTH", ("hipDeviceAttributeMaxSurfaceCubemapLayeredWidth", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_DEVICE_ATTRIBUTE_MAXIMUM_SURFACECUBEMAP_LAYERED_LAYERS", ("hipDeviceAttributeMaxSurfaceCubemapLayeredLayers", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE1D_LINEAR_WIDTH", ("hipDeviceAttributeMaxTexture1DLinearWidth", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_LINEAR_WIDTH", ("hipDeviceAttributeMaxTexture2DLinearWidth", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_LINEAR_HEIGHT", ("hipDeviceAttributeMaxTexture2DLinearHeight", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_LINEAR_PITCH", ("hipDeviceAttributeMaxTexture2DLinearPitch", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_MIPMAPPED_WIDTH", ("hipDeviceAttributeMaxTexture2DMipmappedWidth", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_MIPMAPPED_HEIGHT", ("hipDeviceAttributeMaxTexture2DMipmappedHeight", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_DEVICE_ATTRIBUTE_COMPUTE_CAPABILITY_MAJOR", ("hipDeviceAttributeComputeCapabilityMajor", CONV_TYPE, API_DRIVER)), ("CU_DEVICE_ATTRIBUTE_COMPUTE_CAPABILITY_MINOR", ("hipDeviceAttributeComputeCapabilityMinor", CONV_TYPE, API_DRIVER)), ("CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE1D_MIPMAPPED_WIDTH", ("hipDeviceAttributeMaxTexture1DMipmappedWidth", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_DEVICE_ATTRIBUTE_STREAM_PRIORITIES_SUPPORTED", ("hipDeviceAttributeStreamPrioritiesSupported", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_DEVICE_ATTRIBUTE_GLOBAL_L1_CACHE_SUPPORTED", ("hipDeviceAttributeGlobalL1CacheSupported", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_DEVICE_ATTRIBUTE_LOCAL_L1_CACHE_SUPPORTED", ("hipDeviceAttributeLocalL1CacheSupported", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_DEVICE_ATTRIBUTE_MAX_SHARED_MEMORY_PER_MULTIPROCESSOR", ("hipDeviceAttributeMaxSharedMemoryPerMultiprocessor", CONV_TYPE, API_DRIVER)), ("CU_DEVICE_ATTRIBUTE_MAX_REGISTERS_PER_MULTIPROCESSOR", ("hipDeviceAttributeMaxRegistersPerMultiprocessor", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_DEVICE_ATTRIBUTE_MANAGED_MEMORY", ("hipDeviceAttributeManagedMemory", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_DEVICE_ATTRIBUTE_MULTI_GPU_BOARD", ("hipDeviceAttributeIsMultiGpuBoard", CONV_TYPE, API_DRIVER)), ("CU_DEVICE_ATTRIBUTE_MULTI_GPU_BOARD_GROUP_ID", ("hipDeviceAttributeMultiGpuBoardGroupId", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_DEVICE_ATTRIBUTE_HOST_NATIVE_ATOMIC_SUPPORTED", ("hipDeviceAttributeHostNativeAtomicSupported", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_DEVICE_ATTRIBUTE_SINGLE_TO_DOUBLE_PRECISION_PERF_RATIO", ("hipDeviceAttributeSingleToDoublePrecisionPerfRatio", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_DEVICE_ATTRIBUTE_PAGEABLE_MEMORY_ACCESS", ("hipDeviceAttributePageableMemoryAccess", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_DEVICE_ATTRIBUTE_CONCURRENT_MANAGED_ACCESS", ("hipDeviceAttributeConcurrentManagedAccess", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_DEVICE_ATTRIBUTE_COMPUTE_PREEMPTION_SUPPORTED", ("hipDeviceAttributeComputePreemptionSupported", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_DEVICE_ATTRIBUTE_CAN_USE_HOST_POINTER_FOR_REGISTERED_MEM", ("hipDeviceAttributeCanUseHostPointerForRegisteredMem", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_DEVICE_ATTRIBUTE_MAX", ("hipDeviceAttributeMax", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_POINTER_ATTRIBUTE_CONTEXT", ("hipPointerAttributeContext", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_POINTER_ATTRIBUTE_MEMORY_TYPE", ("hipPointerAttributeMemoryType", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_POINTER_ATTRIBUTE_DEVICE_POINTER", ("hipPointerAttributeDevicePointer", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_POINTER_ATTRIBUTE_HOST_POINTER", ("hipPointerAttributeHostPointer", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_POINTER_ATTRIBUTE_P2P_TOKENS", ("hipPointerAttributeP2pTokens", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_POINTER_ATTRIBUTE_SYNC_MEMOPS", ("hipPointerAttributeSyncMemops", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_POINTER_ATTRIBUTE_BUFFER_ID", ("hipPointerAttributeBufferId", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_POINTER_ATTRIBUTE_IS_MANAGED", ("hipPointerAttributeIsManaged", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_FUNC_ATTRIBUTE_MAX_THREADS_PER_BLOCK", ("hipFuncAttributeMaxThreadsPerBlocks", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_FUNC_ATTRIBUTE_SHARED_SIZE_BYTES", ("hipFuncAttributeSharedSizeBytes", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_FUNC_ATTRIBUTE_CONST_SIZE_BYTES", ("hipFuncAttributeConstSizeBytes", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_FUNC_ATTRIBUTE_LOCAL_SIZE_BYTES", ("hipFuncAttributeLocalSizeBytes", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_FUNC_ATTRIBUTE_NUM_REGS", ("hipFuncAttributeNumRegs", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_FUNC_ATTRIBUTE_PTX_VERSION", ("hipFuncAttributePtxVersion", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_FUNC_ATTRIBUTE_BINARY_VERSION", ("hipFuncAttributeBinaryVersion", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_FUNC_ATTRIBUTE_CACHE_MODE_CA", ("hipFuncAttributeCacheModeCA", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_FUNC_ATTRIBUTE_MAX", ("hipFuncAttributeMax", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_GRAPHICS_MAP_RESOURCE_FLAGS_NONE", ("hipGraphicsMapFlagsNone", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_GRAPHICS_MAP_RESOURCE_FLAGS_READ_ONLY", ("hipGraphicsMapFlagsReadOnly", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_GRAPHICS_MAP_RESOURCE_FLAGS_WRITE_DISCARD", ("hipGraphicsMapFlagsWriteDiscard", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_GRAPHICS_REGISTER_FLAGS_NONE", ("hipGraphicsRegisterFlagsNone", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_GRAPHICS_REGISTER_FLAGS_READ_ONLY", ("hipGraphicsRegisterFlagsReadOnly", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_GRAPHICS_REGISTER_FLAGS_WRITE_DISCARD", ("hipGraphicsRegisterFlagsWriteDiscard", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_GRAPHICS_REGISTER_FLAGS_SURFACE_LDST", ("hipGraphicsRegisterFlagsSurfaceLoadStore", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_GRAPHICS_REGISTER_FLAGS_TEXTURE_GATHER", ("hipGraphicsRegisterFlagsTextureGather", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_OCCUPANCY_DEFAULT", ("hipOccupancyDefault", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_OCCUPANCY_DISABLE_CACHING_OVERRIDE", ("hipOccupancyDisableCachingOverride", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_FUNC_CACHE_PREFER_NONE", ("hipFuncCachePreferNone", CONV_CACHE, API_DRIVER)), ("CU_FUNC_CACHE_PREFER_SHARED", ("hipFuncCachePreferShared", CONV_CACHE, API_DRIVER)), ("CU_FUNC_CACHE_PREFER_L1", ("hipFuncCachePreferL1", CONV_CACHE, API_DRIVER)), ("CU_FUNC_CACHE_PREFER_EQUAL", ("hipFuncCachePreferEqual", CONV_CACHE, API_DRIVER)), ("CU_IPC_MEM_LAZY_ENABLE_PEER_ACCESS", ("hipIpcMemLazyEnablePeerAccess", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CUDA_IPC_HANDLE_SIZE", ("HIP_IPC_HANDLE_SIZE", CONV_TYPE, API_DRIVER)), ("CU_JIT_CACHE_OPTION_NONE", ("hipJitCacheModeOptionNone", CONV_JIT, API_DRIVER, HIP_UNSUPPORTED)), ("CU_JIT_CACHE_OPTION_CG", ("hipJitCacheModeOptionCG", CONV_JIT, API_DRIVER, HIP_UNSUPPORTED)), ("CU_JIT_CACHE_OPTION_CA", ("hipJitCacheModeOptionCA", CONV_JIT, API_DRIVER, HIP_UNSUPPORTED)), ("CU_PREFER_PTX", ("hipJitFallbackPreferPtx", CONV_JIT, API_DRIVER, HIP_UNSUPPORTED)), ("CU_PREFER_BINARY", ("hipJitFallbackPreferBinary", CONV_JIT, API_DRIVER, HIP_UNSUPPORTED)), ("CU_JIT_MAX_REGISTERS", ("hipJitOptionMaxRegisters", CONV_JIT, API_DRIVER)), ("CU_JIT_THREADS_PER_BLOCK", ("hipJitOptionThreadsPerBlock", CONV_JIT, API_DRIVER)), ("CU_JIT_WALL_TIME", ("hipJitOptionWallTime", CONV_JIT, API_DRIVER)), ("CU_JIT_INFO_LOG_BUFFER", ("hipJitOptionInfoLogBuffer", CONV_JIT, API_DRIVER)), ("CU_JIT_INFO_LOG_BUFFER_SIZE_BYTES", ("hipJitOptionInfoLogBufferSizeBytes", CONV_JIT, API_DRIVER)), ("CU_JIT_ERROR_LOG_BUFFER", ("hipJitOptionErrorLogBuffer", CONV_JIT, API_DRIVER)), ("CU_JIT_ERROR_LOG_BUFFER_SIZE_BYTES", ("hipJitOptionErrorLogBufferSizeBytes", CONV_JIT, API_DRIVER)), ("CU_JIT_OPTIMIZATION_LEVEL", ("hipJitOptionOptimizationLevel", CONV_JIT, API_DRIVER)), ("CU_JIT_TARGET_FROM_CUCONTEXT", ("hipJitOptionTargetFromContext", CONV_JIT, API_DRIVER)), ("CU_JIT_TARGET", ("hipJitOptionTarget", CONV_JIT, API_DRIVER)), ("CU_JIT_FALLBACK_STRATEGY", ("hipJitOptionFallbackStrategy", CONV_JIT, API_DRIVER)), ("CU_JIT_GENERATE_DEBUG_INFO", ("hipJitOptionGenerateDebugInfo", CONV_JIT, API_DRIVER)), ("CU_JIT_LOG_VERBOSE", ("hipJitOptionLogVerbose", CONV_JIT, API_DRIVER)), ("CU_JIT_GENERATE_LINE_INFO", ("hipJitOptionGenerateLineInfo", CONV_JIT, API_DRIVER)), ("CU_JIT_CACHE_MODE", ("hipJitOptionCacheMode", CONV_JIT, API_DRIVER)), ("CU_JIT_NEW_SM3X_OPT", ("hipJitOptionSm3xOpt", CONV_JIT, API_DRIVER)), ("CU_JIT_FAST_COMPILE", ("hipJitOptionFastCompile", CONV_JIT, API_DRIVER)), ("CU_JIT_NUM_OPTIONS", ("hipJitOptionNumOptions", CONV_JIT, API_DRIVER)), ("CU_TARGET_COMPUTE_10", ("hipJitTargetCompute10", CONV_JIT, API_DRIVER, HIP_UNSUPPORTED)), ("CU_TARGET_COMPUTE_11", ("hipJitTargetCompute11", CONV_JIT, API_DRIVER, HIP_UNSUPPORTED)), ("CU_TARGET_COMPUTE_12", ("hipJitTargetCompute12", CONV_JIT, API_DRIVER, HIP_UNSUPPORTED)), ("CU_TARGET_COMPUTE_13", ("hipJitTargetCompute13", CONV_JIT, API_DRIVER, HIP_UNSUPPORTED)), ("CU_TARGET_COMPUTE_20", ("hipJitTargetCompute20", CONV_JIT, API_DRIVER, HIP_UNSUPPORTED)), ("CU_TARGET_COMPUTE_21", ("hipJitTargetCompute21", CONV_JIT, API_DRIVER, HIP_UNSUPPORTED)), ("CU_TARGET_COMPUTE_30", ("hipJitTargetCompute30", CONV_JIT, API_DRIVER, HIP_UNSUPPORTED)), ("CU_TARGET_COMPUTE_32", ("hipJitTargetCompute32", CONV_JIT, API_DRIVER, HIP_UNSUPPORTED)), ("CU_TARGET_COMPUTE_35", ("hipJitTargetCompute35", CONV_JIT, API_DRIVER, HIP_UNSUPPORTED)), ("CU_TARGET_COMPUTE_37", ("hipJitTargetCompute37", CONV_JIT, API_DRIVER, HIP_UNSUPPORTED)), ("CU_TARGET_COMPUTE_50", ("hipJitTargetCompute50", CONV_JIT, API_DRIVER, HIP_UNSUPPORTED)), ("CU_TARGET_COMPUTE_52", ("hipJitTargetCompute52", CONV_JIT, API_DRIVER, HIP_UNSUPPORTED)), ("CU_TARGET_COMPUTE_53", ("hipJitTargetCompute53", CONV_JIT, API_DRIVER, HIP_UNSUPPORTED)), ("CU_TARGET_COMPUTE_60", ("hipJitTargetCompute60", CONV_JIT, API_DRIVER, HIP_UNSUPPORTED)), ("CU_TARGET_COMPUTE_61", ("hipJitTargetCompute61", CONV_JIT, API_DRIVER, HIP_UNSUPPORTED)), ("CU_TARGET_COMPUTE_62", ("hipJitTargetCompute62", CONV_JIT, API_DRIVER, HIP_UNSUPPORTED)), ("CU_JIT_INPUT_CUBIN", ("hipJitInputTypeBin", CONV_JIT, API_DRIVER, HIP_UNSUPPORTED)), ("CU_JIT_INPUT_PTX", ("hipJitInputTypePtx", CONV_JIT, API_DRIVER, HIP_UNSUPPORTED)), ("CU_JIT_INPUT_FATBINARY", ("hipJitInputTypeFatBinary", CONV_JIT, API_DRIVER, HIP_UNSUPPORTED)), ("CU_JIT_INPUT_OBJECT", ("hipJitInputTypeObject", CONV_JIT, API_DRIVER, HIP_UNSUPPORTED)), ("CU_JIT_INPUT_LIBRARY", ("hipJitInputTypeLibrary", CONV_JIT, API_DRIVER, HIP_UNSUPPORTED)), ("CU_JIT_NUM_INPUT_TYPES", ("hipJitInputTypeNumInputTypes", CONV_JIT, API_DRIVER, HIP_UNSUPPORTED)), ("CU_LIMIT_STACK_SIZE", ("hipLimitStackSize", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_LIMIT_PRINTF_FIFO_SIZE", ("hipLimitPrintfFifoSize", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_LIMIT_MALLOC_HEAP_SIZE", ("hipLimitMallocHeapSize", CONV_TYPE, API_DRIVER)), ("CU_LIMIT_DEV_RUNTIME_SYNC_DEPTH", ("hipLimitDevRuntimeSyncDepth", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_LIMIT_DEV_RUNTIME_PENDING_LAUNCH_COUNT", ("hipLimitDevRuntimePendingLaunchCount", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_LIMIT_STACK_SIZE", ("hipLimitStackSize", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_MEM_ATTACH_GLOBAL", ("hipMemAttachGlobal", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_MEM_ATTACH_HOST", ("hipMemAttachHost", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_MEM_ATTACH_SINGLE", ("hipMemAttachSingle", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_MEMORYTYPE_HOST", ("hipMemTypeHost", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_MEMORYTYPE_DEVICE", ("hipMemTypeDevice", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_MEMORYTYPE_ARRAY", ("hipMemTypeArray", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_MEMORYTYPE_UNIFIED", ("hipMemTypeUnified", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_RESOURCE_TYPE_ARRAY", ("hipResourceTypeArray", CONV_TEX, API_DRIVER, HIP_UNSUPPORTED)), ("CU_RESOURCE_TYPE_MIPMAPPED_ARRAY", ("hipResourceTypeMipmappedArray", CONV_TEX, API_DRIVER, HIP_UNSUPPORTED)), ("CU_RESOURCE_TYPE_LINEAR", ("hipResourceTypeLinear", CONV_TEX, API_DRIVER, HIP_UNSUPPORTED)), ("CU_RESOURCE_TYPE_PITCH2D", ("hipResourceTypePitch2D", CONV_TEX, API_DRIVER, HIP_UNSUPPORTED)), ("CU_RES_VIEW_FORMAT_NONE", ("hipResViewFormatNone", CONV_TEX, API_DRIVER)), ("CU_RES_VIEW_FORMAT_UINT_1X8", ("hipResViewFormatUnsignedChar1", CONV_TEX, API_DRIVER)), ("CU_RES_VIEW_FORMAT_UINT_2X8", ("hipResViewFormatUnsignedChar2", CONV_TEX, API_DRIVER)), ("CU_RES_VIEW_FORMAT_UINT_4X8", ("hipResViewFormatUnsignedChar4", CONV_TEX, API_DRIVER)), ("CU_RES_VIEW_FORMAT_SINT_1X8", ("hipResViewFormatSignedChar1", CONV_TEX, API_DRIVER)), ("CU_RES_VIEW_FORMAT_SINT_2X8", ("hipResViewFormatSignedChar2", CONV_TEX, API_DRIVER)), ("CU_RES_VIEW_FORMAT_SINT_4X8", ("hipResViewFormatSignedChar4", CONV_TEX, API_DRIVER)), ("CU_RES_VIEW_FORMAT_UINT_1X16", ("hipResViewFormatUnsignedShort1", CONV_TEX, API_DRIVER)), ("CU_RES_VIEW_FORMAT_UINT_2X16", ("hipResViewFormatUnsignedShort2", CONV_TEX, API_DRIVER)), ("CU_RES_VIEW_FORMAT_UINT_4X16", ("hipResViewFormatUnsignedShort4", CONV_TEX, API_DRIVER)), ("CU_RES_VIEW_FORMAT_SINT_1X16", ("hipResViewFormatSignedShort1", CONV_TEX, API_DRIVER)), ("CU_RES_VIEW_FORMAT_SINT_2X16", ("hipResViewFormatSignedShort2", CONV_TEX, API_DRIVER)), ("CU_RES_VIEW_FORMAT_SINT_4X16", ("hipResViewFormatSignedShort4", CONV_TEX, API_DRIVER)), ("CU_RES_VIEW_FORMAT_UINT_1X32", ("hipResViewFormatUnsignedInt1", CONV_TEX, API_DRIVER)), ("CU_RES_VIEW_FORMAT_UINT_2X32", ("hipResViewFormatUnsignedInt2", CONV_TEX, API_DRIVER)), ("CU_RES_VIEW_FORMAT_UINT_4X32", ("hipResViewFormatUnsignedInt4", CONV_TEX, API_DRIVER)), ("CU_RES_VIEW_FORMAT_SINT_1X32", ("hipResViewFormatSignedInt1", CONV_TEX, API_DRIVER)), ("CU_RES_VIEW_FORMAT_SINT_2X32", ("hipResViewFormatSignedInt2", CONV_TEX, API_DRIVER)), ("CU_RES_VIEW_FORMAT_SINT_4X32", ("hipResViewFormatSignedInt4", CONV_TEX, API_DRIVER)), ("CU_RES_VIEW_FORMAT_FLOAT_1X16", ("hipResViewFormatHalf1", CONV_TEX, API_DRIVER)), ("CU_RES_VIEW_FORMAT_FLOAT_2X16", ("hipResViewFormatHalf2", CONV_TEX, API_DRIVER)), ("CU_RES_VIEW_FORMAT_FLOAT_4X16", ("hipResViewFormatHalf4", CONV_TEX, API_DRIVER)), ("CU_RES_VIEW_FORMAT_FLOAT_1X32", ("hipResViewFormatFloat1", CONV_TEX, API_DRIVER)), ("CU_RES_VIEW_FORMAT_FLOAT_2X32", ("hipResViewFormatFloat2", CONV_TEX, API_DRIVER)), ("CU_RES_VIEW_FORMAT_FLOAT_4X32", ("hipResViewFormatFloat4", CONV_TEX, API_DRIVER)), ("CU_RES_VIEW_FORMAT_UNSIGNED_BC1", ("hipResViewFormatUnsignedBlockCompressed1", CONV_TEX, API_DRIVER)), ("CU_RES_VIEW_FORMAT_UNSIGNED_BC2", ("hipResViewFormatUnsignedBlockCompressed2", CONV_TEX, API_DRIVER)), ("CU_RES_VIEW_FORMAT_UNSIGNED_BC3", ("hipResViewFormatUnsignedBlockCompressed3", CONV_TEX, API_DRIVER)), ("CU_RES_VIEW_FORMAT_UNSIGNED_BC4", ("hipResViewFormatUnsignedBlockCompressed4", CONV_TEX, API_DRIVER)), ("CU_RES_VIEW_FORMAT_SIGNED_BC4", ("hipResViewFormatSignedBlockCompressed4", CONV_TEX, API_DRIVER)), ("CU_RES_VIEW_FORMAT_UNSIGNED_BC5", ("hipResViewFormatUnsignedBlockCompressed5", CONV_TEX, API_DRIVER)), ("CU_RES_VIEW_FORMAT_SIGNED_BC5", ("hipResViewFormatSignedBlockCompressed5", CONV_TEX, API_DRIVER)), ("CU_RES_VIEW_FORMAT_UNSIGNED_BC6H", ("hipResViewFormatUnsignedBlockCompressed6H", CONV_TEX, API_DRIVER)), ("CU_RES_VIEW_FORMAT_SIGNED_BC6H", ("hipResViewFormatSignedBlockCompressed6H", CONV_TEX, API_DRIVER)), ("CU_RES_VIEW_FORMAT_UNSIGNED_BC7", ("hipResViewFormatUnsignedBlockCompressed7", CONV_TEX, API_DRIVER)), ("CU_SHARED_MEM_CONFIG_DEFAULT_BANK_SIZE", ("hipSharedMemBankSizeDefault", CONV_TYPE, API_DRIVER)), ("CU_SHARED_MEM_CONFIG_FOUR_BYTE_BANK_SIZE", ("hipSharedMemBankSizeFourByte", CONV_TYPE, API_DRIVER)), ("CU_SHARED_MEM_CONFIG_EIGHT_BYTE_BANK_SIZE", ("hipSharedMemBankSizeEightByte", CONV_TYPE, API_DRIVER)), ("CU_STREAM_DEFAULT", ("hipStreamDefault", CONV_TYPE, API_DRIVER)), ("CU_STREAM_NON_BLOCKING", ("hipStreamNonBlocking", CONV_TYPE, API_DRIVER)), ("CU_STREAM_WAIT_VALUE_GEQ", ("hipStreamWaitValueGeq", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_STREAM_WAIT_VALUE_EQ", ("hipStreamWaitValueEq", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_STREAM_WAIT_VALUE_AND", ("hipStreamWaitValueAnd", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_STREAM_WAIT_VALUE_FLUSH", ("hipStreamWaitValueFlush", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_STREAM_WRITE_VALUE_DEFAULT", ("hipStreamWriteValueDefault", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_STREAM_WRITE_VALUE_NO_MEMORY_BARRIER", ("hipStreamWriteValueNoMemoryBarrier", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_STREAM_MEM_OP_WAIT_VALUE_32", ("hipStreamBatchMemOpWaitValue32", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_STREAM_MEM_OP_WRITE_VALUE_32", ("hipStreamBatchMemOpWriteValue32", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_STREAM_MEM_OP_FLUSH_REMOTE_WRITES", ("hipStreamBatchMemOpFlushRemoteWrites", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("cuGetErrorName", ("hipGetErrorName___", CONV_ERROR, API_DRIVER, HIP_UNSUPPORTED)), ("cuGetErrorString", ("hipGetErrorString___", CONV_ERROR, API_DRIVER, HIP_UNSUPPORTED)), ("cuInit", ("hipInit", CONV_INIT, API_DRIVER)), ("cuDriverGetVersion", ("hipDriverGetVersion", CONV_VERSION, API_DRIVER)), ("cuCtxCreate_v2", ("hipCtxCreate", CONV_CONTEXT, API_DRIVER)), ("cuCtxDestroy_v2", ("hipCtxDestroy", CONV_CONTEXT, API_DRIVER)), ("cuCtxGetApiVersion", ("hipCtxGetApiVersion", CONV_CONTEXT, API_DRIVER)), ("cuCtxGetCacheConfig", ("hipCtxGetCacheConfig", CONV_CONTEXT, API_DRIVER)), ("cuCtxGetCurrent", ("hipCtxGetCurrent", CONV_CONTEXT, API_DRIVER)), ("cuCtxGetDevice", ("hipCtxGetDevice", CONV_CONTEXT, API_DRIVER)), ("cuCtxGetFlags", ("hipCtxGetFlags", CONV_CONTEXT, API_DRIVER)), ("cuCtxGetLimit", ("hipCtxGetLimit", CONV_CONTEXT, API_DRIVER, HIP_UNSUPPORTED)), ("cuCtxGetSharedMemConfig", ("hipCtxGetSharedMemConfig", CONV_CONTEXT, API_DRIVER)), ("cuCtxGetStreamPriorityRange", ("hipCtxGetStreamPriorityRange", CONV_CONTEXT, API_DRIVER, HIP_UNSUPPORTED)), ("cuCtxPopCurrent_v2", ("hipCtxPopCurrent", CONV_CONTEXT, API_DRIVER)), ("cuCtxPushCurrent_v2", ("hipCtxPushCurrent", CONV_CONTEXT, API_DRIVER)), ("cuCtxSetCacheConfig", ("hipCtxSetCacheConfig", CONV_CONTEXT, API_DRIVER)), ("cuCtxSetCurrent", ("hipCtxSetCurrent", CONV_CONTEXT, API_DRIVER)), ("cuCtxSetLimit", ("hipCtxSetLimit", CONV_CONTEXT, API_DRIVER, HIP_UNSUPPORTED)), ("cuCtxSetSharedMemConfig", ("hipCtxSetSharedMemConfig", CONV_CONTEXT, API_DRIVER)), ("cuCtxSynchronize", ("hipCtxSynchronize", CONV_CONTEXT, API_DRIVER)), ("cuCtxAttach", ("hipCtxAttach", CONV_CONTEXT, API_DRIVER, HIP_UNSUPPORTED)), ("cuCtxDetach", ("hipCtxDetach", CONV_CONTEXT, API_DRIVER, HIP_UNSUPPORTED)), ("cuCtxEnablePeerAccess", ("hipCtxEnablePeerAccess", CONV_PEER, API_DRIVER)), ("cuCtxDisablePeerAccess", ("hipCtxDisablePeerAccess", CONV_PEER, API_DRIVER)), ("cuDeviceCanAccessPeer", ("hipDeviceCanAccessPeer", CONV_PEER, API_DRIVER)), ("cuDeviceGetP2PAttribute", ("hipDeviceGetP2PAttribute", CONV_PEER, API_DRIVER, HIP_UNSUPPORTED)), ("cuDevicePrimaryCtxGetState", ("hipDevicePrimaryCtxGetState", CONV_CONTEXT, API_DRIVER)), ("cuDevicePrimaryCtxRelease", ("hipDevicePrimaryCtxRelease", CONV_CONTEXT, API_DRIVER)), ("cuDevicePrimaryCtxReset", ("hipDevicePrimaryCtxReset", CONV_CONTEXT, API_DRIVER)), ("cuDevicePrimaryCtxRetain", ("hipDevicePrimaryCtxRetain", CONV_CONTEXT, API_DRIVER)), ("cuDevicePrimaryCtxSetFlags", ("hipDevicePrimaryCtxSetFlags", CONV_CONTEXT, API_DRIVER)), ("cuDeviceGet", ("hipGetDevice", CONV_DEVICE, API_DRIVER)), ("cuDeviceGetName", ("hipDeviceGetName", CONV_DEVICE, API_DRIVER)), ("cuDeviceGetCount", ("hipGetDeviceCount", CONV_DEVICE, API_DRIVER)), ("cuDeviceGetAttribute", ("hipDeviceGetAttribute", CONV_DEVICE, API_DRIVER)), ("cuDeviceGetPCIBusId", ("hipDeviceGetPCIBusId", CONV_DEVICE, API_DRIVER)), ("cuDeviceGetByPCIBusId", ("hipDeviceGetByPCIBusId", CONV_DEVICE, API_DRIVER)), ("cuDeviceTotalMem_v2", ("hipDeviceTotalMem", CONV_DEVICE, API_DRIVER)), ("cuDeviceComputeCapability", ("hipDeviceComputeCapability", CONV_DEVICE, API_DRIVER)), ("cuDeviceGetProperties", ("hipGetDeviceProperties", CONV_DEVICE, API_DRIVER)), ("cuLinkAddData", ("hipLinkAddData", CONV_MODULE, API_DRIVER, HIP_UNSUPPORTED)), ("cuLinkAddFile", ("hipLinkAddFile", CONV_MODULE, API_DRIVER, HIP_UNSUPPORTED)), ("cuLinkComplete", ("hipLinkComplete", CONV_MODULE, API_DRIVER, HIP_UNSUPPORTED)), ("cuLinkCreate", ("hipLinkCreate", CONV_MODULE, API_DRIVER, HIP_UNSUPPORTED)), ("cuLinkDestroy", ("hipLinkDestroy", CONV_MODULE, API_DRIVER, HIP_UNSUPPORTED)), ("cuModuleGetFunction", ("hipModuleGetFunction", CONV_MODULE, API_DRIVER)), ("cuModuleGetGlobal_v2", ("hipModuleGetGlobal", CONV_MODULE, API_DRIVER)), ("cuModuleGetSurfRef", ("hipModuleGetSurfRef", CONV_MODULE, API_DRIVER, HIP_UNSUPPORTED)), ("cuModuleGetTexRef", ("hipModuleGetTexRef", CONV_MODULE, API_DRIVER)), ("cuModuleLoad", ("hipModuleLoad", CONV_MODULE, API_DRIVER)), ("cuModuleLoadData", ("hipModuleLoadData", CONV_MODULE, API_DRIVER)), ("cuModuleLoadDataEx", ("hipModuleLoadDataEx", CONV_MODULE, API_DRIVER)), ("cuModuleLoadFatBinary", ("hipModuleLoadFatBinary", CONV_MODULE, API_DRIVER, HIP_UNSUPPORTED)), ("cuModuleUnload", ("hipModuleUnload", CONV_MODULE, API_DRIVER)), ("CU_DEVICE_P2P_ATTRIBUTE_PERFORMANCE_RANK", ("hipDeviceP2PAttributePerformanceRank", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_DEVICE_P2P_ATTRIBUTE_ACCESS_SUPPORTED", ("hipDeviceP2PAttributeAccessSupported", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_DEVICE_P2P_ATTRIBUTE_NATIVE_ATOMIC_SUPPORTED", ("hipDeviceP2PAttributeNativeAtomicSupported", CONV_TYPE, API_DRIVER, HIP_UNSUPPORTED)), ("CU_EVENT_DEFAULT", ("hipEventDefault", CONV_EVENT, API_DRIVER)), ("CU_EVENT_BLOCKING_SYNC", ("hipEventBlockingSync", CONV_EVENT, API_DRIVER)), ("CU_EVENT_DISABLE_TIMING", ("hipEventDisableTiming", CONV_EVENT, API_DRIVER)), ("CU_EVENT_INTERPROCESS", ("hipEventInterprocess", CONV_EVENT, API_DRIVER)), ("cuEventCreate", ("hipEventCreate", CONV_EVENT, API_DRIVER)), ("cuEventDestroy_v2", ("hipEventDestroy", CONV_EVENT, API_DRIVER)), ("cuEventElapsedTime", ("hipEventElapsedTime", CONV_EVENT, API_DRIVER)), ("cuEventQuery", ("hipEventQuery", CONV_EVENT, API_DRIVER)), ("cuEventRecord", ("hipEventRecord", CONV_EVENT, API_DRIVER)), ("cuEventSynchronize", ("hipEventSynchronize", CONV_EVENT, API_DRIVER)), ("cuFuncGetAttribute", ("hipFuncGetAttribute", CONV_MODULE, API_DRIVER, HIP_UNSUPPORTED)), ("cuFuncSetCacheConfig", ("hipFuncSetCacheConfig", CONV_MODULE, API_DRIVER)), ("cuFuncSetSharedMemConfig", ("hipFuncSetSharedMemConfig", CONV_MODULE, API_DRIVER, HIP_UNSUPPORTED)), ("cuLaunchKernel", ("hipModuleLaunchKernel", CONV_MODULE, API_DRIVER)), ("cuFuncSetBlockShape", ("hipFuncSetBlockShape", CONV_MODULE, API_DRIVER, HIP_UNSUPPORTED)), ("cuFuncSetSharedSize", ("hipFuncSetSharedSize", CONV_MODULE, API_DRIVER, HIP_UNSUPPORTED)), ("cuLaunch", ("hipLaunch", CONV_MODULE, API_DRIVER, HIP_UNSUPPORTED)), ("cuLaunchGrid", ("hipLaunchGrid", CONV_MODULE, API_DRIVER, HIP_UNSUPPORTED)), ("cuLaunchGridAsync", ("hipLaunchGridAsync", CONV_MODULE, API_DRIVER, HIP_UNSUPPORTED)), ("cuParamSetf", ("hipParamSetf", CONV_MODULE, API_DRIVER, HIP_UNSUPPORTED)), ("cuParamSeti", ("hipParamSeti", CONV_MODULE, API_DRIVER, HIP_UNSUPPORTED)), ("cuParamSetSize", ("hipParamSetSize", CONV_MODULE, API_DRIVER, HIP_UNSUPPORTED)), ("cuParamSetSize", ("hipParamSetSize", CONV_MODULE, API_DRIVER, HIP_UNSUPPORTED)), ("cuParamSetv", ("hipParamSetv", CONV_MODULE, API_DRIVER, HIP_UNSUPPORTED)), ("cuOccupancyMaxActiveBlocksPerMultiprocessor", ("hipOccupancyMaxActiveBlocksPerMultiprocessor", CONV_OCCUPANCY, API_DRIVER)), ("cuOccupancyMaxActiveBlocksPerMultiprocessorWithFlags", ("hipOccupancyMaxActiveBlocksPerMultiprocessorWithFlags", CONV_OCCUPANCY, API_DRIVER, HIP_UNSUPPORTED)), ("cuOccupancyMaxPotentialBlockSize", ("hipOccupancyMaxPotentialBlockSize", CONV_OCCUPANCY, API_DRIVER)), ("cuOccupancyMaxPotentialBlockSizeWithFlags", ("hipOccupancyMaxPotentialBlockSizeWithFlags", CONV_OCCUPANCY, API_DRIVER, HIP_UNSUPPORTED)), ("cuStreamAddCallback", ("hipStreamAddCallback", CONV_STREAM, API_DRIVER)), ("cuStreamAttachMemAsync", ("hipStreamAttachMemAsync", CONV_STREAM, API_DRIVER, HIP_UNSUPPORTED)), ("cuStreamCreate", ("hipStreamCreate__", CONV_STREAM, API_DRIVER, HIP_UNSUPPORTED)), ("cuStreamCreateWithPriority", ("hipStreamCreateWithPriority", CONV_STREAM, API_DRIVER, HIP_UNSUPPORTED)), ("cuStreamDestroy_v2", ("hipStreamDestroy", CONV_STREAM, API_DRIVER)), ("cuStreamGetFlags", ("hipStreamGetFlags", CONV_STREAM, API_DRIVER)), ("cuStreamGetPriority", ("hipStreamGetPriority", CONV_STREAM, API_DRIVER, HIP_UNSUPPORTED)), ("cuStreamQuery", ("hipStreamQuery", CONV_STREAM, API_DRIVER)), ("cuStreamSynchronize", ("hipStreamSynchronize", CONV_STREAM, API_DRIVER)), ("cuStreamWaitEvent", ("hipStreamWaitEvent", CONV_STREAM, API_DRIVER)), ("cuStreamWaitValue32", ("hipStreamWaitValue32", CONV_STREAM, API_DRIVER, HIP_UNSUPPORTED)), ("cuStreamWriteValue32", ("hipStreamWriteValue32", CONV_STREAM, API_DRIVER, HIP_UNSUPPORTED)), ("cuStreamBatchMemOp", ("hipStreamBatchMemOp", CONV_STREAM, API_DRIVER, HIP_UNSUPPORTED)), ("cuArray3DCreate", ("hipArray3DCreate", CONV_MEM, API_DRIVER)), ("cuArray3DGetDescriptor", ("hipArray3DGetDescriptor", CONV_MEM, API_DRIVER, HIP_UNSUPPORTED)), ("cuArrayCreate", ("hipArrayCreate", CONV_MEM, API_DRIVER, HIP_UNSUPPORTED)), ("cuArrayDestroy", ("hipArrayDestroy", CONV_MEM, API_DRIVER, HIP_UNSUPPORTED)), ("cuArrayGetDescriptor", ("hipArrayGetDescriptor", CONV_MEM, API_DRIVER, HIP_UNSUPPORTED)), ("cuIpcCloseMemHandle", ("hipIpcCloseMemHandle", CONV_MEM, API_DRIVER, HIP_UNSUPPORTED)), ("cuIpcGetEventHandle", ("hipIpcGetEventHandle", CONV_MEM, API_DRIVER, HIP_UNSUPPORTED)), ("cuIpcGetMemHandle", ("hipIpcGetMemHandle", CONV_MEM, API_DRIVER, HIP_UNSUPPORTED)), ("cuIpcOpenEventHandle", ("hipIpcOpenEventHandle", CONV_MEM, API_DRIVER, HIP_UNSUPPORTED)), ("cuIpcOpenMemHandle", ("hipIpcOpenMemHandle", CONV_MEM, API_DRIVER, HIP_UNSUPPORTED)), ("cuMemAlloc_v2", ("hipMalloc", CONV_MEM, API_DRIVER)), ("cuMemAllocHost", ("hipMemAllocHost", CONV_MEM, API_DRIVER, HIP_UNSUPPORTED)), ("cuMemAllocManaged", ("hipMemAllocManaged", CONV_MEM, API_DRIVER, HIP_UNSUPPORTED)), ("cuMemAllocPitch", ("hipMemAllocPitch__", CONV_MEM, API_DRIVER, HIP_UNSUPPORTED)), ("cuMemcpy", ("hipMemcpy__", CONV_MEM, API_DRIVER, HIP_UNSUPPORTED)), ("cuMemcpy2D", ("hipMemcpy2D__", CONV_MEM, API_DRIVER, HIP_UNSUPPORTED)), ("cuMemcpy2DAsync", ("hipMemcpy2DAsync__", CONV_MEM, API_DRIVER, HIP_UNSUPPORTED)), ("cuMemcpy2DUnaligned", ("hipMemcpy2DUnaligned", CONV_MEM, API_DRIVER, HIP_UNSUPPORTED)), ("cuMemcpy3D", ("hipMemcpy3D__", CONV_MEM, API_DRIVER, HIP_UNSUPPORTED)), ("cuMemcpy3DAsync", ("hipMemcpy3DAsync__", CONV_MEM, API_DRIVER, HIP_UNSUPPORTED)), ("cuMemcpy3DPeer", ("hipMemcpy3DPeer__", CONV_MEM, API_DRIVER, HIP_UNSUPPORTED)), ("cuMemcpy3DPeerAsync", ("hipMemcpy3DPeerAsync__", CONV_MEM, API_DRIVER, HIP_UNSUPPORTED)), ("cuMemcpyAsync", ("hipMemcpyAsync__", CONV_MEM, API_DRIVER, HIP_UNSUPPORTED)), ("cuMemcpyAtoA", ("hipMemcpyAtoA", CONV_MEM, API_DRIVER, HIP_UNSUPPORTED)), ("cuMemcpyAtoD", ("hipMemcpyAtoD", CONV_MEM, API_DRIVER, HIP_UNSUPPORTED)), ("cuMemcpyAtoH", ("hipMemcpyAtoH", CONV_MEM, API_DRIVER, HIP_UNSUPPORTED)), ("cuMemcpyAtoHAsync", ("hipMemcpyAtoHAsync", CONV_MEM, API_DRIVER, HIP_UNSUPPORTED)), ("cuMemcpyDtoA", ("hipMemcpyDtoA", CONV_MEM, API_DRIVER, HIP_UNSUPPORTED)), ("cuMemcpyDtoD_v2", ("hipMemcpyDtoD", CONV_MEM, API_DRIVER)), ("cuMemcpyDtoDAsync_v2", ("hipMemcpyDtoDAsync", CONV_MEM, API_DRIVER)), ("cuMemcpyDtoH_v2", ("hipMemcpyDtoH", CONV_MEM, API_DRIVER)), ("cuMemcpyDtoHAsync_v2", ("hipMemcpyDtoHAsync", CONV_MEM, API_DRIVER)), ("cuMemcpyHtoA", ("hipMemcpyHtoA", CONV_MEM, API_DRIVER, HIP_UNSUPPORTED)), ("cuMemcpyHtoAAsync", ("hipMemcpyHtoAAsync", CONV_MEM, API_DRIVER, HIP_UNSUPPORTED)), ("cuMemcpyHtoD_v2", ("hipMemcpyHtoD", CONV_MEM, API_DRIVER)), ("cuMemcpyHtoDAsync_v2", ("hipMemcpyHtoDAsync", CONV_MEM, API_DRIVER)), ("cuMemcpyPeerAsync", ("hipMemcpyPeerAsync__", CONV_MEM, API_DRIVER, HIP_UNSUPPORTED)), ("cuMemcpyPeer", ("hipMemcpyPeer__", CONV_MEM, API_DRIVER, HIP_UNSUPPORTED)), ("cuMemFree_v2", ("hipFree", CONV_MEM, API_DRIVER)), ("cuMemFreeHost", ("hipHostFree", CONV_MEM, API_DRIVER)), ("cuMemGetAddressRange", ("hipMemGetAddressRange", CONV_MEM, API_DRIVER, HIP_UNSUPPORTED)), ("cuMemGetInfo_v2", ("hipMemGetInfo", CONV_MEM, API_DRIVER)), ("cuMemHostAlloc", ("hipHostMalloc", CONV_MEM, API_DRIVER)), ("cuMemHostGetDevicePointer", ("hipMemHostGetDevicePointer", CONV_MEM, API_DRIVER, HIP_UNSUPPORTED)), ("cuMemHostGetFlags", ("hipMemHostGetFlags", CONV_MEM, API_DRIVER, HIP_UNSUPPORTED)), ("cuMemHostRegister_v2", ("hipHostRegister", CONV_MEM, API_DRIVER)), ("cuMemHostUnregister", ("hipHostUnregister", CONV_MEM, API_DRIVER)), ("cuMemsetD16_v2", ("hipMemsetD16", CONV_MEM, API_DRIVER, HIP_UNSUPPORTED)), ("cuMemsetD16Async", ("hipMemsetD16Async", CONV_MEM, API_DRIVER, HIP_UNSUPPORTED)), ("cuMemsetD2D16_v2", ("hipMemsetD2D16", CONV_MEM, API_DRIVER, HIP_UNSUPPORTED)), ("cuMemsetD2D16Async", ("hipMemsetD2D16Async", CONV_MEM, API_DRIVER, HIP_UNSUPPORTED)), ("cuMemsetD2D32_v2", ("hipMemsetD2D32", CONV_MEM, API_DRIVER, HIP_UNSUPPORTED)), ("cuMemsetD2D32Async", ("hipMemsetD2D32Async", CONV_MEM, API_DRIVER, HIP_UNSUPPORTED)), ("cuMemsetD2D8_v2", ("hipMemsetD2D8", CONV_MEM, API_DRIVER, HIP_UNSUPPORTED)), ("cuMemsetD2D8Async", ("hipMemsetD2D8Async", CONV_MEM, API_DRIVER, HIP_UNSUPPORTED)), ("cuMemsetD32_v2", ("hipMemset", CONV_MEM, API_DRIVER)), ("cuMemsetD32Async", ("hipMemsetAsync", CONV_MEM, API_DRIVER)), ("cuMemsetD8_v2", ("hipMemsetD8", CONV_MEM, API_DRIVER, HIP_UNSUPPORTED)), ("cuMemsetD8Async", ("hipMemsetD8Async", CONV_MEM, API_DRIVER, HIP_UNSUPPORTED)), ("cuMipmappedArrayCreate", ("hipMipmappedArrayCreate", CONV_MEM, API_DRIVER, HIP_UNSUPPORTED)), ("cuMipmappedArrayDestroy", ("hipMipmappedArrayDestroy", CONV_MEM, API_DRIVER, HIP_UNSUPPORTED)), ("cuMipmappedArrayGetLevel", ("hipMipmappedArrayGetLevel", CONV_MEM, API_DRIVER, HIP_UNSUPPORTED)), ("cuMemPrefetchAsync", ("hipMemPrefetchAsync__", CONV_MEM, API_DRIVER, HIP_UNSUPPORTED)), ("cuMemAdvise", ("hipMemAdvise", CONV_MEM, API_DRIVER, HIP_UNSUPPORTED)), ("cuMemRangeGetAttribute", ("hipMemRangeGetAttribute", CONV_MEM, API_DRIVER, HIP_UNSUPPORTED)), ("cuMemRangeGetAttributes", ("hipMemRangeGetAttributes", CONV_MEM, API_DRIVER, HIP_UNSUPPORTED)), ("cuPointerGetAttribute", ("hipPointerGetAttribute", CONV_MEM, API_DRIVER, HIP_UNSUPPORTED)), ("cuPointerGetAttributes", ("hipPointerGetAttributes", CONV_MEM, API_DRIVER, HIP_UNSUPPORTED)), ("cuPointerSetAttribute", ("hipPointerSetAttribute", CONV_MEM, API_DRIVER, HIP_UNSUPPORTED)), ("CU_TR_FILTER_MODE_POINT", ("hipFilterModePoint", CONV_TEX, API_DRIVER)), ("CU_TR_FILTER_MODE_LINEAR", ("hipFilterModeLinear", CONV_TEX, API_DRIVER, HIP_UNSUPPORTED)), ("cuTexRefGetAddress", ("hipTexRefGetAddress", CONV_TEX, API_DRIVER, HIP_UNSUPPORTED)), ("cuTexRefGetAddressMode", ("hipTexRefGetAddressMode", CONV_TEX, API_DRIVER, HIP_UNSUPPORTED)), ("cuTexRefGetArray", ("hipTexRefGetArray", CONV_TEX, API_DRIVER, HIP_UNSUPPORTED)), ("cuTexRefGetBorderColor", ("hipTexRefGetBorderColor", CONV_TEX, API_DRIVER, HIP_UNSUPPORTED)), ("cuTexRefGetFilterMode", ("hipTexRefGetFilterMode", CONV_TEX, API_DRIVER, HIP_UNSUPPORTED)), ("cuTexRefGetFlags", ("hipTexRefGetFlags", CONV_TEX, API_DRIVER, HIP_UNSUPPORTED)), ("cuTexRefGetFormat", ("hipTexRefGetFormat", CONV_TEX, API_DRIVER, HIP_UNSUPPORTED)), ("cuTexRefGetMaxAnisotropy", ("hipTexRefGetMaxAnisotropy", CONV_TEX, API_DRIVER, HIP_UNSUPPORTED)), ("cuTexRefGetMipmapFilterMode", ("hipTexRefGetMipmapFilterMode", CONV_TEX, API_DRIVER, HIP_UNSUPPORTED)), ("cuTexRefGetMipmapLevelBias", ("hipTexRefGetMipmapLevelBias", CONV_TEX, API_DRIVER, HIP_UNSUPPORTED)), ("cuTexRefGetMipmapLevelClamp", ("hipTexRefGetMipmapLevelClamp", CONV_TEX, API_DRIVER, HIP_UNSUPPORTED)), ("cuTexRefGetMipmappedArray", ("hipTexRefGetMipmappedArray", CONV_TEX, API_DRIVER, HIP_UNSUPPORTED)), ("cuTexRefSetAddress", ("hipTexRefSetAddress", CONV_TEX, API_DRIVER, HIP_UNSUPPORTED)), ("cuTexRefSetAddress2D", ("hipTexRefSetAddress2D", CONV_TEX, API_DRIVER, HIP_UNSUPPORTED)), ("cuTexRefSetAddressMode", ("hipTexRefSetAddressMode", CONV_TEX, API_DRIVER)), ("cuTexRefSetArray", ("hipTexRefSetArray", CONV_TEX, API_DRIVER)), ("cuTexRefSetBorderColor", ("hipTexRefSetBorderColor", CONV_TEX, API_DRIVER, HIP_UNSUPPORTED)), ("cuTexRefSetFilterMode", ("hipTexRefSetFilterMode", CONV_TEX, API_DRIVER)), ("cuTexRefSetFlags", ("hipTexRefSetFlags", CONV_TEX, API_DRIVER)), ("cuTexRefSetFormat", ("hipTexRefSetFormat", CONV_TEX, API_DRIVER)), ("cuTexRefSetMaxAnisotropy", ("hipTexRefSetMaxAnisotropy", CONV_TEX, API_DRIVER, HIP_UNSUPPORTED)), ("cuTexRefSetMipmapFilterMode", ("hipTexRefSetMipmapFilterMode", CONV_TEX, API_DRIVER, HIP_UNSUPPORTED)), ("cuTexRefSetMipmapLevelBias", ("hipTexRefSetMipmapLevelBias", CONV_TEX, API_DRIVER, HIP_UNSUPPORTED)), ("cuTexRefSetMipmapLevelClamp", ("hipTexRefSetMipmapLevelClamp", CONV_TEX, API_DRIVER, HIP_UNSUPPORTED)), ("cuTexRefSetMipmappedArray", ("hipTexRefSetMipmappedArray", CONV_TEX, API_DRIVER, HIP_UNSUPPORTED)), ("cuTexRefCreate", ("hipTexRefCreate", CONV_TEX, API_DRIVER, HIP_UNSUPPORTED)), ("cuTexRefDestroy", ("hipTexRefDestroy", CONV_TEX, API_DRIVER, HIP_UNSUPPORTED)), ("cuSurfRefGetArray", ("hipSurfRefGetArray", CONV_SURFACE, API_DRIVER, HIP_UNSUPPORTED)), ("cuSurfRefSetArray", ("hipSurfRefSetArray", CONV_SURFACE, API_DRIVER, HIP_UNSUPPORTED)), ("cuTexObjectCreate", ("hipTexObjectCreate", CONV_TEX, API_DRIVER, HIP_UNSUPPORTED)), ("cuTexObjectDestroy", ("hipTexObjectDestroy", CONV_TEX, API_DRIVER, HIP_UNSUPPORTED)), ("cuTexObjectGetResourceDesc", ("hipTexObjectGetResourceDesc", CONV_TEX, API_DRIVER, HIP_UNSUPPORTED)), ("cuTexObjectGetResourceViewDesc", ("hipTexObjectGetResourceViewDesc", CONV_TEX, API_DRIVER, HIP_UNSUPPORTED)), ("cuTexObjectGetTextureDesc", ("hipTexObjectGetTextureDesc", CONV_TEX, API_DRIVER, HIP_UNSUPPORTED)), ("cuSurfObjectCreate", ("hipSurfObjectCreate", CONV_TEX, API_DRIVER, HIP_UNSUPPORTED)), ("cuSurfObjectDestroy", ("hipSurfObjectDestroy", CONV_TEX, API_DRIVER, HIP_UNSUPPORTED)), ("cuSurfObjectGetResourceDesc", ("hipSurfObjectGetResourceDesc", CONV_TEX, API_DRIVER, HIP_UNSUPPORTED)), ("cuGraphicsMapResources", ("hipGraphicsMapResources", CONV_GRAPHICS, API_DRIVER, HIP_UNSUPPORTED)), ("cuGraphicsResourceGetMappedMipmappedArray", ("hipGraphicsResourceGetMappedMipmappedArray", CONV_GRAPHICS, API_DRIVER, HIP_UNSUPPORTED)), ("cuGraphicsResourceGetMappedPointer", ("hipGraphicsResourceGetMappedPointer", CONV_GRAPHICS, API_DRIVER, HIP_UNSUPPORTED)), ("cuGraphicsResourceSetMapFlags", ("hipGraphicsResourceSetMapFlags", CONV_GRAPHICS, API_DRIVER, HIP_UNSUPPORTED)), ("cuGraphicsSubResourceGetMappedArray", ("hipGraphicsSubResourceGetMappedArray", CONV_GRAPHICS, API_DRIVER, HIP_UNSUPPORTED)), ("cuGraphicsUnmapResources", ("hipGraphicsUnmapResources", CONV_GRAPHICS, API_DRIVER, HIP_UNSUPPORTED)), ("cuGraphicsUnregisterResource", ("hipGraphicsUnregisterResource", CONV_GRAPHICS, API_DRIVER, HIP_UNSUPPORTED)), ("cuProfilerInitialize", ("hipProfilerInitialize", CONV_OTHER, API_DRIVER, HIP_UNSUPPORTED)), ("cuProfilerStart", ("hipProfilerStart", CONV_OTHER, API_DRIVER)), ("cuProfilerStop", ("hipProfilerStop", CONV_OTHER, API_DRIVER)), ("CU_GL_DEVICE_LIST_ALL", ("HIP_GL_DEVICE_LIST_ALL", CONV_GL, API_DRIVER, HIP_UNSUPPORTED)), ("CU_GL_DEVICE_LIST_CURRENT_FRAME", ("HIP_GL_DEVICE_LIST_CURRENT_FRAME", CONV_GL, API_DRIVER, HIP_UNSUPPORTED)), ("CU_GL_DEVICE_LIST_NEXT_FRAME", ("HIP_GL_DEVICE_LIST_NEXT_FRAME", CONV_GL, API_DRIVER, HIP_UNSUPPORTED)), ("cuGLGetDevices", ("hipGLGetDevices", CONV_GL, API_DRIVER, HIP_UNSUPPORTED)), ("cuGraphicsGLRegisterBuffer", ("hipGraphicsGLRegisterBuffer", CONV_GL, API_DRIVER, HIP_UNSUPPORTED)), ("cuGraphicsGLRegisterImage", ("hipGraphicsGLRegisterImage", CONV_GL, API_DRIVER, HIP_UNSUPPORTED)), ("cuWGLGetDevice", ("hipWGLGetDevice", CONV_GL, API_DRIVER, HIP_UNSUPPORTED)), ("CU_GL_MAP_RESOURCE_FLAGS_NONE", ("HIP_GL_MAP_RESOURCE_FLAGS_NONE", CONV_GL, API_DRIVER, HIP_UNSUPPORTED)), ("CU_GL_MAP_RESOURCE_FLAGS_READ_ONLY", ("HIP_GL_MAP_RESOURCE_FLAGS_READ_ONLY", CONV_GL, API_DRIVER, HIP_UNSUPPORTED)), ("CU_GL_MAP_RESOURCE_FLAGS_WRITE_DISCARD", ("HIP_GL_MAP_RESOURCE_FLAGS_WRITE_DISCARD", CONV_GL, API_DRIVER, HIP_UNSUPPORTED)), ("cuGLCtxCreate", ("hipGLCtxCreate", CONV_GL, API_DRIVER, HIP_UNSUPPORTED)), ("cuGLInit", ("hipGLInit", CONV_GL, API_DRIVER, HIP_UNSUPPORTED)), ("cuGLMapBufferObject", ("hipGLMapBufferObject", CONV_GL, API_DRIVER, HIP_UNSUPPORTED)), ("cuGLMapBufferObjectAsync", ("hipGLMapBufferObjectAsync", CONV_GL, API_DRIVER, HIP_UNSUPPORTED)), ("cuGLRegisterBufferObject", ("hipGLRegisterBufferObject", CONV_GL, API_DRIVER, HIP_UNSUPPORTED)), ("cuGLSetBufferObjectMapFlags", ("hipGLSetBufferObjectMapFlags", CONV_GL, API_DRIVER, HIP_UNSUPPORTED)), ("cuGLUnmapBufferObject", ("hipGLUnmapBufferObject", CONV_GL, API_DRIVER, HIP_UNSUPPORTED)), ("cuGLUnmapBufferObjectAsync", ("hipGLUnmapBufferObjectAsync", CONV_GL, API_DRIVER, HIP_UNSUPPORTED)), ("cuGLUnregisterBufferObject", ("hipGLUnregisterBufferObject", CONV_GL, API_DRIVER, HIP_UNSUPPORTED)), ("CU_D3D9_DEVICE_LIST_ALL", ("HIP_D3D9_DEVICE_LIST_ALL", CONV_D3D9, API_DRIVER, HIP_UNSUPPORTED)), ("CU_D3D9_DEVICE_LIST_CURRENT_FRAME", ("HIP_D3D9_DEVICE_LIST_CURRENT_FRAME", CONV_D3D9, API_DRIVER, HIP_UNSUPPORTED)), ("CU_D3D9_DEVICE_LIST_NEXT_FRAME", ("HIP_D3D9_DEVICE_LIST_NEXT_FRAME", CONV_D3D9, API_DRIVER, HIP_UNSUPPORTED)), ("cuD3D9CtxCreate", ("hipD3D9CtxCreate", CONV_D3D9, API_DRIVER, HIP_UNSUPPORTED)), ("cuD3D9CtxCreateOnDevice", ("hipD3D9CtxCreateOnDevice", CONV_D3D9, API_DRIVER, HIP_UNSUPPORTED)), ("cuD3D9GetDevice", ("hipD3D9GetDevice", CONV_D3D9, API_DRIVER, HIP_UNSUPPORTED)), ("cuD3D9GetDevices", ("hipD3D9GetDevices", CONV_D3D9, API_DRIVER, HIP_UNSUPPORTED)), ("cuD3D9GetDirect3DDevice", ("hipD3D9GetDirect3DDevice", CONV_D3D9, API_DRIVER, HIP_UNSUPPORTED)), ("cuGraphicsD3D9RegisterResource", ("hipGraphicsD3D9RegisterResource", CONV_D3D9, API_DRIVER, HIP_UNSUPPORTED)), ("CU_D3D9_MAPRESOURCE_FLAGS_NONE", ("HIP_D3D9_MAPRESOURCE_FLAGS_NONE", CONV_D3D9, API_DRIVER, HIP_UNSUPPORTED)), ("CU_D3D9_MAPRESOURCE_FLAGS_READONLY", ("HIP_D3D9_MAPRESOURCE_FLAGS_READONLY", CONV_D3D9, API_DRIVER, HIP_UNSUPPORTED)), ("CU_D3D9_MAPRESOURCE_FLAGS_WRITEDISCARD", ("HIP_D3D9_MAPRESOURCE_FLAGS_WRITEDISCARD", CONV_D3D9, API_DRIVER, HIP_UNSUPPORTED)), ("CU_D3D9_REGISTER_FLAGS_NONE", ("HIP_D3D9_REGISTER_FLAGS_NONE", CONV_D3D9, API_DRIVER, HIP_UNSUPPORTED)), ("CU_D3D9_REGISTER_FLAGS_ARRAY", ("HIP_D3D9_REGISTER_FLAGS_ARRAY", CONV_D3D9, API_DRIVER, HIP_UNSUPPORTED)), ("cuD3D9MapResources", ("hipD3D9MapResources", CONV_D3D9, API_DRIVER, HIP_UNSUPPORTED)), ("cuD3D9RegisterResource", ("hipD3D9RegisterResource", CONV_D3D9, API_DRIVER, HIP_UNSUPPORTED)), ("cuD3D9ResourceGetMappedArray", ("hipD3D9ResourceGetMappedArray", CONV_D3D9, API_DRIVER, HIP_UNSUPPORTED)), ("cuD3D9ResourceGetMappedPitch", ("hipD3D9ResourceGetMappedPitch", CONV_D3D9, API_DRIVER, HIP_UNSUPPORTED)), ("cuD3D9ResourceGetMappedPointer", ("hipD3D9ResourceGetMappedPointer", CONV_D3D9, API_DRIVER, HIP_UNSUPPORTED)), ("cuD3D9ResourceGetMappedSize", ("hipD3D9ResourceGetMappedSize", CONV_D3D9, API_DRIVER, HIP_UNSUPPORTED)), ("cuD3D9ResourceGetSurfaceDimensions", ("hipD3D9ResourceGetSurfaceDimensions", CONV_D3D9, API_DRIVER, HIP_UNSUPPORTED)), ("cuD3D9ResourceSetMapFlags", ("hipD3D9ResourceSetMapFlags", CONV_D3D9, API_DRIVER, HIP_UNSUPPORTED)), ("cuD3D9UnmapResources", ("hipD3D9UnmapResources", CONV_D3D9, API_DRIVER, HIP_UNSUPPORTED)), ("cuD3D9UnregisterResource", ("hipD3D9UnregisterResource", CONV_D3D9, API_DRIVER, HIP_UNSUPPORTED)), ("CU_D3D10_DEVICE_LIST_ALL", ("HIP_D3D10_DEVICE_LIST_ALL", CONV_D3D10, API_DRIVER, HIP_UNSUPPORTED)), ("CU_D3D10_DEVICE_LIST_CURRENT_FRAME", ("HIP_D3D10_DEVICE_LIST_CURRENT_FRAME", CONV_D3D10, API_DRIVER, HIP_UNSUPPORTED)), ("CU_D3D10_DEVICE_LIST_NEXT_FRAME", ("HIP_D3D10_DEVICE_LIST_NEXT_FRAME", CONV_D3D10, API_DRIVER, HIP_UNSUPPORTED)), ("cuD3D10GetDevice", ("hipD3D10GetDevice", CONV_D3D10, API_DRIVER, HIP_UNSUPPORTED)), ("cuD3D10GetDevices", ("hipD3D10GetDevices", CONV_D3D10, API_DRIVER, HIP_UNSUPPORTED)), ("cuGraphicsD3D10RegisterResource", ("hipGraphicsD3D10RegisterResource", CONV_D3D10, API_DRIVER, HIP_UNSUPPORTED)), ("CU_D3D10_MAPRESOURCE_FLAGS_NONE", ("HIP_D3D10_MAPRESOURCE_FLAGS_NONE", CONV_D3D10, API_DRIVER, HIP_UNSUPPORTED)), ("CU_D3D10_MAPRESOURCE_FLAGS_READONLY", ("HIP_D3D10_MAPRESOURCE_FLAGS_READONLY", CONV_D3D10, API_DRIVER, HIP_UNSUPPORTED)), ("CU_D3D10_MAPRESOURCE_FLAGS_WRITEDISCARD", ("HIP_D3D10_MAPRESOURCE_FLAGS_WRITEDISCARD", CONV_D3D10, API_DRIVER, HIP_UNSUPPORTED)), ("CU_D3D10_REGISTER_FLAGS_NONE", ("HIP_D3D10_REGISTER_FLAGS_NONE", CONV_D3D10, API_DRIVER, HIP_UNSUPPORTED)), ("CU_D3D10_REGISTER_FLAGS_ARRAY", ("HIP_D3D10_REGISTER_FLAGS_ARRAY", CONV_D3D10, API_DRIVER, HIP_UNSUPPORTED)), ("cuD3D10CtxCreate", ("hipD3D10CtxCreate", CONV_D3D10, API_DRIVER, HIP_UNSUPPORTED)), ("cuD3D10CtxCreateOnDevice", ("hipD3D10CtxCreateOnDevice", CONV_D3D10, API_DRIVER, HIP_UNSUPPORTED)), ("cuD3D10GetDirect3DDevice", ("hipD3D10GetDirect3DDevice", CONV_D3D10, API_DRIVER, HIP_UNSUPPORTED)), ("cuD3D10MapResources", ("hipD3D10MapResources", CONV_D3D10, API_DRIVER, HIP_UNSUPPORTED)), ("cuD3D10RegisterResource", ("hipD3D10RegisterResource", CONV_D3D10, API_DRIVER, HIP_UNSUPPORTED)), ("cuD3D10ResourceGetMappedArray", ("hipD3D10ResourceGetMappedArray", CONV_D3D10, API_DRIVER, HIP_UNSUPPORTED)), ("cuD3D10ResourceGetMappedPitch", ("hipD3D10ResourceGetMappedPitch", CONV_D3D10, API_DRIVER, HIP_UNSUPPORTED)), ("cuD3D10ResourceGetMappedPointer", ("hipD3D10ResourceGetMappedPointer", CONV_D3D10, API_DRIVER, HIP_UNSUPPORTED)), ("cuD3D10ResourceGetMappedSize", ("hipD3D10ResourceGetMappedSize", CONV_D3D10, API_DRIVER, HIP_UNSUPPORTED)), ("cuD3D10ResourceGetSurfaceDimensions", ("hipD3D10ResourceGetSurfaceDimensions", CONV_D3D10, API_DRIVER, HIP_UNSUPPORTED)), ("cuD310ResourceSetMapFlags", ("hipD3D10ResourceSetMapFlags", CONV_D3D10, API_DRIVER, HIP_UNSUPPORTED)), ("cuD3D10UnmapResources", ("hipD3D10UnmapResources", CONV_D3D10, API_DRIVER, HIP_UNSUPPORTED)), ("cuD3D10UnregisterResource", ("hipD3D10UnregisterResource", CONV_D3D10, API_DRIVER, HIP_UNSUPPORTED)), ("CU_D3D11_DEVICE_LIST_ALL", ("HIP_D3D11_DEVICE_LIST_ALL", CONV_D3D11, API_DRIVER, HIP_UNSUPPORTED)), ("CU_D3D11_DEVICE_LIST_CURRENT_FRAME", ("HIP_D3D11_DEVICE_LIST_CURRENT_FRAME", CONV_D3D11, API_DRIVER, HIP_UNSUPPORTED)), ("CU_D3D11_DEVICE_LIST_NEXT_FRAME", ("HIP_D3D11_DEVICE_LIST_NEXT_FRAME", CONV_D3D11, API_DRIVER, HIP_UNSUPPORTED)), ("cuD3D11GetDevice", ("hipD3D11GetDevice", CONV_D3D11, API_DRIVER, HIP_UNSUPPORTED)), ("cuD3D11GetDevices", ("hipD3D11GetDevices", CONV_D3D11, API_DRIVER, HIP_UNSUPPORTED)), ("cuGraphicsD3D11RegisterResource", ("hipGraphicsD3D11RegisterResource", CONV_D3D11, API_DRIVER, HIP_UNSUPPORTED)), ("cuD3D11CtxCreate", ("hipD3D11CtxCreate", CONV_D3D11, API_DRIVER, HIP_UNSUPPORTED)), ("cuD3D11CtxCreateOnDevice", ("hipD3D11CtxCreateOnDevice", CONV_D3D11, API_DRIVER, HIP_UNSUPPORTED)), ("cuD3D11GetDirect3DDevice", ("hipD3D11GetDirect3DDevice", CONV_D3D11, API_DRIVER, HIP_UNSUPPORTED)), ("cuGraphicsVDPAURegisterOutputSurface", ("hipGraphicsVDPAURegisterOutputSurface", CONV_VDPAU, API_DRIVER, HIP_UNSUPPORTED)), ("cuGraphicsVDPAURegisterVideoSurface", ("hipGraphicsVDPAURegisterVideoSurface", CONV_VDPAU, API_DRIVER, HIP_UNSUPPORTED)), ("cuVDPAUGetDevice", ("hipVDPAUGetDevice", CONV_VDPAU, API_DRIVER, HIP_UNSUPPORTED)), ("cuVDPAUCtxCreate", ("hipVDPAUCtxCreate", CONV_VDPAU, API_DRIVER, HIP_UNSUPPORTED)), ("cuEGLStreamConsumerAcquireFrame", ("hipEGLStreamConsumerAcquireFrame", CONV_EGL, API_DRIVER, HIP_UNSUPPORTED)), ("cuEGLStreamConsumerConnect", ("hipEGLStreamConsumerConnect", CONV_EGL, API_DRIVER, HIP_UNSUPPORTED)), ("cuEGLStreamConsumerConnectWithFlags", ("hipEGLStreamConsumerConnectWithFlags", CONV_EGL, API_DRIVER, HIP_UNSUPPORTED)), ("cuEGLStreamConsumerDisconnect", ("hipEGLStreamConsumerDisconnect", CONV_EGL, API_DRIVER, HIP_UNSUPPORTED)), ("cuEGLStreamConsumerReleaseFrame", ("hipEGLStreamConsumerReleaseFrame", CONV_EGL, API_DRIVER, HIP_UNSUPPORTED)), ("cuEGLStreamProducerConnect", ("hipEGLStreamProducerConnect", CONV_EGL, API_DRIVER, HIP_UNSUPPORTED)), ("cuEGLStreamProducerDisconnect", ("hipEGLStreamProducerDisconnect", CONV_EGL, API_DRIVER, HIP_UNSUPPORTED)), ("cuEGLStreamProducerPresentFrame", ("hipEGLStreamProducerPresentFrame", CONV_EGL, API_DRIVER, HIP_UNSUPPORTED)), ("cuEGLStreamProducerReturnFrame", ("hipEGLStreamProducerReturnFrame", CONV_EGL, API_DRIVER, HIP_UNSUPPORTED)), ("cuGraphicsEGLRegisterImage", ("hipGraphicsEGLRegisterImage", CONV_EGL, API_DRIVER, HIP_UNSUPPORTED)), ("cuGraphicsResourceGetMappedEglFrame", ("hipGraphicsResourceGetMappedEglFrame", CONV_EGL, API_DRIVER, HIP_UNSUPPORTED)), ("cudaDataType_t", ("hipDataType_t", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaDataType", ("hipDataType_t", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("CUDA_R_16F", ("hipR16F", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("CUDA_C_16F", ("hipC16F", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("CUDA_R_32F", ("hipR32F", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("CUDA_C_32F", ("hipC32F", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("CUDA_R_64F", ("hipR64F", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("CUDA_C_64F", ("hipC64F", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("CUDA_R_8I", ("hipR8I", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("CUDA_C_8I", ("hipC8I", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("CUDA_R_8U", ("hipR8U", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("CUDA_C_8U", ("hipC8U", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("CUDA_R_32I", ("hipR32I", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("CUDA_C_32I", ("hipC32I", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("CUDA_R_32U", ("hipR32U", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("CUDA_C_32U", ("hipC32U", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("MAJOR_VERSION", ("hipLibraryMajorVersion", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("MINOR_VERSION", ("hipLibraryMinorVersion", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("PATCH_LEVEL", ("hipLibraryPatchVersion", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaMemAttachGlobal", ("hipMemAttachGlobal", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaMemAttachHost", ("hipMemAttachHost", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaMemAttachSingle", ("hipMemAttachSingle", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaOccupancyDefault", ("hipOccupancyDefault", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaOccupancyDisableCachingOverride", ("hipOccupancyDisableCachingOverride", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaGetLastError", ("hipGetLastError", CONV_ERROR, API_RUNTIME)), ("cudaPeekAtLastError", ("hipPeekAtLastError", CONV_ERROR, API_RUNTIME)), ("cudaGetErrorName", ("hipGetErrorName", CONV_ERROR, API_RUNTIME)), ("cudaGetErrorString", ("hipGetErrorString", CONV_ERROR, API_RUNTIME)), ("cudaMemcpy3DParms", ("hipMemcpy3DParms", CONV_MEM, API_RUNTIME)), ("cudaMemcpy3DPeerParms", ("hipMemcpy3DPeerParms", CONV_MEM, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaMemcpy", ("hipMemcpy", CONV_MEM, API_RUNTIME)), ("cudaMemcpyToArray", ("hipMemcpyToArray", CONV_MEM, API_RUNTIME)), ("cudaMemcpyToSymbol", ("hipMemcpyToSymbol", CONV_MEM, API_RUNTIME)), ("cudaMemcpyToSymbolAsync", ("hipMemcpyToSymbolAsync", CONV_MEM, API_RUNTIME)), ("cudaMemcpyAsync", ("hipMemcpyAsync", CONV_MEM, API_RUNTIME)), ("cudaMemcpy2D", ("hipMemcpy2D", CONV_MEM, API_RUNTIME)), ("cudaMemcpy2DAsync", ("hipMemcpy2DAsync", CONV_MEM, API_RUNTIME)), ("cudaMemcpy2DToArray", ("hipMemcpy2DToArray", CONV_MEM, API_RUNTIME)), ("cudaMemcpy2DArrayToArray", ("hipMemcpy2DArrayToArray", CONV_MEM, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaMemcpy2DFromArray", ("hipMemcpy2DFromArray", CONV_MEM, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaMemcpy2DFromArrayAsync", ("hipMemcpy2DFromArrayAsync", CONV_MEM, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaMemcpy2DToArrayAsync", ("hipMemcpy2DToArrayAsync", CONV_MEM, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaMemcpy3D", ("hipMemcpy3D", CONV_MEM, API_RUNTIME)), ("cudaMemcpy3DAsync", ("hipMemcpy3DAsync", CONV_MEM, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaMemcpy3DPeer", ("hipMemcpy3DPeer", CONV_MEM, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaMemcpy3DPeerAsync", ("hipMemcpy3DPeerAsync", CONV_MEM, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaMemcpyArrayToArray", ("hipMemcpyArrayToArray", CONV_MEM, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaMemcpyFromArrayAsync", ("hipMemcpyFromArrayAsync", CONV_MEM, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaMemcpyFromSymbol", ("hipMemcpyFromSymbol", CONV_MEM, API_RUNTIME)), ("cudaMemcpyFromSymbolAsync", ("hipMemcpyFromSymbolAsync", CONV_MEM, API_RUNTIME)), ("cudaMemAdvise", ("hipMemAdvise", CONV_MEM, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaMemRangeGetAttribute", ("hipMemRangeGetAttribute", CONV_MEM, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaMemRangeGetAttributes", ("hipMemRangeGetAttributes", CONV_MEM, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaMemAdviseSetReadMostly", ("hipMemAdviseSetReadMostly", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaMemAdviseUnsetReadMostly", ("hipMemAdviseUnsetReadMostly", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaMemAdviseSetPreferredLocation", ("hipMemAdviseSetPreferredLocation", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaMemAdviseUnsetPreferredLocation", ("hipMemAdviseUnsetPreferredLocation", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaMemAdviseSetAccessedBy", ("hipMemAdviseSetAccessedBy", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaMemAdviseUnsetAccessedBy", ("hipMemAdviseUnsetAccessedBy", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaMemRangeAttributeReadMostly", ("hipMemRangeAttributeReadMostly", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaMemRangeAttributePreferredLocation", ("hipMemRangeAttributePreferredLocation", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaMemRangeAttributeAccessedBy", ("hipMemRangeAttributeAccessedBy", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaMemRangeAttributeLastPrefetchLocation", ("hipMemRangeAttributeLastPrefetchLocation", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaMemcpyHostToHost", ("hipMemcpyHostToHost", CONV_MEM, API_RUNTIME)), ("cudaMemcpyHostToDevice", ("hipMemcpyHostToDevice", CONV_MEM, API_RUNTIME)), ("cudaMemcpyDeviceToHost", ("hipMemcpyDeviceToHost", CONV_MEM, API_RUNTIME)), ("cudaMemcpyDeviceToDevice", ("hipMemcpyDeviceToDevice", CONV_MEM, API_RUNTIME)), ("cudaMemcpyDefault", ("hipMemcpyDefault", CONV_MEM, API_RUNTIME)), ("cudaMemset", ("hipMemset", CONV_MEM, API_RUNTIME)), ("cudaMemsetAsync", ("hipMemsetAsync", CONV_MEM, API_RUNTIME)), ("cudaMemset2D", ("hipMemset2D", CONV_MEM, API_RUNTIME)), ("cudaMemset2DAsync", ("hipMemset2DAsync", CONV_MEM, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaMemset3D", ("hipMemset3D", CONV_MEM, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaMemset3DAsync", ("hipMemset3DAsync", CONV_MEM, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaMemGetInfo", ("hipMemGetInfo", CONV_MEM, API_RUNTIME)), ("cudaArrayGetInfo", ("hipArrayGetInfo", CONV_MEM, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaFreeMipmappedArray", ("hipFreeMipmappedArray", CONV_MEM, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaGetMipmappedArrayLevel", ("hipGetMipmappedArrayLevel", CONV_MEM, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaGetSymbolAddress", ("hipGetSymbolAddress", CONV_MEM, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaGetSymbolSize", ("hipGetSymbolSize", CONV_MEM, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaMemPrefetchAsync", ("hipMemPrefetchAsync", CONV_MEM, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaMallocHost", ("hipHostMalloc", CONV_MEM, API_RUNTIME)), ("cudaMallocArray", ("hipMallocArray", CONV_MEM, API_RUNTIME)), ("cudaMalloc", ("hipMalloc", CONV_MEM, API_RUNTIME)), ("cudaMalloc3D", ("hipMalloc3D", CONV_MEM, API_RUNTIME)), ("cudaMalloc3DArray", ("hipMalloc3DArray", CONV_MEM, API_RUNTIME)), ("cudaMallocManaged", ("hipMallocManaged", CONV_MEM, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaMallocMipmappedArray", ("hipMallocMipmappedArray", CONV_MEM, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaMallocPitch", ("hipMallocPitch", CONV_MEM, API_RUNTIME)), ("cudaFreeHost", ("hipHostFree", CONV_MEM, API_RUNTIME)), ("cudaFreeArray", ("hipFreeArray", CONV_MEM, API_RUNTIME)), ("cudaFree", ("hipFree", CONV_MEM, API_RUNTIME)), ("cudaHostRegister", ("hipHostRegister", CONV_MEM, API_RUNTIME)), ("cudaHostUnregister", ("hipHostUnregister", CONV_MEM, API_RUNTIME)), ("cudaHostAlloc", ("hipHostMalloc", CONV_MEM, API_RUNTIME)), ("cudaMemoryTypeHost", ("hipMemoryTypeHost", CONV_MEM, API_RUNTIME)), ("cudaMemoryTypeDevice", ("hipMemoryTypeDevice", CONV_MEM, API_RUNTIME)), ("make_cudaExtent", ("make_hipExtent", CONV_MEM, API_RUNTIME)), ("make_cudaPitchedPtr", ("make_hipPitchedPtr", CONV_MEM, API_RUNTIME)), ("make_cudaPos", ("make_hipPos", CONV_MEM, API_RUNTIME)), ("cudaHostAllocDefault", ("hipHostMallocDefault", CONV_MEM, API_RUNTIME)), ("cudaHostAllocPortable", ("hipHostMallocPortable", CONV_MEM, API_RUNTIME)), ("cudaHostAllocMapped", ("hipHostMallocMapped", CONV_MEM, API_RUNTIME)), ("cudaHostAllocWriteCombined", ("hipHostMallocWriteCombined", CONV_MEM, API_RUNTIME)), ("cudaHostGetFlags", ("hipHostGetFlags", CONV_MEM, API_RUNTIME)), ("cudaHostRegisterDefault", ("hipHostRegisterDefault", CONV_MEM, API_RUNTIME)), ("cudaHostRegisterPortable", ("hipHostRegisterPortable", CONV_MEM, API_RUNTIME)), ("cudaHostRegisterMapped", ("hipHostRegisterMapped", CONV_MEM, API_RUNTIME)), ("cudaHostRegisterIoMemory", ("hipHostRegisterIoMemory", CONV_MEM, API_RUNTIME)), # ("warpSize", ("hipWarpSize", CONV_SPECIAL_FUNC, API_RUNTIME), (HIP actually uses warpSize...), ("cudaEventCreate", ("hipEventCreate", CONV_EVENT, API_RUNTIME)), ("cudaEventCreateWithFlags", ("hipEventCreateWithFlags", CONV_EVENT, API_RUNTIME)), ("cudaEventDestroy", ("hipEventDestroy", CONV_EVENT, API_RUNTIME)), ("cudaEventRecord", ("hipEventRecord", CONV_EVENT, API_RUNTIME)), ("cudaEventElapsedTime", ("hipEventElapsedTime", CONV_EVENT, API_RUNTIME)), ("cudaEventSynchronize", ("hipEventSynchronize", CONV_EVENT, API_RUNTIME)), ("cudaEventQuery", ("hipEventQuery", CONV_EVENT, API_RUNTIME)), ("cudaEventDefault", ("hipEventDefault", CONV_EVENT, API_RUNTIME)), ("cudaEventBlockingSync", ("hipEventBlockingSync", CONV_EVENT, API_RUNTIME)), ("cudaEventDisableTiming", ("hipEventDisableTiming", CONV_EVENT, API_RUNTIME)), ("cudaEventInterprocess", ("hipEventInterprocess", CONV_EVENT, API_RUNTIME)), ("cudaStreamCreate", ("hipStreamCreate", CONV_STREAM, API_RUNTIME)), ("cudaStreamCreateWithFlags", ("hipStreamCreateWithFlags", CONV_STREAM, API_RUNTIME)), ("cudaStreamCreateWithPriority", ("hipStreamCreateWithPriority", CONV_STREAM, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaStreamDestroy", ("hipStreamDestroy", CONV_STREAM, API_RUNTIME)), ("cudaStreamWaitEvent", ("hipStreamWaitEvent", CONV_STREAM, API_RUNTIME)), ("cudaStreamSynchronize", ("hipStreamSynchronize", CONV_STREAM, API_RUNTIME)), ("cudaStreamGetFlags", ("hipStreamGetFlags", CONV_STREAM, API_RUNTIME)), ("cudaStreamQuery", ("hipStreamQuery", CONV_STREAM, API_RUNTIME)), ("cudaStreamAddCallback", ("hipStreamAddCallback", CONV_STREAM, API_RUNTIME)), ("cudaStreamAttachMemAsync", ("hipStreamAttachMemAsync", CONV_STREAM, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaStreamGetPriority", ("hipStreamGetPriority", CONV_STREAM, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaStreamDefault", ("hipStreamDefault", CONV_TYPE, API_RUNTIME)), ("cudaStreamNonBlocking", ("hipStreamNonBlocking", CONV_TYPE, API_RUNTIME)), ("cudaDeviceSynchronize", ("hipDeviceSynchronize", CONV_DEVICE, API_RUNTIME)), ("cudaDeviceReset", ("hipDeviceReset", CONV_DEVICE, API_RUNTIME)), ("cudaSetDevice", ("hipSetDevice", CONV_DEVICE, API_RUNTIME)), ("cudaGetDevice", ("hipGetDevice", CONV_DEVICE, API_RUNTIME)), ("cudaGetDeviceCount", ("hipGetDeviceCount", CONV_DEVICE, API_RUNTIME)), ("cudaChooseDevice", ("hipChooseDevice", CONV_DEVICE, API_RUNTIME)), ("cudaThreadExit", ("hipDeviceReset", CONV_THREAD, API_RUNTIME)), ("cudaThreadGetCacheConfig", ("hipDeviceGetCacheConfig", CONV_THREAD, API_RUNTIME)), ("cudaThreadGetLimit", ("hipThreadGetLimit", CONV_THREAD, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaThreadSetCacheConfig", ("hipDeviceSetCacheConfig", CONV_THREAD, API_RUNTIME)), ("cudaThreadSetLimit", ("hipThreadSetLimit", CONV_THREAD, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaThreadSynchronize", ("hipDeviceSynchronize", CONV_THREAD, API_RUNTIME)), ("cudaDeviceGetAttribute", ("hipDeviceGetAttribute", CONV_DEVICE, API_RUNTIME)), ("cudaDevAttrMaxThreadsPerBlock", ("hipDeviceAttributeMaxThreadsPerBlock", CONV_TYPE, API_RUNTIME)), ("cudaDevAttrMaxBlockDimX", ("hipDeviceAttributeMaxBlockDimX", CONV_TYPE, API_RUNTIME)), ("cudaDevAttrMaxBlockDimY", ("hipDeviceAttributeMaxBlockDimY", CONV_TYPE, API_RUNTIME)), ("cudaDevAttrMaxBlockDimZ", ("hipDeviceAttributeMaxBlockDimZ", CONV_TYPE, API_RUNTIME)), ("cudaDevAttrMaxGridDimX", ("hipDeviceAttributeMaxGridDimX", CONV_TYPE, API_RUNTIME)), ("cudaDevAttrMaxGridDimY", ("hipDeviceAttributeMaxGridDimY", CONV_TYPE, API_RUNTIME)), ("cudaDevAttrMaxGridDimZ", ("hipDeviceAttributeMaxGridDimZ", CONV_TYPE, API_RUNTIME)), ("cudaDevAttrMaxSharedMemoryPerBlock", ("hipDeviceAttributeMaxSharedMemoryPerBlock", CONV_TYPE, API_RUNTIME)), ("cudaDevAttrTotalConstantMemory", ("hipDeviceAttributeTotalConstantMemory", CONV_TYPE, API_RUNTIME)), ("cudaDevAttrWarpSize", ("hipDeviceAttributeWarpSize", CONV_TYPE, API_RUNTIME)), ("cudaDevAttrMaxPitch", ("hipDeviceAttributeMaxPitch", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaDevAttrMaxRegistersPerBlock", ("hipDeviceAttributeMaxRegistersPerBlock", CONV_TYPE, API_RUNTIME)), ("cudaDevAttrClockRate", ("hipDeviceAttributeClockRate", CONV_TYPE, API_RUNTIME)), ("cudaDevAttrTextureAlignment", ("hipDeviceAttributeTextureAlignment", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaDevAttrGpuOverlap", ("hipDeviceAttributeGpuOverlap", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaDevAttrMultiProcessorCount", ("hipDeviceAttributeMultiprocessorCount", CONV_TYPE, API_RUNTIME)), ("cudaDevAttrKernelExecTimeout", ("hipDeviceAttributeKernelExecTimeout", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaDevAttrIntegrated", ("hipDeviceAttributeIntegrated", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaDevAttrCanMapHostMemory", ("hipDeviceAttributeCanMapHostMemory", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaDevAttrComputeMode", ("hipDeviceAttributeComputeMode", CONV_TYPE, API_RUNTIME)), ("cudaDevAttrMaxTexture1DWidth", ("hipDeviceAttributeMaxTexture1DWidth", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaDevAttrMaxTexture2DWidth", ("hipDeviceAttributeMaxTexture2DWidth", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaDevAttrMaxTexture2DHeight", ("hipDeviceAttributeMaxTexture2DHeight", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaDevAttrMaxTexture3DWidth", ("hipDeviceAttributeMaxTexture3DWidth", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaDevAttrMaxTexture3DHeight", ("hipDeviceAttributeMaxTexture3DHeight", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaDevAttrMaxTexture3DDepth", ("hipDeviceAttributeMaxTexture3DDepth", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaDevAttrMaxTexture2DLayeredWidth", ("hipDeviceAttributeMaxTexture2DLayeredWidth", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaDevAttrMaxTexture2DLayeredHeight", ("hipDeviceAttributeMaxTexture2DLayeredHeight", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaDevAttrMaxTexture2DLayeredLayers", ("hipDeviceAttributeMaxTexture2DLayeredLayers", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaDevAttrSurfaceAlignment", ("hipDeviceAttributeSurfaceAlignment", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaDevAttrConcurrentKernels", ("hipDeviceAttributeConcurrentKernels", CONV_TYPE, API_RUNTIME)), ("cudaDevAttrEccEnabled", ("hipDeviceAttributeEccEnabled", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaDevAttrPciBusId", ("hipDeviceAttributePciBusId", CONV_TYPE, API_RUNTIME)), ("cudaDevAttrPciDeviceId", ("hipDeviceAttributePciDeviceId", CONV_TYPE, API_RUNTIME)), ("cudaDevAttrTccDriver", ("hipDeviceAttributeTccDriver", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaDevAttrMemoryClockRate", ("hipDeviceAttributeMemoryClockRate", CONV_TYPE, API_RUNTIME)), ("cudaDevAttrGlobalMemoryBusWidth", ("hipDeviceAttributeMemoryBusWidth", CONV_TYPE, API_RUNTIME)), ("cudaDevAttrL2CacheSize", ("hipDeviceAttributeL2CacheSize", CONV_TYPE, API_RUNTIME)), ("cudaDevAttrMaxThreadsPerMultiProcessor", ("hipDeviceAttributeMaxThreadsPerMultiProcessor", CONV_TYPE, API_RUNTIME)), ("cudaDevAttrAsyncEngineCount", ("hipDeviceAttributeAsyncEngineCount", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaDevAttrUnifiedAddressing", ("hipDeviceAttributeUnifiedAddressing", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaDevAttrMaxTexture1DLayeredWidth", ("hipDeviceAttributeMaxTexture1DLayeredWidth", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaDevAttrMaxTexture1DLayeredLayers", ("hipDeviceAttributeMaxTexture1DLayeredLayers", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaDevAttrMaxTexture2DGatherWidth", ("hipDeviceAttributeMaxTexture2DGatherWidth", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaDevAttrMaxTexture2DGatherHeight", ("hipDeviceAttributeMaxTexture2DGatherHeight", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaDevAttrMaxTexture3DWidthAlt", ("hipDeviceAttributeMaxTexture3DWidthAlternate", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaDevAttrMaxTexture3DHeightAlt", ("hipDeviceAttributeMaxTexture3DHeightAlternate", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaDevAttrMaxTexture3DDepthAlt", ("hipDeviceAttributeMaxTexture3DDepthAlternate", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaDevAttrPciDomainId", ("hipDeviceAttributePciDomainId", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaDevAttrTexturePitchAlignment", ("hipDeviceAttributeTexturePitchAlignment", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaDevAttrMaxTextureCubemapWidth", ("hipDeviceAttributeMaxTextureCubemapWidth", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaDevAttrMaxTextureCubemapLayeredWidth", ("hipDeviceAttributeMaxTextureCubemapLayeredWidth", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaDevAttrMaxTextureCubemapLayeredLayers", ("hipDeviceAttributeMaxTextureCubemapLayeredLayers", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaDevAttrMaxSurface1DWidth", ("hipDeviceAttributeMaxSurface1DWidth", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaDevAttrMaxSurface2DWidth", ("hipDeviceAttributeMaxSurface2DWidth", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaDevAttrMaxSurface2DHeight", ("hipDeviceAttributeMaxSurface2DHeight", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaDevAttrMaxSurface3DWidth", ("hipDeviceAttributeMaxSurface3DWidth", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaDevAttrMaxSurface3DHeight", ("hipDeviceAttributeMaxSurface3DHeight", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaDevAttrMaxSurface3DDepth", ("hipDeviceAttributeMaxSurface3DDepth", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaDevAttrMaxSurface1DLayeredWidth", ("hipDeviceAttributeMaxSurface1DLayeredWidth", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaDevAttrMaxSurface1DLayeredLayers", ("hipDeviceAttributeMaxSurface1DLayeredLayers", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaDevAttrMaxSurface2DLayeredWidth", ("hipDeviceAttributeMaxSurface2DLayeredWidth", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaDevAttrMaxSurface2DLayeredHeight", ("hipDeviceAttributeMaxSurface2DLayeredHeight", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaDevAttrMaxSurface2DLayeredLayers", ("hipDeviceAttributeMaxSurface2DLayeredLayers", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaDevAttrMaxSurfaceCubemapWidth", ("hipDeviceAttributeMaxSurfaceCubemapWidth", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaDevAttrMaxSurfaceCubemapLayeredWidth", ("hipDeviceAttributeMaxSurfaceCubemapLayeredWidth", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaDevAttrMaxSurfaceCubemapLayeredLayers", ("hipDeviceAttributeMaxSurfaceCubemapLayeredLayers", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaDevAttrMaxTexture1DLinearWidth", ("hipDeviceAttributeMaxTexture1DLinearWidth", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaDevAttrMaxTexture2DLinearWidth", ("hipDeviceAttributeMaxTexture2DLinearWidth", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaDevAttrMaxTexture2DLinearHeight", ("hipDeviceAttributeMaxTexture2DLinearHeight", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaDevAttrMaxTexture2DLinearPitch", ("hipDeviceAttributeMaxTexture2DLinearPitch", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaDevAttrMaxTexture2DMipmappedWidth", ("hipDeviceAttributeMaxTexture2DMipmappedWidth", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaDevAttrMaxTexture2DMipmappedHeight", ("hipDeviceAttributeMaxTexture2DMipmappedHeight", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaDevAttrComputeCapabilityMajor", ("hipDeviceAttributeComputeCapabilityMajor", CONV_TYPE, API_RUNTIME)), ("cudaDevAttrComputeCapabilityMinor", ("hipDeviceAttributeComputeCapabilityMinor", CONV_TYPE, API_RUNTIME)), ("cudaDevAttrMaxTexture1DMipmappedWidth", ("hipDeviceAttributeMaxTexture1DMipmappedWidth", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaDevAttrStreamPrioritiesSupported", ("hipDeviceAttributeStreamPrioritiesSupported", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaDevAttrGlobalL1CacheSupported", ("hipDeviceAttributeGlobalL1CacheSupported", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaDevAttrLocalL1CacheSupported", ("hipDeviceAttributeLocalL1CacheSupported", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaDevAttrMaxSharedMemoryPerMultiprocessor", ("hipDeviceAttributeMaxSharedMemoryPerMultiprocessor", CONV_TYPE, API_RUNTIME)), ("cudaDevAttrMaxRegistersPerMultiprocessor", ("hipDeviceAttributeMaxRegistersPerMultiprocessor", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaDevAttrManagedMemory", ("hipDeviceAttributeManagedMemory", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaDevAttrIsMultiGpuBoard", ("hipDeviceAttributeIsMultiGpuBoard", CONV_TYPE, API_RUNTIME)), ("cudaDevAttrMultiGpuBoardGroupID", ("hipDeviceAttributeMultiGpuBoardGroupID", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaDevAttrHostNativeAtomicSupported", ("hipDeviceAttributeHostNativeAtomicSupported", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaDevAttrSingleToDoublePrecisionPerfRatio", ("hipDeviceAttributeSingleToDoublePrecisionPerfRatio", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaDevAttrPageableMemoryAccess", ("hipDeviceAttributePageableMemoryAccess", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaDevAttrConcurrentManagedAccess", ("hipDeviceAttributeConcurrentManagedAccess", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaDevAttrComputePreemptionSupported", ("hipDeviceAttributeComputePreemptionSupported", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaDevAttrCanUseHostPointerForRegisteredMem", ("hipDeviceAttributeCanUseHostPointerForRegisteredMem", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaPointerGetAttributes", ("hipPointerGetAttributes", CONV_MEM, API_RUNTIME)), ("cudaHostGetDevicePointer", ("hipHostGetDevicePointer", CONV_MEM, API_RUNTIME)), ("cudaGetDeviceProperties", ("hipGetDeviceProperties", CONV_DEVICE, API_RUNTIME)), ("cudaDeviceGetPCIBusId", ("hipDeviceGetPCIBusId", CONV_DEVICE, API_RUNTIME)), ("cudaDeviceGetByPCIBusId", ("hipDeviceGetByPCIBusId", CONV_DEVICE, API_RUNTIME)), ("cudaDeviceGetStreamPriorityRange", ("hipDeviceGetStreamPriorityRange", CONV_DEVICE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaSetValidDevices", ("hipSetValidDevices", CONV_DEVICE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaDevP2PAttrPerformanceRank", ("hipDeviceP2PAttributePerformanceRank", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaDevP2PAttrAccessSupported", ("hipDeviceP2PAttributeAccessSupported", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaDevP2PAttrNativeAtomicSupported", ("hipDeviceP2PAttributeNativeAtomicSupported", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaDeviceGetP2PAttribute", ("hipDeviceGetP2PAttribute", CONV_DEVICE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaComputeModeDefault", ("hipComputeModeDefault", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaComputeModeExclusive", ("hipComputeModeExclusive", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaComputeModeProhibited", ("hipComputeModeProhibited", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaComputeModeExclusiveProcess", ("hipComputeModeExclusiveProcess", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaGetDeviceFlags", ("hipGetDeviceFlags", CONV_DEVICE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaSetDeviceFlags", ("hipSetDeviceFlags", CONV_DEVICE, API_RUNTIME)), ("cudaDeviceScheduleAuto", ("hipDeviceScheduleAuto", CONV_TYPE, API_RUNTIME)), ("cudaDeviceScheduleSpin", ("hipDeviceScheduleSpin", CONV_TYPE, API_RUNTIME)), ("cudaDeviceScheduleYield", ("hipDeviceScheduleYield", CONV_TYPE, API_RUNTIME)), ("cudaDeviceBlockingSync", ("hipDeviceScheduleBlockingSync", CONV_TYPE, API_RUNTIME)), ("cudaDeviceScheduleBlockingSync", ("hipDeviceScheduleBlockingSync", CONV_TYPE, API_RUNTIME)), ("cudaDeviceScheduleMask", ("hipDeviceScheduleMask", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaDeviceMapHost", ("hipDeviceMapHost", CONV_TYPE, API_RUNTIME)), ("cudaDeviceLmemResizeToMax", ("hipDeviceLmemResizeToMax", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaDeviceMask", ("hipDeviceMask", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaDeviceSetCacheConfig", ("hipDeviceSetCacheConfig", CONV_CACHE, API_RUNTIME)), ("cudaDeviceGetCacheConfig", ("hipDeviceGetCacheConfig", CONV_CACHE, API_RUNTIME)), ("cudaFuncSetCacheConfig", ("hipFuncSetCacheConfig", CONV_CACHE, API_RUNTIME)), ("cudaFuncCachePreferNone", ("hipFuncCachePreferNone", CONV_CACHE, API_RUNTIME)), ("cudaFuncCachePreferShared", ("hipFuncCachePreferShared", CONV_CACHE, API_RUNTIME)), ("cudaFuncCachePreferL1", ("hipFuncCachePreferL1", CONV_CACHE, API_RUNTIME)), ("cudaFuncCachePreferEqual", ("hipFuncCachePreferEqual", CONV_CACHE, API_RUNTIME)), ("cudaFuncGetAttributes", ("hipFuncGetAttributes", CONV_EXEC, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaFuncSetSharedMemConfig", ("hipFuncSetSharedMemConfig", CONV_EXEC, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaGetParameterBuffer", ("hipGetParameterBuffer", CONV_EXEC, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaSetDoubleForDevice", ("hipSetDoubleForDevice", CONV_EXEC, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaSetDoubleForHost", ("hipSetDoubleForHost", CONV_EXEC, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaConfigureCall", ("hipConfigureCall", CONV_EXEC, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaLaunch", ("hipLaunch", CONV_EXEC, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaSetupArgument", ("hipSetupArgument", CONV_EXEC, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaDriverGetVersion", ("hipDriverGetVersion", CONV_VERSION, API_RUNTIME)), ("cudaRuntimeGetVersion", ("hipRuntimeGetVersion", CONV_VERSION, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaOccupancyMaxPotentialBlockSize", ("hipOccupancyMaxPotentialBlockSize", CONV_OCCUPANCY, API_RUNTIME)), ("cudaOccupancyMaxPotentialBlockSizeWithFlags", ("hipOccupancyMaxPotentialBlockSizeWithFlags", CONV_OCCUPANCY, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaOccupancyMaxActiveBlocksPerMultiprocessor", ("hipOccupancyMaxActiveBlocksPerMultiprocessor", CONV_OCCUPANCY, API_RUNTIME)), ("cudaOccupancyMaxActiveBlocksPerMultiprocessorWithFlags", ("hipOccupancyMaxActiveBlocksPerMultiprocessorWithFlags", CONV_OCCUPANCY, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaOccupancyMaxPotentialBlockSizeVariableSMem", ("hipOccupancyMaxPotentialBlockSizeVariableSMem", CONV_OCCUPANCY, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaOccupancyMaxPotentialBlockSizeVariableSMemWithFlags", ("hipOccupancyMaxPotentialBlockSizeVariableSMemWithFlags", CONV_OCCUPANCY, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaDeviceCanAccessPeer", ("hipDeviceCanAccessPeer", CONV_PEER, API_RUNTIME)), ("cudaDeviceDisablePeerAccess", ("hipDeviceDisablePeerAccess", CONV_PEER, API_RUNTIME)), ("cudaDeviceEnablePeerAccess", ("hipDeviceEnablePeerAccess", CONV_PEER, API_RUNTIME)), ("cudaMemcpyPeerAsync", ("hipMemcpyPeerAsync", CONV_MEM, API_RUNTIME)), ("cudaMemcpyPeer", ("hipMemcpyPeer", CONV_MEM, API_RUNTIME)), ("cudaIpcMemLazyEnablePeerAccess", ("hipIpcMemLazyEnablePeerAccess", CONV_TYPE, API_RUNTIME)), ("cudaDeviceSetSharedMemConfig", ("hipDeviceSetSharedMemConfig", CONV_DEVICE, API_RUNTIME)), ("cudaDeviceGetSharedMemConfig", ("hipDeviceGetSharedMemConfig", CONV_DEVICE, API_RUNTIME)), ("cudaSharedMemBankSizeDefault", ("hipSharedMemBankSizeDefault", CONV_TYPE, API_RUNTIME)), ("cudaSharedMemBankSizeFourByte", ("hipSharedMemBankSizeFourByte", CONV_TYPE, API_RUNTIME)), ("cudaSharedMemBankSizeEightByte", ("hipSharedMemBankSizeEightByte", CONV_TYPE, API_RUNTIME)), ("cudaLimitStackSize", ("hipLimitStackSize", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaLimitPrintfFifoSize", ("hipLimitPrintfFifoSize", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaLimitMallocHeapSize", ("hipLimitMallocHeapSize", CONV_TYPE, API_RUNTIME)), ("cudaLimitDevRuntimeSyncDepth", ("hipLimitDevRuntimeSyncDepth", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaLimitDevRuntimePendingLaunchCount", ("hipLimitDevRuntimePendingLaunchCount", CONV_TYPE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaDeviceGetLimit", ("hipDeviceGetLimit", CONV_DEVICE, API_RUNTIME)), ("cudaProfilerInitialize", ("hipProfilerInitialize", CONV_OTHER, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaProfilerStart", ("hipProfilerStart", CONV_OTHER, API_RUNTIME)), ("cudaProfilerStop", ("hipProfilerStop", CONV_OTHER, API_RUNTIME)), ("cudaKeyValuePair", ("hipKeyValuePair", CONV_OTHER, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaCSV", ("hipCSV", CONV_OTHER, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaReadModeElementType", ("hipReadModeElementType", CONV_TEX, API_RUNTIME)), ("cudaReadModeNormalizedFloat", ("hipReadModeNormalizedFloat", CONV_TEX, API_RUNTIME)), ("cudaFilterModePoint", ("hipFilterModePoint", CONV_TEX, API_RUNTIME)), ("cudaFilterModeLinear", ("hipFilterModeLinear", CONV_TEX, API_RUNTIME)), ("cudaBindTexture", ("hipBindTexture", CONV_TEX, API_RUNTIME)), ("cudaUnbindTexture", ("hipUnbindTexture", CONV_TEX, API_RUNTIME)), ("cudaBindTexture2D", ("hipBindTexture2D", CONV_TEX, API_RUNTIME)), ("cudaBindTextureToArray", ("hipBindTextureToArray", CONV_TEX, API_RUNTIME)), ("cudaBindTextureToMipmappedArray", ("hipBindTextureToMipmappedArray", CONV_TEX, API_RUNTIME)), ("cudaGetTextureAlignmentOffset", ("hipGetTextureAlignmentOffset", CONV_TEX, API_RUNTIME)), ("cudaGetTextureReference", ("hipGetTextureReference", CONV_TEX, API_RUNTIME)), ("cudaChannelFormatKindSigned", ("hipChannelFormatKindSigned", CONV_TEX, API_RUNTIME)), ("cudaChannelFormatKindUnsigned", ("hipChannelFormatKindUnsigned", CONV_TEX, API_RUNTIME)), ("cudaChannelFormatKindFloat", ("hipChannelFormatKindFloat", CONV_TEX, API_RUNTIME)), ("cudaChannelFormatKindNone", ("hipChannelFormatKindNone", CONV_TEX, API_RUNTIME)), ("cudaCreateChannelDesc", ("hipCreateChannelDesc", CONV_TEX, API_RUNTIME)), ("cudaGetChannelDesc", ("hipGetChannelDesc", CONV_TEX, API_RUNTIME)), ("cudaResourceTypeArray", ("hipResourceTypeArray", CONV_TEX, API_RUNTIME)), ("cudaResourceTypeMipmappedArray", ("hipResourceTypeMipmappedArray", CONV_TEX, API_RUNTIME)), ("cudaResourceTypeLinear", ("hipResourceTypeLinear", CONV_TEX, API_RUNTIME)), ("cudaResourceTypePitch2D", ("hipResourceTypePitch2D", CONV_TEX, API_RUNTIME)), ("cudaResViewFormatNone", ("hipResViewFormatNone", CONV_TEX, API_RUNTIME)), ("cudaResViewFormatUnsignedChar1", ("hipResViewFormatUnsignedChar1", CONV_TEX, API_RUNTIME)), ("cudaResViewFormatUnsignedChar2", ("hipResViewFormatUnsignedChar2", CONV_TEX, API_RUNTIME)), ("cudaResViewFormatUnsignedChar4", ("hipResViewFormatUnsignedChar4", CONV_TEX, API_RUNTIME)), ("cudaResViewFormatSignedChar1", ("hipResViewFormatSignedChar1", CONV_TEX, API_RUNTIME)), ("cudaResViewFormatSignedChar2", ("hipResViewFormatSignedChar2", CONV_TEX, API_RUNTIME)), ("cudaResViewFormatSignedChar4", ("hipResViewFormatSignedChar4", CONV_TEX, API_RUNTIME)), ("cudaResViewFormatUnsignedShort1", ("hipResViewFormatUnsignedShort1", CONV_TEX, API_RUNTIME)), ("cudaResViewFormatUnsignedShort2", ("hipResViewFormatUnsignedShort2", CONV_TEX, API_RUNTIME)), ("cudaResViewFormatUnsignedShort4", ("hipResViewFormatUnsignedShort4", CONV_TEX, API_RUNTIME)), ("cudaResViewFormatSignedShort1", ("hipResViewFormatSignedShort1", CONV_TEX, API_RUNTIME)), ("cudaResViewFormatSignedShort2", ("hipResViewFormatSignedShort2", CONV_TEX, API_RUNTIME)), ("cudaResViewFormatSignedShort4", ("hipResViewFormatSignedShort4", CONV_TEX, API_RUNTIME)), ("cudaResViewFormatUnsignedInt1", ("hipResViewFormatUnsignedInt1", CONV_TEX, API_RUNTIME)), ("cudaResViewFormatUnsignedInt2", ("hipResViewFormatUnsignedInt2", CONV_TEX, API_RUNTIME)), ("cudaResViewFormatUnsignedInt4", ("hipResViewFormatUnsignedInt4", CONV_TEX, API_RUNTIME)), ("cudaResViewFormatSignedInt1", ("hipResViewFormatSignedInt1", CONV_TEX, API_RUNTIME)), ("cudaResViewFormatSignedInt2", ("hipResViewFormatSignedInt2", CONV_TEX, API_RUNTIME)), ("cudaResViewFormatSignedInt4", ("hipResViewFormatSignedInt4", CONV_TEX, API_RUNTIME)), ("cudaResViewFormatHalf1", ("hipResViewFormatHalf1", CONV_TEX, API_RUNTIME)), ("cudaResViewFormatHalf2", ("hipResViewFormatHalf2", CONV_TEX, API_RUNTIME)), ("cudaResViewFormatHalf4", ("hipResViewFormatHalf4", CONV_TEX, API_RUNTIME)), ("cudaResViewFormatFloat1", ("hipResViewFormatFloat1", CONV_TEX, API_RUNTIME)), ("cudaResViewFormatFloat2", ("hipResViewFormatFloat2", CONV_TEX, API_RUNTIME)), ("cudaResViewFormatFloat4", ("hipResViewFormatFloat4", CONV_TEX, API_RUNTIME)), ("cudaResViewFormatUnsignedBlockCompressed1", ("hipResViewFormatUnsignedBlockCompressed1", CONV_TEX, API_RUNTIME)), ("cudaResViewFormatUnsignedBlockCompressed2", ("hipResViewFormatUnsignedBlockCompressed2", CONV_TEX, API_RUNTIME)), ("cudaResViewFormatUnsignedBlockCompressed3", ("hipResViewFormatUnsignedBlockCompressed3", CONV_TEX, API_RUNTIME)), ("cudaResViewFormatUnsignedBlockCompressed4", ("hipResViewFormatUnsignedBlockCompressed4", CONV_TEX, API_RUNTIME)), ("cudaResViewFormatSignedBlockCompressed4", ("hipResViewFormatSignedBlockCompressed4", CONV_TEX, API_RUNTIME)), ("cudaResViewFormatUnsignedBlockCompressed5", ("hipResViewFormatUnsignedBlockCompressed5", CONV_TEX, API_RUNTIME)), ("cudaResViewFormatSignedBlockCompressed5", ("hipResViewFormatSignedBlockCompressed5", CONV_TEX, API_RUNTIME)), ("cudaResViewFormatUnsignedBlockCompressed6H", ("hipResViewFormatUnsignedBlockCompressed6H", CONV_TEX, API_RUNTIME)), ("cudaResViewFormatSignedBlockCompressed6H", ("hipResViewFormatSignedBlockCompressed6H", CONV_TEX, API_RUNTIME)), ("cudaResViewFormatUnsignedBlockCompressed7", ("hipResViewFormatUnsignedBlockCompressed7", CONV_TEX, API_RUNTIME)), ("cudaAddressModeWrap", ("hipAddressModeWrap", CONV_TEX, API_RUNTIME)), ("cudaAddressModeClamp", ("hipAddressModeClamp", CONV_TEX, API_RUNTIME)), ("cudaAddressModeMirror", ("hipAddressModeMirror", CONV_TEX, API_RUNTIME)), ("cudaAddressModeBorder", ("hipAddressModeBorder", CONV_TEX, API_RUNTIME)), ("cudaCreateTextureObject", ("hipCreateTextureObject", CONV_TEX, API_RUNTIME)), ("cudaDestroyTextureObject", ("hipDestroyTextureObject", CONV_TEX, API_RUNTIME)), ("cudaGetTextureObjectResourceDesc", ("hipGetTextureObjectResourceDesc", CONV_TEX, API_RUNTIME)), ("cudaGetTextureObjectResourceViewDesc", ("hipGetTextureObjectResourceViewDesc", CONV_TEX, API_RUNTIME)), ("cudaGetTextureObjectTextureDesc", ("hipGetTextureObjectTextureDesc", CONV_TEX, API_RUNTIME)), ("cudaBindSurfaceToArray", ("hipBindSurfaceToArray", CONV_SURFACE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaGetSurfaceReference", ("hipGetSurfaceReference", CONV_SURFACE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaBoundaryModeZero", ("hipBoundaryModeZero", CONV_SURFACE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaBoundaryModeClamp", ("hipBoundaryModeClamp", CONV_SURFACE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaBoundaryModeTrap", ("hipBoundaryModeTrap", CONV_SURFACE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaFormatModeForced", ("hipFormatModeForced", CONV_SURFACE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaFormatModeAuto", ("hipFormatModeAuto", CONV_SURFACE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaCreateSurfaceObject", ("hipCreateSurfaceObject", CONV_SURFACE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaDestroySurfaceObject", ("hipDestroySurfaceObject", CONV_SURFACE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaGetSurfaceObjectResourceDesc", ("hipGetSurfaceObjectResourceDesc", CONV_SURFACE, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaIpcCloseMemHandle", ("hipIpcCloseMemHandle", CONV_DEVICE, API_RUNTIME)), ("cudaIpcGetEventHandle", ("hipIpcGetEventHandle", CONV_DEVICE, API_RUNTIME)), ("cudaIpcGetMemHandle", ("hipIpcGetMemHandle", CONV_DEVICE, API_RUNTIME)), ("cudaIpcOpenEventHandle", ("hipIpcOpenEventHandle", CONV_DEVICE, API_RUNTIME)), ("cudaIpcOpenMemHandle", ("hipIpcOpenMemHandle", CONV_DEVICE, API_RUNTIME)), ("cudaGLGetDevices", ("hipGLGetDevices", CONV_GL, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaGraphicsGLRegisterBuffer", ("hipGraphicsGLRegisterBuffer", CONV_GL, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaGraphicsGLRegisterImage", ("hipGraphicsGLRegisterImage", CONV_GL, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaWGLGetDevice", ("hipWGLGetDevice", CONV_GL, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaGraphicsMapResources", ("hipGraphicsMapResources", CONV_GRAPHICS, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaGraphicsResourceGetMappedMipmappedArray", ("hipGraphicsResourceGetMappedMipmappedArray", CONV_GRAPHICS, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaGraphicsResourceGetMappedPointer", ("hipGraphicsResourceGetMappedPointer", CONV_GRAPHICS, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaGraphicsResourceSetMapFlags", ("hipGraphicsResourceSetMapFlags", CONV_GRAPHICS, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaGraphicsSubResourceGetMappedArray", ("hipGraphicsSubResourceGetMappedArray", CONV_GRAPHICS, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaGraphicsUnmapResources", ("hipGraphicsUnmapResources", CONV_GRAPHICS, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaGraphicsUnregisterResource", ("hipGraphicsUnregisterResource", CONV_GRAPHICS, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaGraphicsCubeFacePositiveX", ("hipGraphicsCubeFacePositiveX", CONV_GRAPHICS, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaGraphicsCubeFaceNegativeX", ("hipGraphicsCubeFaceNegativeX", CONV_GRAPHICS, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaGraphicsCubeFacePositiveY", ("hipGraphicsCubeFacePositiveY", CONV_GRAPHICS, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaGraphicsCubeFaceNegativeY", ("hipGraphicsCubeFaceNegativeY", CONV_GRAPHICS, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaGraphicsCubeFacePositiveZ", ("hipGraphicsCubeFacePositiveZ", CONV_GRAPHICS, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaGraphicsCubeFaceNegativeZ", ("hipGraphicsCubeFaceNegativeZ", CONV_GRAPHICS, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaGraphicsMapFlagsNone", ("hipGraphicsMapFlagsNone", CONV_GRAPHICS, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaGraphicsMapFlagsReadOnly", ("hipGraphicsMapFlagsReadOnly", CONV_GRAPHICS, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaGraphicsMapFlagsWriteDiscard", ("hipGraphicsMapFlagsWriteDiscard", CONV_GRAPHICS, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaGraphicsRegisterFlagsNone", ("hipGraphicsRegisterFlagsNone", CONV_GRAPHICS, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaGraphicsRegisterFlagsReadOnly", ("hipGraphicsRegisterFlagsReadOnly", CONV_GRAPHICS, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaGraphicsRegisterFlagsWriteDiscard", ("hipGraphicsRegisterFlagsWriteDiscard", CONV_GRAPHICS, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaGraphicsRegisterFlagsSurfaceLoadStore", ("hipGraphicsRegisterFlagsSurfaceLoadStore", CONV_GRAPHICS, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaGraphicsRegisterFlagsTextureGather", ("hipGraphicsRegisterFlagsTextureGather", CONV_GRAPHICS, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaGLDeviceListAll", ("HIP_GL_DEVICE_LIST_ALL", CONV_GL, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaGLDeviceListCurrentFrame", ("HIP_GL_DEVICE_LIST_CURRENT_FRAME", CONV_GL, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaGLDeviceListNextFrame", ("HIP_GL_DEVICE_LIST_NEXT_FRAME", CONV_GL, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaGLGetDevices", ("hipGLGetDevices", CONV_GL, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaGraphicsGLRegisterBuffer", ("hipGraphicsGLRegisterBuffer", CONV_GL, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaGraphicsGLRegisterImage", ("hipGraphicsGLRegisterImage", CONV_GL, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaWGLGetDevice", ("hipWGLGetDevice", CONV_GL, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaGLMapFlagsNone", ("HIP_GL_MAP_RESOURCE_FLAGS_NONE", CONV_GL, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaGLMapFlagsReadOnly", ("HIP_GL_MAP_RESOURCE_FLAGS_READ_ONLY", CONV_GL, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaGLMapFlagsWriteDiscard", ("HIP_GL_MAP_RESOURCE_FLAGS_WRITE_DISCARD", CONV_GL, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaGLMapBufferObject", ("hipGLMapBufferObject__", CONV_GL, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaGLMapBufferObjectAsync", ("hipGLMapBufferObjectAsync__", CONV_GL, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaGLRegisterBufferObject", ("hipGLRegisterBufferObject", CONV_GL, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaGLSetBufferObjectMapFlags", ("hipGLSetBufferObjectMapFlags", CONV_GL, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaGLSetGLDevice", ("hipGLSetGLDevice", CONV_GL, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaGLUnmapBufferObject", ("hipGLUnmapBufferObject", CONV_GL, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaGLUnmapBufferObjectAsync", ("hipGLUnmapBufferObjectAsync", CONV_GL, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaGLUnregisterBufferObject", ("hipGLUnregisterBufferObject", CONV_GL, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaD3D9DeviceListAll", ("HIP_D3D9_DEVICE_LIST_ALL", CONV_D3D9, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaD3D9DeviceListCurrentFrame", ("HIP_D3D9_DEVICE_LIST_CURRENT_FRAME", CONV_D3D9, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaD3D9DeviceListNextFrame", ("HIP_D3D9_DEVICE_LIST_NEXT_FRAME", CONV_D3D9, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaD3D9GetDevice", ("hipD3D9GetDevice", CONV_D3D9, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaD3D9GetDevices", ("hipD3D9GetDevices", CONV_D3D9, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaD3D9GetDirect3DDevice", ("hipD3D9GetDirect3DDevice", CONV_D3D9, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaD3D9SetDirect3DDevice", ("hipD3D9SetDirect3DDevice", CONV_D3D9, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaGraphicsD3D9RegisterResource", ("hipGraphicsD3D9RegisterResource", CONV_D3D9, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaD3D9MapFlags", ("hipD3D9MapFlags", CONV_D3D9, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaD3D9MapFlagsNone", ("HIP_D3D9_MAPRESOURCE_FLAGS_NONE", CONV_D3D9, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaD3D9MapFlagsReadOnly", ("HIP_D3D9_MAPRESOURCE_FLAGS_READONLY", CONV_D3D9, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaD3D9MapFlagsWriteDiscard", ("HIP_D3D9_MAPRESOURCE_FLAGS_WRITEDISCARD", CONV_D3D9, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaD3D9RegisterFlagsNone", ("HIP_D3D9_REGISTER_FLAGS_NONE", CONV_D3D9, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaD3D9RegisterFlagsArray", ("HIP_D3D9_REGISTER_FLAGS_ARRAY", CONV_D3D9, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaD3D9MapResources", ("hipD3D9MapResources", CONV_D3D9, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaD3D9RegisterResource", ("hipD3D9RegisterResource", CONV_D3D9, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaD3D9ResourceGetMappedArray", ("hipD3D9ResourceGetMappedArray", CONV_D3D9, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaD3D9ResourceGetMappedPitch", ("hipD3D9ResourceGetMappedPitch", CONV_D3D9, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaD3D9ResourceGetMappedPointer", ("hipD3D9ResourceGetMappedPointer", CONV_D3D9, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaD3D9ResourceGetMappedSize", ("hipD3D9ResourceGetMappedSize", CONV_D3D9, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaD3D9ResourceGetSurfaceDimensions", ("hipD3D9ResourceGetSurfaceDimensions", CONV_D3D9, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaD3D9ResourceSetMapFlags", ("hipD3D9ResourceSetMapFlags", CONV_D3D9, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaD3D9UnmapResources", ("hipD3D9UnmapResources", CONV_D3D9, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaD3D9UnregisterResource", ("hipD3D9UnregisterResource", CONV_D3D9, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaD3D10DeviceListAll", ("HIP_D3D10_DEVICE_LIST_ALL", CONV_D3D10, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaD3D10DeviceListCurrentFrame", ("HIP_D3D10_DEVICE_LIST_CURRENT_FRAME", CONV_D3D10, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaD3D10DeviceListNextFrame", ("HIP_D3D10_DEVICE_LIST_NEXT_FRAME", CONV_D3D10, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaD3D10GetDevice", ("hipD3D10GetDevice", CONV_D3D10, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaD3D10GetDevices", ("hipD3D10GetDevices", CONV_D3D10, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaGraphicsD3D10RegisterResource", ("hipGraphicsD3D10RegisterResource", CONV_D3D10, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaD3D10MapFlagsNone", ("HIP_D3D10_MAPRESOURCE_FLAGS_NONE", CONV_D3D10, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaD3D10MapFlagsReadOnly", ("HIP_D3D10_MAPRESOURCE_FLAGS_READONLY", CONV_D3D10, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaD3D10MapFlagsWriteDiscard", ("HIP_D3D10_MAPRESOURCE_FLAGS_WRITEDISCARD", CONV_D3D10, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaD3D10RegisterFlagsNone", ("HIP_D3D10_REGISTER_FLAGS_NONE", CONV_D3D10, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaD3D10RegisterFlagsArray", ("HIP_D3D10_REGISTER_FLAGS_ARRAY", CONV_D3D10, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaD3D10GetDirect3DDevice", ("hipD3D10GetDirect3DDevice", CONV_D3D10, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaD3D10MapResources", ("hipD3D10MapResources", CONV_D3D10, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaD3D10RegisterResource", ("hipD3D10RegisterResource", CONV_D3D10, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaD3D10ResourceGetMappedArray", ("hipD3D10ResourceGetMappedArray", CONV_D3D10, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaD3D10ResourceGetMappedPitch", ("hipD3D10ResourceGetMappedPitch", CONV_D3D10, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaD3D10ResourceGetMappedPointer", ("hipD3D10ResourceGetMappedPointer", CONV_D3D10, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaD3D10ResourceGetMappedSize", ("hipD3D10ResourceGetMappedSize", CONV_D3D10, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaD3D10ResourceGetSurfaceDimensions", ("hipD3D10ResourceGetSurfaceDimensions", CONV_D3D10, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaD3D10ResourceSetMapFlags", ("hipD3D10ResourceSetMapFlags", CONV_D3D10, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaD3D10SetDirect3DDevice", ("hipD3D10SetDirect3DDevice", CONV_D3D10, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaD3D10UnmapResources", ("hipD3D10UnmapResources", CONV_D3D10, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaD3D10UnregisterResource", ("hipD3D10UnregisterResource", CONV_D3D10, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaD3D11DeviceListAll", ("HIP_D3D11_DEVICE_LIST_ALL", CONV_D3D11, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaD3D11DeviceListCurrentFrame", ("HIP_D3D11_DEVICE_LIST_CURRENT_FRAME", CONV_D3D11, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaD3D11DeviceListNextFrame", ("HIP_D3D11_DEVICE_LIST_NEXT_FRAME", CONV_D3D11, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaD3D11GetDevice", ("hipD3D11GetDevice", CONV_D3D11, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaD3D11GetDevices", ("hipD3D11GetDevices", CONV_D3D11, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaGraphicsD3D11RegisterResource", ("hipGraphicsD3D11RegisterResource", CONV_D3D11, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaD3D11GetDevice", ("hipD3D11GetDevice", CONV_D3D11, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaD3D11GetDevices", ("hipD3D11GetDevices", CONV_D3D11, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaGraphicsD3D11RegisterResource", ("hipGraphicsD3D11RegisterResource", CONV_D3D11, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaGraphicsVDPAURegisterOutputSurface", ("hipGraphicsVDPAURegisterOutputSurface", CONV_VDPAU, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaGraphicsVDPAURegisterVideoSurface", ("hipGraphicsVDPAURegisterVideoSurface", CONV_VDPAU, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaVDPAUGetDevice", ("hipVDPAUGetDevice", CONV_VDPAU, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaVDPAUSetVDPAUDevice", ("hipVDPAUSetDevice", CONV_VDPAU, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaEGLStreamConsumerAcquireFrame", ("hipEGLStreamConsumerAcquireFrame", CONV_EGL, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaEGLStreamConsumerConnect", ("hipEGLStreamConsumerConnect", CONV_EGL, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaEGLStreamConsumerConnectWithFlags", ("hipEGLStreamConsumerConnectWithFlags", CONV_EGL, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaEGLStreamConsumerReleaseFrame", ("hipEGLStreamConsumerReleaseFrame", CONV_EGL, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaEGLStreamProducerConnect", ("hipEGLStreamProducerConnect", CONV_EGL, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaEGLStreamProducerDisconnect", ("hipEGLStreamProducerDisconnect", CONV_EGL, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaEGLStreamProducerPresentFrame", ("hipEGLStreamProducerPresentFrame", CONV_EGL, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaEGLStreamProducerReturnFrame", ("hipEGLStreamProducerReturnFrame", CONV_EGL, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaGraphicsEGLRegisterImage", ("hipGraphicsEGLRegisterImage", CONV_EGL, API_RUNTIME, HIP_UNSUPPORTED)), ("cudaGraphicsResourceGetMappedEglFrame", ("hipGraphicsResourceGetMappedEglFrame", CONV_EGL, API_RUNTIME, HIP_UNSUPPORTED)), ("cublasInit", ("rocblas_init", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasShutdown", ("rocblas_shutdown", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasGetVersion", ("rocblas_get_version", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasGetError", ("rocblas_get_error", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasAlloc", ("rocblas_alloc", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasFree", ("rocblas_free", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasSetKernelStream", ("rocblas_set_kernel_stream", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasGetAtomicsMode", ("rocblas_get_atomics_mode", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasSetAtomicsMode", ("rocblas_set_atomics_mode", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasGetMathMode", ("rocblas_get_math_mode", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasSetMathMode", ("rocblas_set_math_mode", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("CUBLAS_OP_N", ("rocblas_operation_none", CONV_NUMERIC_LITERAL, API_BLAS)), ("CUBLAS_OP_T", ("rocblas_operation_transpose", CONV_NUMERIC_LITERAL, API_BLAS)), ("CUBLAS_OP_C", ("rocblas_operation_conjugate_transpose", CONV_NUMERIC_LITERAL, API_BLAS)), ("CUBLAS_STATUS_SUCCESS", ("rocblas_status_success", CONV_NUMERIC_LITERAL, API_BLAS)), ("CUBLAS_STATUS_NOT_INITIALIZED", ("rocblas_status_invalid_handle", CONV_NUMERIC_LITERAL, API_BLAS)), ("CUBLAS_STATUS_ALLOC_FAILED", ("rocblas_status_memory_error", CONV_NUMERIC_LITERAL, API_BLAS)), ("CUBLAS_STATUS_INVALID_VALUE", ("rocblas_status_invalid_pointer", CONV_NUMERIC_LITERAL, API_BLAS)), ("CUBLAS_STATUS_MAPPING_ERROR", ("rocblas_status_internal_error", CONV_NUMERIC_LITERAL, API_BLAS)), ("CUBLAS_STATUS_EXECUTION_FAILED", ("rocblas_status_internal_error", CONV_NUMERIC_LITERAL, API_BLAS)), ("CUBLAS_STATUS_INTERNAL_ERROR", ("rocblas_status_internal_error", CONV_NUMERIC_LITERAL, API_BLAS)), ("CUBLAS_STATUS_NOT_SUPPORTED", ("rocblas_status_not_implemented", CONV_NUMERIC_LITERAL, API_BLAS)), ("CUBLAS_STATUS_ARCH_MISMATCH", ("rocblas_status_not_implemented", CONV_NUMERIC_LITERAL, API_BLAS)), ("CUBLAS_FILL_MODE_LOWER", ("rocblas_fill_lower", CONV_NUMERIC_LITERAL, API_BLAS)), ("CUBLAS_FILL_MODE_UPPER", ("rocblas_fill_upper", CONV_NUMERIC_LITERAL, API_BLAS)), ("CUBLAS_DIAG_NON_UNIT", ("rocblas_diagonal_non_unit", CONV_NUMERIC_LITERAL, API_BLAS)), ("CUBLAS_DIAG_UNIT", ("rocblas_diagonal_unit", CONV_NUMERIC_LITERAL, API_BLAS)), ("CUBLAS_SIDE_LEFT", ("rocblas_side_left", CONV_NUMERIC_LITERAL, API_BLAS)), ("CUBLAS_SIDE_RIGHT", ("rocblas_side_right", CONV_NUMERIC_LITERAL, API_BLAS)), ("CUBLAS_POINTER_MODE_HOST", ("rocblas_pointer_mode_host", CONV_NUMERIC_LITERAL, API_BLAS)), ("CUBLAS_POINTER_MODE_DEVICE", ("rocblas_pointer_mode_device", CONV_NUMERIC_LITERAL, API_BLAS)), ("CUBLAS_ATOMICS_NOT_ALLOWED", ("rocblas_atomics_not_allowed", CONV_NUMERIC_LITERAL, API_BLAS, HIP_UNSUPPORTED)), ("CUBLAS_ATOMICS_ALLOWED", ("rocblas_atomics_allowed", CONV_NUMERIC_LITERAL, API_BLAS, HIP_UNSUPPORTED)), ("CUBLAS_DATA_FLOAT", ("rocblas_precision_float", CONV_NUMERIC_LITERAL, API_BLAS, HIP_UNSUPPORTED)), ("CUBLAS_DATA_DOUBLE", ("rocblas_precision_double", CONV_NUMERIC_LITERAL, API_BLAS, HIP_UNSUPPORTED)), ("CUBLAS_DATA_HALF", ("rocblas_precision_half", CONV_NUMERIC_LITERAL, API_BLAS, HIP_UNSUPPORTED)), ("CUBLAS_DATA_INT8", ("rocblas_precision_int8", CONV_NUMERIC_LITERAL, API_BLAS, HIP_UNSUPPORTED)), ("cublasCreate", ("rocblas_create_handle", CONV_MATH_FUNC, API_BLAS)), ("cublasDestroy", ("rocblas_destroy_handle", CONV_MATH_FUNC, API_BLAS)), ("cublasSetVector", ("rocblas_set_vector", CONV_MATH_FUNC, API_BLAS)), ("cublasGetVector", ("rocblas_get_vector", CONV_MATH_FUNC, API_BLAS)), ("cublasSetVectorAsync", ("rocblas_set_vector_async", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasGetVectorAsync", ("rocblas_get_vector_async", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasSetMatrix", ("rocblas_set_matrix", CONV_MATH_FUNC, API_BLAS)), ("cublasGetMatrix", ("rocblas_get_matrix", CONV_MATH_FUNC, API_BLAS)), ("cublasGetMatrixAsync", ("rocblas_get_matrix_async", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasSetMatrixAsync", ("rocblas_set_matrix_async", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasXerbla", ("rocblas_xerbla", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasSnrm2", ("rocblas_snrm2", CONV_MATH_FUNC, API_BLAS)), ("cublasDnrm2", ("rocblas_dnrm2", CONV_MATH_FUNC, API_BLAS)), ("cublasScnrm2", ("rocblas_scnrm2", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasDznrm2", ("rocblas_dznrm2", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasNrm2Ex", ("rocblas_nrm2_ex", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasSdot", ("rocblas_sdot", CONV_MATH_FUNC, API_BLAS)), ("cublasSdotBatched", ("rocblas_sdot_batched", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasDdot", ("rocblas_ddot", CONV_MATH_FUNC, API_BLAS)), ("cublasDdotBatched", ("rocblas_ddot_batched", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasCdotu", ("rocblas_cdotu", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasCdotc", ("rocblas_cdotc", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasZdotu", ("rocblas_zdotu", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasZdotc", ("rocblas_zdotc", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasSscal", ("rocblas_sscal", CONV_MATH_FUNC, API_BLAS)), ("cublasSscalBatched", ("rocblas_sscal_batched", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasDscal", ("rocblas_dscal", CONV_MATH_FUNC, API_BLAS)), ("cublasDscalBatched", ("rocblas_dscal_batched", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasCscal", ("rocblas_cscal", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasCsscal", ("rocblas_csscal", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasZscal", ("rocblas_zscal", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasZdscal", ("rocblas_zdscal", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasSaxpy", ("rocblas_saxpy", CONV_MATH_FUNC, API_BLAS)), ("cublasSaxpyBatched", ("rocblas_saxpy_batched", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasDaxpy", ("rocblas_daxpy", CONV_MATH_FUNC, API_BLAS)), ("cublasCaxpy", ("rocblas_caxpy", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasZaxpy", ("rocblas_zaxpy", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasScopy", ("rocblas_scopy", CONV_MATH_FUNC, API_BLAS)), ("cublasScopyBatched", ("rocblas_scopy_batched", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasDcopy", ("rocblas_dcopy", CONV_MATH_FUNC, API_BLAS)), ("cublasDcopyBatched", ("rocblas_dcopy_batched", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasCcopy", ("rocblas_ccopy", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasZcopy", ("rocblas_zcopy", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasSswap", ("rocblas_sswap", CONV_MATH_FUNC, API_BLAS)), ("cublasDswap", ("rocblas_dswap", CONV_MATH_FUNC, API_BLAS)), ("cublasCswap", ("rocblas_cswap", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasZswap", ("rocblas_zswap", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasIsamax", ("rocblas_isamax", CONV_MATH_FUNC, API_BLAS)), ("cublasIdamax", ("rocblas_idamax", CONV_MATH_FUNC, API_BLAS)), ("cublasIcamax", ("rocblas_icamax", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasIzamax", ("rocblas_izamax", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasIsamin", ("rocblas_isamin", CONV_MATH_FUNC, API_BLAS)), ("cublasIdamin", ("rocblas_idamin", CONV_MATH_FUNC, API_BLAS)), ("cublasIcamin", ("rocblas_icamin", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasIzamin", ("rocblas_izamin", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasSasum", ("rocblas_sasum", CONV_MATH_FUNC, API_BLAS)), ("cublasSasumBatched", ("rocblas_sasum_batched", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasDasum", ("rocblas_dasum", CONV_MATH_FUNC, API_BLAS)), ("cublasDasumBatched", ("rocblas_dasum_batched", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasScasum", ("rocblas_scasum", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasDzasum", ("rocblas_dzasum", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasSrot", ("rocblas_srot", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasDrot", ("rocblas_drot", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasCrot", ("rocblas_crot", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasCsrot", ("rocblas_csrot", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasZrot", ("rocblas_zrot", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasZdrot", ("rocblas_zdrot", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasSrotg", ("rocblas_srotg", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasDrotg", ("rocblas_drotg", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasCrotg", ("rocblas_crotg", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasZrotg", ("rocblas_zrotg", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasSrotm", ("rocblas_srotm", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasDrotm", ("rocblas_drotm", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasSrotmg", ("rocblas_srotmg", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasDrotmg", ("rocblas_drotmg", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasSgemv", ("rocblas_sgemv", CONV_MATH_FUNC, API_BLAS)), ("cublasSgemvBatched", ("rocblas_sgemv_batched", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasDgemv", ("rocblas_dgemv", CONV_MATH_FUNC, API_BLAS)), ("cublasCgemv", ("rocblas_cgemv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasZgemv", ("rocblas_zgemv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasSgbmv", ("rocblas_sgbmv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasDgbmv", ("rocblas_dgbmv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasCgbmv", ("rocblas_cgbmv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasZgbmv", ("rocblas_zgbmv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasStrmv", ("rocblas_strmv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasDtrmv", ("rocblas_dtrmv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasCtrmv", ("rocblas_ctrmv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasZtrmv", ("rocblas_ztrmv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasStbmv", ("rocblas_stbmv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasDtbmv", ("rocblas_dtbmv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasCtbmv", ("rocblas_ctbmv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasZtbmv", ("rocblas_ztbmv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasStpmv", ("rocblas_stpmv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasDtpmv", ("rocblas_dtpmv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasCtpmv", ("rocblas_ctpmv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasZtpmv", ("rocblas_ztpmv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasStrsv", ("rocblas_strsv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasDtrsv", ("rocblas_dtrsv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasCtrsv", ("rocblas_ctrsv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasZtrsv", ("rocblas_ztrsv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasStpsv", ("rocblas_stpsv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasDtpsv", ("rocblas_dtpsv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasCtpsv", ("rocblas_ctpsv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasZtpsv", ("rocblas_ztpsv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasStbsv", ("rocblas_stbsv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasDtbsv", ("rocblas_dtbsv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasCtbsv", ("rocblas_ctbsv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasZtbsv", ("rocblas_ztbsv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasSsymv", ("rocblas_ssymv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasDsymv", ("rocblas_dsymv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasCsymv", ("rocblas_csymv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasZsymv", ("rocblas_zsymv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasChemv", ("rocblas_chemv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasZhemv", ("rocblas_zhemv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasSsbmv", ("rocblas_ssbmv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasDsbmv", ("rocblas_dsbmv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasChbmv", ("rocblas_chbmv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasZhbmv", ("rocblas_zhbmv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasSspmv", ("rocblas_sspmv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasDspmv", ("rocblas_dspmv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasChpmv", ("rocblas_chpmv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasZhpmv", ("rocblas_zhpmv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasSger", ("rocblas_sger", CONV_MATH_FUNC, API_BLAS)), ("cublasDger", ("rocblas_dger", CONV_MATH_FUNC, API_BLAS)), ("cublasCgeru", ("rocblas_cgeru", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasCgerc", ("rocblas_cgerc", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasZgeru", ("rocblas_zgeru", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasZgerc", ("rocblas_zgerc", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasSsyr", ("rocblas_ssyr", CONV_MATH_FUNC, API_BLAS)), ("cublasDsyr", ("rocblas_dsyr", CONV_MATH_FUNC, API_BLAS)), ("cublasCher", ("rocblas_cher", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasZher", ("rocblas_zher", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasSspr", ("rocblas_sspr", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasDspr", ("rocblas_dspr", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasChpr", ("rocblas_chpr", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasZhpr", ("rocblas_zhpr", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasSsyr2", ("rocblas_ssyr2", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasDsyr2", ("rocblas_dsyr2", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasCher2", ("rocblas_cher2", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasZher2", ("rocblas_zher2", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasSspr2", ("rocblas_sspr2", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasDspr2", ("rocblas_dspr2", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasChpr2", ("rocblas_chpr2", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasZhpr2", ("rocblas_zhpr2", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasSgemmBatched", ("rocblas_sgemm_batched", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasDgemmBatched", ("rocblas_dgemm_batched", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasHgemmBatched", ("rocblas_hgemm_batched", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasSgemmStridedBatched", ("rocblas_sgemm_strided_batched", CONV_MATH_FUNC, API_BLAS)), ("cublasDgemmStridedBatched", ("rocblas_dgemm_strided_batched", CONV_MATH_FUNC, API_BLAS)), ("cublasHgemmStridedBatched", ("rocblas_hgemm_strided_batched", CONV_MATH_FUNC, API_BLAS)), ("cublasCgemmBatched", ("rocblas_cgemm_batched", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasCgemm3mBatched", ("rocblas_cgemm_3m_batched", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasZgemmBatched", ("rocblas_zgemm_batched", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasCgemmStridedBatched", ("rocblas_cgemm_strided_batched", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasCgemm3mStridedBatched", ("rocblas_cgemm_3m_strided_batched", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasZgemmStridedBatched", ("rocblas_zgemm_strided_batched", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasHgemmStridedBatched", ("rocblas_hgemm_strided_batched", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasSgemm", ("rocblas_sgemm", CONV_MATH_FUNC, API_BLAS)), ("cublasDgemm", ("rocblas_dgemm", CONV_MATH_FUNC, API_BLAS)), ("cublasCgemm", ("rocblas_cgemm", CONV_MATH_FUNC, API_BLAS)), ("cublasZgemm", ("rocblas_zgemm", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasHgemm", ("rocblas_hgemm", CONV_MATH_FUNC, API_BLAS)), ("cublasSsyrk", ("rocblas_ssyrk", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasDsyrk", ("rocblas_dsyrk", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasCsyrk", ("rocblas_csyrk", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasZsyrk", ("rocblas_zsyrk", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasCherk", ("rocblas_cherk", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasZherk", ("rocblas_zherk", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasSsyr2k", ("rocblas_ssyr2k", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasDsyr2k", ("rocblas_dsyr2k", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasCsyr2k", ("rocblas_csyr2k", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasZsyr2k", ("rocblas_zyr2k", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasSsyrkx", ("rocblas_ssyrkx", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasDsyrkx", ("rocblas_dsyrkx", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasCsyrkx", ("rocblas_csyrkx", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasZsyrkx", ("rocblas_zsyrkx", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasCher2k", ("rocblas_cher2k", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasZher2k", ("rocblas_zher2k", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasCherkx", ("rocblas_cherkx", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasZherkx", ("rocblas_zherkx", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasSsymm", ("rocblas_ssymm", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasDsymm", ("rocblas_dsymm", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasCsymm", ("rocblas_csymm", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasZsymm", ("rocblas_zsymm", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasChemm", ("rocblas_chemm", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasZhemm", ("rocblas_zhemm", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasStrsm", ("rocblas_strsm", CONV_MATH_FUNC, API_BLAS)), ("cublasDtrsm", ("rocblas_dtrsm", CONV_MATH_FUNC, API_BLAS)), ("cublasCtrsm", ("rocblas_ctrsm", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasZtrsm", ("rocblas_ztrsm", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasStrsmBatched", ("rocblas_strsm_batched", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasDtrsmBatched", ("rocblas_dtrsm_batched", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasCtrsmBatched", ("rocblas_ctrsm_batched", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasZtrsmBatched", ("rocblas_ztrsm_batched", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasStrmm", ("rocblas_strmm", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasDtrmm", ("rocblas_dtrmm", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasCtrmm", ("rocblas_ctrmm", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasZtrmm", ("rocblas_ztrmm", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasSgeam", ("rocblas_sgeam", CONV_MATH_FUNC, API_BLAS)), ("cublasDgeam", ("rocblas_dgeam", CONV_MATH_FUNC, API_BLAS)), ("cublasCgeam", ("rocblas_cgeam", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasZgeam", ("rocblas_zgeam", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasSgetrfBatched", ("rocblas_sgetrf_batched", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasDgetrfBatched", ("rocblas_dgetrf_batched", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasCgetrfBatched", ("rocblas_cgetrf_batched", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasZgetrfBatched", ("rocblas_zgetrf_batched", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasSgetriBatched", ("rocblas_sgetri_batched", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasDgetriBatched", ("rocblas_dgetri_batched", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasCgetriBatched", ("rocblas_cgetri_batched", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasZgetriBatched", ("rocblas_zgetri_batched", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasSgetrsBatched", ("rocblas_sgetrs_batched", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasDgetrsBatched", ("rocblas_dgetrs_batched", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasCgetrsBatched", ("rocblas_cgetrs_batched", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasZgetrsBatched", ("rocblas_zgetrs_batched", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasStrsmBatched", ("rocblas_strsm_batched", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasDtrsmBatched", ("rocblas_dtrsm_batched", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasCtrsmBatched", ("rocblas_ctrsm_batched", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasZtrsmBatched", ("rocblas_dtrsm_batched", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasSmatinvBatched", ("rocblas_smatinv_batched", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasDmatinvBatched", ("rocblas_dmatinv_batched", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasCmatinvBatched", ("rocblas_cmatinv_batched", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasZmatinvBatched", ("rocblas_zmatinv_batched", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasSgeqrfBatched", ("rocblas_sgeqrf_batched", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasDgeqrfBatched", ("rocblas_dgeqrf_batched", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasCgeqrfBatched", ("rocblas_cgeqrf_batched", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasZgeqrfBatched", ("rocblas_zgeqrf_batched", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasSgelsBatched", ("rocblas_sgels_batched", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasDgelsBatched", ("rocblas_dgels_batched", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasCgelsBatched", ("rocblas_cgels_batched", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasZgelsBatched", ("rocblas_zgels_batched", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasSdgmm", ("rocblas_sdgmm", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasDdgmm", ("rocblas_ddgmm", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasCdgmm", ("rocblas_cdgmm", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasZdgmm", ("rocblas_zdgmm", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasStpttr", ("rocblas_stpttr", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasDtpttr", ("rocblas_dtpttr", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasCtpttr", ("rocblas_ctpttr", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasZtpttr", ("rocblas_ztpttr", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasStrttp", ("rocblas_strttp", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasDtrttp", ("rocblas_dtrttp", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasCtrttp", ("rocblas_ctrttp", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasZtrttp", ("rocblas_ztrttp", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasCreate_v2", ("rocblas_create_handle", CONV_MATH_FUNC, API_BLAS)), ("cublasDestroy_v2", ("rocblas_destroy_handle", CONV_MATH_FUNC, API_BLAS)), ("cublasGetVersion_v2", ("rocblas_get_version", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasSetStream", ("rocblas_set_stream", CONV_MATH_FUNC, API_BLAS)), ("cublasGetStream", ("rocblas_get_stream", CONV_MATH_FUNC, API_BLAS)), ("cublasSetStream_v2", ("rocblas_set_stream", CONV_MATH_FUNC, API_BLAS)), ("cublasGetStream_v2", ("rocblas_get_stream", CONV_MATH_FUNC, API_BLAS)), ("cublasGetPointerMode", ("rocblas_get_pointer_mode", CONV_MATH_FUNC, API_BLAS)), ("cublasSetPointerMode", ("rocblas_set_pointer_mode", CONV_MATH_FUNC, API_BLAS)), ("cublasGetPointerMode_v2", ("rocblas_get_pointer_mode", CONV_MATH_FUNC, API_BLAS)), ("cublasSetPointerMode_v2", ("rocblas_set_pointer_mode", CONV_MATH_FUNC, API_BLAS)), ("cublasSgemv_v2", ("rocblas_sgemv", CONV_MATH_FUNC, API_BLAS)), ("cublasDgemv_v2", ("rocblas_dgemv", CONV_MATH_FUNC, API_BLAS)), ("cublasCgemv_v2", ("rocblas_cgemv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasZgemv_v2", ("rocblas_zgemv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasSgbmv_v2", ("rocblas_sgbmv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasDgbmv_v2", ("rocblas_dgbmv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasCgbmv_v2", ("rocblas_cgbmv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasZgbmv_v2", ("rocblas_zgbmv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasStrmv_v2", ("rocblas_strmv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasDtrmv_v2", ("rocblas_dtrmv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasCtrmv_v2", ("rocblas_ctrmv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasZtrmv_v2", ("rocblas_ztrmv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasStbmv_v2", ("rocblas_stbmv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasDtbmv_v2", ("rocblas_dtbmv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasCtbmv_v2", ("rocblas_ctbmv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasZtbmv_v2", ("rocblas_ztbmv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasStpmv_v2", ("rocblas_stpmv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasDtpmv_v2", ("rocblas_dtpmv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasCtpmv_v2", ("rocblas_ctpmv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasZtpmv_v2", ("rocblas_ztpmv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasStrsv_v2", ("rocblas_strsv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasDtrsv_v2", ("rocblas_dtrsv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasCtrsv_v2", ("rocblas_ctrsv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasZtrsv_v2", ("rocblas_ztrsv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasStpsv_v2", ("rocblas_stpsv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasDtpsv_v2", ("rocblas_dtpsv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasCtpsv_v2", ("rocblas_ctpsv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasZtpsv_v2", ("rocblas_ztpsv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasStbsv_v2", ("rocblas_stbsv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasDtbsv_v2", ("rocblas_dtbsv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasCtbsv_v2", ("rocblas_ctbsv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasZtbsv_v2", ("rocblas_ztbsv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasSsymv_v2", ("rocblas_ssymv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasDsymv_v2", ("rocblas_dsymv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasCsymv_v2", ("rocblas_csymv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasZsymv_v2", ("rocblas_zsymv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasChemv_v2", ("rocblas_chemv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasZhemv_v2", ("rocblas_zhemv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasSsbmv_v2", ("rocblas_ssbmv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasDsbmv_v2", ("rocblas_dsbmv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasChbmv_v2", ("rocblas_chbmv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasZhbmv_v2", ("rocblas_zhbmv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasSspmv_v2", ("rocblas_sspmv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasDspmv_v2", ("rocblas_dspmv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasChpmv_v2", ("rocblas_chpmv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasZhpmv_v2", ("rocblas_zhpmv", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasSger_v2", ("rocblas_sger", CONV_MATH_FUNC, API_BLAS)), ("cublasDger_v2", ("rocblas_dger", CONV_MATH_FUNC, API_BLAS)), ("cublasCgeru_v2", ("rocblas_cgeru", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasCgerc_v2", ("rocblas_cergc", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasZgeru_v2", ("rocblas_zgeru", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasZgerc_v2", ("rocblas_zgerc", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasSsyr_v2", ("rocblas_ssyr", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasDsyr_v2", ("rocblas_dsyr", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasCsyr_v2", ("rocblas_csyr", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasZsyr_v2", ("rocblas_zsyr", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasCher_v2", ("rocblas_cher", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasZher_v2", ("rocblas_zher", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasSspr_v2", ("rocblas_sspr", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasDspr_v2", ("rocblas_dspr", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasChpr_v2", ("rocblas_chpr", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasZhpr_v2", ("rocblas_zhpr", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasSsyr2_v2", ("rocblas_ssyr2", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasDsyr2_v2", ("rocblas_dsyr2", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasCsyr2_v2", ("rocblas_csyr2", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasZsyr2_v2", ("rocblas_zsyr2", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasCher2_v2", ("rocblas_cher2", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasZher2_v2", ("rocblas_zher2", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasSspr2_v2", ("rocblas_sspr2", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasDspr2_v2", ("rocblas_dspr2", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasChpr2_v2", ("rocblas_chpr2", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasZhpr2_v2", ("rocblas_zhpr2", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasSgemm_v2", ("rocblas_sgemm", CONV_MATH_FUNC, API_BLAS)), ("cublasDgemm_v2", ("rocblas_dgemm", CONV_MATH_FUNC, API_BLAS)), ("cublasCgemm_v2", ("rocblas_cgemm", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasCgemm3m", ("rocblas_cgemm_3m", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasCgemm3mEx", ("rocblas_cgemm_3mex", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasZgemm_v2", ("rocblas_zgemm", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasZgemm3m", ("rocblas_zgemm_3m", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), # NB: The function rocblas_sgemmex doesn't actually exist in # rocblas, as of 2018-12-05 ("cublasSgemmEx", ("rocblas_sgemmex", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasGemmEx", ("rocblas_gemmex", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasCgemmEx", ("rocblas_cgemmex", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasUint8gemmBias", ("rocblas_uint8gemmbias", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasSsyrk_v2", ("rocblas_ssyrk", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasDsyrk_v2", ("rocblas_dsyrk", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasCsyrk_v2", ("rocblas_csyrk", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasZsyrk_v2", ("rocblas_zsyrk", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasCsyrkEx", ("rocblas_csyrkex", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasCsyrk3mEx", ("rocblas_csyrk3mex", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasCherk_v2", ("rocblas_cherk", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasCherkEx", ("rocblas_cherkex", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasCherk3mEx", ("rocblas_cherk3mex", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasZherk_v2", ("rocblas_zherk", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasSsyr2k_v2", ("rocblas_ssyr2k", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasDsyr2k_v2", ("rocblas_dsyr2k", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasCsyr2k_v2", ("rocblas_csyr2k", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasZsyr2k_v2", ("rocblas_zsyr2k", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasCher2k_v2", ("rocblas_cher2k", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasZher2k_v2", ("rocblas_zher2k", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasSsymm_v2", ("rocblas_ssymm", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasDsymm_v2", ("rocblas_dsymm", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasCsymm_v2", ("rocblas_csymm", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasZsymm_v2", ("rocblas_zsymm", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasChemm_v2", ("rocblas_chemm", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasZhemm_v2", ("rocblas_zhemm", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasStrsm_v2", ("rocblas_strsm", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasDtrsm_v2", ("rocblas_dtrsm", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasCtrsm_v2", ("rocblas_ctrsm", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasZtrsm_v2", ("rocblas_ztrsm", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasStrmm_v2", ("rocblas_strmm", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasDtrmm_v2", ("rocblas_dtrmm", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasCtrmm_v2", ("rocblas_ctrmm", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasZtrmm_v2", ("rocblas_ztrmm", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasSnrm2_v2", ("rocblas_snrm2", CONV_MATH_FUNC, API_BLAS)), ("cublasDnrm2_v2", ("rocblas_dnrm2", CONV_MATH_FUNC, API_BLAS)), ("cublasScnrm2_v2", ("rocblas_scnrm2", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasDznrm2_v2", ("rocblas_dznrm2", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasDotEx", ("rocblas_dotex", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasDotcEx", ("rocblas_dotcex", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasSdot_v2", ("rocblas_sdot", CONV_MATH_FUNC, API_BLAS)), ("cublasDdot_v2", ("rocblas_ddot", CONV_MATH_FUNC, API_BLAS)), ("cublasCdotu_v2", ("rocblas_cdotu", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasCdotc_v2", ("rocblas_cdotc", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasZdotu_v2", ("rocblas_zdotu", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasZdotc_v2", ("rocblas_zdotc", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasScalEx", ("rocblas_scalex", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasSscal_v2", ("rocblas_sscal", CONV_MATH_FUNC, API_BLAS)), ("cublasDscal_v2", ("rocblas_dscal", CONV_MATH_FUNC, API_BLAS)), ("cublasCscal_v2", ("rocblas_cscal", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasCsscal_v2", ("rocblas_csscal", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasZscal_v2", ("rocblas_zcsal", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasZdscal_v2", ("rocblas_zdscal", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasAxpyEx", ("rocblas_axpyex", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasSaxpy_v2", ("rocblas_saxpy", CONV_MATH_FUNC, API_BLAS)), ("cublasDaxpy_v2", ("rocblas_daxpy", CONV_MATH_FUNC, API_BLAS)), ("cublasCaxpy_v2", ("rocblas_caxpy", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasZaxpy_v2", ("rocblas_zaxpy", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasScopy_v2", ("rocblas_scopy", CONV_MATH_FUNC, API_BLAS)), ("cublasDcopy_v2", ("rocblas_dcopy", CONV_MATH_FUNC, API_BLAS)), ("cublasCcopy_v2", ("rocblas_ccopy", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasZcopy_v2", ("rocblas_zcopy", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasSswap_v2", ("rocblas_sswap", CONV_MATH_FUNC, API_BLAS)), ("cublasDswap_v2", ("rocblas_dswap", CONV_MATH_FUNC, API_BLAS)), ("cublasCswap_v2", ("rocblas_cswap", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasZswap_v2", ("rocblas_zswap", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasIsamax_v2", ("rocblas_isamax", CONV_MATH_FUNC, API_BLAS)), ("cublasIdamax_v2", ("rocblas_idamax", CONV_MATH_FUNC, API_BLAS)), ("cublasIcamax_v2", ("rocblas_icamax", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasIzamax_v2", ("rocblas_izamax", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasIsamin_v2", ("rocblas_isamin", CONV_MATH_FUNC, API_BLAS)), ("cublasIdamin_v2", ("rocblas_idamin", CONV_MATH_FUNC, API_BLAS)), ("cublasIcamin_v2", ("rocblas_icamin", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasIzamin_v2", ("rocblas_izamin", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasSasum_v2", ("rocblas_sasum", CONV_MATH_FUNC, API_BLAS)), ("cublasDasum_v2", ("rocblas_dasum", CONV_MATH_FUNC, API_BLAS)), ("cublasScasum_v2", ("rocblas_scasum", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasDzasum_v2", ("rocblas_dzasum", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasSrot_v2", ("rocblas_srot", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasDrot_v2", ("rocblas_drot", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasCrot_v2", ("rocblas_crot", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasCsrot_v2", ("rocblas_csrot", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasZrot_v2", ("rocblas_zrot", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasZdrot_v2", ("rocblas_zdrot", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasSrotg_v2", ("rocblas_srotg", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasDrotg_v2", ("rocblas_drotg", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasCrotg_v2", ("rocblas_crotg", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasZrotg_v2", ("rocblas_zrotg", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasSrotm_v2", ("rocblas_srotm", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasDrotm_v2", ("rocblas_drotm", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasSrotmg_v2", ("rocblas_srotmg", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("cublasDrotmg_v2", ("rocblas_drotmg", CONV_MATH_FUNC, API_BLAS, HIP_UNSUPPORTED)), ("CURAND_STATUS_SUCCESS", ("HIPRAND_STATUS_SUCCESS", CONV_NUMERIC_LITERAL, API_RAND)), ("CURAND_STATUS_VERSION_MISMATCH", ("HIPRAND_STATUS_VERSION_MISMATCH", CONV_NUMERIC_LITERAL, API_RAND)), ("CURAND_STATUS_NOT_INITIALIZED", ("HIPRAND_STATUS_NOT_INITIALIZED", CONV_NUMERIC_LITERAL, API_RAND)), ("CURAND_STATUS_ALLOCATION_FAILED", ("HIPRAND_STATUS_ALLOCATION_FAILED", CONV_NUMERIC_LITERAL, API_RAND)), ("CURAND_STATUS_TYPE_ERROR", ("HIPRAND_STATUS_TYPE_ERROR", CONV_NUMERIC_LITERAL, API_RAND)), ("CURAND_STATUS_OUT_OF_RANGE", ("HIPRAND_STATUS_OUT_OF_RANGE", CONV_NUMERIC_LITERAL, API_RAND)), ("CURAND_STATUS_LENGTH_NOT_MULTIPLE", ("HIPRAND_STATUS_LENGTH_NOT_MULTIPLE", CONV_NUMERIC_LITERAL, API_RAND)), ("CURAND_STATUS_DOUBLE_PRECISION_REQUIRED", ("HIPRAND_STATUS_DOUBLE_PRECISION_REQUIRED", CONV_NUMERIC_LITERAL, API_RAND)), ("CURAND_STATUS_LAUNCH_FAILURE", ("HIPRAND_STATUS_LAUNCH_FAILURE", CONV_NUMERIC_LITERAL, API_RAND)), ("CURAND_STATUS_PREEXISTING_FAILURE", ("HIPRAND_STATUS_PREEXISTING_FAILURE", CONV_NUMERIC_LITERAL, API_RAND)), ("CURAND_STATUS_INITIALIZATION_FAILED", ("HIPRAND_STATUS_INITIALIZATION_FAILED", CONV_NUMERIC_LITERAL, API_RAND)), ("CURAND_STATUS_ARCH_MISMATCH", ("HIPRAND_STATUS_ARCH_MISMATCH", CONV_NUMERIC_LITERAL, API_RAND)), ("CURAND_STATUS_INTERNAL_ERROR", ("HIPRAND_STATUS_INTERNAL_ERROR", CONV_NUMERIC_LITERAL, API_RAND)), ("CURAND_RNG_TEST", ("HIPRAND_RNG_TEST", CONV_NUMERIC_LITERAL, API_RAND)), ("mtgp32dc_params_fast_11213", ("mtgp32dc_params_fast_11213", CONV_NUMERIC_LITERAL, API_RAND)), ("CURAND_RNG_PSEUDO_DEFAULT", ("HIPRAND_RNG_PSEUDO_DEFAULT", CONV_NUMERIC_LITERAL, API_RAND)), ("CURAND_RNG_PSEUDO_XORWOW", ("HIPRAND_RNG_PSEUDO_XORWOW", CONV_NUMERIC_LITERAL, API_RAND)), ("CURAND_RNG_PSEUDO_MRG32K3A", ("HIPRAND_RNG_PSEUDO_MRG32K3A", CONV_NUMERIC_LITERAL, API_RAND)), ("CURAND_RNG_PSEUDO_MTGP32", ("HIPRAND_RNG_PSEUDO_MTGP32", CONV_NUMERIC_LITERAL, API_RAND)), ("CURAND_RNG_PSEUDO_MT19937", ("HIPRAND_RNG_PSEUDO_MT19937", CONV_NUMERIC_LITERAL, API_RAND)), ("CURAND_RNG_PSEUDO_PHILOX4_32_10", ("HIPRAND_RNG_PSEUDO_PHILOX4_32_10", CONV_NUMERIC_LITERAL, API_RAND)), ("CURAND_RNG_QUASI_DEFAULT", ("HIPRAND_RNG_QUASI_DEFAULT", CONV_NUMERIC_LITERAL, API_RAND)), ("CURAND_RNG_QUASI_SOBOL32", ("HIPRAND_RNG_QUASI_SOBOL32", CONV_NUMERIC_LITERAL, API_RAND)), ("CURAND_RNG_QUASI_SCRAMBLED_SOBOL32", ("HIPRAND_RNG_QUASI_SCRAMBLED_SOBOL32", CONV_NUMERIC_LITERAL, API_RAND)), ("CURAND_RNG_QUASI_SOBOL64", ("HIPRAND_RNG_QUASI_SOBOL64", CONV_NUMERIC_LITERAL, API_RAND)), ("CURAND_RNG_QUASI_SCRAMBLED_SOBOL64", ("HIPRAND_RNG_QUASI_SCRAMBLED_SOBOL64", CONV_NUMERIC_LITERAL, API_RAND)), ("curand_ORDERING_PSEUDO_BEST", ("HIPRAND_ORDERING_PSEUDO_BEST", CONV_NUMERIC_LITERAL, API_RAND, HIP_UNSUPPORTED)), ("curand_ORDERING_PSEUDO_DEFAULT", ("HIPRAND_ORDERING_PSEUDO_DEFAULT", CONV_NUMERIC_LITERAL, API_RAND, HIP_UNSUPPORTED)), ("curand_ORDERING_PSEUDO_SEEDED", ("HIPRAND_ORDERING_PSEUDO_SEEDED", CONV_NUMERIC_LITERAL, API_RAND, HIP_UNSUPPORTED)), ("curand_ORDERING_QUASI_DEFAULT", ("HIPRAND_ORDERING_QUASI_DEFAULT", CONV_NUMERIC_LITERAL, API_RAND, HIP_UNSUPPORTED)), ("curand_DIRECTION_VECTORS_32_JOEKUO6", ("HIPRAND_DIRECTION_VECTORS_32_JOEKUO6", CONV_NUMERIC_LITERAL, API_RAND, HIP_UNSUPPORTED)), ("curand_SCRAMBLED_DIRECTION_VECTORS_32_JOEKUO6", ("HIPRAND_SCRAMBLED_DIRECTION_VECTORS_32_JOEKUO6", CONV_NUMERIC_LITERAL, API_RAND, HIP_UNSUPPORTED)), ("curand_DIRECTION_VECTORS_64_JOEKUO6", ("HIPRAND_DIRECTION_VECTORS_64_JOEKUO6", CONV_NUMERIC_LITERAL, API_RAND, HIP_UNSUPPORTED)), ("curand_SCRAMBLED_DIRECTION_VECTORS_64_JOEKUO6", ("HIPRAND_SCRAMBLED_DIRECTION_VECTORS_64_JOEKUO6", CONV_NUMERIC_LITERAL, API_RAND, HIP_UNSUPPORTED)), ("curand_CHOOSE_BEST", ("HIPRAND_CHOOSE_BEST", CONV_NUMERIC_LITERAL, API_RAND, HIP_UNSUPPORTED)), ("curand_ITR", ("HIPRAND_ITR", CONV_NUMERIC_LITERAL, API_RAND, HIP_UNSUPPORTED)), ("curand_KNUTH", ("HIPRAND_KNUTH", CONV_NUMERIC_LITERAL, API_RAND, HIP_UNSUPPORTED)), ("curand_HITR", ("HIPRAND_HITR", CONV_NUMERIC_LITERAL, API_RAND, HIP_UNSUPPORTED)), ("curand_M1", ("HIPRAND_M1", CONV_NUMERIC_LITERAL, API_RAND, HIP_UNSUPPORTED)), ("curand_M2", ("HIPRAND_M2", CONV_NUMERIC_LITERAL, API_RAND, HIP_UNSUPPORTED)), ("curand_BINARY_SEARCH", ("HIPRAND_BINARY_SEARCH", CONV_NUMERIC_LITERAL, API_RAND, HIP_UNSUPPORTED)), ("curand_DISCRETE_GAUSS", ("HIPRAND_DISCRETE_GAUSS", CONV_NUMERIC_LITERAL, API_RAND, HIP_UNSUPPORTED)), ("curand_REJECTION", ("HIPRAND_REJECTION", CONV_NUMERIC_LITERAL, API_RAND, HIP_UNSUPPORTED)), ("curand_DEVICE_API", ("HIPRAND_DEVICE_API", CONV_NUMERIC_LITERAL, API_RAND, HIP_UNSUPPORTED)), ("curand_FAST_REJECTION", ("HIPRAND_FAST_REJECTION", CONV_NUMERIC_LITERAL, API_RAND, HIP_UNSUPPORTED)), ("curand_3RD", ("HIPRAND_3RD", CONV_NUMERIC_LITERAL, API_RAND, HIP_UNSUPPORTED)), ("curand_DEFINITION", ("HIPRAND_DEFINITION", CONV_NUMERIC_LITERAL, API_RAND, HIP_UNSUPPORTED)), ("curand_POISSON", ("HIPRAND_POISSON", CONV_NUMERIC_LITERAL, API_RAND, HIP_UNSUPPORTED)), ("curandCreateGenerator", ("hiprandCreateGenerator", CONV_MATH_FUNC, API_RAND)), ("curandCreateGeneratorHost", ("hiprandCreateGeneratorHost", CONV_MATH_FUNC, API_RAND)), ("curandCreatePoissonDistribution", ("hiprandCreatePoissonDistribution", CONV_MATH_FUNC, API_RAND)), ("curandDestroyDistribution", ("hiprandDestroyDistribution", CONV_MATH_FUNC, API_RAND)), ("curandDestroyGenerator", ("hiprandDestroyGenerator", CONV_MATH_FUNC, API_RAND)), ("curandGenerate", ("hiprandGenerate", CONV_MATH_FUNC, API_RAND)), ("curandGenerateLogNormal", ("hiprandGenerateLogNormal", CONV_MATH_FUNC, API_RAND)), ("curandGenerateLogNormalDouble", ("hiprandGenerateLogNormalDouble", CONV_MATH_FUNC, API_RAND)), ("curandGenerateLongLong", ("hiprandGenerateLongLong", CONV_MATH_FUNC, API_RAND, HIP_UNSUPPORTED)), ("curandGenerateNormal", ("hiprandGenerateNormal", CONV_MATH_FUNC, API_RAND)), ("curandGenerateNormalDouble", ("hiprandGenerateNormalDouble", CONV_MATH_FUNC, API_RAND)), ("curandGeneratePoisson", ("hiprandGeneratePoisson", CONV_MATH_FUNC, API_RAND)), ("curandGenerateSeeds", ("hiprandGenerateSeeds", CONV_MATH_FUNC, API_RAND)), ("curandGenerateUniform", ("hiprandGenerateUniform", CONV_MATH_FUNC, API_RAND)), ("curandGenerateUniformDouble", ("hiprandGenerateUniformDouble", CONV_MATH_FUNC, API_RAND)), ("curandGetDirectionVectors32", ("hiprandGetDirectionVectors32", CONV_MATH_FUNC, API_RAND, HIP_UNSUPPORTED)), ("curandGetDirectionVectors64", ("hiprandGetDirectionVectors64", CONV_MATH_FUNC, API_RAND, HIP_UNSUPPORTED)), ("curandGetProperty", ("hiprandGetProperty", CONV_MATH_FUNC, API_RAND, HIP_UNSUPPORTED)), ("curandGetScrambleConstants32", ("hiprandGetScrambleConstants32", CONV_MATH_FUNC, API_RAND, HIP_UNSUPPORTED)), ("curandGetScrambleConstants64", ("hiprandGetScrambleConstants64", CONV_MATH_FUNC, API_RAND, HIP_UNSUPPORTED)), ("curandGetVersion", ("hiprandGetVersion", CONV_MATH_FUNC, API_RAND)), ("curandSetGeneratorOffset", ("hiprandSetGeneratorOffset", CONV_MATH_FUNC, API_RAND)), ("curandSetGeneratorOrdering", ("hiprandSetGeneratorOrdering", CONV_MATH_FUNC, API_RAND, HIP_UNSUPPORTED)), ("curandSetPseudoRandomGeneratorSeed", ("hiprandSetPseudoRandomGeneratorSeed", CONV_MATH_FUNC, API_RAND)), ("curandSetQuasiRandomGeneratorDimensions", ("hiprandSetQuasiRandomGeneratorDimensions", CONV_MATH_FUNC, API_RAND)), ("curandSetStream", ("hiprandSetStream", CONV_MATH_FUNC, API_RAND)), ("curand", ("hiprand", CONV_DEVICE_FUNC, API_RAND)), ("curand_init", ("hiprand_init", CONV_DEVICE_FUNC, API_RAND)), ("curand_log_normal", ("hiprand_log_normal", CONV_DEVICE_FUNC, API_RAND)), ("curand_log_normal_double", ("hiprand_log_normal_double", CONV_DEVICE_FUNC, API_RAND)), ("curand_log_normal2", ("hiprand_log_normal2", CONV_DEVICE_FUNC, API_RAND)), ("curand_log_normal2_double", ("hiprand_log_normal2_double", CONV_DEVICE_FUNC, API_RAND)), ("curand_log_normal4", ("hiprand_log_normal4", CONV_DEVICE_FUNC, API_RAND)), ("curand_log_normal4_double", ("hiprand_log_normal4_double", CONV_DEVICE_FUNC, API_RAND)), ("curand_mtgp32_single", ("hiprand_mtgp32_single", CONV_DEVICE_FUNC, API_RAND, HIP_UNSUPPORTED)), ("curand_mtgp32_single_specific", ("hiprand_mtgp32_single_specific", CONV_DEVICE_FUNC, API_RAND, HIP_UNSUPPORTED)), ("curand_mtgp32_specific", ("hiprand_mtgp32_specific", CONV_DEVICE_FUNC, API_RAND, HIP_UNSUPPORTED)), ("curand_normal", ("hiprand_normal", CONV_DEVICE_FUNC, API_RAND)), ("curandMakeMTGP32Constants", ("hiprandMakeMTGP32Constants", CONV_DEVICE_FUNC, API_RAND)), ("curandMakeMTGP32KernelState", ("hiprandMakeMTGP32KernelState", CONV_DEVICE_FUNC, API_RAND)), ("curand_normal_double", ("hiprand_normal_double", CONV_DEVICE_FUNC, API_RAND)), ("curand_normal2", ("hiprand_normal2", CONV_DEVICE_FUNC, API_RAND)), ("curand_normal2_double", ("hiprand_normal2_double", CONV_DEVICE_FUNC, API_RAND)), ("curand_normal4", ("hiprand_normal4", CONV_DEVICE_FUNC, API_RAND)), ("curand_normal4_double", ("hiprand_normal4_double", CONV_DEVICE_FUNC, API_RAND)), ("curand_uniform", ("hiprand_uniform", CONV_DEVICE_FUNC, API_RAND)), ("curand_uniform_double", ("hiprand_uniform_double", CONV_DEVICE_FUNC, API_RAND)), ("curand_uniform2_double", ("hiprand_uniform2_double", CONV_DEVICE_FUNC, API_RAND)), ("curand_uniform4", ("hiprand_uniform4", CONV_DEVICE_FUNC, API_RAND)), ("curand_uniform4_double", ("hiprand_uniform4_double", CONV_DEVICE_FUNC, API_RAND)), ("curand_discrete", ("hiprand_discrete", CONV_DEVICE_FUNC, API_RAND)), ("curand_discrete4", ("hiprand_discrete4", CONV_DEVICE_FUNC, API_RAND)), ("curand_poisson", ("hiprand_poisson", CONV_DEVICE_FUNC, API_RAND)), ("curand_poisson4", ("hiprand_poisson4", CONV_DEVICE_FUNC, API_RAND)), ("curand_Philox4x32_10", ("hiprand_Philox4x32_10", CONV_DEVICE_FUNC, API_RAND, HIP_UNSUPPORTED)), ("mtgp32_kernel_params", ("mtgp32_kernel_params_t", CONV_MATH_FUNC, API_RAND)), ("CUFFT_FORWARD", ("HIPFFT_FORWARD", CONV_NUMERIC_LITERAL, API_BLAS)), ("CUFFT_INVERSE", ("HIPFFT_BACKWARD", CONV_NUMERIC_LITERAL, API_BLAS)), ("CUFFT_COMPATIBILITY_DEFAULT", ("HIPFFT_COMPATIBILITY_DEFAULT", CONV_NUMERIC_LITERAL, API_BLAS, HIP_UNSUPPORTED)), ("cufftResult_t", ("hipfftResult_t", CONV_TYPE, API_FFT)), ("cufftResult", ("hipfftResult", CONV_TYPE, API_FFT)), ("CUFFT_SUCCESS", ("HIPFFT_SUCCESS", CONV_NUMERIC_LITERAL, API_FFT)), ("CUFFT_INVALID_PLAN", ("HIPFFT_INVALID_PLAN", CONV_NUMERIC_LITERAL, API_FFT)), ("CUFFT_ALLOC_FAILED", ("HIPFFT_ALLOC_FAILED", CONV_NUMERIC_LITERAL, API_FFT)), ("CUFFT_INVALID_TYPE", ("HIPFFT_INVALID_TYPE", CONV_NUMERIC_LITERAL, API_FFT)), ("CUFFT_INVALID_VALUE", ("HIPFFT_INVALID_VALUE", CONV_NUMERIC_LITERAL, API_FFT)), ("CUFFT_INTERNAL_ERROR", ("HIPFFT_INTERNAL_ERROR", CONV_NUMERIC_LITERAL, API_FFT)), ("CUFFT_EXEC_FAILED", ("HIPFFT_EXEC_FAILED", CONV_NUMERIC_LITERAL, API_FFT)), ("CUFFT_SETUP_FAILED", ("HIPFFT_SETUP_FAILED", CONV_NUMERIC_LITERAL, API_FFT)), ("CUFFT_INVALID_SIZE", ("HIPFFT_INVALID_SIZE", CONV_NUMERIC_LITERAL, API_FFT)), ("CUFFT_UNALIGNED_DATA", ("HIPFFT_UNALIGNED_DATA", CONV_NUMERIC_LITERAL, API_FFT)), ("CUFFT_INCOMPLETE_PARAMETER_LIST", ("HIPFFT_INCOMPLETE_PARAMETER_LIST", CONV_NUMERIC_LITERAL, API_FFT)), ("CUFFT_INVALID_DEVICE", ("HIPFFT_INVALID_DEVICE", CONV_NUMERIC_LITERAL, API_FFT)), ("CUFFT_PARSE_ERROR", ("HIPFFT_PARSE_ERROR", CONV_NUMERIC_LITERAL, API_FFT)), ("CUFFT_NO_WORKSPACE", ("HIPFFT_NO_WORKSPACE", CONV_NUMERIC_LITERAL, API_FFT)), ("CUFFT_NOT_IMPLEMENTED", ("HIPFFT_NOT_IMPLEMENTED", CONV_NUMERIC_LITERAL, API_FFT)), ("CUFFT_LICENSE_ERROR", ("HIPFFT_LICENSE_ERROR", CONV_NUMERIC_LITERAL, API_FFT, HIP_UNSUPPORTED)), ("CUFFT_NOT_SUPPORTED", ("HIPFFT_NOT_SUPPORTED", CONV_NUMERIC_LITERAL, API_FFT)), ("cufftType_t", ("hipfftType_t", CONV_TYPE, API_FFT)), ("cufftType", ("hipfftType", CONV_TYPE, API_FFT)), ("CUFFT_R2C", ("HIPFFT_R2C", CONV_NUMERIC_LITERAL, API_FFT)), ("CUFFT_C2R", ("HIPFFT_C2R", CONV_NUMERIC_LITERAL, API_FFT)), ("CUFFT_C2C", ("HIPFFT_C2C", CONV_NUMERIC_LITERAL, API_FFT)), ("CUFFT_D2Z", ("HIPFFT_D2Z", CONV_NUMERIC_LITERAL, API_FFT)), ("CUFFT_Z2D", ("HIPFFT_Z2D", CONV_NUMERIC_LITERAL, API_FFT)), ("CUFFT_Z2Z", ("HIPFFT_Z2Z", CONV_NUMERIC_LITERAL, API_FFT)), ("cufftCompatibility_t", ("hipfftCompatibility_t", CONV_TYPE, API_FFT, HIP_UNSUPPORTED)), ("cufftCompatibility", ("hipfftCompatibility", CONV_TYPE, API_FFT, HIP_UNSUPPORTED)), ("CUFFT_COMPATIBILITY_FFTW_PADDING", ("HIPFFT_COMPATIBILITY_FFTW_PADDING", CONV_NUMERIC_LITERAL, API_FFT, HIP_UNSUPPORTED)), ("cufftReal", ("hipfftReal", CONV_TYPE, API_FFT)), ("cufftDoubleReal", ("hipfftDoubleReal", CONV_TYPE, API_FFT)), ("cufftComplex", ("hipfftComplex", CONV_TYPE, API_FFT)), ("cufftDoubleComplex", ("hipfftDoubleComplex", CONV_TYPE, API_FFT)), ("cufftHandle", ("hipfftHandle", CONV_TYPE, API_FFT)), ("cufftPlan1d", ("hipfftPlan1d", CONV_MATH_FUNC, API_FFT)), ("cufftPlan2d", ("hipfftPlan2d", CONV_MATH_FUNC, API_FFT)), ("cufftPlan3d", ("hipfftPlan3d", CONV_MATH_FUNC, API_FFT)), ("cufftPlanMany", ("hipfftPlanMany", CONV_MATH_FUNC, API_FFT)), ("cufftMakePlan1d", ("hipfftMakePlan1d", CONV_MATH_FUNC, API_FFT)), ("cufftMakePlan2d", ("hipfftMakePlan2d", CONV_MATH_FUNC, API_FFT)), ("cufftMakePlan3d", ("hipfftMakePlan3d", CONV_MATH_FUNC, API_FFT)), ("cufftMakePlanMany", ("hipfftMakePlanMany", CONV_MATH_FUNC, API_FFT)), ("cufftMakePlanMany64", ("hipfftMakePlanMany64", CONV_MATH_FUNC, API_FFT)), ("cufftGetSizeMany64", ("hipfftGetSizeMany64", CONV_MATH_FUNC, API_FFT)), ("cufftEstimate1d", ("hipfftEstimate1d", CONV_MATH_FUNC, API_FFT)), ("cufftEstimate2d", ("hipfftEstimate2d", CONV_MATH_FUNC, API_FFT)), ("cufftEstimate3d", ("hipfftEstimate3d", CONV_MATH_FUNC, API_FFT)), ("cufftEstimateMany", ("hipfftEstimateMany", CONV_MATH_FUNC, API_FFT)), ("cufftCreate", ("hipfftCreate", CONV_MATH_FUNC, API_FFT)), ("cufftGetSize1d", ("hipfftGetSize1d", CONV_MATH_FUNC, API_FFT)), ("cufftGetSize2d", ("hipfftGetSize2d", CONV_MATH_FUNC, API_FFT)), ("cufftGetSize3d", ("hipfftGetSize3d", CONV_MATH_FUNC, API_FFT)), ("cufftGetSizeMany", ("hipfftGetSizeMany", CONV_MATH_FUNC, API_FFT)), ("cufftGetSize", ("hipfftGetSize", CONV_MATH_FUNC, API_FFT)), ("cufftSetWorkArea", ("hipfftSetWorkArea", CONV_MATH_FUNC, API_FFT)), ("cufftSetAutoAllocation", ("hipfftSetAutoAllocation", CONV_MATH_FUNC, API_FFT)), ("cufftExecC2C", ("hipfftExecC2C", CONV_MATH_FUNC, API_FFT)), ("cufftExecR2C", ("hipfftExecR2C", CONV_MATH_FUNC, API_FFT)), ("cufftExecC2R", ("hipfftExecC2R", CONV_MATH_FUNC, API_FFT)), ("cufftExecZ2Z", ("hipfftExecZ2Z", CONV_MATH_FUNC, API_FFT)), ("cufftExecD2Z", ("hipfftExecD2Z", CONV_MATH_FUNC, API_FFT)), ("cufftExecZ2D", ("hipfftExecZ2D", CONV_MATH_FUNC, API_FFT)), ("cufftSetStream", ("hipfftSetStream", CONV_MATH_FUNC, API_FFT)), ("cufftDestroy", ("hipfftDestroy", CONV_MATH_FUNC, API_FFT)), ("cufftGetVersion", ("hipfftGetVersion", CONV_MATH_FUNC, API_FFT)), ("cufftGetProperty", ("hipfftGetProperty", CONV_MATH_FUNC, API_FFT, HIP_UNSUPPORTED)), ]) CUDA_SPARSE_MAP = collections.OrderedDict([ ("cusparseStatus_t", ("hipsparseStatus_t", CONV_MATH_FUNC, API_SPARSE)), ("cusparseHandle_t", ("hipsparseHandle_t", CONV_MATH_FUNC, API_SPARSE)), ("cusparseOperation_t", ("hipsparseOperation_t", CONV_TYPE, API_SPARSE)), ("cusparseCreateMatDescr", ("hipsparseCreateMatDescr", CONV_MATH_FUNC, API_SPARSE)), ("cusparseCreate", ("hipsparseCreate", CONV_MATH_FUNC, API_SPARSE)), ("cusparseDestroyMatDescr", ("hipsparseDestroyMatDescr", CONV_MATH_FUNC, API_SPARSE)), ("cusparseDestroy", ("hipsparseDestroy", CONV_MATH_FUNC, API_SPARSE)), ("cusparseXcoo2csr", ("hipsparseXcoo2csr", CONV_MATH_FUNC, API_SPARSE)), ("cusparseMatDescr_t", ("hipsparseMatDescr_t", CONV_MATH_FUNC, API_SPARSE)), ("cusparseScsrmm2", ("hipsparseScsrmm2", CONV_MATH_FUNC, API_SPARSE)), ("cusparseDcsrmm2", ("hipsparseDcsrmm2", CONV_MATH_FUNC, API_SPARSE)), ("cusparseScsrmm", ("hipsparseScsrmm", CONV_MATH_FUNC, API_SPARSE)), ("cusparseDcsrmm", ("hipsparseDcsrmm", CONV_MATH_FUNC, API_SPARSE)), ("cusparseXcsrsort_bufferSizeExt", ("hipsparseXcsrsort_bufferSizeExt", CONV_MATH_FUNC, API_SPARSE)), ("cusparseXcsrsort", ("hipsparseXcsrsort", CONV_MATH_FUNC, API_SPARSE)), ("cusparseXcoosort_bufferSizeExt", ("hipsparseXcoosort_bufferSizeExt", CONV_MATH_FUNC, API_SPARSE)), ("cusparseXcoosortByRow", ("hipsparseXcoosortByRow", CONV_MATH_FUNC, API_SPARSE)), ("cusparseSetStream", ("hipsparseSetStream", CONV_MATH_FUNC, API_SPARSE)), ("cusparseCreateIdentityPermutation", ("hipsparseCreateIdentityPermutation", CONV_MATH_FUNC, API_SPARSE)), ("cusparseSetMatIndexBase", ("hipsparseSetMatIndexBase", CONV_MATH_FUNC, API_SPARSE)), ("cusparseSetMatType", ("hipsparseSetMatType", CONV_MATH_FUNC, API_SPARSE)), ("CUSPARSE_STATUS_SUCCESS", ("HIPSPARSE_STATUS_SUCCESS", CONV_NUMERIC_LITERAL, API_SPARSE)), ("CUSPARSE_STATUS_NOT_INITIALIZED", ("HIPSPARSE_STATUS_NOT_INITIALIZED", CONV_NUMERIC_LITERAL, API_SPARSE)), ("CUSPARSE_STATUS_ALLOC_FAILED", ("HIPSPARSE_STATUS_ALLOC_FAILED", CONV_NUMERIC_LITERAL, API_SPARSE)), ("CUSPARSE_STATUS_INVALID_VALUE", ("HIPSPARSE_STATUS_INVALID_VALUE", CONV_NUMERIC_LITERAL, API_SPARSE)), ("CUSPARSE_STATUS_MAPPING_ERROR", ("HIPSPARSE_STATUS_MAPPING_ERROR", CONV_NUMERIC_LITERAL, API_SPARSE)), ("CUSPARSE_STATUS_EXECUTION_FAILED", ("HIPSPARSE_STATUS_EXECUTION_FAILED", CONV_NUMERIC_LITERAL, API_SPARSE)), ("CUSPARSE_STATUS_INTERNAL_ERROR", ("HIPSPARSE_STATUS_INTERNAL_ERROR", CONV_NUMERIC_LITERAL, API_SPARSE)), ("CUSPARSE_STATUS_MATRIX_TYPE_NOT_SUPPORTED", ("HIPSPARSE_STATUS_MATRIX_TYPE_NOT_SUPPORTED", CONV_NUMERIC_LITERAL, API_SPARSE)), ("CUSPARSE_STATUS_ARCH_MISMATCH", ("HIPSPARSE_STATUS_ARCH_MISMATCH", CONV_NUMERIC_LITERAL, API_SPARSE)), ("CUSPARSE_STATUS_ZERO_PIVOT", ("HIPSPARSE_STATUS_ZERO_PIVOT", CONV_NUMERIC_LITERAL, API_SPARSE)), ("CUSPARSE_OPERATION_TRANSPOSE", ("HIPSPARSE_OPERATION_TRANSPOSE", CONV_NUMERIC_LITERAL, API_SPARSE)), ("CUSPARSE_OPERATION_NON_TRANSPOSE", ("HIPSPARSE_OPERATION_NON_TRANSPOSE", CONV_NUMERIC_LITERAL, API_SPARSE)), ("CUSPARSE_OPERATION_CONJUGATE_TRANSPOSE", ("HIPSPARSE_OPERATION_CONJUGATE_TRANSPOSE", CONV_NUMERIC_LITERAL, API_SPARSE)), ("CUSPARSE_INDEX_BASE_ZERO", ("HIPSPARSE_INDEX_BASE_ZERO", CONV_NUMERIC_LITERAL, API_SPARSE)), ("CUSPARSE_INDEX_BASE_ONE", ("HIPSPARSE_INDEX_BASE_ONE", CONV_NUMERIC_LITERAL, API_SPARSE)), ("CUSPARSE_MATRIX_TYPE_GENERAL", ("HIPSPARSE_MATRIX_TYPE_GENERAL", CONV_NUMERIC_LITERAL, API_SPARSE)), ]) PYTORCH_SPECIFIC_MAPPINGS = collections.OrderedDict([ ("cudaHostAllocator", ("hipHostAllocator", API_PYTORCH)), ("cudaDeviceAllocator", ("hipDeviceAllocator", API_PYTORCH)), ("define MAX_NUM_BLOCKS 200", ("define MAX_NUM_BLOCKS 64", API_PYTORCH)), ("cuda::CUDAGuard", ("hip::HIPGuardMasqueradingAsCUDA", API_PYTORCH)), ("CUDAGuard", ("HIPGuardMasqueradingAsCUDA", API_PYTORCH)), ("cuda::OptionalCUDAGuard", ("hip::OptionalHIPGuardMasqueradingAsCUDA", API_PYTORCH)), ("OptionalCUDAGuard", ("OptionalHIPGuardMasqueradingAsCUDA", API_PYTORCH)), ("cuda::CUDAStreamGuard", ("hip::HIPStreamGuardMasqueradingAsCUDA", API_PYTORCH)), ("CUDAStreamGuard", ("HIPStreamGuardMasqueradingAsCUDA", API_PYTORCH)), ("cuda::OptionalCUDAStreamGuard", ("hip::OptionalHIPStreamGuardMasqueradingAsCUDA", API_PYTORCH)), ("OptionalCUDAStreamGuard", ("OptionalHIPStreamGuardMasqueradingAsCUDA", API_PYTORCH)), # Only get needs to be transformed this way; all the other ones can go # straight to the normal versions hip::HIPCachingAllocator ("cuda::CUDACachingAllocator::get", ("hip::HIPCachingAllocatorMasqueradingAsCUDA::get", API_PYTORCH)), ("CUDACachingAllocator::get", ("HIPCachingAllocatorMasqueradingAsCUDA::get", API_PYTORCH)), ("cuda::CUDACachingAllocator::recordStream", ("hip::HIPCachingAllocatorMasqueradingAsCUDA::recordStreamMasqueradingAsCUDA", API_PYTORCH)), ("CUDACachingAllocator::recordStream", ("HIPCachingAllocatorMasqueradingAsCUDA::recordStreamMasqueradingAsCUDA", API_PYTORCH)), ("cuda::CUDAStream", ("hip::HIPStreamMasqueradingAsCUDA", API_PYTORCH)), ("CUDAStream", ("HIPStreamMasqueradingAsCUDA", API_PYTORCH)), ("cuda::getStreamFromPool", ("hip::getStreamFromPoolMasqueradingAsCUDA", API_PYTORCH)), ("getStreamFromPool", ("getStreamFromPoolMasqueradingAsCUDA", API_PYTORCH)), ("cuda::getDefaultCUDAStream", ("hip::getDefaultHIPStreamMasqueradingAsCUDA", API_PYTORCH)), ("getDefaultCUDAStream", ("getDefaultHIPStreamMasqueradingAsCUDA", API_PYTORCH)), ("cuda::getCurrentCUDAStream", ("hip::getCurrentHIPStreamMasqueradingAsCUDA", API_PYTORCH)), ("getCurrentCUDAStream", ("getCurrentHIPStreamMasqueradingAsCUDA", API_PYTORCH)), ("cuda::setCurrentCUDAStream", ("hip::setCurrentHIPStreamMasqueradingAsCUDA", API_PYTORCH)), ("setCurrentCUDAStream", ("setCurrentHIPStreamMasqueradingAsCUDA", API_PYTORCH)), # TODO: Undo this special-case; see the header for motivation behind this # hack. It's VERY important this is only applied to PyTorch HIPify. ("c10/cuda/CUDAGuard.h", ("ATen/hip/impl/HIPGuardImplMasqueradingAsCUDA.h", API_PYTORCH)), ("c10/cuda/CUDACachingAllocator.h", ("ATen/hip/impl/HIPCachingAllocatorMasqueradingAsCUDA.h", API_PYTORCH)), ("c10/cuda/CUDAStream.h", ("ATen/hip/impl/HIPStreamMasqueradingAsCUDA.h", API_PYTORCH)), ]) CAFFE2_SPECIFIC_MAPPINGS = collections.OrderedDict([ ("cuda_stream" , ("hip_stream", API_CAFFE2)), # if the header is a native hip folder (under hip directory), # there is no need to add a hip path to it; the trie in hipify script # takes this mapping order to forbid further replacement ("/hip/" , ("/hip/", API_CAFFE2)), ("/context_gpu" , ("/hip/context_gpu", API_CAFFE2)), ("/common_gpu" , ("/hip/common_gpu", API_CAFFE2)), ("/mixed_utils" , ("/hip/mixed_utils", API_CAFFE2)), ("/operator_fallback_gpu" , ("/hip/operator_fallback_gpu", API_CAFFE2)), ("/spatial_batch_norm_op_impl" , ("/hip/spatial_batch_norm_op_impl", API_CAFFE2)), ("/recurrent_network_executor_gpu" , ("/hip/recurrent_network_executor_gpu", API_CAFFE2)), ("/generate_proposals_op_util_nms_gpu" , ("/hip/generate_proposals_op_util_nms_gpu", API_CAFFE2)), ("/max_pool_with_index_gpu", ("/hip/max_pool_with_index_gpu", API_CAFFE2)), ("/THCCachingAllocator_gpu", ("/hip/THCCachingAllocator_gpu", API_CAFFE2)), ("/top_k_heap_selection", ("/hip/top_k_heap_selection", API_CAFFE2)), ("/top_k_radix_selection", ("/hip/top_k_radix_selection", API_CAFFE2)), ("/GpuDefs", ("/hip/GpuDefs", API_CAFFE2)), ("/GpuScanUtils", ("/hip/GpuScanUtils", API_CAFFE2)), ("/GpuBitonicSort", ("/hip/GpuBitonicSort", API_CAFFE2)), ("/math/reduce.cuh", ("/math/hip/reduce.cuh", API_CAFFE2)), ("/gather_op.cuh", ("/hip/gather_op.cuh", API_CAFFE2)), ("caffe2/core/common_cudnn.h", ("caffe2/core/hip/common_miopen.h", API_CAFFE2)), ("REGISTER_CUDA_OPERATOR" , ("REGISTER_HIP_OPERATOR", API_CAFFE2)), ("CUDA_1D_KERNEL_LOOP" , ("HIP_1D_KERNEL_LOOP", API_CAFFE2)), ("CUDAContext" , ("HIPContext", API_CAFFE2)), ("CAFFE_CUDA_NUM_THREADS" , ("CAFFE_HIP_NUM_THREADS", API_CAFFE2)), ("HasCudaGPU" , ("HasHipGPU", API_CAFFE2)), ("__expf" , ("expf", API_CAFFE2)), ("CUBLAS_ENFORCE" , ("ROCBLAS_ENFORCE", API_CAFFE2)), ("CUBLAS_CHECK" , ("ROCBLAS_CHECK", API_CAFFE2)), ("cublas_handle" , ("rocblashandle", API_CAFFE2)), ("CURAND_ENFORCE" ,("HIPRAND_ENFORCE", API_CAFFE2)), ("CURAND_CHECK" ,("HIPRAND_CHECK", API_CAFFE2)), ("curandGenerateUniform" , ("hiprandGenerateUniform", API_CAFFE2)), ("curand_generator" , ("hiprand_generator", API_CAFFE2)), ("CaffeCudaGetDevice" , ("CaffeHipGetDevice", API_CAFFE2)), ("CUDA" ,("HIP", API_CAFFE2)), ("Cuda" ,("Hip", API_CAFFE2)), ("cuda_" ,("hip_", API_CAFFE2)), ("_cuda" ,("_hip", API_CAFFE2)), ("CUDNN" ,("MIOPEN", API_CAFFE2)), ("CuDNN" ,("MIOPEN", API_CAFFE2)), ("cudnn" ,("miopen", API_CAFFE2)), ("namespace cuda", ("namespace hip", API_CAFFE2)), ("cuda::CUDAGuard", ("hip::HIPGuard", API_CAFFE2)), ("cuda::OptionalCUDAGuard", ("hip::OptionalHIPGuard", API_CAFFE2)), ("cuda::CUDAStreamGuard", ("hip::HIPStreamGuard", API_CAFFE2)), ("cuda::OptionalCUDAStreamGuard", ("hip::OptionalHIPStreamGuard", API_CAFFE2)), ("c10/cuda/CUDAGuard.h", ("c10/hip/HIPGuard.h", API_CAFFE2)), ]) # We must tread very carefully here. Blanket conversions like are done # in CAFFE2_SPECIFIC_MAPPINGS are not presently supported on PyTorch, # because a regex for CUDA will also match a filename like CUDAGuard.h, # but the HIPIFY script doesn't presently move the file and so the substitution # will be invalid. Instead, we specifically list out every identifier # and file from c10/cuda which may be used externally, and do substitutions this # way. # # NB: if you want a transformation to ONLY apply to the c10/ directory, # put it as API_CAFFE2 C10_MAPPINGS = collections.OrderedDict([ ("cuda::compat::", ("hip::compat::", API_C10)), ("c10/cuda/CUDAException.h", ("c10/hip/HIPException.h", API_C10)), ("c10/cuda/CUDAMacros.h", ("c10/hip/HIPMacros.h", API_C10)), ("c10/cuda/CUDAMathCompat.h", ("c10/hip/HIPMathCompat.h", API_C10)), ("c10/cuda/CUDAFunctions.h", ("c10/hip/HIPFunctions.h", API_C10)), ("c10/cuda/CUDAStream.h", ("c10/hip/HIPStream.h", API_C10)), ("c10/cuda/CUDACachingAllocator.h", ("c10/hip/HIPCachingAllocator.h", API_C10)), ("c10/cuda/impl/CUDATest.h", ("c10/hip/impl/HIPTest.h", API_C10)), ("c10/cuda/impl/CUDAGuardImpl.h", ("c10/hip/impl/HIPGuardImpl.h", API_C10)), ("c10/cuda/impl/cuda_cmake_macros.h", ("c10/hip/impl/hip_cmake_macros.h", API_C10)), ("C10_CUDA_CHECK", ("C10_HIP_CHECK", API_C10)), ("c10::cuda", ("c10::hip", API_C10)), ("cuda::CUDAStream", ("hip::HIPStream", API_C10)), ("CUDAStream", ("HIPStream", API_C10)), # This substitution is not permissible, because there's another copy of this # function in torch/cuda.h # ("cuda::device_count", ("hip::device_count", API_C10)), ("cuda::current_device", ("hip::current_device", API_C10)), ("cuda::set_device", ("hip::set_device", API_C10)), ("cuda::getStreamFromPool", ("hip::getStreamFromPool", API_C10)), ("getStreamFromPool", ("getStreamFromPool", API_C10)), ("cuda::getDefaultCUDAStream", ("hip::getDefaultHIPStream", API_C10)), ("getDefaultCUDAStream", ("getDefaultHIPStream", API_C10)), ("cuda::getCurrentCUDAStream", ("hip::getCurrentHIPStream", API_C10)), ("getCurrentCUDAStream", ("getCurrentHIPStream", API_C10)), ("cuda::setCurrentCUDAStream", ("hip::setCurrentHIPStream", API_C10)), ("setCurrentCUDAStream", ("setCurrentHIPStream", API_C10)), ("cuda::CUDACachingAllocator", ("hip::HIPCachingAllocator", API_C10)), ("CUDACachingAllocator", ("HIPCachingAllocator", API_C10)), ]) # NB: C10 mappings are more specific than Caffe2 mappings, so run them # first CUDA_TO_HIP_MAPPINGS = [CUDA_IDENTIFIER_MAP, CUDA_TYPE_NAME_MAP, CUDA_INCLUDE_MAP, CUDA_SPARSE_MAP, C10_MAPPINGS, PYTORCH_SPECIFIC_MAPPINGS, CAFFE2_SPECIFIC_MAPPINGS]
5a083a5caacded4d0503d61b1eed6d0a6b641e29
0cf6728548830b42c60e37ea1c38b54d0e019ddd
/Learning_Quant/python金融大数据挖掘与分析全流程详解/chapter12.py
05cc6faabfc1d70c38f3d38fc05b14eb7a328704
[]
no_license
MuSaCN/PythonLearning
8efe166f66f2bd020d00b479421878d91f580298
507f1d82a9228d0209c416626566cf390e1cf758
refs/heads/master
2022-11-11T09:13:08.863712
2022-11-08T04:20:09
2022-11-08T04:20:09
299,617,217
2
2
null
null
null
null
UTF-8
Python
false
false
2,889
py
# Author:Zhang Yuan from MyPackage import * import numpy as np import pandas as pd import matplotlib.pyplot as plt import matplotlib.patches as patches import seaborn as sns import statsmodels.api as sm from scipy import stats #------------------------------------------------------------ __mypath__ = MyPath.MyClass_Path("\\python金融大数据挖掘与分析全流程详解") # 路径类 myfile = MyFile.MyClass_File() # 文件操作类 mytime = MyTime.MyClass_Time() # 时间类 myplt = MyPlot.MyClass_Plot() # 直接绘图类(单个图窗) mypltpro = MyPlot.MyClass_PlotPro() # Plot高级图系列 myfig = MyPlot.MyClass_Figure(AddFigure=False) # 对象式绘图类(可多个图窗) myfigpro = MyPlot.MyClass_FigurePro(AddFigure=False) # Figure高级图系列 mynp = MyArray.MyClass_NumPy() # 多维数组类(整合Numpy) mypd = MyArray.MyClass_Pandas() # 矩阵数组类(整合Pandas) mypdpro = MyArray.MyClass_PandasPro() # 高级矩阵数组类 myDA = MyDataAnalysis.MyClass_DataAnalysis() # 数据分析类 # myMql = MyMql.MyClass_MqlBackups() # Mql备份类 # myMT5 = MyMql.MyClass_ConnectMT5(connect=False) # Python链接MetaTrader5客户端类 # myDefault = MyDefault.MyClass_Default_Matplotlib() # matplotlib默认设置 # myBaidu = MyWebCrawler.MyClass_BaiduPan() # Baidu网盘交互类 # myImage = MyImage.MyClass_ImageProcess() # 图片处理类 myBT = MyBackTest.MyClass_BackTestEvent() # 事件驱动型回测类 myBTV = MyBackTest.MyClass_BackTestVector() # 向量型回测类 myML = MyMachineLearning.MyClass_MachineLearning() # 机器学习综合类 mySQL = MyDataBase.MyClass_MySQL(connect=False) # MySQL类 myWebQD = MyWebCrawler.MyClass_QuotesDownload(tushare=False) # 金融行情下载类 myWebR = MyWebCrawler.MyClass_Requests() # Requests爬虫类 myWebS = MyWebCrawler.MyClass_Selenium(openChrome=False) # Selenium模拟浏览器类 myWebAPP = MyWebCrawler.MyClass_APPIntegration() # 爬虫整合应用类 myEmail = MyWebCrawler.MyClass_Email() # 邮箱交互类 myReportA = MyQuant.MyClass_ReportAnalysis() # 研报分析类 #------------------------------------------------------------ # 12.1.1-1 requests库下载文件 url = 'http://images.china-pub.com/ebook8055001-8060000/8057968/shupi.jpg' myWebR.download(url,"pic.jpg") # 12.1.1-2 通过pandas获取表格 url = 'http://vip.stock.finance.sina.com.cn/q/go.php/vInvestConsult/kind/dzjy/index.phtml' # 新浪财经数据中心提供股票大宗交易的在线表格 myWebAPP.read_html(url,to_excel="测试.xlsx") # 12.1.2 和讯研报网表格获取 table = myWebAPP.hexun_yanbao_stock(ybsj_index=5,to_page=1,to_excel=None) # ---分析和讯研报数据_券商评级调升股: page_or_read = 5爬取网站 / "*.xlsx"读取;lengths代表时长,[10,20]则表示10、20天前;path为仅路径 myReportA.hexun_broker_buy_analysis(page_or_excel=2,lengths=[10,20,30],path="")
952864ce7904fc1199cb55db3743982e823bc1c3
1b461ec82c8dd1099021ce3a32a7f649fa970226
/Exercises/warm_up_bar_coding_string_match.py
4a3a9d80d11b210caf26c8c7eb8bcb83eb67f669
[]
no_license
AdamSierzan/Learn-to-code-in-Python-3-basics
9df20c80c33f40da8800d257ee2ec05881198419
ef298bcba72250e19080283cb81dbecf6a245563
refs/heads/master
2022-11-06T00:48:17.413322
2020-06-16T20:52:08
2020-06-16T20:52:08
250,247,475
0
0
null
null
null
null
UTF-8
Python
false
false
116
py
#def string_match(a, b): a = "xxcaazz" b = 'xxbaaz' for i in (len(a)): print(i,a[+1]) print(a[0],a[1])
fb63f6ee8a057a30027089c59c6d5ccb87cc6dc9
facb8b9155a569b09ba66aefc22564a5bf9cd319
/wp2/kikoAnalysis/slpDailyMeanFiles/43-tideGauge.py
4657f7de0acc7b31a05efa28139e82d5dd1442be
[]
no_license
moinabyssinia/modeling-global-storm-surges
13e69faa8f45a1244a964c5de4e2a5a6c95b2128
6e385b2a5f0867df8ceabd155e17ba876779c1bd
refs/heads/master
2023-06-09T00:40:39.319465
2021-06-25T21:00:44
2021-06-25T21:00:44
229,080,191
0
0
null
null
null
null
UTF-8
Python
false
false
1,411
py
# -*- coding: utf-8 -*- """ Created on Tue Sep 29 09:40:12 2020 @author: Michael Tadesse """ import os import pandas as pd dir_in = "/lustre/fs0/home/mtadesse/eraFiveConcat" dir_out = "/lustre/fs0/home/mtadesse/dailyPred" os.chdir(dir_in) tgList = os.listdir() x = 43 y = 44 #looping through individual tide gauges for ii in range(x, y): os.chdir(tgList[ii]) #load file slp = pd.read_csv('slp.csv') slp.drop(['Unnamed: 0', 'Unnamed: 0.1'], axis = 1, inplace = True) #sort by date slp = slp.sort_values(by = 'date') #reset indices slp.reset_index(inplace = True) slp.drop(['index'], axis = 1, inplace = True) #get daily time steps getDays = lambda x: x.split()[0] slp['days'] = pd.DataFrame(list(map(getDays, slp['date']))) #get unique days days = slp['days'].unique() first = True for d in days: currentDay = slp[slp['days'] == d] print(currentDay) if first: currentMean = pd.DataFrame(currentDay.mean(axis = 0)).T currentMean['date'] = d first = False dailyMean = currentMean else: currentMean = pd.DataFrame(currentDay.mean(axis = 0)).T currentMean['date'] = d dailyMean = pd.concat([dailyMean, currentMean], axis = 0) dailyMean.to_csv('slpDaily.csv')
73f7923b5825d9bf1260499fa1cc901620659557
f82757475ea13965581c2147ff57123b361c5d62
/gi-stubs/repository/Gio/UnixInputStreamClass.py
83dcff9394d0a3fa7e5dbf2594bcb42187c4ab48
[]
no_license
ttys3/pygobject-stubs
9b15d1b473db06f47e5ffba5ad0a31d6d1becb57
d0e6e93399212aada4386d2ce80344eb9a31db48
refs/heads/master
2022-09-23T12:58:44.526554
2020-06-06T04:15:00
2020-06-06T04:15:00
269,693,287
8
2
null
2020-06-05T15:57:54
2020-06-05T15:57:54
null
UTF-8
Python
false
false
5,125
py
# encoding: utf-8 # module gi.repository.Gio # from /usr/lib64/girepository-1.0/Gio-2.0.typelib # by generator 1.147 # no doc # imports import gi as __gi import gi.overrides as __gi_overrides import gi.overrides.Gio as __gi_overrides_Gio import gi.overrides.GObject as __gi_overrides_GObject import gi.repository.GObject as __gi_repository_GObject import gobject as __gobject class UnixInputStreamClass(__gi.Struct): """ :Constructors: :: UnixInputStreamClass() """ def __delattr__(self, *args, **kwargs): # real signature unknown """ Implement delattr(self, name). """ pass def __dir__(self, *args, **kwargs): # real signature unknown """ Default dir() implementation. """ pass def __eq__(self, *args, **kwargs): # real signature unknown """ Return self==value. """ pass def __format__(self, *args, **kwargs): # real signature unknown """ Default object formatter. """ pass def __getattribute__(self, *args, **kwargs): # real signature unknown """ Return getattr(self, name). """ pass def __ge__(self, *args, **kwargs): # real signature unknown """ Return self>=value. """ pass def __gt__(self, *args, **kwargs): # real signature unknown """ Return self>value. """ pass def __hash__(self, *args, **kwargs): # real signature unknown """ Return hash(self). """ pass def __init_subclass__(self, *args, **kwargs): # real signature unknown """ This method is called when a class is subclassed. The default implementation does nothing. It may be overridden to extend subclasses. """ pass def __init__(self): # real signature unknown; restored from __doc__ pass def __le__(self, *args, **kwargs): # real signature unknown """ Return self<=value. """ pass def __lt__(self, *args, **kwargs): # real signature unknown """ Return self<value. """ pass @staticmethod # known case of __new__ def __new__(*args, **kwargs): # real signature unknown """ Create and return a new object. See help(type) for accurate signature. """ pass def __ne__(self, *args, **kwargs): # real signature unknown """ Return self!=value. """ pass def __reduce_ex__(self, *args, **kwargs): # real signature unknown """ Helper for pickle. """ pass def __reduce__(self, *args, **kwargs): # real signature unknown """ Helper for pickle. """ pass def __repr__(self, *args, **kwargs): # real signature unknown """ Return repr(self). """ pass def __setattr__(self, *args, **kwargs): # real signature unknown """ Implement setattr(self, name, value). """ pass def __sizeof__(self, *args, **kwargs): # real signature unknown """ Size of object in memory, in bytes. """ pass def __str__(self, *args, **kwargs): # real signature unknown """ Return str(self). """ pass def __subclasshook__(self, *args, **kwargs): # real signature unknown """ Abstract classes can override this to customize issubclass(). This is invoked early on by abc.ABCMeta.__subclasscheck__(). It should return True, False or NotImplemented. If it returns NotImplemented, the normal algorithm is used. Otherwise, it overrides the normal algorithm (and the outcome is cached). """ pass def __weakref__(self, *args, **kwargs): # real signature unknown pass parent_class = property(lambda self: object(), lambda self, v: None, lambda self: None) # default _g_reserved1 = property(lambda self: object(), lambda self, v: None, lambda self: None) # default _g_reserved2 = property(lambda self: object(), lambda self, v: None, lambda self: None) # default _g_reserved3 = property(lambda self: object(), lambda self, v: None, lambda self: None) # default _g_reserved4 = property(lambda self: object(), lambda self, v: None, lambda self: None) # default _g_reserved5 = property(lambda self: object(), lambda self, v: None, lambda self: None) # default __class__ = None # (!) real value is "<class 'gi.types.StructMeta'>" __dict__ = None # (!) real value is "mappingproxy({'__info__': StructInfo(UnixInputStreamClass), '__module__': 'gi.repository.Gio', '__gtype__': <GType void (4)>, '__dict__': <attribute '__dict__' of 'UnixInputStreamClass' objects>, '__weakref__': <attribute '__weakref__' of 'UnixInputStreamClass' objects>, '__doc__': None, 'parent_class': <property object at 0x7f4b87767d60>, '_g_reserved1': <property object at 0x7f4b87767e50>, '_g_reserved2': <property object at 0x7f4b87767f40>, '_g_reserved3': <property object at 0x7f4b8776b090>, '_g_reserved4': <property object at 0x7f4b8776b180>, '_g_reserved5': <property object at 0x7f4b8776b270>})" __gtype__ = None # (!) real value is '<GType void (4)>' __info__ = StructInfo(UnixInputStreamClass)
f27837e23b09a26eefdf2310dfb8b68e4031e84d
0822d36728e9ed1d4e91d8ee8b5ea39010ac9371
/robo/pages/mato_grosso_do_sul/jd1noticias.py
738245155ef16987361a670e3484ee9f0add3ad5
[]
no_license
diegothuran/blog
11161e6f425d08bf7689190eac0ca5bd7cb65dd7
233135a1db24541de98a7aeffd840cf51e5e462e
refs/heads/master
2022-12-08T14:03:02.876353
2019-06-05T17:57:55
2019-06-05T17:57:55
176,329,704
0
0
null
2022-12-08T04:53:02
2019-03-18T16:46:43
Python
UTF-8
Python
false
false
924
py
# coding: utf-8 import sys sys.path.insert(0, '../../../blog') from bs4 import BeautifulSoup import requests from robo.pages.util.constantes import PAGE_LIMIT GLOBAL_RANK = 1125849 RANK_BRAZIL = 31946 NAME = 'jd1noticias.com' def get_urls(): try: urls = [] for i in range(1, PAGE_LIMIT): link = 'http://www.jd1noticias.com/canal/ultimas-noticias/p/' + str(i) req = requests.get(link) noticias = BeautifulSoup(req.text, "html.parser").find_all('ul', class_='listNoticias listCanal') for lista in noticias: for noticia in lista: try: href = noticia.find_all('a', href=True)[0]['href'] urls.append(href) except: pass return urls except: raise Exception('Exception in jd1noticias')
299c3360d98aebb3d35976830345e1b5570228f7
5ae3bc1920fafc33693cdfa3928a48158aa6f725
/315/315-Segment.py
d49170abb3a3388d343616b67714c0002c5e9626
[]
no_license
sjzyjc/leetcode
2d0764aec6681d567bffd8ff9a8cc482c44336c2
5e09a5d36ac55d782628a888ad57d48e234b61ac
refs/heads/master
2021-04-03T08:26:38.232218
2019-08-15T21:54:59
2019-08-15T21:54:59
124,685,278
0
0
null
null
null
null
UTF-8
Python
false
false
2,317
py
class SegmentTreeNode: def __init__(self, start, end, val): self.start = start self.end = end self.val = val self.left = self.right = None class SegmentTree: def __init__(self, n): self.root = self.build(0, len(n) - 1, n) def build(self, start, end, n): if start > end: return None cur = SegmentTreeNode(start, end, n[start]) if start == end: return cur mid = (start + end) // 2 cur.left = self.build(start, mid, n) cur.right = self.build(mid + 1, end, n) if cur.left: cur.val = cur.left.val if cur.right: cur.val += cur.right.val return cur def query(self, root, start, end): if not root: return 0 if root.start == start and root.end == end: return root.val mid = (root.start + root.end) // 2 if end <= mid: return self.query(root.left, start, end) elif start > mid: return self.query(root.right, start, end) else: return self.query(root.left, start, mid) + self.query(root.right, mid+1, end) def update(self, root, index): if not root: return if root.start == root.end == index: root.val += 1 return mid = (root.start + root.end) // 2 if index <= mid: self.update(root.left, index) else: self.update(root.right, index) root.val = root.left.val + root.right.val class Solution(object): def countSmaller(self, nums): """ :type nums: List[int] :rtype: List[int] """ if not nums: return [] min_num = min(nums) size = max(nums) - min_num + 1 count = [0 for _ in range(size)] st = SegmentTree(count) ans = [] for index in range(len(nums) - 1, -1, -1): count_index = nums[index] - min_num st.update(st.root, count_index) ans.append(st.query(st.root, 0, count_index - 1)) return ans[::-1]
c9135d8bc839acb9df559e73377e0df9a5dc5901
edb10a06f56d9bd19b0b60581728900a03d9732a
/Python/leetcode/Anagrams.py
ca5c1a364909e0a69634540c9097753018bccfff
[ "MIT" ]
permissive
darrencheng0817/AlgorithmLearning
3ba19e6044bc14b0244d477903959730e9f9aaa8
aec1ddd0c51b619c1bae1e05f940d9ed587aa82f
refs/heads/master
2021-01-21T04:26:14.814810
2019-11-22T06:02:01
2019-11-22T06:02:01
47,100,767
2
0
null
null
null
null
UTF-8
Python
false
false
409
py
''' Created on 1.12.2016 @author: Darren '''''' Given an array of strings, group anagrams together. For example, given: ["eat", "tea", "tan", "ate", "nat", "bat"], Return: [ ["ate", "eat","tea"], ["nat","tan"], ["bat"] ] Note: For the return value, each inner list s elements must follow the lexicographic order. All inputs will be in lower-case. " '''
820d0141ddd1005770849d9e401f6a14435fbca5
80922ad42ea7232c8b3f3de8e7928aaf2142e13f
/mylar/PostProcessor.py
9a5b8d2fed0506d985e26ef04ee12c11f42fbf48
[]
no_license
rykerwilliams/mylar
d2db698580898952afd1e1a7f29dd58411b8d5c4
e64b50a3ffaf5ddb3f944576104a05e845016fec
refs/heads/master
2021-01-16T21:52:29.098345
2014-07-28T18:48:56
2014-07-28T18:48:56
null
0
0
null
null
null
null
UTF-8
Python
false
false
53,988
py
# This file is part of Mylar. # # Mylar is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Mylar is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Mylar. If not, see <http://www.gnu.org/licenses/>. from __future__ import with_statement import os import shutil import re import shlex import time import logging import mylar import subprocess import urllib2 import sqlite3 from xml.dom.minidom import parseString from mylar import logger, db, helpers, updater, notifiers, filechecker, weeklypull class PostProcessor(object): """ A class which will process a media file according to the post processing settings in the config. """ EXISTS_LARGER = 1 EXISTS_SAME = 2 EXISTS_SMALLER = 3 DOESNT_EXIST = 4 # IGNORED_FILESTRINGS = [ "" ] NZB_NAME = 1 FOLDER_NAME = 2 FILE_NAME = 3 def __init__(self, nzb_name, nzb_folder, module=None): """ Creates a new post processor with the given file path and optionally an NZB name. file_path: The path to the file to be processed nzb_name: The name of the NZB which resulted in this file being downloaded (optional) """ # absolute path to the folder that is being processed #self.folder_path = ek.ek(os.path.dirname, ek.ek(os.path.abspath, file_path)) # full path to file #self.file_path = file_path # file name only #self.file_name = ek.ek(os.path.basename, file_path) # the name of the folder only #self.folder_name = ek.ek(os.path.basename, self.folder_path) # name of the NZB that resulted in this folder self.nzb_name = nzb_name self.nzb_folder = nzb_folder if module is not None: self.module = module + '[POST-PROCESSING]' else: self.module = '[POST-PROCESSING]' #self.in_history = False #self.release_group = None #self.is_proper = False self.log = '' def _log(self, message, level=logger.message): #level=logger.MESSAGE): """ A wrapper for the internal logger which also keeps track of messages and saves them to a string for $ message: The string to log (unicode) level: The log level to use (optional) """ # logger.log(message, level) self.log += message + '\n' def _run_pre_scripts(self, nzb_name, nzb_folder, seriesmetadata): """ Executes any pre scripts defined in the config. ep_obj: The object to use when calling the pre script """ self._log("initiating pre script detection.") self._log("mylar.PRE_SCRIPTS : " + mylar.PRE_SCRIPTS) # for currentScriptName in mylar.PRE_SCRIPTS: currentScriptName = str(mylar.PRE_SCRIPTS).decode("string_escape") self._log("pre script detected...enabling: " + str(currentScriptName)) # generate a safe command line string to execute the script and provide all the parameters script_cmd = shlex.split(currentScriptName, posix=False) + [str(nzb_name), str(nzb_folder), str(seriesmetadata)] self._log("cmd to be executed: " + str(script_cmd)) # use subprocess to run the command and capture output self._log(u"Executing command "+str(script_cmd)) self._log(u"Absolute path to script: "+script_cmd[0]) try: p = subprocess.Popen(script_cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, cwd=mylar.PROG_DIR) out, err = p.communicate() #@UnusedVariable self._log(u"Script result: "+str(out)) except OSError, e: self._log(u"Unable to run pre_script: " + str(script_cmd)) def _run_extra_scripts(self, nzb_name, nzb_folder, filen, folderp, seriesmetadata): """ Executes any extra scripts defined in the config. ep_obj: The object to use when calling the extra script """ self._log("initiating extra script detection.") self._log("mylar.EXTRA_SCRIPTS : " + mylar.EXTRA_SCRIPTS) # for curScriptName in mylar.EXTRA_SCRIPTS: curScriptName = str(mylar.EXTRA_SCRIPTS).decode("string_escape") self._log("extra script detected...enabling: " + str(curScriptName)) # generate a safe command line string to execute the script and provide all the parameters script_cmd = shlex.split(curScriptName) + [str(nzb_name), str(nzb_folder), str(filen), str(folderp), str(seriesmetadata)] self._log("cmd to be executed: " + str(script_cmd)) # use subprocess to run the command and capture output self._log(u"Executing command "+str(script_cmd)) self._log(u"Absolute path to script: "+script_cmd[0]) try: p = subprocess.Popen(script_cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, cwd=mylar.PROG_DIR) out, err = p.communicate() #@UnusedVariable self._log(u"Script result: "+str(out)) except OSError, e: self._log(u"Unable to run extra_script: " + str(script_cmd)) def Process(self): module = self.module self._log("nzb name: " + str(self.nzb_name)) self._log("nzb folder: " + str(self.nzb_folder)) logger.fdebug(module + ' nzb name: ' + str(self.nzb_name)) logger.fdebug(module + ' nzb folder: ' + str(self.nzb_folder)) if mylar.USE_SABNZBD==0: logger.fdebug(module + ' Not using SABnzbd') elif mylar.USE_SABNZBD != 0 and self.nzb_name == 'Manual Run': logger.fdebug(module + ' Not using SABnzbd : Manual Run') else: # if the SAB Directory option is enabled, let's use that folder name and append the jobname. if mylar.SAB_DIRECTORY is not None and mylar.SAB_DIRECTORY is not 'None' and len(mylar.SAB_DIRECTORY) > 4: self.nzb_folder = os.path.join(mylar.SAB_DIRECTORY, self.nzb_name).encode(mylar.SYS_ENCODING) logger.fdebug(module + ' SABnzbd Download folder option enabled. Directory set to : ' + self.nzb_folder) # -- start. not used. #query SAB to find out if Replace Spaces enabled / not as well as Replace Decimals #http://localhost:8080/sabnzbd/api?mode=set_config&section=misc&keyword=dirscan_speed&value=5 #querysab = str(mylar.SAB_HOST) + "/api?mode=get_config&section=misc&output=xml&apikey=" + str(mylar.SAB_APIKEY) #logger.info("querysab_string:" + str(querysab)) #file = urllib2.urlopen(querysab) #data = file.read() #file.close() #dom = parseString(data) #try: # sabreps = dom.getElementsByTagName('replace_spaces')[0].firstChild.wholeText #except: # errorm = dom.getElementsByTagName('error')[0].firstChild.wholeText # logger.error(u"Error detected attempting to retrieve SAB data : " + errorm) # return #sabrepd = dom.getElementsByTagName('replace_dots')[0].firstChild.wholeText #logger.fdebug("SAB Replace Spaces: " + str(sabreps)) #logger.fdebug("SAB Replace Dots: " + str(sabrepd)) # -- end. not used. if mylar.USE_NZBGET==1: if self.nzb_name != 'Manual Run': logger.fdebug(module + ' Using NZBGET') logger.fdebug(module + ' NZB name as passed from NZBGet: ' + self.nzb_name) # if the NZBGet Directory option is enabled, let's use that folder name and append the jobname. if self.nzb_name == 'Manual Run': logger.fdebug(module + ' Manual Run Post-Processing enabled.') elif mylar.NZBGET_DIRECTORY is not None and mylar.NZBGET_DIRECTORY is not 'None' and len(mylar.NZBGET_DIRECTORY) > 4: self.nzb_folder = os.path.join(mylar.NZBGET_DIRECTORY, self.nzb_name).encode(mylar.SYS_ENCODING) logger.fdebug(module + ' NZBGET Download folder option enabled. Directory set to : ' + self.nzb_folder) myDB = db.DBConnection() if self.nzb_name == 'Manual Run': logger.fdebug (module + ' Manual Run initiated') #Manual postprocessing on a folder. #use the nzb_folder to determine every file #walk the dir, #once a series name and issue are matched, #write the series/issue/filename to a tuple #when all done, iterate over the tuple until completion... comicseries = myDB.select("SELECT * FROM comics") manual_list = [] if comicseries is None: logger.error(module + ' No Series in Watchlist - aborting Manual Post Processing. Maybe you should be running Import?') return else: ccnt=0 nm=0 watchvals = {} for cs in comicseries: watchvals = {"SeriesYear": cs['ComicYear'], "LatestDate": cs['LatestDate'], "ComicVersion": cs['ComicVersion'], "Publisher": cs['ComicPublisher'], "Total": cs['Total']} watchmatch = filechecker.listFiles(self.nzb_folder,cs['ComicName'],cs['ComicPublisher'],cs['AlternateSearch'], manual=watchvals) if watchmatch['comiccount'] == 0: # is None: nm+=1 continue else: fn = 0 fccnt = int(watchmatch['comiccount']) if len(watchmatch) == 1: continue while (fn < fccnt): try: tmpfc = watchmatch['comiclist'][fn] except IndexError,KeyError: break temploc= tmpfc['JusttheDigits'].replace('_', ' ') temploc = re.sub('[\#\']', '', temploc) if 'annual' in temploc.lower(): logger.info(module + ' Annual detected.') annchk = "yes" fcdigit = helpers.issuedigits(re.sub('annual', '', str(temploc.lower())).strip()) issuechk = myDB.selectone("SELECT * from annuals WHERE ComicID=? AND Int_IssueNumber=?", [cs['ComicID'],fcdigit]).fetchone() else: fcdigit = helpers.issuedigits(temploc) issuechk = myDB.selectone("SELECT * from issues WHERE ComicID=? AND Int_IssueNumber=?", [cs['ComicID'],fcdigit]).fetchone() if issuechk is None: logger.fdebug(module + ' No corresponding issue # found for ' + str(cs['ComicID'])) else: datematch = "True" if len(watchmatch) >= 1 and tmpfc['ComicYear'] is not None: #if the # of matches is more than 1, we need to make sure we get the right series #compare the ReleaseDate for the issue, to the found issue date in the filename. #if ReleaseDate doesn't exist, use IssueDate #if no issue date was found, then ignore. issyr = None #logger.fdebug('issuedate:' + str(issuechk['IssueDate'])) #logger.fdebug('issuechk: ' + str(issuechk['IssueDate'][5:7])) #logger.info('ReleaseDate: ' + str(issuechk['ReleaseDate'])) #logger.info('IssueDate: ' + str(issuechk['IssueDate'])) if issuechk['ReleaseDate'] is not None and issuechk['ReleaseDate'] != '0000-00-00': monthval = issuechk['ReleaseDate'] if int(issuechk['ReleaseDate'][:4]) < int(tmpfc['ComicYear']): logger.fdebug(module + ' ' + str(issuechk['ReleaseDate']) + ' is before the issue year of ' + str(tmpfc['ComicYear']) + ' that was discovered in the filename') datematch = "False" else: monthval = issuechk['IssueDate'] if int(issuechk['IssueDate'][:4]) < int(tmpfc['ComicYear']): logger.fdebug(module + ' ' + str(issuechk['IssueDate']) + ' is before the issue year ' + str(tmpfc['ComicYear']) + ' that was discovered in the filename') datematch = "False" if int(monthval[5:7]) == 11 or int(monthval[5:7]) == 12: issyr = int(monthval[:4]) + 1 logger.fdebug(module + ' IssueYear (issyr) is ' + str(issyr)) elif int(monthval[5:7]) == 1 or int(monthval[5:7]) == 2: issyr = int(monthval[:4]) - 1 if datematch == "False" and issyr is not None: logger.fdebug(module + ' ' + str(issyr) + ' comparing to ' + str(tmpfc['ComicYear']) + ' : rechecking by month-check versus year.') datematch = "True" if int(issyr) != int(tmpfc['ComicYear']): logger.fdebug(module + '[.:FAIL:.] Issue is before the modified issue year of ' + str(issyr)) datematch = "False" else: logger.info(module + ' Found matching issue # ' + str(fcdigit) + ' for ComicID: ' + str(cs['ComicID']) + ' / IssueID: ' + str(issuechk['IssueID'])) if datematch == "True": manual_list.append({"ComicLocation": tmpfc['ComicLocation'], "ComicID": cs['ComicID'], "IssueID": issuechk['IssueID'], "IssueNumber": issuechk['Issue_Number'], "ComicName": cs['ComicName']}) else: logger.fdebug(module + ' Incorrect series - not populating..continuing post-processing') #ccnt+=1 fn+=1 logger.fdebug(module + ' There are ' + str(len(manual_list)) + ' files found that match on your watchlist, ' + str(nm) + ' do not match anything and will be ignored.') else: nzbname = self.nzb_name #remove extensions from nzb_name if they somehow got through (Experimental most likely) extensions = ('.cbr', '.cbz') if nzbname.lower().endswith(extensions): fd, ext = os.path.splitext(nzbname) self._log("Removed extension from nzb: " + ext) nzbname = re.sub(str(ext), '', str(nzbname)) #replace spaces nzbname = re.sub(' ', '.', str(nzbname)) nzbname = re.sub('[\,\:\?]', '', str(nzbname)) nzbname = re.sub('[\&]', 'and', str(nzbname)) logger.fdebug(module + ' After conversions, nzbname is : ' + str(nzbname)) # if mylar.USE_NZBGET==1: # nzbname=self.nzb_name self._log("nzbname: " + str(nzbname)) nzbiss = myDB.selectone("SELECT * from nzblog WHERE nzbname=?", [nzbname]).fetchone() if nzbiss is None: self._log("Failure - could not initially locate nzbfile in my database to rename.") logger.fdebug(module + ' Failure - could not locate nzbfile initially') # if failed on spaces, change it all to decimals and try again. nzbname = re.sub('_', '.', str(nzbname)) self._log("trying again with this nzbname: " + str(nzbname)) logger.fdebug(module + ' Trying to locate nzbfile again with nzbname of : ' + str(nzbname)) nzbiss = myDB.selectone("SELECT * from nzblog WHERE nzbname=?", [nzbname]).fetchone() if nzbiss is None: logger.error(module + ' Unable to locate downloaded file to rename. PostProcessing aborted.') return else: self._log("I corrected and found the nzb as : " + str(nzbname)) logger.fdebug(module + ' Auto-corrected and found the nzb as : ' + str(nzbname)) issueid = nzbiss['IssueID'] else: issueid = nzbiss['IssueID'] logger.fdebug(module + ' Issueid: ' + str(issueid)) sarc = nzbiss['SARC'] #use issueid to get publisher, series, year, issue number annchk = "no" if 'annual' in nzbname.lower(): logger.info(module + ' Annual detected.') annchk = "yes" issuenzb = myDB.selectone("SELECT * from annuals WHERE IssueID=? AND ComicName NOT NULL", [issueid]).fetchone() else: issuenzb = myDB.selectone("SELECT * from issues WHERE IssueID=? AND ComicName NOT NULL", [issueid]).fetchone() if issuenzb is not None: logger.info(module + ' issuenzb found.') if helpers.is_number(issueid): sandwich = int(issuenzb['IssueID']) else: logger.info(module + ' issuenzb not found.') #if it's non-numeric, it contains a 'G' at the beginning indicating it's a multi-volume #using GCD data. Set sandwich to 1 so it will bypass and continue post-processing. if 'S' in issueid: sandwich = issueid elif 'G' in issueid or '-' in issueid: sandwich = 1 if helpers.is_number(sandwich): if sandwich < 900000: # if sandwich is less than 900000 it's a normal watchlist download. Bypass. pass else: if issuenzb is None or 'S' in sandwich or int(sandwich) >= 900000: # this has no issueID, therefore it's a one-off or a manual post-proc. # At this point, let's just drop it into the Comic Location folder and forget about it.. if 'S' in sandwich: self._log("One-off STORYARC mode enabled for Post-Processing for " + str(sarc)) logger.info(module + 'One-off STORYARC mode enabled for Post-Processing for ' + str(sarc)) if mylar.STORYARCDIR: storyarcd = os.path.join(mylar.DESTINATION_DIR, "StoryArcs", sarc) self._log("StoryArc Directory set to : " + storyarcd) else: self._log("Grab-Bag Directory set to : " + mylar.GRABBAG_DIR) else: self._log("One-off mode enabled for Post-Processing. All I'm doing is moving the file untouched into the Grab-bag directory.") logger.info(module + ' One-off mode enabled for Post-Processing. Will move into Grab-bag directory.') self._log("Grab-Bag Directory set to : " + mylar.GRABBAG_DIR) for root, dirnames, filenames in os.walk(self.nzb_folder): for filename in filenames: if filename.lower().endswith(extensions): ofilename = filename path, ext = os.path.splitext(ofilename) if 'S' in sandwich: if mylar.STORYARCDIR: grdst = storyarcd else: grdst = mylar.DESTINATION_DIR else: if mylar.GRABBAG_DIR: grdst = mylar.GRABBAG_DIR else: grdst = mylar.DESTINATION_DIR filechecker.validateAndCreateDirectory(grdst, True, module=module) if 'S' in sandwich: #if from a StoryArc, check to see if we're appending the ReadingOrder to the filename if mylar.READ2FILENAME: issuearcid = re.sub('S', '', issueid) logger.fdebug(module + ' issuearcid:' + str(issuearcid)) arcdata = myDB.selectone("SELECT * FROM readinglist WHERE IssueArcID=?",[issuearcid]).fetchone() logger.fdebug(module + ' readingorder#: ' + str(arcdata['ReadingOrder'])) if int(arcdata['ReadingOrder']) < 10: readord = "00" + str(arcdata['ReadingOrder']) elif int(arcdata['ReadingOrder']) > 10 and int(arcdata['ReadingOrder']) < 99: readord = "0" + str(arcdata['ReadingOrder']) else: readord = str(arcdata['ReadingOrder']) dfilename = str(readord) + "-" + ofilename else: dfilename = ofilename grab_dst = os.path.join(grdst, dfilename) else: grab_dst = os.path.join(grdst, ofilename) self._log("Destination Path : " + grab_dst) logger.info(module + ' Destination Path : ' + grab_dst) grab_src = os.path.join(self.nzb_folder, ofilename) self._log("Source Path : " + grab_src) logger.info(module + ' Source Path : ' + grab_src) logger.info(module + ' Moving ' + str(ofilename) + ' into directory : ' + str(grdst)) try: shutil.move(grab_src, grab_dst) except (OSError, IOError): self._log("Failed to move directory - check directories and manually re-run.") logger.debug(module + ' Failed to move directory - check directories and manually re-run.') return #tidyup old path try: shutil.rmtree(self.nzb_folder) except (OSError, IOError): self._log("Failed to remove temporary directory.") logger.debug(module + ' Failed to remove temporary directory - check directory and manually re-run.') return logger.debug(module + ' Removed temporary directory : ' + str(self.nzb_folder)) self._log("Removed temporary directory : " + self.nzb_folder) #delete entry from nzblog table myDB.action('DELETE from nzblog WHERE issueid=?', [issueid]) if 'S' in issueid: issuearcid = re.sub('S', '', issueid) logger.info(module + ' IssueArcID is : ' + str(issuearcid)) ctrlVal = {"IssueArcID": issuearcid} newVal = {"Status": "Downloaded", "Location": grab_dst } myDB.upsert("readinglist",newVal,ctrlVal) logger.info(module + ' Updated status to Downloaded') return self.log if self.nzb_name == 'Manual Run': #loop through the hits here. if len(manual_list) == '0': logger.info(module + ' No matches for Manual Run ... exiting.') return for ml in manual_list: comicid = ml['ComicID'] issueid = ml['IssueID'] issuenumOG = ml['IssueNumber'] self.Process_next(comicid,issueid,issuenumOG,ml) logger.info(module + ' Manual post-processing completed.') return else: comicid = issuenzb['ComicID'] issuenumOG = issuenzb['Issue_Number'] return self.Process_next(comicid,issueid,issuenumOG) def Process_next(self,comicid,issueid,issuenumOG,ml=None): module = self.module annchk = "no" extensions = ('.cbr', '.cbz') snatchedtorrent = False myDB = db.DBConnection() comicnzb = myDB.selectone("SELECT * from comics WHERE comicid=?", [comicid]).fetchone() issuenzb = myDB.selectone("SELECT * from issues WHERE issueid=? AND comicid=? AND ComicName NOT NULL", [issueid,comicid]).fetchone() if ml is not None and mylar.SNATCHEDTORRENT_NOTIFY: snatchnzb = myDB.selectone("SELECT * from snatched WHERE IssueID=? AND ComicID=? AND (provider=? OR provider=?) AND Status='Snatched'", [issueid,comicid,'KAT','CBT']).fetchone() if snatchnzb is None: logger.fdebug(module + ' Was not downloaded with Mylar and the usage of torrents. Disabling torrent manual post-processing completion notification.') else: logger.fdebug(module + ' Was downloaded from ' + snatchnzb['Provider'] + '. Enabling torrent manual post-processing completion notification.') snatchedtorrent = True if issuenzb is None: issuenzb = myDB.selectone("SELECT * from annuals WHERE issueid=? and comicid=?", [issueid,comicid]).fetchone() annchk = "yes" if annchk == "no": logger.info(module + ' Starting Post-Processing for ' + issuenzb['ComicName'] + ' issue: ' + str(issuenzb['Issue_Number'])) else: logger.info(module + ' Starting Post-Processing for ' + issuenzb['ComicName'] + ' Annual issue: ' + str(issuenzb['Issue_Number'])) logger.fdebug(module + ' issueid: ' + str(issueid)) logger.fdebug(module + ' issuenumOG: ' + str(issuenumOG)) #issueno = str(issuenum).split('.')[0] #new CV API - removed all decimals...here we go AGAIN! issuenum = issuenzb['Issue_Number'] issue_except = 'None' if 'au' in issuenum.lower() and issuenum[:1].isdigit(): issuenum = re.sub("[^0-9]", "", issuenum) issue_except = ' AU' elif 'ai' in issuenum.lower() and issuenum[:1].isdigit(): issuenum = re.sub("[^0-9]", "", issuenum) issue_except = ' AI' elif 'inh' in issuenum.lower() and issuenum[:1].isdigit(): issuenum = re.sub("[^0-9]", "", issuenum) issue_except = '.INH' elif 'now' in issuenum.lower() and issuenum[:1].isdigit(): if '!' in issuenum: issuenum = re.sub('\!', '', issuenum) issuenum = re.sub("[^0-9]", "", issuenum) issue_except = '.NOW' if '.' in issuenum: iss_find = issuenum.find('.') iss_b4dec = issuenum[:iss_find] iss_decval = issuenum[iss_find+1:] if int(iss_decval) == 0: iss = iss_b4dec issdec = int(iss_decval) issueno = str(iss) self._log("Issue Number: " + str(issueno)) logger.fdebug(module + 'Issue Number: ' + str(issueno)) else: if len(iss_decval) == 1: iss = iss_b4dec + "." + iss_decval issdec = int(iss_decval) * 10 else: iss = iss_b4dec + "." + iss_decval.rstrip('0') issdec = int(iss_decval.rstrip('0')) * 10 issueno = iss_b4dec self._log("Issue Number: " + str(iss)) logger.fdebug(module + ' Issue Number: ' + str(iss)) else: iss = issuenum issueno = str(iss) # issue zero-suppression here if mylar.ZERO_LEVEL == "0": zeroadd = "" else: if mylar.ZERO_LEVEL_N == "none": zeroadd = "" elif mylar.ZERO_LEVEL_N == "0x": zeroadd = "0" elif mylar.ZERO_LEVEL_N == "00x": zeroadd = "00" logger.fdebug(module + ' Zero Suppression set to : ' + str(mylar.ZERO_LEVEL_N)) if str(len(issueno)) > 1: if int(issueno) < 0: self._log("issue detected is a negative") prettycomiss = '-' + str(zeroadd) + str(abs(issueno)) elif int(issueno) < 10: self._log("issue detected less than 10") if '.' in iss: if int(iss_decval) > 0: issueno = str(iss) prettycomiss = str(zeroadd) + str(iss) else: prettycomiss = str(zeroadd) + str(int(issueno)) else: prettycomiss = str(zeroadd) + str(iss) if issue_except != 'None': prettycomiss = str(prettycomiss) + issue_except self._log("Zero level supplement set to " + str(mylar.ZERO_LEVEL_N) + ". Issue will be set as : " + str(prettycomiss)) elif int(issueno) >= 10 and int(issueno) < 100: self._log("issue detected greater than 10, but less than 100") if mylar.ZERO_LEVEL_N == "none": zeroadd = "" else: zeroadd = "0" if '.' in iss: if int(iss_decval) > 0: issueno = str(iss) prettycomiss = str(zeroadd) + str(iss) else: prettycomiss = str(zeroadd) + str(int(issueno)) else: prettycomiss = str(zeroadd) + str(iss) if issue_except != 'None': prettycomiss = str(prettycomiss) + issue_except self._log("Zero level supplement set to " + str(mylar.ZERO_LEVEL_N) + ".Issue will be set as : " + str(prettycomiss)) else: self._log("issue detected greater than 100") if '.' in iss: if int(iss_decval) > 0: issueno = str(iss) prettycomiss = str(issueno) if issue_except != 'None': prettycomiss = str(prettycomiss) + issue_except self._log("Zero level supplement set to " + str(mylar.ZERO_LEVEL_N) + ". Issue will be set as : " + str(prettycomiss)) else: prettycomiss = str(issueno) self._log("issue length error - cannot determine length. Defaulting to None: " + str(prettycomiss)) if annchk == "yes": self._log("Annual detected.") logger.fdebug(module + ' Pretty Comic Issue is : ' + str(prettycomiss)) issueyear = issuenzb['IssueDate'][:4] self._log("Issue Year: " + str(issueyear)) logger.fdebug(module + ' Issue Year : ' + str(issueyear)) month = issuenzb['IssueDate'][5:7].replace('-','').strip() month_name = helpers.fullmonth(month) # comicnzb= myDB.action("SELECT * from comics WHERE comicid=?", [comicid]).fetchone() publisher = comicnzb['ComicPublisher'] self._log("Publisher: " + publisher) logger.fdebug(module + ' Publisher: ' + str(publisher)) #we need to un-unicode this to make sure we can write the filenames properly for spec.chars series = comicnzb['ComicName'].encode('ascii', 'ignore').strip() self._log("Series: " + series) logger.fdebug(module + ' Series: ' + str(series)) seriesyear = comicnzb['ComicYear'] self._log("Year: " + seriesyear) logger.fdebug(module + ' Year: ' + str(seriesyear)) comlocation = comicnzb['ComicLocation'] self._log("Comic Location: " + comlocation) logger.fdebug(module + ' Comic Location: ' + str(comlocation)) comversion = comicnzb['ComicVersion'] self._log("Comic Version: " + str(comversion)) logger.fdebug(module + ' Comic Version: ' + str(comversion)) if comversion is None: comversion = 'None' #if comversion is None, remove it so it doesn't populate with 'None' if comversion == 'None': chunk_f_f = re.sub('\$VolumeN','',mylar.FILE_FORMAT) chunk_f = re.compile(r'\s+') chunk_file_format = chunk_f.sub(' ', chunk_f_f) self._log("No version # found for series - tag will not be available for renaming.") logger.fdebug(module + ' No version # found for series, removing from filename') logger.fdebug(module + ' New format is now: ' + str(chunk_file_format)) else: chunk_file_format = mylar.FILE_FORMAT if annchk == "no": chunk_f_f = re.sub('\$Annual','',chunk_file_format) chunk_f = re.compile(r'\s+') chunk_file_format = chunk_f.sub(' ', chunk_f_f) logger.fdebug(module + ' Not an annual - removing from filename paramaters') logger.fdebug(module + ' New format: ' + str(chunk_file_format)) else: logger.fdebug(module + ' Chunk_file_format is: ' + str(chunk_file_format)) if '$Annual' not in chunk_file_format: #if it's an annual, but $Annual isn't specified in file_format, we need to #force it in there, by default in the format of $Annual $Issue prettycomiss = "Annual " + str(prettycomiss) logger.fdebug(module + ' prettycomiss: ' + str(prettycomiss)) ofilename = None #if meta-tagging is not enabled, we need to declare the check as being fail #if meta-tagging is enabled, it gets changed just below to a default of pass pcheck = "fail" #tag the meta. if mylar.ENABLE_META: self._log("Metatagging enabled - proceeding...") logger.fdebug(module + ' Metatagging enabled - proceeding...') pcheck = "pass" try: import cmtagmylar if ml is None: pcheck = cmtagmylar.run(self.nzb_folder, issueid=issueid) else: pcheck = cmtagmylar.run(self.nzb_folder, issueid=issueid, manual="yes", filename=ml['ComicLocation']) except ImportError: logger.fdebug(module + ' comictaggerlib not found on system. Ensure the ENTIRE lib directory is located within mylar/lib/comictaggerlib/') logger.fdebug(module + ' continuing with PostProcessing, but I am not using metadata.') pcheck = "fail" if pcheck == "fail": self._log("Unable to write metadata successfully - check mylar.log file. Attempting to continue without tagging...") logger.fdebug(module + ' Unable to write metadata successfully - check mylar.log file. Attempting to continue without tagging...') #we need to set this to the cbz file since not doing it will result in nothing getting moved. #not sure how to do this atm elif pcheck == "unrar error": self._log("This is a corrupt archive - whether CRC errors or it's incomplete. Marking as BAD, and retrying a different copy.") logger.error(module + ' This is a corrupt archive - whether CRC errors or it is incomplete. Marking as BAD, and retrying a different copy.') return self.log else: otofilename = pcheck self._log("Sucessfully wrote metadata to .cbz - Continuing..") logger.info(module + ' Sucessfully wrote metadata to .cbz (' + os.path.split(otofilename)[1] + ') - Continuing..') #Run Pre-script if mylar.ENABLE_PRE_SCRIPTS: nzbn = self.nzb_name #original nzb name nzbf = self.nzb_folder #original nzb folder #name, comicyear, comicid , issueid, issueyear, issue, publisher #create the dic and send it. seriesmeta = [] seriesmetadata = {} seriesmeta.append({ 'name': series, 'comicyear': seriesyear, 'comicid': comicid, 'issueid': issueid, 'issueyear': issueyear, 'issue': issuenum, 'publisher': publisher }) seriesmetadata['seriesmeta'] = seriesmeta self._run_pre_scripts(nzbn, nzbf, seriesmetadata ) #rename file and move to new path #nfilename = series + " " + issueno + " (" + seriesyear + ")" file_values = {'$Series': series, '$Issue': prettycomiss, '$Year': issueyear, '$series': series.lower(), '$Publisher': publisher, '$publisher': publisher.lower(), '$VolumeY': 'V' + str(seriesyear), '$VolumeN': comversion, '$monthname': month_name, '$month': month, '$Annual': 'Annual' } #if it's a Manual Run, use the ml['ComicLocation'] for the exact filename. if ml is None: for root, dirnames, filenames in os.walk(self.nzb_folder): for filename in filenames: if filename.lower().endswith(extensions): odir = root logger.fdebug(module + ' odir (root): ' + odir) ofilename = filename logger.fdebug(module + ' ofilename: ' + ofilename) path, ext = os.path.splitext(ofilename) if odir is None: logger.fdebug(module + ' No root folder set.') odir = self.nzb_folder logger.fdebug(module + ' odir: ' + str(odir)) logger.fdebug(module + ' ofilename: ' + str(ofilename)) else: if pcheck == "fail": otofilename = ml['ComicLocation'] logger.fdebug(module + ' otofilename:' + str(otofilename)) odir, ofilename = os.path.split(otofilename) logger.fdebug(module + ' odir: ' + str(odir)) logger.fdebug(module + ' ofilename: ' + str(ofilename)) path, ext = os.path.splitext(ofilename) logger.fdebug(module + ' path: ' + str(path)) logger.fdebug(module + ' ext:' + str(ext)) if ofilename is None: logger.error(module + ' Aborting PostProcessing - the filename does not exist in the location given. Make sure that ' + str(self.nzb_folder) + ' exists and is the correct location.') return self._log("Original Filename: " + ofilename) self._log("Original Extension: " + ext) logger.fdebug(module + ' Original Filname: ' + str(ofilename)) logger.fdebug(module + ' Original Extension: ' + str(ext)) if mylar.FILE_FORMAT == '' or not mylar.RENAME_FILES: self._log("Rename Files isn't enabled...keeping original filename.") logger.fdebug(module + ' Rename Files is not enabled - keeping original filename.') #check if extension is in nzb_name - will screw up otherwise if ofilename.lower().endswith(extensions): nfilename = ofilename[:-4] else: nfilename = ofilename else: nfilename = helpers.replace_all(chunk_file_format, file_values) if mylar.REPLACE_SPACES: #mylar.REPLACE_CHAR ...determines what to replace spaces with underscore or dot nfilename = nfilename.replace(' ', mylar.REPLACE_CHAR) nfilename = re.sub('[\,\:\?]', '', nfilename) nfilename = re.sub('[\/]', '-', nfilename) self._log("New Filename: " + nfilename) logger.fdebug(module + ' New Filename: ' + str(nfilename)) #src = os.path.join(self.nzb_folder, ofilename) src = os.path.join(odir, ofilename) filechecker.validateAndCreateDirectory(comlocation, True, module=module) if mylar.LOWERCASE_FILENAMES: dst = os.path.join(comlocation, (nfilename + ext).lower()) else: dst = os.path.join(comlocation, (nfilename + ext.lower())) self._log("Source:" + src) self._log("Destination:" + dst) logger.fdebug(module + ' Source: ' + str(src)) logger.fdebug(module + ' Destination: ' + str(dst)) if ml is None: #downtype = for use with updater on history table to set status to 'Downloaded' downtype = 'True' #non-manual run moving/deleting... logger.fdebug(module + ' self.nzb_folder: ' + self.nzb_folder) logger.fdebug(module + ' odir: ' + str(odir)) logger.fdebug(module + ' ofilename:' + str(ofilename)) logger.fdebug(module + ' nfilename:' + str(nfilename + ext)) if mylar.RENAME_FILES: if str(ofilename) != str(nfilename + ext): logger.fdebug(module + ' Renaming ' + os.path.join(odir, str(ofilename)) + ' ..to.. ' + os.path.join(odir,str(nfilename + ext))) os.rename(os.path.join(odir, str(ofilename)), os.path.join(odir,str(nfilename + ext))) else: logger.fdebug(module + ' Filename is identical as original, not renaming.') #src = os.path.join(self.nzb_folder, str(nfilename + ext)) src = os.path.join(odir, str(nfilename + ext)) try: shutil.move(src, dst) except (OSError, IOError): self._log("Failed to move directory - check directories and manually re-run.") self._log("Post-Processing ABORTED.") logger.warn(module + ' Failed to move directory : ' + src + ' to ' + dst + ' - check directory and manually re-run') logger.warn(module + ' Post-Processing ABORTED') return #tidyup old path try: shutil.rmtree(self.nzb_folder) except (OSError, IOError): self._log("Failed to remove temporary directory - check directory and manually re-run.") self._log("Post-Processing ABORTED.") logger.warn(module + ' Failed to remove temporary directory : ' + self.nzb_folder) logger.warn(module + ' Post-Processing ABORTED') return self._log("Removed temporary directory : " + str(self.nzb_folder)) logger.fdebug(module + ' Removed temporary directory : ' + self.nzb_folder) else: #downtype = for use with updater on history table to set status to 'Post-Processed' downtype = 'PP' #Manual Run, this is the portion. if mylar.RENAME_FILES: if str(ofilename) != str(nfilename + ext): logger.fdebug(module + ' Renaming ' + os.path.join(odir, str(ofilename)) + ' ..to.. ' + os.path.join(odir, self.nzb_folder,str(nfilename + ext))) os.rename(os.path.join(odir, str(ofilename)), os.path.join(odir ,str(nfilename + ext))) else: logger.fdebug(module + ' Filename is identical as original, not renaming.') src = os.path.join(odir, str(nfilename + ext)) logger.fdebug(module + ' odir src : ' + os.path.join(odir, str(nfilename + ext))) logger.fdebug(module + ' Moving ' + src + ' ... to ... ' + dst) try: shutil.move(src, dst) except (OSError, IOError): logger.fdebug(module + ' Failed to move directory - check directories and manually re-run.') logger.fdebug(module + ' Post-Processing ABORTED.') return logger.fdebug(module + ' Successfully moved to : ' + dst) #tidyup old path try: if os.path.isdir(odir) and odir != self.nzb_folder: # check to see if the directory is empty or not. if not os.listdir(odir): logger.fdebug(module + ' Tidying up. Deleting folder : ' + odir) shutil.rmtree(odir) else: raise OSError(module + ' ' + odir + ' not empty. Skipping removal of directory - this will either be caught in further post-processing or it will have to be removed manually.') else: raise OSError(module + ' ' + odir + ' unable to remove at this time.') except (OSError, IOError): logger.fdebug(module + ' Failed to remove temporary directory (' + odir + ') - Processing will continue, but manual removal is necessary') #Hopefully set permissions on downloaded file try: permission = int(mylar.CHMOD_FILE, 8) os.umask(0) os.chmod(dst.rstrip(), permission) except OSError: logger.error(module + ' Failed to change file permissions. Ensure that the user running Mylar has proper permissions to change permissions in : ' + dst) logger.fdebug(module + ' Continuing post-processing but unable to change file permissions in ' + dst) #delete entry from nzblog table myDB.action('DELETE from nzblog WHERE issueid=?', [issueid]) #update snatched table to change status to Downloaded if annchk == "no": updater.foundsearch(comicid, issueid, down=downtype, module=module) dispiss = 'issue: ' + str(issuenumOG) else: updater.foundsearch(comicid, issueid, mode='want_ann', down=downtype, module=module) dispiss = 'annual issue: ' + str(issuenumOG) #force rescan of files updater.forceRescan(comicid,module=module) if mylar.WEEKFOLDER: #if enabled, will *copy* the post-processed file to the weeklypull list folder for the given week. weeklypull.weekly_singlecopy(comicid,issuenum,str(nfilename+ext),dst,module=module) # retrieve/create the corresponding comic objects if mylar.ENABLE_EXTRA_SCRIPTS: folderp = str(dst) #folder location after move/rename nzbn = self.nzb_name #original nzb name filen = str(nfilename + ext) #new filename #name, comicyear, comicid , issueid, issueyear, issue, publisher #create the dic and send it. seriesmeta = [] seriesmetadata = {} seriesmeta.append({ 'name': series, 'comicyear': seriesyear, 'comicid': comicid, 'issueid': issueid, 'issueyear': issueyear, 'issue': issuenum, 'publisher': publisher }) seriesmetadata['seriesmeta'] = seriesmeta self._run_extra_scripts(nzbn, self.nzb_folder, filen, folderp, seriesmetadata ) if ml is not None: #we only need to return self.log if it's a manual run and it's not a snatched torrent if snatchedtorrent: #manual run + snatched torrent pass else: #manual run + not snatched torrent (or normal manual-run) logger.info(module + ' Post-Processing completed for: ' + series + ' ' + dispiss ) self._log(u"Post Processing SUCCESSFUL! ") return self.log if annchk == "no": prline = series + '(' + issueyear + ') - issue #' + issuenumOG else: prline = series + ' Annual (' + issueyear + ') - issue #' + issuenumOG prline2 = 'Mylar has downloaded and post-processed: ' + prline if mylar.PROWL_ENABLED: pushmessage = prline prowl = notifiers.PROWL() prowl.notify(pushmessage,"Download and Postprocessing completed", module=module) if mylar.NMA_ENABLED: nma = notifiers.NMA() nma.notify(prline=prline, prline2=prline2, module=module) if mylar.PUSHOVER_ENABLED: pushover = notifiers.PUSHOVER() pushover.notify(prline, "Download and Post-Processing completed", module=module) if mylar.BOXCAR_ENABLED: boxcar = notifiers.BOXCAR() boxcar.notify(prline=prline, prline2=prline2, module=module) if mylar.PUSHBULLET_ENABLED: pushbullet = notifiers.PUSHBULLET() pushbullet.notify(prline=prline, prline2=prline2, module=module) logger.info(module + ' Post-Processing completed for: ' + series + ' ' + dispiss ) self._log(u"Post Processing SUCCESSFUL! ") return self.log class FolderCheck(): def run(self): module = '[FOLDER-CHECK]' import PostProcessor, logger #monitor a selected folder for 'snatched' files that haven't been processed logger.info(module + ' Checking folder ' + mylar.CHECK_FOLDER + ' for newly snatched downloads') PostProcess = PostProcessor.PostProcessor('Manual Run', mylar.CHECK_FOLDER) result = PostProcess.Process() logger.info(module + ' Finished checking for newly snatched downloads')
df69ecd68dbc05aa63ae2dc25a88a9c5272233bc
cec916f882afbd09fe68f6b88879e68eaea976f6
/bigmler/resourcesapi/fusions.py
1c8a17d3f87803d2ed503abbe367ac47e23f8336
[ "Apache-2.0" ]
permissive
jaor/bigmler
d86db6d7950768d7ba3e21b5f29bc265467f4cad
bbf221e41ef04e8d37a511a35a63216b64689449
refs/heads/master
2023-04-26T12:07:49.428263
2023-04-12T15:22:20
2023-04-12T15:22:20
15,663,632
0
0
null
null
null
null
UTF-8
Python
false
false
5,785
py
# -*- coding: utf-8 -*- # # Copyright 2020-2023 BigML # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """Resources management functions """ import sys import bigml.api from bigmler.utils import (dated, get_url, log_message, check_resource, is_shared, check_resource_error, log_created_resources) from bigmler.reports import report from bigmler.resourcesapi.common import set_basic_args, \ update_json_args, wait_for_available_tasks from bigmler.resourcesapi.common import FIELDS_QS, \ ALL_FIELDS_QS def set_fusion_args(args, name=None, fields=None): """Return fusion arguments dict """ if name is None: name = args.name fusion_args = set_basic_args(args, name) if 'fusion' in args.json_args: update_json_args(fusion_args, args.json_args.get('fusion'), fields) return fusion_args def create_fusion(models, fusion, fusion_args, args, api=None, path=None, session_file=None, log=None): """Create remote fusion """ if api is None: api = bigml.api.BigML() fusions = [] fusion_ids = [] if fusion is not None: fusions = [fusion] fusion_ids = [fusion] # if resuming and all fusions were created if models: # Only one fusion per command, at present message = dated("Creating fusion.\n") log_message(message, log_file=session_file, console=args.verbosity) query_string = FIELDS_QS inprogress = [] wait_for_available_tasks(inprogress, args.max_parallel_fusions, api, "fusion") fusion = api.create_fusion(models, fusion_args, retries=None) fusion_id = check_resource_error( \ fusion, "Failed to create fusion: ") log_message("%s\n" % fusion_id, log_file=log) fusion_ids.append(fusion_id) inprogress.append(fusion_id) fusions.append(fusion) log_created_resources("fusions", path, fusion_id, mode='a') if args.verbosity: if bigml.api.get_status(fusion)['code'] != bigml.api.FINISHED: try: fusion = check_resource( \ fusion, api.get_fusion, query_string=query_string, raise_on_error=True) except Exception as exception: sys.exit("Failed to get a finished fusion: %s" % str(exception)) fusions[0] = fusion message = dated("Fusion created: %s\n" % get_url(fusion)) log_message(message, log_file=session_file, console=args.verbosity) if args.reports: report(args.reports, path, fusion) return fusion def get_fusion(fusion, args, api=None, session_file=None): """Retrieves remote fusion in its actual status """ if api is None: api = bigml.api.BigML() message = dated("Retrieving Fusion. %s\n" % get_url(fusion)) log_message(message, log_file=session_file, console=args.verbosity) # only one fusion at present try: # we need the whole fields structure when exporting fields fusion = check_resource(fusion, api.get_fusion, query_string=ALL_FIELDS_QS, raise_on_error=True) except Exception as exception: sys.exit("Failed to get a finished fusion: %s" % \ str(exception)) return fusion def set_publish_fusion_args(args): """Set args to publish fusion """ public_fusion = {} if args.public_fusion: public_fusion = {"private": False} if args.model_price: public_fusion.update(price=args.model_price) if args.cpp: public_fusion.update(credits_per_prediction=args.cpp) return public_fusion def update_fusion(fusion, fusion_args, args, api=None, path=None, session_file=None): """Updates fusion properties """ if api is None: api = bigml.api.BigML() message = dated("Updating Fusion. %s\n" % get_url(fusion)) log_message(message, log_file=session_file, console=args.verbosity) fusion = api.update_fusion(fusion, fusion_args) check_resource_error(fusion, "Failed to update Fusion: %s" % fusion['resource']) fusion = check_resource(fusion, api.get_fusion, query_string=FIELDS_QS, raise_on_error=True) if is_shared(fusion): message = dated("Shared Fusion link. %s\n" % get_url(fusion, shared=True)) log_message(message, log_file=session_file, console=args.verbosity) if args.reports: report(args.reports, path, fusion) return fusion
8b298efd886c26c6cc53a15b22eb5b96064022d5
7d7da2d78526436aedbe44f2a1b26f31409993f5
/ABOUT/views.py
5c8a785178e768c6719b4701506222f43a77f655
[]
no_license
Arif553715/NGO
c4042b59a96de0b1f8c74f73ca166aa03ed6223c
7a901931dd70702e6e81d8e0880bca962da09443
refs/heads/master
2020-05-06T20:32:42.036796
2019-04-18T09:36:17
2019-04-18T09:36:17
180,239,663
0
0
null
null
null
null
UTF-8
Python
false
false
752
py
from django.shortcuts import render,HttpResponse,get_object_or_404 from .models import Author1,Artical,Catagory,Our_Team # Create your views here. # start blogapp def about(request): context={'post':Artical.objects.all(), 'teams':Our_Team.objects.all()} return render(request,'about.html',context) def getauthor(request,name): return render(request,'profile.html') def getsingle(request,id): post=get_object_or_404(Artical,pk=id) first=Artical.objects.first() last=Artical.objects.last() context={ 'post':post, 'first':first, 'last':last } return render(request,'single.html',context) def gettopic(request,name): return render(request,'catagory.html') # end blogapp
b9603c227e39f7d5e195f02d9a03afe31a826525
f9f2d8064943906e8ee0d305d405ca1e5dd0a6b7
/Hysteresis_Measurement/tooltip.py
d252b1f9c6760bf06e328eb70ab58b3b73bb2afb
[]
no_license
Jeffrey-Ede/Atomic-Force-Microscopy
a46930657b256f4dc772c1b2130a55486dbb6e2b
7df834b17ad9974016b02a72711f8847f6b15d4d
refs/heads/master
2021-01-18T12:06:38.779728
2017-10-06T07:24:12
2017-10-06T07:24:12
100,364,689
4
1
null
null
null
null
UTF-8
Python
false
false
1,336
py
# -*- coding: utf-8 -*- """ Created on Tue Aug 15 22:48:56 2017 @author: Jeffrey Ede """ import tkinter as Tk class ToolTip(object): def __init__(self, widget): self.widget = widget self.tipwindow = None self.id = None self.x = self.y = 0 def showtip(self, text): "Display text in tooltip window" self.text = text if self.tipwindow or not self.text: return x, y, cx, cy = self.widget.bbox("insert") x = x + self.widget.winfo_rootx() + 27 y = y + cy + self.widget.winfo_rooty() +27 self.tipwindow = tw = Tk.Toplevel(self.widget) tw.wm_overrideredirect(1) tw.wm_geometry("+%d+%d" % (x, y)) label = Tk.Label(tw, text=self.text, justify=Tk.LEFT, background="#ffffe0", relief=Tk.SOLID, borderwidth=1, font=("tahoma", "8", "normal")) label.pack(ipadx=1) def hidetip(self): tw = self.tipwindow self.tipwindow = None if tw: tw.destroy() def createToolTip(widget, text): toolTip = ToolTip(widget) def enter(event): toolTip.showtip(text) def leave(event): toolTip.hidetip() widget.bind('<Enter>', enter) widget.bind('<Leave>', leave)
37bf8c7b0152c0dc58cbad1f1dc6b119848ae1ea
fb5c5d50d87a6861393d31911b9fae39bdc3cc62
/Scripts/sims4communitylib/utils/sims/common_sim_posture_utils.py
942b6a83e30a1b592931b2b26886eea4d99d6716
[ "CC-BY-4.0" ]
permissive
ColonolNutty/Sims4CommunityLibrary
ee26126375f2f59e5567b72f6eb4fe9737a61df3
58e7beb30b9c818b294d35abd2436a0192cd3e82
refs/heads/master
2023-08-31T06:04:09.223005
2023-08-22T19:57:42
2023-08-22T19:57:42
205,197,959
183
38
null
2023-05-28T16:17:53
2019-08-29T15:48:35
Python
UTF-8
Python
false
false
12,599
py
""" The Sims 4 Community Library is licensed under the Creative Commons Attribution 4.0 International public license (CC BY 4.0). https://creativecommons.org/licenses/by/4.0/ https://creativecommons.org/licenses/by/4.0/legalcode Copyright (c) COLONOLNUTTY """ from typing import Tuple, Union, Any from postures.posture import Posture from postures.posture_state import PostureState from sims.sim_info import SimInfo from sims4communitylib.classes.testing.common_test_result import CommonTestResult from sims4communitylib.enums.common_posture_id import CommonPostureId from sims4communitylib.enums.enumtypes.common_int import CommonInt from sims4communitylib.logging._has_s4cl_class_log import _HasS4CLClassLog from sims4communitylib.utils.sims.common_sim_utils import CommonSimUtils class CommonSimPostureUtils(_HasS4CLClassLog): """Utilities for managing the posture of Sims.""" # noinspection PyMissingOrEmptyDocstring @classmethod def get_log_identifier(cls) -> str: return 'common_sim_posture_utils' @classmethod def has_posture(cls, sim_info: SimInfo, posture: Union[int, CommonPostureId, Posture, CommonInt]) -> CommonTestResult: """has_posture(sim_info, posture) Determine if a Sim has a posture. :param sim_info: An instance of a Sim. :type sim_info: SimInfo :param posture: The identifier of the posture to check. :type posture: Union[int, CommonPostureId, Posture, CommonInt] """ sim = CommonSimUtils.get_sim_instance(sim_info) if sim is None: return CommonTestResult(False, reason=f'Posture test failed because the {sim_info} is non-instantiated.') posture_instance = cls.load_posture_by_id(posture) if posture_instance is None: return CommonTestResult(False, reason=f'No posture was found with id.') for aspect in cls.get_posture_aspects(sim_info): if not posture_instance.multi_sim and aspect.posture_type is posture_instance: return CommonTestResult.TRUE return CommonTestResult(False, reason=f'{sim_info} does not have posture {posture_instance}.') @classmethod def has_posture_with_sim(cls, sim_info: SimInfo, target_sim_info: SimInfo, posture: Union[int, CommonPostureId, Posture, CommonInt]) -> CommonTestResult: """has_posture_with_sim(sim_info, target_sim_info, posture) Determine if a Sim has a posture with another Sim. :param sim_info: An instance of a Sim. :type sim_info: SimInfo :param target_sim_info: An instance of another Sim. :type target_sim_info: SimInfo :param posture: The identifier of the posture to check. :type posture: Union[int, CommonPostureId, Posture, CommonInt] """ sim = CommonSimUtils.get_sim_instance(sim_info) if sim is None: return CommonTestResult(False, reason=f'Posture test failed because the {sim_info} is non-instantiated.') target_sim = CommonSimUtils.get_sim_instance(target_sim_info) if target_sim is None: return CommonTestResult(False, reason=f'Posture test failed because the {target_sim_info} is non-instantiated.') posture_instance = cls.load_posture_by_id(posture) if posture_instance is None: return CommonTestResult(False, reason=f'No posture was found with id.') for aspect in cls.get_posture_aspects(sim_info): if aspect.posture_type is posture_instance and (not posture_instance.multi_sim or aspect.linked_sim is target_sim): break return CommonTestResult(False, reason=f'{sim_info} does not have posture {posture_instance}.') @classmethod def can_sim_be_picked_up(cls, sim_info: SimInfo) -> CommonTestResult: """can_be_picked_up(sim_info) Determine if a Sim can be picked up. :param sim_info: An instance of a Sim. :type sim_info: SimInfo :return: True, if the Sim can be picked up. False, it not. :rtype: bool """ from sims4communitylib.utils.sims.common_species_utils import CommonSpeciesUtils from sims4communitylib.utils.sims.common_age_utils import CommonAgeUtils if CommonSpeciesUtils.is_fox(sim_info) or CommonSpeciesUtils.is_small_dog(sim_info) or CommonSpeciesUtils.is_cat(sim_info): cls.get_log().format_with_message('Success, Sim is a fox, small dog, or cat and thus may be picked up.', sim=sim_info) return CommonTestResult.TRUE if CommonSpeciesUtils.is_animal(sim_info) and CommonAgeUtils.is_child(sim_info): cls.get_log().format_with_message('Success, Sim is a child animal and thus may be picked up.', sim=sim_info) return CommonTestResult.TRUE if CommonSpeciesUtils.is_human(sim_info) and (CommonAgeUtils.is_toddler(sim_info) or CommonAgeUtils.is_baby(sim_info)): cls.get_log().format_with_message('Success, Sim is a toddler or baby human and thus may be picked up.', sim=sim_info) return CommonTestResult.TRUE from sims4communitylib.enums.strings_enum import CommonStringId return CommonTestResult(False, reason=f'{sim_info} cannot be picked up.', tooltip_text=CommonStringId.S4CL_SIM_CANNOT_BE_PICKED_UP, tooltip_tokens=(sim_info,)) @classmethod def is_on_container_supporting_posture(cls, sim_info: SimInfo, posture: Union[int, CommonPostureId, Posture, CommonInt]) -> CommonTestResult: """is_on_container_supporting_posture(sim_info, posture) Determine if the container a Sim is interacting with has a posture. :param sim_info: An instance of a Sim. :type sim_info: SimInfo :param posture: The identifier of the posture to check. :type posture: Union[int, CommonPostureId, Posture, CommonInt] """ sim = CommonSimUtils.get_sim_instance(sim_info) if sim is None: return CommonTestResult(False, reason=f'Posture test failed because the {sim_info} is non-instantiated.') posture_instance = cls.load_posture_by_id(posture) if posture_instance is None: return CommonTestResult(False, reason=f'No posture was found with id.') container = cls.get_posture_target(sim_info) if container is None or not container.is_part: sim_posture = cls.get_posture(sim_info) return CommonTestResult(False, reason=f'Posture container for {sim_posture} is None or not a part') parts = {container} parts.update(container.get_overlapping_parts()) for container_part in parts: if container_part.supports_posture_type(posture_instance): return CommonTestResult.TRUE return CommonTestResult(False, reason=f'Posture container {container} does not support {posture_instance}') @classmethod def is_on_container_supporting_posture_with_sim(cls, sim_info: SimInfo, target_sim_info: SimInfo, posture: Union[int, CommonPostureId, Posture, CommonInt]) -> CommonTestResult: """is_on_container_supporting_posture(sim_info, target_sim_info, posture) Determine if the container a Sim is interacting with has a posture that supports another Sim. :param sim_info: An instance of a Sim. :type sim_info: SimInfo :param target_sim_info: An instance of another Sim. :type target_sim_info: SimInfo :param posture: The identifier of the posture to check. :type posture: Union[int, CommonPostureId, Posture, CommonInt] """ sim = CommonSimUtils.get_sim_instance(sim_info) if sim is None: return CommonTestResult(False, reason=f'Posture test failed because the {sim_info} is non-instantiated.') target_sim = CommonSimUtils.get_sim_instance(target_sim_info) if target_sim is None: return CommonTestResult(False, reason=f'Posture test failed because the {target_sim_info} is non-instantiated.') posture_instance = cls.load_posture_by_id(posture) if posture_instance is None: return CommonTestResult(False, reason=f'No posture was found with id.') container = cls.get_posture_target(sim_info) if container is None or not container.is_part: sim_posture = cls.get_posture(sim_info) return CommonTestResult(False, reason=f'Posture container for {sim_posture} is None or not a part') parts = {container} parts.update(container.get_overlapping_parts()) if not any(container_parts.supports_posture_type(posture_instance) for container_parts in parts): return CommonTestResult(False, reason=f'Posture container {container} does not support {posture_instance}') if posture_instance.multi_sim: if target_sim is None: return CommonTestResult(False, reason=f'Posture test failed because the target is None') if target_sim is None: return CommonTestResult(False, reason=f'Posture test failed because the target is non-instantiated.') if not container.has_adjacent_part(target_sim): return CommonTestResult(False, reason=f'Posture container {container} requires an adjacent part for {target_sim} since {posture_instance} is multi-Sim') return CommonTestResult.TRUE @classmethod def get_posture_target(cls, sim_info: SimInfo) -> Union[Any, None]: """get_posture_target(sim_info) Retrieve the target of the posture of a Sim. :param sim_info: An instance of a Sim. :type sim_info: SimInfo :return: The target of the posture of a Sim. :rtype: Union[Any, None] """ posture = cls.get_posture(sim_info) if posture is None: return None return posture.target @classmethod def get_posture(cls, sim_info: SimInfo) -> Union[Posture, None]: """get_posture(sim_info) Retrieve the posture of a Sim. :param sim_info: An instance of a Sim. :type sim_info: SimInfo :return: The posture of a Sim. :rtype: Union[Posture, None] """ sim = CommonSimUtils.get_sim_instance(sim_info) if sim is None: return None return sim.posture @classmethod def get_posture_aspects(cls, sim_info: SimInfo) -> Tuple[Posture]: """get_posture_aspects(sim_info) Retrieve the posture aspects of a Sim. :param sim_info: An instance of a Sim. :type sim_info: SimInfo :return: The aspects of the posture of the Sim. :rtype: Tuple[Posture] """ posture_state = cls.get_posture_state(sim_info) if posture_state is None: return tuple() return posture_state.aspects @classmethod def get_posture_state(cls, sim_info: SimInfo) -> Union[PostureState, None]: """get_posture_state(sim_info) Retrieve the posture aspects of a Sim. :param sim_info: An instance of a Sim. :type sim_info: SimInfo :return: The posture state of a Sim. :rtype: Union[PostureState, None] """ sim = CommonSimUtils.get_sim_instance(sim_info) if sim is None: return None # noinspection PyPropertyAccess return sim.posture_state @classmethod def load_posture_by_id(cls, posture: Union[int, CommonPostureId, Posture, CommonInt]) -> Union[Posture, None]: """load_posture_by_id(posture) Load an instance of a Posture by its identifier. :param posture: The identifier of a Posture. :type posture: Union[int, CommonPostureId, Posture, CommonInt] :return: An instance of a Posture matching the decimal identifier or None if not found. :rtype: Union[Posture, None] """ if isinstance(posture, Posture): return posture # noinspection PyBroadException try: # noinspection PyCallingNonCallable posture_instance = posture() if isinstance(posture_instance, Posture): return posture except: pass # noinspection PyBroadException try: posture: int = int(posture) except: # noinspection PyTypeChecker posture: Posture = posture return posture from sims4.resources import Types from sims4communitylib.utils.common_resource_utils import CommonResourceUtils return CommonResourceUtils.load_instance(Types.POSTURE, posture)
a4e87d3fbf5daf9bafa306e7e3ed00ae74f7e018
13cccbc1bbaec02f53d2f4e654d480512f6c2bb5
/binary-search/leetcode-tutorial/Search_in_Rotated_Sorted_Array.py
5d641e52117e3dc735343227c664d4231e10097f
[]
no_license
sjdeak/interview-practice
580cc61ec0d20d548bbc1e9ebebb4a64cd7ac2dc
1746aaf5ab06603942f9c85c360e319c110d4df8
refs/heads/master
2020-07-20T21:06:23.864208
2019-09-08T10:54:16
2019-09-08T10:54:16
206,709,284
2
0
null
null
null
null
UTF-8
Python
false
false
2,079
py
# https://leetcode.com/explore/learn/card/binary-search/125/template-i/952/ import os, sys, shutil, glob, re import time, calendar from datetime import datetime, timezone import hashlib, zipfile, zlib from math import * from operator import itemgetter from functools import wraps, cmp_to_key from itertools import count, combinations, permutations from collections import namedtuple, defaultdict, Counter from queue import Queue def refreshGlobals(): pass refreshGlobals() def binarySearch(left, right, nums, target): if len(nums) == 0: return -1 while left <= right: mid = (left + right) // 2 if nums[mid] == target: return mid elif nums[mid] < target: left = mid + 1 else: right = mid - 1 return -1 def findPivot(nums): left, right = 0, len(nums) - 1 leftMin, rightMax = nums[0], nums[-1] if leftMin < rightMax: return 0 while left < right: mid = left + (right - left) // 2 if nums[mid] >= leftMin: left = mid + 1 else: right = mid return left class Solution(object): def search(self, nums, target): """ :type nums: List[int] :type target: int :rtype: int """ if not nums: return -1 left, right = None, None leftMin, rightMax = nums[0], nums[-1] if leftMin <= rightMax: # 不分左右端 left, right = 0, len(nums) - 1 else: pivot = findPivot(nums) if target >= nums[0]: # >= 左端最小值 则target在左端 left, right = 0, pivot - 1 else: # 否则在右端 left, right = pivot, len(nums) - 1 return binarySearch(left, right, nums, target) if __name__ == '__main__' and ('SJDEAK' in os.environ): from utils.tree import TreeNode, array2TreeNode def test(*args): print('输入数据: ', *args) print('结果: ', Solution().search(*args), end='\n-----\n') test([4, 5, 6, 7, 0, 1, 2], 0) test([4, 5, 6, 7, 0, 1, 2], 3) test([0, 1, 2, 4, 5, 6, 7], 3) test([1, 2, 4, 5, 6, 7, 0], 7) test([], 7) test([1], 1) else: print = lambda *args, **kwargs: None
349b2be9f926e5186d63da726ea61cc465eb15c3
a685fa36823caa4b910969e80adbcae4f2829bd6
/python_Fundamentals/Find_Characters.py
70a7927579c0dbc033b28e77130ce161b8d75be1
[]
no_license
hmp36/Python
35e4fbc003b216ca6c7c45c558dd4f24edba5b9a
dcddf40a0428542d78f2e32d4755b54ebdaadffd
refs/heads/master
2021-09-15T01:35:41.013949
2018-05-23T13:05:59
2018-05-23T13:05:59
112,358,856
1
0
null
null
null
null
UTF-8
Python
false
false
302
py
#find_characters def find_character(word_list, char): new_list = [] for i in range(0, len(word_list)): if word_list[i].find(char) != -1: new_list.append(word_list[i]) print new_list test_list = ['hello','world','my','name','is','Hagan'] find_character(test_list,'o')
f3cea51fa24ed1b3bcff3995d808663d8a4aad6a
28e8ff11d8d4d633e9bd69390eb8504dc52d34ac
/python/paddle/optimizer/adamw.py
a5cb779835327a8c8dfdd02a1b62e87d3aa11988
[ "Apache-2.0" ]
permissive
zhupengyang/Paddle
1cda899a18de8725bfbbcedfcf45bce0bc2706a7
226b4a95df0c992dfaf37cca2c0e89eb730dd298
refs/heads/develop
2023-08-30T22:09:01.452182
2023-03-01T09:35:50
2023-03-01T09:35:50
186,746,928
0
0
Apache-2.0
2023-07-19T01:56:42
2019-05-15T04:05:53
C++
UTF-8
Python
false
false
26,979
py
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import warnings from collections import defaultdict from collections.abc import Callable import paddle from .. import _C_ops from ..fluid import core, framework, unique_name from ..fluid.dygraph import base as imperative_base from ..fluid.framework import Parameter, Variable from ..fluid.layer_helper import LayerHelper from ..nn.clip import GradientClipBase from .lr import LRScheduler from .optimizer import Optimizer __all__ = [] class AdamW(Optimizer): r""" The AdamW optimizer is implemented based on the AdamW Optimization in paper `DECOUPLED WEIGHT DECAY REGULARIZATION <https://arxiv.org/pdf/1711.05101.pdf>`_. it can resolves the problem of L2 regularization failure in the Adam optimizer. .. math:: t & = t + 1 moment\_1\_out & = {\beta}_1 * moment\_1 + (1 - {\beta}_1) * grad moemnt\_2\_out & = {\beta}_2 * moment\_2 + (1 - {\beta}_2) * grad * grad learning\_rate & = learning\_rate * \frac{\sqrt{1 - {\beta}_2^t}}{1 - {beta}_1^t} param\_out & = param - learning\_rate * (\frac{moment\_1}{\sqrt{moment\_2} + \epsilon} + \lambda * param) Args: learning_rate (float|LRScheduler, optional): The learning rate used to update ``Parameter``. It can be a float value or a LRScheduler. The default value is 0.001. parameters (list|tuple, optional): List/Tuple of ``Tensor`` names to update to minimize ``loss``. This parameter is required in dygraph mode. And you can specify different options for different parameter groups such as the learning rate, weight decay, etc, then the parameters are list of dict. Note that the learning_rate in paramter groups represents the scale of base learning_rate. The default value is None in static graph mode, at this time all parameters will be updated. beta1 (float|Tensor, optional): The exponential decay rate for the 1st moment estimates. It should be a float number or a Tensor with shape [1] and data type as float32. The default value is 0.9. beta2 (float|Tensor, optional): The exponential decay rate for the 2nd moment estimates. It should be a float number or a Tensor with shape [1] and data type as float32. The default value is 0.999. epsilon (float, optional): A small float value for numerical stability. The default value is 1e-08. weight_decay (float|Tensor, optional): The weight decay coefficient, it can be float or Tensor. The default value is 0.01. lr_ratio (function|None, optional): If it is not None, the learning rate will be updated with layerwise learning rate ratio. Otherwise, the learning rate is the original. Default: None. apply_decay_param_fun (function|None, optional): If it is not None, only tensors that makes apply_decay_param_fun(Tensor.name)==True will be updated with weight decay. It only works when we want to specify tensors. Default: None. grad_clip (GradientClipBase, optional): Gradient cliping strategy, it's an instance of some derived class of ``GradientClipBase`` . There are three cliping strategies ( :ref:`api_fluid_clip_GradientClipByGlobalNorm` , :ref:`api_fluid_clip_GradientClipByNorm` , :ref:`api_fluid_clip_GradientClipByValue` ). Default None, meaning there is no gradient clipping. lazy_mode (bool, optional): The official Adam algorithm has two moving-average accumulators. The accumulators are updated at every step. Every element of the two moving-average is updated in both dense mode and sparse mode. If the size of parameter is very large, then the update may be very slow. The lazy mode only update the element that has gradient in current mini-batch, so it will be much more faster. But this mode has different semantics with the original Adam algorithm and may lead to different result. The default value is False. multi_precision (bool, optional): Whether to use multi-precision during weight updating. Default is false. name (str, optional): Normally there is no need for user to set this property. For more information, please refer to :ref:`api_guide_Name`. The default value is None. **Notes**: **Currently, AdamW doesn't support sparse parameter optimization.** Examples: .. code-block:: python import paddle linear = paddle.nn.Linear(10, 10) inp = paddle.rand([10,10], dtype="float32") out = linear(inp) loss = paddle.mean(out) beta1 = paddle.to_tensor([0.9], dtype="float32") beta2 = paddle.to_tensor([0.99], dtype="float32") opt = paddle.optimizer.AdamW(learning_rate=0.1, parameters=linear.parameters(), beta1=beta1, beta2=beta2, weight_decay=0.01) out.backward() opt.step() opt.clear_grad() #Note that the learning_rate of linear_2 is 0.01. linear_1 = paddle.nn.Linear(10, 10) linear_2 = paddle.nn.Linear(10, 10) inp = paddle.uniform(shape=[10, 10], min=-0.1, max=0.1) out = linear_1(inp) out = linear_2(out) loss = paddle.mean(out) opt = paddle.optimizer.AdamW( learning_rate=0.1, parameters=[{ 'params': linear_1.parameters() }, { 'params': linear_2.parameters(), 'weight_decay': 0.001, 'learning_rate': 0.1, 'beta1': 0.8 }], weight_decay=0.01, beta1=0.9) out.backward() opt.step() opt.clear_grad() """ _moment1_acc_str = "moment1" _moment2_acc_str = "moment2" _beta1_pow_acc_str = "beta1_pow_acc" _beta2_pow_acc_str = "beta2_pow_acc" def __init__( self, learning_rate=0.001, beta1=0.9, beta2=0.999, epsilon=1e-8, parameters=None, weight_decay=0.01, lr_ratio=None, apply_decay_param_fun=None, grad_clip=None, lazy_mode=False, multi_precision=False, name=None, ): assert learning_rate is not None assert beta1 is not None assert beta2 is not None assert epsilon is not None if not 0 <= beta1 < 1: raise ValueError("Invaild value of beta1, expect beta1 in [0,1).") if not 0 <= beta2 < 1: raise ValueError("Invaild value of beta2, expect beta2 in [0,1).") if not 0 <= epsilon: raise ValueError("Invaild value of epsilon, expect epsilon >= 0.") if not isinstance(weight_decay, float) and not isinstance( weight_decay, framework.Variable ): raise TypeError("weight_decay should be float or Tensor.") if lr_ratio is not None: assert isinstance(lr_ratio, Callable) if ( not core.is_compiled_with_cuda() and not core.is_compiled_with_xpu() ): raise NotImplementedError( "'lr_ratio' is unimplemented in CPU, and NPU" ) if parameters is not None: # paddle.Tensor is also iterable, so here we don't check whether # the input is iterable, if the input is paddle.Tensor, the # list(paddle.Tensor) will be a error value if isinstance(parameters, (paddle.Tensor, core.eager.Tensor)): raise TypeError( "`parameters` argument given to the optimizer should be " "an iterable of paddle Tensors, but got argument type is `{}`.".format( type(parameters) ) ) if isinstance(parameters, dict): raise TypeError( "`parameters` argument should not get dict type, " "if parameter groups is needed, please set `parameters`" " as list of dict" ) self._parameter_list = list(parameters) else: self._parameter_list = None self._name = name if framework._non_static_mode(): if self._parameter_list is None: raise AttributeError( "parameters argument given to the Optimizer should not be None in dygraph mode." ) if not isinstance(learning_rate, (float, LRScheduler)): raise TypeError( "learning rate should be float or LRScheduler, got %s here" % type(learning_rate) ) if grad_clip is not None: if not isinstance(grad_clip, GradientClipBase): raise TypeError( "'grad_clip' should be an instance of GradientClipBase's derived class" ) self._dtype = None # Infer the dtype form parameter if self._parameter_list: if isinstance(self._parameter_list[0], dict): for param_group in self._parameter_list: assert ( 'params' in param_group ), 'params should be set in parameters if parameter groups are optimized in different options' self._dtype = self._parameter_list[0]['params'][0].dtype else: self._dtype = self._parameter_list[0].dtype # each program should have a independent learning rate # program -> tensor(learning_rate) self._learning_rate_map = dict() # Dictionary of accumulators. Some optimizer subclasses need to # allocate and manage extra tensors associated with the parameters # to train. These tensors are called accumulators. # {accum_name : { paramter_name : accumulator_for_parameter, ...}, ...} self._accumulators = defaultdict(lambda: dict()) self.helper = None self._opti_name_list = [] self._accumulators_holder = {} self._param_device_map = dict() self.clear_gradients = self.clear_grad self.type = "adamw" self._learning_rate = learning_rate self._params_name = set() self._apply_decay_param_fun = apply_decay_param_fun self._weight_decay = weight_decay self._grad_clip = grad_clip self._lr_ratio = lr_ratio self._beta1 = beta1 self._beta2 = beta2 self._epsilon = epsilon self._lazy_mode = lazy_mode self._multi_precision = multi_precision self._master_weights = {} self._default_dict = { 'weight_decay': weight_decay, 'beta1': beta1, 'beta2': beta2, 'epsilon': epsilon, 'lazy_mode': lazy_mode, 'grad_clip': grad_clip, } self._param_groups = [] if self._parameter_list and isinstance(self._parameter_list[0], dict): for param_group in self._parameter_list: self._add_param_group(param_group.copy()) else: self._param_groups = self._parameter_list self._use_multi_tensor = None self.regularization = None self._auxiliary_vars = {} def _set_auxiliary_var(self, key, val): self._auxiliary_vars[key] = val def _get_auxiliary_var(self, key): if key in self._auxiliary_vars: return self._auxiliary_vars[key] else: return None def _add_param_group(self, param_group): """ Add a param group to parameter_list. Args: param_group (dict): The group of Tensors to be optimzed with different optimization options. """ params = param_group['params'] if isinstance(params, Parameter): param_group['params'] = [params] elif isinstance(params, set): raise TypeError( "optimizer parameters should be in ordered collections," "but received set, please use list instead." ) else: param_group['params'] = list(params) # Update optimization options for each groups for k, v in self._default_dict.items(): param_group.setdefault(k, v) param_set = set() for group in self._param_groups: param_set.update(set(group['params'])) if not param_set.isdisjoint(set(param_group['params'])): raise ValueError( "some parameters appear in more than one parameter group" ) for param in param_group['params']: param.optimize_attr['learning_rate'] = param_group.get( 'learning_rate', 1.0 ) self._param_groups.append(param_group) def _create_master_weight(self, param): if param.name in self._master_weights: var = self._master_weights[param.name] else: assert isinstance(self.helper, LayerHelper) var_name = param.name + "_fp32_master" var_name = unique_name.generate(var_name) var = paddle.static.create_global_var( name=var_name, shape=param.shape, value=0, dtype='float32', persistable=True, ) block = self.helper.startup_program.global_block() block.append_op( type="cast", inputs={"X": [param]}, outputs={"Out": [var]}, attrs={ "in_dtype": param.dtype, "out_dtype": core.VarDesc.VarType.FP32, }, ) self._master_weights[param.name] = var return var def _get_accumulator(self, name, param): """Utility function to fetch an accumulator for a parameter Args: name: name of the accumulator param: parameter variable for which accumulator is to be fetched Returns: accumulator variable for the parameter """ if self._name is not None: name = self._name + "_" + name find_master = self._multi_precision and self._is_dtype_fp16_or_bf16( param.dtype ) target_param = ( self._master_weights[param.name] if find_master else param ) target_name = target_param.name if ( name not in self._accumulators or target_name not in self._accumulators[name] ): raise Exception( "Accumulator {} does not exist for parameter {}".format( name, target_name ) ) return self._accumulators[name][target_name] def _add_moments_pows(self, p): acc_dtype = p.dtype if self._is_dtype_fp16_or_bf16(acc_dtype): acc_dtype = core.VarDesc.VarType.FP32 self._add_accumulator(self._moment1_acc_str, p, dtype=acc_dtype) self._add_accumulator(self._moment2_acc_str, p, dtype=acc_dtype) self._add_accumulator( name=self._beta1_pow_acc_str, param=p, dtype=acc_dtype, fill_value=0.9 if isinstance(self._beta1, Variable) else self._beta1, shape=[1], type=core.VarDesc.VarType.LOD_TENSOR, device='cpu', ) self._add_accumulator( name=self._beta2_pow_acc_str, param=p, dtype=acc_dtype, fill_value=0.999 if isinstance(self._beta2, Variable) else self._beta2, shape=[1], type=core.VarDesc.VarType.LOD_TENSOR, device='cpu', ) def _create_accumulators(self, block, parameters): assert isinstance(block, framework.Block) if isinstance(parameters, dict): parameters = self._update_param_group(parameters) # Create accumulator tensors for first and second moments for p in parameters: if self._multi_precision and self._is_dtype_fp16_or_bf16(p.dtype): master_p = self._create_master_weight(p) self._add_moments_pows(master_p) continue if ( self._is_dtype_fp16_or_bf16(p.dtype) and not self._multi_precision ): warnings.warn( "Accumulating with FP16 or BF16 in optimizer can lead to poor accuracy or slow convergence." "Consider using multi_precision=True option of the Adam optimizer." ) self._add_moments_pows(p) def _append_optimize_op(self, block, param_and_grad): assert isinstance(block, framework.Block) if isinstance(param_and_grad, dict): param_and_grad = self._update_param_group(param_and_grad) param, grad = param_and_grad # Whether we should do weight decay for the parameter. with_decay = True if ( self._apply_decay_param_fun is not None and not self._apply_decay_param_fun(param.name) ): with_decay = False moment1 = self._get_accumulator( self._moment1_acc_str, param_and_grad[0] ) moment2 = self._get_accumulator( self._moment2_acc_str, param_and_grad[0] ) beta1_pow_acc = self._get_accumulator( self._beta1_pow_acc_str, param_and_grad[0] ) beta2_pow_acc = self._get_accumulator( self._beta2_pow_acc_str, param_and_grad[0] ) find_master = self._multi_precision and self._is_dtype_fp16_or_bf16( param_and_grad[0].dtype ) master_weight = ( self._master_weights[param_and_grad[0].name] if find_master else None ) lr = self._create_param_lr(param_and_grad) # create the adamw optimize op if framework.in_dygraph_mode(): lr_ratio_ = ( 1.0 if self._lr_ratio is None else self._lr_ratio(param_and_grad[0]) ) _beta1 = ( self._beta1 if not isinstance(self._beta1, Variable) else self._beta1.numpy().item(0) ) _beta2 = ( self._beta2 if not isinstance(self._beta2, Variable) else self._beta2.numpy().item(0) ) found_inf = self._get_auxiliary_var('found_inf') _, _, _, _, _, _ = _C_ops.adamw_( param_and_grad[0], param_and_grad[1], lr, moment1, moment2, beta1_pow_acc, beta2_pow_acc, master_weight, found_inf, _beta1, _beta2, self._epsilon, lr_ratio_, self._weight_decay, with_decay, self._lazy_mode, 1000, find_master, False, ) return None else: inputs = { "Param": [param_and_grad[0]], "Grad": [param_and_grad[1]], "LearningRate": [lr], "Moment1": [moment1], "Moment2": [moment2], "Beta1Pow": [beta1_pow_acc], "Beta2Pow": [beta2_pow_acc], } # Pass found_inf to adamw, to skip update for not only param, but also momentum and beta_pow found_inf = self._get_auxiliary_var('found_inf') if found_inf: inputs['SkipUpdate'] = found_inf outputs = { "ParamOut": [param_and_grad[0]], "Moment1Out": [moment1], "Moment2Out": [moment2], "Beta1PowOut": [beta1_pow_acc], "Beta2PowOut": [beta2_pow_acc], } attrs = { "lazy_mode": self._lazy_mode, "min_row_size_to_use_multithread": 1000, "multi_precision": find_master, "with_decay": with_decay, "coeff": self._weight_decay, "lr_ratio": 1.0 if self._lr_ratio is None else self._lr_ratio(param_and_grad[0]), } if isinstance(self._beta1, Variable): inputs['Beta1Tensor'] = self._beta1 else: attrs['beta1'] = self._beta1 if isinstance(self._beta2, Variable): inputs['Beta2Tensor'] = self._beta2 else: attrs['beta2'] = self._beta2 if isinstance(self._epsilon, Variable): inputs['EpsilonTensor'] = self._epsilon else: attrs['epsilon'] = self._epsilon if find_master: inputs["MasterParam"] = master_weight outputs["MasterParamOut"] = master_weight adamw_op = block.append_op( type=self.type, inputs=inputs, outputs=outputs, attrs=attrs, stop_gradient=True, ) return adamw_op def __str__(self): return " ".join(["Weight Decay, params:", ",".join(self._params_name)]) @imperative_base.no_grad @framework.dygraph_only def step(self): """ Execute the optimizer and update parameters once. Returns: None Examples: .. code-block:: python import paddle a = paddle.rand([2,13], dtype="float32") linear = paddle.nn.Linear(13, 5) # This can be any optimizer supported by dygraph. opt = paddle.optimizer.AdamW(learning_rate = 0.01, parameters = linear.parameters()) out = linear(a) out.backward() opt.step() opt.clear_grad() """ if not isinstance(self._parameter_list[0], dict): params_grads = [] for param in self._parameter_list: if param.stop_gradient: continue if param._grad_ivar() is not None: grad_var = param._grad_ivar() if framework.in_dygraph_mode(): if ( hasattr(grad_var, "is_selected_rows") and grad_var.is_selected_rows() and self.regularization is not None ): raise RuntimeError( "AdamW don't support weight_decay with sparse parameters, please set it to None." ) else: if ( hasattr(grad_var, "_is_sparse") and grad_var._is_sparse() and self.regularization is not None ): raise RuntimeError( "AdamW don't support weight_decay with sparse parameters, please set it to None." ) params_grads.append((param, grad_var)) optimize_ops = self._apply_optimize( loss=None, startup_program=None, params_grads=params_grads ) else: # optimize parameters in groups for param_group in self._param_groups: params_grads = defaultdict(lambda: list()) for param in param_group['params']: if param.stop_gradient: continue if param._grad_ivar() is not None: grad_var = param._grad_ivar() if framework.in_dygraph_mode(): if ( hasattr(grad_var, "is_selected_rows") and grad_var.is_selected_rows() and self.regularization is not None ): raise RuntimeError( "AdamW don't support weight_decay with sparse parameters, please set it to None." ) else: if ( hasattr(grad_var, "_is_sparse") and grad_var._is_sparse() and self.regularization is not None ): raise RuntimeError( "AdamW don't support weight_decay with sparse parameters, please set it to None." ) params_grads['params'].append((param, grad_var)) params_grads.update( {k: v for k, v in param_group.items() if k != 'params'} ) self._apply_optimize( loss=None, startup_program=None, params_grads=params_grads ) def _update_param_group(self, parameters): self._beta1 = parameters.get('beta1', self._default_dict['beta1']) self._beta2 = parameters.get('beta2', self._default_dict['beta2']) self._epsilon = parameters.get('epsilon', self._default_dict['epsilon']) self._lazy_mode = parameters.get( 'lazy_mode', self._default_dict['lazy_mode'] ) self._weight_decay = parameters.get( 'weight_decay', self._default_dict['weight_decay'] ) parameters = parameters.get('params') return parameters
61723176d8f107f09aa921c5b13fd058568de260
85e27209a7df58f76ab0f9f2ed13b1c6ac31ffc9
/src_python/habitat_sim/utils/gfx_replay_utils.py
f4a40ecbd3f41db0fa440ce577fe25b83c0612c5
[ "CC-BY-4.0", "CC-BY-3.0", "MIT" ]
permissive
facebookresearch/habitat-sim
72a78877c412fef1d42a553f896654c71c54d245
6f46bccc1733f4cec30b89d994ac55df2b46eb4a
refs/heads/main
2023-09-03T00:17:30.809849
2023-08-29T16:06:16
2023-08-29T16:06:16
169,164,539
1,924
432
MIT
2023-09-14T17:12:21
2019-02-04T23:14:28
C++
UTF-8
Python
false
false
1,009
py
# Copyright (c) Meta Platforms, Inc. and its affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import magnum as mn import habitat_sim def add_node_user_transform(sim, node, name): translation = node.absolute_translation rot = mn.Quaternion(mn.Quaterniond(node.rotation)) while True: node = node.parent if not node: break try: rot = node.rotation * rot except AttributeError: # scene root has no rotation attribute break sim.gfx_replay_manager.add_user_transform_to_keyframe(name, translation, rot) def make_backend_configuration_for_playback( need_separate_semantic_scene_graph=False, ): backend_cfg = habitat_sim.SimulatorConfiguration() backend_cfg.scene_id = "NONE" # see Asset.h EMPTY_SCENE backend_cfg.force_separate_semantic_scene_graph = need_separate_semantic_scene_graph return backend_cfg
6001ba346612f6f193597608f08320170e40f44b
05f668036da3c4295b7f5282b7a7c9bd387bdd0b
/spiders/start.py
1df95b4204485539feeb2f92e43feb231c054bc9
[ "MIT" ]
permissive
ProgramRipper/biliob-spider
8ae476f7ab096734ac9c24c3318f98ee41af8c7f
2fe3d5fd91bb301dd0d0eb21d03153d6882f6bcf
refs/heads/master
2022-04-11T09:51:42.037081
2020-03-23T16:31:12
2020-03-23T16:31:12
312,482,354
0
0
MIT
2023-05-17T00:33:30
2020-11-13T05:32:19
null
UTF-8
Python
false
false
1,500
py
from time import sleep import datetime import schedule import psutil import os def find_procs_by_name(name): "Return a list of processes matching 'name'." ls = [] for process in psutil.process_iter(): try: for each in process.cmdline(): if name in each: ls.append(process.pid) break pass except Exception as e: pass return ls def delete_by_name(name): pids = find_procs_by_name(name) for pid in pids: os.kill(pid, 9) spiders = ['add_public_video.py', 'author_follow.py', 'author.py', 'video.py', 'new_author.py', 'new_video.py', 'tag.py'] weekly_spider = [ 'utils/keyword.py' ] daily_spiders = ['utils/keyword_author.py'] def check(): for each_spider_group in [spiders, weekly_spider]: for each_spider in each_spider_group: pid = find_procs_by_name(each_spider) if len(pid) == 0: run_spider(each_spider) pass def run_spider(spider): print('[{}] 重启 {}'.format(datetime.datetime.now(), spider)) delete_by_name(spider) cmd = 'nohup python {} 1>{}.log 2>&1 &'.format(spider, spider) os.system(cmd) pass schedule.every(10).seconds.do(check) schedule.every().day.at('09:00').do(run_spider, 'rank_add.py') schedule.every().day.at('03:00').do(run_spider, 'utils/keyword_author.py') schedule.every().wednesday.at('03:20').do(run_spider, 'utils/keyword.py') while True: schedule.run_pending() sleep(10)
ef2e356bf57c377f09b460ddb28b36cf239114ae
e23a4f57ce5474d468258e5e63b9e23fb6011188
/125_algorithms/_exercises/templates/_algorithms_challenges/hackerrank/HackerrankPractice-master/Algorithms/01. Warmup/008. Mini-Max Sum.py
426a1546f2599b3b1e1a4fc95470f8d1c9f0422f
[]
no_license
syurskyi/Python_Topics
52851ecce000cb751a3b986408efe32f0b4c0835
be331826b490b73f0a176e6abed86ef68ff2dd2b
refs/heads/master
2023-06-08T19:29:16.214395
2023-05-29T17:09:11
2023-05-29T17:09:11
220,583,118
3
2
null
2023-02-16T03:08:10
2019-11-09T02:58:47
Python
UTF-8
Python
false
false
162
py
# Problem: https://www.hackerrank.com/challenges/mini-max-sum/problem # Score: 10 arr l.. m..(i.., i.. ).s..())) print(s..(arr) - m..(arr), s..(arr) - m..(arr
18927a4d6c41ee8f5750ed1b5eee62ec6a794d33
bdccb54daf0d0b0a19fabfe9ea9b90fcfc1bdfbf
/Interview Preparation Kits/Interview Preparation Kit/Miscellaneous/Flipping Bits/flipping_bits.py
cd52f26938ced69241748542cf1618a1bdcac0d9
[ "MIT" ]
permissive
xuedong/hacker-rank
aba1ad8587bc88efda1e90d7ecfef8dbd74ccd68
1ee76899d555850a257a7d3000d8c2be78339dc9
refs/heads/master
2022-08-08T07:43:26.633759
2022-07-16T11:02:27
2022-07-16T11:02:27
120,025,883
1
0
null
null
null
null
UTF-8
Python
false
false
410
py
#!/bin/python3 import math import os import random import re import sys # Complete the flippingBits function below. def flippingBits(n): return ~n & 0xffffffff if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') q = int(input()) for q_itr in range(q): n = int(input()) result = flippingBits(n) fptr.write(str(result) + '\n') fptr.close()
8088e111feb0c6e373b52debc22c1789345ce61f
0a1f8957a798006deaa53d10d09f733fab1e6b05
/bin/Python27/Lib/site-packages/sympy/geometry/polygon.py
f6b974c4f784fa93cf0c61d1f0cdce8aaa951310
[ "LicenseRef-scancode-other-permissive" ]
permissive
metamorph-inc/meta-core
a89504ccb1ed2f97cc6e792ba52e3a6df349efef
bc7a05e04c7901f477fe553c59e478a837116d92
refs/heads/master
2023-03-07T02:52:57.262506
2023-03-01T18:49:49
2023-03-01T18:49:49
40,361,476
25
15
NOASSERTION
2023-01-13T16:54:30
2015-08-07T13:21:24
Python
UTF-8
Python
false
false
59,827
py
from sympy.core import Expr, S, sympify, oo, pi, Symbol, zoo from sympy.core.compatibility import as_int from sympy.functions.elementary.piecewise import Piecewise from sympy.functions.elementary.trigonometric import cos, sin, tan, sqrt from sympy.simplify import simplify, nsimplify from sympy.geometry.exceptions import GeometryError from sympy.matrices import Matrix from sympy.solvers import solve from sympy.utilities.iterables import has_variety, has_dups from entity import GeometryEntity from point import Point from ellipse import Circle from line import Line, Segment from util import _symbol import warnings class Polygon(GeometryEntity): """A two-dimensional polygon. A simple polygon in space. Can be constructed from a sequence of points or from a center, radius, number of sides and rotation angle. Parameters ========== vertices : sequence of Points Attributes ========== area angles perimeter vertices centroid sides Raises ====== GeometryError If all parameters are not Points. If the Polygon has intersecting sides. See Also ======== sympy.geometry.point.Point, sympy.geometry.line.Segment, Triangle Notes ===== Polygons are treated as closed paths rather than 2D areas so some calculations can be be negative or positive (e.g., area) based on the orientation of the points. Any consecutive identical points are reduced to a single point and any points collinear and between two points will be removed unless they are needed to define an explicit intersection (see examples). A Triangle, Segment or Point will be returned when there are 3 or fewer points provided. Examples ======== >>> from sympy import Point, Polygon, pi >>> p1, p2, p3, p4, p5 = [(0, 0), (1, 0), (5, 1), (0, 1), (3, 0)] >>> Polygon(p1, p2, p3, p4) Polygon(Point(0, 0), Point(1, 0), Point(5, 1), Point(0, 1)) >>> Polygon(p1, p2) Segment(Point(0, 0), Point(1, 0)) >>> Polygon(p1, p2, p5) Segment(Point(0, 0), Point(3, 0)) While the sides of a polygon are not allowed to cross implicitly, they can do so explicitly. For example, a polygon shaped like a Z with the top left connecting to the bottom right of the Z must have the point in the middle of the Z explicitly given: >>> mid = Point(1, 1) >>> Polygon((0, 2), (2, 2), mid, (0, 0), (2, 0), mid).area 0 >>> Polygon((0, 2), (2, 2), mid, (2, 0), (0, 0), mid).area -2 When the the keyword `n` is used to define the number of sides of the Polygon then a RegularPolygon is created and the other arguments are interpreted as center, radius and rotation. The unrotated RegularPolygon will always have a vertex at Point(r, 0) where `r` is the radius of the circle that circumscribes the RegularPolygon. Its method `spin` can be used to increment that angle. >>> p = Polygon((0,0), 1, n=3) >>> p RegularPolygon(Point(0, 0), 1, 3, 0) >>> p.vertices[0] Point(1, 0) >>> p.args[0] Point(0, 0) >>> p.spin(pi/2) >>> p.vertices[0] Point(0, 1) """ def __new__(cls, *args, **kwargs): if kwargs.get('n', 0): n = kwargs.pop('n') args = list(args) # return a virtual polygon with n sides if len(args) == 2: # center, radius args.append(n) elif len(args) == 3: # center, radius, rotation args.insert(2, n) return RegularPolygon(*args, **kwargs) vertices = [Point(a) for a in args] # remove consecutive duplicates nodup = [] for p in vertices: if nodup and p == nodup[-1]: continue nodup.append(p) if len(nodup) > 1 and nodup[-1] == nodup[0]: nodup.pop() # last point was same as first # remove collinear points unless they are shared points got = set() shared = set() for p in nodup: if p in got: shared.add(p) else: got.add(p) i = -3 while i < len(nodup) - 3 and len(nodup) > 2: a, b, c = sorted([nodup[i], nodup[i + 1], nodup[i + 2]]) if b not in shared and Point.is_collinear(a, b, c): nodup[i] = a nodup[i + 1] = None nodup.pop(i + 1) i += 1 vertices = filter(lambda x: x is not None, nodup) if len(vertices) > 3: rv = GeometryEntity.__new__(cls, *vertices, **kwargs) elif len(vertices) == 3: return Triangle(*vertices, **kwargs) elif len(vertices) == 2: return Segment(*vertices, **kwargs) else: return Point(*vertices, **kwargs) # reject polygons that have intersecting sides unless the # intersection is a shared point or a generalized intersection. # A self-intersecting polygon is easier to detect than a # random set of segments since only those sides that are not # part of the convex hull can possibly intersect with other # sides of the polygon...but for now we use the n**2 algorithm # and check all sides with intersection with any preceding sides hit = _symbol('hit') if not rv.is_convex: sides = rv.sides for i, si in enumerate(sides): pts = si[0], si[1] ai = si.arbitrary_point(hit) for j in xrange(i): sj = sides[j] if sj[0] not in pts and sj[1] not in pts: aj = si.arbitrary_point(hit) tx = (solve(ai[0] - aj[0]) or [S.Zero])[0] if tx.is_number and 0 <= tx <= 1: ty = (solve(ai[1] - aj[1]) or [S.Zero])[0] if (tx or ty) and ty.is_number and 0 <= ty <= 1: print ai, aj raise GeometryError("Polygon has intersecting sides.") return rv @property def area(self): """ The area of the polygon. Notes ===== The area calculation can be positive or negative based on the orientation of the points. See Also ======== sympy.geometry.ellipse.Ellipse.area Examples ======== >>> from sympy import Point, Polygon >>> p1, p2, p3, p4 = map(Point, [(0, 0), (1, 0), (5, 1), (0, 1)]) >>> poly = Polygon(p1, p2, p3, p4) >>> poly.area 3 """ area = 0 args = self.args for i in xrange(len(args)): x1, y1 = args[i - 1].args x2, y2 = args[i].args area += x1*y2 - x2*y1 return simplify(area) / 2 @property def angles(self): """The internal angle at each vertex. Returns ======= angles : dict A dictionary where each key is a vertex and each value is the internal angle at that vertex. The vertices are represented as Points. See Also ======== sympy.geometry.point.Point, sympy.geometry.line.LinearEntity.angle_between Examples ======== >>> from sympy import Point, Polygon >>> p1, p2, p3, p4 = map(Point, [(0, 0), (1, 0), (5, 1), (0, 1)]) >>> poly = Polygon(p1, p2, p3, p4) >>> poly.angles[p1] pi/2 >>> poly.angles[p2] acos(-4*sqrt(17)/17) """ def _isright(a, b, c): ba = b - a ca = c - a t_area = ba.x*ca.y - ca.x*ba.y return bool(t_area <= 0) # Determine orientation of points args = self.vertices cw = _isright(args[-1], args[0], args[1]) ret = {} for i in xrange(len(args)): a, b, c = args[i - 2], args[i - 1], args[i] ang = Line.angle_between(Line(b, a), Line(b, c)) if cw ^ _isright(a, b, c): ret[b] = 2*S.Pi - ang else: ret[b] = ang return ret @property def perimeter(self): """The perimeter of the polygon. Returns ======= perimeter : number or Basic instance See Also ======== sympy.geometry.line.Segment.length Examples ======== >>> from sympy import Point, Polygon >>> p1, p2, p3, p4 = map(Point, [(0, 0), (1, 0), (5, 1), (0, 1)]) >>> poly = Polygon(p1, p2, p3, p4) >>> poly.perimeter sqrt(17) + 7 """ p = 0 args = self.vertices for i in xrange(len(args)): p += args[i - 1].distance(args[i]) return simplify(p) @property def vertices(self): """The vertices of the polygon. Returns ======= vertices : tuple of Points Notes ===== When iterating over the vertices, it is more efficient to index self rather than to request the vertices and index them. Only use the vertices when you want to process all of them at once. This is even more important with RegularPolygons that calculate each vertex. See Also ======== sympy.geometry.point.Point Examples ======== >>> from sympy import Point, Polygon >>> p1, p2, p3, p4 = map(Point, [(0, 0), (1, 0), (5, 1), (0, 1)]) >>> poly = Polygon(p1, p2, p3, p4) >>> poly.vertices (Point(0, 0), Point(1, 0), Point(5, 1), Point(0, 1)) >>> poly.args[0] Point(0, 0) """ return self.args @property def centroid(self): """The centroid of the polygon. Returns ======= centroid : Point See Also ======== sympy.geometry.point.Point, sympy.geometry.util.centroid Examples ======== >>> from sympy import Point, Polygon >>> p1, p2, p3, p4 = map(Point, [(0, 0), (1, 0), (5, 1), (0, 1)]) >>> poly = Polygon(p1, p2, p3, p4) >>> poly.centroid Point(31/18, 11/18) """ A = 1/(6*self.area) cx, cy = 0, 0 args = self.args for i in xrange(len(args)): x1, y1 = args[i - 1].args x2, y2 = args[i].args v = x1*y2 - x2*y1 cx += v*(x1 + x2) cy += v*(y1 + y2) return Point(simplify(A*cx), simplify(A*cy)) @property def sides(self): """The line segments that form the sides of the polygon. Returns ======= sides : list of sides Each side is a Segment. Notes ===== The Segments that represent the sides are an undirected line segment so cannot be used to tell the orientation of the polygon. See Also ======== sympy.geometry.point.Point, sympy.geometry.line.Segment Examples ======== >>> from sympy import Point, Polygon >>> p1, p2, p3, p4 = map(Point, [(0, 0), (1, 0), (5, 1), (0, 1)]) >>> poly = Polygon(p1, p2, p3, p4) >>> poly.sides [Segment(Point(0, 0), Point(1, 0)), Segment(Point(1, 0), Point(5, 1)), Segment(Point(0, 1), Point(5, 1)), Segment(Point(0, 0), Point(0, 1))] """ res = [] args = self.vertices for i in xrange(-len(args), 0): res.append(Segment(args[i], args[i + 1])) return res def is_convex(self): """Is the polygon convex? A polygon is convex if all its interior angles are less than 180 degrees. Returns ======= is_convex : boolean True if this polygon is convex, False otherwise. See Also ======== sympy.geometry.util.convex_hull Examples ======== >>> from sympy import Point, Polygon >>> p1, p2, p3, p4 = map(Point, [(0, 0), (1, 0), (5, 1), (0, 1)]) >>> poly = Polygon(p1, p2, p3, p4) >>> poly.is_convex() True """ def _isright(a, b, c): ba = b - a ca = c - a t_area = simplify(ba.x*ca.y - ca.x*ba.y) return bool(t_area <= 0) # Determine orientation of points args = self.vertices cw = _isright(args[-2], args[-1], args[0]) for i in xrange(1, len(args)): if cw ^ _isright(args[i - 2], args[i - 1], args[i]): return False return True def encloses_point(self, p): """ Return True if p is enclosed by (is inside of) self. Notes ===== Being on the border of self is considered False. Parameters ========== p : Point Returns ======= encloses_point : True, False or None See Also ======== sympy.geometry.point.Point, sympy.geometry.ellipse.Ellipse.encloses_point Examples ======== >>> from sympy import Polygon, Point >>> from sympy.abc import t >>> p = Polygon((0, 0), (4, 0), (4, 4)) >>> p.encloses_point(Point(2, 1)) True >>> p.encloses_point(Point(2, 2)) False >>> p.encloses_point(Point(5, 5)) False References ========== [1] http://www.ariel.com.au/a/python-point-int-poly.html [2] http://local.wasp.uwa.edu.au/~pbourke/geometry/insidepoly/ """ p = Point(p) if p in self.vertices or any(p in s for s in self.sides): return False # move to p, checking that the result is numeric lit = [] for v in self.vertices: lit.append(v - p) # the difference is simplified if lit[-1].free_symbols: return None self = Polygon(*lit) # polygon closure is assumed in the following test but Polygon removes duplicate pts so # the last point has to be added so all sides are computed. Using Polygon.sides is # not good since Segments are unordered. args = self.args indices = range(-len(args), 1) if self.is_convex(): orientation = None for i in indices: a = args[i] b = args[i + 1] test = ((-a.y)*(b.x - a.x) - (-a.x)*(b.y - a.y)).is_negative if orientation is None: orientation = test elif test is not orientation: return False return True hit_odd = False p1x, p1y = args[0].args for i in indices[1:]: p2x, p2y = args[i].args if 0 > min(p1y, p2y): if 0 <= max(p1y, p2y): if 0 <= max(p1x, p2x): if p1y != p2y: xinters = (-p1y)*(p2x - p1x)/(p2y - p1y) + p1x if p1x == p2x or 0 <= xinters: hit_odd = not hit_odd p1x, p1y = p2x, p2y return hit_odd def arbitrary_point(self, parameter='t'): """A parameterized point on the polygon. The parameter, varying from 0 to 1, assigns points to the position on the perimeter that is that fraction of the total perimeter. So the point evaluated at t=1/2 would return the point from the first vertex that is 1/2 way around the polygon. Parameters ========== parameter : str, optional Default value is 't'. Returns ======= arbitrary_point : Point Raises ====== ValueError When `parameter` already appears in the Polygon's definition. See Also ======== sympy.geometry.point.Point Examples ======== >>> from sympy import Polygon, S, Symbol >>> t = Symbol('t', real=True) >>> tri = Polygon((0, 0), (1, 0), (1, 1)) >>> p = tri.arbitrary_point('t') >>> perimeter = tri.perimeter >>> s1, s2 = [s.length for s in tri.sides[:2]] >>> p.subs(t, (s1 + s2/2)/perimeter) Point(1, 1/2) """ t = _symbol(parameter) if t.name in (f.name for f in self.free_symbols): raise ValueError('Symbol %s already appears in object and cannot be used as a parameter.' % t.name) sides = [] perimeter = self.perimeter perim_fraction_start = 0 for s in self.sides: side_perim_fraction = s.length/perimeter perim_fraction_end = perim_fraction_start + side_perim_fraction pt = s.arbitrary_point(parameter).subs( t, (t - perim_fraction_start)/side_perim_fraction) sides.append((pt, (perim_fraction_start <= t < perim_fraction_end))) perim_fraction_start = perim_fraction_end return Piecewise(*sides) def plot_interval(self, parameter='t'): """The plot interval for the default geometric plot of the polygon. Parameters ========== parameter : str, optional Default value is 't'. Returns ======= plot_interval : list (plot interval) [parameter, lower_bound, upper_bound] Examples ======== >>> from sympy import Polygon >>> p = Polygon((0, 0), (1, 0), (1, 1)) >>> p.plot_interval() [t, 0, 1] """ t = Symbol(parameter, real=True) return [t, 0, 1] def intersection(self, o): """The intersection of two polygons. The intersection may be empty and can contain individual Points and complete Line Segments. Parameters ========== other: Polygon Returns ======= intersection : list The list of Segments and Points See Also ======== sympy.geometry.point.Point, sympy.geometry.line.Segment Examples ======== >>> from sympy import Point, Polygon >>> p1, p2, p3, p4 = map(Point, [(0, 0), (1, 0), (5, 1), (0, 1)]) >>> poly1 = Polygon(p1, p2, p3, p4) >>> p5, p6, p7 = map(Point, [(3, 2), (1, -1), (0, 2)]) >>> poly2 = Polygon(p5, p6, p7) >>> poly1.intersection(poly2) [Point(2/3, 0), Point(9/5, 1/5), Point(7/3, 1), Point(1/3, 1)] """ res = [] for side in self.sides: inter = side.intersection(o) if inter is not None: res.extend(inter) return res def distance(self, o): """ Returns the shortest distance between self and o. If o is a point, then self does not need to be convex. If o is another polygon self and o must be complex. Examples ======== >>> from sympy import Point, Polygon, RegularPolygon >>> p1, p2 = map(Point, [(0, 0), (7, 5)]) >>> poly = Polygon(*RegularPolygon(p1, 1, 3).vertices) >>> poly.distance(p2) sqrt(61) """ if isinstance(o, Point): dist = oo for side in self.sides: current = side.distance(o) if current == 0: return S.Zero elif current < dist: dist = current return dist elif isinstance(o, Polygon) and self.is_convex() and o.is_convex(): return self._do_poly_distance(o) raise NotImplementedError() def _do_poly_distance(self, e2): """ Calculates the least distance between the exteriors of two convex polygons e1 and e2. Does not check for the convexity of the polygons as this is checked by Polygon.distance. Notes ===== - Prints a warning if the two polygons possibly intersect as the return value will not be valid in such a case. For a more through test of intersection use intersection(). See Also ======== sympy.geometry.point.Point.distance Examples ======= >>> from sympy.geometry import Point, Polygon >>> square = Polygon(Point(0, 0), Point(0, 1), Point(1, 1), Point(1, 0)) >>> triangle = Polygon(Point(1, 2), Point(2, 2), Point(2, 1)) >>> square._do_poly_distance(triangle) sqrt(2)/2 Description of method used ========================== Method: [1] http://cgm.cs.mcgill.ca/~orm/mind2p.html Uses rotating calipers: [2] http://en.wikipedia.org/wiki/Rotating_calipers and antipodal points: [3] http://en.wikipedia.org/wiki/Antipodal_point """ e1 = self '''Tests for a possible intersection between the polygons and outputs a warning''' e1_center = e1.centroid e2_center = e2.centroid e1_max_radius = S.Zero e2_max_radius = S.Zero for vertex in e1.vertices: r = Point.distance(e1_center, vertex) if e1_max_radius < r: e1_max_radius = r for vertex in e2.vertices: r = Point.distance(e2_center, vertex) if e2_max_radius < r: e2_max_radius = r center_dist = Point.distance(e1_center, e2_center) if center_dist <= e1_max_radius + e2_max_radius: warnings.warn("Polygons may intersect producing erroneous output") ''' Find the upper rightmost vertex of e1 and the lowest leftmost vertex of e2 ''' e1_ymax = Point(0, -oo) e2_ymin = Point(0, oo) for vertex in e1.vertices: if vertex.y > e1_ymax.y or (vertex.y == e1_ymax.y and vertex.x > e1_ymax.x): e1_ymax = vertex for vertex in e2.vertices: if vertex.y < e2_ymin.y or (vertex.y == e2_ymin.y and vertex.x < e2_ymin.x): e2_ymin = vertex min_dist = Point.distance(e1_ymax, e2_ymin) ''' Produce a dictionary with vertices of e1 as the keys and, for each vertex, the points to which the vertex is connected as its value. The same is then done for e2. ''' e1_connections = {} e2_connections = {} for side in e1.sides: if side.p1 in e1_connections: e1_connections[side.p1].append(side.p2) else: e1_connections[side.p1] = [side.p2] if side.p2 in e1_connections: e1_connections[side.p2].append(side.p1) else: e1_connections[side.p2] = [side.p1] for side in e2.sides: if side.p1 in e2_connections: e2_connections[side.p1].append(side.p2) else: e2_connections[side.p1] = [side.p2] if side.p2 in e2_connections: e2_connections[side.p2].append(side.p1) else: e2_connections[side.p2] = [side.p1] e1_current = e1_ymax e2_current = e2_ymin support_line = Line(Point(S.Zero, S.Zero), Point(S.One, S.Zero)) ''' Determine which point in e1 and e2 will be selected after e2_ymin and e1_ymax, this information combined with the above produced dictionaries determines the path that will be taken around the polygons ''' point1 = e1_connections[e1_ymax][0] point2 = e1_connections[e1_ymax][1] angle1 = support_line.angle_between(Line(e1_ymax, point1)) angle2 = support_line.angle_between(Line(e1_ymax, point2)) if angle1 < angle2: e1_next = point1 elif angle2 < angle1: e1_next = point2 elif Point.distance(e1_ymax, point1) > Point.distance(e1_ymax, point2): e1_next = point2 else: e1_next = point1 point1 = e2_connections[e2_ymin][0] point2 = e2_connections[e2_ymin][1] angle1 = support_line.angle_between(Line(e2_ymin, point1)) angle2 = support_line.angle_between(Line(e2_ymin, point2)) if angle1 > angle2: e2_next = point1 elif angle2 > angle1: e2_next = point2 elif Point.distance(e2_ymin, point1) > Point.distance(e2_ymin, point2): e2_next = point2 else: e2_next = point1 ''' Loop which determins the distance between anti-podal pairs and updates the minimum distance accordingly. It repeats until it reaches the starting position. ''' while True: e1_angle = support_line.angle_between(Line(e1_current, e1_next)) e2_angle = pi - support_line.angle_between(Line(e2_current, e2_next)) if e1_angle < e2_angle: support_line = Line(e1_current, e1_next) e1_segment = Segment(e1_current, e1_next) min_dist_current = e1_segment.distance(e2_current) if min_dist_current.evalf() < min_dist.evalf(): min_dist = min_dist_current if e1_connections[e1_next][0] != e1_current: e1_current = e1_next e1_next = e1_connections[e1_next][0] else: e1_current = e1_next e1_next = e1_connections[e1_next][1] elif e1_angle > e2_angle: support_line = Line(e2_next, e2_current) e2_segment = Segment(e2_current, e2_next) min_dist_current = e2_segment.distance(e1_current) if min_dist_current.evalf() < min_dist.evalf(): min_dist = min_dist_current if e2_connections[e2_next][0] != e2_current: e2_current = e2_next e2_next = e2_connections[e2_next][0] else: e2_current = e2_next e2_next = e2_connections[e2_next][1] else: support_line = Line(e1_current, e1_next) e1_segment = Segment(e1_current, e1_next) e2_segment = Segment(e2_current, e2_next) min1 = e1_segment.distance(e2_next) min2 = e2_segment.distance(e1_next) min_dist_current = min(min1, min2) if min_dist_current.evalf() < min_dist.evalf(): min_dist = min_dist_current if e1_connections[e1_next][0] != e1_current: e1_current = e1_next e1_next = e1_connections[e1_next][0] else: e1_current = e1_next e1_next = e1_connections[e1_next][1] if e2_connections[e2_next][0] != e2_current: e2_current = e2_next e2_next = e2_connections[e2_next][0] else: e2_current = e2_next e2_next = e2_connections[e2_next][1] if e1_current == e1_ymax and e2_current == e2_ymin: break return min_dist def __eq__(self, o): if not isinstance(o, Polygon) or len(self.args) != len(o.args): return False # See if self can ever be traversed (cw or ccw) from any of its # vertices to match all points of o args = self.args oargs = o.args n = len(args) o0 = oargs[0] for i0 in xrange(n): if args[i0] == o0: if all(args[(i0 + i) % n] == oargs[i] for i in xrange(1, n)): return True if all(args[(i0 - i) % n] == oargs[i] for i in xrange(1, n)): return True return False def __hash__(self): return super(Polygon, self).__hash__() def __contains__(self, o): """ Return True if o is contained within the boundary lines of self.altitudes Parameters ========== other : GeometryEntity Returns ======= contained in : bool The points (and sides, if applicable) are contained in self. See Also ======== sympy.geometry.entity.GeometryEntity.encloses Examples ======== >>> from sympy import Line, Segment, Point >>> p = Point(0, 0) >>> q = Point(1, 1) >>> s = Segment(p, q*2) >>> l = Line(p, q) >>> p in q False >>> p in s True >>> q*3 in s False >>> s in l True """ if isinstance(o, Polygon): return self == o elif isinstance(o, Segment): return any(o in s for s in self.sides) elif isinstance(o, Point): if o in self.vertices: return True for side in self.sides: if o in side: return True return False class RegularPolygon(Polygon): """ A regular polygon. Such a polygon has all internal angles equal and all sides the same length. Parameters ========== center : Point radius : number or Basic instance The distance from the center to a vertex n : int The number of sides Attributes ========== vertices center radius rotation apothem interior_angle exterior_angle circumcircle incircle angles Raises ====== GeometryError If the `center` is not a Point, or the `radius` is not a number or Basic instance, or the number of sides, `n`, is less than three. Notes ===== A RegularPolygon can be instantiated with Polygon with the kwarg n. Regular polygons are instantiated with a center, radius, number of sides and a rotation angle. Whereas the arguments of a Polygon are vertices, the vertices of the RegularPolygon must be obtained with the vertices method. See Also ======== sympy.geometry.point.Point, Polygon Examples ======== >>> from sympy.geometry import RegularPolygon, Point >>> r = RegularPolygon(Point(0, 0), 5, 3) >>> r RegularPolygon(Point(0, 0), 5, 3, 0) >>> r.vertices[0] Point(5, 0) """ __slots__ = ['_n', '_center', '_radius', '_rot'] def __new__(self, c, r, n, rot=0, **kwargs): r, n, rot = sympify([r, n, rot]) c = Point(c) if not isinstance(r, Expr): raise GeometryError("r must be an Expr object, not %s" % r) if n.is_Number: as_int(n) # let an error raise if necessary if n < 3: raise GeometryError("n must be a >= 3, not %s" % n) obj = GeometryEntity.__new__(self, c, r, n, **kwargs) obj._n = n obj._center = c obj._radius = r obj._rot = rot return obj @property def args(self): """ Returns the center point, the radius, the number of sides, and the orientation angle. Examples ======== >>> from sympy import RegularPolygon, Point >>> r = RegularPolygon(Point(0, 0), 5, 3) >>> r.args (Point(0, 0), 5, 3, 0) """ return self._center, self._radius, self._n, self._rot def __str__(self): return 'RegularPolygon(%s, %s, %s, %s)' % tuple(self.args) def __repr__(self): return 'RegularPolygon(%s, %s, %s, %s)' % tuple(self.args) @property def area(self): """Returns the area. Examples ======== >>> from sympy.geometry import RegularPolygon >>> square = RegularPolygon((0, 0), 1, 4) >>> square.area 2 >>> _ == square.length**2 True """ c, r, n, rot = self.args return n*self.length**2/(4*tan(pi/n)) @property def length(self): """Returns the length of the sides. The half-length of the side and the apothem form two legs of a right triangle whose hypotenuse is the radius of the regular polygon. Examples ======== >>> from sympy.geometry import RegularPolygon >>> from sympy import sqrt >>> s = square_in_unit_circle = RegularPolygon((0, 0), 1, 4) >>> s.length sqrt(2) >>> sqrt((_/2)**2 + s.apothem**2) == s.radius True """ return self.radius*2*sin(pi/self._n) @property def center(self): """The center of the RegularPolygon This is also the center of the circumscribing circle. Returns ======= center : Point See Also ======== sympy.geometry.point.Point, sympy.geometry.ellipse.Ellipse.center Examples ======== >>> from sympy.geometry import RegularPolygon, Point >>> rp = RegularPolygon(Point(0, 0), 5, 4) >>> rp.center Point(0, 0) """ return self._center @property def circumcenter(self): """ Alias for center. Examples ======== >>> from sympy.geometry import RegularPolygon, Point >>> rp = RegularPolygon(Point(0, 0), 5, 4) >>> rp.circumcenter Point(0, 0) """ return self.center @property def radius(self): """Radius of the RegularPolygon This is also the radius of the circumscribing circle. Returns ======= radius : number or instance of Basic See Also ======== sympy.geometry.line.Segment.length, sympy.geometry.ellipse.Circle.radius Examples ======== >>> from sympy import Symbol >>> from sympy.geometry import RegularPolygon, Point >>> radius = Symbol('r') >>> rp = RegularPolygon(Point(0, 0), radius, 4) >>> rp.radius r """ return self._radius @property def circumradius(self): """ Alias for radius. Examples ======== >>> from sympy import Symbol >>> from sympy.geometry import RegularPolygon, Point >>> radius = Symbol('r') >>> rp = RegularPolygon(Point(0, 0), radius, 4) >>> rp.circumradius r """ return self.radius @property def rotation(self): """CCW angle by which the RegularPolygon is rotated Returns ======= rotation : number or instance of Basic Examples ======== >>> from sympy import pi >>> from sympy.geometry import RegularPolygon, Point >>> RegularPolygon(Point(0, 0), 3, 4, pi).rotation pi """ return self._rot @property def apothem(self): """The inradius of the RegularPolygon. The apothem/inradius is the radius of the inscribed circle. Returns ======= apothem : number or instance of Basic See Also ======== sympy.geometry.line.Segment.length, sympy.geometry.ellipse.Circle.radius Examples ======== >>> from sympy import Symbol >>> from sympy.geometry import RegularPolygon, Point >>> radius = Symbol('r') >>> rp = RegularPolygon(Point(0, 0), radius, 4) >>> rp.apothem sqrt(2)*r/2 """ return self.radius * cos(S.Pi/self._n) @property def inradius(self): """ Alias for apothem. Examples ======== >>> from sympy import Symbol >>> from sympy.geometry import RegularPolygon, Point >>> radius = Symbol('r') >>> rp = RegularPolygon(Point(0, 0), radius, 4) >>> rp.inradius sqrt(2)*r/2 """ return self.apothem @property def interior_angle(self): """Measure of the interior angles. Returns ======= interior_angle : number See Also ======== sympy.geometry.line.LinearEntity.angle_between Examples ======== >>> from sympy.geometry import RegularPolygon, Point >>> rp = RegularPolygon(Point(0, 0), 4, 8) >>> rp.interior_angle 3*pi/4 """ return (self._n - 2)*S.Pi/self._n @property def exterior_angle(self): """Measure of the exterior angles. Returns ======= exterior_angle : number See Also ======== sympy.geometry.line.LinearEntity.angle_between Examples ======== >>> from sympy.geometry import RegularPolygon, Point >>> rp = RegularPolygon(Point(0, 0), 4, 8) >>> rp.exterior_angle pi/4 """ return 2*S.Pi/self._n @property def circumcircle(self): """The circumcircle of the RegularPolygon. Returns ======= circumcircle : Circle See Also ======== circumcenter, sympy.geometry.ellipse.Circle Examples ======== >>> from sympy.geometry import RegularPolygon, Point >>> rp = RegularPolygon(Point(0, 0), 4, 8) >>> rp.circumcircle Circle(Point(0, 0), 4) """ return Circle(self.center, self.radius) @property def incircle(self): """The incircle of the RegularPolygon. Returns ======= incircle : Circle See Also ======== inradius, sympy.geometry.ellipse.Circle Examples ======== >>> from sympy.geometry import RegularPolygon, Point >>> rp = RegularPolygon(Point(0, 0), 4, 8) >>> rp.incircle Circle(Point(0, 0), 4*cos(pi/8)) """ return Circle(self.center, self.apothem) @property def angles(self): """ Returns a dictionary with keys, the vertices of the Polygon, and values, the interior angle at each vertex. Examples ======== >>> from sympy import RegularPolygon, Point >>> r = RegularPolygon(Point(0, 0), 5, 3) >>> r.angles {Point(-5/2, -5*sqrt(3)/2): pi/3, Point(-5/2, 5*sqrt(3)/2): pi/3, Point(5, 0): pi/3} """ ret = {} ang = self.interior_angle for v in self.vertices: ret[v] = ang return ret def encloses_point(self, p): """ Return True if p is enclosed by (is inside of) self. Notes ===== Being on the border of self is considered False. The general Polygon.encloses_point method is called only if a point is not within or beyond the incircle or circumcircle, respectively. Parameters ========== p : Point Returns ======= encloses_point : True, False or None See Also ======== sympy.geometry.ellipse.Ellipse.encloses_point Examples ======== >>> from sympy import RegularPolygon, S, Point, Symbol >>> p = RegularPolygon((0, 0), 3, 4) >>> p.encloses_point(Point(0, 0)) True >>> r, R = p.inradius, p.circumradius >>> p.encloses_point(Point((r + R)/2, 0)) True >>> p.encloses_point(Point(R/2, R/2 + (R - r)/10)) False >>> t = Symbol('t', real=True) >>> p.encloses_point(p.arbitrary_point().subs(t, S.Half)) False >>> p.encloses_point(Point(5, 5)) False """ c = self.center d = Segment(c, p).length if d >= self.radius: return False elif d < self.inradius: return True else: # now enumerate the RegularPolygon like a general polygon. return Polygon.encloses_point(self, p) def spin(self, angle): """Increment *in place* the virtual Polygon's rotation by ccw angle. See also: rotate method which moves the center. >>> from sympy import Polygon, Point, pi >>> r = Polygon(Point(0,0), 1, n=3) >>> r.vertices[0] Point(1, 0) >>> r.spin(pi/6) >>> r.vertices[0] Point(sqrt(3)/2, 1/2) See Also ======== rotation rotate : Creates a copy of the RegularPolygon rotated about a Point """ self._rot += angle def rotate(self, angle, pt=None): """Override GeometryEntity.rotate to first rotate the RegularPolygon about its center. >>> from sympy import Point, RegularPolygon, Polygon, pi >>> t = RegularPolygon(Point(1, 0), 1, 3) >>> t.vertices[0] # vertex on x-axis Point(2, 0) >>> t.rotate(pi/2).vertices[0] # vertex on y axis now Point(0, 2) See Also ======== rotation spin : Rotates a RegularPolygon in place """ r = type(self)(*self.args) # need a copy or else changes are in-place r._rot += angle return GeometryEntity.rotate(r, angle, pt) def scale(self, x=1, y=1, pt=None): """Override GeometryEntity.scale since it is the radius that must be scaled (if x == y) or else a new Polygon must be returned. >>> from sympy import RegularPolygon Symmetric scaling returns a RegularPolygon: >>> RegularPolygon((0, 0), 1, 4).scale(2, 2) RegularPolygon(Point(0, 0), 2, 4, 0) Asymmetric scaling returns a kite as a Polygon: >>> RegularPolygon((0, 0), 1, 4).scale(2, 1) Polygon(Point(2, 0), Point(0, 1), Point(-2, 0), Point(0, -1)) """ if pt: pt = Point(pt) return self.translate(*(-pt).args).scale(x, y).translate(*pt.args) if x != y: return Polygon(*self.vertices).scale(x, y) c, r, n, rot = self.args r *= x return self.func(c, r, n, rot) @property def vertices(self): """The vertices of the RegularPolygon. Returns ======= vertices : list Each vertex is a Point. See Also ======== sympy.geometry.point.Point Examples ======== >>> from sympy.geometry import RegularPolygon, Point >>> rp = RegularPolygon(Point(0, 0), 5, 4) >>> rp.vertices [Point(5, 0), Point(0, 5), Point(-5, 0), Point(0, -5)] """ c = self._center r = self._radius rot = self._rot v = 2*S.Pi/self._n return [Point(c.x + r*cos(k*v + rot), c.y + r*sin(k*v + rot)) for k in xrange(self._n)] def __eq__(self, o): if not isinstance(o, Polygon): return False elif not isinstance(o, RegularPolygon): return Polygon.__eq__(o, self) return self.args == o.args def __hash__(self): return super(RegularPolygon, self).__hash__() class Triangle(Polygon): """ A polygon with three vertices and three sides. Parameters ========== points : sequence of Points keyword: asa, sas, or sss to specify sides/angles of the triangle Attributes ========== vertices altitudes orthocenter circumcenter circumradius circumcircle inradius incircle medians medial Raises ====== GeometryError If the number of vertices is not equal to three, or one of the vertices is not a Point, or a valid keyword is not given. See Also ======== sympy.geometry.point.Point, Polygon Examples ======== >>> from sympy.geometry import Triangle, Point >>> Triangle(Point(0, 0), Point(4, 0), Point(4, 3)) Triangle(Point(0, 0), Point(4, 0), Point(4, 3)) Keywords sss, sas, or asa can be used to give the desired side lengths (in order) and interior angles (in degrees) that define the triangle: >>> Triangle(sss=(3, 4, 5)) Triangle(Point(0, 0), Point(3, 0), Point(3, 4)) >>> Triangle(asa=(30, 1, 30)) Triangle(Point(0, 0), Point(1, 0), Point(1/2, sqrt(3)/6)) >>> Triangle(sas=(1, 45, 2)) Triangle(Point(0, 0), Point(2, 0), Point(sqrt(2)/2, sqrt(2)/2)) """ def __new__(cls, *args, **kwargs): if len(args) != 3: if 'sss' in kwargs: return _sss(*[nsimplify(a) for a in kwargs['sss']]) if 'asa' in kwargs: return _asa(*[nsimplify(a) for a in kwargs['asa']]) if 'sas' in kwargs: return _sas(*[nsimplify(a) for a in kwargs['sas']]) msg = "Triangle instantiates with three points or a valid keyword." raise GeometryError(msg) vertices = [Point(a) for a in args] # remove consecutive duplicates nodup = [] for p in vertices: if nodup and p == nodup[-1]: continue nodup.append(p) if len(nodup) > 1 and nodup[-1] == nodup[0]: nodup.pop() # last point was same as first # remove collinear points i = -3 while i < len(nodup) - 3 and len(nodup) > 2: a, b, c = sorted([nodup[i], nodup[i + 1], nodup[i + 2]]) if Point.is_collinear(a, b, c): nodup[i] = a nodup[i + 1] = None nodup.pop(i + 1) i += 1 vertices = filter(lambda x: x is not None, nodup) if len(vertices) == 3: return GeometryEntity.__new__(cls, *vertices, **kwargs) elif len(vertices) == 2: return Segment(*vertices, **kwargs) else: return Point(*vertices, **kwargs) @property def vertices(self): """The triangle's vertices Returns ======= vertices : tuple Each element in the tuple is a Point See Also ======== sympy.geometry.point.Point Examples ======== >>> from sympy.geometry import Triangle, Point >>> t = Triangle(Point(0, 0), Point(4, 0), Point(4, 3)) >>> t.vertices (Point(0, 0), Point(4, 0), Point(4, 3)) """ return self.args def is_similar(t1, t2): """Is another triangle similar to this one. Two triangles are similar if one can be uniformly scaled to the other. Parameters ========== other: Triangle Returns ======= is_similar : boolean See Also ======== sympy.geometry.entity.GeometryEntity.is_similar Examples ======== >>> from sympy.geometry import Triangle, Point >>> t1 = Triangle(Point(0, 0), Point(4, 0), Point(4, 3)) >>> t2 = Triangle(Point(0, 0), Point(-4, 0), Point(-4, -3)) >>> t1.is_similar(t2) True >>> t2 = Triangle(Point(0, 0), Point(-4, 0), Point(-4, -4)) >>> t1.is_similar(t2) False """ if not isinstance(t2, Polygon): return False s1_1, s1_2, s1_3 = [side.length for side in t1.sides] s2 = [side.length for side in t2.sides] def _are_similar(u1, u2, u3, v1, v2, v3): e1 = simplify(u1/v1) e2 = simplify(u2/v2) e3 = simplify(u3/v3) return bool(e1 == e2) and bool(e2 == e3) # There's only 6 permutations, so write them out return _are_similar(s1_1, s1_2, s1_3, *s2) or \ _are_similar(s1_1, s1_3, s1_2, *s2) or \ _are_similar(s1_2, s1_1, s1_3, *s2) or \ _are_similar(s1_2, s1_3, s1_1, *s2) or \ _are_similar(s1_3, s1_1, s1_2, *s2) or \ _are_similar(s1_3, s1_2, s1_1, *s2) def is_equilateral(self): """Are all the sides the same length? Returns ======= is_equilateral : boolean See Also ======== sympy.geometry.entity.GeometryEntity.is_similar, RegularPolygon is_isosceles, is_right, is_scalene Examples ======== >>> from sympy.geometry import Triangle, Point >>> t1 = Triangle(Point(0, 0), Point(4, 0), Point(4, 3)) >>> t1.is_equilateral() False >>> from sympy import sqrt >>> t2 = Triangle(Point(0, 0), Point(10, 0), Point(5, 5*sqrt(3))) >>> t2.is_equilateral() True """ return not has_variety(s.length for s in self.sides) def is_isosceles(self): """Are two or more of the sides the same length? Returns ======= is_isosceles : boolean See Also ======== is_equilateral, is_right, is_scalene Examples ======== >>> from sympy.geometry import Triangle, Point >>> t1 = Triangle(Point(0, 0), Point(4, 0), Point(2, 4)) >>> t1.is_isosceles() True """ return has_dups(s.length for s in self.sides) def is_scalene(self): """Are all the sides of the triangle of different lengths? Returns ======= is_scalene : boolean See Also ======== is_equilateral, is_isosceles, is_right Examples ======== >>> from sympy.geometry import Triangle, Point >>> t1 = Triangle(Point(0, 0), Point(4, 0), Point(1, 4)) >>> t1.is_scalene() True """ return not has_dups(s.length for s in self.sides) def is_right(self): """Is the triangle right-angled. Returns ======= is_right : boolean See Also ======== sympy.geometry.line.LinearEntity.is_perpendicular is_equilateral, is_isosceles, is_scalene Examples ======== >>> from sympy.geometry import Triangle, Point >>> t1 = Triangle(Point(0, 0), Point(4, 0), Point(4, 3)) >>> t1.is_right() True """ s = self.sides return Segment.is_perpendicular(s[0], s[1]) or \ Segment.is_perpendicular(s[1], s[2]) or \ Segment.is_perpendicular(s[0], s[2]) @property def altitudes(self): """The altitudes of the triangle. An altitude of a triangle is a segment through a vertex, perpendicular to the opposite side, with length being the height of the vertex measured from the line containing the side. Returns ======= altitudes : dict The dictionary consists of keys which are vertices and values which are Segments. See Also ======== sympy.geometry.point.Point, sympy.geometry.line.Segment.length Examples ======== >>> from sympy.geometry import Point, Triangle >>> p1, p2, p3 = Point(0, 0), Point(1, 0), Point(0, 1) >>> t = Triangle(p1, p2, p3) >>> t.altitudes[p1] Segment(Point(0, 0), Point(1/2, 1/2)) """ s = self.sides v = self.vertices return {v[0]: s[1].perpendicular_segment(v[0]), v[1]: s[2].perpendicular_segment(v[1]), v[2]: s[0].perpendicular_segment(v[2])} @property def orthocenter(self): """The orthocenter of the triangle. The orthocenter is the intersection of the altitudes of a triangle. It may lie inside, outside or on the triangle. Returns ======= orthocenter : Point See Also ======== sympy.geometry.point.Point Examples ======== >>> from sympy.geometry import Point, Triangle >>> p1, p2, p3 = Point(0, 0), Point(1, 0), Point(0, 1) >>> t = Triangle(p1, p2, p3) >>> t.orthocenter Point(0, 0) """ a = self.altitudes v = self.vertices return Line(a[v[0]]).intersection(Line(a[v[1]]))[0] @property def circumcenter(self): """The circumcenter of the triangle The circumcenter is the center of the circumcircle. Returns ======= circumcenter : Point See Also ======== sympy.geometry.point.Point Examples ======== >>> from sympy.geometry import Point, Triangle >>> p1, p2, p3 = Point(0, 0), Point(1, 0), Point(0, 1) >>> t = Triangle(p1, p2, p3) >>> t.circumcenter Point(1/2, 1/2) """ a,b,c = [x.perpendicular_bisector() for x in self.sides] return a.intersection(b)[0] @property def circumradius(self): """The radius of the circumcircle of the triangle. Returns ======= circumradius : number of Basic instance See Also ======== sympy.geometry.ellipse.Circle.radius Examples ======== >>> from sympy import Symbol >>> from sympy.geometry import Point, Triangle >>> a = Symbol('a') >>> p1, p2, p3 = Point(0, 0), Point(1, 0), Point(0, a) >>> t = Triangle(p1, p2, p3) >>> t.circumradius sqrt(a**2/4 + 1/4) """ return Point.distance(self.circumcenter, self.vertices[0]) @property def circumcircle(self): """The circle which passes through the three vertices of the triangle. Returns ======= circumcircle : Circle See Also ======== sympy.geometry.ellipse.Circle Examples ======== >>> from sympy.geometry import Point, Triangle >>> p1, p2, p3 = Point(0, 0), Point(1, 0), Point(0, 1) >>> t = Triangle(p1, p2, p3) >>> t.circumcircle Circle(Point(1/2, 1/2), sqrt(2)/2) """ return Circle(self.circumcenter, self.circumradius) def bisectors(self): """The angle bisectors of the triangle. An angle bisector of a triangle is a straight line through a vertex which cuts the corresponding angle in half. Returns ======= bisectors : dict Each key is a vertex (Point) and each value is the corresponding bisector (Segment). See Also ======== sympy.geometry.point.Point, sympy.geometry.line.Segment Examples ======== >>> from sympy.geometry import Point, Triangle, Segment >>> p1, p2, p3 = Point(0, 0), Point(1, 0), Point(0, 1) >>> t = Triangle(p1, p2, p3) >>> from sympy import sqrt >>> t.bisectors()[p2] == Segment(Point(0, sqrt(2) - 1), Point(1, 0)) True """ s = self.sides v = self.vertices c = self.incenter l1 = Segment(v[0], Line(v[0], c).intersection(s[1])[0]) l2 = Segment(v[1], Line(v[1], c).intersection(s[2])[0]) l3 = Segment(v[2], Line(v[2], c).intersection(s[0])[0]) return {v[0]: l1, v[1]: l2, v[2]: l3} @property def incenter(self): """The center of the incircle. The incircle is the circle which lies inside the triangle and touches all three sides. Returns ======= incenter : Point See Also ======== incircle, sympy.geometry.point.Point Examples ======== >>> from sympy.geometry import Point, Triangle >>> p1, p2, p3 = Point(0, 0), Point(1, 0), Point(0, 1) >>> t = Triangle(p1, p2, p3) >>> t.incenter Point(-sqrt(2)/2 + 1, -sqrt(2)/2 + 1) """ s = self.sides l = Matrix([s[i].length for i in [1, 2, 0]]) p = sum(l) v = self.vertices x = simplify(l.dot(Matrix([vi.x for vi in v]))/p) y = simplify(l.dot(Matrix([vi.y for vi in v]))/p) return Point(x, y) @property def inradius(self): """The radius of the incircle. Returns ======= inradius : number of Basic instance See Also ======== incircle, sympy.geometry.ellipse.Circle.radius Examples ======== >>> from sympy.geometry import Point, Triangle >>> p1, p2, p3 = Point(0, 0), Point(4, 0), Point(0, 3) >>> t = Triangle(p1, p2, p3) >>> t.inradius 1 """ return simplify(2 * self.area / self.perimeter) @property def incircle(self): """The incircle of the triangle. The incircle is the circle which lies inside the triangle and touches all three sides. Returns ======= incircle : Circle See Also ======== sympy.geometry.ellipse.Circle Examples ======== >>> from sympy.geometry import Point, Triangle >>> p1, p2, p3 = Point(0, 0), Point(2, 0), Point(0, 2) >>> t = Triangle(p1, p2, p3) >>> t.incircle Circle(Point(-sqrt(2) + 2, -sqrt(2) + 2), -sqrt(2) + 2) """ return Circle(self.incenter, self.inradius) @property def medians(self): """The medians of the triangle. A median of a triangle is a straight line through a vertex and the midpoint of the opposite side, and divides the triangle into two equal areas. Returns ======= medians : dict Each key is a vertex (Point) and each value is the median (Segment) at that point. See Also ======== sympy.geometry.point.Point.midpoint, sympy.geometry.line.Segment.midpoint Examples ======== >>> from sympy.geometry import Point, Triangle >>> p1, p2, p3 = Point(0, 0), Point(1, 0), Point(0, 1) >>> t = Triangle(p1, p2, p3) >>> t.medians[p1] Segment(Point(0, 0), Point(1/2, 1/2)) """ s = self.sides v = self.vertices return {v[0]: Segment(s[1].midpoint, v[0]), v[1]: Segment(s[2].midpoint, v[1]), v[2]: Segment(s[0].midpoint, v[2])} @property def medial(self): """The medial triangle of the triangle. The triangle which is formed from the midpoints of the three sides. Returns ======= medial : Triangle See Also ======== sympy.geometry.line.Segment.midpoint Examples ======== >>> from sympy.geometry import Point, Triangle >>> p1, p2, p3 = Point(0, 0), Point(1, 0), Point(0, 1) >>> t = Triangle(p1, p2, p3) >>> t.medial Triangle(Point(1/2, 0), Point(1/2, 1/2), Point(0, 1/2)) """ s = self.sides return Triangle(s[0].midpoint, s[1].midpoint, s[2].midpoint) #@property #def excircles(self): # """Returns a list of the three excircles for this triangle.""" # pass def rad(d): """Return the radian value for the given degrees (pi = 180 degrees).""" return d*pi/180 def deg(r): """Return the degree value for the given radians (pi = 180 degrees).""" return r/pi*180 def _slope(d): rv = tan(rad(d)) return rv def _asa(d1, l, d2): """Return triangle having side with length l on the x-axis.""" xy = Line((0, 0), slope=_slope(d1)).intersection( Line((l, 0), slope=_slope(180 - d2)))[0] return Triangle((0,0),(l,0),xy) def _sss(l1, l2, l3): """Return triangle having side of length l1 on the x-axis.""" c1 = Circle((0,0), l3) c2 = Circle((l1, 0), l2) inter = [a for a in c1.intersection(c2) if a.y.is_nonnegative] if not inter: return None pt = inter[0] return Triangle((0,0), (l1,0), pt) def _sas(l1, d, l2): """Return triangle having side with length l2 on the x-axis.""" p1 = Point(0, 0) p2 = Point(l2, 0) p3 = Point(cos(rad(d))*l1, sin(rad(d))*l1) return Triangle(p1, p2, p3)
796fb3923593aff09a76764b03a1b6e7e18b9a25
1990344218def595b8fe8a60d2367f8733289586
/Tape.py
ee1c22b1754b1f413c8732078cf15e7b640bfbea
[]
no_license
fortable1999/dynamicprogramming
7afd49a5bc8b2f92eb927581e718c57fdb040f51
976efa646cb16e40eb13772046e7d04ff109dc10
refs/heads/master
2020-04-09T15:31:08.153342
2018-12-06T02:17:51
2018-12-06T02:17:51
160,428,467
0
0
null
null
null
null
UTF-8
Python
false
false
379
py
import math def solution(A): # write your code in Python 3.6 left, right = A[0], sum(A[1:]) diff = abs(left - right) for elem in A[1:-1]: left += elem right -= elem if abs(left - right) < diff: diff = abs(left - right) return diff print(solution([-1, 1, 1000, -1])) print(solution([1, -1, -11])) print(solution([1, 2]))
8b63a29441cb9e8d2602e6259654e50e3ae5e4be
8da91c26d423bacbeee1163ac7e969904c7e4338
/pyvisdk/mo/guest_operations_manager.py
42811965f87e374b8b96d6972b7bd55e7f8b7f68
[]
no_license
pexip/os-python-infi-pyvisdk
5d8f3a3858cdd61fb76485574e74ae525cdc7e25
1aadea0afbc306d09f6ecb9af0e683dbbf961d20
refs/heads/master
2023-08-28T02:40:28.789786
2020-07-16T04:00:53
2020-07-16T04:00:53
10,032,240
0
1
null
null
null
null
UTF-8
Python
false
false
1,275
py
from pyvisdk.base.managed_object_types import ManagedObjectTypes from pyvisdk.base.base_entity import BaseEntity import logging ######################################## # Automatically generated, do not edit. ######################################## log = logging.getLogger(__name__) class GuestOperationsManager(BaseEntity): '''GuestOperationsManager is the managed object that provides APIs to manipulate the guest operating system files and process. Each class of APIs is separated into its own manager.''' def __init__(self, core, name=None, ref=None, type=ManagedObjectTypes.GuestOperationsManager): super(GuestOperationsManager, self).__init__(core, name=name, ref=ref, type=type) @property def authManager(self): '''A singleton managed object that provides methods for guest authentication operations.''' return self.update('authManager') @property def fileManager(self): '''A singleton managed object that provides methods for guest file operations.''' return self.update('fileManager') @property def processManager(self): '''A singleton managed object that provides methods for guest process operations.''' return self.update('processManager')
e33b7e0b004944fe986a82dc58d7668f0d622a18
15f321878face2af9317363c5f6de1e5ddd9b749
/solutions_python/Problem_136/1488.py
04ea069f2a72cc94a1d2641d3b845e5b20b5ece6
[]
no_license
dr-dos-ok/Code_Jam_Webscraper
c06fd59870842664cd79c41eb460a09553e1c80a
26a35bf114a3aa30fc4c677ef069d95f41665cc0
refs/heads/master
2020-04-06T08:17:40.938460
2018-10-14T10:12:47
2018-10-14T10:12:47
null
0
0
null
null
null
null
UTF-8
Python
false
false
598
py
# https://code.google.com/codejam/contest/2974486/dashboard#s=p1 import sys def readline(): return sys.stdin.readline().rstrip() f0 = 2 t = int(readline()) for case in range(t): line = readline() [c, f, x] = [float(s) for s in line.split()] time = x/f0 time2 = c/f0 + x/(f+f0) more = time2 < time factories = 0 n = 0 while more: factories = factories + c/(f*n+f0) time2 = factories + x/(f*(n+1)+f0) more = time2 < time time = min(time2, time) n = n+1 result = time print 'Case #{}: {}'.format(case+1, result)
6f8f55d475bcc0e553f442897fd874177c3d347c
2491df3f643539e6055bb0b2a4b659474c57491f
/interval.py
1c48b76451542d32868f5e00496c2a8e10df5e23
[]
no_license
ghilbing/Ejemplos
85efc91346028b8a3d26d7680d9286b26234c771
339a45ef48c9a61002a01f7c823cc42d34fab409
refs/heads/master
2021-05-13T13:58:33.010157
2018-02-26T20:44:44
2018-02-26T20:44:44
116,724,506
0
0
null
null
null
null
UTF-8
Python
false
false
1,199
py
def interval(intervals, new_interval): s = new_interval.start e = new_interval.end parts = merge = [] left = [] right = [] for i in intervals: parts[(i.end < s) - (i.start > e)].append(i) if merge: s = min(s, merge[0].start) e = max(e, merge[-1].end) return left + [Interval(s, e)] + right # Definition for an interval. class Interval: def __init__(self, s=0, e=0): self.start = s self.end = e intervals = [ (6037774, 6198243), (6726550, 7004541), (8842554, 10866536), (11027721, 11341296), (11972532, 14746848), (16374805, 16706396), (17557262, 20518214), (22139780, 22379559), (27212352, 28404611), (28921768, 29621583), (29823256, 32060921), (33950165, 36418956), (37225039, 37785557), (40087908, 41184444), (41922814, 45297414), (48142402, 48244133), (48622983, 50443163), (50898369, 55612831), (57030757, 58120901), (59772759, 59943999), (61141939, 64859907), (65277782, 65296274), (67497842, 68386607), (70414085, 73339545), (73896106, 75605861), (79672668, 84539434), (84821550, 86558001), (91116470, 92198054), (96147808, 98979097) ] new_interval = (36210193, 61984219) print interval(intervals, new_interval)
2f7e7080307ec0ae3515529e27fa46310cc9f7cb
a0a0932b6ab6ec47c2757d8929216790f5bc6535
/order/apps.py
63251174a40de7091e5dd63e488b3497605ea2bb
[]
no_license
lianglunzhong/latte-erp
b4e6e3b13c4bce17911ff166fecc36172e0bea5b
b58936c8d9917f3efdcb3585c54bfd3aba4723c2
refs/heads/master
2022-11-27T03:08:23.780124
2017-04-28T02:51:43
2017-04-28T02:51:43
89,660,834
0
0
null
2022-11-22T01:04:12
2017-04-28T02:48:50
Python
UTF-8
Python
false
false
179
py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.apps import AppConfig class OrderConfig(AppConfig): name = 'order' verbose_name = u"订单"
aa7e54c13f82ec435d13c5be8999b09e623f6ee0
e07b8420df6ebe15b0de68ca6889fcaa68d8fad3
/Keras/study/cross_entrophy.py
18e196f4acd85efa5fad1fc77cdf07724becf698
[]
no_license
AllenLiuX/Machine-Learning-Projects
2fcbb3dc3d8efee08de9d96020e551a9c0758fa6
ea20ea04cb956a9fb8f7099ddb7ec36ab5730cc2
refs/heads/master
2023-01-24T05:46:33.123993
2020-11-21T08:24:05
2020-11-21T08:24:05
299,807,064
0
0
null
null
null
null
UTF-8
Python
false
false
1,397
py
import numpy as np import matplotlib.pyplot as plt from keras.datasets import mnist from keras.utils import np_utils from keras.models import Sequential from keras.layers import Dense, Activation from keras.optimizers import SGD # (x_train, y_train), (x_test, y_test) = mnist.load_data() f = np.load('mnist.npz') x_train, y_train = f['x_train'], f['y_train'] x_test, y_test = f['x_test'], f['y_test'] f.close() # (x_train, y_train), (x_test, y_test) = np.load('mnist.npz') # (60000, 28, 28) print('x_shape:', x_train.shape) #60000 print('y_shape:', y_train.shape) #60000 # 60000, 28, 28 -> 60000, 784 x_train = x_train.reshape(x_train.shape[0], -1)/255.0 #/255 -> 均一化, -1表示自动计算行数 x_test = x_test.reshape(x_test.shape[0], -1)/255.0 #换one hot格式 y_train = np_utils.to_categorical(y_train, num_classes=10) y_test = np_utils.to_categorical(y_test, num_classes=10) # 创建模型 model = Sequential() model.add(Dense(units=10, input_dim=784, bias_initializer='one', activation='softmax')) sgd = SGD(lr=0.2) # 定义优化器,loss,训练过程中计算准确率 model.compile(optimizer=sgd, loss='categorical_crossentropy', metrics=['accuracy']) # 训练模型 model.fit(x_train, y_train, batch_size=32, epochs=10) # 评估模型 loss, accuracy = model.evaluate(x_test, y_test) print('\ntest loss', loss) print('accuracy', accuracy)
9ddb472d2ff2e53ba564d04caed1083c15bdb513
2033d6d7b9547c6722bfc9f52379683ebfca7186
/pbf_kao_gui/Commands/new_pygame_screen.py
e4d417e14846ac385b85c64668550296c079c27d
[]
no_license
cloew/KaoGUIPBF
5119e4f149343804d6e031b14d920a9e2229eb2b
819a908bccfd579c9d0666f216395d08e230353f
refs/heads/master
2021-01-01T20:16:57.033719
2015-02-17T16:39:51
2015-02-17T16:39:51
16,234,905
0
0
null
null
null
null
UTF-8
Python
false
false
1,039
py
from pbf.helpers.filename_helper import GetPythonClassnameFromFilename from pbf.templates.template_loader import TemplateLoader from pbf_kao_gui.templates import TemplatesRoot class NewPygameScreen: """ Command to Create a new Pygame Screen """ TEMPLATE_LOADER = TemplateLoader("pygame_screen.py", TemplatesRoot) def addArguments(self, parser): """ Add arguments to the parser """ parser.add_argument('destination', action='store', help='Destination for the new pygame screen') def run(self, arguments): """ Run the command """ screenFileName = arguments.destination screenName = GetPythonClassnameFromFilename(screenFileName) print "Creating Pygame Screen:", screenName, "at:", screenFileName self.createScreen(screenFileName, screenName) def createScreen(self, screenFileName, screenName): """ Create the widget file """ self.TEMPLATE_LOADER.copy(screenFileName, keywords={"%ScreenName%":screenName})
ebb2fa048817413a11e3f6b1fa17173e0b9a4846
95594364c548081b4f139b0fec2d2474d23129da
/Pretreatment/Audio/Step3_Assembly.py
a86b07697b9a6e3da8c5f926464515397e374d1f
[]
no_license
Grace-JingXiao/AVEC_2017_DDS_CNN_Research
0e932e2e5f38039dd2884595e6d75bc67da8e20a
71d04f3d765efb18f6dbe99eab3ef12e5e5f8489
refs/heads/master
2020-09-05T22:09:02.904761
2019-09-11T06:07:53
2019-09-11T06:07:53
220,227,983
1
0
null
2019-11-07T12:06:41
2019-11-07T12:06:40
null
UTF-8
Python
false
false
906
py
import numpy import os if __name__ == '__main__': loadpath = 'D:/PythonProjects_Data/AVEC2017-OtherFeatures/Step1_features3D/' savepath = 'D:/PythonProjects_Data/AVEC2017-OtherFeatures/Step3_features3D_Assembly/' os.makedirs(savepath) ususalShape = 0 for foldname in os.listdir(loadpath): totalData = [] for filename in os.listdir(os.path.join(loadpath, foldname)): if filename.find('Participant') == -1: continue data = numpy.genfromtxt(fname=os.path.join(loadpath, foldname, filename), dtype=float, delimiter=',') if ususalShape == 0: ususalShape = numpy.shape(data)[1] else: data = numpy.reshape(data, [-1, ususalShape]) totalData.extend(data) print(foldname, numpy.shape(totalData)) numpy.save(savepath + foldname + '.npy', totalData, allow_pickle=True)
8b332439a2fe2e912f9c5478e97e3bb5fc6ab0dd
08fe752455b2e8bea36f69bd7eb0d70641691514
/12월 3주차/[BAEKJOON] 12904_A와 B.py
abd5edb88c54b6248ff79f668d83207e4fb1c09a
[]
no_license
2020-ASW/gayoung_yoon
69a7a20c073710aaec76261cac59aa6541250588
0ad21c5484ed087d704d72b03fc1f14c3fa9e25f
refs/heads/main
2023-02-14T19:28:38.966502
2021-01-10T07:56:10
2021-01-10T07:56:10
320,287,097
0
0
null
null
null
null
UTF-8
Python
false
false
442
py
# S = "B" # T = "ABBA" # S = "AB" # T = "ABB" ''' 조건1 문자열의 뒤에 A를 추가한다. 조건2 문자열을 뒤집고 뒤에 B를 추가한다. S -> T를 확인하기 위해 T -> S로 변경가능한지 check! ''' S = list(input()) T = list(input()) while True: if len(S) == len(T): break if T[-1] == 'A': T.pop() else: T.pop() T = T[::-1] if S == T: print(1) else: print(0)
212953611e16a73c32f310c5769c10ea1a31a979
adb748ac7d24f6184ad81881d6caf5ea4689c38f
/spatialdata/units/NondimElasticQuasistatic.py
3e050ad231632b437bb4a2686b50c9bb5b8b973c
[ "MIT" ]
permissive
Zilhe/spatialdata
7a291703703cc2ff254cceec3683dc066925b5f4
fee0e77dcb820d466857a0e914af265255709285
refs/heads/main
2023-04-30T08:16:55.977142
2021-05-19T01:41:42
2021-05-19T01:41:42
null
0
0
null
null
null
null
UTF-8
Python
false
false
2,928
py
# ---------------------------------------------------------------------- # # Brad T. Aagaard, U.S. Geological Survey # # This code was developed as part of the Computational Infrastructure # for Geodynamics (http://geodynamics.org). # # Copyright (c) 2010-2017 University of California, Davis # # See COPYING for license information. # # ---------------------------------------------------------------------- # # @file spatialdata/units/NondimElasticQuasistatic.py # # @brief Python manager for nondimensionalizing quasi-static # elasticity problems. # # Factory: nondimensional from .Nondimensional import Nondimensional class NondimElasticQuasistatic(Nondimensional): """ Python manager for nondimensionalizing quasi-static elasticity problems. Factory: nondimensional INVENTORY Properties - *shear_modulus* Shear modules for pressure scale of problem. - *length_scale* Discretization size for length scale of problem. - *relaxation_time* Viscoelastic relaxation time for time scale of problem. Facilities - None """ import pythia.pyre.inventory from pythia.pyre.units.length import meter lengthScale = pythia.pyre.inventory.dimensional("length_scale", default=1.0e+3 * meter, validator=pythia.pyre.inventory.greater(0.0 * meter)) lengthScale.meta['tip'] = "Value to nondimensionalize length scale." from pythia.pyre.units.pressure import pascal shearModulus = pythia.pyre.inventory.dimensional("shear_modulus", default=3.0e+10 * pascal, validator=pythia.pyre.inventory.greater(0.0 * pascal)) shearModulus.meta['tip'] = "Shear modulus to nondimensionalize pressure." from pythia.pyre.units.time import year relaxationTime = pythia.pyre.inventory.dimensional("relaxation_time", default=100.0 * year, validator=pythia.pyre.inventory.greater(0.0 * year)) relaxationTime.meta['tip'] = "Relaxation time to nondimensionalize time." # PUBLIC METHODS ///////////////////////////////////////////////////// def __init__(self, name="nondimelasticquasistatic"): """ Constructor. """ Nondimensional.__init__(self, name) # PRIVATE METHODS //////////////////////////////////////////////////// def _configure(self): """ Setup members using inventory. """ Nondimensional._configure(self) self.setLengthScale(self.inventory.lengthScale) self.setPressureScale(self.inventory.shearModulus) self.setTimeScale(self.inventory.relaxationTime) self.computeDensityScale() # FACTORIES //////////////////////////////////////////////////////////// def nondimensional(): """ Factory associated with NondimElasticQuasistatic. """ return NondimElasticQuasistatic() # End of file
ee7531e0c603f1da58441201aa9edfb6ddd4b581
368be25e37bafa8cc795f7c9f34e4585e017091f
/.history/app_fav_books/views_20201115164620.py
ec1fa1c5ffa54349752a175c646dd05ab409740e
[]
no_license
steven-halla/fav_books_proj
ebcfbfda0e7f3cdc49d592c86c633b1d331da513
512005deb84ac906c9f24d4ab0939bd0db096716
refs/heads/master
2023-03-30T09:37:38.016063
2021-04-02T20:27:22
2021-04-02T20:27:22
354,125,658
0
0
null
null
null
null
UTF-8
Python
false
false
5,513
py
from django.shortcuts import render, redirect from .models import * from django.contrib import messages # contains user signup + login form def view_index(request): # bonus, if user is already logged in, lets not show them login/registration page, # and instead redirect them to /books, which is already where we redirect users # after they login/register. if 'user_id' in request.session: return redirect("/books") return render(request, "index.html") # user signup form will post to a url (/register) which maps to this function def register_new_user(request): # returns a dictionary of errors. # e.g. errors['first_name'] = 'letters only' errors = User.objects.user_registration_validator(request.POST) # iterate over each error (key/value) pair in the errors dictionary # and take the error key and value and makes a full error message, # and then adds the error message via messages.error() if len(errors) > 0: for key, value in errors.items(): error_msg = key + ' - ' + value messages.error(request, error_msg) return redirect("/") else: first_name_from_post = request.POST['first_name'] last_name_from_post = request.POST['last_name'] email_from_post = request.POST['email'] password_from_post = request.POST['password'] new_user = User.objects.create( first_name=first_name_from_post, last_name=last_name_from_post, email=email_from_post, password=password_from_post ) print(new_user.id) request.session['user_id'] = new_user.id return redirect('/books') def login(request): # user did provide email/password, now lets check database email_from_post = request.POST['email'] password_from_post = request.POST['password'] # this will return all users that have the email_from_post # in future we should require email to be unique users = User.objects.filter(email=email_from_post) if len(users) == 0: messages.error(request, "email/password does not exist") return redirect("/") user = users[0] print(user) # check that the user submitted password is the same as what we have stored in the database if (user.password != password_from_post): messages.error(request, "email/password does not exist") return redirect("/") # we store the logged in user's id in the session variable, # so that we can quickly get the current logged in user's id any time we need it in back end functions. # e.g. view_books when we look up the user by: User.objects.get(id=request.session['user_id']) # session variables are shared accors all of my requests # LEARN request.session['user_id'] = user.id return redirect("/books") def logout(request): request.session.clear() return redirect("/") # this will render view_books.html page. # this page will show a list of all the books and the current logged in user. def view_books(request): if 'user_id' not in request.session: return redirect("/") user = User.objects.get(id=request.session['user_id']) all_books_from_db = Books.objects.all() context = { "user": user, "all_books": all_books_from_db } return render(request, "view_books.html", context) # this will render view_book.html page. # this page will show a single book and the current logged in user. def view_book(request, book_id): if 'user_id' not in request.session: return redirect("/") user = User.objects.get(id=request.session['user_id']) book_from_db = Books.objects.get(id=book_id) context = { "user": user, "book": book_from_db } print(book_from_db.id) return render(request, "view_book.html", context) # adds new book to database that you like def add_book(request): if 'user_id' not in request.session: return redirect("/") errors = Books.objects.add_book_validator(request.POST) print(errors) if len(errors) > 0: for key, value in errors.items(): error_msg = key + ' - ' + value messages.error(request, error_msg) return redirect("/books") # current logged in user current_user = User.objects.get(id=request.session['user_id']) title_from_post = request.POST['title'] description_from_post = request.POST['desc'] book = Books.objects.create( title=title_from_post, desc=description_from_post, uploaded_by_id=current_user.id, ) print(book) book.users_who_favorite.add(current_user) return redirect("/books") # favorite a book that you did not upload def favorite_book(request, book_id): if 'user_id' not in request.session: return redirect("/") book_from_db = Books.objects.get(id=book_id) user_from_db = User.objects.get(id=request.session['user_id']) # TODO if user has already added book as favorite, just return, don't re-add book_from_db.users_who_favorite.add(user_from_db) book_from_db.save() return redirect("/books/" + str(book_id)) def edit_book(request): errors = Books.objects.add_book_validator(request.POST) if len(errors) > 0: for key, value in errors.items(): messages.error(request, value) return redirect("/books/" + str(book_id) + "/edit") book_to_update = Books.objects.get(id=book)
4bb05b091867737e9ecaec70c098f12cf3a01a8a
9da0e040c87ca42a0407061e914067c59b959096
/rich/text.py
394fc494bc5a967ebe4347553e5af92fb75da82c
[ "MIT" ]
permissive
4thel00z/rich
dc52d1068f23dab347932c4fabcde637379fa742
54b7e3c88108a14c9ac327a01728c279d70d9c54
refs/heads/master
2022-07-18T12:36:50.920553
2020-05-17T13:52:48
2020-05-17T13:52:48
null
0
0
null
null
null
null
UTF-8
Python
false
false
24,112
py
import re from operator import itemgetter from typing import ( TYPE_CHECKING, Any, Dict, Iterable, List, NamedTuple, Optional, Tuple, Union, cast, ) from typing_extensions import Literal from ._emoji_replace import _emoji_replace from ._loop import loop_first_last, loop_last from ._wrap import divide_line from .cells import cell_len from .containers import Lines from .control import strip_control_codes from .measure import Measurement from .segment import Segment from .style import Style, StyleType if TYPE_CHECKING: # pragma: no cover from .console import ( Console, ConsoleOptions, JustifyValues, RenderResult, RenderableType, ) class Span(NamedTuple): """A marked up region in some text.""" start: int end: int style: Union[str, Style] def __repr__(self) -> str: return f"Span({self.start}, {self.end}, {str(self.style)!r})" def __bool__(self) -> bool: return self.end > self.start def split(self, offset: int) -> Tuple["Span", Optional["Span"]]: """Split a span in to 2 from a given offset.""" if offset < self.start: return self, None if offset >= self.end: return self, None start, end, style = self span1 = Span(start, min(end, offset), style) span2 = Span(span1.end, end, style) return span1, span2 def move(self, offset: int) -> "Span": """Move start and end by a given offset. Args: offset (int): Number of characters to add to start and end. Returns: TextSpan: A new TextSpan with adjusted position. """ start, end, style = self return Span(start + offset, end + offset, style) def right_crop(self, offset: int) -> "Span": """Crop the span at the given offset. Args: offset (int): A value between start and end. Returns: Span: A new (possibly smaller) span. """ start, end, style = self if offset >= end: return self return Span(start, min(offset, end), style) class Text: r"""Text with color / style. Args: text (str, optional): Default unstyled text. Defaults to "". style (Union[str, Style], optional): Base style for text. Defaults to "". justify (str, optional): Default alignment for text, "left", "center", "full" or "right". Defaults to None. end (str, optional): Character to end text with. Defaults to "\n". tab_size (int): Number of spaces per tab, or ``None`` to use ``console.tab_size``. Defaults to 8. """ def __init__( self, text: str = "", style: Union[str, Style] = "", justify: "JustifyValues" = None, end: str = "\n", tab_size: Optional[int] = 8, spans: List[Span] = None, ) -> None: text = strip_control_codes(text) self._text: List[str] = [text] if text else [] self.style = style self.justify = justify self.end = end self.tab_size = tab_size self._spans: List[Span] = spans if spans is not None else [] self._length: int = len(text) def __len__(self) -> int: return self._length def __bool__(self) -> bool: return bool(self._length) def __str__(self) -> str: return self.text def __repr__(self) -> str: return f"<text {self.text!r} {self._spans!r}>" def __add__(self, other: Any) -> "Text": if isinstance(other, (str, Text)): result = self.copy() result.append(other) return result return NotImplemented def __eq__(self, other: object) -> bool: if not isinstance(other, Text): return NotImplemented return self.text == other.text and self._spans == other._spans def __contains__(self, other: object) -> bool: if isinstance(other, str): return other in self.text elif isinstance(other, Text): return other.text in self.text return False @classmethod def from_markup( cls, text: str, style: Union[str, Style] = "", emoji: bool = True, justify: "JustifyValues" = None, ) -> "Text": """Create Text instance from markup. Args: text (str): A string containing console markup. emoji (bool, optional): Also render emoji code. Defaults to True. justify (str, optional): Default alignment for text, "left", "center", "full" or "right". Defaults to None. Returns: Text: A Text instance with markup rendered. """ from .markup import render rendered_text = render(text, style, emoji=emoji) rendered_text.justify = justify return rendered_text @classmethod def assemble( cls, *parts: Union[str, "Text", Tuple[str, StyleType]], style: Union[str, Style] = "", justify: "JustifyValues" = None, end: str = "\n", tab_size: int = 8, ) -> "Text": """Construct a text instance by combining a sequence of strings with optional styles. The positional arguments should be either strings, or a tuple of string + style. Args: style (Union[str, Style], optional): Base style for text. Defaults to "". justify (str, optional): Default alignment for text, "left", "center", "full" or "right". Defaults to None. end (str, optional): Character to end text with. Defaults to "\n". tab_size (int): Number of spaces per tab, or ``None`` to use ``console.tab_size``. Defaults to 8. Returns: Text: A new text instance. """ text = cls(style=style, justify=justify, end=end, tab_size=tab_size) append = text.append for part in parts: if isinstance(part, (Text, str)): append(part) else: append(*part) return text @property def text(self) -> str: """Get the text as a single string.""" if len(self._text) not in (0, 1): text = "".join(self._text) self._text[:] = [text] return self._text[0] if self._text else "" @text.setter def text(self, new_text: str) -> None: """Set the text to a new value.""" self._text[:] = [new_text] old_length = self._length self._length = len(new_text) if old_length > self._length: self._trim_spans() @property def spans(self) -> List[Span]: """Get a copy of the list of spans.""" return self._spans @spans.setter def spans(self, spans: List[Span]) -> None: """Set spans.""" self._spans = spans[:] def blank_copy(self) -> "Text": """Return a new Text instance with copied meta data (but not the string or spans).""" copy_self = Text( style=self.style, justify=self.justify, end=self.end, tab_size=self.tab_size, ) return copy_self def copy(self) -> "Text": """Return a copy of this instance.""" copy_self = Text( self.text, style=self.style.copy() if isinstance(self.style, Style) else self.style, justify=self.justify, end=self.end, tab_size=self.tab_size, ) copy_self._spans[:] = self._spans return copy_self def stylize(self, start: int, end: int, style: Union[str, Style]) -> None: """Apply a style to a portion of the text. Args: start (int): Start offset. end (int): End offset. style (Union[str, Style]): Style instance or style definition to apply. """ length = len(self) if end < 0 or start >= length: # span not in range return self._spans.append(Span(max(0, start), min(length + 1, end), style)) def stylize_all(self, style: Union[str, Style]) -> None: """Apply a style to all the text. Args: start (int): Start offset. end (int): End offset. style (Union[str, Style]): Style instance or style definition to apply. """ self._spans.append(Span(0, len(self), style)) def get_style_at_offset(self, console: "Console", offset: int) -> Style: """Get the style of a character at give offset. Args: console (~Console): Console where text will be rendered. offset (int): Offset in to text (negative indexing supported) Returns: Style: A Style instance. """ if offset < 0: offset = len(self) + offset get_style = console.get_style style = console.get_style(self.style).copy() for start, end, span_style in self._spans: if offset >= start and offset < end: style += get_style(span_style) return style def highlight_regex( self, re_highlight: str, style: Union[str, Style] = None, style_prefix: str = "" ) -> int: """Highlight text with a regular expression, where group names are translated to styles. Args: re_highlight (str): A regular expression. style (Union[str, Style]): Optional style to apply to whole match. style_prefix (str, optional): Optional prefix to add to style group names. Returns: int: Number of regex matches """ count = 0 append_span = self._spans.append _Span = Span for match in re.finditer(re_highlight, self.text): _span = match.span if style: start, end = _span() append_span(_Span(start, end, style)) count += 1 for name, _ in match.groupdict().items(): start, end = _span(name) if start != -1: append_span(_Span(start, end, f"{style_prefix}{name}")) return count def highlight_words( self, words: Iterable[str], style: Union[str, Style], case_sensitive: bool = True, ) -> int: """Highlight words with a style. Args: words (Iterable[str]): Worlds to highlight. style (Union[str, Style]): Style to apply. Returns: int: Number of words highlighted. """ re_words = "|".join(re.escape(word) for word in words) add_span = self._spans.append count = 0 _Span = Span for match in re.finditer( re_words, self.text, flags=0 if case_sensitive else re.IGNORECASE ): start, end = match.span(0) add_span(_Span(start, end, style)) count += 1 return count def rstrip(self) -> None: """Trip whitespace from end of text.""" self.text = self.text.rstrip() def set_length(self, new_length: int) -> None: """Set new length of the text, clipping or padding is required.""" length = len(self) if length == new_length: return if length < new_length: self.pad_right(new_length - length) else: text = self.text[:new_length] self.text = text new_spans = [] for span in self._spans: if span.start < new_length: new_spans.append(span.right_crop(new_length)) self._spans[:] = new_spans def __console__( self, console: "Console", options: "ConsoleOptions" ) -> Iterable[Segment]: tab_size: int = console.tab_size or self.tab_size or 8 # type: ignore lines = self.wrap( console, options.max_width, justify=self.justify or options.justify, tab_size=tab_size or 8, ) all_lines = Text("\n").join(lines) yield from all_lines.render(console, end=self.end) def __measure__(self, console: "Console", max_width: int) -> Measurement: text = self.text if not text.strip(): return Measurement(cell_len(text), cell_len(text)) max_text_width = max(cell_len(line) for line in text.splitlines()) min_text_width = max(cell_len(word) for word in text.split()) return Measurement(min_text_width, max_text_width) def render(self, console: "Console", end: str = "") -> Iterable["Segment"]: """Render the text as Segments. Args: console (Console): Console instance. end (Optional[str], optional): Optional end character. Returns: Iterable[Segment]: Result of render that may be written to the console. """ text = self.text style_map: Dict[int, Style] = {} null_style = Style() def get_style(style: Union[str, Style]) -> Style: return console.get_style(style, default=null_style) enumerated_spans = list(enumerate(self._spans, 1)) style_map = {index: get_style(span.style) for index, span in enumerated_spans} style_map[0] = get_style(self.style) spans = [ (0, False, 0), *((span.start, False, index) for index, span in enumerated_spans), *((span.end, True, index) for index, span in enumerated_spans), (len(text), True, 0), ] spans.sort(key=itemgetter(0, 1)) stack: List[int] = [] stack_append = stack.append stack_pop = stack.remove _Segment = Segment style_cache: Dict[Tuple[int, ...], Style] = {} combine = Style.combine def get_current_style() -> Style: """Construct current style from stack.""" style_ids = tuple(sorted(stack)) cached_style = style_cache.get(style_ids) if cached_style is not None: return cached_style current_style = combine(style_map[_style_id] for _style_id in style_ids) style_cache[style_ids] = current_style return current_style for (offset, leaving, style_id), (next_offset, _, _) in zip(spans, spans[1:]): if leaving: stack_pop(style_id) else: stack_append(style_id) if next_offset > offset: yield _Segment(text[offset:next_offset], get_current_style()) if end: yield _Segment(end) def join(self, lines: Iterable["Text"]) -> "Text": """Join text together with this instance as the separator. Args: lines (Iterable[Text]): An iterable of Text instances to join. Returns: Text: A new text instance containing join text. """ new_text = self.blank_copy() append = new_text.append for last, line in loop_last(lines): append(line) if not last: append(self) return new_text def tabs_to_spaces(self, tab_size: int = None) -> "Text": """Get a new string with tabs converted to spaces. Args: tab_size (int, optional): Size of tabs. Defaults to 8. Returns: Text: A new instance with tabs replaces by spaces. """ if "\t" not in self.text: return self.copy() parts = self.split("\t", include_separator=True) pos = 0 if tab_size is None: tab_size = self.tab_size assert tab_size is not None result = Text( style=self.style, justify=self.justify, end=self.end, tab_size=self.tab_size ) append = result.append for part in parts: if part.text.endswith("\t"): part._text = [part.text[:-1] + " "] append(part) pos += len(part) spaces = tab_size - ((pos - 1) % tab_size) - 1 if spaces: append(" " * spaces, self.style) pos += spaces else: append(part) return result def _trim_spans(self) -> None: """Remove or modify any spans that are over the end of the text.""" new_length = self._length spans: List[Span] = [] append = spans.append for span in self._spans: if span.end < new_length: append(span) continue if span.start >= new_length: continue append(span.right_crop(new_length)) self._spans[:] = spans def pad_left(self, count: int, character: str = " ") -> None: """Pad the left with a given character. Args: count (int): Number of characters to pad. character (str, optional): Character to pad with. Defaults to " ". """ assert len(character) == 1, "Character must be a string of length 1" if count: self.text = f"{character * count}{self.text}" self._spans[:] = [span.move(count) for span in self._spans] def pad_right(self, count: int, character: str = " ") -> None: """Pad the right with a given character. Args: count (int): Number of characters to pad. character (str, optional): Character to pad with. Defaults to " ". """ assert len(character) == 1, "Character must be a string of length 1" if count: self.text = f"{self.text}{character * count}" def append( self, text: Union["Text", str], style: Union[str, "Style"] = None ) -> None: """Add text with an optional style. Args: text (Union[Text, str]): A str or Text to append. style (str, optional): A style name. Defaults to None. """ if not len(text): return if isinstance(text, str): text = strip_control_codes(text) self._text.append(text) offset = len(self) text_length = len(text) if style is not None: self._spans.append(Span(offset, offset + text_length, style)) self._length += text_length elif isinstance(text, Text): _Span = Span if style is not None: raise ValueError("style must not be set when appending Text instance") text_length = self._length if text.style is not None: self._spans.append( _Span(text_length, text_length + len(text), text.style) ) self._text.append(text.text) self._spans.extend( _Span(start + text_length, end + text_length, style) for start, end, style in text._spans ) self._length += len(text) else: raise TypeError("Only str or Text can be appended to Text") def copy_styles(self, text: "Text") -> None: """Copy styles from another Text instance. Args: text (Text): A Text instance to copy styles from, must be the same length. """ self._spans.extend(text._spans) def split(self, separator="\n", include_separator: bool = False) -> Lines: r"""Split rich text in to lines, preserving styles. Args: separator (str, optional): String to split on. Defaults to "\n". Returns: List[RichText]: A list of rich text, one per line of the original. """ assert separator, "separator must not be empty" text = self.text if separator not in text: return Lines([self.copy()]) if text.endswith(separator): text = text[: -len(separator)] offsets: List[int] = [] append = offsets.append offset = 0 while True: try: offset = text.index(separator, offset) + len(separator) except ValueError: break append(offset) lines = self.divide(offsets) if not include_separator: separator_length = len(separator) for line in lines: if line.text.endswith(separator): line.right_crop(separator_length) return lines def divide(self, offsets: Iterable[int]) -> Lines: """Divide text in to a number of lines at given offsets. Args: offsets (Iterable[int]): Offsets used to divide text. Returns: Lines: New RichText instances between offsets. """ if not offsets: line = self.copy() return Lines([line]) text = self.text text_length = len(text) divide_offsets = [0, *offsets, text_length] line_ranges = list(zip(divide_offsets, divide_offsets[1:])) average_line_length = -(-text_length // len(line_ranges)) new_lines = Lines( Text(text[start:end], style=self.style, justify=self.justify) for start, end in line_ranges ) line_ranges = [ (offset, offset + len(line)) for offset, line in zip(divide_offsets, new_lines) ] for span in self._spans: line_index = (span.start // average_line_length) % len(line_ranges) line_start, line_end = line_ranges[line_index] if span.start < line_start: while True: line_index -= 1 line_start, line_end = line_ranges[line_index] if span.end >= line_start: break elif span.start > line_end: while True: line_index += 1 line_start, line_end = line_ranges[line_index] if span.start <= line_end: break while True: span, new_span = span.split(line_end) new_lines[line_index]._spans.append(span.move(-line_start)) if new_span is None: break span = new_span line_index += 1 line_start, line_end = line_ranges[line_index] return new_lines def right_crop(self, amount: int = 1) -> None: """Remove a number of characters from the end of the text.""" self.text = self.text[:-amount] def wrap( self, console: "Console", width: int, justify: "JustifyValues" = "left", tab_size: int = 8, ) -> Lines: """Word wrap the text. Args: width (int): Number of characters per line. justify (bool, optional): True to pad lines with spaces. Defaults to False. Returns: Lines: Number of lines. """ lines: Lines = Lines() for line in self.split(): if "\t" in line: line = line.tabs_to_spaces(tab_size) offsets = divide_line(str(line), width) new_lines = line.divide(offsets) if justify: new_lines.justify(console, width, align=justify) lines.extend(new_lines) return lines def fit(self, width: int) -> Lines: """Fit the text in to given width by chopping in to lines. Args: width (int): Maximum characters in a line. Returns: Lines: List of lines. """ lines: Lines = Lines() append = lines.append for line in self.split(): line.set_length(width) append(line) return lines
c205f8c46b863a632e3fe38baa0cd98c509905b5
63a7f3f0e6448bc0ba21847c57fcdb4fc23abb7a
/project6/ecommerce/ecommerce/urls.py
47f8dc0148f60120dbcbd857a1077a16c3502156
[]
no_license
alaminbhuyan/Django-Projects
33854b972312b19387b3b0c5a054464a5b7d843c
c46a5691954ccaa016144793115cfffd8b1058d9
refs/heads/master
2021-01-26T13:40:18.729125
2020-03-31T16:42:13
2020-03-31T16:42:13
243,444,335
0
0
null
null
null
null
UTF-8
Python
false
false
936
py
"""ecommerce URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.0/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path , include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('',include('shop.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
57651bd056392553b7461799fcdab49cd38ccc3f
c21960247829b620d0e36a3408ef8099d248c742
/cirq/protocols/equal_up_to_global_phase.py
a6db82844732657e2d5140fb5820451d2b01ddff
[ "Apache-2.0" ]
permissive
iamvamsikrishnad/Cirq
ce1439853c9172690e3340fec70b47fd5614e2d1
4bec5447242c0d06f773a075383eea9dae0eebd3
refs/heads/master
2020-06-06T06:15:10.526041
2019-06-19T02:32:58
2019-06-19T02:32:58
192,661,193
1
0
Apache-2.0
2019-06-19T04:57:38
2019-06-19T04:57:38
null
UTF-8
Python
false
false
4,248
py
# Copyright 2019 The Cirq Developers # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from collections import Iterable import numbers from typing import Any, Union import numpy as np from typing_extensions import Protocol import cirq class SupportsEqualUpToGlobalPhase(Protocol): """Object which can be compared for equality mod global phase.""" def _equal_up_to_global_phase_(self, other: Any, *, atol: Union[int, float]) -> bool: """Approximate comparator. Types implementing this protocol define their own logic for comparison with other types. Args: other: Target object for comparison of equality up to global phase. atol: The minimum absolute tolerance. See `np.isclose()` documentation for details. Returns: True if objects are equal up to a global phase, False otherwise. Returns NotImplemented when checking equality up to a global phase is not implemented for given types. """ def equal_up_to_global_phase(val: Any, other: Any, *, atol: Union[int, float] = 1e-8) -> bool: """Determine whether two objects are equal up to global phase. If `val` implements a `_equal_up_to_global_phase_` method then it is invoked and takes precedence over all other checks: - For complex primitive type the magnitudes of the values are compared. - For `val` and `other` both iterable of the same length, consecutive elements are compared recursively. Types of `val` and `other` does not necessarily needs to match each other. They just need to be iterable and have the same structure. - For all other types, fall back to `_approx_eq_` Args: val: Source object for approximate comparison. other: Target object for approximate comparison. atol: The minimum absolute tolerance. This places an upper bound on the differences in *magnitudes* of two compared complex numbers. Returns: True if objects are approximately equal up to phase, False otherwise. """ # Attempt _equal_up_to_global_phase_ for val. eq_up_to_phase_getter = getattr(val, '_equal_up_to_global_phase_', None) if eq_up_to_phase_getter is not None: result = eq_up_to_phase_getter(other, atol) if result is not NotImplemented: return result # Fall back to _equal_up_to_global_phase_ for other. other_eq_up_to_phase_getter = getattr(other, '_equal_up_to_global_phase_', None) if other_eq_up_to_phase_getter is not None: result = other_eq_up_to_phase_getter(val, atol) if result is not NotImplemented: return result # Fall back to special check for numeric arrays. # Defer to numpy automatic type casting to determine numeric type. if isinstance(val, Iterable) and isinstance(other, Iterable): a = np.asarray(val) b = np.asarray(other) if a.dtype.kind in 'uifc' and b.dtype.kind in 'uifc': return cirq.linalg.allclose_up_to_global_phase(a, b, atol=atol) # Fall back to approx_eq for compare the magnitude of two numbers. if isinstance(val, numbers.Number) and isinstance(other, numbers.Number): result = cirq.approx_eq(abs(val), abs(other), atol=atol) # type: ignore if result is not NotImplemented: return result # Fall back to cirq approx_eq for remaining types. return cirq.approx_eq(val, other, atol=atol)
b5fd20af137de58b757e8b55bfffde6aa2cc80f8
ee8c4c954b7c1711899b6d2527bdb12b5c79c9be
/assessment2/amazon/run/core/controllers/unwieldy.py
30434fbf85008b2c83c8b9159fa9d0a2baf010fe
[]
no_license
sqlconsult/byte
02ac9899aebea4475614969b594bfe2992ffe29a
548f6cb5038e927b54adca29caf02c981fdcecfc
refs/heads/master
2021-01-25T14:45:42.120220
2018-08-11T23:45:31
2018-08-11T23:45:31
117,135,069
0
0
null
null
null
null
UTF-8
Python
false
false
370
py
#!/usr/bin/env python3 from flask import Blueprint, Flask, render_template, request, url_for controller = Blueprint('unwieldy', __name__, url_prefix='/unwieldy') # @controller.route('/<string:title>', methods=['GET']) # def lookup(title): # if title == 'Republic': # TODO 2 # return render_template('republic.html') # TODO 2 # else: # pass
6c3cee0d518b7e09a352a7a9febe99dee52efab2
3a9f2b3d79cf214704829427ee280f4b49dca70a
/saigon/rat/RuckusAutoTest/scripts/zd/ats_ZD_Combo_Palo_Alto_WISPr_Enable_Disable.py
19bc854ef34aece8a3cf553113c84ee16e59b58f
[]
no_license
jichunwei/MyGitHub-1
ae0c1461fe0a337ef459da7c0d24d4cf8d4a4791
f826fc89a030c6c4e08052d2d43af0b1b4b410e3
refs/heads/master
2021-01-21T10:19:22.900905
2016-08-20T03:34:52
2016-08-20T03:34:52
null
0
0
null
null
null
null
UTF-8
Python
false
false
29,190
py
''' Created on 2011-7-25 @author: Administrator ''' import sys import time import copy import libZD_TestSuite as testsuite from RuckusAutoTest.common import lib_KwList as kwlist from RuckusAutoTest.common import Ratutils as utils from RuckusAutoTest.common import lib_Constant as const BROWSER_STARTED = False #-------------------------- Test Step builder ---------------# class TestStepBuilder: ####################################### # Constant # ####################################### NORMAL = 0 WEBAUTH = 1 GUESTAUTH = 2 HOTSPOT = 3 ####################################### # Access Methods # ####################################### @classmethod def build_create_local_user_step(cls, EXEC_LEVEL, **user_cfg): user_cfg = {'username': 'local.username', 'password': 'local.password' } user_cfg.update(user_cfg) return [(user_cfg, 'CB_ZD_Create_Local_User', 'Create a local user', EXEC_LEVEL, False)] @classmethod def build_create_wlans_step(cls, EXEC_LEVEL, wlans): return [(dict(wlan_cfg_list = copy.deepcopy(wlans)), 'CB_ZD_Create_Wlans', 'Create WLANs', EXEC_LEVEL, False), ] @classmethod def build_uncheck_wlans_in_default_wg_step(cls, EXEC_LEVEL = 0): return [({}, 'CB_ZD_Remove_All_Wlans_Out_Of_Default_Wlan_Group', 'Remove all wlans out of default', EXEC_LEVEL, False) ] @classmethod def build_clean_wlan_wlangroup_steps(cls, EXEC_LEVEL = 0): return [ ({}, 'CB_ZD_Remove_All_Wlan_Groups', 'Remove All WLAN Groups for cleanup ENV', EXEC_LEVEL, False), ({}, 'CB_ZD_Remove_All_Wlans', 'Clean all WLANs for cleanup ENV', EXEC_LEVEL, False), ] @classmethod def build_clean_hotspot_step(cls, EXEC_LEVEL = 0): return [({}, 'CB_ZD_Remove_All_Profiles', 'Remove all profiles', EXEC_LEVEL, False)] @classmethod def build_station_pre_steps(cls, **kwargs): param_dict = {'active_ap':'', 'wlan_cfg':'', 'wlan_group_name':'', 'target_station':'', 'radio':None, 'sta_tag':'sta_1', 'ap_tag':'tap', } param_dict.update(kwargs) active_ap = param_dict['active_ap'] wlan_cfg = copy.deepcopy(param_dict['wlan_cfg']) wlan_group_name = param_dict['wlan_group_name'] radio = param_dict['radio'] target_station = param_dict['target_station'] sta_tag = param_dict['sta_tag'] ap_tag = param_dict['ap_tag'] EXEC_LEVEL = 1 test_cfgs = [] param_cfg = dict(active_ap = active_ap) test_cfgs.append((param_cfg, 'CB_ZD_Find_Active_AP', 'Create an Active AP', EXEC_LEVEL, False)) param_cfg = dict(active_ap = active_ap, wlan_group_name = wlan_group_name, radio_mode = radio) test_cfgs.append((param_cfg, 'CB_ZD_Assign_AP_To_Wlan_Groups', 'Associate AP with radio %s to %s' % (radio, wlan_group_name), EXEC_LEVEL, False)) test_cfgs.append(({'sta_tag': sta_tag, 'sta_ip_addr': target_station}, 'CB_ZD_Create_Station', 'Get the station', EXEC_LEVEL, False)) test_cfgs.append(({'ap_tag': ap_tag, 'active_ap': active_ap}, 'CB_ZD_Create_Active_AP', 'Get the active AP', EXEC_LEVEL, False)) test_cfgs.append(({'sta_tag': sta_tag, 'wlan_cfg': wlan_cfg}, 'CB_ZD_Associate_Station_1', 'Associate the station', EXEC_LEVEL, False)) test_cfgs.append(({'sta_tag': sta_tag}, 'CB_ZD_Get_Station_Wifi_Addr_1', 'Get wifi address', EXEC_LEVEL, False)) global BROWSER_STARTED if not BROWSER_STARTED: test_cfgs.append(({'sta_tag': sta_tag}, 'CB_Station_CaptivePortal_Start_Browser', 'Open authentication web page', EXEC_LEVEL, False, )) BROWSER_STARTED = True return test_cfgs @classmethod def build_station_post_steps(cls, **kwargs): param_dict = {'radio':None, 'wlan_group_name':None, 'active_ap': None, } param_dict.update(kwargs) radio = param_dict['radio'] active_ap = param_dict['active_ap'] wlan_group_name = param_dict['wlan_group_name'] EXEC_LEVEL = 1 param_cfg = dict(active_ap = active_ap, wlan_group_name = wlan_group_name, radio_mode = radio) return[(param_cfg, 'CB_ZD_Assign_AP_To_Wlan_Groups', 'Associate AP with radio: %s to Default' % (radio), EXEC_LEVEL, False)] @classmethod def build_station_check_steps(cls, auth_type, **kwargs): param_dict = {'active_ap':'', 'wlan_cfg':'', 'wlan_group_name':'', 'target_station':'', 'target_ip':'', 'radio':None, 'chk_radio':False, 'sta_tag':'sta_1', 'ap_tag':'tap', 'hotspot_cfg':None, 'webauth_cfg':None, 'guest_cfg':None, 'tcid':None, } param_dict.update(kwargs) EXEC_LEVEL = 1 test_cfgs = [] active_ap = param_dict['active_ap'] radio = param_dict['radio'] wlan_cfg = copy.deepcopy(param_dict['wlan_cfg']) wlan_group_name = param_dict['wlan_group_name'] target_station = param_dict['target_station'] target_ip = param_dict['target_ip'] sta_tag = param_dict['sta_tag'] ap_tag = param_dict['ap_tag'] tcid = param_dict['tcid'] chk_radio = param_dict['chk_radio'] hotspot_cfg = copy.deepcopy(param_dict['hotspot_cfg']) webauth_cfg = copy.deepcopy(param_dict['webauth_cfg']) guest_cfg = copy.deepcopy(param_dict['guest_cfg']) if auth_type == TestStepBuilder.HOTSPOT: kwargs = dict(EXEC_LEVEL = EXEC_LEVEL, wlan_cfg = wlan_cfg, hotspot_cfg = hotspot_cfg, sta_tag = sta_tag, ap_tag = ap_tag, tcid = tcid, chk_radio = chk_radio, radio = radio) test_cfgs.extend(TestStepBuilder._build_hotspot_station(**kwargs)) elif auth_type == TestStepBuilder.WEBAUTH: kwargs = dict(EXEC_LEVEL = EXEC_LEVEL, wlan_cfg = wlan_cfg, sta_tag = sta_tag, ap_tag = ap_tag, tcid = tcid, chk_radio = chk_radio, radio = radio, ) test_cfgs.extend(TestStepBuilder._build_webauth_station(**kargs)) elif auth_type == TestStepBuilder.GUESTAUTH: kwargs = dict(EXEC_LEVEL = EXEC_LEVEL, wlan_cfg = wlan_cfg, guest_cfg = guest_cfg, sta_tag = sta_tag, tcid = tcid, chk_radio = chk_radio, radio = radio) test_cfgs.extend(TestStepBuilder._build_guestauth_station(**kwargs)) else: kwargs = dict(EXEC_LEVEL = EXEC_LEVEL, wlan_cfg = wlan_cfg, sta_tag = sta_tag, ap_tag = ap_tag, tcid = tcid, chk_radio = chk_radio, radio = radio) test_cfgs.extend(TestStepBuilder._build_normal_station(**kwargs)) return test_cfgs @classmethod def build_station_ping_step(cls, **kwargs): EXEC_LEVEL = 1 param_dict = {'sta_tag':'sta_1', 'target_ip':'', 'condition': 'allowed', } param_dict.update(kwargs) sta_tag = param_dict['sta_tag'] target_ip = param_dict['target_ip'] condition = param_dict['condition'] return[({'sta_tag': sta_tag, 'condition': condition, 'target': target_ip, 'ping_timeout_ms': 10 * 1000 }, 'CB_ZD_Client_Ping_Dest', 'The station ping a target IP', EXEC_LEVEL + 1, False) ] @classmethod def build_station_all_steps(cls, auth_type, **kwargs): param_dict = {'active_ap':'', 'wlan_cfg':'', 'wlan_group_name':'', 'target_station':'', 'target_ip':'', 'radios':[], 'chk_radio':False, 'sta_tag':'sta_1', 'ap_tag':'tap', 'hotspot_cfg':None, 'webauth_cfg':None, 'guest_cfg':None, 'tcid':None, } param_dict.update(kwargs) EXEC_LEVEL = 1 test_cfgs = [] active_ap = param_dict['active_ap'] radios = param_dict['radios'] wlan_cfg = copy.deepcopy(param_dict['wlan_cfg']) wlan_group_name = param_dict['wlan_group_name'] target_station = param_dict['target_station'] target_ip = param_dict['target_ip'] sta_tag = param_dict['sta_tag'] ap_tag = param_dict['ap_tag'] tcid = param_dict['tcid'] chk_radio = param_dict['chk_radio'] hotspot_cfg = copy.deepcopy(param_dict['hotspot_cfg']) webauth_cfg = copy.deepcopy(param_dict['webauth_cfg']) guest_cfg = copy.deepcopy(param_dict['guest_cfg']) for radio in radios: param_dict['radio'] = radio test_cfgs.extend(TestStepBuilder.build_station_pre_steps(**param_dict)) test_cfgs.extend(TestStepBuilder.build_station_check_steps(auth_type, **param_dict)) test_cfgs.extend(TestStepBuilder.build_station_ping_step(**param_dict)) test_cfgs.extend(TestStepBuilder.build_station_post_steps(**param_dict)) return test_cfgs ####################################### # Protected Methods # ####################################### @classmethod def _encode_tcid(cls, tcid, test_cfgs): #append test cases identifier. if tcid: test_cfgs_copy = [] for test_params, testname, common_name, exc_level, is_cleanup in test_cfgs: common_name = '%s%s' % (tcid, common_name) test_cfgs_copy.append((test_params, testname, common_name, exc_level, is_cleanup)) return test_cfgs_copy return test_cfgs @classmethod def _build_normal_station(cls, EXEC_LEVEL = 1, wlan_cfg = None, sta_tag = 'sta_1', ap_tag = 'tap', tcid = None, chk_radio=False, radio = None ): test_cfgs = [] param_cfg = {'wlan_cfg':wlan_cfg, 'chk_empty':False, 'status':'Authorized', 'chk_radio':chk_radio, 'radio_mode':radio, 'sta_tag':sta_tag, 'ap_tag':ap_tag,} test_cfgs.append((param_cfg, 'CB_ZD_Verify_Station_Info_V2', 'Verify the station information on ZD', EXEC_LEVEL + 1, False)) if tcid: return TestStepBuilder._encode_tcid(tcid, test_cfgs) return test_cfgs @classmethod def _build_hotspot_station(cls, EXEC_LEVEL = 1, wlan_cfg = None, hotspot_cfg = None, sta_tag = 'sta_1', ap_tag = 'tap', tcid = None, chk_radio = False, radio = None): test_cfgs = [] param_cfg = {'wlan_cfg':wlan_cfg, 'chk_empty':False, 'status':'Unauthorized', 'chk_radio':chk_radio, 'radio_mode':radio, 'sta_tag':sta_tag, 'ap_tag':ap_tag, } test_cfgs.append((param_cfg, 'CB_ZD_Verify_Station_Info_V2', 'Verify the station before hotspot auth', EXEC_LEVEL + 1, False)) param_cfgs = {'sta_tag':sta_tag} for k, v in hotspot_cfg['auth_info'].items(): param_cfgs[k] = v test_cfgs.append((param_cfgs, 'CB_Station_CaptivePortal_Perform_HotspotAuth', 'Perform Hotspot authentication', EXEC_LEVEL, False)) username = hotspot_cfg['auth_info']['username'] param_cfg = {'wlan_cfg':wlan_cfg, 'chk_empty':False, 'status':'Authorized', 'chk_radio':chk_radio, 'radio_mode':radio, 'sta_tag':sta_tag, 'ap_tag':ap_tag, 'username':username} test_cfgs.append((param_cfg, 'CB_ZD_Verify_Station_Info_V2', 'Verify the station after hotspot auth', EXEC_LEVEL + 1, False)) test_cfgs.append(({'sta_tag':sta_tag}, 'CB_Station_CaptivePortal_Download_File', 'Download files from server', EXEC_LEVEL + 1, False )) if tcid: return TestStepBuilder._encode_tcid(tcid, test_cfgs) return test_cfgs @classmethod def _build_webauth_station(cls, EXEC_LEVEL = 1, wlan_cfg = None, webauth_cfg = None, sta_tag = 'sta_1', ap_tag = 'tap', tcid = None, chk_radio = False, radio = None): test_cfgs = [] param_cfg = {'wlan_cfg':wlan_cfg, 'chk_empty':False, 'status':'Unauthorized', 'chk_radio':chk_radio, 'radio_mode': radio, 'sta_tag':sta_tag, 'ap_tag':ap_tag,} test_cfgs.append((param_cfg, 'CB_ZD_Verify_Station_Info_V2', 'Verify the station before web auth', EXEC_LEVEL + 1, False)) param_cfgs = {'sta_tag':sta_tag} for k, v in webauth_cfg['auth_info'].items(): param_cfgs[k] = v test_cfgs.append((param_cfgs, 'CB_Client_CaptivePortal_WebAuth', 'Perform Web authentication', EXEC_LEVEL, False)) username = webauth_cfg['auth_info']['username'] param_cfg = {'wlan_cfg':wlan_cfg, 'chk_empty':False, 'status':'Authorized', 'chk_radio':chk_radio, 'radio_mode': radio, 'sta_tag':sta_tag, 'ap_tag':ap_tag, 'username':username} test_cfgs.append((param_cfg, 'CB_ZD_Verify_Station_Info_V2', 'Verify the station after web auth', EXEC_LEVEL + 1, False)) if tcid: return TestStepBuilder._encode_tcid(tcid, test_cfgs) return test_cfgs @classmethod def _build_guestauth_station(cls, EXEC_LEVEL = 1, wlan_cfg = None, guest_cfg = None, sta_tag = 'sta_1', ap_tag = 'tap', tcid = None, chk_radio = False, radio = None, ): test_cfgs = [] param_cfg = {'wlan_cfg':wlan_cfg, 'chk_empty':False, 'status':'Unauthorized', 'chk_radio':chk_radio, 'radio_mode' : radio, 'sta_tag':sta_tag, 'ap_tag':ap_tag,} test_cfgs.append((param_cfg, 'CB_ZD_Verify_Station_Info_V2', 'Verify the station before guest-auth', EXEC_LEVEL + 1, False)) param_cfgs = {'sta_tag':sta_tag} for k, v in guest_cfg.items(): param_cfgs[k] = v test_cfgs.append((param_cfgs, 'CB_Client_CaptivePortal_GuestAuth', 'Perform Guest authentication', EXEC_LEVEL, False)) username = webauth_cfg['auth_info']['username'] param_cfg = {'wlan_cfg':wlan_cfg, 'chk_empty':False, 'status':'Authorized', 'chk_radio':chk_radio, 'radio_mode' : radio, 'sta_tag':sta_tag, 'ap_tag':ap_tag, } test_cfgs.append((param_cfg, 'CB_ZD_Verify_Station_Info_V2', 'Verify the station info after guest-auth', EXEC_LEVEL + 1, False)) if tcid: return TestStepBuilder._encode_tcid(tcid, test_cfgs) return test_cfgs #---------------------- Test step builder END ---------------# OPEN_NONE_INDEX = 0 def define_wlans(): wlan_cfg_list = [] # Open-None wlan_cfg_list.append(dict(ssid = "RAT-Open-None", auth = "open", encryption = "none", web_auth = None)) return wlan_cfg_list def define_test_params(target_station): cfg = dict() cfg['target_station'] = target_station cfg['target_ip'] = '172.126.0.252' cfg['hotspot_cfg'] = {'login_page': 'http://192.168.0.250/login.html', 'name': 'A Sampe Hotspot Profile'} #define AAA server data. cfg['local_server'] = {'username': 'local.username', 'password': 'local.password'} return cfg #define an ID generator def gen(): k = 0 while True: k += 1 yield k ID_GEN = gen().next def build_sta_hot_cfg(test_params, server_name='local_server'): return dict(hotspot_profile_name = test_params['hotspot_cfg']['name'], auth_info = test_params[server_name], station_ip = test_params['target_station']) def build_test_cases(target_station, target_station_radio, active_ap): EXEC_LEVEL = 0 test_cfgs = [] test_params = define_test_params(target_station) wlans = define_wlans() test_cfgs.extend(TestStepBuilder.build_clean_wlan_wlangroup_steps()) test_cfgs.extend(TestStepBuilder.build_clean_hotspot_step()) test_cfgs.extend(TestStepBuilder.build_create_local_user_step(EXEC_LEVEL, **test_params['local_server'])) tcid = '[Test Hotspot disable in WLAN]' param_cfg = dict(hotspot_profiles_list = [test_params['hotspot_cfg']]) test_cfgs.append((param_cfg, 'CB_ZD_Create_Hotspot_Profiles', '%sCreate Hotspot service' % tcid, EXEC_LEVEL, False)) test_cfgs.extend(TestStepBuilder.build_create_wlans_step(EXEC_LEVEL, wlans)) test_cfgs.extend(TestStepBuilder.build_uncheck_wlans_in_default_wg_step()) wlans_copy = copy.deepcopy(wlans) OPEN_WLANGROUP = 'open_none_wlangroup_1' param_cfg = dict(wlangroups_map = {OPEN_WLANGROUP:wlans_copy[OPEN_NONE_INDEX]['ssid']}) test_cfgs.append((param_cfg, 'CB_ZD_Create_WLANGroups_with_WLANs', 'Create WLANGroup and WLAN in pair', EXEC_LEVEL, False)) #Disable Hotspot on a WLAN. param_dict = {'active_ap':active_ap, 'wlan_cfg':wlans_copy[OPEN_NONE_INDEX], 'wlan_group_name':OPEN_WLANGROUP, 'target_station':target_station, 'target_ip':test_params['target_ip'], 'radios':[target_station_radio], 'chk_radio':False, 'sta_tag':'sta_1', 'ap_tag':'tap', 'hotspot_cfg':None, 'tcid':tcid, } test_cfgs.extend(TestStepBuilder.build_station_all_steps(TestStepBuilder.NORMAL, **param_dict)) wlan_copy2 = copy.deepcopy(wlans) #Update WLAN to support hotspot. test_name = 'CB_ZD_Create_Wlan' hotspot_cfg = build_sta_hot_cfg(test_params, server_name='local_server') common_name = 'Modify WLAN{%s} with hotspot file{%s}' % (wlan_copy2[OPEN_NONE_INDEX]['ssid'], hotspot_cfg['hotspot_profile_name']) wlan_copy2[OPEN_NONE_INDEX]['hotspot_profile'] = hotspot_cfg['hotspot_profile_name'] wlan_copy2[OPEN_NONE_INDEX]['type'] = 'hotspot' param_cfg = dict(wlan_cfg_list = [wlan_copy2[OPEN_NONE_INDEX]]) test_cfgs.append((param_cfg, test_name, common_name, EXEC_LEVEL, False)) tcid = '[Test Hotspot enable in WLAN]' #Enable Hotspot on a WLAN. param_dict = {'active_ap':active_ap, 'wlan_cfg':wlan_copy2[OPEN_NONE_INDEX], 'wlan_group_name':OPEN_WLANGROUP, 'target_station':target_station, 'target_ip':test_params['target_ip'], 'radios':[target_station_radio], 'chk_radio':False, 'sta_tag':'sta_1', 'ap_tag':'tap', 'hotspot_cfg':hotspot_cfg, 'tcid':tcid, } test_cfgs.extend(TestStepBuilder.build_station_all_steps(TestStepBuilder.HOTSPOT, **param_dict)) if BROWSER_STARTED: test_cfgs.append(({'sta_tag':'sta_1'}, 'CB_Station_CaptivePortal_Quit_Browser', 'Close Authentication browser', False, 1, )) return test_cfgs def decorate_common_name(test_cfgs): test_cfgs_copy = [] for test_params, testname, common_name, exc_level, is_cleanup in test_cfgs: common_name = _get_common_name(common_name) test_cfgs_copy.append((test_params, testname, common_name, exc_level, is_cleanup)) return test_cfgs_copy def _get_common_name(common_name): b_index = common_name.find('[') e_index = common_name.find(']') if b_index >=0 and e_index > b_index: return '[%s]%s.%s'% (common_name[b_index+1:e_index], ID_GEN(), common_name[e_index+1:]) else: return '%s.%s' % (ID_GEN(), common_name) def create_test_suite(**kwargs): STA_INDEX = 0 STA_RADIO_INDEX = 1 attrs = dict(interactive_mode = True, station = (0,"g"), targetap = False, testsuite_name = "Palo Alto WISPr Enable and Disable - 11g", ) attrs.update(kwargs) tb = testsuite.getTestbed2(**kwargs) tbcfg = testsuite.getTestbedConfig(tb) sta_ip_list = tbcfg['sta_ip_list'] if attrs["interactive_mode"]: target_sta = testsuite.getTargetStation(sta_ip_list) target_sta_radio = testsuite.get_target_sta_radio() else: target_sta = sta_ip_list[attrs["station"][STA_INDEX]] target_sta_radio = attrs["station"][STA_RADIO_INDEX] ap_sym_dict = tbcfg['ap_sym_dict'] active_ap = None for ap_sym_name, ap_info in ap_sym_dict.items(): if target_sta_radio in const._ap_model_info[ap_info['model'].lower()]['radios']: active_ap = ap_sym_name break if not active_ap: raise Exception('Have not found valid AP model') ap_model = ap_sym_dict[active_ap]['model'] if attrs["interactive_mode"]: ts_name = "Palo Alto WISPr Enable and Disable - 11%s, %s" % (target_sta_radio, ap_model) else: ts_name = attrs["testsuite_name"] ts = testsuite.get_testsuite(ts_name, "Palo Alto WISPr Enable and Disable - 11%s, %s" % (target_sta_radio, ap_model), combotest=True) test_cfgs = build_test_cases(target_sta, target_sta_radio, active_ap) test_cfgs = decorate_common_name(test_cfgs) test_order = 1 test_added = 0 for test_params, testname, common_name, exc_level, is_cleanup in test_cfgs: if testsuite.addTestCase(ts, testname, common_name, test_params, test_order, exc_level, is_cleanup) > 0: test_added += 1 test_order += 1 print "Add test case with test name: %s\n\t\common name: %s" % (testname, common_name) print "\n-- Summary: added %d test cases into test suite '%s'" % (test_added, ts.name) if __name__ == "__main__": _dict = kwlist.as_dict(sys.argv[1:]) create_test_suite(**_dict)
513441ca0605b94e533042b091aea4e190179b11
23a0130020e00bf09dbf9e158460ed3534adddba
/Main.py
155f306f28acf1e00c4b54d05604fb7743806502
[]
no_license
Smikhalcv/diplom_adpy-10
f6923e1e6ad3c99faa0eba294050448affca5737
072a69b95e821c2804966fc21f6214f274573206
refs/heads/master
2022-10-14T16:59:43.901261
2020-06-11T22:02:16
2020-06-11T22:02:16
260,189,471
0
0
null
null
null
null
UTF-8
Python
false
false
1,161
py
from User.get_token import Token from User.user_id import id_user from search_peoples import Search from mongo_db import Mongo_DB from executor import get_result if __name__ in '__main__': database = Mongo_DB('VKinder') database.create_db() token = Token() access_token = token.read_token() user_id = str(id_user(access_token)) if user_id in database.show_coll(): print('По данному пользователю уже проводился поиск, начать новый? (да/нет)') print('(при выборе нет, продолжит чтение из старого поиска)') flag = input('- ') if flag.lower().startswith('д'): user = Search(access_token, user_id) user.change_parametr() value_compability = user.compability() get_result(access_token, user_id) else: get_result(access_token, user_id) if user_id not in database.show_coll(): user = Search(access_token, user_id) user.change_parametr() value_compability = user.compability() get_result(access_token, user_id)
c6e7a41f411c28428cdffda9d8489491dfb15727
cce6364dd85b62782671cd8048873eede2045137
/primary/3_isPalindrome.py
499cab542bacb21c2fb831b1a52c66aa1c3dc427
[]
no_license
gmt710/leetcode_python
ed647958440f66583b8717dae7bca49c516984da
441623afee3713506b702c5fd462c7ba84b48442
refs/heads/master
2020-03-28T05:11:02.851792
2019-04-17T09:14:51
2019-04-17T09:14:51
147,761,046
1
0
null
null
null
null
UTF-8
Python
false
false
479
py
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def isPalindrome(self, head): """ :type head: ListNode :rtype: bool """ q = [] while(head): q.append(head.val) head = head.next if q == q[::-1]: return True else: return False
2592d28fb5f3680d1324df3073feaa1e5934d16e
960b3a17a4011264a001304e64bfb76d669b8ac5
/mstrio/utils/formjson.py
1a7443b172fcf930301b16b20e88b803adfcb11c
[ "Apache-2.0" ]
permissive
MicroStrategy/mstrio-py
012d55df782a56dab3a32e0217b9cbfd0b59b8dd
c6cea33b15bcd876ded4de25138b3f5e5165cd6d
refs/heads/master
2023-08-08T17:12:07.714614
2023-08-03T12:30:11
2023-08-03T12:30:11
138,627,591
84
60
Apache-2.0
2023-07-31T06:43:33
2018-06-25T17:23:55
Python
UTF-8
Python
false
false
2,139
py
def _map_data_type(datatype): if datatype == 'object': return "STRING" elif datatype in ['int64', 'int32']: return "INTEGER" elif datatype in ['float64', 'float32']: return "DOUBLE" elif datatype == 'bool': return "BOOL" elif datatype == 'datetime64[ns]': return 'DATETIME' def formjson(df, table_name, as_metrics=None, as_attributes=None): def _form_column_headers(_col_names, _col_types): return [{'name': n, 'dataType': t} for n, t in zip(_col_names, _col_types)] def _form_attribute_list(_attributes): return [ { 'name': n, 'attributeForms': [ { 'category': 'ID', 'expressions': [{'formula': table_name + "." + n}], } ], } for n in _attributes ] def _form_metric_list(_metrics): return [ { 'name': n, 'dataType': 'number', 'expressions': [{'formula': table_name + "." + n}], } for n in _metrics ] col_names = list(df.columns) col_types = list(map(_map_data_type, list(df.dtypes.values))) # Adjust attributes/metrics mapping if new mappings were provided in # as_metrics and as_attributes attributes = [] metrics = [] for _name, _type in zip(col_names, col_types): if _type in ['DOUBLE', 'INTEGER']: # metric if as_attributes is not None and _name in as_attributes: attributes.append(_name) else: metrics.append(_name) else: # attribute if as_metrics is not None and _name in as_metrics: metrics.append(_name) else: attributes.append(_name) column_headers = _form_column_headers(_col_names=col_names, _col_types=col_types) attribute_list = _form_attribute_list(_attributes=attributes) metric_list = _form_metric_list(_metrics=metrics) return column_headers, attribute_list, metric_list
583d4e23b65f984ba202876acb1201c70362d1e4
d7d53826ab804a3d0f229b0a189f2626d4ebe99b
/platforms/renren/tests/__init__.py
80a2fd3dcd7289818ac37ae1ad56d06bdbb697e4
[]
no_license
zbcbcbc/xiaomaifeng
6e299e7f1d13dbca95af7a1e46d66dd0d1c86b08
91b7da9404678227d3c2c4a446777be6dacdedb7
refs/heads/master
2020-12-02T16:58:26.661967
2016-09-04T17:53:51
2016-09-04T17:53:51
67,359,821
0
0
null
null
null
null
UTF-8
Python
false
false
43
py
from platforms.renren.tests.models import *
8079e7c0070fb7f2259f0841bdbfdf4061c16d82
08bfc8a1f8e44adc624d1f1c6250a3d9635f99de
/SDKs/swig/Examples/test-suite/python/overload_numeric_runme.py
5c80fb9fa3daff4ae841ab619589410a4f917df7
[]
no_license
Personwithhat/CE_SDKs
cd998a2181fcbc9e3de8c58c7cc7b2156ca21d02
7afbd2f7767c9c5e95912a1af42b37c24d57f0d4
refs/heads/master
2020-04-09T22:14:56.917176
2019-07-04T00:19:11
2019-07-04T00:19:11
160,623,495
0
0
null
null
null
null
UTF-8
Python
false
false
129
py
version https://git-lfs.github.com/spec/v1 oid sha256:d59bc759f2c6bc1cca8b0a8bc70aca5b1e64ce1a52153ed569bfe234315d4512 size 1317
931602884d1cb512161cc9ce477f276bbb8c1cfa
981f1a81ba19baa36bcb109d55ee8e7520fe5aca
/Orm_test.py
4ae2a3d305124b2e735345ed8a1505038ff06f51
[]
no_license
Pythondeveloper6/Library-System-Python-PyQt5
6f1a43bdeae0d4689ed5da1f6710e7211dae52fd
28971eb5232d2f42de12fb396abacda12b4d3c65
refs/heads/master
2020-09-15T09:41:34.853547
2020-07-01T18:30:15
2020-07-01T18:30:15
223,413,327
24
14
null
2019-12-22T12:21:16
2019-11-22T13:48:48
Python
UTF-8
Python
false
false
621
py
from peewee import * # db = SqliteDatabase('people.db') # Connect to a MySQL database on network. db = MySQLDatabase('myapp', user='root', password='toor', host='localhost', port=3306) class Person(Model): name = CharField() birthday = DateField() class Meta: database = db # This model uses the "people.db" database. class Pet(Model): owner = ForeignKeyField(Person, backref='pets') name = CharField() animal_type = CharField() class Meta: database = db # this model uses the "people.db" database db.connect() db.create_tables([Pet , Person])
886cc2c5fcddba65dc70c85d5cb0c261518b81e4
9340fdb7250d6466899f238fe5fc33b91b062f34
/backend/newwork_1986/settings.py
529c88bcd24aa0bc0340cba58609104e7722128b
[]
no_license
crowdbotics-apps/newwork-1986
09b600d13fcff79afef424d120dfec6944715265
d000f09ac7384fe83e04c64028cda1e0ef9aa033
refs/heads/master
2022-12-15T07:50:34.384076
2019-04-05T17:35:53
2019-04-05T17:35:53
179,727,307
0
0
null
2022-12-06T15:22:15
2019-04-05T17:35:50
JavaScript
UTF-8
Python
false
false
4,740
py
""" Django settings for newwork_1986 project. Generated by 'django-admin startproject' using Django 1.11.16. For more information on this file, see https://docs.djangoproject.com/en/1.11/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.11/ref/settings/ """ import os import environ # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/ env = environ.Env() environ.Env.read_env(os.path.join(BASE_DIR, '.env')) # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = env.str('SECRET_KEY') # SECURITY WARNING: don't run with debug turned on in production! DEBUG = env.bool('DEBUG', default=True) ALLOWED_HOSTS = ['*'] SITE_ID = 1 # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites' ] LOCAL_APPS = [ 'home', ] THIRD_PARTY_APPS = [ 'rest_framework', 'rest_framework.authtoken', 'bootstrap4', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.google', ] INSTALLED_APPS += LOCAL_APPS + THIRD_PARTY_APPS MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', ] ROOT_URLCONF = 'newwork_1986.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates'), ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'newwork_1986.wsgi.application' # Database # https://docs.djangoproject.com/en/1.11/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'newwork_1986', 'USER': 'newwork_1986', 'PASSWORD': 'newwork_1986', 'HOST': 'localhost', 'PORT': '5432', } } if env.str('DATABASE_URL', default=None): DATABASES = { 'default': env.db() } # Password validation # https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/1.11/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.11/howto/static-files/ STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', 'allauth.account.auth_backends.AuthenticationBackend' ) # allauth ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_AUTHENTICATION_METHOD = 'email' ACCOUNT_USERNAME_REQUIRED = False ACCOUNT_EMAIL_VERIFICATION = None LOGIN_REDIRECT_URL = '/' if DEBUG: # output email to console instead of sending EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' EMAIL_HOST = 'smtp.sendgrid.net' EMAIL_HOST_USER = env.str('SENDGRID_USERNAME', '') EMAIL_HOST_PASSWORD = env.str('SENDGRID_PASSWORD', '') EMAIL_PORT = 587 EMAIL_USE_TLS = True # Import local settings try: from .local_settings import * INSTALLED_APPS += DEBUG_APPS except: pass
1136c6923f5b46ab2360eb4494b1157796fcccb7
d83118503614bb83ad8edb72dda7f449a1226f8b
/src/dprj/platinumegg/app/cabaret/views/mgr/model_edit/gacha_header.py
2db815f7f6f2334c265f0fe81fb7afe0a57ec6a9
[]
no_license
hitandaway100/caba
686fe4390e182e158cd9714c90024a082deb8c69
492bf477ac00c380f2b2758c86b46aa7e58bbad9
refs/heads/master
2021-08-23T05:59:28.910129
2017-12-03T19:03:15
2017-12-03T19:03:15
112,512,044
0
0
null
null
null
null
UTF-8
Python
false
false
1,372
py
# -*- coding: utf-8 -*- from platinumegg.app.cabaret.views.mgr.model_edit import AdminModelEditHandler,\ AppModelForm, ModelEditValidError, AppModelChoiceField from defines import Defines from platinumegg.app.cabaret.models.Gacha import GachaHeaderMaster, GachaMaster class Handler(AdminModelEditHandler): """マスターデータの操作. """ class Form(AppModelForm): class Meta: model = GachaHeaderMaster exclude = ( Defines.MASTER_EDITTIME_COLUMN, ) id = AppModelChoiceField(GachaMaster, required=False, label=u'ガチャID') def setting_property(self): self.MODEL_LABEL = u'引抜のヘッダー画像設定' self.html_param['Defines'] = Defines def __valid_master(self, master): if not master.is_public: return if not isinstance(master.header, list): raise ModelEditValidError(u'headerのJSONが壊れています.master=%d' % master.id) # elif len(master.header) == 0: # raise ModelEditValidError(u'空のheaderが設定されています.master=%d' % master.id) def valid_insert(self, master): self.__valid_master(master) def valid_update(self, master): self.__valid_master(master) def main(request): return Handler.run(request)
1dff67206507943c23fc76cad97fd2f5d6e582d1
5ff947dd2e1c6fa35f4b27cbfa7b5d2027a0f699
/backend/manage.py
4ef77aa25ab2afbd68a04d97d8a91f8647411f7c
[]
no_license
crowdbotics-apps/game-3861
17b14ba1fd53b619a3e93ada6727007c742a8c23
d6404952fee48d411fda66803f88fbd01d08e419
refs/heads/master
2022-12-12T15:30:27.157082
2019-05-26T16:35:45
2019-05-26T16:35:45
188,707,474
0
0
null
2022-12-09T04:00:17
2019-05-26T16:35:29
Python
UTF-8
Python
false
false
807
py
#!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "game_3861.settings") try: from django.core.management import execute_from_command_line except ImportError: # The above import may fail for some other reason. Ensure that the # issue is really that Django is missing to avoid masking other # exceptions on Python 2. try: import django except ImportError: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) raise execute_from_command_line(sys.argv)
841c6046c5b6b37c26338a127242921eb0a5ea05
2bbc7ba3ecdb54feffa446ed50297432f249e3dc
/tests/test_addons/test_addon_mtext.py
3aec15c652a5c501ee0432a626c758f40b8ebcd8
[ "MIT" ]
permissive
stephenthoma/ezdxf
16f7b06e43bad55ccf96387e22b68fd624a5d8fb
5cb1fb0298707d69d1b039858523b97990d85fba
refs/heads/master
2020-04-04T11:59:42.480375
2018-04-02T05:01:49
2018-04-02T05:01:49
155,910,581
0
0
NOASSERTION
2018-11-02T19:07:21
2018-11-02T19:07:21
null
UTF-8
Python
false
false
4,379
py
# Created: 09.03.2010, 2018 adapted for ezdxf # Copyright (C) 2010-2018, Manfred Moitzi # License: MIT License from __future__ import unicode_literals __author__ = "mozman <[email protected]>" import pytest import ezdxf from ezdxf.addons import MText @pytest.fixture(scope='module') def dxf(): return ezdxf.new('R12') def test_horiz_top(dxf): layout = dxf.blocks.new('test_horiz_top') text = "lineA\nlineB" mtext = MText(text, (0., 0., 0.), 1.0) mtext.render(layout) assert len(layout) == 2 lines = list(layout) assert lines[0].dxftype() == 'TEXT' assert lines[1].dxftype() == 'TEXT' assert lines[0].dxf.text == 'lineA' assert lines[1].dxf.text == 'lineB' assert lines[0].dxf.align_point == (0, 0, 0) assert lines[1].dxf.align_point == (0, -1, 0) assert lines[0].dxf.valign == MText.TOP assert lines[0].dxf.halign == MText.LEFT def test_horiz_bottom(dxf): layout = dxf.blocks.new('test_horiz_bottom') text = "lineA\nlineB" mtext = MText(text, (0., 0., 0.), 1.0, align='BOTTOM_LEFT') mtext.render(layout) assert len(layout) == 2 lines = list(layout) assert lines[0].dxftype() == 'TEXT' assert lines[1].dxftype() == 'TEXT' assert lines[0].dxf.text == 'lineA' assert lines[1].dxf.text == 'lineB' assert lines[0].dxf.align_point == (0, 1, 0) assert lines[1].dxf.align_point == (0, 0, 0) assert lines[0].dxf.valign == MText.BOTTOM assert lines[0].dxf.halign == MText.LEFT def test_horiz_middle(dxf): layout = dxf.blocks.new('test_horiz_middle') text = "lineA\nlineB" mtext = MText(text, (0., 0., 0.), 1.0, align='MIDDLE_LEFT') mtext.render(layout) assert len(layout) == 2 lines = list(layout) assert lines[0].dxftype() == 'TEXT' assert lines[1].dxftype() == 'TEXT' assert lines[0].dxf.text == 'lineA' assert lines[1].dxf.text == 'lineB' assert lines[0].dxf.align_point == (0, .5, 0) assert lines[1].dxf.align_point == (0, -.5, 0) assert lines[0].dxf.valign == MText.MIDDLE assert lines[0].dxf.halign == MText.LEFT def test_45deg_top(dxf): layout = dxf.blocks.new('test_45deg_top') text = "lineA\nlineB\nlineC" mtext = MText(text, (0., 0., 0.), 1.0, align='TOP_LEFT', rotation=45) mtext.render(layout) assert len(layout) == 3 lines = list(layout) assert lines[0].dxftype() == 'TEXT' assert lines[1].dxftype() == 'TEXT' assert lines[2].dxftype() == 'TEXT' assert lines[0].dxf.text == 'lineA' assert lines[1].dxf.text == 'lineB' assert lines[2].dxf.text == 'lineC' assert lines[0].dxf.align_point == (0, 0, 0) assert lines[1].dxf.align_point == (0.707107, -0.707107, 0) assert lines[2].dxf.align_point == (1.414214, -1.414214, 0) assert lines[0].dxf.rotation == 45 assert lines[0].dxf.valign == MText.TOP assert lines[0].dxf.halign == MText.LEFT def test_45deg_bottom(dxf): layout = dxf.blocks.new('test_45deg_top') text = "lineA\nlineB\nlineC" mtext = MText(text, (0., 0., 0.), 1.0, align='BOTTOM_LEFT', rotation=45) mtext.render(layout) assert len(layout) == 3 lines = list(layout) assert lines[0].dxftype() == 'TEXT' assert lines[1].dxftype() == 'TEXT' assert lines[2].dxftype() == 'TEXT' assert lines[0].dxf.text == 'lineA' assert lines[1].dxf.text == 'lineB' assert lines[2].dxf.text == 'lineC' assert lines[0].dxf.align_point == (-1.414214, 1.414214, 0) assert lines[1].dxf.align_point == (-0.707107, 0.707107, 0) assert lines[2].dxf.align_point == (0, 0, 0) assert lines[0].dxf.rotation == 45 assert lines[0].dxf.valign == MText.BOTTOM assert lines[0].dxf.halign == MText.LEFT def test_one_liner(dxf): layout = dxf.blocks.new('test_one_liner') text = "OneLine" mtext = MText(text, (0., 0., 0.)) mtext.render(layout) assert len(layout) == 1 lines = list(layout) assert lines[0].dxftype() == 'TEXT' assert lines[0].dxf.align_point == (0, 0, 0) assert lines[0].dxf.valign == MText.TOP assert lines[0].dxf.halign == MText.LEFT def test_get_attribute_by_subscript(): mtext = MText("Test\nTest", (0, 0)) layer = mtext['layer'] assert layer == mtext.layer def test_set_attribute_by_subscript(): mtext = MText("Test\nTest", (0, 0)) mtext['layer'] = "modified" assert mtext.layer == "modified"
ad3a475a300d0c1344e0d8e9e66b213d15d22e95
206c10808b6224f7d8236e27cc555e723af695d9
/tomodachi/launcher.py
4a7f1e19743d1f01214c04f799e54b9807194733
[ "MIT" ]
permissive
xdmiodz/tomodachi
3280209ae49100ec902e3b15c323b38e7480cdd3
7ca998a421dd724df5967d5baa0cf79f5112b79b
refs/heads/master
2023-03-15T19:22:16.381212
2023-01-20T07:34:48
2023-01-20T07:34:48
200,020,833
0
2
MIT
2023-03-08T00:00:01
2019-08-01T09:30:22
Python
UTF-8
Python
false
false
12,014
py
import asyncio import datetime import importlib import logging import os import platform import signal import sys import time from typing import Any, Dict, List, Optional, Set, Union, cast import tomodachi.__version__ import tomodachi.container import tomodachi.importer import tomodachi.invoker from tomodachi.container import ServiceContainer from tomodachi.helpers.execution_context import clear_execution_context, clear_services, set_execution_context from tomodachi.helpers.safe_modules import SAFE_MODULES from tomodachi.importer import ServiceImporter CancelledError = asyncio.CancelledError try: asyncioexceptions = getattr(asyncio, "exceptions") if asyncioexceptions: _CancelledError = asyncioexceptions.CancelledError except (Exception, ModuleNotFoundError, ImportError): _CancelledError = asyncio.CancelledError class ServiceLauncher(object): _close_waiter: Optional[asyncio.Future] = None _stopped_waiter: Optional[asyncio.Future] = None restart_services = False services: Set = set() @classmethod def run_until_complete( cls, service_files: Union[List, set], configuration: Optional[Dict] = None, watcher: Any = None, ) -> None: def stop_services() -> None: asyncio.ensure_future(_stop_services()) async def _stop_services() -> None: if cls._close_waiter and not cls._close_waiter.done(): cls._close_waiter.set_result(None) for service in cls.services: try: service.stop_service() except Exception: pass if cls._stopped_waiter: cls._stopped_waiter.set_result(None) if cls._stopped_waiter: await cls._stopped_waiter def sigintHandler(*args: Any) -> None: sys.stdout.write("\b\b\r") sys.stdout.flush() logging.getLogger("system").warning("Received <ctrl+c> interrupt [SIGINT]") cls.restart_services = False def sigtermHandler(*args: Any) -> None: logging.getLogger("system").warning("Received termination signal [SIGTERM]") cls.restart_services = False logging.basicConfig(level=logging.DEBUG) loop = asyncio.get_event_loop() if loop and loop.is_closed(): loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) for signame in ("SIGINT", "SIGTERM"): loop.add_signal_handler(getattr(signal, signame), stop_services) signal.siginterrupt(signal.SIGTERM, False) signal.siginterrupt(signal.SIGUSR1, False) signal.signal(signal.SIGINT, sigintHandler) signal.signal(signal.SIGTERM, sigtermHandler) watcher_future = None if watcher: async def _watcher_restart(updated_files: Union[List, set]) -> None: cls.restart_services = True for file in service_files: try: ServiceImporter.import_service_file(file) except (SyntaxError, IndentationError) as e: logging.getLogger("exception").exception("Uncaught exception: {}".format(str(e))) logging.getLogger("watcher.restart").warning("Service cannot restart due to errors") cls.restart_services = False return pre_import_current_modules = [m for m in sys.modules.keys()] cwd = os.getcwd() for file in updated_files: if file.lower().endswith(".py"): module_name = file[:-3].replace("/", ".") module_name_full_path = "{}/{}".format(os.path.realpath(cwd), file)[:-3].replace("/", ".") try: for m in pre_import_current_modules: if m == module_name or (len(m) > len(file) and module_name_full_path.endswith(m)): ServiceImporter.import_module(file) except (SyntaxError, IndentationError) as e: logging.getLogger("exception").exception("Uncaught exception: {}".format(str(e))) logging.getLogger("watcher.restart").warning("Service cannot restart due to errors") cls.restart_services = False return logging.getLogger("watcher.restart").warning("Restarting services") stop_services() watcher_future = loop.run_until_complete(watcher.watch(loop=loop, callback_func=_watcher_restart)) cls.restart_services = True init_modules = [m for m in sys.modules.keys()] restarting = False while cls.restart_services: init_timestamp = time.time() init_timestamp_str = datetime.datetime.utcfromtimestamp(init_timestamp).isoformat() + "Z" process_id = os.getpid() event_loop_alias = "" event_loop_version = "" try: if "uvloop." in str(loop.__class__): event_loop_alias = "uvloop" import uvloop # noqa # isort:skip event_loop_version = str(uvloop.__version__) elif "asyncio." in str(loop.__class__): event_loop_alias = "asyncio" else: event_loop_alias = "{}.{}".format(loop.__class__.__module__, loop.__class__.__name__) except Exception: event_loop_alias = str(loop) clear_services() clear_execution_context() set_execution_context( { "tomodachi_version": tomodachi.__version__, "python_version": platform.python_version(), "system_platform": platform.system(), "process_id": process_id, "init_timestamp": init_timestamp_str, "event_loop": event_loop_alias, } ) if event_loop_alias == "uvloop" and event_loop_version: set_execution_context( { "uvloop_version": event_loop_version, } ) if watcher: tz: Any = None utc_tz: Any = None try: import pytz # noqa # isort:skip import tzlocal # noqa # isort:skip utc_tz = pytz.UTC try: tz = tzlocal.get_localzone() if not tz: tz = pytz.UTC except Exception: tz = pytz.UTC except Exception: pass init_local_datetime = ( datetime.datetime.fromtimestamp(init_timestamp) if tz and tz is not utc_tz and str(tz) != "UTC" else datetime.datetime.utcfromtimestamp(init_timestamp) ) print("---") print("Starting tomodachi services (pid: {}) ...".format(process_id)) for file in service_files: print("* {}".format(file)) print() print( "Current version: tomodachi {} on Python {}".format( tomodachi.__version__, platform.python_version() ) ) print( "Event loop implementation: {}{}".format( event_loop_alias, " {}".format(event_loop_version) if event_loop_version else "" ) ) if tz: print("Local time: {} {}".format(init_local_datetime.strftime("%B %d, %Y - %H:%M:%S,%f"), str(tz))) print("Timestamp in UTC: {}".format(init_timestamp_str)) print() print("File watcher is active - code changes will automatically restart services") print("Quit running services with <ctrl+c>") print() cls._close_waiter = asyncio.Future() cls._stopped_waiter = asyncio.Future() cls.restart_services = False try: cls.services = set( [ ServiceContainer(ServiceImporter.import_service_file(file), configuration) for file in service_files ] ) result = loop.run_until_complete( asyncio.wait([asyncio.ensure_future(service.run_until_complete()) for service in cls.services]) ) exception = [v.exception() for v in [value for value in result if value][0] if v.exception()] if exception: raise cast(Exception, exception[0]) except tomodachi.importer.ServicePackageError: pass except Exception as e: logging.getLogger("exception").exception("Uncaught exception: {}".format(str(e))) if isinstance(e, ModuleNotFoundError): # pragma: no cover missing_module_name = str(getattr(e, "name", None) or "") if missing_module_name: color = "" color_reset = "" try: import colorama # noqa # isort:skip color = colorama.Fore.WHITE + colorama.Back.RED color_reset = colorama.Style.RESET_ALL except Exception: pass print("") print( "{}[fatal error] The '{}' package is missing or cannot be imported.{}".format( color, missing_module_name, color_reset ) ) print("") if restarting: logging.getLogger("watcher.restart").warning("Service cannot restart due to errors") logging.getLogger("watcher.restart").warning("Trying again in 1.5 seconds") loop.run_until_complete(asyncio.wait([asyncio.sleep(1.5)])) if cls._close_waiter and not cls._close_waiter.done(): cls.restart_services = True else: for signame in ("SIGINT", "SIGTERM"): loop.remove_signal_handler(getattr(signal, signame)) else: for signame in ("SIGINT", "SIGTERM"): loop.remove_signal_handler(getattr(signal, signame)) current_modules = [m for m in sys.modules.keys()] for m in current_modules: if m not in init_modules and m not in SAFE_MODULES: del sys.modules[m] importlib.reload(tomodachi.container) importlib.reload(tomodachi.invoker) importlib.reload(tomodachi.invoker.base) importlib.reload(tomodachi.importer) restarting = True if watcher: if watcher_future and not watcher_future.done(): try: watcher_future.set_result(None) except RuntimeError: # pragma: no cover watcher_future.cancel() if not watcher_future.done(): # pragma: no cover try: loop.run_until_complete(watcher_future) except (Exception, CancelledError, _CancelledError): pass
6f8524311c4daba1891bb1f2acf250e6288f9817
5a628b54e511e6186dcbc8636b530eab48cc6523
/django/template/base.py
67a7b330bed5e1a3646ecffeadb5155a98669f67
[ "BSD-3-Clause", "Python-2.0" ]
permissive
hdknr/annotated-django
9c6241853ce09d0d130a57e0f6611a062cc4f17b
5843908dd6586a54b92d974f45049fa87e64db8b
refs/heads/2.1.x
2021-05-22T08:08:11.469887
2020-01-25T22:41:11
2020-01-25T22:41:11
41,231,818
0
0
NOASSERTION
2019-11-02T22:33:33
2015-08-23T02:04:03
Python
UTF-8
Python
false
false
38,442
py
""" This is the Django template system. How it works: The Lexer.tokenize() method converts a template string (i.e., a string containing markup with custom template tags) to tokens, which can be either plain text (TokenType.TEXT), variables (TokenType.VAR), or block statements (TokenType.BLOCK). The Parser() class takes a list of tokens in its constructor, and its parse() method returns a compiled template -- which is, under the hood, a list of Node objects. Each Node is responsible for creating some sort of output -- e.g. simple text (TextNode), variable values in a given context (VariableNode), results of basic logic (IfNode), results of looping (ForNode), or anything else. The core Node types are TextNode, VariableNode, IfNode and ForNode, but plugin modules can define their own custom node types. Each Node has a render() method, which takes a Context and returns a string of the rendered node. For example, the render() method of a Variable Node returns the variable's value as a string. The render() method of a ForNode returns the rendered output of whatever was inside the loop, recursively. The Template class is a convenient wrapper that takes care of template compilation and rendering. Usage: The only thing you should ever use directly in this file is the Template class. Create a compiled template object with a template_string, then call render() with a context. In the compilation stage, the TemplateSyntaxError exception will be raised if the template doesn't have proper syntax. Sample code: >>> from django import template >>> s = '<html>{% if test %}<h1>{{ varvalue }}</h1>{% endif %}</html>' >>> t = template.Template(s) (t is now a compiled template, and its render() method can be called multiple times with multiple contexts) >>> c = template.Context({'test':True, 'varvalue': 'Hello'}) >>> t.render(c) '<html><h1>Hello</h1></html>' >>> c = template.Context({'test':False, 'varvalue': 'Hello'}) >>> t.render(c) '<html></html>' """ import logging import re from enum import Enum from inspect import getcallargs, getfullargspec, unwrap from django.template.context import ( # NOQA: imported for backwards compatibility BaseContext, Context, ContextPopException, RequestContext, ) from django.utils.formats import localize from django.utils.html import conditional_escape, escape from django.utils.safestring import SafeData, mark_safe from django.utils.text import ( get_text_list, smart_split, unescape_string_literal, ) from django.utils.timezone import template_localtime from django.utils.translation import gettext_lazy, pgettext_lazy from .exceptions import TemplateSyntaxError # template syntax constants FILTER_SEPARATOR = '|' FILTER_ARGUMENT_SEPARATOR = ':' VARIABLE_ATTRIBUTE_SEPARATOR = '.' BLOCK_TAG_START = '{%' BLOCK_TAG_END = '%}' VARIABLE_TAG_START = '{{' VARIABLE_TAG_END = '}}' COMMENT_TAG_START = '{#' COMMENT_TAG_END = '#}' TRANSLATOR_COMMENT_MARK = 'Translators' SINGLE_BRACE_START = '{' SINGLE_BRACE_END = '}' # what to report as the origin for templates that come from non-loader sources # (e.g. strings) UNKNOWN_SOURCE = '<unknown source>' # match a variable or block tag and capture the entire tag, including start/end # delimiters tag_re = (re.compile('(%s.*?%s|%s.*?%s|%s.*?%s)' % (re.escape(BLOCK_TAG_START), re.escape(BLOCK_TAG_END), re.escape(VARIABLE_TAG_START), re.escape(VARIABLE_TAG_END), re.escape(COMMENT_TAG_START), re.escape(COMMENT_TAG_END)))) logger = logging.getLogger('django.template') class TokenType(Enum): TEXT = 0 VAR = 1 BLOCK = 2 COMMENT = 3 class VariableDoesNotExist(Exception): def __init__(self, msg, params=()): self.msg = msg self.params = params def __str__(self): return self.msg % self.params class Origin: def __init__(self, name, template_name=None, loader=None): self.name = name self.template_name = template_name self.loader = loader def __str__(self): return self.name def __eq__(self, other): return ( isinstance(other, Origin) and self.name == other.name and self.loader == other.loader ) @property def loader_name(self): if self.loader: return '%s.%s' % ( self.loader.__module__, self.loader.__class__.__name__, ) class Template: def __init__(self, template_string, origin=None, name=None, engine=None): # If Template is instantiated directly rather than from an Engine and # exactly one Django template engine is configured, use that engine. # This is required to preserve backwards-compatibility for direct use # e.g. Template('...').render(Context({...})) if engine is None: from .engine import Engine engine = Engine.get_default() if origin is None: origin = Origin(UNKNOWN_SOURCE) self.name = name self.origin = origin self.engine = engine self.source = str(template_string) # May be lazy. self.nodelist = self.compile_nodelist() def __iter__(self): for node in self.nodelist: yield from node def _render(self, context): return self.nodelist.render(context) def render(self, context): "Display stage -- can be called many times" with context.render_context.push_state(self): if context.template is None: with context.bind_template(self): context.template_name = self.name return self._render(context) else: return self._render(context) def compile_nodelist(self): """ Parse and compile the template source into a nodelist. If debug is True and an exception occurs during parsing, the exception is is annotated with contextual line information where it occurred in the template source. """ if self.engine.debug: lexer = DebugLexer(self.source) else: lexer = Lexer(self.source) tokens = lexer.tokenize() parser = Parser( tokens, self.engine.template_libraries, self.engine.template_builtins, self.origin, ) try: return parser.parse() except Exception as e: if self.engine.debug: e.template_debug = self.get_exception_info(e, e.token) raise def get_exception_info(self, exception, token): """ Return a dictionary containing contextual line information of where the exception occurred in the template. The following information is provided: message The message of the exception raised. source_lines The lines before, after, and including the line the exception occurred on. line The line number the exception occurred on. before, during, after The line the exception occurred on split into three parts: 1. The content before the token that raised the error. 2. The token that raised the error. 3. The content after the token that raised the error. total The number of lines in source_lines. top The line number where source_lines starts. bottom The line number where source_lines ends. start The start position of the token in the template source. end The end position of the token in the template source. """ start, end = token.position context_lines = 10 line = 0 upto = 0 source_lines = [] before = during = after = "" for num, next in enumerate(linebreak_iter(self.source)): if start >= upto and end <= next: line = num before = escape(self.source[upto:start]) during = escape(self.source[start:end]) after = escape(self.source[end:next]) source_lines.append((num, escape(self.source[upto:next]))) upto = next total = len(source_lines) top = max(1, line - context_lines) bottom = min(total, line + 1 + context_lines) # In some rare cases exc_value.args can be empty or an invalid # string. try: message = str(exception.args[0]) except (IndexError, UnicodeDecodeError): message = '(Could not get exception message)' return { 'message': message, 'source_lines': source_lines[top:bottom], 'before': before, 'during': during, 'after': after, 'top': top, 'bottom': bottom, 'total': total, 'line': line, 'name': self.origin.name, 'start': start, 'end': end, } def linebreak_iter(template_source): yield 0 p = template_source.find('\n') while p >= 0: yield p + 1 p = template_source.find('\n', p + 1) yield len(template_source) + 1 class Token: def __init__(self, token_type, contents, position=None, lineno=None): """ A token representing a string from the template. token_type A TokenType, either .TEXT, .VAR, .BLOCK, or .COMMENT. contents The token source string. position An optional tuple containing the start and end index of the token in the template source. This is used for traceback information when debug is on. lineno The line number the token appears on in the template source. This is used for traceback information and gettext files. """ self.token_type, self.contents = token_type, contents self.lineno = lineno self.position = position def __str__(self): token_name = self.token_type.name.capitalize() return ('<%s token: "%s...">' % (token_name, self.contents[:20].replace('\n', ''))) def split_contents(self): split = [] bits = smart_split(self.contents) for bit in bits: # Handle translation-marked template pieces if bit.startswith(('_("', "_('")): sentinel = bit[2] + ')' trans_bit = [bit] while not bit.endswith(sentinel): bit = next(bits) trans_bit.append(bit) bit = ' '.join(trans_bit) split.append(bit) return split class Lexer: def __init__(self, template_string): self.template_string = template_string self.verbatim = False def tokenize(self): """ Return a list of tokens from a given template_string. """ in_tag = False lineno = 1 result = [] for bit in tag_re.split(self.template_string): if bit: result.append(self.create_token(bit, None, lineno, in_tag)) in_tag = not in_tag lineno += bit.count('\n') return result def create_token(self, token_string, position, lineno, in_tag): """ Convert the given token string into a new Token object and return it. If in_tag is True, we are processing something that matched a tag, otherwise it should be treated as a literal string. """ if in_tag and token_string.startswith(BLOCK_TAG_START): # The [2:-2] ranges below strip off *_TAG_START and *_TAG_END. # We could do len(BLOCK_TAG_START) to be more "correct", but we've # hard-coded the 2s here for performance. And it's not like # the TAG_START values are going to change anytime, anyway. block_content = token_string[2:-2].strip() if self.verbatim and block_content == self.verbatim: self.verbatim = False if in_tag and not self.verbatim: if token_string.startswith(VARIABLE_TAG_START): return Token(TokenType.VAR, token_string[2:-2].strip(), position, lineno) elif token_string.startswith(BLOCK_TAG_START): if block_content[:9] in ('verbatim', 'verbatim '): self.verbatim = 'end%s' % block_content return Token(TokenType.BLOCK, block_content, position, lineno) elif token_string.startswith(COMMENT_TAG_START): content = '' if token_string.find(TRANSLATOR_COMMENT_MARK): content = token_string[2:-2].strip() return Token(TokenType.COMMENT, content, position, lineno) else: return Token(TokenType.TEXT, token_string, position, lineno) class DebugLexer(Lexer): def tokenize(self): """ Split a template string into tokens and annotates each token with its start and end position in the source. This is slower than the default lexer so only use it when debug is True. """ lineno = 1 result = [] upto = 0 for match in tag_re.finditer(self.template_string): start, end = match.span() if start > upto: token_string = self.template_string[upto:start] result.append(self.create_token(token_string, (upto, start), lineno, in_tag=False)) lineno += token_string.count('\n') upto = start token_string = self.template_string[start:end] result.append(self.create_token(token_string, (start, end), lineno, in_tag=True)) lineno += token_string.count('\n') upto = end last_bit = self.template_string[upto:] if last_bit: result.append(self.create_token(last_bit, (upto, upto + len(last_bit)), lineno, in_tag=False)) return result class Parser: def __init__(self, tokens, libraries=None, builtins=None, origin=None): self.tokens = tokens self.tags = {} self.filters = {} self.command_stack = [] if libraries is None: libraries = {} if builtins is None: builtins = [] self.libraries = libraries for builtin in builtins: self.add_library(builtin) self.origin = origin def parse(self, parse_until=None): """ Iterate through the parser tokens and compiles each one into a node. If parse_until is provided, parsing will stop once one of the specified tokens has been reached. This is formatted as a list of tokens, e.g. ['elif', 'else', 'endif']. If no matching token is reached, raise an exception with the unclosed block tag details. """ if parse_until is None: parse_until = [] nodelist = NodeList() while self.tokens: token = self.next_token() # Use the raw values here for TokenType.* for a tiny performance boost. if token.token_type.value == 0: # TokenType.TEXT self.extend_nodelist(nodelist, TextNode(token.contents), token) elif token.token_type.value == 1: # TokenType.VAR 変数トークン if not token.contents: raise self.error(token, 'Empty variable tag on line %d' % token.lineno) try: filter_expression = self.compile_filter(token.contents) except TemplateSyntaxError as e: raise self.error(token, e) # 変数トークンオブジェクトを生成して、リストに追加 var_node = VariableNode(filter_expression) self.extend_nodelist(nodelist, var_node, token) elif token.token_type.value == 2: # TokenType.BLOCK try: command = token.contents.split()[0] except IndexError: raise self.error(token, 'Empty block tag on line %d' % token.lineno) if command in parse_until: # A matching token has been reached. Return control to # the caller. Put the token back on the token list so the # caller knows where it terminated. self.prepend_token(token) return nodelist # Add the token to the command stack. This is used for error # messages if further parsing fails due to an unclosed block # tag. self.command_stack.append((command, token)) # Get the tag callback function from the ones registered with # the parser. try: compile_func = self.tags[command] except KeyError: self.invalid_block_tag(token, command, parse_until) # Compile the callback into a node object and add it to # the node list. try: compiled_result = compile_func(self, token) except Exception as e: raise self.error(token, e) self.extend_nodelist(nodelist, compiled_result, token) # Compile success. Remove the token from the command stack. self.command_stack.pop() if parse_until: self.unclosed_block_tag(parse_until) return nodelist def skip_past(self, endtag): while self.tokens: token = self.next_token() if token.token_type == TokenType.BLOCK and token.contents == endtag: return self.unclosed_block_tag([endtag]) def extend_nodelist(self, nodelist, node, token): # Check that non-text nodes don't appear before an extends tag. if node.must_be_first and nodelist.contains_nontext: raise self.error( token, '%r must be the first tag in the template.' % node, ) if isinstance(nodelist, NodeList) and not isinstance(node, TextNode): nodelist.contains_nontext = True # Set origin and token here since we can't modify the node __init__() # method. node.token = token node.origin = self.origin nodelist.append(node) def error(self, token, e): """ Return an exception annotated with the originating token. Since the parser can be called recursively, check if a token is already set. This ensures the innermost token is highlighted if an exception occurs, e.g. a compile error within the body of an if statement. """ if not isinstance(e, Exception): e = TemplateSyntaxError(e) if not hasattr(e, 'token'): e.token = token return e def invalid_block_tag(self, token, command, parse_until=None): if parse_until: raise self.error( token, "Invalid block tag on line %d: '%s', expected %s. Did you " "forget to register or load this tag?" % ( token.lineno, command, get_text_list(["'%s'" % p for p in parse_until], 'or'), ), ) raise self.error( token, "Invalid block tag on line %d: '%s'. Did you forget to register " "or load this tag?" % (token.lineno, command) ) def unclosed_block_tag(self, parse_until): command, token = self.command_stack.pop() msg = "Unclosed tag on line %d: '%s'. Looking for one of: %s." % ( token.lineno, command, ', '.join(parse_until), ) raise self.error(token, msg) def next_token(self): return self.tokens.pop(0) def prepend_token(self, token): self.tokens.insert(0, token) def delete_first_token(self): del self.tokens[0] def add_library(self, lib): self.tags.update(lib.tags) self.filters.update(lib.filters) def compile_filter(self, token): """ Convenient wrapper for FilterExpression """ return FilterExpression(token, self) def find_filter(self, filter_name): if filter_name in self.filters: return self.filters[filter_name] else: raise TemplateSyntaxError("Invalid filter: '%s'" % filter_name) # This only matches constant *strings* (things in quotes or marked for # translation). Numbers are treated as variables for implementation reasons # (so that they retain their type when passed to filters). constant_string = r""" (?:%(i18n_open)s%(strdq)s%(i18n_close)s| %(i18n_open)s%(strsq)s%(i18n_close)s| %(strdq)s| %(strsq)s) """ % { 'strdq': r'"[^"\\]*(?:\\.[^"\\]*)*"', # double-quoted string 'strsq': r"'[^'\\]*(?:\\.[^'\\]*)*'", # single-quoted string 'i18n_open': re.escape("_("), 'i18n_close': re.escape(")"), } constant_string = constant_string.replace("\n", "") filter_raw_string = r""" ^(?P<constant>%(constant)s)| ^(?P<var>[%(var_chars)s]+|%(num)s)| (?:\s*%(filter_sep)s\s* (?P<filter_name>\w+) (?:%(arg_sep)s (?: (?P<constant_arg>%(constant)s)| (?P<var_arg>[%(var_chars)s]+|%(num)s) ) )? )""" % { 'constant': constant_string, 'num': r'[-+\.]?\d[\d\.e]*', 'var_chars': r'\w\.', 'filter_sep': re.escape(FILTER_SEPARATOR), 'arg_sep': re.escape(FILTER_ARGUMENT_SEPARATOR), } filter_re = re.compile(filter_raw_string, re.VERBOSE) class FilterExpression: """ Parse a variable token and its optional filters (all as a single string), and return a list of tuples of the filter name and arguments. Sample:: >>> token = 'variable|default:"Default value"|date:"Y-m-d"' >>> p = Parser('') >>> fe = FilterExpression(token, p) >>> len(fe.filters) 2 >>> fe.var <Variable: 'variable'> """ def __init__(self, token, parser): self.token = token matches = filter_re.finditer(token) var_obj = None filters = [] upto = 0 for match in matches: start = match.start() if upto != start: raise TemplateSyntaxError("Could not parse some characters: " "%s|%s|%s" % (token[:upto], token[upto:start], token[start:])) if var_obj is None: var, constant = match.group("var", "constant") if constant: try: var_obj = Variable(constant).resolve({}) except VariableDoesNotExist: var_obj = None elif var is None: raise TemplateSyntaxError("Could not find variable at " "start of %s." % token) else: var_obj = Variable(var) else: filter_name = match.group("filter_name") args = [] constant_arg, var_arg = match.group("constant_arg", "var_arg") if constant_arg: args.append((False, Variable(constant_arg).resolve({}))) elif var_arg: args.append((True, Variable(var_arg))) filter_func = parser.find_filter(filter_name) self.args_check(filter_name, filter_func, args) filters.append((filter_func, args)) upto = match.end() if upto != len(token): raise TemplateSyntaxError("Could not parse the remainder: '%s' " "from '%s'" % (token[upto:], token)) self.filters = filters self.var = var_obj def resolve(self, context, ignore_failures=False): if isinstance(self.var, Variable): try: obj = self.var.resolve(context) except VariableDoesNotExist: if ignore_failures: obj = None else: string_if_invalid = context.template.engine.string_if_invalid if string_if_invalid: if '%s' in string_if_invalid: return string_if_invalid % self.var else: return string_if_invalid else: obj = string_if_invalid else: obj = self.var for func, args in self.filters: arg_vals = [] for lookup, arg in args: if not lookup: arg_vals.append(mark_safe(arg)) else: arg_vals.append(arg.resolve(context)) if getattr(func, 'expects_localtime', False): obj = template_localtime(obj, context.use_tz) if getattr(func, 'needs_autoescape', False): new_obj = func(obj, autoescape=context.autoescape, *arg_vals) else: new_obj = func(obj, *arg_vals) if getattr(func, 'is_safe', False) and isinstance(obj, SafeData): obj = mark_safe(new_obj) else: obj = new_obj return obj def args_check(name, func, provided): provided = list(provided) # First argument, filter input, is implied. plen = len(provided) + 1 # Check to see if a decorator is providing the real function. func = unwrap(func) args, _, _, defaults, _, _, _ = getfullargspec(func) alen = len(args) dlen = len(defaults or []) # Not enough OR Too many if plen < (alen - dlen) or plen > alen: raise TemplateSyntaxError("%s requires %d arguments, %d provided" % (name, alen - dlen, plen)) return True args_check = staticmethod(args_check) def __str__(self): return self.token class Variable: """ A template variable, resolvable against a given context. The variable may be a hard-coded string (if it begins and ends with single or double quote marks):: >>> c = {'article': {'section':'News'}} >>> Variable('article.section').resolve(c) 'News' >>> Variable('article').resolve(c) {'section': 'News'} >>> class AClass: pass >>> c = AClass() >>> c.article = AClass() >>> c.article.section = 'News' (The example assumes VARIABLE_ATTRIBUTE_SEPARATOR is '.') """ def __init__(self, var): self.var = var self.literal = None self.lookups = None self.translate = False self.message_context = None if not isinstance(var, str): raise TypeError( "Variable must be a string or number, got %s" % type(var)) try: # First try to treat this variable as a number. # # Note that this could cause an OverflowError here that we're not # catching. Since this should only happen at compile time, that's # probably OK. # Try to interpret values containing a period or an 'e'/'E' # (possibly scientific notation) as a float; otherwise, try int. if '.' in var or 'e' in var.lower(): self.literal = float(var) # "2." is invalid if var.endswith('.'): raise ValueError else: self.literal = int(var) except ValueError: # A ValueError means that the variable isn't a number. if var.startswith('_(') and var.endswith(')'): # The result of the lookup should be translated at rendering # time. self.translate = True var = var[2:-1] # If it's wrapped with quotes (single or double), then # we're also dealing with a literal. try: self.literal = mark_safe(unescape_string_literal(var)) except ValueError: # Otherwise we'll set self.lookups so that resolve() knows we're # dealing with a bonafide variable if var.find(VARIABLE_ATTRIBUTE_SEPARATOR + '_') > -1 or var[0] == '_': raise TemplateSyntaxError("Variables and attributes may " "not begin with underscores: '%s'" % var) self.lookups = tuple(var.split(VARIABLE_ATTRIBUTE_SEPARATOR)) def resolve(self, context): """Resolve this variable against a given context.""" if self.lookups is not None: # We're dealing with a variable that needs to be resolved value = self._resolve_lookup(context) else: # We're dealing with a literal, so it's already been "resolved" value = self.literal if self.translate: is_safe = isinstance(value, SafeData) msgid = value.replace('%', '%%') msgid = mark_safe(msgid) if is_safe else msgid if self.message_context: return pgettext_lazy(self.message_context, msgid) else: return gettext_lazy(msgid) return value def __repr__(self): return "<%s: %r>" % (self.__class__.__name__, self.var) def __str__(self): return self.var def _resolve_lookup(self, context): """ Perform resolution of a real variable (i.e. not a literal) against the given context. As indicated by the method's name, this method is an implementation detail and shouldn't be called by external code. Use Variable.resolve() instead. """ current = context try: # catch-all for silent variable failures for bit in self.lookups: try: # dictionary lookup current = current[bit] # ValueError/IndexError are for numpy.array lookup on # numpy < 1.9 and 1.9+ respectively except (TypeError, AttributeError, KeyError, ValueError, IndexError): try: # attribute lookup # Don't return class attributes if the class is the context: if isinstance(current, BaseContext) and getattr(type(current), bit): raise AttributeError current = getattr(current, bit) except (TypeError, AttributeError): # Reraise if the exception was raised by a @property if not isinstance(current, BaseContext) and bit in dir(current): raise try: # list-index lookup current = current[int(bit)] except (IndexError, # list index out of range ValueError, # invalid literal for int() KeyError, # current is a dict without `int(bit)` key TypeError): # unsubscriptable object raise VariableDoesNotExist("Failed lookup for key " "[%s] in %r", (bit, current)) # missing attribute if callable(current): if getattr(current, 'do_not_call_in_templates', False): pass elif getattr(current, 'alters_data', False): current = context.template.engine.string_if_invalid else: try: # method call (assuming no args required) current = current() except TypeError: try: getcallargs(current) except TypeError: # arguments *were* required current = context.template.engine.string_if_invalid # invalid method call else: raise except Exception as e: template_name = getattr(context, 'template_name', None) or 'unknown' logger.debug( "Exception while resolving variable '%s' in template '%s'.", bit, template_name, exc_info=True, ) if getattr(e, 'silent_variable_failure', False): current = context.template.engine.string_if_invalid else: raise return current class Node: # Set this to True for nodes that must be first in the template (although # they can be preceded by text nodes. must_be_first = False child_nodelists = ('nodelist',) token = None def render(self, context): """ Return the node rendered as a string. """ pass def render_annotated(self, context): """ Render the node. If debug is True and an exception occurs during rendering, the exception is annotated with contextual line information where it occurred in the template. For internal usage this method is preferred over using the render method directly. """ try: return self.render(context) except Exception as e: if context.template.engine.debug and not hasattr(e, 'template_debug'): e.template_debug = context.render_context.template.get_exception_info(e, self.token) raise def __iter__(self): yield self def get_nodes_by_type(self, nodetype): """ Return a list of all nodes (within this node and its nodelist) of the given type """ nodes = [] if isinstance(self, nodetype): nodes.append(self) for attr in self.child_nodelists: nodelist = getattr(self, attr, None) if nodelist: nodes.extend(nodelist.get_nodes_by_type(nodetype)) return nodes class NodeList(list): # Set to True the first time a non-TextNode is inserted by # extend_nodelist(). contains_nontext = False def render(self, context): bits = [] for node in self: if isinstance(node, Node): bit = node.render_annotated(context) else: bit = node bits.append(str(bit)) return mark_safe(''.join(bits)) def get_nodes_by_type(self, nodetype): "Return a list of all nodes of the given type" nodes = [] for node in self: nodes.extend(node.get_nodes_by_type(nodetype)) return nodes class TextNode(Node): def __init__(self, s): self.s = s def __repr__(self): return "<%s: %r>" % (self.__class__.__name__, self.s[:25]) def render(self, context): return self.s def render_value_in_context(value, context): """ Convert any value to a string to become part of a rendered template. This means escaping, if required, and conversion to a string. If value is a string, it's expected to already be translated. """ value = template_localtime(value, use_tz=context.use_tz) # 日時はコンテキストのタイムゾーンに変換 value = localize(value, use_l10n=context.use_l10n) # エンコーディングはコンテキストのロケールに if context.autoescape: if not issubclass(type(value), str): value = str(value) return conditional_escape(value) else: return str(value) class VariableNode(Node): def __init__(self, filter_expression): self.filter_expression = filter_expression def __repr__(self): return "<Variable Node: %s>" % self.filter_expression def render(self, context): try: output = self.filter_expression.resolve(context) except UnicodeDecodeError: # Unicode conversion can fail sometimes for reasons out of our # control (e.g. exception rendering). In that case, we fail # quietly. return '' # レンダリング return render_value_in_context(output, context) # Regex for token keyword arguments kwarg_re = re.compile(r"(?:(\w+)=)?(.+)") def token_kwargs(bits, parser, support_legacy=False): """ Parse token keyword arguments and return a dictionary of the arguments retrieved from the ``bits`` token list. `bits` is a list containing the remainder of the token (split by spaces) that is to be checked for arguments. Valid arguments are removed from this list. `support_legacy` - if True, the legacy format ``1 as foo`` is accepted. Otherwise, only the standard ``foo=1`` format is allowed. There is no requirement for all remaining token ``bits`` to be keyword arguments, so return the dictionary as soon as an invalid argument format is reached. """ if not bits: return {} match = kwarg_re.match(bits[0]) kwarg_format = match and match.group(1) if not kwarg_format: if not support_legacy: return {} if len(bits) < 3 or bits[1] != 'as': return {} kwargs = {} while bits: if kwarg_format: match = kwarg_re.match(bits[0]) if not match or not match.group(1): return kwargs key, value = match.groups() del bits[:1] else: if len(bits) < 3 or bits[1] != 'as': return kwargs key, value = bits[2], bits[0] del bits[:3] kwargs[key] = parser.compile_filter(value) if bits and not kwarg_format: if bits[0] != 'and': return kwargs del bits[:1] return kwargs
48c65b2c68ce49ed81e4e99de686a1e06dc4d029
f0d713996eb095bcdc701f3fab0a8110b8541cbb
/Fe6wvtjcNFwuANuLu_17.py
2edae5acef2d0784cbb3e57f8f1de8dc2e9a243d
[]
no_license
daniel-reich/turbo-robot
feda6c0523bb83ab8954b6d06302bfec5b16ebdf
a7a25c63097674c0a81675eed7e6b763785f1c41
refs/heads/main
2023-03-26T01:55:14.210264
2021-03-23T16:08:01
2021-03-23T16:08:01
350,773,815
0
0
null
null
null
null
UTF-8
Python
false
false
1,088
py
""" A game of table tennis almost always sounds like _Ping!_ followed by _Pong!_ Therefore, you know that Player 2 has won if you hear _Pong!_ as the last sound (since Player 1 didn't return the ball back). Given a list of _Ping!_ , create a function that inserts _Pong!_ in between each element. Also: * If `win` equals `True`, end the list with _Pong!_. * If `win` equals `False`, end with _Ping!_ instead. ### Examples ping_pong(["Ping!"], True) ➞ ["Ping!", "Pong!"] ping_pong(["Ping!", "Ping!"], False) ➞ ["Ping!", "Pong!", "Ping!"] ping_pong(["Ping!", "Ping!", "Ping!"], True) ➞ ["Ping!", "Pong!", "Ping!", "Pong!", "Ping!", "Pong!"] ### Notes * You will always return the ball (i.e. the Pongs are yours). * Player 1 serves the ball and makes _Ping!_. * Return a list of strings. """ def ping_pong(lst, win): l=[] if win: for i in range(len(lst)): l.append("Ping!") l.append("Pong!") return l else: for i in range(len(lst)): l.append("Ping!") l.append("Pong!") l.pop(-1) return l
16d79f6a693248f707912d0602e5b5898033423f
60a525218779f250d725ca4f9677bd626eb687b9
/repos/system_upgrade/common/actors/checkfips/tests/unit_test_checkfips.py
7774352e00b1e0a332de81aef86c509fa0641ce8
[ "Apache-2.0" ]
permissive
examon/leapp-repository
920c9246540a2c603c7c9dfcbf9ae3673487f221
4cedc35b45aeb9131a651c8362f5ff4d89e3b5ee
refs/heads/master
2023-02-24T09:33:10.280795
2023-02-01T10:05:25
2023-02-06T11:03:38
169,085,644
0
0
Apache-2.0
2020-02-24T09:56:34
2019-02-04T13:52:38
Python
UTF-8
Python
false
false
1,403
py
import pytest from leapp.models import KernelCmdline, KernelCmdlineArg, Report from leapp.snactor.fixture import current_actor_context ballast1 = [KernelCmdlineArg(key=k, value=v) for k, v in [ ('BOOT_IMAGE', '/vmlinuz-3.10.0-1127.el7.x86_64'), ('root', '/dev/mapper/rhel_ibm--p8--kvm--03--guest--02-root'), ('ro', ''), ('console', 'tty0'), ('console', 'ttyS0,115200'), ('rd_NO_PLYMOUTH', '')]] ballast2 = [KernelCmdlineArg(key=k, value=v) for k, v in [ ('crashkernel', 'auto'), ('rd.lvm.lv', 'rhel_ibm-p8-kvm-03-guest-02/root'), ('rd.lvm.lv', 'rhel_ibm-p8-kvm-03-guest-02/swap'), ('rhgb', ''), ('quiet', ''), ('LANG', 'en_US.UTF-8')]] @pytest.mark.parametrize('parameters,expected_report', [ ([], False), ([KernelCmdlineArg(key='fips', value='')], False), ([KernelCmdlineArg(key='fips', value='0')], False), ([KernelCmdlineArg(key='fips', value='1')], True), ([KernelCmdlineArg(key='fips', value='11')], False), ([KernelCmdlineArg(key='fips', value='yes')], False) ]) def test_check_fips(current_actor_context, parameters, expected_report): cmdline = KernelCmdline(parameters=ballast1+parameters+ballast2) current_actor_context.feed(cmdline) current_actor_context.run() if expected_report: assert current_actor_context.consume(Report) else: assert not current_actor_context.consume(Report)
d4dfd3cbda727e702637ff99d4c9cb5e3d6eca6d
53fab060fa262e5d5026e0807d93c75fb81e67b9
/backup/user_014/ch167_2020_06_22_20_37_54_917135.py
a99f1260d35132010fb4d2db003a6410b59fc2c4
[]
no_license
gabriellaec/desoft-analise-exercicios
b77c6999424c5ce7e44086a12589a0ad43d6adca
01940ab0897aa6005764fc220b900e4d6161d36b
refs/heads/main
2023-01-31T17:19:42.050628
2020-12-16T05:21:31
2020-12-16T05:21:31
306,735,108
0
0
null
null
null
null
UTF-8
Python
false
false
276
py
def bairro_mais_custoso(gastos): saida_1 = {} saida_2 = {} for x,y in gastos.items(): saida_1[x] = y[6:12] for a,b in saida.items(): saida_2[a] = sum(b) for i,j in saida_2.items(): if j == max(saida_2.values()): return i
9309569dbb1a25d10ac57786f2e48786252a6ec1
05ace8ef6257681ae5b677ad1fcfceb316c5fd24
/moshmosh/repl_apis.py
99b0530c2b6116c52020d0369353a87b90d1a9da
[ "MIT" ]
permissive
thautwarm/moshmosh
cb0e5c2cc7c00886ec5f400629185f32cbe4e8c7
12435ac6288e88b42ea13d59825b90b37e297f38
refs/heads/master
2022-01-09T01:50:34.333840
2020-05-29T01:19:40
2020-05-29T01:19:40
196,604,714
120
7
MIT
2022-01-01T03:36:27
2019-07-12T15:39:55
Python
UTF-8
Python
false
false
4,289
py
from moshmosh.extension import * from moshmosh.extension import _extension_pragma_re_u def update_pragmas(extension_builder: t.Dict[object, Extension], lines): """ Traverse the source codes and extract out the scope of every extension. Incrementally. """ # bind to local for faster visiting in the loop extension_pragma_re = _extension_pragma_re_u registered = Registered.extensions # for new cells of IPython, refresh the scoping info # of the extensions for ext in extension_builder.values(): intervals = ext.activation.intervals if intervals: last = intervals.pop() intervals.clear() if type(last) is int: intervals.append(0) for i, line in enumerate(lines): pragma = extension_pragma_re.match(line) if pragma: pragma = pragma.groupdict() action = pragma['action'] extension = pragma['ext'] params = pragma['params'] or '' params = (param.strip() for param in params.split(',')) params = tuple(i for i in params if i) try: ext_cls = registered[extension] except KeyError: # TODO: add source code position info raise ExtensionNotFoundError(extension) key = (ext_cls, params) ext = extension_builder.get(key, None) if ext is None: try: ext = extension_builder[key] = ext_cls(*params) except Exception as e: raise lineno = i + 1 if action == "+": ext.activation.enable(lineno) else: ext.activation.disable(lineno) return list(extension_builder.values()) def perform_extension_incr( extension_builder: t.Dict[object, Extension], source_code, filename ): str_type = type(source_code) node = ast.parse(source_code, filename) if str_type is bytes: source_code = source_code.decode('utf8') extensions = update_pragmas(extension_builder, StringIO(source_code)) extensions = sum(map(list, solve_deps(extensions)), []) string_io = StringIO() for each in extensions: each.pre_rewrite_src(string_io) for each in extensions: node = each.rewrite_ast(node) ast.fix_missing_locations(node) literal = ast_to_literal(node) string_io.write("import ast as _ast\n") string_io.write("from moshmosh.rewrite_helper import literal_to_ast as _literal_to_ast\n") string_io.write('\n') string_io.write('__literal__ = ') string_io.write(repr(literal)) string_io.write('\n') string_io.write("__ast__ = _literal_to_ast(__literal__)\n") string_io.write('__code__ = compile') string_io.write('(__ast__, ') string_io.write('__import__("os").path.abspath("") if __name__ == "__main__" else __file__,') string_io.write('"exec")\n') string_io.write('exec(__code__, globals())\n') for each in extensions: each.post_rewrite_src(string_io) code = string_io.getvalue() if str_type is bytes: code = bytes(code, encoding='utf8') return code class IPythonSupport: def __init__(self, builder: t.Dict[object, Extension]): self.builder = builder self.tmp_exts = None def input_transform(self, lines): self.tmp_exts = update_pragmas(self.builder, lines) return lines def ast_transform(self, node): extensions = self.tmp_exts extensions = sum(map(list, solve_deps(extensions)), []) prev_io = StringIO() for each in extensions: each.pre_rewrite_src(prev_io) prev_io.write("import ast as _ast\n") prev_io.write("from moshmosh.rewrite_helper import literal_to_ast as _literal_to_ast\n") prev_stmts = ast.parse(prev_io.getvalue()).body for each in extensions: node = each.rewrite_ast(node) ast.fix_missing_locations(node) post_io = StringIO() for each in extensions: each.post_rewrite_src(post_io) post_stmts = ast.parse(post_io.getvalue()).body node.body = prev_stmts + node.body + post_stmts return node
1161e6cadac870db9df449d7395504a2bd9f4d9d
dbb3b3d39f7bd5255d846347b6cd7b153969955c
/packages/vaex-jupyter/vaex/jupyter/view.py
22d3ea574d52d2a61d0b1c553b838233437142c4
[ "MIT" ]
permissive
bbbbpage/vaex
ab02e89cdaf1ec99a13775d292dfcbfdc49c0384
bdf6670b5438bfbdf677477c7c71e69128b063e0
refs/heads/master
2022-07-30T09:26:28.060993
2020-05-22T14:51:58
2020-05-22T14:51:58
null
0
0
null
null
null
null
UTF-8
Python
false
false
11,857
py
from __future__ import absolute_import import sys import vaex.ml import traitlets import ipywidgets as widgets import ipyvuetify as v import numpy as np from IPython.display import display from . import widgets as vw from . import model from .traitlets import traitlet_fixes import matplotlib.colors colors_default = [f'C{i}' for i in range(10)] colors_default = list(map(matplotlib.colors.to_hex, colors_default)) colors_default C0, C1 = colors_default[:2] C0, C1 = '#9ECBF5', '#E0732C' DEBOUNCE_SLICE = 0.1 DEBOUNCE_LIMITS = 0.3 DEBOUNCE_HOVER_SLICED = 3 DEBOUNCE_SELECT = 0.5 ICON_HISTOGRAM = 'histogram' ICON_HEATMAP = 'heatmap' def _translate_selection(selection): if selection in [None, False]: return None if selection is True: return 'default' else: return selection @traitlet_fixes class ViewBase(v.Container): selection_active = traitlets.Unicode(None, allow_none=True) tool = traitlets.Unicode(None, allow_none=True) def __init__(self, **kwargs): super(ViewBase, self).__init__(**kwargs) self.df = self.model.df self.selection_active = _translate_selection(self.model.selections[-1]) self.progress_indicator = vw.ProgressCircularNoAnimation(size=30, width=5, height=20, color=C0, value=10.4, text='') self.progress_text = vw.Status(value=self.model.status_text) traitlets.dlink((self.model, 'status_text'), (self.progress_text, 'value')) self.progress_widget = v.Container(children=[self.progress_indicator, self.progress_text]) # self.progress_widget.layout.width = "95%" # self.progress_widget.layout.max_width = '500px' # self.progress_widget.description = "progress" self.model.signal_grid_progress.connect(self.on_grid_progress) def on_grid_progress(self, fraction): try: with self.output: self.progress_indicator.hidden = False vaex.jupyter.kernel_tick() self.progress_indicator.value = fraction * 100 if fraction == 1: self.hide_progress() return True except Exception as e: # noqa with self.output: print("oops", e) return True @vaex.jupyter.debounced(0.3, skip_gather=True) def hide_progress(self): self.progress_indicator.hidden = True def select_nothing(self): with self.output: name = _translate_selection(self.selection_active) self.df.select_nothing(name=name) def select_rectangle(self, x1, x2, y1, y2, mode='replace'): with self.output: name = _translate_selection(self.selection_active) self.df.select_rectangle(self.model.x.expression, self.model.y.expression, limits=[[x1, x2], [y1, y2]], mode=mode, name=name) def select_x_range(self, x1, x2, mode='replace'): with self.output: name = _translate_selection(self.selection_active) self.df.select_box([self.model.x.expression], [[x1, x2]], mode=mode, name=name) @traitlet_fixes class DataArray(ViewBase): """Will display a DataArray interactively, with an optional custom display_function. By default, it will simply display(...) the DataArray, using xarray's default display mechanism. """ model = traitlets.Instance(model.DataArray) clear_output = traitlets.Bool(True, help="Clear output each time the data changes") display_function = traitlets.Any(display) matplotlib_autoshow = traitlets.Bool(True, help="Will call plt.show() inside output context if open figure handles exist") numpy_errstate = traitlets.Dict({'all': 'ignore'}, help="Default numpy errstate during display to avoid showing error messsages, see :py:data:`numpy.errstate`_ ") def __init__(self, **kwargs): super().__init__(**kwargs) self.output = widgets.Output() self.output_data_array = widgets.Output() self.children = (self.progress_widget, self.output_data_array, self.output) self.model.observe(self.update_output, ['grid', 'grid_sliced']) self.update_output() def update_output(self, change=None): if self.clear_output: self.output_data_array.clear_output(wait=True) with self.output_data_array, np.errstate(**self.numpy_errstate): grid = self.model.grid_sliced if grid is None: grid = self.model.grid if grid is not None: self.display_function(grid) # make sure show is called inside the output widget if self.matplotlib_autoshow and 'matplotlib' in sys.modules: import matplotlib.pyplot as plt if plt.get_fignums(): plt.show() class Heatmap(ViewBase): model = traitlets.Instance(model.Heatmap) normalize = traitlets.Bool(False) colormap = traitlets.Unicode('afmhot') blend = traitlets.Unicode('selections') # TODO: should we expose this trait? tool = traitlets.Unicode(None, allow_none=True) transform = traitlets.Unicode("identity") dimension_fade = traitlets.Unicode('selections') dimension_facets = traitlets.Unicode('groupby1') dimension_alternative = traitlets.Unicode('slice') supports_transforms = True supports_normalize = False def __init__(self, **kwargs): super().__init__(**kwargs) from . import bqplot self.output = widgets.Output() self.plot = bqplot.Heatmap(self.output, self, x_min=self.model.x.min, x_max=self.model.x.max, y_min=self.model.y.min, y_max=self.model.y.max) self.children = (self.progress_widget, self.plot.widget, self.output) grid = self.model.grid if self.model.grid_sliced is not None: grid = self.model.grid_sliced if self.normalize: grid = grid/grid.sum() traitlets.dlink((self, 'tool'), (self.plot, 'tool')) # first dlink our model to the plot traitlets.dlink((self.model.x, 'expression'), (self.plot, 'x_label'), transform=str) traitlets.dlink((self.model.y, 'expression'), (self.plot, 'y_label'), transform=str) # dlink the plot axis to the model traitlets.dlink((self.plot, 'x_min'), (self.model.x, 'min')) traitlets.dlink((self.plot, 'x_max'), (self.model.x, 'max')) traitlets.dlink((self.plot, 'y_min'), (self.model.y, 'min')) traitlets.dlink((self.plot, 'y_max'), (self.model.y, 'max')) self.model.observe(self.update_heatmap, ['grid', 'grid_sliced']) self.observe(self.update_heatmap, ['transform']) if self.model.grid is not None: self.update_heatmap() def update_heatmap(self, change=None): with self.output: grid = self.model.grid if self.dimension_alternative == 'slice': if self.model.grid_sliced is not None: grid = self.model.grid_sliced from vaex.utils import _parse_reduction, _parse_f, _normalize f = _parse_f(self.transform) with np.errstate(divide='ignore', invalid='ignore'): grid = f(grid) # if self.model.grid_sliced is not None: # grid = self.model.grid_sliced # if self.normalize: grid = grid.astype(np.float64) grid, vmin, vmax = _normalize(grid) rgb_image = _parse_reduction("colormap", self.colormap, [])(grid) if rgb_image.shape[0] == 1: rgb_image = rgb_image[0] else: if self.blend == 'selections': rgb_image = vaex.image.fade(rgb_image[::-1]) else: raise ValueError('Unknown what to do with selection') assert rgb_image.ndim == 3 # including color channel rgb_image = np.transpose(rgb_image, (1, 0, 2)) # flip with/height rgb_image = rgb_image.copy() # make contiguous assert rgb_image.shape[-1] == 4, "last dimention is channel" # TODO: we should pass the xarray to plot and let that take tare dims = self.model.grid.dims dim_x = dims[1] dim_y = dims[2] self.plot.x_min = self.model.grid.coords[dim_x].attrs['min'] self.plot.x_max = self.model.grid.coords[dim_x].attrs['max'] self.plot.y_min = self.model.grid.coords[dim_y].attrs['min'] self.plot.y_max = self.model.grid.coords[dim_y].attrs['max'] self.plot.set_rgb_image(rgb_image) class Histogram(ViewBase): model = traitlets.Instance(model.Histogram) normalize = traitlets.Bool(False) dimension_groups = traitlets.Unicode('selections') dimension_facets = traitlets.Unicode('group1') dimension_overplot = traitlets.Unicode('slice') transform = traitlets.Unicode("identity") supports_transforms = False supports_normalize = True def __init__(self, **kwargs): self._control = None super().__init__(**kwargs) self.output = widgets.Output() self.plot = self.create_plot() self.children = (self.progress_widget, self.plot.widget, self.output) widgets.dlink((self, 'tool'), (self.plot, 'tool')) # first dlink our model to the plot widgets.dlink((self.model.x, 'expression'), (self.plot, 'x_label'), transform=str) self.plot.y_label = "count" # set before we observe changes if self.model.x.min is not None: self.plot.x_min = self.model.x.min if self.model.x.max is not None: self.plot.x_max = self.model.x.max # then we sync the limits of the plot with a debouce to the model traitlets.dlink((self.plot, 'x_min'), (self.model.x, 'min')) traitlets.dlink((self.plot, 'x_max'), (self.model.x, 'max')) self.model.observe(self.update_data, ['grid', 'grid_sliced']) self.observe(self.update_data, ['normalize', 'dimension_groups']) @self.output.capture() @vaex.jupyter.debounced(DEBOUNCE_HOVER_SLICED) def unhighlight(): self.plot.highlight(None) self.model.x_slice = None @self.output.capture() # @vaex.jupyter.debounced(DEBOUNCE_SLICE) def on_bar_hover(bar, event): self.model.x_slice = event['data']['index'] self.plot.highlight(self.model.x_slice) unhighlight() self.plot.mark.on_hover(on_bar_hover) if self.model.grid is not None: self.update_data() def create_plot(self): from . import bqplot return bqplot.Histogram(self.output, self) def update_data(self, change=None): ylist = [] colors = [] if self.dimension_groups == 'slice': y0 = self.model.grid[0] ylist.append(y0) colors.append(C0) if self.model.grid_sliced is not None: y1 = self.model.grid_sliced[0] ylist.append(y1) colors.append(C1) elif self.dimension_groups == 'selections': ylist = self.model.grid colors = colors_default[:len(ylist)] else: raise ValueError(f'Unknown action {self.dimension_groups} for dimension_groups') if self.normalize: ylist = [y / np.sum(y) for y in ylist] x = self.model.x.centers self.plot.x_min = self.model.x.min self.plot.x_max = self.model.x.max self.plot.update_data(x, np.array(ylist), colors) class PieChart(Histogram): radius_split_fraction = 0.8 def create_plot(self): from . import bqplot return bqplot.Piechart(self.output, self)
b150aea66bc591e189b33cf0d8f0aa9d5350afed
8ae16d0b53f3b70adab41b307d30148a3b7b6133
/csv_read.py
56bc1dfd50fa8a983b42d8ad2391437544c4817f
[]
no_license
maiorem/python_dataAnalysis
415af6fe401b76e623ba6c336e027d053d8dccc5
a2eb45bfcfb9ed3ae2533c021de1e8537bf2f563
refs/heads/main
2023-03-31T09:28:28.664694
2021-04-04T06:40:02
2021-04-04T06:40:02
354,154,214
1
0
null
null
null
null
UTF-8
Python
false
false
777
py
line_counter=0 data_header=[] employee=[] customer_USA_only_list=[] customer=None with open('customers.csv') as customer_data : while 1: data=customer_data.readline() if not data : break if line_counter==0 : data_header=data.split(",") else : customer=data.split(",") if customer[10].upper()=="USA": customer_USA_only_list.append(customer) line_counter+=1 print("Header : ", data_header) for i in range(0, 10) : print("Data", customer_USA_only_list[i]) print(len(customer_USA_only_list)) with open("customer_USA_only.csv", "w") as customer_USA_only_csv : for customer in customer_USA_only_list : customer_USA_only_csv.write(",".join(customer).strip('\n')+"\n")
12f4d68a13f543af6e710002b21fd31de60dd105
7fd0c4608e32c53fea935ac63cacf66e1a0c971d
/models/ZpHiggs_UFO_2000_70_1500_700/parameters.py
1f1099ab2ac1513eaaff2137a36bd4910bdb225e
[]
no_license
Quantumapple/MadGraph5_cards
285f8a303b04b9745abfc83f5ea4fb06a2922fc9
3db368ada01f59bace11b48eab2f58ab40ba29f2
refs/heads/master
2020-05-02T20:43:23.791641
2020-01-17T16:10:46
2020-01-17T16:10:46
178,199,838
0
2
null
null
null
null
UTF-8
Python
false
false
15,885
py
# This file was automatically created by FeynRules 2.0.28 # Mathematica version: 9.0 for Linux x86 (64-bit) (February 7, 2013) # Date: Tue 7 Mar 2017 15:17:59 from object_library import all_parameters, Parameter from function_library import complexconjugate, re, im, csc, sec, acsc, asec, cot # This is a default parameter object representing 0. ZERO = Parameter(name = 'ZERO', nature = 'internal', type = 'real', value = '0.0', texname = '0') # User-defined parameters. cabi = Parameter(name = 'cabi', nature = 'external', type = 'real', value = 0.227736, texname = '\\theta _c', lhablock = 'CKMBLOCK', lhacode = [ 1 ]) aEWM1 = Parameter(name = 'aEWM1', nature = 'external', type = 'real', value = 127.9, texname = '\\text{aEWM1}', lhablock = 'SMINPUTS', lhacode = [ 1 ]) Gf = Parameter(name = 'Gf', nature = 'external', type = 'real', value = 0.0000116637, texname = 'G_f', lhablock = 'SMINPUTS', lhacode = [ 2 ]) aS = Parameter(name = 'aS', nature = 'external', type = 'real', value = 0.1184, texname = '\\alpha _s', lhablock = 'SMINPUTS', lhacode = [ 3 ]) ymdo = Parameter(name = 'ymdo', nature = 'external', type = 'real', value = 0.00504, texname = '\\text{ymdo}', lhablock = 'YUKAWA', lhacode = [ 1 ]) ymup = Parameter(name = 'ymup', nature = 'external', type = 'real', value = 0.00255, texname = '\\text{ymup}', lhablock = 'YUKAWA', lhacode = [ 2 ]) yms = Parameter(name = 'yms', nature = 'external', type = 'real', value = 0.101, texname = '\\text{yms}', lhablock = 'YUKAWA', lhacode = [ 3 ]) ymc = Parameter(name = 'ymc', nature = 'external', type = 'real', value = 1.27, texname = '\\text{ymc}', lhablock = 'YUKAWA', lhacode = [ 4 ]) ymb = Parameter(name = 'ymb', nature = 'external', type = 'real', value = 4.7, texname = '\\text{ymb}', lhablock = 'YUKAWA', lhacode = [ 5 ]) ymt = Parameter(name = 'ymt', nature = 'external', type = 'real', value = 172, texname = '\\text{ymt}', lhablock = 'YUKAWA', lhacode = [ 6 ]) yme = Parameter(name = 'yme', nature = 'external', type = 'real', value = 0.000511, texname = '\\text{yme}', lhablock = 'YUKAWA', lhacode = [ 11 ]) ymm = Parameter(name = 'ymm', nature = 'external', type = 'real', value = 0.10566, texname = '\\text{ymm}', lhablock = 'YUKAWA', lhacode = [ 13 ]) ymtau = Parameter(name = 'ymtau', nature = 'external', type = 'real', value = 1.777, texname = '\\text{ymtau}', lhablock = 'YUKAWA', lhacode = [ 15 ]) gq = Parameter(name = 'gq', nature = 'external', type = 'real', value = 0.25 , texname = '\\text{gq}', lhablock = 'FRBlock', lhacode = [ 1 ]) gx = Parameter(name = 'gx', nature = 'external', type = 'real', value = 1.001 , texname = '\\text{gx}', lhablock = 'FRBlock', lhacode = [ 2 ]) th = Parameter(name = 'th', nature = 'external', type = 'real', value = 0.01 , texname = '\\text{th}', lhablock = 'FRBlock', lhacode = [ 3 ]) MZ = Parameter(name = 'MZ', nature = 'external', type = 'real', value = 91.1876, texname = '\\text{MZ}', lhablock = 'MASS', lhacode = [ 23 ]) Me = Parameter(name = 'Me', nature = 'external', type = 'real', value = 0.000511, texname = '\\text{Me}', lhablock = 'MASS', lhacode = [ 11 ]) MMU = Parameter(name = 'MMU', nature = 'external', type = 'real', value = 0.10566, texname = '\\text{MMU}', lhablock = 'MASS', lhacode = [ 13 ]) MTA = Parameter(name = 'MTA', nature = 'external', type = 'real', value = 1.777, texname = '\\text{MTA}', lhablock = 'MASS', lhacode = [ 15 ]) MU = Parameter(name = 'MU', nature = 'external', type = 'real', value = 0.00255, texname = 'M', lhablock = 'MASS', lhacode = [ 2 ]) MC = Parameter(name = 'MC', nature = 'external', type = 'real', value = 1.27, texname = '\\text{MC}', lhablock = 'MASS', lhacode = [ 4 ]) MT = Parameter(name = 'MT', nature = 'external', type = 'real', value = 172, texname = '\\text{MT}', lhablock = 'MASS', lhacode = [ 6 ]) MD = Parameter(name = 'MD', nature = 'external', type = 'real', value = 0.00504, texname = '\\text{MD}', lhablock = 'MASS', lhacode = [ 1 ]) MS = Parameter(name = 'MS', nature = 'external', type = 'real', value = 0.101, texname = '\\text{MS}', lhablock = 'MASS', lhacode = [ 3 ]) MB = Parameter(name = 'MB', nature = 'external', type = 'real', value = 4.7, texname = '\\text{MB}', lhablock = 'MASS', lhacode = [ 5 ]) MH = Parameter(name = 'MH', nature = 'external', type = 'real', value = 125, texname = '\\text{MH}', lhablock = 'MASS', lhacode = [ 25 ]) MDM = Parameter(name = 'MDM', nature = 'external', type = 'real', value = 1500 , texname = '\\text{MDM}', lhablock = 'MASS', lhacode = [ 52 ]) MHs = Parameter(name = 'MHs', nature = 'external', type = 'real', value = 70 , texname = '\\text{MHs}', lhablock = 'MASS', lhacode = [ 54 ]) MZP = Parameter(name = 'MZP', nature = 'external', type = 'real', value = 2000 , texname = '\\text{MZP}', lhablock = 'MASS', lhacode = [ 55 ]) WZ = Parameter(name = 'WZ', nature = 'external', type = 'real', value = 2.4952, texname = '\\text{WZ}', lhablock = 'DECAY', lhacode = [ 23 ]) WW = Parameter(name = 'WW', nature = 'external', type = 'real', value = 2.085, texname = '\\text{WW}', lhablock = 'DECAY', lhacode = [ 24 ]) WT = Parameter(name = 'WT', nature = 'external', type = 'real', value = 1.50833649, texname = '\\text{WT}', lhablock = 'DECAY', lhacode = [ 6 ]) WH = Parameter(name = 'WH', nature = 'external', type = 'real', value = 0.00407, texname = '\\text{WH}', lhablock = 'DECAY', lhacode = [ 25 ]) wHs = Parameter(name = 'wHs', nature = 'external', type = 'real', value = 0.001, texname = '\\text{wHs}', lhablock = 'DECAY', lhacode = [ 54 ]) wZp = Parameter(name = 'wZp', nature = 'external', type = 'real', value = 10, texname = '\\text{wZp}', lhablock = 'DECAY', lhacode = [ 55 ]) aEW = Parameter(name = 'aEW', nature = 'internal', type = 'real', value = '1/aEWM1', texname = '\\alpha _{\\text{EW}}') G = Parameter(name = 'G', nature = 'internal', type = 'real', value = '2*cmath.sqrt(aS)*cmath.sqrt(cmath.pi)', texname = 'G') CKM1x1 = Parameter(name = 'CKM1x1', nature = 'internal', type = 'complex', value = 'cmath.cos(cabi)', texname = '\\text{CKM1x1}') CKM1x2 = Parameter(name = 'CKM1x2', nature = 'internal', type = 'complex', value = 'cmath.sin(cabi)', texname = '\\text{CKM1x2}') CKM1x3 = Parameter(name = 'CKM1x3', nature = 'internal', type = 'complex', value = '0', texname = '\\text{CKM1x3}') CKM2x1 = Parameter(name = 'CKM2x1', nature = 'internal', type = 'complex', value = '-cmath.sin(cabi)', texname = '\\text{CKM2x1}') CKM2x2 = Parameter(name = 'CKM2x2', nature = 'internal', type = 'complex', value = 'cmath.cos(cabi)', texname = '\\text{CKM2x2}') CKM2x3 = Parameter(name = 'CKM2x3', nature = 'internal', type = 'complex', value = '0', texname = '\\text{CKM2x3}') CKM3x1 = Parameter(name = 'CKM3x1', nature = 'internal', type = 'complex', value = '0', texname = '\\text{CKM3x1}') CKM3x2 = Parameter(name = 'CKM3x2', nature = 'internal', type = 'complex', value = '0', texname = '\\text{CKM3x2}') CKM3x3 = Parameter(name = 'CKM3x3', nature = 'internal', type = 'complex', value = '1', texname = '\\text{CKM3x3}') wew = Parameter(name = 'wew', nature = 'internal', type = 'real', value = 'MZP/(2.*cmath.sqrt(gx**2))', texname = '\\text{wew}') MW = Parameter(name = 'MW', nature = 'internal', type = 'real', value = 'cmath.sqrt(MZ**2/2. + cmath.sqrt(MZ**4/4. - (aEW*cmath.pi*MZ**2)/(Gf*cmath.sqrt(2))))', texname = 'M_W') ee = Parameter(name = 'ee', nature = 'internal', type = 'real', value = '2*cmath.sqrt(aEW)*cmath.sqrt(cmath.pi)', texname = 'e') ls = Parameter(name = 'ls', nature = 'internal', type = 'real', value = '(MHs**2*cmath.cos(th)**2 + MH**2*cmath.sin(th)**2)/(2.*wew**2)', texname = '\\text{ls}') yx = Parameter(name = 'yx', nature = 'internal', type = 'real', value = '(MDM*cmath.sqrt(2))/wew', texname = '\\text{yx}') sw2 = Parameter(name = 'sw2', nature = 'internal', type = 'real', value = '1 - MW**2/MZ**2', texname = '\\text{sw2}') cw = Parameter(name = 'cw', nature = 'internal', type = 'real', value = 'cmath.sqrt(1 - sw2)', texname = 'c_w') sw = Parameter(name = 'sw', nature = 'internal', type = 'real', value = 'cmath.sqrt(sw2)', texname = 's_w') g1 = Parameter(name = 'g1', nature = 'internal', type = 'real', value = 'ee/cw', texname = 'g_1') gw = Parameter(name = 'gw', nature = 'internal', type = 'real', value = 'ee/sw', texname = 'g_w') vev = Parameter(name = 'vev', nature = 'internal', type = 'real', value = '(2*MW*sw)/ee', texname = '\\text{vev}') lam = Parameter(name = 'lam', nature = 'internal', type = 'real', value = '(MH**2*cmath.cos(th)**2 + MHs**2*cmath.sin(th)**2)/(2.*vev**2)', texname = '\\text{lam}') lhs = Parameter(name = 'lhs', nature = 'internal', type = 'real', value = '-(((-MH**2 + MHs**2)*cmath.cos(th)*cmath.sin(th))/(vev*wew))', texname = '\\text{lhs}') yb = Parameter(name = 'yb', nature = 'internal', type = 'real', value = '(ymb*cmath.sqrt(2))/vev', texname = '\\text{yb}') yc = Parameter(name = 'yc', nature = 'internal', type = 'real', value = '(ymc*cmath.sqrt(2))/vev', texname = '\\text{yc}') ydo = Parameter(name = 'ydo', nature = 'internal', type = 'real', value = '(ymdo*cmath.sqrt(2))/vev', texname = '\\text{ydo}') ye = Parameter(name = 'ye', nature = 'internal', type = 'real', value = '(yme*cmath.sqrt(2))/vev', texname = '\\text{ye}') ym = Parameter(name = 'ym', nature = 'internal', type = 'real', value = '(ymm*cmath.sqrt(2))/vev', texname = '\\text{ym}') ys = Parameter(name = 'ys', nature = 'internal', type = 'real', value = '(yms*cmath.sqrt(2))/vev', texname = '\\text{ys}') yt = Parameter(name = 'yt', nature = 'internal', type = 'real', value = '(ymt*cmath.sqrt(2))/vev', texname = '\\text{yt}') ytau = Parameter(name = 'ytau', nature = 'internal', type = 'real', value = '(ymtau*cmath.sqrt(2))/vev', texname = '\\text{ytau}') yup = Parameter(name = 'yup', nature = 'internal', type = 'real', value = '(ymup*cmath.sqrt(2))/vev', texname = '\\text{yup}') muH = Parameter(name = 'muH', nature = 'internal', type = 'real', value = 'cmath.sqrt(lam*vev**2 + (lhs*wew**2)/2.)', texname = '\\mu') mus2 = Parameter(name = 'mus2', nature = 'internal', type = 'real', value = '(lhs*vev**2)/2. + ls*wew**2', texname = '\\text{mus2}')
7ec62fa65d189134f96ad76d02130a15a9598acd
90419da201cd4948a27d3612f0b482c68026c96f
/sdk/python/pulumi_azure_nextgen/web/latest/web_app_swift_virtual_network_connection.py
3e8952e7afad52a8498263aaa96cb79bcd78486d
[ "BSD-3-Clause", "Apache-2.0" ]
permissive
test-wiz-sec/pulumi-azure-nextgen
cd4bee5d70cb0d332c04f16bb54e17d016d2adaf
20a695af0d020b34b0f1c336e1b69702755174cc
refs/heads/master
2023-06-08T02:35:52.639773
2020-11-06T22:39:06
2020-11-06T22:39:06
312,993,761
0
0
Apache-2.0
2023-06-02T06:47:28
2020-11-15T09:04:00
null
UTF-8
Python
false
false
6,147
py
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union from ... import _utilities, _tables __all__ = ['WebAppSwiftVirtualNetworkConnection'] class WebAppSwiftVirtualNetworkConnection(pulumi.CustomResource): def __init__(__self__, resource_name: str, opts: Optional[pulumi.ResourceOptions] = None, kind: Optional[pulumi.Input[str]] = None, name: Optional[pulumi.Input[str]] = None, resource_group_name: Optional[pulumi.Input[str]] = None, subnet_resource_id: Optional[pulumi.Input[str]] = None, swift_supported: Optional[pulumi.Input[bool]] = None, __props__=None, __name__=None, __opts__=None): """ Swift Virtual Network Contract. This is used to enable the new Swift way of doing virtual network integration. :param str resource_name: The name of the resource. :param pulumi.ResourceOptions opts: Options for the resource. :param pulumi.Input[str] kind: Kind of resource. :param pulumi.Input[str] name: Name of the app. :param pulumi.Input[str] resource_group_name: Name of the resource group to which the resource belongs. :param pulumi.Input[str] subnet_resource_id: The Virtual Network subnet's resource ID. This is the subnet that this Web App will join. This subnet must have a delegation to Microsoft.Web/serverFarms defined first. :param pulumi.Input[bool] swift_supported: A flag that specifies if the scale unit this Web App is on supports Swift integration. """ if __name__ is not None: warnings.warn("explicit use of __name__ is deprecated", DeprecationWarning) resource_name = __name__ if __opts__ is not None: warnings.warn("explicit use of __opts__ is deprecated, use 'opts' instead", DeprecationWarning) opts = __opts__ if opts is None: opts = pulumi.ResourceOptions() if not isinstance(opts, pulumi.ResourceOptions): raise TypeError('Expected resource options to be a ResourceOptions instance') if opts.version is None: opts.version = _utilities.get_version() if opts.id is None: if __props__ is not None: raise TypeError('__props__ is only valid when passed in combination with a valid opts.id to get an existing resource') __props__ = dict() __props__['kind'] = kind if name is None: raise TypeError("Missing required property 'name'") __props__['name'] = name if resource_group_name is None: raise TypeError("Missing required property 'resource_group_name'") __props__['resource_group_name'] = resource_group_name __props__['subnet_resource_id'] = subnet_resource_id __props__['swift_supported'] = swift_supported __props__['type'] = None alias_opts = pulumi.ResourceOptions(aliases=[pulumi.Alias(type_="azure-nextgen:web/v20180201:WebAppSwiftVirtualNetworkConnection"), pulumi.Alias(type_="azure-nextgen:web/v20181101:WebAppSwiftVirtualNetworkConnection"), pulumi.Alias(type_="azure-nextgen:web/v20190801:WebAppSwiftVirtualNetworkConnection"), pulumi.Alias(type_="azure-nextgen:web/v20200601:WebAppSwiftVirtualNetworkConnection")]) opts = pulumi.ResourceOptions.merge(opts, alias_opts) super(WebAppSwiftVirtualNetworkConnection, __self__).__init__( 'azure-nextgen:web/latest:WebAppSwiftVirtualNetworkConnection', resource_name, __props__, opts) @staticmethod def get(resource_name: str, id: pulumi.Input[str], opts: Optional[pulumi.ResourceOptions] = None) -> 'WebAppSwiftVirtualNetworkConnection': """ Get an existing WebAppSwiftVirtualNetworkConnection resource's state with the given name, id, and optional extra properties used to qualify the lookup. :param str resource_name: The unique name of the resulting resource. :param pulumi.Input[str] id: The unique provider ID of the resource to lookup. :param pulumi.ResourceOptions opts: Options for the resource. """ opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id)) __props__ = dict() return WebAppSwiftVirtualNetworkConnection(resource_name, opts=opts, __props__=__props__) @property @pulumi.getter def kind(self) -> pulumi.Output[Optional[str]]: """ Kind of resource. """ return pulumi.get(self, "kind") @property @pulumi.getter def name(self) -> pulumi.Output[str]: """ Resource Name. """ return pulumi.get(self, "name") @property @pulumi.getter(name="subnetResourceId") def subnet_resource_id(self) -> pulumi.Output[Optional[str]]: """ The Virtual Network subnet's resource ID. This is the subnet that this Web App will join. This subnet must have a delegation to Microsoft.Web/serverFarms defined first. """ return pulumi.get(self, "subnet_resource_id") @property @pulumi.getter(name="swiftSupported") def swift_supported(self) -> pulumi.Output[Optional[bool]]: """ A flag that specifies if the scale unit this Web App is on supports Swift integration. """ return pulumi.get(self, "swift_supported") @property @pulumi.getter def type(self) -> pulumi.Output[str]: """ Resource type. """ return pulumi.get(self, "type") def translate_output_property(self, prop): return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop def translate_input_property(self, prop): return _tables.SNAKE_TO_CAMEL_CASE_TABLE.get(prop) or prop
1561dc7a0d4fdcc7d078decb8d7a38e0e0838680
8600ea155f279e5a8dfe5a1926038511f6b6a7ea
/membership/wizard/__init__.py
ab1f292ce8f004d75e6a9cebe2c074fb580a2a84
[]
no_license
MarkNorgate/addons-EAD
c2fff89ab16fce3ba19fbe433ee5863705a6f4e5
840f28642b5d328e4b86839c413e5164622295a5
refs/heads/master
2020-04-23T22:11:00.164438
2015-07-22T12:24:53
2015-07-22T12:24:53
39,501,011
0
0
null
null
null
null
UTF-8
Python
false
false
1,084
py
# -*- encoding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>). All Rights Reserved # $Id$ # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## import invoice_membership # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
e9e2037b55eee5289c172664d2628b589cfd35ef
b7620d0f1a90390224c8ab71774b9c906ab3e8e9
/aliyun-python-sdk-live/aliyunsdklive/request/v20161101/DescribeLiveStreamWatermarksRequest.py
75fdfa4674d65607a75e94f5a4e7d72a1d5becb4
[ "Apache-2.0" ]
permissive
YaoYinYing/aliyun-openapi-python-sdk
e9c62940baee1a35b9ec4a9fbd1e4eb0aaf93b2f
e9a93cc94bd8290d1b1a391a9cb0fad2e6c64627
refs/heads/master
2022-10-17T16:39:04.515562
2022-10-10T15:18:34
2022-10-10T15:18:34
117,057,304
0
0
null
2018-01-11T06:03:02
2018-01-11T06:03:01
null
UTF-8
Python
false
false
1,844
py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # # http://www.apache.org/licenses/LICENSE-2.0 # # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. from aliyunsdkcore.request import RpcRequest from aliyunsdklive.endpoint import endpoint_data class DescribeLiveStreamWatermarksRequest(RpcRequest): def __init__(self): RpcRequest.__init__(self, 'live', '2016-11-01', 'DescribeLiveStreamWatermarks','live') self.set_method('POST') if hasattr(self, "endpoint_map"): setattr(self, "endpoint_map", endpoint_data.getEndpointMap()) if hasattr(self, "endpoint_regional"): setattr(self, "endpoint_regional", endpoint_data.getEndpointRegional()) def get_PageNumber(self): # Integer return self.get_query_params().get('PageNumber') def set_PageNumber(self, PageNumber): # Integer self.add_query_param('PageNumber', PageNumber) def get_PageSize(self): # Integer return self.get_query_params().get('PageSize') def set_PageSize(self, PageSize): # Integer self.add_query_param('PageSize', PageSize) def get_OwnerId(self): # Long return self.get_query_params().get('OwnerId') def set_OwnerId(self, OwnerId): # Long self.add_query_param('OwnerId', OwnerId)
ae433691f368227705fc5d0df3b181e7c53763e9
25ba4b387bf6bb278af1335b18e99ea0389548be
/think_python_solutions/chapter-06/exercise-6.8.py
9b6ed0d969a178a8c2633a592518055b1d9abade
[]
no_license
adwanAK/adwan_python_core
56ffc63b326ec3f6739bc4733c060dc49554f1ae
745922331cf36f65376c55115ee9a3df4d5c0450
refs/heads/master
2022-12-12T21:35:42.387685
2018-09-26T08:53:43
2018-09-26T08:53:43
148,442,004
2
1
null
2022-12-08T02:23:54
2018-09-12T07:46:34
Python
UTF-8
Python
false
false
841
py
#!/usr/bin/env python # encoding: utf-8 """ exercise-6.8.py Greatest commond divisor with Euclid's algorithm. PITA to realize that we must return the function vaule, not simply invoke the gcd function via recursion. Created by Terry Bates on 2012-08-19. Copyright (c) 2012 http://the-awesome-python-blog.posterous.com. All rights reserved.""" def gcd(a,b): # catch base case from the door if b == 0: return a # otherwise, do the other steps else: # compute remainder remainder = a % b # If we have base case, no need to # call again if remainder == 0: return b # otherwise, we recurse and grab the return value else: return gcd(b, remainder) if __name__ == '__main__': print gcd(9, 3) print gcd(15, 12) print gcd(24,8)
f75a4829b19ba35e524480bfe8810f6d7f6964e9
81aaa9ffcbdddf0b6f99a5c4c84adf179fef8f3e
/maml_rl/tests/utils/test_torch_utils.py
3c9d2a02ccef8f45ec2b222cc40ed8c90c499847
[ "MIT" ]
permissive
dkkim93/pytorch-maml-rl
5ffd728d356224136244f46bc32b18c72568d007
6dd0dd7dbf2e8aed29e5c3bbab9f42cfd780c99a
refs/heads/master
2021-07-09T07:28:40.184950
2020-08-10T03:50:10
2020-08-10T03:50:10
174,039,301
1
0
MIT
2019-03-06T00:01:14
2019-03-06T00:01:13
null
UTF-8
Python
false
false
3,711
py
import pytest import numpy as np import torch import torch.nn as nn from maml_rl.utils.torch_utils import (weighted_mean, weighted_normalize, vector_to_parameters) def test_weighted_mean(): lengths = [2, 3, 7, 5, 11] # Inputs inputs_np = np.random.rand(13, 5).astype(np.float32) for i, length in enumerate(lengths): inputs_np[length:, i] = 0. # Pytorch inputs_th = torch.as_tensor(inputs_np) mean_th = weighted_mean(inputs_th, lengths=lengths) # Numpy mean_np = np.zeros((5,), dtype=np.float32) for i, length in enumerate(lengths): for j in range(13): if j < length: mean_np[i] += inputs_np[j, i] mean_np[i] /= length assert mean_th.dim() == 1 assert mean_th.shape == (5,) np.testing.assert_allclose(mean_th.detach().numpy(), mean_np) def test_weighted_mean_multi_dimensional(): lengths = [2, 3, 7, 5, 11] # Inputs inputs_np = np.random.rand(13, 5, 17, 19).astype(np.float32) for i, length in enumerate(lengths): inputs_np[length:, i] = 0. # Pytorch inputs_th = torch.as_tensor(inputs_np) mean_th = weighted_mean(inputs_th, lengths=lengths) # Numpy mean_np = np.zeros((5, 17, 19), dtype=np.float32) for i, length in enumerate(lengths): for j in range(13): if j < length: mean_np[i] += inputs_np[j, i] mean_np[i] /= length assert mean_th.dim() == 3 assert mean_th.shape == (5, 17, 19) np.testing.assert_allclose(mean_th.detach().numpy(), mean_np) def test_weighted_mean_side_effect(): lengths = [2, 3, 7, 5, 11] # Inputs inputs_np = np.random.rand(13, 5).astype(np.float32) # Pytorch inputs_th = torch.as_tensor(inputs_np) mean_th = weighted_mean(inputs_th, lengths=lengths) for i, length in enumerate(lengths): assert (inputs_th[length:, i] == 0.).all() assert (inputs_np[length:, i] == 0.).all() def test_weighted_normalize(): lengths = [2, 3, 7, 5, 11] # Inputs inputs_np = np.random.rand(13, 5).astype(np.float32) # Pytorch inputs_th = torch.as_tensor(inputs_np) normalized_th = weighted_normalize(inputs_th, lengths=lengths) for i, length in enumerate(lengths): assert (normalized_th[length:, i] == 0.).all() def test_vector_to_parameters_no_shared_memory(): model = nn.Sequential( nn.Linear(2, 3, bias=True), nn.Linear(3, 5, bias=True)) num_params = (2 * 3) + 3 + (3 * 5) + 5 vector_np = np.random.rand(num_params).astype(np.float32) vector = torch.as_tensor(vector_np) vector_to_parameters(vector, model.parameters()) pointer = 0 for param in model.parameters(): num_param = param.numel() param_np = param.view(-1).detach().numpy() np.testing.assert_array_equal(param_np, vector_np[pointer:pointer + num_param]) pointer += num_param def test_vector_to_parameters_shared_memory(): model = nn.Sequential( nn.Linear(2, 3, bias=True), nn.Linear(3, 5, bias=True)) model.share_memory() for param in model.parameters(): assert param.data.is_shared() num_params = (2 * 3) + 3 + (3 * 5) + 5 vector_np = np.random.rand(num_params).astype(np.float32) vector = torch.as_tensor(vector_np) vector_to_parameters(vector, model.parameters()) pointer = 0 for param in model.parameters(): num_param = param.numel() param_np = param.view(-1).detach().numpy() np.testing.assert_array_equal(param_np, vector_np[pointer:pointer + num_param]) assert param.data.is_shared() pointer += num_param
d5e42271c0c9c4f4137445c35e1ded34b0605485
b22588340d7925b614a735bbbde1b351ad657ffc
/athena/LArCalorimeter/LArCafJobs/python/GetLBsToIgnore.py
d5216ef4195445e6fc9d1d5401447eaec33faf2e
[]
no_license
rushioda/PIXELVALID_athena
90befe12042c1249cbb3655dde1428bb9b9a42ce
22df23187ef85e9c3120122c8375ea0e7d8ea440
refs/heads/master
2020-12-14T22:01:15.365949
2020-01-19T03:59:35
2020-01-19T03:59:35
234,836,993
1
0
null
null
null
null
UTF-8
Python
false
false
8,238
py
# Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration import sys, string ,re import xmlrpclib from PyCool import cool from CoolConvUtilities.AtlCoolLib import indirectOpen from DQDefects import DefectsDB try: serverfile=open("/afs/cern.ch/user/l/larmon/public/atlasdqmpass.txt") password=serverfile.readline().strip() serverfile.close() except Exception,e: print "Failed to read xmlrpc server connection details from AFS location" print e sys.exit(-1) def getLBsToIgnore(runnum,burstsFromCosmic=True,bulkProcessing=False, dropNonReady=True): badLBs=set() # 1. Get LB range for this run and LBs without "ATLAS-READY" nReadyLBs=0 nNotReadyLBs=0 tdaqdb=indirectOpen('COOLONL_TDAQ/CONDBR2') if (tdaqdb is None): print "ERROR: Can't access COOLONL_TDAQ/CONDBR2" sys.exit(-1) fmode=tdaqdb.getFolder("/TDAQ/RunCtrl/DataTakingMode") since=(runnum<<32)+1 until=((1+runnum)<<32)-1 maxLb=0 minLb=1 itr=fmode.browseObjects(since,until,cool.ChannelSelection.all()) while itr.goToNext(): obj=itr.currentRef() pl=obj.payload() isReady=pl["ReadyForPhysics"] lb1=max(since,obj.since()) & 0xFFFFFFFF ts2=obj.until() if ts2<until: #ignore the IOV beyond the end of the run lb2=ts2 & 0xFFFFFFFF if lb2>maxLb: maxLb=lb2 if not isReady: if dropNonReady: print "Ignoring LumiBlocks %i - %i not ATLAS READY" % (lb1,lb2) badLBs.update(xrange(lb1,lb2)) nNotReadyLBs+=(lb2-lb1) else: nReadyLBs+=(lb2-lb1) pass pass pass pass itr.close() tdaqdb.closeDatabase() print "Run %i goes up to LB %i" % (runnum,maxLb) #2. Get problematic LBs #2.1 Look for collisions in empty bunches - Fetch from DQ Web Server source = 'tier0' stream = 'physics_CosmicCalo' serverstring="https://%[email protected]" % password server = xmlrpclib.ServerProxy(serverstring) multicall = xmlrpclib.MultiCall(server) # Look for the highest(latest) processing version of CosmicCalo by retrieving amitag run_spec = {'source': source, 'high_run': runnum, 'low_run': runnum} multicall.get_procpass_amitag_mapping(run_spec) results = multicall() if len(results[0])==0: print "Nothing found about run",runnum,"on DQM server" proc = 0 try: list = results[0][str(runnum)] for item in list: if ("f" in item[2] and bulkProcessing and "CosmicCalo" in item[1] and item[0]>proc): proc = 2 if ("x" in item[2] and (not bulkProcessing) and "CosmicCalo" in item[1] and item[0]>proc): print item proc = 1 pass pass except Exception,e: print "ERROR: can't retrieve the AMI Tag" print e if (proc == 0): print "I haven't found any processing version for CosmicCalo. Assume express processing" proc=1 try: multicall = xmlrpclib.MultiCall(server) run_spec = {'source': source, 'high_run': runnum, 'stream': stream, 'proc_ver': proc, 'low_run': runnum} multicall.get_timestamp(run_spec) results=multicall() timestamp=results[0][str(runnum)] from time import asctime,localtime print "DQM server timestamp:", asctime(localtime(timestamp)) print "Now: ",asctime() except Exception,e: print "ERROR: can't get timestamp from DQM server" print e multicall = xmlrpclib.MultiCall(server) run_spec = {'source': source, 'high_run': runnum, 'stream': stream, 'proc_ver': proc, 'low_run': runnum} multicall.get_dqmf_all_results(run_spec,'LAr/LAR_GLOBAL/Collisions-Bkg/LArCollTimeLumiBlockTimeCut') results = multicall() RE = re.compile(r'\((?P<lb>\S+)\.0*\)') try: list = results[0][str(runnum)] for item in list: if 'NBins' in item: continue m = RE.search(item).groupdict() lb=int(m['lb']) ncollisions=int(results[0][str(runnum)][item]) if ncollisions > 50: badLBs.add(lb) print "LumiBlock %i ignored because it is empty bunches are polluted with collisions" % lb pass pass except Exception,e: print "ERROR: can't get LArCollTimeLumiBlockTimeCut from DQM server" print e if (burstsFromCosmic):# CosmicCalo stream : from the DQ web histoName = {'EMBC':'BarrelC','EMBA':'BarrelA','EMECC':'EMECC','EMECA':'EMECA'} for iPart in histoName.keys(): multicall = xmlrpclib.MultiCall(server) #multicall.get_dqmf_all_results(run_spec,'LAr/%s/Noise/Partition/NoisyEvent_TimeVeto_%s'%(iPart,histoName[iPart])) multicall.get_dqmf_all_results(run_spec,'/LAr/%s/Occupancy-Noise/Noise_Burst/NoisyEvent_TimeVeto_%s'%(iPart,iPart)) results = multicall() try: resultlist = results[0][str(runnum)] #print "Got %i items for NoisyEvent_TimeVeto_%s" % (len(list),histoName[iPart]) for item in resultlist: if 'NBins' in item: continue m = RE.search(item).groupdict() lb=int(m['lb']) yieldbursts=float(results[0][str(runnum)][item]) if yieldbursts > 0: badLBs.add(lb) print "LumiBlock %i ignored because it contains bursts in CosmicCalo stream in %s" % (lb,iPart) pass pass except Exception,e: print "ERROR: can't get NoisyEvent from DQM server" print e del multicall del server #3.2 Get defects from Defects DB db = DefectsDB() lar_defects = [d for d in (db.defect_names | db.virtual_defect_names) if d.startswith("LAR")] defects = db.retrieve((runnum, minLb), (runnum, maxLb), lar_defects) for defect in defects: part=defect.channel.split("_")[1] #3.2.1 Check for HV trip if "HVTRIP" in defect.channel and defect.present: for lb in range(defect.since.lumi,defect.until.lumi): badLBs.add(lb) print "LumiBlock %i ignored because of a HV trip in partition %s" % (lb,part) pass pass #3.2.2 Check for Noise Bursts from the defects if (not burstsFromCosmic): if not bulkProcessing: if "NOISEBURST" in defect.channel and defect.present: for lb in range(defect.since.lumi,defect.until.lumi): badLBs.add(lb) print "LumiBlock %i ignored because of a noise burst in partition %s" % (lb,part) pass pass else: #not bulk processing if "SEVNOISEBURST" in defect.channel and defect.present: for lb in range(defect.since.lumi,defect.until.lumi): badLBs.add(lb) print "LumiBlock %i ignored because of a severe noise burst in partition %s" % (lb,part) pass pass del db #Close Defects DB nBadLBs=len(badLBs) if dropNonReady: nBadLBs=nBadLBs-nNotReadyLBs print "Found %i not-ready LBs, %i atlas-ready LBs and %i bad LBs" % (nNotReadyLBs,nReadyLBs,nBadLBs) return badLBs ######################################################################## if __name__ == "__main__": import getopt if len(sys.argv) == 1 : print print "usage: python %s <options> <runnumber> "%(sys.argv[0]) print sys.exit(1) burstsFromCosmic=True bulkProcessing=False dropNonReady=True outputFN=None opts,args=getopt.getopt(sys.argv[1:],"brco:",[]) for o,a in opts: if (o=='-c'): burstsFromCosmics=False if (o=='-b'): bulkProcessing=True if (o=='-r'): dropNonReady=False if (o=='-o'): outputFN=a if len(args)<0: print "No run number found" sys.exit(-1) if len(args)>1: print "Too many arguments" sys.exit(-1) run=int(args[0]) if (bulkProcessing): print "Searching for bad lumi blocks in run %d for bulk processing"%run else: print "Searching for bad lumi blocks in run %d for express processing"%run if (dropNonReady): print "LB not marked as AtlasReady will be considered bad" else: print "LB not marked as AtlasReady will be considered good" badLBset=getLBsToIgnore(run,burstsFromCosmic,bulkProcessing, dropNonReady) badLBsorted=sorted(badLBset) print "LBs to ignore:",badLBsorted if outputFN is not None: out=open(outputFN,"w") out.write(', '.join([ str(i) for i in badLBsorted ])) out.write("\n") out.close() # badLBset2=getLBsToIgnore(run) # print "LBs to ignore:",sorted(badLBset)
51f33cc29c4bf5e9a4b13ce80679ec1ace1b8c61
a298d0b4a3e9e12170651a6bf728093b4badfac7
/LeetCode/394 - Decode String/decodeString.py
98d734f3743b24e348b307092d67a1c6b79350b9
[]
no_license
gavinz0228/AlgoPractice
fc8ecd194ea2d26de59df45909838161c802b8cd
1cb183a326a0612a5cd941778500a8265e1d7255
refs/heads/master
2022-07-27T11:42:06.887668
2022-07-18T20:38:31
2022-07-18T20:38:31
172,929,652
1
0
null
null
null
null
UTF-8
Python
false
false
1,021
py
class Solution(object): def decodeString(self, s): """ :type s: str :rtype: str """ return self.getString(s)[0] def getChars(self, s): if not s: return "","" if ord(s[0]) > 57: for i in range(len(s)): if ord(s[i]) <= 57 or s[i]== "]": return s[:i] , s[i:] return s, "" else: return "", s def getString(self, s): result = [] while s and s[0] != "]": _s, _tail = self.getChars(s) __s, __tail = self.getNum(_tail) result.append(_s+__s) s = __tail return "".join(result), s def getNum(self, s): if not s: return "","" if ord(s[0]) <= 57: lb = s.index("[") chars, tail = self.getString( s[lb+1:] ) n = int(s[:lb]) return n*chars, tail[1:] else: return "", s
8f9b74e584166ea6b796806111f5fc467dbaebf4
f36b733f9c24d4cabd0d3354e0344094fbf3c026
/a10_saltstack/helpers/helper_modules/a10_cgnv6_lsn.py
cd9e9303c79271c0cf98e7829c74d1a2739c5a8a
[ "Apache-2.0" ]
permissive
a10networks/a10-saltstack
08e13647e0187b09500ed3d9053ae06e7e808746
0d86043b1d09e75ea170e72fac5068254fc4037c
refs/heads/master
2021-03-19T16:11:14.211706
2019-07-24T17:18:04
2019-07-24T17:18:04
123,501,933
2
3
null
2019-07-24T17:18:05
2018-03-01T22:55:53
Python
UTF-8
Python
false
false
2,223
py
# Copyright 2019 A10 Networks # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Hacky way of having access to object properties for evaluation AVAILABLE_PROPERTIES = ["alg","endpoint_independent_filtering","endpoint_independent_mapping","global","health_check_gateway_list","inside","performance","port_overloading","port_reservation_list","radius","stun_timeout","tcp",] REF_PROPERTIES = { "alg": "/axapi/v3/cgnv6/lsn/alg", "endpoint_independent_filtering": "/axapi/v3/cgnv6/lsn/endpoint-independent-filtering", "endpoint_independent_mapping": "/axapi/v3/cgnv6/lsn/endpoint-independent-mapping", "global": "/axapi/v3/cgnv6/lsn/global", "health_check_gateway_list": "/axapi/v3/cgnv6/lsn/health-check-gateway/{ipv4-addr}+{ipv6-addr}", "inside": "/axapi/v3/cgnv6/lsn/inside", "performance": "/axapi/v3/cgnv6/lsn/performance", "port_overloading": "/axapi/v3/cgnv6/lsn/port-overloading", "port_reservation_list": "/axapi/v3/cgnv6/lsn/port-reservation/{inside}+{inside-port-start}+{inside-port-end}+{nat}+{nat-port-start}+{nat-port-end}", "radius": "/axapi/v3/cgnv6/lsn/radius", "stun_timeout": "/axapi/v3/cgnv6/lsn/stun-timeout", "tcp": "/axapi/v3/cgnv6/lsn/tcp", } MODULE_NAME = "lsn" PARENT_KEYS = [] CHILD_KEYS = [] def new_url(**kwargs): """Return the URL for creating a resource""" # To create the URL, we need to take the format string and return it with no params url_base = "/axapi/v3/cgnv6/lsn" f_dict = {} return url_base.format(**f_dict) def existing_url(**kwargs): """Return the URL for an existing resource""" # Build the format dictionary url_base = "/axapi/v3/cgnv6/lsn" f_dict = {} return url_base.format(**f_dict)
b032bab5b656e6bb9d18d5ee3d3dded0406cb869
f9d564f1aa83eca45872dab7fbaa26dd48210d08
/huaweicloud-sdk-ocr/huaweicloudsdkocr/v1/model/recognize_thailand_license_plate_request.py
c1acf5879b063b5598ca85dc49a3cc438cd447aa
[ "Apache-2.0" ]
permissive
huaweicloud/huaweicloud-sdk-python-v3
cde6d849ce5b1de05ac5ebfd6153f27803837d84
f69344c1dadb79067746ddf9bfde4bddc18d5ecf
refs/heads/master
2023-09-01T19:29:43.013318
2023-08-31T08:28:59
2023-08-31T08:28:59
262,207,814
103
44
NOASSERTION
2023-06-22T14:50:48
2020-05-08T02:28:43
Python
UTF-8
Python
false
false
6,709
py
# coding: utf-8 import six from huaweicloudsdkcore.utils.http_utils import sanitize_for_serialization class RecognizeThailandLicensePlateRequest: """ Attributes: openapi_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ sensitive_list = [] openapi_types = { 'enterprise_project_id': 'str', 'body': 'ThailandLicensePlateRequestBody' } attribute_map = { 'enterprise_project_id': 'Enterprise-Project-Id', 'body': 'body' } def __init__(self, enterprise_project_id=None, body=None): """RecognizeThailandLicensePlateRequest The model defined in huaweicloud sdk :param enterprise_project_id: 企业项目ID。OCR支持通过企业项目管理(EPS)对不同用户组和用户的资源使用,进行分账。 获取方法:进入“[企业项目管理](https://console-intl.huaweicloud.com/eps/?region&#x3D;ap-southeast-2#/projects/list)”页面,单击企业项目名称,在企业项目详情页获取Enterprise-Project-Id(企业项目ID)。 企业项目创建步骤请参见用户指南。 &gt; 说明: 创建企业项目后,在传参时,有以下三类场景。 - 携带正确的ID,正常使用OCR服务,账单归到企业ID对应的企业项目中。 - 携带错误的ID,正常使用OCR服务,账单的企业项目会被分类为“未归集”。 - 不携带ID,正常使用OCR服务,账单的企业项目会被分类为“未归集”。 :type enterprise_project_id: str :param body: Body of the RecognizeThailandLicensePlateRequest :type body: :class:`huaweicloudsdkocr.v1.ThailandLicensePlateRequestBody` """ self._enterprise_project_id = None self._body = None self.discriminator = None if enterprise_project_id is not None: self.enterprise_project_id = enterprise_project_id if body is not None: self.body = body @property def enterprise_project_id(self): """Gets the enterprise_project_id of this RecognizeThailandLicensePlateRequest. 企业项目ID。OCR支持通过企业项目管理(EPS)对不同用户组和用户的资源使用,进行分账。 获取方法:进入“[企业项目管理](https://console-intl.huaweicloud.com/eps/?region=ap-southeast-2#/projects/list)”页面,单击企业项目名称,在企业项目详情页获取Enterprise-Project-Id(企业项目ID)。 企业项目创建步骤请参见用户指南。 > 说明: 创建企业项目后,在传参时,有以下三类场景。 - 携带正确的ID,正常使用OCR服务,账单归到企业ID对应的企业项目中。 - 携带错误的ID,正常使用OCR服务,账单的企业项目会被分类为“未归集”。 - 不携带ID,正常使用OCR服务,账单的企业项目会被分类为“未归集”。 :return: The enterprise_project_id of this RecognizeThailandLicensePlateRequest. :rtype: str """ return self._enterprise_project_id @enterprise_project_id.setter def enterprise_project_id(self, enterprise_project_id): """Sets the enterprise_project_id of this RecognizeThailandLicensePlateRequest. 企业项目ID。OCR支持通过企业项目管理(EPS)对不同用户组和用户的资源使用,进行分账。 获取方法:进入“[企业项目管理](https://console-intl.huaweicloud.com/eps/?region=ap-southeast-2#/projects/list)”页面,单击企业项目名称,在企业项目详情页获取Enterprise-Project-Id(企业项目ID)。 企业项目创建步骤请参见用户指南。 > 说明: 创建企业项目后,在传参时,有以下三类场景。 - 携带正确的ID,正常使用OCR服务,账单归到企业ID对应的企业项目中。 - 携带错误的ID,正常使用OCR服务,账单的企业项目会被分类为“未归集”。 - 不携带ID,正常使用OCR服务,账单的企业项目会被分类为“未归集”。 :param enterprise_project_id: The enterprise_project_id of this RecognizeThailandLicensePlateRequest. :type enterprise_project_id: str """ self._enterprise_project_id = enterprise_project_id @property def body(self): """Gets the body of this RecognizeThailandLicensePlateRequest. :return: The body of this RecognizeThailandLicensePlateRequest. :rtype: :class:`huaweicloudsdkocr.v1.ThailandLicensePlateRequestBody` """ return self._body @body.setter def body(self, body): """Sets the body of this RecognizeThailandLicensePlateRequest. :param body: The body of this RecognizeThailandLicensePlateRequest. :type body: :class:`huaweicloudsdkocr.v1.ThailandLicensePlateRequestBody` """ self._body = body def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, _ in six.iteritems(self.openapi_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: if attr in self.sensitive_list: result[attr] = "****" else: result[attr] = value return result def to_str(self): """Returns the string representation of the model""" import simplejson as json if six.PY2: import sys reload(sys) sys.setdefaultencoding("utf-8") return json.dumps(sanitize_for_serialization(self), ensure_ascii=False) def __repr__(self): """For `print`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, RecognizeThailandLicensePlateRequest): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Returns true if both objects are not equal""" return not self == other
6d49fc4df7c3b8e4dd925d25afe79a6b324151f9
78b160d8131f3c4b7aef0d051b040825a9c50e0d
/algoexpert/threeNumberSum.py
864ca5a9c129c8a28975b66b5644991a336c3890
[ "MIT" ]
permissive
ardakkk/Algorithms-and-Data-Structures
744f8c9ffb233b95040e5bdcbddb9f5d2ff7a5ba
c428bb0bd7eeb6c34448630f88f13e1329b54636
refs/heads/master
2021-07-08T22:40:40.361282
2020-07-20T10:39:58
2020-07-20T10:39:58
156,005,721
0
0
null
null
null
null
UTF-8
Python
false
false
657
py
# Time: 0(n^2) | Space: O(n) def threeNumberSum(array, target_sum): array.sort() triplets = [] for i in range(len(array) - 2): left = i + 1 right = len(array) - 1 while left < right: current_sum = array[i] = array[left] + array[right] if current_sum == target_sum: triplets.append([array[i], array[left], array[right]]) left += 1 right -= 1 elif current_sum < target_sum: left += 1 elif current_sum > target_sum: right -= 1 return triplets print(threeNumberSum([-1, 0, 1, 2, -1, -4], 0))
c780e1290022738f2784cc181bb9b35646860418
315145ec1f997da0ac2dcedc221285b9a8aae3a9
/2016/get_tweetid_boundary.py
91f38626644492392eded816ed26277cf40cc24c
[]
no_license
lukuang/2016-rts
55cc7f942ad674c325e1e906246873016e3b9678
bfe8c57711aa3243419ff4c0487e971eee667aa6
refs/heads/master
2021-01-19T04:21:53.707708
2019-01-03T23:14:46
2019-01-03T23:14:46
61,137,503
1
0
null
null
null
null
UTF-8
Python
false
false
1,432
py
""" generate tweet boundary for each day """ import os import json import sys import re import argparse import codecs import subprocess def get_tweet_id(output): for line in output.split("\n"): tweetid_finder = re.search("<DOCNO>(\d+)",line) if tweetid_finder: return tweetid_finder.group(1) def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--raw_tweet_dir","-rd",default="/infolab/headnode2/lukuang/2016-rts/data/raw/first/reparsed_text/") parser.add_argument("dest_file") args=parser.parse_args() boundary = {} for day_file_name in os.walk(args.raw_tweet_dir).next()[2]: m = re.search("08-(\d+)",day_file_name) if m: day = m.group(1) boundary[day] = { "start":"", "end":"" } day_file = os.path.join(args.raw_tweet_dir,day_file_name) p1 = subprocess.Popen(["head","-10",day_file], stdout=subprocess.PIPE) head_output = p1.communicate()[0] boundary[day]["start"] = get_tweet_id(head_output) p2 = subprocess.Popen(["tail","-10",day_file], stdout=subprocess.PIPE) tail_output = p2.communicate()[0] boundary[day]["end"] = get_tweet_id(tail_output) with open(args.dest_file,"w") as f: f.write(json.dumps(boundary)) if __name__=="__main__": main()
484932b2584a92629dfb5af13608264e37cf192e
3b8ea489dcf2eea47c37156527a2727221e216f3
/virtual/lib/python3.6/site-packages/gunicorn/__init__.py
0edcf51907fe1909fae903ba27d6f143406cb4ac
[ "MIT" ]
permissive
toelapiut/unsplash
d57ec93825ebae7107aea43823b1acbe4e5493f6
a93a694bef7214c64d248e20f3a6b904b463672d
refs/heads/master
2021-08-31T14:49:31.383197
2017-12-21T19:07:11
2017-12-21T19:07:11
111,072,300
5
0
MIT
2017-12-21T19:07:12
2017-11-17T07:31:39
Python
UTF-8
Python
false
false
255
py
# -*- coding: utf-8 - # # This file is part of gunicorn released under the MIT license. # See the NOTICE for more information. version_info = (19, 7, 1) __version__ = ".".join([str(v) for v in version_info]) SERVER_SOFTWARE = "gunicorn/%s" % __version__
ac563116caaf0fd04a8dc147dae27c0f347f95fe
75fa11b13ddab8fd987428376f5d9c42dff0ba44
/metadata-ingestion/tests/integration/git/test_git_clone.py
3436c692f5d95399a53d6f910545ab484c6be3d1
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause", "MIT" ]
permissive
RyanHolstien/datahub
163d0ff6b4636919ed223ee63a27cba6db2d0156
8cf299aeb43fa95afb22fefbc7728117c727f0b3
refs/heads/master
2023-09-04T10:59:12.931758
2023-08-21T18:33:10
2023-08-21T18:33:10
246,685,891
0
0
Apache-2.0
2021-02-16T23:48:05
2020-03-11T21:43:58
TypeScript
UTF-8
Python
false
false
3,961
py
import os import pytest from pydantic import SecretStr from datahub.configuration.common import ConfigurationWarning from datahub.configuration.git import GitInfo, GitReference from datahub.ingestion.source.git.git_import import GitClone LOOKML_TEST_SSH_KEY = os.environ.get("DATAHUB_LOOKML_GIT_TEST_SSH_KEY") def test_base_url_guessing(): # Basic GitHub repo. config = GitInfo(repo="https://github.com/datahub-project/datahub", branch="master") assert config.repo_ssh_locator == "[email protected]:datahub-project/datahub.git" # Defaults to GitHub. config = GitInfo(repo="datahub-project/datahub", branch="master") assert ( config.get_url_for_file_path("docker/README.md") == "https://github.com/datahub-project/datahub/blob/master/docker/README.md" ) assert config.repo_ssh_locator == "[email protected]:datahub-project/datahub.git" # GitLab repo (notice the trailing slash). config_ref = GitReference( repo="https://gitlab.com/gitlab-tests/sample-project/", branch="master" ) assert ( config_ref.get_url_for_file_path("hello_world.md") == "https://gitlab.com/gitlab-tests/sample-project/-/blob/master/hello_world.md" ) # Three-tier GitLab repo. config = GitInfo( repo="https://gitlab.com/gitlab-com/gl-infra/reliability", branch="master" ) assert ( config.get_url_for_file_path("onboarding/gitlab.nix") == "https://gitlab.com/gitlab-com/gl-infra/reliability/-/blob/master/onboarding/gitlab.nix" ) assert ( config.repo_ssh_locator == "[email protected]:gitlab-com/gl-infra/reliability.git" ) # Overrides. config = GitInfo( repo="https://gitea.com/gitea/tea", branch="main", url_template="https://gitea.com/gitea/tea/src/branch/{branch}/{file_path}", repo_ssh_locator="https://gitea.com/gitea/tea.git", ) assert ( config.get_url_for_file_path("cmd/admin.go") == "https://gitea.com/gitea/tea/src/branch/main/cmd/admin.go" ) assert config.repo_ssh_locator == "https://gitea.com/gitea/tea.git" # Deprecated: base_url. with pytest.warns(ConfigurationWarning, match="base_url is deprecated"): config = GitInfo.parse_obj( dict( repo="https://github.com/datahub-project/datahub", branch="master", base_url="http://mygithubmirror.local", ) ) def test_github_branch(): config = GitInfo( repo="owner/repo", ) assert config.branch_for_clone is None config = GitInfo( repo="owner/repo", branch="main", ) assert config.branch_for_clone == "main" def test_git_clone_public(tmp_path): git_clone = GitClone(str(tmp_path)) checkout_dir = git_clone.clone( ssh_key=None, repo_url="https://gitlab.com/gitlab-tests/sample-project", branch="90c439634077a85bcf42d38c2c79cd94664a94ad", ) assert checkout_dir.exists() assert set(os.listdir(checkout_dir)) == { ".git", "README.md", "hello_world.md", "fork-sample-project.png", } @pytest.mark.skipif( LOOKML_TEST_SSH_KEY is None, reason="DATAHUB_LOOKML_GIT_TEST_SSH_KEY env variable is not configured", ) def test_git_clone_private(tmp_path): git_clone = GitClone(str(tmp_path)) secret_key = SecretStr(LOOKML_TEST_SSH_KEY) if LOOKML_TEST_SSH_KEY else None checkout_dir = git_clone.clone( ssh_key=secret_key, repo_url="[email protected]:acryldata/long-tail-companions-looker", branch="d380a2b777ec6f4653626f39c68dba85893faa74", ) assert checkout_dir.exists() assert set(os.listdir(checkout_dir)) == set( [ ".datahub", "models", "README.md", ".github", ".git", "views", "manifest_lock.lkml", "manifest.lkml", ] )
2b811bc4a558ca355bc8465310d5280b36813baf
8ee8fe3c2acea497a85428bfb3dfde19e58b2bc3
/test-examples/issue_673_reproduce.py
aa8cc0108c7bfb6feebd605779c329efcf6936d2
[ "BSD-3-Clause" ]
permissive
sofroniewn/image-demos
a6e46f08fd4ce621aa96d6b6378b50f63ac2b381
2eeeb23f34a47798ae7be0987182724ee3799eb8
refs/heads/master
2022-11-02T23:50:23.098830
2022-10-30T04:38:19
2022-10-30T04:38:19
179,378,745
11
1
null
null
null
null
UTF-8
Python
false
false
729
py
""" Test adding 4D followed by 5D image layers to the viewer Intially only 2 sliders should be present, then a third slider should be created. """ import numpy as np from skimage import data, measure import napari import scipy.ndimage as ndi image = data.binary_blobs(128, n_dim=3) verts, faces, normals, values = ( measure.marching_cubes_lewiner(image.astype(float), level=0.7) ) labels = ndi.label(image)[0] vertex_labels = ndi.map_coordinates(labels, verts.T, order=0).astype(int) with napari.gui_qt(): viewer = napari.view_surface((verts, faces, values)) surf_layer = viewer.add_surface((verts, faces, vertex_labels), colormap='gist_earth') viewer.dims.ndisplay = 3
05f26dba9cb6933495ecf2bc530966099292e3d2
6c14069181f313e84eeb524dd495e3882156ef50
/samples/basic/executor/models/cisco-ios-xr/Cisco-IOS-XR-cfgmgr-rollback-act/nc-execute-xr-cfgmgr-rollback-act-42-ydk.py
9ef12861c74cd7aea090947f557c9240b9294995
[ "Apache-2.0" ]
permissive
decolnz/ydk-py-samples
dde0fd64fd4df12a215588766a0f1fb8baf07fcd
7fa3f53c4d458c3332d372fb2fe3c46c5e036f07
refs/heads/master
2021-01-19T03:24:19.877929
2017-04-04T17:16:46
2017-04-04T17:16:46
87,310,389
1
0
null
2017-04-05T13:06:57
2017-04-05T13:06:57
null
UTF-8
Python
false
false
3,204
py
#!/usr/bin/env python # # Copyright 2016 Cisco Systems, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # """ Execute RPC for model Cisco-IOS-XR-cfgmgr-rollback-act. usage: nc-execute-xr-cfgmgr-rollback-act-42-ydk.py [-h] [-v] device positional arguments: device NETCONF device (ssh://user:password@host:port) optional arguments: -h, --help show this help message and exit -v, --verbose print debugging messages """ from argparse import ArgumentParser from urlparse import urlparse from ydk.services import ExecutorService from ydk.providers import NetconfServiceProvider from ydk.models.cisco_ios_xr import Cisco_IOS_XR_cfgmgr_rollback_act \ as xr_cfgmgr_rollback_act import logging def prepare_roll_back_configuration_to_exclude_rpc(roll_back_configuration_to_exclude_rpc): """Add RPC input data to roll_back_configuration_to_exclude_rpc object.""" # roll back to (but excluding) specific commit id roll_back_configuration_to_exclude_rpc.input.comment = "Simple programmatic rollback" roll_back_configuration_to_exclude_rpc.input.commit_id = "1000000010" if __name__ == "__main__": """Execute main program.""" parser = ArgumentParser() parser.add_argument("-v", "--verbose", help="print debugging messages", action="store_true") parser.add_argument("device", help="NETCONF device (ssh://user:password@host:port)") args = parser.parse_args() device = urlparse(args.device) # log debug messages if verbose argument specified if args.verbose: logger = logging.getLogger("ydk") logger.setLevel(logging.DEBUG) handler = logging.StreamHandler() formatter = logging.Formatter(("%(asctime)s - %(name)s - " "%(levelname)s - %(message)s")) handler.setFormatter(formatter) logger.addHandler(handler) # create NETCONF provider provider = NetconfServiceProvider(address=device.hostname, port=device.port, username=device.username, password=device.password, protocol=device.scheme) # create executor service executor = ExecutorService() roll_back_configuration_to_exclude_rpc = xr_cfgmgr_rollback_act.RollBackConfigurationToExcludeRpc() # create object prepare_roll_back_configuration_to_exclude_rpc(roll_back_configuration_to_exclude_rpc) # add RPC input # execute RPC on NETCONF device executor.execute_rpc(provider, roll_back_configuration_to_exclude_rpc) provider.close() exit() # End of script
bf676537a89da5673703b3507daf8b5d7be47720
161d96f4b16e1cc7e473f12b7070aa9f5615e28e
/iternal/discord/cogs/admin/debug.py
d348403298838515aca40e1a29a7ddeae2b6b833
[]
no_license
pikoUsername/prison-bot
be717d4d64eb18d922bf808bb9d48db659269318
c6b8df54e71a4f0fc0fa1568d9da070a290d43da
refs/heads/master
2023-04-02T18:46:52.034934
2021-04-13T05:07:41
2021-04-13T05:07:41
345,583,521
0
0
null
null
null
null
UTF-8
Python
false
false
1,744
py
from discord.ext import commands as commands from discord import Embed as Embed from .utils import log as log from iternal.discord.loader import _ as __, proj_root as proj_root from iternal.store.prison import Prison as Prison class Debugger(commands.Cog, name='pantry | Кладовка'): """ Использвать для того что бы не копатся в говно коде. For not change shit code. """ __slots__ = "bot", def __init__(self, bot): self.bot = bot @commands.command(name="show_logs", help=__("shows last logs")) @commands.is_owner() async def show_logs(self, ctx, file: str = None): if not file: last_log_path = log.last_file() with open(proj_root / "logs" / last_log_path) as f: result = f.read() e = Embed( title=last_log_path.name, description=result ) await ctx.send(embed=e) return e = Embed( title=file, description="".join(await log.read_log( proj_root / "logs" / file )) ) await ctx.send(embed=e) @commands.group(name="i18n") @commands.has_permissions(administrator=True) async def change_guild_language(self, ctx, language: str): try: await Prison.change_lang(language, ctx.guild.id) except TypeError as ex: await ctx.send(embed=Embed( title=__("Выбран неправильный язык"), description=f"```{str(ex)}```" )) return else: await ctx.send(__("Успешно изменен язык на {language}").format(language))
064c47c344a4c113a40b9dfe3e8c77cca1f181ac
415a8a4315e6331b2a157de8a1429fe0562729f8
/python/matplotlib/axisSciNotation.py
72ae2b7e657fd9d1a2ed94320b673af0cd30a29a
[]
no_license
alfaceor/programming-examples
784690dd1104e4adbdf958e4163b3b462f635881
abea970a54cfab0eacc5280ae62383495e9e6eeb
refs/heads/master
2022-05-04T23:14:30.503114
2022-04-29T10:11:45
2022-04-29T10:11:45
36,015,541
0
0
null
null
null
null
UTF-8
Python
false
false
1,197
py
#!/usr/bin/python import numpy as np import matplotlib.pyplot as plt import matplotlib.ticker as mtick ###### BEGIN PLOT DECORATION VARIABLES font = {'family' : 'normal', 'weight' : 'bold', 'size' : 18} plt.rc('font', **font) plt.rc('text', usetex=True) ###### END PLOT DECORATION VARIABLES XX = np.linspace(0.0000001, 0.000001, num=20 ) YY = np.linspace(100000, 100002, 20) fig, ax = plt.subplots() ax.set_xlabel("$\sqrt{x}$", size=30) ax.tick_params(axis='x', labelsize=10) ax.tick_params(axis='y', labelsize=10) ax.ticklabel_format(useOffset=True, useMathText=True, style='sci', axis='x', scilimits=(0,0) ) ax.ticklabel_format( useMathText=True, style='sci', axis='y', scilimits=(0,0) ) #ax.ticklabel_format(useOffset=False) offset = ax.yaxis.get_offset_text() print offset print offset.get_position() offset.set_x(0.2) offset.set_y(1.0) offset.set_fontsize(10) print "get_text() = ", offset.get_text() print "get_usetex() = ", offset.get_usetex() print offset.get_position() offset.set_usetex("AAA") print "get_text() = ", offset.get_text() ax.plot(XX,YY) #ax.xaxis.set_major_formatter(mtick.ScalarFormatter(useMathText=True)) fig.tight_layout() plt.show()
[ "alfaceor" ]
alfaceor
548b27946f87ef8704f9fc1a9ba223e08c830efa
6a3af6fe669b2e17db1fa7d0751cbc4e04948079
/fn_icdx/tests/test_icdx_helper.py
9b02b54530b75dba078fdc5e236bea2fe5278b8f
[ "MIT" ]
permissive
jjfallete/resilient-community-apps
5f0a728fe0be958acc44d982bf0289959f84aa20
2e3c4b6102555517bad22bf87fa4a06341714166
refs/heads/master
2022-04-17T13:20:36.961976
2020-04-13T07:03:54
2020-04-13T07:03:54
169,295,943
1
0
MIT
2020-04-13T07:03:56
2019-02-05T19:06:57
Python
UTF-8
Python
false
false
5,963
py
# -*- coding: utf-8 -*- # (c) Copyright IBM Corp. 2010, 2018. All Rights Reserved. """Tests using pytest_resilient_circuits""" from __future__ import print_function import pytest from fn_icdx.util.helper import ICDXHelper class TestIcdxUtilitiesHelper: """ Tests for the helper class""" @pytest.mark.parametrize("input_dict", [ (({},{},{})), (({'Malware SHA-256 Hash': u'E1B8TEST', 'File Path': u'c:\\workarea\\TEST', 'File Name': u'TEST'}, {}, {'Malware MD5 Hash': u'C1B07TEST'})), (({'Malware SHA-256 Hash': u'E1B8TEST', 'File Path': u'c:\\workarea\\TEST', 'File Name': u'TEST'}, None)) ]) def test_dictionary_merge(self, input_dict): """ Test that the dictionary merge function works as expected. The function should return a dictionary If 1 or all inputs or None or empty it should not affect the return type""" helper = ICDXHelper({}) result = helper.merge_dicts(input_dict) assert(isinstance(result, dict)) @pytest.mark.parametrize("input_dict", [ (({}, {}, {})), (({},None, {})), (({}, None)) ]) def test_dictionary_merge_failure(self, input_dict): """ Test that the dictionary merge function handles empty inputs. The function should return a dictionary If 1 or all inputs or None or empty it should not affect the return type But if all inputs are None or empty the return should be False-y i.e empty dict""" helper = ICDXHelper({}) result = helper.merge_dicts(input_dict) assert (isinstance(result, dict)) assert(bool(result) == False) @pytest.mark.parametrize("search_result", [ ({"name": "Test","file":{'sha2': u'E1B8TEST', 'path': u'c:\\workarea\\TEST', 'name': u'TEST', 'md5': u'C1B07TEST'}}), ({"name": "Test","file":{'sha2': u'E1B8TEST', 'path': u'c:\\workarea\\TEST'}}), ]) def test_file_artifact_parse_success(self, search_result): """ Test that the file artifact function works as expected The function should return a dictionary With a known good input the return should be Truth-y (has elements) """ helper = ICDXHelper({}) result = helper.parse_for_file_artifacts(search_result) assert (isinstance(result, dict)) assert (bool(result)) @pytest.mark.parametrize("search_result", [ ({"name": "Test"}), ({"name": "Test", "file": {}}), ]) def test_file_artifact_parse_failure(self, search_result): helper = ICDXHelper({}) result = helper.parse_for_file_artifacts(search_result) assert (not result) assert (bool(result) is False) @pytest.mark.parametrize("search_result", [ ({"name": "Test", "connection": {'dst_ip':'192.168.1.1', 'dst_mac':'mac', 'dst_name':'test_conn', 'dst_port':80}}), ({"name": "Test", "connection": {'src_ip':'10.1.1.1', 'src_mac':'mac2', 'src_name':'test_conn2', 'src_port':8080}}), ]) def test_network_artifact_parse_success(self, search_result): """ Test that the file artifact function works as expected The function should return a dictionary With a known good input the return should be Truth-y (has elements) """ helper = ICDXHelper({}) result = helper.parse_for_network_artifacts(search_result) assert (isinstance(result, dict)) assert (bool(result)) @pytest.mark.parametrize("search_result", [ ({"name": "Test"}), ({"name": "Test", "connection": {}}), ]) def test_network_artifact_parse_failure(self, search_result): helper = ICDXHelper({}) result = helper.parse_for_network_artifacts(search_result) assert (not result) assert (bool(result) is False) @pytest.mark.parametrize("search_result", [ ({"name": "Test", "email": {'header_subject': u'Important updates', 'header_from': u'testuser2', 'header_to': u'testuser2'}}), ({"name": "Test", "email": {'header_subject': u'New version of software', 'header_from': u'testuser'}}), ]) def test_email_artifact_parse_success(self, search_result): """ Test that the file artifact function works as expected The function should return a dictionary With a known good input the return should be Truth-y (has elements) """ helper = ICDXHelper({}) result = helper.parse_for_email_artifacts(search_result) assert (isinstance(result, dict)) assert (bool(result)) @pytest.mark.parametrize("search_result", [ ({"name": "Test"}), ({"name": "Test", "email": {}}), ]) def test_email_artifact_parse_failure(self, search_result): helper = ICDXHelper({}) result = helper.parse_for_email_artifacts(search_result) assert (not result) assert (bool(result) is False) @pytest.mark.parametrize("search_result", [ ({"name": "Test with email object ", "connection": {'dst_ip': '10.1.1.1', 'dst_mac': 'mac', 'dst_name': 'test_conn', 'dst_port': 80}, 'email' :{'sender_ip':'127.0.0.1'}}), ({"name": "Test with email object 2", "connection": {'src_ip': '10.1.1.1', 'src_mac': 'mac2', 'src_name': 'test_conn2', 'src_port': 8080},'email' :{'sender_ip':'127.0.0.1'}}), ]) def test_multi_artifact_parse_success(self, search_result): """ Test that the file artifact function works as expected The function should return a dictionary With a known good input the return should be Truth-y (has elements) """ helper = ICDXHelper({}) result = helper.search_for_artifact_data(search_result) assert (isinstance(result, dict)) assert (result is not None) assert '10.1.1.1' in result['IP Address'] if 'email object' in search_result['name']: assert '127.0.0.1' in result['IP Address']
677afc8e9b4fedb3137341367891adad32492c94
00fc70953dd85f2699fc80cd7c59e9c472cbb90e
/test/test_retention_metadata.py
841367183a76561a116775360f9a0f8cb528dae3
[ "MIT" ]
permissive
solidgoldbomb/python-harbor
89b270caaa6ac450245753c0a3a13af3ff96c142
4a12789a9712cc101abd3f8d32464bc8a474e0a4
refs/heads/main
2023-02-25T20:22:19.137094
2021-02-01T11:58:24
2021-02-01T11:58:24
null
0
0
null
null
null
null
UTF-8
Python
false
false
880
py
# coding: utf-8 """ Harbor API These APIs provide services for manipulating Harbor project. # noqa: E501 OpenAPI spec version: 2.0 Generated by: https://github.com/swagger-api/swagger-codegen.git """ from __future__ import absolute_import import unittest import harbor from harbor.models.retention_metadata import RetentionMetadata # noqa: E501 from harbor.rest import ApiException class TestRetentionMetadata(unittest.TestCase): """RetentionMetadata unit test stubs""" def setUp(self): pass def tearDown(self): pass def testRetentionMetadata(self): """Test RetentionMetadata""" # FIXME: construct object with mandatory attributes with example values # model = harbor.models.retention_metadata.RetentionMetadata() # noqa: E501 pass if __name__ == '__main__': unittest.main()
a1a70d3b122ddbe41c7677983806a28e4eeed340
0b60be2c526149603fcbd3f1a40545ed5d6ed1fc
/uiautomator2/exceptions.py
c5cc3d53d859bec09c096e8a1a9a6578010f23ac
[ "MIT" ]
permissive
levixie/uiautomator2
6f2d4eb1bd1e416dc6ad8a0e50f56dd2f1344530
7fa465601d747aad5c673d603486ad2145b9e860
refs/heads/master
2020-05-20T20:55:13.068591
2019-06-23T23:03:57
2019-06-23T23:03:57
185,751,403
0
0
MIT
2019-06-23T23:03:58
2019-05-09T07:46:01
Python
UTF-8
Python
false
false
1,802
py
# coding: utf-8 # # class ATXError(Exception): # pass class UiaError(Exception): pass class ConnectError(UiaError): pass class XPathElementNotFoundError(UiaError): pass class GatewayError(UiaError): def __init__(self, response, description): self.response = response self.description = description def __str__(self): return "uiautomator2.GatewayError(" + self.description + ")" class JsonRpcError(UiaError): @staticmethod def format_errcode(errcode): m = { -32700: 'Parse error', -32600: 'Invalid Request', -32601: 'Method not found', -32602: 'Invalid params', -32603: 'Internal error', -32001: 'Jsonrpc error', -32002: 'Client error', } if errcode in m: return m[errcode] if errcode >= -32099 and errcode <= -32000: return 'Server error' return 'Unknown error' def __init__(self, error={}, method=None): self.code = error.get('code') self.message = error.get('message', '') self.data = error.get('data', '') self.method = method def __str__(self): return '%d %s: <%s> data: %s, method: %s' % ( self.code, self.format_errcode( self.code), self.message, self.data, self.method) def __repr__(self): return repr(str(self)) class SessionBrokenError(UiaError): """ only happens when app quit or crash """ class UiObjectNotFoundError(JsonRpcError): pass class UiAutomationNotConnectedError(JsonRpcError): pass class NullObjectExceptionError(JsonRpcError): pass class NullPointerExceptionError(JsonRpcError): pass class StaleObjectExceptionError(JsonRpcError): pass
1b2d28b012a3ae9806e7d4ee05e0969f02935089
ed9e1b622dad6b559cd0fe6fa23d6a27f857dc7f
/galsim/deprecated/gsobject_ring.py
6a44668976b265c701e31f9d701d4287480961e9
[ "BSD-3-Clause", "BSD-2-Clause" ]
permissive
ajwheeler/GalSim
40d6f8c64789b601ed2547eefed05f1577592613
cf0ef33e5f83da1b13a0617d362d8357056d6f22
refs/heads/master
2021-01-22T06:14:31.486159
2017-04-20T01:20:20
2017-04-20T01:20:20
null
0
0
null
null
null
null
UTF-8
Python
false
false
3,029
py
# Copyright (c) 2012-2017 by the GalSim developers team on GitHub # https://github.com/GalSim-developers # # This file is part of GalSim: The modular galaxy image simulation toolkit. # https://github.com/GalSim-developers/GalSim # # GalSim is free software: redistribution and use in source and binary forms, # with or without modification, are permitted provided that the following # conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions, and the disclaimer given in the accompanying LICENSE # file. # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions, and the disclaimer given in the documentation # and/or other materials provided with the distribution. # import galsim import galsim.config from galsim.deprecated import depr # This file adds gsobject type Ring which builds an object once every n times, and then # rotates it in a ring for the other n-1 times per per group. def _BuildRing(config, base, ignore, gsparams, logger): """@brief Build a GSObject in a Ring. Now deprecated. """ depr('gal.type = Ring', 1.4, 'stamp.type = Ring', 'The galaxy Ring type may not work properly in conjunction with image.nproc != 1. '+ 'See demo5 and demo10 for examples of the new stamp type=Ring syntax.') req = { 'num' : int, 'first' : dict } opt = { 'full_rotation' : galsim.Angle , 'index' : int } # Only Check, not Get. We need to handle first a bit differently, since it's a gsobject. galsim.config.CheckAllParams(config, req=req, opt=opt, ignore=ignore) num = galsim.config.ParseValue(config, 'num', base, int)[0] if num <= 0: raise ValueError("Attribute num for gal.type == Ring must be > 0") # Setup the indexing sequence if it hasn't been specified using the number of items. galsim.config.SetDefaultIndex(config, num) index, safe = galsim.config.ParseValue(config, 'index', base, int) if index < 0 or index >= num: raise AttributeError("index %d out of bounds for config.%s"%(index,type)) if 'full_rotation' in config: full_rotation = galsim.config.ParseValue(config, 'full_rotation', base, galsim.Angle)[0] else: import math full_rotation = math.pi * galsim.radians dtheta = full_rotation / num if logger: logger.debug('obj %d: Ring dtheta = %f',base['obj_num'],dtheta.rad()) if index % num == 0: # Then this is the first in the Ring. gsobject = galsim.config.BuildGSObject(config, 'first', base, gsparams, logger)[0] else: if not isinstance(config['first'],dict) or 'current_val' not in config['first']: raise RuntimeError("Building Ring after the first item, but no current_val stored.") gsobject = config['first']['current_val'].rotate(index*dtheta) return gsobject, False # Register this as a valid gsobject type galsim.config.RegisterObjectType('Ring', _BuildRing, _is_block=True)
36a144965c4bb6563e225c7952ef2dcb1868ab71
b9022c3d2a463ca3f363b09ee5c387a76fa10fbd
/abc029b.py
82ea3b373a5f42cfaede47fb7738b4ce580a32e6
[]
no_license
galileo15640215/atcoder
1371c90bbed185327cd5c3ce32516b5306889db8
27f17573589a43e5ac479e8df048ba461b942b83
refs/heads/master
2021-07-20T14:19:29.361693
2021-07-11T14:34:56
2021-07-11T14:34:56
194,278,891
0
0
null
null
null
null
UTF-8
Python
false
false
101
py
S = [input() for i in range(12)] a=0 for i in range(12): if 'r' in S[i] : a+=1 print(a)
9d492d34a91b9b6a2adaf147e43b85fd5e1810c3
6bf7149077f539ab599db1f717c93aca82724512
/static-and-class_metods/movie-world/customer.py
3aed9a54bd7db6ed12a7a149c4e8651417f97feb
[]
no_license
KalinHar/OOP-Python-SoftUni
8b53e8b734b364878c5372525c4249fdd32f0899
9787eea7ab5101e887ed4aaeb0a8b3b80efcfdd7
refs/heads/master
2023-07-09T08:15:59.765422
2021-08-16T06:01:08
2021-08-16T06:01:19
380,813,294
0
1
null
null
null
null
UTF-8
Python
false
false
361
py
class Customer: def __init__(self, name, age, id): self.name = name self.age = age self.id = id self.rented_dvds = [] def __repr__(self): return f"{self.id}: {self.name} of age {self.age} has {len(self.rented_dvds)} " \ f"rented DVD's ({', '.join([dvd.family_name for dvd in self.rented_dvds])})"
13ecdc3abf138774ecd6ae0a21a5abc0bc3c11a0
a321652061fd5c389490030f898a0191a35f21c3
/managers/operatorsTranscribe/metadata_filegenerator.py
d22dd980ee14d63ef5b5c619fa7a92e2f3597a43
[ "BSD-3-Clause" ]
permissive
cerebunit/cerebmodels
5c4b1485e68d078988ff7057385309a26e05415a
316d69d7aed7a0292ce93c7fea20473e48cfce60
refs/heads/master
2023-02-18T06:45:08.716877
2022-07-18T11:34:13
2022-07-18T11:34:13
139,698,484
0
1
BSD-3-Clause
2023-02-10T21:20:07
2018-07-04T09:15:24
AMPL
UTF-8
Python
false
false
7,147
py
# ~/managers/operatorsTranscribe/metadata_filegenerator.py import platform import uuid import time from datetime import datetime from dateutil.tz import tzlocal class FileGenerator(object): """ **Available Methods:** +---------------------------------+----------------------------------+ | Method name | Method type | +=================================+==================================+ | :py:meth:`.forfile` | class method | +---------------------------------+----------------------------------+ | :py:meth:`.get_modelID` | static method | +---------------------------------+----------------------------------+ | :py:meth:`.get_username` | static method | +---------------------------------+----------------------------------+ | :py:meth:`.get_testdescription` | static method | +---------------------------------+----------------------------------+ | :py:meth:`.get_labelname` | static method | +---------------------------------+----------------------------------+ | :py:meth:`.get_institution` | static method | +---------------------------------+----------------------------------+ """ @staticmethod def get_modelID(model): """Try extracting the ``uuid`` attribute value of the model and return it or return ``"no_model_uuid"``. **Argument:** The instantiated model is passed into this function. """ try: uuid_value = getattr(model, 'uuid') return uuid_value[:8]+"_"+uuid_value[-12:] except: return "no_model_uuid" @staticmethod def get_username(username): """Returns the username (also argument passed as a string) or returns "anonymous" if argument is ``None``. """ if username is None: return "anonymous" else: return username @staticmethod def get_testdescription(test): """Returns the string "raw simulation without running any CerebUnit test" if the argument is ``None`` otherwise it returns the attribute ``.description`` of the argument. *Note:* The argument should be the test metadata. """ if test is None: return "raw simulation without running any CerebUnit test" else: return test.description @staticmethod def get_labname(labname): """Returns the string "no lab name was provided" if the argument is ``None`` otherwise it returns the attribute the argument (a string) itself. *Note:* The argument should be the name of the laboratory. """ if labname is None: return platform.platform() else: return labname @staticmethod def get_institution(instname): """Returns the string "no institution was provided" if the argument is ``None`` otherwise it returns the attribute the argument (a string) itself. *Note:* The argument should be the name of the institute. """ if instname is None: return "no institution was provided" else: return instname @classmethod def forfile( cls, chosenmodel=None, simtime=None, vtest=None, username=None, labname=None, institutename=None ): """Creates the `NWB <https://www.nwb.org/>`_ formatted metadata for an intended file to be saved. **Keyword Arguments:** +------------------------------+--------------------------------------------+ | Key | Value type | +==============================+============================================+ | ``chosenmodel`` | instantiated model | +------------------------------+--------------------------------------------+ | ``simtime`` | datetime.datetime when simulation started | +------------------------------+--------------------------------------------+ | ``vtest`` (optional) | instantiated validation ``CerebUnit`` test | +------------------------------+--------------------------------------------+ | ``username`` (optional) | string | +------------------------------+--------------------------------------------+ | ``labname`` (optional) | string | +------------------------------+--------------------------------------------+ | ``institutename`` (optional) | string | +------------------------------+--------------------------------------------+ **Returned value:** It is a dictionary of the form :: { "session_description": string; "identifier": string, "session_start_time": datetime, "experimenter": string, "experiment_description": string, "session_id": string, "lab": string, "institution": string } *NOTE:* * ``vtest`` is not given for raw stimulation of the chosenmodel * http://pynwb.readthedocs.io/en/latest/pynwb.file.html#pynwb.file.NWBFile **Use case:** ``>> fg = FileGenerator()`` ``>> model = Xyz()`` For simulation without validation test ``>> filemd = fg.forfile(chosenmodel = model)`` For simulation with validation test ``>> vtest = SomeTest()`` ``>> filemd = fg.forfile(chosenmodel=model, simtime=datetime.datetime.now(), test=vtest, username='john', labname='hbp brain sim lab', institute='CNRS-UNIC')`` """ if chosenmodel is None and simtime is None: raise ValueError("passing an instantiated chosenmodel and datetime is mandatory") else: return { #'source': platform.platform(), #string. No longer part of NWB2.0 # Required 'session_description': "simulation of " + chosenmodel.modelname, 'identifier': cls.get_modelID(chosenmodel), #string 'session_start_time': datetime(simtime.year, simtime.month, simtime.day, simtime.hour, simtime.minute, simtime.second, simtime.microsecond, tzinfo=tzlocal()), #'session_start_time': time.asctime(time.gmtime(time.time()))+' '+time.tzname[0], # Optional 'experimenter': cls.get_username(username), #string 'experiment_description': cls.get_testdescription(vtest), #string 'session_id': str(hash(str(uuid.uuid1()))).replace('-',''), # remove any minus 'lab': cls.get_labname(labname), #string 'institution': cls.get_institution(institutename) }
6decd7a44b88980b1b2eb4cf82a52ae9b74c63df
4c499782655f8e929a5dd6b39d6c5d378fcfd7bd
/2_7_grid.py
4c2dab664014608b73819477edbe701451b3cf3f
[]
no_license
IanCBrown/practice_questions
53a3fd66bee807f6e30e6d57632966f146c704c9
838b94c26cd3c26b76c3908277944a3b5f9bc7c7
refs/heads/master
2021-08-06T07:14:57.237709
2020-04-16T05:03:33
2020-04-16T05:03:33
149,521,025
1
0
null
null
null
null
UTF-8
Python
false
false
1,705
py
from __future__ import absolute_import import sys grid = [] def bfs(grid, n, m): visited = [] q = [(0,0)] while q: node = q.pop(0) if node[0] == n and node[1] == m: visited.append(node) return visited if node not in visited: visited.append(node) neighbors = get_neighbors(node[0], node[1], grid[node[0]][node[1]], n, m) for neighbor in neighbors: q.append(neighbor) def solution(grid, n, m): visited = [] q = [[(0,0)]] while q: path = list(q.pop(0)) node = path[-1] if node not in visited: neighbors = get_neighbors(node[0], node[1], grid[node[0]][node[1]], n, m) for neighbor in neighbors: new_path = list(path) new_path.append(neighbor) q.append(new_path) if neighbor[0] == n and neighbor[1] == m: return new_path visited.append(node) return -1 def get_neighbors(row, col, value, n, m): ret = [] if row + value <= n: ret.append((row + value, col)) if row - value >= 0: ret.append((row - value, col)) if col + value <= m: ret.append((row, col + value)) if col - value >= 0: ret.append((row, col - value)) return ret def main(): dim = [int(x) for x in raw_input().split()] n = dim[0] m = dim[1] grid = [[int(x) for x in list(line.strip())] for line in sys.stdin.readlines()] path = solution(grid, n - 1, m - 1) if path == -1: print -1 else: print len(path) - 1 if __name__ == u"__main__": main()
bdc8891fa9754d6a88a31b22a34e0d3fbb425a84
2d4380518d9c591b6b6c09ea51e28a34381fc80c
/CIM16/IEC61970/Informative/InfLoadControl/LoadShedFunction.py
026cb4a998ab4aeff40560258328b4003d84f7c7
[ "MIT" ]
permissive
fran-jo/PyCIM
355e36ae14d1b64b01e752c5acd5395bf88cd949
de942633d966bdf2bd76d680ecb20517fc873281
refs/heads/master
2021-01-20T03:00:41.186556
2017-09-19T14:15:33
2017-09-19T14:15:33
89,480,767
0
1
null
2017-04-26T12:57:44
2017-04-26T12:57:44
null
UTF-8
Python
false
false
2,090
py
# Copyright (C) 2010-2011 Richard Lincoln # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to # deal in the Software without restriction, including without limitation the # rights to use, copy, modify, merge, publish, distribute, sublicense, and/or # sell copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS # IN THE SOFTWARE. from CIM16.IEC61970.Informative.InfLoadControl.LoadMgmtFunction import LoadMgmtFunction class LoadShedFunction(LoadMgmtFunction): """A kind of LoadMgmtFunction that sheds a part of the customer load.A kind of LoadMgmtFunction that sheds a part of the customer load. """ def __init__(self, switchedLoad=0.0, *args, **kw_args): """Initialises a new 'LoadShedFunction' instance. @param switchedLoad: The value of the load that is connected to the shedding switch. Typically this is a noted nominal value rather than a measured value. """ #: The value of the load that is connected to the shedding switch. Typically this is a noted nominal value rather than a measured value. self.switchedLoad = switchedLoad super(LoadShedFunction, self).__init__(*args, **kw_args) _attrs = ["switchedLoad"] _attr_types = {"switchedLoad": float} _defaults = {"switchedLoad": 0.0} _enums = {} _refs = [] _many_refs = []
c227554a1f48abf4ce05d9d0b46bc3a3308ee863
443a3a4fd4a53a3dd900b86037a526951bc929a2
/tests/test_hgvs_location.py
298c9f1ecfc1f0d44392d8a89307b7dbe2a22492
[ "Apache-2.0" ]
permissive
imaurer/hgvs
224a48de4628ebf5c6e3687122ac99261499c0b6
b53b033609bd51bf1af96e8c7fbecc3bdd1fdf3c
refs/heads/master
2021-01-22T23:05:48.777440
2017-03-16T12:20:16
2017-03-16T12:20:16
null
0
0
null
null
null
null
UTF-8
Python
false
false
9,444
py
# -*- coding: utf-8 -*- from __future__ import absolute_import, division, print_function, unicode_literals import unittest from nose.plugins.attrib import attr from hgvs.exceptions import HGVSError, HGVSUnsupportedOperationError import hgvs.location import hgvs.parser @attr(tags=["quick", "models"]) class Test_SimplePosition(unittest.TestCase): @classmethod def setUpClass(cls): cls.hp = hgvs.parser.Parser() def test_success(self): self.assertEqual(str(hgvs.location.SimplePosition(5)), "5") self.assertEqual(str(hgvs.location.SimplePosition(5, uncertain=True)), "(5)") self.assertEqual(str(hgvs.location.SimplePosition(None)), "?") def test_failure(self): with self.assertRaises(AssertionError): self.assertEqual(hgvs.location.SimplePosition(-1), "SHOULD FAIL") def test_simple_subtraction(self): self.assertEqual( hgvs.location.SimplePosition(5) - hgvs.location.SimplePosition(3), 2) def test_simple_comparision(self): var = self.hp.parse_hgvs_variant("NC_000007.13:g.36561662_36561683del") self.assertFalse(var.posedit.pos.start == var.posedit.pos.end) self.assertTrue(var.posedit.pos.start < var.posedit.pos.end) self.assertTrue(var.posedit.pos.start <= var.posedit.pos.end) self.assertFalse(var.posedit.pos.start > var.posedit.pos.end) self.assertFalse(var.posedit.pos.start >= var.posedit.pos.end) var = self.hp.parse_hgvs_variant("NC_000007.13:g.36561662C>T") self.assertTrue(var.posedit.pos.start == var.posedit.pos.end) self.assertFalse(var.posedit.pos.start < var.posedit.pos.end) self.assertTrue(var.posedit.pos.start <= var.posedit.pos.end) self.assertFalse(var.posedit.pos.start > var.posedit.pos.end) self.assertTrue(var.posedit.pos.start >= var.posedit.pos.end) @attr(tags=["quick"]) class Test_BaseOffsetPosition(unittest.TestCase): @classmethod def setUpClass(cls): cls.hp = hgvs.parser.Parser() def test_success(self): # r.5 cdsp = hgvs.location.BaseOffsetPosition(5) self.assertEqual(cdsp.datum, hgvs.location.SEQ_START) self.assertEqual(cdsp.base, 5) self.assertEqual(cdsp.offset, 0) self.assertEqual(str(cdsp), "5") self.assertFalse(cdsp.is_intronic) #r.5+6 cdsp.offset = 6 self.assertEqual(str(cdsp), "5+6") self.assertTrue(cdsp.is_intronic) #r.5+? cdsp.offset = None self.assertEqual(str(cdsp), "5+?") self.assertTrue(cdsp.is_intronic) #r.(5+?) cdsp.uncertain = True self.assertEqual(str(cdsp), "(5+?)") # c.*5 cdsp = hgvs.location.BaseOffsetPosition(5, datum=hgvs.location.CDS_END) self.assertEqual(cdsp.datum, hgvs.location.CDS_END) self.assertEqual(cdsp.base, 5) self.assertEqual(cdsp.offset, 0) self.assertEqual(str(cdsp), "*5") cdsp.uncertain = True self.assertEqual(str(cdsp), "(*5)") cdsp.offset = 7 self.assertEqual(str(cdsp), "(*5+7)") def test_baseoffset_subtraction(self): v30 = hgvs.location.BaseOffsetPosition(3,0) v50 = hgvs.location.BaseOffsetPosition(5,0) v52 = hgvs.location.BaseOffsetPosition(5,2) v54 = hgvs.location.BaseOffsetPosition(5,4) self.assertEqual(v50-v30, 2) with self.assertRaises(HGVSError): _ = v54-v30 def test_baseoffset_comparision(self): var = self.hp.parse_hgvs_variant("NM_000030.2:c.669_680del") self.assertFalse(var.posedit.pos.start == var.posedit.pos.end) self.assertTrue(var.posedit.pos.start < var.posedit.pos.end) self.assertTrue(var.posedit.pos.start <= var.posedit.pos.end) self.assertFalse(var.posedit.pos.start > var.posedit.pos.end) self.assertFalse(var.posedit.pos.start >= var.posedit.pos.end) var = self.hp.parse_hgvs_variant("NM_000030.2:c.679_680+2del") self.assertFalse(var.posedit.pos.start == var.posedit.pos.end) self.assertTrue(var.posedit.pos.start < var.posedit.pos.end) self.assertTrue(var.posedit.pos.start <= var.posedit.pos.end) self.assertFalse(var.posedit.pos.start > var.posedit.pos.end) self.assertFalse(var.posedit.pos.start >= var.posedit.pos.end) var = self.hp.parse_hgvs_variant("NM_000030.2:c.-6_680+2del") self.assertFalse(var.posedit.pos.start == var.posedit.pos.end) self.assertTrue(var.posedit.pos.start < var.posedit.pos.end) self.assertTrue(var.posedit.pos.start <= var.posedit.pos.end) self.assertFalse(var.posedit.pos.start > var.posedit.pos.end) self.assertFalse(var.posedit.pos.start >= var.posedit.pos.end) var = self.hp.parse_hgvs_variant("NM_000030.2:c.680+2_680+10del") self.assertFalse(var.posedit.pos.start == var.posedit.pos.end) self.assertTrue(var.posedit.pos.start < var.posedit.pos.end) self.assertTrue(var.posedit.pos.start <= var.posedit.pos.end) self.assertFalse(var.posedit.pos.start > var.posedit.pos.end) self.assertFalse(var.posedit.pos.start >= var.posedit.pos.end) var = self.hp.parse_hgvs_variant("NM_000030.2:c.680+2_*82del") self.assertFalse(var.posedit.pos.start == var.posedit.pos.end) self.assertTrue(var.posedit.pos.start < var.posedit.pos.end) self.assertTrue(var.posedit.pos.start <= var.posedit.pos.end) self.assertFalse(var.posedit.pos.start > var.posedit.pos.end) self.assertFalse(var.posedit.pos.start >= var.posedit.pos.end) var = self.hp.parse_hgvs_variant("NM_000030.2:c.-12_*82del") self.assertFalse(var.posedit.pos.start == var.posedit.pos.end) self.assertTrue(var.posedit.pos.start < var.posedit.pos.end) self.assertTrue(var.posedit.pos.start <= var.posedit.pos.end) self.assertFalse(var.posedit.pos.start > var.posedit.pos.end) self.assertFalse(var.posedit.pos.start >= var.posedit.pos.end) var = self.hp.parse_hgvs_variant("NM_000030.2:c.680+2_681del") self.assertFalse(var.posedit.pos.start == var.posedit.pos.end) self.assertTrue(var.posedit.pos.start < var.posedit.pos.end) self.assertTrue(var.posedit.pos.start <= var.posedit.pos.end) self.assertFalse(var.posedit.pos.start > var.posedit.pos.end) self.assertFalse(var.posedit.pos.start >= var.posedit.pos.end) var = self.hp.parse_hgvs_variant("NM_000030.2:c.680+2_681-32del") with self.assertRaises(HGVSUnsupportedOperationError): var.posedit.pos.start < var.posedit.pos.end @attr(tags=["quick"]) class Test_AAPosition(unittest.TestCase): @classmethod def setUpClass(cls): cls.hp = hgvs.parser.Parser() def test_AAPosition(self): ap = hgvs.location.AAPosition(15, "S") self.assertEqual(ap.pos, 15) self.assertEqual(str(ap), "Ser15") def test_aaposition_subtraction(self): l1 = hgvs.location.AAPosition(15, 'S') l2 = hgvs.location.AAPosition(20, 'S') self.assertEqual(l2-l1, 5) def test_aaposition_comparision(self): var = self.hp.parse_hgvs_variant("NP_000042.3:p.His1082_Val1085delinsLeuHisGlnAla") self.assertTrue(var.posedit.pos.start < var.posedit.pos.end) self.assertFalse(var.posedit.pos.start > var.posedit.pos.end) var = self.hp.parse_hgvs_variant("NP_000042.3:p.His1082ArgfsTer2") self.assertFalse(var.posedit.pos.start < var.posedit.pos.end) self.assertFalse(var.posedit.pos.start > var.posedit.pos.end) @attr(tags=["quick"]) class Test_Interval(unittest.TestCase): def test_Interval(self): ival = hgvs.location.Interval(hgvs.location.BaseOffsetPosition(base=12, offset=+34), hgvs.location.BaseOffsetPosition(base=56, offset=-78)) self.assertEqual(ival.start.base, 12) self.assertEqual(ival.start.offset, 34) self.assertEqual(ival.end.base, 56) self.assertEqual(ival.end.offset, -78) self.assertEqual(str(ival), "12+34_56-78") def test_length(self): ival = hgvs.location.Interval(hgvs.location.BaseOffsetPosition(base=12, offset=0), hgvs.location.BaseOffsetPosition(base=50, offset=0)) self.assertEqual(ival._length(), 39) if __name__ == "__main__": unittest.main() # <LICENSE> # Copyright 2013-2015 HGVS Contributors (https://github.com/biocommons/hgvs) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # </LICENSE>
97f2b7fc974fd31f932b8119a1893c6cdcfbf035
55a273347cb103fe2b2704cb9653956956d0dd34
/code/tmp_rtrip/encodings/cp1257.py
f99bc227bb34ce2c00c56c2c65c9741d841809b6
[ "MIT" ]
permissive
emilyemorehouse/ast-and-me
4af1bc74fc967ea69ac1aed92664f6428acabe6a
3f58117512e125e1ecbe3c72f2f0d26adb80b7b3
refs/heads/master
2022-11-18T03:50:36.505882
2018-05-12T17:53:44
2018-05-12T17:53:44
115,035,148
25
1
MIT
2022-11-04T11:36:43
2017-12-21T18:27:19
Python
UTF-8
Python
false
false
1,767
py
""" Python Character Mapping Codec cp1257 generated from 'MAPPINGS/VENDORS/MICSFT/WINDOWS/CP1257.TXT' with gencodec.py. """ import codecs class Codec(codecs.Codec): def encode(self, input, errors='strict'): return codecs.charmap_encode(input, errors, encoding_table) def decode(self, input, errors='strict'): return codecs.charmap_decode(input, errors, decoding_table) class IncrementalEncoder(codecs.IncrementalEncoder): def encode(self, input, final=False): return codecs.charmap_encode(input, self.errors, encoding_table)[0] class IncrementalDecoder(codecs.IncrementalDecoder): def decode(self, input, final=False): return codecs.charmap_decode(input, self.errors, decoding_table)[0] class StreamWriter(Codec, codecs.StreamWriter): pass class StreamReader(Codec, codecs.StreamReader): pass def getregentry(): return codecs.CodecInfo(name='cp1257', encode=Codec().encode, decode= Codec().decode, incrementalencoder=IncrementalEncoder, incrementaldecoder=IncrementalDecoder, streamreader=StreamReader, streamwriter=StreamWriter) decoding_table = ( '\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\x7f€\ufffe‚\ufffe„…†‡\ufffe‰\ufffe‹\ufffe¨ˇ¸\ufffe‘’“”•–—\ufffe™\ufffe›\ufffe¯˛\ufffe\xa0\ufffe¢£¤\ufffe¦§Ø©Ŗ«¬\xad®Æ°±²³´µ¶·ø¹ŗ»¼½¾æĄĮĀĆÄÅĘĒČÉŹĖĢĶĪĻŠŃŅÓŌÕÖ×ŲŁŚŪÜŻŽßąįāćäåęēčéźėģķīļšńņóōõö÷ųłśūüżž˙' ) encoding_table = codecs.charmap_build(decoding_table)
cff6911a30320c0e916ef582ab4652791fb96ef3
3b07edf0cd5c546a09ef79fd93ebfd2b04e162e1
/data/ebs-ai-basic/2/2/05.py
09b0cd80cc813b63c21f1f472eb40eb13a01d637
[]
no_license
neverlish/Learned
603b41f7c6ba3cf4e5eea162f501fc42f8326aa3
47f9160c2e516c8b4d1692f1f7dbf200f1cadbb6
refs/heads/master
2023-06-24T06:03:35.848932
2023-06-10T11:38:53
2023-06-10T11:38:53
78,947,372
8
1
null
2023-09-14T05:26:47
2017-01-14T15:12:57
Jupyter Notebook
UTF-8
Python
false
false
2,670
py
# 행렬의 차이를 이용해서 두 이미지 표현하기 import turtle import numpy as np pixelSize = 10 def putPixel(x, y, pSize, pCol): turtle.penup() turtle.goto(x*pSize, (-1)*y*pSize) turtle.pendown() turtle.begin_fill() turtle.fillcolor(pCol) turtle.setheading(45) turtle.circle(pSize/2, steps=4) turtle.end_fill() faceImg = np.array( # 46쪽 (a) 도형을 나타내는 이미지 데이터 행렬 [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0], [0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0], [0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0], [0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0], [0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0], [0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]) smileImg = np.array( # 46쪽 (b) 도형을 나타내는 이미지 데이터 행렬 [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 2, 2, 0, 0, 2, 2, 0, 0, 0, 0, 0], [0, 0, 0, 0, 2, 0, 2, 0, 2, 0, 2, 0, 0, 0, 0, 0], [0, 0, 0, 0, 2, 2, 2, 0, 2, 2, 2, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0], [0, 0, 0, 0, 2, 2, 0, 0, 0, 0, 2, 2, 0, 0, 0, 0], [0, 0, 0, 0, 0, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]) diffImage = np.array(faceImg - smileImg) for j in range(0, 16): for i in range(0, 16): if (diffImage[j][i] > 0): putPixel(i, j, pixelSize, "orange") else: # 각 배열 요소의 값이 0이면 흰색으로 출력 putPixel(i, j, pixelSize, "white")
4d7128e1848b65dbcfc95770e62a47980627bd14
a463f5858c663199b6f6e38d9b2dc93e9a9ae730
/problem/2003/00_200316/4522_세상의모든팰린드롬.py
e11adf0825d5dc9730b7dab4969ef9b58acbd159
[]
no_license
do-park/swexpertacademy
4993f79e3a73697ecdc71e0f654306466626b00b
7cbbb0957ce5191cb44cd35094da5b0d29783e49
refs/heads/master
2020-12-22T19:26:35.257666
2020-10-19T02:02:32
2020-10-19T02:02:32
236,907,286
0
0
null
null
null
null
UTF-8
Python
false
false
400
py
for tc in range(1, int(input()) + 1): flag = ['Not exist', 'Exist'] f = 1 string = list(map(str, input())) for i in range(0, len(string) // 2): if string[i] != string[len(string) - i - 1]: if string[i] == '?' or string[len(string) - i - 1] == '?': continue else: f = 0 break print(f'#{tc} {flag[f]}')
d6391f42975e1fd64be45e9ba6750c4ab0765042
bb06411e37bcba25a89bd523133a4e4d083558f1
/sdk/python/pulumi_xyz/provider.py
aba9d6d647b165a5401f010edb5b6ccd24ccc548
[ "Apache-2.0" ]
permissive
zelarhq/pulumi-provider-boilerplate-openapi
7410b57bc220bee9c7095d0a6e9d8e8250ff5620
aec2430937a0c5df072c713f4641ea5ba128569f
refs/heads/master
2023-08-14T19:14:58.092965
2021-06-03T13:32:23
2021-06-03T13:32:23
null
0
0
null
null
null
null
UTF-8
Python
false
false
2,776
py
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from . import _utilities __all__ = ['ProviderArgs', 'Provider'] @pulumi.input_type class ProviderArgs: def __init__(__self__): """ The set of arguments for constructing a Provider resource. """ pass class Provider(pulumi.ProviderResource): @overload def __init__(__self__, resource_name: str, opts: Optional[pulumi.ResourceOptions] = None, __props__=None): """ Create a Xyz resource with the given unique name, props, and options. :param str resource_name: The name of the resource. :param pulumi.ResourceOptions opts: Options for the resource. """ ... @overload def __init__(__self__, resource_name: str, args: Optional[ProviderArgs] = None, opts: Optional[pulumi.ResourceOptions] = None): """ Create a Xyz resource with the given unique name, props, and options. :param str resource_name: The name of the resource. :param ProviderArgs args: The arguments to use to populate this resource's properties. :param pulumi.ResourceOptions opts: Options for the resource. """ ... def __init__(__self__, resource_name: str, *args, **kwargs): resource_args, opts = _utilities.get_resource_args_opts(ProviderArgs, pulumi.ResourceOptions, *args, **kwargs) if resource_args is not None: __self__._internal_init(resource_name, opts, **resource_args.__dict__) else: __self__._internal_init(resource_name, *args, **kwargs) def _internal_init(__self__, resource_name: str, opts: Optional[pulumi.ResourceOptions] = None, __props__=None): if opts is None: opts = pulumi.ResourceOptions() if not isinstance(opts, pulumi.ResourceOptions): raise TypeError('Expected resource options to be a ResourceOptions instance') if opts.version is None: opts.version = _utilities.get_version() if opts.id is None: if __props__ is not None: raise TypeError('__props__ is only valid when passed in combination with a valid opts.id to get an existing resource') __props__ = ProviderArgs.__new__(ProviderArgs) super(Provider, __self__).__init__( 'xyz', resource_name, __props__, opts)
87ea8efb7076d210da8faaf220c1197c97519945
a9bd335b3948d707a6785490e132d59e375c7242
/Problem 101 - 200/P107.py
a61e07fcfa2ee8db5f4498938d386c14f1f48737
[]
no_license
xzguy/LeetCode
cc52f5329843bb2f692cea131c20b629af910bab
54d99f5e54391ea6ed467e2b5c984848a918dc2a
refs/heads/main
2023-03-25T17:50:50.173621
2021-03-28T16:06:03
2021-03-28T16:06:03
331,409,968
0
0
null
null
null
null
UTF-8
Python
false
false
1,302
py
class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def levelOrderBottom(self, root: TreeNode) -> [[int]]: if not root: return [] queue = [root] res = [] while queue: q_len = len(queue) lvl_list = [] for _ in range(q_len): node = queue.pop(0) lvl_list.append(node.val) if node.left: queue.append(node.left) if node.right: queue.append(node.right) res.insert(0, lvl_list) return res def levelOrderBottom_1(self, root: TreeNode) -> [[int]]: stack = [(root, 0)] res = [] while stack: node, level = stack.pop() if node: if len(res)-1 < level: res.insert(0, []) res[-(level+1)].append(node.val) stack.append((node.right, level+1)) stack.append((node.left, level+1)) return res t = TreeNode(3) t.left = TreeNode(9) t.right = TreeNode(20) t.left.left = TreeNode(15) t.right.right = TreeNode(7) sol = Solution() print(sol.levelOrderBottom_1(t))
[ "xuzhou.guy@gmai" ]
xuzhou.guy@gmai
1dd8bdd14d661670b6c8fefa7039e907d5c112bc
e32ee307e4c59cc18f9dea18d797784a1b23148f
/removing the longest palindrome from it..py
6f68218a0b80234c2729e290897466feffb27853
[]
no_license
GuhanSGCIT/SGCIT
f4ab44346186d45129c74cbad466c6614f9f0f08
8b2e5ccf693384aa22aa9d57f39b63e4659f6261
refs/heads/master
2020-07-11T05:47:54.033120
2020-07-07T05:02:41
2020-07-07T05:02:41
204,459,836
0
0
null
null
null
null
UTF-8
Python
false
false
1,287
py
# Python 3 implementation to find # minimum number of deletions # to make a string palindromic # Returns the length of # the longest palindromic # subsequence in 'str' def lps(str): n = len(str) # Create a table to store # results of subproblems L = [[0 for x in range(n)]for y in range(n)] # Strings of length 1 # are palindrome of length 1 for i in range(n): L[i][i] = 1 # Build the table. Note that # the lower diagonal values # of table are useless and # not filled in the process. # c1 is length of substring for cl in range( 2, n+1): for i in range(n - cl + 1): j = i + cl - 1 if (str[i] == str[j] and cl == 2): L[i][j] = 2 elif (str[i] == str[j]): L[i][j] = L[i + 1][j - 1] + 2 else: L[i][j] = max(L[i][j - 1],L[i + 1][j]) # length of longest # palindromic subseq return L[0][n - 1] # function to calculate # minimum number of deletions def minimumNumberOfDeletions( str): n = len(str) # Find longest palindromic # subsequence l = lps(str) # After removing characters # other than the lps, we # get palindrome. return (l) # Driver Code if __name__ == "__main__": str = input() print(minimumNumberOfDeletions(str))
8aefb0884aeec07500f70bb238b221cef9a1b21b
cbd2eee46663fad5b5375b13c8c21b1b06eb4c6b
/python_test/except.py
a006780e3fc9b3e0aafc7e7df11473ee0268902a
[]
no_license
1026237416/Python
ef474ee40d7efcd6dabb6fb0ecba81b4dcfc7e14
ffa8f9ffb8bfec114b0ca46295db05c4213c4c30
refs/heads/master
2021-07-05T00:57:00.456886
2019-04-26T10:13:46
2019-04-26T10:13:46
114,510,323
0
0
null
null
null
null
UTF-8
Python
false
false
300
py
s=raw_input("Please input your age:") if s == "": raise Exception("Input must no be empty.") try: i = int(s) except ValueError: print "Could not convert data to an integer." except: print "Unknow exception!" else: print "You are %d"%i, "years old" finally: print "Goodbye"
f96f89d9b4a367edb8f8dbf294ee4d21024402b0
283464882733bf4fb9d98c74f46279e98cfd20f9
/calenguay/events/views.py
20e252ce8b369cbac61b1125d1ab5f7e54873b6a
[]
no_license
mariocesar/calenguay
8647734f3fdf3fdeacca44f493b7128be9de54f0
f1759a2a0c35bfc82976b36d7cea65e10a81f572
refs/heads/master
2021-09-25T11:43:08.339647
2020-03-24T22:55:57
2020-03-24T22:55:57
249,537,405
0
0
null
2021-09-22T18:46:55
2020-03-23T20:30:14
Python
UTF-8
Python
false
false
1,560
py
from django import forms from django.contrib import messages from django.core.exceptions import ValidationError from django.core.mail import message from django.shortcuts import get_object_or_404, redirect, render from calenguay.events.models import Category, Event, EventType def landing(request): categories = Category.objects.all() return render(request, "landing.html", {"categories": categories}) def category_detail(request, pk): category = get_object_or_404(Category, pk=pk) event_types = EventType.objects.filter(user__in=category.users.all()) return render( request, "categories/detail.html", {"category": category, "event_types": event_types}, ) def eventtype_detail(request, pk): event_type = get_object_or_404(EventType, pk=pk) return render(request, "eventtypes/detail.html", {"event_type": event_type}) class AppointmentForm(forms.Form): start_at = forms.DateTimeField() def eventtype_make_appointment(request, pk): event_type = get_object_or_404(EventType, pk=pk) form = AppointmentForm(request.POST or None) if form.is_valid(): event = Event( eventtype=event_type, start_at=form.cleaned_data["start_at"], user=request.user, ) try: event.full_clean() except ValidationError as err: messages.error(request, repr(err)) else: event.save() else: messages.error(request, repr(form.errors)) return redirect("eventtype_detail", pk=pk)
49606bc5d3a8da0cae3a8792f1f6867089dfb5f2
f9d3ee7b3b203d23f9ef2c95055e1d26bfddd74b
/nn/embedding/embedding.py
29d3ea957df9c0aae268444adcd8460d4784fb39
[ "MIT" ]
permissive
kefirski/amt
ec4b1d4f2bb9a0103c82ef3c09357894272b44f4
6dcca5743ea8750a740c569181ec6998352ef784
refs/heads/master
2021-05-12T19:26:27.756474
2018-01-14T19:56:24
2018-01-14T19:56:24
117,093,089
28
2
null
null
null
null
UTF-8
Python
false
false
2,362
py
from math import sqrt import numpy as np import torch as t import torch.nn as nn from gensim.models.keyedvectors import KeyedVectors from torch.autograd import Variable class Embeddings(nn.Module): def __init__(self, path, vocab_size, max_len, h_size): super(Embeddings, self).__init__() self.vocab_size = vocab_size self.max_len = max_len self.h_size = h_size self.token_embeddings = nn.Embedding(vocab_size, h_size) self.positional_embeddings = nn.Embedding(int(max_len), h_size, padding_idx=0) self._token_embedding_init(path) self._position_embedding_init() def forward(self, input): mixed = len(input.size()) == 3 batch_size, seq_len, *_ = input.size() positional = Variable(t.LongTensor([i for i in range(1, seq_len + 1)])).repeat(batch_size).view(batch_size, -1) if input.is_cuda: positional = positional.cuda() if mixed: input = input.view(batch_size * seq_len, -1) return t.mm(input, self.token_embeddings.weight).view(batch_size, seq_len, -1) + \ self.positional_embeddings(positional) else: return self.token_embeddings(input) + self.positional_embeddings(positional) def _randn_embed(self): return np.random.randn(self.h_size) / sqrt(self.h_size) def _token_embedding_init(self, path): """ :param path: Path to pretrained embeddings for each index in vocabulary """ keyed_vectors = KeyedVectors.load_word2vec_format(path, binary=True) embeddings = np.array([keyed_vectors.wv[str(idx)] if str(idx) in keyed_vectors.vocab else self._randn_embed() for idx in range(self.vocab_size)]) self.token_embeddings.weight = nn.Parameter(t.from_numpy(embeddings).float(), requires_grad=False) def _position_embedding_init(self): encoding = np.array([ [pos / np.power(10000, 2 * i / self.h_size) for i in range(self.h_size)] if pos != 0 else np.zeros(self.h_size) for pos in range(self.max_len) ]) encoding[1:, 0::2] = np.sin(encoding[1:, 0::2]) encoding[1:, 1::2] = np.cos(encoding[1:, 1::2]) self.positional_embeddings.weight = nn.Parameter(t.from_numpy(encoding).float(), requires_grad=False)
0845d1f075a7811404b355d17f30f0b0df9abc6c
045cb1a5638c3575296f83471758dc09a8065725
/addons/whatsapp_live/__manifest__.py
38438a168cf3acf2f7b5d8951b7acb880a863574
[]
no_license
marionumza/saas
7236842b0db98d1a0d0c3c88df32d268509629cb
148dd95d991a348ebbaff9396759a7dd1fe6e101
refs/heads/main
2023-03-27T14:08:57.121601
2021-03-20T07:59:08
2021-03-20T07:59:08
null
0
0
null
null
null
null
UTF-8
Python
false
false
699
py
# -*- coding: utf-8 -*- # Copyright 2019 GTICA C.A. - Ing Henry Vivas { 'name': 'Whatsapp Connect Chat Live', 'summary': 'Marketing, Sale, connect Chat Whatsapp live for your business', 'version': '13.0.1.0.0', 'category': 'Website', 'author': 'Harpiya Software Technologies', 'support': '[email protected]', 'license': 'AGPL-3', 'website': 'http://harpiya.com/', 'depends': [ 'web', 'website', ], 'data': [ 'views/res_config_settings.xml', 'views/assets.xml', 'views/view_website_whatsapp.xml', ], 'images': ['static/description/main_screenshot.png'], 'application': False, 'installable': True, }
4bcaa3376d450b8aa1c54c76e3908d3796c1edd3
68bfd128be73ab94ce3b2084585d2957376477d5
/use_cos_loss/data_process.py
b71008b8eac28d7d60168c393e09fd653501c2c9
[]
no_license
SunnyangBoy/Table_Derection
88ceaab3c5f9f8b5ca5d62b7cdb8bffe6e5520b0
35eb4d48858f5aaabe4e46602b169acf67aca2d0
refs/heads/master
2022-10-21T08:20:22.546040
2020-06-17T15:46:30
2020-06-17T15:46:30
273,015,655
1
0
null
null
null
null
UTF-8
Python
false
false
4,758
py
import cv2 import numpy as np import os import math def avg_count(img): sum_r = 0 sum_g = 0 sum_b = 0 for i in range(10): for j in range(10): sum_r += img[i][j][0] sum_g += img[i][j][1] sum_b += img[i][j][2] return sum_r/100, sum_g/100, sum_b/100 def avg(img1, img2, img3, img4): r1, g1, b1 = avg_count(img1) r2, g2, b2 = avg_count(img2) r3, g3, b3 = avg_count(img3) r4, g4, b4 = avg_count(img4) return (r1+r2+r3+r4)//4, (g1+g2+g3+g4)//4, (b1+b2+b3+b4)//4 def rotate_bound(image, angle): # grab the dimensions of the image and then determine the # center (h, w) = image.shape[:2] (cX, cY) = (w // 2, h // 2) # grab the rotation matrix (applying the negative of the # angle to rotate clockwise), then grab the sine and cosine # (i.e., the rotation components of the matrix) M = cv2.getRotationMatrix2D((cX, cY), -angle, 1.0) cos = np.abs(M[0, 0]) sin = np.abs(M[0, 1]) # compute the new bounding dimensions of the image nW = int((h * sin) + (w * cos)) nH = int((h * cos) + (w * sin)) # adjust the rotation matrix to take into account translation M[0, 2] += (nW / 2) - cX M[1, 2] += (nH / 2) - cY avg_r, avg_g, avg_b = avg(image[0:10, 0:10], image[0:10, w-10:w], image[h-10:h, 0:10], image[h-10:h, w-10:w]) # perform the actual rotation and return the image return cv2.warpAffine(image, M, (nW, nH), borderValue=(avg_r, avg_g, avg_b)) def crop_image(image, resize): ratio = np.random.uniform(0.6, 1.0) print('ratio ', ratio) h, w = image.shape[:2] print(h, w) c_w, c_h = w // 2, h // 2 n_w, n_h = int((w * ratio) / 2), int((h * ratio) / 2) if (w * ratio) < resize or (h * ratio) < resize: return image crop_img = image[c_h - n_h:c_h + n_h, c_w - n_w:c_w + n_w] return crop_img if __name__ == '__main__': pre_num = 6 create_txt = '/home/ubuntu/cs/table_derection_tf2/use_cos_loss/train_data/train_angles.txt' create_images = '/home/ubuntu/cs/table_derection_tf2/use_cos_loss/train_data/rot_images' root_dir = '/home/ubuntu/cs/table_derection_tf2/use_cos_loss/train_data/images' file_names = sorted(os.listdir(root_dir)) rand_angle = np.random.uniform(0, 359, (len(file_names)) * pre_num) # print("rand_angels ", rand_angle) rand_angle = rand_angle * math.pi / 180.0 # print("rand_angels ", rand_angle) print('len: ', len(file_names)) cnt = 0 resize = 600 with open(create_txt, 'w') as writer: for i, file_name in enumerate(file_names): print(file_name) img_path = os.path.join(root_dir, file_name) image = cv2.imread(img_path) new_name = file_name[:-4] + '_10' + '.jpg' new_imgPath = os.path.join(create_images, new_name) new_image = cv2.resize(image, (resize, resize)) cv2.imwrite(new_imgPath, new_image) line = new_name + ';' + '0.0000' + '\n' writer.write(line) new_image = rotate_bound(image, 90) new_image = cv2.resize(new_image, (resize, resize)) new_name = file_name[:-4] + '_11' + '.jpg' new_imgPath = os.path.join(create_images, new_name) cv2.imwrite(new_imgPath, new_image) line = new_name + ';' + '1.5708' + '\n' writer.write(line) new_image = rotate_bound(image, 180) new_image = cv2.resize(new_image, (resize, resize)) new_name = file_name[:-4] + '_12' + '.jpg' new_imgPath = os.path.join(create_images, new_name) cv2.imwrite(new_imgPath, new_image) line = new_name + ';' + '3.1416' + '\n' writer.write(line) new_image = rotate_bound(image, 270) new_image = cv2.resize(new_image, (resize, resize)) new_name = file_name[:-4] + '_13' + '.jpg' new_imgPath = os.path.join(create_images, new_name) cv2.imwrite(new_imgPath, new_image) line = new_name + ';' + '4.7124' + '\n' writer.write(line) for j in range(pre_num): angle = rand_angle[cnt] cnt += 1 new_image = rotate_bound(image, angle / math.pi * 180.0) new_image = crop_image(new_image, resize) new_image = cv2.resize(new_image, (resize, resize)) new_name = file_name[:-4] + '_' + str(j).zfill(2) + '.jpg' new_imgPath = os.path.join(create_images, new_name) cv2.imwrite(new_imgPath, new_image) line = new_name + ';' + str(angle) + '\n' writer.write(line) writer.close()
7bb05a4bbe2e8267a6c43e3620d67b4f465c3b44
2a54e8d6ed124c64abb9e075cc5524bb859ba0fa
/.history/1-Python-Basics/28-tuples2_20200413203128.py
8c41bfd70429203ae803473b037a15cffd43b26d
[]
no_license
CaptainStorm21/Python-Foundation
01b5fbaf7a913506518cf22e0339dd948e65cea1
a385adeda74f43dd7fb2d99d326b0be23db25024
refs/heads/master
2021-05-23T01:29:18.885239
2020-04-23T19:18:06
2020-04-23T19:18:06
253,171,611
0
0
null
null
null
null
UTF-8
Python
false
false
42
py
#Tuples part 2 my_tuple = (2, 1, 4, 10)
d6d7a75916aede2d40d4a98a66ef61730b3e96b4
0b9e588b3d6ddf95d87a0a0f02d10ef6efcccf51
/eduapi/api/views/mixins.py
3813677de2e8238d750d2f38aae79b5771ad513e
[]
no_license
omni360/inspiration-edu-api
b5d07a7fe3a473689d5323e60e6f88dd3d6fb4cb
6e1bbf8d895082d4c44af4ae35b9f5aa5cc9addc
refs/heads/master
2022-01-22T23:30:09.879433
2016-04-28T02:02:46
2016-04-28T02:02:46
57,559,736
0
0
null
2022-01-06T22:24:03
2016-05-01T06:35:12
Python
UTF-8
Python
false
false
36,165
py
import types from django.db.models import Q from django.contrib.contenttypes.models import ContentType from django.shortcuts import get_object_or_404 from django.http import Http404 from rest_framework import generics from rest_framework import exceptions from rest_framework.request import clone_request from rest_framework.filters import OrderingFilter from .filters import MappedOrderingFilter from ..models import Classroom, Project, Lesson, Step, Review, ClassroomState, ProjectState, LessonState, StepState, IgniteUser, Purchase class RootViewBuilder(object): ''' This root view builder is helper class to create nested views. It helps to define the view queryset based on the root view object. Simply inherit this builder to your nested view class, and define the root view: root_view_name - the default name of the root view object. root_view_class - the root view class (must be subclass of generics.GenericAPIView). root_view_options - default options for the root view (default: {'request_method': 'GET'}). root_view_use_object - flag whether to use the root object or queryset (default: True). root_view_lookup_url_kwarg - the lookup url kwarg to get the root view pk. available only when root_view_use_object is True. root_view_objects - list of predefined root objects, of the form: {'rootobj_edit': {'request_method': 'PUT', ...}, ...} a default root_view_object will always be created with root_view_name and root_view_options. available only when root_view_use_object is True. By default, when accessing the root_object, all prefetch_related is emptied (for optimization). If prefetch is needed, use 'with_prefetch' True. def make_root_queryset(self, root_object): #root_object argument is the default root object from the root view (root_view_objects[root_view_name]). root_qs = root_object.<field>.all() #... you can alter the root queryset more as you wish ...# return root_qs IMPORTANT: In order to have the magic work, you must define all your root view settings attributes TOGETHER in single class! [The builder reads the attributes from each root class separately and all together, avoiding inheritance]. After initializing, then in the view you can have these methods: get_root_queryset(self, root_queryset=None, until_class=None) Returns the root queryset. Mainly used to initialize self.queryset for get_queryset. This will throw exception if cannot get the root queryset. get_root_object_<root_view_object_key>(self) -> self.root_object_<root_view_object_key> Returns the root object with the given key as defined in root_view_objects. Mainly used to get (with permission check) the root object for view actions methods. This will throw exception if cannot get the root object. ''' def _prepare_view(self, view_class, lookup_url_kwarg, request_method='GET', queryset=None, action_request=None, action_args=None, action_kwargs=None, permission_classes=None, authentication_classes=None, override_options=None): ''' Prepares the root view for action. ''' #defaults: action_request = action_request if action_request is not None else self.request action_args = action_args if action_args is not None else self.args action_kwargs = action_kwargs if action_kwargs is not None else self.kwargs #make the view instance: view_instance = view_class(lookup_url_kwarg=lookup_url_kwarg) view_instance.args = action_args view_instance.kwargs = action_kwargs view_instance.request = clone_request(action_request, request_method) #clone the same request but with GET method #IMPORTANT: set the queryset of the root view to the current queryset: #(this allows to concatenate RootViewBuilder's) view_instance.queryset = queryset #Do not override permission/authentication classes, but add to them to strict more: #The rationale beyond this is that any inner object in the url is not accessible if the #former object in the URL is not accessible. if permission_classes is not None: view_instance.permission_classes += permission_classes if authentication_classes is not None: view_instance.authentication_classes += authentication_classes #override more options (preferred not to use it): if isinstance(override_options, dict): for opt_key, opt_val in override_options: if hasattr(view_instance, opt_key): setattr(view_instance, opt_key, opt_val) #initialize the view instance: view_instance.initial(view_instance.request, *action_args, **action_kwargs) return view_instance def get_root_object_from_view(self, *args, **kwargs): ''' Gets object from another view (root_view_use_object = True). Just set which request method to use (defaults to 'GET'), and the lookup_url_kwarg parameter. ''' with_prefetch = kwargs.pop('with_prefetch', None) view_instance = kwargs.pop('view_instance', None) view_instance = view_instance or self._prepare_view(*args, **kwargs) queryset = self.get_root_queryset_from_view(view_instance=view_instance, with_prefetch=with_prefetch) return view_instance.get_object() def get_root_queryset_from_view(self, *args, **kwargs): ''' Gets queryset from another view (root_view_use_object = False). Just set which request method to use (defaults to 'GET'). ''' with_prefetch = kwargs.pop('with_prefetch', None) with_prefetch = with_prefetch if with_prefetch is not None else False view_instance = kwargs.pop('view_instance', None) view_instance = view_instance or self._prepare_view(*args, **kwargs) queryset = view_instance.get_queryset() if not with_prefetch: queryset = queryset.prefetch_related(None) return queryset def get_root_object_or_queryset_from_view(self, root_view_use_object, *args, **kwargs): ''' Gets queryset or object from another view (based on root_view_use_object). ''' if root_view_use_object: return self.get_root_object_from_view(*args, **kwargs) return self.get_root_queryset_from_view(*args, **kwargs) def check_root_object_permissions_from_view(self, *args, **kwargs): ''' Checks object permission from another view. Just set the lookup_url_kwarg parameter, and which request method to use (defaults to 'GET'). You can restrict more permissions and authentications with permission_classes and authentication_classes. ''' view_instance = self._prepare_view(*args, **kwargs) return view_instance.check_permissions(view_instance.request) @classmethod def make_get_root_object_method(cls, root_class, attr_name, *args, **kwargs): ''' Adds get_root_object_<attr_name>() method to the class of self. That method gets the root object, and stores it in self.root_object_<attr_name>. *args and **kwargs are transferred to get_root_object_from_view() method. ''' self_attr_name = 'root_object_' + attr_name def get_root_object_method(self): if not hasattr(self, self_attr_name): kwargs['queryset'] = self.get_root_queryset(until_class=root_class) setattr(self, self_attr_name, self.get_root_object_from_view(*args, **kwargs)) return getattr(self, self_attr_name) setattr(cls, 'get_' + self_attr_name, get_root_object_method) @classmethod def make_get_root_queryset(cls, root_view_use_object, root_class, root_view_class, root_view_lookup_url_kwarg, root_view_options): def wrapper(func): def wrapped_get_root_queryset(self, root_queryset=None, until_class=None, of_class=None): #if we have already got to until_class, then return the passed root_queryset: if ((until_class and (not issubclass(until_class, root_class) or until_class is root_class)) or (of_class and not issubclass(of_class, root_class))): return root_queryset #get the root object or queryset with the default root_view_options: root_view_options['queryset'] = root_queryset #set root queryset root_obj_or_qs = self.get_root_object_or_queryset_from_view(root_view_use_object, root_view_class, root_view_lookup_url_kwarg, **root_view_options) #alter the root queryset by passing the root object or queryset to func: root_queryset = func(self, root_obj_or_qs) #if we have already got to of_class, then return the current root_queryset: if of_class and of_class is root_class: return root_queryset #continue to build the root queryset from this root class: return super(root_class, self).get_root_queryset(root_queryset, until_class, of_class) return wrapped_get_root_queryset return wrapper def __new__(cls, *args, **kwargs): ''' This is called before instantiating a class object, to build the root view methods and behavior. ''' #if class was not yet initialized with RootViewBuilder, then initialize class: if not getattr(cls, '__root_view_initialized__', False): #go over the classes that inherit RootViewBuilder and build them: for base_class in cls.mro(): #if got to self base_class, then stop: if base_class is RootViewBuilder: break #access only attributes defined on the class (because getting attribute with base_class access also inherited attributes): base_class_dict = base_class.__dict__ #get class settings: root_view_name = base_class_dict.get('root_view_name', None) root_view_class = base_class_dict.get('root_view_class', None) root_view_options = base_class_dict.get('root_view_options', { 'request_method': 'GET' }) #default root view options #got enough settings to make get_root_object methods: if root_view_name and root_view_class: #get more class settings: root_view_use_object = base_class_dict.get('root_view_use_object', True) #whether to use object (default: True) root_view_lookup_url_kwarg = base_class_dict.get('root_view_lookup_url_kwarg', None) #lookup_url_kwarg attribute in case of using objects #if root view use objects, then make get_root_object methods: if root_view_use_object: #get more class settings: root_view_objects = base_class_dict.get('root_view_objects', {}) #make default get_root_object method: root_view_objects[root_view_name] = root_view_options #make get_root_object methods as in settings: for root_view_obj_name, root_view_obj_kwargs in root_view_objects.iteritems(): cls.make_get_root_object_method(base_class, root_view_obj_name, view_class=root_view_class, lookup_url_kwarg=root_view_lookup_url_kwarg, **root_view_obj_kwargs) #if got enough settings to make get_root_queryset method: meth_get_root_queryset = base_class_dict.get('make_root_queryset', None) #make_root_queryset base_class method if meth_get_root_queryset: #wrap the get_root_queryset method: wrapped_meth_get_root_queryset = cls.make_get_root_queryset(root_view_use_object, base_class, root_view_class, root_view_lookup_url_kwarg, root_view_options)(meth_get_root_queryset) # wrapped_meth_get_root_queryset.__name__ setattr(base_class, 'get_root_queryset', wrapped_meth_get_root_queryset) setattr(cls, '__root_view_initialized__', True) return super(RootViewBuilder, cls).__new__(cls, *args, **kwargs) def get_root_queryset(self, root_queryset=None, until_class=None, of_class=None): ''' Returns the root view queryset. ''' self.root_queryset = root_queryset return self.root_queryset def get_queryset(self): #set the initial queryset to root queryset (truncates attribute): self.queryset = getattr(self, 'root_queryset', self.get_root_queryset()) return super(RootViewBuilder, self).get_queryset() class DisableHttpMethodsMixin(object): ''' Disables view methods. For http methods use attribute 'disable_http_methods'. For operation methods use attribute 'disable_operation_methods'. ''' disable_http_methods = [] disable_operation_methods = [] def __init__(self, *args, **kwargs): super(DisableHttpMethodsMixin, self).__init__(*args, **kwargs) #map operation to http method name: map_operation_to_http = { 'retrieve': 'get', 'update': 'put', 'partial_update': 'patch', 'destroy': 'delete', 'list': 'get', 'create': 'post', 'metadata': 'options', } #get list of http method names to disable from 'disable_http_methods' attribute: disable_http_method_names = [m.lower() for m in self.disable_http_methods] #get list of http method names to disable from 'disable_operation_methods' attribute: disable_http_method_names += [map_operation_to_http[o] for o in self.disable_operation_methods if map_operation_to_http.has_key(o)] #remove disabled http method names from http_method_names: self.http_method_names = [m for m in self.http_method_names if m not in disable_http_method_names] class UpdateWithCreateMixin(object): ''' This mixin makes the view having PUT-as-create behavior, and POST-as-update. The POST method is redirected to PUT .update() method. The method .perform_create() called by POST method is now out of use. Instead, .perform_update() method handles both updating and creating. Pay attention: .perform_update() might have serializer.instance None. ''' #list of http methods that will be used for update with create: update_with_create_methods = ['POST', 'PUT'] #possible to add PATCH def get_object(self): try: obj = super(UpdateWithCreateMixin, self).get_object() except Http404: #For PUT-as-create, return None when object is not found: if self.request.method in self.update_with_create_methods: obj = None else: raise return obj def create(self, request, *args, **kwargs): ''' Since using PUT-as-create, then redirect POST (create) to PUT (update), and handle both create and update in .perform_update. ''' return self.update(request, *args, **kwargs) def post(self, request, *args, **kwargs): ''' Add POST method to view. ''' return self.create(request, *args, **kwargs) class BulkUpdateWithCreateMixin(object): ''' Like UpdateWithCreateMixin, but for bulk create and bulk update: ''' def create(self, request, *args, **kwargs): bulk = isinstance(request.data, list) #if not bulk, use regular create: if not bulk: return super(BulkUpdateWithCreateMixin, self).create(request, *args, **kwargs) #if bulk, use bulk create as bulk update: else: self.request = clone_request(request, 'PUT') return self.bulk_update(self.request, *args, **kwargs) def post(self, request, *args, **kwargs): ''' Add POST method to view. ''' return self.create(request, *args, **kwargs) class UseAuthenticatedSerializerMixin(object): def get_serializer_class(self): if self.request.user.is_authenticated() and self.request.GET.get('user', '') == 'current': return self.authenticated_serializer_class return self.serializer_class class EnrichSerializerContextMixin(object): embed_choices = tuple() embed_user_related = tuple() embed_list_base = [] #Note: Theses are not class attributes, but instance attributes # embed_list = [] # embed_user = None def initial(self, request, *args, **kwargs): #set embed list for the view, initialized from the query params plus base embed list: self.embed_list = self.embed_list_base[:] #copy list embed = request.GET.get('embed', '') request_embed_list = set(embed.split(',')) self.embed_list += [x for x in request_embed_list if x in self.embed_choices] #add user related fields: self.embed_user = None if self.request.user.is_authenticated() and self.request.GET.get('user', '') == 'current': self.embed_list += self.embed_user_related self.embed_user = self.request.user super(EnrichSerializerContextMixin, self).initial(request, *args, **kwargs) def get_serializer_context(self): context = super(EnrichSerializerContextMixin, self).get_serializer_context() context['allowed'] = tuple(self.embed_list) return context class CacheRootObjectMixin(object): """ Generic view mixin that defines a method to get and cache root object from the url kwargs. """ def get_cache_root_object(self, model, lookup_field='pk', lookup_url_kwarg=None, queryset=None, cache_root_name=None, raise_not_found=True): """ Gets the root object and caches it. :param model: The model class (used to fetch defaults for other parameters). :param lookup_field: The lookup field for getting the object (default 'pk'). :param lookup_url_kwarg: Yhe lookup url kwarg for getting the value of the lookup field (default {model_name}_{lookup_field}). :param queryset: The queryset to get the object from (default model.objects.all()). :param cache_root_name: The name of the cache root object (default {model_name}) - sets cache in the view as attribute _cache_root_{cache_root_name}. :param raise_not_found: Whether to raise DRF exception NotFound if object is not found. If False then return None. (default True). :return: The object or None if not exists (if raise_not_found is True then raises DRF exception NotFound instead of returning None). """ model_name = model._meta.model_name cache_root_name = cache_root_name or model_name cache_key = '_cache_root_' + cache_root_name cache_object = None if hasattr(self, cache_key): cache_object = getattr(self, cache_key) else: lookup_field = lookup_field or 'pk' lookup_url_kwarg = lookup_url_kwarg or '{}_{}'.format(model_name, lookup_field) lookup_value = self.kwargs.get(lookup_url_kwarg, None) if lookup_value is not None: queryset = queryset if queryset is not None else model.objects.all() #get cache object try: cache_object = queryset.get(**{lookup_field: lookup_value}) except model.DoesNotExist: pass setattr(self, cache_key, cache_object) if cache_object is None and raise_not_found: raise exceptions.NotFound return cache_object class FilterAllowedMixin(object): """ This mixin is responsible to filter allowed objects. It is commonly used in views to filter allowed objects for deeper related objects, based on common url kwargs (e.g project_pk, lesson_pk, etc). IMPORTANT: Make sure to put all the Q filters of *allowed* objects of models in this mixin. Do not filter out disallowed objects in views querysets (put it in this mixin). Do not filter query-params in this mixin (e.g isArchived for /classrooms/ list). Make sure to keep the common url kwargs in all urls using this mixin. """ def get_allowed_q_filter(self, model=None, **kwargs): # Default model: if model is None: model = self.model if model == Classroom: include_children_classrooms = kwargs.get('include_children_classrooms', True) exclude_archived_classrooms = kwargs.get('exclude_archived_classrooms', False) return self._get_allowed_q_filter_for_classroom(model, include_children_classrooms=include_children_classrooms, exclude_archived_classrooms=exclude_archived_classrooms) elif model in (Project, Lesson, Step, ProjectState, LessonState, StepState,): exclude_non_searchable_projects = kwargs.get('exclude_non_searchable_projects', False) return self._get_allowed_q_filter_for_project_lesson_step(model, exclude_non_searchable_projects=exclude_non_searchable_projects) elif model == Review: return self._get_allowed_q_filter_for_review(model) # If model not supported, then raise error: raise AssertionError('ProgrammingError: \'%s\' does not support \'%s\' model.' % (self.__class__.__name__, model.__name__)) def _get_allowed_q_filter_for_project_lesson_step(self, model, exclude_non_searchable_projects=False): user = self.request.user # If super user, then do not filter (using empty Q): if user.is_superuser: return Q() # Get query fields lookups (acronym: qfl): qfl = None if model == Project: qfl = { 'pk': 'pk', 'publish_mode': 'publish_mode', 'owner': 'owner', 'application': None, 'is_searchable': 'is_searchable', 'hash': 'view_invite__hash', } elif model == Lesson: qfl = { 'pk': 'project__pk', 'publish_mode': 'project__publish_mode', 'owner': 'project__owner', 'application': 'application', 'is_searchable': 'project__is_searchable', 'hash': 'project__view_invite__hash', } elif model == Step: qfl = { 'pk': 'lesson__project__pk', 'publish_mode': 'lesson__project__publish_mode', 'owner': 'lesson__project__owner', 'application': 'lesson__application', 'is_searchable': 'lesson__project__is_searchable', 'hash': 'lesson__project__view_invite__hash', } elif model == ProjectState: qfl = { 'pk': 'project__pk', 'publish_mode': 'project__publish_mode', 'owner': 'project__owner', 'application': None, 'is_searchable': 'project__is_searchable', 'hash': 'project__view_invite__hash', } elif model == LessonState: qfl = { 'pk': 'lesson__project__pk', 'publish_mode': 'lesson__project__publish_mode', 'owner': 'lesson__project__owner', 'application': 'lesson__application', 'is_searchable': 'lesson__project__is_searchable', 'hash': 'lesson__project__view_invite__hash', } elif model == StepState: qfl = { 'pk': 'step__lesson__project__pk', 'publish_mode': 'step__lesson__project__publish_mode', 'owner': 'step__lesson__project__owner', 'application': 'step__lesson__application', 'is_searchable': 'step__lesson__project__is_searchable', 'hash': 'step__lesson__project__view_invite__hash', } # Filter by published content and searchable. published_filter = Q(**{qfl['publish_mode']: Project.PUBLISH_MODE_PUBLISHED}) # Exclude non-searchable (hidden) projects. if exclude_non_searchable_projects: published_filter &= Q(**{qfl['is_searchable']: True}) filters = published_filter # Filter by matching request 'hash' query param: req_hash = self.request.QUERY_PARAMS.get('hash', False) if req_hash: filters |= Q(**{qfl['hash']: req_hash}) # If the user is logged in if user and not user.is_anonymous(): # Or unpublished content that belongs to the user or her delegators/children. filters |= Q(**{qfl['owner']: user}) filters |= Q(**{qfl['owner']+'__in': user.delegators.all()}) filters |= Q(**{qfl['owner']+'__in': user.children.all()}) #TODO: add OR filter for project/lessons in review/ready mode for reviewer users. # (currently reviewer=superuser, which are already handled above to get access to all). #IMPORTANT NOTE: # Usually projects for purchase are searchable and published, therefore they are already included in the queryset. # This handles an edge case when a project is_searchable=False (and publish_mode=published) and lock=True # (not searchable and for purchase), and because it adds overhead to the query (more JOIN), # therefore it is commented out. #TODO: Uncomment the following couple lines of code when it is required. # if exclude_non_searchable_projects: # filters |= Q(**{qfl['publish_mode']: Project.PUBLISH_MODE_PUBLISHED, qfl['pk']+'__in': user.purchases.values('project')}) # This is an ugly patch. # We want to let applications get the lessons that belong # to them and every project (because lessons belong to project # and projects don't have an application). # If you find a better solution for this, feel free to refactor. # Get a list of apps that this user is affiliated with. user_apps = Lesson.get_user_app_groups(user) if user_apps: # Projects - if user is affiliated with any app, show all project. if model == Project: filters = Q() # Lessons or Steps - also allow. else: filters |= Q(**{qfl['application']+'__in': user_apps}) return filters def _get_allowed_q_filter_for_classroom(self, model, include_children_classrooms=True, exclude_archived_classrooms=False): user = self.request.user if user and not user.is_anonymous(): # If super user, then do not filter (using empty Q): if user.is_superuser: return Q() # Filter owned classrooms. filters = Q(owner=user) # Filter registered classrooms: classroom_states_filter_q = Q(user=user) #student if include_children_classrooms: classroom_states_filter_q |= Q(user__in=user.childguardian_child_set.values('child')) #child student (user is guardian) classroom_states_qs = ClassroomState.objects.filter( Q(status=ClassroomState.APPROVED_STATUS), #approved classroom_states_filter_q #student user filter (user with/without children) ) registered_classrooms_filter = Q(pk__in=classroom_states_qs.values('classroom')) if exclude_archived_classrooms: registered_classrooms_filter &= Q(is_archived=False) filters |= registered_classrooms_filter return filters else: # Not logged-in users have no access to any project: return Q(pk__isnull=True) #will match nothing def _get_allowed_q_filter_for_review(self, model): filters = Q(content_type__model=Lesson._meta.model_name) & self.get_allowed_q_filter(Lesson) filters |= Q(content_type__model=Project._meta.model_name) & self.get_allowed_q_filter(Project) return filters def get_allowed_q_filter_for_user(self, model, user, **kwargs): # Default model: if model is None: model = self.model if model in (ClassroomState, ProjectState, LessonState,): return self._get_allowed_q_filter_for_users_states(model, user) elif model == Review: return self._get_allowed_q_filter_for_users_reviews(model, user) # If model not supported, then raise error: raise AssertionError('ProgrammingError: \'%s\' does not support \'%s\' model.' % (self.__class__.__name__, model.__name__)) def __can_request_user_access_user(self, user): """Returns whether a request user can access the user info""" #try get it from self cache: request_user_access_users = getattr(self, '_cache_request_user_access_users', {}) can_access = request_user_access_users.get(user.id, None) #if not in cache, then check if can access and cache in self: if can_access is None: if ( self.request.user.is_superuser or #request user is super user self.request.user == user or #request user is the user itself user.get_cache_childguardian_guardian(self.request.user) #request user is guardian of the user ): can_access = True else: can_access = False request_user_access_users[user.id] = can_access setattr(self, '_cache_request_user_access_users', request_user_access_users) return can_access def _get_allowed_q_filter_for_users_states(self, model, user): # Get query fields lookups (acronym: qfl): qfl = None if model == ClassroomState: qfl = { 'user': 'user', 'project': None, 'classroom': 'classroom' } elif model == ProjectState: qfl = { 'user': 'user', 'project': 'project', } elif model == LessonState: qfl = { 'user': 'project_state__user', #TODO: When lesson state has its own 'user' field then use it 'project': 'lesson__project', } state_subject = model.get_state_subject() # Filter states for the user: filters = Q(**{qfl['user']: user}) # If request user is not allowed to access all states, then filter states of the authored classrooms only: if not self.__can_request_user_access_user(user): if state_subject == 'classroom': filters &= Q(**{'{}__owner'.format(qfl['classroom']): self.request.user}) else: filters &= Q(**{ '{}__in'.format(qfl['project']): user.classrooms_states.filter(classroom__owner=self.request.user).values('classroom__projects') }) return filters def _get_allowed_q_filter_for_users_reviews(self, model, user): filters = Q(owner=user) # If request user is not allowed to access all reviews, then filter reviews of the authored classrooms only: if not self.__can_request_user_access_user(user): user_classroom_states_qs = ClassroomState.objects.filter(self._get_allowed_q_filter_for_users_states(ClassroomState, user)) filters &= ( Q( #teacher classroom - project reviews content_type=ContentType.objects.get_for_model(Project), object_id__in=user_classroom_states_qs.values('classroom__projects') ) ) return filters class ChoicesOnGet(object): def metadata(self, request): ret = super(ChoicesOnGet, self).metadata(request) ret['actions'] = ret.get('actions', {}) serializer = self.get_serializer() get_meta = serializer.metadata() ret['actions']['GET'] = { key: {u'choices': val['choices']} for key, val in get_meta.items() if val.get('choices') } return ret class MappedOrderingView(generics.GenericAPIView): ''' Adds MappedOrderingFilter to the filter_backends of the view. ''' ordering_fields_map = {} def initial(self, request, *args, **kwargs): super(MappedOrderingView, self).initial(request, *args, **kwargs) #replace OrderingFilter with MappedOrderingFilter, or append MappedOrderingFilter: if MappedOrderingFilter not in self.filter_backends: if OrderingFilter in self.filter_backends: self.filter_backends = tuple([MappedOrderingFilter if fb==OrderingFilter else fb for fb in self.filter_backends]) else: self.filter_backends += (MappedOrderingFilter,) #DEPRECATED! #NOTE: Since DRF 3 this mixin is not required anymore, because DRF 3 updates the instance before serializing, and # expects the programmer to update the instance as well - Serializer .update() and .create() methods. class PrefetchViewMixin(object): ''' Defines how to prefetch_related and select_related the view queryset, or add annotate/extra fields. Optionally handles re-prefetch of the object post saving (post_save_prefetch=False by default). Use this option when the view is able to change related objects. ''' post_save_prefetch = False def __new__(cls, *args, **kwargs): instance = super(PrefetchViewMixin, cls).__new__(cls, *args, **kwargs) #get the original get_queryset method of the instance: get_queryset_method = getattr(instance, 'get_queryset') #define a new get_queryset method to preform prefetch after getting the queryset: def get_queryset_with_prefetch(self): #call original get_queryset method of the instance: queryset = get_queryset_method() #prefetch queryset: queryset = self.prefetch_queryset(queryset) return queryset #set the new get_queryset method: instance.get_queryset = types.MethodType(get_queryset_with_prefetch, instance, cls) return instance def prefetch_queryset(self, queryset): ''' Gets a queryset and only adds prefetch_related and select_related to it, or add annotate/extra fields. Do not filter or exclude objects of the queryset in this method. ''' return queryset def post_save(self, obj, created=False): super(PrefetchViewMixin, self).post_save(obj, created) #re-prefetch the object only in case the object is updated: if self.post_save_prefetch: #get the object again re-prefetched, and copy all attributes from the new object: #Note: The reason for copying all attributes is that the obj parameter given in this method is the object in # serializer, and there's no way to replace that object in the serializer, so we update the current one. new_obj = self.prefetch_queryset(self.model.objects.all()).get(pk=obj.pk) obj.__dict__ = new_obj.__dict__.copy()
b372f136945c7c140f928e3fcc06b705264dd82a
163bbb4e0920dedd5941e3edfb2d8706ba75627d
/Code/CodeRecords/2606/60797/247414.py
a53d3bf72630c68d1fad189adb9a6e4ed7f2c6f0
[]
no_license
AdamZhouSE/pythonHomework
a25c120b03a158d60aaa9fdc5fb203b1bb377a19
ffc5606817a666aa6241cfab27364326f5c066ff
refs/heads/master
2022-11-24T08:05:22.122011
2020-07-28T16:21:24
2020-07-28T16:21:24
259,576,640
2
1
null
null
null
null
UTF-8
Python
false
false
471
py
import math def search(nums, target): left = 0 right = len(nums) - 1 i = (left + right) // 2 while target != nums[i]: if target < nums[i]: right = i - 1 i = (left + right) // 2 else: left = i + 1 i = (left + right) // 2 return i if __name__ == "__main__": nums = [int(a) for a in input().strip("[]").split(",")] target = int(input()) re = search(nums, target) print(re)