<commit_before># Core Skia library code.
{
  'includes': [
    'common.gypi',
  ],
  'targets': [
    {
      'target_name': 'core',
      'type': 'static_library',
      'msvs_guid': 'B7760B5E-BFA8-486B-ACFD-49E3A6DE8E76',
      'sources': [
        '../src/core/ARGB32_Clamp_Bilinear_BitmapShader.h',
        '../src/core/Sk64.cpp',
        '../src/core/SkAdvancedTypefaceMetrics.cpp',
        '../src/core/SkAlphaRuns.cpp',
        '../src/core/SkAntiRun.h',
        '../src/core/SkBitmap.cpp',
        '../src/core/SkBitmapProcShader.cpp',
        '../src/core/SkBitmapProcShader.h',
        '../src/core/SkBitmapProcState.cpp',
        '../src/core/SkBitmapProcState.h',
        '../src/core/SkBitmapProcState_matrix.h',
        '../src/core/SkBitmapProcState_matrixProcs.cpp',
        '../src/core/SkBitmapProcState_sample.h',
        '../src/core/SkBitmapSampler.cpp',
        '../src/core/SkBitmapSampler.h',
        '../src/core/SkBitmapSamplerTemplate.h',
        '../src/core/SkBitmapShader16BilerpTemplate.h',
        '../src/core/SkBitmapShaderTemplate.h',
        '../src/core/SkBitmap_scroll.cpp',
        '../src/core/SkBlitBWMaskTemplate.h',
        '../src/core/SkBlitRow_D16.cpp',
        '../src/core/SkBlitRow_D32.cpp',
        '../src/core/SkBlitRow_D4444.cpp',
        '../src/core/SkBlitter.cpp',
        '../src/core/SkBlitter_4444.cpp',
        '../src/core/SkBlitter_A1.cpp',
        '../src/core/SkBlitter_A8.cpp',
        '../src/core/SkBlitter_ARGB32.cpp',
        '../src/core/SkBlitter_RGB16.cpp',
        '../src/core/SkBlitter_Sprite.cpp',
        '../src/core/SkBuffer.cpp',
        '../src/core/SkCanvas.cpp',
        '../src/core/SkChunkAlloc.cpp',
        '../src/core/SkClampRange.cpp',
        '../src/core/SkClipStack.cpp',
        '../src/core/SkColor.cpp',
        '../src/core/SkColorFilter.cpp',
        '../src/core/SkColorTable.cpp',
        '../src/core/SkComposeShader.cpp',
        '../src/core/SkConcaveToTriangles.cpp',
        '../src/core/SkConcaveToTriangles.h',
        '../src/core/SkCordic.cpp',
        '../src/core/SkCordic.h',
        '../src/core/SkCoreBlitters.h',
        '../src/core/SkCubicClipper.cpp',
        '../src/core/SkCubicClipper.h',
        '../src/core/SkData.cpp',
        '../src/core/SkDebug.cpp',
        '../src/core/SkDeque.cpp',
        '../src/core/SkDevice.cpp',
        '../src/core/SkDither.cpp',
        '../src/core/SkDraw.cpp',
        '../src/core/SkDrawProcs.h',
        '../src/core/SkEdgeBuilder.cpp',
        '../src/core/SkEdgeClipper.cpp',
        '../src/core/SkEdge.cpp',
        '../src/core/SkEdge.h',
        '../src/core/SkFP.h',
        '../src/core/SkFilterProc.cpp',
        '../src/core/SkFilterProc.h',
        '../src/core/SkFlattenable.cpp',
        '../src/core/SkFloat.cpp',
        '../src/core/SkFloat.h',
        '../src/core/SkFloatBits.cpp',
        '../src/core/SkFontHost.cpp',
        '../src/core/SkGeometry.cpp',
        '../src/core/SkGlobals.cpp',
        '../src/core/SkGlyphCache.cpp',
        '../src/core/SkGlyphCache.h',
        '../src/core/SkGraphics.cpp',
        '../src/core/SkLineClipper.cpp',
        '../src/core/SkMallocPixelRef.cpp',
        '../src/core/SkMask.cpp',
        '../src/core/SkMaskFilter.cpp',
        '../src/core/SkMath.cpp',
        '../src/core/SkMatrix.cpp',
        '../src/core/SkMetaData.cpp',
        '../src/core/SkPackBits.cpp',
        '../src/core/SkPaint.cpp',
        '../src/core/SkPath.cpp',
        '../src/core/SkPathEffect.cpp',
        '../src/core/SkPathHeap.cpp',
        '../src/core/SkPathHeap.h',
        '../src/core/SkPathMeasure.cpp',
        '../src/core/SkPicture.cpp',
        '../src/core/SkPictureFlat.cpp',
        '../src/core/SkPictureFlat.h',
        '../src/core/SkPicturePlayback.cpp',
        '../src/core/SkPicturePlayback.h',
        '../src/core/SkPictureRecord.cpp',
        '../src/core/SkPictureRecord.h',
        '../src/core/SkPixelRef.cpp',
        '../src/core/SkPoint.cpp',
        '../src/core/SkProcSpriteBlitter.cpp',
        '../src/core/SkPtrRecorder.cpp',
        '../src/core/SkQuadClipper.cpp',
        '../src/core/SkQuadClipper.h',
        '../src/core/SkRasterizer.cpp',
        '../src/core/SkRect.cpp',
        '../src/core/SkRefDict.cpp',
        '../src/core/SkRegion.cpp',
        '../src/core/SkRegionPriv.h',
        '../src/core/SkRegion_path.cpp',
        '../src/core/SkScalar.cpp',
        '../src/core/SkScalerContext.cpp',
        '../src/core/SkScan.cpp',
        '../src/core/SkScanPriv.h',
        '../src/core/SkScan_AntiPath.cpp',
        '../src/core/SkScan_Antihair.cpp',
        '../src/core/SkScan_Hairline.cpp',
        '../src/core/SkScan_Path.cpp',
        '../src/core/SkShader.cpp',
        '../src/core/SkShape.cpp',
        '../src/core/SkSpriteBlitter_ARGB32.cpp',
        '../src/core/SkSpriteBlitter_RGB16.cpp',
        '../src/core/SkSinTable.h',
        '../src/core/SkSpriteBlitter.h',
        '../src/core/SkSpriteBlitterTemplate.h',
        '../src/core/SkStream.cpp',
        '../src/core/SkString.cpp',
        '../src/core/SkStroke.cpp',
        '../src/core/SkStrokerPriv.cpp',
        '../src/core/SkStrokerPriv.h',
        '../src/core/SkTextFormatParams.h',
        '../src/core/SkTSearch.cpp',
        '../src/core/SkTSort.h',
        '../src/core/SkTemplatesPriv.h',
        '../src/core/SkTypeface.cpp',
        '../src/core/SkTypefaceCache.cpp',
        '../src/core/SkTypefaceCache.h',
        '../src/core/SkUnPreMultiply.cpp',
        '../src/core/SkUserTrace.h',
        '../src/core/SkUtils.cpp',
        '../src/core/SkWriter32.cpp',
        '../src/core/SkXfermode.cpp',

        '../src/opts/opts_check_SSE2.cpp',

        '../src/ports/SkDebug_stdio.cpp',
        '../src/ports/SkDebug_win.cpp',

        '../src/ports/SkFontHost_tables.cpp',
        '../src/ports/SkGlobals_global.cpp',
        '../src/ports/SkMemory_malloc.cpp',
        '../src/ports/SkOSFile_stdio.cpp',
        '../src/ports/SkTime_Unix.cpp',
        '../src/ports/SkTime_win.cpp',
        '../src/ports/SkXMLParser_empty.cpp',
        '../src/ports/sk_predefined_gamma.h',

        '../include/core/Sk64.h',
        '../include/core/SkAdvancedTypefaceMetrics.h',
        '../include/core/SkAutoKern.h',
        '../include/core/SkBitmap.h',
        '../include/core/SkBlitRow.h',
        '../include/core/SkBlitter.h',
        '../include/core/SkBounder.h',
        '../include/core/SkBuffer.h',
        '../include/core/SkCanvas.h',
        '../include/core/SkChunkAlloc.h',
        '../include/core/SkClampRange.h',
        '../include/core/SkClipStack.h',
        '../include/core/SkColor.h',
        '../include/core/SkColorFilter.h',
        '../include/core/SkColorPriv.h',
        '../include/core/SkColorShader.h',
        '../include/core/SkComposeShader.h',
        '../include/core/SkData.h',
        '../include/core/SkDeque.h',
        '../include/core/SkDescriptor.h',
        '../include/core/SkDevice.h',
        '../include/core/SkDither.h',
        '../include/core/SkDraw.h',
        '../include/core/SkDrawFilter.h',
        '../include/core/SkDrawLooper.h',
        '../include/core/SkEndian.h',
        '../include/core/SkFDot6.h',
        '../include/core/SkFixed.h',
        '../include/core/SkFlattenable.h',
        '../include/core/SkFloatBits.h',
        '../include/core/SkFloatingPoint.h',
        '../include/core/SkFontHost.h',
        '../include/core/SkGeometry.h',
        '../include/core/SkGlobals.h',
        '../include/core/SkGraphics.h',
        '../include/core/SkMallocPixelRef.h',
        '../include/core/SkMask.h',
        '../include/core/SkMaskFilter.h',
        '../include/core/SkMath.h',
        '../include/core/SkMatrix.h',
        '../include/core/SkMetaData.h',
        '../include/core/SkOSFile.h',
        '../include/core/SkPackBits.h',
        '../include/core/SkPaint.h',
        '../include/core/SkPath.h',
        '../include/core/SkPathEffect.h',
        '../include/core/SkPathMeasure.h',
        '../include/core/SkPerspIter.h',
        '../include/core/SkPicture.h',
        '../include/core/SkPixelRef.h',
        '../include/core/SkPoint.h',
        '../include/core/SkPtrRecorder.h',
        '../include/core/SkRandom.h',
        '../include/core/SkRasterizer.h',
        '../include/core/SkReader32.h',
        '../include/core/SkRect.h',
        '../include/core/SkRefCnt.h',
        '../include/core/SkRefDict.h',
        '../include/core/SkRegion.h',
        '../include/core/SkScalar.h',
        '../include/core/SkScalarCompare.h',
        '../include/core/SkScalerContext.h',
        '../include/core/SkScan.h',
        '../include/core/SkShader.h',
        '../include/core/SkStream.h',
        '../include/core/SkString.h',
        '../include/core/SkStroke.h',
        '../include/core/SkTDArray.h',
        '../include/core/SkTDStack.h',
        '../include/core/SkTDict.h',
        '../include/core/SkTRegistry.h',
        '../include/core/SkTScopedPtr.h',
        '../include/core/SkTSearch.h',
        '../include/core/SkTemplates.h',
        '../include/core/SkThread.h',
        '../include/core/SkThread_platform.h',
        '../include/core/SkTime.h',
        '../include/core/SkTrace.h',
        '../include/core/SkTypeface.h',
        '../include/core/SkTypes.h',
        '../include/core/SkUnPreMultiply.h',
        '../include/core/SkUnitMapper.h',
        '../include/core/SkUtils.h',
        '../include/core/SkWriter32.h',
        '../include/core/SkXfermode.h',
      ],
      'include_dirs': [
        '../include/config',
        '../include/core',
        '../include/ports',
        '../include/xml',
        '../src/core',
      ],
      'msvs_disabled_warnings': [4244, 4267,4345, 4390, 4554, 4800],
      'conditions': [
        [ 'skia_os in ["linux", "freebsd", "openbsd", "solaris"]', {
          'cflags': [
            '-Wno-unused',
            '-Wno-unused-function',
          ],
          'sources': [
            '../include/core/SkMMapStream.h',
            '../src/core/SkMMapStream.cpp',
            '../src/ports/SkThread_pthread.cpp',
            '../src/ports/SkTime_Unix.cpp',
            '../src/ports/SkFontHost_FreeType.cpp',
            '../src/ports/SkFontHost_gamma_none.cpp',
            '../src/ports/SkFontHost_linux.cpp',
          ],
          'link_settings': {
            'libraries': [
              '-lfreetype',
              '-lpthread',
            ],
          },
        }],
        [ 'skia_os == "mac"', {
          'include_dirs': [
            '../include/utils/mac',
          ],
          'sources': [
            '../include/core/SkMMapStream.h',
            '../include/utils/mac/SkCGUtils.h',

            '../src/core/SkMMapStream.cpp',
            '../src/ports/SkFontHost_mac_coretext.cpp',

            '../src/ports/SkThread_pthread.cpp',
            '../src/ports/SkTime_Unix.cpp',
          ],
          'link_settings': {
            'libraries': [
              '$(SDKROOT)/System/Library/Frameworks/Carbon.framework',
              '$(SDKROOT)/System/Library/Frameworks/ApplicationServices.framework',
            ],
          },
        }],
        [ 'skia_os == "ios"', {
          'include_dirs': [
            '../include/utils/ios',
          ],
          'sources': [
            '../include/core/SkMMapStream.h',
            '../include/utils/mac/SkCGUtils.h',

            '../src/core/SkMMapStream.cpp',
            '../src/ports/SkFontHost_mac_coretext.cpp',

            '../src/ports/SkThread_pthread.cpp',
            '../src/ports/SkTime_Unix.cpp',
          ],
          'link_settings': {
            'libraries': [
              '/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS4.3.sdk/System/Library/Frameworks/CoreFoundation.framework',
              '/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS4.3.sdk/System/Library/Frameworks/CoreGraphics.framework',
              '/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS4.3.sdk/System/Library/Frameworks/CoreText.framework',
              '/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS4.3.sdk/System/Library/Frameworks/UIKit.framework',
              '/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS4.3.sdk/System/Library/Frameworks/Foundation.framework',
              '/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS4.3.sdk/System/Library/Frameworks/QuartzCore.framework',
              '/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS4.3.sdk/System/Library/Frameworks/OpenGLES.framework',
            ],
          },
        }],
        [ 'skia_os == "win"', {
          'include_dirs': [
            'config/win',
          ],
          'sources': [
            '../src/ports/SkFontHost_win.cpp',
            '../src/ports/SkThread_win.cpp',
          ],
          'sources!': [
            '../src/ports/SkDebug_stdio.cpp',
          ],
        }],
        [ 'skia_os != "win"', {
          'sources!': [
            '../src/ports/SkDebug_win.cpp',
            '../src/ports/SkTime_win.cpp',
          ],
        }],
      ],
      'direct_dependent_settings': {
        'include_dirs': [
          'config',
          '../include/config',
          '../include/core',
          'ext',
        ],
      },
      'dependencies': [
        'opts.gyp:opts'
      ],
    },
  ],
}

# Local Variables:
# tab-width:2
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=2 shiftwidth=2:
<commit_msg>little bit of gyp cleanup (fixes windows build of sktime_unix)<commit_after># Core Skia library code.
{
  'includes': [
    'common.gypi',
  ],
  'targets': [
    {
      'target_name': 'core',
      'type': 'static_library',
      'msvs_guid': 'B7760B5E-BFA8-486B-ACFD-49E3A6DE8E76',
      'sources': [
        '../src/core/ARGB32_Clamp_Bilinear_BitmapShader.h',
        '../src/core/Sk64.cpp',
        '../src/core/SkAdvancedTypefaceMetrics.cpp',
        '../src/core/SkAlphaRuns.cpp',
        '../src/core/SkAntiRun.h',
        '../src/core/SkBitmap.cpp',
        '../src/core/SkBitmapProcShader.cpp',
        '../src/core/SkBitmapProcShader.h',
        '../src/core/SkBitmapProcState.cpp',
        '../src/core/SkBitmapProcState.h',
        '../src/core/SkBitmapProcState_matrix.h',
        '../src/core/SkBitmapProcState_matrixProcs.cpp',
        '../src/core/SkBitmapProcState_sample.h',
        '../src/core/SkBitmapSampler.cpp',
        '../src/core/SkBitmapSampler.h',
        '../src/core/SkBitmapSamplerTemplate.h',
        '../src/core/SkBitmapShader16BilerpTemplate.h',
        '../src/core/SkBitmapShaderTemplate.h',
        '../src/core/SkBitmap_scroll.cpp',
        '../src/core/SkBlitBWMaskTemplate.h',
        '../src/core/SkBlitRow_D16.cpp',
        '../src/core/SkBlitRow_D32.cpp',
        '../src/core/SkBlitRow_D4444.cpp',
        '../src/core/SkBlitter.cpp',
        '../src/core/SkBlitter_4444.cpp',
        '../src/core/SkBlitter_A1.cpp',
        '../src/core/SkBlitter_A8.cpp',
        '../src/core/SkBlitter_ARGB32.cpp',
        '../src/core/SkBlitter_RGB16.cpp',
        '../src/core/SkBlitter_Sprite.cpp',
        '../src/core/SkBuffer.cpp',
        '../src/core/SkCanvas.cpp',
        '../src/core/SkChunkAlloc.cpp',
        '../src/core/SkClampRange.cpp',
        '../src/core/SkClipStack.cpp',
        '../src/core/SkColor.cpp',
        '../src/core/SkColorFilter.cpp',
        '../src/core/SkColorTable.cpp',
        '../src/core/SkComposeShader.cpp',
        '../src/core/SkConcaveToTriangles.cpp',
        '../src/core/SkConcaveToTriangles.h',
        '../src/core/SkCordic.cpp',
        '../src/core/SkCordic.h',
        '../src/core/SkCoreBlitters.h',
        '../src/core/SkCubicClipper.cpp',
        '../src/core/SkCubicClipper.h',
        '../src/core/SkData.cpp',
        '../src/core/SkDebug.cpp',
        '../src/core/SkDeque.cpp',
        '../src/core/SkDevice.cpp',
        '../src/core/SkDither.cpp',
        '../src/core/SkDraw.cpp',
        '../src/core/SkDrawProcs.h',
        '../src/core/SkEdgeBuilder.cpp',
        '../src/core/SkEdgeClipper.cpp',
        '../src/core/SkEdge.cpp',
        '../src/core/SkEdge.h',
        '../src/core/SkFP.h',
        '../src/core/SkFilterProc.cpp',
        '../src/core/SkFilterProc.h',
        '../src/core/SkFlattenable.cpp',
        '../src/core/SkFloat.cpp',
        '../src/core/SkFloat.h',
        '../src/core/SkFloatBits.cpp',
        '../src/core/SkFontHost.cpp',
        '../src/core/SkGeometry.cpp',
        '../src/core/SkGlobals.cpp',
        '../src/core/SkGlyphCache.cpp',
        '../src/core/SkGlyphCache.h',
        '../src/core/SkGraphics.cpp',
        '../src/core/SkLineClipper.cpp',
        '../src/core/SkMallocPixelRef.cpp',
        '../src/core/SkMask.cpp',
        '../src/core/SkMaskFilter.cpp',
        '../src/core/SkMath.cpp',
        '../src/core/SkMatrix.cpp',
        '../src/core/SkMetaData.cpp',
        '../src/core/SkPackBits.cpp',
        '../src/core/SkPaint.cpp',
        '../src/core/SkPath.cpp',
        '../src/core/SkPathEffect.cpp',
        '../src/core/SkPathHeap.cpp',
        '../src/core/SkPathHeap.h',
        '../src/core/SkPathMeasure.cpp',
        '../src/core/SkPicture.cpp',
        '../src/core/SkPictureFlat.cpp',
        '../src/core/SkPictureFlat.h',
        '../src/core/SkPicturePlayback.cpp',
        '../src/core/SkPicturePlayback.h',
        '../src/core/SkPictureRecord.cpp',
        '../src/core/SkPictureRecord.h',
        '../src/core/SkPixelRef.cpp',
        '../src/core/SkPoint.cpp',
        '../src/core/SkProcSpriteBlitter.cpp',
        '../src/core/SkPtrRecorder.cpp',
        '../src/core/SkQuadClipper.cpp',
        '../src/core/SkQuadClipper.h',
        '../src/core/SkRasterizer.cpp',
        '../src/core/SkRect.cpp',
        '../src/core/SkRefDict.cpp',
        '../src/core/SkRegion.cpp',
        '../src/core/SkRegionPriv.h',
        '../src/core/SkRegion_path.cpp',
        '../src/core/SkScalar.cpp',
        '../src/core/SkScalerContext.cpp',
        '../src/core/SkScan.cpp',
        '../src/core/SkScanPriv.h',
        '../src/core/SkScan_AntiPath.cpp',
        '../src/core/SkScan_Antihair.cpp',
        '../src/core/SkScan_Hairline.cpp',
        '../src/core/SkScan_Path.cpp',
        '../src/core/SkShader.cpp',
        '../src/core/SkShape.cpp',
        '../src/core/SkSpriteBlitter_ARGB32.cpp',
        '../src/core/SkSpriteBlitter_RGB16.cpp',
        '../src/core/SkSinTable.h',
        '../src/core/SkSpriteBlitter.h',
        '../src/core/SkSpriteBlitterTemplate.h',
        '../src/core/SkStream.cpp',
        '../src/core/SkString.cpp',
        '../src/core/SkStroke.cpp',
        '../src/core/SkStrokerPriv.cpp',
        '../src/core/SkStrokerPriv.h',
        '../src/core/SkTextFormatParams.h',
        '../src/core/SkTSearch.cpp',
        '../src/core/SkTSort.h',
        '../src/core/SkTemplatesPriv.h',
        '../src/core/SkTypeface.cpp',
        '../src/core/SkTypefaceCache.cpp',
        '../src/core/SkTypefaceCache.h',
        '../src/core/SkUnPreMultiply.cpp',
        '../src/core/SkUserTrace.h',
        '../src/core/SkUtils.cpp',
        '../src/core/SkWriter32.cpp',
        '../src/core/SkXfermode.cpp',

        '../src/opts/opts_check_SSE2.cpp',

        '../src/ports/SkDebug_stdio.cpp',
        '../src/ports/SkDebug_win.cpp',
        '../src/ports/SkFontHost_win.cpp',
        '../src/ports/SkThread_win.cpp',

        '../src/ports/SkFontHost_tables.cpp',
        '../src/ports/SkGlobals_global.cpp',
        '../src/ports/SkMemory_malloc.cpp',
        '../src/ports/SkOSFile_stdio.cpp',
        '../src/ports/SkTime_Unix.cpp',
        '../src/ports/SkTime_win.cpp',
        '../src/ports/SkXMLParser_empty.cpp',
        '../src/ports/sk_predefined_gamma.h',

        '../include/core/Sk64.h',
        '../include/core/SkAdvancedTypefaceMetrics.h',
        '../include/core/SkAutoKern.h',
        '../include/core/SkBitmap.h',
        '../include/core/SkBlitRow.h',
        '../include/core/SkBlitter.h',
        '../include/core/SkBounder.h',
        '../include/core/SkBuffer.h',
        '../include/core/SkCanvas.h',
        '../include/core/SkChunkAlloc.h',
        '../include/core/SkClampRange.h',
        '../include/core/SkClipStack.h',
        '../include/core/SkColor.h',
        '../include/core/SkColorFilter.h',
        '../include/core/SkColorPriv.h',
        '../include/core/SkColorShader.h',
        '../include/core/SkComposeShader.h',
        '../include/core/SkData.h',
        '../include/core/SkDeque.h',
        '../include/core/SkDescriptor.h',
        '../include/core/SkDevice.h',
        '../include/core/SkDither.h',
        '../include/core/SkDraw.h',
        '../include/core/SkDrawFilter.h',
        '../include/core/SkDrawLooper.h',
        '../include/core/SkEndian.h',
        '../include/core/SkFDot6.h',
        '../include/core/SkFixed.h',
        '../include/core/SkFlattenable.h',
        '../include/core/SkFloatBits.h',
        '../include/core/SkFloatingPoint.h',
        '../include/core/SkFontHost.h',
        '../include/core/SkGeometry.h',
        '../include/core/SkGlobals.h',
        '../include/core/SkGraphics.h',
        '../include/core/SkMallocPixelRef.h',
        '../include/core/SkMask.h',
        '../include/core/SkMaskFilter.h',
        '../include/core/SkMath.h',
        '../include/core/SkMatrix.h',
        '../include/core/SkMetaData.h',
        '../include/core/SkOSFile.h',
        '../include/core/SkPackBits.h',
        '../include/core/SkPaint.h',
        '../include/core/SkPath.h',
        '../include/core/SkPathEffect.h',
        '../include/core/SkPathMeasure.h',
        '../include/core/SkPerspIter.h',
        '../include/core/SkPicture.h',
        '../include/core/SkPixelRef.h',
        '../include/core/SkPoint.h',
        '../include/core/SkPtrRecorder.h',
        '../include/core/SkRandom.h',
        '../include/core/SkRasterizer.h',
        '../include/core/SkReader32.h',
        '../include/core/SkRect.h',
        '../include/core/SkRefCnt.h',
        '../include/core/SkRefDict.h',
        '../include/core/SkRegion.h',
        '../include/core/SkScalar.h',
        '../include/core/SkScalarCompare.h',
        '../include/core/SkScalerContext.h',
        '../include/core/SkScan.h',
        '../include/core/SkShader.h',
        '../include/core/SkStream.h',
        '../include/core/SkString.h',
        '../include/core/SkStroke.h',
        '../include/core/SkTDArray.h',
        '../include/core/SkTDStack.h',
        '../include/core/SkTDict.h',
        '../include/core/SkTRegistry.h',
        '../include/core/SkTScopedPtr.h',
        '../include/core/SkTSearch.h',
        '../include/core/SkTemplates.h',
        '../include/core/SkThread.h',
        '../include/core/SkThread_platform.h',
        '../include/core/SkTime.h',
        '../include/core/SkTrace.h',
        '../include/core/SkTypeface.h',
        '../include/core/SkTypes.h',
        '../include/core/SkUnPreMultiply.h',
        '../include/core/SkUnitMapper.h',
        '../include/core/SkUtils.h',
        '../include/core/SkWriter32.h',
        '../include/core/SkXfermode.h',
      ],
      'include_dirs': [
        '../include/config',
        '../include/core',
        '../include/ports',
        '../include/xml',
        '../src/core',
      ],
      'msvs_disabled_warnings': [4244, 4267,4345, 4390, 4554, 4800],
      'conditions': [
        [ 'skia_os in ["linux", "freebsd", "openbsd", "solaris"]', {
          'cflags': [
            '-Wno-unused',
            '-Wno-unused-function',
          ],
          'sources': [
            '../include/core/SkMMapStream.h',
            '../src/core/SkMMapStream.cpp',
            '../src/ports/SkThread_pthread.cpp',
            '../src/ports/SkFontHost_FreeType.cpp',
            '../src/ports/SkFontHost_gamma_none.cpp',
            '../src/ports/SkFontHost_linux.cpp',
          ],
          'link_settings': {
            'libraries': [
              '-lfreetype',
              '-lpthread',
            ],
          },
        }],
        [ 'skia_os == "mac"', {
          'include_dirs': [
            '../include/utils/mac',
          ],
          'sources': [
            '../include/core/SkMMapStream.h',
            '../include/utils/mac/SkCGUtils.h',

            '../src/core/SkMMapStream.cpp',
            '../src/ports/SkFontHost_mac_coretext.cpp',

            '../src/ports/SkThread_pthread.cpp',
          ],
          'link_settings': {
            'libraries': [
              '$(SDKROOT)/System/Library/Frameworks/Carbon.framework',
              '$(SDKROOT)/System/Library/Frameworks/ApplicationServices.framework',
            ],
          },
        }],
        [ 'skia_os == "ios"', {
          'include_dirs': [
            '../include/utils/ios',
          ],
          'sources': [
            '../include/core/SkMMapStream.h',
            '../include/utils/mac/SkCGUtils.h',

            '../src/core/SkMMapStream.cpp',
            '../src/ports/SkFontHost_mac_coretext.cpp',

            '../src/ports/SkThread_pthread.cpp',
          ],
          'link_settings': {
            'libraries': [
              '/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS4.3.sdk/System/Library/Frameworks/CoreFoundation.framework',
              '/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS4.3.sdk/System/Library/Frameworks/CoreGraphics.framework',
              '/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS4.3.sdk/System/Library/Frameworks/CoreText.framework',
              '/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS4.3.sdk/System/Library/Frameworks/UIKit.framework',
              '/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS4.3.sdk/System/Library/Frameworks/Foundation.framework',
              '/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS4.3.sdk/System/Library/Frameworks/QuartzCore.framework',
              '/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS4.3.sdk/System/Library/Frameworks/OpenGLES.framework',
            ],
          },
        }],
        [ 'skia_os == "win"', {
          'include_dirs': [
            'config/win',
          ],
          'sources!': [ # these are used everywhere but windows
            '../src/ports/SkDebug_stdio.cpp',
            '../src/ports/SkTime_Unix.cpp',
          ],
        }, { # else !win
          'sources!': [
            '../src/ports/SkDebug_win.cpp',
            '../src/ports/SkFontHost_win.cpp',
            '../src/ports/SkThread_win.cpp',
            '../src/ports/SkTime_win.cpp',
          ],
        }],
      ],
      'direct_dependent_settings': {
        'include_dirs': [
          'config',
          '../include/config',
          '../include/core',
          'ext',
        ],
      },
      'dependencies': [
        'opts.gyp:opts'
      ],
    },
  ],
}

# Local Variables:
# tab-width:2
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=2 shiftwidth=2:
<|endoftext|>


<commit_before>#!/usr/bin/env python

# http://stackoverflow.com/a/14050282
def check_antipackage():
    from sys import version_info
    sys_version = version_info[:2]
    found = True
    if sys_version < (3, 0):
        # 'python 2'
        from pkgutil import find_loader
        found = find_loader('antipackage') is not None
    elif sys_version <= (3, 3):
        # 'python <= 3.3'
        from importlib import find_loader
        found = find_loader('antipackage') is not None
    else:
        # 'python >= 3.4'
        from importlib import util
        found = util.find_spec('antipackage') is not None
    if not found:
        print('Install missing package "antipackage"')
        print('Example: pip install git+https://github.com/ellisonbg/antipackage.git#egg=antipackage')
        from sys import exit
        exit(1)
check_antipackage()

# ref: https://github.com/ellisonbg/antipackage
import antipackage
from github.appscode.libbuild import libbuild

import os
import os.path
import subprocess
import sys
from os.path import expandvars

libbuild.REPO_ROOT = expandvars('$GOPATH') + '/src/github.com/appscode/searchlight'
BUILD_METADATA = libbuild.metadata(libbuild.REPO_ROOT)
libbuild.BIN_MATRIX = {
    'searchlight': {
        'type': 'go',
        'go_version': True,
        'distro': {
            'linux': ['amd64']
        }
    },
    'hyperalert': {
        'type': 'go',
        'go_version': True,
        'distro': {
            'linux': ['amd64']
        }
    },
    'check_component_status': {
        'type': 'go',
        'go_version': True,
        'distro': {
            'linux': ['amd64']
        }
    },
    'check_influx_query': {
        'type': 'go',
        'go_version': True,
        'distro': {
            'linux': ['amd64']
        }
    },
    'check_json_path': {
        'type': 'go',
        'go_version': True,
        'distro': {
            'linux': ['amd64']
        }
    },
    'check_node_count': {
        'type': 'go',
        'go_version': True,
        'distro': {
            'linux': ['amd64']
        }
    },
    'check_node_status': {
        'type': 'go',
        'go_version': True,
        'distro': {
            'linux': ['amd64']
        }
    },
    'check_pod_exists': {
        'type': 'go',
        'go_version': True,
        'distro': {
            'linux': ['amd64']
        }
    },
    'check_pod_status': {
        'type': 'go',
        'go_version': True,
        'distro': {
            'linux': ['amd64']
        }
    },
    'check_prometheus_metric': {
        'type': 'go',
        'go_version': True,
        'distro': {
            'linux': ['amd64']
        }
    },
    'check_volume': {
        'type': 'go',
        'go_version': True,
        'distro': {
            'linux': ['amd64']
        }
    },
    'notifier': {
        'type': 'go',
        'go_version': True,
        'distro': {
            'linux': ['amd64']
        }
    },
    'hello_icinga': {
        'type': 'go',
        'go_version': True,
        'distro': {
            'linux': ['amd64']
        }
    },
}
libbuild.BUCKET_MATRIX = {
    'prod': 'gs://appscode-cdn',
    'dev': 'gs://appscode-dev'
}

def call(cmd, stdin=None, cwd=libbuild.REPO_ROOT):
    print(cmd)
    return subprocess.call([expandvars(cmd)], shell=True, stdin=stdin, cwd=cwd)

def die(status):
    if status:
        sys.exit(status)

def check_output(cmd, stdin=None, cwd=libbuild.REPO_ROOT):
    print(cmd)
    return subprocess.check_output([expandvars(cmd)], shell=True, stdin=stdin, cwd=cwd)

def version():
    # json.dump(BUILD_METADATA, sys.stdout, sort_keys=True, indent=2)
    for k in sorted(BUILD_METADATA):
        print(k + '=' + BUILD_METADATA[k])

def fmt():
    die(call('goimports -w cmd data pkg plugins util'))
    call('gofmt -s -w cmd data pkg plugins util')

def vet():
    call('go vet ./cmd/... ./data/... ./pkg/... ./plugins/... ./util/...')

def lint():
    call('golint ./cmd/...')
    call('golint ./data/...')
    call('golint ./pkg/...')
    call('golint ./plugins/...')
    call('golint ./util/...')

def gen_assets():
    die(call('go-bindata -ignore=\\.go -ignore=\\.DS_Store -mode=0644 -modtime=1453795200 -o bindata.go -pkg files ./...', cwd=libbuild.REPO_ROOT + '/data/files'))

def gen_extpoints():
    die(call('go generate cmd/notifier/main.go'))

def gen():
    gen_assets()
    gen_extpoints()

def build_cmd(name):
    cfg = libbuild.BIN_MATRIX[name]
    if cfg['type'] == 'go':
        if 'distro' in cfg:
            for goos, archs in cfg['distro'].items():
                for goarch in archs:
                    libbuild.go_build(name, goos, goarch, main='cmd/{}/*.go'.format(name))
        else:
            libbuild.go_build(name, libbuild.GOHOSTOS, libbuild.GOHOSTARCH, main='cmd/{}/*.go'.format(name))

def build_cmds():
    gen()
    for name in libbuild.BIN_MATRIX:
        build_cmd(name)

def build(name=None):
    if name:
        cfg = libbuild.BIN_MATRIX[name]
        if cfg['type'] == 'go':
            gen()
            fmt()
            build_cmd(name)
    else:
        build_cmds()

def push(name=None):
    if name:
        bindir = libbuild.REPO_ROOT + '/dist/' + name
        push_bin(bindir)
    else:
        dist = libbuild.REPO_ROOT + '/dist'
        for name in os.listdir(dist):
            d = dist + '/' + name
            if os.path.isdir(d):
                push_bin(d)

def push_bin(bindir):
    call('rm -f *.md5', cwd=bindir)
    call('rm -f *.sha1', cwd=bindir)
    for f in os.listdir(bindir):
        if os.path.isfile(bindir + '/' + f):
            libbuild.upload_to_cloud(bindir, f, BUILD_METADATA['version'])

def update_registry():
    libbuild.update_registry(BUILD_METADATA['version'])

def install():
    die(call('GO15VENDOREXPERIMENT=1 ' + libbuild.GOC + ' install ./cmd/...'))

def default():
    gen()
    fmt()
    die(call('GO15VENDOREXPERIMENT=1 ' + libbuild.GOC + ' install ./cmd/...'))

if __name__ == "__main__":
    if len(sys.argv) > 1:
        # http://stackoverflow.com/a/834451
        # http://stackoverflow.com/a/817296
        globals()[sys.argv[1]](*sys.argv[2:])
    else:
        default()
<commit_msg>Avoid fmt() for prod build.<commit_after>#!/usr/bin/env python

# http://stackoverflow.com/a/14050282
def check_antipackage():
    from sys import version_info
    sys_version = version_info[:2]
    found = True
    if sys_version < (3, 0):
        # 'python 2'
        from pkgutil import find_loader
        found = find_loader('antipackage') is not None
    elif sys_version <= (3, 3):
        # 'python <= 3.3'
        from importlib import find_loader
        found = find_loader('antipackage') is not None
    else:
        # 'python >= 3.4'
        from importlib import util
        found = util.find_spec('antipackage') is not None
    if not found:
        print('Install missing package "antipackage"')
        print('Example: pip install git+https://github.com/ellisonbg/antipackage.git#egg=antipackage')
        from sys import exit
        exit(1)
check_antipackage()

# ref: https://github.com/ellisonbg/antipackage
import antipackage
from github.appscode.libbuild import libbuild

import os
import os.path
import subprocess
import sys
from os.path import expandvars

libbuild.REPO_ROOT = expandvars('$GOPATH') + '/src/github.com/appscode/searchlight'
BUILD_METADATA = libbuild.metadata(libbuild.REPO_ROOT)
libbuild.BIN_MATRIX = {
    'searchlight': {
        'type': 'go',
        'go_version': True,
        'distro': {
            'linux': ['amd64']
        }
    },
    'hyperalert': {
        'type': 'go',
        'go_version': True,
        'distro': {
            'linux': ['amd64']
        }
    },
    'check_component_status': {
        'type': 'go',
        'go_version': True,
        'distro': {
            'linux': ['amd64']
        }
    },
    'check_influx_query': {
        'type': 'go',
        'go_version': True,
        'distro': {
            'linux': ['amd64']
        }
    },
    'check_json_path': {
        'type': 'go',
        'go_version': True,
        'distro': {
            'linux': ['amd64']
        }
    },
    'check_node_count': {
        'type': 'go',
        'go_version': True,
        'distro': {
            'linux': ['amd64']
        }
    },
    'check_node_status': {
        'type': 'go',
        'go_version': True,
        'distro': {
            'linux': ['amd64']
        }
    },
    'check_pod_exists': {
        'type': 'go',
        'go_version': True,
        'distro': {
            'linux': ['amd64']
        }
    },
    'check_pod_status': {
        'type': 'go',
        'go_version': True,
        'distro': {
            'linux': ['amd64']
        }
    },
    'check_prometheus_metric': {
        'type': 'go',
        'go_version': True,
        'distro': {
            'linux': ['amd64']
        }
    },
    'check_volume': {
        'type': 'go',
        'go_version': True,
        'distro': {
            'linux': ['amd64']
        }
    },
    'notifier': {
        'type': 'go',
        'go_version': True,
        'distro': {
            'linux': ['amd64']
        }
    },
    'hello_icinga': {
        'type': 'go',
        'go_version': True,
        'distro': {
            'linux': ['amd64']
        }
    },
}
libbuild.BUCKET_MATRIX = {
    'prod': 'gs://appscode-cdn',
    'dev': 'gs://appscode-dev'
}

def call(cmd, stdin=None, cwd=libbuild.REPO_ROOT):
    print(cmd)
    return subprocess.call([expandvars(cmd)], shell=True, stdin=stdin, cwd=cwd)

def die(status):
    if status:
        sys.exit(status)

def check_output(cmd, stdin=None, cwd=libbuild.REPO_ROOT):
    print(cmd)
    return subprocess.check_output([expandvars(cmd)], shell=True, stdin=stdin, cwd=cwd)

def version():
    # json.dump(BUILD_METADATA, sys.stdout, sort_keys=True, indent=2)
    for k in sorted(BUILD_METADATA):
        print(k + '=' + BUILD_METADATA[k])

def fmt():
    die(call('goimports -w cmd data pkg plugins util'))
    call('gofmt -s -w cmd data pkg plugins util')

def vet():
    call('go vet ./cmd/... ./data/... ./pkg/... ./plugins/... ./util/...')

def lint():
    call('golint ./cmd/...')
    call('golint ./data/...')
    call('golint ./pkg/...')
    call('golint ./plugins/...')
    call('golint ./util/...')

def gen_assets():
    die(call('go-bindata -ignore=\\.go -ignore=\\.DS_Store -mode=0644 -modtime=1453795200 -o bindata.go -pkg files ./...', cwd=libbuild.REPO_ROOT + '/data/files'))

def gen_extpoints():
    die(call('go generate cmd/notifier/main.go'))

def gen():
    gen_assets()
    gen_extpoints()

def build_cmd(name):
    cfg = libbuild.BIN_MATRIX[name]
    if cfg['type'] == 'go':
        if 'distro' in cfg:
            for goos, archs in cfg['distro'].items():
                for goarch in archs:
                    libbuild.go_build(name, goos, goarch, main='cmd/{}/*.go'.format(name))
        else:
            libbuild.go_build(name, libbuild.GOHOSTOS, libbuild.GOHOSTARCH, main='cmd/{}/*.go'.format(name))

def build_cmds():
    gen()
    for name in libbuild.BIN_MATRIX:
        build_cmd(name)

def build(name=None):
    if name:
        cfg = libbuild.BIN_MATRIX[name]
        if cfg['type'] == 'go':
            gen()
            build_cmd(name)
    else:
        build_cmds()

def push(name=None):
    if name:
        bindir = libbuild.REPO_ROOT + '/dist/' + name
        push_bin(bindir)
    else:
        dist = libbuild.REPO_ROOT + '/dist'
        for name in os.listdir(dist):
            d = dist + '/' + name
            if os.path.isdir(d):
                push_bin(d)

def push_bin(bindir):
    call('rm -f *.md5', cwd=bindir)
    call('rm -f *.sha1', cwd=bindir)
    for f in os.listdir(bindir):
        if os.path.isfile(bindir + '/' + f):
            libbuild.upload_to_cloud(bindir, f, BUILD_METADATA['version'])

def update_registry():
    libbuild.update_registry(BUILD_METADATA['version'])

def install():
    die(call('GO15VENDOREXPERIMENT=1 ' + libbuild.GOC + ' install ./cmd/...'))

def default():
    gen()
    fmt()
    die(call('GO15VENDOREXPERIMENT=1 ' + libbuild.GOC + ' install ./cmd/...'))

if __name__ == "__main__":
    if len(sys.argv) > 1:
        # http://stackoverflow.com/a/834451
        # http://stackoverflow.com/a/817296
        globals()[sys.argv[1]](*sys.argv[2:])
    else:
        default()
<|endoftext|>


<commit_before>#!/usr/bin/env python
#
## happyfile - File open read/write functions, with automatic support for Gzip or BZip2 compression
## Created by: John McCrow (Feb. 25, 2016)
#
# 1. Basic hopen and hopen_write are happy, and thus do not complain by way of IOError exceptions.
#    Instead they return None, in case of file not found or permission issues.
#    Otherwise they return a valid file handle.
#
# 2. _any functions will attempt to open a base filename with added extensions of any compression method
#
# 3. _or_else functions will report a nice message to stderr upon failure to open, rather than raise exception
#
# 4. _write functions open file handles for writing, and can write compressed files directly
#

import bz2, gzip, sys, re

class hCompression:
    none = 0
    gzip = 1
    gz = 1
    bzip2 = 2
    bz2 = 2

def xprint(s):
    sys.stderr.write(str(s) + '\n')

def hopen(infile):
    f = None
    try:
        if re.search('\.bz2$', infile):
            f = bz2.BZ2File(infile, 'r')
        elif re.search('\.gz$', infile):
            f = gzip.GzipFile(infile, 'r')
        else:
            f = open(infile)
    except IOError:
        return None
    return f

def hopen_any(basefile):
    for ext in '', '.gz', '.bz2':
        f = hopen(basefile + ext)
        if f:
            return f
    return None

def hopen_or_else(infile):
    f = hopen(infile)
    if f:
        return f
    else:
        xprint("Unable to open file: " + infile)
        sys.exit(2)

def hopen_or_else_any(basefile):
    f = hopen_any(basefile)
    if f:
        return f
    else:
        xprint("Unable to open file: " + basefile)
        sys.exit(2)

def hopen_write(outfile, compression=hCompression.none, level=9):
    f = None
    if not level in range(1, 10):  # compression level must be integer 1-9
        level = 9
    try:
        if compression == hCompression.bzip2:
            if not re.search('\.bz2$', outfile):
                outfile += '.bz2'
            f = bz2.BZ2File(outfile, 'w', level)
        elif compression == hCompression.gzip:
            if not re.search('\.gz$', outfile):
                outfile += '.gz'
            f = gzip.GzipFile(outfile, 'w', level)
        else:
            f = open(outfile, 'w')
    except IOError:
        return None
    return f

def hopen_write_or_else(outfile, compression=hCompression.none, level=9):
    f = hopen_write(outfile, compression, level)
    if f:
        return f
    else:
        xprint("Unable to write to file: " + outfile)
        sys.exit(2)
<commit_msg>gzip text open fix<commit_after>#!/usr/bin/env python
#
## happyfile - File open read/write functions, with automatic support for Gzip or BZip2 compression
## Created by: John McCrow (Feb. 25, 2016)
#
# 1. Basic hopen and hopen_write are happy, and thus do not complain by way of IOError exceptions.
#    Instead they return None, in case of file not found or permission issues.
#    Otherwise they return a valid file handle.
#
# 2. _any functions will attempt to open a base filename with added extensions of any compression method
#
# 3. _or_else functions will report a nice message to stderr upon failure to open, rather than raise exception
#
# 4. _write functions open file handles for writing, and can write compressed files directly
#

import bz2, gzip, sys, re

class hCompression:
    none = 0
    gzip = 1
    gz = 1
    bzip2 = 2
    bz2 = 2

def xprint(s):
    sys.stderr.write(str(s) + '\n')

def hopen(infile):
    f = None
    try:
        if re.search('\.bz2$', infile):
            f = bz2.open(infile, 'rt')
        elif re.search('\.gz$', infile):
            f = gzip.open(infile, 'rt')
        else:
            f = open(infile)
    except IOError:
        return None
    return f

def hopen_any(basefile):
    for ext in '', '.gz', '.bz2':
        f = hopen(basefile + ext)
        if f:
            return f
    return None

def hopen_or_else(infile):
    f = hopen(infile)
    if f:
        return f
    else:
        xprint("Unable to open file: " + infile)
        sys.exit(2)

def hopen_or_else_any(basefile):
    f = hopen_any(basefile)
    if f:
        return f
    else:
        xprint("Unable to open file: " + basefile)
        sys.exit(2)

def hopen_write(outfile, compression=hCompression.none, level=9):
    f = None
    if not level in range(1, 10):  # compression level must be integer 1-9
        level = 9
    try:
        if compression == hCompression.bzip2:
            if not re.search('\.bz2$', outfile):
                outfile += '.bz2'
            f = bz2.BZ2File(outfile, 'w', level)
        elif compression == hCompression.gzip:
            if not re.search('\.gz$', outfile):
                outfile += '.gz'
            f = gzip.GzipFile(outfile, 'w', level)
        else:
            f = open(outfile, 'w')
    except IOError:
        return None
    return f

def hopen_write_or_else(outfile, compression=hCompression.none, level=9):
    f = hopen_write(outfile, compression, level)
    if f:
        return f
    else:
        xprint("Unable to write to file: " + outfile)
        sys.exit(2)
<|endoftext|>


<commit_before>import freqs
import heapq as hp
from collections import defaultdict
from music21 import corpus
from frequtils import *

table = freqs.Env()
table.train(corpus.getBachChorales())

def harmonize(notes, key = None, voice = None, vel = None): # TODO generalize as kwargs
    '''
    harmonize(notes, key = None, voice = None, vel = None)
    Returns the most probable sequence of chords for the given sequence of notes, with optional information
    given for the key, voice, signature and harmonic rhythm.
    The key is inferred if not provided; the other variables are averaged or not considered.
    '''

    # Viterbi algorithm
    probs  = defaultdict(Prob)
    preds  = {}
    length = len(notes)

    for c, k, p in chords(notes[0], key, voice): # should iterate through all keys if key None, else just k
        probs[c, k, 0] = p # cprob(c, k) * nprob(notes[0], c, k, voice) # perhaps move cprob to chords

    for i in xrange(1, length):
        bestprob = Prob()
        best = None
        for c, k, _ in chords(notes[i], key, voice):
            # find max and arg max of transition
            for c1, _ in chords(notes[i-1], k):
                newprob = probs[c1, k, i - 1] * cprob(c1, k, c, vel) * nprob(notes[i], c1, k, voice, notes[i-1], c, vel)
                if probs[c, k, i] < newprob:
                    probs[c, k, i] = newprob
                    preds[c, k, i] = c1
            # update bestprob and bestchor
            if bestprob < probs[c, k, i]:
                bestprob = probs[c, k, i]
                best = c, k

    # construct chords
    # perhaps construct likeliest four-part voice leading from these later
    c, k = best
    chors = [c]
    for i in xrange(length - 1, 0, -1):
        c = preds[c, k, i]
        chors.append(c)

    return k, chors, bestprob

def cprob(c, k, c1 = None, vel = None):
    '''
    cprob(c, k[, c1, vel])
    Returns the probability that chord c will occur in key k, optionally after chord c1 and with harmonic velocity vel.
    '''
    # compute P(Trans(Func(c, k), Func(c1, k))[| vel])
    # TODO normalize over None variables instead, or move that to freqs
    if not c1 or not vel:
        return table.cprob(c, k)
    return table.tprob(c, k, c1, vel)

def nprob(n, c, k, voice = None, n1 = None, c1 = None, vel = None):
    '''
    nprob(n, c, k[, voice, n1, c1, vel])
    Returns the probability that note n will occur in the given voice of chord c and key k,
    optionally after note n1 in chord c1 and with harmonic velocity vel.
    '''
    # compute P(Pitch(n, c) | Pitch(n1, c1), voice, Trans(Func(c1, k), Func(c, k)), vel)
    if not n1 or not c1 or not vel:
        return table.nprob(n, c, k, voice)
    return table.vprob(n, n1, c, c1, k, voice, vel)

def chords(note, key = None, voice = None):
    '''
    chords(note[, key, voice])
    Iterates through all chords that contain note, optionally in a given key or voice.
    Returns a generator of tuples of type (Chord, Key, Probability).
    '''
    # probability = cprob(chord, key) * nprob(note, chord, key, voice)
    def prob(c, n, k, v):
        return cprob(c, k) * nprob(n, c, k, v)

    for k in ([key] if key else keys):
        for c in chords:
            p = prob(c, note, key, voice)
            if p > threshold: # TODO constant threshold
                yield c, k, p
<commit_msg>Moved table from harmonize to freqs<commit_after>import freqs
import heapq as hp
from collections import defaultdict
from music21 import corpus
from frequtils import *

table = freqs.table

def harmonize(notes, key = None, voice = None, vel = None): # TODO generalize as kwargs
    '''
    harmonize(notes, key = None, voice = None, vel = None)
    Returns the most probable sequence of chords for the given sequence of notes, with optional information
    given for the key, voice, signature and harmonic rhythm.
    The key is inferred if not provided; the other variables are averaged or not considered.
    '''

    # Viterbi algorithm
    probs  = defaultdict(Prob)
    preds  = {}
    length = len(notes)

    for c, k, p in chords(notes[0], key, voice): # should iterate through all keys if key None, else just k
        probs[c, k, 0] = p # cprob(c, k) * nprob(notes[0], c, k, voice) # perhaps move cprob to chords

    for i in xrange(1, length):
        bestprob = Prob()
        best = None
        for c, k, _ in chords(notes[i], key, voice):
            # find max and arg max of transition
            for c1, _ in chords(notes[i-1], k):
                newprob = probs[c1, k, i - 1] * cprob(c1, k, c, vel) * nprob(notes[i], c1, k, voice, notes[i-1], c, vel)
                if probs[c, k, i] < newprob:
                    probs[c, k, i] = newprob
                    preds[c, k, i] = c1
            # update bestprob and bestchor
            if bestprob < probs[c, k, i]:
                bestprob = probs[c, k, i]
                best = c, k

    # construct chords
    # perhaps construct likeliest four-part voice leading from these later
    c, k = best
    chors = [c]
    for i in xrange(length - 1, 0, -1):
        c = preds[c, k, i]
        chors.append(c)

    return k, chors, bestprob

def cprob(c, k, c1 = None, vel = None):
    '''
    cprob(c, k[, c1, vel])
    Returns the probability that chord c will occur in key k, optionally after chord c1 and with harmonic velocity vel.
    '''
    # compute P(Trans(Func(c, k), Func(c1, k))[| vel])
    # TODO normalize over None variables instead, or move that to freqs
    if not c1 or not vel:
        return table.cprob(c, k)
    return table.tprob(c, k, c1, vel)

def nprob(n, c, k, voice = None, n1 = None, c1 = None, vel = None):
    '''
    nprob(n, c, k[, voice, n1, c1, vel])
    Returns the probability that note n will occur in the given voice of chord c and key k,
    optionally after note n1 in chord c1 and with harmonic velocity vel.
    '''
    # compute P(Pitch(n, c) | Pitch(n1, c1), voice, Trans(Func(c1, k), Func(c, k)), vel)
    if not n1 or not c1 or not vel:
        return table.nprob(n, c, k, voice)
    return table.vprob(n, n1, c, c1, k, voice, vel)

def chords(note, key = None, voice = None):
    '''
    chords(note[, key, voice])
    Iterates through all chords that contain note, optionally in a given key or voice.
    Returns a generator of tuples of type (Chord, Key, Probability).
    '''
    # probability = cprob(chord, key) * nprob(note, chord, key, voice)
    def prob(c, n, k, v):
        return cprob(c, k) * nprob(n, c, k, v)

    for k in ([key] if key else keys):
        for c in chords:
            p = prob(c, note, key, voice)
            if p > threshold: # TODO constant threshold
                yield c, k, p
<|endoftext|>


<commit_before>#!/usr/bin/python3

# This program takes one argument: a directory path.
# It looks at every file in that directory, and hashes its contents,
# then gives it a name composed of three random words selected
# deterministically from that hash.

from sys import exit, argv
from hashlib import sha512
import os

# Start by verifying that a words file exists.
def getWords(path='/usr/share/dict/words'):
    try:
        with open(path, 'r') as wordsFile:
            return wordsFile.readlines()
    except FileNotFoundError:
        print('No words file found at {}.'.format(path))
        sys.exit(1)

# Get an int from the hash of file contents.
def hashFile(path):
    with open(path, 'rb') as f:
        # Pipe contents into hash, get hexdump, decode to int.
        #contents = f.read().encode()
        #return int(sha512(contents).hexdigest(), 16)
        return int(sha512(f.read()).hexdigest(), 16)

# Make a name of three words from the words list and an integer.
def makeUpName(filename, words):
    name = ''
    wordslen = len(words)
    seed = hashFile(filename)
    for i in range(3):
        index = seed % wordslen
        seed += index
        word = str(words[index]).capitalize().strip().replace("'", '')
        name += word
    print(name)
    return name

# Main function; renames specified files based on their contents.
def renameFiles(path, words):
    try:
        files = os.listdir(path)
        # If it's a directory, then we need to strip trailing slashes, and
        # prepend the path to each file name.
        path = path.rstrip('/') + os.sep
        for index, f in enumerate(files):
            files[index] = path + f
    except NotADirectoryError:
        files = [path]
        path = ''
    except FileNotFoundError:
        print('Invalid path: {}.'.format(path))
        exit(1)

    words = getWords()
    for filename in files:
        # Get the filetype.
        if len(filename.split('.')) > 1:
            ext = '.' + filename.split('.')[-1]
        else:
            ext = ''
        os.rename(filename, path + makeUpName(filename, words) + ext)

if __name__ == '__main__':
    renameFiles(argv[1], getWords())

<commit_msg>revised hashnames to take multiple dirs<commit_after>#!/usr/bin/python3

# This program takes one argument: a directory path.
# It looks at every file in that directory, and hashes its contents,
# then gives it a name composed of three random words selected
# deterministically from that hash.

from sys import exit, argv
from hashlib import sha512
import os

# Start by verifying that a words file exists.
def getWords(path='/usr/share/dict/words'):
    try:
        with open(path, 'r') as wordsFile:
            return wordsFile.readlines()
    except FileNotFoundError:
        print('No words file found at {}.'.format(path))
        sys.exit(1)

# Get an int from the hash of file contents.
def hashFile(path):
    with open(path, 'rb') as f:
        # Pipe contents into hash, get hexdump, decode to int.
        #contents = f.read().encode()
        #return int(sha512(contents).hexdigest(), 16)
        return int(sha512(f.read()).hexdigest(), 16)

# Make a name of three words from the words list and an integer.
def makeUpName(filename, words):
    name = ''
    wordslen = len(words)
    seed = hashFile(filename)
    for i in range(3):
        index = seed % wordslen
        seed += index
        word = str(words[index]).capitalize().strip().replace("'", '')
        name += word
    print(name)
    return name

# Main function; renames specified files based on their contents.
def renameFiles(path, words):
    try:
        files = os.listdir(path)
        # If it's a directory, then we need to strip trailing slashes, and
        # prepend the path to each file name.
        path = path.rstrip('/') + os.sep
        for index, f in enumerate(files):
            files[index] = path + f
    except NotADirectoryError:
        files = [path]
        path = ''
    except FileNotFoundError:
        print('Invalid path: {}.'.format(path))
        exit(1)

    words = getWords()
    for filename in files:
        # Get the filetype.
        if len(filename.split('.')) > 1:
            ext = '.' + filename.split('.')[-1]
        else:
            ext = ''
        os.rename(filename, path + makeUpName(filename, words) + ext)

if __name__ == '__main__':
    for arg in argv[1:]:
        renameFiles(arg, getWords())

<|endoftext|>


<commit_before># coding: utf-8

import mimetypes
import re

from bs4 import BeautifulSoup
import requests

from . import exceptions, settings, utils

simple_url_re = re.compile(r'^https?://\[?\w', re.IGNORECASE)

class Haul(object):
    """
    Haul
    """

    def __init__(self,
                 parser=settings.DEFAULT_PARSER,
                 finder_pipeline=settings.FINDER_PIPELINE,
                 extender_pipeline=settings.EXTENDER_PIPELINE):

        self.parser = parser
        self.finder_pipeline = finder_pipeline
        self.extender_pipeline = extender_pipeline

        self.response = None # via Requests
        self.soup = None # via BeautifulSoup

        self._result = None

    def __repr__(self):
        return '<Haul [parser: %s]>' % (self.parser)

    @property
    def result(self):
        if not isinstance(self._result, HaulResult):
            self._result = HaulResult()

        return self._result

    def retrieve_url(self, url):
        """
        Use requests to fetch remote content
        """

        try:
            r = requests.get(url)
        except requests.ConnectionError:
            raise exceptions.RetrieveError('Connection fail')

        if r.status_code >= 400:
            raise exceptions.RetrieveError('Connected, but status code is %s' % (r.status_code))

        real_url = r.url
        content = r.content

        try:
            content_type = r.headers['Content-Type']
        except KeyError:
            content_type, encoding = mimetypes.guess_type(real_url, strict=False)

        self.response = r

        return content_type.lower(), content

    def parse_html(self, html):
        """
        Use BeautifulSoup to parse HTML / XML
        http://www.crummy.com/software/BeautifulSoup/bs4/doc/#specifying-the-parser-to-use
        """

        soup = BeautifulSoup(html, self.parser)

        title_tag = soup.find('title')
        self.result.title = title_tag.string if title_tag else None

        self.soup = soup

        return soup

    def start_finder_pipeline(self, *args, **kwargs):
        pipeline_input = {
            'soup': self.soup,
        }
        pipeline_output = pipeline_input.copy()

        for idx, name in enumerate(self.finder_pipeline):
            pipeline_output['pipeline_index'] = idx
            pipeline_output['pipeline_break'] = False

            if hasattr(name, '__call__'):
                finder_func = name
            else:
                finder_func = utils.module_member(name)

            output = finder_func(*args, **pipeline_output)

            if isinstance(output, dict):
                pipeline_output.update(output)

            if pipeline_output['pipeline_break']:
                break

        # remove unnecessary items
        pipeline_output.pop('pipeline_index', None)
        pipeline_output.pop('pipeline_break', None)
        pipeline_output.pop('soup', None)

        self.result.finder_image_urls = pipeline_output.get('finder_image_urls', [])

        return self.result

    def start_extender_pipeline(self, *args, **kwargs):
        pipeline_input = {
            'finder_image_urls': self.result.finder_image_urls,
        }
        pipeline_output = pipeline_input.copy()

        for idx, name in enumerate(self.extender_pipeline):
            pipeline_output['pipeline_index'] = idx
            pipeline_output['pipeline_break'] = False

            if hasattr(name, '__call__'):
                extender_func = name
            else:
                extender_func = utils.module_member(name)

            output = extender_func(*args, **pipeline_output)

            if isinstance(output, dict):
                pipeline_output.update(output)

            if pipeline_output['pipeline_break']:
                break

        # remove unnecessary items
        pipeline_output.pop('pipeline_index', None)
        pipeline_output.pop('pipeline_break', None)
        pipeline_output.pop('finder_image_urls', None)

        self.result.extender_image_urls = pipeline_output.get('extender_image_urls', [])

        return self.result

    # API
    def find_images(self, url_or_html, extend=False):
        url = None
        content = None

        try:
            is_url = simple_url_re.match(url_or_html)
        except TypeError:
            raise exceptions.InvalidParameterError('Should be a URL or HTML text')

        if is_url:
            url = url_or_html
            content_type, content = self.retrieve_url(url)
        else:
            content_type = 'text/html'
            content = url_or_html

        self.result.url = url
        self.result.content_type = content_type

        if 'text/html' in content_type:
            self.parse_html(content)

            self.start_finder_pipeline()

            if extend:
                self.start_extender_pipeline()

        elif 'image/' in content_type:
            self.result.finder_image_urls = [str(self.response.url), ]

            if extend:
                self.start_extender_pipeline()

        else:
            raise exceptions.ContentTypeNotSupported(content_type)

        return self.result

class HaulResult(object):
    """
    Result of Haul
    """

    def __init__(self):
        self.content_type = None
        self.url = None
        self.title = None
        self.finder_image_urls = []
        self.extender_image_urls = []

    def __repr__(self):
        return '<HaulResult [Content-Type: %s]>' % (self.content_type)

    @property
    def image_urls(self):
        """
        Combine finder_image_urls and extender_image_urls,
        remove duplicate but keep order
        """

        all_image_urls = self.finder_image_urls[:]
        for image_url in self.extender_image_urls:
            if image_url not in all_image_urls:
                all_image_urls.append(image_url)

        return all_image_urls

    def to_dict(self):
        return self.__dict__
<commit_msg>add to_ordered_dict()<commit_after># coding: utf-8

from collections import OrderedDict
import mimetypes
import re

from bs4 import BeautifulSoup
import requests

from . import exceptions, settings, utils

simple_url_re = re.compile(r'^https?://\[?\w', re.IGNORECASE)

class Haul(object):
    """
    Haul
    """

    def __init__(self,
                 parser=settings.DEFAULT_PARSER,
                 finder_pipeline=settings.FINDER_PIPELINE,
                 extender_pipeline=settings.EXTENDER_PIPELINE):

        self.parser = parser
        self.finder_pipeline = finder_pipeline
        self.extender_pipeline = extender_pipeline

        self.response = None # via Requests
        self.soup = None # via BeautifulSoup

        self._result = None

    def __repr__(self):
        return '<Haul [parser: %s]>' % (self.parser)

    @property
    def result(self):
        if not isinstance(self._result, HaulResult):
            self._result = HaulResult()

        return self._result

    def retrieve_url(self, url):
        """
        Use requests to fetch remote content
        """

        try:
            r = requests.get(url)
        except requests.ConnectionError:
            raise exceptions.RetrieveError('Connection fail')

        if r.status_code >= 400:
            raise exceptions.RetrieveError('Connected, but status code is %s' % (r.status_code))

        real_url = r.url
        content = r.content

        try:
            content_type = r.headers['Content-Type']
        except KeyError:
            content_type, encoding = mimetypes.guess_type(real_url, strict=False)

        self.response = r

        return content_type.lower(), content

    def parse_html(self, html):
        """
        Use BeautifulSoup to parse HTML / XML
        http://www.crummy.com/software/BeautifulSoup/bs4/doc/#specifying-the-parser-to-use
        """

        soup = BeautifulSoup(html, self.parser)

        title_tag = soup.find('title')
        self.result.title = title_tag.string if title_tag else None

        self.soup = soup

        return soup

    def start_finder_pipeline(self, *args, **kwargs):
        pipeline_input = {
            'soup': self.soup,
        }
        pipeline_output = pipeline_input.copy()

        for idx, name in enumerate(self.finder_pipeline):
            pipeline_output['pipeline_index'] = idx
            pipeline_output['pipeline_break'] = False

            if hasattr(name, '__call__'):
                finder_func = name
            else:
                finder_func = utils.module_member(name)

            output = finder_func(*args, **pipeline_output)

            if isinstance(output, dict):
                pipeline_output.update(output)

            if pipeline_output['pipeline_break']:
                break

        # remove unnecessary items
        pipeline_output.pop('pipeline_index', None)
        pipeline_output.pop('pipeline_break', None)
        pipeline_output.pop('soup', None)

        self.result.finder_image_urls = pipeline_output.get('finder_image_urls', [])

        return self.result

    def start_extender_pipeline(self, *args, **kwargs):
        pipeline_input = {
            'finder_image_urls': self.result.finder_image_urls,
        }
        pipeline_output = pipeline_input.copy()

        for idx, name in enumerate(self.extender_pipeline):
            pipeline_output['pipeline_index'] = idx
            pipeline_output['pipeline_break'] = False

            if hasattr(name, '__call__'):
                extender_func = name
            else:
                extender_func = utils.module_member(name)

            output = extender_func(*args, **pipeline_output)

            if isinstance(output, dict):
                pipeline_output.update(output)

            if pipeline_output['pipeline_break']:
                break

        # remove unnecessary items
        pipeline_output.pop('pipeline_index', None)
        pipeline_output.pop('pipeline_break', None)
        pipeline_output.pop('finder_image_urls', None)

        self.result.extender_image_urls = pipeline_output.get('extender_image_urls', [])

        return self.result

    # API
    def find_images(self, url_or_html, extend=False):
        url = None
        content = None

        try:
            is_url = simple_url_re.match(url_or_html)
        except TypeError:
            raise exceptions.InvalidParameterError('Should be a URL or HTML text')

        if is_url:
            url = url_or_html
            content_type, content = self.retrieve_url(url)
        else:
            content_type = 'text/html'
            content = url_or_html

        self.result.url = url
        self.result.content_type = content_type

        if 'text/html' in content_type:
            self.parse_html(content)

            self.start_finder_pipeline()

            if extend:
                self.start_extender_pipeline()

        elif 'image/' in content_type:
            self.result.finder_image_urls = [str(self.response.url), ]

            if extend:
                self.start_extender_pipeline()

        else:
            raise exceptions.ContentTypeNotSupported(content_type)

        return self.result

class HaulResult(object):
    """
    Result of Haul
    """

    def __init__(self):
        self.url = None
        self.content_type = None
        self.title = None
        self.finder_image_urls = []
        self.extender_image_urls = []

    def __repr__(self):
        return '<HaulResult [Content-Type: %s]>' % (self.content_type)

    @property
    def image_urls(self):
        """
        Combine finder_image_urls and extender_image_urls,
        remove duplicate but keep order
        """

        all_image_urls = self.finder_image_urls[:]
        for image_url in self.extender_image_urls:
            if image_url not in all_image_urls:
                all_image_urls.append(image_url)

        return all_image_urls

    def to_dict(self):
        return self.__dict__

    def to_ordered_dict(self):
        order_keys = (
            'url',
            'content_type',
            'title',
            'finder_image_urls',
            'extender_image_urls',
        )

        d = OrderedDict()
        for key in order_keys:
            d[key] = getattr(self, key)

        return d
<|endoftext|>


<commit_before>import pygame
import os
from gi.repository import Gtk
from Button import Button
from Background import Background
from TextItem import TextItem

class Help(object):

    def __init__(self, main):
        self.main = main
        self.buttons = []
        self.background_image = os.path.join('assets', 'startscreen', 'night_sunset_gradient.png')
        self.background = Background(self.background_image)
        self.tut = pygame.image.load(os.path.join('assets', 'tutorial-images', 'tut1.jpg'))
        self.menuBtn = Button(500, 750, 200, 75, 'Menu')
        self.backBtn = Button(300, 650, 200,75, 'Back')
        self.nextBtn = Button(700, 650, 200, 75, 'Next')
        self.currentScreen = 1
        # Help screen buttons
        self.buttons.append(self.menuBtn)
        self.buttons.append(self.nextBtn)
        self.buttons.append(self.backBtn)

    def listenForEvents(self):
        if 1 in pygame.mouse.get_pressed():
            #Help state buttos
            for button in self.buttons:
                if button.is_under(pygame.mouse.get_pos()):
                    print 'You clicked the ' + button.text + ' button'
                    if button == self.menuBtn:
                        self.main.set_mode('menu')

    def renderScreen(self):
        self.background.draw(self.main.screen)
        self.main.screen.blit(self.tut, (self.main.hcenter - 400, 50))
        for button in self.buttons:
            if button != self.backBtn:
                button.draw(self.main.screen)

    def enter(self):
        print("entered help screen")<commit_msg>How to play screen is working...no error handling yet though<commit_after>import pygame
import os
from gi.repository import Gtk
from Button import Button
from Background import Background
from TextItem import TextItem

class Help(object):

    def __init__(self, main):
        self.main = main
        self.buttons = []
        self.background_image = os.path.join('assets', 'startscreen', 'night_sunset_gradient.png')
        self.background = Background(self.background_image)
        self.tutImage = Background('assets/tutorial-images/tut1.jpg',self.main.hcenter - 400, 50)
        self.menuBtn = Button(500, 750, 200, 75, 'Menu')
        self.backBtn = Button(300, 650, 200,75, 'Back')
        self.nextBtn = Button(700, 650, 200, 75, 'Next')
        self.currentScreen = 1
        # Help screen buttons
        self.buttons.append(self.menuBtn)
        self.buttons.append(self.nextBtn)
        self.buttons.append(self.backBtn)

    def listenForEvents(self):
        if 1 in pygame.mouse.get_pressed():
            #Help state buttos
            for button in self.buttons:
                if button.is_under(pygame.mouse.get_pos()):
                    print 'You clicked the ' + button.text + ' button'
                    if button == self.menuBtn:
                        self.main.set_mode('menu')
                    if button == self.nextBtn:
                        if self.currentScreen < 7:
                            self.currentScreen+=1
                            print(self.currentScreen)
                            filepath = 'assets/tutorial-images/tut'+str(self.currentScreen)+'.jpg'
                            print 'here'
                            self.tutImage.image = pygame.image.load(filepath)
                            self.tutImage.filename = filepath
                    elif button == self.backBtn:
                        self.currentScreen-=1
                        if self.currentScreen >= 1:
                            filepath = 'assets/tutorial-images/tut'+str(self.currentScreen)+'.jpg'
                            print 'here'
                            self.tutImage.image = pygame.image.load(filepath)
                            self.tutImage.filename = filepath

    def renderScreen(self):
        self.background.draw(self.main.screen)
        self.tutImage.draw(self.main.screen)
        for button in self.buttons:
            #if button != self.backBtn:
            button.draw(self.main.screen)

    def enter(self):
        print("entered help screen")<|endoftext|>


<commit_before># Copyright 2013 Google, Inc. All Rights Reserved.
#
# Google Author(s): Behdad Esfahbod

from fontTools.misc.py23 import *
from fontTools.misc.textTools import safeEval
from . import DefaultTable

class table_C_O_L_R_(DefaultTable.DefaultTable):

	""" This table is structured so that you can treat it like a dictionary keyed by glyph name.
	ttFont['COLR'][<glyphName>] will return the color layers for any glyph
	ttFont['COLR'][<glyphName>] = <value> will set the color layers for any glyph.
	"""

	def decompile(self, data, ttFont):
		from .otBase import OTTableReader
		from . import otTables

		reader = OTTableReader(data, tableTag=self.tableTag)
		tableClass = getattr(otTables, self.tableTag)
		table = tableClass()
		table.decompile(reader, ttFont)

		self.version = table.Version
		assert (self.version == 0), "Version of COLR table is higher than I know how to handle"

		self.ColorLayers = colorLayerLists = {}

		layerRecords = table.LayerRecordArray.LayerRecord
		numLayerRecords = len(layerRecords)
		for baseRec in table.BaseGlyphRecordArray.BaseGlyphRecord:
			baseGlyph = baseRec.BaseGlyph
			firstLayerIndex = baseRec.FirstLayerIndex
			numLayers = baseRec.NumLayers
			assert (firstLayerIndex + numLayers <= numLayerRecords)
			layers = []
			for i in range(firstLayerIndex, firstLayerIndex+numLayers):
				layerRec = layerRecords[i]
				layers.append(LayerRecord(layerRec.LayerGlyph, layerRec.PaletteIndex))
			colorLayerLists[baseGlyph] = layers

	def compile(self, ttFont):
		from .otBase import OTTableWriter
		from . import otTables

		ttFont.getReverseGlyphMap(rebuild=True)

		tableClass = getattr(otTables, self.tableTag)
		table = tableClass()

		table.Version = self.version

		table.BaseGlyphRecordArray = otTables.BaseGlyphRecordArray()
		table.BaseGlyphRecordArray.BaseGlyphRecord = baseGlyphRecords = []
		table.LayerRecordArray = otTables.LayerRecordArray()
		table.LayerRecordArray.LayerRecord = layerRecords = []

		for baseGlyph in sorted(self.ColorLayers.keys(), key=ttFont.getGlyphID):
			layers = self.ColorLayers[baseGlyph]

			baseRec = otTables.BaseGlyphRecord()
			baseRec.BaseGlyph = baseGlyph
			baseRec.FirstLayerIndex = len(layerRecords)
			baseRec.NumLayers = len(layers)
			baseGlyphRecords.append(baseRec)

			for layer in layers:
				layerRec = otTables.LayerRecord()
				layerRec.LayerGlyph = layer.name
				layerRec.PaletteIndex = layer.colorID
				layerRecords.append(layerRec)

		writer = OTTableWriter(tableTag=self.tableTag)
		table.compile(writer, ttFont)
		return writer.getAllData()

	def toXML(self, writer, ttFont):
		writer.simpletag("version", value=self.version)
		writer.newline()
		for baseGlyph in sorted(self.ColorLayers.keys(), key=ttFont.getGlyphID):
			writer.begintag("ColorGlyph", name=baseGlyph)
			writer.newline()
			for layer in self.ColorLayers[baseGlyph]:
				layer.toXML(writer, ttFont)
			writer.endtag("ColorGlyph")
			writer.newline()

	def fromXML(self, name, attrs, content, ttFont):
		if not hasattr(self, "ColorLayers"):
			self.ColorLayers = {}
		if name == "ColorGlyph":
			glyphName = attrs["name"]
			for element in content:
				if isinstance(element, basestring):
					continue
			layers = []
			for element in content:
				if isinstance(element, basestring):
					continue
				layer = LayerRecord()
				layer.fromXML(element[0], element[1], element[2], ttFont)
				layers.append (layer)
			self[glyphName] = layers
		elif "value" in attrs:
			setattr(self, name, safeEval(attrs["value"]))

	def __getitem__(self, glyphName):
		if not isinstance(glyphName, str):
			raise TypeError(f"expected str, found {type(glyphName).__name__}")
		return self.ColorLayers[glyphName]

	def __setitem__(self, glyphName, value):
		if not isinstance(glyphName, str):
			raise TypeError(f"expected str, found {type(glyphName).__name__}")
		if value is not None:
			self.ColorLayers[glyphName] = value
		elif glyphName in self.ColorLayers:
			del self.ColorLayers[glyphName]

	def __delitem__(self, glyphName):
		del self.ColorLayers[glyphName]

class LayerRecord(object):

	def __init__(self, name=None, colorID=None):
		self.name = name
		self.colorID = colorID

	def toXML(self, writer, ttFont):
		writer.simpletag("layer", name=self.name, colorID=self.colorID)
		writer.newline()

	def fromXML(self, eltname, attrs, content, ttFont):
		for (name, value) in attrs.items():
			if name == "name":
				if isinstance(value, int):
					value = ttFont.getGlyphName(value)
				setattr(self, name, value)
			else:
				setattr(self, name, safeEval(value))
<commit_msg>make ttLib.C_O_L_R_ a hybrid that keeps old API for v0, uses otTables for COLRv1<commit_after># Copyright 2013 Google, Inc. All Rights Reserved.
#
# Google Author(s): Behdad Esfahbod

from fontTools.misc.py23 import *
from fontTools.misc.textTools import safeEval
from . import DefaultTable

class table_C_O_L_R_(DefaultTable.DefaultTable):

	""" This table is structured so that you can treat it like a dictionary keyed by glyph name.
	ttFont['COLR'][<glyphName>] will return the color layers for any glyph
	ttFont['COLR'][<glyphName>] = <value> will set the color layers for any glyph.
	"""

	def _fromOTTable(self, table):
		self.version = 0
		self.ColorLayers = colorLayerLists = {}
		layerRecords = table.LayerRecordArray.LayerRecord
		numLayerRecords = len(layerRecords)
		for baseRec in table.BaseGlyphRecordArray.BaseGlyphRecord:
			baseGlyph = baseRec.BaseGlyph
			firstLayerIndex = baseRec.FirstLayerIndex
			numLayers = baseRec.NumLayers
			assert (firstLayerIndex + numLayers <= numLayerRecords)
			layers = []
			for i in range(firstLayerIndex, firstLayerIndex+numLayers):
				layerRec = layerRecords[i]
				layers.append(
					LayerRecord(layerRec.LayerGlyph, layerRec.PaletteIndex)
				)
			colorLayerLists[baseGlyph] = layers

	def _toOTTable(self, ttFont):
		from . import otTables
		from fontTools.colorLib.builder import populateCOLRv0

		tableClass = getattr(otTables, self.tableTag)
		table = tableClass()
		table.Version = self.version

		populateCOLRv0(
			table,
			{
				baseGlyph: [(layer.name, layer.colorID) for layer in layers]
				for baseGlyph, layers in self.ColorLayers.items()
			},
			glyphMap=ttFont.getReverseGlyphMap(rebuild=True),
		)
		return table

	def decompile(self, data, ttFont):
		from .otBase import OTTableReader
		from . import otTables

		# We use otData to decompile, but we adapt the decompiled otTables to the
		# existing COLR v0 API for backward compatibility.
		reader = OTTableReader(data, tableTag=self.tableTag)
		tableClass = getattr(otTables, self.tableTag)
		table = tableClass()
		table.decompile(reader, ttFont)

		if table.Version == 0:
			self._fromOTTable(table)
		else:
			# for new versions, keep the raw otTables around
			self.table = table

	def compile(self, ttFont):
		from .otBase import OTTableWriter

		if hasattr(self, "table"):
			table = self.table
		else:
			table = self._toOTTable(ttFont)

		writer = OTTableWriter(tableTag=self.tableTag)
		table.compile(writer, ttFont)
		return writer.getAllData()

	def toXML(self, writer, ttFont):
		if hasattr(self, "table"):
			self.table.toXML2(writer, ttFont)
		else:
			writer.simpletag("version", value=self.version)
			writer.newline()
			for baseGlyph in sorted(self.ColorLayers.keys(), key=ttFont.getGlyphID):
				writer.begintag("ColorGlyph", name=baseGlyph)
				writer.newline()
				for layer in self.ColorLayers[baseGlyph]:
					layer.toXML(writer, ttFont)
				writer.endtag("ColorGlyph")
				writer.newline()

	def fromXML(self, name, attrs, content, ttFont):
		if name == "version":  # old COLR v0 API
			setattr(self, name, safeEval(attrs["value"]))
		elif name == "ColorGlyph":
			if not hasattr(self, "ColorLayers"):
				self.ColorLayers = {}
			glyphName = attrs["name"]
			for element in content:
				if isinstance(element, basestring):
					continue
			layers = []
			for element in content:
				if isinstance(element, basestring):
					continue
				layer = LayerRecord()
				layer.fromXML(element[0], element[1], element[2], ttFont)
				layers.append (layer)
			self.ColorLayers[glyphName] = layers
		else:  # new COLR v1 API
			from . import otTables

			if not hasattr(self, "table"):
				tableClass = getattr(otTables, self.tableTag)
				self.table = tableClass()
			self.table.fromXML(name, attrs, content, ttFont)
			self.table.populateDefaults()

	def __getitem__(self, glyphName):
		if not isinstance(glyphName, str):
			raise TypeError(f"expected str, found {type(glyphName).__name__}")
		return self.ColorLayers[glyphName]

	def __setitem__(self, glyphName, value):
		if not isinstance(glyphName, str):
			raise TypeError(f"expected str, found {type(glyphName).__name__}")
		if value is not None:
			self.ColorLayers[glyphName] = value
		elif glyphName in self.ColorLayers:
			del self.ColorLayers[glyphName]

	def __delitem__(self, glyphName):
		del self.ColorLayers[glyphName]

class LayerRecord(object):

	def __init__(self, name=None, colorID=None):
		self.name = name
		self.colorID = colorID

	def toXML(self, writer, ttFont):
		writer.simpletag("layer", name=self.name, colorID=self.colorID)
		writer.newline()

	def fromXML(self, eltname, attrs, content, ttFont):
		for (name, value) in attrs.items():
			if name == "name":
				if isinstance(value, int):
					value = ttFont.getGlyphName(value)
				setattr(self, name, value)
			else:
				setattr(self, name, safeEval(value))
<|endoftext|>


<commit_before># Copyright 2013 Google, Inc. All Rights Reserved.
#
# Google Author(s): Behdad Esfahbod

from __future__ import print_function, division, absolute_import
from fontTools.misc.py23 import *
from fontTools.misc.textTools import safeEval
from . import DefaultTable
import operator
import struct

class table_C_O_L_R_(DefaultTable.DefaultTable):

	""" This table is structured so that you can treat it like a dictionary keyed by glyph name.
	ttFont['COLR'][<glyphName>] will return the color layers for any glyph
	ttFont['COLR'][<glyphName>] = <value> will set the color layers for any glyph.
	"""

	def decompile(self, data, ttFont):
		self.getGlyphName = ttFont.getGlyphName # for use in get/set item functions, for access by GID
		self.version, numBaseGlyphRecords, offsetBaseGlyphRecord, offsetLayerRecord, numLayerRecords = struct.unpack(">HHLLH", data[:14])
		assert (self.version == 0), "Version of COLR table is higher than I know how to handle"
		glyphOrder = ttFont.getGlyphOrder()
		gids = []
		layerLists = []
		glyphPos = offsetBaseGlyphRecord
		for i in range(numBaseGlyphRecords):
			gid, firstLayerIndex, numLayers = struct.unpack(">HHH", data[glyphPos:glyphPos+6])
			glyphPos += 6
			gids.append(gid)
			assert (firstLayerIndex + numLayers <= numLayerRecords)
			layerPos = offsetLayerRecord + firstLayerIndex * 4
			layers = []
			for j in range(numLayers):
				layerGid, colorID = struct.unpack(">HH", data[layerPos:layerPos+4])
				try:
					layerName = glyphOrder[layerGid]
				except IndexError:
					layerName = self.getGlyphName(layerGid)
				layerPos += 4
				layers.append(LayerRecord(layerName, colorID))
			layerLists.append(layers)

		self.ColorLayers = colorLayerLists = {}
		try:
			names = list(map(operator.getitem, [glyphOrder]*numBaseGlyphRecords, gids))
		except IndexError:
			getGlyphName = self.getGlyphName
			names = list(map(getGlyphName, gids ))

		list(map(operator.setitem, [colorLayerLists]*numBaseGlyphRecords, names, layerLists))

	def compile(self, ttFont):
		ordered = []
		ttFont.getReverseGlyphMap(rebuild=True)
		glyphNames = self.ColorLayers.keys()
		for glyphName in glyphNames:
			try:
				gid = ttFont.getGlyphID(glyphName)
			except:
				assert 0, "COLR table contains a glyph name not in ttFont.getGlyphNames(): " + str(glyphName)
			ordered.append([gid, glyphName, self.ColorLayers[glyphName]])
		ordered.sort()

		glyphMap = []
		layerMap = []
		for (gid, glyphName, layers) in ordered:
			glyphMap.append(struct.pack(">HHH", gid, len(layerMap), len(layers)))
			for layer in layers:
				layerMap.append(struct.pack(">HH", ttFont.getGlyphID(layer.name), layer.colorID))

		dataList = [struct.pack(">HHLLH", self.version, len(glyphMap), 14, 14+6*len(glyphMap), len(layerMap))]
		dataList.extend(glyphMap)
		dataList.extend(layerMap)
		data = bytesjoin(dataList)
		return data

	def toXML(self, writer, ttFont):
		writer.simpletag("version", value=self.version)
		writer.newline()
		ordered = []
		glyphNames = self.ColorLayers.keys()
		for glyphName in glyphNames:
			try:
				gid = ttFont.getGlyphID(glyphName)
			except:
				assert 0, "COLR table contains a glyph name not in ttFont.getGlyphNames(): " + str(glyphName)
			ordered.append([gid, glyphName, self.ColorLayers[glyphName]])
		ordered.sort()
		for entry in ordered:
			writer.begintag("ColorGlyph", name=entry[1])
			writer.newline()
			for layer in entry[2]:
				layer.toXML(writer, ttFont)
			writer.endtag("ColorGlyph")
			writer.newline()

	def fromXML(self, name, attrs, content, ttFont):
		if not hasattr(self, "ColorLayers"):
			self.ColorLayers = {}
		self.getGlyphName = ttFont.getGlyphName # for use in get/set item functions, for access by GID
		if name == "ColorGlyph":
			glyphName = attrs["name"]
			for element in content:
				if isinstance(element, basestring):
					continue
			layers = []
			for element in content:
				if isinstance(element, basestring):
					continue
				layer = LayerRecord()
				layer.fromXML(element[0], element[1], element[2], ttFont)
				layers.append (layer)
			operator.setitem(self, glyphName, layers)
		elif "value" in attrs:
			setattr(self, name, safeEval(attrs["value"]))

	def __getitem__(self, glyphSelector):
		if isinstance(glyphSelector, int):
			# its a gid, convert to glyph name
			glyphSelector = self.getGlyphName(glyphSelector)

		if glyphSelector not in self.ColorLayers:
			return None

		return self.ColorLayers[glyphSelector]

	def __setitem__(self, glyphSelector, value):
		if isinstance(glyphSelector, int):
			# its a gid, convert to glyph name
			glyphSelector = self.getGlyphName(glyphSelector)

		if  value:
			self.ColorLayers[glyphSelector] = value
		elif glyphSelector in self.ColorLayers:
			del self.ColorLayers[glyphSelector]

	def __delitem__(self, glyphSelector):
		del self.ColorLayers[glyphSelector]

class LayerRecord(object):

	def __init__(self, name=None, colorID=None):
		self.name = name
		self.colorID = colorID

	def toXML(self, writer, ttFont):
		writer.simpletag("layer", name=self.name, colorID=self.colorID)
		writer.newline()

	def fromXML(self, eltname, attrs, content, ttFont):
		for (name, value) in attrs.items():
			if name == "name":
				if isinstance(value, int):
					value = ttFont.getGlyphName(value)
				setattr(self, name, value)
			else:
				setattr(self, name, safeEval(value))
<commit_msg>removed unneeded use of operator.gititem and operator.setitem and replaced with idiomatic code<commit_after># Copyright 2013 Google, Inc. All Rights Reserved.
#
# Google Author(s): Behdad Esfahbod

from __future__ import print_function, division, absolute_import
from fontTools.misc.py23 import *
from fontTools.misc.textTools import safeEval
from . import DefaultTable
import struct

class table_C_O_L_R_(DefaultTable.DefaultTable):

	""" This table is structured so that you can treat it like a dictionary keyed by glyph name.
	ttFont['COLR'][<glyphName>] will return the color layers for any glyph
	ttFont['COLR'][<glyphName>] = <value> will set the color layers for any glyph.
	"""

	def decompile(self, data, ttFont):
		self.getGlyphName = ttFont.getGlyphName # for use in get/set item functions, for access by GID
		self.version, numBaseGlyphRecords, offsetBaseGlyphRecord, offsetLayerRecord, numLayerRecords = struct.unpack(">HHLLH", data[:14])
		assert (self.version == 0), "Version of COLR table is higher than I know how to handle"
		glyphOrder = ttFont.getGlyphOrder()
		gids = []
		layerLists = []
		glyphPos = offsetBaseGlyphRecord
		for i in range(numBaseGlyphRecords):
			gid, firstLayerIndex, numLayers = struct.unpack(">HHH", data[glyphPos:glyphPos+6])
			glyphPos += 6
			gids.append(gid)
			assert (firstLayerIndex + numLayers <= numLayerRecords)
			layerPos = offsetLayerRecord + firstLayerIndex * 4
			layers = []
			for j in range(numLayers):
				layerGid, colorID = struct.unpack(">HH", data[layerPos:layerPos+4])
				try:
					layerName = glyphOrder[layerGid]
				except IndexError:
					layerName = self.getGlyphName(layerGid)
				layerPos += 4
				layers.append(LayerRecord(layerName, colorID))
			layerLists.append(layers)

		self.ColorLayers = colorLayerLists = {}
		try:
			names = [glyphOrder[gid] for gid in gids]
		except IndexError:
			getGlyphName = self.getGlyphName
			names = map(getGlyphName, gids)

		for name, layerList in zip(names, layerLists):
			colorLayerLists[name] = layerList

	def compile(self, ttFont):
		ordered = []
		ttFont.getReverseGlyphMap(rebuild=True)
		glyphNames = self.ColorLayers.keys()
		for glyphName in glyphNames:
			try:
				gid = ttFont.getGlyphID(glyphName)
			except:
				assert 0, "COLR table contains a glyph name not in ttFont.getGlyphNames(): " + str(glyphName)
			ordered.append([gid, glyphName, self.ColorLayers[glyphName]])
		ordered.sort()

		glyphMap = []
		layerMap = []
		for (gid, glyphName, layers) in ordered:
			glyphMap.append(struct.pack(">HHH", gid, len(layerMap), len(layers)))
			for layer in layers:
				layerMap.append(struct.pack(">HH", ttFont.getGlyphID(layer.name), layer.colorID))

		dataList = [struct.pack(">HHLLH", self.version, len(glyphMap), 14, 14+6*len(glyphMap), len(layerMap))]
		dataList.extend(glyphMap)
		dataList.extend(layerMap)
		data = bytesjoin(dataList)
		return data

	def toXML(self, writer, ttFont):
		writer.simpletag("version", value=self.version)
		writer.newline()
		ordered = []
		glyphNames = self.ColorLayers.keys()
		for glyphName in glyphNames:
			try:
				gid = ttFont.getGlyphID(glyphName)
			except:
				assert 0, "COLR table contains a glyph name not in ttFont.getGlyphNames(): " + str(glyphName)
			ordered.append([gid, glyphName, self.ColorLayers[glyphName]])
		ordered.sort()
		for entry in ordered:
			writer.begintag("ColorGlyph", name=entry[1])
			writer.newline()
			for layer in entry[2]:
				layer.toXML(writer, ttFont)
			writer.endtag("ColorGlyph")
			writer.newline()

	def fromXML(self, name, attrs, content, ttFont):
		if not hasattr(self, "ColorLayers"):
			self.ColorLayers = {}
		self.getGlyphName = ttFont.getGlyphName # for use in get/set item functions, for access by GID
		if name == "ColorGlyph":
			glyphName = attrs["name"]
			for element in content:
				if isinstance(element, basestring):
					continue
			layers = []
			for element in content:
				if isinstance(element, basestring):
					continue
				layer = LayerRecord()
				layer.fromXML(element[0], element[1], element[2], ttFont)
				layers.append (layer)
			self[glyphName] = layers
		elif "value" in attrs:
			setattr(self, name, safeEval(attrs["value"]))

	def __getitem__(self, glyphSelector):
		if isinstance(glyphSelector, int):
			# its a gid, convert to glyph name
			glyphSelector = self.getGlyphName(glyphSelector)

		if glyphSelector not in self.ColorLayers:
			return None

		return self.ColorLayers[glyphSelector]

	def __setitem__(self, glyphSelector, value):
		if isinstance(glyphSelector, int):
			# its a gid, convert to glyph name
			glyphSelector = self.getGlyphName(glyphSelector)

		if  value:
			self.ColorLayers[glyphSelector] = value
		elif glyphSelector in self.ColorLayers:
			del self.ColorLayers[glyphSelector]

	def __delitem__(self, glyphSelector):
		del self.ColorLayers[glyphSelector]

class LayerRecord(object):

	def __init__(self, name=None, colorID=None):
		self.name = name
		self.colorID = colorID

	def toXML(self, writer, ttFont):
		writer.simpletag("layer", name=self.name, colorID=self.colorID)
		writer.newline()

	def fromXML(self, eltname, attrs, content, ttFont):
		for (name, value) in attrs.items():
			if name == "name":
				if isinstance(value, int):
					value = ttFont.getGlyphName(value)
				setattr(self, name, value)
			else:
				setattr(self, name, safeEval(value))
<|endoftext|>


<commit_before>import json
import os
import urllib
import urllib2

def GetLastRelease(httpaddress):
    httpstream = urllib2.urlopen(httpaddress)
    res = httpstream.read()
    res_json = json.loads(res)
    return res_json["tag_name"], res_json["zipball_url"]

def DownLoadLastRelease(version, zipurl):
    path = r'F:'
    file_name = version + r'.zip'
    dest_dir = os.path.join(path, file_name)
    #urllib.urlretrieve(zipurl, path + "/" + version + ".zip")
    f = urllib2.urlopen(zipurl)
    data = f.read()
    with open(path+"/"+version+".zip", "wb") as code:
        code.write(data)
    return path+"/"+version+".zip"

ves, zipUrl = GetLastRelease("https://api.github.com/repos/coolpy/coolpyV/releases/latest")
print ves, zipUrl
print DownLoadLastRelease(ves, zipUrl)
<commit_msg>revert version<commit_after>import commands
import json
import os
import re
import urllib
import urllib2

import subprocess
import zipfile

def GetLastRelease(httpaddress):
    httpstream = urllib2.urlopen(httpaddress)
    res = httpstream.read()
    res_json = json.loads(res)
    return res_json["tag_name"], res_json["zipball_url"]

def DownLoadLastRelease(version, zipurl):
    path = r'F:'
    file_name = version + r'.zip'
    dest_dir = os.path.join(path, file_name)
    #urllib.urlretrieve(zipurl, path + "/" + version + ".zip")
    f = urllib2.urlopen(zipurl)
    data = f.read()
    with open(path+"/"+version+".zip", "wb") as code:
        code.write(data)
    return path+"/"+version+".zip"

# ves, zipUrl = GetLastRelease("https://api.github.com/repos/jacoblai/Coolpy5Sub/releases/latest")
# print ves, zipUrl
# zippath = DownLoadLastRelease(ves, zipUrl)
# print zippath

zippath = "F:/5.0.1.0.zip"

os.chdir("F:/")
r = zipfile.is_zipfile(zippath)
first_dic = False
filename = ""
if r:
    fz = zipfile.ZipFile(zippath, 'r')
    for file in fz.namelist():
        if not first_dic:
            filename = file
            first_dic = True
        fz.extract(file, "/")
else:
    print('This file is not zip file')

print 'zip finish'

print filename

# for parent,dirnames,_ in os.walk("F:/"):
#     for dirname in dirnames:
#         print "parent is:" + parent
#         print "dirname is" + dirname

os.environ["GOPATH"]="F:/"+filename
#print os.environ["GOPATH"]
os.chdir("F:/"+filename)
#print os.getcwd()
#os.system("go build main.go")
#cmd = os.popen("go env")
#ss = cmd.read().decode('GB2312')
#print ss

#for i in cmd:
    #print i
#ss = cmd.readline().decode('GB2312')
child = subprocess.Popen('go build main.go',shell=False,stdout=subprocess.PIPE,stderr=subprocess.STDOUT)
returncode = child.poll()
info = child.stdout.read().decode('gb2312')
print "message:",info
res = re.findall("cannot find package \"(.*)\"", info)
print res

for pack in res:
    child = subprocess.Popen('go get ' + pack,shell=False,stdout=subprocess.PIPE,stderr=subprocess.STDOUT)
    returncode = child.poll()
    info = child.stdout.read().decode('gb2312')

#print (a)
#res = re.findall("\w", cmd)
#print res
#cmd = os.system("go build -o win32.exe main.go")
#print cmd
<|endoftext|>