repo_name
stringlengths
6
91
ref
stringlengths
12
59
path
stringlengths
7
936
license
stringclasses
15 values
copies
stringlengths
1
3
content
stringlengths
61
714k
hash
stringlengths
32
32
line_mean
float64
4.88
60.8
line_max
int64
12
421
alpha_frac
float64
0.1
0.92
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
huangboju/AsyncDisplay_Study
refs/heads/master
AsyncDisplay/SocialAppLayout/PostNode.swift
mit
1
// // PostNode.swift // AsyncDisplay // // Created by 伯驹 黄 on 2017/4/26. // Copyright © 2017年 伯驹 黄. All rights reserved. // import AsyncDisplayKit // Processing URLs in post let kLinkAttributeName = NSAttributedString.Key(rawValue: "TextLinkAttributeName") class SocialSingleton { static let shared = SocialSingleton() private var _urlDetector: NSDataDetector? var urlDetector: NSDataDetector? { if _urlDetector == nil { _urlDetector = try? NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue) } return _urlDetector } private init() {} } class PostNode: ASCellNode { let divider = ASDisplayNode() let nameNode = ASTextNode() let usernameNode = ASTextNode() let timeNode = ASTextNode() let postNode = ASTextNode() var viaNode: ASImageNode? let avatarNode = ASNetworkImageNode() var mediaNode: ASNetworkImageNode? var likesNode: LikesNode! var commentsNode: CommentsNode! var optionsNode: ASImageNode! init(post: Post) { super.init() selectionStyle = .none // Name node nameNode.attributedText = NSAttributedString(string: post.name, attributes: TextStyles.nameStyle) nameNode.maximumNumberOfLines = 1 addSubnode(nameNode) // Username node usernameNode.attributedText = NSAttributedString(string: post.username, attributes: TextStyles.usernameStyle) usernameNode.style.flexShrink = 1.0 //if name and username don't fit to cell width, allow username shrink usernameNode.truncationMode = .byTruncatingTail usernameNode.maximumNumberOfLines = 1 addSubnode(usernameNode) // Time node timeNode.attributedText = NSAttributedString(string: post.time, attributes: TextStyles.timeStyle) addSubnode(timeNode) if !post.post.isEmpty { let attrString = NSMutableAttributedString(string: post.post, attributes: TextStyles.postStyle) let urlDetector = SocialSingleton.shared.urlDetector urlDetector?.enumerateMatches(in: attrString.string, options: [], range: NSMakeRange(0, attrString.string.length), using: { (result, flags, stop) in if result?.resultType == NSTextCheckingResult.CheckingType.link { var linkAttributes = TextStyles.postLinkStyle linkAttributes[kLinkAttributeName] = URL(string: (result?.url?.absoluteString)!) attrString.addAttributes(linkAttributes, range: (result?.range)!) } }) // Configure node to support tappable links postNode.delegate = self postNode.isUserInteractionEnabled = true postNode.linkAttributeNames = [kLinkAttributeName.rawValue] postNode.attributedText = attrString postNode.passthroughNonlinkTouches = true // passes touches through when they aren't on a link } addSubnode(postNode) // Media if !post.media.isEmpty { mediaNode = ASNetworkImageNode() mediaNode?.backgroundColor = ASDisplayNodeDefaultPlaceholderColor() mediaNode?.cornerRadius = 4.0 mediaNode?.url = URL(string: post.media) mediaNode?.delegate = self mediaNode?.imageModificationBlock = { image, _ in return image.corner(with: 8) } addSubnode(mediaNode!) } // User pic avatarNode.backgroundColor = ASDisplayNodeDefaultPlaceholderColor() avatarNode.style.preferredSize = CGSize(width: 44, height: 44) avatarNode.cornerRadius = 22.0 avatarNode.url = URL(string: post.photo) avatarNode.imageModificationBlock = { image, _ in return image.corner(with: 44) } addSubnode(avatarNode) // Hairline cell separator updateDividerColor() addSubnode(divider) // Via if post.via != 0 { viaNode = ASImageNode() viaNode?.image = UIImage(named: (post.via == 1) ? "icon_ios" : "icon_android") addSubnode(viaNode!) } // Bottom controls likesNode = LikesNode(likesCount: post.likes) addSubnode(likesNode) commentsNode = CommentsNode(comentsCount: post.comments) addSubnode(commentsNode) optionsNode = ASImageNode() optionsNode.image = UIImage(named: "icon_more") addSubnode(optionsNode) for node in subnodes! where node != postNode { node.isLayerBacked = true } } func updateDividerColor() { /* * UITableViewCell traverses through all its descendant views and adjusts their background color accordingly * either to [UIColor clearColor], although potentially it could use the same color as the selection highlight itself. * After selection, the same trick is performed again in reverse, putting all the backgrounds back as they used to be. * But in our case, we don't want to have the background color disappearing so we reset it after highlighting or * selection is done. */ divider.backgroundColor = UIColor.lightGray } override func didLoad() { // enable highlighting now that self.layer has loaded -- see ASHighlightOverlayLayer.h layer.as_allowsHighlightDrawing = true super.didLoad() } override func layoutSpecThatFits(_ constrainedSize: ASSizeRange) -> ASLayoutSpec { // Flexible spacer between username and time let spacer = ASLayoutSpec() // 占位 spacer.style.flexGrow = 1.0 // 项目的放大比例,默认为0,即如果存在剩余空间,也不放大 // Horizontal stack for name, username, via icon and time var layoutSpecChildren: [ASLayoutElement] = [nameNode, usernameNode, spacer] if let viaNode = viaNode { layoutSpecChildren.append(viaNode) } layoutSpecChildren.append(timeNode) let nameStack = ASStackLayoutSpec(direction: .horizontal, spacing: 5, justifyContent: .start, alignItems: .center, children: layoutSpecChildren) nameStack.style.alignSelf = .stretch // 伸展 // bottom controls horizontal stack let controlsStack = ASStackLayoutSpec(direction: .horizontal, spacing: 10, justifyContent: .start, alignItems: .center, children: [likesNode, commentsNode, optionsNode]) // Add more gaps for control line controlsStack.style.spacingAfter = 3.0 controlsStack.style.spacingBefore = 3.0 var mainStackContent: [ASLayoutElement] = [nameStack, postNode] // Only add the media node if an image is present if let mediaNode = mediaNode { let imagePlace = ASRatioLayoutSpec(ratio: 0.5, child: mediaNode) imagePlace.style.spacingAfter = 3.0 imagePlace.style.spacingBefore = 3.0 mainStackContent.append(imagePlace) } mainStackContent.append(controlsStack) // Vertical spec of cell main content let contentSpec = ASStackLayoutSpec(direction: .vertical, spacing: 8, justifyContent: .start, alignItems: .stretch, children: mainStackContent) contentSpec.style.flexShrink = 1.0 // 收缩 // Horizontal spec for avatar let avatarContentSpec = ASStackLayoutSpec(direction: .horizontal, spacing: 8, justifyContent: .start, alignItems: .start, children: [avatarNode, contentSpec]) return ASInsetLayoutSpec(insets: UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10), child: avatarContentSpec) } override func layout() { super.layout() // Manually layout the divider. let pixelHeight = 1.0 / UIScreen.main.scale divider.frame = CGRect(x: 0.0, y: 0.0, width: calculatedSize.width, height: pixelHeight) } override var isHighlighted: Bool { didSet { updateDividerColor() } } override var isSelected: Bool { didSet { updateDividerColor() } } } extension PostNode: ASNetworkImageNodeDelegate { func imageNode(_ imageNode: ASNetworkImageNode, didLoad image: UIImage) { setNeedsLayout() } } extension PostNode: ASTextNodeDelegate { func textNode(_ textNode: ASTextNode, shouldHighlightLinkAttribute attribute: String, value: Any, at point: CGPoint) -> Bool { return true } func textNode(_ textNode: ASTextNode, tappedLinkAttribute attribute: String, value: Any, at point: CGPoint, textRange: NSRange) { guard let url = value as? URL else { return } UIApplication.shared.openURL(url) } }
2329ed1934eed1562dac6aa12c80e29a
34.322709
177
0.641778
false
false
false
false
JGiola/swift
refs/heads/main
test/Interop/Cxx/value-witness-table/copy-constructors-irgen.swift
apache-2.0
8
// RUN: %target-swift-frontend -enable-experimental-cxx-interop -I %S/Inputs %s -emit-ir | %FileCheck %s // REQUIRES: CPU=x86_64 // REQUIRES: objc_interop import CopyConstructors // CHECK-LABEL: define swiftcc void @"$s4main31testUserProvidedCopyConstructor3objSo03HascdeF0V_AEtAE_tF" // CHECK: [[T0_DEST:%.*]] = bitcast %TSo30HasUserProvidedCopyConstructorV* [[ARG0:%[0-9]+]] to %struct.HasUserProvidedCopyConstructor* // CHECK: [[T0_SRC:%.*]] = bitcast %TSo30HasUserProvidedCopyConstructorV* [[ARG2:%[0-9]+]] to %struct.HasUserProvidedCopyConstructor* // CHECK: call void @_ZN30HasUserProvidedCopyConstructorC1ERKS_(%struct.HasUserProvidedCopyConstructor* [[T0_DEST]], %struct.HasUserProvidedCopyConstructor* [[T0_SRC]]) // CHECK: [[T1_DEST:%.*]] = bitcast %TSo30HasUserProvidedCopyConstructorV* [[ARG1:%[0-9]+]] to %struct.HasUserProvidedCopyConstructor* // CHECK: [[T1_SRC:%.*]] = bitcast %TSo30HasUserProvidedCopyConstructorV* [[ARG2]] to %struct.HasUserProvidedCopyConstructor* // CHECK: call void @_ZN30HasUserProvidedCopyConstructorC1ERKS_(%struct.HasUserProvidedCopyConstructor* [[T1_DEST]], %struct.HasUserProvidedCopyConstructor* [[T1_SRC]]) // CHECK: ret void // CHECK-LABEL: define linkonce_odr void @_ZN30HasUserProvidedCopyConstructorC1ERKS_ public func testUserProvidedCopyConstructor(obj : HasUserProvidedCopyConstructor) -> (HasUserProvidedCopyConstructor, HasUserProvidedCopyConstructor) { return (obj, obj) } // CHECK-LABEL: define swiftcc void @"$s4main26testDefaultCopyConstructor3defSo013HasNonTrivialcdE0V_AEtAE_tF" // CHECK: call void @_ZN35HasNonTrivialDefaultCopyConstructorC1ERKS_ // CHECK: call void @_ZN35HasNonTrivialDefaultCopyConstructorC1ERKS_ // Make sure we call the copy constructor of our member (HasUserProvidedCopyConstructor) // CHECK-LABEL: define linkonce_odr void @_ZN35HasNonTrivialDefaultCopyConstructorC1ERKS_ // CHECK: call void @_ZN35HasNonTrivialDefaultCopyConstructorC2ERKS_ public func testDefaultCopyConstructor(def : HasNonTrivialDefaultCopyConstructor) -> (HasNonTrivialDefaultCopyConstructor, HasNonTrivialDefaultCopyConstructor) { return (def, def) } // CHECK-LABEL: define swiftcc void @"$s4main27testImplicitCopyConstructor3impSo013HasNonTrivialcdE0V_AEtAE_tF" // CHECK: call void @_ZN36HasNonTrivialImplicitCopyConstructorC1ERKS_ // CHECK: call void @_ZN36HasNonTrivialImplicitCopyConstructorC1ERKS_ // Same as above. // CHECK-LABEL: define linkonce_odr void @_ZN36HasNonTrivialImplicitCopyConstructorC1ERKS_ // CHECK: call void @_ZN36HasNonTrivialImplicitCopyConstructorC2ERKS_ public func testImplicitCopyConstructor(imp : HasNonTrivialImplicitCopyConstructor) -> (HasNonTrivialImplicitCopyConstructor, HasNonTrivialImplicitCopyConstructor) { return (imp, imp) }
c2619cf5f8d4ecc069760976df4f8b26
59.955556
168
0.804229
false
true
false
false
coodly/TalkToCloud
refs/heads/main
Sources/TalkToCloud/SystemSign.swift
apache-2.0
1
/* * Copyright 2020 Coodly LLC * * 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. */ #if os(macOS) import Foundation import CommonCrypto public class SystemSign: SignData { private lazy var privateKey: SecKey = { var importedItems: CFArray? let pemData = try! Data(contentsOf: self.pathToPEM) let err = SecItemImport( pemData as CFData, "pem" as CFString, nil, nil, [], nil, nil, &importedItems ) assert(err == errSecSuccess) let importedKeys = importedItems as! [SecKeychainItem] assert(importedKeys.count == 1) return (importedKeys[0] as AnyObject as! SecKey) }() private let pathToPEM: URL public init(pathToPEM: URL) { self.pathToPEM = pathToPEM } // Inspired by https://github.com/ooper-shlab/CryptoCompatibility-Swift public func sign(_ data: Data) -> String { if #available(OSX 10.12, *) { return createSignature(of: data) } else { return transformSign(data) } } private func transformSign(_ inputData: Data) -> String { var umErrorCF: Unmanaged<CFError>? guard let transform = SecSignTransformCreate(self.privateKey, &umErrorCF) else { fatalError() } let setTypeSuccess = SecTransformSetAttribute(transform, kSecDigestTypeAttribute, kSecDigestSHA2, nil) assert(setTypeSuccess) let setLengthSuccess = SecTransformSetAttribute(transform, kSecDigestLengthAttribute, 256 as CFNumber, nil) assert(setLengthSuccess) let addSuccess = SecTransformSetAttribute(transform, kSecTransformInputAttributeName, inputData as CFData, &umErrorCF) assert(addSuccess) let resultData = SecTransformExecute(transform, &umErrorCF) assert(CFGetTypeID(resultData) == CFDataGetTypeID()) return (resultData as! Data).base64EncodedString() } @available(OSX 10.12, *) private func createSignature(of inputData: Data) -> String { var digest = Data(count: Int(CC_SHA256_DIGEST_LENGTH)) inputData.withUnsafeBytes {bytes in digest.withUnsafeMutableBytes {mutableBytes in _ = CC_SHA256(bytes, CC_LONG(inputData.count), mutableBytes) } } var umErrorCF: Unmanaged<CFError>? = nil let resultData = SecKeyCreateSignature( self.privateKey, SecKeyAlgorithm.ecdsaSignatureDigestX962SHA256, digest as CFData, &umErrorCF) let data = resultData as! Data return data.base64EncodedString() } private func hash(of body: Data) -> String { let sha256Data = sha256(data: body) return sha256Data.base64EncodedString() } private func sha256(data : Data) -> Data { var hash = [UInt8](repeating: 0, count: Int(CC_SHA256_DIGEST_LENGTH)) data.withUnsafeBytes { _ = CC_SHA256($0, CC_LONG(data.count), &hash) } return Data(bytes: hash) } } #endif
b8bd26d6346a9996185232ab836344e3
31.883929
126
0.628835
false
false
false
false
zvonler/PasswordElephant
refs/heads/master
external/github.com/apple/swift-protobuf/Sources/SwiftProtobuf/NameMap.swift
gpl-3.0
1
// Sources/SwiftProtobuf/NameMap.swift - Bidirectional number/name mapping // // Copyright (c) 2014 - 2016 Apple Inc. and the project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See LICENSE.txt for license information: // https://github.com/apple/swift-protobuf/blob/master/LICENSE.txt // // ----------------------------------------------------------------------------- /// TODO: Right now, only the NameMap and the NameDescription enum /// (which are directly used by the generated code) are public. /// This means that code outside the library has no way to actually /// use this data. We should develop and publicize a suitable API /// for that purpose. (Which might be the same as the internal API.) /// This must be exactly the same as the corresponding code in the /// protoc-gen-swift code generator. Changing it will break /// compatibility of the library with older generated code. /// /// It does not necessarily need to match protoc's JSON field naming /// logic, however. private func toJsonFieldName(_ s: String) -> String { var result = String() var capitalizeNext = false #if swift(>=3.2) let chars = s #else let chars = s.characters #endif for c in chars { if c == "_" { capitalizeNext = true } else if capitalizeNext { result.append(String(c).uppercased()) capitalizeNext = false } else { result.append(String(c)) } } return result; } /// Allocate static memory buffers to intern UTF-8 /// string data. Track the buffers and release all of those buffers /// in case we ever get deallocated. fileprivate class InternPool { private var interned = [UnsafeBufferPointer<UInt8>]() func intern(utf8: String.UTF8View) -> UnsafeBufferPointer<UInt8> { let bytePointer = UnsafeMutablePointer<UInt8>.allocate(capacity: utf8.count) let mutable = UnsafeMutableBufferPointer<UInt8>(start: bytePointer, count: utf8.count) #if swift(>=3.1) _ = mutable.initialize(from: utf8) #else for (utf8Index, mutableIndex) in zip(utf8.indices, mutable.indices) { mutable[mutableIndex] = utf8[utf8Index] } #endif let immutable = UnsafeBufferPointer<UInt8>(start: bytePointer, count: utf8.count) interned.append(immutable) return immutable } deinit { for buff in interned { #if swift(>=4.1) buff.deallocate() #else let p = UnsafeMutableRawPointer(mutating: buff.baseAddress)! p.deallocate(bytes: buff.count, alignedTo: 1) #endif } } } // Constants for FNV hash http://tools.ietf.org/html/draft-eastlake-fnv-03 private let i_2166136261 = Int(bitPattern: 2166136261) private let i_16777619 = Int(16777619) /// An immutable bidirectional mapping between field/enum-case names /// and numbers, used to record field names for text-based /// serialization (JSON and text). These maps are lazily instantiated /// for each message as needed, so there is no run-time overhead for /// users who do not use text-based serialization formats. public struct _NameMap: ExpressibleByDictionaryLiteral { /// An immutable interned string container. The `utf8Start` pointer /// is guaranteed valid for the lifetime of the `NameMap` that you /// fetched it from. Since `NameMap`s are only instantiated as /// immutable static values, that should be the lifetime of the /// program. /// /// Internally, this uses `StaticString` (which refers to a fixed /// block of UTF-8 data) where possible. In cases where the string /// has to be computed, it caches the UTF-8 bytes in an /// unmovable and immutable heap area. internal struct Name: Hashable, CustomStringConvertible { // This is safe to use elsewhere in this library internal init(staticString: StaticString) { self.nameString = .staticString(staticString) self.utf8Buffer = UnsafeBufferPointer<UInt8>(start: staticString.utf8Start, count: staticString.utf8CodeUnitCount) } // This should not be used outside of this file, as it requires // coordinating the lifecycle with the lifecycle of the pool // where the raw UTF8 gets interned. fileprivate init(string: String, pool: InternPool) { let utf8 = string.utf8 self.utf8Buffer = pool.intern(utf8: utf8) self.nameString = .string(string) } // This is for building a transient `Name` object sufficient for lookup purposes. // It MUST NOT be exposed outside of this file. fileprivate init(transientUtf8Buffer: UnsafeBufferPointer<UInt8>) { self.nameString = .staticString("") self.utf8Buffer = transientUtf8Buffer } private(set) var utf8Buffer: UnsafeBufferPointer<UInt8> private enum NameString { case string(String) case staticString(StaticString) } private var nameString: NameString public var description: String { switch nameString { case .string(let s): return s case .staticString(let s): return s.description } } public var hashValue: Int { var h = i_2166136261 for byte in utf8Buffer { h = (h ^ Int(byte)) &* i_16777619 } return h } public static func ==(lhs: Name, rhs: Name) -> Bool { if lhs.utf8Buffer.count != rhs.utf8Buffer.count { return false } return lhs.utf8Buffer.elementsEqual(rhs.utf8Buffer) } } /// The JSON and proto names for a particular field, enum case, or extension. internal struct Names { private(set) var json: Name? private(set) var proto: Name } /// A description of the names for a particular field or enum case. /// The different forms here let us minimize the amount of string /// data that we store in the binary. /// /// These are only used in the generated code to initialize a NameMap. public enum NameDescription { /// The proto (text format) name and the JSON name are the same string. case same(proto: StaticString) /// The JSON name can be computed from the proto string case standard(proto: StaticString) /// The JSON and text format names are just different. case unique(proto: StaticString, json: StaticString) /// Used for enum cases only to represent a value's primary proto name (the /// first defined case) and its aliases. The JSON and text format names for /// enums are always the same. case aliased(proto: StaticString, aliases: [StaticString]) } private var internPool = InternPool() /// The mapping from field/enum-case numbers to names. private var numberToNameMap: [Int: Names] = [:] /// The mapping from proto/text names to field/enum-case numbers. private var protoToNumberMap: [Name: Int] = [:] /// The mapping from JSON names to field/enum-case numbers. /// Note that this also contains all of the proto/text names, /// as required by Google's spec for protobuf JSON. private var jsonToNumberMap: [Name: Int] = [:] /// Creates a new empty field/enum-case name/number mapping. public init() {} /// Build the bidirectional maps between numbers and proto/JSON names. public init(dictionaryLiteral elements: (Int, NameDescription)...) { for (number, description) in elements { switch description { case .same(proto: let p): let protoName = Name(staticString: p) let names = Names(json: protoName, proto: protoName) numberToNameMap[number] = names protoToNumberMap[protoName] = number jsonToNumberMap[protoName] = number case .standard(proto: let p): let protoName = Name(staticString: p) let jsonString = toJsonFieldName(protoName.description) let jsonName = Name(string: jsonString, pool: internPool) let names = Names(json: jsonName, proto: protoName) numberToNameMap[number] = names protoToNumberMap[protoName] = number jsonToNumberMap[protoName] = number jsonToNumberMap[jsonName] = number case .unique(proto: let p, json: let j): let jsonName = Name(staticString: j) let protoName = Name(staticString: p) let names = Names(json: jsonName, proto: protoName) numberToNameMap[number] = names protoToNumberMap[protoName] = number jsonToNumberMap[protoName] = number jsonToNumberMap[jsonName] = number case .aliased(proto: let p, aliases: let aliases): let protoName = Name(staticString: p) let names = Names(json: protoName, proto: protoName) numberToNameMap[number] = names protoToNumberMap[protoName] = number jsonToNumberMap[protoName] = number for alias in aliases { let protoName = Name(staticString: alias) protoToNumberMap[protoName] = number jsonToNumberMap[protoName] = number } } } } /// Returns the name bundle for the field/enum-case with the given number, or /// `nil` if there is no match. internal func names(for number: Int) -> Names? { return numberToNameMap[number] } /// Returns the field/enum-case number that has the given JSON name, /// or `nil` if there is no match. /// /// This is used by the Text format parser to look up field or enum /// names using a direct reference to the un-decoded UTF8 bytes. internal func number(forProtoName raw: UnsafeBufferPointer<UInt8>) -> Int? { let n = Name(transientUtf8Buffer: raw) return protoToNumberMap[n] } /// Returns the field/enum-case number that has the given JSON name, /// or `nil` if there is no match. /// /// This accepts a regular `String` and is used in JSON parsing /// only when a field name or enum name was decoded from a string /// containing backslash escapes. /// /// JSON parsing must interpret *both* the JSON name of the /// field/enum-case provided by the descriptor *as well as* its /// original proto/text name. internal func number(forJSONName name: String) -> Int? { let utf8 = Array(name.utf8) return utf8.withUnsafeBufferPointer { (buffer: UnsafeBufferPointer<UInt8>) in let n = Name(transientUtf8Buffer: buffer) return jsonToNumberMap[n] } } /// Returns the field/enum-case number that has the given JSON name, /// or `nil` if there is no match. /// /// This is used by the JSON parser when a field name or enum name /// required no special processing. As a result, we can avoid /// copying the name and look up the number using a direct reference /// to the un-decoded UTF8 bytes. internal func number(forJSONName raw: UnsafeBufferPointer<UInt8>) -> Int? { let n = Name(transientUtf8Buffer: raw) return jsonToNumberMap[n] } }
4b2264ac5db6dee34cf3302a2a197918
36.383275
122
0.676671
false
false
false
false
callumboddy/Buttons
refs/heads/dev
ButtonKit/ButtonKit/ButtonTitles.swift
mit
1
// // ButtonTitles.swift // Buttons // // Created by Callum Boddy on 22/08/2016. // Copyright © 2016 Callum Boddy. All rights reserved. // import Foundation import UIKit struct ButtonTitle { static func applyTitleStyle(button: UIButton, font: UIFont, color: UIColor, style: ButtonStyle) { button.button_setTitleLabelColor(font, color: color, style: style) } } public extension UIButton { func setIcon(icon: Ionicon) { titleLabel?.font = UIFont.ioniconOfSize(30) setTitle(String.ioniconWithName(icon), forState: .Normal) } } private extension UIButton { func button_setTitleLabelColor(font: UIFont, color: UIColor, style: ButtonStyle) { titleLabel?.font = font if color.isColorBright() && style == .Flat { setTitleColor(color.darkenColor(70), forState: .Normal) } else { setTitleColor(UIColor.whiteColor(), forState: .Normal) } if style == .Bordered { setTitleColor(color, forState: .Normal) setTitleColor(UIColor.whiteColor(), forState: .Highlighted) } } }
aaba908bfbb5d1419aedf99dff2815bd
28.105263
101
0.653707
false
false
false
false
LYM-mg/DemoTest
refs/heads/master
其他功能/MGImagePickerControllerDemo/MGImagePickerControllerDemo/Manager/MGPhotoConfig.swift
mit
1
// // MGPhotoConfig.swift // MGImagePickerControllerDemo // // Created by newunion on 2019/7/5. // Copyright © 2019 MG. All rights reserved. // import UIKit /// 相机胶卷 let ConfigurationCameraRoll : String = "Camera Roll" /// iOS10.2后将Camera Roll变为了All Photos let ConfigurationAllPhotos : String = "All Photos" /// 隐藏 let ConfigurationHidden : String = "Hidden" /// 慢动作 let ConfigurationSlo_mo : String = "Slo-mo" /// 屏幕快照 let ConfigurationScreenshots : String = "Screenshots" /// 视频 let ConfigurationVideos : String = "Videos" /// 全景照片 let ConfigurationPanoramas : String = "Panoramas" /// 定时拍照 let ConfigurationTime_lapse : String = "Time-lapse" /// 最近添加 let ConfigurationRecentlyAdded : String = "Recently Added" /// 最近删除 let ConfigurationRecentlyDeleted : String = "Recently Deleted" /// 快照连拍 let ConfigurationBursts : String = "Bursts" /// 喜欢 let ConfigurationFavorite : String = "Favorite" /// 自拍 let ConfigurationSelfies : String = "Selfies" class MGPhotoConfig: NSObject { /// 配置选项,默认为如下 static var groupNames : [String] = [ NSLocalizedString(ConfigurationCameraRoll, comment: ""), NSLocalizedString(ConfigurationAllPhotos, comment: ""), NSLocalizedString(ConfigurationSlo_mo, comment: ""), NSLocalizedString(ConfigurationScreenshots, comment: ""), NSLocalizedString(ConfigurationVideos, comment: ""), NSLocalizedString(ConfigurationPanoramas, comment: ""), NSLocalizedString(ConfigurationRecentlyAdded, comment: ""), NSLocalizedString(ConfigurationSelfies, comment: ""), ] /// 获得的配置选项 var groups : [String]{ get{ return MGPhotoConfig.groupNames } } override init() { super.init() } convenience init(groupnames:[String]!) { self.init() MGPhotoConfig.groupNames = groupnames //本地化 localizeHandle() } /// 本地化语言处理 func localizeHandle() { let localizedHandle = MGPhotoConfig.groupNames let finalHandle = localizedHandle.map { (configurationName) -> String in return NSLocalizedString(configurationName, comment: "") } MGPhotoConfig.groupNames = finalHandle } }
be172c147c334d1161a56b91e25479e5
22.030928
80
0.666965
false
true
false
false
xixi197/XXColorTheme
refs/heads/master
Classes/UIKit/UILabel+XXColorStyle.swift
mit
1
// // UILabel+XXColorStyle.swift // XXColorTheme // // Created by xixi197 on 16/1/21. // Copyright © 2016年 xixi197. All rights reserved. // import UIKit import RxSwift import NSObject_Rx extension UILabel { private struct AssociatedKeys { static var TextColorStyle = "xx_textColorStyle" static var ShadowColorStyle = "xx_shadowColorStyle" static var HighlightedTextColorStyle = "xx_highlightedTextColorStyle" static var FontSizeStyle = "xx_fontSizeStyle" } var xx_textColorStyle: XXColorStyle? { get { let lookup = objc_getAssociatedObject(self, &AssociatedKeys.TextColorStyle) as? String ?? "" return XXColorStyle(rawValue: lookup) } set { objc_setAssociatedObject(self, &AssociatedKeys.TextColorStyle, newValue?.rawValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) xx_addColorStyle(newValue, forSelector: "setTextColor:") } } var xx_shadowColorStyle: XXColorStyle? { get { let lookup = objc_getAssociatedObject(self, &AssociatedKeys.ShadowColorStyle) as? String ?? "" return XXColorStyle(rawValue: lookup) } set { objc_setAssociatedObject(self, &AssociatedKeys.ShadowColorStyle, newValue?.rawValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) xx_addColorStyle(newValue, forSelector: "setShadowColor:") } } var xx_highlightedTextColorStyle: XXColorStyle? { get { let lookup = objc_getAssociatedObject(self, &AssociatedKeys.HighlightedTextColorStyle) as? String ?? "" return XXColorStyle(rawValue: lookup) } set { objc_setAssociatedObject(self, &AssociatedKeys.HighlightedTextColorStyle, newValue?.rawValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) xx_addColorStyle(newValue, forSelector: "setHighlightedTextColor:") } } var xx_fontSizeStyle: XXFontSizeStyle? { get { let lookup = objc_getAssociatedObject(self, &AssociatedKeys.FontSizeStyle) as? String ?? "" return XXFontSizeStyle(rawValue: lookup) } set { objc_setAssociatedObject(self, &AssociatedKeys.FontSizeStyle, newValue?.rawValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) xx_addFontSizeStyle(newValue, forSelector: "setFontSize:") } } }
271b088aebdbaabef340138e015a3ddc
33.970588
141
0.659798
false
false
false
false
asowers1/RevCheckIn
refs/heads/master
RevCheckIn/AppDelegate.swift
mit
1
// // AppDelegate.swift // RevCheckIn // // Created by Andrew Sowers on 7/27/14. // Copyright (c) 2014 Andrew Sowers. All rights reserved. // import UIKit import CoreData import CoreLocation @UIApplicationMain @objc class AppDelegate: UIResponder, UIApplicationDelegate, CLLocationManagerDelegate, NSURLSessionDelegate { var window: UIWindow? var locationManager: CLLocationManager? var lastProximity: CLProximity? var myList: Array<AnyObject> = [] var isIn : Bool = false var outOfBoundsCount: Int = 0 var inBounds: Int = 0 var completionHandler:()->Void={} func application(application: UIApplication, handleEventsForBackgroundURLSession identifier: String, completionHandler: () -> Void) { self.completionHandler = completionHandler } func application(application: UIApplication!, didFinishLaunchingWithOptions launchOptions: NSDictionary!) -> Bool { // Override point for customization after application launch. // if(application.respondsToSelector("registerUserNotificationSettings:")) { // application.registerUserNotificationSettings( // UIUserNotificationSettings( // forTypes: UIUserNotificationType.Alert | UIUserNotificationType.Sound, // categories: nil // ) // ) // } /* Problems with iOS 7 */ // Launched from remote notification var helper: HTTPHelper = HTTPHelper() helper.deleteActiveDevice() helper.setDeviceContext("-1") var data: CoreDataHelper = CoreDataHelper() data.setUserStatus("0") application.setMinimumBackgroundFetchInterval(UIApplicationBackgroundFetchIntervalMinimum) var types: UIUserNotificationType = UIUserNotificationType.Badge | UIUserNotificationType.Alert | UIUserNotificationType.Sound var settings: UIUserNotificationSettings = UIUserNotificationSettings( forTypes: types, categories: nil ) application.registerUserNotificationSettings( settings ) application.registerForRemoteNotifications() var uuidString:String = "C0A52410-3B53-11E4-916C-0800200C9A66" as String let beaconIdentifier = "Push" let beaconUUID:NSUUID = NSUUID(UUIDString: uuidString) let beaconRegion:CLBeaconRegion = CLBeaconRegion(proximityUUID: beaconUUID, identifier: beaconIdentifier) locationManager = CLLocationManager() if(locationManager!.respondsToSelector("requestAlwaysAuthorization")) { locationManager!.requestAlwaysAuthorization() } locationManager!.delegate = self locationManager!.pausesLocationUpdatesAutomatically = false locationManager!.startMonitoringForRegion(beaconRegion) locationManager!.startRangingBeaconsInRegion(beaconRegion) locationManager!.startUpdatingLocation() UINavigationBar.appearance().barTintColor = UIColor(red: (246/255.0), green: (86/255.0), blue: (12/255.0), alpha: 1) Crashlytics.startWithAPIKey("6e63974ab6878886d46e46575c43005ded0cfa08") return true } func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) { // Received notification in foreground and background } func application(application: UIApplication, performFetchWithCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) { println("BACKGROUND FETCH") self.setUserState(CoreDataHelper().getUserStatus()) HTTPBackground().getAllUsers() } 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. println("RESIGN ACTIVE FETCH") self.setUserState(CoreDataHelper().getUserStatus()) HTTPBackground().getAllUsers() } 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. println("ENTER BACKGROUND FETCH") self.setUserState(CoreDataHelper().getUserStatus()) HTTPBackground().getAllUsers() } 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. println("ENTER FOREGROUND FETCH") self.setUserState(CoreDataHelper().getUserStatus()) HTTPBackground().getAllUsers() } 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. var data:CoreDataHelper = CoreDataHelper() var backgrounder:HTTPBackground = HTTPBackground() self.completionHandler = {} backgrounder.updateUserState(data.getUsername(), "-1") let state:String = data.getUserStatus() println("username: \(data.getUsername())") data.setUserStatus("-1") let username:String = data.getUsername() if username != "-1" { sendLocalNotificationWithMessage("You've quit RevCheckIn, \(username). this makes your account inactive!") println("SENDING TERMINATION STATE") } self.saveContext() } /* func application( application: UIApplication!, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData! ) { var characterSet: NSCharacterSet = NSCharacterSet( charactersInString: "<>" ) var deviceTokenString: String = ( deviceToken.description as NSString ) .stringByTrimmingCharactersInSet( characterSet ) .stringByReplacingOccurrencesOfString( " ", withString: "" ) as String //record user device var helper: HTTPHelper = HTTPHelper() helper.deleteActiveDevice() helper.setDeviceContext(deviceTokenString) let device = helper.getDeviceContext() println("device token string: \(device)") var myList: Array<AnyObject> = [] var appDel2: AppDelegate = UIApplication.sharedApplication().delegate as AppDelegate var context2: NSManagedObjectContext = appDel2.managedObjectContext! let freq = NSFetchRequest(entityName: "Active_user") myList = context2.executeFetchRequest(freq, error: nil)! if (myList.count > 0){ var selectedItem: NSManagedObject = myList[0] as NSManagedObject var user: String = selectedItem.valueForKeyPath("username") as String if user != "-1" { var coreDataHelper: CoreDataHelper = CoreDataHelper() let network: HTTPBackground = HTTPBackground() network.linkUserToDevice(user, device) println("user:\(user): device:\(device): LINKED") } else{ println("login unsuccessful") } } } func application( application: UIApplication!, didFailToRegisterForRemoteNotificationsWithError error: NSError! ) { println("device token error: \(error.localizedDescription )") var helper: HTTPHelper = HTTPHelper() helper.deleteActiveDevice() helper.setDeviceContext("nil token") } */ // MARK: - Core Data stack lazy var applicationDocumentsDirectory: NSURL = { // The directory the application uses to store the Core Data store file. This code uses a directory named "-.RevCheckIn" in the application's documents Application Support directory. let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls[urls.count-1] as NSURL }() lazy var managedObjectModel: NSManagedObjectModel = { // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model. let modelURL = NSBundle.mainBundle().URLForResource("Model", withExtension: "momd") return NSManagedObjectModel(contentsOfURL: modelURL!) }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = { // The persistent store coordinator for the applicati on. This implementation creates and return a coordinator, having added 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. // Create the coordinator and store var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("RevCheckIn.sqlite") var error: NSError? = nil var failureReason = "There was an error creating or loading the application's saved data." if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil, error: &error) == nil { coordinator = nil // Report any error we got. let dict = NSMutableDictionary() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" dict[NSLocalizedFailureReasonErrorKey] = failureReason dict[NSUnderlyingErrorKey] = error error = NSError.errorWithDomain("YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) // Replace this with code to handle the error appropriately. // abort() 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. NSLog("Unresolved error \(error), \(error!.userInfo)") abort() } return coordinator }() lazy var managedObjectContext: NSManagedObjectContext? = { // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. let coordinator = self.persistentStoreCoordinator if coordinator == nil { return nil } var managedObjectContext = NSManagedObjectContext() managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // MARK: - Core Data Saving support func saveContext () { if let moc = self.managedObjectContext { var error: NSError? = nil if moc.hasChanges && !moc.save(&error) { // Replace this implementation with code to handle the error appropriately. // abort() 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. NSLog("Unresolved error \(error), \(error!.userInfo)") abort() } } } } extension AppDelegate: CLLocationManagerDelegate { func sendLocalNotificationWithMessage(message: String!) { let notification:UILocalNotification = UILocalNotification() notification.alertBody = message UIApplication.sharedApplication().scheduleLocalNotification(notification) } func locationManager(manager: CLLocationManager!, didRangeBeacons beacons: [AnyObject]!, inRegion region: CLBeaconRegion!) { var message:String = "" NSLog("didRangeBeacon"); var data:CoreDataHelper=CoreDataHelper() let username: String = data.getUsername() if username == "-1" { println("username data: \(username)") } if(beacons.count > 0) { NSLog("Found beacons"); let nearestBeacon:CLBeacon = beacons[0] as CLBeacon if username == "-1" { println("Set unknown user state to 1") data.setUserStatus("1") }else{ } if(nearestBeacon.proximity == lastProximity || nearestBeacon.proximity == CLProximity.Unknown) { return; } lastProximity = nearestBeacon.proximity; switch nearestBeacon.proximity { case CLProximity.Far: message = "You are far away from the beacon" case CLProximity.Near: message = "You are near the beacon" case CLProximity.Immediate: message = "You are in the immediate proximity of the beacon" case CLProximity.Unknown: return } } NSLog("%@", message) } func locationManager(manager: CLLocationManager!, didEnterRegion region: CLRegion!) { manager.startRangingBeaconsInRegion(region as CLBeaconRegion) manager.startUpdatingLocation() var myList: Array<AnyObject> = [] var appDel1: AppDelegate = UIApplication.sharedApplication().delegate as AppDelegate var context1: NSManagedObjectContext = appDel1.managedObjectContext! var freq1 = NSFetchRequest(entityName: "User_status") while myList.isEmpty {myList = context1.executeFetchRequest(freq1, error: nil)!} var selectedItem1: NSManagedObject = myList[0] as NSManagedObject var state: String = selectedItem1.valueForKeyPath("checked_in") as String //if state != "1"{ CoreDataHelper().setUserStatus(state) self.setUserState("1") //} //else{ //} } func locationManager(manager: CLLocationManager!, didExitRegion region: CLRegion!) { manager.stopRangingBeaconsInRegion(region as CLBeaconRegion) manager.stopUpdatingLocation() var myList: Array<AnyObject> = [] var appDel1: AppDelegate = UIApplication.sharedApplication().delegate as AppDelegate var context1: NSManagedObjectContext = appDel1.managedObjectContext! var freq1 = NSFetchRequest(entityName: "User_status") while myList.isEmpty {myList = context1.executeFetchRequest(freq1, error: nil)!} var selectedItem1: NSManagedObject = myList[0] as NSManagedObject var state: String = selectedItem1.valueForKeyPath("checked_in") as String //if state != "0"{ CoreDataHelper().setUserStatus(state) self.setUserState("0") //} //else{ //} } func setUserState(state:String){ NSLog("Setting user state"); var myList: Array<AnyObject> = [] var appDel2: AppDelegate = UIApplication.sharedApplication().delegate as AppDelegate var context2: NSManagedObjectContext = appDel2.managedObjectContext! let freq = NSFetchRequest(entityName: "Active_user") NSLog("Prepping fetch in setuserstate"); while myList.isEmpty {myList = context2.executeFetchRequest(freq, error: nil)!} NSLog("finished fetch in setuserstate"); var selectedItem: NSManagedObject = myList[0] as NSManagedObject var user: String = selectedItem.valueForKeyPath("username") as String //self.sendLocalNotificationWithMessage("username: \(user)") if user != "-1" || user != ""{ NSLog("user not -1, prepping background task"); var httpBackgrounder: HTTPBackground = HTTPBackground() if (state == "0"){ NSLog("sending 0 state"); httpBackgrounder.updateUserState(user, "0") } else if (state == "1"){ NSLog("sending 1 state"); httpBackgrounder.updateUserState(user, "1") } NSLog("Finished background task"); //httpBackgrounder.getAllUsers() } } func deleteUserStatus(){ let appDel: AppDelegate = UIApplication.sharedApplication().delegate as AppDelegate let context: NSManagedObjectContext = appDel.managedObjectContext! let freq = NSFetchRequest(entityName: "User_status") var myList: Array<AnyObject> = [] myList = context.executeFetchRequest(freq, error: nil)! if !myList.isEmpty{ println("deleting context") for item in myList { context.deleteObject(item as NSManagedObject) } } context.save(nil) } }
d773629e62235aef8f6a61469087677b
43.209135
293
0.643739
false
false
false
false
DanielAsher/VIPER-SWIFT
refs/heads/master
Carthage/Checkouts/Moya/Carthage/Checkouts/RxSwift/RxSwift/Rx.swift
apache-2.0
42
// // Rx.swift // Rx // // Created by Krunoslav Zaher on 2/14/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import Foundation #if TRACE_RESOURCES /** Counts internal Rx resources (Observables, Observers, Disposables ...). It provides a really simple way to detect leaks early during development. */ public var resourceCount: AtomicInt = 0 #endif // Swift doesn't have a concept of abstract metods. // This function is being used as a runtime check that abstract methods aren't being called. @noreturn func abstractMethod() -> Void { rxFatalError("Abstract method") } @noreturn func rxFatalError(lastMessage: String) { // The temptation to comment this line is great, but please don't, it's for your own good. The choice is yours. fatalError(lastMessage) } func incrementChecked(inout i: Int) throws -> Int { if i == Int.max { throw RxError.Overflow } let result = i i += 1 return result } func decrementChecked(inout i: Int) throws -> Int { if i == Int.min { throw RxError.Overflow } let result = i i -= 1 return result }
74d8d6d80d950ba28860e051b8765512
22.829787
115
0.682143
false
false
false
false
victorwon/SwiftBus
refs/heads/master
Pod/Classes/SwiftBusConnectionHandler.swift
mit
1
// // ConnectionHandler.swift // SwiftBus // // Created by Adam on 2015-08-29. // Copyright (c) 2017 Adam Boyd. All rights reserved. // import Foundation import SWXMLHash enum RequestType { case allAgencies(([String: TransitAgency]) -> Void) case allRoutes(([String : TransitRoute]) -> Void) case routeConfiguration((TransitRoute?) -> Void) case stopPredictions(([String : [TransitPrediction]], [TransitMessage]) -> Void) case stationPredictions(([String : [String : [TransitPrediction]]]) -> Void) case vehicleLocations(([String : [TransitVehicle]]) -> Void) } class SwiftBusConnectionHandler: NSObject { //MARK: Requesting data func requestAllAgencies(_ completion: @escaping (_ agencies: [String: TransitAgency]) -> Void) { startConnection(allAgenciesURL, with: .allAgencies(completion)) } //Request data for all lines func requestAllRouteData(_ agencyTag: String, completion: @escaping (_ agencyRoutes: [String: TransitRoute]) -> Void) { startConnection(allRoutesURL + agencyTag, with: .allRoutes(completion)) } func requestRouteConfiguration(_ routeTag: String, fromAgency agencyTag: String, completion: @escaping (_ route: TransitRoute?) -> Void) { startConnection(routeConfigURL + agencyTag + routeURLSegment + routeTag, with: .routeConfiguration(completion)) } func requestVehicleLocationData(onRoute routeTag: String, withAgency agencyTag: String, completion: @escaping (_ locations: [String: [TransitVehicle]]) -> Void) { startConnection(vehicleLocationsURL + agencyTag + routeURLSegment + routeTag, with: .vehicleLocations(completion)) } func requestStationPredictionData(_ stopTag: String, forRoutes routeTags: [String], withAgency agencyTag: String, completion: @escaping (_ predictions: PredictionGroup) -> Void) { //Building the multi stop url var multiplePredictionString = multiplePredictionsURL + agencyTag for tag in routeTags { multiplePredictionString += multiStopURLSegment + tag + "|" + stopTag } startConnection(multiplePredictionString, with: .stationPredictions(completion)) } func requestStopPredictionData(_ stopTag: String, onRoute routeTag: String, withAgency agencyTag:String, completion: @escaping (_ predictions: [DirectionName: [TransitPrediction]], _ messages: [TransitMessage]) -> Void) { startConnection(stopPredictionsURL + agencyTag + routeURLSegment + routeTag + stopURLSegment + stopTag, with: .stopPredictions(completion)) } func requestMultipleStopPredictionData(_ stopTags: [String], forRoutes routeTags: [String], withAgency agencyTag: String, completion: @escaping (_ predictions: PredictionGroup) -> Void) { let smallestArrayCount = min(stopTags.count, routeTags.count) //Building the multi stop url var multiplePredictionString = multiplePredictionsURL + agencyTag for index in 0..<smallestArrayCount { multiplePredictionString.append("\(multiStopURLSegment)\(routeTags[index])|\(stopTags[index])") } startConnection(multiplePredictionString, with: .stationPredictions(completion)) } /** This is the method that all other request methods call in order to create the URL & start downloading data via an NSURLConnection - parameter requestURL: string of the url that is being requested */ fileprivate func startConnection(_ requestURL:String, with requestType: RequestType) { let url = URL(string: requestURL.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)!) if let url = url { var sessionConfig = URLSessionConfiguration.default; sessionConfig.timeoutIntervalForRequest = 10.0; sessionConfig.timeoutIntervalForResource = 30.0; let session = URLSession(configuration: sessionConfig) let dataTask = session.dataTask(with: url) { data, response, error in let xmlString = NSString(data: data ?? Data(), encoding: String.Encoding.utf8.rawValue)! as String let xml = SWXMLHash.parse(xmlString) let parser = SwiftBusDataParser() switch requestType { case .allAgencies(let closure): parser.parseAllAgenciesData(xml, completion: closure) case .allRoutes(let closure): parser.parseAllRoutesData(xml, completion: closure) case .routeConfiguration(let closure): parser.parseRouteConfiguration(xml, completion: closure) case .vehicleLocations(let closure): parser.parseVehicleLocations(xml, completion: closure) case .stationPredictions(let closure): parser.parseStationPredictions(xml, completion: closure) case .stopPredictions(let closure): parser.parseStopPredictions(xml, completion: closure) } } dataTask.resume() } } }
356ab9da6e453f4fede18d14906fc152
44.843478
225
0.657625
false
true
false
false
soapyigu/LeetCode_Swift
refs/heads/master
Array/SpiralMatrix.swift
mit
1
/** * Question Link: https://leetcode.com/problems/spiral-matrix/ * Primary idea: Use four index to get the right element during iteration * * Time Complexity: O(n^2), Space Complexity: O(1) */ class SpiralMatrix { func spiralOrder(_ matrix: [[Int]]) -> [Int] { var res = [Int]() guard matrix.count != 0 else { return res } var startX = 0 var endX = matrix.count - 1 var startY = 0 var endY = matrix[0].count - 1 while true { // top for i in startY...endY { res.append(matrix[startX][i]) } startX += 1 if startX > endX { break } // right for i in startX...endX { res.append(matrix[i][endY]) } endY -= 1 if startY > endY { break } // bottom for i in stride(from: endY, through: startY, by: -1) { res.append(matrix[endX][i]) } endX -= 1 if startX > endX { break } // left for i in stride(from: endX, through: startX, by: -1) { res.append(matrix[i][startY]) } startY += 1 if startY > endY { break } } return res } }
95a689be6a6ba5b5e4579b3fa6087bf5
23.622951
73
0.398136
false
false
false
false
kickstarter/ios-oss
refs/heads/main
Kickstarter-iOS/Features/Settings/ViewModel/SettingsViewModel.swift
apache-2.0
1
/** FIXME: This VM and its tests should be moved to the Library framework and refactored to not need the `viewControllerFactory` passed to its initializer. */ import KsApi import Library import Prelude import ReactiveSwift import UIKit public protocol SettingsViewModelInputs { func currentUserUpdated() func logoutConfirmed() func settingsCellTapped(cellType: SettingsCellType) func viewDidLoad() func viewWillAppear() } public protocol SettingsViewModelOutputs { var findFriendsDisabledProperty: MutableProperty<Bool> { get } var goToAppStoreRating: Signal<String, Never> { get } var logoutWithParams: Signal<DiscoveryParams, Never> { get } var reloadDataWithUser: Signal<User, Never> { get } var showConfirmLogoutPrompt: Signal<(message: String, cancel: String, confirm: String), Never> { get } var transitionToViewController: Signal<UIViewController, Never> { get } } public protocol SettingsViewModelType { var inputs: SettingsViewModelInputs { get } var outputs: SettingsViewModelOutputs { get } func shouldSelectRow(for cellType: SettingsCellType) -> Bool } public final class SettingsViewModel: SettingsViewModelInputs, SettingsViewModelOutputs, SettingsViewModelType { public init(_ viewControllerFactory: @escaping (SettingsCellType) -> UIViewController?) { let user = Signal.merge( self.viewDidLoadProperty.signal, self.currentUserUpdatedProperty.signal ) .flatMap { AppEnvironment.current.apiService.fetchUserSelf() .wrapInOptional() .prefix(value: AppEnvironment.current.currentUser) .demoteErrors() } .skipNil() let isFollowingEnabled = user .map { $0 |> (\User.social).view } .map { $0 ?? true } self.findFriendsDisabledProperty <~ isFollowingEnabled.negate() self.reloadDataWithUser = Signal.zip(user, self.findFriendsDisabledProperty.signal).map(first) self.showConfirmLogoutPrompt = self.selectedCellTypeProperty.signal .skipNil() .filter { $0 == .logout } .map { _ in ( message: Strings.profile_settings_logout_alert_message(), cancel: Strings.profile_settings_logout_alert_cancel_button(), confirm: Strings.Yes() ) } self.logoutWithParams = self.logoutConfirmedProperty.signal .map { .defaults |> DiscoveryParams.lens.includePOTD .~ true |> DiscoveryParams.lens.sort .~ .magic } self.goToAppStoreRating = self.selectedCellTypeProperty.signal .skipNil() .filter { $0 == .rateInAppStore } .map { _ in AppEnvironment.current.config?.iTunesLink ?? "" } self.transitionToViewController = self.selectedCellTypeProperty.signal .skipNil() .map(viewControllerFactory) .skipNil() } private var currentUserUpdatedProperty = MutableProperty(()) public func currentUserUpdated() { self.currentUserUpdatedProperty.value = () } private var selectedCellTypeProperty = MutableProperty<SettingsCellType?>(nil) public func settingsCellTapped(cellType: SettingsCellType) { self.selectedCellTypeProperty.value = cellType } fileprivate let logoutConfirmedProperty = MutableProperty(()) public func logoutConfirmed() { self.logoutConfirmedProperty.value = () } fileprivate let viewDidLoadProperty = MutableProperty(()) public func viewDidLoad() { self.viewDidLoadProperty.value = () } fileprivate let viewWillAppearProperty = MutableProperty(()) public func viewWillAppear() { self.viewWillAppearProperty.value = () } public let findFriendsDisabledProperty = MutableProperty<Bool>(false) public let goToAppStoreRating: Signal<String, Never> public let logoutWithParams: Signal<DiscoveryParams, Never> public let showConfirmLogoutPrompt: Signal<(message: String, cancel: String, confirm: String), Never> public let reloadDataWithUser: Signal<User, Never> public let transitionToViewController: Signal<UIViewController, Never> public var inputs: SettingsViewModelInputs { return self } public var outputs: SettingsViewModelOutputs { return self } } // MARK: - Helpers extension SettingsViewModel { public func shouldSelectRow(for cellType: SettingsCellType) -> Bool { switch cellType { case .findFriends: guard let user = AppEnvironment.current.currentUser else { return true } return (user |> User.lens.social.view) ?? true default: return true } } }
d35a8841bf058fa35e0c8687d6c6880e
31.326087
104
0.725622
false
false
false
false
akolov/FlingChallenge
refs/heads/master
FlingChallenge/FlingChallenge/Alerts.swift
mit
1
// // Alerts.swift // FlingChallenge // // Created by Alexander Kolov on 9/5/16. // Copyright © 2016 Alexander Kolov. All rights reserved. // import UIKit final class Alerts { static func presentFatalAlert(controller: UIViewController) { let title = NSLocalizedString("Oh no! 😢", comment: "Title of the fatal alert") let message = NSLocalizedString("Something really bad is preventing the app from working properly.\n" + "Please force quit the app by swiping it up in the task switcher and " + "try launching again. If the issue persists, reboot your device and/or " + "delete and reinstall the app.\nSorry about this!", comment: "Message of the fatal alert") let alert = UIAlertController(title: title, message: message, preferredStyle: .Alert) let actionTitle = NSLocalizedString("Dismiss", comment: "Dismiss action title") let action = UIAlertAction(title: actionTitle, style: .Cancel, handler: nil) alert.addAction(action) controller.presentViewController(alert, animated: true, completion: nil) } }
9c35dd9b8b00718f6b77d6138daf6e4a
40.034483
110
0.643697
false
false
false
false
playstones/NEKit
refs/heads/master
src/IPStack/Packet/PacketProtocolParser.swift
bsd-3-clause
2
import Foundation protocol TransportProtocolParserProtocol { var packetData: Data! { get set } var offset: Int { get set } var bytesLength: Int { get } var payload: Data! { get set } func buildSegment(_ pseudoHeaderChecksum: UInt32) } /// Parser to process UDP packet and build packet. class UDPProtocolParser: TransportProtocolParserProtocol { /// The source port. var sourcePort: Port! /// The destination port. var destinationPort: Port! /// The data containing the UDP segment. var packetData: Data! /// The offset of the UDP segment in the `packetData`. var offset: Int = 0 /// The payload to be encapsulated. var payload: Data! /// The length of the UDP segment. var bytesLength: Int { return payload.count + 8 } init() {} init?(packetData: Data, offset: Int) { guard packetData.count >= offset + 8 else { return nil } self.packetData = packetData self.offset = offset sourcePort = Port(bytesInNetworkOrder: (packetData as NSData).bytes.advanced(by: offset)) destinationPort = Port(bytesInNetworkOrder: (packetData as NSData).bytes.advanced(by: offset + 2)) payload = packetData.subdata(in: offset+8..<packetData.count) } func buildSegment(_ pseudoHeaderChecksum: UInt32) { sourcePort.withUnsafeBufferPointer { self.packetData.replaceSubrange(offset..<offset+2, with: $0) } destinationPort.withUnsafeBufferPointer { self.packetData.replaceSubrange(offset+2..<offset+4, with: $0) } var length = NSSwapHostShortToBig(UInt16(bytesLength)) withUnsafeBytes(of: &length) { packetData.replaceSubrange(offset+4..<offset+6, with: $0) } packetData.replaceSubrange(offset+8..<offset+8+payload.count, with: payload) packetData.resetBytes(in: offset+6..<offset+8) var checksum = Checksum.computeChecksum(packetData, from: offset, to: nil, withPseudoHeaderChecksum: pseudoHeaderChecksum) withUnsafeBytes(of: &checksum) { packetData.replaceSubrange(offset+6..<offset+8, with: $0) } } }
fb82b77c140f8191374cb972fb859689
29.652778
130
0.651563
false
false
false
false
EstefaniaGilVaquero/ciceIOS
refs/heads/master
App_VolksWagenFinal-/App_VolksWagenFinal-/VWConcesionariosModel.swift
apache-2.0
1
// // VWConcesionariosModel.swift // App_VolksWagenFinal_CICE // // Created by Formador on 5/10/16. // Copyright © 2016 icologic. All rights reserved. // import UIKit class VWConcesionariosModel: NSObject { var Contacto : String? var CoreoContacto : String? var Horario : String? var Nombre : String? var Provincia_Nombre : String? var Responsable : String? var telefono : Int? var Ubicacion : String? var Imagen : String? var Longitud : Double? var Latitud : Double? init(pContacto : String, pCoreoContacto : String, pHorario : String, pNombre : String, pProvincia_Nombre : String, pResponsable : String, pTelefono : Int, pUbicacion : String, pImagen : String, pLongitud : Double, pLatitud : Double) { self.Contacto = pContacto self.CoreoContacto = pCoreoContacto self.Horario = pHorario self.Nombre = pNombre self.Provincia_Nombre = pProvincia_Nombre self.Responsable = pResponsable self.telefono = pTelefono self.Ubicacion = pUbicacion self.Imagen = pImagen self.Longitud = pLongitud self.Latitud = pLatitud super.init() } }
f338998abf5f834611447428a1367805
28.317073
238
0.653622
false
false
false
false
1457792186/JWSwift
refs/heads/dev
05-filtering-operators/starter/RxSwiftPlayground/Pods/RxSwift/RxSwift/Observables/Reduce.swift
apache-2.0
132
// // Reduce.swift // RxSwift // // Created by Krunoslav Zaher on 4/1/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // extension ObservableType { /** Applies an `accumulator` function over an observable sequence, returning the result of the aggregation as a single element in the result sequence. The specified `seed` value is used as the initial accumulator value. For aggregation behavior with incremental intermediate results, see `scan`. - seealso: [reduce operator on reactivex.io](http://reactivex.io/documentation/operators/reduce.html) - parameter seed: The initial accumulator value. - parameter accumulator: A accumulator function to be invoked on each element. - parameter mapResult: A function to transform the final accumulator value into the result value. - returns: An observable sequence containing a single element with the final accumulator value. */ public func reduce<A, R>(_ seed: A, accumulator: @escaping (A, E) throws -> A, mapResult: @escaping (A) throws -> R) -> Observable<R> { return Reduce(source: self.asObservable(), seed: seed, accumulator: accumulator, mapResult: mapResult) } /** Applies an `accumulator` function over an observable sequence, returning the result of the aggregation as a single element in the result sequence. The specified `seed` value is used as the initial accumulator value. For aggregation behavior with incremental intermediate results, see `scan`. - seealso: [reduce operator on reactivex.io](http://reactivex.io/documentation/operators/reduce.html) - parameter seed: The initial accumulator value. - parameter accumulator: A accumulator function to be invoked on each element. - returns: An observable sequence containing a single element with the final accumulator value. */ public func reduce<A>(_ seed: A, accumulator: @escaping (A, E) throws -> A) -> Observable<A> { return Reduce(source: self.asObservable(), seed: seed, accumulator: accumulator, mapResult: { $0 }) } } final fileprivate class ReduceSink<SourceType, AccumulateType, O: ObserverType> : Sink<O>, ObserverType { typealias ResultType = O.E typealias Parent = Reduce<SourceType, AccumulateType, ResultType> private let _parent: Parent private var _accumulation: AccumulateType init(parent: Parent, observer: O, cancel: Cancelable) { _parent = parent _accumulation = parent._seed super.init(observer: observer, cancel: cancel) } func on(_ event: Event<SourceType>) { switch event { case .next(let value): do { _accumulation = try _parent._accumulator(_accumulation, value) } catch let e { forwardOn(.error(e)) dispose() } case .error(let e): forwardOn(.error(e)) dispose() case .completed: do { let result = try _parent._mapResult(_accumulation) forwardOn(.next(result)) forwardOn(.completed) dispose() } catch let e { forwardOn(.error(e)) dispose() } } } } final fileprivate class Reduce<SourceType, AccumulateType, ResultType> : Producer<ResultType> { typealias AccumulatorType = (AccumulateType, SourceType) throws -> AccumulateType typealias ResultSelectorType = (AccumulateType) throws -> ResultType fileprivate let _source: Observable<SourceType> fileprivate let _seed: AccumulateType fileprivate let _accumulator: AccumulatorType fileprivate let _mapResult: ResultSelectorType init(source: Observable<SourceType>, seed: AccumulateType, accumulator: @escaping AccumulatorType, mapResult: @escaping ResultSelectorType) { _source = source _seed = seed _accumulator = accumulator _mapResult = mapResult } override func run<O: ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == ResultType { let sink = ReduceSink(parent: self, observer: observer, cancel: cancel) let subscription = _source.subscribe(sink) return (sink: sink, subscription: subscription) } }
ff18091fa4095a640e87ee30fc704280
39.284404
219
0.660214
false
false
false
false
looseyi/RefreshController
refs/heads/master
Source/RefreshView.swift
mit
1
// // RefreshView.swift // RefreshController // // Created by Edmond on 5/6/2559 BE. // Copyright © 2559 BE Edmond. All rights reserved. // import UIKit public protocol RefreshViewProtocol: class { func pullToUpdate(_ controller: PullToRefreshController, didChangeState state: RefreshState) func pullToUpdate(_ controller: PullToRefreshController, didChangePercentage percentate: CGFloat) func pullToUpdate(_ controller: PullToRefreshController, didSetEnable enable: Bool) } open class RefreshView: UIView { var state: RefreshState? { willSet { if newValue == .stop { indicator.stopAnimating() } else if newValue == .loading { indicator.startAnimating() } } } public let indicator = RefreshIndicator(color: .lightGray) public override init(frame: CGRect) { super.init(frame: frame) addSubview(indicator) } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } open override func layoutSubviews() { super.layoutSubviews() let boundsCenter = CGPoint(x: bounds.midX, y: bounds.midY) indicator.center = boundsCenter } } extension RefreshView: RefreshViewProtocol { public func pullToUpdate(_ controller: PullToRefreshController, didChangeState state: RefreshState) { self.state = state setNeedsLayout() } public func pullToUpdate(_ controller: PullToRefreshController, didChangePercentage percentage: CGFloat) { indicator.setPercentage(percentage) } public func pullToUpdate(_ controller: PullToRefreshController, didSetEnable enable: Bool) { if !enable { state = .stop } } }
025d83d644e5519e758aa942ed056b15
27.03125
110
0.667224
false
false
false
false
garethpaul/furni-ios
refs/heads/master
Furni/AccountViewController.swift
apache-2.0
1
// // Copyright (C) 2015 Twitter, Inc. and other contributors. // // 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 final class AccountViewController: UIViewController { // MARK: Properties @IBOutlet private weak var pictureImageView: UIImageView! @IBOutlet private weak var nameLabel: UILabel! @IBOutlet private weak var signOutButton: UIButton! // MARK: IBActions @IBAction private func signOutButtonTapped(sender: AnyObject) { AccountManager.defaultAccountManager.signOut() SignInViewController.presentSignInViewController() { _ in } } @IBAction private func learnMoreButtonTapped(sender: AnyObject) { UIApplication.sharedApplication().openURL(NSURL(string: "http://furni.xyz")!) } // MARK: View Life Cycle override func viewDidLoad() { super.viewDidLoad() signOutButton.decorateForFurni() } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() // Add rounded corners to the image. pictureImageView.layer.cornerRadius = pictureImageView.bounds.width / 2 pictureImageView.layer.masksToBounds = true } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) // Assign the user name and image. let user = AccountManager.defaultAccountManager.user user?.populateWithLocalContact() self.nameLabel.text = user?.fullName self.pictureImageView.image = user?.image } }
a739a58476a3b72b0f2aa1da2338c588
29.727273
85
0.705621
false
false
false
false
Faryn/Calculator
refs/heads/master
Calculator/CalculatorBrain.swift
mit
1
// // CalculatorBrain.swift // Calculator // // Created by Paul Pfeiffer on 01/02/15. // Copyright (c) 2015 Paul Pfeiffer. All rights reserved. // import Foundation class CalculatorBrain { private enum Op: Printable { case Operand(Double) case Constant(String, Double) case Variable(String) case UnaryOperation(String, Double -> Double) case BinaryOperation(String, (Double, Double) -> Double) var description: String { get { switch self { case .Operand(let operand): return "\(operand)" case .Variable(let variable): return "\(variable)" case .Constant(let symbol, _): return symbol case .UnaryOperation(let symbol, _): return symbol case .BinaryOperation(let symbol, _): return symbol } } } } private var opStack = [Op]() private var knownOps = [String:Op]() private var variableValues = [String: Double]() func setVar(s: String, v: Double) -> Double? { variableValues[s] = v return evaluate() } init() { func learnOp(op:Op) { knownOps[op.description] = op } learnOp(Op.BinaryOperation("×", *)) learnOp(Op.BinaryOperation("÷") { $1 / $0 }) learnOp(Op.BinaryOperation("+", +)) learnOp(Op.BinaryOperation("−") { $1 - $0 }) learnOp(Op.UnaryOperation("√", sqrt)) learnOp(Op.UnaryOperation("sin", sin)) learnOp(Op.UnaryOperation("cos", cos)) learnOp(Op.Constant("ᴨ", M_PI)) } var program: AnyObject { // guaranteed to be a PropertyList get { return opStack.map { $0.description } } set { if let opSymbols = newValue as? Array<String> { var newOpStack = [Op]() for opSymbol in opSymbols { if let op = knownOps[opSymbol] { newOpStack.append(op) } else if let operand = NSNumberFormatter().numberFromString(opSymbol)?.doubleValue { newOpStack.append(.Operand(operand)) } else { newOpStack.append(.Variable(opSymbol)) } } opStack = newOpStack } } } private func evaluate(ops: [Op]) -> (result: Double?, remainingOps: [Op]) { if !ops.isEmpty { var remainingOps = ops let op = remainingOps.removeLast() switch op { case .Operand(let operand): return (operand, remainingOps) case .Variable(let variable): return (variableValues[variable]?, remainingOps) case .Constant(_, let value): return (value, remainingOps) case .UnaryOperation(_, let operation): let operandEvaluation = evaluate(remainingOps) if let operand = operandEvaluation.result { return (operation(operand), operandEvaluation.remainingOps) } case .BinaryOperation(let name, let operation): let op1Evaluation = evaluate(remainingOps) if let operand1 = op1Evaluation.result { let op2Evaluation = evaluate(op1Evaluation.remainingOps) if let operand2 = op2Evaluation.result { return (operation(operand1, operand2), op2Evaluation.remainingOps) } } } } return (nil, ops) } var description: String? { get { var result = String?() var remainder = [Op]() (result, remainder) = description(opStack) while !remainder.isEmpty { let expression = description(remainder) if let expDescription = expression.result { result = "\(expDescription), \(result!)" remainder = expression.remainingOps } else { remainder.removeLast() } } return result } } func evaluate() -> Double? { let (result, remainder) = evaluate(opStack) return result } private func description(ops: [Op]) -> (result: String?, remainingOps: [Op]) { if !ops.isEmpty { var remainingOps = ops let op = remainingOps.removeLast() switch op { case .Operand(let operand): return ("\(operand)", remainingOps) case .Variable(let variable): return (variable, remainingOps) case .Constant(let constant, _): return (constant, remainingOps) case .UnaryOperation(let operation, _): let operandDescription = description(remainingOps) if let operand = operandDescription.result { return (("\(operation)(\(operand))"), operandDescription.remainingOps) } case .BinaryOperation(let operation, _): let op1Description = description(remainingOps) if let operand1 = op1Description.result { let op2Description = description (op1Description.remainingOps) if let operand2 = op2Description.result { return (("\(operand2)\(operation)\(operand1)"), op2Description.remainingOps) } else { return (("?\(operation)\(operand1)"), op2Description.remainingOps) } } } } return (nil, ops) } func pushOperand(operand: Double) -> Double? { opStack.append(Op.Operand(operand)) return evaluate() } func pushOperand(symbol: String) -> Double? { opStack.append(Op.Variable(symbol)) return evaluate() } func performOperation(symbol: String) -> Double? { if let operation = knownOps[symbol] { opStack.append(operation) } return evaluate() } func removeLastFromStack () -> Double? { if !opStack.isEmpty { opStack.removeLast() return evaluate() } return nil } func resetVars() { variableValues.removeAll(keepCapacity: false) } func reset() { opStack.removeAll(keepCapacity: false) resetVars() } }
7719d79c1642069c18a23abc41f4f3ef
31.907317
105
0.509266
false
false
false
false
e-government-ua/iMobile
refs/heads/master
iGov/SMSTableViewCell.swift
gpl-3.0
1
// // SMSTableViewCell.swift // iGov // // Created by Sergii Maksiuta on 2/27/17. // Copyright © 2017 iGov. All rights reserved. // import UIKit class SMSTableViewCell: UITableViewCell { static let kReuseID = "SMSTableViewCell" var textFields = [UITextField]() let smsdigits = 6 override func awakeFromNib() { super.awakeFromNib() } override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) let offset:CGFloat = 15.0 let fieldWidth = (self.bounds.size.width-CGFloat(smsdigits+1)*offset)/CGFloat(smsdigits) let container = UIView() self.addSubview(container) container.snp.makeConstraints { (make) in make.width.equalTo(CGFloat(smsdigits)*fieldWidth + CGFloat(smsdigits + 1)*offset) make.top.bottom.equalTo(self) make.centerX.equalTo(self) } for i in 1...smsdigits{ let textField = UITextField() textField.keyboardType = .numberPad textFields.append(textField) container.addSubview(textField); textField.backgroundColor = UIColor.red textField.snp.makeConstraints({ (make) in make.left.equalTo(CGFloat(i - 1)*fieldWidth+CGFloat(i)*offset) make.width.equalTo(fieldWidth) make.centerY.height.equalTo(self) }); } } func numberFromSMSCode () -> String { var result : String = "" for field in textFields { result += field.text! } return result } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } class var reuseIdentifier: String{ return kReuseID } }
06c0c9a68cae5f3a94a5ff78c6394c69
28.261538
96
0.590957
false
false
false
false
Masteryyz/CSYMicroBlockSina
refs/heads/master
CSYMicroBlockSina/CSYMicroBlockSina/Classes/Module/Basic/CSYBasicTableViewController.swift
mit
1
// // CSYBasicTableViewController.swift // CSYMicroBlockSina // // Created by 姚彦兆 on 15/11/8. // Copyright © 2015年 姚彦兆. All rights reserved. // // 只是做个测试 // 同时导入Github 和 GitOSChina import UIKit import AFNetworking class CSYBasicTableViewController: UITableViewController,CSYVisitorViewDelegate { var userJurisdiction : Bool { return GetUserInfoModel().isLogin } //设置"拦截者" 进行访问者的权限设定 var visitorView : CSYVisitorView? override func loadView() { userJurisdiction ? super.loadView() : loadVisitorView() } private func loadVisitorView (){ visitorView = CSYVisitorView() visitorView?.delegate = self view = visitorView //Nav上的按钮 self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "注册", style: UIBarButtonItemStyle.Plain, target: self, action: "startRegist") self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "登陆", style: UIBarButtonItemStyle.Plain, target: self, action: "startLogin") } //实现代理方法 @objc internal func startLogin() { print("用户点击了登录按钮") //点击登录按钮之后 presentViewController(UINavigationController(rootViewController: LoginViewWithOAUTHViewController()), animated: true) { () -> Void in print("LoadSuccess") } } @objc internal func startRegist() { print("用户点击了注册按钮") } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 0 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return 0 } /* override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath) // Configure the cell... return cell } */ /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
ad7ff1f451acb6d8acbac92737dc0613
28.394366
157
0.651893
false
false
false
false
veeman961/Flicks
refs/heads/master
Pods/RAMAnimatedTabBarController/RAMAnimatedTabBarController/RAMAnimatedTabBarController.swift
apache-2.0
1
// AnimationTabBarController.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 // MARK: Custom Badge extension RAMAnimatedTabBarItem { /// The current badge value override open var badgeValue: String? { get { return badge?.text } set(newValue) { if newValue == nil { badge?.removeFromSuperview() badge = nil; return } if let iconView = iconView, let contanerView = iconView.icon.superview , badge == nil { badge = RAMBadge.badge() badge!.addBadgeOnView(contanerView) } badge?.text = newValue } } } /// UITabBarItem with animation open class RAMAnimatedTabBarItem: UITabBarItem { @IBInspectable open var yOffSet: CGFloat = 0 open override var isEnabled: Bool { didSet { iconView?.icon.alpha = isEnabled == true ? 1 : 0.5 iconView?.textLabel.alpha = isEnabled == true ? 1 : 0.5 } } /// animation for UITabBarItem. use RAMFumeAnimation, RAMBounceAnimation, RAMRotationAnimation, RAMFrameItemAnimation, RAMTransitionAnimation /// or create custom anmation inherit RAMItemAnimation @IBOutlet open var animation: RAMItemAnimation! /// The font used to render the UITabBarItem text. open var textFont: UIFont = UIFont.systemFont(ofSize: 10) /// The color of the UITabBarItem text. @IBInspectable open var textColor: UIColor = UIColor.black /// The tint color of the UITabBarItem icon. @IBInspectable open var iconColor: UIColor = UIColor.clear // if alpha color is 0 color ignoring var bgDefaultColor: UIColor = UIColor.clear // background color var bgSelectedColor: UIColor = UIColor.clear // The current badge value open var badge: RAMBadge? // use badgeValue to show badge // Container for icon and text in UITableItem. open var iconView: (icon: UIImageView, textLabel: UILabel)? /** Start selected animation */ open func playAnimation() { assert(animation != nil, "add animation in UITabBarItem") guard animation != nil && iconView != nil else { return } animation.playAnimation(iconView!.icon, textLabel: iconView!.textLabel) } /** Start unselected animation */ open func deselectAnimation() { guard animation != nil && iconView != nil else { return } animation.deselectAnimation( iconView!.icon, textLabel: iconView!.textLabel, defaultTextColor: textColor, defaultIconColor: iconColor) } /** Set selected state without animation */ open func selectedState() { guard animation != nil && iconView != nil else { return } animation.selectedState(iconView!.icon, textLabel: iconView!.textLabel) } } extension RAMAnimatedTabBarController { /** Change selected color for each UITabBarItem - parameter textSelectedColor: set new color for text - parameter iconSelectedColor: set new color for icon */ open func changeSelectedColor(_ textSelectedColor:UIColor, iconSelectedColor:UIColor) { let items = tabBar.items as! [RAMAnimatedTabBarItem] for index in 0..<items.count { let item = items[index] item.animation.textSelectedColor = textSelectedColor item.animation.iconSelectedColor = iconSelectedColor if item == self.tabBar.selectedItem { item.selectedState() } } } /** Hide UITabBarController - parameter isHidden: A Boolean indicating whether the UITabBarController is displayed */ open func animationTabBarHidden(_ isHidden:Bool) { guard let items = tabBar.items as? [RAMAnimatedTabBarItem] else { fatalError("items must inherit RAMAnimatedTabBarItem") } for item in items { if let iconView = item.iconView { iconView.icon.superview?.isHidden = isHidden } } self.tabBar.isHidden = isHidden; } /** Selected UITabBarItem with animaton - parameter from: Index for unselected animation - parameter to: Index for selected animation */ open func setSelectIndex(from: Int, to: Int) { selectedIndex = to guard let items = tabBar.items as? [RAMAnimatedTabBarItem] else { fatalError("items must inherit RAMAnimatedTabBarItem") } let containerFrom = items[from].iconView?.icon.superview containerFrom?.backgroundColor = items[from].bgDefaultColor items[from].deselectAnimation() let containerTo = items[to].iconView?.icon.superview containerTo?.backgroundColor = items[to].bgSelectedColor items[to].playAnimation() } } /// UITabBarController with item animations open class RAMAnimatedTabBarController: UITabBarController { fileprivate var didInit: Bool = false fileprivate var didLoadView: Bool = false // MARK: life circle /** Returns a newly initialized view controller with the nib file in the specified bundle. - parameter nibNameOrNil: The name of the nib file to associate with the view controller. The nib file name should not contain any leading path information. If you specify nil, the nibName property is set to nil. - parameter nibBundleOrNil: The bundle in which to search for the nib file. This method looks for the nib file in the bundle's language-specific project directories first, followed by the Resources directory. If this parameter is nil, the method uses the heuristics described below to locate the nib file. - returns: A newly initialized RAMAnimatedTabBarController object. */ public override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) self.didInit = true self.initializeContainers() } /** Returns a newly initialized view controller with the nib file in the specified bundle. - parameter viewControllers: Sets the root view controllers of the tab bar controller. - returns: A newly initialized RAMAnimatedTabBarController object. */ public init(viewControllers: [UIViewController]) { super.init(nibName: nil, bundle: nil) self.didInit = true // Set initial items self.setViewControllers(viewControllers, animated: false) self.initializeContainers() } /** Returns a newly initialized view controller with the nib file in the specified bundle. - parameter coder: An unarchiver object. - returns: A newly initialized RAMAnimatedTabBarController object. */ required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.didInit = true self.initializeContainers() } override open func viewDidLoad() { super.viewDidLoad() self.didLoadView = true self.initializeContainers() } fileprivate func initializeContainers() { if !self.didInit || !self.didLoadView { return } let containers = self.createViewContainers() self.createCustomIcons(containers) } // MARK: create methods fileprivate func createCustomIcons(_ containers : NSDictionary) { guard let items = tabBar.items as? [RAMAnimatedTabBarItem] else { fatalError("items must inherit RAMAnimatedTabBarItem") } var index = 0 for item in items { guard let itemImage = item.image else { fatalError("add image icon in UITabBarItem") } guard let container = containers["container\(items.count - 1 - index)"] as? UIView else { fatalError() } container.tag = index let renderMode = item.iconColor.cgColor.alpha == 0 ? UIImageRenderingMode.alwaysOriginal : UIImageRenderingMode.alwaysTemplate let icon = UIImageView(image: item.image?.withRenderingMode(renderMode)) icon.translatesAutoresizingMaskIntoConstraints = false icon.tintColor = item.iconColor // text let textLabel = UILabel() textLabel.text = item.title textLabel.backgroundColor = UIColor.clear textLabel.textColor = item.textColor textLabel.font = item.textFont textLabel.textAlignment = NSTextAlignment.center textLabel.translatesAutoresizingMaskIntoConstraints = false container.backgroundColor = (items as [RAMAnimatedTabBarItem])[index].bgDefaultColor container.addSubview(icon) createConstraints(icon, container: container, size: itemImage.size, yOffset: -5 - item.yOffSet) container.addSubview(textLabel) let textLabelWidth = tabBar.frame.size.width / CGFloat(items.count) - 5.0 createConstraints(textLabel, container: container, size: CGSize(width: textLabelWidth , height: 10), yOffset: 16 - item.yOffSet) if item.isEnabled == false { icon.alpha = 0.5 textLabel.alpha = 0.5 } item.iconView = (icon:icon, textLabel:textLabel) if 0 == index { // selected first elemet item.selectedState() container.backgroundColor = (items as [RAMAnimatedTabBarItem])[index].bgSelectedColor } item.image = nil item.title = "" index += 1 } } fileprivate func createConstraints(_ view:UIView, container:UIView, size:CGSize, yOffset:CGFloat) { let constX = NSLayoutConstraint(item: view, attribute: NSLayoutAttribute.centerX, relatedBy: NSLayoutRelation.equal, toItem: container, attribute: NSLayoutAttribute.centerX, multiplier: 1, constant: 0) container.addConstraint(constX) let constY = NSLayoutConstraint(item: view, attribute: NSLayoutAttribute.centerY, relatedBy: NSLayoutRelation.equal, toItem: container, attribute: NSLayoutAttribute.centerY, multiplier: 1, constant: yOffset) container.addConstraint(constY) let constW = NSLayoutConstraint(item: view, attribute: NSLayoutAttribute.width, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: size.width) view.addConstraint(constW) let constH = NSLayoutConstraint(item: view, attribute: NSLayoutAttribute.height, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: size.height) view.addConstraint(constH) } fileprivate func createViewContainers() -> NSDictionary { guard let items = tabBar.items else { fatalError("add items in tabBar") } var containersDict = [String: AnyObject]() for index in 0..<items.count { let viewContainer = createViewContainer() containersDict["container\(index)"] = viewContainer } var formatString = "H:|-(0)-[container0]" for index in 1..<items.count { formatString += "-(0)-[container\(index)(==container0)]" } formatString += "-(0)-|" let constranints = NSLayoutConstraint.constraints(withVisualFormat: formatString, options:NSLayoutFormatOptions.directionRightToLeft, metrics: nil, views: (containersDict as [String : AnyObject])) view.addConstraints(constranints) return containersDict as NSDictionary } fileprivate func createViewContainer() -> UIView { let viewContainer = UIView(); viewContainer.backgroundColor = UIColor.clear // for test viewContainer.translatesAutoresizingMaskIntoConstraints = false viewContainer.isExclusiveTouch = true view.addSubview(viewContainer) // add gesture let tapGesture = UITapGestureRecognizer(target: self, action: #selector(RAMAnimatedTabBarController.tapHandler(_:))) tapGesture.numberOfTouchesRequired = 1 viewContainer.addGestureRecognizer(tapGesture) // add constrains let constY = NSLayoutConstraint(item: viewContainer, attribute: NSLayoutAttribute.bottom, relatedBy: NSLayoutRelation.equal, toItem: view, attribute: NSLayoutAttribute.bottom, multiplier: 1, constant: 0) view.addConstraint(constY) let constH = NSLayoutConstraint(item: viewContainer, attribute: NSLayoutAttribute.height, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: tabBar.frame.size.height) viewContainer.addConstraint(constH) return viewContainer } // MARK: actions open func tapHandler(_ gesture:UIGestureRecognizer) { guard let items = tabBar.items as? [RAMAnimatedTabBarItem], let gestureView = gesture.view else { fatalError("items must inherit RAMAnimatedTabBarItem") } let currentIndex = gestureView.tag if items[currentIndex].isEnabled == false { return } let controller = self.childViewControllers[currentIndex] if let shouldSelect = delegate?.tabBarController?(self, shouldSelect: controller) , !shouldSelect { return } if selectedIndex != currentIndex { let animationItem : RAMAnimatedTabBarItem = items[currentIndex] animationItem.playAnimation() let deselectItem = items[selectedIndex] let containerPrevious : UIView = deselectItem.iconView!.icon.superview! containerPrevious.backgroundColor = items[currentIndex].bgDefaultColor deselectItem.deselectAnimation() let container : UIView = animationItem.iconView!.icon.superview! container.backgroundColor = items[currentIndex].bgSelectedColor selectedIndex = gestureView.tag delegate?.tabBarController?(self, didSelect: controller) } else if selectedIndex == currentIndex { if let navVC = self.viewControllers![selectedIndex] as? UINavigationController { navVC.popToRootViewController(animated: true) } } } }
39742b388de32020dbb5eec865ab598d
33.466245
143
0.634511
false
false
false
false
tbajis/Bop
refs/heads/master
Photo.swift
apache-2.0
1
// // Photo+CoreDataClass.swift // Bop // // Created by Thomas Manos Bajis on 4/24/17. // Copyright © 2017 Thomas Manos Bajis. All rights reserved. // import Foundation import CoreData // MARK: - Photo: NSManagedObject class Photo: NSManagedObject { // MARK: Initializer convenience init(id: String?, height: Double, width: Double, mediaURL: String, context: NSManagedObjectContext) { if let ent = NSEntityDescription.entity(forEntityName: "Photo", in: context) { self.init(entity: ent, insertInto: context) self.id = id self.mediaURL = mediaURL self.width = width self.height = height } else { fatalError("Unable to find Entity Photo") } } }
b452eedeec078c7933ab0b39eb932d94
26.392857
117
0.6206
false
false
false
false
vgorloff/AUHost
refs/heads/master
Sources/Common/MainViewUIModel.swift
mit
1
// // MainViewUIModel.swift // AUHost // // Created by Vlad Gorlov on 15.06.17. // Copyright © 2017 WaveLabs. All rights reserved. // import AppKit import AVFoundation import Foundation import MediaLibrary import mcxAppKitMedia import mcxMediaAU import mcxMediaExtensions import mcxFoundation import mcxRuntime private let log = Logger.getLogger(MainViewUIModel.self) class MainViewUIModel { struct State: OptionSet, CustomStringConvertible { let rawValue: Int static let empty = State([]) static let canPlayback = State(rawValue: 1 << 0) static let canOpenEffect = State(rawValue: 1 << 1) var description: String { switch self { case .canPlayback: return "canPlayback" case .canOpenEffect: return "canOpenEffect" default: return "empty" } } } enum Event { case loadingEffects(Bool) case willSelectEffect case didSelectEffect(Error?) case didClearEffect case playbackEngineStageChanged(PlaybackEngine.State) case audioComponentsChanged case selectMedia(URL) case effectWindowWillOpen case effectWindowWillClose } var eventHandler: ((Event, State) -> Void)? private var isEffectOpened = false private(set) var selectedAUComponent: AVAudioUnitComponent? private(set) var availableEffects: [AVAudioUnitComponent] = [] private(set) var availablePresets: [AUAudioUnitPreset] = [] private(set) lazy var audioUnitDatasource = AudioComponentsUtility() private(set) lazy var mediaLibraryLoader = MediaLibraryUtility() private(set) lazy var playbackEngine = PlaybackEngine() private var effectWindowController: NSWindowController? // Temporary store init() { setupHandlers() } } extension MainViewUIModel { var canOpenEffectView: Bool { guard !isEffectOpened, let component = selectedAUComponent else { return false } let flags = AudioComponentFlags(rawValue: component.audioComponentDescription.componentFlags) let v3AU = flags.contains(AudioComponentFlags.isV3AudioUnit) return component.hasCustomView || v3AU } func reloadEffects() { eventHandler?(.loadingEffects(true), .empty) audioUnitDatasource.updateEffectList { [weak self] in guard let this = self else { return } this.availableEffects = $0 this.eventHandler?(.loadingEffects(false), this.state) } } var state: State { var state = State.empty if canOpenEffectView { state.insert(.canOpenEffect) } return state } func selectEffect(_ component: AVAudioUnitComponent?, completion: Completion<AVAudioUnit>?) { eventHandler?(.willSelectEffect, .empty) playbackEngine.selectEffect(componentDescription: component?.audioComponentDescription) { [weak self] in guard let this = self else { return } switch $0 { case .effectCleared: this.availablePresets.removeAll() this.selectedAUComponent = nil this.eventHandler?(.didClearEffect, this.state) case .failure(let error): log.error(error) this.eventHandler?(.didSelectEffect(error), this.state) case .success(let effect): this.availablePresets = effect.auAudioUnit.factoryPresets ?? [] this.selectedAUComponent = component this.eventHandler?(.didSelectEffect(nil), this.state) completion?(effect) } } } func selectPreset(_ preset: AUAudioUnitPreset?) { playbackEngine.selectPreset(preset: preset) } func togglePlay() { do { switch playbackEngine.stateID { case .playing: try playbackEngine.pause() case .paused: try playbackEngine.resume() case .stopped: try playbackEngine.play() case .updatingGraph: break } } catch { log.error(error) } } func processFileAtURL(_ url: URL) { do { defer { url.stopAccessingSecurityScopedResource() // Seems working fine without this line } _ = url.startAccessingSecurityScopedResource() // Seems working fine without this line eventHandler?(.selectMedia(url), .empty) let file = try AVAudioFile(forReading: url) playbackEngine.setFileToPlay(file) if playbackEngine.stateID == .stopped { try playbackEngine.play() } log.verbose("File assigned: \(url.absoluteString)") } catch { log.error(error) } } func openEffectView(completion: Completion<NSViewController>?) { isEffectOpened = true playbackEngine.openEffectView { [weak self] in if let vc = $0 { completion?(vc) } else { self?.isEffectOpened = false } } } func closeEffectView() { effectWindowController?.close() effectWindowWillClose() } func effectWindowWillOpen(_ vc: NSWindowController) { isEffectOpened = true effectWindowController = vc eventHandler?(.effectWindowWillOpen, state) } func effectWindowWillClose() { isEffectOpened = false effectWindowController = nil eventHandler?(.effectWindowWillClose, state) } func handlePastboard(_ objects: MediaObjectPasteboardUtility.PasteboardObjects) { switch objects { case .none: break case .mediaObjects(let mediaObjectsDict): let mediaObjects = mediaLibraryLoader.mediaObjectsFromPlist(pasteboardPlist: mediaObjectsDict) if let firstMediaObject = mediaObjects.first?.1.first?.1, let url = firstMediaObject.url { processFileAtURL(url) } case .filePaths(let filePaths): if let firstFilePath = filePaths.first { let url = NSURL(fileURLWithPath: firstFilePath) processFileAtURL(url as URL) } } } } extension MainViewUIModel { private func setupHandlers() { playbackEngine.changeHandler = { [weak self] in guard let this = self else { return } self?.eventHandler?(.playbackEngineStageChanged($0.newState), this.state) } audioUnitDatasource.handlerStateChange = { [weak self] change in guard let this = self else { return } switch change { case .audioComponentRegistered: this.eventHandler?(.audioComponentsChanged, this.state) case .audioComponentInstanceInvalidated(let au): if au.componentDescription == this.selectedAUComponent?.audioComponentDescription { this.selectEffect(nil, completion: nil) // This execution branch seems working not correctly. } else { this.eventHandler?(.audioComponentsChanged, this.state) } } } } }
6bd1948eb759bd14706ad1a416961fe2
30.175676
110
0.648028
false
false
false
false
squaremeals/squaremeals-ios-app
refs/heads/master
SquareMeals/Coordinator/MainCoordinator.swift
mit
1
// // MainCoordinator.swift // SquareMeals // // Created by Zachary Shakked on 11/14/17. // Copyright © 2017 Shakd, LLC. All rights reserved. // import UIKit public final class MainCoordinator: Coordinator, MealPlanDayViewControllerDelegate, MealViewControllerDelegate { fileprivate let rootViewController: UIViewController init(rootViewController: UIViewController) { self.rootViewController = rootViewController } public func start() { let graphsViewController = UIViewController() graphsViewController.tabBarItem.image = #imageLiteral(resourceName: "stats") graphsViewController.tabBarItem.title = "Graphs" let mealsViewController = MealPlanDayViewController() mealsViewController.delegate = self mealsViewController.tabBarItem.image = #imageLiteral(resourceName: "meals_gray") mealsViewController.tabBarItem.selectedImage = #imageLiteral(resourceName: "meals") let profileViewController = UIViewController() profileViewController.tabBarItem.image = #imageLiteral(resourceName: "user") profileViewController.tabBarItem.title = "Profile" let tabBarController = SMTabBarController(viewControllers: [graphsViewController, mealsViewController, profileViewController], selectedIndex: 1) rootViewController.present(tabBarController, animated: true, completion: nil) } //MARK:- MealPlanDayViewControllerDelegate public func mealPlanDayViewControllerDidLoad(controller: MealPlanDayViewController) { controller.meals = LocalMeal.samples() } public func mealPlanDayViewControllerShouldLoadMore(controller: MealPlanDayViewController) { } public func mealPlanDayViewControllerMealSelected(_ meal: Meal, controller: MealPlanDayViewController) { let mealViewController = MealViewController(meal: meal) mealViewController.delegate = self controller.present(mealViewController, animated: true, completion: nil) } //MARK:- MealViewControllerDelegate public func mealViewControllerDidLoad(controller: MealViewController) { } public func profileButtonPressed(controller: MealViewController) { } }
28c2e03089bb8a4cced42a7d44898b5c
32.585714
152
0.705657
false
false
false
false
ben-ng/swift
refs/heads/master
test/SILGen/super_init_refcounting.swift
apache-2.0
1
// RUN: %target-swift-frontend -emit-silgen %s | %FileCheck %s class Foo { init() {} init(_ x: Foo) {} init(_ x: Int) {} } class Bar: Foo { // CHECK-LABEL: sil hidden @_TFC22super_init_refcounting3Barc // CHECK: [[SELF_VAR:%.*]] = alloc_box $<τ_0_0> { var τ_0_0 } <Bar> // CHECK: [[PB:%.*]] = project_box [[SELF_VAR]] // CHECK: [[SELF_MUI:%.*]] = mark_uninitialized [derivedself] [[PB]] // CHECK: [[ORIG_SELF:%.*]] = load_borrow [[SELF_MUI]] // CHECK-NOT: copy_value [[ORIG_SELF]] // CHECK: [[ORIG_SELF_UP:%.*]] = upcast [[ORIG_SELF]] // CHECK-NOT: copy_value [[ORIG_SELF_UP]] // CHECK: [[SUPER_INIT:%[0-9]+]] = function_ref @_TFC22super_init_refcounting3FoocfT_S0_ : $@convention(method) (@owned Foo) -> @owned Foo // CHECK: [[NEW_SELF:%.*]] = apply [[SUPER_INIT]]([[ORIG_SELF_UP]]) // CHECK: [[NEW_SELF_DOWN:%.*]] = unchecked_ref_cast [[NEW_SELF]] // CHECK: store [[NEW_SELF_DOWN]] to [init] [[SELF_MUI]] override init() { super.init() } } extension Foo { // CHECK-LABEL: sil hidden @_TFC22super_init_refcounting3Fooc // CHECK: [[SELF_VAR:%.*]] = alloc_box $<τ_0_0> { var τ_0_0 } <Foo> // CHECK: [[PB:%.*]] = project_box [[SELF_VAR]] // CHECK: [[SELF_MUI:%.*]] = mark_uninitialized [delegatingself] [[PB]] // CHECK: [[ORIG_SELF:%.*]] = load_borrow [[SELF_MUI]] // CHECK-NOT: copy_value [[ORIG_SELF]] // CHECK: [[SUPER_INIT:%.*]] = class_method // CHECK: [[NEW_SELF:%.*]] = apply [[SUPER_INIT]]([[ORIG_SELF]]) // CHECK: store [[NEW_SELF]] to [init] [[SELF_MUI]] convenience init(x: Int) { self.init() } } class Zim: Foo { var foo = Foo() // CHECK-LABEL: sil hidden @_TFC22super_init_refcounting3Zimc // CHECK-NOT: copy_value // CHECK-NOT: destroy_value // CHECK: function_ref @_TFC22super_init_refcounting3FoocfT_S0_ : $@convention(method) (@owned Foo) -> @owned Foo } class Zang: Foo { var foo: Foo override init() { foo = Foo() super.init() } // CHECK-LABEL: sil hidden @_TFC22super_init_refcounting4Zangc // CHECK-NOT: copy_value // CHECK-NOT: destroy_value // CHECK: function_ref @_TFC22super_init_refcounting3FoocfT_S0_ : $@convention(method) (@owned Foo) -> @owned Foo } class Bad: Foo { // Invalid code, but it's not diagnosed till DI. We at least shouldn't // crash on it. override init() { super.init(self) } } class Good: Foo { let x: Int // CHECK-LABEL: sil hidden @_TFC22super_init_refcounting4Goodc // CHECK: [[SELF_BOX:%.*]] = alloc_box $<τ_0_0> { var τ_0_0 } <Good> // CHECK: [[PB:%.*]] = project_box [[SELF_BOX]] // CHECK: [[SELF:%.*]] = mark_uninitialized [derivedself] [[PB]] // CHECK: store %0 to [init] [[SELF]] // CHECK: [[SELF_OBJ:%.*]] = load_borrow [[SELF]] // CHECK: [[X_ADDR:%.*]] = ref_element_addr [[SELF_OBJ]] : $Good, #Good.x // CHECK: assign {{.*}} to [[X_ADDR]] : $*Int // CHECK: [[SELF_OBJ:%.*]] = load_borrow [[SELF]] : $*Good // CHECK: [[SUPER_OBJ:%.*]] = upcast [[SELF_OBJ]] : $Good to $Foo // CHECK: [[SUPER_INIT:%.*]] = function_ref @_TFC22super_init_refcounting3FoocfSiS0_ : $@convention(method) (Int, @owned Foo) -> @owned Foo // CHECK: [[SELF_OBJ:%.*]] = load_borrow [[SELF]] // CHECK: [[X_ADDR:%.*]] = ref_element_addr [[SELF_OBJ]] : $Good, #Good.x // CHECK: [[X:%.*]] = load [trivial] [[X_ADDR]] : $*Int // CHECK: apply [[SUPER_INIT]]([[X]], [[SUPER_OBJ]]) override init() { x = 10 super.init(x) } }
15bc96a1882a418acfae5076dd7105be
38.688172
149
0.535085
false
false
false
false
HassanEskandari/Eureka
refs/heads/master
Pods/Eureka/Source/Rows/SliderRow.swift
apache-2.0
3
// SliderRow.swift // Eureka ( https://github.com/xmartlabs/Eureka ) // // Copyright (c) 2016 Xmartlabs ( http://xmartlabs.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 cell of the SliderRow open class SliderCell: Cell<Float>, CellType { private var awakeFromNibCalled = false @IBOutlet open weak var titleLabel: UILabel! @IBOutlet open weak var valueLabel: UILabel! @IBOutlet open weak var slider: UISlider! open var formatter: NumberFormatter? public required init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: .value1, reuseIdentifier: reuseIdentifier) NotificationCenter.default.addObserver(forName: Notification.Name.UIContentSizeCategoryDidChange, object: nil, queue: nil) { [weak self] _ in guard let me = self else { return } if me.shouldShowTitle { me.titleLabel = me.textLabel me.valueLabel = me.detailTextLabel me.addConstraints() } } } deinit { guard !awakeFromNibCalled else { return } NotificationCenter.default.removeObserver(self, name: Notification.Name.UIContentSizeCategoryDidChange, object: nil) } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) awakeFromNibCalled = true } open override func setup() { super.setup() if !awakeFromNibCalled { // title let title = textLabel textLabel?.translatesAutoresizingMaskIntoConstraints = false textLabel?.setContentHuggingPriority(UILayoutPriority(500), for: .horizontal) self.titleLabel = title let value = detailTextLabel value?.translatesAutoresizingMaskIntoConstraints = false value?.setContentHuggingPriority(UILayoutPriority(500), for: .horizontal) self.valueLabel = value let slider = UISlider() slider.translatesAutoresizingMaskIntoConstraints = false slider.setContentHuggingPriority(UILayoutPriority(500), for: .horizontal) self.slider = slider if shouldShowTitle { contentView.addSubview(titleLabel) contentView.addSubview(valueLabel!) } contentView.addSubview(slider) addConstraints() } selectionStyle = .none slider.minimumValue = sliderRow.minimumValue slider.maximumValue = sliderRow.maximumValue slider.addTarget(self, action: #selector(SliderCell.valueChanged), for: .valueChanged) } open override func update() { super.update() titleLabel.text = row.title valueLabel.text = row.displayValueFor?(row.value) valueLabel.isHidden = !shouldShowTitle && !awakeFromNibCalled titleLabel.isHidden = valueLabel.isHidden slider.value = row.value ?? 0.0 slider.isEnabled = !row.isDisabled } func addConstraints() { guard !awakeFromNibCalled else { return } let views: [String : Any] = ["titleLabel": titleLabel, "valueLabel": valueLabel, "slider": slider] let metrics = ["vPadding": 12.0, "spacing": 12.0] if shouldShowTitle { contentView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-[titleLabel]-[valueLabel]-|", options: NSLayoutFormatOptions.alignAllLastBaseline, metrics: metrics, views: views)) contentView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-vPadding-[titleLabel]-spacing-[slider]-vPadding-|", options: NSLayoutFormatOptions.alignAllLeft, metrics: metrics, views: views)) } else { contentView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-vPadding-[slider]-vPadding-|", options: NSLayoutFormatOptions.alignAllLeft, metrics: metrics, views: views)) } contentView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-[slider]-|", options: NSLayoutFormatOptions.alignAllLastBaseline, metrics: metrics, views: views)) } @objc func valueChanged() { let roundedValue: Float let steps = Float(sliderRow.steps) if steps > 0 { let stepValue = round((slider.value - slider.minimumValue) / (slider.maximumValue - slider.minimumValue) * steps) let stepAmount = (slider.maximumValue - slider.minimumValue) / steps roundedValue = stepValue * stepAmount + self.slider.minimumValue } else { roundedValue = slider.value } row.value = roundedValue row.updateCell() } var shouldShowTitle: Bool { return row?.title?.isEmpty == false } private var sliderRow: SliderRow { return row as! SliderRow } } /// A row that displays a UISlider. If there is a title set then the title and value will appear above the UISlider. public final class SliderRow: Row<SliderCell>, RowType { public var minimumValue: Float = 0.0 public var maximumValue: Float = 10.0 public var steps: UInt = 20 required public init(tag: String?) { super.init(tag: tag) } }
23d9759f0be00f495624593bcef49dc8
40.384106
222
0.678669
false
false
false
false
banxi1988/BXForm
refs/heads/master
Pod/Classes/Buttons/OutlineButton.swift
mit
1
// // OutlineButton.swift // SubjectEditorDemo // // Created by Haizhen Lee on 15/6/3. // Copyright (c) 2015年 banxi1988. All rights reserved. // import UIKit public enum BXOutlineStyle:Int{ case rounded case oval case semicircle case none } open class OutlineButton: UIButton { public init(style:BXOutlineStyle = .rounded){ super.init(frame: CGRect(x: 0, y: 0, width: 44, height: 44)) outlineStyle = style } open var useTitleColorAsStrokeColor = true { didSet{ updateOutlineColor() } } open var outlineColor:UIColor?{ didSet{ updateOutlineColor() } } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } open var outlineStyle = BXOutlineStyle.rounded{ didSet{ updateOutlinePath() } } open var cornerRadius:CGFloat = 4.0 { didSet{ updateOutlinePath() } } open var lineWidth :CGFloat = 0.5 { didSet{ outlineLayer.lineWidth = lineWidth } } open lazy var maskLayer : CAShapeLayer = { [unowned self] in let maskLayer = CAShapeLayer() maskLayer.frame = self.frame self.layer.mask = maskLayer return maskLayer }() open lazy var outlineLayer : CAShapeLayer = { [unowned self] in let outlineLayer = CAShapeLayer() outlineLayer.frame = self.frame outlineLayer.lineWidth = self.lineWidth outlineLayer.fillColor = UIColor.clear.cgColor outlineLayer.strokeColor = self.currentTitleColor.cgColor self.layer.addSublayer(outlineLayer) return outlineLayer }() open override func layoutSubviews() { super.layoutSubviews() maskLayer.frame = bounds outlineLayer.frame = bounds updateOutlineColor() updateOutlinePath() } fileprivate func updateOutlinePath(){ let path:UIBezierPath switch outlineStyle{ case .rounded: path = UIBezierPath(roundedRect: bounds, cornerRadius: cornerRadius) case .oval: path = UIBezierPath(ovalIn: bounds) case .semicircle: path = UIBezierPath(roundedRect: bounds, cornerRadius: bounds.height * 0.5) case .none: maskLayer.path = nil outlineLayer.path = nil return } maskLayer.path = path.cgPath outlineLayer.path = path.cgPath } fileprivate func updateOutlineColor(){ if let color = outlineColor{ outlineLayer.strokeColor = color.cgColor }else if useTitleColorAsStrokeColor{ outlineLayer.strokeColor = currentTitleColor.cgColor }else{ outlineLayer.strokeColor = tintColor.cgColor } } open override func tintColorDidChange() { super.tintColorDidChange() updateOutlineColor() } }
5ef2520274a3770e38b1e44123fe0cf5
21.441667
81
0.672484
false
false
false
false
wangyaqing/AKNavigation
refs/heads/master
Src/AKExtension.swift
mit
1
// // AKExtension.swift // AKNavigation // // Created by arkin on 27/03/2017. // Copyright © 2017 arkin. All rights reserved. // import UIKit extension UIImage { class public func image(from color:UIColor) -> UIImage { UIGraphicsBeginImageContextWithOptions(CGSize(width:1, height:1), false, 0) let context = UIGraphicsGetCurrentContext() context?.setFillColor(color.cgColor) context?.fill(CGRect(x:0, y:0, width:1, height:1)) let desImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return desImage! } } extension UIColor { class public func hex(from hex: UInt) -> UIColor { let a = CGFloat((hex >> 24) & 0xFF) let r = CGFloat((hex >> 16) & 0xFF) let g = CGFloat((hex >> 8) & 0xFF) let b = CGFloat(hex & 0xFF) return UIColor(red: r / 255.0, green: g / 255.0, blue: b / 255.0, alpha: a / 255.0) } }
1987955631db28a064de67a20c1b13af
28.030303
91
0.617954
false
false
false
false
RxLeanCloud/rx-lean-swift
refs/heads/master
src/RxLeanCloudSwift/Internal/HttpClient/HttpClient.swift
mit
1
// // AlamofireHttpClient.swift // RxLeanCloudSwift // // Created by WuJun on 23/05/2017. // Copyright © 2017 LeanCloud. All rights reserved. // import Foundation import Alamofire import RxSwift import RxAlamofire import RxCocoa public class AlamofireHttpClient: IHttpClient { open static let `default`: AlamofireHttpClient = { return AlamofireHttpClient() }() static let backgroundQueue = DispatchQueue(label: "LeanCloud.AlamofireHttpClient", attributes: .concurrent) public func rxExecute(httpRequest: HttpRequest) -> Observable<HttpResponse> { let manager = self.getAlamofireManager() let method = self.getAlamofireMethod(httpRequest: httpRequest) let urlEncoding = self.getAlamofireUrlEncoding(httpRequest: httpRequest) let escapedString = httpRequest.url.addingPercentEncoding(withAllowedCharacters: NSCharacterSet.urlQueryAllowed) return manager.rx.responseData(method, escapedString!, parameters: nil, encoding: urlEncoding, headers: httpRequest.headers).map { (response, data) -> HttpResponse in let httpResponse = HttpResponse(statusCode: response.statusCode, data: data) RxAVClient.sharedInstance.httpLog(request: httpRequest, response: httpResponse) return httpResponse } } public func syncExecute(httpRequest: HttpRequest) -> HttpResponse { let avResponse = HttpResponse(statusCode: -1, data: nil) let semaphore = DispatchSemaphore(value: 0) let queue = DispatchQueue(label: "cn.leancloud.sdk", qos: .background, attributes: .concurrent, autoreleaseFrequency: .inherit, target: nil) let manager = self.getAlamofireManager() let method = self.getAlamofireMethod(httpRequest: httpRequest) let urlEncoding = self.getAlamofireUrlEncoding(httpRequest: httpRequest) let escapedString = httpRequest.url.addingPercentEncoding(withAllowedCharacters: NSCharacterSet.urlQueryAllowed) let alamofireRequest = manager.request(escapedString!, method: method, parameters: nil, encoding: urlEncoding, headers: httpRequest.headers) alamofireRequest.responseData(queue: queue, completionHandler: { alamofireResponse in switch alamofireResponse.result { case .success(_): if let httpResponse = alamofireResponse.response { avResponse.satusCode = httpResponse.statusCode } else { avResponse.satusCode = 400 } if let data = alamofireResponse.data { avResponse.data = data } case .failure(_): avResponse.satusCode = -1 } semaphore.signal() }) _ = semaphore.wait(timeout: DispatchTime.distantFuture) return avResponse } func asynchronize<Result>(_ task: @escaping () -> Result, completion: @escaping (Result) -> Void) { AVUtility.asynchronize(task, AlamofireHttpClient.backgroundQueue, completion) } public func callbackExecute(httpRequest: HttpRequest, _ completion: @escaping (HttpResponse) -> Void) { self.asynchronize({ self.syncExecute(httpRequest: httpRequest) }) { result in completion(result) } } func getAlamofireUrlEncoding(httpRequest: HttpRequest) -> ParameterEncoding { let methodUpperCase = httpRequest.method.uppercased() switch methodUpperCase { case "GET": return URLEncoding.default case "DELETE": return URLEncoding.default case "POST": return HttpBodyEncoding.data(data: httpRequest.data!) case "PUT": return HttpBodyEncoding.data(data: httpRequest.data!) default: return JSONEncoding.default } } func getAlamofireManager() -> Alamofire.SessionManager { let sessionManager = Alamofire.SessionManager.default return sessionManager } func getAlamofireMethod(httpRequest: HttpRequest) -> Alamofire.HTTPMethod { let methodUpperCase = httpRequest.method.uppercased() switch methodUpperCase { case "POST": return Alamofire.HTTPMethod.post case "PUT": return Alamofire.HTTPMethod.put case "DELETE": return Alamofire.HTTPMethod.delete default: return Alamofire.HTTPMethod.get } } } enum HttpBodyEncoding: ParameterEncoding { case data(data: Data) func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest { switch self { case .data(let data): var request = try urlRequest.asURLRequest() request.httpBody = data return request // default: // return urlRequest } } }
8acdb892c4e62d6d0f518093f246976a
38.560976
174
0.661734
false
false
false
false
soapyigu/LeetCode_Swift
refs/heads/master
LinkedList/RemoveDuplicatesFromSortedList.swift
mit
1
/** * Question Link: https://leetcode.com/problems/remove-duplicates-from-sorted-list/ * Primary idea: Iterate the list, jump over duplicates by replacing next with next.next * Time Complexity: O(n), Space Complexity: O(1) * * Definition for singly-linked list. * public class ListNode { * public var val: Int * public var next: ListNode? * public init(_ val: Int) { * self.val = val * self.next = nil * } * } */ class RemoveDuplicatesFromSortedList { func deleteDuplicates(_ head: ListNode?) -> ListNode? { guard let head = head else { return nil } var curt = head while curt.next != nil { if curt.next!.val == curt.val { curt.next = curt.next!.next } else { curt = curt.next! } } return head } }
0e130d38d690c3788f160ea303546116
24.828571
88
0.539313
false
false
false
false
lyft/SwiftLint
refs/heads/master
Source/SwiftLintFramework/Rules/RuleConfigurations/PrivateOutletRuleConfiguration.swift
mit
1
import Foundation public struct PrivateOutletRuleConfiguration: RuleConfiguration, Equatable { var severityConfiguration = SeverityConfiguration(.warning) var allowPrivateSet = false public var consoleDescription: String { return severityConfiguration.consoleDescription + ", allow_private_set: \(allowPrivateSet)" } public init(allowPrivateSet: Bool) { self.allowPrivateSet = allowPrivateSet } public mutating func apply(configuration: Any) throws { guard let configuration = configuration as? [String: Any] else { throw ConfigurationError.unknownConfiguration } allowPrivateSet = (configuration["allow_private_set"] as? Bool == true) if let severityString = configuration["severity"] as? String { try severityConfiguration.apply(configuration: severityString) } } } public func == (lhs: PrivateOutletRuleConfiguration, rhs: PrivateOutletRuleConfiguration) -> Bool { return lhs.allowPrivateSet == rhs.allowPrivateSet && lhs.severityConfiguration == rhs.severityConfiguration }
e9399b3cbe49f3f3167bc4acf85d0930
34.15625
99
0.705778
false
true
false
false
tokyovigilante/CesiumKit
refs/heads/master
CesiumKit/Core/Interval.swift
apache-2.0
1
// // Interval.swift // CesiumKit // // Created by Ryan Walklin on 7/06/14. // Copyright (c) 2014 Test Toast. All rights reserved. // /** * Represents the closed interval [start, stop]. * @alias Interval * @constructor * * @param {Number} [start=0.0] The beginning of the interval. * @param {Number} [stop=0.0] The end of the interval. */ struct Interval: Equatable { /** * The beginning of the interval. * @type {Number} * @default 0.0 */ var start = 0.0 /** * The end of the interval. * @type {Number} * @default 0.0 */ var stop = 0.0 } func == (lhs: Interval, rhs: Interval) -> Bool { return lhs.start == rhs.start && lhs.stop == rhs.stop }
a58f6c411546aa4c4051ca27e46ea20d
19.647059
60
0.595442
false
false
false
false
EasySwift/EasySwift
refs/heads/master
Carthage/Checkouts/YXJSlideBar/YXJSlideBar/YXJSlideBar/ViewController1.swift
apache-2.0
2
// // TableViewController.swift // YXJSlideBarTest // // Created by yuanxiaojun on 16/8/10. // Copyright © 2016年 袁晓钧. All rights reserved. // import UIKit import YXJSlideBar class ViewController1: UIViewController, YXJSlideContentViewDataSource { fileprivate var slideBar: YXJSlideBar! fileprivate var contentView: YXJSlideContentView! fileprivate var vcs = [ UIViewController(), UIViewController(), UIViewController(), UIViewController(), UIViewController(), UIViewController(), UIViewController(), UIViewController(), UIViewController(), UIViewController()] override func viewDidLoad() { super.viewDidLoad() // 菜单2 self.slideBar = YXJSlideBar(frame: CGRect(x: 0, y: 50, width: ScreenWidth, height: 50)) self.slideBar.backgroundColor = UIColor.groupTableViewBackground self.slideBar.itemsTitle = ["选项1", "选项2", "选项3", "选项4", "选项5", "选项6", "选项7", "选项8", "选项9", "选项10"] self.slideBar.itemColor = UIColor.gray self.slideBar.itemSelectedColor = UIColor.red self.slideBar.sliderColor = UIColor.red self.slideBar.slideBarItemSelectedCallback { [weak self](idx) -> Void in print(idx) self?.contentView.scroll(to: idx) } self.view.addSubview(self.slideBar) self.contentView = YXJSlideContentView(frame: CGRect(x: 0, y: 100, width: ScreenWidth, height: 300)) self.contentView.dataSource = self self.contentView.setIsEnableScroll(true) self.contentView.slideContentViewScrollFinished { [weak self](idx) in print(idx) self?.slideBar.selectItem(at: idx) } self.view.addSubview(contentView) vcs[0].view.backgroundColor = UIColor.red vcs[1].view.backgroundColor = UIColor.black vcs[2].view.backgroundColor = UIColor.darkGray vcs[3].view.backgroundColor = UIColor.lightGray vcs[4].view.backgroundColor = UIColor.green vcs[5].view.backgroundColor = UIColor.blue vcs[6].view.backgroundColor = UIColor.cyan vcs[7].view.backgroundColor = UIColor.yellow vcs[8].view.backgroundColor = UIColor.magenta vcs[9].view.backgroundColor = UIColor.orange } // MARK:YXJSlideContentViewDataSource func slideContentView(_ contentView: YXJSlideContentView!, viewControllerFor index: UInt) -> UIViewController! { return vcs[Int(index)] } func numOfContentView() -> Int { return vcs.count } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } }
c5c4f6150cc9a9f015e509273f0a0d14
34.958904
116
0.666667
false
false
false
false
nessBautista/iOSBackup
refs/heads/master
RxSwift_01/Pods/SwiftLocation/Sources/SwiftLocation/LocationTracker.swift
cc0-1.0
2
/* * SwiftLocation * Easy and Efficent Location Tracker for Swift * * Created by: Daniele Margutti * Email: [email protected] * Web: http://www.danielemargutti.com * Twitter: @danielemargutti * * Copyright © 2017 Daniele Margutti * * * 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 MapKit import CoreLocation /// Singleton instance for location tracker public let Location = LocationTracker.shared /// Location tracker class public final class LocationTracker: NSObject, CLLocationManagerDelegate { public typealias RequestPoolDidChange = ((Any) -> (Void)) public typealias LocationTrackerSettingsDidChange = ((TrackerSettings) -> (Void)) public typealias LocationDidChange = ((CLLocation) -> (Void)) /// This is a reference to LocationManager's singleton where the main queue for Requests. static let shared : LocationTracker = { // CLLocationManager must be created on main thread otherwise // it will generate an error at init time. if Thread.isMainThread { return LocationTracker() } else { return DispatchQueue.main.sync { return LocationTracker() } } }() /// Initialize func private override init() { self.locationManager = CLLocationManager() super.init() self.locationManager.delegate = self // Listen for any change (add or remove) into all queues let onAddHandler: ((Any) -> (Void)) = { self.onAddNewRequest?($0) } let onRemoveHandler: ((Any) -> (Void)) = { self.onRemoveRequest?($0) } for var pool in self.pools { pool.onAdd = onAddHandler pool.onRemove = onRemoveHandler } } public override var description: String { let countRunning: Int = self.pools.reduce(0, { $0 + $1.countRunning }) let countPaused: Int = self.pools.reduce(0, { $0 + $1.countPaused }) let countAll: Int = self.pools.reduce(0, { $0 + $1.count }) var status = "Requests: \(countRunning)/\(countAll) (\(countPaused) paused)" if let settings = self.locationSettings { status += "\nSettings:\(settings)" } else { status += "\nSettings: services off" } return status } /// Callback called when a new request is added public var onAddNewRequest: RequestPoolDidChange? = nil /// Callback called when a request was removed public var onRemoveRequest: RequestPoolDidChange? = nil /// Called when location manager settings did change public var onChangeTrackerSettings: LocationTrackerSettingsDidChange? = nil /// On Receive new location public var onReceiveNewLocation: LocationDidChange? = nil /// Internal location manager reference internal var locationManager: CLLocationManager /// Queued requests regarding location services private var locationRequests: RequestsQueue<LocationRequest> = RequestsQueue() /// Queued requests regarding reverse geocoding services private var geocoderRequests: RequestsQueue<GeocoderRequest> = RequestsQueue() /// Queued requests regarding heading services private var headingRequests: RequestsQueue<HeadingRequest> = RequestsQueue() /// Queued requests regarding region monitor services private var regionRequests: RequestsQueue<RegionRequest> = RequestsQueue() /// Queued requests regarding visits private var visitRequests: RequestsQueue<VisitsRequest> = RequestsQueue() /// This represent the status of the authorizations before a change private var lastStatus: CLAuthorizationStatus = CLAuthorizationStatus.notDetermined /// `true` if location is deferred private(set) var isDeferred: Bool = false /// This represent the last locations received (best accurated location and last received location) public private(set) var lastLocation = LastLocation() /// Active CoreLocation settings based upon running requests private var _locationSettings: TrackerSettings? private(set) var locationSettings: TrackerSettings? { set { guard let settings = newValue else { locationManager.stopAllLocationServices() _locationSettings = newValue return } if _locationSettings == newValue { return // ignore equal settings, avoid multiple sets } _locationSettings = newValue // Set attributes for CLLocationManager instance locationManager.activityType = settings.activity // activity type (used to better preserve battery based upon activity) locationManager.desiredAccuracy = settings.accuracy.level // accuracy (used to preserve battery based upon update frequency) locationManager.distanceFilter = settings.distanceFilter self.onChangeTrackerSettings?(settings) switch settings.frequency { case .significant: guard CLLocationManager.significantLocationChangeMonitoringAvailable() else { locationManager.stopAllLocationServices() return } // If best frequency is significant location update (and hardware supports it) then start only significant location update locationManager.stopUpdatingLocation() locationManager.allowsBackgroundLocationUpdates = true locationManager.startMonitoringSignificantLocationChanges() case .deferredUntil(_,_,_): locationManager.stopMonitoringSignificantLocationChanges() locationManager.allowsBackgroundLocationUpdates = true locationManager.startUpdatingLocation() default: locationManager.stopMonitoringSignificantLocationChanges() locationManager.allowsBackgroundLocationUpdates = false locationManager.startUpdatingLocation() locationManager.disallowDeferredLocationUpdates() } } get { return _locationSettings } } /// Asks whether the heading calibration alert should be displayed. /// This method is called in an effort to calibrate the onboard hardware used to determine heading values. /// Typically at the following times: /// - The first time heading updates are ever requested /// - When Core Location observes a significant change in magnitude or inclination of the observed magnetic field /// /// If true from this method, Core Location displays the heading calibration alert on top of the current window. /// The calibration alert prompts the user to move the device in a particular pattern so that Core Location can /// distinguish between the Earth’s magnetic field and any local magnetic fields. /// The alert remains visible until calibration is complete or until you explicitly dismiss it by calling the /// dismissHeadingCalibrationDisplay() method. public var displayHeadingCalibration: Bool = true /// When `true` this property is a good way to improve battery life. /// This function also scan for any running Request's `activityType` and see if location data is unlikely to change. /// If yes (for example when user stops for food while using a navigation app) the location manager might pause updates /// for a period of time. /// By default is set to `false`. public var autoPauseUpdates: Bool = false { didSet { locationManager.pausesLocationUpdatesAutomatically = autoPauseUpdates } } /// The device orientation to use when computing heading values. /// When computing heading values, the location manager assumes that the top of the device in portrait mode represents /// due north (0 degrees) by default. For apps that run in other orientations, this may not always be the most convenient /// orientation. /// /// This property allows you to specify which device orientation you want the location manager to use as the reference /// point for due north. /// /// Although you can set the value of this property to unknown, faceUp, or faceDown, doing so has no effect on the /// orientation reference point. The original reference point is retained instead. /// Changing the value in this property affects only those heading values reported after the change is made. public var headingOrientation: CLDeviceOrientation { set { locationManager.headingOrientation = headingOrientation } get { return locationManager.headingOrientation } } /// You can use this method to dismiss it after an appropriate amount of time to ensure that your app’s user interface /// is not unduly disrupted. public func dismissHeadingCalibrationDisplay() { locationManager.dismissHeadingCalibrationDisplay() } // MARK: - Get location /// Create and enque a new location tracking request /// /// - Parameters: /// - accuracy: accuracy of the location request (it may affect device's energy consumption) /// - frequency: frequency of the location retrive process (it may affect device's energy consumption) /// - timeout: optional timeout. If no location were found before timeout a `LocationError.timeout` error is reported. /// - success: success handler to call when a new location were found for this request /// - error: error handler to call when an error did occour while searching for request /// - cancelOnError: if `true` request will be cancelled when first error is received (both timeout or location service error) /// - Returns: request @discardableResult public func getLocation(accuracy: Accuracy, frequency: Frequency, timeout: TimeInterval? = nil, cancelOnError: Bool = false, success: @escaping LocObserver.onSuccess, error: @escaping LocObserver.onError) -> LocationRequest { let req = LocationRequest(accuracy: accuracy, frequency: frequency, success, error) req.timeout = timeout req.cancelOnError = cancelOnError req.resume() return req } /// Create and enqueue a new reverse geocoding request for an input address string /// /// - Parameters: /// - address: address string to reverse /// - region: A geographical region to use as a hint when looking up the specified address. /// Specifying a region lets you prioritize the returned set of results to locations that are close to some /// specific geographical area, which is typically the user’s current location. /// - timeout: timeout of the operation; nil to ignore timeout, a valid seconds interval. If reverse geocoding does not succeded or /// fail inside this time interval request fails with `LocationError.timeout` error and registered callbacks are called. /// - cancelOnError: if `true` request will be cancelled when first error is received (both timeout or location service error) /// /// - success: success handler to call when reverse geocoding succeded /// - failure: failure handler to call when reverse geocoding fails /// - Returns: request @discardableResult public func getLocation(forAddress address: String, inRegion region: CLRegion? = nil, timeout: TimeInterval? = nil, cancelOnError: Bool = false, success: @escaping GeocoderObserver.onSuccess, failure: @escaping GeocoderObserver.onError) -> GeocoderRequest { let req = GeocoderRequest(address: address, region: region, success, failure) req.timeout = timeout req.cancelOnError = cancelOnError req.resume() return req } /// Create and enqueue a new reverse geocoding request for an instance of `CLLocation` object. /// /// - Parameters: /// - location: location to reverse /// - timeout: timeout of the operation; nil to ignore timeout, a valid seconds interval. If reverse geocoding does not succeded or /// fail inside this time interval request fails with `LocationError.timeout` error and registered callbacks are called. /// - success: success handler to call when reverse geocoding succeded /// - failure: failure handler to call when reverse geocoding fails /// - Returns: request @discardableResult public func getPlacemark(forLocation location: CLLocation, timeout: TimeInterval? = nil, success: @escaping GeocoderObserver.onSuccess, failure: @escaping GeocoderObserver.onError) -> GeocoderRequest { let req = GeocoderRequest(location: location, success, failure) req.timeout = timeout req.resume() return req } /// Create and enqueue a new reverse geocoding request for an Address Book `Dictionary` object. /// /// - Parameters: /// - dict: address book dictionary /// - timeout: timeout of the operation; nil to ignore timeout, a valid seconds interval. If reverse geocoding does not succeded or /// fail inside this time interval request fails with `LocationError.timeout` error and registered callbacks are called. /// - success: success handler to call when reverse geocoding succeded /// - failure: failure handler to call when reverse geocoding fails /// - Returns: request @discardableResult public func getLocation(forABDictionary dict: [AnyHashable: Any], timeout: TimeInterval? = nil, success: @escaping GeocoderObserver.onSuccess, failure: @escaping GeocoderObserver.onError) -> GeocoderRequest { let req = GeocoderRequest(abDictionary: dict, success, failure) req.timeout = timeout req.resume() return req } // MARK: - Get heading /// Allows you to receive heading update with a minimum filter degree /// /// - Parameters: /// - filter: The minimum angular change (measured in degrees) required to generate new heading events. /// - cancelOnError: if `true` request will be cancelled when first error is received (both timeout or location service error) /// - success: succss handler /// - failure: failure handler /// - Returns: request @discardableResult public func getContinousHeading(filter: CLLocationDegrees, cancelOnError: Bool = false, success: @escaping HeadingObserver.onSuccess, failure: @escaping HeadingObserver.onError) throws -> HeadingRequest { let request = try HeadingRequest(filter: filter, success: success, failure: failure) request.resume() request.cancelOnError = cancelOnError return request } // MARK: - Monitor geographic location /// Monitor a geographic region identified by a center coordinate and a radius. /// Region monitoring /// /// - Parameters: /// - center: coordinate center /// - radius: radius in meters /// - cancelOnError: if `true` request will be cancelled when first error is received (both timeout or location service error) /// - enter: callback for region enter event /// - exit: callback for region exit event /// - error: callback for errors /// - Returns: request /// - Throws: throw `LocationError.serviceNotAvailable` if hardware does not support region monitoring @discardableResult public func monitor(regionAt center: CLLocationCoordinate2D, radius: CLLocationDistance, cancelOnError: Bool = false, enter: RegionObserver.onEvent?, exit: RegionObserver.onEvent?, error: @escaping RegionObserver.onFailure) throws -> RegionRequest { let request = try RegionRequest(center: center, radius: radius, onEnter: enter, onExit: exit, error: error) request.resume() request.cancelOnError = cancelOnError return request } /// Monitor a specified region /// /// - Parameters: /// - region: region to monitor /// - cancelOnError: if `true` request will be cancelled when first error is received (both timeout or location service error) /// - enter: callback for region enter event /// - exit: callback for region exit event /// - error: callback for errors /// - error: callback for errors /// - Throws: throw `LocationError.serviceNotAvailable` if hardware does not support region monitoring @discardableResult public func monitor(region: CLCircularRegion, cancelOnError: Bool = false, enter: RegionObserver.onEvent?, exit: RegionObserver.onEvent?, error: @escaping RegionObserver.onFailure) throws -> RegionRequest { let request = try RegionRequest(region: region, onEnter: enter, onExit: exit, error: error) request.cancelOnError = cancelOnError request.resume() return request } /// Calling this method begins the delivery of visit-related events to your app. /// Enabling visit events for one location manager enables visit events for all other location manager objects in your app. /// When a new visit event arrives callback is called and request still alive until removed. /// This service require always authorization. /// /// - Parameters: /// - event: callback called when a new visit arrive /// - error: callback called when an error occours /// - Returns: request /// - Throws: throw an exception if app does not support alway authorization @discardableResult public func monitorVisit(event: @escaping VisitObserver.onVisit, error: @escaping VisitObserver.onFailure) throws -> VisitsRequest { let request = try VisitsRequest(event: event, error: error) request.resume() return request } //MARK: - Register/Unregister location requests /// Register a new request and enqueue it /// /// - Parameter request: request to enqueue /// - Returns: `true` if added correctly to the queue, `false` otherwise. public func start<T: Request>(_ requests: T...) { var hasChanges = false for request in requests { // Location Requests if let request = request as? LocationRequest { request._state = .running if locationRequests.add(request) { hasChanges = true } } // Geocoder Requests if let request = request as? GeocoderRequest { request._state = .running if geocoderRequests.add(request) { hasChanges = true } } // Heading requests if let request = request as? HeadingRequest { request._state = .running if headingRequests.add(request) { hasChanges = true } } // Region Monitoring requests if let request = request as? RegionRequest { request._state = .running if regionRequests.add(request) { hasChanges = true } } } if hasChanges { requests.forEach { $0.onResume() } self.updateServicesStatus() } } /// Unregister and stops a queued request /// /// - Parameter request: request to remove /// - Returns: `true` if request was removed successfully, `false` if it's not part of the queue public func cancel<T: Request>(_ requests: T...) { var hasChanges = false for request in requests { if self.isQueued(request) == false { continue } // Location Requests if let request = request as? LocationRequest { request._state = .idle locationRequests.remove(request) hasChanges = true } // Geocoder requests if let request = request as? GeocoderRequest { request._state = .idle geocoderRequests.remove(request) hasChanges = true } // Heading requests if let request = request as? HeadingRequest { request._state = .idle headingRequests.remove(request) hasChanges = true } // Region Monitoring requests if let request = request as? RegionRequest { request._state = .idle locationManager.stopMonitoring(for: request.region) regionRequests.remove(request) hasChanges = true } } if hasChanges == true { self.updateServicesStatus() requests.forEach { $0.onCancel() } } } /// Pause any passed queued reques /// /// - Parameter requests: requests to pause public func pause<T: Request>(_ requests: T...) { var hasChanges = false for request in requests { if self.isQueued(request) == false { continue } if self.isQueued(request) && request.state.isRunning { // Location requests if let request = request as? LocationRequest { request._state = .paused hasChanges = true } // Geocoder requests if let request = request as? GeocoderRequest { request._state = .paused hasChanges = true } // Heading requests if let request = request as? HeadingRequest { request._state = .paused hasChanges = true } // Region Monitoring requests if let request = request as? RegionRequest { locationManager.stopMonitoring(for: request.region) request._state = .paused hasChanges = true } } } if hasChanges == true { self.updateServicesStatus() requests.forEach { $0.onPause() } } } /// Return `true` if target `request` is part of a queue. /// /// - Parameter request: target request /// - Returns: `true` if request is in a queue, `false` otherwise internal func isQueued<T: Request>(_ request: T?) -> Bool { guard let request = request else { return false } // Location Request if let request = request as? LocationRequest { return locationRequests.isQueued(request) } // Geocoder Request if let request = request as? GeocoderRequest { return geocoderRequests.isQueued(request) } // Heading Request if let request = request as? HeadingRequest { return headingRequests.isQueued(request) } // Region Request if let request = request as? RegionRequest { return regionRequests.isQueued(request) } return false } //MARK: CLLocationManager Visits Delegate public func locationManager(_ manager: CLLocationManager, didVisit visit: CLVisit) { self.visitRequests.dispatch(value: visit) } //MARK: CLLocationManager Region Monitoring Delegate public func locationManager(_ manager: CLLocationManager, didStartMonitoringFor region: CLRegion) { let region = self.regionRequests.filter { $0.region == region }.first region?.onStartMonitoring?() } public func locationManager(_ manager: CLLocationManager, monitoringDidFailFor region: CLRegion?, withError error: Error) { let region = self.regionRequests.filter { $0.region == region }.first region?.dispatch(error: error) } public func locationManager(_ manager: CLLocationManager, didEnterRegion region: CLRegion) { let region = self.regionRequests.filter { $0.region == region }.first region?.dispatch(event: .entered) } public func locationManager(_ manager: CLLocationManager, didExitRegion region: CLRegion) { let region = self.regionRequests.filter { $0.region == region }.first region?.dispatch(event: .exited) } public func locationManager(_ manager: CLLocationManager, didDetermineState state: CLRegionState, for region: CLRegion) { let region = self.regionRequests.filter { $0.region == region }.first region?.dispatch(state: state) } //MARK: - Internal Heading Manager Func public func locationManager(_ manager: CLLocationManager, didUpdateHeading newHeading: CLHeading) { self.headingRequests.dispatch(value: newHeading) } public func locationManagerShouldDisplayHeadingCalibration(_ manager: CLLocationManager) -> Bool { return self.displayHeadingCalibration } //MARK: Internal Location Manager Func /// Set the request's `state` for any queued requests which is in one the following states /// /// - Parameters: /// - newState: new state to set /// - states: request's allowed state to be changed private func loc_setRequestState(_ newState: RequestState, forRequestsIn states: Set<RequestState>) { locationRequests.forEach { if states.contains($0.state) { $0._state = newState } } } //MARK: - Deferred Location Helper Funcs private var isDeferredAvailable: Bool { // Seems `deferredLocationUpdatesAvailable()` function does not work properly in iOS 10 // It's not clear if it's a bug or not. // Som elinks about the topic: // https://github.com/zakishaheen/deferred-location-implementation // http://stackoverflow.com/questions/39498899/deferredlocationupdatesavailable-returns-no-in-ios-10 // https://github.com/lionheart/openradar-mirror/issues/15939 // // Moreover activating deferred locations causes didFinishDeferredUpdatesWithError to be called with kCLErrorDeferredFailed if #available(iOS 10, *) { return true } else { return CLLocationManager.deferredLocationUpdatesAvailable() } } /// Evaluate deferred location best settings /// /// - Returns: settings to apply private func deferredLocationSettings() -> (meters: Double, timeout: TimeInterval, accuracy: Accuracy)? { var meters: Double? = nil var timeout: TimeInterval? = nil var accuracyIsNavigation: Bool = false self.locationRequests.forEach { if case let .deferredUntil(rMt,rTime,rAcc) = $0.frequency { if meters == nil || (rMt < meters!) { meters = rMt } if timeout == nil || (rTime < timeout!) { timeout = rTime } if rAcc == true { accuracyIsNavigation = true } } } let accuracy = (accuracyIsNavigation ? Accuracy.navigation : Accuracy.room) return (meters == nil ? nil : (meters!,timeout!, accuracy)) } /// Turn on and off deferred location updated if needed private func turnOnOrOffDeferredLocationUpdates() { // Turn on/off deferred location updates if let defSettings = deferredLocationSettings() { if self.isDeferred == false { locationManager.desiredAccuracy = defSettings.accuracy.level locationManager.allowsBackgroundLocationUpdates = true locationManager.pausesLocationUpdatesAutomatically = true locationManager.allowDeferredLocationUpdates(untilTraveled: defSettings.meters, timeout: defSettings.timeout) self.isDeferred = true } } else { if self.isDeferred { locationManager.disallowDeferredLocationUpdates() self.isDeferred = false } } } //MARK: - Location Tracking Helper Funcs /// Evaluate best settings based upon running location requests /// /// - Returns: best settings private func locationTrackingBestSettings() -> TrackerSettings? { guard locationRequests.countRunning > 0 else { return nil // no settings, location manager can be disabled } var accuracy: Accuracy = .any var frequency: Frequency = .significant var type: CLActivityType = .other var distanceFilter: CLLocationDistance? = kCLDistanceFilterNone for request in locationRequests { guard request.state.isRunning else { continue // request is not running, can be ignored } if request.accuracy.orderValue > accuracy.orderValue { accuracy = request.accuracy } if request.frequency < frequency { frequency = request.frequency } if request.activity.rawValue > type.rawValue { type = request.activity } if request.minimumDistance == nil { // If mimumDistance is nil it's equal to `kCLDistanceFilterNone` and it will // reports all movements regardless measured distance distanceFilter = nil } else { // Otherwise if distanceFilter is higher than `kCLDistanceFilterNone` and our value is less than // the current value, we want to store it. Lower value is the setting. if distanceFilter != nil && request.minimumDistance! < distanceFilter! { distanceFilter = request.minimumDistance! } } } if distanceFilter == nil { // translate it to the right value. `kCLDistanceFilterNone` report all movements // regardless the horizontal distance measured. distanceFilter = kCLDistanceFilterNone } // Deferred location updates // Because deferred updates use the GPS to track location changes, // the location manager allows deferred updates only when GPS hardware // is available on the device and when the desired accuracy is set to kCLLocationAccuracyBest // or kCLLocationAccuracyBestForNavigation. // - A) If the GPS hardware is not available, the location manager reports a deferredFailed error. // - B) If the accuracy is not set to one of the supported values, the location manager reports a deferredAccuracyTooLow error. // - C) In addition, the distanceFilter property of the location manager must be set to kCLDistanceFilterNone. // If it is set to any other value, the location manager reports a deferredDistanceFiltered error. if isDeferredAvailable, let deferredSettings = self.deferredLocationSettings() { // has any deferred location request accuracy = deferredSettings.accuracy // B) distanceFilter = kCLDistanceFilterNone // C) let isNavigationAccuracy = (deferredSettings.accuracy.level == kCLLocationAccuracyBestForNavigation) frequency = .deferredUntil(distance: deferredSettings.meters, timeout: deferredSettings.timeout, navigation: isNavigationAccuracy) } return TrackerSettings(accuracy: accuracy, frequency: frequency, activity: type, distanceFilter: distanceFilter!) } //MARK: - CLLocationManager Location Tracking Delegate @objc open func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) { locationRequests.forEach { $0.dispatchAuthChange(self.lastStatus, status) } self.lastStatus = status switch status { case .denied, .restricted: let error = LocationError.authDidChange(status) self.pools.forEach { $0.dispatch(error: error) } self.updateServicesStatus() case .authorizedAlways, .authorizedWhenInUse: self.pools.forEach { $0.resumeWaitingAuth() } self.updateServicesStatus() default: break } } @objc public func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { guard let location = locations.last else { return } self.onReceiveNewLocation?(location) // Note: // We need to start the deferred location delivery (by calling allowDeferredLocationUpdates) after // the first location is arrived. So if this is the first location we have received and we have // running deferred location request we can start it. if self.lastLocation.last != nil { turnOnOrOffDeferredLocationUpdates() } // Store last location self.lastLocation.set(location: location) // Dispatch to any request (which is not of type deferred) locationRequests.iterate({ return ($0.frequency.isDeferredFrequency == false) }, { $0.dispatch(location: location) }) } //MARK: CLLocationManager Deferred Error Delegate public func locationManager(_ manager: CLLocationManager, didFinishDeferredUpdatesWithError error: Error?) { // iterate over deferred locations locationRequests.iterate({ return $0.frequency.isDeferredFrequency }, { $0.dispatch(error: error ?? LocationError.unknown) }) } //MARK: CLLocationManager Error Delegate @objc open func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) { locationRequests.iterate({ return $0.frequency.isDeferredFrequency }, { $0.dispatch(error: error) }) } //MARK: - Update Services Status /// Update services (turn on/off hardware) based upon running requests private func updateServicesStatus() { let pools = self.pools func updateAllServices() { self.updateLocationServices() self.updateHeadingServices() self.updateRegionMonitoringServices() self.updateVisitsServices() } do { // Check if we need to ask for authorization based upon currently running requests guard try self.requireAuthorizationIfNeeded() == false else { return } // Otherwise we can continue updateAllServices() } catch { // Something went wrong, stop all... self.locationSettings = nil // Dispatch error pools.forEach { $0.dispatch(error: error) } } } private var pools: [RequestsQueueProtocol] { let pools: [RequestsQueueProtocol] = [locationRequests, regionRequests, visitRequests,geocoderRequests,headingRequests] return pools } /// Require authorizations if needed /// /// - Returns: `true` if authorization is needed, `false` otherwise /// - Throws: throw if some required settings are missing private func requireAuthorizationIfNeeded() throws -> Bool { func pauseAllRunningRequest() { // Mark running requests as pending pools.forEach { $0.set(.waitingUserAuth, forRequestsIn: [.running,.idle]) } } // This is the authorization keys set in Info.plist let plistAuth = CLLocationManager.appAuthorization // Get the max authorization between all running request let requiredAuth = self.pools.map({ $0.requiredAuthorization }).reduce(.none, { $0 < $1 ? $0 : $1 }) // This is the current authorization of CLLocationManager let currentAuth = LocAuth.status if requiredAuth == .none { // No authorization are needed return false } switch currentAuth { case .denied,.disabled, .restricted: // Authorization was explicity disabled throw LocationError.authorizationDenided default: if requiredAuth == .always && (currentAuth == .inUseAuthorized || currentAuth == .undetermined) { // We need always authorization but we have in-use authorization if plistAuth != .always && plistAuth != .both { // we have not set the correct plist key to support this auth throw LocationError.missingAuthInInfoPlist } // Okay we can require it pauseAllRunningRequest() locationManager.requestAlwaysAuthorization() return true } if requiredAuth == .inuse && currentAuth == .undetermined { // We have not set not always or in-use auth plist so we can continue if plistAuth != .inuse && plistAuth != .both { throw LocationError.missingAuthInInfoPlist } // require in use authorization pauseAllRunningRequest() locationManager.requestWhenInUseAuthorization() return true } } // We have enough rights to continue without requiring auth return false } // MARK: - Services Update /// Update visiting services internal func updateVisitsServices() { guard visitRequests.countRunning > 0 else { // There is not any running request, we can stop monitoring all regions locationManager.stopMonitoringVisits() return } locationManager.startMonitoringVisits() } /// Update location services based upon running Requests internal func updateLocationServices() { let hasBackgroundRequests = locationRequests.hasBackgroundRequests() guard locationRequests.countRunning > 0 else { // There is not any running request, we can stop location service to preserve battery. self.locationSettings = nil return } // Evaluate best accuracy,frequency and activity type based upon all queued requests guard let bestSettings = self.locationTrackingBestSettings() else { // No need to setup CLLocationManager, stop it. self.locationSettings = nil return } print("Settings \(bestSettings)") // Request authorizations if needed if bestSettings.accuracy.requestUserAuth == true { // Check if device supports location services. // If not dispatch the error to any running request and stop. guard CLLocationManager.locationServicesEnabled() else { locationRequests.forEach { $0.dispatch(error: LocationError.serviceNotAvailable) } return } } // If there is a request which needs background capabilities and we have not set it // dispatch proper error. if hasBackgroundRequests && CLLocationManager.isBackgroundUpdateEnabled == false { locationRequests.forEach { $0.dispatch(error: LocationError.backgroundModeNotSet) } return } // Everything is okay we can setup CLLocationManager based upon the most accuracted/most frequent // Request queued and running. let isAppInBackground = (UIApplication.shared.applicationState == .background && CLLocationManager.isBackgroundUpdateEnabled) self.locationManager.allowsBackgroundLocationUpdates = isAppInBackground if isAppInBackground { self.autoPauseUpdates = false } // Resume any paused request (a paused request is in `.waitingUserAuth`,`.paused` or `.failed`) locationRequests.iterate([.waitingUserAuth]) { $0.resume() } // Setup with best settings self.locationSettings = bestSettings } internal func updateRegionMonitoringServices() { // Region monitoring is not available for this hardware guard CLLocationManager.isMonitoringAvailable(for: CLCircularRegion.self) else { regionRequests.dispatch(error: LocationError.serviceNotAvailable) return } // Region monitoring require always authorizaiton, if not generate error let auth = CLLocationManager.appAuthorization if auth != .always && auth != .both { regionRequests.dispatch(error: LocationError.requireAlwaysAuth) return } guard regionRequests.countRunning > 0 else { // There is not any running request, we can stop monitoring all regions locationManager.stopMonitoringAllRegions() return } // Monitor queued regions regionRequests.forEach { if $0.state.isRunning { locationManager.startMonitoring(for: $0.region) } } } /// Update heading services internal func updateHeadingServices() { // Heading service is not available on current hardware guard CLLocationManager.headingAvailable() else { self.headingRequests.dispatch(error: LocationError.serviceNotAvailable) return } guard headingRequests.countRunning > 0 else { // There is not any running request, we can stop location service to preserve battery. locationManager.stopUpdatingHeading() return } // Find max accuracy in reporting heading and set it var bestHeading: CLLocationDegrees = Double.infinity for request in headingRequests { guard let filter = request.filter else { bestHeading = kCLHeadingFilterNone break } bestHeading = min(bestHeading,filter) } locationManager.headingFilter = bestHeading // Start locationManager.startUpdatingHeading() } }
312915ec5d1c7f0fb25f725781cbe9e7
36.901902
258
0.73352
false
false
false
false
d4rkl0rd3r3b05/Data_Structure_And_Algorithm
refs/heads/master
GeeksForGeeks_Get2MinimumElements.swift
mit
1
/* * Get smaller and smallest element of an array. */ public func get2MinimumElements<T : Comparable>(arrayToBeProcessed : [T]) -> (smaller : T, smallest : T)?{ guard arrayToBeProcessed.count >= 2 else { return nil } var smaller = arrayToBeProcessed[1] var smallest = arrayToBeProcessed[0] for currentElement in arrayToBeProcessed { if smallest > currentElement { smaller = smallest smallest = currentElement } else if (smaller > currentElement && currentElement != smallest) || (smaller == smallest) { smaller = currentElement } } return (smaller: smaller, smallest : smallest) }
fae263c5bd53218d1c1687aad7d5d1c0
27.32
106
0.611582
false
false
false
false
danthorpe/YapDatabaseExtensions
refs/heads/development
Sources/YapDatabaseExtensions.swift
mit
1
// // Created by Daniel Thorpe on 08/04/2015. // import ValueCoding import YapDatabase /** This is a struct used as a namespace for new types to avoid any possible future clashes with `YapDatabase` types. */ public struct YapDB { /** Helper function for building the path to a database for easy use in the YapDatabase constructor. - parameter directory: a NSSearchPathDirectory value, use .DocumentDirectory for production. - parameter name: a String, the name of the sqlite file. - parameter suffix: a String, will be appended to the name of the file. - returns: a String representing the path to a database in the given search directory, with the given name/suffix. */ public static func pathToDatabase(directory: NSSearchPathDirectory, name: String, suffix: String? = .None) -> String { let paths = NSSearchPathForDirectoriesInDomains(directory, .UserDomainMask, true) let directory: String = paths.first ?? NSTemporaryDirectory() let filename: String = { if let suffix = suffix { return "\(name)-\(suffix).sqlite" } return "\(name).sqlite" }() return (directory as NSString).stringByAppendingPathComponent(filename) } /// Type of closure which can perform operations on newly created/opened database instances. public typealias DatabaseOperationsBlock = (YapDatabase) -> Void /** Conveniently create or read a YapDatabase with the given name in the application's documents directory. Optionally, pass a block which receives the database instance, which is called before being returned. This block allows for things like registering extensions. Typical usage in a production environment would be to use this inside a singleton pattern, eg extension YapDB { public static var userDefaults: YapDatabase { get { struct DatabaseSingleton { static func database() -> YapDatabase { return YapDB.databaseNamed("User Defaults") } static let instance = DatabaseSingleton.database() } return DatabaseSingleton.instance } } } which would allow the following behavior in your app: let userDefaultDatabase = YapDB.userDefaults Note that you can only use this convenience if you use the default serializers and sanitizers etc. - parameter name: a String, which will be the name of the SQLite database in the documents folder. - parameter operations: a DatabaseOperationsBlock closure, which receives the database, but is executed before the database is returned. - returns: the YapDatabase instance. */ public static func databaseNamed(name: String, operations: DatabaseOperationsBlock? = .None) -> YapDatabase { let db = YapDatabase(path: pathToDatabase(.DocumentDirectory, name: name, suffix: .None)) operations?(db) return db } /** Conveniently create an empty database for testing purposes in the app's Caches directory. This function should only be used in unit tests, as it will delete any previously existing SQLite file with the same path. It should only be used like this inside your test case. func test_MyUnitTest() { let db = YapDB.testDatabaseForFile(__FILE__, test: __FUNCTION__) // etc etc } func test_GivenInitialData_MyUnitTest(initialDataImport: YapDB.DatabaseOperationsBlock) { let db = YapDB.testDatabaseForFile(__FILE__, test: __FUNCTION__, operations: initialDataImport) // etc etc } - parameter file: a String, which should be the swift special macro __FILE__ - parameter test: a String, which should be the swift special macro __FUNCTION__ - parameter operations: a DatabaseOperationsBlock closure, which receives the database, but is executed before the database is returned. This is very useful if you want to populate the database with some objects before running the test. - returns: the YapDatabase instance. */ public static func testDatabase(file: String = #file, test: String = #function, operations: DatabaseOperationsBlock? = .None) -> YapDatabase { let path = pathToDatabase(.CachesDirectory, name: (file as NSString).lastPathComponent, suffix: test.stringByTrimmingCharactersInSet(NSCharacterSet(charactersInString: "()"))) assert(!path.isEmpty, "Path should not be empty.") do { try NSFileManager.defaultManager().removeItemAtPath(path) } catch { } let db = YapDatabase(path: path) operations?(db) return db } } extension YapDB { /** A database index value type. */ public struct Index { /// The index's collection public let collection: String // The index's key public let key: String /** Create a new Index value. - parameter collection: a String - parameter key: a String */ public init(collection: String, key: String) { self.collection = collection self.key = key } } } // MARK: - Identifiable /** A generic protocol which is used to return a unique identifier for the type. To use `String` type identifiers, use the aliased Identifier type. */ public protocol Identifiable { associatedtype IdentifierType: CustomStringConvertible var identifier: IdentifierType { get } } /** A typealias of String, which implements the Printable protocol. When implementing the Identifiable protocol, use Identifier for your String identifiers. extension Person: Identifiable { let identifier: Identifier } */ public typealias Identifier = String extension Identifier: CustomStringConvertible { public var description: String { return self } } // MARK: - Persistable /** Types which implement Persistable can be used in the functions defined in this framework. It assumes that all instances of a type are stored in the same YapDatabase collection. */ public protocol Persistable: Identifiable { /// The nested type of the metadata. Defaults to Void. associatedtype MetadataType /// The YapDatabase collection name the type is stored in. static var collection: String { get } /// A metadata which is set when reading, and get when writing. var metadata: MetadataType? { get set } } extension Persistable { /** Convenience static function to get an index for a given key with this type's collection. - parameter key: a `String` - returns: a `YapDB.Index` value. */ public static func indexWithKey(key: String) -> YapDB.Index { return YapDB.Index(collection: collection, key: key) } /** Convenience static function to get an array of indexes for an array of keys with this type's collection. - warning: This function will remove any duplicated keys and the order of the indexes is not guaranteed to match the keys. - parameter keys: a sequence of `String`s - returns: an array of `YapDB.Index` values. */ public static func indexesWithKeys< Keys where Keys: SequenceType, Keys.Generator.Element == String>(keys: Keys) -> [YapDB.Index] { return Set(keys).map { YapDB.Index(collection: collection, key: $0) } } /** Default metadata property. Implement this to re-define your own MetadataType. */ public var metadata: Void? { get { return .None } set { } } /** Convenience computed property to get the key for a persistable, which is just the identifier's description. - returns: a String. */ public var key: String { return identifier.description } /** Convenience computed property to get the index for a persistable. - returns: a `YapDB.Index`. */ public var index: YapDB.Index { return self.dynamicType.indexWithKey(key) } } // MARK: Functions public func keyForPersistable<P: Persistable>(persistable: P) -> String { return persistable.key } public func indexForPersistable<P: Persistable>(persistable: P) -> YapDB.Index { return persistable.index } // MARK: - /// A facade interface for a read transaction. public protocol ReadTransactionType { /** Returns all the keys of a collection. - parameter collection: a String. Not optional. - returns: an array of String values. */ func keysInCollection(collection: String) -> [String] /** Read the object at the index. - parameter index: a YapDB.Index. - returns: an `AnyObject` if an item existing in the database for this index. */ func readAtIndex(index: YapDB.Index) -> AnyObject? /** Read the metadata at the index. - parameter index: a YapDB.Index. - returns: an `AnyObject` if a metadata item existing in the database for this index. */ func readMetadataAtIndex(index: YapDB.Index) -> AnyObject? } /// A facade interface for a write transaction. public protocol WriteTransactionType: ReadTransactionType { /** Write the object to the database at the index, including optional metadata. - parameter index: the `YapDB.Index` to write to. - parameter object: the `AnyObject` which will be written. - parameter metadata: an optional `AnyObject` which will be written as metadata. */ func writeAtIndex(index: YapDB.Index, object: AnyObject, metadata: AnyObject?) /** Remove the sequence object from the database at the indexes (if it exists), including metadata - parameter indexes: the `[YapDB.Index]` to remove. */ func removeAtIndexes< Indexes where Indexes: SequenceType, Indexes.Generator.Element == YapDB.Index>(indexes: Indexes) } /// A facade interface for a database connection. public protocol ConnectionType { associatedtype ReadTransaction: ReadTransactionType associatedtype WriteTransaction: WriteTransactionType /** Synchronously reads from the database on the connection. The closure receives the read transaction, and the function returns the result of the closure. This makes it very suitable as a building block for more functional methods. The majority of the wrapped functions provided by these extensions use this as their basis. - parameter block: a closure which receives YapDatabaseReadTransaction and returns T - returns: An instance of T */ func read<T>(block: ReadTransaction -> T) -> T /** Synchronously writes to the database on the connection. The closure receives the read write transaction, and the function returns the result of the closure. This makes it very suitable as a building block for more functional methods. The majority of the wrapped functions provided by these extensions use this as their basis. - parameter block: a closure which receives YapDatabaseReadWriteTransaction and returns T - returns: An instance of T */ func write<T>(block: WriteTransaction -> T) -> T /** Asynchronously reads from the database on the connection. The closure receives the read transaction, and completion block receives the result of the closure. This makes it very suitable as a building block for more functional methods. The majority of the wrapped functions provided by these extensions use this as their basis. The completion block is run on the given `queue`. - parameter block: a closure which receives YapDatabaseReadTransaction and returns T - parameter queue: a dispatch_queue_t, defaults to main queue, can be ommitted in most cases. - parameter completion: a closure which receives T and returns Void. */ func asyncRead<T>(block: ReadTransaction -> T, queue: dispatch_queue_t, completion: (T) -> Void) /** Asynchronously writes to the database on the connection. The closure receives the read write transaction, and completion block receives the result of the closure. This makes it very suitable as a building block for more functional methods. The majority of the wrapped functions provided by these extensions use this as their basis. The completion block is run on the given `queue`. - parameter block: a closure which receives YapDatabaseReadWriteTransaction and returns T - parameter queue: a dispatch_queue_t, defaults to main queue, can be ommitted in most cases. - parameter completion: a closure which receives T and returns Void. */ func asyncWrite<T>(block: WriteTransaction -> T, queue: dispatch_queue_t, completion: (T -> Void)?) /** Execute a read/write block inside a `NSOperation`. The block argument receives a `YapDatabaseReadWriteTransaction`. This method is very handy for writing different item types to the database inside the same transaction. For example let operation = connection.writeBlockOperation { transaction in people.write.on(transaction) barcode.write.on(transaction) } queue.addOperation(operation) - parameter block: a closure of type (YapDatabaseReadWriteTransaction) -> Void - returns: an `NSOperation`. */ func writeBlockOperation(block: WriteTransaction -> Void) -> NSOperation } /// A facade interface for a database. public protocol DatabaseType { associatedtype Connection: ConnectionType func makeNewConnection() -> Connection } internal enum Handle<D: DatabaseType> { case Transaction(D.Connection.ReadTransaction) case Connection(D.Connection) case Database(D) } // MARK: - YapDatabaseReadTransaction extension YapDatabaseReadTransaction: ReadTransactionType { /** Returns all the keys in a collection from the database - parameter collection: a String. - returns: an array of String values. */ public func keysInCollection(collection: String) -> [String] { return allKeysInCollection(collection) } /** Reads the object sored at this index using the transaction. - parameter index: The YapDB.Index value. - returns: An optional AnyObject. */ public func readAtIndex(index: YapDB.Index) -> AnyObject? { return objectForKey(index.key, inCollection: index.collection) } /** Reads any metadata sored at this index using the transaction. - parameter index: The YapDB.Index value. - returns: An optional AnyObject. */ public func readMetadataAtIndex(index: YapDB.Index) -> AnyObject? { return metadataForKey(index.key, inCollection: index.collection) } } // MARK: - YapDatabaseReadWriteTransaction extension YapDatabaseReadWriteTransaction: WriteTransactionType { public func writeAtIndex(index: YapDB.Index, object: AnyObject, metadata: AnyObject? = .None) { if let metadata: AnyObject = metadata { setObject(object, forKey: index.key, inCollection: index.collection, withMetadata: metadata) } else { setObject(object, forKey: index.key, inCollection: index.collection) } } func removeAtIndex(index: YapDB.Index) { removeObjectForKey(index.key, inCollection: index.collection) } public func removeAtIndexes< Indexes where Indexes: SequenceType, Indexes.Generator.Element == YapDB.Index>(indexes: Indexes) { indexes.forEach(removeAtIndex) } } extension YapDatabaseConnection: ConnectionType { /** Synchronously reads from the database on the connection. The closure receives the read transaction, and the function returns the result of the closure. This makes it very suitable as a building block for more functional methods. The majority of the wrapped functions provided by these extensions use this as their basis. - parameter block: a closure which receives YapDatabaseReadTransaction and returns T - returns: An instance of T */ public func read<T>(block: YapDatabaseReadTransaction -> T) -> T { var result: T! = .None readWithBlock { result = block($0) } return result } /** Synchronously writes to the database on the connection. The closure receives the read write transaction, and the function returns the result of the closure. This makes it very suitable as a building block for more functional methods. The majority of the wrapped functions provided by these extensions use this as their basis. - parameter block: a closure which receives YapDatabaseReadWriteTransaction and returns T - returns: An instance of T */ public func write<T>(block: YapDatabaseReadWriteTransaction -> T) -> T { var result: T! = .None readWriteWithBlock { result = block($0) } return result } /** Asynchronously reads from the database on the connection. The closure receives the read transaction, and completion block receives the result of the closure. This makes it very suitable as a building block for more functional methods. The majority of the wrapped functions provided by these extensions use this as their basis. The completion block is run on the given `queue`. - parameter block: a closure which receives YapDatabaseReadTransaction and returns T - parameter queue: a dispatch_queue_t, defaults to main queue, can be ommitted in most cases. - parameter completion: a closure which receives T and returns Void. */ public func asyncRead<T>(block: YapDatabaseReadTransaction -> T, queue: dispatch_queue_t = dispatch_get_main_queue(), completion: (T) -> Void) { var result: T! = .None asyncReadWithBlock({ result = block($0) }, completionQueue: queue) { completion(result) } } /** Asynchronously writes to the database on the connection. The closure receives the read write transaction, and completion block receives the result of the closure. This makes it very suitable as a building block for more functional methods. The majority of the wrapped functions provided by these extensions use this as their basis. The completion block is run on the given `queue`. - parameter block: a closure which receives YapDatabaseReadWriteTransaction and returns T - parameter queue: a dispatch_queue_t, defaults to main queue, can be ommitted in most cases. - parameter completion: a closure which receives T and returns Void. */ public func asyncWrite<T>(block: YapDatabaseReadWriteTransaction -> T, queue: dispatch_queue_t = dispatch_get_main_queue(), completion: (T -> Void)?) { var result: T! = .None asyncReadWriteWithBlock({ result = block($0) }, completionQueue: queue) { completion?(result) } } /** Execute a read/write block inside a `NSOperation`. The block argument receives a `YapDatabaseReadWriteTransaction`. This method is very handy for writing different item types to the database inside the same transaction. For example let operation = connection.writeBlockOperation { transaction in people.write.on(transaction) barcode.write.on(transaction) } queue.addOperation(operation) - parameter block: a closure of type (YapDatabaseReadWriteTransaction) -> Void - returns: an `NSOperation`. */ public func writeBlockOperation(block: (YapDatabaseReadWriteTransaction) -> Void) -> NSOperation { return NSBlockOperation { self.readWriteWithBlock(block) } } } extension YapDatabase: DatabaseType { public func makeNewConnection() -> YapDatabaseConnection { return newConnection() } } // MARK: - YapDB.Index // MARK: Hashable & Equality extension YapDB.Index: Hashable { public var hashValue: Int { return description.hashValue } } public func == (a: YapDB.Index, b: YapDB.Index) -> Bool { return (a.collection == b.collection) && (a.key == b.key) } // MARK: CustomStringConvertible extension YapDB.Index: CustomStringConvertible { public var description: String { return "\(collection):\(key)" } } // MARK: ValueCoding extension YapDB.Index: ValueCoding { public typealias Coder = YapDBIndexCoder } // MARK: Coders public final class YapDBIndexCoder: NSObject, NSCoding, CodingType { public let value: YapDB.Index public init(_ v: YapDB.Index) { value = v } public required init(coder aDecoder: NSCoder) { let collection = aDecoder.decodeObjectForKey("collection") as! String let key = aDecoder.decodeObjectForKey("key") as! String value = YapDB.Index(collection: collection, key: key) } public func encodeWithCoder(aCoder: NSCoder) { aCoder.encodeObject(value.collection, forKey: "collection") aCoder.encodeObject(value.key, forKey: "key") } } // MARK: - Deprecations @available(*, unavailable, renamed="Persistable") public typealias MetadataPersistable = Persistable @available(*, unavailable, renamed="Persistable") public typealias ObjectMetadataPersistable = Persistable @available(*, unavailable, renamed="Persistable") public typealias ValueMetadataPersistable = Persistable @available(*, unavailable, renamed="ValueCoding") public typealias Saveable = ValueCoding @available(*, unavailable, renamed="CodingType") public typealias Archiver = CodingType
34188b8395b6d78e32c6459143ec6b60
32.989028
183
0.690892
false
false
false
false
SEMT2Group1/CASPER_IOS_Client
refs/heads/master
casper/SocketConn.swift
mit
1
// // SocketConn.swift // casper // // Created by Pontus Pohl on 28/02/16. // Copyright © 2016 Pontus Pohl. All rights reserved. // // //import Foundation // // // // //class SocketConn:NSObject, NSStreamDelegate{ // // //private var input: NSInputStream? //private var output: NSOutputStream? // // //var dataToStream: NSData! // //var byteIndex: Int! // //func Connect(){ // // let host:CFStringRef = "127.0.0.1" // let port:UInt32 = 9999 // // // // // // // // NSStream.getStreamsToHostWithName(host as String, port: 9999, inputStream: &input, output: &outputStream) // // let inputStream = input! // let outputStream = output! // // self.inputStream = readStream!.takeRetainedValue() // self.outputStream = writeStream!.takeRetainedValue() // // // self.inputStream.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode) // self.outputStream.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode) // // self.inputStream.delegate = self // self.outputStream.delegate = self // // //inputStream.open() // //outputStream.open() // self.inputStream.open() // self.outputStream.open() // // // dataToStream = sendValue() // var readBytes = dataToStream.bytes // var dataLength = dataToStream.length // // var buffer = Array<UInt8>(count: dataLength, repeatedValue: 0) // memcpy(UnsafeMutablePointer(buffer), readBytes, dataLength) // var len = self.outputStream.write(buffer, maxLength: dataLength) // // } //}
7ad3025028a32775c3eddd814ee3df5f
23.257576
111
0.639375
false
false
false
false
Shivol/Swift-CS333
refs/heads/master
examples/uiKit/uiKitCatalog/UIKitCatalog/SliderViewController.swift
mit
3
/* Copyright (C) 2016 Apple Inc. All Rights Reserved. See LICENSE.txt for this sample’s licensing information Abstract: A view controller that demonstrates how to use UISlider. */ import UIKit class SliderViewController: UITableViewController { // MARK: - Properties @IBOutlet weak var defaultSlider: UISlider! @IBOutlet weak var tintedSlider: UISlider! @IBOutlet weak var customSlider: UISlider! // MARK: - View Life Cycle override func viewDidLoad() { super.viewDidLoad() configureDefaultSlider() configureTintedSlider() configureCustomSlider() } // MARK: - Configuration func configureDefaultSlider() { defaultSlider.minimumValue = 0 defaultSlider.maximumValue = 100 defaultSlider.value = 42 defaultSlider.isContinuous = true defaultSlider.addTarget(self, action: #selector(SliderViewController.sliderValueDidChange(_:)), for: .valueChanged) } func configureTintedSlider() { tintedSlider.minimumTrackTintColor = UIColor.applicationBlueColor tintedSlider.maximumTrackTintColor = UIColor.applicationPurpleColor tintedSlider.addTarget(self, action: #selector(SliderViewController.sliderValueDidChange(_:)), for: .valueChanged) } func configureCustomSlider() { let leftTrackImage = UIImage(named: "slider_blue_track") customSlider.setMinimumTrackImage(leftTrackImage, for: UIControlState()) let rightTrackImage = UIImage(named: "slider_green_track") customSlider.setMaximumTrackImage(rightTrackImage, for: UIControlState()) let thumbImage = UIImage(named: "slider_thumb") customSlider.setThumbImage(thumbImage, for: UIControlState()) customSlider.minimumValue = 0 customSlider.maximumValue = 100 customSlider.isContinuous = false customSlider.value = 84 customSlider.addTarget(self, action: #selector(SliderViewController.sliderValueDidChange(_:)), for: .valueChanged) } // MARK: - Actions func sliderValueDidChange(_ slider: UISlider) { NSLog("A slider changed its value: \(slider).") } }
2e4ea2c0445ad4687f8215ea59d70ad6
29.901408
123
0.695533
false
true
false
false
ivanbruel/Maya
refs/heads/master
Pod/Classes/MayaCalendarMonthCollectionViewCell.swift
mit
1
// // MayaCalendarCollectionViewCell.swift // Pods // // Created by Ivan Bruel on 01/03/16. // // import UIKit class MayaCalendarMonthCollectionViewCell: UICollectionViewCell { @IBOutlet var dayButtons: [UIButton]! @IBOutlet var weekdayLabels: [UILabel]! var clickBlock: ((MayaDate) -> Void)? @IBAction func dayClicked(button: UIButton) { guard let index = dayButtons.indexOf(button) else { return } viewModel.viewModelClicked(index) } var viewModel: MayaMonthViewModel! { didSet { for index in 0..<viewModel.weekdays.count { weekdayLabels[index].text = viewModel.weekdays[index] weekdayLabels[index].textColor = viewModel.weekdayTextColor weekdayLabels[index].font = viewModel.weekdayFont } for index in 0..<viewModel.viewModels.count { let dayViewModel = viewModel.viewModels[index] let dayButton = dayButtons[index] dayButton.setTitle(dayViewModel.day, forState: .Normal) dayButton.setTitleColor(dayViewModel.textColor, forState: .Normal) dayButton.titleLabel?.font = dayViewModel.font dayButton.backgroundColor = dayViewModel.backgroundColor } } } }
69809fa9f76972377ca976bdf6235d03
25.369565
74
0.688119
false
false
false
false
rnystrom/GitHawk
refs/heads/master
Local Pods/GitHubAPI/GitHubAPI/V3StatusCode205.swift
mit
1
// // V3StatusCode205.swift // GitHubAPI // // Created by Ryan Nystrom on 3/3/18. // Copyright © 2018 Ryan Nystrom. All rights reserved. // import Foundation public struct V3StatusCode205: V3StatusCodeSuccess { public static func success(statusCode: Int) -> Bool { return statusCode == 205 } } public struct V3StatusCode200: V3StatusCodeSuccess { public static func success(statusCode: Int) -> Bool { return statusCode == 200 } } public struct V3StatusCode200or201: V3StatusCodeSuccess { public static func success(statusCode: Int) -> Bool { return statusCode == 200 || statusCode == 201 } }
56cd300775dd823d570e2ce37a5d1333
22.428571
57
0.678354
false
false
false
false
danthorpe/TaylorSource
refs/heads/development
Tests/YapDBDatasourceTests.swift
mit
2
// // YapDBDatasourceTests.swift // Datasources // // Created by Daniel Thorpe on 08/05/2015. // Copyright (c) 2015 Daniel Thorpe. All rights reserved. // import UIKit import XCTest import YapDatabase import YapDatabaseExtensions import TaylorSource class YapDBDatasourceTests: XCTestCase { typealias Factory = YapDBFactory<Event, UITableViewCell, UITableViewHeaderFooterView, StubbedTableView> typealias Datasource = YapDBDatasource<Factory> let configuration: TaylorSource.Configuration<Event> = events(true) let view = StubbedTableView() let factory = Factory() var someEvents: [Event]! var numberOfEvents: Int! override func setUp() { super.setUp() someEvents = createManyEvents() numberOfEvents = someEvents.count } func datasourceWithDatabase(db: YapDatabase, changesValidator: YapDatabaseViewMappings.Changes? = .None) -> Datasource { if let changes = changesValidator { return Datasource(id: "test datasource", database: db, factory: factory, processChanges: changes, configuration: configuration) } return Datasource(id: "test datasource", database: db, factory: factory, processChanges: { changeset in }, configuration: configuration) } } extension YapDBDatasourceTests { func test_GivenEmptyDatabase_ThatHasCorrectSections() { let db = YapDB.testDatabase() let datasource = datasourceWithDatabase(db) XCTAssertEqual(datasource.numberOfSections, 0) } func test_GivenDatabaseWithOneRedEvent_ThatHasCorrectSections() { let db = YapDB.testDatabase() { database in database.newConnection().write(createOneEvent()) } let datasource = datasourceWithDatabase(db) XCTAssertEqual(datasource.numberOfSections, 1) XCTAssertEqual(datasource.numberOfItemsInSection(0), 1) } func test_GivenDatabaseWithManyRedEvents_ThatHasCorrectSections() { let db = YapDB.testDatabase() { database in database.newConnection().write(self.someEvents) } let datasource = datasourceWithDatabase(db) XCTAssertEqual(datasource.numberOfSections, 1) XCTAssertEqual(datasource.numberOfItemsInSection(0), numberOfEvents) } func test_GivenDatabaseWithManyRedAndManyBlueEvents_ThatHasCorrectSections() { let redEvents = createManyEvents() let numberOfRedEvents = redEvents.count let blueEvents = createManyEvents(.Blue) let numberOfBlueEvents = blueEvents.count let db = YapDB.testDatabase() { database in database.newConnection().write { transaction in transaction.write(redEvents) transaction.write(blueEvents) } } let datasource = datasourceWithDatabase(db) XCTAssertEqual(datasource.numberOfSections, 2) XCTAssertEqual(datasource.numberOfItemsInSection(0), numberOfRedEvents) XCTAssertEqual(datasource.numberOfItemsInSection(1), numberOfBlueEvents) } func test_GivenStaticDatasource_WhenAccessingItemsAtANegativeIndex_ThatResultIsNone() { let db = YapDB.testDatabase() { database in database.newConnection().write(self.someEvents) } let datasource = datasourceWithDatabase(db) XCTAssertTrue(datasource.itemAtIndexPath(NSIndexPath(forRow: numberOfEvents * -1, inSection: 0)) == nil) } func test_GivenStaticDatasource_WhenAccessingItemsGreaterThanMaxIndex_ThatResultIsNone() { let db = YapDB.testDatabase() { database in database.newConnection().write(self.someEvents) } let datasource = datasourceWithDatabase(db) XCTAssertTrue(datasource.itemAtIndexPath(NSIndexPath(forRow: numberOfEvents * -1, inSection: 0)) == nil) } func test_GivenStaticDatasource_WhenAccessingItems_ThatCorrectItemIsReturned() { let db = YapDB.testDatabase() { database in database.newConnection().write(self.someEvents) } let datasource = datasourceWithDatabase(db) XCTAssertEqual(datasource.itemAtIndexPath(NSIndexPath.first)!, someEvents[0]) } }
2ea928286300af072187b305a795b45b
37.275229
144
0.705177
false
true
false
false
julienbodet/wikipedia-ios
refs/heads/develop
Wikipedia/Code/ArticleFetchedResultsViewController.swift
mit
1
import UIKit import WMF @objc(WMFArticleFetchedResultsViewController) class ArticleFetchedResultsViewController: ArticleCollectionViewController, CollectionViewUpdaterDelegate { var fetchedResultsController: NSFetchedResultsController<WMFArticle>! var collectionViewUpdater: CollectionViewUpdater<WMFArticle>! open func setupFetchedResultsController(with dataStore: MWKDataStore) { assert(false, "Subclassers should override this method") } @objc override var dataStore: MWKDataStore! { didSet { setupFetchedResultsController(with: dataStore) collectionViewUpdater = CollectionViewUpdater(fetchedResultsController: fetchedResultsController, collectionView: collectionView) collectionViewUpdater?.delegate = self } } override func article(at indexPath: IndexPath) -> WMFArticle? { guard let sections = fetchedResultsController.sections, indexPath.section < sections.count, indexPath.item < sections[indexPath.section].numberOfObjects else { return nil } return fetchedResultsController.object(at: indexPath) } override func articleURL(at indexPath: IndexPath) -> URL? { return article(at: indexPath)?.url } override func delete(at indexPath: IndexPath) { guard let articleURL = articleURL(at: indexPath) else { return } dataStore.historyList.removeEntry(with: articleURL) } override func canDelete(at indexPath: IndexPath) -> Bool { return true } var deleteAllButtonText: String? = nil var deleteAllConfirmationText: String? = nil var deleteAllCancelText: String? = nil var deleteAllText: String? = nil var isDeleteAllVisible: Bool = false open func deleteAll() { } fileprivate final func updateDeleteButton() { guard isDeleteAllVisible else { navigationItem.leftBarButtonItem = nil return } if navigationItem.leftBarButtonItem == nil { navigationItem.leftBarButtonItem = UIBarButtonItem(title: deleteAllButtonText, style: .plain, target: self, action: #selector(deleteButtonPressed(_:))) } navigationItem.leftBarButtonItem?.isEnabled = !isEmpty } @objc fileprivate final func deleteButtonPressed(_ sender: UIBarButtonItem) { let alertController = UIAlertController(title: deleteAllConfirmationText, message: nil, preferredStyle: .actionSheet) alertController.addAction(UIAlertAction(title: deleteAllText, style: .destructive, handler: { (action) in self.deleteAll() })) alertController.addAction(UIAlertAction(title: deleteAllCancelText, style: .cancel, handler: nil)) alertController.popoverPresentationController?.barButtonItem = sender alertController.popoverPresentationController?.permittedArrowDirections = .any present(alertController, animated: true, completion: nil) } open func collectionViewUpdater<T>(_ updater: CollectionViewUpdater<T>, didUpdate collectionView: UICollectionView) { for indexPath in collectionView.indexPathsForVisibleItems { guard let cell = collectionView.cellForItem(at: indexPath) as? ArticleRightAlignedImageCollectionViewCell else { continue } configure(cell: cell, forItemAt: indexPath, layoutOnly: false) } updateEmptyState() } override func isEmptyDidChange() { super.isEmptyDidChange() updateDeleteButton() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) editController.close() } override func viewWillHaveFirstAppearance(_ animated: Bool) { do { try fetchedResultsController.performFetch() } catch let error { DDLogError("Error fetching articles for \(self): \(error)") } collectionView.reloadData() super.viewWillHaveFirstAppearance(animated) } func collectionView(_ collectionView: UICollectionView, shouldHighlightItemAt indexPath: IndexPath) -> Bool { guard let translation = editController.swipeTranslationForItem(at: indexPath) else { return true } return translation == 0 } } // MARK: UICollectionViewDataSource extension ArticleFetchedResultsViewController { override func numberOfSections(in collectionView: UICollectionView) -> Int { guard let sectionsCount = self.fetchedResultsController.sections?.count else { return 0 } return sectionsCount } override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { guard let sections = self.fetchedResultsController.sections, section < sections.count else { return 0 } return sections[section].numberOfObjects } }
13524aba10b902318e66391fbdf3f208
37.015038
163
0.681764
false
false
false
false
MaximShoustin/Swift-Extension-Helper
refs/heads/master
MyExtensions.swift
mit
1
import Foundation extension NSData { func toString() -> String { return NSString(data: self, encoding: NSUTF8StringEncoding)! } } extension Double { func format(f: String) -> String { return NSString(format: "%\(f)f", self) } func toString() -> String { return String(format: "%.1f",self) } func toInt() -> Int{ var temp:Int64 = Int64(self) return Int(temp) } } extension String { func split(splitter: String) -> Array<String> { let regEx = NSRegularExpression(pattern: splitter, options: NSRegularExpressionOptions(), error: nil)! let stop = "SomeStringThatYouDoNotExpectToOccurInSelf" let modifiedString = regEx.stringByReplacingMatchesInString(self, options: NSMatchingOptions(), range: NSMakeRange(0, countElements(self)), withTemplate: stop) return modifiedString.componentsSeparatedByString(stop) } func startWith(find: String) -> Bool { return self.hasPrefix(find) } func equals(find: String) -> Bool { return self == find } func contains(find: String) -> Bool{ if let temp = self.rangeOfString(find){ return true } return false } func replace(replaceStr:String, with withStr:String) -> String{ return self.stringByReplacingOccurrencesOfString( replaceStr, withString: withStr, options: .allZeros, // or just nil range: nil) } func equalsIgnoreCase(find: String) -> Bool { return self.lowercaseString == find.lowercaseString } func trim() -> String { return self.stringByTrimmingCharactersInSet(.whitespaceAndNewlineCharacterSet()) } func removeCharsFromEnd(count:Int) -> String{ let stringLength = countElements(self) let substringIndex = (stringLength < count) ? 0 : stringLength - count return self.substringToIndex(advance(self.startIndex, substringIndex)) } func length() -> Int { return countElements(self) } }
6151feb9cf5385e8b4dafb9cd33cef98
24.435294
175
0.608696
false
false
false
false
accepton/accepton-apple
refs/heads/master
Pod/Classes/AcceptOnViewController/FillOutRemaining/AcceptOnAddressPreview.swift
mit
1
import UIKit //This view supports showing an address or just gray boxes where the address fields would go class AcceptOnAddressPreview: UIView { //----------------------------------------------------------------------------------------------------- //Constants //----------------------------------------------------------------------------------------------------- let fieldHeight = 20 let fieldSpacing = 5 //----------------------------------------------------------------------------------------------------- //Properties //----------------------------------------------------------------------------------------------------- let line1Field = AcceptOnAddressPreviewLineLabel() let line2Field = AcceptOnAddressPreviewLineLabel() let cityField = AcceptOnAddressPreviewLineLabel() let stateField = AcceptOnAddressPreviewLineLabel() let zipField = AcceptOnAddressPreviewLineLabel() var activeFields: [UILabel] { if line2IsActive { return [line1Field, line2Field, cityField, stateField, zipField] } else { return [line1Field, cityField, stateField, zipField] } } var fields: [UILabel] { return [line1Field, line2Field, cityField, stateField, zipField] } var content = UIView() //Line2 is optional var line2HeightConstraint: Constraint! var line2TopOffset: Constraint! var line2IsActive: Bool = false { didSet { if line2IsActive { line2HeightConstraint.updateOffset(fieldHeight) line2TopOffset.updateOffset(fieldSpacing) } else { line2HeightConstraint.updateOffset(0) line2TopOffset.updateOffset(0) } } } var address: AcceptOnAPIAddress? { didSet { if let address = address { line1Field.text = address.line1 cityField.text = address.city stateField.text = address.region zipField.text = address.postalCode if let line2 = address.line2 { line2IsActive = true line2Field.text = line2 } else { line2IsActive = false line2Field.text = nil } } else { line1Field.text = "" cityField.text = "" stateField.text = "" zipField.text = "" line2IsActive = false } } } var loadingSpinner = UIActivityIndicatorView(activityIndicatorStyle: .WhiteLarge) //----------------------------------------------------------------------------------------------------- //Constructors, Initializers, and UIView lifecycle //----------------------------------------------------------------------------------------------------- override init(frame: CGRect) { super.init(frame: frame) defaultInit() } required init(coder: NSCoder) { super.init(coder: coder)! defaultInit() } convenience init() { self.init(frame: CGRectZero) } func defaultInit() { self.backgroundColor = UIColor(white: 0.9, alpha: 1) //Centers all fields self.addSubview(content) content.snp_makeConstraints { $0.center.equalTo(0) $0.width.equalTo(200) $0.top.equalTo(12) $0.bottom.equalTo(-12) $0.left.equalTo(12) $0.right.equalTo(-12) return } content.addSubview(line1Field) line1Field.snp_makeConstraints { $0.top.equalTo(0) $0.left.right.equalTo(0) $0.height.equalTo(self.fieldHeight) return } line1Field.backgroundColor = UIColor(white: 0.8, alpha: 1) line1Field.clipsToBounds = true //Optional content.addSubview(line2Field) line2Field.snp_makeConstraints { self.line2TopOffset = $0.top.equalTo(line1Field.snp_bottom).offset(0).constraint $0.left.right.equalTo(0) self.line2HeightConstraint = $0.height.equalTo(0).constraint return } line2Field.backgroundColor = UIColor(white: 0.8, alpha: 1) line2Field.clipsToBounds = true content.addSubview(cityField) cityField.snp_makeConstraints { $0.top.equalTo(self.line2Field.snp_bottom).offset(self.fieldSpacing) $0.left.equalTo(0) $0.height.equalTo(line1Field.snp_height) $0.width.equalTo(60) return } cityField.backgroundColor = UIColor(white: 0.8, alpha: 1) cityField.clipsToBounds = true cityField.minimumScaleFactor = 0.5 cityField.adjustsFontSizeToFitWidth = true content.addSubview(stateField) stateField.snp_makeConstraints { $0.top.equalTo(self.cityField.snp_top) $0.left.equalTo(self.cityField.snp_right).offset(self.fieldSpacing) $0.height.equalTo(line1Field.snp_height) $0.bottom.equalTo(cityField.snp_bottom) $0.width.equalTo(40) return } stateField.backgroundColor = UIColor(white: 0.8, alpha: 1) stateField.clipsToBounds = true content.addSubview(zipField) zipField.snp_makeConstraints { $0.top.equalTo(stateField.snp_bottom).offset(self.fieldSpacing) $0.left.equalTo(0) $0.width.equalTo(80) $0.height.equalTo(line1Field.snp_height) $0.bottom.equalTo(0) return } zipField.backgroundColor = UIColor(white: 0.8, alpha: 1) zipField.clipsToBounds = true self.clipsToBounds = true self.layer.cornerRadius = 2 for e in fields { e.textColor = UIColor(white: 0.15, alpha: 1) e.font = UIFont(name: "HelveticaNeue-Light", size: 12) } //Add loading spinner self.addSubview(loadingSpinner) loadingSpinner.snp_makeConstraints { $0.center.equalTo(self.snp_center) return } loadingSpinner.alpha = 0 loadingSpinner.startAnimating() loadingSpinner.color = UIColor(white: 0.15, alpha: 1) } override func layoutSubviews() { super.layoutSubviews() } var constraintsWereUpdated = false override func updateConstraints() { super.updateConstraints() //Only run custom constraints once if (constraintsWereUpdated) { return } constraintsWereUpdated = true } //----------------------------------------------------------------------------------------------------- //Animation Helpers //----------------------------------------------------------------------------------------------------- func toggleLoadingAnimation(show: Bool) { if show { for e in activeFields { e.alpha = 0 loadingSpinner.alpha = 1 } } else { for (i, e) in activeFields.enumerate() { var transform = CATransform3DMakeScale(0.8, 0.8, 1) transform = CATransform3DTranslate(transform, 0, 40, 0) e.layer.transform = transform UIView.animateWithDuration(0.77, delay: NSTimeInterval(i)*0.05, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: .CurveEaseOut, animations: { e.layer.transform = CATransform3DIdentity e.alpha = 1 }, completion: nil) } loadingSpinner.alpha = 0 } } //----------------------------------------------------------------------------------------------------- //Signal / Action Handlers //----------------------------------------------------------------------------------------------------- //----------------------------------------------------------------------------------------------------- //External / Delegate Handlers //----------------------------------------------------------------------------------------------------- } class AcceptOnAddressPreviewLineLabel: UILabel { override func drawTextInRect(rect: CGRect) { let insets = UIEdgeInsets(top: 2, left: 5, bottom: 2, right: 5) super.drawTextInRect(UIEdgeInsetsInsetRect(rect, insets)) } }
5f4321461eb74d287f34836af8742312
35.179167
170
0.483589
false
false
false
false
iosdevzone/IDZSwiftGLKit
refs/heads/master
IDZSwiftGLKitTests/IDZSwiftGLKitTests.swift
mit
1
// // IDZSwiftGLKitTests.swift // IDZSwiftGLKitTests // // Created by Danny Keogan on 6/5/16. // Copyright © 2016 iOS Developer Zone. All rights reserved. // import XCTest @testable import IDZSwiftGLKit import GLKit class IDZSwiftGLKitTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testMultiply() { let I = GLKMatrix4.eye let X = GLKMatrix4(m: (1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 8.0, 7.0, 6.0, 5.0, 4.0, 3.0, 2.0)) let P1 = I * X XCTAssert(P1 == X) let P2 = X * I XCTAssert(P2 == X) let Y = GLKMatrix4(m: (10.0, 2.0, 13.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 8.0, 17.0, 6.0, 5.0, 24.0, 3.0, 2.0)) let P3 = (X * Y).transpose let P4 = Y.transpose * X.transpose XCTAssert(P3 == P4) } func testSubtract() { let X = GLKMatrix4(m: (1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 8.0, 7.0, 6.0, 5.0, 4.0, 3.0, 2.0)) let Z = GLKMatrix4.zero XCTAssert(X - X == Z) XCTAssert(X - Z == X) } func testTranspose() { let X = GLKMatrix4(m: (1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 8.0, 7.0, 6.0, 5.0, 4.0, 3.0, 2.0)) let Y = GLKMatrix4(m: (10.0, 2.0, 13.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 8.0, 17.0, 6.0, 5.0, 24.0, 3.0, 2.0)) XCTAssert(X.transpose.transpose == X) } }
cd6e35373bf1a69b7936efadf575b181
23.9875
111
0.444222
false
true
false
false
illescasDaniel/Questions
refs/heads/master
Questions/Extensions/AVAudioPlayer+Extension.swift
mit
1
import AVFoundation extension AVAudioPlayer { enum AudioTypes: String { case mp3 case wav // ... } convenience init?(file: String, type: AudioTypes, volume: Float? = nil) { guard let path = Bundle.main.path(forResource: file, ofType: type.rawValue) else { print("Incorrect audio path"); return nil } let url = URL(fileURLWithPath: path) try? self.init(contentsOf: url) if let validVolume = volume, validVolume >= 0.0 && validVolume <= 1.0 { self.volume = validVolume } } func setVolumeLevel(to volume: Float, duration: TimeInterval? = nil) { if #available(iOS 10.0, *) { self.setVolume(volume, fadeDuration: duration ?? 1) } else { self.volume = volume } } }
b5e917e08a5de3ea36d7a9bc9bfdc3a3
22.733333
128
0.66573
false
false
false
false
kyasuda2003/omicron
refs/heads/master
BusinessManagement/BizApi.swift
gpl-2.0
1
// // BizApi.swift // BusinessManagement // // Created by Yasuda Keisuke on 3/11/15. // Copyright (c) 2015 Yasuda Keisuke. All rights reserved. // import UIKit struct appvar { static var productApi="http://pacificoasis.com/obj/products" static var imgApi="http://pacificoasis.com/obj/photos" static var imgBlobApi="http://pacificoasis.com/media/photos" } class BizApi: NSObject { convenience init(uid:NSString?,pwd:NSString?){ self.init() } class var sharedApi: BizApi { struct _static { static var instance: BizApi? static var token: dispatch_once_t = 0 } dispatch_once(&_static.token) { _static.instance = BizApi() } return _static.instance! } func fetchJSONDataFromURL(url: NSURL, withCallback callback: (NSData?,NSError?) -> Void) -> Void { //if callback { //NSException.raise("Invalid callback handler", format: "callback %@ is invalid", arguments: getVaList(["BizApi > fetchJSONDataFromURL"])) //} NSURLConnection.sendAsynchronousRequest(NSURLRequest(URL: url), queue: NSOperationQueue.mainQueue(), completionHandler: {(_res:NSURLResponse!, _data:NSData!, _err:NSError!) -> Void in let statusCode=(_res as? NSHTTPURLResponse)?.statusCode ?? -1 if statusCode>=200&&statusCode<300{ if _err==nil{ //var _err:NSError? //var toDict:NSDictionary=NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &_err) as NSDictionary callback(_data, _err) } else { callback(nil,_err) } } else{ var _msg:NSString=NSString(format:"Invalid status response code: %ld",statusCode) var _err:NSError=NSError(domain:"cc.proxicode",code:statusCode,userInfo:[NSLocalizedDescriptionKey:_msg]) } } ) } }
038d8b4d8e219b22717c5c123a49ceeb
32.590909
173
0.552097
false
false
false
false
IngmarStein/swift
refs/heads/master
test/IRGen/metadata_dominance.swift
apache-2.0
1
// RUN: %target-swift-frontend -emit-ir -primary-file %s | %FileCheck %s // RUN: %target-swift-frontend -O -emit-ir -primary-file %s | %FileCheck %s --check-prefix=CHECK-OPT func use_metadata<F>(_ f: F) {} func voidToVoid() {} func intToInt(_ x: Int) -> Int { return x } func cond() -> Bool { return true } // CHECK: define hidden void @_TF18metadata_dominance5test1FT_T_() func test1() { // CHECK: call i1 @_TF18metadata_dominance4condFT_Sb() if cond() { // CHECK: [[T0:%.*]] = call %swift.type* @_TMaFT_T_() // CHECK: call void @_TF18metadata_dominance12use_metadataurFxT_(%swift.opaque* {{.*}}, %swift.type* [[T0]]) use_metadata(voidToVoid) // CHECK: call i1 @_TF18metadata_dominance4condFT_Sb() // CHECK-NOT: @_TMaFT_T_ // CHECK: call void @_TF18metadata_dominance12use_metadataurFxT_(%swift.opaque* {{.*}}, %swift.type* [[T0]]) if cond() { use_metadata(voidToVoid) } else { // CHECK-NOT: @_TMaFT_T_ // CHECK: call void @_TF18metadata_dominance12use_metadataurFxT_(%swift.opaque* {{.*}}, %swift.type* [[T0]]) use_metadata(voidToVoid) } } // CHECK: [[T1:%.*]] = call %swift.type* @_TMaFT_T_() // CHECK: call void @_TF18metadata_dominance12use_metadataurFxT_(%swift.opaque* {{.*}}, %swift.type* [[T1]]) use_metadata(voidToVoid) } // CHECK: define hidden void @_TF18metadata_dominance5test2FT_T_() func test2() { // CHECK: call i1 @_TF18metadata_dominance4condFT_Sb() if cond() { // CHECK: call i1 @_TF18metadata_dominance4condFT_Sb() // CHECK: [[T0:%.*]] = call %swift.type* @_TMaFT_T_() // CHECK: call void @_TF18metadata_dominance12use_metadataurFxT_(%swift.opaque* {{.*}}, %swift.type* [[T0]]) if cond() { use_metadata(voidToVoid) } else { // CHECK: [[T1:%.*]] = call %swift.type* @_TMaFT_T_() // CHECK: call void @_TF18metadata_dominance12use_metadataurFxT_(%swift.opaque* {{.*}}, %swift.type* [[T1]]) use_metadata(voidToVoid) } } // CHECK: [[T2:%.*]] = call %swift.type* @_TMaFT_T_() // CHECK: call void @_TF18metadata_dominance12use_metadataurFxT_(%swift.opaque* {{.*}}, %swift.type* [[T2]]) use_metadata(voidToVoid) } protocol P { func makeFoo() -> Foo } class Foo: P { func makeFoo() -> Foo { fatalError() } } class SubFoo: Foo { final override func makeFoo() -> Foo { // Check that it creates an instance of type Foo, // and not an instance of a Self type involved // in this protocol conformance. return Foo() } } @inline(never) func testMakeFoo(_ p: P) -> Foo.Type { let foo = p.makeFoo() return type(of: foo) } // The protocol witness for metadata_dominance.P.makeFoo () -> metadata_dominance.Foo in // conformance metadata_dominance.Foo : metadata_dominance.P should not use the Self type // as the type of the object to be created. It should dynamically obtain the type. // CHECK-OPT-LABEL: define hidden %C18metadata_dominance3Foo* @_TTWC18metadata_dominance3FooS_1PS_FS1_7makeFoofT_S0_ // CHECK-OPT-NOT: tail call noalias %swift.refcounted* @rt_swift_allocObject(%swift.type* %Self
980ed1140455b929c32dd01f4a303c8d
35.178571
116
0.650214
false
true
false
false
josve05a/wikipedia-ios
refs/heads/develop
Wikipedia/Code/NewsCollectionViewCell+WMFFeedContentDisplaying.swift
mit
3
import UIKit extension NewsCollectionViewCell { public func configure(with story: WMFFeedNewsStory, dataStore: MWKDataStore, showArticles: Bool = true, theme: Theme, layoutOnly: Bool) { let previews = story.articlePreviews ?? [] descriptionHTML = story.storyHTML if showArticles { articles = previews.map { (articlePreview) -> CellArticle in return CellArticle(articleURL:articlePreview.articleURL, title: articlePreview.displayTitle, titleHTML: articlePreview.displayTitleHTML, description: articlePreview.descriptionOrSnippet, imageURL: articlePreview.thumbnailURL) } } let articleLanguage = story.articlePreviews?.first?.articleURL.wmf_language descriptionLabel.accessibilityLanguage = articleLanguage semanticContentAttributeOverride = MWLanguageInfo.semanticContentAttribute(forWMFLanguage: articleLanguage) let imageWidthToRequest = traitCollection.wmf_potdImageWidth if let articleURL = story.featuredArticlePreview?.articleURL ?? previews.first?.articleURL, let article = dataStore.fetchArticle(with: articleURL), let imageURL = article.imageURL(forWidth: imageWidthToRequest) { isImageViewHidden = false if !layoutOnly { imageView.wmf_setImage(with: imageURL, detectFaces: true, onGPU: true, failure: {(error) in }, success: { }) } } else { isImageViewHidden = true } apply(theme: theme) resetContentOffset() setNeedsLayout() } }
501dd19c309337d9b1e1fe93e2bea74a
48.875
241
0.686717
false
false
false
false
TheCodedSelf/Hush-Time
refs/heads/master
HushTime/TimeSelector.swift
mit
1
// // TimeSelector.swift // HushTime // // Created by Keegan Rush on 2017/07/16. // Copyright © 2017 TheCodedSelf. All rights reserved. // import AppKit typealias Time = Measurement<UnitDuration> class TimeSelector: NSView { var valueChanged: (() -> ())? = nil @IBOutlet private weak var mainView: NSView! @IBOutlet fileprivate weak var minuteTextField: NSTextField! @IBOutlet fileprivate weak var hourTextField: NSTextField! @IBOutlet fileprivate weak var hourStepper: NSStepper! @IBOutlet fileprivate weak var minuteStepper: NSStepper! var value: Time { return hours + minutes } private var hours: Time { return Time(value: Double(hourTextField.stringValue) ?? 0, unit: .hours) } private var minutes: Time { return Time(value: Double(minuteTextField.stringValue) ?? 0, unit: .minutes) } override init(frame frameRect: NSRect) { super.init(frame: frameRect) loadView() } required init?(coder: NSCoder) { super.init(coder: coder) loadView() } func populate(with time: Time) { minuteTextField.integerValue = Int(time.converted(to: .minutes).value) % 60 hourTextField.integerValue = Int(time.converted(to: .hours).value) updateForChangedValues() } fileprivate func updateForChangedValues() { resetHourTextIfNotValidHour() resetMinuteTextIfNotValidMinute() valueChanged?() } @IBAction private func minutesChanged(_ sender: Any) { minuteTextField.integerValue = minuteStepper.integerValue updateForChangedValues() } @IBAction private func hoursChanged(_ sender: Any) { hourTextField.integerValue = hourStepper.integerValue updateForChangedValues() } private func loadView() { Bundle.main.loadNibNamed(String(describing: TimeSelector.self), owner: self, topLevelObjects: nil) mainView.frame = bounds mainView.autoresizingMask = [.viewWidthSizable, .viewHeightSizable] layer?.backgroundColor = CGColor.black addSubview(mainView) layoutSubtreeIfNeeded() minuteTextField.delegate = self hourTextField.delegate = self hourStepper.minValue = 0 minuteStepper.minValue = 0 minuteStepper.maxValue = 59 } private func resetHourTextIfNotValidHour() { reset(textField: hourTextField, stepper: hourStepper, ifNot: { $0 > -1} ) } private func resetMinuteTextIfNotValidMinute() { reset(textField: minuteTextField, stepper: minuteStepper, ifNot: { $0 < 60 && $0 > -1 }) } private func reset(textField: NSTextField, stepper: NSStepper, ifNot valid: (Int) -> Bool) { if let field = Int(textField.stringValue), valid(field) { } else { textField.integerValue = 0 } stepper.integerValue = textField.integerValue if textField.stringValue.characters.count == 1 { textField.stringValue = "0" + textField.stringValue } } } extension TimeSelector: NSTextFieldDelegate { override func controlTextDidEndEditing(_ obj: Notification) { updateForChangedValues() } override func controlTextDidChange(_ obj: Notification) { guard let textField = obj.object as? NSTextField else { return } if textField == hourTextField { if let hour = Int(textField.stringValue) { hourStepper.integerValue = hour } } else if textField == minuteTextField { if let minute = Int(textField.stringValue) { minuteStepper.integerValue = minute } } } }
90e8364849bd395e43ce42b82c4d6ad1
28.036765
96
0.609015
false
false
false
false
woohyuknrg/GithubTrending
refs/heads/master
github/View Controllers/LoginViewController.swift
mit
1
import UIKit import Moya import RxSwift import RxCocoa class LoginViewController: UIViewController { var viewModel: LoginViewModel! @IBOutlet weak fileprivate var usernameTextField: UITextField! @IBOutlet weak fileprivate var passwordTextField: UITextField! @IBOutlet weak fileprivate var signInButton: UIButton! fileprivate let disposeBag = DisposeBag() override func viewDidLoad() { super.viewDidLoad() bindToRx() customizeSignInButton() } func bindToRx() { _ = usernameTextField.rx.text.orEmpty.bind(to: viewModel.username).disposed(by: disposeBag) _ = passwordTextField.rx.text.orEmpty.bind(to: viewModel.password).disposed(by: disposeBag) _ = signInButton.rx.tap.bind(to: viewModel.loginTaps).disposed(by: disposeBag) viewModel.loginEnabled .drive(signInButton.rx.isEnabled) .disposed(by: disposeBag) viewModel.loginExecuting .drive(onNext: { executing in UIApplication.shared.isNetworkActivityIndicatorVisible = executing }) .disposed(by: disposeBag) viewModel.loginFinished .drive(onNext: { [weak self] loginResult in switch loginResult { case .failed(let message): let alert = UIAlertController(title: "Oops!", message:message, preferredStyle: .alert) alert.addAction(UIAlertAction(title: "OK", style: .default) { _ in }) self?.present(alert, animated: true, completion: nil) case .ok: self?.dismiss(animated: true, completion: nil) } }) .disposed(by: disposeBag) } func dismissKeyboard() { view.endEditing(true) } } // MARK: UI stuff extension LoginViewController { fileprivate func customizeSignInButton() { signInButton.layer.cornerRadius = 6.0 signInButton.layer.masksToBounds = true } }
dcf669b8ce424b440a2584efa3370f9f
32.209677
106
0.616319
false
false
false
false
alessandrostone/ModelRocket
refs/heads/master
ModelRocket/PropertyArray.swift
mit
6
// PropertyArray.swift // // Copyright (c) 2015 Oven Bits, LLC // // 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 final public class PropertyArray<T : JSONTransformable>: PropertyDescription { typealias PropertyType = T /// Backing store for property data public var values: [PropertyType] = [] /// Post-processing closure. public var postProcess: (([PropertyType]) -> Void)? /// JSON parameter key public var key: String /// Type information public var type: String { return "\(PropertyType.self)" } /// Specify whether value is required public var required = false public var count: Int { return values.count } public var isEmpty: Bool { return values.isEmpty } public var first: PropertyType? { return values.first } public var last: PropertyType? { return values.last } // MARK: Initialization /// Initialize with JSON property key public init(key: String, defaultValues: [PropertyType] = [], required: Bool = false, postProcess: (([PropertyType]) -> Void)? = nil) { self.key = key self.values = defaultValues self.required = required self.postProcess = postProcess } // MARK: Transform /// Extract object from JSON and return whether or not the value was extracted public func fromJSON(json: JSON) -> Bool { var jsonValue: JSON = json let keyPaths = key.componentsSeparatedByString(".") for key in keyPaths { jsonValue = jsonValue[key] } values.removeAll(keepCapacity: false) for object in jsonValue.array ?? [] { if let property = PropertyType.fromJSON(object) as? PropertyType { values.append(property) } } return !values.isEmpty } /// Convert object to JSON public func toJSON() -> AnyObject? { var jsonArray: [AnyObject] = [] for value in values { jsonArray.append(value.toJSON()) } return jsonArray } /// Perform initialization post-processing public func initPostProcess() { postProcess?(values) } // MARK: Coding /// Encode public func encode(coder: NSCoder) { let objectArray = values.map { $0 as? AnyObject }.filter { $0 != nil }.map { $0! } coder.encodeObject(objectArray, forKey: key) } public func decode(decoder: NSCoder) { let decodedObjects = decoder.decodeObjectForKey(key) as? [AnyObject] values.removeAll(keepCapacity: false) for object in decodedObjects ?? [] { if let value = object as? PropertyType { values.append(value) } } } } // MARK:- Printable extension PropertyArray: Printable { public var description: String { return "PropertyArray<\(type)> (key: \(key), count: \(values.count), required: \(required))" } } // MARK:- DebugPrintable extension PropertyArray: DebugPrintable { public var debugDescription: String { return description } } // MARK:- CollectionType extension PropertyArray: CollectionType { public func generate() -> IndexingGenerator<[PropertyType]> { return values.generate() } public var startIndex: Int { return 0 } public var endIndex: Int { return values.count } public subscript(index: Int) -> PropertyType { return values[index] } } // MARK:- Sliceable extension PropertyArray: Sliceable { public subscript (subRange: Range<Int>) -> ArraySlice<PropertyType> { return values[subRange] } } // MARK:- Hashable extension PropertyArray: Hashable { public var hashValue: Int { return key.hashValue } } // MARK:- Equatable extension PropertyArray: Equatable {} public func ==<T>(lhs: PropertyArray<T>, rhs: PropertyArray<T>) -> Bool { return lhs.key == rhs.key }
559ec1c67e4b820c085d0aa8194b0bbe
27.043956
138
0.636951
false
false
false
false
moray95/AwesomeSwiftSocks
refs/heads/master
AwesomeSwiftSocks/Classes/Socket.swift
mit
1
// // Socket.swift // Pods // // Created by Moray on 23/06/16. // // import Foundation public class Socket { /// The lower level socket. var socket : SocketType? = nil { didSet { if let socket = socket { socketIgnoreSigpipe(socket) } } } /// The port of the server to connect through. public let port : PortType init(socket : SocketType? = nil, port : PortType) { self.socket = socket self.port = port } /** * Closes the current session with the * server. Does nothing if the socket is * not already closed or not connected. */ public func close() { if let socket = socket { closeSocket(socket) } socket = nil } deinit { close() } }
5df26c74cce546179c37e18a4b091345
13.634615
51
0.573684
false
false
false
false
itsaboutcode/WordPress-iOS
refs/heads/develop
WordPress/Classes/ViewRelated/Plugins/PluginDirectoryViewModel.swift
gpl-2.0
2
import Foundation import WordPressFlux import Gridicons protocol PluginListPresenter: AnyObject { func present(site: JetpackSiteRef, query: PluginQuery) } class PluginDirectoryViewModel: Observable { let site: JetpackSiteRef let changeDispatcher = Dispatcher<Void>() weak var noResultsDelegate: NoResultsViewControllerDelegate? private let store: PluginStore private let installedReceipt: Receipt private let featuredReceipt: Receipt private let popularReceipt: Receipt private let newReceipt: Receipt private var actionReceipt: Receipt? private let throttle = Scheduler(seconds: 1) public init(site: JetpackSiteRef, store: PluginStore = StoreContainer.shared.plugin) { self.store = store self.site = site installedReceipt = store.query(.all(site: site)) featuredReceipt = store.query(.featured) popularReceipt = store.query(.feed(type: .popular)) newReceipt = store.query(.feed(type: .newest)) actionReceipt = ActionDispatcher.global.subscribe { [changeDispatcher, throttle] action in // Fairly often, a bunch of those network calls can finish very close to each other — within few hundred // milliseconds or so. Doing a reload in this case is both wasteful and noticably slow. // Instead, we throttle the call so we trigger the reload at most once a second. throttle.throttle { changeDispatcher.dispatch() } } } func reloadFailed() { allQueries .filter { !isFetching(for: $0) } .filter { !hasResults(for: $0) } .compactMap { refreshAction(for: $0) } .forEach { ActionDispatcher.dispatch($0) } } private func isFetching(`for` query: PluginQuery) -> Bool { switch query { case .all(let site): return store.isFetchingPlugins(site: site) case .featured: return store.isFetchingFeatured() case .feed(let feed): return store.isFetchingFeed(feed: feed) case .directoryEntry: return false } } private func hasResults(`for` query: PluginQuery) -> Bool { switch query { case .all: return installedPlugins != nil case .featured: return featuredPlugins != nil case .feed(.popular): return popularPlugins != nil case .feed(.newest): return newPlugins != nil case .feed(.search): return false case .directoryEntry: return false } } private func noResultsView(for query: PluginQuery) -> NoResultsViewController? { guard hasResults(for: query) == false else { return nil } let noResultsView = NoResultsViewController.controller() noResultsView.delegate = noResultsDelegate noResultsView.hideImageView() let model: NoResultsViewController.Model if isFetching(for: query) { model = NoResultsViewController.Model(title: NSLocalizedString("Loading plugins...", comment: "Messaged displayed when fetching plugins."), accessoryView: NoResultsViewController.loadingAccessoryView()) } else { model = NoResultsViewController.Model(title: NSLocalizedString("Error loading plugins", comment: "Messaged displayed when fetching plugins failed."), buttonText: NSLocalizedString("Try again", comment: "Button that lets users try to reload the plugin directory after loading failure")) } noResultsView.bindViewModel(model) return noResultsView } private func installedRow(presenter: PluginPresenter & PluginListPresenter) -> ImmuTableRow? { guard BlogService.blog(with: site)?.isHostedAtWPcom == false else { // If it's a (probably) AT-eligible site, but not a Jetpack site yet, hide the "installed" row. return nil } let title = NSLocalizedString("Installed", comment: "Header of section in Plugin Directory showing installed plugins") let secondaryTitle = NSLocalizedString("Manage", comment: "Button leading to a screen where users can manage their installed plugins") let query = PluginQuery.all(site: site) if let installed = installedPlugins { return CollectionViewContainerRow(title: title, secondaryTitle: secondaryTitle, sitePlugins: installed, site: site, listViewQuery: query, presenter: presenter) } else if let noResults = noResultsView(for: query) { return CollectionViewContainerRow(title: title, secondaryTitle: secondaryTitle, site: site, listViewQuery: query, noResultsView: noResults, presenter: presenter) } return nil } private func featuredRow(presenter: PluginPresenter & PluginListPresenter) -> ImmuTableRow? { let title = NSLocalizedString("Featured", comment: "Header of section in Plugin Directory showing featured plugins") if let featured = featuredPlugins { return CollectionViewContainerRow(title: title, secondaryTitle: nil, plugins: featured, site: site, accessoryViewCallback: accessoryViewCallback, listViewQuery: nil, presenter: presenter) } else if let noResults = noResultsView(for: .featured) { return CollectionViewContainerRow(title: title, secondaryTitle: nil, site: site, listViewQuery: nil, noResultsView: noResults, presenter: presenter) } return nil } private func popularRow(presenter: PluginPresenter & PluginListPresenter) -> ImmuTableRow? { let title = NSLocalizedString("Popular", comment: "Header of section in Plugin Directory showing popular plugins") let secondaryTitle = NSLocalizedString("See All", comment: "Button in Plugin Directory letting users see more plugins") let query = PluginQuery.feed(type: .popular) if let popular = popularPlugins { return CollectionViewContainerRow(title: title, secondaryTitle: secondaryTitle, plugins: popular, site: site, accessoryViewCallback: accessoryViewCallback, listViewQuery: query, presenter: presenter) } else if let noResults = noResultsView(for: query) { return CollectionViewContainerRow(title: title, secondaryTitle: secondaryTitle, site: site, listViewQuery: query, noResultsView: noResults, presenter: presenter) } return nil } private func newRow(presenter: PluginPresenter & PluginListPresenter) -> ImmuTableRow? { let title = NSLocalizedString("New", comment: "Header of section in Plugin Directory showing newest plugins") let secondaryTitle = NSLocalizedString("See All", comment: "Button in Plugin Directory letting users see more plugins") let query = PluginQuery.feed(type: .newest) if let new = newPlugins { return CollectionViewContainerRow(title: title, secondaryTitle: secondaryTitle, plugins: new, site: site, accessoryViewCallback: accessoryViewCallback, listViewQuery: query, presenter: presenter) } else if let noResults = noResultsView(for: query) { return CollectionViewContainerRow(title: title, secondaryTitle: secondaryTitle, site: site, listViewQuery: query, noResultsView: noResults, presenter: presenter) } return nil } private var accessoryViewCallback: ((PluginDirectoryEntry) -> UIView) { // We need to be able to map between a `PluginDirectoryEntry` and a potentially already installed `Plugin`, // but passing the entire `PluginStore` to the CollectionViewContainerRow isn't the best idea. // Instead, we allow the row to reach back to us and ask for the accessoryView. return { [weak self] (entry: PluginDirectoryEntry) -> UIView in guard let strongSelf = self else { return UIView() } return strongSelf.accessoryView(for: entry) } } func tableViewModel(presenter: PluginPresenter & PluginListPresenter) -> ImmuTable { return ImmuTable(optionalSections: [ ImmuTableSection(optionalRows: [ installedRow(presenter: presenter), featuredRow(presenter: presenter), popularRow(presenter: presenter), newRow(presenter: presenter), ]), ]) } public func refresh() { allQueries .compactMap { refreshAction(for: $0) } .forEach { ActionDispatcher.dispatch($0) } } private var allQueries: [PluginQuery] { return [.all(site: site), .featured, .feed(type: .popular), .feed(type: .newest)] } private func refreshAction(`for` query: PluginQuery) -> PluginAction? { switch query { case .all(let site): return PluginAction.refreshPlugins(site: site) case .featured: return PluginAction.refreshFeaturedPlugins case .feed(let feedType): return PluginAction.refreshFeed(feed: feedType) case .directoryEntry: return nil } } private var installedPlugins: Plugins? { return store.getPlugins(site: site) } private var featuredPlugins: [PluginDirectoryEntry]? { return store.getFeaturedPlugins() } private var popularPlugins: [PluginDirectoryEntry]? { guard let popular = store.getPluginDirectoryFeedPlugins(from: .popular) else { return nil } return Array(popular.prefix(6)) } private var newPlugins: [PluginDirectoryEntry]? { guard let newest = store.getPluginDirectoryFeedPlugins(from: .newest) else { return nil } return Array(newest.prefix(6)) } private func accessoryView(`for` directoryEntry: PluginDirectoryEntry) -> UIView { if let plugin = store.getPlugin(slug: directoryEntry.slug, site: site) { return accessoryView(for: plugin) } return PluginDirectoryAccessoryItem.accessoryView(plugin: directoryEntry) } private func accessoryView(`for` plugin: Plugin) -> UIView { return PluginDirectoryAccessoryItem.accessoryView(pluginState: plugin.state) } } private extension CollectionViewContainerRow where Item == PluginDirectoryEntry, CollectionViewCellType == PluginDirectoryCollectionViewCell { init(title: String, secondaryTitle: String?, plugins: [PluginDirectoryEntry], site: JetpackSiteRef, accessoryViewCallback: @escaping ((Item) -> UIView), listViewQuery: PluginQuery?, presenter: PluginPresenter & PluginListPresenter) { let configureCell: (PluginDirectoryCollectionViewCell, PluginDirectoryEntry) -> Void = { cell, item in cell.configure(with: item) cell.accessoryView = accessoryViewCallback(item) } let actionClosure: ImmuTableAction = { [weak presenter] _ in guard let presenter = presenter, let query = listViewQuery else { return } presenter.present(site: site, query: query) } let cellSelected: (PluginDirectoryEntry) -> Void = { [weak presenter] entry in presenter?.present(directoryEntry: entry) } self.init(data: plugins, title: title, secondaryTitle: secondaryTitle, action: actionClosure, configureCollectionCell: configureCell, collectionCellSelected: cellSelected) } } private extension CollectionViewContainerRow where Item == Plugin, CollectionViewCellType == PluginDirectoryCollectionViewCell { init(title: String, secondaryTitle: String?, sitePlugins: Plugins?, site: JetpackSiteRef, listViewQuery: PluginQuery?, presenter: PluginPresenter & PluginListPresenter) { let configureCell: (PluginDirectoryCollectionViewCell, Plugin) -> Void = { cell, item in cell.configure(with: item) cell.accessoryView = PluginDirectoryAccessoryItem.accessoryView(pluginState: item.state) } let actionClosure: ImmuTableAction = { [weak presenter] _ in guard let presenter = presenter, let query = listViewQuery else { return } presenter.present(site: site, query: query) } let cellSelected: (Plugin) -> Void = { [weak presenter] plugin in guard let capabilities = sitePlugins?.capabilities else { return } presenter?.present(plugin: plugin, capabilities: capabilities) } self.init(data: sitePlugins?.plugins ?? [], title: title, secondaryTitle: secondaryTitle, action: actionClosure, configureCollectionCell: configureCell, collectionCellSelected: cellSelected) } } private extension CollectionViewContainerRow where Item == Any, CollectionViewCellType == PluginDirectoryCollectionViewCell { init(title: String, secondaryTitle: String?, site: JetpackSiteRef, listViewQuery: PluginQuery?, noResultsView: NoResultsViewController, presenter: PluginPresenter & PluginListPresenter) { let actionClosure: ImmuTableAction = { [weak presenter] _ in guard let presenter = presenter, let query = listViewQuery else { return } presenter.present(site: site, query: query) } self.init(title: title, secondaryTitle: secondaryTitle, action: actionClosure, noResultsView: noResultsView) } }
1d455473f1badcd92f8c2ad6be90c924
40.012853
185
0.566817
false
false
false
false
kayak/attributions
refs/heads/master
Attributions/Attributions/LicenseReader.swift
apache-2.0
1
import Foundation struct LicenseReader { let attribution: Attribution private let licenseFiles: [String] init(attribution: Attribution, licenseFiles: [String]) { self.attribution = attribution self.licenseFiles = licenseFiles } func text() throws -> String { switch attribution.license { case .id(let id): return try readText(resource: id.appending(".txt")) case .text(let text): return text case .file(let file, let bundleID): let bundle = bundleFromIdentifier(bundleID) return try readText(resource: file, bundle: bundle) } } private func readText(resource: String) throws -> String { guard let path = licenseFiles.first(where: { $0.contains(resource) }) else { throw NSError.makeError(description: "Could not find file: \(resource)") } let data = try Data(contentsOf: URL(fileURLWithPath: path)) guard let text = String(data: data, encoding: .utf8) else { throw NSError.makeError(description: "Could not read from file: \(resource)") } return text } private func readText(resource: String, bundle: Bundle) throws -> String { let filename = (resource as NSString).deletingPathExtension let fileExtension = (resource as NSString).pathExtension guard let path = bundle.url(forResource: filename, withExtension: fileExtension) else { throw NSError.makeError(description: "Could not find file: \(resource)") } let data = try Data(contentsOf: path) guard let text = String(data: data, encoding: .utf8) else { throw NSError.makeError(description: "Could not read from file: \(resource)") } return text } func verifyLicenseExists() throws { switch attribution.license { case .id(let id): guard licenseFiles.first(where: { $0.contains("\(id).txt") }) != nil else { throw NSError.makeError(description: "Invalid license key \(id) for \(attribution.name)") } case .text(_): break case .file(let file, let bundleID): let bundle = bundleFromIdentifier(bundleID) let filename = (file as NSString).deletingPathExtension let fileExtension = (file as NSString).pathExtension guard bundle.url(forResource: filename, withExtension: fileExtension) != nil else { throw NSError.makeError(description: "Could not find license \(file) for \(attribution.name)") } } } private func bundleFromIdentifier(_ identifier: String?) -> Bundle { if let bundleID = identifier, let licenseBundle = Bundle(identifier: bundleID) { return licenseBundle } else { return .main } } }
55c90648fccace4c8bc1a5fe310aa7f9
38.324324
110
0.610653
false
false
false
false
gilserrap/Bigotes
refs/heads/master
Pods/GRMustache.swift/Mustache/Goodies/ZipFilter.swift
mit
1
// The MIT License // // Copyright (c) 2015 Gwendal Roué // // 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 let ZipFilter = VariadicFilter { (boxes) in // Turn collection arguments into generators. Generators can be iterated // all together, and this is what we need. // // Other kinds of arguments generate an error. var zippedGenerators: [AnyGenerator<MustacheBox>] = [] for box in boxes { if box.isEmpty { // Missing collection does not provide anything } else if let array = box.arrayValue { // Array zippedGenerators.append(anyGenerator(array.generate())) } else { // Error throw MustacheError(kind: .RenderError, message: "Non-enumerable argument in zip filter: `\(box.value)`") } } // Build an array of custom render functions var renderFunctions: [RenderFunction] = [] while true { // Extract from all generators the boxes that should enter the rendering // context at each iteration. // // Given the [1,2,3], [a,b,c] input collections, those boxes would be // [1,a] then [2,b] and finally [3,c]. var zippedBoxes: [MustacheBox] = [] for generator in zippedGenerators { var generator = generator if let box = generator.next() { zippedBoxes.append(box) } } // All generators have been enumerated: stop if zippedBoxes.isEmpty { break; } // Build a render function which extends the rendering context with // zipped boxes before rendering the tag. let renderFunction: RenderFunction = { (info) -> Rendering in var context = zippedBoxes.reduce(info.context) { (context, box) in context.extendedContext(box) } return try info.tag.render(context) } renderFunctions.append(renderFunction) } // Return a box of those boxed render functions return Box(renderFunctions.map(Box)) }
11204f604783ab4a7a6cc81319fe22e0
34.318681
117
0.638967
false
false
false
false
DivineDominion/mac-appdev-code
refs/heads/master
DDDViewDataExample/CoreDataBoxRepository.swift
mit
1
import Cocoa import CoreData import Security public protocol GeneratesIntegerId { func integerId() -> IntegerId } let coreDataReadErrorNotificationName = Notification.Name(rawValue: "Core Data Read Error") open class CoreDataBoxRepository: BoxRepository { let managedObjectContext: NSManagedObjectContext let integerIdGenerator: GeneratesIntegerId public convenience init(managedObjectContext: NSManagedObjectContext) { self.init(managedObjectContext: managedObjectContext, integerIdGenerator: DefaultIntegerIdGenerator()) } public init(managedObjectContext: NSManagedObjectContext, integerIdGenerator: GeneratesIntegerId) { self.managedObjectContext = managedObjectContext self.integerIdGenerator = integerIdGenerator } //MARK: - //MARK: CRUD Actions open func addBox(_ box: Box) { ManagedBox.insertManagedBox(box.boxId, title: box.title, inManagedObjectContext: self.managedObjectContext) } open func removeBox(boxId: BoxId) { guard let managedBox = managedBoxWithId(boxId) else { return } managedObjectContext.delete(managedBox) } open func box(boxId: BoxId) -> Box? { guard let managedBox = managedBoxWithId(boxId) else { return nil } return managedBox.box } fileprivate func managedBoxWithId(_ boxId: BoxId) -> ManagedBox? { return managedBoxWithUniqueId(boxId.identifier) } open func boxes() -> [Box] { let fetchRequest = NSFetchRequest<ManagedBox>(entityName: ManagedBox.entityName) fetchRequest.includesSubentities = true let results: [AnyObject] do { results = try managedObjectContext.fetch(fetchRequest) } catch let error as NSError { logError(error, operation: "find existing boxes") postReadErrorNotification() assertionFailure("error fetching boxes") return [] } return results .map { $0 as! ManagedBox } .map { $0.box } } /// - returns: `NSNotFound` on error open func count() -> Int { let fetchRequest = NSFetchRequest<ManagedBox>(entityName: ManagedBox.entityName) fetchRequest.includesSubentities = false let count: Int do { count = try managedObjectContext.count(for: fetchRequest) } catch { logError(error, operation: "fetching box count") postReadErrorNotification() assertionFailure("error fetching count") return NSNotFound } return count } //MARK: Box ID Generation open func nextId() -> BoxId { func hasManagedBoxWithUniqueId(identifier: IntegerId) -> Bool { return self.managedBoxWithUniqueId(identifier) != nil } let generator = IdGenerator<BoxId>(integerIdGenerator: integerIdGenerator, integerIdIsTaken: hasManagedBoxWithUniqueId) return generator.nextId() } fileprivate func managedBoxWithUniqueId(_ identifier: IntegerId) -> ManagedBox? { let managedObjectModel = managedObjectContext.persistentStoreCoordinator!.managedObjectModel let templateName = "ManagedBoxWithUniqueId" let fetchRequest = managedObjectModel.fetchRequestFromTemplate(withName: templateName, substitutionVariables: ["IDENTIFIER": NSNumber(value: identifier as Int64)]) precondition(hasValue(fetchRequest), "Fetch request named 'ManagedBoxWithUniqueId' is required") let result: [AnyObject] do { result = try managedObjectContext.fetch(fetchRequest!) } catch let error as NSError { logError(error, operation: "find existing box with ID '\(identifier)'") postReadErrorNotification() assertionFailure("error fetching box with id") return nil } return result.first as? ManagedBox } //MARK: Item ID Generation open func nextItemId() -> ItemId { let generator = IdGenerator<ItemId>(integerIdGenerator: integerIdGenerator, integerIdIsTaken: hasManagedItemWithUniqueId) return generator.nextId() } fileprivate func hasManagedItemWithUniqueId(_ identifier: IntegerId) -> Bool { let managedObjectModel = managedObjectContext.persistentStoreCoordinator!.managedObjectModel let templateName = "ManagedItemWithUniqueId" let fetchRequest = managedObjectModel.fetchRequestFromTemplate(withName: templateName, substitutionVariables: ["IDENTIFIER": NSNumber(value: identifier as Int64)]) precondition(hasValue(fetchRequest), "Fetch request named 'ManagedItemWithUniqueId' is required") let count: Int do { count = try managedObjectContext.count(for: fetchRequest!) } catch { logError(error, operation: "find existing item with ID '\(identifier)'") postReadErrorNotification() assertionFailure("error fetching item with id") return false } return count > 0 } //MARK: - //MARK: Error Handling func logError(_ error: Error, operation: String) { NSLog("Failed to \(operation): \(error.localizedDescription)") logDetailledErrors(error) } /// - note: Override-point for error handling in tests. open var notificationCenter: NotificationCenter { return NotificationCenter.default } func postReadErrorNotification() { notificationCenter.post(name: coreDataReadErrorNotificationName, object: self) } }
fa40c15195a4dc98cf17733a3c3dc7b5
33.177515
171
0.653913
false
false
false
false
RamonGilabert/RamonGilabert
refs/heads/master
RamonGilabert/RamonGilabert/ViewModel.swift
mit
1
import UIKit struct Constant { struct Setup { static let NumberOfPagesScrolling = 3 as Int static let NameOfNotification = "MovieDismissed" } struct Size { static let DeviceWidth = UIScreen.mainScreen().bounds.width static let DeviceHeight = UIScreen.mainScreen().bounds.height static let RelationHeights = (Constant.Size.DeviceHeight - 75)/480 } struct Positioning { static let WidthMenuButton = 75 * Constant.Size.RelationHeights as CGFloat static let HeightMenuButton = 94.6 * Constant.Size.RelationHeights as CGFloat static let XPositionLeftMenuButton = Constant.Size.DeviceWidth / 8 static let XPositionRightMenuButton = Constant.Size.DeviceWidth - Constant.Positioning.XPositionLeftMenuButton - Constant.Positioning.WidthMenuButton static let MenuButtonsSpacing = (Constant.Size.DeviceHeight - ((Constant.Positioning.HeightMenuButton) * 3) - 33) / 4 static let CrossSize = 26.5 as CGFloat static let CrossXPosition = 19 as CGFloat static let CrossYPosition = 25 as CGFloat static let HeightOfHeaderStory = 70 * Constant.Size.RelationHeights } struct TableViewConstants { static let Identifier = "CellID" static let MinimumPadding = 15 as CGFloat static let HeightOfImages = 400 * Constant.Size.RelationHeights/2 as CGFloat static let LineSpacingStory = 10 as CGFloat } struct TableViewSkillVariables { static let Identifier = "CellID" static let MinimumPadding = 20 as CGFloat static let HeightHeaderView = Constant.Size.DeviceHeight * 0.45 static let ProfileImageSize = 130 * Constant.Size.RelationHeights/1.15 static let SizeOfGraphWidth = 18 * Constant.Size.RelationHeights*1.15 static let SizeOfGraph = 110 * Constant.Size.RelationHeights*1.15 + Constant.TableViewSkillVariables.SizeOfGraphWidth/2 static let HeightCellGraphs = 200 * Constant.Size.RelationHeights static let LineSpacingStory = 7 as CGFloat static let HeightBottomImage = 260 * Constant.Size.RelationHeights } struct ProjectsViewPositioning { static let MinimumPaddingView = 15 as CGFloat static let WidthOfMainView = Constant.Size.DeviceWidth - (Constant.ProjectsViewPositioning.MinimumPaddingView * 2) static let HeightOfMainView = Constant.Size.DeviceHeight - (140 * Constant.Size.RelationHeights) static let YPositionMainView = (Constant.Size.DeviceHeight - Constant.ProjectsViewPositioning.HeightOfMainView) / 2 static let HeightImageViewProject = Constant.ProjectsViewPositioning.HeightOfMainView / 1.65 static let MinimumPaddingInsideView = 15 * Constant.Size.RelationHeights static let YPositionLabelExplanation = Constant.ProjectsViewPositioning.HeightImageViewProject + Constant.ProjectsViewPositioning.MinimumPaddingInsideView static let WidthLabelInside = Constant.ProjectsViewPositioning.WidthOfMainView - (Constant.ProjectsViewPositioning.MinimumPaddingInsideView * 2) static let HeightLabelsInside = Constant.ProjectsViewPositioning.HeightOfMainView - Constant.ProjectsViewPositioning.HeightImageViewProject - (Constant.ProjectsViewPositioning.MinimumPaddingInsideView * (1.5)) static let WidthBlurView = Constant.ProjectsViewPositioning.WidthOfMainView static let HeightBlurView = Constant.ProjectsViewPositioning.HeightImageViewProject / 4.2 static let LineSpacingStory = 6 * Constant.Size.RelationHeights } struct TipsViewPositioning { static let MinimumViewPadding = 25 * Constant.Size.RelationHeights static let WidthTipFirstIcon = 98 * Constant.Size.RelationHeights static let HeightTipFirstIcon = 53 * Constant.Size.RelationHeights static let WidthTipSecondIcon = 71 * Constant.Size.RelationHeights static let HeightTipSecondIcon = 83 * Constant.Size.RelationHeights static let WidthTipThirdIcon = 91 * Constant.Size.RelationHeights static let HeightTipThirdIcon = 97 * Constant.Size.RelationHeights static let LabelExplainingWidth = Constant.Size.DeviceWidth - (Constant.TipsViewPositioning.MinimumViewPadding * 2) static let PositionPaddingFromBottom = 35 * Constant.Size.RelationHeights static let FirstIconImage = "swipe-right-left" static let SecondIconImage = "swipe-up-icon" static let ThirdIconImage = "menu-icon" static let TextForSlider = "Slide left to start" } struct SocialViewPositioning { static let HeightOfView = Constant.Size.DeviceHeight / 2.75 static let SizeOfSocialButtons = 100 * Constant.Size.RelationHeights static let CrossSize = 24 * Constant.Size.RelationHeights static let YPositionCross = 20 * Constant.Size.RelationHeights static let SpacingBetweenViews = (Constant.Size.DeviceWidth - (Constant.SocialViewPositioning.SizeOfSocialButtons * 3)) / 4 } } class ViewModel: NSObject { // MARK: Main layout func initMainScrollViewInView(view: UIView) -> UIScrollView { let scrollView = UIScrollView(frame: CGRectMake(0, 0, Constant.Size.DeviceWidth, Constant.Size.DeviceHeight)) scrollView.contentSize = CGSizeMake(Constant.Size.DeviceWidth * CGFloat(Constant.Setup.NumberOfPagesScrolling), Constant.Size.DeviceHeight) scrollView.backgroundColor = UIColor.whiteColor() scrollView.pagingEnabled = true scrollView.showsHorizontalScrollIndicator = false view.addSubview(scrollView) return scrollView } func initChildScrollViewsInView(view: UIView) -> UIScrollView { let scrollView = UIScrollView(frame: CGRectMake(0, 0, Constant.Size.DeviceWidth, Constant.Size.DeviceHeight)) scrollView.contentSize = CGSizeMake(Constant.Size.DeviceWidth, Constant.Size.DeviceHeight * 5) view.addSubview(scrollView) return scrollView } // MARK: Menu layout func buttonInMenu(xPosition: CGFloat, yPosition: CGFloat, image: String, text: String, viewController: UIViewController, tag: Int) -> UIButton { let button = UIButton(frame: CGRectMake( xPosition, yPosition, Constant.Positioning.WidthMenuButton, Constant.Positioning.HeightMenuButton)) button.setBackgroundImage(UIImage(named: image), forState: UIControlState.Normal) button.setTitle(text, forState: UIControlState.Normal) button.titleLabel!.font = UIFont_WWDC.menuButtonFont() button.titleEdgeInsets = UIEdgeInsetsMake(125 * Constant.Size.RelationHeights, 0, 0, 0) button.setTitleColor(UIColor_WWDC.highlightedColorButtons(), forState: UIControlState.Highlighted) button.addTarget(viewController, action: "onMenuButtonTouched:", forControlEvents: UIControlEvents.TouchUpInside) button.tag = tag viewController.view.addSubview(button) return button } func setBlurView() -> UIVisualEffectView { let blurEffect = UIBlurEffect(style: UIBlurEffectStyle.Dark) let blurView = UIVisualEffectView(effect: blurEffect) blurView.frame = CGRectMake(0, 0, Constant.Size.DeviceWidth, Constant.Size.DeviceHeight) return blurView } // MARK: Story layout func setTitleLabelInView(view: UIView) -> UILabel { let label = UILabel(frame: CGRectMake(0, 23, Constant.Size.DeviceWidth, 33)) label.text = "MENU" label.textAlignment = NSTextAlignment.Center label.textColor = UIColor.whiteColor() label.font = UIFont_WWDC.titleFont() view.addSubview(label) return label } func setCoverImageWithGradient() -> UIImageView { let colorTop = UIColor(hue: 0, saturation: 0, brightness: 1, alpha: 0).CGColor let colorMiddle = UIColor(hue: 0, saturation: 0, brightness: 0.06, alpha: 0.6).CGColor let colorBottom = UIColor.blackColor().CGColor let gradientLayer = CAGradientLayer() gradientLayer.colors = [ colorTop, colorMiddle, colorBottom ] gradientLayer.locations = [ 0.0, 0.6, 1.0 ] gradientLayer.frame = CGRectMake(0, 0, Constant.Size.DeviceWidth, Constant.Size.DeviceHeight) let imageView = UIImageView(image: UIImage(named: "background-image-menu-simulator")) imageView.frame = CGRectMake(0, -Constant.Size.DeviceHeight, Constant.Size.DeviceWidth, Constant.Size.DeviceHeight) imageView.contentMode = UIViewContentMode.ScaleAspectFill imageView.clipsToBounds = true imageView.layer.addSublayer(gradientLayer) return imageView } func setFullScreenTableView(view: UIView, delegate: UITableViewDelegate, dataSource: UITableViewDataSource) -> UITableView { let tableView = UITableView(frame: CGRectMake(0, 0, Constant.Size.DeviceWidth, Constant.Size.DeviceHeight)) tableView.registerClass(RGStoryCustomTableViewCell.classForCoder(), forCellReuseIdentifier: Constant.TableViewConstants.Identifier) tableView.contentInset = UIEdgeInsetsMake(Constant.Size.DeviceHeight, 0, 0, 0) tableView.separatorStyle = UITableViewCellSeparatorStyle.None tableView.allowsSelection = false tableView.delegate = delegate tableView.dataSource = dataSource view.addSubview(tableView) return tableView } func setTitleBlogPost(view: UIView) -> UILabel { let label = UILabel(frame: CGRectMake(20, 0, Constant.Size.DeviceWidth - 40, 0)) label.text = Text.Titles.StoryTitle label.font = UIFont_WWDC.titleStoryFont() label.numberOfLines = 2 label.textColor = UIColor.whiteColor() label.sizeToFit() label.frame = CGRectMake(20, (Constant.Size.DeviceHeight - label.frame.height) / 2 - 35, label.frame.width, label.frame.height) view.addSubview(label) return label } func setSubtitleBlogPost(view: UIView) -> UILabel { let label = UILabel(frame: CGRectMake(20, 0, Constant.Size.DeviceWidth - 40, 18)) label.text = Text.Titles.StorySubtitle label.font = UIFont_WWDC.subTitleStoryFont() label.textColor = UIColor.whiteColor() label.adjustsFontSizeToFitWidth = true label.minimumScaleFactor = 0 view.addSubview(label) return label } func setSecondaryBlogPostLabel() -> UILabel { let label = UILabel(frame: CGRectMake(0, 0, Constant.Size.DeviceWidth, Constant.Positioning.HeightOfHeaderStory)) label.text = Text.Titles.StorySecondaryTitle label.font = UIFont_WWDC.secondaryTitleFont() label.textAlignment = NSTextAlignment.Center label.textColor = UIColor.whiteColor() label.transform = CGAffineTransformMakeTranslation(0, -100) return label } func setFakeBlurView() -> UIImageView { let blurView = setBlurView() let imageView = UIImageView(frame: CGRectMake(0, -Constant.Size.DeviceHeight, Constant.Size.DeviceWidth, Constant.Size.DeviceHeight)) imageView.image = UIImage(named: "background-image-menu-simulator") imageView.contentMode = UIViewContentMode.ScaleAspectFill imageView.clipsToBounds = true imageView.addSubview(blurView) return imageView } func textLabelInBlogPost(text: String) -> UILabel { let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.lineSpacing = Constant.TableViewConstants.LineSpacingStory let label = UILabel(frame: CGRectMake(Constant.TableViewConstants.MinimumPadding, Constant.TableViewConstants.MinimumPadding, Constant.Size.DeviceWidth - (Constant.TableViewConstants.MinimumPadding * 2), 0)) label.font = UIFont_WWDC.mainTextBlogPost() label.numberOfLines = 0 label.attributedText = NSAttributedString(string: text, attributes: [NSParagraphStyleAttributeName : paragraphStyle]) label.sizeToFit() label.frame = CGRectMake(label.frame.origin.x, label.frame.origin.y, label.frame.width, label.frame.height) return label } // MARK: Skills layout func setSkillTableView(view: UIView, delegate: UITableViewDelegate, dataSource: UITableViewDataSource) -> UITableView { let tableView = UITableView(frame: CGRectMake(0, 0, Constant.Size.DeviceWidth, Constant.Size.DeviceHeight)) tableView.registerClass(RGSkillsCustomTableViewCell.classForCoder(), forCellReuseIdentifier: Constant.TableViewConstants.Identifier) tableView.contentInset = UIEdgeInsetsMake(Constant.TableViewSkillVariables.HeightHeaderView, 0, 0, 0) tableView.separatorStyle = UITableViewCellSeparatorStyle.None tableView.allowsSelection = false tableView.delegate = delegate tableView.dataSource = dataSource view.addSubview(tableView) return tableView } func setHeaderViewSkills(view: UIView, image: String) -> UIImageView { let imageView = UIImageView(frame: CGRectMake(0, -Constant.TableViewSkillVariables.HeightHeaderView, Constant.Size.DeviceWidth, Constant.TableViewSkillVariables.HeightHeaderView)) imageView.image = UIImage(named: image) imageView.contentMode = UIViewContentMode.ScaleAspectFill imageView.clipsToBounds = true view.addSubview(imageView) return imageView } func setProfileImageSkills(view: UIView) -> UIImageView { let imageView = UIImageView(frame: CGRectMake((Constant.Size.DeviceWidth - Constant.TableViewSkillVariables.ProfileImageSize)/2, -Constant.TableViewSkillVariables.HeightHeaderView + (Constant.TableViewSkillVariables.HeightHeaderView - Constant.TableViewSkillVariables.ProfileImageSize)/2, Constant.TableViewSkillVariables.ProfileImageSize, Constant.TableViewSkillVariables.ProfileImageSize)) imageView.image = UIImage(named: "profile-image-skills") imageView.contentMode = UIViewContentMode.ScaleAspectFill imageView.clipsToBounds = true imageView.layer.cornerRadius = imageView.frame.width/2 imageView.layer.borderColor = UIColor(red:0.51, green:0.82, blue:0.2, alpha:1).CGColor imageView.layer.borderWidth = 4 view.addSubview(imageView) return imageView } func setAttributedLabelInExplanation(text: String) -> UILabel { let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.lineSpacing = Constant.TableViewSkillVariables.LineSpacingStory let label = UILabel(frame: CGRectMake(Constant.TableViewSkillVariables.MinimumPadding, Constant.TableViewSkillVariables.MinimumPadding/1.5, Constant.Size.DeviceWidth - (Constant.TableViewSkillVariables.MinimumPadding * 2), 0)) label.textColor = UIColor_WWDC.skillsColor() label.font = UIFont_WWDC.explanationInSkills() label.numberOfLines = 0 label.attributedText = NSAttributedString(string: text, attributes: [NSParagraphStyleAttributeName : paragraphStyle]) label.sizeToFit() return label } // MARK: Projects layout func setBackgroundProjects(view: UIView) -> UIImageView { let imageView = UIImageView(frame: CGRectMake(0, -15, Constant.Size.DeviceWidth, Constant.Size.DeviceHeight + 30)) imageView.contentMode = UIViewContentMode.ScaleAspectFill imageView.clipsToBounds = true imageView.image = UIImage(named: "background-image-menu-simulator") view.addSubview(imageView) return imageView } func setMainView(view: UIView) -> UIView { let viewToAdd = UIView(frame: CGRectMake(Constant.ProjectsViewPositioning.MinimumPaddingView, Constant.ProjectsViewPositioning.YPositionMainView, Constant.ProjectsViewPositioning.WidthOfMainView, Constant.ProjectsViewPositioning.HeightOfMainView)) viewToAdd.clipsToBounds = true viewToAdd.layer.cornerRadius = 7 viewToAdd.backgroundColor = UIColor_WWDC.titleProjectsColor() view.addSubview(viewToAdd) return viewToAdd } func setTitleProject(view: UIView, text: String) -> UILabel { let label = UILabel(frame: CGRectMake(0, Constant.ProjectsViewPositioning.HeightBlurView/6, Constant.ProjectsViewPositioning.WidthOfMainView, Constant.ProjectsViewPositioning.HeightBlurView/3)) label.textAlignment = NSTextAlignment.Center label.textColor = UIColor_WWDC.titleProjectsColor() label.font = UIFont_WWDC.titleInProjects() label.text = text view.addSubview(label) return label } func setSubtitleProject(view: UIView, text: String) -> UILabel { let label = UILabel(frame: CGRectMake(0, Constant.ProjectsViewPositioning.HeightBlurView/2.5, Constant.ProjectsViewPositioning.WidthOfMainView, Constant.ProjectsViewPositioning.HeightBlurView - Constant.ProjectsViewPositioning.HeightBlurView/3)) label.textAlignment = NSTextAlignment.Center label.textColor = UIColor_WWDC.titleProjectsColor() label.font = UIFont_WWDC.subtitleInProjects() label.text = text view.addSubview(label) return label } func setImageViewProject(view: UIView, image: String) -> UIImageView { let blurView = setBlurView() blurView.frame = CGRectMake(0, 0, Constant.ProjectsViewPositioning.WidthOfMainView, Constant.ProjectsViewPositioning.HeightBlurView) let imageView = UIImageView(frame: CGRectMake(0, 0, Constant.ProjectsViewPositioning.WidthOfMainView, Constant.ProjectsViewPositioning.HeightImageViewProject)) imageView.contentMode = UIViewContentMode.ScaleAspectFill imageView.clipsToBounds = true imageView.image = UIImage(named: image) view.addSubview(imageView) imageView.addSubview(blurView) return imageView } func setExplanationProject(view: UIView, text: String) -> UILabel { let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.lineSpacing = Constant.ProjectsViewPositioning.LineSpacingStory let label = UILabel(frame: CGRectMake(Constant.ProjectsViewPositioning.MinimumPaddingInsideView, Constant.ProjectsViewPositioning.YPositionLabelExplanation, Constant.ProjectsViewPositioning.WidthOfMainView - (Constant.ProjectsViewPositioning.MinimumPaddingInsideView * 2), Constant.ProjectsViewPositioning.HeightLabelsInside)) label.textColor = UIColor_WWDC.explanationProjectsColor() label.font = UIFont_WWDC.explanationInProjects() label.numberOfLines = 0 label.attributedText = NSAttributedString(string: text, attributes: [NSParagraphStyleAttributeName : paragraphStyle]) label.sizeToFit() view.addSubview(label) return label } // MARK: Tips layout func setTipsIcon(view: UIView, frame: CGRect, image: String) -> UIImageView { let imageView = UIImageView(frame: frame) imageView.image = UIImage(named: image) imageView.contentMode = UIViewContentMode.ScaleAspectFit imageView.clipsToBounds = true view.addSubview(imageView) return imageView } func setTipsTitle(view: UIView, yPosition: CGFloat, text: String) -> UILabel { let label = UILabel(frame: CGRectMake(30 * Constant.Size.RelationHeights, yPosition, Constant.TipsViewPositioning.LabelExplainingWidth, 0)) label.text = text label.numberOfLines = 0 label.textAlignment = NSTextAlignment.Center label.font = UIFont_WWDC.titleTips() label.textColor = UIColor_WWDC.tipsColor() label.sizeToFit() label.frame = CGRectMake(label.frame.origin.x, label.frame.origin.y, Constant.TipsViewPositioning.LabelExplainingWidth, label.frame.height) view.addSubview(label) return label } // MARK: Social layout func setBackgroundViewSocial(view: UIView) -> UIView { let backgroundView = UIView(frame: CGRectMake(0, 0, Constant.Size.DeviceWidth, Constant.Size.DeviceHeight)) backgroundView.backgroundColor = UIColor.blackColor() backgroundView.alpha = 0 view.addSubview(backgroundView) return backgroundView } func setContainerOfViewSocial(view: UIView) -> UIView { let viewToAdd = UIView(frame: CGRectMake(0, Constant.Size.DeviceHeight - Constant.SocialViewPositioning.HeightOfView, Constant.Size.DeviceWidth, Constant.SocialViewPositioning.HeightOfView * 2)) viewToAdd.backgroundColor = UIColor_WWDC.almostBlackColor() viewToAdd.transform = CGAffineTransformMakeTranslation(0, Constant.SocialViewPositioning.HeightOfView) let labelWithTitle = UILabel(frame: CGRectMake(0, 0, Constant.Size.DeviceWidth, Constant.SocialViewPositioning.HeightOfView / 3)) labelWithTitle.text = "Social" labelWithTitle.font = UIFont_WWDC.titleInProjects() labelWithTitle.textColor = UIColor.whiteColor() labelWithTitle.textAlignment = NSTextAlignment.Center viewToAdd.addSubview(labelWithTitle) view.addSubview(viewToAdd) return viewToAdd } func setCrossButtonSocial(view: UIView, viewController: UIViewController) -> UIButton { let button = UIButton(frame: CGRectMake(20, Constant.SocialViewPositioning.YPositionCross, Constant.SocialViewPositioning.CrossSize, Constant.SocialViewPositioning.CrossSize)) button.setBackgroundImage(UIImage(named: "cross-button-image"), forState: UIControlState.Normal) button.transform = CGAffineTransformMakeScale(0, 0) button.addTarget(viewController, action: "onCrossButtonPressed", forControlEvents: UIControlEvents.TouchUpInside) view.addSubview(button) return button } func setTwitterButton(view: UIView, viewController: UIViewController) -> UIButton { let button = UIButton(frame: CGRectMake(Constant.SocialViewPositioning.SpacingBetweenViews, (Constant.SocialViewPositioning.HeightOfView - Constant.SocialViewPositioning.SizeOfSocialButtons)/2 + 20, Constant.SocialViewPositioning.SizeOfSocialButtons, Constant.SocialViewPositioning.SizeOfSocialButtons)) button.setBackgroundImage(UIImage(named: "twitter-icon-social"), forState: UIControlState.Normal) button.tag = 0 button.transform = CGAffineTransformMakeTranslation(0, Constant.SocialViewPositioning.HeightOfView) button.addTarget(viewController, action: "onSocialButtonPressed:", forControlEvents: UIControlEvents.TouchUpInside) view.addSubview(button) return button } func setDribbbleButton(view: UIView, viewController: UIViewController) -> UIButton { let button = UIButton(frame: CGRectMake((Constant.SocialViewPositioning.SpacingBetweenViews * 2) + Constant.SocialViewPositioning.SizeOfSocialButtons, (Constant.SocialViewPositioning.HeightOfView - Constant.SocialViewPositioning.SizeOfSocialButtons)/2 + 20, Constant.SocialViewPositioning.SizeOfSocialButtons, Constant.SocialViewPositioning.SizeOfSocialButtons)) button.setBackgroundImage(UIImage(named: "dribbble-icon-social"), forState: UIControlState.Normal) button.tag = 1 button.transform = CGAffineTransformMakeTranslation(0, Constant.SocialViewPositioning.HeightOfView) button.addTarget(viewController, action: "onSocialButtonPressed:", forControlEvents: UIControlEvents.TouchUpInside) view.addSubview(button) return button } func setGithubButton(view: UIView, viewController: UIViewController) -> UIButton { let button = UIButton(frame: CGRectMake((Constant.SocialViewPositioning.SpacingBetweenViews * 3) + (Constant.SocialViewPositioning.SizeOfSocialButtons * 2), (Constant.SocialViewPositioning.HeightOfView - Constant.SocialViewPositioning.SizeOfSocialButtons)/2 + 20, Constant.SocialViewPositioning.SizeOfSocialButtons, Constant.SocialViewPositioning.SizeOfSocialButtons)) button.setBackgroundImage(UIImage(named: "github-icon-social"), forState: UIControlState.Normal) button.tag = 2 button.transform = CGAffineTransformMakeTranslation(0, Constant.SocialViewPositioning.HeightOfView) button.addTarget(viewController, action: "onSocialButtonPressed:", forControlEvents: UIControlEvents.TouchUpInside) view.addSubview(button) return button } // MARK: WebView layout func setCrossButtonWebView(view: UIView, viewController: UIViewController) { let crossButton = UIButton(frame: CGRectMake(20, (view.frame.height - 24)/2, 24, 24)) crossButton.setBackgroundImage(UIImage(named: "cross-button-image"), forState: UIControlState.Normal) crossButton.addTarget(viewController, action: "onCloseButtonPressed", forControlEvents: UIControlEvents.TouchUpInside) view.addSubview(crossButton) } func setWebView(view: UIView, webViewDelegate: UIWebViewDelegate) -> UIWebView { let webView = UIWebView(frame: CGRectMake(0, Constant.Size.DeviceHeight/9, Constant.Size.DeviceWidth, Constant.Size.DeviceHeight - Constant.Size.DeviceHeight/10)) webView.delegate = webViewDelegate view.addSubview(webView) return webView } func setBackButton(view: UIView, viewController: UIViewController) -> UIButton { let button = UIButton(frame: CGRectMake(Constant.Size.DeviceWidth - 28 - 60, (view.frame.height - 24)/2, 14, 24)) button.setBackgroundImage(UIImage(named: "back-button-image"), forState: UIControlState.Normal) button.addTarget(viewController, action: "onBackButtonPressed:", forControlEvents: UIControlEvents.TouchUpInside) view.addSubview(button) return button } func setForwardButton(view: UIView, viewController: UIViewController) -> UIButton { let button = UIButton(frame: CGRectMake(Constant.Size.DeviceWidth - 14 - 20, (view.frame.height - 24)/2, 14, 24)) button.setBackgroundImage(UIImage(named: "forward-button-image"), forState: UIControlState.Normal) button.addTarget(viewController, action: "onForwardButtonPressed:", forControlEvents: UIControlEvents.TouchUpInside) view.addSubview(button) return button } func setErrorMessage(view: UIView) -> UIView { let viewError = UIView(frame: CGRectMake(0, Constant.Size.DeviceHeight / 9, Constant.Size.DeviceWidth, Constant.Size.DeviceHeight - Constant.Size.DeviceHeight / 9)) viewError.transform = CGAffineTransformMakeScale(0, 0) viewError.backgroundColor = UIColor_WWDC.almostBlackColor() let labelError = UILabel(frame: viewError.frame) labelError.text = "There was an error loading your web! Try again later!" labelError.font = UIFont_WWDC.menuButtonFont() labelError.textColor = UIColor.whiteColor() viewError.addSubview(labelError) view.addSubview(viewError) return viewError } }
588f46535dbf5ba57bbe6bd713a15cb3
48.669131
399
0.733356
false
false
false
false
passt0r/MaliDeck
refs/heads/master
MaliDeck/HitStackView.swift
gpl-3.0
1
// // HitStackView.swift // MaliDeck // // Created by Dmytro Pasinchuk on 16.02.17. // Copyright © 2017 Dmytro Pasinchuk. All rights reserved. // import UIKit @IBDesignable class HitStackView: UIStackView { /* // Only override draw() if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func draw(_ rect: CGRect) { // Drawing code } */ @IBInspectable var availableHits: Int = 14 { didSet { setupButtons() } } var hitsLeft = 0 { didSet { updateButtonStages() } }//hits that left and all available hits (take data from cardViewController table View) var buttons = [UIButton]() //all available buttons @IBInspectable var buttonSize: CGSize = CGSize(width: 20, height: 17) { didSet { setupButtons() } } override init(frame: CGRect) { super.init(frame: frame) setupButtons() } required init(coder: NSCoder) { super.init(coder: coder) setupButtons() } //MARK: Button actoins func touched(button: UIButton) { guard let buttonIndex = buttons.index(of: button) else { fatalError("Unexpected button was touched") } let hits = buttonIndex + 1 if(hitsLeft == availableHits - 1) && (buttonIndex == 0) { hitsLeft = availableHits } else { hitsLeft = availableHits - hits } } private func updateButtonStages() { for (index, buttton) in buttons.enumerated() { let highlitedButtons = availableHits - hitsLeft buttton.isSelected = index < highlitedButtons } } //MARK: Hit buttons private func setupButtons() { //clear all buttons that can be before start setup for button in buttons { removeArrangedSubview(button) button.removeFromSuperview() } buttons.removeAll() let bundle = Bundle(for: type(of: self)) let hited = UIImage(named: "hited", in: bundle, compatibleWith: self.traitCollection) let notHited = UIImage(named: "not_hited", in: bundle, compatibleWith: self.traitCollection) //generate all buttons for index in 0..<availableHits { let button = UIButton() //generate button button.setImage(notHited, for: .normal) button.setImage(hited, for: .selected) //added images for all posible stages button.setImage(hited, for: .highlighted) button.setImage(hited, for: [.highlighted, .selected]) // set constraints to the generated buttons button.translatesAutoresizingMaskIntoConstraints = false button.heightAnchor.constraint(equalToConstant: buttonSize.height).isActive = true button.widthAnchor.constraint(equalToConstant: buttonSize.width).isActive = true // set accebility Label for button button.accessibilityLabel = "Take \(index + 1) wounds" //add action event for button button.addTarget(self, action: #selector(HitStackView.touched(button:)), for: .touchUpInside) //add button to the StackView addArrangedSubview(button) //add button to the array of buttons buttons.append(button) } } }
6c8609f351b53e9e8644e88c8a9638c6
29.368421
106
0.60312
false
false
false
false
thedreamer979/Calvinus
refs/heads/master
Calvin/BackgroundView.swift
gpl-3.0
1
// // BackgroundView.swift // Calvin // // Created by Arion Zimmermann on 26.02.17. // Copyright © 2017 AZEntreprise. All rights reserved. // import UIKit class BackgroundView : UIView { override init(frame: CGRect) { super.init(frame: frame) let imageView = UIImageView(image: UIImage(named: "calvin.jpg")) imageView.frame = self.bounds imageView.contentMode = .scaleAspectFill let blurEffect = UIBlurEffect(style: .light) let blurEffectView = UIVisualEffectView(effect: blurEffect) blurEffectView.alpha = 0.95 blurEffectView.frame = imageView.bounds let vibrancyEffect = UIVibrancyEffect(blurEffect: blurEffect) let vibrancyEffectView = UIVisualEffectView(effect: vibrancyEffect) vibrancyEffectView.frame = imageView.bounds self.addSubview(imageView) self.addSubview(blurEffectView) self.addSubview(vibrancyEffectView) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } }
f6a75814ca5f71486bef02e67569f77a
28.324324
75
0.658065
false
false
false
false
josve05a/wikipedia-ios
refs/heads/develop
Wikipedia/Code/InsertMediaSelectedImageView.swift
mit
4
import UIKit import AVFoundation final class InsertMediaSelectedImageView: SetupView { private let imageView = UIImageView() private let imageInfoView = InsertMediaImageInfoView.wmf_viewFromClassNib()! private let imageInfoContainerView = UIView() private var imageInfoContainerViewBottomConstraint: NSLayoutConstraint? public var moreInformationAction: ((URL) -> Void)? var image: UIImage? { return imageView.image } var searchResult: InsertMediaSearchResult? override func setup() { super.setup() imageView.accessibilityIgnoresInvertColors = true imageView.contentMode = .scaleAspectFit imageView.translatesAutoresizingMaskIntoConstraints = false wmf_addSubviewWithConstraintsToEdges(imageView) imageInfoContainerView.translatesAutoresizingMaskIntoConstraints = false addSubview(imageInfoContainerView) imageInfoContainerView.alpha = 0.8 let leadingConstraint = imageInfoContainerView.leadingAnchor.constraint(equalTo: leadingAnchor) let trailingConstraint = imageInfoContainerView.trailingAnchor.constraint(equalTo: trailingAnchor) let bottomConstraint = imageInfoContainerView.bottomAnchor.constraint(equalTo: bottomAnchor) let heightConstraint = imageInfoContainerView.heightAnchor.constraint(lessThanOrEqualTo: imageView.heightAnchor, multiplier: 0.5) imageInfoContainerViewBottomConstraint = bottomConstraint NSLayoutConstraint.activate([ leadingConstraint, trailingConstraint, bottomConstraint, heightConstraint ]) imageInfoView.translatesAutoresizingMaskIntoConstraints = false imageInfoContainerView.backgroundColor = UIColor.white imageInfoContainerView.wmf_addSubviewWithConstraintsToEdges(imageInfoView) } public func configure(with imageURL: URL, searchResult: InsertMediaSearchResult, theme: Theme, completion: @escaping (Error?) -> Void) { imageView.image = nil imageView.wmf_setImage(with: imageURL, detectFaces: false, onGPU: true, failure: { error in completion(error) }) { self.searchResult = searchResult self.imageView.backgroundColor = .clear self.imageInfoView.moreInformationAction = self.moreInformationAction self.imageInfoView.configure(with: searchResult, showImageDescription: false, showLicenseName: true, showMoreInformationButton: true, theme: theme) completion(nil) } } } extension InsertMediaSelectedImageView: Themeable { func apply(theme: Theme) { backgroundColor = theme.colors.baseBackground imageInfoContainerView.backgroundColor = backgroundColor imageView.backgroundColor = .clear } }
43068632a981acf16d3983f7610a5c36
42.384615
159
0.734043
false
false
false
false
justindarc/firefox-ios
refs/heads/master
Client/Helpers/TabEventHandler.swift
mpl-2.0
1
/* 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 Storage /** * A handler can be a plain old swift object. It does not need to extend any * other object, but can. * * ``` * class HandoffHandler { * init() { * register(self, forTabEvents: .didLoadFavicon, .didLoadPageMetadata) * } * } * ``` * * Handlers can implement any or all `TabEventHandler` methods. If you * implement a method, you should probably `registerFor` the event above. * * ``` * extension HandoffHandler: TabEventHandler { * func tab(_ tab: Tab, didLoadPageMetadata metadata: PageMetadata) { * print("\(tab) has \(pageMetadata)") * } * * func tab(_ tab: Tab, didLoadFavicon favicon: Favicon) { * print("\(tab) has \(favicon)") * } * } * ``` * * Tab events should probably be only posted from one place, to avoid cycles. * * ``` * TabEvent.post(.didLoadPageMetadata(aPageMetadata), for: tab) * ``` * * In this manner, we are able to use the notification center and have type safety. * */ // As we want more events we add more here. // Each event needs: // 1. a method in the TabEventHandler. // 2. a default implementation of the method – so not everyone needs to implement it // 3. a TabEventLabel, which is needed for registration // 4. a TabEvent, with whatever parameters are needed. // i) a case to map the event to the event label (var label) // ii) a case to map the event to the event handler (func handle:with:) protocol TabEventHandler: AnyObject { func tab(_ tab: Tab, didChangeURL url: URL) func tab(_ tab: Tab, didLoadPageMetadata metadata: PageMetadata) func tab(_ tab: Tab, didLoadFavicon favicon: Favicon?, with: Data?) func tabDidGainFocus(_ tab: Tab) func tabDidLoseFocus(_ tab: Tab) func tabDidClose(_ tab: Tab) func tab(_ tab: Tab, didDeriveMetadata metadata: DerivedMetadata) func tabDidToggleDesktopMode(_ tab: Tab) func tabDidChangeContentBlocking(_ tab: Tab) } // Provide default implmentations, because we don't want to litter the code with // empty methods, and `@objc optional` doesn't really work very well. extension TabEventHandler { func tab(_ tab: Tab, didChangeURL url: URL) {} func tab(_ tab: Tab, didLoadPageMetadata metadata: PageMetadata) {} func tab(_ tab: Tab, didLoadFavicon favicon: Favicon?, with: Data?) {} func tabDidGainFocus(_ tab: Tab) {} func tabDidLoseFocus(_ tab: Tab) {} func tabDidClose(_ tab: Tab) {} func tab(_ tab: Tab, didDeriveMetadata metadata: DerivedMetadata) {} func tabDidToggleDesktopMode(_ tab: Tab) {} func tabDidChangeContentBlocking(_ tab: Tab) {} } enum TabEventLabel: String { case didChangeURL case didLoadPageMetadata case didLoadFavicon case didGainFocus case didLoseFocus case didClose case didDeriveMetadata case didToggleDesktopMode case didChangeContentBlocking } // Names of events must be unique! enum TabEvent { case didChangeURL(URL) case didLoadPageMetadata(PageMetadata) case didLoadFavicon(Favicon?, with: Data?) case didGainFocus case didLoseFocus case didClose case didDeriveMetadata(DerivedMetadata) case didToggleDesktopMode case didChangeContentBlocking var label: TabEventLabel { let str = "\(self)".components(separatedBy: "(")[0] // Will grab just the name from 'didChangeURL(...)' guard let result = TabEventLabel(rawValue: str) else { fatalError("Bad tab event label.") } return result } func handle(_ tab: Tab, with handler: TabEventHandler) { switch self { case .didChangeURL(let url): handler.tab(tab, didChangeURL: url) case .didLoadPageMetadata(let metadata): handler.tab(tab, didLoadPageMetadata: metadata) case .didLoadFavicon(let favicon, let data): handler.tab(tab, didLoadFavicon: favicon, with: data) case .didGainFocus: handler.tabDidGainFocus(tab) case .didLoseFocus: handler.tabDidLoseFocus(tab) case .didClose: handler.tabDidClose(tab) case .didDeriveMetadata(let metadata): handler.tab(tab, didDeriveMetadata: metadata) case .didToggleDesktopMode: handler.tabDidToggleDesktopMode(tab) case .didChangeContentBlocking: handler.tabDidChangeContentBlocking(tab) } } } // Hide some of the machinery away from the boiler plate above. //////////////////////////////////////////////////////////////////////////////////////// extension TabEventLabel { var name: Notification.Name { return Notification.Name(self.rawValue) } } extension TabEvent { func notification(for tab: Tab) -> Notification { return Notification(name: label.name, object: tab, userInfo: ["payload": self]) } /// Use this method to post notifications to any concerned listeners. static func post(_ event: TabEvent, for tab: Tab) { assert(Thread.isMainThread) center.post(event.notification(for: tab)) } } // These methods are used by TabEventHandler implementers. // Their usage remains consistent, even as we add more event types and handler methods. //////////////////////////////////////////////////////////////////////////////////////// private let center = NotificationCenter() private struct AssociatedKeys { static var key = "observers" } private class ObserverWrapper: NSObject { var observers = [NSObjectProtocol]() deinit { observers.forEach { observer in center.removeObserver(observer) } } } extension TabEventHandler { /// Implementations of handles should use this method to register for events. /// `TabObservers` should be preserved for unregistering later. func register(_ observer: AnyObject, forTabEvents events: TabEventLabel...) { let wrapper = ObserverWrapper() wrapper.observers = events.map { [weak self] eventType in center.addObserver(forName: eventType.name, object: nil, queue: .main) { notification in guard let tab = notification.object as? Tab, let event = notification.userInfo?["payload"] as? TabEvent else { return } if let me = self { event.handle(tab, with: me) } } } objc_setAssociatedObject(observer, &AssociatedKeys.key, wrapper, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) } }
035fc3ae73a91409a9042b5be905b8f2
34.182292
130
0.647816
false
false
false
false
Pluto-tv/RxSwift
refs/heads/master
Rx.playground/Pages/Subjects.xcplaygroundpage/Contents.swift
mit
14
//: [<< Previous](@previous) - [Index](Index) import RxSwift /*: A Subject is a sort of bridge or proxy that is available in some implementations of ReactiveX that acts both as an observer and as an Observable. Because it is an observer, it can subscribe to one or more Observables, and because it is an Observable, it can pass through the items it observes by reemitting them, and it can also emit new items. */ func writeSequenceToConsole<O: ObservableType>(name: String, sequence: O) { sequence .subscribe { e in print("Subscription: \(name), event: \(e)") } } /*: ## PublishSubject `PublishSubject` emits to an observer only those items that are emitted by the source Observable(s) subsequent to the time of the subscription. ![](https://raw.githubusercontent.com/kzaher/rxswiftcontent/master/MarbleDiagrams/png/publishsubject.png) ![](https://raw.githubusercontent.com/kzaher/rxswiftcontent/master/MarbleDiagrams/png/publishsubject_error.png) */ example("PublishSubject") { let subject = PublishSubject<String>() writeSequenceToConsole("1", sequence: subject) subject.on(.Next("a")) subject.on(.Next("b")) writeSequenceToConsole("2", sequence: subject) subject.on(.Next("c")) subject.on(.Next("d")) } /*: ## ReplaySubject `ReplaySubject` emits to any observer all of the items that were emitted by the source Observable(s), regardless of when the observer subscribes. ![](https://raw.githubusercontent.com/kzaher/rxswiftcontent/master/MarbleDiagrams/png/replaysubject.png) */ example("ReplaySubject") { let subject = ReplaySubject<String>.create(bufferSize: 1) writeSequenceToConsole("1", sequence: subject) subject.on(.Next("a")) subject.on(.Next("b")) writeSequenceToConsole("2", sequence: subject) subject.on(.Next("c")) subject.on(.Next("d")) } /*: ## BehaviorSubject When an observer subscribes to a `BehaviorSubject`, it begins by emitting the item most recently emitted by the source Observable (or a seed/default value if none has yet been emitted) and then continues to emit any other items emitted later by the source Observable(s). ![](https://raw.githubusercontent.com/kzaher/rxswiftcontent/master/MarbleDiagrams/png/behaviorsubject.png) ![](https://raw.githubusercontent.com/kzaher/rxswiftcontent/master/MarbleDiagrams/png/behaviorsubject_error.png) */ example("BehaviorSubject") { let subject = BehaviorSubject(value: "z") writeSequenceToConsole("1", sequence: subject) subject.on(.Next("a")) subject.on(.Next("b")) writeSequenceToConsole("2", sequence: subject) subject.on(.Next("c")) subject.on(.Next("d")) subject.on(.Completed) } /*: ## Variable `Variable` wraps `BehaviorSubject`. Advantage of using variable over `BehaviorSubject` is that variable can never explicitly complete or error out, and `BehaviorSubject` can in case `Error` or `Completed` message is send to it. `Variable` will also automatically complete in case it's being deallocated. */ example("Variable") { let variable = Variable("z") writeSequenceToConsole("1", sequence: variable) variable.value = "a" variable.value = "b" writeSequenceToConsole("2", sequence: variable) variable.value = "c" variable.value = "d" } //: [Index](Index) - [Next >>](@next)
2b56905f7cdd87e2248e5db429add9be
32.908163
344
0.718929
false
false
false
false
stephentyrone/swift
refs/heads/master
test/attr/attr_dynamic_member_lookup.swift
apache-2.0
1
// RUN: %target-typecheck-verify-swift var global = 42 @dynamicMemberLookup struct Gettable { subscript(dynamicMember member: StaticString) -> Int { return 42 } } @dynamicMemberLookup struct Settable { subscript(dynamicMember member: StaticString) -> Int { get {return 42} set {} } } @dynamicMemberLookup struct MutGettable { subscript(dynamicMember member: StaticString) -> Int { mutating get { return 42 } } } @dynamicMemberLookup struct NonMutSettable { subscript(dynamicMember member: StaticString) -> Int { get { return 42 } nonmutating set {} } } func test(a: Gettable, b: Settable, c: MutGettable, d: NonMutSettable) { global = a.wyverns a.flavor = global // expected-error {{cannot assign to property: 'a' is a 'let' constant}} global = b.flavor b.universal = global // expected-error {{cannot assign to property: 'b' is a 'let' constant}} b.thing += 1 // expected-error {{left side of mutating operator isn't mutable: 'b' is a 'let' constant}} var bm = b global = bm.flavor bm.universal = global bm.thing += 1 var cm = c global = c.dragons // expected-error {{cannot use mutating getter on immutable value: 'c' is a 'let' constant}} global = c[dynamicMember: "dragons"] // expected-error {{cannot use mutating getter on immutable value: 'c' is a 'let' constant}} global = cm.dragons c.woof = global // expected-error {{cannot use mutating getter on immutable value: 'c' is a 'let' constant}} var dm = d global = d.dragons // ok global = dm.dragons // ok d.woof = global // ok dm.woof = global // ok } func testIUO(a: Gettable!, b: Settable!) { global = a.wyverns a.flavor = global // expected-error {{cannot assign through dynamic lookup property: 'a' is a 'let' constant}} global = b.flavor b.universal = global // expected-error {{cannot assign through dynamic lookup property: 'b' is a 'let' constant}} var bm: Settable! = b global = bm.flavor bm.universal = global } //===----------------------------------------------------------------------===// // Returning a function //===----------------------------------------------------------------------===// @dynamicMemberLookup struct FnTest { subscript(dynamicMember member: StaticString) -> (Int) -> () { return { x in () } } } func testFunction(x: FnTest) { x.phunky(12) } func testFunctionIUO(x: FnTest!) { x.flavor(12) } //===----------------------------------------------------------------------===// // Explicitly declared members take precedence //===----------------------------------------------------------------------===// @dynamicMemberLookup struct Dog { public var name = "Kaylee" subscript(dynamicMember member: String) -> String { return "Zoey" } } func testDog(person: Dog) -> String { return person.name + person.otherName } //===----------------------------------------------------------------------===// // Returning an IUO //===----------------------------------------------------------------------===// @dynamicMemberLookup struct IUOResult { subscript(dynamicMember member: StaticString) -> Int! { get { return 42 } nonmutating set {} } } func testIUOResult(x: IUOResult) { x.foo?.negate() // Test mutating writeback. let _: Int = x.bar // Test implicitly forced optional let b = x.bar // expected-note@-1{{short-circuit}} // expected-note@-2{{coalesce}} // expected-note@-3{{force-unwrap}} let _: Int = b // expected-error {{value of optional type 'Int?' must be unwrapped to a value of type 'Int'}} // expected-note@-1{{coalesce}} // expected-note@-2{{force-unwrap}} } //===----------------------------------------------------------------------===// // Error cases //===----------------------------------------------------------------------===// // Subscript index must be ExpressibleByStringLiteral. @dynamicMemberLookup struct Invalid1 { // expected-error @+1 {{@dynamicMemberLookup attribute requires 'Invalid1' to have a 'subscript(dynamicMember:)' method that accepts either 'ExpressibleByStringLiteral' or a key path}} subscript(dynamicMember member: Int) -> Int { return 42 } } // Subscript may not be variadic. @dynamicMemberLookup struct Invalid2 { // expected-error @+1 {{@dynamicMemberLookup attribute requires 'Invalid2' to have a 'subscript(dynamicMember:)' method that accepts either 'ExpressibleByStringLiteral' or a key path}} subscript(dynamicMember member: String...) -> Int { return 42 } } // References to overloads are resolved just like normal subscript lookup: // they are either contextually disambiguated or are invalid. @dynamicMemberLookup struct Ambiguity { subscript(dynamicMember member: String) -> Int { return 42 } subscript(dynamicMember member: String) -> Float { return 42 } } func testAmbiguity(a: Ambiguity) { let _: Int = a.flexibility let _: Float = a.dynamism _ = a.dynamism // expected-error {{ambiguous use of 'subscript(dynamicMember:)'}} } // expected-error @+1 {{'@dynamicMemberLookup' attribute cannot be applied to this declaration}} @dynamicMemberLookup extension Int { subscript(dynamicMember member: String) -> Int { fatalError() } } // expected-error @+1 {{'@dynamicMemberLookup' attribute cannot be applied to this declaration}} @dynamicMemberLookup func NotAllowedOnFunc() {} // @dynamicMemberLookup cannot be declared on a base class and fulfilled with a // derived class. // expected-error @+1 {{@dynamicMemberLookup attribute requires 'InvalidBase' to have a 'subscript(dynamicMember:)' method that accepts either 'ExpressibleByStringLiteral' or a key path}} @dynamicMemberLookup class InvalidBase {} class InvalidDerived : InvalidBase { subscript(dynamicMember: String) -> Int { get {}} } // expected-error @+1 {{value of type 'InvalidDerived' has no member 'dynamicallyLookedUp'}} _ = InvalidDerived().dynamicallyLookedUp //===----------------------------------------------------------------------===// // Existentials //===----------------------------------------------------------------------===// @dynamicMemberLookup protocol DynamicProtocol { subscript(dynamicMember member: StaticString) -> DynamicProtocol { get nonmutating set } } struct MyDynamicStruct : DynamicProtocol { subscript(dynamicMember member: StaticString) -> DynamicProtocol { get { fatalError() } nonmutating set {} } } func testMutableExistential(a: DynamicProtocol, b: MyDynamicStruct) -> DynamicProtocol { a.x.y = b b.x.y = b return a.foo.bar.baz } // Verify protocol compositions and protocol refinements work. protocol SubDynamicProtocol : DynamicProtocol {} typealias ProtocolComp = AnyObject & DynamicProtocol func testMutableExistential2(a: AnyObject & DynamicProtocol, b: SubDynamicProtocol, c: ProtocolComp & AnyObject) { a.x.y = b b.x.y = b c.x.y = b } @dynamicMemberLookup protocol ProtoExt {} extension ProtoExt { subscript(dynamicMember member: String) -> String { get {} } } extension String: ProtoExt {} func testProtoExt() -> String { let str = "test" return str.sdfsdfsdf } //===----------------------------------------------------------------------===// // JSON example //===----------------------------------------------------------------------===// @dynamicMemberLookup enum JSON { case IntValue(Int) case StringValue(String) case ArrayValue(Array<JSON>) case DictionaryValue(Dictionary<String, JSON>) var stringValue: String? { if case .StringValue(let str) = self { return str } return nil } subscript(index: Int) -> JSON? { if case .ArrayValue(let arr) = self { return index < arr.count ? arr[index] : nil } return nil } subscript(key: String) -> JSON? { if case .DictionaryValue(let dict) = self { return dict[key] } return nil } subscript(dynamicMember member: String) -> JSON? { if case .DictionaryValue(let dict) = self { return dict[member] } return nil } } func testJsonExample(x: JSON) -> String? { _ = x.name?.first return x.name?.first?.stringValue } //===----------------------------------------------------------------------===// // Class inheritance tests //===----------------------------------------------------------------------===// @dynamicMemberLookup class BaseClass { subscript(dynamicMember member: String) -> Int { return 42 } } class DerivedClass : BaseClass {} func testDerivedClass(x: BaseClass, y: DerivedClass) -> Int { return x.life - y.the + x.universe - y.and + x.everything } // Test that derived classes can add a setter. class DerivedClassWithSetter : BaseClass { override subscript(dynamicMember member: String) -> Int { get { return super[dynamicMember: member] } set {} } } func testOverrideSubscript(a: BaseClass, b: DerivedClassWithSetter) { let x = a.frotz + b.garbalaz b.baranozo = x a.balboza = 12 // expected-error {{cannot assign to property}} } //===----------------------------------------------------------------------===// // Generics //===----------------------------------------------------------------------===// @dynamicMemberLookup struct SettableGeneric1<T> { subscript(dynamicMember member: StaticString) -> T? { get {} nonmutating set {} } } func testGenericType<T>(a: SettableGeneric1<T>, b: T) -> T? { a.dfasdf = b return a.dfsdffff } func testConcreteGenericType(a: SettableGeneric1<Int>) -> Int? { a.dfasdf = 42 return a.dfsdffff } @dynamicMemberLookup struct SettableGeneric2<T> { subscript<U: ExpressibleByStringLiteral>(dynamicMember member: U) -> T { get {} nonmutating set {} } } func testGenericType2<T>(a: SettableGeneric2<T>, b: T) -> T? { a[dynamicMember: "fasdf"] = b a.dfasdf = b return a.dfsdffff } func testConcreteGenericType2(a: SettableGeneric2<Int>) -> Int? { a.dfasdf = 42 return a.dfsdffff } // SR-8077 test case. // `subscript(dynamicMember:)` works as a `@dynamicMemberLookup` protocol // requirement. @dynamicMemberLookup protocol GenericProtocol { associatedtype S: ExpressibleByStringLiteral associatedtype T subscript(dynamicMember member: S) -> T { get } } @dynamicMemberLookup class GenericClass<S: ExpressibleByStringLiteral, T> { let t: T init(_ t: T) { self.t = t } subscript(dynamicMember member: S) -> T { return t } } func testGenerics<S, T, P: GenericProtocol>( a: P, b: AnyObject & GenericClass<S, T> ) where P.S == S, P.T == T { let _: T = a.wew let _: T = b.lad } //===----------------------------------------------------------------------===// // Keypaths //===----------------------------------------------------------------------===// @dynamicMemberLookup class KP { subscript(dynamicMember member: String) -> Int { return 7 } } _ = \KP.[dynamicMember: "hi"] _ = \KP.testLookup /* KeyPath based dynamic lookup */ struct Point { var x: Int let y: Int // expected-note 2 {{change 'let' to 'var' to make it mutable}} private let z: Int = 0 // expected-note 10 {{declared here}} } struct Rectangle { var topLeft, bottomRight: Point } @dynamicMemberLookup struct Lens<T> { var obj: T init(_ obj: T) { self.obj = obj } subscript<U>(dynamicMember member: KeyPath<T, U>) -> Lens<U> { get { return Lens<U>(obj[keyPath: member]) } } subscript<U>(dynamicMember member: WritableKeyPath<T, U>) -> Lens<U> { get { return Lens<U>(obj[keyPath: member]) } set { obj[keyPath: member] = newValue.obj } } } var topLeft = Point(x: 0, y: 0) var bottomRight = Point(x: 10, y: 10) var lens = Lens(Rectangle(topLeft: topLeft, bottomRight: bottomRight)) _ = lens.topLeft _ = lens.topLeft.x _ = lens.topLeft.y _ = lens.topLeft.z // expected-error {{'z' is inaccessible due to 'private' protection level}} _ = lens.bottomRight _ = lens.bottomRight.x _ = lens.bottomRight.y _ = lens.bottomRight.z // expected-error {{'z' is inaccessible due to 'private' protection level}} _ = \Lens<Point>.x _ = \Lens<Point>.y _ = \Lens<Point>.z // expected-error {{'z' is inaccessible due to 'private' protection level}} _ = \Lens<Rectangle>.topLeft.x _ = \Lens<Rectangle>.topLeft.y _ = \Lens<Rectangle>.topLeft.z // expected-error {{'z' is inaccessible due to 'private' protection level}} _ = \Lens<[Int]>.count _ = \Lens<[Int]>.[0] _ = \Lens<[[Int]]>.[0].count lens.topLeft = Lens(Point(x: 1, y: 2)) // Ok lens.bottomRight.x = Lens(11) // Ok lens.bottomRight.y = Lens(12) // expected-error {{cannot assign to property: 'y' is a 'let' constant}} lens.bottomRight.z = Lens(13) // expected-error {{'z' is inaccessible due to 'private' protection level}} func acceptKeyPathDynamicLookup(_: Lens<Int>) {} acceptKeyPathDynamicLookup(lens.topLeft.x) acceptKeyPathDynamicLookup(lens.topLeft.y) acceptKeyPathDynamicLookup(lens.topLeft.z) // expected-error {{'z' is inaccessible due to 'private' protection level}} var tupleLens = Lens<(String, Int)>(("ultimate question", 42)) _ = tupleLens.0.count _ = tupleLens.1 var namedTupleLens = Lens<(question: String, answer: Int)>((question: "ultimate question", answer: 42)) _ = namedTupleLens.question.count _ = namedTupleLens.answer @dynamicMemberLookup class A<T> { var value: T init(_ v: T) { self.value = v } subscript<U>(dynamicMember member: KeyPath<T, U>) -> U { get { return value[keyPath: member] } } } // Let's make sure that keypath dynamic member lookup // works with inheritance class B<T> : A<T> {} func bar(_ b: B<Point>) { let _: Int = b.x let _ = b.y let _: Float = b.y // expected-error {{cannot convert value of type 'Int' to specified type 'Float'}} let _ = b.z // expected-error {{'z' is inaccessible due to 'private' protection level}} } // Existentials and IUOs @dynamicMemberLookup protocol KeyPathLookup { associatedtype T var value: T { get } subscript(dynamicMember member: KeyPath<T, Int>) -> Int! { get } } extension KeyPathLookup { subscript(dynamicMember member: KeyPath<T, Int>) -> Int! { get { return value[keyPath: member] } } } class C<T> : KeyPathLookup { var value: T init(_ v: T) { self.value = v } } func baz(_ c: C<Point>) { let _: Int = c.x let _ = c.y let _: Float = c.y // expected-error {{cannot convert value of type 'Int?' to specified type 'Float'}} let _ = c.z // expected-error {{'z' is inaccessible due to 'private' protection level}} } @dynamicMemberLookup class D<T> { var value: T init(_ v: T) { self.value = v } subscript<U: Numeric>(dynamicMember member: KeyPath<T, U>) -> (U) -> U { get { return { offset in self.value[keyPath: member] + offset } } } } func faz(_ d: D<Point>) { let _: Int = d.x(42) let _ = d.y(1 + 0) let _: Float = d.y(1 + 0) // expected-error {{cannot convert value of type 'Int' to specified type 'Float'}} let _ = d.z(1 + 0) // expected-error {{'z' is inaccessible due to 'private' protection level}} } @dynamicMemberLookup struct SubscriptLens<T> { var value: T var counter: Int = 0 subscript(foo: String) -> Int { get { return 42 } } subscript(offset: Int) -> Int { get { return counter } set { counter = counter + newValue } } subscript<U>(dynamicMember member: KeyPath<T, U>) -> U! { get { return value[keyPath: member] } } subscript<U>(dynamicMember member: WritableKeyPath<T, U>) -> U { get { return value[keyPath: member] } set { value[keyPath: member] = newValue } } } func keypath_with_subscripts(_ arr: SubscriptLens<[Int]>, _ dict: inout SubscriptLens<[String: Int]>) { _ = arr[0..<3] for idx in 0..<arr.count { let _ = arr[idx] print(arr[idx]) } _ = arr["hello"] // Ok _ = dict["hello"] // Ok _ = arr["hello"] = 42 // expected-error {{cannot assign through subscript: subscript is get-only}} _ = dict["hello"] = 0 // Ok _ = arr[0] = 42 // expected-error {{cannot assign through subscript: 'arr' is a 'let' constant}} _ = dict[0] = 1 // Ok if let index = dict.value.firstIndex(where: { $0.value == 42 }) { let _ = dict[index] } dict["ultimate question"] = 42 } func keypath_with_incorrect_return_type(_ arr: Lens<Array<Int>>) { for idx in 0..<arr.count { // expected-error@-1 {{cannot convert value of type 'Int' to expected argument type 'Lens<Int>'}} let _ = arr[idx] } } struct WithTrailingClosure { subscript(fn: () -> Int) -> Int { get { return fn() } nonmutating set { _ = fn() + newValue } } subscript(offset: Int, _ fn: () -> Int) -> Int { get { return offset + fn() } } } func keypath_with_trailing_closure_subscript(_ ty: inout SubscriptLens<WithTrailingClosure>) { _ = ty[0] { 42 } // expected-error {{subscript index of type '() -> Int' in a key path must be Hashable}} _ = ty[0] { 42 } = 0 // expected-error {{cannot assign through subscript: subscript is get-only}} // expected-error@-1 {{subscript index of type '() -> Int' in a key path must be Hashable}} _ = ty[] { 42 } // expected-error {{subscript index of type '() -> Int' in a key path must be Hashable}} _ = ty[] { 42 } = 0 // expected-error {{subscript index of type '() -> Int' in a key path must be Hashable}} } func keypath_to_subscript_to_property(_ lens: inout Lens<Array<Rectangle>>) { _ = lens[0].topLeft.x _ = lens[0].topLeft.y _ = lens[0].topLeft.x = Lens(0) _ = lens[0].topLeft.y = Lens(1) // expected-error@-1 {{cannot assign to property: 'y' is a 'let' constant}} } @dynamicMemberLookup struct SingleChoiceLens<T> { var obj: T init(_ obj: T) { self.obj = obj } subscript<U>(dynamicMember member: WritableKeyPath<T, U>) -> U { get { return obj[keyPath: member] } set { obj[keyPath: member] = newValue } } } // Make sure that disjunction filtering optimization doesn't // impede keypath dynamic member lookup by eagerly trying to // simplify disjunctions with a single viable choice. func test_lens_with_a_single_choice(a: inout SingleChoiceLens<[Int]>) { a[0] = 1 // Ok } func test_chain_of_recursive_lookups(_ lens: Lens<Lens<Lens<Point>>>) { _ = lens.x _ = lens.y _ = lens.z // expected-error {{'z' is inaccessible due to 'private' protection level}} // Make sure that 'obj' field could be retrieved at any level _ = lens.obj _ = lens.obj.obj _ = lens.obj.x _ = lens.obj.obj.x _ = \Lens<Lens<Point>>.x _ = \Lens<Lens<Point>>.obj.x } // KeyPath Dynamic Member Lookup can't refer to methods, mutating setters and static members // because of the KeyPath limitations func invalid_refs_through_dynamic_lookup() { struct S { static var foo: Int = 42 func bar() -> Q { return Q() } static func baz(_: String) -> Int { return 0 } } struct Q { var faz: Int = 0 } func test(_ lens: A<S>) { _ = lens.foo // expected-error {{dynamic key path member lookup cannot refer to static member 'foo'}} _ = lens.bar() // expected-error {{dynamic key path member lookup cannot refer to instance method 'bar()'}} _ = lens.bar().faz + 1 // expected-error {{dynamic key path member lookup cannot refer to instance method 'bar()'}} _ = lens.baz("hello") // expected-error {{dynamic key path member lookup cannot refer to static method 'baz'}} } } // SR-10597 final class SR10597 { } @dynamicMemberLookup struct SR10597_W<T> { var obj: T init(_ obj: T) { self.obj = obj } subscript<U>(dynamicMember member: KeyPath<T, U>) -> U { return obj[keyPath: member] } var wooo: SR10597 { SR10597() } // expected-note {{declared here}} } _ = SR10597_W<SR10597>(SR10597()).wooooo // expected-error {{value of type 'SR10597_W<SR10597>' has no dynamic member 'wooooo' using key path from root type 'SR10597'; did you mean 'wooo'?}} _ = SR10597_W<SR10597>(SR10597()).bla // expected-error {{value of type 'SR10597_W<SR10597>' has no dynamic member 'bla' using key path from root type 'SR10597'}} final class SR10597_1 { var woo: Int? // expected-note 2 {{'woo' declared here}} } @dynamicMemberLookup struct SR10597_1_W<T> { var obj: T init(_ obj: T) { self.obj = obj } subscript<U>(dynamicMember member: KeyPath<T, U>) -> U { return obj[keyPath: member] } } _ = SR10597_1_W<SR10597_1>(SR10597_1()).wooo // expected-error {{value of type 'SR10597_1_W<SR10597_1>' has no dynamic member 'wooo' using key path from root type 'SR10597_1'; did you mean 'woo'?}} _ = SR10597_1_W<SR10597_1>(SR10597_1()).bla // expected-error {{value of type 'SR10597_1_W<SR10597_1>' has no dynamic member 'bla' using key path from root type 'SR10597_1'}} // SR-10557 @dynamicMemberLookup struct SR_10557_S { subscript(dynamicMember: String) -> String { // expected-error {{@dynamicMemberLookup attribute requires 'SR_10557_S' to have a 'subscript(dynamicMember:)' method that accepts either 'ExpressibleByStringLiteral' or a key path}} // expected-note@-1 {{add an explicit argument label to this subscript to satisfy the @dynamicMemberLookup requirement}}{{13-13=dynamicMember }} fatalError() } } @dynamicMemberLookup struct SR_10557_S1 { subscript(foo bar: String) -> String { // expected-error {{@dynamicMemberLookup attribute requires 'SR_10557_S1' to have a 'subscript(dynamicMember:)' method that accepts either 'ExpressibleByStringLiteral' or a key path}} fatalError() } subscript(foo: String) -> String { // expected-error {{@dynamicMemberLookup attribute requires 'SR_10557_S1' to have a 'subscript(dynamicMember:)' method that accepts either 'ExpressibleByStringLiteral' or a key path}} // expected-note@-1 {{add an explicit argument label to this subscript to satisfy the @dynamicMemberLookup requirement}} {{13-13=dynamicMember }} fatalError() } } @dynamicMemberLookup struct SR11877 { subscript(dynamicMember member: Substring) -> Int { 0 } } _ = \SR11877.okay func test_infinite_self_recursion() { @dynamicMemberLookup struct Recurse<T> { subscript<U>(dynamicMember member: KeyPath<Recurse<T>, U>) -> Int { return 1 } } _ = Recurse<Int>().foo // expected-error@-1 {{value of type 'Recurse<Int>' has no dynamic member 'foo' using key path from root type 'Recurse<Int>'}} } // rdar://problem/60225883 - crash during solution application (ExprRewritter::buildKeyPathDynamicMemberIndexExpr) func test_combination_of_keypath_and_string_lookups() { @dynamicMemberLookup struct Outer { subscript(dynamicMember member: String) -> Outer { Outer() } subscript(dynamicMember member: KeyPath<Inner, Inner>) -> Outer { Outer() } } @dynamicMemberLookup struct Inner { subscript(dynamicMember member: String) -> Inner { Inner() } } func test(outer: Outer) { _ = outer.hello.world // Ok } } // SR-12626 @dynamicMemberLookup struct SR12626 { var i: Int subscript(dynamicMember member: KeyPath<SR12626, Int>) -> Int { get { self[keyPath: member] } set { self[keyPath: member] = newValue } // expected-error {{cannot assign through subscript: 'member' is a read-only key path}} } } // SR-12245 public struct SR12425_S {} @dynamicMemberLookup public struct SR12425_R {} internal var rightStructInstance: SR12425_R = SR12425_R() public extension SR12425_R { subscript<T>(dynamicMember member: WritableKeyPath<SR12425_S, T>) -> T { get { rightStructInstance[keyPath: member] } // expected-error {{key path with root type 'SR12425_S' cannot be applied to a base of type 'SR12425_R'}} set { rightStructInstance[keyPath: member] = newValue } // expected-error {{key path with root type 'SR12425_S' cannot be applied to a base of type 'SR12425_R'}} } } @dynamicMemberLookup public struct SR12425_R1 {} public extension SR12425_R1 { subscript<T>(dynamicMember member: KeyPath<SR12425_R1, T>) -> T { get { rightStructInstance[keyPath: member] } // expected-error {{key path with root type 'SR12425_R1' cannot be applied to a base of type 'SR12425_R'}} } }
aeecd108d712ed998bcb0de72c46283d
28.140777
229
0.628477
false
false
false
false
QQLS/YouTobe
refs/heads/master
YouTube/Class/Subscriptions/Controller/BQSubscriptionsViewController.swift
apache-2.0
1
// // BQSubscriptionsViewController.swift // YouTube // // Created by xiupai on 2017/3/15. // Copyright © 2017年 QQLS. All rights reserved. // import UIKit private let subscriptionTopCellReuseID = BQSubscriptionTopCell.nameOfClass class BQSubscriptionsViewController: BQBaseCollectionViewController { override func viewDidLoad() { super.viewDidLoad() } } // MARK: - UICollectionViewDataSource extension BQSubscriptionsViewController { override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return videoList.count + 1 } override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { if 0 == indexPath.item { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: subscriptionTopCellReuseID, for: indexPath) return cell } else { if let cell = collectionView.dequeueReusableCell(withReuseIdentifier: videoCellReuseID, for: indexPath) as? BQVideoListCell { cell.videoModel = videoList[indexPath.item - 1] return cell } } return UICollectionViewCell() } } // MARK: - UICollectionViewDelegateFlowLayout extension BQSubscriptionsViewController { override func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { if 0 == indexPath.item { return CGSize(width: collectionView.width, height: 70) } else { return super.collectionView(collectionView, layout: collectionViewLayout, sizeForItemAt: indexPath) } } }
58ba522361633e58ec3ad0a5ade2175d
33.588235
169
0.704649
false
false
false
false
adobe-behancemobile/PeekPan
refs/heads/master
PeekPan/Demo/ImageEditorController.swift
apache-2.0
1
/****************************************************************************** * * ADOBE CONFIDENTIAL * ___________________ * * Copyright 2016 Adobe Systems Incorporated * All Rights Reserved. * * This file is licensed to you under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. You may obtain a copy * of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS * OF ANY KIND, either express or implied. See the License for the specific language * governing permissions and limitations under the License. ******************************************************************************/ import CoreImage import CoreGraphics import UIKit class ImageEditorController : UIViewController, UIViewControllerPreviewingDelegate, PeekPanCoordinatorDelegate, PeekPanCoordinatorDataSource, PeekPanViewControllerDelegate { @IBOutlet var brightnessSlider: UISlider! @IBOutlet var contrastSlider: UISlider! @IBOutlet var sharpnessSlider: UISlider! @IBOutlet var brightnessLabel: UILabel! @IBOutlet var contrastLabel: UILabel! @IBOutlet var sharpnessLabel: UILabel! let coreImage = CIImage(image: UIImage(named: "color_image")!) var brightnessValue: CGFloat = 0.0 var contrastValue: CGFloat = 1.0 var sharpnessValue: CGFloat = 0.4 weak var selectedSlider: UISlider? @IBOutlet var imageView: UIImageView! var peekPanCoordinator: PeekPanCoordinator! let peekPanVC = PeekPanViewController() // MARK: UIViewController override func viewDidLoad() { super.viewDidLoad() brightnessLabel.text = String(describing: brightnessValue) contrastLabel.text = String(describing: contrastValue) sharpnessLabel.text = String(describing: sharpnessValue) } override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) { super.traitCollectionDidChange(previousTraitCollection) if #available(iOS 9.0, *) { if traitCollection.forceTouchCapability == .available { registerForPreviewing(with: self, sourceView: view) peekPanCoordinator = PeekPanCoordinator(sourceView: view) peekPanCoordinator.delegate = peekPanVC peekPanCoordinator.dataSource = self peekPanVC.delegate = self } } } // MARK: Methods @IBAction func didSetBrightness(_ sender: UISlider) { brightnessValue = CGFloat(sender.value) brightnessLabel.text = NSString(format: "%.2f", sender.value) as String updateImageWithCurrentValues(imageView) } @IBAction func didSetContrast(_ sender: UISlider) { contrastValue = CGFloat(sender.value) contrastLabel.text = NSString(format: "%.2f", sender.value) as String updateImageWithCurrentValues(imageView) } @IBAction func didSetSharpness(_ sender: UISlider) { sharpnessValue = CGFloat(sender.value) sharpnessLabel.text = NSString(format: "%.2f", sender.value) as String updateImageWithCurrentValues(imageView) } func updateSelected() { if selectedSlider == nil { return } if selectedSlider == brightnessSlider { selectedSlider!.value = Float(brightnessValue) brightnessLabel!.text = NSString(format: "%.2f", brightnessValue) as String } else if selectedSlider == contrastSlider { selectedSlider!.value = Float(contrastValue) contrastLabel!.text = NSString(format: "%.2f", contrastValue) as String } else if selectedSlider == sharpnessSlider { selectedSlider!.value = Float(sharpnessValue) sharpnessLabel!.text = NSString(format: "%.2f", sharpnessValue) as String } } func revertSelected() { if selectedSlider == nil { return } if selectedSlider == brightnessSlider { brightnessValue = CGFloat(selectedSlider!.value) } else if selectedSlider == contrastSlider { contrastValue = CGFloat(selectedSlider!.value) } else if selectedSlider == sharpnessSlider { sharpnessValue = CGFloat(selectedSlider!.value) } } func updateImageWithCurrentValues(_ imageView: UIImageView) { let context = CIContext(options: nil) var extent = CGRect.zero let colorFilter = CIFilter(name: "CIColorControls")! // brightness & contrast colorFilter.setValue(coreImage, forKey: kCIInputImageKey) colorFilter.setValue(brightnessValue, forKey: kCIInputBrightnessKey) colorFilter.setValue(contrastValue, forKey: kCIInputContrastKey) var outputImage = colorFilter.value(forKey: kCIOutputImageKey) as! CIImage let sharpnessFilter = CIFilter(name: "CISharpenLuminance")! sharpnessFilter.setValue(outputImage, forKey: kCIInputImageKey) sharpnessFilter.setValue(sharpnessValue, forKey: kCIInputSharpnessKey) outputImage = sharpnessFilter.value(forKey: kCIOutputImageKey) as! CIImage extent = outputImage.extent imageView.image = UIImage(cgImage: context.createCGImage(outputImage, from: extent)!) } // MARK: PeekPanCoordinatorDataSource func maximumIndex(for peekPanCoordinator: PeekPanCoordinator) -> Int { return 0 } func shouldStartFromMinimumIndex(for peekPanCoordinator: PeekPanCoordinator) -> Bool { return false } func minimumPoint(for peekPanCoordinator: PeekPanCoordinator) -> CGPoint { if let slider = selectedSlider { return slider.frame.origin } return CGPoint.zero } func maximumPoint(for peekPanCoordinator: PeekPanCoordinator) -> CGPoint { if let slider = selectedSlider { return CGPoint(x: slider.frame.maxX, y: slider.frame.maxY) } return CGPoint.zero } // MARK: PeekPanViewControllerDelegate func peekPanCoordinatorEnded(_ peekPanCoordinator: PeekPanCoordinator) { if peekPanCoordinator.state == .popped { updateSelected() updateImageWithCurrentValues(imageView) } else { revertSelected() } selectedSlider = nil } func view(for peekPanViewController: PeekPanViewController, atPercentage percentage: CGFloat) -> UIView? { let imageView = UIImageView() let valueLabel = UILabel() valueLabel.textColor = .white valueLabel.frame.origin = CGPoint(x: 20, y: 20) valueLabel.font = UIFont.systemFont(ofSize: 38) valueLabel.backgroundColor = UIColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 0.3) imageView.addSubview(valueLabel) if selectedSlider == brightnessSlider { brightnessValue = CGFloat(brightnessSlider.maximumValue - brightnessSlider.minimumValue) * percentage + CGFloat(brightnessSlider.minimumValue) valueLabel.text = NSString(format: "%.2f", brightnessValue) as String } else if selectedSlider == contrastSlider { let range = CGFloat(contrastSlider.maximumValue - contrastSlider.minimumValue) * 0.3 let startingValue = (CGFloat(peekPanCoordinator.startingPoint.x) - selectedSlider!.frame.minX) / selectedSlider!.bounds.width * CGFloat(contrastSlider.maximumValue - contrastSlider.minimumValue) contrastValue = min(max(range * percentage + (startingValue - range/2), CGFloat(contrastSlider.minimumValue)), CGFloat(contrastSlider.maximumValue)) valueLabel.text = NSString(format: "%.2f", contrastValue) as String } else if selectedSlider == sharpnessSlider { sharpnessValue = CGFloat(sharpnessSlider.maximumValue - sharpnessSlider.minimumValue) * percentage + CGFloat(sharpnessSlider.minimumValue) valueLabel.text = NSString(format: "%.2f", sharpnessValue) as String let zoomRatio: CGFloat = 0.3 imageView.layer.contentsRect = CGRect( x: 0.5 - (self.imageView.bounds.width*zoomRatio/2)/self.imageView.bounds.width, y: 0.5 - (self.imageView.bounds.height*zoomRatio)/self.imageView.bounds.height, width: zoomRatio, height: zoomRatio) } valueLabel.sizeToFit() updateImageWithCurrentValues(imageView) return imageView } // MARK: UIViewControllerPreviewingDelegate @available (iOS 9.0, *) func previewingContext(_ previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? { if brightnessSlider.frame.contains(location) { selectedSlider = brightnessSlider } else if contrastSlider.frame.contains(location) { selectedSlider = contrastSlider } else if sharpnessSlider.frame.contains(location) { selectedSlider = sharpnessSlider } else { selectedSlider = nil return nil } peekPanCoordinator.setup() previewingContext.sourceRect = selectedSlider!.frame return peekPanVC } @available (iOS 9.0, *) func previewingContext(_ previewingContext: UIViewControllerPreviewing, commit viewControllerToCommit: UIViewController) { peekPanCoordinator.end(true) } }
c1a9841391f6fa9d9aa83f7a5237a41d
40.708155
206
0.657543
false
false
false
false
wireapp/wire-ios
refs/heads/develop
Wire Notification Service Extension/Simple/Job.swift
gpl-3.0
1
// // Wire // Copyright (C) 2022 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 UserNotifications import WireTransport import WireSyncEngine import WireCommonComponents @available(iOS 15, *) final class Job: NSObject, Loggable { // MARK: - Types enum InitializationError: Error { case invalidEnvironment } typealias PushPayload = (userID: UUID, eventID: UUID) // MARK: - Properties private let request: UNNotificationRequest private let userID: UUID private let eventID: UUID private let environment: BackendEnvironmentProvider = BackendEnvironment.shared private let networkSession: NetworkSessionProtocol private let accessAPIClient: AccessAPIClientProtocol private let notificationsAPIClient: NotificationsAPIClientProtocol // MARK: - Life cycle init( request: UNNotificationRequest, networkSession: NetworkSessionProtocol? = nil, accessAPIClient: AccessAPIClientProtocol? = nil, notificationsAPIClient: NotificationsAPIClientProtocol? = nil ) throws { self.request = request let (userID, eventID) = try Self.pushPayload(from: request) self.userID = userID self.eventID = eventID let session = try networkSession ?? NetworkSession(userID: userID) self.networkSession = session self.accessAPIClient = accessAPIClient ?? AccessAPIClient(networkSession: session) self.notificationsAPIClient = notificationsAPIClient ?? NotificationsAPIClient(networkSession: session) super.init() } // MARK: - Methods func execute() async throws -> UNNotificationContent { logger.trace("\(self.request.identifier, privacy: .public): executing job...") logger.info("\(self.request.identifier, privacy: .public): request is for user (\(self.userID, privacy: .public)) and event (\(self.eventID, privacy: .public)") guard isUserAuthenticated else { throw NotificationServiceError.userNotAuthenticated } networkSession.accessToken = try await fetchAccessToken() let event = try await fetchEvent(eventID: eventID) switch event.type { case .conversationOtrMessageAdd: logger.trace("\(self.request.identifier, privacy: .public): returning notification for new message") let content = UNMutableNotificationContent() content.body = "You received a new message" return content default: logger.trace("\(self.request.identifier, privacy: .public): ignoring event of type: \(String(describing: event.type), privacy: .public)") return .empty } } private class func pushPayload(from request: UNNotificationRequest) throws -> PushPayload { guard let notificationData = request.content.userInfo["data"] as? [String: Any], let userIDString = notificationData["user"] as? String, let userID = UUID(uuidString: userIDString), let data = notificationData["data"] as? [String: Any], let eventIDString = data["id"] as? String, let eventID = UUID(uuidString: eventIDString) else { throw NotificationServiceError.malformedPushPayload } return (userID, eventID) } private var isUserAuthenticated: Bool { return networkSession.isAuthenticated } private func fetchAccessToken() async throws -> AccessToken { logger.trace("\(self.request.identifier, privacy: .public): fetching access token") return try await accessAPIClient.fetchAccessToken() } private func fetchEvent(eventID: UUID) async throws -> ZMUpdateEvent { logger.trace("\(self.request.identifier, privacy: .public): fetching event (\(eventID, privacy: .public))") return try await notificationsAPIClient.fetchEvent(eventID: eventID) } }
487cbf0b01406900df9523c0fc6da35e
35.504
168
0.689459
false
false
false
false
uberbruns/CasingTools
refs/heads/master
Tests/CasingToolsTests/CasingToolsTests.swift
mit
1
// // CasingToolsTests.swift // CasingTools // // Created by Karsten Bruns on 2017-04-29. // Copyright © 2017 CasingTools. All rights reserved. // import Foundation import XCTest class CasingToolsTests: XCTestCase { static let allTests = [ ("testLowerCamelCase", testLowerCamelCase), ("testLowercaseSnailCase", testLowercaseSnailCase), ("testLowercaseTrainCase", testLowercaseTrainCase), ("testUpperCamelCase", testUpperCamelCase), ("testUppercaseSnailCase", testUppercaseSnailCase), ("testUppercaseTrainCase", testUppercaseTrainCase), ("testComponentPerformance", testComponentPerformance), ("testUsagePerformance", testUsagePerformance), ("testEmpty", testEmpty), ] let testStringA = "Some people tell Me that I need HELP!" let testStringB = "SomePeopleTellMeThatINeedHELP" let testStringC = "Some-Pêöple\nTellMe??ThatINeedHELP " func testLowerCamelCase() { XCTAssertEqual(Casing.lowerCamelCase(testStringA), "somePeopleTellMeThatINeedHELP") XCTAssertEqual(Casing.lowerCamelCase(testStringB), "somePeopleTellMeThatINeedHELP") XCTAssertEqual(Casing.lowerCamelCase(testStringC), "somePeopleTellMeThatINeedHELP") } func testLowercaseSnailCase() { XCTAssertEqual(Casing.lowercaseSnailCase(testStringA), "some_people_tell_me_that_i_need_help") XCTAssertEqual(Casing.lowercaseSnailCase(testStringB), "some_people_tell_me_that_i_need_help") XCTAssertEqual(Casing.lowercaseSnailCase(testStringC), "some_people_tell_me_that_i_need_help") } func testLowercaseTrainCase() { XCTAssertEqual(Casing.lowercaseTrainCase(testStringA), "some-people-tell-me-that-i-need-help") XCTAssertEqual(Casing.lowercaseTrainCase(testStringB), "some-people-tell-me-that-i-need-help") XCTAssertEqual(Casing.lowercaseTrainCase(testStringC), "some-people-tell-me-that-i-need-help") } func testUpperCamelCase() { XCTAssertEqual(Casing.upperCamelCase(testStringA), "SomePeopleTellMeThatINeedHELP") XCTAssertEqual(Casing.upperCamelCase(testStringB), "SomePeopleTellMeThatINeedHELP") XCTAssertEqual(Casing.upperCamelCase(testStringC), "SomePeopleTellMeThatINeedHELP") } func testUppercaseSnailCase() { XCTAssertEqual(Casing.uppercaseSnailCase(testStringA), "SOME_PEOPLE_TELL_ME_THAT_I_NEED_HELP") XCTAssertEqual(Casing.uppercaseSnailCase(testStringB), "SOME_PEOPLE_TELL_ME_THAT_I_NEED_HELP") XCTAssertEqual(Casing.uppercaseSnailCase(testStringC), "SOME_PEOPLE_TELL_ME_THAT_I_NEED_HELP") } func testUppercaseTrainCase() { XCTAssertEqual(Casing.uppercaseTrainCase(testStringA), "SOME-PEOPLE-TELL-ME-THAT-I-NEED-HELP") XCTAssertEqual(Casing.uppercaseTrainCase(testStringB), "SOME-PEOPLE-TELL-ME-THAT-I-NEED-HELP") XCTAssertEqual(Casing.uppercaseTrainCase(testStringC), "SOME-PEOPLE-TELL-ME-THAT-I-NEED-HELP") print(Casing.splitIntoWords(testStringA)) print(Casing.splitIntoWords(testStringC)) } func testComponentPerformance() { let test = testStringA self.measure { for _ in 0..<10000 { _ = Casing.splitIntoWords(test) } } } func testUsagePerformance() { let test = testStringA self.measure { for _ in 0..<1000 { _ = Casing.lowerCamelCase(test) _ = Casing.lowercaseSnailCase(test) _ = Casing.lowercaseTrainCase(test) _ = Casing.upperCamelCase(test) _ = Casing.uppercaseSnailCase(test) _ = Casing.uppercaseTrainCase(test) } } } func testEmpty() { var test = "" XCTAssertTrue(Casing.lowercaseSnailCase(test) == "") test = " " XCTAssertTrue(Casing.lowercaseSnailCase(test) == "") test = "\n" XCTAssertTrue(Casing.lowercaseSnailCase(test) == "") test = " \n " XCTAssertTrue(Casing.lowercaseSnailCase(test) == "") test = "a" XCTAssertTrue(Casing.lowercaseSnailCase(test) == "a") test = "A" XCTAssertTrue(Casing.lowercaseSnailCase(test) == "a") test = "aa" XCTAssertTrue(Casing.lowercaseSnailCase(test) == "aa") test = "aA" XCTAssertTrue(Casing.lowercaseSnailCase(test) == "a_a") test = "Aa" XCTAssertTrue(Casing.lowercaseSnailCase(test) == "aa") test = "AA" XCTAssertTrue(Casing.lowercaseSnailCase(test) == "aa") } }
3d2e64b0d008662e96d7bb3685765e2a
32.751825
102
0.663279
false
true
false
false
eladb/nodeswift
refs/heads/master
nodeswift-sample/socket.swift
apache-2.0
1
// // stream.swift // nodeswift-sample // // Created by Elad Ben-Israel on 7/31/15. // Copyright © 2015 Citylifeapps Inc. All rights reserved. // import Foundation class Socket: Hashable, Equatable { let tcp: Handle<uv_tcp_t> var stream: UnsafeMutablePointer<uv_stream_t> { return UnsafeMutablePointer<uv_stream_t>(self.tcp.handle) } var hashValue: Int { return self.tcp.hashValue } // Events var data = EventEmitter1<Buffer>() var end = EventEmitter0() var closed = EventEmitter0() var error = ErrorEventEmitter() var connected = EventEmitter0() init() { self.tcp = Handle(closable: true) self.tcp.callback = self.ondata uv_tcp_init(uv_default_loop(), self.tcp.handle) } deinit { print("Socket deinit") } func connect(port: UInt16, host: String = "localhost", connectionListener: (() -> ())? = nil) { if let listener = connectionListener { self.connected.once(listener) } let connect = Handle<uv_connect_t>(closable: false) connect.callback = self.onconnect let addr = UnsafeMutablePointer<sockaddr_in>.alloc(1); uv_ip4_addr(host.cStringUsingEncoding(NSUTF8StringEncoding)!, Int32(port), addr) let result = uv_tcp_connect(connect.handle, self.tcp.handle, UnsafeMutablePointer<sockaddr>(addr), connect_cb) addr.dealloc(1) if let err = Error(result: result) { nextTick { self.error.emit(err) } return } } func write(string: String, callback: ((Error?) -> ())? = nil) { let req = Handle<uv_write_t>(closable: false) req.callback = { args in callback?(args[0] as? Error) } if let cString = string.cStringUsingEncoding(NSUTF8StringEncoding) { let buf = UnsafeMutablePointer<uv_buf_t>.alloc(1) buf.memory = uv_buf_init(UnsafeMutablePointer<Int8>(cString), UInt32(cString.count)) uv_write(req.handle, self.stream, UnsafePointer<uv_buf_t>(buf), 1, write_cb) } } func resume() { uv_read_start(self.stream, alloc_cb, read_cb) } func pause() { uv_read_stop(self.stream) } func close() { self.tcp.close { self.closed.emit() } } private func ondata(args: [AnyObject?]) { let event = args[0] as! String if event == "data" { self.data.emit(args[1] as! Buffer) } else if event == "end" { self.end.emit() self.close() } } private func onconnect(args: [AnyObject?]) { if let err = args[0] as! Error? { self.error.emit(err) } else { self.connected.emit() // start emitting data events self.resume() } } } private func connect_cb(handle: UnsafeMutablePointer<uv_connect_t>, result: Int32) { let err = Error(result: result) RawHandle.callback(handle, args: [ err ], autoclose: true) } private func alloc_cb(handle: UnsafeMutablePointer<uv_handle_t>, suggested_size: Int, buf: UnsafeMutablePointer<uv_buf_t>) { buf.memory = uv_buf_init(UnsafeMutablePointer<Int8>.alloc(suggested_size), UInt32(suggested_size)) } private func read_cb(handle: UnsafeMutablePointer<uv_stream_t>, nread: Int, buf: UnsafePointer<uv_buf_t>) { if Int32(nread) == UV_EOF.rawValue { // release the buffer and emit "end" print("Deallocate buf") buf.memory.base.dealloc(buf.memory.len) RawHandle.callback(handle, args: [ "end" ], autoclose: false) return } // buf will be deallocated on Buffer deinit let buffer = Buffer(autoDealloc: buf, nlen: nread) RawHandle.callback(handle, args: [ "data", buffer ], autoclose: false) } private func write_cb(handle: UnsafeMutablePointer<uv_write_t>, status: Int32) { RawHandle.callback(handle, args: [ Error(result: status) ], autoclose: true) } func ==(lhs: Socket, rhs: Socket) -> Bool { return lhs.tcp == rhs.tcp }
6996a29b17c12377f0041406b8bb93d2
28.820144
124
0.597346
false
false
false
false
LeonClover/DouYu
refs/heads/master
DouYuZB/DouYuZB/Classes/Main/View/PageContentView.swift
mit
1
// // PageContentView.swift // DouYuZB // // Created by Leon on 2017/6/7. // Copyright © 2017年 pingan. All rights reserved. // import UIKit protocol PageContentViewDelegate: class { func pageContentView(contentView: PageContentView, progress: CGFloat, sourceIndex: Int, targetIndex: Int) } private let contentCellID = "contentCellID" class PageContentView: UIView { //定义属性 fileprivate var childVcs: [UIViewController] fileprivate weak var parentVC: UIViewController? fileprivate var startOffsetX: CGFloat = 0.0 fileprivate var isForbidScrollDelegate: Bool = false weak var delegate: PageContentViewDelegate? //懒加载属性 fileprivate lazy var collectionView: UICollectionView = {[weak self] in let layout = UICollectionViewFlowLayout() layout.itemSize = (self?.bounds.size)! layout.minimumLineSpacing = 0 layout.minimumInteritemSpacing = 0 layout.scrollDirection = .horizontal let collectionView = UICollectionView(frame: CGRect(), collectionViewLayout: layout) collectionView.showsHorizontalScrollIndicator = false collectionView.isPagingEnabled = true collectionView.bounces = false collectionView.dataSource = self collectionView.delegate = self collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: contentCellID) return collectionView }() init(frame: CGRect, childVcs: [UIViewController], parentVC: UIViewController?) { self.childVcs = childVcs self.parentVC = parentVC super.init(frame: frame) setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } //设置UI界面 extension PageContentView { fileprivate func setupUI() { for childVC in childVcs { parentVC?.addChildViewController(childVC) } collectionView.frame = bounds addSubview(collectionView) } } //实现协议 extension PageContentView: UICollectionViewDataSource{ func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return childVcs.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: contentCellID, for: indexPath) for view in cell.contentView.subviews { view.removeFromSuperview() } let childVC = childVcs[indexPath.item] childVC.view.frame = cell.contentView.bounds cell.contentView.addSubview(childVC.view) return cell } } // extension PageContentView: UICollectionViewDelegate{ func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { isForbidScrollDelegate = false; startOffsetX = scrollView.contentOffset.x } func scrollViewDidScroll(_ scrollView: UIScrollView) { if isForbidScrollDelegate { return } //1.定义获取需要的数据 var progress: CGFloat = 0.0 var sourceIndex = 0 var targetIndex = 0 //2.判断左滑还是右滑 let currentOffsetX = scrollView.contentOffset.x let scrollViewW = scrollView.bounds.width if currentOffsetX > startOffsetX { //左滑 //1.计算progress progress = currentOffsetX / scrollViewW - floor(currentOffsetX / scrollViewW) //2.计算sourceIndex sourceIndex = Int(currentOffsetX / scrollViewW) //3.计算targetIndex targetIndex = sourceIndex + 1 if targetIndex >= childVcs.count { targetIndex = childVcs.count - 1 } }else{ //1.计算progress progress = 1 - (currentOffsetX / scrollViewW - floor(currentOffsetX / scrollViewW)) //2.计算targetIndex targetIndex = Int(currentOffsetX / scrollViewW) //3.计算sourceIndex sourceIndex = targetIndex + 1 if sourceIndex >= childVcs.count { sourceIndex = childVcs.count - 1 } } //3.将progress,sourceIndex,targetIndex,传给titleView delegate?.pageContentView(contentView: self, progress: progress, sourceIndex: sourceIndex, targetIndex: targetIndex) } } //对外暴露的方法 extension PageContentView{ func setCurrentIndex(currentIndex: Int) { isForbidScrollDelegate = true; let offsetX = CGFloat(currentIndex) * collectionView.frame.width collectionView.setContentOffset(CGPoint(x: offsetX, y: 0.0), animated: false) } }
c18720ff056fb10ebaa668249094bbb6
32.439716
124
0.656416
false
false
false
false
Raureif/WikipediaKit
refs/heads/main
Sources/Wikipedia+Languages.swift
mit
1
// // Wikipedia+Languages.swift // WikipediaKit // // Created by Frank Rausch on 2017-03-21. // Copyright © 2017 Raureif GmbH / Frank Rausch // // MIT License // // 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 #if canImport(FoundationNetworking) import FoundationNetworking #endif extension Wikipedia { public func requestAvailableLanguages(for article: WikipediaArticle, completion: @escaping (WikipediaArticle, WikipediaError?)->()) -> URLSessionDataTask? { guard article.languageLinks == nil, // has not been populated previously article.areOtherLanguagesAvailable // other languages are available else { DispatchQueue.main.async { completion(article, nil) } return nil } let parameters: [String:String] = [ "action": "parse", "format": "json", "formatversion": "2", "page" : article.title, "prop": "langlinks", "maxage": "\(self.maxAgeInSeconds)", "smaxage": "\(self.maxAgeInSeconds)", "uselang": WikipediaLanguage.systemLanguage.variant ?? WikipediaLanguage.systemLanguage.code, ] guard let request = Wikipedia.buildURLRequest(language: article.language, parameters: parameters) else { DispatchQueue.main.async { completion(article, .other(nil)) } return nil } return WikipediaNetworking.shared.loadJSON(urlRequest: request) { jsonDictionary, error in guard error == nil else { // (also occurs when the request was cancelled programmatically) DispatchQueue.main.async { completion (article, error) } return } guard let jsonDictionary = jsonDictionary else { DispatchQueue.main.async { completion (article, .decodingError) } return } guard let parse = jsonDictionary["parse"] as? JSONDictionary, let langlinks = parse["langlinks"] as? [JSONDictionary] else { DispatchQueue.main.async { completion (article, .decodingError) } return } let languages = langlinks.compactMap(WikipediaArticleLanguageLink.init) article.languageLinks = languages DispatchQueue.main.async { completion(article, error) } } } }
6bfd62d787e1a8a9c620cd01582541b3
37.336634
105
0.587293
false
false
false
false
brandenr/ExSwift
refs/heads/master
ExSwift/NSDate.swift
apache-2.0
5
// // File.swift // ExSwift // // Created by Piergiuseppe Longo on 23/11/14. // Copyright (c) 2014 pNre. All rights reserved. // import Foundation public extension NSDate { // MARK: NSDate Manipulation /** Returns a new NSDate object representing the date calculated by adding the amount specified to self date :param: seconds number of seconds to add :param: minutes number of minutes to add :param: hours number of hours to add :param: days number of days to add :param: weeks number of weeks to add :param: months number of months to add :param: years number of years to add :returns: the NSDate computed */ public func add(seconds: Int = 0, minutes: Int = 0, hours: Int = 0, days: Int = 0, weeks: Int = 0, months: Int = 0, years: Int = 0) -> NSDate { var calendar = NSCalendar.currentCalendar() var date = calendar.dateByAddingUnit(.CalendarUnitSecond, value: seconds, toDate: self, options: nil) as NSDate! date = calendar.dateByAddingUnit(.CalendarUnitMinute, value: minutes, toDate: date, options: nil) date = calendar.dateByAddingUnit(.CalendarUnitDay, value: days, toDate: date, options: nil) date = calendar.dateByAddingUnit(.CalendarUnitHour, value: hours, toDate: date, options: nil) date = calendar.dateByAddingUnit(.CalendarUnitWeekOfMonth, value: weeks, toDate: date, options: nil) date = calendar.dateByAddingUnit(.CalendarUnitMonth, value: months, toDate: date, options: nil) date = calendar.dateByAddingUnit(.CalendarUnitYear, value: years, toDate: date, options: nil) return date } /** Returns a new NSDate object representing the date calculated by adding an amount of seconds to self date :param: seconds number of seconds to add :returns: the NSDate computed */ public func addSeconds (seconds: Int) -> NSDate { return add(seconds: seconds) } /** Returns a new NSDate object representing the date calculated by adding an amount of minutes to self date :param: minutes number of minutes to add :returns: the NSDate computed */ public func addMinutes (minute: Int) -> NSDate { return add(minutes: minute) } /** Returns a new NSDate object representing the date calculated by adding an amount of hours to self date :param: hours number of hours to add :returns: the NSDate computed */ public func addHours(hours: Int) -> NSDate { return add(hours: hours) } /** Returns a new NSDate object representing the date calculated by adding an amount of days to self date :param: days number of days to add :returns: the NSDate computed */ public func addDays(days: Int) -> NSDate { return add(days: days) } /** Returns a new NSDate object representing the date calculated by adding an amount of weeks to self date :param: weeks number of weeks to add :returns: the NSDate computed */ public func addWeeks(weeks: Int) -> NSDate { return add(weeks: weeks) } /** Returns a new NSDate object representing the date calculated by adding an amount of months to self date :param: months number of months to add :returns: the NSDate computed */ public func addMonths(months: Int) -> NSDate { return add(months: months) } /** Returns a new NSDate object representing the date calculated by adding an amount of years to self date :param: years number of year to add :returns: the NSDate computed */ public func addYears(years: Int) -> NSDate { return add(years: years) } // MARK: Date comparison /** Checks if self is after input NSDate :param: date NSDate to compare :returns: True if self is after the input NSDate, false otherwise */ public func isAfter(date: NSDate) -> Bool{ return (self.compare(date) == NSComparisonResult.OrderedDescending) } /** Checks if self is before input NSDate :param: date NSDate to compare :returns: True if self is before the input NSDate, false otherwise */ public func isBefore(date: NSDate) -> Bool{ return (self.compare(date) == NSComparisonResult.OrderedAscending) } // MARK: Getter /** Date year */ public var year : Int { get { return getComponent(.CalendarUnitYear) } } /** Date month */ public var month : Int { get { return getComponent(.CalendarUnitMonth) } } /** Date weekday */ public var weekday : Int { get { return getComponent(.CalendarUnitWeekday) } } /** Date weekMonth */ public var weekMonth : Int { get { return getComponent(.CalendarUnitWeekOfMonth) } } /** Date days */ public var days : Int { get { return getComponent(.CalendarUnitDay) } } /** Date hours */ public var hours : Int { get { return getComponent(.CalendarUnitHour) } } /** Date minuts */ public var minutes : Int { get { return getComponent(.CalendarUnitMinute) } } /** Date seconds */ public var seconds : Int { get { return getComponent(.CalendarUnitSecond) } } /** Returns the value of the NSDate component :param: component NSCalendarUnit :returns: the value of the component */ public func getComponent (component : NSCalendarUnit) -> Int { let calendar = NSCalendar.currentCalendar() let components = calendar.components(component, fromDate: self) return components.valueForComponent(component) } } extension NSDate: Strideable { public func distanceTo(other: NSDate) -> NSTimeInterval { return other - self } public func advancedBy(n: NSTimeInterval) -> Self { return self.dynamicType(timeIntervalSinceReferenceDate: self.timeIntervalSinceReferenceDate + n) } } // MARK: Arithmetic func +(date: NSDate, timeInterval: Int) -> NSDate { return date + NSTimeInterval(timeInterval) } func -(date: NSDate, timeInterval: Int) -> NSDate { return date - NSTimeInterval(timeInterval) } func +=(inout date: NSDate, timeInterval: Int) { date = date + timeInterval } func -=(inout date: NSDate, timeInterval: Int) { date = date - timeInterval } func +(date: NSDate, timeInterval: Double) -> NSDate { return date.dateByAddingTimeInterval(NSTimeInterval(timeInterval)) } func -(date: NSDate, timeInterval: Double) -> NSDate { return date.dateByAddingTimeInterval(NSTimeInterval(-timeInterval)) } func +=(inout date: NSDate, timeInterval: Double) { date = date + timeInterval } func -=(inout date: NSDate, timeInterval: Double) { date = date - timeInterval } func -(date: NSDate, otherDate: NSDate) -> NSTimeInterval { return date.timeIntervalSinceDate(otherDate) } extension NSDate: Equatable { } public func ==(lhs: NSDate, rhs: NSDate) -> Bool { return lhs.compare(rhs) == NSComparisonResult.OrderedSame } extension NSDate: Comparable { } public func <(lhs: NSDate, rhs: NSDate) -> Bool { return lhs.compare(rhs) == NSComparisonResult.OrderedAscending }
734871b222dfbc34a0ddbd41a3319e7b
26.260563
147
0.617024
false
false
false
false
LoopKit/LoopKit
refs/heads/dev
LoopKitUI/CarbKit/FoodEmojiDataSource.swift
mit
1
// // FoodEmojiDataSource.swift // LoopKit // // Copyright © 2017 LoopKit Authors. All rights reserved. // public func CarbAbsorptionInputController() -> EmojiInputController { return EmojiInputController.instance(withEmojis: FoodEmojiDataSource()) } private class FoodEmojiDataSource: EmojiDataSource { private static let fast: [String] = { var fast = [ "🍭", "🍬", "🍯", "🍇", "🍈", "🍉", "🍊", "🍋", "🍌", "🍍", "🍎", "🍏", "🍐", "🍑", "🍒", "🍓", "🥝", "🌽", "🍿", "🍘", "🍡", "🍦", "🍧", "🎂", "🥠", "☕️", ] return fast }() private static let medium: [String] = { var medium = [ "🌮", "🍟", "🍳", "🍲", "🍱", "🍛", "🍜", "🍠", "🍤", "🍥", "🥪", "🥫", "🥟", "🥡", "🍢", "🍣", "🍅", "🥔", "🥕", "🌶", "🥒", "🥗", "🍄", "🥦", "🍆", "🥥", "🍞", "🥐", "🥖", "🥨", "🥞", "🍙", "🍚", "🍼", "🥛", "🍮", "🥧", "🍨", "🍩", "🍪", "🍰", "🍫", ] return medium }() private static let slow: [String] = { var slow = [ "🍕", "🥑", "🥜", "🌰", "🧀", "🍖", "🍗", "🥓", "🍔", "🌭", "🌯", "🍝", "🥩" ] return slow }() private static let other: [String] = { var other = [ "🍶", "🍾", "🍷", "🍸", "🍺", "🍻", "🥂", "🥃", "🍹", "🥣", "🥤", "🥢", "🍵", "1️⃣", "2️⃣", "3️⃣", "4️⃣", "5️⃣", "6️⃣", "7️⃣", "8️⃣", "9️⃣", "🔟" ] return other }() let sections: [EmojiSection] init() { sections = [ EmojiSection( title: LocalizedString("Fast", comment: "Section title for fast absorbing food"), items: type(of: self).fast, indexSymbol: " 🍭 " ), EmojiSection( title: LocalizedString("Medium", comment: "Section title for medium absorbing food"), items: type(of: self).medium, indexSymbol: "🌮" ), EmojiSection( title: LocalizedString("Slow", comment: "Section title for slow absorbing food"), items: type(of: self).slow, indexSymbol: "🍕" ), EmojiSection( title: LocalizedString("Other", comment: "Section title for no-carb food"), items: type(of: self).other, indexSymbol: "⋯ " ) ] } }
8afffedcb46fa17d79b3a963feaf3fa2
27.372093
101
0.364344
false
false
false
false
DragonCherry/AssetsPickerViewController
refs/heads/master
AssetsPickerViewController/Classes/Picker/Controller/AssetsPickerViewController.swift
mit
1
// // AssetsPickerViewController.swift // Pods // // Created by DragonCherry on 5/17/17. // // import UIKit import Photos // MARK: - AssetsPickerViewControllerDelegate @objc public protocol AssetsPickerViewControllerDelegate: class { @objc optional func assetsPickerDidCancel(controller: AssetsPickerViewController) @objc optional func assetsPickerCannotAccessPhotoLibrary(controller: AssetsPickerViewController) func assetsPicker(controller: AssetsPickerViewController, selected assets: [PHAsset]) @objc optional func assetsPicker(controller: AssetsPickerViewController, shouldSelect asset: PHAsset, at indexPath: IndexPath) -> Bool @objc optional func assetsPicker(controller: AssetsPickerViewController, didSelect asset: PHAsset, at indexPath: IndexPath) @objc optional func assetsPicker(controller: AssetsPickerViewController, shouldDeselect asset: PHAsset, at indexPath: IndexPath) -> Bool @objc optional func assetsPicker(controller: AssetsPickerViewController, didDeselect asset: PHAsset, at indexPath: IndexPath) @objc optional func assetsPicker(controller: AssetsPickerViewController, didDismissByCancelling byCancel: Bool) } // MARK: - AssetsPickerViewController @objcMembers open class AssetsPickerViewController: UINavigationController { @objc open weak var pickerDelegate: AssetsPickerViewControllerDelegate? open var selectedAssets: [PHAsset] { return photoViewController.selectedArray } open var isShowLog: Bool = false { didSet { TinyLog.isShowInfoLog = isShowLog TinyLog.isShowErrorLog = isShowLog } } public var pickerConfig: AssetsPickerConfig! { didSet { if let config = self.pickerConfig?.prepare() { AssetsManager.shared.pickerConfig = config photoViewController?.pickerConfig = config } } } public private(set) var photoViewController: AssetsPhotoViewController! required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } override public init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) commonInit() } public convenience init() { self.init(nibName: nil, bundle: nil) } func commonInit() { let config = AssetsPickerConfig().prepare() self.pickerConfig = config AssetsManager.shared.pickerConfig = config let controller = AssetsPhotoViewController() controller.pickerConfig = config self.photoViewController = controller viewControllers = [photoViewController] } deinit { AssetsManager.shared.clear() logd("Released \(type(of: self))") } }
e051d5bf1a2e5d1fc45ac432a878f0ca
35.253165
140
0.705656
false
true
false
false
time-fighters/patachu
refs/heads/master
Time Fighter/Shooting.swift
mit
1
// // Bullet.swift // Time Fighter // // Created by Wilson Martins on 29/06/17. // Copyright © 2017 Fera. All rights reserved. // import Foundation import SpriteKit import UIKit import SpriteKit protocol Shoot { func shoot() } class Shooting: SKNode, JoystickController, Update, NodeInformation { var node: SKNode var bullet: SKNode var isShooting: Bool = false var direction: CGVector var angle: Double let parentRelativePosition: CGPoint let rateOfFire: Double = 0.3 var lastShot: TimeInterval var parentScene: SKScene var bullets: Double = 6 { didSet { let bulletCounter:SKLabelNode = (self.parentScene.camera!.childNode(withName: "bulletsCounter") as? SKLabelNode)! bulletCounter.text = String(Int(bullets)) } } var isReloading: Bool = false var directionNode: NodeInformation let TIME_INTERVAL:Double = 1 let BULLET_VELOCITY: Double = 600 init(_ node: SKNode, _ bullet: SKNode, _ parentRelativePosition: CGPoint, _ directionNode: NodeInformation, _ scene: SKScene) { self.node = node self.parentRelativePosition = parentRelativePosition self.directionNode = directionNode self.bullet = bullet self.direction = CGVector() self.lastShot = TimeInterval() self.angle = 0 self.parentScene = scene super.init() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func joystickInteraction(velocity: CGVector, angularVelocity: CGFloat) { self.direction = velocity self.angle = Double(angularVelocity) } func update(_ currentTime: TimeInterval) { // self.isShooting(isShooting) let vx: Double = self.BULLET_VELOCITY * cos(self.angle) let vy: Double = self.BULLET_VELOCITY * sin(self.angle) if (self.isShooting && vx < 0) { self.setDirection(.left) self.node.zRotation = .pi - CGFloat(self.angle) } else if (self.isShooting && vx >= 0) { self.setDirection(.right) self.node.zRotation = CGFloat(self.angle) } else if (!self.isShooting) { self.node.zRotation = 0 } guard self.isShooting else { return } guard self.bullets > 0 else { if (!isReloading) { self.isShooting = false self.reload() } return } guard currentTime - self.lastShot > self.rateOfFire else { return } self.lastShot = currentTime let bullet = self.makeBullet() bullet.physicsBody?.velocity = CGVector(dx: vx, dy: vy) bullet.physicsBody?.linearDamping = 0 bullet.physicsBody?.affectedByGravity = false bullet.zRotation = CGFloat(self.angle) self.bullets -= 1 } func configureStateMachine(forStatus status: JoystickStatusEnum) { if (status == .started) { self.isShooting(true, status: status) } else if (status == .running) { self.isShooting(true, status: status) }else if (status == .finished) { self.isShooting(false, status: status) } } func makeBullet() -> SKNode { let bullet = self.bullet.copy() as! SKSpriteNode bullet.zPosition = 0 bullet.removeAllChildren() bullet.position = self.node.convert(CGPoint(x: self.node.position.x + 100, y: self.node.position.y - 10), to: self.bullet) bullet.zPosition = 0 self.bullet.addChild(bullet) return bullet } func setDirection(_ direction: DirectionEnum) { self.directionNode.setDirection(direction) } func isShooting(_ isShooting: Bool, status: JoystickStatusEnum) { self.isShooting = isShooting self.directionNode.isShooting(isShooting, status: status) } func reload() { self.isReloading = true DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) { self.bullets = 6 self.isReloading = false } } }
05f8241beacbd044a01d061b2d5e7e3d
27.568493
131
0.609686
false
false
false
false
Dreezydraig/actor-platform
refs/heads/master
actor-apps/app-ios/ActorApp/Controllers/Conversation/Cells/AABubbleBaseFileCell.swift
mit
26
// // Copyright (c) 2014-2015 Actor LLC. <https://actor.im> // import Foundation class AABubbleBaseFileCell: AABubbleCell { var bindGeneration = 0; var bindedDownloadFile: jlong? = nil var bindedDownloadCallback: CocoaDownloadCallback? = nil var bindedUploadFile: jlong? = nil var bindedUploadCallback: CocoaUploadCallback? = nil func fileBind(message: ACMessage, autoDownload: Bool) { if let doc = message.content as? ACDocumentContent { // Next generation of binding bindGeneration++ // Saving generation to new binding var selfGeneration = bindGeneration; // Remove old bindings fileUnbind() if let source = doc.getSource() as? ACFileRemoteSource { var fileReference = source.getFileReference(); bindedDownloadFile = fileReference.getFileId() bindedDownloadCallback = CocoaDownloadCallback(notDownloaded: { () -> () in if (self.bindGeneration != selfGeneration) { return } self.fileDownloadPaused(selfGeneration) }, onDownloading: { (progress) -> () in if (self.bindGeneration != selfGeneration) { return } self.fileDownloading(progress, selfGeneration: selfGeneration) }, onDownloaded: { (reference) -> () in if (self.bindGeneration != selfGeneration) { return } self.fileReady(reference, selfGeneration: selfGeneration) }) Actor.bindRawFileWithReference(fileReference, autoStart: autoDownload, withCallback: bindedDownloadCallback) } else if let source = doc.getSource() as? ACFileLocalSource { var fileReference = source.getFileDescriptor(); bindedUploadFile = message.rid; bindedUploadCallback = CocoaUploadCallback(notUploaded: { () -> () in if (self.bindGeneration != selfGeneration) { return } self.fileUploadPaused(fileReference, selfGeneration: selfGeneration) }, onUploading: { (progress) -> () in if (self.bindGeneration != selfGeneration) { return } self.fileUploading(fileReference, progress: progress, selfGeneration: selfGeneration) }, onUploadedClosure: { () -> () in if (self.bindGeneration != selfGeneration) { return } self.fileReady(fileReference, selfGeneration: selfGeneration) }); Actor.bindRawUploadFileWithRid(message.rid, withCallback: bindedUploadCallback) } else { fatalError("Unsupported file source") } } else { fatalError("Unsupported message type") } } func fileUploadPaused(reference: String, selfGeneration: Int) { } func fileUploading(reference: String, progress: Double, selfGeneration: Int) { } func fileDownloadPaused(selfGeneration: Int) { } func fileDownloading(progress: Double, selfGeneration: Int) { } func fileReady(reference: String, selfGeneration: Int) { } func runOnUiThread(selfGeneration: Int, closure: ()->()){ if (selfGeneration != self.bindGeneration) { return } dispatchOnUi { if (selfGeneration != self.bindGeneration) { return } closure() } } func fileUnbind() { if (bindedDownloadFile != nil && bindedDownloadCallback != nil) { Actor.unbindRawFileWithFileId(bindedDownloadFile!, autoCancel: false, withCallback: bindedDownloadCallback) bindedDownloadFile = nil bindedDownloadCallback = nil } if (bindedUploadFile != nil && bindedUploadCallback != nil) { Actor.unbindRawUploadFileWithRid(bindedUploadFile!, withCallback: bindedUploadCallback) bindedUploadFile = nil bindedUploadCallback = nil } } }
874136c406f7ff1e1847f99be91d4c44
35.677419
124
0.541236
false
false
false
false
Minitour/AZDialogViewController
refs/heads/master
AZDialogViewControllerExample/AZDialogViewControllerExample/ViewController.swift
mit
1
// // ViewController.swift // AZDialogViewControllerExample // // Created by Antonio Zaitoun on 26/02/2017. // Copyright © 2017 Antonio Zaitoun. All rights reserved. // import UIKit class ViewController: UIViewController { let primaryColor = #colorLiteral(red: 0.6271930337, green: 0.3653797209, blue: 0.8019730449, alpha: 1) let primaryColorDark = #colorLiteral(red: 0.5373370051, green: 0.2116269171, blue: 0.7118118405, alpha: 1) 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. } @IBAction func click(_ sender: UIButton) { switch sender.tag{ case 0: ignDialog() //loadingIndicator() //imagePreviewDialog() //tableViewDialog() case 1: editUserDialog() case 2: reportUserDialog(controller: self) case 3: reportDialog() default: break } } func imagePreviewDialog(){ let dialog = AZDialogViewController(title: "Image",message: "Image Description") let container = dialog.container let imageView = UIImageView(image: #imageLiteral(resourceName: "image")) imageView.contentMode = .scaleAspectFit container.addSubview(imageView) imageView.translatesAutoresizingMaskIntoConstraints = false imageView.topAnchor.constraint(equalTo: container.topAnchor).isActive = true imageView.bottomAnchor.constraint(equalTo: container.bottomAnchor).isActive = true imageView.leftAnchor.constraint(equalTo: container.leftAnchor).isActive = true imageView.rightAnchor.constraint(equalTo: container.rightAnchor).isActive = true dialog.customViewSizeRatio = imageView.image!.size.height / imageView.image!.size.width dialog.addAction(AZDialogAction(title: "Done") { (dialog) -> (Void) in dialog.image = #imageLiteral(resourceName: "ign") }) dialog.show(in: self) } func loadingIndicator(){ let dialog = AZDialogViewController(title: "Loading...", message: "Logging you in, please wait") let container = dialog.container let indicator = UIActivityIndicatorView(style: .gray) dialog.container.addSubview(indicator) indicator.translatesAutoresizingMaskIntoConstraints = false indicator.centerXAnchor.constraint(equalTo: container.centerXAnchor).isActive = true indicator.centerYAnchor.constraint(equalTo: container.centerYAnchor).isActive = true indicator.startAnimating() dialog.buttonStyle = { (button,height,position) in button.setBackgroundImage(UIImage.imageWithColor(self.primaryColorDark), for: .highlighted) button.setTitleColor(UIColor.white, for: .highlighted) button.setTitleColor(self.primaryColor, for: .normal) button.layer.masksToBounds = true button.layer.borderColor = self.primaryColor.cgColor } //dialog.animationDuration = 5.0 dialog.customViewSizeRatio = 0.2 dialog.dismissDirection = .none dialog.allowDragGesture = false dialog.dismissWithOutsideTouch = true dialog.show(in: self) let when = DispatchTime.now() + 3 // change 2 to desired number of seconds DispatchQueue.main.asyncAfter(deadline: when) { dialog.message = "Preparing..." } DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 4) { dialog.message = "Syncing accounts..." } DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 5) { dialog.title = "Ready" dialog.message = "Let's get started" dialog.image = #imageLiteral(resourceName: "image") dialog.customViewSizeRatio = 0 dialog.addAction(AZDialogAction(title: "Go", handler: { (dialog) -> (Void) in dialog.cancelEnabled = !dialog.cancelEnabled })) dialog.dismissDirection = .bottom dialog.allowDragGesture = true } dialog.cancelButtonStyle = { (button,height) in button.tintColor = self.primaryColor button.setTitle("CANCEL", for: []) return false } } func ignDialog(){ let dialogController = AZDialogViewController(title: "IGN", message: "IGN is your destination for gaming, movies, comics and everything you're into. Find the latest reviews, news, videos, and more more.") dialogController.showSeparator = true dialogController.dismissDirection = .bottom dialogController.imageHandler = { (imageView) in imageView.image = UIImage(named: "ign") imageView.contentMode = .scaleAspectFill return true } dialogController.addAction(AZDialogAction(title: "Subscribe", handler: { (dialog) -> (Void) in //dialog.title = "title" //dialog.message = "new message" //dialog.image = dialog.image == nil ? #imageLiteral(resourceName: "ign") : nil //dialog.title = "" //dialog.message = "" //dialog.customViewSizeRatio = 0.2 })) //let container = dialogController.container //let button = UIButton(type: .system) //button.setTitle("MY BUTTON", for: []) //dialogController.container.addSubview(button) //button.translatesAutoresizingMaskIntoConstraints = false //button.centerXAnchor.constraint(equalTo: container.centerXAnchor).isActive = true //button.centerYAnchor.constraint(equalTo: container.centerYAnchor).isActive = true dialogController.buttonStyle = { (button,height,position) in button.setBackgroundImage(UIImage.imageWithColor(self.primaryColor) , for: .normal) button.setBackgroundImage(UIImage.imageWithColor(self.primaryColorDark), for: .highlighted) button.setTitleColor(UIColor.white, for: []) button.layer.masksToBounds = true button.layer.borderColor = self.primaryColor.cgColor button.tintColor = .white if position == 0 { let image = #imageLiteral(resourceName: "ic_bookmark").withRenderingMode(.alwaysTemplate) button.setImage(image, for: []) button.imageView?.contentMode = .scaleAspectFit } } dialogController.blurBackground = true dialogController.blurEffectStyle = .dark dialogController.rightToolStyle = { (button) in button.setImage(#imageLiteral(resourceName: "share"), for: []) button.tintColor = .lightGray return true } dialogController.rightToolAction = { (button) in print("Share function") } dialogController.dismissWithOutsideTouch = true dialogController.show(in: self) } func editUserDialog(){ let dialogController = AZDialogViewController(title: "Antonio Zaitoun", message: "minitour") dialogController.showSeparator = true dialogController.addAction(AZDialogAction(title: "Edit Name", handler: { (dialog) -> (Void) in //dialog.removeAction(at: 0) dialog.addAction(AZDialogAction(title: "action") { (dialog) -> (Void) in dialog.dismiss() }) dialog.contentOffset = self.view.frame.height / 2.0 - dialog.estimatedHeight / 2.0 - 16 })) dialogController.addAction(AZDialogAction(title: "Remove Friend", handler: { (dialog) -> (Void) in dialog.removeAction(at: 1) })) dialogController.addAction(AZDialogAction(title: "Block", handler: { (dialog) -> (Void) in //dialog.spacing = 20 dialog.removeAction(at: 2) dialog.contentOffset = self.view.frame.height / 2.0 - dialog.estimatedHeight / 2.0 - 16 })) dialogController.cancelButtonStyle = { (button,height) in button.tintColor = self.primaryColor button.setTitle("CANCEL", for: []) return true } dialogController.cancelEnabled = true dialogController.buttonStyle = { (button,height,position) in button.setBackgroundImage(UIImage.imageWithColor(self.primaryColorDark), for: .highlighted) button.setTitleColor(UIColor.white, for: .highlighted) button.setTitleColor(self.primaryColor, for: .normal) button.layer.masksToBounds = true button.layer.borderColor = self.primaryColor.cgColor } dialogController.dismissDirection = .bottom dialogController.dismissWithOutsideTouch = true dialogController.contentOffset = self.view.frame.height / 2.0 - dialogController.estimatedHeight / 2.0 - 16 dialogController.show(in: self) } func reportUserDialog(controller: UIViewController){ let dialogController = AZDialogViewController(title: "Minitour has been blocked.", message: "Let us know your reason for blocking them?", widthRatio: 0.8) dialogController.dismissDirection = .none dialogController.dismissWithOutsideTouch = false dialogController.addAction(AZDialogAction(title: "Annoying", handler: { (dialog) -> (Void) in dialog.dismiss() })) dialogController.addAction(AZDialogAction(title: "I don't know them", handler: { (dialog) -> (Void) in dialog.dismiss() })) dialogController.addAction(AZDialogAction(title: "Inappropriate Snaps", handler: { (dialog) -> (Void) in dialog.dismiss() })) dialogController.addAction(AZDialogAction(title: "Harassing me", handler: { (dialog) -> (Void) in dialog.dismiss() })) dialogController.addAction(AZDialogAction(title: "Other", handler: { (dialog) -> (Void) in dialog.removeSection(0) //dialog.dismiss() })) dialogController.buttonStyle = { (button,height,position) in button.setBackgroundImage(UIImage.imageWithColor(self.primaryColorDark), for: .highlighted) button.setTitleColor(UIColor.white, for: .highlighted) button.setTitleColor(self.primaryColor, for: .normal) button.layer.masksToBounds = true button.layer.borderColor = self.primaryColor.cgColor } let imageView = UIImageView(image: #imageLiteral(resourceName: "image")) imageView.contentMode = .scaleAspectFill imageView.heightAnchor.constraint(equalToConstant: 100.0).isActive = true dialogController.show(in: controller) { $0.section(view: imageView) imageView.superview?.superview?.layer.masksToBounds = true } } func reportDialog(){ let dialogController = AZDialogViewController(title: nil, message: nil) dialogController.dismissDirection = .bottom dialogController.dismissWithOutsideTouch = true let primary = #colorLiteral(red: 0.1019607843, green: 0.737254902, blue: 0.6117647059, alpha: 1) let primaryDark = #colorLiteral(red: 0.0862745098, green: 0.6274509804, blue: 0.5215686275, alpha: 1) dialogController.buttonStyle = { (button,height,position) in button.tintColor = primary button.layer.masksToBounds = true button.setBackgroundImage(UIImage.imageWithColor(primary) , for: .normal) button.setBackgroundImage(UIImage.imageWithColor(primaryDark), for: .highlighted) button.setTitleColor(UIColor.white, for: []) button.layer.masksToBounds = true button.layer.borderColor = self.primaryColor.cgColor button.layer.borderColor = primary.cgColor } dialogController.buttonInit = { index in return HighlightableButton() } dialogController.cancelEnabled = true dialogController.cancelButtonStyle = { (button, height) in button.tintColor = primary button.setTitle("CANCEL", for: []) return true } dialogController.addAction(AZDialogAction(title: "Mute", handler: { (dialog) -> (Void) in dialog.dismiss() })) dialogController.addAction(AZDialogAction(title: "Group Info", handler: { (dialog) -> (Void) in dialog.dismiss() })) dialogController.addAction(AZDialogAction(title: "Export Chat", handler: { (dialog) -> (Void) in dialog.dismiss() })) dialogController.addAction(AZDialogAction(title: "Clear Chat", handler: { (dialog) -> (Void) in dialog.dismiss() })) dialogController.addAction(AZDialogAction(title: "Exit Chat", handler: { (dialog) -> (Void) in dialog.dismiss() })) dialogController.show(in: self) } var tableViewDialogController: AZDialogViewController? func tableViewDialog(){ let dialog = AZDialogViewController(title: "Switch Account", message: nil,widthRatio: 1.0) tableViewDialogController = dialog dialog.showSeparator = false let container = dialog.container dialog.customViewSizeRatio = ( view.bounds.height - 100) / view.bounds.width let tableView = UITableView(frame: .zero, style: .plain) container.addSubview(tableView) tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell") tableView.delegate = self tableView.dataSource = self tableView.separatorColor = .clear //tableView.bouncesZoom = false tableView.bounces = false tableView.translatesAutoresizingMaskIntoConstraints = false tableView.topAnchor.constraint(equalTo: container.topAnchor).isActive = true tableView.bottomAnchor.constraint(equalTo: container.bottomAnchor, constant: -32).isActive = true tableView.leftAnchor.constraint(equalTo: container.leftAnchor).isActive = true tableView.rightAnchor.constraint(equalTo: container.rightAnchor).isActive = true dialog.gestureRecognizer.delegate = self dialog.dismissDirection = .bottom dialog.show(in: self) { dialog in dialog.contentOffset = self.view.frame.height / 2.0 - dialog.estimatedHeight / 2.0 + 15 } } @IBAction func fullScreenDialog(_ sender: UIButton) { tableViewDialog() } var items: [String] = { var list = [String]() for i in 0..<100 { list.append("Account \(i)") } return list }() func handlerForIndex(_ index: Int)->ActionHandler{ switch index{ case 0: return { dialog in print("action for index 0") } case 1: return { dialog in print("action for index 1") } default: return {dialog in print("default action") } } } var shouldDismiss: Bool = false var velocity: CGFloat = 0.0 } extension ViewController: UITableViewDelegate{ public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) tableViewDialogController?.dismiss() } func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { let duration = Double(1.0/abs(velocity)) if scrollView.isAtTop { if shouldDismiss { tableViewDialogController?.animationDuration = duration tableViewDialogController?.dismiss() }else { tableViewDialogController?.applyAnimatedTranslation(-velocity * 35.0,duration: min(max(duration,0.2),0.4)) } } } func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) { shouldDismiss = velocity.y < -3.0 self.velocity = velocity.y } func scrollViewDidScroll(_ scrollView: UIScrollView) { scrollView.bounces = !scrollView.isAtTop } } extension ViewController: UIGestureRecognizerDelegate { func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool { let optionalTableView: UITableView? = otherGestureRecognizer.view as? UITableView guard let tableView = optionalTableView, let panGesture = gestureRecognizer as? UIPanGestureRecognizer, let direction = panGesture.direction else { return false } if tableView.isAtTop && direction == .down { return true } else { return false } } } extension ViewController: UITableViewDataSource{ func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return items.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if let cell = tableView.dequeueReusableCell(withIdentifier: "cell"){ cell.textLabel?.text = items[indexPath.row] return cell } return UITableViewCell() } } extension UIImage { class func imageWithColor(_ color: UIColor) -> UIImage { let rect: CGRect = CGRect(x: 0, y: 0, width: 1, height: 1) UIGraphicsBeginImageContextWithOptions(CGSize(width: 1, height: 1), false, 0) color.setFill() UIRectFill(rect) let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext() return image } } class HighlightableButton: UIButton{ var action: ((UIButton)->Void)? = nil convenience init(_ action: ((UIButton)->Void)? = nil ) { self.init() self.action = action addTarget(self, action: #selector(didClick(_:)), for: .touchUpInside) } override init(frame: CGRect) { super.init(frame: frame) setup() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } func setup() { backgroundColor = #colorLiteral(red: 0.1019607843, green: 0.737254902, blue: 0.6117647059, alpha: 1) layer.cornerRadius = 5 layer.masksToBounds = true } override var isHighlighted: Bool{ set{ UIView.animate(withDuration: 0.1) { [weak self] in self?.alpha = newValue ? 0.5 : 1 self?.transform = newValue ? CGAffineTransform(scaleX: 0.95, y: 0.95) : .identity } super.isHighlighted = newValue }get{ return super.isHighlighted } } @objc func didClick(_ sender: UIButton) { self.action?(self) } } public extension UIScrollView { var isAtTop: Bool { return contentOffset.y <= verticalOffsetForTop } var isAtBottom: Bool { return contentOffset.y >= verticalOffsetForBottom } var verticalOffsetForTop: CGFloat { let topInset = contentInset.top return -topInset } var verticalOffsetForBottom: CGFloat { let scrollViewHeight = bounds.height let scrollContentSizeHeight = contentSize.height let bottomInset = contentInset.bottom let scrollViewBottomOffset = scrollContentSizeHeight + bottomInset - scrollViewHeight return scrollViewBottomOffset } } public enum PanDirection: Int { case up, down, left, right public var isVertical: Bool { return [.up, .down].contains(self) } public var isHorizontal: Bool { return !isVertical } } public extension UIPanGestureRecognizer { public var direction: PanDirection? { let velocity = self.velocity(in: view) let isVertical = abs(velocity.y) > abs(velocity.x) switch (isVertical, velocity.x, velocity.y) { case (true, _, let y) where y < 0: return .up case (true, _, let y) where y > 0: return .down case (false, let x, _) where x > 0: return .right case (false, let x, _) where x < 0: return .left default: return nil } } }
711f52e280779b1eb8a3f851ce477ad7
34.759197
198
0.612748
false
false
false
false
abeschneider/stem
refs/heads/master
Sources/Op/checkgradient.swift
mit
1
// // checkgradient.swift // stem // // Created by Abe Schneider on 12/8/15. // Copyright © 2015 Abe Schneider. All rights reserved. // import Foundation import Tensor func calcForwardGrad<S:Storage> (_ op:Op<S>, params:Tensor<S>, eps:Double) -> Tensor<S> where S.ElementType:FloatNumericType { let jacobian:Tensor<S> = zeros(Extent(params.shape.elements, op.output.shape.elements)) // for i in 0..<params.shape.elements { var k = 0 for i in params.indices() { let old_value:S.ElementType = params[i] // positive direction params[i] = old_value + S.ElementType(eps) op.reset() op.apply() let pvalue = copy(ravel(op.output)) // negative direction params[i] = old_value - S.ElementType(eps) op.reset() op.apply() let nvalue = copy(ravel(op.output)) // return to original value params[i] = old_value let diff:Tensor<S> = (pvalue - nvalue) * S.ElementType(1.0/(2.0*eps)) jacobian[k, all] = ravel(diff) k += 1 } return jacobian } func calcBackwardGrad<S:Storage> (_ forward:Op<S>, _ backward:Op<S>, gradParams:Tensor<S>) -> Tensor<S> where S.ElementType:FloatNumericType { forward.reset() forward.apply() // let gradOutput = ravel(backward.inputs["gradOutput"]![0].output) let gradOutput = backward.inputs["gradOutput"]![0].output let jacobian:Tensor<S> = zeros(Extent(gradParams.shape.elements, gradOutput.shape.elements)) // for i in 0..<gradOutput.shape.elements { var k = 0 for i in gradOutput.indices() { fill(gradOutput, value: 0) gradOutput[i] = 1 (backward as! GradientType).reset() backward.apply() let din = ravel(gradParams) jacobian[all, k] = din k += 1 } return jacobian } public func checkGradient<S:Storage> (_ op:Op<S>, grad:Op<S>, params:Tensor<S>, gradParams:Tensor<S>, eps:Double) -> S.ElementType where S.ElementType:FloatNumericType { op.reset() op.apply() grad.apply() let fgrad = calcForwardGrad(op, params: params, eps: eps) let bgrad = calcBackwardGrad(op, grad, gradParams: gradParams) let error:Tensor<S> = zeros(fgrad.shape) sub(fgrad, bgrad, result: error) return max(abs(error)) } // Required for testing loss functions (where gradParams is not available). public func checkGradient<S:Storage, OpT:Op<S>> (_ op:OpT, grad:Op<S>, input:Tensor<S>, eps:Double) -> S.ElementType where S.ElementType:FloatNumericType, OpT:Loss, OpT.StorageType.ElementType==S.ElementType { op.apply() grad.apply() // let result = Tensor<S>(Extent(gradParams.map { $0.shape.elements }.reduce(0, combine: +))) let result:Tensor<S> = zeros(grad.output.shape) // copy gradients, they will be overwritten from subsequent calls to `fn` let analytical_diff = copy(grad.output) for i in 0..<input.shape.elements { let old_value:S.ElementType = input[i] // positive direction input[i] = old_value + S.ElementType(eps) op.apply() let pvalue:OpT.StorageType.ElementType = op.value // negative direction input[i] = old_value - S.ElementType(eps) op.apply() let nvalue:OpT.StorageType.ElementType = op.value // return to original value input[i] = old_value let numerical_diff = (pvalue - nvalue) / S.ElementType(2.0*eps) // TODO: Look into alternate formulations (e.g. either norm of both, or max of denom.) result[i] = abs((numerical_diff - analytical_diff[i])/(analytical_diff[i] + S.ElementType(eps))) } return max(abs(result)) }
701132a41212d135063e2fe7eb2e527c
29.349206
163
0.612448
false
false
false
false
kojima/simple-spritekit-shooting
refs/heads/master
simple-shooting-game/GameScene.swift
gpl-3.0
1
// // GameScene.swift // simple-shooting-game // // Created by Hidenori Kojima on 2016/12/27. // Copyright © 2016年 Hidenori Kojima. All rights reserved. // import SpriteKit import GameplayKit import CoreMotion import AVFoundation class GameScene: SKScene, SKPhysicsContactDelegate { // ゲームの状態を管理するための列挙型を定義する private enum GameState { case Playing // プレイ中 case GameWin // ゲームクリア case GameOver // ゲームオーバー case WaitToRestartFromWin // ゲームクリアからのリスタート待ち case WaitToRestartFromLose // ゲームオーバーからのリスタート待ち } // ゲームの残り距離を表示するためのクラスを定義する private class DistanceMeter: SKSpriteNode { let currentMeter = SKSpriteNode() convenience init(size: CGSize) { self.init(texture: nil, color: SKColor.white, size: size) // 現在の進行距離を表示するためのメーターをセットアップする currentMeter.size = CGSize(width: size.width, height: 0) currentMeter.color = SKColor(red: 26 / 255.0, green: 188 / 255.0, blue: 156 / 255.0, alpha: 1.0) currentMeter.anchorPoint = CGPoint.zero addChild(currentMeter) } // 進行距離をアップデートするメソッド func update(_ distance: Double) { currentMeter.size = CGSize(width: size.width, height: size.height * CGFloat(distance / 100.0)) } } private var player: SKSpriteNode! // プレイヤー (スペースシップ) private var motionManager: CMMotionManager = CMMotionManager() // モーションマネージャー: iPadの傾きを検出する private var beamCount = 0 // ビームの発射数: 同時発射数を最大3発に制限するためのカウンター private var lastEnemySpawnedTime: TimeInterval! // 最後に敵を生成した時刻を保持するための変数 private var bgm = AVAudioPlayer() // BGMようのオーディオプレイヤー private var gameState = GameState.Playing // ゲームの現在の状態 private var gameWinTitle: SKSpriteNode! // ゲームクリア用タイトル private var gameOverTitle: SKSpriteNode! // ゲームオーバー用タイトル private var restartButton: SKSpriteNode! // リスタートボタン private let playerCategory: UInt32 = 0x1 << 0 // プレイヤーとプレイヤービームの衝突判定カテゴリを01(2進数)にする private let enemyCategory: UInt32 = 0x1 << 1 // 敵と敵ビームの衝突判定カテゴリを10(2進数)にする private let font = BMGlyphFont(name:"88ZenFont") // 88Zenフォント(スコア表記に使用する) private var scoreLabel: BMGlyphLabel! // ゲームスコアを表示するためのラベル private var scoreMargin: CGPoint! // ゲームスコアを左上に表示する際のマージン private var currentScore = 0 // 現在のゲームスコア private var distanceMeter: DistanceMeter! // ゲームの進行距離表示メーター private var gameStartTime: TimeInterval! // ゲームのスタート時間 override func didMove(to view: SKView) { player = SKSpriteNode(imageNamed: getImage("spaceship01")) // プレイヤーにデバイスに応じた画像をセットする gameWinTitle = SKSpriteNode(imageNamed: getImage("game_win")) // ゲームクリア用タイトルにデバイスに応じた画像をセットする gameOverTitle = SKSpriteNode(imageNamed: getImage("game_over")) // ゲームオーバー用タイトルにデバイスに応じた画像をセットする restartButton = SKSpriteNode(imageNamed: getImage("restart_button")) // リスタートボタンにデバイスに応じた画像をセットする // 画面をミッドナイトブルー(red = 44, green = 62, blue = 80)に設定する // 色参照: https://flatuicolors.com/ backgroundColor = SKColor(red: 44.0 / 255.0, green: 62.0 / 255.0, blue: 80.0 / 255.0, alpha: 1.0) player.anchorPoint = CGPoint(x: 0.5, y: 0.5) // スプライトの中心を原点とする player.position = CGPoint(x: size.width * 0.5, y: player.size.height * 0.5 + 16) // プレイヤーを画面中央下側に配置する player.zPosition = 100 // プレイヤーを最前面に配置する player.name = "player_ship" // プレイヤースプライトを"player_ship"と名付ける // プレイヤーの物理衝突の設定を行う player.physicsBody = SKPhysicsBody(rectangleOf: player.size) // プレイヤー衝突用の物理ボディーを用意する player.physicsBody?.affectedByGravity = false // 重力の影響は受けないように設定 player.physicsBody?.categoryBitMask = playerCategory // 物理ボティーにプレイヤーの衝突判定カテゴリを設定 player.physicsBody?.contactTestBitMask = enemyCategory // 衝突検出対象を敵の衝突判定カテゴリに設定 player.physicsBody?.collisionBitMask = 0 // 衝突しても衝突相手からの力を受けないように設定 addChild(player) // シーンにプレイヤーを追加する // 星背景(前面)を配置する let starFront = SKSpriteNode(imageNamed: getImage("star_front")) starFront.anchorPoint = CGPoint(x: 0, y: 0) // 星背景(前面)の左下を原点とする starFront.position = CGPoint(x: 0, y: 0) // シーンの左下に配置する starFront.zPosition = 10 // プレイヤーよりも背面に配置する addChild(starFront) // シーンに星背景(前面)を追加する // 星背景(前面)を下方向にシーンの高さ分だけ4秒間で移動し、その後に元の位置に戻す // アクションを追加する let starFrontActionMove = SKAction.moveBy(x: 0, y: -size.height, duration: 4) let starFrontsActionReset = SKAction.moveBy(x: 0, y: size.height, duration: 0) starFront.run(SKAction.repeatForever( SKAction.sequence([starFrontActionMove, starFrontsActionReset]) )) // 星背景(後面)を配置する let starBack = SKSpriteNode(imageNamed: getImage("star_back")) starBack.anchorPoint = CGPoint(x: 0, y: 0) // 星背景(後面)の左下を原点とする starBack.position = CGPoint(x: 0, y: 0) // シーンの左下に配置する starBack.zPosition = 1 // 星背景(前面)よりも背面に配置する addChild(starBack) // シーンに星背景(後面)を追加する // 星背景(後面)を下方向にシーンの高さ分だけ6秒間で移動し、その後に元の位置に戻す // アクションを追加する // 星背景(前面)よりも移動時間を長くすることで、背景に奥行きが感じられるようになる let starBackActionMove = SKAction.moveBy(x: 0, y: -size.height, duration: 6) let starBackActionReset = SKAction.moveBy(x: 0, y: size.height, duration: 0) starBack.run(SKAction.repeatForever( SKAction.sequence([starBackActionMove, starBackActionReset]) )) // ゲームクリア用タイトルをセットアップする gameWinTitle.position = CGPoint(x: size.width * 0.5, y: size.height * 0.5 + 80) // シーン中央より少し上に配置する gameWinTitle.zPosition = 200 // シーンの最前面に表示されるようにする // ゲームクリアの際のリスタートボタンをセットアップする restartButton.position = CGPoint(x: size.width * 0.5, y: size.height * 0.5 - 88) // シーンの中央より少し下に配置する restartButton.zPosition = 200 // シーンの最前面に表示されるようにする // ゲームオーバー用タイトルをセットアップする gameOverTitle.position = CGPoint(x: size.width * 0.5, y: size.height * 0.5) // シーン中央に配置する gameOverTitle.zPosition = 200 // シーンの最前面に表示されるようにする // BGMをループ再生する let bgmUrl = URL(fileURLWithPath: Bundle.main.path(forResource: "bgm", ofType:"mp3")!) bgm = try! AVAudioPlayer(contentsOf: bgmUrl) bgm.numberOfLoops = -1 // ループ再生するように設定 bgm.play() physicsWorld.contactDelegate = self // 衝突判定を自分自身で行うように設定 // iPadの傾き検出を開始する motionManager.startAccelerometerUpdates() // ゲームスコア用ラベルをセットアップする scoreLabel = createScoreLabel() // ゲームスコア用ラベルを作成する scoreLabel.setHorizontalAlignment(.left) // ラベルの横方向基準点を左端にする scoreLabel.setVerticalAlignment(.top) // ラベルの縦方向基準点を上端にする scoreMargin = getScoreMargin() // ラベルのマージン情報を取得する scoreLabel.position = CGPoint(x: scoreMargin.x, y: size.height - scoreMargin.y) // ラベルをシーン左上に配置する addChild(scoreLabel) // ゲームスコア用ラベルをシーンに追加する // ゲームの進行距離表示メーターをセットアップする distanceMeter = DistanceMeter(size: CGSize(width: 16, height: size.height)) distanceMeter.anchorPoint = CGPoint.zero // 原点を左下にする distanceMeter.position = CGPoint(x: size.width - 16, y: 0) // シーンの左端に配置する distanceMeter.zPosition = 20 // シーンの高さ(zPosition)を背景とプレイヤーの間にする addChild(distanceMeter) // メーターをシーンに追加する } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { if gameState == .WaitToRestartFromLose { // ゲームの状態がゲームオーバーからのリスタート待ちの場合 restart() } else if gameState == .WaitToRestartFromWin { // ゲームの状態がゲームクリアからのリスタート待ちの場合 if let touch = touches.first { let location = touch.location(in: self) // タッチされた場所を取得する let touchedNode = atPoint(location) // タッチされた場所に位置するノードを取得する if touchedNode == restartButton { // タッチされたノードがリスタートボタンだった場合 run(SKAction.playSoundFileNamed("tap.wav", waitForCompletion: false)) restart() } else { // それ以外の場所がタッチされた場合 fireBeam() } } } else if gameState == .Playing { // ゲームの状態がプレイ中の場合 fireBeam() } } override func update(_ currentTime: TimeInterval) { if gameState == .Playing { // ゲームの状態がプレイ中の場合 controlPlayer() // ランダムな間隔(3秒〜6秒)で敵を発生させる if lastEnemySpawnedTime == nil { // 最終敵生成時刻が未設定の場合 lastEnemySpawnedTime = currentTime // 現在時刻を最終敵生成時刻に設定する } else if currentTime - lastEnemySpawnedTime > TimeInterval(3 + arc4random_uniform(3)) { spawnEnemy() // 敵を生成する lastEnemySpawnedTime = currentTime // 最終敵生成時刻を更新する } // ゲームの進行距離を更新する if gameStartTime == nil { // ゲーム開始時刻が未設定の場合 gameStartTime = currentTime // 現在の時刻をゲーム開始時刻に設定する } else { // 既にゲーム開始時刻が設定されている場合 let currentDistance = (currentTime - gameStartTime) * 2 // 現在の距離を計算する distanceMeter.update(currentDistance) // ゲームの進行距離表示メーターを更新する if currentDistance > 100 { // 進行距離が100を超えた場合 gameWin() // ゲームクリアの処理をする } } } else if gameState == .GameWin || gameState == .WaitToRestartFromWin { // ゲームの状態がゲームクリアまたはゲームクリアからのリスタート待ちの場合 controlPlayer() } } // プレイヤーからのビームを発射を処理するメソッド private func fireBeam() { // 現在のビーム発射数が3発に達していない場合、ビームを発射する if beamCount < 3 { // ビーム用のスプライトを生成する let beam = SKSpriteNode(imageNamed: getImage("beam")) beam.anchorPoint = CGPoint(x: 0.5, y: 1) // ビームの中央上側を原点とする beam.position = CGPoint(x: player.position.x, y: player.position.y + player.size.height * 0.5) // プレイヤーの先頭にビームを配置する beam.zPosition = player.zPosition - 1 // プレイヤースプライトの背面に配置する beam.name = "player_beam" // ビームスプライトを"player_beam"と名付ける // ビームの物理衝突の設定を行う beam.physicsBody = SKPhysicsBody(rectangleOf: beam.size) // ビーム衝突用の物理ボディーを用意する beam.physicsBody?.affectedByGravity = false // 重力の影響は受けないように設定 beam.physicsBody?.categoryBitMask = playerCategory // 物理ボティーにプレイヤーの衝突判定カテゴリを設定 beam.physicsBody?.contactTestBitMask = enemyCategory // 衝突検出対象を敵の衝突判定カテゴリに設定 beam.physicsBody?.collisionBitMask = 0 // 衝突しても衝突相手からの力を受けないように設定 // ビーム用スプライトに以下のアクションを追加する: // 1. ビーム発射音を再生する // 2. シーンの高さの分だけ0.5秒で前に進む // 3. ビーム発射数を1つ減らす // 4. ビーム用スプライトをシーンから削除する let action = SKAction.sequence([ SKAction.playSoundFileNamed("beam.wav", waitForCompletion: false), SKAction.moveBy(x: 0, y: size.height, duration: 0.5), SKAction.run({ self.beamCount -= 1 }), SKAction.removeFromParent() ]) beam.run(action) // ビームにアクションを追加する addChild(beam) // ビームをシーンに追加する beamCount += 1 // ビーム発射数を1つ増やす } } // プレイヤー操作を処理するメソッド private func controlPlayer() { // iPadの傾きデータが取得できた場合、プレイヤーをコントロールする if let data = motionManager.accelerometerData { // iPadの横方向の傾きが一定以上だった場合、傾き量に応じてプレイヤーを横方向に移動させる if fabs(data.acceleration.x) > 0.2 { player.position.x += CGFloat(20 * data.acceleration.x) if data.acceleration.x > 0 { player.texture = SKTexture(imageNamed: getImage("spaceship03")) } else { player.texture = SKTexture(imageNamed: getImage("spaceship02")) } } else { player.texture = SKTexture(imageNamed: getImage("spaceship01")) } // iPadの縦方向の傾きが一定以上だった場合、傾き量に応じてプレイヤーを縦方向に移動させる if fabs(data.acceleration.y) > 0.2 { player.position.y += 5 * (data.acceleration.y > 0 ? 1 : -1) } } if player.position.x < player.size.width * 0.5 { // プレイヤーが画面左端よりも左に移動してしまったら、画面左端に戻す player.position.x = player.size.width * 0.5 } else if player.position.x > size.width - player.size.width * 0.5 { // プレイヤーが画面右端よりも右に移動してしまったら、画面右端に戻す player.position.x = size.width - player.size.width * 0.5 } if player.position.y < player.size.height * 0.5 { // プレイヤーが画面下端よりも下に移動してしまったら、画面下端に戻す player.position.y = player.size.height * 0.5 } else if player.position.y > size.height - player.size.height * 0.5 { // プレイヤーが画面上端よりも上に移動してしまったら、画面上端に戻す player.position.y = size.height - player.size.height * 0.5 } } // 敵を生成するメソッド private func spawnEnemy() { let enemy = SKSpriteNode(imageNamed: getImage("enemy_ship")) // 敵のスプライトを作成する enemy.anchorPoint = CGPoint(x: 0.5, y: 0.5) // 敵スプライトの中心を原点とする enemy.position.x = size.width * (0.25 + CGFloat(arc4random_uniform(5)) / 10.0) // 敵の横方向の位置をシーン幅の1/4〜3/4の間の値にする enemy.position.y = size.height + enemy.size.height * 0.5 // 敵の縦方向の位置をシーン上端にする enemy.zPosition = player.zPosition + 10 // 敵スプライトをプレイヤーより前面に表示する enemy.name = "enemy_ship" // 敵スプライトを"enemy_ship"と名付ける // 敵の物理衝突の設定を行う enemy.physicsBody = SKPhysicsBody(rectangleOf: enemy.size) // 敵衝突用の物理ボディを用意する enemy.physicsBody?.affectedByGravity = false // 重力の影響は受けないように設定 enemy.physicsBody?.categoryBitMask = enemyCategory // 物理ボティーに敵の衝突判定カテゴリを設定 enemy.physicsBody?.contactTestBitMask = playerCategory // 衝突検出対象をプレイヤーの衝突判定カテゴリに設定 enemy.physicsBody?.collisionBitMask = 0 // 衝突しても衝突相手からの力を受けないように設定 // 敵スプライトの縦方向のアクションを定義する: // 1. 敵発生音を再生する // 2. (シーン縦幅 + 敵スプライト高さ)分の距離を縦方向に3〜6秒の時間(ランダム時間)で移動する // 3. 敵スプライトをシーンから削除する let verticalAction = SKAction.sequence([ SKAction.playSoundFileNamed("enemy_spawn.wav", waitForCompletion: false), SKAction.moveBy(x: 0, y: -(size.height + enemy.size.height * 0.5), duration: TimeInterval(Int(3 + arc4random_uniform(3)))), SKAction.removeFromParent() ]) // 敵スプライトの横方向のアクションを定義する: // 以下の操作をずっと繰り返す: // 1. 0.5〜2秒(ランダム時間)待つ // 2. -50〜50の距離(ランダム距離)を縦方向に0.5秒で移動する let horizontalAction = SKAction.repeatForever( SKAction.sequence([ SKAction.wait(forDuration: 0.5, withRange: 2), SKAction.run { enemy.run(SKAction.moveBy(x: 50.0 - CGFloat(arc4random_uniform(100)), y: 0, duration: 0.5)) } ]) ) // 敵スプライトからビームを発射するアクションを定義する // 以下の操作をずっと繰り返す: // 1. 1〜3秒(ランダム時間)待つ // 2. ビーム発射メソッドを実行する let beamAction = SKAction.repeatForever( SKAction.sequence([ SKAction.wait(forDuration: 1, withRange: 3), SKAction.run { self.spawnEnemyBeam(enemy: enemy); } ]) ) enemy.run(SKAction.group([verticalAction, horizontalAction, beamAction])) // 上の3つのアクションを並行して実行する addChild(enemy) // 敵スプライトをシーンに追加する } // 敵のビームを生成するメソッド private func spawnEnemyBeam(enemy: SKSpriteNode) { let beam = SKSpriteNode(imageNamed: getImage("enemy_beam")) // 敵ビームのスプライトを作成する beam.anchorPoint = CGPoint(x: 0.5, y: 0) // 敵ビームスプライトの中央下側を原点とする beam.position = CGPoint(x: enemy.position.x, y: enemy.position.y - enemy.size.height * 0.5) // 敵スプライトの先端にビームを配置する beam.zPosition = enemy.zPosition - 1 // 敵スプライトの背面にビームを配置する beam.name = "enemy_beam" // 敵ビームスプライトを"enemy_beam"と名付ける // 敵ビームの物理衝突の設定を行う beam.physicsBody = SKPhysicsBody(rectangleOf: beam.size) // 敵ビーム衝突用の物理ボディを用意する beam.physicsBody?.affectedByGravity = false // 重力の影響は受けないように設定 beam.physicsBody?.categoryBitMask = enemyCategory // 物理ボティーに敵の衝突判定カテゴリを設定 beam.physicsBody?.contactTestBitMask = playerCategory // 衝突検出対象をプレイヤーの衝突判定カテゴリに設定 beam.physicsBody?.collisionBitMask = 0 // 衝突しても衝突相手からの力を受けないように設定 // ビーム用に以下のアクションを定義する: // 1. 敵ビーム発射音を再生する // 2. シーンの高さ分の距離だけ縦方向に0.75秒かけて移動する // 3. 敵ビームスプライトをシーンから削除する let action = SKAction.sequence([ SKAction.playSoundFileNamed("enemy_beam.wav", waitForCompletion: false), SKAction.moveBy(x: 0, y: -size.height, duration: 0.75), SKAction.removeFromParent() ]) beam.run(action) // 上記アクションを実行する addChild(beam) // 敵ビームをシーンに追加する } // プレイヤーと敵または敵ビームが接触したときに呼び出されるメソッド func didBegin(_ contact: SKPhysicsContact) { var player: SKNode! var enemy: SKNode! // 衝突した2つの物体(bodyA/bodyB)のうちどちらがプレイヤーカテゴリなのかをチェックする if contact.bodyA.categoryBitMask == playerCategory { player = contact.bodyA.node! // 衝突した2体のうち、bodyAがプレイヤー側 enemy = contact.bodyB.node! // 衝突した2体のうち、bodyBが敵側 } else if contact.bodyB.categoryBitMask == playerCategory { player = contact.bodyB.node! // 衝突した2体のうち、bodyBがプレイヤー側 enemy = contact.bodyA.node! // 衝突した2体のうち、bodyAが敵側 } if player.name == "player_ship" && (enemy.name == "enemy_ship" || enemy.name == "enemy_beam") { // プレイヤーが敵または敵ビームと衝突した場合 explodePlayer(player) // プレイヤーを爆発させる if enemy.name == "enemy_ship" { // 敵側が敵機だった場合: explodeEnemy(enemy) // 敵機も一緒に爆発させる } else { // 敵ビームだった場合: enemy.removeFromParent() // 敵ビームをシーンから削除する } } else if player.name == "player_beam" && enemy.name == "enemy_ship" { // プレイヤービームが敵と衝突した場合 beamCount -= 1 // 敵を爆破したビーム分だけビームカウントを減らす player.removeFromParent() // ビームをシーンから削除する explodeEnemy(enemy) // 敵を爆発させる } } // プレイヤーを爆発させるメソッド private func explodePlayer(_ player: SKNode) { // プレイヤーで以下のアクションを実行する: // 1. プレイヤー爆発用サウンドを再生する // 2. プレイヤーをシーンから削除する player.run(SKAction.sequence([ SKAction.playSoundFileNamed("explosion.wav", waitForCompletion: false), SKAction.removeFromParent() ])) // プレイヤー爆発用のスプライトをセットアップする let explosion = SKSpriteNode(imageNamed: getImage("explosion")) // プレイヤー爆発用スプライトを作成する explosion.position = player.position // プレイヤーと同じ位置に配置する explosion.zPosition = player.zPosition // プレイヤーと同じ高さ(zPosition)にする explosion.alpha = 0 // 最初はスプライトを透過度(アルファ)を透明にする explosion.setScale(0) // 最初はスプライトの倍率(スケール)を0にする // プレイヤー爆発スプライトで以下の2つのアクションを並行して実行する: // 1. スプライトの倍率(スケール)を1倍(元の大きさ)にする // 2. 以下のアクションを順番に実行する: // 2-1. 0.2秒間でフェードインする // 2-2. 0.5秒待つ // 2-3. 1.5秒間でフェードアウトする // 2-4. プレイヤー爆発スプライトをシーンから削除する explosion.run(SKAction.group([ SKAction.scale(to: 1.0, duration: 0.2), SKAction.sequence([ SKAction.fadeIn(withDuration: 0.2), SKAction.wait(forDuration: 0.5), SKAction.fadeOut(withDuration: 1.5), SKAction.removeFromParent() ]) ])) addChild(explosion) // プレイヤー爆発スプライトをシーンに追加する gameOver() } // 敵を爆発させるメソッド private func explodeEnemy(_ enemy: SKNode) { // 敵で以下のアクションを実行する: // 1. 敵爆発用サウンドを再生する // 2. 敵をシーンから削除する enemy.run(SKAction.sequence([ SKAction.playSoundFileNamed("enemy_explosion.wav", waitForCompletion: false), SKAction.removeFromParent() ])) // 敵爆発用のスプライトをセットアップする let explosion = SKSpriteNode(imageNamed: getImage("enemy_explosion")) // 敵爆発用スプライトを作成する explosion.position = enemy.position // 敵と同じ位置に配置する explosion.zPosition = enemy.zPosition // 敵と同じ高さ(zPosition)にする explosion.alpha = 0 // 最初はスプライトを透過度(アルファ)を透明にする explosion.setScale(0) // 最初はスプライトの倍率(スケール)を0にする // 敵爆発スプライトで以下の2つのアクションを並行して実行する: // 1. スプライトの倍率(スケール)を1倍(元の大きさ)にする // 2. 以下のアクションを順番に実行する: // 2-1. 0.2秒間でフェードインする // 2-2. 0.5秒待つ // 2-3. 1.5秒間でフェードアウトする // 2-4. 敵爆発スプライトをシーンから削除する explosion.run(SKAction.group([ SKAction.scale(to: 1.0, duration: 0.2), SKAction.sequence([ SKAction.fadeIn(withDuration: 0.2), SKAction.wait(forDuration: 0.5), SKAction.fadeOut(withDuration: 1.5), SKAction.removeFromParent() ]) ])) addChild(explosion) // 敵爆発スプライトをシーンに追加する // スコアを更新する currentScore += 10 // スコアを10加点する scoreLabel.setGlyphText("スコア: \(currentScore)") // スコアをゲームスコア用ラベルに反映させる } // ゲームクリアを処理するメソッド private func gameWin() { // 現在のゲームの状態がプレイ中でない場合は処理を抜ける if gameState != .Playing { return } // ゲームクリア時にシーン内に残っている敵機はすべて爆発させ、 // 敵ビームはシーンから削除する for node in children { if node.name == "enemy_ship" { explodeEnemy(node) } else if node.name == "enemy_beam" { node.removeFromParent() } } gameState = .GameWin // ゲームの状態をゲームクリアにする run(SKAction.playSoundFileNamed("win.wav", waitForCompletion: false)) // ゲームクリア用サウンドを再生する gameWinTitle.alpha = 0 // ゲームクリアタイトルの透明度(アルファ)を透明にする // ゲームクリアタイトルで以下のアクションを実行する: // 1. 以下の処理を3回繰り返す: // 1-1. 0.2秒間でフェードイン // 1-2. 0.2秒間でフェードアウト // 2. 0.2秒間でフェードイン gameWinTitle.run(SKAction.sequence([ SKAction.repeat(SKAction.sequence([ SKAction.fadeIn(withDuration: 0.2), SKAction.fadeOut(withDuration: 0.2) ]), count: 3), SKAction.fadeIn(withDuration: 0.2) ])) addChild(gameWinTitle) // ゲームクリア用のタイトルをシーンに追加する // 以下のアクションをシーンで実行する: // 1. 2.5秒間待つ // 2. 以下の処理を実行する: // 2-1. スコアラベルを画面中央に配置する // 2-2. リスタートボタンをシーンに追加する // 2-3. ゲームの状態をゲームクリアからのリスタート待ちにする run(SKAction.sequence([ SKAction.wait(forDuration: 2.5), SKAction.run { self.scoreLabel.setHorizontalAlignment(.centered) self.scoreLabel.setVerticalAlignment(.middle) self.scoreLabel.position = CGPoint(x: self.size.width * 0.5, y: self.size.height * 0.5) self.addChild(self.restartButton) self.gameState = .WaitToRestartFromWin } ])) } // ゲームオーバーを処理するメソッド private func gameOver() { // ゲームの状態がプレイ中でなければ処理を抜ける if gameState != .Playing { return } gameState = .GameOver // ゲームの状態をゲームオーバーにする motionManager.stopDeviceMotionUpdates() // iPadの傾き検出を停止する // ゲームオーバーの演出を以下のアクションで実行する: // 1. 1.5秒間待つ // 2. BGMを停止する // 3. ゲームオーバー用サウンドを再生する // 4. 以下の処理を実行する: // 4-1. ゲームの状態をリスタート待ちにする // 4-2. ゲームオーバー用タイトルをシーンに追加する // 4-3. ゲームスコア用ラベルをシーンから削除する run(SKAction.sequence([ SKAction.wait(forDuration: 1.5), SKAction.run { self.bgm.stop() }, SKAction.playSoundFileNamed("lose.wav", waitForCompletion: true), SKAction.run { self.gameState = .WaitToRestartFromLose self.addChild(self.gameOverTitle) self.scoreLabel.removeFromParent() }, ])) } // ゲームリスタートを処理するメソッド private func restart() { // ゲームの状態がリスタート待ちでなければ処理を抜ける if gameState != .WaitToRestartFromWin && gameState != .WaitToRestartFromLose { return } bgm.currentTime = 0 // BGMを先頭に戻す bgm.play() // BGMを再生する currentScore = 0 // 現在のスコアを0点にリセットする scoreLabel.setGlyphText("スコア: \(currentScore)") // スコアをゲームスコア用ラベルに反映する beamCount = 0 // ビームカウントを0にセットする distanceMeter.update(0) // ゲームの進行距離表示メーターをリセットする gameStartTime = nil // ゲーム開始時刻を未設定にする lastEnemySpawnedTime = nil // 最終敵発生時刻を未設定にする motionManager.startAccelerometerUpdates() // iPadの傾き検出を再開する if gameState == .WaitToRestartFromWin { // ゲームクリアからのリスタート待ちの場合 gameWinTitle.removeFromParent() // ゲームクリア用タイトルをシーンから削除する restartButton.removeFromParent() // リスタートボタンをシーンから削除する scoreLabel.setHorizontalAlignment(.left) scoreLabel.setVerticalAlignment(.top) scoreLabel.position = CGPoint(x: scoreMargin.x, y: size.height - scoreMargin.y) // スコアラベルをシーン左上に配置し直す } else if gameState == .WaitToRestartFromLose { // ゲームオーバーからのリスタート待ちの場合 gameOverTitle.removeFromParent() // ゲームオーバー用タイトルをシーンから削除する player.position = CGPoint(x: size.width * 0.5, y: player.size.height * 0.5 + 16) // プレイヤーを画面中央下側に配置する addChild(player) // プレイヤーを再度追加する addChild(scoreLabel) // ゲームスコア用ラベルをシーンに追加する } gameState = .Playing // ゲームの状態をプレイ中にする } // デバイスに応じた画像名を返すメソッド private func getImage(_ name: String) -> String { if UIDevice.current.userInterfaceIdiom == .pad { // iPadの場合 return name // そのままの名前で返す } else { // iPhoneの場合 return "\(name)-phone" // 名前の最後に"-phone"と付けて返す } } // デバイスに応じたスコアラベルを生成するメソッド private func createScoreLabel() -> BMGlyphLabel{ let label = BMGlyphLabel(txt: "スコア: \(currentScore)", fnt: font) if UIDevice.current.userInterfaceIdiom == .phone { // iPhoneの場合 label.setScale(0.75) // 少しサイズを小さくする } return label } // デバイスに応じたスコアラベルのマージンを返すメソッド private func getScoreMargin() -> CGPoint { if UIDevice.current.userInterfaceIdiom == .pad { // iPadの場合 return CGPoint(x: 24, y: 16) // 左マージン: 24point, 上マージン: 16pointとする } else { // iPhoneの場合 return CGPoint(x: 12, y: 8) //   左マージン: 12point, 上マージン: 8pointとする } } }
a6e72db79189ceb07830869ecc6e968e
47.920608
135
0.553089
false
false
false
false
when50/TabBarView
refs/heads/master
TabBarPageView/TabBarView.swift
mit
1
// // TabBarView.swift // TabBarPageView // // Created by chc on 2017/6/9. // Copyright © 2017年 chc. All rights reserved. // import UIKit public class TabBarView: UIView, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout { var tabItems: [(String, ((Int) -> Void))] = [] var currentTabIndex = 0 var collectionView: UICollectionView private var cellForSize: TabCollectionCell public var selectedStyle: BaseStyle = { return SelectedStyle(textColor: UIColor.gray) }() public var unselectedStyle: BaseStyle = { return UnselectedStyle(textColor: UIColor.black) }() public init(items: [(String, ((Int) -> Void))]){ let bundle = Bundle(for: TabBarView.self) let nib = UINib(nibName: "\(TabCollectionCell.self)", bundle: bundle) cellForSize = nib.instantiate(withOwner: nil, options: nil).first as! TabCollectionCell tabItems = items let layout = UICollectionViewFlowLayout() layout.scrollDirection = .horizontal collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout) super.init(frame: .zero) collectionView.dataSource = self collectionView.delegate = self collectionView.scrollsToTop = false collectionView.translatesAutoresizingMaskIntoConstraints = false collectionView.backgroundColor = UIColor.white collectionView.showsHorizontalScrollIndicator = false collectionView.showsVerticalScrollIndicator = false collectionView.register(nib, forCellWithReuseIdentifier: "\(TabCollectionCell.self)") addSubview(collectionView) let top = NSLayoutConstraint(item: self, attribute: .top, relatedBy: .equal, toItem: collectionView, attribute: .top, multiplier: 1.0, constant: 0) let bottom = NSLayoutConstraint(item: self, attribute: .bottom, relatedBy: .equal, toItem: collectionView, attribute: .bottom, multiplier: 1.0, constant: 0) let left = NSLayoutConstraint(item: self, attribute: .left, relatedBy: .equal, toItem: collectionView, attribute: .left, multiplier: 1.0, constant: 0) let right = NSLayoutConstraint(item: self, attribute: .right, relatedBy: .equal, toItem: collectionView, attribute: .right, multiplier: 1.0, constant: 0) addConstraints([top, bottom, left, right]) } convenience override init(frame: CGRect) { self.init(items: []) } required public init?(coder aDecoder: NSCoder) { fatalError() } public func setCurrentTabIndex(newIndex: Int) { collectionView.scrollToItem( at: IndexPath(item: newIndex, section: 0), at: newIndex < currentTabIndex ? .left : .right, animated: true) currentTabIndex = newIndex collectionView.reloadData() } // MARK: UICollectionViewDataSource public func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return tabItems.count } public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "\(TabCollectionCell.self)", for: indexPath) as? TabCollectionCell else { fatalError() } cell.titleLabel.text = tabItems[indexPath.item].0 let style = currentTabIndex == indexPath.item ? selectedStyle : unselectedStyle style.applyTo(cell) return cell } // MARK: UICollectionViewDelegate public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { if indexPath.item != currentTabIndex { let selected = IndexPath(item: currentTabIndex, section: 0) currentTabIndex = indexPath.item collectionView.reloadItems(at: [selected, indexPath]) tabItems[indexPath.item].1(currentTabIndex) } } // MARK: UICollectionViewDelegateFlowLayout var cacheSizes: [IndexPath: CGSize] = [:] public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { if let size = cacheSizes[indexPath] { return size } else { cellForSize.titleText = tabItems[indexPath.item].0 cellForSize.sizeToFit() let size = CGSize(width: cellForSize.bounds.size.width, height: bounds.size.height) cacheSizes[indexPath] = size return size } } public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat { return 0.0 } public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat { return 0.0 } }
e00b01b57aa556d59bec467b47f6b1c1
41.455172
182
0.578785
false
false
false
false
infobip/mobile-messaging-sdk-ios
refs/heads/master
Classes/Vendor/PSOperations/Operation.swift
apache-2.0
1
/* Copyright (C) 2015 Apple Inc. All Rights Reserved. See LICENSE.txt for this sample’s licensing information Abstract: This file contains the foundational subclass of NSOperation. */ import Foundation /** The subclass of `NSOperation` from which all other operations should be derived. This class adds both Conditions and Observers, which allow the operation to define extended readiness requirements, as well as notify many interested parties about interesting operation state changes */ open class Operation: Foundation.Operation { unowned(unsafe) open var underlyingQueue: DispatchQueue! /* The completionBlock property has unexpected behaviors such as executing twice and executing on unexpected threads. BlockObserver * executes in an expected manner. */ @available(*, deprecated, message: "use BlockObserver completions instead") override open var completionBlock: (() -> Void)? { set { fatalError("The completionBlock property on NSOperation has unexpected behavior and is not supported in PSOperations.Operation 😈") } get { return nil } } // use the KVO mechanism to indicate that changes to "state" affect other properties as well @objc class func keyPathsForValuesAffectingIsReady() -> Set<NSObject> { return ["state" as NSObject] } @objc class func keyPathsForValuesAffectingIsExecuting() -> Set<NSObject> { return ["state" as NSObject] } @objc class func keyPathsForValuesAffectingIsFinished() -> Set<NSObject> { return ["state" as NSObject] } @objc class func keyPathsForValuesAffectingIsCancelled() -> Set<NSObject> { return ["cancelledState" as NSObject] } private var instanceContext = 0 public override init() { super.init() self.addObserver(self, forKeyPath: "isReady", options: [], context: &instanceContext) } init(isUserInitiated: Bool) { super.init() self.userInitiated = isUserInitiated self.addObserver(self, forKeyPath: "isReady", options: [], context: &instanceContext) } deinit { self.removeObserver(self, forKeyPath: "isReady", context: &instanceContext) } open override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { guard context == &instanceContext else { super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context) return } stateAccess.lock() defer { stateAccess.unlock() } guard super.isReady && !isCancelled && state == .pending else { return } evaluateConditions() } /** Indicates that the Operation can now begin to evaluate readiness conditions, if appropriate. */ func didEnqueue() { stateAccess.lock() defer { stateAccess.unlock() } state = .pending } private let stateAccess = NSRecursiveLock() /// Private storage for the `state` property that will be KVO observed. private var _state = State.initialized private let stateQueue = DispatchQueue(label: "Operations.Operation.state") fileprivate var state: State { get { var currentState = State.initialized stateQueue.sync { currentState = _state } return currentState } set { // guard newValue != _state else { return } /* It's important to note that the KVO notifications are NOT called from inside the lock. If they were, the app would deadlock, because in the middle of calling the `didChangeValueForKey()` method, the observers try to access properties like "isReady" or "isFinished". Since those methods also acquire the lock, then we'd be stuck waiting on our own lock. It's the classic definition of deadlock. */ willChangeValue(forKey: "state") stateQueue.sync { guard _state != .finished else { return } assert(_state.canTransitionToState(newValue, operationIsCancelled: isCancelled), "Performing invalid state transition. from: \(_state) to: \(newValue)") _state = newValue } didChangeValue(forKey: "state") } } // Here is where we extend our definition of "readiness". override open var isReady: Bool { stateAccess.lock() defer { stateAccess.unlock() } guard super.isReady else { return false } guard !isCancelled else { return true } switch state { case .initialized, .evaluatingConditions, .pending: return false case .ready, .executing, .finishing, .finished: return true } } open var userInitiated: Bool { get { return qualityOfService == .userInitiated } set { stateAccess.lock() defer { stateAccess.unlock() } assert(state < .executing, "Cannot modify userInitiated after execution has begun.") qualityOfService = newValue ? .userInitiated : .default } } override open var isExecuting: Bool { return state == .executing } override open var isFinished: Bool { return state == .finished } private var __cancelled = false private let cancelledQueue = DispatchQueue(label: "Operations.Operation.cancelled") private var _cancelled: Bool { get { var currentState = false cancelledQueue.sync { currentState = __cancelled } return currentState } set { stateAccess.lock() defer { stateAccess.unlock() } guard _cancelled != newValue else { return } willChangeValue(forKey: "cancelledState") cancelledQueue.sync { __cancelled = newValue } if state == .initialized || state == .pending { state = .ready } didChangeValue(forKey: "cancelledState") if newValue { for observer in observers { observer.operationDidCancel(self) } } } } override open var isCancelled: Bool { return _cancelled } fileprivate func evaluateConditions() { stateAccess.lock() defer { stateAccess.unlock() } assert(state == .pending && !isCancelled, "evaluateConditions() was called out-of-order") guard conditions.count > 0 else { state = .ready return } state = .evaluatingConditions OperationConditionEvaluator.evaluate(conditions, operation: self) { failures in self.stateAccess.lock() defer { self.stateAccess.unlock() } if !failures.isEmpty { self.cancelWithErrors(failures) } self.state = .ready } } // MARK: Observers and Conditions fileprivate(set) var conditions: [OperationCondition] = [] open func addCondition(_ condition: OperationCondition) { assert(state < .evaluatingConditions, "Cannot modify conditions after execution has begun.") conditions.append(condition) } fileprivate(set) var observers: [OperationObserver] = [] open func addObserver(_ observer: OperationObserver) { assert(state < .executing, "Cannot modify observers after execution has begun.") observers.append(observer) } override open func addDependency(_ operation: Foundation.Operation) { assert(state <= .executing, "Dependencies cannot be modified after execution has begun.") super.addDependency(operation) } // MARK: Execution and Cancellation override final public func main() { stateAccess.lock() assert(state == .ready, "This operation must be performed on an operation queue.") if _internalErrors.isEmpty && !isCancelled { state = .executing stateAccess.unlock() for observer in observers { observer.operationDidStart(self) } execute() } else { finish() stateAccess.unlock() } } /** `execute()` is the entry point of execution for all `Operation` subclasses. If you subclass `Operation` and wish to customize its execution, you would do so by overriding the `execute()` method. At some point, your `Operation` subclass must call one of the "finish" methods defined below; this is how you indicate that your operation has finished its execution, and that operations dependent on yours can re-evaluate their readiness state. */ open func execute() { print("\(type(of: self)) must override `execute()`.") finish() } fileprivate var _internalErrors: [NSError] = [] open var errors : [NSError] { return _internalErrors } override open func cancel() { stateAccess.lock() defer { stateAccess.unlock() } guard !isFinished else { return } _cancelled = true if state > .ready { finish() } } open func cancelWithErrors(_ errors: [NSError]) { _internalErrors += errors cancel() } open func cancelWithError(_ error: NSError) { cancelWithErrors([error]) } public final func produceOperation(_ operation: Foundation.Operation) { for observer in observers { observer.operation(self, didProduceOperation: operation) } } // MARK: Finishing /** Most operations may finish with a single error, if they have one at all. This is a convenience method to simplify calling the actual `finish()` method. This is also useful if you wish to finish with an error provided by the system frameworks. As an example, see `DownloadEarthquakesOperation` for how an error from an `NSURLSession` is passed along via the `finishWithError()` method. */ public final func finishWithError(_ error: NSError?) { if let error = error { finish([error]) } else { finish() } } /** A private property to ensure we only notify the observers once that the operation has finished. */ fileprivate var hasFinishedAlready = false public final func finish(_ errors: [NSError] = []) { stateAccess.lock() defer { stateAccess.unlock() } guard !hasFinishedAlready else { return } hasFinishedAlready = true state = .finishing _internalErrors += errors let finishedBlock = { self.finished(self._internalErrors) } if userInitiated { DispatchQueue.main.async(execute: finishedBlock) } else { finishedBlock() } for observer in observers { observer.operationDidFinish(self, errors: _internalErrors) } state = .finished } /** Subclasses may override `finished(_:)` if they wish to react to the operation finishing with errors. For example, the `LoadModelOperation` implements this method to potentially inform the user about an error when trying to bring up the Core Data stack. */ open func finished(_ errors: [NSError]) { } // override open func waitUntilFinished() { // /* // Waiting on operations is almost NEVER the right thing to do. It is // usually superior to use proper locking constructs, such as `dispatch_semaphore_t` // or `dispatch_group_notify`, or even `NSLocking` objects. Many developers // use waiting when they should instead be chaining discrete operations // together using dependencies. // // To reinforce this idea, invoking `waitUntilFinished()` will crash your // app, as incentive for you to find a more appropriate way to express // the behavior you're wishing to create. // */ // fatalError("Waiting on operations is an anti-pattern.") // } }
b36595bcdb1243bc3f8a3b3b168fb5e2
32.599476
168
0.594468
false
false
false
false
uasys/swift
refs/heads/master
stdlib/public/core/Character.swift
apache-2.0
1
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// /// A single extended grapheme cluster that approximates a user-perceived /// character. /// /// The `Character` type represents a character made up of one or more Unicode /// scalar values, grouped by a Unicode boundary algorithm. Generally, a /// `Character` instance matches what the reader of a string will perceive as /// a single character. Strings are collections of `Character` instances, so /// the number of visible characters is generally the most natural way to /// count the length of a string. /// /// let greeting = "Hello! 🐥" /// print("Length: \(greeting.count)") /// // Prints "Length: 8" /// /// Because each character in a string can be made up of one or more Unicode /// scalar values, the number of characters in a string may not match the /// length of the Unicode scalar value representation or the length of the /// string in a particular binary representation. /// /// print("Unicode scalar value count: \(greeting.unicodeScalars.count)") /// // Prints "Unicode scalar value count: 15" /// /// print("UTF-8 representation count: \(greeting.utf8.count)") /// // Prints "UTF-8 representation count: 18" /// /// Every `Character` instance is composed of one or more Unicode scalar values /// that are grouped together as an *extended grapheme cluster*. The way these /// scalar values are grouped is defined by a canonical, localized, or /// otherwise tailored Unicode segmentation algorithm. /// /// For example, a country's Unicode flag character is made up of two regional /// indicator scalar values that correspond to that country's ISO 3166-1 /// alpha-2 code. The alpha-2 code for The United States is "US", so its flag /// character is made up of the Unicode scalar values `"\u{1F1FA}"` (REGIONAL /// INDICATOR SYMBOL LETTER U) and `"\u{1F1F8}"` (REGIONAL INDICATOR SYMBOL /// LETTER S). When placed next to each other in a string literal, these two /// scalar values are combined into a single grapheme cluster, represented by /// a `Character` instance in Swift. /// /// let usFlag: Character = "\u{1F1FA}\u{1F1F8}" /// print(usFlag) /// // Prints "🇺🇸" /// /// For more information about the Unicode terms used in this discussion, see /// the [Unicode.org glossary][glossary]. In particular, this discussion /// mentions [extended grapheme clusters][clusters] and [Unicode scalar /// values][scalars]. /// /// [glossary]: http://www.unicode.org/glossary/ /// [clusters]: http://www.unicode.org/glossary/#extended_grapheme_cluster /// [scalars]: http://www.unicode.org/glossary/#unicode_scalar_value @_fixed_layout public struct Character : _ExpressibleByBuiltinUTF16ExtendedGraphemeClusterLiteral, ExpressibleByExtendedGraphemeClusterLiteral, Hashable { // Fundamentally, it is just a String, but it is optimized for the common case // where the UTF-16 representation fits in 63 bits. The remaining bit is used // to discriminate between small and large representations. Since a grapheme // cluster cannot have U+0000 anywhere but in its first scalar, we can store // zero in empty code units above the first one. @_versioned internal enum Representation { case smallUTF16(Builtin.Int63) case large(_StringBuffer._Storage) } /// Creates a character containing the given Unicode scalar value. /// /// - Parameter content: The Unicode scalar value to convert into a character. public init(_ content: Unicode.Scalar) { let content16 = UTF16.encode(content)._unsafelyUnwrappedUnchecked _representation = .smallUTF16( Builtin.zext_Int32_Int63(content16._storage._value)) } @effects(readonly) public init(_builtinUnicodeScalarLiteral value: Builtin.Int32) { self = Character( String._fromWellFormedCodeUnitSequence( UTF32.self, input: CollectionOfOne(UInt32(value)))) } // Inlining ensures that the whole constructor can be folded away to a single // integer constant in case of small character literals. @inline(__always) @effects(readonly) public init( _builtinExtendedGraphemeClusterLiteral start: Builtin.RawPointer, utf8CodeUnitCount: Builtin.Word, isASCII: Builtin.Int1 ) { let utf8 = UnsafeBufferPointer( start: UnsafePointer<Unicode.UTF8.CodeUnit>(start), count: Int(utf8CodeUnitCount)) if utf8.count == 1 { _representation = .smallUTF16( Builtin.zext_Int8_Int63(utf8.first._unsafelyUnwrappedUnchecked._value)) return } FastPath: repeat { var shift = 0 let maxShift = 64 - 16 var bits: UInt64 = 0 for s8 in Unicode._ParsingIterator( codeUnits: utf8.makeIterator(), parser: UTF8.ForwardParser()) { let s16 = UTF16.transcode(s8, from: UTF8.self)._unsafelyUnwrappedUnchecked for u16 in s16 { guard _fastPath(shift <= maxShift) else { break FastPath } bits |= UInt64(u16) &<< shift shift += 16 } } guard _fastPath(Int64(truncatingIfNeeded: bits) >= 0) else { break FastPath } _representation = .smallUTF16(Builtin.trunc_Int64_Int63(bits._value)) return } while false // For anything that doesn't fit in 63 bits, build the large // representation. self = Character(_largeRepresentationString: String( _builtinExtendedGraphemeClusterLiteral: start, utf8CodeUnitCount: utf8CodeUnitCount, isASCII: isASCII)) } // Inlining ensures that the whole constructor can be folded away to a single // integer constant in case of small character literals. @inline(__always) @effects(readonly) public init( _builtinExtendedGraphemeClusterLiteral start: Builtin.RawPointer, utf16CodeUnitCount: Builtin.Word ) { let utf16 = UnsafeBufferPointer( start: UnsafePointer<Unicode.UTF16.CodeUnit>(start), count: Int(utf16CodeUnitCount)) switch utf16.count { case 1: _representation = .smallUTF16(Builtin.zext_Int16_Int63(utf16[0]._value)) case 2: let bits = UInt32(utf16[0]) | UInt32(utf16[1]) &<< 16 _representation = .smallUTF16(Builtin.zext_Int32_Int63(bits._value)) case 3: let bits = UInt64(utf16[0]) | UInt64(utf16[1]) &<< 16 | UInt64(utf16[2]) &<< 32 _representation = .smallUTF16(Builtin.trunc_Int64_Int63(bits._value)) case 4 where utf16[3] < 0x8000: let bits = UInt64(utf16[0]) | UInt64(utf16[1]) &<< 16 | UInt64(utf16[2]) &<< 32 | UInt64(utf16[3]) &<< 48 _representation = .smallUTF16(Builtin.trunc_Int64_Int63(bits._value)) default: _representation = Character( _largeRepresentationString: String( _StringCore( baseAddress: UnsafeMutableRawPointer(start), count: utf16.count, elementShift: 1, hasCocoaBuffer: false, owner: nil) ))._representation } } /// Creates a character with the specified value. /// /// Do not call this initalizer directly. It is used by the compiler when /// you use a string literal to initialize a `Character` instance. For /// example: /// /// let oBreve: Character = "o\u{306}" /// print(oBreve) /// // Prints "ŏ" /// /// The assignment to the `oBreve` constant calls this initializer behind the /// scenes. public init(extendedGraphemeClusterLiteral value: Character) { self = value } /// Creates a character from a single-character string. /// /// The following example creates a new character from the uppercase version /// of a string that only holds one character. /// /// let a = "a" /// let capitalA = Character(a.uppercased()) /// /// - Parameter s: The single-character string to convert to a `Character` /// instance. `s` must contain exactly one extended grapheme cluster. public init(_ s: String) { _precondition( s._core.count != 0, "Can't form a Character from an empty String") _debugPrecondition( s.index(after: s.startIndex) == s.endIndex, "Can't form a Character from a String containing more than one extended grapheme cluster") if _fastPath(s._core.count <= 4) { let b = _UIntBuffer<UInt64, Unicode.UTF16.CodeUnit>(s._core) if _fastPath(Int64(truncatingIfNeeded: b._storage) >= 0) { _representation = .smallUTF16( Builtin.trunc_Int64_Int63(b._storage._value)) return } } self = Character(_largeRepresentationString: s) } /// Creates a Character from a String that is already known to require the /// large representation. /// /// - Note: `s` should contain only a single grapheme, but we can't require /// that formally because of grapheme cluster literals and the shifting /// sands of Unicode. https://bugs.swift.org/browse/SR-4955 @_versioned internal init(_largeRepresentationString s: String) { if let native = s._core.nativeBuffer, native.start == s._core._baseAddress!, native.usedCount == s._core.count { _representation = .large(native._storage) return } var nativeString = "" nativeString.append(s) _representation = .large(nativeString._core.nativeBuffer!._storage) } static func _smallValue(_ value: Builtin.Int63) -> UInt64 { return UInt64(Builtin.zext_Int63_Int64(value)) } /// The character's hash value. /// /// Hash values are not guaranteed to be equal across different executions of /// your program. Do not save hash values to use during a future execution. public var hashValue: Int { // FIXME(performance): constructing a temporary string is extremely // wasteful and inefficient. return String(self).hashValue } typealias UTF16View = String.UTF16View var utf16: UTF16View { return String(self).utf16 } @_versioned internal var _representation: Representation } extension Character : CustomStringConvertible { public var description: String { return String(describing: self) } } extension Character : LosslessStringConvertible {} extension Character : CustomDebugStringConvertible { /// A textual representation of the character, suitable for debugging. public var debugDescription: String { return String(self).debugDescription } } extension Character { @_versioned internal var _smallUTF16 : _UIntBuffer<UInt64, Unicode.UTF16.CodeUnit>? { guard case .smallUTF16(let _63bits) = _representation else { return nil } _onFastPath() let bits = UInt64(Builtin.zext_Int63_Int64(_63bits)) let minBitWidth = type(of: bits).bitWidth - bits.leadingZeroBitCount return _UIntBuffer<UInt64, Unicode.UTF16.CodeUnit>( _storage: bits, _bitCount: UInt8( truncatingIfNeeded: 16 * Swift.max(1, (minBitWidth + 15) / 16)) ) } @_versioned internal var _largeUTF16 : _StringCore? { guard case .large(let storage) = _representation else { return nil } return _StringCore(_StringBuffer(storage)) } } extension String { /// Creates a string containing the given character. /// /// - Parameter c: The character to convert to a string. public init(_ c: Character) { if let utf16 = c._smallUTF16 { self = String(decoding: utf16, as: Unicode.UTF16.self) } else { self = String(c._largeUTF16!) } } } /// `.small` characters are stored in an Int63 with their UTF-8 representation, /// with any unused bytes set to 0xFF. ASCII characters will have all bytes set /// to 0xFF except for the lowest byte, which will store the ASCII value. Since /// 0x7FFFFFFFFFFFFF80 or greater is an invalid UTF-8 sequence, we know if a /// value is ASCII by checking if it is greater than or equal to /// 0x7FFFFFFFFFFFFF00. internal var _minASCIICharReprBuiltin: Builtin.Int63 { @inline(__always) get { let x: Int64 = 0x7FFFFFFFFFFFFF00 return Builtin.truncOrBitCast_Int64_Int63(x._value) } } extension Character : Equatable { @_inlineable @inline(__always) public static func == (lhs: Character, rhs: Character) -> Bool { let l0 = lhs._smallUTF16 if _fastPath(l0 != nil), let l = l0?._storage { let r0 = rhs._smallUTF16 if _fastPath(r0 != nil), let r = r0?._storage { if (l | r) < 0x300 { return l == r } if l == r { return true } } } // FIXME(performance): constructing two temporary strings is extremely // wasteful and inefficient. return String(lhs) == String(rhs) } } extension Character : Comparable { @_inlineable @inline(__always) public static func < (lhs: Character, rhs: Character) -> Bool { let l0 = lhs._smallUTF16 if _fastPath(l0 != nil), let l = l0?._storage { let r0 = rhs._smallUTF16 if _fastPath(r0 != nil), let r = r0?._storage { if (l | r) < 0x80 { return l < r } if l == r { return false } } } // FIXME(performance): constructing two temporary strings is extremely // wasteful and inefficient. return String(lhs) < String(rhs) } }
fef9e79dcb59bbeec2d695f334b0e365
34.976064
96
0.665927
false
false
false
false
jcfausto/transit-app
refs/heads/master
TransitApp/TransitApp/DateFormatterHelper.swift
mit
1
// // DateFormatter.swift // TransitApp // // Created by Julio Cesar Fausto on 25/02/16. // Copyright © 2016 Julio Cesar Fausto. All rights reserved. // import Foundation class DateFormatter { static let sharedInstance = DateFormatter() let formatterForJsonConversion: NSDateFormatter init() { self.formatterForJsonConversion = NSDateFormatter() self.formatterForJsonConversion.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ" self.formatterForJsonConversion.timeZone = NSTimeZone(forSecondsFromGMT: 0) self.formatterForJsonConversion.locale = NSLocale(localeIdentifier: "en_US_POSIX") } }
f11fdeb28f561bb371b61124b404ef79
25.32
90
0.707763
false
false
false
false
yunlzheng/practice-space
refs/heads/master
swift/helloApp/helloApp/helloApp/AppDelegate.swift
mit
1
// // AppDelegate.swift // helloApp // // Created by apple on 15/7/3. // Copyright (c) 2015年 moo. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> 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 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:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var applicationDocumentsDirectory: NSURL = { // The directory the application uses to store the Core Data store file. This code uses a directory named "moo.helloApp" in the application's documents Application Support directory. let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls[urls.count-1] as NSURL }() lazy var managedObjectModel: NSManagedObjectModel = { // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model. let modelURL = NSBundle.mainBundle().URLForResource("helloApp", withExtension: "momd")! return NSManagedObjectModel(contentsOfURL: modelURL)! }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = { // The persistent store coordinator for the application. This implementation creates and return a coordinator, having added 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. // Create the coordinator and store var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("helloApp.sqlite") var error: NSError? = nil var failureReason = "There was an error creating or loading the application's saved data." if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil, error: &error) == nil { coordinator = nil // Report any error we got. let dict = NSMutableDictionary() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" dict[NSLocalizedFailureReasonErrorKey] = failureReason dict[NSUnderlyingErrorKey] = error error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) // Replace this with code to handle the error appropriately. // abort() 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. NSLog("Unresolved error \(error), \(error!.userInfo)") abort() } return coordinator }() lazy var managedObjectContext: NSManagedObjectContext? = { // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. let coordinator = self.persistentStoreCoordinator if coordinator == nil { return nil } var managedObjectContext = NSManagedObjectContext() managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // MARK: - Core Data Saving support func saveContext () { if let moc = self.managedObjectContext { var error: NSError? = nil if moc.hasChanges && !moc.save(&error) { // Replace this implementation with code to handle the error appropriately. // abort() 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. NSLog("Unresolved error \(error), \(error!.userInfo)") abort() } } } }
4a516771fb4955cfe7b08ae89e6da619
53.945946
290
0.715527
false
false
false
false
julianshen/SwSelect
refs/heads/master
SwSelectTests/SwSelectTests.swift
mit
1
// // SwSelectTests.swift // SwSelectTests // // Created by Julian Shen on 2015/10/5. // Copyright © 2015年 cowbay.wtf. All rights reserved. // import XCTest @testable import SwSelect struct SelectorTest { let html:String let selector:String let expected:[String] } class SwSelectTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testParseIdentifier() { let identifierTests:[String:String] = ["x":"x", "90":"", "-x":"-x", "r\\e9sumé":"résumé", "a\\\"b":"a\"b"] for (src, want) in identifierTests { var p = Parser(src: src, pos:0) do { let got = try p.parseIdentifier() print("parsing " + src) assert(want == got, "Wrong identifier: \"" + got + "\" expected \"" + want + "\"") } catch { if want != "" { assertionFailure("Error parsing identifier") } } } } func testParseString() { let stringTests:[String:String] = ["\"x\"":"x", "'x'":"x", "'x":"", "'x\\\r\nx'":"xx", "\"r\\e9sumé\"":"résumé", "\"a\\\"b\"":"a\"b"] for (src, want) in stringTests{ var p = Parser(src: src, pos:0) do { let got = try p.parseString() let a = "'x\\\r\nx'" for s in a.characters { if s=="\r" { print("got you") } } assert(want != "" && got != "", "Expected error but got \"" + got + "\"") assert(want == got, "Wrong string: \"" + got + "\" expected \"" + want + "\"") assert(p.pos == p.src.length, "Something has been left behind") } catch { if want != "" { assertionFailure("Error parsing string: " + src + ":" + want) } } } } func testSelector() { let selTests:[SelectorTest] = [ SelectorTest(html:"<body><address>This address...</address></body>", selector:"address", expected:["<address>"]), SelectorTest(html:"<html><head></head><body></body></html>", selector:"*", expected:["<html>","<head>","<body>"]), SelectorTest(html:"<p id=\"foo\"><p id=\"bar\">", selector:"#foo", expected:["<p id=\"foo\">"]), SelectorTest(html:"<ul><li id=\"t1\"><p id=\"t1\">", selector:"li#t1", expected:["<li id=\"t1\">"]), SelectorTest(html:"<ol><li id=\"t4\"><li id=\"t44\">", selector:"*#t4", expected:["<li id=\"t4\">"]), SelectorTest(html:"<ul><li class=\"t1\"><li class=\"t2\">", selector:".t1", expected:["<li class=\"t1\">"]), SelectorTest(html:"<p class=\"t1 t2\">", selector:"p.t1", expected:["<p class=\"t1 t2\">"]), SelectorTest(html:"<div class=\"test\">", selector:"div.teST", expected:[]), SelectorTest(html:"<p class=\"t1 t2\">", selector:".t1.fail", expected:[]), SelectorTest(html:"<p class=\"t1 t2\">", selector:"p.t1.t2", expected:["<p class=\"t1 t2\">"]), SelectorTest(html:"<p><p title=\"title\">", selector:"p[title]", expected:["<p title=\"title\">"]), SelectorTest(html:"<address><address title=\"foo\"><address title=\"bar\">", selector:"address[title=\"foo\"]", expected:["<address title=\"foo\">"]), SelectorTest(html:"<p title=\"tot foo bar\">", selector:"[ title ~= foo ]", expected:["<p title=\"tot foo bar\">"]), SelectorTest(html:"<p title=\"hello world\">", selector:"[title~=\"hello world\"]", expected:[]), SelectorTest(html:"<p lang=\"en\"><p lang=\"en-gb\"><p lang=\"enough\"><p lang=\"fr-en\">", selector:"[lang|=\"en\"]", expected:["<p lang=\"en\">", "<p lang=\"en-gb\">"]), SelectorTest(html:"<p title=\"foobar\"><p title=\"barfoo\">", selector:"[title^=\"foo\"]", expected:["<p title=\"foobar\">"]), SelectorTest(html:"<p title=\"foobar\"><p title=\"barfoo\">", selector:"[title$=\"bar\"]", expected:["<p title=\"foobar\">"]), SelectorTest(html:"<p title=\"foobarufoo\">", selector:"[title*=\"bar\"]", expected:["<p title=\"foobarufoo\">"]), SelectorTest(html:"<p class=\"t1 t2\">", selector:".t1:not(.t2)", expected:[]), SelectorTest(html:"<div class=\"t3\">", selector:"div:not(.t1)", expected:["<div class=\"t3\">"]), SelectorTest(html:"<ol><li id=1><li id=2><li id=3></ol>", selector:"li:nth-child(odd)", expected:["<li id=\"1\">", "<li id=\"3\">"]), SelectorTest(html:"<ol><li id=1><li id=2><li id=3></ol>", selector:"li:nth-child(even)", expected:["<li id=\"2\">"]), SelectorTest(html:"<ol><li id=1><li id=2><li id=3></ol>", selector:"li:nth-child(-n+2)", expected:["<li id=\"1\">", "<li id=\"2\">"]), SelectorTest(html:"<ol><li id=1><li id=2><li id=3></ol>", selector:"li:nth-child(3n+1)", expected:["<li id=\"1\">"]), SelectorTest(html:"<ol><li id=1><li id=2><li id=3><li id=4></ol>", selector:"li:nth-last-child(odd)", expected:["<li id=\"2\">","<li id=\"4\">"]), SelectorTest(html:"<ol><li id=1><li id=2><li id=3><li id=4></ol>", selector:"li:nth-last-child(even)", expected:["<li id=\"1\">","<li id=\"3\">"]), SelectorTest(html:"<ol><li id=1><li id=2><li id=3><li id=4></ol>", selector:"li:nth-last-child(-n+2)", expected:["<li id=\"3\">","<li id=\"4\">"]), SelectorTest(html:"<ol><li id=1><li id=2><li id=3><li id=4></ol>", selector:"li:nth-last-child(3n+1)", expected:["<li id=\"1\">","<li id=\"4\">"]), SelectorTest(html:"<p>some text <span id=\"1\">and a span</span><span id=\"2\"> and another</span></p>", selector:"span:first-child", expected:["<span id=\"1\">"]), SelectorTest(html:"<span>a span</span> and some text", selector:"span:last-child", expected:["<span>"]), SelectorTest(html:"<address></address><p id=1><p id=2>", selector:"p:nth-of-type(2)", expected:["<p id=\"2\">"]), SelectorTest(html:"<address></address><p id=1><p id=2>", selector:"p:nth-last-of-type(2)", expected:["<p id=\"1\">"]), SelectorTest(html:"<address></address><p id=1><p id=2>", selector:"p:last-of-type", expected:["<p id=\"2\">"]), SelectorTest(html:"<address></address><p id=1><p id=2>", selector:"p:first-of-type", expected:["<p id=\"1\">"]), SelectorTest(html:"<div><p id=\"1\"></p><a></a></div><div><p id=\"2\"></p></div>", selector:"p:only-child", expected:["<p id=\"2\">"]), SelectorTest(html:"<div><p id=\"1\"></p><a></a></div><div><p id=\"2\"></p><p id=\"3\"></p></div>", selector:"p:only-of-type", expected:["<p id=\"1\">"]), SelectorTest(html:"<p id=\"1\"><!-- --><p id=\"2\">Hello<p id=\"3\"><span>", selector:":empty", expected:["<p id=\"1\">", "<span>"]), SelectorTest(html:"<div><p id=\"1\"><table><tr><td><p id=\"2\"></table></div><p id=\"3\">", selector:"div p", expected:["<p id=\"1\">", "<p id=\"2\">"]), SelectorTest(html:"<div><p id=\"1\"><table><tr><td><p id=\"2\"></table></div><p id=\"3\">", selector:"div table p", expected:["<p id=\"2\">"]), SelectorTest(html:"<div><p id=\"1\"><div><p id=\"2\"></div><table><tr><td><p id=\"3\"></table></div>", selector:"div > p", expected:["<p id=\"1\">", "<p id=\"2\">"]), SelectorTest(html:"<p id=\"1\"><p id=\"2\"></p><address></address><p id=\"3\">", selector:"p ~ p", expected:["<p id=\"2\">", "<p id=\"3\">"]), SelectorTest(html:"<p id=\"1\"></p>\n<!--comment-->\n <p id=\"2\"></p><address></address><p id=\"3\">", selector:"p + p", expected:["<p id=\"2\">"]), SelectorTest(html:"<ul><li></li><li></li></ul><p>", selector:"li, p", expected:["<li>", "<li>", "<p>"]), SelectorTest(html:"<p id=\"1\"><p id=\"2\"></p><address></address><p id=\"3\">", selector:"p +/*This is a comment*/ p", expected:["<p id=\"2\">"]), SelectorTest(html:"<p>Text block that <span>wraps inner text</span> and continues</p>", selector:"p:contains(\"that wraps\")", expected:["<p>"]), SelectorTest(html:"<p>Text block that <span>wraps inner text</span> and continues</p>", selector:"p:containsOwn(\"that wraps\")", expected:[]), SelectorTest(html:"<p>Text block that <span>wraps inner text</span> and continues</p>", selector:":containsOwn(\"inner\")", expected:["<span>"]), SelectorTest(html:"<p>Text block that <span>wraps inner text</span> and continues</p>", selector:"p:containsOwn(\"block\")", expected:["<p>"]), SelectorTest(html:"<div id=\"d1\"><p id=\"p1\"><span>text content</span></p></div><div id=\"d2\"/>", selector:"div:has(#p1)", expected:["<div id=\"d1\">"]), SelectorTest(html:"<div id=\"d1\"><p id=\"p1\"><span>contents 1</span></p></div>\n<div id=\"d2\"><p>contents <em>2</em></p></div>", selector:"div:has(:containsOwn(\"2\"))", expected:["<div id=\"d2\">"]), SelectorTest(html:"<p id=\"p1\">0123456789</p><p id=\"p2\">abcdef</p><p id=\"p3\">0123ABCD</p>", selector:"p:matches([\\d])", expected:["<p id=\"p1\">", "<p id=\"p3\">"]), SelectorTest(html:"<p id=\"p1\">0123456789</p><p id=\"p2\">abcdef</p><p id=\"p3\">0123ABCD</p>", selector:"p:matches([a-z])", expected:["<p id=\"p2\">"]), SelectorTest(html:"<p id=\"p1\">0123456789</p><p id=\"p2\">abcdef</p><p id=\"p3\">0123ABCD</p>", selector:"p:matches([a-zA-Z])", expected:["<p id=\"p2\">", "<p id=\"p3\">"]), SelectorTest(html:"<p id=\"p1\">0123456789</p><p id=\"p2\">abcdef</p><p id=\"p3\">0123ABCD</p>", selector:"p:matches([^\\d])", expected:["<p id=\"p2\">", "<p id=\"p3\">"]), SelectorTest(html:"<p id=\"p1\">0123456789</p><p id=\"p2\">abcdef</p><p id=\"p3\">0123ABCD</p>", selector:"p:matches(^(0|a))", expected:["<p id=\"p1\">", "<p id=\"p2\">", "<p id=\"p3\">"]), SelectorTest(html:"<p id=\"p1\">0123456789</p><p id=\"p2\">abcdef</p><p id=\"p3\">0123ABCD</p>", selector:"p:matches(^\\d+$)", expected:["<p id=\"p1\">"]), SelectorTest(html:"<p id=\"p1\">0123456789</p><p id=\"p2\">abcdef</p><p id=\"p3\">0123ABCD</p>", selector:"p:not(:matches(^\\d+$))", expected:["<p id=\"p2\">", "<p id=\"p3\">"]), SelectorTest(html:"<ul>\n" + "<li><a id=\"a1\" href=\"http://www.google.com/finance\"/>\n" + "<li><a id=\"a2\" href=\"http://finance.yahoo.com/\"/>\n" + "<li><a id=\"a2\" href=\"http://finance.untrusted.com/\"/>\n" + "<li><a id=\"a3\" href=\"https://www.google.com/news\"/>\n" + "<li><a id=\"a4\" href=\"http://news.yahoo.com\"/>\n" + "</ul>", selector:"[href#=(fina)]:not([href#=(\\/\\/[^\\/]+untrusted)])", expected:["<a id=\"a1\" href=\"http://www.google.com/finance\">", "<a id=\"a2\" href=\"http://finance.yahoo.com/\">"]), SelectorTest(html:"<form>\n" + "<label>Username <input type=\"text\" name=\"username\" /></label>\n" + "<label>Password <input type=\"password\" name=\"password\" /></label>\n" + "<label>Country\n" + "<select name=\"country\">\n" + "<option value=\"ca\">Canada</option>\n" + "<option value=\"us\">United States</option>\n" + "</select>\n" + "</label>" + "<label>Bio <textarea name=\"bio\"></textarea></label>" + "<button>Sign up</button>" + "</form>", selector:":input", expected:["<input type=\"text\" name=\"username\">", "<input type=\"password\" name=\"password\">", "<select name=\"country\">", "<textarea name=\"bio\">", "<button>"]), SelectorTest(html:"<ul>\n" + "<li><a id=\"a1\" href=\"http://www.google.com/finance\"/>\n" + "<li><a id=\"a2\" href=\"http://finance.yahoo.com/\"/>\n" + "<li><a id=\"a3\" href=\"https://www.google.com/news\"/>\n" + "<li><a id=\"a4\" href=\"http://news.yahoo.com\"/>\n" + "</ul>", selector:"[href#=(^https:\\/\\/[^\\/]*\\/?news)]", expected:["<a id=\"a3\" href=\"https://www.google.com/news\">"]) ] for test in selTests { do { let $ = try SwSelect(test.html) let nodes = $(test.selector) assert(nodes.count == test.expected.count, "Wrong result count " + String(nodes.count) + " should be " + String(test.expected.count) + ":" + test.html + " selector:" + test.selector) var c = 0 for n in nodes { if(String(n).containedIn(test.expected)) { c++ } } assert(nodes.count == c, "Wrong result count") } catch { assertionFailure("Error testing selector: " + test.selector) } } } func testFind() { let html:String = "<ul class=\"level-1\">" + "<li class=\"item-i\">I</li>" + "<li class=\"item-ii\">II" + "<ul class=\"level-2\">" + "<li class=\"item-a\">A</li>" + "<li class=\"item-b\">B" + "<ul class=\"level-3\">" + "<li class=\"item-1\">1</li>" + "<li class=\"item-2\">2</li>" + "<li class=\"item-3\">3</li>" + "</ul>" + "</li>" + "<li class=\"item-c\">C</li>" + "</ul>" + "</li>" + "<li class=\"item-iii\">III</li>" + "</ul>" do { let $ = try SwSelect(html) let nodes = $( "li.item-ii" ).find( "li" ) assert(nodes.count == 6, "Testing find: Wrong count - " + String(nodes.count)) } catch { assertionFailure("Error testing find") } } func testAttr() { let html:String = "<ul class=\"level-1\"><li>Test</li></ul>" do { let $ = try SwSelect(html) let nodes = $( "ul" ) let n = nodes.first! if let a = n.attr("class") { assert(a == "level-1", "Wrong attribute: " + a) } let lis = nodes.find("li") let l = lis.first! if let _ = l.attr("class") { assert(false, "Attr class should not be existed") } } catch { assertionFailure("Error testing find") } } func testAttrs() { let html:String = "<ul class=\"level-1\"><li class=\"l2\">Test2</li><li class=\"l1\">Test</li><li>aaa</li></ul>" do { let $ = try SwSelect(html) let nodes = $( "li" ) let aVals = nodes.attrs("class") assert(aVals.count == 2, "Wrong attrs got") for v in aVals { print(v) } } catch { assertionFailure("Error testing find") } } func testText() { let html:String = "<ul class=\"level-1\"><li class=\"l2\">Test2</li><li class=\"l1\">Test</li><li class=\"l1\">aaa</li></ul>" do { let $ = try SwSelect(html) var nodes = $( "ul" ) assert(nodes.first!.text == "Test2Testaaa") nodes = $(".l1") assert(nodes.text == "Testaaa") } catch { assertionFailure("Error testing find") } } }
f0e299ff75695696324b36f57bf08a0b
59.692015
215
0.480829
false
true
false
false
norwoood/swiftBook
refs/heads/master
函数式swift/optiontype.playground/Contents.swift
mit
1
//: Playground - noun: a place where people can play import UIKit //swift可选值表示一个值得缺失,或者计算失败 let dictionary = ["beijing": 30000000, "chongqing": 40000000, "hebei": 100000000] //可选绑定 don't force unwrapping if let cq = dictionary["chongqing"] { print("cq population is \(cq)") }else{ print("undefine key of chongqing") } //let cqqq = dictionary["hebei"] ?? 11111 infix operator ???? func ???? <T>(_ option: T? , defaultVAlue: @autoclosure ()throws -> T)rethrows -> T { if let x = option { return x }else{ return try defaultVAlue() } } //可选链 struct Order { let orderNumber: Int let person: Person? } struct Person{ let name: String let address: Address? } struct Address{ let state: String? let city: String let streetName: String } let order1 = Order(orderNumber: 1, person: nil) order1.person?.address?.state // 任何一个可选值的返回nil都会终止可选链 //分支上的可选值 switch语句 guard 语句,当可选值为空的时候,需要提前退出就用这个guard语句 //与可选绑定一起处理没有值得情况 // 可选映射 func add(_ optionX: Int?, _ optionY: Int?) -> Int? { if let x = optionX , let y = optionY { return x + y } return nil } func addg(_ optionX: Int?, _ optionY: Int?) -> Int? { guard let x = optionX, let y = optionY else { return nil } return x + y } extension Optional { func flatMap<U>(_ transfrom: (Wrapped) -> U?) -> U? { guard let x = self else { return nil } return transfrom(x) } } func addf1(_ optionX: Int?, _ optionY: Int?) -> Int? { return optionX.flatMap{ x in optionY.flatMap{ y in return x + y } } } //为什么使用可选型 //增强了代码的静态安全性 //提供了更加丰富的函数签名,代码即文档的感觉 //类型系统的安全性的补充
e599c797ee6497ce5660fcbf14307dc9
11.585526
85
0.537376
false
false
false
false
PJayRushton/stats
refs/heads/master
Stats/AtBatCreationViewController.swift
mit
1
// // AtBatCreationViewController.swift // Stats // // Created by Parker Rushton on 4/20/17. // Copyright © 2017 AppsByPJ. All rights reserved. // import UIKit import AIFlatSwitch import BetterSegmentedControl import Firebase import Presentr import Whisper class AtBatCreationViewController: Component, AutoStoryboardInitializable { // MARK: - IBOutlets @IBOutlet weak var previousPlayerLabel: UILabel! @IBOutlet weak var currentPlayerLabel: UILabel! @IBOutlet weak var nextPlayerLabel: UILabel! @IBOutlet weak var singleButton: AtBatButton! @IBOutlet weak var doubleButton: AtBatButton! @IBOutlet weak var tripleButton: AtBatButton! @IBOutlet weak var hrButton: AtBatButton! @IBOutlet weak var fieldersChoiceButton: AtBatButton! @IBOutlet weak var sacButton: AtBatButton! @IBOutlet weak var inTheParkView: UIView! @IBOutlet weak var inTheParkSwitch: AIFlatSwitch! @IBOutlet weak var walkButton: AtBatButton! @IBOutlet weak var roeButton: AtBatButton! @IBOutlet weak var strikeOutButton: AtBatButton! @IBOutlet weak var outButton: AtBatButton! @IBOutlet weak var rbisSegControl: BetterSegmentedControl! @IBOutlet weak var outsStack: UIStackView! @IBOutlet var outButtons: [UIButton]! @IBOutlet weak var deleteButton: UIButton! @IBOutlet weak var cancelButton: UIButton! @IBOutlet weak var saveButton: CustomButton! @IBOutlet weak var saveNextButton: CustomButton! // MARK: - Public Properties var editingAtBat: AtBat? var showOpponentScoreEdit: () -> Void = { } // MARK: - Internal Properties fileprivate var currentGame: Game? { return core.state.gameState.currentGame } fileprivate var allResultButtons: [AtBatButton] { return [singleButton, doubleButton, tripleButton, hrButton, walkButton, roeButton, strikeOutButton, outButton, fieldersChoiceButton, sacButton] } fileprivate var rbis = 0 fileprivate var currentPlayer: Player? { return core.state.gameState.currentPlayer } fileprivate var newAtBatRef: DatabaseReference { return StatsRefs.atBatsRef(teamId: core.state.teamState.currentTeam!.id).childByAutoId() } fileprivate var currentAtBatResult = AtBatCode.single { didSet { updateUI(with: currentAtBatResult) } } fileprivate var saveIsEnabled = true { didSet { saveButton.isEnabled = saveIsEnabled saveNextButton.isEnabled = saveIsEnabled } } fileprivate var isShowingITPSwitch = false { didSet { guard isShowingITPSwitch != oldValue else { return } toggleITPView(isHidden: !isShowingITPSwitch) } } fileprivate var isLastOut: Bool { guard let game = currentGame else { return false } return game.outs == 3 || (game.outs == 2 && currentAtBatResult.isOut) } // MARK: - ViewController Lifecycle override func viewDidLoad() { super.viewDidLoad() toggleITPView(isHidden: true, animated: false) setUpButtons() setUpRBISegControl() let isEditing = editingAtBat != nil deleteButton.isHidden = !isEditing saveNextButton.isHidden = isEditing currentAtBatResult = .single if let editingAtBat = editingAtBat { update(with: editingAtBat) } } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) core.fire(event: Selected<AtBatCode>(.single)) } // MARK: - IBActions @IBAction func resultButtonPressed(_ sender: AtBatButton) { let code = inTheParkSwitch.isSelected && sender.code == .hr ? .hrITP : sender.code core.fire(event: Selected<AtBatCode>(code)) } @IBAction func itpChanged(_ sender: AIFlatSwitch) { guard hrButton.isSelected else { return } core.fire(event: Selected<AtBatCode>(sender.isSelected ? .hrITP : .hr)) } @IBAction func rbisChanged(_ sender: BetterSegmentedControl) { rbis = Int(sender.index) } @IBAction func outButtonPressed(_ sender: UIButton) { guard let index = outButtons.index(of: sender), let game = currentGame else { return } if index == game.outs { updateOuts() } else { updateOuts(outs: game.outs - 1) } } @IBAction func deleteButtonPressed(_ sender: UIButton) { showDeleteConfirmation() } @IBAction func saveButtonPressed(_ sender: CustomButton) { saveAtBat(next: false) } @IBAction func saveNextButtonPressed(_ sender: CustomButton) { saveAtBat(next: true) } @IBAction func dismiss(_ sender: Any) { dismiss(animated: false, completion: nil) } override func update(with state: AppState) { currentAtBatResult = state.atBatState.currentResult // Player labels guard let game = state.gameState.currentGame else { return } currentPlayerLabel.text = currentPlayer?.name let lineup = game.lineupIds.compactMap { state.playerState.player(withId: $0) } previousPlayerLabel.text = "" nextPlayerLabel.text = "" if let player = currentPlayer, let index = lineup.index(of: player) { if index > 0, case let previousPlayer = lineup[index - 1] { previousPlayerLabel.text = previousPlayer.name } if index < lineup.count - 1, case let nextPlayer = lineup[index + 1] { nextPlayerLabel.text = nextPlayer.name } } // Outs let outs = game.outs for (index, button) in outButtons.enumerated() { button.isEnabled = index <= outs if index > outs { button.alpha = 0 } else if index == outs { button.alpha = 0.3 } else { button.alpha = 1 } } } } // MARK: - Internal extension AtBatCreationViewController { fileprivate func setUpButtons() { singleButton.code = .single doubleButton.code = .double tripleButton.code = .triple hrButton.code = .hr walkButton.code = .w fieldersChoiceButton.code = .fc sacButton.code = .sac roeButton.code = .roe strikeOutButton.code = .k outButton.code = .out allResultButtons.forEach { button in button.tintColor = UIColor.mainAppColor } } fileprivate func update(with atBat: AtBat) { outsStack.isHidden = true saveNextButton.isHidden = true core.fire(event: Selected<AtBatCode>(atBat.resultCode)) currentAtBatResult = atBat.resultCode isShowingITPSwitch = atBat.resultCode.isHR inTheParkSwitch.isSelected = atBat.resultCode == .hrITP try? rbisSegControl.setIndex(UInt(atBat.rbis)) } fileprivate func updateUI(with code: AtBatCode) { allResultButtons.forEach { button in button.isSelected = button.code == code } hrButton.isSelected = code.isHR isShowingITPSwitch = code.isHR if (code.isHR || code == .sac) && rbisSegControl.index == 0 { try? rbisSegControl.setIndex(1, animated: true) } UIView.animate(withDuration: 0.25) { self.saveNextButton.isHidden = self.isLastOut || self.editingAtBat != nil } } fileprivate func toggleITPView(isHidden: Bool, animated: Bool = true) { if animated { UIView.animate(withDuration: 0.25) { self.inTheParkView.isHidden = isHidden self.inTheParkView.alpha = isHidden ? 0 : 1 } } else { inTheParkView.isHidden = isHidden } } fileprivate func setUpRBISegControl() { let titles = ["0", "1", "2", "3", "4"] rbisSegControl.setUp(with: titles, fontSize: 20) } fileprivate func saveAtBat(next: Bool) { guard let atBat = constructedAtBat() else { return } saveIsEnabled = false let updateCommand = UpdateObject(atBat) { success in self.saveIsEnabled = true guard success else { return } self.handleAtBatSavedSuccessfully(atBat: atBat, next: next) } core.fire(command: updateCommand) } fileprivate func handleAtBatSavedSuccessfully(atBat: AtBat, next: Bool) { updateGameScore(atBat: atBat) if let _ = self.editingAtBat { self.dismiss(animated: true, completion: nil) return } if next { clear() } else { dismiss(animated: true) { [weak self] in guard let weakSelf = self, weakSelf.isLastOut else { return } weakSelf.upInning() weakSelf.showOpponentScoreEdit() } } moveToNextBatter() } fileprivate func upInning() { guard var updatedGame = core.state.gameState.currentGame else { return } updatedGame.inning += 1 updatedGame.outs = 0 core.fire(command: UpdateObject(updatedGame)) } fileprivate func updateOuts(outs: Int? = nil) { guard var game = currentGame else { return } game.outs = outs ?? game.outs + 1 core.fire(command: UpdateObject(game)) } fileprivate func moveToNextBatter() { guard let currentGame = core.state.gameState.currentGame, let player = currentPlayer else { return } var nextPlayerId = currentGame.lineupIds.first if player.id != currentGame.lineupIds.last, let index = currentGame.lineupIds.index(of: player.id) { nextPlayerId = currentGame.lineupIds[index + 1] } guard let nextId = nextPlayerId, let nextPlayer = core.state.playerState.player(withId: nextId) else { return } core.fire(event: Selected<Player>(nextPlayer)) } fileprivate func constructedAtBat() -> AtBat? { if let editingAtBat = editingAtBat { return AtBat(id: editingAtBat.id, creationDate: editingAtBat.creationDate, gameId: editingAtBat.gameId, playerId: editingAtBat.playerId, rbis: rbis, resultCode: currentAtBatResult, seasonId: editingAtBat.seasonId, teamId: editingAtBat.teamId) } else { let id = newAtBatRef.key guard let game = core.state.gameState.currentGame else { return nil } guard let player = currentPlayer else { return nil } guard let team = core.state.teamState.currentTeam else { return nil } guard let seasonId = team.currentSeasonId else { return nil } return AtBat(id: id, gameId: game.id, playerId: player.id, rbis: rbis, resultCode: currentAtBatResult, seasonId: seasonId, teamId: team.id) } } fileprivate func clear() { core.fire(event: Selected<AtBatCode>(.single)) try? rbisSegControl.setIndex(0, animated: true) rbis = 0 } fileprivate func showDeleteConfirmation() { guard let editingAtBat = editingAtBat else { return } let alert = Presentr.alertViewController(title: "Delete this at bat?", body: "This cannot be undone") alert.addAction(AlertAction(title: "Cancel 😳", style: .cancel, handler: nil)) alert.addAction(AlertAction(title: "☠️", style: .destructive) { _ in self.core.fire(command: DeleteObject(editingAtBat)) self.updateGameScore(atBat: editingAtBat, delete: true) self.dismiss(animated: true, completion: { self.dismiss(animated: true, completion: nil) }) }) customPresentViewController(alertPresenter, viewController: alert, animated: true, completion: nil) } fileprivate func updateGameScore(atBat: AtBat, delete: Bool = false) { guard var currentGame = core.state.gameState.currentGame else { return } if let editingAtBat = editingAtBat { if delete { currentGame.score -= atBat.rbis } else { currentGame.score += atBat.rbis - editingAtBat.rbis } } else { currentGame.score = delete ? currentGame.score - atBat.rbis : currentGame.score + atBat.rbis } //Catch all currentGame.score = max(currentGame.score, 0) let updateCommand = UpdateObject(currentGame) { success in guard success && atBat.resultCode.isOut && !delete else { return } self.updateOuts() } core.fire(command: updateCommand) } }
f5e1d239c22403cec95d58382a95ce2c
34.243836
254
0.619092
false
false
false
false
azimin/Rainbow
refs/heads/master
Rainbow/ColorsOnImageGenerateContextViewController.swift
mit
1
// // ColorsOnImageGenerateContextViewController.swift // Rainbow // // Created by Alex Zimin on 10/04/16. // Copyright © 2016 Alex Zimin. All rights reserved. // import UIKit struct ColorsOnImageGenerateSettings { var numberOfColors: Int var comressionType: Int } protocol ColorsOnImageGenerateDelegate { func colorsOnImageGenerateWithSelectedSettings(setting: ColorsOnImageGenerateSettings) } class ColorsOnImageGenerateContextViewController: UIViewController { @IBOutlet weak var containerView: UIView! weak var remindViewController: ColorsOnImageGenerateTableViewController? var delegate: ColorsOnImageGenerateDelegate? { didSet { remindViewController?.delegate = delegate } } override func viewDidLoad() { super.viewDidLoad() containerView.layer.cornerRadius = 8 containerView.layer.masksToBounds = true // Do any additional setup after loading the view. } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { remindViewController = segue.destinationViewController as? ColorsOnImageGenerateTableViewController remindViewController?.delegate = delegate } }
a8a128f1f2460b789c40b5b1d4aab57f
25.681818
103
0.770869
false
false
false
false
drewby/FriesOrNot
refs/heads/master
end/FriesOrNot/ViewController.swift
apache-2.0
1
// // ViewController.swift // FriesOrNot // // Created by Drew Robbins on 2017/07/30. // Copyright © 2017 Drew Robbins. All rights reserved. // import UIKit class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate { @IBOutlet weak var photoImageView: UIImageView! @IBOutlet weak var resultLabel: UILabel! @IBOutlet weak var activityIndicator: UIActivityIndicatorView! var service = CustomVisionService() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. resultLabel.text = "" } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func selectImage(_ sender: UITapGestureRecognizer) { let imagePickerController = UIImagePickerController() imagePickerController.sourceType = .photoLibrary imagePickerController.delegate = self present(imagePickerController, animated: true, completion: nil) } func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { dismiss(animated: true, completion: nil) } func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { guard let selectedImage = info[UIImagePickerControllerOriginalImage] as? UIImage else { fatalError("Expected an image, but was provided \(info)") } photoImageView.image = selectedImage dismiss(animated: true, completion: nil) resultLabel.text = "" self.activityIndicator.startAnimating() let imageData = UIImageJPEGRepresentation(selectedImage, 0.8)! service.predict(image: imageData, completion: { (result: CustomVisionResult?, error: Error?) in DispatchQueue.main.async { self.activityIndicator.stopAnimating() if let error = error { self.resultLabel.text = error.localizedDescription } else if let result = result { let prediction = result.Predictions[0] let probabilityLabel = String(format: "%.1f", prediction.Probability * 100) self.resultLabel.text = "\(probabilityLabel)% sure this is \(prediction.Tag)" } } }) } }
9e4800a4ed27c547d7e2daaaf89427e9
34.191781
119
0.635656
false
false
false
false
gaintext/gaintext-engine
refs/heads/master
Sources/Blocks/TitledContent.swift
gpl-3.0
1
// // GainText parser // Copyright Martin Waitz // // 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. // import Engine import Runes func detectSectionStart(underlineChars: String = "=-~_+'\"") -> Parser<Character> { return Parser { input in var cursor = input guard !cursor.atEndOfBlock else { throw ParserError.notFound(position: input.position) } guard !cursor.atWhitespaceOnlyLine else { throw ParserError.notFound(position: input.position) } try! cursor.advanceLine() guard !cursor.atEndOfBlock else { throw ParserError.notFound(position: input.position) } // check that second line only contains the underline let c = cursor.char guard underlineChars.characters.contains(c) else { throw ParserError.notFound(position: input.position) } var count = 1 try! cursor.advance() while !cursor.atEndOfLine { if cursor.char == c { count += 1 } else if !cursor.atWhitespace { throw ParserError.notFound(position: input.position) } try! cursor.advance() } guard count >= 3 else { throw ParserError.notFound(position: input.position) } try! cursor.advanceLine() if !cursor.atEndOfBlock { guard cursor.atWhitespaceOnlyLine else { throw ParserError.notFound(position: input.position) } try! cursor.advanceLine() } return (c, cursor) } } /// Parser which creates the element instance. /// /// If available, it consumes the element specification (up to the colon) /// and creates a corresponding element. /// Otherwise, it creates a default 'section' element. private let namedElementOrSection = elementStartBlockParser <|> elementCreateBlockParser(name: "section") /// Parser which produces a list of lines which belong to the content. private func contentLines(level: Character) -> Parser<[Line]> { let nextSection = detectSectionStart(underlineChars: String(level)) return Parser { input in var cursor = input var lines: [Line] = [] while !cursor.atEndOfBlock { do { _ = try nextSection.parse(cursor) break } catch is ParserError {} lines.append(cursor.line) try! cursor.advanceLine() } return (lines, cursor) } } /// Parses all lines up to the start of the next section as one block. private func content(underline: Character) -> Parser<()> { return ( emptyLine *> skipEmptyLines *> contentLines(level: underline) >>- elementBodyBlock ) } /// Parser for a section of titled content. /// /// Matches the title line which has to be followed by underline characters. /// All following lines up to another such title line are parsed as content. public let titledContent = lookahead(detectSectionStart()) >>- { underline in element( namedElementOrSection *> elementTitleLine *> endOfLine *> advanceLine *> // line with underline characters elementNodeAttribute("underline", value: String(underline)) *> (skipEmptyLines *> endOfBlock <|> content(underline: underline)) ) }
2b262018ad9a953d935b9f453dec2141
34.222222
104
0.64296
false
false
false
false
Esri/arcgis-runtime-samples-ios
refs/heads/main
arcgis-ios-sdk-samples/Layers/Blend renderer/BlendRendererViewController.swift
apache-2.0
1
// // Copyright 2016 Esri. // // 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 import ArcGIS class BlendRendererViewController: UIViewController, BlendRendererSettingsViewControllerDelegate { @IBOutlet var mapView: AGSMapView! let imageryBasemapLayer: AGSRasterLayer = { let raster = AGSRaster(name: "Shasta", extension: "tif") return AGSRasterLayer(raster: raster) }() let elevationBasemapLayer: AGSRasterLayer = { let raster = AGSRaster(name: "Shasta_Elevation", extension: "tif") return AGSRasterLayer(raster: raster) }() override func viewDidLoad() { super.viewDidLoad() // add the source code button item to the right of navigation bar (navigationItem.rightBarButtonItem as! SourceCodeBarButtonItem).filenames = ["BlendRendererViewController", "BlendRendererSettingsViewController", "OptionsTableViewController"] // initialize map let map = AGSMap() // assign map to the map view mapView.map = map // set the initial blend renderer setBlendRenderer(altitude: 0, azimuth: 0, slopeType: .none, colorRampType: .none) } /// The color ramp type that was used to create the currently applied blend renderer. private var displayedColorRampType: AGSPresetColorRampType = .none // MARK: - BlendRendererSettingsViewControllerDelegate func blendRendererSettingsViewController(_ blendRendererSettingsViewController: BlendRendererSettingsViewController, selectedAltitude altitude: Double, azimuth: Double, slopeType: AGSSlopeType, colorRampType: AGSPresetColorRampType) { setBlendRenderer(altitude: altitude, azimuth: azimuth, slopeType: slopeType, colorRampType: colorRampType) } private func setBlendRenderer(altitude: Double, azimuth: Double, slopeType: AGSSlopeType, colorRampType: AGSPresetColorRampType) { displayedColorRampType = colorRampType // create a colorRamp object from the type specified let colorRamp = colorRampType != .none ? AGSColorRamp(type: colorRampType, size: 800) : nil // the raster to use for blending let elevationRaster = AGSRaster(name: "Shasta_Elevation", extension: "tif") // create a blend renderer let blendRenderer = AGSBlendRenderer( elevationRaster: elevationRaster, outputMinValues: [9], outputMaxValues: [255], sourceMinValues: [], sourceMaxValues: [], noDataValues: [], gammas: [], colorRamp: colorRamp, altitude: altitude, azimuth: azimuth, zFactor: 1, slopeType: slopeType, pixelSizeFactor: 1, pixelSizePower: 1, outputBitDepth: 8) // remove the exisiting layers mapView.map?.basemap.baseLayers.removeAllObjects() // if the colorRamp type is .none, then use the imagery for blending. // else use the elevation let rasterLayer = colorRampType == .none ? imageryBasemapLayer : elevationBasemapLayer // apply the blend renderer on this new raster layer rasterLayer.renderer = blendRenderer // add the raster layer to the basemap mapView.map?.basemap.baseLayers.add(rasterLayer) } // MARK: - Navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let navController = segue.destination as? UINavigationController, let controller = navController.viewControllers.first as? BlendRendererSettingsViewController, let rasterLayer = mapView.map?.basemap.baseLayers.firstObject as? AGSRasterLayer, let renderer = rasterLayer.renderer as? AGSBlendRenderer { controller.preferredContentSize = CGSize(width: 375, height: 180) navController.presentationController?.delegate = self controller.delegate = self controller.altitude = renderer.altitude controller.azimuth = renderer.azimuth controller.slopeType = renderer.slopeType controller.colorRampType = displayedColorRampType } } } extension BlendRendererViewController: UIAdaptivePresentationControllerDelegate { func adaptivePresentationStyle(for controller: UIPresentationController, traitCollection: UITraitCollection) -> UIModalPresentationStyle { return .none } }
490fc58ec5d079107baa5557d9b232b1
41.686441
238
0.682748
false
false
false
false
RedRoma/Lexis-Database
refs/heads/develop
LexisDatabase/LexisWord+WordType.swift
apache-2.0
1
// // LexisWord+WordType.swift // LexisDatabase // // Created by Wellington Moreno on 9/17/16. // Copyright © 2016 RedRoma, Inc. All rights reserved. // import AlchemySwift import Archeota import Foundation public enum Conjugation: String, CaseIterable { case First case Second case Third case Fourth case Irregular case Unconjugated public static let all = allCases public var name: String { return self.rawValue } public static func from(name: String) -> Conjugation? { if let conjugation = Conjugation(rawValue: name) { return conjugation } else { LOG.warn("Failed to find Conjugation with name: \(name)") return nil } } private static let shortCodes: [String: Conjugation] = [ "1st" : .First, "2nd" : .Second, "3rd" : .Third, "4th" : .Fourth ] static func fromShortCode(code: String) -> Conjugation { return shortCodes[code] ?? .Irregular } } public enum VerbType: String, CaseIterable { case Transitive case Intransitive case Impersonal case Deponent case SemiDeponent case PerfectDefinite case Unknown public static let all = allCases public var name: String { return self.rawValue } public static func from(name: String) -> VerbType? { if let verbType = VerbType(rawValue: name) { return verbType } else { LOG.warn("Failed to decode Verb Type from name: \(name)") return nil } } } public enum Gender: String, CaseIterable { case Male case Female case Neuter case Unknown public static let all = allCases public var name: String { return self.rawValue } public static func from(name: String) -> Gender? { if let gender = Gender(rawValue: name) { return gender } else { LOG.warn("Failed to decode Gender from name: \(name)") return nil } } } public enum Declension: String, CaseIterable { case First case Second case Third case Fourth case Fifth case Undeclined public static let all = allCases public var name: String { return self.rawValue } public static func from(name: String) -> Declension? { if let declension = Declension(rawValue: name) { return declension } else { LOG.warn("Failed to decode Declension from: \(name)") return nil } } private static let shortCodes: [String: Declension] = [ "1st" : .First, "2nd" : .Second, "3rd" : .Third, "4th" : .Fourth, "5th" : .Fifth ] static func fromShortCode(code: String) -> Declension { return shortCodes[code] ?? .Undeclined } private static let shortForms: [Declension: String] = [ .First: "1st", .Second: "2nd", .Third: "3rd", .Fourth: "4th", .Fifth: "5th" ] public var shortForm: String { return Declension.shortForms[self] ?? "Uknwn" } } /** `CaseType` represents the case of a Noun or an Adjective. */ public enum CaseType: String, CaseIterable { case Nominative case Genitive case Accusative case Dative case Ablative case Vocative case Locative case Unknown static let all = allCases public var name: String { self.rawValue } public static func from(name: String) -> CaseType? { if let caseType = CaseType(rawValue: name) { return caseType } else { LOG.warn("Failed to decode case from: \(name)") return nil } } static func from(shortCode: String) -> CaseType { codes[shortCode] ?? .Unknown } private static let codes: [String: CaseType] = [ "NOM": .Nominative, "GEN": .Genitive, "ACC": .Accusative, "DAT": .Dative, "ABL": .Ablative, "VOC": .Vocative, "LOC": .Locative ] } public enum PronounType: String, CaseIterable { case Reflexive case Personal public static let all = allCases public var name: String { self.rawValue } public static func from(name: String) -> PronounType? { if let pronounType = PronounType(rawValue: name) { return pronounType } else { LOG.warn("Failed to decode PronounType from name: \(name)") return nil } } } public enum WordType: Equatable { case Adjective case Adverb case Conjunction case Interjection case Noun(Declension, Gender) case Numeral case PersonalPronoun case Preposition(CaseType) case Pronoun case Verb(Conjugation, VerbType) private static let serializer = BasicJSONSerializer.instance public var description: String { self.asJSONString(serializer: WordType.serializer) ?? "" } public var asData: Data? { guard let jsonString = self.asJSONString(serializer: WordType.serializer) else { return nil } return jsonString.data(using: .utf8) } public static func from(data: Data) -> WordType? { guard let jsonObject = try? JSONSerialization.jsonObject(with: data, options: []), let dictionary = jsonObject as? NSDictionary else { LOG.warn("Failed to deserialize object from JSON") return nil } return WordType.fromJSON(json: dictionary) as? WordType } } public func ==(lhs: WordType, rhs: WordType) -> Bool { switch (lhs, rhs) { case (let .Verb(leftConjugation, leftVerbType), let .Verb(rightConjugation, rightVerbType)) : return leftConjugation == rightConjugation && leftVerbType == rightVerbType case (let .Noun(leftDeclension, leftGender), let .Noun(rightDeclension, rightGender)) : return leftDeclension == rightDeclension && leftGender == rightGender case (let .Preposition(leftCaseType), let .Preposition(rightCaseType)) : return leftCaseType == rightCaseType case (.Adjective, .Adjective) : return true case (.Adverb, .Adverb) : return true case (.Conjunction, .Conjunction) : return true case (.Interjection, .Interjection) : return true case (.Numeral, .Numeral) : return true case (.PersonalPronoun, .PersonalPronoun) : return true case (.Pronoun, .Pronoun) : return true default: return false } } extension WordType: Hashable { public func hash(into hasher: inout Hasher) { let string: String if case let .Verb(conjugation, verbType) = self { string = "Verb-\(conjugation)-\(verbType)" } else if case let .Noun(declension, gender) = self { string = "Noun-\(declension)-\(gender)" } else if case let .Preposition(caseType) = self { string = "Preposition-\(caseType)" } else { string = String(describing: self) } hasher.combine(string) } }
35b273f2659326721b0cedc09a91e104
21.646707
101
0.56597
false
false
false
false
esheppard/travel-lingo
refs/heads/master
xcode/Travel Lingo/Source/Utils/AudioUtils.swift
gpl-3.0
1
// // AudioUtils.swift // Travel Lingo // // Created by Elijah Sheppard on 22/04/2016. // Copyright © 2016 Elijah Sheppard. All rights reserved. // import AudioToolbox func loadAudio(file: String) -> SystemSoundID? { guard let resourcePath = resourcePathForFile(file) else { return nil } if !fileExistsAtPath(resourcePath) { return nil } let resourceUrl = NSURL(fileURLWithPath: resourcePath) var soundId: SystemSoundID = 0 if AudioServicesCreateSystemSoundID(resourceUrl, &soundId) == 0 { return soundId } return nil }
e188e936a5db467c18b79347699b39fa
19.896552
69
0.655116
false
false
false
false
ffittschen/hackaTUM
refs/heads/master
MachtSpass/Features/QRScannerTab/QRScannerTabViewCoordinator.swift
mit
1
// // QRScannerTabViewCoordinator.swift // MachtSpass // // Created by Peter Christian Glade on 12.11.16. // Copyright © 2016 BaconLove. All rights reserved. // import Foundation import UIKit import RxSwift import BarcodeScanner import CleanroomLogger import RxMoya import Moya import Freddy class QRScannerTabViewCoordinator: NSObject, TabCoordinator { let tabBarItem: UITabBarItem let navigationController: UINavigationController var viewModel: ScanResultsViewModel fileprivate let disposeBag: DisposeBag fileprivate let viewController: ScanResultsViewController fileprivate let barcodeScannerController: BarcodeScannerController fileprivate let backendProvider: RxMoyaProvider<BackendService> // This closure adds `application/json` as header and transmits the data in a way known as `raw` in other tools, e.g. Postman let endpointClosure = { (target: BackendService) -> Endpoint<BackendService> in let url = target.baseURL.appendingPathComponent(target.path).absoluteString let endpoint: Endpoint<BackendService> = Endpoint<BackendService>(URL: url, sampleResponseClosure: {.networkResponse(200, target.sampleData)}, method: target.method, parameters: target.parameters, parameterEncoding: JSONEncoding.default ) return endpoint.adding(newHttpHeaderFields: ["Content-Type": "application/json"]) } override init() { disposeBag = DisposeBag() // Set tabBarItem attributes tabBarItem = UITabBarItem(title: "Scan", image: #imageLiteral(resourceName: "ScanTabIcon"), selectedImage: nil) // Init BarcodeScanner BarcodeScanner.Info.text = NSLocalizedString( "Halte die Kamera über den QR-Code. Die Produktsuche startet automatisch.", comment: "") barcodeScannerController = BarcodeScannerController() barcodeScannerController.edgesForExtendedLayout = [] // Init viewModel & navigation stack viewModel = ScanResultsViewModel() viewController = ScanResultsViewController(viewModel: viewModel) navigationController = UINavigationController(rootViewController: viewController) navigationController.tabBarItem = tabBarItem navigationController.navigationBar.barTintColor = .white // Set title image of navigationBar let titleImageView = UIImageView(frame: CGRect(x: 0, y: 0, width: navigationController.navigationBar.bounds.width - 16, height: navigationController.navigationBar.bounds.height - 8)) titleImageView.image = #imageLiteral(resourceName: "Media Markt") titleImageView.contentMode = .scaleAspectFit viewController.navigationItem.titleView = titleImageView // Init moya Backend Provider backendProvider = RxMoyaProvider<BackendService>(endpointClosure: endpointClosure) super.init() // Set the delegates viewController.delegate = self barcodeScannerController.codeDelegate = self barcodeScannerController.errorDelegate = self barcodeScannerController.dismissalDelegate = self } func start() { // The barcodeScanner uses the camera, therefore we need to mock the value to avoid simulator crashes if UIDevice.isSimulator { viewModel.qrContent.value = "1234567" } else { showBarcodeScanner() } let pushID = UserDefaults.standard.string(forKey: "PushDeviceToken") ?? "" let userID = UserDefaults.standard.string(forKey: "UserID") ?? "" // As soon as we successfully scanned a product, we want to get product information from the backend viewModel.productID.asObservable() .subscribe(onNext: { (productID: String) in self.backendProvider.request(.product(id: productID, pushID: pushID, userID: userID), completion: { result in switch result { case .success(let response): let json = try! JSON(data: response.data) let userID = try! json.getString(at: "Userid") if UserDefaults.standard.string(forKey: "UserID") == nil { UserDefaults.standard.set(userID, forKey: "UserID") } self.viewModel.updateProduct(with: json) case .failure(let error): Log.error?.message("Error while getting product information: \(error)") } }) }) .addDisposableTo(disposeBag) } fileprivate func registerForPush() { guard let pushToken = UserDefaults.standard.string(forKey: "PushDeviceToken") else { fatalError("No push device token found.") } if let userID = UserDefaults.standard.string(forKey: "UserID") { backendProvider.request(.getProfile(id: userID)) { result in switch result { case .success(let response): guard let json = try? JSON(data: response.data) else { print("Unable to parse JSON Response") return } guard let token = try? json.getString(at: "pushid") else { print("Unable to find 'pushid' in: \(json)") return } if pushToken != token { self.backendProvider.request(.updateProfile(id: try! json.getString(at: "id"), name: try! json.getString(at: "name"), avatar: try! json.getString(at: "avatar"), pushID: token, notificationActive: try! json.getBool(at: "notificationactive"))) } case.failure(let error): print("Erro while get user: \(error)") } } } else { backendProvider.request(.postProfile(name: UIDevice.current.identifierForVendor!.uuidString, avatar: "", pushID: pushToken, notificationActive: true)) { result in switch result { case .success(let response): guard let json = try? JSON(data: response.data) else { print("Unable to parse JSON Response") return } guard let userID = try? json.getString(at: "id") else { print("Unable to find user id in: \(json)") return } UserDefaults.standard.setValue(userID, forKey: "UserID") case .failure(let error): print("Erro while post user: \(error)") } } } } private func showBarcodeScanner() { barcodeScannerController.navigationItem.setHidesBackButton(true, animated: false) barcodeScannerController.title = "Scan" navigationController.pushViewController(barcodeScannerController, animated: true) } } extension QRScannerTabViewCoordinator: BarcodeScannerCodeDelegate { func barcodeScanner(_ controller: BarcodeScannerController, didCaptureCode code: String, type: String) { Log.debug?.message("Received Barcode: \(code)") viewModel.qrContent.value = code // The normal `.reset()` seems to be buggy / not working, so we use `.resetWithError()` barcodeScannerController.resetWithError() navigationController.popViewController(animated: true) } } extension QRScannerTabViewCoordinator: BarcodeScannerErrorDelegate { func barcodeScanner(_ controller: BarcodeScannerController, didReceiveError error: Swift.Error) { Log.error?.message("Error while scanning a barcode:") Log.error?.value(error) } } extension QRScannerTabViewCoordinator: BarcodeScannerDismissalDelegate { func barcodeScannerDidDismiss(_ controller: BarcodeScannerController) { navigationController.popViewController(animated: true) } } extension QRScannerTabViewCoordinator: ScanResultsViewControllerDelegate { func registerForRemotePush() { registerForPush() } /// Reset the tab and start scanning for QR codes again func didPressScanQRCodeButton() { start() } /// When the MachtSpassButton is being pressed, we send the question to the backend in order to trigger the push notifications func didPressMachtSpassButton() { let userID = UserDefaults.standard.string(forKey: "UserID") ?? "" viewModel.productID .subscribe(onNext: { productID in self.backendProvider.request(.postQuestion(userID: userID, productID: productID)) { result in switch result { case .success(let response): Log.debug?.message("Posted question. Response: \(response.debugDescription)") if let json = try? JSON(data: response.data) { Log.debug?.message("\(json.description)") } case .failure(let error): Log.error?.message("Error while pressing machtSpassButton: \(error)") } } }) .addDisposableTo(disposeBag) } }
cff8535e6bc029ce0253ff5ef6ab1cc2
42.898678
246
0.587757
false
false
false
false
ConradoMateu/Swift-Basics
refs/heads/master
Basic/If:Else&Switch.playground/Contents.swift
apache-2.0
1
//: Playground - noun: a place where people can play import UIKit // If Statements var age = 13 // Greater than or equal to if age >= 18 { print("You can play!") } else { print("Sorry, you're too young") } // Equal to var name = "Kirsten" if name == "Rob" { print("Hi " + name + " you can play!") } else { print("Sorry, " + name + " you can't play") } // 2 If statements with AND if name == "Kirsten" && age >= 18 { print("You can play!") } // 2 If statements with OR if name == "Kirsten" || name == "Rob" { print("Welcome " + name) } var isMale = true if isMale { print("You are a man!") } // Challenge var username = "robpercival" var password = "myPass" if username == "robpercival" && password == "myPass123" { print("You're In!") } else if username != "robpercival" && password != "myPass123" { print("Both your username and password are wrong") } else if username == "robpercival" { print("Your password is wrong") } else { print("Your username is wrong") } //If Let to check if the optional value is not null var optionalName: String? = "John Appleseed" var greeting = "Hello!" if let name = optionalName { greeting = "Hello, \(name)" } var optionalHello: String? = "Hello" if let hello = optionalHello where hello.hasPrefix("H"), let name = optionalName { greeting = "\(hello), \(name)" } // Switch example let vegetable = "red pepper" switch vegetable { case "celery": let vegetableComment = "Add some raisins and make ants on a log." case "cucumber", "watercress": let vegetableComment = "That would make a good tea sandwich." case let x where x.hasSuffix("pepper"): let vegetableComment = "Is it a spicy \(x)?" default: let vegetableComment = "Everything tastes good in soup." }
5bb736e851675fe99be872b106c5c2d0
14.528455
82
0.597906
false
false
false
false
overtake/TelegramSwift
refs/heads/master
Telegram-Mac/InstantPageSlideshowItem.swift
gpl-2.0
1
// // InstantPageSlideshowItem.swift // Telegram // // Created by keepcoder on 17/08/2017. // Copyright © 2017 Telegram. All rights reserved. // import Cocoa import TelegramCore import TGUIKit class InstantPageSlideshowItem: InstantPageItem { var frame: CGRect let medias: [InstantPageMedia] let wantsView: Bool = true let hasLinks: Bool = false let isInteractive: Bool = true let separatesTiles: Bool = false let webPage: TelegramMediaWebpage init(frame: CGRect, webPage: TelegramMediaWebpage, medias: [InstantPageMedia]) { self.frame = frame self.webPage = webPage self.medias = medias } func drawInTile(context: CGContext) { } func matchesAnchor(_ anchor: String) -> Bool { return false } func matchesView(_ node: InstantPageView) -> Bool { if let view = node as? InstantPageSlideshowView { return self.medias == view.medias } return false } func view(arguments: InstantPageItemArguments, currentExpandedDetails: [Int : Bool]?) -> (InstantPageView & NSView)? { return InstantPageSlideshowView(frameRect: frame, medias: medias, context: arguments.context) } func linkSelectionViews() -> [InstantPageLinkSelectionView] { return [] } func distanceThresholdGroup() -> Int? { return 1 } func distanceThresholdWithGroupCount(_ count: Int) -> CGFloat { return 1000 } } class InstantPageSlideshowView : View, InstantPageView { fileprivate let medias: [InstantPageMedia] private let slideView: SliderView init(frameRect: NSRect, medias: [InstantPageMedia], context: AccountContext) { self.medias = medias slideView = SliderView(frame: NSMakeRect(0, 0, frameRect.width, frameRect.height)) super.init(frame: frameRect) addSubview(slideView) for media in medias { var arguments: InstantPageMediaArguments = .image(interactive: true, roundCorners: false, fit: false) if let media = media.media as? TelegramMediaFile { if media.isVideo { arguments = .video(interactive: true, autoplay: media.isAnimated) } } let view = InstantPageMediaView(context: context, media: media, arguments: arguments) slideView.addSlide(view) } } override func layout() { super.layout() slideView.center() } var indexOfDisplayedSlide: Int { return Int(slideView.indexOfDisplayedSlide) } override func copy() -> Any { return slideView.displayedSlide?.copy() ?? super.copy() } func updateIsVisible(_ isVisible: Bool) { } required init(frame frameRect: NSRect) { fatalError("init(frame:) has not been implemented") } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
96f51055c2c5e7c7d2929b0ac05eb7bc
26.348214
122
0.620307
false
false
false
false
Ivacker/swift
refs/heads/master
test/attr/attr_availability_watchos.swift
apache-2.0
13
// RUN: %swift -parse -verify -parse-stdlib -target i386-apple-watchos2.0 %s @available(watchOS, introduced=1.0, deprecated=1.5, obsoleted=2.0, message="you don't want to do that anyway") func doSomething() { } // expected-note @-1{{'doSomething()' was obsoleted in watchOS 2.0}} doSomething() // expected-error{{'doSomething()' is unavailable: you don't want to do that anyway}} // Preservation of major.minor.micro @available(watchOS, introduced=1.0, deprecated=1.5, obsoleted=1.5.3) func doSomethingElse() { } // expected-note @-1{{'doSomethingElse()' was obsoleted in watchOS 1.5.3}} doSomethingElse() // expected-error{{'doSomethingElse()' is unavailable}} // Preservation of minor-only version @available(watchOS, introduced=1.0, deprecated=1.5, obsoleted=2) func doSomethingReallyOld() { } // expected-note @-1{{'doSomethingReallyOld()' was obsoleted in watchOS 2}} doSomethingReallyOld() // expected-error{{'doSomethingReallyOld()' is unavailable}} // Test deprecations in 2.0 and later @available(watchOS, introduced=1.1, deprecated=2.0, message="Use another function") func deprecatedFunctionWithMessage() { } deprecatedFunctionWithMessage() // expected-warning{{'deprecatedFunctionWithMessage()' was deprecated in watchOS 2.0: Use another function}} @available(watchOS, introduced=1.0, deprecated=2.0) func deprecatedFunctionWithoutMessage() { } deprecatedFunctionWithoutMessage() // expected-warning{{'deprecatedFunctionWithoutMessage()' was deprecated in watchOS 2.0}} @available(watchOS, introduced=1.0, deprecated=2.0, message="Use BetterClass instead") class DeprecatedClass { } func functionWithDeprecatedParameter(p: DeprecatedClass) { } // expected-warning{{'DeprecatedClass' was deprecated in watchOS 2.0: Use BetterClass instead}} @available(watchOS, introduced=2.0, deprecated=4.0, message="Use BetterClass instead") class DeprecatedClassIn3_0 { } // Elements deprecated later than the minimum deployment target (which is 2.0, in this case) should not generate warnings func functionWithDeprecatedLaterParameter(p: DeprecatedClassIn3_0) { } // Treat watchOS as distinct from iOS in availability queries @available(watchOS, introduced=2.2) func functionIntroducedOnwatchOS2_2() { } if #available(iOS 9.3, *) { functionIntroducedOnwatchOS2_2() // expected-error {{'functionIntroducedOnwatchOS2_2()' is only available on watchOS 2.2 or newer}} // expected-note@-1 {{add 'if #available' version check}} } if #available(iOS 9.3, watchOS 2.1, *) { functionIntroducedOnwatchOS2_2() // expected-error {{'functionIntroducedOnwatchOS2_2()' is only available on watchOS 2.2 or newer}} // expected-note@-1 {{add 'if #available' version check}} } if #available(iOS 9.1, watchOS 2.2, *) { functionIntroducedOnwatchOS2_2() } if #available(iOS 8.0, watchOS 2.2, *) { } if #available(iOS 9.2, watchOS 1.0, *) { // expected-warning {{unnecessary check for 'watchOS'; minimum deployment target ensures guard will always be true}} } // Swift-originated iOS availability attributes should not be transcribed to watchOS @available(iOS, unavailable) func swiftOriginatedFunctionUnavailableOnIOS() { } @available(iOS, introduced=6.0, deprecated=9.0) func swiftOriginatedFunctionDeprecatedOnIOS() { } @available(iOS, introduced=10.0) func swiftOriginatedFunctionPotentiallyUnavailableOnIOS() { } func useSwiftOriginatedFunctions() { // We do not expect diagnostics here because iOS availability attributes coming from // Swift should not be transcribed to watchOS. swiftOriginatedFunctionUnavailableOnIOS() swiftOriginatedFunctionDeprecatedOnIOS() swiftOriginatedFunctionPotentiallyUnavailableOnIOS() }
7243e1ba317f0995d56816a42f803ca3
38.5
157
0.74899
false
false
false
false
CharlinFeng/TextField-InputView
refs/heads/master
UITextField+InputView/TextField+InputView/OneCol/OneColTF.swift
mit
1
// // File.swift // TextFieldWithPickerView // // Created by 成林 on 15/8/24. // Copyright (c) 2015年 冯成林. All rights reserved. // import UIKit class OneColTF: InputViewTextField { /** API */ var pickerViewBgColor: UIColor = BgColor{didSet{bgColorSet()}} var message: String!{didSet{msgSet()}} var removeAccessoryView: Bool = false{didSet{removeSet()}} var selectedPickerViewValue: Any! var selectedAction: ((tf: InputViewTextField, row: Int, model: PickerDataModel!)->Void)! var doneBtnActionClosure: ((row: Int,value: Any!)->Void)! /** Inner: orinal */ private var titles: [String]! private lazy var pickerView: UIPickerView = {UIPickerView()}() /** model */ private var models: [PickerDataModel]! /** common */ private var isModelData: Bool = false } extension OneColTF: UIPickerViewDelegate,UIPickerViewDataSource{ /** 添加一个单列的原始值的pickerView */ func addOneColPickerViewWithTitles(titles: [String]){ dataPrepare() isModelData = false //记录 self.titles = titles } /** 单列模型 */ func addOneColPickerViewWithModels(models: [PickerDataModel]!){ dataPrepare() isModelData = true //记录 self.models = models } private func bgColorSet(){pickerView.backgroundColor = pickerViewBgColor} private func msgSet(){accessoryView.msgLabel.text = message} private func removeSet(){if removeAccessoryView {self.inputAccessoryView = nil}} func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int { return 1 } func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return isModelData ? (models?.count ?? 0) : (titles?.count ?? 0) } func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { return isModelData ? models[row].title : titles[row] } func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { if isModelData { if row >= (models?.count ?? 0) {return} }else { if row >= (titles?.count ?? 0) {return} } selectedPickerViewValue = isModelData ? models?[row] : titles?[row] text = isModelData ? models?[row].title : titles?[row] selectedAction?(tf: self, row: row, model: models[row]) } override func noti_textFieldDidBeginEditing(textField: UITextField) { if (models?.count ?? 0) == 0 && isModelData {return} if text == nil || text?.characters.count==0 { pickerView(pickerView, didSelectRow: 0, inComponent: 0) }else { var choosedIndex: Int = 999 if isModelData { //模型数据 for (var i=0; i<models?.count ?? 0; i += 1){ if (models?[i].title ?? "") == (text ?? "") { choosedIndex = i pickerView.selectRow(i, inComponent: 0, animated: true) } } }else { for (var i=0; i<titles?.count ?? 0; i += 1){ if (titles?[i] ?? "") == (text ?? "") { choosedIndex = i pickerView.selectRow(i, inComponent: 0, animated: true) } } } if choosedIndex == 999 { text = isModelData ? models.first?.title : titles.first pickerView(pickerView, didSelectRow: 0, inComponent: 0) } } } override func dataPrepare() { super.dataPrepare() pickerView.dataSource = self pickerView.delegate = self self.inputView = pickerView accessoryView.hideCancelBtn=true accessoryView.doneBtnActionClosure = { [unowned self] in self.endEditing(true) self.doneBtnActionClosure?(row: self.pickerView.selectedRowInComponent(0),value: self.selectedPickerViewValue) } bgColorSet() } }
4c51567ccf1443d5ba4448a9aec8de27
28.453947
122
0.532395
false
false
false
false
suifengqjn/CatLive
refs/heads/master
CatLive/CatLive/Classes/Home/ViewModel/HomeViewModel.swift
apache-2.0
1
// // HomeViewModel.swift // XMGTV // // Created by apple on 16/11/9. // Copyright © 2016年 coderwhy. All rights reserved. // MVVM --> M(model)V(View)C(Controller网络请求/本地存储数据(sqlite)) --> 网络请求 // ViewModel : RAC/RxSwift import UIKit class HomeViewModel { lazy var anchorModels = [AnchorModel]() } extension HomeViewModel { func loadHomeData(type : HomeType, index : Int, finishedCallback : @escaping () -> ()) { NetworkTools.requestData(.get, URLString: "http://qf.56.com/home/v4/moreAnchor.ios", parameters: ["type" : type.type, "index" : index, "size" : 48], finishedCallback: { (result) -> Void in guard let resultDict = result as? [String : Any] else { return } guard let messageDict = resultDict["message"] as? [String : Any] else { return } guard let dataArray = messageDict["anchors"] as? [[String : Any]] else { return } for (index, dict) in dataArray.enumerated() { let anchor = AnchorModel(dict: dict) anchor.isEvenIndex = index % 2 == 0 self.anchorModels.append(anchor) } finishedCallback() }) } }
593c0d3297a43e506f16598374224168
35.454545
196
0.587697
false
false
false
false