repo_name
stringlengths
7
91
path
stringlengths
8
658
copies
stringclasses
125 values
size
stringlengths
3
6
content
stringlengths
118
674k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6.09
99.2
line_max
int64
17
995
alpha_frac
float64
0.3
0.9
ratio
float64
2
9.18
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
dclelland/AudioKit
AudioKit/Common/Nodes/Effects/Filters/Low Pass Butterworth Filter/AKLowPassButterworthFilter.swift
1
3848
// // AKLowPassButterworthFilter.swift // AudioKit // // Created by Aurelius Prochazka, revision history on Github. // Copyright (c) 2016 Aurelius Prochazka. All rights reserved. // import AVFoundation /// These filters are Butterworth second-order IIR filters. They offer an almost /// flat passband and very good precision and stopband attenuation. /// /// - parameter input: Input node to process /// - parameter cutoffFrequency: Cutoff frequency. (in Hertz) /// public class AKLowPassButterworthFilter: AKNode, AKToggleable { // MARK: - Properties internal var internalAU: AKLowPassButterworthFilterAudioUnit? internal var token: AUParameterObserverToken? private var cutoffFrequencyParameter: AUParameter? /// Ramp Time represents the speed at which parameters are allowed to change public var rampTime: Double = AKSettings.rampTime { willSet { if rampTime != newValue { internalAU?.rampTime = newValue internalAU?.setUpParameterRamp() } } } /// Cutoff frequency. (in Hertz) public var cutoffFrequency: Double = 1000 { willSet { if cutoffFrequency != newValue { if internalAU!.isSetUp() { cutoffFrequencyParameter?.setValue(Float(newValue), originator: token!) } else { internalAU?.cutoffFrequency = Float(newValue) } } } } /// Tells whether the node is processing (ie. started, playing, or active) public var isStarted: Bool { return internalAU!.isPlaying() } // MARK: - Initialization /// Initialize this filter node /// /// - parameter input: Input node to process /// - parameter cutoffFrequency: Cutoff frequency. (in Hertz) /// public init( _ input: AKNode, cutoffFrequency: Double = 1000) { self.cutoffFrequency = cutoffFrequency var description = AudioComponentDescription() description.componentType = kAudioUnitType_Effect description.componentSubType = 0x62746c70 /*'btlp'*/ description.componentManufacturer = 0x41754b74 /*'AuKt'*/ description.componentFlags = 0 description.componentFlagsMask = 0 AUAudioUnit.registerSubclass( AKLowPassButterworthFilterAudioUnit.self, asComponentDescription: description, name: "Local AKLowPassButterworthFilter", version: UInt32.max) super.init() AVAudioUnit.instantiateWithComponentDescription(description, options: []) { avAudioUnit, error in guard let avAudioUnitEffect = avAudioUnit else { return } self.avAudioNode = avAudioUnitEffect self.internalAU = avAudioUnitEffect.AUAudioUnit as? AKLowPassButterworthFilterAudioUnit AudioKit.engine.attachNode(self.avAudioNode) input.addConnectionPoint(self) } guard let tree = internalAU?.parameterTree else { return } cutoffFrequencyParameter = tree.valueForKey("cutoffFrequency") as? AUParameter token = tree.tokenByAddingParameterObserver { address, value in dispatch_async(dispatch_get_main_queue()) { if address == self.cutoffFrequencyParameter!.address { self.cutoffFrequency = Double(value) } } } internalAU?.cutoffFrequency = Float(cutoffFrequency) } // MARK: - Control /// Function to start, play, or activate the node, all do the same thing public func start() { self.internalAU!.start() } /// Function to stop or bypass the node, both are equivalent public func stop() { self.internalAU!.stop() } }
mit
63c4e8b1ff65657aa89dd6153c81705f
31.066667
99
0.632796
5.568741
false
false
false
false
justindarc/firefox-ios
Account/SyncAuthState.swift
2
7000
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import Shared import XCGLogger import SwiftyJSON private let CurrentSyncAuthStateCacheVersion = 1 private let log = Logger.syncLogger public struct SyncAuthStateCache { let token: TokenServerToken let forKey: Data let expiresAt: Timestamp } public protocol SyncAuthState { func invalidate() func token(_ now: Timestamp, canBeExpired: Bool) -> Deferred<Maybe<(token: TokenServerToken, forKey: Data)>> var deviceID: String? { get } var enginesEnablements: [String: Bool]? { get set } var clientName: String? { get set } } public func syncAuthStateCachefromJSON(_ json: JSON) -> SyncAuthStateCache? { if let version = json["version"].int { if version != CurrentSyncAuthStateCacheVersion { log.warning("Sync Auth State Cache is wrong version; dropping.") return nil } if let token = TokenServerToken.fromJSON(json["token"]), let forKey = json["forKey"].string?.hexDecodedData, let expiresAt = json["expiresAt"].int64 { return SyncAuthStateCache(token: token, forKey: forKey, expiresAt: Timestamp(expiresAt)) } } return nil } extension SyncAuthStateCache: JSONLiteralConvertible { public func asJSON() -> JSON { return JSON([ "version": CurrentSyncAuthStateCacheVersion, "token": token.asJSON(), "forKey": forKey.hexEncodedString, "expiresAt": NSNumber(value: expiresAt), ] as NSDictionary) } } open class FirefoxAccountSyncAuthState: SyncAuthState { fileprivate let account: FirefoxAccount fileprivate let cache: KeychainCache<SyncAuthStateCache> public var deviceID: String? { return account.deviceRegistration?.id } public var enginesEnablements: [String: Bool]? public var clientName: String? init(account: FirefoxAccount, cache: KeychainCache<SyncAuthStateCache>) { self.account = account self.cache = cache } // If a token gives you a 401, invalidate it and request a new one. open func invalidate() { log.info("Invalidating cached token server token.") self.cache.value = nil } // Generate an assertion and try to fetch a token server token, retrying at most a fixed number // of times. // // It's tricky to get Swift to recurse into a closure that captures from the environment without // segfaulting the compiler, so we pass everything around, like barbarians. fileprivate func generateAssertionAndFetchTokenAt(_ audience: String, client: TokenServerClient, clientState: String?, married: MarriedState, now: Timestamp, retryCount: Int) -> Deferred<Maybe<TokenServerToken>> { let assertion = married.generateAssertionForAudience(audience, now: now) return client.token(assertion, clientState: clientState).bind { result in if retryCount > 0 { if let tokenServerError = result.failureValue as? TokenServerError { switch tokenServerError { case let .remote(code, status, remoteTimestamp) where code == 401 && status == "invalid-timestamp": if let remoteTimestamp = remoteTimestamp { let skew = Int64(remoteTimestamp) - Int64(now) // Without casts, runtime crash due to overflow. log.info("Token server responded with 401/invalid-timestamp: retrying with remote timestamp \(remoteTimestamp), which is local timestamp + skew = \(now) + \(skew).") return self.generateAssertionAndFetchTokenAt(audience, client: client, clientState: clientState, married: married, now: remoteTimestamp, retryCount: retryCount - 1) } default: break } } } // Fall-through. return Deferred(value: result) } } open func token(_ now: Timestamp, canBeExpired: Bool) -> Deferred<Maybe<(token: TokenServerToken, forKey: Data)>> { if let value = cache.value { // Give ourselves some room to do work. let isExpired = value.expiresAt < now + 5 * OneMinuteInMilliseconds if canBeExpired { if isExpired { log.info("Returning cached expired token.") } else { log.info("Returning cached token, which should be valid.") } return deferMaybe((token: value.token, forKey: value.forKey)) } if !isExpired { log.info("Returning cached token, which should be valid.") return deferMaybe((token: value.token, forKey: value.forKey)) } } log.debug("Advancing Account state.") return account.marriedState().bind { result in if let married = result.successValue { log.info("Account is in Married state; generating assertion.") let tokenServerEndpointURL = self.account.configuration.sync15Configuration.tokenServerEndpointURL let audience = TokenServerClient.getAudience(forURL: tokenServerEndpointURL) let client = TokenServerClient(url: tokenServerEndpointURL) let clientState = married.kXCS log.debug("Fetching token server token.") let deferred = self.generateAssertionAndFetchTokenAt(audience, client: client, clientState: clientState, married: married, now: now, retryCount: 1) deferred.upon { result in // This could race to update the cache with multiple token results. // One racer will win -- that's fine, presumably she has the freshest token. // If not, that's okay, 'cuz the slightly dated token is still a valid token. if let token = result.successValue { let newCache = SyncAuthStateCache(token: token, forKey: married.kSync, expiresAt: now + 1000 * token.durationInSeconds) log.debug("Fetched token server token! Token expires at \(newCache.expiresAt).") self.cache.value = newCache } } return chain(deferred, f: { (token: $0, forKey: married.kSync) }) } return deferMaybe(result.failureValue!) } } }
mpl-2.0
d1cc62665ac8c6af3d25a90f32b00fe0
45.052632
193
0.595429
5.422153
false
false
false
false
STShenZhaoliang/iOS-GuidesAndSampleCode
精通Swift设计模式/Chapter 20/Command/Command/Calculator.swift
1
1341
import Foundation; class Calculator { private(set) var total = 0; typealias CommandClosure = (Calculator -> Void); private var history = [CommandClosure](); private var queue = dispatch_queue_create("arrayQ", DISPATCH_QUEUE_SERIAL); func add(amount:Int) { addMacro(Calculator.add, amount: amount); total += amount; } func subtract(amount:Int) { addMacro(Calculator.subtract, amount: amount); total -= amount; } func multiply(amount:Int) { addMacro(Calculator.multiply, amount: amount); total = total * amount; } func divide(amount:Int) { addMacro(Calculator.divide, amount: amount); total = total / amount; } private func addMacro(method:Calculator -> Int -> Void, amount:Int) { dispatch_sync(self.queue, {() in self.history.append({ calc in method(calc)(amount)}); }); } func getMacroCommand() -> (Calculator -> Void) { var commands = [CommandClosure](); dispatch_sync(queue, {() in commands = self.history }); return { calc in if (commands.count > 0) { for index in 0 ..< commands.count { commands[index](calc); } } }; } }
mit
1a020ef4ff500f2e4fd600d6193c7bd7
26.9375
79
0.545116
4.396721
false
false
false
false
optimizely/swift-sdk
Sources/Data Model/Audience/SemanticVersion.swift
1
4941
// // Copyright 2020-2021, Optimizely, Inc. and 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 Foundation typealias SemanticVersion = String /* This comparison is ported from the Optimizely web version of semantic version compare. Full testing in SemanticVersionTests. */ extension SemanticVersion { func compareVersion(targetedVersion: SemanticVersion?) throws -> Int { guard let targetedVersion = targetedVersion else { // Any version. return 0 } let targetedVersionParts = try targetedVersion.splitSemanticVersion() let versionParts = try self.splitSemanticVersion() // Up to the precision of targetedVersion, expect version to match exactly. for idx in targetedVersionParts.indices { if versionParts.count <= idx { // even if they are equal at this point. if the target is a prerelease then it must be greater than the pre release. return targetedVersion.isPreRelease ? 1 : -1 } else if !versionParts[idx].isNumber { // Compare strings if versionParts[idx] < targetedVersionParts[idx] { return targetedVersion.isPreRelease && !self.isPreRelease ? 1 : -1 } else if versionParts[idx] > targetedVersionParts[idx] { return !targetedVersion.isPreRelease && self.isPreRelease ? -1 : 1 } } else if let part = Int(versionParts[idx]), let target = Int(targetedVersionParts[idx]) { if part < target { return -1 } else if part > target { return 1 } } else { return -1 } } if self.isPreRelease && !targetedVersion.isPreRelease { return -1 } return 0 } func splitSemanticVersion() throws -> [Substring] { var targetParts: [Substring]? var targetPrefix = self var targetSuffix: ArraySlice<Substring>? if hasWhiteSpace { throw OptimizelyError.attributeFormatInvalid } if isPreRelease || isBuild { targetParts = split(separator: isPreRelease ? preReleaseSeperator : buildSeperator, maxSplits: 1) guard let targetParts = targetParts, targetParts.count > 1 else { throw OptimizelyError.attributeFormatInvalid } targetPrefix = String(targetParts[0]) targetSuffix = targetParts[1...] } // Expect a version string of the form x.y.z let dotCount = targetPrefix.filter({$0 == "."}).count if dotCount > 2 { throw OptimizelyError.attributeFormatInvalid } var targetedVersionParts = targetPrefix.split(separator: ".") guard targetedVersionParts.count == dotCount + 1 && targetedVersionParts.filter({$0.isNumber}).count == targetedVersionParts.count else { throw OptimizelyError.attributeFormatInvalid } if let targetSuffix = targetSuffix { targetedVersionParts.append(contentsOf: targetSuffix) } return targetedVersionParts } var hasWhiteSpace: Bool { return contains(" ") } var isNumber: Bool { return !isEmpty && rangeOfCharacter(from: CharacterSet.decimalDigits.inverted) == nil } var isPreRelease: Bool { return firstIndex(of: "-")?.utf16Offset(in: self) ?? Int.max < firstIndex(of: "+")?.utf16Offset(in: self) ?? Int.max } var isBuild: Bool { return firstIndex(of: "+")?.utf16Offset(in: self) ?? Int.max < firstIndex(of: "-")?.utf16Offset(in: self) ?? Int.max } var buildSeperator: Character { return "+" } var preReleaseSeperator: Character { return "-" } } extension Substring { var isNumber: Bool { return !isEmpty && rangeOfCharacter(from: CharacterSet.decimalDigits.inverted) == nil } var isPreRelease: Bool { return firstIndex(of: "-")?.utf16Offset(in: self) ?? Int.max < firstIndex(of: "+")?.utf16Offset(in: self) ?? Int.max } var isBuild: Bool { return firstIndex(of: "+")?.utf16Offset(in: self) ?? Int.max < firstIndex(of: "-")?.utf16Offset(in: self) ?? Int.max } }
apache-2.0
7dc8d55a3491485fb5892401906ae265
35.330882
145
0.608176
4.678977
false
false
false
false
slightair/iOSArchitectures
Architectures.playground/Sources/ColorItemCell.swift
1
958
import Foundation import UIKit public class ColorItemCell: UITableViewCell { let colorView = UIView() let nameLabel = UILabel() override public init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) addSubview(colorView) addSubview(nameLabel) colorView.layer.cornerRadius = 3.0 } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } public func update(with colorItem: ColorItem) { colorView.backgroundColor = colorItem.color nameLabel.text = colorItem.name } override public func layoutSubviews() { super.layoutSubviews() colorView.frame = CGRect(x: 8, y: (frame.height - 32) / 2, width: 32, height: 32) nameLabel.frame = CGRect(x: colorView.frame.maxX + 8, y: (frame.height - 21) / 2, width: 200, height: 21) } }
mit
681ccfc20bec46a55af55a842da6d47e
28.9375
113
0.663883
4.394495
false
false
false
false
bigL055/SPKit
Sources/UIControl/UIControl.swift
1
9905
// // SPKit // // Copyright (c) 2017 linhay - https:// github.com/linhay // // 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 import UIKit // MARK: - <#Description#> public extension UIControl { /// 添加响应事件 /// /// - Parameters: /// - event: 响应事件类型 /// - action: 响应事件 public func add(for event: UIControl.Event, action: @escaping () -> ()) { guard let selector = selector(event: event) else { return } let act = ActionBlock(key: event.rawValue, action: action) actionBlocks = actionBlocks.filter { (item) -> Bool in return item.key != act.key } actionBlocks.append(act) self.addTarget(self, action: selector, for: event) } } // MARK: - runtime keys extension UIControl { fileprivate static var once: Bool = false fileprivate class func swizzing() { if once == false { once = true let select1 = #selector(UIControl.sendAction(_:to:for:)) let select2 = #selector(UIControl.sp_sendAction(action:to:forEvent:)) let classType = UIControl.self let select1Method = class_getInstanceMethod(classType, select1) let select2Method = class_getInstanceMethod(classType, select2) let didAddMethod = class_addMethod(classType, select1, method_getImplementation(select2Method!), method_getTypeEncoding(select2Method!)) if didAddMethod { class_replaceMethod(classType, select2, method_getImplementation(select1Method!), method_getTypeEncoding(select1Method!)) }else { method_exchangeImplementations(select1Method!, select2Method!) } } } fileprivate struct ActionKey { static var action = UnsafeRawPointer(bitPattern: "uicontrol_action_block".hashValue) static var time = UnsafeRawPointer(bitPattern: "uicontrol_event_time".hashValue) static var interval = UnsafeRawPointer(bitPattern: "uicontrol_event_interval".hashValue) } } // MARK: - time extension UIControl { /// 系统响应事件 fileprivate var systemActions: [String] { return ["_handleShutterButtonReleased:", "cameraShutterPressed:", "_tappedBottomBarCancelButton:", "_tappedBottomBarDoneButton:", "recordStart:", "btnTouchUp:withEvent:"] } // 重复点击的间隔 public var eventInterval: TimeInterval { get { if let eventInterval = objc_getAssociatedObject(self, UIControl.ActionKey.interval!) as? TimeInterval { return eventInterval } return 0 } set { UIControl.swizzing() objc_setAssociatedObject(self, UIControl.ActionKey.interval!, newValue as TimeInterval, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } /// 上次事件响应时间 fileprivate var lastEventTime: TimeInterval { get { if let eventTime = objc_getAssociatedObject(self, UIControl.ActionKey.time!) as? TimeInterval { return eventTime } return 1.0 } set { UIControl.swizzing() objc_setAssociatedObject(self, UIControl.ActionKey.time!, newValue as TimeInterval, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } @objc fileprivate func sp_sendAction(action: Selector, to target: AnyObject?, forEvent event: UIEvent?) { if systemActions.contains(action.description) || eventInterval <= 0 { self.sp_sendAction(action: action, to: target, forEvent: event) return } let nowTime = Date().timeIntervalSince1970 if nowTime - lastEventTime < eventInterval { return } if eventInterval > 0 { lastEventTime = nowTime } self.sp_sendAction(action: action, to: target, forEvent: event) } } // MARK: - target extension UIControl { fileprivate struct ActionBlock { var key: UInt var action: ()->() } fileprivate var actionBlocks: [ActionBlock] { get { return objc_getAssociatedObject(self,UIControl.ActionKey.action!) as? [ActionBlock] ?? [] } set { objc_setAssociatedObject(self, UIControl.ActionKey.action!, newValue as [ActionBlock], .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } fileprivate func triggerAction(for: UIControl, event: UIControl.Event){ let action = actionBlocks.filter { (item) -> Bool in return item.key == event.rawValue }.first guard let act = action else { return } act.action() } fileprivate func selector(event: UIControl.Event) -> Selector? { var selector: Selector? switch event.rawValue { // Touch events case 1 << 0: selector = #selector(touchDown(sender:)) case 1 << 1: selector = #selector(touchDownRepeat(sender:)) case 1 << 2: selector = #selector(touchDragInside(sender:)) case 2 << 2: selector = #selector(touchDragOutside(sender:)) case 2 << 3: selector = #selector(touchDragEnter(sender:)) case 2 << 4: selector = #selector(touchDragExit(sender:)) case 2 << 5: selector = #selector(touchUpInside(sender:)) case 2 << 6: selector = #selector(touchUpOutside(sender:)) case 2 << 7: selector = #selector(touchCancel(sender:)) // UISlider events case 2 << 11: selector = #selector(valueChanged(sender:)) // TV event case 2 << 12: selector = #selector(primaryActionTriggered(sender:)) // UITextField events case 2 << 15: selector = #selector(editingDidBegin(sender:)) case 2 << 16: selector = #selector(editingChanged(sender:)) case 2 << 17: selector = #selector(editingDidEnd(sender:)) case 2 << 18: selector = #selector(editingDidEndOnExit(sender:)) // Other events case 4095: selector = #selector(allTouchEvents(sender:)) case 983040: selector = #selector(allEditingEvents(sender:)) case 251658240: selector = #selector(applicationReserved(sender:)) case 4026531840: selector = #selector(systemReserved(sender:)) case 4294967295: selector = #selector(allEvents(sender:)) default: selector = nil } return selector } @objc fileprivate func touchDown(sender: UIControl) { triggerAction(for: sender, event: .touchDown) } @objc fileprivate func touchDownRepeat(sender: UIControl) { triggerAction(for:sender, event: .touchDownRepeat) } @objc fileprivate func touchDragInside(sender: UIControl) { triggerAction(for:sender, event: .touchDragInside) } @objc fileprivate func touchDragOutside(sender: UIControl) { triggerAction(for:sender, event: .touchDragOutside) } @objc fileprivate func touchDragEnter(sender: UIControl) { triggerAction(for:sender, event: .touchDragEnter) } @objc fileprivate func touchDragExit(sender: UIControl) { triggerAction(for:sender, event: .touchDragExit) } @objc fileprivate func touchUpInside(sender: UIControl) { triggerAction(for:sender, event: .touchUpInside) } @objc fileprivate func touchUpOutside(sender: UIControl) { triggerAction(for:sender, event: .touchUpOutside) } @objc fileprivate func touchCancel(sender: UIControl) { triggerAction(for:sender, event: .touchCancel) } @objc fileprivate func valueChanged(sender: UIControl) { triggerAction(for:sender, event: .valueChanged) } @objc fileprivate func primaryActionTriggered(sender: UIControl) { if #available(iOS 9.0, *) { triggerAction(for:sender, event: .primaryActionTriggered) } } @objc fileprivate func editingDidBegin(sender: UIControl) { triggerAction(for:sender, event: .editingDidBegin) } @objc fileprivate func editingChanged(sender: UIControl) { triggerAction(for:sender, event: .editingChanged) } @objc fileprivate func editingDidEnd(sender: UIControl) { triggerAction(for:sender, event: .editingDidEnd) } @objc fileprivate func editingDidEndOnExit(sender: UIControl) { triggerAction(for:sender, event: .editingDidEndOnExit) } @objc fileprivate func allTouchEvents(sender: UIControl) { triggerAction(for:sender, event: .allTouchEvents) } @objc fileprivate func allEditingEvents(sender: UIControl) { triggerAction(for:sender, event: .allEditingEvents) } @objc fileprivate func applicationReserved(sender: UIControl) { triggerAction(for:sender, event: .applicationReserved) } @objc fileprivate func systemReserved(sender: UIControl) { triggerAction(for:sender, event: .systemReserved) } @objc fileprivate func allEvents(sender: UIControl) { triggerAction(for:sender, event: .allEvents) } }
apache-2.0
eef0e1514dcdd80239650cc78d6aa15b
36.380228
107
0.661784
4.557719
false
false
false
false
SmallElephant/FEAlgorithm-Swift
11-GoldenInterview/11-GoldenInterview/Tree/BinaryTree.swift
1
3077
// // BinaryTree.swift // 11-GoldenInterview // // Created by keso on 2017/5/13. // Copyright © 2017年 FlyElephant. All rights reserved. // import Foundation class BinaryTree { func treeNodeHeight(treeNode:TreeNode?) -> Int { if treeNode == nil { return 0 } return max(treeNodeHeight(treeNode:treeNode?.leftChild), treeNodeHeight(treeNode: treeNode?.rightChild)) + 1 } func isBalanced(root:TreeNode?) -> Bool { if root == nil { return true } let heightDiff:Int = abs(treeNodeHeight(treeNode: root?.leftChild) - treeNodeHeight(treeNode: root?.rightChild)) if heightDiff > 1 { return false } else { return isBalanced(root:root?.leftChild) && isBalanced(root:root?.rightChild) } } func checkTreeNodeHeight(treeNode:TreeNode?) -> Int { if treeNode == nil { return 0 } // 检查左子树是否平衡 let leftHeight:Int = checkTreeNodeHeight(treeNode: treeNode?.leftChild) if leftHeight == -1 { return -1 } let rightHeight:Int = checkTreeNodeHeight(treeNode: treeNode?.rightChild) if rightHeight == -1 { return -1 } let heightDiff:Int = abs(leftHeight - rightHeight) if heightDiff > 1 { return -1 } else { return max(leftHeight, rightHeight) + 1 } } func isBalanced2(root:TreeNode?) -> Bool { if checkTreeNodeHeight(treeNode: root) == -1 { return false } else { return true } } var pathList:[[String]] = [] var path:[String] = [] func findPath(root:TreeNode?,targetNum:Int) { if root == nil { return } path.append(root!.data!) let target:Int = targetNum - Int(root!.data!)! // 叶子节点,且满足要求 if target == 0 && root?.leftChild == nil && root?.rightChild == nil { pathList.append(path) } // 遍历左子节点 if root?.leftChild != nil { findPath(root: root?.leftChild, targetNum: target) } // 遍历右子节点 if root?.rightChild != nil { findPath(root: root?.rightChild, targetNum: target) } path.removeLast() } func invertTree(rootNode:TreeNode?) { if rootNode == nil || (rootNode?.leftChild == nil && rootNode?.rightChild == nil) { return } let root:TreeNode = rootNode! swap(&root.leftChild, &root.rightChild) if root.leftChild != nil { invertTree(rootNode: root.leftChild) } if root.rightChild != nil { invertTree(rootNode: root.rightChild) } } }
mit
4322b65b3919621114b46cb80159c255
23.290323
120
0.500664
4.584475
false
false
false
false
xuephil/Perfect
Connectors/PostgreSQL/PostgreSQLTests/PostgreSQLTests.swift
2
3536
// // PostgreSQLTests.swift // PostgreSQLTests // // Created by Kyle Jessup on 2015-10-19. // Copyright © 2015 PerfectlySoft. All rights reserved. // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as // published by the Free Software Foundation, either version 3 of the // License, or (at your option) any later version, as supplemented by the // Perfect Additional Terms. // // 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 Affero General Public License, as supplemented by the // Perfect Additional Terms, for more details. // // You should have received a copy of the GNU Affero General Public License // and the Perfect Additional Terms that immediately follow the terms and // conditions of the GNU Affero General Public License along with this // program. If not, see <http://www.perfect.org/AGPL_3_0_With_Perfect_Additional_Terms.txt>. // import XCTest @testable import PostgreSQL class PostgreSQLTests: 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 testConnect() { let p = PGConnection() p.connectdb("dbname = postgres") let status = p.status() XCTAssert(status == .OK) p.finish() } func testExec() { let p = PGConnection() p.connectdb("dbname = postgres") let status = p.status() XCTAssert(status == .OK) let res = p.exec("select * from pg_database") XCTAssertEqual(res.status(), PGResult.StatusType.TuplesOK) let num = res.numFields() XCTAssert(num > 0) for x in 0..<num { let fn = res.fieldName(x) XCTAssertNotNil(fn) print(fn!) } res.clear() p.finish() } func testExecGetValues() { let p = PGConnection() p.connectdb("dbname = postgres") let status = p.status() XCTAssert(status == .OK) // name, oid, integer, boolean let res = p.exec("select datname,datdba,encoding,datistemplate from pg_database") XCTAssertEqual(res.status(), PGResult.StatusType.TuplesOK) let num = res.numTuples() XCTAssert(num > 0) for x in 0..<num { let c1 = res.getFieldString(x, fieldIndex: 0) XCTAssertTrue(c1.characters.count > 0) let c2 = res.getFieldInt(x, fieldIndex: 1) let c3 = res.getFieldInt(x, fieldIndex: 2) let c4 = res.getFieldBool(x, fieldIndex: 3) print("c1=\(c1) c2=\(c2) c3=\(c3) c4=\(c4)") } res.clear() p.finish() } func testExecGetValuesParams() { let p = PGConnection() p.connectdb("dbname = postgres") let status = p.status() XCTAssert(status == .OK) // name, oid, integer, boolean let res = p.exec("select datname,datdba,encoding,datistemplate from pg_database where encoding = $1", params: ["6"]) XCTAssertEqual(res.status(), PGResult.StatusType.TuplesOK, res.errorMessage()) let num = res.numTuples() XCTAssert(num > 0) for x in 0..<num { let c1 = res.getFieldString(x, fieldIndex: 0) XCTAssertTrue(c1.characters.count > 0) let c2 = res.getFieldInt(x, fieldIndex: 1) let c3 = res.getFieldInt(x, fieldIndex: 2) let c4 = res.getFieldBool(x, fieldIndex: 3) print("c1=\(c1) c2=\(c2) c3=\(c3) c4=\(c4)") } res.clear() p.finish() } }
agpl-3.0
d9cbec62b60f9a1f90df7b91d43d74a3
29.474138
118
0.691372
3.231261
false
true
false
false
vulgur/WeeklyFoodPlan
WeeklyFoodPlan/WeeklyFoodPlan/Models/Managers/FoodManager.swift
1
2059
// // FoodManager.swift // WeeklyFoodPlan // // Created by vulgur on 2017/3/15. // Copyright © 2017年 MAD. All rights reserved. // import Foundation import RealmSwift class FoodManager { static let shared = FoodManager() let realm = try! Realm() func randomFood(of when: Food.When) -> Food { let whenObject = realm.objects(WhenObject.self).first { (w) -> Bool in w.value == when.rawValue } let results = realm.objects(Food.self).filter("%@ IN whenObjects", whenObject!) let randomIndex = Int(arc4random_uniform(UInt32(results.count))) return results[randomIndex] } func randomMealFood(of when: Food.When) -> MealFood { let food = randomFood(of: when) let mealFood = MealFood(food: food) return mealFood } func allFoods(of when: Food.When) -> [Food] { let whenObject = realm.objects(WhenObject.self).first { (w) -> Bool in w.value == when.rawValue } let results = realm.objects(Food.self).filter("%@ IN whenObjects", whenObject!) return results.toArray() } func allFoods(of keyword: String) -> [Food] { var result = Set<Food>() // by name let nameResults = realm.objects(Food.self).filter("name CONTAINS %@", keyword).toArray() result = result.union(nameResults) // by tag if let tag = realm.objects(Tag.self).first(where: { (t) -> Bool in t.name.contains(keyword) }) { let tagResults = realm.objects(Food.self).filter("%@ IN tags", tag).toArray() result = result.union(tagResults) } // by ingredient if let ingredient = realm.objects(Ingredient.self).first(where: { (i) -> Bool in i.name.contains(keyword) }) { let ingredentResults = realm.objects(Food.self).filter("%@ IN ingredients", ingredient).toArray() result = result.union(ingredentResults) } return Array(result) } }
mit
99120022bb446174d828a3c994afe30a
31.634921
109
0.588035
4.031373
false
false
false
false
MobileToolkit/Tesseract
TesseractTests/RestfulClient+PUT_Tests.swift
2
1678
// // RestfulClient+PUT_Tests.swift // Tesseract // // Created by Sebastian Owodzin on 10/09/2015. // Copyright © 2015 mobiletoolkit.org. All rights reserved. // import XCTest @testable import Tesseract class RestfulClient_PUT_Tests: XCTestCase { override func setUp() { super.setUp() RestfulClient.baseURL = NSURL(string: "http://localhost:3000") } override func tearDown() { super.tearDown() } func testPutObject() { let expectation = expectationWithDescription("Testing PUT object") let payload = JSONPayload(data: ["product": ["name": "test product", "price": "666"]]) RestfulClient.sharedInstance.POST(Product.self, payload: payload) { (objectData, error) -> Void in if nil == error, let objectData = objectData, let data = objectData["data"] as? Dictionary<String, AnyObject> { let productId = data["id"] as! Int let payload = JSONPayload(data: ["product": ["name": "test product 666", "price": "777"]]) RestfulClient.sharedInstance.PUT(Product.self, objectID: productId, payload: payload) { (objectData, error) -> Void in if nil == error { XCTAssertNotNil(objectData) expectation.fulfill() } } } } waitForExpectationsWithTimeout(5.0) { (error) -> Void in if let error = error { XCTFail("PUT object failed with error: \(error)"); } } } }
mit
5943801d2452a3076ae4e03f16615fa0
31.25
134
0.537865
4.805158
false
true
false
false
domenicosolazzo/practice-swift
Views/NavigationController/Fonts/FontSizesViewController.swift
1
1478
// // FontSizesViewController.swift // Fonts // // Created by Domenico on 23.04.15. // Copyright (c) 2015 Domenico Solazzo. All rights reserved. // import UIKit class FontSizesViewController: UITableViewController { var font: UIFont! fileprivate var pointSizes: [CGFloat] { struct Constants { static let pointSizes: [CGFloat] = [ 9, 10, 11, 12, 13, 14, 18, 24, 36, 48, 64, 72, 96, 144 ] } return Constants.pointSizes } fileprivate let cellIdentifier = "FontNameAndSize" func fontForDisplay(atIndexPath indexPath: IndexPath) -> UIFont { let pointSize = pointSizes[(indexPath as NSIndexPath).row] return font.withSize(pointSize) } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // Return the number of rows in the section. return pointSizes.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) cell.textLabel!.font = fontForDisplay(atIndexPath: indexPath) cell.textLabel!.text = font.fontName cell.detailTextLabel?.text = "\(pointSizes[(indexPath as NSIndexPath).row]) point" return cell } }
mit
8ebe637786837f31a15b133292bae5bc
29.791667
101
0.61908
5.010169
false
false
false
false
Athlee/ATHKit
Examples/ATHImagePickerController/Storyboard/TestPicker/Pods/Material/Sources/iOS/CollectionReusableView.swift
1
9170
/* * Copyright (C) 2015 - 2016, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.com>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of CosmicMind nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import UIKit @objc(CollectionReusableView) open class CollectionReusableView: UICollectionReusableView, Pulseable { /** A CAShapeLayer used to manage elements that would be affected by the clipToBounds property of the backing layer. For example, this allows the dropshadow effect on the backing layer, while clipping the image to a desired shape within the visualLayer. */ open let visualLayer = CAShapeLayer() /// A Pulse reference. fileprivate var pulse: Pulse! /// PulseAnimation value. open var pulseAnimation: PulseAnimation { get { return pulse.animation } set(value) { pulse.animation = value } } /// PulseAnimation color. @IBInspectable open var pulseColor: UIColor { get { return pulse.color } set(value) { pulse.color = value } } /// Pulse opacity. @IBInspectable open var pulseOpacity: CGFloat { get { return pulse.opacity } set(value) { pulse.opacity = value } } /** A property that manages an image for the visualLayer's contents property. Images should not be set to the backing layer's contents property to avoid conflicts when using clipsToBounds. */ @IBInspectable open var image: UIImage? { didSet { visualLayer.contents = image?.cgImage } } /** Allows a relative subrectangle within the range of 0 to 1 to be specified for the visualLayer's contents property. This allows much greater flexibility than the contentsGravity property in terms of how the image is cropped and stretched. */ @IBInspectable open var contentsRect: CGRect { get { return visualLayer.contentsRect } set(value) { visualLayer.contentsRect = value } } /** A CGRect that defines a stretchable region inside the visualLayer with a fixed border around the edge. */ @IBInspectable open var contentsCenter: CGRect { get { return visualLayer.contentsCenter } set(value) { visualLayer.contentsCenter = value } } /** A floating point value that defines a ratio between the pixel dimensions of the visualLayer's contents property and the size of the view. By default, this value is set to the Screen.scale. */ @IBInspectable open var contentsScale: CGFloat { get { return visualLayer.contentsScale } set(value) { visualLayer.contentsScale = value } } /// A Preset for the contentsGravity property. open var contentsGravityPreset: Gravity { didSet { contentsGravity = GravityToValue(gravity: contentsGravityPreset) } } /// Determines how content should be aligned within the visualLayer's bounds. @IBInspectable open var contentsGravity: String { get { return visualLayer.contentsGravity } set(value) { visualLayer.contentsGravity = value } } /// A preset wrapper around contentEdgeInsets. open var contentEdgeInsetsPreset: EdgeInsetsPreset { get { return grid.contentEdgeInsetsPreset } set(value) { grid.contentEdgeInsetsPreset = value } } /// A reference to EdgeInsets. @IBInspectable open var contentEdgeInsets: UIEdgeInsets { get { return grid.contentEdgeInsets } set(value) { grid.contentEdgeInsets = value } } /// A preset wrapper around interimSpace. open var interimSpacePreset: InterimSpacePreset { get { return grid.interimSpacePreset } set(value) { grid.interimSpacePreset = value } } /// A wrapper around grid.interimSpace. @IBInspectable open var interimSpace: InterimSpace { get { return grid.interimSpace } set(value) { grid.interimSpace = value } } /// A property that accesses the backing layer's background @IBInspectable open override var backgroundColor: UIColor? { didSet { layer.backgroundColor = backgroundColor?.cgColor } } /** An initializer that initializes the object with a NSCoder object. - Parameter aDecoder: A NSCoder instance. */ public required init?(coder aDecoder: NSCoder) { contentsGravityPreset = .resizeAspectFill super.init(coder: aDecoder) prepare() } /** An initializer that initializes the object with a CGRect object. If AutoLayout is used, it is better to initilize the instance using the init() initializer. - Parameter frame: A CGRect instance. */ public override init(frame: CGRect) { contentsGravityPreset = .resizeAspectFill super.init(frame: frame) prepare() } /// A convenience initializer. public convenience init() { self.init(frame: .zero) } open override func layoutSubviews() { super.layoutSubviews() layoutShape() layoutVisualLayer() layoutShadowPath() } /** Triggers the pulse animation. - Parameter point: A Optional point to pulse from, otherwise pulses from the center. */ open func pulse(point: CGPoint? = nil) { let p = point ?? center pulse.expandAnimation(point: p) Motion.delay(time: 0.35) { [weak self] in self?.pulse.contractAnimation() } } /** A delegation method that is executed when the view has began a touch event. - Parameter touches: A set of UITouch objects. - Parameter event: A UIEvent object. */ open override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesBegan(touches, with: event) pulse.expandAnimation(point: layer.convert(touches.first!.location(in: self), from: layer)) } /** A delegation method that is executed when the view touch event has ended. - Parameter touches: A set of UITouch objects. - Parameter event: A UIEvent object. */ open override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesEnded(touches, with: event) pulse.contractAnimation() } /** A delegation method that is executed when the view touch event has been cancelled. - Parameter touches: A set of UITouch objects. - Parameter event: A UIEvent object. */ open override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesCancelled(touches, with: event) pulse.contractAnimation() } /** Prepares the view instance when intialized. When subclassing, it is recommended to override the prepare method to initialize property values and other setup operations. The super.prepare method should always be called immediately when subclassing. */ open func prepare() { contentScaleFactor = Screen.scale prepareVisualLayer() preparePulse() } } extension CollectionReusableView { /// Prepares the pulse motion. fileprivate func preparePulse() { pulse = Pulse(pulseView: self, pulseLayer: visualLayer) pulseAnimation = .none } /// Prepares the visualLayer property. fileprivate func prepareVisualLayer() { visualLayer.zPosition = 0 visualLayer.masksToBounds = true layer.addSublayer(visualLayer) } } extension CollectionReusableView { /// Manages the layout for the visualLayer property. fileprivate func layoutVisualLayer() { visualLayer.frame = bounds visualLayer.cornerRadius = cornerRadius } }
mit
e965a243df0d8862f7f2a3e3ff2b336a
27.746082
99
0.680153
4.690537
false
false
false
false
nathantannar4/Parse-Dashboard-for-iOS-Pro
Pods/BiometricAuthentication/BiometricAuthentication/BiometricAuthentication/Authentication/BioMetricAuthenticator.swift
1
5321
// // BioMetricAuthenticator.swift // BiometricAuthentication // // Copyright (c) 2017 Rushi Sangani // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import UIKit import LocalAuthentication open class BioMetricAuthenticator: NSObject { // MARK: - Singleton public static let shared = BioMetricAuthenticator() } // MARK:- Public public extension BioMetricAuthenticator { /// checks if TouchID or FaceID is available on the device. class func canAuthenticate() -> Bool { var isBiometricAuthenticationAvailable = false var error: NSError? = nil if LAContext().canEvaluatePolicy(LAPolicy.deviceOwnerAuthenticationWithBiometrics, error: &error) { isBiometricAuthenticationAvailable = (error == nil) } return isBiometricAuthenticationAvailable } /// Check for biometric authentication class func authenticateWithBioMetrics(reason: String, fallbackTitle: String? = "", cancelTitle: String? = "", success successBlock:@escaping AuthenticationSuccess, failure failureBlock:@escaping AuthenticationFailure) { let reasonString = reason.isEmpty ? BioMetricAuthenticator.shared.defaultBiometricAuthenticationReason() : reason let context = LAContext() context.localizedFallbackTitle = fallbackTitle // cancel button title if #available(iOS 10.0, *) { context.localizedCancelTitle = cancelTitle } // authenticate BioMetricAuthenticator.shared.evaluate(policy: LAPolicy.deviceOwnerAuthenticationWithBiometrics, with: context, reason: reasonString, success: successBlock, failure: failureBlock) } /// Check for device passcode authentication class func authenticateWithPasscode(reason: String, cancelTitle: String? = "", success successBlock:@escaping AuthenticationSuccess, failure failureBlock:@escaping AuthenticationFailure) { let reasonString = reason.isEmpty ? BioMetricAuthenticator.shared.defaultPasscodeAuthenticationReason() : reason let context = LAContext() // cancel button title if #available(iOS 10.0, *) { context.localizedCancelTitle = cancelTitle } // authenticate if #available(iOS 9.0, *) { BioMetricAuthenticator.shared.evaluate(policy: LAPolicy.deviceOwnerAuthentication, with: context, reason: reasonString, success: successBlock, failure: failureBlock) } else { // Fallback on earlier versions BioMetricAuthenticator.shared.evaluate(policy: LAPolicy.deviceOwnerAuthenticationWithBiometrics, with: context, reason: reasonString, success: successBlock, failure: failureBlock) } } /// checks if face id is avaiable on device public func faceIDAvailable() -> Bool { if #available(iOS 11.0, *) { let context = LAContext() return (context.canEvaluatePolicy(LAPolicy.deviceOwnerAuthentication, error: nil) && context.biometryType == .faceID) } return false } } // MARK:- Private extension BioMetricAuthenticator { /// get authentication reason to show while authentication func defaultBiometricAuthenticationReason() -> String { return faceIDAvailable() ? kFaceIdAuthenticationReason : kTouchIdAuthenticationReason } /// get passcode authentication reason to show while entering device passcode after multiple failed attempts. func defaultPasscodeAuthenticationReason() -> String { return faceIDAvailable() ? kFaceIdPasscodeAuthenticationReason : kTouchIdPasscodeAuthenticationReason } /// evaluate policy func evaluate(policy: LAPolicy, with context: LAContext, reason: String, success successBlock:@escaping AuthenticationSuccess, failure failureBlock:@escaping AuthenticationFailure) { context.evaluatePolicy(policy, localizedReason: reason) { (success, err) in DispatchQueue.main.async { if success { successBlock() } else { let errorType = AuthenticationError(error: err as! LAError) failureBlock(errorType) } } } } }
mit
3b2ad72845db5e6116844ac77519aa56
42.260163
223
0.697989
5.363911
false
false
false
false
itsaboutcode/WordPress-iOS
WordPress/WordPressTest/ReaderReblogActionTests.swift
1
5205
@testable import WordPress import CoreData import XCTest class MockReblogPresenter: ReaderReblogPresenter { var presentReblogExpectation: XCTestExpectation? override func presentReblog(blogService: BlogService, readerPost: ReaderPost, origin: UIViewController) { presentReblogExpectation?.fulfill() } } class MockBlogService: BlogService { var blogsForAllAccountsExpectation: XCTestExpectation? var lastUsedOrFirstBlogExpectation: XCTestExpectation? var blogCount = 1 override func blogCountVisibleForWPComAccounts() -> Int { return blogCount } override func visibleBlogsForWPComAccounts() -> [Blog] { blogsForAllAccountsExpectation?.fulfill() return [Blog(context: self.managedObjectContext), Blog(context: self.managedObjectContext)] } override func lastUsedOrFirstBlog() -> Blog? { lastUsedOrFirstBlogExpectation?.fulfill() return Blog(context: self.managedObjectContext) } } class MockPostService: PostService { var draftPostExpectation: XCTestExpectation? override func createDraftPost(for blog: Blog) -> Post { draftPostExpectation?.fulfill() return Post(context: self.managedObjectContext) } } class ReblogTestCase: XCTestCase { var contextManager: TestContextManager! var context: NSManagedObjectContext! var readerPost: ReaderPost? var blogService: MockBlogService? var postService: MockPostService? override func setUp() { contextManager = TestContextManager() context = contextManager.getMockContext() readerPost = ReaderPost(context: self.context!) blogService = MockBlogService(managedObjectContext: self.context!) postService = MockPostService(managedObjectContext: self.context!) } override func tearDown() { contextManager = nil context = nil readerPost = nil blogService = nil postService = nil } } class ReaderReblogActionTests: ReblogTestCase { func testExecuteAction() { // Given let presenter = MockReblogPresenter(postService: postService!) presenter.presentReblogExpectation = expectation(description: "presentBlog was called") let action = ReaderReblogAction(blogService: blogService!, presenter: presenter) let controller = UIViewController() // When action.execute(readerPost: readerPost!, origin: controller, reblogSource: .list) // Then waitForExpectations(timeout: 4) { error in if let error = error { XCTFail("waitForExpectationsWithTimeout errored: \(error)") } } } } class ReblogPresenterTests: ReblogTestCase { func testPresentEditorForOneSite() { // Given postService!.draftPostExpectation = expectation(description: "createDraftPost was called") blogService!.blogsForAllAccountsExpectation = expectation(description: "blogsForAllAccounts was called") let presenter = ReaderReblogPresenter(postService: postService!) // When presenter.presentReblog(blogService: blogService!, readerPost: readerPost!, origin: UIViewController()) // Then waitForExpectations(timeout: 4) { error in if let error = error { XCTFail("waitForExpectationsWithTimeout errored: \(error)") } } } func testPresentEditorForMultipleSites() { // Given blogService!.lastUsedOrFirstBlogExpectation = expectation(description: "lastUsedOrFirstBlog was called") blogService!.blogCount = 2 let presenter = ReaderReblogPresenter(postService: postService!) // When presenter.presentReblog(blogService: blogService!, readerPost: readerPost!, origin: UIViewController()) // Then waitForExpectations(timeout: 4) { error in if let error = error { XCTFail("waitForExpectationsWithTimeout errored: \(error)") } } } } class ReblogFormatterTests: XCTestCase { func testWordPressQuote() { // Given let quote = "Quote" // When let wpQuote = ReaderReblogFormatter.gutenbergQuote(text: quote) // Then XCTAssertEqual("<!-- wp:quote -->\n<blockquote class=\"wp-block-quote\"><p>Quote</p></blockquote>\n<!-- /wp:quote -->", wpQuote) } func testHyperLink() { // Given let url = "https://wordpress.com" let text = "WordPress.com" // When let wpLink = ReaderReblogFormatter.hyperLink(url: url, text: text) // Then XCTAssertEqual("<a href=\"https://wordpress.com\">WordPress.com</a>", wpLink) } func testImage() { // Given let image = "image.jpg" // When let wpImage = ReaderReblogFormatter.gutenbergImage(image: image) // Then XCTAssertEqual("<!-- wp:image {\"className\":\"size-large\"} -->\n" + "<figure class=\"wp-block-image size-large\">" + "<img src=\"image.jpg\" alt=\"\"/>" + "</figure>\n<!-- /wp:image -->", wpImage) } }
gpl-2.0
ab68e1a2c4fd96fa62a71b3fcdabd796
33.019608
136
0.648415
4.995202
false
true
false
false
cocoascientist/Jetstream
JetstreamCore/Controllers/DarkSkyAPI.swift
1
1475
// // DarkSkyAPI.swift // Jetstream // // Created by Andrew Shepard on 2/19/15. // Copyright (c) 2015 Andrew Shepard. All rights reserved. // import Foundation import CoreLocation public enum DarkSkyAPI { case forecast(CLLocation) } extension DarkSkyAPI { private var apiKey: String { // register for an API key at https://darksky.net/dev/register // replace the value below with your API key, and return it // remove the fatalError once your API key is set above return "55219b5db1bfdf0f8b0fae33e516ee98" } private var baseURL: String { return "https://api.darksky.net" } private var path: String { switch self { case .forecast(let location): let latitude = location.coordinate.latitude let longitude = location.coordinate.longitude return "\(baseURL)/forecast/\(apiKey)/\(latitude),\(longitude)?exclude=flags,minutely&units=\(units)" } } public var request: URLRequest { let path = self.path let url = URL(string: path)! return URLRequest(url: url, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 60.0) } private var units: String { let units = UserDefaults.standard.integer(forKey: "units") switch units { case 1: return "si" case 2: return "us" default: return "auto" } } }
mit
8534b1dddc1dd1aadb3787f75a8d6abb
24.877193
113
0.604068
4.287791
false
false
false
false
kaich/CKAlertView
CKAlertView/Classes/Core/Category/NSAttributeString+Alert.swift
1
2389
// // NSAttributeString+Alert.swift // Pods // // Created by mac on 16/11/8. // // import Foundation public enum CKIndentStyle { case firstLine , headIndent , tailIndent } extension NSAttributedString : CKAlertViewStringable { public func ck_string() -> String { return string } public func ck_attributeString() -> NSAttributedString { return self } public func ck_apply(align : NSTextAlignment) -> NSAttributedString { let finalAttributes = self.attributes(at: 0, effectiveRange: nil) if let paragraphStyle = finalAttributes[NSAttributedString.Key.paragraphStyle] as? NSMutableParagraphStyle { paragraphStyle.alignment = align } return self } public func ck_apply(font :UIFont) -> NSAttributedString { let finalString :NSMutableAttributedString = NSMutableAttributedString(attributedString: self) finalString.addAttribute(NSAttributedString.Key.font, value: font, range: NSMakeRange(0, length)) return finalString } public func ck_apply(color :UIColor) -> NSAttributedString { let finalString :NSMutableAttributedString = NSMutableAttributedString(attributedString: self) finalString.addAttribute(NSAttributedString.Key.foregroundColor, value:color, range:NSMakeRange(0, length)); return finalString } public func ck_apply(indent :CGFloat , style :CKIndentStyle) -> NSAttributedString { let finalAttributes = self.attributes(at: 0, effectiveRange: nil) if let paragraphStyle = finalAttributes[NSAttributedString.Key.paragraphStyle] as? NSMutableParagraphStyle { switch style { case .firstLine: paragraphStyle.firstLineHeadIndent = indent case .headIndent: paragraphStyle.headIndent = indent case .tailIndent: paragraphStyle.tailIndent = indent } } return self } public func ck_apply(lineSpacing :CGFloat) -> NSAttributedString { let finalAttributes = self.attributes(at: 0, effectiveRange: nil) if let paragraphStyle = finalAttributes[NSAttributedString.Key.paragraphStyle] as? NSMutableParagraphStyle { paragraphStyle.lineSpacing = lineSpacing } return self } }
mit
35c04877532045f848406939a95249cb
32.180556
116
0.663039
5.517321
false
false
false
false
rsyncOSX/RsyncOSX
RsyncOSX/extensionDate.swift
1
6899
// // extension Date // RsyncOSX // // Created by Thomas Evensen on 08/12/2018. // Copyright © 2018 Thomas Evensen. All rights reserved. // // swiftlint:disable line_length import Foundation extension Date { func weekday(date _: Date) -> Int { let calendar = Calendar.current let dateComponent = (calendar as NSCalendar).components(.weekday, from: self) return dateComponent.weekday! } func numberOfDaysInMonth() -> Int { let calendar = Calendar.current let days = (calendar as NSCalendar).range(of: NSCalendar.Unit.day, in: NSCalendar.Unit.month, for: self) return days.length } func dateByAddingMonths(_ months: Int) -> Date { let calendar = Calendar.current var dateComponent = DateComponents() dateComponent.month = months return (calendar as NSCalendar).date(byAdding: dateComponent, to: self, options: NSCalendar.Options.matchNextTime)! } func dateByAddingDays(_ days: Int) -> Date { let calendar = Calendar.current var dateComponent = DateComponents() dateComponent.day = days return (calendar as NSCalendar).date(byAdding: dateComponent, to: self, options: NSCalendar.Options.matchNextTime)! } func daymonth() -> Int { let calendar = Calendar.current let dateComponent = (calendar as NSCalendar).components(.day, from: self) return dateComponent.day! } func isSaturday() -> Bool { return (getWeekday() == 7) } func isSunday() -> Bool { return getWeekday() == 1 } func isWeekday() -> Bool { return getWeekday() != 1 } func getWeekday() -> Int { let calendar = Calendar.current return (calendar as NSCalendar).components(.weekday, from: self).weekday! } func isSelectedDayofWeek(day: NumDayofweek) -> Bool { return getWeekday() == day.rawValue } func monthNameFull() -> String { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "MMMM YYYY" return dateFormatter.string(from: self) } func monthNameShort() -> String { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "MMM" return dateFormatter.string(from: self) } func dayNameShort() -> String { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "EEEE" return dateFormatter.string(from: self) } func month() -> Int { let calendar = Calendar.current let dateComponent = (calendar as NSCalendar).components(.month, from: self) return dateComponent.month! } func year() -> Int { let calendar = Calendar.current let dateComponent = (calendar as NSCalendar).components(.year, from: self) return dateComponent.year! } static func == (lhs: Date, rhs: Date) -> Bool { return lhs.compare(rhs) == ComparisonResult.orderedSame } static func < (lhs: Date, rhs: Date) -> Bool { return lhs.compare(rhs) == ComparisonResult.orderedAscending } static func > (lhs: Date, rhs: Date) -> Bool { return rhs.compare(lhs) == ComparisonResult.orderedAscending } var ispreviousmont: Bool { let calendar = Calendar.current let yearComponent = (calendar as NSCalendar).components(.year, from: self) let monthComponent = (calendar as NSCalendar).components(.month, from: self) let today = Date() let todayComponentyear = (calendar as NSCalendar).components(.year, from: today) let todaymonthComponent = (calendar as NSCalendar).components(.month, from: today) if yearComponent == todayComponentyear { if (monthComponent.month ?? -1) == (todaymonthComponent.month ?? -1) - 1 { return true } } return false } var secondstonow: Int { let components = Set<Calendar.Component>([.second]) return Calendar.current.dateComponents(components, from: self, to: Date()).second ?? 0 } var daystonow: Int { let components = Set<Calendar.Component>([.day]) return Calendar.current.dateComponents(components, from: self, to: Date()).day ?? 0 } var weekstonow: Int { let components = Set<Calendar.Component>([.weekOfYear]) return Calendar.current.dateComponents(components, from: self, to: Date()).weekOfYear ?? 0 } func localized_string_from_date() -> String { let dateformatter = DateFormatter() dateformatter.formatterBehavior = .behavior10_4 dateformatter.dateStyle = .medium dateformatter.timeStyle = .short return dateformatter.string(from: self) } func long_localized_string_from_date() -> String { let dateformatter = DateFormatter() dateformatter.formatterBehavior = .behavior10_4 dateformatter.dateStyle = .medium dateformatter.timeStyle = .long return dateformatter.string(from: self) } func en_us_string_from_date() -> String { let dateformatter = DateFormatter() dateformatter.locale = Locale(identifier: "en_US") dateformatter.dateStyle = .medium dateformatter.timeStyle = .short dateformatter.dateFormat = "dd MMM yyyy HH:mm" return dateformatter.string(from: self) } func shortlocalized_string_from_date() -> String { // MM-dd-yyyy HH:mm let dateformatter = DateFormatter() dateformatter.formatterBehavior = .behavior10_4 dateformatter.dateStyle = .medium dateformatter.timeStyle = .short dateformatter.dateFormat = "MM-dd-yyyy:HH:mm" return dateformatter.string(from: self) } init(year: Int, month: Int, day: Int) { let calendar = Calendar.current var dateComponent = DateComponents() dateComponent.year = year dateComponent.month = month dateComponent.day = day self = calendar.date(from: dateComponent)! } } extension String { func en_us_date_from_string() -> Date { let dateformatter = DateFormatter() dateformatter.locale = Locale(identifier: "en_US") dateformatter.dateStyle = .medium dateformatter.timeStyle = .short dateformatter.dateFormat = "dd MMM yyyy HH:mm" return dateformatter.date(from: self) ?? Date() } func localized_date_from_string() -> Date { let dateformatter = DateFormatter() dateformatter.formatterBehavior = .behavior10_4 dateformatter.dateStyle = .medium dateformatter.timeStyle = .short return dateformatter.date(from: self) ?? Date() } var setdatesuffixbackupstring: String { let formatter = DateFormatter() formatter.dateFormat = "-yyyy-MM-dd" return self + formatter.string(from: Date()) } }
mit
1a7b7e08d1fe2a64014b80506341823f
32.485437
123
0.636416
4.617135
false
false
false
false
sonsongithub/reddift
application/ImageViewController.swift
1
14176
// // ImageViewController.swift // UZImageCollectionView // // Created by sonson on 2015/06/05. // Copyright (c) 2015年 sonson. All rights reserved. // import UIKit import FLAnimatedImage let ImageViewControllerDidChangeCurrentImageName = Notification.Name(rawValue: "ImageViewControllerDidChangeCurrentImage") class ImageViewController: UIViewController, Page, ImageDownloadable, ImageViewDestination { var thumbnails: [Thumbnail] = [] let index: Int let scrollView = UIScrollView(frame: CGRect.zero) let mainImageView = FLAnimatedImageView(frame: CGRect.zero) var indicator = UIActivityIndicatorView(activityIndicatorStyle: .gray) var maximumZoomScale: CGFloat = 0 var minimumZoomScale: CGFloat = 0 var imageURL = URL(string: "https://api.sonson.jp")! var task: URLSessionDataTask? var isOpenedBy3DTouch = false private var _alphaWithoutMainContent: CGFloat = 1 var initialiContentOffsetY = CGFloat(0) var alphaWithoutMainContent: CGFloat { get { return _alphaWithoutMainContent } set { _alphaWithoutMainContent = newValue scrollView.backgroundColor = scrollView.backgroundColor?.withAlphaComponent(_alphaWithoutMainContent) view.backgroundColor = view.backgroundColor?.withAlphaComponent(_alphaWithoutMainContent) } } func thumbnailImageView() -> UIImageView { return mainImageView } deinit { print("deinit ImageViewController") NotificationCenter.default.removeObserver(self) } required init?(coder aDecoder: NSCoder) { self.index = 0 // self.imageCollectionViewController = ImageCollectionViewController(collection: ImageCollection(newList: [])) super.init(coder: aDecoder) } override func viewDidLoad() { super.viewDidLoad() setupSubviews() view.backgroundColor = UIColor.white scrollView.backgroundColor = UIColor.white scrollView.alwaysBounceVertical = true let rec = UITapGestureRecognizer(target: self, action: #selector(ImageViewController.didTapGesture(recognizer:))) self.scrollView.addGestureRecognizer(rec) } @objc func didTapGesture(recognizer: UITapGestureRecognizer) { if let imageViewPageController = self.parentImageViewPageController { imageViewPageController.navigationBar.isHidden = !imageViewPageController.navigationBar.isHidden } } override func willMove(toParentViewController parent: UIViewController?) { super.willMove(toParentViewController: parent) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) } override func viewDidAppear(_ animated: Bool) { print("viewDidAppear") super.viewDidAppear(animated) } override func viewDidDisappear(_ animated: Bool) { print("viewDidDisappear") super.viewDidDisappear(animated) } func toggleDarkMode(isDark: Bool) { UIView.animate(withDuration: 0.2, animations: { () -> Void in self.scrollView.backgroundColor = isDark ? UIColor.black : UIColor.white }, completion: { (_) -> Void in }) } init(index: Int, thumbnails: [Thumbnail], isOpenedBy3DTouch: Bool = false) { self.index = index scrollView.addSubview(mainImageView) super.init(nibName: nil, bundle: nil) self.thumbnails = thumbnails self.imageURL = thumbnails[index].thumbnailURL self.isOpenedBy3DTouch = isOpenedBy3DTouch NotificationCenter.default.addObserver(self, selector: #selector(ImageViewController.didFinishDownloading(notification:)), name: ImageDownloadableDidFinishDownloadingName, object: nil) download(imageURLs: [self.imageURL], sender: self) } class func controllerWithIndex(index: Int, isDark: Bool, thumbnails: [Thumbnail]) -> ImageViewController { let con = ImageViewController(index: index, thumbnails: thumbnails) return con } } extension ImageViewController { func setupScrollViewScale(imageSize: CGSize) { scrollView.frame = self.view.bounds let boundsSize = self.view.bounds // calculate min/max zoomscale let xScale = boundsSize.width / imageSize.width; // the scale needed to perfectly fit the image width-wise let yScale = boundsSize.height / imageSize.height; // the scale needed to perfectly fit the image height-wise // fill width if the image and phone are both portrait or both landscape; otherwise take smaller scale let imagePortrait = imageSize.height > imageSize.width let phonePortrait = boundsSize.height > imageSize.width var minScale = imagePortrait == phonePortrait ? xScale : (xScale < yScale ? xScale : yScale) // on high resolution screens we have double the pixel density, so we will be seeing every pixel if we limit the // maximum zoom scale to 0.5. let maxScale = 10.0 / UIScreen.main.scale // don't let minScale exceed maxScale. (If the image is smaller than the screen, we don't want to force it to be zoomed.) if minScale > maxScale { minScale = maxScale } scrollView.maximumZoomScale = maxScale scrollView.minimumZoomScale = minScale scrollView.contentSize = mainImageView.image!.size scrollView.zoomScale = scrollView.minimumZoomScale } func updateImageCenter() { let boundsSize = self.view.bounds var frameToCenter = mainImageView.frame if frameToCenter.size.width < boundsSize.width { frameToCenter.origin.x = (boundsSize.width - frameToCenter.size.width) / 2 } else { frameToCenter.origin.x = 0 } if frameToCenter.size.height < boundsSize.height { frameToCenter.origin.y = (boundsSize.height - frameToCenter.size.height) / 2 } else { frameToCenter.origin.y = 0 } mainImageView.frame = frameToCenter } func setIndicator() { self.view.addSubview(indicator) indicator.translatesAutoresizingMaskIntoConstraints = false self.view.addConstraint(NSLayoutConstraint(item: indicator, attribute: NSLayoutAttribute.centerX, relatedBy: NSLayoutRelation.equal, toItem: self.view, attribute: NSLayoutAttribute.centerX, multiplier: 1, constant: 0)) self.view.addConstraint(NSLayoutConstraint(item: indicator, attribute: NSLayoutAttribute.centerY, relatedBy: NSLayoutRelation.equal, toItem: self.view, attribute: NSLayoutAttribute.centerY, multiplier: 1, constant: 0)) } func setScrollView() { scrollView.showsVerticalScrollIndicator = false scrollView.showsHorizontalScrollIndicator = false scrollView.bouncesZoom = true scrollView.decelerationRate = UIScrollViewDecelerationRateFast scrollView.delegate = self scrollView.isMultipleTouchEnabled = true self.view.addSubview(scrollView) scrollView.translatesAutoresizingMaskIntoConstraints = false self.view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-0-[scrollView]-0-|", options: NSLayoutFormatOptions(), metrics: [:], views: ["scrollView": scrollView])) self.view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-0-[scrollView]-1-|", options: NSLayoutFormatOptions(), metrics: [:], views: ["scrollView": scrollView])) } func setupSubviews() { self.view.isMultipleTouchEnabled = true self.navigationController?.view.isMultipleTouchEnabled = true setScrollView() setIndicator() indicator.startAnimating() indicator.isHidden = false setImage(of: self.imageURL) } func close() { if let imageViewPageController = parentImageViewPageController { imageViewPageController.close(sender: self) } } var parentImageViewPageController: ImageViewPageController? { if let vc1 = self.parent as? ImageViewPageController { return vc1 } return nil } } // MARK: UIScrollViewDelegate extension ImageViewController: UIScrollViewDelegate { func scrollViewDidZoom(_ scrollView: UIScrollView) { print("scrollViewDidZoom") let ratio = scrollView.zoomScale / scrollView.minimumZoomScale let threshold = CGFloat(0.6) var alpha = CGFloat(1) print(ratio) if ratio > 1 { alpha = 1 } else if ratio > threshold { // alpha = (ratio - threshold / 2) * (ratio - threshold / 2) + 1 - (1 - threshold / 2) * (1 - threshold / 2) alpha = (ratio - 1) * (ratio - 1) * (-1) / ((threshold - 1) * (threshold - 1)) + 1 } else { alpha = 0 } print(alpha) parentImageViewPageController?.alphaWithoutMainContent = alpha self.updateImageCenter() if ratio < threshold { close() } } func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) { print("scrollViewDidEndDragging") } func scrollViewDidScroll(_ scrollView: UIScrollView) { print("scrollViewDidScroll") if scrollView.contentOffset.y < initialiContentOffsetY { let threshold = CGFloat(-150) let s = CGFloat(-50) let x = scrollView.contentOffset.y - initialiContentOffsetY if x < s { let param = (x - s) * (x - s) * (-1) / ((threshold - s) * (threshold - s)) + 1 parentImageViewPageController?.alphaWithoutMainContent = param } else { parentImageViewPageController?.alphaWithoutMainContent = 1 } if x < threshold { close() } } } func scrollViewWillBeginDecelerating(_ scrollView: UIScrollView) { print("scrollViewWillBeginDecelerating") } func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) { print("scrollViewDidEndScrollingAnimation") } func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { print("scrollViewDidEndDecelerating") } func scrollViewDidEndZooming(_ scrollView: UIScrollView, with view: UIView?, atScale scale: CGFloat) { print("scrollViewDidEndZooming") self.updateImageCenter() } func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { print("scrollViewWillBeginDragging") let userInfo: [String: Any] = ["index": self.index, "thumbnail": self.thumbnails[self.index]] NotificationCenter.default.post(name: ImageViewPageControllerDidChangePageName, object: nil, userInfo: userInfo) NotificationCenter.default.post(name: ImageViewPageControllerDidStartDraggingThumbnailName, object: nil, userInfo: ["thumbnail": thumbnails[index]]) } func scrollViewWillBeginZooming(_ scrollView: UIScrollView, with view: UIView?) { print("scrollViewWillBeginZooming") let userInfo: [String: Any] = ["index": self.index, "thumbnail": self.thumbnails[self.index]] NotificationCenter.default.post(name: ImageViewPageControllerDidChangePageName, object: nil, userInfo: userInfo) NotificationCenter.default.post(name: ImageViewPageControllerDidStartDraggingThumbnailName, object: nil, userInfo: ["thumbnail": thumbnails[index]]) } func viewForZooming(in scrollView: UIScrollView) -> UIView? { print("viewForZooming") return mainImageView } } // MARK: ImageDownloadable extension ImageViewController { func setImage(of url: URL) { do { let data = try cachedDataInCache(of: url) guard let animatedImage: FLAnimatedImage = FLAnimatedImage(animatedGIFData: data) else { if let image = UIImage(data: data as Data) { mainImageView.isHidden = false mainImageView.image = image mainImageView.frame = CGRect(origin: CGPoint(x: 0, y: 0), size: image.size) setupScrollViewScale(imageSize: image.size) updateImageCenter() initialiContentOffsetY = scrollView.contentOffset.y indicator.stopAnimating() indicator.isHidden = true } else { indicator.startAnimating() indicator.isHidden = false } return } mainImageView.animatedImage = animatedImage mainImageView.frame = CGRect(origin: CGPoint(x: 0, y: 0), size: animatedImage.size) setupScrollViewScale(imageSize: animatedImage.size) updateImageCenter() initialiContentOffsetY = scrollView.contentOffset.y indicator.stopAnimating() indicator.isHidden = true } catch { print(error) } } @objc func didFinishDownloading(notification: NSNotification) { if let userInfo = notification.userInfo, let obj = userInfo[ImageDownloadableSenderKey] as? ImageViewController, let url = userInfo[ImageDownloadableUrlKey] as? URL { if obj == self { if let _ = userInfo[ImageDownloadableErrorKey] as? NSError { mainImageView.isHidden = false mainImageView.image = UIImage(named: "error") mainImageView.frame = self.view.bounds updateImageCenter() mainImageView.contentMode = .center mainImageView.isUserInteractionEnabled = false indicator.stopAnimating() indicator.isHidden = true } else { setImage(of: url) } } } } }
mit
2618db304f7a05e6ffc6d8c8ca566c30
39.381766
226
0.646042
5.483172
false
false
false
false
CocoaheadsSaar/Treffen
Treffen2/Autolayout Teil 2/AutolayoutTests2/AutolayoutTests/MainView.swift
1
1858
// // MainView.swift // AutolayoutTests // // Created by Markus Schmitt on 12.01.16. // Copyright © 2016 My - Markus Schmitt. All rights reserved. // import UIKit class MainView: UIView { var textLabel: UILabel var textField: UITextField override init(frame: CGRect) { // views textLabel = UILabel(frame: .zero) textLabel.translatesAutoresizingMaskIntoConstraints = false textLabel.text = "Testlabel" let textSize = textLabel.intrinsicContentSize().width textField = UITextField(frame: .zero) textField.borderStyle = .Line textField.translatesAutoresizingMaskIntoConstraints = false super.init(frame: frame) backgroundColor = .whiteColor() addSubview(textLabel) addSubview(textField) self.addConstraint(NSLayoutConstraint(item: textField, attribute: .CenterY, relatedBy: .Equal, toItem: textLabel, attribute: .CenterY, multiplier: 1.0, constant: 0)) self.addConstraint(NSLayoutConstraint(item: textField, attribute: .Left, relatedBy: .Equal, toItem: textLabel, attribute: .Right, multiplier: 1.0, constant: 10.0)) self.addConstraint(NSLayoutConstraint(item: textLabel, attribute: .Left, relatedBy: .Equal, toItem: self, attribute: .LeftMargin , multiplier: 1.0, constant: 0)) self.addConstraint(NSLayoutConstraint(item: textField, attribute: .Right, relatedBy: .Equal, toItem: self, attribute: .RightMargin , multiplier: 1.0, constant: 0)) self.addConstraint(NSLayoutConstraint(item: textLabel, attribute: .Width, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute , multiplier: 1.0, constant: textSize )) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
gpl-2.0
20e48b8ae55884e8244161683ecdca28
39.369565
181
0.676898
4.761538
false
false
false
false
pauljohanneskraft/Algorithms-and-Data-structures
AlgorithmsDataStructures/Classes/Graphs/Graph.swift
1
3475
// // Graph.swift // Algorithms&DataStructures // // Created by Paul Kraft on 09.08.16. // Copyright © 2016 pauljohanneskraft. All rights reserved. // // swiftlint:disable trailing_whitespace public protocol Graph { init() var vertices: Set<Int> { get } var edges: Set<GraphEdge> { get set } subscript(start: Int) -> [(end: Int, weight: Int)] { get } subscript(start: Int, end: Int) -> Int? { get set } } extension Graph { public init(vertices: Set<Int>, rule: (Int, Int) throws -> Int?) rethrows { self.init() for start in vertices { for end in vertices { if let length = try rule(start, end) { self[start, end] = length } } } } public var noEmtpyVertices: Bool { for v in vertices { guard self[v].count > 0 else { return false } } return true } public func unEvenVertices(directed: Bool) -> Int? { var counts = [Int: (incoming: Int, outgoing: Int)]() for v in vertices { counts[v] = (0, 0) } for e in edges { let cstart = counts[e.start]! let cend = counts[e.end ]! counts[e.start ]! = (cstart.0, cstart.1 + 1) counts[e.end ]! = (cend.0 + 1, cend.1) } var count = 0 guard directed else { for c in counts { guard c.value.incoming == c.value.outgoing else { return nil } if c.value.incoming % 2 == 1 { count += 1 } } return count } for v in vertices { let c = counts[v]! if c.0 != c.1 { if abs(c.0 - c.1) == 1 { count += 1 } else { return nil } } } return count } public var directed: Bool { for v in vertices { for e in self[v] { guard self[e.end].contains(where: { $0.end == v }) else { return true } } } return false } public var semiEulerian: Bool { var counts = [Int: (incoming: Int, outgoing: Int)]() for v in vertices { counts[v] = (0, 0) } for e in edges { let cstart = counts[e.start]! let cend = counts[e.end ]! counts[e.start ]! = (cstart.0, cstart.1 + 1) counts[e.end ]! = (cend.0 + 1, cend.1) } var count = 0 for v in vertices { let c = counts[v]! if c.0 != c.1 { if abs(c.0 - c.1) == 1 { count += 1 } else { return false } } } return count == 2 || count == 0 } public var eulerian: Bool { var counts = [Int: (incoming: Int, outgoing: Int)]() for v in vertices { counts[v] = (0, 0) } for e in edges { let cstart = counts[e.start]! let cend = counts[e.end ]! counts[e.start ]! = (cstart.0, cstart.1 + 1) counts[e.end ]! = (cend.0 + 1, cend.1) } for v in vertices { let c = counts[v]! guard c.0 == c.1 else { return false } } return true } public func degree(of vertex: Int) -> Int { return self[vertex].count } public func convert< G: Graph >(to other: G.Type) -> G { var a = other.init() a.edges = self.edges return a } } public func == (lhs: Graph, rhs: Graph) -> Bool { return lhs.edges == rhs.edges } public struct GraphEdge { var start: Int, end: Int, weight: Int } extension GraphEdge: Hashable { public var hashValue: Int { return (start << 32) | end } public static func == (lhs: GraphEdge, rhs: GraphEdge) -> Bool { return lhs.start == rhs.start && lhs.end == rhs.end && lhs.weight == rhs.weight } } extension GraphEdge: CustomStringConvertible { public var description: String { guard weight != 1 else { return "\(start) -> \(end)" } return "\(start) -(\(weight))> \(end)" } }
mit
2569a5d25e69b6037bd9be03ffdaeeb1
22.958621
87
0.574266
2.897415
false
false
false
false
krzysztofzablocki/Sourcery
SourceryRuntime/Sources/Extensions.swift
1
7607
import Foundation public extension StringProtocol { /// Trimms leading and trailing whitespaces and newlines var trimmed: String { self.trimmingCharacters(in: .whitespacesAndNewlines) } } public extension String { /// Returns nil if string is empty var nilIfEmpty: String? { if isEmpty { return nil } return self } /// Returns nil if string is empty or contains `_` character var nilIfNotValidParameterName: String? { if isEmpty { return nil } if self == "_" { return nil } return self } /// :nodoc: /// - Parameter substring: Instance of a substring /// - Returns: Returns number of times a substring appears in self func countInstances(of substring: String) -> Int { guard !substring.isEmpty else { return 0 } var count = 0 var searchRange: Range<String.Index>? while let foundRange = range(of: substring, options: [], range: searchRange) { count += 1 searchRange = Range(uncheckedBounds: (lower: foundRange.upperBound, upper: endIndex)) } return count } /// :nodoc: /// Removes leading and trailing whitespace from str. Returns false if str was not altered. @discardableResult mutating func strip() -> Bool { let strippedString = stripped() guard strippedString != self else { return false } self = strippedString return true } /// :nodoc: /// Returns a copy of str with leading and trailing whitespace removed. func stripped() -> String { return String(self.trimmingCharacters(in: .whitespaces)) } /// :nodoc: @discardableResult mutating func trimPrefix(_ prefix: String) -> Bool { guard hasPrefix(prefix) else { return false } self = String(self.suffix(self.count - prefix.count)) return true } /// :nodoc: func trimmingPrefix(_ prefix: String) -> String { guard hasPrefix(prefix) else { return self } return String(self.suffix(self.count - prefix.count)) } /// :nodoc: @discardableResult mutating func trimSuffix(_ suffix: String) -> Bool { guard hasSuffix(suffix) else { return false } self = String(self.prefix(self.count - suffix.count)) return true } /// :nodoc: func trimmingSuffix(_ suffix: String) -> String { guard hasSuffix(suffix) else { return self } return String(self.prefix(self.count - suffix.count)) } /// :nodoc: func dropFirstAndLast(_ n: Int = 1) -> String { return drop(first: n, last: n) } /// :nodoc: func drop(first: Int, last: Int) -> String { return String(self.dropFirst(first).dropLast(last)) } /// :nodoc: /// Wraps brackets if needed to make a valid type name func bracketsBalancing() -> String { if hasPrefix("(") && hasSuffix(")") { let unwrapped = dropFirstAndLast() return unwrapped.commaSeparated().count == 1 ? unwrapped.bracketsBalancing() : self } else { let wrapped = "(\(self))" return wrapped.isValidTupleName() || !isBracketsBalanced() ? wrapped : self } } /// :nodoc: /// Returns true if given string can represent a valid tuple type name func isValidTupleName() -> Bool { guard hasPrefix("(") && hasSuffix(")") else { return false } let trimmedBracketsName = dropFirstAndLast() return trimmedBracketsName.isBracketsBalanced() && trimmedBracketsName.commaSeparated().count > 1 } /// :nodoc: func isValidArrayName() -> Bool { if hasPrefix("Array<") { return true } if hasPrefix("[") && hasSuffix("]") { return dropFirstAndLast().colonSeparated().count == 1 } return false } /// :nodoc: func isValidDictionaryName() -> Bool { if hasPrefix("Dictionary<") { return true } if hasPrefix("[") && contains(":") && hasSuffix("]") { return dropFirstAndLast().colonSeparated().count == 2 } return false } /// :nodoc: func isValidClosureName() -> Bool { return components(separatedBy: "->", excludingDelimiterBetween: (["(", "<"], [")", ">"])).count > 1 } /// :nodoc: /// Returns true if all opening brackets are balanced with closed brackets. func isBracketsBalanced() -> Bool { var bracketsCount: Int = 0 for char in self { if char == "(" { bracketsCount += 1 } else if char == ")" { bracketsCount -= 1 } if bracketsCount < 0 { return false } } return bracketsCount == 0 } /// :nodoc: /// Returns components separated with a comma respecting nested types func commaSeparated() -> [String] { return components(separatedBy: ",", excludingDelimiterBetween: ("<[({", "})]>")) } /// :nodoc: /// Returns components separated with colon respecting nested types func colonSeparated() -> [String] { return components(separatedBy: ":", excludingDelimiterBetween: ("<[({", "})]>")) } /// :nodoc: /// Returns components separated with semicolon respecting nested contexts func semicolonSeparated() -> [String] { return components(separatedBy: ";", excludingDelimiterBetween: ("{", "}")) } /// :nodoc: func components(separatedBy delimiter: String, excludingDelimiterBetween between: (open: String, close: String)) -> [String] { return self.components(separatedBy: delimiter, excludingDelimiterBetween: (between.open.map { String($0) }, between.close.map { String($0) })) } /// :nodoc: func components(separatedBy delimiter: String, excludingDelimiterBetween between: (open: [String], close: [String])) -> [String] { var boundingCharactersCount: Int = 0 var quotesCount: Int = 0 var item = "" var items = [String]() var i = self.startIndex while i < self.endIndex { var offset = 1 defer { i = self.index(i, offsetBy: offset) } let currentlyScanned = self[i..<(self.index(i, offsetBy: delimiter.count, limitedBy: self.endIndex) ?? self.endIndex)] if let openString = between.open.first(where: { String(self[i...]).starts(with: $0) }) { if !(boundingCharactersCount == 0 && String(self[i]) == delimiter) { boundingCharactersCount += 1 } offset = openString.count } else if let closeString = between.close.first(where: { String(self[i...]).starts(with: $0) }) { // do not count `->` if !(self[i] == ">" && item.last == "-") { boundingCharactersCount = max(0, boundingCharactersCount - 1) } offset = closeString.count } if self[i] == "\"" { quotesCount += 1 } if currentlyScanned == delimiter && boundingCharactersCount == 0 && quotesCount % 2 == 0 { items.append(item) item = "" i = self.index(i, offsetBy: delimiter.count - 1) } else { item += self[i..<self.index(i, offsetBy: offset)] } } items.append(item) return items } } public extension NSString { /// :nodoc: var entireRange: NSRange { return NSRange(location: 0, length: self.length) } }
mit
fcca854e1bad6df6bb72ab1d9f6fabc3
32.511013
150
0.572368
4.684113
false
false
false
false
arn00s/caralho
Sources/CaralhoText.swift
1
830
// // CaralhoText.swift // caralho // // Created by Arnaud Schloune on 20/10/2017. // Copyright © 2017 Arnaud Schloune. All rights reserved. // import Foundation import UIKit class CaralhoText { var text: String = "" var time: Double = 0.0 var backgroundImage: UIImage? var position: Int var inAnimation: UITableViewRowAnimation var outAnimation: UITableViewRowAnimation init(text: String, time: Double, image: UIImage? = nil, position: Int, inAnimation: UITableViewRowAnimation = .middle, outAnimation: UITableViewRowAnimation = .middle) { self.text = text self.time = time self.backgroundImage = image self.position = position self.inAnimation = inAnimation self.outAnimation = outAnimation } }
mit
3cefa786efffb4e22af26ffe8a7792ef
24.121212
59
0.648975
4.273196
false
false
false
false
Brightify/DataMapper
Source/Core/Map/DeserializableMappableDataWrapper.swift
1
5695
// // DeserializableMappableDataWrapper.swift // DataMapper // // Created by Filip Dolnik on 23.10.16. // Copyright © 2016 Brightify. All rights reserved. // public struct DeserializableMappableDataWrapper: MappableData { public let delegate: DeserializableData public init(delegate: DeserializableData) { self.delegate = delegate } public subscript(path: [String]) -> MappableData { get { return DeserializableMappableDataWrapper(delegate: delegate[path]) } set { // Intentionally left empty to conform protocol requirements. } } public subscript(path: String...) -> MappableData { get { return self[path] } set { self[path] = newValue } } public func map<T: SerializableAndDeserializable>(_ value: inout T?) { value = delegate.get() } public func map<T: SerializableAndDeserializable>(_ value: inout T, or: T) { value = delegate.get(or: or) } public func map<T: SerializableAndDeserializable>(_ value: inout T) throws { value = try delegate.get() } public func map<T: SerializableAndDeserializable>(_ array: inout [T]?) { array = delegate.get() } public func map<T: SerializableAndDeserializable>(_ array: inout [T], or: [T]) { array = delegate.get(or: or) } public func map<T: SerializableAndDeserializable>(_ array: inout [T]) throws { array = try delegate.get() } public func map<T: SerializableAndDeserializable>(_ array: inout [T?]?) { array = delegate.get() } public func map<T: SerializableAndDeserializable>(_ array: inout [T?], or: [T?]) { array = delegate.get(or: or) } public func map<T: SerializableAndDeserializable>(_ array: inout [T?]) throws { array = try delegate.get() } public func map<T: SerializableAndDeserializable>(_ dictionary: inout [String: T]?) { dictionary = delegate.get() } public func map<T: SerializableAndDeserializable>(_ dictionary: inout [String: T], or: [String: T]) { dictionary = delegate.get(or: or) } public func map<T: SerializableAndDeserializable>(_ dictionary: inout [String: T]) throws { dictionary = try delegate.get() } public func map<T: SerializableAndDeserializable>(_ dictionary: inout [String: T?]?) { dictionary = delegate.get() } public func map<T: SerializableAndDeserializable>(_ dictionary: inout [String: T?], or: [String: T?]) { dictionary = delegate.get(or: or) } public func map<T: SerializableAndDeserializable>(_ dictionary: inout [String: T?]) throws { dictionary = try delegate.get() } public func map<T, R: Transformation>(_ value: inout T?, using transformation: R) where R.Object == T { value = delegate.get(using: transformation) } public func map<T, R: Transformation>(_ value: inout T, using transformation: R, or: T) where R.Object == T { value = delegate.get(using: transformation, or: or) } public func map<T, R: Transformation>(_ value: inout T, using transformation: R) throws where R.Object == T { value = try delegate.get(using: transformation) } public func map<T, R: Transformation>(_ array: inout [T]?, using transformation: R) where R.Object == T { array = delegate.get(using: transformation) } public func map<T, R: Transformation>(_ array: inout [T], using transformation: R, or: [T]) where R.Object == T { array = delegate.get(using: transformation, or: or) } public func map<T, R: Transformation>(_ array: inout [T], using transformation: R) throws where R.Object == T { array = try delegate.get(using: transformation) } public func map<T, R: Transformation>(_ array: inout [T?]?, using transformation: R) where R.Object == T { array = delegate.get(using: transformation) } public func map<T, R: Transformation>(_ array: inout [T?], using transformation: R, or: [T?]) where R.Object == T { array = delegate.get(using: transformation, or: or) } public func map<T, R: Transformation>(_ array: inout [T?], using transformation: R) throws where R.Object == T { array = try delegate.get(using: transformation) } public func map<T, R: Transformation>(_ dictionary: inout [String: T]?, using transformation: R) where R.Object == T { dictionary = delegate.get(using: transformation) } public func map<T, R: Transformation>(_ dictionary: inout [String: T], using transformation: R, or: [String: T]) where R.Object == T { dictionary = delegate.get(using: transformation, or: or) } public func map<T, R: Transformation>(_ dictionary: inout [String: T], using transformation: R) throws where R.Object == T { dictionary = try delegate.get(using: transformation) } public func map<T, R: Transformation>(_ dictionary: inout [String: T?]?, using transformation: R) where R.Object == T { dictionary = delegate.get(using: transformation) } public func map<T, R: Transformation>(_ dictionary: inout [String: T?], using transformation: R, or: [String: T?]) where R.Object == T { dictionary = delegate.get(using: transformation, or: or) } public func map<T, R: Transformation>(_ dictionary: inout [String: T?], using transformation: R) throws where R.Object == T { dictionary = try delegate.get(using: transformation) } }
mit
559461535e66c01aa3655867ce531d30
35.974026
140
0.620829
4.217778
false
false
false
false
onevcat/CotEditor
CotEditor/Sources/DraggableArrayController.swift
2
3835
// // DraggableArrayController.swift // // CotEditor // https://coteditor.com // // Created by 1024jp on 2014-08-18. // // --------------------------------------------------------------------------- // // © 2014-2021 1024jp // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import Cocoa final class DraggableArrayController: NSArrayController, NSTableViewDataSource { // MARK: Table Data Source Protocol /// start dragging func tableView(_ tableView: NSTableView, pasteboardWriterForRow row: Int) -> NSPasteboardWriting? { tableView.registerForDraggedTypes([.string]) let item = NSPasteboardItem() item.setString(String(row), forType: .string) return item } /// validate when dragged items come to tableView func tableView(_ tableView: NSTableView, validateDrop info: NSDraggingInfo, proposedRow row: Int, proposedDropOperation dropOperation: NSTableView.DropOperation) -> NSDragOperation { // accept only self drag-and-drop guard info.draggingSource as? NSTableView == tableView else { return [] } if dropOperation == .on { tableView.setDropRow(row, dropOperation: .above) } return .move } /// check acceptability of dragged items and insert them to table func tableView(_ tableView: NSTableView, acceptDrop info: NSDraggingInfo, row: Int, dropOperation: NSTableView.DropOperation) -> Bool { // accept only self drag-and-drop guard info.draggingSource as? NSTableView == tableView else { return false } // obtain original rows from pasteboard var sourceRows = IndexSet() info.enumerateDraggingItems(options: .concurrent, for: tableView, classes: [NSPasteboardItem.self]) { (item, _, _) in guard let string = (item.item as? NSPasteboardItem)?.string(forType: .string), let row = Int(string) else { return } sourceRows.insert(row) } let draggingItems = (self.arrangedObjects as AnyObject).objects(at: sourceRows) let destinationRow = row - sourceRows.count(in: 0...row) // real insertion point after removing items to move let destinationRows = IndexSet(destinationRow..<(destinationRow + draggingItems.count)) // update NSAnimationContext.runAnimationGroup({ _ in // update UI var sourceOffset = 0 var destinationOffset = 0 tableView.beginUpdates() for sourceRow in sourceRows { if sourceRow < row { tableView.moveRow(at: sourceRow + sourceOffset, to: row - 1) sourceOffset -= 1 } else { tableView.moveRow(at: sourceRow, to: row + destinationOffset) destinationOffset += 1 } } tableView.endUpdates() }, completionHandler: { // update data self.remove(atArrangedObjectIndexes: sourceRows) self.insert(contentsOf: draggingItems, atArrangedObjectIndexes: destinationRows) }) return true } }
apache-2.0
34d0f50fa3cd30b73ce3558b8b6bfbb1
35.169811
186
0.603547
5.071429
false
false
false
false
snakajima/remoteio
ios/remoteio/remoteio/RoomPicker.swift
1
2186
// // RoomPicker // ioswall // // Created by satoshi on 10/20/16. // Copyright © 2016 UIEvolution Inc. All rights reserved. // import UIKit class RoomPicker: UITableViewController { var handler:SocketHandler! var rooms = [[String:Any]]() var room:[String:Any]? let notificationManger = SNNotificationManager() override func viewDidLoad() { super.viewDidLoad() self.title = "Rooms" notificationManger.addObserver(forName: SocketHandler.didConnectionChange, object: nil, queue: OperationQueue.main) { [unowned self] (_) in self.tableView.reloadData() } notificationManger.addObserver(forName: SocketHandler.didLoadConfig, object: nil, queue: OperationQueue.main) { [unowned self] (_) in self.tableView.reloadData() } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { rooms = handler.rooms return handler.connected ? rooms.count : 0 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = self.tableView.dequeueReusableCell(withIdentifier: "standard", for: indexPath) cell.textLabel?.text = rooms[indexPath.row]["name"] as? String return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { room = rooms[indexPath.row] if let name = room?["name"] as? String { handler.switchTo(room:name) performSegue(withIdentifier: "room", sender: nil) } tableView.deselectRow(at: indexPath, animated: true) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let vc = segue.destination as? ScenePicker, let name = room?["name"] as? String { vc.room = name vc.handler = handler } } }
mit
b0e1f4cb57b1cbdd1c71f368a6a50723
33.140625
147
0.646682
4.760349
false
false
false
false
syd24/DouYuZB
DouYu/DouYu/classes/main/view/PageContentView.swift
1
5011
// // PageContentView.swift // DouYu // // Created by Kobe24 on 16/10/23. // Copyright © 2016年 ADMIN. All rights reserved. // import UIKit protocol PageContentViewDelegate:class { func pageContentView(pageContentView: PageContentView , progress: CGFloat , sourceIndex: Int, targetIndex: Int); } private let cellID = "cellID"; class PageContentView: UIView { weak var delegate:PageContentViewDelegate?; fileprivate var isForbidScrollDelegate : Bool = false fileprivate var startOffsetX : CGFloat = 0; fileprivate let _controllers : [UIViewController]; fileprivate let _parentViewController: UIViewController; fileprivate lazy var collectionView : UICollectionView = {[weak self] in let layout = UICollectionViewFlowLayout(); layout.minimumLineSpacing = 0; layout.minimumInteritemSpacing = 0; layout.itemSize = (self?.bounds.size)!; layout.scrollDirection = .horizontal; let collectionview = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout); collectionview.bounces = false; collectionview.showsHorizontalScrollIndicator = false; collectionview.isPagingEnabled = true; collectionview.dataSource = self; collectionview.delegate = self; collectionview.register(UICollectionViewCell.self, forCellWithReuseIdentifier: cellID); return collectionview; }() //初始化方法 init(frame: CGRect , controllers:[UIViewController] , parentController:UIViewController?) { self._controllers = controllers; self._parentViewController = parentController!; super.init(frame: frame); setupUI(); } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } extension PageContentView{ fileprivate func setupUI(){ addSubview(collectionView); collectionView.frame = bounds; for vc in _controllers { _parentViewController.addChildViewController(vc); } } } extension PageContentView: UICollectionViewDataSource{ func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return _controllers.count; } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let item = collectionView.dequeueReusableCell(withReuseIdentifier: cellID, for: indexPath); //移除视图 for view in item.contentView.subviews { view.removeFromSuperview(); } let chirldVC = _controllers[indexPath.item]; chirldVC.view.frame = item.contentView.bounds; item.contentView.addSubview(chirldVC.view); return item; } } extension PageContentView: UICollectionViewDelegate{ func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { isForbidScrollDelegate = false startOffsetX = scrollView.contentOffset.x; } func scrollViewDidScroll(_ scrollView: UIScrollView) { if isForbidScrollDelegate { return } var progress: CGFloat = 0; var sourceIndex: Int = 0; var targetIndex: Int = 0; let currentOffsetX = scrollView.contentOffset.x; let scrollViewW = scrollView.frame.width; if currentOffsetX > startOffsetX {//向左 progress = currentOffsetX / scrollViewW - floor(currentOffsetX / scrollViewW); sourceIndex = Int(currentOffsetX / scrollViewW); targetIndex = sourceIndex + 1; if targetIndex >= _controllers.count { targetIndex = _controllers.count - 1; } if currentOffsetX - startOffsetX == scrollViewW { progress = 1; targetIndex = sourceIndex; } }else{ progress = 1 - (currentOffsetX/scrollViewW - floor(currentOffsetX/scrollViewW)); targetIndex = Int(currentOffsetX/scrollViewW); sourceIndex = targetIndex + 1; if sourceIndex >= _controllers.count { sourceIndex = _controllers.count - 1; } } delegate?.pageContentView(pageContentView: self, progress: progress, sourceIndex: sourceIndex, targetIndex: targetIndex); } } extension PageContentView{ func setCurrentIndex(currentIndex : Int) { isForbidScrollDelegate = true let offX = CGFloat(currentIndex) * collectionView.frame.width; collectionView.setContentOffset(CGPoint(x: offX, y: 0), animated: true); } }
mit
cb826be2d7d386e78c4a04cca0f3754b
27.820809
129
0.613718
6.029021
false
false
false
false
YouareMylovelyGirl/Sina-Weibo
新浪微博/新浪微博/Classes/Tools(工具)/RefreshControl/RefreshView.swift
1
2335
// // RefreshView.swift // 刷新控件 // // Created by 阳光 on 2017/6/13. // Copyright © 2017年 YG. All rights reserved. // import UIKit /// 刷新视图 - 负责刷新相关的 UI 显示和动画 class RefreshView: UIView { /// 刷新状态 /** iOS 系统中 UIView 封装的旋转动画 - 默认顺时针旋转 - 就近原则 - 要想实现同方向旋转,需要调整一个 非常小的数字(近) - 如果想实现 360 旋转,需要核心动画 CABaseAnimation */ var refreshState: RefreshState = .Normal { didSet { switch refreshState { case .Normal: // 恢复状态 tipIcon?.isHidden = false indicator?.stopAnimating() tipLabel?.text = "继续使劲拉..." UIView.animate(withDuration: 0.25) { self.tipIcon?.transform = CGAffineTransform.identity } case .Pulling: tipLabel?.text = "放手就刷新..." UIView.animate(withDuration: 0.25) { self.tipIcon?.transform = CGAffineTransform(rotationAngle: CGFloat(Double.pi + 0.001)) } case .WillRefresh: tipLabel?.text = "正在刷新中..." // 隐藏提示图标 tipIcon?.isHidden = true // 显示菊花 indicator?.startAnimating() } } } /// 父视图的高度 - 为了刷新控件不需要关心当前具体的刷新视图是谁! var parentViewHeight: CGFloat = 0 //提示图标 @IBOutlet weak var tipIcon: UIImageView? //指示器 @IBOutlet weak var indicator: UIActivityIndicatorView? //提示标签 @IBOutlet weak var tipLabel: UILabel? class func refreshView() -> RefreshView { let nib = UINib(nibName: "MTRefreshView", bundle: nil) return nib.instantiate(withOwner: nil, options: nil)[0] as! RefreshView } }
apache-2.0
ebe1ee2857d7b4f2d0a18a4e77f137dc
26.753425
110
0.457058
4.89372
false
false
false
false
xeecos/motionmaker
GIFMaker/SettingViewController.swift
1
5973
// // SettingViewController.swift // GIFMaker // // Created by indream on 15/9/20. // Copyright © 2015年 indream. All rights reserved. // import UIKit class SettingViewController: UIViewController,UITableViewDataSource,UITableViewDelegate { @IBOutlet weak var videoView: UIView! @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var tableView: UITableView! override func viewDidLoad() { super.viewDidLoad() self.titleLabel.text = NSLocalizedString("Setting", comment: "") // Do any additional setup after loading the view. } override func viewDidAppear(_ animated: Bool) { if((self.videoView)==nil){ }else{ VideoManager.sharedManager().configVideoView(self.videoView!) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func backHandle(_ sender: AnyObject) { DataManager.sharedManager().save() self.dismiss(animated: true) { () -> Void in } } /* // 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. } */ @IBAction func focusSwitch(_ sender: AnyObject) { } @IBAction func addCameraHandle(_ sender: AnyObject) { DataManager.sharedManager().createCamera(0,cid:DataManager.sharedManager().countOfCamera(0)); self.tableView.reloadData() } @IBAction func removeCameraHandle(_ sender: AnyObject) { let count:Int16 = DataManager.sharedManager().countOfCamera(0) if(count>2){ DataManager.sharedManager().removeCamera(0,cid:count-1); self.tableView.reloadData() } } func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { var title:String? switch(section){ case 0: title = NSLocalizedString("Mode", comment: "") break case 1: title = NSLocalizedString("Resolution", comment: "") break case 2: title = NSLocalizedString("Start", comment: "") break default: break } if(section==tableView.numberOfSections-1){ title = NSLocalizedString("Add", comment: "") }else if(section==tableView.numberOfSections-2){ title = NSLocalizedString("End", comment: "") }else if(section>2){ title = "# \(section-2)" } return title } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 1 } func numberOfSections(in tableView: UITableView) ->Int { return Int(DataManager.sharedManager().countOfCamera(0))+3 } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { var height:CGFloat = 44.0 let section:NSInteger = indexPath.section if(section==tableView.numberOfSections-2){ height = 196 }else if(section==tableView.numberOfSections-1){ height = 44 }else if(section>1){ height = 300 }else{ height = 44 } return height } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var cell:UITableViewCell? let section = indexPath.section switch(section){ case 0: cell = tableView.dequeueReusableCell(withIdentifier: "modeSettingCell") if(cell==nil){ cell = Bundle.main.loadNibNamed("SettingCells", owner: self, options: nil)?[0] as? UITableViewCell; } break case 1: cell = tableView.dequeueReusableCell(withIdentifier: "resolutionSettingCell") if(cell==nil){ cell = Bundle.main.loadNibNamed("SettingCells", owner: self, options: nil)?[1] as? UITableViewCell; } break default: break } if(section==tableView.numberOfSections-1){ cell = tableView.dequeueReusableCell(withIdentifier: "addSettingCell") if(cell==nil){ cell = Bundle.main.loadNibNamed("SettingCells", owner: self, options: nil)?[4] as? UITableViewCell; } }else if(section==tableView.numberOfSections-2){ cell = tableView.dequeueReusableCell(withIdentifier: "endSettingCell") if(cell==nil){ cell = Bundle.main.loadNibNamed("SettingCells", owner: self, options: nil)?[3] as? UITableViewCell; } (cell as! EndCameraSettingCell).setCameraIndex(0, cid: Int16(indexPath.section-2)) (cell as! EndCameraSettingCell).assignTableView(self.tableView) }else if(section>1){ cell = tableView.dequeueReusableCell(withIdentifier: "cameraSettingCell") if(cell==nil){ cell = Bundle.main.loadNibNamed("SettingCells", owner: self, options: nil)?[2] as? UITableViewCell; } (cell as! CameraSettingCell).setCameraIndex(0, cid: Int16(indexPath.section-2)) (cell as! CameraSettingCell).assignTableView(self.tableView) } return cell! } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { } override var supportedInterfaceOrientations : UIInterfaceOrientationMask { return UIInterfaceOrientationMask.landscapeRight; } override var prefersStatusBarHidden : Bool { return false; } }
mit
70c106818f033dbe3d83c6605bcefc87
35.851852
119
0.61139
5.098207
false
false
false
false
Raizlabs/Anchorage
AnchorageDemo/Cells/EqualSpaceViewCell.swift
1
2749
// // EqualSpaceViewCell.swift // AnchorageDemo // // Created by Connor Neville on 9/21/16. // Copyright © 2016 Connor Neville. All rights reserved. // import UIKit import Anchorage class EqualSpaceViewCell: BaseCell { override class func reuseId() -> String { return "EqualSpaceViewCell" } let bodyLabel: UILabel = { let l = UILabel() l.text = "These views take up the width of the cell by pinning to its leading, trailing, and having a constant space in between. Tap to adjust the space in between." l.font = UIFont.systemFont(ofSize: 12.0) l.numberOfLines = 0 return l }() let views: [UIView] = { var views: [UIView] = [] for i in 0...5 { let view = UIView() view.backgroundColor = (i % 2 == 0) ? UIColor.green : UIColor.cyan views.append(view) } return views }() // Here we have an array of constraints that we'll alter later. var spacingConstraints: [NSLayoutConstraint] = [] override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) configureView() configureLayout() } override func update(forDataSource dataSource: RootViewDataSource) { for constraint in spacingConstraints { constraint.constant = dataSource.equalSpacingConstraintConstant } layoutIfNeeded() } } private extension EqualSpaceViewCell { func configureView() { contentView.addSubview(bodyLabel) for view in views { contentView.addSubview(view) } } func configureLayout() { bodyLabel.topAnchor == contentView.topAnchor bodyLabel.horizontalAnchors == contentView.horizontalAnchors + 10 guard let first = views.first, let last = views.last else { preconditionFailure("Empty views array in EqualSpaceViewCell") } first.leadingAnchor == contentView.leadingAnchor first.topAnchor == bodyLabel.bottomAnchor + 5 first.heightAnchor == 30 first.bottomAnchor == contentView.bottomAnchor for i in 1..<views.count { views[i].widthAnchor == first.widthAnchor views[i].topAnchor == first.topAnchor views[i].bottomAnchor == first.bottomAnchor // Each view's leading anchor is at the previous view's trailing anchor. // As long as you're targeting iOS 9+, situations like this can often be handled with UIStackView. spacingConstraints.append(views[i].leadingAnchor == views[i - 1].trailingAnchor) } last.trailingAnchor == contentView.trailingAnchor } }
mit
bd23411d34ac9f7649f7754164c75fe3
32.108434
173
0.639738
4.907143
false
false
false
false
vmanot/swift-package-manager
Sources/Build/llbuild.swift
1
9340
/* This source file is part of the Swift.org open source project Copyright 2015 - 2016 Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for Swift project authors */ import Basic import Utility import PackageModel import PackageGraph /// llbuild manifest file generator for a build plan. public struct LLBuildManifestGenerator { /// The name of the llbuild target that builds all products and targets (excluding tests). public static let llbuildMainTargetName = "main" /// The name of the llbuild target that builds all products and targets (including tests). public static let llbuildTestTargetName = "test" /// The build plan to work on. public let plan: BuildPlan /// Create a new generator with a build plan. public init(_ plan: BuildPlan) { self.plan = plan } /// A structure for targets in the manifest. private struct Targets { /// Main target. private(set) var main = Target(name: LLBuildManifestGenerator.llbuildMainTargetName) /// Test target. private(set) var test = Target(name: LLBuildManifestGenerator.llbuildTestTargetName) /// All targets. var allTargets: [Target] { return [main, test] + otherTargets.sorted(by: { $0.name < $1.name }) } /// All commands. private(set) var allCommands = SortedArray<Command>(areInIncreasingOrder: <) /// Other targets. private var otherTargets: [Target] = [] /// Append a command. mutating func append(_ target: Target, isTest: Bool) { // Create a phony command with a virtual output node that represents the target. let virtualNodeName = "<\(target.name)>" let phonyTool = PhonyTool(inputs: target.outputs.values, outputs: [virtualNodeName]) let phonyCommand = Command(name: "<C.\(target.name)>", tool: phonyTool) // Use the phony command as dependency. var newTarget = target newTarget.outputs.insert(virtualNodeName) newTarget.cmds.insert(phonyCommand) otherTargets.append(newTarget) if !isTest { main.outputs += newTarget.outputs main.cmds += newTarget.cmds } // Always build everything for the test target. test.outputs += newTarget.outputs test.cmds += newTarget.cmds allCommands += newTarget.cmds } } /// Generate manifest at the given path. public func generateManifest(at path: AbsolutePath) throws { var targets = Targets() // Create commands for all target description in the plan. for buildTarget in plan.targets { switch buildTarget { case .swift(let target): targets.append(createSwiftCompileTarget(target), isTest: target.isTestTarget) case .clang(let target): targets.append(createClangCompileTarget(target), isTest: target.isTestTarget) } } // Create command for all products in the plan. for buildProduct in plan.buildProducts { targets.append(createProductTarget(buildProduct), isTest: buildProduct.product.type == .test) } // Write the manifest. let stream = BufferedOutputByteStream() stream <<< """ client: name: swift-build tools: {} targets:\n """ for target in targets.allTargets { stream <<< " " <<< Format.asJSON(target.name) stream <<< ": " <<< Format.asJSON(target.outputs.values) <<< "\n" } stream <<< "default: " <<< Format.asJSON(targets.main.name) <<< "\n" stream <<< "commands: \n" for command in targets.allCommands.sorted(by: { $0.name < $1.name }) { stream <<< " " <<< Format.asJSON(command.name) <<< ":\n" command.tool.append(to: stream) stream <<< "\n" } try localFileSystem.writeFileContents(path, bytes: stream.bytes) } /// Create a llbuild target for a product description. private func createProductTarget(_ buildProduct: ProductBuildDescription) -> Target { let tool: ToolProtocol // Create archive tool for static library and shell tool for rest of the products. if buildProduct.product.type == .library(.static) { tool = ArchiveTool( inputs: buildProduct.objects.map({ $0.asString }), outputs: [buildProduct.binary.asString]) } else { let inputs = buildProduct.objects + buildProduct.dylibs.map({ $0.binary }) tool = ShellTool( description: "Linking \(buildProduct.binary.prettyPath)", inputs: inputs.map({ $0.asString }), outputs: [buildProduct.binary.asString], args: buildProduct.linkArguments()) } var target = Target(name: buildProduct.product.llbuildTargetName) target.outputs.insert(contentsOf: tool.outputs) target.cmds.insert(Command(name: buildProduct.product.commandName, tool: tool)) return target } /// Create a llbuild target for a Swift target description. private func createSwiftCompileTarget(_ target: SwiftTargetDescription) -> Target { // Compute inital inputs. var inputs = SortedArray<String>() inputs += target.target.sources.paths.map({ $0.asString }) func addStaticTargetInputs(_ target: ResolvedTarget) { // Ignore C Modules. if target.underlyingTarget is CTarget { return } switch plan.targetMap[target] { case .swift(let target)?: inputs.insert(target.moduleOutputPath.asString) case .clang(let target)?: inputs += target.objects.map({ $0.asString }) case nil: fatalError("unexpected: target \(target) not in target map \(plan.targetMap)") } } for dependency in target.target.dependencies { switch dependency { case .target(let target): addStaticTargetInputs(target) case .product(let product): switch product.type { case .executable, .library(.dynamic): // Establish a dependency on binary of the product. inputs += [plan.productMap[product]!.binary.asString] // For automatic and static libraries, add their targets as static input. case .library(.automatic), .library(.static): for target in product.targets { addStaticTargetInputs(target) } case .test: break } } } var buildTarget = Target(name: target.target.llbuildTargetName) // The target only cares about the module output. buildTarget.outputs.insert(target.moduleOutputPath.asString) let tool = SwiftCompilerTool(target: target, inputs: inputs.values) buildTarget.cmds.insert(Command(name: target.target.commandName, tool: tool)) return buildTarget } /// Create a llbuild target for a Clang target description. private func createClangCompileTarget(_ target: ClangTargetDescription) -> Target { let commands: [Command] = target.compilePaths().map({ path in var args = target.basicArguments() args += ["-MD", "-MT", "dependencies", "-MF", path.deps.asString] args += ["-c", path.source.asString, "-o", path.object.asString] let clang = ClangTool( desc: "Compile \(target.target.name) \(path.filename.asString)", //FIXME: Should we add build time dependency on dependent targets? inputs: [path.source.asString], outputs: [path.object.asString], args: [plan.buildParameters.toolchain.clangCompiler.asString] + args, deps: path.deps.asString) return Command(name: path.object.asString, tool: clang) }) // For Clang, the target requires all command outputs. var buildTarget = Target(name: target.target.llbuildTargetName) buildTarget.outputs.insert(contentsOf: commands.flatMap({ $0.tool.outputs })) buildTarget.cmds += commands return buildTarget } } extension ResolvedTarget { public var llbuildTargetName: String { return "\(name).module" } var commandName: String { return "C.\(llbuildTargetName)" } } extension ResolvedProduct { public var llbuildTargetName: String { switch type { case .library(.dynamic): return "\(name).dylib" case .test: return "\(name).test" case .library(.static): return "\(name).a" case .library(.automatic): fatalError() case .executable: return "\(name).exe" } } var commandName: String { return "C.\(llbuildTargetName)" } }
apache-2.0
16d3fdf7e8b0fd17a71af619f30cb533
37.278689
105
0.599358
4.73151
false
true
false
false
bamzy/goQueer-iOS
GoQueer/RadioButtonController.swift
1
3465
// // RadioButtonController.swift // GoQueer // // Created by Circa Lab on 2017-11-04. // Copyright © 2017 Kode. All rights reserved. // import Foundation import UIKit /// RadioButtonControllerDelegate. Delegate optionally implements didSelectButton that receives selected button. @objc protocol RadioButtonControllerDelegate { /** This function is called when a button is selected. If 'shouldLetDeSelect' is true, and a button is deselected, this function is called with a nil. */ @objc func didSelectButton(selectedButton: UIButton?) } class RadioButtonsController : NSObject { fileprivate var buttonsArray = [UIButton]() var delegate : RadioButtonControllerDelegate? = nil /** Set whether a selected radio button can be deselected or not. Default value is false. */ var shouldLetDeSelect = false /** Variadic parameter init that accepts UIButtons. - parameter buttons: Buttons that should behave as Radio Buttons */ init(buttons: UIButton...) { super.init() for aButton in buttons { aButton.addTarget(self, action: #selector(RadioButtonsController.pressed(_:)), for: UIControlEvents.touchUpInside) } self.buttonsArray = buttons } /** Add a UIButton to Controller - parameter button: Add the button to controller. */ func addButton(_ aButton: UIButton) { buttonsArray.append(aButton) aButton.addTarget(self, action: #selector(RadioButtonsController.pressed(_:)), for: UIControlEvents.touchUpInside) } /** Remove a UIButton from controller. - parameter button: Button to be removed from controller. */ func removeButton(_ aButton: UIButton) { var iteratingButton: UIButton? = nil if(buttonsArray.contains(aButton)) { iteratingButton = aButton } if(iteratingButton != nil) { buttonsArray.remove(at: buttonsArray.index(of: iteratingButton!)!) iteratingButton!.removeTarget(self, action: #selector(RadioButtonsController.pressed(_:)), for: UIControlEvents.touchUpInside) iteratingButton!.isSelected = false } } /** Set an array of UIButons to behave as controller. - parameter buttonArray: Array of buttons */ func setButtonsArray(_ aButtonsArray: [UIButton]) { for aButton in aButtonsArray { aButton.addTarget(self, action: #selector(RadioButtonsController.pressed(_:)), for: UIControlEvents.touchUpInside) } buttonsArray = aButtonsArray } @objc func pressed(_ sender: UIButton) { var currentSelectedButton: UIButton? = nil if(sender.isSelected) { if shouldLetDeSelect { sender.isSelected = false currentSelectedButton = nil } } else { for aButton in buttonsArray { aButton.isSelected = false } sender.isSelected = true currentSelectedButton = sender } delegate?.didSelectButton(selectedButton: currentSelectedButton) } /** Get the currently selected button. - returns: Currenlty selected button. */ func selectedButton() -> UIButton? { guard let index = buttonsArray.index(where: { button in button.isSelected }) else { return nil } return buttonsArray[index] } }
mit
99821d5a25512d77215eed6c66423d3a
32.631068
138
0.643476
5.193403
false
false
false
false
blerchy/EssenceOfDesign
Essence/ViewController.swift
1
6239
// // ViewController.swift // Essence // // Created by Matt Lebl on 2015-08-10. // Copyright (c) 2015 Matt Lebl. All rights reserved. // // // ______ __ _____ _ // | ____| / _| | __ \ (_) // | |__ ___ ___ ___ _ __ ___ ___ ___ | |_ | | | | ___ ___ _ __ _ _ __ // | __| / __/ __|/ _ \ '_ \ / __/ _ \ / _ \| _| | | | |/ _ \/ __| |/ _` | '_ \ // | |____\__ \__ \ __/ | | | (_| __/ | (_) | | | |__| | __/\__ \ | (_| | | | | // |______|___/___/\___|_| |_|\___\___| \___/|_| |_____/ \___||___/_|\__, |_| |_| // __/ | // |___/ import UIKit class ViewController: UIViewController { @IBOutlet weak var reminderLabel: UILabel! @IBOutlet weak var title1Label: UILabel! @IBOutlet weak var title2Label: UILabel! @IBOutlet weak var zenLabel: UILabel! @IBOutlet weak var zenVerticalConstraint: NSLayoutConstraint! override func preferredStatusBarStyle() -> UIStatusBarStyle { return UIStatusBarStyle.LightContent; } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. hideZen(false) } override func viewDidAppear(animated: Bool) { getZen() } override func canBecomeFirstResponder() -> Bool { return true } override func motionEnded(motion: UIEventSubtype, withEvent event: UIEvent) { if motion == .MotionShake { self.randomizeColours(true) self.refreshZen(true) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func showZen(animated: Bool) { let duration = 1.5 let offset = -100 if animated { self.zenLabel.alpha = 0 self.zenVerticalConstraint.constant = CGFloat(offset) self.view.layoutIfNeeded() UIView.animateWithDuration(duration, delay: 0, options: UIViewAnimationOptions.CurveEaseOut, animations: { () -> Void in self.zenVerticalConstraint.constant = 0 self.view.layoutIfNeeded() self.zenLabel.alpha = 1.0 println("zen showing, animated") }, completion: nil) } else { self.zenVerticalConstraint.constant = 0 self.view.layoutIfNeeded() self.zenLabel.alpha = 1.0 println("Zen showing, not animated") } println("Zen should be onscreen") } func hideZen(animated: Bool) { let duration = 1.0 if animated { UIView.animateWithDuration(duration, delay: 0, options: UIViewAnimationOptions.CurveEaseInOut, animations: { () -> Void in self.zenLabel.alpha = 0 }, completion: nil) } else { self.zenLabel.alpha = 0 } } func getZen() { let zenURL = NSURL(string: "https://api.github.com/zen") let configuration = NSURLSessionConfiguration.defaultSessionConfiguration() let session = NSURLSession(configuration: configuration) let request = NSURLRequest(URL: zenURL!) let dataTask = session.dataTaskWithRequest(request, completionHandler: { (data, response, error) -> Void in if error == nil { if let string = NSString(data: data, encoding: NSASCIIStringEncoding) as? String { println(string) dispatch_async(dispatch_get_main_queue(), { () -> Void in if string[0] != "{" { self.zenLabel.text = string self.showZen(true) } else { println(string) self.zenLabel.text = "c:" self.showZen(true) self.showNoZensAlert() } }) } else { println("Couldn't convert data to string. Check your encoding!") self.zenLabel.text = "c:" self.showZen(true) self.showNoZensAlert() } } else { println(error) } }) dataTask.resume() } func randomizeColours(animated: Bool) { let colours = [UIColor(rgba: "#EF476F"), UIColor(rgba: "#FFD166"), UIColor(rgba: "#118AB2"), UIColor(rgba: "#063D4C"), UIColor(rgba: "#18F2B0")] let index = Int(arc4random_uniform(UInt32(colours.count))) let duration = 1.0 if animated { UIView.animateWithDuration(duration, delay: 0, options: UIViewAnimationOptions.CurveEaseInOut, animations: { () -> Void in self.view.backgroundColor = colours[index] }, completion: nil) } else { self.view.backgroundColor = colours[index] } } func showNoZensAlert() { let alert = UIAlertController(title: "No Quotes.", message: "There aren't any quotes right now. Check your Internet connection, or try again in a little while.", preferredStyle: UIAlertControllerStyle.Alert) alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Cancel, handler: nil)) self.presentViewController(alert, animated: true, completion: nil) } func refreshZen(animated: Bool) { let duration = 1.0 if animated { UIView.animateWithDuration(duration, delay: 0, options: UIViewAnimationOptions.CurveEaseInOut, animations: { () -> Void in self.zenLabel.alpha = 0 }, completion: {(Bool) -> Void in self.getZen() }) } else { self.zenLabel.alpha = 0 } } }
gpl-3.0
d3a13ddd430841a7dd1c400519c4ec71
33.661111
215
0.493989
4.766234
false
false
false
false
DarkSupremo/CircleSlider
Pod/Classes/TrackLayer.swift
1
2429
// // TrackLayer.swift // Pods // // Created by shushutochako on 11/17/15. // Copyright © 2015 shushutochako. All rights reserved. // import UIKit internal class TrackLayer: CAShapeLayer { struct Setting { var startAngle = Double() var barWidth = CGFloat() var barColor = UIColor() var trackingColor = UIColor() } internal var setting = Setting() internal var degree: Double = 0 internal var hollowRadius: CGFloat { return (self.bounds.width * 0.5) - self.setting.barWidth } internal var currentCenter: CGPoint { return CGPoint(x: self.bounds.midX, y: self.bounds.midY) } internal var hollowRect: CGRect { return CGRect( x: self.currentCenter.x - self.hollowRadius, y: self.currentCenter.y - self.hollowRadius, width: self.hollowRadius * 2.0, height: self.hollowRadius * 2.0) } internal init(bounds: CGRect, setting: Setting) { super.init() self.bounds = bounds self.setting = setting self.cornerRadius = self.bounds.size.width * 0.5 self.masksToBounds = true self.position = self.currentCenter self.backgroundColor = self.setting.barColor.cgColor self.mask() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override internal func draw(in ctx: CGContext) { self.drawTrack(ctx) } fileprivate func mask() { let maskLayer = CAShapeLayer() maskLayer.bounds = self.bounds let ovalRect = self.hollowRect let path = UIBezierPath(ovalIn: ovalRect) path.append(UIBezierPath(rect: maskLayer.bounds)) maskLayer.path = path.cgPath maskLayer.position = self.currentCenter maskLayer.fillRule = kCAFillRuleEvenOdd self.mask = maskLayer } fileprivate func drawTrack(_ ctx: CGContext) { let adjustDegree = Math.adjustDegree(self.setting.startAngle, degree: self.degree) let centerX = self.currentCenter.x let centerY = self.currentCenter.y let radius = min(centerX, centerY) ctx.setFillColor(self.setting.trackingColor.cgColor) ctx.beginPath() ctx.move(to: CGPoint(x: centerX, y: centerY)) ctx.addArc(center: CGPoint(x: centerX, y: centerY), radius: radius, startAngle: CGFloat(Math.degreesToRadians(self.setting.startAngle)), endAngle: CGFloat(Math.degreesToRadians(adjustDegree)), clockwise: false) ctx.closePath(); ctx.fillPath(); } }
mit
fc53bbacb54ee4c355d1d2514db1bef4
30.128205
88
0.688221
3.960848
false
false
false
false
jigneshsheth/Datastructures
DataStructure/DataStructure/TowSum.swift
1
1408
// // TowSum.swift // DataStructure // // Created by Jigs Sheth on 11/2/21. // Copyright © 2021 jigneshsheth.com. All rights reserved. // import Foundation /** Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. You may assume that each input would have exactly one solution, and you may not use the same element twice. You can return the answer in any order. Example 1: Input: nums = [2,7,11,15], target = 9 Output: [0,1] Output: Because nums[0] + nums[1] == 9, we return [0, 1]. Example 2: Input: nums = [3,2,4], target = 6 Output: [1,2] Example 3: Input: nums = [3,3], target = 6 Output: [0,1] - */ class TwoSum { func twoSum(_ nums: [Int], _ target: Int) -> [Int] { var i = 0 var result:[Int] = [] while i < nums.count { result.append(i) let findValue = target - nums[i] var j = i+1 while j < nums.count { if nums[j] == findValue { result.append(j) return result } j += 1 } i += 1 result = [] } return result } func twoSum_Efficient(_ nums:[Int], _ target:Int) -> [Int]{ var dict:[Int:Int] = [:] for index in 0...nums.count{ let value = nums[index] let findValue = target - value if let exitIndex = dict[findValue]{ return [exitIndex,index] }else{ dict[value] = index } } return [-1,-1] } }
mit
7c341b41995a4e24f57b6766a71a949e
18.816901
122
0.597726
2.913043
false
false
false
false
m-alani/contests
leetcode/pascalsTriangleII.swift
1
905
// // pascalsTriangleII.swift // // Practice solution - Marwan Alani - 2017 // // Check the problem (and run the code) on leetCode @ https://leetcode.com/problems/pascals-triangle-ii/ // Note: make sure that you select "Swift" from the top-left language menu of the code editor when testing this code // class Solution { func getRow(_ rowIndex: Int) -> [Int] { var row = Array(repeating: 0, count: rowIndex + 1) var num = Double(rowIndex), den = 1.0, idx = 1 row[0] = 1 // Cover the edge case of index = 0 if rowIndex == 0 { return row } // Find the values for the first half while num >= den { row[idx] = Int(Double(row[idx-1]) * num / den) num -= 1 den += 1 idx += 1 } // Mirror the values to the second half let half = row.count / 2 row[row.count-half...rowIndex] = ArraySlice(row[0..<half].reversed()) return row } }
mit
87384abc65b2a02ccf395d9f578c27ad
27.28125
117
0.61326
3.441065
false
false
false
false
mssun/passforios
passExtension/Controllers/ExtensionViewController.swift
2
5724
// // ExtensionViewController.swift // passExtension // // Created by Yishi Lin on 13/6/17. // Copyright © 2017 Bob Sun. All rights reserved. // import Foundation import MobileCoreServices import passKit class ExtensionViewController: UIViewController { private lazy var passcodelock: PasscodeExtensionDisplay = { [unowned self] in PasscodeExtensionDisplay(extensionContext: extensionContext!) }() private lazy var passwordsViewController: PasswordsViewController = (children.first as! UINavigationController).viewControllers.first as! PasswordsViewController private lazy var credentialProvider: CredentialProvider = { [unowned self] in CredentialProvider(viewController: self, extensionContext: extensionContext!, afterDecryption: NotificationCenterDispatcher.showOTPNotification) }() private lazy var passwordsTableEntries = PasswordStore.shared.fetchPasswordEntityCoreData(withDir: false) .map(PasswordTableEntry.init) enum Action { case findLogin, fillBrowser, unknown } private var action = Action.unknown override func viewDidLoad() { super.viewDidLoad() view.isHidden = true passwordsViewController.dataSource = PasswordsTableDataSource(entries: passwordsTableEntries) passwordsViewController.selectionDelegate = self passwordsViewController.navigationItem.leftBarButtonItem = UIBarButtonItem( barButtonSystemItem: .cancel, target: self, action: #selector(cancel) ) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) prepareCredentialList() passcodelock.presentPasscodeLockIfNeeded(self, after: { [unowned self] in self.view.isHidden = false }) } @objc private func cancel(_: AnyObject?) { extensionContext?.completeRequest(returningItems: nil) } private func prepareCredentialList() { guard let attachments = extensionContext?.attachments else { return } func completeTask(_ text: String?) { DispatchQueue.main.async { self.passwordsViewController.showPasswordsWithSuggestion(matching: text ?? "") self.passwordsViewController.navigationItem.prompt = text } } DispatchQueue.global(qos: .userInitiated).async { for attachment in attachments { if attachment.hasURL { self.action = .fillBrowser attachment.extractSearchText { completeTask($0) } } else if attachment.hasFindLoginAction { self.action = .findLogin attachment.extractSearchText { completeTask($0) } } else if attachment.hasPropertyList { self.action = .fillBrowser attachment.extractSearchText { completeTask($0) } } else { self.action = .unknown } } } } } extension ExtensionViewController: PasswordSelectionDelegate { func selected(password: PasswordTableEntry) { switch action { case .findLogin: credentialProvider.provideCredentialsFindLogin(with: password.passwordEntity.getPath()) case .fillBrowser: credentialProvider.provideCredentialsBrowser(with: password.passwordEntity.getPath()) default: extensionContext?.completeRequest(returningItems: nil, completionHandler: nil) } } } extension NSDictionary { func extractSearchText() -> String? { if let value = self[PassExtensionKey.URLStringKey] as? String { if let host = URL(string: value)?.host { return host } return value } else if let value = self[NSExtensionJavaScriptPreprocessingResultsKey] as? String { if let host = URL(string: value)?.host { return host } return value } return nil } } extension NSItemProvider { var hasFindLoginAction: Bool { hasItemConformingToTypeIdentifier(PassExtensionActions.findLogin) } var hasURL: Bool { hasItemConformingToTypeIdentifier(kUTTypeURL as String) && registeredTypeIdentifiers.count == 1 } var hasPropertyList: Bool { hasItemConformingToTypeIdentifier(kUTTypePropertyList as String) } } extension NSExtensionContext { /// Get all the attachments to this post. var attachments: [NSItemProvider] { guard let items = inputItems as? [NSExtensionItem] else { return [] } return items.flatMap { $0.attachments ?? [] } } } extension NSItemProvider { /// Extracts the URL from the item provider func extractSearchText(completion: @escaping (String?) -> Void) { loadItem(forTypeIdentifier: kUTTypeURL as String) { item, _ in if let url = item as? NSURL { completion(url.host) } else { completion(nil) } } loadItem(forTypeIdentifier: kUTTypePropertyList as String) { item, _ in if let dict = item as? NSDictionary { if let result = dict[NSExtensionJavaScriptPreprocessingResultsKey] as? NSDictionary { completion(result.extractSearchText()) } } } loadItem(forTypeIdentifier: PassExtensionActions.findLogin) { item, _ in if let dict = item as? NSDictionary { let text = dict.extractSearchText() completion(text) } } } }
mit
3e657af87833e3a2d28337de13e5d124
33.065476
165
0.631487
5.476555
false
false
false
false
pixyzehn/AirbnbViewController
AirbnbViewController-Sample/AirbnbViewController-Sample/ViewController.swift
1
1207
// // ViewController.swift // AirbnbViewController-Sample // // Created by pixyzehn on 1/27/15. // Copyright (c) 2015 pixyzehn. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor.blackColor() var button: UIButton = UIButton.buttonWithType(UIButtonType.Custom) as! UIButton button.frame = CGRectMake(0, 0, 50, 35) button.setTitle("Menu", forState: UIControlState.Normal) button.setTitleColor(UIColor(red:0.3, green:0.69, blue:0.75, alpha:1), forState: UIControlState.Normal) button.addTarget(self, action: "leftButtonTouch", forControlEvents: UIControlEvents.TouchUpInside) self.navigationItem.leftBarButtonItem = UIBarButtonItem(customView: button) self.airSwipeHandler = {() -> Void in self.airViewController.showAirViewFromViewController(self.navigationController, complete: nil) return } } func leftButtonTouch() { self.airViewController.showAirViewFromViewController(self.navigationController, complete: nil) } }
mit
205f364765d4868dc284a4b3fb923235
32.527778
111
0.681856
4.714844
false
false
false
false
yytong/ReactiveCocoa
ReactiveCocoaTests/Swift/BagSpec.swift
148
1346
// // BagSpec.swift // ReactiveCocoa // // Created by Justin Spahr-Summers on 2014-07-13. // Copyright (c) 2014 GitHub. All rights reserved. // import Nimble import Quick import ReactiveCocoa class BagSpec: QuickSpec { override func spec() { var bag = Bag<String>() beforeEach { bag = Bag() } it("should insert values") { let a = bag.insert("foo") let b = bag.insert("bar") let c = bag.insert("buzz") expect(contains(bag, "foo")).to(beTruthy()) expect(contains(bag, "bar")).to(beTruthy()) expect(contains(bag, "buzz")).to(beTruthy()) expect(contains(bag, "fuzz")).to(beFalsy()) expect(contains(bag, "foobar")).to(beFalsy()) } it("should remove values given the token from insertion") { let a = bag.insert("foo") let b = bag.insert("bar") let c = bag.insert("buzz") bag.removeValueForToken(b) expect(contains(bag, "foo")).to(beTruthy()) expect(contains(bag, "bar")).to(beFalsy()) expect(contains(bag, "buzz")).to(beTruthy()) bag.removeValueForToken(a) expect(contains(bag, "foo")).to(beFalsy()) expect(contains(bag, "bar")).to(beFalsy()) expect(contains(bag, "buzz")).to(beTruthy()) bag.removeValueForToken(c) expect(contains(bag, "foo")).to(beFalsy()) expect(contains(bag, "bar")).to(beFalsy()) expect(contains(bag, "buzz")).to(beFalsy()) } } }
mit
8a12f3fde3f3420eb49e8802955f86af
23.925926
61
0.640416
3.12297
false
false
false
false
scottkawai/sendgrid-swift
Sources/SendGrid/API/V3/Mail/Send/Settings/Tracking/OpenTracking.swift
1
3240
import Foundation /// The `OpenTracking` class is used to toggle the open tracking setting for an /// email. public struct OpenTracking: Encodable { // MARK: - Properties /// A bool indicating if the setting should be toggled on or off. public let enable: Bool /// An optional tag to specify where to place the open tracking pixel. public let substitutionTag: String? // MARK: - Initialization /// Initializes the setting with a location to put the open tracking pixel /// at. /// /// If the open tracking setting is enabled by default on your SendGrid /// account and you want to disable it for this specific email, you should /// use the `.off` case. /// /// - Parameter location: The location to put the open tracking pixel at /// in the email. If you want to turn the setting /// off, use the `.off` case. public init(location: Location) { switch location { case .off: self.enable = false self.substitutionTag = nil case .bottom: self.enable = true self.substitutionTag = nil case .at(let tag): self.enable = true self.substitutionTag = tag } } } public extension OpenTracking /* Encodable conformance */ { /// :nodoc: enum CodingKeys: String, CodingKey { case enable case substitutionTag = "substitution_tag" } } public extension OpenTracking /* Location enum */ { /// The `OpenTracking.Location` enum represents where the open tracking /// pixel should be placed in the email. /// /// If the open tracking setting is enabled by default on your SendGrid /// account and you want to disable it for this specific email, you should /// use the `.off` case. /// /// - off: Disables open tracking for the email. /// - bottom: Places the open tracking pixel at the bottom of the email /// body. /// - at: Places the open tracking pixel at a specified substitution /// tag. For instance, if you wanted to place the open tracking /// pixel at the top of your email, you can specify this case /// with a tag, such as `.at(tag: "%open_tracking%")`, and then /// in the body of your email you can place the text /// "%open_tracking%" at the top. The tag will then be replaced /// with the open tracking pixel. enum Location { /// Disables open tracking for the email. case off /// Places the open tracking pixel at the bottom of the email body. case bottom /// Places the open tracking pixel at a specified substitution tag. For /// instance, if you wanted to place the open tracking pixel at the top /// of your email, you can specify this case with a tag, such as /// `.at(tag: "%open_tracking%")`, and then in the body of your email /// you can place the text "%open_tracking%" at the top. The tag will /// then be replaced with the open tracking pixel. case at(tag: String) } }
mit
27b65185ef45090665518988f0a30733
38.512195
79
0.59784
4.778761
false
false
false
false
scottkawai/sendgrid-swift
Tests/SendGridTests/API/V3/Mail/Send/Settings/Tracking/SubscriptionTrackingTests.swift
1
2065
@testable import SendGrid import XCTest class SubscriptionTrackingTests: XCTestCase, EncodingTester { typealias EncodableObject = SubscriptionTracking func testEncoding() { let templateSetting = SubscriptionTracking(plainText: "Unsubscribe: <% %>", html: "<% Unsubscribe %>") let templateExpectations: [String: Any] = [ "enable": true, "text": "Unsubscribe: <% %>", "html": "<% Unsubscribe %>" ] XCTAssertEncodedObject(templateSetting, equals: templateExpectations) let subSetting = SubscriptionTracking(substitutionTag: "%unsub%") XCTAssertEncodedObject(subSetting, equals: ["enable": true, "substitution_tag": "%unsub%"]) let offSetting = SubscriptionTracking() XCTAssertEncodedObject(offSetting, equals: ["enable": false]) } func testValidation() { let good1 = SubscriptionTracking( plainText: "Click here to unsubscribe: <% %>.", html: "<p><% Click here %> to unsubscribe.</p>" ) XCTAssertNoThrow(try good1.validate()) let good2 = SubscriptionTracking() XCTAssertNoThrow(try good2.validate()) do { let missingPlain = SubscriptionTracking( plainText: "Click here to unsubscribe", html: "<p><% Click here %> to unsubscribe.</p>" ) try missingPlain.validate() } catch SendGrid.Exception.Mail.missingSubscriptionTrackingTag { XCTAssertTrue(true) } catch { XCTFailUnknownError(error) } do { let missingHTML = SubscriptionTracking( plainText: "Click here to unsubscribe: <% %>.", html: "<p>Click here to unsubscribe.</p>" ) try missingHTML.validate() } catch SendGrid.Exception.Mail.missingSubscriptionTrackingTag { XCTAssertTrue(true) } catch { XCTFailUnknownError(error) } } }
mit
f08542d4e79debcf9ae6360bde2275cb
35.22807
110
0.579177
5.214646
false
true
false
false
fanyinan/ImagePickerProject
ImagePicker/Camera/CameraHelper.swift
1
2796
// // CameraHelper.swift // ImagePickerProject // // Created by 范祎楠 on 16/3/3. // Copyright © 2016年 fyn. All rights reserved. // import UIKit import Photos class CameraHelper: NSObject { static let cropViewControllerTranlateType_Push = 0 static let cropViewControllerTranlateType_Present = 1 fileprivate weak var handlerViewController: UIViewController? var isCrop = false //当为false时由WZImagePickerHelper来负责dismiss var cropViewControllerTranlateType: Int = CameraHelper.cropViewControllerTranlateType_Push var imagePicker:UIImagePickerController! init(handlerViewController: UIViewController) { self.handlerViewController = handlerViewController } func openCamera() { if UIImagePickerController.isSourceTypeAvailable(.camera) { imagePicker = UIImagePickerController() imagePicker.sourceType = .camera imagePicker.cameraDevice = .front imagePicker.isEditing = false imagePicker.delegate = self handlerViewController?.modalPresentationStyle = .overCurrentContext handlerViewController?.present(imagePicker, animated: true, completion: nil) } else { let _ = UIAlertView(title: "相机不可用", message: nil, delegate: nil, cancelButtonTitle: "确定").show() } } } extension CameraHelper: UIImagePickerControllerDelegate, UINavigationControllerDelegate { func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { let type : String = info[UIImagePickerControllerMediaType] as! String if type == "public.image" { let image : UIImage = info[UIImagePickerControllerOriginalImage] as! UIImage if isCrop { let viewController = PhotoCropViewController(image: image) viewController.hidesBottomBarWhenPushed = true picker.dismiss(animated: false, completion: nil) //这种情况dismiss,是因为外部会dismiss掉PhotoCropViewController的rootViewController if cropViewControllerTranlateType == CameraHelper.cropViewControllerTranlateType_Push { handlerViewController?.navigationController?.pushViewController(viewController, animated: true) //这种情况dismiss是因为会present出新的viewcontroller,外部会dismiss新的viewcontroller } else if cropViewControllerTranlateType == CameraHelper.cropViewControllerTranlateType_Present{ handlerViewController?.present(viewController, animated: true, completion: nil) } } else { picker.dismiss(animated: false, completion: nil) PhotosManager.shared.didFinish(.image(images: [image])) } } } }
bsd-2-clause
bc6be878e087038688ca2cbfe20aa3c6
29.670455
117
0.714339
5.240777
false
false
false
false
pabloroca/NewsApp
NewsApp/Controllers/DataControllers/FeedDataController.swift
1
2753
// // FeedDataController.swift // NewsApp // // Created by Pablo Roca Rozas on 28/03/2017. // Copyright © 2017 PR2Studio. All rights reserved. // import Foundation import SWXMLHash import RealmSwift open class FeedDataController { var realm: Realm = try! Realm() public func processxml(feedid: Int, xml: XMLIndexer) { self.deleteForFeed(feedid: feedid) do { try realm.safeWrite { for elem in xml["rss"]["channel"]["item"].all { if let channeltitle = xml["rss"]["channel"]["title"].element?.text { if channeltitle.range(of:"BBC") != nil { self.realm.add(Feed.init(feedid: feedid, title: elem["title"].element?.text, fdescription: elem["description"].element?.text, link: elem["link"].element?.text, pubDate: elem["pubDate"].element?.text?.PR2DateFormatterFromWeb(), media: elem["media:thumbnail"].element?.attribute(by: "url")?.text)!) } else { self.realm.add(Feed.init(feedid: feedid, title: elem["title"].element?.text, fdescription: elem["description"].element?.text, link: elem["link"].element?.text, pubDate: elem["pubDate"].element?.text?.PR2DateFormatterFromWeb(), media: "")!) } } } } SettingsDataController().setTSFeedRead(feedid: feedid, ts: Date().timeIntervalSince1970) } catch let error as NSError { print("setup - Something went wrong: \(error.localizedDescription)") } } public func readAll() -> [Feed] { let results = self.realm.objects(Feed.self) return(Array(results)) } public func readForFeed(feedid: Int) -> [Feed] { let predicate = NSPredicate(format: "feedid = %d", feedid) let results = realm.objects(Feed.self).filter(predicate) let arrResults = Array(results) // newwest by pubDate on top let myArraySorted = arrResults.sorted { (one, two) -> Bool in return one.pubDate! > two.pubDate! } return(myArraySorted) } public func deleteForFeed(feedid: Int) { do { try realm.write { realm.delete(self.readForFeed(feedid: feedid)) } } catch let error as NSError { print("deleteAll - Something went wrong: \(error.localizedDescription)") } } public func deleteAll() { do { try realm.write { realm.delete(self.readAll()) } } catch let error as NSError { print("deleteAll - Something went wrong: \(error.localizedDescription)") } } }
mit
90421222aca821a9e3aabd3eb62ff565
35.210526
324
0.567951
4.347551
false
false
false
false
getsocial-im/getsocial-ios-sdk
example/GetSocialDemo/Views/Communities/Polls/CreatePoll/CreatePollView.swift
1
6501
// // CreatePollView.swift // GetSocialDemo // // Created by Gábor Vass on 26/04/2021. // Copyright © 2021 GrambleWorld. All rights reserved. // import Foundation import UIKit class CreatePollView: UIViewController { private let textLabel = UILabel() private let endDateLabel = UILabel() private let selectDateLabel = UILabel() private let allowMultipleVotesLabel = UILabel() private let text = UITextFieldWithCopyPaste() private let endDate = UITextFieldWithCopyPaste() private let endDatePicker = UIDatePicker() private let allowMultipleVotes = UISwitch() private let addOption = UIButton(type: .roundedRect) private let createButton = UIButton(type: .roundedRect) private let optionsStack = UIStackView() private let scrollView = UIScrollView() private let viewModel: CreatePollViewModel init(_ postTarget: PostActivityTarget) { self.viewModel = CreatePollViewModel(postTarget) super.init(nibName: nil, bundle: nil) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } deinit { NotificationCenter.default.removeObserver(self) } override func viewDidLoad() { setup() } private func setup() { // setup keyboard observers NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(notification:)), name: UIResponder.keyboardWillShowNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(notification:)), name: UIResponder.keyboardWillHideNotification, object: nil) self.view.backgroundColor = UIDesign.Colors.viewBackground self.scrollView.translatesAutoresizingMaskIntoConstraints = false self.view.addSubview(self.scrollView) let stackview = UIStackView() stackview.translatesAutoresizingMaskIntoConstraints = false stackview.axis = .vertical stackview.spacing = 4 scrollView.addSubview(stackview) textLabel.text = "Text" endDateLabel.text = "End Date" selectDateLabel.text = "Select" allowMultipleVotesLabel.text = "Allow Multiple" text.textColor = UIDesign.Colors.inputText text.backgroundColor = .lightGray endDate.backgroundColor = .lightGray endDatePicker.addTarget(self, action: #selector(dateChanged(sender:)), for: .valueChanged) stackview.addFormRow(elements: [textLabel, text]) stackview.addFormRow(elements: [endDateLabel, endDate]) stackview.addFormRow(elements: [selectDateLabel, endDatePicker]) stackview.addFormRow(elements: [allowMultipleVotesLabel, allowMultipleVotes]) addOption.setTitle("Add Option", for: .normal) addOption.addTarget(self, action: #selector(addOption(sender:)), for: .touchUpInside) stackview.addArrangedSubview(addOption) optionsStack.axis = .vertical optionsStack.translatesAutoresizingMaskIntoConstraints = false scrollView.addSubview(optionsStack) createButton.setTitle("Create", for: .normal) createButton.addTarget(self, action: #selector(create(sender:)), for: .touchUpInside) stackview.addArrangedSubview(createButton) NSLayoutConstraint.activate([ scrollView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor), scrollView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor), scrollView.topAnchor.constraint(equalTo: self.view.topAnchor), scrollView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor), stackview.leadingAnchor.constraint(equalTo: self.view.leadingAnchor), stackview.trailingAnchor.constraint(equalTo: self.view.trailingAnchor), stackview.topAnchor.constraint(equalTo: scrollView.topAnchor, constant: 8), optionsStack.leadingAnchor.constraint(equalTo: self.view.leadingAnchor), optionsStack.trailingAnchor.constraint(equalTo: self.view.trailingAnchor), optionsStack.topAnchor.constraint(equalTo: stackview.bottomAnchor), optionsStack.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor) ]) } // MARK: Handle keyboard @objc private func keyboardWillShow(notification: NSNotification) { let userInfo = notification.userInfo if let keyboardSize = (userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue { self.scrollView.contentInset = UIEdgeInsets.init(top: self.scrollView.contentInset.top, left: self.scrollView.contentInset.left, bottom: keyboardSize.height, right: self.scrollView.contentInset.right) } } @objc private func keyboardWillHide(notification: NSNotification) { self.scrollView.contentInset = UIEdgeInsets.init(top: self.scrollView.contentInset.top, left: self.scrollView.contentInset.left, bottom: 0, right: self.scrollView.contentInset.right) } @objc private func dateChanged(sender: UIView) { let selectedDate = self.endDatePicker.date let formatter = DateFormatter() formatter.dateFormat = "yyyy-MM-dd HH:mm" self.endDate.text = formatter.string(from: selectedDate) } @objc private func create(sender: UIView) { let activityContent = ActivityContent() let pollContent = PollContent() pollContent.allowMultipleVotes = self.allowMultipleVotes.isOn if (self.endDate.text?.count ?? 0) > 0 { pollContent.endDate = self.endDatePicker.date } var optionsAreValid = true var pollOptions: [PollOptionContent] = [] self.optionsStack.arrangedSubviews.forEach { let view = $0 as! PollOptionView switch view.collectData() { case .success(let pollOption): pollOptions.append(pollOption) case .failure(let error): optionsAreValid = false self.showAlert(withTitle: "Error", andText: "\(error)") } } guard optionsAreValid else { return } pollContent.options = pollOptions activityContent.text = self.text.text activityContent.poll = pollContent self.viewModel.onSuccess = { [weak self] in self?.hideActivityIndicatorView() self?.showAlert(withText: "Poll created") self?.clearFields() } self.viewModel.onError = { [weak self] error in self?.hideActivityIndicatorView() self?.showAlert(withTitle: "Error", andText: error) } self.showActivityIndicatorView() self.viewModel.createPoll(activityContent) } @objc private func addOption(sender: UIView) { let view = PollOptionView() view.onRemoveTap = { self.optionsStack.removeArrangedSubview(view) view.removeFromSuperview() } self.optionsStack.addArrangedSubview(view) } func clearFields() { self.optionsStack.arrangedSubviews.forEach { self.optionsStack.removeArrangedSubview($0) $0.removeFromSuperview() } self.text.text = nil self.endDate.text = nil self.allowMultipleVotes.isOn = false } }
apache-2.0
dda02f6c77144d2f03cf7946b49c1e0b
32.158163
203
0.770426
3.987117
false
false
false
false
supermarin/Swifternalization
Swifternalization/TranslatablePair.swift
1
2051
// // Pairs.swift // Swifternalization // // Created by Tomasz Szulc on 27/06/15. // Copyright (c) 2015 Tomasz Szulc. All rights reserved. // import Foundation /** Represents key-value pair from Localizable.strings files. It contains key, value and expression if exists for the key. It can also validate if text matches expression's requirements. */ struct TranslatablePair: KeyValue { /// Key from Localizable.strings. var key: Key /// Value from Localizable.strings. var value: Value /// `Expression` which is parsed from `key`. var expression: Expression? = nil /// Tells if pair has `expression` or not. var hasExpression: Bool { return expression != nil } /** It returns key without expression pattern. If pair has `expression` set to nil it will return `key`. If `expression` exist the `key` will be parsed and returned without expression pattern. */ var keyWithoutExpression: String { if hasExpression == false { return key } return Regex.firstMatchInString(key, pattern: InternalPattern.KeyWithoutExpression.rawValue)! } /** Creates `TranslatablePair`. It automatically tries to parse expression from key - if there is any. :param: key A key from Localizable.strings :param: value A value from Localizable.strings */ init(key: Key, value: Value) { self.key = key self.value = value parseExpression() } /// Method parses expression from the `key` property. mutating func parseExpression() { self.expression = Expression.expressionFromString(key) } /** Validates string and check if matches `expression`'s requirements. If pair has no expression it return false. :param: value A value that will be matched. :returns: `true` if value matches `expression`, otherwise `false`. */ func validate(value: String) -> Bool { if hasExpression == false { return false } return expression!.validate(value) } }
mit
2b1edb332e576f8ad8c9ed3872b0b7f8
28.724638
101
0.663579
4.497807
false
false
false
false
DaveChambers/SuperCrack
SuperCrack!/PegboardViewController.swift
1
2971
// // PegboardViewController.swift // Pegs in the Head // // Created by Dave Chambers on 04/07/2017. // Copyright © 2017 Dave Chambers. All rights reserved. // import UIKit class PegboardViewController: UIViewController { var memoryVC: MemoryViewController? let game = GameModel() var pegBoardView: PegBoardView! var dimensions: GameDimensions! override func viewDidLoad() { super.viewDidLoad() self.title = "Colour Board" setupDimensionsAndGame() } func updateGeometry() { pegBoardView.removeFromSuperview() setupDimensionsAndGame() } func setupDimensionsAndGame() { //Set the Game Dimensions Global Struct.... dimensions = GameDimensions(game: game, tabBarHeight:(self.tabBarController?.tabBar.frame.size.height)!, vcHeight: self.view.frame.height) game.setupGameModel(dimensions: dimensions) pegBoardView = PegBoardView(frame: CGRect(x: 0, y: 0, width: self.view.frame.width, height: dimensions.usableHeight), dimensions: dimensions, game: game) self.view.addSubview(pegBoardView) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override var prefersStatusBarHidden: Bool { return true } func reallyQuit(completionHandler:@escaping (Bool) -> ()) { let reallyQuitAlert = UIAlertController(title: "Really quit?" , message: "Resume your game or quit.", preferredStyle: .alert) let returnAction = UIAlertAction(title: "Resume", style: .cancel) { action in completionHandler(false) } reallyQuitAlert.addAction(returnAction) let quitAction = UIAlertAction(title: "Quit", style: .destructive) { action in completionHandler(true) } reallyQuitAlert.addAction(quitAction) present(reallyQuitAlert, animated: true, completion: nil) } func finaliseGame(won: Bool, pegBoardView: PegBoardView) { let gameOverAlert = UIAlertController(title: won ? "You won!": "You lost.", message: "Start a new game?", preferredStyle: .alert) let viewBoardAction = UIAlertAction(title: "View Board", style: .cancel) { action in //print("No action required") } gameOverAlert.addAction(viewBoardAction) let newGameAction = UIAlertAction(title: "New Game", style: .destructive) { action in self.restartGame() } gameOverAlert.addAction(newGameAction) present(gameOverAlert, animated: true, completion: nil) } func restartGame() { //New Game Logic: self.game.initGame() //TODO: Make conditional upon if settings need updating: updateGeometry() self.game.setupCodeAndHoles() let pegBoardView = self.pegBoardView! pegBoardView.reactivateTurnOne() _ = pegBoardView.subviews.filter{$0 is FeedbackView}.map{$0.removeFromSuperview()} pegBoardView.addTurnButtons() pegBoardView.setNeedsLayout() if let memoryVC = memoryVC { memoryVC.memView?.resetAll() } } }
mit
13b4a4bcb5d4b343edd633619ab59154
32.370787
157
0.710438
4.153846
false
false
false
false
nuan-nuan/Socket.IO-Client-Swift
SocketIO-MacTests/SocketBasicPacketTest.swift
1
5373
// // SocketBasicPacketTest.swift // Socket.IO-Client-Swift // // Created by Erik Little on 10/7/15. // // import XCTest class SocketBasicPacketTest: XCTestCase { let data = "test".dataUsingEncoding(NSUTF8StringEncoding)! let data2 = "test2".dataUsingEncoding(NSUTF8StringEncoding)! func testEmpyEmit() { let expectedSendString = "2[\"test\"]" let sendData = ["test"] let packet = SocketPacket.packetFromEmit(sendData, id: -1, nsp: "/", ack: false) XCTAssertEqual(packet.packetString, expectedSendString) } func testNullEmit() { let expectedSendString = "2[\"test\",null]" let sendData = ["test", NSNull()] let packet = SocketPacket.packetFromEmit(sendData, id: -1, nsp: "/", ack: false) XCTAssertEqual(packet.packetString, expectedSendString) } func testStringEmit() { let expectedSendString = "2[\"test\",\"foo bar\"]" let sendData = ["test", "foo bar"] let packet = SocketPacket.packetFromEmit(sendData, id: -1, nsp: "/", ack: false) XCTAssertEqual(packet.packetString, expectedSendString) } func testJSONEmit() { let expectedSendString = "2[\"test\",{\"test\":\"hello\",\"hello\":1,\"foobar\":true,\"null\":null}]" let sendData = ["test", ["foobar": true, "hello": 1, "test": "hello", "null": NSNull()]] let packet = SocketPacket.packetFromEmit(sendData, id: -1, nsp: "/", ack: false) XCTAssertEqual(packet.packetString, expectedSendString) } func testArrayEmit() { let expectedSendString = "2[\"test\",[\"hello\",1,{\"test\":\"test\"}]]" let sendData = ["test", ["hello", 1, ["test": "test"]]] let packet = SocketPacket.packetFromEmit(sendData, id: -1, nsp: "/", ack: false) XCTAssertEqual(packet.packetString, expectedSendString) } func testBinaryEmit() { let expectedSendString = "51-[\"test\",{\"num\":0,\"_placeholder\":true}]" let sendData = ["test", data] let packet = SocketPacket.packetFromEmit(sendData, id: -1, nsp: "/", ack: false) XCTAssertEqual(packet.packetString, expectedSendString) XCTAssertEqual(packet.binary, [data]) } func testMultipleBinaryEmit() { let expectedSendString = "52-[\"test\",{\"data1\":{\"num\":0,\"_placeholder\":true},\"data2\":{\"num\":1,\"_placeholder\":true}}]" let sendData = ["test", ["data1": data, "data2": data2]] let packet = SocketPacket.packetFromEmit(sendData, id: -1, nsp: "/", ack: false) XCTAssertEqual(packet.packetString, expectedSendString) XCTAssertEqual(packet.binary, [data, data2]) } func testEmitWithAck() { let expectedSendString = "20[\"test\"]" let sendData = ["test"] let packet = SocketPacket.packetFromEmit(sendData, id: 0, nsp: "/", ack: false) XCTAssertEqual(packet.packetString, expectedSendString) } func testEmitDataWithAck() { let expectedSendString = "51-0[\"test\",{\"num\":0,\"_placeholder\":true}]" let sendData = ["test", data] let packet = SocketPacket.packetFromEmit(sendData, id: 0, nsp: "/", ack: false) XCTAssertEqual(packet.packetString, expectedSendString) XCTAssertEqual(packet.binary, [data]) } // Acks func testEmptyAck() { let expectedSendString = "30[]" let packet = SocketPacket.packetFromEmit([], id: 0, nsp: "/", ack: true) XCTAssertEqual(packet.packetString, expectedSendString) } func testNullAck() { let expectedSendString = "30[null]" let sendData = [NSNull()] let packet = SocketPacket.packetFromEmit(sendData, id: 0, nsp: "/", ack: true) XCTAssertEqual(packet.packetString, expectedSendString) } func testStringAck() { let expectedSendString = "30[\"test\"]" let sendData = ["test"] let packet = SocketPacket.packetFromEmit(sendData, id: 0, nsp: "/", ack: true) XCTAssertEqual(packet.packetString, expectedSendString) } func testJSONAck() { let expectedSendString = "30[{\"test\":\"hello\",\"hello\":1,\"foobar\":true,\"null\":null}]" let sendData = [["foobar": true, "hello": 1, "test": "hello", "null": NSNull()]] let packet = SocketPacket.packetFromEmit(sendData, id: 0, nsp: "/", ack: true) XCTAssertEqual(packet.packetString, expectedSendString) } func testBinaryAck() { let expectedSendString = "61-0[{\"num\":0,\"_placeholder\":true}]" let sendData = [data] let packet = SocketPacket.packetFromEmit(sendData, id: 0, nsp: "/", ack: true) XCTAssertEqual(packet.packetString, expectedSendString) XCTAssertEqual(packet.binary, [data]) } func testMultipleBinaryAck() { let expectedSendString = "62-0[{\"data2\":{\"num\":0,\"_placeholder\":true},\"data1\":{\"num\":1,\"_placeholder\":true}}]" let sendData = [["data1": data, "data2": data2]] let packet = SocketPacket.packetFromEmit(sendData, id: 0, nsp: "/", ack: true) XCTAssertEqual(packet.packetString, expectedSendString) XCTAssertEqual(packet.binary, [data2, data]) } }
apache-2.0
0afa3151c07b9226a1a6eb5baa95083d
37.654676
138
0.599665
4.187841
false
true
false
false
illusionofchaos/swift-package-optionalAssignment
Sources/assignment.swift
1
557
infix operator ?= { associativity right precedence 90 assignment } infix operator ??= { associativity right precedence 90 assignment } public func ?=<T:Any>(inout lhs:T,rhs:Any?) { if let rhs = rhs as? T { lhs = rhs } } public func ?=<T:Any>(inout lhs:T?,rhs:Any?) { if let rhs = rhs as? T { lhs = rhs } } public func ??=<T:Any>(inout lhs:T,rhs:(optionalValue:Any?, defaultValue:T)) { if let optionalValue = rhs.optionalValue as? T { lhs = optionalValue } else { lhs = rhs.defaultValue } }
mit
d32b0a19d0d5080e162eeba14bbf5e9c
16.4375
78
0.599641
3.417178
false
false
false
false
gribozavr/swift
test/IRGen/prespecialized-metadata/class-inmodule-0argument-within-class-1argument-1distinct_use.swift
1
1065
// RUN: %swift -target %module-target-future -parse-stdlib -emit-ir -prespecialize-generic-metadata %s | %FileCheck %s -DINT=i%target-ptrsize -DALIGNMENT=%target-alignment // UNSUPPORTED: CPU=i386 && OS=ios // UNSUPPORTED: CPU=armv7 && OS=ios // UNSUPPORTED: CPU=armv7s && OS=ios precedencegroup AssignmentPrecedence {} class Namespace<T> {} class Zang { } extension Namespace where T == Zang { class ExtensionNonGeneric {} } @inline(never) func consume<T>(_ t: T) { Builtin.fixLifetime(t) } // CHECK: define hidden swiftcc void @"$s4main4doityyF"() #{{[0-9]+}} { // CHECK: entry: // CHECK: [[METADATA_RESPONSE:%[0-9]+]] = call swiftcc %swift.metadata_response @"$s4main9NamespaceCA2A4ZangCRszlE19ExtensionNonGenericCyAE_GMa"([[INT]] 0) #{{[0-9]+}} // CHECK: [[METADATA:%[0-9]+]] = extractvalue %swift.metadata_response [[METADATA_RESPONSE]], 0 // CHECK: call swiftcc void @"$s4main7consumeyyxlF"(%swift.opaque* noalias nocapture %5, %swift.type* [[METADATA]]) // CHECK: } func doit() { consume( Namespace<Zang>.ExtensionNonGeneric() ) } doit()
apache-2.0
f8cd220d468882af0eea3c192df90fda
31.272727
171
0.692019
3.359621
false
false
false
false
ios-ximen/DYZB
斗鱼直播/斗鱼直播/Classes/Main/Controllers/CustomNavigationViewController.swift
1
1735
// // CustomNavigationViewController.swift // 斗鱼直播 // // Created by niujinfeng on 2017/10/2. // Copyright © 2017年 niujinfeng. All rights reserved. // import UIKit class CustomNavigationViewController: UINavigationController { override func viewDidLoad() { super.viewDidLoad() // 1.获取系统的Pop手势 guard let systemGes = interactivePopGestureRecognizer else { return } // 2.获取手势添加到的View中 guard let gesView = systemGes.view else { return } // 3.获取target/action // 3.1.利用运行时机制查看所有的属性名称 /* var count : UInt32 = 0 let ivars = class_copyIvarList(UIGestureRecognizer.self, &count)! for i in 0..<count { let ivar = ivars[Int(i)] let name = ivar_getName(ivar) print(String(cString: name!)) } */ let targets = systemGes.value(forKey: "_targets") as? [NSObject] guard let targetObjc = targets?.first else { return } // 3.2.取出target guard let target = targetObjc.value(forKey: "target") else { return } // 3.3.取出Action let action = Selector(("handleNavigationTransition:")) // 4.创建自己的Pan手势 let panGes = UIPanGestureRecognizer() gesView.addGestureRecognizer(panGes) panGes.addTarget(target, action: action) } override func pushViewController(_ viewController: UIViewController, animated: Bool) { //隐藏底部tabBar viewController.hidesBottomBarWhenPushed = true super.pushViewController(viewController, animated: animated) } }
mit
bfa12f2528c05d03f73fd18d231ec9e9
28.563636
90
0.611931
4.567416
false
false
false
false
MxABC/LBXAlertAction
TestSwiftAlertAction/ViewController.swift
1
2201
// // ViewController.swift // TestSwiftAlertAction // // Created by lbxia on 16/6/17. // Copyright © 2016年 lbx. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } @IBAction func testAlertView(_ sender: AnyObject) { // let alert = UIAlertView(title: "title", message: "message", delegate: nil, cancelButtonTitle: "cance", otherButtonTitles: "sure", "sure2") // // alert .show { (buttonIndex) in // // print(buttonIndex) // } let items = ["cancel","ok1","ok2"]; AlertAction.showAlert(title: "title", message: "message", btnStatements:items ) { (buttonIndex) in let items = ["cancel","ok1","ok2"]; print(buttonIndex) print(items[buttonIndex]) } } @IBAction func testSheetView(_ sender: AnyObject) { let destrucitve:String? = "destructive" // let destrucitve:String? = nil AlertAction.showSheet(title: "title", message: "ios8之后才会显示本条信息", destructiveButtonTitle: destrucitve,cancelButtonTitle: "cancel", otherButtonTitles: ["other1","other2"]) { (buttonIdx, itemTitle) in /* 经测试 buttonIdx: destructiveButtonTitle 为0, cancelButtonTitle 为1,otherButtonTitles按顺序增加 如果destructiveButtonTitle 传入值为nil,那么 cancelButtonTitle 为0,otherButtonTitles按顺序增加 或者按照itemTitle来判断用户点击那个按钮更稳妥 */ print(buttonIdx) print(itemTitle) } } func alertResult(_ buttonIndex:Int) -> Void { } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
7c1dc5328ba0c2eb933fb1c47d265b31
24.439024
206
0.555129
4.719457
false
false
false
false
rambler-digital-solutions/rambler-it-ios
Carthage/Checkouts/rides-ios-sdk/source/UberRides/RequestDeeplink.swift
1
1867
// // RequestDeeplink.swift // UberRides // // Copyright © 2015 Uber Technologies, Inc. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import CoreLocation import UIKit /** * Builds and executes a deeplink to the native Uber app to request a ride. */ @objc(UBSDKRequestDeeplink) public class RequestDeeplink: BaseDeeplink { static let sourceString = "deeplink" @objc public init(rideParameters: RideParameters = RideParametersBuilder().build()) { rideParameters.source = rideParameters.source ?? RequestDeeplink.sourceString let queryItems = RequestURLUtil.buildRequestQueryParameters(rideParameters) let scheme = "uber" let domain = "" super.init(scheme: scheme, domain: domain, path: "", queryItems: queryItems)! } }
mit
f8a9b7cbdf99ec3c8a890c60632fe878
41.409091
89
0.730975
4.607407
false
false
false
false
jay18001/brickkit-ios
Tests/Cells/AsynchronousResizableBrick.swift
1
1739
// // DummyAsynchronousResizableCell.swift // BrickKit // // Created by Ruben Cagnie on 10/1/16. // Copyright © 2016 Wayfair LLC. All rights reserved. // import UIKit import BrickKit class AsynchronousResizableBrick: Brick { var didChangeSizeCallBack: (() -> Void)? var newHeight: CGFloat = 200 } class AsynchronousResizableBrickCell: BrickCell, Bricklike, AsynchronousResizableCell { typealias BrickType = AsynchronousResizableBrick weak var resizeDelegate: AsynchronousResizableDelegate? @IBOutlet weak var heightConstraint: NSLayoutConstraint! var timer: Timer? override func updateContent() { super.updateContent() timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(AsynchronousResizableBrickCell.fireTimer), userInfo: nil, repeats: false) } func fireTimer() { self.heightConstraint.constant = brick.newHeight self.resizeDelegate?.performResize(cell: self, completion: { [weak self] (_: Bool) in self?.brick.didChangeSizeCallBack?() }) } } class DeinitNotifyingAsyncBrickCell: BrickCell, Bricklike, AsynchronousResizableCell { typealias BrickType = DeinitNotifyingAsyncBrick weak var resizeDelegate: AsynchronousResizableDelegate? override func updateContent() { super.updateContent() self.resizeDelegate?.performResize(cell: self, completion: nil) } deinit { NotificationCenter.default.post(name: NSNotification.Name(rawValue: "DeinitNotifyingAsyncBrickCell.deinit"), object: nil) } } class DeinitNotifyingAsyncBrick: Brick { override class var cellClass: UICollectionViewCell.Type? { return DeinitNotifyingAsyncBrickCell.self } }
apache-2.0
c479feb431e8ba022e89d6c44b2db89e
28.965517
161
0.729574
4.841226
false
false
false
false
AlexeyGolovenkov/DocGenerator
DocGenerator/DocGenerator/Data/ClassObject.swift
1
768
// // ClassObject.swift // DocGenerator // // Created by Alexey Golovenkov on 02.04.16. // Copyright © 2016 Alex & Igor. All rights reserved. // import Cocoa /// Documented class class ClassObject: DocumentableObject { /// Array of methods of the class var methods: [MethodObject] = [] // TODO: Change type override init() { super.init() self.type = .Class } override func jsonDescription() -> [String : AnyObject] { var json = super.jsonDescription() json[generatorTagParamList] = methodsJson() return json } // - MARK: Private methods private func methodsJson() -> [[String: AnyObject]] { var json: [[String: AnyObject]] = [] for method in methods { json.append(method.jsonDescription()) } return json } }
mit
28aa0fba9e9997f39d38a603d454f972
17.707317
58
0.657106
3.454955
false
false
false
false
dreamsxin/swift
test/Interpreter/generics.swift
3
3312
// RUN: %target-run-simple-swift | FileCheck %s // REQUIRES: executable_test struct BigStruct { var a,b,c,d,e,f,g,h:Int } // FIXME: missing symbol for Object destructor? //class SomeClass : Object { } func id<T>(_ x: T) -> T { return x } var int = id(1) var bigStruct = id(BigStruct(a: 1, b: 2,c: 3, d: 4, e: 5, f: 6, g: 7, h: 8)) //var someClass = SomeClass() //var someClass2 = id(someClass) func print(_ bs: BigStruct) { // FIXME: typechecker is too slow to handle this as an interpolated literal print("BigStruct(", terminator: "") print(bs.a, terminator: "") print(", ", terminator: "") print(bs.b, terminator: "") print(", ", terminator: "") print(bs.c, terminator: "") print(", ", terminator: "") print(bs.d, terminator: "") print(", ", terminator: "") print(bs.e, terminator: "") print(", ", terminator: "") print(bs.f, terminator: "") print(", ", terminator: "") print(bs.g, terminator: "") print(", ", terminator: "") print(bs.h, terminator: "") print(")") } // CHECK: 1 print(int) // CHECK: BigStruct(1, 2, 3, 4, 5, 6, 7, 8) print(bigStruct) // FIXME: missing symbol for Object destructor? // C/HECK: true //print(someClass === someClass2) //===---- // Check overload resolution of generic functions. //===---- protocol P1 {} protocol P2 : P1 {} protocol P3 : P2 {} struct S1 : P1 {} struct S2 : P2 {} struct S3 : P3 {} func foo1<T : P1>(_ x: T) { print("P1") } func foo1<T : P2>(_ x: T) { print("P2") } func foo1<T : P3>(_ x: T) { print("P3") } func foo2<T : P1>(_ x: T) { print("P1") } func foo2<T : P2>(_ x: T) { print("P2") } func foo3<T : P1>(_ x: T) { print("P1") } func foo3<T : P3>(_ x: T) { print("P3") } func foo4<T : P3, U : P1>(_ x: T, _ y: U) { print("P3, P1") } func foo4<T : P3, U : P3>(_ x: T, _ y: U) { print("P3, P3") } func checkOverloadResolution() { print("overload resolution:") // CHECK-LABEL: overload resolution foo1(S1()) // CHECK-NEXT: P1 foo1(S2()) // CHECK-NEXT: P2 foo1(S3()) // CHECK-NEXT: P3 foo2(S1()) // CHECK-NEXT: P1 foo2(S2()) // CHECK-NEXT: P2 foo2(S3()) // CHECK-NEXT: P2 foo3(S1()) // CHECK-NEXT: P1 foo3(S2()) // CHECK-NEXT: P1 foo3(S3()) // CHECK-NEXT: P3 foo4(S3(), S1()) // CHECK-NEXT: P3, P1 foo4(S3(), S2()) // CHECK-NEXT: P3, P1 foo4(S3(), S3()) // CHECK-NEXT: P3, P3 } checkOverloadResolution() class Base { var v = 0 required init() {} func map() { v = 1 } } class D1 : Base { required init() {} override func map() { v = 2 } } func parse<T:Base>() -> T { let inst = T() inst.map() return inst } var m : D1 = parse() print(m.v) // CHECK: 2 // rdar://problem/21770225 - infinite recursion with metadata // instantiation when associated type contains Self struct MySlice<T : MyIndexableType> : MySequenceType {} struct MyMutableSlice<T : MyMutableCollectionType> : MySequenceType {} protocol MySequenceType {} protocol MyIndexableType {} protocol MyCollectionType : MySequenceType, MyIndexableType { associatedtype SubSequence = MySlice<Self> } protocol MyMutableCollectionType : MyCollectionType { associatedtype SubSequence = MyMutableSlice<Self> } struct S : MyMutableCollectionType {} // CHECK: MyMutableSlice<S>() print(S.SubSequence()) // CHECK: MyMutableSlice<S> print(S.SubSequence.self)
apache-2.0
aa83969e756d69f83b26215dbb7efe3f
22
77
0.60628
2.890052
false
false
false
false
shadanan/mado
Antlr4Runtime/Sources/Antlr4/RuleContext.swift
1
9328
/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. * Use of this file is governed by the BSD 3-clause license that * can be found in the LICENSE.txt file in the project root. */ /** A rule context is a record of a single rule invocation. * * We form a stack of these context objects using the parent * pointer. A parent pointer of null indicates that the current * context is the bottom of the stack. The ParserRuleContext subclass * as a children list so that we can turn this data structure into a * tree. * * The root node always has a null pointer and invokingState of -1. * * Upon entry to parsing, the first invoked rule function creates a * context object (asubclass specialized for that rule such as * SContext) and makes it the root of a parse tree, recorded by field * Parser._ctx. * * public final SContext s() throws RecognitionException { * SContext _localctx = new SContext(_ctx, getState()); <-- create new node * enterRule(_localctx, 0, RULE_s); <-- push it * ... * exitRule(); <-- pop back to _localctx * return _localctx; * } * * A subsequent rule invocation of r from the start rule s pushes a * new context object for r whose parent points at s and use invoking * state is the state with r emanating as edge label. * * The invokingState fields from a context object to the root * together form a stack of rule indication states where the root * (bottom of the stack) has a -1 sentinel value. If we invoke start * symbol s then call r1, which calls r2, the would look like * this: * * SContext[-1] <- root node (bottom of the stack) * R1Context[p] <- p in rule s called r1 * R2Context[q] <- q in rule r1 called r2 * * So the top of the stack, _ctx, represents a call to the current * rule and it holds the return address from another rule that invoke * to this rule. To invoke a rule, we must always have a current context. * * The parent contexts are useful for computing lookahead sets and * getting error information. * * These objects are used during parsing and prediction. * For the special case of parsers, we use the subclass * ParserRuleContext. * * @see org.antlr.v4.runtime.ParserRuleContext */ open class RuleContext: RuleNode { public static let EMPTY: ParserRuleContext = ParserRuleContext() /** What context invoked this rule? */ public var parent: RuleContext? /** What state invoked the rule associated with this context? * The "return address" is the followState of invokingState * If parent is null, this should be -1 this context object represents * the start rule. */ public var invokingState: Int = -1 override public init() { super.init() } public init(_ parent: RuleContext?, _ invokingState: Int) { self.parent = parent //if ( parent!=null ) { print("invoke "+stateNumber+" from "+parent)} self.invokingState = invokingState } open func depth() -> Int { var n: Int = 0 var p: RuleContext? = self while let pWrap = p { p = pWrap.parent n += 1 } return n } /** A context is empty if there is no invoking state; meaning nobody called * current context. */ open func isEmpty() -> Bool { return invokingState == -1 } // satisfy the ParseTree / SyntaxTree interface override open func getSourceInterval() -> Interval { return Interval.INVALID } override open func getRuleContext() -> RuleContext { return self } override open func getParent() -> Tree? { return parent } override open func getPayload() -> AnyObject { return self } /** Return the combined text of all child nodes. This method only considers * tokens which have been added to the parse tree. * <p> * Since tokens on hidden channels (e.g. whitespace or comments) are not * added to the parse trees, they will not appear in the output of this * method. */ open override func getText() -> String { let length = getChildCount() if length == 0 { return "" } let builder: StringBuilder = StringBuilder() for i in 0..<length { builder.append((getChild(i) as! ParseTree).getText()) } return builder.toString() } open func getRuleIndex() -> Int { return -1 } open func getAltNumber() -> Int { return ATN.INVALID_ALT_NUMBER } open func setAltNumber(_ altNumber: Int) { } open override func getChild(_ i: Int) -> Tree? { return nil } open override func getChildCount() -> Int { return 0 } open override func accept<T>(_ visitor: ParseTreeVisitor<T>) -> T? { return visitor.visitChildren(self) } /* /** Call this method to view a parse tree in a dialog box visually. */ public func inspect(parser : Parser) -> Future<JDialog> { var ruleNames : Array<String> = parser != nil ? Arrays.asList(parser.getRuleNames()) : null; return inspect(ruleNames); } public func inspect(ruleNames : Array<String>) -> Future<JDialog> { var viewer : TreeViewer = TreeViewer(ruleNames, self); return viewer.open(); } /** Save this tree in a postscript file */ public func save(parser : Parser, _ fileName : String) throws; IOException, PrintException { var ruleNames : Array<String> = parser != nil ? Arrays.asList(parser.getRuleNames()) : null; save(ruleNames, fileName); } /** Save this tree in a postscript file using a particular font name and size */ public func save(parser : Parser, _ fileName : String, _ fontName : String, _ fontSize : Int) throws; IOException { var ruleNames : Array<String> = parser != nil ? Arrays.asList(parser.getRuleNames()) : null; save(ruleNames, fileName, fontName, fontSize); } /** Save this tree in a postscript file */ public func save(ruleNames : Array<String>, _ fileName : String) throws; IOException, PrintException { Trees.writePS(self, ruleNames, fileName); } /** Save this tree in a postscript file using a particular font name and size */ public func save(ruleNames : Array<String>, _ fileName : String, _ fontName : String, _ fontSize : Int) throws; IOException { Trees.writePS(self, ruleNames, fileName, fontName, fontSize); } */ /** Print out a whole tree, not just a node, in LISP format * (root child1 .. childN). Print just a node if this is a leaf. * We have to know the recognizer so we can get rule names. */ open override func toStringTree(_ recog: Parser) -> String { return Trees.toStringTree(self, recog) } /** Print out a whole tree, not just a node, in LISP format * (root child1 .. childN). Print just a node if this is a leaf. */ public func toStringTree(_ ruleNames: Array<String>?) -> String { return Trees.toStringTree(self, ruleNames) } open override func toStringTree() -> String { let info: Array<String>? = nil return toStringTree(info) } open override var description: String { let p1: Array<String>? = nil let p2: RuleContext? = nil return toString(p1, p2) } open override var debugDescription: String { return description } public final func toString<T:ATNSimulator>(_ recog: Recognizer<T>) -> String { return toString(recog, ParserRuleContext.EMPTY) } public final func toString(_ ruleNames: Array<String>) -> String { return toString(ruleNames, nil) } // recog null unless ParserRuleContext, in which case we use subclass toString(...) open func toString<T:ATNSimulator>(_ recog: Recognizer<T>?, _ stop: RuleContext) -> String { let ruleNames: [String]? = recog != nil ? recog!.getRuleNames() : nil let ruleNamesList: Array<String>? = ruleNames ?? nil return toString(ruleNamesList, stop) } open func toString(_ ruleNames: Array<String>?, _ stop: RuleContext?) -> String { let buf: StringBuilder = StringBuilder() var p: RuleContext? = self buf.append("[") while let pWrap = p , pWrap !== stop { if ruleNames == nil { if !pWrap.isEmpty() { buf.append(pWrap.invokingState) } } else { let ruleIndex: Int = pWrap.getRuleIndex() let ruleIndexInRange: Bool = ruleIndex >= 0 && ruleIndex < ruleNames!.count let ruleName: String = ruleIndexInRange ? ruleNames![ruleIndex] : String(ruleIndex) buf.append(ruleName) } if pWrap.parent != nil && (ruleNames != nil || !pWrap.parent!.isEmpty()) { buf.append(" ") } p = pWrap.parent } buf.append("]") return buf.toString() } open func castdown<T>(_ subType: T.Type) -> T { return self as! T } }
mit
05780d8c1a4269f16fc0951d294e605e
31.961131
101
0.613958
4.203695
false
false
false
false
nextcloud/ios
Widget/Dashboard/DashboardWidgetView.swift
1
9637
// // DashboardWidgetView.swift // Widget // // Created by Marino Faggiana on 20/08/22. // Copyright © 2022 Marino Faggiana. All rights reserved. // // Author Marino Faggiana <[email protected]> // // 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 SwiftUI import WidgetKit struct DashboardWidgetView: View { var entry: DashboardDataEntry var body: some View { GeometryReader { geo in if entry.isEmpty { VStack(alignment: .center) { Image(systemName: "checkmark") .resizable() .scaledToFit() .frame(width: 50, height: 50) Text(NSLocalizedString("_no_items_", comment: "")) .font(.system(size: 25)) .padding() Text(NSLocalizedString("_check_back_later_", comment: "")) .font(.system(size: 15)) } .frame(width: geo.size.width, height: geo.size.height) } ZStack(alignment: .topLeading) { HStack() { Image(uiImage: entry.titleImage) .renderingMode(.template) .resizable() .scaledToFill() .frame(width: 20, height: 20) Text(entry.title) .font(.system(size: 15)) .fontWeight(.bold) .multilineTextAlignment(.center) .textCase(.uppercase) .lineLimit(1) } .frame(width: geo.size.width - 20) .padding([.top, .leading, .trailing], 10) if !entry.isEmpty { VStack(alignment: .leading) { VStack(spacing: 0) { ForEach(entry.datas, id: \.id) { element in Link(destination: element.link) { HStack { let subTitleColor = Color(white: 0.5) if entry.isPlaceholder { Circle() .fill(Color(.systemGray4)) .frame(width: 35, height: 35) } else if let color = element.imageColor { Image(uiImage: element.icon) .renderingMode(.template) .resizable() .frame(width: 20, height: 20) .foregroundColor(Color(color)) } else if element.template { if entry.dashboard?.itemIconsRound ?? false { Image(uiImage: element.icon) .renderingMode(.template) .resizable() .scaledToFill() .frame(width: 20, height: 20) .foregroundColor(.white) .padding(8) .background(Color(.systemGray4)) .clipShape(Circle()) } else { Image(uiImage: element.icon) .renderingMode(.template) .resizable() .scaledToFill() .frame(width: 25, height: 25) .clipped() .cornerRadius(5) } } else { if entry.dashboard?.itemIconsRound ?? false || element.avatar { Image(uiImage: element.icon) .resizable() .scaledToFill() .frame(width: 35, height: 35) .clipShape(Circle()) } else { Image(uiImage: element.icon) .resizable() .scaledToFill() .frame(width: 35, height: 35) .clipped() .cornerRadius(5) } } VStack(alignment: .leading, spacing: 2) { Text(element.title) .font(.system(size: 12)) .fontWeight(.regular) Text(element.subTitle) .font(.system(size: CGFloat(10))) .foregroundColor(subTitleColor) } Spacer() } .padding(.leading, 10) .frame(height: 50) } Divider() .padding(.leading, 54) } } } .padding(.top, 35) .redacted(reason: entry.isPlaceholder ? .placeholder : []) } if let buttons = entry.buttons, !buttons.isEmpty, !entry.isPlaceholder { HStack(spacing: 10) { let brandColor = Color(NCBrandColor.shared.brand) let brandTextColor = Color(NCBrandColor.shared.brandText) ForEach(buttons, id: \.index) { element in Link(destination: URL(string: element.link)! , label: { Text(element.text) .font(.system(size: 15)) .padding(7) .background(brandColor) .foregroundColor(brandTextColor) .border(brandColor, width: 1) .cornerRadius(.infinity) }) } } .frame(width: geo.size.width - 10, height: geo.size.height - 25, alignment: .bottomTrailing) } HStack { Image(systemName: entry.footerImage) .resizable() .scaledToFit() .frame(width: 15, height: 15) .foregroundColor(entry.isPlaceholder ? Color(.systemGray4) : Color(NCBrandColor.shared.brand)) Text(entry.footerText) .font(.caption2) .lineLimit(1) .foregroundColor(entry.isPlaceholder ? Color(.systemGray4) : Color(NCBrandColor.shared.brand)) } .padding(.horizontal, 15.0) .frame(maxWidth: geo.size.width, maxHeight: geo.size.height - 2, alignment: .bottomTrailing) } } } } struct DashboardWidget_Previews: PreviewProvider { static var previews: some View { let datas = Array(dashboardDatasTest[0...4]) let title = "Dashboard" let titleImage = UIImage(named: "widget")! let entry = DashboardDataEntry(date: Date(), datas: datas, dashboard: nil, buttons: nil, isPlaceholder: false, isEmpty: true, titleImage: titleImage, title: title, footerImage: "checkmark.icloud", footerText: "Nextcloud widget") DashboardWidgetView(entry: entry).previewContext(WidgetPreviewContext(family: .systemLarge)) } }
gpl-3.0
988115c61f389535eb8b50fbb3bd2ddf
45.776699
236
0.374948
6.537313
false
false
false
false
rlisle/Patriot-iOS
IntegrationTests/PhotonIntegrationTests.swift
1
6510
// // PhotonIntegrationTests.swift // Patriot // // This is an integration test for the Photon hardware. // // History: major refactor 4/17/16 // // Created by Ron Lisle on 11/13/16. // Copyright © 2016 Ron Lisle. All rights reserved. // import XCTest import Particle_SDK import PromiseKit class PhotonIntegrationTests: XCTestCase { var cloud: ParticleCloud! var photon: Photon? override func setUp() { super.setUp() cloud = ParticleCloud.sharedInstance() photon = nil } //MARK: Tests func test_ThatParticleCloud_IsInstantiated() { XCTAssertNotNil(cloud) } func test_ThatLogin_Succeeds() { let promise = expectation(description: "login") cloud.login(withUser: Secret.TestEmail, password: Secret.TestPassword) { (error) in XCTAssertNil(error) promise.fulfill() } waitForExpectations(timeout: 3) } func test_ThatPhoton_IsSet() { let photonPromise = expectation(description: "photon") _ = login().then { _ in return self.findTestDevice().then { _ -> Void in XCTAssertNotNil(self.photon) photonPromise.fulfill() } } waitForExpectations(timeout: 3) } func test_Photon_ReadVariable_DevicesNotNil() { let expect = expectation(description: "readVariable") _ = login().then { _ in return self.findTestDevice().then { _ -> Promise<Void> in return self.photon!.readVariable("Devices") .then { variable -> Void in expect.fulfill() } } } waitForExpectations(timeout: 3) } func test_RefreshDevices_ReturnsLED() { let expect = expectation(description: "devices") _ = login().then { _ in return self.findTestDevice().then { _ -> Promise<Void> in return self.photon!.refreshDevices().then { _ -> Void in if let devices = self.photon?.devices { XCTAssert(devices.contains("led")) expect.fulfill() } } } } waitForExpectations(timeout: 5) } func test_RefreshSupported_ReturnsPhoton() { let expect = expectation(description: "supported") _ = login().then { _ in return self.findTestDevice().then { _ in return self.photon?.refreshSupported().then { _ -> Void in if let supported = self.photon?.supported { XCTAssert(supported.contains("photon")) expect.fulfill() } } } } waitForExpectations(timeout: 2) } func test_RefreshActivities_ReturnsTest33() { let expect = expectation(description: "activities") _ = login().then { _ in return self.findTestDevice().then { _ -> Void in self.cloud.publishEvent(withName: "patriot", data: "test:33", isPrivate: true, ttl: 60) { (error:Error?) in if let e = error { print("Error publishing event \(e.localizedDescription)") XCTFail() } } _ = self.photon?.refreshActivities().then { _ -> Void in if let activities = self.photon?.activities { XCTAssertEqual(activities["test"], 33) expect.fulfill() } } } } waitForExpectations(timeout: 5) } func test_ReadPublishName_ReturnsNonNil() { let expect = expectation(description: "publish") _ = login().then { _ in return self.findTestDevice() .then { _ in return self.photon?.readPublishName() .then { publish -> Void in print("Publish read: \(publish)") XCTAssertNotNil(publish) expect.fulfill() } } } waitForExpectations(timeout: 2) } func test_Refresh_setsAtLeast1_supported() { let expect = expectation(description: "refresh") _ = login().then { _ in return self.findTestDevice().then { _ in return self.photon?.refresh().then { _ -> Void in XCTAssert((self.photon?.supported?.count)! > 0) expect.fulfill() } } } waitForExpectations(timeout: 5) } func test_Refresh_SetsDevices_ToLED() { let expect = expectation(description: "refresh") _ = login().then { _ in return self.findTestDevice().then { _ in return self.photon?.refresh().then { _ -> Void in XCTAssert((self.photon?.devices?.count)! > 0) XCTAssertEqual(self.photon?.devices?.first, "led") expect.fulfill() } } } waitForExpectations(timeout: 5) } } //MARK: Test Helpers extension PhotonIntegrationTests { @discardableResult func login() -> Promise<Void> { return Promise<Void> { fulfill, reject in cloud.login(withUser: Secret.TestEmail, password: Secret.TestPassword) { (error) in if error != nil { print("Login error: \(error!)") reject(error!) } else { fulfill(()) } } } } func findTestDevice() -> Promise<Photon?> { return Promise<Photon?> { fulfill, reject in cloud.getDevice(Secret.TestDeviceId) { (device: ParticleDevice?, error: Error?) in if error != nil { print("findTestDevice error = \(error!)") reject(error!) } else { self.photon = Photon(device: device!) fulfill(self.photon) } } } } }
bsd-3-clause
4d670968cb7ef7f5471e978504f66f01
27.056034
103
0.480873
5.101097
false
true
false
false
imojiengineering/imoji-ios-sdk-ui
Source/Editor/IMCameraViewController.swift
2
17853
// // ImojiSDKUI // // Created by Alex Hoang // Copyright (C) 2016 Imoji // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. // import UIKit import AVFoundation import CoreMotion import Masonry struct IMCameraViewControllerConstants { static let NavigationBarHeight: CGFloat = 82.0 static let DefaultButtonTopOffset: CGFloat = 30.0 static let CaptureButtonBottomOffset: CGFloat = 20.0 static let CameraViewBottomButtonBottomOffset: CGFloat = 28.0 } @objc public protocol IMCameraViewControllerDelegate { optional func userDidCancelCameraViewController(viewController: IMCameraViewController) optional func userDidCaptureImage(image: UIImage, metadata: NSDictionary?, fromCameraViewController viewController: IMCameraViewController) optional func userDidPickMediaWithInfo(info: [String : AnyObject], fromImagePickerController picker: UIImagePickerController) } @objc public class IMCameraViewController: UIViewController { // Required init variables private(set) public var session: IMImojiSession! // AVFoundation variables private var captureSession: AVCaptureSession! private var backCameraDevice: AVCaptureDevice! private var frontCameraDevice: AVCaptureDevice! private var stillCameraOutput: AVCaptureStillImageOutput! private var captureMotionManager: CMMotionManager! private(set) public var currentOrientation: UIImageOrientation! private var captureSessionQueue: dispatch_queue_t! private var previewView: UIView! private var previewLayer: AVCaptureVideoPreviewLayer! // Top toolbar private var navigationBar: UIToolbar! private var cancelButton: UIBarButtonItem! // Bottom buttons private var captureButton: UIButton! private var flipButton: UIButton! private var photoLibraryButton: UIButton! // Delegate object public var delegate: IMCameraViewControllerDelegate? // MARK: - Object lifecycle public init(session: IMImojiSession) { self.session = session super.init(nibName: nil, bundle: nil) // Create queue for AVCaptureSession captureSessionQueue = dispatch_queue_create("com.sopressata.artmoji.capture_session", DISPATCH_QUEUE_SERIAL) } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - View lifecycle override public func loadView() { super.loadView() view.backgroundColor = UIColor(red: 48.0 / 255.0, green: 48.0 / 255.0, blue: 48.0 / 255.0, alpha: 1.0) // Set up toolbar buttons captureButton = UIButton(type: UIButtonType.Custom) captureButton.addTarget(self, action: #selector(captureButtonTapped), forControlEvents: UIControlEvents.TouchUpInside) let cancelButton = UIButton(type: UIButtonType.Custom) cancelButton.addTarget(self, action: #selector(cancelButtonTapped), forControlEvents: UIControlEvents.TouchUpInside) cancelButton.imageEdgeInsets = UIEdgeInsetsMake(6.25, 6.25, 6.25, 6.25) cancelButton.frame = CGRectMake(0, 0, 50, 50) self.cancelButton = UIBarButtonItem(customView: cancelButton) flipButton = UIButton(type: UIButtonType.Custom) flipButton.addTarget(self, action: #selector(flipButtonTapped), forControlEvents: UIControlEvents.TouchUpInside) photoLibraryButton = UIButton(type: UIButtonType.Custom) photoLibraryButton.addTarget(self, action: #selector(photoLibraryButtonTapped), forControlEvents: UIControlEvents.TouchUpInside) if let bundlePath = NSBundle.init(forClass: IMCameraViewController.self).pathForResource("ImojiEditorAssets", ofType: "bundle") { captureButton.setImage(UIImage(contentsOfFile: String(format: "%@/camera_button.png", bundlePath)), forState: UIControlState.Normal) cancelButton.setImage(UIImage(contentsOfFile: String(format: "%@/camera_cancel.png", bundlePath)), forState: UIControlState.Normal) flipButton.setImage(UIImage(contentsOfFile: String(format: "%@/camera_flipcam.png", bundlePath)), forState: UIControlState.Normal) photoLibraryButton.setImage(UIImage(contentsOfFile: String(format: "%@/camera_photos.png", bundlePath)), forState: UIControlState.Normal) } // Set up top nav bar navigationBar = UIToolbar() navigationBar.clipsToBounds = true navigationBar.setBackgroundImage(UIImage(), forToolbarPosition: UIBarPosition.Any, barMetrics: UIBarMetrics.Default) navigationBar.tintColor = UIColor.whiteColor() navigationBar.barTintColor = UIColor.clearColor() determineCancelCameraButtonVisibility() // Setup AVCaptureSession captureSession = AVCaptureSession() captureSession.sessionPreset = AVCaptureSessionPresetPhoto // Get available devices and save reference to front and back cameras let availableCameraDevices = AVCaptureDevice.devicesWithMediaType(AVMediaTypeVideo) for device in availableCameraDevices as! [AVCaptureDevice] { if device.position == AVCaptureDevicePosition.Back { backCameraDevice = device } else if device.position == AVCaptureDevicePosition.Front { frontCameraDevice = device } } do { self.captureSession.beginConfiguration() let cameraInput = try AVCaptureDeviceInput(device: self.frontCameraDevice) do { try cameraInput.device.lockForConfiguration() if cameraInput.device.isExposureModeSupported(AVCaptureExposureMode.ContinuousAutoExposure) { cameraInput.device.exposureMode = AVCaptureExposureMode.ContinuousAutoExposure } if cameraInput.device.isFocusModeSupported(AVCaptureFocusMode.ContinuousAutoFocus) { cameraInput.device.focusMode = AVCaptureFocusMode.ContinuousAutoFocus } cameraInput.device.unlockForConfiguration() } catch let error as NSError { NSLog("error trying to lock camera for configuration in setup(): \(error)") } if self.captureSession.canAddInput(cameraInput) { self.captureSession.addInput(cameraInput) } self.captureSession.commitConfiguration() } catch let error as NSError { NSLog("error while performing camera configuration: \(error)") } // Add the still image capture to AVCaptureSession stillCameraOutput = AVCaptureStillImageOutput() if captureSession.canAddOutput(stillCameraOutput) { captureSession.addOutput(stillCameraOutput) } // Add subviews view.addSubview(navigationBar) view.addSubview(photoLibraryButton) view.addSubview(flipButton) view.addSubview(captureButton) // Constraints navigationBar.mas_makeConstraints { make in make.top.equalTo()(self.view) make.left.equalTo()(self.view) make.right.equalTo()(self.view) make.height.equalTo()(IMCameraViewControllerConstants.NavigationBarHeight) } photoLibraryButton.mas_makeConstraints { make in make.bottom.equalTo()(self.view).offset()(-IMCameraViewControllerConstants.CameraViewBottomButtonBottomOffset) make.left.equalTo()(self.view).offset()(34) } flipButton.mas_makeConstraints { make in make.bottom.equalTo()(self.view).offset()(-IMCameraViewControllerConstants.CameraViewBottomButtonBottomOffset) make.right.equalTo()(self.view).offset()(-30) } captureButton.mas_makeConstraints { make in make.bottom.equalTo()(self.view).offset()(-IMCameraViewControllerConstants.CaptureButtonBottomOffset) make.centerX.equalTo()(self.view) } } override public func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) // Start tracking accelerometer data captureMotionManager = CMMotionManager() captureMotionManager.accelerometerUpdateInterval = 0.2 captureMotionManager.startAccelerometerUpdatesToQueue(NSOperationQueue()) { accelerometerData, error in if let data = accelerometerData { // Set the image orientation based on device orientation // This will work even if the orientation is locked on the device self.currentOrientation = abs(data.acceleration.y) < abs(data.acceleration.x) ? data.acceleration.x > 0 ? UIImageOrientation.Right : UIImageOrientation.Left : data.acceleration.y > 0 ? UIImageOrientation.Down : UIImageOrientation.Up } } // Reset preview previewView = UIView(frame: CGRectZero) previewView.backgroundColor = view.backgroundColor previewView.frame = view.frame previewLayer = AVCaptureVideoPreviewLayer(session: captureSession) previewLayer.frame = previewView.bounds previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill previewView.layer.addSublayer(previewLayer) // Add preview view.insertSubview(previewView, belowSubview: navigationBar) // Start AVCaptureSession #if (arch(i386) || arch(x86_64)) && os(iOS) #else if checkAuthorizationStatus() == AVAuthorizationStatus.Authorized { dispatch_async(captureSessionQueue) { self.captureSession.startRunning() } } #endif } override public func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) // Stop tracking accelerometer captureMotionManager.stopAccelerometerUpdates() // Remove preview from the view previewLayer.removeFromSuperlayer() previewView.removeFromSuperview() // Stop running AVCaptureSession #if (arch(i386) || arch(x86_64)) && os(iOS) #else if checkAuthorizationStatus() == AVAuthorizationStatus.Authorized { dispatch_async(captureSessionQueue) { self.captureSession.stopRunning() } } #endif } override public func prefersStatusBarHidden() -> Bool { return true } func checkAuthorizationStatus() -> AVAuthorizationStatus { var authorizationStatus = AVCaptureDevice.authorizationStatusForMediaType(AVMediaTypeVideo) switch authorizationStatus { case .NotDetermined: // permission dialog not yet presented, request authorization AVCaptureDevice.requestAccessForMediaType(AVMediaTypeVideo) { granted in if granted { authorizationStatus = .Authorized } else { // user denied, nothing much to do authorizationStatus = .Denied } } break case .Authorized: // go ahead break case .Denied, .Restricted: // the user explicitly denied camera usage or is not allowed to access the camera devices break } return authorizationStatus } func determineCancelCameraButtonVisibility() { if let _ = navigationBar.items, let index = navigationBar.items!.indexOf(cancelButton) { navigationBar.items!.removeAtIndex(index) } if delegate?.userDidCancelCameraViewController != nil { navigationBar.items = [cancelButton] } } // MARK: - Camera button logic func captureButtonTapped() { dispatch_async(captureSessionQueue) { let connection = self.stillCameraOutput.connectionWithMediaType(AVMediaTypeVideo) self.stillCameraOutput.captureStillImageAsynchronouslyFromConnection(connection) { sampleBuffer, error in if error == nil { // if the session preset .Photo is used, or if explicitly set in the device's outputSettings // we get the data already compressed as JPEG let imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(sampleBuffer) // the sample buffer also contains the metadata, in case we want to modify it let metadata = CMCopyDictionaryOfAttachments(nil, sampleBuffer, CMAttachmentMode(kCMAttachmentMode_ShouldPropagate)) if var image = UIImage(data: imageData) { if let currentCameraInput = self.captureSession.inputs.first as? AVCaptureDeviceInput { if currentCameraInput.device.position == AVCaptureDevicePosition.Front { image = IMDrawingUtils().flipImage(image) } } dispatch_async(dispatch_get_main_queue()) { self.delegate?.userDidCaptureImage?(image, metadata: metadata!, fromCameraViewController: self) } } } else { NSLog("error while capturing still image: \(error)") self.showCaptureErrorAlertTitle("Problems", message: "Yikes! There was a problem taking the photo.") } } } } func flipButtonTapped() { dispatch_async(captureSessionQueue) { self.captureSession.beginConfiguration() if let currentCameraInput = self.captureSession.inputs.first as? AVCaptureDeviceInput { self.captureSession.removeInput(currentCameraInput) do { let cameraInput = try AVCaptureDeviceInput(device: currentCameraInput.device.position == AVCaptureDevicePosition.Front ? self.backCameraDevice : self.frontCameraDevice) do { try cameraInput.device.lockForConfiguration() if cameraInput.device.isExposureModeSupported(AVCaptureExposureMode.ContinuousAutoExposure) { cameraInput.device.exposureMode = AVCaptureExposureMode.ContinuousAutoExposure } if cameraInput.device.isFocusModeSupported(AVCaptureFocusMode.ContinuousAutoFocus) { cameraInput.device.focusMode = AVCaptureFocusMode.ContinuousAutoFocus } cameraInput.device.unlockForConfiguration() } catch let error as NSError { NSLog("error while locking camera for configuration in flipButtonTapped(): \(error)") } if self.captureSession.canAddInput(cameraInput) { self.captureSession.addInput(cameraInput) } } catch let error as NSError { NSLog("error while flipping camera: \(error)") } } self.captureSession.commitConfiguration() } } func photoLibraryButtonTapped() { if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.PhotoLibrary) { let picker = UIImagePickerController() picker.delegate = self picker.allowsEditing = false picker.sourceType = UIImagePickerControllerSourceType.PhotoLibrary picker.modalPresentationStyle = UIModalPresentationStyle.CurrentContext presentViewController(picker, animated: true, completion: nil) } else { showCaptureErrorAlertTitle("Photo Library Unavailable", message: "Yikes! There's a problem accessing your photo library.") } } func cancelButtonTapped() { delegate?.userDidCancelCameraViewController?(self) } func showCaptureErrorAlertTitle(title: String, message: String) { let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert) alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: nil)) presentViewController(alert, animated: true, completion: nil) } } // MARK: - UIImagePickerControllerDelegate extension IMCameraViewController: UIImagePickerControllerDelegate { public func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) { delegate?.userDidPickMediaWithInfo?(info, fromImagePickerController: picker) } } // MARK: - UINavigationControllerDelegate extension IMCameraViewController: UINavigationControllerDelegate { }
mit
cc091f041d46f7dc949596471c53a7c1
43.081481
188
0.669355
5.803966
false
false
false
false
bwoods/SQLite.swift
SQLite/Extensions/FTS4.swift
3
11713
// // SQLite.swift // https://github.com/stephencelis/SQLite.swift // Copyright © 2014-2015 Stephen Celis. // // 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. // extension Module { @warn_unused_result public static func FTS4(column: Expressible, _ more: Expressible...) -> Module { return FTS4([column] + more) } @warn_unused_result public static func FTS4(columns: [Expressible] = [], tokenize tokenizer: Tokenizer? = nil) -> Module { return FTS4(FTS4Config().columns(columns).tokenizer(tokenizer)) } @warn_unused_result public static func FTS4(config: FTS4Config) -> Module { return Module(name: "fts4", arguments: config.arguments()) } } extension VirtualTable { /// Builds an expression appended with a `MATCH` query against the given /// pattern. /// /// let emails = VirtualTable("emails") /// /// emails.filter(emails.match("Hello")) /// // SELECT * FROM "emails" WHERE "emails" MATCH 'Hello' /// /// - Parameter pattern: A pattern to match. /// /// - Returns: An expression appended with a `MATCH` query against the given /// pattern. @warn_unused_result public func match(pattern: String) -> Expression<Bool> { return "MATCH".infix(tableName(), pattern) } @warn_unused_result public func match(pattern: Expression<String>) -> Expression<Bool> { return "MATCH".infix(tableName(), pattern) } @warn_unused_result public func match(pattern: Expression<String?>) -> Expression<Bool?> { return "MATCH".infix(tableName(), pattern) } /// Builds a copy of the query with a `WHERE … MATCH` clause. /// /// let emails = VirtualTable("emails") /// /// emails.match("Hello") /// // SELECT * FROM "emails" WHERE "emails" MATCH 'Hello' /// /// - Parameter pattern: A pattern to match. /// /// - Returns: A query with the given `WHERE … MATCH` clause applied. @warn_unused_result public func match(pattern: String) -> QueryType { return filter(match(pattern)) } @warn_unused_result public func match(pattern: Expression<String>) -> QueryType { return filter(match(pattern)) } @warn_unused_result public func match(pattern: Expression<String?>) -> QueryType { return filter(match(pattern)) } } public struct Tokenizer { public static let Simple = Tokenizer("simple") public static let Porter = Tokenizer("porter") @warn_unused_result public static func Unicode61(removeDiacritics removeDiacritics: Bool? = nil, tokenchars: Set<Character> = [], separators: Set<Character> = []) -> Tokenizer { var arguments = [String]() if let removeDiacritics = removeDiacritics { arguments.append("removeDiacritics=\(removeDiacritics ? 1 : 0)".quote()) } if !tokenchars.isEmpty { let joined = tokenchars.map { String($0) }.joinWithSeparator("") arguments.append("tokenchars=\(joined)".quote()) } if !separators.isEmpty { let joined = separators.map { String($0) }.joinWithSeparator("") arguments.append("separators=\(joined)".quote()) } return Tokenizer("unicode61", arguments) } @warn_unused_result public static func Custom(name: String) -> Tokenizer { return Tokenizer(Tokenizer.moduleName.quote(), [name.quote()]) } public let name: String public let arguments: [String] private init(_ name: String, _ arguments: [String] = []) { self.name = name self.arguments = arguments } private static let moduleName = "SQLite.swift" } extension Tokenizer : CustomStringConvertible { public var description: String { return ([name] + arguments).joinWithSeparator(" ") } } extension Connection { public func registerTokenizer(submoduleName: String, next: String -> (String, Range<String.Index>)?) throws { try check(_SQLiteRegisterTokenizer(handle, Tokenizer.moduleName, submoduleName) { input, offset, length in let string = String.fromCString(input)! guard let (token, range) = next(string) else { return nil } let view = string.utf8 offset.memory += string.substringToIndex(range.startIndex).utf8.count length.memory = Int32(range.startIndex.samePositionIn(view).distanceTo(range.endIndex.samePositionIn(view))) return token }) } } /// Configuration options shared between the [FTS4](https://www.sqlite.org/fts3.html) and /// [FTS5](https://www.sqlite.org/fts5.html) extensions. public class FTSConfig { public enum ColumnOption { /// [The notindexed= option](https://www.sqlite.org/fts3.html#section_6_5) case unindexed } typealias ColumnDefinition = (Expressible, options: [ColumnOption]) var columnDefinitions = [ColumnDefinition]() var tokenizer: Tokenizer? var prefixes = [Int]() var externalContentSchema: SchemaType? var isContentless: Bool = false /// Adds a column definition public func column(column: Expressible, _ options: [ColumnOption] = []) -> Self { self.columnDefinitions.append((column, options)) return self } public func columns(columns: [Expressible]) -> Self { for column in columns { self.column(column) } return self } /// [Tokenizers](https://www.sqlite.org/fts3.html#tokenizer) public func tokenizer(tokenizer: Tokenizer?) -> Self { self.tokenizer = tokenizer return self } /// [The prefix= option](https://www.sqlite.org/fts3.html#section_6_6) public func prefix(prefix: [Int]) -> Self { self.prefixes += prefix return self } /// [The content= option](https://www.sqlite.org/fts3.html#section_6_2) public func externalContent(schema: SchemaType) -> Self { self.externalContentSchema = schema return self } /// [Contentless FTS4 Tables](https://www.sqlite.org/fts3.html#section_6_2_1) public func contentless() -> Self { self.isContentless = true return self } func formatColumnDefinitions() -> [Expressible] { return columnDefinitions.map { $0.0 } } func arguments() -> [Expressible] { return options().arguments } func options() -> Options { var options = Options() options.append(formatColumnDefinitions()) if let tokenizer = tokenizer { options.append("tokenize", value: Expression<Void>(literal: tokenizer.description)) } options.appendCommaSeparated("prefix", values:prefixes.sort().map { String($0) }) if isContentless { options.append("content", value: "") } else if let externalContentSchema = externalContentSchema { options.append("content", value: externalContentSchema.tableName()) } return options } struct Options { var arguments = [Expressible]() mutating func append(columns: [Expressible]) -> Options { arguments.appendContentsOf(columns) return self } mutating func appendCommaSeparated(key: String, values: [String]) -> Options { if values.isEmpty { return self } else { return append(key, value: values.joinWithSeparator(",")) } } mutating func append(key: String, value: CustomStringConvertible?) -> Options { return append(key, value: value?.description) } mutating func append(key: String, value: String?) -> Options { return append(key, value: value.map { Expression<String>($0) }) } mutating func append(key: String, value: Expressible?) -> Options { if let value = value { arguments.append("=".join([Expression<Void>(literal: key), value])) } return self } } } /// Configuration for the [FTS4](https://www.sqlite.org/fts3.html) extension. public class FTS4Config : FTSConfig { /// [The matchinfo= option](https://www.sqlite.org/fts3.html#section_6_4) public enum MatchInfo : CustomStringConvertible { case FTS3 public var description: String { return "fts3" } } /// [FTS4 options](https://www.sqlite.org/fts3.html#fts4_options) public enum Order : CustomStringConvertible { /// Data structures are optimized for returning results in ascending order by docid (default) case Asc /// FTS4 stores its data in such a way as to optimize returning results in descending order by docid. case Desc public var description: String { switch self { case Asc: return "asc" case Desc: return "desc" } } } var compressFunction: String? var uncompressFunction: String? var languageId: String? var matchInfo: MatchInfo? var order: Order? override public init() { } /// [The compress= and uncompress= options](https://www.sqlite.org/fts3.html#section_6_1) public func compress(functionName: String) -> Self { self.compressFunction = functionName return self } /// [The compress= and uncompress= options](https://www.sqlite.org/fts3.html#section_6_1) public func uncompress(functionName: String) -> Self { self.uncompressFunction = functionName return self } /// [The languageid= option](https://www.sqlite.org/fts3.html#section_6_3) public func languageId(columnName: String) -> Self { self.languageId = columnName return self } /// [The matchinfo= option](https://www.sqlite.org/fts3.html#section_6_4) public func matchInfo(matchInfo: MatchInfo) -> Self { self.matchInfo = matchInfo return self } /// [FTS4 options](https://www.sqlite.org/fts3.html#fts4_options) public func order(order: Order) -> Self { self.order = order return self } override func options() -> Options { var options = super.options() for (column, _) in (columnDefinitions.filter { $0.options.contains(.unindexed) }) { options.append("notindexed", value: column) } options.append("languageid", value: languageId) options.append("compress", value: compressFunction) options.append("uncompress", value: uncompressFunction) options.append("matchinfo", value: matchInfo) options.append("order", value: order) return options } }
mit
d421828b15f8763e2bd8ef742b50fe63
33.233918
181
0.635463
4.378459
false
false
false
false
bjvanlinschoten/Pala
Pala/Pala/WallCollectionViewController.swift
1
7623
// // WallCollectionViewController.swift // Pala // // Created by Boris van Linschoten on 09-06-15. // Copyright (c) 2015 bjvanlinschoten. All rights reserved. // import UIKit class WallCollectionViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout { // Properties var wallUserArray: [Person]? var currentUser: User? var wall: Wall? let sectionInsets = UIEdgeInsets(top: 15.0, left: 15.0, bottom: 15.0, right: 15.0) var selectedGender: NSInteger? var refreshControl: UIRefreshControl! @IBOutlet var wallCollection: UICollectionView! @IBOutlet var centerLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.wallCollection.delegate = self self.wallCollection.dataSource = self self.addLeftBarButtonWithImage(UIImage(named: "Pagoda.png")!) self.addRightBarButtonWithImage(UIImage(named: "Match.png")!) self.navigationController?.navigationBar.barTintColor = UIColor(hexString: "FF7400", alpha: 1) self.navigationController?.navigationBar.tintColor = UIColor.whiteColor() self.navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.whiteColor()] // Pull to refresh self.refreshControl = UIRefreshControl() self.refreshControl.attributedTitle = NSAttributedString(string: "Pull to refresh") self.refreshControl.addTarget(self, action: "refreshWallCollectionView", forControlEvents: UIControlEvents.ValueChanged) self.wallCollection.addSubview(self.refreshControl) self.wallCollection.alwaysBounceVertical = true // appearance self.automaticallyAdjustsScrollViewInsets = false self.wallCollection.hidden = true self.centerLabel.hidden = false } // Reload collection view when Wall will appear from Event selection func appearsFromEventSelect() { if let selectedEventId = self.wall?.selectedEvent["id"] as? String { self.wall!.getUsersToShow(selectedEventId, selectedGender: self.wall!.selectedGender!) { (userArray: [Person]) -> Void in if userArray != [] { self.wallUserArray = userArray as [Person] self.centerLabel.hidden = true self.wallCollection.reloadData() } else { self.centerLabel.text = "You've either (dis)liked everyone already or you're the only one going!" } self.wallCollection.hidden = false self.title = self.wall?.selectedEvent["name"] as? String MBProgressHUD.hideHUDForView(self.view, animated: true) } } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: UICollectionViewDataSource func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { return 1 } func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { if let array = self.wallUserArray { return array.count } else { return 0 } } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier("wallCell", forIndexPath: indexPath) as! WallCollectionViewCell // Person shown in the cell let person = wallUserArray![indexPath.row] as Person // Set picture let picURL: NSURL! = NSURL(string: "https://graph.facebook.com/\(person.facebookId)/picture?width=600&height=600") cell.imageView.frame = CGRectMake(10,10,150,230) cell.imageView.sd_setImageWithURL(picURL) cell.nameLabel.text = "\(person.name) (\(person.getPersonAge()))" // Set images on buttons cell.dislikeButton.imageView?.contentMode = UIViewContentMode.ScaleAspectFit cell.likeButton.imageView?.contentMode = UIViewContentMode.ScaleAspectFit // Set drop shadow cell.layer.masksToBounds = false cell.layer.shadowOpacity = 0.3 cell.layer.shadowRadius = 1.0 cell.layer.shadowOffset = CGSize(width: 2, height: 2) return cell } func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize { return CGSize(width: 160, height: 280) } func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets { return sectionInsets } // Liking a user @IBAction func likeUser(sender: UIButton){ let cell = sender.superview! as! WallCollectionViewCell let indexPath = self.wallCollection.indexPathForCell(cell) let likedUser = wallUserArray![indexPath!.row] as Person MBProgressHUD.showHUDAddedTo(self.view, animated: true) self.wall!.likeUser(likedUser) {(result: Bool) -> Void in if result == true { let matchAlert: UIAlertView = UIAlertView(title: "New match!", message: "It's a match! Go meet up!", delegate: self, cancelButtonTitle: "Nice!") matchAlert.show() } self.removeUserFromWall(indexPath!) MBProgressHUD.hideHUDForView(self.view, animated: true) } } // Disliking a user @IBAction func dislikeUser(sender: UIButton){ let cell = sender.superview! as! WallCollectionViewCell let indexPath = self.wallCollection.indexPathForCell(cell) let dislikedUser = wallUserArray![indexPath!.row] as Person self.wall!.dislikeUser(dislikedUser.objectId) self.removeUserFromWall(indexPath!) } // Remove user from wall after (dis)liking func removeUserFromWall(indexPath: NSIndexPath) { self.wallUserArray?.removeAtIndex(indexPath.row) if self.wallUserArray! == [] { self.centerLabel.text = "No more users left!" self.centerLabel.hidden = false self.wallCollection.hidden = true } self.wallCollection.reloadData() } // Pull to refresh voor wall collectionview func refreshWallCollectionView() { self.currentUser?.parseUser.fetchInBackgroundWithBlock({ (object: PFObject?, error: NSError?) -> Void in self.wall!.getUsersToShow(self.wall!.selectedEvent!["id"] as! String, selectedGender: self.wall!.selectedGender!) { (userArray: [Person]) -> Void in if userArray != [] { self.wallUserArray = userArray as [Person] self.wallCollection.hidden = false self.centerLabel.hidden = true self.wallCollection.reloadData() } else { self.wallUserArray = [] self.wallCollection.hidden = true self.centerLabel.hidden = false self.centerLabel.text = "You've either (dis)liked everyone already or you're the only one going!" } self.refreshControl.endRefreshing() } }) } }
mit
ff658871c4649350fe59cf6a8b0650ba
41.121547
169
0.650794
5.164634
false
false
false
false
voyages-sncf-technologies/Collor
Example/Tests/CollectionDatasTest.swift
1
2920
// // CollectionDataTest.swift // Collor // // Created by Guihal Gwenn on 03/05/17. // Copyright (c) 2017-present, Voyages-sncf.com. All rights reserved.. All rights reserved. // import XCTest @testable import Collor class CollectionDataTest: XCTestCase { var data:TestData! override func setUp() { super.setUp() data = TestData() data.reloadData() data.computeIndices() // not linked with collectionView } override func tearDown() { super.tearDown() } func testGetSectionDescribableAtIndexPath() { // given let indexPath = IndexPath(item: 0, section: 1) // when let sectionDescriptor = data.sectionDescribable(at: indexPath) // then XCTAssertTrue(sectionDescriptor === data.sections[1]) } func testGetSectionDescribableAtIndexPathNil() { // given let indexPath = IndexPath(item: 0, section: 10) // when let sectionDescriptor = data.sectionDescribable(at: indexPath) // then XCTAssertNil(sectionDescriptor) } func testGetSectionDescribableForCell() { // given let cellDescriptor = data.sections[1].cells[2] // when let sectionDescriptor = data.sectionDescribable(for: cellDescriptor) // then XCTAssertTrue(sectionDescriptor === data.sections[1]) } func testGetCellDescribable() { // given let indexPath = IndexPath(item: 1, section: 0) // when let cellDescriptor = data.cellDescribable(at: indexPath) // then XCTAssertTrue(cellDescriptor === data.sections[0].cells[1]) } func testGetCellDescribableNil() { // given let indexPath = IndexPath(item: 20, section: 3) // when let cellDescriptor = data.cellDescribable(at: indexPath) // then XCTAssertNil(cellDescriptor) } func testGetSupplementaryViewDescribableNil() { // given let indexPath = IndexPath(item: 1, section: 8) // when let descriptor = data.supplementaryViewDescribable(at: indexPath, for: "test") // then XCTAssertNil(descriptor) } func testGetSupplementaryViewDescribable() { // given let indexPath = IndexPath(item: 1, section: 2) // when let descriptor = data.supplementaryViewDescribable(at: indexPath, for: "test") // then XCTAssertTrue(descriptor === data.sections[2].supplementaryViews["test"]?[1]) } func testGetSupplementaryViewDescribableIndexPath() { // given let indexPath = IndexPath(item: 1, section: 2) // when let descriptor = data.supplementaryViewDescribable(at: indexPath, for: "test") // then XCTAssertEqual(descriptor?.indexPath, indexPath) } }
bsd-3-clause
11970500861977c48f970672aba070dc
27.627451
92
0.608904
4.794745
false
true
false
false
michael-lehew/swift-corelibs-foundation
Foundation/ProgressFraction.swift
2
11442
// This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // // Implementation note: This file is included in both the framework and the test bundle, in order for us to be able to test it directly. Once @testable support works for Linux we may be able to use it from the framework instead. internal struct _ProgressFraction : Equatable, CustomDebugStringConvertible { var completed : Int64 var total : Int64 private(set) var overflowed : Bool init() { completed = 0 total = 0 overflowed = false } init(double: Double, overflow: Bool = false) { if double == 0 { self.completed = 0 self.total = 1 } else if double == 1 { self.completed = 1 self.total = 1 } (self.completed, self.total) = _ProgressFraction._fromDouble(double) self.overflowed = overflow } init(completed: Int64, total: Int64) { self.completed = completed self.total = total self.overflowed = false } // ---- internal mutating func simplify() { if self.total == 0 { return } (self.completed, self.total) = _ProgressFraction._simplify(completed, total) } internal func simplified() -> _ProgressFraction { let simplified = _ProgressFraction._simplify(completed, total) return _ProgressFraction(completed: simplified.0, total: simplified.1) } static private func _math(lhs: _ProgressFraction, rhs: _ProgressFraction, whichOperator: (_ lhs : Double, _ rhs : Double) -> Double, whichOverflow : (_ lhs: Int64, _ rhs: Int64) -> (Int64, overflow: Bool)) -> _ProgressFraction { // Mathematically, it is nonsense to add or subtract something with a denominator of 0. However, for the purposes of implementing Progress' fractions, we just assume that a zero-denominator fraction is "weightless" and return the other value. We still need to check for the case where they are both nonsense though. precondition(!(lhs.total == 0 && rhs.total == 0), "Attempt to add or subtract invalid fraction") guard lhs.total != 0 else { return rhs } guard rhs.total != 0 else { return lhs } guard !lhs.overflowed && !rhs.overflowed else { // If either has overflowed already, we preserve that return _ProgressFraction(double: whichOperator(lhs.fractionCompleted, rhs.fractionCompleted), overflow: true) } if let lcm = _leastCommonMultiple(lhs.total, rhs.total) { let result = whichOverflow(lhs.completed * (lcm / lhs.total), rhs.completed * (lcm / rhs.total)) if result.overflow { return _ProgressFraction(double: whichOperator(lhs.fractionCompleted, rhs.fractionCompleted), overflow: true) } else { return _ProgressFraction(completed: result.0, total: lcm) } } else { // Overflow - simplify and then try again let lhsSimplified = lhs.simplified() let rhsSimplified = rhs.simplified() if let lcm = _leastCommonMultiple(lhsSimplified.total, rhsSimplified.total) { let result = whichOverflow(lhsSimplified.completed * (lcm / lhsSimplified.total), rhsSimplified.completed * (lcm / rhsSimplified.total)) if result.overflow { // Use original lhs/rhs here return _ProgressFraction(double: whichOperator(lhs.fractionCompleted, rhs.fractionCompleted), overflow: true) } else { return _ProgressFraction(completed: result.0, total: lcm) } } else { // Still overflow return _ProgressFraction(double: whichOperator(lhs.fractionCompleted, rhs.fractionCompleted), overflow: true) } } } static internal func +(lhs: _ProgressFraction, rhs: _ProgressFraction) -> _ProgressFraction { return _math(lhs: lhs, rhs: rhs, whichOperator: +, whichOverflow: Int64.addWithOverflow) } static internal func -(lhs: _ProgressFraction, rhs: _ProgressFraction) -> _ProgressFraction { return _math(lhs: lhs, rhs: rhs, whichOperator: -, whichOverflow: Int64.subtractWithOverflow) } static internal func *(lhs: _ProgressFraction, rhs: _ProgressFraction) -> _ProgressFraction { guard !lhs.overflowed && !rhs.overflowed else { // If either has overflowed already, we preserve that return _ProgressFraction(double: rhs.fractionCompleted * rhs.fractionCompleted, overflow: true) } let newCompleted = Int64.multiplyWithOverflow(lhs.completed, rhs.completed) let newTotal = Int64.multiplyWithOverflow(lhs.total, rhs.total) if newCompleted.overflow || newTotal.overflow { // Try simplifying, then do it again let lhsSimplified = lhs.simplified() let rhsSimplified = rhs.simplified() let newCompletedSimplified = Int64.multiplyWithOverflow(lhsSimplified.completed, rhsSimplified.completed) let newTotalSimplified = Int64.multiplyWithOverflow(lhsSimplified.total, rhsSimplified.total) if newCompletedSimplified.overflow || newTotalSimplified.overflow { // Still overflow return _ProgressFraction(double: lhs.fractionCompleted * rhs.fractionCompleted, overflow: true) } else { return _ProgressFraction(completed: newCompletedSimplified.0, total: newTotalSimplified.0) } } else { return _ProgressFraction(completed: newCompleted.0, total: newTotal.0) } } static internal func /(lhs: _ProgressFraction, rhs: Int64) -> _ProgressFraction { guard !lhs.overflowed else { // If lhs has overflowed, we preserve that return _ProgressFraction(double: lhs.fractionCompleted / Double(rhs), overflow: true) } let newTotal = Int64.multiplyWithOverflow(lhs.total, rhs) if newTotal.overflow { let simplified = lhs.simplified() let newTotalSimplified = Int64.multiplyWithOverflow(simplified.total, rhs) if newTotalSimplified.overflow { // Still overflow return _ProgressFraction(double: lhs.fractionCompleted / Double(rhs), overflow: true) } else { return _ProgressFraction(completed: lhs.completed, total: newTotalSimplified.0) } } else { return _ProgressFraction(completed: lhs.completed, total: newTotal.0) } } static internal func ==(lhs: _ProgressFraction, rhs: _ProgressFraction) -> Bool { if lhs.isNaN || rhs.isNaN { // NaN fractions are never equal return false } else if lhs.completed == rhs.completed && lhs.total == rhs.total { return true } else if lhs.total == rhs.total { // Direct comparison of numerator return lhs.completed == rhs.completed } else if lhs.completed == 0 && rhs.completed == 0 { return true } else if lhs.completed == lhs.total && rhs.completed == rhs.total { // Both finished (1) return true } else if (lhs.completed == 0 && rhs.completed != 0) || (lhs.completed != 0 && rhs.completed == 0) { // One 0, one not 0 return false } else { // Cross-multiply let left = Int64.multiplyWithOverflow(lhs.completed, rhs.total) let right = Int64.multiplyWithOverflow(lhs.total, rhs.completed) if !left.overflow && !right.overflow { if left.0 == right.0 { return true } } else { // Try simplifying then cross multiply again let lhsSimplified = lhs.simplified() let rhsSimplified = rhs.simplified() let leftSimplified = Int64.multiplyWithOverflow(lhsSimplified.completed, rhsSimplified.total) let rightSimplified = Int64.multiplyWithOverflow(lhsSimplified.total, rhsSimplified.completed) if !leftSimplified.overflow && !rightSimplified.overflow { if leftSimplified.0 == rightSimplified.0 { return true } } else { // Ok... fallback to doubles. This doesn't use an epsilon return lhs.fractionCompleted == rhs.fractionCompleted } } } return false } // ---- internal var isIndeterminate : Bool { return completed < 0 || total < 0 || (completed == 0 && total == 0) } internal var isFinished : Bool { return ((completed >= total) && completed > 0 && total > 0) || (completed > 0 && total == 0) } internal var fractionCompleted : Double { if isIndeterminate { // Return something predictable return 0.0 } else if total == 0 { // When there is nothing to do, you're always done return 1.0 } else { return Double(completed) / Double(total) } } internal var isNaN : Bool { return total == 0 } internal var debugDescription : String { return "\(completed) / \(total) (\(fractionCompleted))" } // ---- private static func _fromDouble(_ d : Double) -> (Int64, Int64) { // This simplistic algorithm could someday be replaced with something better. // Basically - how many 1/Nths is this double? // And we choose to use 131072 for N let denominator : Int64 = 131072 let numerator = Int64(d / (1.0 / Double(denominator))) return (numerator, denominator) } private static func _greatestCommonDivisor(_ inA : Int64, _ inB : Int64) -> Int64 { // This is Euclid's algorithm. There are faster ones, like Knuth, but this is the simplest one for now. var a = inA var b = inB repeat { let tmp = b b = a % b a = tmp } while (b != 0) return a } private static func _leastCommonMultiple(_ a : Int64, _ b : Int64) -> Int64? { // This division always results in an integer value because gcd(a,b) is a divisor of a. // lcm(a,b) == (|a|/gcd(a,b))*b == (|b|/gcd(a,b))*a let result = Int64.multiplyWithOverflow((a / _greatestCommonDivisor(a, b)), b) if result.overflow { return nil } else { return result.0 } } private static func _simplify(_ n : Int64, _ d : Int64) -> (Int64, Int64) { let gcd = _greatestCommonDivisor(n, d) return (n / gcd, d / gcd) } }
apache-2.0
49bf615f152fc007c337bd1784669613
40.456522
323
0.586349
4.803526
false
false
false
false
addisflava/iSub
Classes/BookmarksViewController.swift
2
21604
// // BookmarksViewController.swift // iSub // // Created by Ben Baron on 5/10/10. // Copyright 2010 Ben Baron. All rights reserved. // import Foundation import UIKit public class BookmarksViewController: CustomUITableViewController { private let _database = DatabaseSingleton.sharedInstance() private let _settings = SavedSettings.sharedInstance() private let _playlist = PlaylistSingleton.sharedInstance() private let _music = MusicSingleton.sharedInstance() private let _jukebox = JukeboxSingleton.sharedInstance() private let _reuseIdentifier = "Bookmark Cell" private var _multiDeleteList = [Int]() private var _isNoBookmarksScreenShowing = false private let _noBookmarksScreen = UIImageView() private let _textLabel = UILabel() private let _headerView = UIView() private let _bookmarkCountLabel = UILabel() private let _deleteBookmarksButton = UIButton.buttonWithType(UIButtonType.Custom) as UIButton private let _deleteBookmarksLabel = UILabel() private let _editBookmarksLabel = UILabel() private let _editBookmarksButton = UIButton.buttonWithType(UIButtonType.Custom) as UIButton private var _bookmarkIds = [Int]() // MARK: - View Lifecycle - deinit { NSNotificationCenter.defaultCenter().removeObserver(self) } public override func viewDidLoad() { super.viewDidLoad() self.title = "Bookmarks" } public override func customizeTableView(tableView: UITableView!) { tableView.registerClass(CustomUITableViewCell.self, forCellReuseIdentifier: _reuseIdentifier) tableView.separatorColor = UIColor.clearColor() tableView.rowHeight = ISMSAlbumCellHeight + ISMSCellHeaderHeight } public override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) self.tableView.tableHeaderView = nil if _isNoBookmarksScreenShowing { _noBookmarksScreen.removeFromSuperview() _isNoBookmarksScreenShowing = false } // TODO: Switch back to intForQuery once the header issues are sorted var bookmarksCount = 0; _database.bookmarksDbQueue.inDatabase({ (db: FMDatabase!) in let result = db.executeQuery("SELECT COUNT(*) FROM bookmarks", withArgumentsInArray:[]) if result.next() { bookmarksCount = Int(result.intForColumnIndex(0)) } }) if bookmarksCount == 0 { _isNoBookmarksScreenShowing = true if _noBookmarksScreen.subviews.count == 0 { _noBookmarksScreen.autoresizingMask = UIViewAutoresizing.FlexibleLeftMargin | UIViewAutoresizing.FlexibleTopMargin | UIViewAutoresizing.FlexibleRightMargin | UIViewAutoresizing.FlexibleBottomMargin _noBookmarksScreen.frame = CGRectMake(40, 100, 240, 180) _noBookmarksScreen.center = CGPointMake(self.view.bounds.size.width / 2.0, self.view.bounds.size.height / 2.0) _noBookmarksScreen.image = UIImage(named:"loading-screen-image") _noBookmarksScreen.alpha = 0.80 _textLabel.backgroundColor = UIColor.clearColor() _textLabel.textColor = UIColor.whiteColor() _textLabel.font = ISMSBoldFont(30) _textLabel.textAlignment = NSTextAlignment.Center _textLabel.numberOfLines = 0 _textLabel.frame = CGRectMake(20, 20, 200, 140) _noBookmarksScreen.addSubview(_textLabel) } if _settings.isOfflineMode { _textLabel.text = "No Offline\nBookmarks" } else { _textLabel.text = "No Saved\nBookmarks" } self.view.addSubview(_noBookmarksScreen) } else { if _headerView.subviews.count == 0 { _headerView.frame = CGRectMake(0, 0, 320, 50) _headerView.backgroundColor = UIColor(white:0.3, alpha:1.0) _bookmarkCountLabel.frame = CGRectMake(0, 0, 232, 50) _bookmarkCountLabel.autoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleRightMargin _bookmarkCountLabel.backgroundColor = UIColor.clearColor() _bookmarkCountLabel.textColor = UIColor.whiteColor() _bookmarkCountLabel.textAlignment = NSTextAlignment.Center _bookmarkCountLabel.font = ISMSBoldFont(22) _headerView.addSubview(_bookmarkCountLabel) _deleteBookmarksButton.autoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleRightMargin _deleteBookmarksButton.frame = CGRectMake(0, 0, 232, 50) _deleteBookmarksButton.addTarget(self, action:"_deleteBookmarksAction:", forControlEvents:UIControlEvents.TouchUpInside) _headerView.addSubview(_deleteBookmarksButton) _editBookmarksLabel.frame = CGRectMake(232, 0, 88, 50) _editBookmarksLabel.autoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleLeftMargin _editBookmarksLabel.backgroundColor = UIColor.clearColor() _editBookmarksLabel.textColor = UIColor.whiteColor() _editBookmarksLabel.textAlignment = NSTextAlignment.Center _editBookmarksLabel.font = ISMSBoldFont(22) _editBookmarksLabel.text = "Edit" _headerView.addSubview(_editBookmarksLabel) _editBookmarksButton.autoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleLeftMargin _editBookmarksButton.frame = CGRectMake(232, 0, 88, 40) _editBookmarksButton.addTarget(self, action:"_editBookmarksAction:", forControlEvents:UIControlEvents.TouchUpInside) _headerView.addSubview(_editBookmarksButton) _deleteBookmarksLabel.frame = CGRectMake(0, 0, 232, 50) _deleteBookmarksLabel.autoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleRightMargin _deleteBookmarksLabel.backgroundColor = UIColor(red:1, green:0, blue:0, alpha:0.5) _deleteBookmarksLabel.textColor = UIColor.whiteColor() _deleteBookmarksLabel.textAlignment = NSTextAlignment.Center _deleteBookmarksLabel.font = ISMSBoldFont(22) _deleteBookmarksLabel.adjustsFontSizeToFitWidth = true _deleteBookmarksLabel.minimumScaleFactor = 12.0 / _deleteBookmarksLabel.font.pointSize _deleteBookmarksLabel.text = "Remove # Bookmarks" _deleteBookmarksLabel.hidden = true _headerView.addSubview(_deleteBookmarksLabel) } _bookmarkCountLabel.text = bookmarksCount == 1 ? "1 Bookmark" : "\(bookmarksCount) Bookmarks" self.tableView.tableHeaderView = _headerView } _loadBookmarkIds() self.tableView.reloadData() Flurry.logEvent("BookmarksTab") } public override func viewWillDisappear(animated: Bool) { _bookmarkIds.removeAll() } private func _loadBookmarkIds() { var bookmarkIdsTemp = [Int]() _database.bookmarksDbQueue.inDatabase({ (db: FMDatabase!) in let query = "SELECT bookmarkId FROM bookmarks" let result = db.executeQuery(query, withArgumentsInArray: []) while result.next() { autoreleasepool { if let bookmarkId = result.objectForColumnIndex(0) as? Int { bookmarkIdsTemp.append(bookmarkId) } } } result.close() }) _bookmarkIds = bookmarkIdsTemp } private func _stringForCount(count: Int) -> String { switch count { case 0: return "Clear Bookmarks" case 1: return "Remove 1 Bookmark" default: return "Remove \(count) Bookmarks" } } private func _showDeleteButton() { _deleteBookmarksLabel.text = _stringForCount(_multiDeleteList.count) _bookmarkCountLabel.hidden = true _deleteBookmarksLabel.hidden = false } private func _hideDeleteButton() { _deleteBookmarksLabel.text = _stringForCount(_multiDeleteList.count) if _multiDeleteList.count == 0 && !self.tableView.editing { _bookmarkCountLabel.hidden = false _deleteBookmarksLabel.hidden = true } else { _deleteBookmarksLabel.text = "Clear Bookmarks" } } public func _editBookmarksAction(sender: AnyObject?) { if self.tableView.editing { NSNotificationCenter.defaultCenter().removeObserver(self, name:ISMSNotification_ShowDeleteButton, object:nil) NSNotificationCenter.defaultCenter().removeObserver(self, name:ISMSNotification_HideDeleteButton, object:nil) _multiDeleteList.removeAll() self.tableView.setEditing(false, animated:true) _hideDeleteButton() _editBookmarksLabel.backgroundColor = UIColor.clearColor() _editBookmarksLabel.text = "Edit" self.hideDeleteToggles() // Reload the table self.viewWillAppear(false) } else { NSNotificationCenter.defaultCenter().addObserver(self, selector:"_showDeleteButton", name:ISMSNotification_ShowDeleteButton, object:nil) NSNotificationCenter.defaultCenter().addObserver(self, selector:"_hideDeleteButton", name:ISMSNotification_HideDeleteButton, object:nil) _multiDeleteList.removeAll() self.tableView.setEditing(true, animated:true) _editBookmarksLabel.backgroundColor = UIColor(red:0.008, green:0.46, blue:0.933, alpha:1) _editBookmarksLabel.text = "Done" _showDeleteButton() self.showDeleteToggles() } } public func _deleteBookmarksAction(sender: AnyObject?) { // TODO: Don't use a string check for this, tisk tisk if _deleteBookmarksLabel.text == "Clear Bookmarks" { _database.bookmarksDbQueue.inDatabase({ (db: FMDatabase!) in db.executeUpdate("DROP TABLE IF EXISTS bookmarks", withArgumentsInArray:[]) db.executeUpdate("CREATE TABLE bookmarks (bookmarkId INTEGER PRIMARY KEY, playlistIndex INTEGER, name TEXT, position INTEGER, \(ISMSSong.standardSongColumnSchema()), bytes INTEGER)", withArgumentsInArray:[]) db.executeUpdate("CREATE INDEX songId ON bookmarks (songId)", withArgumentsInArray:[]) }) _editBookmarksAction(nil) // Reload table data // TODO: Stop calling view delegate methods directly self.viewWillAppear(false) } else { var indexPaths = [AnyObject]() for index in _multiDeleteList { indexPaths.append(NSIndexPath(forRow:index, inSection:0)) let bookmarkId = _bookmarkIds[index] _database.bookmarksDbQueue.inDatabase({ (db: FMDatabase!) in db.executeUpdate("DELETE FROM bookmarks WHERE bookmarkId = ?", withArgumentsInArray:[bookmarkId]) return }) } _loadBookmarkIds() self.tableView.deleteRowsAtIndexPaths(indexPaths, withRowAnimation:UITableViewRowAnimation.Automatic) _editBookmarksAction(nil) } } } extension BookmarksViewController: UITableViewDelegate, UITableViewDataSource { /*public override func tableView(tableView: UITableView, moveRowAtIndexPath sourceIndexPath: NSIndexPath, toIndexPath destinationIndexPath: NSIndexPath) { // Move the bookmark _database.bookmarksDbQueue.inDatabase({ (db: FMDatabase!) in let fromRow = sourceIndexPath.row + 1 let toRow = destinationIndexPath.row + 1 db.executeUpdate("DROP TABLE bookmarksTemp", withArgumentsInArray:[]) db.executeUpdate("CREATE TABLE bookmarks (bookmarkId INTEGER PRIMARY KEY, playlistIndex INTEGER, name TEXT, position INTEGER, \(ISMSSong.standardSongColumnSchema()), bytes INTEGER)", withArgumentsInArray:[]) if fromRow < toRow { db.executeUpdate("INSERT INTO bookmarksTemp SELECT * FROM bookmarks WHERE ROWID < ?", withArgumentsInArray:[fromRow]) db.executeUpdate("INSERT INTO bookmarksTemp SELECT * FROM bookmarks WHERE ROWID > ? AND ROWID <= ?", withArgumentsInArray:[fromRow, toRow]) db.executeUpdate("INSERT INTO bookmarksTemp SELECT * FROM bookmarks WHERE ROWID = ?", withArgumentsInArray:[fromRow]) db.executeUpdate("INSERT INTO bookmarksTemp SELECT * FROM bookmarks WHERE ROWID > ?", withArgumentsInArray:[toRow]) db.executeUpdate("DROP TABLE bookmarks", withArgumentsInArray:[]) db.executeUpdate("ALTER TABLE bookmarksTemp RENAME TO bookmarks", withArgumentsInArray:[]) db.executeUpdate("CREATE INDEX songId ON bookmarks (songId)", withArgumentsInArray:[]) } else { db.executeUpdate("INSERT INTO bookmarksTemp SELECT * FROM bookmarks WHERE ROWID < ?", withArgumentsInArray:[toRow]) db.executeUpdate("INSERT INTO bookmarksTemp SELECT * FROM bookmarks WHERE ROWID = ?", withArgumentsInArray:[fromRow]) db.executeUpdate("INSERT INTO bookmarksTemp SELECT * FROM bookmarks WHERE ROWID >= ? AND ROWID < ?", withArgumentsInArray:[toRow, fromRow]) db.executeUpdate("INSERT INTO bookmarksTemp SELECT * FROM bookmarks WHERE ROWID > ?", withArgumentsInArray:[fromRow]) db.executeUpdate("DROP TABLE bookmarks", withArgumentsInArray:[]) db.executeUpdate("ALTER TABLE bookmarksTemp RENAME TO bookmarks", withArgumentsInArray:[]) db.executeUpdate("CREATE INDEX songId ON bookmarks (songId)", withArgumentsInArray:[]) } }) // Fix the multiDeleteList to reflect the new row positions if _multiDeleteList.count > 0 { let fromRow = sourceIndexPath.row let toRow = destinationIndexPath.row var tempMultiDeleteList = [Int]() var newPosition: Int = 0 for position in _multiDeleteList { if fromRow > toRow { if position >= toRow && position <= fromRow { if position == fromRow { tempMultiDeleteList.append(toRow) } else { newPosition = position + 1 tempMultiDeleteList.append(newPosition) } } else { tempMultiDeleteList.append(position) } } else { if position <= toRow && position >= fromRow { if position == fromRow { tempMultiDeleteList.append(toRow) } else { newPosition = position - 1 tempMultiDeleteList.append(newPosition) } } else { tempMultiDeleteList.append(position) } } } _multiDeleteList = tempMultiDeleteList } } public override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { return true }*/ public override func tableView(tableView: UITableView, editingStyleForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCellEditingStyle { return UITableViewCellEditingStyle.None } public override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } public override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return _bookmarkIds.count } public override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier(_reuseIdentifier, forIndexPath:indexPath) as CustomUITableViewCell cell.selectionStyle = UITableViewCellSelectionStyle.None cell.overlayDisabled = true cell.indexPath = indexPath cell.markedForDelete = contains(_multiDeleteList, indexPath.row) // Set up the cell... var song: ISMSSong? = nil var name: String? = nil var position: Double? = nil _database.bookmarksDbQueue.inDatabase({ (db: FMDatabase!) in let bookmarkId = self._bookmarkIds[indexPath.row] let result = db.executeQuery("SELECT * FROM bookmarks WHERE bookmarkId = ?", withArgumentsInArray:[bookmarkId]) song = ISMSSong(fromDbResult:result) name = result.stringForColumn("name") position = result.doubleForColumn("position") result.close() }) cell.coverArtId = song!.coverArtId cell.headerTitle = "\(name!) - \(NSString.formatTime(position!))" cell.title = song!.title cell.subTitle = song!.albumName == nil ? song!.artistName : "\(song!.artistName) - \(song!.albumName)" return cell } public override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { if _settings.isJukeboxEnabled { _database.resetJukeboxPlaylist() _jukebox.jukeboxClearRemotePlaylist() } else { _database.resetCurrentPlaylistDb() } _playlist.isShuffle = false let bookmarkId = self._bookmarkIds[indexPath.row] var playlistIndex = 0 var offsetSeconds = 0 var offsetBytes = 0 var song: ISMSSong? = nil _database.bookmarksDbQueue.inDatabase({ (db: FMDatabase!) in let result = db.executeQuery("SELECT * FROM bookmarks WHERE bookmarkId = ?", withArgumentsInArray:[bookmarkId]) song = ISMSSong(fromDbResult: result) playlistIndex = Int(result.intForColumn("playlistIndex")) offsetSeconds = Int(result.intForColumn("position")) offsetBytes = Int(result.intForColumn("bytes")) result.close() }) // See if there's a playlist table for this bookmark if _database.bookmarksDbQueue.tableExists("bookmark\(bookmarkId)") { // Save the playlist let databaseName = _settings.isOfflineMode ? "offlineCurrentPlaylist.db" : "\(_settings.urlString.md5())currentPlaylist.db" let currTable = _settings.isJukeboxEnabled ? "jukeboxCurrentPlaylist" : "currentPlaylist" let shufTable = _settings.isJukeboxEnabled ? "jukeboxShufflePlaylist" : "shufflePlaylist" let table = _playlist.isShuffle ? shufTable : currTable _database.bookmarksDbQueue.inDatabase({ (db: FMDatabase!) in let database = self._database.databaseFolderPath + "/" + databaseName db.executeUpdate("ATTACH DATABASE ? AS ?", withArgumentsInArray:[database, "currentPlaylistDb"]) db.executeUpdate("INSERT INTO currentPlaylistDb.\(table) SELECT * FROM bookmark\(bookmarkId)", withArgumentsInArray:[]) db.executeUpdate("DETACH DATABASE currentPlaylistDb", withArgumentsInArray:[]) }) if _settings.isJukeboxEnabled { _jukebox.jukeboxReplacePlaylistWithLocal() } } else { song?.addToCurrentPlaylistDbQueue() } _playlist.currentIndex = playlistIndex NSNotificationCenter.postNotificationToMainThreadWithName(ISMSNotification_CurrentPlaylistSongsQueued) self.showPlayer() // Check if these are old bookmarks and don't have byteOffset saved if offsetBytes == 0 && offsetSeconds != 0 { // By default, use the server reported bitrate var bitrate = Int(song!.bitRate) if song!.transcodedSuffix != nil { // This is a transcode, guess the bitrate and byteoffset let maxBitrate = _settings.currentMaxBitrate == 0 ? 128 : _settings.currentMaxBitrate bitrate = maxBitrate < bitrate ? maxBitrate : bitrate } // Use the bitrate to get byteoffset offsetBytes = BytesForSecondsAtBitrate(offsetSeconds, bitrate) } if _settings.isJukeboxEnabled { _music.playSongAtPosition(playlistIndex) } else { _music.startSongAtOffsetInBytes(UInt64(offsetBytes), andSeconds:Double(offsetSeconds)) } } }
gpl-3.0
fe5f55b2792acff6cad9190442ebf932
46.170306
223
0.616506
5.598342
false
false
false
false
prebid/prebid-mobile-ios
InternalTestApp/PrebidMobileDemoRendering/ViewControllers/Configuration/NativeAdConfigEditor/Extensions/FormViewController+RowBuildHelpers.swift
1
17569
/*   Copyright 2018-2021 Prebid.org, Inc.  Licensed under the Apache License, Version 2.0 (the "License");  you may not use this file except in compliance with the License.  You may obtain a copy of the License at  http://www.apache.org/licenses/LICENSE-2.0  Unless required by applicable law or agreed to in writing, software  distributed under the License is distributed on an "AS IS" BASIS,  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the License for the specific language governing permissions and  limitations under the License.  */ import Foundation import UIKit import Eureka import PrebidMobile protocol RowBuildHelpConsumer: FormViewController { associatedtype DataContainer var dataContainer: DataContainer? { get } var requiredPropertiesSection: Section { get } var optionalPropertiesListSection: Section { get } var optionalPropertiesValuesSection: Section { get } var onExit: ()->() { get set } } extension RowBuildHelpConsumer { func include_tag(field: String) -> String { return "\(field)_include" } func value_tag(field: String) -> String { return "\(field)_value" } private func makeIncudeRow<T>(_ field: String, keyPath: ReferenceWritableKeyPath<DataContainer, T?>, defVal: T, onChange: ((CheckRow)->())? = nil) -> CheckRow { return CheckRow(include_tag(field: field)) { [weak self] row in row.title = field row.value = self?.dataContainer?[keyPath: keyPath] != nil } .cellSetup { [weak self] cell, row in cell.accessibilityIdentifier = self?.include_tag(field: field) } .onChange { [weak self] row in self?.dataContainer?[keyPath: keyPath] = (row.value == true) ? defVal : nil onChange?(row) } } private func makeValueRow<T, C:Cell<T>, U:RowType&FieldRow<C>>(_ field: String, rowGen: (String, (U)->()) -> U, src: @escaping ()->T?, dst: @escaping (T?)->()) -> U { return rowGen(value_tag(field: field)) { row in row.title = field row.value = src() row.hidden = Condition.function([include_tag(field: field)]) { _ in src() == nil } } .cellSetup { [weak self] cell, row in row.value = src() cell.textField.accessibilityIdentifier = self?.value_tag(field: field) } .onChange { (row: U) in dst(row.value) } } private func makeOptionalValueRow<V, T, C:Cell<T>, U:RowType&FieldRow<C>>(_ field: String, keyPath: ReferenceWritableKeyPath<DataContainer, V?>, rowGen: (String, (U)->()) -> U, rawValGen: @escaping (V)->T, valGen: @escaping (T)->V) -> U { let boxVal: (T?)->V? = { ($0 == nil) ? nil : valGen($0!) } let unboxVal: (V?)->(T?) = { ($0 == nil) ? nil : rawValGen($0!) } return makeValueRow(field, rowGen: rowGen, src: { [weak self] in unboxVal(self?.dataContainer?[keyPath: keyPath]) }, dst: { [weak self] in self?.dataContainer?[keyPath: keyPath] = boxVal($0) }) } private func makeRequiredValueRow<T, C:Cell<T>, U:RowType&FieldRow<C>>(_ field: String, keyPath: ReferenceWritableKeyPath<DataContainer, T>, rowGen: (String, (U)->()) -> U, defVal: T) -> U { return makeValueRow(field, rowGen: rowGen, src: { [weak self] in self?.dataContainer?[keyPath: keyPath] }, dst: { [weak self] in self?.dataContainer?[keyPath: keyPath] = $0 ?? defVal }) } func makeRequiredIntRow(_ field: String, keyPath: ReferenceWritableKeyPath<DataContainer, Int>) -> IntRow { return makeRequiredValueRow(field, keyPath: keyPath, rowGen: IntRow.init, defVal: 0) } func makeRequiredEnumRow<T: RawRepresentable>(_ field: String, keyPath: ReferenceWritableKeyPath<DataContainer, T>, defVal: T) -> IntRow where T.RawValue == Int { return makeValueRow(field, rowGen: IntRow.init, src: { [weak self] in self?.dataContainer?[keyPath: keyPath].rawValue }, dst: { [weak self] in if let intVal = $0, let enumVal = T(rawValue: intVal) { self?.dataContainer?[keyPath: keyPath] = enumVal } }) } func makeOptionalIntRow(_ field: String, keyPath: ReferenceWritableKeyPath<DataContainer, NSNumber?>) -> IntRow { return makeOptionalValueRow(field, keyPath: keyPath, rowGen: IntRow.init, rawValGen: { $0.intValue }, valGen: NSNumber.init) } func makeOptionalStringRow(_ field: String, keyPath: ReferenceWritableKeyPath<DataContainer, String?>) -> TextRow { return makeOptionalValueRow(field, keyPath: keyPath, rowGen: TextRow.init, rawValGen: { $0 }, valGen: { $0 }) } func makeArrayEditorRow<T>(_ field:String, getter: ()->[T]?, setter: ([T]?)->(), hidden: Condition? = nil, onSelect: @escaping ()->()) -> LabelRow { LabelRow(value_tag(field: field)) { row in row.title = field row.hidden = hidden } .cellSetup { [weak self] cell, row in cell.accessibilityIdentifier = self?.include_tag(field: field) cell.accessoryType = .disclosureIndicator } .onCellSelection { cell, row in cell.isSelected = false onSelect() } } func makeArrayEditorRow<T>(_ field:String, keyPath: ReferenceWritableKeyPath<DataContainer, [T]>,s hidden: Condition? = nil, onSelect: @escaping ()->()) -> LabelRow { return makeArrayEditorRow(field, getter: { [weak self] in self?.dataContainer?[keyPath: keyPath] }, setter: { [weak self] in self?.dataContainer?[keyPath: keyPath] = $0 ?? [] }, hidden: hidden, onSelect: onSelect) } func addOptionalString(_ field:String, keyPath: ReferenceWritableKeyPath<DataContainer, String?>) { let valueRow = makeOptionalStringRow(field, keyPath: keyPath) optionalPropertiesValuesSection <<< valueRow optionalPropertiesListSection <<< makeIncudeRow(field, keyPath: keyPath, defVal: "") { [weak self] row in if row.value == true { valueRow.value = self?.dataContainer?[keyPath: keyPath] valueRow.updateCell() } } } func addOptionalInt(_ field:String, keyPath: ReferenceWritableKeyPath<DataContainer, NSNumber?>) { let valueRow = makeOptionalIntRow(field, keyPath: keyPath) optionalPropertiesValuesSection <<< valueRow optionalPropertiesListSection <<< makeIncudeRow(field, keyPath: keyPath, defVal: 0) { [weak self] row in if row.value == true { valueRow.value = self?.dataContainer?[keyPath: keyPath]?.intValue ?? 0 valueRow.updateCell() } } } func addInt(_ field:String, keyPath: ReferenceWritableKeyPath<DataContainer, Int>) { let valueRow = makeRequiredIntRow(field, keyPath: keyPath) requiredPropertiesSection <<< valueRow } func addEnum<T: RawRepresentable>(_ field:String, keyPath: ReferenceWritableKeyPath<DataContainer, T>, defVal: T) where T.RawValue == Int { let valueRow = makeRequiredEnumRow(field, keyPath: keyPath, defVal: defVal) optionalPropertiesValuesSection <<< valueRow } func addOptionalArray<T>(_ field:String, keyPath: ReferenceWritableKeyPath<DataContainer, [T]?>, onSelect: @escaping ()->()) { optionalPropertiesListSection <<< makeIncudeRow(field, keyPath: keyPath, defVal: []) { [weak self] row in self?.updateArrayCount(field: field, count: self?.dataContainer?[keyPath: keyPath]?.count ?? 0) } let hidden = Condition.function([include_tag(field: field)]) { [weak self] _ in self?.dataContainer?[keyPath: keyPath] == nil } optionalPropertiesValuesSection <<< makeArrayEditorRow(field, getter: { [weak self] in self?.dataContainer?[keyPath: keyPath] }, setter: { [weak self] in self?.dataContainer?[keyPath: keyPath] = $0 ?? [] }, hidden: hidden, onSelect: onSelect) } func updateArrayCount(field: String, count: Int) { if let arrayButtonRow = form.rowBy(tag: value_tag(field: field)) as? LabelRow { arrayButtonRow.value = "\(count)" arrayButtonRow.updateCell() } } func makeMultiValuesSection<T, C:Cell<T>, U:RowType&FieldRow<C>>(field: String, getter: @escaping ()->[T]?, setter: @escaping ([T]?)->(), rowGen: @escaping (String?, (U)->()) -> U, defVal: T? = nil, hidden: Condition? = nil) -> MultivaluedSection { let valuesSection = MultivaluedSection(multivaluedOptions: [.Insert, .Reorder, .Delete], header: field, footer: nil) { section in func makeValRow(value: T?) -> U { return rowGen(nil) { row in row.title = field row.value = value } } section.addButtonProvider = { _ in ButtonRow() { row in row.title = "Add \(field.capitalized)" } } section.multivaluedRowToInsertAt = { _ in makeValRow(value: defVal) } getter()?.map(makeValRow).forEach(section.append) section.hidden = hidden } let oldOnExit = onExit onExit = { oldOnExit() setter(valuesSection.values().compactMap { $0 as? T }) } return valuesSection } func addOptionalMultiValuesSection<T, V, C:Cell<V>, U:RowType&FieldRow<C>>(field: String, keyPath: ReferenceWritableKeyPath<DataContainer, [T]?>, rowGen: @escaping (String?, (U)->()) -> U, rawValGen: @escaping (V)->T, valGen: @escaping (T)->V, defVal: V? = nil) { let boxVal: (T?)->V? = { ($0 == nil) ? nil : valGen($0!) } let unboxVal: (V?)->(T?) = { ($0 == nil) ? nil : rawValGen($0!) } var valuesSection = makeMultiValuesSection(field: field, getter: { [weak self] in self?.dataContainer?[keyPath: keyPath]?.compactMap(boxVal) }, setter: { [weak self] in self?.dataContainer?[keyPath: keyPath] = $0?.compactMap(unboxVal) }, rowGen: rowGen, defVal: defVal, hidden: Condition.function([include_tag(field: field)]) { [weak self] _ in self?.dataContainer?[keyPath: keyPath] == nil }) optionalPropertiesListSection <<< makeIncudeRow(field, keyPath: keyPath, defVal: []) { row in if row.value == true { valuesSection.removeSubrange(0..<(valuesSection.count-1)) } } form +++ valuesSection } func addRequiredIntArrayField(field: String, keyPath: ReferenceWritableKeyPath<DataContainer, [NSNumber]>) { form +++ makeMultiValuesSection(field: field, getter: { [weak self] in self?.dataContainer?[keyPath: keyPath].map { $0.intValue } }, setter: { [weak self] in self?.dataContainer?[keyPath: keyPath] = ($0 ?? []).map(NSNumber.init) }, rowGen: IntRow.init, defVal: 0) } func addRequiredIntArrayField(field: String, keyPath: ReferenceWritableKeyPath<DataContainer, [Int]>) { form +++ makeMultiValuesSection(field: field, getter: { [weak self] in self?.dataContainer?[keyPath: keyPath].map { $0 } }, setter: { [weak self] in self?.dataContainer?[keyPath: keyPath] = ($0 ?? []) }, rowGen: IntRow.init, defVal: 0) } func addRequiredStringArrayField(field: String, keyPath: ReferenceWritableKeyPath<DataContainer, [String]>) { form +++ makeMultiValuesSection(field: field, getter: { [weak self] in self?.dataContainer?[keyPath: keyPath] }, setter: { [weak self] in self?.dataContainer?[keyPath: keyPath] = $0 ?? [] }, rowGen: TextRow.init, defVal: "") } func addOptionalStringArrayField(field: String, keyPath: ReferenceWritableKeyPath<DataContainer, [String]?>) { addOptionalMultiValuesSection(field: field, keyPath: keyPath, rowGen: TextRow.init, rawValGen: { $0 }, valGen: { $0 }, defVal: "") } func addExtRow(field: String, src: KeyPath<DataContainer, [String: Any]?>, dst: @escaping (DataContainer) -> ([String: Any]?) throws -> ()) { optionalPropertiesListSection <<< CheckRow(include_tag(field: field)) { [weak self] row in row.title = field row.value = self?.dataContainer?[keyPath: src] != nil } .onChange { [weak self] row in guard let self = self, let dataContainer = self.dataContainer, let valueRow = self.form.rowBy(tag: self.value_tag(field: field)) as? TextRow else { return } if row.value == true { try? dst(dataContainer)([:]) valueRow.value = "{}" } else { try? dst(dataContainer)([:]) valueRow.value = nil } valueRow.updateCell() } optionalPropertiesValuesSection <<< TextRow(value_tag(field: field)) { row in row.title = field row.value = { if let dic = dataContainer?[keyPath: src], let data = try? JSONSerialization.data(withJSONObject: dic, options: []), let str = String(data: data, encoding: .utf8) { return str } else { return nil } }() row.hidden = Condition.function([include_tag(field: field)]) { [weak self] _ in self?.dataContainer?[keyPath: src] == nil } } .onChange { [weak self] row in if let self = self, let dataContainer = self.dataContainer, let data = row.value?.data(using: .utf8), let obj = try? JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] { try? dst(dataContainer)(obj) } } } }
apache-2.0
587bc0d178b41785689fd35b2655bd86
47.502762
166
0.480636
5.161082
false
false
false
false
wordpress-mobile/WordPress-iOS
WordPress/WordPressTest/StockPhotosMediaGroupTests.swift
2
1337
import XCTest @testable import WordPress final class StockPhotosMediaGroupTests: XCTestCase { private var mediaGroup: StockPhotosMediaGroup? private struct Constants { static let name = String.freePhotosLibrary static let mediaRequestID: WPMediaRequestID = 0 static let baseGroup = "" static let identifier = "group id" static let numberOfAssets = 10 } override func setUp() { super.setUp() mediaGroup = StockPhotosMediaGroup() } override func tearDown() { mediaGroup = nil super.tearDown() } func testGroupNameMatchesExpectation() { XCTAssertEqual(mediaGroup!.name(), Constants.name) } func testGroupMediaRequestIDMatchesExpectation() { XCTAssertEqual(mediaGroup!.image(with: .zero, completionHandler: { (image, error) in }), Constants.mediaRequestID) } func testBaseGroupIsEmpty() { XCTAssertEqual(mediaGroup!.baseGroup() as! String, Constants.baseGroup) } func testIdentifierMatchesExpectation() { XCTAssertEqual(mediaGroup!.identifier(), Constants.identifier) } func testNumberOfAssetsMatchExpectation() { let numberOfAssets = mediaGroup?.numberOfAssets(of: .image) XCTAssertEqual(numberOfAssets, Constants.numberOfAssets) } }
gpl-2.0
2ce082b9a4ab5a312bb6a974992a421e
27.446809
92
0.682124
4.97026
false
true
false
false
wordpress-mobile/WordPress-iOS
WordPress/Classes/ViewRelated/Site Creation/Shared/ShadowView.swift
2
1400
final class ShadowView: UIView { private let shadowLayer = CAShapeLayer() private let shadowMaskLayer = CAShapeLayer() private enum Appearance { static let shadowColor: UIColor = .black static let shadowOpacity: Float = 0.20 static let shadowRadius: CGFloat = 8.0 static let shadowOffset = CGSize(width: 0.0, height: 5.0) } func addShadow() { shadowLayer.shadowPath = UIBezierPath(roundedRect: layer.bounds, cornerRadius: 0.0).cgPath shadowLayer.shadowColor = Appearance.shadowColor.cgColor shadowLayer.shadowOpacity = Appearance.shadowOpacity shadowLayer.shadowRadius = Appearance.shadowRadius shadowLayer.shadowOffset = Appearance.shadowOffset layer.insertSublayer(shadowLayer, at: 0) shadowMaskLayer.fillRule = CAShapeLayerFillRule.evenOdd shadowLayer.mask = shadowMaskLayer updateShadowPath() } private func updateShadowPath() { let shadowPath = UIBezierPath(roundedRect: bounds, cornerRadius: 0.0).cgPath shadowLayer.shadowPath = shadowPath let maskPath = CGMutablePath() let topInset: CGFloat = 5.0 maskPath.addRect(bounds.insetBy(dx: 0.0, dy: -topInset)) maskPath.addPath(shadowPath) shadowMaskLayer.path = maskPath } func clearShadow() { shadowLayer.removeFromSuperlayer() } }
gpl-2.0
fa1af8c4016f6cd4b7b59f997e8a65a4
34
98
0.685
5.223881
false
false
false
false
Aaron-zheng/yugioh
yugioh/DeckViewEntity.swift
1
639
// // DeckView.swift // yugioh // // Created by Aaron on 6/8/2017. // Copyright © 2017 sightcorner. All rights reserved. // import Foundation class DeckViewEntity { // 卡组的唯一标识 public var id: String = "" // 卡组名称 public var title: String = "" // 卡组介绍 public var introduction: String = "" // 卡组类型 public var type: String = "" init() { } init(id: String, title: String, introduction: String, type: String) { self.id = id self.title = title self.introduction = introduction self.type = type } }
agpl-3.0
dd5d9b8e9b5e27f41fd5a9f72ffa11fb
17.75
73
0.56
3.614458
false
false
false
false
aidos9/my-notes
My notes/notesTableVC.swift
1
5036
// // notesTableVC.swift // My notes // // Created by Aidyn Malojer on 13/12/16. // Copyright © 2016 Aidyn Malojer. All rights reserved. // import UIKit import CoreData class notesTableVC: UITableViewController { var notebook: Notebook? { didSet{ self.navigationItem.title = notebook!.title! } } var textNotes = [TextNote]() override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .compose, target: self, action: #selector(composePressed)) } func fetchNotes(){ textNotes.removeAll() let title = notebook?.title let app = UIApplication.shared.delegate as! AppDelegate let context = app.persistentContainer.viewContext let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "TextNote") do{ let results = try context.fetch(fetchRequest) let notes = results as! [TextNote] for note in notes{ print(note.noteBook!) if note.noteBook == title{ textNotes.append(note) } } }catch let err as NSError{ print(err.description) } tableView.reloadData() } override func viewWillAppear(_ animated: Bool) { fetchNotes() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func composePressed(){ performSegue(withIdentifier: "createNewNoteSegue", sender: notebook) } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return textNotes.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "notesCell", for: indexPath) as! notesCell let note = textNotes[indexPath.row] cell.titleLabel.text = note.title cell.descLabel.text = note.content cell.dateLabel.text = note.dateCreated return cell } /* // Override to support conditional editing of the table view. override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> 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, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { let app = UIApplication.shared.delegate as! AppDelegate let context = app.persistentContainer.viewContext let note = textNotes[indexPath.row] context.delete(note) do{ try context.save() textNotes.remove(at: indexPath.row) }catch{ print("Error deleting a note: \(error)") } tableView.deleteRows(at: [indexPath], with: .fade) } } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { performSegue(withIdentifier: "editNote", sender: textNotes[indexPath.row]) } /* // Override to support rearranging the table view. override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> 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 prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "createNewNoteSegue"{ let dest = segue.destination as! newNoteVC dest.noteBook = sender as? Notebook }else if segue.identifier == "editNote"{ let dest = segue.destination as! editNoteVC dest.note = sender as? TextNote } } }
mit
d0aca55a98bb7f2c0630832cff3b4b05
33.486301
144
0.639921
5.158811
false
false
false
false
algolia/algoliasearch-client-swift
Sources/AlgoliaSearchClient/Transport/URLSession/URLRequest+APIKey.swift
1
2135
// // URLRequest+APIKey.swift // // // Created by Vladislav Fitc on 20/07/2022. // import Foundation #if canImport(FoundationNetworking) import FoundationNetworking #endif extension URLRequest { static let maxHeaderAPIKeyLength = 500 internal mutating func setAPIKey(_ apiKey: APIKey?) throws { guard let apiKeyValue = apiKey?.rawValue, apiKeyValue.count > URLRequest.maxHeaderAPIKeyLength else { self[header: .apiKey] = apiKey?.rawValue return } Logger.warning("The API length is > \(URLRequest.maxHeaderAPIKeyLength). Attempt to insert it into request body.") guard let body = httpBody else { throw APIKeyBodyError.missingHTTPBody } let decodingResult = Result { try JSONDecoder().decode(JSON.self, from: body) } guard case .success(let bodyJSON) = decodingResult else { if case .failure(let error) = decodingResult { throw APIKeyBodyError.bodyDecodingJSONError(error) } return } guard case .dictionary(var jsonDictionary) = bodyJSON else { throw APIKeyBodyError.bodyNonKeyValueJSON } jsonDictionary["apiKey"] = .string(apiKeyValue) let encodingResult = Result { try JSONEncoder().encode(jsonDictionary) } guard case .success(let updatedBody) = encodingResult else { if case .failure(let error) = encodingResult { throw APIKeyBodyError.bodyEncodingJSONError(error) } return } httpBody = updatedBody } } public extension URLRequest { enum APIKeyBodyError: Error, CustomStringConvertible { case missingHTTPBody case bodyDecodingJSONError(Error) case bodyNonKeyValueJSON case bodyEncodingJSONError(Error) public var description: String { switch self { case .missingHTTPBody: return "Request doesn't contain HTTP body" case .bodyDecodingJSONError(let error): return "HTTP body JSON decoding error: \(error)" case .bodyEncodingJSONError(let error): return "HTTP body JSON encoding error: \(error)" case .bodyNonKeyValueJSON: return "HTTP body JSON is not key-value type" } } } }
mit
fa81631b08345ce06bddd580d2da1cca
26.025316
118
0.695082
4.581545
false
false
false
false
phuongvnc/CPConfettiView
CPConfettiView/CPConfettiView.swift
1
2406
// // CPConfettiView.swift // CPConfettiViewExample // // Created by framgia on 3/3/17. // Copyright © 2017 Vo Nguyen Chi Phuong. All rights reserved. // import Foundation import UIKit import QuartzCore public enum CPConfettiDirection { case Top case Bottom } public class CPConfettiView: UIView { var emitter: CAEmitterLayer = CAEmitterLayer() public var intensity: Float! private var active :Bool! private var image: UIImage? var direction: CPConfettiDirection = .Top required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } public override init(frame: CGRect) { super.init(frame: frame) setup() } func setup() { intensity = 0.5 direction = .Top active = false } // Duration is time active anitmation.Default is 0 -> It won't stop public func startConfetti(duration: TimeInterval = 0) { guard let _ = image else { return } let x = frame.size.width / 2 let y = direction == .Top ? 0 : frame.size.height emitter.emitterPosition = CGPoint(x: x, y: y) emitter.emitterShape = kCAEmitterLayerLine emitter.emitterSize = CGSize(width: frame.size.width, height: 1) emitter.birthRate = 1 emitter.emitterCells = [confettiWithColor()] layer.addSublayer(emitter) active = true if duration != 0 { DispatchQueue.main.asyncAfter(deadline: .now() + duration, execute: { self.stopConfetti() }) } } public func stopConfetti() { emitter.birthRate = 0 active = false } public func setImageForConfetti(image: UIImage) { self.image = image } func confettiWithColor() -> CAEmitterCell { let confetti = CAEmitterCell() confetti.birthRate = 4 * intensity confetti.lifetime = 10 confetti.velocity = CGFloat(350 * intensity) confetti.velocityRange = CGFloat(80.0 * intensity) confetti.emissionLongitude = direction == .Top ? CGFloat(M_PI) : CGFloat(0) confetti.emissionRange = CGFloat(M_PI / 10) confetti.scale = 1 confetti.scaleRange = 0.5 confetti.contents = image!.cgImage return confetti } public func isActive() -> Bool { return self.active } }
mit
5af9a18ee078e2f0d1d42cf2b1f1b2cb
25.141304
83
0.609979
4.412844
false
false
false
false
t2421/iOS-snipet
iOS-snipets/samples/FontNameViewController.swift
1
1851
// // FontNameViewController.swift // iOS-snipets // // Created by taigakiyotaki on 2015/07/21. // Copyright (c) 2015年 taigakiyotaki. All rights reserved. // @see https://github.com/shu223/iOS8-Sampler/blob/master/iOS8Sampler/Samples/FontsViewController.m // import UIKit class FontNameViewController: UIViewController,UITableViewDataSource,UITableViewDelegate { var fontList:[AnyObject]!; @IBOutlet weak var tableView: UITableView! override func viewDidLoad() { super.viewDidLoad() fontList = UIFont.familyNames(); print(UIFont.familyNames()); tableView.delegate = self; tableView.dataSource = self; // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return fontList.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "Cell") let fontName = fontList[indexPath.row] as! String; let font:UIFont = UIFont(name: fontName, size: 19.0)!; cell.textLabel?.font = font; cell.textLabel?.text = fontName; return cell } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
6c2d04220c849f2d8917d000f0220b10
33.240741
114
0.689562
4.753213
false
false
false
false
Urinx/SublimeCode
Sublime/Pods/AlamofireRSSParser/Pod/Classes/RSSFeed.swift
1
1391
// // RSSFeed.swift // AlamofireRSSParser // // Created by Donald Angelillo on 3/1/16. // Copyright © 2016 Donald Angelillo. All rights reserved. // import Foundation /** RSS gets deserialized into an instance of `RSSFeed`. Top-level RSS elements are housed here. Item-level elements are deserialized into `RSSItem` objects and stored in the `items` property. */ public class RSSFeed: CustomStringConvertible { public var title: String? = nil public var link: String? = nil public var feedDescription: String? = nil public var pubDate: NSDate? = nil public var lastBuildDate: NSDate? = nil public var language: String? = nil public var copyright: String? = nil public var managingEditor: String? = nil public var webMaster: String? = nil public var generator: String? = nil public var docs: String? = nil public var ttl: NSNumber? = nil public var items: [RSSItem] = Array() public var description: String { return "title: \(self.title)\nfeedDescription: \(self.feedDescription)\nlink: \(self.link)\npubDate: \(self.pubDate)\nlastBuildDate: \(self.lastBuildDate)\nlanguage: \(self.language)\ncopyright: \(self.copyright)\nmanagingEditor: \(self.managingEditor)\nwebMaster: \(self.webMaster)\ngenerator: \(self.generator)\ndocs: \(self.docs)\nttl: \(self.ttl)\nitems: \n\(self.items)" } }
gpl-3.0
9acf95bf4f4588ee9dd8ac8c179db575
37.638889
383
0.693525
3.787466
false
false
false
false
AymenFarrah/PlayAir
PlayAir/PARadio.swift
1
901
// // PARadio.swift // PlayAir // // Created by Aymen on 14/02/2016. // Copyright © 2016 Farrah. All rights reserved. // import Foundation class PARadio: NSObject { var radioId : Int! var name : String! var url : NSURL! var picto : String! var desc : String! var categories : Array<String>! var isFavorite : Bool! init(radioId: Int, name: String, url: NSURL, picto: String, desc: String, categories: Array<String>) { super.init() self.radioId = radioId self.name = name self.url = url self.picto = picto self.desc = desc self.categories = categories self.isFavorite = false } override var description: String { return "radioId: \(radioId)" + "name: \(name)" + "url: \(url)" + "picto: \(picto)" + "desc: \(desc)" } }
mit
664ae878a3f51f1f415bb10ac18a8cb9
21.525
106
0.546667
3.557312
false
false
false
false
shajrawi/swift
test/decl/nested/type_in_type.swift
1
9618
// RUN: %target-typecheck-verify-swift struct OuterNonGeneric { struct MidNonGeneric { struct InnerNonGeneric {} struct InnerGeneric<A> {} } struct MidGeneric<B> { struct InnerNonGeneric {} struct InnerGeneric<C> {} func flock(_ b: B) {} } } struct OuterGeneric<D> { struct MidNonGeneric { struct InnerNonGeneric {} struct InnerGeneric<E> {} func roost(_ d: D) {} } struct MidGeneric<F> { struct InnerNonGeneric {} struct InnerGeneric<G> {} func nest(_ d: D, f: F) {} } func nonGenericMethod(_ d: D) { func genericFunction<E>(_ d: D, e: E) {} genericFunction(d, e: ()) } } class OuterNonGenericClass { enum InnerNonGeneric { case Baz case Zab } class InnerNonGenericBase { init() {} } class InnerNonGenericClass1 : InnerNonGenericBase { override init() { super.init() } } class InnerNonGenericClass2 : OuterNonGenericClass { override init() { super.init() } } class InnerGenericClass<U> : OuterNonGenericClass { override init() { super.init() } } } class OuterGenericClass<T> { enum InnerNonGeneric { case Baz case Zab } class InnerNonGenericBase { init() {} } class InnerNonGenericClass1 : InnerNonGenericBase { override init() { super.init() } } class InnerNonGenericClass2 : OuterGenericClass { override init() { super.init() } } class InnerNonGenericClass3 : OuterGenericClass<Int> { override init() { super.init() } } class InnerNonGenericClass4 : OuterGenericClass<T> { override init() { super.init() } } class InnerGenericClass<U> : OuterGenericClass<U> { override init() { super.init() } } class Middle { class Inner1<T> {} class Inner2<T> : Middle where T: Inner1<Int> {} } } // <rdar://problem/12895793> struct AnyStream<T : Sequence> { struct StreamRange<S : IteratorProtocol> { var index : Int var elements : S // Conform to the IteratorProtocol protocol. typealias Element = (Int, S.Element) mutating func next() -> Element? { let result = (index, elements.next()) if result.1 == nil { return .none } index += 1 return (result.0, result.1!) } } var input : T // Conform to the enumerable protocol. typealias Elements = StreamRange<T.Iterator> func getElements() -> Elements { return Elements(index: 0, elements: input.makeIterator()) } } func enumerate<T>(_ arg: T) -> AnyStream<T> { return AnyStream<T>(input: arg) } // Check unqualified lookup of inherited types. class Foo<T> { typealias Nested = T } class Bar : Foo<Int> { func f(_ x: Int) -> Nested { return x } struct Inner { func g(_ x: Int) -> Nested { return x } func withLocal() { struct Local { func h(_ x: Int) -> Nested { return x } } } } } extension Bar { func g(_ x: Int) -> Nested { return x } // <rdar://problem/14376418> struct Inner2 { func f(_ x: Int) -> Nested { return x } } } class X6<T> { let d: D<T> init(_ value: T) { d = D(value) } class D<T2> { init(_ value: T2) {} } } // --------------------------------------------- // Unbound name references within a generic type // --------------------------------------------- struct GS<T> { func f() -> GS { let gs = GS() return gs } struct Nested { func ff() -> GS { let gs = GS() return gs } } struct NestedGeneric<U> { // expected-note{{generic type 'NestedGeneric' declared here}} func fff() -> (GS, NestedGeneric) { let gs = GS() let ns = NestedGeneric() return (gs, ns) } } // FIXME: We're losing some sugar here by performing the substitution. func ng() -> NestedGeneric { } // expected-error{{reference to generic type 'GS<T>.NestedGeneric' requires arguments in <...>}} } extension GS { func g() -> GS { let gs = GS() return gs } func h() { _ = GS() as GS<Int> // expected-error{{'GS<T>' is not convertible to 'GS<Int>'; did you mean to use 'as!' to force downcast?}} } } struct HasNested<T> { init<U>(_ t: T, _ u: U) {} func f<U>(_ t: T, u: U) -> (T, U) {} struct InnerGeneric<U> { init() {} func g<V>(_ t: T, u: U, v: V) -> (T, U, V) {} } struct Inner { init (_ x: T) {} func identity(_ x: T) -> T { return x } } } func useNested(_ ii: Int, hni: HasNested<Int>, xisi : HasNested<Int>.InnerGeneric<String>, xfs: HasNested<Float>.InnerGeneric<String>) { var i = ii, xis = xisi typealias InnerI = HasNested<Int>.Inner var innerI = InnerI(5) typealias InnerF = HasNested<Float>.Inner var innerF : InnerF = innerI // expected-error{{cannot convert value of type 'InnerI' (aka 'HasNested<Int>.Inner') to specified type 'InnerF' (aka 'HasNested<Float>.Inner')}} _ = innerI.identity(i) i = innerI.identity(i) // Generic function in a generic class typealias HNI = HasNested<Int> var id = hni.f(1, u: 3.14159) id = (2, 3.14159) hni.f(1.5, 3.14159) // expected-error{{missing argument label 'u:' in call}} hni.f(1.5, u: 3.14159) // expected-error{{cannot convert value of type 'Double' to expected argument type 'Int'}} // Generic constructor of a generic struct HNI(1, 2.71828) // expected-warning{{unused}} HNI(1.5, 2.71828) // expected-error{{'Double' is not convertible to 'Int'}} // Generic function in a nested generic struct var ids = xis.g(1, u: "Hello", v: 3.14159) ids = (2, "world", 2.71828) xis = xfs // expected-error{{cannot assign value of type 'HasNested<Float>.InnerGeneric<String>' to type 'HasNested<Int>.InnerGeneric<String>'}} } // Extensions of nested generic types extension OuterNonGeneric.MidGeneric { func takesB(b: B) {} } extension OuterGeneric.MidNonGeneric { func takesD(d: D) {} } extension OuterGeneric.MidGeneric { func takesD(d: D) {} func takesB(f: F) {} } protocol HasAssocType { associatedtype FirstAssocType associatedtype SecondAssocType func takesAssocType(first: FirstAssocType, second: SecondAssocType) } extension OuterGeneric.MidGeneric : HasAssocType { func takesAssocType(first: D, second: F) {} } typealias OuterGenericMidNonGeneric<T> = OuterGeneric<T>.MidNonGeneric extension OuterGenericMidNonGeneric { } class BaseClass { struct T {} func m1() -> T {} func m2() -> BaseClass.T {} func m3() -> DerivedClass.T {} } func f1() -> DerivedClass.T { return BaseClass.T() } func f2() -> BaseClass.T { return DerivedClass.T() } func f3() -> DerivedClass.T { return DerivedClass.T() } class DerivedClass : BaseClass { override func m1() -> DerivedClass.T { return f2() } override func m2() -> BaseClass.T { return f3() } override func m3() -> T { return f2() } } // https://bugs.swift.org/browse/SR-3847: Resolve members in inner types. // This first extension isn't necessary; we could have put 'originalValue' in // the original declaration. extension OuterNonGenericClass.InnerNonGenericBase { static let originalValue = 0 } // Each of these two cases used to crash. extension OuterNonGenericClass.InnerNonGenericBase { static let propUsingMember = originalValue } extension OuterNonGenericClass.InnerNonGenericClass1 { static let anotherPropUsingMember = originalValue } // rdar://problem/30353095: Extensions of nested types with generic // requirements placed on type parameters struct OuterWithConstraint<T : HasAssocType> { struct InnerWithConstraint<U : HasAssocType> { } } extension OuterWithConstraint.InnerWithConstraint { func foo<V>(v: V) where T.FirstAssocType == U.SecondAssocType {} } // Name lookup within a 'where' clause should find generic parameters // of the outer type. extension OuterGeneric.MidGeneric where D == Int, F == String { func doStuff() -> (D, F) { return (100, "hello") } } // https://bugs.swift.org/browse/SR-4672 protocol ExpressibleByCatLiteral {} protocol ExpressibleByDogLiteral {} struct Kitten : ExpressibleByCatLiteral {} struct Puppy : ExpressibleByDogLiteral {} struct Claws<A: ExpressibleByCatLiteral> { struct Fangs<B: ExpressibleByDogLiteral> { } // expected-note {{where 'B' = 'NotADog'}} } struct NotADog {} func pets<T>(fur: T) -> Claws<Kitten>.Fangs<T> { return Claws<Kitten>.Fangs<T>() } func something<T>() -> T { // expected-note {{in call to function 'something()'}} while true {} } func test() { let _: Claws<Kitten>.Fangs<Puppy> = pets(fur: Puppy()) // <https://bugs.swift.org/browse/SR-5600> let _: Claws.Fangs<Puppy> = pets(fur: Puppy()) let _: Claws.Fangs<Puppy> = Claws<Kitten>.Fangs() let _: Claws.Fangs<Puppy> = Claws.Fangs() // expected-error@-1 {{cannot convert value of type 'Claws<_>.Fangs<_>' to specified type 'Claws.Fangs<Puppy>'}} let _: Claws.Fangs<NotADog> = something() // expected-error@-1 {{generic parameter 'T' could not be inferred}} // FIXME: bad diagnostic _ = Claws.Fangs<NotADog>() // TODO(diagnostics): There should be two errors here - "cannot infer A" and "NotADog conformance to ExpressibleByDogLiteral" // expected-error@-1 {{referencing initializer 'init()' on 'Claws.Fangs' requires that 'NotADog' conform to 'ExpressibleByDogLiteral'}} } // https://bugs.swift.org/browse/SR-4379 extension OuterGeneric.MidNonGeneric { func doStuff() -> OuterGeneric { return OuterGeneric() } func doMoreStuff() -> OuterGeneric.MidNonGeneric { return OuterGeneric.MidNonGeneric() } func doMoreStuffWrong() -> Self { } }
apache-2.0
5612f5f49a9cdbd63a653b23cb551536
21.845606
176
0.635787
3.536029
false
false
false
false
nathawes/swift
test/diagnostics/Localization/fr_localization.swift
3
851
// RUN: %empty-directory(%t) // RUN: swift-serialize-diagnostics --input-file-path=%S/Inputs/fr.yaml --output-directory=%t/ // RUN: swift-serialize-diagnostics --input-file-path=%S/Inputs/en.yaml --output-directory=%t/ 2>&1 | %FileCheck %s // RUN: %target-typecheck-verify-swift -localization-path %t -locale fr // CHECK: These diagnostic IDs are no longer availiable: 'not_available_in_def, not_available_in_def_2, not_available_in_def_3, not_available_in_def_4, not_available_in_def_5' _ = "HI! // expected-error@-1{{chaîne non terminée littérale}} var self1 = self1 // expected-error {{variable utilisée dans sa propre valeur initiale}} struct Broken { var b : Bool = True // expected-error{{impossible de trouver 'True' portée}} } var v1 : Int[1 // expected-error {{expected ']' in array type}} expected-note {{to match this opening '['}}
apache-2.0
20eec9f726b1819f3dc4d9d17045081a
64.076923
175
0.713948
3.087591
false
false
false
false
Acidburn0zzz/firefox-ios
Shared/Extensions/UIImageExtensions.swift
7
2160
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import UIKit import SDWebImage private let imageLock = NSLock() extension CGRect { public init(width: CGFloat, height: CGFloat) { self.init(x: 0, y: 0, width: width, height: height) } public init(size: CGSize) { self.init(origin: .zero, size: size) } } extension Data { public var isGIF: Bool { return [0x47, 0x49, 0x46].elementsEqual(prefix(3)) } } extension UIImage { /// Despite docs that say otherwise, UIImage(data: NSData) isn't thread-safe (see bug 1223132). /// As a workaround, synchronize access to this initializer. /// This fix requires that you *always* use this over UIImage(data: NSData)! public static func imageFromDataThreadSafe(_ data: Data) -> UIImage? { imageLock.lock() let image = UIImage(data: data) imageLock.unlock() return image } public static func createWithColor(_ size: CGSize, color: UIColor) -> UIImage { UIGraphicsImageRenderer(size: size).image { (ctx) in color.setFill() ctx.fill(CGRect(size: size)) } } public func createScaled(_ size: CGSize) -> UIImage { UIGraphicsImageRenderer(size: size).image { (ctx) in draw(in: CGRect(size: size)) } } public static func templateImageNamed(_ name: String) -> UIImage? { return UIImage(named: name)?.withRenderingMode(.alwaysTemplate) } // Uses compositor blending to apply color to an image. public func tinted(withColor: UIColor) -> UIImage { let img2 = UIImage.createWithColor(size, color: withColor) let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height) let renderer = UIGraphicsImageRenderer(size: size) let result = renderer.image { ctx in img2.draw(in: rect, blendMode: .normal, alpha: 1) draw(in: rect, blendMode: .destinationIn, alpha: 1) } return result } }
mpl-2.0
bc0ffef3e27955065275d90972d0dcd8
32.230769
99
0.634259
4.044944
false
false
false
false
Sroik/FunLayout
src/FunLayout/FunLayoutModule/FunLayoutConstraintsActivation.swift
1
2907
// // FunnyLayout.swift // FunLayout // // Created by Sroik on 4/27/16. // Copyright © 2016 Sroik. All rights reserved. // import UIKit internal func fun_activateConstraints(var leftLayoutAttribute leftLayoutAttribute: FunLayoutAttribute, right: FunLayoutable, relation: NSLayoutRelation) -> [NSLayoutConstraint] { leftLayoutAttribute.relation = relation leftLayoutAttribute.owner?.fun_removeFamiliarConstraints(forFunLayoutAttribute: leftLayoutAttribute) let rightLayoutAttribute = fun_suitableRightLayoutAttribute(leftLayoutAttribute, right: right) assert(rightLayoutAttribute != nil, "wrong right expression type, check it pls. It must be one of FunLayoutAttribute, UIView, CGFloat") let constraints = fun_layoutConstraints(leftLayoutAttribute: leftLayoutAttribute, rightLayoutAttribute: rightLayoutAttribute!, relation: relation) for constraint in constraints { constraint.active = true leftLayoutAttribute.owner?.fun_addFamiliarConstraint(constraint) } return constraints } private func fun_layoutConstraints(leftLayoutAttribute leftLayoutAttribute: FunLayoutAttribute, rightLayoutAttribute: FunLayoutAttribute, relation: NSLayoutRelation) -> [NSLayoutConstraint] { assert(leftLayoutAttribute.owner != nil, "left funLayoutAttribute owner is nil assertion") var constraints = [NSLayoutConstraint]() for i in 0 ..< leftLayoutAttribute.layoutAttributes.count { let firstAttribute = leftLayoutAttribute.layoutAttributes[i] let secondAttributeIndex = (rightLayoutAttribute.layoutAttributes.count > i) ? i : 0 let secondAttribute = rightLayoutAttribute.layoutAttributes[secondAttributeIndex] let constraint = NSLayoutConstraint(item: leftLayoutAttribute.owner!, attribute: firstAttribute, relatedBy: relation, toItem: rightLayoutAttribute.owner, attribute: secondAttribute, multiplier: rightLayoutAttribute.multiplier, constant: rightLayoutAttribute.constant) constraint.priority = leftLayoutAttribute.priority constraints.append(constraint) } return constraints } private func fun_suitableRightLayoutAttribute(leftLayoutAttribute: FunLayoutAttribute, right: FunLayoutable) -> FunLayoutAttribute? { var layoutAttribute = FunLayoutAttribute(attributes: [.NotAnAttribute], owner: nil) switch right { case let funLayoutAttribute as FunLayoutAttribute: layoutAttribute = funLayoutAttribute break case let view as UIView: layoutAttribute.owner = view layoutAttribute.layoutAttributes = leftLayoutAttribute.layoutAttributes break default: layoutAttribute.constant = CGFloat.fun_CGFloatWithFunLayoutable(right) } return layoutAttribute }
mit
90acb145db11c9758b3f6f670e3cef5f
36.25641
191
0.731246
5.535238
false
false
false
false
randallli/material-components-ios
components/NavigationBar/tests/unit/NavigationBarColorThemerTests.swift
1
2354
/* Copyright 2018-present the Material Components for iOS authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import XCTest import MaterialComponents.MaterialNavigationBar import MaterialComponents.MaterialNavigationBar_ColorThemer class NavigationBarColorThemerTests: XCTestCase { func testColorThemerChangesTheCorrectParameters() { // Given let colorScheme = MDCSemanticColorScheme() let navigationBar = MDCNavigationBar() colorScheme.primaryColor = .red colorScheme.onPrimaryColor = .blue navigationBar.backgroundColor = .white navigationBar.titleTextColor = .white navigationBar.tintColor = .white // When MDCNavigationBarColorThemer.applySemanticColorScheme(colorScheme, to: navigationBar) // Then XCTAssertEqual(navigationBar.backgroundColor, colorScheme.primaryColor) XCTAssertEqual(navigationBar.titleTextColor, colorScheme.onPrimaryColor) XCTAssertEqual(navigationBar.tintColor, colorScheme.onPrimaryColor) } func testSurfaceVariantColorThemerChangesTheCorrectParameters() { // Given let colorScheme = MDCSemanticColorScheme() let navigationBar = MDCNavigationBar() colorScheme.surfaceColor = .red colorScheme.onSurfaceColor = .blue navigationBar.backgroundColor = .white navigationBar.titleTextColor = .white navigationBar.tintColor = .white // When MDCNavigationBarColorThemer.applySurfaceVariant(withColorScheme: colorScheme, to: navigationBar) // Then XCTAssertEqual(navigationBar.titleTextColor, colorScheme.onSurfaceColor.withAlphaComponent(0.87)) XCTAssertEqual(navigationBar.buttonsTitleColor(for: .normal), colorScheme.onSurfaceColor.withAlphaComponent(0.87)) XCTAssertEqual(navigationBar.tintColor, colorScheme.onSurfaceColor.withAlphaComponent(0.54)) } }
apache-2.0
ce9de187b25f5da965e43e4ce378e51d
36.967742
100
0.7774
5.423963
false
true
false
false
blockchain/My-Wallet-V3-iOS
Modules/FeatureApp/Sources/FeatureAppUI/Handlers/BlurVisualEffectHandler.swift
1
1650
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import UIKit /// Types adopting to `BlurVisualEffectHandlerAPI` should provide a way to apply a blur effect to the given view public protocol BlurVisualEffectHandlerAPI { /// Applies a blur effect /// - Parameter view: A `UIView` for the effect to be applied to func applyEffect(on view: UIView) /// Removes a blur effect /// - Parameter view: A `UIView` for the effect to be removed from func removeEffect(from view: UIView) } final class BlurVisualEffectHandler: BlurVisualEffectHandlerAPI { private lazy var visualEffectView: UIVisualEffectView = { let view = UIVisualEffectView(effect: UIBlurEffect(style: .light)) view.alpha = 0 return view }() func applyEffect(on view: UIView) { applyAnimated(on: view, shouldRemove: false) } func removeEffect(from view: UIView) { applyAnimated(on: view, shouldRemove: true) } private func applyAnimated(on view: UIView, shouldRemove: Bool) { let alpha: CGFloat = shouldRemove ? 0 : 1 visualEffectView.frame = view.bounds view.addSubview(visualEffectView) UIView.animate( withDuration: 0.12, delay: 0, options: [.beginFromCurrentState], animations: { self.visualEffectView.alpha = alpha }, completion: { finished in if finished { if shouldRemove { self.visualEffectView.removeFromSuperview() } } } ) } }
lgpl-3.0
2735787dc836e5adfcb5f65add1a7376
30.113208
112
0.611886
5.012158
false
false
false
false
qinting513/Learning-QT
2016 Plan/5月/数据持久化/CoreDataSw/CoreDataSw/ViewController.swift
1
1842
// // ViewController.swift // CoreDataSw // // Created by Qinting on 16/5/9. // Copyright © 2016年 Qinting. All rights reserved. // import UIKit import CoreData class ViewController: UIViewController { var context : NSManagedObjectContext? override func viewDidLoad() { super.viewDidLoad() let context = NSManagedObjectContext.init() let model = NSManagedObjectModel.mergedModelFromBundles(nil) let docPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last let sqlPath = docPath?.stringByAppendingString("/company.sqlite") let store = NSPersistentStoreCoordinator.init(managedObjectModel: model!) let url = NSURL.fileURLWithPath(sqlPath!) do { try store.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil) } catch _ { } context.persistentStoreCoordinator = store self.context = context } @IBAction func insertData(sender: AnyObject) { let emp = NSEntityDescription.insertNewObjectForEntityForName("Employee", inManagedObjectContext: context!) as! Employee emp.name = "zhangsan" emp.age = 126 do{ try context!.save() print("成功插入") } catch let error as NSError { print(error) } } @IBAction func queryData(sender: AnyObject) { let fetch = NSFetchRequest.init(entityName: "Employee") do { let emps : [AnyObject] = try context!.executeFetchRequest(fetch) for emp in emps as! [Employee] { print("name:\(emp.name!) age: \(emp.age!)") } }catch let error as NSError { print("error:\( error)") } } }
apache-2.0
ead38bc28633db0780e9d82f3dfe4e6b
27.169231
128
0.614418
4.922043
false
false
false
false
gerbot150/SwiftyFire
swift/SwiftyFire/main.swift
1
2918
// // main.swift // SwiftyJSONModelMaker // // Created by Gregory Bateman on 2017-03-03. // Copyright © 2017 Gregory Bateman. All rights reserved. // import Foundation func main() { var name: String? let tokenizer = Tokenizer() let parser = Parser() let swiftifier = Swiftifier() do { let input: (name: String?, text: String) try input = getInput() name = input.name let text = input.text try tokenizer.tokenize(text) try parser.parse(tokens: tokenizer.tokens) try swiftifier.swiftifyJSON(parser.topLevelNode, with: name) } catch { print("ERROR: \(error), program will exit\n") return } printHeader(with: name) printImports() print(swiftifier.swiftifiedJSON) } func getInput() throws -> (String?, String) { var name: String? = nil var text = "" let arguments = CommandLine.arguments if arguments.count < 2 { // Input from standard input while let line = readLine(strippingNewline: true) { text += line } let ignorableCharacters = CharacterSet.controlCharacters.union(CharacterSet.whitespacesAndNewlines) text = text.trimmingCharacters(in: ignorableCharacters) } else { // Input from file do { try text = String(contentsOfFile: arguments[1], encoding: .utf8) // These commands are apparently not usable in the current version of // Swift on linux - or I couldn't find the library to link them properly // but the characters are handled accordingly in the tokenizer // text = text.components(separatedBy: "\r").joined(separator: "") // text = text.components(separatedBy: "\n").joined(separator: "") // text = text.components(separatedBy: "\t").joined(separator: " ") name = arguments[1] while let range = name?.range(of: "/") { name = name?.substring(from: range.upperBound) } if let range = name?.range(of: ".") { name = name?.substring(to: range.lowerBound) } name = name?.capitalCased } catch { throw error } } return (name, text) } func printHeader(with name: String?) { print("//") print("// \(name ?? "Object").swift") print("//") print("// Created by SwiftyFire on \(getDate())") print("// SwiftyFire is a development tool made by Greg Bateman") print("// It was created to reduce the tedious amount of time required to create") print("// model classes when using SwiftyJSON to parse JSON in swift") print("//") print() } func printImports() { print("import SwiftyJSON") print() } func getDate() -> String { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd" return dateFormatter.string(from: Date()) } main()
mit
13f65019bed869b6d9bbf8176df4e206
30.365591
107
0.605074
4.373313
false
false
false
false
Conche/Conche
ConcheSpecs/VersionSpec.swift
2
3846
import Spectre import Conche public func ~> <E: ExpectationType where E.ValueType == Version>(lhs: E, rhs: E.ValueType) throws { if let value = try lhs.expression() { guard value ~> rhs else { throw lhs.failure("\(value) is not ~> \(rhs)") } } else { throw lhs.failure("nil is not ~> \(rhs)") } } describe("Version") { let version = Version(major: 1, minor: 2, patch: 3, prerelease: "beta.1") $0.it("has a major") { try expect(version.major) == 1 } $0.it("has a minor") { try expect(version.minor) == 2 } $0.it("has a patch") { try expect(version.patch) == 3 } $0.it("has a prerelease") { try expect(version.prerelease) == "beta.1" } $0.it("is hashable") { let items = [version: 66] try expect(items[version]) == 66 } $0.it("can be converted to a string") { try expect(version.description) == "1.2.3-beta.1" } $0.describe("when parsing a string") { $0.it("parses the major, minor and patch version") { let version = try Version("1.2.3") try expect(version.major) == 1 try expect(version.minor) == 2 try expect(version.patch) == 3 try expect(version.prerelease).to.beNil() } $0.it("parses the major, minor, patch with a pre-release component") { let version = try Version("1.2.3-beta.1") try expect(version.major) == 1 try expect(version.minor) == 2 try expect(version.patch) == 3 try expect(version.prerelease) == "beta.1" } } $0.context("when comparing two versions") { func v(major:Int, _ minor:Int? = nil, _ patch:Int? = nil) -> Version { return Version(major: major, minor: minor, patch: patch) } $0.it("is equal to version with the same major, minor, patch and pre-release") { try expect(version) == Version(major: 1, minor: 2, patch: 3, prerelease: "beta.1") } $0.it("is not equal to version with a different major, minor, patch or pre-release") { try expect(version) != Version(major: 0, minor: 2, patch: 3, prerelease: "beta.1") try expect(version) != Version(major: 1, minor: 0, patch: 3, prerelease: "beta.1") try expect(version) != Version(major: 1, minor: 2, patch: 0, prerelease: "beta.1") try expect(version) != Version(major: 1, minor: 2, patch: 3, prerelease: "beta.2") } $0.context("with the more than operator") { $0.it("returns whether a version is more than another version") { let requirement = v(3, 1, 2) try expect(v(3, 1, 3)) > requirement try expect(v(3, 2, 2)) > requirement try expect(v(4, 1, 3)) > requirement try expect(v(3, 1, 2) > requirement).to.beFalse() try expect(v(2, 1, 2) > requirement).to.beFalse() } } $0.context("with the optimistic operator") { $0.it("returns whether a version satisfies using a major version") { let requirement = v(3) try expect(v(3, 3, 0)) ~> requirement try expect(v(4, 0, 0)) ~> requirement } $0.it("returns whether a version satisfies using a minor version") { let requirement = v(3, 2) try expect(v(3, 2)) ~> requirement try expect(v(3, 2, 0)) ~> requirement try expect(v(3, 2, 1)) ~> requirement try expect(v(3, 3)) ~> requirement try expect(v(3, 3, 0)) ~> requirement try expect(v(4, 0, 0) ~> requirement).to.beFalse() } $0.it("returns whether a version satisfies using a patch version") { let requirement = v(3, 2, 0) try expect(v(3, 2)) ~> requirement try expect(v(3, 2, 0)) ~> requirement try expect(v(3, 2, 1)) ~> requirement try expect(v(3, 3) ~> requirement).to.beFalse() try expect(v(3, 3, 0) ~> requirement).to.beFalse() try expect(v(4, 0, 0) ~> requirement).to.beFalse() } } } }
bsd-2-clause
9863023a2c5fd8ba42bb4ef84bc0a6ad
31.59322
99
0.585023
3.335646
false
false
false
false
iachievedit/moreswift
translator/main.swift
1
1337
// Copyright 2015 iAchieved.it 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. import translator import Foundation import Glibc guard CommandLine.arguments.count == 6 && CommandLine.arguments[2] == "from" && CommandLine.arguments[4] == "to" else { print("Usage: translate STRING from LANG to LANG") exit(-1) } let string = CommandLine.arguments[1] let fromLang = CommandLine.arguments[3] let toLang = CommandLine.arguments[5] let translator = Translator() translator.translate(text:string, from:fromLang, to:toLang) { (translation:String?, error:NSError?) -> Void in guard error == nil && translation != nil else { print("Error: No translation available") exit(-1) } if let translatedText = translation { print("Translation: " + translatedText) exit(0) } }
apache-2.0
debdab828448585614cac11a3bce353c
30.093023
75
0.706806
3.920821
false
false
false
false
epayco/sdk-ios
Epayco/Encription/CryptoJS.swift
1
24121
// // CryptoJS.swift // // Created by Emartin on 2015-08-25. // Copyright (c) 2015 Emartin. All rights reserved. // import Foundation import JavaScriptCore private var cryptoJScontext = JSContext() internal class CryptoJS{ class AES: CryptoJS{ fileprivate var encryptFunction: JSValue! fileprivate var decryptFunction: JSValue! override init(){ super.init() // Retrieve the content of aes.js let cryptoJSpath = Bundle(for: CryptoJS.self).path(forResource: "aes", ofType: "js") if(( cryptoJSpath ) != nil){ do { let cryptoJS = try String(contentsOfFile: cryptoJSpath!, encoding: String.Encoding.utf8) print("Loaded aes.js") // Evaluate aes.js _ = cryptoJScontext?.evaluateScript(cryptoJS) // Reference functions encryptFunction = cryptoJScontext?.objectForKeyedSubscript("encrypt") decryptFunction = cryptoJScontext?.objectForKeyedSubscript("decrypt") } catch { print("Unable to load aes.js") } }else{ print("Unable to find aes.js") } } func encrypt(_ secretMessage: String,secretKey: String,options: Any?=nil)->String { if let unwrappedOptions: Any = options { return "\(encryptFunction.call(withArguments: [secretMessage, secretKey, unwrappedOptions])!)" }else{ return "\(encryptFunction.call(withArguments: [secretMessage, secretKey])!)" } } func decrypt(_ encryptedMessage: String,secretKey: String,options: Any?=nil)->String { if let unwrappedOptions: Any = options { return "\(decryptFunction.call(withArguments: [encryptedMessage, secretKey, unwrappedOptions])!)" }else{ return "\(decryptFunction.call(withArguments: [encryptedMessage, secretKey])!)" } } } class TripleDES: CryptoJS{ fileprivate var encryptFunction: JSValue! fileprivate var decryptFunction: JSValue! override init(){ super.init() // Retrieve the content of tripledes.js let cryptoJSpath = Bundle.main.path(forResource: "tripledes", ofType: "js", inDirectory: "components") if(( cryptoJSpath ) != nil){ do { let cryptoJS = try String(contentsOfFile: cryptoJSpath!, encoding: String.Encoding.utf8) print("Loaded tripledes.js") // Evaluate tripledes.js _ = cryptoJScontext?.evaluateScript(cryptoJS) // Reference functions encryptFunction = cryptoJScontext?.objectForKeyedSubscript("encryptTripleDES") decryptFunction = cryptoJScontext?.objectForKeyedSubscript("decryptTripleDES") } catch { print("Unable to load tripledes.js") } }else{ print("Unable to find tripledes.js") } } func encrypt(_ secretMessage: String,secretKey: String)->String { return "\(encryptFunction.call(withArguments: [secretMessage, secretKey])!)" } func decrypt(_ encryptedMessage: String,secretKey: String)->String { return "\(decryptFunction.call(withArguments: [encryptedMessage, secretKey])!)" } } class DES: CryptoJS{ fileprivate var encryptFunction: JSValue! fileprivate var decryptFunction: JSValue! override init(){ super.init() // Retrieve the content of tripledes.js let cryptoJSpath = Bundle.main.path(forResource: "tripledes", ofType: "js", inDirectory: "components") if(( cryptoJSpath ) != nil){ do { let cryptoJS = try String(contentsOfFile: cryptoJSpath!, encoding: String.Encoding.utf8) print("Loaded tripledes.js (DES)") // Evaluate tripledes.js _ = cryptoJScontext?.evaluateScript(cryptoJS) // Reference functions encryptFunction = cryptoJScontext?.objectForKeyedSubscript("encryptDES") decryptFunction = cryptoJScontext?.objectForKeyedSubscript("decryptDES") } catch { print("Unable to load tripledes.js (DES)") } }else{ print("Unable to find tripledes.js (DES)") } } func encrypt(_ secretMessage: String,secretKey: String)->String { return "\(encryptFunction.call(withArguments: [secretMessage, secretKey])!)" } func decrypt(_ encryptedMessage: String,secretKey: String)->String { return "\(decryptFunction.call(withArguments: [encryptedMessage, secretKey])!)" } } class MD5: CryptoJS{ fileprivate var MD5: JSValue! override init(){ super.init() // Retrieve the content of md5.js let cryptoJSpath = Bundle.main.path(forResource: "md5", ofType: "js", inDirectory: "components") if(( cryptoJSpath ) != nil){ do { let cryptoJS = try String(contentsOfFile: cryptoJSpath!, encoding:String.Encoding.utf8) print("Loaded md5.js") // Evaluate md5.js _ = cryptoJScontext?.evaluateScript(cryptoJS) // Reference functions self.MD5 = cryptoJScontext?.objectForKeyedSubscript("MD5") } catch { print("Unable to load md5.js") } }else{ print("Unable to find md5.js") } } func hash(_ string: String)->String { return "\(self.MD5.call(withArguments: [string])!)" } } class SHA1: CryptoJS{ fileprivate var SHA1: JSValue! override init(){ super.init() // Retrieve the content of sha1.js let cryptoJSpath = Bundle.main.path(forResource: "sha1", ofType: "js", inDirectory: "components") if(( cryptoJSpath ) != nil){ do { let cryptoJS = try String(contentsOfFile: cryptoJSpath!, encoding:String.Encoding.utf8) print("Loaded sha1.js") // Evaluate sha1.js _ = cryptoJScontext?.evaluateScript(cryptoJS) // Reference functions self.SHA1 = cryptoJScontext?.objectForKeyedSubscript("SHA1") } catch { print("Unable to load sha1.js") } }else{ print("Unable to find sha1.js") } } func hash(_ string: String)->String { return "\(self.SHA1.call(withArguments: [string])!)" } } class SHA224: CryptoJS{ fileprivate var SHA224: JSValue! override init(){ super.init() // Retrieve the content of sha224.js let cryptoJSpath = Bundle.main.path(forResource: "sha224", ofType: "js", inDirectory: "components") if(( cryptoJSpath ) != nil){ do { let cryptoJS = try String(contentsOfFile: cryptoJSpath!, encoding:String.Encoding.utf8) print("Loaded sha224.js") // Evaluate sha224.js _ = cryptoJScontext?.evaluateScript(cryptoJS) // Reference functions self.SHA224 = cryptoJScontext?.objectForKeyedSubscript("SHA224") } catch { print("Unable to load sha224.js") } }else{ print("Unable to find sha224.js") } } func hash(_ string: String)->String { return "\(self.SHA224.call(withArguments: [string])!)" } } class SHA256: CryptoJS{ fileprivate var SHA256: JSValue! override init(){ super.init() // Retrieve the content of sha256.js let cryptoJSpath = Bundle.main.path(forResource: "sha256", ofType: "js", inDirectory: "components") if(( cryptoJSpath ) != nil){ do { let cryptoJS = try String(contentsOfFile: cryptoJSpath!, encoding:String.Encoding.utf8) print("Loaded sha256.js") // Evaluate sha256.js _ = cryptoJScontext?.evaluateScript(cryptoJS) // Reference functions self.SHA256 = cryptoJScontext?.objectForKeyedSubscript("SHA256") } catch { print("Unable to load sha256.js") } }else{ print("Unable to find sha256.js") } } func hash(_ string: String)->String { return "\(self.SHA256.call(withArguments: [string])!)" } } class SHA384: CryptoJS{ fileprivate var SHA384: JSValue! override init(){ super.init() // Retrieve the content of sha384.js let cryptoJSpath = Bundle.main.path(forResource: "sha384", ofType: "js", inDirectory: "components") if(( cryptoJSpath ) != nil){ do { let cryptoJS = try String(contentsOfFile: cryptoJSpath!, encoding:String.Encoding.utf8) print("Loaded sha384.js") // Evaluate sha384.js _ = cryptoJScontext?.evaluateScript(cryptoJS) // Reference functions self.SHA384 = cryptoJScontext?.objectForKeyedSubscript("SHA384") } catch { print("Unable to load sha384.js") } }else{ print("Unable to find sha384.js") } } func hash(_ string: String)->String { return "\(self.SHA384.call(withArguments: [string])!)" } } class SHA512: CryptoJS{ fileprivate var SHA512: JSValue! override init(){ super.init() // Retrieve the content of sha512.js let cryptoJSpath = Bundle.main.path(forResource: "sha512", ofType: "js", inDirectory: "components") if(( cryptoJSpath ) != nil){ do { let cryptoJS = try String(contentsOfFile: cryptoJSpath!, encoding:String.Encoding.utf8) print("Loaded sha512.js") // Evaluate sha512.js _ = cryptoJScontext?.evaluateScript(cryptoJS) // Reference functions self.SHA512 = cryptoJScontext?.objectForKeyedSubscript("SHA512") } catch { print("Unable to load sha512.js") } }else{ print("Unable to find sha512.js") } } func hash(_ string: String)->String { return "\(self.SHA512.call(withArguments: [string])!)" } } class SHA3: CryptoJS{ fileprivate var SHA3: JSValue! override init(){ super.init() // Retrieve the content of sha3.js let cryptoJSpath = Bundle.main.path(forResource: "sha3", ofType: "js", inDirectory: "components") if(( cryptoJSpath ) != nil){ do { let cryptoJS = try String(contentsOfFile: cryptoJSpath!, encoding:String.Encoding.utf8) print("Loaded sha3.js") // Evaluate sha3.js _ = cryptoJScontext?.evaluateScript(cryptoJS) // Reference functions self.SHA3 = cryptoJScontext?.objectForKeyedSubscript("SHA3") } catch { print("Unable to load sha3.js") } } } func hash(_ string: String,outputLength: Int?=nil)->String { if let unwrappedOutputLength = outputLength { return "\(self.SHA3.call(withArguments: [string,unwrappedOutputLength])!)" } else { return "\(self.SHA3.call(withArguments: [string])!)" } } } class RIPEMD160: CryptoJS{ fileprivate var RIPEMD160: JSValue! override init(){ super.init() // Retrieve the content of ripemd160.js let cryptoJSpath = Bundle.main.path(forResource: "ripemd160", ofType: "js", inDirectory: "components") if(( cryptoJSpath ) != nil){ do { let cryptoJS = try String(contentsOfFile: cryptoJSpath!, encoding:String.Encoding.utf8) print("Loaded ripemd160.js") // Evaluate ripemd160.js _ = cryptoJScontext?.evaluateScript(cryptoJS) // Reference functions self.RIPEMD160 = cryptoJScontext?.objectForKeyedSubscript("RIPEMD160") } catch { print("Unable to load ripemd160.js") } } } func hash(_ string: String,outputLength: Int?=nil)->String { if let unwrappedOutputLength = outputLength { return "\(self.RIPEMD160.call(withArguments: [string,unwrappedOutputLength])!)" } else { return "\(self.RIPEMD160.call(withArguments: [string])!)" } } } class mode: CryptoJS{ var CFB:String = "CFB" var CTR:String = "CTR" var OFB:String = "OFB" var ECB:String = "ECB" class CFB: CryptoJS{ override init(){ super.init() // Retrieve the content of the script let cryptoJSpath = Bundle.main.path(forResource: "mode-\(CryptoJS.mode().CFB.lowercased())", ofType: "js", inDirectory: "components") if(( cryptoJSpath ) != nil){ do { let cryptoJS = try String(contentsOfFile: cryptoJSpath!, encoding:String.Encoding.utf8) print("Loaded mode-\(CryptoJS.mode().CFB).js") // Evaluate script _ = cryptoJScontext?.evaluateScript(cryptoJS) } catch { print("Unable to load mode-\(CryptoJS.mode().CFB).js") } } } } class CTR: CryptoJS{ override init(){ super.init() // Retrieve the content of the script let cryptoJSpath = Bundle.main.path(forResource: "mode-\(CryptoJS.mode().CTR.lowercased())", ofType: "js", inDirectory: "components") if(( cryptoJSpath ) != nil){ do { let cryptoJS = try String(contentsOfFile: cryptoJSpath!, encoding:String.Encoding.utf8) print("Loaded mode-\(CryptoJS.mode().CTR).js") // Evaluate script _ = cryptoJScontext?.evaluateScript(cryptoJS) } catch { print("Unable to load mode-\(CryptoJS.mode().CTR).js") } } } } class OFB: CryptoJS{ override init(){ super.init() // Retrieve the content of the script let cryptoJSpath = Bundle.main.path(forResource: "mode-\(CryptoJS.mode().OFB.lowercased())", ofType: "js", inDirectory: "components") if(( cryptoJSpath ) != nil){ do { let cryptoJS = try String(contentsOfFile: cryptoJSpath!, encoding:String.Encoding.utf8) print("Loaded mode-\(CryptoJS.mode().OFB).js") // Evaluate script _ = cryptoJScontext?.evaluateScript(cryptoJS) } catch { print("Unable to load mode-\(CryptoJS.mode().OFB).js") } } } } class ECB: CryptoJS{ override init(){ super.init() // Retrieve the content of the script let cryptoJSpath = Bundle.main.path(forResource: "mode-\(CryptoJS.mode().ECB.lowercased())", ofType: "js", inDirectory: "components") if(( cryptoJSpath ) != nil){ do { let cryptoJS = try String(contentsOfFile: cryptoJSpath!, encoding:String.Encoding.utf8) print("Loaded mode-\(CryptoJS.mode().ECB).js") // Evaluate script _ = cryptoJScontext?.evaluateScript(cryptoJS) } catch { print("Unable to load mode-\(CryptoJS.mode().ECB).js") } } } } } class pad: CryptoJS{ var AnsiX923:String = "AnsiX923" var Iso97971:String = "Iso97971" var Iso10126:String = "Iso10126" var ZeroPadding:String = "ZeroPadding" var NoPadding:String = "NoPadding" class AnsiX923: CryptoJS{ override init(){ super.init() // Retrieve the content of the script let cryptoJSpath = Bundle.main.path(forResource: "pad-\(CryptoJS.pad().AnsiX923.lowercased())", ofType: "js", inDirectory: "components") if(( cryptoJSpath ) != nil){ do { let cryptoJS = try String(contentsOfFile: cryptoJSpath!, encoding:String.Encoding.utf8) print("Loaded pad-\(CryptoJS.pad().AnsiX923).js") // Evaluate script _ = cryptoJScontext?.evaluateScript(cryptoJS) } catch { print("Unable to load pad-\(CryptoJS.pad().AnsiX923).js") } } } } class Iso97971: CryptoJS{ override init(){ super.init() // Load dependencies _ = CryptoJS.pad.ZeroPadding() // Retrieve the content of the script let cryptoJSpath = Bundle.main.path(forResource: "pad-\(CryptoJS.pad().Iso97971.lowercased())", ofType: "js", inDirectory: "components") if(( cryptoJSpath ) != nil){ do { let cryptoJS = try String(contentsOfFile: cryptoJSpath!, encoding:String.Encoding.utf8) print("Loaded pad-\(CryptoJS.pad().Iso97971).js") // Evaluate script _ = cryptoJScontext?.evaluateScript(cryptoJS) } catch { print("Unable to load pad-\(CryptoJS.pad().Iso97971).js") } } } } class Iso10126: CryptoJS{ override init(){ super.init() // Retrieve the content of the script let cryptoJSpath = Bundle.main.path(forResource: "pad-\(CryptoJS.pad().Iso10126.lowercased())", ofType: "js", inDirectory: "components") if(( cryptoJSpath ) != nil){ do { let cryptoJS = try String(contentsOfFile: cryptoJSpath!, encoding:String.Encoding.utf8) print("Loaded pad-\(CryptoJS.pad().Iso10126).js") // Evaluate script _ = cryptoJScontext?.evaluateScript(cryptoJS) } catch { print("Unable to load pad-\(CryptoJS.pad().Iso10126).js") } } } } class ZeroPadding: CryptoJS{ override init(){ super.init() // Retrieve the content of the script let cryptoJSpath = Bundle.main.path(forResource: "pad-\(CryptoJS.pad().ZeroPadding.lowercased())", ofType: "js", inDirectory: "components") if(( cryptoJSpath ) != nil){ do { let cryptoJS = try String(contentsOfFile: cryptoJSpath!, encoding:String.Encoding.utf8) print("Loaded pad-\(CryptoJS.pad().ZeroPadding).js") // Evaluate script _ = cryptoJScontext?.evaluateScript(cryptoJS) } catch { print("Unable to load pad-\(CryptoJS.pad().ZeroPadding).js") } } } } class NoPadding: CryptoJS{ override init(){ super.init() // Retrieve the content of the script let cryptoJSpath = Bundle.main.path(forResource: "pad-\(CryptoJS.pad().NoPadding.lowercased())", ofType: "js", inDirectory: "components") if(( cryptoJSpath ) != nil){ do { let cryptoJS = try String(contentsOfFile: cryptoJSpath!, encoding:String.Encoding.utf8) print("Loaded pad-\(CryptoJS.pad().NoPadding).js") // Evaluate script _ = cryptoJScontext?.evaluateScript(cryptoJS) } catch { print("Unable to load pad-\(CryptoJS.pad().NoPadding).js") } } } } } }
mit
67e356807cf786738d6db64bd77c4161
35.54697
155
0.456656
5.564245
false
false
false
false
CapstoneTeamA/Mobile-Test-Runner-for-Jama
Mobile Test Runner for Jama/Mobile Test Runner for Jama/ItemTypes.swift
1
2761
// // ItemTypes.swift // Mobile Test Runner for Jama // // Created by Meghan McBee on 9/4/17. // Copyright © 2017 Jaca. All rights reserved. // import Foundation class ItemTypes { var endpointString: String = "" var totalItemTypesReturned: Int = 0 var username: String = "" var password: String = "" let planKey: String = "TSTPL" let cycleKey: String = "TSTCY" let runKey: String = "TSTRN" var planId: Int = -1 var cycleId: Int = -1 var runId: Int = -1 // Build endpoint string and call API to get instance-specific item type ids func getItemIds(instance: String, username: String, password: String) { self.username = username self.password = password endpointString = RestHelper.getEndpointString(method: "Get", endpoint: "ItemTypes") endpointString = "https://" + instance + "." + endpointString RestHelper.hitEndpoint(atEndpointString: endpointString, withDelegate: self, username: username, password: password, timestamp: RestHelper.getCurrentTimestampString()) } // Check that all desired item types were found and saved func didNotFindAllTypes() -> Bool { return planId < 0 || cycleId < 0 || runId < 0 } // Only save item type ids for plan, cycle, and run func extractItemTypes(fromData: [[String : AnyObject]]) { for item in fromData { if item["typeKey"] as! String == planKey { planId = item["id"] as! Int } else if item["typeKey"] as! String == cycleKey { cycleId = item["id"] as! Int } else if item["typeKey"] as! String == runKey { runId = item["id"] as! Int } self.totalItemTypesReturned += 1 // Stop checking item types once plan, cycle, and run are found if !didNotFindAllTypes() { return } } } } extension ItemTypes: EndpointDelegate { func didLoadEndpoint(data: [[String : AnyObject]]?, totalItems: Int, timestamp: String) { guard let unwrappedData = data else { return } DispatchQueue.main.async { self.extractItemTypes(fromData: unwrappedData) //Keep calling API if desired types weren't found in first batch and there are more types to check if self.totalItemTypesReturned < totalItems && self.didNotFindAllTypes() { RestHelper.hitEndpoint(atEndpointString: self.endpointString + "&startAt=\(self.totalItemTypesReturned)", withDelegate: self, username: self.username, password: self.password, timestamp: RestHelper.getCurrentTimestampString()) } } } }
mit
7c9b22d8ab420be6c9dabee65085484d
35.315789
242
0.61087
4.367089
false
false
false
false
CatchChat/Yep
FayeClient/FayeMessage.swift
1
2067
// // FayeMessage.swift // Yep // // Created by NIX on 16/5/17. // Copyright © 2016年 Catch Inc. All rights reserved. // import Foundation public struct FayeMessage { let ID: String? let channel: String let clientID: String? public let successful: Bool let authSuccessful: Bool let version: String let minimunVersion: String? let supportedConnectionTypes: [String] let advice: [String: AnyObject] let error: String? let subscription: String? let timestamp: NSDate? let data: [String: AnyObject] let ext: [String: AnyObject] static func messageFromDictionary(info: [String: AnyObject]) -> FayeMessage? { let ID = info["id"] as? String guard let channel = info["channel"] as? String else { return nil } let clientID = info["clientId"] as? String let successful = (info["successful"] as? Bool) ?? false let authSuccessful = (info["authSuccessful"] as? Bool) ?? false let version = info["version"] as? String ?? "1.0" let minimumVersion = info["minimumVersion"] as? String let supportedConnectionTypes = (info["supportedConnectionTypes"] as? [String]) ?? [] let advice = (info["advice"] as? [String: AnyObject]) ?? [:] let error = info["error"] as? String let subscription = info["subscription"] as? String let timestamp: NSDate? if let timestampUnixTime = info["timestamp"] as? NSTimeInterval { timestamp = NSDate(timeIntervalSince1970: timestampUnixTime) } else { timestamp = nil } let data = (info["data"] as? [String: AnyObject]) ?? [:] let ext = (info["ext"] as? [String: AnyObject]) ?? [:] return FayeMessage(ID: ID, channel: channel, clientID: clientID, successful: successful, authSuccessful: authSuccessful, version: version, minimunVersion: minimumVersion, supportedConnectionTypes: supportedConnectionTypes, advice: advice, error: error, subscription: subscription, timestamp: timestamp, data: data, ext: ext) } }
mit
9f07f52b21c9921aa3e1b1cecb4f3bcf
37.943396
332
0.650194
4.212245
false
false
false
false
psharanda/LayoutOps
Sources/CALayer+LX.swift
1
2209
// // Created by Pavel Sharanda on 09.02.2018. // Copyright © 2018 LayoutOps. All rights reserved. // #if os(macOS) import Cocoa #else import UIKit #endif private var key: UInt8 = 0 private var viewPortInsetsKey: UInt8 = 0 extension CALayer: Layoutable { public var lx_frame: CGRect { get { #if os(macOS) return frame.flipped(in: superlayer?.bounds) #else return frame #endif } set { #if os(macOS) frame = newValue.flipped(in: superlayer?.bounds) #else frame = newValue #endif } } public var lx_parent: Layoutable? { return superlayer } public var lx_viewport: CGRect? { set { #if os(macOS) objc_setAssociatedObject(self, &viewPortInsetsKey, newValue.map { NSValue(rect: $0) }, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) #else objc_setAssociatedObject(self, &viewPortInsetsKey, newValue.map { NSValue(cgRect: $0) }, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) #endif } get { #if os(macOS) return (objc_getAssociatedObject(self, &viewPortInsetsKey) as? NSValue)?.rectValue #else return (objc_getAssociatedObject(self, &viewPortInsetsKey) as? NSValue)?.cgRectValue #endif } } } extension CALayer: LayoutingCompatible { } #if os(iOS) extension CALayer: NodeContainer { public func lx_add(child: NodeContainer) { if let child = child as? CALayer { addSublayer(child) } } public var lx_tag: String? { set { objc_setAssociatedObject(self, &key, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } get { return objc_getAssociatedObject(self, &key) as? String } } public func lx_child(with tag: String) -> NodeContainer? { for v in sublayers ?? [] { if v.lx_tag == Optional.some(tag) { return v } } return nil } } #endif
mit
3f02999c749143a9005b26ddbb479555
23.533333
140
0.533967
4.262548
false
false
false
false
cnoon/swift-compiler-crashes
crashes-duplicates/05422-swift-sourcemanager-getmessage.swift
11
2532
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing } class func i(" typealias e : a { class c, class protocol A : BooleanType, A { class let t: a { { let i: e : e : P } protocol A { typealias e : c { println() -> U)) } return "[1)" class } struct A { return " case c, class a<T where g<T where T : e : e { func i: NSObject { class a { typealias e : C { protocol A { case c, func a let f = [1) case c<T { return " var d = { typealias e : c, let t: e class b class c, func f: BooleanType, A : NSObject { struct S<T : c { struct Q<T where g class b: e : c { class func i(" return " return " println() { class a { return "[1) typealias e : a { return " case c<T : C { let t: T: BooleanType, A { } typealias e : C { typealias e { return " case c<T: a { return "\() { struct Q<T { class func f: a { { case c, typealias e { struct A : c { let f = { return ""\(" struct S<T where g: e return " typealias e : Int -> ("[1) let t: c, class func g<T: e : P typealias e { protocol P { class case c, struct Q<d = " println() -> (f: Int -> ("[Void{ struct A { case c<T where g: c { case c<T where T : a { typealias e { class a } protocol A : e : a { typealias e : T: Int -> U) typealias e == { protocol A { class a { let t: NSObject { var d where T where g: P class b class a { class b: a { protocol A : NSObject { func i: b typealias e { typealias e { let i() -> ("\() { class func g: b let t: P let t: Int -> U) let t: NSObject { func i: e : e { struct A { typealias e == " { func a<d = { case c<T : a { func g typealias e { let t: T> case c, typealias e : BooleanType, A : BooleanType, A { let t: c<T : e class func a<d = { println() -> (" class a { func g: Int -> (" class a case c<d where T : b } typealias e : a { var d where g<T where g struct S<T : Int -> () { class func g func f: a { let t: C { case c, let t: T: c { class a let t: T: e == "[Void{ func i() -> U) protocol P { var d = { } protocol A : Int -> () -> U)"""" func g var d where T where T : BooleanType, A { println() -> U)" let t: a { } func f: T: a { struct S<T> { class a { class a { class func f: P class c, class b class b: e : a { struct S<T: a { return " func a<T : e typealias e : b class c, } let t: NSObject { println() -> U)"[Void{ typealias e { func f: e == [Void{ func a<T> return " func a<d where T { class let i: e { } typealias e : P typealias e == [Void{ struct A { func g<T where g } return " class c, println(" protocol A { let i(" return
mit
0eb83c41256f7ba4cb8f7d15a097da17
12.98895
87
0.601106
2.58104
false
false
false
false
svanimpe/around-the-table
Sources/AroundTheTable/Models/User.swift
1
3171
import BSON import Foundation /** A user. */ final class User { /// The user's ID. /// If set to nil, an ID is assigned when the instance is persisted. var id: Int? /// The user's display name. var name: String /// The user's profile picture. /// A default picture will be used when this value is `nil`. var picture: URL? /// The user's stored location. var location: Location? /// The date and time of the user's last sign-in. var lastSignIn: Date /** Initializes a `User`. `id` should be set to nil for new (unpersisted) instances. This is also its default value. `lastSignIn` is set to the current date and time by default. `picture` and `location` are nil by default. */ init(id: Int? = nil, lastSignIn: Date = Date(), name: String, picture: URL? = nil, location: Location? = nil) { self.id = id self.lastSignIn = lastSignIn self.name = name self.picture = picture self.location = location } } /** Adds `Equatable` conformance to `User`. Users are considered equal if they have the same `id`. */ extension User: Equatable { static func ==(lhs: User, rhs: User) -> Bool { return lhs.id == rhs.id } } /** Adds `BSON.Primitive` conformance to `User`. */ extension User: Primitive { /// A `User` is stored as a BSON `Document`. var typeIdentifier: Byte { return Document().typeIdentifier } /// This `User` as a BSON `Document`. /// Optional properties are included only when they are not `nil`. var document: Document { var document: Document = [ "_id": id, "name": name, "lastSignIn": lastSignIn ] if let picture = picture { document["picture"] = picture } if let location = location { document["location"] = location } return document } /** Returns this `User` as a BSON `Document` in binary form. */ func makeBinary() -> Bytes { return document.makeBinary() } /** Decodes a `User` from a BSON primitive. - Returns: `nil` when the primitive is not a `Document`. - Throws: a `BSONError` when the document does not contain all required properties. */ convenience init?(_ bson: Primitive?) throws { guard let bson = bson as? Document else { return nil } guard let id = Int(bson["_id"]) else { throw log(BSONError.missingField(name: "_id")) } guard let lastSignIn = Date(bson["lastSignIn"]) else { throw log(BSONError.missingField(name: "lastSignIn")) } guard let name = String(bson["name"]) else { throw log(BSONError.missingField(name: "name")) } let picture = try URL(bson["picture"]) let location = try Location(bson["location"]) self.init(id: id, lastSignIn: lastSignIn, name: name, picture: picture, location: location) } }
bsd-2-clause
5a8d58663c584091fb2894fc03778a3e
26.336207
115
0.561652
4.279352
false
false
false
false
mobilabsolutions/jenkins-ios
JenkinsiOS/Service/FavoritesLoader.swift
1
2551
// // Created by Robert on 22.06.17. // Copyright (c) 2017 MobiLab Solutions. All rights reserved. // import Foundation protocol FavoritesLoading: class { func didLoadFavorite(favoritable: Favoratible, from favorite: Favorite) func didFailToLoad(favorite: Favorite, reason: FavoriteLoadingFailure) } enum FavoriteLoadingFailure { case noAccount case networkManagerError(error: Error) case noFavoritableReturned } class FavoritesLoader { private unowned var delegate: FavoritesLoading init(with delegate: FavoritesLoading) { self.delegate = delegate } func loadFavorites(favorites: [Favorite]) { for favorite in favorites { guard let account = favorite.account else { delegate.didFailToLoad(favorite: favorite, reason: .noAccount); continue } switch favorite.type { case .build: loadBuild(favorite: favorite, with: account) // Folders are in essence just jobs themselves case .job, .folder: loadJob(favorite: favorite, with: account) } } } private func didLoadFavoritable(favoritable: Favoratible?, error: Error?, for favorite: Favorite) { DispatchQueue.main.async { guard error == nil else { self.delegate.didFailToLoad(favorite: favorite, reason: .networkManagerError(error: error!)) return } guard let favoritable = favoritable else { self.delegate.didFailToLoad(favorite: favorite, reason: .noFavoritableReturned) return } self.delegate.didLoadFavorite(favoritable: favoritable, from: favorite) } } private func loadJob(favorite: Favorite, with account: Account) { let userRequest = UserRequest.userRequestForJob(account: account, requestUrl: favorite.url) _ = NetworkManager.manager.getJob(userRequest: userRequest) { job, error in self.didLoadFavoritable(favoritable: job, error: error, for: favorite) } } private func loadBuild(favorite: Favorite, with account: Account) { let userRequest = UserRequest(requestUrl: favorite.url, account: account) _ = NetworkManager.manager.getBuild(userRequest: userRequest) { build, error in self.didLoadFavoritable(favoritable: build, error: error, for: favorite) } } }
mit
166942a53a595fc94b9dc286fb473e0c
33.945205
103
0.625245
4.724074
false
false
false
false
Rochester-Ting/XMLY
XMLY/XMLY/Classes/Main(主要)/View/RRTabBar.swift
1
2153
// // RRTabBar.swift // XMLY // // Created by Rochester on 17/1/17. // Copyright © 2017年 Rochester. All rights reserved. // import UIKit let kScreenW : CGFloat = UIScreen.main.bounds.width // 定义一个闭包 typealias btnTag = (_ tag : Int) -> Void class RRTabBar: UITabBar { lazy var selectedBtn = UIButton(type:.custom) var btntag : btnTag? override func layoutSubviews() { super.layoutSubviews() // tabBar的width let kWidth = self.frame.size.width // tabBar的height let kHeight = self.frame.size.height // 设置索引 var index : CGFloat = 0 // 获取每个tabbar的宽度 let tabBarW : CGFloat = kWidth / 5 let tabBarH : CGFloat = kHeight let ImageArr = [#imageLiteral(resourceName: "tabbar_find_n"),#imageLiteral(resourceName: "tabbar_sound_n"),#imageLiteral(resourceName: "tabbar_np_playnon"),#imageLiteral(resourceName: "tabbar_download_n"),#imageLiteral(resourceName: "tabbar_me_n")] let selectImage = [#imageLiteral(resourceName: "tabbar_find_h"),#imageLiteral(resourceName: "tabbar_sound_h"),#imageLiteral(resourceName: "tabbar_np_playnon"),#imageLiteral(resourceName: "tabbar_download_h"),#imageLiteral(resourceName: "tabbar_me_h")] for i in 0..<5{ let btn = UIButton(type: .custom) btn.frame = CGRect(x: CGFloat(i) + (index * tabBarW), y: 0, width: tabBarW, height: tabBarH) btn.setImage(ImageArr[i], for: .normal) btn.setImage(selectImage[i], for: .selected) btn.addTarget(self, action: #selector(btnClick(_:)), for: .touchUpInside) btn.tag = i if i == 0{ btn.isSelected = true selectedBtn = btn } self.addSubview(btn) index += 1 } } @objc func btnClick(_ btn : UIButton){ if btn.tag == 2{ }else{ btn.isSelected = true selectedBtn.isSelected = false selectedBtn = btn } if (btntag != nil) { btntag!(btn.tag) } } }
mit
f463e44c27deecde121b03ef74acb1d4
34.79661
259
0.581913
4.07722
false
false
false
false
lumenlunae/SwiftSpriter
SwiftSpriter/Classes/Model/SpriterTimeline.swift
1
778
// // SpriterTimeline.swift // SwiftSpriter // // Created by Matt on 8/27/16. // Copyright © 2016 BiminiRoad. All rights reserved. // import Foundation struct SpriterTimeline: SpriterParseable { var id: Int var name: String var objectType: SpriterObjectType? var keys: [SpriterTimelineKey] = [] init?(data: AnyObject) { guard let id = data.value(forKey: "id") as? Int, let name = data.value(forKey: "name") as? String else { return nil } self.id = id self.name = name if let type = data.value(forKey: "type") as? String, let objectType = SpriterObjectType(rawValue: type) { self.objectType = objectType } } }
mit
9ff550b36a870209713a80aae90a3601
21.852941
67
0.564994
3.904523
false
false
false
false
niunaruto/DeDaoAppSwift
testSwift/Pods/RxSwift/RxSwift/Observables/SingleAsync.swift
14
3648
// // SingleAsync.swift // RxSwift // // Created by Junior B. on 09/11/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // extension ObservableType { /** The single operator is similar to first, but throws a `RxError.noElements` or `RxError.moreThanOneElement` if the source Observable does not emit exactly one element before successfully completing. - seealso: [single operator on reactivex.io](http://reactivex.io/documentation/operators/first.html) - returns: An observable sequence that emits a single element or throws an exception if more (or none) of them are emitted. */ public func single() -> Observable<Element> { return SingleAsync(source: self.asObservable()) } /** The single operator is similar to first, but throws a `RxError.NoElements` or `RxError.MoreThanOneElement` if the source Observable does not emit exactly one element before successfully completing. - seealso: [single operator on reactivex.io](http://reactivex.io/documentation/operators/first.html) - parameter predicate: A function to test each source element for a condition. - returns: An observable sequence that emits a single element or throws an exception if more (or none) of them are emitted. */ public func single(_ predicate: @escaping (Element) throws -> Bool) -> Observable<Element> { return SingleAsync(source: self.asObservable(), predicate: predicate) } } fileprivate final class SingleAsyncSink<Observer: ObserverType> : Sink<Observer>, ObserverType { typealias Element = Observer.Element typealias Parent = SingleAsync<Element> private let _parent: Parent private var _seenValue: Bool = false init(parent: Parent, observer: Observer, cancel: Cancelable) { self._parent = parent super.init(observer: observer, cancel: cancel) } func on(_ event: Event<Element>) { switch event { case .next(let value): do { let forward = try self._parent._predicate?(value) ?? true if !forward { return } } catch let error { self.forwardOn(.error(error as Swift.Error)) self.dispose() return } if self._seenValue { self.forwardOn(.error(RxError.moreThanOneElement)) self.dispose() return } self._seenValue = true self.forwardOn(.next(value)) case .error: self.forwardOn(event) self.dispose() case .completed: if self._seenValue { self.forwardOn(.completed) } else { self.forwardOn(.error(RxError.noElements)) } self.dispose() } } } final class SingleAsync<Element>: Producer<Element> { typealias Predicate = (Element) throws -> Bool fileprivate let _source: Observable<Element> fileprivate let _predicate: Predicate? init(source: Observable<Element>, predicate: Predicate? = nil) { self._source = source self._predicate = predicate } override func run<Observer: ObserverType>(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { let sink = SingleAsyncSink(parent: self, observer: observer, cancel: cancel) let subscription = self._source.subscribe(sink) return (sink: sink, subscription: subscription) } }
mit
ffd9be774a4b7c2bdbead591c20a7267
34.067308
171
0.623526
4.805007
false
false
false
false
huang1988519/WechatArticles
WechatArticles/WechatArticles/Library/Loggerithm/Loggerithm.swift
1
13122
// // Loggerithm.swift // Loggerithm // // Created by Honghao Zhang on 2014-12-10. // Copyright (c) 2015 Honghao Zhang (张宏昊) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import Foundation public struct Loggerithm { /// A default logger instance. public static let defaultLogger = Loggerithm() /// Log level current used. public var logLevel = LogLevel.defaultLevel /// Whether should show date & time field, ture for showing, false for hidding. public var showDateTime = true /// Whether should show log level field, ture for showing, false for hidding. public var showLogLevel = true /// Whether should show file name field, ture for showing, false for hidding. public var showFileName = true /// Whether should show line number field, ture for showing, false for hidding. public var showLineNumber = true /// Whether should show function name field, ture for showing, false for hidding. public var showFunctionName = true /// Whether should output color log. public var useColorfulLog = false /// Color used for verbose log string. public var verboseColor: Color? { set { LoggerColor.verboseColor = newValue } get { return LoggerColor.verboseColor } } /// Color used for debug log string. public var debugColor: Color? { set { LoggerColor.debugColor = newValue } get { return LoggerColor.debugColor } } /// Color used for info log string. public var infoColor: Color? { set { LoggerColor.infoColor = newValue } get { return LoggerColor.infoColor } } /// Color used for warning log string. public var warningColor: Color? { set { LoggerColor.warningColor = newValue } get { return LoggerColor.warningColor } } /// Color used for error log string. public var errorColor: Color? { set { LoggerColor.errorColor = newValue } get { return LoggerColor.errorColor } } /// NSDateFromatter used internally. private let dateFormatter = NSDateFormatter() /// LogFunction used, print for DEBUG, NSLog for Production. #if DEBUG private let LogFunction: (format: String) -> Void = {format in print(format)} private let UsingNSLog = false #else private let LogFunction: (format: String, args: CVarArgType...) -> Void = NSLog private let UsingNSLog = true #endif public init() { dateFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX") //24H dateFormatter.dateFormat = "y-MM-dd HH:mm:ss.SSS" // Check to see whether XcodeColors is installed and enabled // useColorfulLog will be turned on when environment variable "XcodeColors" == "YES" if let xcodeColorsEnabled = NSProcessInfo().environment["XcodeColors"] as String? where xcodeColorsEnabled == "YES" { useColorfulLog = true } } /** Prinln an new line, without any fileds. This will ignore any filed settings. */ public func emptyLine() { dispatch_async(dispatch_get_main_queue(), { () -> Void in self.LogFunction(format: "") }) } /** Logs textual representation of `value` with .Verbose level. - parameter value: A value conforms `Streamable`, `Printable`, `DebugPrintable`. - parameter function: Function name - parameter file: File name - parameter line: Line number - returns: The string logged out. */ public func verbose<T>(value: T, function: String = __FUNCTION__, file: String = __FILE__, line: Int = __LINE__) -> String? { return verbose("\(value)", function: function, file: file, line: line) } /** Logs an message with formatted string and arguments list with .Verbose level. - parameter format: Formatted string - parameter function: Function name - parameter file: File name - parameter line: Line number - parameter args: Arguments list - returns: The string logged out. */ public func verbose(format: String, function: String = __FUNCTION__, file: String = __FILE__, line: Int = __LINE__, args: CVarArgType...) -> String? { if .Verbose >= logLevel { return log(.Verbose, function: function, file: file, line: line, format: format, args: args) } return nil } /** Logs textual representation of `value` with .Debug level. - parameter value: A value conforms `Streamable`, `Printable`, `DebugPrintable`. - parameter function: Function name - parameter file: File name - parameter line: Line number - returns: The string logged out. */ public func debug<T>(value: T, function: String = __FUNCTION__, file: String = __FILE__, line: Int = __LINE__) -> String? { return debug("\(value)", function: function, file: file, line: line) } /** Logs an message with formatted string and arguments list with .Debug level. - parameter format: Formatted string - parameter function: Function name - parameter file: File name - parameter line: Line number - parameter args: Arguments list - returns: The string logged out. */ public func debug(format: String, function: String = __FUNCTION__, file: String = __FILE__, line: Int = __LINE__, args: CVarArgType...) -> String? { if .Debug >= logLevel { return log(.Debug, function: function, file: file, line: line, format: format, args: args) } return nil } /** Logs textual representation of `value` with .Info level. - parameter value: A value conforms `Streamable`, `Printable`, `DebugPrintable`. - parameter function: Function name - parameter file: File name - parameter line: Line number - returns: The string logged out. */ public func info<T>(value: T, function: String = __FUNCTION__, file: String = __FILE__, line: Int = __LINE__) -> String? { return info("\(value)", function: function, file: file, line: line) } /** Logs an message with formatted string and arguments list with .Info level. - parameter format: Formatted string - parameter function: Function name - parameter file: File name - parameter line: Line number - parameter args: Arguments list - returns: The string logged out. */ public func info(format: String, function: String = __FUNCTION__, file: String = __FILE__, line: Int = __LINE__, args: CVarArgType...) -> String? { if .Info >= logLevel { return log(.Info, function: function, file: file, line: line, format: format, args: args) } return nil } /** Logs textual representation of `value` with .Warning level. - parameter value: A value conforms `Streamable`, `Printable`, `DebugPrintable`. - parameter function: Function name - parameter file: File name - parameter line: Line number - returns: The string logged out. */ public func warning<T>(value: T, function: String = __FUNCTION__, file: String = __FILE__, line: Int = __LINE__) -> String? { return warning("\(value)", function: function, file: file, line: line) } /** Logs an message with formatted string and arguments list with .Warning level. - parameter format: Formatted string - parameter function: Function name - parameter file: File name - parameter line: Line number - parameter args: Arguments list - returns: The string logged out. */ public func warning(format: String, function: String = __FUNCTION__, file: String = __FILE__, line: Int = __LINE__, args: CVarArgType...) -> String? { if .Warning >= logLevel { return log(.Warning, function: function, file: file, line: line, format: format, args: args) } return nil } /** Logs textual representation of `value` with .Error level. - parameter value: A value conforms `Streamable`, `Printable`, `DebugPrintable`. - parameter function: Function name - parameter file: File name - parameter line: Line number - returns: The string logged out. */ public func error<T>(value: T, function: String = __FUNCTION__, file: String = __FILE__, line: Int = __LINE__) -> String? { return error("\(value)", function: function, file: file, line: line) } /** Logs an message with formatted string and arguments list with .Error level. - parameter format: Formatted string - parameter function: Function name - parameter file: File name - parameter line: Line number - parameter args: Arguments list - returns: The string logged out. */ public func error(format: String, function: String = __FUNCTION__, file: String = __FILE__, line: Int = __LINE__, args: CVarArgType...) -> String? { if .Error >= logLevel { return log(.Error, function: function, file: file, line: line, format: format, args: args) } return nil } /** Logs an message with formatted string and arguments list. - parameter level: Log level - parameter format: Formatted string - parameter function: Function name - parameter file: File name - parameter line: Line number - parameter args: Arguments list - returns: The string logged out. */ public func logWithLevel(level: LogLevel, _ format: String = "", function: String = __FUNCTION__, file: String = __FILE__, line: Int = __LINE__, args: CVarArgType...) -> String? { if level >= logLevel { return log(level, file: file, function: function, line: line, format: format, args: args) } return nil } /** Construct a log message, log it out and return it. - parameter level: Log level - parameter function: Function name - parameter file: File name - parameter line: Line number - parameter format: Formatted string - parameter args: Arguments list - returns: The string logged out. */ private func log(level: LogLevel, function: String = __FUNCTION__, file: String = __FILE__, line: Int = __LINE__, format: String, args: [CVarArgType]) -> String { let dateTime = showDateTime ? (UsingNSLog ? "" : "\(dateFormatter.stringFromDate(NSDate())) ") : "" let levelString = showLogLevel ? "[\(LogLevel.descritionForLogLevel(level))] " : "" var fileLine = "" if showFileName { fileLine += "[" + (file as NSString).lastPathComponent if showLineNumber { fileLine += ":\(line)" } fileLine += "] " } let functionString = showFunctionName ? function : "" let message: String if args.count == 0 { message = format } else { message = String(format: format, arguments: args) } let infoString = "\(dateTime)\(levelString)\(fileLine)\(functionString)".stringByTrimmingCharactersInSet(NSCharacterSet(charactersInString: " ")) let logString = infoString + (infoString.isEmpty ? "" : ": ") + "\(message)" let outputString = useColorfulLog ? LoggerColor.applyColorForLogString(logString, withLevel: level) : logString dispatch_async(dispatch_get_main_queue(), { () -> Void in self.LogFunction(format: outputString) }) return logString } }
apache-2.0
ddf6dcff7f52bd611f5845a8ec6c42e5
34.836066
181
0.609332
4.646121
false
false
false
false
Rapid-SDK/ios
Examples/RapiChat - Chat client/RapiChat shared/Message.swift
1
606
// // Message.swift // RapiChat // // Created by Jan on 27/06/2017. // Copyright © 2017 Rapid. All rights reserved. // import Foundation import Rapid struct Message: Codable { let id: String let channelID: String let text: String? let sender: String let sentDate: Date enum CodingKeys : String, CodingKey { case id = "id" case channelID = "channelId" case text = "text" case sender = "senderName" case sentDate = "sentDate" } var isMyMessage: Bool { return sender == UserDefaultsManager.username } }
mit
1fcffc6bce6386885ab23e3bd865b44e
18.516129
53
0.601653
4.033333
false
false
false
false
alblue/swift
stdlib/public/core/StringBridge.swift
1
10115
//===----------------------------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// import SwiftShims /// Effectively an untyped NSString that doesn't require foundation. @usableFromInline internal typealias _CocoaString = AnyObject #if _runtime(_ObjC) // Swift's String bridges NSString via this protocol and these // variables, allowing the core stdlib to remain decoupled from // Foundation. @usableFromInline // @testable @_effects(releasenone) internal func _stdlib_binary_CFStringCreateCopy( _ source: _CocoaString ) -> _CocoaString { let result = _swift_stdlib_CFStringCreateCopy(nil, source) as AnyObject return result } @usableFromInline // @testable @_effects(readonly) internal func _stdlib_binary_CFStringGetLength( _ source: _CocoaString ) -> Int { return _swift_stdlib_CFStringGetLength(source) } @usableFromInline // @testable @_effects(readonly) internal func _stdlib_binary_CFStringGetCharactersPtr( _ source: _CocoaString ) -> UnsafeMutablePointer<UTF16.CodeUnit>? { return UnsafeMutablePointer( mutating: _swift_stdlib_CFStringGetCharactersPtr(source)) } /// Copies a slice of a _CocoaString into contiguous storage of /// sufficient capacity. @_effects(releasenone) internal func _cocoaStringCopyCharacters( from source: _CocoaString, range: Range<Int>, into destination: UnsafeMutablePointer<UTF16.CodeUnit> ) { _swift_stdlib_CFStringGetCharacters( source, _swift_shims_CFRange(location: range.lowerBound, length: range.count), destination) } @_effects(readonly) internal func _cocoaStringSubscript( _ target: _CocoaString, _ position: Int ) -> UTF16.CodeUnit { let cfSelf: _swift_shims_CFStringRef = target return _swift_stdlib_CFStringGetCharacterAtIndex(cfSelf, position) } // // Conversion from NSString to Swift's native representation // private var kCFStringEncodingASCII : _swift_shims_CFStringEncoding { @inline(__always) get { return 0x0600 } } private var kCFStringEncodingUTF8 : _swift_shims_CFStringEncoding { @inline(__always) get { return 0x8000100 } } #if !(arch(i386) || arch(arm)) // Resiliently write a tagged cocoa string's contents into a buffer @_effects(releasenone) // @opaque internal func _bridgeTagged( _ cocoa: _CocoaString, intoUTF8 bufPtr: UnsafeMutableBufferPointer<UInt8> ) -> Int? { _sanityCheck(_isObjCTaggedPointer(cocoa)) let ptr = bufPtr.baseAddress._unsafelyUnwrappedUnchecked let length = _stdlib_binary_CFStringGetLength(cocoa) _sanityCheck(length <= _SmallString.capacity) var count = 0 let numCharWritten = _swift_stdlib_CFStringGetBytes( cocoa, _swift_shims_CFRange(location: 0, length: length), kCFStringEncodingUTF8, 0, 0, ptr, bufPtr.count, &count) return length == numCharWritten ? count : nil } #endif @_effects(releasenone) // @opaque internal func _cocoaUTF8Pointer(_ str: _CocoaString) -> UnsafePointer<UInt8>? { // TODO(String bridging): Is there a better interface here? This requires nul // termination and may assume ASCII. guard let ptr = _swift_stdlib_CFStringGetCStringPtr( str, kCFStringEncodingUTF8 ) else { return nil } return ptr._asUInt8 } private enum CocoaStringPointer { case ascii(UnsafePointer<UInt8>) case utf8(UnsafePointer<UInt8>) case utf16(UnsafePointer<UInt16>) case none } @_effects(readonly) private func _getCocoaStringPointer( _ cfImmutableValue: _CocoaString ) -> CocoaStringPointer { if let utf8Ptr = _cocoaUTF8Pointer(cfImmutableValue) { // NOTE: CFStringGetCStringPointer means ASCII return .ascii(utf8Ptr) } if let utf16Ptr = _swift_stdlib_CFStringGetCharactersPtr(cfImmutableValue) { return .utf16(utf16Ptr) } return .none } @usableFromInline @_effects(releasenone) // @opaque internal func _bridgeCocoaString(_ cocoaString: _CocoaString) -> _StringGuts { if let abstract = cocoaString as? _AbstractStringStorage { return abstract.asString._guts } #if !(arch(i386) || arch(arm)) if _isObjCTaggedPointer(cocoaString) { return _StringGuts(_SmallString(taggedCocoa: cocoaString)) } #endif // "copy" it into a value to be sure nobody will modify behind // our backs. In practice, when value is already immutable, this // just does a retain. // // TODO: Only in certain circumstances should we emit this call: // 1) If it's immutable, just retain it. // 2) If it's mutable with no associated information, then a copy must // happen; might as well eagerly bridge it in. // 3) If it's mutable with associated information, must make the call // let immutableCopy = _stdlib_binary_CFStringCreateCopy(cocoaString) as AnyObject #if !(arch(i386) || arch(arm)) if _isObjCTaggedPointer(immutableCopy) { return _StringGuts(_SmallString(taggedCocoa: immutableCopy)) } #endif let (fastUTF8, isASCII): (Bool, Bool) switch _getCocoaStringPointer(immutableCopy) { case .ascii(_): (fastUTF8, isASCII) = (true, true) case .utf8(_): (fastUTF8, isASCII) = (true, false) default: (fastUTF8, isASCII) = (false, false) } let length = _stdlib_binary_CFStringGetLength(immutableCopy) return _StringGuts( cocoa: immutableCopy, providesFastUTF8: fastUTF8, isASCII: isASCII, length: length) } extension String { public // SPI(Foundation) init(_cocoaString: AnyObject) { self._guts = _bridgeCocoaString(_cocoaString) } } extension String { @_effects(releasenone) public // SPI(Foundation) func _bridgeToObjectiveCImpl() -> AnyObject { if _guts.isSmall { return _guts.asSmall.withUTF8 { bufPtr in // TODO(String bridging): worth isASCII check for different encoding? return _swift_stdlib_CFStringCreateWithBytes( nil, bufPtr.baseAddress._unsafelyUnwrappedUnchecked, bufPtr.count, kCFStringEncodingUTF8, 0) as AnyObject } } if _guts._object.isImmortal { return _SharedStringStorage( immortal: _guts._object.fastUTF8.baseAddress!, countAndFlags: _guts._object._countAndFlags) } _sanityCheck(_guts._object.hasObjCBridgeableObject, "Unknown non-bridgeable object case") return _guts._object.objCBridgeableObject } } // At runtime, this class is derived from `__SwiftNativeNSStringBase`, // which is derived from `NSString`. // // The @_swift_native_objc_runtime_base attribute // This allows us to subclass an Objective-C class and use the fast Swift // memory allocator. @_fixed_layout // FIXME(sil-serialize-all) @objc @_swift_native_objc_runtime_base(__SwiftNativeNSStringBase) public class __SwiftNativeNSString { @usableFromInline // FIXME(sil-serialize-all) @objc internal init() {} deinit {} } /// A shadow for the "core operations" of NSString. /// /// Covers a set of operations everyone needs to implement in order to /// be a useful `NSString` subclass. @objc public protocol _NSStringCore : _NSCopying /* _NSFastEnumeration */ { // The following methods should be overridden when implementing an // NSString subclass. @objc(length) var length: Int { get } @objc(characterAtIndex:) func character(at index: Int) -> UInt16 // We also override the following methods for efficiency. @objc(getCharacters:range:) func getCharacters( _ buffer: UnsafeMutablePointer<UInt16>, range aRange: _SwiftNSRange) @objc(_fastCharacterContents) func _fastCharacterContents() -> UnsafePointer<UInt16>? @objc(_fastCStringContents) func _fastCStringContents() -> UnsafePointer<CChar>? } // Called by the SwiftObject implementation to get the description of a value // as an NSString. @_silgen_name("swift_stdlib_getDescription") public func _getDescription<T>(_ x: T) -> AnyObject { return String(reflecting: x)._bridgeToObjectiveCImpl() } #else // !_runtime(_ObjC) @_fixed_layout // FIXME(sil-serialize-all) public class __SwiftNativeNSString { @usableFromInline // FIXME(sil-serialize-all) internal init() {} deinit {} } public protocol _NSStringCore: class {} #endif // Special-case Index <-> Offset converters for bridging and use in accelerating // the UTF16View in general. extension StringProtocol { @_specialize(where Self == String) @_specialize(where Self == Substring) public // SPI(Foundation) func _toUTF16Offset(_ idx: Index) -> Int { return self.utf16.distance(from: self.utf16.startIndex, to: idx) } @_specialize(where Self == String) @_specialize(where Self == Substring) public // SPI(Foundation) func _toUTF16Index(_ offset: Int) -> Index { return self.utf16.index(self.utf16.startIndex, offsetBy: offset) } @_specialize(where Self == String) @_specialize(where Self == Substring) public // SPI(Foundation) func _toUTF16Offsets(_ indices: Range<Index>) -> Range<Int> { let lowerbound = _toUTF16Offset(indices.lowerBound) let length = self.utf16.distance( from: indices.lowerBound, to: indices.upperBound) return Range( uncheckedBounds: (lower: lowerbound, upper: lowerbound + length)) } @_specialize(where Self == String) @_specialize(where Self == Substring) public // SPI(Foundation) func _toUTF16Indices(_ range: Range<Int>) -> Range<Index> { let lowerbound = _toUTF16Index(range.lowerBound) let upperbound = _toUTF16Index(range.lowerBound + range.count) return Range(uncheckedBounds: (lower: lowerbound, upper: upperbound)) } } extension String { public // @testable / @benchmarkable func _copyUTF16CodeUnits( into buffer: UnsafeMutableBufferPointer<UInt16>, range: Range<Int> ) { _sanityCheck(buffer.count >= range.count) let indexRange = self._toUTF16Indices(range) self._nativeCopyUTF16CodeUnits(into: buffer, range: indexRange) } }
apache-2.0
a169d49be3bc3e322f342c24fcb4a475
30.027607
80
0.710035
4.167697
false
false
false
false
jum/Charts
ChartsDemo-macOS/ChartsDemo-macOS/Demos/RadarDemoViewController.swift
5
1463
// // RadarDemoViewController.swift // ChartsDemo-OSX // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/ios-charts import Foundation import Cocoa import Charts open class RadarDemoViewController: NSViewController { @IBOutlet var radarChartView: RadarChartView! override open func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. let ys1 = Array(1..<10).map { x in return sin(Double(x) / 2.0 / 3.141 * 1.5) } let ys2 = Array(1..<10).map { x in return cos(Double(x) / 2.0 / 3.141) } let yse1 = ys1.enumerated().map { x, y in return RadarChartDataEntry(value: y) } let yse2 = ys2.enumerated().map { x, y in return RadarChartDataEntry(value: y) } let data = RadarChartData() let ds1 = RadarChartDataSet(entries: yse1, label: "Hello") ds1.colors = [NSUIColor.red] data.addDataSet(ds1) let ds2 = RadarChartDataSet(entries: yse2, label: "World") ds2.colors = [NSUIColor.blue] data.addDataSet(ds2) self.radarChartView.data = data self.radarChartView.chartDescription?.text = "Radarchart Demo" } override open func viewWillAppear() { self.radarChartView.animate(xAxisDuration: 0.0, yAxisDuration: 1.0) } }
apache-2.0
6bcea37ad414f27b45220177d5e8fc07
30.12766
88
0.636364
3.932796
false
false
false
false
codestergit/LTMorphingLabel
LTMorphingLabel/LTMorphingLabel+Sparkle.swift
1
5893
// // LTMorphingLabel+Sparkle.swift // https://github.com/lexrus/LTMorphingLabel // // The MIT License (MIT) // Copyright (c) 2014 Lex Tang, http://LexTang.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 var kEmitterViewKey = "kEmitterViewKey" let kEmitterViewPointer = ConstUnsafePointer<String>(COpaquePointer(&kEmitterViewKey)) extension LTMorphingLabel { var emitterView: LTEmitterView { get { if let _emitterView: LTEmitterView = objc_getAssociatedObject(self, kEmitterViewPointer) as? LTEmitterView { return _emitterView } let _emitterView = LTEmitterView(frame: self.bounds) self.addSubview(_emitterView) self.emitterView = _emitterView return _emitterView } set { objc_setAssociatedObject(self, kEmitterViewPointer, newValue, objc_AssociationPolicy(OBJC_ASSOCIATION_RETAIN_NONATOMIC)) } } func _maskedImageForCharLimbo(charLimbo: LTCharacterLimbo, withProgress progress: CGFloat) -> (UIImage, CGRect) { let maskedHeight = charLimbo.rect.size.height * max(0.01, progress) let maskedSize = CGSizeMake( charLimbo.rect.size.width, maskedHeight) UIGraphicsBeginImageContextWithOptions(maskedSize, false, UIScreen.mainScreen().scale) let rect = CGRectMake(0, 0, charLimbo.rect.size.width, maskedHeight) String(charLimbo.char).bridgeToObjectiveC().drawInRect(rect, withAttributes: [ NSFontAttributeName: self.font, NSForegroundColorAttributeName: self.textColor ]) let newImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); let newRect = CGRectMake( charLimbo.rect.origin.x, charLimbo.rect.origin.y, charLimbo.rect.size.width, maskedHeight) return (newImage, newRect) } func SparkleLoad() { _startClosures["Sparkle\(LTMorphingPhaseStart)"] = { self.emitterView.removeAllEmit() } _progressClosures["Sparkle\(LTMorphingPhaseManipulateProgress)"] = { (index: Int, progress: Float, isNewChar: Bool) in if !isNewChar { return min(1.0, max(0.0, progress - self.morphingCharacterDelay * Float(index))) } let j = Float(sin(Double(index))) * 1.6 return min(1.0, max(0.0001, progress + self.morphingCharacterDelay * j)) } _effectClosures["Sparkle\(LTMorphingPhaseDisappear)"] = { (char:Character, index: Int, progress: Float) in return LTCharacterLimbo( char: char, rect: self._originRects[index], alpha: CGFloat(1.0 - progress), size: self.font.pointSize, drawingProgress: 0.0) } _effectClosures["Sparkle\(LTMorphingPhaseAppear)"] = { (char:Character, index: Int, progress: Float) in if char != " " { let rect = self._newRects[index] let emitterPosition = CGPointMake( rect.origin.x + rect.size.width / 2.0, CGFloat(progress) * rect.size.height + rect.origin.y) self.emitterView.createEmitter("c\(index)", duration: 0.6) { (layer, cell) in layer.emitterSize = CGSizeMake(rect.size.width , 1) cell.emissionLongitude = CGFloat(M_PI / 2.0) cell.scale = self.font.pointSize / 300.0 cell.scaleSpeed = self.font.pointSize / 300.0 * -1.5 cell.color = self.textColor.CGColor cell.birthRate = Float(self.font.pointSize * CGFloat(arc4random_uniform(7) + 3)) }.update { (layer, cell) in layer.emitterPosition = emitterPosition }.play() } return LTCharacterLimbo( char: char, rect: self._newRects[index], alpha: CGFloat(self.morphingProgress), size: self.font.pointSize, drawingProgress: CGFloat(progress) ) } _drawingClosures["Sparkle\(LTMorphingPhaseDraw)"] = { (charLimbo: LTCharacterLimbo) in if charLimbo.drawingProgress > 0.0 { let (charImage, rect) = self._maskedImageForCharLimbo(charLimbo, withProgress: charLimbo.drawingProgress) charImage.drawInRect(rect) return true } return false } } }
mit
dc6ef12b1e065758b1d2f4190d540508
39.034014
121
0.598131
4.908257
false
false
false
false
gogunskiy/The-Name
NameMe/Classes/UserInterface/ViewControllers/NMOriginsListViewController/NMOriginsListViewController.swift
1
2935
// // NMNamesListViewController // NameMe // // Created by Vladimir Gogunsky on 1/3/15. // Copyright (c) 2015 Volodymyr Hohunskyi. All rights reserved. // import UIKit class NMOriginsListViewController: NMBaseViewController { @IBOutlet var tableView : UITableView! @IBOutlet var searchBar : UISearchBar! var origins : NSArray = NSArray() override func viewDidLoad() { super.viewDidLoad() fetchData() } func updateUI() { tableView.reloadData() } func fetchData() { NEDataManager.sharedInstance.fetchOrigins { (result) -> () in self.origins = result dispatch_async(dispatch_get_main_queue(), { self.tableView.reloadData() }) } } func filteredItems() -> NSArray { var predicateString = ""; if searchBar != nil { if !searchBar.text.isEmpty { predicateString = NSString(format: "name contains[cd] '%@'", searchBar.text) } } if predicateString.isEmpty { return self.origins; } else { return self.origins.filteredArrayUsingPredicate(NSPredicate(format: predicateString)!) } } func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return filteredItems().count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { var cell:NMOriginListCell = self.tableView.dequeueReusableCellWithIdentifier("NMOriginListCell") as NMOriginListCell var item: NMOriginItem = filteredItems()[indexPath.row] as NMOriginItem cell.nameLabel.text = item.name return cell } func scrollViewWillBeginDragging(scrollView: UIScrollView) { searchBar.resignFirstResponder() } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { var viewController :NMNamesListViewController = segue.destinationViewController as NMNamesListViewController var indexPath : NSIndexPath? = self.tableView?.indexPathForSelectedRow() var item: NMOriginItem = filteredItems()[indexPath!.row] as NMOriginItem let query = NMQuery( pattern: nil, origins: [item.id!], sortType: .name, groupType: .alpha) viewController.fetchData(query, completion: { (result) -> () in }) } func searchBar(searchBar: UISearchBar, textDidChange searchText: String) { self.tableView.reloadData() } func searchBarSearchButtonClicked(searchBar: UISearchBar) { searchBar.resignFirstResponder() } }
mit
cb7297f411078fa812a35dfb7c5856a6
27.495146
124
0.613969
5.445269
false
false
false
false
walkingsmarts/ReactiveCocoa
ReactiveCocoa/ObjC+Runtime.swift
13
665
/// Search in `class` for any method that matches the supplied selector without /// propagating to the ancestors. /// /// - parameters: /// - class: The class to search the method in. /// - selector: The selector of the method. /// /// - returns: The matching method, or `nil` if none is found. internal func class_getImmediateMethod(_ `class`: AnyClass, _ selector: Selector) -> Method? { if let buffer = class_copyMethodList(`class`, nil) { defer { free(buffer) } var iterator = buffer while let method = iterator.pointee { if method_getName(method) == selector { return method } iterator = iterator.advanced(by: 1) } } return nil }
mit
a20283856e93706a2ef5a0f2203dd46f
27.913043
94
0.67218
3.63388
false
false
false
false