repo_name
stringlengths
7
91
path
stringlengths
8
658
copies
stringclasses
125 values
size
stringlengths
3
6
content
stringlengths
118
674k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6.09
99.2
line_max
int64
17
995
alpha_frac
float64
0.3
0.9
ratio
float64
2
9.18
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
Aishwarya-Ramakrishnan/sparkios
Source/Phone/Call/CallClient.swift
1
5568
// Copyright 2016 Cisco Systems Inc // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation // TODO: need to discuss if use term - "locus" class CallClient: CompletionHandlerType<CallInfo>{ private func requestBuilder() -> ServiceRequest.Builder { return ServiceRequest.Builder().keyPath("locus") } func join(_ localInfo: RequestParameter, queue: DispatchQueue? = nil, completionHandler: @escaping ObjectHandler) { let request = requestBuilder() .method(.post) .baseUrl(DeviceService.sharedInstance.getServiceUrl("locus")!) .body(localInfo) .path("loci/call") .queue(queue) .build() request.responseObject(completionHandler) } func join(_ callUrl: String, localInfo: RequestParameter, queue: DispatchQueue? = nil, completionHandler: @escaping ObjectHandler) { let request = requestBuilder() .method(.post) .body(localInfo) .path("participant") .baseUrl(callUrl) .queue(queue) .build() request.responseObject(completionHandler) } func leave(_ participantUrl: String, deviceUrl: String, queue: DispatchQueue? = nil, completionHandler: @escaping ObjectHandler) { let request = requestBuilder() .method(.put) .baseUrl(participantUrl) .path("leave") .body(RequestParameter(["deviceUrl": deviceUrl])) .queue(queue) .build() request.responseObject(completionHandler) } func decline(_ callUrl: String, deviceUrl: String, queue: DispatchQueue? = nil, completionHandler: @escaping AnyHandler) { let request = requestBuilder() .method(.put) .baseUrl(callUrl) .body(RequestParameter(["deviceUrl": deviceUrl])) .path("participant/decline") .queue(queue) .build() request.responseJSON(completionHandler) } func alert(_ participantUrl: String, deviceUrl: String, queue: DispatchQueue? = nil, completionHandler: @escaping AnyHandler) { let request = requestBuilder() .method(.put) .baseUrl(participantUrl) .body(RequestParameter(["deviceUrl": deviceUrl])) .path("alert") .queue(queue) .build() request.responseJSON(completionHandler) } func sendDtmf(_ participantUrl: String, deviceUrl: String, correlationId: Int, events: String, volume: Int? = nil, durationMillis: Int? = nil, queue: DispatchQueue? = nil, completionHandler: @escaping AnyHandler) { var dtmfInfo: [String:Any] = [ "tones": events, "correlationId": correlationId] if volume != nil { dtmfInfo["volume"] = volume } if durationMillis != nil { dtmfInfo["durationMillis"] = durationMillis } let body:[String: Any] = [ "deviceUrl": deviceUrl, "dtmf": dtmfInfo] let request = requestBuilder() .method(.post) .baseUrl(participantUrl) .body(RequestParameter(body)) .path("sendDtmf") .queue(queue) .build() request.responseJSON(completionHandler) } func updateMedia(_ mediaUrl: String, localInfo: RequestParameter, queue: DispatchQueue? = nil, completionHandler: @escaping ObjectHandler) { let request = requestBuilder() .method(.put) .baseUrl(mediaUrl) .body(localInfo) .queue(queue) .build() request.responseObject(completionHandler) } func fetchCallInfo(_ callUrl: String, queue: DispatchQueue? = nil, completionHandler: @escaping ObjectHandler) { let request = requestBuilder() .method(.get) .baseUrl(callUrl) .queue(queue) .build() request.responseObject(completionHandler) } func fetchCallInfos(_ queue: DispatchQueue? = nil, completionHandler: @escaping ArrayHandler) { let request = requestBuilder() .method(.get) .baseUrl(DeviceService.sharedInstance.getServiceUrl("locus")!) .path("loci") .keyPath("loci") .queue(queue) .build() request.responseArray(completionHandler) } }
mit
8ad730ea710d3401a45bfc7f44f05797
36.877551
218
0.614943
4.888499
false
false
false
false
svachmic/ios-url-remote
URLRemote/Classes/View/Stylesheet.swift
1
2239
// // Stylesheet.swift // URLRemote // // Created by Michal Švácha on 21/01/2018. // Copyright © 2018 Svacha, Michal. All rights reserved. // import UIKit import Material /// Application stylesheet with style definitions. enum Stylesheet { /// General components enum General { /// Any generic flat button static let flatButton = Style<FlatButton> { $0.titleColor = .white $0.pulseColor = .white $0.titleLabel?.font = RobotoFont.bold(with: 15) } } /// Login screen components enum Login { /// Background table view static let tableView = Style<UITableView> { $0.backgroundColor = UIColor(named: .gray) $0.tableFooterView = UIView(frame: .zero) $0.alwaysBounceVertical = false $0.alwaysBounceHorizontal = false $0.separatorStyle = .none } /// Any TextField used for user input. static let textField = Style<TextField> { $0.font = RobotoFont.regular(with: 15) $0.leftViewMode = .always $0.placeholderActiveColor = UIColor(named: .green).darker() $0.dividerActiveColor = UIColor(named: .green).darker() $0.leftViewActiveColor = UIColor(named: .green).darker() $0.isClearIconButtonEnabled = true $0.detailColor = UIColor(named: .red) } } /// Actions Screen enum Actions { /// Floating button static let fabButton = Style<FABButton> { $0.tintColor = .white $0.pulseColor = .white $0.backgroundColor = Color.grey.base } } /// Entry setup form components enum EntrySetup { /// Any TextField used for user input. static let textField = Style<TextField> { $0.autocorrectionType = .no $0.font = RobotoFont.regular(with: 13) $0.placeholderActiveColor = UIColor(named: .green).darker() $0.dividerActiveColor = UIColor(named: .green).darker() $0.isClearIconButtonEnabled = true $0.detailColor = UIColor(named: .red) } } }
apache-2.0
bf78ad72907614ba12be1f07f6985cc5
29.216216
71
0.563506
4.591376
false
false
false
false
austinzheng/swift
test/NameBinding/Dependencies/private-function.swift
13
867
// RUN: %target-swift-frontend -emit-silgen -primary-file %s %S/Inputs/InterestingType.swift -DOLD -emit-reference-dependencies-path %t.swiftdeps -module-name main | %FileCheck %s -check-prefix=CHECK-OLD // RUN: %FileCheck -check-prefix=CHECK-DEPS %s < %t.swiftdeps // RUN: %target-swift-frontend -emit-silgen -primary-file %s %S/Inputs/InterestingType.swift -DNEW -emit-reference-dependencies-path %t.swiftdeps -module-name main | %FileCheck %s -check-prefix=CHECK-NEW // RUN: %FileCheck -check-prefix=CHECK-DEPS %s < %t.swiftdeps private func testParamType(_: InterestingType) {} // CHECK-OLD: sil_global hidden @$s4main1x{{[^ ]+}} : ${{(@[a-zA-Z_]+ )?}}(Int) -> () // CHECK-NEW: sil_global hidden @$s4main1x{{[^ ]+}} : ${{(@[a-zA-Z_]+ )?}}(Double) -> () internal var x = testParamType // CHECK-DEPS-LABEL: depends-top-level: // CHECK-DEPS: - "InterestingType"
apache-2.0
87bdde128946d2f54375b8e3d4d6644e
60.928571
203
0.687428
3.074468
false
true
false
false
kreshikhin/scituner
SciTuner/Views/PointerView.swift
1
686
// // PointerView.swift // SciTuner // // Created by Denis Kreshikhin on 27.02.15. // Copyright (c) 2015 Denis Kreshikhin. All rights reserved. // import Foundation import UIKit import CoreGraphics class PointerView: UIView{ required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override init(frame: CGRect) { super.init(frame: frame) backgroundColor = .clear layer.borderColor = UIColor.white.cgColor layer.cornerRadius = frame.height / 2 layer.masksToBounds = true layer.borderWidth = 2 layer.borderColor = UIColor.white.cgColor } }
mit
c035d51b344dd1dfc34e114287972b0c
22.655172
61
0.642857
4.341772
false
false
false
false
aleffert/dials
Desktop/Source/PluginController.swift
1
3549
// // PluginController.swift // Dials-Desktop // // Created by Akiva Leffert on 12/6/14. // // import Cocoa private let PluginPathExtension = "dialsplugin" protocol ConstraintInfoSource : class { var constraintSources : [ConstraintPlugin] { get } } protocol ConstraintInfoOwner : class { weak var constraintInfoSource : ConstraintInfoSource? { get set } } class PluginController: NSObject, ConstraintInfoSource { fileprivate var plugins : [Plugin] = [] fileprivate let codeManager = CodeManager() override init() { super.init() self.registerDefaultPlugins() self.registerBundlePlugins() self.registerAdjacentPlugins() } var constraintSources : [ConstraintPlugin] { return self.plugins.flatMap { return $0 as? ConstraintPlugin } } fileprivate func registerDefaultPlugins() { registerPlugin(ControlPanelPlugin()) registerPlugin(ViewsPlugin()) registerPlugin(NetworkRequestsPlugin()) } fileprivate func registerPluginsFromURLs(_ urls : [URL]) { for url in urls { let fileName = url.lastPathComponent if let bundle = Bundle(url: url), let loaded = bundle.load() as Bool?, loaded { print("Loaded plugin named: \(fileName)") if let pluginClass = bundle.principalClass as? NSObject.Type, let plugin = pluginClass.init() as? Plugin { registerPlugin(plugin) print("Registered plugin class: \(pluginClass)") if let owner = plugin as? CodeHelperOwner { owner.codeHelper = codeManager } } } else { print("Failed to load plugin: \(url.lastPathComponent)") } } } fileprivate func registerBundlePlugins() { let urls = Bundle.main.urls(forResourcesWithExtension: PluginPathExtension, subdirectory: "PlugIns") ?? [] registerPluginsFromURLs(urls) } // We also pick up any plugins side by side with the app so that build products // are easy to pick up fileprivate func registerAdjacentPlugins() { let bundleURL = Bundle.main.bundleURL let searchURL = bundleURL.deletingLastPathComponent() if let adjacentPaths = FileManager.default.enumerator(at: searchURL, includingPropertiesForKeys: nil, options: [], errorHandler: nil) { let urls = adjacentPaths.filter { ($0 as! URL).pathExtension == PluginPathExtension } as? [URL] ?? [] registerPluginsFromURLs(urls) } } fileprivate func registerPlugin(_ plugin : Plugin) { plugins.append(plugin) } fileprivate func pluginWithIdentifier(_ identifier : String) -> Plugin? { for possible in plugins { if possible.identifier == identifier { return possible } } return nil } func routeMessage(_ data : Data, channel : DLSChannel) { let plugin = pluginWithIdentifier(channel.name) plugin?.receiveMessage(data) } func connectionClosed() { for plugin in plugins { plugin.connectionClosed() } } func connectedWithContext(_ context : PluginContext) { for plugin in plugins { plugin.connected(with: context) } } }
mit
8619b80a6b95f8de4f467902e7623d26
29.86087
143
0.590589
5.136035
false
false
false
false
dclelland/AudioKit
AudioKit/iOS/AudioKit/AudioKit.playground/Pages/Tanh Distortion.xcplaygroundpage/Contents.swift
1
3643
//: [TOC](Table%20Of%20Contents) | [Previous](@previous) | [Next](@next) //: //: --- //: //: ## Tanh Distortion //: ## //: import XCPlayground import AudioKit let bundle = NSBundle.mainBundle() let file = bundle.pathForResource("guitarloop", ofType: "wav") var player = AKAudioPlayer(file!) player.looping = true var distortion = AKTanhDistortion(player) //: Set the parameters here distortion.pregain = 1.0 distortion.postgain = 1.0 distortion.postiveShapeParameter = 1.0 distortion.negativeShapeParameter = 1.0 AudioKit.output = distortion AudioKit.start() player.play() //: User Interface Set up class PlaygroundView: AKPlaygroundView { //: UI Elements we'll need to be able to access var pregainLabel: Label? var postgainLabel: Label? var postiveShapeParameterLabel: Label? var negativeShapeParameterLabel: Label? override func setup() { addTitle("Tanh Distortion") addLabel("Audio Player") addButton("Start", action: #selector(start)) addButton("Stop", action: #selector(stop)) addLabel("Distortion Parameters") addButton("Process", action: #selector(process)) addButton("Bypass", action: #selector(bypass)) pregainLabel = addLabel("Pregain: \(distortion.pregain) Hz") addSlider(#selector(setPregain), value: distortion.pregain, minimum: 0, maximum: 10) postgainLabel = addLabel("Postgain: \(distortion.postgain) Hz") addSlider(#selector(setPostgain), value: distortion.postgain, minimum: 0, maximum: 10) postiveShapeParameterLabel = addLabel("Postive Shape Parameter: \(distortion.postiveShapeParameter)") addSlider(#selector(setPositiveShapeParameter), value: distortion.postiveShapeParameter, minimum: -10, maximum: 10) negativeShapeParameterLabel = addLabel("Negative Shape Parameter: \(distortion.negativeShapeParameter)") addSlider(#selector(setNegativeShapeParameter), value: distortion.negativeShapeParameter, minimum: -10, maximum: 10) } //: Handle UI Events func start() { player.play() } func stop() { player.stop() } func process() { distortion.start() } func bypass() { distortion.bypass() } func setPregain(slider: Slider) { distortion.pregain = Double(slider.value) let pregain = String(format: "%0.2f", distortion.pregain) pregainLabel!.text = "Pregain: \(pregain) Hz" } func setPostgain(slider: Slider) { distortion.postgain = Double(slider.value) let postgain = String(format: "%0.2f", distortion.postgain) postgainLabel!.text = "Postgain: \(postgain) Hz" } func setPositiveShapeParameter(slider: Slider) { distortion.postiveShapeParameter = Double(slider.value) let postiveShapeParameter = String(format: "%0.2f", distortion.postiveShapeParameter) postiveShapeParameterLabel!.text = "Positive Shape Parameter: \(postiveShapeParameter)" } func setNegativeShapeParameter(slider: Slider) { distortion.negativeShapeParameter = Double(slider.value) let negativeShapeParameter = String(format: "%0.2f", distortion.negativeShapeParameter) negativeShapeParameterLabel!.text = "Negative Shape Parameter: \(negativeShapeParameter)" } } let view = PlaygroundView(frame: CGRect(x: 0, y: 0, width: 500, height: 550)) XCPlaygroundPage.currentPage.needsIndefiniteExecution = true XCPlaygroundPage.currentPage.liveView = view //: [TOC](Table%20Of%20Contents) | [Previous](@previous) | [Next](@next)
mit
78db1304ba473f35b255b269c34a6132
31.526786
124
0.678836
4.206697
false
false
false
false
jovito-royeca/Cineko
Cineko/TVSeason.swift
1
1847
// // TVSeason.swift // Cineko // // Created by Jovit Royeca on 06/04/2016. // Copyright © 2016 Jovito Royeca. All rights reserved. // import Foundation import CoreData class TVSeason: NSManagedObject { struct Keys { static let AirDate = "air_date" static let EpisodeCount = "episode_count" static let Name = "name" static let Overview = "overview" static let PosterPath = "poster_path" static let SeasonNumber = "season_number" static let TVSeasonID = "id" } override init(entity: NSEntityDescription, insertIntoManagedObjectContext context: NSManagedObjectContext?) { super.init(entity: entity, insertIntoManagedObjectContext: context) } init(dictionary: [String : AnyObject], context: NSManagedObjectContext) { let entity = NSEntityDescription.entityForName("TVSeason", inManagedObjectContext: context)! super.init(entity: entity,insertIntoManagedObjectContext: context) update(dictionary) } func update(dictionary: [String : AnyObject]) { airDate = dictionary[Keys.AirDate] as? String episodeCount = dictionary[Keys.EpisodeCount] as? NSNumber name = dictionary[Keys.Name] as? String overview = dictionary[Keys.Overview] as? String posterPath = dictionary[Keys.PosterPath] as? String seasonNumber = dictionary[Keys.SeasonNumber] as? NSNumber tvSeasonID = dictionary[Keys.TVSeasonID] as? NSNumber } } extension TVSeason : ThumbnailDisplayable { func imagePath(displayType: DisplayType) -> String? { return posterPath } func caption(captionType: CaptionType) -> String? { if let seasonNumber = seasonNumber { return "Season \(seasonNumber.integerValue)" } return nil } }
apache-2.0
221188dd528da6a0afdd7918210c12a8
31.385965
113
0.667389
4.626566
false
false
false
false
itsaboutcode/WordPress-iOS
WordPress/Classes/Services/AccountSettingsService.swift
1
10341
import Foundation import CocoaLumberjack import Reachability import WordPressKit extension NSNotification.Name { static let AccountSettingsServiceChangeSaveFailed = NSNotification.Name(rawValue: "AccountSettingsServiceChangeSaveFailed") static let AccountSettingsChanged = NSNotification.Name(rawValue: "AccountSettingsServiceSettingsChanged") static let AccountSettingsServiceRefreshStatusChanged = NSNotification.Name(rawValue: "AccountSettingsServiceRefreshStatusChanged") } @objc extension NSNotification { public static let AccountSettingsChanged = NSNotification.Name.AccountSettingsChanged } protocol AccountSettingsRemoteInterface { func getSettings(success: @escaping (AccountSettings) -> Void, failure: @escaping (Error) -> Void) func updateSetting(_ change: AccountSettingsChange, success: @escaping () -> Void, failure: @escaping (Error) -> Void) func changeUsername(to username: String, success: @escaping () -> Void, failure: @escaping () -> Void) func suggestUsernames(base: String, finished: @escaping ([String]) -> Void) func updatePassword(_ password: String, success: @escaping () -> Void, failure: @escaping (Error) -> Void) func closeAccount(success: @escaping () -> Void, failure: @escaping (Error) -> Void) } extension AccountSettingsRemote: AccountSettingsRemoteInterface {} class AccountSettingsService { struct Defaults { static let stallTimeout = 4.0 static let maxRetries = 3 static let pollingInterval = 60.0 } let remote: AccountSettingsRemoteInterface let userID: Int var status: RefreshStatus = .idle { didSet { stallTimer?.invalidate() stallTimer = nil NotificationCenter.default.post(name: NSNotification.Name.AccountSettingsServiceRefreshStatusChanged, object: nil) } } var settings: AccountSettings? = nil { didSet { NotificationCenter.default.post(name: NSNotification.Name.AccountSettingsChanged, object: nil) } } var stallTimer: Timer? fileprivate let context = ContextManager.sharedInstance().mainContext convenience init(userID: Int, api: WordPressComRestApi) { let remote = AccountSettingsRemote.remoteWithApi(api) self.init(userID: userID, remote: remote) } init(userID: Int, remote: AccountSettingsRemoteInterface) { self.userID = userID self.remote = remote loadSettings() } func getSettingsAttempt(count: Int = 0) { self.remote.getSettings( success: { settings in self.updateSettings(settings) self.status = .idle }, failure: { error in let error = error as NSError if error.domain == NSURLErrorDomain { DDLogError("Error refreshing settings (attempt \(count)): \(error)") } else { DDLogError("Error refreshing settings (unrecoverable): \(error)") } if error.domain == NSURLErrorDomain && count < Defaults.maxRetries { self.getSettingsAttempt(count: count + 1) } else { self.status = .failed } } ) } func refreshSettings() { guard status == .idle || status == .failed else { return } status = .refreshing getSettingsAttempt() stallTimer = Timer.scheduledTimer(timeInterval: Defaults.stallTimeout, target: self, selector: #selector(AccountSettingsService.stallTimerFired), userInfo: nil, repeats: false) } @objc func stallTimerFired() { guard status == .refreshing else { return } status = .stalled } func saveChange(_ change: AccountSettingsChange, finished: ((Bool) -> ())? = nil) { guard let reverse = try? applyChange(change) else { return } remote.updateSetting(change, success: { finished?(true) }) { (error) -> Void in do { // revert change try self.applyChange(reverse) } catch { DDLogError("Error reverting change \(error)") } DDLogError("Error saving account settings change \(error)") NotificationCenter.default.post(name: NSNotification.Name.AccountSettingsServiceChangeSaveFailed, object: self, userInfo: [NSUnderlyingErrorKey: error]) finished?(false) } } func updateDisplayName(_ displayName: String, finished: ((Bool, Error?) -> ())? = nil) { remote.updateSetting(.displayName(displayName), success: { finished?(true, nil) }) { error in DDLogError("Error saving account settings change \(error)") NotificationCenter.default.post(name: NSNotification.Name.AccountSettingsServiceChangeSaveFailed, object: self, userInfo: [NSUnderlyingErrorKey: error]) finished?(false, error) } } func updatePassword(_ password: String, finished: ((Bool, Error?) -> ())? = nil) { remote.updatePassword(password, success: { finished?(true, nil) }) { (error) -> Void in DDLogError("Error saving account settings change \(error)") NotificationCenter.default.post(name: NSNotification.Name.AccountSettingsServiceChangeSaveFailed, object: error as NSError) finished?(false, error) } } func closeAccount(result: @escaping (Result<Void, Error>) -> Void) { remote.closeAccount { result(.success(())) } failure: { error in result(.failure(error)) } } func primarySiteNameForSettings(_ settings: AccountSettings) -> String? { return try? Blog.lookup(withID: settings.primarySiteID, in: context)?.settings?.name } /// Change the current user's username /// /// - Parameters: /// - username: the new username /// - success: block for success /// - failure: block for failure public func changeUsername(to username: String, success: @escaping () -> Void, failure: @escaping () -> Void) { remote.changeUsername(to: username, success: success, failure: success) } public func suggestUsernames(base: String, finished: @escaping ([String]) -> Void) { remote.suggestUsernames(base: base, finished: finished) } fileprivate func loadSettings() { settings = accountSettingsWithID(self.userID) } @discardableResult fileprivate func applyChange(_ change: AccountSettingsChange) throws -> AccountSettingsChange { guard let settings = managedAccountSettingsWithID(userID) else { DDLogError("Tried to apply a change to nonexistent settings (ID: \(userID)") throw Errors.notFound } let reverse = settings.applyChange(change) settings.account.applyChange(change) ContextManager.sharedInstance().save(context) loadSettings() return reverse } fileprivate func updateSettings(_ settings: AccountSettings) { if let managedSettings = managedAccountSettingsWithID(userID) { managedSettings.updateWith(settings) } else { createAccountSettings(userID, settings: settings) } ContextManager.sharedInstance().save(context) loadSettings() } fileprivate func accountSettingsWithID(_ userID: Int) -> AccountSettings? { guard let managedAccount = managedAccountSettingsWithID(userID) else { return nil } return AccountSettings.init(managed: managedAccount) } fileprivate func managedAccountSettingsWithID(_ userID: Int) -> ManagedAccountSettings? { let request = NSFetchRequest<NSFetchRequestResult>(entityName: ManagedAccountSettings.entityName()) request.predicate = NSPredicate(format: "account.userID = %d", userID) request.fetchLimit = 1 guard let results = (try? context.fetch(request)) as? [ManagedAccountSettings] else { return nil } return results.first } fileprivate func createAccountSettings(_ userID: Int, settings: AccountSettings) { let accountService = AccountService(managedObjectContext: context) guard let account = accountService.findAccount(withUserID: NSNumber(value: userID)) else { DDLogError("Tried to create settings for a missing account (ID: \(userID)): \(settings)") return } if let managedSettings = NSEntityDescription.insertNewObject(forEntityName: ManagedAccountSettings.entityName(), into: context) as? ManagedAccountSettings { managedSettings.updateWith(settings) managedSettings.account = account } } enum Errors: Error { case notFound } enum RefreshStatus { case idle case refreshing case stalled case failed var errorMessage: String? { switch self { case .stalled: return NSLocalizedString("We are having trouble loading data", comment: "Error message displayed when a refresh is taking longer than usual. The refresh hasn't failed and it might still succeed") case .failed: return NSLocalizedString("We had trouble loading data", comment: "Error message displayed when a refresh failed") case .idle, .refreshing: return nil } } } } struct AccountSettingsHelper { let accountService: AccountService init(accountService: AccountService) { self.accountService = accountService } func updateTracksOptOutSetting(_ optOut: Bool) { guard let account = accountService.defaultWordPressComAccount() else { return } let change = AccountSettingsChange.tracksOptOut(optOut) AccountSettingsService(userID: account.userID.intValue, api: account.wordPressComRestApi).saveChange(change) } }
gpl-2.0
7121ec7d81b756b4fb99b7016c15b5e4
36.064516
211
0.629823
5.402821
false
false
false
false
Reality-Virtually-Hackathon/Team-2
WorkspaceAR/VirtualObjectInteraction.swift
1
8040
/* See LICENSE folder for this sample’s licensing information. Abstract: Coordinates movement and gesture interactions with virtual objects. */ import UIKit import ARKit /// - Tag: VirtualObjectInteraction class VirtualObjectInteraction: NSObject, UIGestureRecognizerDelegate { /// Developer setting to translate assuming the detected plane extends infinitely. let translateAssumingInfinitePlane = true /// The scene view to hit test against when moving virtual content. let sceneView: VirtualObjectARView /** The object that has been most recently intereacted with. The `selectedObject` can be moved at any time with the tap gesture. */ var selectedObject: VirtualObject? /// The object that is tracked for use by the pan and rotation gestures. private var trackedObject: VirtualObject? { didSet { guard trackedObject != nil else { return } selectedObject = trackedObject } } /// The tracked screen position used to update the `trackedObject`'s position in `updateObjectToCurrentTrackingPosition()`. private var currentTrackingPosition: CGPoint? init(sceneView: VirtualObjectARView) { self.sceneView = sceneView super.init() let panGesture = ThresholdPanGesture(target: self, action: #selector(didPan(_:))) panGesture.delegate = self let rotationGesture = UIRotationGestureRecognizer(target: self, action: #selector(didRotate(_:))) rotationGesture.delegate = self let tapGesture = UITapGestureRecognizer(target: self, action: #selector(didTap(_:))) // Add gestures to the `sceneView`. sceneView.addGestureRecognizer(panGesture) sceneView.addGestureRecognizer(rotationGesture) sceneView.addGestureRecognizer(tapGesture) } // MARK: - Gesture Actions @objc func didPan(_ gesture: ThresholdPanGesture) { switch gesture.state { case .began: // Check for interaction with a new object. if let object = objectInteracting(with: gesture, in: sceneView) { trackedObject = object } case .changed where gesture.isThresholdExceeded: guard let object = trackedObject else { return } let translation = gesture.translation(in: sceneView) let currentPosition = currentTrackingPosition ?? CGPoint(sceneView.projectPoint(object.position)) // The `currentTrackingPosition` is used to update the `selectedObject` in `updateObjectToCurrentTrackingPosition()`. currentTrackingPosition = CGPoint(x: currentPosition.x + translation.x, y: currentPosition.y + translation.y) gesture.setTranslation(.zero, in: sceneView) case .changed: // Ignore changes to the pan gesture until the threshold for displacment has been exceeded. break default: // Clear the current position tracking. currentTrackingPosition = nil trackedObject = nil } } /** If a drag gesture is in progress, update the tracked object's position by converting the 2D touch location on screen (`currentTrackingPosition`) to 3D world space. This method is called per frame (via `SCNSceneRendererDelegate` callbacks), allowing drag gestures to move virtual objects regardless of whether one drags a finger across the screen or moves the device through space. - Tag: updateObjectToCurrentTrackingPosition */ @objc func updateObjectToCurrentTrackingPosition() { guard let object = trackedObject, let position = currentTrackingPosition else { return } translate(object, basedOn: position, infinitePlane: translateAssumingInfinitePlane) } /// - Tag: didRotate @objc func didRotate(_ gesture: UIRotationGestureRecognizer) { guard gesture.state == .changed else { return } //MUST BE A CLIENT TO ROTATE let ut = DataManager.shared().userType guard ut == .Client else { return } //MUST BE A CLIENT IN PLANE-DETECTED MODE (alignment-state) let state = DataManager.shared().state guard state == .AlignmentStage else { return } /* - Note: For looking down on the object (99% of all use cases), we need to subtract the angle. To make rotation also work correctly when looking from below the object one would have to flip the sign of the angle depending on whether the object is above or below the camera... */ trackedObject?.eulerAngles.y -= Float(gesture.rotation) gesture.rotation = 0 } @objc func didTap(_ gesture: UITapGestureRecognizer) { let touchLocation = gesture.location(in: sceneView) if let tappedObject = sceneView.virtualObject(at: touchLocation) { // Select a new object. selectedObject = tappedObject } else if let object = selectedObject { // Teleport the object to whereever the user touched the screen. translate(object, basedOn: touchLocation, infinitePlane: false) } } func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool { // Allow objects to be translated and rotated at the same time. return true } /// A helper method to return the first object that is found under the provided `gesture`s touch locations. /// - Tag: TouchTesting private func objectInteracting(with gesture: UIGestureRecognizer, in view: ARSCNView) -> VirtualObject? { let ut = DataManager.shared().userType let state = DataManager.shared().state if (ut == .Client && state == .AlignmentStage) { return selectedObject //if it's a client in the alignment stage, //regardless of the tap, return the selectedObject, //which is 'vo', the virtual object holding the root node } for index in 0..<gesture.numberOfTouches { let touchLocation = gesture.location(ofTouch: index, in: view) // Look for an object directly under the `touchLocation`. if let object = sceneView.virtualObject(at: touchLocation) { return object } } // As a last resort look for an object under the center of the touches. return sceneView.virtualObject(at: gesture.center(in: view)) } // MARK: - Update object position /// - Tag: DragVirtualObject private func translate(_ object: VirtualObject, basedOn screenPos: CGPoint, infinitePlane: Bool) { guard let cameraTransform = sceneView.session.currentFrame?.camera.transform, let (position, _, isOnPlane) = sceneView.worldPosition(fromScreenPosition: screenPos, objectPosition: object.simdPosition, infinitePlane: infinitePlane) else { return } /* Plane hit test results are generally smooth. If we did *not* hit a plane, smooth the movement to prevent large jumps. */ object.setPosition(position, relativeTo: cameraTransform, smoothMovement: !isOnPlane) } } /// Extends `UIGestureRecognizer` to provide the center point resulting from multiple touches. extension UIGestureRecognizer { func center(in view: UIView) -> CGPoint { let first = CGRect(origin: location(ofTouch: 0, in: view), size: .zero) let touchBounds = (1..<numberOfTouches).reduce(first) { touchBounds, index in return touchBounds.union(CGRect(origin: location(ofTouch: index, in: view), size: .zero)) } return CGPoint(x: touchBounds.midX, y: touchBounds.midY) } }
mit
96a5a11c8a72e1ebc18a4b4c8fafb3fa
39.39196
157
0.65153
5.209332
false
false
false
false
snowpunch/AppLove
App Love/UI/Cells/ReviewCell.swift
1
3012
// // ReviewCell.swift // App Love // // Created by Woodie Dovich on 2016-02-23. // Copyright © 2016 Snowpunch. All rights reserved. // // Displays user comments, visual stars for rating, allows translations. // import UIKit import Foundation class ReviewCell: UITableViewCell { @IBOutlet weak var flagImage: UIImageView! @IBOutlet weak var authorLabel: UILabel! @IBOutlet weak var reviewLabel: UILabel! @IBOutlet weak var titleLabel: UILabel! var model:ReviewModel? = nil var stars = [UIImageView]() func setup(model:ReviewModel) { self.model = model; if let title = model.title, let comment = model.comment { titleLabel.text = title reviewLabel.text = comment reviewLabel.numberOfLines = 0 reviewLabel.sizeToFit() } if let name = model.name, let rating = model.rating, let version = model.version, let territory = model.territory { let ratingNumber = Int(rating) ?? 1 let str = "\(territory) v\(version) \(name)" self.authorLabel.text = str self.addStars(ratingNumber) } else { authorLabel.text = "" } if let territoryCode = model.territoryCode { flagImage.image = UIImage(named:territoryCode) } // else { // print("error territoryCode \(model.territoryCode)") // if let territoryCode = model.territoryCode { // flagImage.image = UIImage(named:territoryCode) // } // else { // print("fail again") // } // } } func addStars(rating:Int) { var xpos:CGFloat = 13.0 for _ in 1...rating { addStar(xpos) xpos += 13 } } func layoutStars() { for star in stars { star.center = CGPoint(x: star.center.x, y: authorLabel.center.y-1) } } override func layoutSubviews() { super.layoutSubviews() layoutStars() } func addStar(pos:CGFloat) { let imageView = UIImageView() imageView.image = UIImage(named:"star") imageView.frame = CGRect(x: pos,y: authorLabel.center.y,width: 13,height: 13) self.addSubview(imageView) stars.append(imageView) } func removeStars() { for imageView in stars { imageView.removeFromSuperview() } stars.removeAll() } @IBAction func onReviewButton(button: UIButton) { if let modelData = self.model { let data:[String:AnyObject] = ["reviewModel":modelData, "button":button] let nc = NSNotificationCenter.defaultCenter() nc.postNotificationName(Const.reviewOptions.showOptions, object:nil, userInfo:data) } } override func prepareForReuse() { removeStars() flagImage.image = nil } }
mit
64aadae5191d2ac345709463474e3f5b
27.685714
95
0.563932
4.473997
false
false
false
false
cwwise/CWWeChat
CWWeChat/MainClass/Contacts/NewFriend/CWNewFriendCell.swift
2
2363
// // CWNewFriendCell.swift // CWWeChat // // Created by chenwei on 2017/4/8. // Copyright © 2017年 cwcoder. All rights reserved. // import UIKit class CWNewFriendCell: UITableViewCell { override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) self.contentView.addSubview(avatarImageView) self.contentView.addSubview(usernameLabel) self.contentView.addSubview(messageLabel) p_snap() } func p_snap() { avatarImageView.snp.makeConstraints { (make) in make.left.equalTo(ChatSessionCellUI.headerImageViewLeftPadding) make.top.equalTo(ChatSessionCellUI.headerImageViewTopPadding) make.bottom.equalTo(-ChatSessionCellUI.headerImageViewTopPadding) make.width.equalTo(self.avatarImageView.snp.height); } //用户名 usernameLabel.snp.makeConstraints { (make) in make.left.equalTo(avatarImageView.snp.right).offset(10) make.top.equalTo(avatarImageView).offset(2.0) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } lazy var avatarImageView:UIImageView = { let avatarImageView = UIImageView() return avatarImageView }() lazy var usernameLabel:UILabel = { let usernameLabel = UILabel() usernameLabel.backgroundColor = UIColor.white usernameLabel.font = UIFont.systemFont(ofSize: 16) return usernameLabel }() //邀请信息 lazy var messageLabel:UILabel = { let messageLabel = UILabel() messageLabel.backgroundColor = UIColor.gray messageLabel.font = UIFont.systemFont(ofSize: 14) return messageLabel }() lazy var actionButton:UIButton = { let actionButton = UIButton(type: .custom) actionButton.titleLabel?.font = UIFont.systemFont(ofSize: 14) return actionButton }() }
mit
6394f4f9afc7e27c1d119bd2c0384ee3
28.325
77
0.644928
4.980892
false
false
false
false
TellMeAMovieTeam/TellMeAMovie_iOSApp
TellMeAMovie/Pods/TMDBSwift/Sources/Client/Client_TV.swift
1
1011
// // Client_TV.swift // MDBSwiftWrapper // // Created by George Kye on 2016-02-15. // Copyright © 2016 George KyeKye. All rights reserved. // import Foundation extension Client{ static func TV(_ urlType: String!, api_key: String!, page: Int?, language: String?, timezone: String?, append_to: [String]? = nil, completion: @escaping (ClientReturn) -> ()) -> (){ var parameters: [String : AnyObject] = ["api_key": api_key as AnyObject] if(page != nil){ parameters["page"] = page as AnyObject? } if(language != nil){ parameters["language"] = language as AnyObject? } if(timezone != nil){ parameters["timezone"] = timezone as AnyObject? } if append_to != nil{ parameters["append_to_response"] = append_to?.joined(separator: ",") as AnyObject? } let url = "https://api.themoviedb.org/3/tv/" + urlType networkRequest(url: url, parameters: parameters, completion: { apiReturn in completion(apiReturn) }) } }
apache-2.0
6a35dd1629303c6191955c662de19562
27.857143
183
0.620792
3.869732
false
false
false
false
AlexMoffat/timecalc
TimeCalc/SynchroScrollView.swift
1
3174
/* * Copyright (c) 2017 Alex Moffat * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of mosquitto nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ import AppKit import Foundation class SynchroScrollView: NSScrollView { weak var synchronizedView: NSScrollView? var paused = false func setSynchronziedScrollView(view: NSScrollView) { stopSynchronizing() synchronizedView = view let contentView = view.contentView contentView.postsBoundsChangedNotifications = true NotificationCenter.default.addObserver(forName: NSView.boundsDidChangeNotification, object: contentView, queue: nil, using: synchroViewContentBoundsDidChange) } func stopSynchronizing() { if let contentView = synchronizedView?.contentView { NotificationCenter.default.removeObserver(self, name: NSView.boundsDidChangeNotification, object: contentView) synchronizedView = nil } } func synchroViewContentBoundsDidChange(notification: Notification) { if !paused { synchroViewContentBoundsDidChange(notifyingView: notification.object as! NSClipView) } } func synchroViewContentBoundsDidChange(notifyingView: NSClipView) { let changedBoundsOrigin = notifyingView.documentVisibleRect.origin let currentOffset = contentView.bounds.origin if !NSEqualPoints(currentOffset, changedBoundsOrigin) { var newOffset = currentOffset newOffset.y = changedBoundsOrigin.y contentView.scroll(to: newOffset) reflectScrolledClipView(contentView) } } }
bsd-3-clause
eb6c6b327e7dd0b760a119bb39c0944e
38.185185
166
0.710775
5.254967
false
false
false
false
ChristianDeckert/CDTools
CDTools/UI/UICollectionViewCell+CDTools.swift
1
1172
// // UICollectionViewCell+CDTools.swift // CDTools // // Created by Christian Deckert on 25.11.16. // Copyright © 2017 Christian Deckert // import Foundation import UIKit public extension UICollectionViewCell { public class var cellReuseIdentifier: String { let id = String(NSStringFromClass(self.classForCoder()).components(separatedBy: ".")[1]) return id! } } open class CDCollectionViewCell: UICollectionViewCell { open var viewModel: CDViewModelBase? { didSet { viewModelUpdated() } } fileprivate var _indexPath: IndexPath = IndexPath() open var indexPath: IndexPath { set { _indexPath = IndexPath(item: newValue.item, section: newValue.section) } get { return _indexPath } } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.indexPath = IndexPath(item: 0, section: 0) commonInit() } open func commonInit() { } open func viewModelUpdated() { self.transform = CGAffineTransform.identity } }
mit
76ce93b8a11215ca7f7fe781cfdf34fc
21.09434
96
0.603757
4.838843
false
false
false
false
rb-de0/HotSpring
Sources/HotSpring/AnyRequest.swift
1
755
import Foundation final class AnyRequest<T: Request>: Request { typealias Response = T.Response let base: URL let path: String let method: HTTPMethod let headers: [String : String]? let parameters: [String : Any]? let encoding: ParameterEncoding let _decodeResponse: (Any) throws -> Response init(_ request: T, context: RequestContext) { base = request.base path = request.path method = request.method headers = context.headers parameters = context.parameters encoding = request.encoding _decodeResponse = request.decodeResponse } func decodeResponse(_ data: Any) throws -> Response { return try _decodeResponse(data) } }
mit
d84dec146a69d63f7758cb026783eccf
25.964286
57
0.634437
4.870968
false
false
false
false
missiondata/transit
transit/transit/BusRoute.swift
1
559
// // BusRoute.swift // Transit // // Created by Dan Hilton on 2/3/16. // Copyright © 2016 MissionData. All rights reserved. // import Foundation open class BusRoute { open var routeId: String? open var name: String? open var description: String? public init(json: JSON) { routeId = json["RouteID"].string name = json["Name"].string description = json["LineDescription"].string } public init(routeId:String?, name:String?) { self.routeId = routeId self.name = name } }
mit
769d7ec713708e461dca7b60d9c270a1
19.666667
54
0.605735
3.985714
false
false
false
false
Kofktu/KofktuSDK
KofktuSDK/Classes/Components/KUIViewControllerPager.swift
1
9566
// // KUIViewControllerPager.swift // KofktuSDK // // Created by Kofktu on 2016. 9. 7.. // Copyright © 2016년 Kofktu. All rights reserved. // import Foundation import UIKit // view life cycle 중 will/did Appear/Disappear 메서드가 will/Did 가 동시에 일어나므로 did 에서 처리하길 권장 public protocol KMViewControllerPagerChildViewControllerProtocol { var pagerScrollView: UIScrollView? { get } } @objc public protocol KUIViewControllerPagerDelegate { @objc optional func pagerInitialized(_ pager: KUIViewControllerPager) @objc optional func pagerWillChangeIndex(_ pager: KUIViewControllerPager, viewController: UIViewController, atIndex index: Int) @objc optional func pagerDidChangeIndex(_ pager: KUIViewControllerPager, viewController: UIViewController, atIndex index: Int) @objc optional func pager(_ pager: KUIViewControllerPager, didScroll offset: CGPoint) } fileprivate class ReusableViewControllerCollectionViewCell: UICollectionViewCell {} open class KUIViewControllerPager : NSObject, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout { fileprivate weak var parentViewController: UIViewController! fileprivate weak var targetView: UIView! public fileprivate(set) lazy var collectionView: UICollectionView = { let layout = UICollectionViewFlowLayout() layout.scrollDirection = .horizontal layout.minimumLineSpacing = 0.0 layout.minimumInteritemSpacing = 0.0 layout.sectionInset = UIEdgeInsets.zero let collectionView = UICollectionView(frame: self.targetView.bounds, collectionViewLayout: layout) collectionView.backgroundColor = UIColor.clear collectionView.delegate = self collectionView.dataSource = self collectionView.bounces = false collectionView.clipsToBounds = true collectionView.scrollsToTop = false collectionView.isPagingEnabled = true collectionView.showsVerticalScrollIndicator = false collectionView.showsHorizontalScrollIndicator = false collectionView.translatesAutoresizingMaskIntoConstraints = false collectionView.addObserver(self, forKeyPath: "contentSize", options: [.new], context: nil) collectionView.register(ReusableViewControllerCollectionViewCell.self, forCellWithReuseIdentifier: ReusableViewControllerCollectionViewCell.reusableIdentifier) return collectionView }() open weak var delegate: KUIViewControllerPagerDelegate? open var viewControllers: [UIViewController]? { didSet { collectionView.reloadData() } } open var visibleViewController: UIViewController? { if let viewControllers = viewControllers, currentIndex < viewControllers.count { return viewControllers[currentIndex] } return nil } open var currentIndex: Int = 0 public var isScrollEnabled: Bool { get { return collectionView.isScrollEnabled } set { collectionView.isScrollEnabled = newValue } } fileprivate var willMoveIndex: Int = 0 fileprivate var contentSizeObserving = true fileprivate var scrollObserving = true fileprivate var latestOffset = CGPoint.zero deinit { if contentSizeObserving { collectionView.removeObserver(self, forKeyPath: "contentSize") } } open override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { guard let keyPath = keyPath, keyPath == "contentSize" else { return } if contentSizeObserving && !collectionView.contentSize.equalTo(CGSize.zero) { contentSizeObserving = false moveToIndex(currentIndex, animated: false) collectionView.removeObserver(self, forKeyPath: "contentSize") delegate?.pagerInitialized?(self) } } public init(parentViewController: UIViewController, targetView: UIView) { super.init() self.targetView = targetView self.parentViewController = parentViewController parentViewController.automaticallyAdjustsScrollViewInsets = false targetView.addSubviewAtFit(collectionView) } open func moveToIndex(_ index: Int, animated: Bool = true) { if collectionView.contentSize.equalTo(CGSize.zero) { return } let moveIndex = max(0, min(index, viewControllers?.count ?? 0)) if animated { scrollObserving = false UIView.animate(withDuration: 0.25, animations: { self.collectionView.contentOffset = CGPoint(x: CGFloat(moveIndex) * self.collectionView.width, y: 0.0) }, completion: { (finished) in self.scrollObserving = true self.scrollViewDidEndDecelerating(self.collectionView) }) } else { UIView.setAnimationsEnabled(false) if let cell = collectionView.cellForItem(at: IndexPath(item: index, section: 0)) { addViewControllerIfNeeded(cell, at: index) } collectionView.scrollToItem(at: IndexPath(item: index, section: 0), at: .centeredHorizontally, animated: animated) scrollViewDidEndDecelerating(collectionView) UIView.setAnimationsEnabled(true) } } open func refreshLayout(_ animated: Bool = true) { if animated { collectionView.performBatchUpdates({ self.collectionView.collectionViewLayout.invalidateLayout() self.collectionView.setCollectionViewLayout(self.collectionView.collectionViewLayout, animated: false) }, completion: nil) } else { collectionView.collectionViewLayout.invalidateLayout() collectionView.setCollectionViewLayout(collectionView.collectionViewLayout, animated: false) } } public func updateScroll(_ offset: CGPoint, animated: Bool = true) { collectionView.setContentOffset(offset, animated: animated) } fileprivate func updateViewControllersScrollToTop() { guard let viewControllers = viewControllers else { return } for (index, viewController) in viewControllers.enumerated() { (viewController as? KMViewControllerPagerChildViewControllerProtocol)?.pagerScrollView?.scrollsToTop = (index == currentIndex) } } fileprivate func addViewControllerIfNeeded(_ cell: UICollectionViewCell, at index: Int) { guard let viewController = viewControllers?[index], viewController.parent == nil else { return } parentViewController.addChild(viewController) cell.contentView.addSubviewAtFit(viewController.view) viewController.didMove(toParent: parentViewController) } fileprivate func removeViewController(_ index: Int) { guard let viewController = viewControllers?[index] else { return } viewController.willMove(toParent: nil) viewController.view.removeFromSuperview() viewController.removeFromParent() } // MARK: UIScrollViewDelegate public func scrollViewDidScroll(_ scrollView: UIScrollView) { delegate?.pager?(self, didScroll: scrollView.contentOffset) } open func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) { guard !decelerate else { return } self.scrollViewDidEndDecelerating(scrollView) } open func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { guard let viewControllers = viewControllers else { return } let contentOffset = scrollView.contentOffset let index = Int(floor(contentOffset.x / scrollView.width)) willMoveIndex = index currentIndex = index updateViewControllersScrollToTop() delegate?.pagerDidChangeIndex?(self, viewController: viewControllers[currentIndex], atIndex: currentIndex) } // MARK: - UICollectionViewProtocol open func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return viewControllers?.count ?? 0 } open func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { return collectionView.dequeueReusableCell(withReuseIdentifier: ReusableViewControllerCollectionViewCell.reusableIdentifier, for: indexPath) as! ReusableViewControllerCollectionViewCell } open func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) { guard let viewControllers = viewControllers else { return } willMoveIndex = indexPath.item addViewControllerIfNeeded(cell, at: willMoveIndex) delegate?.pagerWillChangeIndex?(self, viewController: viewControllers[willMoveIndex], atIndex: willMoveIndex) } open func collectionView(_ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) { removeViewController(indexPath.item) } open func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return collectionView.size } }
mit
bd304731bba087784b956e9eb85316b8
42.665138
192
0.701229
6.00947
false
false
false
false
alecgorge/AGAudioPlayer
AGAudioPlayer/UI/AGExtensions.swift
1
1548
// // AGExtensions.swift // AGAudioPlayer // // Created by Alec Gorge on 1/20/17. // Copyright © 2017 Alec Gorge. All rights reserved. // import Foundation extension TimeInterval { public func formatted() -> String { let seconds = Int(self.truncatingRemainder(dividingBy: 60)); let minutes = Int((self / 60).truncatingRemainder(dividingBy: 60)); let hours = Int(self / 3600); if(hours == 0) { return String(format: "%d:%02d", minutes, seconds); } return String(format: "%d:%02d:%02d", hours, minutes, seconds); } } extension NSLayoutConstraint { /** Change multiplier constraint - parameter multiplier: CGFloat - returns: NSLayoutConstraint */ public func setMultiplier(multiplier:CGFloat) -> NSLayoutConstraint { guard firstItem != nil else { return self } NSLayoutConstraint.deactivate([self]) let newConstraint = NSLayoutConstraint( item: firstItem!, attribute: firstAttribute, relatedBy: relation, toItem: secondItem, attribute: secondAttribute, multiplier: multiplier == 0 ? 1.0 : multiplier, constant: constant) newConstraint.priority = priority newConstraint.shouldBeArchived = self.shouldBeArchived newConstraint.identifier = self.identifier NSLayoutConstraint.activate([newConstraint]) return newConstraint } }
mit
aeb369ff9330fb80ebf957fedc021332
27.127273
75
0.604396
5.173913
false
false
false
false
Game-of-whales/GOW-SDK-IOS
Example/test/PlayerInfo.swift
1
3452
/* * Game Of Whales SDK * * https://www.gameofwhales.com/ * * Copyright © 2018 GameOfWhales. All rights reserved. * * Licence: https://www.gameofwhales.com/licence * */ import Foundation import GameOfWhales class PlayerInfo { static var sharedInstance: PlayerInfo = PlayerInfo() var userClass:String = "Warrior"; var level:Int = 1; var coins:Int = 100000; var location:String = "A"; var locationCode:Int = 0; var gender:Bool = false; var productCoins:[String:Int] = ["product_5":500, "product_10":1000, "product_20":2500, "sub_week_grace3_1":0, "sub_month_graceno_2":0] public func getItemCost(itemID:String) -> Int { if (itemID == "item1") { return 1000; } if (itemID == "item2") { return 2000; } return 1; } public func getLevel() -> Int { return level } public func getLocation() -> String { return location } public func getGender() -> Bool { return gender } public func getUserClass() -> String { return userClass } public func getProductCoins(productIdentifier:String)->Int{ return productCoins[productIdentifier]!; } func load() { let defaults = UserDefaults.standard locationCode = defaults.integer(forKey: "location") == 0 ? locationCode : defaults.integer(forKey: "location") level = defaults.integer(forKey: "level") == 0 ? level : defaults.integer(forKey: "level") userClass = defaults.string(forKey: "class") == nil ? userClass : defaults.string(forKey: "class")! gender = defaults.bool(forKey: "gender") coins = defaults.integer(forKey: "coins") == 0 ? coins : defaults.integer(forKey: "coins") } func save() { let defaults = UserDefaults.standard defaults.set(level, forKey: "level") defaults.set(userClass, forKey: "class") defaults.set(gender, forKey: "gender") defaults.set(locationCode, forKey: "location") defaults.set(coins, forKey: "coins"); } init() { var classes: [String] = ["Warrior", "Wizard", "Rogue"] userClass = classes[Int(arc4random() % 3)] gender = arc4random() % 2 == 0 ? false : true; load() updateLocation() } public func addLevel() { level += 1; GW.profile(["level":level]) save() } public func incCoins(val:Int){ coins += val; GW.profile(["coins":coins]); save(); } public func getCoins() -> Int { return coins; } public func decCoins(val:Int) { coins -= val GW.profile(["coins":coins]); save(); } public func canBuy(cost:Int) -> Bool { return cost <= coins; } func updateLocation() { let startingValue = Int(("A" as UnicodeScalar).value) location = String(Character(UnicodeScalar(startingValue + locationCode)!)) } public func nextLocation() { locationCode += 1; if (locationCode >= 33) { locationCode = 0; } GW.profile(["location_\(locationCode)":true]) updateLocation() save() } }
mit
309ee0aaabf45dfdf4e427addccb95f0
22.006667
139
0.537236
4.22399
false
false
false
false
syd24/DouYuZB
DouYu/DouYu/classes/tools/NetworkTools.swift
1
815
// // NetworkTools.swift // DouYu // // Created by ADMIN on 16/11/11. // Copyright © 2016年 ADMIN. All rights reserved. // import UIKit import Alamofire enum MethodType { case get case post } class NetworkTools: NSObject { class func requestData(type : MethodType, URLString : String, parameters : [String : Any]? = nil, finishedCallback: @escaping (_ result : Any) -> ()) { let method = type == .get ? HTTPMethod.get : HTTPMethod.post; Alamofire.request(URLString, method: method, parameters: parameters).responseJSON { (response) in guard let result = response.result.value else{ return; } finishedCallback(result) } } }
mit
4b8004f651677011d568e50b6ba6e52a
20.945946
156
0.555419
4.666667
false
false
false
false
jjcmwangxinyu/DouYuTV
DouYuTV/DouYuTV/Classes/Main/PageTitleView.swift
1
5331
// // PageTitleView.swift // DouYuTV // // Created by 王新宇 on 2017/3/12. // Copyright © 2017年 王新宇. All rights reserved. // import UIKit private let kScrollLineH : CGFloat = 2 private let kNormalColor : (CGFloat, CGFloat, CGFloat) = (85, 85, 85) private let kSelectColor : (CGFloat, CGFloat, CGFloat) = (255, 128, 0) protocol PageTitleViewDelegate :class{ func returnValue(_ titleView:PageTitleView ,selectIndex index:Int) } class PageTitleView: UIView { weak var delegate:PageTitleViewDelegate? fileprivate var titles :[String] //定义懒加载属性 fileprivate lazy var titleLabels :[UILabel] = [UILabel]() fileprivate var currentIndex:Int = 0 init(frame: CGRect, titles:[String]) { self.titles = titles super.init(frame: frame) //设置UI setUpUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } fileprivate lazy var scroll:UIScrollView = { let scroll = UIScrollView() scroll.isPagingEnabled = false scroll.bounces = false scroll.showsHorizontalScrollIndicator = false scroll.scrollsToTop = false return scroll }() fileprivate lazy var scrollLine:UIView = { let scrollLine = UIView() scrollLine.backgroundColor = UIColor.orange return scrollLine }() } extension PageTitleView { fileprivate func setUpUI() { //添加scrolview self.addSubview(scroll) scroll.frame = bounds //添加label setTitleLabels() //设置底线 setBottomLine() } fileprivate func setBottomLine() { //设置底线 let bottomeLine = UIView() bottomeLine.backgroundColor = UIColor.lightGray let bottomH :CGFloat = 0.5 bottomeLine.frame = CGRect(x: 0, y: frame.height-bottomH, width: frame.width, height: bottomH) addSubview(bottomeLine) // guard let firstLabel = titleLabels.first else{return} firstLabel.textColor = UIColor(r: kSelectColor.0, g: kSelectColor.1, b: kSelectColor.2) scroll.addSubview(scrollLine) scrollLine.frame = CGRect(x: firstLabel.frame.origin.x, y: frame.height-kScrollLineH, width: firstLabel.frame.size.width, height: kScrollLineH) } fileprivate func setTitleLabels() { //设置label frame let labelw :CGFloat = frame.width/CGFloat(titles.count) let labelh :CGFloat = frame.size.height-kScrollLineH let labely :CGFloat = 0 for (index,title) in titles.enumerated() { let label = UILabel()//创建label //设置label属性 label.text = title label.tag = index label.font = UIFont.systemFont(ofSize: 17) label.textColor = UIColor(r: kNormalColor.0, g: kNormalColor.1, b: kNormalColor.2) label.textAlignment = .center let labelx :CGFloat = labelw * CGFloat(index) label.frame = CGRect(x: labelx, y: labely, width: labelw, height: labelh) scroll.addSubview(label) titleLabels.append(label) label.isUserInteractionEnabled = true let tapGes = UITapGestureRecognizer(target: self, action: #selector(self.tapClick(_:))) label.addGestureRecognizer(tapGes) } } } extension PageTitleView { func setPageOffset(progress:CGFloat,sourceIndex:Int,targetIndex:Int) { //取出 source target 对应的label let source = titleLabels[sourceIndex] let target = titleLabels[targetIndex] //处理滑块逻辑 let moveTotal = target.frame.origin.x - source.frame.origin.x let moveX = moveTotal*progress scrollLine.frame.origin.x = source.frame.origin.x+moveX // 3.颜色的渐变(复杂) // 3.1.取出变化的范围 let colorDelta = (kSelectColor.0 - kNormalColor.0, kSelectColor.1 - kNormalColor.1, kSelectColor.2 - kNormalColor.2) // 3.2.变化sourceLabel source.textColor = UIColor(r: kSelectColor.0 - colorDelta.0 * progress, g: kSelectColor.1 - colorDelta.1 * progress, b: kSelectColor.2 - colorDelta.2 * progress) // 3.2.变化targetLabel target.textColor = UIColor(r: kNormalColor.0 + colorDelta.0 * progress, g: kNormalColor.1 + colorDelta.1 * progress, b: kNormalColor.2 + colorDelta.2 * progress) currentIndex = targetIndex; } } extension PageTitleView { @objc fileprivate func tapClick(_ tap:UITapGestureRecognizer) { guard let currentLabel = tap.view as? UILabel else {return} let oldLabel = titleLabels[currentIndex] currentIndex = currentLabel.tag if currentLabel.tag == oldLabel.tag { return } currentLabel.textColor = UIColor.orange oldLabel.textColor = UIColor(r: kNormalColor.0, g: kNormalColor.1, b: kNormalColor.2) delegate?.returnValue(self, selectIndex: currentLabel.tag) // 5.滚动条位置发生改变 let scrollLineX = CGFloat(currentIndex) * scrollLine.frame.width UIView.animate(withDuration: 0.15, animations: { self.scrollLine.frame.origin.x = scrollLineX }) } }
mit
b1a29cdc596b6e4921eb86356b28eeda
35.751773
169
0.637399
4.502172
false
false
false
false
sareninden/DataSourceFramework
DataSourceFrameworkDemo/DataSourceFrameworkDemo/CustomRowActionsTableViewController.swift
1
3872
import Foundation import UIKit import DataSourceFramework class CustomRowActionsTableViewController : BaseTableViewController { // MARK:- Class Variables // MARK:- Variables // MARK:- Init and Dealloc override init() { super.init() title = "Custom Row Actions" tableController.editingSupportDelegate = self tableController.editingStyle = .Delete tableController.canEdit = true } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK:- Public Class Methods // MARK:- Internal Instance Methods override func loadData() { for sectionIndex in 0..<5 { let section = sectionWithHeaderTitle("Section \(sectionIndex)") for row in 0...5 { let item = TableItem(text: "<< Swipe section \(sectionIndex) row \(row)") section.addItem(item) if row > 3 { item.text = "<< Custom section \(sectionIndex) row \(row)" let action1 = UITableViewRowAction(style: .Normal, title: "Custom1") { (action, indexPath) -> Void in self.showAlertAndCloseEditing("Custom1") } let action2 = UITableViewRowAction(style: .Default, title: "Custom2") { (action, indexPath) -> Void in self.showAlertAndCloseEditing("Custom2") } item.editActionsForRow = [action2, action1] } } tableController.addSection(section) } } } extension CustomRowActionsTableViewController : TableControllerEditingSupportInterface { func tableController(tableController : TableController, tableView: UITableView, titleForDeleteConfirmationButtonForRowAtIndexPath indexPath: NSIndexPath) -> String? { return nil } func tableController(tableController : TableController, tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [UITableViewRowAction]? { let action1 = UITableViewRowAction(style: .Normal, title: "Action1") { (action, indexPath) -> Void in self.showAlertAndCloseEditing("Action1") } let action2 = UITableViewRowAction(style: .Default, title: "Action2") { (action, indexPath) -> Void in self.showAlertAndCloseEditing("Action2") } let action3 = UITableViewRowAction(style: .Normal, title: "Action3") { (action, indexPath) -> Void in self.showAlertAndCloseEditing("Action3") } return [action3, action2, action1] } func tableController(tableController : TableController, tableView: UITableView, shouldIndentWhileEditingRowAtIndexPath indexPath: NSIndexPath) -> Bool? { return false } func tableController(tableController : TableController, tableView: UITableView, willBeginEditingRowAtIndexPath indexPath: NSIndexPath) { } func tableController(tableController : TableController, tableView: UITableView, didEndEditingRowAtIndexPath indexPath: NSIndexPath) { } func showAlertAndCloseEditing(text : String) { tableView.setEditing(false, animated: true) let alertController = UIAlertController(title: "Action selected", message: text, preferredStyle: .Alert) alertController.addAction(UIAlertAction(title: "Close", style: .Cancel, handler: { (action) -> Void in })) presentViewController(alertController, animated: true, completion: nil) } }
gpl-3.0
78edc4c13c80be9add8a36386e783639
34.861111
170
0.600723
5.93865
false
false
false
false
343max/WorldTime
WorldTime/Location.swift
1
2929
// Copyright 2014-present Max von Webel. All Rights Reserved. import Foundation struct Location { var name: String var timeZone: TimeZone init(name: String, timeZone: TimeZone) { self.name = name self.timeZone = timeZone; } init(name: String, timeZoneAbbrevation: String) { guard let timeZone = TimeZone(abbreviation: timeZoneAbbrevation) else { fatalError("couldn't create timeZone: \(timeZoneAbbrevation)") } self.init(name: name, timeZone: timeZone) } init(name: String, timeZoneName: String) { guard let timeZone = TimeZone(identifier: timeZoneName) else { fatalError("couldn't create timeZone: \(timeZoneName)") } self.init(name: name, timeZone: timeZone) } } extension Location { typealias Dictionary = [String: AnyObject] static var nameKey = "Name" static var timeZoneNameKey = "TimeZoneName" init?(dictionary: Location.Dictionary) { guard let name = dictionary[Location.nameKey] as? String, let timeZoneName = dictionary[Location.timeZoneNameKey] as? String else { return nil } self.init(name: name, timeZoneName: timeZoneName) } var dictionary: Location.Dictionary { get { return [ Location.nameKey: self.name as AnyObject, Location.timeZoneNameKey: self.timeZone.identifier as AnyObject ] } } static func from(arrayOfDicts: [Location.Dictionary]) -> [Location] { return arrayOfDicts.compactMap() { (dict) -> Location? in return Location(dictionary: dict) } } static func arrayOfDicts(locations: [Location]) -> [Location.Dictionary] { return locations.map() { (location) -> Location.Dictionary in return location.dictionary } } } extension Location { func stringFrom(date: Date, formatter: DateFormatter) -> String { formatter.timeZone = timeZone return formatter.string(from: date as Date) } } extension Location { static var locationsKey = "Locations" static var userDefaults = UserDefaults(suiteName: "group.de.343max.WorldTime")! static func defaultLocations() -> [Location] { return [ Location(name: "San Francisco", timeZoneAbbrevation: "PST"), Location(name: "Berlin", timeZoneAbbrevation: "CEST") ] } static func fromDefaults() -> [Location] { guard let locations = Location.userDefaults.array(forKey: locationsKey) as? [Location.Dictionary] else { return self.defaultLocations() } return self.from(arrayOfDicts: locations) } static func toDefaults(locations: [Location]) { self.userDefaults.setValue(self.arrayOfDicts(locations: locations), forKey: self.locationsKey) self.userDefaults.synchronize() } }
mit
94e69ed8dd197c4eb9a9b8834bd198b7
30.159574
112
0.636736
4.590909
false
false
false
false
EvsenevDev/SmartReceiptsiOS
SmartReceipts/Common/UI/ScansPurchaseButton.swift
2
1630
// // ScansPurchaseButton.swift // SmartReceipts // // Created by Bogdan Evsenev on 27/10/2017. // Copyright © 2017 Will Baumann. All rights reserved. // import UIKit import RxSwift class ScansPurchaseButton: UIButton { @IBOutlet weak var title: UILabel! @IBOutlet weak var subtitle: UILabel! @IBOutlet fileprivate weak var price: UILabel! @IBOutlet fileprivate weak var activityIndicator: UIActivityIndicatorView! private let bag = DisposeBag() override func awakeFromNib() { layer.cornerRadius = 7 rx.controlEvent(.touchDown) .subscribe(onNext: { [unowned self] in self.backgroundColor = UIColor.srViolet2.withAlphaComponent(0.8) }).disposed(by: bag) rx.controlEvent([.touchUpInside, .touchUpOutside, .touchCancel]) .subscribe(onNext: { [unowned self] in self.backgroundColor = .srViolet2 }).disposed(by: bag) apply(style: .mainBig) } func setScans(count: Int) { let titleFormat = LocalizedString("ocr_configuration_module_purchase_title") title.text = String(format: titleFormat, count) let subtitleFormat = LocalizedString("ocr_configuration_module_purchase_subtitle") subtitle.text = String(format: subtitleFormat, count) } } extension Reactive where Base: ScansPurchaseButton { var price: AnyObserver<String> { return AnyObserver<String>(onNext: { [unowned base] price in base.price.text = price base.activityIndicator.stopAnimating() }) } }
agpl-3.0
5fc9bb5f27b5b4383e395aa4fae8ccba
30.326923
90
0.645795
4.627841
false
false
false
false
mssun/passforios
pass/Controllers/SSHKeyArmorImportTableViewController.swift
2
3323
// // SSHKeyArmorImportTableViewController.swift // pass // // Created by Mingshen Sun on 2/4/2017. // Copyright © 2017 Bob Sun. All rights reserved. // import passKit import UIKit class SSHKeyArmorImportTableViewController: AutoCellHeightUITableViewController, UITextViewDelegate, QRScannerControllerDelegate { @IBOutlet var armorPrivateKeyTextView: UITextView! @IBOutlet var scanPrivateKeyCell: UITableViewCell! private var armorPrivateKey: String? private var scanner = QRKeyScanner(keyType: .sshPrivate) override func viewDidLoad() { super.viewDidLoad() armorPrivateKeyTextView.delegate = self scanPrivateKeyCell?.textLabel?.text = "ScanPrivateKeyQrCodes".localize() scanPrivateKeyCell?.selectionStyle = .default scanPrivateKeyCell?.accessoryType = .disclosureIndicator } @IBAction private func doneButtonTapped(_: Any) { armorPrivateKey = armorPrivateKeyTextView.text performSegue(withIdentifier: "importSSHKeySegue", sender: self) } func textView(_: UITextView, shouldChangeTextIn _: NSRange, replacementText text: String) -> Bool { if text == UIPasteboard.general.string { // user pastes something, do the copy here again and clear the pasteboard in 45s SecurePasteboard.shared.copy(textToCopy: text) } return true } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let selectedCell = tableView.cellForRow(at: indexPath) if selectedCell == scanPrivateKeyCell { scanner = QRKeyScanner(keyType: .sshPrivate) performSegue(withIdentifier: "showSSHScannerSegue", sender: self) } tableView.deselectRow(at: indexPath, animated: true) } // MARK: - QRScannerControllerDelegate Methods func checkScannedOutput(line: String) -> (accepted: Bool, message: String) { scanner.add(segment: line).unrolled } // MARK: - QRScannerControllerDelegate Methods func handleScannedOutput(line _: String) { armorPrivateKeyTextView.text = scanner.scannedKey } override func prepare(for segue: UIStoryboardSegue, sender _: Any?) { guard segue.identifier == "showSSHScannerSegue" else { return } if let navController = segue.destination as? UINavigationController { if let viewController = navController.topViewController as? QRScannerController { viewController.delegate = self } } else if let viewController = segue.destination as? QRScannerController { viewController.delegate = self } } @IBAction private func cancelSSHScanner(segue _: UIStoryboardSegue) {} } extension SSHKeyArmorImportTableViewController: KeyImporter { static let keySource = KeySource.armor static let label = "AsciiArmorEncryptedKey".localize() func isReadyToUse() -> Bool { guard !armorPrivateKeyTextView.text.isEmpty else { Utils.alert(title: "CannotSave".localize(), message: "SetPrivateKey.".localize(), controller: self) return false } return true } func importKeys() throws { try KeyFileManager.PrivateSSH.importKey(from: armorPrivateKey ?? "") } }
mit
91e1a2bc1fba9bf57bf931d0069c1e8a
33.604167
130
0.687237
5.079511
false
false
false
false
schrockblock/gtfs-stations-paris
GTFSStationsParis/Classes/PARStationManager.swift
1
9279
// // PARStationManager.swift // GTFSStationsParis // // Created by Elliot Schrock on 7/1/16. // Copyright © 2016 CocoaPods. All rights reserved. // import UIKit import SQLite import SubwayStations open class PARStationManager: NSObject, StationManager { @objc open var sourceFilePath: String? @objc lazy var dbManager: DBManager = { let lazyManager = DBManager(sourcePath: self.sourceFilePath) return lazyManager }() open var allStations: Array<Station> = Array<Station>() open var routes: Array<Route> = Array<Route>() @objc open var timeLimitForPredictions: Int32 = 20 @objc public init(sourceFilePath: String?) throws { super.init() if let file = sourceFilePath { self.sourceFilePath = file } do { var stationIds = Array<String>() let stopRows = try dbManager.database.prepare("SELECT stop_name, stop_id FROM stops") for stopRow in stopRows { let stop = PARStop(name: stopRow[0] as! String, objectId: stopRow[1] as! String) if !stationIds.contains(stop.name) { let station = PARStation(name: stop.name) station.stops.append(stop) stationIds.append(stop.name) var stationName = station.name.replacingOccurrences(of: "d'", with: "", options: NSString.CompareOptions.caseInsensitive, range: nil) stationName = stationName.replacingOccurrences(of: "l'", with: "", options: NSString.CompareOptions.caseInsensitive, range: nil) let stationNameArray = stationName.components(separatedBy: NSCharacterSet.whitespaces) if let queryForName = queryForNameArray(stationNameArray) { for otherStopRow in try dbManager.database.prepare("SELECT stop_name, stop_id FROM stops WHERE location_type = 0" + queryForName) { let parent = PARStop(name: otherStopRow[0] as! String, objectId: otherStopRow[1] as! String) if station == PARStation(name: parent.name) { station.stops.append(parent) stationIds.append(parent.name) } } } allStations.append(station) } } for routeRow in try dbManager.database.prepare("SELECT route_id, route_short_name FROM routes") { let route = PARRoute(objectId: routeRow[1] as! String) route.color = PARRouteColorManager().colorForRouteId(routeRow[1] as! String) if let oldRouteIndex = routes.index(where: {route == ($0 as! PARRoute)}) { let oldRoute = routes[oldRouteIndex] as! PARRoute if !oldRoute.routeIds.contains(routeRow[0] as! String) { oldRoute.routeIds.append(routeRow[0] as! String) } }else{ route.routeIds.append(routeRow[0] as! String) routes.append(route) } } }catch let error as NSError { print(error.debugDescription) } } open func stationsForSearchString(_ stationName: String!) -> Array<Station>? { return allStations.filter({$0.name!.lowercased().range(of: stationName.lowercased()) != nil}) } public func predictions(_ station: Station!, time: Date!) -> Array<Prediction> { var predictions = Array<Prediction>() do { let stops = station.stops let timesQuery = "SELECT trip_id, departure_time FROM stop_times WHERE stop_id IN (" + questionMarksForStopArray(stops)! + ") AND departure_time BETWEEN ? AND ?" var stopIds: [Binding?] = stops.map({ (stop: Stop) -> Binding? in stop.objectId as Binding }) stopIds.append(dateToTime(time)) stopIds.append(dateToTime((time as Date).increment(NSCalendar.Unit.minute, amount: Int(timeLimitForPredictions)))) let stmt = try dbManager.database.prepare(timesQuery) for timeRow in stmt.bind(stopIds) { let tripId = timeRow[0] as! String let depTime = timeRow[1] as! String let prediction = Prediction(time: timeToDate(depTime, referenceDate: time)) for tripRow in try dbManager.database.prepare("SELECT direction_id, route_id FROM trips WHERE trip_id = ?", [tripId]) { let direction = tripRow[0] as! Int64 let routeId = tripRow[1] as! String prediction.direction = direction == 0 ? Direction.uptown : Direction.downtown let routeArray = routes.filter({($0 as! PARRoute).routeIds.contains(routeId)}) prediction.route = routeArray[0] } if !predictions.contains(where: {$0 == prediction}) { predictions.append(prediction) } } }catch _ { } return predictions } open func routeIdsForStation(_ station: Station) -> Array<String> { var routeNames = Array<String>() do { let stops = station.stops let sqlStatementString = "SELECT trips.route_id FROM trips INNER JOIN stop_times ON stop_times.trip_id = trips.trip_id WHERE stop_times.stop_id IN (" + questionMarksForStopArray(stops)! + ") GROUP BY trips.route_id" let sqlStatement = try dbManager.database.prepare(sqlStatementString) let stopIds: [Binding?] = stops.map({ (stop: Stop) -> Binding? in stop.objectId as Binding }) var routeIds = Array<String>() for routeRow in sqlStatement.bind(stopIds) { routeIds.append(routeRow[0] as! String) } for routeId in routeIds { for route in routes { let parRoute = route as! PARRoute if parRoute.routeIds.contains(routeId) && !routeNames.contains(parRoute.objectId) { routeNames.append(parRoute.objectId) } } } }catch _ { } return routeNames } public func stationsForRoute(_ route: Route) -> Array<Station>? { var stations = Array<Station>() do { let sqlString = "SELECT stops.parent_station,stop_times.stop_sequence FROM stops " + "INNER JOIN stop_times ON stop_times.stop_id = stops.stop_id " + "INNER JOIN trips ON stop_times.trip_id = trips.trip_id " + "WHERE trips.route_id = ? AND trips.direction_id = 0 AND stop_times.departure_time BETWEEN ? AND ? " + "GROUP BY stops.parent_station " + "ORDER BY stop_times.stop_sequence DESC " for stopRow in try dbManager.database.prepare(sqlString, [route.objectId, "10:00:00", "15:00:00"]) { let parentId = stopRow[0] as? String for station in allStations { var foundOne = false for stop in station.stops { if stop.objectId == parentId { stations.append(station) foundOne = true break } } if foundOne { break } } } }catch _ { } return stations } @objc func dateToTime(_ time: Date!) -> String{ let formatter: DateFormatter = DateFormatter() formatter.dateFormat = "HH:mm:ss" return formatter.string(from: time) } @objc func timeToDate(_ time: String!, referenceDate: Date!) -> Date?{ let dateFormatter = DateFormatter() dateFormatter.dateFormat = "YYYY-MM-DD " let formatter: DateFormatter = DateFormatter() formatter.dateFormat = "YYYY-MM-DD HH:mm:ss" let timeString = dateFormatter.string(from: referenceDate) + time return formatter.date(from: timeString) } func questionMarksForStopArray(_ array: Array<Stop>?) -> String?{ var qMarks: String = "?" if let stops = array { if stops.count > 1 { for _ in stops { qMarks = qMarks + ",?" } let index = qMarks.characters.index(qMarks.endIndex, offsetBy: -2) qMarks = qMarks.substring(to: index) } }else{ return nil } return qMarks } @objc func queryForNameArray(_ array: Array<String>?) -> String? { var query = "" if let nameArray = array { for nameComponent in nameArray { query += " AND stop_name LIKE '%\(nameComponent)%'" } }else{ return nil } return query } }
mit
8660f800299d30bc355b5286baf59347
42.35514
227
0.540203
4.690597
false
false
false
false
huahuasj/ios-charts
Charts/Classes/Renderers/PieChartRenderer.swift
3
15762
// // PieChartRenderer.swift // Charts // // Created by Daniel Cohen Gindi on 4/3/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/ios-charts // import Foundation import CoreGraphics.CGBase import UIKit.UIColor import UIKit.UIFont public class PieChartRenderer: ChartDataRendererBase { internal weak var _chart: PieChartView! public var drawHoleEnabled = true public var holeTransparent = true public var holeColor: UIColor? = UIColor.whiteColor() public var holeRadiusPercent = CGFloat(0.5) public var transparentCircleRadiusPercent = CGFloat(0.55) public var centerTextColor = UIColor.blackColor() public var centerTextFont = UIFont.systemFontOfSize(12.0) public var drawXLabelsEnabled = true public var usePercentValuesEnabled = false public var centerText: String! public var drawCenterTextEnabled = true public var centerTextLineBreakMode = NSLineBreakMode.ByTruncatingTail public var centerTextRadiusPercent: CGFloat = 1.0 public init(chart: PieChartView, animator: ChartAnimator?, viewPortHandler: ChartViewPortHandler) { super.init(animator: animator, viewPortHandler: viewPortHandler); _chart = chart; } public override func drawData(#context: CGContext) { if (_chart !== nil) { var pieData = _chart.data; if (pieData != nil) { for set in pieData!.dataSets as! [PieChartDataSet] { if (set.isVisible) { drawDataSet(context: context, dataSet: set); } } } } } internal func drawDataSet(#context: CGContext, dataSet: PieChartDataSet) { var angle = _chart.rotationAngle; var cnt = 0; var entries = dataSet.yVals; var drawAngles = _chart.drawAngles; var circleBox = _chart.circleBox; var radius = _chart.radius; var innerRadius = drawHoleEnabled && holeTransparent ? radius * holeRadiusPercent : 0.0; CGContextSaveGState(context); for (var j = 0; j < entries.count; j++) { var newangle = drawAngles[cnt]; var sliceSpace = dataSet.sliceSpace; var e = entries[j]; // draw only if the value is greater than zero if ((abs(e.value) > 0.000001)) { if (!_chart.needsHighlight(xIndex: e.xIndex, dataSetIndex: _chart.data!.indexOfDataSet(dataSet))) { var startAngle = angle + sliceSpace / 2.0; var sweepAngle = newangle * _animator.phaseY - sliceSpace / 2.0; if (sweepAngle < 0.0) { sweepAngle = 0.0; } var endAngle = startAngle + sweepAngle; var path = CGPathCreateMutable(); CGPathMoveToPoint(path, nil, circleBox.midX, circleBox.midY); CGPathAddArc(path, nil, circleBox.midX, circleBox.midY, radius, startAngle * ChartUtils.Math.FDEG2RAD, endAngle * ChartUtils.Math.FDEG2RAD, false); CGPathCloseSubpath(path); if (innerRadius > 0.0) { CGPathMoveToPoint(path, nil, circleBox.midX, circleBox.midY); CGPathAddArc(path, nil, circleBox.midX, circleBox.midY, innerRadius, startAngle * ChartUtils.Math.FDEG2RAD, endAngle * ChartUtils.Math.FDEG2RAD, false); CGPathCloseSubpath(path); } CGContextBeginPath(context); CGContextAddPath(context, path); CGContextSetFillColorWithColor(context, dataSet.colorAt(j).CGColor); CGContextEOFillPath(context); } } angle += newangle * _animator.phaseX; cnt++; } CGContextRestoreGState(context); } public override func drawValues(#context: CGContext) { var center = _chart.centerCircleBox; // get whole the radius var r = _chart.radius; var rotationAngle = _chart.rotationAngle; var drawAngles = _chart.drawAngles; var absoluteAngles = _chart.absoluteAngles; var off = r / 10.0 * 3.0; if (drawHoleEnabled) { off = (r - (r * _chart.holeRadiusPercent)) / 2.0; } r -= off; // offset to keep things inside the chart var data: ChartData! = _chart.data; if (data === nil) { return; } var defaultValueFormatter = _chart.valueFormatter; var dataSets = data.dataSets; var drawXVals = drawXLabelsEnabled; var cnt = 0; for (var i = 0; i < dataSets.count; i++) { var dataSet = dataSets[i] as! PieChartDataSet; var drawYVals = dataSet.isDrawValuesEnabled; if (!drawYVals && !drawXVals) { continue; } var valueFont = dataSet.valueFont; var valueTextColor = dataSet.valueTextColor; var formatter = dataSet.valueFormatter; if (formatter === nil) { formatter = defaultValueFormatter; } var entries = dataSet.yVals; for (var j = 0, maxEntry = Int(min(ceil(CGFloat(entries.count) * _animator.phaseX), CGFloat(entries.count))); j < maxEntry; j++) { if (drawXVals && !drawYVals && (j >= data.xValCount || data.xVals[j] == nil)) { continue; } // offset needed to center the drawn text in the slice var offset = drawAngles[cnt] / 2.0; // calculate the text position var x = (r * cos(((rotationAngle + absoluteAngles[cnt] - offset) * _animator.phaseY) * ChartUtils.Math.FDEG2RAD) + center.x); var y = (r * sin(((rotationAngle + absoluteAngles[cnt] - offset) * _animator.phaseY) * ChartUtils.Math.FDEG2RAD) + center.y); var value = usePercentValuesEnabled ? entries[j].value / _chart.yValueSum * 100.0 : entries[j].value; var val = formatter!.stringFromNumber(value)!; var lineHeight = valueFont.lineHeight; y -= lineHeight; // draw everything, depending on settings if (drawXVals && drawYVals) { ChartUtils.drawText(context: context, text: val, point: CGPoint(x: x, y: y), align: .Center, attributes: [NSFontAttributeName: valueFont, NSForegroundColorAttributeName: valueTextColor]); if (j < data.xValCount && data.xVals[j] != nil) { ChartUtils.drawText(context: context, text: data.xVals[j]!, point: CGPoint(x: x, y: y + lineHeight), align: .Center, attributes: [NSFontAttributeName: valueFont, NSForegroundColorAttributeName: valueTextColor]); } } else if (drawXVals && !drawYVals) { ChartUtils.drawText(context: context, text: data.xVals[j]!, point: CGPoint(x: x, y: y + lineHeight / 2.0), align: .Center, attributes: [NSFontAttributeName: valueFont, NSForegroundColorAttributeName: valueTextColor]); } else if (!drawXVals && drawYVals) { ChartUtils.drawText(context: context, text: val, point: CGPoint(x: x, y: y + lineHeight / 2.0), align: .Center, attributes: [NSFontAttributeName: valueFont, NSForegroundColorAttributeName: valueTextColor]); } cnt++; } } } public override func drawExtras(#context: CGContext) { drawHole(context: context); drawCenterText(context: context); } /// draws the hole in the center of the chart and the transparent circle / hole private func drawHole(#context: CGContext) { if (_chart.drawHoleEnabled) { CGContextSaveGState(context); var radius = _chart.radius; var holeRadius = radius * holeRadiusPercent; var center = _chart.centerCircleBox; if (holeColor !== nil && holeColor != UIColor.clearColor()) { // draw the hole-circle CGContextSetFillColorWithColor(context, holeColor!.CGColor); CGContextFillEllipseInRect(context, CGRect(x: center.x - holeRadius, y: center.y - holeRadius, width: holeRadius * 2.0, height: holeRadius * 2.0)); } if (transparentCircleRadiusPercent > holeRadiusPercent) { var secondHoleRadius = radius * transparentCircleRadiusPercent; // make transparent CGContextSetFillColorWithColor(context, holeColor!.colorWithAlphaComponent(CGFloat(0x60) / CGFloat(0xFF)).CGColor); // draw the transparent-circle CGContextFillEllipseInRect(context, CGRect(x: center.x - secondHoleRadius, y: center.y - secondHoleRadius, width: secondHoleRadius * 2.0, height: secondHoleRadius * 2.0)); } CGContextRestoreGState(context); } } /// draws the description text in the center of the pie chart makes most sense when center-hole is enabled private func drawCenterText(#context: CGContext) { if (drawCenterTextEnabled && centerText != nil && centerText.lengthOfBytesUsingEncoding(NSUTF16StringEncoding) > 0) { var center = _chart.centerCircleBox; var innerRadius = drawHoleEnabled && holeTransparent ? _chart.radius * holeRadiusPercent : _chart.radius; var holeRect = CGRect(x: center.x - innerRadius, y: center.y - innerRadius, width: innerRadius * 2.0, height: innerRadius * 2.0); var boundingRect = holeRect; if (centerTextRadiusPercent > 0.0) { boundingRect = CGRectInset(boundingRect, (boundingRect.width - boundingRect.width * centerTextRadiusPercent) / 2.0, (boundingRect.height - boundingRect.height * centerTextRadiusPercent) / 2.0); } var centerTextNs = self.centerText as NSString; var paragraphStyle = NSParagraphStyle.defaultParagraphStyle().mutableCopy() as! NSMutableParagraphStyle; paragraphStyle.lineBreakMode = centerTextLineBreakMode; paragraphStyle.alignment = .Center; let drawingAttrs = [NSFontAttributeName: centerTextFont, NSParagraphStyleAttributeName: paragraphStyle, NSForegroundColorAttributeName: centerTextColor]; var textBounds = centerTextNs.boundingRectWithSize(boundingRect.size, options: .UsesLineFragmentOrigin | .UsesFontLeading | .TruncatesLastVisibleLine, attributes: drawingAttrs, context: nil); var drawingRect = boundingRect; drawingRect.origin.x += (boundingRect.size.width - textBounds.size.width) / 2.0; drawingRect.origin.y += (boundingRect.size.height - textBounds.size.height) / 2.0; drawingRect.size = textBounds.size; CGContextSaveGState(context); var clippingPath = CGPathCreateWithEllipseInRect(holeRect, nil); CGContextBeginPath(context); CGContextAddPath(context, clippingPath); CGContextClip(context); centerTextNs.drawWithRect(drawingRect, options: .UsesLineFragmentOrigin | .UsesFontLeading | .TruncatesLastVisibleLine, attributes: drawingAttrs, context: nil); CGContextRestoreGState(context); } } public override func drawHighlighted(#context: CGContext, indices: [ChartHighlight]) { if (_chart.data === nil) { return; } CGContextSaveGState(context); var rotationAngle = _chart.rotationAngle; var angle = CGFloat(0.0); var drawAngles = _chart.drawAngles; var absoluteAngles = _chart.absoluteAngles; var innerRadius = drawHoleEnabled && holeTransparent ? _chart.radius * holeRadiusPercent : 0.0; for (var i = 0; i < indices.count; i++) { // get the index to highlight var xIndex = indices[i].xIndex; if (xIndex >= drawAngles.count) { continue; } if (xIndex == 0) { angle = rotationAngle; } else { angle = rotationAngle + absoluteAngles[xIndex - 1]; } angle *= _animator.phaseY; var sliceDegrees = drawAngles[xIndex]; var set = _chart.data?.getDataSetByIndex(indices[i].dataSetIndex) as! PieChartDataSet!; if (set === nil) { continue; } var shift = set.selectionShift; var circleBox = _chart.circleBox; var highlighted = CGRect( x: circleBox.origin.x - shift, y: circleBox.origin.y - shift, width: circleBox.size.width + shift * 2.0, height: circleBox.size.height + shift * 2.0); CGContextSetFillColorWithColor(context, set.colorAt(xIndex).CGColor); // redefine the rect that contains the arc so that the highlighted pie is not cut off var startAngle = angle + set.sliceSpace / 2.0; var sweepAngle = sliceDegrees * _animator.phaseY - set.sliceSpace / 2.0; if (sweepAngle < 0.0) { sweepAngle = 0.0; } var endAngle = startAngle + sweepAngle; var path = CGPathCreateMutable(); CGPathMoveToPoint(path, nil, highlighted.midX, highlighted.midY); CGPathAddArc(path, nil, highlighted.midX, highlighted.midY, highlighted.size.width / 2.0, startAngle * ChartUtils.Math.FDEG2RAD, endAngle * ChartUtils.Math.FDEG2RAD, false); CGPathCloseSubpath(path); if (innerRadius > 0.0) { CGPathMoveToPoint(path, nil, highlighted.midX, highlighted.midY); CGPathAddArc(path, nil, highlighted.midX, highlighted.midY, innerRadius, startAngle * ChartUtils.Math.FDEG2RAD, endAngle * ChartUtils.Math.FDEG2RAD, false); CGPathCloseSubpath(path); } CGContextBeginPath(context); CGContextAddPath(context, path); CGContextEOFillPath(context); } CGContextRestoreGState(context); } }
apache-2.0
3131fcf27e58f769f4803130d9db1c2e
39.211735
237
0.551326
5.372188
false
false
false
false
sachin004/firefox-ios
Account/FirefoxAccountConfiguration.swift
6
5131
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation public enum FirefoxAccountConfigurationLabel: String { case LatestDev = "LatestDev" case StableDev = "StableDev" case Production = "Production" public func toConfiguration() -> FirefoxAccountConfiguration { switch self { case LatestDev: return LatestDevFirefoxAccountConfiguration() case StableDev: return StableDevFirefoxAccountConfiguration() case Production: return ProductionFirefoxAccountConfiguration() } } } /** * In the URLs below, service=sync ensures that we always get the keys with signin messages, * and context=fx_ios_v1 opts us in to the Desktop Sync postMessage interface. * * For the moment we add exclude_signup as a parameter to limit the UI; see Bug 1190097. */ public protocol FirefoxAccountConfiguration { init() var label: FirefoxAccountConfigurationLabel { get } /// A Firefox Account exists on a particular server. The auth endpoint should speak the protocol documented at /// https://github.com/mozilla/fxa-auth-server/blob/02f88502700b0c5ef5a4768a8adf332f062ad9bf/docs/api.md var authEndpointURL: NSURL { get } /// The associated oauth server should speak the protocol documented at /// https://github.com/mozilla/fxa-oauth-server/blob/6cc91e285fc51045a365dbacb3617ef29093dbc3/docs/api.md var oauthEndpointURL: NSURL { get } var profileEndpointURL: NSURL { get } /// The associated content server should speak the protocol implemented (but not yet documented) at /// https://github.com/mozilla/fxa-content-server/blob/161bff2d2b50bac86ec46c507e597441c8575189/app/scripts/models/auth_brokers/fx-desktop.js var signInURL: NSURL { get } var settingsURL: NSURL { get } var forceAuthURL: NSURL { get } var sync15Configuration: Sync15Configuration { get } } public struct LatestDevFirefoxAccountConfiguration: FirefoxAccountConfiguration { public init() { } public let label = FirefoxAccountConfigurationLabel.LatestDev public let authEndpointURL = NSURL(string: "https://latest.dev.lcip.org/auth/v1")! public let oauthEndpointURL = NSURL(string: "https://oauth-latest.dev.lcip.org")! public let profileEndpointURL = NSURL(string: "https://latest.dev.lcip.org/profile")! public let signInURL = NSURL(string: "https://latest.dev.lcip.org/signin?service=sync&context=fx_ios_v1")! public let settingsURL = NSURL(string: "https://latest.dev.lcip.org/settings?context=fx_ios_v1")! public let forceAuthURL = NSURL(string: "https://latest.dev.lcip.org/force_auth?service=sync&context=fx_ios_v1")! public let sync15Configuration: Sync15Configuration = StageSync15Configuration() } public struct StableDevFirefoxAccountConfiguration: FirefoxAccountConfiguration { public init() { } public let label = FirefoxAccountConfigurationLabel.StableDev public let authEndpointURL = NSURL(string: "https://stable.dev.lcip.org/auth/v1")! public let oauthEndpointURL = NSURL(string: "https://oauth-stable.dev.lcip.org")! public let profileEndpointURL = NSURL(string: "https://stable.dev.lcip.org/profile")! public let signInURL = NSURL(string: "https://stable.dev.lcip.org/signin?service=sync&context=fx_ios_v1")! public let settingsURL = NSURL(string: "https://stable.dev.lcip.org/settings?context=fx_ios_v1")! public let forceAuthURL = NSURL(string: "https://stable.dev.lcip.org/force_auth?service=sync&context=fx_ios_v1")! public let sync15Configuration: Sync15Configuration = StageSync15Configuration() } public struct ProductionFirefoxAccountConfiguration: FirefoxAccountConfiguration { public init() { } public let label = FirefoxAccountConfigurationLabel.Production public let authEndpointURL = NSURL(string: "https://api.accounts.firefox.com/v1")! public let oauthEndpointURL = NSURL(string: "https://oauth.accounts.firefox.com/v1")! public let profileEndpointURL = NSURL(string: "https://profile.accounts.firefox.com/v1")! public let signInURL = NSURL(string: "https://accounts.firefox.com/signin?service=sync&context=fx_ios_v1")! public let settingsURL = NSURL(string: "https://accounts.firefox.com/settings?context=fx_ios_v1")! public let forceAuthURL = NSURL(string: "https://accounts.firefox.com/force_auth?service=sync&context=fx_ios_v1")! public let sync15Configuration: Sync15Configuration = ProductionSync15Configuration() } public protocol Sync15Configuration { init() var tokenServerEndpointURL: NSURL { get } } public struct ProductionSync15Configuration: Sync15Configuration { public init() { } public let tokenServerEndpointURL = NSURL(string: "https://token.services.mozilla.com/1.0/sync/1.5")! } public struct StageSync15Configuration: Sync15Configuration { public init() { } public let tokenServerEndpointURL = NSURL(string: "https://token.stage.mozaws.net/1.0/sync/1.5")! }
mpl-2.0
23e9747038d3895c3b18c109124158dd
42.117647
145
0.743325
3.974438
false
true
false
false
zendobk/SwiftUtils
Sources/Classes/AlertController.swift
1
3224
// // UIAlertController.swift // TimorAir // // Created by DaoNV on 8/23/15. // Copyright © 2016 Asian Tech Co., Ltd. All rights reserved. // import UIKit public enum AlertLevel: Int { case low case normal case high case require } public protocol AlertLevelProtocol: class { var level: AlertLevel { get } func dismiss(animated: Bool, completion: (() -> Void)?) } open class AlertController: UIAlertController, AlertLevelProtocol { open var level = AlertLevel.normal open func addAction(_ title: String?, style: UIAlertAction.Style = UIAlertAction.Style.default, handler: (() -> Void)? = nil) { let actionHandler: ((UIAlertAction) -> Void)? = handler != nil ? { (action: UIAlertAction) -> Void in handler?() }: nil let action = UIAlertAction(title: title, style: style, handler: actionHandler) addAction(action) } // Recommend `present` method for AlertController instead of default is `presentViewController`. open func present(from: UIViewController? = nil, animated: Bool = true, completion: (() -> Void)? = nil) { if let from = from, from.isViewLoaded { if let popup = from.presentedViewController { if let vc = popup as? AlertLevelProtocol { if level > vc.level { vc.dismiss(animated: animated, completion: { () -> Void in self.present(from: from, animated: animated, completion: completion) }) } } else if level > .normal { popup.dismiss(animated: animated, completion: { () -> Void in self.present(from: from, animated: animated, completion: completion) }) } } else { from.present(self, animated: animated, completion: completion) } } else if let root = UIApplication.shared.delegate?.window??.rootViewController, root.isViewLoaded { present(from: root, animated: animated, completion: completion) } } open func dismiss(_ animated: Bool = true, completion: (() -> Void)? = nil) { self.dismiss(animated: animated, completion: completion) } open class func alertWithError(_ error: NSError, level: AlertLevel = .normal, handler: (() -> Void)? = nil) -> AlertController { let alert = AlertController( title: Bundle.main.name.localized(), message: error.localizedDescription.localized(), preferredStyle: .alert ) alert.addAction("OK".localized(), style: .cancel, handler: handler) return alert } } public func == (lhs: AlertLevel, rhs: AlertLevel) -> Bool { return lhs.rawValue == rhs.rawValue } public func > (lhs: AlertLevel, rhs: AlertLevel) -> Bool { return lhs.rawValue > rhs.rawValue } public func >= (lhs: AlertLevel, rhs: AlertLevel) -> Bool { return lhs.rawValue >= rhs.rawValue } public func < (lhs: AlertLevel, rhs: AlertLevel) -> Bool { return lhs.rawValue < rhs.rawValue } public func <= (lhs: AlertLevel, rhs: AlertLevel) -> Bool { return lhs.rawValue <= rhs.rawValue }
apache-2.0
a03272cde1555e1eb741f3f1f0d077e5
34.417582
132
0.604406
4.476389
false
false
false
false
zhaobin19918183/zhaobinCode
FamilyShop/FamilyShop/EndViewController/EndViewController.swift
1
3149
// // EndViewController.swift // NBALive // // Created by Zhao.bin on 16/10/11. // Copyright © 2016年 Zhao.bin. All rights reserved. // import UIKit import Alamofire import AlamofireImage class EndViewController: UIViewController,UITableViewDataSource,UITableViewDelegate { @IBOutlet weak var _tableview: UITableView! var EndDic0:[String:AnyObject]! var EndDic1:[String:AnyObject]! var EndDic:[String:AnyObject]! var EndArray0:[[String:AnyObject]]! var EndArray1:[[String:AnyObject]]! var EndArray:NSMutableArray! override func viewDidLoad() { super.viewDidLoad() //alamofireRequest() } override func viewDidAppear(_ animated: Bool) { alamofireRequest() } func alamofireRequest() { Alamofire.request("http://op.juhe.cn/onebox/basketball/nba?dtype=&=&key=a77b663959938859a741024f8cbb11ac").responseJSON { (data) in let dic = data.result.value as! [String:AnyObject] let arr = dic["result"]?["list"] as! [[String:AnyObject]] self.EndDic0 = arr[0] self.EndArray0 = self.EndDic0["tr"] as! [[String:AnyObject]] self.EndDic1 = arr[1] self.EndArray1 = self.EndDic1["tr"] as! [[String:AnyObject]] for index in 0...self.EndArray1.count - 1 { let dic = self.EndArray1[index] let status = dic["status"] as! NSNumber if status == 2 { self.EndArray0.append( self.EndArray1[index]) } } self._tableview.reloadData() } } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if self.EndArray0 == nil { return 0 } else { return self.EndArray0.count } } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let initIdentifier : String = "TableViewCellID" var cell : EndTableViewCell? = tableView.dequeueReusableCell(withIdentifier: initIdentifier) as? EndTableViewCell if cell == nil { let nibArray = Bundle.main.loadNibNamed("EndTableViewCell", owner: self, options: nil) cell = nibArray?.first as? EndTableViewCell } if self.EndDic0 != nil { cell?.endLiveAction(dic: self.EndDic0) cell?.endLiveDicAction(dic: self.EndArray0[indexPath.row] ,tableview:tableView) cell?.navigationController = self.navigationController } cell?.selectionStyle = UITableViewCellSelectionStyle.none return cell! } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 260 } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
gpl-3.0
6bc9353d97e96ffa3e8e4dfdaf975d48
27.6
139
0.580737
4.612903
false
false
false
false
AnnMic/FestivalArchitect
FestivalArchitect/Classes/Components/PhysicalNeedComponent.swift
1
677
// // VisitorComponent.swift // FestivalArchitect // // Created by Ann Michelsen on 12/11/14. // Copyright (c) 2014 AnnMi. All rights reserved. // import Foundation class PhysicalNeedComponent : Component { var fatigue:Int = 0 var thirst:Int = 0 var hunger:Int = 0 //hygiene //mental stuff //fun //social //personality //shy //sloppy //active init(fatigue:Int, thirst:Int, hunger:Int) { self.fatigue = fatigue self.thirst = thirst self.hunger = hunger } internal override class func name() -> String { return "PhysicalNeedComponent" } }
mit
1e991feff83e6a9a99053004016bb841
17.324324
51
0.577548
3.824859
false
false
false
false
icaksama/Weathersama
WeathersamaDemo/Pods/Weathersama/Weathersama/Weathersama/Models/Daily Forecast/DailyForecastListModel.swift
2
6495
// // DailyForecastListModel.swift // Weathersama // // Created by Saiful I. Wicaksana on 10/6/17. // Copyright © 2017 icaksama. All rights reserved. // import Foundation public class DailyForecastListModel { private let TAG = "DailyForecastListModel" public var dt: Int! public var pressure: Double! public var humidity: Int! public var speed: Double! public var deg: Int! public var clouds: Int! public var rain: Double! public var snow: Double! public var weather: [DailyForecastListWeather] = [DailyForecastListWeather]() public var temperature: DailyForecastListTemperature = DailyForecastListTemperature() internal func parseJSON(jsonArray: [[String: AnyObject]]) -> [DailyForecastListModel] { var dailyForecastLists: [DailyForecastListModel] = [DailyForecastListModel]() for jsonSerialized in jsonArray { let dailyForecastList: DailyForecastListModel = DailyForecastListModel() if let dt = jsonSerialized["dt"] as? Int { dailyForecastList.dt = dt } else { print("\(TAG) error : JSON parsing dt not found") } if let pressure = jsonSerialized["pressure"] as? Double { dailyForecastList.pressure = pressure } else { print("\(TAG) error : JSON parsing pressure not found") } if let humidity = jsonSerialized["humidity"] as? Int { dailyForecastList.humidity = humidity } else { print("\(TAG) error : JSON parsing humidity not found") } if let speed = jsonSerialized["speed"] as? Double { dailyForecastList.speed = speed } else { print("\(TAG) error : JSON parsing speed not found") } if let deg = jsonSerialized["deg"] as? Int { dailyForecastList.deg = deg } else { print("\(TAG) error : JSON parsing deg not found") } if let clouds = jsonSerialized["clouds"] as? Int { dailyForecastList.clouds = clouds } else { print("\(TAG) error : JSON parsing clouds not found") } if let rain = jsonSerialized["rain"] as? Double { dailyForecastList.rain = rain } else { print("\(TAG) error : JSON parsing rain not found") } if let snow = jsonSerialized["snow"] as? Double { dailyForecastList.snow = snow } else { print("\(TAG) error : JSON parsing snow not found") } if let weathers = jsonSerialized["weather"] as? [[String: AnyObject]] { for weather in weathers { let weatherClass = DailyForecastListWeather() if let id = weather["id"] as? Int { weatherClass.id = id } else { print("\(TAG) error : JSON parsing id not found") } if let main = weather["main"] as? String { weatherClass.main = main } else { print("\(TAG) error : JSON parsing main not found") } if let description = weather["description"] as? String { weatherClass.description = description } else { print("\(TAG) error : JSON parsing description not found") } if let icon = weather["icon"] as? String { weatherClass.icon = icon } else { print("\(TAG) error : JSON parsing icon not found") } dailyForecastList.weather.append(weatherClass) } } else { print("\(TAG) error : JSON parsing weather not found") } if let temperature = jsonSerialized["temp"] as? [String: AnyObject] { if let day = temperature["day"] as? Double { dailyForecastList.temperature.day = day } else { print("\(TAG) error : JSON parsing day not found") } if let min = temperature["min"] as? Double { dailyForecastList.temperature.min = min } else { print("\(TAG) error : JSON parsing min not found") } if let max = temperature["max"] as? Double { dailyForecastList.temperature.max = max } else { print("\(TAG) error : JSON parsing max not found") } if let night = temperature["night"] as? Double { dailyForecastList.temperature.night = night } else { print("\(TAG) error : JSON parsing night not found") } if let evening = temperature["eve"] as? Double { dailyForecastList.temperature.evening = evening } else { print("\(TAG) error : JSON parsing eve not found") } if let morning = temperature["morn"] as? Double { dailyForecastList.temperature.morning = morning } else { print("\(TAG) error : JSON parsing morn not found") } } else { print("\(TAG) error : JSON parsing temp not found") } dailyForecastLists.append(dailyForecastList) } return dailyForecastLists } } public class DailyForecastListWeather { public var id: Int! public var main: String! public var description: String! public var icon: String! } public class DailyForecastListTemperature { public var day: Double! public var min: Double! public var max: Double! public var night: Double! public var evening: Double! public var morning: Double! }
mit
d3f9cff3ecd2c4f2a91a2df41147038c
36.537572
91
0.489837
5.475548
false
false
false
false
chadsy/onebusaway-iphone
ui/alerts/AlertPresenter.swift
1
1155
// // AlertPresenter.swift // org.onebusaway.iphone // // Created by Aaron Brethorst on 8/28/16. // Copyright © 2016 OneBusAway. All rights reserved. // import UIKit import SwiftMessages @objc public class AlertPresenter: NSObject { public class func showWarning(title: String, body: String) { var config = SwiftMessages.Config() config.presentationContext = .Window(windowLevel: UIWindowLevelStatusBar) config.duration = .Seconds(seconds: 5) config.dimMode = .Gray(interactive: true) config.interactiveHide = true config.preferredStatusBarStyle = .LightContent // Instantiate a message view from the provided card view layout. SwiftMessages searches for nib // files in the main bundle first, so you can easily copy them into your project and make changes. let view = MessageView.viewFromNib(layout: .CardView) view.button?.hidden = true view.configureTheme(.Warning) view.configureDropShadow() view.configureContent(title: title, body: body) // Show the message. SwiftMessages.show(config: config, view: view) } }
apache-2.0
119dde7810840901788b89d604cfb65d
32.941176
106
0.689775
4.561265
false
true
false
false
Drusy/auvergne-webcams-ios
AuvergneWebcams/SearchViewController.swift
1
5119
// // SearchViewController.swift // AuvergneWebcams // // Created by Drusy on 20/02/2017. // // import UIKit class SearchViewController: AbstractRealmViewController { @IBOutlet var searchViewTopConstraint: NSLayoutConstraint! @IBOutlet var clearSearchButton: UIButton! @IBOutlet var collectionView: UICollectionView! @IBOutlet var searchLabel: UILabel! @IBOutlet var searchTextField: UITextField! { didSet { searchTextField.delegate = self } } lazy var provider: WebcamSectionViewProvider = { let provider = WebcamSectionViewProvider(collectionView: self.collectionView) provider.delegate = self return provider }() override func viewDidLoad() { super.viewDidLoad() collectionView.alwaysBounceVertical = true provider.itemSelectionHandler = { [weak self] webcam, indexPath in let webcamDetail = WebcamDetailViewController(webcam: webcam) self?.navigationController?.pushViewController(webcamDetail, animated: true) } searchTextField.becomeFirstResponder() search(text: nil) } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() if let navigationController = navigationController { var height = navigationController.navigationBar.bounds.height if !UIApplication.shared.isStatusBarHidden { height += UIApplication.shared.statusBarFrame.height } searchViewTopConstraint.constant = height } } // MARK: - override func translate() { super.translate() title = "Rechercher" searchTextField.attributedPlaceholder = "Rechercher une webcam" .withFont(UIFont.proximaNovaLightItalic(withSize: 16)) .withTextColor(UIColor.awLightGray) } func search(text: String?) { if let searchText = text, !searchText.isEmpty { clearSearchButton.isHidden = false let webcams = Array(WebcamManager.shared.webcams()) let searchResult = webcams.filter { webcam in let title = webcam.title ?? "" let tags = webcam.tags.filter { (webcamTag: WebcamTag) -> Bool in return webcamTag.tag.localizedCaseInsensitiveContains(searchText) } if !tags.isEmpty { return true } return title.localizedCaseInsensitiveContains(searchText) } provider.objects = searchResult var label: String if searchResult.isEmpty { label = "Aucun résultat pour " } else if searchResult.count == 1 { label = "1 résultat pour " } else { label = "\(searchResult.count) résultats pour " } let attributedResultText = label .withFont(UIFont.proximaNovaRegular(withSize: 16)) .withTextColor(UIColor.white) let attributedSearchText = searchText .withFont(UIFont.proximaNovaSemiBoldItalic(withSize: 16)) .withTextColor(UIColor.awBlue) attributedResultText.append(attributedSearchText) searchLabel.attributedText = attributedResultText } else { provider.objects = [] searchLabel.text = nil clearSearchButton.isHidden = true } } // MARK: - IBActions @IBAction func onEditingDidBegin(_ sender: Any) { clearSearchButton.isHidden = false } @IBAction func onEditingDidEnd(_ sender: Any) { guard let text = searchTextField.text, !text.isEmpty else { return } AnalyticsManager.logEvent(searchText: text) } @IBAction func onSearchEditingChanged(_ sender: Any) { guard let searchText = searchTextField.text else { return } search(text: searchText) } @IBAction func onClearSearchTouched(_ sender: Any) { searchTextField.text = nil searchTextField.resignFirstResponder() clearSearchButton.isHidden = true search(text: nil) } } // MARK: - WebcamCarouselViewProviderDelegate extension SearchViewController: WebcamSectionViewProviderDelegate { func webcamSection(viewProvider: WebcamSectionViewProvider, scrollViewDidScroll scrollView: UIScrollView) { if searchTextField.isEditing { searchTextField.endEditing(true) } } } // MARK: - UITextFieldDelegate extension SearchViewController: UITextFieldDelegate { func textFieldShouldReturn(_ textField: UITextField) -> Bool { guard let searchText = textField.text else { return true } textField.resignFirstResponder() search(text: searchText) return true } }
apache-2.0
03235fcfd60bc80476d0f4badc0432d5
30.386503
111
0.601837
5.591257
false
false
false
false
evestorm/SWWeather
SWWeather/SWWeather/Classes/Tools/pch.swift
1
2645
// // pch.swift // SWWeather // // Created by Mac on 16/7/30. // Copyright © 2016年 Mac. All rights reserved. // import UIKit // 百度AK let BAIDUAK = "5knAwtLP2VvgPv7hZMs9aQtn" // 百度天气api示例 var API:String = "http://api.map.baidu.com/telematics/v3/weather?location=CITYNAME&output=json&ak=5knAwtLP2VvgPv7hZMs9aQtn" //屏幕宽度和高度、导航栏高度 let SCREEN_WIDTH = UIScreen.mainScreen().bounds.size.width let SCREEN_HEIGHT = UIScreen.mainScreen().bounds.size.height let NavigationHeight:CGFloat = 64 let tabBarHeight:CGFloat = 44 /** 根据天气选择图片名称 - parameter name: 天气 - returns: 返回对应天气图片名称 */ public func stringByWeather(name:String) -> String { // 1. 得到传过来的天气信息 let getName = name var needIconName = "" // 2. 对其进行筛选 switch getName { case "晴": needIconName = "weather_sun" break case "多云","阴": needIconName = "weather_cloud" break case "阵雨","雷阵雨","雷阵雨伴有冰雹": needIconName = "weather_hail" break case "雨夹雪": needIconName = "weather_mistyrain" break case "小雨": needIconName = "weather_mistyrain" break case "中雨","冻雨","小雨转中雨": needIconName = "weather_rain" break case "大雨","暴雨","大暴雨","特大暴雨","中雨转大雨","大雨转暴雨","暴雨转大暴雨","大暴雨转特大暴雨": needIconName = "weather_storm-11" break case "阵雪","小雪": needIconName = "weather_cloud_snowflake" break case "中雪","小雪转中雪": needIconName = "weather_snow" break case "大雪","暴雪","中雪转大雪","大雪转暴雪": needIconName = "weather_snowflake" break case "雾": needIconName = "weather_fog" break case "沙尘暴","强沙尘暴": needIconName = "weather_aquarius" break case "浮尘","扬沙": needIconName = "weather_windgust" break case "霾": needIconName = "weather_cancer" break default: if (getName.rangeOfString("雨") != nil) { needIconName = "weather_rain" } else if (getName.rangeOfString("云") != nil) { needIconName = "weather_cloud" } else if (getName.rangeOfString("雪") != nil) { needIconName = "weather_snow" } else { needIconName = "weather_aries" } } //let needIconName = "weather_cloud_drop" return needIconName }
mit
650c9c573610db8e7d2e99bc7e05fd32
24.406593
123
0.588235
2.94898
false
false
false
false
pmlbrito/cookiecutter-ios-template
PRODUCTNAME/app/PRODUCTNAME/Domain/KeyChainAccess/KeyChainAccessManager.swift
1
1576
// // KeyChainAccessManager.swift // PRODUCTNAME // // Created by LEADDEVELOPER on 06/09/2017. // Copyright © 2017 ORGANIZATION. All rights reserved. // import Foundation import KeychainAccess struct KeyChainAccessManagerKeys { static let keychainServiceIdentifier = "KeyChainAccessManager" } open class KeyChainAccessManager { var keychain = Keychain(service: BuildType.active.identifier(suffix: KeyChainAccessManagerKeys.keychainServiceIdentifier)) func getUserLoginCredentials(username: String) -> SignInUserCredentials { var userLogin: SignInUserCredentials = SignInUserCredentials(userName: username, password: nil) do { let userPassword = try keychain.getString(username) if userPassword != nil { userLogin.password = userPassword } } catch let error { Log.error("Error getting user login credentials to keychain: \(error.localizedDescription)") } return userLogin } func saveUserLoginCredentials(credentials: SignInUserCredentials) { do { if credentials.userName != nil { if credentials.password != nil { try keychain.set(credentials.password!, key: credentials.userName!) } else { try keychain.remove(credentials.userName!) } } } catch let error { Log.error("Error setting user login credentials to keychain: \(error.localizedDescription)") } } }
mit
0e782fd0fcb84eb3fe79da8852d30c48
29.882353
126
0.634921
5.46875
false
false
false
false
haskellswift/swift-package-manager
Sources/SourceControl/Repository.swift
1
7036
/* This source file is part of the Swift.org open source project Copyright 2016 Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for Swift project authors */ import Basic /// Specifies a repository address. public struct RepositorySpecifier: Hashable { /// The URL of the repository. public let url: String /// Create a specifier. public init(url: String) { self.url = url } /// A unique identifier for this specifier. /// /// This identifier is suitable for use in a file system path, and /// unique for each repository. public var fileSystemIdentifier: String { // FIXME: Need to do something better here. In particular, we should use // a stable hash function since this interacts with the RepositoryManager // persistence. let basename = url.components(separatedBy: "/").last! return basename + "-" + String(url.hashValue) } public var hashValue: Int { return url.hashValue } } public func ==(lhs: RepositorySpecifier, rhs: RepositorySpecifier) -> Bool { return lhs.url == rhs.url } /// A repository provider. /// /// This protocol defines the lower level interface used to to access /// repositories. High-level clients should access repositories via a /// `RepositoryManager`. public protocol RepositoryProvider { /// Fetch the complete repository at the given location to `path`. /// /// - Throws: If there is an error fetching the repository. func fetch(repository: RepositorySpecifier, to path: AbsolutePath) throws /// Open the given repository. /// /// - Parameters: /// - repository: The specifier for the repository. /// - path: The location of the repository on disk, at which the /// repository has previously been created via `fetch`. /// - Throws: If the repository is unable to be opened. func open(repository: RepositorySpecifier, at path: AbsolutePath) throws -> Repository /// Clone a managed repository into a working copy at on the local file system. /// /// Once complete, the repository can be opened using `openCheckout`. /// /// - Parameters: /// - sourcePath: The location of the repository on disk, at which the /// repository has previously been created via `fetch`. /// - destinationPath: The path at which to create the working copy; it is /// expected to be non-existent when called. /// - editable: The checkout is expected to be edited by users. func cloneCheckout(repository: RepositorySpecifier, at sourcePath: AbsolutePath, to destinationPath: AbsolutePath, editable: Bool) throws /// Open a working repository copy. /// /// - Parameters: /// - path: The location of the repository on disk, at which the /// repository has previously been created via `cloneCheckout`. func openCheckout(at path: AbsolutePath) throws -> WorkingCheckout } /// Abstract repository operations. /// /// This interface provides access to an abstracted representation of a /// repository which is ultimately owned by a `RepositoryManager`. This interface /// is designed in such a way as to provide the minimal facilities required by /// the package manager to gather basic information about a repository, but it /// does not aim to provide all of the interfaces one might want for working /// with an editable checkout of a repository on disk. /// /// The goal of this design is to allow the `RepositoryManager` a large degree of /// flexibility in the storage and maintenance of its underlying repositories. /// /// This protocol is designed under the assumption that the repository can only /// be mutated via the functions provided here; thus, e.g., `tags` is expected /// to be unchanged through the lifetime of an instance except as otherwise /// documented. The behavior when this assumption is violated is undefined, /// although the expectation is that implementations should throw or crash when /// an inconsistency can be detected. public protocol Repository { /// Get the list of tags in the repository. var tags: [String] { get } /// Resolve the revision for a specific tag. /// /// - Precondition: The `tag` should be a member of `tags`. /// - Throws: If a error occurs accessing the named tag. func resolveRevision(tag: String) throws -> Revision /// Fetch and update the repository from its remote. /// /// - Throws: If an error occurs while performing the fetch operation. func fetch() throws /// Open an immutable file system view for a particular revision. /// /// This view exposes the contents of the repository at the given revision /// as a file system rooted inside the repository. The repository must /// support opening multiple views concurrently, but the expectation is that /// clients should be prepared for this to be inefficient when performing /// interleaved accesses across separate views (i.e., the repository may /// back the view by an actual file system representation of the /// repository). /// /// It is expected behavior that attempts to mutate the given FileSystem /// will fail or crash. /// /// - Throws: If a error occurs accessing the revision. func openFileView(revision: Revision) throws -> FileSystem } /// An editable checkout of a repository (i.e. a working copy) on the local file /// system. public protocol WorkingCheckout { /// Get the list of tags in the repository. var tags: [String] { get } /// Get the current revision. func getCurrentRevision() throws -> Revision /// Fetch and update the repository from its remote. /// /// - Throws: If an error occurs while performing the fetch operation. func fetch() throws /// Query whether the checkout has any commits which are not pushed to its remote. func hasUnpushedCommits() throws -> Bool /// This check for any modified state of the repository and returns true /// if there are uncommited changes. func hasUncommitedChanges() -> Bool /// Check out the given tag. func checkout(tag: String) throws /// Check out the given revision. func checkout(revision: Revision) throws } /// A single repository revision. public struct Revision: Equatable { /// A precise identifier for a single repository revision, in a repository-specified manner. /// /// This string is intended to be opaque to the client, but understandable /// by a user. For example, a Git repository might supply the SHA1 of a /// commit, or an SVN repository might supply a string such as 'r123'. public let identifier: String public init(identifier: String) { self.identifier = identifier } } public func ==(lhs: Revision, rhs: Revision) -> Bool { return lhs.identifier == rhs.identifier }
apache-2.0
865a3a92e762f725c52914cf973cf1a9
38.977273
141
0.696703
4.829101
false
false
false
false
nsagora/validation-kit
Sources/Helpers/AsyncOperation.swift
1
2139
import Foundation extension AsyncConstraintSet { class AsyncOperation<T>: Operation { enum State { case ready case executing case finished var keyPath: String { switch self { case .ready: return "isReady" case .executing: return "isExecuting" case .finished: return "isFinished" } } } private let constraint: AnyAsyncConstraint<T> private let input: T private var workQueue: DispatchQueue { return DispatchQueue(label: "com.nsagora.validation-toolkit.async-operation", attributes: .concurrent) } private var state: State = .ready { willSet { willChangeValue(forKey: newValue.keyPath) } didSet { didChangeValue(forKey: state.keyPath) } } var result: ValidationResult? init(input: T, constraint: AnyAsyncConstraint<T>) { self.input = input self.constraint = constraint super.init() self.qualityOfService = .userInitiated } override var isReady: Bool { return state == .ready && super.isReady } override var isExecuting: Bool { return state == .executing } override var isFinished: Bool { return state == .finished } override var isAsynchronous: Bool { return true } override func start() { super.start() if (isCancelled) { return finish() } state = .executing execute() } func execute() { constraint.evaluate(with: input, queue: workQueue) { result in self.result = result self.finish() } } internal func finish() { state = .finished } } }
apache-2.0
b2c2eb714c595baf2387f2b8bccbdf02
23.586207
114
0.473118
5.925208
false
false
false
false
heitorgcosta/Quiver
Quiver/Validating/ValidatorEngine.swift
1
3203
// // ValidatorEngine.swift // Quiver // // Created by Heitor Costa on 22/09/17. // Copyright © 2017 Heitor Costa. All rights reserved. // internal protocol IsOptional {} extension Optional: IsOptional {} class ValidatorEngine<T> where T: Validatable { private(set) var mapper: ValidatorMapper private(set) var validatableSubject: T init(mapper: ValidatorMapper, validatableSubject: T) { self.mapper = mapper self.validatableSubject = validatableSubject } func performValidations() -> ValidatorResult { validatableSubject.validations(with: mapper) let keyPaths = mapper.keyPaths var errorItems: [ValidationErrorItem] = [] for keyPath in keyPaths { let validators = mapper[keyPath] let unit = ValidatorEngineUnit(object: validatableSubject, keyPath: keyPath, validators: validators) errorItems.append(contentsOf: unit.results()) } return ValidatorResult(success: errorItems.count == 0, error: errorItems.count == 0 ? nil : ValidationError(items: errorItems)) } } class ValidatorEngineUnit { private(set) var object: Any private(set) var keyPath: AnyKeyPath private(set) var validators: [Validator] init(object: Any, keyPath: AnyKeyPath, validators: [Validator]) { self.object = object self.keyPath = keyPath self.validators = validators } func results() -> [ValidationErrorItem] { var errorItems: [ValidationErrorItem] = [] for validator in validators { let wrappedValue = object[keyPath: keyPath] if wrappedValue == nil { fatalError("Invalid keypath for object of type '\(type(of: object))'. Check if all keypaths in the 'validations(with:)' are correct.") } let unwrappedValue = wrappedValue! var value: Any? if unwrappedValue is IsOptional { if let (_, any) = Mirror(reflecting: unwrappedValue).children.first { value = any as Any } } else { value = unwrappedValue as Any } do { let result = try validator.validate(with: value) if !result { errorItems.append(ValidationErrorItem(message: validator.message, type: .validation(value: value), keyPath: keyPath)) } } catch let error as ValidationErrorType { errorItems.append(ValidationErrorItem(message: validator.message, type: error, keyPath: keyPath)) } catch let error { fatalError("Unknown error occurred during validation: \(error.localizedDescription). Check if any validators are throwning errors other than ValidationErrorType.") } } return errorItems } }
mit
ee617083af373abee8cbe566fb761ef8
35.804598
179
0.558089
5.454855
false
false
false
false
magi82/MGRelativeKit
Sources/RelativeLayout.swift
1
2283
// The MIT License (MIT) // // Copyright (c) 2017 ByungKook Hwang (https://magi82.github.io) // // 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 enum LayoutChangeType { case leftOf case rightOf case topOf case bottomOf case alignLeft case alignRight case alignTop case alignBottom case alignSuperLeft case alignSuperRight case alignSuperTop case alignSuperBottom } public class RelativeLayout { weak var myView: UIView? var layoutChanged: Set<LayoutChangeType> init(_ view: UIView) { self.myView = view self.layoutChanged = [] } public func apply() { self.layoutChanged.removeAll() } } private var RelativeLayoutKey: Int = 0 extension UIView { public var relativeLayout: RelativeLayout { return _relativeLayoutValue } var _relativeLayoutValue: RelativeLayout { get { if let value = objc_getAssociatedObject(self, &RelativeLayoutKey) as? RelativeLayout { return value } let layout = RelativeLayout(self) self._relativeLayoutValue = layout return layout } set { objc_setAssociatedObject(self, &RelativeLayoutKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } }
mit
2708c7536ef15391d257652e43789902
27.5375
81
0.725799
4.398844
false
false
false
false
MaxHasADHD/TraktKit
Common/Wrapper/Enums.swift
1
8788
// // Enums.swift // TraktKit // // Created by Maximilian Litteral on 6/22/16. // Copyright © 2016 Maximilian Litteral. All rights reserved. // import Foundation public enum Method: String { /// Select one or more items. Success returns 200 status code. case GET /// Create a new item. Success returns 201 status code. case POST /// Update an item. Success returns 200 status code. case PUT /// Delete an item. Success returns 200 or 204 status code. case DELETE } public struct StatusCodes { /// Success public static let Success = 200 /// Success - new resource created (POST) public static let SuccessNewResourceCreated = 201 /// Success - no content to return (DELETE) public static let SuccessNoContentToReturn = 204 /// Bad Request - request couldn't be parsed public static let BadRequest = 400 /// Unauthorized - OAuth must be provided public static let Unauthorized = 401 /// Forbidden - invalid API key or unapproved app public static let Forbidden = 403 /// Not Found - method exists, but no record found public static let NotFound = 404 /// Method Not Found - method doesn't exist public static let MethodNotFound = 405 /// Conflict - resource already created public static let Conflict = 409 /// Precondition Failed - use application/json content type public static let PreconditionFailed = 412 /// Account Limit Exceeded - list count, item count, etc public static let AccountLimitExceeded = 420 /// Unprocessable Entity - validation errors public static let UnprocessableEntity = 422 /// Trakt account locked. Have user contact Trakt https://github.com/trakt/api-help/issues/228 public static let acountLocked = 423 /// VIP Only - user must upgrade to VIP public static let vipOnly = 426 /// Rate Limit Exceeded public static let RateLimitExceeded = 429 /// Server Error public static let ServerError = 500 /// Service Unavailable - Cloudflare error public static let CloudflareError = 520 /// Service Unavailable - Cloudflare error public static let CloudflareError2 = 521 /// Service Unavailable - Cloudflare error public static let CloudflareError3 = 522 static func message(for status: Int) -> String? { switch status { case Unauthorized: return "App not authorized. Please sign in again." case Forbidden: return "Invalid API Key" case NotFound: return "API not found" case AccountLimitExceeded: return "The number of Trakt lists or list items has been exceeded. Please see Trakt.tv for account limits and support." case acountLocked: return "Trakt.tv has indicated that this account is locked. Please contact Trakt support to unlock your account." case vipOnly: return "This feature is VIP only with Trakt. Please see Trakt.tv for more information." case RateLimitExceeded: return "Rate Limit Exceeded. Please try again in a minute." case ServerError..<CloudflareError: return "Trakt.tv is down. Please try again later." case CloudflareError..<600: return "CloudFlare error. Please try again later." default: return nil } } } /// What to search for public enum SearchType: String { case movie case show case episode case person case list public struct Field { public let title: String } public struct Fields { public struct Movie { public static let title = Field(title: "title") public static let tagline = Field(title: "tagline") public static let overview = Field(title: "overview") public static let people = Field(title: "people") public static let translations = Field(title: "translations") public static let aliases = Field(title: "aliases") } public struct Show { public static let title = Field(title: "title") public static let overview = Field(title: "overview") public static let people = Field(title: "people") public static let translations = Field(title: "translations") public static let aliases = Field(title: "aliases") } public struct Episode { public static let title = Field(title: "title") public static let overview = Field(title: "overview") } public struct Person { public static let name = Field(title: "name") public static let biography = Field(title: "biography") } public struct List { public static let name = Field(title: "name") public static let description = Field(title: "description") } } } /// Type of ID used for look up public enum LookupType { case Trakt(id: NSNumber) case IMDB(id: String) case TMDB(id: NSNumber) case TVDB(id: NSNumber) case TVRage(id: NSNumber) var name: String { switch self { case .Trakt: return "trakt" case .IMDB: return "imdb" case .TMDB: return "tmdb" case .TVDB: return "tvdb" case .TVRage: return "tvrage" } } var id: String { switch self { case .Trakt(let id): return "\(id)" case .IMDB(let id): return id case .TMDB(let id): return "\(id)" case .TVDB(let id): return "\(id)" case .TVRage(let id): return "\(id)" } } } public enum MediaType: String, CustomStringConvertible { case movies, shows public var description: String { return self.rawValue } } public enum WatchedType: String, CustomStringConvertible { case Movies = "movies" case Shows = "shows" case Seasons = "seasons" case Episodes = "episodes" public var description: String { return self.rawValue } } public enum Type2: String, CustomStringConvertible { case All = "all" case Movies = "movies" case Shows = "shows" case Seasons = "seasons" case Episodes = "episodes" case Lists = "lists" public var description: String { return self.rawValue } } public enum ListType: String, CustomStringConvertible { case all case personal case official case watchlists public var description: String { return self.rawValue } } public enum ListSortType: String, CustomStringConvertible { case popular case likes case comments case items case added case updated public var description: String { return self.rawValue } } /// Type of comments public enum CommentType: String { case all = "all" case reviews = "reviews" case shouts = "shouts" } /// Extended information public enum ExtendedType: String, CustomStringConvertible { /// Least amount of info case Min = "min" /// All information, excluding images case Full = "full" /// Collection only. Additional video and audio info. case Metadata = "metadata" /// Get all seasons and episodes case Episodes = "episodes" /// Get watched shows without seasons. https://trakt.docs.apiary.io/#reference/users/watched/get-watched case noSeasons = "noseasons" /// For the show and season `/people` methods. case guestStars = "guest_stars" public var description: String { return self.rawValue } } extension Sequence where Iterator.Element: CustomStringConvertible { func queryString() -> String { return self.map { $0.description }.joined(separator: ",") // Search with multiple types } } /// Possible values for items in Lists public enum ListItemType: String { case movies = "movie" case shows = "show" case seasons = "season" case episodes = "episode" case people = "person" } public enum Period: String { case Weekly = "weekly" case Monthly = "monthly" case All = "all" } public enum SectionType: String { /// Can hide movie, show objects case Calendar = "calendar" /// Can hide show, season objects case ProgressWatched = "progress_watched" /// Can hide show, season objects case ProgressCollected = "progress_collected" /// Can hide movie, show objects case Recommendations = "recommendations" } public enum HiddenItemsType: String { case Movie = "movie" case Show = "show" case Season = "Season" } public enum LikeType: String { case Comments = "comments" case Lists = "lists" }
mit
648ae022335c774a8fb3241d393aa877
28.585859
131
0.631501
4.627172
false
false
false
false
ben-ng/swift
test/IRGen/objc_bridge.swift
7
10888
// RUN: rm -rf %t && mkdir -p %t // RUN: %build-irgen-test-overlays // RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -emit-ir -primary-file %s | %FileCheck %s // REQUIRES: CPU=x86_64 // REQUIRES: objc_interop import Foundation // CHECK: [[GETTER_SIGNATURE:@.*]] = private unnamed_addr constant [8 x i8] c"@16@0:8\00" // CHECK: [[SETTER_SIGNATURE:@.*]] = private unnamed_addr constant [11 x i8] c"v24@0:8@16\00" // CHECK: [[DEALLOC_SIGNATURE:@.*]] = private unnamed_addr constant [8 x i8] c"v16@0:8\00" // CHECK: @_INSTANCE_METHODS__TtC11objc_bridge3Bas = private constant { i32, i32, [17 x { i8*, i8*, i8* }] } { // CHECK: i32 24, // CHECK: i32 17, // CHECK: [17 x { i8*, i8*, i8* }] [ // CHECK: { i8*, i8*, i8* } { // CHECK: i8* getelementptr inbounds ([12 x i8], [12 x i8]* @"\01L_selector_data(strRealProp)", i64 0, i64 0), // CHECK: i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[GETTER_SIGNATURE]], i64 0, i64 0), // CHECK: i8* bitcast ([[OPAQUE:.*]]* ([[OPAQUE:.*]]*, i8*)* @_TToFC11objc_bridge3Basg11strRealPropSS to i8*) // CHECK: }, // CHECK: { i8*, i8*, i8* } { // CHECK: i8* getelementptr inbounds ([16 x i8], [16 x i8]* @"\01L_selector_data(setStrRealProp:)", i64 0, i64 0), // CHECK: i8* getelementptr inbounds ([11 x i8], [11 x i8]* [[SETTER_SIGNATURE]], i64 0, i64 0), // CHECK: i8* bitcast (void ([[OPAQUE:.*]]*, i8*, [[OPAQUE:.*]]*)* @_TToFC11objc_bridge3Bass11strRealPropSS to i8*) // CHECK: }, // CHECK: { i8*, i8*, i8* } { // CHECK: i8* getelementptr inbounds ([12 x i8], [12 x i8]* @"\01L_selector_data(strFakeProp)", i64 0, i64 0), // CHECK: i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[GETTER_SIGNATURE]], i64 0, i64 0), // CHECK: i8* bitcast ([[OPAQUE:.*]]* ([[OPAQUE:.*]]*, i8*)* @_TToFC11objc_bridge3Basg11strFakePropSS to i8*) // CHECK: }, // CHECK: { i8*, i8*, i8* } { // CHECK: i8* getelementptr inbounds ([16 x i8], [16 x i8]* @"\01L_selector_data(setStrFakeProp:)", i64 0, i64 0), // CHECK: i8* getelementptr inbounds ([11 x i8], [11 x i8]* [[SETTER_SIGNATURE]], i64 0, i64 0), // CHECK: i8* bitcast (void ([[OPAQUE:.*]]*, i8*, [[OPAQUE:.*]]*)* @_TToFC11objc_bridge3Bass11strFakePropSS to i8*) // CHECK: }, // CHECK: { i8*, i8*, i8* } { // CHECK: i8* getelementptr inbounds ([14 x i8], [14 x i8]* @"\01L_selector_data(nsstrRealProp)", i64 0, i64 0), // CHECK: i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[GETTER_SIGNATURE]], i64 0, i64 0), // CHECK: i8* bitcast ([[OPAQUE:.*]]* ([[OPAQUE:.*]]*, i8*)* @_TToFC11objc_bridge3Basg13nsstrRealPropCSo8NSString to i8*) // CHECK: }, // CHECK: { i8*, i8*, i8* } { // CHECK: i8* getelementptr inbounds ([18 x i8], [18 x i8]* @"\01L_selector_data(setNsstrRealProp:)", i64 0, i64 0), // CHECK: i8* getelementptr inbounds ([11 x i8], [11 x i8]* [[SETTER_SIGNATURE]], i64 0, i64 0), // CHECK: i8* bitcast (void ([[OPAQUE:.*]]*, i8*, [[OPAQUE:.*]]*)* @_TToFC11objc_bridge3Bass13nsstrRealPropCSo8NSString to i8*) // CHECK: }, // CHECK: { i8*, i8*, i8* } { // CHECK: i8* getelementptr inbounds ([14 x i8], [14 x i8]* @"\01L_selector_data(nsstrFakeProp)", i64 0, i64 0), // CHECK: i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[GETTER_SIGNATURE]], i64 0, i64 0), // CHECK: i8* bitcast ([[OPAQUE:.*]]* ([[OPAQUE:.*]]*, i8*)* @_TToFC11objc_bridge3Basg13nsstrFakePropCSo8NSString to i8*) // CHECK: }, // CHECK: { i8*, i8*, i8* } { // CHECK: i8* getelementptr inbounds ([18 x i8], [18 x i8]* @"\01L_selector_data(setNsstrFakeProp:)", i64 0, i64 0), // CHECK: i8* getelementptr inbounds ([11 x i8], [11 x i8]* [[SETTER_SIGNATURE]], i64 0, i64 0), // CHECK: i8* bitcast (void ([[OPAQUE:.*]]*, i8*, [[OPAQUE:.*]]*)* @_TToFC11objc_bridge3Bass13nsstrFakePropCSo8NSString to i8*) // CHECK: }, // CHECK: { i8*, i8*, i8* } { // CHECK: i8* getelementptr inbounds ([10 x i8], [10 x i8]* @"\01L_selector_data(strResult)", i64 0, i64 0), // CHECK: i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[GETTER_SIGNATURE]], i64 0, i64 0), // CHECK: i8* bitcast ([[OPAQUE:.*]]* ([[OPAQUE:.*]]*, i8*)* @_TToFC11objc_bridge3Bas9strResultfT_SS to i8*) // CHECK: }, // CHECK: { i8*, i8*, i8* } { // CHECK: i8* getelementptr inbounds ([{{[0-9]*}} x i8], [{{[0-9]*}} x i8]* @"\01L_selector_data(strArgWithS:)", i64 0, i64 0), // CHECK: i8* getelementptr inbounds ([11 x i8], [11 x i8]* [[SETTER_SIGNATURE]], i64 0, i64 0), // CHECK: i8* bitcast (void ([[OPAQUE:.*]]*, i8*, [[OPAQUE:.*]]*)* @_TToFC11objc_bridge3Bas6strArgfT1sSS_T_ to i8*) // CHECK: }, // CHECK: { i8*, i8*, i8* } { // CHECK: i8* getelementptr inbounds ([12 x i8], [12 x i8]* @"\01L_selector_data(nsstrResult)", i64 0, i64 0), // CHECK: i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[GETTER_SIGNATURE]], i64 0, i64 0), // CHECK: i8* bitcast ([[OPAQUE:.*]]* ([[OPAQUE:.*]]*, i8*)* @_TToFC11objc_bridge3Bas11nsstrResultfT_CSo8NSString to i8*) // CHECK: }, // CHECK: { i8*, i8*, i8* } { // CHECK: i8* getelementptr inbounds ([{{[0-9]+}} x i8], [{{[0-9]+}} x i8]* @"\01L_selector_data(nsstrArgWithS:)", i64 0, i64 0), // CHECK: i8* getelementptr inbounds ([11 x i8], [11 x i8]* [[SETTER_SIGNATURE]], i64 0, i64 0), // CHECK: i8* bitcast (void ([[OPAQUE:.*]]*, i8*, [[OPAQUE:.*]]*)* @_TToFC11objc_bridge3Bas8nsstrArgfT1sCSo8NSString_T_ to i8*) // CHECK: }, // CHECK: { i8*, i8*, i8* } { // CHECK: i8* getelementptr inbounds ([5 x i8], [5 x i8]* @"\01L_selector_data(init)", i64 0, i64 0), // CHECK: i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[GETTER_SIGNATURE]], i64 0, i64 0), // CHECK: i8* bitcast ([[OPAQUE:.*]]* ([[OPAQUE:.*]]*, i8*)* @_TToFC11objc_bridge3BascfT_S0_ to i8*) // CHECK: }, // CHECK: { i8*, i8*, i8* } { // CHECK: i8* getelementptr inbounds ([8 x i8], [8 x i8]* @"\01L_selector_data(dealloc)", i64 0, i64 0), // CHECK: i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[DEALLOC_SIGNATURE]], i64 0, i64 0), // CHECK: i8* bitcast (void ([[OPAQUE:.*]]*, i8*)* @_TToFC11objc_bridge3BasD to i8*) // CHECK: }, // CHECK: { i8*, i8*, i8* } { // CHECK: i8* getelementptr inbounds ([11 x i8], [11 x i8]* @"\01L_selector_data(acceptSet:)", i64 0, i64 0), // CHECK: i8* getelementptr inbounds ([11 x i8], [11 x i8]* @{{[0-9]+}}, i64 0, i64 0), // CHECK: i8* bitcast (void (%3*, i8*, %4*)* @_TToFC11objc_bridge3Bas9acceptSetfGVs3SetS0__T_ to i8*) // CHECK: } // CHECK: { i8*, i8*, i8* } { // CHECK: i8* getelementptr inbounds ([14 x i8], [14 x i8]* @"\01L_selector_data(.cxx_destruct)", i64 0, i64 0), // CHECK: i8* getelementptr inbounds ([3 x i8], [3 x i8]* @{{.*}}, i64 0, i64 0), // CHECK: i8* bitcast (void ([[OPAQUE:.*]]*, i8*)* @_TToFC11objc_bridge3BasE to i8*) // CHECK: } // CHECK: ] // CHECK: }, section "__DATA, __objc_const", align 8 // CHECK: @_PROPERTIES__TtC11objc_bridge3Bas = private constant { i32, i32, [5 x { i8*, i8* }] } { // CHECK: [[OBJC_BLOCK_PROPERTY:@.*]] = private unnamed_addr constant [11 x i8] c"T@?,N,C,Vx\00" // CHECK: @_PROPERTIES__TtC11objc_bridge21OptionalBlockProperty = private constant {{.*}} [[OBJC_BLOCK_PROPERTY]] func getDescription(_ o: NSObject) -> String { return o.description } func getUppercaseString(_ s: NSString) -> String { return s.uppercase() } // @interface Foo -(void) setFoo: (NSString*)s; @end func setFoo(_ f: Foo, s: String) { f.setFoo(s) } // NSString *bar(int); func callBar() -> String { return bar(0) } // void setBar(NSString *s); func callSetBar(_ s: String) { setBar(s) } var NSS : NSString = NSString() // -- NSString methods don't convert 'self' extension NSString { // CHECK: define internal [[OPAQUE:.*]]* @_TToFE11objc_bridgeCSo8NSStringg13nsstrFakePropS0_([[OPAQUE:.*]]*, i8*) unnamed_addr // CHECK: define internal void @_TToFE11objc_bridgeCSo8NSStrings13nsstrFakePropS0_([[OPAQUE:.*]]*, i8*, [[OPAQUE:.*]]*) unnamed_addr var nsstrFakeProp : NSString { get { return NSS } set {} } // CHECK: define internal [[OPAQUE:.*]]* @_TToFE11objc_bridgeCSo8NSString11nsstrResultfT_S0_([[OPAQUE:.*]]*, i8*) unnamed_addr func nsstrResult() -> NSString { return NSS } // CHECK: define internal void @_TToFE11objc_bridgeCSo8NSString8nsstrArgfT1sS0__T_([[OPAQUE:.*]]*, i8*, [[OPAQUE:.*]]*) unnamed_addr func nsstrArg(s s: NSString) { } } class Bas : NSObject { // CHECK: define internal [[OPAQUE:.*]]* @_TToFC11objc_bridge3Basg11strRealPropSS([[OPAQUE:.*]]*, i8*) unnamed_addr {{.*}} { // CHECK: define internal void @_TToFC11objc_bridge3Bass11strRealPropSS([[OPAQUE:.*]]*, i8*, [[OPAQUE:.*]]*) unnamed_addr {{.*}} { var strRealProp : String // CHECK: define internal [[OPAQUE:.*]]* @_TToFC11objc_bridge3Basg11strFakePropSS([[OPAQUE:.*]]*, i8*) unnamed_addr {{.*}} { // CHECK: define internal void @_TToFC11objc_bridge3Bass11strFakePropSS([[OPAQUE:.*]]*, i8*, [[OPAQUE:.*]]*) unnamed_addr {{.*}} { var strFakeProp : String { get { return "" } set {} } // CHECK: define internal [[OPAQUE:.*]]* @_TToFC11objc_bridge3Basg13nsstrRealPropCSo8NSString([[OPAQUE:.*]]*, i8*) unnamed_addr {{.*}} { // CHECK: define internal void @_TToFC11objc_bridge3Bass13nsstrRealPropCSo8NSString([[OPAQUE:.*]]*, i8*, [[OPAQUE:.*]]*) unnamed_addr {{.*}} { var nsstrRealProp : NSString // CHECK: define hidden %CSo8NSString* @_TFC11objc_bridge3Basg13nsstrFakePropCSo8NSString(%C11objc_bridge3Bas*) {{.*}} { // CHECK: define internal void @_TToFC11objc_bridge3Bass13nsstrFakePropCSo8NSString([[OPAQUE:.*]]*, i8*, [[OPAQUE:.*]]*) unnamed_addr {{.*}} { var nsstrFakeProp : NSString { get { return NSS } set {} } // CHECK: define internal [[OPAQUE:.*]]* @_TToFC11objc_bridge3Bas9strResultfT_SS([[OPAQUE:.*]]*, i8*) unnamed_addr {{.*}} { func strResult() -> String { return "" } // CHECK: define internal void @_TToFC11objc_bridge3Bas6strArgfT1sSS_T_([[OPAQUE:.*]]*, i8*, [[OPAQUE:.*]]*) unnamed_addr {{.*}} { func strArg(s s: String) { } // CHECK: define internal [[OPAQUE:.*]]* @_TToFC11objc_bridge3Bas11nsstrResultfT_CSo8NSString([[OPAQUE:.*]]*, i8*) unnamed_addr {{.*}} { func nsstrResult() -> NSString { return NSS } // CHECK: define internal void @_TToFC11objc_bridge3Bas8nsstrArgfT1sCSo8NSString_T_([[OPAQUE:.*]]*, i8*, [[OPAQUE:.*]]*) unnamed_addr {{.*}} { func nsstrArg(s s: NSString) { } override init() { strRealProp = String() nsstrRealProp = NSString() super.init() } deinit { var x = 10 } override var hashValue: Int { return 0 } func acceptSet(_ set: Set<Bas>) { } } func ==(lhs: Bas, rhs: Bas) -> Bool { return true } class OptionalBlockProperty: NSObject { var x: (([AnyObject]) -> [AnyObject])? }
apache-2.0
80adb8e8d2701689c52d7beb2e141bd8
52.635468
144
0.592946
3.109081
false
false
false
false
raphaelhanneken/iconizer
Iconizer/Models/AppIcon.swift
1
3783
// // AppIcon.swift // Iconizer // https://github.com/raphaelhanneken/iconizer // import Cocoa class AppIcon: Codable { private static let marketing = "marketing" class var directory: String { return Constants.Directory.appIcon } class var `extension`: String { return Constants.AssetExtension.appIcon } let idiom: String let size: AssetSize let scale: AssetScale let role: String? //Apple Watch let subtype: String? //Apple Watch let platform: String? //iMessage var filename: String { let scaledWidth = Int(size.width * Float(scale.value)) return "icon-\(scaledWidth).png" } private enum ReadKeys: String, CodingKey { case idiom case size case scale case role case subtype case platform } private enum WriteKeys: String, CodingKey { case idiom case size case scale case role case subtype case platform case filename } init(idiom: String, size: AssetSize, scale: AssetScale, role: String? = nil, subtype: String? = nil, platform: String?) { self.idiom = idiom self.size = size self.scale = scale self.role = role self.subtype = subtype self.platform = platform } required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: ReadKeys.self) let idiom = try container.decode(String.self, forKey: .idiom) guard let scale = AssetScale(rawValue: try container.decode(String.self, forKey: .scale)) else { throw AssetCatalogError.invalidFormat(format: .scale) } let size = try AssetSize(size: try container.decode(String.self, forKey: .size)) self.idiom = idiom self.size = size self.scale = scale self.role = try container.decodeIfPresent(String.self, forKey: .role) self.subtype = try container.decodeIfPresent(String.self, forKey: .subtype) self.platform = try container.decodeIfPresent(String.self, forKey: .platform) } func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: WriteKeys.self) try container.encode(idiom, forKey: .idiom) try container.encode(size.string, forKey: .size) try container.encode(scale.rawValue, forKey: .scale) try container.encode(filename, forKey: .filename) try container.encodeIfPresent(role, forKey: .role) try container.encodeIfPresent(subtype, forKey: .subtype) try container.encodeIfPresent(platform, forKey: .platform) } } extension AppIcon: Asset { static let resourcePrefix = "AppIcon_" static func directory(named: String) -> String { return "\(directory)/\(named).\(self.extension)" } func save(_ image: [ImageOrientation: NSImage], aspect: AspectMode?, to url: URL) throws { guard let image = image[.all] else { throw AssetCatalogError.missingImage } //append filename to asset folder path let url = url.appendingPathComponent(filename, isDirectory: false) //skip if already exist //filename based on size, so we will reuse same images in Contents.json guard !FileManager.default.fileExists(atPath: url.path) else { return } //resize icon guard let resized = image.resize(toSize: size.multiply(scale), aspectMode: aspect ?? .fit) else { throw AssetCatalogError.rescalingImageFailed } //save to filesystem //no alpha for `ios-marketing` 1024x1024 try resized.savePng(url: url, withoutAlpha: idiom.contains(AppIcon.marketing)) } }
mit
53974cb98cecd7d9e3053dd781c743e2
30.789916
105
0.636796
4.450588
false
false
false
false
zcfsmile/Swifter
BasicSyntax/019构造过程/019Initialization.playground/Contents.swift
1
9075
//: Playground - noun: a place where people can play import UIKit //: 构造过程 //: 也就是一个实例对象的初始化过程 //: 存储属性初始化 //: 类创建实例时,必须要为存储属性设置初始值。可以通过直接赋值的方式,也可以是在构造器中赋初值 //: > 注意:为存储属性设置默认值,或在构造器中赋值时,不会触发属性观察器。 //: 构造器 struct Fahrenheit { var temperature: Double init() { temperature = 32.0 } } var f = Fahrenheit() //: 默认属性值 class Person { var name: String = "张三" } let zs = Person() //: 自定义构造过程 //: 可以通过输入参数和可选类型的属性来自定义构造过程,也可以在构造过程中修改常量属性。 class SurveyQuestion { let name: String var text: String var response: String? init(text: String) { self.name = "1111" self.text = text } func ask() { print(text) } } let cheeseQuestion = SurveyQuestion(text: "Do you like cheese?") cheeseQuestion.ask() cheeseQuestion.response = "Yes, I do like cheese" //: 默认构造器 //: 结构体或类的所有属性都有默认值,同时没有自定义的构造器,那么 Swift 会给这些结构体或类提供一个默认构造器(default initializers)。这个默认构造器将简单地创建一个所有属性值都设置为默认值的实例。 //class ShoppingListItem { // var name: String? // var quantity = 1 // var purchased = false //} //var item = ShoppingListItem() //: 结构体的逐一成员构造器 //: 如果结构体没有提供自定义的构造器,它们将自动获得一个逐一成员构造器,即使结构体的存储型属性没有默认值。 struct Size1 { var width: Double, height: Double } var size = Size1(width: 100, height: 100) //: 值类型的构造器代理 //: 构造器可以通过调用其它构造器来完成实例的部分构造过程。这一过程称为构造器代理,它能减少多个构造器间的代码重复。 //: 如果你为某个值类型定义了一个自定义的构造器,你将无法访问到默认构造器(如果是结构体,还将无法访问逐一成员构造器)。 //: 假如你希望默认构造器、逐一成员构造器以及你自己的自定义构造器都能用来创建实例,可以将自定义的构造器写到扩展(extension)中,而不是写在值类型的原始定义中。 struct Size { var width = 0.0, height = 0.0 } struct Point { var x = 0.0, y = 0.0 } struct Rext { var origin = Point() var size = Size() // 类似默认构造器 init() {} // 类似逐一成员构造器 init(origin: Point, size: Size) { self.origin = origin self.size = size } init(center: Point, size: Size) { let originX = center.x - (size.width / 2) let originY = center.y - (size.height / 2) self.init(origin: Point(x: originX, y: originY), size: size) } } //: 类的继承和构造过程 //: 指定构造器 //: 指定构造器是类中最主要的构造器。一个指定构造器将初始化类中提供的所有属性,并根据父类链往上调用父类的构造器来实现父类的初始化。 //: 便利构造器 convenience //: 便利构造器是类中比较次要的、辅助型的构造器。你可以定义便利构造器来调用同一个类中的指定构造器,并为其参数提供默认值。你也可以定义便利构造器来创建一个特殊用途或特定输入值的实例。 //: 类的构造器代理规则 //: 1. 指定构造器必须调用其父类的指定构造器 //: 2. 便利构造器必须调用同级中的其他构造器 //: 3. 便利构造器必须最终导致一个指定构造器被调用。 //: 类的两段式构造过程 //: 1. 为每一个类的存储属性指定一个初始值 //: 2. 它给每个类一次机会,在新实例准备使用之前进一步定制它们的存储型属性。 //: 第一阶段的过程: //: 1. 调用某个指定构造器或便利构造器 //: 2. 完成新实例的内存分配,但是内存还没有被初始化 //: 3. 指定构造器确保所在来类的所有存储性属性都已赋值。存储型属性所属的内存完成初始化。 //: 4. 指定构造器将调用父类的构造器,完成父类属性的初始化 //: 5. 这个调用父类构造器的过程沿着构造器链一直往上执行,直到到达构造器链的最顶部。 //: 6. 当到达了构造器链最顶部,且已确保所有实例包含的存储型属性都已经赋值,这个实例的内存被认为已经完全初始化。此时阶段 1 完成。 //: 第二阶段: //: 1. 从顶部构造器链一直往下,每个构造器链中类的指定构造器都有机会进一步定制实例。构造器此时可以访问self、修改它的属性并调用实例方法等等。 //: 2. 最终,任意构造器链中的便利构造器可以有机会定制实例和使用self。 //: 构造器的继承和重写 //: Swift 中的子类默认情况下不会继承父类的构造器。在定义子类构造器时带上override修饰符。即使你重写的是系统自动提供的默认构造器,也需要带上override修饰符. //: 你在子类中“重写”一个父类便利构造器时,不需要加override前缀,由于子类不能直接调用父类的便利构造器(每个规则都在上文类的构造器代理规则有所描述) class Vehicle { var numberOfWheels = 0 var description: String { return "\(numberOfWheels) wheels" } } // Vehicle 类只有默认构造器 let vehicle = Vehicle() print("Vehicle: \(vehicle.description)") class Bicycle: Vehicle { // 重写父类的默认构造器 override init() { // 1. 初始化本类的属性,这里是没有 // 2. 调用父类的指定构造器,初始化父类的属性 super.init() // 3. 再次定义继承自父类的属性 numberOfWheels = 2 } } let bicycle = Bicycle() print(bicycle.numberOfWheels) // 2 //: 构造器的自动继承 //: 类在默认情况下不会继承父类的构造器。但是如果满足特定条件,父类构造器是可以被自动继承的。 //: 规则1: 如果子类没有定义任何指定构造器,它将自动继承所有父类的指定构造器。 //: 规则2: 如果子类提供了所有父类指定构造器的实现——无论是通过规则 1 继承过来的,还是提供了自定义实现——它将自动继承所有父类的便利构造器。 //: > 注意: 对于规则 2,子类可以将父类的指定构造器实现为便利构造器。 //: 实践 // Food 基类 class Food { var name: String init(name: String) { self.name = name } convenience init() { self.init(name: "[Unnamed]") } } let nameMeat = Food(name: "Bacon") let mysteryMeat = Food() class RecipeIngredient: Food { var quantity: Int init(name: String, quantity: Int) { self.quantity = quantity super.init(name: name) } override convenience init(name: String) { self.init(name: name, quantity: 1) } } let oneMysteryItem = RecipeIngredient() let oneBacon = RecipeIngredient(name: "bacon") let sixEggs = RecipeIngredient(name: "Eggs", quantity: 6) //: 由于它为自己引入的所有属性都提供了默认值,并且自己没有定义任何构造器,ShoppingListItem将自动继承所有父类中的指定构造器和便利构造器。 class ShoppingListItem: RecipeIngredient { var purchased = false var description: String { var output = "\(quantity) * \(name)" output += purchased ? "Yes" : "False" return output } } //: 可失败构造器 init? //: 如果一个类、结构体或枚举类型的对象,在构造过程中有可能失败,则为其定义一个可失败构造器。这里所指的“失败”是指,如给构造器传入无效的参数值,或缺少某种所需的外部资源,又或是不满足某种必要的条件等。 struct Animal { let species: String init?(species: String) { if species.isEmpty { return nil } self.species = species } } let someCreature = Animal(species: "Giraffe") type(of: someCreature) // //: 构造失败的传递 //: 类,结构体,枚举的可失败构造器可以横向代理到类型中的其他可失败构造器。类似的,子类的可失败构造器也能向上代理到父类的可失败构造器。 //: 必要构造器 //: 在类的构造器前添加required修饰符表明所有该类的子类都必须实现该构造器: //: 在子类重写父类的必要构造器时,必须在子类的构造器前也添加required修饰符,表明该构造器要求也应用于继承链后面的子类。在重写父类中必要的指定构造器时,不需要添加override修饰符: //: 过闭包或函数设置属性的默认值 class SomeClass { let someProperty: String = { return "1111" }() }
mit
e1f35026ac1141f2da0871c193d73cb0
22.790179
113
0.68268
2.623831
false
false
false
false
swift-gtk/SwiftGTK
Sources/UIKit/DeleteType.swift
1
2179
public enum DeleteType: RawRepresentable { /// Delete characters. case characters /// Delete only the portion of the word to the left/right of cursor if we’re /// in the middle of a word. case wordEnds /// Delete words. case words /// Delete display-lines. Display-lines refers to the visible lines, with /// respect to to the current line breaks. As opposed to paragraphs, which are /// defined by line breaks in the input. case displayLines /// Delete only the portion of the display-line to the left/right of cursor. case displayLineEnds /// Delete to the end of the paragraph. Like C-k in Emacs (or its reverse). case paragraphEnds /// Delete entire line. Like C-k in pico. case paragraphs /// Delete only whitespace. Like M-\ in Emacs. case whitespace public typealias RawValue = GtkDeleteType public var rawValue: RawValue { switch self { case .characters: return GTK_DELETE_CHARS case .displayLineEnds: return GTK_DELETE_DISPLAY_LINE_ENDS case .displayLines: return GTK_DELETE_DISPLAY_LINES case .paragraphEnds: return GTK_DELETE_PARAGRAPH_ENDS case .paragraphs: return GTK_DELETE_PARAGRAPHS case .whitespace: return GTK_DELETE_WHITESPACE case .wordEnds: return GTK_DELETE_WORD_ENDS case .words: return GTK_DELETE_WORDS } } public init?(rawValue: RawValue) { switch rawValue { case GTK_DELETE_CHARS: self = .characters case GTK_DELETE_DISPLAY_LINE_ENDS: self = .displayLineEnds case GTK_DELETE_DISPLAY_LINES: self = .displayLines case GTK_DELETE_PARAGRAPH_ENDS: self = .paragraphEnds case GTK_DELETE_PARAGRAPHS: self = .paragraphs case GTK_DELETE_WHITESPACE: self = .whitespace case GTK_DELETE_WORD_ENDS: self = .wordEnds case GTK_DELETE_WORDS: self = .words default: return nil } } }
gpl-2.0
f3962c4aa104bec330bce089ae8be9ab
30.550725
82
0.600367
4.415822
false
false
false
false
yasuoza/graphPON
graphPON iOS/Views/LineChartFooterView.swift
1
3474
import UIKit class LineChartFooterView: UIView { var footerSeparatorColor: UIColor! = UIColor.whiteColor() var sectionCount: NSInteger! = 2 { didSet { // re-drawRect self.setNeedsDisplay() } } var leftLabel: UILabel! = UILabel() var rightLabel: UILabel! = UILabel() private var topSeparatorView: UIView! = UIView() // MARK: - Alloc/Init required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override init(frame: CGRect) { super.init(frame: frame) self.backgroundColor = UIColor.clearColor() self.topSeparatorView.backgroundColor = self.footerSeparatorColor self.addSubview(self.topSeparatorView) self.leftLabel.adjustsFontSizeToFitWidth = true self.leftLabel.textAlignment = NSTextAlignment.Left self.leftLabel.textColor = UIColor.whiteColor() self.leftLabel.backgroundColor = UIColor.clearColor() self.addSubview(self.leftLabel) self.rightLabel.adjustsFontSizeToFitWidth = true self.rightLabel.textAlignment = NSTextAlignment.Right self.rightLabel.textColor = UIColor.whiteColor() self.rightLabel.backgroundColor = UIColor.clearColor() self.addSubview(self.rightLabel) } // MARK: - Drawing override func drawRect(rect: CGRect) { super.drawRect(rect) let context = UIGraphicsGetCurrentContext() CGContextSetStrokeColorWithColor(context, self.footerSeparatorColor.CGColor) CGContextSetLineWidth(context, 0.5) CGContextSetShouldAntialias(context, true) var xOffset = CGFloat(0) let yOffset = CGFloat(0.5) let stepLength = ceil(CGFloat(self.bounds.size.width) / CGFloat(self.sectionCount - 1)) for (var i = 0; i < self.sectionCount; i++) { CGContextSaveGState(context) CGContextMoveToPoint(context, xOffset + (kJBLineChartFooterViewSeparatorWidth * 0.5), yOffset) CGContextAddLineToPoint(context, xOffset + (kJBLineChartFooterViewSeparatorWidth * 0.5), yOffset + kJBLineChartFooterViewSeparatorHeight) CGContextStrokePath(context) xOffset += stepLength; CGContextRestoreGState(context); } if (self.sectionCount > 1) { CGContextSaveGState(context) CGContextMoveToPoint(context, self.bounds.size.width - (kJBLineChartFooterViewSeparatorWidth * 0.5), yOffset) CGContextAddLineToPoint(context, self.bounds.size.width - (kJBLineChartFooterViewSeparatorWidth * 0.5), yOffset + kJBLineChartFooterViewSeparatorHeight) CGContextStrokePath(context) CGContextRestoreGState(context); } } // MARK: - Layout override func layoutSubviews() { super.layoutSubviews() self.topSeparatorView.frame = CGRectMake( self.bounds.origin.x, self.bounds.origin.y, self.bounds.size.width, kJBLineChartFooterViewSeparatorWidth ) let xOffset = CGFloat(0) let yOffset = kJBLineChartFooterViewSeparatorSectionPadding let width = ceil(self.bounds.size.width * 0.5) self.leftLabel.frame = CGRectMake(xOffset, yOffset, width, self.bounds.size.height) self.rightLabel.frame = CGRectMake(CGRectGetMaxX(self.leftLabel.frame), yOffset, width, self.bounds.size.height) } }
mit
852f383f40e97b2771f63eef522f3a7e
34.44898
135
0.663212
4.991379
false
false
false
false
brightdigit/speculid
TestSetup/main.swift
1
5104
// // main.swift // TestSetup // // Created by Leo Dion on 1/17/20. // Copyright © 2020 Bright Digit, LLC. All rights reserved. // import Foundation extension URL { func relativePath(from base: URL) -> String? { // Ensure that both URLs represent files: guard self.isFileURL && base.isFileURL else { return nil } // Remove/replace "." and "..", make paths absolute: let destComponents = self.standardized.pathComponents let baseComponents = base.standardized.pathComponents // Find number of common path components: var i = 0 while i < destComponents.count && i < baseComponents.count && destComponents[i] == baseComponents[i] { i += 1 } // Build relative path: var relComponents = Array(repeating: "..", count: baseComponents.count - i) relComponents.append(contentsOf: destComponents[i...]) return relComponents.joined(separator: "/") } } let folderContentsJson = """ { "info" : { "version" : 1, "author" : "xcode" } } """ let appIconSpeculidUrl = URL(fileURLWithPath: "/Users/leo/Documents/Projects/Speculid/examples/Assets/AppIcon.speculid") let imageSetSpeculidUrl = URL(fileURLWithPath: "/Users/leo/Documents/Projects/Speculid/examples/Assets/Image Set.speculid") guard let filePath = CommandLine.arguments.last.flatMap({ URL(fileURLWithPath: $0) }) else { fatalError() } guard let enumerator = FileManager.default.enumerator(at: filePath, includingPropertiesForKeys: nil) else { fatalError() } let assetsParentUrl = URL(fileURLWithPath: "/Users/leo/Documents/Projects/Speculid/examples/Assets", isDirectory: true) let speculidIconsUrl = assetsParentUrl.appendingPathComponent("icons", isDirectory: true) let assetsUrl = assetsParentUrl.appendingPathComponent("Assets.xcassets", isDirectory: true) let appIconContentsUrl = assetsUrl.appendingPathComponent("AppIcon.appiconset").appendingPathComponent("Contents.json") //URL(fileURLWithPath: "/Users/leo/Documents/Projects/Speculid/examples/Assets/Assets.xcassets/AppIcon.appiconset/Contents.json", isDirectory: true) let imageSetContentsUrl = assetsUrl.appendingPathComponent("ImageSet.imageset").appendingPathComponent("Contents.json") //URL(fileURLWithPath: "/Users/leo/Documents/Projects/Speculid/examples/Assets/Assets.xcassets/ImageSet.imageset/Contents.json", isDirectory: true) let iconsUrl = assetsUrl.appendingPathComponent("icons") let iconsContentsUrl = iconsUrl.appendingPathComponent("Contents.json") if FileManager.default.fileExists(atPath: iconsUrl.path, isDirectory: nil) { try! FileManager.default.removeItem(at: iconsUrl) } if FileManager.default.fileExists(atPath: speculidIconsUrl.path, isDirectory: nil) { try! FileManager.default.removeItem(at: speculidIconsUrl) } try! FileManager.default.createDirectory(at: iconsUrl, withIntermediateDirectories: false, attributes: nil) try! FileManager.default.createDirectory(at: speculidIconsUrl, withIntermediateDirectories: false, attributes: nil) try! folderContentsJson.write(to: iconsContentsUrl, atomically: true, encoding: .utf8) for case let url as URL in enumerator { guard url.pathExtension == "svg" else { continue } let components = url.deletingPathExtension().pathComponents[filePath.pathComponents.count...] let name = components.joined(separator: "-") let appIconSetUrl = iconsUrl.appendingPathComponent(name).appendingPathExtension("appiconset") let imageSetUrl = iconsUrl.appendingPathComponent(name).appendingPathExtension("imageset") let appIconSpecUrl = speculidIconsUrl.appendingPathComponent("\(name).appicon.speculid") let imageSetSpecUrl = speculidIconsUrl.appendingPathComponent("\(name).imageset.speculid") try! FileManager.default.createDirectory(at: appIconSetUrl, withIntermediateDirectories: false, attributes: nil) try! FileManager.default.createDirectory(at: imageSetUrl, withIntermediateDirectories: false, attributes: nil) try! FileManager.default.copyItem(at: appIconContentsUrl, to: appIconSetUrl.appendingPathComponent("Contents.json")) try! FileManager.default.copyItem(at: imageSetContentsUrl, to: imageSetUrl.appendingPathComponent("Contents.json")) let appIconSpecText = """ { "set" : "\(appIconSetUrl.relativePath(from: appIconSpecUrl.deletingLastPathComponent())!)", "source" : "\(url.relativePath(from: appIconSpecUrl.deletingLastPathComponent())!)", "background" : "#FFFFFF", "remove-alpha" : true } """ let imageSetSpecText = """ { "set" : "\(imageSetUrl.relativePath(from: imageSetSpecUrl.deletingLastPathComponent())!)", "source" : "\(url.relativePath(from: imageSetSpecUrl.deletingLastPathComponent())!)" } """ try! appIconSpecText.write(to: appIconSpecUrl, atomically: true, encoding: .utf8) //try! FileManager.default.copyItem(at: appIconSpeculidUrl, to: appIconSpecUrl) // try! FileManager.default.copyItem(at: imageSetSpeculidUrl, to: // imageSetSpecUrl) try! imageSetSpecText.write(to: imageSetSpecUrl, atomically: true, encoding: .utf8) }
mit
5dc45124722dbb8ea42b523b490a3952
39.181102
267
0.745836
4.245424
false
false
false
false
suifengqjn/swiftDemo
Swift基本语法-黑马笔记/运算符/main.swift
1
2428
// // main.swift // 运算符 // // Created by 李南江 on 15/2/28. // Copyright (c) 2015年 itcast. All rights reserved. // import Foundation /* 算术运算符: 除了取模, 其它和OC一样, 包括优先级 + - * / % ++ -- */ var result = 10 + 10 result = 10 * 10 result = 10 - 10 result = 10 / 10 print(result) /* 注意:Swift是安全严格的编程语言, 会在编译时候检查是否溢出, 但是只会检查字面量而不会检查变量, 所以在Swift中一定要注意隐式溢出 可以检测 var num1:UInt8 = 255 + 1; 无法检测 var num1:UInt8 = 255 var num2:UInt8 = 250 var result = num1 + num2 println(result) 遇到这种问题可以利用溢出运算符解决该问题:http://www.yiibai.com/swift/overflow_operators.html &+ &- &* &/ &% */ /* 取模 % OC: 只能对整数取模 NSLog(@"%tu", 10 % 3); Swift: 支持小数取模 */ print(10 % 3.5) /* 自增 自减 */ var number = 10 number++ print(number) number-- print(number) /* 赋值运算 = += -= /= *= %= */ var num1 = 10 num1 = 20 num1 += 10 num1 -= 10 num1 /= 10 num1 *= 10 num1 %= 5 print(num1) /* 基本用法和OC一样, 唯一要注意的是表达式的值 OC: 表达式的结合方向是从左至右, 整个表达式的值整体的值等于最后一个变量的值, 简而言之就是连续赋值 Swift: 不允许连续赋值, Swift中的整个表达式是没有值的. 主要是为了避免 if (c == 9) 这种情况误写为 if (c = 9) , c = 9是一个表达式, 表达式是没有值的, 所以在Swift中if (c = 9)不成立 var num2:Int var num3:Int num3 = num2 = 10 */ /* 关系运算符, 得出的值是Bool值, 基本用法和OC一样 > < >= <= == != ?: */ var result1:Bool = 250 > 100 var result2 = 250 > 100 ? 250 : 100 print(result2) /* 逻辑运算符,基本用法和OC一样, 唯一要注意的是Swift中的逻辑运算符只能操作Bool类型数据, 而OC可以操作整形(非0即真) ! && || */ var open = false if !open { print("打开") } var age = 20 var height = 180 var wage = 30000 if (age > 25 && age < 40 && height > 175) || wage > 20000 { print("约") } /* 区间 闭区间: 包含区间内所有值 a...b 例如: 1...5 半闭区间: 包含头不包含尾 a..<b 例如: 1..<5 注意: 1.Swift刚出来时的写法是 a..b 2.区间只能用于整数, 写小数会有问题 应用场景: 遍历, 数组等 */ for i in 1...5 { print(i) } for i in 1..<5 { print(i) }
apache-2.0
8f7d633ff0bc838f2939166c94ea1e27
12.228346
121
0.614286
2.121212
false
false
false
false
hikelee/cinema
Sources/App/Models/User.swift
1
2856
import Vapor import Fluent import HTTP final class User: ChannelBasedModel { public static var entity: String { return "c_user" } enum Role:String{ case root case admin case staff init(value: String){ switch value { case "root": self = .root case "admin": self = .admin default: self = .staff } } } var id: Node? var channelId: Node? var name: String? var password: String? var title: String? var role: Role var isActive: Bool = false var exists: Bool = false //used in fluent var roleName: String { switch role{ case .root: return "超级管理员" case .admin: return "管理员" case .staff: return "营业员" } } var isRoot : Bool{ return role == .root } var isAdmin : Bool { return role == .admin } var isStaff : Bool { return role == .staff } var isRoleEditable : Bool { return isRoot || isAdmin } var isChannelEditable: Bool { return isRoot } convenience init(node: Node, in context: Context) throws { try self.init(node:node) } init(node: Node) throws { id = try? node.extract("id") channelId = try? node.extract("channel_id") title = try? node.extract("title") name = try? node.extract("name") password = try? node.extract("password") role = Role(value: (try? node.extract("role")) ?? "") isActive = (try? node.extract("is_active")) ?? true } func makeNode() throws -> Node { return try Node.init( node:[ "id": id, "title": title, "channel_id":channelId, "name": name, "password": password, "role": role.rawValue, "is_active": isActive ] ) } func makeLeafNode() throws -> Node { var node = try makeNode() node["role_name"] = Node(roleName) node["channel"]=try Channel.node(channelId) return node } func validate(isCreate: Bool) throws ->[String:String] { var result:[String:String]=[:] if name?.isEmpty ?? true {result["name"] = "必填项"} if password?.isEmpty ?? true {result["password"] = "必填项"} switch role { case .admin, .staff: if ((channelId?.int) ?? 0) == 0 { result["channel_id"] = "必选项"; } else if try Channel.load(channelId) == nil { result["channel_id"] = "找不到所选的渠道" } default: break } return result } }
mit
8a6087f174538edaeb120727eea766b0
23.137931
65
0.491071
4.261796
false
false
false
false
festrs/Plantinfo
PlantInfo/CustomAlbumPhoto.swift
1
5093
// // CustomAlbumPhoto.swift // PlantInfo // // Created by Felipe Dias Pereira on 2016-08-19. // Copyright © 2016 Felipe Dias Pereira. All rights reserved. // import Photos class CustomPhotoAlbum: NSObject { static let albumName = "Herba" static let sharedInstance = CustomPhotoAlbum() var assetCollection: PHAssetCollection! var manager = PHImageManager.defaultManager() override init() { super.init() if let assetCollection = fetchAssetCollectionForAlbum() { self.assetCollection = assetCollection return } if PHPhotoLibrary.authorizationStatus() != PHAuthorizationStatus.Authorized { PHPhotoLibrary.requestAuthorization({ (status: PHAuthorizationStatus) -> Void in status }) } if PHPhotoLibrary.authorizationStatus() == PHAuthorizationStatus.Authorized { self.createAlbum() } else { PHPhotoLibrary.requestAuthorization(requestAuthorizationHandler) } } func requestAuthorizationHandler(status: PHAuthorizationStatus) { if PHPhotoLibrary.authorizationStatus() == PHAuthorizationStatus.Authorized { // ideally this ensures the creation of the photo album even if authorization wasn't prompted till after init was done print("trying again to create the album") self.createAlbum() } else { print("should really prompt the user to let them know it's failed") } } func createAlbum() { PHPhotoLibrary.sharedPhotoLibrary().performChanges({ PHAssetCollectionChangeRequest.creationRequestForAssetCollectionWithTitle(CustomPhotoAlbum.albumName) // create an asset collection with the album name }) { success, error in if success { self.assetCollection = self.fetchAssetCollectionForAlbum() } else { print("error \(error)") } } } func fetchAssetCollectionForAlbum() -> PHAssetCollection! { let fetchOptions = PHFetchOptions() fetchOptions.predicate = NSPredicate(format: "title = %@", CustomPhotoAlbum.albumName) let collection = PHAssetCollection.fetchAssetCollectionsWithType(.Album, subtype: .Any, options: fetchOptions) if let _: AnyObject = collection.firstObject { return collection.firstObject as! PHAssetCollection } return nil } func saveImageAsAsset(image: UIImage, completion: (localIdentifier:String?) -> Void) { var placeholder: PHObjectPlaceholder? PHPhotoLibrary.sharedPhotoLibrary().performChanges({ // Request creating an asset from the image let createAssetRequest = PHAssetChangeRequest.creationRequestForAssetFromImage(image) // Request editing the album guard let albumChangeRequest = PHAssetCollectionChangeRequest(forAssetCollection: self.assetCollection) else { assert(false, "Album change request failed") return } // Get a placeholder for the new asset and add it to the album editing request guard let photoPlaceholder = createAssetRequest.placeholderForCreatedAsset else { assert(false, "Placeholder is nil") return } placeholder = photoPlaceholder albumChangeRequest.addAssets([photoPlaceholder]) }, completionHandler: { success, error in guard let placeholder = placeholder else { assert(false, "Placeholder is nil") completion(localIdentifier: nil) return } if success { completion(localIdentifier: placeholder.localIdentifier) } else { print(error) completion(localIdentifier: nil) } }) } func retrieveImageWithIdentifer(localIdentifier:String, completion: (image:UIImage?) -> Void) { let fetchOptions = PHFetchOptions() fetchOptions.predicate = NSPredicate(format: "mediaType == %d", PHAssetMediaType.Image.rawValue) let fetchResults = PHAsset.fetchAssetsWithLocalIdentifiers([localIdentifier], options: fetchOptions) if fetchResults.count > 0 { if let imageAsset = fetchResults.firstObject as? PHAsset { let requestOptions = PHImageRequestOptions() requestOptions.deliveryMode = .HighQualityFormat manager.requestImageForAsset(imageAsset, targetSize: CGSize(width: 720, height: 1280), contentMode: .AspectFill, options: requestOptions, resultHandler: { (image, info) -> Void in completion(image: image) }) } else { completion(image: nil) } } else { completion(image: nil) } } }
mit
e0c6a9fb6e64a36594f3cf6bcc748dd6
39.102362
195
0.61469
6.112845
false
false
false
false
DanielAsher/Madness
Documentation/Subset of Common Markdown.playground/section-2.swift
1
2062
// MARK: - Lexing rules let newline = ignore("\n") let ws = %" " | %"\t" let lower = %("a"..."z") let upper = %("A"..."Z") let digit = %("0"..."9") let text = lower | upper | digit | ws let restOfLine: Parser<String, String>.Function = (text+ |> map { "".join($0) }) ++ newline // MARK: - AST enum Node: Printable { case Blockquote([Node]) case Header(Int, String) case Paragraph(String) func analysis<T>(#ifBlockquote: [Node] -> T, ifHeader: (Int, String) -> T, ifParagraph: String -> T) -> T { switch self { case let Blockquote(nodes): return ifBlockquote(nodes) case let Header(level, text): return ifHeader(level, text) case let Paragraph(text): return ifParagraph(text) } } // MARK: Printable var description: String { return analysis( ifBlockquote: { "<blockquote>\n\t" + "\n\t".join(lazy($0).map { $0.description }) + "\n</blockquote>" }, ifHeader: { "<h\($0)>\($1)</h\($0)>" }, ifParagraph: { "<p>\($0)</p>" }) } } // MARK: - Parsing rules typealias NodeParser = Parser<String, Ignore>.Function -> Parser<String, Node>.Function let element: NodeParser = fix { element in { prefix in let prefixedElements: NodeParser = { let each = (element(prefix ++ $0) | (prefix ++ $0 ++ newline)) |> map { $0.map { [ $0 ] } ?? [] } return (each)+ |> map { Node.Blockquote(join([], $0)) } } let octothorpes: Parser<String, Int>.Function = (%"#" * (1..<7)) |> map { $0.count } let header: Parser<String, Node>.Function = prefix ++ octothorpes ++ ignore(" ") ++ restOfLine |> map { (level: Int, title: String) in Node.Header(level, title) } let paragraph: Parser<String, Node>.Function = (prefix ++ restOfLine)+ |> map { Node.Paragraph("\n".join($0)) } let blockquote: Parser<String, Node>.Function = prefix ++ { prefixedElements(ignore("> "))($0, $1) } return header | paragraph | blockquote } } let ok: Parser<String, Ignore>.Function = { (Ignore(), $1) } let parsed = parse(element(ok), "> # hello\n> \n> hello\n> there\n> \n> \n") if let translated = parsed.0 { translated.description }
mit
179ae06d83f24ce874ac3986a9998df5
29.776119
164
0.609602
3.02346
false
false
false
false
csnu17/My-Blognone-apps
myblognone/Common/Adapters/ProgressView.swift
1
891
// // ProgressView.swift // myblognone // // Created by Kittisak Phetrungnapha on 12/21/2559 BE. // Copyright © 2559 Kittisak Phetrungnapha. All rights reserved. // import UIKit class ProgressView: NSObject { static let shared = ProgressView() private var shown = false private var indicator: UIActivityIndicatorView! private override init() { indicator = UIActivityIndicatorView(activityIndicatorStyle: .gray) let transform = CGAffineTransform(scaleX: 1.4, y: 1.4) indicator.transform = transform indicator.startAnimating() } func show(in view: UIView!) { indicator.center = view.center view.addSubview(indicator) shown = true } func hide() { indicator.removeFromSuperview() shown = false } func isShown() -> Bool { return shown } }
mit
0998dbf5153666ceb8ac5f898fbe41f5
21.820513
74
0.630337
4.836957
false
false
false
false
xivol/MCS-V3-Mobile
examples/networking/firebase-test/firebase-test/Model/FirebaseDataDelegate.swift
1
2540
// // FirebaseDataDelegate.swift // firebase-test // // Created by Илья Лошкарёв on 17.11.2017. // Copyright © 2017 Илья Лошкарёв. All rights reserved. // import FirebaseDatabase typealias FirebaseDataObservers = [DataEventType : (DataSnapshot)->Void] @objc protocol FirebaseDataDelegate { var fireSourceRef: DatabaseReference! {get set} var fireObservers: NSMutableDictionary {get set} @objc optional func fireValue(withSnapshot snapshot: DataSnapshot) @objc optional func fireChildAdded(withSnapshot snapshot: DataSnapshot) @objc optional func fireChildRemoved(withSnapshot snapshot: DataSnapshot) @objc optional func fireChildMoved(withSnapshot snapshot: DataSnapshot) @objc optional func fireChildChanged(withSnapshot snapshot: DataSnapshot) } extension DatabaseReference { func connect(delegate: FirebaseDataDelegate) { if let source = delegate.fireSourceRef { if source.key != self.key { source.disconnect(delegate: delegate) } } delegate.fireSourceRef = self if let observer = delegate.fireValue(withSnapshot:){ delegate.fireObservers.setObject(self.observe(.value, with: observer), forKey: DataEventType.value.rawValue as NSCopying) } if let observer = delegate.fireChildAdded(withSnapshot:) { delegate.fireObservers.setObject(self.observe(.childAdded, with: observer), forKey: DataEventType.childAdded.rawValue as NSCopying) } if let observer = delegate.fireChildRemoved(withSnapshot:) { delegate.fireObservers.setObject(self.observe(.childRemoved, with: observer), forKey: DataEventType.childRemoved.rawValue as NSCopying) } if let observer = delegate.fireChildMoved(withSnapshot:) { delegate.fireObservers.setObject(self.observe(.childMoved, with: observer), forKey: DataEventType.childMoved.rawValue as NSCopying) } if let observer = delegate.fireChildChanged(withSnapshot:) { delegate.fireObservers.setObject(self.observe(.childChanged, with: observer), forKey: DataEventType.childChanged.rawValue as NSCopying) } } func disconnect(delegate: FirebaseDataDelegate) { for (_, handle) in delegate.fireObservers { self.removeObserver(withHandle: handle as! UInt) } } func load(with completion: @escaping (DataSnapshot)->Void) { self.observeSingleEvent(of: .value, with: completion) } }
mit
c4ddcfdf947df6abba2674ddf0be6074
41.627119
147
0.705368
4.692164
false
false
false
false
XLabKC/Badger
Badger/Badger/TaskEditContentCell.swift
1
1957
import UIKit protocol TaskEditContentCellDelegate: InputCellDelegate { func editContentCell(cell: TaskEditContentCell, hasChangedHeight: CGFloat); } class TaskEditContentCell: InputCell, UITextViewDelegate { private let minVerticalPadding: CGFloat = 59.0 private let minTextHeight: CGFloat = 24.0 private var hasAwakened = false private var textToSet: String? private var currentHeight: CGFloat = 0 weak var cellDelegate: TaskEditContentCellDelegate? @IBOutlet weak var textView: UITextView! override func awakeFromNib() { super.awakeFromNib() self.hasAwakened = true if let text = self.textToSet { self.textView.text = text } self.textView.delegate = self self.textViewDidChange(self.textView) } func textViewDidChange(textView: UITextView) { let newHeight = self.calculateCellHeight() if self.currentHeight != newHeight { self.currentHeight = newHeight self.cellDelegate?.editContentCell(self, hasChangedHeight: self.currentHeight) } self.textView.scrollRectToVisible(CGRectMake(0, 0, self.textView.frame.width, 1), animated: true) } func textViewDidBeginEditing(textView: UITextView) { self.delegate?.cellDidBeginEditing(self) } func calculateCellHeight() -> CGFloat { return Helpers.calculateTextViewHeight(self.textView, minVerticalPadding: self.minVerticalPadding, minTextHeight: self.minTextHeight) } override func setContent(text: String) { if self.hasAwakened { self.textView.text = text } else { self.textToSet = text } } override func getContent() -> String { return self.textView.text } override func closeKeyboard() { self.textView.resignFirstResponder() } override func openKeyboard() { self.textView.becomeFirstResponder() } }
gpl-2.0
ec036a36176bddbb687e9b55a34faaca
28.208955
141
0.677057
4.844059
false
false
false
false
scarlettwu93/test
Example/test/Business.swift
1
6447
// // Business.swift // Yelp // // Created by Timothy Lee on 4/23/15. // Copyright (c) 2015 Timothy Lee. All rights reserved. // import UIKit import Alamofire import Kanna func ==(lhs: Business, rhs: Business) -> Bool { return lhs.id == rhs.id } struct Business : Hashable { var hashValue: Int { get { return id.hash } } let id: String let name: String let snippet: String let imageURL: NSURL let URL: NSURL let address: String // let categories: [(String, String)] // let distance: String let ratingImageURL: NSURL let reviewCount: NSNumber init?(dictionary: NSDictionary) { guard let id = dictionary["id"] as? String, name = dictionary["name"] as? String, imageURLString = dictionary["image_url"] as? String, imageURL = NSURL(string: imageURLString), URLString = dictionary["url"] as? String, URL = NSURL(string: URLString), location = dictionary["location"] as? NSDictionary, addressArray = location["display_address"] as? [String], // categoriesArray = dictionary["categories"] as? [[String]], // distanceMeters = dictionary["distance"] as? Double, ratingImageURLString = dictionary["rating_img_url_large"] as? String, ratingImageURL = NSURL(string: ratingImageURLString), reviewCount = dictionary["review_count"] as? Int, snippet = dictionary["snippet_text"] as? String else { print(dictionary) return nil } self.id = id self.name = name self.imageURL = imageURL self.URL = URL self.address = addressArray.joinWithSeparator(",") self.ratingImageURL = ratingImageURL self.reviewCount = reviewCount self.snippet = snippet // categories = categoriesArray.map {pair in (pair[0], pair[1])} // let milesPerMeter = 0.000621371 // distance = String(format: "%.2f mi", milesPerMeter * distanceMeters) } static func search(parameters: YelpSearchParameters) -> SearchResults { return SearchResults(parameters: parameters) } // func getFoodImages() -> [FoodImage] { // // } // ?tab=food } extension CollectionType { /// Return a copy of `self` with its elements shuffled func shuffle() -> [Generator.Element] { var list = Array(self) list.shuffleInPlace() return list } } extension MutableCollectionType where Index == Int { /// Shuffle the elements of `self` in-place. mutating func shuffleInPlace() { // empty and single-element collections don't shuffle if count < 2 { return } for i in 0..<count - 1 { let j = Int(arc4random_uniform(UInt32(count - i))) + i guard i != j else { continue } swap(&self[i], &self[j]) } } } // accsess business images class SearchResults { var parameters: YelpSearchParameters var busniesses = [String: Business]() var foodImages = [FoodImage]() var foodImageIndex = 0 var didChange = {} init(parameters: YelpSearchParameters) { self.parameters = parameters self.parameters.limit = 5 fetchMoreBusniesses() } func nextFoodImage() -> FoodImage? { guard foodImageIndex < foodImages.count else { fetchMoreBusniesses() return nil } let foodImage = foodImages[foodImageIndex] foodImageIndex += 1 if foodImageIndex > foodImages.count - 10 { fetchMoreBusniesses() } return foodImage } var hasMoreBusniesses = true var searchingForBusiness = false func fetchMoreBusniesses() { guard hasMoreBusniesses && !searchingForBusiness else { return } YelpClient.sharedInstance.search(parameters) { (businesses, error) in self.searchingForBusiness = false guard let businesses = businesses where error == nil else { return } businesses.forEach(self.addBusniess) // if self.busniesses.count < self.parameters.offset { // self.hasMoreBusniesses = false // } print(self.busniesses.count) } searchingForBusiness = true parameters.offset += parameters.limit } func addBusniess(business: Business) { busniesses[business.id] = business fetchFoodImagesForBusniess(business) } func addFoodImage(foodImage: FoodImage) { if foodImageIndex == foodImages.count { foodImages.append(foodImage) didChange() return } let range = foodImages.count - foodImageIndex let randomIndex = foodImageIndex + random() % range foodImages.insert(foodImage, atIndex: randomIndex) didChange() } func fetchFoodImagesForBusniess(business: Business) { // example: http://www.yelp.com/biz_photos/tutti-frutti-frozen-yogurt-la-crescenta-montrose?tab=food // the first image let first = FoodImage(busniessID: business.id, imageURL: business.imageURL, descirption: business.snippet) addFoodImage(first) // fetch more let urlString = "http://www.yelp.com/biz_photos/\(business.id)?tab=food" Alamofire.request(.GET, urlString).responseString { (response) in guard let html = response.result.value, doc = Kanna.HTML(html: html, encoding: NSUTF8StringEncoding) where response.result.isSuccess else { return } // Search for nodes by CSS // #super-container > div.container > div.media-landing.js-media-landing > div.media-landing_gallery.photos > ul > li:nth-child(1) > div > img for img in doc.css("div.container .photo-box-grid img").dropFirst() { if let alt = img["alt"], src = img["src"], url = NSURL(string: "http:"+src), endRange = alt.rangeOfString(". ") { let range = alt.startIndex ..< endRange.endIndex let descirption = alt.stringByReplacingCharactersInRange(range, withString: "") let foodImage = FoodImage(busniessID: business.id, imageURL: url, descirption: descirption) self.addFoodImage(foodImage) } } } } }
mit
a01b7ce39af7da1180e9896afd8b1ef7
29.84689
154
0.603847
4.341414
false
false
false
false
debugsquad/Hyperborea
Hyperborea/Controller/CParent.swift
1
9959
import UIKit class CParent:UIViewController { enum TransitionVertical:CGFloat { case fromTop = -1 case fromBottom = 1 case none = 0 } enum TransitionHorizontal:CGFloat { case fromLeft = -1 case fromRight = 1 case none = 0 } private(set) weak var viewParent:VParent! private var barHidden:Bool = false private var statusBarStyle:UIStatusBarStyle = UIStatusBarStyle.default init() { super.init(nibName:nil, bundle:nil) } required init?(coder:NSCoder) { return nil } override func viewDidLoad() { super.viewDidLoad() let controllerSearch:CSearch = CSearch() mainController(controller:controllerSearch) MSession.sharedInstance.loadSession() } override func loadView() { let viewParent:VParent = VParent(controller:self) self.viewParent = viewParent view = viewParent } override var preferredStatusBarStyle:UIStatusBarStyle { return statusBarStyle } override var prefersStatusBarHidden:Bool { return barHidden } //MARK: private private func slide(controller:CController, left:CGFloat) { guard let currentController:CController = childViewControllers.last as? CController, let newView:VView = controller.view as? VView, let currentView:VView = currentController.view as? VView else { return } addChildViewController(controller) controller.beginAppearanceTransition(true, animated:true) currentController.beginAppearanceTransition(false, animated:true) viewParent.slide( currentView:currentView, newView:newView, left:left) { controller.endAppearanceTransition() currentController.endAppearanceTransition() currentController.removeFromParentViewController() } } //MARK: public func hideBar(barHidden:Bool) { self.barHidden = barHidden setNeedsStatusBarAppearanceUpdate() } func statusBarAppareance(statusBarStyle:UIStatusBarStyle) { self.statusBarStyle = statusBarStyle setNeedsStatusBarAppearanceUpdate() } func slideTo(horizontal:TransitionHorizontal, controller:CController) { let left:CGFloat = -viewParent.bounds.maxX * horizontal.rawValue slide(controller:controller, left:left) } func mainController(controller:CController) { addChildViewController(controller) guard let newView:VView = controller.view as? VView else { return } viewParent.mainView(view:newView) } func push( controller:CController, horizontal:TransitionHorizontal = TransitionHorizontal.none, vertical:TransitionVertical = TransitionVertical.none, background:Bool = true, completion:(() -> ())? = nil) { let width:CGFloat = viewParent.bounds.maxX let height:CGFloat = viewParent.bounds.maxY let left:CGFloat = width * horizontal.rawValue let top:CGFloat = height * vertical.rawValue guard let currentController:CController = childViewControllers.last as? CController, let newView:VView = controller.view as? VView else { return } addChildViewController(controller) controller.beginAppearanceTransition(true, animated:true) currentController.beginAppearanceTransition(false, animated:true) viewParent.panRecognizer.isEnabled = true viewParent.push( newView:newView, left:left, top:top, background:background) { controller.endAppearanceTransition() currentController.endAppearanceTransition() completion?() } } func animateOver(controller:CController) { guard let currentController:CController = childViewControllers.last as? CController, let newView:VView = controller.view as? VView else { return } addChildViewController(controller) controller.beginAppearanceTransition(true, animated:true) currentController.beginAppearanceTransition(false, animated:true) viewParent.animateOver( newView:newView) { controller.endAppearanceTransition() currentController.endAppearanceTransition() } } func removeBetweenFirstAndLast() { var controllers:Int = childViewControllers.count - 1 while controllers > 1 { controllers -= 1 guard let controller:CController = childViewControllers[controllers] as? CController, let view:VView = controller.view as? VView else { continue } controller.beginAppearanceTransition(false, animated:false) view.removeFromSuperview() controller.endAppearanceTransition() controller.removeFromParentViewController() } } func removeAllButLast() { var controllers:Int = childViewControllers.count - 1 while controllers > 0 { controllers -= 1 guard let controller:CController = childViewControllers[controllers] as? CController, let view:VView = controller.view as? VView else { continue } controller.beginAppearanceTransition(false, animated:false) view.removeFromSuperview() controller.endAppearanceTransition() controller.removeFromParentViewController() } } func pop( horizontal:TransitionHorizontal = TransitionHorizontal.none, vertical:TransitionVertical = TransitionVertical.none, completion:(() -> ())? = nil) { let width:CGFloat = viewParent.bounds.maxX let height:CGFloat = viewParent.bounds.maxY let left:CGFloat = width * horizontal.rawValue let top:CGFloat = height * vertical.rawValue let controllers:Int = childViewControllers.count if controllers > 1 { guard let currentController:CController = childViewControllers[controllers - 1] as? CController, let previousController:CController = childViewControllers[controllers - 2] as? CController, let currentView:VView = currentController.view as? VView else { return } currentController.beginAppearanceTransition(false, animated:true) previousController.beginAppearanceTransition(true, animated:true) viewParent.pop( currentView:currentView, left:left, top:top) { previousController.endAppearanceTransition() currentController.endAppearanceTransition() currentController.removeFromParentViewController() completion?() if self.childViewControllers.count > 1 { self.viewParent.panRecognizer.isEnabled = true } else { self.viewParent.panRecognizer.isEnabled = false } } } } func popSilent(removeIndex:Int) { let controllers:Int = childViewControllers.count if controllers > removeIndex { guard let removeController:CController = childViewControllers[removeIndex] as? CController, let removeView:VView = removeController.view as? VView else { return } removeView.pushBackground?.removeFromSuperview() removeView.removeFromSuperview() removeController.removeFromParentViewController() if childViewControllers.count < 2 { self.viewParent.panRecognizer.isEnabled = false } } } func dismissAnimateOver(completion:(() -> ())?) { guard let currentController:CController = childViewControllers.last as? CController, let currentView:VView = currentController.view as? VView else { return } currentController.removeFromParentViewController() guard let previousController:CController = childViewControllers.last as? CController else { return } currentController.beginAppearanceTransition(false, animated:true) previousController.beginAppearanceTransition(true, animated:true) viewParent.dismissAnimateOver( currentView:currentView) { currentController.endAppearanceTransition() previousController.endAppearanceTransition() completion?() } } }
mit
d18731b9c3b0e21e345f0061e382026a
27.373219
107
0.560398
6.458495
false
false
false
false
wordpress-mobile/WordPress-iOS
WordPress/Classes/ViewRelated/Blog/Site Settings/SiteIconPickerPresenter.swift
2
9897
import Foundation import SVProgressHUD import WPMediaPicker import WordPressShared import MobileCoreServices /// Encapsulates the interactions required to capture a new site icon image, crop it and resize it. /// class SiteIconPickerPresenter: NSObject { // MARK: - Public Properties @objc var blog: Blog /// Will be invoked with a Media item from the user library or an error @objc var onCompletion: ((Media?, Error?) -> Void)? @objc var onIconSelection: (() -> Void)? @objc var originalMedia: Media? // MARK: - Private Properties fileprivate let noResultsView = NoResultsViewController.controller() fileprivate var mediaLibraryChangeObserverKey: NSObjectProtocol? = nil /// Media Library Data Source /// fileprivate lazy var mediaLibraryDataSource: WPAndDeviceMediaLibraryDataSource = { return WPAndDeviceMediaLibraryDataSource(blog: self.blog) }() /// Media Picker View Controller /// fileprivate lazy var mediaPickerViewController: WPNavigationMediaPickerViewController = { let options = WPMediaPickerOptions() options.showMostRecentFirst = true options.filter = [.image] options.allowMultipleSelection = false options.showSearchBar = true options.badgedUTTypes = [String(kUTTypeGIF)] options.preferredStatusBarStyle = WPStyleGuide.preferredStatusBarStyle let pickerViewController = WPNavigationMediaPickerViewController(options: options) pickerViewController.dataSource = self.mediaLibraryDataSource pickerViewController.delegate = self pickerViewController.modalPresentationStyle = .formSheet return pickerViewController }() // MARK: - Public methods /// Designated Initializer /// /// - Parameters: /// - blog: The current blog. /// @objc init(blog: Blog) { self.blog = blog noResultsView.configureForNoAssets(userCanUploadMedia: false) super.init() } deinit { unregisterChangeObserver() } /// Presents a new WPMediaPickerViewController instance. /// @objc func presentPickerFrom(_ viewController: UIViewController) { viewController.present(mediaPickerViewController, animated: true) registerChangeObserver(forPicker: mediaPickerViewController.mediaPicker) } // MARK: - Private Methods fileprivate func showLoadingMessage() { SVProgressHUD.setDefaultMaskType(.clear) SVProgressHUD.show(withStatus: NSLocalizedString("Loading...", comment: "Text displayed in HUD while a media item is being loaded.")) } fileprivate func showErrorLoadingImageMessage() { SVProgressHUD.showDismissibleError(withStatus: NSLocalizedString("Unable to load the image. Please choose a different one or try again later.", comment: "Text displayed in HUD if there was an error attempting to load a media image.")) } /// Shows a new ImageCropViewController for the given image. /// fileprivate func showImageCropViewController(_ image: UIImage) { DispatchQueue.main.async { SVProgressHUD.dismiss() let imageCropViewController = ImageCropViewController(image: image) imageCropViewController.maskShape = .square imageCropViewController.onCompletion = { [weak self] image, modified in guard let self = self else { return } self.onIconSelection?() if !modified, let media = self.originalMedia { self.onCompletion?(media, nil) } else { let mediaService = MediaService(managedObjectContext: ContextManager.sharedInstance().mainContext) WPAnalytics.track(.siteSettingsSiteIconCropped) mediaService.createMedia(with: image, blog: self.blog, post: nil, progress: nil, thumbnailCallback: nil, completion: { (media, error) in guard let media = media, error == nil else { WPAnalytics.track(.siteSettingsSiteIconUploadFailed) self.onCompletion?(nil, error) return } var uploadProgress: Progress? mediaService.uploadMedia(media, automatedRetry: false, progress: &uploadProgress, success: { WPAnalytics.track(.siteSettingsSiteIconUploaded) self.onCompletion?(media, nil) }, failure: { (error) in WPAnalytics.track(.siteSettingsSiteIconUploadFailed) self.onCompletion?(nil, error) }) }) } } self.mediaPickerViewController.show(after: imageCropViewController) } } fileprivate func registerChangeObserver(forPicker picker: WPMediaPickerViewController) { assert(mediaLibraryChangeObserverKey == nil) mediaLibraryChangeObserverKey = mediaLibraryDataSource.registerChangeObserverBlock({ [weak self] _, _, _, _, _ in self?.updateSearchBar(mediaPicker: picker) let isNotSearching = self?.mediaLibraryDataSource.searchQuery?.count ?? 0 != 0 let hasNoAssets = self?.mediaLibraryDataSource.numberOfAssets() == 0 if isNotSearching && hasNoAssets { self?.noResultsView.removeFromView() self?.noResultsView.configureForNoAssets(userCanUploadMedia: false) } }) } fileprivate func unregisterChangeObserver() { if let mediaLibraryChangeObserverKey = mediaLibraryChangeObserverKey { mediaLibraryDataSource.unregisterChangeObserver(mediaLibraryChangeObserverKey) } mediaLibraryChangeObserverKey = nil } fileprivate func updateSearchBar(mediaPicker: WPMediaPickerViewController) { let isSearching = mediaLibraryDataSource.searchQuery?.count ?? 0 != 0 let hasAssets = mediaLibraryDataSource.numberOfAssets() > 0 if mediaLibraryDataSource.dataSourceType == .mediaLibrary && (isSearching || hasAssets) { mediaPicker.showSearchBar() if let searchBar = mediaPicker.searchBar { WPStyleGuide.configureSearchBar(searchBar) } } else { mediaPicker.hideSearchBar() } } } extension SiteIconPickerPresenter: WPMediaPickerViewControllerDelegate { func mediaPickerControllerWillBeginLoadingData(_ picker: WPMediaPickerViewController) { updateSearchBar(mediaPicker: picker) noResultsView.configureForFetching() } func mediaPickerControllerDidEndLoadingData(_ picker: WPMediaPickerViewController) { noResultsView.removeFromView() noResultsView.configureForNoAssets(userCanUploadMedia: false) updateSearchBar(mediaPicker: picker) } func mediaPickerController(_ picker: WPMediaPickerViewController, didUpdateSearchWithAssetCount assetCount: Int) { noResultsView.removeFromView() if (mediaLibraryDataSource.searchQuery?.count ?? 0) > 0 { noResultsView.configureForNoSearchResult() } } func mediaPickerController(_ picker: WPMediaPickerViewController, shouldShow asset: WPMediaAsset) -> Bool { return asset.isKind(of: PHAsset.self) } func mediaPickerControllerDidCancel(_ picker: WPMediaPickerViewController) { mediaLibraryDataSource.searchCancelled() onCompletion?(nil, nil) } /// Retrieves the chosen image and triggers the ImageCropViewController display. /// func mediaPickerController(_ picker: WPMediaPickerViewController, didFinishPicking assets: [WPMediaAsset]) { mediaLibraryDataSource.searchCancelled() if assets.isEmpty { return } let asset = assets.first WPAnalytics.track(.siteSettingsSiteIconGalleryPicked) switch asset { case let phAsset as PHAsset: showLoadingMessage() originalMedia = nil let exporter = MediaAssetExporter(asset: phAsset) exporter.imageOptions = MediaImageExporter.Options() exporter.export(onCompletion: { [weak self](assetExport) in guard let image = UIImage(contentsOfFile: assetExport.url.path) else { self?.showErrorLoadingImageMessage() return } self?.showImageCropViewController(image) }, onError: { [weak self](error) in self?.showErrorLoadingImageMessage() }) case let media as Media: showLoadingMessage() originalMedia = media MediaThumbnailCoordinator.shared.thumbnail(for: media, with: CGSize.zero, onCompletion: { [weak self] (image, error) in guard let image = image else { self?.showErrorLoadingImageMessage() return } self?.showImageCropViewController(image) }) default: break } } func emptyViewController(forMediaPickerController picker: WPMediaPickerViewController) -> UIViewController? { return noResultsView } }
gpl-2.0
e27119113a64b13ddf2187d3d47ba6eb
38.588
163
0.616348
6.1702
false
false
false
false
antonio081014/LeeCode-CodeBase
Swift/binary-search-tree-iterator.swift
2
3411
/** * https://leetcode.com/problems/binary-search-tree-iterator/ * * */ // Date: Mon Aug 24 14:15:09 PDT 2020 /** * Definition for a binary tree node. * public class TreeNode { * public var val: Int * public var left: TreeNode? * public var right: TreeNode? * public init() { self.val = 0; self.left = nil; self.right = nil; } * public init(_ val: Int) { self.val = val; self.left = nil; self.right = nil; } * public init(_ val: Int, _ left: TreeNode?, _ right: TreeNode?) { * self.val = val * self.left = left * self.right = right * } * } */ class BSTIterator { var candidate: [Int] var index: Int init(_ root: TreeNode?) { self.candidate = BSTIterator.inorderTraversal(root) self.index = 0 } /// Iterative solution. private static func inorderTraversal(_ root: TreeNode?) -> [Int] { guard let root = root else { return [] } var result = [Int]() var stack: [TreeNode] = [] self.pushAllLeftChildren(root, into: &stack) while stack.isEmpty == false { let node = stack.removeLast() result.append(node.val) self.pushAllLeftChildren(node.right, into: &stack) } return result } private static func pushAllLeftChildren(_ root: TreeNode?, into stack: inout [TreeNode]) { var node = root while let cNode = node { stack.append(cNode) node = cNode.left } } /** @return the next smallest number */ func next() -> Int { let val = self.candidate[index] index += 1 return val } /** @return whether we have a next smallest number */ func hasNext() -> Bool { return index < self.candidate.count } } /** * Your BSTIterator object will be instantiated and called as such: * let obj = BSTIterator(root) * let ret_1: Int = obj.next() * let ret_2: Bool = obj.hasNext() *//** * https://leetcode.com/problems/binary-search-tree-iterator/ * * */ // Date: Wed Dec 9 09:56:33 PST 2020 /** * Definition for a binary tree node. * public class TreeNode { * public var val: Int * public var left: TreeNode? * public var right: TreeNode? * public init() { self.val = 0; self.left = nil; self.right = nil; } * public init(_ val: Int) { self.val = val; self.left = nil; self.right = nil; } * public init(_ val: Int, _ left: TreeNode?, _ right: TreeNode?) { * self.val = val * self.left = left * self.right = right * } * } */ class BSTIterator { let list: [Int] var pointer: Int init(_ root: TreeNode?) { self.pointer = 0 var array: [Int] = [] func inorder(_ root: TreeNode?) { guard let root = root else { return } inorder(root.left) array.append(root.val) inorder(root.right) } inorder(root) self.list = array } func next() -> Int { let val = self.list[self.pointer] self.pointer += 1 return val } func hasNext() -> Bool { return self.pointer < self.list.count } } /** * Your BSTIterator object will be instantiated and called as such: * let obj = BSTIterator(root) * let ret_1: Int = obj.next() * let ret_2: Bool = obj.hasNext() */
mit
e96a25e3edf1eb899b16f01f04178bb1
25.449612
94
0.552917
3.663802
false
false
false
false
bryanmikaelian/GaugeKit
GaugeKit/Gauge.swift
1
7778
// // Gauge.swift // SWGauge // // Created by Petr Korolev on 02/06/15. // Copyright (c) 2015 Petr Korolev. All rights reserved. // import UIKit import QuartzCore @IBDesignable public class Gauge: UIView { enum GaugeType: Int { case Circle = 0 case Left case Right case Line case Custom } @IBInspectable public var startColor: UIColor = UIColor.greenColor() { didSet { resetLayers() updateLayerProperties() } } /// default is nil: endColor is same as startColor @IBInspectable public var endColor: UIColor { get { if let _endColor = _endColor { return _endColor } else { return UIColor.redColor() } } set { _endColor = newValue } } private var _endColor: UIColor? { didSet { resetLayers() updateLayerProperties() } } @IBInspectable public var bgColor: UIColor? { didSet { updateLayerProperties() setNeedsLayout() } } internal var _bgStartColor: UIColor { get { if let bgColor = bgColor { return bgColor.colorWithAlphaComponent(bgAlpha) } else { return startColor.colorWithAlphaComponent(bgAlpha) } } } internal var _bgEndColor: UIColor { get { if let bgColor = bgColor { return bgColor.colorWithAlphaComponent(bgAlpha) } else { return endColor.colorWithAlphaComponent(bgAlpha) } } } @IBInspectable public var bgAlpha: CGFloat = 0.2 { didSet { updateLayerProperties() } } @IBInspectable public var rotate: Double = 0 { didSet { updateLayerProperties() } } @IBInspectable public var colorsArray: Bool = false { didSet { updateLayerProperties() } } @IBInspectable public var shadowRadius: CGFloat = 0 { didSet { updateLayerProperties() } } @IBInspectable public var shadowOpacity: Float = 0.5 { didSet { updateLayerProperties() } } @IBInspectable public var reverse: Bool = false { didSet { resetLayers() updateLayerProperties() } } /// Default is equal to #lineWidth. Set it to 0 to remove round edges @IBInspectable public var roundCap: Bool = true { didSet { updateLayerProperties() } } var type: GaugeType = .Circle { didSet { resetLayers() updateLayerProperties() } } /// Convenience property to setup type variable from IB @IBInspectable var gaugeTypeInt: Int { get { return type.rawValue } set(newValue) { if let newType = GaugeType(rawValue: newValue) { type = newType } else { type = .Circle } } } /// This value specify rate value for 100% filled gauge. Default is 10. ///i.e. with rate = 10 gauge is 100% filled. @IBInspectable public var maxValue: CGFloat = 10 { didSet { updateLayerProperties() } } /// percantage of filled Gauge. 0..maxValue. @IBInspectable public var rate: CGFloat = 8 { didSet { updateLayerProperties() } } @IBInspectable var isCircle: Bool = false { didSet { updateLayerProperties() } } @IBInspectable var lineWidth: CGFloat = 15.0 { didSet { updateLayerProperties() } } /// Main gauge layer var gaugeLayer: CALayer! /// Colored layer, depends from scale var ringLayer: CAShapeLayer! /// background for ring layer var bgLayer: CAShapeLayer! /// ring gradient layer var ringGradientLayer: CAGradientLayer! /// background gradient var bgGradientLayer: CAGradientLayer! func getGauge(rotateAngle: Double = 0) -> CAShapeLayer { switch type { case .Left, .Right: return getHalfGauge(rotateAngle) case .Circle: return getCircleGauge(rotateAngle) case .Line: return getLineGauge(rotateAngle) default: return getCircleGauge(rotateAngle) } } func updateLayerProperties() { backgroundColor = UIColor.clearColor() if (ringLayer != nil) { switch (type) { case .Left, .Right: // For Half gauge you have to fill 50% of circle and round it wisely. let percanage = rate / 2 / maxValue % 0.5 ringLayer.strokeEnd = (rate >= maxValue ? 0.5 : percanage + ((rate != 0 && percanage == 0) ? 0.5 : 0)) case .Circle, .Custom: ringLayer.strokeEnd = rate / maxValue default: ringLayer.strokeEnd = rate / maxValue } var strokeColor = UIColor.lightGrayColor() //TODO: replace pre-defined colors with array of user-defined colors //TODO: and split them proportionally in whole sector if colorsArray { switch (rate / maxValue) { case let r where r >= 0.75: strokeColor = UIColor(hue: 112.0 / 360.0, saturation: 0.39, brightness: 0.85, alpha: 1.0) case let r where r >= 0.5: strokeColor = UIColor(hue: 208.0 / 360.0, saturation: 0.51, brightness: 0.75, alpha: 1.0) case let r where r >= 0.25: strokeColor = UIColor(hue: 40.0 / 360.0, saturation: 0.39, brightness: 0.85, alpha: 1.0) default: strokeColor = UIColor(hue: 359.0 / 360.0, saturation: 0.48, brightness: 0.63, alpha: 1.0) } if (ringGradientLayer != nil) { ringGradientLayer.colors = [strokeColor.CGColor, strokeColor.CGColor] } else { ringLayer.strokeColor = strokeColor.CGColor } } else { ringLayer.strokeColor = startColor.CGColor } } } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) updateLayerProperties() } public override init(frame: CGRect) { super.init(frame: frame) updateLayerProperties() } public override func drawRect(rect: CGRect) { super.drawRect(rect) updateLayerProperties() } func reverseX(layer: CALayer) { // layer.transform = CATransform3DScale(CATransform3DMakeRotation(CGFloat(M_PI_2), 0, 0, 1), -1, 1, 1) layer.transform = CATransform3DScale(layer.transform, -1, 1, 1) } func reverseY(layer: CALayer) { // layer.transform = CATransform3DScale(CATransform3DMakeRotation(CGFloat(M_PI_2), 0, 0, 1), 1, -1, 1) layer.transform = CATransform3DScale(layer.transform, 1, -1, 1) } func resetLayers() { layer.sublayers = nil bgLayer = nil ringLayer = nil ringGradientLayer = nil bgGradientLayer = nil } public override func layoutSubviews() { resetLayers() gaugeLayer = getGauge(rotate / 10 * M_PI) layer.addSublayer(gaugeLayer) updateLayerProperties() } }
mit
75d92adb8735790f8b3bb8cb753c76e7
26.679715
118
0.529956
4.985897
false
false
false
false
hughbe/swift
test/SILGen/protocol_class_refinement.swift
3
4807
// RUN: %target-swift-frontend -emit-silgen %s | %FileCheck %s protocol UID { func uid() -> Int var clsid: Int { get set } var iid: Int { get } } extension UID { var nextCLSID: Int { get { return clsid + 1 } set { clsid = newValue - 1 } } } protocol ObjectUID : class, UID {} extension ObjectUID { var secondNextCLSID: Int { get { return clsid + 2 } set { } } } class Base {} // CHECK-LABEL: sil hidden @_T025protocol_class_refinement12getObjectUID{{[_0-9a-zA-Z]*}}F func getObjectUID<T: ObjectUID>(x: T) -> (Int, Int, Int, Int) { var x = x // CHECK: [[XBOX:%.*]] = alloc_box $<τ_0_0 where τ_0_0 : ObjectUID> { var τ_0_0 } <T> // CHECK: [[PB:%.*]] = project_box [[XBOX]] // -- call x.uid() // CHECK: [[GET_UID:%.*]] = witness_method $T, #UID.uid!1 // CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PB]] : $*T // CHECK: [[X:%.*]] = load [copy] [[READ]] // CHECK: [[X_TMP:%.*]] = alloc_stack // CHECK: store [[X]] to [init] [[X_TMP]] // CHECK: [[UID:%.*]] = apply [[GET_UID]]<T>([[X_TMP]]) // CHECK: [[X2:%.*]] = load [take] [[X_TMP]] // CHECK: destroy_value [[X2]] // -- call set x.clsid // CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] [[PB]] : $*T // CHECK: [[SET_CLSID:%.*]] = witness_method $T, #UID.clsid!setter.1 // CHECK: apply [[SET_CLSID]]<T>([[UID]], [[WRITE]]) x.clsid = x.uid() // -- call x.uid() // CHECK: [[GET_UID:%.*]] = witness_method $T, #UID.uid!1 // CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PB]] : $*T // CHECK: [[X:%.*]] = load [copy] [[READ]] // CHECK: [[X_TMP:%.*]] = alloc_stack // CHECK: store [[X]] to [init] [[X_TMP]] // CHECK: [[UID:%.*]] = apply [[GET_UID]]<T>([[X_TMP]]) // CHECK: [[X2:%.*]] = load [take] [[X_TMP]] // CHECK: destroy_value [[X2]] // -- call nextCLSID from protocol ext // CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] [[PB]] : $*T // CHECK: [[SET_NEXTCLSID:%.*]] = function_ref @_T025protocol_class_refinement3UIDPAAE9nextCLSIDSifs // CHECK: apply [[SET_NEXTCLSID]]<T>([[UID]], [[WRITE]]) x.nextCLSID = x.uid() // -- call x.uid() // CHECK: [[READ1:%.*]] = begin_access [read] [unknown] [[PB]] : $*T // CHECK: [[X1:%.*]] = load [copy] [[READ1]] // CHECK: [[GET_UID:%.*]] = witness_method $T, #UID.uid!1 // CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PB]] : $*T // CHECK: [[X:%.*]] = load [copy] [[READ]] // CHECK: [[X_TMP:%.*]] = alloc_stack // CHECK: store [[X]] to [init] [[X_TMP]] // CHECK: [[UID:%.*]] = apply [[GET_UID]]<T>([[X_TMP]]) // CHECK: [[X2:%.*]] = load [take] [[X_TMP]] // CHECK: destroy_value [[X2]] // -- call secondNextCLSID from class-constrained protocol ext // CHECK: [[SET_SECONDNEXT:%.*]] = function_ref @_T025protocol_class_refinement9ObjectUIDPAAE15secondNextCLSIDSifs // CHECK: apply [[SET_SECONDNEXT]]<T>([[UID]], [[X1]]) // CHECK: destroy_value [[X1]] x.secondNextCLSID = x.uid() return (x.iid, x.clsid, x.nextCLSID, x.secondNextCLSID) // CHECK: return } // CHECK-LABEL: sil hidden @_T025protocol_class_refinement16getBaseObjectUID{{[_0-9a-zA-Z]*}}F func getBaseObjectUID<T: UID where T: Base>(x: T) -> (Int, Int, Int) { var x = x // CHECK: [[XBOX:%.*]] = alloc_box $<τ_0_0 where τ_0_0 : Base, τ_0_0 : UID> { var τ_0_0 } <T> // CHECK: [[PB:%.*]] = project_box [[XBOX]] // -- call x.uid() // CHECK: [[GET_UID:%.*]] = witness_method $T, #UID.uid!1 // CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PB]] : $*T // CHECK: [[X:%.*]] = load [copy] [[READ]] // CHECK: [[X_TMP:%.*]] = alloc_stack // CHECK: store [[X]] to [init] [[X_TMP]] // CHECK: [[UID:%.*]] = apply [[GET_UID]]<T>([[X_TMP]]) // CHECK: [[X2:%.*]] = load [take] [[X_TMP]] // CHECK: destroy_value [[X2]] // -- call set x.clsid // CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] [[PB]] : $*T // CHECK: [[SET_CLSID:%.*]] = witness_method $T, #UID.clsid!setter.1 // CHECK: apply [[SET_CLSID]]<T>([[UID]], [[WRITE]]) x.clsid = x.uid() // -- call x.uid() // CHECK: [[GET_UID:%.*]] = witness_method $T, #UID.uid!1 // CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PB]] : $*T // CHECK: [[X:%.*]] = load [copy] [[READ]] // CHECK: [[X_TMP:%.*]] = alloc_stack // CHECK: store [[X]] to [init] [[X_TMP]] // CHECK: [[UID:%.*]] = apply [[GET_UID]]<T>([[X_TMP]]) // CHECK: [[X2:%.*]] = load [take] [[X_TMP]] // CHECK: destroy_value [[X2]] // -- call nextCLSID from protocol ext // CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] [[PB]] : $*T // CHECK: [[SET_NEXTCLSID:%.*]] = function_ref @_T025protocol_class_refinement3UIDPAAE9nextCLSIDSifs // CHECK: apply [[SET_NEXTCLSID]]<T>([[UID]], [[WRITE]]) x.nextCLSID = x.uid() return (x.iid, x.clsid, x.nextCLSID) // CHECK: return }
apache-2.0
6252f115d492c7b78b46e7cebba1c3e1
38.344262
116
0.533958
2.898551
false
false
false
false
Jigsaw-Code/outline-client
src/cordova/plugin/apple/src/OutlineConnectivity.swift
1
2898
// Copyright 2018 The Outline Authors // // 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 CocoaLumberjack import CocoaLumberjackSwift import Tun2socks // Class to perform connectivity tests against remote Outline servers. class OutlineConnectivity: NSObject { // Asynchronously calls |completion| with a boolean representing whether |host| and |port| // are reachable. func isServerReachable(host: String, port: UInt16, completion: @escaping((Bool) -> Void)) { DispatchQueue.global(qos: .background).async { guard let networkIp = self.getNetworkIpAddress(host) else { DDLogError("Failed to retrieve the remote host IP address in the network"); return completion(false) } completion(ShadowsocksCheckServerReachable(networkIp, Int(port), nil)) } } // Calls getaddrinfo to retrieve the IP address literal as a string for |ipv4Address| in the // active network. This is necessary to support IPv6 DNS64/NAT64 networks. For more details see: // https://developer.apple.com/library/content/documentation/NetworkingInternetWeb/Conceptual/NetworkingOverview/UnderstandingandPreparingfortheIPv6Transition/UnderstandingandPreparingfortheIPv6Transition.html private func getNetworkIpAddress(_ ipv4Address: String) -> String? { var hints = addrinfo( ai_flags: AI_DEFAULT, ai_family: AF_UNSPEC, ai_socktype: SOCK_STREAM, ai_protocol: 0, ai_addrlen: 0, ai_canonname: nil, ai_addr: nil, ai_next: nil) var info: UnsafeMutablePointer<addrinfo>? let err = getaddrinfo(ipv4Address, nil, &hints, &info) if err != 0 { DDLogError("getaddrinfo failed \(String(describing: gai_strerror(err)))") return nil } defer { freeaddrinfo(info) } return getIpAddressString(addr: info?.pointee.ai_addr) } private func getIpAddressString(addr: UnsafePointer<sockaddr>?) -> String? { guard addr != nil else { DDLogError("Failed to get IP address string: invalid argument") return nil } var host : String? var buffer = [CChar](repeating: 0, count: Int(NI_MAXHOST)) let err = getnameinfo(addr, socklen_t(addr!.pointee.sa_len), &buffer, socklen_t(buffer.count), nil, 0, NI_NUMERICHOST | NI_NUMERICSERV) if err == 0 { host = String(cString: buffer) } return host } }
apache-2.0
8e2cd4951673560fac244786041a4747
38.69863
211
0.700828
4.193922
false
false
false
false
mohamede1945/quran-ios
Quran/QuranDataSource.swift
1
3009
// // QuranDataSource.swift // Quran // // Created by Mohamed Afifi on 3/19/17. // // Quran for iOS is a Quran reading application for iOS. // Copyright (C) 2017 Quran.com // // 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. // import Foundation import GenericDataSources class QuranDataSource: SegmentedDataSource { private let dataSourceHandlers: [QuranDataSourceHandler] private let dataSourceRepresentables: [AnyBasicDataSourceRepresentable<QuranPage>] var onScrollViewWillBeginDragging: (() -> Void)? private var selectedDataSourceHandler: QuranDataSourceHandler { return dataSourceHandlers[selectedDataSourceIndex] } var selectedBasicDataSource: AnyBasicDataSourceRepresentable<QuranPage> { return dataSourceRepresentables[selectedDataSourceIndex] } override var selectedDataSource: DataSource? { didSet { if oldValue !== selectedDataSource { ds_reusableViewDelegate?.ds_reloadData() } } } init(dataSources: [AnyBasicDataSourceRepresentable<QuranPage>], handlers: [QuranDataSourceHandler]) { assert(dataSources.count == handlers.count) self.dataSourceHandlers = handlers self.dataSourceRepresentables = dataSources super.init() for ds in dataSources { add(ds.dataSource) } NotificationCenter.default.addObserver(self, selector: #selector(applicationDidBecomeActive), name: .UIApplicationDidBecomeActive, object: nil) handlers.forEach { $0.onScrollViewWillBeginDragging = { [weak self] in self?.onScrollViewWillBeginDragging?() } } } deinit { NotificationCenter.default.removeObserver(self) } func applicationDidBecomeActive() { selectedDataSourceHandler.applicationDidBecomeActive() } func highlightAyaht(_ ayat: Set<AyahNumber>) { for (offset, ds) in dataSourceHandlers.enumerated() { ds.highlightAyaht(ayat, isActive: offset == selectedDataSourceIndex) } } func setItems(_ items: [QuranPage]) { for ds in dataSourceRepresentables { ds.items = items } ds_reusableViewDelegate?.ds_reloadData() } func invalidate() { dataSourceHandlers.forEach { $0.invalidate() } ds_reusableViewDelegate?.ds_reloadData() } }
gpl-3.0
6f9eaa7540f36cc80e2055d6d968fed9
32.065934
105
0.652044
5.091371
false
false
false
false
justindarc/firefox-ios
Client/Frontend/Browser/TabTrayController+KeyCommands.swift
2
4568
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Shared import UIKit extension TabTrayController { override var keyCommands: [UIKeyCommand]? { let toggleText = tabDisplayManager.isPrivate ? Strings.SwitchToNonPBMKeyCodeTitle: Strings.SwitchToPBMKeyCodeTitle var commands = [ UIKeyCommand(input: "`", modifierFlags: .command, action: #selector(didTogglePrivateModeKeyCommand), discoverabilityTitle: toggleText), UIKeyCommand(input: "w", modifierFlags: .command, action: #selector(didCloseTabKeyCommand)), UIKeyCommand(input: "w", modifierFlags: [.command, .shift], action: #selector(didCloseAllTabsKeyCommand), discoverabilityTitle: Strings.CloseAllTabsFromTabTrayKeyCodeTitle), UIKeyCommand(input: "\\", modifierFlags: [.command, .shift], action: #selector(didEnterTabKeyCommand)), UIKeyCommand(input: "\t", modifierFlags: [.command, .alternate], action: #selector(didEnterTabKeyCommand)), UIKeyCommand(input: "t", modifierFlags: .command, action: #selector(didOpenNewTabKeyCommand), discoverabilityTitle: Strings.OpenNewTabFromTabTrayKeyCodeTitle), UIKeyCommand(input: UIKeyCommand.inputDownArrow, modifierFlags: [], action: #selector(didChangeSelectedTabKeyCommand(sender:))), UIKeyCommand(input: UIKeyCommand.inputUpArrow, modifierFlags: [], action: #selector(didChangeSelectedTabKeyCommand(sender:))), ] if !searchBar.isFirstResponder { let extraCommands = [ UIKeyCommand(input: "\u{8}", modifierFlags: [], action: #selector(didCloseTabKeyCommand), discoverabilityTitle: Strings.CloseTabFromTabTrayKeyCodeTitle), UIKeyCommand(input: UIKeyCommand.inputLeftArrow, modifierFlags: [], action: #selector(didChangeSelectedTabKeyCommand(sender:))), UIKeyCommand(input: "\r", modifierFlags: [], action: #selector(didEnterTabKeyCommand), discoverabilityTitle: Strings.OpenSelectedTabFromTabTrayKeyCodeTitle), UIKeyCommand(input: UIKeyCommand.inputRightArrow, modifierFlags: [], action: #selector(didChangeSelectedTabKeyCommand(sender:))), ] commands.append(contentsOf: extraCommands) } return commands } @objc func didTogglePrivateModeKeyCommand() { // NOTE: We cannot and should not capture telemetry here. didTogglePrivateMode() } @objc func didCloseTabKeyCommand() { UnifiedTelemetry.recordEvent(category: .action, method: .press, object: .keyCommand, extras: ["action": "close-tab"]) if let tab = tabManager.selectedTab { tabManager.removeTabAndUpdateSelectedIndex(tab) } } @objc func didCloseAllTabsKeyCommand() { UnifiedTelemetry.recordEvent(category: .action, method: .press, object: .keyCommand, extras: ["action": "close-all-tabs"]) closeTabsForCurrentTray() } @objc func didEnterTabKeyCommand() { UnifiedTelemetry.recordEvent(category: .action, method: .press, object: .keyCommand, extras: ["action": "enter-tab"]) _ = self.navigationController?.popViewController(animated: true) } @objc func didOpenNewTabKeyCommand() { UnifiedTelemetry.recordEvent(category: .action, method: .press, object: .keyCommand, extras: ["action": "new-tab"]) openNewTab() } @objc func didChangeSelectedTabKeyCommand(sender: UIKeyCommand) { UnifiedTelemetry.recordEvent(category: .action, method: .press, object: .keyCommand, extras: ["action": "select-tab"]) let step: Int guard let input = sender.input else { return } switch input { case UIKeyCommand.inputLeftArrow: step = -1 case UIKeyCommand.inputRightArrow: step = 1 case UIKeyCommand.inputUpArrow: step = -numberOfColumns case UIKeyCommand.inputDownArrow: step = numberOfColumns default: step = 0 } let tabs = tabDisplayManager.dataStore let currentIndex: Int if let selected = tabManager.selectedTab { currentIndex = tabs.index(of: selected) ?? 0 } else { currentIndex = 0 } let nextIndex = max(0, min(currentIndex + step, tabs.count - 1)) if let nextTab = tabs.at(nextIndex) { tabManager.selectTab(nextTab) } } }
mpl-2.0
5e1242b4b90c1d85e0cef50f0d796787
49.755556
185
0.675131
4.997812
false
false
false
false
erikmartens/NearbyWeather
NearbyWeather/Scenes/Settings Scene/SettingsViewController.swift
1
3682
// // SettingsViewController.swift // NearbyWeather // // Created by Erik Maximilian Martens on 06.03.22. // Copyright © 2022 Erik Maximilian Martens. All rights reserved. // import UIKit import RxSwift // MARK: - Definitions private extension SettingsViewController { struct Definitions {} } // MARK: - Class Definition final class SettingsViewController: UIViewController, BaseViewController { typealias ViewModel = SettingsViewModel // MARK: - UIComponents fileprivate lazy var tableView = Factory.TableView.make(fromType: .standard(frame: view.frame)) // MARK: - Assets private let disposeBag = DisposeBag() // MARK: - Properties let viewModel: ViewModel // MARK: - Initialization required init(dependencies: ViewModel.Dependencies) { viewModel = SettingsViewModel(dependencies: dependencies) super.init(nibName: nil, bundle: nil) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } deinit { printDebugMessage( domain: String(describing: self), message: "was deinitialized", type: .info ) } // MARK: - ViewController LifeCycle override func viewDidLoad() { super.viewDidLoad() viewModel.viewDidLoad() setupUiComponents() setupBindings() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) viewModel.viewWillAppear() setupUiAppearance() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) viewModel.viewWillDisappear() } } // MARK: - ViewModel Bindings extension SettingsViewController { func setupBindings() { viewModel.observeEvents() bindContentFromViewModel(viewModel) bindUserInputToViewModel(viewModel) } func bindContentFromViewModel(_ viewModel: ViewModel) { viewModel .tableDataSource .sectionDataSources .map { _ in () } .asDriver(onErrorJustReturn: ()) .drive(onNext: { [weak tableView] in tableView?.reloadData() }) .disposed(by: disposeBag) } } // MARK: - Setup private extension SettingsViewController { func setupUiComponents() { tableView.dataSource = viewModel.tableDataSource tableView.delegate = viewModel.tableDelegate tableView.registerCells([ SettingsImagedSingleLabelCell.self, SettingsImagedDualLabelCell.self, SettingsImagedDualLabelSubtitleCell.self, SettingsImagedSingleLabelToggleCell.self ]) tableView.contentInset = UIEdgeInsets( top: Constants.Dimensions.TableCellContentInsets.top, left: .zero, bottom: Constants.Dimensions.TableCellContentInsets.bottom, right: .zero ) view.addSubview(tableView, constraints: [ tableView.leadingAnchor.constraint(equalTo: view.leadingAnchor), tableView.trailingAnchor.constraint(equalTo: view.trailingAnchor), tableView.topAnchor.constraint(equalTo: view.topAnchor), tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor) ]) } func setupUiAppearance() { navigationController?.navigationBar.prefersLargeTitles = true navigationItem.largeTitleDisplayMode = .automatic DispatchQueue.main.async { self.navigationController?.navigationBar.sizeToFit() } title = R.string.localizable.tab_settings() tabBarController?.tabBar.isTranslucent = true navigationController?.navigationBar.isTranslucent = true navigationController?.view.backgroundColor = Constants.Theme.Color.ViewElement.secondaryBackground view.backgroundColor = Constants.Theme.Color.ViewElement.secondaryBackground } }
mit
8df73ef2647767565b0063a65a9714a5
25.106383
102
0.715838
5.098338
false
false
false
false
ghclara/hackaLink
LinkHub/LinkHub/AppDelegate.swift
1
6079
// // AppDelegate.swift // LinkHub // // Created by Student on 14/12/15. // Copyright © 2015 Student. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var applicationDocumentsDirectory: NSURL = { // The directory the application uses to store the Core Data store file. This code uses a directory named "com.hacka.LinkHub" in the application's documents Application Support directory. let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls[urls.count-1] }() lazy var managedObjectModel: NSManagedObjectModel = { // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model. let modelURL = NSBundle.mainBundle().URLForResource("LinkHub", withExtension: "momd")! return NSManagedObjectModel(contentsOfURL: modelURL)! }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = { // The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. // Create the coordinator and store let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SingleViewCoreData.sqlite") var failureReason = "There was an error creating or loading the application's saved data." do { try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil) } catch { // Report any error we got. var dict = [String: AnyObject]() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" dict[NSLocalizedFailureReasonErrorKey] = failureReason dict[NSUnderlyingErrorKey] = error as NSError let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) // Replace this with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)") abort() } return coordinator }() lazy var managedObjectContext: NSManagedObjectContext = { // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. let coordinator = self.persistentStoreCoordinator var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType) managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // MARK: - Core Data Saving support func saveContext () { if managedObjectContext.hasChanges { do { try managedObjectContext.save() } catch { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError NSLog("Unresolved error \(nserror), \(nserror.userInfo)") abort() } } } }
mit
c031cc3d60fe76f226b8c1cdba41930c
53.756757
291
0.719151
5.895247
false
false
false
false
apaoww/swift-perfect-web
Package.swift
1
860
// // Package.swift // PerfectTemplate // // Created by Kyle Jessup on 4/20/16. // Copyright (C) 2016 PerfectlySoft, Inc. // //===----------------------------------------------------------------------===// // // This source file is part of the Perfect.org open source project // // Copyright (c) 2015 - 2016 PerfectlySoft Inc. and the Perfect project authors // Licensed under Apache License v2.0 // // See http://perfect.org/licensing.html for license information // //===----------------------------------------------------------------------===// // import PackageDescription let package = Package( name: "PerfectTemplate", targets: [], dependencies: [ .Package(url: "https://github.com/PerfectlySoft/Perfect-HTTPServer.git", majorVersion: 2), .Package(url:"https://github.com/PerfectlySoft/Perfect-MySQL.git", majorVersion: 2, minor: 0) ] )
apache-2.0
fab0b505221a4080a91924decba336a5
28.655172
95
0.576744
4.174757
false
false
false
false
groue/GRMustache.swift
Sources/Context.swift
4
9935
// The MIT License // // Copyright (c) 2015 Gwendal Roué // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation /// A Context represents a state of the Mustache "context stack". /// /// The context stack grows and shrinks as the Mustache engine enters and leaves /// Mustache sections. /// /// The top of the context stack is called the "current context". It is the /// value rendered by the `{{.}}` tag: /// /// // Renders "Kitty, Pussy, Melba, " /// let template = try! Template(string: "{{#cats}}{{.}}, {{/cats}}") /// try! template.render(["cats": ["Kitty", "Pussy", "Melba"]]) /// /// Key lookup starts with the current context and digs down the stack until if /// finds a value: /// /// // Renders "<child>, <parent>, " /// let template = try! Template(string: "{{#children}}<{{name}}>, {{/children}}") /// let data: [String: Any] = [ /// "name": "parent", /// "children": [ /// ["name": "child"], /// [:] // a child without a name /// ] /// ] /// try! template.render(data) /// /// - seealso: Configuration /// - seealso: TemplateRepository /// - seealso: RenderFunction final public class Context { // ========================================================================= // MARK: - Creating Contexts /// Creates an empty Context. public convenience init() { self.init(type: .root) } /// Creates a context that contains the provided value. /// /// - parameter value: A value. public convenience init(_ value: Any?) { self.init(type: .box(box: Box(value), parent: Context())) } /// Creates a context with a registered key. Registered keys are looked up /// first when evaluating Mustache tags. /// /// - parameter key: An identifier. /// - parameter value: A value. public convenience init(registeredKey key: String, value: Any?) { self.init(type: .root, registeredKeysContext: Context([key: value])) } // ========================================================================= // MARK: - Deriving New Contexts /// Creates a new context with the provided value pushed at the top of the /// context stack. /// /// - parameter value: A value. /// - returns: A new context with *value* pushed at the top of the stack. public func extendedContext(_ value: Any?) -> Context { return Context(type: .box(box: Box(value), parent: self), registeredKeysContext: registeredKeysContext) } /// Creates a new context with the provided value registered for *key*. /// Registered keys are looked up first when evaluating Mustache tags. /// /// - parameter key: An identifier. /// - parameter value: A value. /// - returns: A new context with *value* registered for *key*. public func extendedContext(withRegisteredValue value: Any?, forKey key: String) -> Context { let registeredKeysContext = (self.registeredKeysContext ?? Context()).extendedContext([key: value]) return Context(type: self.type, registeredKeysContext: registeredKeysContext) } // ========================================================================= // MARK: - Fetching Values from the Context Stack /// The top box of the context stack, the one that would be rendered by /// the `{{.}}` tag. public var topBox: MustacheBox { switch type { case .root: return EmptyBox case .box(box: let box, parent: _): return box case .partialOverride(partialOverride: _, parent: let parent): return parent.topBox } } /// Returns the boxed value stored in the context stack for the given key. /// /// The following search pattern is used: /// /// 1. If the key is "registered", returns the registered box for that key. /// /// 2. Otherwise, searches the context stack for a box that has a non-empty /// box for the key (see `KeyedSubscriptFunction`). /// /// 3. If none of the above situations occurs, returns the empty box. /// /// let data = ["name": "Groucho Marx"] /// let context = Context(data) /// /// // "Groucho Marx" /// context.mustacheBox(forKey: "name").value /// /// If you want the value for a full Mustache expression such as `user.name` or /// `uppercase(user.name)`, use the `mustacheBox(forExpression:)` method. /// /// - parameter key: A key. /// - returns: The MustacheBox for *key*. public func mustacheBox(forKey key: String) -> MustacheBox { if let registeredKeysContext = registeredKeysContext { let box = registeredKeysContext.mustacheBox(forKey: key) if !box.isEmpty { return box } } switch type { case .root: return EmptyBox case .box(box: let box, parent: let parent): let innerBox = box.mustacheBox(forKey: key) if innerBox.isEmpty { return parent.mustacheBox(forKey: key) } else { return innerBox } case .partialOverride(partialOverride: _, parent: let parent): return parent.mustacheBox(forKey: key) } } /// Evaluates a Mustache expression such as `name`, /// or `uppercase(user.name)`. /// /// let data = ["person": ["name": "Albert Einstein"]] /// let context = Context(data) /// /// // "Albert Einstein" /// try! context.mustacheBoxForExpression("person.name").value /// /// - parameter string: The expression string. /// - throws: MustacheError /// - returns: The value of the expression. public func mustacheBox(forExpression string: String) throws -> MustacheBox { let parser = ExpressionParser() var empty = false let expression = try parser.parse(string, empty: &empty) let invocation = ExpressionInvocation(expression: expression) return try invocation.invokeWithContext(self) } // ========================================================================= // MARK: - Not public fileprivate enum `Type` { case root case box(box: MustacheBox, parent: Context) case partialOverride(partialOverride: TemplateASTNode.PartialOverride, parent: Context) } fileprivate var registeredKeysContext: Context? fileprivate let type: Type var willRenderStack: [WillRenderFunction] { switch type { case .root: return [] case .box(box: let box, parent: let parent): if let willRender = box.willRender { return [willRender] + parent.willRenderStack } else { return parent.willRenderStack } case .partialOverride(partialOverride: _, parent: let parent): return parent.willRenderStack } } var didRenderStack: [DidRenderFunction] { switch type { case .root: return [] case .box(box: let box, parent: let parent): if let didRender = box.didRender { return parent.didRenderStack + [didRender] } else { return parent.didRenderStack } case .partialOverride(partialOverride: _, parent: let parent): return parent.didRenderStack } } var partialOverrideStack: [TemplateASTNode.PartialOverride] { switch type { case .root: return [] case .box(box: _, parent: let parent): return parent.partialOverrideStack case .partialOverride(partialOverride: let partialOverride, parent: let parent): return [partialOverride] + parent.partialOverrideStack } } fileprivate init(type: Type, registeredKeysContext: Context? = nil) { self.type = type self.registeredKeysContext = registeredKeysContext } func extendedContext(partialOverride: TemplateASTNode.PartialOverride) -> Context { return Context(type: .partialOverride(partialOverride: partialOverride, parent: self), registeredKeysContext: registeredKeysContext) } } extension Context: CustomDebugStringConvertible { /// A textual representation of `self`, suitable for debugging. public var debugDescription: String { switch type { case .root: return "Context.Root" case .box(box: let box, parent: let parent): return "Context.Box(\(box)):\(parent.debugDescription)" case .partialOverride(partialOverride: _, parent: let parent): return "Context.PartialOverride:\(parent.debugDescription)" } } }
mit
09ca02866e01e0f111c73e39b26c6cef
36.771863
140
0.596235
4.748566
false
false
false
false
OpsLabJPL/MarsImagesIOS
MarsImagesIOS/Quaternion.swift
1
361
// // Quaternion.swift // MarsImagesIOS // // Created by Mark Powell on 9/26/17. // Copyright © 2017 Mark Powell. All rights reserved. // import Foundation class Quaternion { static let identity = [1.0, 0.0, 0.0, 0.0] public var w = identity[0] public var x = identity[1] public var y = identity[2] public var z = identity[3] }
apache-2.0
ab76795ccf52823e2998e4ba6231b898
17.947368
54
0.627778
3.130435
false
false
false
false
rshevchuk/ScreenSceneController
ScreenSceneController/ScreenSceneControllerTests/ScreenSceneAttachmenSpec.swift
1
7260
// // ScreenSceneAttachmenSpec.swift // ScreenSceneController // // Copyright (c) 2014 Ruslan Shevchuk // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit import Quick import Nimble class ScreenSceneAttachmenSpec: QuickSpec { override func spec() { describe("ScreenSceneAttachment") { var screenSceneAttachment: MockScreenSceneAttachment! beforeEach { screenSceneAttachment = MockScreenSceneAttachment(viewController: UIViewController()) } it("should setup navigationBar when it newly created") { expect(screenSceneAttachment.setupAttachmentNavigationBarWasCalled).to(beFalsy()) screenSceneAttachment.performInitialSetups() expect(screenSceneAttachment.setupAttachmentNavigationBarWasCalled).to(beTruthy()) } it("should setup viewController.view when it newly created") { expect(screenSceneAttachment.setupAttachmentViewControllerViewWasCalled).to(beFalsy()) screenSceneAttachment.performInitialSetups() expect(screenSceneAttachment.setupAttachmentViewControllerViewWasCalled).to(beTruthy()) } it("should setup attachment.containerView when it newly created") { expect(screenSceneAttachment.setupAttachmentContainerOverlayWasCalled).to(beFalsy()) screenSceneAttachment.performInitialSetups() expect(screenSceneAttachment.setupAttachmentContainerOverlayWasCalled).to(beTruthy()) } it("should setup attachment.containerOverlay when it newly created") { expect(screenSceneAttachment.setupAttachmentContainerOverlayWasCalled).to(beFalsy()) screenSceneAttachment.performInitialSetups() expect(screenSceneAttachment.setupAttachmentContainerOverlayWasCalled).to(beTruthy()) } } describe("ScreenSceneAttachmentLayout") { var screenSceneAttachmentLayout: MockScreenSceneAttachmentLayout! beforeEach { screenSceneAttachmentLayout = MockScreenSceneAttachmentLayout() } context("should perform updateAttachemntLayout() when didSet some var") { it("exclusiveFocus") { screenSceneAttachmentLayout.exclusiveFocus = false expect(screenSceneAttachmentLayout.updateAttachemntLayoutWasCalled).to(beTruthy()) } it("portraitWidth") { screenSceneAttachmentLayout.portraitWidth = 100 expect(screenSceneAttachmentLayout.updateAttachemntLayoutWasCalled).to(beTruthy()) } it("landscapeWidth") { screenSceneAttachmentLayout.landscapeWidth = 100 expect(screenSceneAttachmentLayout.updateAttachemntLayoutWasCalled).to(beTruthy()) } it("relative") { screenSceneAttachmentLayout.relative = false expect(screenSceneAttachmentLayout.updateAttachemntLayoutWasCalled).to(beTruthy()) } it("insets") { screenSceneAttachmentLayout.portraitInsets = UIEdgeInsetsZero expect(screenSceneAttachmentLayout.updateAttachemntLayoutWasCalled).to(beTruthy()) screenSceneAttachmentLayout.updateAttachemntLayoutWasCalled = false screenSceneAttachmentLayout.landscapeInsets = UIEdgeInsetsZero expect(screenSceneAttachmentLayout.updateAttachemntLayoutWasCalled).to(beTruthy()) } it("interpolatingEffectRelativeValue") { screenSceneAttachmentLayout.interpolatingEffectRelativeValue = 100 expect(screenSceneAttachmentLayout.updateAttachemntLayoutWasCalled).to(beTruthy()) } it("shadowIntensity") { screenSceneAttachmentLayout.shadowIntensity = 100 expect(screenSceneAttachmentLayout.updateAttachemntLayoutWasCalled).to(beTruthy()) } } it("should have portraitWidth == landscapeWidth when init(width: ...") { screenSceneAttachmentLayout = MockScreenSceneAttachmentLayout() expect(screenSceneAttachmentLayout.landscapeWidth).to(equal(screenSceneAttachmentLayout.portraitWidth)) expect(screenSceneAttachmentLayout.relative).to(equal(true)) } } } } class MockScreenSceneAttachment : ScreenSceneAttachment { var setupAttachmentNavigationBarWasCalled = false var setupAttachmentViewControllerViewWasCalled = false var setupAttachmentContainerViewWasCalled = false var setupAttachmentContainerOverlayWasCalled = false override func setupAttachmentNavigationBar(navigationBar: UINavigationBar, navigationItem: UINavigationItem) { super.setupAttachmentNavigationBar(navigationBar, navigationItem: navigationItem) setupAttachmentNavigationBarWasCalled = true } override func setupAttachmentViewControllerView(view: UIView) { super.setupAttachmentViewControllerView(view) setupAttachmentViewControllerViewWasCalled = true } override func setupAttachmentContainerView(view: UIView) { super.setupAttachmentContainerView(view) setupAttachmentContainerViewWasCalled = true } override func setupAttachmentContainerOverlay(view: UIView) { super.setupAttachmentContainerOverlay(view) setupAttachmentContainerOverlayWasCalled = true } } class MockScreenSceneAttachmentLayout : ScreenSceneAttachmentLayout { var updateAttachemntLayoutWasCalled = false override func updateAttachemntLayout() { super.updateAttachemntLayout() updateAttachemntLayoutWasCalled = true } }
mit
acc9e3d8b0f65aeb9ec34f4eb65d68f7
44.949367
119
0.666253
5.826645
false
false
false
false
Holight/QuiltLayout
QuiltDemo/ViewController.swift
1
8234
// // ViewController.swift // QuiltLayout // import UIKit class ViewController: UIViewController { @IBOutlet weak var collectionView: UICollectionView! var numbers = [Int]() var numberWidths = [Int]() var numberHeights = [Int]() var longPressGestureRecognizer: UIGestureRecognizer! var draggedItem: UICollectionViewCell? override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. dataInit() let layout = collectionView.collectionViewLayout as! QuiltLayout layout.delegate = self //layout.direction = .horizontal //layout.blockPixels = CGSize(width: 50, height: 50) longPressGestureRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(longPressed(_:))) collectionView.addGestureRecognizer(longPressGestureRecognizer) self.collectionView.reloadData() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) collectionView.reloadData() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func dataInit() { numbers.removeAll() numberWidths.removeAll() numberHeights.removeAll() for num in 0...15 { numbers.append(num) numberWidths.append(ViewController.randomLength()) numberHeights.append(ViewController.randomLength()) } } @IBAction func add(_ sender: Any) { let visibleIndexPaths = collectionView.indexPathsForVisibleItems add(indexPath: visibleIndexPaths.first ?? IndexPath(row: 0, section: 0)) } @IBAction func remove(_ sender: Any) { if (numbers.count == 0) { return } let visibleIndexPaths = collectionView.indexPathsForVisibleItems let toRemove = visibleIndexPaths[Int(arc4random()) % visibleIndexPaths.count] remove(indexPath: toRemove) } @IBAction func reload(_ sender: Any) { dataInit() collectionView.reloadData() } func colorForNumber(num: Int) -> UIColor { return UIColor(hue: CGFloat((19 * num) % 255) / 255, saturation: 1, brightness: 1, alpha: 1) } private var isAnimating = false func add(indexPath: IndexPath) { if (indexPath.row > numbers.count) { return } if (isAnimating) { return } isAnimating = true collectionView.performBatchUpdates( { let index = indexPath.row self.numbers.insert(self.numbers.count, at: index) self.numberWidths.insert(ViewController.randomLength(), at: index) self.numberHeights.insert(ViewController.randomLength(), at: index) self.collectionView.insertItems(at: [indexPath]) }) { _ in self.isAnimating = false } } func remove(indexPath: IndexPath) { if (numbers.count == 0 || indexPath.row > numbers.count) { return } if (isAnimating) { return } isAnimating = true collectionView.performBatchUpdates({ let index = indexPath.row self.numbers.remove(at: index) self.numberWidths.remove(at: index) self.numberHeights.remove(at: index) self.collectionView.deleteItems(at: [indexPath]) }) { _ in self.isAnimating = false } } } extension ViewController: UICollectionViewDelegate { func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { remove(indexPath: indexPath) } @objc func longPressed(_ gesture: UIGestureRecognizer) { switch(gesture.state) { case .began: guard let selectedIndexPath = collectionView.indexPathForItem(at: gesture.location(in: collectionView)) else { return } collectionView.beginInteractiveMovementForItem(at: selectedIndexPath) draggedItem = collectionView.cellForItem(at: selectedIndexPath) UIView.animate(withDuration: 0.2) { self.draggedItem?.transform = CGAffineTransform(scaleX: 1.1, y: 1.1) self.draggedItem?.layer.shadowOpacity = 0.2 } case .changed: collectionView.updateInteractiveMovementTargetPosition(gesture.location(in: gesture.view!)) case .ended: collectionView.endInteractiveMovement() UIView.animate(withDuration: 0.1) { self.draggedItem?.transform = CGAffineTransform(scaleX: 1.0, y: 1.0) self.draggedItem?.layer.shadowOpacity = 0.0 } draggedItem = nil default: collectionView.cancelInteractiveMovement() draggedItem = nil } } func collectionView(_ collectionView: UICollectionView, canMoveItemAt indexPath: IndexPath) -> Bool { return true } func collectionView(_ collectionView: UICollectionView, moveItemAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) { } } extension ViewController: UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return numbers.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) cell.backgroundColor = colorForNumber(num: numbers[indexPath.row]) var label = cell.viewWithTag(5) as? UILabel if (label == nil) { label = UILabel(frame: CGRect(x: 0, y: 0, width: 30, height: 20)) } label?.tag = 5 label?.textColor = UIColor.black let number = numbers[indexPath.row] label?.text = "\(number)" label?.backgroundColor = UIColor.clear cell.addSubview(label!) return cell } } extension ViewController: QuiltLayoutDelegate { func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { if (indexPath.row >= numbers.count) { //NSLog(@"Asking for index paths of non-existant cells!! %ld from %lu cells", (long)indexPath.row, (unsigned long)numbers.count); } let width = numberWidths[indexPath.row] let height = numberHeights[indexPath.row] return CGSize(width: width, height: height) } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets { return UIEdgeInsets(top: 2, left: 2, bottom: 2, right: 2) } func collectionView(_ collectionView: UICollectionView, targetIndexPathForMoveFromItemAt originalIndexPath: IndexPath, toProposedIndexPath proposedIndexPath: IndexPath) -> IndexPath { let item = numbers.remove(at: originalIndexPath.item) let width = numberWidths.remove(at: originalIndexPath.item) let height = numberHeights.remove(at: originalIndexPath.item) numbers.insert(item, at: proposedIndexPath.item) numberWidths.insert(width, at: proposedIndexPath.item) numberHeights.insert(height, at: proposedIndexPath.item) return proposedIndexPath } } extension ViewController { static func randomLength() -> Int { // always returns a random length between 1 and 3, weighted towards lower numbers. var result = Int(arc4random() % 6) // 3/6 chance of it being 1. if (result <= 2) { result = 1 } // 1/6 chance of it being 3. else if (result == 5) { result = 3 } // 2/6 chance of it being 2. else { result = 2 } return result } }
unlicense
468259c76fdc2c209314189d1fdbac40
34.8
187
0.629828
5.201516
false
false
false
false
ngominhtrint/Twittient
Twittient/Tweet.swift
1
1810
// // Tweet.swift // Twittient // // Created by TriNgo on 3/24/16. // Copyright © 2016 TriNgo. All rights reserved. // import UIKit class Tweet: NSObject { var id: NSString? var text: NSString? var timeStamp: NSDate? var retweetCount: Int = 0 var favoritesCount: Int = 0 var profileImageUrl: NSURL? var name: NSString? var screenName: NSString? var favorited: Bool = false var retweeted: Bool = false var inReplyToUserId: NSString? override init() { } init(dictionary: NSDictionary){ id = dictionary["id_str"] as? String text = dictionary["text"] as? String retweetCount = (dictionary["retweet_count"] as? Int) ?? 0 favoritesCount = (dictionary["favorite_count"] as? Int) ?? 0 let timeStampString = dictionary["created_at"] as? String if let timeStampString = timeStampString { let formatter = NSDateFormatter() formatter.dateFormat = "EEE MMM d HH:mm:ss Z y" timeStamp = formatter.dateFromString(timeStampString) } favorited = (dictionary["favorited"] as? Bool)! retweeted = (dictionary["retweeted"] as? Bool)! inReplyToUserId = dictionary["in_reply_to_user_id"] as? String let user = User.init(dictionary: dictionary["user"] as! NSDictionary) profileImageUrl = user.profileUrl name = user.name screenName = user.screenName } class func tweetsWithArray(dictionaries: [NSDictionary]) -> [Tweet]{ var tweets = [Tweet]() for dictionary in dictionaries{ let tweet = Tweet(dictionary: dictionary) tweets.append(tweet) } return tweets } }
apache-2.0
7bb6609ae0cfd2fd9b4d60bbbc406e0f
26.830769
77
0.590934
4.603053
false
false
false
false
Cessation/even.tr
Pods/ALCameraViewController/ALCameraViewController/Utilities/UIButtonExtensions.swift
3
1408
// // UIButtonExtensions.swift // ALCameraViewController // // Created by Alex Littlejohn on 2016/03/26. // Copyright © 2016 zero. All rights reserved. // import UIKit typealias ButtonAction = () -> Void extension UIButton { private struct AssociatedKeys { static var ActionKey = "ActionKey" } private class ActionWrapper { let action: ButtonAction init(action: ButtonAction) { self.action = action } } var action: ButtonAction? { set(newValue) { removeTarget(self, action: #selector(UIButton.performAction), forControlEvents: UIControlEvents.TouchUpInside) var wrapper: ActionWrapper? if let newValue = newValue { wrapper = ActionWrapper(action: newValue) addTarget(self, action: #selector(UIButton.performAction), forControlEvents: UIControlEvents.TouchUpInside) } objc_setAssociatedObject(self, &AssociatedKeys.ActionKey, wrapper, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } get { guard let wrapper = objc_getAssociatedObject(self, &AssociatedKeys.ActionKey) as? ActionWrapper else { return nil } return wrapper.action } } func performAction() { if let a = action { a() } } }
apache-2.0
f0a1c0a8dbd4d2d589e6baa52fe93f63
26.057692
123
0.591329
5.230483
false
false
false
false
lammertw/BoxesView
Example/BoxesView/ViewController.swift
1
1811
// // ViewController.swift // BoxesView // // Created by Lammert Westerhoff on 02/14/2016. // Copyright (c) 2016 Lammert Westerhoff. All rights reserved. // import UIKit import BoxesView import SnapKit class ViewController: UIViewController { @IBOutlet weak var boxesView: BoxesView! @IBOutlet weak var photosBoxesView: BoxesView! @IBOutlet weak var fixedHeightSwitch: UISwitch! @IBOutlet weak var boxHeightSwitch: UISwitch! @IBOutlet weak var acpectRatio: UISwitch! override func viewDidLoad() { super.viewDidLoad() recreateBoxes() } @IBAction private func recreateBoxes() { boxesView.rowHeight = fixedHeightSwitch.on ? 40 : -1 photosBoxesView.rowHeight = fixedHeightSwitch.on ? 60 : -1 boxesView.boxes = [ colorView(.greenColor(), height: 20), colorView(.purpleColor(), height: 15), colorView(.yellowColor(), height: 25), colorView(.grayColor(), height: 60), colorView(.magentaColor(), height: 35), ] photosBoxesView.boxes = [ photoView(1), photoView(2), photoView(3), photoView(4), ] } private func colorView(color: UIColor, height: Float? = nil) -> UIView { let view = UIView() view.backgroundColor = color if let height = height where boxHeightSwitch.on { view.snp_makeConstraints { make in make.height.equalTo(height) } } return view } private func photoView(index: Int) -> UIView { let imageView = UIImageView(image: UIImage(named: "photo\(index)")!) imageView.contentMode = acpectRatio.on ? .ScaleAspectFit : .ScaleToFill return imageView } }
mit
d16bc57d235b905fc2ec86d3547da969
26.439394
79
0.606295
4.504975
false
false
false
false
Zverik/omim
iphone/Maps/Core/Ads/BannerType.swift
4
1481
enum BannerType { case none case facebook(String) case rb(String) case mopub(String) var banner: Banner? { switch self { case .none: return nil case .facebook(let id): return FacebookBanner(bannerID: id) case .rb(let id): return RBBanner(bannerID: id) case .mopub(let id): return MopubBanner(bannerID: id) } } var mwmType: MWMBannerType { switch self { case .none: return .none case .facebook: return .facebook case .rb: return .rb case .mopub: return .mopub } } init(type: MWMBannerType, id: String) { switch type { case .none: self = .none case .facebook: self = .facebook(id) case .rb: self = .rb(id) case .mopub: self = .mopub(id) } } } extension BannerType: Equatable { static func ==(lhs: BannerType, rhs: BannerType) -> Bool { switch (lhs, rhs) { case (.none, .none): return true case let (.facebook(l), .facebook(r)): return l == r case let (.rb(l), .rb(r)): return l == r case let (.mopub(l), .mopub(r)): return l == r case (.none, _), (.facebook, _), (.rb, _), (.mopub, _): return false } } } extension BannerType: Hashable { var hashValue: Int { switch self { case .none: return mwmType.hashValue case .facebook(let id): return mwmType.hashValue ^ id.hashValue case .rb(let id): return mwmType.hashValue ^ id.hashValue case .mopub(let id): return mwmType.hashValue ^ id.hashValue } } }
apache-2.0
01c52bca0d7b80d192a7ecaa6af82a42
24.101695
67
0.606347
3.420323
false
false
false
false
cornerAnt/PilesSugar
PilesSugar/PilesSugar/Module/Club/ClubMore/Model/ClubListModel.swift
1
1355
// // ClubListModel.swift // PilesSugar // // Created by SoloKM on 16/1/22. // Copyright © 2016年 SoloKM. All rights reserved. // import UIKit import SwiftyJSON class ClubListModel: NSObject { var path: String? var name:String? var member_count :Int! override init() { super.init() path = "" name = "" member_count = 0 } class func loadClubListModels(data:NSData) -> [ClubListModel]{ let json = JSON(data: data) var clubListModels = [ClubListModel]() for (_,subJson):(String, JSON) in json["data"]["object_list"]{ let clubListModel = ClubListModel() clubListModel.name = subJson["name"].stringValue clubListModel.path = subJson["photo"]["path"].stringValue clubListModel.member_count = subJson["member_count"].intValue clubListModels.append(clubListModel) } return clubListModels } } /* "id": "562dba25257ac474e6bf0182", "member_count": 3945, "name": "热缩片", "photo": { "path": "http://img4q.duitang.com/uploads/people/201510/29/20151029103154_sPxUX.jpeg" } }, */
apache-2.0
02ff1364ca4ad6cc2f4b27f99c6537c5
18.808824
85
0.518574
4.232704
false
false
false
false
apple/swift-driver
Sources/SwiftDriver/ExplicitModuleBuilds/ModuleDependencyScanning.swift
1
20281
//===--------------- ModuleDependencyScanning.swift -----------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2020 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import TSCBasic // <<< import protocol TSCBasic.FileSystem import struct TSCBasic.AbsolutePath import struct TSCBasic.Diagnostic import var TSCBasic.localFileSystem import var TSCBasic.stdoutStream import SwiftOptions import struct Foundation.Data import class Foundation.JSONEncoder import class Foundation.JSONDecoder import var Foundation.EXIT_SUCCESS extension Diagnostic.Message { static func warn_scanner_frontend_fallback() -> Diagnostic.Message { .warning("Fallback to `swift-frontend` dependency scanner invocation") } static func scanner_diagnostic_error(_ message: String) -> Diagnostic.Message { .error("Dependency scanning failure: \(message)") } static func scanner_diagnostic_warn(_ message: String) -> Diagnostic.Message { .warning(message) } static func scanner_diagnostic_note(_ message: String) -> Diagnostic.Message { .note(message) } static func scanner_diagnostic_remark(_ message: String) -> Diagnostic.Message { .remark(message) } } public extension Driver { /// Precompute the dependencies for a given Swift compilation, producing a /// dependency graph including all Swift and C module files and /// source files. mutating func dependencyScanningJob() throws -> Job { let (inputs, commandLine) = try dependencyScannerInvocationCommand() // Construct the scanning job. return Job(moduleName: moduleOutputInfo.name, kind: .scanDependencies, tool: try toolchain.resolvedTool(.swiftCompiler), commandLine: commandLine, displayInputs: inputs, inputs: inputs, primaryInputs: [], outputs: [TypedVirtualPath(file: .standardOutput, type: .jsonDependencies)]) } /// Generate a full command-line invocation to be used for the dependency scanning action /// on the target module. @_spi(Testing) mutating func dependencyScannerInvocationCommand() throws -> ([TypedVirtualPath],[Job.ArgTemplate]) { // Aggregate the fast dependency scanner arguments var inputs: [TypedVirtualPath] = [] var commandLine: [Job.ArgTemplate] = swiftCompilerPrefixArgs.map { Job.ArgTemplate.flag($0) } commandLine.appendFlag("-frontend") commandLine.appendFlag("-scan-dependencies") try addCommonFrontendOptions(commandLine: &commandLine, inputs: &inputs, bridgingHeaderHandling: .ignored, moduleDependencyGraphUse: .dependencyScan) // FIXME: MSVC runtime flags // Pass in external target dependencies to be treated as placeholder dependencies by the scanner if let externalTargetDetailsMap = externalTargetModuleDetailsMap { let dependencyPlaceholderMapFile = try serializeExternalDependencyArtifacts(externalTargetDependencyDetails: externalTargetDetailsMap) commandLine.appendFlag("-placeholder-dependency-module-map-file") commandLine.appendPath(dependencyPlaceholderMapFile) } // Pass on the input files commandLine.append(contentsOf: inputFiles.map { .path($0.file) }) return (inputs, commandLine) } /// Serialize a map of placeholder (external) dependencies for the dependency scanner. private func serializeExternalDependencyArtifacts(externalTargetDependencyDetails: ExternalTargetModuleDetailsMap) throws -> VirtualPath { var placeholderArtifacts: [SwiftModuleArtifactInfo] = [] // Explicit external targets for (moduleId, dependencyDetails) in externalTargetDependencyDetails { let modPath = TextualVirtualPath(path: VirtualPath.absolute(dependencyDetails.path).intern()) placeholderArtifacts.append( SwiftModuleArtifactInfo(name: moduleId.moduleName, modulePath: modPath)) } let encoder = JSONEncoder() encoder.outputFormatting = [.prettyPrinted] let contents = try encoder.encode(placeholderArtifacts) return VirtualPath.createUniqueTemporaryFileWithKnownContents(.init("\(moduleOutputInfo.name)-external-modules.json"), contents) } /// Returns false if the lib is available and ready to use private func initSwiftScanLib() throws -> Bool { // If `-nonlib-dependency-scanner` was specified or the libSwiftScan library cannot be found, // attempt to fallback to using `swift-frontend -scan-dependencies` invocations for dependency // scanning. var fallbackToFrontend = parsedOptions.hasArgument(.driverScanDependenciesNonLib) let scanLibPath = try Self.getScanLibPath(of: toolchain, hostTriple: hostTriple, env: env) if try interModuleDependencyOracle .verifyOrCreateScannerInstance(fileSystem: fileSystem, swiftScanLibPath: scanLibPath) == false { fallbackToFrontend = true // This warning is mostly useful for debugging the driver, so let's hide it // when libSwiftDriver is used, instead of a swift-driver executable. if !integratedDriver { diagnosticEngine.emit(.warn_scanner_frontend_fallback()) } } return fallbackToFrontend } private func sanitizeCommandForLibScanInvocation(_ command: inout [String]) { // Remove the tool executable to only leave the arguments. When passing the // command line into libSwiftScan, the library is itself the tool and only // needs to parse the remaining arguments. command.removeFirst() // We generate full swiftc -frontend -scan-dependencies invocations in order to also be // able to launch them as standalone jobs. Frontend's argument parser won't recognize // -frontend when passed directly. if command.first == "-frontend" { command.removeFirst() } } mutating func performImportPrescan() throws -> InterModuleDependencyImports { let preScanJob = try importPreScanningJob() let forceResponseFiles = parsedOptions.hasArgument(.driverForceResponseFiles) let imports: InterModuleDependencyImports let isSwiftScanLibAvailable = !(try initSwiftScanLib()) if isSwiftScanLibAvailable { let cwd = workingDirectory ?? fileSystem.currentWorkingDirectory! var command = try itemizedJobCommand(of: preScanJob, useResponseFiles: .disabled, using: executor.resolver) sanitizeCommandForLibScanInvocation(&command) imports = try interModuleDependencyOracle.getImports(workingDirectory: cwd, moduleAliases: moduleOutputInfo.aliases, commandLine: command) } else { // Fallback to legacy invocation of the dependency scanner with // `swift-frontend -scan-dependencies -import-prescan` imports = try self.executor.execute(job: preScanJob, capturingJSONOutputAs: InterModuleDependencyImports.self, forceResponseFiles: forceResponseFiles, recordedInputModificationDates: recordedInputModificationDates) } return imports } mutating internal func performDependencyScan() throws -> InterModuleDependencyGraph { let scannerJob = try dependencyScanningJob() let forceResponseFiles = parsedOptions.hasArgument(.driverForceResponseFiles) let dependencyGraph: InterModuleDependencyGraph if parsedOptions.contains(.v) { let arguments: [String] = try executor.resolver.resolveArgumentList(for: scannerJob, useResponseFiles: .disabled) stdoutStream <<< arguments.map { $0.spm_shellEscaped() }.joined(separator: " ") <<< "\n" stdoutStream.flush() } let isSwiftScanLibAvailable = !(try initSwiftScanLib()) if isSwiftScanLibAvailable { let cwd = workingDirectory ?? fileSystem.currentWorkingDirectory! var command = try itemizedJobCommand(of: scannerJob, useResponseFiles: .disabled, using: executor.resolver) sanitizeCommandForLibScanInvocation(&command) dependencyGraph = try interModuleDependencyOracle.getDependencies(workingDirectory: cwd, moduleAliases: moduleOutputInfo.aliases, commandLine: command) let possibleDiags = try interModuleDependencyOracle.getScannerDiagnostics() if let diags = possibleDiags { for diagnostic in diags { switch diagnostic.severity { case .error: diagnosticEngine.emit(.scanner_diagnostic_error(diagnostic.message)) case .warning: diagnosticEngine.emit(.scanner_diagnostic_warn(diagnostic.message)) case .note: diagnosticEngine.emit(.scanner_diagnostic_note(diagnostic.message)) case .remark: diagnosticEngine.emit(.scanner_diagnostic_remark(diagnostic.message)) case .ignored: diagnosticEngine.emit(.scanner_diagnostic_error(diagnostic.message)) } } } } else { // Fallback to legacy invocation of the dependency scanner with // `swift-frontend -scan-dependencies` dependencyGraph = try self.executor.execute(job: scannerJob, capturingJSONOutputAs: InterModuleDependencyGraph.self, forceResponseFiles: forceResponseFiles, recordedInputModificationDates: recordedInputModificationDates) } return dependencyGraph } mutating internal func performBatchDependencyScan(moduleInfos: [BatchScanModuleInfo]) throws -> [ModuleDependencyId: [InterModuleDependencyGraph]] { let batchScanningJob = try batchDependencyScanningJob(for: moduleInfos) let forceResponseFiles = parsedOptions.hasArgument(.driverForceResponseFiles) let moduleVersionedGraphMap: [ModuleDependencyId: [InterModuleDependencyGraph]] let isSwiftScanLibAvailable = !(try initSwiftScanLib()) if isSwiftScanLibAvailable { let cwd = workingDirectory ?? fileSystem.currentWorkingDirectory! var command = try itemizedJobCommand(of: batchScanningJob, useResponseFiles: .disabled, using: executor.resolver) sanitizeCommandForLibScanInvocation(&command) moduleVersionedGraphMap = try interModuleDependencyOracle.getBatchDependencies(workingDirectory: cwd, moduleAliases: moduleOutputInfo.aliases, commandLine: command, batchInfos: moduleInfos) } else { // Fallback to legacy invocation of the dependency scanner with // `swift-frontend -scan-dependencies` moduleVersionedGraphMap = try executeLegacyBatchScan(moduleInfos: moduleInfos, batchScanningJob: batchScanningJob, forceResponseFiles: forceResponseFiles) } return moduleVersionedGraphMap } // Perform a batch scan by invoking the command-line dependency scanner and decoding the resulting // JSON. fileprivate func executeLegacyBatchScan(moduleInfos: [BatchScanModuleInfo], batchScanningJob: Job, forceResponseFiles: Bool) throws -> [ModuleDependencyId: [InterModuleDependencyGraph]] { let batchScanResult = try self.executor.execute(job: batchScanningJob, forceResponseFiles: forceResponseFiles, recordedInputModificationDates: recordedInputModificationDates) let success = batchScanResult.exitStatus == .terminated(code: EXIT_SUCCESS) guard success else { throw JobExecutionError.jobFailedWithNonzeroExitCode( type(of: executor).computeReturnCode(exitStatus: batchScanResult.exitStatus), try batchScanResult.utf8stderrOutput()) } // Decode the resulting dependency graphs and build a dictionary from a moduleId to // a set of dependency graphs that were built for it let moduleVersionedGraphMap = try moduleInfos.reduce(into: [ModuleDependencyId: [InterModuleDependencyGraph]]()) { let moduleId: ModuleDependencyId let dependencyGraphPath: VirtualPath switch $1 { case .swift(let swiftModuleBatchScanInfo): moduleId = .swift(swiftModuleBatchScanInfo.swiftModuleName) dependencyGraphPath = try VirtualPath(path: swiftModuleBatchScanInfo.output) case .clang(let clangModuleBatchScanInfo): moduleId = .clang(clangModuleBatchScanInfo.clangModuleName) dependencyGraphPath = try VirtualPath(path: clangModuleBatchScanInfo.output) } let contents = try fileSystem.readFileContents(dependencyGraphPath) let decodedGraph = try JSONDecoder().decode(InterModuleDependencyGraph.self, from: Data(contents.contents)) if $0[moduleId] != nil { $0[moduleId]!.append(decodedGraph) } else { $0[moduleId] = [decodedGraph] } } return moduleVersionedGraphMap } /// Precompute the set of module names as imported by the current module mutating private func importPreScanningJob() throws -> Job { // Aggregate the fast dependency scanner arguments var inputs: [TypedVirtualPath] = [] var commandLine: [Job.ArgTemplate] = swiftCompilerPrefixArgs.map { Job.ArgTemplate.flag($0) } commandLine.appendFlag("-frontend") commandLine.appendFlag("-scan-dependencies") commandLine.appendFlag("-import-prescan") try addCommonFrontendOptions(commandLine: &commandLine, inputs: &inputs, bridgingHeaderHandling: .ignored, moduleDependencyGraphUse: .dependencyScan) // FIXME: MSVC runtime flags // Pass on the input files commandLine.append(contentsOf: inputFiles.map { .path($0.file) }) // Construct the scanning job. return Job(moduleName: moduleOutputInfo.name, kind: .scanDependencies, tool: try toolchain.resolvedTool(.swiftCompiler), commandLine: commandLine, displayInputs: inputs, inputs: inputs, primaryInputs: [], outputs: [TypedVirtualPath(file: .standardOutput, type: .jsonDependencies)]) } /// Precompute the dependencies for a given collection of modules using swift frontend's batch scanning mode mutating private func batchDependencyScanningJob(for moduleInfos: [BatchScanModuleInfo]) throws -> Job { var inputs: [TypedVirtualPath] = [] // Aggregate the fast dependency scanner arguments var commandLine: [Job.ArgTemplate] = swiftCompilerPrefixArgs.map { Job.ArgTemplate.flag($0) } // The dependency scanner automatically operates in batch mode if -batch-scan-input-file // is present. commandLine.appendFlag("-frontend") commandLine.appendFlag("-scan-dependencies") try addCommonFrontendOptions(commandLine: &commandLine, inputs: &inputs, bridgingHeaderHandling: .ignored, moduleDependencyGraphUse: .dependencyScan) let batchScanInputFilePath = try serializeBatchScanningModuleArtifacts(moduleInfos: moduleInfos) commandLine.appendFlag("-batch-scan-input-file") commandLine.appendPath(batchScanInputFilePath) // This action does not require any input files, but all frontend actions require // at least one input so pick any input of the current compilation. let inputFile = inputFiles.first { $0.type == .swift } commandLine.appendPath(inputFile!.file) inputs.append(inputFile!) // This job's outputs are defined as a set of dependency graph json files let outputs: [TypedVirtualPath] = try moduleInfos.map { switch $0 { case .swift(let swiftModuleBatchScanInfo): return TypedVirtualPath(file: try VirtualPath.intern(path: swiftModuleBatchScanInfo.output), type: .jsonDependencies) case .clang(let clangModuleBatchScanInfo): return TypedVirtualPath(file: try VirtualPath.intern(path: clangModuleBatchScanInfo.output), type: .jsonDependencies) } } // Construct the scanning job. return Job(moduleName: moduleOutputInfo.name, kind: .scanDependencies, tool: try toolchain.resolvedTool(.swiftCompiler), commandLine: commandLine, displayInputs: inputs, inputs: inputs, primaryInputs: [], outputs: outputs) } /// Serialize a collection of modules into an input format expected by the batch module dependency scanner. func serializeBatchScanningModuleArtifacts(moduleInfos: [BatchScanModuleInfo]) throws -> VirtualPath { let encoder = JSONEncoder() encoder.outputFormatting = [.prettyPrinted] let contents = try encoder.encode(moduleInfos) return VirtualPath.createUniqueTemporaryFileWithKnownContents(.init("\(moduleOutputInfo.name)-batch-module-scan.json"), contents) } fileprivate func itemizedJobCommand(of job: Job, useResponseFiles: ResponseFileHandling, using resolver: ArgsResolver) throws -> [String] { let (args, _) = try resolver.resolveArgumentList(for: job, useResponseFiles: useResponseFiles) return args } } @_spi(Testing) public extension Driver { static func getScanLibPath(of toolchain: Toolchain, hostTriple: Triple, env: [String: String]) throws -> AbsolutePath { if hostTriple.isWindows { // no matter if we are in a build tree or an installed tree, the layout is // always: `bin/_InternalSwiftScan.dll` return try getRootPath(of: toolchain, env: env) .appending(component: "bin") .appending(component: "_InternalSwiftScan.dll") } let sharedLibExt: String if hostTriple.isMacOSX { sharedLibExt = ".dylib" } else { sharedLibExt = ".so" } let libScanner = "lib_InternalSwiftScan\(sharedLibExt)" // We first look into position in toolchain let libPath = try getRootPath(of: toolchain, env: env).appending(component: "lib") .appending(component: "swift") .appending(component: hostTriple.osNameUnversioned) .appending(component: libScanner) if localFileSystem.exists(libPath) { return libPath } // In case we are using a compiler from the build dir, we should also try // this path. return try getRootPath(of: toolchain, env: env).appending(component: "lib") .appending(component: libScanner) } static func getRootPath(of toolchain: Toolchain, env: [String: String]) throws -> AbsolutePath { if let overrideString = env["SWIFT_DRIVER_SWIFT_SCAN_TOOLCHAIN_PATH"] { return try AbsolutePath(validating: overrideString) } return try toolchain.getToolPath(.swiftCompiler) .parentDirectory // bin .parentDirectory // toolchain root } }
apache-2.0
571549a207c8ae4667416af634852184
46.607981
123
0.65909
5.2719
false
false
false
false
CoderZZF/DYZB
DYZB/DYZB/Classes/Home/View/RecommendGameView.swift
1
1927
// // RecommendGameView.swift // DYZB // // Created by zhangzhifu on 2017/3/17. // Copyright © 2017年 seemygo. All rights reserved. // import UIKit private let kGameCellID = "kGameCellID" private let kEdgeInsetMargin : CGFloat = 10 class RecommendGameView: UIView { // MARK:- 定义数据属性 var groups : [BaseGameModel]? { didSet { // 刷新表格 collectionView.reloadData() } } // MARK:- 控件属性 @IBOutlet weak var collectionView: UICollectionView! // MARK:- 系统回调 override func awakeFromNib() { super.awakeFromNib() // 移除autoresizingMask autoresizingMask = UIViewAutoresizing() // 注册cell collectionView.register(UINib(nibName: "CollectionGameCell", bundle: nil), forCellWithReuseIdentifier: kGameCellID) // 给collectionView添加内边距 collectionView.contentInset = UIEdgeInsets(top: 0, left: kEdgeInsetMargin, bottom: 0, right: kEdgeInsetMargin) } } // MARK:- 快速创建的类方法 extension RecommendGameView { class func recommendGameView() -> RecommendGameView { return Bundle.main.loadNibNamed("RecommendGameView", owner: nil, options: nil)?.first as! RecommendGameView } } // MARK:- 遵守UICollectionView的数据源协议 extension RecommendGameView : UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return groups?.count ?? 0 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kGameCellID, for: indexPath) as! CollectionGameCell cell.baseGame = groups![(indexPath as NSIndexPath).item] return cell } }
apache-2.0
81aa225f2971320761096a7225f421a5
28.612903
126
0.673203
5.337209
false
false
false
false
nikriek/gesundheit.space
NotYet/BaseOverviewViewController.swift
1
6680
// // OverviewViewController.swift // NotYet // // Created by Niklas Riekenbrauck on 25.11.16. // Copyright © 2016 Niklas Riekenbrauck. All rights reserved. // import UIKit import SnapKit import RxSwift import RxCocoa protocol BaseOverviewViewModel { var statusText: Variable<NSAttributedString?> { get } var tipText: Variable<String?> { get } var actionTapped: PublishSubject<Void> { get } var skipTapped: PublishSubject<Void> { get } var actionTitle: Variable<String?> { get } var skipTitle: Variable<String?> { get } var done: PublishSubject<Void> { get } var infoTapped: PublishSubject<Void> { get } } class BaseOverviewViewController<ViewModel: BaseOverviewViewModel>: UIViewController { weak var coordinator: Coordinator? private lazy var statusLabel: UILabel = { let label = UILabel() label.textColor = UIColor.white label.font = UIFont.systemFont(ofSize: 42) label.numberOfLines = 0 let wrapperView = UIView() self.topStackView.insertArrangedSubview(wrapperView, at: 0) wrapperView.addSubview(label) label.snp.makeConstraints { make in make.leading.equalTo(wrapperView.snp.leading).offset(38) make.trailing.equalTo(wrapperView.snp.trailing).offset(-38) make.bottom.equalTo(wrapperView.snp.bottom) } return label }() private lazy var tipLabel: UILabel = { let label = UILabel() label.textColor = UIColor.white label.font = UIFont.systemFont(ofSize: 30) label.numberOfLines = 0 let wrapperView = UIView() self.topStackView.insertArrangedSubview(wrapperView, at: 1) wrapperView.addSubview(label) label.snp.makeConstraints { make in make.leading.equalTo(wrapperView.snp.leading).offset(38) make.trailing.equalTo(wrapperView.snp.trailing).offset(-38) make.top.equalTo(wrapperView.snp.top) } return label }() private lazy var actionButton: UIButton = { let button = UIButton() button.setTitleColor(UIColor.customLightGreen, for: .normal) button.titleLabel?.font = UIFont.systemFont(ofSize: 24) self.bottomStackView.insertArrangedSubview(button, at: 0) button.snp.makeConstraints { make in make.height.equalTo(48) } return button }() private lazy var skipButton: UIButton = { let button = UIButton() button.setTitleColor(UIColor.gray, for: .normal) button.titleLabel?.font = UIFont.systemFont(ofSize: 16) self.bottomStackView.insertArrangedSubview(button, at: 1) return button }() private lazy var containerStackView: UIStackView = { let stackView = UIStackView() self.view.addSubview(stackView) stackView.snp.makeConstraints { make in make.edges.equalTo(self.view.snp.edges) } stackView.axis = .vertical return stackView }() private lazy var topStackView: UIStackView = { let stackView = UIStackView() stackView.axis = .vertical stackView.distribution = .fillEqually stackView.spacing = 38 self.containerStackView.insertArrangedSubview(stackView, at: 0) return stackView }() private lazy var infoButton: UIButton = { let button = UIButton(type: .infoLight) let barItem = UIBarButtonItem(customView: button) button.tintColor = UIColor.white self.navigationItem.rightBarButtonItem = barItem return button }() private lazy var bottomStackView: UIStackView = { let stackView = UIStackView() stackView.axis = .vertical self.containerStackView.insertArrangedSubview(stackView, at: 1) stackView.layoutMargins = UIEdgeInsets(top: 24, left: 0, bottom: 24, right: 0) stackView.isLayoutMarginsRelativeArrangement = true return stackView }() let viewModel: ViewModel let disposeBag = DisposeBag() init(viewModel: ViewModel) { self.viewModel = viewModel super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() viewModel.statusText.asDriver() .drive(statusLabel.rx.attributedText) .addDisposableTo(disposeBag) viewModel.tipText.asDriver() .drive(tipLabel.rx.text) .addDisposableTo(disposeBag) viewModel.actionTitle.asDriver() .drive(actionButton.rx.title()) .addDisposableTo(disposeBag) viewModel.skipTitle.asDriver() .drive(skipButton.rx.title()) .addDisposableTo(disposeBag) viewModel.skipTitle.asDriver() .map { $0 == nil } .drive(skipButton.rx.isHidden) .addDisposableTo(disposeBag) actionButton.rx.tap.asObservable() .bindTo(viewModel.actionTapped) .addDisposableTo(disposeBag) skipButton.rx.tap.asObservable() .bindTo(viewModel.skipTapped) .addDisposableTo(disposeBag) viewModel.done.asObservable() .observeOn(MainScheduler.instance) .subscribe(onNext: { [weak self] in guard let `self` = self else { return } self.coordinator?.done(with: self) }) .addDisposableTo(disposeBag) infoButton.rx.tap .bindTo(viewModel.infoTapped) .addDisposableTo(disposeBag) if let vm = (viewModel as? OverviewViewModel) { vm.presentInsight .observeOn(MainScheduler.instance) .subscribe(onNext: { [weak self] _ in guard let `self` = self, let recommendationId = vm.currentRecommendation.value?.id else { return } self.coordinator?.presentInsight(on: self, recommendationId: recommendationId) }) .addDisposableTo(disposeBag) } } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() topStackView.applyGradient(topRightColor: UIColor.customLightGreen, bottomLeftColor: UIColor.customGreen) } }
mit
09d118ff9f0066bc627e98d7192c00e1
30.504717
118
0.606378
5.141647
false
false
false
false
faimin/ZDOpenSourceDemo
ZDOpenSourceSwiftDemo/Pods/LifetimeTracker/Sources/iOS/UI/LifetimeTracker+DashboardView.swift
1
8868
// // LifetimeTracker+DashboardView.swift // LifetimeTracker // // Created by Krzysztof Zablocki on 9/25/17. // import UIKit fileprivate extension String { #if swift(>=4.0) typealias AttributedStringKey = NSAttributedString.Key static let foregroundColorAttributeName = NSAttributedString.Key.foregroundColor #else typealias AttributedStringKey = String static let foregroundColorAttributeName = NSForegroundColorAttributeName #endif func attributed(_ attributes: [AttributedStringKey: Any] = [:]) -> NSAttributedString { return NSAttributedString(string: self, attributes: attributes) } } extension NSAttributedString { fileprivate static func + (left: NSAttributedString, right: NSAttributedString) -> NSAttributedString { let result = NSMutableAttributedString(attributedString: left) result.append(right) return result } } typealias EntryModel = (color: UIColor, description: String) typealias GroupModel = (color: UIColor, title: String, groupName: String, groupCount: Int, groupMaxCount: Int, entries: [EntryModel]) @objc public final class LifetimeTrackerDashboardIntegration: NSObject { public enum Style { case bar case circular internal func makeViewable() -> UIViewController & LifetimeTrackerViewable { switch self { case .bar: return BarDashboardViewController.makeFromNib() case .circular: return CircularDashboardViewController.makeFromNib() } } } public enum Visibility { case alwaysHidden case alwaysVisible case visibleWithIssuesDetected func windowIsHidden(hasIssuesToDisplay: Bool) -> Bool { switch self { case .alwaysHidden: return true case .alwaysVisible: return false case .visibleWithIssuesDetected: return !hasIssuesToDisplay } } } private lazy var lifetimeTrackerView: UIViewController & LifetimeTrackerViewable = { return self.style.makeViewable() }() private lazy var window: UIWindow = { let window = UIWindow(frame: .zero) window.windowLevel = UIWindow.Level.statusBar window.frame = UIScreen.main.bounds window.rootViewController = self.lifetimeTrackerView return window }() public var style: Style = .bar public var visibility: Visibility = .visibleWithIssuesDetected convenience public init(visibility: Visibility, style: Style = .bar) { self.init() self.visibility = visibility self.style = style } @objc public func refreshUI(trackedGroups: [String: LifetimeTracker.EntriesGroup]) { DispatchQueue.main.async { self.window.isHidden = self.visibility.windowIsHidden(hasIssuesToDisplay: self.hasIssuesToDisplay(from: trackedGroups)) let entries = self.entries(from: trackedGroups) let vm = BarDashboardViewModel(leaksCount: entries.leaksCount, summary: self.summary(from: trackedGroups), sections: entries.groups) self.lifetimeTrackerView.update(with: vm) } } private func summary(from trackedGroups: [String: LifetimeTracker.EntriesGroup]) -> NSAttributedString { let groupNames = trackedGroups.keys.sorted(by: >) let leakyGroupSummaries = groupNames.filter { groupName in return trackedGroups[groupName]?.lifetimeState == .leaky }.map { groupName in let group = trackedGroups[groupName]! let maxCountString = group.maxCount == Int.max ? "macCount.notSpecified".lt_localized : "\(group.maxCount)" return "\(group.name ?? "dashboard.sectionHeader.title.noGroup".lt_localized) (\(group.count)/\(maxCountString))" }.joined(separator: ", ") if leakyGroupSummaries.isEmpty { return "dashboard.header.issue.description.noIssues".lt_localized.attributed([ String.foregroundColorAttributeName: UIColor.green ]) } return ("\("dashboard.header.issue.description.leakDetected".lt_localized): ").attributed([ String.foregroundColorAttributeName: UIColor.red ]) + leakyGroupSummaries.attributed() } private func entries(from trackedGroups: [String: LifetimeTracker.EntriesGroup]) -> (groups: [GroupModel], leaksCount: Int) { var leaksCount = 0 var sections = [GroupModel]() let filteredGroups = trackedGroups.filter { (_, group: LifetimeTracker.EntriesGroup) -> Bool in group.count > 0 } filteredGroups .sorted { (lhs: (key: String, value: LifetimeTracker.EntriesGroup), rhs: (key: String, value: LifetimeTracker.EntriesGroup)) -> Bool in return (lhs.value.maxCount - lhs.value.count) < (rhs.value.maxCount - rhs.value.count) } .forEach { (groupName: String, group: LifetimeTracker.EntriesGroup) in var groupColor: UIColor switch group.lifetimeState { case .valid: groupColor = .green case .leaky: groupColor = .red } let groupMaxCountString = group.maxCount == Int.max ? "macCount.notSpecified".lt_localized : "\(group.maxCount)" let title = "\(group.name ?? "dashboard.sectionHeader.title.noGroup".lt_localized) (\(group.count)/\(groupMaxCountString))" var rows = [EntryModel]() group.entries.sorted { (lhs: (key: String, value: LifetimeTracker.Entry), rhs: (key: String, value: LifetimeTracker.Entry)) -> Bool in lhs.value.count > rhs.value.count } .filter { (_, entry: LifetimeTracker.Entry) -> Bool in entry.count > 0 }.forEach { (_, entry: LifetimeTracker.Entry) in var color: UIColor switch entry.lifetimeState { case .valid: color = .green case .leaky: color = .red leaksCount += entry.count - entry.maxCount } let entryMaxCountString = entry.maxCount == Int.max ? "macCount.notSpecified".lt_localized : "\(entry.maxCount)" let description = "\(entry.name) (\(entry.count)/\(entryMaxCountString)):\n\(entry.pointers.joined(separator: ", "))" rows.append((color: color, description: description)) } sections.append((color: groupColor, title: title, groupName: "\(group.name ?? "dashboard.sectionHeader.title.noGroup".lt_localized)", groupCount: group.count, groupMaxCount: group.maxCount, entries: rows)) } return (groups: sections, leaksCount: leaksCount) } func hasIssuesToDisplay(from trackedGroups: [String: LifetimeTracker.EntriesGroup]) -> Bool { let aDetectedIssue = trackedGroups.keys.first { trackedGroups[$0]?.lifetimeState == .leaky } return aDetectedIssue != nil } } // MARK: - Objective-C Configuration Helper extension LifetimeTrackerDashboardIntegration { @objc public func setVisibleWhenIssueDetected() { self.visibility = .visibleWithIssuesDetected } @objc public func setAlwaysVisible() { self.visibility = .alwaysVisible } @objc public func setAlwaysHidden() { self.visibility = .alwaysHidden } @objc public func useBarStyle() { self.style = .bar } @objc public func useCircularStyle() { self.style = .circular } } // MARK: - Deprecated Configuration Helper extension LifetimeTrackerDashboardIntegration { @available(*, deprecated, message: "Use `LifetimeTrackerDashboardIntegration(visibility: Visibility, style: Style)` in Swift or `setVisibleWhenIssueDetected` instead") @objc public static func visibleWhenIssueDetected() -> LifetimeTrackerDashboardIntegration { return LifetimeTrackerDashboardIntegration(visibility: .visibleWithIssuesDetected) } @available(*, deprecated, message: "Use `LifetimeTrackerDashboardIntegration(visibility: Visibility, style: Style)` in Swift or `setAlwaysVisible` instead") @objc public static func alwaysVisible() -> LifetimeTrackerDashboardIntegration { return LifetimeTrackerDashboardIntegration(visibility: .alwaysVisible) } @available(*, deprecated, message: "Use `LifetimeTrackerDashboardIntegration(visibility: Visibility, style: Style)` in Swift or `setAlwaysHidden` instead") @objc public static func alwaysHidden() -> LifetimeTrackerDashboardIntegration { return LifetimeTrackerDashboardIntegration(visibility: .alwaysHidden) } }
mit
a9128c8f2309e91a2aba2980e25254e2
42.048544
221
0.649752
4.943144
false
false
false
false
Jnosh/swift
test/decl/subscript/subscripting.swift
13
8157
// RUN: %target-typecheck-verify-swift struct X { } // expected-note * {{did you mean 'X'?}} // Simple examples struct X1 { var stored : Int subscript (i : Int) -> Int { get { return stored } mutating set { stored = newValue } } } struct X2 { var stored : Int subscript (i : Int) -> Int { get { return stored + i } set(v) { stored = v - i } } } struct X3 { var stored : Int subscript (_ : Int) -> Int { get { return stored } set(v) { stored = v } } } struct X4 { var stored : Int subscript (i : Int, j : Int) -> Int { get { return stored + i + j } set(v) { stored = v + i - j } } } // Semantic errors struct Y1 { var x : X subscript(i: Int) -> Int { get { return x // expected-error{{cannot convert return expression of type 'X' to return type 'Int'}} } set { x = newValue // expected-error{{cannot assign value of type 'Int' to type 'X'}} } } } struct Y2 { subscript(idx: Int) -> TypoType { // expected-error 3{{use of undeclared type 'TypoType'}} get { repeat {} while true } set {} } } class Y3 { subscript(idx: Int) -> TypoType { // expected-error 3{{use of undeclared type 'TypoType'}} get { repeat {} while true } set {} } } protocol ProtocolGetSet0 { subscript(i: Int) -> Int {} // expected-error {{subscript declarations must have a getter}} } protocol ProtocolGetSet1 { subscript(i: Int) -> Int { get } } protocol ProtocolGetSet2 { subscript(i: Int) -> Int { set } // expected-error {{subscript declarations must have a getter}} } protocol ProtocolGetSet3 { subscript(i: Int) -> Int { get set } } protocol ProtocolGetSet4 { subscript(i: Int) -> Int { set get } } protocol ProtocolWillSetDidSet1 { subscript(i: Int) -> Int { willSet } // expected-error {{expected get or set in a protocol property}} } protocol ProtocolWillSetDidSet2 { subscript(i: Int) -> Int { didSet } // expected-error {{expected get or set in a protocol property}} } protocol ProtocolWillSetDidSet3 { subscript(i: Int) -> Int { willSet didSet } // expected-error {{expected get or set in a protocol property}} } protocol ProtocolWillSetDidSet4 { subscript(i: Int) -> Int { didSet willSet } // expected-error {{expected get or set in a protocol property}} } class DidSetInSubscript { subscript(_: Int) -> Int { didSet { // expected-error {{didSet is not allowed in subscripts}} print("eek") } get {} } } class WillSetInSubscript { subscript(_: Int) -> Int { willSet { // expected-error {{willSet is not allowed in subscripts}} print("eek") } get {} } } subscript(i: Int) -> Int { // expected-error{{'subscript' functions may only be declared within a type}} get {} } func f() { // expected-note * {{did you mean 'f'?}} subscript (i: Int) -> Int { // expected-error{{'subscript' functions may only be declared within a type}} get {} } } struct NoSubscript { } struct OverloadedSubscript { subscript(i: Int) -> Int { get { return i } set {} } subscript(i: Int, j: Int) -> Int { get { return i } set {} } } struct RetOverloadedSubscript { subscript(i: Int) -> Int { // expected-note {{found this candidate}} get { return i } set {} } subscript(i: Int) -> Float { // expected-note {{found this candidate}} get { return Float(i) } set {} } } struct MissingGetterSubscript1 { subscript (i : Int) -> Int { } // expected-error {{computed property must have accessors specified}} } struct MissingGetterSubscript2 { subscript (i : Int, j : Int) -> Int { // expected-error{{subscript declarations must have a getter}} set {} } } func test_subscript(_ x2: inout X2, i: Int, j: Int, value: inout Int, no: NoSubscript, ovl: inout OverloadedSubscript, ret: inout RetOverloadedSubscript) { no[i] = value // expected-error{{type 'NoSubscript' has no subscript members}} value = x2[i] x2[i] = value value = ovl[i] ovl[i] = value value = ovl[(i, j)] ovl[(i, j)] = value value = ovl[(i, j, i)] // expected-error{{cannot convert value of type '(Int, Int, Int)' to expected argument type 'Int'}} ret[i] // expected-error{{ambiguous use of 'subscript'}} value = ret[i] ret[i] = value } func subscript_rvalue_materialize(_ i: inout Int) { i = X1(stored: 0)[i] } func subscript_coerce(_ fn: ([UnicodeScalar], [UnicodeScalar]) -> Bool) {} func test_subscript_coerce() { subscript_coerce({ $0[$0.count-1] < $1[$1.count-1] }) } struct no_index { subscript () -> Int { return 42 } func test() -> Int { return self[] } } struct tuple_index { subscript (x : Int, y : Int) -> (Int, Int) { return (x, y) } func test() -> (Int, Int) { return self[123, 456] } } struct MutableComputedGetter { var value: Int subscript(index: Int) -> Int { value = 5 // expected-error{{cannot assign to property: 'self' is immutable}} return 5 } var getValue : Int { value = 5 // expected-error {{cannot assign to property: 'self' is immutable}} return 5 } } struct MutableSubscriptInGetter { var value: Int subscript(index: Int) -> Int { get { // expected-note {{mark accessor 'mutating' to make 'self' mutable}} value = 5 // expected-error{{cannot assign to property: 'self' is immutable}} return 5 } } } struct SubscriptTest1 { subscript(keyword:String) -> Bool { return true } // expected-note 2 {{found this candidate}} subscript(keyword:String) -> String? {return nil } // expected-note 2 {{found this candidate}} } func testSubscript1(_ s1 : SubscriptTest1) { let _ : Int = s1["hello"] // expected-error {{ambiguous subscript with base type 'SubscriptTest1' and index type 'String'}} if s1["hello"] {} let _ = s1["hello"] // expected-error {{ambiguous use of 'subscript'}} } struct SubscriptTest2 { subscript(a : String, b : Int) -> Int { return 0 } subscript(a : String, b : String) -> Int { return 0 } } func testSubscript1(_ s2 : SubscriptTest2) { _ = s2["foo"] // expected-error {{cannot subscript a value of type 'SubscriptTest2' with an index of type 'String'}} // expected-note @-1 {{overloads for 'subscript' exist with these partially matching parameter lists: (String, Int), (String, String)}} let a = s2["foo", 1.0] // expected-error {{cannot subscript a value of type 'SubscriptTest2' with an index of type '(String, Double)'}} // expected-note @-1 {{overloads for 'subscript' exist with these partially matching parameter lists: (String, Int), (String, String)}} let b = s2[1, "foo"] // expected-error {{cannot convert value of type 'Int' to expected argument type 'String'}} // rdar://problem/27449208 let v: (Int?, [Int]?) = (nil [17]) // expected-error {{cannot subscript a nil literal value}} } // sr-114 & rdar://22007370 class Foo { subscript(key: String) -> String { // expected-note {{'subscript' previously declared here}} get { a } // expected-error {{use of unresolved identifier 'a'}} set { b } // expected-error {{use of unresolved identifier 'b'}} } subscript(key: String) -> String { // expected-error {{invalid redeclaration of 'subscript'}} get { a } // expected-error {{use of unresolved identifier 'a'}} set { b } // expected-error {{use of unresolved identifier 'b'}} } } // <rdar://problem/23952125> QoI: Subscript in protocol with missing {}, better diagnostic please protocol r23952125 { associatedtype ItemType var count: Int { get } subscript(index: Int) -> ItemType // expected-error {{subscript in protocol must have explicit { get } or { get set } specifier}} {{36-36= { get set \}}} var c : Int // expected-error {{property in protocol must have explicit { get } or { get set } specifier}} } // <rdar://problem/16812341> QoI: Poor error message when providing a default value for a subscript parameter struct S4 { subscript(subs: Int = 0) -> Int { // expected-error {{default arguments are not allowed in subscripts}} get { return 1 } } }
apache-2.0
6528ee43a49ece26c8b035a5cf01e140
25.144231
156
0.624249
3.596561
false
false
false
false
Jnosh/swift
test/decl/init/resilience.swift
7
2938
// RUN: rm -rf %t && mkdir %t // RUN: %target-swift-frontend -emit-module -enable-resilience -emit-module-path=%t/resilient_struct.swiftmodule -module-name=resilient_struct %S/../../Inputs/resilient_struct.swift // RUN: %target-swift-frontend -emit-module -enable-resilience -emit-module-path=%t/resilient_protocol.swiftmodule -module-name=resilient_protocol %S/../../Inputs/resilient_protocol.swift // RUN: %target-swift-frontend -typecheck -verify -enable-resilience -I %t %s import resilient_struct import resilient_protocol // Point is @_fixed_layout -- this is OK extension Point { init(xx: Int, yy: Int) { self.x = xx self.y = yy } } // Size is not @_fixed_layout, so we cannot define a new designated initializer extension Size { init(ww: Int, hh: Int) { // expected-error@-1 {{initializer declared in an extension of non-'@_fixed_layout' type 'Size' must delegate to another initializer}} self.w = ww self.h = hh } // This is OK init(www: Int, hhh: Int) { self.init(w: www, h: hhh) } // FIXME: This should be allowed, but Sema doesn't distinguish this // case from memberwise initialization, and DI explodes the value type init(other: Size) { // expected-error@-1 {{initializer declared in an extension of non-'@_fixed_layout' type 'Size' must delegate to another initializer}} self = other } } // Animal is not @_fixed_layout, so we cannot define an @_inlineable // designated initializer public struct Animal { public let name: String @_inlineable public init(name: String) { // expected-error@-1 {{initializer for non-'@_fixed_layout' type 'Animal' is '@_inlineable' and must delegate to another initializer}} self.name = name } @inline(__always) public init(dog: String) { // expected-error@-1 {{initializer for non-'@_fixed_layout' type 'Animal' is '@inline(__always)' and must delegate to another initializer}} self.name = dog } @_transparent public init(cat: String) { // expected-error@-1 {{initializer for non-'@_fixed_layout' type 'Animal' is '@_transparent' and must delegate to another initializer}} self.name = cat } // This is OK @_inlineable public init(cow: String) { self.init(name: cow) } // FIXME: This should be allowed, but Sema doesn't distinguish this // case from memberwise initialization, and DI explodes the value type @_inlineable public init(other: Animal) { // expected-error@-1 {{initializer for non-'@_fixed_layout' type 'Animal' is '@_inlineable' and must delegate to another initializer}} self = other } } public class Widget { public let name: String @_inlineable public init(name: String) { // expected-error@-1 {{initializer for class 'Widget' is '@_inlineable' and must delegate to another initializer}} self.name = name } } // Protocol extension initializers are OK too extension OtherResilientProtocol { public init(other: Self) { self = other } }
apache-2.0
b6cbf32bc450c926c79e81873a4f6f80
33.564706
187
0.69435
3.820546
false
false
false
false
ripventura/VCHTTPConnect
Example/Pods/VCSwiftToolkit/VCSwiftToolkit/Classes/LocalNotificationHelper.swift
2
7926
/* The MIT License (MIT) Copyright (c) 2015 AhmetKeskin Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import Foundation import AVKit let sharedLocalNotificationHelper : LocalNotificationHelper = LocalNotificationHelper() enum LocalNotificationAction: String { case Cancel = "LOCAL_NOTIFICATION_ACTION_CANCEL_IDENTIFIER" case Confirm = "LOCAL_NOTIFICATION_ACTION_CONFIRM_IDENTIFIER" } class LocalNotificationHelper: NSObject { let LOCAL_NOTIFICATION_CATEGORY : String = "LocalNotificationCategory" // MARK: - Shared Instance class func sharedInstance() -> LocalNotificationHelper { struct Singleton { static var sharedInstance = LocalNotificationHelper() } return Singleton.sharedInstance } // MARK: - Schedule Notification /** * Schedules a new Local Notification whitin the next given seconds */ func scheduleNotificationWithKey(key: String, title: String, message: String, seconds: Double, userInfo: [NSObject: AnyObject]?) { let date = NSDate(timeIntervalSinceNow: TimeInterval(seconds)) let notification = notificationWithTitle(key: key, title: title, message: message, date: date, userInfo: userInfo, soundName: nil, hasAction: true) notification.category = LOCAL_NOTIFICATION_CATEGORY UIApplication.shared.scheduleLocalNotification(notification) } /** * Schedules a new Local Notification with the given date */ func scheduleNotificationWithKey(key: String, title: String, message: String, date: NSDate, userInfo: [NSObject: AnyObject]?){ let notification = notificationWithTitle(key: key, title: title, message: message, date: date, userInfo: userInfo, soundName: nil, hasAction: true) notification.category = LOCAL_NOTIFICATION_CATEGORY UIApplication.shared.scheduleLocalNotification(notification) } /** * Schedules a new Local Notification whitin the next given seconds, with a custom sound */ func scheduleNotificationWithKey(key: String, title: String, message: String, seconds: Double, soundName: String, userInfo: [NSObject: AnyObject]?){ let date = NSDate(timeIntervalSinceNow: TimeInterval(seconds)) let notification = notificationWithTitle(key: key, title: title, message: message, date: date, userInfo: userInfo, soundName: soundName, hasAction: true) UIApplication.shared.scheduleLocalNotification(notification) } /** * Schedules a new Local Notification with the given date, with a custom sound */ func scheduleNotificationWithKey(key: String, title: String, message: String, date: NSDate, soundName: String, userInfo: [NSObject: AnyObject]?){ let notification = notificationWithTitle(key: key, title: title, message: message, date: date, userInfo: userInfo, soundName: soundName, hasAction: true) UIApplication.shared.scheduleLocalNotification(notification) } // MARK: - Present Notification func presentNotificationWithKey(key: String, title: String, message: String, soundName: String, userInfo: [NSObject: AnyObject]?) { let notification = notificationWithTitle(key: key, title: title, message: message, date: nil, userInfo: userInfo, soundName: nil, hasAction: true) UIApplication.shared.presentLocalNotificationNow(notification) } // MARK: - Create Notification func notificationWithTitle(key : String, title: String, message: String, date: NSDate?, userInfo: [NSObject: AnyObject]?, soundName: String?, hasAction: Bool) -> UILocalNotification { var dct : Dictionary<String,AnyObject>? = userInfo as? Dictionary<String,AnyObject> if dct != nil { dct!["key"] = NSString(string: key) as AnyObject? } else { dct = ["key" : NSString(string: key) as AnyObject] } let notification = UILocalNotification() notification.alertAction = title notification.alertBody = message notification.userInfo = dct notification.soundName = soundName ?? UILocalNotificationDefaultSoundName notification.fireDate = date as Date? notification.hasAction = hasAction return notification } func getNotificationWithKey(key : String) -> UILocalNotification { var notif : UILocalNotification? for notification in UIApplication.shared.scheduledLocalNotifications! where notification.userInfo!["key"] as! String == key{ notif = notification break } return notif! } func cancelNotification(key : String){ for notification in UIApplication.shared.scheduledLocalNotifications! where notification.userInfo!["key"] as! String == key{ UIApplication.shared.cancelLocalNotification(notification) break } } func getAllNotifications() -> [UILocalNotification]? { return UIApplication.shared.scheduledLocalNotifications } func cancelAllNotifications() { UIApplication.shared.cancelAllLocalNotifications() } /** * Creates a Notification Action Button to be used on the Notification */ func createUserNotificationActionButton(identifier : String, title : String) -> UIUserNotificationAction{ let actionButton = UIMutableUserNotificationAction() actionButton.identifier = identifier actionButton.title = title actionButton.activationMode = UIUserNotificationActivationMode.background actionButton.isAuthenticationRequired = true actionButton.isDestructive = false return actionButton } /** * Registers the the Notification with the Action Buttons within the given array */ func registerUserNotificationWithActionButtons(actions : [UIUserNotificationAction]){ let category = UIMutableUserNotificationCategory() category.identifier = LOCAL_NOTIFICATION_CATEGORY category.setActions(actions, for: UIUserNotificationActionContext.default) let settings = UIUserNotificationSettings(types: [UIUserNotificationType.sound, UIUserNotificationType.alert, UIUserNotificationType.badge], categories: [category]) UIApplication.shared.registerUserNotificationSettings(settings) } /** * Registers the the Notification without any Action Buttons */ func registerUserNotification(){ let settings = UIUserNotificationSettings(types: [UIUserNotificationType.sound, UIUserNotificationType.alert, UIUserNotificationType.badge], categories: nil) UIApplication.shared.registerUserNotificationSettings(settings) } }
mit
96bd60ba34fa56191bf8ef4551e8471c
41.385027
461
0.698965
5.633262
false
false
false
false
perusworld/BleComm
Example/BleComm/BLETableViewController.swift
1
2207
import UIKit import CoreBluetooth import BleComm class BLETableViewController: UITableViewController { var bleScan : BLEScan! var entries : [String:NSUUID] = [:] var names : [String] = [] @IBOutlet var tblEntries: UITableView! let textCellIdentifier = "TextCell" let segueIdentifier = "ConnectToDevice" override func viewDidLoad() { super.viewDidLoad() entries = [:] names = [] tblEntries.reloadData() bleScan = BLEScan ( serviceUUID: demoServiceUUID(), onScanDone: { (pheripherals:[String:NSUUID]?)->() in for(name, id) in pheripherals! { self.entries[name] = id self.names.append(name) } self.tblEntries.reloadData() } ) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return entries.count } func demoServiceUUID() -> CBUUID { return CBUUID(string:"fff0") } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { //let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath) let cell = tableView.dequeueReusableCellWithIdentifier(textCellIdentifier, forIndexPath: indexPath) as UITableViewCell let row = indexPath.row cell.textLabel?.text = names[row] return cell //return cell } // MARK: - Navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == segueIdentifier { if let destination = segue.destinationViewController as? ViewController { if let nameIndex = tableView.indexPathForSelectedRow?.row { destination.deviceId = entries[names[nameIndex]] } } } } }
mit
86d8dbee7b1a1f98f7631a1d35ec80ab
27.662338
126
0.612143
5.503741
false
false
false
false
cornerstonecollege/402
Younseo/DebuggingAndViews/DebuggingAndViews/ViewController.swift
1
1319
// // ViewController.swift // DebuggingAndViews // // Created by hoconey on 2016/10/12. // Copyright © 2016年 younseo. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() creatViews() } func creatViews(){ // let rect = CGRect(x: 0, y: 0, width: 100, height: 100) // let label = UILabel(frame: rect) // label.backgroundColor = UIColor.red // label.text = "I'm a label" // label.center = self.view.center // self.view.addSubview(label) let label = UILabel() label.text = "I'm a label" label.sizeToFit() // the size will fit the text size label.center = CGPoint(x: 50, y: 50) label.backgroundColor = UIColor.blue self.view.addSubview(label) let btnRect = CGRect(x: 100, y: 100, width: 100, height: 100) let button = UIButton(frame: btnRect) button.backgroundColor = UIColor.gray // Right way button.setTitle("I'm a button", for: UIControlState.normal) // Wrong way //button.titleLabel?.text = "BUTTON" self.view.addSubview(button) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } }
gpl-3.0
fb4e0d48ef1f64051fab1637eda3ef73
26.416667
69
0.598784
4
false
false
false
false
WangCrystal/actor-platform
actor-apps/app-ios/ActorApp/View/BigPlaceholderView.swift
4
8984
// // Copyright (c) 2015 Actor LLC. <https://actor.im> // import UIKit class BigPlaceholderView: UIView { // MARK: - // MARK: Private vars private var contentView: UIView! private var bgView: UIView! private var imageView: UIImageView! private var titleLabel: UILabel! private var subtitleLabel: UILabel! private var actionButton: UIButton! private var topOffset: CGFloat! private var subtitle2Label: UILabel! private var action2Button: UIButton! // MARK: - // MARK: Public vars // MARK: - // MARK: Constructors init(topOffset: CGFloat!) { super.init(frame: CGRectZero) self.topOffset = topOffset backgroundColor = UIColor.whiteColor() contentView = UIView() contentView.backgroundColor = UIColor.whiteColor() addSubview(contentView) imageView = UIImageView() imageView.hidden = true bgView = UIView() bgView.backgroundColor = MainAppTheme.navigation.barSolidColor contentView.addSubview(bgView) contentView.addSubview(imageView) titleLabel = UILabel() titleLabel.textColor = MainAppTheme.placeholder.textTitle titleLabel.font = UIFont(name: "HelveticaNeue", size: 22.0); titleLabel.textAlignment = NSTextAlignment.Center titleLabel.text = " " titleLabel.sizeToFit() contentView.addSubview(titleLabel) subtitleLabel = UILabel() subtitleLabel.textColor = MainAppTheme.placeholder.textHint subtitleLabel.font = UIFont.systemFontOfSize(16.0) subtitleLabel.textAlignment = NSTextAlignment.Center subtitleLabel.numberOfLines = 0 contentView.addSubview(subtitleLabel) actionButton = UIButton(type: .System) actionButton.titleLabel!.font = UIFont(name: "HelveticaNeue-Medium", size: 21.0) contentView.addSubview(actionButton) subtitle2Label = UILabel() subtitle2Label.textColor = MainAppTheme.placeholder.textHint subtitle2Label.font = UIFont.systemFontOfSize(16.0) subtitle2Label.textAlignment = NSTextAlignment.Center subtitle2Label.numberOfLines = 0 contentView.addSubview(subtitle2Label) action2Button = UIButton(type: .System) action2Button.titleLabel!.font = UIFont(name: "HelveticaNeue-Medium", size: 21.0) contentView.addSubview(action2Button) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - // MARK: Setters func setImage(image: UIImage?, title: String?, subtitle: String?) { setImage(image, title: title, subtitle: subtitle, actionTitle: nil, subtitle2: nil, actionTarget: nil, actionSelector: nil, action2title: nil, action2Selector: nil) } func setImage(image: UIImage?, title: String?, subtitle: String?, actionTitle: String?, subtitle2: String?, actionTarget: AnyObject?, actionSelector: Selector?, action2title: String?, action2Selector: Selector?) { if image != nil { imageView.image = image! imageView.hidden = false } else { imageView.hidden = true } if title != nil { titleLabel.text = title titleLabel.hidden = false } else { titleLabel.hidden = true } if subtitle != nil { let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.lineHeightMultiple = 1.11 paragraphStyle.alignment = NSTextAlignment.Center let attrString = NSMutableAttributedString(string: subtitle!) attrString.addAttribute(NSParagraphStyleAttributeName, value:paragraphStyle, range:NSMakeRange(0, attrString.length)) subtitleLabel.attributedText = attrString subtitleLabel.hidden = false } else { subtitleLabel.hidden = true } if actionTitle != nil && actionTarget != nil && actionSelector != nil { actionButton.removeTarget(nil, action: nil, forControlEvents: UIControlEvents.AllEvents) actionButton.addTarget(actionTarget!, action: actionSelector!, forControlEvents: UIControlEvents.TouchUpInside) actionButton.setTitle(actionTitle, forState: UIControlState.Normal) actionButton.hidden = false } else { actionButton.hidden = true } if (subtitle2 != nil) { let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.lineHeightMultiple = 1.11 paragraphStyle.alignment = NSTextAlignment.Center let attrString = NSMutableAttributedString(string: subtitle2!) attrString.addAttribute(NSParagraphStyleAttributeName, value:paragraphStyle, range:NSMakeRange(0, attrString.length)) subtitle2Label.attributedText = attrString subtitle2Label.hidden = false } else { subtitle2Label.hidden = true } if action2title != nil && actionTarget != nil && actionSelector != nil { action2Button.removeTarget(nil, action: nil, forControlEvents: UIControlEvents.AllEvents) action2Button.addTarget(actionTarget!, action: action2Selector!, forControlEvents: UIControlEvents.TouchUpInside) action2Button.setTitle(action2title, forState: UIControlState.Normal) action2Button.hidden = false } else { action2Button.hidden = true } setNeedsLayout() } // MARK: - // MARK: Layout override func layoutSubviews() { super.layoutSubviews() var contentHeight: CGFloat = 0 let maxContentWidth = bounds.size.width - 40 if imageView.hidden == false { imageView.frame = CGRect(x: 20 + (maxContentWidth - imageView.image!.size.width) / 2.0, y: topOffset, width: imageView.image!.size.width, height: imageView.image!.size.height) contentHeight += imageView.image!.size.height + topOffset } bgView.frame = CGRect(x: 0, y: 0, width: bounds.size.width, height: imageView.frame.height * 0.75 + topOffset) if titleLabel.hidden == false { if contentHeight > 0 { contentHeight += 10 } titleLabel.frame = CGRect(x: 20, y: contentHeight, width: maxContentWidth, height: titleLabel.bounds.size.height) contentHeight += titleLabel.bounds.size.height } if subtitleLabel.hidden == false { if contentHeight > 0 { contentHeight += 14 } let subtitleLabelSize = subtitleLabel.sizeThatFits(CGSize(width: maxContentWidth, height: CGFloat.max)) subtitleLabel.frame = CGRect(x: 20, y: contentHeight, width: maxContentWidth, height: subtitleLabelSize.height) contentHeight += subtitleLabelSize.height } if actionButton.hidden == false { if contentHeight > 0 { contentHeight += 14 } let actionButtonTitleLabelSize = actionButton.titleLabel!.sizeThatFits(CGSize(width: maxContentWidth, height: CGFloat.max)) actionButton.frame = CGRect(x: 20, y: contentHeight, width: maxContentWidth, height: actionButtonTitleLabelSize.height) contentHeight += actionButtonTitleLabelSize.height } if subtitle2Label.hidden == false { if contentHeight > 0 { contentHeight += 14 } let subtitleLabelSize = subtitle2Label.sizeThatFits(CGSize(width: maxContentWidth, height: CGFloat.max)) subtitle2Label.frame = CGRect(x: 20, y: contentHeight, width: maxContentWidth, height: subtitleLabelSize.height) contentHeight += subtitleLabelSize.height } if action2Button.hidden == false { if contentHeight > 0 { contentHeight += 14 } let actionButtonTitleLabelSize = action2Button.titleLabel!.sizeThatFits(CGSize(width: maxContentWidth, height: CGFloat.max)) action2Button.frame = CGRect(x: 20, y: contentHeight, width: maxContentWidth, height: actionButtonTitleLabelSize.height) contentHeight += actionButtonTitleLabelSize.height } // contentView.frame = CGRect(x: (bounds.size.width - maxContentWidth) / 2.0, y: (bounds.size.height - contentHeight) / 2.0, width: maxContentWidth, height: contentHeight) contentView.frame = CGRect(x: 0, y: 0, width: maxContentWidth, height: contentHeight) } }
mit
03edbf9ae8a617836b6ea7ea31d8dedd
38.403509
217
0.622106
5.468046
false
false
false
false
Eonil/HomeworkApp1
Modules/Monolith/CancellableBlockingIO/Sources/HTTP.ProgressiveDownloading2.swift
1
4603
// // HTTP.ProgressiveDownloading2.swift // EonilCancellableBlockingIO // // Created by Hoon H. on 11/8/14. // Copyright (c) 2014 Eonil. All rights reserved. // import Foundation extension HTTP { /// Progressive downloading context. /// /// 1. Call `progress()` until it returns `Done`. /// 2. Call `complete()` to query final state. /// /// Step 1 can be omitted if you don't want a progress. /// Stepping calls will be blocked using semaphores until meaningful result /// comes up. /// /// This uses `NSURLSession` internally. public final class ProgressiveDownloading2 { public enum Progress { case Continue(range:Range<Int64>, total:Range<Int64>?) case Done } public enum Complete { case Cancel case Error(message:String) case Ready(file:NSURL) } public let progress:()->Progress public let complete:()->Complete init(address:NSURL, cancellation:Trigger) { if cancellation.state { progress = { return Progress.Done } complete = { return Complete.Cancel } return } let pal1 = Palette() var fcmpl1 = false let conf1 = nil as NSURLSessionConfiguration? let dele1 = DownloadController(pal1) let sess1 = NSURLSession(configuration: conf1,delegate: dele1, delegateQueue: defaultDownloadingQueue()) let task1 = sess1.downloadTaskWithURL(address) let watc1 = cancellation.watch { task1.cancel() } progress = { ()->Progress in precondition(fcmpl1 == false, "You cannot call this function for once completed downloading.") let v1 = pal1.progressChannel.wait() return v1 } complete = { [watc1]()->Complete in /// Keep watch until finishes. let v1 = pal1.completionChannel.wait() fcmpl1 = true return v1 } task1.resume() } } } extension HTTP.ProgressiveDownloading2.Complete: Printable { public var ready:NSURL? { get { switch self { case let .Ready(s): return s default: return nil } } } public var description:String { get { switch self { case Cancel: return "Cancel" case Error(let s): return "Error(\(s.message))" case Ready(let s): return "Ready(\(s.file))" } } } } /// MARK: /// MARK: Implementation Details /// MARK: private class Palette { typealias Progress = HTTP.ProgressiveDownloading2.Progress typealias Complete = HTTP.ProgressiveDownloading2.Complete let progressChannel = Channel<Progress>() let completionChannel = Channel<Complete>() } private func defaultDownloadingQueue() -> NSOperationQueue { struct Slot { static let value = NSOperationQueue() } Slot.value.qualityOfService = NSQualityOfService.Background return Slot.value } /// All the delegate methods should be called from another thread. /// Otherwise, it's deadlock. private final class DownloadController: NSObject, NSURLSessionDelegate, NSURLSessionDownloadDelegate { typealias Progress = HTTP.ProgressiveDownloading2.Progress typealias Complete = HTTP.ProgressiveDownloading2.Complete let palette:Palette init(_ palette:Palette) { self.palette = palette } @objc private func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didFinishDownloadingToURL location: NSURL) { self.palette.progressChannel.signal(Progress.Done) self.palette.completionChannel.signal(Complete.Ready(file: location)) } private func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didResumeAtOffset fileOffset: Int64, expectedTotalBytes: Int64) { } private func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) { let r1 = Range<Int64>(start: totalBytesWritten-bytesWritten, end: totalBytesWritten) let r2 = totalBytesExpectedToWrite == NSURLSessionTransferSizeUnknown ? nil : Range<Int64>(start: 0, end: totalBytesExpectedToWrite) as Range<Int64>? self.palette.progressChannel.signal(Progress.Continue(range: r1, total: r2)) } private func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) { self.palette.progressChannel.signal(Progress.Done) self.palette.completionChannel.signal(Complete.Error(message: error == nil ? "Unknown error" : error!.description)) } private func URLSession(session: NSURLSession, didBecomeInvalidWithError error: NSError?) { self.palette.progressChannel.signal(Progress.Done) self.palette.completionChannel.signal(Complete.Error(message: error == nil ? "Unknown error" : error!.description)) } }
mit
1e2f3527277af00e21eb8423d7000968
22.973958
183
0.726483
3.641614
false
false
false
false
yogaboy/cordova-plugin-iosrtc-capturestill
src/ios/iosrtcCaptureStill.swift
1
1061
import UIKit import Foundation import AVFoundation extension PluginMediaStreamRenderer { func getStillURI() -> String { // Create the UIImage UIGraphicsBeginImageContextWithOptions(self.elementView.bounds.size, true, 0.0) self.elementView.drawViewHierarchyInRect(self.elementView.bounds, afterScreenUpdates: true) self.elementView.layer.renderInContext(UIGraphicsGetCurrentContext()!) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() let imageData : NSData = UIImageJPEGRepresentation(image!, 0.8)! let strBase64 : String = imageData.base64EncodedStringWithOptions(.Encoding64CharacterLineLength) return strBase64 } } extension iosrtcPlugin { func captureStillAsURI(id : Int) -> String { let pluginMediaStreamRenderer = self.pluginMediaStreamRenderers[id] if pluginMediaStreamRenderer == nil { NSLog("iosrtcPlugin#captureStillAsURI() | ERROR: pluginMediaStreamRenderer with id=%@ does not exist", String(id)) return "" } return self.pluginMediaStreamRenderers[id]!.getStillURI() } }
apache-2.0
a7c9e17aee0211030be9c030ce1c8130
34.366667
117
0.792648
4.348361
false
false
false
false
lockerfish/mini-hacks
ios-share-extension/Playgrounds/REST_POST_document.playground/Contents.swift
3
882
//: Playground - noun: a place where people can play import UIKit import XCPlayground // Let asynchronous code run XCPSetExecutionShouldContinueIndefinitely() let url = NSURL(string: "http://localhost:4984/db/")! let session = NSURLSession.sharedSession() let request = NSMutableURLRequest(URL: url) request.addValue("application/json", forHTTPHeaderField: "Content-Type") request.HTTPMethod = "POST" let json: Dictionary<String, AnyObject> = ["name": "oliver"] let data = NSJSONSerialization.dataWithJSONObject(json, options: NSJSONWritingOptions.allZeros, error: nil) let uploadTask = session.uploadTaskWithRequest(request, fromData: data) { (data, response, error) -> Void in let json = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableLeaves, error: nil) as! Dictionary<String, AnyObject> println(json) } uploadTask.resume()
mit
1650f905638e679a2d36919369868a4c
34.28
150
0.773243
4.38806
false
false
false
false
yuppielabel/YPDrawSignatureView
Sources/YPDrawSignatureView.swift
2
7629
// YPDrawSignatureView is open source // Version 1.2.1 // // Copyright (c) 2014 - 2019 The YPDrawSignatureView Project Contributors // Available under the MIT license // // https://github.com/GJNilsen/YPDrawSignatureView/blob/master/LICENSE License Information // https://github.com/GJNilsen/YPDrawSignatureView/blob/master/README.md Project Contributors import UIKit import CoreGraphics // MARK: Class properties and initialization /// # Class: YPDrawSignatureView /// Accepts touches and draws an image to an UIView /// ## Description /// This is an UIView based class for capturing a signature drawn by a finger in iOS. /// ## Usage /// Add the YPSignatureDelegate to the view to exploit the optional delegate methods /// - startedDrawing(_ view: YPDrawSignatureView) /// - finishedDrawing(_ view: YPDrawSignatureView) /// - Add an @IBOutlet, and set its delegate to self /// - Clear the signature field by calling clear() to it /// - Retrieve the signature from the field by either calling /// - getSignature() or /// - getCroppedSignature() @IBDesignable final public class YPDrawSignatureView: UIView { public weak var delegate: YPSignatureDelegate? // MARK: - Public properties @IBInspectable public var strokeWidth: CGFloat = 2.0 { didSet { path.lineWidth = strokeWidth } } @IBInspectable public var strokeColor: UIColor = .black { didSet { if !path.isEmpty { strokeColor.setStroke() } } } @objc @available(*, deprecated, renamed: "backgroundColor") @IBInspectable public var signatureBackgroundColor: UIColor = .white { didSet { backgroundColor = signatureBackgroundColor } } // Computed Property returns true if the view actually contains a signature public var doesContainSignature: Bool { get { if path.isEmpty { return false } else { return true } } } // MARK: - Private properties fileprivate var path = UIBezierPath() fileprivate var points = [CGPoint](repeating: CGPoint(), count: 5) fileprivate var controlPoint = 0 // MARK: - Init required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) path.lineWidth = strokeWidth path.lineJoinStyle = .round path.lineCapStyle = .round } override public init(frame: CGRect) { super.init(frame: frame) path.lineWidth = strokeWidth path.lineJoinStyle = .round path.lineCapStyle = .round } // MARK: - Draw override public func draw(_ rect: CGRect) { self.strokeColor.setStroke() self.path.stroke() } // MARK: - Touch handling functions override public func touchesBegan(_ touches: Set <UITouch>, with event: UIEvent?) { if let firstTouch = touches.first { let touchPoint = firstTouch.location(in: self) controlPoint = 0 points[0] = touchPoint } if let delegate = delegate { delegate.didStart(self) } } override public func touchesMoved(_ touches: Set <UITouch>, with event: UIEvent?) { if let firstTouch = touches.first { let touchPoint = firstTouch.location(in: self) controlPoint += 1 points[controlPoint] = touchPoint if (controlPoint == 4) { points[3] = CGPoint(x: (points[2].x + points[4].x)/2.0, y: (points[2].y + points[4].y)/2.0) path.move(to: points[0]) path.addCurve(to: points[3], controlPoint1: points[1], controlPoint2: points[2]) setNeedsDisplay() points[0] = points[3] points[1] = points[4] controlPoint = 1 } setNeedsDisplay() } } override public func touchesEnded(_ touches: Set <UITouch>, with event: UIEvent?) { if controlPoint < 4 { let touchPoint = points[0] path.move(to: CGPoint(x: touchPoint.x,y: touchPoint.y)) path.addLine(to: CGPoint(x: touchPoint.x,y: touchPoint.y)) setNeedsDisplay() } else { controlPoint = 0 } if let delegate = delegate { delegate.didFinish(self) } } public override func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool { // prevent gesture recognizers (e.g. UIPanGestureRecognizer in a FormSheet) from capturing the touches return false } // MARK: - Methods for interacting with Signature View // Clear the Signature View public func clear() { self.path.removeAllPoints() self.setNeedsDisplay() } // Save the Signature as an UIImage public func getSignature(scale:CGFloat = 1) -> UIImage? { if !doesContainSignature { return nil } UIGraphicsBeginImageContextWithOptions(self.bounds.size, false, scale) self.strokeColor.setStroke() self.path.stroke() let signature = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return signature } // Save the Signature (cropped of outside white space) as a UIImage public func getCroppedSignature(scale:CGFloat = 1) -> UIImage? { guard let fullRender = getSignature(scale:scale) else { return nil } let bounds = self.scale(path.bounds.insetBy(dx: -strokeWidth/2, dy: -strokeWidth/2), byFactor: scale) guard let imageRef = fullRender.cgImage?.cropping(to: bounds) else { return nil } return UIImage(cgImage: imageRef) } fileprivate func scale(_ rect: CGRect, byFactor factor: CGFloat) -> CGRect { var scaledRect = rect scaledRect.origin.x *= factor scaledRect.origin.y *= factor scaledRect.size.width *= factor scaledRect.size.height *= factor return scaledRect } // Saves the Signature as a Vector PDF Data blob public func getPDFSignature() -> Data { let mutableData = CFDataCreateMutable(nil, 0) guard let dataConsumer = CGDataConsumer.init(data: mutableData!) else { fatalError() } var rect = CGRect(x: 0, y: 0, width: frame.width, height: frame.height) guard let pdfContext = CGContext(consumer: dataConsumer, mediaBox: &rect, nil) else { fatalError() } pdfContext.beginPDFPage(nil) pdfContext.translateBy(x: 0, y: frame.height) pdfContext.scaleBy(x: 1, y: -1) pdfContext.addPath(path.cgPath) pdfContext.setStrokeColor(strokeColor.cgColor) pdfContext.strokePath() pdfContext.saveGState() pdfContext.endPDFPage() pdfContext.closePDF() let data = mutableData! as Data return data } } // MARK: - Protocol definition for YPDrawSignatureViewDelegate /// ## YPDrawSignatureViewDelegate Protocol /// YPDrawSignatureViewDelegate: /// - optional didStart(_ view : YPDrawSignatureView) /// - optional didFinish(_ view : YPDrawSignatureView) @objc public protocol YPSignatureDelegate: class { func didStart(_ view : YPDrawSignatureView) func didFinish(_ view : YPDrawSignatureView) } extension YPSignatureDelegate { func didStart(_ view : YPDrawSignatureView) {} func didFinish(_ view : YPDrawSignatureView) {} }
mit
7a0494d1e105c011efb8cc5d833a6c50
32.60793
110
0.619478
4.768125
false
false
false
false
Prosumma/Guise
Sources/Guise/Registrar/Registrar+Async.swift
1
4576
// // Registrar+Async.swift // Guise // // Created by Gregory Higley on 2022-09-21. // public extension Registrar { @discardableResult func register<T>( _ type: T.Type = T.self, tags: AnyHashable..., lifetime: Lifetime = .transient, factory: @escaping (any Resolver) async throws -> T ) -> Key { let factory: (any Resolver, Void) async throws -> T = { r, _ in try await factory(r) } return register(type, tags: Set(tags), lifetime: lifetime, factory: factory) } @discardableResult func register<T, A>( _ type: T.Type = T.self, tags: AnyHashable..., lifetime: Lifetime = .transient, factory: @escaping AsyncFactory<T, A> ) -> Key { register(type, tags: Set(tags), lifetime: lifetime, factory: factory) } @discardableResult func register<T, A1, A2>( _ type: T.Type = T.self, tags: AnyHashable..., lifetime: Lifetime = .transient, factory: @escaping (any Resolver, A1, A2) async throws -> T ) -> Key { let factory: AsyncFactory<T, (A1, A2)> = { r, arg in try await factory(r, arg.0, arg.1) } return register(type, tags: Set(tags), lifetime: lifetime, factory: factory) } @discardableResult func register<T, A1, A2, A3>( _ type: T.Type = T.self, tags: AnyHashable..., lifetime: Lifetime = .transient, factory: @escaping (any Resolver, A1, A2, A3) async throws -> T ) -> Key { let factory: AsyncFactory<T, (A1, A2, A3)> = { r, arg in try await factory(r, arg.0, arg.1, arg.2) } return register(type, tags: Set(tags), lifetime: lifetime, factory: factory) } @discardableResult func register<T, A1, A2, A3, A4>( _ type: T.Type = T.self, tags: AnyHashable..., lifetime: Lifetime = .transient, factory: @escaping (any Resolver, A1, A2, A3, A4) async throws -> T ) -> Key { let factory: AsyncFactory<T, (A1, A2, A3, A4)> = { r, arg in try await factory(r, arg.0, arg.1, arg.2, arg.3) } return register(type, tags: Set(tags), lifetime: lifetime, factory: factory) } @discardableResult func register<T, A1, A2, A3, A4, A5>( _ type: T.Type = T.self, tags: AnyHashable..., lifetime: Lifetime = .transient, factory: @escaping (any Resolver, A1, A2, A3, A4, A5) async throws -> T ) -> Key { let factory: AsyncFactory<T, (A1, A2, A3, A4, A5)> = { r, arg in try await factory(r, arg.0, arg.1, arg.2, arg.3, arg.4) } return register(type, tags: Set(tags), lifetime: lifetime, factory: factory) } @discardableResult func register<T, A1, A2, A3, A4, A5, A6>( _ type: T.Type = T.self, tags: AnyHashable..., lifetime: Lifetime = .transient, factory: @escaping (any Resolver, A1, A2, A3, A4, A5, A6) async throws -> T ) -> Key { let factory: AsyncFactory<T, (A1, A2, A3, A4, A5, A6)> = { r, arg in try await factory(r, arg.0, arg.1, arg.2, arg.3, arg.4, arg.5) } return register(type, tags: Set(tags), lifetime: lifetime, factory: factory) } @discardableResult func register<T, A1, A2, A3, A4, A5, A6, A7>( _ type: T.Type = T.self, tags: AnyHashable..., lifetime: Lifetime = .transient, factory: @escaping (any Resolver, A1, A2, A3, A4, A5, A6, A7) async throws -> T ) -> Key { let factory: AsyncFactory<T, (A1, A2, A3, A4, A5, A6, A7)> = { r, arg in try await factory(r, arg.0, arg.1, arg.2, arg.3, arg.4, arg.5, arg.6) } return register(type, tags: Set(tags), lifetime: lifetime, factory: factory) } @discardableResult func register<T, A1, A2, A3, A4, A5, A6, A7, A8>( _ type: T.Type = T.self, tags: AnyHashable..., lifetime: Lifetime = .transient, factory: @escaping (any Resolver, A1, A2, A3, A4, A5, A6, A7, A8) async throws -> T ) -> Key { let factory: AsyncFactory<T, (A1, A2, A3, A4, A5, A6, A7, A8)> = { r, arg in try await factory(r, arg.0, arg.1, arg.2, arg.3, arg.4, arg.5, arg.6, arg.7) } return register(type, tags: Set(tags), lifetime: lifetime, factory: factory) } @discardableResult func register<T, A1, A2, A3, A4, A5, A6, A7, A8, A9>( _ type: T.Type = T.self, tags: AnyHashable..., lifetime: Lifetime = .transient, factory: @escaping (any Resolver, A1, A2, A3, A4, A5, A6, A7, A8, A9) async throws -> T ) -> Key { let factory: AsyncFactory<T, (A1, A2, A3, A4, A5, A6, A7, A8, A9)> = { r, arg in try await factory(r, arg.0, arg.1, arg.2, arg.3, arg.4, arg.5, arg.6, arg.7, arg.8) } return register(type, tags: Set(tags), lifetime: lifetime, factory: factory) } }
mit
61b75df8176b67ddaa903de2453489f5
32.896296
91
0.603584
2.887066
false
false
false
false
PETERZer/SingularityIMClient-PeterZ
SingularityIMClient-PeterZDemo/SingularityIMClient/SingularityIMClient/UnreadModel.swift
1
2758
// // UnreadModel.swift // SingularityIMClient // // Created by apple on 1/14/16. // Copyright © 2016 张勇. All rights reserved. // import UIKit class UnreadModel: NSObject { var _chat_session_id:String? var _chat_session_type:String? var _sender_id:String? var _message_id:String? var _message:String? var _message_time:String? var _message_type:String? var chat_session_id:String?{ get{ if self._chat_session_id == nil { print("_chat_session_id没有值") return nil }else { return self._chat_session_id } } set(newChatSID){ self._chat_session_id = newChatSID } } var chat_session_type:String?{ get{ if self._chat_session_type == nil { print("_chat_session_type没有值") return nil }else { return self._chat_session_type } } set(newChatSType){ self._chat_session_type = newChatSType } } var sender_id:String?{ get{ if self._sender_id == nil { print("_sender_id没有值") return nil }else { return self._sender_id } } set(newSenderID){ self._sender_id = newSenderID } } var message_id:String?{ get{ if self._message_id == nil { print("_message_id没有值") return nil }else { return self._message_id } } set(newMsgId){ self._message_id = newMsgId } } var message:String?{ get{ if self._message == nil { print("_message没有值") return nil }else { return self._message } } set(newMsg){ self._message = newMsg } } var message_time:String?{ get{ if self._message_time == nil { print("_message_time没有值") return nil }else { return self._message_time } } set(newMsgTime){ self._message_time = newMsgTime } } var message_type:String?{ get{ if self._message_type == nil { print("_message_type没有值") return nil }else { return self._message_type } } set(newMsgType){ self._message_type = newMsgType } } }
mit
0e9d5f2a280042a1da82fbe34be3d71e
21.221311
50
0.434157
4.458882
false
false
false
false
NoryCao/zhuishushenqi
zhuishushenqi/Root/Service/ZSMyService.swift
1
2949
// // ZSMyService.swift // zhuishushenqi // // Created by yung on 2018/10/20. // Copyright © 2018年 QS. All rights reserved. // import UIKit import ZSAPI class ZSMyService { func fetchAccount(token:String ,completion:@escaping ZSBaseCallback<ZSAccount>) { let api = ZSAPI.account(token: token) // https://api.zhuishushenqi.com/user/account?token=MR7bHBNojupotkWO0IH1QZY0 zs_get(api.path, parameters: api.parameters) { (json) in if let account = ZSAccount.deserialize(from: json) { completion(account) } else { completion(nil) } } } func fetchCoin(token:String, completion:@escaping ZSBaseCallback<ZSCoin>) { // http://goldcoin.zhuishushenqi.com/account?token=MR7bHBNojupotkWO0IH1QZY0 let api = ZSAPI.golden(token: token) zs_get(api.path, parameters: api.parameters) { (json) in let coin = ZSCoin.deserialize(from: json) completion(coin) } } func fetchDetail(token:String, completion:@escaping ZSBaseCallback<ZSUserDetail>) { // https://api.zhuishushenqi.com/user/detail-info?token=MR7bHBNojupotkWO0IH1QZY0 let api = ZSAPI.userDetail(token: token) zs_get(api.path, parameters: api.parameters) { (json) in let detail = ZSUserDetail.deserialize(from: json) completion(detail) } } func fetchUserBind (token:String, completion:@escaping ZSBaseCallback<ZSUserBind>) { // https://api.zhuishushenqi.com/user/loginBind?token=MR7bHBNojupotkWO0IH1QZY0 let api = ZSAPI.userBind(token: token) zs_get(api.path, parameters: api.parameters) { (json) in let bind = ZSUserBind.deserialize(from: json) completion(bind) } } func fetchLogout(token:String, completion:@escaping ZSBaseCallback<[String:Any]>) { // https://api.zhuishushenqi.com/user/logout let api = ZSAPI.logout(token: token) zs_post(api.path, parameters: api.parameters) { (json) in // let books = [ZSUserBookshelf].deserialize(from: json?["books"] as? [Any]) as? [String:Any] completion(json) } } func fetchNicknameChange(url:String, param:[String:Any]?, completion:@escaping ZSBaseCallback<[String:Any]>) { zs_post(url, parameters: param) { (json) in completion(json) } } func fetchVoucherList(url:String, param:[String:Any]?, completion:@escaping ZSBaseCallback<[ZSVoucher]>) { zs_get(url, parameters: param) { (json) in if let vouchers = json?["vouchers"] as? [[String:Any]] { if let voucherModels = [ZSVoucher].deserialize(from: vouchers) as? [ZSVoucher] { completion(voucherModels) } } else { completion([]) } } } }
mit
70889d8d6beb2deac4d8706921129626
35.825
114
0.605567
3.835938
false
false
false
false
Swiftification/StepFlow
Sources/StepFlow/Flow.swift
1
4358
/* Copyright (c) 2016 João Mourato <[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 Foundation public final class Flow { fileprivate var steps: [Step] public typealias FinishBlock = (FlowState<Any>) -> () public typealias ErrorBlock = (Error) -> () public typealias CancelBlock = () -> () fileprivate var finishBlock: FinishBlock = { _ in } fileprivate var errorBlock: ErrorBlock? fileprivate var cancelBlock: CancelBlock? fileprivate var currentState: FlowState<Any> = .queued fileprivate let syncQueue = DispatchQueue(label: "com.flow.syncQueue", attributes: DispatchQueue.Attributes.concurrent) public var state: FlowState<Any> { var val: FlowState<Any>? syncQueue.sync { val = self.currentState } return val! } public init(steps: [Step]) { self.steps = steps } public init(steps: Step...) { self.steps = steps } public func onFinish(_ block: @escaping FinishBlock) -> Self { guard case .queued = state else { print("Cannot modify flow after starting") ; return self } finishBlock = block return self } public func onError(_ block: @escaping ErrorBlock) -> Self { guard case .queued = state else { print("Cannot modify flow after starting") ; return self } errorBlock = block return self } public func onCancel(_ block: @escaping CancelBlock) -> Self { guard case .queued = state else { print("Cannot modify flow after starting") ; return self } cancelBlock = block return self } public func start() { guard case .queued = state else { print("Cannot start flow twice") ; return } if !steps.isEmpty { currentState = .running(Void.self) let step = steps.first steps.removeFirst() step?.runStep(stepFlowImplementor: self, previousResult: nil) } else { print("No steps to run") } } public func cancel() { syncQueue.sync(flags: .barrier, execute: { self.steps.removeAll() self.currentState = .canceled }) DispatchQueue.main.async { guard let cancelBlock = self.cancelBlock else { self.finishBlock(self.state) return } cancelBlock() self.cancelBlock = nil } } deinit { print("Will De Init Flow Object") } } extension Flow: StepFlow { public func finish<T>(_ result: T) { guard case .running = state else { print("Step finished but flow will be interrupted due to state being : \(state) ") return } guard !steps.isEmpty else { syncQueue.sync(flags: .barrier, execute: { self.currentState = .finished(result) }) DispatchQueue.main.async { self.finishBlock(self.state) } return } var step: Step? syncQueue.sync(flags: .barrier, execute: { self.currentState = .running(result) step = self.steps.first self.steps.removeFirst() }) step?.runStep(stepFlowImplementor: self, previousResult: result) } public func finish(_ error: Error) { syncQueue.sync(flags: .barrier, execute: { self.steps.removeAll() self.currentState = .failed(error) }) DispatchQueue.main.async { guard let errorBlock = self.errorBlock else { self.finishBlock(self.state) return } errorBlock(error) self.errorBlock = nil } } }
mit
f646ac623027ce0c311073e852d70601
29.048276
121
0.679367
4.309594
false
false
false
false
creatubbles/ctb-api-swift
CreatubblesAPIClient/Sources/Requests/RequestSender.swift
1
8123
// // RequestSender.swift // CreatubblesAPIClient // // Copyright (c) 2017 Creatubbles Pte. Ltd. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit public class RequestSender: NSObject { fileprivate var networkManager: NetworkManager fileprivate var uploadManager: UploadManager open let settings: APIClientSettings init(settings: APIClientSettings) { self.settings = settings self.networkManager = NetworkManager(settings: settings) self.uploadManager = UploadManager(settings: settings) super.init() } // MARK: - Authentication var authenticationToken: String? { get { return networkManager.authClient.privateAccessToken } set { networkManager.authClient.privateAccessToken = newValue } } @discardableResult func login(_ username: String, password: String, completion: ErrorClosure?) -> RequestHandler { let request = AuthenticationRequest(username: username, password: password, settings: settings) return excuteAuthenticationRequest(request: request, isPublicAuthentication: false, completion: completion) } @discardableResult func authenticate(completion: ErrorClosure?) -> RequestHandler { let request = AuthenticationRequest(username: nil, password: nil, settings: settings) return excuteAuthenticationRequest(request: request, isPublicAuthentication: true, completion: completion) } public func excuteAuthenticationRequest(request: AuthenticationRequest, isPublicAuthentication: Bool, completion: ErrorClosure?) -> RequestHandler { self.networkManager.dataTask(request: request) { (response, error) in DispatchQueue.main.async { if let error = error { Logger.log(.error, "Error while login:\(String(describing: response))") if isPublicAuthentication { self.networkManager.authClient.publicAccessToken = nil } else { self.networkManager.authClient.privateAccessToken = nil } guard let response = response else { completion?(error) return } if let err_msg = response["error_description"] as? String { completion?(RequestSender.errorFromLoginError(AuthenticationError.responseError(err_msg))) } else if let err_code = response["error"] as? String { completion?(RequestSender.errorFromLoginError(AuthenticationError.fromResponseError(err_code))) } return } if let accessToken = response?["access_token"] as? String { if isPublicAuthentication { self.networkManager.authClient.publicAccessToken = accessToken } else { self.networkManager.authClient.privateAccessToken = accessToken } } completion?(nil) } } return RequestHandler(object: request as Cancelable) } fileprivate class func errorFromLoginError(_ error: Error?) -> APIClientError { if let err = error as? AuthenticationError { return ErrorTransformer.errorFromAuthenticationError(err) } if let err = error as NSError? { return ErrorTransformer.errorFromNSError(err) } return APIClientError.genericLoginError } func logout() { networkManager.authClient.logout() } func isLoggedIn() -> Bool { return networkManager.authClient.privateAccessToken != nil } // MARK: - Request sending @discardableResult public func send(_ request: Request, withResponseHandler handler: ResponseHandler) -> RequestHandler { Logger.log(.debug, "Sending request: \(type(of: request))") self.networkManager.dataTask(request: request) { (response, error) in if let error = error { guard let response = response else { handler.handleResponse(nil, error: error) return } Logger.log(.error, "Error while sending request:\(type(of: request))\nError:\nResponse:\n\(response)") handler.handleResponse(nil, error: ErrorTransformer.errorsFromResponse(response as? Dictionary<String, AnyObject>).first) } else { DispatchQueue.global().async { if let response = response as? Dictionary<String, AnyObject> { handler.handleResponse(response, error: nil) } else if let array = response as? Array<AnyObject> { // Added this case to handle non standard json-api format array response handler.handleResponse(["data": array as AnyObject], error: nil) } else { handler.handleResponse((response as? Dictionary<String, AnyObject>), error: nil) } } } } return RequestHandler(object: request as Cancelable) } // MARK: - Creation sending func send(_ creationData: NewCreationData, uploadData: CreationUpload, progressChanged: @escaping (_ completedUnitCount: Int64, _ totalUnitCount: Int64, _ fractionCompleted: Double) -> Void, completion: @escaping (_ error: Error?) -> Void) -> RequestHandler { var request = URLRequest(url: URL(string: uploadData.uploadUrl)!) request.httpMethod = "PUT" request.setValue(uploadData.contentType, forHTTPHeaderField: "Content-Type") let uploadTask: UploadTask! switch creationData.dataType { case .image: uploadTask = uploadManager.upload(request: request, fromData: UIImagePNGRepresentation(creationData.image!)!) case .data: uploadTask = uploadManager.upload(request: request, fromData: creationData.data!) case .url: uploadTask = uploadManager.upload(request: request, fromFile: creationData.url!) } uploadTask.uploadProgressHandler = { progress in Logger.log(.verbose, "Uploading progress for data with identifier:\(uploadData.identifier) \n \(progress.fractionCompleted)") progressChanged(progress.completedUnitCount, progress.totalUnitCount, progress.fractionCompleted) } uploadTask.completionHandler = { error in Logger.log(.verbose, "Uploading finished for data with identifier:\(uploadData.identifier)") completion(error) } return RequestHandler(object: uploadTask) } var backgroundCompletionHandler: (() -> Void)? { get { return uploadManager.backgroundCompletionHandler } set { uploadManager.backgroundCompletionHandler = newValue } } }
mit
8eb7af85cac4fc8476d38c4f732fd3ac
40.233503
263
0.635726
5.433445
false
false
false
false
zzltjnh/KeyframePicker
Example/Example/View/PhotoLibraryPickerViewCell.swift
1
990
// // PhotoLibraryPickerViewCell.swift // Example // // Created by zhangzhilong on 2016/11/11. // Copyright © 2016年 zhangzhilong. All rights reserved. // import UIKit import Photos class PhotoLibraryPickerViewCell: UICollectionViewCell { @IBOutlet weak var imageView: UIImageView! var videoModel: VideoModel? func updateUI() { guard let asset = videoModel?.asset else { return } //获取视频缩略图 let screenSize = UIScreen.main.bounds.size let thumbnailsSize = CGSize(width:screenSize.width / 4 * UIScreen.main.scale, height:screenSize.width / 4 * UIScreen.main.scale) let options = PHImageRequestOptions() options.deliveryMode = .fastFormat PHImageManager.default().requestImage(for: asset, targetSize: thumbnailsSize, contentMode: .aspectFill, options: options, resultHandler: { [weak self] (image, info) in self?.imageView.image = image }) } }
mit
3051039beb6c0f38ba5bd38fbeb18891
29.40625
175
0.669065
4.402715
false
false
false
false
HongxiangShe/DYZB
DY/DY/Class/Home/Controller/RecommendViewController.swift
1
4600
// // RecommendViewController.swift // DY // // Created by 佘红响 on 16/12/19. // Copyright © 2016年 佘红响. All rights reserved. // import UIKit fileprivate let kNormalCellID = "kNormalCellID" fileprivate let kPrettyCellID = "kPrettyCellID" fileprivate let kHeaderID = "kHeaderID" fileprivate let kCellMargin: CGFloat = 5 fileprivate let kCellWidth: CGFloat = (kScreenWidth - kCellMargin) / 2 fileprivate let kNormalCellHeight: CGFloat = kCellWidth * 3 / 4 fileprivate let kPrettyCellHeight: CGFloat = kCellWidth * 4 / 3 fileprivate let kHeaderHeight: CGFloat = 50 class RecommendViewController: UIViewController { // VM层 fileprivate lazy var recommendVM: RecommendViewModel = RecommendViewModel() fileprivate weak var collectionView: UICollectionView? override func viewDidLoad() { super.viewDidLoad() setupUI() loadData() } override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() collectionView?.frame = self.view.bounds } } // MARK: - 设置UI界面 extension RecommendViewController { func setupUI() { // 创建并设置布局 let layout = UICollectionViewFlowLayout() // layout.itemSize = CGSize(width: kCellWidth, height: kNormalCellHeight) layout.minimumLineSpacing = 0 layout.minimumInteritemSpacing = 0 layout.headerReferenceSize = CGSize(width: kScreenWidth, height: kHeaderHeight) // 创建collectionView let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout) collectionView.backgroundColor = UIColor.white collectionView.contentInset = UIEdgeInsetsMake(0, 0, 0, kCellMargin) collectionView.dataSource = self collectionView.delegate = self self.collectionView = collectionView view.addSubview(collectionView) collectionView.register(UINib(nibName: "CollectionViewNormalCell", bundle: nil), forCellWithReuseIdentifier: kNormalCellID) collectionView.register(UINib(nibName: "CollectionViewPrettyCell", bundle: nil), forCellWithReuseIdentifier: kPrettyCellID) collectionView.register(UINib(nibName: "HomeCollectionHeaderView", bundle: nil), forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: kHeaderID) } } // MARK: - UICollectionViewDataSource, UICollectionViewDelegateFlowLayout extension RecommendViewController: UICollectionViewDataSource, UICollectionViewDelegateFlowLayout { public func numberOfSections(in collectionView: UICollectionView) -> Int { return recommendVM.anchorGroups.count } public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { let anchorGroup = recommendVM.anchorGroups[section] return anchorGroup.anchors.count } public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let anchor = recommendVM.anchorGroups[indexPath.section].anchors[indexPath.item] if (indexPath.section == 1) { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kPrettyCellID, for: indexPath) as! CollectionViewPrettyCell cell.anchor = anchor return cell } else { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kNormalCellID, for: indexPath) as! CollectionViewNormalCell cell.anchor = anchor return cell } } public func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: kHeaderID, for: indexPath) as! HomeCollectionHeaderView headerView.group = recommendVM.anchorGroups[indexPath.section] return headerView } public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { if indexPath.section == 1 { return CGSize(width: kCellWidth, height: kPrettyCellHeight) } return CGSize(width: kCellWidth, height: kNormalCellHeight) } } // MARK: - 加载数据 extension RecommendViewController { func loadData() { recommendVM.requestData { self.collectionView?.reloadData() } } }
mit
1d245bfb50c76d848adc6e79b2990103
38.215517
186
0.71774
5.824584
false
false
false
false
HeMet/MVVMKit
MVVMKit/DataBindings/Adapters/TableViewDictionaryAdapter.swift
1
3512
// // TableViewDictionaryAdapter.swift // MVVMKit // // Created by Евгений Губин on 21.06.15. // Copyright (c) 2015 GitHub. All rights reserved. // import Foundation public class TableViewDictionaryAdapter<K: Hashable, T: AnyObject>: TableViewSinglePartAdapter<ObservableOrderedMultiDictionary<K, T>> { public override init(tableView: UITableView) { super.init(tableView: tableView) } override func numberOfSections(tableView: UITableView) -> Int { return data.count } override func numberOfRowsInSection(tableView: UITableView, section: Int) -> Int { return data[section].1.count } override func viewModelForIndexPath(indexPath: NSIndexPath) -> AnyObject { return data[indexPath.section].1[indexPath.row] } override func beginListeningForData() { super.beginListeningForData() data.onDidInsertSubItems.register(tag, listener: handleSubItemsInserted) data.onDidRemoveSubItems.register(tag, listener: handleSubItemsRemoved) data.onDidChangeSubItems.register(tag, listener: handleSubItemsChanged) } override func stopListeningForData() { super.stopListeningForData() data.onDidInsertSubItems.unregister(tag) data.onDidRemoveSubItems.unregister(tag) data.onDidChangeSubItems.unregister(tag) } override func handleItemsChanged(sender: ObservableOrderedMultiDictionary<K, T>, items: [(K, ObservableArray<T>)], range: Range<Int>) { let set = indexSetOf(range) tableView.reloadSections(set, withRowAnimation: .Left) //onCellsReloaded?(self, paths) } override func handleItemsInserted(sender: ObservableOrderedMultiDictionary<K, T>, items: [(K, ObservableArray<T>)], range: Range<Int>) { let set = indexSetOf(range) tableView.insertSections(set, withRowAnimation: .Right) //onCellsInserted?(self, paths) } override func handleItemsRemoved(sender: ObservableOrderedMultiDictionary<K, T>, items: [(K, ObservableArray<T>)], range: Range<Int>) { let set = indexSetOf(range) tableView.deleteSections(set, withRowAnimation: .Middle) //onCellsRemoved?(self, paths) } func handleSubItemsInserted(sender: ObservableOrderedMultiDictionary<K, T>, items: [(T, Int, Int)]) { let paths = pathsOf(items) tableView.insertRowsAtIndexPaths(paths, withRowAnimation: .Right) onCellsInserted?(self, paths) } func handleSubItemsRemoved(sender: ObservableOrderedMultiDictionary<K, T>, items: [(T, Int, Int)]) { let paths = pathsOf(items) tableView.deleteRowsAtIndexPaths(paths, withRowAnimation: .Middle) onCellsRemoved?(self, paths) } func handleSubItemsChanged(sender: ObservableOrderedMultiDictionary<K, T>, items: [(T, Int, Int)]) { let paths = pathsOf(items) tableView.reloadRowsAtIndexPaths(paths, withRowAnimation: .Left) onCellsReloaded?(self, paths) } func pathsOf(items: [(T, Int, Int)]) -> [NSIndexPath] { var result: [NSIndexPath] = [] for (item, sec, row) in items { result.append(NSIndexPath(forRow: row, inSection: sec)) } return result } func indexSetOf(range: Range<Int>) -> NSIndexSet { var result = NSMutableIndexSet() for idx in range { result.addIndex(idx) } return result } }
mit
798e446c15937e64863174775f804a99
35.46875
140
0.666
4.458599
false
false
false
false
Erez-Panda/LiveBankSDK
Pod/Classes/SignDocumentPanelView.swift
1
2155
// // SignDocumentPanelView.swift // Panda4doctor // // Created by Erez Haim on 9/8/15. // Copyright (c) 2015 Erez. All rights reserved. // import UIKit class SignDocumentPanelView: UIView { var onSign: ((signatureView: LinearInterpView, origin: CGPoint) -> ())? var onClose: ((sender: UIView) -> ())? @IBOutlet weak var signLabel: UILabel! @IBOutlet weak var watingLabel: UILabel! @IBOutlet weak var buttonleadingConstraint: NSLayoutConstraint! @IBOutlet weak var buttonTrailingConstraint: NSLayoutConstraint! @IBOutlet weak var signView: LinearInterpView! /* // Only override drawRect: if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func drawRect(rect: CGRect) { // Drawing code } */ override func awakeFromNib() { //self.layer.cornerRadius = 8 self.layer.borderColor = SignColors.sharedInstance.buttonColor().CGColor self.layer.borderWidth = 2 //self.clipsToBounds = true self.signView.blockTouches = true } func attachToView(view: UIView){ view.addSubview(self) self.addConstraintsToSuperview(view, top: 0, left: 0, bottom: 0, right: 0) } func clean(){ signView.cleanView() } func disable(){ watingLabel.hidden = false signLabel.hidden = true self.userInteractionEnabled = false } func isEmpty() -> Bool{ return signView.points.count == 0 } @IBAction func sign(sender: AnyObject) { watingLabel.hidden = false UIView.animateWithDuration(0.5, animations: { () -> Void in self.buttonTrailingConstraint.constant = -300 self.buttonleadingConstraint.constant = 300 self.layoutIfNeeded() }) let offset = CGPointMake(frame.origin.x + signView.frame.origin.x, frame.origin.y + signView.frame.origin.y) onSign?(signatureView:signView, origin: offset) } @IBAction func cancel(sender: AnyObject) { self.removeFromSuperview() onClose?(sender: self) } }
mit
166c8805e49ba1644721bbc6974bb518
29.352113
116
0.645476
4.389002
false
false
false
false
0xcodezero/Vatrena
Vatrena/Vatrena/controller/ProductDetailsViewController.swift
1
5941
// // ProductDetailsViewController.swift // Vatrena // // Created by Ahmed Ghalab on 8/2/17. // Copyright © 2017 Softcare, LLC. All rights reserved. // import UIKit protocol ProductDetailsDelegate { func hideDetailsViewController() } class ProductDetailsViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate { @IBOutlet weak var productNameLabel: UILabel! @IBOutlet weak var defaultpriceLabel: UILabel! @IBOutlet weak var descriptionLabel: UILabel! @IBOutlet weak var productImageView: UIImageView! @IBOutlet weak var optionsCollectionView: UICollectionView! var delegate : ProductDetailsDelegate? var item : VTItem! var store: VTStore! var initialFrame : CGRect! override func viewDidLoad() { super.viewDidLoad() prepareViews(animated: false) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) UIView.setAnimationsEnabled(true) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) UIView.animate(withDuration: 1, animations: { [unowned self] in self.view.frame = CGRect(x: 0, y: 80, width: UIScreen.main.bounds.size.width, height: UIScreen.main.bounds.size.height - 160) self.productNameLabel.alpha = 1.0 }) { [unowned self] _ in UIView.animate(withDuration: 0.3, delay: 0.0, options: [], animations: { [unowned self] in self.defaultpriceLabel.alpha = 1.0 self.descriptionLabel.alpha = 1.0 self.optionsCollectionView.alpha = 1.0 }) } } func prepareViews(animated: Bool){ productNameLabel.text = item.name defaultpriceLabel.text = "\(item.price) ريال" descriptionLabel.text = item.offering productImageView.image = UIImage(named: "product-placeholder") productImageView.loadingImageUsingCache(withURLString: item.imageURL ?? "") } func removeFromSuperView(animated : Bool){ UIView.animate(withDuration: 0.7, delay: 0, options: [.curveEaseOut], animations: { [unowned self] in self.view.frame = self.initialFrame self.optionsCollectionView.alpha = 0.0 }) { [unowned self] _ in self.view.removeFromSuperview() self.removeFromParentViewController() } } @IBAction func hideDetailsAction(_ sender: UIButton) { delegate?.hideDetailsViewController() } public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int{ return item.optionGroups?[section].options?.count ?? 0 } public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell{ let cell = collectionView.dequeueReusableCell(withReuseIdentifier:"option-cell", for: indexPath) as! OptionCollectionViewCell cell.optionButton.tag = (indexPath.section * Constants.GROUP_OFFSET) + indexPath.row let option = item.optionGroups?[indexPath.section].options?[indexPath.row] cell.setOptionItem(option!) return cell } public func numberOfSections(in collectionView: UICollectionView) -> Int { return item.optionGroups?.count ?? 0 } func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { var reusableView : OptionGroupCollectionHeaderReusableView! if kind == UICollectionElementKindSectionHeader { reusableView = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "HeaderView", for: indexPath) as! OptionGroupCollectionHeaderReusableView reusableView.optionGroupTitleLabel.text = item.optionGroups?[indexPath.section].name } return reusableView } @objc(collectionView:layout:insetForSectionAtIndex:) func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets{ let flowLayout = collectionViewLayout as! UICollectionViewFlowLayout let numberOfItems = collectionView.numberOfItems(inSection: section) let combinedItemWidth:CGFloat = (CGFloat(numberOfItems) * flowLayout.itemSize.width) + ((CGFloat(numberOfItems) - 1) * flowLayout.minimumInteritemSpacing) let padding = (collectionView.frame.size.width - combinedItemWidth) / 2 return UIEdgeInsetsMake(0, max(padding, 20), 10, max(padding, 20)) } @IBAction func selectOptionAction(_ sender: UIButton) { let section = sender.tag / Constants.GROUP_OFFSET let row = sender.tag % Constants.GROUP_OFFSET let optionGroup = item.optionGroups![section] let option = optionGroup.options![row] if optionGroup.selectionType == .single { for optionItem in optionGroup.options! { optionItem.selected = false } option.selected = true }else{ option.selected = !option.selected } UIView.setAnimationsEnabled(false) optionsCollectionView.reloadData() prepareViews(animated:true) Timer.scheduledTimer(timeInterval: 0.05, target: self, selector: #selector(reEnableAnimationLayer), userInfo: nil, repeats: false) } func reEnableAnimationLayer() { UIView.setAnimationsEnabled(true) } }
mit
8d6478d9bdc97d711ce507c0106fff25
35.641975
215
0.664757
5.36224
false
false
false
false
hooman/swift
test/decl/async/objc.swift
12
1718
// RUN: %target-swift-frontend -disable-objc-attr-requires-foundation-module -typecheck -verify %s -swift-version 5 -disable-availability-checking // RUN: %target-swift-ide-test -skip-deinit=false -print-ast-typechecked -source-filename %s -function-definitions=true -prefer-type-repr=false -print-implicit-attrs=true -explode-pattern-binding-decls=true -disable-objc-attr-requires-foundation-module -swift-version 5 | %FileCheck %s // REQUIRES: objc_interop // REQUIRES: concurrency import Foundation import ObjectiveC @objc protocol P { func doBigJob() async -> Int } // Infer @objc from protocol conformance // CHECK: class ConformsToP class ConformsToP: P { // CHECK: @objc func doBigJob() async -> Int func doBigJob() async -> Int { 5 } } // Infer @objc from superclass class Super { @objc func longRunningRequest() async throws -> [String] { [] } } // CHECK: class Sub class Sub : Super { // CHECK-NEXT: @objc override func longRunningRequest() async throws -> [String] override func longRunningRequest() async throws -> [String] { [] } } // Check selector computation. @objc protocol MakeSelectors { func selectorAsync() async -> Int func selector(value: Int) async -> Int } func testSelectors() { // expected-warning@+1{{use '#selector' instead of explicitly constructing a 'Selector'}} _ = Selector("selectorAsyncWithCompletionHandler:") // expected-warning@+1{{use '#selector' instead of explicitly constructing a 'Selector'}} _ = Selector("selectorWithValue:completionHandler:") _ = Selector("canary:") // expected-warning{{no method declared with Objective-C selector 'canary:'}} // expected-note@-1{{wrap the selector name in parentheses to suppress this warning}} }
apache-2.0
6879aaa4ec95e324c9feaf143d073731
37.177778
286
0.728172
3.986079
false
false
false
false