repo_name
stringlengths 7
91
| path
stringlengths 8
658
| copies
stringclasses 125
values | size
stringlengths 3
6
| content
stringlengths 118
674k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6.09
99.2
| line_max
int64 17
995
| alpha_frac
float64 0.3
0.9
| ratio
float64 2
9.18
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ben-ng/swift | validation-test/compiler_crashers_fixed/27087-swift-declcontext-getlocalconformances.swift | 1 | 955 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
re g{ enum b = c("))
let a{}()
}class A {
a
B<T where g:b(")
class d>(_ = c{
import Foundation
func f.C{let:T? = [Void{
class A {
class d<f<T : {
init()
var b<T : T
if true{
T] {
init()
class A{
if tocol c(){
struct S <T.c
var a
struct Q<T where H:T.c()
class A : {enum b {
class B:P{
end " ( 1 ]
var a{
struct c(){
class B<C<d<d<d<T{}struct S< C {
func c(_ = F>()
struct A<
class C<T {
struct S< {
class B< g<T where T.e: {let v{{}
b{{
var b:T.c{ enum b<T{
let c{
var b(_ = 0
B
func f<T : T.c{ enum b = e
class A : a {
if true {}class B:P{
class C{
struct
| apache-2.0 | 453020381cbb9cf3a07652f2cecdc829 | 18.489796 | 79 | 0.640838 | 2.60929 | false | false | false | false |
JamieScanlon/AugmentKit | AugmentKit/Renderer/Render Modules/PrecalculationModule.swift | 1 | 35500 | //
// PrecalculationModule.swift
// AugmentKit
//
// MIT License
//
// Copyright (c) 2019 JamieScanlon
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
//
import ARKit
import AugmentKitShader
import Foundation
import MetalKit
class PrecalculationModule: PreRenderComputeModule {
weak var computePass: ComputePass<PrecalculatedParameters>?
var device: MTLDevice?
var frameCount: Int = 1
var moduleIdentifier: String {
return "PrecalculationModule"
}
var state: ShaderModuleState = .uninitialized
var renderLayer: Int {
return -3
}
var errors = [AKError]()
var renderDistance: Double = 500
var sharedModuleIdentifiers: [String]? = [SharedBuffersRenderModule.identifier]
func initializeBuffers(withDevice device: MTLDevice, maxInFlightFrames: Int, maxInstances: Int) {
state = .initializing
self.device = device
frameCount = maxInFlightFrames
instanceCount = maxInstances
alignedGeometryInstanceUniformsSize = ((MemoryLayout<AnchorInstanceUniforms>.stride * instanceCount) & ~0xFF) + 0x100
alignedEffectsUniformSize = ((MemoryLayout<AnchorEffectsUniforms>.stride * instanceCount) & ~0xFF) + 0x100
alignedEnvironmentUniformSize = ((MemoryLayout<EnvironmentUniforms>.stride * instanceCount) & ~0xFF) + 0x100
// Calculate our uniform buffer sizes. We allocate `maxInFlightFrames` instances for uniform
// storage in a single buffer. This allows us to update uniforms in a ring (i.e. triple
// buffer the uniforms) so that the GPU reads from one slot in the ring wil the CPU writes
// to another. Geometry uniforms should be specified with a max instance count for instancing.
// Also uniform storage must be aligned (to 256 bytes) to meet the requirements to be an
// argument in the constant address space of our shading functions.
let geometryUniformBufferSize = alignedGeometryInstanceUniformsSize * maxInFlightFrames
let jointTransformBufferSize = Constants.alignedJointTransform * Constants.maxJointCount * maxInFlightFrames
let effectsUniformBufferSize = alignedEffectsUniformSize * maxInFlightFrames
let environmentUniformBufferSize = alignedEnvironmentUniformSize * maxInFlightFrames
// Create and allocate our uniform buffer objects. Indicate shared storage so that both the
// CPU can access the buffer
geometryUniformBuffer = device.makeBuffer(length: geometryUniformBufferSize, options: .storageModeShared)
geometryUniformBuffer?.label = "Geometry Uniform Buffer"
jointTransformBuffer = device.makeBuffer(length: jointTransformBufferSize, options: [])
jointTransformBuffer?.label = "Joint Transform Buffer"
effectsUniformBuffer = device.makeBuffer(length: effectsUniformBufferSize, options: .storageModeShared)
effectsUniformBuffer?.label = "Effects Uniform Buffer"
environmentUniformBuffer = device.makeBuffer(length: environmentUniformBufferSize, options: .storageModeShared)
environmentUniformBuffer?.label = "Environment Uniform Buffer"
}
func loadPipeline(withMetalLibrary metalLibrary: MTLLibrary, renderDestination: RenderDestinationProvider, textureBundle: Bundle, forComputePass computePass: ComputePass<PrecalculatedParameters>?) -> ThreadGroup? {
guard let computePass = computePass else {
print("Warning (PrecalculationModule) - a ComputePass was not found. Aborting.")
let underlyingError = NSError(domain: AKErrorDomain, code: AKErrorCodeModelNotFound, userInfo: nil)
let newError = AKError.warning(.renderPipelineError(.failedToInitialize(PipelineErrorInfo(moduleIdentifier: moduleIdentifier, underlyingError: underlyingError))))
recordNewError(newError)
state = .ready
return nil
}
self.computePass = computePass
self.computePass?.functionName = "precalculationComputeShader"
self.computePass?.initializeBuffers(withDevice: device)
self.computePass?.loadPipeline(withMetalLibrary: metalLibrary, instanceCount: instanceCount, threadgroupDepth: 1)
state = .ready
return self.computePass?.threadGroup
}
func updateBufferState(withBufferIndex bufferIndex: Int) {
geometryUniformBufferOffset = alignedGeometryInstanceUniformsSize * bufferIndex
jointTransformBufferOffset = Constants.alignedJointTransform * Constants.maxJointCount * bufferIndex
effectsUniformBufferOffset = alignedEffectsUniformSize * bufferIndex
environmentUniformBufferOffset = alignedEnvironmentUniformSize * bufferIndex
geometryUniformBufferAddress = geometryUniformBuffer?.contents().advanced(by: geometryUniformBufferOffset)
jointTransformBufferAddress = jointTransformBuffer?.contents().advanced(by: jointTransformBufferOffset)
effectsUniformBufferAddress = effectsUniformBuffer?.contents().advanced(by: effectsUniformBufferOffset)
environmentUniformBufferAddress = environmentUniformBuffer?.contents().advanced(by: environmentUniformBufferOffset)
computePass?.updateBuffers(withFrameIndex: bufferIndex)
}
func prepareToDraw(withAllEntities allEntities: [AKEntity], cameraProperties: CameraProperties, environmentProperties: EnvironmentProperties, shadowProperties: ShadowProperties, computePass: ComputePass<PrecalculatedParameters>, renderPass: RenderPass?) {
var drawCallGroupOffset = 0
var drawCallGroupIndex = 0
let geometryUniforms = geometryUniformBufferAddress?.assumingMemoryBound(to: AnchorInstanceUniforms.self)
let environmentUniforms = environmentUniformBufferAddress?.assumingMemoryBound(to: EnvironmentUniforms.self)
let effectsUniforms = effectsUniformBufferAddress?.assumingMemoryBound(to: AnchorEffectsUniforms.self)
// Get all of the AKGeometricEntity's
var allGeometricEntities: [AKGeometricEntity] = allEntities.compactMap({
if let geoEntity = $0 as? AKGeometricEntity {
return geoEntity
} else {
return nil
}
})
let allGeometricEntityGroups: [AKGeometricEntityGroup] = allEntities.compactMap({
if let geoEntity = $0 as? AKGeometricEntityGroup {
return geoEntity
} else {
return nil
}
})
let groupGeometries = allGeometricEntityGroups.flatMap({$0.geometries})
allGeometricEntities.append(contentsOf: groupGeometries)
renderPass?.drawCallGroups.forEach { drawCallGroup in
let uuid = drawCallGroup.uuid
let geometricEntity = allGeometricEntities.first(where: {$0.identifier == uuid})
var drawCallIndex = 0
for drawCall in drawCallGroup.drawCalls {
//
// Environment Uniform Setup
//
if let environmentUniform = environmentUniforms?.advanced(by: drawCallGroupOffset + drawCallIndex), computePass.usesEnvironment {
// See if this anchor is associated with an environment anchor. An environment anchor applies to a region of space which may contain several anchors. The environment anchor that has the smallest volume is assumed to be more localized and therefore be the best for for this anchor
var environmentTexture: MTLTexture?
let environmentProbes: [AREnvironmentProbeAnchor] = environmentProperties.environmentAnchorsWithReatedAnchors.compactMap{
if $0.value.contains(uuid) {
return $0.key
} else {
return nil
}
}
if environmentProbes.count > 1 {
var bestEnvironmentProbe: AREnvironmentProbeAnchor?
environmentProbes.forEach {
if let theBestEnvironmentProbe = bestEnvironmentProbe {
let existingVolume = AKCube(position: AKVector(x: theBestEnvironmentProbe.transform.columns.3.x, y: theBestEnvironmentProbe.transform.columns.3.y, z: theBestEnvironmentProbe.transform.columns.3.z), extent: AKVector(theBestEnvironmentProbe.extent)).volume()
let newVolume = AKCube(position: AKVector(x: $0.transform.columns.3.x, y: $0.transform.columns.3.y, z: $0.transform.columns.3.z), extent: AKVector($0.extent)).volume()
if newVolume < existingVolume {
bestEnvironmentProbe = $0
}
} else {
bestEnvironmentProbe = $0
}
}
if let environmentProbeAnchor = bestEnvironmentProbe, let texture = environmentProbeAnchor.environmentTexture {
environmentTexture = texture
}
} else {
if let environmentProbeAnchor = environmentProbes.first, let texture = environmentProbeAnchor.environmentTexture {
environmentTexture = texture
}
}
let environmentData: EnvironmentData = {
var myEnvironmentData = EnvironmentData()
if let texture = environmentTexture {
myEnvironmentData.environmentTexture = texture
myEnvironmentData.hasEnvironmentMap = true
return myEnvironmentData
} else {
myEnvironmentData.hasEnvironmentMap = false
}
return myEnvironmentData
}()
// Set up lighting for the scene using the ambient intensity if provided
let ambientIntensity: Float = {
if let lightEstimate = environmentProperties.lightEstimate {
return Float(lightEstimate.ambientIntensity) / 1000.0
} else {
return 1
}
}()
let ambientLightColor: SIMD3<Float> = {
if let lightEstimate = environmentProperties.lightEstimate {
// FIXME: Remove
return getRGB(from: lightEstimate.ambientColorTemperature)
} else {
return SIMD3<Float>(0.5, 0.5, 0.5)
}
}()
environmentUniforms?.pointee.ambientLightIntensity = ambientIntensity
environmentUniform.pointee.ambientLightColor = ambientLightColor// * ambientIntensity
var directionalLightDirection : SIMD3<Float> = environmentProperties.directionalLightDirection
directionalLightDirection = simd_normalize(directionalLightDirection)
environmentUniform.pointee.directionalLightDirection = directionalLightDirection
let directionalLightColor: SIMD3<Float> = SIMD3<Float>(0.6, 0.6, 0.6)
environmentUniform.pointee.directionalLightColor = directionalLightColor// * ambientIntensity
environmentUniform.pointee.directionalLightMVP = environmentProperties.directionalLightMVP
environmentUniform.pointee.shadowMVPTransformMatrix = shadowProperties.shadowMVPTransformMatrix
if environmentData.hasEnvironmentMap == true {
environmentUniform.pointee.hasEnvironmentMap = 1
} else {
environmentUniform.pointee.hasEnvironmentMap = 0
}
}
//
// Effects Uniform Setup
//
if let effectsUniform = effectsUniforms?.advanced(by: drawCallGroupOffset + drawCallIndex), computePass.usesEnvironment {
var hasSetAlpha = false
var hasSetGlow = false
var hasSetTint = false
var hasSetScale = false
if let effects = geometricEntity?.effects {
let currentTime: TimeInterval = Double(cameraProperties.currentFrame) / cameraProperties.frameRate
for effect in effects {
switch effect.effectType {
case .alpha:
if let value = effect.value(forTime: currentTime) as? Float {
effectsUniform.pointee.alpha = value
hasSetAlpha = true
}
case .glow:
if let value = effect.value(forTime: currentTime) as? Float {
effectsUniform.pointee.glow = value
hasSetGlow = true
}
case .tint:
if let value = effect.value(forTime: currentTime) as? SIMD3<Float> {
effectsUniform.pointee.tint = value
hasSetTint = true
}
case .scale:
if let value = effect.value(forTime: currentTime) as? Float {
let scaleMatrix = matrix_identity_float4x4
effectsUniform.pointee.scale = scaleMatrix.scale(x: value, y: value, z: value)
hasSetScale = true
}
}
}
}
if !hasSetAlpha {
effectsUniform.pointee.alpha = 1
}
if !hasSetGlow {
effectsUniform.pointee.glow = 0
}
if !hasSetTint {
effectsUniform.pointee.tint = SIMD3<Float>(1,1,1)
}
if !hasSetScale {
effectsUniform.pointee.scale = matrix_identity_float4x4
}
}
//
// Geometry Uniform Setup
//
if let geometryUniform = geometryUniforms?.advanced(by: drawCallGroupOffset + drawCallIndex), computePass.usesGeometry {
guard let drawData = drawCall.drawData, drawCallIndex <= instanceCount else {
geometryUniform.pointee.hasGeometry = 0
drawCallIndex += 1
continue
}
// FIXME: - Let the compute shader do most of this
// Apply the world transform (as defined in the imported model) if applicable
let worldTransform: matrix_float4x4 = {
if let pathSegment = geometricEntity as? AKPathSegmentAnchor {
// For path segments, use the segmentTransform as the worldTransform
return pathSegment.segmentTransform
} else if drawData.worldTransformAnimations.count > 0 {
let index = Int(cameraProperties.currentFrame % UInt(drawData.worldTransformAnimations.count))
return drawData.worldTransformAnimations[index]
} else {
return drawData.worldTransform
}
}()
var hasHeading = false
var headingType: HeadingType = .absolute
var headingTransform = matrix_identity_float4x4
var locationTransform = matrix_identity_float4x4
if let akAnchor = geometricEntity as? AKAnchor {
// Update Heading
headingTransform = akAnchor.heading.offsetRotation.quaternion.toMatrix4()
hasHeading = true
headingType = akAnchor.heading.type
// Update postion
locationTransform = akAnchor.worldLocation.transform
} else if let akTarget = geometricEntity as? AKTarget {
// Apply the transform of the target relative to the reference transform
let targetAbsoluteTransform = akTarget.position.referenceTransform * akTarget.position.transform
locationTransform = targetAbsoluteTransform
} else if let akTracker = geometricEntity as? AKTracker {
if let heading = akTracker.position.heading {
// Update Heading
headingTransform = heading.offsetRotation.quaternion.toMatrix4()
hasHeading = true
headingType = heading.type
}
// Update position
// Apply the transform of the target relative to the reference transform
let trackerAbsoluteTransform = akTracker.position.referenceTransform * akTracker.position.transform
locationTransform = trackerAbsoluteTransform
}
// Ignore anchors that are beyond the renderDistance
let distance = anchorDistance(withTransform: locationTransform, cameraProperties: cameraProperties)
guard Double(distance) < renderDistance else {
geometryUniform.pointee.hasGeometry = 0
drawCallIndex += 1
continue
}
// Calculate LOD
let lodMapWeights = computeTextureWeights(for: distance)
geometryUniform.pointee.hasGeometry = 1
geometryUniform.pointee.hasHeading = hasHeading ? 1 : 0
geometryUniform.pointee.headingType = headingType == .absolute ? 0 : 1
geometryUniform.pointee.headingTransform = headingTransform
geometryUniform.pointee.worldTransform = worldTransform
geometryUniform.pointee.locationTransform = locationTransform
geometryUniform.pointee.mapWeights = lodMapWeights
}
drawCallIndex += 1
}
drawCallGroupOffset += drawCallGroup.drawCalls.count
drawCallGroupIndex += 1
}
}
func dispatch(withComputePass computePass: ComputePass<PrecalculatedParameters>?, sharedModules: [SharedRenderModule]?) {
guard let computePass = computePass else {
return
}
guard let computeEncoder = computePass.computeCommandEncoder else {
return
}
guard let threadGroup = computePass.threadGroup else {
return
}
computeEncoder.pushDebugGroup("Dispatch Precalculation")
computeEncoder.setBytes(&instanceCount, length: MemoryLayout<Int>.size, index: Int(kBufferIndexInstanceCount.rawValue))
if let sharedRenderModule = sharedModules?.first(where: {$0.moduleIdentifier == SharedBuffersRenderModule.identifier}), let sharedBuffer = sharedRenderModule.sharedUniformsBuffer?.buffer, let sharedBufferOffset = sharedRenderModule.sharedUniformsBuffer?.currentBufferFrameOffset, computePass.usesSharedBuffer {
computeEncoder.pushDebugGroup("Shared Uniforms")
computeEncoder.setBuffer(sharedBuffer, offset: sharedBufferOffset, index: sharedRenderModule.sharedUniformsBuffer?.shaderAttributeIndex ?? 0)
computeEncoder.popDebugGroup()
}
if let environmentUniformBuffer = environmentUniformBuffer, computePass.usesEnvironment {
computeEncoder.pushDebugGroup("Environment Uniforms")
computeEncoder.setBuffer(environmentUniformBuffer, offset: environmentUniformBufferOffset, index: Int(kBufferIndexEnvironmentUniforms.rawValue))
computeEncoder.popDebugGroup()
}
if let effectsBuffer = effectsUniformBuffer, computePass.usesEffects {
computeEncoder.pushDebugGroup("Effects Uniforms")
computeEncoder.setBuffer(effectsBuffer, offset: effectsUniformBufferOffset, index: Int(kBufferIndexAnchorEffectsUniforms.rawValue))
computeEncoder.popDebugGroup()
}
if computePass.usesGeometry {
computeEncoder.pushDebugGroup("Geometry Uniforms")
computeEncoder.setBuffer(geometryUniformBuffer, offset: geometryUniformBufferOffset, index: Int(kBufferIndexAnchorInstanceUniforms.rawValue))
computeEncoder.popDebugGroup()
if computePass.hasSkeleton {
computeEncoder.pushDebugGroup("Joint Transform Uniforms")
computeEncoder.setBuffer(jointTransformBuffer, offset: jointTransformBufferOffset, index: Int(kBufferIndexMeshJointTransforms.rawValue))
computeEncoder.popDebugGroup()
}
}
// Output Buffer
if let argumentOutputBuffer = computePass.outputBuffer?.buffer, let argumentOutputBufferOffset = computePass.outputBuffer?.currentBufferFrameOffset {
computeEncoder.pushDebugGroup("Output Buffer")
computeEncoder.setBuffer(argumentOutputBuffer, offset: argumentOutputBufferOffset, index: Int(kBufferIndexPrecalculationOutputBuffer.rawValue))
computeEncoder.popDebugGroup()
}
computePass.prepareThreadGroup()
// Requires the device supports non-uniform threadgroup sizes
computeEncoder.dispatchThreads(MTLSize(width: threadGroup.size.width, height: threadGroup.size.height, depth: threadGroup.size.depth), threadsPerThreadgroup: MTLSize(width: threadGroup.threadsPerGroup.width, height: threadGroup.threadsPerGroup.height, depth: 1))
computeEncoder.popDebugGroup()
}
func frameEncodingComplete(renderPasses: [RenderPass]) {
//
}
func recordNewError(_ akError: AKError) {
errors.append(akError)
}
// MARK: - Private
fileprivate enum Constants {
static let maxJointCount = 100
static let alignedJointTransform = (MemoryLayout<matrix_float4x4>.stride & ~0xFF) + 0x100
}
fileprivate var instanceCount: Int = 0
fileprivate var alignedGeometryInstanceUniformsSize: Int = 0
fileprivate var alignedEffectsUniformSize: Int = 0
fileprivate var alignedEnvironmentUniformSize: Int = 0
fileprivate var geometryUniformBuffer: MTLBuffer?
fileprivate var jointTransformBuffer: MTLBuffer?
fileprivate var effectsUniformBuffer: MTLBuffer?
fileprivate var environmentUniformBuffer: MTLBuffer?
// Offset within geometryUniformBuffer to set for the current frame
fileprivate var geometryUniformBufferOffset: Int = 0
// Offset within jointTransformBuffer to set for the current frame
fileprivate var jointTransformBufferOffset = 0
// Offset within effectsUniformBuffer to set for the current frame
fileprivate var effectsUniformBufferOffset: Int = 0
// Offset within environmentUniformBuffer to set for the current frame
fileprivate var environmentUniformBufferOffset: Int = 0
// Addresses to write geometry uniforms to each frame
fileprivate var geometryUniformBufferAddress: UnsafeMutableRawPointer?
// Addresses to write jointTransform to each frame
fileprivate var jointTransformBufferAddress: UnsafeMutableRawPointer?
// Addresses to write effects uniforms to each frame
fileprivate var effectsUniformBufferAddress: UnsafeMutableRawPointer?
// Addresses to write environment uniforms to each frame
fileprivate var environmentUniformBufferAddress: UnsafeMutableRawPointer?
// FIXME: Remove - put in compute shader
fileprivate func anchorDistance(withTransform transform: matrix_float4x4, cameraProperties: CameraProperties?) -> Float {
guard let cameraProperties = cameraProperties else {
return 0
}
let point = SIMD3<Float>(transform.columns.3.x, transform.columns.3.x, transform.columns.3.z)
return length(point - cameraProperties.position)
}
fileprivate func computeTextureWeights(for distance: Float) -> (Float, Float, Float, Float, Float, Float, Float, Float, Float, Float, Float, Float, Float, Float) {
guard AKCapabilities.LevelOfDetail else {
return (Float(1), Float(1), Float(1), Float(1), Float(1), Float(1), Float(1), Float(1), Float(1), Float(1), Float(1), Float(1), Float(1), Float(1))
}
let quality = RenderUtilities.getQualityLevel(for: distance)
// Escape hatch for performance. If the quality is low, exit with all 0 values
guard quality.rawValue < 2 else {
return (Float(0), Float(0), Float(0), Float(0), Float(0), Float(0), Float(0), Float(0), Float(0), Float(0), Float(0), Float(0), Float(0), Float(0))
}
var baseMapWeight: Float = 1
var normalMapWeight: Float = 1
var metallicMapWeight: Float = 1
var roughnessMapWeight: Float = 1
var ambientOcclusionMapWeight: Float = 1
var emissionMapWeight: Float = 1
var subsurfaceMapWeight: Float = 1
var specularMapWeight: Float = 1
var specularTintMapWeight: Float = 1
var anisotropicMapWeight: Float = 1
var sheenMapWeight: Float = 1
var sheenTintMapWeight: Float = 1
var clearcoatMapWeight: Float = 1
var clearcoatMapWeightGlossMapWeight: Float = 1
let nextLevel: QualityLevel = {
if quality == kQualityLevelHigh {
return kQualityLevelMedium
} else {
return kQualityLevelLow
}
}()
let mapWeight = getMapWeight(for: quality, distance: distance)
if !RenderUtilities.hasTexture(for: kTextureIndexColor, qualityLevel: quality) {
baseMapWeight = 0
} else if RenderUtilities.hasTexture(for: kTextureIndexColor, qualityLevel: quality) && !RenderUtilities.hasTexture(for: kTextureIndexColor, qualityLevel: nextLevel) {
baseMapWeight = mapWeight
}
if !RenderUtilities.hasTexture(for: kTextureIndexNormal, qualityLevel: quality) {
normalMapWeight = 0
} else if RenderUtilities.hasTexture(for: kTextureIndexNormal, qualityLevel: quality) && !RenderUtilities.hasTexture(for: kTextureIndexNormal, qualityLevel: nextLevel) {
normalMapWeight = mapWeight
}
if !RenderUtilities.hasTexture(for: kTextureIndexMetallic, qualityLevel: quality) {
metallicMapWeight = 0
} else if RenderUtilities.hasTexture(for: kTextureIndexMetallic, qualityLevel: quality) && !RenderUtilities.hasTexture(for: kTextureIndexMetallic, qualityLevel: nextLevel) {
metallicMapWeight = mapWeight
}
if !RenderUtilities.hasTexture(for: kTextureIndexRoughness, qualityLevel: quality) {
roughnessMapWeight = 0
} else if RenderUtilities.hasTexture(for: kTextureIndexRoughness, qualityLevel: quality) && !RenderUtilities.hasTexture(for: kTextureIndexRoughness, qualityLevel: nextLevel) {
roughnessMapWeight = mapWeight
}
if !RenderUtilities.hasTexture(for: kTextureIndexAmbientOcclusion, qualityLevel: quality) {
ambientOcclusionMapWeight = 0
} else if RenderUtilities.hasTexture(for: kTextureIndexAmbientOcclusion, qualityLevel: quality) && !RenderUtilities.hasTexture(for: kTextureIndexAmbientOcclusion, qualityLevel: nextLevel) {
ambientOcclusionMapWeight = mapWeight
}
if !RenderUtilities.hasTexture(for: kTextureIndexEmissionMap, qualityLevel: quality) {
emissionMapWeight = 0
} else if RenderUtilities.hasTexture(for: kTextureIndexEmissionMap, qualityLevel: quality) && !RenderUtilities.hasTexture(for: kTextureIndexEmissionMap, qualityLevel: nextLevel) {
emissionMapWeight = mapWeight
}
if !RenderUtilities.hasTexture(for: kTextureIndexSubsurfaceMap, qualityLevel: quality) {
subsurfaceMapWeight = 0
} else if RenderUtilities.hasTexture(for: kTextureIndexSubsurfaceMap, qualityLevel: quality) && !RenderUtilities.hasTexture(for: kTextureIndexSubsurfaceMap, qualityLevel: nextLevel) {
subsurfaceMapWeight = mapWeight
}
if !RenderUtilities.hasTexture(for: kTextureIndexSpecularMap, qualityLevel: quality) {
specularMapWeight = 0
} else if RenderUtilities.hasTexture(for: kTextureIndexSpecularMap, qualityLevel: quality) && !RenderUtilities.hasTexture(for: kTextureIndexSpecularMap, qualityLevel: nextLevel) {
specularMapWeight = mapWeight
}
if !RenderUtilities.hasTexture(for: kTextureIndexSpecularTintMap, qualityLevel: quality) {
specularTintMapWeight = 0
} else if RenderUtilities.hasTexture(for: kTextureIndexSpecularTintMap, qualityLevel: quality) && !RenderUtilities.hasTexture(for: kTextureIndexSpecularTintMap, qualityLevel: nextLevel) {
specularTintMapWeight = mapWeight
}
if !RenderUtilities.hasTexture(for: kTextureIndexAnisotropicMap, qualityLevel: quality) {
anisotropicMapWeight = 0
} else if RenderUtilities.hasTexture(for: kTextureIndexAnisotropicMap, qualityLevel: quality) && !RenderUtilities.hasTexture(for: kTextureIndexAnisotropicMap, qualityLevel: nextLevel) {
anisotropicMapWeight = mapWeight
}
if !RenderUtilities.hasTexture(for: kTextureIndexSheenMap, qualityLevel: quality) {
sheenMapWeight = 0
} else if RenderUtilities.hasTexture(for: kTextureIndexSheenMap, qualityLevel: quality) && !RenderUtilities.hasTexture(for: kTextureIndexSheenMap, qualityLevel: nextLevel) {
sheenMapWeight = mapWeight
}
if !RenderUtilities.hasTexture(for: kTextureIndexSheenTintMap, qualityLevel: quality) {
sheenTintMapWeight = 0
} else if RenderUtilities.hasTexture(for: kTextureIndexSheenTintMap, qualityLevel: quality) && !RenderUtilities.hasTexture(for: kTextureIndexSheenTintMap, qualityLevel: nextLevel) {
sheenTintMapWeight = mapWeight
}
if !RenderUtilities.hasTexture(for: kTextureIndexClearcoatMap, qualityLevel: quality) {
clearcoatMapWeight = 0
} else if RenderUtilities.hasTexture(for: kTextureIndexClearcoatMap, qualityLevel: quality) && !RenderUtilities.hasTexture(for: kTextureIndexClearcoatMap, qualityLevel: nextLevel) {
clearcoatMapWeight = mapWeight
}
if !RenderUtilities.hasTexture(for: kTextureIndexClearcoatGlossMap, qualityLevel: quality) {
clearcoatMapWeightGlossMapWeight = 0
} else if RenderUtilities.hasTexture(for: kTextureIndexClearcoatGlossMap, qualityLevel: quality) && !RenderUtilities.hasTexture(for: kTextureIndexClearcoatGlossMap, qualityLevel: nextLevel) {
clearcoatMapWeightGlossMapWeight = mapWeight
}
return (baseMapWeight, normalMapWeight, metallicMapWeight, roughnessMapWeight, ambientOcclusionMapWeight, emissionMapWeight, subsurfaceMapWeight, specularMapWeight, specularTintMapWeight, anisotropicMapWeight, sheenMapWeight, sheenTintMapWeight, clearcoatMapWeight, clearcoatMapWeightGlossMapWeight)
}
fileprivate func getMapWeight(for level: QualityLevel, distance: Float) -> Float {
guard AKCapabilities.LevelOfDetail else {
return 1
}
guard distance > 0 else {
return 1
}
// In meters
let MediumQualityDepth: Float = 15
let LowQualityDepth: Float = 65
let TransitionDepthAmount: Float = 50
if level == kQualityLevelHigh {
let TransitionDepth = MediumQualityDepth - TransitionDepthAmount
if distance > TransitionDepth {
return 1 - ((distance - TransitionDepth) / TransitionDepthAmount)
} else {
return 1
}
} else if level == kQualityLevelMedium {
let TransitionDepth = LowQualityDepth - TransitionDepthAmount
if distance > TransitionDepth {
return 1 - ((distance - TransitionDepth) / TransitionDepthAmount)
} else {
return 1
}
} else {
return 0
}
}
}
| mit | 4888cfd9f2252334b5b8be1ab6a77eb2 | 51.437223 | 318 | 0.616113 | 5.634921 | false | false | false | false |
debugsquad/nubecero | nubecero/View/Store/VStoreHeader.swift | 1 | 4362 | import UIKit
class VStoreHeader:UICollectionReusableView
{
private let attrTitle:[String:Any]
private let attrDescr:[String:Any]
private let labelMargins:CGFloat
private weak var label:UILabel!
private weak var imageView:UIImageView!
private weak var layoutLabelHeight:NSLayoutConstraint!
private let kLabelMarginHorizontal:CGFloat = 20
private let kImageViewSize:CGFloat = 100
override init(frame:CGRect)
{
attrTitle = [
NSFontAttributeName:UIFont.medium(size:18),
NSForegroundColorAttributeName:UIColor.main
]
attrDescr = [
NSFontAttributeName:UIFont.regular(size:18),
NSForegroundColorAttributeName:UIColor.black
]
labelMargins = kLabelMarginHorizontal + kImageViewSize
super.init(frame:frame)
clipsToBounds = true
backgroundColor = UIColor.white
let label:UILabel = UILabel()
label.isUserInteractionEnabled = false
label.backgroundColor = UIColor.clear
label.translatesAutoresizingMaskIntoConstraints = false
label.numberOfLines = 0
self.label = label
let imageView:UIImageView = UIImageView()
imageView.isUserInteractionEnabled = false
imageView.clipsToBounds = true
imageView.contentMode = UIViewContentMode.center
imageView.translatesAutoresizingMaskIntoConstraints = false
self.imageView = imageView
addSubview(label)
addSubview(imageView)
let views:[String:UIView] = [
"label":label,
"imageView":imageView]
let metrics:[String:CGFloat] = [
"labelMarginHorizontal":kLabelMarginHorizontal,
"imageViewSize":kImageViewSize]
addConstraints(NSLayoutConstraint.constraints(
withVisualFormat:"H:|-0-[imageView(imageViewSize)]-0-[label]-(labelMarginHorizontal)-|",
options:[],
metrics:metrics,
views:views))
addConstraints(NSLayoutConstraint.constraints(
withVisualFormat:"V:|-22-[label]",
options:[],
metrics:metrics,
views:views))
addConstraints(NSLayoutConstraint.constraints(
withVisualFormat:"V:|-0-[imageView(imageViewSize)]",
options:[],
metrics:metrics,
views:views))
layoutLabelHeight = NSLayoutConstraint(
item:label,
attribute:NSLayoutAttribute.height,
relatedBy:NSLayoutRelation.equal,
toItem:nil,
attribute:NSLayoutAttribute.notAnAttribute,
multiplier:1,
constant:0)
addConstraint(layoutLabelHeight)
}
required init?(coder:NSCoder)
{
fatalError()
}
override func layoutSubviews()
{
guard
let attributedText:NSAttributedString = label.attributedText
else
{
return
}
let width:CGFloat = bounds.maxX
let height:CGFloat = bounds.maxY
let usableWidth:CGFloat = width - labelMargins
let usableSize:CGSize = CGSize(width:usableWidth, height:height)
let boundingRect:CGRect = attributedText.boundingRect(
with:usableSize,
options:NSStringDrawingOptions([
NSStringDrawingOptions.usesLineFragmentOrigin,
NSStringDrawingOptions.usesFontLeading
]),
context:nil)
layoutLabelHeight.constant = ceil(boundingRect.size.height)
super.layoutSubviews()
}
//MARK: public
func config(model:MStoreItem)
{
let mutableString:NSMutableAttributedString = NSMutableAttributedString()
let stringTitle:NSAttributedString = NSAttributedString(
string:model.title,
attributes:attrTitle)
let stringDescr:NSAttributedString = NSAttributedString(
string:model.descr,
attributes:attrDescr)
mutableString.append(stringTitle)
mutableString.append(stringDescr)
label.attributedText = mutableString
imageView.image = model.image
setNeedsLayout()
}
}
| mit | 67399e3a4add41c80b147425840bf8b0 | 31.073529 | 100 | 0.613709 | 6.135021 | false | false | false | false |
jianwoo/ios-charts | Charts/Classes/Renderers/CandleStickChartRenderer.swift | 1 | 10397 | //
// CandleStickChartRenderer.swift
// Charts
//
// Created by Daniel Cohen Gindi on 4/3/15.
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/ios-charts
//
import Foundation
@objc
public protocol CandleStickChartRendererDelegate
{
func candleStickChartRendererCandleData(renderer: CandleStickChartRenderer) -> CandleChartData!;
func candleStickChartRenderer(renderer: CandleStickChartRenderer, transformerForAxis which: ChartYAxis.AxisDependency) -> ChartTransformer!;
func candleStickChartDefaultRendererValueFormatter(renderer: CandleStickChartRenderer) -> NSNumberFormatter!;
func candleStickChartRendererChartYMax(renderer: CandleStickChartRenderer) -> Float;
func candleStickChartRendererChartYMin(renderer: CandleStickChartRenderer) -> Float;
func candleStickChartRendererChartXMax(renderer: CandleStickChartRenderer) -> Float;
func candleStickChartRendererChartXMin(renderer: CandleStickChartRenderer) -> Float;
func candleStickChartRendererMaxVisibleValueCount(renderer: CandleStickChartRenderer) -> Int;
}
public class CandleStickChartRenderer: ChartDataRendererBase
{
public weak var delegate: CandleStickChartRendererDelegate?;
public init(delegate: CandleStickChartRendererDelegate?, animator: ChartAnimator?, viewPortHandler: ChartViewPortHandler)
{
super.init(animator: animator, viewPortHandler: viewPortHandler);
self.delegate = delegate;
}
public override func drawData(#context: CGContext)
{
var candleData = delegate!.candleStickChartRendererCandleData(self);
for set in candleData.dataSets as! [CandleChartDataSet]
{
if (set.isVisible)
{
drawDataSet(context: context, dataSet: set);
}
}
}
private var _shadowPoints = [CGPoint](count: 2, repeatedValue: CGPoint());
private var _bodyRect = CGRect();
private var _lineSegments = [CGPoint](count: 2, repeatedValue: CGPoint());
internal func drawDataSet(#context: CGContext, dataSet: CandleChartDataSet)
{
var candleData = delegate!.candleStickChartRendererCandleData(self);
var trans = delegate!.candleStickChartRenderer(self, transformerForAxis: dataSet.axisDependency);
calcXBounds(trans);
var phaseX = _animator.phaseX;
var phaseY = _animator.phaseY;
var bodySpace = dataSet.bodySpace;
var dataSetIndex = candleData.indexOfDataSet(dataSet);
var entries = dataSet.yVals as! [CandleChartDataEntry];
CGContextSaveGState(context);
CGContextSetLineWidth(context, dataSet.shadowWidth);
for (var j = 0, count = Int(ceil(CGFloat(entries.count) * _animator.phaseX)); j < count; j++)
{
// get the color that is specified for this position from the DataSet, this will reuse colors, if the index is out of bounds
CGContextSetFillColorWithColor(context, dataSet.colorAt(j).CGColor);
CGContextSetStrokeColorWithColor(context, dataSet.colorAt(j).CGColor);
// get the entry
var e = entries[j];
if (e.xIndex < _minX || e.xIndex > _maxX)
{
continue;
}
// calculate the shadow
_shadowPoints[0].x = CGFloat(e.xIndex);
_shadowPoints[0].y = CGFloat(e.high) * phaseY;
_shadowPoints[1].x = CGFloat(e.xIndex);
_shadowPoints[1].y = CGFloat(e.low) * phaseY;
trans.pointValuesToPixel(&_shadowPoints);
// draw the shadow
CGContextStrokeLineSegments(context, _shadowPoints, 2);
// calculate the body
_bodyRect.origin.x = CGFloat(e.xIndex) - 0.5 + bodySpace;
_bodyRect.origin.y = CGFloat(e.close) * phaseY;
_bodyRect.size.width = (CGFloat(e.xIndex) + 0.5 - bodySpace) - _bodyRect.origin.x;
_bodyRect.size.height = (CGFloat(e.open) * phaseY) - _bodyRect.origin.y;
trans.rectValueToPixel(&_bodyRect);
// decide whether the body is hollow or filled
if (_bodyRect.size.height > 0.0)
{
// draw the body
CGContextFillRect(context, _bodyRect);
}
else
{
// draw the body
CGContextStrokeRect(context, _bodyRect);
}
}
CGContextRestoreGState(context);
}
public override func drawValues(#context: CGContext)
{
var candleData = delegate!.candleStickChartRendererCandleData(self);
if (candleData === nil)
{
return;
}
var defaultValueFormatter = delegate!.candleStickChartDefaultRendererValueFormatter(self);
// if values are drawn
if (candleData.yValCount < Int(ceil(CGFloat(delegate!.candleStickChartRendererMaxVisibleValueCount(self)) * viewPortHandler.scaleX)))
{
var dataSets = candleData.dataSets;
for (var i = 0; i < dataSets.count; i++)
{
var dataSet = dataSets[i];
if (!dataSet.isDrawValuesEnabled)
{
continue;
}
var valueFont = dataSet.valueFont;
var valueTextColor = dataSet.valueTextColor;
var formatter = dataSet.valueFormatter;
if (formatter === nil)
{
formatter = defaultValueFormatter;
}
var trans = delegate!.candleStickChartRenderer(self, transformerForAxis: dataSet.axisDependency);
var entries = dataSet.yVals as! [CandleChartDataEntry];
var positions = trans.generateTransformedValuesCandle(entries, phaseY: _animator.phaseY);
var lineHeight = valueFont.lineHeight;
var yOffset: CGFloat = lineHeight + 5.0;
for (var j = 0, count = Int(ceil(CGFloat(positions.count) * _animator.phaseX)); j < count; j++)
{
var x = positions[j].x;
var y = positions[j].y;
if (!viewPortHandler.isInBoundsRight(x))
{
break;
}
if (!viewPortHandler.isInBoundsLeft(x) || !viewPortHandler.isInBoundsY(y))
{
continue;
}
var val = entries[j].high;
ChartUtils.drawText(context: context, text: formatter!.stringFromNumber(val)!, point: CGPoint(x: x, y: y - yOffset), align: .Center, attributes: [NSFontAttributeName: valueFont, NSForegroundColorAttributeName: valueTextColor]);
}
}
}
}
public override func drawExtras(#context: CGContext)
{
}
private var _vertPtsBuffer = [CGPoint](count: 4, repeatedValue: CGPoint());
private var _horzPtsBuffer = [CGPoint](count: 4, repeatedValue: CGPoint());
public override func drawHighlighted(#context: CGContext, indices: [ChartHighlight])
{
var candleData = delegate!.candleStickChartRendererCandleData(self);
if (candleData === nil)
{
return;
}
for (var i = 0; i < indices.count; i++)
{
var xIndex = indices[i].xIndex; // get the x-position
var set = candleData.getDataSetByIndex(indices[i].dataSetIndex) as! CandleChartDataSet!;
if (set === nil)
{
continue;
}
var e = set.entryForXIndex(xIndex) as! CandleChartDataEntry!;
if (e === nil)
{
continue;
}
var trans = delegate!.candleStickChartRenderer(self, transformerForAxis: set.axisDependency);
CGContextSetStrokeColorWithColor(context, set.highlightColor.CGColor);
CGContextSetLineWidth(context, set.highlightLineWidth);
if (set.highlightLineDashLengths != nil)
{
CGContextSetLineDash(context, set.highlightLineDashPhase, set.highlightLineDashLengths!, set.highlightLineDashLengths!.count);
}
else
{
CGContextSetLineDash(context, 0.0, nil, 0);
}
var low = CGFloat(e.low) * _animator.phaseY;
var high = CGFloat(e.high) * _animator.phaseY;
var min = delegate!.candleStickChartRendererChartYMin(self);
var max = delegate!.candleStickChartRendererChartYMax(self);
_vertPtsBuffer[0] = CGPoint(x: CGFloat(xIndex) - 0.5, y: CGFloat(max));
_vertPtsBuffer[1] = CGPoint(x: CGFloat(xIndex) - 0.5, y: CGFloat(min));
_vertPtsBuffer[2] = CGPoint(x: CGFloat(xIndex) + 0.5, y: CGFloat(max));
_vertPtsBuffer[3] = CGPoint(x: CGFloat(xIndex) + 0.5, y: CGFloat(min));
_horzPtsBuffer[0] = CGPoint(x: CGFloat(0.0), y: low);
_horzPtsBuffer[1] = CGPoint(x: CGFloat(delegate!.candleStickChartRendererChartXMax(self)), y: low);
_horzPtsBuffer[2] = CGPoint(x: 0.0, y: high);
_horzPtsBuffer[3] = CGPoint(x: CGFloat(delegate!.candleStickChartRendererChartXMax(self)), y: high);
trans.pointValuesToPixel(&_vertPtsBuffer);
trans.pointValuesToPixel(&_horzPtsBuffer);
// draw the vertical highlight lines
CGContextStrokeLineSegments(context, _vertPtsBuffer, 4);
// draw the horizontal highlight lines
CGContextStrokeLineSegments(context, _horzPtsBuffer, 4);
}
}
} | apache-2.0 | 51a9f208fa86de1a0fdb49d1b3897c31 | 38.386364 | 247 | 0.570645 | 5.498149 | false | false | false | false |
xmartlabs/Bender | Sources/Adapters/Tensorflow/TFVariableProcessor.swift | 1 | 2677 | //
// TFVariableProcessor.swift
// Bender
//
// Created by Mathias Claassen on 5/18/17.
//
//
/// Processes `Variable` nodes / groups from TensorFlow.
public class TFVariableProcessor: TFOptimizer {
/* Takes
Const --> Assign Output
^ ^
VariableV2 --> Read
Returns
Const --> VariableV2 --> Output
*/
public func optimize(graph: TFGraph) {
for node in graph.nodes {
if node.nodeDef.isTFVariableV2Op {
if let assign = node.outgoingNodes().filter({ ($0 as? TFNode)?.nodeDef.isTFVariableAssignOp ?? false }).first,
let read = node.outgoingNodes().filter({ ($0 as? TFNode)?.nodeDef.name.isTFVariableReadName ?? false }).first,
let outputNode = read.outgoingNodes().first {
read.strip()
if let constValue = assign.incomingNodes().filter({ ($0 as? TFNode)?.nodeDef.isTFConstOp ?? false }).first {
// Embedded const variables
assign.strip()
outputNode.addIncomingEdge(from: node)
node.addIncomingEdge(from: constValue)
} else {
// No variables or randomly initialized. You must pass a parameter loader in this case
assign.deleteIncomingEdge(node: node)
assign.strip(recursive: true)
outputNode.addIncomingEdge(from: node)
}
}
} else if node.nodeDef.name.isTFVariableReadName,
let readInput = node.incomingNodes() as? [TFNode], readInput.count == 1,
let variable = readInput.first, variable.nodeDef.isTFConstOp, variable.incomingNodes().isEmpty,
let outputs = node.outgoingNodes() as? [TFNode], outputs.count == 1, let output = outputs.first {
//Freezed graph variables are transformed to Const
node.strip()
output.addIncomingEdge(from: variable)
}
}
}
}
fileprivate extension String {
// swiftlint:disable force_try
var isTFVariableValue: Bool {
let regex = try! Regex("Variable(_\\d+)?/initial_value")
return regex.test(self)
}
var isTFVariableV2Name: Bool {
let regex = try! Regex("Variable(_\\d+)?")
return regex.test(self)
}
var isTFVariableReadName: Bool {
let regex = try! Regex(".*/read$")
return regex.test(self)
}
// swiftlint:enable force_try
}
| mit | f30b3c4c0a4f762bb252baff0040787d | 35.671233 | 129 | 0.538289 | 4.607573 | false | false | false | false |
nanthi1990/CVCalendar | CVCalendar/CVSet.swift | 8 | 1864 | //
// CVSet.swift
// CVCalendar Demo
//
// Created by Eugene Mozharovsky on 17/03/15.
// Copyright (c) 2015 GameApp. All rights reserved.
//
import UIKit
/**
* Deprecated since Swift 1.2.
* Instead use native Swift Set<T> collection.
*/
public struct CVSet<T: AnyObject>: NilLiteralConvertible {
// MARK: - Private properties
private var storage = [T]()
// MARK: - Public properties
var count: Int {
return storage.count
}
var last: T? {
return storage.last
}
// MARK: - Initialization
public init(nilLiteral: ()) { }
init() { }
// MARK: - Subscript
subscript(index: Int) -> T? {
get {
if index < storage.count {
return storage[index]
} else {
return nil
}
}
}
}
// MARK: - Mutating methods
public extension CVSet {
mutating func addObject(object: T) {
if indexObject(object) == nil {
storage.append(object)
}
}
mutating func removeObject(object: T) {
if let index = indexObject(object) {
storage.removeAtIndex(index)
}
}
mutating func removeAll(keepCapacity: Bool) {
storage.removeAll(keepCapacity: keepCapacity)
}
}
// MARK: - Util
private extension CVSet {
func indexObject(object: T) -> Int? {
for (index, storageObj) in enumerate(storage) {
if storageObj === object {
return index
}
}
return nil
}
}
// MARK: - SequenceType
extension CVSet: SequenceType {
public func generate() -> GeneratorOf<T> {
var power = 0
var nextClosure : () -> T? = {
(power < self.count) ? self.storage[power++] : nil
}
return GeneratorOf<T>(nextClosure)
}
} | mit | f4e76363b2d26970ed8f28752d76e536 | 19.955056 | 62 | 0.539163 | 4.207675 | false | false | false | false |
eduresende/ios-nd-swift-syntax-swift-3 | Lesson7/L7_Exercises_withSolutions.playground/Contents.swift | 1 | 4715 | //: ## Lesson 7 Exercises - Enums & Structs
//: __Problem 1__
//:
//: At the end of the code snippet below, what is the value of macchiato.steamedMilk when EspressoDrink is implemented as a struct? What about when EspressoDrink is implemented as a class?
enum Amount {
case none
case splash
case some
case alot
}
struct EspressoDrink {
let numberOfShots: Int
var steamedMilk: Amount
let foam: Bool
init(numberOfShots: Int, steamedMilk: Amount, foam: Bool) {
self.numberOfShots = numberOfShots
self.steamedMilk = steamedMilk
self.foam = foam
}
}
var macchiato = EspressoDrink(numberOfShots: 2, steamedMilk: .none, foam: true)
var espressoForGabrielle = macchiato
espressoForGabrielle.steamedMilk = .splash
macchiato.steamedMilk
// Solution
// if EspressoDrink is a struct, macchiato.steamedMilk == .None
// if EspressoDrink is a class, macchiato.steamedMilk == .Splash
//: __Problem 2__
//:
//: __2a.__
//: Write an enum to represent the five fingers on a human hand.
//:
//: __2b.__
//: Associate an Int value with each finger.
// Solution
enum Finger: Int {
case thumb, index, middle, ring, pinky
}
//: __Problem 3__
//:
//: Enum, class, or struct?
//:
//: Uncomment the code below and choose whether each type should be an enum, class, or struct.
struct Window {
let height: Double
let width: Double
var open: Bool
}
enum WritingImplement {
case pen
case pencil
case marker
case crayon
case chalk
}
struct Material {
let name: String
let density: Double
let stiffness: Double
}
struct Bicycle {
let frame: Material
let weight: Double
let category: String
static var bikeCategories: [String] = ["Road", "Touring", "Mountain", "Commuter", "BMX"]
func lookCool() {
print("Check out my gear-shifters!")
}
}
class Cyclist {
var speed: Double
let agility: Double
let bike: Bicycle
var maneuverability: Double {
get {
return agility - speed/5
}
}
init(speed: Double, agility: Double, bike: Bicycle) {
self.speed = speed
self.agility = agility
self.bike = bike
}
func brake() {
speed -= 1
}
func pedalFaster(_ factor: Double) {
speed * factor
}
}
enum Size: String {
case small = "8 ounces"
case medium = "12 ounces"
case large = "16 ounces"
}
//: __Problem 4__
//:
//: Write a cookie struct.
//:
//: __4a.__
//: Include 2 stored properties. Examples might include a string representing flavor, or an int representing minutesSinceRemovalFromOven.
//:__4b.__
//: Add a computed property, "delicious", a bool whose value depends upon the values of the stored properties.
//:__4c.__
//:Include a method. For example, the method tempt() might return or print out an indication of a person being tempted to eat the cookie.
//: __4d.__
//: Create an instance of your Cookie struct and call its method.
// Example Solution
struct Cookie {
let flavor: String
let minutesSinceBaking: Int
var delicious: Bool {
get {
if flavor == "Chocolate Chip" || (minutesSinceBaking < 30) {
return true
} else {
return false
}
}
}
func tempt(){
if delicious {
print("I'll just have one more.")
} else {
print("I really shouldn't.")
}
}
}
//: __Problem 5__
//:
//: Write a class to represent a listing for a Bed and Breakfast.
//:
//: __5a.__
//: Include 3 stored properties. Examples might include a category representing the type of housing i.e. apartment or house, or a bool representing availability.
//: __5b.__
//: Consider writing a helper enum and incorporating it as one of your properties.
//: __5c.__
//: Include at least one method. For example, the method book() might toggle the availability bool or return a reservation confirmation.
//: __5d.__
//: Create an instance of your BnBListing class and call one of its methods.
// Example Solution
enum Housing {
case mansion
case apartment
case shack
case house
}
class BnBListing {
let category: Housing
let capacity: Int
var available: Bool
init(category: Housing, price: Int, capacity: Int, available: Bool) {
self.category = category
self.capacity = capacity
self.available = available
}
func book() {
self.available = false
print("Reservation confirmed!")
}
}
let beachBungalow = BnBListing(category: .shack, price: 20, capacity: 2, available: true)
beachBungalow.book()
beachBungalow.available
| mit | 302d032f75260d2b51b96dca63367389 | 22.341584 | 188 | 0.63351 | 3.858429 | false | false | false | false |
zhangjk4859/playGround | pickCandy/pickCandy/main.swift | 1 | 635 | //
// main.swift
// pickCandy
//
// Created by 张俊凯 on 2016/11/29.
// Copyright © 2016年 张俊凯. All rights reserved.
//
import Foundation
private func showMeTheCandy(candy:String){
print(candy)
}
let candys = ["a","b","c","d","e","f","g"]
print(candys)
showMeTheCandy(candy: candys[2])
var toPickCandyLocation = 5
var currentCandyLocation = 1
var candyPicked:String? = nil;
let candysTwo : Dictionary<String,String> = [
"1" : "A",
"2" : "B",
"3" : "C",
"4" : "D",
"5" : "E",
"6" : "F",
"7" : "G",
"8" : "H",
"9" : "I"
]
showMeTheCandy(candy: candysTwo["2"]!)
| mit | 5953df929be62d02053f7eb811d4c3fb | 11.4 | 47 | 0.548387 | 2.605042 | false | false | false | false |
Kevin-De-Koninck/Sub-It | Sub It/installationGuideTextField.swift | 1 | 1118 | //
// installationGuideTextField.swift
// Sub It
//
// Created by Kevin De Koninck on 05/02/2017.
// Copyright © 2017 Kevin De Koninck. All rights reserved.
//
import Cocoa
class installationGuideTextField: NSTextField {
override func draw(_ dirtyRect: NSRect) {
super.draw(dirtyRect)
var bgColor = NSColor(red: 251/255.0, green: 251/255.0, blue: 251/255.0, alpha: 1.0)
bgColor = NSColor(red: 255/255.0, green: 255/255.0, blue: 255/255.0, alpha: 1.0)
self.focusRingType = .none
self.isBordered = false
self.drawsBackground = false
self.backgroundColor = bgColor
self.layer?.backgroundColor = bgColor.cgColor
//underline
let border = CALayer()
let width = CGFloat(1.0)
border.borderColor = blueColor.cgColor
border.frame = CGRect(x: 0, y: self.frame.size.height - width, width: self.frame.size.width, height: self.frame.size.height)
border.borderWidth = width
self.layer?.addSublayer(border)
self.layer?.masksToBounds = true
}
}
| mit | 5706ca121c6979814cfe7773f7cef2e3 | 30.027778 | 133 | 0.622202 | 3.919298 | false | false | false | false |
AppriaTT/Swift_SelfLearning | Swift/swift09 ImageScrollerEffect/swift09 ImageScrollerEffect/ViewController.swift | 1 | 2117 | //
// ViewController.swift
// swift09 ImageScrollerEffect
//
// Created by Aaron on 16/7/13.
// Copyright © 2016年 Aaron. All rights reserved.
//
import UIKit
class ViewController: UIViewController,UIScrollViewDelegate {
var sV:UIScrollView!
var img:UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
let imgBG = UIImageView(image: UIImage(named: "steve"))
imgBG.frame = self.view.bounds
self.view.addSubview(imgBG)
let visualView = UIVisualEffectView(frame: self.view.bounds)
visualView.effect = UIBlurEffect(style: UIBlurEffectStyle.Light)
self.view.addSubview(visualView)
sV = UIScrollView(frame: self.view.bounds)
sV.delegate = self
self.view.addSubview(sV)
img = UIImageView(image: UIImage(named: "steve"))
img.frame.size = CGSizeMake(UIScreen.mainScreen().bounds.width, UIScreen.mainScreen().bounds.width/img.frame.size.width * img.frame.size.height)
sV.addSubview(img)
// img.center = sV.center
img.userInteractionEnabled = true
sV.minimumZoomScale = 1
sV.maximumZoomScale = 10
recenterImage()
// Do any additional setup after loading the view, typically from a nib.
}
private func recenterImage() {
//重新中心化图片 使它固定在中间
let scrollViewSize = sV.bounds.size
let imageViewSize = img.frame.size
let horizontalSpace = imageViewSize.width < scrollViewSize.width ? (scrollViewSize.width - imageViewSize.width) / 2.0 : 0
let verticalSpace = imageViewSize.height < scrollViewSize.height ? (scrollViewSize.height - imageViewSize.width) / 2.0 : 0
sV.contentInset = UIEdgeInsetsMake(verticalSpace, horizontalSpace, verticalSpace, horizontalSpace)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView?{
return img
}
}
| mit | 2e352dbf1034ff9cc5770eb227fbce77 | 34.965517 | 152 | 0.666347 | 4.524946 | false | false | false | false |
Gypsyan/KGButtonBadge | KGButtonBadge/KGButtonBadge.swift | 1 | 3505 | //
// KGButtonBadge.swift
// KGButtonBadge
//
// Created by Anantha Krishnan K G on 29/11/16.
// Copyright © 2016 Ananth. All rights reserved.
//
import UIKit
@IBDesignable
open class KGButtonBadge: UIButton {
fileprivate var badgeIcon: UILabel
fileprivate var badgeEdgeInsets: UIEdgeInsets?
@IBInspectable
open var badgeValue: String = "0" {
didSet {
setupBadgeViewWithString(badgeText: badgeValue)
}
}
@IBInspectable
open var makeRound:Bool = false {
didSet {
setupBadgeViewWithString(badgeText: badgeValue)
}
}
@IBInspectable
open var badgeBackgroundColor:UIColor = UIColor.blue {
didSet {
badgeIcon.backgroundColor = badgeBackgroundColor
}
}
@IBInspectable
open var badgeTextColor:UIColor = UIColor.white {
didSet {
badgeIcon.textColor = badgeTextColor
}
}
override public init(frame: CGRect) {
badgeIcon = UILabel()
super.init(frame: frame)
setupBadgeViewWithString(badgeText: "")
}
required public init?(coder aDecoder: NSCoder) {
badgeIcon = UILabel()
super.init(coder: aDecoder)
setupBadgeViewWithString(badgeText: "")
}
open func initWithFrame(frame: CGRect, withBadgeString badgeString: String, withBadgeInsets badgeInsets: UIEdgeInsets) -> AnyObject {
badgeIcon = UILabel()
badgeEdgeInsets = badgeInsets
setupBadgeViewWithString(badgeText: badgeString)
return self
}
fileprivate func setupBadgeViewWithString(badgeText: String?) {
badgeIcon.clipsToBounds = true
badgeIcon.text = badgeText
badgeIcon.font = UIFont.systemFont(ofSize: 12)
badgeIcon.textAlignment = .center
badgeIcon.sizeToFit()
let badgeSize = badgeIcon.frame.size
let height = max(20, Double(badgeSize.height) + 5.0)
let width = max(height, Double(badgeSize.width) + 10.0)
var vertical: Double?, horizontal: Double?
if let badgeInset = self.badgeEdgeInsets {
vertical = Double(badgeInset.top) - Double(badgeInset.bottom)
horizontal = Double(badgeInset.left) - Double(badgeInset.right)
let x = (Double(bounds.size.width) - 10 + horizontal!)-20
let y = -(Double(badgeSize.height) / 2) - 10 + vertical!
badgeIcon.frame = CGRect(x: x, y: y, width: width, height: height)
} else {
let x = self.frame.width - CGFloat((width / 2.0))
let y = CGFloat(-(height / 2.0))
badgeIcon.frame = CGRect(x: x, y: y, width: CGFloat(width), height: CGFloat(height))
}
setupBadgeStyle()
addSubview(badgeIcon)
if let text = badgeText {
badgeIcon.isHidden = text != "" ? false : true
} else {
badgeIcon.isHidden = true
}
}
fileprivate func setupBadgeStyle() {
badgeIcon.textAlignment = .center
badgeIcon.backgroundColor = badgeBackgroundColor
badgeIcon.textColor = badgeTextColor
badgeIcon.layer.cornerRadius = badgeIcon.bounds.size.height / 2
if self.bounds.size.height > self.bounds.size.width {
self.layer.cornerRadius = self.bounds.size.height/2
} else{
self.layer.cornerRadius = self.bounds.size.width/2
}
}
}
| apache-2.0 | 5a10cf616951559081672d9e0cf24a38 | 30.567568 | 137 | 0.606735 | 4.665779 | false | false | false | false |
kareman/SwiftShell | Sources/SwiftShell/Command.swift | 1 | 15736 | /*
* Released under the MIT License (MIT), http://opensource.org/licenses/MIT
*
* Copyright (c) 2015 Kåre Morstøl, NotTooBad Software (nottoobadsoftware.com)
*
*/
import Dispatch
import Foundation
// MARK: exit
/**
Prints message to standard error and terminates the application.
In debug builds it precedes the message with filename and line number.
- parameter errormessage: the error message.
- parameter errorcode: exit code for the entire program. Defaults to 1.
- returns: Never.
*/
public func exit<T>(errormessage: T, errorcode: Int = 1, file: String = #file, line: Int = #line) -> Never {
#if DEBUG
main.stderror.print(file + ":\(line):", errormessage)
#else
main.stderror.print(errormessage)
#endif
exit(Int32(errorcode))
}
/**
Prints error to standard error and terminates the application.
- parameter error: the error
- returns: Never.
*/
public func exit(_ error: Error, file: String = #file, line: Int = #line) -> Never {
if let commanderror = error as? CommandError {
exit(errormessage: commanderror, errorcode: commanderror.errorcode, file: file, line: line)
} else {
exit(errormessage: error.localizedDescription, errorcode: error._code, file: file, line: line)
}
}
// MARK: CommandRunning
/// Can run commands.
public protocol CommandRunning {
var context: Context { get }
}
extension CommandRunning where Self: Context {
public var context: Context { self }
}
extension CommandRunning {
func createProcess(_ executable: String, args: [String]) -> Process {
/**
If `executable` is not a path and a path for an executable file of that name can be found, return that path.
Otherwise just return `executable`.
*/
func path(for executable: String) -> String {
guard !executable.contains("/") else {
return executable
}
let path = self.run("/usr/bin/which", executable).stdout
return path.isEmpty ? executable : path
}
let process = Process()
process.arguments = args
if #available(OSX 10.13, *) {
process.executableURL = URL(fileURLWithPath: path(for: executable))
} else {
process.launchPath = path(for: executable)
}
process.environment = context.env
if #available(OSX 10.13, *) {
process.currentDirectoryURL = URL(fileURLWithPath: context.currentdirectory, isDirectory: true)
} else {
process.currentDirectoryPath = context.currentdirectory
}
process.standardInput = context.stdin.filehandle
process.standardOutput = context.stdout.filehandle
process.standardError = context.stderror.filehandle
return process
}
}
// MARK: CommandError
/** Error type for commands. */
public enum CommandError: Error, Equatable {
/** Exit code was not zero. */
case returnedErrorCode(command: String, errorcode: Int)
/** Command could not be executed. */
case inAccessibleExecutable(path: String)
/** Exit code for this error. */
public var errorcode: Int {
switch self {
case let .returnedErrorCode(_, code):
return code
case .inAccessibleExecutable:
return 127 // according to http://tldp.org/LDP/abs/html/exitcodes.html
}
}
}
extension CommandError: CustomStringConvertible {
public var description: String {
switch self {
case let .inAccessibleExecutable(path):
return "Could not execute file at path '\(path)'."
case let .returnedErrorCode(command, code):
return "Command '\(command)' returned with error code \(code)."
}
}
}
// MARK: run
/// Output from a `run` command.
public final class RunOutput {
private let output: AsyncCommand
private let rawStdout: Data
private let rawStderror: Data
/// The error from running the command, if any.
public let error: CommandError?
/// Launches command, reads all output from both standard output and standard error simultaneously,
/// and waits until the command is finished.
init(launch command: AsyncCommand) {
var error: CommandError?
var stdout = Data()
var stderror = Data()
let group = DispatchGroup()
do {
// launch and read stdout and stderror.
// see https://github.com/kareman/SwiftShell/issues/52
try command.process.launchThrowably()
if command.stdout.filehandle.fileDescriptor != command.stderror.filehandle.fileDescriptor {
DispatchQueue.global().async(group: group) {
stderror = command.stderror.readData()
}
}
stdout = command.stdout.readData()
try command.finish()
} catch let commandError as CommandError {
error = commandError
} catch {
assertionFailure("Unexpected error: \(error)")
}
group.wait()
self.rawStdout = stdout
self.rawStderror = stderror
self.output = command
self.error = error
}
/// If text is single-line, trim it.
private static func cleanUpOutput(_ text: String) -> String {
let afterfirstnewline = text.firstIndex(of: "\n").map(text.index(after:))
return (afterfirstnewline == nil || afterfirstnewline == text.endIndex)
? text.trimmingCharacters(in: .whitespacesAndNewlines)
: text
}
/// Standard output, trimmed of whitespace and newline if it is single-line.
public private(set) lazy var stdout: String = {
guard let result = String(data: rawStdout, encoding: output.stdout.encoding) else {
fatalError("Could not convert binary output of stdout to text using encoding \(output.stdout.encoding).")
}
return RunOutput.cleanUpOutput(result)
}()
/// Standard error, trimmed of whitespace and newline if it is single-line.
public private(set) lazy var stderror: String = {
guard let result = String(data: rawStderror, encoding: output.stderror.encoding) else {
fatalError("Could not convert binary output of stderror to text using encoding \(output.stderror.encoding).")
}
return RunOutput.cleanUpOutput(result)
}()
/// The exit code of the command. Anything but 0 means there was an error.
public var exitcode: Int { output.exitcode() }
/// Checks if the exit code is 0.
public var succeeded: Bool { exitcode == 0 }
/// Runs the first command, then the second one only if the first succeeded.
///
/// - Returns: the result of the second one if it was run, otherwise the first one.
@discardableResult
public static func && (lhs: RunOutput, rhs: @autoclosure () -> RunOutput) -> RunOutput {
guard lhs.succeeded else { return lhs }
return rhs()
}
/// Runs the first command, then the second one only if the first failed.
///
/// - Returns: the result of the second one if it was run, otherwise the first one.
@discardableResult
public static func || (lhs: RunOutput, rhs: @autoclosure () -> RunOutput) -> RunOutput {
if lhs.succeeded { return lhs }
return rhs()
}
}
extension CommandRunning {
@available(*, unavailable, message: "Use `run(...).stdout` instead.")
@discardableResult public func run(_ executable: String, _ args: Any ..., combineOutput: Bool = false) -> String {
fatalError()
}
/// Runs a command.
///
/// - parameter executable: path to an executable, or the name of an executable in PATH.
/// - parameter args: the arguments, one string for each.
/// - parameter combineOutput: if true then stdout and stderror go to the same stream. Default is false.
@discardableResult public func run(_ executable: String, _ args: Any ..., combineOutput: Bool = false) -> RunOutput {
let stringargs = args.flatten().map(String.init(describing:))
let asyncCommand = AsyncCommand(unlaunched: createProcess(executable, args: stringargs), combineOutput: combineOutput)
return RunOutput(launch: asyncCommand)
}
}
// MARK: runAsync
/// Output from the `runAsyncAndPrint` commands.
public class PrintedAsyncCommand {
fileprivate let process: Process
init(unlaunched process: Process, combineOutput: Bool) {
self.process = process
if combineOutput {
process.standardError = process.standardOutput
}
}
/// Calls `init(unlaunched:)`, then launches the process and exits the application on error.
convenience init(launch process: Process, file: String, line: Int) {
self.init(unlaunched: process, combineOutput: false)
do {
try process.launchThrowably()
} catch {
exit(errormessage: error, file: file, line: line)
}
}
/// Is the command still running?
public var isRunning: Bool { process.isRunning }
/// Terminates the command by sending the SIGTERM signal.
public func stop() {
process.terminate()
}
/// Interrupts the command by sending the SIGINT signal.
public func interrupt() {
process.interrupt()
}
/**
Temporarily suspends a command. Call resume() to resume a suspended command.
- warning: You may suspend a command multiple times, but it must be resumed an equal number of times before the command will truly be resumed.
- returns: `true` iff the command was successfully suspended.
*/
@discardableResult public func suspend() -> Bool {
process.suspend()
}
/**
Resumes a command previously suspended with suspend().
- warning: If the command has been suspended multiple times then it will have to be resumed the same number of times before execution will truly be resumed.
- returns: true if the command was successfully resumed.
*/
@discardableResult public func resume() -> Bool {
process.resume()
}
/**
Waits for this command to finish.
- warning: Hangs if the unread output of either standard output or standard error is larger than 64KB ([#52](https://github.com/kareman/SwiftShell/issues/52)). To work around this problem, read all the output first, even if you're not going to use it.
- returns: self
- throws: `CommandError.returnedErrorCode(command: String, errorcode: Int)` if the exit code is anything but 0.
*/
@discardableResult public func finish() throws -> Self {
try process.finish()
return self
}
/** Waits for command to finish, then returns with exit code. */
public func exitcode() -> Int {
process.waitUntilExit()
return Int(process.terminationStatus)
}
/**
Waits for the command to finish, then returns why the command terminated.
- returns: `.exited` if the command exited normally, otherwise `.uncaughtSignal`.
*/
public func terminationReason() -> Process.TerminationReason {
process.waitUntilExit()
return process.terminationReason
}
/// Takes a closure to be called when the command has finished.
///
/// - Parameter handler: A closure taking this AsyncCommand as input, returning nothing.
/// - Returns: This PrintedAsyncCommand.
@discardableResult public func onCompletion(_ handler: @escaping (PrintedAsyncCommand) -> Void) -> Self {
process.terminationHandler = { _ in
handler(self)
}
return self
}
}
/** Output from the 'runAsync' commands. */
public final class AsyncCommand: PrintedAsyncCommand {
public let stdout: ReadableStream
public let stderror: ReadableStream
override init(unlaunched process: Process, combineOutput: Bool) {
let outpipe = Pipe()
process.standardOutput = outpipe
stdout = FileHandleStream(outpipe.fileHandleForReading, encoding: main.encoding)
if combineOutput {
stderror = stdout
} else {
let errorpipe = Pipe()
process.standardError = errorpipe
stderror = FileHandleStream(errorpipe.fileHandleForReading, encoding: main.encoding)
}
super.init(unlaunched: process, combineOutput: combineOutput)
}
/// Takes a closure to be called when the command has finished.
///
/// - Parameter handler: A closure taking this AsyncCommand as input, returning nothing.
/// - Returns: This AsyncCommand.
@discardableResult public override func onCompletion(_ handler: @escaping (AsyncCommand) -> Void) -> Self {
process.terminationHandler = { _ in
handler(self)
}
return self
}
}
extension CommandRunning {
/**
Runs executable and returns before it is finished.
- warning: Application will be terminated if ‘executable’ could not be launched.
- parameter executable: Path to an executable file. If not then exit.
- parameter args: Arguments to the executable.
*/
public func runAsync(_ executable: String, _ args: Any ..., file: String = #file, line: Int = #line) -> AsyncCommand {
let stringargs = args.flatten().map(String.init(describing:))
return AsyncCommand(launch: createProcess(executable, args: stringargs), file: file, line: line)
}
/**
Runs executable and returns before it is finished.
Any output is printed to standard output and standard error, respectively.
- warning: Application will be terminated if ‘executable’ could not be launched.
- parameter executable: Path to an executable file. If not then exit.
- parameter args: Arguments to the executable.
*/
public func runAsyncAndPrint(_ executable: String, _ args: Any ..., file: String = #file, line: Int = #line) -> PrintedAsyncCommand {
let stringargs = args.flatten().map(String.init(describing:))
return PrintedAsyncCommand(launch: createProcess(executable, args: stringargs), file: file, line: line)
}
}
// MARK: runAndPrint
extension CommandRunning {
/**
Runs executable and prints output and errors.
- parameter executable: path to an executable file.
- parameter args: arguments to the executable.
- throws:
`CommandError.returnedErrorCode(command: String, errorcode: Int)` if the exit code is anything but 0.
`CommandError.inAccessibleExecutable(path: String)` if 'executable’ turned out to be not so executable after all.
*/
public func runAndPrint(_ executable: String, _ args: Any ...) throws {
let stringargs = args.flatten().map(String.init(describing:))
let process = createProcess(executable, args: stringargs)
try process.launchThrowably()
try process.finish()
}
}
// MARK: Global functions
/// Runs a command.
///
/// - parameter executable: path to an executable, or the name of an executable in PATH.
/// - parameter args: the arguments, one string for each.
/// - parameter combineOutput: if true then stdout and stderror go to the same stream. Default is false.
@discardableResult public func run(_ executable: String, _ args: Any ..., combineOutput: Bool = false) -> RunOutput {
main.run(executable, args, combineOutput: combineOutput)
}
@available(*, unavailable, message: "Use `run(...).stdout` instead.")
@discardableResult public func run(_ executable: String, _ args: Any ..., combineOutput: Bool = false) -> String {
fatalError()
}
/**
Runs executable and returns before it is finished.
- warning: Application will be terminated if ‘executable’ could not be launched.
- parameter executable: Path to an executable file. If not then exit.
- parameter args: Arguments to the executable.
*/
public func runAsync(_ executable: String, _ args: Any ..., file: String = #file, line: Int = #line) -> AsyncCommand {
main.runAsync(executable, args, file: file, line: line)
}
/**
Runs executable and returns before it is finished.
Any output is printed to standard output and standard error, respectively.
- warning: Application will be terminated if ‘executable’ could not be launched.
- parameter executable: Path to an executable file. If not then exit.
- parameter args: Arguments to the executable.
*/
public func runAsyncAndPrint(_ executable: String, _ args: Any ..., file: String = #file, line: Int = #line) -> PrintedAsyncCommand {
main.runAsyncAndPrint(executable, args, file: file, line: line)
}
/**
Runs executable and prints output and errors.
- parameter executable: path to an executable file.
- parameter args: arguments to the executable.
- throws: `CommandError.returnedErrorCode(command: String, errorcode: Int)` if the exit code is anything but 0.
`CommandError.inAccessibleExecutable(path: String)` if 'executable’ turned out to be not so executable after all.
*/
public func runAndPrint(_ executable: String, _ args: Any ...) throws {
try main.runAndPrint(executable, args)
}
| mit | 8d9568d23b5df06bae3ce3dd58c0e9ee | 32.648822 | 253 | 0.719422 | 3.89153 | false | false | false | false |
royhsu/tiny-core | Sources/Core/Geometry/Radian.swift | 1 | 1630 | //
// Radian.swift
// TinyCore
//
// Created by Roy Hsu on 2018/4/5.
// Copyright © 2018 TinyWorld. All rights reserved.
//
// MARK: - Radian
public struct Radian: RawRepresentable {
public var rawValue: Double
public init(rawValue: Double) { self.rawValue = rawValue }
}
// MARK: - Numeric
extension Radian: Numeric {
public init?<T>(exactly source: T) where T: BinaryInteger {
guard
let value = Double(exactly: source)
else { return nil }
self.init(rawValue: value)
}
public init(integerLiteral value: Double) { self.init(rawValue: value) }
public var magnitude: Double { return rawValue.magnitude }
public static func + (
lhs: Radian,
rhs: Radian
)
-> Radian { return Radian(rawValue: lhs.rawValue + rhs.rawValue) }
public static func += (
lhs: inout Radian,
rhs: Radian
) { lhs.rawValue += rhs.rawValue }
public static func - (
lhs: Radian,
rhs: Radian
)
-> Radian { return Radian(rawValue: lhs.rawValue - rhs.rawValue) }
public static func -= (
lhs: inout Radian,
rhs: Radian
) { lhs.rawValue -= rhs.rawValue }
public static func * (
lhs: Radian,
rhs: Radian
)
-> Radian { return Radian(rawValue: lhs.rawValue * rhs.rawValue) }
public static func *= (
lhs: inout Radian,
rhs: Radian
) { lhs.rawValue *= rhs.rawValue }
}
// MARK: - ExpressibleByFloatLiteral
extension Radian: ExpressibleByFloatLiteral {
public init(floatLiteral value: Double) { self.init(rawValue: value) }
}
| mit | ac06cd5bf0159eaa15d0fea193626705 | 19.884615 | 76 | 0.607735 | 4.092965 | false | false | false | false |
brandonlee503/Weather-App | Weather App/DailyWeather.swift | 2 | 2996 | //
// DailyWeather.swift
// Weather App
//
// Created by Brandon Lee on 8/16/15.
// Copyright (c) 2015 Brandon Lee. All rights reserved.
//
import Foundation
import UIKit
struct DailyWeather {
let maxTemperature: Int?
let minTemperature: Int?
let humidity: Int?
let precipChance: Int?
let summary: String?
var icon: UIImage? = UIImage(named: "default.png")
var largeIcon: UIImage? = UIImage(named: "default_large.png")
var sunriseTime: String?
var sunsetTime: String?
var day: String?
// Date formatter stored property
let dateFormatter = NSDateFormatter()
init(dailyWeatherDict: [String: AnyObject]) {
// Using the optional cast operator (as?) in case the dictionary we pass in doesn't contain the key, will still be stored as an optional
maxTemperature = dailyWeatherDict["temperatureMax"] as? Int
minTemperature = dailyWeatherDict["temperatureMin"] as? Int
// Safely cast as Int
if let humidityFloat = dailyWeatherDict["humidity"] as? Double {
humidity = Int(humidityFloat * 100)
} else {
humidity = nil
}
if let precipChanceFloat = dailyWeatherDict["precipProbability"] as? Double {
precipChance = Int(precipChanceFloat * 100)
} else {
precipChance = nil
}
summary = dailyWeatherDict["summary"] as? String
// Chain optional binding command (versus nesting)
if let iconString = dailyWeatherDict["icon"] as? String,
let iconEnum = Icon(rawValue: iconString) {
(icon, largeIcon) = iconEnum.toImage()
}
if let sunriseDate = dailyWeatherDict["sunriseTime"] as? Double {
sunriseTime = timeStringFromUnixTime(sunriseDate)
} else {
sunriseTime = nil
}
if let sunsetDate = dailyWeatherDict["sunsetTime"] as? Double {
sunsetTime = timeStringFromUnixTime(sunsetDate)
} else {
sunsetTime = nil
}
if let time = dailyWeatherDict["time"] as? Double {
day = dayStringFromTime(time)
}
}
func timeStringFromUnixTime(unixTime: Double) -> String {
let date = NSDate(timeIntervalSince1970: unixTime)
// Returns date formatted as 12 hour timeg
dateFormatter.dateFormat = "hh:mm a"
return dateFormatter.stringFromDate(date)
}
func dayStringFromTime(unixTime: Double) -> String {
let date = NSDate(timeIntervalSince1970: unixTime)
// Ask for the current locale of the iPhone to display day correctly (eg. Language)
dateFormatter.locale = NSLocale(localeIdentifier: NSLocale.currentLocale().localeIdentifier)
// Get full day name (eg. MONDAY)
dateFormatter.dateFormat = "EEEE"
return dateFormatter.stringFromDate(date)
}
} | mit | 4016b1f33585de0bfe52f28074803219 | 31.934066 | 144 | 0.615154 | 4.778309 | false | false | false | false |
Ezfen/iOS.Apprentice.1-4 | MyLocations/MyLocations/CategoryPickerViewController.swift | 1 | 3210 | //
// CategoryPickerViewController.swift
// MyLocations
//
// Created by ezfen on 16/8/19.
// Copyright © 2016年 Ezfen Inc. All rights reserved.
//
import UIKit
class CategoryPickerViewController: UITableViewController {
var selectedCategoryName = ""
let categories = [
"No Category",
"Apple Store",
"Bar",
"Bookstore",
"Club",
"Grocery Store",
"Historic Building",
"House",
"Icecream Vendor",
"Landmark",
"Park"]
var selectedIndexPath = NSIndexPath()
override func viewDidLoad() {
super.viewDidLoad()
for i in 0..<categories.count {
if categories[i] == selectedCategoryName {
selectedIndexPath = NSIndexPath(forRow: i, inSection: 0)
break
}
}
tableView.backgroundColor = UIColor.blackColor()
tableView.separatorColor = UIColor(white: 1.0, alpha: 0.2)
tableView.indicatorStyle = .White
}
// MARK: - UITableViewDataSource
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return categories.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
let categoryName = categories[indexPath.row]
cell.textLabel!.text = categoryName
if categoryName == selectedCategoryName {
cell.accessoryType = .Checkmark
} else {
cell.accessoryType = .None
}
return cell
}
// MARK: - UITableViewDelegate
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if indexPath.row != selectedIndexPath.row {
if let newCell = tableView.cellForRowAtIndexPath(indexPath) {
newCell.accessoryType = .Checkmark
}
if let oldCell = tableView.cellForRowAtIndexPath(selectedIndexPath) {
oldCell.accessoryType = .None
}
selectedIndexPath = indexPath
}
}
override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
cell.backgroundColor = UIColor.blackColor()
if let textLabel = cell.textLabel {
textLabel.textColor = UIColor.whiteColor()
textLabel.highlightedTextColor = textLabel.textColor
}
let selectionView = UIView(frame: CGRect.zero)
selectionView.backgroundColor = UIColor(white: 1.0, alpha: 0.2)
cell.selectedBackgroundView = selectionView
}
// MARK: - prepareForSegue
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "PickedCategory" {
let cell = sender as! UITableViewCell
if let indexPath = tableView.indexPathForCell(cell) {
selectedCategoryName = categories[indexPath.row]
}
}
}
}
| mit | 9e47c20efbd78af46d4daa344b78f5b3 | 31.72449 | 134 | 0.618023 | 5.606643 | false | false | false | false |
ScoutHarris/WordPress-iOS | WordPress/Classes/ViewRelated/Cells/MediaItemTableViewCells.swift | 2 | 10328 | import UIKit
import Gridicons
import WordPressShared
class MediaItemImageTableViewCell: WPTableViewCell {
let customImageView = UIImageView()
let activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: .white)
let activityMaskView = UIView()
let videoIconView = PlayIconView()
var isVideo: Bool {
set {
videoIconView.isHidden = !newValue
}
get {
return !videoIconView.isHidden
}
}
// MARK: - Initializers
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
public required override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
commonInit()
}
public convenience init() {
self.init(style: .default, reuseIdentifier: nil)
}
func commonInit() {
setupImageView()
setupLoadingViews()
setupVideoIconView()
}
private func setupImageView() {
contentView.addSubview(customImageView)
customImageView.translatesAutoresizingMaskIntoConstraints = false
customImageView.contentMode = .scaleAspectFit
NSLayoutConstraint.activate([
customImageView.leadingAnchor.constraint(equalTo: contentView.readableContentGuide.leadingAnchor),
customImageView.trailingAnchor.constraint(equalTo: contentView.readableContentGuide.trailingAnchor),
customImageView.topAnchor.constraint(equalTo: contentView.topAnchor),
customImageView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor)
])
customImageView.setContentHuggingPriority(UILayoutPriorityDefaultLow, for: .horizontal)
}
private func setupLoadingViews() {
contentView.addSubview(activityMaskView)
activityMaskView.translatesAutoresizingMaskIntoConstraints = false
activityMaskView.backgroundColor = .black
activityMaskView.alpha = 0.5
contentView.addSubview(activityIndicator)
activityIndicator.translatesAutoresizingMaskIntoConstraints = false
activityIndicator.hidesWhenStopped = true
NSLayoutConstraint.activate([
activityIndicator.centerXAnchor.constraint(equalTo: contentView.centerXAnchor),
activityIndicator.centerYAnchor.constraint(equalTo: contentView.centerYAnchor),
activityMaskView.leadingAnchor.constraint(equalTo: customImageView.leadingAnchor),
activityMaskView.trailingAnchor.constraint(equalTo: customImageView.trailingAnchor),
activityMaskView.topAnchor.constraint(equalTo: customImageView.topAnchor),
activityMaskView.bottomAnchor.constraint(equalTo: customImageView.bottomAnchor)
])
}
private func setupVideoIconView() {
contentView.addSubview(videoIconView)
videoIconView.isHidden = true
}
private var aspectRatioConstraint: NSLayoutConstraint? = nil
var targetAspectRatio: CGFloat {
set {
if let aspectRatioConstraint = aspectRatioConstraint {
customImageView.removeConstraint(aspectRatioConstraint)
}
aspectRatioConstraint = customImageView.heightAnchor.constraint(equalTo: customImageView.widthAnchor, multiplier: newValue, constant: 1.0)
aspectRatioConstraint?.priority = UILayoutPriorityDefaultHigh
aspectRatioConstraint?.isActive = true
}
get {
return aspectRatioConstraint?.multiplier ?? 0
}
}
override func setHighlighted(_ highlighted: Bool, animated: Bool) {
super.setHighlighted(highlighted, animated: animated)
resetBackgroundColors()
if animated {
UIView.animate(withDuration: 0.2) {
self.videoIconView.isHighlighted = highlighted
}
} else {
videoIconView.isHighlighted = highlighted
}
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
resetBackgroundColors()
}
private func resetBackgroundColors() {
customImageView.backgroundColor = .black
contentView.backgroundColor = .white
}
override func layoutSubviews() {
super.layoutSubviews()
videoIconView.center = contentView.center
}
// MARK: - Loading
var isLoading: Bool = false {
didSet {
if isLoading {
activityMaskView.alpha = 0.5
activityIndicator.startAnimating()
} else {
activityMaskView.alpha = 0
activityIndicator.stopAnimating()
}
}
}
}
class MediaItemDocumentTableViewCell: WPTableViewCell {
let customImageView = UIImageView()
// MARK: - Initializers
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
public required override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
commonInit()
}
public convenience init() {
self.init(style: .default, reuseIdentifier: nil)
}
func commonInit() {
setupImageView()
}
private func setupImageView() {
customImageView.backgroundColor = .clear
contentView.addSubview(customImageView)
customImageView.translatesAutoresizingMaskIntoConstraints = false
customImageView.contentMode = .center
NSLayoutConstraint.activate([
customImageView.leadingAnchor.constraint(equalTo: contentView.readableContentGuide.leadingAnchor),
customImageView.trailingAnchor.constraint(equalTo: contentView.readableContentGuide.trailingAnchor),
customImageView.topAnchor.constraint(equalTo: contentView.topAnchor),
customImageView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor)
])
}
func showIconForMedia(_ media: Media) {
let dimension = CGFloat(MediaDocumentRow.customHeight! / 2)
let size = CGSize(width: dimension, height: dimension)
if media.mediaType == .audio {
customImageView.image = Gridicon.iconOfType(.audio, withSize: size)
} else {
customImageView.image = Gridicon.iconOfType(.pages, withSize: size)
}
}
}
struct MediaImageRow: ImmuTableRow {
static let cell = ImmuTableCell.class(MediaItemImageTableViewCell.self)
let media: Media
let action: ImmuTableAction?
func configureCell(_ cell: UITableViewCell) {
WPStyleGuide.configureTableViewCell(cell)
if let cell = cell as? MediaItemImageTableViewCell {
setAspectRatioFor(cell)
loadImageFor(cell)
cell.isVideo = media.mediaType == .video
}
}
func willDisplay(_ cell: UITableViewCell) {
if let cell = cell as? MediaItemImageTableViewCell {
cell.customImageView.backgroundColor = .black
}
}
private func setAspectRatioFor(_ cell: MediaItemImageTableViewCell) {
guard let width = media.width, let height = media.height, width.floatValue > 0 else {
return
}
let mediaAspectRatio = CGFloat(height.floatValue) / CGFloat(width.floatValue)
// Set a maximum aspect ratio for videos
if media.mediaType == .video {
cell.targetAspectRatio = min(mediaAspectRatio, 0.75)
} else {
cell.targetAspectRatio = mediaAspectRatio
}
}
private func addPlaceholderImageFor(_ cell: MediaItemImageTableViewCell) {
if let url = media.absoluteLocalURL,
let image = UIImage(contentsOfFile: url.path) {
cell.customImageView.image = image
} else if let url = media.absoluteThumbnailLocalURL,
let image = UIImage(contentsOfFile: url.path) {
cell.customImageView.image = image
}
}
private func loadImageFor(_ cell: MediaItemImageTableViewCell) {
if !cell.isLoading && cell.customImageView.image == nil {
addPlaceholderImageFor(cell)
cell.isLoading = true
media.image(with: .zero,
completionHandler: { image, error in
DispatchQueue.main.async {
if let error = error, image == nil {
cell.isLoading = false
self.show(error)
} else if let image = image {
self.animateImageChange(image: image, for: cell)
}
}
})
}
}
private func show(_ error: Error) {
let alertController = UIAlertController(title: nil, message: NSLocalizedString("There was a problem loading the media item.",
comment: "Error message displayed when the Media Library is unable to load a full sized preview of an item."), preferredStyle: .alert)
alertController.addCancelActionWithTitle(NSLocalizedString("Dismiss", comment: "Verb. User action to dismiss error alert when failing to load media item."))
alertController.presentFromRootViewController()
}
private func animateImageChange(image: UIImage, for cell: MediaItemImageTableViewCell) {
UIView.transition(with: cell.customImageView, duration: 0.2, options: .transitionCrossDissolve, animations: {
cell.isLoading = false
cell.customImageView.image = image
}, completion: nil)
}
}
struct MediaDocumentRow: ImmuTableRow {
static let cell = ImmuTableCell.class(MediaItemDocumentTableViewCell.self)
static let customHeight: Float? = 96.0
let media: Media
let action: ImmuTableAction?
func configureCell(_ cell: UITableViewCell) {
WPStyleGuide.configureTableViewCell(cell)
if let cell = cell as? MediaItemDocumentTableViewCell {
cell.customImageView.tintColor = cell.textLabel?.textColor
cell.showIconForMedia(media)
}
}
}
| gpl-2.0 | b3a29db9fd8b36a1f9278225b3ba6c9c | 34.613793 | 221 | 0.649593 | 5.721884 | false | false | false | false |
huangboju/Moots | 算法学习/LeetCode/LeetCode/DP/LengthOfLIS.swift | 1 | 1153 | //
// LengthOfLIS.swift
// LeetCode
//
// Created by 黄伯驹 on 2022/5/6.
// Copyright © 2022 伯驹 黄. All rights reserved.
//
import Foundation
/// https://leetcode-cn.com/problems/longest-increasing-subsequence/
func lengthOfLIS(_ nums: [Int]) -> Int {
var dp: [Int] = Array(repeating: 1, count: nums.count)
for i in 0 ..< nums.count {
for j in 0 ..< i {
if nums[i] > nums[j] {
dp[i] = max(dp[i], dp[j] + 1)
}
}
}
return dp.max() ?? 0
}
// https://leetcode-cn.com/problems/longest-continuous-increasing-subsequence/
//输入: [1,3,5,4,7]
//输出: 3
//解释: 最长连续递增序列是 [1,3,5], 长度为3。
//尽管 [1,3,5,7] 也是升序的子序列, 但它不是连续的,因为5和7在原数组里被4隔开。
func findLengthOfLCIS(_ nums: [Int]) -> Int {
if nums.isEmpty { return 0 }
var result = 1
var maxLength = 1
for i in 1..<nums.count {
if nums[i-1] < nums[i] {
result += 1
maxLength = max(maxLength, result)
} else {
result = 1
}
}
return maxLength
}
| mit | 50d10abb89440cedeb5be15991c0d155 | 21.170213 | 78 | 0.536468 | 2.846995 | false | false | false | false |
aaronraimist/firefox-ios | Client/Application/TestAppDelegate.swift | 2 | 3263 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Shared
import WebImage
import XCGLogger
private let log = Logger.browserLogger
class TestAppDelegate: AppDelegate {
override func getProfile(application: UIApplication) -> Profile {
if let profile = self.profile {
return profile
}
let profile = BrowserProfile(localName: "testProfile", app: application)
if NSProcessInfo.processInfo().arguments.contains("RESET_FIREFOX") {
// Use a clean profile for each test session.
_ = try? profile.files.removeFilesInDirectory()
profile.prefs.clearAll()
// Don't show the What's New page.
profile.prefs.setString(AppInfo.appVersion, forKey: LatestAppVersionProfileKey)
// Skip the first run UI except when we are running Fastlane Snapshot tests
if !AppConstants.IsRunningFastlaneSnapshot {
profile.prefs.setInt(1, forKey: IntroViewControllerSeenProfileKey)
}
}
self.profile = profile
return profile
}
override func application(application: UIApplication, willFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]?) -> Bool {
// If the app is running from a XCUITest reset all settings in the app
if NSProcessInfo.processInfo().arguments.contains("RESET_FIREFOX") {
resetApplication()
}
return super.application(application, willFinishLaunchingWithOptions: launchOptions)
}
/**
Use this to reset the application between tests.
**/
func resetApplication() {
log.debug("Wiping everything for a clean start.")
// Clear image cache
SDImageCache.sharedImageCache().clearDisk()
SDImageCache.sharedImageCache().clearMemory()
// Clear the cookie/url cache
NSURLCache.sharedURLCache().removeAllCachedResponses()
let storage = NSHTTPCookieStorage.sharedHTTPCookieStorage()
if let cookies = storage.cookies {
for cookie in cookies {
storage.deleteCookie(cookie)
}
}
// Clear the documents directory
var rootPath: String = ""
if let sharedContainerIdentifier = AppInfo.sharedContainerIdentifier(), url = NSFileManager.defaultManager().containerURLForSecurityApplicationGroupIdentifier(sharedContainerIdentifier), path = url.path {
rootPath = path
} else {
rootPath = (NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)[0])
}
let manager = NSFileManager.defaultManager()
let documents = NSURL(fileURLWithPath: rootPath)
let docContents = try! manager.contentsOfDirectoryAtPath(rootPath)
for content in docContents {
do {
try manager.removeItemAtURL(documents.URLByAppendingPathComponent(content))
} catch {
log.debug("Couldn't delete some document contents.")
}
}
}
} | mpl-2.0 | dc0d69f8489d5b14a689b4b5212c2a06 | 37.857143 | 212 | 0.66258 | 5.69459 | false | true | false | false |
youprofit/firefox-ios | Client/Frontend/Browser/TabTrayController.swift | 2 | 32016 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import UIKit
import SnapKit
struct TabTrayControllerUX {
static let CornerRadius = CGFloat(4.0)
static let BackgroundColor = UIConstants.AppBackgroundColor
static let CellBackgroundColor = UIColor(red:0.95, green:0.95, blue:0.95, alpha:1)
static let TextBoxHeight = CGFloat(32.0)
static let FaviconSize = CGFloat(18.0)
static let Margin = CGFloat(15)
static let ToolbarBarTintColor = UIConstants.AppBackgroundColor
static let ToolbarButtonOffset = CGFloat(10.0)
static let TabTitleTextFont = UIConstants.DefaultSmallFontBold
static let CloseButtonSize = CGFloat(18.0)
static let CloseButtonMargin = CGFloat(6.0)
static let CloseButtonEdgeInset = CGFloat(10)
static let NumberOfColumnsThin = 1
static let NumberOfColumnsWide = 3
static let CompactNumberOfColumnsThin = 2
// Moved from UIConstants temporarily until animation code is merged
static var StatusBarHeight: CGFloat {
if UIScreen.mainScreen().traitCollection.verticalSizeClass == .Compact {
return 0
}
return 20
}
}
struct LightTabCellUX {
static let TabTitleTextColor = UIColor.blackColor()
}
struct DarkTabCellUX {
static let TabTitleTextColor = UIColor.whiteColor()
}
protocol TabCellDelegate: class {
func tabCellDidClose(cell: TabCell)
}
class TabCell: UICollectionViewCell {
enum Style {
case Light
case Dark
}
static let Identifier = "TabCellIdentifier"
var style: Style = .Light {
didSet {
applyStyle(style)
}
}
let backgroundHolder = UIView()
let background = UIImageViewAligned()
let titleText: UILabel
let innerStroke: InnerStrokedView
let favicon: UIImageView = UIImageView()
let closeButton: UIButton
var title: UIVisualEffectView!
var animator: SwipeAnimator!
weak var delegate: TabCellDelegate?
// Changes depending on whether we're full-screen or not.
var margin = CGFloat(0)
override init(frame: CGRect) {
self.backgroundHolder.backgroundColor = UIColor.whiteColor()
self.backgroundHolder.layer.cornerRadius = TabTrayControllerUX.CornerRadius
self.backgroundHolder.clipsToBounds = true
self.backgroundHolder.backgroundColor = TabTrayControllerUX.CellBackgroundColor
self.background.contentMode = UIViewContentMode.ScaleAspectFill
self.background.clipsToBounds = true
self.background.userInteractionEnabled = false
self.background.alignLeft = true
self.background.alignTop = true
self.favicon.backgroundColor = UIColor.clearColor()
self.favicon.layer.cornerRadius = 2.0
self.favicon.layer.masksToBounds = true
self.titleText = UILabel()
self.titleText.textAlignment = NSTextAlignment.Left
self.titleText.userInteractionEnabled = false
self.titleText.numberOfLines = 1
self.titleText.font = TabTrayControllerUX.TabTitleTextFont
self.closeButton = UIButton()
self.closeButton.setImage(UIImage(named: "stop"), forState: UIControlState.Normal)
self.closeButton.imageEdgeInsets = UIEdgeInsetsMake(TabTrayControllerUX.CloseButtonEdgeInset, TabTrayControllerUX.CloseButtonEdgeInset, TabTrayControllerUX.CloseButtonEdgeInset, TabTrayControllerUX.CloseButtonEdgeInset)
self.innerStroke = InnerStrokedView(frame: self.backgroundHolder.frame)
self.innerStroke.layer.backgroundColor = UIColor.clearColor().CGColor
super.init(frame: frame)
self.opaque = true
self.animator = SwipeAnimator(animatingView: self.backgroundHolder, container: self)
self.closeButton.addTarget(self.animator, action: "SELcloseWithoutGesture", forControlEvents: UIControlEvents.TouchUpInside)
contentView.addSubview(backgroundHolder)
backgroundHolder.addSubview(self.background)
backgroundHolder.addSubview(innerStroke)
// Default style is light
applyStyle(style)
self.accessibilityCustomActions = [
UIAccessibilityCustomAction(name: NSLocalizedString("Close", comment: "Accessibility label for action denoting closing a tab in tab list (tray)"), target: self.animator, selector: "SELcloseWithoutGesture")
]
}
private func applyStyle(style: Style) {
self.title?.removeFromSuperview()
let title: UIVisualEffectView
switch style {
case .Light:
title = UIVisualEffectView(effect: UIBlurEffect(style: .ExtraLight))
self.titleText.textColor = LightTabCellUX.TabTitleTextColor
case .Dark:
title = UIVisualEffectView(effect: UIBlurEffect(style: .Dark))
self.titleText.textColor = DarkTabCellUX.TabTitleTextColor
}
titleText.backgroundColor = UIColor.clearColor()
title.layer.shadowColor = UIColor.blackColor().CGColor
title.layer.shadowOpacity = 0.2
title.layer.shadowOffset = CGSize(width: 0, height: 0.5)
title.layer.shadowRadius = 0
title.addSubview(self.closeButton)
title.addSubview(self.titleText)
title.addSubview(self.favicon)
backgroundHolder.addSubview(title)
self.title = title
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
let w = frame.width
let h = frame.height
backgroundHolder.frame = CGRect(x: margin,
y: margin,
width: w,
height: h)
background.frame = CGRect(origin: CGPointMake(0, 0), size: backgroundHolder.frame.size)
title.frame = CGRect(x: 0,
y: 0,
width: backgroundHolder.frame.width,
height: TabTrayControllerUX.TextBoxHeight)
favicon.frame = CGRect(x: 6,
y: (TabTrayControllerUX.TextBoxHeight - TabTrayControllerUX.FaviconSize)/2,
width: TabTrayControllerUX.FaviconSize,
height: TabTrayControllerUX.FaviconSize)
let titleTextLeft = favicon.frame.origin.x + favicon.frame.width + 6
titleText.frame = CGRect(x: titleTextLeft,
y: 0,
width: title.frame.width - titleTextLeft - margin - TabTrayControllerUX.CloseButtonSize - TabTrayControllerUX.CloseButtonMargin * 2,
height: title.frame.height)
innerStroke.frame = background.frame
closeButton.snp_makeConstraints { make in
make.size.equalTo(title.snp_height)
make.trailing.centerY.equalTo(title)
}
let top = (TabTrayControllerUX.TextBoxHeight - titleText.bounds.height) / 2.0
titleText.frame.origin = CGPoint(x: titleText.frame.origin.x, y: max(0, top))
}
override func prepareForReuse() {
// Reset any close animations.
backgroundHolder.transform = CGAffineTransformIdentity
backgroundHolder.alpha = 1
}
override func accessibilityScroll(direction: UIAccessibilityScrollDirection) -> Bool {
var right: Bool
switch direction {
case .Left:
right = false
case .Right:
right = true
default:
return false
}
animator.close(right: right)
return true
}
}
@available(iOS 9, *)
struct PrivateModeStrings {
static let toggleAccessibilityLabel = NSLocalizedString("Private Mode", tableName: "PrivateBrowsing", comment: "Accessibility label for toggling on/off private mode")
static let toggleAccessibilityHint = NSLocalizedString("Turns private mode on or off", tableName: "PrivateBrowsing", comment: "Accessiblity hint for toggling on/off private mode")
static let toggleAccessibilityValueOn = NSLocalizedString("On", tableName: "PrivateBrowsing", comment: "Toggled ON accessibility value")
static let toggleAccessibilityValueOff = NSLocalizedString("Off", tableName: "PrivateBrowsing", comment: "Toggled OFF accessibility value")
}
class TabTrayController: UIViewController {
let tabManager: TabManager
let profile: Profile
var collectionView: UICollectionView!
var navBar: UIView!
var addTabButton: UIButton!
var settingsButton: UIButton!
var collectionViewTransitionSnapshot: UIView?
private var privateMode: Bool = false {
didSet {
if #available(iOS 9, *) {
togglePrivateMode.selected = privateMode
togglePrivateMode.accessibilityValue = privateMode ? PrivateModeStrings.toggleAccessibilityValueOn : PrivateModeStrings.toggleAccessibilityValueOff
emptyPrivateTabsView.hidden = !(privateMode && tabManager.privateTabs.count == 0)
tabDataSource.tabs = tabsToDisplay
collectionView.reloadData()
}
}
}
private var tabsToDisplay: [Browser] {
return self.privateMode ? tabManager.privateTabs : tabManager.normalTabs
}
@available(iOS 9, *)
lazy var togglePrivateMode: UIButton = {
let button = UIButton()
button.setImage(UIImage(named: "smallPrivateMask"), forState: UIControlState.Normal)
button.setImage(UIImage(named: "smallPrivateMaskSelected"), forState: UIControlState.Selected)
button.addTarget(self, action: "SELdidTogglePrivateMode", forControlEvents: .TouchUpInside)
button.accessibilityLabel = PrivateModeStrings.toggleAccessibilityLabel
button.accessibilityHint = PrivateModeStrings.toggleAccessibilityHint
button.accessibilityValue = self.privateMode ? PrivateModeStrings.toggleAccessibilityValueOn : PrivateModeStrings.toggleAccessibilityValueOff
return button
}()
@available(iOS 9, *)
private lazy var emptyPrivateTabsView: EmptyPrivateTabsView = {
return EmptyPrivateTabsView()
}()
private lazy var tabDataSource: TabManagerDataSource = {
return TabManagerDataSource(tabs: self.tabsToDisplay, cellDelegate: self)
}()
private lazy var tabLayoutDelegate: TabLayoutDelegate = {
let delegate = TabLayoutDelegate(profile: self.profile, traitCollection: self.traitCollection)
delegate.tabSelectionDelegate = self
return delegate
}()
private var removedTabIndexPath: NSIndexPath?
init(tabManager: TabManager, profile: Profile) {
self.tabManager = tabManager
self.profile = profile
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: View Controller Callbacks
override func viewDidLoad() {
super.viewDidLoad()
view.accessibilityLabel = NSLocalizedString("Tabs Tray", comment: "Accessibility label for the Tabs Tray view.")
tabManager.addDelegate(self)
navBar = UIView()
navBar.backgroundColor = TabTrayControllerUX.BackgroundColor
addTabButton = UIButton()
addTabButton.setImage(UIImage(named: "add"), forState: .Normal)
addTabButton.addTarget(self, action: "SELdidClickAddTab", forControlEvents: .TouchUpInside)
addTabButton.accessibilityLabel = NSLocalizedString("Add Tab", comment: "Accessibility label for the Add Tab button in the Tab Tray.")
settingsButton = UIButton()
settingsButton.setImage(UIImage(named: "settings"), forState: .Normal)
settingsButton.addTarget(self, action: "SELdidClickSettingsItem", forControlEvents: .TouchUpInside)
settingsButton.accessibilityLabel = NSLocalizedString("Settings", comment: "Accessibility label for the Settings button in the Tab Tray.")
let flowLayout = TabTrayCollectionViewLayout()
collectionView = UICollectionView(frame: view.frame, collectionViewLayout: flowLayout)
collectionView.dataSource = tabDataSource
collectionView.delegate = tabLayoutDelegate
collectionView.registerClass(TabCell.self, forCellWithReuseIdentifier: TabCell.Identifier)
collectionView.backgroundColor = TabTrayControllerUX.BackgroundColor
view.addSubview(collectionView)
view.addSubview(navBar)
view.addSubview(addTabButton)
view.addSubview(settingsButton)
makeConstraints()
if #available(iOS 9, *) {
view.addSubview(togglePrivateMode)
togglePrivateMode.snp_makeConstraints { make in
make.right.equalTo(addTabButton.snp_left).offset(-10)
make.size.equalTo(UIConstants.ToolbarHeight)
make.centerY.equalTo(self.navBar)
}
view.insertSubview(emptyPrivateTabsView, aboveSubview: collectionView)
emptyPrivateTabsView.hidden = !(privateMode && tabManager.privateTabs.count == 0)
emptyPrivateTabsView.snp_makeConstraints { make in
make.edges.equalTo(self.view)
}
if let tab = tabManager.selectedTab where tab.isPrivate {
privateMode = true
}
}
}
override func traitCollectionDidChange(previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
// Update the trait collection we reference in our layout delegate
tabLayoutDelegate.traitCollection = traitCollection
collectionView.collectionViewLayout.invalidateLayout()
}
override func preferredStatusBarStyle() -> UIStatusBarStyle {
return UIStatusBarStyle.LightContent
}
private func makeConstraints() {
let viewBindings: [String: AnyObject] = [
"topLayoutGuide" : topLayoutGuide,
"navBar" : navBar
]
let topConstraints = NSLayoutConstraint.constraintsWithVisualFormat("V:|[topLayoutGuide][navBar]", options: [], metrics: nil, views: viewBindings)
view.addConstraints(topConstraints)
navBar.snp_makeConstraints { make in
make.height.equalTo(UIConstants.ToolbarHeight)
make.left.right.equalTo(self.view)
}
addTabButton.snp_makeConstraints { make in
make.trailing.bottom.equalTo(self.navBar)
make.size.equalTo(UIConstants.ToolbarHeight)
}
settingsButton.snp_makeConstraints { make in
make.leading.bottom.equalTo(self.navBar)
make.size.equalTo(UIConstants.ToolbarHeight)
}
collectionView.snp_makeConstraints { make in
make.top.equalTo(navBar.snp_bottom)
make.left.right.bottom.equalTo(self.view)
}
}
// MARK: Selectors
func SELdidClickDone() {
presentingViewController!.dismissViewControllerAnimated(true, completion: nil)
}
func SELdidClickSettingsItem() {
let settingsTableViewController = SettingsTableViewController()
settingsTableViewController.profile = profile
settingsTableViewController.tabManager = tabManager
let controller = SettingsNavigationController(rootViewController: settingsTableViewController)
controller.popoverDelegate = self
controller.modalPresentationStyle = UIModalPresentationStyle.FormSheet
presentViewController(controller, animated: true, completion: nil)
}
func SELdidClickAddTab() {
if #available(iOS 9, *) {
if privateMode {
emptyPrivateTabsView.hidden = true
}
}
// We're only doing one update here, but using a batch update lets us delay selecting the tab
// until after its insert animation finishes.
self.collectionView.performBatchUpdates({ _ in
var tab: Browser
if #available(iOS 9, *) {
tab = self.tabManager.addTab(isPrivate: self.privateMode)
} else {
tab = self.tabManager.addTab()
}
self.tabManager.selectTab(tab)
}, completion: { finished in
if finished {
self.navigationController?.popViewControllerAnimated(true)
}
})
}
@available(iOS 9, *)
func SELdidTogglePrivateMode() {
privateMode = !privateMode
}
}
extension TabTrayController: TabSelectionDelegate {
func didSelectTabAtIndex(index: Int) {
let tab = tabsToDisplay[index]
tabManager.selectTab(tab)
self.navigationController?.popViewControllerAnimated(true)
}
}
extension TabTrayController: PresentingModalViewControllerDelegate {
func dismissPresentedModalViewController(modalViewController: UIViewController, animated: Bool) {
dismissViewControllerAnimated(animated, completion: { self.collectionView.reloadData() })
}
}
extension TabTrayController: TabManagerDelegate {
func tabManager(tabManager: TabManager, didSelectedTabChange selected: Browser?, previous: Browser?) {
}
func tabManager(tabManager: TabManager, didCreateTab tab: Browser, restoring: Bool) {
}
func tabManager(tabManager: TabManager, didAddTab tab: Browser, restoring: Bool) {
// Get the index of the added tab from it's set (private or normal)
guard let index = tabsToDisplay.indexOf(tab) else { return }
tabDataSource.tabs.append(tab)
self.collectionView.performBatchUpdates({ _ in
self.collectionView.insertItemsAtIndexPaths([NSIndexPath(forItem: index, inSection: 0)])
}, completion: { finished in
if finished {
tabManager.selectTab(tab)
// don't pop the tab tray view controller if it is not in the foreground
if self.presentedViewController == nil {
self.navigationController?.popViewControllerAnimated(true)
}
}
})
}
func tabManager(tabManager: TabManager, didRemoveTab tab: Browser) {
if let removedIndex = removedTabIndexPath {
tabDataSource.tabs.removeAtIndex(removedIndex.item)
removedTabIndexPath = nil
self.collectionView.deleteItemsAtIndexPaths([removedIndex])
// Workaround: On iOS 8.* devices, cells don't get reloaded during the deletion but after the
// animation has finished which causes cells that animate from above to suddenly 'appear'. This
// is fixed on iOS 9 but for iOS 8 we force a reload on non-visible cells during the animation.
if (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_8_3) {
let visibleCount = collectionView.indexPathsForVisibleItems().count
var offscreenIndexPaths = [NSIndexPath]()
for i in 0..<(tabsToDisplay.count - visibleCount) {
offscreenIndexPaths.append(NSIndexPath(forItem: i, inSection: 0))
}
self.collectionView.reloadItemsAtIndexPaths(offscreenIndexPaths)
}
if #available(iOS 9, *) {
if privateMode && tabsToDisplay.count == 0 {
emptyPrivateTabsView.hidden = false
}
}
}
}
func tabManagerDidAddTabs(tabManager: TabManager) {
}
func tabManagerDidRestoreTabs(tabManager: TabManager) {
}
}
extension TabTrayController: UIScrollViewAccessibilityDelegate {
func accessibilityScrollStatusForScrollView(scrollView: UIScrollView) -> String? {
var visibleCells = collectionView.visibleCells() as! [TabCell]
var bounds = collectionView.bounds
bounds = CGRectOffset(bounds, collectionView.contentInset.left, collectionView.contentInset.top)
bounds.size.width -= collectionView.contentInset.left + collectionView.contentInset.right
bounds.size.height -= collectionView.contentInset.top + collectionView.contentInset.bottom
// visible cells do sometimes return also not visible cells when attempting to go past the last cell with VoiceOver right-flick gesture; so make sure we have only visible cells (yeah...)
visibleCells = visibleCells.filter { !CGRectIsEmpty(CGRectIntersection($0.frame, bounds)) }
var indexPaths = visibleCells.map { self.collectionView.indexPathForCell($0)! }
indexPaths.sortInPlace { $0.section < $1.section || ($0.section == $1.section && $0.row < $1.row) }
if indexPaths.count == 0 {
return NSLocalizedString("No tabs", comment: "Message spoken by VoiceOver to indicate that there are no tabs in the Tabs Tray")
}
let firstTab = indexPaths.first!.row + 1
let lastTab = indexPaths.last!.row + 1
let tabCount = collectionView.numberOfItemsInSection(0)
if (firstTab == lastTab) {
let format = NSLocalizedString("Tab %@ of %@", comment: "Message spoken by VoiceOver saying the position of the single currently visible tab in Tabs Tray, along with the total number of tabs. E.g. \"Tab 2 of 5\" says that tab 2 is visible (and is the only visible tab), out of 5 tabs total.")
return String(format: format, NSNumber(integer: firstTab), NSNumber(integer: tabCount))
} else {
let format = NSLocalizedString("Tabs %@ to %@ of %@", comment: "Message spoken by VoiceOver saying the range of tabs that are currently visible in Tabs Tray, along with the total number of tabs. E.g. \"Tabs 8 to 10 of 15\" says tabs 8, 9 and 10 are visible, out of 15 tabs total.")
return String(format: format, NSNumber(integer: firstTab), NSNumber(integer: lastTab), NSNumber(integer: tabCount))
}
}
}
extension TabTrayController: SwipeAnimatorDelegate {
func swipeAnimator(animator: SwipeAnimator, viewDidExitContainerBounds: UIView) {
let tabCell = animator.container as! TabCell
if let indexPath = collectionView.indexPathForCell(tabCell) {
let tab = tabsToDisplay[indexPath.item]
removedTabIndexPath = indexPath
tabManager.removeTab(tab)
UIAccessibilityPostNotification(UIAccessibilityAnnouncementNotification, NSLocalizedString("Closing tab", comment: ""))
}
}
}
extension TabTrayController: TabCellDelegate {
func tabCellDidClose(cell: TabCell) {
let indexPath = collectionView.indexPathForCell(cell)!
let tab = tabsToDisplay[indexPath.item]
removedTabIndexPath = indexPath
tabManager.removeTab(tab)
}
}
private class TabManagerDataSource: NSObject, UICollectionViewDataSource {
unowned var cellDelegate: protocol<TabCellDelegate, SwipeAnimatorDelegate>
var tabs: [Browser]
init(tabs: [Browser], cellDelegate: protocol<TabCellDelegate, SwipeAnimatorDelegate>) {
self.cellDelegate = cellDelegate
self.tabs = tabs
super.init()
}
@objc func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let tabCell = collectionView.dequeueReusableCellWithReuseIdentifier(TabCell.Identifier, forIndexPath: indexPath) as! TabCell
tabCell.animator.delegate = cellDelegate
tabCell.delegate = cellDelegate
let tab = tabs[indexPath.item]
tabCell.style = tab.isPrivate ? .Dark : .Light
tabCell.titleText.text = tab.displayTitle
if !tab.displayTitle.isEmpty {
tabCell.accessibilityLabel = tab.displayTitle
} else {
tabCell.accessibilityLabel = AboutUtils.getAboutComponent(tab.url)
}
tabCell.isAccessibilityElement = true
tabCell.accessibilityHint = NSLocalizedString("Swipe right or left with three fingers to close the tab.", comment: "Accessibility hint for tab tray's displayed tab.")
if let favIcon = tab.displayFavicon {
tabCell.favicon.sd_setImageWithURL(NSURL(string: favIcon.url)!)
} else {
tabCell.favicon.image = UIImage(named: "defaultFavicon")
}
tabCell.background.image = tab.screenshot
return tabCell
}
@objc func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return tabs.count
}
}
@objc protocol TabSelectionDelegate: class {
func didSelectTabAtIndex(index :Int)
}
private class TabLayoutDelegate: NSObject, UICollectionViewDelegateFlowLayout {
weak var tabSelectionDelegate: TabSelectionDelegate?
private var traitCollection: UITraitCollection
private var profile: Profile
private var numberOfColumns: Int {
let compactLayout = profile.prefs.boolForKey("CompactTabLayout") ?? true
// iPhone 4-6+ portrait
if traitCollection.horizontalSizeClass == .Compact && traitCollection.verticalSizeClass == .Regular {
return compactLayout ? TabTrayControllerUX.CompactNumberOfColumnsThin : TabTrayControllerUX.NumberOfColumnsThin
} else {
return TabTrayControllerUX.NumberOfColumnsWide
}
}
init(profile: Profile, traitCollection: UITraitCollection) {
self.profile = profile
self.traitCollection = traitCollection
super.init()
}
private func cellHeightForCurrentDevice() -> CGFloat {
let compactLayout = profile.prefs.boolForKey("CompactTabLayout") ?? true
let shortHeight = (compactLayout ? TabTrayControllerUX.TextBoxHeight * 6 : TabTrayControllerUX.TextBoxHeight * 5)
if self.traitCollection.verticalSizeClass == UIUserInterfaceSizeClass.Compact {
return shortHeight
} else if self.traitCollection.horizontalSizeClass == UIUserInterfaceSizeClass.Compact {
return shortHeight
} else {
return TabTrayControllerUX.TextBoxHeight * 8
}
}
@objc func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAtIndex section: Int) -> CGFloat {
return TabTrayControllerUX.Margin
}
@objc func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
let cellWidth = (collectionView.bounds.width - TabTrayControllerUX.Margin * CGFloat(numberOfColumns + 1)) / CGFloat(numberOfColumns)
return CGSizeMake(cellWidth, self.cellHeightForCurrentDevice())
}
@objc func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets {
return UIEdgeInsetsMake(TabTrayControllerUX.Margin, TabTrayControllerUX.Margin, TabTrayControllerUX.Margin, TabTrayControllerUX.Margin)
}
@objc func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAtIndex section: Int) -> CGFloat {
return TabTrayControllerUX.Margin
}
@objc func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
tabSelectionDelegate?.didSelectTabAtIndex(indexPath.row)
}
}
// There seems to be a bug with UIKit where when the UICollectionView changes its contentSize
// from > frame.size to <= frame.size: the contentSet animation doesn't properly happen and 'jumps' to the
// final state.
// This workaround forces the contentSize to always be larger than the frame size so the animation happens more
// smoothly. This also makes the tabs be able to 'bounce' when there are not enough to fill the screen, which I
// think is fine, but if needed we can disable user scrolling in this case.
private class TabTrayCollectionViewLayout: UICollectionViewFlowLayout {
private override func collectionViewContentSize() -> CGSize {
var calculatedSize = super.collectionViewContentSize()
let collectionViewHeight = collectionView?.bounds.size.height ?? 0
if calculatedSize.height < collectionViewHeight && collectionViewHeight > 0 {
calculatedSize.height = collectionViewHeight + 1
}
return calculatedSize
}
}
// A transparent view with a rectangular border with rounded corners, stroked
// with a semi-transparent white border.
class InnerStrokedView: UIView {
override init(frame: CGRect) {
super.init(frame: frame)
self.backgroundColor = UIColor.clearColor()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func drawRect(rect: CGRect) {
let strokeWidth = 1.0 as CGFloat
let halfWidth = strokeWidth/2 as CGFloat
let path = UIBezierPath(roundedRect: CGRect(x: halfWidth,
y: halfWidth,
width: rect.width - strokeWidth,
height: rect.height - strokeWidth),
cornerRadius: TabTrayControllerUX.CornerRadius)
path.lineWidth = strokeWidth
UIColor.whiteColor().colorWithAlphaComponent(0.2).setStroke()
path.stroke()
}
}
struct EmptyPrivateTabsViewUX {
static let TitleColor = UIColor.whiteColor()
static let TitleFont = UIFont.systemFontOfSize(22, weight: UIFontWeightMedium)
static let DescriptionColor = UIColor.whiteColor()
static let DescriptionFont = UIFont.systemFontOfSize(17)
static let TextMargin: CGFloat = 18
static let MaxDescriptionWidth: CGFloat = 250
}
// View we display when there are no private tabs created
private class EmptyPrivateTabsView: UIView {
private lazy var titleLabel: UILabel = {
let label = UILabel()
label.textColor = EmptyPrivateTabsViewUX.TitleColor
label.font = EmptyPrivateTabsViewUX.TitleFont
label.textAlignment = NSTextAlignment.Center
return label
}()
private var descriptionLabel: UILabel = {
let label = UILabel()
label.textColor = EmptyPrivateTabsViewUX.DescriptionColor
label.font = EmptyPrivateTabsViewUX.DescriptionFont
label.textAlignment = NSTextAlignment.Center
label.numberOfLines = 3
label.preferredMaxLayoutWidth = EmptyPrivateTabsViewUX.MaxDescriptionWidth
return label
}()
private var iconImageView: UIImageView = {
let imageView = UIImageView(image: UIImage(named: "largePrivateMask"))
return imageView
}()
override init(frame: CGRect) {
super.init(frame: frame)
titleLabel.text = NSLocalizedString("Private Browsing",
tableName: "PrivateBrowsing", comment: "Title displayed for when there are no open tabs while in private mode")
descriptionLabel.text = NSLocalizedString("Firefox won't remember any of your history or cookies, but new bookmarks will be saved.",
tableName: "PrivateBrowsing", comment: "Description text displayed when there are no open tabs while in private mode")
// This landed last-minute as a new string that is needed in the EmptyPrivateTabsView
let learnMoreLabelText = NSLocalizedString("Learn More", tableName: "PrivateBrowsing", comment: "Text button displayed when there are no tabs open while in private mode")
addSubview(titleLabel)
addSubview(descriptionLabel)
addSubview(iconImageView)
titleLabel.snp_makeConstraints { make in
make.center.equalTo(self)
}
iconImageView.snp_makeConstraints { make in
make.bottom.equalTo(titleLabel.snp_top).offset(-EmptyPrivateTabsViewUX.TextMargin)
make.centerX.equalTo(self)
}
descriptionLabel.snp_makeConstraints { make in
make.top.equalTo(titleLabel.snp_bottom).offset(EmptyPrivateTabsViewUX.TextMargin)
make.centerX.equalTo(self)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| mpl-2.0 | 998032c86c554f81e1e1bf34d6792b9f | 40.257732 | 304 | 0.69306 | 5.617828 | false | false | false | false |
karnett/CWIT | cwitExample/ViewController.swift | 1 | 1436 | import UIKit
class ViewController: UIViewController {
//Connections to storyboard
@IBOutlet var welcomeLabel: UILabel!
@IBOutlet var nameTextField: UITextField!
@IBOutlet var submitButton: UIButton!
//variables
@objc let segueIdentifer = "welcome"
override func viewDidLoad() {
super.viewDidLoad()
//Any setup code here before the view shows to the user
//customize color for welcome label
self.welcomeLabel.textColor = UIColor.red
self.submitButton.setTitleColor(UIColor.red, for: UIControlState())
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// This function is called when the app is about to crash due ot Memory overload. Dismiss any resources that can be re-created here.
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
//this method is called during execution of a segue, before the next view loads. you can pass data etc.
//here we take the text from our textfield and pass it to the WelcomeViewController's name variable
if segue.identifier == self.segueIdentifer {
//make sure this is the segue we were expecting..
let welcomeVC = segue.destination as? WelcomeViewController
welcomeVC!.name = self.nameTextField.text
}
}
}
| mit | 11e6f12e3125009475d0b74a1dce8f7c | 32.395349 | 140 | 0.655989 | 5.523077 | false | false | false | false |
jpush/jchat-swift | ContacterModule/ViewController/JCGroupListViewController.swift | 1 | 6004 | //
// JCGroupListViewController.swift
// JChat
//
// Created by JIGUANG on 2017/3/16.
// Copyright © 2017年 HXHG. All rights reserved.
//
import UIKit
import JMessage
class JCGroupListViewController: UITableViewController {
var message: JMSGMessage?
var fromUser: JMSGUser?
override func viewDidLoad() {
super.viewDidLoad()
_init()
}
var groupList: [JMSGGroup] = []
private lazy var defaultImage: UIImage? = UIImage.loadImage("com_icon_group_36")
fileprivate var selectGroup: JMSGGroup!
// MARK: - private func
private func _init() {
self.title = "群组"
view.backgroundColor = .white
tableView.separatorStyle = .none
tableView.register(JCTableViewCell.self, forCellReuseIdentifier: "JCGroupListCell")
_getGroupList()
}
private func _getGroupList() {
MBProgressHUD_JChat.showMessage(message: "加载中...", toView: tableView)
JMSGGroup.myGroupArray { (result, error) in
if error == nil {
self.groupList.removeAll()
let gids = result as! [NSNumber]
if gids.count == 0 {
MBProgressHUD_JChat.hide(forView: self.tableView, animated: true)
return
}
for gid in gids {
JMSGGroup.groupInfo(withGroupId: "\(gid)", completionHandler: { (result, error) in
guard let group = result as? JMSGGroup else {
return
}
self.groupList.append(group)
if self.groupList.count == gids.count {
MBProgressHUD_JChat.hide(forView: self.tableView, animated: true)
self.groupList = self.groupList.sorted(by: { (g1, g2) -> Bool in
return g1.displayName().firstCharacter() < g2.displayName().firstCharacter()
})
self.tableView.reloadData()
}
})
}
} else {
MBProgressHUD_JChat.hide(forView: self.tableView, animated: true)
MBProgressHUD_JChat.show(text: "加载失败", view: self.view)
}
}
}
// MARK: - Table view data source
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return groupList.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
return tableView.dequeueReusableCell(withIdentifier: "JCGroupListCell", for: indexPath)
}
override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
let group = groupList[indexPath.row]
cell.textLabel?.text = group.displayName()
cell.imageView?.image = defaultImage
group.largeAvatarData { (data, _, _) in
if let data = data {
cell.imageView?.image = UIImage(data: data)?.resizeImage(CGSize(width: 36, height: 36))
}
}
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 55
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
let group = groupList[indexPath.row]
selectGroup = group
if let message = message {
forwardMessage(message)
return
}
if fromUser != nil {
sendBusinessCard()
return
}
JMSGConversation.createGroupConversation(withGroupId: group.gid) { (result, error) in
if let conv = result as? JMSGConversation {
let vc = JCChatViewController(conversation: conv)
NotificationCenter.default.post(name: NSNotification.Name(rawValue: kUpdateConversation), object: nil, userInfo: nil)
self.navigationController?.pushViewController(vc, animated: true)
}
}
}
private func sendBusinessCard() {
JCAlertView.bulid().setTitle("发送给:\(selectGroup.displayName())")
.setMessage(fromUser!.displayName() + "的名片")
.setDelegate(self)
.addCancelButton("取消")
.addButton("确定")
.setTag(10003)
.show()
}
private func forwardMessage(_ message: JMSGMessage) {
JCAlertView.bulid().setJMessage(message)
.setTitle("发送给:\(selectGroup.displayName())")
.setDelegate(self)
.setTag(10001)
.show()
}
}
extension JCGroupListViewController: UIAlertViewDelegate {
func alertView(_ alertView: UIAlertView, clickedButtonAt buttonIndex: Int) {
if buttonIndex != 1 {
return
}
switch alertView.tag {
case 10001:
JMSGMessage.forwardMessage(message!, target: selectGroup, optionalContent: JMSGOptionalContent.ex.default)
case 10003:
let msg = JMSGMessage.ex.createBusinessCardMessage(gid: selectGroup.gid, userName: fromUser!.username, appKey: fromUser?.appKey ?? "")
JMSGMessage.send(msg, optionalContent: JMSGOptionalContent.ex.default)
default:
break
}
MBProgressHUD_JChat.show(text: "已发送", view: view, 2)
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.1) {
NotificationCenter.default.post(name: NSNotification.Name(rawValue: kReloadAllMessage), object: nil)
}
weak var weakSelf = self
let time: TimeInterval = 2
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + time) {
weakSelf?.dismiss(animated: true, completion: nil)
}
}
}
| mit | 5b68bc0a7ca4d321f9941e14a8391205 | 36.16875 | 146 | 0.587019 | 4.862633 | false | false | false | false |
duliodenis/calcraft | Calcraft/Calcraft/ViewController.swift | 1 | 3668 | //
// ViewController.swift
// Calcraft
//
// Created by Dulio Denis on 10/30/15.
// Copyright © 2015 Dulio Denis. All rights reserved.
//
import UIKit
import AVFoundation
class ViewController: UIViewController {
enum Operation: String {
case Divide = "/"
case Multiply = "x"
case Add = "+"
case Subtract = "-"
case Empty = "Empty"
}
@IBOutlet weak var outputLabel: UILabel!
var buttonSound: AVAudioPlayer!
var currentDisplay = ""
var leftValueString = ""
var rightValueString = ""
var currentOperation: Operation = Operation.Empty
var result = ""
// MARK: View Lifecyle Methods
override func viewDidLoad() {
super.viewDidLoad()
let path = NSBundle.mainBundle().pathForResource("btn", ofType: "wav")
let soundURL = NSURL(fileURLWithPath: path!)
do {
try buttonSound = AVAudioPlayer(contentsOfURL: soundURL)
buttonSound.prepareToPlay()
} catch let err as NSError {
print(err.debugDescription)
}
}
// MARK: Calculator Action Operations
@IBAction func clearTapped(sender: AnyObject) {
playSound()
currentDisplay = ""
leftValueString = ""
rightValueString = ""
currentOperation = Operation.Empty
result = ""
outputLabel.text = "0"
}
@IBAction func numberPressed(button: UIButton!) {
playSound()
currentDisplay += "\(button.tag)"
outputLabel.text = currentDisplay
}
@IBAction func onDivideTapped(sender: AnyObject) {
processOperation(Operation.Divide)
}
@IBAction func onMultiplyTapped(sender: AnyObject) {
processOperation(Operation.Multiply)
}
@IBAction func onSubtractTapped(sender: AnyObject) {
processOperation(Operation.Subtract)
}
@IBAction func onAddTapped(sender: AnyObject) {
processOperation(Operation.Add)
}
@IBAction func onEqualsTapped(sender: AnyObject) {
processOperation(currentOperation)
}
func processOperation(op: Operation) {
playSound()
if currentOperation != Operation.Empty {
// check to see that the user didn't selected multiple operators in a row
if currentDisplay != "" {
rightValueString = currentDisplay
currentDisplay = ""
if currentOperation == Operation.Multiply {
result = "\(Double(leftValueString)! * Double(rightValueString)!)"
} else if currentOperation == Operation.Divide {
result = "\(Double(leftValueString)! / Double(rightValueString)!)"
} else if currentOperation == Operation.Add {
result = "\(Double(leftValueString)! + Double(rightValueString)!)"
} else if currentOperation == Operation.Subtract {
result = "\(Double(leftValueString)! - Double(rightValueString)!)"
}
leftValueString = result
outputLabel.text = result
}
currentOperation = op
} else { // this is the first time an operation has been tapped
leftValueString = currentDisplay
currentDisplay = ""
currentOperation = op
}
}
func playSound() {
if buttonSound.playing {
buttonSound.stop()
}
buttonSound.play()
}
}
| mit | 1131b7d40fee510132374d836a30a8bb | 26.780303 | 86 | 0.562313 | 5.376833 | false | false | false | false |
austinzheng/swift | validation-test/compiler_crashers_fixed/01198-resolvetypedecl.swift | 65 | 1130 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
func a(x: Any, y: Any) -> (((Any, Any) -> Any) -> Any) {
return {
}
struct X<Y> : A {
func b(b: X.Type) {
}
}
class d<c>: NSObject {
init(b: c) {
}
}
protocol a {
}
class b<h : c, i : c where h.g == i> : a {
}
class b<h, i> {
}
protocol c {
}
protocol a : a {
}
class A : A {
}
class B : C {
}
class c {
func b((Any, c))(a: (Any, AnyObject)) {
}
}
protocol b {
}
struct c {
func e() {
}
}
func d<b: Sequence, e where Optional<e> == b.Generat<d>(() -> d) {
}
protocol A {
}
class B {
func d() -> String {
}
}
class C: B, A {
override func d() -> String {
}
func c() -> String {
}
}
func e<T where T: A, T: B>(t: T) {
}
enum S<T> : P {
func f<T>() -> T -> T {
}
}
protocol P {
}
func a(b: Int = 0) {
}
struct c<d, e: b where d.c == e
| apache-2.0 | 02da5be835d0bd61e821d637d0b74b6b | 15.617647 | 79 | 0.586726 | 2.556561 | false | false | false | false |
outfoxx/CryptoSecurity | Sources/BitSet.swift | 1 | 6471 | //
// BitSet.swift
// CryptoSecurity
//
// Copyright © 2019 Outfox, inc.
//
//
// Distributed under the MIT License, See LICENSE for details.
//
import Foundation
/*
A fixed-size sequence of n bits. Bits have indices 0 to n-1.
*/
public struct BitSet {
/* How many bits this object can hold. */
public private(set) var size: Int
/*
We store the bits in a list of unsigned 8-bit integers.
The first entry, `bytes[0]`, is the least significant byte.
*/
private let N = 8
public typealias Byte = UInt8
public fileprivate(set) var bytes: [UInt8]
private let allOnes = ~Byte()
/* Creates a bit set that can hold `size` bits. All bits are initially 0. */
public init(size: Int) {
precondition(size > 0)
self.size = size
// Round up the count to the next multiple of 8.
let n = (size + (N - 1)) / N
bytes = Array(repeating: 0, count: n)
}
public init(value: UInt8) {
self.init(size: 8)
var value = value
for idx in 0 ..< 8 {
self[idx] = value & 0x1 != 0
value = value >> 1
}
}
public init(value: UInt16) {
self.init(size: 16)
var value = value
for idx in 0 ..< 16 {
self[idx] = value & 0x1 != 0
value = value >> 1
}
}
public init(value: UInt32) {
self.init(size: 32)
var value = value
for idx in 0 ..< 32 {
self[idx] = value & 0x1 != 0
value = value >> 1
}
}
public init(value: UInt64) {
self.init(size: 64)
var value = value
for idx in 0 ..< 64 {
self[idx] = value & 0x1 != 0
value = value >> 1
}
}
/* Converts a bit index into an array index and a mask inside the byte. */
private func indexOf(_ i: Int) -> (Int, Byte) {
precondition(i >= 0)
precondition(i < size)
let o = i / N
let m = Byte(i - o * N)
return (o, 1 << m)
}
/* Returns a mask that has 1s for all bits that are in the last byte. */
private func lastByteMask() -> Byte {
let diff = bytes.count * N - size
if diff > 0 {
// Set the highest bit that's still valid.
let mask = 1 << Byte(63 - diff)
// Subtract 1 to turn it into a mask, and add the high bit back in.
return BitSet.Byte(mask | (mask - 1))
}
else {
return allOnes
}
}
/*
If the size is not a multiple of N, then we have to clear out the bits
that we're not using, or bitwise operations between two differently sized
BitSets will go wrong.
*/
fileprivate mutating func clearUnusedBits() {
bytes[bytes.count - 1] &= lastByteMask()
}
/* So you can write bitset[99] = ... */
public subscript(i: Int) -> Bool {
get { return isSet(i) }
set { if newValue { set(i) } else { clear(i) } }
}
/* Sets the bit at the specified index to 1. */
public mutating func set(_ i: Int) {
let (j, m) = indexOf(i)
bytes[j] |= m
}
/* Sets all the bits to 1. */
public mutating func setAll() {
for i in 0 ..< bytes.count {
bytes[i] = allOnes
}
clearUnusedBits()
}
/* Sets the bit at the specified index to 0. */
public mutating func clear(_ i: Int) {
let (j, m) = indexOf(i)
bytes[j] &= ~m
}
/* Sets all the bits to 0. */
public mutating func clearAll() {
for i in 0 ..< bytes.count {
bytes[i] = 0
}
}
/* Changes 0 into 1 and 1 into 0. Returns the new value of the bit. */
public mutating func flip(i: Int) -> Bool {
let (j, m) = indexOf(i)
bytes[j] ^= m
return (bytes[j] & m) != 0
}
/* Determines whether the bit at the specific index is 1 (true) or 0 (false). */
public func isSet(_ i: Int) -> Bool {
let (j, m) = indexOf(i)
return (bytes[j] & m) != 0
}
/*
Returns the number of bits that are 1. Time complexity is O(s) where s is
the number of 1-bits.
*/
public var cardinality: Int {
var count = 0
for var x in bytes {
while x != 0 {
let y = x & ~(x - 1) // find lowest 1-bit
x = x ^ y // and erase it
count += 1
}
}
return count
}
/* Checks if all the bits are set. */
public func all() -> Bool {
for i in 0 ..< bytes.count - 1 {
if bytes[i] != allOnes { return false }
}
return bytes[bytes.count - 1] == lastByteMask()
}
/* Checks if any of the bits are set. */
public func any() -> Bool {
for x in bytes {
if x != 0 { return true }
}
return false
}
/* Checks if none of the bits are set. */
public func none() -> Bool {
for x in bytes {
if x != 0 { return false }
}
return true
}
}
// MARK: - Equality
extension BitSet: Equatable {}
// MARK: - Hashing
extension BitSet: Hashable {}
// MARK: - Bitwise operations
private func copyLargest(_ lhs: BitSet, _ rhs: BitSet) -> BitSet {
return (lhs.bytes.count > rhs.bytes.count) ? lhs : rhs
}
/*
Note: In all of these bitwise operations, lhs and rhs are allowed to have a
different number of bits. The new BitSet always has the larger size.
The extra bits that get added to the smaller BitSet are considered to be 0.
That will strip off the higher bits from the larger BitSet when doing &.
*/
public func & (lhs: BitSet, rhs: BitSet) -> BitSet {
let m = max(lhs.size, rhs.size)
var out = BitSet(size: m)
let n = min(lhs.bytes.count, rhs.bytes.count)
for i in 0 ..< n {
out.bytes[i] = lhs.bytes[i] & rhs.bytes[i]
}
return out
}
public func | (lhs: BitSet, rhs: BitSet) -> BitSet {
var out = copyLargest(lhs, rhs)
let n = min(lhs.bytes.count, rhs.bytes.count)
for i in 0 ..< n {
out.bytes[i] = lhs.bytes[i] | rhs.bytes[i]
}
return out
}
public func ^ (lhs: BitSet, rhs: BitSet) -> BitSet {
var out = copyLargest(lhs, rhs)
let n = min(lhs.bytes.count, rhs.bytes.count)
for i in 0 ..< n {
out.bytes[i] = lhs.bytes[i] ^ rhs.bytes[i]
}
return out
}
public prefix func ~ (rhs: BitSet) -> BitSet {
var out = BitSet(size: rhs.size)
for i in 0 ..< rhs.bytes.count {
out.bytes[i] = ~rhs.bytes[i]
}
out.clearUnusedBits()
return out
}
// MARK: - Debugging
extension UInt8 {
/* Writes the bits in little-endian order, LSB first. */
public func bitsToString() -> String {
var s = ""
var n = self
for _ in 1 ... 8 {
s += ((n & 1 == 1) ? "1" : "0")
n >>= 1
}
return s
}
}
extension BitSet: CustomStringConvertible {
public var description: String {
var s = ""
for x in bytes {
s += x.bitsToString() + " "
}
return s
}
}
| mit | 7b9541bf5d5f5dba109c6fa35c833121 | 21.387543 | 82 | 0.578207 | 3.336772 | false | false | false | false |
didinozka/Projekt_Bakalarka | bp_v1/BeaconData.swift | 1 | 3631 | //
// BeaconData.swift
// bp_v1
//
// Created by Dusan Drabik on 25/03/16.
// Copyright © 2016 Dusan Drabik. All rights reserved.
//
import Foundation
class BeaconData {
// private var _instance: BeaconData!
private var _beaconList = Dictionary<String, String>()
// Main items storage, others refer to this
lazy private var _items = Dictionary<Int, Item>()
lazy private var _beacons = [Beacon]()
lazy private var _showingBeaconsHash = [ShowingBeacon]()
private var RetailerID: String!
lazy private var _favouriteItems = [Int]()
lazy private var _cart = Cart()
private init () {}
static let sharedInstance = BeaconData()
/**
* List of available beacons in database.
* To insert new entry to list use tuple (string, string)
*/
internal var AvailableBeaconList: Dictionary<String, String> {
return _beaconList
}
internal var Items: Dictionary<Int, Item> {
return _items
}
internal var Beacons: [Beacon] {
return _beacons
}
internal var ShowingBeaconsHash: [ShowingBeacon] {
return _showingBeaconsHash
}
internal var Favourites: [Int] {
return _favouriteItems
}
internal var CartObject: Cart? {
return _cart
}
func AddItem(newItem: Item) -> Bool{
// todo Check duplicity idem insertion
_items[newItem.BeaconObject.hash] = newItem
// _items.append(newItem)
return true
}
func AddBeaconDataToList(newEntry: (id: String,uuid: String)) -> Bool {
if (_beaconList.indexForKey(newEntry.id) != nil) {
print("BeaconData:_beaconList: Entry already in list")
return false
}
_beaconList[newEntry.id] = newEntry.uuid
return true
}
func AddShowingBeacon(pair: BeaconItemPair) {
print("BeaconData:AddShowingBeacon: Beacon want to be added to showingBeacons")
let entry: ShowingBeacon = (pair.item.BeaconObject.hash, K.Proximity.COUNT_TO_DELETE)
_showingBeaconsHash.append(entry)
print("BeaconData:AddShowingBeacon: Beacon added to showingBeacons")
}
func RemoveShowingBeacon(entry: BeaconItemPair) {
let entryindex = getShowingItemsIndex(entry.beacon.hash)
let showedBeacon = _showingBeaconsHash[entryindex]
if showedBeacon.countToDelete == 0 {
_showingBeaconsHash.removeAtIndex(entryindex)
}else {
_showingBeaconsHash[entryindex].countToDelete -= 1
}
}
func AddFavouriteItem(item: Item) {
if _favouriteItems.indexOf(item.BeaconObject.hash) != nil {
print("BeaconData:AddFavouriteItem: Duplicity adding, cancelled")
return
}
_favouriteItems.append(item.BeaconObject.hash)
// _favouriteItems.append(item)
print("BeaconData:AddFavouriteItem: Item added to favourites")
}
func RemoveFromFavouriteItems(item: Item) {
let indexToDelete = _favouriteItems.indexOf(item.BeaconObject.hash)
_favouriteItems.removeAtIndex(indexToDelete!)
}
func AddItemToCart(item: Item) {
_cart.addToCart(item)
}
func DiscartCart() {
_cart = Cart()
}
func getShowingItemsIndex(itemHash: Int) -> Int {
var i = 0
for entry in _showingBeaconsHash {
if entry.itemIndex == itemHash {
return i
}
i += 1
}
return -1
}
}
| apache-2.0 | 7ab3027e95f52de3543c7dd0b6b59ce0 | 23.693878 | 93 | 0.604132 | 4.37877 | false | false | false | false |
DanielAsher/UIClosures | UIClosuresExample/UIClosuresExample/ViewController.swift | 2 | 1486 | //
// ViewController.swift
// UIClosuresExample
//
// Created by Zaid on 5/14/15.
// Copyright (c) 2015 ark. All rights reserved.
//
import UIKit
import UIClosures
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let button = UIButton(frame: CGRect(x: 0, y: 0, width: 100, height: 40))
button.center = self.view.center
button.setTitle("Try Me", forState: UIControlState.Normal)
button.setTitleColor(UIColor.blueColor(), forState: UIControlState.Normal)
self.view.addSubview(button)
button.addListener(UIControlEvents.TouchUpInside, listener: {[unowned self] (sender) -> Void in
self.title = "New Viewcontroller title"
let button = sender as! UIButton
button.setTitle("Tested!", forState: UIControlState.Normal)
})
button.onTouchUpInside() {(sender) -> Void in
button.setTitleColor(UIColor.redColor(), forState: UIControlState.Normal)
}
let tap = UITapGestureRecognizer() {(gesture) -> () in
self.view.backgroundColor = UIColor.greenColor()
}
self.view.addGestureRecognizer(tap)
}
dynamic func doTap() {
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit | 84b22adfad896774a4ac79587139883a | 30.617021 | 103 | 0.643338 | 4.64375 | false | false | false | false |
marty-suzuki/QiitaWithFluxSample | Carthage/Checkouts/RxSwift/Tests/RxSwiftTests/Observable+TakeWhileTests.swift | 2 | 9520 | //
// Observable+TakeWhileTests.swift
// Tests
//
// Created by Krunoslav Zaher on 4/29/17.
// Copyright © 2017 Krunoslav Zaher. All rights reserved.
//
import XCTest
import RxSwift
import RxTest
class ObservableTakeWhileTest : RxTest {
}
extension ObservableTakeWhileTest {
func testTakeWhile_Complete_Before() {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
next(90, -1),
next(110, -1),
next(210, 2),
next(260, 5),
next(290, 13),
next(320, 3),
completed(330),
next(350, 7),
next(390, 4),
next(410, 17),
next(450, 8),
next(500, 23),
completed(600)
])
var invoked = 0
let res = scheduler.start { () -> Observable<Int> in
return xs.takeWhile { (num: Int) -> Bool in
invoked += 1
return isPrime(num)
}
}
XCTAssertEqual(res.events, [
next(210, 2),
next(260, 5),
next(290, 13),
next(320, 3),
completed(330)
])
XCTAssertEqual(xs.subscriptions, [
Subscription(200, 330)
])
XCTAssertEqual(4, invoked)
}
func testTakeWhile_Complete_After() {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
next(90, -1),
next(110, -1),
next(210, 2),
next(260, 5),
next(290, 13),
next(320, 3),
next(350, 7),
next(390, 4),
next(410, 17),
next(450, 8),
next(500, 23),
completed(600)
])
var invoked = 0
let res = scheduler.start { () -> Observable<Int> in
return xs.takeWhile { (num: Int) -> Bool in
invoked += 1
return isPrime(num)
}
}
XCTAssertEqual(res.events, [
next(210, 2),
next(260, 5),
next(290, 13),
next(320, 3),
next(350, 7),
completed(390)
])
XCTAssertEqual(xs.subscriptions, [
Subscription(200, 390)
])
XCTAssertEqual(6, invoked)
}
func testTakeWhile_Error_Before() {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
next(90, -1),
next(110, -1),
next(210, 2),
next(260, 5),
error(270, testError),
next(290, 13),
next(320, 3),
next(350, 7),
next(390, 4),
next(410, 17),
next(450, 8),
next(500, 23),
completed(600)
])
var invoked = 0
let res = scheduler.start { () -> Observable<Int> in
return xs.takeWhile { (num: Int) -> Bool in
invoked += 1
return isPrime(num)
}
}
XCTAssertEqual(res.events, [
next(210, 2),
next(260, 5),
error(270, testError)
])
XCTAssertEqual(xs.subscriptions, [
Subscription(200, 270)
])
XCTAssertEqual(2, invoked)
}
func testTakeWhile_Error_After() {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
next(90, -1),
next(110, -1),
next(210, 2),
next(260, 5),
next(290, 13),
next(320, 3),
next(350, 7),
next(390, 4),
next(410, 17),
next(450, 8),
next(500, 23),
error(600, testError),
])
var invoked = 0
let res = scheduler.start { () -> Observable<Int> in
return xs.takeWhile { (num: Int) -> Bool in
invoked += 1
return isPrime(num)
}
}
XCTAssertEqual(res.events, [
next(210, 2),
next(260, 5),
next(290, 13),
next(320, 3),
next(350, 7),
completed(390)
])
XCTAssertEqual(xs.subscriptions, [
Subscription(200, 390)
])
XCTAssertEqual(6, invoked)
}
func testTakeWhile_Dispose_Before() {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
next(90, -1),
next(110, -1),
next(210, 2),
next(260, 5),
next(290, 13),
next(320, 3),
next(350, 7),
next(390, 4),
next(410, 17),
next(450, 8),
next(500, 23),
error(600, testError),
])
var invoked = 0
let res = scheduler.start(disposed: 300) { () -> Observable<Int> in
return xs.takeWhile { (num: Int) -> Bool in
invoked += 1
return isPrime(num)
}
}
XCTAssertEqual(res.events, [
next(210, 2),
next(260, 5),
next(290, 13)
])
XCTAssertEqual(xs.subscriptions, [
Subscription(200, 300)
])
XCTAssertEqual(3, invoked)
}
func testTakeWhile_Dispose_After() {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
next(90, -1),
next(110, -1),
next(210, 2),
next(260, 5),
next(290, 13),
next(320, 3),
next(350, 7),
next(390, 4),
next(410, 17),
next(450, 8),
next(500, 23),
error(600, testError),
])
var invoked = 0
let res = scheduler.start(disposed: 400) { () -> Observable<Int> in
return xs.takeWhile { (num: Int) -> Bool in
invoked += 1
return isPrime(num)
}
}
XCTAssertEqual(res.events, [
next(210, 2),
next(260, 5),
next(290, 13),
next(320, 3),
next(350, 7),
completed(390)
])
XCTAssertEqual(xs.subscriptions, [
Subscription(200, 390)
])
XCTAssertEqual(6, invoked)
}
func testTakeWhile_Zero() {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
next(90, -1),
next(110, -1),
next(205, 100),
next(210, 2),
next(260, 5),
next(290, 13),
next(320, 3),
next(350, 7),
next(390, 4),
next(410, 17),
next(450, 8),
next(500, 23),
error(600, testError),
])
var invoked = 0
let res = scheduler.start(disposed: 300) { () -> Observable<Int> in
return xs.takeWhile { (num: Int) -> Bool in
invoked += 1
return isPrime(num)
}
}
XCTAssertEqual(res.events, [
completed(205)
])
XCTAssertEqual(xs.subscriptions, [
Subscription(200, 205)
])
XCTAssertEqual(1, invoked)
}
func testTakeWhile_Throw() {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
next(90, -1),
next(110, -1),
next(210, 2),
next(260, 5),
next(290, 13),
next(320, 3),
next(350, 7),
next(390, 4),
next(410, 17),
next(450, 8),
next(500, 23),
completed(600)
])
var invoked = 0
let res = scheduler.start() { () -> Observable<Int> in
return xs.takeWhile { num in
invoked += 1
if invoked == 3 {
throw testError
}
return isPrime(num)
}
}
XCTAssertEqual(res.events, [
next(210, 2),
next(260, 5),
error(290, testError)
])
XCTAssertEqual(xs.subscriptions, [
Subscription(200, 290)
])
XCTAssertEqual(3, invoked)
}
#if TRACE_RESOURCES
func testTakeWhileReleasesResourcesOnComplete() {
_ = Observable<Int>.just(1).takeWhile { _ in true }.subscribe()
}
func testTakeWhile1ReleasesResourcesOnError() {
_ = Observable<Int>.error(testError).takeWhile { _ in true }.subscribe()
}
func testTakeWhile2ReleasesResourcesOnError() {
_ = Observable<Int>.just(1).takeWhile { _ -> Bool in throw testError }.subscribe()
}
#endif
}
| mit | 10998782a2d56367bec2d4ddf666fe6c | 24.866848 | 94 | 0.42599 | 4.691474 | false | true | false | false |
blockchain/My-Wallet-V3-iOS | Modules/FeatureProducts/Sources/FeatureProductsDomain/Product.swift | 1 | 1722 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import Foundation
import ToolKit
public struct ProductIdentifier: NewTypeString {
public static let buy: Self = "BUY"
public static let sell: Self = "SELL"
public static let swap: Self = "SWAP"
public static let trade: Self = "TRADE"
public static let depositFiat: Self = "DEPOSIT_FIAT"
public static let depositCrypto: Self = "DEPOSIT_CRYPTO"
public static let depositInterest: Self = "DEPOSIT_INTEREST"
public static let withdrawFiat: Self = "WITHDRAW_FIAT"
public static let withdrawCrypto: Self = "WITHDRAW_CRYPTO"
public var value: String
public init(_ value: String) {
self.value = value
}
}
public struct ProductSuggestedUpgrade: Hashable, Codable {
public let requiredTier: Int
public init(requiredTier: Int) {
self.requiredTier = requiredTier
}
}
public struct ProductValue: Hashable, Identifiable, Codable {
public let id: ProductIdentifier
public let enabled: Bool
public let maxOrdersCap: Int?
public let maxOrdersLeft: Int?
public let suggestedUpgrade: ProductSuggestedUpgrade?
public let reasonNotEligible: ProductIneligibility?
public init(
id: ProductIdentifier,
enabled: Bool,
maxOrdersCap: Int? = nil,
maxOrdersLeft: Int? = nil,
suggestedUpgrade: ProductSuggestedUpgrade? = nil,
reasonNotEligible: ProductIneligibility? = nil
) {
self.id = id
self.enabled = enabled
self.maxOrdersCap = maxOrdersCap
self.maxOrdersLeft = maxOrdersLeft
self.suggestedUpgrade = suggestedUpgrade
self.reasonNotEligible = reasonNotEligible
}
}
| lgpl-3.0 | 796d74c4bc15f724ff54504a4cbfb944 | 29.192982 | 64 | 0.693202 | 4.281095 | false | false | false | false |
eriklu/qch | View/QCHTextFieldEx.swift | 1 | 2145 | import UIKit
@IBDesignable
class QCHTextFieldEx: UITextField {
enum PattrenFilter: String {
case number = "[^0-9]"
case alphabet = "[^a-zA-Z]"
case lowerAlphabet = "[^a-z]"
case upperAlphabet = "[^A-Z]"
case numberAndAlphabet = "[^0-9a-zA-Z]"
case wechat = "[^_\\-0-9a-zA-Z]"
case chineseCharacter = "[^\\u4e00-\\u9fa5]"
}
//允许的最大长度: 0:无限制; other: 最大长度
@IBInspectable
var maxLength: Int = 0
//过滤模式:正则表达式
@IBInspectable
var pattrenFilter : String = "" {
didSet {
if pattrenFilter != "" {
patternMatcher = try? NSRegularExpression(pattern: pattrenFilter, options: .caseInsensitive)
}else {
patternMatcher = nil
}
}
}
//错误提示函数
var funcShowTip: ((String) -> Void)?
private var patternMatcher : NSRegularExpression?
override init(frame: CGRect) {
super.init(frame: frame)
addTarget(self, action: #selector(qch_textFieldDidChange(_:)), for: .editingChanged)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
addTarget(self, action: #selector(qch_textFieldDidChange(_:)), for: .editingChanged)
}
@objc private func qch_textFieldDidChange(_ tf : UITextField) {
if tf.markedTextRange != nil {
return
}
if patternMatcher != nil {
var text = tf.text!
text = patternMatcher!.stringByReplacingMatches(in: text, options: .reportCompletion, range: NSMakeRange(0, text.characters.count), withTemplate: "")
if tf.text! != text {
tf.text = text
}
}
if maxLength > 0 {
if tf.text!.characters.count > maxLength {
tf.text = tf.text?.substring(to: tf.text!.index(tf.text!.startIndex, offsetBy: maxLength))
funcShowTip?("内容超过最大允许长度\(maxLength)")
}
}
}
}
| mit | 48dc22acde00be9c7e08a83b02c80c8e | 28.528571 | 161 | 0.540881 | 4.342437 | false | false | false | false |
pyanfield/ataturk_olympic | swift_programming_extensions.playground/section-1.swift | 1 | 3686 | // Playground - noun: a place where people can play
import UIKit
// 2.20
// 扩展就是向一个已有的类、结构体或枚举类型添加新功能(functionality)。
// 扩展和 Objective-C 中的分类(categories)类似。(不过与Objective-C不同的是,Swift 的扩展没有名字。)
// Swift 中的扩展可以:
// 添加计算型属性和计算静态属性
// 定义实例方法和类型方法
// 提供新的构造器
// 定义下标
// 定义和使用新的嵌套类型
// 使一个已有类型符合某个协议
// 声明一个扩展使用关键字extension:
// extension SomeType: SomeProtocol, AnotherProctocol {
// // 协议实现写到这里
// }
extension Double {
var km: Double { return self * 1_000.0 }
var m : Double { return self }
var cm: Double { return self / 100.0 }
var mm: Double { return self / 1_000.0 }
var ft: Double { return self / 3.28084 }
}
let oneInch = 25.4.mm
println("One inch is \(oneInch) meters")
let threeFeet = 3.ft
println("Three feet is \(threeFeet) meters")
// 扩展可以添加新的计算属性,但是不可以添加存储属性,也不可以向已有属性添加属性观测器(property observers)。
// 扩展能向类中添加新的便利构造器,但是它们不能向类中添加新的指定构造器或析构函数。指定构造器和析构函数必须总是由原始的类实现来提供。
struct Size {
var width = 0.0, height = 0.0
}
struct Point {
var x = 0.0, y = 0.0
}
struct Rect {
var origin = Point()
var size = Size()
}
let defaultRect = Rect()
let memberwiseRect = Rect(origin: Point(x: 2.0, y: 2.0),
size: Size(width: 5.0, height: 5.0))
extension Rect {
init(center: Point, size: Size) {
let originX = center.x - (size.width / 2)
let originY = center.y - (size.height / 2)
self.init(origin: Point(x: originX, y: originY), size: size)
}
}
let centerRect = Rect(center: Point(x: 4.0, y: 4.0),
size: Size(width: 3.0, height: 3.0))
// 扩展方法 Methods
extension Int{
// 传入的时一个没有参数没有返回值的函数
func repetitions(task: () -> ()){
for i in 0..<self{
task()
}
}
// 结构体和枚举类型中修改self或其属性的方法必须将该实例方法标注为mutating,正如来自原始实现的修改方法一样。
mutating func square(){
self = self * self
}
subscript(digitIndex: Int) -> Int{
var decimalBase = 1
for _ in 1...digitIndex{
decimalBase *= 10
}
return (self / decimalBase) % 10
}
}
3.repetitions{
println("Test repetition function on Int")
}
var three = 3
three.square()
println(three)
println(12345678[5])
// 扩展添加嵌套类型
extension Character {
enum Kind {
case Vowel, Consonant, Other
}
var kind: Kind {
switch String(self).lowercaseString {
case "a", "e", "i", "o", "u":
return .Vowel
case "b", "c", "d", "f", "g", "h", "j", "k", "l", "m",
"n", "p", "q", "r", "s", "t", "v", "w", "x", "y", "z":
return .Consonant
default:
return .Other
}
}
}
func printLetterKinds(word: String) {
println("'\(word)' is made up of the following kinds of letters:")
for character in word {
switch character.kind {
case .Vowel:
print("vowel ")
case .Consonant:
print("consonant ")
case .Other:
print("other ")
}
}
print("\n")
}
printLetterKinds("Hello")
| mit | 46bd0c979b6ea6fb37e15b845c68f3b1 | 21.781955 | 73 | 0.568647 | 3.09816 | false | false | false | false |
Karumi/MarvelApiClient | MarvelApiClient/ThumbnailDTO.swift | 1 | 1476 | //
// ThumbnailDTO.swift
// MarvelAPIClient
//
// Created by Pedro Vicente Gomez on 16/11/15.
// Copyright © 2015 GoKarumi S.L. All rights reserved.
//
import Foundation
public struct ThumbnailDTO {
public let path: String
public let format: String
public func URL(variant: ThumbnailDTOVariant) -> NSURL? {
switch variant {
case .fullSize:
return NSURL(string: "\(path).\(format)")
default:
return NSURL(string: "\(path)/\(variant.rawValue).\(format)")
}
}
}
public enum ThumbnailDTOVariant: String {
case portraitSmall = "portrait_small"
case portraitMedium = "portrait_medium"
case portraitExtraLarge = "portrait_xlarge"
case portraitFantastic = "portrait_fantastic"
case portraitUncanny = "portrait_uncanny"
case portratiIncredible = "portrait_incredible"
case standardSmall = "standard_small"
case standardMedium = "standard_medium"
case standardLarge = "standard_large"
case standardExtraLarge = "standard_xlarge"
case standardFantastic = "standard_fantastic"
case standardAmazing = "standard_amazing"
case landspaceSmall = "landscape_small"
case landscapeMedium = "landscape_medium"
case landscapeLarge = "landscape_large"
case landscapeExtraLarge = "landscape_xlarge"
case landscapeAmazing = "landscape_amazing"
case landscapeIncredible = "landscape_incredible"
case detail = "detail"
case fullSize
}
| apache-2.0 | 899e24a4b1ee810d1032e2c28075a978 | 26.830189 | 73 | 0.690169 | 4.120112 | false | false | false | false |
abertelrud/swift-package-manager | Sources/SPMTestSupport/MockHashAlgorithm.swift | 2 | 1096 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift open source project
//
// Copyright (c) 2014-2019 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import Basics
import TSCBasic
public class MockHashAlgorithm: HashAlgorithm {
public typealias Handler = (ByteString) -> ByteString
public private(set) var hashes = ThreadSafeArrayStore<ByteString>()
private let handler: Handler?
public init(handler: Handler? = nil) {
self.handler = handler
}
public func hash(_ hash: ByteString) -> ByteString {
if let handler = self.handler {
return handler(hash)
} else {
self.hashes.append(hash)
return ByteString(hash.contents.reversed())
}
}
}
| apache-2.0 | 49708c0f2cb12760d75c3c826eb48e0b | 31.235294 | 80 | 0.576642 | 5.097674 | false | true | false | false |
steryokhin/AsciiArtPlayer | src/AsciiArtPlayer/Pods/Watchdog/Classes/Watchdog.swift | 1 | 2414 | import Foundation
/// Class for logging excessive blocking on the main thread.
@objc final public class Watchdog: NSObject {
fileprivate let pingThread: PingThread
fileprivate static let defaultThreshold = 0.4
/// Convenience initializer that allows you to construct a `WatchDog` object with default behavior.
/// - parameter threshold: number of seconds that must pass to consider the main thread blocked.
/// - parameter strictMode: boolean value that stops the execution whenever the threshold is reached.
public convenience init(threshold: Double = Watchdog.defaultThreshold, strictMode: Bool = false) {
let message = "👮 Main thread was blocked for " + String(format:"%.2f", threshold) + "s 👮"
self.init(threshold: threshold) {
if strictMode {
assertionFailure(message)
} else {
NSLog("%@", message)
}
}
}
/// Default initializer that allows you to construct a `WatchDog` object specifying a custom callback.
/// - parameter threshold: number of seconds that must pass to consider the main thread blocked.
/// - parameter watchdogFiredCallback: a callback that will be called when the the threshold is reached
public init(threshold: Double = Watchdog.defaultThreshold, watchdogFiredCallback: @escaping () -> Void) {
self.pingThread = PingThread(threshold: threshold, handler: watchdogFiredCallback)
self.pingThread.start()
super.init()
}
deinit {
pingThread.cancel()
}
}
private final class PingThread: Thread {
fileprivate var pingTaskIsRunning = false
fileprivate var semaphore = DispatchSemaphore(value: 0)
fileprivate let threshold: Double
fileprivate let handler: () -> Void
init(threshold: Double, handler: @escaping () -> Void) {
self.threshold = threshold
self.handler = handler
}
override func main() {
while !isCancelled {
pingTaskIsRunning = true
DispatchQueue.main.async {
self.pingTaskIsRunning = false
self.semaphore.signal()
}
Thread.sleep(forTimeInterval: threshold)
if pingTaskIsRunning {
handler()
}
_ = semaphore.wait(timeout: DispatchTime.distantFuture)
}
}
}
| mit | a94c9fc72252f14ab6f475efa04a98cb | 35.484848 | 109 | 0.637458 | 5.069474 | false | false | false | false |
apple/swift-nio-transport-services | Sources/NIOTSHTTPClient/main.swift | 1 | 2722 | //===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2017-2021 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
#if canImport(Network)
import NIOCore
import NIOTransportServices
import NIOHTTP1
import Network
@available(OSX 10.14, iOS 12.0, tvOS 12.0, watchOS 6.0, *)
final class HTTP1ClientHandler: ChannelInboundHandler {
typealias OutboundOut = HTTPClientRequestPart
typealias InboundIn = HTTPClientResponsePart
func channelActive(context: ChannelHandlerContext) {
var head = HTTPRequestHead(version: .init(major: 1, minor: 1), method: .GET, uri: "/get")
head.headers.add(name: "Host", value: "httpbin.org")
head.headers.add(name: "User-Agent", value: "SwiftNIO")
context.write(self.wrapOutboundOut(.head(head)), promise: nil)
context.writeAndFlush(self.wrapOutboundOut(.end(nil)), promise: nil)
print("Connected to \(context.channel.remoteAddress!) from \(context.channel.localAddress!)")
}
func channelRead(context: ChannelHandlerContext, data: NIOAny) {
let part = self.unwrapInboundIn(data)
switch part {
case .head(let head):
self.printResponseHead(head)
case .body(let b):
print(b.getString(at: b.readerIndex, length: b.readableBytes)!, separator: "")
case .end:
// Print a newline.
print("")
context.close(promise: nil)
}
}
private func printResponseHead(_ head: HTTPResponseHead) {
print("HTTP/\(head.version.major).\(head.version.minor) \(head.status.code) \(head.status.reasonPhrase)")
for (name, value) in head.headers {
print("\(name): \(value)")
}
print("")
}
}
if #available(OSX 10.14, *) {
let group = NIOTSEventLoopGroup()
let channel = try! NIOTSConnectionBootstrap(group: group)
.connectTimeout(.hours(1))
.channelOption(ChannelOptions.socket(IPPROTO_TCP, TCP_NODELAY), value: 1)
.tlsOptions(NWProtocolTLS.Options())
.channelInitializer { channel in
channel.pipeline.addHTTPClientHandlers().flatMap {
channel.pipeline.addHandler(HTTP1ClientHandler())
}
}.connect(host: "httpbin.org", port: 443).wait()
// Wait for the request to complete
try! channel.closeFuture.wait()
}
#endif
| apache-2.0 | 7301477d8959cad0f00d9fb41b01bc02 | 35.293333 | 113 | 0.617561 | 4.369181 | false | false | false | false |
harlanhaskins/HaroldWorkaround | App/Pods/BRYXBanner/Pod/Classes/Banner.swift | 1 | 15063 | //
// Banner.swift
//
// Created by Harlan Haskins on 7/27/15.
// Copyright (c) 2015 Bryx. All rights reserved.
//
import UIKit
private enum BannerState {
case Showing, Hidden, Gone
}
/// A level of 'springiness' for Banners.
///
/// - None: The banner will slide in and not bounce.
/// - Slight: The banner will bounce a little.
/// - Heavy: The banner will bounce a lot.
public enum BannerSpringiness {
case None, Slight, Heavy
private var springValues: (damping: CGFloat, velocity: CGFloat) {
switch self {
case .None: return (damping: 1.0, velocity: 1.0)
case .Slight: return (damping: 0.7, velocity: 1.5)
case .Heavy: return (damping: 0.6, velocity: 2.0)
}
}
}
/// Banner is a dropdown notification view that presents above the main view controller, but below the status bar.
public class Banner: UIView {
private class func topWindow() -> UIWindow? {
for window in UIApplication.sharedApplication().windows.reverse() {
if window.windowLevel == UIWindowLevelNormal && !window.hidden { return window }
}
return nil
}
private let contentView = UIView()
private let labelView = UIView()
private let backgroundView = UIView()
/// How long the slide down animation should last.
public var animationDuration: NSTimeInterval = 0.4
/// The preferred style of the status bar during display of the banner. Defaults to `.LightContent`.
///
/// If the banner's `adjustsStatusBarStyle` is false, this property does nothing.
public var preferredStatusBarStyle = UIStatusBarStyle.LightContent
/// Whether or not this banner should adjust the status bar style during its presentation. Defaults to `false`.
public var adjustsStatusBarStyle = false
/// How 'springy' the banner should display. Defaults to `.Slight`
public var springiness = BannerSpringiness.Slight
/// The color of the text as well as the image tint color if `shouldTintImage` is `true`.
public var textColor = UIColor.whiteColor() {
didSet {
resetTintColor()
}
}
/// Whether or not the banner should show a shadow when presented.
public var hasShadows = true {
didSet {
resetShadows()
}
}
/// The color of the background view. Defaults to `nil`.
override public var backgroundColor: UIColor? {
get { return backgroundView.backgroundColor }
set { backgroundView.backgroundColor = newValue }
}
/// The opacity of the background view. Defaults to 0.95.
override public var alpha: CGFloat {
get { return backgroundView.alpha }
set { backgroundView.alpha = newValue }
}
/// A block to call when the uer taps on the banner.
public var didTapBlock: (() -> ())?
/// A block to call after the banner has finished dismissing and is off screen.
public var didDismissBlock: (() -> ())?
/// Whether or not the banner should dismiss itself when the user taps. Defaults to `true`.
public var dismissesOnTap = true
/// Whether or not the banner should dismiss itself when the user swipes up. Defaults to `true`.
public var dismissesOnSwipe = true
/// Whether or not the banner should tint the associated image to the provided `textColor`. Defaults to `true`.
public var shouldTintImage = true {
didSet {
resetTintColor()
}
}
/// The label that displays the banner's title.
public let titleLabel: UILabel = {
let label = UILabel()
label.font = UIFont.preferredFontForTextStyle(UIFontTextStyleHeadline)
label.numberOfLines = 0
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
/// The label that displays the banner's subtitle.
public let detailLabel: UILabel = {
let label = UILabel()
label.font = UIFont.preferredFontForTextStyle(UIFontTextStyleSubheadline)
label.numberOfLines = 0
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
/// The image on the left of the banner.
let image: UIImage?
/// The image view that displays the `image`.
public let imageView: UIImageView = {
let imageView = UIImageView()
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.contentMode = .ScaleAspectFit
return imageView
}()
private var bannerState = BannerState.Hidden {
didSet {
if bannerState != oldValue {
forceUpdates()
}
}
}
/// A Banner with the provided `title`, `subtitle`, and optional `image`, ready to be presented with `show()`.
///
/// - parameter title: The title of the banner. Optional. Defaults to nil.
/// - parameter subtitle: The subtitle of the banner. Optional. Defaults to nil.
/// - parameter image: The image on the left of the banner. Optional. Defaults to nil.
/// - parameter backgroundColor: The color of the banner's background view. Defaults to `UIColor.blackColor()`.
/// - parameter didTapBlock: An action to be called when the user taps on the banner. Optional. Defaults to `nil`.
public required init(title: String? = nil, subtitle: String? = nil, image: UIImage? = nil, backgroundColor: UIColor = UIColor.blackColor(), didTapBlock: (() -> ())? = nil) {
self.didTapBlock = didTapBlock
self.image = image
super.init(frame: CGRectZero)
resetShadows()
addGestureRecognizers()
initializeSubviews()
resetTintColor()
titleLabel.text = title
detailLabel.text = subtitle
backgroundView.backgroundColor = backgroundColor
backgroundView.alpha = 0.95
}
private func forceUpdates() {
guard let superview = superview, showingConstraint = showingConstraint, hiddenConstraint = hiddenConstraint else { return }
switch bannerState {
case .Hidden:
superview.removeConstraint(showingConstraint)
superview.addConstraint(hiddenConstraint)
case .Showing:
superview.removeConstraint(hiddenConstraint)
superview.addConstraint(showingConstraint)
case .Gone:
superview.removeConstraint(hiddenConstraint)
superview.removeConstraint(showingConstraint)
superview.removeConstraints(commonConstraints)
}
setNeedsLayout()
setNeedsUpdateConstraints()
layoutIfNeeded()
updateConstraintsIfNeeded()
}
internal func didTap(recognizer: UITapGestureRecognizer) {
if dismissesOnTap {
dismiss()
}
didTapBlock?()
}
internal func didSwipe(recognizer: UISwipeGestureRecognizer) {
if dismissesOnSwipe {
dismiss()
}
}
private func addGestureRecognizers() {
addGestureRecognizer(UITapGestureRecognizer(target: self, action: "didTap:"))
let swipe = UISwipeGestureRecognizer(target: self, action: "didSwipe:")
swipe.direction = .Up
addGestureRecognizer(swipe)
}
private func resetTintColor() {
titleLabel.textColor = textColor
detailLabel.textColor = textColor
imageView.image = shouldTintImage ? image?.imageWithRenderingMode(.AlwaysTemplate) : image
imageView.tintColor = shouldTintImage ? textColor : nil
}
private func resetShadows() {
layer.shadowColor = UIColor.blackColor().CGColor
layer.shadowOpacity = self.hasShadows ? 0.5 : 0.0
layer.shadowOffset = CGSize(width: 0, height: 0)
layer.shadowRadius = 4
}
private func initializeSubviews() {
let views = [
"backgroundView": backgroundView,
"contentView": contentView,
"imageView": imageView,
"labelView": labelView,
"titleLabel": titleLabel,
"detailLabel": detailLabel
]
translatesAutoresizingMaskIntoConstraints = false
addSubview(backgroundView)
backgroundView.translatesAutoresizingMaskIntoConstraints = false
addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[backgroundView]|", options: .DirectionLeadingToTrailing, metrics: nil, views: views))
addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[backgroundView(>=80)]|", options: .DirectionLeadingToTrailing, metrics: nil, views: views))
backgroundView.backgroundColor = backgroundColor
contentView.translatesAutoresizingMaskIntoConstraints = false
backgroundView.addSubview(contentView)
labelView.translatesAutoresizingMaskIntoConstraints = false
contentView.addSubview(labelView)
labelView.addSubview(titleLabel)
labelView.addSubview(detailLabel)
let statusBarSize = UIApplication.sharedApplication().statusBarFrame.size
let heightOffset = min(statusBarSize.height, statusBarSize.width) // Arbitrary, but looks nice.
for format in ["H:|[contentView]|", "V:|-(\(heightOffset))-[contentView]|"] {
backgroundView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat(format, options: .DirectionLeadingToTrailing, metrics: nil, views: views))
}
let leftConstraintText: String
if image == nil {
leftConstraintText = "|"
} else {
contentView.addSubview(imageView)
contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-(15)-[imageView]", options: .DirectionLeadingToTrailing, metrics: nil, views: views))
contentView.addConstraint(NSLayoutConstraint(item: imageView, attribute: .CenterY, relatedBy: .Equal, toItem: contentView, attribute: .CenterY, multiplier: 1.0, constant: 0.0))
imageView.addConstraint(NSLayoutConstraint(item: imageView, attribute: .Width, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1.0, constant: 25.0))
imageView.addConstraint(NSLayoutConstraint(item: imageView, attribute: .Height, relatedBy: .Equal, toItem: imageView, attribute: .Width, multiplier: 1.0, constant: 0.0))
leftConstraintText = "[imageView]"
}
let constraintFormat = "H:\(leftConstraintText)-(15)-[labelView]-(8)-|"
contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat(constraintFormat, options: .DirectionLeadingToTrailing, metrics: nil, views: views))
contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-(>=1)-[labelView]-(>=1)-|", options: .DirectionLeadingToTrailing, metrics: nil, views: views))
backgroundView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[contentView]-(<=1)-[labelView]", options: .AlignAllCenterY, metrics: nil, views: views))
for view in [titleLabel, detailLabel] {
let constraintFormat = "H:|-(15)-[label]-(8)-|"
contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat(constraintFormat, options: .DirectionLeadingToTrailing, metrics: nil, views: ["label": view]))
}
labelView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-(10)-[titleLabel][detailLabel]-(10)-|", options: .DirectionLeadingToTrailing, metrics: nil, views: views))
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private var showingConstraint: NSLayoutConstraint?
private var hiddenConstraint: NSLayoutConstraint?
private var commonConstraints = [NSLayoutConstraint]()
override public func didMoveToSuperview() {
super.didMoveToSuperview()
guard let superview = superview where bannerState != .Gone else { return }
commonConstraints = NSLayoutConstraint.constraintsWithVisualFormat("H:|[banner]|", options: .DirectionLeadingToTrailing, metrics: nil, views: ["banner": self])
superview.addConstraints(commonConstraints)
let yOffset: CGFloat = -7.0 // Offset the bottom constraint to make room for the shadow to animate off screen.
showingConstraint = NSLayoutConstraint(item: self, attribute: .Top, relatedBy: .Equal, toItem: superview, attribute: .Top, multiplier: 1.0, constant: yOffset)
hiddenConstraint = NSLayoutConstraint(item: self, attribute: .Bottom, relatedBy: .Equal, toItem: superview, attribute: .Top, multiplier: 1.0, constant: yOffset)
}
/// Shows the banner. If a view is specified, the banner will be displayed at the top of that view, otherwise at top of the top window. If a `duration` is specified, the banner dismisses itself automatically after that duration elapses.
/// - parameter view: A view the banner will be shown in. Optional. Defaults to 'nil', which in turn means it will be shown in the top window. duration A time interval, after which the banner will dismiss itself. Optional. Defaults to `nil`.
public func show(view view: UIView? = Banner.topWindow(), duration: NSTimeInterval? = nil) {
guard let view = view else {
print("[Banner]: Could not find window. Aborting.")
return
}
view.addSubview(self)
forceUpdates()
let (damping, velocity) = self.springiness.springValues
let oldStatusBarStyle = UIApplication.sharedApplication().statusBarStyle
if adjustsStatusBarStyle {
UIApplication.sharedApplication().setStatusBarStyle(preferredStatusBarStyle, animated: true)
}
UIView.animateWithDuration(animationDuration, delay: 0.0, usingSpringWithDamping: damping, initialSpringVelocity: velocity, options: .AllowUserInteraction, animations: {
self.bannerState = .Showing
}, completion: { finished in
if let duration = duration {
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(duration * NSTimeInterval(NSEC_PER_SEC))), dispatch_get_main_queue()) {
self.dismiss(self.adjustsStatusBarStyle ? oldStatusBarStyle : nil)
}
}
})
}
/// Dismisses the banner.
public func dismiss(oldStatusBarStyle: UIStatusBarStyle? = nil) {
let (damping, velocity) = self.springiness.springValues
UIView.animateWithDuration(animationDuration, delay: 0.0, usingSpringWithDamping: damping, initialSpringVelocity: velocity, options: .AllowUserInteraction, animations: {
self.bannerState = .Hidden
if let oldStatusBarStyle = oldStatusBarStyle {
UIApplication.sharedApplication().setStatusBarStyle(oldStatusBarStyle, animated: true)
}
}, completion: { finished in
self.bannerState = .Gone
self.removeFromSuperview()
self.didDismissBlock?()
})
}
}
| mit | 7fe26e9b97fff77bf0c845ecfea2d1fe | 46.071875 | 245 | 0.669521 | 5.377722 | false | false | false | false |
Coderian/SwiftedKML | SwiftedKML/Elements/Href.swift | 1 | 1296 | //
// Href.swift
// SwiftedKML
//
// Created by 佐々木 均 on 2016/02/02.
// Copyright © 2016年 S-Parts. All rights reserved.
//
import Foundation
/// KML Href
///
/// [KML 2.2 shcema](http://schemas.opengis.net/kml/2.2.0/ogckml22.xsd)
///
/// <element name="href" type="string">
/// <annotation>
/// <documentation>not anyURI due to $[x] substitution in
/// PhotoOverlay</documentation>
/// </annotation>
/// </element>
public class Href:SPXMLElement,HasXMLElementValue,HasXMLElementSimpleValue {
public static var elementName: String = "href"
public override var parent:SPXMLElement! {
didSet {
// 複数回呼ばれたて同じものがある場合は追加しない
if self.parent.childs.contains(self) == false {
self.parent.childs.insert(self)
switch parent {
case let v as ItemIcon: v.value.href = self
case let v as IconStyleType.Icon: v.value.href = self
default: break
}
}
}
}
public var value: String = ""
public func makeRelation(contents:String, parent:SPXMLElement) -> SPXMLElement{
self.value = contents
self.parent = parent
return parent
}
}
| mit | f42e2acdaecc9620bbb79bfe9bb84058 | 28.5 | 83 | 0.587571 | 3.812308 | false | false | false | false |
ludwigschubert/cs376-project | DesktopHeartRateMonitor/Surge-master/Source/Matrix.swift | 2 | 12586 | // Hyperbolic.swift
//
// Copyright (c) 2014–2015 Mattt Thompson (http://mattt.me)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Accelerate
public enum MatrixAxies {
case row
case column
}
public struct Matrix<T> where T: FloatingPoint, T: ExpressibleByFloatLiteral {
public typealias Element = T
let rows: Int
let columns: Int
var grid: [Element]
public init(rows: Int, columns: Int, repeatedValue: Element) {
self.rows = rows
self.columns = columns
self.grid = [Element](repeating: repeatedValue, count: rows * columns)
}
public init(_ contents: [[Element]]) {
let m: Int = contents.count
let n: Int = contents[0].count
let repeatedValue: Element = 0.0
self.init(rows: m, columns: n, repeatedValue: repeatedValue)
for (i, row) in contents.enumerated() {
grid.replaceSubrange(i*n..<i*n+Swift.min(m, row.count), with: row)
}
}
public subscript(row: Int, column: Int) -> Element {
get {
assert(indexIsValidForRow(row, column: column))
return grid[(row * columns) + column]
}
set {
assert(indexIsValidForRow(row, column: column))
grid[(row * columns) + column] = newValue
}
}
public subscript(row row: Int) -> [Element] {
get {
assert(row < rows)
let startIndex = row * columns
let endIndex = row * columns + columns
return Array(grid[startIndex..<endIndex])
}
set {
assert(row < rows)
assert(newValue.count == columns)
let startIndex = row * columns
let endIndex = row * columns + columns
grid.replaceSubrange(startIndex..<endIndex, with: newValue)
}
}
public subscript(column column: Int) -> [Element] {
get {
var result = [Element](repeating: 0.0, count: rows)
for i in 0..<rows {
let index = i * columns + column
result[i] = self.grid[index]
}
return result
}
set {
assert(column < columns)
assert(newValue.count == rows)
for i in 0..<rows {
let index = i * columns + column
grid[index] = newValue[i]
}
}
}
fileprivate func indexIsValidForRow(_ row: Int, column: Int) -> Bool {
return row >= 0 && row < rows && column >= 0 && column < columns
}
}
// MARK: - Printable
extension Matrix: CustomStringConvertible {
public var description: String {
var description = ""
for i in 0..<rows {
let contents = (0..<columns).map{"\(self[i, $0])"}.joined(separator: "\t")
switch (i, rows) {
case (0, 1):
description += "(\t\(contents)\t)"
case (0, _):
description += "⎛\t\(contents)\t⎞"
case (rows - 1, _):
description += "⎝\t\(contents)\t⎠"
default:
description += "⎜\t\(contents)\t⎥"
}
description += "\n"
}
return description
}
}
// MARK: - SequenceType
extension Matrix: Sequence {
public func makeIterator() -> AnyIterator<ArraySlice<Element>> {
let endIndex = rows * columns
var nextRowStartIndex = 0
return AnyIterator {
if nextRowStartIndex == endIndex {
return nil
}
let currentRowStartIndex = nextRowStartIndex
nextRowStartIndex += self.columns
return self.grid[currentRowStartIndex..<nextRowStartIndex]
}
}
}
extension Matrix: Equatable {}
public func ==<T> (lhs: Matrix<T>, rhs: Matrix<T>) -> Bool {
return lhs.rows == rhs.rows && lhs.columns == rhs.columns && lhs.grid == rhs.grid
}
// MARK: -
public func add(_ x: Matrix<Float>, y: Matrix<Float>) -> Matrix<Float> {
precondition(x.rows == y.rows && x.columns == y.columns, "Matrix dimensions not compatible with addition")
var results = y
cblas_saxpy(Int32(x.grid.count), 1.0, x.grid, 1, &(results.grid), 1)
return results
}
public func add(_ x: Matrix<Double>, y: Matrix<Double>) -> Matrix<Double> {
precondition(x.rows == y.rows && x.columns == y.columns, "Matrix dimensions not compatible with addition")
var results = y
cblas_daxpy(Int32(x.grid.count), 1.0, x.grid, 1, &(results.grid), 1)
return results
}
public func mul(_ alpha: Float, x: Matrix<Float>) -> Matrix<Float> {
var results = x
cblas_sscal(Int32(x.grid.count), alpha, &(results.grid), 1)
return results
}
public func mul(_ alpha: Double, x: Matrix<Double>) -> Matrix<Double> {
var results = x
cblas_dscal(Int32(x.grid.count), alpha, &(results.grid), 1)
return results
}
public func mul(_ x: Matrix<Float>, y: Matrix<Float>) -> Matrix<Float> {
precondition(x.columns == y.rows, "Matrix dimensions not compatible with multiplication")
var results = Matrix<Float>(rows: x.rows, columns: y.columns, repeatedValue: 0.0)
cblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, Int32(x.rows), Int32(y.columns), Int32(x.columns), 1.0, x.grid, Int32(x.columns), y.grid, Int32(y.columns), 0.0, &(results.grid), Int32(results.columns))
return results
}
public func mul(_ x: Matrix<Double>, y: Matrix<Double>) -> Matrix<Double> {
precondition(x.columns == y.rows, "Matrix dimensions not compatible with multiplication")
var results = Matrix<Double>(rows: x.rows, columns: y.columns, repeatedValue: 0.0)
cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, Int32(x.rows), Int32(y.columns), Int32(x.columns), 1.0, x.grid, Int32(x.columns), y.grid, Int32(y.columns), 0.0, &(results.grid), Int32(results.columns))
return results
}
public func elmul(_ x: Matrix<Double>, y: Matrix<Double>) -> Matrix<Double> {
precondition(x.rows == y.rows && x.columns == y.columns, "Matrix must have the same dimensions")
var result = Matrix<Double>(rows: x.rows, columns: x.columns, repeatedValue: 0.0)
result.grid = x.grid * y.grid
return result
}
public func elmul(_ x: Matrix<Float>, y: Matrix<Float>) -> Matrix<Float> {
precondition(x.rows == y.rows && x.columns == y.columns, "Matrix must have the same dimensions")
var result = Matrix<Float>(rows: x.rows, columns: x.columns, repeatedValue: 0.0)
result.grid = x.grid * y.grid
return result
}
public func div(_ x: Matrix<Double>, y: Matrix<Double>) -> Matrix<Double> {
let yInv = inv(y)
precondition(x.columns == yInv.rows, "Matrix dimensions not compatible")
return mul(x, y: yInv)
}
public func div(_ x: Matrix<Float>, y: Matrix<Float>) -> Matrix<Float> {
let yInv = inv(y)
precondition(x.columns == yInv.rows, "Matrix dimensions not compatible")
return mul(x, y: yInv)
}
public func pow(_ x: Matrix<Double>, _ y: Double) -> Matrix<Double> {
var result = Matrix<Double>(rows: x.rows, columns: x.columns, repeatedValue: 0.0)
result.grid = pow(x.grid, y)
return result
}
public func pow(_ x: Matrix<Float>, _ y: Float) -> Matrix<Float> {
var result = Matrix<Float>(rows: x.rows, columns: x.columns, repeatedValue: 0.0)
result.grid = pow(x.grid, y)
return result
}
public func exp(_ x: Matrix<Double>) -> Matrix<Double> {
var result = Matrix<Double>(rows: x.rows, columns: x.columns, repeatedValue: 0.0)
result.grid = exp(x.grid)
return result
}
public func exp(_ x: Matrix<Float>) -> Matrix<Float> {
var result = Matrix<Float>(rows: x.rows, columns: x.columns, repeatedValue: 0.0)
result.grid = exp(x.grid)
return result
}
public func sum(_ x: Matrix<Double>, axies: MatrixAxies = .column) -> Matrix<Double> {
switch axies {
case .column:
var result = Matrix<Double>(rows: 1, columns: x.columns, repeatedValue: 0.0)
for i in 0..<x.columns {
result.grid[i] = sum(x[column: i])
}
return result
case .row:
var result = Matrix<Double>(rows: x.rows, columns: 1, repeatedValue: 0.0)
for i in 0..<x.rows {
result.grid[i] = sum(x[row: i])
}
return result
}
}
public func inv(_ x : Matrix<Float>) -> Matrix<Float> {
precondition(x.rows == x.columns, "Matrix must be square")
var results = x
var ipiv = [__CLPK_integer](repeating: 0, count: x.rows * x.rows)
var lwork = __CLPK_integer(x.columns * x.columns)
var work = [CFloat](repeating: 0.0, count: Int(lwork))
var error: __CLPK_integer = 0
var nc = __CLPK_integer(x.columns)
sgetrf_(&nc, &nc, &(results.grid), &nc, &ipiv, &error)
sgetri_(&nc, &(results.grid), &nc, &ipiv, &work, &lwork, &error)
assert(error == 0, "Matrix not invertible")
return results
}
public func inv(_ x : Matrix<Double>) -> Matrix<Double> {
precondition(x.rows == x.columns, "Matrix must be square")
var results = x
var ipiv = [__CLPK_integer](repeating: 0, count: x.rows * x.rows)
var lwork = __CLPK_integer(x.columns * x.columns)
var work = [CDouble](repeating: 0.0, count: Int(lwork))
var error: __CLPK_integer = 0
var nc = __CLPK_integer(x.columns)
dgetrf_(&nc, &nc, &(results.grid), &nc, &ipiv, &error)
dgetri_(&nc, &(results.grid), &nc, &ipiv, &work, &lwork, &error)
assert(error == 0, "Matrix not invertible")
return results
}
public func transpose(_ x: Matrix<Float>) -> Matrix<Float> {
var results = Matrix<Float>(rows: x.columns, columns: x.rows, repeatedValue: 0.0)
vDSP_mtrans(x.grid, 1, &(results.grid), 1, vDSP_Length(results.rows), vDSP_Length(results.columns))
return results
}
public func transpose(_ x: Matrix<Double>) -> Matrix<Double> {
var results = Matrix<Double>(rows: x.columns, columns: x.rows, repeatedValue: 0.0)
vDSP_mtransD(x.grid, 1, &(results.grid), 1, vDSP_Length(results.rows), vDSP_Length(results.columns))
return results
}
// MARK: - Operators
public func + (lhs: Matrix<Float>, rhs: Matrix<Float>) -> Matrix<Float> {
return add(lhs, y: rhs)
}
public func + (lhs: Matrix<Double>, rhs: Matrix<Double>) -> Matrix<Double> {
return add(lhs, y: rhs)
}
public func * (lhs: Float, rhs: Matrix<Float>) -> Matrix<Float> {
return mul(lhs, x: rhs)
}
public func * (lhs: Double, rhs: Matrix<Double>) -> Matrix<Double> {
return mul(lhs, x: rhs)
}
public func * (lhs: Matrix<Float>, rhs: Matrix<Float>) -> Matrix<Float> {
return mul(lhs, y: rhs)
}
public func * (lhs: Matrix<Double>, rhs: Matrix<Double>) -> Matrix<Double> {
return mul(lhs, y: rhs)
}
public func / (lhs: Matrix<Double>, rhs: Matrix<Double>) -> Matrix<Double> {
return div(lhs, y: rhs)
}
public func / (lhs: Matrix<Float>, rhs: Matrix<Float>) -> Matrix<Float> {
return div(lhs, y: rhs)
}
public func / (lhs: Matrix<Double>, rhs: Double) -> Matrix<Double> {
var result = Matrix<Double>(rows: lhs.rows, columns: lhs.columns, repeatedValue: 0.0)
result.grid = lhs.grid / rhs;
return result;
}
public func / (lhs: Matrix<Float>, rhs: Float) -> Matrix<Float> {
var result = Matrix<Float>(rows: lhs.rows, columns: lhs.columns, repeatedValue: 0.0)
result.grid = lhs.grid / rhs;
return result;
}
postfix operator ′
public postfix func ′ (value: Matrix<Float>) -> Matrix<Float> {
return transpose(value)
}
public postfix func ′ (value: Matrix<Double>) -> Matrix<Double> {
return transpose(value)
}
| mit | b57d854a02cb4fb3f746262f5db86e1f | 31.303342 | 212 | 0.619211 | 3.586187 | false | false | false | false |
rockwotj/shiloh-ranch | ios/shiloh_ranch/shiloh_ranch/AppDelegate.swift | 1 | 2778 | //
// AppDelegate.swift
// shiloh_ranch
//
// Created by Tyler Rockwood on 6/1/15.
// Copyright (c) 2015 Shiloh Ranch Cowboy Church. All rights reserved.
//
import UIKit
import AVFoundation
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var service : GTLServiceShilohranch {
if (_service != nil) {
return _service!
}
_service = GTLServiceShilohranch()
_service!.retryEnabled = true
_service!.apiVersion = "v1"
return _service!
}
var _service : GTLServiceShilohranch?
var database : Database {
if (_database != nil) {
return _database!
}
_database = Database()
return _database!
}
var _database : Database?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
CategoriesUpdater().sync()
NewsUpdater().sync()
EventsUpdater().sync()
SermonsUpdater().sync()
DeletionsUpdater().sync()
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| mit | f141ebe47c582bf95e3a36ebd812c434 | 38.685714 | 285 | 0.704104 | 5.116022 | false | false | false | false |
roambotics/swift | stdlib/public/Concurrency/Task.swift | 2 | 35799 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2020 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import Swift
@_implementationOnly import _SwiftConcurrencyShims
// ==== Task -------------------------------------------------------------------
/// A unit of asynchronous work.
///
/// When you create an instance of `Task`,
/// you provide a closure that contains the work for that task to perform.
/// Tasks can start running immediately after creation;
/// you don't explicitly start or schedule them.
/// After creating a task, you use the instance to interact with it ---
/// for example, to wait for it to complete or to cancel it.
/// It's not a programming error to discard a reference to a task
/// without waiting for that task to finish or canceling it.
/// A task runs regardless of whether you keep a reference to it.
/// However, if you discard the reference to a task,
/// you give up the ability
/// to wait for that task's result or cancel the task.
///
/// To support operations on the current task,
/// which can be either a detached task or child task,
/// `Task` also exposes class methods like `yield()`.
/// Because these methods are asynchronous,
/// they're always invoked as part of an existing task.
///
/// Only code that's running as part of the task can interact with that task.
/// To interact with the current task,
/// you call one of the static methods on `Task`.
///
/// A task's execution can be seen as a series of periods where the task ran.
/// Each such period ends at a suspension point or the
/// completion of the task.
/// These periods of execution are represented by instances of `PartialAsyncTask`.
/// Unless you're implementing a custom executor,
/// you don't directly interact with partial tasks.
///
/// For information about the language-level concurrency model that `Task` is part of,
/// see [Concurrency][concurrency] in [The Swift Programming Language][tspl].
///
/// [concurrency]: https://docs.swift.org/swift-book/LanguageGuide/Concurrency.html
/// [tspl]: https://docs.swift.org/swift-book/
///
/// Task Cancellation
/// =================
///
/// Tasks include a shared mechanism for indicating cancellation,
/// but not a shared implementation for how to handle cancellation.
/// Depending on the work you're doing in the task,
/// the correct way to stop that work varies.
/// Likewise,
/// it's the responsibility of the code running as part of the task
/// to check for cancellation whenever stopping is appropriate.
/// In a long-task that includes multiple pieces,
/// you might need to check for cancellation at several points,
/// and handle cancellation differently at each point.
/// If you only need to throw an error to stop the work,
/// call the `Task.checkCancellation()` function to check for cancellation.
/// Other responses to cancellation include
/// returning the work completed so far, returning an empty result, or returning `nil`.
///
/// Cancellation is a purely Boolean state;
/// there's no way to include additional information
/// like the reason for cancellation.
/// This reflects the fact that a task can be canceled for many reasons,
/// and additional reasons can accrue during the cancellation process.
@available(SwiftStdlib 5.1, *)
@frozen
public struct Task<Success: Sendable, Failure: Error>: Sendable {
@usableFromInline
internal let _task: Builtin.NativeObject
@_alwaysEmitIntoClient
internal init(_ task: Builtin.NativeObject) {
self._task = task
}
}
@available(SwiftStdlib 5.1, *)
extension Task {
/// The result from a throwing task, after it completes.
///
/// If the task hasn't completed,
/// accessing this property waits for it to complete
/// and its priority increases to that of the current task.
/// Note that this might not be as effective as
/// creating the task with the correct priority,
/// depending on the executor's scheduling details.
///
/// If the task throws an error, this property propagates that error.
/// Tasks that respond to cancellation by throwing `CancellationError`
/// have that error propagated here upon cancellation.
///
/// - Returns: The task's result.
public var value: Success {
get async throws {
return try await _taskFutureGetThrowing(_task)
}
}
/// The result or error from a throwing task, after it completes.
///
/// If the task hasn't completed,
/// accessing this property waits for it to complete
/// and its priority increases to that of the current task.
/// Note that this might not be as effective as
/// creating the task with the correct priority,
/// depending on the executor's scheduling details.
///
/// - Returns: If the task succeeded,
/// `.success` with the task's result as the associated value;
/// otherwise, `.failure` with the error as the associated value.
public var result: Result<Success, Failure> {
get async {
do {
return .success(try await value)
} catch {
return .failure(error as! Failure) // as!-safe, guaranteed to be Failure
}
}
}
/// Indicates that the task should stop running.
///
/// Task cancellation is cooperative:
/// a task that supports cancellation
/// checks whether it has been canceled at various points during its work.
///
/// Calling this method on a task that doesn't support cancellation
/// has no effect.
/// Likewise, if the task has already run
/// past the last point where it would stop early,
/// calling this method has no effect.
///
/// - SeeAlso: `Task.checkCancellation()`
public func cancel() {
Builtin.cancelAsyncTask(_task)
}
}
@available(SwiftStdlib 5.1, *)
extension Task where Failure == Never {
/// The result from a nonthrowing task, after it completes.
///
/// If the task hasn't completed yet,
/// accessing this property waits for it to complete
/// and its priority increases to that of the current task.
/// Note that this might not be as effective as
/// creating the task with the correct priority,
/// depending on the executor's scheduling details.
///
/// Tasks that never throw an error can still check for cancellation,
/// but they need to use an approach like returning `nil`
/// instead of throwing an error.
public var value: Success {
get async {
return await _taskFutureGet(_task)
}
}
}
@available(SwiftStdlib 5.1, *)
extension Task: Hashable {
public func hash(into hasher: inout Hasher) {
UnsafeRawPointer(Builtin.bridgeToRawPointer(_task)).hash(into: &hasher)
}
}
@available(SwiftStdlib 5.1, *)
extension Task: Equatable {
public static func ==(lhs: Self, rhs: Self) -> Bool {
UnsafeRawPointer(Builtin.bridgeToRawPointer(lhs._task)) ==
UnsafeRawPointer(Builtin.bridgeToRawPointer(rhs._task))
}
}
// ==== Task Priority ----------------------------------------------------------
/// The priority of a task.
///
/// The executor determines how priority information affects the way tasks are scheduled.
/// The behavior varies depending on the executor currently being used.
/// Typically, executors attempt to run tasks with a higher priority
/// before tasks with a lower priority.
/// However, the semantics of how priority is treated are left up to each
/// platform and `Executor` implementation.
///
/// Child tasks automatically inherit their parent task's priority.
/// Detached tasks created by `detach(priority:operation:)` don't inherit task priority
/// because they aren't attached to the current task.
///
/// In some situations the priority of a task is elevated ---
/// that is, the task is treated as it if had a higher priority,
/// without actually changing the priority of the task:
///
/// - If a task runs on behalf of an actor,
/// and a new higher-priority task is enqueued to the actor,
/// then the actor's current task is temporarily elevated
/// to the priority of the enqueued task.
/// This priority elevation allows the new task
/// to be processed at the priority it was enqueued with.
/// - If a a higher-priority task calls the `get()` method,
/// then the priority of this task increases until the task completes.
///
/// In both cases, priority elevation helps you prevent a low-priority task
/// from blocking the execution of a high priority task,
/// which is also known as *priority inversion*.
@available(SwiftStdlib 5.1, *)
public struct TaskPriority: RawRepresentable, Sendable {
public typealias RawValue = UInt8
public var rawValue: UInt8
public init(rawValue: UInt8) {
self.rawValue = rawValue
}
public static let high: TaskPriority = .init(rawValue: 0x19)
@_alwaysEmitIntoClient
public static var medium: TaskPriority {
.init(rawValue: 0x15)
}
public static let low: TaskPriority = .init(rawValue: 0x11)
public static let userInitiated: TaskPriority = high
public static let utility: TaskPriority = low
public static let background: TaskPriority = .init(rawValue: 0x09)
@available(*, deprecated, renamed: "medium")
public static let `default`: TaskPriority = .init(rawValue: 0x15)
}
@available(SwiftStdlib 5.1, *)
extension TaskPriority: Equatable {
public static func == (lhs: TaskPriority, rhs: TaskPriority) -> Bool {
lhs.rawValue == rhs.rawValue
}
public static func != (lhs: TaskPriority, rhs: TaskPriority) -> Bool {
lhs.rawValue != rhs.rawValue
}
}
@available(SwiftStdlib 5.1, *)
extension TaskPriority: Comparable {
public static func < (lhs: TaskPriority, rhs: TaskPriority) -> Bool {
lhs.rawValue < rhs.rawValue
}
public static func <= (lhs: TaskPriority, rhs: TaskPriority) -> Bool {
lhs.rawValue <= rhs.rawValue
}
public static func > (lhs: TaskPriority, rhs: TaskPriority) -> Bool {
lhs.rawValue > rhs.rawValue
}
public static func >= (lhs: TaskPriority, rhs: TaskPriority) -> Bool {
lhs.rawValue >= rhs.rawValue
}
}
@available(SwiftStdlib 5.1, *)
extension TaskPriority: Codable { }
@available(SwiftStdlib 5.1, *)
extension Task where Success == Never, Failure == Never {
/// The current task's priority.
///
/// If you access this property outside of any task,
/// this queries the system to determine the
/// priority at which the current function is running.
/// If the system can't provide a priority,
/// this property's value is `Priority.default`.
public static var currentPriority: TaskPriority {
withUnsafeCurrentTask { task in
// If we are running on behalf of a task, use that task's priority.
if let unsafeTask = task {
return TaskPriority(rawValue: _taskCurrentPriority(unsafeTask._task))
}
// Otherwise, query the system.
return TaskPriority(rawValue: UInt8(_getCurrentThreadPriority()))
}
}
/// The current task's base priority.
///
/// If you access this property outside of any task, this returns nil
@available(SwiftStdlib 5.7, *)
public static var basePriority: TaskPriority? {
withUnsafeCurrentTask { task in
// If we are running on behalf of a task, use that task's priority.
if let unsafeTask = task {
return TaskPriority(rawValue: _taskBasePriority(unsafeTask._task))
}
return nil
}
}
}
@available(SwiftStdlib 5.1, *)
extension TaskPriority {
/// Downgrade user-interactive to user-initiated.
var _downgradeUserInteractive: TaskPriority {
return self
}
}
// ==== Job Flags --------------------------------------------------------------
/// Flags for schedulable jobs.
///
/// This is a port of the C++ FlagSet.
@available(SwiftStdlib 5.1, *)
struct JobFlags {
/// Kinds of schedulable jobs.
enum Kind: Int32 {
case task = 0
}
/// The actual bit representation of these flags.
var bits: Int32 = 0
/// The kind of job described by these flags.
var kind: Kind {
get {
Kind(rawValue: bits & 0xFF)!
}
set {
bits = (bits & ~0xFF) | newValue.rawValue
}
}
/// Whether this is an asynchronous task.
var isAsyncTask: Bool { kind == .task }
/// The priority given to the job.
var priority: TaskPriority? {
get {
let value = (Int(bits) & 0xFF00) >> 8
if value == 0 {
return nil
}
return TaskPriority(rawValue: UInt8(value))
}
set {
bits = (bits & ~0xFF00) | Int32((Int(newValue?.rawValue ?? 0) << 8))
}
}
/// Whether this is a child task.
var isChildTask: Bool {
get {
(bits & (1 << 24)) != 0
}
set {
if newValue {
bits = bits | 1 << 24
} else {
bits = (bits & ~(1 << 24))
}
}
}
/// Whether this is a future.
var isFuture: Bool {
get {
(bits & (1 << 25)) != 0
}
set {
if newValue {
bits = bits | 1 << 25
} else {
bits = (bits & ~(1 << 25))
}
}
}
/// Whether this is a group child.
var isGroupChildTask: Bool {
get {
(bits & (1 << 26)) != 0
}
set {
if newValue {
bits = bits | 1 << 26
} else {
bits = (bits & ~(1 << 26))
}
}
}
/// Whether this is a task created by the 'async' operation, which
/// conceptually continues the work of the synchronous code that invokes
/// it.
var isContinuingAsyncTask: Bool {
get {
(bits & (1 << 27)) != 0
}
set {
if newValue {
bits = bits | 1 << 27
} else {
bits = (bits & ~(1 << 27))
}
}
}
}
// ==== Task Creation Flags --------------------------------------------------
/// Form task creation flags for use with the createAsyncTask builtins.
@available(SwiftStdlib 5.1, *)
@_alwaysEmitIntoClient
func taskCreateFlags(
priority: TaskPriority?, isChildTask: Bool, copyTaskLocals: Bool,
inheritContext: Bool, enqueueJob: Bool,
addPendingGroupTaskUnconditionally: Bool
) -> Int {
var bits = 0
bits |= (bits & ~0xFF) | Int(priority?.rawValue ?? 0)
if isChildTask {
bits |= 1 << 8
}
if copyTaskLocals {
bits |= 1 << 10
}
if inheritContext {
bits |= 1 << 11
}
if enqueueJob {
bits |= 1 << 12
}
if addPendingGroupTaskUnconditionally {
bits |= 1 << 13
}
return bits
}
// ==== Task Creation ----------------------------------------------------------
@available(SwiftStdlib 5.1, *)
extension Task where Failure == Never {
#if SWIFT_STDLIB_TASK_TO_THREAD_MODEL_CONCURRENCY
@discardableResult
@_alwaysEmitIntoClient
@available(*, unavailable, message: "Unavailable in task-to-thread concurrency model")
public init(
priority: TaskPriority? = nil,
@_inheritActorContext @_implicitSelfCapture operation: __owned @Sendable @escaping () async -> Success
) {
fatalError("Unavailable in task-to-thread concurrency model.")
}
#else
/// Runs the given nonthrowing operation asynchronously
/// as part of a new top-level task on behalf of the current actor.
///
/// Use this function when creating asynchronous work
/// that operates on behalf of the synchronous function that calls it.
/// Like `Task.detached(priority:operation:)`,
/// this function creates a separate, top-level task.
/// Unlike `Task.detached(priority:operation:)`,
/// the task created by `Task.init(priority:operation:)`
/// inherits the priority and actor context of the caller,
/// so the operation is treated more like an asynchronous extension
/// to the synchronous operation.
///
/// You need to keep a reference to the task
/// if you want to cancel it by calling the `Task.cancel()` method.
/// Discarding your reference to a detached task
/// doesn't implicitly cancel that task,
/// it only makes it impossible for you to explicitly cancel the task.
///
/// - Parameters:
/// - priority: The priority of the task.
/// Pass `nil` to use the priority from `Task.currentPriority`.
/// - operation: The operation to perform.
@discardableResult
@_alwaysEmitIntoClient
public init(
priority: TaskPriority? = nil,
@_inheritActorContext @_implicitSelfCapture operation: __owned @Sendable @escaping () async -> Success
) {
#if compiler(>=5.5) && $BuiltinCreateAsyncTaskInGroup
// Set up the job flags for a new task.
let flags = taskCreateFlags(
priority: priority, isChildTask: false, copyTaskLocals: true,
inheritContext: true, enqueueJob: true,
addPendingGroupTaskUnconditionally: false)
// Create the asynchronous task.
let (task, _) = Builtin.createAsyncTask(flags, operation)
self._task = task
#else
fatalError("Unsupported Swift compiler")
#endif
}
#endif
}
@available(SwiftStdlib 5.1, *)
extension Task where Failure == Error {
#if SWIFT_STDLIB_TASK_TO_THREAD_MODEL_CONCURRENCY
@discardableResult
@_alwaysEmitIntoClient
@available(*, unavailable, message: "Unavailable in task-to-thread concurrency model")
public init(
priority: TaskPriority? = nil,
@_inheritActorContext @_implicitSelfCapture operation: __owned @Sendable @escaping () async throws -> Success
) {
fatalError("Unavailable in task-to-thread concurrency model")
}
#else
/// Runs the given throwing operation asynchronously
/// as part of a new top-level task on behalf of the current actor.
///
/// Use this function when creating asynchronous work
/// that operates on behalf of the synchronous function that calls it.
/// Like `Task.detached(priority:operation:)`,
/// this function creates a separate, top-level task.
/// Unlike `detach(priority:operation:)`,
/// the task created by `Task.init(priority:operation:)`
/// inherits the priority and actor context of the caller,
/// so the operation is treated more like an asynchronous extension
/// to the synchronous operation.
///
/// You need to keep a reference to the task
/// if you want to cancel it by calling the `Task.cancel()` method.
/// Discarding your reference to a detached task
/// doesn't implicitly cancel that task,
/// it only makes it impossible for you to explicitly cancel the task.
///
/// - Parameters:
/// - priority: The priority of the task.
/// Pass `nil` to use the priority from `Task.currentPriority`.
/// - operation: The operation to perform.
@discardableResult
@_alwaysEmitIntoClient
public init(
priority: TaskPriority? = nil,
@_inheritActorContext @_implicitSelfCapture operation: __owned @Sendable @escaping () async throws -> Success
) {
#if compiler(>=5.5) && $BuiltinCreateAsyncTaskInGroup
// Set up the task flags for a new task.
let flags = taskCreateFlags(
priority: priority, isChildTask: false, copyTaskLocals: true,
inheritContext: true, enqueueJob: true,
addPendingGroupTaskUnconditionally: false
)
// Create the asynchronous task future.
let (task, _) = Builtin.createAsyncTask(flags, operation)
self._task = task
#else
fatalError("Unsupported Swift compiler")
#endif
}
#endif
}
// ==== Detached Tasks ---------------------------------------------------------
@available(SwiftStdlib 5.1, *)
extension Task where Failure == Never {
#if SWIFT_STDLIB_TASK_TO_THREAD_MODEL_CONCURRENCY
@discardableResult
@_alwaysEmitIntoClient
@available(*, unavailable, message: "Unavailable in task-to-thread concurrency model")
public static func detached(
priority: TaskPriority? = nil,
operation: __owned @Sendable @escaping () async -> Success
) -> Task<Success, Failure> {
fatalError("Unavailable in task-to-thread concurrency model")
}
#else
/// Runs the given nonthrowing operation asynchronously
/// as part of a new top-level task.
///
/// Don't use a detached task if it's possible
/// to model the operation using structured concurrency features like child tasks.
/// Child tasks inherit the parent task's priority and task-local storage,
/// and canceling a parent task automatically cancels all of its child tasks.
/// You need to handle these considerations manually with a detached task.
///
/// You need to keep a reference to the detached task
/// if you want to cancel it by calling the `Task.cancel()` method.
/// Discarding your reference to a detached task
/// doesn't implicitly cancel that task,
/// it only makes it impossible for you to explicitly cancel the task.
///
/// - Parameters:
/// - priority: The priority of the task.
/// - operation: The operation to perform.
///
/// - Returns: A reference to the task.
@discardableResult
@_alwaysEmitIntoClient
public static func detached(
priority: TaskPriority? = nil,
operation: __owned @Sendable @escaping () async -> Success
) -> Task<Success, Failure> {
#if compiler(>=5.5) && $BuiltinCreateAsyncTaskInGroup
// Set up the job flags for a new task.
let flags = taskCreateFlags(
priority: priority, isChildTask: false, copyTaskLocals: false,
inheritContext: false, enqueueJob: true,
addPendingGroupTaskUnconditionally: false)
// Create the asynchronous task future.
let (task, _) = Builtin.createAsyncTask(flags, operation)
return Task(task)
#else
fatalError("Unsupported Swift compiler")
#endif
}
#endif
}
@available(SwiftStdlib 5.1, *)
extension Task where Failure == Error {
#if SWIFT_STDLIB_TASK_TO_THREAD_MODEL_CONCURRENCY
@discardableResult
@_alwaysEmitIntoClient
@available(*, unavailable, message: "Unavailable in task-to-thread concurrency model")
public static func detached(
priority: TaskPriority? = nil,
operation: __owned @Sendable @escaping () async throws -> Success
) -> Task<Success, Failure> {
fatalError("Unavailable in task-to-thread concurrency model")
}
#else
/// Runs the given throwing operation asynchronously
/// as part of a new top-level task.
///
/// If the operation throws an error, this method propagates that error.
///
/// Don't use a detached task if it's possible
/// to model the operation using structured concurrency features like child tasks.
/// Child tasks inherit the parent task's priority and task-local storage,
/// and canceling a parent task automatically cancels all of its child tasks.
/// You need to handle these considerations manually with a detached task.
///
/// You need to keep a reference to the detached task
/// if you want to cancel it by calling the `Task.cancel()` method.
/// Discarding your reference to a detached task
/// doesn't implicitly cancel that task,
/// it only makes it impossible for you to explicitly cancel the task.
///
/// - Parameters:
/// - priority: The priority of the task.
/// - operation: The operation to perform.
///
/// - Returns: A reference to the task.
@discardableResult
@_alwaysEmitIntoClient
public static func detached(
priority: TaskPriority? = nil,
operation: __owned @Sendable @escaping () async throws -> Success
) -> Task<Success, Failure> {
#if compiler(>=5.5) && $BuiltinCreateAsyncTaskInGroup
// Set up the job flags for a new task.
let flags = taskCreateFlags(
priority: priority, isChildTask: false, copyTaskLocals: false,
inheritContext: false, enqueueJob: true,
addPendingGroupTaskUnconditionally: false
)
// Create the asynchronous task future.
let (task, _) = Builtin.createAsyncTask(flags, operation)
return Task(task)
#else
fatalError("Unsupported Swift compiler")
#endif
}
#endif
}
// ==== Voluntary Suspension -----------------------------------------------------
@available(SwiftStdlib 5.1, *)
extension Task where Success == Never, Failure == Never {
/// Suspends the current task and allows other tasks to execute.
///
/// A task can voluntarily suspend itself
/// in the middle of a long-running operation
/// that doesn't contain any suspension points,
/// to let other tasks run for a while
/// before execution returns to this task.
///
/// If this task is the highest-priority task in the system,
/// the executor immediately resumes execution of the same task.
/// As such,
/// this method isn't necessarily a way to avoid resource starvation.
public static func yield() async {
return await Builtin.withUnsafeContinuation { (continuation: Builtin.RawUnsafeContinuation) -> Void in
let job = _taskCreateNullaryContinuationJob(
priority: Int(Task.currentPriority.rawValue),
continuation: continuation)
_enqueueJobGlobal(job)
}
}
}
// ==== UnsafeCurrentTask ------------------------------------------------------
/// Calls a closure with an unsafe reference to the current task.
///
/// If you call this function from the body of an asynchronous function,
/// the unsafe task handle passed to the closure is always non-`nil`
/// because an asynchronous function always runs in the context of a task.
/// However, if you call this function from the body of a synchronous function,
/// and that function isn't executing in the context of any task,
/// the unsafe task handle is `nil`.
///
/// Don't store an unsafe task reference
/// for use outside this method's closure.
/// Storing an unsafe reference doesn't affect the task's actual life cycle,
/// and the behavior of accessing an unsafe task reference
/// outside of the `withUnsafeCurrentTask(body:)` method's closure isn't defined.
/// There's no safe way to retrieve a reference to the current task
/// and save it for long-term use.
/// To query the current task without saving a reference to it,
/// use properties like `currentPriority`.
/// If you need to store a reference to a task,
/// create an unstructured task using `Task.detached(priority:operation:)` instead.
///
/// - Parameters:
/// - body: A closure that takes an `UnsafeCurrentTask` parameter.
/// If `body` has a return value,
/// that value is also used as the return value
/// for the `withUnsafeCurrentTask(body:)` function.
///
/// - Returns: The return value, if any, of the `body` closure.
@available(SwiftStdlib 5.1, *)
public func withUnsafeCurrentTask<T>(body: (UnsafeCurrentTask?) throws -> T) rethrows -> T {
guard let _task = _getCurrentAsyncTask() else {
return try body(nil)
}
// FIXME: This retain seems pretty wrong, however if we don't we WILL crash
// with "destroying a task that never completed" in the task's destroy.
// How do we solve this properly?
Builtin.retain(_task)
return try body(UnsafeCurrentTask(_task))
}
/// An unsafe reference to the current task.
///
/// To get an instance of `UnsafeCurrentTask` for the current task,
/// call the `withUnsafeCurrentTask(body:)` method.
/// Don't store an unsafe task reference
/// for use outside that method's closure.
/// Storing an unsafe reference doesn't affect the task's actual life cycle,
/// and the behavior of accessing an unsafe task reference
/// outside of the `withUnsafeCurrentTask(body:)` method's closure isn't defined.
///
/// Only APIs on `UnsafeCurrentTask` that are also part of `Task`
/// are safe to invoke from a task other than
/// the task that this `UnsafeCurrentTask` instance refers to.
/// Calling other APIs from another task is undefined behavior,
/// breaks invariants in other parts of the program running on this task,
/// and may lead to crashes or data loss.
///
/// For information about the language-level concurrency model that `UnsafeCurrentTask` is part of,
/// see [Concurrency][concurrency] in [The Swift Programming Language][tspl].
///
/// [concurrency]: https://docs.swift.org/swift-book/LanguageGuide/Concurrency.html
/// [tspl]: https://docs.swift.org/swift-book/
@available(SwiftStdlib 5.1, *)
public struct UnsafeCurrentTask {
internal let _task: Builtin.NativeObject
// May only be created by the standard library.
internal init(_ task: Builtin.NativeObject) {
self._task = task
}
/// A Boolean value that indicates whether the current task was canceled.
///
/// After the value of this property becomes `true`, it remains `true` indefinitely.
/// There is no way to uncancel a task.
///
/// - SeeAlso: `checkCancellation()`
public var isCancelled: Bool {
_taskIsCancelled(_task)
}
/// The current task's priority.
///
/// - SeeAlso: `TaskPriority`
/// - SeeAlso: `Task.currentPriority`
public var priority: TaskPriority {
TaskPriority(rawValue: _taskCurrentPriority(_task))
}
/// Cancel the current task.
public func cancel() {
_taskCancel(_task)
}
}
@available(SwiftStdlib 5.1, *)
@available(*, unavailable)
extension UnsafeCurrentTask: Sendable { }
@available(SwiftStdlib 5.1, *)
extension UnsafeCurrentTask: Hashable {
public func hash(into hasher: inout Hasher) {
UnsafeRawPointer(Builtin.bridgeToRawPointer(_task)).hash(into: &hasher)
}
}
@available(SwiftStdlib 5.1, *)
extension UnsafeCurrentTask: Equatable {
public static func ==(lhs: Self, rhs: Self) -> Bool {
UnsafeRawPointer(Builtin.bridgeToRawPointer(lhs._task)) ==
UnsafeRawPointer(Builtin.bridgeToRawPointer(rhs._task))
}
}
// ==== Internal ---------------------------------------------------------------
@available(SwiftStdlib 5.1, *)
@_silgen_name("swift_task_getCurrent")
func _getCurrentAsyncTask() -> Builtin.NativeObject?
@available(SwiftStdlib 5.1, *)
@_silgen_name("swift_task_getJobFlags")
func getJobFlags(_ task: Builtin.NativeObject) -> JobFlags
@available(SwiftStdlib 5.1, *)
@_silgen_name("swift_task_enqueueGlobal")
@usableFromInline
func _enqueueJobGlobal(_ task: Builtin.Job)
@available(SwiftStdlib 5.1, *)
@_silgen_name("swift_task_enqueueGlobalWithDelay")
@usableFromInline
func _enqueueJobGlobalWithDelay(_ delay: UInt64, _ task: Builtin.Job)
@available(SwiftStdlib 5.7, *)
@_silgen_name("swift_task_enqueueGlobalWithDeadline")
@usableFromInline
func _enqueueJobGlobalWithDeadline(_ seconds: Int64, _ nanoseconds: Int64,
_ toleranceSec: Int64, _ toleranceNSec: Int64,
_ clock: Int32, _ task: Builtin.Job)
@available(SwiftStdlib 5.1, *)
@usableFromInline
@_silgen_name("swift_task_asyncMainDrainQueue")
internal func _asyncMainDrainQueue() -> Never
@available(SwiftStdlib 5.1, *)
@usableFromInline
@_silgen_name("swift_task_getMainExecutor")
internal func _getMainExecutor() -> Builtin.Executor
#if SWIFT_STDLIB_TASK_TO_THREAD_MODEL_CONCURRENCY
@available(SwiftStdlib 5.1, *)
@available(*, unavailable, message: "Unavailable in task-to-thread concurrency model")
@usableFromInline
@preconcurrency
internal func _runAsyncMain(_ asyncFun: @Sendable @escaping () async throws -> ()) {
fatalError("Unavailable in task-to-thread concurrency model")
}
#else
@available(SwiftStdlib 5.1, *)
@usableFromInline
@preconcurrency
internal func _runAsyncMain(_ asyncFun: @Sendable @escaping () async throws -> ()) {
Task.detached {
do {
#if !os(Windows)
#if compiler(>=5.5) && $BuiltinHopToActor
Builtin.hopToActor(MainActor.shared)
#else
fatalError("Swift compiler is incompatible with this SDK version")
#endif
#endif
try await asyncFun()
exit(0)
} catch {
_errorInMain(error)
}
}
_asyncMainDrainQueue()
}
#endif
// FIXME: both of these ought to take their arguments _owned so that
// we can do a move out of the future in the common case where it's
// unreferenced
@available(SwiftStdlib 5.1, *)
@_silgen_name("swift_task_future_wait")
public func _taskFutureGet<T>(_ task: Builtin.NativeObject) async -> T
@available(SwiftStdlib 5.1, *)
@_silgen_name("swift_task_future_wait_throwing")
public func _taskFutureGetThrowing<T>(_ task: Builtin.NativeObject) async throws -> T
@available(SwiftStdlib 5.1, *)
@_silgen_name("swift_task_cancel")
func _taskCancel(_ task: Builtin.NativeObject)
@available(SwiftStdlib 5.1, *)
@_silgen_name("swift_task_isCancelled")
@usableFromInline
func _taskIsCancelled(_ task: Builtin.NativeObject) -> Bool
@_silgen_name("swift_task_currentPriority")
internal func _taskCurrentPriority(_ task: Builtin.NativeObject) -> UInt8
@_silgen_name("swift_task_basePriority")
internal func _taskBasePriority(_ task: Builtin.NativeObject) -> UInt8
@available(SwiftStdlib 5.1, *)
@_silgen_name("swift_task_createNullaryContinuationJob")
func _taskCreateNullaryContinuationJob(priority: Int, continuation: Builtin.RawUnsafeContinuation) -> Builtin.Job
@available(SwiftStdlib 5.1, *)
@usableFromInline
@_silgen_name("swift_task_isCurrentExecutor")
func _taskIsCurrentExecutor(_ executor: Builtin.Executor) -> Bool
@available(SwiftStdlib 5.1, *)
@usableFromInline
@_silgen_name("swift_task_reportUnexpectedExecutor")
func _reportUnexpectedExecutor(_ _filenameStart: Builtin.RawPointer,
_ _filenameLength: Builtin.Word,
_ _filenameIsASCII: Builtin.Int1,
_ _line: Builtin.Word,
_ _executor: Builtin.Executor)
@available(SwiftStdlib 5.1, *)
@_silgen_name("swift_task_getCurrentThreadPriority")
func _getCurrentThreadPriority() -> Int
#if SWIFT_STDLIB_TASK_TO_THREAD_MODEL_CONCURRENCY
@available(SwiftStdlib 5.8, *)
@usableFromInline
@_unavailableFromAsync(message: "Use _taskRunInline from a sync context to begin an async context.")
internal func _taskRunInline<T>(_ body: () async -> T) -> T {
#if compiler(>=5.5) && $BuiltinTaskRunInline
return Builtin.taskRunInline(body)
#else
fatalError("Unsupported Swift compiler")
#endif
}
@available(SwiftStdlib 5.8, *)
extension Task where Failure == Never {
/// Start an async context within the current sync context and run the
/// provided async closure, returning the value it produces.
@available(SwiftStdlib 5.8, *)
@_spi(_TaskToThreadModel)
@_unavailableFromAsync(message: "Use Task.runInline from a sync context to begin an async context.")
public static func runInline(_ body: () async -> Success) -> Success {
return _taskRunInline(body)
}
}
@available(SwiftStdlib 5.8, *)
extension Task where Failure == Error {
@available(SwiftStdlib 5.8, *)
@_alwaysEmitIntoClient
@usableFromInline
internal static func _runInlineHelper<T>(
body: () async -> Result<T, Error>,
rescue: (Result<T, Error>) throws -> T
) rethrows -> T {
return try rescue(
_taskRunInline(body)
)
}
/// Start an async context within the current sync context and run the
/// provided async closure, returning or throwing the value or error it
/// produces.
@available(SwiftStdlib 5.8, *)
@_spi(_TaskToThreadModel)
@_unavailableFromAsync(message: "Use Task.runInline from a sync context to begin an async context.")
public static func runInline(_ body: () async throws -> Success) rethrows -> Success {
return try _runInlineHelper(
body: {
do {
let value = try await body()
return Result.success(value)
}
catch let error {
return Result.failure(error)
}
},
rescue: { try $0.get() }
)
}
}
#endif
#if _runtime(_ObjC)
#if !SWIFT_STDLIB_TASK_TO_THREAD_MODEL_CONCURRENCY
/// Intrinsic used by SILGen to launch a task for bridging a Swift async method
/// which was called through its ObjC-exported completion-handler-based API.
@available(SwiftStdlib 5.1, *)
@_alwaysEmitIntoClient
@usableFromInline
internal func _runTaskForBridgedAsyncMethod(@_inheritActorContext _ body: __owned @Sendable @escaping () async -> Void) {
#if compiler(>=5.6)
Task(operation: body)
#else
Task<Int, Error> {
await body()
return 0
}
#endif
}
#endif
#endif
| apache-2.0 | 21457ca4e47f5008651767b943ecb5ed | 33.257416 | 121 | 0.679153 | 4.295536 | false | false | false | false |
roambotics/swift | SwiftCompilerSources/Sources/Optimizer/FunctionPasses/ReleaseDevirtualizer.swift | 2 | 5854 | //===--- ReleaseDevirtualizer.swift - Devirtualizes release-instructions --===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2022 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import SIL
/// Devirtualizes release instructions which are known to destruct the object.
///
/// This means, it replaces a sequence of
/// %x = alloc_ref [stack] $X
/// ...
/// strong_release %x
/// dealloc_stack_ref %x
/// with
/// %x = alloc_ref [stack] $X
/// ...
/// set_deallocating %x
/// %d = function_ref @dealloc_of_X
/// %a = apply %d(%x)
/// dealloc_stack_ref %x
///
/// The optimization is only done for stack promoted objects because they are
/// known to have no associated objects (which are not explicitly released
/// in the deinit method).
let releaseDevirtualizerPass = FunctionPass(
name: "release-devirtualizer", { function, context in
for block in function.blocks {
// The last `release_value`` or `strong_release`` instruction before the
// deallocation.
var lastRelease: RefCountingInst?
for instruction in block.instructions {
if let release = lastRelease {
// We only do the optimization for stack promoted object, because for
// these we know that they don't have associated objects, which are
// _not_ released by the deinit method.
if let deallocStackRef = instruction as? DeallocStackRefInst {
if !context.continueWithNextSubpassRun(for: release) {
return
}
tryDevirtualizeReleaseOfObject(context, release, deallocStackRef)
lastRelease = nil
continue
}
}
switch instruction {
case is ReleaseValueInst, is StrongReleaseInst:
lastRelease = instruction as? RefCountingInst
case is DeallocRefInst, is SetDeallocatingInst:
lastRelease = nil
default:
if instruction.mayRelease {
lastRelease = nil
}
}
}
}
}
)
/// Tries to de-virtualize the final release of a stack-promoted object.
private func tryDevirtualizeReleaseOfObject(
_ context: PassContext,
_ release: RefCountingInst,
_ deallocStackRef: DeallocStackRefInst
) {
let allocRefInstruction = deallocStackRef.allocRef
// Check if the release instruction right before the `dealloc_stack_ref` really releases
// the allocated object (and not something else).
var finder = FindAllocationOfRelease(allocation: allocRefInstruction)
if !finder.allocationIsRoot(of: release.operand) {
return
}
let type = allocRefInstruction.type
guard let dealloc = context.calleeAnalysis.getDestructor(ofExactType: type) else {
return
}
let builder = Builder(at: release, location: release.location, context)
var object: Value = allocRefInstruction
if object.type != type {
object = builder.createUncheckedRefCast(object: object, type: type)
}
// Do what a release would do before calling the deallocator: set the object
// in deallocating state, which means set the RC_DEALLOCATING_FLAG flag.
builder.createSetDeallocating(operand: object, isAtomic: release.isAtomic)
// Create the call to the destructor with the allocated object as self
// argument.
let functionRef = builder.createFunctionRef(dealloc)
let substitutionMap = context.getContextSubstitutionMap(for: type)
builder.createApply(function: functionRef, substitutionMap, arguments: [object])
context.erase(instruction: release)
}
// Up-walker to find the root of a release instruction.
private struct FindAllocationOfRelease : ValueUseDefWalker {
private let allocInst: AllocRefInstBase
private var allocFound = false
var walkUpCache = WalkerCache<UnusedWalkingPath>()
init(allocation: AllocRefInstBase) { allocInst = allocation }
/// The top-level entry point: returns true if the root of `value` is the `allocInst`.
mutating func allocationIsRoot(of value: Value) -> Bool {
return walkUp(value: value, path: UnusedWalkingPath()) != .abortWalk &&
allocFound
}
mutating func rootDef(value: Value, path: UnusedWalkingPath) -> WalkResult {
if value == allocInst {
allocFound = true
return .continueWalk
}
return .abortWalk
}
// This function is called for `struct` and `tuple` instructions in case the `path` doesn't select
// a specific operand but all operands.
mutating func walkUpAllOperands(of def: Instruction, path: UnusedWalkingPath) -> WalkResult {
// Instead of walking up _all_ operands (which would be the default behavior), require that only a
// _single_ operand is not trivial and walk up that operand.
// We need to check this because the released value must not contain multiple copies of the
// allocated object. We can only replace a _single_ release with the destructor call and not
// multiple releases of the same object. E.g.
//
// %x = alloc_ref [stack] $X
// strong_retain %x
// %t = tuple (%x, %x)
// release_value %t // -> releases %x two times!
// dealloc_stack_ref %x
//
var nonTrivialOperandFound = false
for operand in def.operands {
if !operand.value.hasTrivialType {
if nonTrivialOperandFound {
return .abortWalk
}
nonTrivialOperandFound = true
if walkUp(value: operand.value, path: path) == .abortWalk {
return .abortWalk
}
}
}
return .continueWalk
}
}
| apache-2.0 | 02e82cb16ba8d909c528a6bb05d197df | 34.695122 | 102 | 0.669115 | 4.371919 | false | false | false | false |
crazypoo/PTools | Pods/JXSegmentedView/Sources/Number/JXSegmentedNumberDataSource.swift | 1 | 2740 | //
// JXSegmentedNumberDataSource.swift
// JXSegmentedView
//
// Created by jiaxin on 2018/12/28.
// Copyright © 2018 jiaxin. All rights reserved.
//
import Foundation
import UIKit
open class JXSegmentedNumberDataSource: JXSegmentedTitleDataSource {
/// 需要和titles数组数量一致,没有数字的item填0!!!
open var numbers = [Int]()
/// numberLabel的宽度补偿,numberLabel真实的宽度是文字内容的宽度加上补偿的宽度
open var numberWidthIncrement: CGFloat = 10
/// numberLabel的背景色
open var numberBackgroundColor: UIColor = .red
/// numberLabel的textColor
open var numberTextColor: UIColor = .white
/// numberLabel的font
open var numberFont: UIFont = UIFont.systemFont(ofSize: 11)
/// numberLabel的默认位置是center在titleLabel的右上角,可以通过numberOffset控制X、Y轴的偏移
open var numberOffset: CGPoint = CGPoint.zero
/// 如果业务需要处理超过999就像是999+,就可以通过这个闭包实现。默认显示不会对number进行处理
open var numberStringFormatterClosure: ((Int) -> String)?
/// numberLabel的高度,默认:14
open var numberHeight: CGFloat = 14
open override func preferredItemModelInstance() -> JXSegmentedBaseItemModel {
return JXSegmentedNumberItemModel()
}
open override func preferredRefreshItemModel(_ itemModel: JXSegmentedBaseItemModel, at index: Int, selectedIndex: Int) {
super.preferredRefreshItemModel(itemModel, at: index, selectedIndex: selectedIndex)
guard let itemModel = itemModel as? JXSegmentedNumberItemModel else {
return
}
itemModel.number = numbers[index]
if numberStringFormatterClosure != nil {
itemModel.numberString = numberStringFormatterClosure!(itemModel.number)
}else {
itemModel.numberString = "\(itemModel.number)"
}
itemModel.numberTextColor = numberTextColor
itemModel.numberBackgroundColor = numberBackgroundColor
itemModel.numberOffset = numberOffset
itemModel.numberWidthIncrement = numberWidthIncrement
itemModel.numberHeight = numberHeight
itemModel.numberFont = numberFont
}
//MARK: - JXSegmentedViewDataSource
open override func registerCellClass(in segmentedView: JXSegmentedView) {
segmentedView.collectionView.register(JXSegmentedNumberCell.self, forCellWithReuseIdentifier: "cell")
}
open override func segmentedView(_ segmentedView: JXSegmentedView, cellForItemAt index: Int) -> JXSegmentedBaseCell {
let cell = segmentedView.dequeueReusableCell(withReuseIdentifier: "cell", at: index)
return cell
}
}
| mit | 05e862d3396532d7b48879481daf0520 | 38.109375 | 124 | 0.727127 | 4.879142 | false | false | false | false |
SunLiner/Floral | Floral/Floral/Classes/Malls/Malls/View/Cell/MallGoodsCell.swift | 1 | 3938 | //
// MallGoodsCell.swift
// Floral
//
// Created by 孙林 on 16/5/12.
// Copyright © 2016年 ALin. All rights reserved.
// 商城的cell, 非精选
import UIKit
// 商品格的重用标示符
let GoodsCellIdentfy = "GoodsCellIdentfy"
class MallGoodsCell: UITableViewCell, UICollectionViewDataSource, UICollectionViewDelegate {
// 代理
weak var delegate : MallGoodsCellDelegate?
var mallsGoods : MallsGoods?
{
didSet{
if let _ = mallsGoods {
var count = mallsGoods!.goodsList!.count
// 最多只显示4个
count = count < 4 ? count : 4
let height = (CGFloat((count % 2 == 0) ? count / 2 : count / 2 + 1)) * (ScreenWidth / 2.0)
// 更新高度
goodListView.snp_updateConstraints(closure: { (make) in
make.height.equalTo(height)
})
topView.malls = mallsGoods
goodListView.reloadData()
}
}
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
setup()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func setup()
{
selectionStyle = .None
addSubview(topView)
addSubview(goodListView)
topView.snp_makeConstraints { (make) in
make.left.right.top.equalTo(self)
make.height.equalTo(60)
}
goodListView.snp_makeConstraints { (make) in
make.left.right.equalTo(self)
make.top.equalTo(topView.snp_bottom).offset(10)
}
}
// MARK: - 懒加载
private lazy var topView : CategoryInfoView = {
let infoView = CategoryInfoView()
infoView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(MallGoodsCell.toLookAll)))
return infoView
}()
private lazy var goodListView : UICollectionView = {
let list = UICollectionView(frame: CGRectZero, collectionViewLayout: MallFlowLayout())
list.dataSource = self
list.delegate = self
list.alwaysBounceHorizontal = false
list.alwaysBounceVertical = false
list.registerClass(GoodsCollectionViewCell.self, forCellWithReuseIdentifier: GoodsCellIdentfy)
return list
}()
// MARK: - UICollectionViewDataSource
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
{
let count = mallsGoods?.goodsList?.count ?? 0
return count > 4 ? 4 : count
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell
{
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(GoodsCellIdentfy, forIndexPath: indexPath) as! GoodsCollectionViewCell
if let _ = mallsGoods?.goodsList {
cell.goods = mallsGoods?.goodsList![indexPath.row]
}
return cell
}
// MARK: - UICollectionViewDelegate
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
delegate?.mallGoodsCellDidSelectedGoods!(self, goods: mallsGoods!.goodsList![indexPath.item])
}
// MARK: - 点击事件
func toLookAll() {
delegate?.mallGoodsCellDidSelectedCategory!(self, malls: mallsGoods!.goodsList!)
}
}
@objc
protocol MallGoodsCellDelegate : NSObjectProtocol {
// 选中了类型, 去查看所有的类型
optional func mallGoodsCellDidSelectedCategory(mallGoodsCell: MallGoodsCell, malls:[Goods])
// 点击单独一个, 去查看详情
optional func mallGoodsCellDidSelectedGoods(mallGoodsCell: MallGoodsCell, goods:Goods)
}
| mit | 582c1dbd2fffd1a255de2940a348d589 | 31.887931 | 143 | 0.637221 | 4.663814 | false | false | false | false |
FotiosTragopoulos/Core-Geometry | Core Geometry/Par3ViewLine.swift | 1 | 1735 | //
// Par3ViewLine.swift
// Core Geometry
//
// Created by Fotios Tragopoulos on 13/01/2017.
// Copyright © 2017 Fotios Tragopoulos. All rights reserved.
//
import UIKit
class Par3ViewLine: UIView {
override func draw(_ rect: CGRect) {
let context = UIGraphicsGetCurrentContext()
let myShadowOffset = CGSize (width: 10, height: 10)
context?.setShadow (offset: myShadowOffset, blur: 8)
context?.saveGState()
context?.setLineWidth(3.0)
context?.setStrokeColor(UIColor.red.cgColor)
let xView = viewWithTag(6)?.alignmentRect(forFrame: rect).midX
let yView = viewWithTag(6)?.alignmentRect(forFrame: rect).midY
let width = self.viewWithTag(6)?.frame.size.width
let height = self.viewWithTag(6)?.frame.size.height
let size = CGSize(width: width! * 0.6, height: height! * 0.4)
let linePlacementX = CGFloat(size.width/2)
let linePlacementY = CGFloat(size.height/2)
context?.move(to: CGPoint(x: (xView! - (linePlacementX * 0.7)), y: (yView! - (linePlacementY * 1.2))))
context?.addLine(to: CGPoint(x: (xView! - (linePlacementX * 0.7)), y: (yView! + (linePlacementY * 1.2))))
let dashArray:[CGFloat] = [10, 4]
context?.setLineDash(phase: 3, lengths: dashArray)
context?.strokePath()
context?.restoreGState()
self.transform = CGAffineTransform(scaleX: 0.8, y: 0.8)
UIView.animate(withDuration: 1.0, delay: 0, usingSpringWithDamping: 0.15, initialSpringVelocity: 6.0, options: .allowUserInteraction, animations: { self.transform = CGAffineTransform.identity } ,completion: nil)
}
}
| apache-2.0 | 871b5d3297a499d24a6622b0a7f98139 | 37.533333 | 219 | 0.627451 | 3.870536 | false | false | false | false |
antitypical/Manifold | Manifold/Module+Sigma.swift | 1 | 826 | // Copyright © 2015 Rob Rix. All rights reserved.
extension Module {
public static var sigma: Module {
let Sigma = Declaration("Sigma", Datatype("A", .Type,
Datatype.Argument("B", "A" --> .Type,
[ "sigma": Telescope.Argument("a", "A", .Argument("b", ("B" as Term)["a" as Term], .End)) ]
)
))
let first = Declaration("first",
type: nil => { A in (A --> .Type) => { B in Sigma.ref[A, B] --> A } },
value: nil => { A in nil => { B in nil => { v in v[A, nil => { x in B[x] => const(x) }] } } })
let second = Declaration("second",
type: nil => { A in (A --> .Type) => { B in Sigma.ref[A, B] => { v in B[first.ref[A, B, v]] } } },
value: nil => { A in nil => { B in nil => { v in v[nil, nil => { x in B[x] => id }] } } })
return Module("Sigma", [ Sigma, first, second ])
}
}
import Prelude
| mit | 169a016e12a716fecfb68c4a68bd8019 | 33.375 | 101 | 0.521212 | 2.777778 | false | false | false | false |
Hukuma23/CS193p | Assignment_3/Calculator/CalculatorBrain.swift | 2 | 6809 | //
// CalculatorBrain.swift
// Calculator
//
// Created by Nikita Litvinov on 12/15/2016.
// Copyright © 2016 Nikita Litvinov. All rights reserved.
//
import Foundation
class CalculatorBrain{
private var internalProgram = [AnyObject]()
private var accumulator = 0.0
private var descriptionAccumulator = ""
private var error : String?
var isPartialResult : Bool { return pending != nil }
private var pending: PendingBinaryOperationInfo?
var variableValues = [String:Double]() {
didSet {
program = internalProgram as CalculatorBrain.PropertyList
}
}
func setOperand (variableName: String) {
accumulator = variableValues[variableName] ?? 0
descriptionAccumulator = variableName
internalProgram.append(variableName as AnyObject)
}
var result: (Double, String?) { return (accumulator, error) }
var strAccumulator : String { return String(accumulator) }
var description : String {
if let pend = pending {
return pend.descriptionOperation(pend.descriptionOperand, pend.descriptionOperand != descriptionAccumulator ? descriptionAccumulator : "")
} else {
return descriptionAccumulator
}
}
func clear() {
accumulator = 0
descriptionAccumulator = ""
pending = nil
error = nil
internalProgram.removeAll(keepingCapacity: false)
}
func clearVariables() {
variableValues.removeAll(keepingCapacity: false)
}
func setOperand(_ operand: Double) {
accumulator = operand
descriptionAccumulator = formatter.string(from: NSNumber(value: accumulator)) ?? ""
internalProgram.append(operand as AnyObject)
}
private var operations : [String: Operation] = [
"π": Operation.Constant(M_PI),
"e": Operation.Constant(M_E),
"±": Operation.UnaryOperation({ -$0 }, {"±(" + $0 + ")"}, nil),
"√": Operation.UnaryOperation(sqrt, {"√(" + $0 + ")"}, {$0 < 0 ? "√ отриц. числа" : nil}),
"cos": Operation.UnaryOperation(cos, {"cos(" + $0 + ")"}, nil),
"sin": Operation.UnaryOperation(sin, {"sin(" + $0 + ")"}, nil),
"log": Operation.UnaryOperation(log10, {"log(" + $0 + ")"}, {$0 < 0 ? "log отриц. числа" : nil}),
"x⁻¹": Operation.UnaryOperation({1 / $0}, {"(" + $0 + ")⁻¹"}, nil),
"x²": Operation.UnaryOperation({$0 * $0}, {"(" + $0 + ")²"}, nil),
"×": Operation.BinaryOperation({$0 * $1}, {$0 + " × " + $1}, nil),
"÷": Operation.BinaryOperation({$0 / $1}, {$0 + " ÷ " + $1}, {$1 == 0 ? "÷ на 0" : nil}),
"+": Operation.BinaryOperation({$0 + $1}, {$0 + " + " + $1}, nil),
"−": Operation.BinaryOperation({$0 - $1}, {$0 + " − " + $1}, nil),
"=": Operation.Equals,
"C": Operation.Clear
]
enum Operation{
case Constant(Double)
case UnaryOperation((Double) -> Double, (String) -> String, ((Double) -> String?)?)
case BinaryOperation((Double, Double) -> Double, (String, String) -> String, ((Double, Double) -> String?)?)
case Equals
case Clear
}
func performOperation(_ symbol: String){
internalProgram.append(symbol as AnyObject)
if let operation = operations[symbol]{
switch operation {
case .Constant(let value):
descriptionAccumulator = symbol
accumulator = value
case .UnaryOperation(let function, let descriptionFunction, let errorFunction):
if pending != nil {
descriptionAccumulator = String(accumulator)
}
error = errorFunction?(accumulator)
descriptionAccumulator = descriptionFunction(descriptionAccumulator)
accumulator = function(accumulator)
case .BinaryOperation(let function, let descriptionFunction, let errorFunction):
executeBinaryOperation()
if descriptionAccumulator == "" {
descriptionAccumulator = String(accumulator)
}
pending = PendingBinaryOperationInfo(binaryOperation: function, firstOperand: accumulator, descriptionOperand: descriptionAccumulator, descriptionOperation: descriptionFunction, errorValidator: errorFunction)
case .Equals:
executeBinaryOperation()
case .Clear:
clear()
}
}
}
private func executeBinaryOperation() {
if pending != nil {
error = pending!.errorValidator?(pending!.firstOperand, accumulator)
accumulator = pending!.binaryOperation(pending!.firstOperand, accumulator)
descriptionAccumulator = pending!.descriptionOperation(pending!.descriptionOperand, descriptionAccumulator)
pending = nil
}
}
func undoLast() {
guard !internalProgram.isEmpty else { clear(); return }
internalProgram.removeLast()
program = internalProgram as CalculatorBrain.PropertyList
}
private struct PendingBinaryOperationInfo {
var binaryOperation: (Double, Double) -> Double
var firstOperand: Double
var descriptionOperand : String
var descriptionOperation : (String, String) -> String
var errorValidator : ((Double, Double) -> String?)?
}
typealias PropertyList = AnyObject
var program: PropertyList {
get {
return internalProgram as CalculatorBrain.PropertyList
}
set {
clear()
if let arrayOfOps = newValue as? [AnyObject] {
for op in arrayOfOps {
if let operand = op as? Double {
setOperand(operand)
} else if let operation = op as? String {
if operations[operation] != nil {
performOperation(operation)
} else {
// operation is a variable
setOperand(variableName: operation)
}
}
}
}
}
}
private let formatter : NumberFormatter = {
let formatter = NumberFormatter()
formatter.numberStyle = .decimal
formatter.maximumFractionDigits = 6
formatter.minimumFractionDigits = 0
formatter.notANumberSymbol = "Error"
formatter.groupingSeparator = " "
formatter.locale = Locale.current
return formatter
}()
}
| apache-2.0 | 85c3baf12701f8e746afbe286ef01ed3 | 36.142857 | 224 | 0.564497 | 5.05988 | false | false | false | false |
gaowanli/PinGo | PinGo/PinGo/Other/Tool/Heders.swift | 1 | 912 | //
// Heders.swift
// PinGo
//
// Created by GaoWanli on 16/1/16.
// Copyright © 2016年 GWL. All rights reserved.
//
import Foundation
import UIKit
let iOS9Later = (UIDevice.current.systemVersion as NSString).doubleValue >= 9.0
let iPhone4s = (UIScreen.main.bounds.size.width == 320)
let kNavBarHeight: CGFloat = 64.0
let kTabBarHeight: CGFloat = 49.0
let kScreenWidth = UIScreen.main.bounds.width
let kScreenHeight = UIScreen.main.bounds.height
/// 统一的外观颜色
let kAppearanceColor = UIColor.colorWithRGBA(250, G: 60, B: 67)
/// 主要的字体
let kMainFont = UIFont.fontWithSize(15.0)
let kNavigationBarFont = UIFont.fontWithSize(16)
let kCalendar = Calendar.current
let kDateFormatter = DateFormatter()
enum QueryMethod {
case new // 获取最新数据
case old // 获取旧数据
}
| mit | cbe9446819c3b3000913f34e98d8ad18 | 28.758621 | 92 | 0.655852 | 3.580913 | false | false | false | false |
Ssimboss/Image360 | Image360/Core/GLKUtils.swift | 1 | 8579 | //
// GLKUtils.swift
// Image360
//
// Copyright © 2017 Andrew Simvolokov. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import GLKit
/// OpenGL Texture unit reference.
typealias GLTextureUnit = GLenum
/// OpenGL Method for error detection
/// - parameter msg: Output character string at detection
func glCheckError(_ msg: String) {
var error: GLenum = 0
let noError = GLenum(GL_NO_ERROR)
repeat{
error = glGetError()
if error != noError {
switch error {
case GLenum(GL_INVALID_ENUM):
print("OpenGL error: \(error)(GL_INVALID_ENUM) func: %@\n", error, msg)
case GLenum(GL_INVALID_VALUE):
print("OpenGL error: \(error)(GL_INVALID_VALUE) func:%@\n", error, msg)
case GLenum(GL_INVALID_OPERATION):
print("OpenGL error: \(error)(GL_INVALID_OPERATION) func:%@\n", error, msg)
case GLenum(GL_OUT_OF_MEMORY):
print("OpenGL error: \(error)(GL_OUT_OF_MEMORY) func:%@\n", error, msg)
default:
print("OpenGL error: \(error) func:%@", error, msg)
}
}
} while error != noError
}
/// OpenGL Method to load textures to memory.
/// - parameter data: Dictionary with images which should be loaded to textures memory.
/// Each texture will be associated with uniq key-texture unit.
func glLoadTextures(_ data: [GLTextureUnit : CGImage]) -> [GLTextureUnit : GLKTextureInfo] {
var result: [GLTextureUnit : GLKTextureInfo] = [:]
for (textureUnit, image) in data {
do {
result[textureUnit] = try GLKTextureLoader.texture(with: image, options: nil)
} catch let error {
fatalError("texture load failed: \(error.localizedDescription)")
}
}
for (textureUnit, textureInfo) in result {
glActiveTexture(textureUnit)
glCheckError("glActiveTexture error")
glBindTexture(GLenum(GL_TEXTURE_2D), textureInfo.name)
glCheckError("glBindTexture error")
glTexParameterf(GLenum(GL_TEXTURE_2D), GLenum(GL_TEXTURE_MIN_FILTER), GLfloat(GL_NEAREST))
glCheckError("glTexParameterf error")
glTexParameterf(GLenum(GL_TEXTURE_2D), GLenum(GL_TEXTURE_MAG_FILTER), GLfloat(GL_LINEAR))
glCheckError("glTexParameterf error")
}
return result
}
/// OpenGL Method to unload texture from memory.
/// - parameter unit: Texture unit specified for texture.
/// - parameter info: Texture info.
func glUnloadTexture(unit: GLTextureUnit, info: GLKTextureInfo) {
glActiveTexture(unit)
glCheckError("glActiveTexture")
glBindTexture(info.target, 0)
glCheckError("glBindTexture")
var textureNames = [info.name]
glDeleteTextures(1, &textureNames)
glCheckError("glDeleteTextures")
}
/// OpenGL Method to unload textures from memory.
/// - parameter data: Dictionare of texture info with associated key-texture units.
func glUnloadTextures(_ data: [GLTextureUnit : GLKTextureInfo]) {
for (textureUnit, textureInfo) in data {
glUnloadTexture(unit: textureUnit, info: textureInfo)
}
}
/// Creates & Compiles OpenGL shader.
/// - parameter shaderType: Specifies the type of shader to be created. GL_VERTEX_SHADER or GL_FRAGMENT_SHADER.
/// - parameter source: Shader source code(GLSL).
/// - returns: OpenGL shader's reference.
func glCreateAndCompileShader(shaderType: GLenum, source: String) -> GLuint {
let nsString = NSString(string: source)
var shaderStringUTF8: UnsafePointer<GLchar>? = nsString.utf8String
var shaderStringLength: GLint = GLint(source.utf8.count)
var compiled: GLint = 0
let shader = glCreateShader(shaderType) // Creates shader
guard shader != 0 else {
return 0
}
glShaderSource(shader, 1, &shaderStringUTF8, &shaderStringLength) // Replaces shader's source code
glCompileShader(shader) // Compiles shader's code
glGetShaderiv(shader, GLenum(GL_COMPILE_STATUS), &compiled) // Puts compile status to compiled
guard compiled == GL_TRUE else {
var infoLen: GLint = 0
glGetShaderiv(shader, GLenum(GL_INFO_LOG_LENGTH), &infoLen)
if infoLen > 1 {
var infoBuffer = [Int8](repeating: 0, count: Int(infoLen))
var realLength: GLsizei = 0
glGetShaderInfoLog(shader, GLsizei(infoLen), &realLength, &infoBuffer)
let errorDescription = String(cString: &infoBuffer)
print("Shader compile error: \(errorDescription)")
}
glDeleteShader(shader) // Delete created shader
return 0
}
return shader
}
/// Program creation function for OpenGL
/// - parameter vertexShaderSrc: Vertex shader source
/// - parameter fragmentShaderSrc: Fragment shader source
/// - returns: OpenGL program's reference.
func glCreateProgram(vertexShaderSrc: String, fragmentShaderSrc: String) -> GLuint {
// load the vertex shader
let vertexShader = glCreateAndCompileShader(shaderType: GLenum(GL_VERTEX_SHADER), source: vertexShaderSrc)
guard vertexShader != 0 else {
print("glCreateProgram error: vertexShader == 0")
return 0
}
// load fragment shader
let fragmentShader = glCreateAndCompileShader(shaderType: GLenum(GL_FRAGMENT_SHADER), source: fragmentShaderSrc)
guard fragmentShader != 0 else {
glDeleteShader(vertexShader)
print("glCreateProgram error: fragmentShader == 0")
return 0
}
// create the program object
let program = glCreateProgram()
if program == 0 {
glDeleteShader(vertexShader)
glDeleteShader(fragmentShader)
print("glCreateProgram error: program == 0")
return 0
}
glAttachShader(program, vertexShader)
glAttachShader(program, fragmentShader)
// link the program
glLinkProgram(program)
// check the link status
var linked: GLint = 0
glGetProgramiv(program, GLenum(GL_LINK_STATUS), &linked)
guard linked == GL_TRUE else {
var infoLength: GLint = 0
glGetProgramiv(program, GLenum(GL_INFO_LOG_LENGTH), &infoLength)
if infoLength > 1 {
var infoBuffer = [Int8](repeating: 0, count: Int(infoLength))
var realLength: GLsizei = 0
glGetProgramInfoLog(program, GLsizei(infoLength), &realLength, &infoBuffer)
let errorDescription = String(cString: &infoBuffer)
print("Linking program error: \(errorDescription)")
}
glDeleteProgram(program)
print("glCreateProgram error: linked != GL_TRUE")
return 0
}
glDeleteShader(vertexShader)
glDeleteShader(fragmentShader)
return program
}
/// Modifies the value of a matrix uniform variable or a uniform variable array like `glUniformMatrix4fv`.
/// - parameter location: Location of the uniform value to be modified.
/// - parameter transpose: Whether to transpose the matrix as the values are loaded into the uniform variable. Must be GL_FALSE.
/// - parameter matrix: Matrix that will be used to update the specified uniform variable.
func glUniformGLKMatrix4(_ location: GLint, _ transpose: GLboolean, _ matrix: inout GLKMatrix4) {
let capacity = MemoryLayout.size(ofValue: matrix.m)/MemoryLayout.size(ofValue: matrix.m.0)
withUnsafePointer(to: &matrix.m) {
$0.withMemoryRebound(to: GLfloat.self, capacity: capacity) {
glUniformMatrix4fv(location, 1, transpose, $0)
}
}
}
| mit | d08186ceff68027213edf03feb66459c | 39.847619 | 128 | 0.677314 | 4.26554 | false | false | false | false |
lastobelus/eidolon | Kiosk/Bid Fulfillment/PlaceBidNetworkModel.swift | 4 | 1337 | import UIKit
import ReactiveCocoa
import Moya
class PlaceBidNetworkModel: NSObject {
var fulfillmentController: FulfillmentController!
var bidderPosition: BidderPosition?
init(fulfillmentController: FulfillmentController) {
self.fulfillmentController = fulfillmentController
super.init()
}
func bidSignal(bidDetails: BidDetails) -> RACSignal {
let saleArtwork = bidDetails.saleArtwork
let cents = String(bidDetails.bidAmountCents! as Int)
return bidOnSaleArtwork(saleArtwork!, bidAmountCents: cents)
}
private func bidOnSaleArtwork(saleArtwork: SaleArtwork, bidAmountCents: String) -> RACSignal {
let bidEndpoint: ArtsyAPI = ArtsyAPI.PlaceABid(auctionID: saleArtwork.auctionID!, artworkID: saleArtwork.artwork.id, maxBidCents: bidAmountCents)
let request = fulfillmentController.loggedInProvider!.request(bidEndpoint).filterSuccessfulStatusCodes().mapJSON().mapToObject(BidderPosition.self)
return request.doNext { [weak self] (position) -> Void in
self?.bidderPosition = position as? BidderPosition
return
}.doError { (error) in
logger.log("Bidding on Sale Artwork failed.")
logger.log("Error: \(error.localizedDescription). \n \(error.artsyServerError())")
}
}
}
| mit | dd268c8692820392f8eabfa9cfc778ad | 33.282051 | 155 | 0.709798 | 5.222656 | false | false | false | false |
wjk930726/weibo | weiBo/weiBo/iPhone/Modules/Home/View/StatusCell/WBStatusCell.swift | 1 | 1631 | //
// WBStatusCell.swift
// weiBo
//
// Created by 王靖凯 on 2016/11/29.
// Copyright © 2016年 王靖凯. All rights reserved.
//
import UIKit
class WBStatusCell: UITableViewCell {
var status: WBStatusViewModel? {
didSet {
originView.status = status
retweetedView.retweetedStatus = status
}
}
fileprivate lazy var originView: WBOriginalView = WBOriginalView()
fileprivate lazy var retweetedView: WBRetweetedView = WBRetweetedView()
fileprivate lazy var toolView: WBToolView = WBToolView()
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
setupCell()
}
required init?(coder _: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension WBStatusCell {
fileprivate func setupCell() {
contentView.backgroundColor = UIColor.lightGray
contentView.addSubview(originView)
contentView.addSubview(retweetedView)
contentView.addSubview(toolView)
originView.snp.makeConstraints { make in
make.top.leading.trailing.equalTo(contentView)
}
retweetedView.snp.makeConstraints { make in
make.top.equalTo(originView.snp.bottom)
make.leading.trailing.equalTo(contentView)
}
toolView.snp.makeConstraints { make in
make.top.equalTo(retweetedView.snp.bottom)
make.leading.trailing.equalTo(contentView)
make.height.equalTo(36)
make.bottom.equalTo(contentView)
}
}
}
| mit | ecbaf5f0959a4113518095e06ab223b2 | 27.857143 | 75 | 0.659653 | 4.630372 | false | false | false | false |
Avaruz/MemeV2 | Meme Me/Meme Me/SentMemeCollectionViewController.swift | 1 | 2117 | //
// SentMemeCollectionViewController.swift
// Meme Me
//
// Created by Adhemar Soria Galvarro on 7/12/15.
// Copyright © 2015 Adhemar Soria Galvarro. All rights reserved.
//
import UIKit
private let reuseIdentifier = "SentMemeCell"
class SentMemesCollectionViewController: UICollectionViewController {
@IBOutlet weak var flowLayout: UICollectionViewFlowLayout!
var memes: [Meme]! {
let object = UIApplication.sharedApplication().delegate
let appDelegate = object as! AppDelegate
return appDelegate.memes
}
override func viewDidLoad() {
super.viewDidLoad()
let space : CGFloat = 3.0
let itemWidth = (view.frame.size.width - (2 * space)) / space
let itemHeight = (view.frame.size.height - (2 * space)) / space
flowLayout.minimumInteritemSpacing = space
flowLayout.minimumLineSpacing = space
flowLayout.itemSize = CGSizeMake(itemWidth, itemHeight)
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
collectionView!.reloadData()
}
override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return memes.count
}
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! MemeCollectionViewCell
let meme = memes[indexPath.item]
cell.memeImageView?.image = meme.memedImage
return cell
}
override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
let memeDetailVC = storyboard!.instantiateViewControllerWithIdentifier("MemeDetailViewController") as! MemeDetailViewController
memeDetailVC.indexItem = indexPath.item
navigationController?.pushViewController(memeDetailVC, animated: true)
}
}
| gpl-2.0 | ce7dc7e1b16692264e16cf6487c90596 | 33.129032 | 141 | 0.698488 | 5.688172 | false | false | false | false |
ra1028/OwnKit | OwnKit/Extension/CATransform3D+OwnKit.swift | 1 | 2542 | //
// CATransform3D+OwnKit.swift
// OwnKit
//
// Created by Ryo Aoyama on 1/6/16.
// Copyright © 2016 Ryo Aoyama. All rights reserved.
//
import UIKit
public extension CATransform3D {
typealias TranslationValue = (x: CGFloat, y: CGFloat, z: CGFloat)
typealias ScaleValue = (x: CGFloat, y: CGFloat, z: CGFloat)
static var identity: CATransform3D {
return CATransform3DIdentity
}
var affine: CGAffineTransform {
return CATransform3DGetAffineTransform(self)
}
var isIdentity: Bool {
return CATransform3DIsIdentity(self)
}
var isAffine: Bool {
return CATransform3DIsAffine(self)
}
var invert: CATransform3D {
return CATransform3DInvert(self)
}
var translationValue: TranslationValue {
return (m41, m42, m43)
}
var scaleValue: ScaleValue {
return (m11, m22, m33)
}
static func translation(x x: CGFloat = 0, y: CGFloat = 0, z: CGFloat = 0) -> CATransform3D {
return CATransform3DMakeTranslation(x, y, z)
}
static func scale(x x: CGFloat = 1, y: CGFloat = 1, z: CGFloat = 1) -> CATransform3D {
return CATransform3DMakeScale(x, y, z)
}
static func scale(xy xy: CGFloat = 1, z: CGFloat = 1) -> CATransform3D {
return scale(x: xy, y: xy, z: z)
}
static func rotation(angle angle: CGFloat = 0, x: CGFloat = 0, y: CGFloat = 0, z: CGFloat = 0) -> CATransform3D {
return CATransform3DMakeRotation(angle, x, y, z)
}
static func affineTransform(affine: CGAffineTransform) -> CATransform3D {
return CATransform3DMakeAffineTransform(affine)
}
func translation(x x: CGFloat = 0, y: CGFloat = 0, z: CGFloat = 0) -> CATransform3D {
return CATransform3DTranslate(self, x, y, z)
}
func scale(x x: CGFloat = 1, y: CGFloat = 1, z: CGFloat = 1) -> CATransform3D {
return CATransform3DScale(self, x, y, z)
}
func scale(xy xy: CGFloat = 1, z: CGFloat = 1) -> CATransform3D {
return scale(x: xy, y: xy, z: z)
}
func rotation(angle angle: CGFloat = 0, x: CGFloat = 0, y: CGFloat = 0, z: CGFloat = 0) -> CATransform3D {
return CATransform3DRotate(self, angle, x, y, z)
}
func concat(transform: CATransform3D) -> CATransform3D {
return CATransform3DConcat(self, transform)
}
func isEqual(transform: CATransform3D) -> Bool {
return CATransform3DEqualToTransform(self, transform)
}
} | mit | d14e6147bf986f4219de4ab34a9a7b34 | 28.55814 | 117 | 0.616293 | 3.809595 | false | false | false | false |
Wolox/wolmo-core-ios | WolmoCore/Extensions/UIKit/UIView/Constraints.swift | 1 | 6193 | //
// Constraints.swift
// WolmoCore
//
// Created by Gaston Maspero on 1/21/20.
// Copyright © 2020 Wolox. All rights reserved.
//
import UIKit
extension UIView {
/**
Constrains the view to the specified anchors and size, with optional padding.
- Parameter top: Top anchor to which the view's top anchor will be constrained.
- Parameter leading: leading anchor to which the view's leading anchor will be constrained.
- Parameter bottom: bottom anchor to which the view's bottom anchor will be constrained.
- Parameter trailing: trailing anchor to which the view's trailing anchor will be constrained.
- Parameter padding: these are the constants to be added to the anchors, grouped in a UIEdgeInsets object.
- Parameter size: size to which the view will be constrained.
- Returns: Returns an AnchoredConstraints object, that contains the view's top, bottom, leading, trailing, width and height constraints. This result is discardable.
*/
@discardableResult
func anchor(top: NSLayoutYAxisAnchor? = .none,
leading: NSLayoutXAxisAnchor? = .none,
bottom: NSLayoutYAxisAnchor? = .none,
trailing: NSLayoutXAxisAnchor? = .none,
padding: UIEdgeInsets = .zero,
size: CGSize = .zero) -> AnchoredConstraints {
translatesAutoresizingMaskIntoConstraints = false
var anchoredConstraints = AnchoredConstraints()
if let top = top {
anchoredConstraints.top = topAnchor.constraint(equalTo: top, constant: padding.top)
}
if let leading = leading {
anchoredConstraints.leading = leadingAnchor.constraint(equalTo: leading, constant: padding.left)
}
if let bottom = bottom {
anchoredConstraints.bottom = bottomAnchor.constraint(equalTo: bottom, constant: -padding.bottom)
}
if let trailing = trailing {
anchoredConstraints.trailing = trailingAnchor.constraint(equalTo: trailing, constant: -padding.right)
}
if size.width != 0 {
anchoredConstraints.width = widthAnchor.constraint(equalToConstant: size.width)
}
if size.height != 0 {
anchoredConstraints.height = heightAnchor.constraint(equalToConstant: size.height)
}
[anchoredConstraints.top,
anchoredConstraints.leading,
anchoredConstraints.bottom,
anchoredConstraints.trailing,
anchoredConstraints.width,
anchoredConstraints.height].forEach { $0?.isActive = true }
return anchoredConstraints
}
/**
Constrains the view to the borders of its superview, with optional padding.
- Parameter padding: When using this parameter, the view will fill out its superview, using this paramater as padding.
*/
func fillSuperview(padding: UIEdgeInsets = .zero) {
translatesAutoresizingMaskIntoConstraints = false
if let superviewTopAnchor = superview?.topAnchor {
topAnchor.constraint(equalTo: superviewTopAnchor, constant: padding.top).isActive = true
}
if let superviewBottomAnchor = superview?.bottomAnchor {
bottomAnchor.constraint(equalTo: superviewBottomAnchor, constant: -padding.bottom).isActive = true
}
if let superviewLeadingAnchor = superview?.leadingAnchor {
leadingAnchor.constraint(equalTo: superviewLeadingAnchor, constant: padding.left).isActive = true
}
if let superviewTrailingAnchor = superview?.trailingAnchor {
trailingAnchor.constraint(equalTo: superviewTrailingAnchor, constant: -padding.right).isActive = true
}
}
/**
Centers the view to its superview, and constrains its height and width to the specified size.
- Parameter size: Size to which the view will be constrained.
*/
func centerInSuperview(size: CGSize = .zero) {
translatesAutoresizingMaskIntoConstraints = false
if let superviewCenterXAnchor = superview?.centerXAnchor {
centerXAnchor.constraint(equalTo: superviewCenterXAnchor).isActive = true
}
if let superviewCenterYAnchor = superview?.centerYAnchor {
centerYAnchor.constraint(equalTo: superviewCenterYAnchor).isActive = true
}
if size.width != 0 {
widthAnchor.constraint(equalToConstant: size.width).isActive = true
}
if size.height != 0 {
heightAnchor.constraint(equalToConstant: size.height).isActive = true
}
}
/**
Centers the view's x axis to its superview.
*/
func centerXInSuperview() {
translatesAutoresizingMaskIntoConstraints = false
if let superViewCenterXAnchor = superview?.centerXAnchor {
centerXAnchor.constraint(equalTo: superViewCenterXAnchor).isActive = true
}
}
/**
Centers the view's y axis to its superview.
*/
func centerYInSuperview() {
translatesAutoresizingMaskIntoConstraints = false
if let centerY = superview?.centerYAnchor {
centerYAnchor.constraint(equalTo: centerY).isActive = true
}
}
/**
Constrains the view's width to the specified parameter.
- Parameter constant: Constant to which the view's width will be constrained.
*/
func constrainWidth(constant: CGFloat) {
translatesAutoresizingMaskIntoConstraints = false
widthAnchor.constraint(equalToConstant: constant).isActive = true
}
/**
Constrains the view's height to the specified parameter.
- Parameter constant: Constant to which the view's height will be constrained.
*/
func constrainHeight(constant: CGFloat) {
translatesAutoresizingMaskIntoConstraints = false
heightAnchor.constraint(equalToConstant: constant).isActive = true
}
}
struct AnchoredConstraints {
var top, leading, bottom, trailing, width, height: NSLayoutConstraint?
}
| mit | e9fd2eab7d93865714c7e46b662e021f | 36.98773 | 169 | 0.655846 | 5.578378 | false | false | false | false |
ByteriX/BxInputController | BxInputController/Sources/Controller/BxInputSettings.swift | 1 | 5949 | /**
* @file BxInputSettings.swift
* @namespace BxInputController
*
* @details settings of BxInputController for custom showing any controllers or concrete
* @date 09.01.2017
* @author Sergey Balalaev
*
* @version last in https://github.com/ByteriX/BxInputController.git
* @copyright The MIT License (MIT) https://opensource.org/licenses/MIT
* Copyright (c) 2017 ByteriX. See http://byterix.com
*/
import UIKit
/// Settings of BxInputController for custom showing any controllers or concrete
public struct BxInputSettings
{
/// it is default for all BxInputController objects in a Target
public static var standart = BxInputSettings()
// MARK: - Header/Footer
/// The color of text in a header
public var headerColor: UIColor = secondaryLabel
/// The font of text in a header
public var headerFont: UIFont = UIFont.systemFont(ofSize: 16)
/// The color of text in a footer
public var footerColor: UIColor = tertiaryLabel
/// The font of text in a footer
public var footerFont: UIFont = UIFont.systemFont(ofSize: 12)
// MARK: - Row/Cell
/// it uses from selector rows, when user choose value then selector automatical will closed, if isAutodissmissSelector would be true
public var isAutodissmissSelector: Bool = true
/// The color of text in the title label for a row
public var titleColor: UIColor = label
/// The font of text in the title label for a row
public var titleFont: UIFont = UIFont.boldSystemFont(ofSize: 15)
/// The color of subtext in the subtitle label for a row
public var subtitleColor: UIColor = label
/// The font of subtext in the title label for a row
public var subtitleFont: UIFont = UIFont.systemFont(ofSize: 10)
/// The color of text in the value field for a row
public var valueColor: UIColor = label
/// The font of text in the value field for a row
public var valueFont: UIFont = UIFont.systemFont(ofSize: 15)
/// The color of placeholder in the value field for a row, the font is used from valueFont value.
public var placeholderColor: UIColor? = placeholderText
/// height of cells for all rows, which don't use a dynamic size or the static size
public var cellHeight: CGFloat? = 46
/// height for all headers with all content type exclude view, which don't use a dynamic size or the static size
public var headerHeight: CGFloat? = nil
/// height for all footers with all content type exclude view, which don't use a dynamic size or the static size
public var footerHeight: CGFloat? = nil
/// seporator inset of all cells
public var separatorInset = UIEdgeInsets(top: 0, left: 16, bottom: 0, right: 0)
/// margin of subtitle from bottom
public var subtitleMargin: CGFloat = 2.0
/// alignment of subtitle
public var subtitleAlignment: NSTextAlignment = .left
/// date format for showing value of the rows with date type
public var dateFormat: DateFormatter = DateFormatter(dateStyle: DateFormatter.Style.long, timeStyle: DateFormatter.Style.none)
// MARK: - Decorator featurese BxInputStandartErrorRowDecorator
/// The color for error marking. See BxInputStandartErrorRowDecorator when it used.
public var errorColor: UIColor = UIColor.red
/// If user put a incorrected value the field will shake
public var isErrorHasShake: Bool = true
/// When user put a incorrected value and should shown subtitle you can change that aligment, different with subtitleAlignment. If it is nil then will not change subtitleAlignment.
public var errorSubtitleAlignment: NSTextAlignment? = .right
// MARK: - this don't used for a future
var indentWidth: CGFloat = 10 // tagWidth / lineShift analog
// MARK: - enabled/disabled options:
/// If it is true then visual with UI will be nothing, else uses disabledViewAplpha or changeViewEnableHandler. This has high priority. Default NO.
public var isNormalShowingDisabledCell: Bool = false
/// If isNormalShowingDisabledCell == true then it ignored. It is doing possible change view from isEnabled status. Default is ignored.
public var changeViewEnableHandler: ((_ view: UIView, _ isEnabled: Bool) -> Void)? = nil
/// If isNormalShowingDisabledCell == true or changeViewEnableHandler != nil then it ignored. Used for hidden showing view in cell when it need for showing disabled row. Value can be between 0..1
public var alphaForDisabledView: CGFloat = 0.5
// MARK: - Strings values
/// title of the back button on the keyboard panel
public var backButtonTitle = "Up"
/// title of the next button on the keyboard panel
public var nextButtonTitle = "Down"
/// title of the done button on the keyboard panel
public var doneButtonTitle = "Done"
/// Default initializer
public init() {
// all defined
}
}
extension BxInputSettings {
public static var label : UIColor {
if #available(iOS 13.0, *) {
return UIColor.label
} else {
return UIColor.black
}
}
public static var secondaryLabel : UIColor {
if #available(iOS 13.0, *) {
return UIColor.secondaryLabel
} else {
return UIColor.darkGray
}
}
public static var tertiaryLabel : UIColor {
if #available(iOS 13.0, *) {
return UIColor.tertiaryLabel
} else {
return UIColor.gray
}
}
public static var quaternaryLabel : UIColor {
if #available(iOS 13.0, *) {
return UIColor.quaternaryLabel
} else {
return UIColor.lightGray
}
}
public static var placeholderText : UIColor? {
if #available(iOS 13.0, *) {
return UIColor.placeholderText
} else {
return nil
}
}
}
| mit | 17c31f2198033b5c7bcda5da31c977da | 39.195946 | 199 | 0.677761 | 4.662226 | false | false | false | false |
eggswift/ESTabBarController | Sources/ESTabBarController.swift | 1 | 6197 | //
// ESTabBarController.swift
//
// Created by Vincent Li on 2017/2/8.
// Copyright (c) 2013-2020 ESTabBarController (https://github.com/eggswift/ESTabBarController)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import UIKit
/// 是否需要自定义点击事件回调类型
public typealias ESTabBarControllerShouldHijackHandler = ((_ tabBarController: UITabBarController, _ viewController: UIViewController, _ index: Int) -> (Bool))
/// 自定义点击事件回调类型
public typealias ESTabBarControllerDidHijackHandler = ((_ tabBarController: UITabBarController, _ viewController: UIViewController, _ index: Int) -> (Void))
open class ESTabBarController: UITabBarController, ESTabBarDelegate {
/// 打印异常
public static func printError(_ description: String) {
#if DEBUG
print("ERROR: ESTabBarController catch an error '\(description)' \n")
#endif
}
/// 当前tabBarController是否存在"More"tab
public static func isShowingMore(_ tabBarController: UITabBarController?) -> Bool {
return tabBarController?.moreNavigationController.parent != nil
}
/// Ignore next selection or not.
fileprivate var ignoreNextSelection = false
/// Should hijack select action or not.
open var shouldHijackHandler: ESTabBarControllerShouldHijackHandler?
/// Hijack select action.
open var didHijackHandler: ESTabBarControllerDidHijackHandler?
/// Observer tabBarController's selectedViewController. change its selection when it will-set.
open override var selectedViewController: UIViewController? {
willSet {
guard let newValue = newValue else {
// if newValue == nil ...
return
}
guard !ignoreNextSelection else {
ignoreNextSelection = false
return
}
guard let tabBar = self.tabBar as? ESTabBar, let items = tabBar.items, let index = viewControllers?.firstIndex(of: newValue) else {
return
}
let value = (ESTabBarController.isShowingMore(self) && index > items.count - 1) ? items.count - 1 : index
tabBar.select(itemAtIndex: value, animated: false)
}
}
/// Observer tabBarController's selectedIndex. change its selection when it will-set.
open override var selectedIndex: Int {
willSet {
guard !ignoreNextSelection else {
ignoreNextSelection = false
return
}
guard let tabBar = self.tabBar as? ESTabBar, let items = tabBar.items else {
return
}
let value = (ESTabBarController.isShowingMore(self) && newValue > items.count - 1) ? items.count - 1 : newValue
tabBar.select(itemAtIndex: value, animated: false)
}
}
/// Customize set tabBar use KVC.
open override func viewDidLoad() {
super.viewDidLoad()
let tabBar = { () -> ESTabBar in
let tabBar = ESTabBar()
tabBar.delegate = self
tabBar.customDelegate = self
tabBar.tabBarController = self
return tabBar
}()
self.setValue(tabBar, forKey: "tabBar")
}
// MARK: - UITabBar delegate
open override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
guard let idx = tabBar.items?.firstIndex(of: item) else {
return;
}
if idx == tabBar.items!.count - 1, ESTabBarController.isShowingMore(self) {
ignoreNextSelection = true
selectedViewController = moreNavigationController
return;
}
if let vc = viewControllers?[idx] {
ignoreNextSelection = true
selectedIndex = idx
delegate?.tabBarController?(self, didSelect: vc)
}
}
open override func tabBar(_ tabBar: UITabBar, willBeginCustomizing items: [UITabBarItem]) {
if let tabBar = tabBar as? ESTabBar {
tabBar.updateLayout()
}
}
open override func tabBar(_ tabBar: UITabBar, didEndCustomizing items: [UITabBarItem], changed: Bool) {
if let tabBar = tabBar as? ESTabBar {
tabBar.updateLayout()
}
}
// MARK: - ESTabBar delegate
internal func tabBar(_ tabBar: UITabBar, shouldSelect item: UITabBarItem) -> Bool {
if let idx = tabBar.items?.firstIndex(of: item), let vc = viewControllers?[idx] {
return delegate?.tabBarController?(self, shouldSelect: vc) ?? true
}
return true
}
internal func tabBar(_ tabBar: UITabBar, shouldHijack item: UITabBarItem) -> Bool {
if let idx = tabBar.items?.firstIndex(of: item), let vc = viewControllers?[idx] {
return shouldHijackHandler?(self, vc, idx) ?? false
}
return false
}
internal func tabBar(_ tabBar: UITabBar, didHijack item: UITabBarItem) {
if let idx = tabBar.items?.firstIndex(of: item), let vc = viewControllers?[idx] {
didHijackHandler?(self, vc, idx)
}
}
}
| mit | 69dec956fc98179cee4f5a8a395cd1d0 | 39.296053 | 159 | 0.644082 | 5.078773 | false | false | false | false |
xilosada/TravisViewerIOS | TVModel/DiskStorage.swift | 1 | 3114 | //
// Storage.swift
// TravisViewerIOS
//
// Created by X.I. Losada on 13/02/16.
// Copyright © 2016 XiLosada. All rights reserved.
//
import Foundation
import RxSwift
import CoreData
///Persistance API implementation using CoreData
public class DiskStorage: DiskStoraging {
public enum StorageError: ErrorType {
case NotFound
case UnknownError
}
private let cdsManager: CoreDataStackManager!
public init(cdsManager: CoreDataStackManager) {
self.cdsManager = cdsManager
}
public func loadUser(name:String) -> Observable<UserEntity> {
return loadDbUser(name).map{ $0.toEntity() }
}
private func loadDbUser(name:String) -> Observable<User> {
return Observable.create { observer in
print("load \(name) from DB")
do{
let fetchRequest = NSFetchRequest(entityName: "User")
fetchRequest.predicate = NSPredicate(format: "name == %@", name)
let users = try self.cdsManager.managedObjectContext.executeFetchRequest(fetchRequest) as! [User]
if let user = users.first {
observer.on(.Next(user))
observer.on(.Completed)
return NopDisposable.instance
} else {
observer.on(.Error(StorageError.NotFound))
}
} catch {
observer.on(.Error(StorageError.UnknownError))
}
return NopDisposable.instance
}
}
public func loadRepo(id:Int) -> Observable<RepositoryEntity>{
return Observable.create { observer in
print("load repo \(id) from DB")
do{
let fetchRequest = NSFetchRequest(entityName: "Repo")
let repos = try self.cdsManager.managedObjectContext.executeFetchRequest(fetchRequest) as! [Repo]
if let repo = repos.filter({ $0.id == id}).first {
observer.on(.Next(repo.toEntity()))
observer.on(.Completed)
return NopDisposable.instance
} else {
observer.on(.Error(StorageError.NotFound))
}
} catch {
observer.on(.Error(StorageError.UnknownError))
}
return NopDisposable.instance
}
}
public func saveUser(user:UserEntity) -> Observable<Bool> {
return Observable.create { observer in
print("Saving \(user.name) to DB")
let _ = user.parseToDBO(self.cdsManager.managedObjectContext)
self.cdsManager.saveContext()
observer.on(.Next(true))
observer.on(.Completed)
return NopDisposable.instance
}
}
public func flushDb() -> Observable<Bool> {
return loadDbUser("").map{ user in
print("flush DB")
self.cdsManager.managedObjectContext.deleteObject(user)
return true
}
}
} | mit | 1e909282497c3389cd1c085647a25f9e | 32.12766 | 113 | 0.553807 | 5.070033 | false | false | false | false |
mgoenka/iOS-TipCalculator | tipCaluculator/ViewController.swift | 1 | 1952 | //
// ViewController.swift
// tips
//
// Created by Mohit Goenka on 9/7/14.
// Copyright (c) 2014 mgoenka. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var tipControl: UISegmentedControl!
@IBOutlet weak var billField: UITextField!
@IBOutlet weak var tipLabel: UILabel!
@IBOutlet weak var totalLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
tipLabel.text = "$0.00"
totalLabel.text = "$0.00"
}
override func viewWillAppear(animated: Bool) {
super.viewDidAppear(animated)
println("view did appear")
var defaults = NSUserDefaults.standardUserDefaults()
var defaultTipPercentage = defaults.integerForKey("default_tip")
if (defaultTipPercentage == 18) {
tipControl.selectedSegmentIndex = 0
} else if (defaultTipPercentage == 20) {
tipControl.selectedSegmentIndex = 1
} else {
tipControl.selectedSegmentIndex = 2
}
updateTip()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func onEditingChanged(sender: AnyObject) {
updateTip()
}
@IBAction func onTap(sender: AnyObject) {
view.endEditing(true)
}
func updateTip() {
var tipPercentages = [0.18, 0.2, 0.22]
var tipPercentage = tipPercentages[tipControl.selectedSegmentIndex]
var billAmount = Double((billField.text as NSString).doubleValue)
var tip = billAmount * tipPercentage
var total = billAmount + tip
tipLabel.text = String(format: "$%.2f", tip)
totalLabel.text = String(format: "$%.2f", total)
}
}
| mit | 6ac8852c0155dd6b31251f6782e88f30 | 28.134328 | 80 | 0.618852 | 4.855721 | false | false | false | false |
6ag/AppScreenshots | AppScreenshots/Classes/Module/Home/Transition/JFPhotoPresentationController.swift | 1 | 1270 | //
// JFPhotoPresentationController.swift
// popoverDemo
//
// Created by jianfeng on 15/11/9.
// Copyright © 2015年 六阿哥. All rights reserved.
//
import UIKit
class JFPhotoPresentationController: UIPresentationController {
override func containerViewWillLayoutSubviews() {
super.containerViewWillLayoutSubviews()
// 设置容器视图透明背景
let bgView = UIView(frame: SCREEN_BOUNDS)
bgView.backgroundColor = UIColor(white: 0, alpha: 0.5)
containerView?.insertSubview(bgView, at: 0)
// 添加点击手势
let tap = UITapGestureRecognizer(target: self, action: #selector(didTappedContainerView))
bgView.addGestureRecognizer(tap)
// 呈现视图尺寸
let popWidth: CGFloat = layoutHorizontal(iPhone6: 300)
let popHeight: CGFloat = layoutVertical(iPhone6: 370)
presentedView?.frame = CGRect(x: (SCREEN_WIDTH - popWidth) * 0.5, y: STATUS_HEIGHT + layoutVertical(iPhone6: 40), width: popWidth, height: popHeight)
}
/**
容器视图区域的点击手势
*/
@objc fileprivate func didTappedContainerView() {
presentedViewController.dismiss(animated: true, completion: nil)
}
}
| mit | e76bdcd6ea1160bda8898095e9772e0b | 30.447368 | 157 | 0.659414 | 4.458955 | false | false | false | false |
mercadopago/px-ios | MercadoPagoSDK/MercadoPagoSDK/Tracking/MPXTracker.swift | 1 | 4628 | import UIKit
@objc class MPXTracker: NSObject {
@objc static let sharedInstance = MPXTracker()
private var trackListener: PXTrackerListener?
private var flowDetails: [String: Any]?
private var flowName: String?
private var customSessionId: String?
private var collectorId: String?
private var sessionService: SessionService = SessionService()
private var experiments: [PXExperiment]?
}
// MARK: Getters/setters.
extension MPXTracker {
func setTrack(listener: PXTrackerListener) {
if isPXAddonTrackListener() {
return
}
trackListener = listener
}
func setFlowDetails(flowDetails: [String: Any]?) {
self.flowDetails = flowDetails
}
func setFlowName(name: String?) {
self.flowName = name
}
func setCustomSessionId(_ customSessionId: String?) {
self.customSessionId = customSessionId
}
func startNewSession() {
sessionService.startNewSession()
}
func startNewSession(externalSessionId: String) {
sessionService.startNewSession(externalSessionId: externalSessionId)
}
func getSessionID() -> String {
return customSessionId ?? sessionService.getSessionId()
}
func getRequestId() -> String {
return sessionService.getRequestId()
}
func clean() {
if !isPXAddonTrackListener() {
MPXTracker.sharedInstance.trackListener = nil
}
MPXTracker.sharedInstance.flowDetails = [:]
MPXTracker.sharedInstance.experiments = nil
}
func getFlowName() -> String? {
return flowName
}
func setExperiments(_ experiments: [PXExperiment]?) {
MPXTracker.sharedInstance.experiments = experiments
}
private func isPXAddonTrackListener() -> Bool {
if let trackListener = trackListener,
String(describing: trackListener.self).contains("PXAddon.PXTrack") {
return true
}
return false
}
private func appendFlow(to metadata: [String: Any]) -> [String: Any] {
var metadata = metadata
// TODO: Validate default value for flow name
metadata["flow"] = flowName ?? "PX"
return metadata
}
private func appendExternalData(to metadata: [String: Any]) -> [String: Any] {
var metadata = metadata
if let flowDetails = flowDetails {
metadata["flow_detail"] = flowDetails
}
metadata[SessionService.SESSION_ID_KEY] = getSessionID()
metadata["session_time"] = PXTrackingStore.sharedInstance.getSecondsAfterInit()
if let checkoutType = PXTrackingStore.sharedInstance.getChoType() {
metadata["checkout_type"] = checkoutType
}
if let collectorID = PXCheckoutStore.sharedInstance.getCheckoutPreference()?.collectorId {
metadata["collector_id"] = collectorID
}
metadata["security_enabled"] = PXConfiguratorManager.hasSecurityValidation()
if let experiments = experiments {
metadata["experiments"] = PXExperiment.getExperimentsForTracking(experiments)
}
return metadata
}
}
// MARK: Public interfase.
extension MPXTracker {
func trackScreen(event: TrackingEvents) {
if let trackListenerInterfase = trackListener {
var metadata = appendFlow(to: event.properties)
metadata = appendExternalData(to: metadata)
trackListenerInterfase.trackScreen(screenName: event.name, extraParams: metadata)
}
}
func trackEvent(event: TrackingEvents) {
if let trackListenerInterfase = trackListener {
var metadata = appendFlow(to: event.properties)
if event.name == TrackingPaths.Events.getErrorPath() {
var frictionExtraInfo: [String: Any] = [:]
if let extraInfo = metadata["extra_info"] as? [String: Any] {
frictionExtraInfo = extraInfo
}
metadata["extra_info"] = appendExternalData(to: frictionExtraInfo)
if let experiments = experiments {
metadata["experiments"] = PXExperiment.getExperimentsForTracking(experiments)
}
metadata["security_enabled"] = PXConfiguratorManager.hasSecurityValidation()
metadata["session_time"] = PXTrackingStore.sharedInstance.getSecondsAfterInit()
}
metadata = appendExternalData(to: metadata)
trackListenerInterfase.trackEvent(screenName: event.name, action: "", result: "", extraParams: metadata)
}
}
}
| mit | 8900eebddc3258dc6e5d0e6b89928085 | 30.917241 | 116 | 0.640449 | 4.805815 | false | false | false | false |
clappr/clappr-ios | Tests/Clappr_Tests/Classes/Extensions/Dictionary+ExtTests.swift | 1 | 2272 | import Quick
import Nimble
@testable import Clappr
class DictionaryExtensionTests: QuickSpec {
override func spec() {
describe("Dictionary+Ext") {
describe("#startAt") {
it("returns a Double value if it's a Double") {
let dict: Options = [kStartAt: Double(10)]
expect(dict.startAt).to(beAKindOf(Double.self))
expect(dict.startAt).to(equal(10.0))
}
it("returns a Double value if it's a Int") {
let dict: Options = [kStartAt: Int(10)]
expect(dict.startAt).to(beAKindOf(Double.self))
expect(dict.startAt).to(equal(10.0))
}
it("returns a Double value if it's a String") {
let dict: Options = [kStartAt: String(10)]
expect(dict.startAt).to(beAKindOf(Double.self))
expect(dict.startAt).to(equal(10.0))
}
it("returns nil if it's not a String, Int or Double") {
let dict: Options = [kStartAt: []]
expect(dict.startAt).to(beNil())
}
}
describe("#bool") {
context("when has a bool option in dictionary") {
it("returns true") {
let options: Options = ["foo": true]
expect(options.bool("foo")).to(beTrue())
}
it("returns false") {
let options: Options = ["foo": false]
expect(options.bool("foo")).to(beFalse())
}
}
context("when doesn't have the bool option in dictionary") {
it("returns whichever boolean value we choose") {
let options: Options = [:]
expect(options.bool("foo", orElse: true)).to(beTrue())
expect(options.bool("foo", orElse: false)).to(beFalse())
}
}
}
}
}
}
| bsd-3-clause | 39f978dadc3bb11d19d1c3ae16eb2c57 | 34.5 | 80 | 0.420775 | 5.308411 | false | false | false | false |
tokyovigilante/CesiumKit | CesiumKit/Core/Packable.swift | 1 | 4246 | //
// Packable.swift
// CesiumKit
//
// Created by Ryan Walklin on 9/06/14.
// Copyright (c) 2014 Test Toast. All rights reserved.
//
import Foundation
/**
* Static interface for types which can store their values as packed
* elements in an array. These methods and properties are expected to be
* defined on a constructor function.
*
* @exports Packable
*
* @see PackableForInterpolation
*/
protocol Packable {
/**
* The number of elements used to pack the object into an array.
* @type {Number}
*/
static func packedLength () -> Int
init (array: [Double], startingIndex: Int)
/**
* Stores the provided instance into the provided array.
* @function
*
* @param {Object} value The value to pack.
* @param {Number[]} array The array to pack into.
*/
func pack (_ array: inout [Float], startingIndex: Int)
func toArray () -> [Double]
/**
* Retrieves an instance from a packed array.
* @function
*
* @param {Number[]} array The packed array.
* @param {Number} [startingIndex=0] The starting index of the element to be unpacked.
* @param {Object} [result] The object into which to store the result.
*/
static func unpack(_ array: [Float], startingIndex: Int) -> Self
func checkPackedArrayLength(_ array: [Double], startingIndex: Int) -> Bool
}
extension Packable {
/**
* Stores the provided instance into the provided array.
*
* @param {Matrix3} value The value to pack.
* @param {Number[]} array The array to pack into.
* @param {Number} [startingIndex=0] The index into the array at which to start packing the elements.
*/
func pack(_ array: inout [Float], startingIndex: Int = 0) {
let doubleArray = self.toArray()
//let floatArray = self.toArray().map { Float($0) }
//let fs = strideof(Float)
//let arrayLength = array.count
assert(array.count >= startingIndex + Self.packedLength(), "short array")
//var grid = [Double](count: packedLength, repeatedValue: 0.0)
/*array.withUnsafeMutableBufferPointer { (inout pointer: UnsafeMutableBufferPointer<Float>) in
memcpy(pointer.baseAddress+startingIndex*fs, floatArray, floatArray.count*fs)
}*/
/*
if array.count < startingIndex + Self.packedLength() {
for i in doubleArray.indices {
array.append(Float(array[i]))
}
//array.appendContentsOf(floatArray)
} else {*/
for i in doubleArray.indices {
array[startingIndex+i] = Float(doubleArray[i])
}
//array.replaceRange(Range(start: startingIndex, end: startingIndex+floatArray.count), with: floatArray)
/*}*/
}
/**
* Creates an Array from the provided Matrix3 instance.
* The array will be in column-major order.
*
* @param {Matrix3} matrix The matrix to use..
* @param {Number[]} [result] The Array onto which to store the result.
* @returns {Number[]} The modified Array parameter or a new Array instance if one was not provided.
*/
func toArray() -> [Double] {
let packedLength = Self.packedLength()
var grid = [Double](repeating: 0.0, count: packedLength)
memcpy(&grid, [self], packedLength * MemoryLayout<Double>.stride)
/*grid.withUnsafeMutableBufferPointer { (inout pointer: UnsafeMutableBufferPointer<Double>) in
memcpy(pointer.baseAddress, [self], packedLength * strideof(Double))
}*/
return grid
}
/**
* Retrieves an instance from a packed array.
*
* @param {Number[]} array The packed array.
* @param {Number} [startingIndex=0] The starting index of the element to be unpacked.
* @param {Matrix3} [result] The object into which to store the result.
*/
static func unpack(_ array: [Float], startingIndex: Int = 0) -> Self {
return Self(array: array.map { Double($0) }, startingIndex: startingIndex)
}
func checkPackedArrayLength(_ array: [Double], startingIndex: Int) -> Bool {
return array.count - startingIndex >= Self.packedLength()
}
}
| apache-2.0 | 9c7736e7d217710f038896e65cc49c88 | 32.698413 | 116 | 0.622939 | 4.386364 | false | false | false | false |
3drobotics/SwiftIO | Sources/SocketOptions.swift | 2 | 16101 | //
// SocketOptions.swift
// SwiftIO
//
// Created by Jonathan Wight on 1/25/16.
// Copyright © 2016 schwa.io. All rights reserved.
//
import Darwin
import SwiftUtilities
extension Socket {
public func getsockopt <T>(level: Int32, _ name: Int32) throws -> T {
guard try getsockoptsize(level, name) == sizeof(T) else {
fatalError("Expected size of \(T.self) \(sizeof(T)) doesn't match what getsocktopt expects: \(try? getsockoptsize(level, name))")
}
let ptr = UnsafeMutablePointer <T>.alloc(1)
defer {
ptr.dealloc(1)
}
var length = socklen_t(sizeof(T))
let result = Darwin.getsockopt(descriptor, level, name, ptr, &length)
if result != 0 {
throw Errno(rawValue: errno) ?? Error.Unknown
}
let value = ptr.memory
return value
}
public func setsockopt <T>(level: Int32, _ name: Int32, _ value: T) throws {
guard try getsockoptsize(level, name) == sizeof(T) else {
fatalError("Expected size of \(T.self) \(sizeof(T)) doesn't match what getsocktopt expects: \(try? getsockoptsize(level, name))")
}
var value = value
let result = Darwin.setsockopt(descriptor, level, name, &value, socklen_t(sizeof(T)))
if result != 0 {
throw Errno(rawValue: errno) ?? Error.Unknown
}
}
// Just for bools
public func getsockopt(level: Int32, _ name: Int32) throws -> Bool {
let value: Int32 = try getsockopt(level, name)
return value != 0
}
public func setsockopt(level: Int32, _ name: Int32, _ value: Bool) throws {
let value: Int32 = value ? -1 : 0
try setsockopt(level, name, value)
}
// Just for bools
public func getsockopt(level: Int32, _ name: Int32) throws -> NSTimeInterval {
let value: timeval64 = try getsockopt(level, name)
return value.timeInterval
}
public func setsockopt(level: Int32, _ name: Int32, _ value: NSTimeInterval) throws {
try setsockopt(level, name, timeval64(time: value))
}
// Test size of a socket option
private func getsockoptsize(level: Int32, _ name: Int32) throws -> Int {
var length = socklen_t(256)
var buffer = Array <UInt8> (count: Int(length), repeatedValue: 0)
return try buffer.withUnsafeMutableBufferPointer() {
(inout buffer: UnsafeMutableBufferPointer<UInt8>) -> Int in
let result = Darwin.getsockopt(descriptor, level, name, buffer.baseAddress, &length)
if result != 0 {
throw Errno(rawValue: errno) ?? Error.Unknown
}
return Int(length)
}
}
}
public extension Socket {
var socketOptions: SocketOptions {
return SocketOptions(socket: self)
}
}
// MARK: -
public class SocketOptions {
public private(set) weak var socket: Socket!
public init(socket: Socket) {
self.socket = socket
}
}
// MARK: -
public extension SocketOptions {
/// turn on debugging info recording
var debug: Bool {
get {
return try! socket.getsockopt(SOL_SOCKET, SO_DEBUG)
}
set {
try! socket.setsockopt(SOL_SOCKET, SO_DEBUG, newValue)
}
}
/// socket has had listen()
var acceptConnection: Bool {
get {
return try! socket.getsockopt(SOL_SOCKET, SO_ACCEPTCONN)
}
set {
try! socket.setsockopt(SOL_SOCKET, SO_ACCEPTCONN, newValue)
}
}
/// allow local address reuse
var reuseAddress: Bool {
get {
return try! socket.getsockopt(SOL_SOCKET, SO_REUSEADDR)
}
set {
try! socket.setsockopt(SOL_SOCKET, SO_REUSEADDR, newValue)
}
}
/// keep connections alive
var keepAlive: Bool {
get {
return try! socket.getsockopt(SOL_SOCKET, SO_KEEPALIVE)
}
set {
try! socket.setsockopt(SOL_SOCKET, SO_KEEPALIVE, newValue)
}
}
/// just use interface addresses
var dontRoute: Bool {
get {
return try! socket.getsockopt(SOL_SOCKET, SO_DONTROUTE)
}
set {
try! socket.setsockopt(SOL_SOCKET, SO_DONTROUTE, newValue)
}
}
/// permit sending of broadcast msgs
var broadcast: Bool {
get {
return try! socket.getsockopt(SOL_SOCKET, SO_BROADCAST)
}
set {
try! socket.setsockopt(SOL_SOCKET, SO_BROADCAST, newValue)
}
}
/// bypass hardware when possible
var useLoopback: Bool {
get {
return try! socket.getsockopt(SOL_SOCKET, SO_USELOOPBACK)
}
set {
try! socket.setsockopt(SOL_SOCKET, SO_USELOOPBACK, newValue)
}
}
/// linger on close if data present (in ticks)
var linger: Int64 {
get {
return try! socket.getsockopt(SOL_SOCKET, SO_LINGER)
}
set {
try! socket.setsockopt(SOL_SOCKET, SO_LINGER, newValue)
}
}
/// leave received OOB data in line
var outOfBandInline: Bool {
get {
return try! socket.getsockopt(SOL_SOCKET, SO_OOBINLINE)
}
set {
try! socket.setsockopt(SOL_SOCKET, SO_OOBINLINE, newValue)
}
}
/// allow local address & port reuse
var reusePort: Bool {
get {
return try! socket.getsockopt(SOL_SOCKET, SO_REUSEPORT)
}
set {
try! socket.setsockopt(SOL_SOCKET, SO_REUSEPORT, newValue)
}
}
// SO_TIMESTAMP
// SO_TIMESTAMP_MONOTONIC
// SO_DONTTRUNC: APPLE: Retain unread data *
// SO_WANTMORE: APPLE: Give hint when more data ready *
// SO_WANTOOBFLAG: APPLE: Want OOB in MSG_FLAG on receive *
/// send buffer size *
var sendBufferSize: Int32 {
get {
return try! socket.getsockopt(SOL_SOCKET, SO_SNDBUF)
}
set {
try! socket.setsockopt(SOL_SOCKET, SO_SNDBUF, newValue)
}
}
/// receive buffer size *
var receiveBufferSize: Int32 {
get {
return try! socket.getsockopt(SOL_SOCKET, SO_RCVBUF)
}
set {
try! socket.setsockopt(SOL_SOCKET, SO_RCVBUF, newValue)
}
}
/// send low-water mark *
var sendLowWaterMark: Int32 {
get {
return try! socket.getsockopt(SOL_SOCKET, SO_SNDLOWAT)
}
set {
try! socket.setsockopt(SOL_SOCKET, SO_SNDLOWAT, newValue)
}
}
/// receive low-water mark
var receiveLowWaterMark: Int32 {
get {
return try! socket.getsockopt(SOL_SOCKET, SO_RCVLOWAT)
}
set {
try! socket.setsockopt(SOL_SOCKET, SO_RCVLOWAT, newValue)
}
}
/// send timeout
var sendTimeout: NSTimeInterval {
get {
return try! socket.getsockopt(SOL_SOCKET, SO_SNDTIMEO)
}
set {
try! socket.setsockopt(SOL_SOCKET, SO_SNDTIMEO, newValue)
}
}
/// receive timeout
var receiveTimeout: NSTimeInterval {
get {
return try! socket.getsockopt(SOL_SOCKET, SO_RCVTIMEO)
}
set {
try! socket.setsockopt(SOL_SOCKET, SO_RCVTIMEO, newValue)
}
}
/// get error status and clear *
var error: Int32 {
get {
return try! socket.getsockopt(SOL_SOCKET, SO_ERROR)
}
}
/// get socket type *
var type: Int32 {
get {
return try! socket.getsockopt(SOL_SOCKET, SO_TYPE)
}
}
// SO_LABEL: socket's MAC label *
// SO_PEERLABEL: socket's peer MAC label *
// SO_NREAD: APPLE: get 1st-packet byte count *
// SO_NKE: APPLE: Install socket-level NKE *
// SO_NOSIGPIPE: APPLE: No SIGPIPE on EPIPE *
// SO_NOADDRERR: APPLE: Returns EADDRNOTAVAIL when src is not available anymore *
/// APPLE: Get number of bytes currently in send socket buffer *
var nwrite: Int32 {
get {
return try! socket.getsockopt(SOL_SOCKET, SO_NWRITE)
}
}
// SO_REUSESHAREUID: APPLE: Allow reuse of port/socket by different userids *
/// APPLE: send notification if there is a bind on a port which is already in use *
var notifyConflict: Bool {
get {
return try! socket.getsockopt(SOL_SOCKET, SO_NOTIFYCONFLICT)
}
set {
try! socket.setsockopt(SOL_SOCKET, SO_NOTIFYCONFLICT, newValue)
}
}
/// APPLE: block on close until an upcall returns *
var upcallCloseWait: Bool {
get {
return try! socket.getsockopt(SOL_SOCKET, SO_UPCALLCLOSEWAIT)
}
set {
try! socket.setsockopt(SOL_SOCKET, SO_UPCALLCLOSEWAIT, newValue)
}
}
/// linger on close if data present (in seconds) *
var lingerSeconds: Int64 {
get {
return try! socket.getsockopt(SOL_SOCKET, SO_LINGER_SEC)
}
set {
try! socket.setsockopt(SOL_SOCKET, SO_LINGER_SEC, newValue)
}
}
/// APPLE: request local port randomization *
var randomPort: Bool {
get {
return try! socket.getsockopt(SOL_SOCKET, SO_RANDOMPORT)
}
set {
try! socket.setsockopt(SOL_SOCKET, SO_RANDOMPORT, newValue)
}
}
// SO_NP_EXTENSIONS: To turn off some POSIX behavior *
/// number of datagrams in receive socket buffer *
var numberOfReceiveDatagrams: Bool {
get {
return try! socket.getsockopt(SOL_SOCKET, SO_NUMRCVPKT)
}
}
}
public extension SocketOptions {
var all: [String: Any] {
var all: [String: Any] = [:]
all["debug"] = debug
// all["acceptConnection"] = acceptConnection
all["reuseAddress"] = reuseAddress
all["keepAlive"] = keepAlive
all["dontRoute"] = dontRoute
all["broadcast"] = broadcast
all["useLoopback"] = useLoopback
all["linger"] = linger
all["outOfBandInline"] = outOfBandInline
all["reusePort"] = reusePort
// all["dontTruncate"] = dontTruncate
// all["wantMore"] = wantMore
// all["wantOOBFlag"] = wantOOBFlag
all["sendBufferSize"] = sendBufferSize
all["receiveBufferSize"] = receiveBufferSize
all["sendLowWaterMark"] = sendLowWaterMark
all["receiveLowWaterMark"] = receiveLowWaterMark
all["sendTimeout"] = sendTimeout
all["receiveTimeout"] = receiveTimeout
all["error"] = error
all["type"] = type
all["nwrite"] = nwrite
// all["reuseShareUID"] = reuseShareUID
all["notifyConflict"] = notifyConflict
all["upcallCloseWait"] = upcallCloseWait
all["lingerSeconds"] = lingerSeconds
all["randomPort"] = randomPort
// all["numberOfReceiveDatagrams"] = numberOfReceiveDatagrams
return all
}
}
// MARK: -
public extension SocketOptions {
/// don't delay send to coalesce packets
var noDelay: Bool {
get {
return try! socket.getsockopt(IPPROTO_TCP, TCP_NODELAY)
}
set {
try! socket.setsockopt(IPPROTO_TCP, TCP_NODELAY, newValue)
}
}
/// set maximum segment size
var maxSegmentSize: Int32 {
get {
return try! socket.getsockopt(IPPROTO_TCP, TCP_MAXSEG)
}
set {
try! socket.setsockopt(IPPROTO_TCP, TCP_MAXSEG, newValue)
}
}
/// don't push last block of write
var noPush: Bool {
get {
return try! socket.getsockopt(IPPROTO_TCP, TCP_NOPUSH)
}
set {
try! socket.setsockopt(IPPROTO_TCP, TCP_NOPUSH, newValue)
}
}
/// don't use TCP options
var noOptions: Bool {
get {
return try! socket.getsockopt(IPPROTO_TCP, TCP_NOOPT)
}
set {
try! socket.setsockopt(IPPROTO_TCP, TCP_NOOPT, newValue)
}
}
/// idle time used when SO_KEEPALIVE is enabled
var keepAliveIdleTime: Int32 {
get {
return try! socket.getsockopt(IPPROTO_TCP, TCP_KEEPALIVE)
}
set {
try! socket.setsockopt(IPPROTO_TCP, TCP_KEEPALIVE, newValue)
}
}
/// connection timeout
var connectionTimeout: Int32 {
get {
return try! socket.getsockopt(IPPROTO_TCP, TCP_CONNECTIONTIMEOUT)
}
set {
try! socket.setsockopt(IPPROTO_TCP, TCP_CONNECTIONTIMEOUT, newValue)
}
}
/// time after which tcp retransmissions will be stopped and the connection will be dropped
var retransmissionConnectionDropTime: Int32 {
get {
return try! socket.getsockopt(IPPROTO_TCP, TCP_RXT_CONNDROPTIME)
}
set {
try! socket.setsockopt(IPPROTO_TCP, TCP_RXT_CONNDROPTIME, newValue)
}
}
/// when this option is set, drop a connection after retransmitting the FIN 3 times. It will prevent holding too many mbufs in socket buffer queues.
var retransmissionFINDrop: Bool {
get {
return try! socket.getsockopt(IPPROTO_TCP, TCP_RXT_FINDROP)
}
set {
try! socket.setsockopt(IPPROTO_TCP, TCP_RXT_FINDROP, newValue)
}
}
/// interval between keepalives
var keepAliveInterval: Int32 {
get {
return try! socket.getsockopt(IPPROTO_TCP, TCP_KEEPINTVL)
}
set {
try! socket.setsockopt(IPPROTO_TCP, TCP_KEEPINTVL, newValue)
}
}
/// number of keepalives before close
var keepAliveCount: Int32 {
get {
return try! socket.getsockopt(IPPROTO_TCP, TCP_KEEPCNT)
}
set {
try! socket.setsockopt(IPPROTO_TCP, TCP_KEEPCNT, newValue)
}
}
/// always ack every other packet
var sendMoreACKS: Bool {
get {
return try! socket.getsockopt(IPPROTO_TCP, TCP_SENDMOREACKS)
}
set {
try! socket.setsockopt(IPPROTO_TCP, TCP_SENDMOREACKS, newValue)
}
}
/// Enable ECN on a connection
var enableECN: Bool {
get {
return try! socket.getsockopt(IPPROTO_TCP, TCP_ENABLE_ECN)
}
set {
try! socket.setsockopt(IPPROTO_TCP, TCP_ENABLE_ECN, newValue)
}
}
/// Enable/Disable TCP Fastopen on this socket
var fastOpen: Bool {
get {
return try! socket.getsockopt(IPPROTO_TCP, TCP_FASTOPEN)
}
set {
try! socket.setsockopt(IPPROTO_TCP, TCP_FASTOPEN, newValue)
}
}
/// State of TCP connection
var connectionInfo: tcp_connection_info {
get {
return try! socket.getsockopt(IPPROTO_TCP, TCP_CONNECTION_INFO)
}
}
/// Low water mark for TCP unsent data
var notSentLowWaterMark: Int32 {
get {
return try! socket.getsockopt(IPPROTO_TCP, TCP_NOTSENT_LOWAT)
}
set {
try! socket.setsockopt(IPPROTO_TCP, TCP_NOTSENT_LOWAT, newValue)
}
}
}
// MARK: -
public extension SocketOptions {
var tcpAll: [String: Any] {
var all: [String: Any] = [:]
all["noDelay"] = noDelay
all["maxSegmentSize"] = maxSegmentSize
all["noPush"] = noPush
all["noOptions"] = noOptions
all["keepAliveIdleTime"] = keepAliveIdleTime
all["connectionTimeout"] = connectionTimeout
all["retransmissionConnectionDropTime"] = retransmissionConnectionDropTime
all["retransmissionFINDrop"] = retransmissionFINDrop
all["keepAliveInterval"] = keepAliveInterval
all["keepAliveCount"] = keepAliveCount
all["sendMoreACKS"] = sendMoreACKS
all["enableECN"] = enableECN
// all["fastOpen"] = fastOpen
all["connectionInfo"] = connectionInfo
all["notSentLowWaterMark"] = notSentLowWaterMark
return all
}
}
| mit | 8105335103945bb38e8e038ea39def40 | 27.097731 | 152 | 0.577578 | 3.910615 | false | false | false | false |
wj2061/ios7ptl-swift3.0 | ch21-Text/Columns/Columns/ColumnView.swift | 1 | 4152 | //
// ColumnView.swift
// Columns
//
// Created by wj on 15/11/28.
// Copyright © 2015年 wj. All rights reserved.
//
import UIKit
let kColumnCount = 3
class ColumnView: UIView {
var mode = 0
var attributedString:NSAttributedString?
fileprivate func copyColumnRects()->[CGRect]{
let bounds = self.bounds.insetBy(dx: 20, dy: 20)
var columnRects = Array.init(repeating: CGRect.zero, count: 3)
let columnWidth = bounds.width / CGFloat( kColumnCount)
for i in 0..<kColumnCount{
columnRects[i] = CGRect(x: CGFloat(i)*columnWidth + bounds.minX, y: bounds.minY, width: columnWidth, height: bounds.height)
columnRects[i] = columnRects[i].insetBy(dx: 10, dy: 10)
}
return columnRects
}
func copyPaths()->[CGPath]{
var paths = [CGPath]()
let columnRects = copyColumnRects()
switch mode{
case 0:
for i in 0..<kColumnCount{
let path = CGPath(rect: columnRects[i], transform: nil)
paths.append(path)
}
case 1:
let path = CGMutablePath()
for i in 0..<kColumnCount{
path.addRect(columnRects[i]);
}
paths.append(path)
case 2:
var path = CGMutablePath()
path.move(to: CGPoint(x:30, y:0));
path.addLine(to: CGPoint(x: 344, y: 30));// Bottom right
path.addLine(to: CGPoint(x: 344, y: 400));
path.addLine(to: CGPoint(x: 200, y: 400));
path.addLine(to: CGPoint(x: 200, y: 800));
path.addLine(to: CGPoint(x: 344, y: 800));
path.addLine(to: CGPoint(x: 344, y: 944));// Top right
path.addLine(to: CGPoint(x: 30, y: 944));// Top left
path.closeSubpath()
paths.append(path)
path = CGMutablePath()
path.move(to: CGPoint(x:700, y:30));
path.addLine(to: CGPoint(x: 360, y: 30));
path.addLine(to: CGPoint(x: 360, y: 400));
path.addLine(to: CGPoint(x: 500, y: 400));
path.addLine(to: CGPoint(x: 500, y: 800));
path.addLine(to: CGPoint(x: 360, y: 800));
path.addLine(to: CGPoint(x: 360, y: 944));// Top left
path.addLine(to: CGPoint(x: 700, y: 944));// Top right
path.closeSubpath()
paths.append(path)
case 3:
let path = CGPath(ellipseIn: bounds.insetBy(dx: 30, dy: 30), transform: nil)
paths.append(path)
default:
break
}
print(paths.count)
return paths
}
override init(frame: CGRect) {
super.init(frame: frame)
let transform = CGAffineTransform(scaleX: 1, y: -1)
transform.translatedBy(x: 0, y: -self.bounds.size.height)
self.transform = transform
backgroundColor = UIColor.white
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func draw(_ rect: CGRect) {
if attributedString == nil {return}
let context = UIGraphicsGetCurrentContext()
context!.textMatrix = CGAffineTransform.identity
let framesetter = CTFramesetterCreateWithAttributedString(attributedString!)
let paths = copyPaths()
var charIndex = 0
for i in 0..<paths.count{
let path = paths[i]
let frame = CTFramesetterCreateFrame(framesetter, CFRangeMake(charIndex, 0), path, nil)
CTFrameDraw(frame, context!)
let frameRange = CTFrameGetVisibleStringRange(frame)
charIndex += frameRange.length
}
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
mode = (mode + 1)%4
setNeedsDisplay()
}
}
| mit | 267a28934bade1bfe5df64102ffd945d | 32.459677 | 135 | 0.550735 | 4.272915 | false | false | false | false |
JunDang/SwiftFoundation | Sources/SwiftFoundation/RegularExpressionCompileError.swift | 1 | 4849 | //
// RegularExpressionCompileError.swift
// SwiftFoundation
//
// Created by Alsey Coleman Miller on 8/9/15.
// Copyright © 2015 PureSwift. All rights reserved.
//
#if os(OSX) || os(iOS) || os(watchOS) || os(tvOS)
import Darwin.C
#elseif os(Linux)
import Glibc
#endif
public extension RegularExpression {
// POSIX Regular Expression compilation error
public enum CompileError: RawRepresentable, ErrorType {
/// Invalid use of repetition operators such as using '*' as the first character.
///
/// For example, the consecutive repetition operators ```**``` in ```a**``` are invalid. As another example, if the syntax is extended regular expression syntax, then the repetition operator ```*``` with nothing on which to operate in ```*``` is invalid.
case InvalidRepetition
/// Invalid use of back reference operator.
///
/// For example, the count '```-1```' in '```a\{-1```' is invalid.
case InvalidBackReference
/// The regex routines ran out of memory.
case OutOfMemory
/// Invalid use of pattern operators such as group or list.
case InvalidPatternOperator
/// Un-matched brace interval operators.
case UnMatchedBraceInterval
/// Un-matched bracket list operators.
case UnMatchedBracketList
/// Invalid collating element.
case InvalidCollating
/// Unknown character class name.
case UnknownCharacterClassName
/// Trailing backslash.
case TrailingBackslash
/// Un-matched parenthesis group operators.
case UnMatchedParenthesis
/// Invalid use of the range operator.
///
/// E.g. The ending point of the range occurs prior to the starting point.
case InvalidRange
/// Invalid back reference to a subexpression.
case InvalidBackReferenceToSubExpression
/* Linux
/// Non specific error. This is not defined by POSIX.2.
case GenericError
/// Compiled regular expression requires a pattern buffer larger than 64Kb. This is not defined by POSIX.2.
case GreaterThan64KB
*/
public init?(rawValue: POSIXRegularExpression.ErrorCode) {
switch rawValue {
case REG_BADRPT: self = InvalidRepetition
case REG_BADBR: self = InvalidBackReference
case REG_ESPACE: self = OutOfMemory
case REG_BADPAT: self = InvalidPatternOperator
case REG_EBRACE: self = UnMatchedBraceInterval
case REG_EBRACK: self = UnMatchedBracketList
case REG_ECOLLATE: self = InvalidCollating
case REG_ECTYPE: self = UnknownCharacterClassName
case REG_EESCAPE: self = TrailingBackslash
case REG_EPAREN: self = UnMatchedParenthesis
case REG_ERANGE: self = InvalidRange
case REG_ESUBREG: self = InvalidBackReferenceToSubExpression
/*
#if os(linux)
case REG_EEND: self = .GenericError // Linux
case REG_ESIZE: self = .GreaterThan64KB // Linux
#endif
*/
default: return nil
}
}
public var rawValue: POSIXRegularExpression.ErrorCode {
switch self {
case InvalidRepetition: return REG_BADRPT
case InvalidBackReference: return REG_BADBR
case OutOfMemory: return REG_ESPACE
case InvalidPatternOperator: return REG_BADPAT
case UnMatchedBraceInterval: return REG_EBRACE
case UnMatchedBracketList: return REG_EBRACK
case InvalidCollating: return REG_ECOLLATE
case UnknownCharacterClassName: return REG_ECTYPE
case TrailingBackslash: return REG_EESCAPE
case UnMatchedParenthesis: return REG_EPAREN
case InvalidRange: return REG_ERANGE
case InvalidBackReferenceToSubExpression: return REG_ESUBREG
}
}
}
}
| mit | 3b89537f27ea7ce676e803a6cbe81fc3 | 39.4 | 262 | 0.525165 | 5.75772 | false | false | false | false |
sisomollov/ReSwiftDataSource | Example/ReSwiftDataSource/Table/TableState.swift | 1 | 441 |
import Foundation
import ReSwiftDataSource
struct TableState: DataSourceState {
var operation: DataSourceStateOperation = DataSourceStateOperation()
var data: [ItemSection] = [
TableSection(title: "Section One", headerItem: TableHeaderItem(title: "Section One"))
]
}
extension TableState: Equatable {
static func ==(lhs: TableState, rhs: TableState) -> Bool {
return lhs.operation == rhs.operation
}
}
| mit | 74f0e8fe5e9576f6eb00058e6297c3e4 | 26.5625 | 93 | 0.709751 | 4.366337 | false | false | false | false |
Isuru-Nanayakkara/Swift-Extensions | Swift+Extensions/Swift+Extensions/Foundation/Codable+Extensions.swift | 1 | 3902 | //
// Codable+Extensions.swift
// Swift+Extensions
//
// Created by Isuru Nanayakkara on 7/26/19.
// Copyright © 2019 BitInvent. All rights reserved.
//
import Foundation
// https://stackoverflow.com/a/46049763/1077789
struct JSONCodingKeys: CodingKey {
var stringValue: String
init?(stringValue: String) {
self.stringValue = stringValue
}
var intValue: Int?
init?(intValue: Int) {
self.init(stringValue: "\(intValue)")
self.intValue = intValue
}
}
extension KeyedDecodingContainer {
func decode(_ type: Dictionary<String, Any>.Type, forKey key: K) throws -> Dictionary<String, Any> {
let container = try self.nestedContainer(keyedBy: JSONCodingKeys.self, forKey: key)
return try container.decode(type)
}
func decodeIfPresent(_ type: Dictionary<String, Any>.Type, forKey key: K) throws -> Dictionary<String, Any>? {
guard contains(key) else {
return nil
}
guard try decodeNil(forKey: key) == false else {
return nil
}
return try decode(type, forKey: key)
}
func decode(_ type: Array<Any>.Type, forKey key: K) throws -> Array<Any> {
var container = try self.nestedUnkeyedContainer(forKey: key)
return try container.decode(type)
}
func decodeIfPresent(_ type: Array<Any>.Type, forKey key: K) throws -> Array<Any>? {
guard contains(key) else {
return nil
}
guard try decodeNil(forKey: key) == false else {
return nil
}
return try decode(type, forKey: key)
}
func decode(_ type: Dictionary<String, Any>.Type) throws -> Dictionary<String, Any> {
var dictionary = Dictionary<String, Any>()
for key in allKeys {
if let boolValue = try? decode(Bool.self, forKey: key) {
dictionary[key.stringValue] = boolValue
} else if let stringValue = try? decode(String.self, forKey: key) {
dictionary[key.stringValue] = stringValue
} else if let intValue = try? decode(Int.self, forKey: key) {
dictionary[key.stringValue] = intValue
} else if let doubleValue = try? decode(Double.self, forKey: key) {
dictionary[key.stringValue] = doubleValue
} else if let nestedDictionary = try? decode(Dictionary<String, Any>.self, forKey: key) {
dictionary[key.stringValue] = nestedDictionary
} else if let nestedArray = try? decode(Array<Any>.self, forKey: key) {
dictionary[key.stringValue] = nestedArray
}
}
return dictionary
}
}
extension UnkeyedDecodingContainer {
mutating func decode(_ type: Array<Any>.Type) throws -> Array<Any> {
var array: [Any] = []
while isAtEnd == false {
// See if the current value in the JSON array is `null` first and prevent infite recursion with nested arrays.
if try decodeNil() {
continue
} else if let value = try? decode(Bool.self) {
array.append(value)
} else if let value = try? decode(Double.self) {
array.append(value)
} else if let value = try? decode(String.self) {
array.append(value)
} else if let nestedDictionary = try? decode(Dictionary<String, Any>.self) {
array.append(nestedDictionary)
} else if let nestedArray = try? decode(Array<Any>.self) {
array.append(nestedArray)
}
}
return array
}
mutating func decode(_ type: Dictionary<String, Any>.Type) throws -> Dictionary<String, Any> {
let nestedContainer = try self.nestedContainer(keyedBy: JSONCodingKeys.self)
return try nestedContainer.decode(type)
}
}
| mit | e5e34c22887ef3f4a76931822224e711 | 35.457944 | 122 | 0.594719 | 4.453196 | false | false | false | false |
drougojrom/InstaActivity | InstaActivity/InstaActivity/Shared/InstaActivity.swift | 1 | 6198 | //
// InstaActivity.swift
// InstaActivity
//
// Created by Roman Ustiantcev on 06/04/2017.
// Copyright © 2017 Roman Ustiantcev. All rights reserved.
//
import UIKit
import QuartzCore
protocol InstaActivityProtocol {
// segment's animation duration
var animationDuration: Double {get set}
// indicator animation duration
var rotationDuration: Double {get set}
// the number of segments in indicator
var segmentsNumber: Int {get set}
// stroke color of indicator segments
var strokeColor: UIColor? {get set}
// line width of indicator segments
var lineWidth: CGFloat {get set}
// is hidden when animation stoppes
var hideWhenStopped: Bool {get set}
// is indicator animating or not
var isAnimating: Bool {get set}
// the layer that replicates segments
var replicationLayer: CAReplicatorLayer! {get set}
// visual layer that replicates around the indicator
var segmentLayer: CAShapeLayer! {get set}
func startAnimation()
func stopAnimation()
}
@IBDesignable
class InstaActivity: UIView, InstaActivityProtocol {
@IBInspectable public var animationDuration: Double = 1
@IBInspectable public var rotationDuration: Double = 10
@IBInspectable public var segmentsNumber: Int = 11 {
didSet {
updateSegments()
}
}
@IBInspectable public var strokeColor: UIColor? = .green {
didSet {
segmentLayer.strokeColor = strokeColor?.cgColor
}
}
@IBInspectable public var lineWidth: CGFloat = 8 {
didSet {
segmentLayer.lineWidth = lineWidth
updateSegments()
}
}
@IBInspectable public var hideWhenStopped: Bool = true
@IBInspectable public var isAnimating: Bool = true
var replicationLayer: CAReplicatorLayer!
var segmentLayer: CAShapeLayer!
override init(frame: CGRect) {
super.init(frame: frame)
setupView()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupView()
}
func setupView() {
// create and add the replicator layer
let replicatorLayer = CAReplicatorLayer()
self.layer.addSublayer(replicatorLayer)
// configure the shape layer that gets replicated
let dot = CAShapeLayer()
dot.lineCap = kCALineCapRound
dot.strokeColor = self.strokeColor?.cgColor
dot.lineWidth = self.lineWidth
dot.fillColor = nil
replicatorLayer.addSublayer(dot)
self.replicationLayer = replicatorLayer
self.segmentLayer = dot
}
override func layoutSubviews() {
super.layoutSubviews()
let maxSize = max(0,min(bounds.width, bounds.height))
replicationLayer?.bounds = CGRect(x: 0, y: 0, width: maxSize, height: maxSize)
replicationLayer?.position = CGPoint(x: bounds.width / 2, y: bounds.height / 2)
updateSegments()
}
func updateSegments() {
if segmentsNumber > 0 {
let angle = 2 * CGFloat.pi / CGFloat(segmentsNumber)
replicationLayer?.instanceCount = segmentsNumber
replicationLayer?.instanceTransform = CATransform3DMakeRotation(angle, 0.0, 0.0, 1.0)
replicationLayer?.instanceDelay = 1.5 * animationDuration / Double(segmentsNumber)
let maxRadius = max(0,min(replicationLayer.bounds.width, replicationLayer.bounds.height))/2
let radius: CGFloat = maxRadius - lineWidth/2
segmentLayer?.bounds = CGRect(x: 0, y: 0, width: 2 * maxRadius, height: 2 * maxRadius)
segmentLayer?.position = CGPoint(x: replicationLayer.bounds.width/2, y: replicationLayer.bounds.height / 2)
let path = UIBezierPath(arcCenter: CGPoint(x: maxRadius, y: maxRadius), radius: radius, startAngle: -angle/2 - CGFloat.pi/2, endAngle: angle/2 - CGFloat.pi/2, clockwise: true)
segmentLayer.path = path.cgPath
}
}
func startAnimation() {
self.isHidden = false
isAnimating = true
let rotate = CABasicAnimation(keyPath: "transform.rotation")
rotate.byValue = CGFloat.pi * 2
rotate.duration = rotationDuration
rotate.repeatCount = Float.infinity
// add animations to segment
// multiplying duration changes the time of empty or hidden segments
let shrinkStart = CABasicAnimation(keyPath:"strokeStart")
shrinkStart.fromValue = 0.0
shrinkStart.toValue = 0.5
shrinkStart.duration = animationDuration // * 1.5
shrinkStart.autoreverses = true
shrinkStart.repeatCount = Float.infinity
shrinkStart.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
let shrinkEnd = CABasicAnimation(keyPath:"strokeEnd")
shrinkEnd.fromValue = 1.0
shrinkEnd.toValue = 0.5
shrinkEnd.duration = animationDuration // * 1.5
shrinkEnd.autoreverses = true
shrinkEnd.repeatCount = Float.infinity
shrinkEnd.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
let fade = CABasicAnimation(keyPath:"lineWidth")
fade.fromValue = lineWidth
fade.toValue = 0.0
fade.duration = animationDuration // * 1.5
fade.autoreverses = true;
fade.repeatCount = Float.infinity;
fade.timingFunction = CAMediaTimingFunction(controlPoints: 0.55, 0.0, 0.45, 10)
replicationLayer?.add(rotate, forKey: "rotate")
segmentLayer?.add(shrinkStart, forKey: "start")
segmentLayer?.add(shrinkEnd, forKey: "end")
segmentLayer?.add(fade, forKey: "fade")
}
func stopAnimation() {
isAnimating = false
replicationLayer?.removeAllAnimations()
segmentLayer.removeAllAnimations()
if hideWhenStopped {
isHidden = true
}
}
public override var intrinsicContentSize: CGSize {
return CGSize(width: 180, height: 180)
}
}
| mit | 6c7ce44b76f120675068ca9918310d00 | 33.049451 | 187 | 0.640148 | 4.969527 | false | false | false | false |
sunflash/SwiftHTTPClient | HTTPClient/Classes/HTTP/Client/HTTPObjects.swift | 1 | 10723 | //
// Http.swift
// HTTPClient
//
// Created by Min Wu on 06/02/2017.
// Copyright © 2017 Min WU. All rights reserved.
//
import Foundation
//-----------------------------------------------------------------------------------------------------------------
// MARK: - Network HTTP Struct, Enum
/// Http request method enum
public enum HTTPMethod: String {
/// The GET method requests a representation of the specified resource.
case get = "GET"
/// The POST method requests that the server accept the entity enclosed in the request as a new subordinate of the web resource identified by the URI.
case post = "POST"
/// The PUT method requests that the enclosed entity be stored under the supplied URI.
case put = "PUT"
/// The DELETE method deletes the specified resource.
case delete = "DELETE"
/// The OPTIONS method returns the HTTP methods that the server supports for the specified URL.
case options = "OPTIONS"
/// The HEAD method asks for a response identical to that of a GET request, but without the response body.
case head = "HEAD"
/// The PATCH method applies partial modifications to a resource.
case patch = "PATCH"
/// The TRACE method echoes the received request so that a client can see what (if any) changes or additions have been made by intermediate servers.
case trace = "TRACE"
/// The CONNECT method converts the request connection to a transparent TCP/IP tunne.
case connect = "CONNECT"
}
/// Http content type enum
public enum HTTPContentType {
/// Url encode content type
case URLENCODED
/// Json content type
case JSON
/// XML content type
case XML
/// HTML content type
case HTML
/// Text content type
case TEXT
/// Unknown content type
case unknown
// MARK: - Init and enum string value
/// Init http content type enum
///
/// - Parameter mimeType: content mime type
public init(mimeType: String?) {
guard let type = mimeType?.lowercased() else {
self = .unknown
return
}
let isContainType: ([String]) -> Bool = {$0.filter {type.contains($0)}.isEmpty == false}
if isContainType(["application/x-www-form-urlencoded"]) {
self = .URLENCODED
} else if isContainType(["application/json"]) {
self = .JSON
} else if isContainType(["text/xml", "application/xml"]) {
self = .XML
} else if isContainType(["text/html"]) {
self = .HTML
} else if isContainType(["text/plain"]) {
self = .TEXT
} else {
self = .unknown
}
}
/// Get http content type string value
public var stringValue: String {
switch self {
case .URLENCODED:
return "application/x-www-form-urlencoded"
case .JSON:
return "application/json"
case .XML:
return "text/xml"
case .HTML:
return "text/html"
case .TEXT:
return "text/plain"
default:
return "unknown"
}
}
}
//-----------------------------------------------------------------------------------------------------------------
// MARK: - HTTPRequest
/// Http request parameters and configuration
public struct HTTPRequest {
/// Relative URL path for equest
public let path: String
/// Http method for request
public let method: HTTPMethod
/// Http content type for request, optional
public var contentType: HTTPContentType?
/// Http header for request, optional
public var headers: [String: String]?
/// Http body for request, optional
public var body: Data?
/// Expected response http content type to request, use for content validation, optional.
public var expectedResponseContentType: HTTPContentType?
/// Use internally to keeping track of how many retries was peformed, property is readonly.
var retriesCount = 0
/// Init method for http request
///
/// - Parameters:
/// - path: Relative url path for content
/// - method: Http method for request, default to "GET"
public init(path: String = "", method: HTTPMethod = .get) {
self.path = path
self.method = method
}
/// Generate path with query items
///
/// - Parameters:
/// - path: relative path
/// - queryItems: query items
/// - Returns: path with query items
public static func pathWithQuery(path: String, queryItems: [URLQueryItem]) -> String? {
var urlComponent = URLComponents(string: path)
urlComponent?.queryItems = queryItems
guard let url = urlComponent?.url(relativeTo: nil) else {return nil}
return url.absoluteString
}
}
/// Json reponse extension to HTTPResponse
private typealias BasicAuthenticationRequest = HTTPRequest
extension BasicAuthenticationRequest {
/// Generate basic authentication header from user name and password
///
/// - Parameters:
/// - userName: User name for authentication
/// - password: Password for authentication
/// - Returns: Basic authentication header, nil if user name or password is empty.
public static func basicAuthenticationHeader(userName: String, password: String) -> [String: String]? {
let userNameNoSpace = userName.trimmingCharacters(in: .whitespaces)
let passwordNoSpace = password.trimmingCharacters(in: .whitespaces)
if userNameNoSpace.isEmpty || passwordNoSpace.isEmpty {return nil}
let authString = "\(userNameNoSpace):\(passwordNoSpace)"
let authStringEncoded = authString.data(using: .utf8)?.base64EncodedString()
guard let base64String = authStringEncoded else {return nil}
return ["Authorization": "Basic \(base64String)"]
}
/// Add basic authentication header to http request.
///
/// - Note: Please use URLSessionConfiguration.HTTPAdditionalHeaders for session base basic authentication.
/// - SeeAlso: [HTTPClient.configuration](../Classes/HTTPClient.html)
///
/// - Parameters:
/// - userName: User name for authentication
/// - password: Password for authentication
/// - Returns: Whether add basic authentication to request is successed.
mutating public func addBasicAuthentication(userName: String, password: String) -> Bool {
guard let basicAuthHeader = HTTPRequest.basicAuthenticationHeader(userName: userName, password: password) else {
return false
}
if self.headers == nil {
self.headers = basicAuthHeader
} else {
let headerFieldName = "Authorization"
self.headers?[headerFieldName] = basicAuthHeader[headerFieldName]
}
return true
}
}
//-----------------------------------------------------------------------------------------------------------------
// MARK: - HTTPResponse
/// Http response data
public struct HTTPResponse {
/// URL for response
public let url: URL?
/// Stauts code for response
public let statusCode: HTTPStatusCode
/// Content type for response
public var contentType: HTTPContentType?
/// Headers for response
public let headers: [String: String]
/// Body for response
public var body: Data?
/// Error for response
public var error: Error?
/// Convient init method for http response
///
/// - Parameters:
/// - url: URL for response
/// - statusCode: Stauts code for response
/// - headers: Headers for response
public init(url: URL?, statusCode: HTTPStatusCode, headers: [String: String]) {
self.url = url
self.statusCode = statusCode
self.headers = headers
}
/// Cache deserialized json object for fast lookup.
/// Avoid unnecessary costly json deserialize operation, if json is already deserialize once before.
fileprivate var deserializedJsonObject: Any?
}
/// Json reponse extension to HTTPResponse
private typealias JsonResponse = HTTPResponse
extension JsonResponse {
/// Convenience property for deserialize json from response body
public mutating func json() -> Any? {
if self.deserializedJsonObject != nil {
return self.deserializedJsonObject
}
guard let type = self.contentType, let data = self.body, type == .JSON else {return nil}
do {
let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers)
deserializedJsonObject = json
return json
} catch {
logCoder(.JSONDecode, "\(error)")
return nil
}
}
/// Convenience methode for async deserialize json from response body.
/// Deserialization is occur in background thread without blocking main thread,
/// suite for process big json payload.
///
/// - Parameter object: Dedeserialize object as array or dictionary
public func jsonDeserializeAsync(_ object: @escaping (Any?) -> Void) {
if self.deserializedJsonObject != nil {
return object(self.deserializedJsonObject)
}
guard let type = self.contentType, let data = self.body, type == .JSON else {
object(nil)
return
}
GCD.userInteractive.queue.async {
do {
let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers)
GCD.main.queue.async {
object(json)
}
} catch {
logCoder(.JSONDecode, "\(error)")
}
}
}
/// Get json value with key path, perform asynchronous value look up
///
/// - Parameters:
/// - keyPath: key path to json value, example "coutry,city,address"
/// - completion: value in json key path location, nil if not found
public func jsonValue(keyPath: String, completion: @escaping (Any?) -> Void) {
let getValue: (Any?, @escaping (Any?) -> Void ) -> Void = { object, completion in
GCD.userInitiated.queue.async {
let keys = keyPath.trimmingCharacters(in: .whitespaces).split(separator: ",")
var value = object
if value != nil && keys.isEmpty == false {
keys.forEach {value = (value as? [String: Any])?[String($0)]}
}
GCD.main.queue.async {
completion(value)
}
}
}
jsonDeserializeAsync { object in
getValue(object) { value in
completion(value)
}
}
}
}
| mit | 118f0b0d96b4307f9dd16d41d17a0f13 | 33.038095 | 154 | 0.603339 | 4.973098 | false | false | false | false |
Codezerker/RyCooder | Sources/View.swift | 1 | 1933 | import Foundation
import AVFoundation
internal protocol Displayable {
func display()
}
internal struct AudioFileLoadingView: Displayable {
private let audioFiles: [URL]
internal init(audioFiles: [URL]) {
self.audioFiles = audioFiles
}
internal func display() {
print("\(String.arrow) 🎵 files added to playlist:")
for (index, audioFile) in audioFiles.enumerated() {
let filename = audioFile.lastPathComponent
let indexString = "#\(index + 1)".underlined
print("\(indexString) - \(filename)")
}
print("")
}
}
internal struct StartingView: Displayable {
internal func display() {
print("\(String.arrow) Type \("start".highlighted) to start playing.")
print("\(String.arrow) Type \("next".highlighted) or \("previous".highlighted) to change songs.")
print("\(String.arrow) Type \("index of a song".underlined) to jump to the song.")
print("\(String.arrow) Type \("shuffle".highlighted) to toggle shuffling.")
print("")
}
}
internal struct UnknownCommandView: Displayable {
internal func display() {
print("\(String.arrow) Unrecognized command 😦 .")
}
}
internal struct StartPlayingView: Displayable {
internal func display() {
print("\(String.arrow) 🎵 RyCooder has taken the stage...")
}
}
internal struct ItemPlayingView: Displayable {
private let item: AVPlayerItem
internal init(item: AVPlayerItem) {
self.item = item
}
internal func display() {
guard let asset = item.asset as? AVURLAsset else{
return
}
let filename = asset.url.lastPathComponent
print("\n\(String.arrow) Now playing: \(filename.tinted)")
}
}
internal struct ShuffleView: Displayable {
private let shuffle: Bool
internal init(shuffle: Bool) {
self.shuffle = shuffle
}
internal func display() {
print("\(String.arrow) 🎭 Shuffle turned \(shuffle ? "ON".turnedOn : "OFF".turnedOff).")
}
}
| mit | 3ffd93a10071044ef21f2fb2458eb89a | 22.426829 | 101 | 0.671005 | 4.185185 | false | false | false | false |
ArnavChawla/InteliChat | Carthage/Checkouts/swift-sdk/Source/ToneAnalyzerV3/Models/Utterance.swift | 1 | 1661 | /**
* Copyright IBM Corporation 2018
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
import Foundation
/** Utterance. */
public struct Utterance: Encodable {
/// An utterance contributed by a user in the conversation that is to be analyzed. The utterance can contain multiple sentences.
public var text: String
/// A string that identifies the user who contributed the utterance specified by the `text` parameter.
public var user: String?
// Map each property name to the key that shall be used for encoding/decoding.
private enum CodingKeys: String, CodingKey {
case text = "text"
case user = "user"
}
/**
Initialize a `Utterance` with member variables.
- parameter text: An utterance contributed by a user in the conversation that is to be analyzed. The utterance can contain multiple sentences.
- parameter user: A string that identifies the user who contributed the utterance specified by the `text` parameter.
- returns: An initialized `Utterance`.
*/
public init(text: String, user: String? = nil) {
self.text = text
self.user = user
}
}
| mit | ac0bf4531f06cf8cddd7079c78cdce03 | 34.340426 | 147 | 0.708007 | 4.525886 | false | false | false | false |
patrick-ogrady/godseye-ios | sample/SampleBroadcaster-Swift/SampleBroadcaster-Swift/Event.swift | 1 | 778 |
import UIKit
import MapKit
import CoreLocation
class Event: NSObject, MKAnnotation {
let title: String?
let locationName: String
let coordinate: CLLocationCoordinate2D
let eventObject:PFObject
// var locationManager: LocationManager!
// let geoCoder = CLGeocoder()
// let tempPlace: CLPlacemark
//
init(title: String, coordinate:CLLocationCoordinate2D, locationName: String, pfEventObject: PFObject) {
// locationManager = LocationManager.sharedInstance
self.title = title
self.locationName = locationName
self.coordinate = coordinate
self.eventObject = pfEventObject
super.init()
}
var subtitle: String? {
return locationName
}
}
| mit | 21033efec74bfbf653a1cf6dfb93e816 | 24.096774 | 107 | 0.652956 | 5.256757 | false | false | false | false |
zcfsmile/Swifter | BasicSyntax/016方法/016Methods.playground/Contents.swift | 1 | 3010 | //: Playground - noun: a place where people can play
import UIKit
//: 实例方法
//: 属于某个特定类、结构体、枚举类型实例的方法
class Counter {
var count = 0
func increment() {
count += 1
}
func increment(by amount: Int) {
count += amount
}
func reset() {
count = 0
}
}
let counter = Counter()
counter.increment()
counter.increment(by: 6)
counter.reset()
//: self 属性
//: 类型的每一个实例都有一个隐含属性叫做self,self完全等同于该实例本身。
//: mutating 修饰 可变方法
//: 结构体和枚举是值类型,默认情况下,值类型的属性不能在它的实例方法中被修改。
//: 确实需要在某个特定的方法中修改结构体或者枚举的属性,你可以为这个方法选择可变(mutating)行为,然后就可以从其方法内部改变它的属性;并且这个方法做的任何改变都会在方法执行结束时写回到原始结构中。
struct Point {
var x = 0.0, y = 0.0
mutating func movedByX(deltax: Double, y deltaY: Double) {
x += deltax
y += deltaY
}
}
var somePoint = Point(x: 1.0, y: 1.0)
somePoint.movedByX(deltax: 2.0, y: 3.0)
print("\(somePoint.x), \(somePoint.y)")
//: 可变方法给 Self 赋值
extension Point {
mutating func newPoint(x: Double, y: Double) {
self = Point(x: x, y: y)
}
}
//: 枚举的可变方法可以把self设置为同一枚举类型中不同的成员:
enum TriSteteSwitch {
case Off, Low, High
mutating func next() {
switch self {
case .Off:
self = .Low
case .Low:
self = .High
case .High:
self = .Off
}
}
}
var ovenLight = TriSteteSwitch.Low
ovenLight.next()
ovenLight.next()
//: 类型方法
//: 定义在类型本身上调用的方法,这种方法就叫做类型方法。在方法的func关键字之前加上关键字static,来指定类型方法。类还可以用关键字class来允许子类重写父类的方法实现。
struct LevelTracker {
static var highestUnlockedLevel = 1
var currentLevel = 1
static func unlock(_ level: Int) {
if level > highestUnlockedLevel {
highestUnlockedLevel = level
}
}
static func isUnlocked(_ level: Int) -> Bool {
return level <= highestUnlockedLevel
}
@discardableResult
mutating func advance(to level: Int) -> Bool {
if LevelTracker.isUnlocked(level) {
currentLevel = level
return true
} else {
return false
}
}
}
class Player {
var tracker = LevelTracker()
let playerName: String
func complete(level: Int) {
LevelTracker.unlock(level + 1)
tracker.advance(to: level + 1)
}
init(name: String) {
playerName = name
}
}
var player = Player(name: "Argyrios")
player .complete(level: 1)
print(LevelTracker.highestUnlockedLevel)
| mit | a35cde184da9dbe8ced12482e6486f0b | 17.84375 | 104 | 0.606551 | 3.382889 | false | false | false | false |
pmhicks/Spindle-Player | Spindle Player/AppDelegate.swift | 1 | 2009 | // Spindle Player
// Copyright (C) 2015 Mike Hicks
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Cocoa
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
var aboutWindowController:NSWindowController?
func applicationDidFinishLaunching(aNotification: NSNotification) {
// Insert code here to initialize your application
}
func applicationWillTerminate(aNotification: NSNotification) {
let defaults = NSUserDefaults.standardUserDefaults()
defaults.synchronize()
let cfg = SpindleConfig.sharedInstance
cfg.playList.save()
}
@IBAction func aboutAction(sender: NSMenuItem) {
if let storyboard = NSStoryboard(name: "About", bundle: nil) {
if let controller = storyboard.instantiateInitialController() as? NSWindowController {
aboutWindowController = controller
controller.showWindow(nil)
}
}
}
}
| mit | 9725fb1c5375be95016ca0a09a974c1f | 38.392157 | 98 | 0.724739 | 5.125 | false | false | false | false |
lenglengiOS/BuDeJie | 百思不得姐/Pods/Charts/Charts/Classes/Charts/ChartViewBase.swift | 15 | 35210 | //
// ChartViewBase.swift
// Charts
//
// Created by Daniel Cohen Gindi on 23/2/15.
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/ios-charts
//
// Based on https://github.com/PhilJay/MPAndroidChart/commit/c42b880
import Foundation
import UIKit
@objc
public protocol ChartViewDelegate
{
/// Called when a value has been selected inside the chart.
/// - parameter entry: The selected Entry.
/// - parameter dataSetIndex: The index in the datasets array of the data object the Entrys DataSet is in.
optional func chartValueSelected(chartView: ChartViewBase, entry: ChartDataEntry, dataSetIndex: Int, highlight: ChartHighlight)
// Called when nothing has been selected or an "un-select" has been made.
optional func chartValueNothingSelected(chartView: ChartViewBase)
// Callbacks when the chart is scaled / zoomed via pinch zoom gesture.
optional func chartScaled(chartView: ChartViewBase, scaleX: CGFloat, scaleY: CGFloat)
// Callbacks when the chart is moved / translated via drag gesture.
optional func chartTranslated(chartView: ChartViewBase, dX: CGFloat, dY: CGFloat)
}
public class ChartViewBase: UIView, ChartDataProvider, ChartAnimatorDelegate
{
// MARK: - Properties
/// the default value formatter
internal var _defaultValueFormatter: NSNumberFormatter = ChartUtils.defaultValueFormatter()
/// object that holds all data that was originally set for the chart, before it was modified or any filtering algorithms had been applied
internal var _data: ChartData!
/// Flag that indicates if highlighting per tap (touch) is enabled
private var _highlightPerTapEnabled = true
/// If set to true, chart continues to scroll after touch up
public var dragDecelerationEnabled = true
/// Deceleration friction coefficient in [0 ; 1] interval, higher values indicate that speed will decrease slowly, for example if it set to 0, it will stop immediately.
/// 1 is an invalid value, and will be converted to 0.999 automatically.
private var _dragDecelerationFrictionCoef: CGFloat = 0.9
/// Font object used for drawing the description text (by default in the bottom right corner of the chart)
public var descriptionFont: UIFont? = UIFont(name: "HelveticaNeue", size: 9.0)
/// Text color used for drawing the description text
public var descriptionTextColor: UIColor? = UIColor.blackColor()
/// Text align used for drawing the description text
public var descriptionTextAlign: NSTextAlignment = NSTextAlignment.Right
/// Custom position for the description text in pixels on the screen.
public var descriptionTextPosition: CGPoint? = nil
/// font object for drawing the information text when there are no values in the chart
public var infoFont: UIFont! = UIFont(name: "HelveticaNeue", size: 12.0)
public var infoTextColor: UIColor! = UIColor(red: 247.0/255.0, green: 189.0/255.0, blue: 51.0/255.0, alpha: 1.0) // orange
/// description text that appears in the bottom right corner of the chart
public var descriptionText = "Description"
/// flag that indicates if the chart has been fed with data yet
internal var _dataNotSet = true
/// if true, units are drawn next to the values in the chart
internal var _drawUnitInChart = false
/// the number of x-values the chart displays
internal var _deltaX = CGFloat(1.0)
internal var _chartXMin = Double(0.0)
internal var _chartXMax = Double(0.0)
/// the legend object containing all data associated with the legend
internal var _legend: ChartLegend!
/// delegate to receive chart events
public weak var delegate: ChartViewDelegate?
/// text that is displayed when the chart is empty
public var noDataText = "No chart data available."
/// text that is displayed when the chart is empty that describes why the chart is empty
public var noDataTextDescription: String?
internal var _legendRenderer: ChartLegendRenderer!
/// object responsible for rendering the data
public var renderer: ChartDataRendererBase?
internal var _highlighter: ChartHighlighter?
/// object that manages the bounds and drawing constraints of the chart
internal var _viewPortHandler: ChartViewPortHandler!
/// object responsible for animations
internal var _animator: ChartAnimator!
/// flag that indicates if offsets calculation has already been done or not
private var _offsetsCalculated = false
/// array of Highlight objects that reference the highlighted slices in the chart
internal var _indicesToHighlight = [ChartHighlight]()
/// if set to true, the marker is drawn when a value is clicked
public var drawMarkers = true
/// the view that represents the marker
public var marker: ChartMarker?
private var _interceptTouchEvents = false
/// An extra offset to be appended to the viewport's top
public var extraTopOffset: CGFloat = 0.0
/// An extra offset to be appended to the viewport's right
public var extraRightOffset: CGFloat = 0.0
/// An extra offset to be appended to the viewport's bottom
public var extraBottomOffset: CGFloat = 0.0
/// An extra offset to be appended to the viewport's left
public var extraLeftOffset: CGFloat = 0.0
public func setExtraOffsets(left left: CGFloat, top: CGFloat, right: CGFloat, bottom: CGFloat)
{
extraLeftOffset = left
extraTopOffset = top
extraRightOffset = right
extraBottomOffset = bottom
}
// MARK: - Initializers
public override init(frame: CGRect)
{
super.init(frame: frame)
self.backgroundColor = UIColor.clearColor()
initialize()
}
public required init?(coder aDecoder: NSCoder)
{
super.init(coder: aDecoder)
initialize()
}
deinit
{
self.removeObserver(self, forKeyPath: "bounds")
self.removeObserver(self, forKeyPath: "frame")
}
internal func initialize()
{
_animator = ChartAnimator()
_animator.delegate = self
_viewPortHandler = ChartViewPortHandler()
_viewPortHandler.setChartDimens(width: bounds.size.width, height: bounds.size.height)
_legend = ChartLegend()
_legendRenderer = ChartLegendRenderer(viewPortHandler: _viewPortHandler, legend: _legend)
self.addObserver(self, forKeyPath: "bounds", options: .New, context: nil)
self.addObserver(self, forKeyPath: "frame", options: .New, context: nil)
}
// MARK: - ChartViewBase
/// The data for the chart
public var data: ChartData?
{
get
{
return _data
}
set
{
if newValue == nil
{
print("Charts: data argument is nil on setData()", terminator: "\n")
return
}
_dataNotSet = false
_offsetsCalculated = false
_data = newValue
// calculate how many digits are needed
calculateFormatter(min: _data.getYMin(), max: _data.getYMax())
notifyDataSetChanged()
}
}
/// Clears the chart from all data (sets it to null) and refreshes it (by calling setNeedsDisplay()).
public func clear()
{
_data = nil
_dataNotSet = true
_indicesToHighlight.removeAll()
setNeedsDisplay()
}
/// Removes all DataSets (and thereby Entries) from the chart. Does not remove the x-values. Also refreshes the chart by calling setNeedsDisplay().
public func clearValues()
{
if (_data !== nil)
{
_data.clearValues()
}
setNeedsDisplay()
}
/// - returns: true if the chart is empty (meaning it's data object is either null or contains no entries).
public func isEmpty() -> Bool
{
if (_data == nil)
{
return true
}
else
{
if (_data.yValCount <= 0)
{
return true
}
else
{
return false
}
}
}
/// Lets the chart know its underlying data has changed and should perform all necessary recalculations.
/// It is crucial that this method is called everytime data is changed dynamically. Not calling this method can lead to crashes or unexpected behaviour.
public func notifyDataSetChanged()
{
fatalError("notifyDataSetChanged() cannot be called on ChartViewBase")
}
/// calculates the offsets of the chart to the border depending on the position of an eventual legend or depending on the length of the y-axis and x-axis labels and their position
internal func calculateOffsets()
{
fatalError("calculateOffsets() cannot be called on ChartViewBase")
}
/// calcualtes the y-min and y-max value and the y-delta and x-delta value
internal func calcMinMax()
{
fatalError("calcMinMax() cannot be called on ChartViewBase")
}
/// calculates the required number of digits for the values that might be drawn in the chart (if enabled), and creates the default value formatter
internal func calculateFormatter(min min: Double, max: Double)
{
// check if a custom formatter is set or not
var reference = Double(0.0)
if (_data == nil || _data.xValCount < 2)
{
let absMin = fabs(min)
let absMax = fabs(max)
reference = absMin > absMax ? absMin : absMax
}
else
{
reference = fabs(max - min)
}
let digits = ChartUtils.decimals(reference)
_defaultValueFormatter.maximumFractionDigits = digits
_defaultValueFormatter.minimumFractionDigits = digits
}
public override func drawRect(rect: CGRect)
{
let optionalContext = UIGraphicsGetCurrentContext()
guard let context = optionalContext else { return }
let frame = self.bounds
if (_dataNotSet || _data === nil || _data.yValCount == 0)
{ // check if there is data
CGContextSaveGState(context)
// if no data, inform the user
ChartUtils.drawText(context: context, text: noDataText, point: CGPoint(x: frame.width / 2.0, y: frame.height / 2.0), align: .Center, attributes: [NSFontAttributeName: infoFont, NSForegroundColorAttributeName: infoTextColor])
if (noDataTextDescription != nil && (noDataTextDescription!).characters.count > 0)
{
let textOffset = infoFont.lineHeight
ChartUtils.drawText(context: context, text: noDataTextDescription!, point: CGPoint(x: frame.width / 2.0, y: frame.height / 2.0 + textOffset), align: .Center, attributes: [NSFontAttributeName: infoFont, NSForegroundColorAttributeName: infoTextColor])
}
return
}
if (!_offsetsCalculated)
{
calculateOffsets()
_offsetsCalculated = true
}
}
/// draws the description text in the bottom right corner of the chart
internal func drawDescription(context context: CGContext)
{
if (descriptionText.lengthOfBytesUsingEncoding(NSUTF16StringEncoding) == 0)
{
return
}
let frame = self.bounds
var attrs = [String : AnyObject]()
var font = descriptionFont
if (font == nil)
{
#if os(tvOS)
// 23 is the smallest recommened font size on the TV
font = UIFont.systemFontOfSize(23, weight: UIFontWeightMedium)
#else
font = UIFont.systemFontOfSize(UIFont.systemFontSize())
#endif
}
attrs[NSFontAttributeName] = font
attrs[NSForegroundColorAttributeName] = descriptionTextColor
if descriptionTextPosition == nil
{
ChartUtils.drawText(
context: context,
text: descriptionText,
point: CGPoint(
x: frame.width - _viewPortHandler.offsetRight - 10.0,
y: frame.height - _viewPortHandler.offsetBottom - 10.0 - (font?.lineHeight ?? 0.0)),
align: descriptionTextAlign,
attributes: attrs)
}
else
{
ChartUtils.drawText(
context: context,
text: descriptionText,
point: descriptionTextPosition!,
align: descriptionTextAlign,
attributes: attrs)
}
}
// MARK: - Highlighting
/// - returns: the array of currently highlighted values. This might an empty if nothing is highlighted.
public var highlighted: [ChartHighlight]
{
return _indicesToHighlight
}
/// Set this to false to prevent values from being highlighted by tap gesture.
/// Values can still be highlighted via drag or programmatically.
/// - default: true
public var highlightPerTapEnabled: Bool
{
get { return _highlightPerTapEnabled }
set { _highlightPerTapEnabled = newValue }
}
/// Returns true if values can be highlighted via tap gesture, false if not.
public var isHighLightPerTapEnabled: Bool
{
return highlightPerTapEnabled
}
/// Checks if the highlight array is null, has a length of zero or if the first object is null.
/// - returns: true if there are values to highlight, false if there are no values to highlight.
public func valuesToHighlight() -> Bool
{
return _indicesToHighlight.count > 0
}
/// Highlights the values at the given indices in the given DataSets. Provide
/// null or an empty array to undo all highlighting.
/// This should be used to programmatically highlight values.
/// This DOES NOT generate a callback to the delegate.
public func highlightValues(highs: [ChartHighlight]?)
{
// set the indices to highlight
_indicesToHighlight = highs ?? [ChartHighlight]()
if (_indicesToHighlight.isEmpty)
{
self.lastHighlighted = nil
}
else
{
self.lastHighlighted = _indicesToHighlight[0];
}
// redraw the chart
setNeedsDisplay()
}
/// Highlights the values represented by the provided Highlight object
/// This DOES NOT generate a callback to the delegate.
/// - parameter highlight: contains information about which entry should be highlighted
public func highlightValue(highlight: ChartHighlight?)
{
highlightValue(highlight: highlight, callDelegate: false)
}
/// Highlights the value at the given x-index in the given DataSet.
/// Provide -1 as the x-index to undo all highlighting.
public func highlightValue(xIndex xIndex: Int, dataSetIndex: Int, callDelegate: Bool)
{
if (xIndex < 0 || dataSetIndex < 0 || xIndex >= _data.xValCount || dataSetIndex >= _data.dataSetCount)
{
highlightValue(highlight: nil, callDelegate: callDelegate)
}
else
{
highlightValue(highlight: ChartHighlight(xIndex: xIndex, dataSetIndex: dataSetIndex), callDelegate: callDelegate)
}
}
/// Highlights the value selected by touch gesture.
public func highlightValue(highlight highlight: ChartHighlight?, callDelegate: Bool)
{
var entry: ChartDataEntry?
var h = highlight
if (h == nil)
{
_indicesToHighlight.removeAll(keepCapacity: false)
}
else
{
// set the indices to highlight
entry = _data.getEntryForHighlight(h!)
if (entry === nil || entry!.xIndex != h?.xIndex)
{
h = nil
entry = nil
_indicesToHighlight.removeAll(keepCapacity: false)
}
else
{
_indicesToHighlight = [h!]
}
}
if (callDelegate && delegate != nil)
{
if (h == nil)
{
delegate!.chartValueNothingSelected?(self)
}
else
{
// notify the listener
delegate!.chartValueSelected?(self, entry: entry!, dataSetIndex: h!.dataSetIndex, highlight: h!)
}
}
// redraw the chart
setNeedsDisplay()
}
/// The last value that was highlighted via touch.
public var lastHighlighted: ChartHighlight?
// MARK: - Markers
/// draws all MarkerViews on the highlighted positions
internal func drawMarkers(context context: CGContext)
{
// if there is no marker view or drawing marker is disabled
if (marker === nil || !drawMarkers || !valuesToHighlight())
{
return
}
for (var i = 0, count = _indicesToHighlight.count; i < count; i++)
{
let highlight = _indicesToHighlight[i]
let xIndex = highlight.xIndex
if (xIndex <= Int(_deltaX) && xIndex <= Int(_deltaX * _animator.phaseX))
{
let e = _data.getEntryForHighlight(highlight)
if (e === nil || e!.xIndex != highlight.xIndex)
{
continue
}
let pos = getMarkerPosition(entry: e!, highlight: highlight)
// check bounds
if (!_viewPortHandler.isInBounds(x: pos.x, y: pos.y))
{
continue
}
// callbacks to update the content
marker!.refreshContent(entry: e!, highlight: highlight)
let markerSize = marker!.size
if (pos.y - markerSize.height <= 0.0)
{
let y = markerSize.height - pos.y
marker!.draw(context: context, point: CGPoint(x: pos.x, y: pos.y + y))
}
else
{
marker!.draw(context: context, point: pos)
}
}
}
}
/// - returns: the actual position in pixels of the MarkerView for the given Entry in the given DataSet.
public func getMarkerPosition(entry entry: ChartDataEntry, highlight: ChartHighlight) -> CGPoint
{
fatalError("getMarkerPosition() cannot be called on ChartViewBase")
}
// MARK: - Animation
/// - returns: the animator responsible for animating chart values.
public var animator: ChartAnimator!
{
return _animator
}
/// Animates the drawing / rendering of the chart on both x- and y-axis with the specified animation time.
/// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart.
/// - parameter xAxisDuration: duration for animating the x axis
/// - parameter yAxisDuration: duration for animating the y axis
/// - parameter easingX: an easing function for the animation on the x axis
/// - parameter easingY: an easing function for the animation on the y axis
public func animate(xAxisDuration xAxisDuration: NSTimeInterval, yAxisDuration: NSTimeInterval, easingX: ChartEasingFunctionBlock?, easingY: ChartEasingFunctionBlock?)
{
_animator.animate(xAxisDuration: xAxisDuration, yAxisDuration: yAxisDuration, easingX: easingX, easingY: easingY)
}
/// Animates the drawing / rendering of the chart on both x- and y-axis with the specified animation time.
/// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart.
/// - parameter xAxisDuration: duration for animating the x axis
/// - parameter yAxisDuration: duration for animating the y axis
/// - parameter easingOptionX: the easing function for the animation on the x axis
/// - parameter easingOptionY: the easing function for the animation on the y axis
public func animate(xAxisDuration xAxisDuration: NSTimeInterval, yAxisDuration: NSTimeInterval, easingOptionX: ChartEasingOption, easingOptionY: ChartEasingOption)
{
_animator.animate(xAxisDuration: xAxisDuration, yAxisDuration: yAxisDuration, easingOptionX: easingOptionX, easingOptionY: easingOptionY)
}
/// Animates the drawing / rendering of the chart on both x- and y-axis with the specified animation time.
/// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart.
/// - parameter xAxisDuration: duration for animating the x axis
/// - parameter yAxisDuration: duration for animating the y axis
/// - parameter easing: an easing function for the animation
public func animate(xAxisDuration xAxisDuration: NSTimeInterval, yAxisDuration: NSTimeInterval, easing: ChartEasingFunctionBlock?)
{
_animator.animate(xAxisDuration: xAxisDuration, yAxisDuration: yAxisDuration, easing: easing)
}
/// Animates the drawing / rendering of the chart on both x- and y-axis with the specified animation time.
/// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart.
/// - parameter xAxisDuration: duration for animating the x axis
/// - parameter yAxisDuration: duration for animating the y axis
/// - parameter easingOption: the easing function for the animation
public func animate(xAxisDuration xAxisDuration: NSTimeInterval, yAxisDuration: NSTimeInterval, easingOption: ChartEasingOption)
{
_animator.animate(xAxisDuration: xAxisDuration, yAxisDuration: yAxisDuration, easingOption: easingOption)
}
/// Animates the drawing / rendering of the chart on both x- and y-axis with the specified animation time.
/// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart.
/// - parameter xAxisDuration: duration for animating the x axis
/// - parameter yAxisDuration: duration for animating the y axis
public func animate(xAxisDuration xAxisDuration: NSTimeInterval, yAxisDuration: NSTimeInterval)
{
_animator.animate(xAxisDuration: xAxisDuration, yAxisDuration: yAxisDuration)
}
/// Animates the drawing / rendering of the chart the x-axis with the specified animation time.
/// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart.
/// - parameter xAxisDuration: duration for animating the x axis
/// - parameter easing: an easing function for the animation
public func animate(xAxisDuration xAxisDuration: NSTimeInterval, easing: ChartEasingFunctionBlock?)
{
_animator.animate(xAxisDuration: xAxisDuration, easing: easing)
}
/// Animates the drawing / rendering of the chart the x-axis with the specified animation time.
/// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart.
/// - parameter xAxisDuration: duration for animating the x axis
/// - parameter easingOption: the easing function for the animation
public func animate(xAxisDuration xAxisDuration: NSTimeInterval, easingOption: ChartEasingOption)
{
_animator.animate(xAxisDuration: xAxisDuration, easingOption: easingOption)
}
/// Animates the drawing / rendering of the chart the x-axis with the specified animation time.
/// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart.
/// - parameter xAxisDuration: duration for animating the x axis
public func animate(xAxisDuration xAxisDuration: NSTimeInterval)
{
_animator.animate(xAxisDuration: xAxisDuration)
}
/// Animates the drawing / rendering of the chart the y-axis with the specified animation time.
/// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart.
/// - parameter yAxisDuration: duration for animating the y axis
/// - parameter easing: an easing function for the animation
public func animate(yAxisDuration yAxisDuration: NSTimeInterval, easing: ChartEasingFunctionBlock?)
{
_animator.animate(yAxisDuration: yAxisDuration, easing: easing)
}
/// Animates the drawing / rendering of the chart the y-axis with the specified animation time.
/// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart.
/// - parameter yAxisDuration: duration for animating the y axis
/// - parameter easingOption: the easing function for the animation
public func animate(yAxisDuration yAxisDuration: NSTimeInterval, easingOption: ChartEasingOption)
{
_animator.animate(yAxisDuration: yAxisDuration, easingOption: easingOption)
}
/// Animates the drawing / rendering of the chart the y-axis with the specified animation time.
/// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart.
/// - parameter yAxisDuration: duration for animating the y axis
public func animate(yAxisDuration yAxisDuration: NSTimeInterval)
{
_animator.animate(yAxisDuration: yAxisDuration)
}
// MARK: - Accessors
/// - returns: the current y-max value across all DataSets
public var chartYMax: Double
{
return _data.yMax
}
/// - returns: the current y-min value across all DataSets
public var chartYMin: Double
{
return _data.yMin
}
public var chartXMax: Double
{
return _chartXMax
}
public var chartXMin: Double
{
return _chartXMin
}
public var xValCount: Int
{
return _data.xValCount
}
/// - returns: the total number of (y) values the chart holds (across all DataSets)
public var valueCount: Int
{
return _data.yValCount
}
/// *Note: (Equivalent of getCenter() in MPAndroidChart, as center is already a standard in iOS that returns the center point relative to superview, and MPAndroidChart returns relative to self)*
/// - returns: the center point of the chart (the whole View) in pixels.
public var midPoint: CGPoint
{
let bounds = self.bounds
return CGPoint(x: bounds.origin.x + bounds.size.width / 2.0, y: bounds.origin.y + bounds.size.height / 2.0)
}
public func setDescriptionTextPosition(x x: CGFloat, y: CGFloat)
{
descriptionTextPosition = CGPoint(x: x, y: y)
}
/// - returns: the center of the chart taking offsets under consideration. (returns the center of the content rectangle)
public var centerOffsets: CGPoint
{
return _viewPortHandler.contentCenter
}
/// - returns: the Legend object of the chart. This method can be used to get an instance of the legend in order to customize the automatically generated Legend.
public var legend: ChartLegend
{
return _legend
}
/// - returns: the renderer object responsible for rendering / drawing the Legend.
public var legendRenderer: ChartLegendRenderer!
{
return _legendRenderer
}
/// - returns: the rectangle that defines the borders of the chart-value surface (into which the actual values are drawn).
public var contentRect: CGRect
{
return _viewPortHandler.contentRect
}
/// - returns: the x-value at the given index
public func getXValue(index: Int) -> String!
{
if (_data == nil || _data.xValCount <= index)
{
return nil
}
else
{
return _data.xVals[index]
}
}
/// Get all Entry objects at the given index across all DataSets.
public func getEntriesAtIndex(xIndex: Int) -> [ChartDataEntry]
{
var vals = [ChartDataEntry]()
for (var i = 0, count = _data.dataSetCount; i < count; i++)
{
let set = _data.getDataSetByIndex(i)
let e = set.entryForXIndex(xIndex)
if (e !== nil)
{
vals.append(e!)
}
}
return vals
}
/// - returns: the percentage the given value has of the total y-value sum
public func percentOfTotal(val: Double) -> Double
{
return val / _data.yValueSum * 100.0
}
/// - returns: the ViewPortHandler of the chart that is responsible for the
/// content area of the chart and its offsets and dimensions.
public var viewPortHandler: ChartViewPortHandler!
{
return _viewPortHandler
}
/// - returns: the bitmap that represents the chart.
public func getChartImage(transparent transparent: Bool) -> UIImage
{
UIGraphicsBeginImageContextWithOptions(bounds.size, opaque || !transparent, UIScreen.mainScreen().scale)
let context = UIGraphicsGetCurrentContext()
let rect = CGRect(origin: CGPoint(x: 0, y: 0), size: bounds.size)
if (opaque || !transparent)
{
// Background color may be partially transparent, we must fill with white if we want to output an opaque image
CGContextSetFillColorWithColor(context, UIColor.whiteColor().CGColor)
CGContextFillRect(context, rect)
if (self.backgroundColor !== nil)
{
CGContextSetFillColorWithColor(context, self.backgroundColor?.CGColor)
CGContextFillRect(context, rect)
}
}
if let context = context
{
layer.renderInContext(context)
}
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
public enum ImageFormat
{
case JPEG
case PNG
}
/// Saves the current chart state with the given name to the given path on
/// the sdcard leaving the path empty "" will put the saved file directly on
/// the SD card chart is saved as a PNG image, example:
/// saveToPath("myfilename", "foldername1/foldername2")
///
/// - parameter filePath: path to the image to save
/// - parameter format: the format to save
/// - parameter compressionQuality: compression quality for lossless formats (JPEG)
///
/// - returns: true if the image was saved successfully
public func saveToPath(path: String, format: ImageFormat, compressionQuality: Double) -> Bool
{
let image = getChartImage(transparent: format != .JPEG)
var imageData: NSData!
switch (format)
{
case .PNG:
imageData = UIImagePNGRepresentation(image)
break
case .JPEG:
imageData = UIImageJPEGRepresentation(image, CGFloat(compressionQuality))
break
}
return imageData.writeToFile(path, atomically: true)
}
#if !os(tvOS)
/// Saves the current state of the chart to the camera roll
public func saveToCameraRoll()
{
UIImageWriteToSavedPhotosAlbum(getChartImage(transparent: false), nil, nil, nil)
}
#endif
internal typealias VoidClosureType = () -> ()
internal var _sizeChangeEventActions = [VoidClosureType]()
public override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>)
{
if (keyPath == "bounds" || keyPath == "frame")
{
let bounds = self.bounds
if (_viewPortHandler !== nil &&
(bounds.size.width != _viewPortHandler.chartWidth ||
bounds.size.height != _viewPortHandler.chartHeight))
{
_viewPortHandler.setChartDimens(width: bounds.size.width, height: bounds.size.height)
// Finish any pending viewport changes
while (!_sizeChangeEventActions.isEmpty)
{
_sizeChangeEventActions.removeAtIndex(0)()
}
notifyDataSetChanged()
}
}
}
public func clearPendingViewPortChanges()
{
_sizeChangeEventActions.removeAll(keepCapacity: false)
}
/// **default**: true
/// - returns: true if chart continues to scroll after touch up, false if not.
public var isDragDecelerationEnabled: Bool
{
return dragDecelerationEnabled
}
/// Deceleration friction coefficient in [0 ; 1] interval, higher values indicate that speed will decrease slowly, for example if it set to 0, it will stop immediately.
/// 1 is an invalid value, and will be converted to 0.999 automatically.
///
/// **default**: true
public var dragDecelerationFrictionCoef: CGFloat
{
get
{
return _dragDecelerationFrictionCoef
}
set
{
var val = newValue
if (val < 0.0)
{
val = 0.0
}
if (val >= 1.0)
{
val = 0.999
}
_dragDecelerationFrictionCoef = val
}
}
// MARK: - ChartAnimatorDelegate
public func chartAnimatorUpdated(chartAnimator: ChartAnimator)
{
setNeedsDisplay()
}
public func chartAnimatorStopped(chartAnimator: ChartAnimator)
{
}
// MARK: - Touches
public override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?)
{
if (!_interceptTouchEvents)
{
super.touchesBegan(touches, withEvent: event)
}
}
public override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?)
{
if (!_interceptTouchEvents)
{
super.touchesMoved(touches, withEvent: event)
}
}
public override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?)
{
if (!_interceptTouchEvents)
{
super.touchesEnded(touches, withEvent: event)
}
}
public override func touchesCancelled(touches: Set<UITouch>?, withEvent event: UIEvent?)
{
if (!_interceptTouchEvents)
{
super.touchesCancelled(touches, withEvent: event)
}
}
} | apache-2.0 | 62e31c55408e2a35016530677210023c | 35.563863 | 265 | 0.62397 | 5.373112 | false | false | false | false |
ayo1103/DemoRoundedContentView | DemoRoundedContentView/ViewController.swift | 1 | 1762 | //
// ViewController.swift
// TestCornerTableView
//
// Created by Bryan Lin on 3/4/16.
// Copyright © 2016 ayo1103. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var myTableView: UITableView!
var datas = [String]()
override func viewDidLoad() {
super.viewDidLoad()
myTableView.contentInset = UIEdgeInsets(top: 180, left: 0, bottom: 10, right: 0)
(1...10).forEach {
datas.append(String($0))
}
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
myTableView.makeContentRounded(radius: 5)
}
}
extension UITableView {
func makeContentRounded(radius radius: CGFloat) {
let contentBounds = CGRect(origin: CGPoint.zero, size: self.contentSize)
let rectShape = CAShapeLayer()
rectShape.bounds = contentBounds
rectShape.position = CGPoint(x: CGRectGetMidX(contentBounds), y: CGRectGetMidY(contentBounds))
rectShape.path = UIBezierPath(
roundedRect: contentBounds,
byRoundingCorners: UIRectCorner.AllCorners,
cornerRadii: CGSize(width: radius, height: radius)
).CGPath
self.layer.mask = rectShape
}
}
extension ViewController: UITableViewDataSource {
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return datas.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! MyCell
cell.data = datas[indexPath.row]
return cell
}
}
class MyCell: UITableViewCell {
@IBOutlet weak var myLabel: UILabel!
var data: String! {
didSet {
myLabel.text = data
}
}
} | mit | 521e2a8323c38d0a2fb110c03ba5682a | 22.493333 | 107 | 0.708688 | 4.369727 | false | false | false | false |
erusso1/ERNiftyFoundation | ERNiftyFoundation/Source/Classes/ERGlobals.swift | 1 | 1198 |
public typealias JSONObject = [String : Any]
public typealias VoidCompletionHandler = () -> Void
public typealias ErrorCompletionHandler = (Error?) -> Void
public typealias BoolCompletionHandler = (Bool) -> Void
public func afterDelay(_ delay:Double, closure:@escaping ()->()) {
DispatchQueue.main.asyncAfter(
deadline: DispatchTime.now() + Double(Int64(delay * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC), execute: closure)
}
public func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l < r
case (nil, _?):
return true
default:
return false
}
}
public func > <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l > r
default:
return rhs < lhs
}
}
public func +<Key, Value> (lhs: [Key: Value], rhs: [Key: Value]) -> [Key: Value] {
var result = lhs
rhs.forEach{ result[$0] = $1 }
return result
}
public func += <K, V> (left: inout [K:V], right: [K:V]) {
for (k, v) in right {
left.updateValue(v, forKey: k)
}
}
public func printPretty(_ item: Any) {
print("*****************************************")
print("")
print(item)
print("")
}
| mit | fec98bcca0cd7f530541cf734c7ccf8d | 21.603774 | 120 | 0.59015 | 3.355742 | false | false | false | false |
xwu/swift | libswift/Sources/Optimizer/Analysis/CalleeAnalysis.swift | 4 | 1323 | //===--- CalleeAnalysis.swift - the callee analysis -----------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import OptimizerBridging
import SIL
public struct CalleeAnalysis {
let bridged: BridgedCalleeAnalysis
public func getCallees(callee: Value) -> FunctionArray {
return FunctionArray(bridged: CalleeAnalysis_getCallees(bridged, callee.bridged))
}
}
public struct FunctionArray : RandomAccessCollection, CustomReflectable {
fileprivate let bridged: BridgedCalleeList
public var startIndex: Int { 0 }
public var endIndex: Int { BridgedFunctionArray_size(bridged) }
public subscript(_ index: Int) -> Function {
return BridgedFunctionArray_get(bridged, index).function
}
public var allCalleesKnown: Bool { bridged.incomplete == 0 }
public var customMirror: Mirror {
let c: [Mirror.Child] = map { (label: nil, value: $0.name) }
return Mirror(self, children: c)
}
}
| apache-2.0 | 662fb80111283304cf34c41d2fdf9530 | 32.075 | 85 | 0.676493 | 4.5 | false | false | false | false |
qualaroo/QualarooSDKiOS | Qualaroo/Network/SdkSession.swift | 1 | 1049 | //
// SdkSession.swift
// Qualaroo
//
// Created by Marcin Robaczyński on 16/08/2018.
// Copyright © 2018 Mihály Papp. All rights reserved.
//
import Foundation
struct SdkSession {
let platform = "iOS"
let osVersion = UIDevice.current.systemVersion
let deviceModel = UIDevice.current.type
let language: String = Locale.current.languageCode ?? "unknown"
let sdkVersion: String = Bundle.qualaroo()?.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "unknown"
let appId: String = Bundle.main.bundleIdentifier ?? "unknown"
let resolution: String
let deviceType: String
init() {
let screenSize = UIScreen.main.bounds
self.resolution = "\(Int(screenSize.width))x\(Int(screenSize.height))"
self.deviceType = SdkSession.findDeviceType()
}
private static func findDeviceType() -> String {
let idiom = UIDevice.current.userInterfaceIdiom
switch(idiom) {
case .phone:
return "phone"
case .pad:
return "tablet"
default:
return "other"
}
}
}
| mit | df952d5ce2a228c3fa025fc5242f3f2d | 25.15 | 128 | 0.691205 | 4.007663 | false | false | false | false |
JanGorman/Agrume | Agrume/Agrume.swift | 1 | 22016 | //
// Copyright © 2016 Schnaub. All rights reserved.
//
import UIKit
public final class Agrume: UIViewController {
/// Tap behaviour, i.e. what happens when you tap outside of the image area
public enum TapBehavior {
case dismissIfZoomedOut
case dismissAlways
case zoomOut
case toggleOverlayVisibility
}
private var images: [AgrumeImage]!
private let startIndex: Int
private let dismissal: Dismissal
private let enableLiveText: Bool
private var overlayView: AgrumeOverlayView?
private weak var dataSource: AgrumeDataSource?
/// The background property. Set through the initialiser for most use cases.
public var background: Background
/// The "page" index for the current image
public private(set) var currentIndex: Int
public typealias DownloadCompletion = (_ image: UIImage?) -> Void
/// Optional closure to call when user long pressed on an image
public var onLongPress: ((UIImage?, UIViewController) -> Void)?
/// Optional closure to call whenever Agrume is about to dismiss.
public var willDismiss: (() -> Void)?
/// Optional closure to call whenever Agrume is dismissed.
public var didDismiss: (() -> Void)?
/// Optional closure to call whenever Agrume scrolls to the next image in a collection. Passes the "page" index
public var didScroll: ((_ index: Int) -> Void)?
/// An optional download handler. Passed the URL that is supposed to be loaded. Call the completion with the image
/// when the download is done.
public var download: ((_ url: URL, _ completion: @escaping DownloadCompletion) -> Void)?
/// Status bar style when presenting
public var statusBarStyle: UIStatusBarStyle? {
didSet {
setNeedsStatusBarAppearanceUpdate()
}
}
/// Hide status bar when presenting. Defaults to `false`
public var hideStatusBar = false
/// Default tap behaviour is to dismiss the view if zoomed out
public var tapBehavior: TapBehavior = .dismissIfZoomedOut
override public var preferredStatusBarStyle: UIStatusBarStyle {
statusBarStyle ?? super.preferredStatusBarStyle
}
/// Initialize with a single image
///
/// - Parameters:
/// - image: The image to present
/// - background: The background configuration
/// - dismissal: The dismiss configuration
/// - overlayView: View to overlay the image (does not display with 'button' dismissals)
/// - enableLiveText: Enables Live Text interaction, iOS 16 only
public convenience init(
image: UIImage,
background: Background = .colored(.black),
dismissal: Dismissal = .withPan(.standard),
overlayView: AgrumeOverlayView? = nil,
enableLiveText: Bool = false
) {
self.init(
images: [image],
background: background,
dismissal: dismissal,
overlayView: overlayView,
enableLiveText: enableLiveText
)
}
/// Initialize with a single image url
///
/// - Parameters:
/// - url: The image url to present
/// - background: The background configuration
/// - dismissal: The dismiss configuration
/// - overlayView: View to overlay the image (does not display with 'button' dismissals)
/// - enableLiveText: Enables Live Text interaction, iOS 16 only
public convenience init(
url: URL,
background: Background = .colored(.black),
dismissal: Dismissal = .withPan(.standard),
overlayView: AgrumeOverlayView? = nil,
enableLiveText: Bool = false
) {
self.init(
urls: [url],
background: background,
dismissal: dismissal,
overlayView: overlayView,
enableLiveText: enableLiveText
)
}
/// Initialize with a data source
///
/// - Parameters:
/// - dataSource: The `AgrumeDataSource` to use
/// - startIndex: The optional start index when showing multiple images
/// - background: The background configuration
/// - dismissal: The dismiss configuration
/// - overlayView: View to overlay the image (does not display with 'button' dismissals)
/// - enableLiveText: Enables Live Text interaction, iOS 16 only
public convenience init(
dataSource: AgrumeDataSource,
startIndex: Int = 0,
background: Background = .colored(.black),
dismissal: Dismissal = .withPan(.standard),
overlayView: AgrumeOverlayView? = nil,
enableLiveText: Bool = false
) {
self.init(
images: nil,
dataSource: dataSource,
startIndex: startIndex,
background: background,
dismissal: dismissal,
overlayView: overlayView,
enableLiveText: enableLiveText
)
}
/// Initialize with an array of images
///
/// - Parameters:
/// - images: The images to present
/// - startIndex: The optional start index when showing multiple images
/// - background: The background configuration
/// - dismissal: The dismiss configuration
/// - overlayView: View to overlay the image (does not display with 'button' dismissals)
/// - enableLiveText: Enables Live Text interaction, iOS 16 only
public convenience init(
images: [UIImage],
startIndex: Int = 0,
background: Background = .colored(.black),
dismissal: Dismissal = .withPan(.standard),
overlayView: AgrumeOverlayView? = nil,
enableLiveText: Bool = false
) {
self.init(
images: images,
urls: nil,
startIndex: startIndex,
background: background,
dismissal: dismissal,
overlayView: overlayView,
enableLiveText: enableLiveText
)
}
/// Initialize with an array of image urls
///
/// - Parameters:
/// - urls: The image urls to present
/// - startIndex: The optional start index when showing multiple images
/// - background: The background configuration
/// - dismissal: The dismiss configuration
/// - overlayView: View to overlay the image (does not display with 'button' dismissals)
/// - enableLiveText: Enables Live Text interaction, iOS 16 only
public convenience init(
urls: [URL],
startIndex: Int = 0,
background: Background = .colored(.black),
dismissal: Dismissal = .withPan(.standard),
overlayView: AgrumeOverlayView? = nil,
enableLiveText: Bool = false
) {
self.init(
images: nil,
urls: urls,
startIndex: startIndex,
background: background,
dismissal: dismissal,
overlayView: overlayView,
enableLiveText: enableLiveText
)
}
private init(
images: [UIImage]? = nil,
urls: [URL]? = nil,
dataSource: AgrumeDataSource? = nil,
startIndex: Int,
background: Background,
dismissal: Dismissal,
overlayView: AgrumeOverlayView? = nil,
enableLiveText: Bool = false
) {
switch (images, urls) {
case (let images?, nil):
self.images = images.map { AgrumeImage(image: $0) }
case (_, let urls?):
self.images = urls.map { AgrumeImage(url: $0) }
default:
assert(dataSource != nil, "No images or URLs passed. You must provide an AgrumeDataSource in that case.")
}
self.startIndex = startIndex
self.currentIndex = startIndex
self.background = background
self.dismissal = dismissal
self.enableLiveText = enableLiveText
super.init(nibName: nil, bundle: nil)
self.overlayView = overlayView
self.dataSource = dataSource ?? self
modalPresentationStyle = .custom
modalPresentationCapturesStatusBarAppearance = true
}
deinit {
downloadTask?.cancel()
}
@available(*, unavailable)
required public init?(coder aDecoder: NSCoder) {
fatalError("Not implemented")
}
private var _blurContainerView: UIView?
private var blurContainerView: UIView {
if _blurContainerView == nil {
let blurContainerView = UIView()
blurContainerView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
if case .colored(let color) = background {
blurContainerView.backgroundColor = color
} else {
blurContainerView.backgroundColor = .clear
}
blurContainerView.frame = CGRect(origin: view.frame.origin, size: view.frame.size * 2)
_blurContainerView = blurContainerView
}
return _blurContainerView!
}
private var _blurView: UIVisualEffectView?
private var blurView: UIVisualEffectView {
guard case .blurred(let style) = background, _blurView == nil else {
return _blurView!
}
let blurView = UIVisualEffectView(effect: UIBlurEffect(style: style))
blurView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
blurView.frame = blurContainerView.bounds
_blurView = blurView
return _blurView!
}
private var _collectionView: UICollectionView?
private var collectionView: UICollectionView {
if _collectionView == nil {
let layout = UICollectionViewFlowLayout()
layout.minimumInteritemSpacing = 0
layout.minimumLineSpacing = 0
layout.scrollDirection = .horizontal
let collectionView = UICollectionView(frame: view.bounds, collectionViewLayout: layout)
collectionView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
collectionView.register(AgrumeCell.self)
collectionView.dataSource = self
collectionView.delegate = self
collectionView.isPagingEnabled = true
collectionView.backgroundColor = .clear
collectionView.delaysContentTouches = false
collectionView.showsHorizontalScrollIndicator = false
if #available(iOS 11.0, *) {
collectionView.contentInsetAdjustmentBehavior = .never
}
_collectionView = collectionView
}
return _collectionView!
}
private var _spinner: UIActivityIndicatorView?
private var spinner: UIActivityIndicatorView {
if _spinner == nil {
let indicatorStyle: UIActivityIndicatorView.Style
switch background {
case let .blurred(style):
indicatorStyle = style == .dark ? .large : .medium
case let .colored(color):
indicatorStyle = color.isLight ? .medium : .large
}
let spinner = UIActivityIndicatorView(style: indicatorStyle)
spinner.center = view.center
spinner.startAnimating()
spinner.alpha = 0
_spinner = spinner
}
return _spinner!
}
// Container for the collection view. Fixes an RTL display bug
private lazy var containerView = with(UIView(frame: view.bounds)) { containerView in
containerView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
}
private var downloadTask: URLSessionDataTask?
/// Present Agrume
///
/// - Parameters:
/// - viewController: The UIViewController to present from
public func show(from viewController: UIViewController) {
view.isUserInteractionEnabled = false
addSubviews()
present(from: viewController)
}
/// Update image at index
/// - Parameters:
/// - index: The target index
/// - image: The replacement UIImage
/// - newTitle: The new title, if nil then no change
public func updateImage(at index: Int, with image: UIImage, newTitle: NSAttributedString? = nil) {
assert(images.count > index)
let replacement = with(images[index]) {
$0.url = nil
$0.image = image
if let newTitle {
$0.title = newTitle
}
}
markAsUpdatingSameCell(at: index)
images[index] = replacement
reload()
}
/// Update image at a specific index
/// - Parameters:
/// - index: The target index
/// - url: The replacement URL
/// - newTitle: The new title, if nil then no change
public func updateImage(at index: Int, with url: URL, newTitle: NSAttributedString? = nil) {
assert(images.count > index)
let replacement = with(images[index]) {
$0.image = nil
$0.url = url
if let newTitle {
$0.title = newTitle
}
}
markAsUpdatingSameCell(at: index)
images[index] = replacement
reload()
}
private func markAsUpdatingSameCell(at index: Int) {
collectionView.visibleCells.forEach { cell in
if let cell = cell as? AgrumeCell, cell.index == index {
cell.updatingImageOnSameCell = true
}
}
}
override public func viewDidLoad() {
super.viewDidLoad()
addSubviews()
if onLongPress != nil {
let longPress = UILongPressGestureRecognizer(target: self, action: #selector(didLongPress(_:)))
view.addGestureRecognizer(longPress)
}
}
@objc
func didLongPress(_ gesture: UIGestureRecognizer) {
guard case .began = gesture.state else {
return
}
fetchImage(forIndex: currentIndex) { [weak self] image in
guard let self else {
return
}
self.onLongPress?(image, self)
}
}
public func addSubviews() {
view.autoresizingMask = [.flexibleHeight, .flexibleWidth]
if case .blurred = background {
blurContainerView.addSubview(blurView)
}
view.addSubview(blurContainerView)
view.addSubview(containerView)
containerView.addSubview(collectionView)
view.addSubview(spinner)
}
private func present(from viewController: UIViewController) {
DispatchQueue.main.async {
self.blurContainerView.alpha = 1
self.containerView.alpha = 0
let scale: CGFloat = .initialScaleToExpandFrom
viewController.present(self, animated: false) {
// Transform the container view, not the collection view to prevent an RTL display bug
self.containerView.transform = CGAffineTransform(scaleX: scale, y: scale)
UIView.animate(
withDuration: .transitionAnimationDuration,
delay: 0,
options: .beginFromCurrentState,
animations: {
self.containerView.alpha = 1
self.containerView.transform = .identity
self.addOverlayView()
},
completion: { _ in
self.view.isUserInteractionEnabled = true
}
)
}
}
}
public func addOverlayView() {
switch (dismissal, overlayView) {
case let (.withButton(button), _), let (.withPanAndButton(_, button), _):
let overlayView = AgrumeCloseButtonOverlayView(closeButton: button)
overlayView.delegate = self
overlayView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
overlayView.frame = view.bounds
view.addSubview(overlayView)
self.overlayView = overlayView
case (.withPan, let overlayView?):
overlayView.alpha = 1
overlayView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
overlayView.frame = view.bounds
view.addSubview(overlayView)
default:
break
}
}
private func viewControllerForSnapshot(fromViewController viewController: UIViewController) -> UIViewController? {
var presentingVC = viewController.view.window?.rootViewController
while presentingVC?.presentedViewController != nil {
presentingVC = presentingVC?.presentedViewController
}
return presentingVC
}
public override var keyCommands: [UIKeyCommand]? {
return [
UIKeyCommand(input: UIKeyCommand.inputEscape, modifierFlags: [], action: #selector(escPressed))
]
}
@objc
func escPressed() {
dismiss()
}
public func dismiss() {
dismissAfterFlick()
}
public func showImage(atIndex index: Int, animated: Bool = true) {
scrollToImage(atIndex: index, animated: animated)
}
public func reload() {
DispatchQueue.main.async {
self.collectionView.reloadData()
}
}
override public var prefersStatusBarHidden: Bool {
hideStatusBar
}
private func scrollToImage(atIndex index: Int, animated: Bool = false) {
collectionView.scrollToItem(at: IndexPath(item: index, section: 0), at: .centeredHorizontally, animated: animated)
}
private func currentlyVisibleCellIndex() -> Int {
let visibleRect = CGRect(origin: collectionView.contentOffset, size: collectionView.bounds.size)
let visiblePoint = CGPoint(x: visibleRect.minX, y: visibleRect.minY)
return collectionView.indexPathForItem(at: visiblePoint)?.item ?? startIndex
}
override public func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
layout.itemSize = view.bounds.size
layout.invalidateLayout()
spinner.center = view.center
if currentIndex != currentlyVisibleCellIndex() {
scrollToImage(atIndex: currentIndex)
}
}
override public func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
let indexToRotate = currentIndex
let rotationHandler: ((UIViewControllerTransitionCoordinatorContext) -> Void) = { _ in
self.scrollToImage(atIndex: indexToRotate)
self.collectionView.visibleCells.forEach { cell in
(cell as! AgrumeCell).recenterDuringRotation(size: size)
}
}
coordinator.animate(alongsideTransition: rotationHandler, completion: rotationHandler)
super.viewWillTransition(to: size, with: coordinator)
}
}
extension Agrume: AgrumeDataSource {
public var numberOfImages: Int {
images.count
}
public func image(forIndex index: Int, completion: @escaping (UIImage?) -> Void) {
let downloadHandler = download ?? AgrumeServiceLocator.shared.downloadHandler
if let handler = downloadHandler, let url = images[index].url {
handler(url, completion)
} else if let url = images[index].url {
downloadTask = ImageDownloader.downloadImage(url, completion: completion)
} else {
completion(images[index].image)
}
}
}
extension Agrume: UICollectionViewDataSource {
public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
dataSource?.numberOfImages ?? 0
}
public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell: AgrumeCell = collectionView.dequeue(indexPath: indexPath)
cell.enableLiveText = enableLiveText
cell.tapBehavior = tapBehavior
switch dismissal {
case .withPan(let physics), .withPanAndButton(let physics, _):
cell.panPhysics = physics
case .withButton:
cell.panPhysics = nil
// Backward compatibility
case .withPhysics, .withPhysicsAndButton:
cell.panPhysics = .standard
}
spinner.alpha = 1
fetchImage(forIndex: indexPath.item) { [weak self] image in
cell.index = indexPath.item
cell.image = image
self?.spinner.alpha = 0
}
// Only allow panning if horizontal swiping fails. Horizontal swiping is only active for zoomed in images
collectionView.panGestureRecognizer.require(toFail: cell.swipeGesture)
cell.delegate = self
return cell
}
private func fetchImage(forIndex index: Int, handler: @escaping (UIImage?) -> Void) {
dataSource?.image(forIndex: index) { image in
DispatchQueue.main.async {
handler(image)
}
}
}
}
extension Agrume: UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
public func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
insetForSectionAt section: Int) -> UIEdgeInsets {
// Center cells horizontally
let cellWidth = view.bounds.width
let totalWidth = cellWidth * CGFloat(dataSource?.numberOfImages ?? 0)
let leftRightEdgeInset = max(0, (collectionView.bounds.width - totalWidth) / 2)
return UIEdgeInsets(top: 0, left: leftRightEdgeInset, bottom: 0, right: leftRightEdgeInset)
}
public func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
didScroll?(currentlyVisibleCellIndex())
}
public func scrollViewDidScroll(_ scrollView: UIScrollView) {
let center = CGPoint(x: scrollView.contentOffset.x + (scrollView.frame.width / 2), y: (scrollView.frame.height / 2))
if let indexPath = collectionView.indexPathForItem(at: center) {
currentIndex = indexPath.row
}
}
}
extension Agrume: AgrumeCellDelegate {
var isSingleImageMode: Bool {
dataSource?.numberOfImages == 1
}
private func dismissCompletion(_ finished: Bool) {
presentingViewController?.dismiss(animated: false) { [unowned self] in
self.cleanup()
self.didDismiss?()
}
}
private func cleanup() {
_blurContainerView?.removeFromSuperview()
_blurContainerView = nil
_blurView = nil
_collectionView?.visibleCells.forEach { cell in
(cell as? AgrumeCell)?.cleanup()
}
_collectionView?.removeFromSuperview()
_collectionView = nil
_spinner?.removeFromSuperview()
_spinner = nil
}
func dismissAfterFlick() {
self.willDismiss?()
UIView.animate(
withDuration: .transitionAnimationDuration,
delay: 0,
options: .beginFromCurrentState,
animations: {
self.collectionView.alpha = 0
self.blurContainerView.alpha = 0
self.overlayView?.alpha = 0
},
completion: dismissCompletion
)
}
func dismissAfterTap() {
view.isUserInteractionEnabled = false
self.willDismiss?()
UIView.animate(
withDuration: .transitionAnimationDuration,
delay: 0,
options: .beginFromCurrentState,
animations: {
self.collectionView.alpha = 0
self.blurContainerView.alpha = 0
self.overlayView?.alpha = 0
let scale: CGFloat = .maxScaleForExpandingOffscreen
self.collectionView.transform = CGAffineTransform(scaleX: scale, y: scale)
},
completion: dismissCompletion
)
}
func toggleOverlayVisibility() {
UIView.animate(
withDuration: .transitionAnimationDuration,
delay: 0,
options: .beginFromCurrentState,
animations: {
if let overlayView = self.overlayView {
overlayView.alpha = overlayView.alpha < 0.5 ? 1 : 0
}
},
completion: nil
)
}
}
extension Agrume: AgrumeCloseButtonOverlayViewDelegate {
func agrumeOverlayViewWantsToClose(_ view: AgrumeCloseButtonOverlayView) {
dismiss()
}
}
| mit | f74df406ca75583090af2f2c6295c46b | 30.998547 | 126 | 0.683034 | 4.793164 | false | false | false | false |
xiandan/diaobaoweibo-swift | XWeibo-swift/Classes/Library/PhotoSelector/XPhotoSelectorController.swift | 1 | 7246 | //
// XPhotoSelectorController.swift
// PhotoSelector
//
// Created by Apple on 15/11/10.
// Copyright © 2015年 Apple. All rights reserved.
//
import UIKit
private let reuseIdentifier = "Cell"
class XPhotoSelectorController: UICollectionViewController {
//MARK: - 懒加载
//照片
var photos = [UIImage]()
let photosMaxCount = 6
//记录当前cell的indexPath
var currentIndexPath: NSIndexPath?
override func viewDidLoad() {
super.viewDidLoad()
self.collectionView!.registerClass(XPhotoSelectorCell.self, forCellWithReuseIdentifier: reuseIdentifier)
prepareCollectionView()
}
private let layout = UICollectionViewFlowLayout()
//MARK: - 构造函数
init() {
super.init(collectionViewLayout: layout)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
//MARK: - 准备collectionView
private func prepareCollectionView() {
collectionView?.dataSource = self
layout.itemSize = CGSize(width: 80, height: 80)
collectionView?.backgroundColor = UIColor.purpleColor()
layout.sectionInset = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
}
// MARK: UICollectionViewDataSource
override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return photos.count < photosMaxCount ? photos.count + 1 : photos.count
}
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! XPhotoSelectorCell
cell.cellDelegate = self
if indexPath.item < photos.count {
cell.image = photos[indexPath.row]
}
else {
//防止重用
cell.image = nil
}
return cell
}
}
//MARK: - 代理方法
extension XPhotoSelectorController: XPhotoSelectorCellDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
//添加图片按钮
func photoSelectorCellAdd(cell: XPhotoSelectorCell) {
if !UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.PhotoLibrary) {
print("用户不允许访问相册")
return
}
let picker = UIImagePickerController()
picker.delegate = self
//记录当前cell的indexPath
currentIndexPath = collectionView?.indexPathForCell(cell)
//跳转
presentViewController(picker, animated: true, completion: nil)
}
//删除图片按钮
func photoSelectorCellRemove(cell: XPhotoSelectorCell) {
if let indexPath = collectionView?.indexPathForCell(cell) {
//删除图片
photos.removeAtIndex(indexPath.item)
collectionView?.reloadData()
}
}
func imagePickerController(picker: UIImagePickerController, var didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
image = image.scaleImage()
if currentIndexPath?.item == photos.count {
photos.append(image)
}
else {
//替换图片
photos[currentIndexPath!.item] = image
}
collectionView?.reloadData()
dismissViewControllerAnimated(true, completion: nil)
}
}
//MARK: - cell的代理协议
protocol XPhotoSelectorCellDelegate: NSObjectProtocol {
func photoSelectorCellAdd(cell: XPhotoSelectorCell)
func photoSelectorCellRemove(cell: XPhotoSelectorCell)
}
class XPhotoSelectorCell: UICollectionViewCell {
//照片
var image: UIImage? {
didSet {
if image != nil {
addButton.setImage(image, forState: UIControlState.Normal)
addButton.setImage(image, forState: UIControlState.Highlighted)
removeButton.hidden = false
}
else {
addButton.setImage(UIImage(named: "compose_pic_add_highlighted"), forState: UIControlState.Highlighted)
addButton.setImage(UIImage(named: "compose_pic_add"), forState: UIControlState.Normal)
removeButton.hidden = true
}
}
}
//代理
weak var cellDelegate: XPhotoSelectorCellDelegate?
//MARK: - 构造函数
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override init(frame: CGRect) {
super.init(frame: frame)
prepareUI()
}
//MARK: - 准备UI
private func prepareUI() {
addSubview(addButton)
addSubview(removeButton)
addButton.translatesAutoresizingMaskIntoConstraints = false
removeButton.translatesAutoresizingMaskIntoConstraints = false
addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[ab]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["ab": addButton]))
addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[ab]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["ab": addButton]))
addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:[rb]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["rb": removeButton]))
addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[rb]", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["rb": removeButton]))
}
//MARK: - 按钮点击响应事件
func addButtonClick() {
cellDelegate?.photoSelectorCellAdd(self)
}
func removeButtonClick() {
cellDelegate?.photoSelectorCellRemove(self)
}
//MARK: - 懒加载
lazy var addButton: UIButton = {
let btn = UIButton()
btn.setImage(UIImage(named: "compose_pic_add_highlighted"), forState: UIControlState.Highlighted)
btn.setImage(UIImage(named: "compose_pic_add"), forState: UIControlState.Normal)
//添加点击事件
btn.addTarget(self, action: "addButtonClick", forControlEvents: UIControlEvents.TouchUpInside)
return btn
}()
lazy var removeButton: UIButton = {
let removeBtn = UIButton()
removeBtn.setImage(UIImage(named: "compose_photo_close"), forState: UIControlState.Normal)
removeBtn.addTarget(self, action: "removeButtonClick", forControlEvents: UIControlEvents.TouchUpInside)
removeBtn.hidden = true
return removeBtn
}()
}
| apache-2.0 | c12139d5f46ddd869dfe507dc595be23 | 26.682353 | 173 | 0.612126 | 5.692742 | false | false | false | false |
josipbernat/Hasher | Hasher/View/JBTextView.swift | 1 | 3424 | //
// JBTextView.swift
// Hasher
//
// Created by Josip Bernat on 7/23/15.
// Copyright (c) 2015 Josip Bernat. All rights reserved.
//
import Cocoa
class JBTextView: NSTextView {
typealias TextdDidChangeBlock = (_ text: String?) -> Void
var textChangedBlock: TextdDidChangeBlock?
var placeholder: String = "" {
didSet {
self.setNeedsDisplay(self.bounds)
}
}
let placeholderFont = NSFont.systemFont(ofSize: 15.0)
required init?(coder: NSCoder) {
super.init(coder: coder)
self.drawsBackground = false
self.font = NSFont.systemFont(ofSize: 15.0)
}
override init(frame frameRect: NSRect, textContainer container: NSTextContainer?) {
super.init(frame: frameRect, textContainer:container)
self.drawsBackground = false
self.font = NSFont.systemFont(ofSize: 15.0)
}
//MARK: - Override
override func becomeFirstResponder() -> Bool {
self.needsDisplay = true
return super.becomeFirstResponder()
}
override func resignFirstResponder() -> Bool {
self.needsDisplay = true
return super.resignFirstResponder()
}
override func didChangeText() {
self.textColor = isDarkTheme() ? NSColor.white : NSColor.black
self.needsDisplay = true
super.didChangeText()
if let unwrappedBlock = textChangedBlock {
unwrappedBlock(self.string)
}
}
//MARK: - Drawing
func isDarkTheme() -> Bool {
if #available(OSX 10.14, *) {
return NSAppearance.current.name == .darkAqua || NSAppearance.current.name == .vibrantDark
} else {
// Fallback on earlier versions
return NSAppearance.current.name.rawValue.hasPrefix("NSAppearanceNameVibrantDark")
// return convertFromNSAppearanceName(NSAppearance.current.name).hasPrefix("NSAppearanceNameVibrantDark")
}
}
override func draw(_ dirtyRect: NSRect) {
super.draw(dirtyRect)
NSGraphicsContext.saveGraphicsState()
let hasText = self.string.utf16.count > 0 ? true : false
if placeholder.utf16.count > 0 && hasText == false {
let attributes: [NSAttributedString.Key: Any] = [.foregroundColor: isDarkTheme() ? NSColor.white : NSColor.black,
.font: placeholderFont]
(placeholder as NSString).draw(at: NSMakePoint(6.0, 0.0), withAttributes: attributes)
}
NSGraphicsContext.restoreGraphicsState()
}
}
// Helper function inserted by Swift 4.2 migrator.
//fileprivate func convertFromNSAppearanceName(_ input: NSAppearance.Name) -> String {
// return input.rawValue
//}
// Helper function inserted by Swift 4.2 migrator.
fileprivate func convertFromNSAttributedStringKey(_ input: NSAttributedString.Key) -> String {
return input.rawValue
}
// Helper function inserted by Swift 4.2 migrator.
fileprivate func convertToOptionalNSAttributedStringKeyDictionary(_ input: [String: Any]?) -> [NSAttributedString.Key: Any]? {
guard let input = input else { return nil }
return Dictionary(uniqueKeysWithValues: input.map { key, value in (NSAttributedString.Key(rawValue: key), value)})
}
| mit | fb36cd4c642555069518a2c339a8dc47 | 30.127273 | 126 | 0.624416 | 4.912482 | false | false | false | false |
antonio081014/LeeCode-CodeBase | Swift/bulls-and-cows.swift | 2 | 1187 | /**
* https://leetcode.com/problems/bulls-and-cows/
*
*
*/
// Date: Thu Sep 10 09:48:02 PDT 2020
/// 1. Scan through secret to see what's in it, and count the occurence of each digit.
/// 2. Scan through guess to see if current digit is in secret, if it's in, increase B.
/// Also, if digits at the same index of two strings are identical, then increase A.
class Solution {
/// - Complexity:
/// - Time: O(n + m), n is the length of secret, m is the length of guess.
/// - Space: O(n + m), count takes O(n), and s, g takes O(n) and O(m).
///
func getHint(_ secret: String, _ guess: String) -> String {
var count: [Character : Int] = [:]
let s = Array(secret)
let g = Array(guess)
var A = 0
var B = 0
for index in 0 ..< s.count {
count[s[index]] = count[s[index], default: 0] + 1
}
for index in 0 ..< g.count {
if let value = count[g[index]], value > 0 {
B += 1
count[g[index]] = value - 1
}
if s[index] == g[index] {
A += 1
}
}
return "\(A)A\(B - A)B"
}
}
| mit | 866bcbb6f5f72218e8552b371c30c123 | 32.914286 | 88 | 0.498736 | 3.47076 | false | false | false | false |
easyui/AlamofireImage | Tests/UIImageViewTests.swift | 1 | 26245 | // UIImageViewTests.swift
//
// Copyright (c) 2015-2016 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
@testable import Alamofire
@testable import AlamofireImage
import Foundation
import UIKit
import XCTest
private class TestImageView: UIImageView {
var imageObserver: (Void -> Void)?
convenience init(imageObserver: (Void -> Void)? = nil) {
self.init(frame: CGRectZero)
self.imageObserver = imageObserver
}
override init(frame: CGRect) {
super.init(frame: frame)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override var image: UIImage? {
get {
return super.image
}
set {
super.image = newValue
imageObserver?()
}
}
}
// MARK: -
class UIImageViewTestCase: BaseTestCase {
let URL = NSURL(string: "https://httpbin.org/image/jpeg")!
// MARK: - Setup and Teardown
override func setUp() {
super.setUp()
ImageDownloader.defaultURLCache().removeAllCachedResponses()
ImageDownloader.defaultInstance.imageCache?.removeAllImages()
UIImageView.af_sharedImageDownloader = ImageDownloader.defaultInstance
}
// MARK: - Image Download
func testThatImageCanBeDownloadedFromURL() {
// Given
let expectation = expectationWithDescription("image should download successfully")
var imageDownloadComplete = false
let imageView = TestImageView {
imageDownloadComplete = true
expectation.fulfill()
}
// When
imageView.af_setImageWithURL(URL)
waitForExpectationsWithTimeout(timeout, handler: nil)
// Then
XCTAssertTrue(imageDownloadComplete, "image download complete should be true")
}
func testThatImageDownloadSucceedsWhenDuplicateRequestIsSentToImageView() {
// Given
let expectation = expectationWithDescription("image should download successfully")
var imageDownloadComplete = false
let imageView = TestImageView {
imageDownloadComplete = true
expectation.fulfill()
}
// When
imageView.af_setImageWithURL(URL)
imageView.af_setImageWithURL(URL)
waitForExpectationsWithTimeout(timeout, handler: nil)
// Then
XCTAssertTrue(imageDownloadComplete, "image download complete should be true")
XCTAssertNotNil(imageView.image, "image view image should not be nil")
}
func testThatActiveRequestIsNilAfterImageDownloadCompletes() {
// Given
let expectation = expectationWithDescription("image should download successfully")
var imageDownloadComplete = false
let imageView = TestImageView {
imageDownloadComplete = true
expectation.fulfill()
}
// When
imageView.af_setImageWithURL(URL)
waitForExpectationsWithTimeout(timeout, handler: nil)
// Then
XCTAssertTrue(imageDownloadComplete, "image download complete should be true")
XCTAssertNil(imageView.activeRequestReceipt, "active request receipt should be nil after download completes")
}
// MARK: - Image Downloaders
func testThatImageDownloaderOverridesSharedImageDownloader() {
// Given
let expectation = expectationWithDescription("image should download successfully")
var imageDownloadComplete = false
let imageView = TestImageView {
imageDownloadComplete = true
expectation.fulfill()
}
let configuration = NSURLSessionConfiguration.ephemeralSessionConfiguration()
let imageDownloader = ImageDownloader(configuration: configuration)
imageView.af_imageDownloader = imageDownloader
// When
imageView.af_setImageWithURL(URL)
let activeRequestCount = imageDownloader.activeRequestCount
waitForExpectationsWithTimeout(timeout, handler: nil)
// Then
XCTAssertTrue(imageDownloadComplete, "image download complete should be true")
XCTAssertNil(imageView.activeRequestReceipt, "active request receipt should be nil after download completes")
XCTAssertEqual(activeRequestCount, 1, "active request count should be 1")
}
// MARK: - Image Cache
func testThatImageCanBeLoadedFromImageCacheFromRequestIdentifierIfAvailable() {
// Given
let imageView = UIImageView()
let downloader = ImageDownloader.defaultInstance
let download = URLRequest(.GET, "https://httpbin.org/image/jpeg")
let expectation = expectationWithDescription("image download should succeed")
downloader.downloadImage(URLRequest: download) { _ in
expectation.fulfill()
}
waitForExpectationsWithTimeout(timeout, handler: nil)
// When
imageView.af_setImageWithURL(URL)
imageView.af_cancelImageRequest()
// Then
XCTAssertNotNil(imageView.image, "image view image should not be nil")
}
func testThatImageCanBeLoadedFromImageCacheFromRequestAndFilterIdentifierIfAvailable() {
// Given
let imageView = UIImageView()
let downloader = ImageDownloader.defaultInstance
let download = URLRequest(.GET, "https://httpbin.org/image/jpeg")
let expectation = expectationWithDescription("image download should succeed")
downloader.downloadImage(URLRequest: download, filter: CircleFilter()) { _ in
expectation.fulfill()
}
waitForExpectationsWithTimeout(timeout, handler: nil)
// When
imageView.af_setImageWithURL(URL, filter: CircleFilter())
imageView.af_cancelImageRequest()
// Then
XCTAssertNotNil(imageView.image, "image view image should not be nil")
}
func testThatSharedImageCacheCanBeReplaced() {
// Given
let imageDownloader = ImageDownloader()
// When
let firstEqualityCheck = UIImageView.af_sharedImageDownloader === imageDownloader
UIImageView.af_sharedImageDownloader = imageDownloader
let secondEqualityCheck = UIImageView.af_sharedImageDownloader === imageDownloader
// Then
XCTAssertFalse(firstEqualityCheck, "first equality check should be false")
XCTAssertTrue(secondEqualityCheck, "second equality check should be true")
}
// MARK: - Placeholder Images
func testThatPlaceholderImageIsDisplayedUntilImageIsDownloadedFromURL() {
// Given
let placeholderImage = imageForResource("pirate", withExtension: "jpg")
let expectation = expectationWithDescription("image should download successfully")
var imageDownloadComplete = false
var finalImageEqualsPlaceholderImage = false
let imageView = TestImageView()
// When
imageView.af_setImageWithURL(URL, placeholderImage: placeholderImage)
let initialImageEqualsPlaceholderImage = imageView.image === placeholderImage
imageView.imageObserver = {
imageDownloadComplete = true
finalImageEqualsPlaceholderImage = imageView.image === placeholderImage
expectation.fulfill()
}
waitForExpectationsWithTimeout(timeout, handler: nil)
// Then
XCTAssertTrue(imageDownloadComplete, "image download complete should be true")
XCTAssertTrue(initialImageEqualsPlaceholderImage, "initial image should equal placeholder image")
XCTAssertFalse(finalImageEqualsPlaceholderImage, "final image should not equal placeholder image")
}
func testThatPlaceholderIsNeverDisplayedIfCachedImageIsAvailable() {
// Given
let placeholderImage = imageForResource("pirate", withExtension: "jpg")
let imageView = UIImageView()
let downloader = ImageDownloader.defaultInstance
let download = URLRequest(.GET, "https://httpbin.org/image/jpeg")
let expectation = expectationWithDescription("image download should succeed")
downloader.downloadImage(URLRequest: download) { _ in
expectation.fulfill()
}
waitForExpectationsWithTimeout(timeout, handler: nil)
// When
imageView.af_setImageWithURL(URL, placeholderImage: placeholderImage)
// Then
XCTAssertNotNil(imageView.image, "image view image should not be nil")
XCTAssertFalse(imageView.image === placeholderImage, "image view should not equal placeholder image")
}
// MARK: - Image Filters
func testThatImageFilterCanBeAppliedToDownloadedImageBeforeBeingDisplayed() {
// Given
let size = CGSize(width: 20, height: 20)
let filter = ScaledToSizeFilter(size: size)
let expectation = expectationWithDescription("image download should succeed")
var imageDownloadComplete = false
let imageView = TestImageView {
imageDownloadComplete = true
expectation.fulfill()
}
// When
imageView.af_setImageWithURL(URL, filter: filter)
waitForExpectationsWithTimeout(timeout, handler: nil)
// Then
XCTAssertTrue(imageDownloadComplete, "image download complete should be true")
XCTAssertNotNil(imageView.image, "image view image should not be nil")
if let image = imageView.image {
XCTAssertEqual(image.size, size, "image size does not match expected value")
}
}
// MARK: - Image Transitions
func testThatImageTransitionIsAppliedAfterImageDownloadIsComplete() {
// Given
let expectation = expectationWithDescription("image download should succeed")
var imageDownloadComplete = false
let imageView = TestImageView {
imageDownloadComplete = true
expectation.fulfill()
}
// When
imageView.af_setImageWithURL(URL, placeholderImage: nil, filter: nil, imageTransition: .CrossDissolve(0.5))
waitForExpectationsWithTimeout(timeout, handler: nil)
// Then
XCTAssertTrue(imageDownloadComplete, "image download complete should be true")
XCTAssertNotNil(imageView.image, "image view image should not be nil")
}
func testThatAllImageTransitionsCanBeApplied() {
// Given
let imageView = TestImageView()
var imageTransitionsComplete = false
// When
let expectation1 = expectationWithDescription("image download should succeed")
imageView.imageObserver = { expectation1.fulfill() }
imageView.af_setImageWithURL(URL, imageTransition: .None)
waitForExpectationsWithTimeout(timeout, handler: nil)
let expectation2 = expectationWithDescription("image download should succeed")
imageView.imageObserver = { expectation2.fulfill() }
ImageDownloader.defaultInstance.imageCache?.removeAllImages()
imageView.af_setImageWithURL(URL, imageTransition: .CrossDissolve(0.1))
waitForExpectationsWithTimeout(timeout, handler: nil)
let expectation3 = expectationWithDescription("image download should succeed")
imageView.imageObserver = { expectation3.fulfill() }
ImageDownloader.defaultInstance.imageCache?.removeAllImages()
imageView.af_setImageWithURL(URL, imageTransition: .CurlDown(0.1))
waitForExpectationsWithTimeout(timeout, handler: nil)
let expectation4 = expectationWithDescription("image download should succeed")
imageView.imageObserver = { expectation4.fulfill() }
ImageDownloader.defaultInstance.imageCache?.removeAllImages()
imageView.af_setImageWithURL(URL, imageTransition: .CurlUp(0.1))
waitForExpectationsWithTimeout(timeout, handler: nil)
let expectation5 = expectationWithDescription("image download should succeed")
imageView.imageObserver = { expectation5.fulfill() }
ImageDownloader.defaultInstance.imageCache?.removeAllImages()
imageView.af_setImageWithURL(URL, imageTransition: .FlipFromBottom(0.1))
waitForExpectationsWithTimeout(timeout, handler: nil)
let expectation6 = expectationWithDescription("image download should succeed")
imageView.imageObserver = { expectation6.fulfill() }
ImageDownloader.defaultInstance.imageCache?.removeAllImages()
imageView.af_setImageWithURL(URL, imageTransition: .FlipFromLeft(0.1))
waitForExpectationsWithTimeout(timeout, handler: nil)
let expectation7 = expectationWithDescription("image download should succeed")
imageView.imageObserver = { expectation7.fulfill() }
ImageDownloader.defaultInstance.imageCache?.removeAllImages()
imageView.af_setImageWithURL(URL, imageTransition: .FlipFromRight(0.1))
waitForExpectationsWithTimeout(timeout, handler: nil)
let expectation8 = expectationWithDescription("image download should succeed")
imageView.imageObserver = {
expectation8.fulfill()
}
ImageDownloader.defaultInstance.imageCache?.removeAllImages()
imageView.af_setImageWithURL(URL, imageTransition: .FlipFromTop(0.1))
waitForExpectationsWithTimeout(timeout, handler: nil)
let expectation9 = expectationWithDescription("image download should succeed")
imageView.imageObserver = {
imageTransitionsComplete = true
expectation9.fulfill()
}
ImageDownloader.defaultInstance.imageCache?.removeAllImages()
imageView.af_setImageWithURL(
URL,
imageTransition: .Custom(
duration: 0.5,
animationOptions: UIViewAnimationOptions(),
animations: { $0.image = $1 },
completion: nil
)
)
waitForExpectationsWithTimeout(timeout, handler: nil)
// Then
XCTAssertTrue(imageTransitionsComplete, "image transitions complete should be true")
XCTAssertNotNil(imageView.image, "image view image should not be nil")
}
// MARK: - Completion Handler
func testThatCompletionHandlerIsCalledWhenImageDownloadSucceeds() {
// Given
let imageView = UIImageView()
let URLRequest: NSURLRequest = {
let request = NSMutableURLRequest(URL: URL)
request.addValue("image/*", forHTTPHeaderField: "Accept")
return request
}()
let expectation = expectationWithDescription("image download should succeed")
var completionHandlerCalled = false
var result: Result<UIImage, NSError>?
// When
imageView.af_setImageWithURLRequest(
URLRequest,
placeholderImage: nil,
filter: nil,
imageTransition: .None,
completion: { closureResponse in
completionHandlerCalled = true
result = closureResponse.result
expectation.fulfill()
}
)
waitForExpectationsWithTimeout(timeout, handler: nil)
// Then
XCTAssertTrue(completionHandlerCalled, "completion handler called should be true")
XCTAssertNotNil(imageView.image, "image view image should be not be nil when completion handler is not nil")
XCTAssertTrue(result?.isSuccess ?? false, "result should be a success case")
}
func testThatCompletionHandlerIsCalledWhenImageDownloadFails() {
// Given
let imageView = UIImageView()
let URLRequest = NSURLRequest(URL: NSURL(string: "domain-name-does-not-exist")!)
let expectation = expectationWithDescription("image download should succeed")
var completionHandlerCalled = false
var result: Result<UIImage, NSError>?
// When
imageView.af_setImageWithURLRequest(
URLRequest,
placeholderImage: nil,
filter: nil,
imageTransition: .None,
completion: { closureResponse in
completionHandlerCalled = true
result = closureResponse.result
expectation.fulfill()
}
)
waitForExpectationsWithTimeout(timeout, handler: nil)
// Then
XCTAssertTrue(completionHandlerCalled, "completion handler called should be true")
XCTAssertNil(imageView.image, "image view image should be nil when completion handler is not nil")
XCTAssertTrue(result?.isFailure ?? false, "result should be a failure case")
}
func testThatCompletionHandlerAndCustomTransitionHandlerAreBothCalled() {
// Given
let imageView = UIImageView()
let completionExpectation = expectationWithDescription("image download should succeed")
let transitionExpectation = expectationWithDescription("image transition should complete")
var completionHandlerCalled = false
var transitionCompletionHandlerCalled = false
var result: Result<UIImage, NSError>?
// When
imageView.af_setImageWithURL(
URL,
placeholderImage: nil,
filter: nil,
imageTransition: .Custom(
duration: 0.1,
animationOptions: UIViewAnimationOptions(),
animations: { $0.image = $1 },
completion: { _ in
transitionCompletionHandlerCalled = true
transitionExpectation.fulfill()
}
),
completion: { closureResponse in
completionHandlerCalled = true
result = closureResponse.result
completionExpectation.fulfill()
}
)
waitForExpectationsWithTimeout(timeout, handler: nil)
// Then
XCTAssertTrue(completionHandlerCalled, "completion handler called should be true")
XCTAssertTrue(transitionCompletionHandlerCalled, "transition completion handler called should be true")
XCTAssertNotNil(imageView.image, "image view image should be not be nil when completion handler is not nil")
XCTAssertTrue(result?.isSuccess ?? false, "result should be a success case")
}
func testThatImageIsSetWhenReturnedFromCacheAndCompletionHandlerSet() {
// Given
let imageView = UIImageView()
let URLRequest: NSURLRequest = {
let request = NSMutableURLRequest(URL: URL)
request.addValue("image/*", forHTTPHeaderField: "Accept")
return request
}()
let downloadExpectation = expectationWithDescription("image download should succeed")
// When
UIImageView.af_sharedImageDownloader.downloadImage(URLRequest: URLRequest) { _ in
downloadExpectation.fulfill()
}
waitForExpectationsWithTimeout(timeout, handler: nil)
let cachedExpectation = expectationWithDescription("image should be cached")
var result: Result<UIImage, NSError>?
imageView.af_setImageWithURLRequest(
URLRequest,
placeholderImage: nil,
filter: nil,
imageTransition: .None,
completion: { closureResponse in
result = closureResponse.result
cachedExpectation.fulfill()
}
)
waitForExpectationsWithTimeout(timeout, handler: nil)
// Then
XCTAssertNotNil(result?.value, "result value should not be nil")
XCTAssertEqual(result?.value, imageView.image, "result value should be equal to image view image")
}
// MARK: - Cancellation
func testThatImageDownloadCanBeCancelled() {
// Given
let imageView = UIImageView()
let URLRequest = NSURLRequest(URL: NSURL(string: "domain-name-does-not-exist")!)
let expectation = expectationWithDescription("image download should succeed")
var completionHandlerCalled = false
var result: Result<UIImage, NSError>?
// When
imageView.af_setImageWithURLRequest(
URLRequest,
placeholderImage: nil,
filter: nil,
imageTransition: .None,
completion: { closureResponse in
completionHandlerCalled = true
result = closureResponse.result
expectation.fulfill()
}
)
imageView.af_cancelImageRequest()
waitForExpectationsWithTimeout(timeout, handler: nil)
// Then
XCTAssertTrue(completionHandlerCalled, "completion handler called should be true")
XCTAssertNil(imageView.image, "image view image should be nil when completion handler is not nil")
XCTAssertTrue(result?.isFailure ?? false, "result should be a failure case")
}
func testThatActiveRequestIsAutomaticallyCancelledBySettingNewURL() {
// Given
let imageView = UIImageView()
let expectation = expectationWithDescription("image download should succeed")
var completion1Called = false
var completion2Called = false
var result: Result<UIImage, NSError>?
// When
imageView.af_setImageWithURLRequest(
NSURLRequest(URL: URL),
placeholderImage: nil,
filter: nil,
imageTransition: .None,
completion: { _ in
completion1Called = true
}
)
imageView.af_setImageWithURLRequest(
NSURLRequest(URL: NSURL(string: "https://httpbin.org/image/png")!),
placeholderImage: nil,
filter: nil,
imageTransition: .None,
completion: { closureResponse in
completion2Called = true
result = closureResponse.result
expectation.fulfill()
}
)
waitForExpectationsWithTimeout(timeout, handler: nil)
// Then
XCTAssertTrue(completion1Called, "completion 1 called should be true")
XCTAssertTrue(completion2Called, "completion 2 called should be true")
XCTAssertNotNil(imageView.image, "image view image should not be nil when completion handler is not nil")
XCTAssertTrue(result?.isSuccess ?? false, "result should be a success case")
}
func testThatActiveRequestCanBeCancelledAndRestartedSuccessfully() {
// Given
let imageView = UIImageView()
let expectation = expectationWithDescription("image download should succeed")
var completion1Called = false
var completion2Called = false
var result: Result<UIImage, NSError>?
// When
imageView.af_setImageWithURLRequest(
NSURLRequest(URL: URL),
placeholderImage: nil,
filter: nil,
imageTransition: .None,
completion: { _ in
completion1Called = true
}
)
imageView.af_cancelImageRequest()
imageView.af_setImageWithURLRequest(
NSURLRequest(URL: URL),
placeholderImage: nil,
filter: nil,
imageTransition: .None,
completion: { closureResponse in
completion2Called = true
result = closureResponse.result
expectation.fulfill()
}
)
waitForExpectationsWithTimeout(timeout, handler: nil)
// Then
XCTAssertTrue(completion1Called, "completion 1 called should be true")
XCTAssertTrue(completion2Called, "completion 2 called should be true")
XCTAssertNotNil(imageView.image, "image view image should not be nil when completion handler is not nil")
XCTAssertTrue(result?.isSuccess ?? false, "result should be a success case")
}
// MARK: - Redirects
func testThatImageBehindRedirectCanBeDownloaded() {
// Given
let redirectURLString = "https://httpbin.org/image/png"
let URL = NSURL(string: "https://httpbin.org/redirect-to?url=\(redirectURLString)")!
let expectation = expectationWithDescription("image should download successfully")
var imageDownloadComplete = false
let imageView = TestImageView {
imageDownloadComplete = true
expectation.fulfill()
}
// When
imageView.af_setImageWithURL(URL)
waitForExpectationsWithTimeout(timeout, handler: nil)
// Then
XCTAssertTrue(imageDownloadComplete, "image download complete should be true")
XCTAssertNotNil(imageView.image, "image view image should not be nil")
}
// MARK: - Accept Header
func testThatAcceptHeaderMatchesAcceptableContentTypes() {
// Given
let imageView = UIImageView()
// When
imageView.af_setImageWithURL(URL)
let acceptField = imageView.activeRequestReceipt?.request.request?.allHTTPHeaderFields?["Accept"]
imageView.af_cancelImageRequest()
// Then
XCTAssertNotNil(acceptField)
if let acceptField = acceptField {
XCTAssertEqual(acceptField, Request.acceptableImageContentTypes.joinWithSeparator(","))
}
}
}
| mit | 6c25cd8c792acd7b228afe89fb43efd8 | 36.069209 | 117 | 0.665079 | 5.84391 | false | true | false | false |
t2421/iOS-snipet | iOS-snipets/samples/FontDescriptorViewControllerController.swift | 1 | 2385 | //
// FontDescriptorViewController.swift
// iOS-snipets
//
// Created by taigakiyotaki on 2015/07/21.
// Copyright (c) 2015年 taigakiyotaki. All rights reserved.
//
import UIKit
class FontDescriptorViewController: UIViewController {
var helveticaNeueFamily:UIFontDescriptor!;
var label:UILabel!;
var fontSize:CGFloat = 10.0;
var timer:NSTimer!;
var useFontDescriptor:UIFontDescriptor!;
override func viewDidLoad() {
super.viewDidLoad()
timer = NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: Selector("loop"), userInfo: nil, repeats: true)
label = UILabel();
label.frame.origin.x = 20;
label.frame.origin.y = 200;
label.text = fontSize.description;
self.view.addSubview(label);
helveticaNeueFamily = UIFontDescriptor(fontAttributes: [UIFontDescriptorFamilyAttribute:"Helvetica Neue"])
helveticaNeueFamily = helveticaNeueFamily.fontDescriptorWithSize(fontSize)
helveticaNeueFamily = helveticaNeueFamily.fontDescriptorWithSymbolicTraits(UIFontDescriptorSymbolicTraits.TraitBold);
//sizeに0.0以外を入れるとそちらのサイズがdescriptorに設定されているサイズより優先される。
let helveticaBoldFont = UIFont(descriptor: helveticaNeueFamily, size: 0.0);
label.font = helveticaBoldFont;
label.sizeToFit();
timer.fire();
}
func loop(){
fontSize += 1.0;
helveticaNeueFamily = helveticaNeueFamily.fontDescriptorWithSize(fontSize);
let helveticaBoldFont = UIFont(descriptor: helveticaNeueFamily, size: 0.0);
label.font = helveticaBoldFont;
label.text = fontSize.description;
label.sizeToFit();
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func viewDidDisappear(animated: Bool) {
timer.invalidate();
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit | fc6212ae5b3785c0b21b2cc11b032579 | 31.125 | 131 | 0.677475 | 4.849057 | false | false | false | false |
1000copy/fin | Controller/NodeTopicListViewController.swift | 1 | 6646 | import UIKit
class NodeTopicListViewController: UIViewController {
fileprivate weak var _loadView:V2LoadingView?
func showLoadingView (){
self._loadView = V2LoadingView(view)
}
func hideLoadingView() {
self._loadView?.hideLoadingView()
}
var node:NodeModel?
var favorited:Bool = false
var favoriteUrl:String? {
didSet{
// print(favoriteUrl)
// let startIndex = favoriteUrl?.range(of: "/", options: .backwards, range: nil, locale: nil)
// let endIndex = favoriteUrl?.range(of: "?")
// let nodeId = favoriteUrl?.substring(with: Range<String.Index>( startIndex!.upperBound ..< endIndex!.lowerBound ))
// if let _ = nodeId , let favoriteUrl = favoriteUrl {
// favorited = !favoriteUrl.hasPrefix("/favorite")
// followButton.refreshButtonImage()
// }
favorited = isFavorite(favoriteUrl)
followButton.refreshButtonImage()
}
}
func isFavorite(_ favoriteUrl:String?) -> Bool{
let startIndex = favoriteUrl?.range(of: "/", options: .backwards, range: nil, locale: nil)
let endIndex = favoriteUrl?.range(of: "?")
let nodeId = favoriteUrl?.substring(with: Range<String.Index>( startIndex!.upperBound ..< endIndex!.lowerBound ))
if let _ = nodeId , let favoriteUrl = favoriteUrl {
return !favoriteUrl.hasPrefix("/favorite")
}
return false
}
var followButton:FollowButton!
fileprivate var _tableView :NodeTable!
fileprivate var tableView: NodeTable {
get{
if(_tableView != nil){
return _tableView!;
}
_tableView = NodeTable();
return _tableView!
}
}
override func viewDidLoad() {
super.viewDidLoad()
if self.node?.nodeId == nil {
return;
}
followButton = FollowButton(frame:CGRect(x: 0, y: 0, width: 26, height: 26))
followButton.nodeId = node?.nodeId
let followItem = UIBarButtonItem(customView: followButton)
//处理间距
let fixedSpaceItem = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil, action: nil)
fixedSpaceItem.width = -5
self.navigationItem.rightBarButtonItems = [fixedSpaceItem,followItem]
self.title = self.node?.nodeName
self.view.backgroundColor = V2EXColor.colors.v2_backgroundColor
self.view.addSubview(self.tableView);
self.tableView.snp.makeConstraints{ (make) -> Void in
make.top.right.bottom.left.equalTo(self.view);
}
self.showLoadingView()
self.tableView.scrollUp = refresh
self.tableView.scrollDown = getNextPage
self.tableView.beginScrollUp()
}
var currentPage = 1
func refresh(_ cb : @escaping Callback){
TopicListModelHTTP.getTopicList(self.node!.nodeId!, page: 1){
[weak self](response:V2ValueResponse<([TopicListModel],String?)>) -> Void in
if response.success {
self?._tableView.topicList = response.value?.0
self?.favoriteUrl = response.value?.1
self?.tableView.reloadData()
}
self?.hideLoadingView()
cb()
}
}
func getNextPage(_ cb : @escaping CallbackMore){
if let count = self.tableView.topicList?.count, count <= 0{
return;
}
self.currentPage += 1
TopicListModelHTTP.getTopicList(self.node!.nodeId!, page: self.currentPage){
[weak self](response:V2ValueResponse<([TopicListModel],String?)>) -> Void in
if response.success {
if let weakSelf = self , let value = response.value {
weakSelf.tableView.topicList! += value.0
weakSelf.tableView.reloadData()
}
else{
self?.currentPage -= 1
}
}
cb(true)
}
}
}
fileprivate class NodeTable : TableBase{
fileprivate var topicList:Array<TopicListModel>?
var currentPage = 1
override init(frame: CGRect, style: UITableViewStyle) {
super.init(frame: frame, style: style)
backgroundColor = V2EXColor.colors.v2_backgroundColor
separatorStyle = .none
regClass(self, cell: HomeTopicListTableViewCell.self)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override fileprivate func rowCount(_ section: Int) -> Int {
if let list = self.topicList {
return list.count;
}
return 0;
}
override fileprivate func rowHeight(_ indexPath: IndexPath) -> CGFloat {
let item = self.topicList![indexPath.row]
let titleHeight = item.getHeight() ?? 0
// 上间隔 头像高度 头像下间隔 标题高度 标题下间隔 cell间隔
let height = 12 + 35 + 12 + titleHeight + 12 + 8
return height
}
override fileprivate func cellAt(_ indexPath: IndexPath) -> UITableViewCell {
let cell = getCell(self, cell: HomeTopicListTableViewCell.self, indexPath: indexPath);
cell.bindNodeModel(self.topicList![indexPath.row]);
return cell;
}
override fileprivate func didSelectRowAt(_ indexPath: IndexPath) {
let item = self.topicList![indexPath.row]
if let id = item.topicId {
Msg.send("openTopicDetail1", [id])
self.deselectRow(at: indexPath, animated: true)
}
}
}
class FollowButton : ButtonBase{
override init(frame: CGRect) {
super.init(frame: frame)
tap = toggleFavoriteState
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
var favorited:Bool = false
var nodeId:String?
func refreshButtonImage() {
let followImage = self.favorited == true ? UIImage(named: "ic_favorite")! : UIImage(named: "ic_favorite_border")!
self.setImage(followImage.withRenderingMode(.alwaysTemplate), for: UIControlState())
}
func toggleFavoriteState(){
if(self.favorited){
TopicListModelHTTP.favorite(self.nodeId!, type: 0)
self.favorited = false
V2Success("取消收藏了~")
}
else{
TopicListModelHTTP.favorite(self.nodeId!, type: 1)
self.favorited = true
V2Success("收藏成功")
}
refreshButtonImage()
}
}
| mit | 366b6feaaa176c881496f5d643e8f723 | 37 | 127 | 0.594615 | 4.597203 | false | false | false | false |
sathishkraj/Reachability | Reachability/Reachability.swift | 1 | 7673 | //
// Reachability.swift
// Reachability
//
// Copyright (c) 2015 Sathish Kumar
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
import SystemConfiguration
import Foundation
enum NetworkStatus: Int {
case NotReachable = 0
case ReachableViaWiFi
case ReachableViaWWAN
}
enum ReachabilityType: String {
case hostReachability = "host"
case internetReachability = "internet"
case wifiReachability = "wifi"
}
let kReachabilityChangedNotification = "kNetworkReachabilityChangedNotification"
var kShouldPrintReachabilityFlags: Bool {
return true
}
func PrintReachabilityFlags(flags: SCNetworkReachabilityFlags, comment: NSString) {
guard kShouldPrintReachabilityFlags else {
return
}
print("Reachability Flag Status: %@%@ %@%@%@%@%@%@%@ %@\n",
(flags == .IsWWAN) ? "W" : "-",
(flags == .Reachable) ? "R" : "-",
(flags == .TransientConnection) ? "t" : "-",
(flags == .ConnectionRequired) ? "c" : "-",
(flags == .ConnectionOnTraffic) ? "C" : "-",
(flags == .InterventionRequired) ? "i" : "-",
(flags == .ConnectionOnDemand) ? "D" : "-",
(flags == .IsLocalAddress) ? "l" : "-",
(flags == .IsDirect) ? "d" : "-",
comment
)
}
func ReachabilityCallback(target: SCNetworkReachability, flags: SCNetworkReachabilityFlags, info: UnsafeMutablePointer<Void>) {
NSNotificationCenter.defaultCenter().postNotificationName(kReachabilityChangedNotification, object: nil)
}
class Reachability {
var alwaysReturnLocalWiFiStatus = false
var reachabilityRef: SCNetworkReachabilityRef? = nil
var reachabilityType: ReachabilityType!
class func reachabilityWithHostName(hostName: String) -> Reachability? {
guard let networkReachability = SCNetworkReachabilityCreateWithName(nil, hostName) else {
return nil
}
let reachability = Reachability()
reachability.reachabilityRef = networkReachability
reachability.alwaysReturnLocalWiFiStatus = false
return reachability
}
class func reachabilityWithAddress(hostAddress: UnsafePointer<sockaddr_in>) -> Reachability? {
guard let networkReachability = SCNetworkReachabilityCreateWithAddress(kCFAllocatorDefault, UnsafePointer<sockaddr>(hostAddress)) else {
return nil
}
let reachability = Reachability()
reachability.reachabilityRef = networkReachability
reachability.alwaysReturnLocalWiFiStatus = false
return reachability
}
class func reachabilityForInternetConnection() -> Reachability? {
var zeroAddress: sockaddr_in = sockaddr_in()
bzero(&zeroAddress, sizeofValue(zeroAddress))
zeroAddress.sin_len = __uint8_t(sizeofValue(zeroAddress))
zeroAddress.sin_family = sa_family_t(AF_INET)
return reachabilityWithAddress(&zeroAddress)
}
class func reachabilityForLocalWiFi() -> Reachability? {
var localWifiAddress: sockaddr_in = sockaddr_in()
bzero(&localWifiAddress, sizeofValue(localWifiAddress))
localWifiAddress.sin_len = __uint8_t(sizeofValue(localWifiAddress))
localWifiAddress.sin_family = sa_family_t(AF_INET)
localWifiAddress.sin_addr.s_addr = __uint32_t(0xA9FE0000)
guard let reachability = reachabilityWithAddress(&localWifiAddress) else {
return nil
}
reachability.alwaysReturnLocalWiFiStatus = true
return reachability
}
func startNotifier() -> (Bool) {
var context = SCNetworkReachabilityContext()
context.version = 0
context.info = UnsafeMutablePointer<Void>(Unmanaged<NSString>.passRetained(reachabilityType.rawValue).toOpaque())
guard let reachabilityRef = reachabilityRef where SCNetworkReachabilitySetCallback(reachabilityRef, ReachabilityCallback, &context) else {
return false
}
return SCNetworkReachabilityScheduleWithRunLoop(reachabilityRef, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode)
}
func stopNotifier() {
guard let reachabilityRef = reachabilityRef else {
return
}
SCNetworkReachabilityUnscheduleFromRunLoop(reachabilityRef, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode)
}
func localWiFiStatusForFlags(flags: SCNetworkReachabilityFlags) -> NetworkStatus {
PrintReachabilityFlags(flags, comment: "localWiFiStatusForFlags")
guard flags == .Reachable && flags == .IsDirect else {
return .NotReachable
}
return .ReachableViaWiFi
}
func networkStatusForFlags(flags: SCNetworkReachabilityFlags) -> NetworkStatus {
PrintReachabilityFlags(flags, comment: "networkStatusForFlags")
if flags.rawValue & SCNetworkReachabilityFlags.Reachable.rawValue == 0 {
// The target host is not reachable.
return .NotReachable
}
var returnValue: NetworkStatus = .NotReachable
if (flags.rawValue & SCNetworkReachabilityFlags.ConnectionRequired.rawValue) == 0 {
/*
If the target host is reachable and no connection is required then we'll assume (for now) that you're on Wi-Fi...
*/
returnValue = .ReachableViaWiFi
}
if ((((flags.rawValue & SCNetworkReachabilityFlags.ConnectionOnDemand.rawValue) != 0) || (flags.rawValue & SCNetworkReachabilityFlags.ConnectionOnTraffic.rawValue) != 0)) {
/*
... and the connection is on-demand (or on-traffic) if the calling application is using the CFSocketStream or higher APIs...
*/
if ((flags.rawValue & SCNetworkReachabilityFlags.InterventionRequired.rawValue) == 0) {
/*
... and no [user] intervention is needed...
*/
returnValue = .ReachableViaWiFi
}
}
if ((flags.rawValue & SCNetworkReachabilityFlags.IsWWAN.rawValue) == SCNetworkReachabilityFlags.IsWWAN.rawValue) {
/*
... but WWAN connections are OK if the calling application is using the CFNetwork APIs.
*/
returnValue = .ReachableViaWWAN
}
return returnValue
}
func connectionRequired() -> Bool {
var flags = SCNetworkReachabilityFlags()
guard let reachabilityRef = reachabilityRef where (SCNetworkReachabilityGetFlags(reachabilityRef, &flags)) else {
return false
}
return (flags.rawValue & SCNetworkReachabilityFlags.ConnectionRequired.rawValue) == 1 ? true : false
}
func currentReachabilityStatus() -> NetworkStatus {
var flags = SCNetworkReachabilityFlags()
guard let reachabilityRef = reachabilityRef where (SCNetworkReachabilityGetFlags(reachabilityRef, &flags)) else {
return .NotReachable
}
guard alwaysReturnLocalWiFiStatus else {
return localWiFiStatusForFlags(flags)
}
return networkStatusForFlags(flags)
}
}
| mit | b75bf761f40272926cfb172d416b8174 | 37.365 | 176 | 0.71706 | 5.101729 | false | false | false | false |
hironytic/Moltonf-iOS | Moltonf/Utility/RxCocoaComplement.swift | 1 | 2330 | //
// RxCocoaComplement.swift
// Moltonf
//
// Copyright (c) 2016 Hironori Ichimiya <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import UIKit
import RxSwift
import RxCocoa
extension Reactive where Base: UITableView {
public func modelDeleted<T>(_ modelType: T.Type) -> ControlEvent<T> {
let source: Observable<T> = self.itemDeleted.flatMap { [weak view = self.base as UITableView] indexPath -> Observable<T> in
guard let view = view else {
return Observable.empty()
}
return Observable.just(try view.rx.model(at: indexPath))
}
return ControlEvent(events: source)
}
}
extension Reactive where Base: UIBarButtonItem {
/**
Bindable sink for `title` property.
*/
public var title: AnyObserver<String?> {
return UIBindingObserver(UIElement: self.base) { UIElement, title in
UIElement.title = title
}.asObserver()
}
}
extension Reactive where Base: UILabel {
/**
Bindable sink for `title` property.
*/
public var textColor: AnyObserver<UIColor> {
return UIBindingObserver(UIElement: self.base) { UIElement, textColor in
UIElement.textColor = textColor
}.asObserver()
}
}
| mit | 8058d2df55ef953ff106687a7dbb387e | 35.40625 | 131 | 0.692704 | 4.641434 | false | false | false | false |
ycaihua/codecombat-ios | CodeCombat/ParticleView.swift | 1 | 1472 | //
// ParticleView.swift
// iPadClient
//
// Created by Michael Schmatz on 7/29/14.
// Copyright (c) 2014 CodeCombat. All rights reserved.
//
import UIKit
import SpriteKit
class ParticleView: SKView {
var particleScene:SKScene?
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
startParticles()
}
override init(frame: CGRect) {
super.init(frame: frame)
// Initialization code
startParticles()
}
func startParticles() {
self.showsFPS = false
self.showsNodeCount = false
self.allowsTransparency = true
particleScene = ParticleScene(size: self.bounds.size)
particleScene!.scaleMode = SKSceneScaleMode.AspectFill
particleScene!.backgroundColor = UIColor.clearColor()
self.presentScene(particleScene!)
}
override func removeFromSuperview() {
self.scene?.removeAllChildren()
super.removeFromSuperview()
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func drawRect(rect: CGRect)
{
// Drawing code
}
*/
override func hitTest(point: CGPoint, withEvent event: UIEvent!) -> UIView? {
let hitView:UIView = super.hitTest(point, withEvent: event)!
if hitView == self {
return nil
}
return hitView
}
}
| mit | bc4298e554b36f21593f69c64c35116f | 23.533333 | 81 | 0.633152 | 4.687898 | false | false | false | false |
madeatsampa/MacMagazine-iOS | MacMagazine/Webview/YouTubePlayer.swift | 2 | 1651 | //
// YouTubePlayer.swift
// MacMagazine
//
// Created by Cassio Rossi on 14/04/2019.
// Copyright © 2019 MacMagazine. All rights reserved.
//
import UIKit
import WebKit
class YouTubePlayer: WKWebView {
// MARK: - Properties -
var embedVideoHtml: String {
return """
<!DOCTYPE html><html>
<style>body,html,iframe{margin:0;padding:0;}</style>
<body><div id="player"></div>
<script>
var meta = document.createElement('meta');
meta.setAttribute('name', 'viewport');
meta.setAttribute('content', 'width=device-width');
document.getElementsByTagName('head')[0].appendChild(meta);
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
playerVars: { 'playsinline': 0, 'controls': 1, 'fs': 1 },
height: '\(self.frame.height)',
width: '\(self.frame.width)',
videoId: '\(videoId ?? "")',
events: { 'onReady': onPlayerReady, 'onStateChange': videoPaused }
});
}
function onPlayerReady(event) { event.target.playVideo(); }
function videoPaused(event) {
if (event.data == YT.PlayerState.PAUSED) {
window.webkit.messageHandlers.videoPaused.postMessage(event.data);
}
}
</script>
</body></html>
"""
}
var videoId: String? {
didSet {
guard let _ = videoId else {
return
}
delay(0.4) {
self.loadHTMLString(self.embedVideoHtml, baseURL: nil)
}
}
}
func play() {
self.evaluateJavaScript("player.playVideo()")
}
}
| mit | e66b582e00a843a413a636e9973d4fe3 | 24 | 68 | 0.670909 | 3.210117 | false | false | false | false |
tad-iizuka/swift-sdk | Source/PersonalityInsightsV3/Models/Profile.swift | 2 | 2819 | /**
* Copyright IBM Corporation 2016
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
import Foundation
import RestKit
/** A personality profile generated by the Personality Insights service. */
public struct Profile: JSONDecodable {
/// The number of words found in the input.
public let wordCount: Int
/// The language model used to process the input.
public let processedLanguage: String
/// Recursive array of characteristics describing the Big Five dimensions
/// inferred from the input text.
public let personality: [TraitTreeNode]
/// Array of characteristics describing thneeds of the input text.
public let needs: [TraitTreeNode]
/// Array of characteristics describing values of the input text.
public let values: [TraitTreeNode]
/// Array of behaviors describing values of the input text that is returned
/// only for timestamped JSON input.
public let behavior: [BehaviorNode]?
/// Detailed results for each category of consumption preferences.
public let consumptionPreferences: [ConsumptionPreferencesCategoryNode]?
/// Array of warning messages generated from the input text.
public let warnings: [Warning]
/// A message indicating the number of words found and where the value falls
/// in the range of required or suggested number of words when guidance is
/// available.
public let wordCountMessage: String?
/// Used internally to initialize a `Profile` model from JSON.
public init(json: JSON) throws {
wordCount = try json.getInt(at: "word_count")
processedLanguage = try json.getString(at: "processed_language")
personality = try json.decodedArray(at: "personality", type: TraitTreeNode.self)
needs = try json.decodedArray(at: "needs", type: TraitTreeNode.self)
values = try json.decodedArray(at: "values", type: TraitTreeNode.self)
behavior = try? json.decodedArray(at: "behavior", type: BehaviorNode.self)
consumptionPreferences = try? json.decodedArray(at: "consumption_preferences", type: ConsumptionPreferencesCategoryNode.self)
warnings = try json.decodedArray(at: "warnings", type: Warning.self)
wordCountMessage = try? json.getString(at: "word_count_message")
}
}
| apache-2.0 | 90e3432d9cad226ca95bd0021c2b0598 | 41.712121 | 133 | 0.715857 | 4.636513 | false | false | false | false |
onevcat/CotEditor | CotEditor/Sources/TextSizeTouchBar.swift | 1 | 4669 | //
// TextSizeTouchBar.swift
//
// CotEditor
// https://coteditor.com
//
// Created by 1024jp on 2016-11-14.
//
// ---------------------------------------------------------------------------
//
// © 2016-2021 1024jp
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Combine
import Cocoa
private extension NSTouchBarItem.Identifier {
static let textSizeActual = NSTouchBarItem.Identifier("com.coteditor.CotEditor.TouchBarItem.textSizeActual")
static let textSizeSlider = NSTouchBarItem.Identifier("com.coteditor.CotEditor.TouchBarItem.textSizeSlider")
}
final class TextSizeTouchBar: NSTouchBar, NSTouchBarDelegate, NSUserInterfaceValidations {
// MARK: Private Properties
private weak var textView: NSTextView?
private var scaleObserver: AnyCancellable?
// MARK: -
// MARK: Lifecycle
init(textView: NSTextView, forPressAndHold: Bool = false) {
self.textView = textView
super.init()
NSTouchBar.isAutomaticValidationEnabled = true
self.delegate = self
self.defaultItemIdentifiers = forPressAndHold ? [.textSizeSlider] : [.textSizeActual, .textSizeSlider]
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: Touch Bar Delegate
func touchBar(_ touchBar: NSTouchBar, makeItemForIdentifier identifier: NSTouchBarItem.Identifier) -> NSTouchBarItem? {
switch identifier {
case .textSizeActual:
let item = NSCustomTouchBarItem(identifier: identifier)
item.view = NSButton(title: "Actual Size".localized, target: self, action: #selector(resetTextSize))
return item
case .textSizeSlider:
guard let textView = self.textView else { return nil }
let item = NSSliderTouchBarItem(identifier: identifier)
item.target = self
item.action = #selector(textSizeSliderChanged)
item.doubleValue = textView.scale
item.slider.maxValue = Double(textView.enclosingScrollView?.maxMagnification ?? 5.0)
item.slider.minValue = Double(textView.enclosingScrollView?.minMagnification ?? 0.2)
let minimumValueImage = NSImage(systemSymbolName: "a", accessibilityDescription: "Smaller".localized)!
.withSymbolConfiguration(.init(scale: .small))!
item.minimumValueAccessory = NSSliderAccessory(image: minimumValueImage)
let maximumValueImage = NSImage(systemSymbolName: "a", accessibilityDescription: "larger".localized)!
item.maximumValueAccessory = NSSliderAccessory(image: maximumValueImage)
item.maximumSliderWidth = 300
// observe scale
self.scaleObserver = textView.publisher(for: \.scale)
.filter { _ in item.isVisible }
.map { Double($0) }
.assign(to: \.doubleValue, on: item)
return item
default:
return nil
}
}
// MARK: User Interface Validations
func validateUserInterfaceItem(_ item: NSValidatedUserInterfaceItem) -> Bool {
switch item.action {
case #selector(resetTextSize):
return (self.textView?.scale != 1.0)
case nil:
return false
default:
return true
}
}
// MARK: Action Messages
/// text size slider was moved
@IBAction func textSizeSliderChanged(_ sliderItem: NSSliderTouchBarItem) {
let scale = sliderItem.doubleValue
self.textView?.setScaleKeepingVisibleArea(scale)
}
/// "Actaul Size" button was touched
@IBAction func resetTextSize(_ sender: Any?) {
self.textView?.setScaleKeepingVisibleArea(1.0)
}
}
| apache-2.0 | 2238f46e65508e62443d22bea679833b | 31.643357 | 123 | 0.600686 | 5.262683 | false | false | false | false |
pennlabs/penn-mobile-ios | PennMobile/GSR-Booking/Views/RoomCell.swift | 1 | 4385 | //
// RoomCell.swift
// GSR
//
// Created by Yagil Burowski on 17/09/2016.
// Copyright © 2016 Yagil Burowski. All rights reserved.
//
import UIKit
protocol GSRSelectionDelegate {
func handleSelection(for id: Int)
}
class RoomCell: UITableViewCell {
static let cellHeight: CGFloat = 90
static let identifier = "roomCell"
var room: GSRRoom! {
didSet {
collectionView.dataSource = self
collectionView.reloadData()
}
}
var delegate: GSRSelectionDelegate!
fileprivate lazy var collectionView: UICollectionView = {
let layout = UICollectionViewFlowLayout()
layout.scrollDirection = .horizontal
layout.minimumLineSpacing = 8
let cv = UICollectionView(frame: .zero, collectionViewLayout: layout)
cv.register(GSRTimeCell.self, forCellWithReuseIdentifier: GSRTimeCell.identifier)
cv.backgroundColor = .clear
cv.showsHorizontalScrollIndicator = false
cv.delegate = self
cv.allowsMultipleSelection = true
return cv
}()
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.selectionStyle = .none
addSubview(collectionView)
_ = collectionView.anchor(topAnchor, left: leftAnchor, bottom: bottomAnchor, right: rightAnchor, topConstant: 0, leftConstant: 6, bottomConstant: 0, rightConstant: 0, widthConstant: 0, heightConstant: 0)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func resetSelection() {
collectionView.indexPathsForSelectedItems?.forEach { collectionView.deselectItem(at: $0, animated: true) }
}
func getSelectTimes() -> [GSRTimeSlot] {
(collectionView.indexPathsForSelectedItems ?? []).map({
return room.availability[$0.item]
})
}
}
extension RoomCell: UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return room.availability.count
}
func collectionView(_ collectionView: UICollectionView,
cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: GSRTimeCell.identifier, for: indexPath) as! GSRTimeCell
let timeSlot = room.availability[indexPath.row]
cell.timeSlot = timeSlot
cell.backgroundColor = timeSlot.isAvailable ? UIColor.baseGreen : UIColor.labelSecondary
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let size = RoomCell.cellHeight - 12
return CGSize(width: size, height: size)
}
// only enable selection for available rooms
func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool {
let timeSlot = room.availability[indexPath.row]
return timeSlot.isAvailable
}
// Deselect this time slot and all select ones that follow it
func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
let cell = collectionView.cellForItem(at: indexPath)
cell?.backgroundColor = UIColor.baseGreen
collectionView.indexPathsForSelectedItems?.forEach {
if $0.item > indexPath.item {
collectionView.deselectItem(at: $0, animated: true)
collectionView.reloadItems(at: [$0])
}
}
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
delegate.handleSelection(for: room.id)
let indexPaths = (collectionView.indexPathsForSelectedItems ?? []).sorted(by: {$0.item < $1.item})
for i in 1..<indexPaths.count where
indexPaths[i].item - indexPaths[i-1].item != 1 {
let deselectIndexPath = indexPaths.filter({ $0 != indexPath })
deselectIndexPath.forEach({ collectionView.deselectItem(at: $0, animated: true)})
collectionView.reloadItems(at: deselectIndexPath)
return
}
}
}
| mit | 9156f42ea215aaea557bee902302bc82 | 37.121739 | 211 | 0.684535 | 5.256595 | false | false | false | false |
brightdigit/swiftver | Sources/SwiftVer/Hash.swift | 1 | 822 | import Foundation
/**
Hash struct used for VersionControlInfo.
*/
public struct Hash: CustomStringConvertible, Equatable, Hashable {
/**
The Data of the Hash.
*/
public let data: Data
/**
Creates a Hash object based on a string.
*/
public init?(string: String) {
guard let data = Data(hexString: string) else {
return nil
}
self.data = data
}
/**
Formats the data into a hex **String**.
*/
public var description: String {
return data.map { String(format: "%02x", $0) }.joined(separator: "")
}
/**
Hash value for equality.
*/
public func hash(into hasher: inout Hasher) {
hasher.combine(data)
}
/**
Equality comparison of Hash objects.
*/
public static func == (lhs: Hash, rhs: Hash) -> Bool {
return lhs.data == rhs.data
}
}
| mit | e67685d3e4014823ee2b8450b6b1224a | 18.116279 | 72 | 0.614355 | 3.877358 | false | false | false | false |
335g/Mattress | Sources/Repetition.swift | 1 | 3639 |
import Runes
extension Parser {
public var many: Parser<C, [T]> {
return prepend <^> self <*> delay{ self.many } <|> .pure([])
}
public var some: Parser<C, [T]> {
return prepend <^> self <*> self.many
}
}
public func many<C, T>(_ parser: Parser<C, T>) -> Parser<C, [T]> {
return parser.many
}
public func some<C, T>(_ parser: Parser<C, T>) -> Parser<C, [T]> {
return parser.some
}
extension Int {
public func times<C, T>(_ parser: Parser<C, T>) -> Parser<C, [T]> {
precondition(self >= 0)
return self != 0
? prepend <^> parser <*> delay{ (self - 1).times(parser) }
: .pure([])
}
func decrement() -> Int {
return self == Int.max
? Int.max
: self - 1
}
}
public func * <C, T>(parser: Parser<C, T>, n: Int) -> Parser<C, [T]> {
return n.times(parser)
}
extension CountableClosedRange where Bound == Int {
private func decrement() -> CountableClosedRange {
return CountableClosedRange(uncheckedBounds: (lowerBound.decrement(), upperBound.decrement()))
}
public func times<C, T>(_ parser: Parser<C, T>) -> Parser<C, [T]> {
precondition(upperBound >= 0)
return upperBound == 0
? Parser<C, [T]>{ _, index, _, ifSuccess in try ifSuccess([], index) }
: (parser >>- { append($0) <^> (self.decrement().times(parser)) })
<|> Parser<C, [T]> { _, index, ifFailure, ifSuccess in
return self.lowerBound <= 0
? try ifSuccess([], index)
: try ifFailure(ParsingError(at: index, becauseOf: "At least one must be matched."))
}
}
}
public func * <C, T>(parser: Parser<C, T>, interval: CountableClosedRange<Int>) -> Parser<C, [T]> {
return interval.times(parser)
}
extension CountableRange where Bound == Int {
private func decrement() -> CountableRange {
return CountableRange(uncheckedBounds: (lowerBound.decrement(), upperBound.decrement()))
}
public func times<C, T>(_ parser: Parser<C, T>) -> Parser<C, [T]> {
precondition(upperBound >= 1)
return upperBound == 1
? Parser<C, [T]> { _, index, _, ifSuccess in try ifSuccess([], index) }
: (parser >>- { append($0) <^> (self.decrement().times(parser)) })
<|> Parser<C, [T]> { _, index, ifFailure, ifSuccess in
return self.lowerBound <= 0
? try ifSuccess([], index)
: try ifFailure(ParsingError(at: index, becauseOf: "At least one must be matched."))
}
}
}
public func * <C, T>(parser: Parser<C, T>, interval: CountableRange<Int>) -> Parser<C, [T]> {
return interval.times(parser)
}
// MARK: - sep, end
extension Parser {
public func isSeparatedByAtLeastOne<U>(by separator: Parser<C, U>) -> Parser<C, [T]> {
return prepend <^> self <*> Mattress.many(separator *> self)
}
public func isSeparated<U>(by separator: Parser<C, U>) -> Parser<C, [T]> {
return self.isSeparatedByAtLeastOne(by: separator) <|> .pure([])
}
public func isTerminatedByAtLeastOne<U>(by terminator: Parser<C, U>) -> Parser<C, [T]> {
return (self <* terminator).some
}
public func isTerminated<U>(by terminator: Parser<C, U>) -> Parser<C, [T]> {
return (self <* terminator).many
}
}
public func sep<C, T, U>(by separator: Parser<C, U>, parser: Parser<C, T>) -> Parser<C, [T]> {
return parser.isSeparated(by: separator)
}
public func sep1<C, T, U>(by separator: Parser<C, U>, parser: Parser<C, T>) -> Parser<C, [T]> {
return parser.isSeparatedByAtLeastOne(by: separator)
}
public func end<C, T, U>(by terminator: Parser<C, U>, parser: Parser<C, T>) -> Parser<C, [T]> {
return parser.isTerminated(by: terminator)
}
public func end1<C, T, U>(by terminator: Parser<C, U>, parser: Parser<C, T>) -> Parser<C, [T]> {
return parser.isTerminatedByAtLeastOne(by: terminator)
}
| mit | 7701b970ddb08487a4b15657878d7599 | 28.827869 | 99 | 0.630393 | 3.137069 | false | false | false | false |
PigDogBay/Food-Hygiene-Ratings | Food Hygiene Ratings/DummyDataProvider.swift | 1 | 1363 | //
// DummyDataProvider.swift
// Food Hygiene Ratings
//
// Created by Mark Bailey on 21/02/2017.
// Copyright © 2017 MPD Bailey Technology. All rights reserved.
//
import Foundation
class DummyDataProvider : IDataProvider {
var model : MainModel!
//Stoke
// let latitude = 52.984120
// let longitude = -2.204094
//Glasgow
let latitude = 55.857455
let longitude = -4.248
func findLocalEstablishments() {
self.model.changeState(.locating)
model.location = Coordinate(longitude: longitude, latitude: latitude)
self.model.changeState(.foundLocation)
fetchEstablishments(query : Query(longitude: longitude, latitude: latitude, radiusInMiles: 1))
}
func fetchEstablishments(query : Query){
self.model.changeState(.loading)
let url = Bundle.main.url(forResource: "glasgow", withExtension: "json")
let data = try! Data(contentsOf: url!)
let estResult = FoodHygieneAPI.establishments(fromJSON: data)
switch estResult {
case let .success(results):
self.model.setResults(establishments: results)
self.model.changeState(.loaded)
case let .failure(error):
self.model.error = error
self.model.changeState(.error)
}
}
func stop(){
}
}
| apache-2.0 | e28b319f7184f82b80627a2f3ec8cf0b | 26.24 | 102 | 0.63069 | 4.216718 | false | false | false | false |
Monte9/MoviesDBApp-CodePathU | Project1-FlickM/AppDelegate.swift | 2 | 6193 | //
// AppDelegate.swift
// Project1-FlickM
//
// Created by Monte's Pro 13" on 1/16/16.
// Copyright © 2016 MonteThakkar. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
UIApplication.sharedApplication().statusBarStyle = .LightContent
// UIApplication.sharedApplication().statusBarStyle = UIStatusBarStyle.LightContent
window = UIWindow(frame: UIScreen.mainScreen().bounds)
let storyboard = UIStoryboard(name: "Main", bundle: nil)
//Now Playing tab bar button 1
let nowPlayingNavigationController = storyboard.instantiateViewControllerWithIdentifier("MoviesNavigationController") as! UINavigationController
let nowPlayingViewController = nowPlayingNavigationController.topViewController as! CollectionViewController
nowPlayingViewController.endPoint = "now_playing"
nowPlayingNavigationController.tabBarItem.title = "Now Playing"
nowPlayingNavigationController.tabBarItem.image = UIImage(named: "nowPlaying")
//Customize Now Playing navigation bar UI
nowPlayingNavigationController.navigationBar.barTintColor = UIColor.blackColor()
nowPlayingNavigationController.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.redColor()]
nowPlayingNavigationController.navigationBar.topItem?.title = "Now Playing"
//Top Rated tab bar button 2
let topRatedNavigationController = storyboard.instantiateViewControllerWithIdentifier("MoviesNavigationController") as! UINavigationController
let topRatedViewController = topRatedNavigationController.topViewController as! CollectionViewController
topRatedViewController.endPoint = "top_rated"
topRatedNavigationController.tabBarItem.title = "Top Rated"
topRatedNavigationController.tabBarItem.image = UIImage(named: "topRated")
//Customize Top Rated navigation bar UI
topRatedNavigationController.navigationBar.barTintColor = UIColor.blackColor()
topRatedNavigationController.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.redColor()]
topRatedNavigationController.navigationBar.topItem?.title = "Top Rated"
//Popular tab bar button 3
let popularNavigationController = storyboard.instantiateViewControllerWithIdentifier("MoviesNavigationController") as! UINavigationController
let popularViewController = popularNavigationController.topViewController as! CollectionViewController
popularViewController.endPoint = "popular"
popularNavigationController.tabBarItem.title = "Popular"
popularNavigationController.tabBarItem.image = UIImage(named: "popular")
//Customize Popular navigation bar UI
popularNavigationController.navigationBar.barTintColor = UIColor.blackColor()
popularNavigationController.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.redColor()]
popularNavigationController.navigationBar.topItem?.title = "Popular"
//Upcoming tab bar button 4
let genreNavigationController = storyboard.instantiateViewControllerWithIdentifier("GenreNavigationController") as! UINavigationController
let genreViewController = genreNavigationController.topViewController as! GenreViewController
// upcomingViewController.endPoint = "upcoming"
genreNavigationController.tabBarItem.title = "Genres"
genreNavigationController.tabBarItem.image = UIImage(named: "genreTabBar")
//Customize Upcoming navigation bar UI
genreNavigationController.navigationBar.barTintColor = UIColor.blackColor()
genreNavigationController.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.redColor()]
genreNavigationController.navigationBar.topItem?.title = "Browse Genres"
//Upcoming tab bar button 4
let upcomingNavigationController = storyboard.instantiateViewControllerWithIdentifier("MoviesNavigationController") as! UINavigationController
let upcomingViewController = upcomingNavigationController.topViewController as! CollectionViewController
upcomingViewController.endPoint = "upcoming"
upcomingNavigationController.tabBarItem.title = "Upcoming"
upcomingNavigationController.tabBarItem.image = UIImage(named: "upcoming")
//Customize Upcoming navigation bar UI
upcomingNavigationController.navigationBar.barTintColor = UIColor.blackColor()
upcomingNavigationController.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.redColor()]
upcomingNavigationController.navigationBar.topItem?.title = "Upcoming"
//setup tabbar controller - add tab bar buttons
let tabBarController = UITabBarController()
tabBarController.viewControllers = [topRatedNavigationController, popularNavigationController, genreNavigationController, nowPlayingNavigationController, upcomingNavigationController]
UITabBar.appearance().tintColor = UIColor.redColor()
UITabBar.appearance().barTintColor = UIColor.blackColor()
window?.rootViewController = tabBarController
window?.makeKeyAndVisible()
return true
}
func applicationWillResignActive(application: UIApplication) {
}
func applicationDidEnterBackground(application: UIApplication) {
}
func applicationWillEnterForeground(application: UIApplication) {
}
func applicationDidBecomeActive(application: UIApplication) {
}
func applicationWillTerminate(application: UIApplication) {
}
}
| mit | 552e47d85f304b9b0b8b2ee7440b656b | 43.228571 | 191 | 0.728844 | 7.020408 | false | false | false | false |
siberianisaev/NeutronBarrel | NeutronBarrel/Processor.swift | 1 | 54881 | //
// Processor.swift
// NeutronBarrel
//
// Created by Andrey Isaev on 26/04/2017.
// Copyright © 2018 Flerov Laboratory. All rights reserved.
//
import Foundation
import Cocoa
extension Event {
func getChannelFor(type: SearchType) -> CUnsignedShort {
return (type == .fission || type == .heavy) ? (param2 & Mask.heavyOrFission.rawValue) : (param3 & Mask.recoilOrAlpha.rawValue)
}
func getMarker() -> CUnsignedShort {
return param3 >> 13
}
}
protocol ProcessorDelegate: AnyObject {
func startProcessingFile(_ name: String?)
func endProcessingFile(_ name: String?, correlationsFound: CUnsignedLongLong)
}
enum TOFUnits {
case channels
case nanoseconds
}
class Processor {
fileprivate var neutronsPerAct = NeutronsMatch()
fileprivate var neutronsMultiplicity: NeutronsMultiplicity?
fileprivate var specialPerAct = [Int: CUnsignedShort]()
fileprivate var beamStatePerAct = BeamState()
fileprivate var fissionsAlphaPerAct = DoubleSidedStripDetectorMatch()
fileprivate var fissionsAlphaNextPerAct = [Int: DoubleSidedStripDetectorMatch]()
fileprivate var lastFissionAlphaNextPerAct: DoubleSidedStripDetectorMatch? {
return fissionsAlphaNextPerAct[criteria.nextMaxIndex() ?? -1]
}
fileprivate var currentEventTime: CUnsignedLongLong {
return (criteria.searchExtraFromLastParticle ? lastFissionAlphaNextPerAct : firstParticlePerAct)?.currentEventTime ?? 0
}
fileprivate var recoilsPerAct = DoubleSidedStripDetectorMatch()
fileprivate var firstParticlePerAct: DoubleSidedStripDetectorMatch {
return criteria.startFromRecoil() ? recoilsPerAct : fissionsAlphaPerAct
}
fileprivate var fissionsAlphaWellPerAct = DoubleSidedStripDetectorMatch()
fileprivate var vetoPerAct = DetectorMatch()
fileprivate var stoped = false
fileprivate var logger: Logger!
fileprivate var resultsTable: ResultsTable!
fileprivate var calibration: Calibration {
return Calibration.singleton
}
fileprivate func stripsConfiguration(detector: StripDetector) -> StripsConfiguration {
return StripDetectorManager.singleton.getStripConfigurations(detector)
}
fileprivate var dataProtocol: DataProtocol! {
return DataLoader.singleton.dataProtocol
}
fileprivate var files: [String] {
return DataLoader.singleton.files
}
var filesFinishedCount: Int = 0
fileprivate var file: UnsafeMutablePointer<FILE>!
fileprivate var currentFileName: String?
fileprivate var currentCycle: CUnsignedLongLong = 0
fileprivate var totalEventNumber: CUnsignedLongLong = 0
fileprivate var correlationsPerFile: CUnsignedLongLong = 0
fileprivate var criteria = SearchCriteria()
fileprivate weak var delegate: ProcessorDelegate?
init(criteria: SearchCriteria, delegate: ProcessorDelegate) {
self.criteria = criteria
self.delegate = delegate
}
func stop() {
stoped = true
}
func processDataWith(completion: @escaping (()->())) {
stoped = false
processData()
DispatchQueue.main.async {
completion()
}
}
// MARK: - Algorithms
enum SearchDirection {
case forward, backward
}
fileprivate func forwardSearch(checker: @escaping ((Event, UnsafeMutablePointer<Bool>)->())) {
while feof(file) != 1 {
var event = Event()
fread(&event, Event.size, 1, file)
var stop: Bool = false
checker(event, &stop)
if stop {
return
}
}
}
fileprivate func search(directions: Set<SearchDirection>, startTime: CUnsignedLongLong, minDeltaTime: CUnsignedLongLong, maxDeltaTime: CUnsignedLongLong, maxDeltaTimeBackward: CUnsignedLongLong? = nil, checkMaxDeltaTimeExceeded: Bool = true, useCycleTime: Bool, updateCycle: Bool, checker: @escaping ((Event, CUnsignedLongLong, CLongLong, UnsafeMutablePointer<Bool>, Int)->())) {
//TODO: search over many files
let maxBackward = maxDeltaTimeBackward ?? maxDeltaTime
if directions.contains(.backward) {
var initial = fpos_t()
fgetpos(file, &initial)
var cycle = currentCycle
var current = Int(initial)
while current > -1 {
let size = Event.size
current -= size
fseek(file, current, SEEK_SET)
var event = Event()
fread(&event, size, 1, file)
let id = Int(event.eventId)
if dataProtocol.isCycleTimeEvent(id) {
if cycle > 0 {
cycle -= 1
} else {
print("Backward search time broken!")
}
continue
}
if dataProtocol.isValidEventIdForTimeCheck(id) {
let relativeTime = event.param1
let time = useCycleTime ? absTime(relativeTime, cycle: cycle) : CUnsignedLongLong(relativeTime)
let deltaTime = (time < startTime) ? (startTime - time) : (time - startTime)
if deltaTime <= maxBackward {
if deltaTime < minDeltaTime {
continue
}
var stop: Bool = false
checker(event, time, -(CLongLong)(deltaTime), &stop, current)
if stop {
return
}
} else {
break
}
}
}
fseek(file, Int(initial), SEEK_SET)
}
if directions.contains(.forward) {
var cycle = currentCycle
while feof(file) != 1 {
var event = Event()
fread(&event, Event.size, 1, file)
let id = Int(event.eventId)
if dataProtocol.isCycleTimeEvent(id) {
if updateCycle {
currentCycle += 1
}
cycle += 1
continue
}
if dataProtocol.isValidEventIdForTimeCheck(id) {
let relativeTime = event.param1
let time = useCycleTime ? absTime(relativeTime, cycle: cycle) : CUnsignedLongLong(relativeTime)
let deltaTime = (time < startTime) ? (startTime - time) : (time - startTime)
if !checkMaxDeltaTimeExceeded || deltaTime <= maxDeltaTime {
if deltaTime < minDeltaTime {
continue
}
var stop: Bool = false
var current = fpos_t()
fgetpos(file, ¤t)
checker(event, time, CLongLong(deltaTime), &stop, Int(current))
if stop {
return
}
} else {
return
}
}
}
}
}
// MARK: - Search
fileprivate func showNoDataAlert() {
DispatchQueue.main.async {
let alert = NSAlert()
alert.messageText = "Error"
alert.informativeText = "Please select some data files to start analysis!"
alert.addButton(withTitle: "OK")
alert.alertStyle = .warning
alert.runModal()
}
}
fileprivate func processData() {
if 0 == files.count {
showNoDataAlert()
return
}
neutronsMultiplicity = NeutronsMultiplicity(efficiency: criteria.neutronsDetectorEfficiency, efficiencyError: criteria.neutronsDetectorEfficiencyError, placedSFSource: criteria.placedSFSource)
totalEventNumber = 0
clearActInfo()
logger = Logger(folder: criteria.resultsFolderName)
logger.logSettings()
logInput(onEnd: false)
logCalibration()
resultsTable = ResultsTable(criteria: criteria, logger: logger, delegate: self)
resultsTable.logResultsHeader()
resultsTable.logGammaHeader()
var folders = [String: FolderStatistics]()
for fp in files {
let path = fp as NSString
let folderName = FolderStatistics.folderNameFromPath(fp) ?? ""
var folder = folders[folderName]
if nil == folder {
folder = FolderStatistics(folderName: folderName)
folders[folderName] = folder
}
folder!.startFile(fp)
autoreleasepool {
file = fopen(path.utf8String, "rb")
currentFileName = path.lastPathComponent
DispatchQueue.main.async { [weak self] in
self?.delegate?.startProcessingFile(self?.currentFileName)
}
if let file = file {
setvbuf(file, nil, _IONBF, 0)
forwardSearch(checker: { [weak self] (event: Event, stop: UnsafeMutablePointer<Bool>) in
autoreleasepool {
if let file = self?.file, let currentFileName = self?.currentFileName, let stoped = self?.stoped {
if ferror(file) != 0 {
print("\nError while reading file \(currentFileName)\n")
exit(-1)
}
if stoped {
stop.initialize(to: true)
}
}
self?.mainCycleEventCheck(event, folder: folder!)
}
})
} else {
exit(-1)
}
totalEventNumber += Processor.calculateTotalEventNumberForFile(file)
fclose(file)
folder!.endFile(fp, secondsFromFirstFileStart: TimeInterval(absTime(0, cycle: currentCycle)) * 1e-6, correlationsPerFile: correlationsPerFile)
filesFinishedCount += 1
DispatchQueue.main.async { [weak self] in
self?.delegate?.endProcessingFile(self?.currentFileName, correlationsFound: self?.correlationsPerFile ?? 0)
self?.correlationsPerFile = 0
}
}
}
logInput(onEnd: true)
logger.logStatistics(folders)
if criteria.searchNeutrons, let multiplicity = neutronsMultiplicity {
logger.log(multiplicity: multiplicity)
}
DispatchQueue.main.async {
print("\nDone!\nTotal time took: \((NSApplication.shared.delegate as! AppDelegate).timeTook())")
}
}
class func calculateTotalEventNumberForFile(_ file: UnsafeMutablePointer<FILE>!) -> CUnsignedLongLong {
fseek(file, 0, SEEK_END)
var lastNumber = fpos_t()
fgetpos(file, &lastNumber)
return CUnsignedLongLong(lastNumber)/CUnsignedLongLong(Event.size)
}
fileprivate var currentPosition: Int {
var p = fpos_t()
fgetpos(file, &p)
let position = Int(p)
return position
}
fileprivate func mainCycleEventCheck(_ event: Event, folder: FolderStatistics) {
if dataProtocol.isCycleTimeEvent(Int(event.eventId)) {
currentCycle += 1
} else if isFront(event, type: criteria.startParticleType) {
firstParticlePerAct.currentEventTime = UInt64(event.param1)
if (criteria.inBeamOnly && !isInBeam(event)) || (criteria.overflowOnly && !isOverflow(event)) {
clearActInfo()
return
}
var gamma: DetectorMatch?
let isRecoilSearch = criteria.startFromRecoil()
if isRecoilSearch {
if !validateRecoil(event, deltaTime: 0) {
clearActInfo()
return
}
} else { // FFron or AFron
let energy = getEnergy(event, type: criteria.startParticleType)
if energy < criteria.fissionAlphaFrontMinEnergy || energy > criteria.fissionAlphaFrontMaxEnergy {
clearActInfo()
return
}
if !criteria.searchExtraFromLastParticle {
gamma = findGamma(currentPosition)
if criteria.requiredGamma && nil == gamma {
clearActInfo()
return
}
}
storeFissionAlphaFront(event, deltaTime: 0, subMatches: [.gamma: gamma])
}
let position = currentPosition
if criteria.searchVETO {
findVETO()
fseek(file, position, SEEK_SET)
if criteria.requiredVETO && 0 == vetoPerAct.count {
clearActInfo()
return
}
}
if !isRecoilSearch {
findFissionAlphaBack()
fseek(file, position, SEEK_SET)
if criteria.requiredFissionAlphaBack && 0 == fissionsAlphaPerAct.matchFor(side: .back).count {
clearActInfo()
return
}
// Search them only after search all FBack/ABack
findRecoil()
fseek(file, position, SEEK_SET)
if criteria.requiredRecoil && 0 == recoilsPerAct.matchFor(side: .front).count {
clearActInfo()
return
}
if !criteria.searchExtraFromLastParticle {
findFissionAlphaWell(position)
if wellSearchFailed() {
clearActInfo()
return
}
}
}
if criteria.next[2] != nil {
findFissionAlpha(2)
fseek(file, position, SEEK_SET)
guard let match = fissionsAlphaNextPerAct[2], match.matchFor(side: .front).count > 0 else {
clearActInfo()
return
}
if criteria.next[3] != nil {
findFissionAlpha(3)
fseek(file, position, SEEK_SET)
guard let match = fissionsAlphaNextPerAct[3], match.matchFor(side: .front).count > 0 else {
clearActInfo()
return
}
if criteria.next[4] != nil {
findFissionAlpha(4)
fseek(file, position, SEEK_SET)
guard let match = fissionsAlphaNextPerAct[4], match.matchFor(side: .front).count > 0 else {
clearActInfo()
return
}
}
}
if criteria.searchExtraFromLastParticle && wellSearchFailed() {
clearActInfo()
return
}
}
if !criteria.startFromRecoil() && criteria.requiredGammaOrWell && gamma == nil && fissionsAlphaWellPerAct.matchFor(side: .front).count == 0 {
clearActInfo()
return
}
if !criteria.searchExtraFromLastParticle {
if findNeutrons(position) {
clearActInfo()
return
}
}
if criteria.searchSpecialEvents {
findSpecialEvents()
fseek(file, position, SEEK_SET)
}
if criteria.trackBeamState {
findBeamEvents()
}
fseek(file, position, SEEK_SET)
// Important: this search must be last because we don't do file repositioning here
// Sum(FFron or AFron)
if !isRecoilSearch && criteria.summarizeFissionsAlphaFront {
findAllFirstFissionsAlphaFront(folder)
}
if criteria.searchNeutrons {
neutronsMultiplicity?.increment(multiplicity: neutronsPerAct.count)
}
correlationsPerFile += 1
resultsTable.logActResults()
for b in [false, true] {
resultsTable.logGamma(GeOnly: b)
}
clearActInfo()
} else {
updateFolderStatistics(event, folder: folder)
}
}
fileprivate func wellSearchFailed() -> Bool {
return criteria.searchWell && criteria.requiredWell && fissionsAlphaWellPerAct.matchFor(side: .front).count == 0
}
fileprivate func updateFolderStatistics(_ event: Event, folder: FolderStatistics) {
let id = Int(event.eventId)
if dataProtocol.isBeamEnergy(id) {
let e = event.getFloatValue()
folder.handleEnergy(e)
} else if dataProtocol.isBeamIntegral(id) {
folder.handleIntergal(event)
} else if dataProtocol.isBeamCurrent(id) {
let c = event.getFloatValue()
folder.handleCurrent(c)
}
}
fileprivate func findFissionAlphaWell(_ position: Int) {
if criteria.searchWell {
let directions: Set<SearchDirection> = [.backward, .forward]
search(directions: directions, startTime: currentEventTime, minDeltaTime: 0, maxDeltaTime: criteria.fissionAlphaMaxTime, maxDeltaTimeBackward: criteria.fissionAlphaWellBackwardMaxTime, useCycleTime: false, updateCycle: false) { (event: Event, time: CUnsignedLongLong, deltaTime: CLongLong, stop: UnsafeMutablePointer<Bool>, _) in
for side in [.front, .back] as [StripsSide] {
if self.isFissionOrAlphaWell(event, side: side) {
self.filterAndStoreFissionAlphaWell(event, side: side)
}
}
}
fseek(file, position, SEEK_SET)
}
}
fileprivate func checkIsSimultaneousDecay(_ event: Event, deltaTime: CLongLong) -> Bool {
if criteria.simultaneousDecaysFilterForNeutrons && isBack(event, type: criteria.startParticleBackType) && abs(deltaTime) > criteria.fissionAlphaMaxTime {
let energy = getEnergy(event, type: criteria.startParticleBackType)
if energy >= criteria.fissionAlphaBackMinEnergy && energy <= criteria.fissionAlphaBackMaxEnergy {
return true
}
}
return false
}
fileprivate func findNeutrons(_ position: Int) -> Bool {
var excludeSFEvent: Bool = false
if criteria.searchNeutrons {
let directions: Set<SearchDirection> = [.forward, .backward]
let startTime = currentEventTime
let maxDeltaTime = criteria.maxNeutronTime
let checkMaxDeltaTimeExceeded = !criteria.mixingTimesFilterForNeutrons
search(directions: directions, startTime: startTime, minDeltaTime: criteria.minNeutronTime, maxDeltaTime: maxDeltaTime, maxDeltaTimeBackward: criteria.maxNeutronBackwardTime, checkMaxDeltaTimeExceeded:checkMaxDeltaTimeExceeded, useCycleTime: false, updateCycle: false) { (event: Event, time: CUnsignedLongLong, deltaTime: CLongLong, stop: UnsafeMutablePointer<Bool>, _) in
let id = Int(event.eventId)
// 1) Simultaneous Decays Filter - search the events with fragment energy at the same time with current decay.
if self.checkIsSimultaneousDecay(event, deltaTime: deltaTime) {
excludeSFEvent = true
self.neutronsMultiplicity?.incrementBroken()
stop.initialize(to: true)
} else if abs(deltaTime) < maxDeltaTime {
// 3) Store neutron info.
if self.dataProtocol.isNeutronsNewEvent(id) {
let neutronTime = CUnsignedLongLong(event.param1)
let isNeutronsBkg = self.criteria.neutronsBackground
if (!isNeutronsBkg && neutronTime >= startTime) || (isNeutronsBkg && neutronTime < startTime) { // Effect neutrons must be after SF by time
self.neutronsPerAct.times.append(Float(deltaTime))
var encoder = self.dataProtocol.encoderForEventId(id) // 1-4
var channel = event.param3 & Mask.neutronsNew.rawValue // 0-31
// Convert to encoder 1-8 and strip 0-15 format
self.neutronsPerAct.encoders.append(encoder)
encoder *= 2
if channel > 15 {
channel -= 16
} else {
encoder -= 1
}
let counterNumber = self.stripsConfiguration(detector: .neutron).strip1_N_For(side: .front, encoder: Int(encoder), strip0_15: channel)
self.neutronsPerAct.counters.append(counterNumber)
}
} else if self.dataProtocol.isNeutronsOldEvent(id) {
let t = Float(event.param3 & Mask.neutronsOld.rawValue)
self.neutronsPerAct.times.append(t)
}
if self.dataProtocol.hasNeutrons_N() && self.dataProtocol.isNeutrons_N_Event(id) {
self.neutronsPerAct.NSum += 1
}
} else if !checkMaxDeltaTimeExceeded && !self.dataProtocol.isNeutronsNewEvent(id) {
// 2) The Mixing Neutrons Times Filter. We don't check time for neutrons only. It's necessary to stop the search from this checker if delta-time is exceeded for other events.
stop.initialize(to: true)
}
}
fseek(file, Int(position), SEEK_SET)
}
return excludeSFEvent
}
fileprivate func findAllFirstFissionsAlphaFront(_ folder: FolderStatistics) {
var initial = fpos_t()
fgetpos(file, &initial)
var current = initial
let directions: Set<SearchDirection> = [.forward, .backward]
search(directions: directions, startTime: firstParticlePerAct.currentEventTime, minDeltaTime: 0, maxDeltaTime: criteria.fissionAlphaMaxTime, useCycleTime: false, updateCycle: true) { (event: Event, time: CUnsignedLongLong, deltaTime: CLongLong, stop: UnsafeMutablePointer<Bool>, position: Int) in
// File-position check is used for skip Fission/Alpha First event!
fgetpos(self.file, ¤t)
if current != initial && self.isFront(event, type: self.criteria.startParticleType) && self.isFissionStripNearToFirstFissionFront(event) {
self.storeFissionAlphaFront(event, deltaTime: deltaTime, subMatches: nil)
} else {
self.updateFolderStatistics(event, folder: folder)
}
}
}
fileprivate func findVETO() {
let directions: Set<SearchDirection> = [.forward, .backward]
search(directions: directions, startTime: firstParticlePerAct.currentEventTime, minDeltaTime: 0, maxDeltaTime: criteria.maxVETOTime, useCycleTime: false, updateCycle: false) { (event: Event, time: CUnsignedLongLong, deltaTime: CLongLong, stop: UnsafeMutablePointer<Bool>, _) in
if self.dataProtocol.isVETOEvent(Int(event.eventId)) {
self.storeVETO(event, deltaTime: deltaTime)
}
}
}
fileprivate func findGamma(_ position: Int) -> DetectorMatch? {
let match = DetectorMatch()
let directions: Set<SearchDirection> = [.forward, .backward]
search(directions: directions, startTime: currentEventTime, minDeltaTime: 0, maxDeltaTime: criteria.maxGammaTime, maxDeltaTimeBackward: criteria.maxGammaBackwardTime, useCycleTime: false, updateCycle: false) { (event: Event, time: CUnsignedLongLong, deltaTime: CLongLong, stop: UnsafeMutablePointer<Bool>, _) in
if self.isGammaEvent(event), let item = self.gammaMatchItem(event, deltaTime: deltaTime) {
match.append(item)
}
}
fseek(file, position, SEEK_SET)
return match.count > 0 ? match : nil
}
fileprivate func findFissionAlphaBack() {
let match = fissionsAlphaPerAct
let type = criteria.startParticleBackType
let directions: Set<SearchDirection> = [.backward, .forward]
let byFact = self.criteria.searchFissionAlphaBackByFact
search(directions: directions, startTime: firstParticlePerAct.currentEventTime, minDeltaTime: 0, maxDeltaTime: criteria.fissionAlphaMaxTime, maxDeltaTimeBackward: criteria.fissionAlphaBackBackwardMaxTime, useCycleTime: false, updateCycle: false) { (event: Event, time: CUnsignedLongLong, deltaTime: CLongLong, stop: UnsafeMutablePointer<Bool>, _) in
if self.isBack(event, type: type) {
var store = byFact
if !store {
let energy = self.getEnergy(event, type: type)
store = energy >= self.criteria.fissionAlphaBackMinEnergy && energy <= self.criteria.fissionAlphaBackMaxEnergy
}
if store {
self.storeFissionAlphaBack(event, match: match, type: type, deltaTime: deltaTime)
if byFact { // just stop on first one
stop.initialize(to: true)
}
}
}
}
if !criteria.summarizeFissionsAlphaBack {
match.matchFor(side: .back).filterItemsByMaxEnergy(maxStripsDelta: criteria.recoilBackMaxDeltaStrips)
}
}
fileprivate func findRecoil() {
let fissionTime = absTime(CUnsignedShort(firstParticlePerAct.currentEventTime), cycle: currentCycle)
let directions: Set<SearchDirection> = [.backward]
search(directions: directions, startTime: fissionTime, minDeltaTime: criteria.recoilMinTime, maxDeltaTime: criteria.recoilMaxTime, useCycleTime: true, updateCycle: false) { (event: Event, time: CUnsignedLongLong, deltaTime: CLongLong, stop: UnsafeMutablePointer<Bool>, _) in
let isRecoil = self.isFront(event, type: self.criteria.recoilType)
if isRecoil {
let isNear = self.isEventStripNearToFirstParticle(event, maxDelta: Int(self.criteria.recoilFrontMaxDeltaStrips), side: .front)
if isNear {
let found = self.validateRecoil(event, deltaTime: deltaTime)
if found && self.criteria.searchFirstRecoilOnly {
stop.initialize(to: true)
}
}
}
}
}
@discardableResult fileprivate func validateRecoil(_ event: Event, deltaTime: CLongLong) -> Bool {
let energy = self.getEnergy(event, type: criteria.recoilType)
if energy >= criteria.recoilFrontMinEnergy && energy <= criteria.recoilFrontMaxEnergy {
var position = fpos_t()
fgetpos(self.file, &position)
let t = CUnsignedLongLong(event.param1)
let tof = findTOFForRecoil(event, timeRecoil: t, kind: .TOF)
fseek(self.file, Int(position), SEEK_SET)
var tof2: DetectorMatchItem? = nil
if criteria.useTOF2 {
tof2 = findTOFForRecoil(event, timeRecoil: t, kind: .TOF2)
fseek(self.file, Int(position), SEEK_SET)
}
if (criteria.requiredTOF && !(tof != nil || tof2 != nil)) {
return false
}
let found = findRecoilBack(t, position: Int(position))
if (!found && criteria.requiredRecoilBack) {
return false
}
var gamma: DetectorMatch?
if criteria.startFromRecoil(), !criteria.searchExtraFromLastParticle {
gamma = findGamma(Int(position))
if criteria.requiredGamma && nil == gamma {
return false
}
}
var subMatches: [SearchType : DetectorMatch?] = [:]
if let gamma = gamma {
subMatches[.gamma] = gamma
}
if let tof = tof {
subMatches[.tof] = DetectorMatch(items: [tof])
}
if let tof2 = tof2 {
subMatches[.tof2] = DetectorMatch(items: [tof2])
}
self.storeRecoil(event, energy: energy, deltaTime: deltaTime, subMatches: subMatches)
return true
}
return false
}
fileprivate func findTOFForRecoil(_ eventRecoil: Event, timeRecoil: CUnsignedLongLong, kind: TOFKind) -> DetectorMatchItem? {
let directions: Set<SearchDirection> = [.forward, .backward]
var match: DetectorMatchItem?
search(directions: directions, startTime: timeRecoil, minDeltaTime: 0, maxDeltaTime: criteria.maxTOFTime, useCycleTime: false, updateCycle: false) { (event: Event, time: CUnsignedLongLong, deltaTime: CLongLong, stop: UnsafeMutablePointer<Bool>, _) in
if let k = self.dataProtocol.isTOFEvent(Int(event.eventId)), k == kind {
let value = self.valueTOF(event, eventRecoil: eventRecoil)
if value >= self.criteria.minTOFValue && value <= self.criteria.maxTOFValue {
match = self.TOFValue(value, deltaTime: deltaTime)
stop.initialize(to: true)
}
}
}
return match
}
fileprivate func findRecoilBack(_ timeRecoilFront: CUnsignedLongLong, position: Int) -> Bool {
var items = [DetectorMatchItem]()
let side: StripsSide = .back
let directions: Set<SearchDirection> = [.backward, .forward]
let byFact = self.criteria.searchRecoilBackByFact
search(directions: directions, startTime: timeRecoilFront, minDeltaTime: 0, maxDeltaTime: criteria.recoilBackMaxTime, maxDeltaTimeBackward: criteria.recoilBackBackwardMaxTime, useCycleTime: false, updateCycle: false) { (event: Event, time: CUnsignedLongLong, deltaTime: CLongLong, stop: UnsafeMutablePointer<Bool>, _) in
let type: SearchType = self.criteria.recoilBackType
if self.isBack(event, type: type) {
var store = self.criteria.startFromRecoil() || self.isRecoilBackStripNearToFissionAlphaBack(event)
if !byFact && store {
let energy = self.getEnergy(event, type: type)
store = energy >= self.criteria.recoilBackMinEnergy && energy <= self.criteria.recoilBackMaxEnergy
}
if store {
let item = self.focalDetectorMatchItemFrom(event, type: type, deltaTime: deltaTime, side: side)
items.append(item)
if byFact || self.criteria.searchFirstRecoilOnly { // just stop on first one
stop.initialize(to: true)
}
}
}
}
fseek(self.file, Int(position), SEEK_SET)
if let item = DetectorMatch.getItemWithMaxEnergy(items) {
recoilsPerAct.append(item, side: side)
return true
} else {
return false
}
}
fileprivate func findSpecialEvents() {
var setIds = Set<Int>(criteria.specialEventIds)
if setIds.count == 0 {
return
}
forwardSearch { (event: Event, stop: UnsafeMutablePointer<Bool>) in
let id = Int(event.eventId)
if setIds.contains(id) {
self.storeSpecial(event, id: id)
setIds.remove(id)
}
if setIds.count == 0 {
stop.initialize(to: true)
}
}
}
fileprivate func findBeamEvents() {
forwardSearch { (event: Event, stop: UnsafeMutablePointer<Bool>) in
if self.beamStatePerAct.handleEvent(event, criteria: self.criteria, dataProtocol: self.dataProtocol!) {
stop.initialize(to: true)
}
}
}
fileprivate func findFissionAlpha(_ index: Int) {
guard let c = criteria.next[index] else {
return
}
let startTime = absTime(CUnsignedShort(index == 1 ? firstParticlePerAct.currentEventTime : (fissionsAlphaNextPerAct[index-1]?.currentEventTime ?? 0)), cycle: currentCycle)
let directions: Set<SearchDirection> = [.forward]
let isLastNext = criteria.nextMaxIndex() == index
search(directions: directions, startTime: startTime, minDeltaTime: c.minTime, maxDeltaTime: c.maxTime, useCycleTime: true, updateCycle: false) { (event: Event, time: CUnsignedLongLong, deltaTime: CLongLong, stop: UnsafeMutablePointer<Bool>, position: Int) in
let t = c.frontType
let isFront = self.isFront(event, type: t)
if isFront {
let st = UInt64(event.param1)
self.fissionsAlphaNextPerAct[index]?.currentEventTime = st
let energy = self.getEnergy(event, type: t)
if self.isEventStripNearToFirstParticle(event, maxDelta: Int(c.maxDeltaStrips), side: .front) && ((!isFront && c.backByFact) || (energy >= c.frontMinEnergy && energy <= c.frontMaxEnergy)) {
var store = true
var gamma: DetectorMatch?
// Back
let back = self.findFissionAlphaBack(index, position: position, startTime: st)
if self.criteria.requiredFissionAlphaBack && back == nil {
store = false
} else {
// Extra Search
if isLastNext, self.criteria.searchExtraFromLastParticle {
self.findFissionAlphaWell(position)
if self.findNeutrons(position) {
store = false
}
gamma = self.findGamma(position)
if nil == gamma, self.criteria.requiredGamma {
store = false
}
}
}
if store {
self.storeFissionAlpha(index, event: event, type: t, deltaTime: deltaTime, subMatches: [.gamma: gamma], back: back)
}
}
}
}
}
fileprivate func findFissionAlphaBack(_ index: Int, position: Int, startTime: CUnsignedLongLong) -> DetectorMatchItem? {
guard let c = criteria.next[index] else {
return nil
}
var items = [DetectorMatchItem]()
let directions: Set<SearchDirection> = [.forward, .backward]
let byFact = c.backByFact
search(directions: directions, startTime: startTime, minDeltaTime: 0, maxDeltaTime: criteria.fissionAlphaMaxTime, maxDeltaTimeBackward: criteria.fissionAlphaBackBackwardMaxTime, useCycleTime: false, updateCycle: false) { (event: Event, time: CUnsignedLongLong, deltaTime: CLongLong, stop: UnsafeMutablePointer<Bool>, position: Int) in
let t = c.backType
let isBack = self.isBack(event, type: t)
if isBack {
var store = self.isEventStripNearToFirstParticle(event, maxDelta: Int(self.criteria.recoilBackMaxDeltaStrips), side: .back)
if !byFact && store { // check energy also
let energy = self.getEnergy(event, type: t)
store = energy >= c.backMinEnergy && energy <= c.backMaxEnergy
}
if store {
let item = self.focalDetectorMatchItemFrom(event, type: t, deltaTime: deltaTime, side: .back)
items.append(item)
if byFact { // just stop on first one
stop.initialize(to: true)
}
}
}
}
fseek(file, position, SEEK_SET)
if let item = DetectorMatch.getItemWithMaxEnergy(items) {
return item
}
return nil
}
// MARK: - Storage
fileprivate func focalDetectorMatchItemFrom(_ event: Event, type: SearchType, deltaTime: CLongLong, side: StripsSide) -> DetectorMatchItem {
let id = event.eventId
let encoder = dataProtocol.encoderForEventId(Int(id))
let strip0_15 = event.param2 >> 12
let energy = getEnergy(event, type: type)
let item = DetectorMatchItem(type: type,
stripDetector: .focal,
energy: energy,
encoder: encoder,
strip0_15: strip0_15,
eventNumber: eventNumber(),
deltaTime: deltaTime,
marker: event.getMarker(),
side: side)
return item
}
fileprivate func storeFissionAlphaBack(_ event: Event, match: DoubleSidedStripDetectorMatch, type: SearchType, deltaTime: CLongLong) {
let side: StripsSide = .back
let item = focalDetectorMatchItemFrom(event, type: type, deltaTime: deltaTime, side: side)
match.append(item, side: side)
}
fileprivate func storeFissionAlphaFront(_ event: Event, deltaTime: CLongLong, subMatches: [SearchType: DetectorMatch?]?) {
let id = event.eventId
let type = criteria.startParticleType
let channel = event.getChannelFor(type: type)
let encoder = dataProtocol.encoderForEventId(Int(id))
let strip0_15 = event.param2 >> 12
let energy = getEnergy(event, type: type)
let side: StripsSide = .front
let item = DetectorMatchItem(type: type,
stripDetector: .focal,
energy: energy,
encoder: encoder,
strip0_15: strip0_15,
eventNumber: eventNumber(),
deltaTime: deltaTime,
marker: event.getMarker(),
channel: channel,
subMatches: subMatches,
side: side)
fissionsAlphaPerAct.append(item, side: side)
}
fileprivate func gammaMatchItem(_ event: Event, deltaTime: CLongLong) -> DetectorMatchItem? {
let channel = Double(event.param3 & Mask.gamma.rawValue)
let eventId = Int(event.eventId)
let encoder = dataProtocol.encoderForEventId(eventId)
if criteria.gammaEncodersOnly, !criteria.gammaEncoderIds.contains(Int(encoder)) {
return nil
}
let energy: Double
let type: SearchType = .gamma
if calibration.hasData() {
energy = calibration.calibratedValueForAmplitude(channel, type: type, eventId: eventId, encoder: encoder, strip0_15: nil, dataProtocol: dataProtocol)
} else {
energy = channel
}
// TODO: use marker info
// let coincidenceWithBGO = (event.param3 >> 15) == 1
let strip = (event.param3 << 1) >> 12
let item = DetectorMatchItem(type: type,
stripDetector: nil,
energy: energy,
encoder: encoder,
strip0_15: strip,
deltaTime: deltaTime,
marker: event.getMarker(),
side: nil)
return item
}
fileprivate func storeRecoil(_ event: Event, energy: Double, deltaTime: CLongLong, subMatches: [SearchType: DetectorMatch?]?) {
let id = event.eventId
let encoder = dataProtocol.encoderForEventId(Int(id))
let strip0_15 = event.param2 >> 12
let side: StripsSide = .front
let item = DetectorMatchItem(type: .recoil,
stripDetector: .focal,
energy: energy,
encoder: encoder,
strip0_15: strip0_15,
eventNumber: eventNumber(),
deltaTime: deltaTime,
marker: event.getMarker(),
subMatches: subMatches,
side: side)
recoilsPerAct.append(item, side: side)
}
fileprivate func storeFissionAlpha(_ index: Int, event: Event, type: SearchType, deltaTime: CLongLong, subMatches: [SearchType: DetectorMatch?]?, back: DetectorMatchItem?) {
let id = event.eventId
let encoder = dataProtocol.encoderForEventId(Int(id))
let strip0_15 = event.param2 >> 12
let energy = getEnergy(event, type: type)
let side: StripsSide = .front
let item = DetectorMatchItem(type: type,
stripDetector: .focal,
energy: energy,
encoder: encoder,
strip0_15: strip0_15,
eventNumber: eventNumber(),
deltaTime: deltaTime,
marker: event.getMarker(),
subMatches: subMatches,
side: side)
let match = fissionsAlphaNextPerAct[index] ?? DoubleSidedStripDetectorMatch()
match.append(item, side: side)
if let back = back {
match.append(back, side: .back)
}
fissionsAlphaNextPerAct[index] = match
}
fileprivate func TOFValue(_ value: Double, deltaTime: CLongLong) -> DetectorMatchItem {
let item = DetectorMatchItem(type: .tof,
stripDetector: nil,
deltaTime: deltaTime,
value: value,
side: nil)
return item
}
fileprivate func storeVETO(_ event: Event, deltaTime: CLongLong) {
let strip0_15 = event.param2 >> 12
let type: SearchType = .veto
let energy = getEnergy(event, type: type)
let item = DetectorMatchItem(type: type,
stripDetector: nil,
energy: energy,
strip0_15: strip0_15,
eventNumber: eventNumber(),
deltaTime: deltaTime,
side: nil)
vetoPerAct.append(item)
}
fileprivate func filterAndStoreFissionAlphaWell(_ event: Event, side: StripsSide) {
var type: SearchType
if side == .front {
if criteria.searchExtraFromLastParticle, let index = criteria.nextMaxIndex(), let t = criteria.next[index]?.frontType {
type = t
} else {
type = criteria.startParticleType
}
} else {
type = criteria.wellParticleBackType
}
let energy = getEnergy(event, type: type)
if energy < criteria.fissionAlphaWellMinEnergy || energy > criteria.fissionAlphaWellMaxEnergy {
return
}
let encoder = dataProtocol.encoderForEventId(Int(event.eventId))
let strip0_15 = event.param2 >> 12
let item = DetectorMatchItem(type: type,
stripDetector: .side,
energy: energy,
encoder: encoder,
strip0_15: strip0_15,
marker: event.getMarker(),
side: side)
fissionsAlphaWellPerAct.append(item, side: side)
// Store only well event with max energy
fissionsAlphaWellPerAct.matchFor(side: side).filterItemsByMaxEnergy(maxStripsDelta: criteria.recoilBackMaxDeltaStrips)
}
fileprivate func storeSpecial(_ event: Event, id: Int) {
let channel = event.param3 & Mask.special.rawValue
specialPerAct[id] = channel
}
fileprivate func clearActInfo() {
neutronsPerAct = NeutronsMatch()
fissionsAlphaPerAct.removeAll()
specialPerAct.removeAll()
beamStatePerAct.clean()
fissionsAlphaWellPerAct.removeAll()
recoilsPerAct.removeAll()
fissionsAlphaNextPerAct.removeAll()
vetoPerAct.removeAll()
}
// MARK: - Helpers
fileprivate func isEventStripNearToFirstParticle(_ event: Event, maxDelta: Int, side: StripsSide) -> Bool {
let strip0_15 = event.param2 >> 12
let encoder = dataProtocol.encoderForEventId(Int(event.eventId))
let strip1_N = stripsConfiguration(detector: .focal).strip1_N_For(side: side, encoder: Int(encoder), strip0_15: strip0_15)
if let s = firstParticlePerAct.firstItemsFor(side: side)?.strip1_N {
return abs(Int32(strip1_N) - Int32(s)) <= Int32(maxDelta)
}
return false
}
fileprivate func isRecoilBackStripNearToFissionAlphaBack(_ event: Event) -> Bool {
let side: StripsSide = .back
if let s = fissionsAlphaPerAct.matchFor(side: side).itemWithMaxEnergy()?.strip1_N {
let strip0_15 = event.param2 >> 12
let encoder = dataProtocol.encoderForEventId(Int(event.eventId))
let strip1_N = stripsConfiguration(detector: .focal).strip1_N_For(side: side, encoder: Int(encoder), strip0_15: strip0_15)
return abs(Int32(strip1_N) - Int32(s)) <= Int32(criteria.recoilBackMaxDeltaStrips)
}
return false
}
/**
+/-1 strips check at this moment.
*/
fileprivate func isFissionStripNearToFirstFissionFront(_ event: Event) -> Bool {
let side: StripsSide = .front
if let s = fissionsAlphaPerAct.firstItemsFor(side: side)?.strip1_N {
let strip0_15 = event.param2 >> 12
let encoder = dataProtocol.encoderForEventId(Int(event.eventId))
let strip1_N = stripsConfiguration(detector: .focal).strip1_N_For(side: side, encoder: Int(encoder), strip0_15: strip0_15)
return Int(abs(Int32(strip1_N) - Int32(s))) <= 1
}
return false
}
/**
Time stored in events are relative time (timer from 0x0000 to xFFFF mks resettable on overflow).
We use special event 'dataProtocol.CycleTime' to calculate time from file start.
*/
fileprivate func absTime(_ relativeTime: CUnsignedShort, cycle: CUnsignedLongLong) -> CUnsignedLongLong {
return (cycle << 16) + CUnsignedLongLong(relativeTime)
}
/**
First bit from param3 used to separate recoil and fission/alpha events:
0 - fission fragment,
1 - recoil
*/
fileprivate func isRecoil(_ event: Event) -> Bool {
return (event.param3 >> 15) == 1
}
/**
Second bit from param3 related to beam state:
0 - on,
1 - off (!)
*/
fileprivate func isInBeam(_ event: Event) -> Bool {
// TODO: this is for SHELS separator. Handle reverse logic for GRAND separator.
let outBeam = (event.param3 << 1) >> 15
return outBeam != 1
}
/**
Third bit from param3 is overflow with different signal:
0 - no,
1 - yes
*/
fileprivate func isOverflow(_ event: Event) -> Bool {
let overflow = (event.param3 << 2) >> 15
return overflow == 1
}
fileprivate func isGammaEvent(_ event: Event) -> Bool {
let eventId = Int(event.eventId)
return dataProtocol.isGammaEvent(eventId)
}
fileprivate func isFront(_ event: Event, type: SearchType) -> Bool {
let searchRecoil = type == .recoil || type == .heavy
let currentRecoil = isRecoil(event)
let sameType = (searchRecoil && currentRecoil) || (!searchRecoil && !currentRecoil)
return sameType && isFront(event)
}
fileprivate func isFront(_ event: Event) -> Bool {
let eventId = Int(event.eventId)
return dataProtocol.isAlphaFronEvent(eventId)
}
fileprivate func isFissionOrAlphaWell(_ event: Event, side: StripsSide) -> Bool {
let eventId = Int(event.eventId)
if isRecoil(event) && !criteria.wellRecoilsAllowed {
return false
}
return (side == .front && dataProtocol.isAlphaWellEvent(eventId)) || (side == .back && dataProtocol.isAlphaWellBackEvent(eventId))
}
fileprivate func isBack(_ event: Event, type: SearchType) -> Bool {
let eventId = Int(event.eventId)
let searchRecoil = type == .recoil || type == .heavy
let currentRecoil = isRecoil(event)
let sameType = (searchRecoil && currentRecoil) || (!searchRecoil && !currentRecoil)
return sameType && dataProtocol.isAlphaBackEvent(eventId)
}
fileprivate func eventNumber(_ total: Bool = false) -> CUnsignedLongLong {
var position = fpos_t()
fgetpos(file, &position)
var value = CUnsignedLongLong(position/Int64(Event.size))
if total {
value += totalEventNumber
}
return value
}
fileprivate func channelForTOF(_ event :Event) -> CUnsignedShort {
return event.param3 & Mask.TOF.rawValue
}
fileprivate func getEnergy(_ event: Event, type: SearchType) -> Double {
let channel = Double(event.getChannelFor(type: type))
if calibration.hasData() {
let eventId = Int(event.eventId)
let encoder = dataProtocol.encoderForEventId(eventId)
let strip0_15 = event.param2 >> 12
return calibration.calibratedValueForAmplitude(channel, type: type, eventId: eventId, encoder: encoder, strip0_15: strip0_15, dataProtocol: dataProtocol)
} else {
return channel
}
}
fileprivate func valueTOF(_ eventTOF: Event, eventRecoil: Event) -> Double {
let channel = Double(channelForTOF(eventTOF))
if criteria.unitsTOF == .channels || !calibration.hasData() {
return channel
} else {
if let value = calibration.calibratedTOFValueForAmplitude(channel) {
return value
} else {
let eventId = Int(eventRecoil.eventId)
let encoder = dataProtocol.encoderForEventId(eventId)
let strip0_15 = eventRecoil.param2 >> 12
return calibration.calibratedValueForAmplitude(channel, type: SearchType.tof, eventId: eventId, encoder: encoder, strip0_15: strip0_15, dataProtocol: dataProtocol)
}
}
}
// MARK: - Output
fileprivate func logInput(onEnd: Bool) {
DispatchQueue.main.async { [weak self] in
let appDelegate = NSApplication.shared.delegate as! AppDelegate
let image = appDelegate.window.screenshot()
self?.logger.logInput(image, onEnd: onEnd)
}
}
fileprivate func logCalibration() {
logger.logCalibration(calibration.stringValue ?? "")
}
}
extension Processor: ResultsTableDelegate {
func rowsCountForCurrentResult() -> Int {
return max(max(max(max(max(1, vetoPerAct.count), fissionsAlphaPerAct.count), recoilsPerAct.count), neutronsCountWithNewLine()), fissionsAlphaNextPerAct.values.map { $0.count }.max() ?? 0)
}
// Need special results block for neutron times, so we skeep one line.
func neutronsCountWithNewLine() -> Int {
let count = neutronsPerAct.count
if count > 0 {
return count + 1
} else {
return 0
}
}
func neutrons() -> NeutronsMatch {
return neutronsPerAct
}
func currentFileEventNumber(_ number: CUnsignedLongLong) -> String {
return String(format: "%@_%llu", currentFileName ?? "", number)
}
func focalGammaContainer() -> DetectorMatch? {
var match: DoubleSidedStripDetectorMatch?
if criteria.searchExtraFromLastParticle {
match = lastFissionAlphaNextPerAct
} else if criteria.startFromRecoil() {
match = recoilsPerAct
} else {
match = fissionsAlphaPerAct
}
return match?.matchFor(side: .front)
}
func vetoAt(index: Int) -> DetectorMatchItem? {
return vetoPerAct.itemAt(index: index)
}
func recoilAt(side: StripsSide, index: Int) -> DetectorMatchItem? {
return recoilsPerAct.matchFor(side: side).itemAt(index: index)
}
func fissionsAlphaWellAt(side: StripsSide, index: Int) -> DetectorMatchItem? {
return fissionsAlphaWellPerAct.matchFor(side: side).itemAt(index: index)
}
func beamState() -> BeamState {
return beamStatePerAct
}
func firstParticleAt(side: StripsSide) -> DetectorMatch {
return firstParticlePerAct.matchFor(side: side)
}
func nextParticleAt(side: StripsSide, index: Int) -> DetectorMatch? {
return fissionsAlphaNextPerAct[index]?.matchFor(side: side)
}
func specialWith(eventId: Int) -> CUnsignedShort? {
return specialPerAct[eventId]
}
}
| mit | b72c76eb33eb1381f8663ed692bd35dd | 42.974359 | 384 | 0.557198 | 4.787577 | false | false | false | false |
jasl/RouterX | Sources/RouterX/RoutingPatternScanner.swift | 1 | 2026 | import Foundation
private enum _PatternScanTerminator: Character {
case lParen = "("
case rParen = ")"
case slash = "/"
case dot = "."
case star = "*"
var jointFragment: (token: RoutingPatternToken?, fragment: String) {
switch self {
case .lParen:
return (token: .lParen, fragment: "")
case .rParen:
return (token: .rParen, fragment: "")
case .slash:
return (token: .slash, fragment: "")
case .dot:
return (token: .dot, fragment: "")
case .star:
return (token: nil, fragment: "*")
}
}
}
internal struct RoutingPatternScanner {
static func tokenize(_ pattern: PatternIdentifier) -> [RoutingPatternToken] {
guard !pattern.isEmpty else { return [] }
var appending = ""
var result: [RoutingPatternToken] = pattern.reduce(into: []) { box, char in
guard let terminator = _PatternScanTerminator(rawValue: char) else {
appending.append(char)
return
}
let jointFragment = terminator.jointFragment
defer {
if let token = jointFragment.token {
box.append(token)
}
appending = jointFragment.fragment
}
guard let jointToken = _generateToken(expression: appending) else { return }
box.append(jointToken)
}
if let tailToken = _generateToken(expression: appending) {
result.append(tailToken)
}
return result
}
static private func _generateToken(expression: String) -> RoutingPatternToken? {
guard let firstChar = expression.first else { return nil }
let fragments = String(expression.dropFirst())
switch firstChar {
case ":":
return .symbol(fragments)
case "*":
return .star(fragments)
default:
return .literal(expression)
}
}
}
| mit | 8af63326bcd5fa6a3dc262a6b8c3b7e1 | 28.794118 | 88 | 0.548865 | 4.84689 | false | false | false | false |
Brightify/Cuckoo | Source/Stubbing/StubCall.swift | 2 | 980 | //
// StubCall.swift
// Cuckoo
//
// Created by Filip Dolnik on 29.05.16.
// Copyright © 2016 Brightify. All rights reserved.
//
public protocol StubCall {
var method: String { get }
var parametersAsString: String { get }
}
public struct ConcreteStubCall<IN>: StubCall {
public let method: String
public let parameters: (IN)
public var parametersAsString: String {
let string = String(describing: parameters)
if (string.range(of: ",") != nil && string.hasPrefix("(")) || string == "()" {
return string
} else {
// If only one parameter add brackets and quotes
let wrappedParameter = String(describing: (parameters, 0))
return wrappedParameter[..<wrappedParameter.index(wrappedParameter.endIndex, offsetBy: -4)] + ")"
}
}
public init(method: String, parameters: (IN)) {
self.method = method
self.parameters = parameters
}
}
| mit | 3275fc60b5e9096c91309c8fea086b6f | 28.666667 | 109 | 0.60572 | 4.370536 | false | false | false | false |
haawa799/WaniKit2 | Sources/WaniKit/Apple NSOperation/Conditions/RemoteNotificationCondition.swift | 2 | 4451 | /*
Copyright (C) 2015 Apple Inc. All Rights Reserved.
See LICENSE.txt for this sample’s licensing information
Abstract:
This file shows an example of implementing the OperationCondition protocol.
*/
import Foundation
#if os(iOS)
import UIKit
private let RemoteNotificationQueue = OperationQueue()
private let RemoteNotificationName = "RemoteNotificationPermissionNotification"
private enum RemoteRegistrationResult {
case Token(NSData)
case Error(NSError)
}
/// A condition for verifying that the app has the ability to receive push notifications.
public struct RemoteNotificationCondition: OperationCondition {
public static let name = "RemoteNotification"
public static let isMutuallyExclusive = false
public static func didReceiveNotificationToken(token: NSData) {
NSNotificationCenter.defaultCenter().postNotificationName(RemoteNotificationName, object: nil, userInfo: [
"token": token
])
}
public static func didFailToRegister(error: NSError) {
NSNotificationCenter.defaultCenter().postNotificationName(RemoteNotificationName, object: nil, userInfo: [
"error": error
])
}
let application: UIApplication
init(application: UIApplication) {
self.application = application
}
public func dependencyForOperation(operation: Operation) -> NSOperation? {
return RemoteNotificationPermissionOperation(application: application, handler: { _ in })
}
public func evaluateForOperation(operation: Operation, completion: OperationConditionResult -> Void) {
/*
Since evaluation requires executing an operation, use a private operation
queue.
*/
RemoteNotificationQueue.addOperation(RemoteNotificationPermissionOperation(application: application) { result in
switch result {
case .Token(_):
completion(.Satisfied)
case .Error(let underlyingError):
let error = NSError(code: .ConditionFailed, userInfo: [
OperationConditionKey: self.dynamicType.name,
NSUnderlyingErrorKey: underlyingError
])
completion(.Failed(error))
}
})
}
}
/**
A private `Operation` to request a push notification token from the `UIApplication`.
- note: This operation is used for *both* the generated dependency **and**
condition evaluation, since there is no "easy" way to retrieve the push
notification token other than to ask for it.
- note: This operation requires you to call either `RemoteNotificationCondition.didReceiveNotificationToken(_:)` or
`RemoteNotificationCondition.didFailToRegister(_:)` in the appropriate
`UIApplicationDelegate` method, as shown in the `AppDelegate.swift` file.
*/
private class RemoteNotificationPermissionOperation: Operation {
let application: UIApplication
private let handler: RemoteRegistrationResult -> Void
private init(application: UIApplication, handler: RemoteRegistrationResult -> Void) {
self.application = application
self.handler = handler
super.init()
/*
This operation cannot run at the same time as any other remote notification
permission operation.
*/
addCondition(MutuallyExclusive<RemoteNotificationPermissionOperation>())
}
override func execute() {
dispatch_async(dispatch_get_main_queue()) {
let notificationCenter = NSNotificationCenter.defaultCenter()
notificationCenter.addObserver(self, selector: "didReceiveResponse:", name: RemoteNotificationName, object: nil)
self.application.registerForRemoteNotifications()
}
}
@objc func didReceiveResponse(notification: NSNotification) {
NSNotificationCenter.defaultCenter().removeObserver(self)
let userInfo = notification.userInfo
if let token = userInfo?["token"] as? NSData {
handler(.Token(token))
}
else if let error = userInfo?["error"] as? NSError {
handler(.Error(error))
}
else {
fatalError("Received a notification without a token and without an error.")
}
finish()
}
}
#endif
| mit | 588766ebccaf2378a894688f7f3f359b | 33.488372 | 124 | 0.66307 | 5.869393 | false | false | false | false |
kirby10023/4yrAnniversary | 2b1s/Controllers/ItineraryViewController.swift | 1 | 3644 | //
// ItinerayViewController.swift
// 2b1s
//
// Created by Kirby on 5/31/17.
// Copyright © 2017 Kirby. All rights reserved.
//
import UIKit
import FontAwesome_swift
class ItineraryViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
// reference to tab bar controller
fileprivate var rootController: TabBarViewController {
return parent as! TabBarViewController
}
override func awakeFromNib() {
super.awakeFromNib()
tabBarItem.image = UIImage.fontAwesomeIcon(name: .list, textColor: .black, size: CGSize(width: 40, height: 40))
}
override func viewDidLoad() {
super.viewDidLoad()
tableView.dataSource = self
tableView.delegate = self
// Do any additional setup after loading the view.
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
print("APPEAR")
tableView.reloadData()
}
}
// MARK: - table view data source
extension ItineraryViewController: UITableViewDataSource, UITableViewDelegate {
func tableView(_: UITableView, numberOfRowsInSection section: Int) -> Int {
guard let sectionInfo = rootController.eventFetchedResultsController.sections?[section] else {
return 0
}
return sectionInfo.numberOfObjects
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "ItineraryCell", for: indexPath) as! ItineraryCell
let event = rootController.eventFetchedResultsController.object(at: indexPath)
if event.time > 1_496_617_200 {
// if event.time > Date().timeIntervalSince1970 {
cell.titleLabel.text = "???????"
cell.sampleImage.image = UIImage.fontAwesomeIcon(name: .questionCircle, textColor: .gray, size: cell.sampleImage.bounds.size)
cell.event = nil
} else {
cell.event = event
cell.titleLabel.text = event.name
cell.sampleImage.image = event.image ?? nil
}
let eventDate = Date(timeIntervalSince1970: event.time)
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MMM d, h:mm a"
dateFormatter.amSymbol = "AM"
dateFormatter.pmSymbol = "PM"
let eventString = dateFormatter.string(from: eventDate)
cell.timeLabel.text = eventString
return cell
}
// select row
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
let cell = tableView.cellForRow(at: indexPath) as! ItineraryCell
if cell.event != nil {
performSegue(withIdentifier: "showDetails", sender: cell)
} else {
showAlert()
}
}
}
// MARK: - Segue
extension ItineraryViewController {
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
guard let cell = sender as? ItineraryCell,
let indexPath = tableView.indexPath(for: cell),
let navigationController = segue.destination as? UINavigationController,
let itineraryDetailsViewController = navigationController.topViewController as? ItineraryDetailsViewController
else {
return
}
let event = rootController.eventFetchedResultsController.object(at: indexPath)
itineraryDetailsViewController.event = event
}
}
// MARK: - Alerts
extension ItineraryViewController {
func showAlert() {
let alert = UIAlertController(title: "Hold it!", message: "Don't skip ahead, wait to be suprised!", preferredStyle: .alert)
let action = UIAlertAction(title: "OK", style: .default) { _ in
}
alert.addAction(action)
present(alert, animated: true)
}
}
| mit | d64fcab68efa8be496558c4f1605aff4 | 26.186567 | 131 | 0.709306 | 4.442683 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.