repo_name
stringlengths
6
91
ref
stringlengths
12
59
path
stringlengths
7
936
license
stringclasses
15 values
copies
stringlengths
1
3
content
stringlengths
61
711k
hash
stringlengths
32
32
line_mean
float64
4.88
60.8
line_max
int64
12
421
alpha_frac
float64
0.1
0.92
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
breadwallet/breadwallet-ios
refs/heads/master
breadwalletIntentHandler/IntentHandler.swift
mit
1
// // IntentHandler.swift // breadwalletIntentHandler // // Created by stringcode on 11/02/2021. // Copyright © 2021 Breadwinner AG. All rights reserved. // // See the LICENSE file at the project root for license information. // import Intents class IntentHandler: INExtension { private let service: WidgetService override init() { service = DefaultWidgetService(widgetDataShareService: nil, imageStoreService: nil) super.init() } override func handler(for intent: INIntent) -> Any { return self } } // MARK: - AssetIntentHandling extension IntentHandler: AssetIntentHandling { func provideChartUpColorOptionsCollection(for intent: AssetIntent, with completion: @escaping (INObjectCollection<ColorOption>?, Error?) -> Void) { service.fetchChartUpColorOptions { result in switch result { case let .success(options): let collection = INObjectCollection( sections: [ INObjectSection(title: S.Widget.colorSectionBasic, items: options.filter { $0.isBasicColor }), INObjectSection(title: S.Widget.colorSectionText, items: options.filter { $0.isBrdTextColor }), INObjectSection(title: S.Widget.colorSectionBackground, items: options.filter { $0.isBrdBackgroundColor }) ] ) completion(collection, nil) case let .failure(error): print("Failed to chart up color options", error) completion(INObjectCollection(items: []), error) } } } func defaultChartUpColor(for intent: AssetIntent) -> ColorOption? { return service.defaultChartUpOptions() } func provideChartDownColorOptionsCollection(for intent: AssetIntent, with completion: @escaping (INObjectCollection<ColorOption>?, Error?) -> Void) { service.fetchChartDownColorOptions { result in switch result { case let .success(options): let collection = INObjectCollection( sections: [ INObjectSection(title: S.Widget.colorSectionBasic, items: options.filter { $0.isBasicColor }), INObjectSection(title: S.Widget.colorSectionText, items: options.filter { $0.isBrdTextColor }), INObjectSection(title: S.Widget.colorSectionBackground, items: options.filter { $0.isBrdBackgroundColor }) ] ) completion(collection, nil) case let .failure(error): print("Failed to chart up color options", error) completion(INObjectCollection(items: []), error) } } } func defaultChartDownColor(for intent: AssetIntent) -> ColorOption? { return service.defaultChartDownOptions() } func provideBackgroundColorOptionsCollection(for intent: AssetIntent, with completion: @escaping (INObjectCollection<ColorOption>?, Error?) -> Void) { service.fetchBackgroundColorOptions { result in switch result { case let .success(options): let collection = INObjectCollection( sections: [ INObjectSection(title: S.Widget.colorSectionSystem, items: options.filter { $0.isSystem }), INObjectSection(title: S.Widget.colorSectionBackground, items: options.filter { $0.isBrdBackgroundColor }), INObjectSection(title: S.Widget.colorSectionBasic, items: options.filter { $0.isBasicColor }), INObjectSection(title: S.Widget.colorSectionCurrency, items: options.filter { $0.isCurrencyColor }) ] ) completion(collection, nil) case let .failure(error): print("Failed to chart up color options", error) completion(INObjectCollection(items: []), error) } } } func defaultBackgroundColor(for intent: AssetIntent) -> ColorOption? { return service.defaultBackgroundColor() } func provideTextColorOptionsCollection(for intent: AssetIntent, with completion: @escaping (INObjectCollection<ColorOption>?, Error?) -> Void) { service.fetchTextColorOptions { result in switch result { case let .success(options): let collection = INObjectCollection( sections: [ INObjectSection(title: S.Widget.colorSectionSystem, items: options.filter { $0.isSystem }), INObjectSection(title: S.Widget.colorSectionText, items: options.filter { $0.isBrdTextColor }), INObjectSection(title: S.Widget.colorSectionBasic, items: options.filter { $0.isBasicColor }), INObjectSection(title: S.Widget.colorSectionBackground, items: options.filter { $0.isBrdBackgroundColor }) ] ) completion(collection, nil) case let .failure(error): print("Failed to chart up color options", error) completion(INObjectCollection(items: []), error) } } } func defaultTextColor(for intent: AssetIntent) -> ColorOption? { return service.defaultTextColor() } func provideAssetOptionsCollection(for intent: AssetIntent, with completion: @escaping (INObjectCollection<AssetOption>?, Error?) -> Void) { service.fetchAssetOptions { result in switch result { case let .success(options): completion(INObjectCollection(items: options), nil) case let .failure(error): print("Failed to load asset options", error) completion(INObjectCollection(items: []), error) } } } func defaultAsset(for intent: AssetIntent) -> AssetOption? { return service.defaultAssetOptions().first } } // MARK: - AssetListIntentHandling extension IntentHandler: AssetListIntentHandling { func provideAssetsOptionsCollection(for intent: AssetListIntent, with completion: @escaping (INObjectCollection<AssetOption>?, Error?) -> Void) { service.fetchAssetOptions { result in switch result { case let .success(options): completion(INObjectCollection(items: options), nil) case let .failure(error): print("Failed to load asset options", error) completion(INObjectCollection(items: []), error) } } } func defaultAssets(for intent: AssetListIntent) -> [AssetOption]? { return service.defaultAssetOptions() } func provideChartUpColorOptionsCollection(for intent: AssetListIntent, with completion: @escaping (INObjectCollection<ColorOption>?, Error?) -> Void) { service.fetchChartUpColorOptions { result in switch result { case let .success(options): let collection = INObjectCollection( sections: [ INObjectSection(title: S.Widget.colorSectionBasic, items: options.filter { $0.isBasicColor }), INObjectSection(title: S.Widget.colorSectionText, items: options.filter { $0.isBrdTextColor }), INObjectSection(title: S.Widget.colorSectionBackground, items: options.filter { $0.isBrdBackgroundColor }) ] ) completion(collection, nil) case let .failure(error): print("Failed to chart up color options", error) completion(INObjectCollection(items: []), error) } } } func defaultChartUpColor(for intent: AssetListIntent) -> ColorOption? { return service.defaultChartUpOptions() } func provideChartDownColorOptionsCollection(for intent: AssetListIntent, with completion: @escaping (INObjectCollection<ColorOption>?, Error?) -> Void) { service.fetchChartDownColorOptions { result in switch result { case let .success(options): let collection = INObjectCollection( sections: [ INObjectSection(title: S.Widget.colorSectionBasic, items: options.filter { $0.isBasicColor }), INObjectSection(title: S.Widget.colorSectionText, items: options.filter { $0.isBrdTextColor }), INObjectSection(title: S.Widget.colorSectionBackground, items: options.filter { $0.isBrdBackgroundColor }) ] ) completion(collection, nil) case let .failure(error): print("Failed to chart up color options", error) completion(INObjectCollection(items: []), error) } } } func defaultChartDownColor(for intent: AssetListIntent) -> ColorOption? { return service.defaultChartDownOptions() } func provideBackgroundColorOptionsCollection(for intent: AssetListIntent, with completion: @escaping (INObjectCollection<ColorOption>?, Error?) -> Void) { service.fetchBackgroundColorOptions { result in switch result { case let .success(options): let collection = INObjectCollection( sections: [ INObjectSection(title: S.Widget.colorSectionSystem, items: options.filter { $0.isSystem }), INObjectSection(title: S.Widget.colorSectionBackground, items: options.filter { $0.isBrdBackgroundColor }), INObjectSection(title: S.Widget.colorSectionBasic, items: options.filter { $0.isBasicColor }), INObjectSection(title: S.Widget.colorSectionCurrency, items: options.filter { $0.isCurrencyColor }) ] ) completion(collection, nil) case let .failure(error): print("Failed to chart up color options", error) completion(INObjectCollection(items: []), error) } } } func defaultBackgroundColor(for intent: AssetListIntent) -> ColorOption? { return service.defaultBackgroundColor() } func provideTextColorOptionsCollection(for intent: AssetListIntent, with completion: @escaping (INObjectCollection<ColorOption>?, Error?) -> Void) { service.fetchTextColorOptions { result in switch result { case let .success(options): let collection = INObjectCollection( sections: [ INObjectSection(title: S.Widget.colorSectionSystem, items: options.filter { $0.isSystem }), INObjectSection(title: S.Widget.colorSectionText, items: options.filter { $0.isBrdTextColor }), INObjectSection(title: S.Widget.colorSectionBasic, items: options.filter { $0.isBasicColor }), INObjectSection(title: S.Widget.colorSectionBackground, items: options.filter { $0.isBrdBackgroundColor }) ] ) completion(collection, nil) case let .failure(error): print("Failed to chart up color options", error) completion(INObjectCollection(items: []), error) } } } func defaultTextColor(for intent: AssetListIntent) -> ColorOption? { return service.defaultTextColor() } } // MARK: - PortfolioIntentHandling extension IntentHandler: PortfolioIntentHandling { func provideAssetsOptionsCollection(for intent: PortfolioIntent, with completion: @escaping (INObjectCollection<AssetOption>?, Error?) -> Void) { service.fetchAssetOptions { result in switch result { case let .success(options): completion(INObjectCollection(items: options), nil) case let .failure(error): print("Failed to load asset options", error) completion(INObjectCollection(items: []), error) } } } func defaultAssets(for intent: PortfolioIntent) -> [AssetOption]? { return service.defaultAssetOptions() } func provideChartUpColorOptionsCollection(for intent: PortfolioIntent, with completion: @escaping (INObjectCollection<ColorOption>?, Error?) -> Void) { service.fetchChartUpColorOptions { result in switch result { case let .success(options): let collection = INObjectCollection( sections: [ INObjectSection(title: S.Widget.colorSectionBasic, items: options.filter { $0.isBasicColor }), INObjectSection(title: S.Widget.colorSectionText, items: options.filter { $0.isBrdTextColor }), INObjectSection(title: S.Widget.colorSectionBackground, items: options.filter { $0.isBrdBackgroundColor }) ] ) completion(collection, nil) case let .failure(error): print("Failed to chart up color options", error) completion(INObjectCollection(items: []), error) } } } func defaultChartUpColor(for intent: PortfolioIntent) -> ColorOption? { return service.defaultChartUpOptions() } func provideChartDownColorOptionsCollection(for intent: PortfolioIntent, with completion: @escaping (INObjectCollection<ColorOption>?, Error?) -> Void) { service.fetchChartDownColorOptions { result in switch result { case let .success(options): let collection = INObjectCollection( sections: [ INObjectSection(title: S.Widget.colorSectionBasic, items: options.filter { $0.isBasicColor }), INObjectSection(title: S.Widget.colorSectionText, items: options.filter { $0.isBrdTextColor }), INObjectSection(title: S.Widget.colorSectionBackground, items: options.filter { $0.isBrdBackgroundColor }) ] ) completion(collection, nil) case let .failure(error): print("Failed to chart up color options", error) completion(INObjectCollection(items: []), error) } } } func defaultChartDownColor(for intent: PortfolioIntent) -> ColorOption? { return service.defaultChartDownOptions() } func provideBackgroundColorOptionsCollection(for intent: PortfolioIntent, with completion: @escaping (INObjectCollection<ColorOption>?, Error?) -> Void) { service.fetchBackgroundColorOptions { result in switch result { case let .success(options): let collection = INObjectCollection( sections: [ INObjectSection(title: S.Widget.colorSectionSystem, items: options.filter { $0.isSystem }), INObjectSection(title: S.Widget.colorSectionBackground, items: options.filter { $0.isBrdBackgroundColor }), INObjectSection(title: S.Widget.colorSectionBasic, items: options.filter { $0.isBasicColor }), INObjectSection(title: S.Widget.colorSectionCurrency, items: options.filter { $0.isCurrencyColor }) ] ) completion(collection, nil) case let .failure(error): print("Failed to chart up color options", error) completion(INObjectCollection(items: []), error) } } } func defaultBackgroundColor(for intent: PortfolioIntent) -> ColorOption? { return service.defaultBackgroundColor() } func provideTextColorOptionsCollection(for intent: PortfolioIntent, with completion: @escaping (INObjectCollection<ColorOption>?, Error?) -> Void) { service.fetchTextColorOptions { result in switch result { case let .success(options): let collection = INObjectCollection( sections: [ INObjectSection(title: S.Widget.colorSectionSystem, items: options.filter { $0.isSystem }), INObjectSection(title: S.Widget.colorSectionText, items: options.filter { $0.isBrdTextColor }), INObjectSection(title: S.Widget.colorSectionBasic, items: options.filter { $0.isBasicColor }), INObjectSection(title: S.Widget.colorSectionBackground, items: options.filter { $0.isBrdBackgroundColor }) ] ) completion(collection, nil) case let .failure(error): print("Failed to chart up color options", error) completion(INObjectCollection(items: []), error) } } } func defaultTextColor(for intent: PortfolioIntent) -> ColorOption? { return service.defaultTextColor() } }
37e1387dfcfd6f38ea760a2ab28113bb
44.617788
158
0.548611
false
false
false
false
asynchrony/Re-Lax
refs/heads/master
ReLax/ReLax/CoreStructuredImage.swift
mit
1
import UIKit enum CoreStructuredImage { case flattened(imageName: String) case layer(imageName: String, imageSize: CGSize) case layeredImage(imageName: String, imageSize: CGSize) private var pixelFormat: String { switch self { case .flattened(_): return "GEPJ" case .layer(_, _): return "BGRA" case .layeredImage(_, _): return "ATAD" } } private var colorSpaceID: Int { switch self { case .flattened(_), .layeredImage(_, _): return 15 case .layer(_, _): return 1 } } // Type of Rendition private var layout: Int { switch self { case .flattened(_), .layer(_, _): return 10 case .layeredImage(_, _): return 0x03EA } } private var imageSize: CGSize { switch self { case .flattened(_): return .zero case .layer(_, let size): return size case .layeredImage(_, let size): return size } } private var imageName: String { switch self { case .flattened(let name): return name case .layer(let name, _): return name case .layeredImage(let name, _): return name } } func data(structuredInfoDataLength: Int, payloadDataLength: Int) -> Data { let infoListLength = int32Data(structuredInfoDataLength) let bitmapInfoData = bitmapInfo(payloadLength: payloadDataLength) return concatData([renditionHeader(), metaData(), infoListLength, bitmapInfoData]) } private func renditionHeader() -> Data { let ctsi = "ISTC".data(using: .ascii)! let version = int32Data(1) let renditionFlags = int32Data(0) // unused let width = int32Data(Int(imageSize.width)) let height = int32Data(Int(imageSize.height)) let scale = int32Data(100) // 100 = 1x, 200 = 2x let pixelFormat = self.pixelFormat.data(using: .ascii)! let colorSpaceIDData = int32Data(self.colorSpaceID) return concatData([ctsi, version, renditionFlags, width, height, scale, pixelFormat, colorSpaceIDData]) } private func metaData() -> Data { let modifiedDate = int32Data(0) let layout = int32Data(self.layout) let nameData = self.imageName.padded(count: 128) return concatData([modifiedDate, layout, nameData]) } private func bitmapInfo(payloadLength: Int) -> Data { let bitmapCount = int32Data(1) let reserved = int32Data(0) let payloadSize = int32Data(payloadLength) return concatData([bitmapCount, reserved, payloadSize]) } }
61d65d5e4ac26de109e1e3dc2424e142
29.681319
111
0.577006
false
false
false
false
pmtao/SwiftUtilityFramework
refs/heads/master
SwiftUtilityFramework/Foundation/Text/TextReader.swift
mit
1
// // TextReader.swift // SwiftUtilityFramework // // Created by Meler Paine on 2019/1/18. // Copyright © 2019 SinkingSoul. All rights reserved. // import Foundation import Speech public class TextReader { weak var synthesizerDelegate: AVSpeechSynthesizerDelegate? public var syntesizer = AVSpeechSynthesizer() public init(synthesizerDelegate: AVSpeechSynthesizerDelegate) { self.synthesizerDelegate = synthesizerDelegate syntesizer.delegate = synthesizerDelegate } public func readText(_ text: String) { let textLanguage = TextTagger.decideTextLanguage(text) let isEnglishWord = TextTagger.englishWordDetect(text) let voices = AVSpeechSynthesisVoice.speechVoices() let utterance = AVSpeechUtterance(string: text) var zh_voices:[AVSpeechSynthesisVoice] = [] var enGB_voices:[AVSpeechSynthesisVoice] = [] for voice in voices { if voice.language == "en-GB" && voice.name.hasPrefix("Daniel") { enGB_voices.append(voice) } if voice.language.hasPrefix("zh") { zh_voices.append(voice) } } var speechVoice = AVSpeechSynthesisVoice() if isEnglishWord { speechVoice = enGB_voices[0] } if textLanguage.hasPrefix("zh") { speechVoice = zh_voices[0] } utterance.voice = speechVoice utterance.rate = 0.5; syntesizer.speak(utterance) } }
92b7427e5c11ffc81b6587ae731112bf
27.851852
76
0.615533
false
false
false
false
drinkapoint/DrinkPoint-iOS
refs/heads/master
DrinkPoint/DrinkPoint/Games/Plink/PlinkDefined.swift
mit
1
// // PlinkDefined.swift // DrinkPoint // // Created by Paul Kirk Adams on 6/25/16. // Copyright © 2016 Paul Kirk Adams. All rights reserved. // import Foundation import CoreGraphics let DefinedScreenWidth: CGFloat = 1536 let DefinedScreenHeight: CGFloat = 2048 enum GameSceneChildName: String { case FingerName = "Finger" case GlassAName = "GlassA" case GlassBName = "GlassB" case GlassCName = "GlassC" case ScoreName = "Score" case HealthName = "Health" case GameOverLayerName = "GameOver" } enum GameSceneActionKey: String { case WalkAction = "walk" case GrowAudioAction = "grow_audio" case GrowAction = "grow" case ScaleAction = "scale" } enum GameSceneEffectAudioName: String { case GlassBulletAudioName = "GlassBullet.wav" case GlassHitAudioName = "GlassHit.wav" case FingerBulletAudioName = "FingerBullet.wav" case FingerHitAudioName = "FingerHit.wav" } enum GameSceneZposition: CGFloat { case BackgroundZposition = 0 case FingerZposition = 10 case GlassAZposition = 20 case GlassBZposition = 30 case GlassCZposition = 40 }
9f9fd6794d60df58510ae3381ce9910e
26.888889
58
0.637959
false
false
false
false
steelwheels/KiwiComponents
refs/heads/master
UnitTest/OSX/ConsoleWindow/AppDelegate.swift
lgpl-2.1
1
/** * @file AppDelegate.swift * @brief Define Appdelegate class * @par Copyright * Copyright (C) 2017 Steel Wheels Project */ import KiwiComponents import Canary import Cocoa @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { private var mMainWindow: NSWindowController? = nil func applicationWillFinishLaunching(_ notification: Notification) { let app = KMApplication.shared /* Open console window to get console */ app.openConsoleWindow() /* Open main window */ let console = app.console mMainWindow = KMLoadWindow(ambFile: "main_window", console: console) if let mwindow = mMainWindow { mwindow.showWindow(nil) } } func applicationDidFinishLaunching(_ aNotification: Notification) { /* Open console window to get console */ //KMApplication.shared.openConsoleWindow() } func applicationWillTerminate(_ aNotification: Notification) { } }
a8de3a460ca45c8400e851c6e2b12122
20.761905
70
0.7407
false
false
false
false
allbto/Swiftility
refs/heads/master
Swiftility/Sources/Core/GCD.swift
mit
2
// // GCD.swift // Swiftility // // Created by Allan Barbato on 10/23/15. // Copyright © 2015 Allan Barbato. All rights reserved. // import Foundation public typealias DispatchClosure = () -> Void // TODO: Tests // MARK: - Async /// Convenience call to dispatch_async public func async(queue: DispatchQueue = .global(qos: .background), execute closure: @escaping DispatchClosure) { queue.async(execute: closure) } /// Convenience call to async(queue: .main) public func async_main(_ closure: @escaping DispatchClosure) { async(queue: .main, execute: closure) } // MARK: - After / Delay /// Convenience call to dispatch_after (time is in seconds) public func after(_ delay: TimeInterval, queue: DispatchQueue = .main, execute closure: @escaping DispatchClosure) { queue.asyncAfter( deadline: .now() + delay, execute: closure ) } /// Same as after public func delay(_ delay: TimeInterval, queue: DispatchQueue = .main, execute closure: @escaping DispatchClosure) { after(delay, queue: queue, execute: closure) } // MARK: - Once fileprivate extension DispatchQueue { static var _onceTracker = [String]() } /** Executes a block of code, associated with a unique token, only once. The code is thread safe and will only execute the code once even in the presence of multithreaded calls. - parameter token: A unique reverse DNS style name such as com.vectorform.<name> or a GUID - parameter execute: Closure to execute once */ public func once(token: String, execute closure: DispatchClosure) { objc_sync_enter(DispatchQueue.self); defer { objc_sync_exit(DispatchQueue.self) } if DispatchQueue._onceTracker.contains(token) { return } DispatchQueue._onceTracker.append(token) closure() } // MARK: - Debounce /** Debounce will fire method when delay passed, but if there was request before that, then it invalidates the previous method and uses only the last - parameter delay: delay before each debounce - parameter queue: =.main; Queue to fire to - parameter action: closure called when debouncing - returns: closure to call to fire the debouncing */ public func debounce<T>(_ delay: TimeInterval, queue: DispatchQueue = .main, action: @escaping (T) -> Void) -> (T) -> Void { var lastCall: Int = 0 return { t in // Increase call counter and invalidate the call if it is not the last one lastCall += 1 let currentCall = lastCall queue.asyncAfter( deadline: .now() + delay, execute: { if lastCall == currentCall { action(t) } } ) } }
de040082fcb8610192494d6b5e66d9c3
25.411765
146
0.667038
false
false
false
false
raptorxcz/Rubicon
refs/heads/main
Generator/Generator/TearDownInteractor.swift
mit
1
// // TearDownInteractor.swift // Generator // // Created by Kryštof Matěj on 19.05.2022. // Copyright © 2022 Kryštof Matěj. All rights reserved. // import SwiftSyntax import SwiftSyntaxBuilder import SwiftSyntaxParser public final class TearDownInteractor { private let nilableVariablesParser: NilableVariablesParser public init(nilableVariablesParser: NilableVariablesParser) { self.nilableVariablesParser = nilableVariablesParser } public func execute(text: String, spacing: Int) throws -> String { let file = try SyntaxParser.parse(source: text) let classRewriter = ClassRewriter( nilableVariablesParser: nilableVariablesParser, spacing: spacing ) return classRewriter.visit(file.root).description } } private class ClassRewriter: SyntaxRewriter { private let nilableVariablesParser: NilableVariablesParser private let spacing: Int init(nilableVariablesParser: NilableVariablesParser, spacing: Int) { self.nilableVariablesParser = nilableVariablesParser self.spacing = spacing } override func visit(_ node: ClassDeclSyntax) -> DeclSyntax { guard isRelevantClass(node: node) else { return super.visit(node) } var node = node if let index = firstIndex(node: node, methodName: "tearDown") { let newMembers = node.members.members.removing(childAt: index) node.members = node.members.withMembers(newMembers) } let nilableVariables = nilableVariablesParser.parse(from: node) let tearDownMethod = makeTearDownMethod(variables: nilableVariables) if let index = firstIndex(node: node, methodName: "setUp") { let newMembers = node.members.members.inserting(tearDownMethod, at: index + 1) node.members = node.members.withMembers(newMembers) } else if let index = firstIndex(node: node, methodName: "setUpWithError") { let newMembers = node.members.members.inserting(tearDownMethod, at: index + 1) node.members = node.members.withMembers(newMembers) } else { node.members = node.members.addMember(tearDownMethod) } return super.visit(node) } private func isRelevantClass(node: ClassDeclSyntax) -> Bool { guard node.identifier.text.hasSuffix("Tests") else { return false } guard firstIndex(node: node, methodName: "tearDownWithError") == nil else { return false } return true } private func makeTearDownMethod(variables: [String]) -> MemberDeclListItemSyntax { var modifiers = SyntaxFactory.makeModifierList([ SyntaxFactory.makeDeclModifier(name: .identifier("override"), detailLeftParen: nil, detail: nil, detailRightParen: nil), ]) modifiers.trailingTrivia = .spaces(1) let leftBrace = SyntaxFactory.makeLeftBraceToken(leadingTrivia: .spaces(1)) let rightBrace = SyntaxFactory.makeRightBraceToken(leadingTrivia: Trivia(pieces: [.newlines(1), .spaces(spacing)])) let input = SyntaxFactory.makeParameterClause( leftParen: .leftParen, parameterList: SyntaxFactory.makeFunctionParameterList([]), rightParen: .rightParen ) let signature = SyntaxFactory.makeFunctionSignature(input: input, asyncOrReasyncKeyword: nil, throwsOrRethrowsKeyword: nil, output: nil) var function = SyntaxFactory.makeFunctionDecl( attributes: nil, modifiers: modifiers, funcKeyword: .func, identifier: .identifier("tearDown"), genericParameterClause: nil, signature: signature, genericWhereClause: nil, body: SyntaxFactory.makeCodeBlock( leftBrace: leftBrace, statements: SyntaxFactory.makeCodeBlockItemList([makeSuperRow()] + variables.map(makeRow)), rightBrace: rightBrace ) ) function.leadingTrivia = Trivia(pieces: [.newlines(2), .spaces(spacing)]) return SyntaxFactory.makeMemberDeclListItem( decl: DeclSyntax(function), semicolon: nil ) } private func makeSuperRow() -> CodeBlockItemSyntax { var superExpression = SyntaxFactory.makeSuperRefExpr(superKeyword: .super) superExpression.trailingTrivia = nil var memberExpression = SyntaxFactory.makeMemberAccessExpr(base: ExprSyntax(superExpression), dot: .period, name: .identifier("tearDown"), declNameArguments: nil) memberExpression.leadingTrivia = Trivia(pieces: [.newlines(1), .spaces(2 * spacing)]) let syntax = SyntaxFactory.makeFunctionCallExpr( calledExpression: ExprSyntax(memberExpression), leftParen: .leftParen, argumentList: SyntaxFactory.makeTupleExprElementList([]), rightParen: .rightParen, trailingClosure: nil, additionalTrailingClosures: nil ) return SyntaxFactory.makeCodeBlockItem( item: Syntax(syntax), semicolon: nil, errorTokens: nil ) } private func makeRow(variable: String) -> CodeBlockItemSyntax { let variableSyntax = SyntaxFactory.makeIdentifierExpr(identifier: SyntaxFactory.makeIdentifier(variable, leadingTrivia: Trivia(pieces: [.newlines(1), .spaces(2 * spacing)])), declNameArguments: nil) var assignmentSyntax = SyntaxFactory.makeAssignmentExpr(assignToken: .equal) assignmentSyntax.trailingTrivia = .spaces(1) var nilSyntax = SyntaxFactory.makeNilLiteralExpr(nilKeyword: .nil) nilSyntax.trailingTrivia = nil let syntax = SyntaxFactory.makeSequenceExpr( elements: SyntaxFactory.makeExprList([ ExprSyntax(variableSyntax), ExprSyntax(assignmentSyntax), ExprSyntax(nilSyntax), ]) ) return SyntaxFactory.makeCodeBlockItem( item: Syntax(syntax), semicolon: nil, errorTokens: nil ) } private func firstIndex(node: ClassDeclSyntax, methodName: String) -> Int? { if let (index, _) = node.members.members.enumerated().first(where: { isMethod($1, name: methodName) }) { return index } else { return nil } } private func isMethod(_ member: MemberDeclListItemSyntax, name: String) -> Bool { guard let function = member.decl.as(FunctionDeclSyntax.self) else { return false } if function.modifiers?.contains(where: { $0.name.text == "static" }) == true { return false } return function.identifier.text == name } }
db67f6dff5314340877de0b6e9e4f636
38.55814
206
0.65241
false
false
false
false
theMatys/myWatch
refs/heads/master
myWatch/Source/Core/Device/MWDevice.swift
gpl-3.0
1
// // MWDevice.swift // myWatch // // Created by Máté on 2017. 04. 12.. // Copyright © 2017. theMatys. All rights reserved. // import CoreBluetooth /// Represents the myWatch device that the application uses. /// /// Step/sleep data are held in this object as well as the given name, device ID and the peripheral repsresenting this device. /// /// Encoded to a file when the app is about to terminate to presist data for the device. @objc class MWDevice: NSObject, NSCoding { //MARK: Instance variables /// The name of the device given by the user. var name: String /// The device's ID which is used to identify the device after first launch. var identifier: String /// The Bluetooth peripheral representing this device. var peripheral: CBPeripheral? //MARK: - Inherited initializers from: NSCoding required convenience init?(coder aDecoder: NSCoder) { let name: String = aDecoder.decodeObject(forKey: PropertyKey.name) as? String ?? "" let identifier: String = aDecoder.decodeObject(forKey: PropertyKey.identifier) as? String ?? "" self.init(name: name, identifier: identifier) } //MARK: Initializers /// Makes an `MWDevice` object. /// /// Can be called programatically by any class or by `init(coder:)` to initialize. /// /// - Parameters: /// - name: The name of this device given by the user. /// - identifier: The ID used to identify this device for later use. /// - peripheral: The Bluetooth peripheral representing this device object. /// /// - Returns: An `MWDevice` object. init(name: String = "", identifier: String = "", peripheral: CBPeripheral? = nil) { self.name = name self.identifier = identifier self.peripheral = peripheral } //MARK: Inherited functions from: NSCoding func encode(with aCoder: NSCoder) { aCoder.encode(name, forKey: PropertyKey.name) aCoder.encode(identifier, forKey: PropertyKey.identifier) } //MARK: - /// The structure which holds the property names used in the files to identify the properties of this object. private struct PropertyKey { //MARK: Prefixes /// The prefix of the property keys. private static let prefix: String = "MWDevice" //MARK: Property keys static let name: String = prefix + "Name" static let identifier: String = prefix + "Identifier" } }
20dffefcf80ade92a7dce61248ebd1fd
31.487179
126
0.641673
false
false
false
false
guojiubo/PlainReader
refs/heads/master
PlainReader/StarredArticlesViewController.swift
mit
1
// // PRStarredArticlesViewController.swift // PlainReader // // Created by guo on 11/12/14. // Copyright (c) 2014 guojiubo. All rights reserved. // import UIKit class StarredArticlesViewController: PRPullToRefreshViewController, UITableViewDataSource, UITableViewDelegate { @IBOutlet var tableView: UITableView! var articles = PRDatabase.shared().starredArticles() as! [PRArticle] override func viewDidLoad() { super.viewDidLoad() self.refreshHeader.title = "收藏" let menuView = UIView(frame: CGRect(x: 0, y: 0, width: 60, height: 44)) let menuButton = PRAutoHamburgerButton(frame: CGRect(x: 0, y: 0, width: 30, height: 30)) menuButton.addTarget(self, action: #selector(StarredArticlesViewController.menuAction(_:)), for: .touchUpInside) menuButton.center = menuView.center menuView.addSubview(menuButton) self.refreshHeader.leftView = menuView let nc = NotificationCenter.default nc.addObserver(self, selector: #selector(StarredArticlesViewController.handleStarActionNotification(_:)), name: NSNotification.Name.ArticleViewControllerStarred, object: nil) } func handleStarActionNotification(_ n: Notification) { self.tableView.reloadData() } func menuAction(_ sender: PRAutoHamburgerButton) { self.sideMenuViewController.presentLeftMenuViewController() } override func scrollView() -> UIScrollView! { return self.tableView } override func useRefreshHeader() -> Bool { return true } override func useLoadMoreFooter() -> Bool { return false } override func refreshTriggered() { super.refreshTriggered() articles = PRDatabase.shared().starredArticles() as! [PRArticle] self.tableView.reloadSections(IndexSet(integer: 0), with: .automatic) DispatchQueue.main.async(execute: { [weak self] () -> Void in if let weakSelf = self { weakSelf.refreshCompleted() } }) } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.articles.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cellIdentifier = "ArticleCell" var cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier) as? PRArticleCell if cell == nil { cell = Bundle.main.loadNibNamed("PRArticleCell", owner: self, options: nil)?.first as? PRArticleCell } cell!.article = self.articles[(indexPath as NSIndexPath).row] return cell! } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) let article = self.articles[(indexPath as NSIndexPath).row] let vc = PRArticleViewController.cw_loadFromNibUsingClassName() vc?.articleId = article.articleId; self.stackController.pushViewController(vc, animated: true) } }
d06c32b480606c2d97caa865411bb102
35.418605
182
0.666986
false
false
false
false
ivlevAstef/DITranquillity
refs/heads/master
Sources/Core/Internal/FrameworksDependenciesContainer.swift
mit
1
// // FrameworksDependenciesContainer.swift // DITranquillity // // Created by Alexander Ivlev on 06/06/2017. // Copyright © 2017 Alexander Ivlev. All rights reserved. // final class FrameworksDependenciesContainer { private var imports = [FrameworkWrapper: Set<FrameworkWrapper>]() private var mutex = PThreadMutex(normal: ()) final func dependency(framework: DIFramework.Type, import importFramework: DIFramework.Type) { let frameworkWrapper = FrameworkWrapper(framework: framework) let importFrameworkWrapper = FrameworkWrapper(framework: importFramework) mutex.sync { if nil == imports[frameworkWrapper]?.insert(importFrameworkWrapper) { imports[frameworkWrapper] = [importFrameworkWrapper] } } } func filterByChilds(for framework: DIFramework.Type, components: Components) -> Components { let frameworkWrapper = FrameworkWrapper(framework: framework) let childs = mutex.sync { return imports[frameworkWrapper] ?? [] } return components.filter { $0.framework.map { childs.contains(FrameworkWrapper(framework: $0)) } ?? false } } } private class FrameworkWrapper: Hashable { let framework: DIFramework.Type private let identifier: ObjectIdentifier init(framework: DIFramework.Type) { self.framework = framework self.identifier = ObjectIdentifier(framework) } #if swift(>=5.0) func hash(into hasher: inout Hasher) { hasher.combine(identifier) } #else var hashValue: Int { return identifier.hashValue } #endif static func ==(lhs: FrameworkWrapper, rhs: FrameworkWrapper) -> Bool { return lhs.identifier == rhs.identifier } }
05d3924985796792ea49a772659b2b0d
29.109091
111
0.722826
false
false
false
false
ontouchstart/swift3-playground
refs/heads/playgroundbook
Learn to Code 1.playgroundbook/Contents/Chapters/Document8.playgroundchapter/Pages/Exercise4.playgroundpage/Sources/Assessments.swift
mit
1
// // Assessments.swift // // Copyright (c) 2016 Apple Inc. All Rights Reserved. // let solution = "```swift\nwhile !isOnGem {\n while !isOnClosedSwitch && !isOnGem {\n moveForward()\n }\n if isOnClosedSwitch && isBlocked {\n toggleSwitch()\n turnLeft()\n } else if isOnClosedSwitch {\n toggleSwitch()\n turnRight()\n }\n}\ncollectGem()\n" import PlaygroundSupport public func assessmentPoint() -> AssessmentResults { pageIdentifier = "Which_Way_To_Turn?" let success = "### Brilliant! \nNow you're creating your own algorithms from scratch. How cool is that? \n\n[**Next Page**](@next)" var hints = [ "Each time Byte reaches a switch, you need to decide whether to turn left or right.", "Be sure to run your algorithm until Byte reaches the gem at the end of the puzzle.", "Remember to use the && operator to check multiple conditions with a single `if` statement." ] switch currentPageRunCount { case 2..<4: hints[0] = "You can use nested `while` loops in this puzzle. Make the *outer* loop run while Byte isn’t on a gem. Make the *inner* loop move Byte forward until reaching the next switch." case 4..<6: hints[0] = "Your algorithm should turn Byte to the left if on a switch and blocked, and to the right if just on a switch but not blocked." case 5..<9: hints[0] = "Trying a lot of different approaches is the best way to find one that works. Sometimes the people who fail the most in the beginning are those who end up succeeding in the end." default: break } return updateAssessment(successMessage: success, failureHints: hints, solution: solution) }
bbc053f9e3527ccae35b750e1f6fad52
45.605263
305
0.648786
false
false
false
false
amberstar/Component
refs/heads/master
ComponentKit/operators/Time.swift
mit
2
// // Component: Time.swift // Copyright © 2016 SIMPLETOUCH LLC, All rights reserved. // import Foundation public struct Runtime : OperatorProtocol { private typealias TimeProcess = (TimeInterval, CFAbsoluteTime, CFAbsoluteTime) -> (CFAbsoluteTime, TimeInterval) private final class TimeProcessor { static var firstProcess: TimeProcess = { time, timestamp, _ in return (timestamp, time) } static var normalProcess: TimeProcess = { time, timestamp, previousTimestamp in return (timestamp, time + (timestamp - previousTimestamp)) } lazy var switchingProcess: TimeProcess = { return { time, timestamp, previousTimestamp in self._process = normalProcess return TimeProcessor.firstProcess(time, timestamp, previousTimestamp) }}() lazy var _process: TimeProcess = { return self.switchingProcess }() func process(time: TimeInterval, timestamp: CFAbsoluteTime, previousTimestamp: CFAbsoluteTime) -> (CFAbsoluteTime, TimeInterval) { return _process(time, timestamp, previousTimestamp) } } public private(set) var time: (timestamp: CFAbsoluteTime, time: TimeInterval) private var processor = TimeProcessor() public mutating func input(_ timestamp: CFAbsoluteTime) -> TimeInterval? { time = processor.process(time: time.time, timestamp: timestamp, previousTimestamp: time.timestamp) return time.time } /// Creates an instance with the specified timestamp and uptime in seconds. public init(timestamp: CFAbsoluteTime? = nil, uptime: TimeInterval = 0 ) { self.time = (timestamp: timestamp ?? CFAbsoluteTimeGetCurrent(), time: uptime) } } /// An operator that produces the current absolute time in seconds public struct Timestamp : OperatorProtocol { public mutating func input(_ : Void) -> CFTimeInterval? { return CFAbsoluteTimeGetCurrent() } public init() {} } public struct TimeKeeper { private var op : Operator<(), Double> public private(set) var time: TimeInterval = 0 public mutating func start() { time = op.input()! } public mutating func update() -> TimeInterval { return op.input()! } public mutating func reset() { op = Timestamp().compose(Runtime()) time = 0 } public init(time: TimeInterval = 0) { op = Timestamp().compose(Runtime(timestamp: time)) } }
8be76100cdf1220aea20b2000b242470
32.324324
138
0.667883
false
false
false
false
juancruzmdq/NLService
refs/heads/master
NLService/Classes/NLRemoteRequest.swift
mit
1
// // RemoteRequest.swift // //Copyright (c) 2016 Juan Cruz Ghigliani <[email protected]> www.juancruzmdq.com.ar // //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. //////////////////////////////////////////////////////////////////////////////// // MARK: Imports import Foundation public enum RemoteRequestResult<T> { case Success(T) case Error(NSError) } /** * Class that handle a request to a RemoteResource in a RemoteService */ public class NLRemoteRequest<T>{ //////////////////////////////////////////////////////////////////////////////// // MARK: Types public typealias CompleteBlock = (RemoteRequestResult<T>)->Void //////////////////////////////////////////////////////////////////////////////// // MARK: Public Properties public var resource:NLRemoteResource<T> public var manager:NLManagerProtocol public var params:[String:String] public var HTTPMethod:NLMethod = .GET public var service:NLRemoteService //////////////////////////////////////////////////////////////////////////////// // MARK: Setup & Teardown internal init(resource:NLRemoteResource<T>, service:NLRemoteService, manager:NLManagerProtocol){ self.service = service self.resource = resource self.manager = manager self.params = [:] } //////////////////////////////////////////////////////////////////////////////// // MARK: public Methods public func addParam(key:String,value:String) -> NLRemoteRequest<T>{ self.params[key] = value return self } public func addParams(values:[String:String]) -> NLRemoteRequest<T>{ for(k,v) in values{ self.params[k] = v } return self } public func HTTPMethod(method:NLMethod) -> NLRemoteRequest<T> { self.HTTPMethod = method return self } public func fullURLString() -> String{ return self.fullURL().absoluteString } public func fullURL() -> NSURL{ return self.service.baseURL.URLByAppendingPathComponent(self.resource.path) } /** Use manager to build the request to the remote service, and handle response - parameter onComplete: block to be call after handle response */ public func load(onComplete:CompleteBlock){ preconditionFailure("This method must be overridden - HEEEEELPPPPPPPPP I DON'T KNOW WHAT TO DO") } func handleError(error:NSError?,onComplete:CompleteBlock){ if let error:NSError = error{ onComplete(.Error(error)) }else{ onComplete(.Error(NSError(domain: "RemoteService", code: 5003, localizedDescription:"Empty Response"))) } } }
57d060f3466fe8d768c9abd0c0c54181
35.048077
115
0.614995
false
false
false
false
spweau/Test_DYZB
refs/heads/master
Test_DYZB/Test_DYZB/Classes/Main/View/CollectionBaseCell.swift
mit
1
// // CollectionBaseCell.swift // Test_DYZB // // Created by Spweau on 2017/2/24. // Copyright © 2017年 sp. All rights reserved. // import UIKit class CollectionBaseCell: UICollectionViewCell { @IBOutlet weak var iconImageView: UIImageView! @IBOutlet weak var onlineBtn: UIButton! @IBOutlet weak var nickNameLabel: UILabel! // 定义模型属性 var anchor : AnchorModel? { didSet { // 0.校验模型是否有值 guard let anchor = anchor else { return } // 1.取出在线人数显示的文字 var onlineStr : String = "" if anchor.online >= 10000 { onlineStr = "\(Int(anchor.online / 10000))万在线" } else { onlineStr = "\(anchor.online)在线" } onlineBtn.setTitle(onlineStr, for: .normal) // 2.昵称的显示 nickNameLabel.text = anchor.nickname // 4. 封面 guard let iconURL = URL(string: anchor.vertical_src) else { return } iconImageView.kf.setImage(with: iconURL) } } }
213e521c6fd3a35b5a46ea1557c6f705
23.888889
80
0.524107
false
false
false
false
Kinglioney/DouYuTV
refs/heads/master
DouYuTV/DouYuTV/Classes/Tools/Extension/UIBarButtonItem-Extension.swift
mit
1
// // UIBarButtonItem-Extension.swift // DouYuTV // // Created by apple on 2017/7/17. // Copyright © 2017年 apple. All rights reserved. // import UIKit extension UIBarButtonItem{ /* 类方法扩展 class func createItem(imageName : String, highImageName : String, size : CGSize) -> UIBarButtonItem { let btn = UIButton() btn.setImage(UIImage(named:imageName), for: .normal) btn.setImage(UIImage(named:highImageName), for: .highlighted) btn.frame = CGRect(origin: CGPoint(x:0, y:0), size: size) return UIBarButtonItem(customView: btn) } */ //Swift中推荐使用构造函数 //便利构造函数:1>convenience开头 2>在构造函数中必须明确调用一个设计的构造函数(self) convenience init(imageName : String, highImageName : String = "", size : CGSize = CGSize.zero){ let btn = UIButton() btn.setImage(UIImage(named:imageName), for: .normal) if highImageName != ""{ btn.setImage(UIImage(named:highImageName), for: .highlighted) } if size == CGSize.zero{ btn.sizeToFit() }else{ btn.frame = CGRect(origin: CGPoint.zero, size: size) } self.init(customView: btn) } }
5c40bb73dc463e12bf2ecf483cf94c05
27.658537
105
0.622979
false
false
false
false
donnywdavis/Word-Jive
refs/heads/master
WordJive/WordJive/BackEndRequests.swift
cc0-1.0
1
// // BackEndRequests.swift // WordJive // // Created by Nick Perkins on 5/17/16. // Copyright © 2016 Donny Davis. All rights reserved. // import Foundation protocol CapabilitiesDelegate: class { func availableCapabilities(data: [[String: String]]) } protocol PuzzleDelegate: class { func puzzleData(data: NSData) } enum BackEndURLs : String { case Capabilities = "https://floating-taiga-20677.herokuapp.com/capabilities" case Puzzle = "https://floating-taiga-20677.herokuapp.com/puzzle" } class BackEndRequests : AnyObject { weak static var delegate: CapabilitiesDelegate? weak static var puzzleDelegate: PuzzleDelegate? class func getCapabilities() { startSession(BackEndURLs.Capabilities, gameOptions: nil) } class func getPuzzle(gameOptions: [String: AnyObject]) { startSession(BackEndURLs.Puzzle, gameOptions: gameOptions) } private class func startSession(urlString: BackEndURLs, gameOptions: [String: AnyObject]?) { let url = NSURL(string: urlString.rawValue) let urlRequest = NSMutableURLRequest(URL: url!) let session = NSURLSession.sharedSession() if urlString == .Puzzle { if let gameOptions = gameOptions { do { urlRequest.HTTPBody = try NSJSONSerialization.dataWithJSONObject(gameOptions, options: .PrettyPrinted) } catch { urlRequest.HTTPBody = NSData() } } urlRequest.HTTPMethod = "POST" urlRequest.addValue("application/json", forHTTPHeaderField: "Content-Type") urlRequest.addValue("application/json", forHTTPHeaderField: "Accept") } let task = session.dataTaskWithRequest(urlRequest) { (data, response, error) -> Void in let httpResponse = response as! NSHTTPURLResponse let statusCode = httpResponse.statusCode let urlValue = httpResponse.URL?.absoluteString if (statusCode == 200) { parseData(data!, urlString: urlValue!) } else { print("We did not get a response back. Not good. Status code: \(statusCode).") } } task.resume() } private class func parseData(data: NSData, urlString: String) { switch urlString { case BackEndURLs.Capabilities.rawValue: do { let parsedData = try NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments) as? [[String: String]] delegate?.availableCapabilities(parsedData!) } catch { print("Uh oh!") } case BackEndURLs.Puzzle.rawValue: puzzleDelegate?.puzzleData(data) // do { //// let parsedData = try NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments) as? [String: AnyObject] // puzzleDelegate?.puzzleData(data) // } catch { // print("Uh oh!") // } default: break } } }
ce72728c2807b2407bc59fcb5ad6e3bd
31.24
135
0.586538
false
false
false
false
wmcginty/Shifty
refs/heads/main
Examples/Shifty-iOSExample/Animators/ContinuityTransitionAnimator.swift
mit
1
// // SimpleShiftAnimator.swift // Shifty // // Created by William McGinty on 7/6/16. // Copyright © 2016 Will McGinty. All rights reserved. // import UIKit import Shifty /** An example UIViewControllerAnimatedTransitioning object designed to make movement between similar screens seamless, appearing as a single screen. This animator functions in many scenarios, but functions best with view controllers with similar backgrounds. */ class ContinuityTransitionAnimator: NSObject, UIViewControllerAnimatedTransitioning { // MARK: - UIViewControllerAnimatedTransitioning func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return 0.3 } func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { /** Begin by ensuring the transitionContext is configured correctly, and that our source + destination can power the transition. This being a basic example - exit if this fails, no fallbacks. YMMV with more complicated examples. */ let container = transitionContext.containerView guard let sourceController = transitionContext.viewController(forKey: .from), let destinationController = transitionContext.viewController(forKey: .to) else { return } //Next, add and position the destinationView ABOVE the sourceView container.addSubview(destinationController.view) destinationController.view.frame = transitionContext.finalFrame(for: destinationController) /** Next, we will create a source animator, and instruct it to animate. This will gather all the subviews of `source` with associated `actions` and animate them simultaneously using the options specified to the animator. As soon as the source's actions have completed, the transition can finish. */ let sourceAnimator = ActionAnimator(timingProvider: CubicTimingProvider(duration: transitionDuration(using: transitionContext), curve: .easeIn)) sourceAnimator.animateActions(from: sourceController.view, in: container) { position in transitionContext.completeTransition(position == .end) } let destinationAnimator = sourceAnimator.inverted() destinationAnimator.animateActions(from: destinationController.view, in: container) } }
da6b646fd2b697059aac80a5d6d927a9
54.372093
175
0.746325
false
false
false
false
ethan605/SwiftVD
refs/heads/master
swiftvd/swiftvd/viewcontrollers/TopicCell.swift
mit
1
// // TopicCell.swift // swiftvd // // Created by Ethan Nguyen on 6/8/14. // Copyright (c) 2014 Volcano. All rights reserved. // import UIKit struct SingletonTopicCell { static var sharedInstance: TopicCell? = nil static var token: dispatch_once_t = 0 } class TopicCell: UITableViewCell { @IBOutlet var lblTitle : UILabel = nil @IBOutlet var imgFirstImage : UIImageView = nil class func heightToFit() -> Float { return 320 } class func cellIdentifier() -> String { return "TopicCell" } class func sharedCell() -> TopicCell { dispatch_once(&SingletonTopicCell.token, { SingletonTopicCell.sharedInstance = TopicCell() }) return SingletonTopicCell.sharedInstance! } func reloadCellWithData(topicData: MTopic) { lblTitle.text = topicData.title var sizeThatFits = lblTitle.sizeThatFits(CGSizeMake(lblTitle.frame.size.width, Float(Int32.max))) lblTitle.frame.size.height = sizeThatFits.height lblTitle.superview.frame.size.height = lblTitle.frame.origin.y*2 + lblTitle.frame.size.height var coverPhoto = topicData.coverPhoto! imgFirstImage.setImageWithURL(NSURL(string: coverPhoto.photoURL)) } }
61ef1f7527c57c179bca6c966fa076e1
24.1875
101
0.701406
false
false
false
false
shalex9154/XCGLogger-Firebase
refs/heads/master
XCGLogger+Firebase/AppDelegate.swift
mit
1
// // AppDelegate.swift // XCGLogger+Firebase // // Created by Oleksii Shvachenko on 9/27/17. // Copyright © 2017 oleksii. All rights reserved. // import UIKit import XCGLogger let log = XCGLogger.default extension Tag { static let sensitive = Tag("sensitive") static let ui = Tag("ui") static let data = Tag("data") } extension Dev { static let dave = Dev("dave") static let sabby = Dev("sabby") } @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { let settingsPath = Bundle.main.path(forResource: "FirebaseSetting", ofType: "plist")! let encryptionParams = FirebaseDestination.EncryptionParams(key: "w6xXnb4FwvQEeF1R", iv: "0123456789012345") let destination = FirebaseDestination(firebaseSettingsPath: settingsPath, encryptionParams: encryptionParams)! log.add(destination: destination) log.debug(["Device": "iPhone", "Version": 7]) log.error("omg!") log.severe("omg_2!") log.info("omg_3!") let tags = XCGLogger.Constants.userInfoKeyTags log.error("some error with tag", userInfo: [tags: "iPhone X"]) log.debug("some error with tag", userInfo: [tags: ["iPhone X", "iPhone 8"]]) log.debug("A tagged log message", userInfo: Dev.dave | Tag.sensitive) return true } }
c872cfd31e42622e32fd5043c8a36a1c
30.173913
142
0.712692
false
false
false
false
stripe/stripe-ios
refs/heads/master
StripePaymentSheet/StripePaymentSheet/PaymentSheet/BottomSheet/BottomSheetPresentationAnimator.swift
mit
1
// // BottomSheetPresentationAnimator.swift // StripePaymentSheet // // Copyright © 2022 Stripe, Inc. All rights reserved. // import UIKit /// Handles the animation of the presentedViewController as it is presented or dismissed. /// /// This is a vertical animation that /// - Animates up from the bottom of the screen /// - Dismisses from the top to the bottom of the screen @objc(STPBottomSheetPresentationAnimator) class BottomSheetPresentationAnimator: NSObject { enum TransitionStyle { case presentation case dismissal } private let transitionStyle: TransitionStyle required init(transitionStyle: TransitionStyle) { self.transitionStyle = transitionStyle super.init() } private func animatePresentation(transitionContext: UIViewControllerContextTransitioning) { guard let toVC = transitionContext.viewController(forKey: .to), let fromVC = transitionContext.viewController(forKey: .from) else { return } // Calls viewWillAppear and viewWillDisappear fromVC.beginAppearanceTransition(false, animated: true) transitionContext.containerView.layoutIfNeeded() // Move presented view offscreen (from the bottom) toVC.view.frame = transitionContext.finalFrame(for: toVC) toVC.view.frame.origin.y = transitionContext.containerView.frame.height Self.animate({ transitionContext.containerView.setNeedsLayout() transitionContext.containerView.layoutIfNeeded() }) { didComplete in // Calls viewDidAppear and viewDidDisappear fromVC.endAppearanceTransition() transitionContext.completeTransition(didComplete) } } private func animateDismissal(transitionContext: UIViewControllerContextTransitioning) { guard let toVC = transitionContext.viewController(forKey: .to), let fromVC = transitionContext.viewController(forKey: .from) else { return } // Calls viewWillAppear and viewWillDisappear toVC.beginAppearanceTransition(true, animated: true) Self.animate({ fromVC.view.frame.origin.y = transitionContext.containerView.frame.height }) { didComplete in fromVC.view.removeFromSuperview() // Calls viewDidAppear and viewDidDisappear toVC.endAppearanceTransition() transitionContext.completeTransition(didComplete) } } static func animate( _ animations: @escaping () -> Void, _ completion: ((Bool) -> Void)? = nil ) { let params = UISpringTimingParameters() let animator = UIViewPropertyAnimator(duration: 0, timingParameters: params) animator.addAnimations(animations) if let completion = completion { animator.addCompletion { (_) in completion(true) } } animator.startAnimation() } } // MARK: - UIViewControllerAnimatedTransitioning Delegate extension BottomSheetPresentationAnimator: UIViewControllerAnimatedTransitioning { func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { // TODO This should depend on height so that velocity is constant return 0.5 } func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { switch transitionStyle { case .presentation: animatePresentation(transitionContext: transitionContext) case .dismissal: animateDismissal(transitionContext: transitionContext) } } }
26dcdbf1ff86464ad4e0b502f4d6bbc6
34.046729
95
0.6704
false
false
false
false
yomajkel/RingGraph
refs/heads/master
RingGraph/RingGraph/AnimationHelpers.swift
mit
1
// // AnimationHelper.swift // RingMeter // // Created by Michał Kreft on 13/04/15. // Copyright (c) 2015 Michał Kreft. All rights reserved. // import Foundation internal struct AnimationState { let totalDuration: TimeInterval var currentTime: TimeInterval = 0.0 init(totalDuration: TimeInterval) { self.totalDuration = totalDuration } init(totalDuration: TimeInterval, progress: Float) { self.totalDuration = totalDuration self.currentTime = totalDuration * TimeInterval(progress) } func progress() -> Float { return currentTime >= totalDuration ? 1.0 : Float(currentTime / totalDuration) } mutating func incrementDuration(delta: TimeInterval) { currentTime += delta } } internal struct RangeAnimationHelper { let animationStart: Float let animationEnd: Float init(animationStart: Float = 0.0, animationEnd: Float = 1.0) { self.animationStart = animationStart self.animationEnd = animationEnd } func normalizedProgress(_ absoluteProgress: Float) -> Float { var normalizedProgress: Float = 0.0 switch absoluteProgress { case _ where absoluteProgress < animationStart: normalizedProgress = 0.0 case _ where absoluteProgress > animationEnd: normalizedProgress = 1.0 default: let progressSpan = animationEnd - animationStart normalizedProgress = (absoluteProgress - animationStart) / progressSpan } return normalizedProgress } } struct RingGraphAnimationState { let animationHelper: RangeAnimationHelper let animationProgress: Float let meterValues: [Float] init(graph: RingGraph, animationProgress inProgress: Float) { animationHelper = RangeAnimationHelper(animationStart: 0.3, animationEnd: 1.0) let graphProgress = sinEaseOutValue(forAnimationProgress: animationHelper.normalizedProgress(inProgress)) animationProgress = graphProgress let closureProgress = animationProgress meterValues = graph.meters.map {meter -> Float in return meter.normalizedValue * closureProgress } } } internal func sinEaseOutValue(forAnimationProgress progress: Float) -> Float { return sin(progress * Float(Double.pi) / 2) }
7ee1a86ad3f05b1b4f1870006bf58eac
29.910256
113
0.664869
false
false
false
false
sstanic/Shopfred
refs/heads/master
Shopfred/Shopfred/View Controller/UserRegistrationViewController.swift
mit
1
// // UserRegistrationViewController.swift // Shopfred // // Created by Sascha Stanic on 17.09.17. // Copyright © 2017 Sascha Stanic. All rights reserved. // import UIKit import CoreData /** Shows the user registration view. - important: Gets the current shopping space from the **DataStore**. # Navigation - **LoginViewController** (cancel) - **StartViewController** (successful registration) */ class UserRegistrationViewController: UIViewController { // MARK: - Outelts @IBOutlet weak var labelUserRegistration: UILabel! @IBOutlet weak var textFieldFirstName: UITextField! @IBOutlet weak var textFieldLastName: UITextField! @IBOutlet weak var textFieldEmail: UITextField! @IBOutlet weak var textFieldPassword: UITextField! @IBOutlet weak var textViewInformation: UITextView! @IBOutlet weak var btnRegister: UIButton! @IBOutlet weak var activityIndicator: UIActivityIndicatorView! // MARK: - Lifecycle override func viewDidLoad() { super.viewDidLoad() self.hideKeyboardWhenTappedAround() self.setStyle() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) // Check if registration is possible (in this version restricted to one user per shopping space) // Anyway this check will currently always pass, the registration dialog is only reachable when not logged in if let sp = DataStore.sharedInstance().shoppingStore.shoppingSpace { if let users = sp.users { if users.count == 1 { let u = users.allObjects.first as! User if u.id != Constants.UserNotSet { self.textViewInformation.text = "A user is already registered with this shopping space. User email: \(u.email ?? "<unknown>")" } } else { self.textViewInformation.text = "Several users are already registered in this shopping space." } } else { // no users yet in shopping space => go ahead } } else { print("Shopping space not set. This should have been checked in start view.") } } // MARK: - Styling private func setStyle() { self.labelUserRegistration.style(style: TextStyle.title) self.textFieldFirstName.style(style: TextStyle.body) self.textFieldLastName.style(style: TextStyle.body) self.textFieldEmail.style(style: TextStyle.body) self.textFieldPassword.style(style: TextStyle.body) self.textViewInformation.style(style: TextStyle.body) self.btnRegister.style(style: ViewStyle.Button.register) self.view.style(style: ViewStyle.DetailsView.standard) } // MARK: - IBAction @IBAction func registerClicked(_ sender: Any) { let firstName = self.textFieldFirstName.text! let lastName = self.textFieldLastName.text! let email = self.textFieldEmail.text! let password = self.textFieldPassword.text! Utils.showActivityIndicator(self.view, activityIndicator: self.activityIndicator, alpha: 0.1) DataStore.sharedInstance().userStore.registerNewUser(firstName: firstName, lastName: lastName, email: email, password: password) { user, error in Utils.hideActivityIndicator(self.view, activityIndicator: self.activityIndicator) if error != nil { Utils.showAlert(self, alertMessage: "Error: \(error?.localizedDescription ?? "")", completion: nil) } else { if DataStore.sharedInstance().userStore.CurrentUser == nil { DataStore.sharedInstance().userStore.CurrentUser = user UserDefaults.standard.set(true, forKey: Constants.IsLoggedIn) UserDefaults.standard.set(user!.id!, forKey: Constants.CurrentUser) } UserDefaults.standard.set(true, forKey: Constants.IsLoggedIn) if let navController = self.navigationController { navController.popToRootViewController(animated: true) } else { Utils.showAlert(self, alertMessage: "Sorry, something went wrong. Please restart the app.", completion: nil) } } } } @IBAction func cancelClicked(_ sender: Any) { self.navigateBack() } // MARK: - Navigation private func navigateBack() { if let navController = self.navigationController { navController.popViewController(animated: true) } else { Utils.showAlert(self, alertMessage: "Sorry, something went wrong. Please restart the app.", completion: nil) } } }
82f55f568dfdaf7cd426f8f12dce0254
34.127517
153
0.587314
false
false
false
false
Felizolinha/WidGame
refs/heads/master
WidGame/WidGame/WidGame.swift
mit
1
// // WidGame.swift // NewGame // // Created by Luis Gustavo Avelino de Lima Jacinto on 19/06/17. // Copyright © 2017 BEPiD. All rights reserved. // import Foundation import SpriteKit import NotificationCenter /** Defines which widget properties can be changed from the game scene. - author: Matheus Felizola Freires */ public protocol WGDelegate { ///A bool that defines if the widget should be expandable or not. var isExpandable:Bool {get set} ///A CGFloat that defines the widget's maximum height. var maxHeight:CGFloat {get set} } /** All your widget game scenes should inherit from this class, instead of SKScene. - author: Matheus Felizola Freires */ open class WGScene:SKScene { /** Called when the active display mode changes. You should override this method if you need to update your scene when the widget changes it's display mode. The default implementation of this method is blank. - parameters: - activeDisplayMode: The new active display mode. See NCWidgetDisplayMode for possible values. - maxSize: A CGSize object that represents the new maximum size this widget can have. */ open func widgetActiveDisplayModeDidChange(_ activeDisplayMode: NCWidgetDisplayMode, withMaximumSize maxSize: CGSize) {} /** Called when the widget's frame changes. You should override this method if you need to update your scene when the widget updates it's frame. This usually happens when the widget is transitioning to a different display mode, or to a new preferred content size. The default implementation for this method is blank. - parameters: - frame: A CGRect with the new frame size of the widget. - author: Matheus Felizola Freires */ open func didUpdateWidgetFrame(to frame: CGRect) {} /** Allows your game scene to change the widget's expandability or maximum height. Example of how to change the maximum height of your widget: widgetDelegate.maxHeight = 200 */ open var widgetDelegate: WGDelegate? /** Creates your scene object. - parameters: - size: The size of the scene in points. - controller: The WGDelegate compliant view controller that is creating the scene. - returns: A newly initialized WGScene object. */ public init(size: CGSize, controller: WGDelegate) { super.init(size: size) widgetDelegate = controller scaleMode = SKSceneScaleMode.resizeFill } /** Returns an object initialized from data in a given unarchiver. You typically return self from init(coder:). If you have an advanced need that requires substituting a different object after decoding, you can do so in awakeAfter(using:). - parameter decoder: An unarchiver object. - returns: self, initialized using the data in decoder. */ public required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } /** Your TodayViewController should inherit from WGViewController to implement WidGame's functionalities. - author: Matheus Felizola Freires */ open class WGViewController: UIViewController, NCWidgetProviding, WGDelegate { ///The SKView that will present your WidGame scenes. open var gameView: SKView? /** An enum that provides the reasons which your widget might close. - author: Matheus Felizola Freires */ public enum ExitReason { ///Sent when the widget leaves the screen. case leftTheScreen ///Sent when the widget receives a memory warning. case memoryWarning } @IBInspectable open var isExpandable: Bool = true { didSet { changeExpandability(to: isExpandable) } } open var maxHeight:CGFloat = 359 { didSet { if extensionContext?.widgetActiveDisplayMode == .expanded { preferredContentSize = CGSize(width: preferredContentSize.width, height: maxHeight) } } } /** Sets the widget expandability. - parameter value: A Bool value that tells the method if it should make the widget expandable or not. - requires: iOS 10.0 - TODO: Create a fallback to versions earlier than iOS 10.0 - author: Matheus Felizola Freires */ private func changeExpandability(to value: Bool) { if value { if #available(iOSApplicationExtension 10.0, *) { extensionContext?.widgetLargestAvailableDisplayMode = .expanded } else { // Fallback on earlier versions } } else { if #available(iOSApplicationExtension 10.0, *) { extensionContext?.widgetLargestAvailableDisplayMode = .compact } else { // Fallback on earlier versions } } } /** Notifies the view controller that its view was removed from a view hierarchy. You can override this method to perform additional tasks associated with dismissing or hiding the view. If you override this method, you must call super at some point in your implementation. - parameter animated: If true, the disappearance of the view was animated. */ open override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) self.widgetMightClose(reason: .leftTheScreen) } /** Sent to the view controller when the app receives a memory warning. Your app never calls this method directly. Instead, this method is called when the system determines that the amount of available memory is low. You can override this method to release any additional memory used by your view controller. If you do, your implementation of this method must call the super implementation at some point. */ open override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() self.widgetMightClose(reason: .memoryWarning) } /** Called when the widget is in a situation that it might be closed. An exit reason is provided to the method, so your logic can react accordingly. This method should be used for your save logic. The default implementation of this method is blank. - TODO: Find out if there are more things that might cause the widget to close. - author: Matheus Felizola Freires */ open func widgetMightClose(reason: WGViewController.ExitReason) {} /** Notifies the container that the size of its view is about to change. WidGame uses this method to set some widget configurations and creating your game view. It is this method who calls the presentInitialScene() method. UIKit calls this method before changing the size of a presented view controller’s view. You can override this method in your own objects and use it to perform additional tasks related to the size change. For example, a container view controller might use this method to override the traits of its embedded child view controllers. Use the provided coordinator object to animate any changes you make. If you override this method in your custom view controllers, always call super at some point in your implementation so that UIKit can forward the size change message appropriately. View controllers forward the size change message to their views and child view controllers. Presentation controllers forward the size change to their presented view controller. - parameters: - size: The new size for the container’s view. - coordinator: The transition coordinator object managing the size change. You can use this object to animate your changes or get information about the transition that is in progress. */ open override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransition(to: size, with: coordinator) if gameView == nil { DispatchQueue.main.async { //Use a different thread to lower the chance of crash when leaving the widget screen and going back. [unowned self] in self.preferredContentSize = CGSize(width: 0, height: self.maxHeight) self.changeExpandability(to: self.isExpandable) self.gameView = SKView(frame: self.view.frame) self.presentInitialScene() self.view.addSubview(self.gameView!) } } } /** Override this method to show your first scene and load any saved info. The default implementation of this method is blank. - author: Matheus Felizola Freires */ open func presentInitialScene() {} /** If you override the method below inside your TodayViewController, always call super at some point in your implementation so that WidGame can still update your gameView's frame and tell your game scene about these updates. */ open override func viewDidLayoutSubviews() { gameView?.frame = view.frame //Update game view frame to reflect any changes in widget's size if let scene = gameView?.scene as? WGScene { scene.didUpdateWidgetFrame(to: view.frame) } super.viewDidLayoutSubviews() } /** If you override the method below inside your TodayViewController, always call super at some point in your implementation so that WidGame can still delegate displayMode changes to your WGScene, and set the correct preferredContentSize to your widget. */ open func widgetActiveDisplayModeDidChange(_ activeDisplayMode: NCWidgetDisplayMode, withMaximumSize maxSize: CGSize) { if activeDisplayMode == .expanded { preferredContentSize = CGSize(width: maxSize.width, height: maxHeight) } else { preferredContentSize = maxSize } if let scene = gameView?.scene as? WGScene { scene.widgetActiveDisplayModeDidChange(activeDisplayMode, withMaximumSize: preferredContentSize) } //Don't forget to call super.widgetActiveDisplayModeDidChange(activeDisplayMode, withMaximumSize: maxSize) on your code! } }
b56c846213d58885b340f15a7ef860e9
40.855967
403
0.699636
false
false
false
false
nghialv/Sapporo
refs/heads/master
Sapporo/Sources/Cell/SACell.swift
mit
1
// // SACell.swift // Example // // Created by Le VanNghia on 6/29/15. // Copyright (c) 2015 Le Van Nghia. All rights reserved. // import UIKit open class SACell: UICollectionViewCell { open internal(set) weak var _cellmodel: SACellModel? open var shouldSelect = true open var shouldDeselect = true open var shouldHighlight = true func configure(_ cellmodel: SACellModel) { _cellmodel = cellmodel configure() } open func configure() {} open func configureForSizeCalculating(_ cellmodel: SACellModel) { _cellmodel = cellmodel } open func willDisplay(_ collectionView: UICollectionView) {} open func didEndDisplaying(_ collectionView: UICollectionView) {} open func didHighlight(_ collectionView: UICollectionView) {} open func didUnhighlight(_ collectionView: UICollectionView) {} }
fcc1de0112e91165962ae73ec83a1a4c
25.939394
69
0.677165
false
true
false
false
codepgq/LearningSwift
refs/heads/master
PresentTumblrAnimator/PresentTumblrAnimator/ViewController.swift
apache-2.0
1
// // ViewController.swift // PresentTumblrAnimator // // Created by ios on 16/9/23. // Copyright © 2016年 ios. All rights reserved. // import UIKit struct model { var icon = "animator1.jpg" var name = "default" var backImage = "animator1.jpg" } class ViewController: UIViewController ,UICollectionViewDelegate,UICollectionViewDataSource{ @IBOutlet weak var collectionView: UICollectionView! let data = [ model(icon: "Chat", name: "小明", backImage: "animator1.jpg"), model(icon: "Quote", name: "老王", backImage: "animator2.jpg"), model(icon: "Audio", name: "隔壁大叔", backImage: "animator3.jpg"), model(icon: "Link", name: "邻家淑女", backImage: "animator4.jpg") ] override func viewDidLoad() { super.viewDidLoad() collectionView.delegate = self collectionView.dataSource = self } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func preferredStatusBarStyle() -> UIStatusBarStyle { return .LightContent } @IBAction func unwindToMainViewController (sender: UIStoryboardSegue){ self.dismissViewControllerAnimated(true, completion: nil) } } extension ViewController { func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int{ return 10 } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell{ let cell = collectionView.dequeueReusableCellWithReuseIdentifier("collCell", forIndexPath: indexPath) as! CollectionViewCell let model = data[indexPath.row % 4] cell.backImage.image = UIImage(named: model.backImage) cell.icon.image = UIImage(named:model.icon) cell.nameLabel.text = model.name return cell } }
a9fb8ce29d8d07e2eabca8bcccfff079
29.734375
132
0.671581
false
false
false
false
cismet/belis-app
refs/heads/dev
belis-app/MainViewController.swift
mit
1
// // MainViewController.swift // BelIS // // Created by Thorsten Hell on 08/12/14. // Copyright (c) 2014 cismet. All rights reserved. // import UIKit; import MapKit; import ObjectMapper; import MGSwipeTableCell import JGProgressHUD class MainViewController: UIViewController, UITableViewDataSource, UITableViewDelegate,CLLocationManagerDelegate, MKMapViewDelegate, UITextFieldDelegate, MGSwipeTableCellDelegate { @IBOutlet weak var mapView: MKMapView!; @IBOutlet weak var tableView: UITableView!; @IBOutlet weak var mapTypeSegmentedControl: UISegmentedControl!; @IBOutlet weak var mapToolbar: UIToolbar!; @IBOutlet weak var focusToggle: UISwitch! @IBOutlet weak var textfieldGeoSearch: UITextField! @IBOutlet weak var brightenToggle: UISwitch! @IBOutlet weak var itemArbeitsauftrag: UIBarButtonItem! @IBOutlet weak var bbiMoreFunctionality: UIBarButtonItem! @IBOutlet weak var bbiZoomToAllObjects: UIBarButtonItem! var matchingSearchItems: [MKMapItem] = [MKMapItem]() var matchingSearchItemsAnnotations: [MKPointAnnotation ] = [MKPointAnnotation]() var loginViewController: LoginViewController? var isLeuchtenEnabled=true; var isMastenEnabled=true; var isMauerlaschenEnabled=true; var isleitungenEnabled=true; var isSchaltstelleEnabled=true; var highlightedLine : HighlightedMkPolyline?; var selectedAnnotation : MKAnnotation?; var user=""; var pass=""; var timer = Timer(); var mapRegionSetFromUserDefaults=false let progressHUD = JGProgressHUD(style: JGProgressHUDStyle.dark) var gotoUserLocationButton:MKUserTrackingBarButtonItem!; var locationManager: CLLocationManager! let focusRectShape = CAShapeLayer() static let IMAGE_PICKER=UIImagePickerController() var brightOverlay=MyBrightOverlay() var shownDetails:DetailVC? //MARK: Standard VC functions override func viewDidLoad() { super.viewDidLoad(); CidsConnector.sharedInstance().mainVC=self locationManager=CLLocationManager(); locationManager.desiredAccuracy=kCLLocationAccuracyBest; locationManager.distanceFilter=100.0; locationManager.startUpdatingLocation(); locationManager.requestWhenInUseAuthorization() gotoUserLocationButton=MKUserTrackingBarButtonItem(mapView:mapView); mapToolbar.items!.insert(gotoUserLocationButton,at:0 ); //delegate stuff locationManager.delegate=self; mapView.delegate=self; tableView.delegate=self; //var tileOverlay = MyOSMMKTileOverlay() // mapView.addOverlay(tileOverlay); var lat: CLLocationDegrees = (UserDefaults.standard.double(forKey: "mapPosLat") as CLLocationDegrees?) ?? 0.0 var lng: CLLocationDegrees = (UserDefaults.standard.double(forKey: "mapPosLng") as CLLocationDegrees?) ?? 0.0 var altitude: Double = (UserDefaults.standard.double(forKey: "mapAltitude") as Double?) ?? 0.0 if lat == 0.0 { lat=CidsConnector.sharedInstance().mapPosLat } if lng == 0.0 { lng=CidsConnector.sharedInstance().mapPosLng } if altitude == 0.0 { altitude = CidsConnector.sharedInstance().mapAltitude } let initLocation: CLLocationCoordinate2D = CLLocationCoordinate2DMake(lat, lng) mapView.isRotateEnabled=false; mapView.isZoomEnabled=true; mapView.showsBuildings=true; mapView.setCenter(initLocation, animated: true); mapView.camera.altitude = altitude mapRegionSetFromUserDefaults=true log.warning("initial Position from UserDefaults= \(UserDefaults.standard.double(forKey: "mapPosLat")),\(UserDefaults.standard.double(forKey: "mapPosLng")) with an altitude of \(UserDefaults.standard.double(forKey: "mapAltitide"))") log.warning("initial Position from CidsConnector= \(CidsConnector.sharedInstance().mapPosLat),\(CidsConnector.sharedInstance().mapPosLng) with an altitude of \(CidsConnector.sharedInstance().mapAltitude)") log.info("initial Position= \(lat),\(lng) with an altitude of \(self.mapView.camera.altitude)") focusRectShape.opacity = 0.4 focusRectShape.lineWidth = 2 focusRectShape.lineJoin = kCALineJoinMiter focusRectShape.strokeColor = UIColor(red: 0.29, green: 0.53, blue: 0.53, alpha: 1).cgColor focusRectShape.fillColor = UIColor(red: 0.51, green: 0.76, blue: 0.6, alpha: 1).cgColor let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(MainViewController.mapTapped(_:))) mapView.addGestureRecognizer(tapGestureRecognizer) //UINavigationController(rootViewController: self) textfieldGeoSearch.delegate=self bbiMoreFunctionality.setTitleTextAttributes([ NSFontAttributeName : UIFont(name: GlyphTools.glyphFontName, size: 16)!], for: UIControlState()) bbiMoreFunctionality.title=WebHostingGlyps.glyphs["icon-chevron-down"] bbiZoomToAllObjects.setTitleTextAttributes([ NSFontAttributeName : UIFont(name: GlyphTools.glyphFontName, size: 20)!], for: UIControlState()) bbiZoomToAllObjects.title=WebHostingGlyps.glyphs["icon-world"] log.info(UIDevice.current.identifierForVendor!.uuidString) itemArbeitsauftrag.title="Kein Arbeitsauftrag ausgewählt (\(CidsConnector.sharedInstance().selectedTeam?.name ?? "-"))" } override func viewDidAppear(_ animated: Bool) { if CidsConnector.sharedInstance().selectedTeam != nil { // let alert=UIAlertController(title: "Ausgewähltes Team",message:"\(CidsConnector.sharedInstance().selectedTeam ?? "???")", preferredStyle: UIAlertControllerStyle.alert) // let okButton = UIAlertAction(title: "Ok", style: .default, handler: nil) // alert.addAction(okButton) // self.present(alert, animated: true, completion: nil) } else { let alert=UIAlertController(title: "Kein Team ausgewählt",message:"Ohne ausgewähltes Team können Sie keine Arbeitsaufträge aufrufen.", preferredStyle: UIAlertControllerStyle.alert) let okButton = UIAlertAction(title: "Ok", style: .default, handler: nil) alert.addAction(okButton) show(alert,sender: self) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. if (segue.identifier == "showSearchSelectionPopover") { let selectionVC = segue.destination as! SelectionPopoverViewController selectionVC.mainVC=self; } else if (segue.identifier == "showAdditionalFunctionalityPopover") { let additionalFuncVC = segue.destination as! AdditionalFunctionalityPopoverViewController additionalFuncVC.mainVC=self; } } override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { focusRectShape.removeFromSuperlayer() coordinator.animate(alongsideTransition: nil, completion: { context in if UIDevice.current.orientation.isLandscape { log.verbose("landscape") } else { log.verbose("portraight") } self.ensureFocusRectangleIsDisplayedWhenAndWhereItShould() }) } //MARK: UITableViewDataSource func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return CidsConnector.sharedInstance().searchResults[Entity.byIndex(section)]?.count ?? 0 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell: TableViewCell = tableView.dequeueReusableCell(withIdentifier: "firstCellPrototype")as! TableViewCell // var cellInfoProvider: CellInformationProviderProtocol = NoCellInformation() cell.baseEntity=CidsConnector.sharedInstance().searchResults[Entity.byIndex((indexPath as NSIndexPath).section)]?[(indexPath as NSIndexPath).row] if let obj=cell.baseEntity { if let cellInfoProvider=obj as? CellInformationProviderProtocol { cell.lblBezeichnung.text=cellInfoProvider.getMainTitle() cell.lblStrasse.text=cellInfoProvider.getTertiaryInfo() cell.lblSubText.text=cellInfoProvider.getSubTitle() cell.lblZusatzinfo.text=cellInfoProvider.getQuaternaryInfo() } } cell.delegate=self if let left=cell.baseEntity as? LeftSwipeActionProvider { cell.leftButtons=left.getLeftSwipeActions() } else { cell.leftButtons=[] } if let right=cell.baseEntity as? RightSwipeActionProvider { cell.rightButtons=right.getRightSwipeActions() } else { cell.rightButtons=[] } //let fav=MGSwipeButton(title: "Fav", backgroundColor: UIColor.blueColor()) cell.leftSwipeSettings.transition = MGSwipeTransition.static //configure right buttons // let delete=MGSwipeButton(title: "Delete", backgroundColor: UIColor.redColor()) // let more=MGSwipeButton(title: "More",backgroundColor: UIColor.lightGrayColor()) // // cell.rightButtons = [delete,more] // cell.rightSwipeSettings.transition = MGSwipeTransition.Static cell.leftExpansion.threshold=1.5 cell.leftExpansion.fillOnTrigger=true //cell.leftExpansion.buttonIndex=0 return cell } func numberOfSections(in tableView: UITableView) -> Int { return Entity.allValues.count } func swipeTableCell(_ cell: MGSwipeTableCell, shouldHideSwipeOnTap point: CGPoint) -> Bool { return true } func swipeTableCellWillBeginSwiping(_ cell: MGSwipeTableCell) { if let myTableViewCell=cell as? TableViewCell, let gbe=myTableViewCell.baseEntity as? GeoBaseEntity { self.selectOnMap(gbe) self.selectInTable(gbe, scrollToShow: false) } } //MARK: UITableViewDelegate func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath){ log.verbose("didSelectRowAtIndexPath") if let obj=CidsConnector.sharedInstance().searchResults[Entity.byIndex((indexPath as NSIndexPath).section)]?[(indexPath as NSIndexPath).row] { selectOnMap(obj) // lastSelection=obj } } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { if let array=CidsConnector.sharedInstance().searchResults[Entity.byIndex(section)]{ if (array.count>0){ return 25 } } return 0.0 } func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { let title=Entity.byIndex(section).rawValue if let array=CidsConnector.sharedInstance().searchResults[Entity.byIndex(section)]{ return title + " \(array.count)" } else { return title } } // MARK: CLLocationManagerDelegate func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { } // MARK: NKMapViewDelegates func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer { if overlay is MKPolyline { if overlay is GeoBaseEntityStyledMkPolylineAnnotation { let polylineRenderer = MKPolylineRenderer(overlay: overlay) polylineRenderer.strokeColor = UIColor(red: 228.0/255.0, green: 118.0/255.0, blue: 37.0/255.0, alpha: 0.8); polylineRenderer.lineWidth = 2 return polylineRenderer } else if overlay is HighlightedMkPolyline { let polylineRenderer = MKPolylineRenderer(overlay: overlay) polylineRenderer.strokeColor = UIColor(red: 255.0/255.0, green: 224.0/255.0, blue: 110.0/255.0, alpha: 0.8); polylineRenderer.lineWidth = 10 return polylineRenderer } } else if let polygon = overlay as? GeoBaseEntityStyledMkPolygonAnnotation { let polygonRenderer = MKPolygonRenderer(overlay: polygon) if let styler = polygon.getGeoBaseEntity() as? PolygonStyler { polygonRenderer.strokeColor = styler.getStrokeColor() polygonRenderer.lineWidth = styler.getLineWidth() polygonRenderer.fillColor=styler.getFillColor() }else { polygonRenderer.strokeColor = PolygonStylerConstants.strokeColor polygonRenderer.lineWidth = PolygonStylerConstants.lineWidth polygonRenderer.fillColor=PolygonStylerConstants.fillColor } return polygonRenderer } else if (overlay is MyBrightOverlay){ let renderer = MyBrightOverlayRenderer(tileOverlay: overlay as! MKTileOverlay); return renderer; } return MKOverlayRenderer() } func mapView(_ mapView: MKMapView, regionDidChangeAnimated animated: Bool) { if mapRegionSetFromUserDefaults { log.verbose("Region changed to \(mapView.centerCoordinate.latitude),\(mapView.centerCoordinate.longitude) with an altitude of \(mapView.camera.altitude)") CidsConnector.sharedInstance().mapPosLat=mapView.centerCoordinate.latitude CidsConnector.sharedInstance().mapPosLng=mapView.centerCoordinate.longitude CidsConnector.sharedInstance().mapAltitude=mapView.camera.altitude } } func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? { if (annotation is GeoBaseEntityPointAnnotation){ let gbePA=annotation as! GeoBaseEntityPointAnnotation; let reuseId = "belisAnnotation" var anView = mapView.dequeueReusableAnnotationView(withIdentifier: reuseId) if anView == nil { anView = MKAnnotationView(annotation: gbePA, reuseIdentifier: reuseId) } else { anView!.annotation = gbePA } //Set annotation-specific properties **AFTER** //the view is dequeued or created... anView!.canShowCallout = gbePA.shouldShowCallout; anView!.image = gbePA.annotationImage if let label=GlyphTools.sharedInstance().getGlyphedLabel(gbePA.glyphName) { label.textColor=UIColor(red: 0.0, green: 0.48, blue: 1.0, alpha: 1.0) anView!.leftCalloutAccessoryView=label } if let btn=GlyphTools.sharedInstance().getGlyphedButton("icon-chevron-right"){ btn.setTitleColor(UIColor(red: 0.8, green: 0.8, blue: 0.8, alpha: 1.0), for: UIControlState()) anView!.rightCalloutAccessoryView=btn } anView!.alpha=0.9 return anView } else if (annotation is GeoBaseEntityStyledMkPolylineAnnotation){ let gbeSMKPA=annotation as! GeoBaseEntityStyledMkPolylineAnnotation; let reuseId = "belisAnnotation" var anView = mapView.dequeueReusableAnnotationView(withIdentifier: reuseId) if anView == nil { anView = MKAnnotationView(annotation: gbeSMKPA, reuseIdentifier: reuseId) } else { anView!.annotation = gbeSMKPA } if let label=GlyphTools.sharedInstance().getGlyphedLabel(gbeSMKPA.glyphName) { label.textColor=UIColor(red: 0.0, green: 0.48, blue: 1.0, alpha: 1.0) anView!.leftCalloutAccessoryView=label } if let btn=GlyphTools.sharedInstance().getGlyphedButton("icon-chevron-right"){ btn.setTitleColor(UIColor(red: 0.8, green: 0.8, blue: 0.8, alpha: 1.0), for: UIControlState()) anView!.rightCalloutAccessoryView=btn } //Set annotation-specific properties **AFTER** //the view is dequeued or created... anView!.image = gbeSMKPA.annotationImage; anView!.canShowCallout = gbeSMKPA.shouldShowCallout; anView!.alpha=0.9 return anView } else if (annotation is GeoBaseEntityStyledMkPolygonAnnotation){ let gbeSPGA=annotation as! GeoBaseEntityStyledMkPolygonAnnotation; let reuseId = "belisAnnotation" var anView = mapView.dequeueReusableAnnotationView(withIdentifier: reuseId) if anView == nil { anView = MKAnnotationView(annotation: gbeSPGA, reuseIdentifier: reuseId) } else { anView!.annotation = gbeSPGA } if let label=GlyphTools.sharedInstance().getGlyphedLabel(gbeSPGA.glyphName) { label.textColor=UIColor(red: 0.0, green: 0.48, blue: 1.0, alpha: 1.0) anView!.leftCalloutAccessoryView=label } if let btn=GlyphTools.sharedInstance().getGlyphedButton("icon-chevron-right"){ btn.setTitleColor(UIColor(red: 0.8, green: 0.8, blue: 0.8, alpha: 1.0), for: UIControlState()) anView!.rightCalloutAccessoryView=btn } //Set annotation-specific properties **AFTER** //the view is dequeued or created... anView!.image = gbeSPGA.annotationImage; anView!.canShowCallout = gbeSPGA.shouldShowCallout; anView!.alpha=0.9 return anView } return nil; } func mapView(_ mapView: MKMapView, didChange mode: MKUserTrackingMode, animated: Bool) { log.verbose("didChangeUserTrackingMode") } func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) { delayed(0.0) { if !view.annotation!.isKind(of: MatchingSearchItemsAnnotations.self) { if view.annotation !== self.selectedAnnotation { mapView.deselectAnnotation(view.annotation, animated: false) if let selAnno=self.selectedAnnotation { mapView.selectAnnotation(selAnno, animated: false) } } } } log.verbose("didSelectAnnotationView >> \(String(describing: view.annotation!.title))") } func mapView(_ mapView: MKMapView, didDeselect view: MKAnnotationView) { delayed(0.0) { if view.annotation === self.selectedAnnotation { if let selAnno=self.selectedAnnotation { mapView.selectAnnotation(selAnno, animated: false) } } } log.verbose("didDeselectAnnotationView >> \(String(describing: view.annotation!.title))") } //MARK: - IBActions @IBAction func searchButtonTabbed(_ sender: AnyObject) { removeAllEntityObjects() self.tableView.reloadData(); let searchQueue=CancelableOperationQueue(name: "Objektsuche", afterCancellation: { self.removeAllEntityObjects() self.tableView.reloadData(); forceProgressInWaitingHUD(0) hideWaitingHUD() }) showWaitingHUD(queue: searchQueue, text:"Objektsuche") var mRect : MKMapRect if focusToggle.isOn { mRect = createFocusRect() } else { mRect = self.mapView.visibleMapRect; } let mRegion=MKCoordinateRegionForMapRect(mRect); let x1=mRegion.center.longitude-(mRegion.span.longitudeDelta/2) let y1=mRegion.center.latitude-(mRegion.span.latitudeDelta/2) let x2=mRegion.center.longitude+(mRegion.span.longitudeDelta/2) let y2=mRegion.center.latitude+(mRegion.span.latitudeDelta/2) let ewktMapExtent="SRID=4326;POLYGON((\(x1) \(y1),\(x1) \(y2),\(x2) \(y2),\(x2) \(y1),\(x1) \(y1)))"; CidsConnector.sharedInstance().search(ewktMapExtent, leuchtenEnabled: isLeuchtenEnabled, mastenEnabled: isMastenEnabled, mauerlaschenEnabled: isMauerlaschenEnabled, leitungenEnabled: isleitungenEnabled,schaltstellenEnabled: isSchaltstelleEnabled, queue: searchQueue ) { assert(!Thread.isMainThread ) DispatchQueue.main.async { CidsConnector.sharedInstance().sortSearchResults() self.tableView.reloadData(); for (_, objArray) in CidsConnector.sharedInstance().searchResults{ for obj in objArray { obj.addToMapView(self.mapView); } } hideWaitingHUD() } } } @IBAction func itemArbeitsauftragTapped(_ sender: AnyObject) { if let gbe=CidsConnector.sharedInstance().selectedArbeitsauftrag { let detailVC=DetailVC(nibName: "DetailVC", bundle: nil) shownDetails=detailVC let cellDataProvider=gbe as CellDataProvider detailVC.sections=cellDataProvider.getDataSectionKeys() detailVC.setCellData(cellDataProvider.getAllData()) detailVC.objectToShow=gbe detailVC.title=cellDataProvider.getTitle() let icon=UIBarButtonItem() icon.action=#selector(MainViewController.back(_:)) //icon.image=getGlyphedImage("icon-chevron-left") icon.image=GlyphTools.sharedInstance().getGlyphedImage("icon-chevron-left", fontsize: 11, size: CGSize(width: 14, height: 14)) detailVC.navigationItem.leftBarButtonItem = icon let detailNC=UINavigationController(rootViewController: detailVC) selectedAnnotation=nil detailNC.modalPresentationStyle = UIModalPresentationStyle.popover detailNC.popoverPresentationController?.barButtonItem = itemArbeitsauftrag present(detailNC, animated: true, completion: nil) } else if let indexPath=tableView.indexPathForSelectedRow , let aa = CidsConnector.sharedInstance().searchResults[Entity.byIndex((indexPath as NSIndexPath).section)]?[(indexPath as NSIndexPath).row] as? Arbeitsauftrag { selectArbeitsauftrag(aa) } } @IBAction func mapTypeButtonTabbed(_ sender: AnyObject) { switch(mapTypeSegmentedControl.selectedSegmentIndex){ case 0: mapView.mapType=MKMapType.standard; case 1: mapView.mapType=MKMapType.hybrid; case 2: mapView.mapType=MKMapType.satellite; default: mapView.mapType=MKMapType.standard; } } @IBAction func lookUpButtonTabbed(_ sender: AnyObject) { if let team = CidsConnector.sharedInstance().selectedTeam { selectArbeitsauftrag(nil,showActivityIndicator: false) removeAllEntityObjects() let aaSearchQueue=CancelableOperationQueue(name: "Arbeitsaufträge suchen", afterCancellation: { self.selectArbeitsauftrag(nil,showActivityIndicator: false) self.removeAllEntityObjects() forceProgressInWaitingHUD(0) hideWaitingHUD() }) showWaitingHUD(queue: aaSearchQueue, text:"Arbeitsaufträge suchen") CidsConnector.sharedInstance().searchArbeitsauftraegeForTeam(team, queue: aaSearchQueue) { () -> () in DispatchQueue.main.async { CidsConnector.sharedInstance().sortSearchResults() self.tableView.reloadData(); var annos: [MKAnnotation]=[] for (_, objArray) in CidsConnector.sharedInstance().searchResults{ for obj in objArray { obj.addToMapView(self.mapView); if let anno=obj.mapObject as? MKAnnotation { annos.append(anno) } } } hideWaitingHUD(delayedText: "Veranlassungen werden im\nHintergrund nachgeladen", delay: 1) DispatchQueue.main.async { self.zoomToFitMapAnnotations(annos) } } } } else { let alert=UIAlertController(title: "Kein Team ausgewählt",message:"Bitte wählen Sie zuerst ein Team aus", preferredStyle: UIAlertControllerStyle.alert) let okButton = UIAlertAction(title: "Ok", style: .default, handler: nil) alert.addAction(okButton) show(alert,sender: self) } } @IBAction func focusItemTabbed(_ sender: AnyObject) { focusToggle.setOn(!focusToggle.isOn, animated: true) focusToggleValueChanged(self) } @IBAction func focusToggleValueChanged(_ sender: AnyObject) { ensureFocusRectangleIsDisplayedWhenAndWhereItShould() } @IBAction func brightenItemTabbed(_ sender: AnyObject) { brightenToggle.setOn(!brightenToggle.isOn, animated: true) brightenToggleValueChanged(self) } @IBAction func brightenToggleValueChanged(_ sender: AnyObject) { ensureBrightOverlayIsDisplayedWhenItShould() } @IBAction func geoSearchButtonTabbed(_ sender: AnyObject) { if textfieldGeoSearch.text! != "" { geoSearch() } } @IBAction func geoSearchInputDidEnd(_ sender: AnyObject) { geoSearch() } @IBAction func zoomToAllObjectsTapped(_ sender: AnyObject) { var annos: [MKAnnotation]=[] for (_, objArray) in CidsConnector.sharedInstance().searchResults{ for obj in objArray { if let anno=obj.mapObject as? MKAnnotation { annos.append(anno) } } } DispatchQueue.main.async { self.zoomToFitMapAnnotations(annos) } } // MARK: - Selector functions func back(_ sender: UIBarButtonItem) { if let details=shownDetails{ details.dismiss(animated: true, completion: { () -> Void in CidsConnector.sharedInstance().selectedArbeitsauftrag=nil self.selectArbeitsauftrag(nil) self.shownDetails=nil }) } } func createFocusRect() -> MKMapRect { let mRect = self.mapView.visibleMapRect; let newSize = MKMapSize(width: mRect.size.width/3,height: mRect.size.height/3) let newOrigin = MKMapPoint(x: mRect.origin.x+newSize.width, y: mRect.origin.y+newSize.height) return MKMapRect(origin: newOrigin,size: newSize) } func zoomToFitMapAnnotations(_ annos: [MKAnnotation]) { if annos.count == 0 {return} var topLeftCoordinate = CLLocationCoordinate2D(latitude: -90, longitude: 180) var bottomRightCoordinate = CLLocationCoordinate2D(latitude: 90, longitude: -180) for annotation in annos { if let poly=annotation as? MKMultiPoint { let points=poly.points() for i in 0 ... poly.pointCount-1 { //last point is jwd (dono why) let coord = MKCoordinateForMapPoint(points[i]) topLeftCoordinate.longitude = fmin(topLeftCoordinate.longitude, coord.longitude) topLeftCoordinate.latitude = fmax(topLeftCoordinate.latitude, coord.latitude) bottomRightCoordinate.longitude = fmax(bottomRightCoordinate.longitude, coord.longitude) bottomRightCoordinate.latitude = fmin(bottomRightCoordinate.latitude, coord.latitude) } } else { topLeftCoordinate.longitude = fmin(topLeftCoordinate.longitude, annotation.coordinate.longitude) topLeftCoordinate.latitude = fmax(topLeftCoordinate.latitude, annotation.coordinate.latitude) bottomRightCoordinate.longitude = fmax(bottomRightCoordinate.longitude, annotation.coordinate.longitude) bottomRightCoordinate.latitude = fmin(bottomRightCoordinate.latitude, annotation.coordinate.latitude) } } let center = CLLocationCoordinate2D(latitude: topLeftCoordinate.latitude - (topLeftCoordinate.latitude - bottomRightCoordinate.latitude) * 0.5, longitude: topLeftCoordinate.longitude - (topLeftCoordinate.longitude - bottomRightCoordinate.longitude) * 0.5) // Add a little extra space on the sides let span = MKCoordinateSpanMake(fabs(topLeftCoordinate.latitude - bottomRightCoordinate.latitude) * 1.3, fabs(bottomRightCoordinate.longitude - topLeftCoordinate.longitude) * 1.3) var region = MKCoordinateRegion(center: center, span: span) region = self.mapView.regionThatFits(region) self.mapView.setRegion(region, animated: true) } func selectArbeitsauftrag(_ arbeitsauftrag: Arbeitsauftrag?, showActivityIndicator: Bool = true) { let sel=selectedAnnotation selectedAnnotation=nil if let s=sel { mapView.deselectAnnotation(s, animated: false) } CidsConnector.sharedInstance().selectedArbeitsauftrag=arbeitsauftrag if showActivityIndicator { showWaitingHUD(queue: CancelableOperationQueue(name:"dummy", afterCancellation: {})) } let overlays=self.mapView.overlays self.mapView.removeOverlays(overlays) for anno in self.mapView.selectedAnnotations { self.mapView.deselectAnnotation(anno, animated: false) } var zoomToShowAll=true if let aa=arbeitsauftrag { CidsConnector.sharedInstance().allArbeitsauftraegeBeforeCurrentSelection=CidsConnector.sharedInstance().searchResults fillArbeitsauftragIntoTable(aa) } else { itemArbeitsauftrag.title="Kein Arbeitsauftrag ausgewählt (\(CidsConnector.sharedInstance().selectedTeam?.name ?? "-"))" self.removeAllEntityObjects() CidsConnector.sharedInstance().searchResults=CidsConnector.sharedInstance().allArbeitsauftraegeBeforeCurrentSelection zoomToShowAll=false } visualizeAllSearchResultsInMap(zoomToShowAll: zoomToShowAll, showActivityIndicator: showActivityIndicator) } func fillArbeitsauftragIntoTable(_ arbeitsauftrag: Arbeitsauftrag) { removeAllEntityObjects() itemArbeitsauftrag.title="\(arbeitsauftrag.nummer!) (\(CidsConnector.sharedInstance().selectedTeam?.name ?? "-"))" if let protokolle=arbeitsauftrag.protokolle { for prot in protokolle { if let _=CidsConnector.sharedInstance().searchResults[Entity.PROTOKOLLE] { CidsConnector.sharedInstance().searchResults[Entity.PROTOKOLLE]!.append(prot) } else { CidsConnector.sharedInstance().searchResults.updateValue([prot], forKey: Entity.PROTOKOLLE) } } } } func visualizeAllSearchResultsInMap(zoomToShowAll: Bool,showActivityIndicator:Bool ) { func doIt(){ self.selectedAnnotation=nil self.mapView.deselectAnnotation(selectedAnnotation, animated: false) var annos: [MKAnnotation]=[] for (_, objArray) in CidsConnector.sharedInstance().searchResults{ for obj in objArray { obj.addToMapView(self.mapView); if let anno=obj.mapObject as? MKAnnotation { annos.append(anno) } } } if zoomToShowAll { self.zoomToFitMapAnnotations(annos) } if showActivityIndicator { hideWaitingHUD() } } if Thread.isMainThread { doIt() } else { DispatchQueue.main.async { doIt() } } } // MARK: - public functions func mapTapped(_ sender: UITapGestureRecognizer) { let touchPt = sender.location(in: mapView) //let hittedUI = mapView.hitTest(touchPt, withEvent: nil) // println(hittedUI) log.verbose("mapTabbed") let buffer=CGFloat(22) var foundPolyline: GeoBaseEntityStyledMkPolylineAnnotation? var foundPoint: GeoBaseEntityPointAnnotation? var foundPolygon: GeoBaseEntityStyledMkPolygonAnnotation? for anno: AnyObject in mapView.annotations { if let pointAnnotation = anno as? GeoBaseEntityPointAnnotation { let cgPoint = mapView.convert(pointAnnotation.coordinate, toPointTo: mapView) let path = CGMutablePath() path.move(to: cgPoint) path.addLine(to: cgPoint) let fuzzyPath=CGPath(__byStroking: path, transform: nil, lineWidth: buffer, lineCap: CGLineCap.round, lineJoin: CGLineJoin.round, miterLimit: 0.0) if (fuzzyPath?.contains(touchPt) == true) { foundPoint = pointAnnotation log.verbose("foundPoint") selectOnMap(foundPoint?.getGeoBaseEntity()) selectInTable(foundPoint?.getGeoBaseEntity()) break } } } if (foundPoint == nil){ for overlay: AnyObject in mapView.overlays { if let lineAnnotation = overlay as? GeoBaseEntityStyledMkPolylineAnnotation{ let path = CGMutablePath() for i in 0...lineAnnotation.pointCount-1 { let mapPoint = lineAnnotation.points()[i] let cgPoint = mapView.convert(MKCoordinateForMapPoint(mapPoint), toPointTo: mapView) if i==0 { path.move(to: cgPoint) } else { path.addLine(to: cgPoint); } } let fuzzyPath=CGPath(__byStroking: path, transform: nil, lineWidth: buffer, lineCap: CGLineCap.round, lineJoin: CGLineJoin.round, miterLimit: 0.0) if (fuzzyPath?.contains(touchPt) == true) { foundPolyline = lineAnnotation break } } if let polygonAnnotation = overlay as? GeoBaseEntityStyledMkPolygonAnnotation { let path = CGMutablePath() for i in 0...polygonAnnotation.pointCount-1 { let mapPoint = polygonAnnotation.points()[i] let cgPoint = mapView.convert(MKCoordinateForMapPoint(mapPoint), toPointTo: mapView) if i==0 { path.move(to: cgPoint) } else { path.addLine(to: cgPoint) } } if (path.contains(touchPt) == true ) { foundPolygon=polygonAnnotation break } } } if let hitPolyline = foundPolyline { selectOnMap(hitPolyline.getGeoBaseEntity()) selectInTable(hitPolyline.getGeoBaseEntity()) } else if let hitPolygon=foundPolygon{ selectOnMap(hitPolygon.getGeoBaseEntity()) selectInTable(hitPolygon.getGeoBaseEntity()) } else { selectOnMap(nil) } } } func selectOnMap(_ geoBaseEntityToSelect : GeoBaseEntity?){ if highlightedLine != nil { mapView.remove(highlightedLine!); } if (selectedAnnotation != nil){ mapView.deselectAnnotation(selectedAnnotation, animated: false) } if let geoBaseEntity = geoBaseEntityToSelect{ let mapObj=geoBaseEntity.mapObject if let mO=mapObj as? MKAnnotation { mapView.selectAnnotation(mO, animated: true); selectedAnnotation=mapObj as? MKAnnotation } if mapObj is GeoBaseEntityPointAnnotation { } else if mapObj is GeoBaseEntityStyledMkPolylineAnnotation { let line = mapObj as! GeoBaseEntityStyledMkPolylineAnnotation; highlightedLine = HighlightedMkPolyline(points: line.points(), count: line.pointCount); mapView.remove(line); mapView.add(highlightedLine!); mapView.add(line); //bring the highlightedLine below the line } else if mapObj is GeoBaseEntityStyledMkPolygonAnnotation { //let polygon=mapObj as! GeoBaseEntityStyledMkPolygonAnnotation //let annos=[polygon] //zoomToFitMapAnnotations(annos) } } else { selectedAnnotation=nil } } func selectInTable(_ geoBaseEntityToSelect : GeoBaseEntity?, scrollToShow: Bool=true){ if let geoBaseEntity = geoBaseEntityToSelect{ let entity=geoBaseEntity.getType() //need old fashioned loop for index for i in 0...CidsConnector.sharedInstance().searchResults[entity]!.count-1 { var results : [GeoBaseEntity] = CidsConnector.sharedInstance().searchResults[entity]! if results[i].id == geoBaseEntity.id { if scrollToShow { tableView.selectRow(at: IndexPath(row: i, section: entity.index()), animated: true, scrollPosition: UITableViewScrollPosition.top) } else { tableView.selectRow(at: IndexPath(row: i, section: entity.index()), animated: true, scrollPosition: UITableViewScrollPosition.none) } break; } } } } func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) { //var detailVC=LeuchtenDetailsViewController() // var detailVC=storyboard!.instantiateViewControllerWithIdentifier("LeuchtenDetails") as UIViewController var geoBaseEntity: GeoBaseEntity? if let pointAnnotation = view.annotation as? GeoBaseEntityPointAnnotation { geoBaseEntity=pointAnnotation.geoBaseEntity } else if let lineAnnotation = view.annotation as? GeoBaseEntityStyledMkPolylineAnnotation { geoBaseEntity=lineAnnotation.geoBaseEntity }else if let polygonAnnotation = view.annotation as? GeoBaseEntityStyledMkPolygonAnnotation { geoBaseEntity=polygonAnnotation.geoBaseEntity } if let gbe = geoBaseEntity { let detailVC=DetailVC(nibName: "DetailVC", bundle: nil) if let cellDataProvider=gbe as? CellDataProvider { detailVC.sections=cellDataProvider.getDataSectionKeys() detailVC.setCellData(cellDataProvider.getAllData()) detailVC.objectToShow=gbe detailVC.title=cellDataProvider.getTitle() let icon=UIBarButtonItem() icon.image=GlyphTools.sharedInstance().getGlyphedImage(cellDataProvider.getDetailGlyphIconString()) detailVC.navigationItem.leftBarButtonItem = icon } if let actionProvider=gbe as? ActionProvider { detailVC.actions=actionProvider.getAllActions() let action = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.action, target: detailVC, action:#selector(DetailVC.moreAction)) detailVC.navigationItem.rightBarButtonItem = action } let detailNC=UINavigationController(rootViewController: detailVC) selectedAnnotation=nil mapView.deselectAnnotation(view.annotation, animated: false) detailNC.modalPresentationStyle = UIModalPresentationStyle.popover detailNC.popoverPresentationController?.sourceView = mapView detailNC.popoverPresentationController?.sourceRect = view.frame detailNC.popoverPresentationController?.permittedArrowDirections = UIPopoverArrowDirection.any present(detailNC, animated: true, completion: nil) } } func clearAll() { CidsConnector.sharedInstance().selectedArbeitsauftrag=nil CidsConnector.sharedInstance().allArbeitsauftraegeBeforeCurrentSelection=[Entity: [GeoBaseEntity]]() CidsConnector.sharedInstance().veranlassungsCache=[String:Veranlassung]() removeAllEntityObjects() } func removeAllEntityObjects(){ for (_, entityArray) in CidsConnector.sharedInstance().searchResults{ for obj in entityArray { DispatchQueue.main.async { obj.removeFromMapView(self.mapView); } } } CidsConnector.sharedInstance().searchResults=[Entity: [GeoBaseEntity]]() DispatchQueue.main.async { self.tableView.reloadData(); } } // MARK: - private funcs fileprivate func geoSearch(){ if matchingSearchItems.count>0 { self.mapView.removeAnnotations(self.matchingSearchItemsAnnotations) self.matchingSearchItems.removeAll(keepingCapacity: false) matchingSearchItemsAnnotations.removeAll(keepingCapacity: false) } let request = MKLocalSearchRequest() request.naturalLanguageQuery = "Wuppertal, \(textfieldGeoSearch.text!)" request.region = mapView.region let localSearch = MKLocalSearch(request: request) localSearch.start { (responseIn, errorIn) -> Void in if let error = errorIn { log.error("Error occured in search: \(error.localizedDescription)") } else if let response=responseIn { if response.mapItems.count == 0 { log.warning("No matches found") } else { log.verbose("Matches found") for item in response.mapItems as [MKMapItem] { self.matchingSearchItems.append(item as MKMapItem) log.verbose("Matching items = \(self.matchingSearchItems.count)") let annotation = MatchingSearchItemsAnnotations() annotation.coordinate = item.placemark.coordinate annotation.title = item.name self.matchingSearchItemsAnnotations.append(annotation) self.mapView.addAnnotation(annotation) } self.mapView.showAnnotations(self.matchingSearchItemsAnnotations, animated: true) } } } } fileprivate func ensureBrightOverlayIsDisplayedWhenItShould(){ if brightenToggle.isOn { let overlays=mapView.overlays mapView.removeOverlays(overlays) mapView.add(brightOverlay) mapView.addOverlays(overlays) } else { mapView.remove(brightOverlay) } } fileprivate func ensureFocusRectangleIsDisplayedWhenAndWhereItShould(){ focusRectShape.removeFromSuperlayer() if focusToggle.isOn { let path = UIBezierPath() let w = self.mapView.frame.width / 3 let h = self.mapView.frame.height / 3 let x1 = w let y1 = h let x2 = x1 + w let y2 = y1 let x3 = x2 let y3 = y2 + h let x4 = x1 let y4 = y3 path.move(to: CGPoint(x: x1, y: y1)) path.addLine(to: CGPoint(x: x2, y: y2)) path.addLine(to: CGPoint(x: x3, y: y3)) path.addLine(to: CGPoint(x: x4, y: y4)) path.close() focusRectShape.path = path.cgPath mapView.layer.addSublayer(focusRectShape) } } // func textFieldShouldReturn(textField: UITextField) -> Bool { // self.view.endEditing(true) // return false // } }
1a8a2b9fefb8f804d9c0a8068c7b0993
42.103226
277
0.600894
false
false
false
false
Pocketbrain/nativeadslib-ios
refs/heads/master
PocketMediaNativeAds/Core/adPosition/MarginAdPosition.swift
mit
1
// // MarginAdPosition.swift // PocketMediaNativeAds // // Created by Iain Munro on 04/10/2016. // // import Foundation /** Error this the MarginAdPosition can throw if asked for a position */ public enum MarginAdPositionError: Error { /// Invalid margin is set. case invalidmargin } /** This ad position implementation makes the ads show up at a set interval (margin). */ @objc open class MarginAdPosition: NSObject, AdPosition { /// The margin (interval). Every x amount of position place an ad. fileprivate var margin: Int = 2 /// The offset before an ad should appear. fileprivate var adPositionOffset: Int = -1 /// The current value the positioner is at. fileprivate var currentValue: Int = 0 /** Initializer. - parameter margin: The amount of entries before an ad. (default 2). - paramter adPositionOffset: The offset before an ad should appear. */ public init(margin: Int = 2, adPositionOffset: Int = 0) { super.init() self.margin = margin + 1 setadPositionOffset(adPositionOffset) reset() } /** Called every time the positions are calculated. It resets the ad positioner. */ open func reset() { self.currentValue = adPositionOffset } /** Generates a unique position (integer) of where a new ad should be located. - Returns: a unique integer of where a new ad should be located. - Important: This method throws if it can't return a unique position */ open func getAdPosition(_ maxSize: Int) throws -> NSNumber { if margin < 1 { throw MarginAdPositionError.invalidmargin } currentValue += margin return NSNumber(value: currentValue as Int) } /** Setter method to set self.adPositionOffset. - parameter position: The position of the first ad. Default is 0 */ open func setadPositionOffset(_ position: Int) { self.adPositionOffset = position < 0 ? 0 : position - 1 } }
bc9a517444849ca6c2bfb6db96ffe688
27.25
82
0.651917
false
false
false
false
srn214/Floral
refs/heads/master
Floral/Pods/SwiftLocation/Sources/Auto Complete/Services/GoogleAutoCompleteRequest.swift
mit
1
// // SwiftLocation - Efficient Location Tracking for iOS // // Created by Daniele Margutti // - Web: https://www.danielemargutti.com // - Twitter: https://twitter.com/danielemargutti // - Mail: [email protected] // // Copyright © 2019 Daniele Margutti. Licensed under MIT License. import Foundation public class GoogleAutoCompleteRequest: AutoCompleteRequest { // MARK: - Private Properties - /// JSON Operation private var jsonOperation: JSONOperation? // MARK: - Public Functions - public override func start() { guard state != .expired else { return } // Compose the request URL guard let url = composeURL() else { dispatch(data: .failure(.generic("Failed to compose valid request's URL."))) return } jsonOperation = JSONOperation(url, timeout: self.timeout?.interval) jsonOperation?.start { response in switch response { case .failure(let error): self.stop(reason: error, remove: true) case .success(let json): // Validate google response let status: String? = valueAtKeyPath(root: json, ["status"]) if status != "OK", let errorMsg: String = valueAtKeyPath(root: json, ["error_message"]), !errorMsg.isEmpty { self.stop(reason: .generic(errorMsg), remove: true) return } switch self.options!.operation { case .partialSearch: let places = self.parsePartialMatchJSON(json) self.dispatch(data: .success(places), andComplete: true) case .placeDetail: var places = [PlaceMatch]() if let resultNode: Any = valueAtKeyPath(root: json, ["result"]) { let place = Place(googleJSON: resultNode) places.append(.fullMatch(place)) } self.value = places self.dispatch(data: .success(places), andComplete: true) } } } } // MARK: - Private Helper Functions - private func parsePartialMatchJSON(_ json: Any) -> [PlaceMatch] { let rawList: [Any]? = valueAtKeyPath(root: json, ["predictions"]) let list: [PlaceMatch]? = rawList?.map({ rawItem in let place = PlacePartialMatch(googleJSON: rawItem) return PlaceMatch.partialMatch(place) }) return list ?? [] } private func composeURL() -> URL? { guard let APIKey = (options as? GoogleOptions)?.APIKey else { dispatch(data: .failure(.missingAPIKey)) return nil } var serverParams = [URLQueryItem]() var baseURL: URL! switch options!.operation { case .partialSearch: baseURL = URL(string: "https://maps.googleapis.com/maps/api/place/autocomplete/json")! serverParams.append(URLQueryItem(name: "input", value: options!.operation.value)) case .placeDetail: baseURL = URL(string: "https://maps.googleapis.com/maps/api/place/details/json")! serverParams.append(URLQueryItem(name: "placeid", value: options!.operation.value)) } var urlComponents = URLComponents(url: baseURL, resolvingAgainstBaseURL: false) serverParams.append(URLQueryItem(name: "key", value: APIKey)) // google api key serverParams += (options?.serverParams() ?? []) urlComponents?.queryItems = serverParams return urlComponents?.url } }
8091a8b37c6cf7e1bcec4f7e8991435f
35.269231
109
0.562831
false
false
false
false
XCEssentials/UniFlow
refs/heads/master
Sources/0_Helpers/Publisher+Dispatcher.swift
mit
1
/* MIT License Copyright (c) 2016 Maxim Khatskevich ([email protected]) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import Combine //--- public extension Publisher { func executeNow() { _ = sink(receiveCompletion: { _ in }, receiveValue: { _ in }) } } // MARK: - Access log - Processed vs. Rejected public extension Publisher where Output == Dispatcher.AccessReport, Failure == Never { var onProcessed: AnyPublisher<Dispatcher.ProcessedActionReport, Failure> { return self .compactMap { switch $0.outcome { case .success(let mutations): return .init( timestamp: $0.timestamp, mutations: mutations, storage: $0.storage, origin: $0.origin ) default: return nil } } .eraseToAnyPublisher() } var onRejected: AnyPublisher<Dispatcher.RejectedActionReport, Failure> { return self .compactMap { switch $0.outcome { case .failure(let reason): return .init( timestamp: $0.timestamp, reason: reason, storage: $0.storage, origin: $0.origin ) default: return nil } } .eraseToAnyPublisher() } } // MARK: - Access log - Processed - get individual mutations public extension Publisher where Output == Dispatcher.ProcessedActionReport, Failure == Never { var perEachMutation: AnyPublisher<Storage.HistoryElement, Failure> { flatMap(\.mutations.publisher).eraseToAnyPublisher() } } public extension Publisher where Output == Storage.HistoryElement, Failure == Never { func `as`<T: SomeMutationDecriptor>( _: T.Type ) -> AnyPublisher<T, Failure> { compactMap(T.init(from:)).eraseToAnyPublisher() } } // MARK: - Access log - Processed - get features statuses (dashboard) public extension Publisher where Output == Dispatcher.ProcessedActionReport, Failure == Never { var statusReport: AnyPublisher<[FeatureStatus], Failure> { self .filter { !$0.mutations.isEmpty } .map { $0.storage .allStates .map( FeatureStatus.init ) } .eraseToAnyPublisher() } } public extension Publisher where Output == [FeatureStatus], Failure == Never { func matched( with features: [SomeFeature.Type] ) -> AnyPublisher<Output, Failure> { self .map { existingStatuses in features .map { feature in existingStatuses .first(where: { if let state = $0.state { return type(of: state).feature.name == feature.name } else { return false } }) ?? .init(missing: feature) } } .eraseToAnyPublisher() } }
21cd2c3f87e96e29692358eccf20731e
28.544379
87
0.494092
false
false
false
false
wireapp/wire-ios
refs/heads/develop
Wire-iOS Tests/AudioRecordKeyboardViewControllerTests.swift
gpl-3.0
1
// // Wire // Copyright (C) 2016 Wire Swiss GmbH // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // import Foundation import XCTest @testable import Wire final class MockAudioRecordKeyboardDelegate: AudioRecordViewControllerDelegate { var didCancelHitCount = 0 func audioRecordViewControllerDidCancel(_ audioRecordViewController: AudioRecordBaseViewController) { didCancelHitCount += 1 } var didStartRecordingHitCount = 0 func audioRecordViewControllerDidStartRecording(_ audioRecordViewController: AudioRecordBaseViewController) { didStartRecordingHitCount += 1 } var wantsToSendAudioHitCount = 0 func audioRecordViewControllerWantsToSendAudio(_ audioRecordViewController: AudioRecordBaseViewController, recordingURL: URL, duration: TimeInterval, filter: AVSAudioEffectType) { wantsToSendAudioHitCount += 1 } } final class MockAudioRecorder: AudioRecorderType { var format: AudioRecorderFormat = .wav var state: AudioRecorderState = .initializing var fileURL: URL? = Bundle(for: MockAudioRecorder.self).url(forResource: "audio_sample", withExtension: "m4a") var maxRecordingDuration: TimeInterval? = 25 * 60 var maxFileSize: UInt64? = 25 * 1024 * 1024 - 32 var currentDuration: TimeInterval = 0.0 var recordTimerCallback: ((TimeInterval) -> Void)? var recordLevelCallBack: ((RecordingLevel) -> Void)? var playingStateCallback: ((PlayingState) -> Void)? var recordStartedCallback: (() -> Void)? var recordEndedCallback: ((VoidResult) -> Void)? var startRecordingHitCount = 0 func startRecording(_ completion: @escaping (Bool) -> Void) { state = .recording(start: 0) startRecordingHitCount += 1 completion(true) } var stopRecordingHitCount = 0 @discardableResult func stopRecording() -> Bool { state = .stopped stopRecordingHitCount += 1 return true } var deleteRecordingHitCount = 0 func deleteRecording() { deleteRecordingHitCount += 1 } var playRecordingHitCount = 0 func playRecording() { playRecordingHitCount += 1 } var stopPlayingHitCount = 0 func stopPlaying() { stopPlayingHitCount += 1 } func levelForCurrentState() -> RecordingLevel { return 0 } func durationForCurrentState() -> TimeInterval? { return 0 } func alertForRecording(error: RecordingError) -> UIAlertController? { return nil } } final class AudioRecordKeyboardViewControllerTests: XCTestCase { var sut: AudioRecordKeyboardViewController! var audioRecorder: MockAudioRecorder! var mockDelegate: MockAudioRecordKeyboardDelegate! override func setUp() { super.setUp() self.audioRecorder = MockAudioRecorder() self.mockDelegate = MockAudioRecordKeyboardDelegate() self.sut = AudioRecordKeyboardViewController(audioRecorder: self.audioRecorder) self.sut.delegate = self.mockDelegate } override func tearDown() { self.sut = nil self.audioRecorder = nil self.mockDelegate = nil super.tearDown() } func testThatItStartsRecordingWhenClickingRecordButton() { // when self.sut.recordButton.sendActions(for: .touchUpInside) // then XCTAssertEqual(self.audioRecorder.startRecordingHitCount, 1) XCTAssertEqual(self.audioRecorder.stopRecordingHitCount, 0) XCTAssertEqual(self.audioRecorder.deleteRecordingHitCount, 0) XCTAssertEqual(self.sut.state, AudioRecordKeyboardViewController.State.recording) XCTAssertEqual(self.mockDelegate.didStartRecordingHitCount, 1) } func testThatItStartsRecordingWhenClickingRecordArea() { // when self.sut.recordButtonPressed(self) // then XCTAssertEqual(self.audioRecorder.startRecordingHitCount, 1) XCTAssertEqual(self.audioRecorder.stopRecordingHitCount, 0) XCTAssertEqual(self.audioRecorder.deleteRecordingHitCount, 0) XCTAssertEqual(self.sut.state, AudioRecordKeyboardViewController.State.recording) XCTAssertEqual(self.mockDelegate.didStartRecordingHitCount, 1) } func testThatItStopsRecordingWhenClickingStopButton() { // when self.sut.recordButtonPressed(self) // and when self.sut.stopRecordButton.sendActions(for: .touchUpInside) // then XCTAssertEqual(self.audioRecorder.startRecordingHitCount, 1) XCTAssertEqual(self.audioRecorder.stopRecordingHitCount, 1) XCTAssertEqual(self.audioRecorder.deleteRecordingHitCount, 0) XCTAssertEqual(self.sut.state, AudioRecordKeyboardViewController.State.recording) XCTAssertEqual(self.mockDelegate.didStartRecordingHitCount, 1) } func testThatItSwitchesToEffectsScreenAfterRecord() { // when self.sut.recordButton.sendActions(for: .touchUpInside) // and when self.audioRecorder.recordEndedCallback!(.success) // then XCTAssertEqual(self.sut.state, AudioRecordKeyboardViewController.State.effects) } func testThatItSwitchesToRecordingAfterRecordDiscarded() { // when self.sut.recordButton.sendActions(for: .touchUpInside) // and when self.audioRecorder.recordEndedCallback!(.success) XCTAssertEqual(self.sut.state, AudioRecordKeyboardViewController.State.effects) // and when self.sut.redoButton.sendActions(for: .touchUpInside) // then XCTAssertEqual(self.sut.state, AudioRecordKeyboardViewController.State.ready) XCTAssertEqual(self.mockDelegate.didStartRecordingHitCount, 1) XCTAssertEqual(self.audioRecorder.deleteRecordingHitCount, 1) } func testThatItCallsErrorDelegateCallback() { // when self.sut.recordButton.sendActions(for: .touchUpInside) // and when self.audioRecorder.recordEndedCallback!(.success) XCTAssertEqual(self.sut.state, AudioRecordKeyboardViewController.State.effects) // and when self.sut.cancelButton.sendActions(for: .touchUpInside) // then XCTAssertEqual(self.mockDelegate.didStartRecordingHitCount, 1) XCTAssertEqual(self.mockDelegate.didCancelHitCount, 1) } }
e7670d33609e07451913c1bd03bd986a
33.615
183
0.712552
false
false
false
false
gintsmurans/SwiftCollection
refs/heads/master
Examples/ApiRouter.swift
mit
2
// // ApiRouter.swift // // Created by Gints Murans on 15.08.16. // Copyright © 2016. g. 4Apps. All rights reserved. // import Foundation import Alamofire import NetworkExtension enum ApiRouter: URLRequestConvertible { case authorize() case users() case units case unitDetails(eanCode: String) case findPallet(palletNumber: String) case upload(data: [String: Any]) static let baseURLString = "https://\(Config.api.domain)" var method: HTTPMethod { switch self { // GET case .authorize: fallthrough case .users: return .get // POST case .upload: return .post } } var path: String { switch self { case .authorize: return "/settings/auth/basic" case .users: return "/inventory/api/users" case .upload: return "/inventory/api/upload" } } var describing: String { return urlString } var urlString: String { return "\(ApiRouter.baseURLString)\(path)" } func asURLRequest() throws -> URLRequest { let url = try ApiRouter.baseURLString.asURL() var urlRequest = URLRequest(url: url.appendingPathComponent(path)) urlRequest.httpMethod = method.rawValue switch self { case .upload(let data): urlRequest = try URLEncoding.default.encode(urlRequest, with: data) default: break } return urlRequest } } var unitsCache = CacheObject(name: "ApiUnits") extension Api { func loadUsers(callback: ApiCallback? = nil) { // Request let innerCallback: ApiCallback = { (data, error) in if let error = error { if let callback = callback { callback(nil, error) } return } self.request(ApiRouter.users()) { (data, error) in if error != nil { if let callback = callback { callback(nil, error) } return } guard let dataC = data as? [String: Any] else { print(data!) if let callback = callback { callback(nil, ApiError.apiGeneralError(message: "There was an Unknown issue with data", url: nil)) } return } guard let items = dataC["items"] as? [[String: Any]] else { if let callback = callback { callback(nil, ApiError.apiGeneralError(message: "There was an Unknown issue with data", url: nil)) } return } if let callback = callback { callback(items, nil) } } } // Authenticate first then call all those callbacks self.authenticateNetworkManager(innerCallback) } func upload(_ postData: [String: Any], callback: ApiCallback?) { // Request let innerCallback: ApiCallback = { (data, error) in if let error = error { if let callback = callback { callback(nil, error) } return } self.request(ApiRouter.upload(data: postData), returnType: .json, callback: { (data, error) in guard let callback = callback else { return } if error != nil { callback(nil, error) return } callback(data, nil) }) } // Authenticate first then call all those callbacks self.authenticateNetworkManager(innerCallback) } }
46613d58ece7ee9c1d02fcbd5b0c6dfd
25.821918
122
0.501788
false
false
false
false
jalehman/todolist-mvvm
refs/heads/master
todolist-mvvm/TodoTableViewModel.swift
mit
1
// // TodoListViewModel.swift // todolist-mvvm // // Created by Josh Lehman on 11/6/15. // Copyright © 2015 JL. All rights reserved. // import Foundation import ReactiveCocoa class TodoTableViewModel: ViewModel { // MARK: Properties let todos = MutableProperty<[TodoCellViewModel]>([]) let presentCreateTodo: Action<(), CreateTodoViewModel, NoError> let deleteTodo: Action<(todos: [TodoCellViewModel], cell: TodoCellViewModel), NSIndexPath?, NoError> // MARK: API override init(services: ViewModelServicesProtocol) { self.presentCreateTodo = Action { () -> SignalProducer<CreateTodoViewModel, NoError> in return SignalProducer(value: CreateTodoViewModel(services: services)) } self.deleteTodo = Action { (todos: [TodoCellViewModel], cell: TodoCellViewModel) -> SignalProducer<NSIndexPath?, NoError> in let deleteIndex = todos.indexOf { x -> Bool in return x.todo == cell.todo } if let idx = deleteIndex { return services.todo.delete(cell.todo) .map { _ in NSIndexPath(forRow: idx, inSection: 0) } } return SignalProducer(value: nil) } let createdTodoSignal = presentCreateTodo.values .flatMap(.Latest) { (vm: CreateTodoViewModel) -> Signal<Todo, NoError> in return vm.create.values } // When "presentCreateTodo" sends a value, push the resulting ViewModel presentCreateTodo.values.observeNext(services.push) // When "cancel" sends a value from inside CreateTodoViewModel, pop presentCreateTodo.values .flatMap(.Latest) { vm in vm.cancel.values.map { _ in vm } } .observeNext(services.pop) // When "create" sends a value from inside CreateTodoViewModel, pop presentCreateTodo.values .flatMap(.Latest) { vm in vm.create.values.map { _ in vm } } .observeNext(services.pop) super.init(services: services) func prependTodo(todo: Todo) -> [TodoCellViewModel] { let new = TodoCellViewModel(services: services, todo: todo) var tmp = todos.value tmp.insert(new, atIndex: 0) return tmp } // Whenever a todo is created, create a new viewmodel for it, prepend it to the latest array of todos, and bind the result to todos todos <~ createdTodoSignal.map(prependTodo) func removeTodo(at: NSIndexPath?) -> [TodoCellViewModel] { var tmp = todos.value tmp.removeAtIndex(at!.row) return tmp } // Whenever a todo is deleted, remove it from the backing array todos <~ deleteTodo.values.filter { $0 != nil }.map(removeTodo) } func clearCompleted() { for todo in todos.value { if todo.completed.value { deleteTodo.apply((todos: todos.value, cell: todo)).start() } } } }
6c095bccea4553f6961c42fc6832fc47
34.426966
139
0.58915
false
false
false
false
jindulys/Wikipedia
refs/heads/master
Wikipedia/Code/WMFTableOfContentsViewController.swift
mit
1
import UIKit public protocol WMFTableOfContentsViewControllerDelegate : AnyObject { /** Notifies the delegate that the controller will display Use this to update the ToC if needed */ func tableOfContentsControllerWillDisplay(controller: WMFTableOfContentsViewController) /** The delegate is responsible for dismissing the view controller */ func tableOfContentsController(controller: WMFTableOfContentsViewController, didSelectItem item: TableOfContentsItem) /** The delegate is responsible for dismissing the view controller */ func tableOfContentsControllerDidCancel(controller: WMFTableOfContentsViewController) func tableOfContentsArticleSite() -> MWKSite } public class WMFTableOfContentsViewController: UITableViewController, WMFTableOfContentsAnimatorDelegate { let tableOfContentsFunnel: ToCInteractionFunnel var items: [TableOfContentsItem] { didSet{ self.tableView.reloadData() } } //optional becuase it requires a reference to self to inititialize var animator: WMFTableOfContentsAnimator? weak var delegate: WMFTableOfContentsViewControllerDelegate? // MARK: - Init public required init(presentingViewController: UIViewController, items: [TableOfContentsItem], delegate: WMFTableOfContentsViewControllerDelegate) { self.items = items self.delegate = delegate tableOfContentsFunnel = ToCInteractionFunnel() super.init(nibName: nil, bundle: nil) self.animator = WMFTableOfContentsAnimator(presentingViewController: presentingViewController, presentedViewController: self) self.animator?.delegate = self modalPresentationStyle = .Custom transitioningDelegate = self.animator } public required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - Sections func indexPathForItem(item: TableOfContentsItem) -> NSIndexPath? { if let row = items.indexOf({ item.isEqual($0) }) { return NSIndexPath(forRow: row, inSection: 0) } else { return nil } } public func selectAndScrollToItem(atIndex index: Int, animated: Bool) { selectAndScrollToItem(items[index], animated: animated) } public func selectAndScrollToItem(item: TableOfContentsItem, animated: Bool) { guard let indexPath = indexPathForItem(item) else { fatalError("No indexPath known for TOC item \(item)") } deselectAllRows() tableView.selectRowAtIndexPath(indexPath, animated: animated, scrollPosition: UITableViewScrollPosition.Top) addHighlightOfItemsRelatedTo(item, animated: false) } // MARK: - Selection public func deselectAllRows() { guard let selectedIndexPaths = tableView.indexPathsForSelectedRows else { return } for (_, element) in selectedIndexPaths.enumerate() { if let cell: WMFTableOfContentsCell = tableView.cellForRowAtIndexPath(element) as? WMFTableOfContentsCell { cell.setSectionSelected(false, animated: false) } } } public func addHighlightOfItemsRelatedTo(item: TableOfContentsItem, animated: Bool) { guard let visibleIndexPaths = tableView.indexPathsForVisibleRows else { return } for (_, indexPath) in visibleIndexPaths.enumerate() { if let otherItem: TableOfContentsItem = items[indexPath.row], cell: WMFTableOfContentsCell = tableView.cellForRowAtIndexPath(indexPath) as? WMFTableOfContentsCell { cell.setSectionSelected(otherItem.shouldBeHighlightedAlongWithItem(item), animated: animated) } } } // MARK: - Header func forceUpdateHeaderFrame(){ //See reason for fix here: http://stackoverflow.com/questions/16471846/is-it-possible-to-use-autolayout-with-uitableviews-tableheaderview self.tableView.tableHeaderView!.setNeedsLayout() self.tableView.tableHeaderView!.layoutIfNeeded() let headerHeight = self.tableView.tableHeaderView!.systemLayoutSizeFittingSize(UILayoutFittingCompressedSize).height var headerFrame = self.tableView.tableHeaderView!.frame; headerFrame.size.height = headerHeight self.tableView.tableHeaderView!.frame = headerFrame; self.tableView.tableHeaderView = self.tableView.tableHeaderView } // MARK: - UIViewController public override func viewDidLoad() { super.viewDidLoad() let header = WMFTableOfContentsHeader.wmf_viewFromClassNib() assert(delegate != nil, "TOC delegate not set!") header.articleSite = delegate?.tableOfContentsArticleSite() self.tableView.tableHeaderView = header tableView.registerNib(WMFTableOfContentsCell.wmf_classNib(), forCellReuseIdentifier: WMFTableOfContentsCell.reuseIdentifier()) clearsSelectionOnViewWillAppear = false tableView.estimatedRowHeight = 44.0 tableView.rowHeight = UITableViewAutomaticDimension automaticallyAdjustsScrollViewInsets = false tableView.contentInset = UIEdgeInsetsMake(UIApplication.sharedApplication().statusBarFrame.size.height, 0, 0, 0) tableView.separatorStyle = .None } public override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) self.forceUpdateHeaderFrame() self.delegate?.tableOfContentsControllerWillDisplay(self) tableOfContentsFunnel.logOpen() } public override func viewDidDisappear(animated: Bool) { super.viewDidDisappear(animated) deselectAllRows() } public override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) { coordinator.animateAlongsideTransition({ (context) -> Void in self.forceUpdateHeaderFrame() }) { (context) -> Void in } } // MARK: - UITableViewDataSource public override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return items.count } public override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier(WMFTableOfContentsCell.reuseIdentifier(), forIndexPath: indexPath) as! WMFTableOfContentsCell let selectedItems: [TableOfContentsItem] = tableView.indexPathsForSelectedRows?.map() { items[$0.row] } ?? [] let item = items[indexPath.row] let shouldHighlight = selectedItems.reduce(false) { shouldHighlight, selectedItem in shouldHighlight || item.shouldBeHighlightedAlongWithItem(selectedItem) } cell.setItem(item) cell.setSectionSelected(shouldHighlight, animated: false) return cell } // MARK: - UITableViewDelegate public override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let item = items[indexPath.row] deselectAllRows() tableOfContentsFunnel.logClick() addHighlightOfItemsRelatedTo(item, animated: true) delegate?.tableOfContentsController(self, didSelectItem: item) } public func tableOfContentsAnimatorDidTapBackground(controller: WMFTableOfContentsAnimator) { tableOfContentsFunnel.logClose() delegate?.tableOfContentsControllerDidCancel(self) } }
15e63af911d5ccf9fcd2c44619e29231
40.139785
156
0.705044
false
false
false
false
SaberVicky/LoveStory
refs/heads/master
LoveStory/Feature/Publish/LSPublishViewController.swift
mit
1
// // LSPublishViewController.swift // LoveStory // // Created by songlong on 2016/12/29. // Copyright © 2016年 com.Saber. All rights reserved. // import UIKit import SnapKit import SVProgressHUD import Qiniu class LSPublishViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate { var toolBar: UIView! var editTextView = UITextView() var imgSelectButton = UIButton() var recordSoundButton = UIButton() var recordVideoButton = UIButton() var publishImgUrl: String? override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor(red: 240 / 255.0, green: 240 / 255.0, blue: 240 / 255.0, alpha: 1) title = "新建" navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发布", style: .plain, target: self, action: #selector(LSPublishViewController.publish)) setupUI() NotificationCenter.default.addObserver(self, selector: #selector(keyBoardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(keyBoardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil) } func keyBoardWillShow(note: Notification) { let durationT = 0.25 let deltaY = 216 let animations:(() -> Void) = { self.toolBar.transform = CGAffineTransform(translationX: 0,y: -(CGFloat)(deltaY)-30) } let options : UIViewAnimationOptions = UIViewAnimationOptions(rawValue: 7) UIView.animate(withDuration: durationT, delay: 0, options:options, animations: animations, completion: nil) } func keyBoardWillHide() { } func publish() { let account = LSUser.currentUser()?.user_account var params: [String : String?] if publishImgUrl != nil { params = ["user_account": account, "publish_text" : editTextView.text, "img_url": publishImgUrl] } else { params = ["user_account": account, "publish_text" : editTextView.text] } LSNetworking.sharedInstance.request(method: .GET, URLString: API_PUBLISH, parameters: params, success: { (task, responseObject) in SVProgressHUD.showSuccess(withStatus: "发布成功") }, failure: { (task, error) in SVProgressHUD.showError(withStatus: "发布失败") }) } func setupUI() { editTextView.backgroundColor = .lightGray editTextView.font = UIFont.systemFont(ofSize: 18) editTextView.autocorrectionType = .no editTextView.autocapitalizationType = .none imgSelectButton.setTitle("选择图片", for: .normal) imgSelectButton.setTitleColor(.black, for: .normal) imgSelectButton.addTarget(self, action: #selector(LSPublishViewController.gotoImageLibrary), for: .touchUpInside) recordSoundButton.setTitle("录音", for: .normal) recordSoundButton.setTitleColor(.black, for: .normal) recordSoundButton.addTarget(self, action: #selector(LSPublishViewController.gotoRecord), for: .touchUpInside) recordVideoButton.setTitle("录像", for: .normal) recordVideoButton.setTitleColor(.black, for: .normal) recordVideoButton.addTarget(self, action: #selector(LSPublishViewController.gotoRecordVideo), for: .touchUpInside) view.addSubview(editTextView) view.addSubview(imgSelectButton) view.addSubview(recordSoundButton) view.addSubview(recordVideoButton) editTextView.snp.makeConstraints { (make) in make.top.left.right.equalTo(0) make.height.equalTo(self.view).multipliedBy(0.5) } imgSelectButton.snp.makeConstraints { (make) in make.centerX.equalTo(self.view) make.top.equalTo(editTextView.snp.bottom).offset(20) } recordSoundButton.snp.makeConstraints { (make) in make.centerX.equalTo(self.view) make.top.equalTo(imgSelectButton.snp.bottom).offset(20) } recordVideoButton.snp.makeConstraints { (make) in make.centerX.equalTo(self.view) make.top.equalTo(recordSoundButton.snp.bottom).offset(20) } toolBar = UIView(frame: CGRect(x: 0, y: LSHeight - 30 - 66, width: LSWidth, height: 30)) toolBar.backgroundColor = .black view.addSubview(toolBar) } func gotoRecordVideo() { navigationController?.pushViewController(LSRecordVideoViewController(), animated: true) } func gotoRecord() { navigationController?.pushViewController(LSRecordSoundViewController(), animated: true) } func gotoImageLibrary() { if UIImagePickerController.isSourceTypeAvailable(.photoLibrary) { let imgPicker = UIImagePickerController() imgPicker.sourceType = .photoLibrary imgPicker.delegate = self present(imgPicker, animated: true, completion: nil) } else { let alert = UIAlertController(title: "", message: nil, preferredStyle: .alert) present(alert, animated: true, completion: nil) } } func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { picker.dismiss(animated:true, completion:nil) let img = info[UIImagePickerControllerOriginalImage] as? UIImage let icon = UIImageView(image: img) view.addSubview(icon) icon.snp.makeConstraints { (make) in make.top.left.equalTo(0) make.width.height.equalTo(UIScreen.main.bounds.size.width / 2) } LSNetworking.sharedInstance.request(method: .GET, URLString: API_GET_QINIU_PARAMS, parameters: nil, success: { (task, responseObject) in let config = QNConfiguration.build({ (builder) in builder?.setZone(QNZone.zone1()) }) let dic = responseObject as! NSDictionary let token : String = dic["token"] as! String let key : String = dic["key"] as! String self.publishImgUrl = dic["img_url"] as? String let option = QNUploadOption(progressHandler: { (key, percent) in LSPrint("percent = \(percent)") }) let upManager = QNUploadManager(configuration: config) upManager?.putFile(self.getImagePath(image: img!), key: key, token: token, complete: { (info, key, resp) in if (info?.isOK)! { LSPrint("上传成功") self.publish() } else { SVProgressHUD.showError(withStatus: "上传失败") LSPrint("上传失败") } LSPrint(info) LSPrint(resp) }, option: option) }, failure: { (task, error) in print(error) }) } func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { picker.dismiss(animated: true, completion: nil) } func getImagePath(image: UIImage) -> String { var data: Data? // if UIImagePNGRepresentation(image) == nil { // data = UIImageJPEGRepresentation(image, 0.3) // } else { // data = UIImagePNGRepresentation(image) // } data = UIImageJPEGRepresentation(image, 0.3) let documentsPath = NSHomeDirectory().appending("/Documents") let manager = FileManager.default do { try manager.createDirectory(at: URL(string: documentsPath)!, withIntermediateDirectories: true, attributes: nil) } catch let error as NSError { LSPrint(error.localizedDescription) } let path = documentsPath.appending("/theImage.jpg") manager.createFile(atPath: path, contents: data, attributes: nil) return path } }
047a4b58c8a3f543d3392ad1f4f55936
34.957082
153
0.599905
false
false
false
false
jianghongbing/APIReferenceDemo
refs/heads/master
UIKit/UIPresentationController/UIPresentationController/ViewController.swift
mit
1
// // ViewController.swift // UIPresentationController // // Created by pantosoft on 2018/7/27. // Copyright © 2018年 jianghongbing. All rights reserved. // import UIKit class ViewController: UIViewController { var customTransitioningDelegate: UIViewControllerTransitioningDelegate? @IBAction func buttonTapped(_ sender: Any) { let storyboard = UIStoryboard(name: "Main", bundle: nil) let destinationViewController = storyboard.instantiateViewController(withIdentifier: "destinationViewController") let presentationController = PresentationController(presentedViewController: destinationViewController, presenting: self) customTransitioningDelegate = presentationController destinationViewController.transitioningDelegate = presentationController destinationViewController.modalPresentationStyle = .custom present(destinationViewController, animated: true, completion: nil) } }
15c052b2e808f7dd53405657a576adbc
40.391304
129
0.777311
false
false
false
false
ewhitley/CDAKit
refs/heads/master
CDAKit/health-data-standards/lib/import/c32/c32_care_goal_importer.swift
mit
1
// // immunization_importer.swift // CDAKit // // Created by Eric Whitley on 1/21/16. // Copyright © 2016 Eric Whitley. All rights reserved. // import Foundation import Fuzi class CDAKImport_C32_CareGoalImporter: CDAKImport_CDA_SectionImporter { override init(entry_finder: CDAKImport_CDA_EntryFinder = CDAKImport_CDA_EntryFinder(entry_xpath: "//cda:section[cda:templateId/@root='2.16.840.1.113883.3.88.11.83.124']/cda:entry/cda:*[cda:templateId/@root='2.16.840.1.113883.10.20.1.25']")) { super.init(entry_finder: entry_finder) entry_class = CDAKEntry.self } // NOTE this returns a generic "CDAKEntry" - but it could be any number of sub-types override func create_entry(goal_element: XMLElement, nrh: CDAKImport_CDA_NarrativeReferenceHandler = CDAKImport_CDA_NarrativeReferenceHandler()) -> CDAKEntry? { //original Ruby used "name" - which is "node_name" //looks like Fuzi calls this "tag" var importer: CDAKImport_CDA_SectionImporter switch goal_element.tag! { case "observation": importer = CDAKImport_CDA_ResultImporter() case "supply": importer = CDAKImport_CDA_MedicalEquipmentImporter() case "substanceAdministration": importer = CDAKImport_CDA_MedicationImporter() case "encounter": importer = CDAKImport_CDA_EncounterImporter() case "procedure": importer = CDAKImport_CDA_ProcedureImporter() //this bit here - not in the original Ruby - added our own entry_finder into the mix... //was originally sending nil arguments default: importer = CDAKImport_CDA_SectionImporter(entry_finder: self.entry_finder) //#don't need entry xpath, since we already have the entry } if let care_goal = importer.create_entry(goal_element, nrh: nrh) { extract_negation(goal_element, entry: care_goal) return care_goal } return nil } }
127daa4a4306ca559f519cc1911ba55d
41.295455
244
0.712903
false
false
false
false
RamonGilabert/Walker
refs/heads/master
Source/Constructors/Spring.swift
mit
1
import UIKit /** Spring starts a series of blocks of spring animations, it can have multiple parameters. - Parameter delay: The delay that this chain should wait to be triggered. - Parameter spring: The value of the spring in the animation. - Parameter friction: The value of the friction that the layer will present. - Parameter mass: The value of the mass of the layer. - Parameter tolerance: The tolerance that will default to 0.0001. - Returns: A series of ingredients that you can configure with all the animatable properties. */ @discardableResult public func spring(_ view: UIView, delay: TimeInterval = 0, spring: CGFloat, friction: CGFloat, mass: CGFloat, tolerance: CGFloat = 0.0001, kind: Animation.Spring = .spring, animations: (Ingredient) -> Void) -> Distillery { let builder = constructor([view], delay, spring, friction, mass, tolerance, kind) animations(builder.ingredients[0]) validate(builder.distillery) return builder.distillery } /** Spring starts a series of blocks of spring animations, it can have multiple parameters. - Parameter delay: The delay that this chain should wait to be triggered. - Parameter spring: The value of the spring in the animation. - Parameter friction: The value of the friction that the layer will present. - Parameter mass: The value of the mass of the layer. - Parameter tolerance: The tolerance that will default to 0.0001. - Returns: A series of ingredients that you can configure with all the animatable properties. */ @discardableResult public func spring(_ firstView: UIView, _ secondView: UIView, delay: TimeInterval = 0, spring: CGFloat, friction: CGFloat, mass: CGFloat, tolerance: CGFloat = 0.0001, kind: Animation.Spring = .spring, animations: (Ingredient, Ingredient) -> Void) -> Distillery { let builder = constructor([firstView, secondView], delay, spring, friction, mass, tolerance, kind) animations(builder.ingredients[0], builder.ingredients[1]) validate(builder.distillery) return builder.distillery } /** Spring starts a series of blocks of spring animations, it can have multiple parameters. - Parameter delay: The delay that this chain should wait to be triggered. - Parameter spring: The value of the spring in the animation. - Parameter friction: The value of the friction that the layer will present. - Parameter mass: The value of the mass of the layer. - Parameter tolerance: The tolerance that will default to 0.0001. - Returns: A series of ingredients that you can configure with all the animatable properties. */ @discardableResult public func spring(_ firstView: UIView, _ secondView: UIView, _ thirdView: UIView, delay: TimeInterval = 0, spring: CGFloat, friction: CGFloat, mass: CGFloat, tolerance: CGFloat = 0.0001, kind: Animation.Spring = .spring , animations: (Ingredient, Ingredient, Ingredient) -> Void) -> Distillery { let builder = constructor([firstView, secondView, thirdView], delay, spring, friction, mass, tolerance, kind) animations(builder.ingredients[0], builder.ingredients[1], builder.ingredients[2]) validate(builder.distillery) return builder.distillery } @discardableResult private func constructor(_ views: [UIView], _ delay: TimeInterval, _ spring: CGFloat, _ friction: CGFloat, _ mass: CGFloat, _ tolerance: CGFloat, _ calculation: Animation.Spring) -> (ingredients: [Ingredient], distillery: Distillery) { let distillery = Distillery() var ingredients: [Ingredient] = [] views.forEach { ingredients.append(Ingredient(distillery: distillery, view: $0, spring: spring, friction: friction, mass: mass, tolerance: tolerance, calculation: calculation)) } distillery.delays.append(delay) distillery.ingredients = [ingredients] return (ingredients: ingredients, distillery: distillery) } private func validate(_ distillery: Distillery) { var shouldProceed = true distilleries.forEach { if let ingredients = $0.ingredients.first, let ingredient = ingredients.first , ingredient.finalValues.isEmpty { shouldProceed = false return } } distillery.shouldProceed = shouldProceed if shouldProceed { distilleries.append(distillery) distillery.animate() } }
18da306fe854f264c7ef8a5d1a5dde6f
40.588235
155
0.740217
false
false
false
false
KevinCoble/AIToolbox
refs/heads/master
Playgrounds/NeuralNetwork.playground/Sources/LSTMNeuralNetwork.swift
apache-2.0
2
// // LSTMNeuralNetwork.swift // AIToolbox // // Created by Kevin Coble on 5/20/16. // Copyright © 2016 Kevin Coble. All rights reserved. // import Foundation import Accelerate final class LSTMNeuralNode { // Activation function let activation : NeuralActivationFunction let numInputs : Int let numFeedback : Int // Weights let numWeights : Int // This includes weights from inputs and from feedback for input, forget, cell, and output var Wi : [Double] var Ui : [Double] var Wf : [Double] var Uf : [Double] var Wc : [Double] var Uc : [Double] var Wo : [Double] var Uo : [Double] var h : Double // Last result calculated var outputHistory : [Double] // History of output for the sequence var lastCellState : Double // Last cell state calculated var cellStateHistory : [Double] // History of cell state for the sequence var ho : Double // Last output gate calculated var outputGateHistory : [Double] // History of output gate result for the sequence var hc : Double var memoryCellHistory : [Double] // History of cell activation result for the sequence var hi : Double // Last input gate calculated var inputGateHistory : [Double] // History of input gate result for the sequence var hf : Double // Last forget gate calculated var forgetGateHistory : [Double] // History of forget gate result for the sequence var 𝟃E𝟃h : Double // Gradient in error with respect to output of this node for this time step plus future time steps var 𝟃E𝟃zo : Double // Gradient in error with respect to weighted sum of the output gate var 𝟃E𝟃zi : Double // Gradient in error with respect to weighted sum of the input gate var 𝟃E𝟃zf : Double // Gradient in error with respect to weighted sum of the forget gate var 𝟃E𝟃zc : Double // Gradient in error with respect to weighted sum of the memory cell var 𝟃E𝟃cellState : Double // Gradient in error with respect to state of the memory cell var 𝟃E𝟃Wi : [Double] var 𝟃E𝟃Ui : [Double] var 𝟃E𝟃Wf : [Double] var 𝟃E𝟃Uf : [Double] var 𝟃E𝟃Wc : [Double] var 𝟃E𝟃Uc : [Double] var 𝟃E𝟃Wo : [Double] var 𝟃E𝟃Uo : [Double] var rmspropDecay : Double? // Decay rate for rms prop weight updates. If nil, rmsprop is not used /// Create the LSTM neural network node with a set activation function init(numInputs : Int, numFeedbacks : Int, activationFunction: NeuralActivationFunction) { activation = activationFunction self.numInputs = numInputs + 1 // Add one weight for the bias term self.numFeedback = numFeedbacks // Weights numWeights = (self.numInputs + self.numFeedback) * 4 // input, forget, cell and output all have weights Wi = [] Ui = [] Wf = [] Uf = [] Wc = [] Uc = [] Wo = [] Uo = [] h = 0.0 outputHistory = [] lastCellState = 0.0 cellStateHistory = [] ho = 0.0 outputGateHistory = [] hc = 0.0 memoryCellHistory = [] hi = 0.0 inputGateHistory = [] hf = 0.0 forgetGateHistory = [] 𝟃E𝟃h = 0.0 𝟃E𝟃zo = 0.0 𝟃E𝟃zi = 0.0 𝟃E𝟃zf = 0.0 𝟃E𝟃zc = 0.0 𝟃E𝟃cellState = 0.0 𝟃E𝟃Wi = [] 𝟃E𝟃Ui = [] 𝟃E𝟃Wf = [] 𝟃E𝟃Uf = [] 𝟃E𝟃Wc = [] 𝟃E𝟃Uc = [] 𝟃E𝟃Wo = [] 𝟃E𝟃Uo = [] } // Initialize the weights func initWeights(_ startWeights: [Double]!) { if let startWeights = startWeights { if (startWeights.count == 1) { Wi = [Double](repeating: startWeights[0], count: numInputs) Ui = [Double](repeating: startWeights[0], count: numFeedback) Wf = [Double](repeating: startWeights[0], count: numInputs) Uf = [Double](repeating: startWeights[0], count: numFeedback) Wc = [Double](repeating: startWeights[0], count: numInputs) Uc = [Double](repeating: startWeights[0], count: numFeedback) Wo = [Double](repeating: startWeights[0], count: numInputs) Uo = [Double](repeating: startWeights[0], count: numFeedback) } else if (startWeights.count == (numInputs+numFeedback) * 4) { // Full weight array, just split into the eight weight arrays var index = 0 Wi = Array(startWeights[index..<index+numInputs]) index += numInputs Ui = Array(startWeights[index..<index+numFeedback]) index += numFeedback Wf = Array(startWeights[index..<index+numInputs]) index += numInputs Uf = Array(startWeights[index..<index+numFeedback]) index += numFeedback Wc = Array(startWeights[index..<index+numInputs]) index += numInputs Uc = Array(startWeights[index..<index+numFeedback]) index += numFeedback Wo = Array(startWeights[index..<index+numInputs]) index += numInputs Uo = Array(startWeights[index..<index+numFeedback]) index += numFeedback } else { // Get the weights and bias start indices let numValues = startWeights.count var inputStart : Int var forgetStart : Int var cellStart : Int var outputStart : Int var sectionLength : Int if ((numValues % 4) == 0) { // Evenly divisible by 4, pass each quarter sectionLength = numValues / 4 inputStart = 0 forgetStart = sectionLength cellStart = sectionLength * 2 outputStart = sectionLength * 3 } else { // Use the values for all sections inputStart = 0 forgetStart = 0 cellStart = 0 outputStart = 0 sectionLength = numValues } Wi = [] var index = inputStart // Last number (if more than 1) goes into the bias weight, then repeat the initial for _ in 0..<numInputs-1 { if (index >= sectionLength-1) { index = inputStart } // Wrap if necessary Wi.append(startWeights[index]) index += 1 } Wi.append(startWeights[inputStart + sectionLength - 1]) // Add the bias term Ui = [] for _ in 0..<numFeedback { if (index >= sectionLength-1) { index = inputStart } // Wrap if necessary Ui.append(startWeights[index]) index += 1 } index = forgetStart Wf = [] for _ in 0..<numInputs-1 { if (index >= sectionLength-1) { index = forgetStart } // Wrap if necessary Wi.append(startWeights[index]) index += 1 } Wf.append(startWeights[forgetStart + sectionLength - 1]) // Add the bias term Uf = [] for _ in 0..<numFeedback { if (index >= sectionLength-1) { index = forgetStart } // Wrap if necessary Uf.append(startWeights[index]) index += 1 } index = cellStart Wc = [] for _ in 0..<numInputs-1 { if (index >= sectionLength-1) { index = cellStart } // Wrap if necessary Wc.append(startWeights[index]) index += 1 } Wc.append(startWeights[cellStart + sectionLength - 1]) // Add the bias term Uc = [] for _ in 0..<numFeedback { if (index >= sectionLength-1) { index = cellStart } // Wrap if necessary Uc.append(startWeights[index]) index += 1 } index = outputStart Wo = [] for _ in 0..<numInputs-1 { if (index >= sectionLength-1) { index = outputStart } // Wrap if necessary Wo.append(startWeights[index]) index += 1 } Wo.append(startWeights[outputStart + sectionLength - 1]) // Add the bias term Uo = [] for _ in 0..<numFeedback { if (index >= sectionLength-1) { index = outputStart } // Wrap if necessary Uo.append(startWeights[index]) index += 1 } } } else { Wi = [] for _ in 0..<numInputs-1 { Wi.append(Gaussian.gaussianRandom(0.0, standardDeviation: 1.0 / Double(numInputs-1))) // input weights - Initialize to a random number to break initial symmetry of the network, scaled to the inputs } Wi.append(Gaussian.gaussianRandom(-2.0, standardDeviation:1.0)) // Bias weight - Initialize to a negative number to have inputs learn to feed in Ui = [] for _ in 0..<numFeedback { Ui.append(Gaussian.gaussianRandom(0.0, standardDeviation: 1.0 / Double(numFeedback))) // feedback weights - Initialize to a random number to break initial symmetry of the network, scaled to the inputs } Wf = [] for _ in 0..<numInputs-1 { Wf.append(Gaussian.gaussianRandom(0.0, standardDeviation: 1.0 / Double(numInputs-1))) // input weights - Initialize to a random number to break initial symmetry of the network, scaled to the inputs } Wf.append(Gaussian.gaussianRandom(2.0, standardDeviation:1.0)) // Bias weight - Initialize to a positive number to turn off forget (output close to 1) until it 'learns' to forget Uf = [] for _ in 0..<numFeedback { Uf.append(Gaussian.gaussianRandom(0.0, standardDeviation: 1.0 / Double(numFeedback))) // feedback weights - Initialize to a random number to break initial symmetry of the network, scaled to the inputs } Wc = [] for _ in 0..<numInputs-1 { Wc.append(Gaussian.gaussianRandom(0.0, standardDeviation: 1.0 / Double(numInputs-1))) // input weights - Initialize to a random number to break initial symmetry of the network, scaled to the inputs } Wc.append(Gaussian.gaussianRandom(0.0, standardDeviation:1.0)) // Bias weight - Initialize to a random number to break initial symmetry of the network Uc = [] for _ in 0..<numFeedback { Uc.append(Gaussian.gaussianRandom(0.0, standardDeviation: 1.0 / Double(numFeedback))) // feedback weights - Initialize to a random number to break initial symmetry of the network, scaled to the inputs } Wo = [] for _ in 0..<numInputs-1 { Wo.append(Gaussian.gaussianRandom(0.0, standardDeviation: 1.0 / Double(numInputs-1))) // input weights - Initialize to a random number to break initial symmetry of the network, scaled to the inputs } Wo.append(Gaussian.gaussianRandom(-2.0, standardDeviation:1.0)) // Bias weight - Initialize to a negative number to limit output until network learns when output is needed Uo = [] for _ in 0..<numFeedback { Uo.append(Gaussian.gaussianRandom(0.0, standardDeviation: 1.0 / Double(numFeedback))) // feedback weights - Initialize to a random number to break initial symmetry of the network, scaled to the inputs } } } func setRMSPropDecay(_ decay: Double?) { rmspropDecay = decay } func feedForward(_ x: [Double], hPrev: [Double]) -> Double { // Get the input gate value var zi = 0.0 var sum = 0.0 vDSP_dotprD(Wi, 1, x, 1, &zi, vDSP_Length(numInputs)) vDSP_dotprD(Ui, 1, hPrev, 1, &sum, vDSP_Length(numFeedback)) zi += sum hi = 1.0 / (1.0 + exp(-zi)) // Get the forget gate value var zf = 0.0 vDSP_dotprD(Wf, 1, x, 1, &zf, vDSP_Length(numInputs)) vDSP_dotprD(Uf, 1, hPrev, 1, &sum, vDSP_Length(numFeedback)) zf += sum hf = 1.0 / (1.0 + exp(-zf)) // Get the output gate value var zo = 0.0 vDSP_dotprD(Wo, 1, x, 1, &zo, vDSP_Length(numInputs)) vDSP_dotprD(Uo, 1, hPrev, 1, &sum, vDSP_Length(numFeedback)) zo += sum ho = 1.0 / (1.0 + exp(-zo)) // Get the memory cell z sumation var zc = 0.0 vDSP_dotprD(Wc, 1, x, 1, &zc, vDSP_Length(numInputs)) vDSP_dotprD(Uc, 1, hPrev, 1, &sum, vDSP_Length(numFeedback)) zc += sum // Use the activation function function for the nonlinearity switch (activation) { case .none: hc = zc break case .hyperbolicTangent: hc = tanh(zc) break case .sigmoidWithCrossEntropy: fallthrough case .sigmoid: hc = 1.0 / (1.0 + exp(-zc)) break case .rectifiedLinear: hc = zc if (zc < 0) { hc = 0.0 } break case .softSign: hc = zc / (1.0 + abs(zc)) break case .softMax: hc = exp(zc) break } // Combine the forget and input gates into the cell summation lastCellState = lastCellState * hf + hc * hi // Use the activation function function for the nonlinearity let squashedCellState = getSquashedCellState() // Multiply the cell value by the output gate value to get the final result h = squashedCellState * ho return h } func getSquashedCellState() -> Double { // Use the activation function function for the nonlinearity var squashedCellState : Double switch (activation) { case .none: squashedCellState = lastCellState break case .hyperbolicTangent: squashedCellState = tanh(lastCellState) break case .sigmoidWithCrossEntropy: fallthrough case .sigmoid: squashedCellState = 1.0 / (1.0 + exp(-lastCellState)) break case .rectifiedLinear: squashedCellState = lastCellState if (lastCellState < 0) { squashedCellState = 0.0 } break case .softSign: squashedCellState = lastCellState / (1.0 + abs(lastCellState)) break case .softMax: squashedCellState = exp(lastCellState) break } return squashedCellState } // Get the partial derivitive of the error with respect to the weighted sum func getFinalNode𝟃E𝟃zs(_ 𝟃E𝟃h: Double) { // Store 𝟃E/𝟃h, set initial future error contributions to zero, and have the hidden layer routine do the work self.𝟃E𝟃h = 𝟃E𝟃h get𝟃E𝟃zs() } func reset𝟃E𝟃hs() { 𝟃E𝟃h = 0.0 } func addTo𝟃E𝟃hs(_ addition: Double) { 𝟃E𝟃h += addition } func getWeightTimes𝟃E𝟃zs(_ weightIndex: Int) ->Double { var sum = Wo[weightIndex] * 𝟃E𝟃zo sum += Wf[weightIndex] * 𝟃E𝟃zf sum += Wc[weightIndex] * 𝟃E𝟃zc sum += Wi[weightIndex] * 𝟃E𝟃zi return sum } func getFeedbackWeightTimes𝟃E𝟃zs(_ weightIndex: Int) ->Double { var sum = Uo[weightIndex] * 𝟃E𝟃zo sum += Uf[weightIndex] * 𝟃E𝟃zf sum += Uc[weightIndex] * 𝟃E𝟃zc sum += Ui[weightIndex] * 𝟃E𝟃zi return sum } func get𝟃E𝟃zs() { // 𝟃E𝟃h contains 𝟃E/𝟃h for the current time step plus all future time steps. // h = ho * squashedCellState --> // 𝟃E/𝟃zo = 𝟃E/𝟃h ⋅ 𝟃h/𝟃ho ⋅ 𝟃ho/𝟃zo = 𝟃E/𝟃h ⋅ squashedCellState ⋅ (ho - ho²) // 𝟃E/𝟃cellState = 𝟃E/𝟃h ⋅ 𝟃h/𝟃squashedCellState ⋅ 𝟃squashedCellState/𝟃cellState // = 𝟃E/𝟃h ⋅ ho ⋅ act'(cellState) + 𝟃E_future/𝟃cellState (from previous backpropogation step) 𝟃E𝟃zo = 𝟃E𝟃h * getSquashedCellState() * (ho - ho * ho) 𝟃E𝟃cellState = 𝟃E𝟃h * ho * getActPrime(getSquashedCellState()) + 𝟃E𝟃cellState // cellState = prevCellState * hf + hc * hi --> // 𝟃E/𝟃zf = 𝟃E𝟃cellState ⋅ 𝟃cellState/𝟃hf ⋅ 𝟃hf/𝟃zf = 𝟃E𝟃cellState ⋅ prevCellState ⋅ (hf - hf²) // 𝟃E/𝟃zc = 𝟃E𝟃cellState ⋅ 𝟃cellState/𝟃hc ⋅ 𝟃hc/𝟃zc = 𝟃E𝟃cellState ⋅ hi ⋅ act'(zc) // 𝟃E/𝟃zi = 𝟃E𝟃cellState ⋅ 𝟃cellState/𝟃hi ⋅ 𝟃hi/𝟃zi = 𝟃E𝟃cellState ⋅ hc ⋅ (hi - hi²) 𝟃E𝟃zf = 𝟃E𝟃cellState * getPreviousCellState() * (hf - hf * hf) 𝟃E𝟃zc = 𝟃E𝟃cellState * hi * getActPrime(hc) 𝟃E𝟃zi = 𝟃E𝟃cellState * hc * (hi - hi * hi) } func getActPrime(_ h: Double) -> Double { // derivitive of the non-linearity: tanh' -> 1 - result^2, sigmoid -> result - result^2, rectlinear -> 0 if result<0 else 1 var actPrime = 0.0 switch (activation) { case .none: break case .hyperbolicTangent: actPrime = (1 - h * h) break case .sigmoidWithCrossEntropy: fallthrough case .sigmoid: actPrime = (h - h * h) break case .rectifiedLinear: actPrime = h <= 0.0 ? 0.0 : 1.0 break case .softSign: // Reconstitute z from h var z : Double if (h < 0) { // Negative z z = h / (1.0 + h) actPrime = -1.0 / ((1.0 + z) * (1.0 + z)) } else { // Positive z z = h / (1.0 - h) actPrime = 1.0 / ((1.0 + z) * (1.0 + z)) } break case .softMax: // Should not get here - SoftMax is only valid on output layer break } return actPrime } func getPreviousCellState() -> Double { let prevValue = cellStateHistory.last if (prevValue == nil) { return 0.0 } return prevValue! } func clearWeightChanges() { 𝟃E𝟃Wi = [Double](repeating: 0.0, count: numInputs) 𝟃E𝟃Ui = [Double](repeating: 0.0, count: numFeedback) 𝟃E𝟃Wf = [Double](repeating: 0.0, count: numInputs) 𝟃E𝟃Uf = [Double](repeating: 0.0, count: numFeedback) 𝟃E𝟃Wc = [Double](repeating: 0.0, count: numInputs) 𝟃E𝟃Uc = [Double](repeating: 0.0, count: numFeedback) 𝟃E𝟃Wo = [Double](repeating: 0.0, count: numInputs) 𝟃E𝟃Uo = [Double](repeating: 0.0, count: numFeedback) } func appendWeightChanges(_ x: [Double], hPrev: [Double]) -> Double { // Update each weight accumulation // With 𝟃E/𝟃zo, we can get 𝟃E/𝟃Wo. zo = Wo⋅x + Uo⋅h(t-1)). 𝟃zo/𝟃Wo = x --> 𝟃E/𝟃Wo = 𝟃E/𝟃zo ⋅ 𝟃zo/𝟃Wo = 𝟃E/𝟃zo ⋅ x vDSP_vsmaD(x, 1, &𝟃E𝟃zo, 𝟃E𝟃Wo, 1, &𝟃E𝟃Wo, 1, vDSP_Length(numInputs)) // 𝟃E/𝟃Uo. zo = Wo⋅x + Uo⋅h(t-1). 𝟃zo/𝟃Uo = h(t-1) --> 𝟃E/𝟃Uo = 𝟃E/𝟃zo ⋅ 𝟃zo/𝟃Uo = 𝟃E/𝟃zo ⋅ h(t-1) vDSP_vsmaD(hPrev, 1, &𝟃E𝟃zo, 𝟃E𝟃Uo, 1, &𝟃E𝟃Uo, 1, vDSP_Length(numFeedback)) // With 𝟃E/𝟃zi, we can get 𝟃E/𝟃Wi. zi = Wi⋅x + Ui⋅h(t-1). 𝟃zi/𝟃Wi = x --> 𝟃E/𝟃Wi = 𝟃E/𝟃zi ⋅ 𝟃zi/𝟃Wi = 𝟃E/𝟃zi ⋅ x vDSP_vsmaD(x, 1, &𝟃E𝟃zi, 𝟃E𝟃Wi, 1, &𝟃E𝟃Wi, 1, vDSP_Length(numInputs)) // 𝟃E/𝟃Ui. i = Wi⋅x + Ui⋅h(t-1). 𝟃zi/𝟃Ui = h(t-1) --> 𝟃E/𝟃Ui = 𝟃E/𝟃zi ⋅ 𝟃zi/𝟃Ui = 𝟃E/𝟃zi ⋅ h(t-1) vDSP_vsmaD(hPrev, 1, &𝟃E𝟃zi, 𝟃E𝟃Ui, 1, &𝟃E𝟃Ui, 1, vDSP_Length(numFeedback)) // With 𝟃E/𝟃zf, we can get 𝟃E/𝟃Wf. zf = Wf⋅x + Uf⋅h(t-1). 𝟃zf/𝟃Wf = x --> 𝟃E/𝟃Wf = 𝟃E/𝟃zf ⋅ 𝟃zf/𝟃Wf = 𝟃E/𝟃zf ⋅ x vDSP_vsmaD(x, 1, &𝟃E𝟃zf, 𝟃E𝟃Wf, 1, &𝟃E𝟃Wf, 1, vDSP_Length(numInputs)) // 𝟃E/𝟃Uf. f = Wf⋅x + Uf⋅h(t-1). 𝟃zf/𝟃Uf = h(t-1) --> 𝟃E/𝟃Uf = 𝟃E/𝟃zf ⋅ 𝟃zf/𝟃Uf = 𝟃E/𝟃zf ⋅ h(t-1) vDSP_vsmaD(hPrev, 1, &𝟃E𝟃zf, 𝟃E𝟃Uf, 1, &𝟃E𝟃Uf, 1, vDSP_Length(numFeedback)) // With 𝟃E/𝟃zc, we can get 𝟃E/𝟃Wc. za = Wc⋅x + Uc⋅h(t-1). 𝟃za/𝟃Wa = x --> 𝟃E/𝟃Wc = 𝟃E/𝟃zc ⋅ 𝟃zc/𝟃Wc = 𝟃E/𝟃zc ⋅ x vDSP_vsmaD(x, 1, &𝟃E𝟃zc, 𝟃E𝟃Wc, 1, &𝟃E𝟃Wc, 1, vDSP_Length(numInputs)) // 𝟃E/𝟃Ua. f = Wc⋅x + Uc⋅h(t-1). 𝟃zc/𝟃Uc = h(t-1) --> 𝟃E/𝟃Uc = 𝟃E/𝟃zc ⋅ 𝟃zc/𝟃Uc = 𝟃E/𝟃zc ⋅ h(t-1) vDSP_vsmaD(hPrev, 1, &𝟃E𝟃zc, 𝟃E𝟃Uc, 1, &𝟃E𝟃Uc, 1, vDSP_Length(numFeedback)) return h } func updateWeightsFromAccumulations(_ averageTrainingRate: Double) { // Update the weights from the accumulations // weights -= accumulation * averageTrainingRate var η = -averageTrainingRate vDSP_vsmaD(𝟃E𝟃Wi, 1, &η, Wi, 1, &Wi, 1, vDSP_Length(numInputs)) vDSP_vsmaD(𝟃E𝟃Ui, 1, &η, Ui, 1, &Ui, 1, vDSP_Length(numFeedback)) vDSP_vsmaD(𝟃E𝟃Wf, 1, &η, Wf, 1, &Wf, 1, vDSP_Length(numInputs)) vDSP_vsmaD(𝟃E𝟃Uf, 1, &η, Uf, 1, &Uf, 1, vDSP_Length(numFeedback)) vDSP_vsmaD(𝟃E𝟃Wc, 1, &η, Wc, 1, &Wc, 1, vDSP_Length(numInputs)) vDSP_vsmaD(𝟃E𝟃Uc, 1, &η, Uc, 1, &Uc, 1, vDSP_Length(numFeedback)) vDSP_vsmaD(𝟃E𝟃Wo, 1, &η, Wo, 1, &Wo, 1, vDSP_Length(numInputs)) vDSP_vsmaD(𝟃E𝟃Uo, 1, &η, Uo, 1, &Uo, 1, vDSP_Length(numFeedback)) } func decayWeights(_ decayFactor : Double) { var λ = decayFactor // Needed for unsafe pointer conversion vDSP_vsmulD(Wi, 1, &λ, &Wi, 1, vDSP_Length(numInputs-1)) vDSP_vsmulD(Ui, 1, &λ, &Ui, 1, vDSP_Length(numFeedback)) vDSP_vsmulD(Wf, 1, &λ, &Wf, 1, vDSP_Length(numInputs-1)) vDSP_vsmulD(Uf, 1, &λ, &Uf, 1, vDSP_Length(numFeedback)) vDSP_vsmulD(Wc, 1, &λ, &Wc, 1, vDSP_Length(numInputs-1)) vDSP_vsmulD(Uc, 1, &λ, &Uc, 1, vDSP_Length(numFeedback)) vDSP_vsmulD(Wo, 1, &λ, &Wo, 1, vDSP_Length(numInputs-1)) vDSP_vsmulD(Uo, 1, &λ, &Uo, 1, vDSP_Length(numFeedback)) } func resetSequence() { h = 0.0 lastCellState = 0.0 ho = 0.0 hc = 0.0 hi = 0.0 hf = 0.0 𝟃E𝟃zo = 0.0 𝟃E𝟃zi = 0.0 𝟃E𝟃zf = 0.0 𝟃E𝟃zc = 0.0 𝟃E𝟃cellState = 0.0 outputHistory = [0.0] // first 'previous' value is zero cellStateHistory = [0.0] // first 'previous' value is zero outputGateHistory = [0.0] // first 'previous' value is zero memoryCellHistory = [0.0] // first 'previous' value is zero inputGateHistory = [0.0] // first 'previous' value is zero forgetGateHistory = [0.0] // first 'previous' value is zero } func storeRecurrentValues() { outputHistory.append(h) cellStateHistory.append(lastCellState) outputGateHistory.append(ho) memoryCellHistory.append(hc) inputGateHistory.append(hi) forgetGateHistory.append(hf) } func getLastRecurrentValue() { h = outputHistory.removeLast() lastCellState = cellStateHistory.removeLast() ho = outputGateHistory.removeLast() hc = memoryCellHistory.removeLast() hi = inputGateHistory.removeLast() hf = forgetGateHistory.removeLast() } func getPreviousOutputValue() -> Double { let prevValue = outputHistory.last if (prevValue == nil) { return 0.0 } return prevValue! } } final class LSTMNeuralLayer: NeuralLayer { // Nodes var nodes : [LSTMNeuralNode] var dataSet : DataSet? // Sequence data set (inputs and outputs) /// Create the neural network layer based on a tuple (number of nodes, activation function) init(numInputs : Int, layerDefinition: (layerType: NeuronLayerType, numNodes: Int, activation: NeuralActivationFunction, auxiliaryData: AnyObject?)) { nodes = [] for _ in 0..<layerDefinition.numNodes { nodes.append(LSTMNeuralNode(numInputs: numInputs, numFeedbacks: layerDefinition.numNodes, activationFunction: layerDefinition.activation)) } } // Initialize the weights func initWeights(_ startWeights: [Double]!) { if let startWeights = startWeights { if (startWeights.count >= nodes.count * nodes[0].numWeights) { // If there are enough weights for all nodes, split the weights and initialize var startIndex = 0 for node in nodes { let subArray = Array(startWeights[startIndex...(startIndex+node.numWeights-1)]) node.initWeights(subArray) startIndex += node.numWeights } } else { // If there are not enough weights for all nodes, initialize each node with the set given for node in nodes { node.initWeights(startWeights) } } } else { // No specified weights - just initialize normally for node in nodes { node.initWeights(nil) } } } func getWeights() -> [Double] { var weights: [Double] = [] for node in nodes { weights += node.Wi weights += node.Ui weights += node.Wf weights += node.Uf weights += node.Wc weights += node.Uc weights += node.Wo weights += node.Uo } return weights } func setRMSPropDecay(_ decay: Double?) { for node in nodes { node.setRMSPropDecay(decay) } } func getLastOutput() -> [Double] { var h: [Double] = [] for node in nodes { h.append(node.h) } return h } func getNodeCount() -> Int { return nodes.count } func getWeightsPerNode()-> Int { return nodes[0].numWeights } func getActivation()-> NeuralActivationFunction { return nodes[0].activation } func feedForward(_ x: [Double]) -> [Double] { // Gather the previous outputs for the feedback var hPrev : [Double] = [] for node in nodes { hPrev.append(node.getPreviousOutputValue()) } var outputs : [Double] = [] // Assume input array already has bias constant 1.0 appended // Fully-connected nodes means all nodes get the same input array if (nodes[0].activation == .softMax) { var sum = 0.0 for node in nodes { // Sum each output sum += node.feedForward(x, hPrev: hPrev) } let scale = 1.0 / sum // Do division once for efficiency for node in nodes { // Get the outputs scaled by the sum to give the probability distribuition for the output node.h *= scale outputs.append(node.h) } } else { for node in nodes { outputs.append(node.feedForward(x, hPrev: hPrev)) } } return outputs } func getFinalLayer𝟃E𝟃zs(_ 𝟃E𝟃h: [Double]) { for nNodeIndex in 0..<nodes.count { // Start with the portion from the squared error term nodes[nNodeIndex].getFinalNode𝟃E𝟃zs(𝟃E𝟃h[nNodeIndex]) } } func getLayer𝟃E𝟃zs(_ nextLayer: NeuralLayer) { // Get 𝟃E/𝟃h for nNodeIndex in 0..<nodes.count { // Reset the 𝟃E/𝟃h total nodes[nNodeIndex].reset𝟃E𝟃hs() // Add each portion from the nodes in the next forward layer nodes[nNodeIndex].addTo𝟃E𝟃hs(nextLayer.get𝟃E𝟃hForNodeInPreviousLayer(nNodeIndex)) // Add each portion from the nodes in this layer, using the feedback weights. This adds 𝟃Efuture/𝟃h for node in nodes { nodes[nNodeIndex].addTo𝟃E𝟃hs(node.getFeedbackWeightTimes𝟃E𝟃zs(nNodeIndex)) } } // Calculate 𝟃E/𝟃zs for this time step from 𝟃E/𝟃h for node in nodes { node.get𝟃E𝟃zs() } } func get𝟃E𝟃hForNodeInPreviousLayer(_ inputIndex: Int) ->Double { var sum = 0.0 for node in nodes { sum += node.getWeightTimes𝟃E𝟃zs(inputIndex) } return sum } func clearWeightChanges() { for node in nodes { node.clearWeightChanges() } } func appendWeightChanges(_ x: [Double]) -> [Double] { // Gather the previous outputs for the feedback var hPrev : [Double] = [] for node in nodes { hPrev.append(node.getPreviousOutputValue()) } var outputs : [Double] = [] // Assume input array already has bias constant 1.0 appended // Fully-connected nodes means all nodes get the same input array for node in nodes { outputs.append(node.appendWeightChanges(x, hPrev: hPrev)) } return outputs } func updateWeightsFromAccumulations(_ averageTrainingRate: Double, weightDecay: Double) { // Have each node update it's weights from the accumulations for node in nodes { if (weightDecay < 1) { node.decayWeights(weightDecay) } node.updateWeightsFromAccumulations(averageTrainingRate) } } func decayWeights(_ decayFactor : Double) { for node in nodes { node.decayWeights(decayFactor) } } func getSingleNodeClassifyValue() -> Double { let activation = nodes[0].activation if (activation == .hyperbolicTangent || activation == .rectifiedLinear) { return 0.0 } return 0.5 } func resetSequence() { for node in nodes { node.resetSequence() } } func storeRecurrentValues() { for node in nodes { node.storeRecurrentValues() } } func retrieveRecurrentValues(_ sequenceIndex: Int) { // Set the last recurrent value in the history array to the last output for node in nodes { node.getLastRecurrentValue() } } func gradientCheck(x: [Double], ε: Double, Δ: Double, network: NeuralNetwork) -> Bool { //!! return true } }
cc98eff164fa517c4f904eba27c1abdd
36.759281
220
0.52133
false
false
false
false
antonio081014/LeeCode-CodeBase
refs/heads/main
Swift/image-overlap.swift
mit
2
/** * https://leetcode.com/problems/image-overlap/ * * */ // Date: Sun Sep 6 00:42:52 PDT 2020 class Solution { func largestOverlap(_ C: [[Int]], _ D: [[Int]]) -> Int { func calc(_ A: [[Int]], _ B: [[Int]]) -> Int { let n1 = A.count let n2 = B.count let m1 = A[0].count let m2 = B[0].count var maxCount = 0 for x1 in 0 ..< n1 { for y1 in 0 ..< m1 { var xx = 0 var count = 0 while xx + x1 < n1, xx < n2 { var yy = 0 while yy + y1 < m1, yy < m2 { // print("\(xx):\(yy) - \(x1):\(y1)") if A[x1 + xx][y1 + yy] == 1, B[xx][yy] == 1 { count += 1 } yy += 1 } xx += 1 } // print("\(x1) - \(y1) : \(count)") maxCount = max(maxCount, count) } } return maxCount } return max(calc(C, D), calc(D, C)) } }
142f4e98c420afe1acf283191aec958d
30.307692
73
0.3
false
false
false
false
material-motion/motion-transitioning-objc
refs/heads/develop
examples/supplemental/PhotoAlbum.swift
apache-2.0
2
/* Copyright 2017-present The Material Motion Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import Foundation import UIKit let numberOfImageAssets = 10 let numberOfPhotosInAlbum = 30 class PhotoAlbum { let photos: [Photo] let identifierToIndex: [String: Int] init() { var photos: [Photo] = [] var identifierToIndex: [String: Int] = [:] for index in 0..<numberOfPhotosInAlbum { let photo = Photo(name: "image\(index % numberOfImageAssets)") photos.append(photo) identifierToIndex[photo.uuid] = index } self.photos = photos self.identifierToIndex = identifierToIndex } }
1de79a460c3651c635ed0a4873ab745f
29.052632
73
0.734676
false
false
false
false
GTennis/SuccessFramework
refs/heads/master
Templates/_BusinessAppSwift_/_BusinessAppSwift_/Modules/Home/HomeViewController.swift
mit
2
// // HomeViewController.swift // _BusinessAppSwift_ // // Created by Gytenis Mikulenas on 24/10/2016. // Copyright © 2016 Gytenis Mikulėnas // https://github.com/GitTennis/SuccessFramework // // 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. All rights reserved. // import UIKit let kHomeViewControllerTitleKey = "HomeTitle" let kHomeViewControllerDataLoadingProgressLabelKey = "HomeProgressLabel" class HomeViewController: BaseViewController, UICollectionViewDataSource, UICollectionViewDelegate, HomeCellDelegate { var model: HomeModel? @IBOutlet weak var collectionView: UICollectionView! override func viewDidLoad() { super.viewDidLoad(); self.collectionView.scrollsToTop = true self.prepareUI() self.loadModel() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) // Log user behaviour self.analyticsManager?.log(screenName: kAnalyticsScreen.home) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) } // MARK: GenericViewControllerProtocol override func prepareUI() { super.prepareUI() // ... //self.collectionView.register(HomeCell.self, forCellWithReuseIdentifier: HomeCell.reuseIdentifier) self.viewLoader?.addRefreshControl(containerView: self.collectionView, callback: { [weak self] in self?.loadModel() }) // Set title self.viewLoader?.setTitle(viewController: self, title: localizedString(key: kHomeViewControllerTitleKey)) } override func renderUI() { super.renderUI() // Reload self.collectionView.reloadData() } override func loadModel() { self.renderUI() self.viewLoader?.showScreenActivityIndicator(containerView: self.view) self.model?.loadData(callback: {[weak self] (success, result, context, error) in self?.viewLoader?.hideScreenActivityIndicator(containerView: (self?.view)!) if (success) { // Render UI self?.renderUI() } else { // Show refresh button when error happens // ... } }) } // MARK: UICollectionViewDataSource func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { if let list = self.model?.images?.list { return list.count } else { return 0 } } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell( withReuseIdentifier: HomeCell.reuseIdentifier, for: indexPath ) as! HomeCell cell.delegate = self let image = self.model?.images?.list?[(indexPath as NSIndexPath).row] cell.render(withEntity: image!) return cell } /*- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath { return self.collectionViewCellSize; }*/ /*- (CGSize)collectionViewCellSize { // Override in child classes return CGSizeZero; }*/ // MARK: HomeCellDelegate func didPressedWithImage(image: ImageEntityProtocol) { /*UIViewController *viewController = (UIViewController *)[self.viewControllerFactory photoDetailsViewControllerWithContext:image]; [self.navigationController pushViewController:viewController animated:YES];*/ } }
1410993db0c04fedad61e0e0497f9d72
30.75
169
0.631842
false
false
false
false
MaddTheSane/Nuke
refs/heads/master
Nuke/Source/UI/ImagePreheatingController.swift
mit
3
// The MIT License (MIT) // // Copyright (c) 2015 Alexander Grebenyuk (github.com/kean). import Foundation import UIKit /** Signals the delegate that the preheat window changed. */ public protocol ImagePreheatingControllerDelegate: class { func preheatingController(controller: ImagePreheatingController, didUpdateWithAddedIndexPaths addedIndexPaths: [NSIndexPath], removedIndexPaths: [NSIndexPath]) } /** Automates image preheating. Abstract class. */ public class ImagePreheatingController: NSObject { public weak var delegate: ImagePreheatingControllerDelegate? public let scrollView: UIScrollView public private(set) var preheatIndexPath = [NSIndexPath]() public var enabled = false deinit { self.scrollView.removeObserver(self, forKeyPath: "contentOffset", context: nil) } public init(scrollView: UIScrollView) { self.scrollView = scrollView super.init() self.scrollView.addObserver(self, forKeyPath: "contentOffset", options: [.New], context: nil) } public override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) { if object === self.scrollView { self.scrollViewDidScroll() } else { super.observeValueForKeyPath(keyPath, ofObject: object, change: change, context: nil) } } // MARK: Subclassing Hooks public func scrollViewDidScroll() { assert(false) } public func updatePreheatIndexPaths(indexPaths: [NSIndexPath]) { let addedIndexPaths = indexPaths.filter { return !self.preheatIndexPath.contains($0) } let removedIndexPaths = Set(self.preheatIndexPath).subtract(indexPaths) self.preheatIndexPath = indexPaths self.delegate?.preheatingController(self, didUpdateWithAddedIndexPaths: addedIndexPaths, removedIndexPaths: Array(removedIndexPaths)) } } internal func distanceBetweenPoints(p1: CGPoint, _ p2: CGPoint) -> CGFloat { let dx = p2.x - p1.x, dy = p2.y - p1.y return sqrt((dx * dx) + (dy * dy)) }
2d02d3d8bb478afb7f523c7569b3dc01
36.438596
164
0.703374
false
false
false
false
jekahy/Adoreavatars
refs/heads/master
Adoravatars/DownloadsVC.swift
mit
1
// // DownloadsVC.swift // Adoravatars // // Created by Eugene on 21.06.17. // Copyright © 2017 Eugene. All rights reserved. // import Foundation import UIKit import RxSwift import RxCocoa import Then class DownloadsVC: UIViewController { let cellIdentifier = "downloadCell" @IBOutlet weak var tableView: UITableView! private let disposeBag = DisposeBag() private var viewModel:DownloadsVMType! private var navigator:Navigator! override func viewDidLoad() { super.viewDidLoad() automaticallyAdjustsScrollViewInsets = false viewModel.downloadTasks.drive(tableView.rx.items(cellIdentifier: cellIdentifier, cellType: DownloadCell.self)) { (index, downloadTask: DownloadTaskType, cell) in let downloadVM = DownloadVM(downloadTask) cell.configureWith(downloadVM) }.addDisposableTo(disposeBag) } static func createWith(navigator: Navigator, storyboard: UIStoryboard, viewModel: DownloadsVMType) -> DownloadsVC { return storyboard.instantiateViewController(ofType: DownloadsVC.self).then { vc in vc.navigator = navigator vc.viewModel = viewModel } } }
6ae9bf57d6a0412e6634adc7c9698834
23.803922
119
0.666403
false
false
false
false
te-th/xID3
refs/heads/master
Source/ID3Tag.swift
apache-2.0
1
/* Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import Foundation /// Represents the ID3 Tag public final class ID3Identifier { private let lenId = 3 private let lenVersion = 2 private let lenFlags = 1 private let lenSize = 4 private let lenExtendedHeader = 4 public static let V3 = UInt8(3) static let id = "ID3" public let version: ID3Version public let size: UInt32 /// Indicates that ID3 Tag has an extended header public let extendedHeader: Bool private let a_flag_comparator = UInt8(1) << 7 private let b_flag_comparator = UInt8(1) << 6 private let c_flag_comparator = UInt8(1) << 5 /// Create an optional ID3Identifier instance from the given InputStream. Ignores Extended Header. /// /// - parameters: /// - stream: An InputStream that may contain an ID3 Tag /// init? (_ stream: InputStream) { var identifier = [UInt8](repeating: 0, count: lenId) stream.read(&identifier, maxLength: lenId) if ID3Identifier.id != ID3Utils.toString(identifier) { return nil } var version = [UInt8](repeating: 0, count: lenVersion) stream.read(&version, maxLength: lenVersion) self.version = ID3Version(version[0], version[1]) if self.version.major != ID3Identifier.V3 { return nil } var flag = [UInt8](repeating: 0, count: lenFlags) stream.read(&flag, maxLength: lenFlags) self.extendedHeader = (flag[0] & b_flag_comparator) == UInt8(1) var size = [UInt8](repeating: 0, count: lenSize) stream.read(&size, maxLength: lenSize) self.size = ID3Utils.tagSize(size[0], size[1], size[2], size[3]) if extendedHeader { var extendedHeaderSizeBuffer = [UInt8](repeating: 0, count: lenExtendedHeader) stream.read(&extendedHeaderSizeBuffer, maxLength: lenExtendedHeader) let extendedHeaderSize = ID3Utils.tagSize(size[0], size[1], size[2], size[3]) var dump = [UInt8](repeating: 0, count: Int(extendedHeaderSize) - lenExtendedHeader) stream.read(&dump, maxLength: dump.count) } } } /// Represents the content of an ID3 Tag final class ID3Content { private let lenId = 4 private let lenSize = 4 private let lenFlag = 2 private var availableFrames = [ID3TagFrame]() /// Read ID3 Frames from the given InputStream. /// /// - parameters: /// - stream: The InputStream containing ID3 Information. /// - size: Size of the ID3 Tag. init(_ stream: InputStream, _ size: UInt32) { var i = UInt32(0) while i < size { var frameIdBuffer = [UInt8](repeating: 0, count: lenId) stream.read(&frameIdBuffer, maxLength: lenId) let frameId = ID3Utils.toString(frameIdBuffer) var sizeBuffer = [UInt8](repeating: 0, count: lenSize) stream.read(&sizeBuffer, maxLength: lenSize) let frameSize = ID3Utils.frameSize(sizeBuffer[0], sizeBuffer[1], sizeBuffer[2], sizeBuffer[3]) if frameSize == 0 { break } var flagBuffer = [UInt8](repeating: 0, count: lenFlag) stream.read(&flagBuffer, maxLength: lenFlag) var contentBuffer = [UInt8](repeating: 0, count: Int(frameSize)) stream.read(&contentBuffer, maxLength: contentBuffer.count) let frame = ID3TagFrame(id: frameId, size: frameSize, content: contentBuffer, flags: flagBuffer) availableFrames.append(frame) i += UInt32(lenId + lenSize + lenFlag) + frameSize } } /// Get the available ID3 Frames. /// /// - returns: The available ID3 Frames. public func rawFrames() -> [ID3TagFrame] { return self.availableFrames } } /// Represents a ID3 Frame. public struct ID3TagFrame { let id: String let size: UInt32 let content: [UInt8] let flags: [UInt8] } /// Represents the ID3 Version. public final class ID3Version { let major: UInt8 let minor: UInt8 init(_ major: UInt8, _ minor: UInt8) { self.major = major self.minor = minor } } /// An ID3 Tag consisting of an ID3Identifier and the avaikable Frames. public struct ID3Tag { let identifier: ID3Identifier private let content: ID3Content init(_ identifier: ID3Identifier, _ content: ID3Content) { self.identifier = identifier self.content = content } /// Return the available ID3 Frames. /// /// - returns: The available ID3 Frames. public func rawFrames() -> [ID3TagFrame] { return content.rawFrames() } } /// Utility type extracting an ID3Tag from a given InputStream. Right not ID3v3 is supported. public final class ID3Reader { /// Extracts an ID3Tag from a given InputStream. /// /// - parameters: /// - stream An InputStream that may contain ID3 information. /// /// - return: An optional ID3Tag public static func read(_ stream: InputStream) -> ID3Tag? { let id = ID3Identifier(stream) guard let identifier = id else { return nil } let content = ID3Content(stream, identifier.size) return ID3Tag(identifier, content) } }
6ed424bb69a32dd692def193459ada84
30.395833
108
0.644161
false
false
false
false
anthonypuppo/GDAXSwift
refs/heads/master
GDAXSwift/Classes/GDAXCurrency.swift
mit
1
// // GDAXCurrency.swift // GDAXSwift // // Created by Anthony on 6/4/17. // Copyright © 2017 Anthony Puppo. All rights reserved. // public struct GDAXCurrency: JSONInitializable { public let id: String public let name: String public let minSize: Double internal init(json: Any) throws { var jsonData: Data? if let json = json as? Data { jsonData = json } else { jsonData = try JSONSerialization.data(withJSONObject: json, options: []) } guard let json = jsonData?.json else { throw GDAXError.invalidResponseData } guard let id = json["id"] as? String else { throw GDAXError.responseParsingFailure("id") } guard let name = json["name"] as? String else { throw GDAXError.responseParsingFailure("name") } guard let minSize = Double(json["min_size"] as? String ?? "") else { throw GDAXError.responseParsingFailure("min_size") } self.id = id self.name = name self.minSize = minSize } }
ccffac48e53b0317962a43f8c633ab49
20.422222
75
0.669087
false
false
false
false
warrenm/slug-swift-metal
refs/heads/master
SwiftMetalDemo/MBEDemoThree.swift
mit
1
// // MBEDemoThree.swift // SwiftMetalDemo // // Created by Warren Moore on 11/4/14. // Copyright (c) 2014 Warren Moore. All rights reserved. // import UIKit import Metal class MBEDemoThreeViewController : MBEDemoViewController { var depthStencilState: MTLDepthStencilState! = nil var vertexBuffer: MTLBuffer! = nil var indexBuffer: MTLBuffer! = nil var uniformBuffer: MTLBuffer! = nil var depthTexture: MTLTexture! = nil var diffuseTexture: MTLTexture! = nil var samplerState: MTLSamplerState! = nil var rotationAngle: Float = 0 func textureForImage(_ image:UIImage, device:MTLDevice) -> MTLTexture? { let imageRef = image.cgImage! let width = imageRef.width let height = imageRef.height let colorSpace = CGColorSpaceCreateDeviceRGB() let rawData = calloc(height * width * 4, MemoryLayout<UInt8>.stride) let bytesPerPixel = 4 let bytesPerRow = bytesPerPixel * width let bitsPerComponent = 8 let options = CGImageAlphaInfo.premultipliedLast.rawValue | CGBitmapInfo.byteOrder32Big.rawValue let context = CGContext(data: rawData, width: width, height: height, bitsPerComponent: bitsPerComponent, bytesPerRow: bytesPerRow, space: colorSpace, bitmapInfo: options) context?.draw(imageRef, in: CGRect(x: 0, y: 0, width: CGFloat(width), height: CGFloat(height))) let textureDescriptor = MTLTextureDescriptor.texture2DDescriptor(pixelFormat: .rgba8Unorm, width: Int(width), height: Int(height), mipmapped: true) let texture = device.makeTexture(descriptor: textureDescriptor) let region = MTLRegionMake2D(0, 0, Int(width), Int(height)) texture?.replace(region: region, mipmapLevel: 0, slice: 0, withBytes: rawData!, bytesPerRow: bytesPerRow, bytesPerImage: bytesPerRow * height) free(rawData) return texture } override func buildPipeline() { let library = device.makeDefaultLibrary()! let vertexFunction = library.makeFunction(name: "vertex_demo_three") let fragmentFunction = library.makeFunction(name: "fragment_demo_three") let vertexDescriptor = MTLVertexDescriptor() vertexDescriptor.attributes[0].offset = 0 vertexDescriptor.attributes[0].format = .float4 vertexDescriptor.attributes[0].bufferIndex = 0 vertexDescriptor.attributes[1].offset = MemoryLayout<Float>.stride * 4 vertexDescriptor.attributes[1].format = .float4 vertexDescriptor.attributes[1].bufferIndex = 0 vertexDescriptor.attributes[2].offset = MemoryLayout<Float>.stride * 8 vertexDescriptor.attributes[2].format = .float2 vertexDescriptor.attributes[2].bufferIndex = 0 vertexDescriptor.layouts[0].stepFunction = .perVertex vertexDescriptor.layouts[0].stride = MemoryLayout<Vertex>.stride let pipelineDescriptor = MTLRenderPipelineDescriptor() pipelineDescriptor.vertexFunction = vertexFunction pipelineDescriptor.vertexDescriptor = vertexDescriptor pipelineDescriptor.fragmentFunction = fragmentFunction pipelineDescriptor.colorAttachments[0].pixelFormat = .bgra8Unorm pipelineDescriptor.depthAttachmentPixelFormat = .depth32Float let error: NSErrorPointer? = nil pipeline = try? device.makeRenderPipelineState(descriptor: pipelineDescriptor) if (pipeline == nil) { print("Error occurred when creating pipeline \(String(describing: error))") } let depthStencilDescriptor = MTLDepthStencilDescriptor() depthStencilDescriptor.depthCompareFunction = .less depthStencilDescriptor.isDepthWriteEnabled = true depthStencilState = device.makeDepthStencilState(descriptor: depthStencilDescriptor) commandQueue = device.makeCommandQueue() let samplerDescriptor = MTLSamplerDescriptor() samplerDescriptor.minFilter = .nearest samplerDescriptor.magFilter = .linear samplerState = device.makeSamplerState(descriptor: samplerDescriptor) } override func buildResources() { let (vertexBuffer, indexBuffer) = SphereGenerator.sphereWithRadius(1, stacks: 30, slices: 30, device: device) self.vertexBuffer = vertexBuffer self.indexBuffer = indexBuffer uniformBuffer = device.makeBuffer(length: MemoryLayout<Matrix4x4>.stride * 2, options: []) diffuseTexture = self.textureForImage(UIImage(named: "bluemarble")!, device: device) } override func resize() { super.resize() let layerSize = metalLayer.drawableSize let depthTextureDescriptor = MTLTextureDescriptor.texture2DDescriptor(pixelFormat: .depth32Float, width: Int(layerSize.width), height: Int(layerSize.height), mipmapped: false) depthTextureDescriptor.storageMode = .private depthTextureDescriptor.usage = .renderTarget depthTexture = device.makeTexture(descriptor: depthTextureDescriptor) } override func draw() { if let drawable = metalLayer.nextDrawable() { let yAxis = Vector4(x: 0, y: -1, z: 0, w: 0) var modelViewMatrix = Matrix4x4.rotationAboutAxis(yAxis, byAngle: rotationAngle) modelViewMatrix.W.z = -2.5 let aspect = Float(metalLayer.drawableSize.width) / Float(metalLayer.drawableSize.height) let projectionMatrix = Matrix4x4.perspectiveProjection(aspect, fieldOfViewY: 60, near: 0.1, far: 100.0) let matrices = [projectionMatrix, modelViewMatrix] memcpy(uniformBuffer.contents(), matrices, Int(MemoryLayout<Matrix4x4>.stride * 2)) let commandBuffer = commandQueue.makeCommandBuffer() let passDescriptor = MTLRenderPassDescriptor() passDescriptor.colorAttachments[0].texture = drawable.texture passDescriptor.colorAttachments[0].clearColor = MTLClearColorMake(0.05, 0.05, 0.05, 1) passDescriptor.colorAttachments[0].loadAction = .clear passDescriptor.colorAttachments[0].storeAction = .store passDescriptor.depthAttachment.texture = depthTexture passDescriptor.depthAttachment.clearDepth = 1 passDescriptor.depthAttachment.loadAction = .clear passDescriptor.depthAttachment.storeAction = .dontCare let indexCount = indexBuffer.length / MemoryLayout<UInt16>.stride let commandEncoder = commandBuffer?.makeRenderCommandEncoder(descriptor: passDescriptor) if userToggle { commandEncoder?.setTriangleFillMode(.lines) } commandEncoder?.setRenderPipelineState(pipeline) commandEncoder?.setDepthStencilState(depthStencilState) commandEncoder?.setCullMode(.back) commandEncoder?.setVertexBuffer(vertexBuffer, offset:0, index:0) commandEncoder?.setVertexBuffer(uniformBuffer, offset:0, index:1) commandEncoder?.setFragmentTexture(diffuseTexture, index: 0) commandEncoder?.setFragmentSamplerState(samplerState, index: 0) commandEncoder?.drawIndexedPrimitives(type: .triangle, indexCount:indexCount, indexType:.uint16, indexBuffer:indexBuffer, indexBufferOffset: 0) commandEncoder?.endEncoding() commandBuffer?.present(drawable) commandBuffer?.commit() rotationAngle += 0.01 } } }
683f3d70af521b68e18236cea6bc3f65
43.841026
117
0.595608
false
false
false
false
tudou152/QQZone
refs/heads/master
QQZone/QQZone/Classes/Home/HomeViewController.swift
mit
1
// // HomeViewController.swift // QQZone // // Created by 君哥 on 2016/11/22. // Copyright © 2016年 fistBlood. All rights reserved. // import UIKit extension Selector { static let iconBtnClick = #selector(HomeViewController().iconBtnClick) } class HomeViewController: UIViewController { // MARK: 属性 /// 当前选中的索引 var currrentIndex: Int = 0 /// 容器视图 lazy var containerView: UIView = { // 设置尺寸 let width = min(self.view.frame.width, self.view.frame.height) - kDockItemWH let y: CGFloat = 20 let height: CGFloat = self.view.frame.height - y let x = self.dockView.frame.maxX let containerView = UIView(frame: CGRect(x: x, y: y, width: width, height: height)) return containerView }() /// 导航栏 lazy var dockView: DockView = { // 设置尺寸 let isLandscape = self.view.frame.width > self.view.frame.height let w = isLandscape ? kDockLandscapeWidth : kDockPortraitWidth let dockView = DockView(frame: CGRect(x: 0, y: 0, width: w, height: self.view.bounds.height)) dockView.iconView.addTarget(self, action: .iconBtnClick, for: .touchUpInside) // 设置代理 dockView.tabBarView.delegate = self return dockView }() override func viewDidLoad() { super.viewDidLoad() // 初始化设置 setup() } // 设置状态栏的颜色 override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } } // MARK: 设置子控件 extension HomeViewController { fileprivate func setup() { view.backgroundColor = UIColor(r: 55, g: 55, b: 55) // 添加Dock view.addSubview(dockView) // 添加containerView view.addSubview(containerView) // 添加所有的子控制器 setupChildViewControllers() // 底部菜单栏的点击的回调 dockView.bottomMenuView.didClickBtn = { [weak self] type in switch type { case .mood: let moodVC = MoodViewController() let nav = UINavigationController(rootViewController: moodVC) nav.modalPresentationStyle = .formSheet self?.present(nav, animated: true, completion: nil) case .photo: print("发表图片") case .blog: print("发表日志") } } } /// 添加所有子控制器 fileprivate func setupChildViewControllers() { addOneViewController(AllStatusViewController() , "全部动态", .red) addOneViewController(UIViewController() , "与我相关", .blue) addOneViewController(UIViewController(), "照片墙", .darkGray) addOneViewController(UIViewController(), "电子相框", .yellow) addOneViewController(UIViewController(), "好友", .orange) addOneViewController(UIViewController(), "更多", .white) addOneViewController(CenterViewController(), "个人中心", .gray) } private func addOneViewController(_ viewController: UIViewController, _ title: String,_ bgColor: UIColor) { // 设置控制器属性 viewController.view.backgroundColor = bgColor viewController.title = title // 设置导航控制器属性 let nav = UINavigationController(rootViewController: viewController) nav.navigationBar.isTranslucent = false // 设置导航栏不透明 addChildViewController(nav) } } // MARK: 监听屏幕的旋转 extension HomeViewController { override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { // 将屏幕旋转的时间传递给子控件 self.dockView.viewWillTransiton(to: size, with: coordinator) // 设置子控件的尺寸 let width = min(size.width, size.height) - kDockItemWH let y: CGFloat = 20 let height: CGFloat = size.height - y let x = dockView.frame.maxX containerView.frame = CGRect(x: x, y: y, width: width, height: height) } } // MARK: TabBarViewDelegate extension HomeViewController: TabBarViewDelegate { func tabBarViewSelectIndex(_ tabBarView: TabBarView, from: NSInteger, to: NSInteger) { // 移除旧的View let oldVC = childViewControllers[from] oldVC.view.removeFromSuperview() // 添加新的View let newVC = childViewControllers[to] containerView.addSubview(newVC.view) newVC.view.frame = containerView.bounds // 记录当前选中的索引 currrentIndex = to } } // MARK: 监听按钮点击 extension HomeViewController { /// 取消正在选中的按钮 func iconBtnClick() { // 取消中间菜单栏的选中状态 dockView.tabBarView.selectBtn?.isSelected = false tabBarViewSelectIndex(dockView.tabBarView, from: currrentIndex, to: childViewControllers.count - 1) } }
36f8259259c15c6f6ae287fcd3c7ec07
27.467836
112
0.603328
false
false
false
false
Esri/arcgis-runtime-samples-ios
refs/heads/main
arcgis-ios-sdk-samples/Scenes/Animate 3D graphic/CameraSettingsViewController.swift
apache-2.0
1
// // Copyright 2017 Esri. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import UIKit import ArcGIS class CameraSettingsViewController: UITableViewController { weak var orbitGeoElementCameraController: AGSOrbitGeoElementCameraController? @IBOutlet var headingOffsetSlider: UISlider! @IBOutlet var pitchOffsetSlider: UISlider! @IBOutlet var distanceSlider: UISlider! @IBOutlet var distanceLabel: UILabel! @IBOutlet var headingOffsetLabel: UILabel! @IBOutlet var pitchOffsetLabel: UILabel! @IBOutlet var autoHeadingEnabledSwitch: UISwitch! @IBOutlet var autoPitchEnabledSwitch: UISwitch! @IBOutlet var autoRollEnabledSwitch: UISwitch! private var distanceObservation: NSKeyValueObservation? private var headingObservation: NSKeyValueObservation? private var pitchObservation: NSKeyValueObservation? let measurementFormatter: MeasurementFormatter = { let formatter = MeasurementFormatter() formatter.numberFormatter.maximumFractionDigits = 0 formatter.unitOptions = .providedUnit return formatter }() override func viewDidLoad() { super.viewDidLoad() guard let cameraController = orbitGeoElementCameraController else { return } // apply initial values to controls updateUIForDistance() updateUIForHeadingOffset() updateUIForPitchOffset() autoHeadingEnabledSwitch.isOn = cameraController.isAutoHeadingEnabled autoPitchEnabledSwitch.isOn = cameraController.isAutoPitchEnabled autoRollEnabledSwitch.isOn = cameraController.isAutoRollEnabled // add observers to the values we want to show in the UI distanceObservation = cameraController.observe(\.cameraDistance) { [weak self] (_, _) in DispatchQueue.main.async { self?.updateUIForDistance() } } headingObservation = cameraController.observe(\.cameraHeadingOffset) { [weak self] (_, _) in DispatchQueue.main.async { self?.updateUIForHeadingOffset() } } pitchObservation = cameraController.observe(\.cameraPitchOffset) { [weak self] (_, _) in DispatchQueue.main.async { self?.updateUIForPitchOffset() } } } private func updateUIForDistance() { guard let cameraController = orbitGeoElementCameraController else { return } distanceSlider.value = Float(cameraController.cameraDistance) let measurement = Measurement(value: cameraController.cameraDistance, unit: UnitLength.meters) measurementFormatter.unitStyle = .medium distanceLabel.text = measurementFormatter.string(from: measurement) } private func updateUIForHeadingOffset() { guard let cameraController = orbitGeoElementCameraController else { return } headingOffsetSlider.value = Float(cameraController.cameraHeadingOffset) let measurement = Measurement(value: cameraController.cameraHeadingOffset, unit: UnitAngle.degrees) measurementFormatter.unitStyle = .short headingOffsetLabel.text = measurementFormatter.string(from: measurement) } private func updateUIForPitchOffset() { guard let cameraController = orbitGeoElementCameraController else { return } pitchOffsetSlider.value = Float(cameraController.cameraPitchOffset) let measurement = Measurement(value: cameraController.cameraPitchOffset, unit: UnitAngle.degrees) measurementFormatter.unitStyle = .short pitchOffsetLabel.text = measurementFormatter.string(from: measurement) } // MARK: - Actions @IBAction private func distanceValueChanged(sender: UISlider) { // update property orbitGeoElementCameraController?.cameraDistance = Double(sender.value) // update label updateUIForDistance() } @IBAction private func headingOffsetValueChanged(sender: UISlider) { // update property orbitGeoElementCameraController?.cameraHeadingOffset = Double(sender.value) // update label updateUIForHeadingOffset() } @IBAction private func pitchOffsetValueChanged(sender: UISlider) { // update property orbitGeoElementCameraController?.cameraPitchOffset = Double(sender.value) // update label updateUIForPitchOffset() } @IBAction private func autoHeadingEnabledValueChanged(sender: UISwitch) { // update property orbitGeoElementCameraController?.isAutoHeadingEnabled = sender.isOn } @IBAction private func autoPitchEnabledValueChanged(sender: UISwitch) { // update property orbitGeoElementCameraController?.isAutoPitchEnabled = sender.isOn } @IBAction private func autoRollEnabledValueChanged(sender: UISwitch) { // update property orbitGeoElementCameraController?.isAutoRollEnabled = sender.isOn } }
2028bdb89bab39c2f2304fc728ad9a8c
37.910345
107
0.693726
false
false
false
false
naokits/my-programming-marathon
refs/heads/master
IBDesignableDemo/IBDesignableDemo/CustomButton.swift
mit
1
// // CustomButton.swift // IBDesignableDemo // // Created by Naoki Tsutsui on 1/29/16. // Copyright © 2016 Naoki Tsutsui. All rights reserved. // import UIKit @IBDesignable class CustomButton: UIButton { @IBInspectable var textColor: UIColor? @IBInspectable var cornerRadius: CGFloat = 0 { didSet { layer.cornerRadius = cornerRadius } } @IBInspectable var borderWidth: CGFloat = 0 { didSet { layer.borderWidth = borderWidth } } @IBInspectable var borderColor: UIColor = UIColor.clearColor() { didSet { layer.borderColor = borderColor.CGColor } } }
96d1c028a5bfcacb833f317e5205e920
18.685714
68
0.599419
false
false
false
false
Avtolic/ACAlertController
refs/heads/master
ACAlertController/ACAlertControllerCore.swift
mit
1
// // ACAlertControllerCore.swift // ACAlertControllerDemo // // Created by Yury on 21/09/16. // Copyright © 2016 Avtolic. All rights reserved. // import Foundation import UIKit public var alertLinesColor = UIColor(red:220/256, green:220/256, blue:224/256, alpha:1.0) public protocol ACAlertListViewProtocol { var contentHeight: CGFloat { get } var view: UIView { get } } public protocol ACAlertListViewProvider { func set(alertView: UIView, itemsView: UIView?, actionsView: UIView?, callBlock: @escaping (ACAlertActionProtocolBase) -> Void) -> Void func alertView(items : [ACAlertItemProtocol], width: CGFloat) -> ACAlertListViewProtocol func alertView(actions : [ACAlertActionProtocolBase], width: CGFloat) -> ACAlertListViewProtocol } open class StackViewProvider: NSObject, ACAlertListViewProvider, UIGestureRecognizerDelegate { open func alertView(items: [ACAlertItemProtocol], width: CGFloat) -> ACAlertListViewProtocol { let views = items.map { $0.alertItemView } return ACStackAlertListView(views: views, width: width) } open func alertView(actions: [ACAlertActionProtocolBase], width: CGFloat) -> ACAlertListViewProtocol { buttonsAndActions = actions.map { (buttonView(action: $0), $0) } let views = buttonsAndActions.map { $0.0 } if views.count == 2 { let button1 = views[0] let button2 = views[1] button1.layoutIfNeeded() button2.layoutIfNeeded() let maxReducedWidth = (width - 1) / 2 if button1.bounds.width < maxReducedWidth && button2.bounds.width < maxReducedWidth { Layout.set(width: maxReducedWidth, view: button1) Layout.set(width: maxReducedWidth, view: button2) return ACStackAlertListView3(views: [button1, separatorView2(), button2], width: width) } } let views2 = views.flatMap { [$0, separatorView()] }.dropLast() return ACStackAlertListView2(views: Array(views2), width: width) } open var actionsView: UIView! open var callBlock:((ACAlertActionProtocolBase) -> Void)! open func set(alertView: UIView, itemsView: UIView?, actionsView: UIView?, callBlock:@escaping (ACAlertActionProtocolBase) -> Void) -> Void { self.actionsView = actionsView self.callBlock = callBlock let recognizer = UILongPressGestureRecognizer(target: self, action: #selector(handleRecognizer)) recognizer.minimumPressDuration = 0.0 recognizer.allowableMovement = CGFloat.greatestFiniteMagnitude recognizer.cancelsTouchesInView = false recognizer.delegate = self if let superRecognizers = actionsView?.gestureRecognizers { for r in superRecognizers { recognizer.require(toFail: r) } } if let superRecognizers = itemsView?.gestureRecognizers { for r in superRecognizers { recognizer.require(toFail: r) } } alertView.addGestureRecognizer(recognizer) } open var buttonsAndActions: [(UIView, ACAlertActionProtocolBase)] = [] open var buttonHighlightColor = UIColor(white: 0.9, alpha: 1) // MARK: Touch recogniser @objc open func handleRecognizer(_ recognizer: UILongPressGestureRecognizer) { let point = recognizer.location(in: actionsView) for (button, action) in buttonsAndActions { let isActive = button.frame.contains(point) && action.enabled let isHighlighted = isActive && (recognizer.state == .began || recognizer.state == .changed) button.backgroundColor = isHighlighted ? buttonHighlightColor : UIColor.clear action.highlight(isHighlighted) if isActive && recognizer.state == .ended { callBlock(action) } } } open var buttonsMargins = UIEdgeInsets(top: 4, left: 8, bottom: 4, right: 8) // Applied to buttons open var defaultButtonHeight: CGFloat = 45 open func buttonView(action: ACAlertActionProtocolBase) -> UIView { let actionView = action.alertView actionView.translatesAutoresizingMaskIntoConstraints = false actionView.isUserInteractionEnabled = false let button = UIView() button.layoutMargins = buttonsMargins button.addSubview(actionView) button.translatesAutoresizingMaskIntoConstraints = false Layout.setInCenter(view: button, subview: actionView, margins: true) Layout.setOptional(height: defaultButtonHeight, view: button) return button } open func separatorView() -> UIView { let view = UIView() view.backgroundColor = alertLinesColor view.translatesAutoresizingMaskIntoConstraints = false Layout.set(height: 0.5, view: view) return view } open func separatorView2() -> UIView { let view = UIView() view.backgroundColor = alertLinesColor view.translatesAutoresizingMaskIntoConstraints = false Layout.set(width: 0.5, view: view) return view } } open class ACStackAlertListView: ACAlertListViewProtocol { public var view: UIView { return scrollView } public var contentHeight: CGFloat open let stackView: UIStackView open let scrollView = UIScrollView() open var margins = UIEdgeInsets(top: 10, left: 5, bottom: 10, right: 5) public init(views: [UIView], width: CGFloat) { stackView = UIStackView(arrangedSubviews: views ) stackView.axis = .vertical stackView.alignment = .center stackView.distribution = .equalSpacing stackView.spacing = 0 stackView.translatesAutoresizingMaskIntoConstraints = false scrollView.translatesAutoresizingMaskIntoConstraints = false scrollView.addSubview(stackView) Layout.setEqual(view:scrollView, subview: stackView, margins: false) Layout.set(width: width, view: stackView) stackView.layoutMargins = margins stackView.isLayoutMarginsRelativeArrangement = true contentHeight = stackView.systemLayoutSizeFitting(UILayoutFittingCompressedSize).height } } open class ACStackAlertListView2: ACAlertListViewProtocol { open var view: UIView { return scrollView } open var contentHeight: CGFloat open let stackView: UIStackView open let scrollView = UIScrollView() open var margins = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0) public init(views: [UIView], width: CGFloat) { stackView = UIStackView(arrangedSubviews: views ) stackView.axis = .vertical stackView.alignment = .fill stackView.distribution = .equalSpacing stackView.spacing = 0 stackView.translatesAutoresizingMaskIntoConstraints = false scrollView.translatesAutoresizingMaskIntoConstraints = false scrollView.addSubview(stackView) Layout.setEqual(view:scrollView, subview: stackView, margins: false) Layout.set(width: width, view: stackView) stackView.layoutMargins = margins stackView.isLayoutMarginsRelativeArrangement = true contentHeight = stackView.systemLayoutSizeFitting(UILayoutFittingCompressedSize).height } } open class ACStackAlertListView3: ACAlertListViewProtocol { open var view: UIView { return scrollView } open var contentHeight: CGFloat open let stackView: UIStackView open let scrollView = UIScrollView() open var margins = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0) public init(views: [UIView], width: CGFloat) { stackView = UIStackView(arrangedSubviews: views ) stackView.axis = .horizontal stackView.alignment = .fill stackView.distribution = .equalSpacing stackView.spacing = 0 stackView.translatesAutoresizingMaskIntoConstraints = false scrollView.translatesAutoresizingMaskIntoConstraints = false scrollView.addSubview(stackView) Layout.setEqual(view:scrollView, subview: stackView, margins: false) Layout.set(width: width, view: stackView) stackView.layoutMargins = margins stackView.isLayoutMarginsRelativeArrangement = true contentHeight = stackView.systemLayoutSizeFitting(UILayoutFittingCompressedSize).height } } open class ACAlertController : UIViewController{ fileprivate(set) open var items: [ACAlertItemProtocol] = [] fileprivate(set) open var actions: [ACAlertActionProtocolBase] = [] // open var items: [ACAlertItemProtocol] { return items.map{ $0.0 } } // fileprivate(set) open var actions: [ACAlertActionProtocol] = [] open var backgroundColor = UIColor(white: 250/256, alpha: 1) open var viewMargins = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)//UIEdgeInsets(top: 15, bottom: 15) // open var defaultItemsMargins = UIEdgeInsets(top: 2, left: 0, bottom: 2, right: 0) // Applied to items // open var itemsMargins = UIEdgeInsets(top: 4, bottom: 4) // open var actionsMargins = UIEdgeInsets(top: 4, bottom: 4) open var alertWidth: CGFloat = 270 open var cornerRadius: CGFloat = 16 open var separatorHeight: CGFloat = 0.5 open var alertListsProvider: ACAlertListViewProvider = StackViewProvider() open var itemsAlertList: ACAlertListViewProtocol? open var actionsAlertList: ACAlertListViewProtocol? open var separatorView: UIView = { let view = UIView() view.backgroundColor = alertLinesColor view.translatesAutoresizingMaskIntoConstraints = false return view }() // MARK: Public methods public init() { super.init(nibName: nil, bundle: nil) modalPresentationStyle = .overFullScreen transitioningDelegate = self } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } open func addItem(_ item: ACAlertItemProtocol) { guard isBeingPresented == false else { print("ACAlertController could not be modified if it is already presented") return } items.append(item) } open func addAction(_ action: ACAlertActionProtocolBase) { guard isBeingPresented == false else { print("ACAlertController could not be modified if it is already presented") return } actions.append(action) } override open func loadView() { view = UIView() view.backgroundColor = backgroundColor view.layer.cornerRadius = cornerRadius view.translatesAutoresizingMaskIntoConstraints = false view.layer.masksToBounds = true Layout.set(width: alertWidth, view: view) // Is needed because of layoutMargins http://stackoverflow.com/questions/27421469/setting-layoutmargins-of-uiview-doesnt-work let contentView = UIView() view.addSubview(contentView) contentView.layoutMargins = viewMargins contentView.translatesAutoresizingMaskIntoConstraints = false Layout.setEqual(view: view, subview: contentView, margins: false) setContentView(view: contentView) } open func setContentView(view: UIView) { if hasItems { itemsAlertList = alertListsProvider.alertView(items: items, width: alertWidth - viewMargins.leftPlusRight) } if hasActions { actionsAlertList = alertListsProvider.alertView(actions: actions, width: alertWidth - viewMargins.leftPlusRight) } let (height1, height2) = elementsHeights() if let h = height1, let v = itemsAlertList?.view { Layout.set(height: h, view: v) } if let h = height2, let v = actionsAlertList?.view { Layout.set(height: h, view: v) } if let topSubview = itemsAlertList?.view ?? actionsAlertList?.view { view.addSubview(topSubview) Layout.setEqualTop(view: view, subview: topSubview, margins: true) Layout.setEqualLeftAndRight(view: view, subview: topSubview, margins: true) if let bottomSubview = actionsAlertList?.view, bottomSubview !== topSubview { view.addSubview(separatorView) Layout.setBottomToTop(topView: topSubview, bottomView: separatorView) Layout.setEqualLeftAndRight(view: view, subview: separatorView, margins: true) Layout.set(height: separatorHeight, view: separatorView) view.addSubview(bottomSubview) Layout.setBottomToTop(topView: separatorView, bottomView: bottomSubview) Layout.setEqualLeftAndRight(view: view, subview: bottomSubview, margins: true) Layout.setEqualBottom(view: view, subview: bottomSubview, margins: true) } else { Layout.setEqualBottom(view: view, subview: topSubview, margins: true) } } alertListsProvider.set(alertView: view, itemsView: itemsAlertList?.view, actionsView: actionsAlertList?.view) { (action) in self.presentingViewController?.dismiss(animated: true, completion: { DispatchQueue.main.async(execute: { action.call() }) }) } } open var hasItems: Bool { return items.count > 0 } open var hasActions: Bool { return actions.count > 0 } open var maxViewHeight: CGFloat { return UIScreen.main.bounds.height - 80 } open func elementsHeights() -> (itemsHeight: CGFloat?, actionsHeight: CGFloat?) { let max = maxViewHeight - viewMargins.topPlusBottom switch (itemsAlertList?.contentHeight, actionsAlertList?.contentHeight) { case (nil, nil): return (nil, nil) case (.some(let height1), nil): return (min(height1, max), nil) case (nil, .some(let height2)): return (nil, min(height2, max)) case (.some(let height1), .some(let height2)): let max2 = max - separatorHeight if max2 >= height1 + height2 { return (height1, height2) } else if height1 < max2 * 0.75 { return (height1, max2 - height1) } else if height2 < max2 * 0.75 { return (max2 - height2, height2) } return (max2 / 2, max2 / 2) } } } extension ACAlertController: UIViewControllerTransitioningDelegate { public func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? { return ACAlertControllerAnimatedTransitioningBase(appearing: true) } public func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { return ACAlertControllerAnimatedTransitioningBase(appearing: false) } } open class Layout { open static var nonMandatoryConstraintPriority: UILayoutPriority = 700 // Item's and action's constraints that could conflict with ACAlertController constraints should have priorities in [nonMandatoryConstraintPriority ..< 1000] range. open class func set(width: CGFloat, view: UIView) { NSLayoutConstraint(item: view, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: width).isActive = true } open class func set(height: CGFloat, view: UIView) { NSLayoutConstraint(item: view, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: height).isActive = true } open class func setOptional(height: CGFloat, view: UIView) { let constraint = NSLayoutConstraint(item: view, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: height) constraint.priority = nonMandatoryConstraintPriority constraint.isActive = true } open class func setOptional(width: CGFloat, view: UIView) { let constraint = NSLayoutConstraint(item: view, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: width) constraint.priority = nonMandatoryConstraintPriority constraint.isActive = true } open class func setInCenter(view: UIView, subview: UIView, margins: Bool) { NSLayoutConstraint(item: view, attribute: margins ? .leadingMargin : .leading, relatedBy: .lessThanOrEqual, toItem: subview, attribute: .leading, multiplier: 1, constant: 0).isActive = true NSLayoutConstraint(item: view, attribute: margins ? .trailingMargin : .trailing, relatedBy: .greaterThanOrEqual, toItem: subview, attribute: .trailing, multiplier: 1, constant: 0).isActive = true NSLayoutConstraint(item: view, attribute: margins ? .topMargin : .top, relatedBy: .lessThanOrEqual, toItem: subview, attribute: .top, multiplier: 1, constant: 0).isActive = true NSLayoutConstraint(item: view, attribute: margins ? .bottomMargin : .bottom, relatedBy: .greaterThanOrEqual, toItem: subview, attribute: .bottom, multiplier: 1, constant: 0).isActive = true let centerX = NSLayoutConstraint(item: view, attribute: margins ? .centerXWithinMargins : .centerX, relatedBy: .equal, toItem: subview, attribute: .centerX, multiplier: 1, constant: 0) centerX.priority = nonMandatoryConstraintPriority centerX.isActive = true let centerY = NSLayoutConstraint(item: view, attribute: margins ? .centerYWithinMargins : .centerY, relatedBy: .equal, toItem: subview, attribute: .centerY, multiplier: 1, constant: 0) centerY.priority = nonMandatoryConstraintPriority centerY.isActive = true } open class func setEqual(view: UIView, subview: UIView, margins: Bool) { NSLayoutConstraint(item: view, attribute: margins ? .leftMargin : .left, relatedBy: .equal, toItem: subview, attribute: .left, multiplier: 1, constant: 0).isActive = true NSLayoutConstraint(item: view, attribute: margins ? .rightMargin : .right, relatedBy: .equal, toItem: subview, attribute: .right, multiplier: 1, constant: 0).isActive = true NSLayoutConstraint(item: view, attribute: margins ? .topMargin : .top, relatedBy: .equal, toItem: subview, attribute: .top, multiplier: 1, constant: 0).isActive = true NSLayoutConstraint(item: view, attribute: margins ? .bottomMargin: .bottom, relatedBy: .equal, toItem: subview, attribute: .bottom, multiplier: 1, constant: 0).isActive = true } open class func setEqualLeftAndRight(view: UIView, subview: UIView, margins: Bool) { NSLayoutConstraint(item: view, attribute: margins ? .leftMargin : .left, relatedBy: .equal, toItem: subview, attribute: .left, multiplier: 1, constant: 0).isActive = true NSLayoutConstraint(item: view, attribute: margins ? .rightMargin : .right, relatedBy: .equal, toItem: subview, attribute: .right, multiplier: 1, constant: 0).isActive = true } open class func setEqualTop(view: UIView, subview: UIView, margins: Bool) { NSLayoutConstraint(item: view, attribute: margins ? .topMargin : .top, relatedBy: .equal, toItem: subview, attribute: .top, multiplier: 1, constant: 0).isActive = true } open class func setEqualBottom(view: UIView, subview: UIView, margins: Bool) { NSLayoutConstraint(item: view, attribute: margins ? .bottomMargin : .bottom, relatedBy: .equal, toItem: subview, attribute: .bottom, multiplier: 1, constant: 0).isActive = true } open class func setBottomToTop(topView: UIView, bottomView: UIView) { NSLayoutConstraint(item: topView, attribute: .bottom, relatedBy: .equal, toItem: bottomView, attribute: .top, multiplier: 1, constant: 0).isActive = true } } public extension UIEdgeInsets { public var topPlusBottom: CGFloat { return top + bottom } public var leftPlusRight: CGFloat { return left + right } public init(top: CGFloat, bottom: CGFloat) { self.init(top: top, left: 0, bottom: bottom, right: 0) } }
b862ddb198a9d421db50b7d5a0223eaf
41.456212
239
0.659359
false
false
false
false
manavgabhawala/UberSDK
refs/heads/master
Shared/UberUserAuthenticator.swift
apache-2.0
1
// // UberUserAuthenticator.swift // UberSDK // // Created by Manav Gabhawala on 24/07/15. // // import Foundation internal class UberUserAuthenticator : NSObject { private let refreshSemaphore = dispatch_semaphore_create(1) private var accessToken : String? private var refreshToken: String? private var expiration : NSDate? private var uberOAuthCredentialsLocation : String private var clientID: String private var clientSecret : String internal var redirectURI : String private var scopes : [UberScopes] private var completionBlock : UberSuccessBlock? internal var errorHandler : UberErrorHandler? internal var viewController : AnyObject! internal init(clientID: String, clientSecret: String, redirectURI: String, scopes: [UberScopes]) { self.clientID = clientID self.clientSecret = clientSecret self.redirectURI = redirectURI self.scopes = scopes if let directory = NSSearchPathForDirectoriesInDomains(.ApplicationSupportDirectory, NSSearchPathDomainMask.UserDomainMask, true).first { uberOAuthCredentialsLocation = "\(directory)/Authentication.plist" let fileManager = NSFileManager() if !fileManager.fileExistsAtPath(directory) { try! fileManager.createDirectoryAtPath(directory, withIntermediateDirectories: true, attributes: nil) } if !fileManager.fileExistsAtPath(uberOAuthCredentialsLocation) { fileManager.createFileAtPath(uberOAuthCredentialsLocation, contents: nil, attributes: nil) } } else { uberOAuthCredentialsLocation = "" } if let dictionary = NSDictionary(contentsOfFile: uberOAuthCredentialsLocation) { if let accessTok = dictionary.objectForKey("access_token") as? NSData, let encodedAccessToken = String(data: accessTok) { accessToken = String(data: NSData(base64EncodedString: encodedAccessToken, options: [])) } if let refreshTok = dictionary.objectForKey("refresh_token") as? NSData, let encodedRefreshToken = String(data: refreshTok) { refreshToken = String(data: NSData(base64EncodedString: encodedRefreshToken, options: [])) } expiration = dictionary.objectForKey("timeout") as? NSDate } } /// Tests whether authentication has been performed or not. /// /// - returns: `true` if authentication has been performed else `false`. internal func authenticated() -> Bool { if let _ = accessToken { return true } return false } /// This function adds the bearer access_token to the authorization field if it is available. /// /// - parameter request: A mutable URL Request which is modified to add the access token to the URL Request if one exists for the user. /// /// - returns: `true` if the access token was successfully added to the request. `false` otherwise. internal func addBearerAccessHeader(request: NSMutableURLRequest) -> Bool { if let accessToken = requestAccessToken() { request.addValue("Bearer \(accessToken)", forHTTPHeaderField: "Authorization") return true } return false } private func requestAccessToken(allowsRefresh: Bool = true) -> String? { if (accessToken == nil || refreshToken == nil || expiration == nil) { return nil } if expiration! > NSDate(timeIntervalSinceNow: 0) { return accessToken } else if allowsRefresh { refreshAccessToken() dispatch_semaphore_wait(refreshSemaphore, DISPATCH_TIME_FOREVER) return requestAccessToken(false) } return nil } private func refreshAccessToken() { dispatch_semaphore_wait(refreshSemaphore, DISPATCH_TIME_NOW) let data = "client_id=\(clientID)&client_secret=\(clientSecret)&redirect_uri=\(redirectURI)&grant_type=refresh_token&refresh_token=\(refreshToken)" let URL = NSURL(string: "https://login.uber.com/oauth/token")! let request = NSMutableURLRequest(URL: URL) request.HTTPMethod = "POST" request.HTTPBody = data.dataUsingEncoding(NSUTF8StringEncoding) performFetchForAuthData(request.copy() as! NSURLRequest) } internal func getAuthTokenForCode(code: String) { let data = "code=\(code)&client_id=\(clientID)&client_secret=\(clientSecret)&redirect_uri=\(redirectURI)&grant_type=authorization_code" let URL = NSURL(string: "https://login.uber.com/oauth/token")! let request = NSMutableURLRequest(URL: URL) request.HTTPMethod = HTTPMethod.Post.rawValue request.HTTPBody = data.dataUsingEncoding(NSUTF8StringEncoding) performFetchForAuthData(request.copy() as! NSURLRequest) } private func performFetchForAuthData(request: NSURLRequest) { let session = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration()) let task = session.dataTaskWithRequest(request, completionHandler: {(data, response, error) in if (error == nil) { self.parseAuthDataReceived(data!) // If we can't acquire it, it returns imeediately and it means that someone is waiting and needs to be signalled. // If we do acquire it we release it immediately because we don't actually want to hold it for anytime in the future. dispatch_semaphore_wait(self.refreshSemaphore, DISPATCH_TIME_NOW) dispatch_semaphore_signal(self.refreshSemaphore) } else { self.errorHandler?(UberError(JSONData: data, response: response) ?? UberError(error: error, response: response) ?? unknownError) } }) task.resume() } private func parseAuthDataReceived(authData: NSData) { do { guard let authDictionary = try NSJSONSerialization.JSONObjectWithData(authData, options: []) as? [NSObject : AnyObject] else { return } guard let access = authDictionary["access_token"] as? String, let refresh = authDictionary["refresh_token"] as? String, let timeout = authDictionary["expires_in"] as? NSTimeInterval else { throw NSError(domain: "UberAuthenticationError", code: 1, userInfo: nil) } accessToken = access refreshToken = refresh let time = NSDate(timeInterval: timeout, sinceDate: NSDate(timeIntervalSinceNow: 0)) let encodedAccessToken = accessToken!.dataUsingEncoding(NSUTF8StringEncoding)!.base64EncodedDataWithOptions([]) let encodedRefreshToken = refreshToken!.dataUsingEncoding(NSUTF8StringEncoding)!.base64EncodedDataWithOptions([]) let dictionary : NSDictionary = ["access_token" : encodedAccessToken, "refresh_token" : encodedRefreshToken, "timeout" : time]; dictionary.writeToFile(uberOAuthCredentialsLocation, atomically: true) completionBlock?() } catch let error as NSError { errorHandler?(UberError(error: error)) } catch { errorHandler?(UberError(JSONData: authData) ?? unknownError) } } internal func setupOAuth2AccountStore<T: Viewable>(view: T) { if let _ = requestAccessToken() { completionBlock?() return } var scopesString = scopes.reduce("", combine: { $0.0 + "%20" + $0.1.description }) scopesString = scopesString.substringFromIndex(advance(scopesString.startIndex, 3)) let redirectURL = redirectURI.stringByAddingPercentEncodingWithAllowedCharacters(.URLPasswordAllowedCharacterSet())! let URL = NSURL(string: "https://login.uber.com/oauth/authorize?response_type=code&client_id=\(clientID)&redirect_uri=\(redirectURL)&scope=\(scopesString)")! let request = NSURLRequest(URL: URL) generateCodeForRequest(request, onView: view) } internal func setCallbackBlocks(successBlock successBlock: UberSuccessBlock?, errorBlock: UberErrorHandler?) { completionBlock = successBlock errorHandler = errorBlock } internal func logout(completionBlock success: UberSuccessBlock?, errorHandler failure: UberErrorHandler?) { accessToken = nil refreshToken = nil expiration = nil let fileManager = NSFileManager.defaultManager() if fileManager.fileExistsAtPath(uberOAuthCredentialsLocation) { do { try fileManager.removeItemAtPath(uberOAuthCredentialsLocation) success?() } catch let error as NSError { failure?(UberError(error: error)) } catch { failure?(unknownError) } } else { success?() } } }
9c6b9b5ad0b97b8925bc5b648bd2a32f
33.846491
159
0.743832
false
false
false
false
skyfe79/TIL
refs/heads/master
about.iOS/about.Swift/15.Deinitialization.playground/Contents.swift
mit
1
/*: # Deinitialization * 컴퓨터의 자원이 유한하기 때문에 이 모든 것이 필요한 것이다. */ import UIKit /*: ## How Deinitialization Works */ do { class SomeClass { deinit { // perform the deinitialization } } } /*: ## Deinitializers in Action */ do { class Bank { static var coinsInBank = 10_000 static func vendCoins(numberOfCoinsRequested: Int) -> Int { let numberOfCoinsToVend = min(numberOfCoinsRequested, coinsInBank) coinsInBank -= numberOfCoinsToVend return numberOfCoinsToVend } static func receiveCoins(coins: Int) { coinsInBank += coins } } class Player { var coinsInPurse: Int init(coins: Int) { coinsInPurse = Bank.vendCoins(coins) } func winCoins(coins: Int) { coinsInPurse += Bank.vendCoins(coins) } deinit { Bank.receiveCoins(coinsInPurse) } } var playerOne: Player? = Player(coins: 100) print("A new player has joined the game with \(playerOne!.coinsInPurse) coins") // Prints "A new player has joined the game with 100 coins" print("There are now \(Bank.coinsInBank) coins left in the bank") // Prints "There are now 9900 coins left in the bank" playerOne!.winCoins(2_000) print("PlayerOne won 2000 coins & now has \(playerOne!.coinsInPurse) coins") // Prints "PlayerOne won 2000 coins & now has 2100 coins" print("The bank now only has \(Bank.coinsInBank) coins left") // Prints "The bank now only has 7900 coins left" playerOne = nil print("PlayerOne has left the game") // Prints "PlayerOne has left the game" print("The bank now has \(Bank.coinsInBank) coins") // Prints "The bank now has 10000 coins" }
54262aee29d125149710f5484cddb1e4
27.3125
83
0.611264
false
false
false
false
sessionm/ios-smp-example
refs/heads/master
Offers/Reward Store/RewardStoreTableViewController.swift
mit
1
// // RewardStoreTableViewController.swift // Offers // // Copyright © 2018 SessionM. All rights reserved. // import SessionMOffersKit import UIKit class RewardStoreTableViewCell: UITableViewCell { @IBOutlet weak var header: UILabel! @IBOutlet weak var validDates: UILabel! @IBOutlet weak var points: UILabel! @IBOutlet weak var img: UIImageView! } class RewardStoreTableViewController: UITableViewController { override func viewDidLoad() { super.viewDidLoad() NotificationCenter.default.addObserver(self, selector: #selector(updateToolbar), name: NSNotification.Name(updatedUserNotification), object: nil) self.tableView.rowHeight = UITableViewAutomaticDimension self.tableView.estimatedRowHeight = 200; self.tableView.contentInset = UIEdgeInsetsMake(64,0,0,0); // Put it below the navigation controller modalPresentationStyle = .overCurrentContext definesPresentationContext = true; providesPresentationContextTransitionStyle = true; handleRefresh(refresh: nil) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) performSelector(onMainThread: #selector(updateToolbar), with: nil, waitUntilDone: false) } @objc func updateToolbar() { if let controller = navigationController { controller.navigationBar.topItem!.title = "Rewards Store" Common.showUserInToolbar(nav: controller) } } var _offers : [SMStoreOfferItem] = []; @IBAction func handleRefresh(refresh: UIRefreshControl?) { SMOffersManager.instance().fetchStoreOffers { (result: SMStoreOffersFetchedResponse?, error: SMError?) in if let r = refresh, r.isRefreshing { r.endRefreshing(); } if let error = error { self.present(UIAlertController(title: "Nothing Fetched", message: error.message, preferredStyle: .alert), animated: true, completion: {}) } else if let offers = result?.offers { self._offers = offers; self.tableView.reloadData(); } } } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return _offers.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Reward Store Cell", for: indexPath) as! RewardStoreTableViewCell let item = _offers[indexPath.row]; cell.header.text = item.name; let df = DateFormatter() df.dateFormat = "dd.MM.yyyy" if let endDate = item.endDate { cell.validDates.text = "This offer is available \(df.string(from: item.startDate)) through \(df.string(from: endDate))" } let points = NSNumber(value: item.price).intValue; cell.points.text = "\(points)"; if (item.media.count > 0) { Common.loadImage(parent: self.tableView, uri: item.media[0].uri, imgView: cell.img, imageHeight: nil, maxHeight: 200) } return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let claimVC = storyboard?.instantiateViewController(withIdentifier: "ClaimOffer") as! PurchaseAOfferViewController claimVC.item = _offers[indexPath.row]; present(claimVC, animated: false) {} } }
3ef2afe81f0ddc053721f7f57052e52a
32.458716
153
0.664107
false
false
false
false
Coderian/SwiftedGPX
refs/heads/master
SwiftedGPX/Elements/Type.swift
mit
1
// // Type.swift // SwiftedGPX // // Created by 佐々木 均 on 2016/02/16. // Copyright © 2016年 S-Parts. All rights reserved. // import Foundation /// GPX Type /// /// [GPX 1.1 schema](http://www.topografix.com/GPX/1/1/gpx.xsd) /// /// <xsd:element name="type" type="xsd:string" minOccurs="0"> /// <xsd:annotation> /// <xsd:documentation> /// Type (classification) of the waypoint. /// </xsd:documentation> /// </xsd:annotation> /// </xsd:element> public class Type : SPXMLElement, HasXMLElementValue, HasXMLElementSimpleValue { public static var elementName: String = "type" public override var parent:SPXMLElement! { didSet { // 複数回呼ばれたて同じものがある場合は追加しない if self.parent.childs.contains(self) == false { self.parent.childs.insert(self) switch parent { case let v as WayPoint: v.value.type = self case let v as Track: v.value.type = self case let v as Route: v.value.type = self case let v as TrackPoint: v.value.type = self case let v as RoutePoint: v.value.type = self default: break } } } } public var value: String! public func makeRelation(contents:String, parent:SPXMLElement) -> SPXMLElement{ self.value = contents self.parent = parent return parent } public required init(attributes:[String:String]){ super.init(attributes: attributes) } }
aac3a5d994c8f6ac9d6640f027459590
30.755102
83
0.576206
false
false
false
false
ivygulch/IVGRouter
refs/heads/master
IVGRouterTests/tests/router/RouteSequenceSpec.swift
mit
1
// // RouteSequenceSpec.swift // IVGRouter // // Created by Douglas Sjoquist on 4/24/16. // Copyright © 2016 Ivy Gulch LLC. All rights reserved. // import UIKit import Quick import Nimble import IVGRouter class RouteSequenceSpec: QuickSpec { override func spec() { describe("RouteSequence") { var router: Router = Router(window: nil, routerContext: RouterContext()) let dummyIdentifier = Identifier(name: "dummy") let mockVisualRouteSegmentA = MockVisualRouteSegment(segmentIdentifier: Identifier(name: "A"), presenterIdentifier: dummyIdentifier, presentedViewController: nil) let mockVisualRouteSegmentB = MockVisualRouteSegment(segmentIdentifier: Identifier(name: "B"), presenterIdentifier: dummyIdentifier, presentedViewController: nil) beforeEach { router = Router(window: nil, routerContext: RouterContext()) } context("with valid registered segments") { var routeSequence: RouteSequence! var validatedRouteSegments: [RouteSegmentType]? beforeEach { router = Router(window: nil, routerContext: RouterContext()) router.routerContext.register(routeSegment: mockVisualRouteSegmentA) router.routerContext.register(routeSegment: mockVisualRouteSegmentB) routeSequence = RouteSequence(source: [ mockVisualRouteSegmentA.segmentIdentifier, mockVisualRouteSegmentB.segmentIdentifier ]) validatedRouteSegments = routeSequence.validatedRouteSegmentsWithRouter(router) } it("should have matching route segments") { if let validatedRouteSegments = validatedRouteSegments { expect(validatedRouteSegments).to(haveCount(routeSequence.items.count)) for index in 0..<routeSequence.items.count { if index < validatedRouteSegments.count { let segmentIdentifier = routeSequence.items[index].segmentIdentifier let validatedRouteSegment = validatedRouteSegments[index] expect(validatedRouteSegment.segmentIdentifier).to(equal(segmentIdentifier)) } } } else { expect(validatedRouteSegments).toNot(beNil()) } } } context("with valid but unregistered segments") { var routeSequence: RouteSequence! var validatedRouteSegments: [RouteSegmentType]? beforeEach { router = Router(window: nil, routerContext: RouterContext()) routeSequence = RouteSequence(source: [ mockVisualRouteSegmentA.segmentIdentifier, mockVisualRouteSegmentB.segmentIdentifier ]) validatedRouteSegments = routeSequence.validatedRouteSegmentsWithRouter(router) } it("should not have validated route segments") { expect(validatedRouteSegments).to(beNil()) } } } } }
fdfc537a0b33dd9c5be63980472b43f4
39.576471
174
0.57292
false
false
false
false
lfaoro/Cast
refs/heads/master
Cast/UserNotifications.swift
mit
1
// // Created by Leonardo on 29/07/2015. // Copyright © 2015 Leonardo Faoro. All rights reserved. // import Cocoa final class UserNotifications: NSObject { //--------------------------------------------------------------------------- var notificationCenter: NSUserNotificationCenter! var didActivateNotificationURL: NSURL? //--------------------------------------------------------------------------- override init() { super.init() notificationCenter = NSUserNotificationCenter.defaultUserNotificationCenter() notificationCenter.delegate = self } //--------------------------------------------------------------------------- private func createNotification(title: String, subtitle: String) -> NSUserNotification { let notification = NSUserNotification() notification.title = title notification.subtitle = subtitle notification.informativeText = "Copied to your clipboard" notification.actionButtonTitle = "Open URL" notification.soundName = NSUserNotificationDefaultSoundName return notification } //--------------------------------------------------------------------------- func pushNotification(openURL url: String, title: String = "Casted to gist.GitHub.com") { didActivateNotificationURL = NSURL(string: url)! let notification = self.createNotification(title, subtitle: url) notificationCenter.deliverNotification(notification) startUserNotificationTimer() //IRC: calling from here doesn't work } //--------------------------------------------------------------------------- func pushNotification(error error: String, description: String = "An error occured, please try again.") { let notification = NSUserNotification() notification.title = error notification.informativeText = description notification.soundName = NSUserNotificationDefaultSoundName notification.hasActionButton = false notificationCenter.deliverNotification(notification) startUserNotificationTimer() } //--------------------------------------------------------------------------- private func startUserNotificationTimer() { print(__FUNCTION__) app.timer = NSTimer .scheduledTimerWithTimeInterval( 10.0, target: self, selector: "removeUserNotifcationsAction:", userInfo: nil, repeats: false) } //--------------------------------------------------------------------------- func removeUserNotifcationsAction(timer: NSTimer) { print(__FUNCTION__) notificationCenter.removeAllDeliveredNotifications() timer.invalidate() } //--------------------------------------------------------------------------- } //MARK:- NSUserNotificationCenterDelegate extension UserNotifications: NSUserNotificationCenterDelegate { //--------------------------------------------------------------------------- func userNotificationCenter(center: NSUserNotificationCenter, didActivateNotification notification: NSUserNotification) { print("notification pressed") if let url = didActivateNotificationURL { NSWorkspace.sharedWorkspace().openURL(url) } else { center.removeAllDeliveredNotifications() } } // executes an action whenever the notification is pressed //--------------------------------------------------------------------------- func userNotificationCenter(center: NSUserNotificationCenter, shouldPresentNotification notification: NSUserNotification) -> Bool { return true } // forces the notification to display even when app is active app //--------------------------------------------------------------------------- }
f3a3a2cc239b726bb70ff07146ea31d5
40.75
90
0.5931
false
false
false
false
blockchain/My-Wallet-V3-iOS
refs/heads/master
Modules/FeatureKYC/Sources/FeatureKYCUI/Identity Verification/VeriffController.swift
lgpl-3.0
1
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import Localization import PlatformKit import UIKit import Veriff protocol VeriffController: UIViewController, VeriffSdkDelegate { var veriff: VeriffSdk { get } // Actions func veriffCredentialsRequest() func launchVeriffController(credentials: VeriffCredentials) // Completion handlers func onVeriffSubmissionCompleted() func trackInternalVeriffError(_ error: InternalVeriffError) func onVeriffError(message: String) func onVeriffCancelled() } extension VeriffController { internal var veriff: VeriffSdk { VeriffSdk.shared } func launchVeriffController(credentials: VeriffCredentials) { veriff.delegate = self veriff.startAuthentication(sessionUrl: credentials.url) } } enum InternalVeriffError: Swift.Error { case cameraUnavailable case microphoneUnavailable case serverError case localError case networkError case uploadError case videoFailed case deprecatedSDKVersion case unknown init(veriffError: VeriffSdk.Error) { switch veriffError { case .cameraUnavailable: self = .cameraUnavailable case .microphoneUnavailable: self = .microphoneUnavailable case .serverError: self = .serverError case .localError: self = .localError case .networkError: self = .networkError case .uploadError: self = .uploadError case .videoFailed: self = .videoFailed case .deprecatedSDKVersion: self = .deprecatedSDKVersion case .unknown: self = .unknown @unknown default: self = .unknown } } } extension VeriffSdk.Error { var localizedErrorMessage: String { switch self { case .cameraUnavailable: return LocalizationConstants.Errors.cameraAccessDeniedMessage case .microphoneUnavailable: return LocalizationConstants.Errors.microphoneAccessDeniedMessage case .deprecatedSDKVersion, .localError, .networkError, .serverError, .unknown, .uploadError, .videoFailed: return LocalizationConstants.Errors.genericError @unknown default: return LocalizationConstants.Errors.genericError } } }
cdf20321460c0ca18e7f091152a3ddf4
24.402062
77
0.650568
false
false
false
false
m-alani/contests
refs/heads/master
hackerrank/GameOfThrones-I.swift
mit
1
// // GameOfThrones-I.swift // // Practice solution - Marwan Alani - 2017 // // Check the problem (and run the code) on HackerRank @ https://www.hackerrank.com/challenges/game-of-thrones // Note: make sure that you select "Swift" from the top-right language menu of the code editor when testing this code // // Read Input if let input = readLine() { var oddChars: Set<Character> = Set() let word = input.characters // Process the input line one character at a time. Maintain a set of all characters with odd occurences in the input for char in word { if let exists = oddChars.remove(char) {} else { oddChars.insert(char) } } // Check for passing condition: // The input line can have 1 character at most with odd occurences let output = oddChars.count < 2 ? "YES" : "NO" // Print Output print(output) }
32c521951ccbcea717c3f37c42d7c56b
30.444444
118
0.685512
false
false
false
false
mrdepth/EVEOnlineAPI
refs/heads/master
EVEAPI/EVEAPI/codegen/Fittings.swift
mit
1
import Foundation import Alamofire import Futures public extension ESI { var fittings: Fittings { return Fittings(esi: self) } struct Fittings { let esi: ESI @discardableResult public func deleteFitting(characterID: Int, fittingID: Int, cachePolicy: URLRequest.CachePolicy = .useProtocolCachePolicy) -> Future<ESI.Result<String>> { let scopes = esi.token?.scopes ?? [] guard scopes.contains("esi-fittings.write_fittings.v1") else {return .init(.failure(ESIError.forbidden))} let body: Data? = nil var headers = HTTPHeaders() headers["Accept"] = "application/json" headers["Content-Type"] = "application/json" var query = [URLQueryItem]() query.append(URLQueryItem(name: "datasource", value: esi.server.rawValue)) let url = esi.baseURL + "/characters/\(characterID)/fittings/\(fittingID)/" let components = NSURLComponents(string: url)! components.queryItems = query let promise = Promise<ESI.Result<String>>() esi.request(components.url!, method: .delete, encoding: body ?? URLEncoding.default, headers: headers, cachePolicy: cachePolicy).validateESI().responseESI { (response: DataResponse<String>) in promise.set(response: response, cached: nil) } return promise.future } @discardableResult public func getFittings(characterID: Int, ifNoneMatch: String? = nil, cachePolicy: URLRequest.CachePolicy = .useProtocolCachePolicy) -> Future<ESI.Result<[Fittings.Fitting]>> { let scopes = esi.token?.scopes ?? [] guard scopes.contains("esi-fittings.read_fittings.v1") else {return .init(.failure(ESIError.forbidden))} let body: Data? = nil var headers = HTTPHeaders() headers["Accept"] = "application/json" if let v = ifNoneMatch?.httpQuery { headers["If-None-Match"] = v } var query = [URLQueryItem]() query.append(URLQueryItem(name: "datasource", value: esi.server.rawValue)) let url = esi.baseURL + "/characters/\(characterID)/fittings/" let components = NSURLComponents(string: url)! components.queryItems = query let promise = Promise<ESI.Result<[Fittings.Fitting]>>() esi.request(components.url!, method: .get, encoding: body ?? URLEncoding.default, headers: headers, cachePolicy: cachePolicy).validateESI().responseESI { (response: DataResponse<[Fittings.Fitting]>) in promise.set(response: response, cached: 300.0) } return promise.future } @discardableResult public func createFitting(characterID: Int, fitting: Fittings.MutableFitting, cachePolicy: URLRequest.CachePolicy = .useProtocolCachePolicy) -> Future<ESI.Result<Fittings.CreateFittingResult>> { let scopes = esi.token?.scopes ?? [] guard scopes.contains("esi-fittings.write_fittings.v1") else {return .init(.failure(ESIError.forbidden))} let body = try? JSONEncoder().encode(fitting) var headers = HTTPHeaders() headers["Accept"] = "application/json" headers["Content-Type"] = "application/json" var query = [URLQueryItem]() query.append(URLQueryItem(name: "datasource", value: esi.server.rawValue)) let url = esi.baseURL + "/characters/\(characterID)/fittings/" let components = NSURLComponents(string: url)! components.queryItems = query let promise = Promise<ESI.Result<Fittings.CreateFittingResult>>() esi.request(components.url!, method: .post, encoding: body ?? URLEncoding.default, headers: headers, cachePolicy: cachePolicy).validateESI().responseESI { (response: DataResponse<Fittings.CreateFittingResult>) in promise.set(response: response, cached: nil) } return promise.future } public struct CreateFittingResult: Codable, Hashable { public var fittingID: Int public init(fittingID: Int) { self.fittingID = fittingID } enum CodingKeys: String, CodingKey, DateFormatted { case fittingID = "fitting_id" var dateFormatter: DateFormatter? { switch self { default: return nil } } } } public struct MutableFitting: Codable, Hashable { public var localizedDescription: String public var items: [Fittings.Item] public var name: String public var shipTypeID: Int public init(localizedDescription: String, items: [Fittings.Item], name: String, shipTypeID: Int) { self.localizedDescription = localizedDescription self.items = items self.name = name self.shipTypeID = shipTypeID } enum CodingKeys: String, CodingKey, DateFormatted { case localizedDescription = "description" case items case name case shipTypeID = "ship_type_id" var dateFormatter: DateFormatter? { switch self { default: return nil } } } } public struct Fitting: Codable, Hashable { public var localizedDescription: String public var fittingID: Int public var items: [Fittings.Item] public var name: String public var shipTypeID: Int public init(localizedDescription: String, fittingID: Int, items: [Fittings.Item], name: String, shipTypeID: Int) { self.localizedDescription = localizedDescription self.fittingID = fittingID self.items = items self.name = name self.shipTypeID = shipTypeID } enum CodingKeys: String, CodingKey, DateFormatted { case localizedDescription = "description" case fittingID = "fitting_id" case items case name case shipTypeID = "ship_type_id" var dateFormatter: DateFormatter? { switch self { default: return nil } } } } public struct Item: Codable, Hashable { public enum Flag: String, Codable, HTTPQueryable { case cargo = "Cargo" case droneBay = "DroneBay" case fighterBay = "FighterBay" case hiSlot0 = "HiSlot0" case hiSlot1 = "HiSlot1" case hiSlot2 = "HiSlot2" case hiSlot3 = "HiSlot3" case hiSlot4 = "HiSlot4" case hiSlot5 = "HiSlot5" case hiSlot6 = "HiSlot6" case hiSlot7 = "HiSlot7" case invalid = "Invalid" case loSlot0 = "LoSlot0" case loSlot1 = "LoSlot1" case loSlot2 = "LoSlot2" case loSlot3 = "LoSlot3" case loSlot4 = "LoSlot4" case loSlot5 = "LoSlot5" case loSlot6 = "LoSlot6" case loSlot7 = "LoSlot7" case medSlot0 = "MedSlot0" case medSlot1 = "MedSlot1" case medSlot2 = "MedSlot2" case medSlot3 = "MedSlot3" case medSlot4 = "MedSlot4" case medSlot5 = "MedSlot5" case medSlot6 = "MedSlot6" case medSlot7 = "MedSlot7" case rigSlot0 = "RigSlot0" case rigSlot1 = "RigSlot1" case rigSlot2 = "RigSlot2" case serviceSlot0 = "ServiceSlot0" case serviceSlot1 = "ServiceSlot1" case serviceSlot2 = "ServiceSlot2" case serviceSlot3 = "ServiceSlot3" case serviceSlot4 = "ServiceSlot4" case serviceSlot5 = "ServiceSlot5" case serviceSlot6 = "ServiceSlot6" case serviceSlot7 = "ServiceSlot7" case subSystemSlot0 = "SubSystemSlot0" case subSystemSlot1 = "SubSystemSlot1" case subSystemSlot2 = "SubSystemSlot2" case subSystemSlot3 = "SubSystemSlot3" public var httpQuery: String? { return rawValue } } public var flag: Fittings.Item.Flag public var quantity: Int public var typeID: Int public init(flag: Fittings.Item.Flag, quantity: Int, typeID: Int) { self.flag = flag self.quantity = quantity self.typeID = typeID } enum CodingKeys: String, CodingKey, DateFormatted { case flag case quantity case typeID = "type_id" var dateFormatter: DateFormatter? { switch self { default: return nil } } } } } }
7abfd48e553d31e1af49bc4360fe9060
28.267176
215
0.676448
false
false
false
false
nickswalker/ASCIIfy
refs/heads/master
Tests/TestBlockGrid.swift
mit
1
// // Copyright for portions of ASCIIfy are held by Barış Koç, 2014 as part of // project BKAsciiImage and Amy Dyer, 2012 as part of project Ascii. All other copyright // for ASCIIfy are held by Nick Walker, 2016. // // 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 XCTest @testable import ASCIIfy class TestBlockGrid: XCTestCase { var largeChecker: Image! override func setUp() { super.setUp() let bundle = Bundle(for: type(of: self)) largeChecker = { let fileLocation = bundle.path(forResource: "checker-1024", ofType: "png")! let image = Image(contentsOfFile: fileLocation)! return image }() } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testPixelGridImageConstructor() { let result = BlockGrid(image: largeChecker) XCTAssertEqual(result.width, Int(largeChecker.size.width)) XCTAssertEqual(result.height, Int(largeChecker.size.height)) let black = BlockGrid.Block(r: 0, g: 0, b:0, a: 1) let white = BlockGrid.Block(r: 1, g: 1, b:1, a: 1) XCTAssertEqual(result.block(atRow: 0, column: 0), white) XCTAssertEqual(result.block(atRow:1, column: 0), black) } func testConstructionFromImagePerformance() { measure { let _ = BlockGrid(image: self.largeChecker) } } }
384afb1b4137e9c661ad5c489722caba
41.3
111
0.689125
false
true
false
false
leo150/Pelican
refs/heads/develop
Sources/Pelican/API/Types/Markup/InlineKey.swift
mit
1
// // InlineKey.swift // Pelican // // Created by Takanu Kyriako on 31/08/2017. // import Foundation import Vapor import FluentProvider /** Defines a single keyboard key on a `MarkupInline` keyboard. Each key supports one of 4 different modes: _ _ _ _ _ **Callback Data** This sends a small String back to the bot as a `CallbackQuery`, which is automatically filtered back to the session and to a `callbackState` if one exists. Alternatively if the keyboard the button belongs to is part of a `Prompt`, it will automatically be received by it in the respective ChatSession, and the prompt will respond based on how you have set it up. **URL** The button when pressed will re-direct users to a webpage. **Inine Query Switch** This can only be used when the bot supports Inline Queries. This prompts the user to select one of their chats to open it, and when open the client will insert the bot‘s username and a specified query in the input field. **Inline Query Current Chat** This can only be used when the bot supports Inline Queries. Pressing the button will insert the bot‘s username and an optional specific inline query in the current chat's input field. */ final public class MarkupInlineKey: Model, Equatable { public var storage = Storage() public var text: String // Label text public var data: String public var type: InlineKeyType /** Creates a `MarkupInlineKey` as a URL key. This key type causes the specified URL to be opened by the client when button is pressed. If it links to a public Telegram chat or bot, it will be immediately opened. */ public init(fromURL url: String, text: String) { self.text = text self.data = url self.type = .url } /** Creates a `MarkupInlineKey` as a Callback Data key. This key sends the defined callback data back to the bot to be handled. - parameter callback: The data to be sent back to the bot once pressed. Accepts 1-64 bytes of data. - parameter text: The text label to be shown on the button. Set to nil if you wish it to be the same as the callback. */ public init?(fromCallbackData callback: String, text: String?) { // Check to see if the callback meets the byte requirement. if callback.lengthOfBytes(using: String.Encoding.utf8) > 64 { PLog.error("The MarkupKey with the text label, \"\(String(describing:text))\" has a callback of \(callback) that exceeded 64 bytes.") return nil } // Check to see if we have a label if text != nil { self.text = text! } else { self.text = callback } self.data = callback self.type = .callbackData } /** Creates a `MarkupInlineKey` as a Current Chat Inline Query key. This key prompts the user to select one of their chats, open it and insert the bot‘s username and the specified query in the input field. */ public init(fromInlineQueryCurrent data: String, text: String) { self.text = text self.data = data self.type = .switchInlineQuery_currentChat } /** Creates a `MarkupInlineKey` as a New Chat Inline Query key. This key inserts the bot‘s username and the specified inline query in the current chat's input field. Can be empty. */ public init(fromInlineQueryNewChat data: String, text: String) { self.text = text self.data = data self.type = .switchInlineQuery } static public func ==(lhs: MarkupInlineKey, rhs: MarkupInlineKey) -> Bool { if lhs.text != rhs.text { return false } if lhs.type != rhs.type { return false } if lhs.data != rhs.data { return false } return true } // Ignore context, just try and build an object from a node. public required init(row: Row) throws { text = try row.get("text") if row["url"] != nil { data = try row.get("url") type = .url } else if row["callback_data"] != nil { data = try row.get("callback_data") type = .url } else if row["switch_inline_query"] != nil { data = try row.get("switch_inline_query") type = .url } else if row["switch_inline_query_current_chat"] != nil { data = try row.get("switch_inline_query_current_chat") type = .url } else { data = "" type = .url } } public func makeRow() throws -> Row { var row = Row() try row.set("text", text) switch type { case .url: try row.set("url", data) case .callbackData: try row.set("callback_data", data) case .switchInlineQuery: try row.set("switch_inline_query", data) case .switchInlineQuery_currentChat: try row.set("switch_inline_query_current_chat", data) } return row } }
d07d976547af5b16b1816b57bad5d4fe
27.124224
138
0.696334
false
false
false
false
Jakobeha/lAzR4t
refs/heads/master
lAzR4t Shared/Code/GridElem/GridElemController.swift
mit
1
// // GridController.swift // lAzR4t // // Created by Jakob Hain on 9/30/17. // Copyright © 2017 Jakob Hain. All rights reserved. // import Foundation final class GridElemController<TSub: Elem>: ElemController<GridElem<TSub>> { let grid: GridController<TSub> var _pos: CellPos var pos: CellPos { get { return _pos } set(newPos) { _pos = newPos grid.node.position = pos.toDisplay } } var frame: CellFrame { return curModel.frame } ///Not this element's actual node. This is an actual represetnation of a grid. let gridNode: GridElemNode? override var curModel: GridElem<TSub> { return GridElem(pos: self.pos, grid: self.grid.curModel) } convenience init(frame: CellFrame, display: Bool) { self.init(pos: frame.pos, size: frame.size, display: display) } convenience init(pos: CellPos, size: CellSize, display: Bool) { let node = ElemNode() node.position = pos.toDisplay self.init( grid: GridController(size: size, node: node), pos: pos, display: display ) } private init(grid: GridController<TSub>, pos: CellPos, display: Bool) { self.grid = grid self._pos = pos self.gridNode = display ? GridElemNode(cellSize: grid.curModel.size) : nil super.init(node: grid.node) assert(grid.elemOwner == nil, "Grid can't be owned by two elements") grid._elemOwner = self if let gridNode = gridNode { grid.node.addChild(gridNode) } } } extension GridElemController where TSub: ElemToController { convenience init(curModel: GridElem<TSub>, display: Bool) { let node = ElemNode() node.position = curModel.pos.toDisplay self.init( grid: GridController(curModel: curModel.grid, node: node), pos: curModel.pos, display: display ) } }
af218ebc302f4a90cff6a22f16790f56
29.121212
82
0.603119
false
false
false
false
bfolder/Sweather
refs/heads/master
Sweather/Sweather.swift
mit
1
// // Sweather.swift // // Created by Heiko Dreyer on 08/12/14. // Copyright (c) 2014 boxedfolder.com. All rights reserved. // import Foundation import CoreLocation extension String { func replace(_ string:String, replacement:String) -> String { return self.replacingOccurrences(of: string, with: replacement, options: NSString.CompareOptions.literal, range: nil) } func replaceWhitespace() -> String { return self.replace(" ", replacement: "+") } } open class Sweather { public enum TemperatureFormat: String { case Celsius = "metric" case Fahrenheit = "imperial" } public enum Result { case success(URLResponse?, NSDictionary?) case Error(URLResponse?, NSError?) public func data() -> NSDictionary? { switch self { case .success(_, let dictionary): return dictionary case .Error(_, _): return nil } } public func response() -> URLResponse? { switch self { case .success(let response, _): return response case .Error(let response, _): return response } } public func error() -> NSError? { switch self { case .success(_, _): return nil case .Error(_, let error): return error } } } open var apiKey: String open var apiVersion: String open var language: String open var temperatureFormat: TemperatureFormat fileprivate struct Const { static let basePath = "http://api.openweathermap.org/data/" } // MARK: - // MARK: Initialization public convenience init(apiKey: String) { self.init(apiKey: apiKey, language: "en", temperatureFormat: .Fahrenheit, apiVersion: "2.5") } public convenience init(apiKey: String, temperatureFormat: TemperatureFormat) { self.init(apiKey: apiKey, language: "en", temperatureFormat: temperatureFormat, apiVersion: "2.5") } public convenience init(apiKey: String, language: String, temperatureFormat: TemperatureFormat) { self.init(apiKey: apiKey, language: language, temperatureFormat: temperatureFormat, apiVersion: "2.5") } public init(apiKey: String, language: String, temperatureFormat: TemperatureFormat, apiVersion: String) { self.apiKey = apiKey self.temperatureFormat = temperatureFormat self.apiVersion = apiVersion self.language = language } // MARK: - // MARK: Retrieving current weather data open func currentWeather(_ cityName: String, callback: @escaping (Result) -> ()) { call("/weather?q=\(cityName.replaceWhitespace())", callback: callback) } open func currentWeather(_ coordinate: CLLocationCoordinate2D, callback: @escaping (Result) -> ()) { let coordinateString = "lat=\(coordinate.latitude)&lon=\(coordinate.longitude)" call("/weather?\(coordinateString)", callback: callback) } open func currentWeather(_ cityId: Int, callback: @escaping (Result) -> ()) { call("/weather?id=\(cityId)", callback: callback) } // MARK: - // MARK: Retrieving daily forecast open func dailyForecast(_ cityName: String, callback: @escaping (Result) -> ()) { call("/forecast/daily?q=\(cityName.replaceWhitespace())", callback: callback) } open func dailyForecast(_ coordinate: CLLocationCoordinate2D, callback: @escaping (Result) -> ()) { call("/forecast/daily?lat=\(coordinate.latitude)&lon=\(coordinate.longitude)", callback: callback) } open func dailyForecast(_ cityId: Int, callback: @escaping (Result) -> ()) { call("/forecast/daily?id=\(cityId)", callback: callback) } // MARK: - // MARK: Retrieving forecast open func forecast(_ cityName: String, callback: @escaping (Result) -> ()) { call("/forecast?q=\(cityName.replaceWhitespace())", callback: callback) } open func forecast(_ coordinate: CLLocationCoordinate2D, callback:@escaping (Result) -> ()) { call("/forecast?lat=\(coordinate.latitude)&lon=\(coordinate.longitude)", callback: callback) } open func forecast(_ cityId: Int, callback: @escaping (Result) ->()) { call("/forecast?id=\(cityId)", callback: callback) } // MARK: - // MARK: Retrieving city open func findCity(_ cityName: String, callback: @escaping (Result) -> ()) { call("/find?q=\(cityName.replaceWhitespace())", callback: callback) } open func findCity(_ coordinate: CLLocationCoordinate2D, callback: @escaping (Result) -> ()) { call("/find?lat=\(coordinate.latitude)&lon=\(coordinate.longitude)", callback: callback) } // MARK: - // MARK: Call the api fileprivate func call(_ method: String, callback: @escaping (Result) -> ()) { let url = Const.basePath + apiVersion + method + "&APPID=\(apiKey)&lang=\(language)&units=\(temperatureFormat.rawValue)" let request = URLRequest(url: URL(string: url)!) let currentQueue = OperationQueue.current let task = URLSession.shared.dataTask(with: request, completionHandler: { data, response, error in var error: NSError? = error as NSError? var dictionary: NSDictionary? if let data = data { do { dictionary = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? NSDictionary } catch let e as NSError { error = e } } currentQueue?.addOperation { var result = Result.success(response, dictionary) if error != nil { result = Result.Error(response, error) } callback(result) } }) task.resume() } }
d7517f03c9afcb6a7cae5d8d8eef9333
33.227778
128
0.585295
false
false
false
false
IngmarStein/swift
refs/heads/master
validation-test/compiler_crashers_fixed/01170-getselftypeforcontainer.swift
apache-2.0
11
// 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 // RUN: not %target-swift-frontend %s -parse class k<g>: d { var f: g init(f: g) { l. d { typealias j = je: Int -> Int = { } let d: Int = { c, b in }(f, e) } class d { func l<j where j: h, j: d>(l: j) { } func i(k: b) -> <j>(() -> j) -> b { } class j { func y((Any, j))(v: (Any, AnyObject)) { } } func w(j: () -> ()) { } class v { l _ = w() { } } func v<x>() -> (x, x -> x) -> x { l y j s<q : l, y: l m y.n == q.n> { } o l { } y q<x> { } o n { } class r { func s() -> p { } } class w: r, n { } func b<c { enum b { } } } class d<j : i, f : i where j.i == f> : e { } class d<j, f> { } protocol i { } protocol e { } protocol i : d { func d
42c0d37a754d6250ca2f281839ee4d21
15.147541
78
0.551269
false
false
false
false
S2dentik/Taylor
refs/heads/master
TaylorFramework/Modules/temper/Rules/CyclomaticComplexityRule.swift
mit
4
// // CyclomaticComplexityRule.swift // Temper // // Created by Mihai Seremet on 9/9/15. // Copyright © 2015 Yopeso. All rights reserved. // final class CyclomaticComplexityRule: Rule { let rule = "CyclomaticComplexity" var priority: Int = 2 { willSet { if newValue > 0 { self.priority = newValue } } } let externalInfoUrl = "http://phpmd.org/rules/codesize.html#cyclomaticcomplexity" var limit: Int = 5 { willSet { if newValue > 0 { self.limit = newValue } } } fileprivate let decisionalComponentTypes = [ComponentType.if, .while, .for, .case, .elseIf, .ternary, .nilCoalescing, .guard] func checkComponent(_ component: Component) -> Result { if component.type != ComponentType.function { return (true, nil, nil) } let complexity = findComplexityForComponent(component) + 1 if complexity > limit { let name = component.name ?? "unknown" let message = formatMessage(name, value: complexity) return (false, message, complexity) } return (true, nil, complexity) } func formatMessage(_ name: String, value: Int) -> String { return "The method '\(name)' has a Cyclomatic Complexity of \(value). The allowed Cyclomatic Complexity is \(limit)" } fileprivate func findComplexityForComponent(_ component: Component) -> Int { let complexity = decisionalComponentTypes.contains(component.type) ? 1 : 0 return component.components.map({ findComplexityForComponent($0) }).reduce(complexity, +) } }
31fc9c29afc8b4539a9b362ce7ea4cf1
33.854167
129
0.613867
false
false
false
false
Stanbai/MultiThreadBasicDemo
refs/heads/master
Operation/Swift/NSOperation/NSOperation/ImageLoadOperation.swift
mit
1
// // ImageLoadOperation.swift // NSOperation // // Created by Stan on 2017-07-24. // Copyright © 2017 stan. All rights reserved. // import UIKit class ImageLoadOperation: Operation { let item: Item var dataTask: URLSessionDataTask? let complete: (UIImage?) -> Void init(forItem: Item, execute: @escaping (UIImage?) -> Void) { item = forItem complete = execute super.init() } /* start: 所有并行的 Operations 都必须重写这个方法,然后在你想要执行的线程中手动调用这个方法。注意:任何时候都不能调用父类的start方法。 main: 在start方法中调用,但是注意要定义独立的自动释放池与别的线程区分开。 isExecuting: 是否执行中,需要实现KVO通知机制。 isFinished: 是否已完成,需要实现KVO通知机制。 isAsynchronous: 该方法默认返回 假 ,表示非并发执行。并发执行需要自定义并且返回 真。后面会根据这个返回值来决定是否并发。 */ fileprivate var _executing : Bool = false override var isExecuting: Bool { get { return _executing } set { if newValue != _executing { willChangeValue(forKey: "isExecuting") _executing = newValue didChangeValue(forKey: "isExecuting") } } } fileprivate var _finished : Bool = false override var isFinished: Bool { get { return _finished } set { if newValue != _finished { willChangeValue(forKey: "isFinished") _finished = newValue didChangeValue(forKey: "isFinished") } } } override var isAsynchronous: Bool { get { return true } } override func start() { if !isCancelled { isExecuting = true isFinished = false startOperation() } else { isFinished = true } if let url = item.imageUrl() { let dataTask = URLSession.shared.dataTask(with: url, completionHandler: {[weak self](data, response, error) in if let data = data { let image = UIImage(data: data) self?.endOperationWith(image: image) } else { self?.endOperationWith(image: nil) } }) dataTask.resume() } else { self.endOperationWith(image: nil) } } override func cancel() { if !isCancelled { cancelOperation() } super.cancel() completeOperation() } // MARK: - 自定义对外的方法 func startOperation() { completeOperation() } func cancelOperation() { dataTask?.cancel() } func completeOperation() { if isExecuting && !isFinished { isExecuting = false isFinished = true } } func endOperationWith(image: UIImage?) { if !isCancelled { complete(image) completeOperation() } } }
828fe37047dc8f45b9fdde19fc04aaaa
23.663866
122
0.520954
false
false
false
false
yonaskolb/XcodeGen
refs/heads/master
Sources/ProjectSpec/Dependency.swift
mit
1
import Foundation import JSONUtilities public struct Dependency: Equatable { public static let removeHeadersDefault = true public static let implicitDefault = false public static let weakLinkDefault = false public static let platformFilterDefault: PlatformFilter = .all public var type: DependencyType public var reference: String public var embed: Bool? public var codeSign: Bool? public var removeHeaders: Bool = removeHeadersDefault public var link: Bool? public var implicit: Bool = implicitDefault public var weakLink: Bool = weakLinkDefault public var platformFilter: PlatformFilter = platformFilterDefault public var platforms: Set<Platform>? public var copyPhase: BuildPhaseSpec.CopyFilesSettings? public init( type: DependencyType, reference: String, embed: Bool? = nil, codeSign: Bool? = nil, link: Bool? = nil, implicit: Bool = implicitDefault, weakLink: Bool = weakLinkDefault, platformFilter: PlatformFilter = platformFilterDefault, platforms: Set<Platform>? = nil, copyPhase: BuildPhaseSpec.CopyFilesSettings? = nil ) { self.type = type self.reference = reference self.embed = embed self.codeSign = codeSign self.link = link self.implicit = implicit self.weakLink = weakLink self.platformFilter = platformFilter self.platforms = platforms self.copyPhase = copyPhase } public enum PlatformFilter: String, Equatable { case all case iOS case macOS } public enum CarthageLinkType: String { case dynamic case `static` public static let `default` = dynamic } public enum DependencyType: Hashable { case target case framework case carthage(findFrameworks: Bool?, linkType: CarthageLinkType) case sdk(root: String?) case package(product: String?) case bundle } } extension Dependency { public var uniqueID: String { switch type { case .package(let product): if let product = product { return "\(reference)/\(product)" } else { return reference } default: return reference } } } extension Dependency: Hashable { public func hash(into hasher: inout Hasher) { hasher.combine(reference) } } extension Dependency: JSONObjectConvertible { public init(jsonDictionary: JSONDictionary) throws { if let target: String = jsonDictionary.json(atKeyPath: "target") { type = .target reference = target } else if let framework: String = jsonDictionary.json(atKeyPath: "framework") { type = .framework reference = framework } else if let carthage: String = jsonDictionary.json(atKeyPath: "carthage") { let findFrameworks: Bool? = jsonDictionary.json(atKeyPath: "findFrameworks") let carthageLinkType: CarthageLinkType = (jsonDictionary.json(atKeyPath: "linkType") as String?).flatMap(CarthageLinkType.init(rawValue:)) ?? .default type = .carthage(findFrameworks: findFrameworks, linkType: carthageLinkType) reference = carthage } else if let sdk: String = jsonDictionary.json(atKeyPath: "sdk") { let sdkRoot: String? = jsonDictionary.json(atKeyPath: "root") type = .sdk(root: sdkRoot) reference = sdk } else if let package: String = jsonDictionary.json(atKeyPath: "package") { let product: String? = jsonDictionary.json(atKeyPath: "product") type = .package(product: product) reference = package } else if let bundle: String = jsonDictionary.json(atKeyPath: "bundle") { type = .bundle reference = bundle } else { throw SpecParsingError.invalidDependency(jsonDictionary) } embed = jsonDictionary.json(atKeyPath: "embed") codeSign = jsonDictionary.json(atKeyPath: "codeSign") link = jsonDictionary.json(atKeyPath: "link") if let bool: Bool = jsonDictionary.json(atKeyPath: "removeHeaders") { removeHeaders = bool } if let bool: Bool = jsonDictionary.json(atKeyPath: "implicit") { implicit = bool } if let bool: Bool = jsonDictionary.json(atKeyPath: "weak") { weakLink = bool } if let platformFilterString: String = jsonDictionary.json(atKeyPath: "platformFilter"), let platformFilter = PlatformFilter(rawValue: platformFilterString) { self.platformFilter = platformFilter } else { self.platformFilter = .all } if let platforms: [ProjectSpec.Platform] = jsonDictionary.json(atKeyPath: "platforms") { self.platforms = Set(platforms) } if let object: JSONDictionary = jsonDictionary.json(atKeyPath: "copy") { copyPhase = try BuildPhaseSpec.CopyFilesSettings(jsonDictionary: object) } } } extension Dependency: JSONEncodable { public func toJSONValue() -> Any { var dict: [String: Any?] = [ "embed": embed, "codeSign": codeSign, "link": link, "platforms": platforms?.map(\.rawValue).sorted(), "copy": copyPhase?.toJSONValue(), ] if removeHeaders != Dependency.removeHeadersDefault { dict["removeHeaders"] = removeHeaders } if implicit != Dependency.implicitDefault { dict["implicit"] = implicit } if weakLink != Dependency.weakLinkDefault { dict["weak"] = weakLink } switch type { case .target: dict["target"] = reference case .framework: dict["framework"] = reference case .carthage(let findFrameworks, let linkType): dict["carthage"] = reference if let findFrameworks = findFrameworks { dict["findFrameworks"] = findFrameworks } dict["linkType"] = linkType.rawValue case .sdk: dict["sdk"] = reference case .package: dict["package"] = reference case .bundle: dict["bundle"] = reference } return dict } } extension Dependency: PathContainer { static var pathProperties: [PathProperty] { [ .string("framework"), ] } }
eaf1364499f89d3ca18a5a7faa834054
32.323232
165
0.607305
false
false
false
false
chrisjmendez/swift-exercises
refs/heads/master
Music/Apple/iTunesQueryAdvanced/iTunesQueryAdvanced/APIController.swift
mit
1
// // APIController.swift // iTunesQueryAdvanced // // Created by tommy trojan on 5/20/15. // Copyright (c) 2015 Chris Mendez. All rights reserved. // import Foundation protocol APIControllerProtocol { func didReceiveAPIResults(results: NSArray) } class APIController{ var delegate: APIControllerProtocol? func searchItunesFor(searchTerm: String, searchCategory: String) { // The iTunes API wants multiple terms separated by + symbols, so replace spaces with + signs let itunesSearchTerm = searchTerm.stringByReplacingOccurrencesOfString(" ", withString: "+", options: NSStringCompareOptions.CaseInsensitiveSearch, range: nil) // Now escape anything else that isn't URL-friendly if let escapedSearchTerm = itunesSearchTerm.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding) { let urlPath = "http://itunes.apple.com/search?term=\(escapedSearchTerm)&media=\(searchCategory)" let url = NSURL(string: urlPath) let session = NSURLSession.sharedSession() let task = session.dataTaskWithURL(url!, completionHandler: {data, response, error -> Void in print("\(escapedSearchTerm) query complete.") if(error != nil) { // If there is an error in the web request, print it to the console print(error!.localizedDescription) } var err: NSError? let jsonResult = (try! NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers)) as! NSDictionary if(err != nil) { // If there is an error parsing JSON, print it to the console print("JSON Error \(err!.localizedDescription)") } //Trigger the delegate once the data has been parsed if let results: NSArray = jsonResult["results"] as? NSArray { self.delegate?.didReceiveAPIResults(results) } }) task.resume() } } } extension String { /// Percent escape value to be added to a URL query value as specified in RFC 3986 /// - returns: Return precent escaped string. func stringByReplacingSpaceWithPlusEncodingForQueryValue() -> String? { let term = self.stringByReplacingOccurrencesOfString(" ", withString: "+", options: NSStringCompareOptions.CaseInsensitiveSearch, range: nil) // Anything which is not URL-friendly is escaped let escapedTerm = term.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)! return escapedTerm } }
32943acfb2797c67dc86c34fc7b66567
42.790323
167
0.642357
false
false
false
false
MakeSchool/TripPlanner
refs/heads/master
ArgoTests/Tests/DecodedTests.swift
mit
9
import XCTest import Argo class DecodedTests: XCTestCase { func testDecodedSuccess() { let user: Decoded<User> = decode(JSONFromFile("user_with_email")!) switch user { case let .Success(x): XCTAssert(user.description == "Success(\(x))") default: XCTFail("Unexpected Case Occurred") } } func testDecodedWithError() { let user: Decoded<User> = decode(JSONFromFile("user_with_bad_type")!) switch user.error { case .Some: XCTAssert(true) case .None: XCTFail("Unexpected Success") } } func testDecodedWithNoError() { let user: Decoded<User> = decode(JSONFromFile("user_with_email")!) switch user.error { case .Some: XCTFail("Unexpected Error Occurred") case .None: XCTAssert(true) } } func testDecodedTypeMissmatch() { let user: Decoded<User> = decode(JSONFromFile("user_with_bad_type")!) switch user { case let .Failure(.TypeMismatch(expected, actual)): XCTAssert(user.description == "Failure(TypeMismatch(Expected \(expected), got \(actual)))") default: XCTFail("Unexpected Case Occurred") } } func testDecodedMissingKey() { let user: Decoded<User> = decode(JSONFromFile("user_without_key")!) switch user { case let .Failure(.MissingKey(s)): XCTAssert(user.description == "Failure(MissingKey(\(s)))") default: XCTFail("Unexpected Case Occurred") } } func testDecodedCustomError() { let customError: Decoded<Dummy> = decode([:]) switch customError { case let .Failure(e): XCTAssert(e.description == "Custom(My Custom Error)") default: XCTFail("Unexpected Case Occurred") } } func testDecodedMaterializeSuccess() { let user: Decoded<User> = decode(JSONFromFile("user_with_email")!) let materialized = materialize { user.value! } switch materialized { case let .Success(x): XCTAssert(user.description == "Success(\(x))") default: XCTFail("Unexpected Case Occurred") } } func testDecodedMaterializeFailure() { let error = NSError(domain: "com.thoughtbot.Argo", code: 0, userInfo: nil) let materialized = materialize { throw error } switch materialized { case let .Failure(e): XCTAssert(e.description == "Custom(\(error.description))") default: XCTFail("Unexpected Case Occurred") } } func testDecodedDematerializeSuccess() { let user: Decoded<User> = decode(JSONFromFile("user_with_email")!) do { try user.dematerialize() XCTAssert(true) } catch { XCTFail("Unexpected Error Occurred") } } func testDecodedDematerializeTypeMismatch() { let user: Decoded<User> = decode(JSONFromFile("user_with_bad_type")!) do { try user.dematerialize() XCTFail("Unexpected Success") } catch DecodeError.TypeMismatch { XCTAssert(true) } catch DecodeError.MissingKey { XCTFail("Unexpected Error Occurred") } catch { XCTFail("Unexpected Error Occurred") } } func testDecodedDematerializeMissingKey() { let user: Decoded<User> = decode(JSONFromFile("user_without_key")!) do { try user.dematerialize() XCTFail("Unexpected Success") } catch DecodeError.MissingKey { XCTAssert(true) } catch DecodeError.TypeMismatch { XCTFail("Unexpected Error Occurred") } catch { XCTFail("Unexpected Error Occurred") } } } private struct Dummy: Decodable { static func decode(json: JSON) -> Decoded<Dummy> { return .Failure(.Custom("My Custom Error")) } }
712382612626a5765537f0c738060240
27.288
147
0.658654
false
true
false
false
jsslai/Action
refs/heads/master
Carthage/Checkouts/RxSwift/Tests/RxCocoaTests/ControlEventTests.swift
mit
3
// // ControlEventTests.swift // RxTests // // Created by Krunoslav Zaher on 12/6/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import Foundation import RxCocoa import RxSwift import XCTest class ControlEventTests : RxTest { func testObservingIsAlwaysHappeningOnMainThread() { let hotObservable = MainThreadPrimitiveHotObservable<Int>() var observedOnMainThread = false let expectSubscribeOffMainThread = expectation(description: "Did subscribe off main thread") let controlProperty = ControlEvent(events: Observable.deferred { () -> Observable<Int> in XCTAssertTrue(isMainThread()) observedOnMainThread = true return hotObservable.asObservable() }) doOnBackgroundThread { let d = controlProperty.asObservable().subscribe { n in } let d2 = controlProperty.subscribe { n in } doOnMainThread { d.dispose() d2.dispose() expectSubscribeOffMainThread.fulfill() } } waitForExpectations(timeout: 1.0) { error in XCTAssertNil(error) } XCTAssertTrue(observedOnMainThread) } }
3f2273c046dd4c2d134b221bb773cc19
25.333333
100
0.619462
false
true
false
false
ricardorauber/iOS-Swift
refs/heads/master
iOS-Swift.playground/Pages/Key Value Observing.xcplaygroundpage/Contents.swift
mit
1
//: ## Key Value Observing //: ---- //: [Previous](@previous) import Foundation //: Contexts private var PersonNameObserverContext = 0 private var PersonAgeObserverContext = 0 //: Observable Properties class Person: NSObject { dynamic var name: String dynamic var age: Int init(withName name: String, age: Int) { self.name = name self.age = age } } //: Handle observing class People: NSObject { let manager: Person init(withManager manager: Person) { self.manager = manager super.init() self.manager.addObserver(self, forKeyPath: "name", options: [.New, .Old], context: &PersonNameObserverContext) self.manager.addObserver(self, forKeyPath: "age", options: [.New, .Old], context: &PersonAgeObserverContext) } override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) { switch(context) { case &PersonNameObserverContext: let oldName = change!["old"]! let newName = change!["new"]! print("Manager name was \(oldName) and now is \(newName)") case &PersonAgeObserverContext: let oldAge = change!["old"]! let newAge = change!["new"]! print("Manager age was \(oldAge) and now is \(newAge)") default: print("Unhandled KVO: \(keyPath)") } } deinit { self.manager.removeObserver(self, forKeyPath: "name") self.manager.removeObserver(self, forKeyPath: "age") } } let manager = Person(withName: "John", age: 40) let team = People(withManager: manager) manager.name = "Jack" manager.age = 45 //: [Next](@next)
3db6b30c73b24438dd3edce12765675e
25.984848
157
0.613139
false
false
false
false
kasei/kineo
refs/heads/master
Sources/Kineo/SPARQL/SPARQLTSV.swift
mit
1
// // SPARQLTSV.swift // Kineo // // Created by Gregory Todd Williams on 4/24/18. // import Foundation import SPARQLSyntax public struct SPARQLTSVSerializer<T: ResultProtocol> : SPARQLSerializable where T.TermType == Term { typealias ResultType = T public let canonicalMediaType = "text/tab-separated-values" public var serializesTriples = false public var serializesBindings = true public var serializesBoolean = false public var acceptableMediaTypes: [String] { return [canonicalMediaType] } public init() { } public func serialize<R: Sequence, T: Sequence>(_ results: QueryResult<R, T>) throws -> Data where R.Element == SPARQLResultSolution<Term>, T.Element == Triple { var d = Data() switch results { case .boolean(_): throw SerializationError.encodingError("Boolean results cannot be serialized in SPARQL-TSV") case let .bindings(vars, seq): let head = vars.map { "?\($0)" }.joined(separator: "\t") guard let headData = head.data(using: .utf8) else { throw SerializationError.encodingError("Failed to encode TSV header as utf-8") } d.append(headData) d.append(0x0a) for result in seq { let terms = vars.map { result[$0] } let strings = try terms.map { (t) -> String in if let t = t { guard let termString = t.tsvString else { throw SerializationError.encodingError("Failed to encode term as utf-8: \(t)") } return termString } else { return "" } } let line = strings.joined(separator: "\t") guard let lineData = line.data(using: .utf8) else { throw SerializationError.encodingError("Failed to encode TSV line as utf-8") } d.append(lineData) d.append(0x0a) } return d case .triples(_): throw SerializationError.encodingError("RDF triples cannot be serialized in SPARQL-TSV") } } } private extension String { var tsvStringEscaped: String { var escaped = "" for c in self { switch c { case Character(UnicodeScalar(0x22)): escaped += "\\\"" case Character(UnicodeScalar(0x5c)): escaped += "\\\\" case Character(UnicodeScalar(0x09)): escaped += "\\t" case Character(UnicodeScalar(0x0a)): escaped += "\\n" default: escaped.append(c) } } return escaped } } private extension Term { var tsvString: String? { switch self.type { case .iri: return "<\(value.turtleIRIEscaped)>" case .blank: return "_:\(self.value)" case .language(let l): return "\"\(value.tsvStringEscaped)\"@\(l)" case .datatype(.integer): return "\(Int(self.numericValue))" case .datatype(.string): return "\"\(value.tsvStringEscaped)\"" case .datatype(let dt): return "\"\(value.tsvStringEscaped)\"^^<\(dt.value)>" } } } public struct SPARQLTSVParser : SPARQLParsable { public let mediaTypes = Set(["text/tab-separated-values"]) var encoding: String.Encoding var parser: RDFParserCombined public init(encoding: String.Encoding = .utf8, produceUniqueBlankIdentifiers: Bool = true) { self.encoding = encoding self.parser = RDFParserCombined(base: "http://example.org/", produceUniqueBlankIdentifiers: produceUniqueBlankIdentifiers) } public func parse(_ data: Data) throws -> QueryResult<[SPARQLResultSolution<Term>], [Triple]> { guard let s = String(data: data, encoding: encoding) else { throw SerializationError.encodingError("Failed to decode SPARQL/TSV data as utf-8") } let lines = s.split(separator: "\n") guard let header = lines.first else { throw SerializationError.parsingError("SPARQL/TSV data missing header line") } let names = header.split(separator: "\t").map { String($0.dropFirst()) } var results = [SPARQLResultSolution<Term>]() for line in lines.dropFirst() { let values = line.split(separator: "\t", omittingEmptySubsequences: false) let terms = try values.map { try parseTerm(String($0)) } let pairs = zip(names, terms).compactMap { (name, term) -> (String, Term)? in guard let term = term else { return nil } return (name, term) } let d = Dictionary(uniqueKeysWithValues: pairs) let r = SPARQLResultSolution<Term>(bindings: d) results.append(r) } return QueryResult.bindings(names, results) } private func parseTerm(_ string: String) throws -> Term? { guard !string.isEmpty else { return nil } var term : Term! = nil let ttl = "<> <> \(string) .\n" try parser.parse(string: ttl, syntax: .turtle) { (s,p,o) in term = o } return term } }
8623172c8bfa86212932d7e8794c139a
34.934641
165
0.548017
false
false
false
false
iosdevelopershq/code-challenges
refs/heads/master
CodeChallenge/Challenges/TwoSum/Entries/Aranasaurus.swift
mit
1
// // Aranasaurus.swift // CodeChallenge // // Created by Ryan Arana on 10/31/15. // Copyright © 2015 iosdevelopers. All rights reserved. // import Foundation let aranasaurusTwoSumEntry = CodeChallengeEntry<TwoSumChallenge>(name: "Aranasaurus") { input in var max = Datum(0, 0) let mid = input.target / 2 for (i, number) in input.numbers.enumerated() { guard number >= 0 && number <= input.target && number >= mid else { continue } if number > max.number { if let diffIndex = input.numbers.index(of: input.target - number) { return (diffIndex + 1, i + 1) } max = Datum(i, number) } } return .none } private struct Datum { let index: Int let number: Int init(_ index: Int, _ number: Int) { self.index = index self.number = number } }
a6ab132a66692da50cd7f59e7ffeec49
22.605263
96
0.569677
false
false
false
false
deltaDNA/ios-sdk
refs/heads/master
Example/tvOS Example/ViewController.swift
apache-2.0
1
// // Copyright (c) 2016 deltaDNA Ltd. 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 UIKit import DeltaDNA class ViewController: UIViewController, DDNAImageMessageDelegate { @IBOutlet weak var sdkVersion: UILabel! override func viewDidLoad() { super.viewDidLoad() self.sdkVersion.text = DDNA_SDK_VERSION; DDNASDK.setLogLevel(.debug) DDNASDK.sharedInstance().clientVersion = "tvOS Example v1.0" DDNASDK.sharedInstance().hashSecret = "KmMBBcNwStLJaq6KsEBxXc6HY3A4bhGw" DDNASDK.sharedInstance().start( withEnvironmentKey: "55822530117170763508653519413932", collectURL: "https://collect2010stst.deltadna.net/collect/api", engageURL: "https://engage2010stst.deltadna.net" ) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func onSimpleEvent(_ sender: AnyObject) { DDNASDK.sharedInstance().recordEvent(withName: "achievement", eventParams: [ "achievementName" : "Sunday Showdown Tournament Win", "achievementID" : "SS-2014-03-02-01", "reward" : [ "rewardName" : "Medal", "rewardProducts" : [ "items" : [ [ "item" : [ "itemAmount" : 1, "itemName" : "Sunday Showdown Medal", "itemType" : "Victory Badge" ] ] ], "virtualCurrencies" : [ [ "virtualCurrency" : [ "virtualCurrencyAmount" : 20, "virtualCurrencyName" : "VIP Points", "virtualCurrencyType" : "GRIND" ] ] ], "realCurrency" : [ "realCurrencyAmount" : 5000, "realCurrencyType" : "USD" ] ] ] ]) } @IBAction func onEngage(_ sender: AnyObject) { let engagement = DDNAEngagement(decisionPoint: "gameLoaded")! engagement.setParam(4 as NSNumber, forKey: "userLevel") engagement.setParam(1000 as NSNumber, forKey: "experience") engagement.setParam("Disco Volante" as NSString, forKey: "missionName") DDNASDK.sharedInstance().request(engagement, engagementHandler:{ (response)->() in if response?.json != nil { print("Engagement returned: \(String(describing: response?.json["parameters"]))") } else { print("Engagement failed: \(String(describing: response?.error))") } }) } @IBAction func onImageMessage(_ sender: AnyObject) { let engagement = DDNAEngagement(decisionPoint: "imageMessage"); DDNASDK.sharedInstance().request(engagement, engagementHandler:{ (response)->() in if let imageMessage = DDNAImageMessage(engagement: response, delegate: self) { imageMessage.fetchResources() } }) } @IBAction func onUploadEvents(_ sender: AnyObject) { DDNASDK.sharedInstance().upload(); } func onDismiss(_ imageMessage: DDNAImageMessage!, name: String!) { print("Image message dismissed by \(name)") } func onActionImageMessage(_ imageMessage: DDNAImageMessage!, name: String!, type: String!, value: String!) { print("Image message actioned by \(name) with \(type) and \(value)") } func didReceiveResources(for imageMessage: DDNAImageMessage!) { print("Image message received resources") imageMessage.show(fromRootViewController: self) } func didFailToReceiveResources(for imageMessage: DDNAImageMessage!, withReason reason: String!) { print("Image message failed to receive resources: \(reason)") } }
f4e34523780fcff6a93fd44c5bff368b
36.896825
112
0.564607
false
false
false
false
brentsimmons/Evergreen
refs/heads/ios-candidate
iOS/MasterFeed/Cell/MasterFeedTableViewIdentifier.swift
mit
1
// // MasterFeedTableViewIdentifier.swift // NetNewsWire-iOS // // Created by Maurice Parker on 6/3/20. // Copyright © 2020 Ranchero Software. All rights reserved. // import Foundation import Account import RSTree final class MasterFeedTableViewIdentifier: NSObject, NSCopying { let feedID: FeedIdentifier? let containerID: ContainerIdentifier? let parentContainerID: ContainerIdentifier? let isEditable: Bool let isPsuedoFeed: Bool let isFolder: Bool let isWebFeed: Bool let nameForDisplay: String let url: String? let unreadCount: Int let childCount: Int var account: Account? { if isFolder, let parentContainerID = parentContainerID { return AccountManager.shared.existingContainer(with: parentContainerID) as? Account } if isWebFeed, let feedID = feedID { return (AccountManager.shared.existingFeed(with: feedID) as? WebFeed)?.account } return nil } init(node: Node, unreadCount: Int) { let feed = node.representedObject as! Feed self.feedID = feed.feedID self.containerID = (node.representedObject as? Container)?.containerID self.parentContainerID = (node.parent?.representedObject as? Container)?.containerID self.isEditable = !(node.representedObject is PseudoFeed) self.isPsuedoFeed = node.representedObject is PseudoFeed self.isFolder = node.representedObject is Folder self.isWebFeed = node.representedObject is WebFeed self.nameForDisplay = feed.nameForDisplay if let webFeed = node.representedObject as? WebFeed { self.url = webFeed.url } else { self.url = nil } self.unreadCount = unreadCount self.childCount = node.numberOfChildNodes } override func isEqual(_ object: Any?) -> Bool { guard let otherIdentifier = object as? MasterFeedTableViewIdentifier else { return false } if self === otherIdentifier { return true } return feedID == otherIdentifier.feedID && parentContainerID == otherIdentifier.parentContainerID } override var hash: Int { var hasher = Hasher() hasher.combine(feedID) hasher.combine(parentContainerID) return hasher.finalize() } func copy(with zone: NSZone? = nil) -> Any { return self } }
864ca78a8dc0975923f00fb9a7944813
26.461538
99
0.748833
false
false
false
false
andreipitis/ASPVideoPlayer
refs/heads/master
Example/ASPVideoPlayer/PlayerViewController.swift
mit
1
// // PlayerViewController.swift // ASPVideoPlayer // // Created by Andrei-Sergiu Pițiș on 09/12/2016. // Copyright © 2016 CocoaPods. All rights reserved. // import UIKit import ASPVideoPlayer import AVFoundation class PlayerViewController: UIViewController { @IBOutlet weak var containerView: UIView! @IBOutlet weak var videoPlayerBackgroundView: UIView! @IBOutlet weak var videoPlayer: ASPVideoPlayer! let firstLocalVideoURL = Bundle.main.url(forResource: "video", withExtension: "mp4") let secondLocalVideoURL = Bundle.main.url(forResource: "video2", withExtension: "mp4") let firstNetworkURL = URL(string: "http://devimages.apple.com/iphone/samples/bipbop/bipbopall.m3u8") let secondNetworkURL = URL(string: "http://www.easy-fit.ae/wp-content/uploads/2014/09/WebsiteLoop.mp4") override func viewDidLoad() { super.viewDidLoad() let firstAsset = AVURLAsset(url: firstLocalVideoURL!) let secondAsset = AVURLAsset(url: secondLocalVideoURL!) let thirdAsset = AVURLAsset(url: firstNetworkURL!) let fourthAsset = AVURLAsset(url: secondNetworkURL!) // videoPlayer.videoURLs = [firstLocalVideoURL!, secondLocalVideoURL!, firstNetworkURL!, secondNetworkURL!] videoPlayer.videoAssets = [firstAsset, secondAsset, thirdAsset, fourthAsset] // videoPlayer.configuration = ASPVideoPlayer.Configuration(videoGravity: .aspectFit, shouldLoop: true, startPlayingWhenReady: true, controlsInitiallyHidden: true, allowBackgroundPlay: true) videoPlayer.resizeClosure = { [unowned self] isExpanded in self.rotate(isExpanded: isExpanded) } videoPlayer.delegate = self } override var prefersStatusBarHidden: Bool { return true } var previousConstraints: [NSLayoutConstraint] = [] func rotate(isExpanded: Bool) { let views: [String:Any] = ["videoPlayer": videoPlayer as Any, "backgroundView": videoPlayerBackgroundView as Any] var constraints: [NSLayoutConstraint] = [] if isExpanded == false { self.containerView.removeConstraints(self.videoPlayer.constraints) self.view.addSubview(self.videoPlayerBackgroundView) self.view.addSubview(self.videoPlayer) self.videoPlayer.frame = self.containerView.frame self.videoPlayerBackgroundView.frame = self.containerView.frame let padding = (self.view.bounds.height - self.view.bounds.width) / 2.0 var bottomPadding: CGFloat = 0 if #available(iOS 11.0, *) { if self.view.safeAreaInsets != .zero { bottomPadding = self.view.safeAreaInsets.bottom } } let metrics: [String:Any] = ["padding":padding, "negativePaddingAdjusted":-(padding - bottomPadding), "negativePadding":-padding] constraints.append(contentsOf: NSLayoutConstraint.constraints(withVisualFormat: "H:|-(negativePaddingAdjusted)-[videoPlayer]-(negativePaddingAdjusted)-|", options: [], metrics: metrics, views: views)) constraints.append(contentsOf: NSLayoutConstraint.constraints(withVisualFormat: "V:|-(padding)-[videoPlayer]-(padding)-|", options: [], metrics: metrics, views: views)) constraints.append(contentsOf: NSLayoutConstraint.constraints(withVisualFormat: "H:|-(negativePadding)-[backgroundView]-(negativePadding)-|", options: [], metrics: metrics, views: views)) constraints.append(contentsOf: NSLayoutConstraint.constraints(withVisualFormat: "V:|-(padding)-[backgroundView]-(padding)-|", options: [], metrics: metrics, views: views)) self.view.addConstraints(constraints) } else { self.view.removeConstraints(self.previousConstraints) let targetVideoPlayerFrame = self.view.convert(self.videoPlayer.frame, to: self.containerView) let targetVideoPlayerBackgroundViewFrame = self.view.convert(self.videoPlayerBackgroundView.frame, to: self.containerView) self.containerView.addSubview(self.videoPlayerBackgroundView) self.containerView.addSubview(self.videoPlayer) self.videoPlayer.frame = targetVideoPlayerFrame self.videoPlayerBackgroundView.frame = targetVideoPlayerBackgroundViewFrame constraints.append(contentsOf: NSLayoutConstraint.constraints(withVisualFormat: "H:|[videoPlayer]|", options: [], metrics: nil, views: views)) constraints.append(contentsOf: NSLayoutConstraint.constraints(withVisualFormat: "V:|[videoPlayer]|", options: [], metrics: nil, views: views)) constraints.append(contentsOf: NSLayoutConstraint.constraints(withVisualFormat: "H:|[backgroundView]|", options: [], metrics: nil, views: views)) constraints.append(contentsOf: NSLayoutConstraint.constraints(withVisualFormat: "V:|[backgroundView]|", options: [], metrics: nil, views: views)) self.containerView.addConstraints(constraints) } self.previousConstraints = constraints UIView.animate(withDuration: 0.25, delay: 0.0, options: [], animations: { self.videoPlayer.transform = isExpanded == true ? .identity : CGAffineTransform(rotationAngle: .pi / 2.0) self.videoPlayerBackgroundView.transform = isExpanded == true ? .identity : CGAffineTransform(rotationAngle: .pi / 2.0) self.view.layoutIfNeeded() }) } } extension PlayerViewController: ASPVideoPlayerViewDelegate { func startedVideo() { print("Started video") } func stoppedVideo() { print("Stopped video") } func newVideo() { print("New Video") } func readyToPlayVideo() { print("Ready to play video") } func playingVideo(progress: Double) { // print("Playing: \(progress)") } func pausedVideo() { print("Paused Video") } func finishedVideo() { print("Finished Video") } func seekStarted() { print("Seek started") } func seekEnded() { print("Seek ended") } func error(error: Error) { print("Error: \(error)") } func willShowControls() { print("will show controls") } func didShowControls() { print("did show controls") } func willHideControls() { print("will hide controls") } func didHideControls() { print("did hide controls") } }
175a6f3429621386feb6fe841c084e21
37.743842
205
0.555499
false
false
false
false
Nyx0uf/MPDRemote
refs/heads/master
src/iOS/controllers/NYXNavigationController.swift
mit
1
// NYXNavigationController.swift // Copyright (c) 2017 Nyx0uf // // 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 final class NYXNavigationController : UINavigationController { override var shouldAutorotate: Bool { if let topViewController = self.topViewController { return topViewController.shouldAutorotate } return false } override var supportedInterfaceOrientations: UIInterfaceOrientationMask { if let topViewController = self.topViewController { return topViewController.supportedInterfaceOrientations } return .all } override var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation { if let topViewController = self.topViewController { return topViewController.preferredInterfaceOrientationForPresentation } return .portrait } override var preferredStatusBarStyle: UIStatusBarStyle { if let presentedViewController = self.presentedViewController { return presentedViewController.preferredStatusBarStyle } if let topViewController = self.topViewController { return topViewController.preferredStatusBarStyle } return .default } }
1edbc4a096d483c438255659fc9fa5dd
31.238806
82
0.785185
false
false
false
false
sffernando/CopyItems
refs/heads/master
CPKingFirsher/CPKingFirsher/Resource/Core/Image.swift
mit
1
// // Image.swift // CPKingFirsher // // Created by koudai on 2016/12/8. // Copyright © 2016年 fernando. All rights reserved. // import Foundation #if os(macOS) import AppKit private var imagesKey: Void? private var durationKey: Void? #else import UIKit import MobileCoreServices private var imageSourceKey: Void? private var animatedImageDataKey: Void? #endif import ImageIO import CoreGraphics #if !os(watchOS) import Accelerate import CoreImage #endif // MARK: image properties extension KingFisher where Base: Image { #if os(macOS) var cgImage: CGImage? { return base.cgImage(forProposedRect: nil, context: nil, hints: nil) } var scale: CFloat { return 1.0 } fileprivate(set) var images: [Image]? { get { return objc_getAssociatedObject(base, &imagesKey) as? [Image] } set { objc_setAssociatedObject(base, &imagesKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } fileprivate(set) var duration: TimeInterval { get { objc_getAssociatedObject(base, &durationKey) as? TimeInterval ?? 0.0 } set { objc_setAssociatedObject(base, &durationKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } var size: CGSize { return base.representations.reduce(CGSize.zero, { size, rep in return CGSize(width: max(size.width, CGFloat(rep.pixelsWide)), height: max(size.height, CGFloat(rep.pixelsHigh))) }) } #else var cgImage: CGImage? { return base.cgImage } var scale: CGFloat { return base.scale } var images: [Image]? { return base.images; } var duration: TimeInterval { return base.duration } fileprivate(set) var imageSource: ImageSource? { get { return objc_getAssociatedObject(base, &imageSourceKey) as? ImageSource } set { objc_setAssociatedObject(base, &imageSourceKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } fileprivate(set) var animatedImageData: Data? { get { return objc_getAssociatedObject(base, &animatedImageDataKey) as? Data } set { objc_setAssociatedObject(base, &animatedImageDataKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } var size: CGSize { return base.size } #endif } // MARK: Image Conversion extension KingFisher where Base: Image { #if os(macOS) static func image(cgImage: CGImage, scale: CGFloat, refImage: Image?) -> Image { return Image(cgImage: cgImage, size: CGSize.zero) } /** Normalize the image. This method does nothing in OS X. - returns: The image itself. */ public var normalized: Image { return base } static func animated(with images: [Image], forDuration forDurationduration: TimeInterval) -> Image? { return nil } #else static func image(cgImage: CGImage, scale: CGFloat, refImage: Image?) -> Image { if let refImage = refImage { return Image(cgImage: cgImage, scale: scale, orientation: refImage.imageOrientation) } else { return Image(cgImage: cgImage, scale: scale, orientation: .up) } } /** Normalize the image. This method will try to redraw an image with orientation and scale considered. - returns: The normalized image with orientation set to up and correct scale */ public var normalized: Image { // prevent animated image (GIF) lose it's images guard images == nil else { return base } // no need to do anything if already up guard base.imageOrientation != .up else { return base } return draw(cgImage: nil, to: size) { base.draw(in: CGRect(origin: CGPoint.zero, size: size)) } } static func animated(with images: [Image], forDuration duration: TimeInterval) -> Image? { return .animatedImage(with: images, duration: duration) } #endif } // MARK: Image Representation extension KingFisher where Base: Image { // MARK: - PNG func pngRepresentation() -> Data? { #if os(macOS) guard let cgimage = cgImage else { return nil } let rep = NSBitmapImageRep(cgImage: cgimage) return rep.representation(using: .PNG, properties: [:]) #else return UIImagePNGRepresentation(base) #endif } // MARK: JPEG func jpegRepresentation(compressionQuality: CGFloat) -> Data? { #if os(macOS) guard let cgImage = cgImage else { return nil } let rep = NSBitmapImageRep(cgImage: cgImage) return rep.representation(using:.JPEG, properties: [NSImageCompressionFactor: compressionQuality]) #else return UIImageJPEGRepresentation(base, compressionQuality) #endif } // MARK: - GIF func gifRepresentation() -> Data? { #if os(macOS) return gifRepresentation(duration: 0.0, repeatCount: 0) #else return animatedImageData #endif } #if os(macOS) func gifRepresentation(duration: TimeInterval, repeatCount: Int) -> Data? { guard let images = images else { return nil } let frameCount = images.count let gifDuration = duration <= 0.0 ? duration / Double(frameCount) : duration / Double(frameCount) let frameProperties = [kCGImagePropertyGIFDictionary as String: [kCGImagePropertyGIFDelayTime as String: gifDuration]] let imageProperties = [kCGImagePropertyGIFDictionary as String: [kCGImagePropertyGIFLoopCount as String: repeatCount]] let data = NSMutableData() guard let destination = CGImageDestinationCreateWithData(data, kUTTypeGIF, frameCount, nil) else { return nil } CGImageDestinationSetProperties(destination, imageProperties as CFDictionary) for image in images { CGImageDestinationAddImage(destination, image.kf.cgImage!, frameProperties as CFDictionary) } return CGImageDestinationFinalize(destination) ? data.copy() as? Data : nil } #endif } // MARK: create iamges form data extension KingFisher where Base: Image { static func animated(with data: Data, scale: CGFloat = 1.0, duration: TimeInterval = 0.0, preloadAll: Bool) -> Image?{ func decode(from imageSource: CGImageSource, for options: NSDictionary) -> ([Image], TimeInterval)? { // Calculates frame duration for a gif frame out of the kCGImagePropertyGIFDictionary dictionary func frameDuration(from gifInfo: NSDictionary) -> Double { let gifDefaultFrameDuration = 0.100 let unclampedDelayTime = gifInfo[kCGImagePropertyGIFUnclampedDelayTime as String] as? NSNumber let delayTime = gifInfo[kCGImagePropertyGIFDelayTime as String] as? NSNumber let duration = unclampedDelayTime ?? delayTime guard let frameDuration = duration else { return gifDefaultFrameDuration } return frameDuration.doubleValue > 0.011 ? frameDuration.doubleValue : gifDefaultFrameDuration } let frameCount = CGImageSourceGetCount(imageSource) var images = [Image]() var gifDuration = 0.0 for i in 0 ..< frameCount { guard let imageRef = CGImageSourceCreateImageAtIndex(imageSource, i, options) else { return nil } if frameCount == 1 { // Single frame gifDuration = Double.infinity } else { // Animated GIF guard let properties = CGImageSourceCopyPropertiesAtIndex(imageSource, i, nil),let gifInfo = (properties as NSDictionary)[kCGImagePropertyGIFDictionary as String] as? NSDictionary else { return nil } gifDuration += frameDuration(from: gifInfo) } images.append(KingFisher<Image>.image(cgImage: imageRef, scale: scale, refImage: nil)) } return (images, gifDuration) } // Start of kf.animatedImageWithGIFData let options: NSDictionary = [kCGImageSourceShouldCache as String: true, kCGImageSourceTypeIdentifierHint as String: kUTTypeGIF] guard let imageSource = CGImageSourceCreateWithData(data as CFData, options) else { return nil } #if os(macOS) guard let (images, gifDuration) = decode(from: imageSource, for: options) else { return nil } let image = Image(data: data) image?.kf.images = images image?.kf.duration = gifDuration return image #else if preloadAll { guard let (images, gifDuration) = decode(from: imageSource, for: options) else { return nil } let image = KingFisher<Image>.animated(with: images, forDuration: duration <= 0.0 ? gifDuration : duration) image?.kf.animatedImageData = data return image } else { let image = Image(data: data) image?.kf.animatedImageData = data image?.kf.imageSource = ImageSource(ref: imageSource) return image } #endif } static func image(data: Data, scale: CGFloat, preloadAllGIFData: Bool) -> Image? { var image: Image? #if os(macOS) switch data.kf.imageFormat { case .JPEG: image = Image(data: data) case .PNG: image = Image(data: data) case .GIF: image = KingFisher<Image>.animated(with: data, scale: scale, duration: 0.0, preloadAll: preloadAllGIFData) case .unknown: image = Image(data: data) } #else switch data.kf.imageFormat { case .JPEG: image = Image(data: data, scale: scale) case .PNG: image = Image(data: data, scale: scale) case .GIF: image = KingFisher<Image>.animated(with: data, scale: scale, duration: 0.0, preloadAll: preloadAllGIFData) case .unknown: image = Image(data: data, scale: scale) } #endif return image } } // Reference the source image reference class ImageSource { var imageRef: CGImageSource? init(ref: CGImageSource) { self.imageRef = ref } } extension CGBitmapInfo { var fixed: CGBitmapInfo { var fixed = self let alpha = (rawValue & CGBitmapInfo.alphaInfoMask.rawValue) if alpha == CGImageAlphaInfo.none.rawValue { fixed.remove(.alphaInfoMask) fixed = CGBitmapInfo(rawValue: fixed.rawValue | CGImageAlphaInfo.noneSkipFirst.rawValue) } else if !(alpha == CGImageAlphaInfo.noneSkipFirst.rawValue) || !(alpha == CGImageAlphaInfo.noneSkipLast.rawValue) { fixed.remove(.alphaInfoMask) fixed = CGBitmapInfo(rawValue: fixed.rawValue | CGImageAlphaInfo.premultipliedFirst.rawValue) } return fixed } } extension KingFisher where Base: Image { func draw(cgImage: CGImage?, to size: CGSize, draw: ()->()) -> Image { #if os(macOS) guard let rep = NSBitmapImageRep( bitmapDataPlanes: nil, pixelsWide: Int(size.width), pixelsHigh: Int(size.height), bitsPerSample: cgImage?.bitsPerComponent ?? 8, samplesPerPixel: 4, hasAlpha: true, isPlanar: false, colorSpaceName: NSCalibratedRGBColorSpace, bytesPerRow: 0, bitsPerPixel: 0) else { assertionFailure("[KingFisher] Image representation cannot be created.") } rep.size = size NSGraphicsContext.saveGraphicsState() let context = NSGraphicsContext(bitmapImageRep: rep) NSGraphicsContext.setCurrent(context) draw() NSGraphicsContext.restoreGraphicsState() let outputImage = Image(size: size) outputImage.addRepresentation(rep) return outputImage #else UIGraphicsBeginImageContextWithOptions(size, false, scale) defer { UIGraphicsEndImageContext() } draw() return UIGraphicsGetImageFromCurrentImageContext() ?? base #endif } #if os(macOS) func fixedForRetinaPixel(cgImage: CGImage, to size: CGSize) -> Image { let image = Image(cgImage: cgImage, size: base.size) let rect = CGRect(origin: CGPoint(x: 0, y: 0), size: size) return draw(cgImage: cgImage, to: self.size) { image.draw(in: rect, from: NSRect.zero, operation: .copy, fraction: 1.0) } } #endif } extension CGContext { static func createARGBContext(from imageRef: CGImage) -> CGContext? { let w = imageRef.width let h = imageRef.height let bytesPerRow = w * 4 let colorSpace = CGColorSpaceCreateDeviceRGB() let data = malloc(bytesPerRow * h) defer { free(data) } let bitmapInfo = imageRef.bitmapInfo.fixed // Create the bitmap context. We want pre-multiplied ARGB, 8-bits // per component. Regardless of what the source image format is // (CMYK, Grayscale, and so on) it will be converted over to the format // specified here. return CGContext(data: data, width: w, height: h, bitsPerComponent: imageRef.bitsPerComponent, bytesPerRow: bytesPerRow, space: colorSpace, bitmapInfo: bitmapInfo.rawValue) } } extension Double { var isEven: Bool { return truncatingRemainder(dividingBy: 2.0) == 0 } } // MARK: - Image format private struct ImageHeaderData { static var PNG: [UInt8] = [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A] static var JPEG_SOI: [UInt8] = [0xFF, 0xD8] static var JPEG_IF: [UInt8] = [0xFF] static var GIF: [UInt8] = [0x47, 0x49, 0x46] } enum ImageFormat { case unknown, PNG, JPEG, GIF } // MARK: - Misc Helpers public struct DataProxy { fileprivate let base: Data init(proxy: Data) { base = proxy } } extension Data: KingFisherCompatible { public typealias CompatibleType = DataProxy public var kf: DataProxy { return DataProxy(proxy: self) } } extension DataProxy { var imageFormat: ImageFormat { var buffer = [UInt8](repeating: 0, count: 8) (base as NSData).getBytes(&buffer, length: 8) if buffer == ImageHeaderData.PNG { return .PNG } else if buffer[0] == ImageHeaderData.JPEG_SOI[0] && buffer[1] == ImageHeaderData.JPEG_SOI[1] && buffer[2] == ImageHeaderData.JPEG_IF[0] { return .JPEG } else if buffer[0] == ImageHeaderData.GIF[0] && buffer[1] == ImageHeaderData.GIF[1] && buffer[2] == ImageHeaderData.GIF[2] { return .GIF } return .unknown } }
206c6221c4c183cc25a1824103e84a7b
31.848548
206
0.589023
false
false
false
false
anpavlov/swiftperl
refs/heads/master
Sources/Perl/SvConvertible.swift
mit
1
public protocol PerlSvConvertible { static func fromUnsafeSvPointer(_: UnsafeSvPointer, perl: UnsafeInterpreterPointer/* = UnsafeInterpreter.current */) throws -> Self func toUnsafeSvPointer(perl: UnsafeInterpreterPointer/* = UnsafeInterpreter.current */) -> UnsafeSvPointer } extension Bool : PerlSvConvertible { public static func fromUnsafeSvPointer(_ sv: UnsafeSvPointer, perl: UnsafeInterpreterPointer = UnsafeInterpreter.current) -> Bool { return Bool(sv, perl: perl) } public func toUnsafeSvPointer(perl: UnsafeInterpreterPointer = UnsafeInterpreter.current) -> UnsafeSvPointer { return perl.pointee.newSV(self) } } extension Int : PerlSvConvertible { public static func fromUnsafeSvPointer(_ sv: UnsafeSvPointer, perl: UnsafeInterpreterPointer = UnsafeInterpreter.current) throws -> Int { return try Int(sv, perl: perl) } public func toUnsafeSvPointer(perl: UnsafeInterpreterPointer = UnsafeInterpreter.current) -> UnsafeSvPointer { return perl.pointee.newSV(self) } } extension Double : PerlSvConvertible { public static func fromUnsafeSvPointer(_ sv: UnsafeSvPointer, perl: UnsafeInterpreterPointer = UnsafeInterpreter.current) throws -> Double { return try Double(sv, perl: perl) } public func toUnsafeSvPointer(perl: UnsafeInterpreterPointer = UnsafeInterpreter.current) -> UnsafeSvPointer { return perl.pointee.newSV(self) } } extension String : PerlSvConvertible { public static func fromUnsafeSvPointer(_ sv: UnsafeSvPointer, perl: UnsafeInterpreterPointer = UnsafeInterpreter.current) throws -> String { return try String(sv, perl: perl) } public func toUnsafeSvPointer(perl: UnsafeInterpreterPointer = UnsafeInterpreter.current) -> UnsafeSvPointer { return perl.pointee.newSV(self) } } extension PerlScalar : PerlSvConvertible { public static func fromUnsafeSvPointer(_ sv: UnsafeSvPointer, perl: UnsafeInterpreterPointer = UnsafeInterpreter.current) throws -> PerlScalar { return try PerlScalar(inc: sv, perl: perl) } public func toUnsafeSvPointer(perl: UnsafeInterpreterPointer = UnsafeInterpreter.current) -> UnsafeSvPointer { return withUnsafeSvPointer { sv, _ in sv.pointee.refcntInc() } } } extension PerlDerived where Self : PerlValue, UnsafeValue : UnsafeSvCastable { public static func fromUnsafeSvPointer(_ sv: UnsafeSvPointer, perl: UnsafeInterpreterPointer = UnsafeInterpreter.current) throws -> Self { guard let unsafe = try UnsafeMutablePointer<UnsafeValue>(autoDeref: sv, perl: perl) else { throw PerlError.unexpectedUndef(Perl.fromUnsafeSvPointer(inc: sv, perl: perl)) } return self.init(inc: unsafe, perl: perl) } public func toUnsafeSvPointer(perl: UnsafeInterpreterPointer = UnsafeInterpreter.current) -> UnsafeSvPointer { return withUnsafeSvPointer { sv, perl in perl.pointee.newRV(inc: sv) } } } extension PerlBridgedObject { public static func fromUnsafeSvPointer(_ sv: UnsafeSvPointer, perl: UnsafeInterpreterPointer = UnsafeInterpreter.current) throws -> Self { return try _fromUnsafeSvPointerNonFinalClassWorkaround(sv, perl: perl) } public func toUnsafeSvPointer(perl: UnsafeInterpreterPointer = UnsafeInterpreter.current) -> UnsafeSvPointer { return perl.pointee.newSV(self) } public static func _fromUnsafeSvPointerNonFinalClassWorkaround<T>(_ sv: UnsafeSvPointer, perl: UnsafeInterpreterPointer = UnsafeInterpreter.current) throws -> T { guard let base = sv.pointee.swiftObject(perl: perl) else { throw PerlError.notSwiftObject(Perl.fromUnsafeSvPointer(inc: sv, perl: perl)) } guard let obj = base as? T else { throw PerlError.unexpectedObjectType(Perl.fromUnsafeSvPointer(inc: sv, perl: perl), want: self) } return obj } } extension PerlObject { public static func fromUnsafeSvPointer(_ sv: UnsafeSvPointer, perl: UnsafeInterpreterPointer = UnsafeInterpreter.current) throws -> Self { return try _fromUnsafeSvPointerNonFinalClassWorkaround(sv, perl: perl) } public func toUnsafeSvPointer(perl: UnsafeInterpreterPointer = UnsafeInterpreter.current) -> UnsafeSvPointer { return withUnsafeSvPointer { sv, _ in sv.pointee.refcntInc() } } public static func _fromUnsafeSvPointerNonFinalClassWorkaround<T : PerlObject>(_ sv: UnsafeSvPointer, perl: UnsafeInterpreterPointer = UnsafeInterpreter.current) throws -> T { guard let classname = sv.pointee.classname(perl: perl) else { throw PerlError.notObject(Perl.fromUnsafeSvPointer(inc: sv, perl: perl)) } if let nc = T.self as? PerlNamedClass.Type, nc.perlClassName == classname { return T(incUnchecked: sv, perl: perl) } let base = PerlObject.derivedClass(for: classname).init(incUnchecked: sv, perl: perl) guard let obj = base as? T else { throw PerlError.unexpectedObjectType(Perl.fromUnsafeSvPointer(inc: sv, perl: perl), want: self) } return obj } } extension Optional where Wrapped : PerlSvConvertible { public static func fromUnsafeSvPointer(_ sv: UnsafeSvPointer, perl: UnsafeInterpreterPointer = UnsafeInterpreter.current) throws -> Optional<Wrapped> { return sv.pointee.defined ? try Wrapped.fromUnsafeSvPointer(sv, perl: perl) : nil } public func toUnsafeSvPointer(perl: UnsafeInterpreterPointer = UnsafeInterpreter.current) -> UnsafeSvPointer { switch self { case .some(let value): return value.toUnsafeSvPointer(perl: perl) case .none: return perl.pointee.newSV() } } } extension Array where Element : PerlSvConvertible { public func toUnsafeSvPointer(perl: UnsafeInterpreterPointer = UnsafeInterpreter.current) -> UnsafeSvPointer { let av = perl.pointee.newAV()! var c = av.pointee.collection(perl: perl) c.reserveCapacity(numericCast(count)) for (i, v) in enumerated() { c[i] = v.toUnsafeSvPointer(perl: perl) } return perl.pointee.newRV(noinc: av) } } // where Key == String, but it is unsupported extension Dictionary where Value : PerlSvConvertible { public func toUnsafeSvPointer(perl: UnsafeInterpreterPointer = UnsafeInterpreter.current) -> UnsafeSvPointer { let hv = perl.pointee.newHV()! var c = hv.pointee.collection(perl: perl) for (k, v) in self { c[k as! String] = v.toUnsafeSvPointer(perl: perl) } return perl.pointee.newRV(noinc: hv) } }
c136ac5d17dc19fc4b0acc9019e91901
46.8125
177
0.773203
false
false
false
false
powerytg/Accented
refs/heads/master
Accented/Core/Storage/Models/UserModel.swift
mit
1
// // UserModel.swift // Accented // // User model // // Created by Tiangong You on 8/6/16. // Copyright © 2016 Tiangong You. All rights reserved. // import UIKit import SwiftyJSON // User avatar size definition enum UserAvatar : String { case Large = "large" case Default = "default" case Small = "small" case Tiny = "tiny" } enum UpgradeStatus : Int { case Basic = 0 case Plus = 1 case Awesome = 2 } class UserModel: ModelBase { var dateFormatter = DateFormatter() var userId : String! var followersCount : Int? var coverUrl : String? var lastName : String? var firstName : String? var userName : String! var fullName : String? var city : String? var country : String? var userPhotoUrl : String? var about : String? var registrationDate : Date? var contacts : [String : String]? var equipments : [String : [String]]? var photoCount : Int? var following : Bool? var friendCount : Int? var domain : String? var upgradeStatus : UpgradeStatus! var affection : Int? var galleryCount : Int? // Avatars var avatarUrls = [UserAvatar : String]() override init() { super.init() } init(json : JSON) { super.init() self.userId = String(json["id"].int!) self.modelId = self.userId if let followCount = json["followers_count"].int { followersCount = followCount } self.coverUrl = json["cover_url"].string self.lastName = json["lastname"].string self.firstName = json["firstname"].string self.fullName = json["fullname"].string self.userName = json["username"].string! self.city = json["city"].string self.country = json["country"].string self.userPhotoUrl = json["userpic_url"].string // Avatar urls if let largeAvatar = json["avatars"]["large"]["https"].string { avatarUrls[.Large] = largeAvatar } if let defaultAvatar = json["avatars"]["default"]["https"].string { avatarUrls[.Default] = defaultAvatar } if let smallAvatar = json["avatars"]["small"]["https"].string { avatarUrls[.Small] = smallAvatar } if let tinyAvatar = json["avatars"]["tiny"]["https"].string { avatarUrls[.Tiny] = tinyAvatar } dateFormatter.dateFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ssZZZZZ" self.about = json["about"].string if let regDate = json["registration_date"].string { self.registrationDate = dateFormatter.date(from: regDate) } if let _ = json["contacts"].dictionary { self.contacts = [String : String]() for (key, value) : (String, JSON) in json["contacts"] { self.contacts![key] = value.stringValue } } if let _ = json["equipments"].dictionary { self.equipments = [String : [String]]() for (type, _) : (String, JSON) in json["equipments"] { self.equipments![type] = [] for (_, gear) in json["equipments"][type] { self.equipments![type]!.append(gear.stringValue) } } } self.photoCount = json["photos_count"].int self.following = json["following"].bool self.friendCount = json["friends_count"].int self.domain = json["domain"].string self.upgradeStatus = UpgradeStatus(rawValue: json["upgrade_status"].intValue) self.affection = json["affection"].int self.galleryCount = json["galleries_count"].int } override func copy(with zone: NSZone? = nil) -> Any { let clone = UserModel() clone.userId = self.userId clone.modelId = self.modelId clone.followersCount = self.followersCount clone.coverUrl = self.coverUrl clone.lastName = self.lastName clone.firstName = self.firstName clone.fullName = self.fullName clone.userName = self.userName clone.city = self.city clone.country = self.country clone.userPhotoUrl = self.userPhotoUrl clone.avatarUrls = self.avatarUrls clone.about = self.about clone.registrationDate = self.registrationDate clone.contacts = self.contacts clone.equipments = self.equipments clone.photoCount = self.photoCount clone.following = self.following clone.friendCount = self.friendCount clone.domain = self.domain clone.upgradeStatus = self.upgradeStatus clone.affection = self.affection clone.galleryCount = self.galleryCount return clone } }
ccd0371365c6b8c8d9c44ac88003cce7
30.122581
85
0.582504
false
false
false
false
uber/RIBs
refs/heads/main
ios/RIBs/Classes/Workflow/Workflow.swift
apache-2.0
1
// // Copyright (c) 2017. Uber Technologies // // 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 RxSwift /// Defines the base class for a sequence of steps that execute a flow through the application RIB tree. /// /// At each step of a `Workflow` is a pair of value and actionable item. The value can be used to make logic decisions. /// The actionable item is invoked to perform logic for the step. Typically the actionable item is the `Interactor` of a /// RIB. /// /// A workflow should always start at the root of the tree. open class Workflow<ActionableItemType> { /// Called when the last step observable is completed. /// /// Subclasses should override this method if they want to execute logic at this point in the `Workflow` lifecycle. /// The default implementation does nothing. open func didComplete() { // No-op } /// Called when the `Workflow` is forked. /// /// Subclasses should override this method if they want to execute logic at this point in the `Workflow` lifecycle. /// The default implementation does nothing. open func didFork() { // No-op } /// Called when the last step observable is has error. /// /// Subclasses should override this method if they want to execute logic at this point in the `Workflow` lifecycle. /// The default implementation does nothing. open func didReceiveError(_ error: Error) { // No-op } /// Initializer. public init() {} /// Execute the given closure as the root step. /// /// - parameter onStep: The closure to execute for the root step. /// - returns: The next step. public final func onStep<NextActionableItemType, NextValueType>(_ onStep: @escaping (ActionableItemType) -> Observable<(NextActionableItemType, NextValueType)>) -> Step<ActionableItemType, NextActionableItemType, NextValueType> { return Step(workflow: self, observable: subject.asObservable().take(1)) .onStep { (actionableItem: ActionableItemType, _) in onStep(actionableItem) } } /// Subscribe and start the `Workflow` sequence. /// /// - parameter actionableItem: The initial actionable item for the first step. /// - returns: The disposable of this workflow. public final func subscribe(_ actionableItem: ActionableItemType) -> Disposable { guard compositeDisposable.count > 0 else { assertionFailure("Attempt to subscribe to \(self) before it is comitted.") return Disposables.create() } subject.onNext((actionableItem, ())) return compositeDisposable } // MARK: - Private private let subject = PublishSubject<(ActionableItemType, ())>() private var didInvokeComplete = false /// The composite disposable that contains all subscriptions including the original workflow /// as well as all the forked ones. fileprivate let compositeDisposable = CompositeDisposable() fileprivate func didCompleteIfNotYet() { // Since a workflow may be forked to produce multiple subscribed Rx chains, we should // ensure the didComplete method is only invoked once per Workflow instance. See `Step.commit` // on why the side-effects must be added at the end of the Rx chains. guard !didInvokeComplete else { return } didInvokeComplete = true didComplete() } } /// Defines a single step in a `Workflow`. /// /// A step may produce a next step with a new value and actionable item, eventually forming a sequence of `Workflow` /// steps. /// /// Steps are asynchronous by nature. open class Step<WorkflowActionableItemType, ActionableItemType, ValueType> { private let workflow: Workflow<WorkflowActionableItemType> private var observable: Observable<(ActionableItemType, ValueType)> fileprivate init(workflow: Workflow<WorkflowActionableItemType>, observable: Observable<(ActionableItemType, ValueType)>) { self.workflow = workflow self.observable = observable } /// Executes the given closure for this step. /// /// - parameter onStep: The closure to execute for the `Step`. /// - returns: The next step. public final func onStep<NextActionableItemType, NextValueType>(_ onStep: @escaping (ActionableItemType, ValueType) -> Observable<(NextActionableItemType, NextValueType)>) -> Step<WorkflowActionableItemType, NextActionableItemType, NextValueType> { let confinedNextStep = observable .flatMapLatest { (actionableItem, value) -> Observable<(Bool, ActionableItemType, ValueType)> in // We cannot use generic constraint here since Swift requires constraints be // satisfied by concrete types, preventing using protocol as actionable type. if let interactor = actionableItem as? Interactable { return interactor .isActiveStream .map({ (isActive: Bool) -> (Bool, ActionableItemType, ValueType) in (isActive, actionableItem, value) }) } else { return Observable.just((true, actionableItem, value)) } } .filter { (isActive: Bool, _, _) -> Bool in isActive } .take(1) .flatMapLatest { (_, actionableItem: ActionableItemType, value: ValueType) -> Observable<(NextActionableItemType, NextValueType)> in onStep(actionableItem, value) } .take(1) .share() return Step<WorkflowActionableItemType, NextActionableItemType, NextValueType>(workflow: workflow, observable: confinedNextStep) } /// Executes the given closure when the `Step` produces an error. /// /// - parameter onError: The closure to execute when an error occurs. /// - returns: This step. public final func onError(_ onError: @escaping ((Error) -> ())) -> Step<WorkflowActionableItemType, ActionableItemType, ValueType> { observable = observable.do(onError: onError) return self } /// Commit the steps of the `Workflow` sequence. /// /// - returns: The committed `Workflow`. @discardableResult public final func commit() -> Workflow<WorkflowActionableItemType> { // Side-effects must be chained at the last observable sequence, since errors and complete // events can be emitted by any observables on any steps of the workflow. let disposable = observable .do(onError: workflow.didReceiveError, onCompleted: workflow.didCompleteIfNotYet) .subscribe() _ = workflow.compositeDisposable.insert(disposable) return workflow } /// Convert the `Workflow` into an obseravble. /// /// - returns: The observable representation of this `Workflow`. public final func asObservable() -> Observable<(ActionableItemType, ValueType)> { return observable } } /// `Workflow` related obervable extensions. public extension ObservableType { /// Fork the step from this obervable. /// /// - parameter workflow: The workflow this step belongs to. /// - returns: The newly forked step in the workflow. `nil` if this observable does not conform to the required /// generic type of (ActionableItemType, ValueType). func fork<WorkflowActionableItemType, ActionableItemType, ValueType>(_ workflow: Workflow<WorkflowActionableItemType>) -> Step<WorkflowActionableItemType, ActionableItemType, ValueType>? { if let stepObservable = self as? Observable<(ActionableItemType, ValueType)> { workflow.didFork() return Step(workflow: workflow, observable: stepObservable) } return nil } } /// `Workflow` related `Disposable` extensions. public extension Disposable { /// Dispose the subscription when the given `Workflow` is disposed. /// /// When using this composition, the subscription closure may freely retain the workflow itself, since the /// subscription closure is disposed once the workflow is disposed, thus releasing the retain cycle before the /// `Workflow` needs to be deallocated. /// /// - note: This is the preferred method when trying to confine a subscription to the lifecycle of a `Workflow`. /// /// - parameter workflow: The workflow to dispose the subscription with. func disposeWith<ActionableItemType>(workflow: Workflow<ActionableItemType>) { _ = workflow.compositeDisposable.insert(self) } /// Dispose the subscription when the given `Workflow` is disposed. /// /// When using this composition, the subscription closure may freely retain the workflow itself, since the /// subscription closure is disposed once the workflow is disposed, thus releasing the retain cycle before the /// `Workflow` needs to be deallocated. /// /// - note: This is the preferred method when trying to confine a subscription to the lifecycle of a `Workflow`. /// /// - parameter workflow: The workflow to dispose the subscription with. @available(*, deprecated, renamed: "disposeWith(workflow:)") func disposeWith<ActionableItemType>(worflow: Workflow<ActionableItemType>) { disposeWith(workflow: worflow) } }
8576c927f7e331d54bc6c6b0fcb45834
42.89823
252
0.675033
false
false
false
false
nerd0geek1/NSPageControl
refs/heads/master
Example/Example/AppDelegate.swift
mit
1
// // AppDelegate.swift // Example // // Created by Kohei Tabata on 2016/03/25. // Copyright © 2016年 Kohei Tabata. All rights reserved. // import Cocoa import NSPageControl @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { @IBOutlet weak var window: NSWindow! private var pageControl: NSPageControl! func applicationDidFinishLaunching(_ aNotification: Notification) { setupPageControl() } func applicationWillTerminate(_ aNotification: Notification) { } // MARK: - private private func setupPageControl() { pageControl = NSPageControl() pageControl.numberOfPages = 4 let width: CGFloat = 200 let x: CGFloat = (window.frame.width - width) / 2 pageControl.frame = CGRect(x: x, y: 20, width: 200, height: 20) window.contentView?.addSubview(pageControl) } // MARK: - IBAction @IBAction func tapPreviousButton(_ sender: NSButton) { pageControl.currentPage -= 1 } @IBAction func tapNextButton(_ sender: NSButton) { pageControl.currentPage += 1 } }
6063583bfb0e75c8d3066df548bde2bc
24
72
0.654222
false
false
false
false
huangboju/AsyncDisplay_Study
refs/heads/master
AsyncDisplay/PhotoFeed/PhotoCommentsNode.swift
mit
1
// // PhotoCommentsNode.swift // AsyncDisplay // // Created by 伯驹 黄 on 2017/4/27. // Copyright © 2017年 伯驹 黄. All rights reserved. // let INTER_COMMENT_SPACING: CGFloat = 5 let NUM_COMMENTS_TO_SHOW = 3 import AsyncDisplayKit class PhotoCommentsNode: ASDisplayNode { var commentFeed: CommentFeedModel? lazy var commentNodes: [ASTextNode] = [] override init() { super.init() automaticallyManagesSubnodes = true } override func layoutSpecThatFits(_ constrainedSize: ASSizeRange) -> ASLayoutSpec { return ASStackLayoutSpec(direction: .vertical, spacing: INTER_COMMENT_SPACING, justifyContent: .start, alignItems: .stretch, children: commentNodes) } func updateWithCommentFeedModel(_ feed: CommentFeedModel) { commentFeed = feed commentNodes.removeAll(keepingCapacity: true) if let commentFeed = commentFeed { createCommentLabels() let addViewAllCommentsLabel = feed.numberOfComments(forPhotoExceedsInteger: NUM_COMMENTS_TO_SHOW) var commentLabelString: NSAttributedString var labelsIndex = 0 if addViewAllCommentsLabel { commentLabelString = commentFeed.viewAllCommentsAttributedString() commentNodes[labelsIndex].attributedText = commentLabelString labelsIndex += 1 } let numCommentsInFeed = commentFeed.numberOfItemsInFeed() for feedIndex in 0 ..< numCommentsInFeed { commentLabelString = commentFeed.object(at: feedIndex).commentAttributedString() commentNodes[labelsIndex].attributedText = commentLabelString labelsIndex += 1 } setNeedsLayout() } } private func createCommentLabels() { guard let commentFeed = commentFeed else { return } let addViewAllCommentsLabel = commentFeed.numberOfComments(forPhotoExceedsInteger: NUM_COMMENTS_TO_SHOW) let numCommentsInFeed = commentFeed.numberOfItemsInFeed() let numLabelsToAdd = (addViewAllCommentsLabel) ? numCommentsInFeed + 1 : numCommentsInFeed for _ in 0 ..< numLabelsToAdd { let commentLabel = ASTextNode() commentLabel.isLayerBacked = true commentLabel.maximumNumberOfLines = 3 commentNodes.append(commentLabel) } } }
5474a5ba1a592a8ac8024161440604dc
32.616438
156
0.650367
false
false
false
false
Fenrikur/ef-app_ios
refs/heads/master
Domain Model/EurofurenceModelTestDoubles/CapturingJSONSession.swift
mit
2
import EurofurenceModel import Foundation public class CapturingJSONSession: JSONSession { public init() { } public private(set) var getRequestURL: String? public private(set) var capturedAdditionalGETHeaders: [String: String]? private var GETCompletionHandler: ((Data?, Error?) -> Void)? public func get(_ request: JSONRequest, completionHandler: @escaping (Data?, Error?) -> Void) { getRequestURL = request.url capturedAdditionalGETHeaders = request.headers GETCompletionHandler = completionHandler } public private(set) var postedURL: String? public private(set) var capturedAdditionalPOSTHeaders: [String: String]? public private(set) var POSTData: Data? private var POSTCompletionHandler: ((Data?, Error?) -> Void)? public func post(_ request: JSONRequest, completionHandler: @escaping (Data?, Error?) -> Void) { postedURL = request.url POSTData = request.body self.POSTCompletionHandler = completionHandler capturedAdditionalPOSTHeaders = request.headers } public func postedJSONValue<T>(forKey key: String) -> T? { guard let POSTData = POSTData else { return nil } guard let json = try? JSONSerialization.jsonObject(with: POSTData, options: .allowFragments) else { return nil } guard let jsonDictionary = json as? [String: Any] else { return nil } return jsonDictionary[key] as? T } public func invokeLastGETCompletionHandler(responseData: Data?) { GETCompletionHandler?(responseData, nil) } public func invokeLastPOSTCompletionHandler(responseData: Data?, error: Error? = nil) { POSTCompletionHandler?(responseData, error) } }
ef241926b507ca371720bd3af041d9b2
36.5
120
0.698551
false
false
false
false
selfzhou/Swift3
refs/heads/master
Playground/Swift3-II.playground/Pages/StringsAndCharacters.xcplaygroundpage/Contents.swift
mit
1
//: [Previous](@previous) import Foundation var emptyString = "" var anotherEmptyString = String() if emptyString == anotherEmptyString { print("Equal") } for character in "Dog!🐶".characters { print(character) } let catChatacters: [Character] = ["C", "a", "t"] let catString = String(catChatacters) var welcome = "welcome" welcome.append("!") /** NSString length 利用 UTF-16 表示的十六位代码单元数字,而不是 Unicode 可扩展字符群集 当一个 NSString length 属性被一个 Swift 的 String 值访问时,实际上是调用了 utf16Count */ /** startIndex 获取 String 的第一个 Character 的索引 endIndex 获取最后一个 Character 的`后一个位置`的索引 */ let greeting = "Guten Tag!" greeting[greeting.startIndex] greeting[greeting.index(before: greeting.endIndex)] greeting[greeting.index(after: greeting.startIndex)] let index = greeting.index(greeting.startIndex, offsetBy: 7) greeting[index] /** `indices` characters 属性的 indices 属性会创建一个包含全部索引的范围(Range),用来在一个字符串中访问单个字符 */ for index in greeting.characters.indices { print("\(greeting[index])", terminator: "") } welcome.insert(contentsOf: " hello".characters, at: welcome.index(before: welcome.endIndex))
3570660172e52304a2fa76ecefdad72a
18.789474
92
0.715426
false
false
false
false
neoneye/SwiftyFORM
refs/heads/master
Source/FormItems/TextFieldFormItem.swift
mit
1
// MIT license. Copyright (c) 2021 SwiftyFORM. All rights reserved. import UIKit public class TextFieldFormItem: FormItem, CustomizableLabel { override func accept(visitor: FormItemVisitor) { visitor.visit(object: self) } public var keyboardType: UIKeyboardType = .default @discardableResult public func keyboardType(_ keyboardType: UIKeyboardType) -> Self { self.keyboardType = keyboardType return self } public var autocorrectionType: UITextAutocorrectionType = .no public var autocapitalizationType: UITextAutocapitalizationType = .none public var spellCheckingType: UITextSpellCheckingType = .no public var secureTextEntry = false public var textAlignment: NSTextAlignment = .left public var clearButtonMode: UITextField.ViewMode = .whileEditing public var returnKeyType: UIReturnKeyType = .default @discardableResult public func returnKeyType(_ returnKeyType: UIReturnKeyType) -> Self { self.returnKeyType = returnKeyType return self } public typealias SyncBlock = (_ value: String) -> Void public var syncCellWithValue: SyncBlock = { (string: String) in SwiftyFormLog("sync is not overridden") } internal var innerValue: String = "" public var value: String { get { return self.innerValue } set { self.assignValueAndSync(newValue) } } public typealias TextDidChangeBlock = (_ value: String) -> Void public var textDidChangeBlock: TextDidChangeBlock = { (value: String) in SwiftyFormLog("not overridden") } public func textDidChange(_ value: String) { innerValue = value textDidChangeBlock(value) } public typealias TextEditingEndBlock = (_ value: String) -> Void public var textEditingEndBlock: TextEditingEndBlock = { (value: String) in SwiftyFormLog("not overridden") } public func editingEnd(_ value: String) { textEditingEndBlock(value) } public func assignValueAndSync(_ value: String) { innerValue = value syncCellWithValue(value) } public var reloadPersistentValidationState: () -> Void = {} public var obtainTitleWidth: () -> CGFloat = { return 0 } public var assignTitleWidth: (CGFloat) -> Void = { (width: CGFloat) in // do nothing } public var placeholder: String = "" @discardableResult public func placeholder(_ placeholder: String) -> Self { self.placeholder = placeholder return self } public var title: String = "" public var titleFont: UIFont = .preferredFont(forTextStyle: .body) public var titleTextColor: UIColor = Colors.text public var detailFont: UIFont = .preferredFont(forTextStyle: .body) public var detailTextColor: UIColor = Colors.secondaryText public var errorFont: UIFont = .preferredFont(forTextStyle: .caption2) public var errorTextColor: UIColor = UIColor.red @discardableResult public func password() -> Self { self.secureTextEntry = true return self } public let validatorBuilder = ValidatorBuilder() @discardableResult public func validate(_ specification: Specification, message: String) -> Self { validatorBuilder.hardValidate(specification, message: message) return self } @discardableResult public func softValidate(_ specification: Specification, message: String) -> Self { validatorBuilder.softValidate(specification, message: message) return self } @discardableResult public func submitValidate(_ specification: Specification, message: String) -> Self { validatorBuilder.submitValidate(specification, message: message) return self } @discardableResult public func required(_ message: String) -> Self { submitValidate(CountSpecification.min(1), message: message) return self } public func liveValidateValueText() -> ValidateResult { validatorBuilder.build().liveValidate(self.value) } public func liveValidateText(_ text: String) -> ValidateResult { validatorBuilder.build().validate(text, checkHardRule: true, checkSoftRule: true, checkSubmitRule: false) } public func submitValidateValueText() -> ValidateResult { validatorBuilder.build().submitValidate(self.value) } public func submitValidateText(_ text: String) -> ValidateResult { validatorBuilder.build().validate(text, checkHardRule: true, checkSoftRule: true, checkSubmitRule: true) } public func validateText(_ text: String, checkHardRule: Bool, checkSoftRule: Bool, checkSubmitRule: Bool) -> ValidateResult { validatorBuilder.build().validate(text, checkHardRule: checkHardRule, checkSoftRule: checkSoftRule, checkSubmitRule: checkSubmitRule) } }
e04a79d057a8eed98f9f61b38d2a462b
28.225806
135
0.745475
false
false
false
false
herobin22/TopOmnibus
refs/heads/master
TopOmnibus/TopOmnibus/Commons/OYViewController.swift
mit
1
// // OYViewController.swift // TopOmnibus // // Created by Gold on 2016/11/11. // Copyright © 2016年 herob. All rights reserved. // import UIKit import MJRefresh import GoogleMobileAds//广告 class OYViewController: UIViewController, GADBannerViewDelegate { let tableView = UITableView() var curPage: Int = 1 var bannerView: GADBannerView = GADBannerView() override func viewDidLoad() { super.viewDidLoad() setupUI() setupRefresh() setupTitleView() } private func setupUI() { view.backgroundColor = UIColor.white tableView.frame = view.bounds view.addSubview(tableView) tableView.delegate = self tableView.dataSource = self tableView.estimatedRowHeight = 100 tableView.rowHeight = UITableViewAutomaticDimension tableView.tableFooterView = UIView() tableView.scrollsToTop = true } private func setupRefresh() { tableView.mj_header = MJRefreshNormalHeader(refreshingTarget: self, refreshingAction: #selector(headRefresh)) tableView.mj_header.beginRefreshing() tableView.mj_footer = MJRefreshAutoNormalFooter(refreshingTarget: self, refreshingAction: #selector(footRefresh)) tableView.mj_footer.isHidden = true } private func setupTitleView() { let imageView = UIImageView(image: UIImage(named: "titleBus")) imageView.contentMode = .scaleAspectFit imageView.bounds = CGRect(x: 0, y: 0, width: 150, height: 44) navigationItem.titleView = imageView } @objc private func headRefresh() { curPage = 1 refreshAction() } @objc private func footRefresh() { curPage = curPage + 1 refreshAction() } private func refreshAction() -> Void { loadData() } func endRefresh() { tableView.mj_header.endRefreshing() tableView.mj_footer.endRefreshing() } func loadData() { } } extension OYViewController: UITableViewDelegate, UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 0 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = UITableViewCell() return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { } }
939411ebed7019ff67cde9fed4ff0b5c
27.102273
121
0.650222
false
false
false
false
jisudong/study
refs/heads/master
Study/Study/Study_RxSwift/Platform/DataStructures/Bag.swift
mit
1
// // Bag.swift // Study // // Created by syswin on 2017/7/31. // Copyright © 2017年 syswin. All rights reserved. // import Swift let arrayDictionaryMaxSize = 30 struct BagKey { fileprivate let rawValue: UInt64 } struct Bag<T> : CustomDebugStringConvertible { typealias KeyType = BagKey typealias Entry = (key: BagKey, value: T) fileprivate var _nextKey: BagKey = BagKey(rawValue: 0) var _key0: BagKey? = nil var _value0: T? = nil var _pairs = ContiguousArray<Entry>() var _dictionary: [BagKey : T]? = nil var _onlyFastPath = true init() { } mutating func insert(_ element: T) -> BagKey { let key = _nextKey _nextKey = BagKey(rawValue: _nextKey.rawValue &+ 1) if _key0 == nil { _key0 = key _value0 = element return key } _onlyFastPath = false if _dictionary != nil { _dictionary![key] = element return key } if _pairs.count < arrayDictionaryMaxSize { _pairs.append(key: key, value: element) return key } if _dictionary == nil { _dictionary = [:] } _dictionary![key] = element return key } var count: Int { let dictionaryCount: Int = _dictionary?.count ?? 0 return (_value0 != nil ? 1 : 0) + _pairs.count + dictionaryCount } mutating func removeAll() { _key0 = nil _value0 = nil _pairs.removeAll(keepingCapacity: false) _dictionary?.removeAll(keepingCapacity: false) } mutating func removeKey(_ key: BagKey) -> T? { if _key0 == key { _key0 = nil let value = _value0! _value0 = nil return value } if let existingObject = _dictionary?.removeValue(forKey: key) { return existingObject } for i in 0 ..< _pairs.count { if _pairs[i].key == key { let value = _pairs[i].value _pairs.remove(at: i) return value } } return nil } } extension Bag { var debugDescription: String { return "\(self.count) elements in Bag" } } extension Bag { func forEach(_ action: (T) -> Void) { if _onlyFastPath { if let value0 = _value0 { action(value0) } return } let value0 = _value0 let dictionary = _dictionary if let value0 = value0 { action(value0) } for i in 0 ..< _pairs.count { action(_pairs[i].value) } if dictionary?.count ?? 0 > 0 { for element in dictionary!.values { action(element) } } } } extension BagKey: Hashable { var hashValue: Int { return rawValue.hashValue } } func ==(lhs: BagKey, rhs: BagKey) -> Bool { return lhs.rawValue == rhs.rawValue }
f6c7c89f77b1c5128504f03a26507838
20.271523
72
0.482877
false
false
false
false
KyoheiG3/TableViewDragger
refs/heads/master
TableViewDragger/TableViewDraggerCell.swift
mit
1
// // TableViewDraggerCell.swift // TableViewDragger // // Created by Kyohei Ito on 2015/09/24. // Copyright © 2015年 kyohei_ito. All rights reserved. // import UIKit class TableViewDraggerCell: UIScrollView { private let zoomingView: UIView! var dragAlpha: CGFloat = 1 var dragScale: CGFloat = 1 var dragShadowOpacity: Float = 0.4 var dropIndexPath: IndexPath = IndexPath(index: 0) var offset: CGPoint = CGPoint.zero { didSet { offset.x -= (bounds.width / 2) offset.y -= (bounds.height / 2) center = adjustCenter(location) } } var location: CGPoint = CGPoint.zero { didSet { center = adjustCenter(location) } } var viewHeight: CGFloat { return zoomingView.bounds.height * zoomScale } private func adjustCenter(_ center: CGPoint) -> CGPoint { var center = center center.x -= offset.x center.y -= offset.y return center } required init?(coder aDecoder: NSCoder) { zoomingView = UIView(frame: .zero) super.init(coder: aDecoder) } init(cell: UIView) { zoomingView = UIView(frame: cell.bounds) zoomingView.addSubview(cell) super.init(frame: cell.bounds) delegate = self clipsToBounds = false layer.shadowColor = UIColor.black.cgColor layer.shadowOpacity = 0 layer.shadowRadius = 5 layer.shadowOffset = .zero addSubview(zoomingView) } func transformToPoint(_ point: CGPoint) { if dragScale > 1 { maximumZoomScale = dragScale } else { minimumZoomScale = dragScale } var center = zoomingView.center center.x -= (center.x * dragScale) - point.x center.y -= (center.y * dragScale) - point.y UIView.animate(withDuration: 0.25, delay: 0.1, options: .curveEaseInOut, animations: { self.zoomingView.center = center self.zoomScale = self.dragScale self.alpha = self.dragAlpha }, completion: nil) CATransaction.begin() let anim = CABasicAnimation(keyPath: "shadowOpacity") anim.fromValue = 0 anim.toValue = dragShadowOpacity anim.duration = 0.1 anim.isRemovedOnCompletion = false anim.fillMode = .forwards layer.add(anim, forKey: "cellDragAnimation") CATransaction.commit() } func adjustedCenter(on scrollView: UIScrollView) -> CGPoint { var center = location center.y -= scrollView.contentOffset.y center.x = scrollView.center.x return center } func drop(_ center: CGPoint, completion: (() -> Void)? = nil) { UIView.animate(withDuration: 0.25) { self.zoomingView.adjustCenterAtRect(self.zoomingView.frame) self.center = center self.zoomScale = 1.0 self.alpha = 1.0 } CATransaction.begin() let anim = CABasicAnimation(keyPath: "shadowOpacity") anim.fromValue = dragShadowOpacity anim.toValue = 0 anim.duration = 0.15 anim.beginTime = CACurrentMediaTime() + 0.15 anim.isRemovedOnCompletion = false anim.fillMode = .forwards CATransaction.setCompletionBlock { self.removeFromSuperview() completion?() } layer.add(anim, forKey: "cellDropAnimation") CATransaction.commit() } } extension TableViewDraggerCell: UIScrollViewDelegate { func viewForZooming(in scrollView: UIScrollView) -> UIView? { return zoomingView } } private extension UIView { func adjustCenterAtRect(_ rect: CGRect) { let center = CGPoint(x: rect.size.width / 2, y: rect.size.height / 2) self.center = center } }
e9f9e839590171b540e4cfa38ecb1290
27.279412
94
0.605044
false
false
false
false
volendavidov/NagBar
refs/heads/master
NagBar/Icinga2URLProvider.swift
apache-2.0
1
// // Icinga2URLProvider.swift // NagBar // // Created by Volen Davidov on 02.07.16. // Copyright © 2016 Volen Davidov. All rights reserved. // import Foundation class Icinga2URLProvider : MonitoringProcessorBase, URLProvider { func create() -> Array<MonitoringURL> { var urls: Array<MonitoringURL> = [] urls.append(MonitoringURL.init(urlType: MonitoringURLType.hosts, priority: 1, url: self.monitoringInstance!.url + "/objects/hosts?attrs=name&attrs=address&attrs=last_state_change&attrs=check_attempt&attrs=last_check_result&attrs=state&attrs=acknowledgement&attrs=downtime_depth&filter=" + Icinga2Settings().getHostStatusTypes() + Icinga2Settings().getHostProperties())) urls.append(MonitoringURL.init(urlType: MonitoringURLType.services, priority: 2, url: self.monitoringInstance!.url + "/objects/services?attrs=name&attrs=last_state_change&attrs=check_attempt&attrs=max_check_attempts&attrs=last_check_result&attrs=state&attrs=host_name&attrs=acknowledgement&attrs=downtime_depth&filter=" + Icinga2Settings().getServiceStatusTypes() + Icinga2Settings().getServiceProperties())) if Settings().boolForKey("skipServicesOfHostsWithScD") { urls.append(MonitoringURL.init(urlType: MonitoringURLType.hostScheduledDowntime, priority: 3, url: self.monitoringInstance!.url + "/objects/hosts?attrs=name&filter=host.last_in_downtime==true")) } return urls } }
ea4e689fffc2cc3fa1c13a070ca27822
59.583333
416
0.741403
false
false
false
false
erikmartens/NearbyWeather
refs/heads/develop
NearbyWeather/Commons/Core User Interface Building Blocks/TableView/BaseTableViewDataSource.swift
mit
1
// // TableViewDataSource.swift // NearbyWeather // // Created by Erik Maximilian Martens on 02.01.21. // Copyright © 2021 Erik Maximilian Martens. All rights reserved. // import UIKit import RxSwift import RxCocoa class BaseTableViewDataSource: NSObject { weak var cellEditingDelegate: BaseTableViewDataSourceEditingDelegate? var sectionDataSources: BehaviorRelay<[TableViewSectionDataProtocol]?> = BehaviorRelay(value: nil) init(cellEditingDelegate: BaseTableViewDataSourceEditingDelegate? = nil) { self.cellEditingDelegate = cellEditingDelegate } } extension BaseTableViewDataSource: UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { sectionDataSources.value?.count ?? 0 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { sectionDataSources.value?[safe: section]?.sectionCellsCount ?? 0 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let cellIdentifier = sectionDataSources.value?[safe: indexPath.section]?.sectionCellsIdentifiers?[safe: indexPath.row] else { fatalError("Could not determine reuse-identifier for sections-cells.") } guard let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as? BaseCellProtocol else { fatalError("Cell does not conform to the correct protocol (BaseCellProtocol).") } cell.configure(with: sectionDataSources[indexPath]) return cell } func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { sectionDataSources.value?[safe: section]?.sectionHeaderTitle } func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? { sectionDataSources.value?[safe: section]?.sectionFooterTitle } func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { sectionDataSources.value?[safe: indexPath.section]?.sectionItems[safe: indexPath.row]?.canEditRow ?? false } func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool { sectionDataSources.value?[safe: indexPath.section]?.sectionItems[safe: indexPath.row]?.canMoveRow ?? false } func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) { cellEditingDelegate?.didCommitEdit(with: editingStyle, forRowAt: indexPath) } func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) { cellEditingDelegate?.didMoveRow(at: sourceIndexPath, to: destinationIndexPath) } }
a1cf5afaa29e1165db7d26b700a156ee
39.757576
135
0.762082
false
false
false
false
felipeuntill/WeddingPlanner
refs/heads/master
IOS/WeddingPlanner/GenericRepository.swift
mit
1
// // GenericRepository.swift // WeddingPlanner // // Created by Felipe Assunção on 4/21/16. // Copyright © 2016 Felipe Assunção. All rights reserved. // import Foundation import ObjectMapper class GenericRepository<T: Mappable> { private var address : String! init(address: String!) { self.address = address } func insert (entity : T) -> T { let json = Mapper().toJSONString(entity, prettyPrint: true) let raw = NSDataProvider.LoadFromUri(address, method: "POST", json: json) let result = Mapper<T>().map(raw) return result! } func list () -> Array<T>? { let raw = NSDataProvider.LoadFromUri(address) let list = Mapper<T>().mapArray(raw) return list } func load (id : String) -> T? { let uri = "\(address)/\(id)" let raw = NSDataProvider.LoadFromUri(uri) let entity = Mapper<T>().map(raw) return entity } }
4b572fc4e169afd365cac7af629e8979
23.820513
81
0.593588
false
false
false
false
fahlout/SimpleWebRequests
refs/heads/master
Sources/Web Service Layer/JSON Coder/JSONCoder.swift
mit
1
// // JSONCoder.swift // SimpleWebServiceRequestsDemo // // Created by Niklas Fahl on 10/11/17. // Copyright © 2017 Niklas Fahl. All rights reserved. // import Foundation public final class JSONCoder { public class func encode<T>(object: T, dateEncodingStrategy: JSONEncoder.DateEncodingStrategy = .iso8601) -> Data? where T: Encodable { do { let encoder = JSONEncoder() encoder.dateEncodingStrategy = dateEncodingStrategy return try encoder.encode(object) } catch let error { print("JSON Coder: Could not encode object to JSON data. Error: \(error)") return nil } } public class func decode<T>(data: Data?, dateDecodingStrategy: JSONDecoder.DateDecodingStrategy = .iso8601) -> T? where T: Decodable { guard let data = data else { return nil } do { let decoder = JSONDecoder() decoder.dateDecodingStrategy = dateDecodingStrategy return try decoder.decode(T.self, from: data) } catch let error { print("JSON Coder: Could not decode JSON data to object. Error: \(error)") return nil } } }
039a3881cc65ed15eb9ba55a3dda64b7
32.444444
139
0.61794
false
false
false
false
zhou9734/Warm
refs/heads/master
Warm/Classes/Experience/View/EPageScrollView.swift
mit
1
// // EPageScrollView.swift // Warm // // Created by zhoucj on 16/9/14. // Copyright © 2016年 zhoucj. All rights reserved. // import UIKit import SDWebImage class EPageScrollView: UIView { let pageWidth: CGFloat = UIScreen.mainScreen().bounds.width // let pageHeight: CGFloat = self.frame.size.height let imageView0: UIImageView = UIImageView() let imageView1: UIImageView = UIImageView() let imageView2: UIImageView = UIImageView() /// 图片数组 private var currentPage = 0{ didSet{ if tags.count > 0{ unowned let tmpSelf = self imageView.sd_setImageWithURL(NSURL(string: tags[currentPage].avatar!), placeholderImage: placeholderImage, completed: { (image, error, _, _) -> Void in tmpSelf.imageView.image = image.applyLightEffect() }) } } } var tags: [WTags] = [WTags](){ didSet{ updateImageData() currentPage = 0 } } override init(frame: CGRect) { super.init(frame: frame) setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func setupUI(){ addSubview(imageView) addSubview(scrollView) } private lazy var scrollView: UIScrollView = { let scrollView = UIScrollView() scrollView.frame = self.bounds //为了让内容横向滚动,设置横向内容宽度为3个页面的宽度总和 let pageHeight: CGFloat = self.frame.size.height scrollView.contentSize=CGSizeMake(CGFloat(self.pageWidth*3), CGFloat(pageHeight)) scrollView.pagingEnabled = true scrollView.showsHorizontalScrollIndicator = false scrollView.showsVerticalScrollIndicator = false scrollView.scrollsToTop = false scrollView.delegate = self let imageW = self.pageWidth - (self.pageWidth*0.5) let imageH = pageHeight - (pageHeight*0.3) let offsetY = pageHeight*0.15 self.imageView0.frame = CGRect(x: (self.pageWidth - imageW)/2, y: offsetY, width: imageW, height: imageH) self.imageView1.frame = CGRect(x: self.pageWidth + (self.pageWidth - imageW)/2, y: offsetY, width: imageW, height: imageH) self.imageView2.frame = CGRect(x: self.pageWidth * 2 + (self.pageWidth - imageW)/2, y: offsetY, width: imageW, height: imageH) scrollView.addSubview(self.imageView0) scrollView.addSubview(self.imageView1) scrollView.addSubview(self.imageView2) let tap = UITapGestureRecognizer(target: self, action: "imageViewClick:") scrollView.addGestureRecognizer(tap) return scrollView }() private lazy var imageView: UIImageView = { let iv = UIImageView() iv.frame = CGRect(x: 0.0, y: 0.0, width: self.pageWidth, height: self.frame.size.height) return iv }() // MARK: - 点击图片调转 @objc private func imageViewClick(tap: UITapGestureRecognizer) { NSNotificationCenter.defaultCenter().postNotificationName(TagsImageClick, object: self, userInfo: [ "index" : currentPage]) } } extension EPageScrollView: UIScrollViewDelegate{ func scrollViewDidEndDecelerating(scrollView: UIScrollView) { let ratio = scrollView.contentOffset.x/scrollView.frame.size.width self.endScrollMethod(ratio) } func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) { if !decelerate{ let ratio = scrollView.contentOffset.x/scrollView.frame.size.width endScrollMethod(ratio) } } private func endScrollMethod(ratio:CGFloat){ if ratio <= 0.7{ if currentPage - 1 < 0{ currentPage = tags.count - 1 }else{ currentPage -= 1 } } if ratio >= 1.3{ if currentPage == tags.count - 1{ currentPage = 0 }else{ currentPage += 1 } } updateImageData() } //MARK: - reload data private func updateImageData(){ if currentPage == 0{ imageView0.sd_setImageWithURL(NSURL(string: tags.last!.avatar!), placeholderImage: placeholderImage) imageView1.sd_setImageWithURL(NSURL(string: tags[currentPage].avatar!), placeholderImage: placeholderImage) imageView2.sd_setImageWithURL(NSURL(string: tags[currentPage + 1].avatar!), placeholderImage: placeholderImage) }else if currentPage == tags.count - 1{ imageView0.sd_setImageWithURL(NSURL(string: tags[currentPage - 1 ].avatar!), placeholderImage: placeholderImage) imageView1.sd_setImageWithURL(NSURL(string: tags[currentPage].avatar!), placeholderImage: placeholderImage) imageView2.sd_setImageWithURL(NSURL(string: tags.first!.avatar!), placeholderImage: placeholderImage) }else{ imageView0.sd_setImageWithURL(NSURL(string: tags[currentPage - 1 ].avatar!), placeholderImage: placeholderImage) imageView1.sd_setImageWithURL(NSURL(string: tags[currentPage].avatar!), placeholderImage: placeholderImage) imageView2.sd_setImageWithURL(NSURL(string: tags[currentPage + 1].avatar!), placeholderImage: placeholderImage) } scrollView.contentOffset = CGPoint(x: scrollView.frame.size.width, y: 0) } }
d37a958371075103fa074d3d4fba5c2a
39.840909
167
0.644778
false
false
false
false
Artilles/FloppyCows
refs/heads/master
Floppy Cows/FloppyCow.swift
gpl-2.0
1
// // FloppyCow.swift // Floppy Cows // // Created by Ray Young on 2014-10-31. // Copyright (c) 2014 Velocitrix. All rights reserved. // import Foundation import SpriteKit import AVFoundation // Cow class FloppyCow : SKSpriteNode { private let cowCategory: UInt32 = 0x1 << 1 private let playerCategory: UInt32 = 0x1 << 0 private let madBullCategory: UInt32 = 0x1 << 3 private let deadCategory: UInt32 = 0x1 << 5 var cowID : Int = 0 var targetPosition : CGPoint; var ready = false; var textureChanged = false; var rnd = arc4random_uniform(2) var posIndex : Int = -1; var soundPlayer:AVAudioPlayer = AVAudioPlayer() var mooPlayer:AVAudioPlayer = AVAudioPlayer() var mooURL:NSURL = NSBundle.mainBundle().URLForResource("moo", withExtension: "mp3")! var gallopURL:NSURL = NSBundle.mainBundle().URLForResource("gallop", withExtension: "mp3")! //MadBull var madTimer : Double = 0 var rampageTime : CGFloat = 60.0; var rampageTimer : CGFloat = 0.0; var rampageInterval : CGFloat = 1.0; var rampageCounter : CGFloat = 1.0; var rampageSpeed : CGFloat = 1.0; var isMad : Bool = false; var isCharging : Bool = false var removedWarning : Bool = false; var playerPos: CGPoint = CGPoint(x:0,y: 0); var rampageVector :CGPoint = CGPoint(x :0, y :0); var pathLineMod :CGPoint = CGPoint(x :2, y :4); var cowSpeed : CGFloat = 10; var lockOnPlayer : Bool = false var isAlive : Bool = true; var direction : CGPoint = CGPoint(x :0, y :0); var madBullID : Int = 0 var removeCow = false; //var warnSprite : SKSpriteNode var warn: Warning = Warning() var temp : CGFloat = 1.0; //fade var isFade : Bool = false; convenience override init() { // init then swap texture if the arc4random generated number is 0 // 0 is facing bottom left, 1 is facing bottom right self.init(imageNamed: "mama_cow_falling2") if(rnd == 0) { self.texture = SKTexture(imageNamed:"mama_cow_falling") } xScale = 0.35 yScale = 0.35 physicsBody = SKPhysicsBody(rectangleOfSize: size) physicsBody?.dynamic = true physicsBody?.categoryBitMask = cowCategory physicsBody?.contactTestBitMask = playerCategory physicsBody?.collisionBitMask = 0 soundPlayer = AVAudioPlayer(contentsOfURL: gallopURL, error: nil) mooPlayer = AVAudioPlayer(contentsOfURL: mooURL, error: nil) //warnSprite = SKSpriteNode(imageNamed: "warning") } override init(texture: SKTexture!, color: UIColor!, size: CGSize) { targetPosition = CGPoint(x: 0, y: 0) super.init(texture: texture, color: color, size: size) } required init?(coder decoder: NSCoder) { targetPosition = CGPoint(x: 0, y: 0) super.init(coder: decoder) } func SetCowID(ID: Int) { cowID = ID } func incrementTime(time : Double) { madTimer += time; } func gettingMad() { if(rampageCounter >= rampageInterval){ rampageTimer += 0.1; rampageCounter += 0.1; } } func switchToMadCow() { physicsBody = SKPhysicsBody(circleOfRadius: (size.width / 3.5)) physicsBody?.dynamic = true physicsBody?.categoryBitMask = madBullCategory physicsBody?.contactTestBitMask = playerCategory physicsBody?.collisionBitMask = 0 // if(rnd == 0) { // self.texture = SKTexture(imageNamed: "redcow_horizontal_Right.png") // self.texture = SKTexture(imageNamed: "redcow_horizontal_Left.png") //} } func UpdateCow(currentTime: CFTimeInterval) { if (!ready) { position.y -= 15 if (position.y < targetPosition.y) { // cow has landed ready = true position.y = targetPosition.y // switch the cow texture after landing if (rnd == 1) { self.texture = SKTexture(imageNamed: "Mama_Cow") } else { self.texture = SKTexture(imageNamed: "mama_cow2") } } } else if(ready) { rampage() } } func rampage() { if(rampageTime > rampageTimer){ if(rampageCounter >= rampageInterval){ rampageVector.x = self.position.x-CGFloat(arc4random_uniform(1024)); rampageVector.y = self.position.y-CGFloat(arc4random_uniform(768)); var hypotonuse : CGFloat = sqrt((rampageVector.x * rampageVector.x) + (rampageVector.y * rampageVector.y)); rampageVector.x = (rampageVector.x / hypotonuse); rampageVector.y = (rampageVector.y / hypotonuse); rampageVector.x *= CGFloat(arc4random())%2 == 0 ? -1 : 1; rampageVector.y *= CGFloat(arc4random())%2 == 0 ? -1 : 1; rampageVector.x *= rampageSpeed; rampageVector.y *= rampageSpeed; rampageCounter = 0.0; zRotation = -zRotation; } self.position.x += rampageVector.x; self.position.y += rampageVector.y; warn.setPostion(self.position) rampageTimer += 0.1; rampageCounter += 0.1; warn.alpha = (rampageTimer/rampageTime) } else{ //position.x += speed*5; switchToMadCow() isCharging = true //mooPlayer.prepareToPlay() mooPlayer.play() //soundPlayer.prepareToPlay() soundPlayer.volume = 0.3 soundPlayer.play() if(!lockOnPlayer) { direction = CGPoint(x: playerPos.x - position.x, y: playerPos.y - position.y) var temp : CGPoint = CGPoint(x: 0, y: 0) temp.x = direction.x - self.position.x //temp.y = self.position.y - direction.y if(direction.x < 0) { self.texture = SKTexture(imageNamed: "redcow_horizontal_Left.png") } else if(direction.x >= 0) { self.texture = SKTexture(imageNamed: "redcow_horizontal_Right.png") } if(direction.x > -20 && direction.x < 20 && direction.y > 0) { self.texture = SKTexture(imageNamed: "Cow BUtt.png") } //self.texture = SKTexture(imageNamed: "Cow BUtt.png") lockOnPlayer = true } let mag = sqrt(direction.x ** 2 + direction.y ** 2 ) let normalizedDirection = CGPoint(x: direction.x / mag, y: direction.y / mag) if (mag < cowSpeed) { self.position = playerPos } else { self.position.x += normalizedDirection.x * cowSpeed self.position.y += normalizedDirection.y * cowSpeed } if (position.x > 1200 || position.x < -100 || position.y > 900 || position.y < -100) { removeCow = true } } zPosition = -position.y; } func setPlayerPos(pos : CGPoint) { playerPos = pos; } func setDeadCategory() { physicsBody?.contactTestBitMask = deadCategory physicsBody?.categoryBitMask = madBullCategory } }
1f1b1e103956b7b03fd881aad7eb9d0c
31.048193
123
0.526758
false
false
false
false
apple/swift-experimental-string-processing
refs/heads/main
Sources/_StringProcessing/Executor.swift
apache-2.0
1
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2021-2022 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // //===----------------------------------------------------------------------===// @_implementationOnly import _RegexParser struct Executor { // TODO: consider let, for now lets us toggle tracing var engine: Engine init(program: MEProgram) { self.engine = Engine(program) } @available(SwiftStdlib 5.7, *) func firstMatch<Output>( _ input: String, subjectBounds: Range<String.Index>, searchBounds: Range<String.Index>, graphemeSemantic: Bool ) throws -> Regex<Output>.Match? { var cpu = engine.makeFirstMatchProcessor( input: input, subjectBounds: subjectBounds, searchBounds: searchBounds) #if PROCESSOR_MEASUREMENTS_ENABLED defer { if cpu.shouldMeasureMetrics { cpu.printMetrics() } } #endif var low = searchBounds.lowerBound let high = searchBounds.upperBound while true { if let m: Regex<Output>.Match = try _match( input, from: low, using: &cpu ) { return m } if low >= high { return nil } if graphemeSemantic { input.formIndex(after: &low) } else { input.unicodeScalars.formIndex(after: &low) } cpu.reset(currentPosition: low) } } @available(SwiftStdlib 5.7, *) func match<Output>( _ input: String, in subjectBounds: Range<String.Index>, _ mode: MatchMode ) throws -> Regex<Output>.Match? { var cpu = engine.makeProcessor( input: input, bounds: subjectBounds, matchMode: mode) #if PROCESSOR_MEASUREMENTS_ENABLED defer { if cpu.shouldMeasureMetrics { cpu.printMetrics() } } #endif return try _match(input, from: subjectBounds.lowerBound, using: &cpu) } @available(SwiftStdlib 5.7, *) func _match<Output>( _ input: String, from currentPosition: String.Index, using cpu: inout Processor ) throws -> Regex<Output>.Match? { // FIXME: currentPosition is already encapsulated in cpu, don't pass in // FIXME: cpu.consume() should return the matched range, not the upper bound guard let endIdx = cpu.consume() else { if let e = cpu.failureReason { throw e } return nil } let capList = MECaptureList( values: cpu.storedCaptures, referencedCaptureOffsets: engine.program.referencedCaptureOffsets) let range = currentPosition..<endIdx let caps = engine.program.captureList.createElements(capList) let anyRegexOutput = AnyRegexOutput(input: input, elements: caps) return .init(anyRegexOutput: anyRegexOutput, range: range) } @available(SwiftStdlib 5.7, *) func dynamicMatch( _ input: String, in subjectBounds: Range<String.Index>, _ mode: MatchMode ) throws -> Regex<AnyRegexOutput>.Match? { try match(input, in: subjectBounds, mode) } }
650c108e082dcd9401fe34fad47f0322
29.470588
80
0.638674
false
false
false
false
simplepanda/SimpleSQL
refs/heads/master
Sources/SSConnectionEncoding.swift
apache-2.0
1
// // Part of SimpleSQL // https://github.com/simplepanda/SimpleSQL // // Created by Dylan Neild - July 2016 // [email protected] // // 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 MySQL extension SSConnection { // Get information about the server we're connected to. // public func getCharacterSet() -> SSCharacterEncoding { return SSUtils.translateCharacterString(chars: mysql_character_set_name(mysql)) } /** Get a string in the connection centric character set, as a Data object. - Parameters: - from: The string to encode into data. - Returns: A Data object, representing the original string as encoded data. */ public func stringToConnectionEncoding(_ from: String) -> Data? { return from.data(using: getCharacterSet().getPlatformEncoding(), allowLossyConversion: false) } /** SQL Escape a String using the current connection character encoding - Parameters: - from: The String to escape - Returns: The String, escaped and encoded into the connecton character encoding. */ public func escapeString(_ from: String) -> String? { guard let encoded = stringToConnectionEncoding(from) else { return nil } let sourceLength = encoded.count let targetLength = (sourceLength * 2) + 1 let buffer : UnsafeMutablePointer<Int8> = UnsafeMutablePointer<Int8>.allocate(capacity: targetLength) let conversionSize = encoded.withUnsafeBytes { (ptr: UnsafePointer<Int8>) -> UInt in return mysql_real_escape_string(mysql, buffer, ptr, UInt(sourceLength)) } guard conversionSize >= 0 else { return nil } let r = SSUtils.encodingDataToString(chars: buffer, characterSet: getCharacterSet()) buffer.deallocate(capacity: targetLength) return r } }
db7520e81efed20bffb25312bd2d643f
32.220779
109
0.648944
false
false
false
false
phelgo/Vectors
refs/heads/master
Vectors/Vector3D.swift
mit
1
// Vector structs for Swift // Copyright (c) 2015 phelgo. MIT licensed. import SceneKit public struct Vector3D: CustomDebugStringConvertible, CustomStringConvertible, Equatable, Hashable { public let x: Double public let y: Double public let z: Double public init(_ x: Double, _ y: Double, _ z: Double) { self.x = x self.y = y self.z = z } public var magnitude: Double { return sqrt(x * x + y * y + z * z) } public var squaredMagnitude: Double { return x * x + y * y + z * z } public var normalized: Vector3D { return Vector3D(x / magnitude, y / magnitude, z / magnitude) } public var description: String { return "Vector3D(\(x), \(y), \(z))" } public var debugDescription: String { return "Vector3D(\(x), \(y), \(z)), magnitude: \(magnitude)" } public var hashValue: Int { return x.hashValue ^ y.hashValue ^ z.hashValue } public static let zero = Vector3D(0, 0, 0) public static let one = Vector3D(1, 1, 1) public static let left = Vector3D(-1, 0, 0) public static let right = Vector3D(1, 0, 0) public static let up = Vector3D(0, 1, 0) public static let down = Vector3D(0, -1, 0) public static let forward = Vector3D(0, 0, 1) public static let back = Vector3D(0, 0, -1) } public func == (left: Vector3D, right: Vector3D) -> Bool { return (left.x == right.x) && (left.y == right.y) && (left.z == right.z) } public func + (left: Vector3D, right: Vector3D) -> Vector3D { return Vector3D(left.x + right.x, left.y + right.y, left.z + right.z) } public func - (left: Vector3D, right: Vector3D) -> Vector3D { return Vector3D(left.x - right.x, left.y - right.y, left.z - right.z) } public func += (inout left: Vector3D, right: Vector3D) { left = left + right } public func -= (inout left: Vector3D, right: Vector3D) { left = left - right } public func * (value: Double, vector: Vector3D) -> Vector3D { return Vector3D(value * vector.x, value * vector.y, value * vector.z) } public func * (vector: Vector3D, value: Double) -> Vector3D { return value * vector } public prefix func - (vector: Vector3D) -> Vector3D { return Vector3D(-vector.x, -vector.y, -vector.z) } public func dotProduct(vectorA: Vector3D, vectorB:Vector3D) -> Double { return vectorA.x * vectorB.x + vectorA.y * vectorB.y + vectorA.z * vectorB.z } infix operator -* { associativity left } public func -*(left: Vector3D, right:Vector3D) -> Double { return dotProduct(left, vectorB: right) } public func crossProduct(vectorA: Vector3D, vectorB:Vector3D) -> Vector3D { return Vector3D(vectorA.y * vectorB.z - vectorA.z * vectorB.y, vectorA.z * vectorB.x - vectorA.x * vectorB.z, vectorA.x * vectorB.y - vectorA.y * vectorB.x) } infix operator +* { associativity left } public func +*(left: Vector3D, right: Vector3D) -> Vector3D { return crossProduct(left, vectorB: right) } public extension SCNVector3 { init (_ value: Vector3D) { self.init(x: Float(value.x), y: Float(value.y), z: Float(value.z)) } } public prefix func ~ (vector: Vector3D) -> SCNVector3 { return SCNVector3(vector) }
90ef9bc0ac0827133eff497ca27c7596
28.216216
160
0.629047
false
false
false
false
RamonGilabert/RamonGilabert
refs/heads/master
RamonGilabert/RamonGilabert/RGVideoViewController.swift
mit
1
import AVFoundation import MediaPlayer import UIKit class RGVideoViewController: UIViewController { let session = AVAudioSession() let transitionManager = CustomVideoTransition() var moviePlayerController = MPMoviePlayerController() // MARK: View lifecycle override func viewDidLoad() { super.viewDidLoad() self.transitioningDelegate = self.transitionManager self.moviePlayerController = MPMoviePlayerController(contentURL: Video.MainVideoURL) self.moviePlayerController.view.frame = CGRectMake(0, 0, Constant.Size.DeviceWidth, Constant.Size.DeviceHeight) self.view.addSubview(self.moviePlayerController.view) configureMoviePlayer() addObserverToMoviePlayer() crossButtonLayout() self.session.setCategory(AVAudioSessionCategoryPlayback, error: nil) self.moviePlayerController.play() } // MARK: Notification methods func moviePlayerDidFinishPlaying(notification: NSNotification) { self.session.setCategory(AVAudioSessionCategorySoloAmbient, error: nil) self.dismissViewControllerAnimated(true, completion: { () -> Void in NSNotificationCenter.defaultCenter().postNotificationName(Constant.Setup.NameOfNotification, object: nil) }) } // MARK: UIButton handler func onCrossButtonPressed() { self.moviePlayerController.pause() self.session.setCategory(AVAudioSessionCategorySoloAmbient, error: nil) self.dismissViewControllerAnimated(true, completion: { () -> Void in self.moviePlayerController.stop() NSNotificationCenter.defaultCenter().postNotificationName(Constant.Setup.NameOfNotification, object: nil) }) } // MARK: MoviePlayer configuration func crossButtonLayout() { let crossButton = UIButton(frame: CGRectMake(20, 20, 28, 28)) crossButton.addTarget(self, action: "onCrossButtonPressed", forControlEvents: UIControlEvents.TouchUpInside) crossButton.setBackgroundImage(UIImage(named: "cross-button-shadow"), forState: UIControlState.Normal) self.view.addSubview(crossButton) } func configureMoviePlayer() { self.moviePlayerController.scalingMode = MPMovieScalingMode.AspectFill self.moviePlayerController.controlStyle = MPMovieControlStyle.None self.moviePlayerController.backgroundView.backgroundColor = UIColor_WWDC.backgroundDarkGrayColor() self.moviePlayerController.repeatMode = MPMovieRepeatMode.None self.moviePlayerController.allowsAirPlay = true self.moviePlayerController.prepareToPlay() } func addObserverToMoviePlayer() { NSNotificationCenter.defaultCenter().addObserver(self, selector: "moviePlayerDidFinishPlaying:" , name: MPMoviePlayerPlaybackDidFinishNotification, object: self.moviePlayerController) } }
3cc410a1af392d05fe32d31ef0d497dd
39.535211
191
0.740097
false
false
false
false
whiteshadow-gr/HatForIOS
refs/heads/master
HAT/Objects/Notes/HATNotesData.swift
mpl-2.0
1
/** * Copyright (C) 2018 HAT Data Exchange Ltd * * SPDX-License-Identifier: MPL2 * * This file is part of the Hub of All Things project (HAT). * * 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 SwiftyJSON // MARK: Struct public struct HATNotesData: HATObject, HatApiType { // MARK: - Coding Keys /** The JSON fields used by the hat The Fields are the following: * `authorV1` in JSON is `authorv1` * `photoV1` in JSON is `photov1` * `locationV1` in JSON is `locationv1` * `createdTime` in JSON is `created_time` * `publicUntil` in JSON is `public_until` * `updatedTime` in JSON is `updated_time` * `isShared` in JSON is `shared` * `isCurrentlyShared` in JSON is `currently_shared` * `sharedOn` in JSON is `sharedOn` * `message` in JSON is `message` * `kind` in JSON is `kind` */ private enum CodingKeys: String, CodingKey { case authorV1 = "authorv1" case photoV1 = "photov1" case locationV1 = "locationv1" case createdTime = "created_time" case publicUntil = "public_until" case updatedTime = "updated_time" case isShared = "shared" case isCurrentlyShared = "currently_shared" case sharedOn = "shared_on" case message = "message" case kind = "kind" } // MARK: - Variables /// the author data public var authorV1: HATNotesAuthor = HATNotesAuthor() /// the photo data. Optional public var photoV1: HATNotesPhoto? /// the location data. Optional public var locationV1: HATNotesLocation? /// creation date public var createdTime: String = "" /// the date until this note will be public. Optional public var publicUntil: String? /// the updated time of the note public var updatedTime: String = "" /// if true this note is shared to facebook etc. public var isShared: Bool = false /// if true this note is shared to facebook etc. public var isCurrentlyShared: Bool = false /// If shared, where is it shared? Coma seperated string (don't know if it's optional or not) public var sharedOn: [String] = [] /// the actual message of the note public var message: String = "" /// the kind of the note. 3 types available note, blog or list public var kind: String = "" // MARK: - Initialiser /** The default initialiser. Initialises everything to default values. */ public init() { } /** It initialises everything from the received JSON file from the HAT - dict: The JSON file received from the HAT */ public init(dict: Dictionary<String, JSON>) { self.init() self.inititialize(dict: dict) } /** It initialises everything from the received JSON file from the HAT */ public mutating func inititialize(dict: Dictionary<String, JSON>) { let tempDict: Dictionary<String, JSON> if let temp: [String: JSON] = dict["notablesv1"]?.dictionaryValue { tempDict = temp } else { tempDict = dict } if let tempAuthorData: [String: JSON] = tempDict[CodingKeys.authorV1.rawValue]?.dictionary { authorV1 = HATNotesAuthor.init(dict: tempAuthorData) } if let tempPhotoData: [String: JSON] = tempDict[CodingKeys.photoV1.rawValue]?.dictionary { photoV1 = HATNotesPhoto.init(dict: tempPhotoData) } if let tempLocationData: [String: JSON] = tempDict[CodingKeys.locationV1.rawValue]?.dictionary { locationV1 = HATNotesLocation.init(dict: tempLocationData) } if let tempSharedOn: [JSON] = tempDict[CodingKeys.sharedOn.rawValue]?.arrayValue { for item: JSON in tempSharedOn { sharedOn.append(item.stringValue) } } if let tempPublicUntil: String = tempDict[CodingKeys.publicUntil.rawValue]?.string { publicUntil = tempPublicUntil } if let tempCreatedTime: String = tempDict[CodingKeys.createdTime.rawValue]?.string { createdTime = tempCreatedTime } if let tempUpdatedTime: String = tempDict[CodingKeys.updatedTime.rawValue]?.string { updatedTime = tempUpdatedTime } if let tempShared: Bool = tempDict[CodingKeys.isShared.rawValue]?.boolValue { isShared = tempShared } if let tempCurrentlyShared: Bool = tempDict[CodingKeys.isCurrentlyShared.rawValue]?.boolValue { isCurrentlyShared = tempCurrentlyShared } if let tempMessage: String = tempDict[CodingKeys.message.rawValue]?.string { message = tempMessage } if let tempKind: String = tempDict[CodingKeys.kind.rawValue]?.string { kind = tempKind } } // MARK: - HatApiType Protocol /** Returns the object as Dictionary, JSON - returns: Dictionary<String, String> */ public func toJSON() -> Dictionary<String, Any> { return [ CodingKeys.authorV1.rawValue: authorV1.toJSON(), CodingKeys.photoV1.rawValue: photoV1?.toJSON() ?? HATNotesPhoto().toJSON(), CodingKeys.locationV1.rawValue: locationV1?.toJSON() ?? HATNotesLocation().toJSON(), CodingKeys.createdTime.rawValue: createdTime, CodingKeys.publicUntil.rawValue: publicUntil ?? "", CodingKeys.updatedTime.rawValue: updatedTime, CodingKeys.isShared.rawValue: isShared, CodingKeys.isCurrentlyShared.rawValue: isCurrentlyShared, CodingKeys.sharedOn.rawValue: sharedOn, CodingKeys.message.rawValue: message, CodingKeys.kind.rawValue: kind ] } /** It initialises everything from the received Dictionary file from the cache - fromCache: The dictionary file received from the cache */ public mutating func initialize(fromCache: Dictionary<String, Any>) { let dictionary: JSON = JSON(fromCache) self.inititialize(dict: dictionary.dictionaryValue) } }
de13919bfa15eb87813af7bbd2521b50
31.009569
104
0.596562
false
false
false
false