repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
210 values
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
necrowman/CRLAlamofireFuture
Examples/SimpleTvOSCarthage/Carthage/Checkouts/ExecutionContext/ExecutionContext/ExecutionContextTenant.swift
111
1060
//===--- ExecutionContextTenant.swift ------------------------------------------------------===// //Copyright (c) 2016 Daniel Leping (dileping) // //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. //===----------------------------------------------------------------------===// public protocol ExecutionContextTenantProtocol { var context:ExecutionContextType {get} } public protocol MovableExecutionContextTenantProtocol : ExecutionContextTenantProtocol { associatedtype SettledTenant func settle(in context:ExecutionContextType) -> SettledTenant }
mit
9b1483dcb6a1a7380a897fc2946912e2
41.44
97
0.673585
5.353535
false
false
false
false
practicalswift/swift
test/Constraints/construction.swift
2
4193
// RUN: %target-typecheck-verify-swift struct X { var i : Int, j : Int } struct Y { init (_ x : Int, _ y : Float, _ z : String) {} } enum Z { case none case char(UnicodeScalar) case string(String) case point(Int, Int) init() { self = .none } init(_ c: UnicodeScalar) { self = .char(c) } init(_ s: String) { self = .string(s) } init(_ x: Int, _ y: Int) { self = .point(x, y) } } enum Optional<T> { // expected-note {{'T' declared as parameter to type 'Optional'}} case none case value(T) init() { self = .none } init(_ t: T) { self = .value(t) } } class Base { } class Derived : Base { } var d : Derived typealias Point = (x : Int, y : Int) var hello : String = "hello"; var world : String = "world"; var i : Int var z : Z = .none func acceptZ(_ z: Z) {} func acceptString(_ s: String) {} Point(1, 2) // expected-warning {{expression of type '(x: Int, y: Int)' is unused}} var db : Base = d X(i: 1, j: 2) // expected-warning{{unused}} Y(1, 2, "hello") // expected-warning{{unused}} // Unions Z(UnicodeScalar("a")) // expected-warning{{unused}} Z(1, 2) // expected-warning{{unused}} acceptZ(.none) acceptZ(.char("a")) acceptString("\(hello), \(world) #\(i)!") Optional<Int>(1) // expected-warning{{unused}} Optional(1) // expected-warning{{unused}} _ = .none as Optional<Int> Optional(.none) // expected-error{{generic parameter 'T' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{9-9=<Any>}} // Interpolation _ = "\(hello), \(world) #\(i)!" class File { init() { fd = 0 body = "" } var fd : Int32, body : String func replPrint() { print("File{\n fd=\(fd)\n body=\"\(body)\"\n}", terminator: "") } } // Non-trivial references to metatypes. struct Foo { struct Inner { } } extension Foo { func getInner() -> Inner { return Inner() } } // Downcasting var b : Base _ = b as! Derived // Construction doesn't permit conversion. // NOTE: Int and other integer-literal convertible types // are special cased in the library. Int(i) // expected-warning{{unused}} _ = i as Int Z(z) // expected-error{{cannot invoke initializer for type 'Z' with an argument list of type '(Z)'}} // expected-note @-1 {{overloads for 'Z' exist with these partially matching parameter lists: (String), (UnicodeScalar)}} Z.init(z) // expected-error {{cannot invoke 'Z.Type.init' with an argument list of type '(Z)'}} // expected-note @-1 {{overloads for 'Z.Type.init' exist with these partially matching parameter lists: (String), (UnicodeScalar)}} _ = z as Z // Construction from inouts. struct FooRef { } struct BarRef { init(x: inout FooRef) {} init(x: inout Int) {} } var f = FooRef() var x = 0 BarRef(x: &f) // expected-warning{{unused}} BarRef(x: &x) // expected-warning{{unused}} // Construction from a Type value not immediately resolved. struct S1 { init(i: Int) { } } struct S2 { init(i: Int) { } } func getMetatype(_ i: Int) -> S1.Type { return S1.self } func getMetatype(_ d: Double) -> S2.Type { return S2.self } var s1 = getMetatype(1).init(i: 5) s1 = S1(i: 5) var s2 = getMetatype(3.14).init(i: 5) s2 = S2(i: 5) // rdar://problem/19254404 let i32 = Int32(123123123) Int(i32 - 2 + 1) // expected-warning{{unused}} // rdar://problem/19459079 let xx: UInt64 = 100 let yy = ((xx + 10) - 5) / 5 let zy = (xx + (10 - 5)) / 5 // rdar://problem/30588177 struct S3 { init() { } } let s3a = S3() extension S3 { init?(maybe: S3) { return nil } } let s3b = S3(maybe: s3a) // SR-5245 - Erroneous diagnostic - Type of expression is ambiguous without more context class SR_5245 { struct S { enum E { case e1 case e2 } let e: [E] } init(s: S) {} } SR_5245(s: SR_5245.S(f: [.e1, .e2])) // expected-error@-1 {{incorrect argument label in call (have 'f:', expected 'e:')}} {{22-23=e}} // rdar://problem/34670592 - Compiler crash on heterogeneous collection literal _ = Array([1, "hello"]) // Ok func init_via_non_const_metatype(_ s1: S1.Type) { _ = s1(i: 42) // expected-error {{initializing from a metatype value must reference 'init' explicitly}} {{9-9=.init}} _ = s1.init(i: 42) // ok }
apache-2.0
282c5602fbaba0e7dcafea4308e28662
22.424581
171
0.616504
2.999285
false
false
false
false
daktales/FlatPreloadersSwift
Sources/FlatPreloaderTypeA.swift
1
11902
// // Loader.swift // Test // // Created by Walter Da Col on 01/11/14. // Copyright (c) 2014 Walter Da Col. All rights reserved. // import UIKit /** This preloader is composed by four dots, each one assigned to a quadrants. The animation is composed by dots changing quadrant in a given order (clockwise by default). */ class FlatPreloaderTypeA : FlatPreloader { /** Enumerator for quadrants. - UpLeft: The upper left quadrant. - UpRight: The upper right quadrant. - DownRight: The lower right quadrant. - DownLeft: The lower left quadrant. */ private enum QuadrantPosition : UInt { case UpLeft = 0, UpRight, DownRight, DownLeft } /// An alias to make "quadrants" management easy. private typealias Quadrant = (layer: DotLayer, position: QuadrantPosition) /// Quadrants array. private var quadrants : [Quadrant] = [ (DotLayer(), QuadrantPosition.UpLeft), (DotLayer(), QuadrantPosition.UpRight), (DotLayer(), QuadrantPosition.DownRight), (DotLayer(), QuadrantPosition.DownLeft) ] /// Layer inset construction private var insetLayer = CALayer() /// If preloader is currently animated private var animated : Bool = false /// Dots color (clockwise order). var dotColors : (upLeft: UIColor, upRight: UIColor, downRight: UIColor, downLeft: UIColor) { get { return ( UIColor(CGColor: self.quadrants[0].layer.fillColor), UIColor(CGColor: self.quadrants[1].layer.fillColor), UIColor(CGColor: self.quadrants[2].layer.fillColor), UIColor(CGColor: self.quadrants[3].layer.fillColor) ) } set { self.quadrants[0].layer.fillColor = newValue.upLeft.CGColor self.quadrants[1].layer.fillColor = newValue.upRight.CGColor self.quadrants[2].layer.fillColor = newValue.downRight.CGColor self.quadrants[3].layer.fillColor = newValue.downLeft.CGColor } } /// A CGFloat value that sets the minimum distance between dots. var dotsDistance : CGFloat = 0.0 /// A Boolean value that controls whether the receiver will go clockwise or counterclockwise when the animation is running. var reverseAnimation : Bool = false /// A CFTimeInterval value that sets the duration of an animation cycle var animationDuration : CFTimeInterval = 2.52 /// A CGFloat value that sets the dots padding from view borders var padding : CGFloat = 0.0 /// A Boolean value that controls the receiver backing layer. If `true` layer.cornerRadius will be resized to (dotRadius + padding) var automaticCornerRadius : Bool = false /** Adds layers */ private func addLayers() { self.layer.addSublayer(self.insetLayer) for quadrant in quadrants { self.insetLayer.addSublayer(quadrant.layer) } } /** Creates a new instance of this loader. :param: frame The loader frame. :param: dotsDistance The minimum distance between dots. Defaults to 0.0. :param: dotsColors The dots colors (a tuple of four colors). Defaults to all black. :param: animationDuration The animation (single complete rotation) duration. Defaults to 2.52. :param: reverseAnimation If true, the animation will go counterclockwise. Defaults to false :param: padding The dots inset from external frame. Defaults to 0.0. :param: hidesWhenStopped If true, hides the preloader when animation stops. Defaults to true. :param: automaticCornerRadius If true, the backing layer will automatically resize its cornerRadius value. Defaults to false. :returns: a new instance */ init( frame: CGRect, dotsDistance: CGFloat = 0.0, dotsColors: (UIColor, UIColor, UIColor, UIColor) = (UIColor.blackColor(),UIColor.blackColor(),UIColor.blackColor(),UIColor.blackColor()), animationDuration: CFTimeInterval = 2.52, reverseAnimation: Bool = false, padding: CGFloat = 0.0, hidesWhenStopped: Bool = true, automaticCornerRadius: Bool = false){ super.init(frame: frame) // Add layers self.addLayers() // Attributes self.dotColors = dotsColors self.dotsDistance = dotsDistance self.reverseAnimation = reverseAnimation self.animationDuration = animationDuration self.padding = padding self.automaticCornerRadius = automaticCornerRadius } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } /** Create a new instance of this loader using a default style. :param: style The given style. :returns: A new instance. */ override init(style: Style){ var frame : CGRect var padding : CGFloat var distance : CGFloat let colorA = UIColor(red: 237.0/255.0, green: 177.0/255.0, blue: 111.0/255.0, alpha: 1.0) let colorB = UIColor(red: 80.0/255.0, green: 172.0/255.0, blue: 154.0/255.0, alpha: 1.0) let colorC = UIColor(red: 210.0/255.0, green: 85.0/255.0, blue: 83.0/255.0, alpha: 1.0) let colorD = UIColor(red: 54.0/255.0, green: 77.0/255.0, blue: 88.0/255.0, alpha: 1.0) switch style { case .Small: frame = CGRectMake(0,0,32,32) padding = 3.0 distance = 1.0 case .Medium: frame = CGRectMake(0, 0, 64, 64) padding = 6.0 distance = 2.0 case .Big: frame = CGRectMake(0, 0, 128, 128) padding = 12.0 distance = 4.0 } super.init(style: style) // Add layers self.addLayers() // Attributes self.dotColors = (colorA, colorB, colorC, colorD) self.dotsDistance = distance self.padding = padding } override func layoutSubviews() { super.layoutSubviews() // Resize instet layer self.insetLayer.frame = CGRectInset(self.layer.bounds, self.padding, self.padding) // Resize and align dot layers let size = quadrantSize() for quadrant in quadrants { var origin = quadrantOrigin(quadrant.position) quadrant.layer.frame = CGRect(origin: quadrantOrigin(quadrant.position), size: size) quadrant.layer.draw() // redraw ovals } if self.automaticCornerRadius { self.layer.cornerRadius = CGFloat(dotRadius()) + self.padding } } override func startAnimating() { CATransaction.begin() CATransaction.setDisableActions(true) for quadrant in self.quadrants { if quadrant.layer.isPaused() { quadrant.layer.resume() } else { quadrant.layer.addAnimation(quadrantAnimation(quadrant), forKey: "dotAnimation") } } CATransaction.commit() } override func stopAnimating() { CATransaction.begin() CATransaction.setDisableActions(true) for quadrant in self.quadrants { quadrant.layer.pause() } CATransaction.commit() if self.hidesWhenStopped { self.hidden = true } } override func isAnimating() -> Bool { return self.animated } /** Returns a complete keyframe animation for one quadrant. :param: quadrant The quadrant to animate. :returns: A quadrant animation. */ private func quadrantAnimation(quadrant : Quadrant) -> CAKeyframeAnimation { var currentPoint = quadrantPosition(quadrant.position) var currentQuadrant = quadrant.position var functions : [CAMediaTimingFunction] = [] // For assigning a function to every keyframe animation var path = CGPathCreateMutable() CGPathMoveToPoint(path, nil, currentPoint.x, currentPoint.y) // Add all corners (or quadrant positions) for _ in 1...4 { currentQuadrant = nextQuadrant(currentQuadrant) currentPoint = quadrantPosition(currentQuadrant) CGPathAddLineToPoint(path, nil, currentPoint.x, currentPoint.y) functions.append(CAMediaTimingFunction(name: kCAMediaTimingFunctionDefault)) } var animation = CAKeyframeAnimation(keyPath: "position") animation.path = path animation.duration = self.animationDuration animation.timingFunctions = functions animation.repeatCount = Float(CGFloat.max) return animation } /** Returns the max dot radius for current combination of padding and dotsDistance. This number will be alway rounded to its floor value. :returns: The dots radius. */ private func dotRadius() -> UInt{ let smallestSide = max(0, Float(min(self.insetLayer.bounds.size.height, self.insetLayer.bounds.size.width)) - Float(dotsDistance)) let triangleSide = Float(smallestSide) * sqrt(2.0) * 0.5 let semiperimeter = (triangleSide * 2.0 + smallestSide) * 0.5 if semiperimeter == 0 { return 0 } let triangleArea = (smallestSide * (smallestSide * 0.5)) * 0.5 let radius = triangleArea / semiperimeter return UInt(floor(radius)) } /** Returns the next quadrant position with current animation order (see reverse attribute). :param: quadrant The given quadrant. :returns: The next quadrant position. */ private func nextQuadrant(quadrant: QuadrantPosition) -> QuadrantPosition { if (reverseAnimation) { return QuadrantPosition(rawValue: (quadrant.rawValue == 0 ? 3 : quadrant.rawValue - 1))! } else { return QuadrantPosition(rawValue: (quadrant.rawValue + 1) % 4)! } } /** Returns the max quadrant size for current combination of padding and dotsDistance. :returns: The quadrant size. */ private func quadrantSize() -> CGSize { let radius = CGFloat(dotRadius()) return CGSize(width: radius * 2.0, height: radius * 2.0) } /** Returns the origin of the given quadrant from its current quadrantPosition (animation do not change quadrantPosition, so it's the starting origin). :param: quadrant The given quadrant. :returns: The quadrant origin. */ private func quadrantOrigin(quadrant: QuadrantPosition) -> CGPoint{ let radius = CGFloat(dotRadius()) switch quadrant { case .UpLeft: return CGPoint(x: 0.0, y: 0.0) case .UpRight: return CGPoint(x: (self.insetLayer.bounds.width - radius * 2.0), y: 0) case .DownRight: return CGPoint(x: (self.insetLayer.bounds.width - radius * 2.0), y: (self.insetLayer.bounds.height - radius * 2.0)) case .DownLeft: return CGPoint(x: 0, y: (self.insetLayer.bounds.height - radius * 2.0)) } } /** Returns the position (anchor point 0.5, 0.5) of the given quadrant from its current quadrantPosition (animation do not change quadrantPosition, so it's the starting position). :param: quadrant The given quadrant. :returns: The quadrant position. */ private func quadrantPosition(quadrant: QuadrantPosition) -> CGPoint { let radius = CGFloat(dotRadius()) let origin = quadrantOrigin(quadrant) return CGPoint(x: origin.x + radius, y: origin.y + radius) } }
mit
e2ca47e9ad6c73fbb6972f828b032c09
34.112094
179
0.615275
4.691368
false
false
false
false
ingresse/ios-sdk
IngresseSDK/Model/WalletInfoHolder.swift
1
567
// // Copyright © 2019 Ingresse. All rights reserved. // public class WalletInfoHolder: NSObject, Decodable { public var document: String = "" public var name: String = "" enum CodingKeys: String, CodingKey { case document case name } public required init(from decoder: Decoder) throws { guard let container = try? decoder.container(keyedBy: CodingKeys.self) else { return } document = container.decodeKey(.document, ofType: String.self) name = container.decodeKey(.name, ofType: String.self) } }
mit
45ff568f63e770daffd5162306709afa
27.3
94
0.660777
4.492063
false
false
false
false
adamnemecek/AudioKit
Sources/AudioKit/Taps/AmplitudeTap.swift
1
3332
// Copyright AudioKit. All Rights Reserved. Revision History at http://github.com/AudioKit/AudioKit/ import Accelerate import AVFoundation /// Tap to do amplitude analysis on any node. /// start() will add the tap, and stop() will remove it. public class AmplitudeTap: BaseTap { private var amp: [Float] = Array(repeating: 0, count: 2) /// Detected amplitude (average of left and right channels) public var amplitude: Float { return amp.reduce(0, +) / 2 } /// Detected left channel amplitude public var leftAmplitude: Float { return amp[0] } /// Detected right channel amplitude public var rightAmplitude: Float { return amp[1] } /// Determines if the returned amplitude value is the left, right, or average of the two public var stereoMode: StereoMode = .center /// Determines if the returned amplitude value is the rms or peak value public var analysisMode: AnalysisMode = .rms private var handler: (Float) -> Void = { _ in } /// Initialize the amplitude /// /// - Parameters: /// - input: Node to analyze /// - bufferSize: Size of buffer to analyze /// - stereoMode: left, right, or average returned amplitudes /// - analysisMode: rms or peak returned amplitudes /// - handler: Code to call with new amplitudes public init(_ input: Node, bufferSize: UInt32 = 1_024, stereoMode: StereoMode = .center, analysisMode: AnalysisMode = .rms, handler: @escaping (Float) -> Void = { _ in }) { self.handler = handler self.stereoMode = stereoMode self.analysisMode = analysisMode super.init(input, bufferSize: bufferSize) } /// Overide this method to handle Tap in derived class /// - Parameters: /// - buffer: Buffer to analyze /// - time: Unused in this case override public func doHandleTapBlock(buffer: AVAudioPCMBuffer, at time: AVAudioTime) { guard let floatData = buffer.floatChannelData else { return } let channelCount = Int(buffer.format.channelCount) let length = UInt(buffer.frameLength) // n is the channel for n in 0 ..< channelCount { let data = floatData[n] if analysisMode == .rms { var rms: Float = 0 vDSP_rmsqv(data, 1, &rms, UInt(length)) amp[n] = rms } else { var peak: Float = 0 var index: vDSP_Length = 0 vDSP_maxvi(data, 1, &peak, &index, UInt(length)) amp[n] = peak } } switch stereoMode { case .left: handler(leftAmplitude) case .right: handler(rightAmplitude) case .center: handler(amplitude) } } /// Remove the tap on the input override public func stop() { super.stop() amp[0] = 0 amp[1] = 0 } } /// Tyep of analysis public enum AnalysisMode { /// Root Mean Squared case rms /// Peak case peak } /// How to deal with stereo signals public enum StereoMode { /// Use left channel case left /// Use right channel case right /// Use combined left and right channels case center }
mit
c8911eb0d32668ae3c0d1a61a072ddaa
28.486726
100
0.587635
4.466488
false
false
false
false
networkextension/SFSocket
SFSocket/stack/IPAddress.swift
1
4596
import Foundation public protocol IPAddress: CustomStringConvertible, Hashable { init?(fromString: String) init(fromBytesInNetworkOrder: [UInt8]) init(fromBytesInNetworkOrder: UnsafeRawPointer) var dataInNetworkOrder: Data { get } } open class IPv4Address: IPAddress { fileprivate var _in_addr: in_addr public init(fromInAddr: in_addr) { _in_addr = fromInAddr } public init(fromUInt32InHostOrder: UInt32) { _in_addr = in_addr(s_addr: NSSwapHostIntToBig(fromUInt32InHostOrder)) } required public init(fromBytesInNetworkOrder: UnsafeRawPointer) { _in_addr = fromBytesInNetworkOrder.load(as: in_addr.self) } required public init?(fromString: String) { var addr: in_addr = in_addr() var result: Int32 = 0 fromString.withCString { result = inet_pton(AF_INET, $0, &addr) } guard result == 1 else { return nil } _in_addr = addr presentation = fromString } required public init(fromBytesInNetworkOrder: [UInt8]) { var inaddr: in_addr! = nil fromBytesInNetworkOrder.withUnsafeBufferPointer { inaddr = UnsafeRawPointer($0.baseAddress!).load(as: in_addr.self) } _in_addr = inaddr } public lazy var presentation: String = { [unowned self] in var buffer = [Int8](repeating: 0, count: Int(INET_ADDRSTRLEN)) var p: UnsafePointer<Int8>! = nil withUnsafePointer(to: &self._in_addr) { (ptr: UnsafePointer<in_addr>) in p = inet_ntop(AF_INET, ptr, &buffer, UInt32(INET_ADDRSTRLEN)) } return String(cString: p) }() open var description: String { return "<IPv4Address \(presentation)>" } open var hashValue: Int { return _in_addr.s_addr.hashValue } open var UInt32InHostOrder: UInt32 { return NSSwapBigIntToHost(_in_addr.s_addr) } open var UInt32InNetworkOrder: UInt32 { return _in_addr.s_addr } open func withBytesInNetworkOrder(_ block: (UnsafeRawPointer) -> ()) { withUnsafePointer(to: &_in_addr) { block($0) } } open var dataInNetworkOrder: Data { return Data(bytes: &_in_addr, count: MemoryLayout.size(ofValue: _in_addr)) } } public class IPv6Address: IPAddress { public var dataInNetworkOrder: Data { return Data(bytes: &_in6_addr, count: MemoryLayout.size(ofValue: _in6_addr)) } public required init(fromBytesInNetworkOrder: UnsafeRawPointer) { _in6_addr = fromBytesInNetworkOrder.load(as: in6_addr.self) } public required init(fromBytesInNetworkOrder: [UInt8]) { var in6addr: in6_addr! = nil fromBytesInNetworkOrder.withUnsafeBytes { in6addr = $0.load(as: in6_addr.self) } _in6_addr = in6addr } fileprivate var _in6_addr: in6_addr public required init?(fromString: String) { var addr: in6_addr = in6_addr() var result: Int32 = 0 fromString.withCString { result = inet_pton(AF_INET6, $0, &addr) } guard result == 1 else { return nil } _in6_addr = addr presentation = fromString } lazy var presentation: String = { [unowned self] in var buffer = [Int8](repeating: 0, count: Int(INET6_ADDRSTRLEN)) var p: UnsafePointer<Int8>! = nil withUnsafePointer(to: &self._in6_addr) { (ptr: UnsafePointer<in6_addr>) in p = inet_ntop(AF_INET6, ptr, &buffer, UInt32(INET6_ADDRSTRLEN)) } return String(cString: p) }() open var description: String { return "<IPv6Address \(presentation)>" } open var hashValue: Int { return withUnsafeBytes(of: &_in6_addr.__u6_addr) { return $0.load(as: Int.self) ^ $0.load(fromByteOffset: MemoryLayout<Int>.size, as: Int.self) } } } public func == (left: IPv4Address, right: IPv4Address) -> Bool { return left.hashValue == right.hashValue } public func == (left: IPv6Address, right: IPv6Address) -> Bool { return left._in6_addr.__u6_addr.__u6_addr32 == right._in6_addr.__u6_addr.__u6_addr32 } public func ==<T: IPAddress> (left: T, right: T) -> Bool { switch (left, right) { case let (l as IPv4Address, r as IPv4Address): return l == r case let (l as IPv6Address, r as IPv6Address): return l == r default: return false } }
bsd-3-clause
80808fe61c96e73534eab3c40d1f9da7
28.844156
104
0.597258
3.931565
false
false
false
false
nathantannar4/InputBarAccessoryView
Sources/KeyboardManager/KeyboardNotification.swift
1
2679
// // KeyboardNotification.swift // InputBarAccessoryView // // Copyright © 2017-2020 Nathan Tannar. // // 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. // // Created by Nathan Tannar on 8/18/17. // import UIKit /// An object containing the key animation properties from NSNotification public struct KeyboardNotification { // MARK: - Properties /// The event that triggered the transition public let event: KeyboardEvent /// The animation length the keyboards transition public let timeInterval: TimeInterval /// The animation properties of the keyboards transition public let animationOptions: UIView.AnimationOptions /// iPad supports split-screen apps, this indicates if the notification was for the current app public let isForCurrentApp: Bool /// The keyboards frame at the start of its transition public var startFrame: CGRect /// The keyboards frame at the beginning of its transition public var endFrame: CGRect /// Requires that the `NSNotification` is based on a `UIKeyboard...` event /// /// - Parameter notification: `KeyboardNotification` public init?(from notification: NSNotification) { guard notification.event != .unknown else { return nil } self.event = notification.event self.timeInterval = notification.timeInterval ?? 0.25 self.animationOptions = notification.animationOptions self.isForCurrentApp = notification.isForCurrentApp ?? true self.startFrame = notification.startFrame ?? .zero self.endFrame = notification.endFrame ?? .zero } }
mit
2b60f01a610407c1973526a3dde7cf5a
39.575758
99
0.722181
4.950092
false
false
false
false
shepting/raspberry-swift
tank/Sources/RaspberryTank/Motor.swift
1
1602
import SwiftyGPIO private let i2cs = SwiftyGPIO.hardwareI2Cs(for:.RaspberryPi3)! private let i2c = i2cs[1] // Registers/etc. let ADDRESS: Int = 0x6f let ON_L: UInt8 = 0x06 let ON_H: UInt8 = 0x07 let OFF_L: UInt8 = 0x08 let OFF_H: UInt8 = 0x09 //"Sets a single PWM channel" func setPWM(_ channel: UInt8, _ on: UInt16, _ off: UInt16) { // print(" - Set PWM: \(channel) on: \(on) off: \(off)") i2c.writeByte(ADDRESS, command: ON_L + 4 * channel, value: UInt8(on & 0xFF)) i2c.writeByte(ADDRESS, command: ON_H + 4 * channel, value: UInt8(on >> 8)) i2c.writeByte(ADDRESS, command: OFF_L + 4 * channel, value: UInt8(off & 0xFF)) i2c.writeByte(ADDRESS, command: OFF_H + 4 * channel, value: UInt8(off >> 8)) } public struct Motor { let pin1: UInt8 let pin2: UInt8 let pwm: UInt8 let name: String enum level { case LOW case HIGH } public func backward() { // print(" \(name) ⇒ Backward") setPin(pin2, .LOW) setPin(pin1, .HIGH) } public func forward() { // print(" \(name) ⇒ Forward") setPin(pin1, .LOW) setPin(pin2, .HIGH) } public func stop() { // print(" \(name) ⇒ Stop") setPin(pin1, .LOW) setPin(pin2, .LOW) } public func setSpeed(_ speed: UInt16) { // print(" - Set speed: \(speed)") setPWM(pwm, 0, speed*16) } func setPin(_ pin: UInt8, _ level: level) { // print(" - Set pin: \(pin) \(level)") let value: UInt16 = (level == .HIGH) ? 4096 : 0 setPWM(pin, value, 0) } }
apache-2.0
39faceaca05243c89af50f9abaa32bad
25.163934
82
0.558897
3.00565
false
false
false
false
vapor-tools/vapor-jsonapi
Sources/VaporJsonApi/Json/JsonApiErrorObject.swift
1
2569
// // JsonApiErrorObject.swift // VaporJsonApi // // Created by Koray Koska on 01/05/2017. // // import Foundation import Vapor public class JsonApiErrorObject: JSONRepresentable { public let links: JsonApiErrorLinks? public let status: String? public let code: String? public let title: String? public let detail: String? public let source: JsonApiErrorSource? public let meta: JsonApiMeta? public init(id: String? = nil, links: JsonApiErrorLinks? = nil, status: String? = nil, code: String? = nil, title: String? = nil, detail: String? = nil, source: JsonApiErrorSource? = nil, meta: JsonApiMeta? = nil) { self.links = links self.status = status self.code = code self.title = title self.detail = detail self.source = source self.meta = meta } public func makeJSON() throws -> JSON { var json = try JSON(node: [:]) if let links = links { json["links"] = try links.makeJSON() } if let status = status { json["status"] = try JSON(node: status) } if let code = code { json["code"] = try JSON(node: code) } if let title = title { json["title"] = try JSON(node: title) } if let detail = detail { json["detail"] = try JSON(node: detail) } if let source = source { json["source"] = try source.makeJSON() } if let meta = meta { json["meta"] = try meta.makeJSON() } return json } } public class JsonApiErrorLinks: JSONRepresentable { public let about: URL public init(about: URL) { self.about = about } public func makeJSON() throws -> JSON { return try JSON(node: [ "about": about.absoluteString ]) } } public class JsonApiErrorSource: JSONRepresentable { public let pointer: String? public let parameter: String? init(pointer: String? = nil, parameter: String? = nil) { self.pointer = pointer self.parameter = parameter } public func makeJSON() throws -> JSON { var json = try JSON(node: [:]) if let pointer = pointer { json["pointer"] = try JSON(node: pointer) } if let parameter = parameter { json["parameter"] = try JSON(node: parameter) } return json } }
mit
b1a7adf4ada00b3a8b09f6b9850bdaba
23.466667
60
0.539899
4.421687
false
false
false
false
IrvinDitz/Beagle
Beagle/Beagle/AppDelegate.swift
1
4599
// // AppDelegate.swift // Beagle // // Created by Andriy Dzedolik on 7/Sep/17. // Copyright © 2017 Arnor Labs. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. 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 invalidate graphics rendering callbacks. 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 active 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:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var persistentContainer: NSPersistentContainer = { /* The persistent container for the application. This implementation creates and returns a container, having loaded the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. */ let container = NSPersistentContainer(name: "Beagle") container.loadPersistentStores(completionHandler: { (storeDescription, error) in if let error = error as NSError? { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. /* Typical reasons for an error here include: * The parent directory does not exist, cannot be created, or disallows writing. * The persistent store is not accessible, due to permissions or data protection when the device is locked. * The device is out of space. * The store could not be migrated to the current model version. Check the error message to determine what the actual problem was. */ fatalError("Unresolved error \(error), \(error.userInfo)") } }) return container }() // MARK: - Core Data Saving support func saveContext () { let context = persistentContainer.viewContext if context.hasChanges { do { try context.save() } catch { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError fatalError("Unresolved error \(nserror), \(nserror.userInfo)") } } } }
mit
61964dc40e85b55484f116d7e0256409
48.44086
285
0.684428
5.84244
false
false
false
false
hayashi311/iosdcjp2016app
iOSApp/Pods/APIKit/Sources/BodyParametersType/NSData+NSInputStream.swift
2
1033
import Foundation extension NSData { enum InputStreamError: ErrorType { case InvalidDataCapacity(Int) case UnreadableStream(NSInputStream) } convenience init(inputStream: NSInputStream, capacity: Int = Int(UInt16.max)) throws { guard let data = NSMutableData(capacity: capacity) else { throw InputStreamError.InvalidDataCapacity(capacity) } let bufferSize = min(Int(UInt16.max), capacity) let buffer = UnsafeMutablePointer<UInt8>.alloc(bufferSize) var readSize: Int repeat { readSize = inputStream.read(buffer, maxLength: bufferSize) switch readSize { case let x where x > 0: data.appendBytes(buffer, length: readSize) case let x where x < 0: throw InputStreamError.UnreadableStream(inputStream) default: break } } while readSize > 0 buffer.dealloc(bufferSize) self.init(data: data) } }
mit
3b8ce73f67008ab13f3c1a4253edb57d
26.184211
90
0.605034
5.139303
false
false
false
false
dongdonggaui/FakeWeChat
FakeWeChat/src/ViewControllers/Contacts/ContactsViewController.swift
1
3041
// // ContactsViewController.swift // FakeWeChat // // Created by huangluyang on 15/12/30. // Copyright © 2015年 huangluyang. All rights reserved. // import UIKit class ContactsViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { // MARK: - Life Cycle override func awakeFromNib() { super.awakeFromNib() title = NSLocalizedString("通讯录", comment: "Contacts") tabBarItem.image = UIImage.fontAwesomeIconWithName(.Users, textColor: UIColor.blackColor(), size: CGSizeMake(30, 30)) let rightButton = UIButton(type: .Custom) let addIcon = UIImage.fontAwesomeIconWithName(.UserPlus, textColor: UIColor.whiteColor(), size: CGSizeMake(30, 30)) rightButton.setImage(addIcon, forState: .Normal) rightButton.sizeToFit() let rightItem = UIBarButtonItem(customView: rightButton) navigationItem.rightBarButtonItem = rightItem } override func viewDidLoad() { super.viewDidLoad() tableView.rowHeight = 53 } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Properties @IBOutlet weak var tableView: UITableView! // MARK: - Table View func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 26 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 1 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! ContactTableViewCell self.configureCell(cell, atIndexPath: indexPath) return cell } func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return "\(Character(UnicodeScalar(65 + section)))" } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { } func configureCell(cell: ContactTableViewCell, atIndexPath indexPath: NSIndexPath) { cell.nameLabel.text = "某某某" let avatar = AppContext.avatarPlaceholder() cell.avatarImageView.image = avatar } func sectionIndexTitlesForTableView(tableView: UITableView) -> [String]? { var titles: [String] = [] for section in 0..<26 { titles += ["\(Character(UnicodeScalar(65 + section)))"] } return titles } func tableView(tableView: UITableView, sectionForSectionIndexTitle title: String, atIndex index: Int) -> Int { let char = title.unicodeScalars.first as UnicodeScalar! let index = char.value - 65 return Int(index) } } class ContactTableViewCell: UITableViewCell { @IBOutlet weak var avatarImageView: UIImageView! @IBOutlet weak var nameLabel: UILabel! }
mit
36232abada27153f4362a83b0589c9a3
31.891304
125
0.667217
5.403571
false
false
false
false
asashin227/LNKLabel
LNKLabel/Classes/LinkLabel.swift
1
4509
// // LinkLabel.swift // LinkLabel // // Created by Asakura Shinsuke on 2017/09/13. // Copyright © 2017年 Asakura Shinsuke. All rights reserved. // import UIKit public protocol LNKLabelDelegate: NSObjectProtocol { func didTaped(label: LNKLabel, pattern: Pattern, matchText: String, range: NSRange) } public class LNKLabel: UILabel { fileprivate var matcher = Matcher() public var delegate: LNKLabelDelegate? override public var text: String? { didSet { reloadAttribute() } } public var linkPatterns: [Pattern]? { didSet { reloadAttribute() } } public var linkColor: UIColor = .blue { didSet { reloadAttribute() } } convenience public init() { self.init(frame: .zero) } override public init(frame: CGRect) { super.init(frame: frame) self.addTouchGesture() } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func addTouchGesture() { self.isUserInteractionEnabled = true let gesture = UITapGestureRecognizer(target: self, action: #selector(LNKLabel.didTaped(gesture:))) gesture.numberOfTapsRequired = 1 self.addGestureRecognizer(gesture) } } extension LNKLabel { public func hitLink(at point: CGPoint) -> (touchedText: String, textRange: NSRange, pattern: Pattern)? { guard let text = text else { return nil } for match in matcher.matches { for link in match.value { let glyphRect = rect(of: link.0, in: text, range: link.1) if glyphRect == .zero { continue } if glyphRect.contains(point) { return (link.0, link.1, match.key) } } } return nil } } extension LNKLabel { private func reloadAttribute() { guard let text = text, let linkPatterns = linkPatterns else { return } self.attributedText = linkAttribute(for: text, patterns: linkPatterns) } private func linkAttribute(for text: String, patterns: [Pattern]) -> NSAttributedString? { matcher.text = text matcher.patterms = linkPatterns var attribute = NSMutableAttributedString(string: text) for match in matcher.matches { for link in match.value { addLinkAttribute(for: &attribute, plainText: text, targetText: link.0, range: link.1) } } return attribute } private func addLinkAttribute(for attributes: inout NSMutableAttributedString, plainText: String, targetText: String, range: NSRange) { attributes.addAttributes([NSAttributedStringKey.font : self.font], range: NSMakeRange(0, plainText.count)) attributes.addAttributes([NSAttributedStringKey.underlineStyle : NSUnderlineStyle.styleSingle.rawValue, NSAttributedStringKey.underlineColor : linkColor, NSAttributedStringKey.foregroundColor : linkColor], range: range) } } extension LNKLabel { @objc private func didTaped(gesture: UIGestureRecognizer) { let touchPoint = gesture.location(in: self) guard let res = hitLink(at: touchPoint) else { return } self.didTaped(touchedText: res.touchedText, touchedRange: res.textRange, pattern: res.pattern) } private func rect(of text: String, in plainText: String, range: NSRange) -> CGRect { guard let attributedText = self.attributedText else { return .zero } let textStorage = NSTextStorage(attributedString: attributedText) let layoutManager = NSLayoutManager() textStorage.addLayoutManager(layoutManager) let textContainer = NSTextContainer(size: self.frame.size) layoutManager.addTextContainer(textContainer) textContainer.lineFragmentPadding = 0 let toRange = range let glyphRange = layoutManager.glyphRange(forCharacterRange: toRange, actualCharacterRange: nil) let glyphRect = layoutManager.boundingRect(forGlyphRange: glyphRange, in: textContainer) return glyphRect } private func didTaped(touchedText: String, touchedRange: NSRange, pattern: Pattern) { guard let delegate = delegate else { return } delegate.didTaped(label: self, pattern: pattern, matchText: touchedText, range: touchedRange) } }
mit
8c8972468f186512e4a6e6472602fc85
34.761905
139
0.644918
4.957096
false
false
false
false
mbigatti/StatusApp
StatusApp/ColorButtonsControl.swift
1
3286
// // ColorsButtonView.swift // StatusApp // // Created by Massimiliano Bigatti on 25/09/14. // Copyright (c) 2014 Massimiliano Bigatti. All rights reserved. // import UIKit /// standard button size (width and height are equal as the button is a circle) private let buttonWide = 44 /** Color buttons control. Manages a strip of five circular buttons, each one represent a color supported by the app. */ class ColorButtonsControl : UIControl { // MARK: - Public Properties /// current selected colors var currentColor = StatusEntityColor.AZURE /// array of available buttons let buttons : [CircularButton] = [ CircularButton(frame: CGRectZero), CircularButton(frame: CGRectZero), CircularButton(frame: CGRectZero), CircularButton(frame: CGRectZero), CircularButton(frame: CGRectZero) ]; // MARK: - Lifecycle override init(frame: CGRect) { super.init(frame: frame) commonInit() } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } /// common initialization private func commonInit() { var index = 0 for button in buttons { button.borderWidth = 2 button.normalColor = StatusEntityColor(rawValue: index)!.color() button.tag = index button.addTarget(self, action: "buttonTapped:", forControlEvents: .TouchUpInside) addSubview(button) index++ } selectCurrentButton(buttons[0]) } // MARK: - UIView /** Layout the buttons leaving equal horizontal spacing between buttons and between buttons and containing view. */ override func layoutSubviews() { let availableWidth = bounds.size.width let usedWidth = CGFloat(buttonWide * buttons.count) let remainingSpace = availableWidth - usedWidth let spacingX = Int(floor(remainingSpace / CGFloat(buttons.count + 1))) var x = spacingX for button in buttons { let rect = CGRect(x: Int(x), y: 0, width: buttonWide, height: buttonWide) button.frame = rect x += spacingX + buttonWide } } // MARK: - Actions /** Called when user taps on a button. The button is marked as selected, the current color property is updated and an event is raised to notify the containing view controller that content has changed. */ @objc private func buttonTapped(sender : CircularButton) { selectCurrentButton(sender) currentColor = StatusEntityColor(rawValue: sender.tag)! sendActionsForControlEvents(.ValueChanged); } // MARK: - Privates /** Update appearance of selected button darkening the border color. :param: sender the `CircularButton` to mark as selected */ private func selectCurrentButton(sender: CircularButton) { for button in buttons { button.borderColor = UIColor.blackColor().colorWithAlphaComponent(0.25) } sender.borderColor = UIColor.blackColor().colorWithAlphaComponent(0.5) } }
mit
909d7843ef257c56fb7bd701e27ab697
28.348214
204
0.619294
5.11042
false
false
false
false
zzgo/v2ex
v2ex/Pods/RAMAnimatedTabBarController/RAMAnimatedTabBarController/Animations/BounceAnimation/RAMBounceAnimation.swift
9
3550
// RAMBounceAnimation.swift // // Copyright (c) 11/10/14 Ramotion Inc. (http://ramotion.com) // // 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 /// The RAMBounceAnimation class provides bounce animation. open class RAMBounceAnimation : RAMItemAnimation { /** Start animation, method call when UITabBarItem is selected - parameter icon: animating UITabBarItem icon - parameter textLabel: animating UITabBarItem textLabel */ override open func playAnimation(_ icon : UIImageView, textLabel : UILabel) { playBounceAnimation(icon) textLabel.textColor = textSelectedColor } /** Start animation, method call when UITabBarItem is unselected - parameter icon: animating UITabBarItem icon - parameter textLabel: animating UITabBarItem textLabel - parameter defaultTextColor: default UITabBarItem text color - parameter defaultIconColor: default UITabBarItem icon color */ override open func deselectAnimation(_ icon : UIImageView, textLabel : UILabel, defaultTextColor : UIColor, defaultIconColor: UIColor) { textLabel.textColor = defaultTextColor if let iconImage = icon.image { let renderMode = defaultIconColor.cgColor.alpha == 0 ? UIImageRenderingMode.alwaysOriginal : UIImageRenderingMode.alwaysTemplate let renderImage = iconImage.withRenderingMode(renderMode) icon.image = renderImage icon.tintColor = defaultIconColor } } /** Method call when TabBarController did load - parameter icon: animating UITabBarItem icon - parameter textLabel: animating UITabBarItem textLabel */ override open func selectedState(_ icon : UIImageView, textLabel : UILabel) { textLabel.textColor = textSelectedColor if let iconImage = icon.image { let renderImage = iconImage.withRenderingMode(.alwaysTemplate) icon.image = renderImage icon.tintColor = iconSelectedColor } } func playBounceAnimation(_ icon : UIImageView) { let bounceAnimation = CAKeyframeAnimation(keyPath: Constants.AnimationKeys.Scale) bounceAnimation.values = [1.0 ,1.4, 0.9, 1.15, 0.95, 1.02, 1.0] bounceAnimation.duration = TimeInterval(duration) bounceAnimation.calculationMode = kCAAnimationCubic icon.layer.add(bounceAnimation, forKey: nil) if let iconImage = icon.image { let renderImage = iconImage.withRenderingMode(.alwaysTemplate) icon.image = renderImage icon.tintColor = iconSelectedColor } } }
mit
48adb32f3552d60c317091a804747573
38.010989
138
0.736056
5.159884
false
false
false
false
asiainfomobile/iOS-style-guide
demo/demo/demo/Views/DetailTextView.swift
2
1882
// // DetailTextView.swift // demo // // Created by admin on 3/2/16. // Copyright © 2016 __ASIAINFO__. All rights reserved. // import UIKit class DetailTextView: UIView { @IBOutlet var view: UIView! @IBOutlet weak var label: UILabel! @IBOutlet weak var button: UIButton! @IBOutlet weak var lessOrEqualToMinConstraint: NSLayoutConstraint! @IBOutlet weak var greaterOrEqualToMinConstraint: NSLayoutConstraint! @IBOutlet weak var constraintBetweenLabelAndSelf: NSLayoutConstraint! var text: String? = nil { didSet { label.text = text layoutIfNeeded() } } var expand: Bool = false { didSet { button.setTitle(expand ? "Hide More" : "Show More", forState: .Normal) greaterOrEqualToMinConstraint.priority = expand ? 999 : UILayoutPriorityDefaultLow lessOrEqualToMinConstraint.priority = expand ? UILayoutPriorityDefaultLow : 999 layoutIfNeeded() } } var hideMoreButton: Bool = false { willSet { if hideMoreButton != newValue { if newValue { constraintBetweenLabelAndSelf.priority = 999 button.hidden = true } else { constraintBetweenLabelAndSelf.priority = UILayoutPriorityDefaultLow button.hidden = false } layoutIfNeeded() } } } override init(frame: CGRect) { super.init(frame: frame) self.setupNibView() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.setupNibView() } func setupNibView() { NSBundle.mainBundle().loadNibNamed("DetailTextView", owner: self, options: nil) self.addSubview(self.view) self.view.snp_makeConstraints { (make) -> Void in make.edges.equalTo(self) } } override func layoutSubviews() { super.layoutSubviews() if CGRectGetHeight(label.frame) < 73 { hideMoreButton = true } else { hideMoreButton = false } } @IBAction func buttonPressed(sender: UIButton) { expand = !expand } }
mit
964f72b63a103bb07059997e8c521b9c
21.939024
85
0.705476
3.659533
false
false
false
false
sonnygauran/trailer
PocketTrailer/AboutTrailerViewController.swift
1
844
import SafariServices final class AboutTrailerViewController: UIViewController { @IBOutlet weak var versionNumber: UILabel! @IBOutlet weak var licenseText: UITextView! override func viewDidLoad() { super.viewDidLoad() versionNumber.text = versionString() } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) licenseText.contentOffset = CGPointZero licenseText.textContainerInset = UIEdgeInsetsMake(0, 10, 10, 10) } @IBAction func linkSelected() { let s = SFSafariViewController(URL: NSURL(string: "https://github.com/ptsochantaris/trailer")!) s.view.tintColor = self.view.tintColor self.presentViewController(s, animated: true, completion: nil) } @IBAction func doneSelected() { if app.preferencesDirty { app.startRefresh() } dismissViewControllerAnimated(true, completion: nil) } }
mit
9bf06e192c01f5a5e6c98f7a7c5ea493
28.103448
97
0.767773
3.981132
false
false
false
false
stripe/stripe-ios
StripeIdentity/StripeIdentity/Source/NativeComponents/ViewControllers/SelfieCaptureViewController.swift
1
16023
// // SelfieCaptureViewController.swift // StripeIdentity // // Created by Mel Ludowise on 4/27/22. // Copyright © 2022 Stripe, Inc. All rights reserved. // import AVKit @_spi(STP) import StripeCameraCore @_spi(STP) import StripeCore @_spi(STP) import StripeUICore import UIKit @available(iOSApplicationExtension, unavailable) final class SelfieCaptureViewController: IdentityFlowViewController { typealias SelfieImageScanningSession = ImageScanningSession< EmptyClassificationType, [FaceScannerInputOutput], FaceCaptureData, FaceScannerOutput > typealias State = SelfieImageScanningSession.State // MARK: View Models override var warningAlertViewModel: WarningAlertViewModel? { switch imageScanningSession.state { case .saving, .scanned: return .init( titleText: .Localized.unsavedChanges, messageText: STPLocalizedString( "Your selfie images have not been saved. Do you want to leave?", "Text for message of warning alert" ), acceptButtonText: String.Localized.continue, declineButtonText: String.Localized.cancel ) case .initial, .scanning, .timeout, .noCameraAccess, .cameraError: return nil } } var flowViewModel: IdentityFlowView.ViewModel { return .init( headerViewModel: .init( backgroundColor: .systemBackground, headerType: .plain, titleText: STPLocalizedString( "Selfie captures", "Title of selfie capture screen" ) ), contentViewModel: .init( view: selfieCaptureView, inset: .zero ), buttons: buttonViewModels ) } var buttonViewModels: [IdentityFlowView.ViewModel.Button] { switch imageScanningSession.state { case .initial, .scanning: return [.continueButton(state: .disabled, didTap: {})] case .saving: return [.continueButton(state: .loading, didTap: {})] case .scanned(_, let faceCaptureData): return [ .continueButton { [weak self] in self?.saveDataAndTransitionToNextScreen(faceCaptureData: faceCaptureData) } ] case .noCameraAccess: return [ .init( text: String.Localized.app_settings, didTap: { [weak self] in self?.imageScanningSession.appSettingsHelper.openAppSettings() } ) ] case .cameraError: return [ .init( text: String.Localized.close, didTap: { [weak self] in self?.dismiss(animated: true) } ) ] case .timeout: return [ .init( text: .Localized.try_again_button, didTap: { [weak self] in self?.imageScanningSession.startScanning() } ) ] } } var selfieCaptureViewModel: SelfieCaptureView.ViewModel { switch imageScanningSession.state { case .initial: return .scan( .init( state: .blank, instructionalText: SelfieCaptureViewController.initialInstructionText ) ) case .scanning(_, let collectedSamples): // Show a flash animation when capturing the first sample image return .scan( .init( state: .videoPreview( imageScanningSession.cameraSession, showFlashAnimation: collectedSamples.count == 1 ), instructionalText: collectedSamples.isEmpty ? SelfieCaptureViewController.initialInstructionText : SelfieCaptureViewController.capturingInstructionText ) ) case .scanned(_, let faceCaptureData), .saving(_, let faceCaptureData): return .scan( .init( state: .scanned( faceCaptureData.toArray.map { UIImage(cgImage: $0.image) }, consentHTMLText: apiConfig.trainingConsentText, consentHandler: { [weak self] consentSelection in self?.consentSelection = consentSelection }, openURLHandler: { [weak self] url in self?.openInSafariViewController(url: url) } ), instructionalText: SelfieCaptureViewController.scannedInstructionText ) ) case .noCameraAccess: return .error( .init( titleText: .Localized.noCameraAccessErrorTitleText, bodyText: .Localized.noCameraAccessErrorBodyText ) ) case .cameraError: return .error( .init( titleText: .Localized.cameraUnavailableErrorTitleText, bodyText: .Localized.cameraUnavailableErrorBodyText ) ) case .timeout: return .error( .init( titleText: .Localized.timeoutErrorTitleText, bodyText: .Localized.timeoutErrorBodyText ) ) } } // MARK: Views let selfieCaptureView = SelfieCaptureView() // MARK: Instance Properties let apiConfig: StripeAPI.VerificationPageStaticContentSelfiePage let imageScanningSession: SelfieImageScanningSession let selfieUploader: SelfieUploaderProtocol /// The user's consent selection private var consentSelection: Bool? = false /// This timer will be nil if it's time to take another sample from the camera feed private var sampleTimer: Timer? // MARK: Init init( apiConfig: StripeAPI.VerificationPageStaticContentSelfiePage, imageScanningSession: SelfieImageScanningSession, selfieUploader: SelfieUploaderProtocol, sheetController: VerificationSheetControllerProtocol ) { self.apiConfig = apiConfig self.imageScanningSession = imageScanningSession self.selfieUploader = selfieUploader super.init(sheetController: sheetController, analyticsScreenName: .selfieCapture) imageScanningSession.setDelegate(delegate: self) } convenience init( initialState: State = .initial, apiConfig: StripeAPI.VerificationPageStaticContentSelfiePage, sheetController: VerificationSheetControllerProtocol, cameraSession: CameraSessionProtocol, selfieUploader: SelfieUploaderProtocol, anyFaceScanner: AnyFaceScanner, concurrencyManager: ImageScanningConcurrencyManagerProtocol? = nil, cameraPermissionsManager: CameraPermissionsManagerProtocol = CameraPermissionsManager .shared, appSettingsHelper: AppSettingsHelperProtocol = AppSettingsHelper.shared, notificationCenter: NotificationCenter = .default ) { self.init( apiConfig: apiConfig, imageScanningSession: SelfieImageScanningSession( initialState: initialState, initialCameraPosition: .front, autocaptureTimeout: TimeInterval(milliseconds: apiConfig.autocaptureTimeout), cameraSession: cameraSession, scanner: anyFaceScanner, concurrencyManager: concurrencyManager ?? ImageScanningConcurrencyManager( analyticsClient: sheetController.analyticsClient ), cameraPermissionsManager: cameraPermissionsManager, appSettingsHelper: appSettingsHelper ), selfieUploader: selfieUploader, sheetController: sheetController ) updateUI() } required init?( coder: NSCoder ) { fatalError("init(coder:) has not been implemented") } // MARK: - UIViewController override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) imageScanningSession.startIfNeeded() } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) imageScanningSession.stopScanning() } override func viewWillTransition( to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator ) { super.viewWillTransition(to: size, with: coordinator) imageScanningSession.cameraSession.setVideoOrientation( orientation: UIDevice.current.orientation.videoOrientation ) } } // MARK: - Helpers @available(iOSApplicationExtension, unavailable) extension SelfieCaptureViewController { func updateUI() { configure( backButtonTitle: STPLocalizedString( "Selfie", "Back button title for returning to the selfie screen" ), viewModel: flowViewModel ) selfieCaptureView.configure( with: selfieCaptureViewModel, analyticsClient: sheetController?.analyticsClient ) } func startSampleTimer() { // The sample timer will be nil when it's time to take another sample // image from the camera feed in // `imageScanningSessionShouldScanCameraOutput` sampleTimer?.invalidate() sampleTimer = Timer.scheduledTimer( withTimeInterval: TimeInterval(milliseconds: apiConfig.sampleInterval), repeats: false, block: { [weak self] _ in self?.sampleTimer = nil } ) } func stopSampleTimer() { sampleTimer?.invalidate() sampleTimer = nil } func saveDataAndTransitionToNextScreen( faceCaptureData: FaceCaptureData ) { imageScanningSession.setStateSaving( expectedClassification: .empty, capturedData: faceCaptureData ) self.sheetController?.saveSelfieFileDataAndTransition( from: analyticsScreenName, selfieUploader: selfieUploader, capturedImages: faceCaptureData, trainingConsent: consentSelection == true ) { [weak self] in self?.imageScanningSession.setStateScanned(capturedData: faceCaptureData) } } } // MARK: - ImageScanningSessionDelegate @available(iOSApplicationExtension, unavailable) extension SelfieCaptureViewController: ImageScanningSessionDelegate { func imageScanningSession( _ scanningSession: SelfieImageScanningSession, cameraDidError error: Error ) { guard let sheetController = sheetController else { return } sheetController.analyticsClient.logCameraError( sheetController: sheetController, error: error ) } func imageScanningSession( _ scanningSession: SelfieImageScanningSession, didRequestCameraAccess isGranted: Bool? ) { guard let sheetController = sheetController else { return } sheetController.analyticsClient.logCameraPermissionsChecked( sheetController: sheetController, isGranted: isGranted ) } func imageScanningSessionShouldScanCameraOutput( _ scanningSession: SelfieImageScanningSession ) -> Bool { return sampleTimer == nil } func imageScanningSessionDidUpdate(_ scanningSession: SelfieImageScanningSession) { updateUI() // Notify accessibility engine that the layout has changed UIAccessibility.post(notification: .layoutChanged, argument: nil) } func imageScanningSessionDidReset(_ scanningSession: SelfieImageScanningSession) { selfieUploader.reset() } func imageScanningSession( _ scanningSession: SelfieImageScanningSession, didTimeoutForClassification classification: EmptyClassificationType ) { sheetController?.analyticsClient.logSelfieCaptureTimeout() } func imageScanningSession( _ scanningSession: SelfieImageScanningSession, willStartScanningForClassification classification: EmptyClassificationType ) { // Focus the accessibility VoiceOver back onto the capture view UIAccessibility.post(notification: .layoutChanged, argument: self.selfieCaptureView) // Increment analytics counter sheetController?.analyticsClient.countDidStartSelfieScan() } func imageScanningSessionWillStopScanning(_ scanningSession: SelfieImageScanningSession) { scanningSession.concurrencyManager.getPerformanceMetrics(completeOn: .main) { [weak sheetController] averageFPS, numFramesScanned in guard let averageFPS = averageFPS else { return } sheetController?.analyticsClient.logAverageFramesPerSecond( averageFPS: averageFPS, numFrames: numFramesScanned, scannerName: .selfie ) } sheetController?.analyticsClient.logModelPerformance( mlModelMetricsTrackers: scanningSession.scanner.mlModelMetricsTrackers ) } func imageScanningSessionDidStopScanning(_ scanningSession: SelfieImageScanningSession) { stopSampleTimer() } func imageScanningSessionDidScanImage( _ scanningSession: SelfieImageScanningSession, image: CGImage, scannerOutput: FaceScannerOutput, exifMetadata: CameraExifMetadata?, expectedClassification: EmptyClassificationType ) { // Extract already scanned faces if there are any var collectedSamples: [FaceScannerInputOutput] = [] if case .scanning(_, let _collectedSamples) = scanningSession.state { collectedSamples = _collectedSamples } // If no valid face was found, update state to scanning guard scannerOutput.isValid else { scanningSession.updateScanningState(collectedSamples) return } // Update the number of collected samples collectedSamples.append( .init( image: image, scannerOutput: scannerOutput, cameraExifMetadata: exifMetadata ) ) // Reset timeout timer scanningSession.stopTimeoutTimer() // If we've found the required number of samples, upload images and // finish scanning. Otherwise, keep scanning guard collectedSamples.count == apiConfig.numSamples, let faceCaptureData = FaceCaptureData(samples: collectedSamples) else { // Reset timers scanningSession.startTimeoutTimer() startSampleTimer() scanningSession.updateScanningState(collectedSamples) return } selfieUploader.uploadImages(faceCaptureData) scanningSession.setStateScanned(capturedData: faceCaptureData) } } // MARK: - IdentityDataCollecting @available(iOSApplicationExtension, unavailable) extension SelfieCaptureViewController: IdentityDataCollecting { var collectedFields: Set<StripeAPI.VerificationPageFieldType> { return [.face] } func reset() { imageScanningSession.reset() clearCollectedFields() } }
mit
7f854ea006dbbb73cfb54834375755d7
33.381974
94
0.60935
6.330304
false
false
false
false
wikimedia/wikipedia-ios
Wikipedia/Code/DiffHeaderExtendedView.swift
1
3956
import UIKit protocol DiffHeaderActionDelegate: AnyObject { func tappedUsername(username: String) func tappedRevision(revisionID: Int) } class DiffHeaderExtendedView: UIView { @IBOutlet var contentView: UIView! @IBOutlet var stackView: UIStackView! @IBOutlet var summaryView: DiffHeaderSummaryView! @IBOutlet var editorView: DiffHeaderEditorView! @IBOutlet var compareView: DiffHeaderCompareView! @IBOutlet var divViews: [UIView]! @IBOutlet var summaryDivView: UIView! @IBOutlet var editorDivView: UIView! @IBOutlet var compareDivView: UIView! private var viewModel: DiffHeaderViewModel? weak var delegate: DiffHeaderActionDelegate? { get { return editorView.delegate } set { editorView.delegate = newValue compareView.delegate = newValue } } override init(frame: CGRect) { super.init(frame: frame) commonInit() } required init?(coder: NSCoder) { super.init(coder: coder) commonInit() } private func commonInit() { Bundle.main.loadNibNamed(DiffHeaderExtendedView.wmf_nibName(), owner: self, options: nil) addSubview(contentView) contentView.frame = self.bounds contentView.autoresizingMask = [.flexibleHeight, .flexibleWidth] } func configureHeight(beginSquishYOffset: CGFloat, scrollYOffset: CGFloat) { guard let viewModel = viewModel else { return } switch viewModel.headerType { case .compare: compareView.configureHeight(beginSquishYOffset: beginSquishYOffset, scrollYOffset: scrollYOffset) default: break } } func update(_ new: DiffHeaderViewModel) { self.viewModel = new switch new.headerType { case .compare(let compareViewModel, _): summaryView.isHidden = true summaryDivView.isHidden = true editorView.isHidden = true editorDivView.isHidden = true compareView.isHidden = false compareDivView.isHidden = false compareView.update(compareViewModel) case .single(let editorViewModel, let summaryViewModel): editorView.isHidden = false editorDivView.isHidden = false compareView.isHidden = true compareDivView.isHidden = true if let summary = summaryViewModel.summary, summary.wmf_hasNonWhitespaceText { summaryView.isHidden = false summaryDivView.isHidden = false summaryView.update(summaryViewModel) } else { summaryView.isHidden = true summaryDivView.isHidden = true } editorView.update(editorViewModel) } } override func point(inside point: CGPoint, with event: UIEvent?) -> Bool { let summaryConvertedPoint = self.convert(point, to: summaryView) if summaryView.point(inside: summaryConvertedPoint, with: event) { return true } let editorConvertedPoint = self.convert(point, to: editorView) if editorView.point(inside: editorConvertedPoint, with: event) { return true } let compareConvertedPoint = self.convert(point, to: compareView) if compareView.point(inside: compareConvertedPoint, with: event) { return true } return false } } extension DiffHeaderExtendedView: Themeable { func apply(theme: Theme) { backgroundColor = theme.colors.paperBackground summaryView.apply(theme: theme) editorView.apply(theme: theme) compareView.apply(theme: theme) for view in divViews { view.backgroundColor = theme.colors.chromeShadow } } }
mit
6e04591e940c8dcde589038582f73051
30.903226
109
0.619565
5.449036
false
false
false
false
iCodeForever/ifanr
ifanr/ifanr/Controllers/DetailController/IFDetailsController.swift
1
5385
// // IFDetailsController.swift // ifanr // // Created by sys on 16/7/17. // Copyright © 2016年 ifanrOrg. All rights reserved. // import UIKit import WebKit import SnapKit class IFDetailsController: UIViewController{ var shadowView: UIView? var shareView: ShareView? //MARK:-----life cycle----- override func viewDidLoad() { super.viewDidLoad() self.view.addSubview(self.wkWebView) self.view.addSubview(self.toolBar) self.view.addSubview(self.headerBack) self.setupLayout() self.toolBar.commentButton.showIcon(model?.comments ?? nil) self.toolBar.praiseButton.setTitle(String(format:"点赞(%d)",(model?.like)!), for: UIControlState()) self.wkWebView.load(URLRequest(url: URL(string: (self.model?.link)!)!)) } convenience init(model: CommonModel, naviTitle: String) { self.init() self.model = model self.naviTitle = naviTitle headerBack.title = naviTitle } //MARK:-----Custom Function----- fileprivate func setupLayout() { self.wkWebView.snp.makeConstraints { (make) in make.left.right.top.equalTo(self.view); make.bottom.equalTo(self.view) } self.toolBar.snp.makeConstraints { (make) in make.left.right.bottom.equalTo(self.view) make.height.equalTo(50) } self.headerBack.snp.makeConstraints { (make) in make.left.right.equalTo(self.view) self.headerTopConstraint = make.top.equalTo(self.view).constraint make.height.equalTo(50) } } override var prefersStatusBarHidden : Bool { return true } //MARK:-----Getter and Setter----- fileprivate var lastPosition: CGFloat = 0 fileprivate var headerTopConstraint: Constraint? = nil fileprivate var model: CommonModel? fileprivate var naviTitle: String! /// wkWebView fileprivate lazy var wkWebView: WKWebView = { let wkWebView: WKWebView = WKWebView() wkWebView.navigationDelegate = self wkWebView.scrollView.delegate = self return wkWebView }() /// 底部工具栏 fileprivate lazy var toolBar: BottomToolsBar = { let toolBar: BottomToolsBar = BottomToolsBar() toolBar.delegate = self return toolBar }() /// 顶部返回栏 fileprivate lazy var headerBack: HeaderBackView = { let headerBack: HeaderBackView = HeaderBackView(title: "") headerBack.delegate = self return headerBack }() } //MARK:-----ShareViewDelegate----- extension IFDetailsController: ShareViewDelegate, shareResuable { func weixinShareButtonDidClick() { shareToFriend((model?.excerpt)!, shareImageUrl: (model?.image)!, shareUrl: (model?.link)!, shareTitle: (model?.title)!) } func friendsCircleShareButtonDidClick() { shareToFriendsCircle((model?.excerpt)!, shareTitle: (model?.title)!, shareUrl: (model?.link)!, shareImageUrl: (model?.image)!) } func shareMoreButtonDidClick() { hiddenShareView() } } //MARK:-----ToolBarDelegate----- extension IFDetailsController: ToolBarDelegate { func editCommentDidClick() { debugPrint("editCommon") } func praiseButtonDidClick() { if self.toolBar.praiseButton.isSelected { self.toolBar.praiseButton.isSelected = false } else { self.toolBar.praiseButton.isSelected = true } } func shareButtonDidClick() { self.showShareView() } func commentButtonDidClick() { let ifDetailCommentVC = IFDetailCommentVC(id: model?.ID) self.navigationController?.pushViewController(ifDetailCommentVC, animated: true) } } //MARK:-----WebViewDelegate UIScrollViewDelegate----- extension IFDetailsController: WKNavigationDelegate, UIScrollViewDelegate { func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) { self.showProgress() } func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { self.hiddenProgress() } func scrollViewDidScroll(_ scrollView: UIScrollView) { let currentPosition: CGFloat = scrollView.contentOffset.y if currentPosition - self.lastPosition > 30 && currentPosition > 0 { self.headerTopConstraint?.update(offset: -50) UIView.animate(withDuration: 0.3, animations: { self.headerBack.layoutIfNeeded() }) self.lastPosition = currentPosition } else if self.lastPosition - currentPosition > 10 { self.headerTopConstraint?.update(offset: 0) UIView.animate(withDuration: 0.3, animations: { self.headerBack.layoutIfNeeded() }) self.lastPosition = currentPosition } } } //MARK:-----HeaderViewDelegate----- extension IFDetailsController: HeaderViewDelegate { func backButtonDidClick() { _ = self.navigationController?.popViewController(animated: true) } }
mit
aa5cddaf51cd297b6c033ae96302fd8a
29.793103
105
0.610676
5.102857
false
false
false
false
NoryCao/zhuishushenqi
zhuishushenqi/RightSide/Topic/Controllers/TopicDetail/QSTopicDetailViewController.swift
1
3302
// // QSTopicDetailViewController.swift // zhuishushenqi // // Created yung on 2017/4/20. // Copyright © 2017年 QS. All rights reserved. // // Template generated by Juanpe Catalán @JuanpeCMiOS // import UIKit class QSTopicDetailViewController: BaseViewController ,UITableViewDataSource,UITableViewDelegate, QSTopicDetailViewProtocol { var presenter: QSTopicDetailPresenterProtocol? private var booksModel:[TopicDetailModel] = [] private var headerModel:TopicDetailHeader? private lazy var tableView:UITableView = { let tableView = UITableView(frame: CGRect(x: 0, y: 64, width: ScreenWidth, height: ScreenHeight - 64), style: .grouped) tableView.dataSource = self tableView.delegate = self tableView.sectionHeaderHeight = CGFloat.leastNormalMagnitude tableView.sectionFooterHeight = 10 tableView.rowHeight = 93 tableView.qs_registerCellNib(TopicDetailCell.self) tableView.qs_registerCellNib(TopicDetailHeaderCell.self) return tableView }() override func viewDidLoad() { super.viewDidLoad() view.addSubview(tableView) presenter?.viewDidLoad() self.automaticallyAdjustsScrollViewInsets = false } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { if indexPath.section == 0{ return TopicDetailHeaderCell.height(model: headerModel) } return TopicDetailCell.height(models: booksModel, indexPath: indexPath) } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 1 } func numberOfSections(in tableView: UITableView) -> Int { return booksModel.count + 1 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if indexPath.section == 0 { let headerCell:TopicDetailHeaderCell? = tableView.qs_dequeueReusableCell(TopicDetailHeaderCell.self) headerCell?.backgroundColor = UIColor.white headerCell?.selectionStyle = .none headerCell?.model = headerModel return headerCell! } let cell:TopicDetailCell? = tableView.qs_dequeueReusableCell(TopicDetailCell.self) cell?.backgroundColor = UIColor.white cell?.selectionStyle = .none cell!.model = booksModel.count > (indexPath.section - 1) ? booksModel[indexPath.section - 1]:nil return cell! } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return tableView.sectionHeaderHeight } func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { return tableView.sectionFooterHeight } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { presenter?.didSelectAt(indexPath: indexPath, models: booksModel) } func showList(list: [TopicDetailModel], header: TopicDetailHeader) { self.booksModel = list self.headerModel = header self.tableView.reloadData() } func showEmpty() { } func showTitle(title: String) { self.title = title } }
mit
7824b95ebd724ee5b106481048246489
33.715789
127
0.67738
5.388889
false
false
false
false
gautier-gdx/Hexacon
Hexacon/HexagonalDirection.swift
1
1589
// // HexagonalDirection.swift // Hexacon // // Created by Gautier Gdx on 05/03/16. // Copyright © 2016 Gautier. All rights reserved. // import UIKit enum HexagonalDirection: Int { case right case rightUp case leftUp case left case leftDown case rightDown /** increment the enum to the next move, if it reach the end it come back a the beggining */ mutating func move() { if self != .rightDown { self = HexagonalDirection(rawValue: self.rawValue + 1)! } else { self = .right } } /** this this all the direction we can found in an hexagonal layout following the axial coordinate it's used to move to the next center on the grid - returns: a point diving the direction of the new center */ func direction() -> CGPoint { let horizontalPadding: CGFloat = 1.2 let verticalPadding: CGFloat = 1 switch self { case .right: return CGPoint(x: horizontalPadding,y: 0) case .rightUp: return CGPoint(x: horizontalPadding/2,y: -verticalPadding) case .leftUp: return CGPoint(x: -horizontalPadding/2,y: -verticalPadding) case .left: return CGPoint(x: -horizontalPadding,y: 0) case .leftDown: return CGPoint(x: -horizontalPadding/2,y: verticalPadding) case .rightDown: return CGPoint(x: horizontalPadding/2,y: verticalPadding) } } }
mit
bce3c88d80879d37fe8bf275580c7409
26.859649
99
0.575567
4.511364
false
false
false
false
emilstahl/swift
test/decl/protocol/conforms/inherited.swift
10
4323
// RUN: %target-parse-verify-swift // Inheritable: method with 'Self' in its signature protocol P1 { func f1(x: Self?) -> Bool } // Never inheritable: property with 'Self' in its signature. protocol P2 { var prop2: Self { get } } // Never inheritable: subscript with 'Self' in its result type. protocol P3 { subscript (i: Int) -> Self { get } } // Inheritable: subscript with 'Self' in its index type. protocol P4 { subscript (s: Self) -> Int { get } } // Potentially inheritable: method returning Self protocol P5 { func f5() -> Self } // Inheritable: method returning Self protocol P6 { func f6() -> Self } // Inheritable: method involving associated type. protocol P7 { typealias Assoc func f7() -> Assoc } // Inheritable: initializer requirement. protocol P8 { init(int: Int) } // Inheritable: operator requirement. protocol P9 { func ==(x: Self, y: Self) -> Bool } // Never inheritable: method with 'Self' in a non-contravariant position. protocol P10 { func f10(arr: [Self]) } // Never inheritable: method with 'Self' in curried position. protocol P11 { func f11()(x: Self) -> Int // expected-warning{{curried function declaration syntax will be removed in a future version of Swift}} } // Class A conforms to everything that can be conformed to by a // non-final class. class A : P1, P2, P3, P4, P5, P6, P7, P8, P9, P10 { // P1 func f1(x: A?) -> Bool { return true } // P2 var prop2: A { // expected-error{{protocol 'P2' requirement 'prop2' cannot be satisfied by a non-final class ('A') because it uses 'Self' in a non-parameter, non-result type position}} return self } // P3 subscript (i: Int) -> A { // expected-error{{protocol 'P3' requirement 'subscript' cannot be satisfied by a non-final class ('A') because it uses 'Self' in a non-parameter, non-result type position}} get { return self } } // P4 subscript (a: A) -> Int { get { return 5 } } // P5 func f5() -> A { return self } // expected-error{{method 'f5()' in non-final class 'A' must return `Self` to conform to protocol 'P5'}} // P6 func f6() -> Self { return self } // P7 func f7() -> Int { return 5 } // P8 required init(int: Int) { } // P10 func f10(arr: [A]) { } // expected-error{{protocol 'P10' requirement 'f10' cannot be satisfied by a non-final class ('A') because it uses 'Self' in a non-parameter, non-result type position}} // P11 func f11()(x: A) -> Int { return 5 } // expected-warning{{curried function declaration syntax will be removed in a future version of Swift}} } // P9 func ==(x: A, y: A) -> Bool { return true } // Class B inherits A; gets all of its conformances. class B : A { required init(int: Int) { } } func testB(b: B) { var _: P1 = b // expected-error{{has Self or associated type requirements}} var _: P4 = b // expected-error{{has Self or associated type requirements}} var _: P5 = b var _: P6 = b var _: P7 = b // expected-error{{has Self or associated type requirements}} var _: P8 = b // okay var _: P9 = b // expected-error{{has Self or associated type requirements}} } // Class A5 conforms to P5 in an inheritable manner. class A5 : P5 { // P5 func f5() -> Self { return self } } // Class B5 inherits A5; gets all of its conformances. class B5 : A5 { } func testB5(b5: B5) { var _: P5 = b5 // okay } // Class A8 conforms to P8 in an inheritable manner. class A8 : P8 { required init(int: Int) { } } class B8 : A8 { required init(int: Int) { } } func testB8(b8: B8) { var _: P8 = b8 // okay } // Class A9 conforms to everything. final class A9 : P1, P2, P3, P4, P5, P6, P7, P8, P9, P10 { // P1 func f1(x: A9?) -> Bool { return true } // P2 var prop2: A9 { return self } // P3 subscript (i: Int) -> A9 { get { return self } } // P4 subscript (a: A9) -> Int { get { return 5 } } // P5 func f5() -> A9 { return self } // P6 func f6() -> Self { return self } // P7 func f7() -> Int { return 5 } // P8 required init(int: Int) { } // P10 func f10(arr: [A9]) { } // P11 func f11()(x: A9) -> Int { return 5 } // expected-warning{{curried function declaration syntax will be removed in a future version of Swift}} } // P9 func ==(x: A9, y: A9) -> Bool { return true }
apache-2.0
0ba6a4a9dbfe528bea4ea5e04fed986a
21.515625
201
0.619477
3.1213
false
false
false
false
byu-oit-appdev/ios-byuSuite
byuSuite/Apps/YTime/model/YTimeClient.swift
1
4511
// // YTimeClient.swift // byuSuite // // Created by Eric Romrell on 5/17/17. // Copyright © 2017 Brigham Young University. All rights reserved. // private let TIMESHEET_BASE_URL = "https://api.byu.edu/domains/erp/hr/timesheet/v1" private let PUNCHES_BASE_URL = "https://api.byu.edu/domains/erp/hr/punches/v1" class YTimeClient: ByuClient2 { static func getTimesheet(callback: @escaping (YTimeTimesheet?, ByuError?) -> Void) { getByuId { (byuId, error) in if let byuId = byuId { let request = ByuRequest2(url: super.url(base: TIMESHEET_BASE_URL, pathParams: [byuId]), pathToReadableError: "status.message") ByuRequestManager.instance.makeRequest(request) { (response) in if response.succeeded, let dict = response.getDataJson() as? [String: Any] { callback(YTimeTimesheet(dict: dict), nil) } else { callback(nil, response.error) } } } else { callback(nil, error) } } } static func getPunchSummary(employeeRecord: String, callback: @escaping ([YTimeDay]?, ByuError?) -> Void) { getByuId { (byuId, error) in if let byuId = byuId { //For the pathParams, the service requires comma separated pathParams. Pass them in like this to still use our built in URL builder let req = punchesRequest(pathParams: [byuId, employeeRecord]) ByuRequestManager.instance.makeRequest(req) { (response) in if response.succeeded, let json = response.getDataJson() as? [[String: Any]] { callback(json.map { YTimeDay(dict: $0) }, nil) } else { callback(nil, response.error) } } } else { callback(nil, error) } } } static func createPunch(_ punch: YTimePunch, callback: @escaping (YTimeTimesheet?, ByuError?) -> Void) { //If the punch has a time attached to it, we're correcting a punch - use a PUT. Otherwise, use a POST var method: ByuRequest2.RequestMethod if let date = punch.punchTime { //Overwrite the punch time with Provo timezone let calendar = Calendar.current var components = calendar.dateComponents([.year, .month, .day, .hour, .minute], from: date) components.timeZone = TimeZone(identifier: "America/Denver") punch.punchTime = calendar.date(from: components) method = .PUT } else { //If the date didn't exist before, set it to right now punch.punchTime = Date() method = .POST } getByuId { (byuId, error) in if let byuId = byuId { let req = punchesRequest(pathParams: [byuId], method: method, defaultReadableError: "An error occurred due to device or network issues. Please try again. If this error persists, please submit feedback describing the issue and submit your punch using an alternative method.", body: punch.toDictionary()) ByuRequestManager.instance.makeRequest(req) { (response) in if response.succeeded, let dict = response.getDataJson() as? [String: Any] { callback(YTimeTimesheet(dict: dict), nil) } else { callback(nil, response.error) } } } else { callback(nil, error) } } } static func deletePunch(employeeRecord: String, punchDate: String, sequenceNumber: Int, callback: @escaping (ByuError?) -> Void) { getByuId { (byuId, error) in if let byuId = byuId { //For the pathParams, the service requires comma separated pathParams. Pass them in like this to still use our built in URL builder let req = punchesRequest(pathParams: [byuId, employeeRecord, punchDate, "\(sequenceNumber)"], method: .DELETE) ByuRequestManager.instance.makeRequest(req) { (response) in callback(response.error) } } else { callback(error) } } } private static func punchesRequest(pathParams: [String], method: ByuRequest2.RequestMethod = .GET, defaultReadableError: String? = nil, body: [String: Any]? = nil) -> ByuRequest2 { let request = ByuRequest2(requestMethod: method, url: super.url(base: PUNCHES_BASE_URL, pathParams: [pathParams.joined(separator: ",")]), pathToReadableError: "status.message", defaultReadableError: defaultReadableError) if let body = body, let data = try? JSONSerialization.data(withJSONObject: body) { request.body = data request.contentType = .JSON } return request } private static func getByuId(callback: @escaping (String?, ByuError?) -> Void) { ByuCredentialManager.getPersonSummary { (personSummary, error) in if let personSummary = personSummary { callback(personSummary.cleanByuId, nil) } else { callback(nil, error) } } } }
apache-2.0
68ac1e8d1069cee4e329bf1ff180f6a4
39.267857
306
0.687583
3.705834
false
false
false
false
leolanzinger/readory
Readory_test/ViewController.swift
1
2768
// // ViewController.swift // Created by Kyle Weiner on 10/17/14. // import UIKit class ViewController: UIViewController { @IBOutlet weak var playersLabel: UILabel! @IBOutlet weak var lionPic: UIImageView! @IBOutlet weak var parrotPic: UIImageView! @IBOutlet weak var wolfPic: UIImageView! @IBOutlet weak var foxPic: UIImageView! @IBOutlet weak var lamaPic: UIImageView! var selectedPlayers:Int! var players:Int! = -1 override func viewDidLoad() { super.viewDidLoad() // set the number of players label only if // number of players is set if (players > 0) { playersLabel.text = "YOU ARE PLAYING WITH " + String(players) + " PLAYER" if (players > 1) { playersLabel.text = playersLabel.text! + "S" // show lion picture lionPic.hidden = false if (players > 2) { // show parrot pic parrotPic.hidden = false if (players > 3) { // show wolf pic wolfPic.hidden = false if (players > 4) { // show fox pic foxPic.hidden = false } } } } } } @IBAction func onePlayer(sender: AnyObject) { self.selectedPlayers = 1 performSegueWithIdentifier("confirmGame", sender: self) } @IBAction func twoPlayers(sender: AnyObject) { self.selectedPlayers = 2 performSegueWithIdentifier("confirmGame", sender: self) } @IBAction func threePlayers(sender: AnyObject) { self.selectedPlayers = 3 performSegueWithIdentifier("confirmGame", sender: self) } @IBAction func fourPlayers(sender: AnyObject) { self.selectedPlayers = 4 performSegueWithIdentifier("confirmGame", sender: self) } @IBAction func fivePlayers(sender: AnyObject) { self.selectedPlayers = 5 performSegueWithIdentifier("confirmGame", sender: self) } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if (segue.identifier == "startGame") { Game.init() Game.swiftSharedInstance.setPlayers(self.players) } else if (segue.identifier == "confirmGame") { let secondViewController = segue.destinationViewController as! ViewController let plyrs = self.selectedPlayers as Int secondViewController.players = plyrs } } @IBAction func prepareForUnwind(segue: UIStoryboardSegue) { } }
mit
f6b6c269886dd793b52985001f49d974
30.11236
89
0.561777
5.212806
false
false
false
false
kaltura/playkit-ios
Classes/Player/Protocols/Player.swift
1
4397
// =================================================================================================== // Copyright (C) 2017 Kaltura Inc. // // Licensed under the AGPLv3 license, unless a different license for a // particular library is specified in the applicable library path. // // You may obtain a copy of the License at // https://www.gnu.org/licenses/agpl-3.0.html // =================================================================================================== import UIKit @objc public protocol Player: BasicPlayer { /// The player's associated media entry. @objc weak var mediaEntry: PKMediaEntry? { get } /// The player's settings. @objc var settings: PKPlayerSettings { get } /// The current media format. @objc var mediaFormat: PKMediaSource.MediaFormat { get } /// The player's session id. the `sessionId` is initialized when the player loads. @objc var sessionId: String { get } /// Add Observation to relevant event. @objc func addObserver(_ observer: AnyObject, event: PKEvent.Type, block: @escaping (PKEvent) -> Void) /// Add Observation to relevant events. @objc func addObserver(_ observer: AnyObject, events: [PKEvent.Type], block: @escaping (PKEvent) -> Void) /// Remove Observer for single event. @objc func removeObserver(_ observer: AnyObject, event: PKEvent.Type) /// Remove Observer for several events. @objc func removeObserver(_ observer: AnyObject, events: [PKEvent.Type]) /// Update Plugin Config. @objc func updatePluginConfig(pluginName: String, config: Any) /// Updates the styling from the settings textTrackStyling object @objc func updateTextTrackStyling() /// Indicates if current media is Live. /// /// - Returns: returns true if it's live. @objc func isLive() -> Bool /// Getter for playkit controllers. /// /// - Parameter type: Required class type. /// - Returns: Relevant controller if exist. @objc func getController(type: PKController.Type) -> PKController? /************************************************************/ // MARK: - Time Observation /************************************************************/ /// Adds a periodic time observer with specific interval /// /// - Parameters: /// - interval: time interval for the periodic invocation. /// - dispatchQueue: dispatch queue to observe changes on (nil value will use main). /// - block: block to handle the observation. /// - Returns: A uuid token to represent the observation, used to later remove a single observation. @objc func addPeriodicObserver(interval: TimeInterval, observeOn dispatchQueue: DispatchQueue?, using block: @escaping (TimeInterval) -> Void) -> UUID /// Adds a boundary time observer for the selected boundaries in time (25%, 50%, 30s etc.) /// /// - Parameters: /// - boundaries: boundary objects. /// - dispatchQueue: dispatch queue to observe changes on (nil value will use main). /// - block: block to handle the observation with the observed boundary, block returns (time, boundary percentage). /// - Returns: A uuid token to represent the observation, used to later remove a single observation. /// - Attention: if a boundary is crossed while seeking the observation **won't be triggered**. @objc func addBoundaryObserver(boundaries: [PKBoundary], observeOn dispatchQueue: DispatchQueue?, using block: @escaping (TimeInterval, Double) -> Void) -> UUID /// removes a single periodic observer using the uuid provided when added the observation. @objc func removePeriodicObserver(_ token: UUID) /// removes a single boundary observer using the uuid provided when added the observation. @objc func removeBoundaryObserver(_ token: UUID) } extension Player { /// Getter for playkit controllers. /// /// - Parameter type: Required class type. /// - Returns: Relevant controller if exist. public func getController<T: PKController>(ofType type: T.Type) -> T? { return self.getController(type: type) as? T } } public protocol PlayerDecoratorProvider { func getPlayerDecorator() -> PlayerDecoratorBase? } public protocol PlayerEngineWrapperProvider { func getPlayerEngineWrapper() -> PlayerEngineWrapper? }
agpl-3.0
1d78201c4961e84a76137b48d02c4e03
41.278846
164
0.631567
4.929372
false
false
false
false
twtstudio/WePeiYang-iOS
WePeiYang/Setting/YellowPage/SearchView.swift
1
2817
// // SearchView.swift // YellowPage // // Created by Halcao on 2017/2/23. // Copyright © 2017年 Halcao. All rights reserved. // import UIKit import SnapKit class SearchView: UIView { //let backBtn = UIButton() let backBtn = TappableImageView(with: CGRect.zero, imageSize: CGSize(width: 20, height: 20), image: UIImage(named: "ypback")) let textField = UITextField() /* // Only override draw() if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func draw(_ rect: CGRect) { // Drawing code } */ let bgdView = UIView() override func drawRect(rect: CGRect) { super.drawRect(rect) bgdView.frame = rect self.addSubview(bgdView) self.backgroundColor = UIColor(red: 0.1059, green: 0.6352, blue: 0.9019, alpha: 0.5) bgdView.backgroundColor = UIColor(red: 0.1059, green: 0.6352, blue: 0.9019, alpha: 1) bgdView.addSubview(backBtn) backBtn.snp_makeConstraints { make in make.width.equalTo(30) make.height.equalTo(30) make.centerY.equalTo(self).offset(7) make.left.equalTo(self).offset(20) } let separator = UIView() separator.backgroundColor = UIColor(red: 0.074, green: 0.466, blue: 0.662, alpha: 1) bgdView.addSubview(separator) separator.snp_makeConstraints { make in make.width.equalTo(1) make.height.equalTo(20) make.centerY.equalTo(self).offset(7) make.left.equalTo(backBtn.snp_right).offset(10) } let iconView = UIImageView() iconView.image = UIImage(named: "search") bgdView.addSubview(iconView) iconView.snp_makeConstraints { make in make.width.equalTo(20) make.height.equalTo(20) make.centerY.equalTo(self).offset(7) make.left.equalTo(separator.snp_right).offset(10) } let baseLine = UIView() baseLine.backgroundColor = UIColor.whiteColor() bgdView.addSubview(baseLine) baseLine.snp_makeConstraints { make in make.height.equalTo(1) make.top.equalTo(iconView.snp_bottom).offset(4) make.left.equalTo(iconView.snp_left) make.right.equalTo(bgdView).offset(-15) } self.addSubview(textField) textField.snp_makeConstraints { make in make.left.equalTo(iconView.snp_right).offset(2) make.right.equalTo(baseLine.snp_right) make.bottom.equalTo(baseLine.snp_top).offset(-3) make.height.equalTo(20) } textField.clearButtonMode = .UnlessEditing textField.textColor = UIColor.whiteColor() } }
mit
e57ea57251723358312bd310a615c60c
32.105882
129
0.61123
4.132159
false
false
false
false
fumiyasac/handMadeCalendarAdvance
handMadeCalendarAdvance/MonthlyCalendarViewController.swift
1
11602
// // MonthlyCalendarViewController.swift // handMadeCalendarAdvance // // Created by 酒井文也 on 2016/04/23. // Copyright © 2016年 just1factory. All rights reserved. // import UIKit import CalculateCalendarLogic // カレンダーに関する定数やメソッドを定義した構造体 struct CalendarSetting { static let calendarCellName = "CalendarCell" // カレンダーのセクション数やアイテム数に関するセッティング static let sectionCount = 2 static let firstSectionItemCount = 7 static let secondSectionItemCount = 42 private static let saturdayColor = UIColor(red: CGFloat(0.400), green: CGFloat(0.471), blue: CGFloat(0.980), alpha: CGFloat(1.0)) private static let holidayColor = UIColor(red: CGFloat(0.831), green: CGFloat(0.349), blue: CGFloat(0.224), alpha: CGFloat(1.0)) private static let weekdayColor = UIColor.darkGray // カレンダーの日付に関するセッティング static let weekList: [String] = ["日", "月", "火", "水", "木", "金", "土"] // カレンダーのカラー表示に関するセッティング(①日曜日または祝祭日の場合の色・②土曜日の場合の色・③平日の場合の色の決定) static func getCalendarColor(_ weekdayIndex: Int, isHoliday: Bool = false) -> UIColor { if isSunday(weekdayIndex) || isHoliday { return holidayColor } else if isSaturday(weekdayIndex) { return saturdayColor } else { return weekdayColor } } // 土曜日の判定 private static func isSunday(_ weekdayIndex: Int) -> Bool { return (weekdayIndex % 7 == Weekday.sun.rawValue) } // 日曜日の判定 private static func isSaturday(_ weekdayIndex: Int) -> Bool { return (weekdayIndex % 7 == Weekday.sat.rawValue) } } // カレンダー表示&計算用の値を取得するための構造体 struct TargetDateSetting { static func getTargetYearAndMonthCalendar(_ year: Int, month: Int) -> (Int, Int) { /************* * (重要ポイント) * 現在月の1日のdayOfWeek(曜日の値)を使ってカレンダーの始まる位置を決めるので'yyyy年mm月1日'のデータを作成する。 *************/ // Calendarクラスのインスタンスを初期化した後に日付の情報を取得して、「①指定の年月の1日時点の日付・②日数を年と月」をタプルで返す let targetCalendar: Calendar = Calendar(identifier: Calendar.Identifier.gregorian) var targetComps: DateComponents = DateComponents() targetComps.year = year targetComps.month = month targetComps.day = 1 let targetDate: Date = targetCalendar.date(from: targetComps)! // 引数で渡されたCalendarクラスのインスタンスとDateクラスのインスタンスをもとに日付の情報を取得して、指定の年月の1日時点の日付と日数を取得してタプルで返す let range: Range = targetCalendar.range(of: .day, in: .month, for: targetDate)! let comps: DateComponents = targetCalendar.dateComponents([.year, .month, .day, .weekday], from: targetDate) return (Int(comps.weekday!), Int(range.count)) } } // 現在日付を取得するための構造体 struct CurrentDateSetting { static func getCurrentYearAndMonth() -> (targetYear: Int, targetMonth: Int) { // Calendarクラスのインスタンスを初期化した後に日付の情報を取得して、年と月をタプルで返す let currentCalendar: Calendar = Calendar(identifier: Calendar.Identifier.gregorian) let comps: DateComponents = currentCalendar.dateComponents([.year, .month], from: Date()) return (Int(comps.year!), Int(comps.month!)) } } class MonthlyCalendarViewController: UIViewController { // ラベルに表示するための年と月の変数 private var targetYear: Int! = CurrentDateSetting.getCurrentYearAndMonth().targetYear private var targetMonth: Int! = CurrentDateSetting.getCurrentYearAndMonth().targetMonth // 該当年月の日のリスト private var dayCellLists: [String?] = [] // 日本の祝祭日判定用のインスタンス private let holidayObj: CalculateCalendarLogic = CalculateCalendarLogic() // カレンダー用のUICollectionView @IBOutlet weak var calendarCollectionView: UICollectionView! // Outlet接続をしたUI部品の一覧 @IBOutlet weak var prevMonthButton: UIButton! @IBOutlet weak var nextMonthButton: UIButton! @IBOutlet weak var currentMonthLabel: UILabel! @IBOutlet weak var backgroundView: UIView! override func viewDidLoad() { super.viewDidLoad() // Cellに使われるクラスを登録 calendarCollectionView.register(CalendarCell.self, forCellWithReuseIdentifier: CalendarSetting.calendarCellName) // UICollectionViewDelegate,UICollectionViewDataSourceの拡張宣言 calendarCollectionView.delegate = self calendarCollectionView.dataSource = self changeCalendar() } // 前の月のボタンが押された際のアクション → 現在の月に対して-1をする @IBAction func displayPrevMonth(_ sender: AnyObject) { if targetMonth == 1 { targetYear = targetYear - 1 targetMonth = 12 } else { targetMonth = targetMonth - 1 } changeCalendar() } // 次の月のボタンが押された際のアクション → 現在の月に対して+1をする @IBAction func displayNextMonth(_ sender: AnyObject) { if targetMonth == 12 { targetYear = targetYear + 1 targetMonth = 1 } else { targetMonth = targetMonth + 1 } changeCalendar() } // カレンダー表記を変更する private func changeCalendar() { updateDataSource() calendarCollectionView.reloadData() displaySelectedCalendar() } // 表示対象のカレンダーの年月を表示する private func displaySelectedCalendar() { currentMonthLabel.text = "\(targetYear!)年\(targetMonth!)月" } // CollectionViewCellに格納する日のデータを作成する private func updateDataSource() { var day = 1 dayCellLists = [] for i in 0..<(CalendarSetting.secondSectionItemCount) { if isCellUsing(i) { dayCellLists.append(String(day)) day += 1 } else { dayCellLists.append(nil) } } } // セルに値が格納されるかを判定する private func isCellUsing(_ index: Int) -> Bool { //該当の年と月から1日の曜日と最大日数のタプルを取得する let targetConcern: (Int, Int) = TargetDateSetting.getTargetYearAndMonthCalendar(targetYear, month: targetMonth) let targetWeekdayIndex: Int = targetConcern.0 let targetMaxDay: Int = targetConcern.1 //CollectionViewの該当セルインデックスに値が入るかを判定する if (index < targetWeekdayIndex - 1) { return false } else if (index == targetWeekdayIndex - 1 || index < targetWeekdayIndex + targetMaxDay - 1) { return true } else if (index == targetWeekdayIndex + targetMaxDay - 1 || index < CalendarSetting.secondSectionItemCount) { return false } return false } } // MARK: - UICollectionViewDataSource extension MonthlyCalendarViewController: UICollectionViewDataSource { private enum indexType: Int { case weekdayTitleArea = 0 case calendarContentsArea = 1 } // 配置したCollectionViewのセクション数を返す func numberOfSections(in collectionView: UICollectionView) -> Int { return CalendarSetting.sectionCount } // 配置したCollectionViewの各セクションのアイテム数を返す func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { switch section { case indexType.weekdayTitleArea.rawValue: return CalendarSetting.firstSectionItemCount case indexType.calendarContentsArea.rawValue: return CalendarSetting.secondSectionItemCount default: return 0 } } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: CalendarSetting.calendarCellName, for: indexPath) as! CalendarCell switch indexPath.section { case indexType.weekdayTitleArea.rawValue: // 曜日を表示する cell.setCell( cellText: CalendarSetting.weekList[indexPath.row], cellTextColor: CalendarSetting.getCalendarColor(indexPath.row) ) return cell case indexType.calendarContentsArea.rawValue: // 該当年月の日付を表示する let day: String? = dayCellLists[indexPath.row] if isCellUsing(indexPath.row) { let isHoliday: Bool = holidayObj.judgeJapaneseHoliday(year: targetYear, month: targetMonth, day: Int(day!)!) cell.setCell( cellText: day!, cellTextColor: CalendarSetting.getCalendarColor(indexPath.row, isHoliday: isHoliday) ) } else { cell.setCell( cellText: "", cellTextColor: CalendarSetting.getCalendarColor(indexPath.row) ) } return cell default: return cell } } } // MARK: - UICollectionViewDelegate extension MonthlyCalendarViewController: UICollectionViewDelegate { func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { // 日付が入るセルならば処理をする if isCellUsing(indexPath.row) { let day: String? = dayCellLists[indexPath.row] print("\(targetYear!)年\(targetMonth!)月\(day!)日") } } } // MARK: - UICollectionViewDelegateFlowLayout extension MonthlyCalendarViewController: UICollectionViewDelegateFlowLayout { // セルのサイズを設定 func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { let numberOfMargin: CGFloat = 8.0 let width: CGFloat = (collectionView.frame.size.width - CGFloat(1.5) * numberOfMargin) / CGFloat(7) let height: CGFloat = width * 1.0 return CGSize(width: width, height: height) } // セルの垂直方向のマージンを設定 func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat { return 1.5 } // セルの水平方向のマージンを設定 func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat { return 1.5 } }
mit
7399e97e1f75400d65693505753f9181
34.558304
175
0.65398
4.574091
false
false
false
false
gkaimakas/ReactiveBluetooth
ReactiveBluetooth/Classes/CBCentralManager/CBCentralManager+InitializationOption.swift
1
2346
// // CBCentralManager+InitializationOption.swift // ReactiveBluetooth // // Created by George Kaimakas on 06/03/2018. // import CoreBluetooth import Foundation extension CBCentralManager { public enum InitializationOption: Equatable, Hashable { public static func ==(lhs: InitializationOption, rhs: InitializationOption) -> Bool { switch (lhs, rhs) { case (.showPowerAlert(let a), .showPowerAlert(let b)): return a == b case (.restoreIdentifier(let a), .restoreIdentifier(let b)): return a == b default: return false } } public static func parse(dictionary: [String: Any]) -> [InitializationOption] { return dictionary .map { (key, value) -> InitializationOption? in if key == CBCentralManagerOptionShowPowerAlertKey, let value = value as? Bool { return .showPowerAlert(value) } if key == CBCentralManagerOptionRestoreIdentifierKey, let value = value as? UUID { return .restoreIdentifier(value) } return nil } .filter { $0 != nil } .map { $0! } } public var hashValue: Int { switch self { case .showPowerAlert(_): return 2_000 case .restoreIdentifier(_): return 20_000 } } public var key: String { switch self { case .showPowerAlert(_): return CBCentralManagerOptionShowPowerAlertKey case .restoreIdentifier(_): return CBCentralManagerOptionRestoreIdentifierKey } } public var value: Any { switch self { case .showPowerAlert(let value): return value as Any case .restoreIdentifier(let uuids): return uuids as Any } } case showPowerAlert(Bool) case restoreIdentifier(UUID) } } extension Set where Element == CBCentralManager.InitializationOption { public func merge() -> [String: Any] { return reduce([String: Any]() ) { (partialResult, item) -> [String: Any] in var result = partialResult result[item.key] = item.value return result } } }
mit
47d89a28227861b1bd996e065cb2308c
31.136986
102
0.558824
5.443155
false
false
false
false
alblue/swift
stdlib/public/core/StringGuts.swift
1
9002
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2018 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 SwiftShims // // StringGuts is a parameterization over String's representations. It provides // functionality and guidance for efficiently working with Strings. // @_fixed_layout public // SPI(corelibs-foundation) struct _StringGuts { @usableFromInline internal var _object: _StringObject @inlinable @inline(__always) internal init(_ object: _StringObject) { self._object = object _invariantCheck() } // Empty string @inlinable @inline(__always) init() { self.init(_StringObject(empty: ())) } } // Raw extension _StringGuts { @inlinable internal var rawBits: _StringObject.RawBitPattern { @inline(__always) get { return _object.rawBits } } } // Creation extension _StringGuts { @inlinable @inline(__always) internal init(_ smol: _SmallString) { self.init(_StringObject(smol)) } @inlinable @inline(__always) internal init(_ bufPtr: UnsafeBufferPointer<UInt8>, isASCII: Bool) { self.init(_StringObject(immortal: bufPtr, isASCII: isASCII)) } @inlinable @inline(__always) internal init(_ storage: _StringStorage) { self.init(_StringObject(storage)) } internal init(_ storage: _SharedStringStorage) { // TODO(cleanup): We should probably pass whole perf flags struct around self.init(_StringObject(storage, isASCII: false)) } internal init( cocoa: AnyObject, providesFastUTF8: Bool, isASCII: Bool, length: Int ) { self.init(_StringObject( cocoa: cocoa, providesFastUTF8: providesFastUTF8, isASCII: isASCII, length: length)) } } // Queries extension _StringGuts { // The number of code units @inlinable internal var count: Int { @inline(__always) get { return _object.count } } @inlinable internal var isEmpty: Bool { @inline(__always) get { return count == 0 } } @inlinable internal var isSmall: Bool { @inline(__always) get { return _object.isSmall } } @inlinable internal var asSmall: _SmallString { @inline(__always) get { return _SmallString(_object) } } @inlinable internal var isASCII: Bool { @inline(__always) get { return _object.isASCII } } @inlinable internal var isFastASCII: Bool { @inline(__always) get { return isFastUTF8 && _object.isASCII } } @inlinable internal var isNFC: Bool { @inline(__always) get { return _object.isNFC } } @inlinable internal var isNFCFastUTF8: Bool { // TODO(String micro-performance): Consider a dedicated bit for this @inline(__always) get { return _object.isNFC && isFastUTF8 } } @inlinable internal var hasNativeStorage: Bool { return _object.hasNativeStorage } internal var hasSharedStorage: Bool { return _object.hasSharedStorage } internal var hasBreadcrumbs: Bool { return hasNativeStorage || hasSharedStorage } } // extension _StringGuts { // Whether we can provide fast access to contiguous UTF-8 code units @_transparent @inlinable internal var isFastUTF8: Bool { return _fastPath(_object.providesFastUTF8) } // A String which does not provide fast access to contiguous UTF-8 code units @inlinable internal var isForeign: Bool { @inline(__always) get { return _slowPath(_object.isForeign) } } @inlinable @inline(__always) internal func withFastUTF8<R>( _ f: (UnsafeBufferPointer<UInt8>) throws -> R ) rethrows -> R { _sanityCheck(isFastUTF8) if self.isSmall { return try _SmallString(_object).withUTF8(f) } defer { _fixLifetime(self) } return try f(_object.fastUTF8) } @inlinable @inline(__always) internal func withFastUTF8<R>( range: Range<Int>?, _ f: (UnsafeBufferPointer<UInt8>) throws -> R ) rethrows -> R { return try self.withFastUTF8 { wholeUTF8 in let slicedUTF8: UnsafeBufferPointer<UInt8> if let r = range { slicedUTF8 = UnsafeBufferPointer(rebasing: wholeUTF8[r]) } else { slicedUTF8 = wholeUTF8 } return try f(slicedUTF8) } } @inlinable @inline(__always) internal func withFastCChar<R>( _ f: (UnsafeBufferPointer<CChar>) throws -> R ) rethrows -> R { return try self.withFastUTF8 { utf8 in let ptr = utf8.baseAddress._unsafelyUnwrappedUnchecked._asCChar return try f(UnsafeBufferPointer(start: ptr, count: utf8.count)) } } } // Internal invariants extension _StringGuts { #if !INTERNAL_CHECKS_ENABLED @inlinable @inline(__always) internal func _invariantCheck() {} #else @usableFromInline @inline(never) @_effects(releasenone) internal func _invariantCheck() { #if arch(i386) || arch(arm) _sanityCheck(MemoryLayout<String>.size == 12, """ the runtime is depending on this, update Reflection.mm and \ this if you change it """) #else _sanityCheck(MemoryLayout<String>.size == 16, """ the runtime is depending on this, update Reflection.mm and \ this if you change it """) #endif } #endif // INTERNAL_CHECKS_ENABLED internal func _dump() { _object._dump() } } // C String interop extension _StringGuts { @inlinable @inline(__always) // fast-path: already C-string compatible internal func withCString<Result>( _ body: (UnsafePointer<Int8>) throws -> Result ) rethrows -> Result { if _slowPath(!_object.isFastZeroTerminated) { return try _slowWithCString(body) } return try self.withFastCChar { return try body($0.baseAddress._unsafelyUnwrappedUnchecked) } } @inline(never) // slow-path @usableFromInline internal func _slowWithCString<Result>( _ body: (UnsafePointer<Int8>) throws -> Result ) rethrows -> Result { _sanityCheck(!_object.isFastZeroTerminated) return try String(self).utf8CString.withUnsafeBufferPointer { let ptr = $0.baseAddress._unsafelyUnwrappedUnchecked return try body(ptr) } } } extension _StringGuts { // Copy UTF-8 contents. Returns number written or nil if not enough space. // Contents of the buffer are unspecified if nil is returned. @inlinable internal func copyUTF8(into mbp: UnsafeMutableBufferPointer<UInt8>) -> Int? { let ptr = mbp.baseAddress._unsafelyUnwrappedUnchecked if _fastPath(self.isFastUTF8) { return self.withFastUTF8 { utf8 in guard utf8.count <= mbp.count else { return nil } let utf8Start = utf8.baseAddress._unsafelyUnwrappedUnchecked ptr.initialize(from: utf8Start, count: utf8.count) return utf8.count } } return _foreignCopyUTF8(into: mbp) } @_effects(releasenone) @usableFromInline @inline(never) // slow-path internal func _foreignCopyUTF8( into mbp: UnsafeMutableBufferPointer<UInt8> ) -> Int? { var ptr = mbp.baseAddress._unsafelyUnwrappedUnchecked var numWritten = 0 for cu in String(self).utf8 { guard numWritten < mbp.count else { return nil } ptr.initialize(to: cu) ptr += 1 numWritten += 1 } return numWritten } internal var utf8Count: Int { @inline(__always) get { if _fastPath(self.isFastUTF8) { return count } return String(self).utf8.count } } } // Index extension _StringGuts { @usableFromInline internal typealias Index = String.Index @inlinable internal var startIndex: String.Index { @inline(__always) get { return Index(encodedOffset: 0) } } @inlinable internal var endIndex: String.Index { @inline(__always) get { return Index(encodedOffset: self.count) } } } // Old SPI(corelibs-foundation) extension _StringGuts { @available(*, deprecated) public // SPI(corelibs-foundation) var _isContiguousASCII: Bool { return !isSmall && isFastUTF8 && isASCII } @available(*, deprecated) public // SPI(corelibs-foundation) var _isContiguousUTF16: Bool { return false } // FIXME: Remove. Still used by swift-corelibs-foundation @available(*, deprecated) public var startASCII: UnsafeMutablePointer<UInt8> { return UnsafeMutablePointer(mutating: _object.fastUTF8.baseAddress!) } // FIXME: Remove. Still used by swift-corelibs-foundation @available(*, deprecated) public var startUTF16: UnsafeMutablePointer<UTF16.CodeUnit> { fatalError("Not contiguous UTF-16") } } @available(*, deprecated) public // SPI(corelibs-foundation) func _persistCString(_ p: UnsafePointer<CChar>?) -> [CChar]? { guard let s = p else { return nil } let count = Int(_swift_stdlib_strlen(s)) var result = [CChar](repeating: 0, count: count + 1) for i in 0..<count { result[i] = s[i] } return result }
apache-2.0
1593708128ba313f13f005756b909d21
26.278788
80
0.669518
4.123683
false
false
false
false
wireapp/wire-ios
Wire-iOS/Sources/Permissions/PermissionDeniedViewController.swift
1
7057
// // Wire // Copyright (C) 2019 Wire Swiss GmbH // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // import Foundation import UIKit import WireCommonComponents // MARK: - PermissionDeniedViewControllerDelegate protocol PermissionDeniedViewControllerDelegate: AnyObject { func continueWithoutPermission(_ viewController: PermissionDeniedViewController) } // MARK: - PermissionDeniedViewController final class PermissionDeniedViewController: UIViewController { // MARK: - Properties weak var delegate: PermissionDeniedViewControllerDelegate? private var initialConstraintsCreated = false private let heroLabel: UILabel = UILabel.createHeroLabel() private var settingsButton: LegacyButton! private var laterButton: UIButton! // MARK: - addressBookAccessDeniedViewController class func addressBookAccessDeniedViewController() -> PermissionDeniedViewController { // MARK: - Properties typealias RegistrationAddressBookDenied = L10n.Localizable.Registration.AddressBookAccessDenied let vc = PermissionDeniedViewController() let title = RegistrationAddressBookDenied.Hero.title let paragraph1 = RegistrationAddressBookDenied.Hero.paragraph1 let paragraph2 = RegistrationAddressBookDenied.Hero.paragraph2 let text = [title, paragraph1, paragraph2].joined(separator: "\u{2029}") let attributedText = text.withCustomParagraphSpacing() attributedText.addAttributes([ NSAttributedString.Key.font: FontSpec.largeThinFont.font! ], range: (text as NSString).range(of: [paragraph1, paragraph2].joined(separator: "\u{2029}"))) attributedText.addAttributes([ NSAttributedString.Key.font: FontSpec.largeSemiboldFont.font! ], range: (text as NSString).range(of: title)) vc.heroLabel.attributedText = attributedText vc.settingsButton.setTitle(RegistrationAddressBookDenied.SettingsButton.title.capitalized, for: .normal) vc.laterButton.setTitle(RegistrationAddressBookDenied.MaybeLaterButton.title.capitalized, for: .normal) return vc } // MARK: - pushDeniedViewController class func pushDeniedViewController() -> PermissionDeniedViewController { // MARK: - Properties typealias RegistrationPushAccessDenied = L10n.Localizable.Registration.PushAccessDenied let vc = PermissionDeniedViewController() let title = RegistrationPushAccessDenied.Hero.title let paragraph1 = RegistrationPushAccessDenied.Hero.paragraph1 let text = [title, paragraph1].joined(separator: "\u{2029}") let attributedText = text.withCustomParagraphSpacing() attributedText.addAttributes([ NSAttributedString.Key.font: FontSpec.largeThinFont.font! ], range: (text as NSString).range(of: paragraph1)) attributedText.addAttributes([ NSAttributedString.Key.font: FontSpec.largeSemiboldFont.font! ], range: (text as NSString).range(of: title)) vc.heroLabel.attributedText = attributedText vc.settingsButton.setTitle(RegistrationPushAccessDenied.SettingsButton.title.capitalized, for: .normal) vc.laterButton.setTitle(RegistrationPushAccessDenied.MaybeLaterButton.title.capitalized, for: .normal) return vc } // MARK: - Initialization required init() { super.init(nibName: nil, bundle: nil) view.addSubview(heroLabel) createSettingsButton() createLaterButton() updateViewConstraints() } @available(*, unavailable) required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - Setup Buttons private func createSettingsButton() { settingsButton = Button(style: .accentColorTextButtonStyle, cornerRadius: 16, fontSpec: .normalSemiboldFont) settingsButton.addTarget(self, action: #selector(openSettings(_:)), for: .touchUpInside) view.addSubview(settingsButton) } private func createLaterButton() { laterButton = Button(style: .secondaryTextButtonStyle, cornerRadius: 16, fontSpec: .normalSemiboldFont) laterButton.addTarget(self, action: #selector(continueWithoutAccess(_:)), for: .touchUpInside) view.addSubview(laterButton) } // MARK: - Actions @objc private func openSettings(_ sender: Any?) { if let url = URL(string: UIApplication.openSettingsURLString) { UIApplication.shared.open(url, options: [:], completionHandler: nil) } } @objc private func continueWithoutAccess(_ sender: Any?) { delegate?.continueWithoutPermission(self) } // MARK: - Constraints override func updateViewConstraints() { super.updateViewConstraints() guard !initialConstraintsCreated else { return } initialConstraintsCreated = true [heroLabel, settingsButton, laterButton].forEach { $0?.translatesAutoresizingMaskIntoConstraints = false } var constraints = [heroLabel.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -28), heroLabel.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 28)] constraints += [settingsButton.topAnchor.constraint(equalTo: heroLabel.bottomAnchor, constant: 28), settingsButton.heightAnchor.constraint(equalToConstant: 56)] constraints += [settingsButton.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -28), settingsButton.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 28)] constraints += [laterButton.topAnchor.constraint(equalTo: settingsButton.bottomAnchor, constant: 28), laterButton.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -28), laterButton.centerXAnchor.constraint(equalTo: view.centerXAnchor), laterButton.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -28), laterButton.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 28), laterButton.heightAnchor.constraint(equalToConstant: 56)] NSLayoutConstraint.activate(constraints) } }
gpl-3.0
0f8bca4d6976cdb8dfae0681fede6221
40.02907
112
0.697605
5.436826
false
false
false
false
WhosPablo/PicShare
PicShare/ImageViewController.swift
1
4914
// // ImageViewController.swift // PicShare // // Created by Pablo Arango on 10/23/15. // Copyright © 2015 Pablo Arango. All rights reserved. // import UIKit import Parse import ParseUI class ImageViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate { @IBOutlet weak var myImageView: UIImageView! let picker = UIImagePickerController() @IBOutlet weak var uploadButton: UIButton! func noCamera(){ let alertVC = UIAlertController( title: "No Camera", message: "Sorry, this device has no camera", preferredStyle: .Alert) let okAction = UIAlertAction( title: "OK", style:.Default, handler: nil) alertVC.addAction(okAction) presentViewController( alertVC, animated: true, completion: nil) } @IBAction func photoFromLibrary(sender: UIBarButtonItem) { picker.allowsEditing = false //2 picker.sourceType = .PhotoLibrary //3 picker.modalPresentationStyle = .Popover presentViewController(picker, animated: true, completion: nil)//4 picker.popoverPresentationController?.barButtonItem = sender } @IBAction func shootPhoto(sender: UIBarButtonItem) { if UIImagePickerController.availableCaptureModesForCameraDevice(.Rear) != nil { picker.allowsEditing = false picker.sourceType = UIImagePickerControllerSourceType.Camera picker.cameraCaptureMode = .Photo picker.modalPresentationStyle = .FullScreen presentViewController(picker, animated: true, completion: nil) } else { noCamera() } } override func viewDidLoad() { super.viewDidLoad() picker.delegate = self } func imagePickerController( picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) { let chosenImage = info[UIImagePickerControllerOriginalImage] as! UIImage myImageView.contentMode = .ScaleAspectFit myImageView.image = chosenImage dismissViewControllerAnimated(true, completion: nil) uploadButton.hidden = false; } func imagePickerControllerDidCancel(picker: UIImagePickerController) { dismissViewControllerAnimated(true, completion: nil) } @IBAction func uploadImage(sender: AnyObject) { let anImage = myImageView.image! let resizedImage: UIImage = resizeImage(anImage, targetSize: CGSizeMake(560.0, 560.0)) // JPEG to decrease file size and enable faster uploads & downloads guard let imageData: NSData = UIImageJPEGRepresentation(resizedImage, 0.8) else { return } let photoFile = PFFile(data: imageData) photoFile!.saveInBackgroundWithBlock { (succeeded, error) in if (succeeded) { print("Photo uploaded successfully") } } let photo = PFObject(className: "Photo") photo.setObject(PFUser.currentUser()!.username!, forKey: "user") photo.setObject(photoFile!, forKey: "photo") photo.saveInBackgroundWithBlock { (succeeded, error ) -> Void in if succeeded { print("Photo uploaded") } } self.reloadInputViews() self.tabBarController?.selectedIndex = 0 } override func preferredStatusBarStyle() -> UIStatusBarStyle { return UIStatusBarStyle.LightContent } func resizeImage(image: UIImage, targetSize: CGSize) -> UIImage { let size = image.size let widthRatio = targetSize.width / image.size.width let heightRatio = targetSize.height / image.size.height // Figure out what our orientation is, and use that to form the rectangle var newSize: CGSize if(widthRatio > heightRatio) { newSize = CGSizeMake(size.width * heightRatio, size.height * heightRatio) } else { newSize = CGSizeMake(size.width * widthRatio, size.height * widthRatio) } // This is the rect that we've calculated out and this is what is actually used below let rect = CGRectMake(0, 0, newSize.width, newSize.height) // Actually do the resizing to the rect using the ImageContext stuff UIGraphicsBeginImageContextWithOptions(newSize, false, 1.0) image.drawInRect(rect) let newImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return newImage } }
apache-2.0
b9ab34a968dde51ecb1accbea6a6f1a5
29.899371
98
0.61205
5.855781
false
false
false
false
sharath-cliqz/browser-ios
Client/Frontend/UIConstants.swift
2
6250
/* 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 public struct UIConstants { static let AboutHomePage = URL(string: "\(WebServer.sharedInstance.base)/about/home/")! // Cliqz: Changed Appbackground color, PrivateModePurple, PrivateModeLocationBackgroundColor, PrivateModeLocationBorderColor, PrivateModeActionButtonTintColor, PrivateModeTextHighlightColor, PrivateModeTextHighlightColor according to the requirements static let CliqzThemeColor = UIColor(colorString: "00AEF0") static let GhosteryGray = UIColor(colorString: "97A4AE") static let TextHighlightColor = CliqzThemeColor //UIColor(colorString: "00AEF0")//UIColor(colorString: "8BE0E7") static let AppBackgroundColor = UIColor(rgb: 0xE8E8E8) //UIColor.blackColor() static let SystemBlueColor = UIColor(red: 0 / 255, green: 122 / 255, blue: 255 / 255, alpha: 1) static let PrivateModePurple = UIColor.clear // UIColor(red: 207 / 255, green: 104 / 255, blue: 255 / 255, alpha: 1) static let PrivateModeLocationBackgroundColor = UIColor(rgb: 0x333333) //UIColor(red: 31 / 255, green: 31 / 255, blue: 31 / 255, alpha: 1) static let PrivateModeLocationBorderColor = UIColor.clear // UIColor(red: 255, green: 255, blue: 255, alpha: 0.15) static let PrivateModeActionButtonTintColor = UIColor(red: 255, green: 255, blue: 255, alpha: 0.8) static let PrivateModeTextHighlightColor = CliqzThemeColor // UIColor(red: 120 / 255, green: 120 / 255, blue: 165 / 255, alpha: 1) static let PrivateModeReaderModeBackgroundColor = UIColor(red: 89 / 255, green: 89 / 255, blue: 89 / 255, alpha: 1) static let PrivateModeToolbarTintColor = UIColor(red: 74 / 255, green: 74 / 255, blue: 74 / 255, alpha: 1) // static var OrangeColor: UIColor { return UIColor(red: 246.0/255.0, green: 90.0/255.0, blue: 42.0/255.0, alpha: 1) } static let PrivateModeTextColor: UIColor = UIColor.white static let NormalModeTextColor: UIColor = UIColor.black // Cliqz: Added colors for our new UI static let TextFieldBackgroundColor = UIColor.white static let PrivateModeBackgroundColor = UIColor.black //UIColor(rgb: 0x333333) static let PrivateModeExpandBackgroundColor = UIColor.black // UIColor(rgb: 0x4a4a4a) static let ToolbarHeight: CGFloat = 50 static let DefaultRowHeight: CGFloat = 58 static let DefaultPadding: CGFloat = 10 static let SnackbarButtonHeight: CGFloat = 48 // Static fonts static let DefaultChromeSize: CGFloat = 14 static let DefaultChromeSmallSize: CGFloat = 11 static let PasscodeEntryFontSize: CGFloat = 36 static let DefaultChromeFont: UIFont = UIFont.systemFont(ofSize: DefaultChromeSize, weight: UIFontWeightRegular) static let DefaultChromeBoldFont = UIFont.boldSystemFont(ofSize: DefaultChromeSize) static let DefaultChromeSmallFontBold = UIFont.boldSystemFont(ofSize: DefaultChromeSmallSize) static let PasscodeEntryFont = UIFont.systemFont(ofSize: PasscodeEntryFontSize, weight: UIFontWeightBold) // These highlight colors are currently only used on Snackbar buttons when they're pressed static let HighlightColor = UIColor(red: 205/255, green: 223/255, blue: 243/255, alpha: 0.9) static let HighlightText = UIColor(red: 42/255, green: 121/255, blue: 213/255, alpha: 1.0) static let PanelBackgroundColor = UIColor.white static let SeparatorColor = UIColor(rgb: 0xcccccc) static let HighlightBlue = UIColor(red:76/255, green:158/255, blue:255/255, alpha:1) static let DestructiveRed = UIColor(red: 255/255, green: 64/255, blue: 0/255, alpha: 1.0) static let BorderColor = UIColor.black.withAlphaComponent(0.25) static let BackgroundColor = UIColor(red: 0.21, green: 0.23, blue: 0.25, alpha: 1) // These colours are used on the Menu static let MenuToolbarBackgroundColorNormal = UIColor(red: 241/255, green: 241/255, blue: 241/255, alpha: 1.0) static let MenuToolbarBackgroundColorPrivate = UIColor(red: 74/255, green: 74/255, blue: 74/255, alpha: 1.0) static let MenuToolbarTintColorNormal = BackgroundColor static let MenuToolbarTintColorPrivate = UIColor.white static let MenuBackgroundColorNormal = UIColor(red: 223/255, green: 223/255, blue: 223/255, alpha: 1.0) static let MenuBackgroundColorPrivate = UIColor(red: 59/255, green: 59/255, blue: 59/255, alpha: 1.0) static let MenuSelectedItemTintColor = UIColor(red: 0.30, green: 0.62, blue: 1.0, alpha: 1.0) // settings static let TableViewHeaderBackgroundColor = UIColor(red: 242/255, green: 245/255, blue: 245/255, alpha: 1.0) static let TableViewHeaderTextColor = UIColor(red: 130/255, green: 135/255, blue: 153/255, alpha: 1.0) static let TableViewRowTextColor = UIColor(red: 53.55/255, green: 53.55/255, blue: 53.55/255, alpha: 1.0) static let TableViewDisabledRowTextColor = UIColor.lightGray static let TableViewSeparatorColor = UIColor(rgb: 0xD1D1D4) static let TableViewHeaderFooterHeight = CGFloat(44) static let TableViewRowErrorTextColor = UIColor(red: 255/255, green: 0/255, blue: 26/255, alpha: 1.0) static let TableViewRowWarningTextColor = UIColor(red: 245/255, green: 166/255, blue: 35/255, alpha: 1.0) static let TableViewRowActionAccessoryColor = UIColor(red: 0.29, green: 0.56, blue: 0.89, alpha: 1.0) // Cliqz: Used default tint color for UIControl instead of the custom orange one globally on the whole app // Firefox Orange // static let ControlTintColor = UIColor(red: 240.0 / 255, green: 105.0 / 255, blue: 31.0 / 255, alpha: 1) static let ControlTintColor = UIColor(red: 66.0 / 255, green: 210.0 / 255, blue: 80.0 / 255, alpha: 1) // Passcode dot gray static let PasscodeDotColor = UIColor(rgb: 0x4A4A4A) /// JPEG compression quality for persisted screenshots. Must be between 0-1. static let ScreenshotQuality: Float = 0.3 static let ActiveScreenshotQuality: CGFloat = 0.5 static let OKString = NSLocalizedString("OK", comment: "OK button") static let CancelString = NSLocalizedString("Cancel", comment: "Label for Cancel button") }
mpl-2.0
d9ba16637a452ad6ab9fcea117821c94
64.789474
254
0.73728
3.963221
false
false
false
false
onmyway133/Github.swift
Sources/Classes/Event/Client+Event.swift
1
2371
// // Client+Event.swift // GithubSwift // // Created by Khoa Pham on 22/04/16. // Copyright © 2016 Fantageek. All rights reserved. // import Foundation import RxSwift import Construction public extension Client { // Conditionally fetches events from the current user's activity stream. If // the latest data matches `etag`, the call does not count toward the API rate // limit. /// offset - Allows you to specify an offset at which items will begin being /// returned. /// perPage - The perPage parameter. You can set a custom page size up to 100 and /// the default value 30 will be used if you pass 0 or greater than 100. // // Returns a signal which will send zero or more OCTResponses (of OCTEvents) if // new data was downloaded. Unrecognized events will be omitted from the result. // On success, the signal will send completed regardless of whether there was // new data. If no `user` is set, the signal will error immediately. public func fetchUserEvents(etag: String? = nil, offset: Int = 0, perPage: Int = Constant.defaultPerPage) -> Observable<[Event]> { if !isAuthenticated { return Observable<[Event]>.error(Error.authenticationRequiredError()) } let requestDescriptor: RequestDescriptor = construct { $0.path = "users/\(user?.login ?? "")/received_events" $0.offset = offset $0.perPage = perPage $0.etag = etag } return enqueue(requestDescriptor).map { return Parser.all($0) } } /// Fetches the performed events for the specified `user`. /// /// user - The specified user. This must not be nil. /// offset - Allows you to specify an offset at which items will begin being /// returned. /// perPage - The perPage parameter. You can set a custom page size up to 100 and /// the default value 30 will be used if you pass 0 or greater than 100. /// /// Returns a signal which sends zero or more OCTEvent objects. public func fetchPerformedEvents(user: User, offset: Int, perPage: Int) -> Observable<[Event]> { let requestDescriptor: RequestDescriptor = construct { $0.path = "users/\(user.login)/received_events" $0.offset = offset $0.perPage = perPage } return enqueue(requestDescriptor).map { return Parser.all($0) } } }
mit
a18a4db9d19c12fe93c4ffea808431c7
35.461538
111
0.662869
4.31694
false
false
false
false
wordpress-mobile/WordPress-iOS
WordPress/Classes/ViewRelated/Plugins/PluginDirectoryViewController.swift
1
9043
import UIKit import WordPressFlux import Gridicons class PluginDirectoryViewController: UITableViewController { private let viewModel: PluginDirectoryViewModel private var viewModelReceipt: Receipt? private var tableViewModel: ImmuTable! private var searchWrapperView: SearchWrapperView! private let searchThrottle = Scheduler(seconds: 0.5) init(site: JetpackSiteRef, store: PluginStore = StoreContainer.shared.plugin) { viewModel = PluginDirectoryViewModel(site: site, store: store) super.init(style: .plain) tableViewModel = viewModel.tableViewModel(presenter: self) title = NSLocalizedString("Plugins", comment: "Title for the plugin directory") } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() WPStyleGuide.configureColors(view: nil, tableView: tableView) definesPresentationContext = true extendedLayoutIncludesOpaqueBars = true viewModelReceipt = viewModel.onChange { [weak self] in self?.reloadTable() } viewModel.noResultsDelegate = self tableView.rowHeight = Constants.rowHeight tableView.estimatedRowHeight = Constants.rowHeight tableView.separatorInset = Constants.separatorInset ImmuTable.registerRows([CollectionViewContainerRow<PluginDirectoryCollectionViewCell, PluginDirectoryEntry>.self], tableView: tableView) tableViewModel = viewModel.tableViewModel(presenter: self) setupSearchBar() } private func reloadTable() { tableViewModel = viewModel.tableViewModel(presenter: self) tableView.reloadData() } private func setupSearchBar() { let containerView = SearchWrapperView(frame: CGRect(origin: .zero, size: CGSize(width: tableView.frame.width, height: searchController.searchBar.frame.height))) containerView.addSubview(searchController.searchBar) tableView.tableHeaderView = containerView tableView.verticalScrollIndicatorInsets.top = searchController.searchBar.bounds.height // for some... particlar reason, which I haven't been able to fully track down, if the searchBar is added directly // as the tableHeaderView, the UITableView sort of freaks out and adds like 400pts of random padding // below the content of the tableView. Wrapping it in this container fixes it ¯\_(ツ)_/¯ searchWrapperView = containerView } private lazy var searchController: UISearchController = { let resultsController = PluginListViewController(site: viewModel.site, query: .feed(type: .search(term: ""))) let controller = UISearchController(searchResultsController: resultsController) controller.obscuresBackgroundDuringPresentation = false controller.searchResultsUpdater = self controller.delegate = self let searchBar = controller.searchBar WPStyleGuide.configureSearchBar(searchBar) return controller }() private enum Constants { static var rowHeight: CGFloat = 256 static var separatorInset = UIEdgeInsets(top: 0, left: 16, bottom: 0, right: 16) } fileprivate func updateTableHeaderSize() { if searchController.isActive { // Account for the search bar being moved to the top of the screen. searchWrapperView.frame.size.height = (searchController.searchBar.bounds.height + searchController.searchBar.frame.origin.y) - view.safeAreaInsets.top } else { searchWrapperView.frame.size.height = searchController.searchBar.bounds.height } // Resetting the tableHeaderView is necessary to get the new height to take effect tableView.tableHeaderView = searchWrapperView } } extension PluginDirectoryViewController { override func numberOfSections(in tableView: UITableView) -> Int { return tableViewModel.sections.count } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return tableViewModel.sections[section].rows.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let row = tableViewModel.rowAtIndexPath(indexPath) let cell = tableView.dequeueReusableCell(withIdentifier: row.reusableIdentifier, for: indexPath) row.configureCell(cell) return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let row = tableViewModel.rowAtIndexPath(indexPath) row.action?(row) } override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 0 } override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { return 0 } } extension PluginDirectoryViewController: UISearchControllerDelegate { func didPresentSearchController(_ searchController: UISearchController) { WPAppAnalytics.track(.pluginSearchPerformed, withBlogID: viewModel.site.siteID as NSNumber) // This is required when programmatically `activate`ing the Search controller, // e.g. when the user taps on the "Search" icon in the navbar DispatchQueue.main.async { searchController.searchBar.becomeFirstResponder() } updateTableHeaderSize() tableView.verticalScrollIndicatorInsets.top = searchWrapperView.bounds.height tableView.contentInset.top = 0 } func didDismissSearchController(_ searchController: UISearchController) { updateTableHeaderSize() } } extension PluginDirectoryViewController: UISearchResultsUpdating { func updateSearchResults(for searchController: UISearchController) { guard let pluginListViewController = searchController.searchResultsController as? PluginListViewController, let searchedText = searchController.searchBar.text else { return } searchThrottle.throttle { pluginListViewController.query = .feed(type: .search(term: searchedText)) pluginListViewController.tableView.contentInset.top = self.searchWrapperView.bounds.height } } } extension PluginDirectoryViewController: NoResultsViewControllerDelegate { func actionButtonPressed() { viewModel.reloadFailed() } } extension PluginDirectoryViewController: PluginPresenter { func present(plugin: Plugin, capabilities: SitePluginCapabilities) { guard navigationController?.topViewController == self else { // because of some work we're doing when presenting the VC, there might be a slight lag // between when a user taps on a plugin, and when it appears on screen — unfortunately enough // for users to not be sure whether the tap "registered". // this prevents from pushing the same screen multiple times when users taps again. return } let pluginVC = PluginViewController(plugin: plugin, capabilities: capabilities, site: viewModel.site) navigationController?.pushViewController(pluginVC, animated: true) } func present(directoryEntry: PluginDirectoryEntry) { guard navigationController?.topViewController == self else { return } let pluginVC = PluginViewController(directoryEntry: directoryEntry, site: viewModel.site) navigationController?.pushViewController(pluginVC, animated: true) } } extension PluginDirectoryViewController: PluginListPresenter { func present(site: JetpackSiteRef, query: PluginQuery) { let listType: String? switch query { case .all: listType = "installed" case .featured: listType = "featured" case .feed(.popular): listType = "popular" case .feed(.newest): listType = "newest" default: listType = nil } if let listType = listType { let properties = ["type": listType] let siteID: NSNumber? = (site.isSelfHostedWithoutJetpack ? nil : site.siteID) as NSNumber? WPAppAnalytics.track(.openedPluginList, withProperties: properties, withBlogID: siteID) } let listVC = PluginListViewController(site: site, query: query) navigationController?.pushViewController(listVC, animated: true) } } extension BlogDetailsViewController { @objc func makePluginDirectoryViewController(blog: Blog) -> PluginDirectoryViewController? { guard let site = JetpackSiteRef(blog: blog) else { return nil } return PluginDirectoryViewController(site: site) } }
gpl-2.0
dd36b6e966c249582f9cdf1b1c5c56b7
37.130802
162
0.689609
5.734137
false
false
false
false
biohazardlover/NintendoEverything
Pods/ImageViewer/ImageViewer/Source/VideoView.swift
4
2298
// // VideoView.swift // ImageViewer // // Created by Kristian Angyal on 25/07/2016. // Copyright © 2016 MailOnline. All rights reserved. // import UIKit import AVFoundation class VideoView: UIView { let previewImageView = UIImageView() var image: UIImage? { didSet { previewImageView.image = image } } var player: AVPlayer? { willSet { if newValue == nil { player?.removeObserver(self, forKeyPath: "status") player?.removeObserver(self, forKeyPath: "rate") } } didSet { if let player = self.player, let videoLayer = self.layer as? AVPlayerLayer { videoLayer.player = player videoLayer.videoGravity = AVLayerVideoGravity.resizeAspect player.addObserver(self, forKeyPath: "status", options: NSKeyValueObservingOptions.new, context: nil) player.addObserver(self, forKeyPath: "rate", options: NSKeyValueObservingOptions.new, context: nil) } } } override class var layerClass : AnyClass { return AVPlayerLayer.self } convenience init() { self.init(frame: CGRect.zero) } override init(frame: CGRect) { super.init(frame: frame) self.addSubview(previewImageView) previewImageView.contentMode = .scaleAspectFill previewImageView.autoresizingMask = [.flexibleWidth, .flexibleHeight] previewImageView.clipsToBounds = true } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } deinit { player?.removeObserver(self, forKeyPath: "status") player?.removeObserver(self, forKeyPath: "rate") } override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { if let status = self.player?.status, let rate = self.player?.rate { if status == .readyToPlay && rate != 0 { UIView.animate(withDuration: 0.3, animations: { [weak self] in if let strongSelf = self { strongSelf.previewImageView.alpha = 0 } }) } } } }
mit
cfb202351d17192cb31a296c59717520
26.023529
151
0.595124
5.07064
false
false
false
false
manGoweb/S3
Sources/S3Signer/Dates.swift
1
1202
import Foundation struct Dates { /// The ISO8601 basic format timestamp of signature creation. YYYYMMDD'T'HHMMSS'Z'. let long: String /// The short timestamp of signature creation. YYYYMMDD. let short: String init(_ date: Date) { self.short = date.timestampShort self.long = date.timestampLong } } extension Date { private static let shortDateFormatter: DateFormatter = { let formatter = DateFormatter() formatter.dateFormat = "yyyyMMdd" formatter.timeZone = TimeZone(abbreviation: "UTC") formatter.locale = Locale(identifier: "en_US_POSIX") return formatter }() private static let longDateFormatter: DateFormatter = { let formatter = DateFormatter() formatter.dateFormat = "yyyyMMdd'T'HHmmss'Z'" formatter.timeZone = TimeZone(abbreviation: "UTC") formatter.locale = Locale(identifier: "en_US_POSIX") return formatter }() var timestampShort: String { return Date.shortDateFormatter.string(from: self) } var timestampLong: String { return Date.longDateFormatter.string(from: self) } }
mit
dfe3b3be23796cbd41c9b37c3ca6f972
25.130435
88
0.634775
4.623077
false
false
false
false
Mark-SS/LayerPlayer
LayerPlayer/CAShapeLayerViewController.swift
5
5467
// // CAShapeLayerViewController.swift // LayerPlayer // // Created by Scott Gardner on 11/17/14. // Copyright (c) 2014 Scott Gardner. All rights reserved. // import UIKit class CAShapeLayerViewController: UIViewController { @IBOutlet weak var viewForShapeLayer: UIView! @IBOutlet weak var closePathSwitch: UISwitch! @IBOutlet weak var hueSlider: UISlider! @IBOutlet weak var fillSwitch: UISwitch! @IBOutlet weak var fillRuleSegmentedControl: UISegmentedControl! @IBOutlet weak var lineWidthSlider: UISlider! @IBOutlet weak var lineDashSwitch: UISwitch! @IBOutlet weak var lineCapSegmentedControl: UISegmentedControl! @IBOutlet weak var lineJoinSegmentedControl: UISegmentedControl! enum FillRule: Int { case NonZero, EvenOdd } enum LineCap: Int { case Butt, Round, Square, Cap } enum LineJoin: Int { case Miter, Round, Bevel } let shapeLayer = CAShapeLayer() var color = UIColor(hue: 129/359.0, saturation: 1.0, brightness: 0.4, alpha: 1.0) let openPath = UIBezierPath() let closedPath = UIBezierPath() // MARK: - Quick reference func setUpOpenPath() { openPath.moveToPoint(CGPoint(x: 30, y: 196)) openPath.addCurveToPoint(CGPoint(x: 112.0, y: 12.5), controlPoint1: CGPoint(x: 110.56, y: 13.79), controlPoint2: CGPoint(x: 112.07, y: 13.01)) openPath.addCurveToPoint(CGPoint(x: 194, y: 196), controlPoint1: CGPoint(x: 111.9, y: 11.81), controlPoint2: CGPoint(x: 194, y: 196)) openPath.addLineToPoint(CGPoint(x: 30.0, y: 85.68)) openPath.addLineToPoint(CGPoint(x: 194.0, y: 48.91)) openPath.addLineToPoint(CGPoint(x: 30, y: 196)) } func setUpClosedPath() { closedPath.CGPath = CGPathCreateMutableCopy(openPath.CGPath) closedPath.closePath() } func setUpShapeLayer() { shapeLayer.path = openPath.CGPath shapeLayer.fillColor = nil shapeLayer.fillRule = kCAFillRuleNonZero shapeLayer.lineCap = kCALineCapButt shapeLayer.lineDashPattern = nil shapeLayer.lineDashPhase = 0.0 shapeLayer.lineJoin = kCALineJoinMiter shapeLayer.lineWidth = CGFloat(lineWidthSlider.value) shapeLayer.miterLimit = 4.0 shapeLayer.strokeColor = color.CGColor } // MARK: - View life cycle override func viewDidLoad() { super.viewDidLoad() setUpOpenPath() setUpClosedPath() setUpShapeLayer() viewForShapeLayer.layer.addSublayer(shapeLayer) } // MARK: - IBActions @IBAction func closePathSwitchChanged(sender: UISwitch) { var selectedSegmentIndex: Int! if sender.on { selectedSegmentIndex = UISegmentedControlNoSegment shapeLayer.path = closedPath.CGPath } else { switch shapeLayer.lineCap { case kCALineCapButt: selectedSegmentIndex = LineCap.Butt.rawValue case kCALineCapRound: selectedSegmentIndex = LineCap.Round.rawValue default: selectedSegmentIndex = LineCap.Square.rawValue } shapeLayer.path = openPath.CGPath } lineCapSegmentedControl.selectedSegmentIndex = selectedSegmentIndex } @IBAction func hueSliderChanged(sender: UISlider) { let hue = CGFloat(sender.value / 359.0) let color = UIColor(hue: hue, saturation: hue, brightness: 0.4, alpha: 1.0) shapeLayer.fillColor = fillSwitch.on ? color.CGColor : nil shapeLayer.strokeColor = color.CGColor self.color = color } @IBAction func fillSwitchChanged(sender: UISwitch) { var selectedSegmentIndex: Int if sender.on { shapeLayer.fillColor = color.CGColor if shapeLayer.fillRule == kCAFillRuleNonZero { selectedSegmentIndex = FillRule.NonZero.rawValue } else { selectedSegmentIndex = FillRule.EvenOdd.rawValue } } else { selectedSegmentIndex = UISegmentedControlNoSegment shapeLayer.fillColor = nil } fillRuleSegmentedControl.selectedSegmentIndex = selectedSegmentIndex } @IBAction func fillRuleSegmentedControlChanged(sender: UISegmentedControl) { fillSwitch.on = true shapeLayer.fillColor = color.CGColor var fillRule = kCAFillRuleNonZero if sender.selectedSegmentIndex != FillRule.NonZero.rawValue { fillRule = kCAFillRuleEvenOdd } shapeLayer.fillRule = fillRule } @IBAction func lineWidthSliderChanged(sender: UISlider) { shapeLayer.lineWidth = CGFloat(sender.value) } @IBAction func lineDashSwitchChanged(sender: UISwitch) { if sender.on { shapeLayer.lineDashPattern = [50, 50] shapeLayer.lineDashPhase = 25.0 } else { shapeLayer.lineDashPattern = nil shapeLayer.lineDashPhase = 0 } } @IBAction func lineCapSegmentedControlChanged(sender: UISegmentedControl) { closePathSwitch.on = false shapeLayer.path = openPath.CGPath var lineCap = kCALineCapButt switch sender.selectedSegmentIndex { case LineCap.Round.rawValue: lineCap = kCALineCapRound case LineCap.Square.rawValue: lineCap = kCALineCapSquare default: break } shapeLayer.lineCap = lineCap } @IBAction func lineJoinSegmentedControlChanged(sender: UISegmentedControl) { var lineJoin = kCALineJoinMiter switch sender.selectedSegmentIndex { case LineJoin.Round.rawValue: lineJoin = kCALineJoinRound case LineJoin.Bevel.rawValue: lineJoin = kCALineJoinBevel default: break } shapeLayer.lineJoin = lineJoin } }
mit
015078dc268a1ecfc85f1c46546d976f
28.392473
146
0.701482
4.721071
false
false
false
false
SlackKit/SlackKit
SKServer/Sources/Titan/TitanFormURLEncodedBodyParser/TitanFormURLEncodedBodyParser.swift
2
2279
import Foundation // Copyright 2017 Enervolution GmbH // // 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. public extension RequestType { var formURLEncodedBody: [(name: String, value: String)] { guard let bodyString: String = self.body else { return [] } return parse(body: bodyString) } var postParams: [String: String] { var ret = [String: String]() guard let bodyString: String = self.body else { return ret } let keys = parse(body: bodyString) for (k, v) in keys { ret[k] = v } return ret } } /* Parse application/x-www-form-urlencoded bodies Returns as many name-value pairs as possible Liberal in what it accepts, any failures to delimit pairs or decode percent encoding will result in empty strings */ func parse(body: String) -> [(name: String, value: String)] { var retValue = [(name: String, value: String)]() let pairs = body.components(separatedBy: "&") // Separate the tuples for element in pairs { // Find the equals sign guard let range = element.range(of: "=") else { return retValue } // split out the key and the value let rawKey = element[..<range.lowerBound] let rawValue = element[range.upperBound...] // Remove + character let sanitizedKey = String(rawKey).replacingOccurrences(of: "+", with: " ") let sanitizedValue = String(rawValue).replacingOccurrences(of: "+", with: " ") let key = sanitizedKey.removingPercentEncoding ?? sanitizedKey let value = sanitizedValue.removingPercentEncoding ?? sanitizedValue retValue.append((key, value)) } return retValue }
mit
678f78591497df9890652312dc23c5ae
32.028986
86
0.64502
4.468627
false
false
false
false
Bunn/firefox-ios
Client/Frontend/Login Management/LoginListViewController.swift
1
28783
/* 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 UIKit import SnapKit import Storage import Shared import SwiftKeychainWrapper private struct LoginListUX { static let RowHeight: CGFloat = 58 static let SearchHeight: CGFloat = 58 static let selectionButtonFont = UIFont.systemFont(ofSize: 16) static let NoResultsFont = UIFont.systemFont(ofSize: 16) static let NoResultsTextColor = UIColor.Photon.Grey40 } private extension UITableView { var allLoginIndexPaths: [IndexPath] { return ((LoginsSettingsSection + 1)..<self.numberOfSections).flatMap { sectionNum in (0..<self.numberOfRows(inSection: sectionNum)).map { IndexPath(row: $0, section: sectionNum) } } } } private let CellReuseIdentifier = "cell-reuse-id" private let SectionHeaderId = "section-header-id" private let LoginsSettingsSection = 0 class LoginListViewController: SensitiveViewController { fileprivate lazy var loginSelectionController: ListSelectionController = { return ListSelectionController(tableView: self.tableView) }() fileprivate lazy var loginDataSource: LoginDataSource = { let dataSource = LoginDataSource(profile: profile, searchController: searchController) dataSource.dataObserver = self return dataSource }() fileprivate let profile: Profile fileprivate let searchController = UISearchController(searchResultsController: nil) fileprivate var activeLoginQuery: Deferred<Maybe<[LoginRecord]>>? fileprivate let loadingView = SettingsLoadingView() fileprivate var deleteAlert: UIAlertController? fileprivate var selectionButtonHeightConstraint: Constraint? fileprivate var selectedIndexPaths = [IndexPath]() fileprivate let tableView = UITableView() weak var settingsDelegate: SettingsDelegate? var shownFromAppMenu: Bool = false // Titles for selection/deselect/delete buttons fileprivate let deselectAllTitle = NSLocalizedString("Deselect All", tableName: "LoginManager", comment: "Label for the button used to deselect all logins.") fileprivate let selectAllTitle = NSLocalizedString("Select All", tableName: "LoginManager", comment: "Label for the button used to select all logins.") fileprivate let deleteLoginTitle = NSLocalizedString("Delete", tableName: "LoginManager", comment: "Label for the button used to delete the current login.") fileprivate lazy var selectionButton: UIButton = { let button = UIButton() button.titleLabel?.font = LoginListUX.selectionButtonFont button.setTitle(self.selectAllTitle, for: []) button.addTarget(self, action: #selector(tappedSelectionButton), for: .touchUpInside) return button }() static func shouldShowAppMenuShortcut(forPrefs prefs: Prefs) -> Bool { // default to on return prefs.boolForKey(PrefsKeys.LoginsShowShortcutMenuItem) ?? true } static func create(authenticateInNavigationController navigationController: UINavigationController, profile: Profile, settingsDelegate: SettingsDelegate) -> Deferred<LoginListViewController?> { let deferred = Deferred<LoginListViewController?>() func fillDeferred(ok: Bool) { if ok { LeanPlumClient.shared.track(event: .openedLogins) let viewController = LoginListViewController(profile: profile) viewController.settingsDelegate = settingsDelegate deferred.fill(viewController) } else { deferred.fill(nil) } } guard let authInfo = KeychainWrapper.sharedAppContainerKeychain.authenticationInfo(), authInfo.requiresValidation() else { fillDeferred(ok: true) return deferred } AppAuthenticator.presentAuthenticationUsingInfo(authInfo, touchIDReason: AuthenticationStrings.loginsTouchReason, success: { fillDeferred(ok: true) }, cancel: { fillDeferred(ok: false) }, fallback: { AppAuthenticator.presentPasscodeAuthentication(navigationController).uponQueue(.main) { isOk in if isOk { // In the success case of the passcode dialog, it requires explicit dismissal to continue navigationController.dismiss(animated: true) } fillDeferred(ok: isOk) } }) return deferred } private init(profile: Profile) { self.profile = profile super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() self.title = Strings.LoginsAndPasswordsTitle tableView.register(ThemedTableViewCell.self, forCellReuseIdentifier: CellReuseIdentifier) tableView.register(ThemedTableSectionHeaderFooterView.self, forHeaderFooterViewReuseIdentifier: SectionHeaderId) tableView.accessibilityIdentifier = "Login List" tableView.dataSource = loginDataSource tableView.allowsMultipleSelectionDuringEditing = true tableView.delegate = self tableView.tableFooterView = UIView() // Setup the Search Controller searchController.searchBar.autocapitalizationType = .none searchController.searchResultsUpdater = self searchController.obscuresBackgroundDuringPresentation = false searchController.searchBar.placeholder = Strings.LoginsListSearchPlaceholder searchController.delegate = self navigationItem.hidesSearchBarWhenScrolling = false navigationItem.searchController = searchController definesPresentationContext = true // No need to hide the navigation bar on iPad to make room, and hiding makes the search bar too close to the top searchController.hidesNavigationBarDuringPresentation = UIDevice.current.userInterfaceIdiom != .pad let notificationCenter = NotificationCenter.default notificationCenter.addObserver(self, selector: #selector(remoteLoginsDidChange), name: .DataRemoteLoginChangesWereApplied, object: nil) notificationCenter.addObserver(self, selector: #selector(dismissAlertController), name: UIApplication.didEnterBackgroundNotification, object: nil) setupDefaultNavButtons() view.addSubview(tableView) view.addSubview(loadingView) view.addSubview(selectionButton) loadingView.isHidden = true tableView.snp.makeConstraints { make in make.top.equalTo(self.view.safeAreaLayoutGuide) make.leading.trailing.equalTo(self.view.safeAreaLayoutGuide) make.bottom.equalTo(self.selectionButton.snp.top) } selectionButton.snp.makeConstraints { make in make.leading.trailing.bottom.equalTo(self.view.safeAreaLayoutGuide) make.top.equalTo(self.tableView.snp.bottom) make.bottom.equalTo(self.view.safeAreaLayoutGuide) selectionButtonHeightConstraint = make.height.equalTo(0).constraint } loadingView.snp.makeConstraints { make in make.edges.equalTo(tableView) } applyTheme() KeyboardHelper.defaultHelper.addDelegate(self) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) loadLogins() } func applyTheme() { view.backgroundColor = UIColor.theme.tableView.headerBackground tableView.separatorColor = UIColor.theme.tableView.separator tableView.backgroundColor = UIColor.theme.tableView.headerBackground tableView.reloadData() (tableView.tableHeaderView as? Themeable)?.applyTheme() selectionButton.setTitleColor(UIColor.theme.tableView.rowBackground, for: []) selectionButton.backgroundColor = UIColor.theme.general.highlightBlue let theme = BuiltinThemeName(rawValue: ThemeManager.instance.current.name) ?? .normal if theme == .dark { searchController.searchBar.barStyle = .black } } @objc func dismissLogins() { dismiss(animated: true) } fileprivate func setupDefaultNavButtons() { navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .edit, target: self, action: #selector(beginEditing)) if shownFromAppMenu { navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(dismissLogins)) } else { navigationItem.leftBarButtonItem = nil } } fileprivate func toggleDeleteBarButton() { // Show delete bar button item if we have selected any items if loginSelectionController.selectedCount > 0 { if navigationItem.rightBarButtonItem == nil { navigationItem.rightBarButtonItem = UIBarButtonItem(title: deleteLoginTitle, style: .plain, target: self, action: #selector(tappedDelete)) navigationItem.rightBarButtonItem?.tintColor = UIColor.Photon.Red50 } } else { navigationItem.rightBarButtonItem = nil } } fileprivate func toggleSelectionTitle() { if loginSelectionController.selectedCount == loginDataSource.count { selectionButton.setTitle(deselectAllTitle, for: []) } else { selectionButton.setTitle(selectAllTitle, for: []) } } // Wrap the SQLiteLogins method to allow us to cancel it from our end. fileprivate func queryLogins(_ query: String) -> Deferred<Maybe<[LoginRecord]>> { let deferred = Deferred<Maybe<[LoginRecord]>>() profile.logins.searchLoginsWithQuery(query) >>== { logins in deferred.fillIfUnfilled(Maybe(success: logins.asArray())) succeed() } return deferred } } extension LoginListViewController: UISearchResultsUpdating { func updateSearchResults(for searchController: UISearchController) { guard let query = searchController.searchBar.text else { return } loadLogins(query) } } fileprivate var isDuringSearchControllerDismiss = false extension LoginListViewController: UISearchControllerDelegate { func willDismissSearchController(_ searchController: UISearchController) { isDuringSearchControllerDismiss = true } func didDismissSearchController(_ searchController: UISearchController) { isDuringSearchControllerDismiss = false } } // MARK: - Selectors private extension LoginListViewController { @objc func remoteLoginsDidChange() { DispatchQueue.main.async { self.loadLogins() } } @objc func dismissAlertController() { self.deleteAlert?.dismiss(animated: false, completion: nil) } func loadLogins(_ query: String? = nil) { loadingView.isHidden = false // Fill in an in-flight query and re-query activeLoginQuery?.fillIfUnfilled(Maybe(success: [])) activeLoginQuery = queryLogins(query ?? "") activeLoginQuery! >>== loginDataSource.setLogins } @objc func beginEditing() { navigationItem.rightBarButtonItem = nil navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(cancelSelection)) selectionButtonHeightConstraint?.update(offset: UIConstants.ToolbarHeight) self.view.layoutIfNeeded() tableView.setEditing(true, animated: true) tableView.reloadData() } @objc func cancelSelection() { // Update selection and select all button loginSelectionController.deselectAll() toggleSelectionTitle() selectionButtonHeightConstraint?.update(offset: 0) self.view.layoutIfNeeded() tableView.setEditing(false, animated: true) setupDefaultNavButtons() tableView.reloadData() } @objc func tappedDelete() { profile.logins.hasSyncedLogins().uponQueue(.main) { yes in self.deleteAlert = UIAlertController.deleteLoginAlertWithDeleteCallback({ [unowned self] _ in // Delete here let guidsToDelete = self.loginSelectionController.selectedIndexPaths.compactMap { indexPath in self.loginDataSource.loginAtIndexPath(indexPath)?.id } self.profile.logins.delete(ids: guidsToDelete).uponQueue(.main) { _ in self.cancelSelection() self.loadLogins() } }, hasSyncedLogins: yes.successValue ?? true) self.present(self.deleteAlert!, animated: true, completion: nil) } } @objc func tappedSelectionButton() { // If we haven't selected everything yet, select all if loginSelectionController.selectedCount < loginDataSource.count { // Find all unselected indexPaths let unselectedPaths = tableView.allLoginIndexPaths.filter { indexPath in return !loginSelectionController.indexPathIsSelected(indexPath) } loginSelectionController.selectIndexPaths(unselectedPaths) unselectedPaths.forEach { indexPath in self.tableView.selectRow(at: indexPath, animated: true, scrollPosition: .none) } } // If everything has been selected, deselect all else { loginSelectionController.deselectAll() tableView.allLoginIndexPaths.forEach { indexPath in self.tableView.deselectRow(at: indexPath, animated: true) } } toggleSelectionTitle() toggleDeleteBarButton() } } // MARK: - LoginDataSourceObserver extension LoginListViewController: LoginDataSourceObserver { func loginSectionsDidUpdate() { loadingView.isHidden = true tableView.reloadData() activeLoginQuery = nil navigationItem.rightBarButtonItem?.isEnabled = loginDataSource.count > 0 restoreSelectedRows() } func restoreSelectedRows() { for path in self.loginSelectionController.selectedIndexPaths { tableView.selectRow(at: path, animated: false, scrollPosition: .none) } } } // MARK: - UITableViewDelegate extension LoginListViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { // Headers are hidden except for the first login section, which has a title (see also viewForHeaderInSection) return section == 1 ? 44 : 0 } func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { // Only the start of the logins list gets a title if section != 1 { return nil } guard let headerView = tableView.dequeueReusableHeaderFooterView(withIdentifier: SectionHeaderId) as? ThemedTableSectionHeaderFooterView else { return nil } headerView.titleLabel.text = Strings.LoginsListTitle // not using a grouped table: show header borders headerView.showBorder(for: .top, true) headerView.showBorder(for: .bottom, true) headerView.applyTheme() return headerView } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { if indexPath.section == LoginsSettingsSection, searchController.isActive || tableView.isEditing { return 0 } return indexPath.section == LoginsSettingsSection ? 44 : LoginListUX.RowHeight } func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle { return .none } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if tableView.isEditing { loginSelectionController.selectIndexPath(indexPath) toggleSelectionTitle() toggleDeleteBarButton() } else if let login = loginDataSource.loginAtIndexPath(indexPath) { tableView.deselectRow(at: indexPath, animated: true) let detailViewController = LoginDetailViewController(profile: profile, login: login) detailViewController.settingsDelegate = settingsDelegate navigationController?.pushViewController(detailViewController, animated: true) } } func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) { if tableView.isEditing { loginSelectionController.deselectIndexPath(indexPath) toggleSelectionTitle() toggleDeleteBarButton() } } } // MARK: - KeyboardHelperDelegate extension LoginListViewController: KeyboardHelperDelegate { func keyboardHelper(_ keyboardHelper: KeyboardHelper, keyboardWillShowWithState state: KeyboardState) { let coveredHeight = state.intersectionHeightForView(tableView) tableView.contentInset.bottom = coveredHeight } func keyboardHelper(_ keyboardHelper: KeyboardHelper, keyboardDidShowWithState state: KeyboardState) { } func keyboardHelper(_ keyboardHelper: KeyboardHelper, keyboardWillHideWithState state: KeyboardState) { tableView.contentInset.bottom = 0 } } // MARK: - SearchInputViewDelegate extension LoginListViewController: SearchInputViewDelegate { @objc func searchInputView(_ searchView: SearchInputView, didChangeTextTo text: String) { loadLogins(text) } @objc func searchInputViewBeganEditing(_ searchView: SearchInputView) { // Trigger a cancel for editing cancelSelection() // Hide the edit button while we're searching navigationItem.rightBarButtonItem = nil loadLogins() } @objc func searchInputViewFinishedEditing(_ searchView: SearchInputView) { setupDefaultNavButtons() loadLogins() } } /// Controller that keeps track of selected indexes fileprivate class ListSelectionController: NSObject { private unowned let tableView: UITableView private(set) var selectedIndexPaths = [IndexPath]() var selectedCount: Int { return selectedIndexPaths.count } init(tableView: UITableView) { self.tableView = tableView super.init() } func selectIndexPath(_ indexPath: IndexPath) { selectedIndexPaths.append(indexPath) } func indexPathIsSelected(_ indexPath: IndexPath) -> Bool { return selectedIndexPaths.contains(indexPath) { path1, path2 in return path1.row == path2.row && path1.section == path2.section } } func deselectIndexPath(_ indexPath: IndexPath) { guard let foundSelectedPath = (selectedIndexPaths.filter { $0.row == indexPath.row && $0.section == indexPath.section }).first, let indexToRemove = selectedIndexPaths.firstIndex(of: foundSelectedPath) else { return } selectedIndexPaths.remove(at: indexToRemove) } func deselectAll() { selectedIndexPaths.removeAll() } func selectIndexPaths(_ indexPaths: [IndexPath]) { selectedIndexPaths += indexPaths } } protocol LoginDataSourceObserver: AnyObject { func loginSectionsDidUpdate() } /// Data source for handling LoginData objects from a Cursor class LoginDataSource: NSObject, UITableViewDataSource { var count = 0 weak var dataObserver: LoginDataSourceObserver? weak var searchController: UISearchController? fileprivate let emptyStateView = NoLoginsView() fileprivate var titles = [Character]() let boolSettings: (BoolSetting, BoolSetting) init(profile: Profile, searchController: UISearchController) { self.searchController = searchController boolSettings = ( BoolSetting(prefs: profile.prefs, prefKey: PrefsKeys.LoginsSaveEnabled, defaultValue: true, attributedTitleText: NSAttributedString(string: Strings.SettingToSaveLogins)), BoolSetting(prefs: profile.prefs, prefKey: PrefsKeys.LoginsShowShortcutMenuItem, defaultValue: true, attributedTitleText: NSAttributedString(string: Strings.SettingToShowLoginsInAppMenu))) super.init() } fileprivate var loginRecordSections = [Character: [LoginRecord]]() { didSet { assert(Thread.isMainThread) self.dataObserver?.loginSectionsDidUpdate() } } fileprivate func loginsForSection(_ section: Int) -> [LoginRecord]? { guard section > 0 else { assertionFailure() return nil } let titleForSectionIndex = titles[section - 1] return loginRecordSections[titleForSectionIndex] } func loginAtIndexPath(_ indexPath: IndexPath) -> LoginRecord? { guard indexPath.section > 0 else { assertionFailure() return nil } let titleForSectionIndex = titles[indexPath.section - 1] guard let section = loginRecordSections[titleForSectionIndex] else { assertionFailure() return nil } assert(indexPath.row <= section.count) return section[indexPath.row] } @objc func numberOfSections(in tableView: UITableView) -> Int { if loginRecordSections.isEmpty { tableView.backgroundView = emptyStateView return 1 } tableView.backgroundView = nil // Add one section for the settings section. return loginRecordSections.count + 1 } @objc func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if section == LoginsSettingsSection { return 2 } return loginsForSection(section)?.count ?? 0 } @objc func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = ThemedTableViewCell(style: .subtitle, reuseIdentifier: CellReuseIdentifier) if indexPath.section == LoginsSettingsSection { let hideSettings = searchController?.isActive ?? false || tableView.isEditing let setting = indexPath.row == 0 ? boolSettings.0 : boolSettings.1 setting.onConfigureCell(cell) if hideSettings { cell.isHidden = true } // Fade in the cell while dismissing the search or the cell showing suddenly looks janky if isDuringSearchControllerDismiss { cell.isHidden = false cell.contentView.alpha = 0 cell.accessoryView?.alpha = 0 UIView.animate(withDuration: 0.6) { cell.contentView.alpha = 1 cell.accessoryView?.alpha = 1 } } } else { guard let login = loginAtIndexPath(indexPath) else { return cell } cell.textLabel?.text = login.hostname cell.detailTextColor = UIColor.theme.tableView.rowDetailText cell.detailTextLabel?.text = login.username cell.accessoryType = .disclosureIndicator } // Need to override the default background multi-select color to support theming cell.multipleSelectionBackgroundView = UIView() cell.applyTheme() return cell } func setLogins(_ logins: [LoginRecord]) { // NB: Make sure we call the callback on the main thread so it can be synced up with a reloadData to // prevent race conditions between data/UI indexing. return computeSectionsFromLogins(logins).uponQueue(.main) { result in guard let (titles, sections) = result.successValue else { self.count = 0 self.titles = [] self.loginRecordSections = [:] return } self.count = logins.count self.titles = titles self.loginRecordSections = sections // Disable the search controller if there are no logins saved if !(self.searchController?.isActive ?? true) { self.searchController?.searchBar.isUserInteractionEnabled = !logins.isEmpty self.searchController?.searchBar.alpha = logins.isEmpty ? 0.5 : 1.0 } } } fileprivate func computeSectionsFromLogins(_ logins: [LoginRecord]) -> Deferred<Maybe<([Character], [Character: [LoginRecord]])>> { guard logins.count > 0 else { return deferMaybe( ([Character](), [Character: [LoginRecord]]()) ) } var domainLookup = [GUID: (baseDomain: String?, host: String?, hostname: String)]() var sections = [Character: [LoginRecord]]() var titleSet = Set<Character>() // Small helper method for using the precomputed base domain to determine the title/section of the // given login. func titleForLogin(_ login: LoginRecord) -> Character { // Fallback to hostname if we can't extract a base domain. let titleString = domainLookup[login.id]?.baseDomain?.uppercased() ?? login.hostname return titleString.first ?? Character("") } // Rules for sorting login URLS: // 1. Compare base domains // 2. If bases are equal, compare hosts // 3. If login URL was invalid, revert to full hostname func sortByDomain(_ loginA: LoginRecord, loginB: LoginRecord) -> Bool { guard let domainsA = domainLookup[loginA.id], let domainsB = domainLookup[loginB.id] else { return false } guard let baseDomainA = domainsA.baseDomain, let baseDomainB = domainsB.baseDomain, let hostA = domainsA.host, let hostB = domainsB.host else { return domainsA.hostname < domainsB.hostname } if baseDomainA == baseDomainB { return hostA < hostB } else { return baseDomainA < baseDomainB } } return deferDispatchAsync(DispatchQueue.global(qos: DispatchQoS.userInteractive.qosClass)) { // Precompute the baseDomain, host, and hostname values for sorting later on. At the moment // baseDomain() is a costly call because of the ETLD lookup tables. logins.forEach { login in domainLookup[login.id] = ( login.hostname.asURL?.baseDomain, login.hostname.asURL?.host, login.hostname ) } // 1. Temporarily insert titles into a Set to get duplicate removal for 'free'. logins.forEach { titleSet.insert(titleForLogin($0)) } // 2. Setup an empty list for each title found. titleSet.forEach { sections[$0] = [LoginRecord]() } // 3. Go through our logins and put them in the right section. logins.forEach { sections[titleForLogin($0)]?.append($0) } // 4. Go through each section and sort. sections.forEach { sections[$0] = $1.sorted(by: sortByDomain) } return deferMaybe( (Array(titleSet).sorted(), sections) ) } } } // Empty state view when there is no logins to display. fileprivate class NoLoginsView: UIView { // We use the search bar height to maintain visual balance with the whitespace on this screen. The // title label is centered visually using the empty view + search bar height as the size to center with. var searchBarHeight: CGFloat = 0 { didSet { setNeedsUpdateConstraints() } } lazy var titleLabel: UILabel = { let label = UILabel() label.font = LoginListUX.NoResultsFont label.textColor = LoginListUX.NoResultsTextColor label.text = NSLocalizedString("No logins found", tableName: "LoginManager", comment: "Label displayed when no logins are found after searching.") return label }() override init(frame: CGRect) { super.init(frame: frame) addSubview(titleLabel) } fileprivate override func updateConstraints() { super.updateConstraints() titleLabel.snp.remakeConstraints { make in make.centerX.equalTo(self) make.centerY.equalTo(self).offset(-(searchBarHeight / 2)) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mpl-2.0
0539aa9056c875aee408b064e866eaca
38.054274
200
0.665011
5.66706
false
false
false
false
debugsquad/metalic
metalic/View/Main/VBar.swift
1
10699
import UIKit class VBar:UIView, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout { let model:MMain weak var parent:CParent! weak var collectionView:UICollectionView! weak var label:UILabel! weak var backButton:UIButton! private var currentWidth:CGFloat private let barHeight:CGFloat private let barDelta:CGFloat private let kCellWidth:CGFloat = 70 private let kAnimationDuration:TimeInterval = 0.3 private let kWaitingTime:TimeInterval = 1 init(parent:CParent, barHeight:CGFloat, barDelta:CGFloat) { self.barHeight = barHeight self.barDelta = barDelta model = MMain() currentWidth = 0 super.init(frame:CGRect.zero) translatesAutoresizingMaskIntoConstraints = false clipsToBounds = true backgroundColor = UIColor.main self.parent = parent let flow:UICollectionViewFlowLayout = UICollectionViewFlowLayout() flow.headerReferenceSize = CGSize.zero flow.footerReferenceSize = CGSize.zero flow.minimumLineSpacing = 0 flow.minimumInteritemSpacing = 0 flow.scrollDirection = UICollectionViewScrollDirection.horizontal let collectionView:UICollectionView = UICollectionView(frame:CGRect.zero, collectionViewLayout:flow) collectionView.clipsToBounds = true collectionView.translatesAutoresizingMaskIntoConstraints = false collectionView.backgroundColor = UIColor.clear collectionView.showsVerticalScrollIndicator = false collectionView.showsHorizontalScrollIndicator = false collectionView.isScrollEnabled = false collectionView.bounces = false collectionView.dataSource = self collectionView.delegate = self collectionView.register( VBarCell.self, forCellWithReuseIdentifier: VBarCell.reusableIdentifier) self.collectionView = collectionView let label:UILabel = UILabel() label.isUserInteractionEnabled = false label.backgroundColor = UIColor.clear label.font = UIFont.bold(size:16) label.textAlignment = NSTextAlignment.center label.translatesAutoresizingMaskIntoConstraints = false label.textColor = UIColor.white label.alpha = 0 self.label = label let backButton:UIButton = UIButton() backButton.translatesAutoresizingMaskIntoConstraints = false backButton.setImage(#imageLiteral(resourceName: "assetGenericBack"), for:UIControlState()) backButton.imageView!.clipsToBounds = true backButton.imageView!.contentMode = UIViewContentMode.center backButton.alpha = 0 backButton.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 25) backButton.addTarget( self, action:#selector(actionBack(sender:)), for:UIControlEvents.touchUpInside) self.backButton = backButton addSubview(label) addSubview(backButton) addSubview(collectionView) let views:[String:UIView] = [ "collectionView":collectionView, "backButton":backButton, "label":label] let metrics:[String:CGFloat] = [ "barHeight":barHeight, "barDelta":barDelta] addConstraints(NSLayoutConstraint.constraints( withVisualFormat:"H:|-60-[label]-60-|", options:[], metrics:metrics, views:views)) addConstraints(NSLayoutConstraint.constraints( withVisualFormat:"H:|-0-[backButton(60)]", options:[], metrics:metrics, views:views)) addConstraints(NSLayoutConstraint.constraints( withVisualFormat:"H:|-0-[collectionView]-0-|", options:[], metrics:metrics, views:views)) addConstraints(NSLayoutConstraint.constraints( withVisualFormat:"V:[collectionView(barHeight)]-0-|", options:[], metrics:metrics, views:views)) addConstraints(NSLayoutConstraint.constraints( withVisualFormat:"V:[backButton(barDelta)]-0-|", options:[], metrics:metrics, views:views)) addConstraints(NSLayoutConstraint.constraints( withVisualFormat:"V:[label(barDelta)]-0-|", options:[], metrics:metrics, views:views)) DispatchQueue.main.asyncAfter(deadline:DispatchTime.now() + kWaitingTime) { let indexPath:IndexPath = IndexPath(item:self.model.current.index, section:0) self.collectionView.selectItem( at:indexPath, animated:false, scrollPosition:UICollectionViewScrollPosition()) } } required init?(coder:NSCoder) { fatalError() } override func layoutSubviews() { let width:CGFloat = bounds.maxX if currentWidth != width { currentWidth = width collectionView.collectionViewLayout.invalidateLayout() } DispatchQueue.main.async { let currentHeight:CGFloat = self.bounds.maxY let deltaHeight:CGFloat = self.barHeight - currentHeight let deltaPercent:CGFloat = deltaHeight / self.barDelta let alpha:CGFloat = 1 - deltaPercent if self.model.state.showOptions() { self.collectionView.alpha = alpha } if self.model.state.showBackButton() { self.backButton.alpha = alpha } if self.model.state.showTitle() { self.label.alpha = alpha } } super.layoutSubviews() } //MARK: actions func actionBack(sender button:UIButton) { parent.pop() } //MARK: private private func modelAtIndex(index:IndexPath) -> MMainItem { let item:MMainItem = model.items[index.item] return item } private func selectItem(item:MMainItem) { let controller:CController = item.controller() if item.index < model.current.index { parent.scrollLeft(controller:controller) } else { parent.scrollRight(controller:controller) } model.current = item } //MARK: public func push(name:String?) { model.pushed() label.text = name let alphaCollection:CGFloat let alphaBackButton:CGFloat let alphaLabel:CGFloat if model.state.showOptions() { alphaCollection = 1 } else { alphaCollection = 0 } if model.state.showBackButton() { alphaBackButton = 1 } else { alphaBackButton = 0 } if model.state.showTitle() { alphaLabel = 1 } else { alphaLabel = 0 } UIView.animate(withDuration:kAnimationDuration) { self.collectionView.alpha = alphaCollection self.backButton.alpha = alphaBackButton self.label.alpha = alphaLabel } } func pop() { model.poped() let alphaCollection:CGFloat let alphaBackButton:CGFloat let alphaLabel:CGFloat if model.state.showOptions() { alphaCollection = 1 } else { alphaCollection = 0 } if model.state.showBackButton() { alphaBackButton = 1 } else { alphaBackButton = 0 } if model.state.showTitle() { alphaLabel = 1 } else { alphaLabel = 0 } UIView.animate(withDuration:kAnimationDuration) { self.collectionView.alpha = alphaCollection self.backButton.alpha = alphaBackButton self.label.alpha = alphaLabel } } func synthSelect(index:Int) { let menuItem:MMainItem = model.items[index] let indexPath:IndexPath = IndexPath(item:index, section:0) selectItem(item:menuItem) collectionView.selectItem( at:indexPath, animated:true, scrollPosition:UICollectionViewScrollPosition.centeredHorizontally) } //MARK: col del func collectionView(_ collectionView:UICollectionView, layout collectionViewLayout:UICollectionViewLayout, insetForSectionAt section:Int) -> UIEdgeInsets { let width:CGFloat = collectionView.bounds.maxX let cellsWidth:CGFloat = kCellWidth * CGFloat(model.items.count) let remain:CGFloat = width - cellsWidth let margin:CGFloat = remain / 2.0 let insets:UIEdgeInsets = UIEdgeInsetsMake(0, margin, 0, margin) return insets } func collectionView(_ collectionView:UICollectionView, layout collectionViewLayout:UICollectionViewLayout, sizeForItemAt indexPath:IndexPath) -> CGSize { let height:CGFloat = collectionView.bounds.maxY let size:CGSize = CGSize(width:kCellWidth, height:height) return size } func numberOfSections(in collectionView:UICollectionView) -> Int { return 1 } func collectionView(_ collectionView:UICollectionView, numberOfItemsInSection section:Int) -> Int { let count:Int = model.items.count return count } func collectionView(_ collectionView:UICollectionView, cellForItemAt indexPath:IndexPath) -> UICollectionViewCell { let item:MMainItem = modelAtIndex(index:indexPath) let cell:VBarCell = collectionView.dequeueReusableCell( withReuseIdentifier:VBarCell.reusableIdentifier, for:indexPath) as! VBarCell cell.config(model:item) return cell } func collectionView(_ collectionView:UICollectionView, didSelectItemAt indexPath:IndexPath) { let item:MMainItem = modelAtIndex(index:indexPath) if item !== model.current { selectItem(item:item) } } }
mit
fbe1223df69525b5399b53d608bc855f
28.969188
157
0.589401
5.885039
false
false
false
false
PureSwift/DBus
Sources/DBus/ObjectPath.swift
1
9148
// // ObjectPath.swift // DBus // // Created by Alsey Coleman Miller on 10/20/18. // import Foundation import CDBus /** DBus Object Path (e.g "`/com/example/MusicPlayer1`") The following rules define a valid object path. Implementations must not send or accept messages with invalid object paths. The path may be of any length. The path must begin with an ASCII '/' (integer 47) character, and must consist of elements separated by slash characters. Each element must only contain the ASCII characters "[A-Z][a-z][0-9]_" No element may be the empty string. Multiple '/' characters cannot occur in sequence. A trailing '/' character is not allowed unless the path is the root path (a single '/' character). */ public struct DBusObjectPath { @_versioned internal private(set) var elements: [Element] /// Cached string. /// This will be the original string the object path was created from. /// /// - Note: Any subsequent mutation will set this value to nil, and `rawValue` and `description` getters /// will have to rebuild the string for every invocation. So mutating leads to the unoptimized code path, /// but for values created from either a string or an array of elements, this value is cached. @_versioned internal private(set) var string: String? /// Initialize with an array of elements. public init(_ elements: [Element] = []) { self.elements = elements self.string = String(elements) } } internal extension DBusObjectPath { init(_ unsafe: String) { guard let value = DBusObjectPath(rawValue: unsafe) else { fatalError("Invalid object path \(unsafe)") } self = value } } // MARK: - String Parsing internal extension DBusObjectPath { static let separator = "/".first! /// Parses the object path string and returns the parsed object path. static func parse(_ string: String) -> [Element]? { // The path must begin with an ASCII '/' (integer 47) character, // and must consist of elements separated by slash characters. guard let firstCharacter = string.first, // cant't be empty string firstCharacter == separator, // must start with "/" string.count == 1 || string.last != separator // last character else { return nil } let pathStrings = string.split(separator: separator, maxSplits: .max, omittingEmptySubsequences: true) var elements = [Element]() elements.reserveCapacity(pathStrings.count) // pre-allocate buffer for elementString in pathStrings { guard let element = Element(substring: elementString) else { return nil } elements.append(element) } return elements } static func validate(_ string: String) throws { let error = DBusError.Reference() guard Bool(dbus_validate_path(string, &error.internalValue)) else { throw DBusError(error)! } } } internal extension String { init(_ objectPath: [DBusObjectPath.Element]) { let separator = String(DBusObjectPath.separator) self = objectPath.isEmpty ? separator : objectPath.reduce("", { $0 + separator + $1.rawValue }) } } // MARK: - RawRepresentable extension DBusObjectPath: RawRepresentable { public init?(rawValue: String) { guard let elements = DBusObjectPath.parse(rawValue) else { return nil } self.elements = elements self.string = rawValue // store original string } public var rawValue: String { get { return string ?? String(elements) } } } // MARK: - Equatable extension DBusObjectPath: Equatable { public static func == (lhs: DBusObjectPath, rhs: DBusObjectPath) -> Bool { // fast path if let lhsString = lhs.string, let rhsString = rhs.string { return lhsString == rhsString } // slower comparison return lhs.elements == rhs.elements } } // MARK: - Hashable extension DBusObjectPath: Hashable { public var hashValue: Int { return rawValue.hashValue } } // MARK: - CustomStringConvertible extension DBusObjectPath: CustomStringConvertible { public var description: String { return rawValue } } // MARK: - Array Literal extension DBusObjectPath: ExpressibleByArrayLiteral { public init(arrayLiteral elements: Element...) { self.init(elements) } } // MARK: - Collection extension DBusObjectPath: MutableCollection { public typealias Index = Int public subscript (index: Index) -> Element { get { return elements[index] } mutating set { string = nil elements[index] = newValue } } public var count: Int { return elements.count } /// The start `Index`. public var startIndex: Index { return 0 } /// The end `Index`. /// /// This is the "one-past-the-end" position, and will always be equal to the `count`. public var endIndex: Index { return count } public func index(before i: Index) -> Index { return i - 1 } public func index(after i: Index) -> Index { return i + 1 } public func makeIterator() -> IndexingIterator<DBusObjectPath> { return IndexingIterator(_elements: self) } /// Adds a new element at the end of the object path. /// /// Use this method to append a single element to the end of a mutable object path. public mutating func append(_ element: Element) { string = nil elements.append(element) } /// Removes and returns the first element of the object path. /// /// - Precondition: The object path must not be empty. @discardableResult public mutating func removeFirst() -> Element { string = nil return elements.removeFirst() } /// Removes and returns the last element of the object path. /// /// - Precondition: The object path must not be empty. @discardableResult public mutating func removeLast() -> Element { string = nil return elements.removeLast() } /// Removes and returns the element at the specified position. /// /// All the elements following the specified position are moved up to close the gap. @discardableResult public mutating func remove(at index: Int) -> Element { string = nil return elements.remove(at: index) } /// Removes all elements from the object path. public mutating func removeAll() { self = DBusObjectPath() } } extension DBusObjectPath: RandomAccessCollection { } // MARK: - Element public extension DBusObjectPath { /// An element in the object path public struct Element { /// Don't copy buffer of individual elements, because these elements will always be created /// from a bigger string, which we should just internally reference. internal let substring: Substring /// Designated initializer. internal init?(substring: Substring) { // validate string guard substring.isEmpty == false, // No element may be an empty string. substring.contains(DBusObjectPath.separator) == false, // Multiple '/' characters cannot occur in sequence. substring.rangeOfCharacter(from: Element.invalidCharacters) == nil // only ASCII characters "[A-Z][a-z][0-9]_" else { return nil } self.substring = substring } } } extension DBusObjectPath.Element: RawRepresentable { public init?(rawValue: String) { // This API will rarely be used let substring = Substring(rawValue) self.init(substring: substring) } public var rawValue: String { return String(substring) } } private extension DBusObjectPath.Element { /// only ASCII characters "[A-Z][a-z][0-9]_" static let invalidCharacters = CharacterSet(charactersIn: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLKMNOPQRSTUVWXYZ0123456789_").inverted } extension DBusObjectPath.Element: Equatable { public static func == (lhs: DBusObjectPath.Element, rhs: DBusObjectPath.Element) -> Bool { return lhs.substring == rhs.substring } } extension DBusObjectPath.Element: CustomStringConvertible { public var description: String { return rawValue } } extension DBusObjectPath.Element: Hashable { public var hashValue: Int { return substring.hashValue } }
mit
31260af92ee24f8eb4ab155cddf8b307
25.905882
138
0.606143
5.107761
false
false
false
false
RLovelett/langserver-swift
Sources/LanguageServerProtocol/Functions/CommonRoot.swift
1
1308
// // CommonRoot.swift // langserver-swift // // Created by Ryan Lovelett on 12/24/16. // // import Foundation /// Extract the Swift module root directory. /// /// The module root directory is the longest common path between two sources in the module. Or /// if there is only 1 source then its just the last directory. /// /// ``` /// let urls = [ /// URL(fileURLWithPath: "/module/Sources/dir1/dir1.A/foo.swift", isDirectory: false), /// URL(fileURLWithPath: "/module/Sources/dir1/bar.swift", isDirectory: false) /// ] /// commonRoot(urls) // Returns /module/Sources/dir1/ /// ``` /// /// - Precondition: The collection cannot be empty. /// /// - Parameter sources: A collection of fully qualified paths to Swift sources in a module. /// - Returns: The root directory of the collection. func commonRoot<C: Collection>(_ sources: C) -> URL where C.Iterator.Element == URL { precondition(!sources.isEmpty, "A module must have at least 1 source.") if sources.count == 1, let single = sources.first { return single.deletingLastPathComponent() } else { let first = sources[sources.startIndex] let second = sources[sources.index(after: sources.startIndex)] return URL(fileURLWithPath: first.path.commonPrefix(with: second.path), isDirectory: true) } }
apache-2.0
fb62b85f738caaa1d18ca937ac5c8ae6
32.538462
98
0.682722
3.881306
false
false
false
false
atrick/swift
stdlib/public/core/ContiguouslyStored.swift
7
3339
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2018 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 // //===----------------------------------------------------------------------===// // NOTE: The below is necessary for fast String initialization from untyped // memory. When we add Collection.withContiguousRawStorageIfAvailable(), we can // deprecate this functionality. @usableFromInline internal protocol _HasContiguousBytes { func withUnsafeBytes<R>( _ body: (UnsafeRawBufferPointer) throws -> R ) rethrows -> R var _providesContiguousBytesNoCopy: Bool { get } } extension _HasContiguousBytes { @inlinable var _providesContiguousBytesNoCopy: Bool { @inline(__always) get { return true } } } extension Array: _HasContiguousBytes { @inlinable var _providesContiguousBytesNoCopy: Bool { @inline(__always) get { #if _runtime(_ObjC) return _buffer._isNative #else return true #endif } } } extension ContiguousArray: _HasContiguousBytes {} extension UnsafeBufferPointer: _HasContiguousBytes { @inlinable @inline(__always) func withUnsafeBytes<R>( _ body: (UnsafeRawBufferPointer) throws -> R ) rethrows -> R { let ptr = UnsafeRawPointer(self.baseAddress) let len = self.count &* MemoryLayout<Element>.stride return try body(UnsafeRawBufferPointer(start: ptr, count: len)) } } extension UnsafeMutableBufferPointer: _HasContiguousBytes { @inlinable @inline(__always) func withUnsafeBytes<R>( _ body: (UnsafeRawBufferPointer) throws -> R ) rethrows -> R { let ptr = UnsafeRawPointer(self.baseAddress) let len = self.count &* MemoryLayout<Element>.stride return try body(UnsafeRawBufferPointer(start: ptr, count: len)) } } extension UnsafeRawBufferPointer: _HasContiguousBytes { @inlinable @inline(__always) func withUnsafeBytes<R>( _ body: (UnsafeRawBufferPointer) throws -> R ) rethrows -> R { return try body(self) } } extension UnsafeMutableRawBufferPointer: _HasContiguousBytes { @inlinable @inline(__always) func withUnsafeBytes<R>( _ body: (UnsafeRawBufferPointer) throws -> R ) rethrows -> R { return try body(UnsafeRawBufferPointer(self)) } } extension String: _HasContiguousBytes { @inlinable internal var _providesContiguousBytesNoCopy: Bool { @inline(__always) get { return self._guts.isFastUTF8 } } @inlinable @inline(__always) internal func withUnsafeBytes<R>( _ body: (UnsafeRawBufferPointer) throws -> R ) rethrows -> R { var copy = self return try copy.withUTF8 { return try body(UnsafeRawBufferPointer($0)) } } } extension Substring: _HasContiguousBytes { @inlinable internal var _providesContiguousBytesNoCopy: Bool { @inline(__always) get { return self._wholeGuts.isFastUTF8 } } @inlinable @inline(__always) internal func withUnsafeBytes<R>( _ body: (UnsafeRawBufferPointer) throws -> R ) rethrows -> R { var copy = self return try copy.withUTF8 { return try body(UnsafeRawBufferPointer($0)) } } }
apache-2.0
0738bee41393d649fd1cbf4e8758c1f6
30.205607
80
0.681641
4.66993
false
false
false
false
anirudh24seven/wikipedia-ios
Wikipedia/Code/WMFWelcomeAnalyticsViewController.swift
1
1992
class WMFWelcomeAnalyticsViewController: UIViewController { @IBOutlet private var toggleLabel:UILabel! @IBOutlet private var toggle:UISwitch! override func viewDidLoad() { super.viewDidLoad() updateToggleLabelTitleForUsageReportsIsOn(false) //Set state of the toggle. Also make sure crash manager setting is in sync with this setting - likely to happen on first launch or for previous users. if (NSUserDefaults.wmf_userDefaults().wmf_sendUsageReports()) { toggle.on = true BITHockeyManager.sharedHockeyManager().crashManager.crashManagerStatus = .AutoSend } else { toggle.on = false BITHockeyManager.sharedHockeyManager().crashManager.crashManagerStatus = .AlwaysAsk } } private func updateToggleLabelTitleForUsageReportsIsOn(isOn: Bool) { //Hide accessibility of label because switch will become the label by default. toggleLabel.isAccessibilityElement = false let title = isOn ? localizedStringForKeyFallingBackOnEnglish("welcome-volunteer-thanks").stringByReplacingOccurrencesOfString("$1", withString: "😀") : localizedStringForKeyFallingBackOnEnglish("welcome-volunteer-send-usage-reports") toggleLabel.text = title toggle.accessibilityLabel = localizedStringForKeyFallingBackOnEnglish("welcome-volunteer-send-usage-reports") } @IBAction func toggleAnalytics(withSender sender: UISwitch){ if(sender.on){ BITHockeyManager.sharedHockeyManager().crashManager.crashManagerStatus = .AutoSend NSUserDefaults.wmf_userDefaults().wmf_setSendUsageReports(true) }else{ BITHockeyManager.sharedHockeyManager().crashManager.crashManagerStatus = .AlwaysAsk NSUserDefaults.wmf_userDefaults().wmf_setSendUsageReports(false) } updateToggleLabelTitleForUsageReportsIsOn(sender.on) } }
mit
6171e16c48ed040dd2d279a80bd65246
44.204545
240
0.702363
5.650568
false
false
false
false
PJayRushton/StarvingStudentGuide
StarvingStudentGuide/Deal.swift
1
1739
// // Deal.swift // StarvingStudentGuide // // Created by Parker Rushton on 3/7/16. // Copyright © 2016 AppsByPJ. All rights reserved. // import UIKit import CoreData func circleImageForQuantity(quantity: Int) -> UIImage? { if quantity < 0 { return UIImage(named: "circleUnlimited") } else { return UIImage(named: "circle\(quantity)") } } @objc(Deal) final class Deal: NSManagedObject, Unmarshaling { @NSManaged var store: Store @NSManaged var category: String @NSManaged var info: String @NSManaged var details: String? @NSManaged var quantity: Int @NSManaged var available: Int @NSManaged var buyOneGetOne: Bool @NSManaged var iWant: Bool var used: Int { return quantity - available } var couponCategory: CouponCategory { return CouponCategory.categoryFromString(category) } convenience init(object: MarshaledObject) throws { let entity = NSEntityDescription.entityForName("Deal", inManagedObjectContext: Stack.sharedInstance.managedObjectContext) self.init(entity: entity!, insertIntoManagedObjectContext: Stack.sharedInstance.managedObjectContext) category = try object <| "category" info = try object <| "info" details = try object <| "details" quantity = try object <| "quantity" available = try object <| "quantity" buyOneGetOne = try object <| "bogof" iWant = try object <| "iWant" } func markOneUsed() { if quantity < 1 { return } else if available < 1 { return } else { available -= 1 } Stack.sharedInstance.saveContext() } }
mit
c6688ced3b7784bdb1abf33f4b52ebd8
26.15625
129
0.627158
4.573684
false
false
false
false
dymx101/Gamers
Gamers/ViewModels/SearchCell.swift
1
1717
// // SeachCell.swift // Gamers // // Created by 虚空之翼 on 15/7/27. // Copyright (c) 2015年 Freedom. All rights reserved. // import UIKit class SearchCell: UITableViewCell { @IBOutlet weak var videoImage: UIImageView! @IBOutlet weak var videoTitle: UILabel! @IBOutlet weak var videoChannel: UILabel! @IBOutlet weak var videoViews: UILabel! @IBAction func clickShare(sender: AnyObject) { self.delegate.clickCellButton!(self) } var delegate: MyCellDelegate! override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } func setVideo(video: Video) { videoChannel.text = video.owner videoTitle.text = video.videoTitle videoViews.text = BasicFunction.formatViewsTotal(video.views) + " • " + BasicFunction.formatDateString(video.publishedAt) let imageUrl = video.imageSource.stringByReplacingOccurrencesOfString(" ", withString: "%20", options: NSStringCompareOptions.LiteralSearch, range: nil) videoImage.hnk_setImageFromURL(NSURL(string: imageUrl)!) } override func setHighlighted(highlighted: Bool, animated: Bool) { super.setHighlighted(highlighted, animated: animated) if highlighted { self.delegate.hideKeyboard!(self) } } override func prepareForReuse() { super.prepareForReuse() videoImage.hnk_cancelSetImage() videoImage.image = nil } }
apache-2.0
4bf65c414f3de64001c85be939755de7
26.063492
160
0.649267
4.76257
false
false
false
false
kzaher/RxSwift
RxCocoa/Traits/SharedSequence/SharedSequence.swift
6
8648
// // SharedSequence.swift // RxCocoa // // Created by Krunoslav Zaher on 8/27/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import RxSwift /** Trait that represents observable sequence that shares computation resources with following properties: - it never fails - it delivers events on `SharingStrategy.scheduler` - sharing strategy is customizable using `SharingStrategy.share` behavior `SharedSequence<Element>` can be considered a builder pattern for observable sequences that share computation resources. To find out more about units and how to use them, please visit `Documentation/Traits.md`. */ public struct SharedSequence<SharingStrategy: SharingStrategyProtocol, Element> : SharedSequenceConvertibleType, ObservableConvertibleType { let source: Observable<Element> init(_ source: Observable<Element>) { self.source = SharingStrategy.share(source) } init(raw: Observable<Element>) { self.source = raw } #if EXPANDABLE_SHARED_SEQUENCE /** This method is extension hook in case this unit needs to extended from outside the library. By defining `EXPANDABLE_SHARED_SEQUENCE` one agrees that it's up to them to ensure shared sequence properties are preserved after extension. */ public static func createUnsafe<Source: ObservableType>(source: Source) -> SharedSequence<SharingStrategy, Source.Element> { SharedSequence<SharingStrategy, Source.Element>(raw: source.asObservable()) } #endif /** - returns: Built observable sequence. */ public func asObservable() -> Observable<Element> { self.source } /** - returns: `self` */ public func asSharedSequence() -> SharedSequence<SharingStrategy, Element> { self } } /** Different `SharedSequence` sharing strategies must conform to this protocol. */ public protocol SharingStrategyProtocol { /** Scheduled on which all sequence events will be delivered. */ static var scheduler: SchedulerType { get } /** Computation resources sharing strategy for multiple sequence observers. E.g. One can choose `share(replay:scope:)` as sequence event sharing strategies, but also do something more exotic, like implementing promises or lazy loading chains. */ static func share<Element>(_ source: Observable<Element>) -> Observable<Element> } /** A type that can be converted to `SharedSequence`. */ public protocol SharedSequenceConvertibleType : ObservableConvertibleType { associatedtype SharingStrategy: SharingStrategyProtocol /** Converts self to `SharedSequence`. */ func asSharedSequence() -> SharedSequence<SharingStrategy, Element> } extension SharedSequenceConvertibleType { public func asObservable() -> Observable<Element> { self.asSharedSequence().asObservable() } } extension SharedSequence { /** Returns an empty observable sequence, using the specified scheduler to send out the single `Completed` message. - returns: An observable sequence with no elements. */ public static func empty() -> SharedSequence<SharingStrategy, Element> { SharedSequence(raw: Observable.empty().subscribe(on: SharingStrategy.scheduler)) } /** Returns a non-terminating observable sequence, which can be used to denote an infinite duration. - returns: An observable sequence whose observers will never get called. */ public static func never() -> SharedSequence<SharingStrategy, Element> { SharedSequence(raw: Observable.never()) } /** Returns an observable sequence that contains a single element. - parameter element: Single element in the resulting observable sequence. - returns: An observable sequence containing the single specified element. */ public static func just(_ element: Element) -> SharedSequence<SharingStrategy, Element> { SharedSequence(raw: Observable.just(element).subscribe(on: SharingStrategy.scheduler)) } /** Returns an observable sequence that invokes the specified factory function whenever a new observer subscribes. - parameter observableFactory: Observable factory function to invoke for each observer that subscribes to the resulting sequence. - returns: An observable sequence whose observers trigger an invocation of the given observable factory function. */ public static func deferred(_ observableFactory: @escaping () -> SharedSequence<SharingStrategy, Element>) -> SharedSequence<SharingStrategy, Element> { SharedSequence(Observable.deferred { observableFactory().asObservable() }) } /** This method creates a new Observable instance with a variable number of elements. - seealso: [from operator on reactivex.io](http://reactivex.io/documentation/operators/from.html) - parameter elements: Elements to generate. - returns: The observable sequence whose elements are pulled from the given arguments. */ public static func of(_ elements: Element ...) -> SharedSequence<SharingStrategy, Element> { let source = Observable.from(elements, scheduler: SharingStrategy.scheduler) return SharedSequence(raw: source) } } extension SharedSequence { /** This method converts an array to an observable sequence. - seealso: [from operator on reactivex.io](http://reactivex.io/documentation/operators/from.html) - returns: The observable sequence whose elements are pulled from the given enumerable sequence. */ public static func from(_ array: [Element]) -> SharedSequence<SharingStrategy, Element> { let source = Observable.from(array, scheduler: SharingStrategy.scheduler) return SharedSequence(raw: source) } /** This method converts a sequence to an observable sequence. - seealso: [from operator on reactivex.io](http://reactivex.io/documentation/operators/from.html) - returns: The observable sequence whose elements are pulled from the given enumerable sequence. */ public static func from<Sequence: Swift.Sequence>(_ sequence: Sequence) -> SharedSequence<SharingStrategy, Element> where Sequence.Element == Element { let source = Observable.from(sequence, scheduler: SharingStrategy.scheduler) return SharedSequence(raw: source) } /** This method converts a optional to an observable sequence. - seealso: [from operator on reactivex.io](http://reactivex.io/documentation/operators/from.html) - parameter optional: Optional element in the resulting observable sequence. - returns: An observable sequence containing the wrapped value or not from given optional. */ public static func from(optional: Element?) -> SharedSequence<SharingStrategy, Element> { let source = Observable.from(optional: optional, scheduler: SharingStrategy.scheduler) return SharedSequence(raw: source) } } extension SharedSequence where Element: RxAbstractInteger { /** Returns an observable sequence that produces a value after each period, using the specified scheduler to run timers and to send out observer messages. - seealso: [interval operator on reactivex.io](http://reactivex.io/documentation/operators/interval.html) - parameter period: Period for producing the values in the resulting sequence. - returns: An observable sequence that produces a value after each period. */ public static func interval(_ period: RxTimeInterval) -> SharedSequence<SharingStrategy, Element> { SharedSequence(Observable.interval(period, scheduler: SharingStrategy.scheduler)) } } // MARK: timer extension SharedSequence where Element: RxAbstractInteger { /** Returns an observable sequence that periodically produces a value after the specified initial relative due time has elapsed, using the specified scheduler to run timers. - seealso: [timer operator on reactivex.io](http://reactivex.io/documentation/operators/timer.html) - parameter dueTime: Relative time at which to produce the first value. - parameter period: Period to produce subsequent values. - returns: An observable sequence that produces a value after due time has elapsed and then each period. */ public static func timer(_ dueTime: RxTimeInterval, period: RxTimeInterval) -> SharedSequence<SharingStrategy, Element> { SharedSequence(Observable.timer(dueTime, period: period, scheduler: SharingStrategy.scheduler)) } }
mit
ec2d97e2a1700df096fe94221ac8a473
37.261062
174
0.720134
5.256535
false
false
false
false
riteshhgupta/RGListKit
Pods/ReactiveCocoa/ReactiveCocoa/NSObject+Intercepting.swift
2
16430
import Foundation import ReactiveSwift import enum Result.NoError /// Whether the runtime subclass has already been prepared for method /// interception. fileprivate let interceptedKey = AssociationKey(default: false) /// Holds the method signature cache of the runtime subclass. fileprivate let signatureCacheKey = AssociationKey<SignatureCache>() /// Holds the method selector cache of the runtime subclass. fileprivate let selectorCacheKey = AssociationKey<SelectorCache>() internal let noImplementation: IMP = unsafeBitCast(Int(0), to: IMP.self) extension Reactive where Base: NSObject { /// Create a signal which sends a `next` event at the end of every /// invocation of `selector` on the object. /// /// It completes when the object deinitializes. /// /// - note: Observers to the resulting signal should not call the method /// specified by the selector. /// /// - parameters: /// - selector: The selector to observe. /// /// - returns: A trigger signal. public func trigger(for selector: Selector) -> Signal<(), NoError> { return base.intercept(selector).map { _ in } } /// Create a signal which sends a `next` event, containing an array of /// bridged arguments, at the end of every invocation of `selector` on the /// object. /// /// It completes when the object deinitializes. /// /// - note: Observers to the resulting signal should not call the method /// specified by the selector. /// /// - parameters: /// - selector: The selector to observe. /// /// - returns: A signal that sends an array of bridged arguments. public func signal(for selector: Selector) -> Signal<[Any?], NoError> { return base.intercept(selector).map(unpackInvocation) } } extension NSObject { /// Setup the method interception. /// /// - parameters: /// - object: The object to be intercepted. /// - selector: The selector of the method to be intercepted. /// /// - returns: A signal that sends the corresponding `NSInvocation` after /// every invocation of the method. @nonobjc fileprivate func intercept(_ selector: Selector) -> Signal<AnyObject, NoError> { guard let method = class_getInstanceMethod(objcClass, selector) else { fatalError("Selector `\(selector)` does not exist in class `\(String(describing: objcClass))`.") } let typeEncoding = method_getTypeEncoding(method)! assert(checkTypeEncoding(typeEncoding)) return synchronized { let alias = selector.alias let stateKey = AssociationKey<InterceptingState?>(alias) let interopAlias = selector.interopAlias if let state = associations.value(forKey: stateKey) { return state.signal } let subclass: AnyClass = swizzleClass(self) let subclassAssociations = Associations(subclass as AnyObject) // FIXME: Compiler asks to handle a mysterious throw. try! ReactiveCocoa.synchronized(subclass) { let isSwizzled = subclassAssociations.value(forKey: interceptedKey) let signatureCache: SignatureCache let selectorCache: SelectorCache if isSwizzled { signatureCache = subclassAssociations.value(forKey: signatureCacheKey) selectorCache = subclassAssociations.value(forKey: selectorCacheKey) } else { signatureCache = SignatureCache() selectorCache = SelectorCache() subclassAssociations.setValue(signatureCache, forKey: signatureCacheKey) subclassAssociations.setValue(selectorCache, forKey: selectorCacheKey) subclassAssociations.setValue(true, forKey: interceptedKey) enableMessageForwarding(subclass, selectorCache) setupMethodSignatureCaching(subclass, signatureCache) } selectorCache.cache(selector) if signatureCache[selector] == nil { let signature = NSMethodSignature.signature(withObjCTypes: typeEncoding) signatureCache[selector] = signature } // If an immediate implementation of the selector is found in the // runtime subclass the first time the selector is intercepted, // preserve the implementation. // // Example: KVO setters if the instance is swizzled by KVO before RAC // does. if !class_respondsToSelector(subclass, interopAlias) { let immediateImpl = class_getImmediateMethod(subclass, selector) .flatMap(method_getImplementation) .flatMap { $0 != _rac_objc_msgForward ? $0 : nil } if let impl = immediateImpl { let succeeds = class_addMethod(subclass, interopAlias, impl, typeEncoding) precondition(succeeds, "RAC attempts to swizzle a selector that has message forwarding enabled with a runtime injected implementation. This is unsupported in the current version.") } } } let state = InterceptingState(lifetime: reactive.lifetime) associations.setValue(state, forKey: stateKey) // Start forwarding the messages of the selector. _ = class_replaceMethod(subclass, selector, _rac_objc_msgForward, typeEncoding) return state.signal } } } /// Swizzle `realClass` to enable message forwarding for method interception. /// /// - parameters: /// - realClass: The runtime subclass to be swizzled. private func enableMessageForwarding(_ realClass: AnyClass, _ selectorCache: SelectorCache) { let perceivedClass: AnyClass = class_getSuperclass(realClass)! typealias ForwardInvocationImpl = @convention(block) (Unmanaged<NSObject>, AnyObject) -> Void let newForwardInvocation: ForwardInvocationImpl = { objectRef, invocation in let selector = invocation.selector! let alias = selectorCache.alias(for: selector) let interopAlias = selectorCache.interopAlias(for: selector) defer { let stateKey = AssociationKey<InterceptingState?>(alias) if let state = objectRef.takeUnretainedValue().associations.value(forKey: stateKey) { state.observer.send(value: invocation) } } let method = class_getInstanceMethod(perceivedClass, selector)! let typeEncoding = method_getTypeEncoding(method) if class_respondsToSelector(realClass, interopAlias) { // RAC has preserved an immediate implementation found in the runtime // subclass that was supplied by an external party. // // As the KVO setter relies on the selector to work, it has to be invoked // by swapping in the preserved implementation and restore to the message // forwarder afterwards. // // However, the IMP cache would be thrashed due to the swapping. let topLevelClass: AnyClass = object_getClass(objectRef.takeUnretainedValue())! // The locking below prevents RAC swizzling attempts from intervening the // invocation. // // Given the implementation of `swizzleClass`, `topLevelClass` can only be: // (1) the same as `realClass`; or (2) a subclass of `realClass`. In other // words, this would deadlock only if the locking order is not followed in // other nested locking scenarios of these metaclasses at compile time. synchronized(topLevelClass) { func swizzle() { let interopImpl = class_getMethodImplementation(topLevelClass, interopAlias)! let previousImpl = class_replaceMethod(topLevelClass, selector, interopImpl, typeEncoding) invocation.invoke() _ = class_replaceMethod(topLevelClass, selector, previousImpl ?? noImplementation, typeEncoding) } if topLevelClass != realClass { synchronized(realClass) { // In addition to swapping in the implementation, the message // forwarding needs to be temporarily disabled to prevent circular // invocation. _ = class_replaceMethod(realClass, selector, noImplementation, typeEncoding) swizzle() _ = class_replaceMethod(realClass, selector, _rac_objc_msgForward, typeEncoding) } } else { swizzle() } } return } let impl = method_getImplementation(method) if impl != _rac_objc_msgForward { // The perceived class, or its ancestors, responds to the selector. // // The implementation is invoked through the selector alias, which // reflects the latest implementation of the selector in the perceived // class. if class_getMethodImplementation(realClass, alias) != impl { // Update the alias if and only if the implementation has changed, so as // to avoid thrashing the IMP cache. _ = class_replaceMethod(realClass, alias, impl, typeEncoding) } invocation.setSelector(alias) invocation.invoke() return } // Forward the invocation to the closest `forwardInvocation(_:)` in the // inheritance hierarchy, or the default handler returned by the runtime // if it finds no implementation. typealias SuperForwardInvocation = @convention(c) (Unmanaged<NSObject>, Selector, AnyObject) -> Void let forwardInvocationImpl = class_getMethodImplementation(perceivedClass, ObjCSelector.forwardInvocation) let forwardInvocation = unsafeBitCast(forwardInvocationImpl, to: SuperForwardInvocation.self) forwardInvocation(objectRef, ObjCSelector.forwardInvocation, invocation) } _ = class_replaceMethod(realClass, ObjCSelector.forwardInvocation, imp_implementationWithBlock(newForwardInvocation as Any), ObjCMethodEncoding.forwardInvocation) } /// Swizzle `realClass` to accelerate the method signature retrieval, using a /// signature cache that covers all known intercepted selectors of `realClass`. /// /// - parameters: /// - realClass: The runtime subclass to be swizzled. /// - signatureCache: The method signature cache. private func setupMethodSignatureCaching(_ realClass: AnyClass, _ signatureCache: SignatureCache) { let perceivedClass: AnyClass = class_getSuperclass(realClass)! let newMethodSignatureForSelector: @convention(block) (Unmanaged<NSObject>, Selector) -> AnyObject? = { objectRef, selector in if let signature = signatureCache[selector] { return signature } typealias SuperMethodSignatureForSelector = @convention(c) (Unmanaged<NSObject>, Selector, Selector) -> AnyObject? let impl = class_getMethodImplementation(perceivedClass, ObjCSelector.methodSignatureForSelector) let methodSignatureForSelector = unsafeBitCast(impl, to: SuperMethodSignatureForSelector.self) return methodSignatureForSelector(objectRef, ObjCSelector.methodSignatureForSelector, selector) } _ = class_replaceMethod(realClass, ObjCSelector.methodSignatureForSelector, imp_implementationWithBlock(newMethodSignatureForSelector as Any), ObjCMethodEncoding.methodSignatureForSelector) } /// The state of an intercepted method specific to an instance. private final class InterceptingState { let (signal, observer) = Signal<AnyObject, NoError>.pipe() /// Initialize a state specific to an instance. /// /// - parameters: /// - lifetime: The lifetime of the instance. init(lifetime: Lifetime) { lifetime.ended.observeCompleted(observer.sendCompleted) } } private final class SelectorCache { private var map: [Selector: (main: Selector, interop: Selector)] = [:] init() {} /// Cache the aliases of the specified selector in the cache. /// /// - warning: Any invocation of this method must be synchronized against the /// runtime subclass. @discardableResult func cache(_ selector: Selector) -> (main: Selector, interop: Selector) { if let pair = map[selector] { return pair } let aliases = (selector.alias, selector.interopAlias) map[selector] = aliases return aliases } /// Get the alias of the specified selector. /// /// - parameters: /// - selector: The selector alias. func alias(for selector: Selector) -> Selector { if let (main, _) = map[selector] { return main } return selector.alias } /// Get the secondary alias of the specified selector. /// /// - parameters: /// - selector: The selector alias. func interopAlias(for selector: Selector) -> Selector { if let (_, interop) = map[selector] { return interop } return selector.interopAlias } } // The signature cache for classes that have been swizzled for method // interception. // // Read-copy-update is used here, since the cache has multiple readers but only // one writer. private final class SignatureCache { // `Dictionary` takes 8 bytes for the reference to its storage and does CoW. // So it should not encounter any corrupted, partially updated state. private var map: [Selector: AnyObject] = [:] init() {} /// Get or set the signature for the specified selector. /// /// - warning: Any invocation of the setter must be synchronized against the /// runtime subclass. /// /// - parameters: /// - selector: The method signature. subscript(selector: Selector) -> AnyObject? { get { return map[selector] } set { if map[selector] == nil { map[selector] = newValue } } } } /// Assert that the method does not contain types that cannot be intercepted. /// /// - parameters: /// - types: The type encoding C string of the method. /// /// - returns: `true`. private func checkTypeEncoding(_ types: UnsafePointer<CChar>) -> Bool { // Some types, including vector types, are not encoded. In these cases the // signature starts with the size of the argument frame. assert(types.pointee < Int8(UInt8(ascii: "1")) || types.pointee > Int8(UInt8(ascii: "9")), "unknown method return type not supported in type encoding: \(String(cString: types))") assert(types.pointee != Int8(UInt8(ascii: "(")), "union method return type not supported") assert(types.pointee != Int8(UInt8(ascii: "{")), "struct method return type not supported") assert(types.pointee != Int8(UInt8(ascii: "[")), "array method return type not supported") assert(types.pointee != Int8(UInt8(ascii: "j")), "complex method return type not supported") return true } /// Extract the arguments of an `NSInvocation` as an array of objects. /// /// - parameters: /// - invocation: The `NSInvocation` to unpack. /// /// - returns: An array of objects. private func unpackInvocation(_ invocation: AnyObject) -> [Any?] { let invocation = invocation as AnyObject let methodSignature = invocation.objcMethodSignature! let count = UInt(methodSignature.numberOfArguments!) var bridged = [Any?]() bridged.reserveCapacity(Int(count - 2)) // Ignore `self` and `_cmd` at index 0 and 1. for position in 2 ..< count { let rawEncoding = methodSignature.argumentType(at: position) let encoding = ObjCTypeEncoding(rawValue: rawEncoding.pointee) ?? .undefined func extract<U>(_ type: U.Type) -> U { let pointer = UnsafeMutableRawPointer.allocate(bytes: MemoryLayout<U>.size, alignedTo: MemoryLayout<U>.alignment) defer { pointer.deallocate(bytes: MemoryLayout<U>.size, alignedTo: MemoryLayout<U>.alignment) } invocation.copy(to: pointer, forArgumentAt: Int(position)) return pointer.assumingMemoryBound(to: type).pointee } let value: Any? switch encoding { case .char: value = NSNumber(value: extract(CChar.self)) case .int: value = NSNumber(value: extract(CInt.self)) case .short: value = NSNumber(value: extract(CShort.self)) case .long: value = NSNumber(value: extract(CLong.self)) case .longLong: value = NSNumber(value: extract(CLongLong.self)) case .unsignedChar: value = NSNumber(value: extract(CUnsignedChar.self)) case .unsignedInt: value = NSNumber(value: extract(CUnsignedInt.self)) case .unsignedShort: value = NSNumber(value: extract(CUnsignedShort.self)) case .unsignedLong: value = NSNumber(value: extract(CUnsignedLong.self)) case .unsignedLongLong: value = NSNumber(value: extract(CUnsignedLongLong.self)) case .float: value = NSNumber(value: extract(CFloat.self)) case .double: value = NSNumber(value: extract(CDouble.self)) case .bool: value = NSNumber(value: extract(CBool.self)) case .object: value = extract((AnyObject?).self) case .type: value = extract((AnyClass?).self) case .selector: value = extract((Selector?).self) case .undefined: var size = 0, alignment = 0 NSGetSizeAndAlignment(rawEncoding, &size, &alignment) let buffer = UnsafeMutableRawPointer.allocate(bytes: size, alignedTo: alignment) defer { buffer.deallocate(bytes: size, alignedTo: alignment) } invocation.copy(to: buffer, forArgumentAt: Int(position)) value = NSValue(bytes: buffer, objCType: rawEncoding) } bridged.append(value) } return bridged }
mit
77de6e708d2ef0fb263993b535879949
34.639913
186
0.714851
4.276419
false
false
false
false
florianmari/LiveGQL
Source/Classes/JSONHelper.swift
1
1252
// // JSONHelper.swift // DevGQLMain // // Created by Florian Mari on 23/07/2017. // Copyright © 2017 Florian. All rights reserved. // import Foundation protocol JSONRepresentable { var JSONRepresentation: Any { get } } protocol JSONSerializable: JSONRepresentable { } extension JSONSerializable { var JSONRepresentation: Any { var representation = [String: Any]() for case let (label?, value) in Mirror(reflecting: self).children { switch value { case let value as JSONRepresentable: representation[label] = value.JSONRepresentation case let value as NSObject: representation[label] = value default: break } } return representation } } extension JSONSerializable { func toJSON() -> String? { let representation = JSONRepresentation guard JSONSerialization.isValidJSONObject(representation) else { return nil } do { let data = try JSONSerialization.data(withJSONObject: representation, options: []) return String(data: data, encoding: String.Encoding.utf8) } catch { return nil } } }
mit
760e280655358542cfc19ec1a74dc6c1
24.02
94
0.605915
5.106122
false
false
false
false
soapyigu/Swift30Projects
Project 12 - Tumblr/Tumblr/TransitionManager.swift
1
5298
// // TransitionManager.swift // Tumblr // // Created by Yi Gu on 7/11/16. // Copyright © 2016 yigu. All rights reserved. // import UIKit class TransitionManager: NSObject { fileprivate var presenting = false } extension TransitionManager: UIViewControllerAnimatedTransitioning { func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { let container = transitionContext.containerView // create a tuple of our screens let screens : (from:UIViewController, to:UIViewController) = (transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from)!, transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to)!) // assign references to our menu view controller and the 'bottom' view controller from the tuple // remember that our menuViewController will alternate between the from and to view controller depending if we're presenting or dismissing let menuViewController = !self.presenting ? screens.from as! MenuViewController : screens.to as! MenuViewController let bottomViewController = !self.presenting ? screens.to as UIViewController : screens.from as UIViewController let menuView = menuViewController.view let bottomView = bottomViewController.view // prepare the menu if (self.presenting){ // prepare menu to fade in offStageMenuController(menuViewController) } // add the both views to our view controller container.addSubview(bottomView!) container.addSubview(menuView!) let duration = self.transitionDuration(using: transitionContext) UIView.animate(withDuration: duration, delay: 0.0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.8, options: [], animations: { if (self.presenting){ self.onStageMenuController(menuViewController) // onstage items: slide in } else { self.offStageMenuController(menuViewController) // offstage items: slide out } }, completion: { finished in transitionContext.completeTransition(true) UIApplication.shared.keyWindow?.addSubview(screens.to.view) }) } func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return 0.5 } func offStage(_ amount: CGFloat) -> CGAffineTransform { return CGAffineTransform(translationX: amount, y: 0) } func offStageMenuController(_ menuViewController: MenuViewController){ menuViewController.view.alpha = 0 // setup paramaters for 2D transitions for animations let topRowOffset :CGFloat = 300 let middleRowOffset :CGFloat = 150 let bottomRowOffset :CGFloat = 50 menuViewController.textPostIcon.transform = self.offStage(-topRowOffset) menuViewController.textPostLabel.transform = self.offStage(-topRowOffset) menuViewController.quotePostIcon.transform = self.offStage(-middleRowOffset) menuViewController.quotePostLabel.transform = self.offStage(-middleRowOffset) menuViewController.chatPostIcon.transform = self.offStage(-bottomRowOffset) menuViewController.chatPostLabel.transform = self.offStage(-bottomRowOffset) menuViewController.photoPostIcon.transform = self.offStage(topRowOffset) menuViewController.photoPostLabel.transform = self.offStage(topRowOffset) menuViewController.linkPostIcon.transform = self.offStage(middleRowOffset) menuViewController.linkPostLabel.transform = self.offStage(middleRowOffset) menuViewController.audioPostIcon.transform = self.offStage(bottomRowOffset) menuViewController.audioPostLabel.transform = self.offStage(bottomRowOffset) } func onStageMenuController(_ menuViewController: MenuViewController){ // prepare menu to fade in menuViewController.view.alpha = 1 menuViewController.textPostIcon.transform = CGAffineTransform.identity menuViewController.textPostLabel.transform = CGAffineTransform.identity menuViewController.quotePostIcon.transform = CGAffineTransform.identity menuViewController.quotePostLabel.transform = CGAffineTransform.identity menuViewController.chatPostIcon.transform = CGAffineTransform.identity menuViewController.chatPostLabel.transform = CGAffineTransform.identity menuViewController.photoPostIcon.transform = CGAffineTransform.identity menuViewController.photoPostLabel.transform = CGAffineTransform.identity menuViewController.linkPostIcon.transform = CGAffineTransform.identity menuViewController.linkPostLabel.transform = CGAffineTransform.identity menuViewController.audioPostIcon.transform = CGAffineTransform.identity menuViewController.audioPostLabel.transform = CGAffineTransform.identity } } extension TransitionManager: UIViewControllerTransitioningDelegate { func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? { self.presenting = true return self } func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { self.presenting = false return self } }
apache-2.0
e2bcd99c2e38af7af0ad7c17dfea7aba
38.529851
235
0.764017
5.8337
false
false
false
false
aferodeveloper/sango
Source/Utils.swift
1
5625
/** * Copyright 2016 Afero, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import Foundation open class Utils { static var verbose = false public static func setVerbose(_ state: Bool) -> Void { verbose = state } public static func debug(_ message: String) -> Void { if (verbose) { print(message) } } public static func error(_ message: String) -> Void { print(message) } public static func always(_ message: String) -> Void { print(message) } public static func toJSON(_ dictionary:Dictionary<String, Any>) -> String? { do { var keys = JSONSerialization.WritingOptions.prettyPrinted if #available(OSX 10.13, *) { keys = [JSONSerialization.WritingOptions.sortedKeys, JSONSerialization.WritingOptions.prettyPrinted] } let data: Data = try JSONSerialization.data(withJSONObject: dictionary, options: keys) if let jsonString = NSString(data: data, encoding: String.Encoding.utf8.rawValue) { return jsonString.replacingOccurrences(of: "\\/", with: "/") } return nil } catch let error as NSError { let message:String = error.userInfo["NSDebugDescription"] as! String Utils.error(message) return nil } } public static func fromJSONFile(_ file:String) -> [String:Any]? { var result:[String: Any]? let location = NSString(string: file).expandingTildeInPath let fileContent = try? Data(contentsOf: URL(fileURLWithPath: location)) if (fileContent != nil) { result = fromJSON(fileContent!) if (result == nil) { Utils.error("Error: Can't parse \(location) as JSON") } } else { Utils.error("Error: can't find file \(location)") } return result } public static func fromJSON(_ data:Data) -> [String: Any]? { var dict: Any? do { dict = try JSONSerialization.jsonObject(with: data, options: .allowFragments) } catch let error as NSError { let message:String = error.userInfo["NSDebugDescription"] as! String Utils.error(message) dict = nil } return dict as? [String: Any] } public static func createFolders(_ folders: [String]) -> Bool { for file in folders { do { try FileManager.default.createDirectory(atPath: file, withIntermediateDirectories: true, attributes: nil) } catch { Utils.error("Error: creating folder \(file)") exit(-1) } } return true } @discardableResult public static func createFolderForFile(_ srcFile: String) -> Bool { let destPath = (srcFile as NSString).deletingLastPathComponent return createFolder(destPath) } @discardableResult public static func createFolder(_ src: String) -> Bool { var ok = true do { try FileManager.default.createDirectory(atPath: src, withIntermediateDirectories: true, attributes: nil) } catch { Utils.error("Error: creating folder \(src)") ok = false } return ok } @discardableResult public static func deleteFolder(_ src: String) -> Bool { var ok = true do { try FileManager.default.removeItem(atPath: src) } catch { ok = false } return ok } public static func copyFile(_ src: String, dest: String) -> Bool { deleteFile(dest) var ok = true do { try FileManager.default.copyItem(atPath: src, toPath: dest) Utils.debug("Copy \(src) -> \(dest)") } catch { Utils.error("Error: copying file \(src) to \(dest): \(String(reflecting: error))") ok = false } return ok } public static func copyFiles(_ files: [String], useRoot: Bool, srcRootPath: String, dstRootPath: String) -> Void { for file in files { let filePath = srcRootPath + "/" + file var destFile:String if (useRoot) { destFile = dstRootPath + "/" + file.lastPathComponent() } else { destFile = dstRootPath + "/" + file } let destPath = (destFile as NSString).deletingLastPathComponent createFolder(destPath) if (copyFile(filePath, dest: destFile) == false) { exit(-1) } } } @discardableResult public static func deleteFile(_ src: String) -> Bool { var ok = true do { try FileManager.default.removeItem(atPath: src) } catch { ok = false } return ok } } // EOF
apache-2.0
585de746ceacaab4846d350dd65585bf
29.906593
121
0.556089
4.938543
false
false
false
false
brentsimmons/Evergreen
Account/Sources/Account/ReaderAPI/ReaderAPICaller.swift
1
24970
// // ReaderAPICaller.swift // Account // // Created by Jeremy Beker on 5/28/19. // Copyright © 2019 Ranchero Software, LLC. All rights reserved. // import Foundation import RSWeb import Secrets enum CreateReaderAPISubscriptionResult { case created(ReaderAPISubscription) case notFound } final class ReaderAPICaller: NSObject { enum ItemIDType { case unread case starred case allForAccount case allForFeed } private enum ReaderState: String { case read = "user/-/state/com.google/read" case starred = "user/-/state/com.google/starred" } private enum ReaderStreams: String { case readingList = "user/-/state/com.google/reading-list" } private enum ReaderAPIEndpoints: String { case login = "/accounts/ClientLogin" case token = "/reader/api/0/token" case disableTag = "/reader/api/0/disable-tag" case renameTag = "/reader/api/0/rename-tag" case tagList = "/reader/api/0/tag/list" case subscriptionList = "/reader/api/0/subscription/list" case subscriptionEdit = "/reader/api/0/subscription/edit" case subscriptionAdd = "/reader/api/0/subscription/quickadd" case contents = "/reader/api/0/stream/items/contents" case itemIds = "/reader/api/0/stream/items/ids" case editTag = "/reader/api/0/edit-tag" } private var transport: Transport! private let uriComponentAllowed: CharacterSet private var accessToken: String? weak var accountMetadata: AccountMetadata? var variant: ReaderAPIVariant = .generic var credentials: Credentials? var server: String? { get { return apiBaseURL?.host } } private var apiBaseURL: URL? { get { switch variant { case .generic, .freshRSS: guard let accountMetadata = accountMetadata else { return nil } return accountMetadata.endpointURL default: return URL(string: variant.host) } } } init(transport: Transport) { self.transport = transport var urlHostAllowed = CharacterSet.urlHostAllowed urlHostAllowed.remove("+") urlHostAllowed.remove("&") uriComponentAllowed = urlHostAllowed super.init() } func cancelAll() { transport.cancelAll() } func validateCredentials(endpoint: URL, completion: @escaping (Result<Credentials?, Error>) -> Void) { guard let credentials = credentials else { completion(.failure(CredentialsError.incompleteCredentials)) return } var request = URLRequest(url: endpoint.appendingPathComponent(ReaderAPIEndpoints.login.rawValue), credentials: credentials) addVariantHeaders(&request) transport.send(request: request) { result in switch result { case .success(let (_, data)): guard let resultData = data else { completion(.failure(TransportError.noData)) break } // Convert the return data to UTF8 and then parse out the Auth token guard let rawData = String(data: resultData, encoding: .utf8) else { completion(.failure(TransportError.noData)) break } var authData: [String: String] = [:] rawData.split(separator: "\n").forEach({ (line: Substring) in let items = line.split(separator: "=").map{String($0)} if items.count == 2 { authData[items[0]] = items[1] } }) guard let authString = authData["Auth"] else { completion(.failure(CredentialsError.incompleteCredentials)) break } // Save Auth Token for later use self.credentials = Credentials(type: .readerAPIKey, username: credentials.username, secret: authString) completion(.success(self.credentials)) case .failure(let error): if let transportError = error as? TransportError, case .httpError(let code) = transportError, code == 404 { completion(.failure(ReaderAPIAccountDelegateError.urlNotFound)) } else { completion(.failure(error)) } } } } func requestAuthorizationToken(endpoint: URL, completion: @escaping (Result<String, Error>) -> Void) { // If we have a token already, use it if let accessToken = accessToken { completion(.success(accessToken)) return } // Otherwise request one. guard let credentials = credentials else { completion(.failure(CredentialsError.incompleteCredentials)) return } var request = URLRequest(url: endpoint.appendingPathComponent(ReaderAPIEndpoints.token.rawValue), credentials: credentials) addVariantHeaders(&request) transport.send(request: request) { result in switch result { case .success(let (_, data)): guard let resultData = data else { completion(.failure(TransportError.noData)) break } // Convert the return data to UTF8 and then parse out the Auth token guard let accessToken = String(data: resultData, encoding: .utf8) else { completion(.failure(TransportError.noData)) break } self.accessToken = accessToken completion(.success(accessToken)) case .failure(let error): completion(.failure(error)) } } } func retrieveTags(completion: @escaping (Result<[ReaderAPITag]?, Error>) -> Void) { guard let baseURL = apiBaseURL else { completion(.failure(CredentialsError.incompleteCredentials)) return } var url = baseURL .appendingPathComponent(ReaderAPIEndpoints.tagList.rawValue) .appendingQueryItem(URLQueryItem(name: "output", value: "json")) if variant == .inoreader { url = url?.appendingQueryItem(URLQueryItem(name: "types", value: "1")) } guard let callURL = url else { completion(.failure(TransportError.noURL)) return } var request = URLRequest(url: callURL, credentials: credentials) addVariantHeaders(&request) transport.send(request: request, resultType: ReaderAPITagContainer.self) { result in switch result { case .success(let (_, wrapper)): completion(.success(wrapper?.tags)) case .failure(let error): completion(.failure(error)) } } } func renameTag(oldName: String, newName: String, completion: @escaping (Result<Void, Error>) -> Void) { guard let baseURL = apiBaseURL else { completion(.failure(CredentialsError.incompleteCredentials)) return } self.requestAuthorizationToken(endpoint: baseURL) { (result) in switch result { case .success(let token): var request = URLRequest(url: baseURL.appendingPathComponent(ReaderAPIEndpoints.renameTag.rawValue), credentials: self.credentials) self.addVariantHeaders(&request) request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") request.httpMethod = "POST" guard let encodedOldName = self.encodeForURLPath(oldName), let encodedNewName = self.encodeForURLPath(newName) else { completion(.failure(ReaderAPIAccountDelegateError.invalidParameter)) return } let oldTagName = "user/-/label/\(encodedOldName)" let newTagName = "user/-/label/\(encodedNewName)" let postData = "T=\(token)&s=\(oldTagName)&dest=\(newTagName)".data(using: String.Encoding.utf8) self.transport.send(request: request, method: HTTPMethod.post, payload: postData!, completion: { (result) in switch result { case .success: completion(.success(())) break case .failure(let error): completion(.failure(error)) break } }) case .failure(let error): completion(.failure(error)) } } } func deleteTag(folder: Folder, completion: @escaping (Result<Void, Error>) -> Void) { guard let baseURL = apiBaseURL else { completion(.failure(CredentialsError.incompleteCredentials)) return } guard let folderExternalID = folder.externalID else { completion(.failure(ReaderAPIAccountDelegateError.invalidParameter)) return } self.requestAuthorizationToken(endpoint: baseURL) { (result) in switch result { case .success(let token): var request = URLRequest(url: baseURL.appendingPathComponent(ReaderAPIEndpoints.disableTag.rawValue), credentials: self.credentials) self.addVariantHeaders(&request) request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") request.httpMethod = "POST" let postData = "T=\(token)&s=\(folderExternalID)".data(using: String.Encoding.utf8) self.transport.send(request: request, method: HTTPMethod.post, payload: postData!, completion: { (result) in switch result { case .success: completion(.success(())) break case .failure(let error): completion(.failure(error)) break } }) case .failure(let error): completion(.failure(error)) } } } func retrieveSubscriptions(completion: @escaping (Result<[ReaderAPISubscription]?, Error>) -> Void) { guard let baseURL = apiBaseURL else { completion(.failure(CredentialsError.incompleteCredentials)) return } let url = baseURL .appendingPathComponent(ReaderAPIEndpoints.subscriptionList.rawValue) .appendingQueryItem(URLQueryItem(name: "output", value: "json")) guard let callURL = url else { completion(.failure(TransportError.noURL)) return } var request = URLRequest(url: callURL, credentials: credentials) addVariantHeaders(&request) transport.send(request: request, resultType: ReaderAPISubscriptionContainer.self) { result in switch result { case .success(let (_, container)): completion(.success(container?.subscriptions)) case .failure(let error): completion(.failure(error)) } } } func createSubscription(url: String, name: String?, folder: Folder?, completion: @escaping (Result<CreateReaderAPISubscriptionResult, Error>) -> Void) { guard let baseURL = apiBaseURL else { completion(.failure(CredentialsError.incompleteCredentials)) return } func findSubscription(streamID: String, completion: @escaping (Result<CreateReaderAPISubscriptionResult, Error>) -> Void) { // There is no call to get a single subscription entry, so we get them all, // look up the one we just subscribed to and return that self.retrieveSubscriptions(completion: { (result) in switch result { case .success(let subscriptions): guard let subscriptions = subscriptions else { completion(.failure(AccountError.createErrorNotFound)) return } guard let subscription = subscriptions.first(where: { (sub) -> Bool in sub.feedID == streamID }) else { completion(.failure(AccountError.createErrorNotFound)) return } completion(.success(.created(subscription))) case .failure(let error): completion(.failure(error)) } }) } self.requestAuthorizationToken(endpoint: baseURL) { (result) in switch result { case .success(let token): let callURL = baseURL .appendingPathComponent(ReaderAPIEndpoints.subscriptionAdd.rawValue) var request = URLRequest(url: callURL, credentials: self.credentials) self.addVariantHeaders(&request) request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") request.httpMethod = "POST" guard let encodedFeedURL = self.encodeForURLPath(url) else { completion(.failure(ReaderAPIAccountDelegateError.invalidParameter)) return } let postData = "T=\(token)&quickadd=\(encodedFeedURL)".data(using: String.Encoding.utf8) self.transport.send(request: request, method: HTTPMethod.post, data: postData!, resultType: ReaderAPIQuickAddResult.self, completion: { (result) in switch result { case .success(let (_, subResult)): switch subResult?.numResults { case 0: completion(.success(.notFound)) default: guard let streamId = subResult?.streamId else { completion(.failure(AccountError.createErrorNotFound)) return } findSubscription(streamID: streamId, completion: completion) } case .failure(let error): completion(.failure(error)) } }) case .failure(let error): completion(.failure(error)) } } } func renameSubscription(subscriptionID: String, newName: String, completion: @escaping (Result<Void, Error>) -> Void) { changeSubscription(subscriptionID: subscriptionID, title: newName, completion: completion) } func deleteSubscription(subscriptionID: String, completion: @escaping (Result<Void, Error>) -> Void) { guard let baseURL = apiBaseURL else { completion(.failure(CredentialsError.incompleteCredentials)) return } self.requestAuthorizationToken(endpoint: baseURL) { (result) in switch result { case .success(let token): var request = URLRequest(url: baseURL.appendingPathComponent(ReaderAPIEndpoints.subscriptionEdit.rawValue), credentials: self.credentials) self.addVariantHeaders(&request) request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") request.httpMethod = "POST" let postData = "T=\(token)&s=\(subscriptionID)&ac=unsubscribe".data(using: String.Encoding.utf8) self.transport.send(request: request, method: HTTPMethod.post, payload: postData!, completion: { (result) in switch result { case .success: completion(.success(())) break case .failure(let error): completion(.failure(error)) break } }) case .failure(let error): completion(.failure(error)) } } } func createTagging(subscriptionID: String, tagName: String, completion: @escaping (Result<Void, Error>) -> Void) { changeSubscription(subscriptionID: subscriptionID, addTagName: tagName, completion: completion) } func deleteTagging(subscriptionID: String, tagName: String, completion: @escaping (Result<Void, Error>) -> Void) { changeSubscription(subscriptionID: subscriptionID, removeTagName: tagName, completion: completion) } func moveSubscription(subscriptionID: String, fromTag: String, toTag: String, completion: @escaping (Result<Void, Error>) -> Void) { changeSubscription(subscriptionID: subscriptionID, removeTagName: fromTag, addTagName: toTag, completion: completion) } private func changeSubscription(subscriptionID: String, removeTagName: String? = nil, addTagName: String? = nil, title: String? = nil, completion: @escaping (Result<Void, Error>) -> Void) { guard removeTagName != nil || addTagName != nil || title != nil else { completion(.failure(ReaderAPIAccountDelegateError.invalidParameter)) return } guard let baseURL = apiBaseURL else { completion(.failure(CredentialsError.incompleteCredentials)) return } self.requestAuthorizationToken(endpoint: baseURL) { (result) in switch result { case .success(let token): var request = URLRequest(url: baseURL.appendingPathComponent(ReaderAPIEndpoints.subscriptionEdit.rawValue), credentials: self.credentials) self.addVariantHeaders(&request) request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") request.httpMethod = "POST" var postString = "T=\(token)&s=\(subscriptionID)&ac=edit" if let fromLabel = self.encodeForURLPath(removeTagName) { postString += "&r=user/-/label/\(fromLabel)" } if let toLabel = self.encodeForURLPath(addTagName) { postString += "&a=user/-/label/\(toLabel)" } if let encodedTitle = self.encodeForURLPath(title) { postString += "&t=\(encodedTitle)" } let postData = postString.data(using: String.Encoding.utf8) self.transport.send(request: request, method: HTTPMethod.post, payload: postData!, completion: { (result) in switch result { case .success: completion(.success(())) break case .failure(let error): completion(.failure(error)) break } }) case .failure(let error): completion(.failure(error)) } } } func retrieveEntries(articleIDs: [String], completion: @escaping (Result<([ReaderAPIEntry]?), Error>) -> Void) { guard !articleIDs.isEmpty else { completion(.success(([ReaderAPIEntry]()))) return } guard let baseURL = apiBaseURL else { completion(.failure(CredentialsError.incompleteCredentials)) return } self.requestAuthorizationToken(endpoint: baseURL) { (result) in switch result { case .success(let token): var request = URLRequest(url: baseURL.appendingPathComponent(ReaderAPIEndpoints.contents.rawValue), credentials: self.credentials) self.addVariantHeaders(&request) request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") request.httpMethod = "POST" // Get ids from above into hex representation of value let idsToFetch = articleIDs.map({ articleID -> String in if self.variant == .theOldReader { return "i=tag:google.com,2005:reader/item/\(articleID)" } else { let idValue = Int(articleID)! let idHexString = String(idValue, radix: 16, uppercase: false) return "i=tag:google.com,2005:reader/item/\(idHexString)" } }).joined(separator:"&") let postData = "T=\(token)&output=json&\(idsToFetch)".data(using: String.Encoding.utf8) self.transport.send(request: request, method: HTTPMethod.post, data: postData!, resultType: ReaderAPIEntryWrapper.self, completion: { (result) in switch result { case .success(let (_, entryWrapper)): guard let entryWrapper = entryWrapper else { completion(.failure(ReaderAPIAccountDelegateError.invalidResponse)) return } completion(.success((entryWrapper.entries))) case .failure(let error): completion(.failure(error)) } }) case .failure(let error): completion(.failure(error)) } } } func retrieveItemIDs(type: ItemIDType, webFeedID: String? = nil, completion: @escaping ((Result<[String], Error>) -> Void)) { guard let baseURL = apiBaseURL else { completion(.failure(CredentialsError.incompleteCredentials)) return } var queryItems = [ URLQueryItem(name: "n", value: "1000"), URLQueryItem(name: "output", value: "json") ] switch type { case .allForAccount: let since: Date = { if let lastArticleFetch = self.accountMetadata?.lastArticleFetchStartTime { return lastArticleFetch } else { return Calendar.current.date(byAdding: .month, value: -3, to: Date()) ?? Date() } }() let sinceTimeInterval = since.timeIntervalSince1970 queryItems.append(URLQueryItem(name: "ot", value: String(Int(sinceTimeInterval)))) queryItems.append(URLQueryItem(name: "s", value: ReaderStreams.readingList.rawValue)) case .allForFeed: guard let webFeedID = webFeedID else { completion(.failure(ReaderAPIAccountDelegateError.invalidParameter)) return } let sinceTimeInterval = (Calendar.current.date(byAdding: .month, value: -3, to: Date()) ?? Date()).timeIntervalSince1970 queryItems.append(URLQueryItem(name: "ot", value: String(Int(sinceTimeInterval)))) queryItems.append(URLQueryItem(name: "s", value: webFeedID)) case .unread: queryItems.append(URLQueryItem(name: "s", value: ReaderStreams.readingList.rawValue)) queryItems.append(URLQueryItem(name: "xt", value: ReaderState.read.rawValue)) case .starred: queryItems.append(URLQueryItem(name: "s", value: ReaderState.starred.rawValue)) } let url = baseURL .appendingPathComponent(ReaderAPIEndpoints.itemIds.rawValue) .appendingQueryItems(queryItems) guard let callURL = url else { completion(.failure(TransportError.noURL)) return } var request: URLRequest = URLRequest(url: callURL, credentials: credentials) addVariantHeaders(&request) self.transport.send(request: request, resultType: ReaderAPIReferenceWrapper.self) { result in switch result { case .success(let (response, entries)): guard let entriesItemRefs = entries?.itemRefs, entriesItemRefs.count > 0 else { completion(.success([String]())) return } let dateInfo = HTTPDateInfo(urlResponse: response) let itemIDs = entriesItemRefs.compactMap { $0.itemId } self.retrieveItemIDs(type: type, url: callURL, dateInfo: dateInfo, itemIDs: itemIDs, continuation: entries?.continuation, completion: completion) case .failure(let error): completion(.failure(error)) } } } func retrieveItemIDs(type: ItemIDType, url: URL, dateInfo: HTTPDateInfo?, itemIDs: [String], continuation: String?, completion: @escaping ((Result<[String], Error>) -> Void)) { guard let continuation = continuation else { if type == .allForAccount { self.accountMetadata?.lastArticleFetchStartTime = dateInfo?.date self.accountMetadata?.lastArticleFetchEndTime = Date() } completion(.success(itemIDs)) return } guard var urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false) else { completion(.failure(ReaderAPIAccountDelegateError.invalidParameter)) return } var queryItems = urlComponents.queryItems!.filter({ $0.name != "c" }) queryItems.append(URLQueryItem(name: "c", value: continuation)) urlComponents.queryItems = queryItems guard let callURL = urlComponents.url else { completion(.failure(TransportError.noURL)) return } var request: URLRequest = URLRequest(url: callURL, credentials: credentials) addVariantHeaders(&request) self.transport.send(request: request, resultType: ReaderAPIReferenceWrapper.self) { result in switch result { case .success(let (_, entries)): guard let entriesItemRefs = entries?.itemRefs, entriesItemRefs.count > 0 else { self.retrieveItemIDs(type: type, url: callURL, dateInfo: dateInfo, itemIDs: itemIDs, continuation: entries?.continuation, completion: completion) return } var totalItemIDs = itemIDs totalItemIDs.append(contentsOf: entriesItemRefs.compactMap { $0.itemId }) self.retrieveItemIDs(type: type, url: callURL, dateInfo: dateInfo, itemIDs: totalItemIDs, continuation: entries?.continuation, completion: completion) case .failure(let error): completion(.failure(error)) } } } func createUnreadEntries(entries: [String], completion: @escaping (Result<Void, Error>) -> Void) { updateStateToEntries(entries: entries, state: .read, add: false, completion: completion) } func deleteUnreadEntries(entries: [String], completion: @escaping (Result<Void, Error>) -> Void) { updateStateToEntries(entries: entries, state: .read, add: true, completion: completion) } func createStarredEntries(entries: [String], completion: @escaping (Result<Void, Error>) -> Void) { updateStateToEntries(entries: entries, state: .starred, add: true, completion: completion) } func deleteStarredEntries(entries: [String], completion: @escaping (Result<Void, Error>) -> Void) { updateStateToEntries(entries: entries, state: .starred, add: false, completion: completion) } } // MARK: Private private extension ReaderAPICaller { func encodeForURLPath(_ pathComponent: String?) -> String? { guard let pathComponent = pathComponent else { return nil } return pathComponent.addingPercentEncoding(withAllowedCharacters: uriComponentAllowed) } func addVariantHeaders(_ request: inout URLRequest) { if variant == .inoreader { request.addValue(SecretsManager.provider.inoreaderAppId, forHTTPHeaderField: "AppId") request.addValue(SecretsManager.provider.inoreaderAppKey, forHTTPHeaderField: "AppKey") } } private func updateStateToEntries(entries: [String], state: ReaderState, add: Bool, completion: @escaping (Result<Void, Error>) -> Void) { guard let baseURL = apiBaseURL else { completion(.failure(CredentialsError.incompleteCredentials)) return } self.requestAuthorizationToken(endpoint: baseURL) { (result) in switch result { case .success(let token): // Do POST asking for data about all the new articles var request = URLRequest(url: baseURL.appendingPathComponent(ReaderAPIEndpoints.editTag.rawValue), credentials: self.credentials) self.addVariantHeaders(&request) request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") request.httpMethod = "POST" // Get ids from above into hex representation of value let idsToFetch = entries.compactMap({ idValue -> String? in if self.variant == .theOldReader { return "i=tag:google.com,2005:reader/item/\(idValue)" } else { guard let intValue = Int(idValue) else { return nil } let idHexString = String(format: "%.16llx", intValue) return "i=tag:google.com,2005:reader/item/\(idHexString)" } }).joined(separator:"&") let actionIndicator = add ? "a" : "r" let postData = "T=\(token)&\(idsToFetch)&\(actionIndicator)=\(state.rawValue)".data(using: String.Encoding.utf8) self.transport.send(request: request, method: HTTPMethod.post, payload: postData!, completion: { (result) in switch result { case .success: completion(.success(())) case .failure(let error): completion(.failure(error)) } }) case .failure(let error): completion(.failure(error)) } } } }
mit
8a19593528542fe6699659366410226e
32.381016
190
0.704313
4.050122
false
false
false
false
iainsmith/Features
Features/FeaturePercentageStore.swift
1
865
// // FeatureStore.swift // Features // // Created by iainsmith on 11/07/2016. // Copyright © 2016 Mountain23. All rights reserved. // import Foundation public protocol FeaturePercentageStore { var feature_storedPercentage: UInt? { get set } } extension NSUserDefaults: FeaturePercentageStore { private static let featurePercentageKey = "com.features.percentage" public var feature_storedPercentage: UInt? { get { let value = integerForKey(NSUserDefaults.featurePercentageKey) guard value != 0 else { return nil } return UInt(value) } set { let key = NSUserDefaults.featurePercentageKey if let value = newValue { setInteger(Int(value), forKey: key) } else { removeObjectForKey(key) } } } }
mit
3f6ae696b89874b0d4db3da2418cea4b
23.685714
74
0.612269
4.620321
false
false
false
false
youkchansim/CSPhotoGallery
Pod/Classes/CSPhotoGalleryViewController.swift
1
16224
// // CSPhotoGalleryViewController.swift // CSPhotoGallery // // Created by Youk Chansim on 2016. 12. 7.. // Copyright © 2016년 Youk Chansim. All rights reserved. // import UIKit import Photos typealias CSObservation = UInt8 public class CSPhotoGalleryViewController: UIViewController { public static var instance: CSPhotoGalleryViewController { let podBundle = Bundle(for: CSPhotoGalleryViewController.self) let bundleURL = podBundle.url(forResource: "CSPhotoGallery", withExtension: "bundle") let bundle = bundleURL == nil ? podBundle : Bundle(url: bundleURL!) let storyBoard = UIStoryboard.init(name: "CSPhotoGallery", bundle: bundle) return storyBoard.instantiateViewController(withIdentifier: identifier) as! CSPhotoGalleryViewController } @IBOutlet fileprivate weak var collectionName: UILabel! { didSet { let gesture = UITapGestureRecognizer(target: self, action: #selector(collectionNameTap(_:))) collectionName.addGestureRecognizer(gesture) collectionName.isUserInteractionEnabled = true } } @IBOutlet fileprivate weak var collectionNameArrow: UILabel! @IBOutlet fileprivate weak var checkCount: UILabel! { didSet { checkCount.isHidden = CSPhotoDesignManager.instance.isOKButtonHidden } } @IBOutlet fileprivate weak var okBtn: UIButton! { didSet { if let title = CSPhotoDesignManager.instance.photoGalleryOKButtonTitle { okBtn.setTitle(title, for: .normal) } okBtn.isHidden = CSPhotoDesignManager.instance.isOKButtonHidden } } @IBOutlet fileprivate weak var backBtn: UIButton! { didSet { if let image = CSPhotoDesignManager.instance.photoGalleryBackButtonImage { backBtn.setImage(image, for: .normal) } } } @IBOutlet fileprivate weak var collectionView: UICollectionView! public var delegate: CSPhotoGalleryDelegate? public var mediaType: CSPhotoImageType = .image public var CHECK_MAX_COUNT = 20 public var horizontalCount: CGFloat = 3 fileprivate var assetCollectionViewController = CSPhotoGalleryAssetCollectionViewController.instance fileprivate var thumbnailSize: CGSize = CGSize.zero fileprivate var CSObservationContext = CSObservation() fileprivate var CSCollectionObservationContext = CSObservation() fileprivate var transitionDelegate: CSPhotoViewerTransition = CSPhotoViewerTransition() var checkImage: UIImage? var unCheckImage: UIImage? override public func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. setViewController() setThumbnailSize() checkPhotoLibraryPermission() } override public func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { if context == &CSObservationContext { let count = PhotoManager.sharedInstance.selectedItemCount setCheckCountLabel(count: count) } else if context == &CSCollectionObservationContext { setTitle() reloadCollectionView() } else { super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context) } } deinit { PhotoManager.sharedInstance.removeObserver(self, forKeyPath: "selectedItemCount") PhotoManager.sharedInstance.removeObserver(self, forKeyPath: "currentCollection") PhotoManager.sharedInstance.remover(object: self) } } // MARK:- Gesture extension CSPhotoGalleryViewController { func collectionNameTap(_ sender: UITapGestureRecognizer) { assetCollectionViewController.isHidden = !assetCollectionViewController.isHidden collectionNameArrow.text = assetCollectionViewController.isHidden ? "▼" : "▲" } func reloadCollectionView() { DispatchQueue.main.async { self.collectionView.reloadData() } } func updateCollectionViewCellUI(indexPath: IndexPath) { DispatchQueue.main.async { let cell = self.collectionView.cellForItem(at: indexPath) as? CSPhotoGalleryCollectionViewCell cell?.setButtonImage() } } func collectionViewCellFrame(at indexPath: IndexPath) -> CGRect { let item = collectionView.layoutAttributesForItem(at: indexPath) var frame = item!.frame frame.origin.y = frame.origin.y - collectionView.contentOffset.y + collectionView.frame.origin.y return frame } func scrollRectToVisible(indexPath: IndexPath) { let rect = collectionView.layoutAttributesForItem(at: indexPath)?.frame ?? CGRect.zero let currentOffsetY = collectionView.contentOffset.y // 상단 if currentOffsetY > rect.origin.y { collectionView.contentOffset.y = rect.origin.y // 하단 } else if currentOffsetY + collectionView.frame.height < rect.origin.y + rect.height { collectionView.contentOffset.y = rect.origin.y + rect.height - collectionView.frame.height } } func durationToText(time: TimeInterval) -> String { let time = Date(timeIntervalSince1970: time) let dateFormater = DateFormatter() dateFormater.dateFormat = "mm:ss" return dateFormater.string(from: time) } } // MARK:- Actions private extension CSPhotoGalleryViewController { @IBAction func backBtnAction(_ sender: Any) { dismiss() } @IBAction func checkBtnAction(_ sender: Any) { delegate?.getAssets(assets: PhotoManager.sharedInstance.assets) dismiss() } } // MARK:- Extension fileprivate extension CSPhotoGalleryViewController { func setViewController() { setData() setView() } func setData() { PhotoManager.sharedInstance.CHECK_MAX_COUNT = CHECK_MAX_COUNT PhotoManager.sharedInstance.mediaType = mediaType PhotoManager.sharedInstance.initPhotoManager() } func setThumbnailSize() { let scale = UIScreen.main.scale let cellSize = (collectionView.collectionViewLayout as! UICollectionViewFlowLayout).itemSize let size = min(cellSize.width, cellSize.height) * scale thumbnailSize = CGSize(width: size, height: size) } func setView() { addAssetCollectionView() addObserver() setTitle() let podBundle = Bundle(for: CSPhotoGalleryViewController.self) let bundleURL = podBundle.url(forResource: "CSPhotoGallery", withExtension: "bundle") let bundle = bundleURL == nil ? podBundle : Bundle(url: bundleURL!) let originalCheckImage = UIImage(named: "check_select", in: bundle, compatibleWith: nil) let originalUnCheckImage = UIImage(named: "check_default", in: bundle, compatibleWith: nil) checkImage = CSPhotoDesignManager.instance.photoGalleryCheckImage ?? originalCheckImage unCheckImage = CSPhotoDesignManager.instance.photoGalleryUnCheckImage ?? originalUnCheckImage } func addAssetCollectionView() { assetCollectionViewController.view.frame = collectionView.frame assetCollectionViewController.viewHeight = collectionView.bounds.height assetCollectionViewController.view.frame.size.height = 0 addChildViewController(assetCollectionViewController) view.addSubview(assetCollectionViewController.view) assetCollectionViewController.didMove(toParentViewController: self) } func addObserver() { PhotoManager.sharedInstance.register(object: self) PhotoManager.sharedInstance.addObserver(self, forKeyPath: "selectedItemCount", options: .new, context: &CSObservationContext) PhotoManager.sharedInstance.addObserver(self, forKeyPath: "currentCollection", options: .new, context: &CSCollectionObservationContext) } func setCheckCountLabel(count: Int) { DispatchQueue.main.async { self.checkCount.text = "\(count)" } } func setTitle() { DispatchQueue.main.async { let title = PhotoManager.sharedInstance.currentCollection?.localizedTitle self.collectionName.text = title } } func checkPhotoLibraryPermission() { PHPhotoLibrary.requestAuthorization() { status in switch status { case .authorized: PhotoManager.sharedInstance.initPhotoManager() case .denied, .restricted: break case .notDetermined: self.checkPhotoLibraryPermission() } } } } extension CSPhotoGalleryViewController { func dismiss() { if let nvc = navigationController { let _ = nvc.popViewController(animated: true) } else { dismiss(animated: true, completion: nil) } } } // MARK:- UICollectionView DataSource extension CSPhotoGalleryViewController: UICollectionViewDataSource { public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return PhotoManager.sharedInstance.assetsCount } public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let asset = PhotoManager.sharedInstance.getCurrentCollectionAsset(at: indexPath) var cell: CSPhotoGalleryCollectionViewCell? switch asset.mediaType { case .image: cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CSPhotoGalleryCollectionViewCell", for: indexPath) as? CSPhotoGalleryCollectionViewCell case .video: cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CSPhotoGalleryVideoCollectionViewCell", for: indexPath) as? CSPhotoGalleryCollectionViewCell cell?.setTime(time: durationToText(time: asset.duration)) default: return UICollectionViewCell() } cell?.indexPath = indexPath cell?.representedAssetIdentifier = asset.localIdentifier cell?.checkImage = checkImage cell?.unCheckImage = unCheckImage cell?.setButtonImage() cell?.checkBtn.isHidden = CSPhotoDesignManager.instance.isOKButtonHidden cell?.setPlaceHolderImage(image: nil) PhotoManager.sharedInstance.setThumbnailImage(at: indexPath, thumbnailSize: thumbnailSize, isCliping: true) { image in if cell?.representedAssetIdentifier == asset.localIdentifier { cell?.setImage(image: image) } } return cell! } } // MARK:- UICollectionView Delegate extension CSPhotoGalleryViewController: UICollectionViewDelegate, UICollectionViewDelegateFlowLayout { public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { scrollRectToVisible(indexPath: indexPath) let asset = PhotoManager.sharedInstance.getCurrentCollectionAsset(at: indexPath) if asset.mediaType == .image { PhotoManager.sharedInstance.assetToImage(asset: asset, imageSize: CGSize(width: asset.pixelWidth, height: asset.pixelHeight), isCliping: false) { image in // Present photo viewer let item = collectionView.layoutAttributesForItem(at: indexPath) let vc = CSPhotoGalleryDetailViewController.instance var frame = item!.frame frame.origin.y = frame.origin.y - collectionView.contentOffset.y + collectionView.frame.origin.y self.transitionDelegate.initialRect = frame self.transitionDelegate.originalImage = image vc.delegate = self.delegate vc.currentIndexPath = indexPath vc.transitioningDelegate = self.transitionDelegate vc.modalPresentationStyle = .custom self.present(vc, animated: true, completion: nil) } } else if asset.mediaType == .video { PHCachingImageManager().requestAVAsset(forVideo: asset, options: nil, resultHandler: {(asset: AVAsset?, audioMix: AVAudioMix?, info: [AnyHashable: Any]?) in /* Did we get the URL to the video? */ if let asset = asset as? AVURLAsset{ let player = AVPlayer(url: asset.url) let playerViewController = CSVideoViewController() playerViewController.player = player self.present(playerViewController, animated: true) { if let validPlayer = playerViewController.player { validPlayer.play() } } } else { NSLog("This is not a URL asset. Cannot play") } }) } } public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { let size = (collectionView.bounds.width - horizontalCount - 1) / horizontalCount return CGSize(width: size, height: size) } } extension CSPhotoGalleryViewController: PHPhotoLibraryChangeObserver { public func photoLibraryDidChange(_ changeInstance: PHChange) { guard let currentAsset = PhotoManager.sharedInstance.getCurrentAsset(), let changes = changeInstance.changeDetails(for: currentAsset) else { return } DispatchQueue.main.sync { // Hang on to the new fetch result. PhotoManager.sharedInstance.reloadCurrentAsset() if changes.hasIncrementalChanges { // If we have incremental diffs, animate them in the collection view. guard let collectionView = self.collectionView else { fatalError() } collectionView.performBatchUpdates({ // For indexes to make sense, updates must be in this order: // delete, insert, reload, move if let removed = changes.removedIndexes, removed.count > 0 { collectionView.deleteItems(at: removed.map({ IndexPath(item: $0, section: 0) })) } if let inserted = changes.insertedIndexes, inserted.count > 0 { collectionView.insertItems(at: inserted.map({ IndexPath(item: $0, section: 0) })) } if let changed = changes.changedIndexes, changed.count > 0 { collectionView.reloadItems(at: changed.map({ IndexPath(item: $0, section: 0) })) } changes.enumerateMoves { fromIndex, toIndex in collectionView.moveItem(at: IndexPath(item: fromIndex, section: 0), to: IndexPath(item: toIndex, section: 0)) } }) } else { // Reload the collection view if incremental diffs are not available. collectionView!.reloadData() } } } }
mit
08f07ada86cb92c372cf05e6ceec890e
41.321149
168
0.621753
6.005558
false
false
false
false
Anvics/Amber
Example/Pods/Bond/Sources/Bond/DataSource.swift
2
3445
// // The MIT License (MIT) // // Copyright (c) 2016 Srdan Rasic (@srdanrasic) // // 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 Foundation import ReactiveKit public protocol DataSourceProtocol { var numberOfSections: Int { get } func numberOfItems(inSection section: Int) -> Int } public enum DataSourceEventKind { case reload case insertItems([IndexPath]) case deleteItems([IndexPath]) case reloadItems([IndexPath]) case moveItem(IndexPath, IndexPath) case insertSections(IndexSet) case deleteSections(IndexSet) case reloadSections(IndexSet) case moveSection(Int, Int) case beginUpdates case endUpdates } public protocol DataSourceBatchKind {} public enum BatchKindDiff: DataSourceBatchKind {} public enum BatchKindPatch: DataSourceBatchKind {} public protocol DataSourceEventProtocol { associatedtype DataSource: DataSourceProtocol associatedtype BatchKind: DataSourceBatchKind var kind: DataSourceEventKind { get } var dataSource: DataSource { get } } extension DataSourceEventProtocol { public var _unbox: DataSourceEvent<DataSource, BatchKind> { if let event = self as? DataSourceEvent<DataSource, BatchKind> { return event } else { return DataSourceEvent(kind: self.kind, dataSource: self.dataSource) } } } public struct DataSourceEvent<DataSource: DataSourceProtocol, _BatchKind: DataSourceBatchKind>: DataSourceEventProtocol { public typealias BatchKind = _BatchKind public let kind: DataSourceEventKind public let dataSource: DataSource } extension Array: DataSourceProtocol { public var numberOfSections: Int { return 1 } public func numberOfItems(inSection section: Int) -> Int { return count } } extension Array: DataSourceEventProtocol, ObservableArrayEventProtocol { public typealias BatchKind = BatchKindDiff public var kind: DataSourceEventKind { return .reload } public var dataSource: Array<Element> { return self } public var change: ObservableArrayChange { return .reset } public var source: ObservableArray<Iterator.Element> { return ObservableArray(self) } } extension SignalProtocol where Element: DataSourceProtocol, Error == NoError { public func mapToDataSourceEvent() -> SafeSignal<DataSourceEvent<Element, BatchKindDiff>> { return map { collection in DataSourceEvent(kind: .reload, dataSource: collection) } } }
mit
ae4f9dfebcace04675ba42ffc149ff63
27.94958
121
0.755878
4.818182
false
false
false
false
taxfix/native-navigation
lib/ios/native-navigation/ReactNavigationCoordinator.swift
1
5703
// // ReactNavigationCoordinator.swift // NativeNavigation // // Created by Spike Brehm on 5/5/16. // Copyright © 2016 Airbnb. All rights reserved. // import React import UIKit @objc public protocol ReactNavigationCoordinatorDelegate { func rootViewController(forCoordinator coordinator: ReactNavigationCoordinator) -> UIViewController? @objc optional func flowCoordinatorForId(_ name: String) -> ReactFlowCoordinator? @objc optional func registerReactDeepLinkUrl(_ deepLinkUrl: String) } @objc public protocol ReactFlowCoordinator: class { @objc var reactFlowId: String? { get set } @objc func start(_ props: [String:AnyObject]?) @objc func finish(_ resultCode: ReactFlowResultCode, payload: [String:AnyObject]?) } private var _uuid: Int = 0 private func getUuid() -> String { _uuid = _uuid + 1 return "\(_uuid)" } private struct ViewControllerHolder { weak var viewController: InternalReactViewControllerProtocol? } open class ReactNavigationCoordinator: NSObject { // MARK: Lifecycle override init() { viewControllers = [:] promises = [:] flows = [:] deepLinkMapping = [:] } // MARK: Public open static let sharedInstance = ReactNavigationCoordinator() open var delegate: ReactNavigationCoordinatorDelegate? open var bridge: RCTBridge? open var navigation: ReactNavigationImplementation = DefaultReactNavigationImplementation() open func topViewController() -> UIViewController? { guard let a = delegate?.rootViewController(forCoordinator: self) else { return nil } return a.topMostViewController() } open func topNavigationController() -> UINavigationController? { return topViewController()?.navigationController } open func topTabBarController() -> UITabBarController? { return topViewController()?.tabBarController } open func startFlow(fromName name: String, withProps props: [String: AnyObject], resolve: @escaping RCTPromiseResolveBlock, reject: @escaping RCTPromiseRejectBlock) { guard let flow = delegate?.flowCoordinatorForId?(name) else { return } register(flow, resolve: resolve, reject: reject) flow.start(props) } open func register(_ flow: ReactFlowCoordinator, resolve: @escaping RCTPromiseResolveBlock, reject: @escaping RCTPromiseRejectBlock) { let newId = getUuid() flow.reactFlowId = newId promises[newId] = ReactPromise(resolve: resolve, reject: reject) // This is used to prevent ReactFlowCoordinator from being garbage collected flows[newId] = flow } func viewControllerForId(_ id: String) -> InternalReactViewControllerProtocol? { return viewControllers[id]?.viewController } open func moduleNameForDeepLinkUrl(_ deepLinkUrl: String) -> String? { return deepLinkMapping[deepLinkUrl] } open func registerDeepLinkUrl(_ sceneName: String, deepLinkUrl: String) { deepLinkMapping[deepLinkUrl] = sceneName delegate?.registerReactDeepLinkUrl?(deepLinkUrl) } // MARK: Internal func registerFlow(_ viewController: ReactViewController, resolve: @escaping RCTPromiseResolveBlock, reject: @escaping RCTPromiseRejectBlock) { let newId = getUuid() viewController.reactFlowId = newId promises[newId] = ReactPromise(resolve: resolve, reject: reject) } func registerViewController(_ viewController: InternalReactViewControllerProtocol) { let nativeNavigationInstanceId = viewController.nativeNavigationInstanceId viewControllers[nativeNavigationInstanceId] = ViewControllerHolder(viewController: viewController) } func unregisterViewController(_ nativeNavigationInstanceId: String) { viewControllers[nativeNavigationInstanceId] = nil } var sceneInitialPropertiesMap: [String: [String: AnyObject]] = [:] func registerScreenProperties(_ sceneName: String, properties: [String: AnyObject]) { sceneInitialPropertiesMap[sceneName] = properties } func getScreenProperties(_ sceneName: String) -> [String: AnyObject]? { return sceneInitialPropertiesMap[sceneName] } func dismissViewController(_ nativeNavigationInstanceId: String, payload: [String: AnyObject]) { guard let viewController = viewControllers[nativeNavigationInstanceId]?.viewController else { print("Could not find viewController \(nativeNavigationInstanceId)") return } // Dismiss the view controller. viewController.dismiss(payload) // And remove it from the dictionary. viewControllers[nativeNavigationInstanceId] = nil } func onFlowFinish(_ flow: ReactFlowCoordinator, resultCode: ReactFlowResultCode, payload: [String:AnyObject]?) { guard let id = flow.reactFlowId else { return } guard let promise = promises[id] else { return } // promises can only be resolved once promises[id] = nil // Don't need to prevent flow from being garbage collected flows[id] = nil var result: [String:AnyObject] = [ "code": resultCode.rawValue as AnyObject, ] if let payload = payload { result["payload"] = payload as AnyObject? } promise.resolve(result) if let vc = flow as? ReactViewController { unregisterViewController(vc.nativeNavigationInstanceId) } } // MARK: Private fileprivate var promises: [String: ReactPromise] fileprivate var viewControllers: [String: ViewControllerHolder] fileprivate var flows: [String: ReactFlowCoordinator] fileprivate var deepLinkMapping: [String: String] } class ReactPromise { let resolve: RCTPromiseResolveBlock let reject: RCTPromiseRejectBlock init(resolve: @escaping RCTPromiseResolveBlock, reject: @escaping RCTPromiseRejectBlock) { self.resolve = resolve self.reject = reject } }
mit
fc402af2a7129cbc226597af7001eea5
30.502762
168
0.740091
5.037102
false
false
false
false
vector-im/vector-ios
Riot/Modules/Threads/Beta/ThreadsBetaViewController.swift
1
5426
// // Copyright 2022 New Vector Ltd // // 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 UIKit class ThreadsBetaViewController: UIViewController { // MARK: Constants private enum Constants { static let learnMoreLink = "https://element.io/help#threads" } // MARK: Outlets @IBOutlet private weak var titleLabel: UILabel! @IBOutlet private weak var separatorLineView: UIView! @IBOutlet private weak var informationTextView: UITextView! { didSet { informationTextView.textContainer.lineFragmentPadding = 0 } } @IBOutlet private weak var enableButton: UIButton! @IBOutlet private weak var cancelButton: UIButton! // MARK: Private private var theme: Theme! // MARK: Public @objc var didTapEnableButton: (() -> Void)? @objc var didTapCancelButton: (() -> Void)? // MARK: - Life cycle override func viewDidLoad() { super.viewDidLoad() self.setupViews() self.registerThemeServiceDidChangeThemeNotification() self.update(theme: self.theme) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) // Hide back button self.navigationItem.setHidesBackButton(true, animated: animated) } override var preferredStatusBarStyle: UIStatusBarStyle { return self.theme.statusBarStyle } // MARK: - Setup @objc class func instantiate() -> ThreadsBetaViewController { let viewController = StoryboardScene.ThreadsBetaViewController.initialScene.instantiate() viewController.theme = ThemeService.shared().theme return viewController } // MARK: - Private private func registerThemeServiceDidChangeThemeNotification() { NotificationCenter.default.addObserver(self, selector: #selector(themeDidChange), name: .themeServiceDidChangeTheme, object: nil) } @objc private func themeDidChange() { self.update(theme: ThemeService.shared().theme) } private func setupViews() { self.vc_removeBackTitle() self.enableButton.setTitle(VectorL10n.threadsBetaEnable, for: .normal) self.cancelButton.setTitle(VectorL10n.threadsBetaCancel, for: .normal) self.titleLabel.text = VectorL10n.threadsBetaTitle guard let font = self.informationTextView.font else { return } let attributedString = NSMutableAttributedString(string: VectorL10n.threadsBetaInformation, attributes: [.font: font]) let link = NSAttributedString(string: VectorL10n.threadsBetaInformationLink, attributes: [.link: Constants.learnMoreLink, .font: font]) attributedString.append(link) self.informationTextView.attributedText = attributedString } // MARK: - Actions @IBAction private func enableButtonAction(_ sender: UIButton) { self.didTapEnableButton?() } @IBAction private func cancelButtonAction(_ sender: UIButton) { self.didTapCancelButton?() } } // MARK: - Themable extension ThreadsBetaViewController: Themable { func update(theme: Theme) { self.theme = theme self.view.backgroundColor = theme.colors.background if let navigationBar = self.navigationController?.navigationBar { theme.applyStyle(onNavigationBar: navigationBar) } self.titleLabel.textColor = theme.textPrimaryColor self.separatorLineView.backgroundColor = theme.colors.system self.informationTextView.textColor = theme.textPrimaryColor self.enableButton.vc_setBackgroundColor(theme.tintColor, for: .normal) self.enableButton.setTitleColor(theme.baseTextPrimaryColor, for: .normal) self.cancelButton.vc_setBackgroundColor(.clear, for: .normal) self.cancelButton.setTitleColor(theme.tintColor, for: .normal) } } // MARK: - SlidingModalPresentable extension ThreadsBetaViewController: SlidingModalPresentable { func allowsDismissOnBackgroundTap() -> Bool { return false } func layoutHeightFittingWidth(_ width: CGFloat) -> CGFloat { guard let view = ThreadsNoticeViewController.instantiate().view else { return 0 } view.widthAnchor.constraint(equalToConstant: width).isActive = true view.setNeedsLayout() view.layoutIfNeeded() let fittingSize = CGSize(width: width, height: UIView.layoutFittingCompressedSize.height) return view.systemLayoutSizeFitting(fittingSize).height + UIWindow().safeAreaInsets.top + UIWindow().safeAreaInsets.bottom } }
apache-2.0
4d623f028728aebd76cce1c6174b60cc
30.730994
99
0.660339
5.28335
false
false
false
false
aaronschubert0/AsyncDisplayKit
examples_extra/Shop/Shop/Scenes/Products/ProductsLayout.swift
11
1249
// // ProductsLayout.swift // Shop // // Created by Dimitri on 16/11/2016. // Copyright © 2016 Dimitri. All rights reserved. // import UIKit class ProductsLayout: UICollectionViewFlowLayout { // MARK: - Variables let itemHeight: CGFloat = 220 let numberOfColumns: CGFloat = 2 // MARK: - Object life cycle override init() { super.init() self.setupLayout() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.setupLayout() } // MARK: - Layout private func setupLayout() { self.minimumInteritemSpacing = 0 self.minimumLineSpacing = 0 self.scrollDirection = .vertical } func itemWidth() -> CGFloat { return (collectionView!.frame.width / numberOfColumns) } override var itemSize: CGSize { set { self.itemSize = CGSize(width: itemWidth(), height: itemHeight) } get { return CGSize(width: itemWidth(), height: itemHeight) } } override func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint) -> CGPoint { return self.collectionView!.contentOffset } }
bsd-3-clause
4ae0e2e5df13f63e19d42404d4268d44
21.690909
107
0.601763
4.972112
false
false
false
false
nixzhu/Baby
Sources/Baby/Arguments.swift
1
3577
/* * @nixzhu ([email protected]) */ final public class Arguments { public enum Option: CustomStringConvertible { case Short(key: String) case Long(key: String) case Mixed(shortKey: String, longKey: String) public var description: String { switch self { case .Short(let key): return "-" + key case .Long(let key): return "--" + key case .Mixed(let shortKey, let longKey): return "-" + shortKey + ", " + "--" + longKey } } } enum Value { case None case Exist(String) var value: String? { switch self { case .None: return nil case .Exist(let string): return string } } } let keyValues: [String: Value] public init(_ arguments: [String]) { guard arguments.count > 1 else { self.keyValues = [:] return } var keyValues = [String: Value]() var i = 1 while true { let _a = arguments[arguments_safe: i] let _b = arguments[arguments_safe: i + 1] guard let a = _a else { break } if a.arguments_isKey { if let b = _b, !b.arguments_isKey { keyValues[a] = Value.Exist(b) } else { keyValues[a] = Value.None } } else { print("Invalid argument: `\(a)`!") break } if let b = _b { if b.arguments_isKey { i += 1 } else { i += 2 } } else { break } } self.keyValues = keyValues } public func containsOption(_ option: Option) -> Bool { switch option { case .Short(let key): return keyValues["-" + key] != nil case .Long(let key): return keyValues["--" + key] != nil case .Mixed(let shortKey, let longKey): return (keyValues["-" + shortKey] != nil) || (keyValues["--" + longKey] != nil) } } public func containsOptions(_ options: [Option]) -> Bool { return options.reduce(true, { $0 && containsOption($1) }) } public func valueOfOption(_ option: Option) -> String? { switch option { case .Short(let key): return keyValues["-" + key]?.value case .Long(let key): return keyValues["--" + key]?.value case .Mixed(let shortKey, let longKey): let shortKeyValue = keyValues["-" + shortKey]?.value let longKeyValue = keyValues["--" + longKey]?.value if let shortKeyValue = shortKeyValue, let longKeyValue = longKeyValue { guard shortKeyValue == longKeyValue else { fatalError("Duplicate value for option: `\(option)`!") } } return shortKeyValue ?? longKeyValue } } } private extension String { var arguments_isLongKey: Bool { return hasPrefix("--") } var arguments_isShortKey: Bool { return !arguments_isLongKey && hasPrefix("-") } var arguments_isKey: Bool { return arguments_isLongKey || arguments_isShortKey } } private extension Array { subscript (arguments_safe index: Int) -> Element? { return indices ~= index ? self[index] : nil } }
mit
6d7295d001144ecba917dfb1a938bc6c
26.945313
91
0.48057
4.788487
false
false
false
false
material-motion/motion-transitioning-objc
tests/unit/Transitions/FallbackTransition.swift
2
1163
/* Copyright 2017-present The Material Motion Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import MotionTransitioning final class FallbackTransition: NSObject, Transition, TransitionWithFallback { let fallbackTo: Transition? init(to: Transition) { self.fallbackTo = to } override init() { self.fallbackTo = nil } func fallbackTransition(with context: TransitionContext) -> Transition { if let fallbackTo = fallbackTo { return fallbackTo } return self } var startWasInvoked = false func start(with context: TransitionContext) { startWasInvoked = true context.transitionDidEnd() } }
apache-2.0
b594ee56ce6da82593cd312521b6e6b6
25.431818
78
0.745486
4.633466
false
false
false
false
yhyuan/WeatherMap
WeatherAroundUs/WeatherAroundUs/WeatherInformation.swift
5
14028
// // WeatherInformation.swift // WeatherAroundUs // // Created by Kedan Li on 15/4/5. // Copyright (c) 2015年 Kedan Li. All rights reserved. // import UIKit import Alamofire @objc protocol WeatherInformationDelegate: class { optional func gotWeatherInformation() } var WeatherInfo: WeatherInformation = WeatherInformation() class WeatherInformation: NSObject, InternetConnectionDelegate{ var currentDate = "" // 9 days weather forcast for city var citiesForcast = [String: AnyObject]() // all city in database with one day weather info var citiesAroundDict = [String: AnyObject]() // tree that store all the weather data var currentSearchTrees = [String: QTree]() var currentSearchTreeDict = [String: [String: WeatherDataQTree]]() var searchTrees = [String: QTree]() var searchTreeDict = [String: [String: WeatherDataQTree]]() var mainTree = QTree() var lv2 = QTree() //current city id var currentCityID = "" var forcastMode = false var blockSize = 5 let maxRequestNum = 4 var weatherDelegate : WeatherInformationDelegate? override init() { super.init() if let forcast: AnyObject = NSUserDefaults.standardUserDefaults().objectForKey("citiesForcast"){ citiesForcast = forcast as! [String : AnyObject] } //Load Main Tree if var path = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as? String{ path = path.stringByAppendingString("/MainTree.plist") var arr = NSArray(contentsOfFile: path) as! [NSDictionary] for tree in arr{ mainTree.insertObject(WeatherDataQTree(position: CLLocationCoordinate2DMake((tree.objectForKey("latitude")! as! NSNumber).doubleValue, (tree.objectForKey("longitude")! as! NSNumber).doubleValue), cityID: tree.objectForKey("cityID") as! String)) } } //loadAllTrees() } func loadAllTrees(){ var tree = mainTree.neighboursForLocation(CLLocationCoordinate2DMake(1, 1), limitCount: mainTree.count) as! [WeatherDataQTree] for id in tree{ loadTree(id.cityID) } } func loadTree(cityID: String){ var treeArr = [NSDictionary]() if var path = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as? String{ path = path.stringByAppendingString("/" + cityID + ".plist") var arr = NSArray(contentsOfFile: path) treeArr = arr as! [NSDictionary] } var dict = [String: WeatherDataQTree]() var tree = QTree() for node in treeArr{ //if !cityExist(node.objectForKey("cityID") as! String){ var data = WeatherDataQTree(position: CLLocationCoordinate2DMake(node.objectForKey("latitude")!.doubleValue, node.objectForKey("longitude")!.doubleValue), cityID: node.objectForKey("cityID") as! String) dict.updateValue(data, forKey: data.cityID) tree.insertObject(data) //} } searchTreeDict.updateValue(dict, forKey: cityID) searchTrees.updateValue(tree, forKey: cityID) } func cityExist(cityID: String)->Bool{ for tree in searchTreeDict.keys.array { if searchTreeDict[tree]![cityID] != nil{ return true } } return false } func removeTree(cityID: String){ currentSearchTreeDict.removeValueForKey(cityID) currentSearchTrees.removeValueForKey(cityID) } // get the closest icon func getTheNearestIcon(position: CLLocationCoordinate2D)->WeatherDataQTree{ let nearestTree = mainTree.neighboursForLocation(position, limitCount: 1)[0] as! WeatherDataQTree if currentSearchTrees[nearestTree.cityID] == nil{ loadTree(nearestTree.cityID) } let data = currentSearchTrees[nearestTree.cityID]?.neighboursForLocation(position, limitCount: 1)[0] as! WeatherDataQTree return data } // get the five closest icons func getTheTwoNearestIcons(position: CLLocationCoordinate2D)->NSArray?{ let nearestTree = mainTree.neighboursForLocation(position, limitCount: 1)[0] as! WeatherDataQTree let data = currentSearchTrees[nearestTree.cityID]?.neighboursForLocation(position, limitCount: 2) return data } // get the five closest icons func getTheFiveNearestIcons(position: CLLocationCoordinate2D)->NSArray?{ let nearestTree = mainTree.neighboursForLocation(position, limitCount: 1)[0] as! WeatherDataQTree let data = currentSearchTrees[nearestTree.cityID]?.neighboursForLocation(position, limitCount: 5) return data } // get the closest icons func getNearestIcons(position: CLLocationCoordinate2D)->NSArray{ let nearestTrees = mainTree.neighboursForLocation(position, limitCount: 3) if currentSearchTrees[(nearestTrees[0] as! WeatherDataQTree).cityID] == nil{ loadTree((nearestTrees[0] as! WeatherDataQTree).cityID) } if currentSearchTrees[(nearestTrees[1] as! WeatherDataQTree).cityID] == nil{ loadTree((nearestTrees[1] as! WeatherDataQTree).cityID) } var set = currentSearchTrees[(nearestTrees[0] as! WeatherDataQTree).cityID]?.neighboursForLocation(position, limitCount: 15) if set == nil{ return NSArray() } var set2 = (currentSearchTrees[(nearestTrees[1] as! WeatherDataQTree).cityID]?.neighboursForLocation(position, limitCount: 5)) if set2 == nil{ return set! } return set! + set2! } func getObjectsInRegion(region: MKCoordinateRegion)->NSArray{ var arr = [AnyObject]() for tree in currentSearchTrees.keys.array{ arr = arr + currentSearchTrees[tree]!.getObjectsInRegion(region, minNonClusteredSpan: min(region.span.latitudeDelta, region.span.longitudeDelta) / 5)! } return arr } var ongoingRequest = 0 var latestSearchReq:[QTreeInsertable]! func searchWeatherIfLimitedRequest(cities: [QTreeInsertable]){ if ongoingRequest < maxRequestNum{ searchWeather(cities) }else{ latestSearchReq = cities } } func searchWeather(cities: [QTreeInsertable]){ var index = 7 while index < cities.count { var arr = [QTreeInsertable]() for data in cities[(index - 7)..<index]{ arr.append(data) } var connection = InternetConnection() connection.delegate = self connection.getLocalWeather(arr) index = index + 7 ongoingRequest++ } var arr = [QTreeInsertable]() for data in cities[(index - 7)..<cities.count]{ arr.append(data) } if arr.count > 0{ var connection = InternetConnection() connection.delegate = self connection.getLocalWeather(arr) ongoingRequest++ } } // got local city weather from member func gotLocalCityWeather(cities: [AnyObject]) { ongoingRequest-- var hasNewInfo = false for var index = 0; index < cities.count; index++ { let id: Int = (cities[index] as! [String : AnyObject]) ["id"] as! Int // first time weather data if self.citiesAroundDict["\(id)"] == nil { self.citiesAroundDict.updateValue(cities[index], forKey: "\(id)") var connection = InternetConnection() connection.delegate = self connection.getWeatherForcast("\(id)") hasNewInfo = true } } if !forcastMode && hasNewInfo { self.weatherDelegate?.gotWeatherInformation!() } if ongoingRequest < maxRequestNum && latestSearchReq != nil{ searchWeatherIfLimitedRequest(latestSearchReq) latestSearchReq = nil } } func gotWeatherForcastData(cityID: String, forcast: [AnyObject]) { let userDefault = NSUserDefaults.standardUserDefaults() // get currentDate var currDate = NSDate() var dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "dd.MM.YY" let dateStr = dateFormatter.stringFromDate(currDate) //remove object if not the same day if currentDate != dateStr { currentDate = dateStr userDefault.setValue(dateStr, forKey: "currentDate") userDefault.setObject([String: AnyObject](), forKey: "citiesForcast") userDefault.synchronize() citiesForcast.removeAll(keepCapacity: false) } citiesForcast.updateValue(forcast, forKey: cityID) //display new icon if forcastMode{ self.weatherDelegate?.gotWeatherInformation!() } } /* func splitIntoSubtree(){ //let db = CitySQL() var entireTree = QTree() //db.loadDataToTree(entireTree) for var x = -180; x < 180; x += blockSize { for var y = -90; y < 90; y += blockSize{ let centerCoordinate = CLLocationCoordinate2DMake(Double(y + blockSize / 2), Double(x + blockSize / 2)) let location1 = CLLocation(latitude: Double(y), longitude: Double(x)) let location2 = CLLocation(latitude: Double(y + blockSize), longitude: Double(x)) let location3 = CLLocation(latitude: Double(y + blockSize), longitude: Double(x + blockSize)) let location4 = CLLocation(latitude: Double(y), longitude: Double(x + blockSize)) let distance = location1.distanceFromLocation(CLLocation(latitude: Double(y + blockSize), longitude: Double(x + blockSize))) let region = MKCoordinateRegionMakeWithDistance(centerCoordinate, max(location2.distanceFromLocation(location1), location4.distanceFromLocation(location3)) , max(location2.distanceFromLocation(location3), location4.distanceFromLocation(location1))) // get all nodes in an area let cities = entireTree.getObjectsInRegion(region, minNonClusteredSpan: 0.000001) if cities.count > 0 {//&& cities.count < 5000{ var tree = SecondLevelQTree(position: centerCoordinate, cityID: (cities[0] as! WeatherDataQTree).cityID) for city in cities{ tree.insertObject(city as! WeatherDataQTree) } println(cities.count) lv2.insertObject(tree) } /* else if cities.count >= 5000 { // split into more tree for var tempX = x; tempX < x + blockSize; tempX += 3 { for var tempY = y; tempY < y + blockSize; tempY += 3 { let centerCoordinateS = CLLocationCoordinate2DMake(Double(tempY + 3 / 2), Double(tempX + 3 / 2)) let location1S = CLLocation(latitude: Double(tempY), longitude: Double(tempX)) let distanceS = location1S.distanceFromLocation(CLLocation(latitude: Double(tempY + 3), longitude: Double(tempX + 3))) let regionS = MKCoordinateRegionMakeWithDistance(centerCoordinateS, distanceS, distanceS) // get all nodes in an area let citiesS = entireTree.getObjectsInRegion(regionS, minNonClusteredSpan: 0.000001) if citiesS.count > 0 { var tree = SecondLevelQTree(position: centerCoordinateS, cityID: (citiesS[0] as! WeatherDataQTree).cityID) for city in citiesS{ tree.insertObject(city as! WeatherDataQTree) } println(citiesS.count) lv2.insertObject(tree) } } } }*/ } } QtreeSerialization.saveSecondLevelTree(lv2) QtreeSerialization.saveMainTree(lv2) } */ } class ThirdLevelQTree: QTree, QTreeInsertable{ var coordinate: CLLocationCoordinate2D var cityID: String init(position: CLLocationCoordinate2D, cityID: String) { coordinate = position self.cityID = cityID super.init() } } class SecondLevelQTree: QTree, QTreeInsertable{ var coordinate: CLLocationCoordinate2D var cityID: String init(position: CLLocationCoordinate2D, cityID: String) { coordinate = position self.cityID = cityID super.init() } } /* class FourthLevelQTree: QTree, QTreeInsertable{ var coordinate: CLLocationCoordinate2D var centerCity: String! init(position: CLLocationCoordinate2D) { coordinate = position super.init() } }*/ /* build Tree plist files */
apache-2.0
29eebe9cfcd9982338bdb93013b18f9b
33.634568
264
0.575574
5.409179
false
false
false
false
jpaas/MaterialKit
Source/MKImageView.swift
1
3455
// // MKImageView.swift // MaterialKit // // Created by Le Van Nghia on 11/29/14. // Copyright (c) 2014 Le Van Nghia. All rights reserved. // import UIKit @IBDesignable public class MKImageView: UIImageView { @IBInspectable public var maskEnabled: Bool = true { didSet { mkLayer.enableMask(maskEnabled) } } @IBInspectable public var rippleLocation: MKRippleLocation = .TapLocation { didSet { mkLayer.rippleLocation = rippleLocation } } @IBInspectable public var rippleAniDuration: Float = 0.75 @IBInspectable public var backgroundAniDuration: Float = 1.0 @IBInspectable public var rippleAniTimingFunction: MKTimingFunction = .Linear @IBInspectable public var backgroundAniTimingFunction: MKTimingFunction = .Linear @IBInspectable public var backgroundAniEnabled: Bool = true { didSet { if !backgroundAniEnabled { mkLayer.enableOnlyCircleLayer() } } } @IBInspectable public var ripplePercent: Float = 0.9 { didSet { mkLayer.ripplePercent = ripplePercent } } @IBInspectable public var cornerRadius: CGFloat = 2.5 { didSet { layer.cornerRadius = cornerRadius mkLayer.setMaskLayerCornerRadius(cornerRadius) } } // color @IBInspectable public var rippleLayerColor: UIColor = UIColor(white: 0.45, alpha: 0.5) { didSet { mkLayer.setCircleLayerColor(rippleLayerColor) } } @IBInspectable public var backgroundLayerColor: UIColor = UIColor(white: 0.75, alpha: 0.25) { didSet { mkLayer.setBackgroundLayerColor(backgroundLayerColor) } } override public var bounds: CGRect { didSet { mkLayer.superLayerDidResize() } } private lazy var mkLayer: MKLayer = MKLayer(superLayer: self.layer) required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } override public init(frame: CGRect) { super.init(frame: frame) setup() } override public init(image: UIImage!) { super.init(image: image) setup() } override public init(image: UIImage!, highlightedImage: UIImage?) { super.init(image: image, highlightedImage: highlightedImage) setup() } private func setup() { mkLayer.setCircleLayerColor(rippleLayerColor) mkLayer.setBackgroundLayerColor(backgroundLayerColor) mkLayer.setMaskLayerCornerRadius(cornerRadius) } public func animateRipple(location: CGPoint? = nil) { if let point = location { mkLayer.didChangeTapLocation(point) } else if rippleLocation == .TapLocation { rippleLocation = .Center } mkLayer.animateScaleForCircleLayer(0.65, toScale: 1.0, timingFunction: rippleAniTimingFunction, duration: CFTimeInterval(self.rippleAniDuration)) mkLayer.animateAlphaForBackgroundLayer(backgroundAniTimingFunction, duration: CFTimeInterval(self.backgroundAniDuration)) } override public func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { super.touchesBegan(touches, withEvent: event) if let firstTouch = touches.first as UITouch? { let location = firstTouch.locationInView(self) animateRipple(location) } } }
mit
fd1980d7202d1ac36a6fd007ddcc5aef
30.697248
153
0.650651
5.088365
false
false
false
false
DanielAsher/Few.swift
Few-iOS/TableView.swift
4
10897
// // TableView.swift // Few // // Created by Coen Wessels on 13-03-15. // Copyright (c) 2015 Josh Abernathy. All rights reserved. // import UIKit private let defaultRowHeight: CGFloat = 42 private class FewTableHeaderFooter: UIView { var didChangeHeight: (FewTableHeaderFooter -> Void)? private lazy var parentElement: RealizedElement = {[unowned self] in return RealizedElement(element: Element(), view: self.contentView, parent: nil) }() private(set) lazy var contentView: UIView = {[unowned self] in let v = UIView(frame: self.bounds) configureViewToAutoresize(v) self.addSubview(v) return v }() private var realizedElement: RealizedElement? func updateWithElement(element: Element) { if let oldRealizedElement = realizedElement { if element.canDiff(oldRealizedElement.element) { element.applyDiff(oldRealizedElement.element, realizedSelf: oldRealizedElement) } else { oldRealizedElement.remove() realizedElement = element.realize(parentElement) } } else { realizedElement = element.realize(parentElement) } realizedElement?.layoutFromRoot() let layout = element.assembleLayoutNode().layout(maxWidth: bounds.width) let oldHeight = bounds.height layout.apply(contentView) if contentView.frame.height != oldHeight { bounds.size.height = contentView.frame.height didChangeHeight?(self) } } } private class FewSectionHeaderFooter: UITableViewHeaderFooterView { private lazy var parentElement: RealizedElement = {[unowned self] in return RealizedElement(element: Element(), view: self.contentView, parent: nil) }() private var realizedElement: RealizedElement? func updateWithElement(element: Element) { if let oldRealizedElement = realizedElement { if element.canDiff(oldRealizedElement.element) { element.applyDiff(oldRealizedElement.element, realizedSelf: oldRealizedElement) } else { oldRealizedElement.remove() realizedElement = element.realize(parentElement) } } else { realizedElement = element.realize(parentElement) } realizedElement?.layoutFromRoot() } } private class FewListCell: UITableViewCell { private lazy var parentElement: RealizedElement = {[unowned self] in return RealizedElement(element: Element(), view: self.contentView, parent: nil) }() private var realizedElement: RealizedElement? func updateWithElement(element: Element) { if let oldRealizedElement = realizedElement { if element.canDiff(oldRealizedElement.element) { element.applyDiff(oldRealizedElement.element, realizedSelf: oldRealizedElement) } else { oldRealizedElement.remove() realizedElement = element.realize(parentElement) } } else { realizedElement = element.realize(parentElement) } realizedElement?.layoutFromRoot() } } private let cellKey = "ListCell" private let headerKey = "ListHeader" private let footerKey = "ListFooter" private class TableViewHandler: NSObject, UITableViewDelegate, UITableViewDataSource { let tableView: UITableView var cachedHeights: [String: CGFloat] = [:] // Call `update` rather than setting these directly var elements: [[Element]] var headers: [Element?] var footers: [Element?] let headerView = FewTableHeaderFooter() let footerView = FewTableHeaderFooter() var selectionChanged: (NSIndexPath -> ())? init(tableView: UITableView, elements: [[Element]], headers: [Element?], footers: [Element?]) { self.tableView = tableView self.elements = elements self.headers = headers self.footers = footers super.init() headerView.didChangeHeight = {[weak tableView] view in if let tableView = tableView where tableView.tableHeaderView == view { // set header again to force table view to update contentSize & row offset tableView.tableHeaderView = view // begin/end updates because otherwise table view // randomly miscomputes its row offset after header height change UIView.performWithoutAnimation { tableView.beginUpdates() tableView.endUpdates() } } } footerView.didChangeHeight = {[weak tableView] view in // set footer again to force table view to update contentSize if let tableView = tableView where tableView.tableFooterView == view { tableView.tableFooterView = view } } tableView.registerClass(FewSectionHeaderFooter.self, forHeaderFooterViewReuseIdentifier: headerKey) tableView.registerClass(FewSectionHeaderFooter.self, forHeaderFooterViewReuseIdentifier: footerKey) tableView.registerClass(FewListCell.self, forCellReuseIdentifier: cellKey) tableView.delegate = self tableView.dataSource = self } func update(elements: [[Element]], sectionHeaders: [Element?], sectionFooters: [Element?]) { self.elements = elements self.headers = sectionHeaders self.footers = sectionFooters updateCachedHeights() tableView.reloadData() } // MARK: UITableViewDelegate @objc func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let element = elements[indexPath.section][indexPath.row] let cell = tableView.dequeueReusableCellWithIdentifier(cellKey, forIndexPath: indexPath) as! FewListCell cell.updateWithElement(element) return cell } @objc func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { let element = elements[indexPath.section][indexPath.row] return cachedHeights[memoryAddress(element)] ?? defaultRowHeight } @objc func numberOfSectionsInTableView(tableView: UITableView) -> Int { return elements.count } @objc func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return elements[section].count } @objc func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { selectionChanged?(indexPath) } @objc func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { if section < headers.count { if let header = headers[section] { return cachedHeights[memoryAddress(header)] ?? 0 } } return 0 } @objc func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { if section < headers.count { if let header = headers[section] { let view = tableView.dequeueReusableHeaderFooterViewWithIdentifier(headerKey) as! FewSectionHeaderFooter view.updateWithElement(header) return view } } return nil } @objc func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { if section < footers.count { if let footer = footers[section] { return cachedHeights[memoryAddress(footer)] ?? 0 } } return 0 } @objc func tableView(tableView: UITableView, viewForFooterInSection section: Int) -> UIView? { if section < footers.count { if let footer = footers[section] { let view = tableView.dequeueReusableHeaderFooterViewWithIdentifier(footerKey) as! FewSectionHeaderFooter view.updateWithElement(footer) return view } } return nil } func updateCachedHeights() { var allElements = [Element?]() for section in elements { allElements += section.map { row in Optional(row) } } allElements += headers allElements += footers cachedHeights.removeAll(keepCapacity: true) for element in allElements { if let element = element { let node = element.assembleLayoutNode() let layout = node.layout(maxWidth: tableView.frame.size.width) cachedHeights[memoryAddress(element)] = layout.frame.size.height } } } } private class FewTableView: UITableView { var handler: TableViewHandler? } public class TableView: Element { private let elements: [[Element]] private let selectionChanged: (NSIndexPath -> ())? private let selectedRow: NSIndexPath? private let sectionHeaders: [Element?] private let sectionFooters: [Element?] private let header: Element? private let footer: Element? public init(_ elements: [[Element]], sectionHeaders: [Element?] = [], sectionFooters: [Element?] = [], header: Element? = nil, footer: Element? = nil, selectedRow: NSIndexPath? = nil, selectionChanged: (NSIndexPath -> ())? = nil) { self.elements = elements self.selectionChanged = selectionChanged self.selectedRow = selectedRow self.sectionHeaders = sectionHeaders self.sectionFooters = sectionFooters self.header = header self.footer = footer } // MARK: - public override func applyDiff(old: Element, realizedSelf: RealizedElement?) { super.applyDiff(old, realizedSelf: realizedSelf) if let tableView = realizedSelf?.view as? FewTableView, handler = tableView.handler, oldSelf = old as? TableView { handler.update(elements, sectionHeaders: sectionHeaders, sectionFooters: sectionFooters) handler.selectionChanged = selectionChanged let tableSelected = tableView.indexPathForSelectedRow() if tableSelected != selectedRow { if let selectedRow = selectedRow { tableView.selectRowAtIndexPath(selectedRow, animated: false, scrollPosition: .None) } else if let tableSelected = tableSelected { tableView.deselectRowAtIndexPath(tableSelected, animated: false) } } if let header = header { handler.headerView.updateWithElement(header) if tableView.tableHeaderView != handler.headerView { tableView.tableHeaderView = handler.headerView } } else if tableView.tableHeaderView == handler.headerView { tableView.tableHeaderView = nil } if let footer = footer { handler.footerView.updateWithElement(footer) if tableView.tableFooterView != handler.footerView { tableView.tableFooterView = handler.footerView } } else if tableView.tableFooterView == handler.footerView { tableView.tableFooterView = nil } } } public override func createView() -> ViewType { let tableView = FewTableView() let handler = TableViewHandler(tableView: tableView, elements: elements, headers: sectionHeaders, footers: sectionFooters) tableView.handler = handler tableView.handler?.selectionChanged = selectionChanged tableView.alpha = alpha tableView.hidden = hidden if let header = header { handler.headerView.updateWithElement(header) let layout = header.assembleLayoutNode().layout(maxWidth: tableView.frame.width) layout.apply(handler.headerView) tableView.tableHeaderView = handler.headerView } if let footer = footer { handler.footerView.updateWithElement(footer) let layout = footer.assembleLayoutNode().layout(maxWidth: tableView.frame.width) layout.apply(handler.footerView) tableView.tableFooterView = handler.footerView } return tableView } public override func elementDidLayout(realizedSelf: RealizedElement?) { super.elementDidLayout(realizedSelf) if let scrollView = realizedSelf?.view as? FewTableView { let handler = scrollView.handler handler?.update(elements, sectionHeaders: sectionHeaders, sectionFooters: sectionFooters) } } }
mit
a1604ab1af2dddfcb756b27c493f3110
31.628743
232
0.748371
4.344896
false
false
false
false
overtake/TelegramSwift
Telegram-Mac/PaymentMethodController.swift
1
3190
// // PaymentsCheckoutBotCheckoutPaymentMethodController.swift // Telegram // // Created by Mike Renoir on 26.07.2022. // Copyright © 2022 Telegram. All rights reserved. // import Foundation import Cocoa import TGUIKit import SwiftSignalKit private final class Arguments { let context: AccountContext let openNewMethod:(String)->Void init(context: AccountContext, openNewMethod:@escaping(String)->Void) { self.context = context self.openNewMethod = openNewMethod } } private struct State : Equatable { let methods: [BotCheckoutPaymentMethod] } private func entries(_ state: State, arguments: Arguments) -> [InputDataEntry] { var entries:[InputDataEntry] = [] var sectionId:Int32 = 0 var index: Int32 = 0 entries.append(.sectionId(sectionId, type: .normal)) sectionId += 1 for (i, method) in state.methods.enumerated() { let viewType = bestGeneralViewType(state.methods, for: i) entries.append(.general(sectionId: sectionId, index: index, value: .none, error: nil, identifier: InputDataIdentifier("\(arc4random())"), data: .init(name: method.title, color: theme.colors.text, type: .none, viewType: viewType, action: { switch method { case let .other(method): arguments.openNewMethod(method.url) default: break } }))) index += 1 } // entries entries.append(.sectionId(sectionId, type: .normal)) sectionId += 1 return entries } func PaymentMethodController(context: AccountContext, methods: [BotCheckoutPaymentMethod], newCard: @escaping()->Void, newByUrl:@escaping(String)->Void) -> InputDataModalController { let actionsDisposable = DisposableSet() var close:(()->Void)? = nil let initialState = State(methods: methods) let statePromise = ValuePromise(initialState, ignoreRepeated: true) let stateValue = Atomic(value: initialState) let updateState: ((State) -> State) -> Void = { f in statePromise.set(stateValue.modify (f)) } let arguments = Arguments(context: context, openNewMethod: { url in newByUrl(url) close?() }) let signal = statePromise.get() |> deliverOnPrepareQueue |> map { state in return InputDataSignalValue(entries: entries(state, arguments: arguments)) } let controller = InputDataController(dataSignal: signal, title: strings().checkoutPaymentMethodTitle) controller.onDeinit = { actionsDisposable.dispose() } let modalInteractions = ModalInteractions(acceptTitle: strings().checkoutPaymentMethodNew, accept: { newCard() close?() }, drawBorder: true, height: 50, singleButton: true) let modalController = InputDataModalController(controller, modalInteractions: modalInteractions) controller.leftModalHeader = ModalHeaderData(image: theme.icons.modalClose, handler: { [weak modalController] in modalController?.close() }) close = { [weak modalController] in modalController?.modal?.close() } return modalController } /* */
gpl-2.0
b25d5df34a497c633805a468a1400c75
28.256881
246
0.662277
4.817221
false
false
false
false
presence-insights/pi-clientsdk-ios
IBMPICoreTests/TestConstants.swift
1
984
/** * © Copyright 2016 IBM Corp. * * Licensed under the Presence Insights Client iOS Framework License (the "License"); * you may not use this file except in compliance with the License. You may find * a copy of the license in the license.txt file in this package. * * 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 /** * This struct stores the Presence Insights codes used in the unit tests. * Add the codes of your tenant to this file when testing the framework. */ struct PI { static let Hostname = "" static let Username = "" static let Password = "" static let Tenant = "" static let Org = "" static let Site = "" static let Floor = "" }
epl-1.0
7b0ff1e12e7731ca29cc8106ec57bee7
32.896552
86
0.704985
4.273913
false
true
false
false
illescasDaniel/Questions
Questions/Supporting views/RoundedView.swift
1
4178
// // RoundedView.swift // Questions // // Created by Daniel Illescas Romero on 20/01/2018. // Copyright © 2018 Daniel Illescas Romero. All rights reserved. // import UIKit struct ShadowEffect { let shadowColor: UIColor let shadowOffset: CGSize let shadowOpacity: Float let shadowRadius: CGFloat init(shadowColor: UIColor = .black, shadowOffset: CGSize = CGSize(width: 0.5, height: 4.0), shadowOpacity: Float = 0.5, shadowRadius: CGFloat = 5.0) { self.shadowColor = shadowColor self.shadowOffset = shadowOffset self.shadowOpacity = shadowOpacity self.shadowRadius = shadowRadius } } fileprivate protocol ShadowSettingsDelegate { var shadowColor: UIColor { get set } var shadowOffset: CGSize { get set } var shadowOpacity: Float { get set } var shadowRadius: CGFloat { get set } } @IBDesignable extension UIView: ShadowSettingsDelegate { @IBInspectable fileprivate var shadowColor: UIColor { get { return UIColor(cgColor: self.layer.shadowColor ?? UIColor.clear.cgColor) } set { self.layer.shadowColor = newValue.cgColor } } @IBInspectable fileprivate var shadowOffset: CGSize { get { return self.layer.shadowOffset } set { self.layer.shadowOffset = newValue } } @IBInspectable fileprivate var shadowOpacity: Float { get { return self.layer.shadowOpacity } set { self.layer.shadowOpacity = newValue } } @IBInspectable fileprivate var shadowRadius: CGFloat { get { return self.layer.shadowRadius } set { self.layer.shadowRadius = newValue } } } extension UIView { func setup(shadows: ShadowEffect = ShadowEffect()) { self.layer.shadowColor = shadows.shadowColor.cgColor self.layer.shadowOffset = shadows.shadowOffset self.layer.shadowRadius = shadows.shadowRadius self.layer.shadowOpacity = shadows.shadowOpacity } } @IBDesignable class RoundedView: UIView { @IBInspectable var cornerRadius: CGFloat = 0.0 @IBInspectable var borderColor: UIColor = .clear @IBInspectable var borderWidth: CGFloat = 0.5 private var customBackgroundColor = UIColor.white override var backgroundColor: UIColor? { didSet { customBackgroundColor = backgroundColor ?? .white super.backgroundColor = UIColor.clear } } private func setupPropertiesDefaultValues() { self.layer.shadowOpacity = 0.05; self.layer.shadowRadius = 3.5 super.backgroundColor = UIColor.clear } override init(frame: CGRect) { super.init(frame: frame) self.setupPropertiesDefaultValues() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.setupPropertiesDefaultValues() } override func draw(_ rect: CGRect) { customBackgroundColor.setFill() UIBezierPath(roundedRect: bounds, cornerRadius: cornerRadius).fill() let borderRect = bounds.insetBy(dx: borderWidth/2, dy: borderWidth/2) let borderPath = UIBezierPath(roundedRect: borderRect, cornerRadius: cornerRadius - borderWidth/2) borderColor.setStroke() borderPath.lineWidth = borderWidth borderPath.stroke() } } @IBDesignable class RoundedButton: UIButton { @IBInspectable var cornerRadius: CGFloat = 0.0 @IBInspectable var borderColor = UIColor.clear @IBInspectable var borderWidth: CGFloat = 0.5 private var customBackgroundColor = UIColor.white override var backgroundColor: UIColor? { didSet { customBackgroundColor = backgroundColor ?? .white super.backgroundColor = UIColor.clear } } private func setupPropertiesDefaultValues() { self.layer.shadowOpacity = 0.05; self.layer.shadowRadius = 3.5 super.backgroundColor = UIColor.clear } override init(frame: CGRect) { super.init(frame: frame) self.setupPropertiesDefaultValues() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.setupPropertiesDefaultValues() } override func draw(_ rect: CGRect) { customBackgroundColor.setFill() UIBezierPath(roundedRect: bounds, cornerRadius: cornerRadius).fill() let borderRect = bounds.insetBy(dx: borderWidth/2, dy: borderWidth/2) let borderPath = UIBezierPath(roundedRect: borderRect, cornerRadius: cornerRadius - borderWidth/2) borderColor.setStroke() borderPath.lineWidth = borderWidth borderPath.stroke() } }
mit
5f4b6ec943852e30e651e54403432ed1
26.480263
100
0.748623
4.06323
false
false
false
false
JGiola/swift-package-manager
Sources/Basic/DiagnosticsEngine.swift
2
11344
/* 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 http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for Swift project authors */ import Dispatch /// A type which can be used as a diagnostic parameter. public protocol DiagnosticParameter { /// Human readable diagnostic description of the parameter. var diagnosticDescription: String { get } } // Default implementation for types which conform to CustomStringConvertible. extension DiagnosticParameter where Self: CustomStringConvertible { public var diagnosticDescription: String { return description } } // Conform basic types. extension String: DiagnosticParameter {} extension Int: DiagnosticParameter {} /// A builder for constructing diagnostic descriptions. public class DiagnosticDescriptionBuilder<Data: DiagnosticData> { public var fragments: [DiagnosticID.DescriptionFragment] = [] func build( _ body: (DiagnosticDescriptionBuilder) -> Void ) -> [DiagnosticID.DescriptionFragment] { body(self) return fragments } } @discardableResult public func <<< <T>( builder: DiagnosticDescriptionBuilder<T>, string: String ) -> DiagnosticDescriptionBuilder<T> { builder.fragments.append(.literal(string, preference: .default)) return builder } @discardableResult public func <<<<T, P: DiagnosticParameter>( builder: DiagnosticDescriptionBuilder<T>, accessor: @escaping (T) -> P ) -> DiagnosticDescriptionBuilder<T> { builder.fragments.append(.substitution({ accessor($0 as! T) }, preference: .default)) return builder } @discardableResult public func <<< <T>( builder: DiagnosticDescriptionBuilder<T>, fragment: DiagnosticID.DescriptionFragment ) -> DiagnosticDescriptionBuilder<T> { builder.fragments.append(fragment) return builder } // FIXME: One thing we should consider is whether we should make the diagnostic // a protocol and put these properties on the type, which is conceptually the // right modeling, but might be cumbersome of our desired features don't // perfectly align with what the language can express. // /// A unique identifier for a diagnostic. /// /// Diagnostic identifiers are intended to be a stable representation of a /// particular kind of diagnostic that can be emitted by the client. /// /// The stabilty of identifiers is important for use cases where the client /// (e.g., a command line tool, an IDE, or a web UI) is expecting to receive /// diagnostics and be able to present additional UI affordances or workflows /// associated for specific kinds of diagnostics. public class DiagnosticID: ObjectIdentifierProtocol { /// A piece of a diagnostic description. public enum DescriptionFragment { /// Represents how important a fragment is. public enum Preference { case low, `default`, high } /// A literal string. case literalItem(String, preference: Preference) /// A substitution of a computed value. case substitutionItem((DiagnosticData) -> DiagnosticParameter, preference: Preference) public static func literal( _ string: String, preference: Preference = .default ) -> DescriptionFragment { return .literalItem(string, preference: preference) } public static func substitution( _ accessor: @escaping ((DiagnosticData) -> DiagnosticParameter), preference: Preference = .default ) -> DescriptionFragment { return .substitutionItem(accessor, preference: preference) } } /// The name of the diagnostic, which is expected to be in reverse dotted notation. public let name: String /// The English format string for the diagnostic description. public let description: [DescriptionFragment] /// The default behavior associated with this diagnostic. public let defaultBehavior: Diagnostic.Behavior /// Create a new diagnostic identifier. /// /// - Parameters: /// - type: The type of the payload data, used to help type inference. /// /// - name: The name of the identifier. /// /// - description: A closure which will compute the description from a /// builder. We compute descriptions in this fashion in /// order to take advantage of type inference to make it /// easy to have type safe accessors for the payload /// properties. /// /// The intended use is to support a convenient inline syntax for defining /// new diagnostics, for example: /// /// struct TooFewLives: DiagnosticData { /// static var id = DiagnosticID( /// type: TooFewLives.self, /// name: "org.swift.diags.too-few-lives", /// description: { $0 <<< "cannot create a cat with" <<< { $0.count } <<< "lives" } /// ) /// /// let count: Int /// } public init<T>( type: T.Type, name: String, defaultBehavior: Diagnostic.Behavior = .error, description buildDescription: (DiagnosticDescriptionBuilder<T>) -> Void ) { self.name = name self.description = DiagnosticDescriptionBuilder<T>().build(buildDescription) self.defaultBehavior = defaultBehavior } } /// The payload of a diagnostic. public protocol DiagnosticData: CustomStringConvertible { /// The identifier of the diagnostic this payload corresponds to. static var id: DiagnosticID { get } } extension DiagnosticData { public var description: String { return localizedDescription(for: self) } } /// The location of the diagnostic. public protocol DiagnosticLocation { /// The human readable summary description for the location. var localizedDescription: String { get } } public struct Diagnostic { public typealias Location = DiagnosticLocation /// The behavior associated with this diagnostic. public enum Behavior { /// An error which will halt the operation. case error /// A warning, but which will not halt the operation. case warning /// An informational message. case note /// A diagnostic which was ignored. case ignored } /// The diagnostic identifier. public var id: DiagnosticID { return type(of: data).id } /// The diagnostic's behavior. public let behavior: Behavior /// The conceptual location of this diagnostic. /// /// This could refer to a concrete location in a file, for example, but it /// could also refer to an abstract location such as "the Git repository at /// this URL". public let location: Location /// The information on the actual diagnostic. public let data: DiagnosticData // FIXME: Need additional attachment mechanism (backtrace, etc.), or // extensible handlers (e.g., interactive diagnostics). /// Create a new diagnostic. /// /// - Parameters: /// - location: The abstract location of the issue which triggered the diagnostic. /// - parameters: The parameters to the diagnostic conveying additional information. /// - Precondition: The bindings must match those declared by the identifier. public init(location: Location, data: DiagnosticData) { // FIXME: Implement behavior overrides. self.behavior = type(of: data).id.defaultBehavior self.location = location self.data = data } /// The human readable summary description for the diagnostic. public var localizedDescription: String { return Basic.localizedDescription(for: data) } } /// A scope of diagnostics. /// /// The scope provides aggregate information on all of the diagnostics which can /// be produced by a component. public protocol DiagnosticsScope { /// Get a URL for more information on a particular diagnostic ID. /// /// This is intended to be used to provide verbose descriptions for diagnostics. /// /// - Parameters: /// - id: The diagnostic ID to describe. /// - diagnostic: If provided, a specific diagnostic to describe. /// - Returns: If available, a URL which will give more information about /// the diagnostic. func url(describing id: DiagnosticID, for diagnostic: Diagnostic?) -> String? } public class DiagnosticsEngine: CustomStringConvertible { public typealias DiagnosticsHandler = (Diagnostic) -> Void /// Queue to protect concurrent mutations to the diagnositcs engine. private let queue = DispatchQueue(label: "\(DiagnosticsEngine.self)") /// Queue for dispatching handlers. private let handlerQueue = DispatchQueue(label: "\(DiagnosticsEngine.self)-callback") /// The diagnostics produced by the engine. public var diagnostics: [Diagnostic] { return queue.sync { _diagnostics } } private var _diagnostics: [Diagnostic] = [] /// The list of handlers to run when a diagnostic is emitted. /// /// The handler will be called on an unknown queue. private let handlers: [DiagnosticsHandler] /// Returns true if there is an error diagnostics in the engine. public var hasErrors: Bool { return diagnostics.contains(where: { $0.behavior == .error }) } public init(handlers: [DiagnosticsHandler] = []) { self.handlers = handlers } public func emit(data: DiagnosticData, location: DiagnosticLocation) { let diagnostic = Diagnostic(location: location, data: data) queue.sync { _diagnostics.append(diagnostic) } // Call the handlers on the background queue, if we have any. if !handlers.isEmpty { // FIXME: We should probably do this async but then we need // a way for clients to be able to wait until all handlers // are called. handlerQueue.sync { for handler in self.handlers { handler(diagnostic) } } } } /// Merges contents of given engine. public func merge(_ engine: DiagnosticsEngine) { for diagnostic in engine.diagnostics { emit(data: diagnostic.data, location: diagnostic.location) } } public var description: String { let stream = BufferedOutputByteStream() stream <<< "[" for diag in diagnostics { stream <<< diag.localizedDescription <<< ", " } stream <<< "]" return stream.bytes.asString! } } /// Returns localized description of a diagnostic data. fileprivate func localizedDescription(for data: DiagnosticData) -> String { var result = "" for (i, fragment) in type(of: data).id.description.enumerated() { if i != 0 { result += " " } switch fragment { case let .literalItem(string, _): result += string case let .substitutionItem(accessor, _): result += accessor(data).diagnosticDescription } } return result }
apache-2.0
a0449b7b390c05250b2236e9a81756f6
32.661721
99
0.657881
5.032831
false
false
false
false
jigneshsheth/Datastructures
DataStructure/DataStructure/Utils/ReflectedStringConvertible.swift
1
902
// // ReflectedStringConvertible.swift // DataStructure // // Created by Jigs Sheth on 4/24/16. // Copyright © 2016 jigneshsheth.com. All rights reserved. // import Foundation //http://mattcomi.tumblr.com/post/143043907238/struct-style-printing-of-classes-in-swift?utm_campaign=Swift%2BSandbox&utm_medium=email&utm_source=Swift_Sandbox_38 public protocol ReflectedStringConvertible:CustomStringConvertible {} extension ReflectedStringConvertible { public var description:String { let mirror = Mirror(reflecting: self) var str = "\(mirror.subjectType)(" var first = true for (label, value) in mirror.children { if let label = label { if first { first = false }else { str += "," } str += label str += ": " str += "\(value)" } } str += ")" return str } }
mit
a7b6ecff84861bddff67dfca69637baf
21
162
0.611543
4.040359
false
false
false
false
benlangmuir/swift
validation-test/compiler_crashers_2_fixed/0183-sr8998.swift
32
238
// RUN: not %target-swift-frontend -emit-ir %s protocol P { associatedtype A: Q where A.B == Self } protocol Q { associatedtype B: P where B.A == Self } struct S1<T>: P where T: Q { } struct S2: Q { typealias B = S1<S2> }
apache-2.0
0172bc43e7b1ea2ee67dea98734f66a3
14.866667
46
0.605042
2.704545
false
false
false
false
wireapp/wire-ios
Wire-iOS Tests/ProfileViewTests.swift
1
2450
// // Wire // Copyright (C) 2019 Wire Swiss GmbH // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // import XCTest @testable import Wire final class ProfileViewTests: ZMSnapshotTestCase { func test_DefaultOptions() { verifyProfile(options: []) } func testDefaultOptions_NoAvailability() { verifyProfile(options: [], availability: .none) } func testDefaultOptions_NoAvailability_Edit() { verifyProfile(options: [.allowEditingAvailability], availability: .none) } func test_DefaultOptions_AllowEditing() { verifyProfile(options: [.allowEditingAvailability]) } func test_HideName() { verifyProfile(options: [.hideUsername]) } func test_HideTeamName() { verifyProfile(options: [.hideTeamName]) } func test_HideHandle() { verifyProfile(options: [.hideHandle]) } func test_HideNameAndHandle() { verifyProfile(options: [.hideUsername, .hideHandle]) } func test_HideAvailability() { verifyProfile(options: [.hideAvailability]) } // MARK: - Helpers func verifyProfile(options: ProfileHeaderViewController.Options, availability: AvailabilityKind = .available, file: StaticString = #file, line: UInt = #line) { let selfUser = MockUserType.createSelfUser(name: "selfUser", inTeam: UUID()) selfUser.teamName = "Stunning" selfUser.handle = "browncow" selfUser.availability = availability let sut = ProfileHeaderViewController(user: selfUser, viewer: selfUser, options: options) sut.view.frame.size = sut.view.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize) sut.view.backgroundColor = SemanticColors.View.backgroundDefault sut.overrideUserInterfaceStyle = .dark verify(view: sut.view, file: file, line: line) } }
gpl-3.0
4cd26204fc10aac48abc664b363d11e0
31.236842
163
0.697143
4.605263
false
true
false
false
Noobish1/KeyedAPIParameters
KeyedAPIParametersTests/Protocols/APIParamConvertibleSpec.swift
1
5270
import Quick import Nimble import Fakery @testable import KeyedAPIParameters internal final class APIParamConvertibleSpec: QuickSpec { private func testNumberParamConvertible<T: APIParamConvertible>(object objectClosure: @escaping () -> T) where T: NumberParamConvertible { var object: T! beforeEach { object = objectClosure() } context("get") { it("should return the number as a string") { expect(object.value(forHTTPMethod: .get) as? String) == String(describing: object!) } } testNumberParamConvertible("post", object: objectClosure, forNonGetHTTPMethod: { .post }) testNumberParamConvertible("put", object: objectClosure, forNonGetHTTPMethod: { .put }) testNumberParamConvertible("delete", object: objectClosure, forNonGetHTTPMethod: { .delete }) } private func testNumberParamConvertible<T: APIParamConvertible>(_ contextName: String, object objectClosure: @escaping () -> T, forNonGetHTTPMethod methodClosure: @escaping () -> HTTPMethod) where T: NumberParamConvertible { var method: HTTPMethod! var object: T! beforeEach { object = objectClosure() method = methodClosure() } context("\(contextName)") { it("should return the value wrapped as an NSNumber") { expect(object.value(forHTTPMethod: method) as? NSNumber) == object.toNSNumber() } } } internal override func spec() { let faker = Faker() describe("it's value for HTTPMethod") { context("when the object is a") { context("String") { var object: String! beforeEach { object = faker.lorem.characters() } it("should return itself") { expect(object.value(forHTTPMethod: .get) as? String) == object } } context("Bool") { testNumberParamConvertible { faker.number.randomBool() } } context("Int") { testNumberParamConvertible { faker.number.randomInt() } } context("Float") { testNumberParamConvertible { faker.number.randomFloat() } } context("Double") { testNumberParamConvertible { faker.number.randomDouble() } } context("optionalConvertible") { context("when the given value is nil") { var actual: NSNull! var object: String? beforeEach { object = nil actual = object.value(forHTTPMethod: .get) as? NSNull } it("should return NSNull") { expect(actual) == NSNull() } } context("when the given is not nil") { var expected: String! var actual: String! var object: String? beforeEach { expected = "expected" object = expected actual = object.value(forHTTPMethod: .get) as? String } it("should return the result of calling valueForHTTPMethod on that value") { expect(actual) == expected } } } context("arrayConvertible") { var actual: [String]! var expected: [String]! beforeEach { expected = ["expected"] actual = expected.value(forHTTPMethod: .get) as? [String] } it("should return an array of the results of calling valueForHTTPMethod on each of its elements") { expect(actual) == expected } } context("null") { var actual: NSNull! var expected: NSNull! beforeEach { expected = NSNull() actual = expected.value(forHTTPMethod: .get) as? NSNull } it("should return NSNull") { expect(actual) == expected } } } } } }
mit
e20d64b2ade3f4494f22ec9db5843643
37.75
229
0.420873
6.906946
false
true
false
false
dictav/SwiftLint
Source/SwiftLintFramework/Extensions/String+SwiftLint.swift
1
2505
// // String+SwiftLint.swift // SwiftLint // // Created by JP Simard on 2015-05-16. // Copyright (c) 2015 Realm. All rights reserved. // import Foundation import SourceKittenFramework import SwiftXPC extension String { func hasTrailingWhitespace() -> Bool { if isEmpty { return false } if let character = utf16.suffix(1).first { return NSCharacterSet.whitespaceCharacterSet().characterIsMember(character) } return false } func isUppercase() -> Bool { return self == uppercaseString } public var chomped: String { return stringByTrimmingCharactersInSet(NSCharacterSet.newlineCharacterSet()) } public func nameStrippingLeadingUnderscoreIfPrivate(dict: XPCDictionary) -> String { let privateACL = "source.lang.swift.accessibility.private" if dict["key.accessibility"] as? String == privateACL && characters.first == "_" { return self[startIndex.successor()..<endIndex] } return self } subscript (range: Range<Int>) -> String { get { let subStart = startIndex.advancedBy(range.startIndex, limit: endIndex) let subEnd = subStart.advancedBy(range.endIndex - range.startIndex, limit: endIndex) return substringWithRange(Range(start: subStart, end: subEnd)) } } func substring(from: Int, length: Int? = nil) -> String { if let length = length { return self[from..<from + length] } return substringFromIndex(startIndex.advancedBy(from, limit: endIndex)) } public func lastIndexOf(search: String) -> Int? { if let range = rangeOfString(search, options: [.LiteralSearch, .BackwardsSearch]) { return startIndex.distanceTo(range.startIndex) } return nil } } extension NSString { public func lineAndCharacterForCharacterOffset(offset: Int) -> (line: Int, character: Int)? { let range = NSRange(location: offset, length: 0) var numberOfLines = 0, index = 0, lineRangeStart = 0, previousIndex = 0 while index < length { numberOfLines++ if index > range.location { break } lineRangeStart = numberOfLines previousIndex = index index = NSMaxRange(lineRangeForRange(NSRange(location: index, length: 1))) } return (lineRangeStart, range.location - previousIndex + 1) } }
mit
9b09961b100ec894f69e6614a9640d65
30.3125
97
0.623553
4.854651
false
false
false
false
yichizhang/SubjectiveCCastroControls_Swift
SCCastroControls/SCPlaybackViewController.swift
1
9519
// // SCPlaybackViewController.swift // SCCastroControls // // Created by Yichi on 1/03/2015. // Copyright (c) 2015 Subjective-C. All rights reserved. // import Foundation import UIKit // MARK: Consts let kViewHeight:CGFloat = 50 let kTimelineCollapsedHeight:CGFloat = 2 let kTimelineExpandedHeight:CGFloat = 22 let kKeylineHeight:CGFloat = 1 let kCollisionBoundaryOffset:CGFloat = 10 let kPushMagnitude:CGFloat = 4 let kGravityMagnitude:CGFloat = 2 class SCPlaybackViewController : UIViewController, UICollisionBehaviorDelegate, SCControlsViewDelegate { var playbackItem:SCPlaybackItem { set { _playbackItem = newValue timelineView.updateForPlaybackItem(playbackItem) controlsView.updateForPlaybackItem(playbackItem) } get { if _playbackItem == nil { _playbackItem = SCPlaybackItem() } return _playbackItem! } } // MARK: Private properties: private var _playbackItem:SCPlaybackItem? lazy var dynamicAnimator:UIDynamicAnimator = { return UIDynamicAnimator(referenceView: self.view) }() var playbackTimer:NSTimer? lazy var scrubbingBehavior:SCScrubbingBehavior = { return SCScrubbingBehavior(item: self.controlsView, snapToPoint: self.view.center) }() lazy var tapHintBehavior:SCTapHintBehavior = { return SCTapHintBehavior(items: [self.controlsView]) }() lazy var controlsView:SCControlsView = { return SCControlsView(frame: self.view.bounds) }() lazy var timelineView:SCTimelineView = { SCTimelineView(frame: CGRect(x: 0, y: kTimelineExpandedHeight * -1.0, width: self.view.bounds.width, height: kTimelineExpandedHeight)) }() var touchesBeganPoint = CGPointZero var elapsedTimeAtTouchesBegan = NSTimeInterval(0) lazy var panGestureRecognizer:UIPanGestureRecognizer = { return UIPanGestureRecognizer(target: self, action: "panGestureRecognized:") }() lazy var tapGestureRecognizer:UITapGestureRecognizer = { return UITapGestureRecognizer(target: self, action: "tapGestureRecognized:") }() var timelineScrubbing = false var commitTimelineScrubbing = false var shouldCommitTimelineScrubbing:Bool { return commitTimelineScrubbing } // MARK: loadView and viewDidLoad override func loadView() { let view = UIView(frame: CGRect(x: 0, y: 0, width: UIScreen.mainScreen().bounds.width, height: kViewHeight)) self.view = view } override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.blackColor() controlsView.delegate = self view.addSubview(controlsView) collapseTimelineViewAnimated(false) view.addSubview(timelineView) let keylineView = UIView(frame: CGRect(x: 0, y: kKeylineHeight * -1, width: view.bounds.width, height: kKeylineHeight)) keylineView.backgroundColor = UIColor.whiteColor().colorWithAlphaComponent(0.25) view.addSubview(keylineView) tapHintBehavior.collisionBehavior.collisionDelegate = self tapHintBehavior.collisionBehavior.translatesReferenceBoundsIntoBoundary = false dynamicAnimator.addBehavior(scrubbingBehavior) controlsView.addGestureRecognizer(panGestureRecognizer) controlsView.addGestureRecognizer(tapGestureRecognizer) } // MARK: Playback timer func timerDidFire(sender:AnyObject) { if timelineScrubbing == false && playbackItem.elapsedTime < playbackItem.totalTime { playbackItem.elapsedTime += 1 timelineView.updateForPlaybackItem(playbackItem) controlsView.updateForPlaybackItem(playbackItem) } } func expandTimelineViewAnimated(animated:Bool) { timelineScrubbing = true timelineView.elapsedTimeLabel.alpha = 1.0 let timelineExpansionBlock = { () -> () in self.timelineView.transform = CGAffineTransformIdentity } let completionBlock = { (completed:Bool) -> Void in self.commitTimelineScrubbing = true } if animated { UIView.animateWithDuration(0.2, delay: 0, options: .BeginFromCurrentState, animations: timelineExpansionBlock, completion: completionBlock) } else { timelineExpansionBlock() completionBlock(true) } } func collapseTimelineViewAnimated(animated:Bool) { timelineScrubbing = false timelineView.elapsedTimeLabel.alpha = 0.0 if shouldCommitTimelineScrubbing == false { playbackItem.elapsedTime = elapsedTimeAtTouchesBegan timelineView.updateForPlaybackItem(playbackItem) controlsView.updateForPlaybackItem(playbackItem) } let timelineCollapsingBlock = { () -> Void in let timelineViewScaleTransform = CGAffineTransformMakeScale(1.0, kTimelineCollapsedHeight / kTimelineExpandedHeight) let timelineViewTranslationTransform = CGAffineTransformMakeTranslation(0.0, kTimelineExpandedHeight / kTimelineCollapsedHeight) self.timelineView.transform = CGAffineTransformConcat(timelineViewScaleTransform, timelineViewTranslationTransform) } let completionBlock = { (completed:Bool) -> Void in self.commitTimelineScrubbing = false } if animated { UIView.animateWithDuration(0.15, delay: 0, options: .BeginFromCurrentState, animations: timelineCollapsingBlock, completion: completionBlock) } else { timelineCollapsingBlock() completionBlock(true) } } // MARK: UIPanGestureRecognizer func panGestureRecognized(panGesture:UIPanGestureRecognizer) { let translationInView = panGesture.translationInView(view) if panGesture.state == .Began { dynamicAnimator.removeBehavior(scrubbingBehavior) touchesBeganPoint = translationInView elapsedTimeAtTouchesBegan = playbackItem.elapsedTime expandTimelineViewAnimated(true) fadeOutControls() } else if panGesture.state == .Changed { let translatedCenterX = view.center.x + (translationInView.x - self.touchesBeganPoint.x) let scrubbingProgress = (translationInView.x - touchesBeganPoint.x) / view.bounds.width let timeAdjustment = playbackItem.totalTime * NSTimeInterval(scrubbingProgress) playbackItem.elapsedTime = elapsedTimeAtTouchesBegan + timeAdjustment timelineView.updateForPlaybackItem(playbackItem) controlsView.updateForPlaybackItem(playbackItem) controlsView.center = CGPoint(x: translatedCenterX, y: controlsView.center.y) } else if panGesture.state == .Ended { dynamicAnimator.addBehavior(scrubbingBehavior) collapseTimelineViewAnimated(true) fadeInControls() } } // MARK: View fading func fadeOutControls() { UIView.animateWithDuration(0.2, delay: 0, options: .BeginFromCurrentState, animations: { () -> Void in self.controlsView.configureAlphaForScrubbingState() }, completion: nil) } func fadeInControls() { UIView.animateWithDuration(0.15, delay: 0, options: .BeginFromCurrentState, animations: { () -> Void in self.controlsView.configureAlphaForDefaultState() }, completion: nil) } // MARK: UITapGestureRecognizer func tapGestureRecognized(tapGestureRecognizer:UITapGestureRecognizer) { tapHintBehavior.collisionBehavior.removeAllBoundaries() dynamicAnimator.removeBehavior(scrubbingBehavior) dynamicAnimator.addBehavior(tapHintBehavior) let locationInView = tapGestureRecognizer.locationInView(view) if locationInView.x < view.bounds.midX { let leftCollisionPointTop = CGPoint(x: kCollisionBoundaryOffset * -1, y: 0) let leftCollisionPointBottom = CGPoint(x: kCollisionBoundaryOffset * -1, y: view.bounds.height) tapHintBehavior.collisionBehavior.addBoundaryWithIdentifier("leftCollisionPoint", fromPoint: leftCollisionPointTop, toPoint: leftCollisionPointBottom) tapHintBehavior.gravityBehavior.setAngle(CGFloat(M_PI), magnitude: kGravityMagnitude) tapHintBehavior.pushBehavior.setAngle(0, magnitude: kPushMagnitude) } else { let rightCollisionPointTop = CGPoint(x: view.bounds.width + kCollisionBoundaryOffset, y: 0) let rightCollisionPointBottom = CGPoint(x: view.bounds.width + kCollisionBoundaryOffset, y: view.bounds.height) tapHintBehavior.collisionBehavior.addBoundaryWithIdentifier("rightCollisionPoint", fromPoint: rightCollisionPointTop, toPoint: rightCollisionPointBottom) tapHintBehavior.gravityBehavior.setAngle(0, magnitude: kGravityMagnitude) tapHintBehavior.pushBehavior.setAngle(CGFloat(M_PI), magnitude: kPushMagnitude) } tapHintBehavior.pushBehavior.active = true } // MARK: UICollisionBehaviorDelegate func collisionBehavior(behavior: UICollisionBehavior, beganContactForItem item: UIDynamicItem, withBoundaryIdentifier identifier: NSCopying, atPoint p: CGPoint) { dynamicAnimator.addBehavior(scrubbingBehavior) dynamicAnimator.removeBehavior(tapHintBehavior) } // MARK: SCControlsViewDelegate func controlsView(controlsView: SCControlsView!, didTapPlayButton playButton: UIButton!) { playbackTimer = NSTimer(timeInterval: NSTimeInterval(1), target: self, selector: "timerDidFire:", userInfo: nil, repeats: true) NSRunLoop.currentRunLoop().addTimer(playbackTimer!, forMode: NSDefaultRunLoopMode) } func controlsView(controlsView: SCControlsView!, didTapPauseButton playButton: UIButton!) { playbackTimer?.invalidate() } func controlsView(controlsView: SCControlsView!, didTapRewindButton playButton: UIButton!) { playbackItem.elapsedTime = max(0, playbackItem.elapsedTime - 30) timelineView.updateForPlaybackItem(playbackItem) controlsView.updateForPlaybackItem(playbackItem) } func controlsView(controlsView: SCControlsView!, didTapFastForwardButton playButton: UIButton!) { playbackItem.elapsedTime = min(playbackItem.totalTime, playbackItem.elapsedTime + 30) timelineView.updateForPlaybackItem(playbackItem) controlsView.updateForPlaybackItem(playbackItem) } }
mit
efe662e181c8007fad6b7128f042c8c4
34.785714
163
0.784011
4.567658
false
false
false
false
zning1994/practice
Swift学习/MySwiftProjTest/MySwiftProjTest/main.swift
1
3720
// // main.swift // MySwiftProjTest // // Created by ZNing on 15/6/9. // Copyright (c) 2015年 ZNing. All rights reserved. // import Foundation print("Hello, World!") print("唐静是个SHACHA") var 😂😂="String" print(😂😂) var numsec = 5 var description = "数值 \(numsec) 是" switch numsec { case 2,3,5,7,11,13,17,19: description += "[质数]而且还是" fallthrough default: description += "[整数]" } print(description) var sorce = 75 switch sorce { case 91...100: print("A.") case 81...90: print("B.") case 71...80: print("C.") case 61...70: print("D.") case 0..<60: print("F.") default: break } var mineArr : Array<String> var mineNames : [String] var mineNums : [Int] mineArr = Array<String>() mineNames = Array<String> (count: 10, repeatedValue: "fkit") mineNums = Array<Int> (count: 100, repeatedValue: 0) var flowers:[String] = ["😂😂😂😊","♦️","♠️","♣️"] var values = ["2","3","4","5","6"] print(mineNames[1]) mineNames[0] = "Spring" for var i = 0; i < flowers.count ;i++ { print(flowers[i]) } mineNames[1] = "Lua" mineNames[2] = "Ruby" for var i = 0 ; i < mineNames.count ; i++ { print(mineNames[i]) } var books : [String] = ["理想之路","玄幻之路","傻叉之路"] for book in books { print(book) } var languages = ["Swift"] languages.append("Go") languages.append("Lua") print(languages) print(languages.count) languages = languages + ["Ruby"] languages += ["Ruby"] print(languages) print(languages.count) var newLanguages = ["Swift"] newLanguages.insert("Go", atIndex: 0) newLanguages.insert("Lua", atIndex: 2) print(newLanguages) print(newLanguages.count) //newLanguages.insert("Ruby", atIndex: 4) 错误:超出数组现有长度 var secLanguages = ["Swift","OC","PHP","Perl","Ruby","Go"] let subRange = secLanguages[1..<4] secLanguages[2...4] = ["C/C++","Python"] secLanguages[1...2] = ["a","b","c"] secLanguages[0..<secLanguages.count] = [] print(secLanguages) secLanguages = ["Swift","OC","PHP","Perl","Ruby","Go"] secLanguages.removeAtIndex(2) secLanguages.removeAtIndex(2) secLanguages.removeLast() print(secLanguages) secLanguages.removeAll() print(secLanguages) print(secLanguages.count) var amax : [[Int]] amax = Array<Array<Int>> (count: 4, repeatedValue: []) for var i = 0 , len = amax.count; i < len ; i++ { print(amax[i]); } amax[0] = Array<Int> (count: 2 , repeatedValue: 0) amax[0][1] = 6; for var i = 0, len = amax[0].count ; i<len ; i++ { print(amax[0][i]); } var myDict : Dictionary<String, String> var scores : [String : Int] var health : [String : String] myDict = Dictionary<String, String>() scores = Dictionary<String, Int>(minimumCapacity: 5) print(scores) health = ["Hight":"178","Weight":"74","BloodPresure":"86/113"] print(health) var dict = ["one": 1,"two": 2, "three": 3,"four": 4] print(dict) var emptyDict:[String:Double] = [:] print(emptyDict.isEmpty) print(emptyDict) var height = health["Hight"] print("身高为:\(height)") var noExist = health["no"] print(noExist) health["血压"] = "78/112" print(health) //赋值失败?等号中英文问题,解决。 scores["语文"]=87 scores["数学"]=92 scores["英语"]=95 print(scores) var englishScore : Int? = scores["英语"] if englishScore != nil { print("scores中包含的英语成绩为:\(englishScore!)") } var result = scores.updateValue(20, forKey: "java") print(result) print(scores) var seasons = ["spring":"春暖花开","summer":"夏日炎炎","autumn":"秋高气爽","winter":"冬雪皑皑"] for (season, desc) in seasons { print("\(season)-->\(desc)") } var keys = Array(seasons.keys) var valuess = Array(seasons.values) print(keys) print(valuess)
gpl-2.0
0f4bfd995edc76c7c560eab637628063
17.951087
79
0.648021
2.779904
false
false
false
false
almazrafi/Metatron
Sources/ID3v2/FrameStuffs/ID3v2AudioEncryption.swift
1
4037
// // ID3v2AudioEncryption.swift // Metatron // // Copyright (c) 2016 Almaz Ibragimov // // 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 Foundation public class ID3v2AudioEncryption: ID3v2FrameStuff { // MARK: Instance Properties public var ownerIdentifier: String = "" public var previewStart: UInt16 = 0 public var previewLength: UInt16 = 0 public var encryptionInfo: [UInt8] = [] // MARK: public var isEmpty: Bool { return self.ownerIdentifier.isEmpty } // MARK: Initializers public init() { } public required init(fromData data: [UInt8], version: ID3v2Version) { guard (data.count > 5) && (data[0] != 0) else { return } guard let ownerIdentifier = ID3v2TextEncoding.latin1.decode(data) else { return } let offset = ownerIdentifier.endIndex guard offset <= data.count - 4 else { return } self.ownerIdentifier = ownerIdentifier.text self.previewStart = UInt16(data[offset + 1]) | (UInt16(data[offset + 0]) << 8) self.previewLength = UInt16(data[offset + 3]) | (UInt16(data[offset + 2]) << 8) self.encryptionInfo = [UInt8](data.suffix(from: offset + 4)) } // MARK: Instance Methods public func toData(version: ID3v2Version) -> [UInt8]? { guard !self.isEmpty else { return nil } var data = ID3v2TextEncoding.latin1.encode(self.ownerIdentifier, termination: true) data.append(contentsOf: [UInt8((self.previewStart >> 8) & 255), UInt8((self.previewStart) & 255), UInt8((self.previewLength >> 8) & 255), UInt8((self.previewLength) & 255)]) data.append(contentsOf: self.encryptionInfo) return data } public func toData() -> (data: [UInt8], version: ID3v2Version)? { guard let data = self.toData(version: ID3v2Version.v4) else { return nil } return (data: data, version: ID3v2Version.v4) } } public class ID3v2AudioEncryptionFormat: ID3v2FrameStuffSubclassFormat { // MARK: Type Properties public static let regular = ID3v2AudioEncryptionFormat() // MARK: Instance Methods public func createStuffSubclass(fromData data: [UInt8], version: ID3v2Version) -> ID3v2AudioEncryption { return ID3v2AudioEncryption(fromData: data, version: version) } public func createStuffSubclass(fromOther other: ID3v2AudioEncryption) -> ID3v2AudioEncryption { let stuff = ID3v2AudioEncryption() stuff.ownerIdentifier = other.ownerIdentifier stuff.previewStart = other.previewStart stuff.previewLength = other.previewLength stuff.encryptionInfo = other.encryptionInfo return stuff } public func createStuffSubclass() -> ID3v2AudioEncryption { return ID3v2AudioEncryption() } }
mit
d958eb376c4bdad386667fbe68c15c59
30.294574
108
0.659153
4.276483
false
false
false
false
Sillyplus/swifter
Sources/Swifter/DemoServer.swift
1
3828
// // DemoServer.swift // Swifter // Copyright (c) 2015 Damian Kołakowski. All rights reserved. // import Foundation public func demoServer(publicDir: String?) -> HttpServer { let server = HttpServer() if let publicDir = publicDir { server["/resources/:file"] = HttpHandlers.directory(publicDir) } server["/files/:path"] = HttpHandlers.directoryBrowser("~/") server["/"] = { r in var listPage = "Available services:<br><ul>" listPage += server.routes.map({ "<li><a href=\"\($0)\">\($0)</a></li>"}).joinWithSeparator("") return .OK(.Html(listPage)) } server["/magic"] = { .OK(.Html("You asked for " + $0.url)) } server["/test/:param1/:param2"] = { r in var headersInfo = "" for (name, value) in r.headers { headersInfo += "\(name) : \(value)<br>" } var queryParamsInfo = "" for (name, value) in r.urlParams { queryParamsInfo += "\(name) : \(value)<br>" } var pathParamsInfo = "" for token in r.params { pathParamsInfo += "\(token.0) : \(token.1)<br>" } return .OK(.Html("<h3>Address: \(r.address)</h3><h3>Url:</h3> \(r.url)<h3>Method: \(r.method)</h3><h3>Headers:</h3>\(headersInfo)<h3>Query:</h3>\(queryParamsInfo)<h3>Path params:</h3>\(pathParamsInfo)")) } server["/upload"] = { r in switch r.method.uppercaseString { case "GET": if let rootDir = publicDir { if let html = NSData(contentsOfFile:"\(rootDir)/file.html") { var array = [UInt8](count: html.length, repeatedValue: 0) html.getBytes(&array, length: html.length) return HttpResponse.RAW(200, "OK", nil, array) } else { return .NotFound } } case "POST": let formFields = r.parseMultiPartFormData() return HttpResponse.OK(.Html(formFields.map({ UInt8ArrayToUTF8String($0.body) }).joinWithSeparator("<br>"))) default: return .NotFound } return .NotFound } server["/login"] = { r in switch r.method.uppercaseString { case "GET": if let rootDir = publicDir { if let html = NSData(contentsOfFile:"\(rootDir)/login.html") { var array = [UInt8](count: html.length, repeatedValue: 0) html.getBytes(&array, length: html.length) return HttpResponse.RAW(200, "OK", nil, array) } else { return .NotFound } } case "POST": let formFields = r.parseUrlencodedForm() return HttpResponse.OK(.Html(formFields.map({ "\($0.0) = \($0.1)" }).joinWithSeparator("<br>"))) default: return .NotFound } return .NotFound } server["/demo"] = { r in return .OK(.Html("<center><h2>Hello Swift</h2><img src=\"https://devimages.apple.com.edgekey.net/swift/images/swift-hero_2x.png\"/><br></center>")) } server["/raw"] = { request in return HttpResponse.RAW(200, "OK", ["XXX-Custom-Header": "value"], [UInt8]("Sample Response".utf8)) } server["/json"] = { request in let jsonObject: NSDictionary = [NSString(string: "foo"): NSNumber(int: 3), NSString(string: "bar"): NSString(string: "baz")] return .OK(.Json(jsonObject)) } server["/redirect"] = { request in return .MovedPermanently("http://www.google.com") } server["/long"] = { request in var longResponse = "" for k in 0..<1000 { longResponse += "(\(k)),->" } return .OK(.Html(longResponse)) } return server }
bsd-3-clause
17c3e77de3566ca464dfedf771fa76b3
34.435185
211
0.528874
4.075612
false
false
false
false
Molbie/Outlaw
Sources/Outlaw/Core/IndexExtractable/IndexExtractable.swift
1
3240
// // IndexExtractable.swift // Outlaw // // Created by Brian Mullen on 11/23/16. // Copyright © 2016 Molbie LLC. All rights reserved. // import Foundation public protocol IndexExtractable { var count: Int { get } var isEmpty: Bool { get } func any(for index: Index) throws -> Any func optionalAny(for index: Index) -> Any? } public extension IndexExtractable { func any(for index: Index) throws -> Any { let indexes = [index] var accumulator: Any = self for component in indexes { if let componentData = accumulator as? IndexExtractable, let value = componentData.optionalAny(for: component) { accumulator = value continue } throw OutlawError.indexNotFound(index: component.outlawIndex) } if let _ = accumulator as? NSNull { throw OutlawError.nullValueWithIndex(index: indexes[0].outlawIndex) } return accumulator } } // MARK: - // MARK: Any Array public extension IndexExtractable { func value<V>(for index: Index) throws -> [V] { let any = try self.any(for: index) do { return try Array<V>.value(from: any) } catch let OutlawError.typeMismatch(expected: expected, actual: actual) { throw OutlawError.typeMismatchWithIndex(index: index.outlawIndex, expected: expected, actual: actual) } } func optional<V>(for index: Index) -> [V]? { return try? self.value(for: index) } func value<V>(for index: Index, or value: [V]) -> [V] { guard let result: [V] = self.optional(for: index) else { return value } return result } } // MARK: - // MARK: Any Dictionary public extension IndexExtractable { func value<K, V>(for index: Index) throws -> [K: V] { let any = try self.any(for: index) do { return try Dictionary<K, V>.value(from: any) } catch let OutlawError.typeMismatch(expected: expected, actual: actual) { throw OutlawError.typeMismatchWithIndex(index: index.outlawIndex, expected: expected, actual: actual) } } func optional<K, V>(for index: Index) -> [K: V]? { return try? self.value(for: index) } func value<K, V>(for index: Index, or value: [K: V]) -> [K: V] { guard let result: [K: V] = self.optional(for: index) else { return value } return result } } // MARK: - // MARK: Any Set public extension IndexExtractable { func value<V>(for index: Index) throws -> Set<V> { let any = try self.any(for: index) do { return try Set<V>.value(from: any) } catch let OutlawError.typeMismatch(expected: expected, actual: actual) { throw OutlawError.typeMismatchWithIndex(index: index.outlawIndex, expected: expected, actual: actual) } } func optional<V>(for index: Index) -> Set<V>? { return try? self.value(for: index) } func value<V>(for index: Index, or value: Set<V>) -> Set<V> { guard let result: Set<V> = self.optional(for: index) else { return value } return result } }
mit
d961a38daa78e61dc9cdefb49390645a
28.18018
124
0.590306
4.013631
false
false
false
false
MainasuK/Bangumi-M
Percolator/Percolator/SubjectCollectionViewBookCell.swift
1
2286
// // SubjectCollectionViewBookCell.swift // Percolator // // Created by Cirno MainasuK on 2016-6-20. // // Ref: https://github.com/strawberrycode/SCSectionBackground import UIKit import AlamofireImage class SubjectCollectionViewBookCell: SubjectCollectionViewCell { typealias ModelCollectError = SubjectCollectionViewModel.ModelCollectError @IBOutlet weak var cardView: UIView! @IBOutlet weak var bookCover: UIImageView! @IBOutlet weak var bookNameLabel: UILabel! // No subtitle for book @IBOutlet weak var indicatorLabel: UILabel! override func awakeFromNib() { super.awakeFromNib() bookNameLabel.layer.masksToBounds = true indicatorLabel.layer.masksToBounds = true } override func prepareForReuse() { super.prepareForReuse() bookCover.af_cancelImageRequest() bookCover.layer.removeAllAnimations() bookCover.image = nil } override func configure(with item: ItemType) { let subjectItem = item.0 bookNameLabel.text = subjectItem.title configureIndicator(with: item.1) bookCover.backgroundColor = .systemFill let size = CGSize(width: 1, height: 1) if let url = URL(string: subjectItem.coverUrlPath) { bookCover.af_setImage(withURL: url, placeholderImage: UIImage(), progressQueue: DispatchQueue.global(qos: .userInitiated), imageTransition: .crossDissolve(0.2)) } else { bookCover.image = nil } // Set iamge view corner bookCover.layer.borderColor = UIColor.percolatorGray.cgColor bookCover.layer.borderWidth = 0.5 // Set background color backgroundColor = .secondarySystemGroupedBackground } } extension SubjectCollectionViewBookCell { fileprivate func configureIndicator(with result: Result<CollectInfoSmall>) { indicatorLabel.text = "" do { let collect = try result.resolve() indicatorLabel.text = collect.name } catch ModelCollectError.unknown { consolePrint("Unknown subject collect info") } catch { consolePrint(error) } } }
mit
8efb3bde3109a1a6bfbd39b95888c00b
28.307692
172
0.643045
5.068736
false
false
false
false
infobip/mobile-messaging-sdk-ios
Example/MobileMessagingExample/Views/MessageCell.swift
1
1420
// // MessageCell.swift // MobileMessagingExample // // Created by Andrey K. on 20/05/16. // import UIKit class MessageCell: UITableViewCell { deinit { resetMessageObserving() } override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) textLabel?.numberOfLines = 5 accessoryType = .disclosureIndicator } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } var message: Message? { willSet { resetMessageObserving() } didSet { if let message = message { textLabel?.text = message.text refreshSeenStatus() } message?.addObserver(self, forKeyPath: kMessageSeenAttribute, options: .new, context: nil) } } override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { if keyPath == kMessageSeenAttribute { refreshSeenStatus() } else { super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context) } } fileprivate func resetMessageObserving() { message?.removeObserver(self, forKeyPath: kMessageSeenAttribute) } fileprivate func refreshSeenStatus() { guard let message = message else { return } textLabel?.font = message.seen ? UIFont.systemFont(ofSize: 15.0) : UIFont.boldSystemFont(ofSize: 15.0) } }
apache-2.0
5361c5f721fabd367943888ef7212632
23.912281
148
0.719718
3.827493
false
false
false
false
clappr/clappr-ios
Sources/Clappr_tvOS/Classes/Plugin/Playback/AVFoundationPlayback/AVFoundationNowPlayingBuilder.swift
1
3785
import MediaPlayer import AVKit import AVFoundation struct AVFoundationNowPlayingBuilder { struct Keys { static var contentIdentifier: String { if #available(tvOS 10.1, *) { return AVKitMetadataIdentifierExternalContentIdentifier } else { return "NPI/_MPNowPlayingInfoPropertyExternalContentIdentifier" } } static var playbackProgress: String { if #available(tvOS 10.1, *) { return AVKitMetadataIdentifierPlaybackProgress } else { return "NPI/_MPNowPlayingInfoPropertyPlaybackProgress" } } } let metadata: [String: Any] init(metadata: [String: Any] = [:]) { self.metadata = metadata } func getContentIdentifier() -> AVMutableMetadataItem? { guard let contentIdentifier = self.metadata[kMetaDataContentIdentifier] as? NSString else { return nil } return generateItem(for: Keys.contentIdentifier, with: contentIdentifier) } func getWatchedTime() -> AVMutableMetadataItem? { guard let watchedTime = self.metadata[kMetaDataWatchedTime] as? (NSCopying & NSObjectProtocol) else { return nil } return generateItem(for: Keys.playbackProgress, with: watchedTime) } func getTitle() -> AVMutableMetadataItem? { guard let title = self.metadata[kMetaDataTitle] as? NSString else { return nil } return generateItem(for: AVMetadataIdentifier.commonIdentifierTitle.rawValue, with: title) } func getDescription() -> AVMutableMetadataItem? { guard let description = self.metadata[kMetaDataDescription] as? NSString else { return nil } return generateItem(for: AVMetadataIdentifier.commonIdentifierDescription.rawValue, with: description) } func getDate() -> AVMutableMetadataItem? { guard let date = self.metadata[kMetaDataDate] as? Date else { return nil } let metadataDateFormatter = DateFormatter() metadataDateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ" let value = metadataDateFormatter.string(from: date) as NSString return generateItem(for: AVMetadataIdentifier.commonIdentifierCreationDate.rawValue, with: value) } func getArtwork(with options: Options, completion: @escaping (AVMutableMetadataItem?) -> Void) { if let image = metadata[kMetaDataArtwork] as? UIImage { completion(getArtwork(with: image)) } else if let poster = options[kPosterUrl] as? String, let url = URL(string: poster) { let task = URLSession.shared.dataTask(with: url) { data, _, _ in if let data = data, let image = UIImage(data: data) { completion(self.getArtwork(with: image)) } else { completion(nil) } } task.resume() } } func getArtwork(with image: UIImage) -> AVMutableMetadataItem? { guard let data = image.jpegData(compressionQuality: 1) as (NSCopying & NSObjectProtocol)? else { return nil } let item = generateItem(for: AVMetadataIdentifier.commonIdentifierArtwork.rawValue, with: data) item.dataType = kCMMetadataBaseDataType_JPEG as String return item } func generateItem(for identifier: String, with value: (NSCopying & NSObjectProtocol)?) -> AVMutableMetadataItem { let item = AVMutableMetadataItem() item.identifier = AVMetadataIdentifier(rawValue: identifier) item.value = value item.extendedLanguageTag = "und" return item } func build() -> [AVMetadataItem] { return [getTitle(), getDescription(), getDate(), getContentIdentifier(), getWatchedTime()].compactMap({ $0 }) } }
bsd-3-clause
ce6c34df73bf044c87bda2bc177467a2
39.265957
122
0.65469
5.073727
false
false
false
false
GreatfeatServices/gf-mobile-app
olivin-esguerra/ios-exam/Pods/RxSwift/RxSwift/Observables/Implementations/Timeout.swift
11
3478
// // Timeout.swift // RxSwift // // Created by Tomi Koskinen on 13/11/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import Foundation class TimeoutSink<O: ObserverType>: Sink<O>, LockOwnerType, ObserverType { typealias E = O.E typealias Parent = Timeout<E> private let _parent: Parent let _lock = NSRecursiveLock() private let _timerD = SerialDisposable() private let _subscription = SerialDisposable() private var _id = 0 private var _switched = false init(parent: Parent, observer: O, cancel: Cancelable) { _parent = parent super.init(observer: observer, cancel: cancel) } func run() -> Disposable { let original = SingleAssignmentDisposable() _subscription.disposable = original _createTimeoutTimer() original.setDisposable(_parent._source.subscribeSafe(self)) return Disposables.create(_subscription, _timerD) } func on(_ event: Event<E>) { switch event { case .next: var onNextWins = false _lock.performLocked() { onNextWins = !self._switched if onNextWins { self._id = self._id &+ 1 } } if onNextWins { forwardOn(event) self._createTimeoutTimer() } case .error, .completed: var onEventWins = false _lock.performLocked() { onEventWins = !self._switched if onEventWins { self._id = self._id &+ 1 } } if onEventWins { forwardOn(event) self.dispose() } } } private func _createTimeoutTimer() { if _timerD.isDisposed { return } let nextTimer = SingleAssignmentDisposable() _timerD.disposable = nextTimer let disposeSchedule = _parent._scheduler.scheduleRelative(_id, dueTime: _parent._dueTime) { state in var timerWins = false self._lock.performLocked() { self._switched = (state == self._id) timerWins = self._switched } if timerWins { self._subscription.disposable = self._parent._other.subscribeSafe(self.forwarder()) } return Disposables.create() } nextTimer.setDisposable(disposeSchedule) } } class Timeout<Element> : Producer<Element> { fileprivate let _source: Observable<Element> fileprivate let _dueTime: RxTimeInterval fileprivate let _other: Observable<Element> fileprivate let _scheduler: SchedulerType init(source: Observable<Element>, dueTime: RxTimeInterval, other: Observable<Element>, scheduler: SchedulerType) { _source = source _dueTime = dueTime _other = other _scheduler = scheduler } override func run<O : ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Element { let sink = TimeoutSink(parent: self, observer: observer, cancel: cancel) let subscription = sink.run() return (sink: sink, subscription: subscription) } }
apache-2.0
3227e3640d09304f22f3de107cb1e08f
27.5
145
0.54616
5.341014
false
false
false
false
NghiaTranUIT/Unofficial-Uber-macOS
UberGo/UberGo/MenuView.swift
1
2041
// // MenuView.swift // UberGo // // Created by Nghia Tran on 9/15/17. // Copyright © 2017 Nghia Tran. All rights reserved. // import Cocoa import RxCocoa import RxSwift import UberGoCore class MenuView: NSView { // MARK: - OUTLET @IBOutlet fileprivate weak var avatarImageView: NSImageView! @IBOutlet fileprivate weak var usernameLbl: NSTextField! @IBOutlet fileprivate weak var startLbl: NSTextField! // MARK: - Variable fileprivate let disposeBag = DisposeBag() override func awakeFromNib() { super.awakeFromNib() initCommon() binding() } // MARK: - Action @IBAction func paymentBtnOnTap(_ sender: NSButton) { } @IBAction func yourTripBtnOnTap(_ sender: NSButton) { } @IBAction func helpBtnOnTap(_ sender: NSButton) { } @IBAction func settingBtnOnTap(_ sender: NSButton) { } @IBAction func legalBtnOnTap(_ sender: NSButton) { } // MARK: - Public public func configureLayout(_ parentView: NSView) { translatesAutoresizingMaskIntoConstraints = false parentView.addSubview(self) edges(to: parentView) } } // MARK: - Binding extension MenuView { fileprivate func initCommon() { // Border avatarImageView.wantsLayer = true avatarImageView.layer?.cornerRadius = 32 avatarImageView.layer?.contentsGravity = kCAGravityResizeAspect } fileprivate func binding() { guard let user = UberAuth.share.currentUser else { return } // Profile user.requestUserProfile() user.userProfileObjVar .asDriver() .filterNil() .drive(onNext: {[weak self] profile in guard let `self` = self else { return } self.usernameLbl.stringValue = profile.fullName self.avatarImageView.asyncDownloadImage(profile.picture) }) .addDisposableTo(disposeBag) } } extension MenuView: XIBInitializable { typealias XibType = MenuView }
mit
b3c09b778609f0e6dc85c6ad4b8da641
23.578313
72
0.639706
4.915663
false
false
false
false
kristopherjohnson/KJNotepad
KJNotepad/KeyboardNotification.swift
1
3003
// // KeyboardNotification.swift // KJNotepad // // Created by Kristopher Johnson on 4/24/15. // Copyright (c) 2015 Kristopher Johnson. All rights reserved. // import UIKit /// Wrapper for the NSNotification userInfo values associated with a keyboard notification. /// /// It provides properties retrieve userInfo dictionary values with these keys: /// /// - UIKeyboardFrameBeginUserInfoKey /// - UIKeyboardFrameEndUserInfoKey /// - UIKeyboardAnimationDurationUserInfoKey /// - UIKeyboardAnimationCurveUserInfoKey public struct KeyboardNotification { let notification: NSNotification let userInfo: NSDictionary /// Initializer /// /// :param: notification Keyboard-related notification public init(_ notification: NSNotification) { self.notification = notification if let userInfo = notification.userInfo { self.userInfo = userInfo } else { self.userInfo = NSDictionary() } } /// Start frame of the keyboard in screen coordinates public var screenFrameBegin: CGRect { if let value = userInfo[UIKeyboardFrameBeginUserInfoKey] as? NSValue { return value.CGRectValue() } else { return CGRectZero } } /// End frame of the keyboard in screen coordinates public var screenFrameEnd: CGRect { if let value = userInfo[UIKeyboardFrameEndUserInfoKey] as? NSValue { return value.CGRectValue() } else { return CGRectZero } } /// Keyboard animation duration public var animationDuration: Double { if let number = userInfo[UIKeyboardAnimationDurationUserInfoKey] as? NSNumber { return number.doubleValue } else { return 0.25 } } /// Keyboard animation curve /// /// Note that the value returned by this method may not correspond to a /// UIViewAnimationCurve enum value. For example, in iOS 7 and iOS 8, /// this returns the value 7. public var animationCurve: Int { if let number = userInfo[UIKeyboardAnimationCurveUserInfoKey] as? NSNumber { return number.integerValue } return UIViewAnimationCurve.EaseInOut.rawValue } /// Start frame of the keyboard in coordinates of specified view /// /// :param: view UIView to whose coordinate system the frame will be converted /// :returns: frame rectangle in view's coordinate system public func frameBeginForView(view: UIView) -> CGRect { return view.convertRect(screenFrameBegin, fromView: view.window) } /// Start frame of the keyboard in coordinates of specified view /// /// :param: view UIView to whose coordinate system the frame will be converted /// :returns: frame rectangle in view's coordinate system public func frameEndForView(view: UIView) -> CGRect { return view.convertRect(screenFrameEnd, fromView: view.window) } }
mit
b79a4f81d4771d7fa5d5e727c92709e8
30.610526
91
0.664003
5.43038
false
false
false
false
abonz/Swift
CoreAnimationSample4/CoreAnimationSample4/ViewController.swift
6
3597
// // ViewController.swift // CoreAnimationSample4 // // Created by Carlos Butron on 02/12/14. // Copyright (c) 2015 Carlos Butron. All rights reserved. // // This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public // License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later // version. // This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied // warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. // You should have received a copy of the GNU General Public License along with this program. If not, see // http:/www.gnu.org/licenses/. // import UIKit class ViewController: UIViewController { var position = true @IBOutlet weak var image: UIImageView! @IBAction func animate(sender: UIButton) { if (position){ //SAMPLE 2 //SAMPLE 3 let subLayer : CALayer = self.image.layer let thePath : CGMutablePathRef = CGPathCreateMutable(); CGPathMoveToPoint(thePath, nil, 160.0, 200.0); CGPathAddCurveToPoint(thePath, nil, 83.0, 50.0, 100.0, 100.0, 160.0, 200.0); //CGPathAddCurveToPoint(thePath, nil, 320.0, 500.0, 566.0, 500.0, 566.0, 74.0); let theAnimation: CAKeyframeAnimation = CAKeyframeAnimation(keyPath:"position") theAnimation.path = thePath theAnimation.duration = 5.0 theAnimation.fillMode = kCAFillModeForwards theAnimation.removedOnCompletion = false let resizeAnimation:CABasicAnimation = CABasicAnimation(keyPath:"bounds.size") resizeAnimation.toValue = NSValue(CGSize:CGSizeMake(240, 60)) //SAMPLE 2 resizeAnimation.duration = 5.0 resizeAnimation.fillMode = kCAFillModeForwards resizeAnimation.removedOnCompletion = false subLayer.addAnimation(theAnimation, forKey: "position") image.layer.addAnimation(resizeAnimation, forKey: "bounds.size") position = false } else{ let animation:CABasicAnimation! = CABasicAnimation(keyPath:"position") animation.fromValue = NSValue(CGPoint:CGPointMake(160, 200)) //SAMPLE 2 animation.fillMode = kCAFillModeForwards animation.removedOnCompletion = false let resizeAnimation:CABasicAnimation = CABasicAnimation(keyPath:"bounds.size") resizeAnimation.fromValue = NSValue(CGSize:CGSizeMake(240, 60)) //SAMPLE 2 resizeAnimation.fillMode = kCAFillModeForwards resizeAnimation.removedOnCompletion = false image.layer.addAnimation(animation, forKey: "position") image.layer.addAnimation(resizeAnimation, forKey: "bounds.size") position = true } } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
gpl-3.0
4ed6461ee7473f038e1bc93032a741eb
34.613861
121
0.610787
5.491603
false
false
false
false
ingopaulsen/MovingHelper
MovingHelper/Models/Task.swift
22
3220
// // Task.swift // MovingHelper // // Created by Ellen Shapiro on 6/7/15. // Copyright (c) 2015 Razeware. All rights reserved. // import Foundation //MARK: Equatable public func == (lhs: Task, rhs: Task) -> Bool { return lhs.taskID == rhs.taskID } /** The main representation of a moving task. */ public class Task: CustomStringConvertible, Equatable { //MARK: Constants //MARK: Property variables public var taskID: Int public var title: String public var notes: String? public var dueDate: TaskDueDate public var done: Bool = false // MARK: Printable public var description: String { return "\(title)" } //MARK: Initializers /** Initializes a task with required values - parameter aTitle: The title of the task - parameter aDueDate: The due date of the task - returns: The created task with an assigned ID */ public init(aTitle: String, aDueDate: TaskDueDate) { title = aTitle dueDate = aDueDate taskID = Task.nextIdentifier() } /** Initializes a task from JSON. - parameter fromJSON: The NSDictionary with the data regarding the task. - returns: The instantiated task object. */ public init(fromJSON: NSDictionary) { title = fromJSON.safeString(TaskJSONKey.Title.rawValue) let dueDateString = fromJSON.safeString(TaskJSONKey.DueDate.rawValue) if let enumDueDate = TaskDueDate(rawValue: dueDateString) { dueDate = enumDueDate } else { dueDate = TaskDueDate.OneDayBefore } let fromJSONNotes = fromJSON.safeString(TaskJSONKey.Notes.rawValue) if fromJSONNotes.lengthOfBytesUsingEncoding(NSUTF8StringEncoding) > 0 { notes = fromJSONNotes } done = fromJSON.safeBoolean(TaskJSONKey.Done.rawValue) taskID = fromJSON.safeInt(TaskJSONKey.TaskID.rawValue) if taskID == 0 { taskID = Task.nextIdentifier() } } static func tasksFromArrayOfJSONDictionaries(arrayOfDictionaries: [NSDictionary]) -> [Task] { var tasks = [Task]() for dict in arrayOfDictionaries { tasks.append(Task(fromJSON: dict)) } return tasks } //MARK: Identifier generation /** - returns: The next sequential identifier so all task identifiers are unique. */ private static func nextIdentifier() -> Int { let defaults = NSUserDefaults.standardUserDefaults() let lastIdentifier = defaults.integerForKey(UserDefaultKey.LastAddedTaskID.rawValue) let nextIdentifier = lastIdentifier + 1 defaults.setInteger(nextIdentifier, forKey:UserDefaultKey.LastAddedTaskID.rawValue) defaults.synchronize() return nextIdentifier } //MARK: JSON generation public func asJson() -> NSDictionary { var dict = [String: AnyObject]() dict.updateValue(taskID, forKey: TaskJSONKey.TaskID.rawValue) dict.updateValue(title, forKey: TaskJSONKey.Title.rawValue) if let notes = notes { dict.updateValue(notes, forKey: TaskJSONKey.Notes.rawValue) } dict.updateValue(dueDate.rawValue, forKey: TaskJSONKey.DueDate.rawValue) dict.updateValue(NSNumber(bool: done), forKey: TaskJSONKey.Done.rawValue) return dict as NSDictionary } }
mit
546653829a7c5dd3247445169babeb26
24.362205
95
0.690683
4.567376
false
false
false
false
assist-group/assist-mcommerce-sdk-ios
AssistMobileTest/AssistMobile/FiscalReceiptService.swift
1
2602
// // FiscalReceiptService.swift // AssistMobile // // Created by Timofey on 24/03/2020. // Copyright © 2020 Assist. All rights reserved. // import Foundation class FiscalReceiptRequest: SoapRequest { struct Names { static let Login = "login" static let Password = "password" static let Billnumber = "billnumber" static let MerchantId = "merchant_id" } init() { super.init(soapAction: "http://www.paysecure.ru/ws/fiscalreceipt") } var login: String? { get { return data[Names.Login] } set { data[Names.Login] = newValue } } var password: String? { get { return data[Names.Password] } set { data[Names.Password] = newValue } } var billnumber: String? { get { return data[Names.Billnumber] } set { data[Names.Billnumber] = newValue } } var merchantId: String? { get { return data[Names.MerchantId] } set { data[Names.MerchantId] = newValue } } override func buildRequestHeader() -> String { return "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ws=\"http://www.paysecure.ru/ws/\">\n<soapenv:Header/>\n<soapenv:Body>\n<ws:fiscalreceipt>\n<format>4</format>" } override func buildRequestTail() -> String { return "</ws:fiscalreceipt>\n</soapenv:Body>\n</soapenv:Envelope>" } } protocol FiscalReceiptServiceDelegate { func fiscalReceiptResult(_ url: String) func resultError(_ faultcode: String?, faultstring: String?) } class FiscalReceiptService: SoapService { let url = ".SOAP-ENV:Envelope.SOAP-ENV:Body.ASS-NS:result.fiscalreceipt.url" fileprivate var requestData: FiscalReceiptRequest fileprivate var delegate: FiscalReceiptServiceDelegate init(requestData: FiscalReceiptRequest, delegate: FiscalReceiptServiceDelegate) { self.requestData = requestData self.delegate = delegate } func start() { run(requestData) } override func getUrl() -> String { return AssistLinks.currentHost + AssistLinks.FiscalReceiptService } override func finish(_ values: [String : String]) { if let url = values[url] { delegate.fiscalReceiptResult(url) } else { delegate.resultError(values[faultcode], faultstring: values[faultstring]) } } }
apache-2.0
15f9a5b838ee5311e82e54cfe0827872
25.272727
211
0.596694
4.364094
false
false
false
false
mrdepth/Neocom
Legacy/Neocom/Neocom/InvTypeMarketOrdersPresenter.swift
2
3505
// // InvTypeMarketOrdersPresenter.swift // Neocom // // Created by Artem Shimanski on 9/26/18. // Copyright © 2018 Artem Shimanski. All rights reserved. // import Foundation import TreeController import Futures import CloudData class InvTypeMarketOrdersPresenter: TreePresenter { typealias View = InvTypeMarketOrdersViewController typealias Interactor = InvTypeMarketOrdersInteractor typealias Presentation = [Tree.Item.SimpleSection<Tree.Item.Row<Tree.Content.InvTypeMarketOrder>>] weak var view: View? lazy var interactor: Interactor! = Interactor(presenter: self) var content: Interactor.Content? var presentation: Presentation? var loading: Future<Presentation>? required init(view: View) { self.view = view } func configure() { view?.tableView.register([Prototype.TreeSectionCell.default, Prototype.InvTypeMarketOrderCell.default]) interactor.configure() applicationWillEnterForegroundObserver = NotificationCenter.default.addNotificationObserver(forName: UIApplication.willEnterForegroundNotification, object: nil, queue: .main) { [weak self] (note) in self?.applicationWillEnterForeground() } let region = Services.sde.viewContext.mapRegion(interactor.regionID) view?.title = region?.regionName ?? NSLocalizedString("Market Orders", comment: "") } private var applicationWillEnterForegroundObserver: NotificationObserver? func presentation(for content: Interactor.Content) -> Future<Presentation> { let progress = Progress(totalUnitCount: 2) return DispatchQueue.global(qos: .utility).async { [weak self] () -> Presentation in guard let strongSelf = self else { throw NCError.cancelled(type: type(of: self), function: #function) } var orders = content.value guard !orders.isEmpty else { throw NCError.noResults } let locationIDs = Set(orders.map{$0.locationID}) let locations = progress.performAsCurrent(withPendingUnitCount: 1) { try? strongSelf.interactor.locations(ids: locationIDs).get() } let i = orders.partition { $0.isBuyOrder } var sell = orders[..<i] var buy = orders[i...] buy.sort {return $0.price > $1.price} sell.sort {return $0.price < $1.price} let sellRows = sell.map { Tree.Item.Row(Tree.Content.InvTypeMarketOrder(prototype: Prototype.InvTypeMarketOrderCell.default, order: $0, location: locations?[$0.locationID]?.displayName)) } let buyRows = buy.map { Tree.Item.Row(Tree.Content.InvTypeMarketOrder(prototype: Prototype.InvTypeMarketOrderCell.default, order: $0, location: locations?[$0.locationID]?.displayName)) } progress.completedUnitCount += 1 return [Tree.Item.SimpleSection(title: NSLocalizedString("Sellers", comment: "").uppercased(), treeController: strongSelf.view?.treeController, children: sellRows), Tree.Item.SimpleSection(title: NSLocalizedString("Buyers", comment: "").uppercased(), treeController: strongSelf.view?.treeController, children: buyRows)] } } func onRegions(_ sender: Any) { guard let view = view else {return} Router.SDE.mapLocationPicker(MapLocationPicker.View.Input(mode: [.regions], completion: { [weak self] (controller, location) in if case let .region(region) = location { Services.settings.marketRegionID = Int(region.regionID) self?.view?.title = region.regionName ?? NSLocalizedString("Market Orders", comment: "") self?.reloadIfNeeded() } guard let view = self?.view else {return} controller.unwinder?.unwind(to: view) })).perform(from: view) } }
lgpl-2.1
385d4a6e3eb653e5e8b61850ea76c7e8
36.276596
200
0.742295
4.112676
false
false
false
false
ZhengShouDong/CloudPacker
Sources/CloudPacker/Libraries/CryptoSwift/SHA2.swift
1
14363
// // CryptoSwift // // Copyright (C) 2014-2017 Marcin Krzyżanowski <[email protected]> // This software is provided 'as-is', without any express or implied warranty. // // In no event will the authors be held liable for any damages arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: // // - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. // - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. // - This notice may not be removed or altered from any source or binary distribution. // // TODO: generic for process32/64 (UInt32/UInt64) // public final class SHA2: DigestType { let variant: Variant let size: Int let blockSize: Int let digestLength: Int private let k: Array<UInt64> fileprivate var accumulated = Array<UInt8>() fileprivate var processedBytesTotalCount: Int = 0 fileprivate var accumulatedHash32 = Array<UInt32>() fileprivate var accumulatedHash64 = Array<UInt64>() public enum Variant: RawRepresentable { case sha224, sha256, sha384, sha512 public var digestLength: Int { return rawValue / 8 } public var blockSize: Int { switch self { case .sha224, .sha256: return 64 case .sha384, .sha512: return 128 } } public typealias RawValue = Int public var rawValue: RawValue { switch self { case .sha224: return 224 case .sha256: return 256 case .sha384: return 384 case .sha512: return 512 } } public init?(rawValue: RawValue) { switch rawValue { case 224: self = .sha224 break case 256: self = .sha256 break case 384: self = .sha384 break case 512: self = .sha512 break default: return nil } } fileprivate var h: Array<UInt64> { switch self { case .sha224: return [0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4] case .sha256: return [0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19] case .sha384: return [0xcbbb9d5dc1059ed8, 0x629a292a367cd507, 0x9159015a3070dd17, 0x152fecd8f70e5939, 0x67332667ffc00b31, 0x8eb44a8768581511, 0xdb0c2e0d64f98fa7, 0x47b5481dbefa4fa4] case .sha512: return [0x6a09e667f3bcc908, 0xbb67ae8584caa73b, 0x3c6ef372fe94f82b, 0xa54ff53a5f1d36f1, 0x510e527fade682d1, 0x9b05688c2b3e6c1f, 0x1f83d9abfb41bd6b, 0x5be0cd19137e2179] } } fileprivate var finalLength: Int { switch self { case .sha224: return 7 case .sha384: return 6 default: return Int.max } } } public init(variant: SHA2.Variant) { self.variant = variant switch self.variant { case .sha224, .sha256: accumulatedHash32 = variant.h.map { UInt32($0) } // FIXME: UInt64 for process64 blockSize = variant.blockSize size = variant.rawValue digestLength = variant.digestLength k = [ 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2, ] case .sha384, .sha512: accumulatedHash64 = variant.h blockSize = variant.blockSize size = variant.rawValue digestLength = variant.digestLength k = [ 0x428a2f98d728ae22, 0x7137449123ef65cd, 0xb5c0fbcfec4d3b2f, 0xe9b5dba58189dbbc, 0x3956c25bf348b538, 0x59f111f1b605d019, 0x923f82a4af194f9b, 0xab1c5ed5da6d8118, 0xd807aa98a3030242, 0x12835b0145706fbe, 0x243185be4ee4b28c, 0x550c7dc3d5ffb4e2, 0x72be5d74f27b896f, 0x80deb1fe3b1696b1, 0x9bdc06a725c71235, 0xc19bf174cf692694, 0xe49b69c19ef14ad2, 0xefbe4786384f25e3, 0x0fc19dc68b8cd5b5, 0x240ca1cc77ac9c65, 0x2de92c6f592b0275, 0x4a7484aa6ea6e483, 0x5cb0a9dcbd41fbd4, 0x76f988da831153b5, 0x983e5152ee66dfab, 0xa831c66d2db43210, 0xb00327c898fb213f, 0xbf597fc7beef0ee4, 0xc6e00bf33da88fc2, 0xd5a79147930aa725, 0x06ca6351e003826f, 0x142929670a0e6e70, 0x27b70a8546d22ffc, 0x2e1b21385c26c926, 0x4d2c6dfc5ac42aed, 0x53380d139d95b3df, 0x650a73548baf63de, 0x766a0abb3c77b2a8, 0x81c2c92e47edaee6, 0x92722c851482353b, 0xa2bfe8a14cf10364, 0xa81a664bbc423001, 0xc24b8b70d0f89791, 0xc76c51a30654be30, 0xd192e819d6ef5218, 0xd69906245565a910, 0xf40e35855771202a, 0x106aa07032bbd1b8, 0x19a4c116b8d2d0c8, 0x1e376c085141ab53, 0x2748774cdf8eeb99, 0x34b0bcb5e19b48a8, 0x391c0cb3c5c95a63, 0x4ed8aa4ae3418acb, 0x5b9cca4f7763e373, 0x682e6ff3d6b2b8a3, 0x748f82ee5defb2fc, 0x78a5636f43172f60, 0x84c87814a1f0ab72, 0x8cc702081a6439ec, 0x90befffa23631e28, 0xa4506cebde82bde9, 0xbef9a3f7b2c67915, 0xc67178f2e372532b, 0xca273eceea26619c, 0xd186b8c721c0c207, 0xeada7dd6cde0eb1e, 0xf57d4f7fee6ed178, 0x06f067aa72176fba, 0x0a637dc5a2c898a6, 0x113f9804bef90dae, 0x1b710b35131c471b, 0x28db77f523047d84, 0x32caab7b40c72493, 0x3c9ebe0a15c9bebc, 0x431d67c49c100d4c, 0x4cc5d4becb3e42b6, 0x597f299cfc657e2a, 0x5fcb6fab3ad6faec, 0x6c44198c4a475817, ] } } public func calculate(for bytes: Array<UInt8>) -> Array<UInt8> { do { return try update(withBytes: bytes.slice, isLast: true) } catch { return [] } } fileprivate func process64(block chunk: ArraySlice<UInt8>, currentHash hh: inout Array<UInt64>) { // break chunk into sixteen 64-bit words M[j], 0 ≤ j ≤ 15, big-endian // Extend the sixteen 64-bit words into eighty 64-bit words: let M = UnsafeMutablePointer<UInt64>.allocate(capacity: k.count) M.initialize(to: 0, count: k.count) defer { M.deinitialize(count: self.k.count) M.deallocate(capacity: self.k.count) } for x in 0..<k.count { switch x { case 0...15: let start = chunk.startIndex.advanced(by: x * 8) // * MemoryLayout<UInt64>.size M[x] = UInt64(bytes: chunk, fromIndex: start) break default: let s0 = rotateRight(M[x - 15], by: 1) ^ rotateRight(M[x - 15], by: 8) ^ (M[x - 15] >> 7) let s1 = rotateRight(M[x - 2], by: 19) ^ rotateRight(M[x - 2], by: 61) ^ (M[x - 2] >> 6) M[x] = M[x - 16] &+ s0 &+ M[x - 7] &+ s1 break } } var A = hh[0] var B = hh[1] var C = hh[2] var D = hh[3] var E = hh[4] var F = hh[5] var G = hh[6] var H = hh[7] // Main loop for j in 0..<k.count { let s0 = rotateRight(A, by: 28) ^ rotateRight(A, by: 34) ^ rotateRight(A, by: 39) let maj = (A & B) ^ (A & C) ^ (B & C) let t2 = s0 &+ maj let s1 = rotateRight(E, by: 14) ^ rotateRight(E, by: 18) ^ rotateRight(E, by: 41) let ch = (E & F) ^ ((~E) & G) let t1 = H &+ s1 &+ ch &+ k[j] &+ UInt64(M[j]) H = G G = F F = E E = D &+ t1 D = C C = B B = A A = t1 &+ t2 } hh[0] = (hh[0] &+ A) hh[1] = (hh[1] &+ B) hh[2] = (hh[2] &+ C) hh[3] = (hh[3] &+ D) hh[4] = (hh[4] &+ E) hh[5] = (hh[5] &+ F) hh[6] = (hh[6] &+ G) hh[7] = (hh[7] &+ H) } // mutating currentHash in place is way faster than returning new result fileprivate func process32(block chunk: ArraySlice<UInt8>, currentHash hh: inout Array<UInt32>) { // break chunk into sixteen 32-bit words M[j], 0 ≤ j ≤ 15, big-endian // Extend the sixteen 32-bit words into sixty-four 32-bit words: let M = UnsafeMutablePointer<UInt32>.allocate(capacity: k.count) M.initialize(to: 0, count: k.count) defer { M.deinitialize(count: self.k.count) M.deallocate(capacity: self.k.count) } for x in 0..<k.count { switch x { case 0...15: let start = chunk.startIndex.advanced(by: x * 4) // * MemoryLayout<UInt32>.size M[x] = UInt32(bytes: chunk, fromIndex: start) break default: let s0 = rotateRight(M[x - 15], by: 7) ^ rotateRight(M[x - 15], by: 18) ^ (M[x - 15] >> 3) let s1 = rotateRight(M[x - 2], by: 17) ^ rotateRight(M[x - 2], by: 19) ^ (M[x - 2] >> 10) M[x] = M[x - 16] &+ s0 &+ M[x - 7] &+ s1 break } } var A = hh[0] var B = hh[1] var C = hh[2] var D = hh[3] var E = hh[4] var F = hh[5] var G = hh[6] var H = hh[7] // Main loop for j in 0..<k.count { let s0 = rotateRight(A, by: 2) ^ rotateRight(A, by: 13) ^ rotateRight(A, by: 22) let maj = (A & B) ^ (A & C) ^ (B & C) let t2 = s0 &+ maj let s1 = rotateRight(E, by: 6) ^ rotateRight(E, by: 11) ^ rotateRight(E, by: 25) let ch = (E & F) ^ ((~E) & G) let t1 = H &+ s1 &+ ch &+ UInt32(k[j]) &+ M[j] H = G G = F F = E E = D &+ t1 D = C C = B B = A A = t1 &+ t2 } hh[0] = hh[0] &+ A hh[1] = hh[1] &+ B hh[2] = hh[2] &+ C hh[3] = hh[3] &+ D hh[4] = hh[4] &+ E hh[5] = hh[5] &+ F hh[6] = hh[6] &+ G hh[7] = hh[7] &+ H } } extension SHA2: Updatable { public func update(withBytes bytes: ArraySlice<UInt8>, isLast: Bool = false) throws -> Array<UInt8> { accumulated += bytes if isLast { let lengthInBits = (processedBytesTotalCount + accumulated.count) * 8 let lengthBytes = lengthInBits.bytes(totalBytes: blockSize / 8) // A 64-bit/128-bit representation of b. blockSize fit by accident. // Step 1. Append padding bitPadding(to: &accumulated, blockSize: blockSize, allowance: blockSize / 8) // Step 2. Append Length a 64-bit representation of lengthInBits accumulated += lengthBytes } var processedBytes = 0 for chunk in accumulated.batched(by: blockSize) { if isLast || (accumulated.count - processedBytes) >= blockSize { switch variant { case .sha224, .sha256: process32(block: chunk, currentHash: &accumulatedHash32) case .sha384, .sha512: process64(block: chunk, currentHash: &accumulatedHash64) } processedBytes += chunk.count } } accumulated.removeFirst(processedBytes) processedBytesTotalCount += processedBytes // output current hash var result = Array<UInt8>(repeating: 0, count: variant.digestLength) switch variant { case .sha224, .sha256: var pos = 0 for idx in 0..<accumulatedHash32.count where idx < variant.finalLength { let h = accumulatedHash32[idx].bigEndian result[pos] = UInt8(h & 0xff) result[pos + 1] = UInt8((h >> 8) & 0xff) result[pos + 2] = UInt8((h >> 16) & 0xff) result[pos + 3] = UInt8((h >> 24) & 0xff) pos += 4 } case .sha384, .sha512: var pos = 0 for idx in 0..<accumulatedHash64.count where idx < variant.finalLength { let h = accumulatedHash64[idx].bigEndian result[pos] = UInt8(h & 0xff) result[pos + 1] = UInt8((h >> 8) & 0xff) result[pos + 2] = UInt8((h >> 16) & 0xff) result[pos + 3] = UInt8((h >> 24) & 0xff) result[pos + 4] = UInt8((h >> 32) & 0xff) result[pos + 5] = UInt8((h >> 40) & 0xff) result[pos + 6] = UInt8((h >> 48) & 0xff) result[pos + 7] = UInt8((h >> 56) & 0xff) pos += 8 } } // reset hash value for instance if isLast { switch variant { case .sha224, .sha256: accumulatedHash32 = variant.h.lazy.map { UInt32($0) } // FIXME: UInt64 for process64 case .sha384, .sha512: accumulatedHash64 = variant.h } } return result } }
apache-2.0
ee06873ac5c47a924eb25db3c6093ade
39.548023
217
0.552041
3.160978
false
false
false
false
naoto0822/try-reactive-swift
TryRxSwift/TryRxSwift/AllItemRequest.swift
1
1499
// // AllItemRequest.swift // TryRxSwift // // Created by naoto yamaguchi on 2016/04/11. // Copyright © 2016年 naoto yamaguchi. All rights reserved. // import UIKit import RxSwift import Alamofire extension API { public class AllItemRequest { // MARK: - Property var page: Int = 1 let disposeBag = DisposeBag() // MARK: - LifeCycle init() { // NOOP } // MARK: - Public public func send() -> Observable<[Item]> { return Observable.create{ (observer) in let router = API.Router.AllItem(page: "\(self.page)") API.manager.request(router).responseJSON(completionHandler: { response in switch response.result { case .Success(let value): // TODO: ObjectMapper guard let value = value as? [[String: AnyObject]] else { return observer.on(.Completed) } let items = value.flatMap{ Item(dictionary: $0) } observer.on(.Next(items)) observer.on(.Completed) case .Failure(let error): observer.onError(error) } }) return AnonymousDisposable { // TODO } } } } }
mit
5cf52544035067881c2b2c557966dfee
27.769231
89
0.453877
5.42029
false
false
false
false
honishi/Hakumai
Hakumai/Managers/SpeechManager/AudioCacher.swift
1
2285
// // AudioCacher.swift // Hakumai // // Created by Hiroyuki Onishi on 2022/02/11. // Copyright © 2022 Hiroyuki Onishi. All rights reserved. // import Foundation protocol AudioCacherType { func get(speedScale: Float, volumeScale: Float, speaker: Int, text: String) -> Data? func set(speedScale: Float, volumeScale: Float, speaker: Int, text: String, data: Data) } private let cacheCountLimit = 100 final class AudioCacher: NSObject, AudioCacherType { static let shared = AudioCacher() private let cache = NSCache<NSString, AudioData>() override init() { super.init() cache.delegate = self cache.countLimit = cacheCountLimit } deinit { log.debug("") } func get(speedScale: Float, volumeScale: Float, speaker: Int, text: String) -> Data? { let key = cacheKey(speedScale, volumeScale, speaker, text) return cache.object(forKey: key)?.data } func set(speedScale: Float, volumeScale: Float, speaker: Int, text: String, data: Data) { let key = cacheKey(speedScale, volumeScale, speaker, text) let object = AudioData( speedScale: speedScale, volumeScale: volumeScale, speaker: speaker, text: text, data: data) cache.setObject(object, forKey: key) } } extension AudioCacher: NSCacheDelegate { func cache(_ cache: NSCache<AnyObject, AnyObject>, willEvictObject obj: Any) { log.debug("Audio cache evicted: \(obj)") } } private extension AudioCacher { func cacheKey(_ speedScale: Float, _ volumeScale: Float, _ speaker: Int, _ text: String) -> NSString { return "\(speedScale):\(volumeScale):\(speaker):\(text.hashValue)" as NSString } } private class AudioData: CustomStringConvertible { let speedScale: Float let volumeScale: Float let speaker: Int let text: String let data: Data var description: String { "\(speedScale)/\(volumeScale)/\(speaker)/\(text)/\(data)"} init(speedScale: Float, volumeScale: Float, speaker: Int, text: String, data: Data) { self.speedScale = speedScale self.volumeScale = volumeScale self.speaker = speaker self.text = text self.data = data } deinit { log.debug("") } }
mit
098c0dcd9d7886722ab7f42036eea215
28.282051
106
0.646235
4.333966
false
false
false
false
xmanbest/LJHWeiBo
LJHWeiBo/LJHWeiBo/AppDelegate.swift
1
2531
// // AppDelegate.swift // LJHWeiBo // // Created by 李建華 on 16/5/29. // Copyright © 2016年 lijianhua. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { setupBarAppearence() window = UIWindow(frame: UIScreen.mainScreen().bounds) window?.backgroundColor = UIColor.whiteColor() window?.rootViewController = JHMainTabBarController(); window?.makeKeyAndVisible() return true } private func setupBarAppearence() { UINavigationBar.appearance().tintColor = UIColor.orangeColor() UITabBar.appearance().tintColor = UIColor.orangeColor() } 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
8aed6a583667214930faf9189513221f
42.482759
285
0.733545
5.555066
false
false
false
false
xwu/swift
test/Concurrency/Runtime/basic_future.swift
1
2391
// RUN: %target-run-simple-swift( -Xfrontend -disable-availability-checking %import-libdispatch -parse-as-library) // REQUIRES: executable_test // REQUIRES: concurrency // REQUIRES: libdispatch // rdar://76038845 // REQUIRES: concurrency_runtime // UNSUPPORTED: back_deployment_runtime import Dispatch enum HomeworkError: Error, Equatable { case dogAteIt(String) } @available(SwiftStdlib 5.5, *) func formGreeting(name: String) async -> String { return "Hello \(name) from async world" } @available(SwiftStdlib 5.5, *) func testSimple( name: String, dogName: String, shouldThrow: Bool, doSuspend: Bool ) async { print("Testing name: \(name), dog: \(dogName), shouldThrow: \(shouldThrow) doSuspend: \(doSuspend)") var completed = false let taskHandle: Task.Handle<String, Error> = detach { let greeting = await formGreeting(name: name) // If the intent is to test suspending, wait a bit so the second task // can complete. if doSuspend { print("- Future sleeping") await Task.sleep(1_000_000_000) } if (shouldThrow) { print("- Future throwing") throw HomeworkError.dogAteIt(dogName + " the dog") } print("- Future returning normally") return greeting + "!" } // If the intent is not to test suspending, wait a bit so the first task // can complete. if !doSuspend { print("+ Reader sleeping") await Task.sleep(1_000_000_000) } do { print("+ Reader waiting for the result") let result = try await taskHandle.get() completed = true print("+ Normal return: \(result)") assert(result == "Hello \(name) from async world!") } catch HomeworkError.dogAteIt(let badDog) { completed = true print("+ Error return: HomeworkError.dogAteIt(\(badDog))") assert(badDog == dogName + " the dog") } catch { fatalError("Caught a different exception?") } assert(completed) print("Finished test") } @available(SwiftStdlib 5.5, *) @main struct Main { static func main() async { await testSimple(name: "Ted", dogName: "Hazel", shouldThrow: false, doSuspend: false) await testSimple(name: "Ted", dogName: "Hazel", shouldThrow: true, doSuspend: false) await testSimple(name: "Ted", dogName: "Hazel", shouldThrow: false, doSuspend: true) await testSimple(name: "Ted", dogName: "Hazel", shouldThrow: true, doSuspend: true) print("Done") } }
apache-2.0
4e625ab061e27c85d2844a3707856b72
27.129412
115
0.674195
3.919672
false
true
false
false
joerocca/GitHawk
Classes/Repository/Empty/RepositoryEmptyResultsSectionController.swift
1
1397
// // RepositoryEmptyResultsSectionController.swift // Freetime // // Created by Sherlock, James on 01/08/2017. // Copyright © 2017 Ryan Nystrom. All rights reserved. // import IGListKit final class RepositoryEmptyResultsSectionController: ListSectionController { let topInset: CGFloat let topLayoutGuide: UILayoutSupport let bottomLayoutGuide: UILayoutSupport let type: RepositoryEmptyResultsType init(topInset: CGFloat, topLayoutGuide: UILayoutSupport, bottomLayoutGuide: UILayoutSupport, type: RepositoryEmptyResultsType) { self.topInset = topInset self.topLayoutGuide = topLayoutGuide self.bottomLayoutGuide = bottomLayoutGuide self.type = type super.init() } override func sizeForItem(at index: Int) -> CGSize { guard let size = collectionContext?.containerSize else { fatalError("Missing context") } return CGSize(width: size.width, height: size.height - topInset - topLayoutGuide.length - bottomLayoutGuide.length) } override func cellForItem(at index: Int) -> UICollectionViewCell { guard let cell = collectionContext?.dequeueReusableCell(of: RepositoryEmptyResultsCell.self, for: self, at: index) as? RepositoryEmptyResultsCell else { fatalError("Missing context, object, or cell is wrong type") } cell.configure(type) return cell } }
mit
1b6607d162fcc70bc5e01c76a61ed82b
33.9
160
0.719198
5.267925
false
false
false
false
xoyip/AzureStorageApiClient
Pod/Classes/AzureStorage/Blob/Request/GetBlobRequest.swift
1
1189
// // GetBlobRequest.swift // Pods // // Created by Hiromasa Ohno on 8/14/15. // // import Foundation public extension AzureBlob { public class GetBlobRequest: Request { public let method = "GET" let container : String let name : String let mimetype : String public typealias Response = NSData public init(container: String, name: String, mimetype: String) { self.container = container self.name = name.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)! self.mimetype = mimetype } public func path() -> String { return "/\(container)/\(name)" } public func body() -> NSData? { return nil } public func additionalHeaders() -> [String : String] { return ["If-Modified-Since":"", "If-None-Match": ""] } public func convertResponseObject(object: AnyObject?) -> Response? { return object as? NSData } public func responseTypes() -> Set<String>? { return [mimetype] } } }
mit
83ba3d3dabb1b207bb4c1fa858e870be
24.297872
93
0.539108
5.059574
false
false
false
false
hikelee/cinema
Sources/App/Controllers/AdsController.swift
1
2084
import Vapor import HTTP import Foundation class AdsAdminController : ChannelBasedController<Ads> { typealias Model = Ads override var path:String {return "/admin/cinema/ads"} override func additonalFormData(_ request: Request) throws ->[String:Node]{ return try [ "types": Model.types.allNode(), "states": Model.states.allNode(), "parents":Channel.allNode() ] } } class AdsApiController: Controller { let path = "/api/cinema/ads" override func makeRouter(){ routerGroup.group(path){group in group.get("/"){ return try self.doAds($0) } } } func doAds(_ request: Request) throws -> JSON { guard let identification = request.data["id"]?.string?.uppercased() else{ return try JSON(node:["status":1, "message":"no id"]) } guard let projector = try Projector.load("identification",identification) else { return try JSON(node:["status":1, "message":"no projector"]) } guard let server = try projector.server() else{ return try JSON(node:["status":1, "message":"no server"]) } let time = Date().string() let adsArray = try Ads.query() .filter("channel_id",.equals,projector.channelId!) .filter("state",.equals, 1) .filter("start_time",.lessThan,time) .filter("end_time",.greaterThan,time) .sort("id",.descending).all().map{ node in try JSON( node:[ "type":node.type, "title":node.title, "url": node.mediaUrl!.hasPrefix("http://") ? node.mediaUrl!:"http://\(server.ipAddress)(node.mediaUrl!)", "duration":node.duration ]) } if adsArray.isEmpty { return try JSON(node:["status":1, "message":"no ads"]) } return try JSON( node:[ "status":0, "list":adsArray.makeNode() ]) } }
mit
028b1540d8cfc28202ce7d58d92a6311
33.163934
88
0.534069
4.415254
false
false
false
false
gdimaggio/SwiftlyRater
SwiftlyRater/SRDefaults.swift
1
3047
// // SRDefaults.swift // SwiftlyRaterSample // // Created by Gianluca Di Maggio on 1/5/17. // Copyright © 2017 dima. All rights reserved. // import Foundation // MARK: - Int User Defaults protocol IntUserDefaultable { associatedtype StateDefaultKey: RawRepresentable } extension IntUserDefaultable where StateDefaultKey.RawValue == String { static func set(_ value: Int, forKey key: StateDefaultKey) { let key = key.rawValue UserDefaults.standard.set(value, forKey: key) } static func int(forKey key: StateDefaultKey) -> Int { let key = key.rawValue return UserDefaults.standard.integer(forKey: key) } } // MARK: - Bool User Defaults protocol BoolUserDefaultable { associatedtype StateDefaultKey: RawRepresentable } extension BoolUserDefaultable where StateDefaultKey.RawValue == String { static func set(_ value: Bool, forKey key: StateDefaultKey) { let key = key.rawValue UserDefaults.standard.set(value, forKey: key) } static func bool(forKey key: StateDefaultKey) -> Bool { let key = key.rawValue return UserDefaults.standard.bool(forKey: key) } } // MARK: - Object User Defaults protocol ObjectUserDefaultable { associatedtype StateDefaultKey: RawRepresentable } extension ObjectUserDefaultable where StateDefaultKey.RawValue == String { static func set(_ value: Any?, forKey key: StateDefaultKey) { let key = key.rawValue UserDefaults.standard.set(value, forKey: key) } } // MARK: - String User Defaults protocol StringUserDefaultable { associatedtype StateDefaultKey: RawRepresentable } extension StringUserDefaultable where StateDefaultKey.RawValue == String { static func set(_ value: String, forKey key: StateDefaultKey) { let key = key.rawValue UserDefaults.standard.set(value, forKey: key) } static func string(forKey key: StateDefaultKey) -> String? { let key = key.rawValue return UserDefaults.standard.string(forKey: key) } } // MARK: - Date User Defaults protocol DateUserDefaultable { associatedtype StateDefaultKey: RawRepresentable } extension DateUserDefaultable where StateDefaultKey.RawValue == String { static func date(forKey key: StateDefaultKey) -> Date? { let key = key.rawValue guard let dateTimestamp = UserDefaults.standard.object(forKey: key) as? Double else { return nil } return Date(timeIntervalSince1970: dateTimestamp) } } extension UserDefaults { struct SRDefaults: IntUserDefaultable, BoolUserDefaultable, ObjectUserDefaultable, StringUserDefaultable, DateUserDefaultable { enum StateDefaultKey: String { case firstUse case lastReminded case usesCount case eventsCount case declinedToRate case versionRated case lastVersionUsed } static func synchronize() { UserDefaults.standard.synchronize() } } }
mit
a892a6650edc7a9e87175418c24eff8a
25.258621
131
0.687787
4.8736
false
false
false
false
algolia/algoliasearch-client-swift
Tests/AlgoliaSearchClientTests/Doc/APIParameters/APIParameters+Performance.swift
1
1191
// // APIParameters+Performance.swift // // // Created by Vladislav Fitc on 07/07/2020. // import Foundation import AlgoliaSearchClient extension APIParameters { //MARK: - Performance func performance() { func numericAttributesForFiltering() { /* numericAttributesForFiltering = [ "attribute1", .#{equalOnly}("attribute2") ] */ func set_numeric_attributes_for_filtering() { let settings = Settings() .set(\.numericAttributesForFiltering, to: ["quantity", "popularity"]) index.setSettings(settings) { result in if case .success(let response) = result { print("Response: \(response)") } } } } func allowCompressionOfIntegerArray() { /* allowCompressionOfIntegerArray = true|false */ func enable_compression_of_integer_array() { let settings = Settings() .set(\.allowCompressionOfIntegerArray, to: true) index.setSettings(settings) { result in if case .success(let response) = result { print("Response: \(response)") } } } } } }
mit
8690e3907f157ae5a646aa84d7c1a6b0
23.8125
79
0.574307
4.563218
false
false
false
false
stephentyrone/swift
test/SPI/spi_client.swift
5
2396
/// Check an SPI import of an SPI library to detect correct SPI access // RUN: %empty-directory(%t) // /// Compile the SPI lib // RUN: %target-swift-frontend -emit-module %S/Inputs/spi_helper.swift -module-name SPIHelper -emit-module-path %t/SPIHelper.swiftmodule -emit-module-interface-path %t/SPIHelper.swiftinterface -emit-private-module-interface-path %t/SPIHelper.private.swiftinterface -enable-library-evolution -swift-version 5 -parse-as-library /// Reading from swiftmodule // RUN: %target-typecheck-verify-swift -I %t -verify-ignore-unknown /// Reading from .private.swiftinterface // RUN: rm %t/SPIHelper.swiftmodule // RUN: %target-typecheck-verify-swift -I %t -verify-ignore-unknown //// Reading from .swiftinterface should fail as it won't find the decls // RUN: rm %t/SPIHelper.private.swiftinterface // RUN: not %target-swift-frontend -typecheck -I %t @_spi(HelperSPI) import SPIHelper // Use as SPI publicFunc() spiFunc() internalFunc() // expected-error {{cannot find 'internalFunc' in scope}} let c = SPIClass() c.spiMethod() c.spiVar = "write" print(c.spiVar) let s = SPIStruct() s.spiMethod() s.spiInherit() s.spiDontInherit() // expected-error {{'spiDontInherit' is inaccessible due to '@_spi' protection level}} s.spiExtensionHidden() s.spiExtension() s.spiExtensionInherited() s.spiVar = "write" print(s.spiVar) SPIEnum().spiMethod() SPIEnum.A.spiMethod() var ps = PublicStruct() let _ = PublicStruct(alt_init: 1) ps.spiMethod() ps.spiVar = "write" print(ps.spiVar) otherApiFunc() // expected-error {{cannot find 'otherApiFunc' in scope}} public func publicUseOfSPI(param: SPIClass) -> SPIClass {} // expected-error 2{{cannot use class 'SPIClass' here; it is an SPI imported from 'SPIHelper'}} public func publicUseOfSPI2() -> [SPIClass] {} // expected-error {{cannot use class 'SPIClass' here; it is an SPI imported from 'SPIHelper'}} @inlinable func inlinable() -> SPIClass { // expected-error {{class 'SPIClass' is '@_spi' and cannot be referenced from an '@inlinable' function}} spiFunc() // expected-error {{global function 'spiFunc()' is '@_spi' and cannot be referenced from an '@inlinable' function}} _ = SPIClass() // expected-error {{class 'SPIClass' is '@_spi' and cannot be referenced from an '@inlinable' function}} _ = [SPIClass]() // expected-error {{class 'SPIClass' is '@_spi' and cannot be referenced from an '@inlinable' function}} }
apache-2.0
e28787bdeaa3276f24e10e339032a79f
38.933333
325
0.72788
3.603008
false
false
false
false
zybug/firefox-ios
Client/Application/AppDelegate.swift
4
12317
/* 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 Shared import Storage import AVFoundation import XCGLogger import Breakpad private let log = Logger.browserLogger class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? var browserViewController: BrowserViewController! var rootViewController: UINavigationController! weak var profile: BrowserProfile? var tabManager: TabManager! let appVersion = NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleShortVersionString") as! String func application(application: UIApplication, willFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Set the Firefox UA for browsing. setUserAgent() // Start the keyboard helper to monitor and cache keyboard state. KeyboardHelper.defaultHelper.startObserving() // Create a new sync log file on cold app launch Logger.syncLogger.newLogWithDate(NSDate()) let profile = getProfile(application) // Set up a web server that serves us static content. Do this early so that it is ready when the UI is presented. setUpWebServer(profile) do { // for aural progress bar: play even with silent switch on, and do not stop audio from other apps (like music) try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, withOptions: AVAudioSessionCategoryOptions.MixWithOthers) } catch _ { log.error("Failed to assign AVAudioSession category to allow playing with silent switch on for aural progress bar") } self.window = UIWindow(frame: UIScreen.mainScreen().bounds) self.window!.backgroundColor = UIColor.whiteColor() let defaultRequest = NSURLRequest(URL: UIConstants.DefaultHomePage) self.tabManager = TabManager(defaultNewTabRequest: defaultRequest, profile: profile) browserViewController = BrowserViewController(profile: profile, tabManager: self.tabManager) // Add restoration class, the factory that will return the ViewController we // will restore with. browserViewController.restorationIdentifier = NSStringFromClass(BrowserViewController.self) browserViewController.restorationClass = AppDelegate.self browserViewController.automaticallyAdjustsScrollViewInsets = false rootViewController = UINavigationController(rootViewController: browserViewController) rootViewController.automaticallyAdjustsScrollViewInsets = false rootViewController.delegate = self rootViewController.navigationBarHidden = true self.window!.rootViewController = rootViewController self.window!.backgroundColor = UIConstants.AppBackgroundColor activeCrashReporter = BreakpadCrashReporter(breakpadInstance: BreakpadController.sharedInstance()) configureActiveCrashReporter(profile.prefs.boolForKey("crashreports.send.always")) NSNotificationCenter.defaultCenter().addObserverForName(FSReadingListAddReadingListItemNotification, object: nil, queue: nil) { (notification) -> Void in if let userInfo = notification.userInfo, url = userInfo["URL"] as? NSURL { let title = (userInfo["Title"] as? String) ?? "" profile.readingList?.createRecordWithURL(url.absoluteString, title: title, addedBy: UIDevice.currentDevice().name) } } // check to see if we started 'cos someone tapped on a notification. if let localNotification = launchOptions?[UIApplicationLaunchOptionsLocalNotificationKey] as? UILocalNotification { viewURLInNewTab(localNotification) } return true } /** * We maintain a weak reference to the profile so that we can pause timed * syncs when we're backgrounded. * * The long-lasting ref to the profile lives in BrowserViewController, * which we set in application:willFinishLaunchingWithOptions:. * * If that ever disappears, we won't be able to grab the profile to stop * syncing... but in that case the profile's deinit will take care of things. */ func getProfile(application: UIApplication) -> Profile { if let profile = self.profile { return profile } let p = BrowserProfile(localName: "profile", app: application) self.profile = p return p } func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]?) -> Bool { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0)) { AdjustIntegration.sharedInstance.triggerApplicationDidFinishLaunchingWithOptions(launchOptions) } self.window!.makeKeyAndVisible() return true } func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject) -> Bool { if let components = NSURLComponents(URL: url, resolvingAgainstBaseURL: false) { if components.scheme != "firefox" && components.scheme != "firefox-x-callback" { return false } var url: String? for item in (components.queryItems ?? []) as [NSURLQueryItem] { switch item.name { case "url": url = item.value default: () } } if let url = url, newURL = NSURL(string: url.unescape()) { self.browserViewController.openURLInNewTab(newURL) return true } } return false } // We sync in the foreground only, to avoid the possibility of runaway resource usage. // Eventually we'll sync in response to notifications. func applicationDidBecomeActive(application: UIApplication) { self.profile?.syncManager.applicationDidBecomeActive() // We could load these here, but then we have to futz with the tab counter // and making NSURLRequests. self.browserViewController.loadQueuedTabs() } func applicationDidEnterBackground(application: UIApplication) { self.profile?.syncManager.applicationDidEnterBackground() var taskId: UIBackgroundTaskIdentifier = 0 taskId = application.beginBackgroundTaskWithExpirationHandler { _ in log.warning("Running out of background time, but we have a profile shutdown pending.") application.endBackgroundTask(taskId) } dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0)) { self.profile?.shutdown() application.endBackgroundTask(taskId) } } private func setUpWebServer(profile: Profile) { let server = WebServer.sharedInstance ReaderModeHandlers.register(server, profile: profile) ErrorPageHelper.register(server) AboutHomeHandler.register(server) AboutLicenseHandler.register(server) SessionRestoreHandler.register(server) server.start() } private func setUserAgent() { // Note that we use defaults here that are readable from extensions, so they // can just used the cached identifier. let defaults = NSUserDefaults(suiteName: AppInfo.sharedContainerIdentifier())! let firefoxUA = UserAgent.defaultUserAgent(defaults) // Set the UA for WKWebView (via defaults), the favicon fetcher, and the image loader. // This only needs to be done once per runtime. defaults.registerDefaults(["UserAgent": firefoxUA]) FaviconFetcher.userAgent = firefoxUA SDWebImageDownloader.sharedDownloader().setValue(firefoxUA, forHTTPHeaderField: "User-Agent") // Record the user agent for use by search suggestion clients. SearchViewController.userAgent = firefoxUA } func application(application: UIApplication, handleActionWithIdentifier identifier: String?, forLocalNotification notification: UILocalNotification, completionHandler: () -> Void) { if let actionId = identifier { if let action = SentTabAction(rawValue: actionId) { viewURLInNewTab(notification) switch(action) { case .Bookmark: addBookmark(notification) break case .ReadingList: addToReadingList(notification) break default: break } } else { print("ERROR: Unknown notification action received") } } else { print("ERROR: Unknown notification received") } } func application(application: UIApplication, didReceiveLocalNotification notification: UILocalNotification) { viewURLInNewTab(notification) } private func viewURLInNewTab(notification: UILocalNotification) { if let alertURL = notification.userInfo?[TabSendURLKey] as? String { if let urlToOpen = NSURL(string: alertURL) { browserViewController.openURLInNewTab(urlToOpen) } } } private func addBookmark(notification: UILocalNotification) { if let alertURL = notification.userInfo?[TabSendURLKey] as? String, let title = notification.userInfo?[TabSendTitleKey] as? String { browserViewController.addBookmark(alertURL, title: title) } } private func addToReadingList(notification: UILocalNotification) { if let alertURL = notification.userInfo?[TabSendURLKey] as? String, let title = notification.userInfo?[TabSendTitleKey] as? String { if let urlToOpen = NSURL(string: alertURL) { NSNotificationCenter.defaultCenter().postNotificationName(FSReadingListAddReadingListItemNotification, object: self, userInfo: ["URL": urlToOpen, "Title": title]) } } } } // MARK: - Root View Controller Animations extension AppDelegate: UINavigationControllerDelegate { func navigationController(navigationController: UINavigationController, animationControllerForOperation operation: UINavigationControllerOperation, fromViewController fromVC: UIViewController, toViewController toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? { if operation == UINavigationControllerOperation.Push { return BrowserToTrayAnimator() } else if operation == UINavigationControllerOperation.Pop { return TrayToBrowserAnimator() } else { return nil } } } var activeCrashReporter: CrashReporter? func configureActiveCrashReporter(optedIn: Bool?) { if let reporter = activeCrashReporter { configureCrashReporter(reporter, optedIn: optedIn) } } public func configureCrashReporter(reporter: CrashReporter, optedIn: Bool?) { let configureReporter: () -> () = { let addUploadParameterForKey: String -> Void = { key in if let value = NSBundle.mainBundle().objectForInfoDictionaryKey(key) as? String { reporter.addUploadParameter(value, forKey: key) } } addUploadParameterForKey("AppID") addUploadParameterForKey("BuildID") addUploadParameterForKey("ReleaseChannel") addUploadParameterForKey("Vendor") } if let optedIn = optedIn { // User has explicitly opted-in for sending crash reports. If this is not true, then the user has // explicitly opted-out of crash reporting so don't bother starting breakpad or stop if it was running if optedIn { reporter.start(true) configureReporter() reporter.setUploadingEnabled(true) } else { reporter.stop() } } // We haven't asked the user for their crash reporting preference yet. Log crashes anyways but don't send them. else { reporter.start(true) configureReporter() } }
mpl-2.0
4ee2857cdf276ab843d30cfd519602bd
41.916376
185
0.673703
5.851306
false
false
false
false